Chapter 2 · Build and stress

Continuous batching and speculative decoding

Throughput techniques earn their place only when they improve completed requests—not merely scheduled tokens.

65–90 min4 key conceptsReviewed 26 Aug 2026
01 · Production proposition

Long-context generation breaks latency and cost targets.

This chapter moves from replay real arrivals to measure acceptance economics. We will make the idea concrete in a small code example before placing it back inside a production system with p99 first-token and cost/token SLOs.

Decision

For speculative decoding, compare accepted tokens per draft call with draft cost and target verification time.

Evidence

Verify the behavior illustrated in speculate.py, then measure decision utility, slice reliability, and system latency.

Failure consequence

Maximizing aggregate tokens/s destroys p99 first-token latency and harms a rare-language quality slice. An unsafe release must degrade to a named baseline or the last known-good version.

02 · Guided chapter

Build the idea one layer at a time.

Static batches wait for every sequence to finish, wasting decode slots when outputs have different lengths. Continuous batching refills those slots; speculative decoding tries to fill several future positions at once. Both improve useful work per accelerator only when scheduling overhead and tail latency stay bounded.

A continuous scheduler operates at token boundaries. Finished or paused requests leave the active batch, and queued requests enter without waiting for a global batch to drain. This raises utilization, but a very large active set increases queueing, cache pressure, and the time each request waits between tokens.

Speculative decoding asks a cheaper draft model for several candidate tokens, then verifies them with the target model in parallel. Correct acceptance preserves the target distribution; speed depends on draft cost and acceptance length. A fast draft that is often rejected can make the system slower, so acceptance must be measured by workload slice.

Keep in view
  • paged attention
  • continuous batching
  • speculative decoding
  • MoE
WORKED PATH

Follow the reasoning before touching the code.

  1. 01

    Replay real arrivals

    Preserve prompt lengths, generation lengths, burstiness, priorities, and cancellations rather than benchmarking one synthetic batch.

  2. 02

    Bound the scheduler

    Set limits for active tokens, cache occupancy, queue delay, and per-tenant share; shed or degrade before memory is exhausted.

  3. 03

    Measure acceptance economics

    For speculative decoding, compare accepted tokens per draft call with draft cost and target verification time.

pythonspeculate.py
def accepted_prefix(draft, target):
    accepted = 0
    for proposed, verified in zip(draft, target):
        if proposed != verified:
            break
        accepted += 1
    return accepted

requests = [([4, 8, 1], [4, 8, 9]),
            ([3, 2, 7], [6, 2, 7])]
for draft, target in requests:
    print(accepted_prefix(draft, target))

Count the useful prefix from a speculative draft

READ THE EXAMPLE

What to notice

  • The first draft saves verification work for a two-token prefix; the second fails at the first token and contributes no accepted prefix.
  • Real speculative sampling uses an acceptance rule over probabilities, not simple token equality, but the useful-work intuition is the same.
YOUR TURN Pause and predict before revealing the answer.

Suppose a draft proposes four tokens at one unit of cost and the target verifies them at four units. When is drafting unattractive?

Need a hint?

Compare accepted progress with the extra draft cost and with an ordinary target decode step.

Check your reasoning

It is unattractive when acceptance is so low that the added draft work and verification do not reduce target decode steps enough to offset their overhead.

Bring forward

Lessons 1, 2, 3 in this course.

03 · Formal treatment

Connect the chapter to the course’s quantitative spine.

Throughput techniques earn their place only when they improve completed requests—not merely scheduled tokens. The kv-cache memory estimate below is the shared course-level lens that helps quantify the surrounding system. Name each symbol, check its units or shape, and use only values that were available at the production cutoff.

Formal treatment
MKV≈2⋅L⋅B⋅S⋅Hkv⋅dh⋅qM_{\mathrm{KV}} \approx 2 \cdot L \cdot B \cdot S \cdot H_{\mathrm{kv}} \cdot d_h \cdot q

KV-cache memory estimate

Symbol, shape or unit contract
SymbolMeaning / shape / unit
Ldecoder layers
Bactive sequences
Scached tokens
H_kvKV heads
qbytes 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.

  1. Write the named inputs: L, B, S, H_kv, q.
  2. Substitute one small, hand-checkable batch before vectorizing.
  3. 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)
04 · Deterministic lab

Change one assumption and make the tradeoff visible.

Use the worked chapter as your prediction, then change one input in the lab and explain why the output moves. The lab runs predefined TypeScript and never executes learner code, so the focus stays on the concept rather than setup.

Estimate

GPU memory ledger

Change microbatch size and calculate a simplified training-memory budget.

samples
Primary8.6 GB
Secondary36.0%
DiagnosisFits

Assumption: 3.2 GB weights+grads+optimizer, 0.34 GB activations per sample, 24 GB device, 10% reserve.

Open nonvisual data table
ItemComputed stateInterpretation
block 11.09 GB activationsresident
block 22.18 GB activationsresident
block 33.26 GB activationsresident
block 44.35 GB activationsresident
block 55.44 GB activationsresident
05 · Production implications

Trace the complete operating path.

Carry the chapter’s central idea into the system: Throughput techniques earn their place only when they improve completed requests—not merely scheduled tokens. The path below shows where that reasoning needs an artifact, a test, an owner, or a fallback.

  1. 01

    Turn “Replay real arrivals” into a written invariant and a failing test.

  2. 02

    Promote speculate.py from illustration to a versioned implementation with representative fixtures.

  3. 03

    Use “Measure acceptance economics” as the release checkpoint: For speculative decoding, compare accepted tokens per draft call with draft cost and target verification time.

  4. 04

    Serve or materialize behind explicit p99 first-token and cost/token SLOs.

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

06 · Check understanding

Explain the contract, not just the vocabulary.

Browser-graded checkpointPass ≥ 80%
01Why does KV memory grow with context?
02Why can continuous batching hurt a request?
03When is quantization acceptable?
07 · Apply in production

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
Open assignment and rubric
08 · Sources & next depth

Read primary material with a purpose.

09 · Production resolution

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 the worked code example, 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.