KV caches, GQA/MQA, and long context
Use kv caches, gqa/mqa, and long context to move the efficient inference production brief toward a defensible release.
Long-context generation breaks latency and cost targets.
This lesson isolates kv caches, gqa/mqa, and long context as one decision inside that system. The people affected are product users and operators; the learning data must carry event time, availability time, ownership, and version; and the operating envelope is p99 first-token and cost/token SLOs.
Choose whether and how to use sampling at a declared prediction cutoff.
Measure decision utility alongside calibration, slice reliability, and system latency—not model score alone.
Long-context generation breaks latency and cost targets. An unsafe release must degrade to a named baseline or the last known-good version.
Build the mental model before the machinery.
The core move is to treat kv caches, gqa/mqa, and long context as a contract between data, a computation, and an action. Choose optimizations from workload traces with quality gates, tail latency, memory headroom, and cost per token. The implementation becomes easier to debug once you can state which inputs exist, which state is learned, what output means, and what must remain invariant after serialization.
sampling
Define it in a hand-checkable form and name the prediction-time inputs.
KV layout
Connect it to the production metric and identify what it cannot guarantee.
GQA/MQA
Stress it with a slice, a temporal boundary, and a failure-safe alternative.
quantization
Stress it with a slice, a temporal boundary, and a failure-safe alternative.
Lessons 1 in this course.
Name every symbol. Check every shape.
KV-cache memory estimate is the central invariant for this lesson. The formula is useful only when its inputs match the production cutoff and its output maps to an action.
KV-cache memory estimate
| Symbol | Meaning / shape / unit |
|---|---|
L | decoder layers |
B | active sequences |
S | cached tokens |
H_kv | KV heads |
q | bytes per scalar |
Open derivation and numerical substitution
Start from the production quantity being optimized, substitute the observed values with their declared units, then isolate the model-controlled term. Preserve shape annotations at each step so broadcasting or aggregation cannot silently change the result.
- Write the named inputs: L, B, S, H_kv, q.
- Substitute one small, hand-checkable batch before vectorizing.
- Calculate an independent reference value and compare within a declared tolerance.
# equation → code contract
inputs = validate_shapes_and_units(batch)
value = compute_c16(inputs)
assert is_finite(value)Calculate it small. Shape it realistically. Break it on purpose.
A result you can reproduce on paper
Compute cache bytes for two layers, one sequence, four tokens, one KV head, and eight-wide FP16 values.
- Write every input and unit.
- Substitute values into the kv-cache memory estimate equation above.
- Compare the result to one simple baseline and explain the direction of the difference.
The same reasoning under real constraints
Replay short-chat and long-document traces through continuous batching and compare quantized variants.
The production record includes the data snapshot, transformation state, artifact identity, cutoff, score, decision, and the version of the policy that consumed it.
The attractive result you should reject
Maximizing aggregate tokens/s destroys p99 first-token latency and harms a rare-language quality slice.
Diagnostic: replay the smallest failing slice from immutable inputs, then compare each boundary rather than retuning the model.
Change one assumption and make the tradeoff visible.
This lab runs predefined TypeScript only. It never executes learner code. Use the slider, numeric input, reset, live text, or table—the computation is the same.
GPU memory ledger
Change microbatch size and calculate a simplified training-memory budget.
Assumption: 3.2 GB weights+grads+optimizer, 0.34 GB activations per sample, 24 GB device, 10% reserve.
Open nonvisual data table
| Item | Computed state | Interpretation |
|---|---|---|
| block 1 | 1.09 GB activations | resident |
| block 2 | 2.18 GB activations | resident |
| block 3 | 3.26 GB activations | resident |
| block 4 | 4.35 GB activations | resident |
| block 5 | 5.44 GB activations | resident |
Trace the complete operating path.
- 01
Validate and version sampling.
- 02
Compute kv caches, gqa/mqa, and long context from prediction-time-safe inputs.
- 03
Persist model, feature, and configuration identities together.
- 04
Serve or materialize behind explicit p99 first-token and cost/token SLOs.
- 05
Join telemetry to mature outcomes and retain a rollback path.
Observability
Join service health, input quality, prediction distributions, slice behavior, and mature outcomes by exact version.
Cost
Measure storage, preprocessing, compute, queueing, and human review under a representative arrival pattern.
Failure modes
Maximizing aggregate tokens/s destroys p99 first-token latency and harms a rare-language quality slice. Add a detector, owner, mitigation, and stop condition for this class of failure.
Alternatives
Compare a rule, a simpler statistical baseline, and a different system boundary before adding model complexity.
Explain the contract, not just the vocabulary.
LLM inference capacity plan
Benchmark cache, batching, concurrency, sampling, and one quantized path on mixed traces.
- Benchmark contract
- Profiler/bottleneck report
- Quality gates
- Capacity and cost recommendation
Read primary material with a purpose.
Return to the opening failure.
Choose optimizations from workload traces with quality gates, tail latency, memory headroom, and cost per token.
For this lesson, the release evidence is a hand-checked formal result, deterministic simulation output, a ≥80% checkpoint, the production rubric, and a named fallback. The course resolves when the system can produce a capacity plan using efficient attention, quantization, batching, and modern routing.