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:

    1. Verify the shape of each tensor against the configuration file, paying special attention to QKV projections, output projections, and MoE expert weights.
    2. Verify naming mappings to ensure every key in the source format has a unique target key, with no omissions or duplicates.
    3. Generate a weight manifest recording the filename, byte count, and SHA256 of each shard. Compare these item by item when upgrading model versions.
    4. 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.

    1. # Requirements: Python 3.10+. Usage:
    2. # python check_manifest.py old_manifest.json /path/to/new_shards
    3. import hashlib
    4. import json
    5. import os
    6. import sys
    7. def sha256_file(path: str, chunk_size: int = 1 << 20) -> str:
    8. h = hashlib.sha256()
    9. with open(path, "rb") as f:
    10. for block in iter(lambda: f.read(chunk_size), b""):
    11. h.update(block)
    12. return h.hexdigest()
    13. def build_manifest(shard_dir: str) -> dict[str, dict]:
    14. manifest = {}
    15. for name in sorted(os.listdir(shard_dir)):
    16. path = os.path.join(shard_dir, name)
    17. if os.path.isfile(path):
    18. manifest[name] = {"size": os.path.getsize(path), "sha256": sha256_file(path)}
    19. return manifest
    20. def diff_manifest(old: dict[str, dict], new: dict[str, dict]) -> list[str]:
    21. problems = []
    22. for name in sorted(old.keys() | new.keys()):
    23. if name not in new:
    24. problems.append(f"Missing shard: {name}")
    25. elif name not in old:
    26. problems.append(f"New shard: {name}")
    27. elif old[name] != new[name]:
    28. problems.append(f"Size or hash mismatch: {name}")
    29. return problems
    30. if __name__ == "__main__":
    31. old_path, new_dir = sys.argv[1], sys.argv[2]
    32. with open(old_path, encoding="utf-8") as f:
    33. old = json.load(f)
    34. problems = diff_manifest(old, build_manifest(new_dir))
    35. for p in problems:
    36. print(p)
    37. 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.

    1. 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.

    1. import sys
    2. from dataclasses import dataclass, field
    3. CRITICAL_OPS = {"attention", "matmul", "all_reduce"}
    4. VALID_SOURCES = {"native", "compiled", "fallback"}
    5. @dataclass
    6. class OpRecord:
    7. name: str
    8. backend: str
    9. dtype: str
    10. source: str
    11. reason: str = ""
    12. @dataclass
    13. class CoverageReport:
    14. missing: list[str] = field(default_factory=list)
    15. fallback: list[str] = field(default_factory=list)
    16. ok: list[str] = field(default_factory=list)
    17. def blocking(self) -> list[str]:
    18. """Missing or fallback critical ops will block deployment."""
    19. return [op for op in self.missing + self.fallback if op in CRITICAL_OPS]
    20. def check_coverage(records: list[OpRecord], required: set[str]) -> CoverageReport:
    21. for r in records:
    22. if r.source not in VALID_SOURCES:
    23. raise ValueError(f"Invalid implementation source for op {r.name}: {r.source}")
    24. by_name: dict[str, list[OpRecord]] = {}
    25. for r in records:
    26. by_name.setdefault(r.name, []).append(r)
    27. report = CoverageReport()
    28. for op in sorted(required):
    29. recs = by_name.get(op)
    30. if not recs:
    31. report.missing.append(op)
    32. elif any(r.source == "fallback" for r in recs):
    33. report.fallback.append(op)
    34. else:
    35. report.ok.append(op)
    36. return report
    37. if __name__ == "__main__":
    38. records = [
    39. OpRecord("attention", "backend-A 1.2", "bf16", "native"),
    40. OpRecord("matmul", "backend-A 1.2", "bf16", "compiled"),
    41. OpRecord("all_reduce", "backend-A 1.2", "bf16", "fallback", "Communication library does not cover this topology"),
    42. ]
    43. report = check_coverage(records, {"attention", "matmul", "all_reduce", "swiglu"})
    44. print(report)
    45. blocking = report.blocking()
    46. if blocking:
    47. print(f"Blocks deployment: {blocking}")
    48. 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.

    1. {"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.

    1. def kv_cache_bytes(layers, kv_heads, head_dim, seq_len, bytes_per_elem, batch=1):
    2. values = (layers, kv_heads, head_dim, seq_len, bytes_per_elem, batch)
    3. if any(v <= 0 for v in values):
    4. raise ValueError("All parameters must be positive integers")
    5. return 2 * layers * kv_heads * head_dim * seq_len * bytes_per_elem * batch
    6. if __name__ == "__main__":
    7. for seq in (4_096, 32_768, 131_072, 1_000_000):
    8. bf16 = kv_cache_bytes(80, 8, 128, seq, 2)
    9. fp8 = kv_cache_bytes(80, 8, 128, seq, 1)
    10. 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.