ELLMEngineering Large
Language Models
Download PDF

Chapter 65

Formula and Capacity Sheet

On this page

Symbols and unit boundaries

Symbol Meaning / units Applicability
B, S, L Sequences, retained tokens per sequence, layers Ragged batches use the sum of lengths
Hkv, d, b KV heads, head width, bytes per stored value Layer-specific geometry for hybrids
P, BW Useful FLOP/s, sustainable bytes/s Same device/precision/workload as the bound
F, M Operation count, bytes crossing a named boundary Avoid combining different intervals
lambda, W, N Arrivals/s, mean seconds, mean in-flight count Stable system and consistent boundary
GB, GiB 10^9 bytes, 2^30 bytes Never mix nominal device capacity and tensor units silently

Part I's Estimating Memory and Runtime derives the consolidated capacity ledger. The inference chapters refine phase-specific traffic; the distributed chapters identify which tensors are replicated or sharded. These references are bounds and accounting identities, not device measurements.

Training

Quantity Approximation Use
Global batch microbatch * accumulation * DP Schedule and optimizer comparisons
Dense training compute proportional to parameters * tokens Budget and scaling estimates
Adam state weights + gradients + two moments, precision dependent Device and sharding memory
Pipeline bubble fraction (stages - 1) / (microbatches + stages - 1) for balanced forward-only stages Fraction of schedule spent idle
Ring all-reduce traffic 2 (n - 1) / n * tensor_bytes sent per rank; the same volume received Network estimate

Always specify which bytes are sharded, replicated, offloaded, or temporarily gathered. Adam memory may also include higher-precision master weights. Activation memory depends on sequence, microbatch, hidden width, saved intermediates, and checkpointing. The pipeline expression assumes equal stage times and ignores communication; training schedules need their own backward and overlap accounting. (stages - 1) / microbatches is bubble overhead relative to useful work, not the idle fraction of total time.

Transformer inference

KV_bytes = 2 * layers * batch * sequence * kv_heads * head_dim * bytes_per_element

decode_weight_lower_bound = weight_bytes / sustainable_bandwidth

roofline = min(peak_compute, bandwidth * FLOPs_per_byte)

attention_scores = O(sequence^2) values if materialized

FlashAttention preserves O(sequence^2) arithmetic for dense attention while reducing HBM materialization.

The KV expression assumes equal sequence lengths and head dimensions, with every listed layer storing full-history K and V. For ragged batches, replace batch * sequence by the sum of retained sequence lengths. For heterogeneous layers, sum retained_tokens * kv_heads * (key_dim * key_bytes + value_dim * value_bytes) over each request and attention layer; then account for shared prefixes, block padding, replication, and sharding. The weight-streaming expression is a time bound for one pass over the listed weights, not a per-request latency prediction for a batch.

Hybrid and recurrent state

For a hybrid, add the KV of attention layers, recurrent state for recurrent layers, local-convolution history, and allocator/workspace overhead. Do not multiply full-attention KV by the total layer count.

matrix_state_bytes = recurrent_layers * batch * heads * value_dim * key_dim * state_bytes_per_element

The expression assumes one matrix state per listed head and omits model-specific auxiliary state. MLA stores a compressed representation plus required positional state; sparse selection does not necessarily reduce stored history unless the architecture or cache policy also compresses/evicts it.

Adaptation and reinforcement learning

LoRA_parameters = rank * (input_width + output_width) for one adapted matrix.

DPO_loss = softplus(-beta * (policy_preference_logratio - reference_preference_logratio))

PPO_surrogate = min(ratio * advantage, clip(ratio, 1-eps, 1+eps) * advantage)

The PPO expression is maximized; a minimized policy loss uses its negative. DPO preference log-ratios compare chosen versus rejected response probabilities conditional on the same prompt.

group_advantage = (reward - group_mean) / group_std for the stated standardized GRPO variant; zero-variance groups require a defined policy.

ESS = sum(weights)^2 / sum(weight^2) for nonnegative weights with a positive total.

Reference-policy KL, behavior-policy ratios, and a learned value baseline have different roles. Clipping or low version lag does not establish on-policy equivalence.

Speculative decoding

accept(x) = min(1, p(x) / q(x))

correction(x) proportional to max(0, p(x) - q(x))

Pr(accept) = sum_x min(p(x), q(x)) = 1 - TV(p,q) at a fixed shared history.

Pr(accepted_prefix >= k) = product of conditional acceptance through k

E[accepted] = sum_(k=1..gamma) Pr(accepted_prefix >= k)

speedup = baseline_time_for_same_committed_tokens / speculative_time

Here p is the target distribution and q is the actual proposal distribution at the same history, after their respective sampling transformations. Acceptance is evaluated on a sampled proposal with q(x) > 0; the correction distribution is normalized only after rejection. Committed output also includes the correction token, or the extra target token when every proposal is accepted. Compare matched output work and include draft, verification, sampling, queueing, and scheduling in elapsed time; account for draft memory and lost target batch capacity separately.

Distillation

KL(p || q) = sum p log(p / q)

H(p, q) = H(p) + KL(p || q)

softmax_i(z, T) = exp(z_i / T) / sum_j exp(z_j / T)

Classic logit distillation often uses T^2 * KL(teacher_T || student_T) plus a hard-label loss.

Diffusion transformers and flow matching

latent_tokens = (latent_height / patch_side) * (latent_width / patch_side) for divisible spatial dimensions; each patch contains channels * patch_side^2 scalars.

x_t = (1-t)*x_0 + t*x_1, velocity_target = x_1-x_0, with noise at time zero and data at time one.

x_next = x + dt*v_theta(x,t,c) is one Euler step. Network evaluations depend on the solver stages and any guidance calls, not only the number of outer steps. A changing bidirectional latent generally cannot reuse an append-only autoregressive KV cache.

Streaming

Structure Update / query Memory Contract
Min-heap top-k O(log k) update O(k) Exact for insert-only global top-k
Monotonic deque amortized O(1) window size worst case Exact sliding min/max
Reservoir O(1) expected O(k) Uniform sample of unknown-length stream
Count-Min Sketch O(depth) O(width * depth) One-sided overestimate for nonnegative current frequencies under standard linear updates
HyperLogLog O(1) fixed registers Probabilistic cardinality
Bloom filter O(hashes) bit array False positives, no false negatives for insert-only membership

For tied quantile values, distinguish cumulative rank R_le(v) from the occupied occurrence interval [R_lt(v)+1,R_le(v)]. A returned-value rank tolerance can intersect that interval even when its upper endpoint is far from the requested rank.

Queueing and capacity

Little's Law under stable conditions: L = lambda W, where L is average work in system, lambda arrival rate, and W average time.

It does not predict tail latency or prove capacity. Use it to check dimensional consistency and connect concurrency to service time.

At high utilization with variable service time, queueing rises nonlinearly. Provision headroom based on burst and failure targets, not average utilization alone.

Precision and quantization

For symmetric signed quantization with scale s:

q = clip(round(x / s), q_min, q_max)

x_hat = s q

Per-group metadata cost is number_of_groups * scale_bytes plus optional zero points. Effective model bytes include packing, alignment, scales, outliers, and any higher-precision fallback.

Communication

Communication time is often modeled as:

time = latency_term * messages + bytes / bandwidth

Collective algorithms alter both. Overlap hides only communication that runs concurrently with independent useful compute; report exposed communication on the critical path.