Deploying Large Models on Heterogeneous Compute: Boundaries, Conversion, and Acceptance Guidelines
This article outlines the essential steps for deploying large language models on heterogeneous computing hardware. It covers how to define problem boundaries and acceptance metrics, verify weight conversions and operator coverage, and accurately estimate KV cache requirements and parallelism parameters for million-token contexts.
1. Defining Problem Boundaries and Acceptance Metrics
Before deploying large models on heterogeneous compute, you must answer three questions: Is the memory sufficient for long contexts? Are the required operators available on the target chip? Is the output consistent with the reference implementation? Before starting, confirm the following four items:
- Model specs: Number of parameters, layers, attention heads, KV heads, head_dim, and maximum context length. Base these on the official configuration file rather than extracting them from papers or promotional pages.
- Target scenarios: Will the primary context length be 4K to 32K, or do you need million-token contexts? The memory budgets for these two scenarios differ by more than an order of magnitude.
- Precision targets: What precision will be used for weights, activations, and KV cache? Is quantization allowed, and has the quantization scheme been evaluated?
- Acceptance criteria: Time To First Token (TTFT), Time Per Output Token (TPOT), throughput, error rate, and numerical error. Metrics without clear definitions cannot be compared.
It is recommended to standardize metric definitions as follows:
- TTFT: Timed from when the client sends the request to when it receives the first output token, including queueing time.
- TPOT: Calculated as (end-to-end latency - TTFT) / (number of output tokens - 1).
- Throughput: Calculated as total output tokens divided by the stress test window duration. Input length distribution should also be recorded.
Acceptance values should be defined by the team based on business SLAs. This article does not provide universal values, as results vary significantly across different models, chips, and concurrency levels.
2. Weight Conversion and Operator Coverage
2.1 Weight Conversion Checks
When weight conversion goes wrong, the loading process typically does not throw an error. Instead, the problem manifests as degraded output quality. It is recommended to include the following checks in the conversion pipeline:
- Verify the shape of each tensor against the configuration file, paying special attention to QKV projections, output projections, and MoE expert weights.
- Verify naming mappings to ensure every key in the source format has a unique target key, with no omissions or duplicates.
- Generate a weight manifest recording the filename, byte count, and SHA256 of each shard. Compare these item by item when upgrading model versions.
- Check memory layouts. Mismatches between row-major and column-major layouts will produce incorrect matrix multiplication results, which tensor shape checks will not catch.
The following script generates a manifest and compares it with an old version. The manifest is saved in JSON format and exits with a non-zero code on comparison failure, making it easy to integrate into CI.
# Requirements: Python 3.10+. Usage:# python check_manifest.py old_manifest.json /path/to/new_shardsimport hashlibimport jsonimport osimport sysdef sha256_file(path: str, chunk_size: int = 1 << 20) -> str:h = hashlib.sha256()with open(path, "rb") as f:for block in iter(lambda: f.read(chunk_size), b""):h.update(block)return h.hexdigest()def build_manifest(shard_dir: str) -> dict[str, dict]:manifest = {}for name in sorted(os.listdir(shard_dir)):path = os.path.join(shard_dir, name)if os.path.isfile(path):manifest[name] = {"size": os.path.getsize(path), "sha256": sha256_file(path)}return manifestdef diff_manifest(old: dict[str, dict], new: dict[str, dict]) -> list[str]:problems = []for name in sorted(old.keys() | new.keys()):if name not in new:problems.append(f"Missing shard: {name}")elif name not in old:problems.append(f"New shard: {name}")elif old[name] != new[name]:problems.append(f"Size or hash mismatch: {name}")return problemsif __name__ == "__main__":old_path, new_dir = sys.argv[1], sys.argv[2]with open(old_path, encoding="utf-8") as f:old = json.load(f)problems = diff_manifest(old, build_manifest(new_dir))for p in problems:print(p)sys.exit(1 if problems else 0)
An example output from an upgrade is shown below. This output is for formatting illustration only, and the filename is hypothetical.
Hash mismatch: model-00003-of-00010.safetensors
2.2 Operator Coverage Checklist
An operator coverage checklist should be maintained for each chip. It is recommended to include the following fields:
| Field | Description |
|---|---|
| Op name | e.g., attention, rmsnorm, matmul, swiglu, all_reduce |
| Chip & driver | Chip model, driver version |
| Compiler & comm library | Compiler version, collective communication library version |
| Precision | Supported data types, e.g., BF16, FP16, FP8, INT8 |
| Implementation source | One of: native library, compiled, or general fallback implementation |
| Performance baseline | Latency or throughput for the same input scale, with measurement conditions attached |
| Fallback path | The implementation used when missing, and its associated performance penalty |
| Status | Pass, partial pass, fail |
The rules for the checklist are as follows. If critical operators (attention, matmul, all_reduce) are missing or fall back to an alternative implementation, deployment is blocked. When non-critical operators fall back, record and evaluate their time share. The following script outputs results based on this rule.
import sysfrom dataclasses import dataclass, fieldCRITICAL_OPS = {"attention", "matmul", "all_reduce"}VALID_SOURCES = {"native", "compiled", "fallback"}@dataclassclass OpRecord:name: strbackend: strdtype: strsource: strreason: str = ""@dataclassclass CoverageReport:missing: list[str] = field(default_factory=list)fallback: list[str] = field(default_factory=list)ok: list[str] = field(default_factory=list)def blocking(self) -> list[str]:"""Missing or fallback critical ops will block deployment."""return [op for op in self.missing + self.fallback if op in CRITICAL_OPS]def check_coverage(records: list[OpRecord], required: set[str]) -> CoverageReport:for r in records:if r.source not in VALID_SOURCES:raise ValueError(f"Invalid implementation source for op {r.name}: {r.source}")by_name: dict[str, list[OpRecord]] = {}for r in records:by_name.setdefault(r.name, []).append(r)report = CoverageReport()for op in sorted(required):recs = by_name.get(op)if not recs:report.missing.append(op)elif any(r.source == "fallback" for r in recs):report.fallback.append(op)else:report.ok.append(op)return reportif __name__ == "__main__":records = [OpRecord("attention", "backend-A 1.2", "bf16", "native"),OpRecord("matmul", "backend-A 1.2", "bf16", "compiled"),OpRecord("all_reduce", "backend-A 1.2", "bf16", "fallback", "Communication library does not cover this topology"),]report = check_coverage(records, {"attention", "matmul", "all_reduce", "swiglu"})print(report)blocking = report.blocking()if blocking:print(f"Blocks deployment: {blocking}")sys.exit(1)
Running the example above yields the following result: all_reduce blocks deployment due to falling back, while swiglu is missing but is not a critical operator, so it only appears in the report.
2.3 Logging Operator Fallbacks
Fallbacks must be discoverable. Every runtime fallback should output a structured log. Recommended fields include: op name, input shape, precision, fallback reason, duration, batch, sequence length, and trace_id. The trace_id is useful for associating the log with a specific request.
{"event": "op_fallback", "op": "attention", "input_shape": [4, 64, 1, 128], "dtype": "bf16", "reason": "paged kernel not built for head_dim 128", "duration_ms": 0.8, "batch": 4, "seq_len": 32768, "trace_id": "a13f9c"}
Before deployment, aggregate fallback occurrences by operator name and stage (prefill or decode). If a fallback occurs at every decoding step, it incurs an additional fallback overhead for every generated token. Such issues should be prioritized for resolution.
3. KV Cache Estimation and Parallel Scheduling for Million-Token Contexts
3.1 KV Cache Estimation
The KV cache size for a single request can be estimated using the following formula:
KV cache bytes = 2 × layers × KV heads × head_dim × sequence length × bytes per element × concurrent requests
The coefficient 2 accounts for storing K and V separately. The bytes per element depends on the KV cache precision: 2 for BF16, and 1 for FP8 and INT8. When calculating in decimal GB (10^9 bytes), note that memory capacity labeled by vendors is typically in GiB (2^30 bytes); these should be distinguished clearly.
Let’s calculate using a hypothetical configuration: 80 layers, 8 KV heads, head_dim of 128. This calculation only accounts for the KV cache and excludes weights and activations.
def kv_cache_bytes(layers, kv_heads, head_dim, seq_len, bytes_per_elem, batch=1):values = (layers, kv_heads, head_dim, seq_len, bytes_per_elem, batch)if any(v <= 0 for v in values):raise ValueError("All parameters must be positive integers")return 2 * layers * kv_heads * head_dim * seq_len * bytes_per_elem * batchif __name__ == "__main__":for seq in (4_096, 32_768, 131_072, 1_000_000):bf16 = kv_cache_bytes(80, 8, 128, seq, 2)fp8 = kv_cache_bytes(80, 8, 128, seq, 1)print(f"seq={seq:>9,} BF16={bf16 / 1e9:8.2f} GB FP8={fp8 / 1e9:8.2f} GB")
The output is shown below, in decimal GB with a batch size of 1.
| Sequence Length | BF16 | FP8 |
|---|---|---|
| 4,096 | 1.34 GB | 0.67 GB |
| 32,768 | 10.74 GB | 5.37 GB |
| 131,072 | 42.95 GB | 21.47 GB |
| 1,000,000 | 327.68 GB | 163.84 GB |
A single request with a million tokens exceeds typical single-GPU memory. Switching the KV cache to FP8 only halves the theoretical size, still requiring multi-GPU splitting or methods like compression attention and paged management. Therefore, million-token scenarios must simultaneously consider KV compression, paged management, and multi-GPU splitting; simply adding more memory will not solve the problem.
3.2 Per-GPU Allocation and KV Head Constraints
Tensor Parallelism (TP) typically splits the KV cache by attention heads. In the hypothetical configuration above, with TP set to 8, each GPU gets 1 KV head. For a 1,000,000-token single request, the KV cache per GPU is 40.96 GB (BF16) or 20.48 GB (FP8).
When TP exceeds the number of KV heads, the KV shard per GPU does not continue to shrink; instead, the KV heads are replicated across multiple GPUs. At this point, total memory usage increases as TP increases. When selecting TP, first verify if the model supports this KV replication method, then calculate the total memory.
The per-GPU memory budget can be roughly estimated using the following relationship:
Per-GPU memory ≥ Weight shard + KV shard × target concurrency + Activations & comm buffer + Reserved space
The reserved space is for fragmentation and temporary tensors. It is recommended to keep at least several GB for this item, validated by actual measurements.
3.3 Parallelism and Scheduling Parameters
The table below lists common parameters, constraints, and starting values. Starting values are only for beginning stress testing; final values must be determined through profiling.
| Parameter | Description | Constraints | Starting Value |
|---|---|---|---|
| tp_size | Tensor parallelism | Must evenly divide attention heads; KV replication occurs if KV heads < TP | Number of GPUs per machine, prioritizing high-speed interconnects |
| pp_size | Pipeline parallelism | Layers should be evenly distributed across stages | Determined by memory needs; deeper pipelines usually mean higher TTFT |
| cp_size | Context parallelism | Depends on the corresponding attention operator; verify in coverage checklist | Enable only for long-context scenarios |
| ep_size | Expert parallelism | Experts must be evenly divisible by ep_size; load imbalance slows overall performance | Choose based on expert count and GPU count |
| dp_replicas | Data parallel replicas | Increases throughput, does not reduce per-request memory | Increase based on throughput targets |
| block_size | KV paging block size (tokens) | Larger blocks mean less metadata, but more internal fragmentation for short requests | 16 or 32, requires stress testing |
| max_model_len | Maximum context | Set based on business limits, do not directly set to model maximum | Based on business scenarios |
| prefill_chunk | Prefill chunk size | Too large blocks decoding; too small reduces throughput | Requires stress testing |
| max_num_seqs | Max concurrent sequences | Linked to KV budget; exceeds leads to queuing or rejection | Inferred from memory budget |
| memory_utilization | Memory utilization ratio | Too high risks OOM; too low wastes memory | Requires stress testing |
Communication domains must also be clearly defined. TP communication should be limited to a single machine or high-speed interconnect domain.
