ELLMEngineering Large
Language Models
Download PDF

Chapter 37

Model Portability and Compiled State

On this page

Operator correctness is only one boundary. Model state, compiled variants, and serving behavior determine whether a platform can run the actual workload.

Port the running model before comparing devices

Keep the service's checkpoint, tokenizer, GQA geometry, and quality evaluation fixed. With 32 layers, eight KV heads, head dimension 128, and two-byte cached elements, one token's K and V require 2 * 32 * 8 * 128 * 2 = 131,072 bytes across the model. Eight sequences at context 4096 therefore occupy 4 GiB of logical KV state. This is independent of vendor; physical allocation can be larger because of padding, replication, alignment, and reserved pools.

The earlier model's roughly 14 GB of weights and 4.3 GB of logical KV reads give a useful first decode ledger under the stated full-read assumptions. Replace the illustrative GPU bandwidth with the target's measured sustainable bandwidth; do not reuse the earlier 3 TB/s number as a TPU, AMD, or Trainium specification. Likewise, aggregate memory across devices is not freely pooled memory. Weight shards and KV shards must fit where the executable places them.

Before applying the 4 GiB ledger, ask which precision changed: the weight artifact's packing and scales, the compute dtype, or KV storage and its scale layout. In the checked vLLM Neuron feature guide, FP8 KV is dequantized to BF16 for attention; weight loading is a separate path with its own checkpoint and target restrictions.

Changing weights alone leaves this model's two-byte KV payload at 4 GiB. A supported one-byte KV format stores 2 GiB of elements before scales, padding, replication, and reservations. Measure the full allocation and latency. Treat a requantized checkpoint as a new artifact, preserve the original baseline, and rerun the quality gate.

More ranks can replicate state

Assume uniform full-history GQA, no pipeline partition, and tensor parallelism that partitions whole KV heads when possible. With eight KV heads and TP=4, each rank owns two heads: the 4 GiB logical cache becomes 1 GiB per rank. At TP=16, suppose the implementation instead replicates each KV head across two ranks. Each rank holds 512 MiB, but aggregate physical KV becomes 8 GiB. Lower per-rank memory and greater aggregate memory are compatible outcomes.

Now combine TP=4 with an abstract independent context axis, CP=2: the groups partition heads and token positions independently. Each of eight ranks stores two heads for half the history, giving 512 MiB per rank and 4 GiB aggregate. This capacity model is neither an engine flag nor a schedule. Part V distinguishes phase-specific prefill PCP from decode DCP. Uneven context partitions add padding; pipeline partitions, sliding windows, latent caches, and other replication policies require different arithmetic.

The same 4 GiB logical cache has different physical layouts. Counts describe ranks, not interchangeable devices. The example isolates KV state; weights, activations, workspace, and reserved pools are additional allocations.
Open full diagram ↗

The same 4 GiB logical cache has different physical layouts. Counts describe ranks, not interchangeable devices. The example isolates KV state; weights, activations, workspace, and reserved pools are additional allocations.

Example status: Runnable Python; self-contained KV arithmetic for the three stated layouts.

layers, batch, context = 32, 8, 4096
kv_heads, head_dim, element_bytes = 8, 128, 2
logical_kv = (2 * layers * batch * context
              * kv_heads * head_dim * element_bytes)
results = []
for tp, cp in [(4, 1), (16, 1), (4, 2)]:
    # Whole heads partition; beyond 8 TP ranks, each head is replicated.
    heads_per_rank = max(1, kv_heads // tp)
    tokens_per_rank = (context + cp - 1) // cp
    local_kv = (2 * layers * batch * tokens_per_rank
                * heads_per_rank * head_dim * element_bytes)
    modeled_total = local_kv * tp * cp
    results.append((local_kv // 2**20, modeled_total // 2**20))
assert logical_kv == 4 * 2**30
one_byte_kv = logical_kv // element_bytes
assert one_byte_kv == 2 * 2**30  # excludes scale metadata
assert results == [(1024, 4096), (512, 8192), (512, 4096)]

Each result is (MiB per rank, aggregate modeled KV MiB). The general helper in examples/accelerator_portability.py validates integer and head-divisibility assumptions; the printed calculation intentionally evaluates only the three named configurations.

The preceding CP example adds ranks; with prefill context parallelism disabled, vLLM DCP reuses them within TP. In the Neuron SDK 2.32 decode mapping, TP=16 and DCP=2 form pairs of ranks that would otherwise replicate a KV head. Each rank owns interleaved blocks covering half that head's history. For the service's 32 query heads and eight KV heads, the modeled payload becomes 512 / 2 = 256 MiB per rank and 16 * 256 MiB = 4 GiB aggregate. There are 16 ranks, not 32.

This mapping requires TP greater than the KV-head count, DCP no greater than TP/KV-heads, and DCP to divide both TP and the query-to-KV-head ratio; attention data parallelism is excluded. Our geometry passes these checks. Prefill groups and whole-model support need their own validation. Record group membership and keep the independent-CP helper separate from this nested-DCP calculation.

For admission, use the most constrained rank's peak live allocation, not the average across the cluster. A useful per-rank ledger is weights + live KV + peak workspace/activations + runtime reservations + safety margin. If one rank cannot fit its largest supported prefill chunk while retaining admitted decode state, spare bytes elsewhere do not rescue that executable. Reducing TP can remove collectives but increase per-rank weight traffic; adding CP reduces local history while introducing partial-attention communication. Measure both phases after each placement change.

Treat compiled variants as deployment artifacts

Compilation adds another budget. Suppose a serving implementation buckets prompt lengths 2048 and 4096, and pads a 2300-token prompt to 4096. A fully padded linear operation processes about 4096 / 2300 = 1.78 times as many positions. A dense quadratic operation would process about 1.78^2 = 3.17 times as many position pairs. These are padding ratios, not measured latency multipliers: masked tile skipping, ragged kernels, chunked prefill, and other operators change the result. Smaller buckets reduce waste but add executable variants, compilation work, and warm-up cost.

Capture cold compilation separately from warm execution. Then test a rolling deployment where new workers must become ready while old workers still serve traffic. A fast warm benchmark is insufficient if compiling or loading the required variants prevents timely recovery.

A warm request uses a compatible compiled variant; a miss needs an explicit policy. Prewarming and persistent artifacts reduce repeated work but do not make an unsupported shape legal. The cache key is a compatibility identity, not merely a prompt length.
Open full diagram ↗

A warm request uses a compatible compiled variant; a miss needs an explicit policy. Prewarming and persistent artifacts reduce repeated work but do not make an unsupported shape legal. The cache key is a compatibility identity, not merely a prompt length.

Concrete tensor shapes, dtypes, static configuration, and target/compiler choices can affect specialization. The exact key belongs to the integration. For JAX, JIT compilation and the persistent compilation cache explain the distinction. Shape-polymorphic export can reuse tracing/lowering work without promising a single device executable for every concrete shape. For NKI, the SDK's specialization rules similarly distinguish tensor metadata from runtime values. A bounded valid length inside allocated storage is not an unbounded dynamic allocation.

Use a small cost calculation to decide which variants deserve prewarming. Suppose one variant costs 60 seconds to compile, a baseline call takes 125 milliseconds, and the candidate takes 62.5 milliseconds. At a fixed serial workload, it repays compilation after 60 / (0.125 - 0.0625) = 960 calls. These deliberately simple numbers are illustrative, not a vendor measurement. A rare shape used twenty times per worker may never repay its own compile cost. Sharing a trusted compatible artifact changes that calculation; so do overlap, throughput-oriented batching, and worker lifetime.

The CPU helper tests the padding and repayment arithmetic. To plan deployment, also count which configurations need separate artifacts. Assume a hypothetical integration specializes on two storage-length buckets, two dtypes, and two supported static layouts: that creates eight possible combinations. Its runtime valid-length value only changes a mask within the selected storage bucket. The actual integration defines the key; these choices are an example.

Call Storage length / valid length Dtype / static layout Artifact decision in this example
A 4096 / 2300 BF16 / layout 1 Select the matching variant
B 4096 / 3000 BF16 / layout 1 Reuse A's variant; change the runtime mask
C 4096 / 2300 FP16 / layout 1 Different dtype variant
D 4096 / 2300 BF16 / layout 2 Different static-layout variant

Same prompt length therefore need not mean the same executable. A prewarm manifest records the required variants with model revision, target/compiler compatibility, and trusted artifact identity. Economics and readiness can also disagree: a rare required variant may deserve prewarming to meet cold-start SLOs even when that worker never repays its compilation cost through faster calls.

The serving decision is not “always add more buckets.” Choose a bounded set from the workload, warm the important variants before declaring readiness, and specify the miss policy: queue within a deadline, use a supported fallback, or reject. Do not assume an eager fallback exists on every integration. Count misses and compile time separately from prompt execution. A shared executable cache is also a trust boundary: accept artifacts only from trusted writers, with version/target compatibility and integrity checks.

Specify the cache ABI as a tensor contract

Represent a cache allocation by (dtype, shape, byte_strides, alignment, page_table_format, position_convention, quantization_metadata). Equality of logical shapes is insufficient for sharing it across compiled implementations. A different head grouping or quantization scale axis can produce plausible values at wrong logical positions without causing an out-of-bounds access.

Construct a diagnostic cache in which every (layer,head,token,channel) has a distinct, exactly representable identifier at the test scale. Verify append, gather, page permutation, and export/import against that identifier map before comparing full-model logits. For a quantized cache, separately check dequantized values and scale ownership; bitwise identity is not an appropriate cross-format requirement.

A compiled variant key must include every property that specializes the generated address calculation or numerical path. Dynamic sequence length may be an argument, a bounded bucket, or a compilation constant; document which. Reusing an executable compiled for a different stride or head grouping is an ABI violation even when its input allocation is large enough.

Training, prefill, and decode need different acceptance evidence

Phase What must work What to measure on the target
Training Backward kernels, optimizer state, precision, checkpoint restore Time to agreed quality; step tails; communication and recovery
Prefill Prompt masks, ragged lengths, KV writes, chunk scheduling TTFT by length; useful tokens/s; padding and compile misses
Decode Paged state, sampling, cancellation, cache reuse Token-gap tails; admitted concurrency; KV traffic and collectives

Compare serving candidates on the service's request distribution and p99 targets. Check logits against a trusted reference with justified tolerances, then run task-level quality evaluation. Different reduction orders can change generated tokens without implying a bug; convincing-looking output can also hide one.

Replay eight active decodes while a long prompt arrives. Does the installed scheduler put prompt chunks and decode work in one batch, or alternate phase-specific batches? Which interval creates the worst visible token gap? The checked vLLM Neuron feature guide describes segmented prefill and continuous batching with separate prefill and decode batches. Separate batches still permit request interleaving; they change how to interpret the trace.

For that replay, record the prefill and decode rank groups, KV ownership, and reductions, including which collectives cross hosts. Identical payload arithmetic can travel over very different communication paths. Judge the configuration by TTFT and token-gap tails under the existing load and quality gate. Part V's Distributed Inference and Stateful Placement, after its collective foundations, derives those decompositions; here the scheduler trace connects those choices to a user's wait.

For disaggregated serving, apply the backend, connector, and representation gates above even when both pools use the same vendor. Then budget repacking and transport. A shared checkpoint is a useful starting point, not a shared cache ABI.

Name the handoff unit before calculating its cost: one request, a microbatch, or a pool migration. The earlier 4 GiB represents the whole batch of eight sequences with 4096 committed tokens each. One 2000-token request instead has 250 MiB of logical KV under the same full-history, uncompressed geometry. Transfer bytes also depend on physical representation and which shards move.

Suppose that whole-batch 4 GiB handoff uses an illustrative effective link rate of 50 GiB/s. Its payload-only time is 80 milliseconds. If packing and unpacking each take 15 milliseconds and the operations are serialized, the handoff already costs 110 milliseconds before queueing, protocol overhead, and attention work. A separate 100-millisecond transfer budget fails even though the link-only estimate passed. Overlap requires a measured schedule and correct buffer lifetimes. This is planning arithmetic, not measured cross-vendor interoperability; the transfer budget is distinct from the service's visible token-gap SLO.

Decide with a bounded experiment

Begin with one supported model and a replay containing short and long prompts, warm and cold prefixes, cancellation, and overload. Establish correctness, then profile the largest end-to-end gap. Only then decide whether it warrants a custom HIP, Triton, Pallas, or NKI kernel. Keep a known-good backend and versioned artifacts for rollback; do not attempt to recover an in-flight request by copying opaque device memory between ecosystems.

Compare cost per successful request that meets the SLO, including idle capacity, host resources, networking, compilation, and recovery. Add the engineering cost of maintaining another backend over an explicit planning horizon. For training, use time and cost to an agreed quality threshold, not merely examples per second. These denominators make a capacity-driven or cost-driven choice explainable without claiming that one vendor is universally faster.

For this workload, retain the existing p99 first-token target of 1.5 seconds and p99 visible token-gap target of 100 milliseconds. Report them by prompt/output-length cohort at the same arrival process, including rejected and failed requests in the accounting. Do not claim a win by quietly admitting less traffic or shortening outputs. Report the final quality gate, sustained offered load, accepted concurrency, cold-worker readiness, peak per-rank memory, and SLO-qualified cost together. The best kernel result is a diagnostic; the deployment result is the decision.

Evidence stage Smallest useful artifact What it still does not prove
CPU semantics Oracle tests; simulator or interpreter results where available Device compilation, hardware numerics, or speed
Device operator Pinned versions, shape/dtype sweep, numerical comparison Model integration and request behavior
Integrated engine Same model/features, quality gate, warm replay Cold recovery, overload, sustained operating cost
Deployment trial Arrival replay, SLO tails, failure/recovery, total cost Universal superiority on other workloads

The repository validates CPU planning and oracle tests. Accelerator listings remain source-only unless explicitly marked device-tested; no accelerator compilation or benchmark is recorded for this chapter. The companion examples carry target-validation checklists, and docs/accelerator-acceptance-template.md supplies a baseline/candidate report with unmeasured fields left explicit.

Design Exercises

  1. A custom RMSNorm passes a CPU interpreter or simulator at widths 4096 and 4097. What must happen before reporting a device speedup?
  2. A TPU or Neuron serving port has fast warm decode but poor TTFT after scaling out. Once warm, a long prompt also interrupts eight active decodes. Which traces separate the two problems?
  3. Why does the independent TP=4, CP=2 example use eight ranks, while the nested TP=16, DCP=2 example uses sixteen? Could a larger-memory target safely reduce TP?
  4. A 2000-token request uses this chapter's cache geometry. A proposed cross-vendor handoff has a 25 GiB/s effective link, serialized pack/unpack costs of 2 ms each, and a 15 ms transfer budget. Is that enough evidence to approve it?
  5. A three-element row uses a four-element Triton tile or a 256-thread HIP block. A developer divides by four in the first kernel and adds if (tid >= n) return; to the second. Diagnose both changes.

Worked Solutions

1. A passing interpreter is the first gate

Compile for the named device and pinned stack; check supported operations, layouts, and working-memory fit. Compare device outputs across the declared dtypes and boundary shapes, then warm and synchronize the timed region. Separate compilation, copies, dispatch, and kernel work. Finally measure the operator inside the engine under the same workload and quality gate. The CPU result establishes neither device legality nor the speed of an asynchronous device execution.

2. Cold-start attribution

Trace compilation, artifact loading, allocation, warm-up, queue time, and prefill separately. Replay the same shapes on already-warm workers and count new executable variants. A cold-only regression points toward readiness and artifact distribution. For the warm interruption, inspect padded work and the scheduler's mixed or separate batches; align phase boundaries and collective intervals with visible token gaps. Require both the autoscaling test and the eight-decode replay before attributing the problem to a slow attention kernel.

3. Memory is necessary, not sufficient

Independent CP adds a second rank dimension: 4 * 2 = 8. Nested DCP partitions history among the existing sixteen TP ranks, giving 256 MiB/rank for the stated geometry. Passing DCP=2 as the helper's independent CP argument would double-count ranks. To reduce TP on a larger-memory target, recompute weights, KV, workspace, activations, and replication on the constraining rank. Confirm backend support, then compare TTFT, decode tails, and admitted concurrency under the same traffic: fewer ranks can remove collectives while reducing the bandwidth available to a request.

4. A small margin and an unproven cache contract

The request's logical KV is 2000 * 131072 = 262144000 bytes, or 250 MiB. Payload transfer takes 250 / (25 * 1024) seconds, about 9.766 ms; adding both conversions gives 13.766 ms. Only about 1.234 ms remains for the other transfer-path costs. This clears the illustrative arithmetic, not the deployment gate: establish actual wire bytes, compatible positions/head/dtype/quantization semantics, and latency under concurrent load. Test cancellation, partial transfer, ownership handoff, and failure. If that path is unsupported or misses the budget, keep homogeneous pools or route whole requests to each ecosystem.

5. A tile is not the row, and inactive work still synchronizes

The Triton squared sum must be divided by the three actual elements. The zero-filled padding lane adds no squared value and should not change the normalization. In HIP, threads with no input elements still contribute zero and reach every block barrier. Returning them early violates the block-wide synchronization contract; keep them in the reduction or design a different supported collective.

The port ends with a supported deployment configuration and workload evidence, not a translated source tree. The next part adds peers to the device schedule: which rank owns a tensor, when another rank needs it, and what happens when that rank fails. Those questions survive every accelerator choice.