LLM Inference connects large language model generation to memory capacity, request scheduling, latency, throughput and output quality. Learn to explain serving-engine behavior and compare changes while keeping workload and decoding semantics explicit.
Read GPU Performance Tools before practical work. Complete GPU Fundamentals and GPU Performance Optimization first, or bring their execution, timing and profiling skills. No training-course prerequisite is required. Begin with generation mechanics, then develop local serving-engine comparisons and request measurement.
Local GPU practice uses one full H100; distributed serving and multi-worker placement belong to Advanced Labs. Serving experiments require qualified runtimes and model artifacts before making performance claims. Follow the shared Lab Preparation and check its completion summary before practice. Default setup includes optional engine dependencies; it does not start or qualify a model server.
Read the objective and explanation, then use the mental model to review the mechanism. Explain what the technique is, why it is useful and how it works before following the Practice links.
Practice
Follow Lab Preparation to prepare the available lab software with one command. Check its completion summary before submitting a lab. Each practical lab explains its purpose and concepts, then gives the commands and comparison to make. Check the results before interpreting performance.
Review
Compare correctness, repeated measurements, and profiler observations. Use the glossary and detailed diagrams when a term or relationship needs a second look.
Use the benchmark worksheet to record what your environment demonstrates and what remains to be tested.
Optional further study
Dynamo disaggregated serving and KV-aware routing
1. Model inference and artifact preparation
Objective
Explain how fixed model parameters generate output tokens and verify the model artifacts needed for a controlled inference run.
How it works
What inference is
Inference means using an already-trained model to compute an output for a new input. The model's parameters are the learned numbers used in that computation. Ordinary inference reads those parameters; it does not run an optimizer to learn from the current request. Inference can mean classification, producing an embedding vector, or generating text. This course focuses on autoregressive decoder-only language models: models that generate later tokens using the input and previously generated tokens.
A token is a unit in a tokenizer's vocabulary, represented by an integer ID. It can be a word fragment, punctuation or part of a byte sequence, so tokens are not interchangeable with words or network chunks. The model processes IDs, not human-readable sentences directly. A tokenizer converts between text and IDs; a chat template formats roles and messages into the model's expected input. Weights, tokenizer and configuration must agree.
Why inference needs its own course
Training pays to change model behavior. Inference repeatedly pays to use that behavior for actual requests. A usable application needs more than a plausible answer: it needs appropriate response time, output quality, memory capacity, throughput and safe input/output handling. A GPU that can hold a model's weights may still lack space for many long requests. A change that increases total throughput can make each user wait longer. These are distinct engineering decisions.
Generating text does not by itself update model weights or guarantee factual correctness. Adding retrieved documents changes the context available to the request, not the learned parameters. Applications may store conversations or separately train from approved data, but that is an additional workflow, not an automatic effect of inference. GPU Fundamentals and Optimizations provide the device and measurement prerequisites.
How one request becomes generated text
A large language model (LLM) needs an artifact bundle: its weight files plus the configuration, tokenizer and other data required to reproduce execution. A revision identifies a particular version; a checksum or cryptographic hash is a content fingerprint used to detect changed bytes, not proof that the content is trustworthy. An adapter supplies additional learned parameters associated with a base model. Quantization metadata describes how compact stored values map to numerical weights. A safetensors shard is one tensor-data file in a split weight set. Remote model code is executable implementation code obtained with a model, so allowing it has a different security meaning from reading tensor data. The audit later in this lesson checks these distinct components.
First establish a trusted, compatible model artifact, then load its fixed weights and prepare the engine. For a request, the host formats and tokenizes the prompt, queues it, and supplies token IDs to the model. Embeddings turn IDs into vectors. Transformer layers combine information from allowed preceding positions and produce logits: scores for possible next tokens. Softmax and the chosen decoding rule turn those scores into a token choice. Greedy decoding chooses a highest-scoring token; sampling draws from a configured distribution.
Prefill processes the known prompt and stores reusable attention keys and values, called the key/value (KV) cache. The logits at the final prompt position supply the first output token. There is no compulsory extra decode pass before that first choice. If the request continues, the next forward processes the newly chosen token, reads earlier cached state and appends that input token's keys and values. It then supplies logits for another token. This feedback loop is decode.
Check end-of-sequence, stop rules and the output budget after token selection. Detokenize permitted output and return or stream it; release request state when the request finishes. The newest selected token only acquires KV entries if it is subsequently processed by a forward pass. While weights stay fixed, the token history, cache, random-number state and scheduler membership can change. CPU and GPU responsibilities depend on the engine: formatting and networking are usually host work, while model tensor computation is GPU work. Never assume every step or every sampling implementation runs on one processor.
Autoregressive inference lifecycle
Tokenization produces prompt IDs; prefill produces first-token logits and prompt KV. Both prefill and later decode logits feed one sampling policy. The chosen ID passes through a common append, stopping, buffering, detokenization and streaming policy. Emit only allowed content, withholding EOS and matched stop strings. Continuing requests feed the chosen token to decode; finished requests finalize the response.
Execution and dependencies
A request will become token IDs, model computations and generated tokens. Before loading any model, establish what artifact supplies those computations and whether it is safe and compatible to load. No running engine is needed for this first metadata audit; GPU Fundamentals and Optimizations supply the device and measurement prerequisites.
Loading a model turns an artifact bundle into an executable computation. The configuration describes the architecture; the weight shards and index supply its tensors; the tokenizer and chat template determine the input IDs. Generation settings, adapters and quantization metadata can change how the same visible request is processed. Immutable revisions and checksums identify which bundle is being used, while expected tensor shapes, dtypes and special-token IDs check that its parts agree.
The loading path has several stages. Metadata is resolved first, files are downloaded or staged on the CPU if needed, loading places the weights in device memory, and libraries or kernels perform first-use setup. Readiness follows only after the intended request path can run. Mixing those stages into a steady-state benchmark makes loading and warm-up look like ordinary inference cost.
Artifact loading
Read downward through preparation. The configuration, tokenizer, weights, adapters and quantization must agree. A live process is not sufficient readiness; startup and warm-up remain separate from steady serving.
Enabling trust_remote_code=True permits Python code supplied by the model repository to execute. It is not merely permission to read weight data. License metadata also needs review rather than automatic acceptance. The artifact record distinguishes local, fetched, transformed and compiled components while keeping credentials and private paths out of shared evidence.
During inference, an embedding table maps each input ID to a vector, and model operations read the loaded parameters. model.eval() selects evaluation behavior for modules such as dropout; it does not disable autograd. torch.inference_mode() avoids autograd recording for forward-only work. Neither mode makes parameters immutable. Keeping weights fixed is part of the inference workflow: no optimizer update is performed for the request.
A model name is not a complete artifact identity. Different tokenizer, chat template, adapter, quantization, generation, or remote-code revisions can change token counts, memory, outputs, and performance while appearing to be “the same model.”
Try a small example
Imagine a four-token vocabulary: I, like, GPUs and an end marker. A fixed table of next-token scores can map I to like, like to GPUs, and GPUs to the end marker. Starting with I, three repeated choices yield like, GPUs and stop. The table never changes. A one-token output budget instead stops after like. This is a transparent autoregressive model, not a trained transformer: it has no attention, prefill optimization or KV cache.
Practice
Begin with Lab 35’s fixed-parameter inference exercise, then use Lab 16 to audit the model and tokenizer metadata before loading a real model.
Inference behavior depends on an artifact bundle: architecture config, tokenizer and template, weights, generation defaults, adapters, quantization scheme, revision, and optional remote code.
2. Autoregressive generation
Objective
Trace one request from text to tokens, prompt processing, iterative decode, detokenization, and stop conditions.
How it works
Tokenization converts text into token IDs using a vocabulary and its rules. Prefill processes the known prompt and produces attention state plus logits, the scores used to choose the first output token. Decode then processes newly selected tokens one step at a time using the saved state. Detokenization turns output IDs back into text, and stopping decides when generation ends. The first output does not require a separate decode pass after prefill. TensorRT-LLM also calls prefill the context phase and decode the generation phase.
Inside attention, a learned projection transforms token vectors into queries (Q), keys (K) and values (V). A query describes what a position seeks, keys provide matching information, and values carry the information mixed into the result. The key/value (KV) cache stores prior keys and values. In shape notation, B is batch size, S is sequence length and H is hidden-vector width. These components explain the request workflow before its tensor shapes and timed operations are examined.
The audit fixes the tokenizer and model. This lesson follows one request through those artifacts so later metrics can be attached to exact phases rather than to a single opaque “inference time.”
Process the known prompt
The chat template formats the request, and the pinned tokenizer converts it into IDs [B,S]. Embedding lookup produces vectors [B,S,H]. Prefill processes those known prompt positions, forms attention queries, keys and values, and stores per-layer K/V state for the processed tokens. Causal masking prevents a position from using future prompt tokens even though many positions are computed in parallel.
The final prompt position's logits already describe the first output-token distribution. The decoding rule selects that token directly; no extra decode forward is required before the first choice. The stopping and buffering policy then decides whether to end generation and which content may be returned.
Continue only while another token is needed
If generation continues, the sampled token becomes the input to the next forward pass. That pass reads prior K/V, appends K/V for its current input token and produces logits for the following token. Selection and stopping checks repeat. A token gains cache entries only when a forward pass processes it; the final sampled token may never enter KV if generation stops immediately afterward.
Prefill and decode
Read downward in event order. Prefill supplies the first output distribution; only if generation continues does a forward process the sampled token and append its KV. The spacing shows order, not measured time.
Hugging Face Transformers provides model/tokenizer classes and a DynamicCache that grows as new inputs are processed. Parameters stay fixed during this loop, while request history, cache blocks, random number generator (RNG) state and scheduler membership can change. Detokenization may buffer incomplete byte sequences, and a Hypertext Transfer Protocol (HTTP) chunk can carry zero, one or several model tokens.
Match the attention mask to the phase
For one head, attention forms scores Q @ K.T / sqrt(head_dim), applies the allowed-position mask, converts scores to weights with softmax and combines V using those weights. Square prompt attention has a lower-triangular allowed region. A one-token continuation instead needs access to all valid cached positions, including its current input. A square-prefill masking rule applied without checking absolute positions can hide required history in this nonsquare case.
Prefill writes the KV cache; decode reads and appends it
Prefill processes prompt positions, creates per-layer K/V, and produces first-token logits. During subsequent decode steps, the model processes a generated token to create its current Q/K/V. Current Q attends to past and current K/V; output projection, residual/MLP paths, remaining layers, final normalization and LM head produce next-token logits. Appending K/V is a storage side effect, never the producer of logits.
PyTorch's scaled dot-product attention (SDPA) application programming interface (API), scaled_dot_product_attention, expresses the operation but does not by itself identify the chosen kernel. Correct shapes and allowed context come first; Lesson 11 develops backend optimization.
Prefill and decode execute different shapes and stress different resources. Model correctness, service correctness, and streaming transport correctness are also separate: valid logits do not guarantee correct stop handling or chunk/token accounting.
Practice
Run Lab 09 to trace prefill and continuation. Inspect Lab 08’s cache shapes as a preview; its full comparison belongs to Lesson 4.
Prefill computes prompt representations, initializes KV state, and supplies the final prompt position's logits for sampling the first output token. If generation continues, decode reads prior KV, processes the last sampled token and appends that input token's KV, then produces logits and samples the following token. Each sampled token passes through the same stopping checks.
3. Decoding policy and output quality
Objective
Separate deterministic decoding, stochastic workload control, and output-quality evaluation.
How it works
Sampling chooses a next token from a probability distribution derived from the model's logits, or raw scores. Greedy decoding chooses a highest-scoring token instead of drawing randomly. Temperature changes how concentrated the distribution is; top-k restricts choices to k leading tokens, while top-p keeps a leading set whose cumulative probability reaches a threshold. A seed initializes pseudorandom choices for reproducibility; it does not guarantee identical results across different implementations or hardware.
For probabilities [0.7, 0.2, 0.1], greedy decoding chooses the first token, but sampling can choose any allowed token. Changing the policy can change answer length, content and computational work. A quality metric evaluates whether outputs meet the task's needs, whereas a repeatability check asks whether a declared run can be reproduced. Holding sampling settings fixed is necessary for a useful comparison, but identical speed or identical text is not by itself a measure of answer quality.
The decode loop applies sampling and stopping after logits. Those policies determine both output semantics and how much work each request performs.
The model first produces logits for the next token. Greedy decoding selects a largest logit. Stochastic decoding instead constructs a probability distribution and samples from it, so several tokens can be valid outcomes of the same prompt.
Temperature T > 0 divides logits by T before softmax. A smaller T makes high-scoring tokens relatively more likely; a larger T flattens the probabilities. Top-k retains the k leading candidates. Top-p retains the smallest ranked prefix whose cumulative probability reaches p, then renormalizes the retained probabilities. Applying top-k and top-p together can give different results in different orders, so the engine's processor order and threshold convention are part of the policy.
Repetition controls, maximum tokens, stop IDs or strings and sampling choices affect both the output and the amount of work. A candidate that stops earlier can appear faster without executing equivalent generation. Prompt-token counts, output-length distributions, finish reasons and empty or error responses make that difference visible.
Decoding policy
Arrows show policy order. Apply the declared temperature and filtering before selection; greedy selection chooses the highest eligible score, while sampling draws from the eligible distribution. Append the chosen token and evaluate stopping rules before continuing. The policy and random-state convention determine the output contract.
A deterministic regression profile, often greedy or fixed settings and seed, checks a bounded reproducible behavior. A fixed seed helps replay on the same qualified stack but does not promise identical samples across kernels or engines. A representative stochastic profile tests a declared distribution of requests and outputs instead. Exact token/text comparisons suit an exact-equality contract; task evaluators and confidence intervals suit stochastic quality claims. Generated length must be reported when it is both an outcome and a performance denominator.
A candidate can look faster only because it emits fewer tokens, stops earlier, uses a different seed, or changes randomness. Deterministic regression and representative stochastic service evaluation answer different questions.
Practice
Use Lab 17 to compare greedy and seeded stochastic generation with explicit stopping and output-equivalence rules.
Decoding configuration changes token choices, output length, termination, and quality. Performance comparisons need a fixed profile or a declared stochastic distribution.
4. Attention-cache capacity
Objective
Derive KV bytes per token and predict concurrency limits.
How it works
The key-value (KV) cache stores attention information from tokens the model has already processed, avoiding repeated key/value computation during generation. Attention heads are parallel components that form queries, keys and values; head dimension is the width of each head's vectors. Multi-head attention (MHA) uses separate key/value heads for its query heads. Grouped-query attention (GQA) shares each key/value head among a group of query heads. Multi-query attention (MQA) shares one key/value head across all query heads.
These are model-architecture choices, not interchangeable cache switches for arbitrary weights. Cache dtype is the numerical representation used to store its values. Device-resident state is data currently stored in GPU memory, and headroom is capacity left for growth or other allocations. KV size therefore depends on the model's actual layers, key/value heads, head dimension, stored-token count and representation—not simply its parameter count.
Generation and sampling now define what output is requested and when it stops. Cached key/value tensors retain attention state from processed tokens, so their size connects that fixed token contract to the maximum resident workload.
For each processed token, each attention layer retains a key vector and a value vector for every KV head. A head has head_dim elements, and each stored element uses a chosen number of bytes. Multiplying these dimensions gives ideal KV bytes per token: layers × KV_heads × head_dim × 2(K and V) × bytes_per_element. Multiply again by the stored token count across active requests to estimate their logical cache payload.
The factor of two counts keys and values. The head count is the number of KV heads, not automatically the number of query heads. MHA normally supplies one KV head per query head; GQA shares fewer KV heads among query groups; MQA shares one. These architectural choices can reduce cache bytes while retaining the query-head count. They cannot simply be switched on for arbitrary trained weights.
The ideal payload is only one part of peak device memory. Weights and quantization metadata coexist with the KV pool, while prefill activations, attention workspaces, graph pools and communication buffers can add phase-specific peaks. Loading and staging can create a different peak again. Allocator overhead, fragmentation and operational headroom need separate allowance without double-counting active bytes already included in reserved memory.
Inference memory by lifecycle phase
Fixed model weights remain resident. Loading and warm-up use staging or compilation memory, prefill uses large temporary activations, decode retains growing key-value cache blocks, and the serving engine reserves allocator and scheduler capacity.
Actual allocated blocks can exceed the formula because of padding, alignment, page metadata, replication or engine-specific layouts. Hybrid attention layers can also require a layer-specific calculation. Comparing the logical formula with allocated blocks and measured peaks explains the difference between expected payload and usable admission capacity.
KV cache often limits active sequence concurrency, but the ideal formula is only one part of peak memory. Ignoring weights, workspaces, graph pools, communication buffers, fragmentation, and safety reserve creates unsafe admission limits.
For a hypothetical model with 32 layers, 8 key/value heads per layer, 128 values per head and 2 bytes per stored value, one cached token needs 2 × 32 × 8 × 128 × 2 = 131,072 bytes, or 128 KiB. The initial factor of two counts keys and values. At 2,048 cached tokens, one request needs 256 MiB; eight such requests need 2 GiB. This excludes block rounding, metadata and all other model memory. It is a capacity calculation, not a measured allocation or a promise that every architecture uses this layout.
KV capacity
The arrows show the calculation: first derive bytes per token, then multiply by stored tokens. Admission also needs room for weights, workspaces, pools and overhead; the ideal KV formula is not total peak memory.
Practice
Use Lab 26 to calculate ideal cache capacity, then Lab 08 to compare cached attention with recomputation. Distinguish the storage model from measured execution.
KV cache scales with layers, KV heads, head dimension, dtype bytes, tokens, and active sequences. GQA/MQA reduce KV heads relative to query heads.
5. Inference workload shape
Objective
Build a workload matrix that reveals phase and queueing behavior.
How it works
Input sequence length (ISL) counts prompt tokens and output sequence length (OSL) counts generated tokens. A requested output limit is a maximum; the observed output may be shorter because of stopping. Concurrency counts requests in progress together, while arrival rate counts new requests entering per unit time. These describe different aspects of a workload: ten active requests do not tell you whether they arrived together or gradually.
A workload distribution records the mix of lengths and request types. Burstiness describes arrivals concentrated into short intervals. A queue holds waiting work, and a scheduler chooses what runs next. A service-level objective (SLO) is a declared service target, such as a first-token latency threshold for a stated fraction of requests. Before tuning an engine, define this workload: a long-prompt, short-answer service stresses different phases from a short-prompt, long-answer service.
Prefill cost scales with input sequence length, decode lifetime with output length, and scheduler pressure with arrivals/concurrency. One average prompt hides these interacting axes.
A workload cell describes both how a request begins and how long it continues. ISL sets the amount of prompt processing and initial key/value (KV) state. Observed OSL sets the number of generated tokens, continuation passes and growth of history reads. A long prompt with a short answer therefore stresses different phases from a short prompt with a long answer.
Concurrency adds requests that compete or batch together. Arrival rate and burstiness determine how quickly new requests reach the queue; they are not implied by the number currently active. An ISL×OSL heat map should therefore include short/short, long/short, short/long and long/long cases, with the arrival process and concurrency defined alongside it. Weighted aggregate results are useful only after individual cells remain visible, especially those with strict service targets. Changing traffic patterns can justify versioned operational profiles with explicit conditions for switching or review.
ISL and OSL matrix
Rows vary prompt length (ISL), and columns vary generated length (OSL). Each cell is a different workload; repeat the matrix at other concurrency or arrival rates rather than treating load as another cell.
Batch shape introduces a further cost. Padding lengths 3, 4 and 8 into one rectangular batch uses 24 positions for 15 real tokens. Bucketing [3,4] separately from [8] uses 16 positions for those same 15 tokens. It reduces padding but creates extra batches or scheduling constraints. Prompt identity, masks and position information must survive grouping and ungrouping; otherwise the apparent saving changes the computation.
Sequential dependence is another axis beyond size. In state = tanh(state @ weight), each update needs the previous state before it can proceed. Tanh is an elementwise function bounded between -1 and 1. Such recurrent updates offer different parallelism from processing a wide known input, which is why total element count alone does not describe a workload.
Engine settings that win for short chat can fail for long-context summarization or long generation. Production traffic may also change by time or tenant, so one permanent configuration is not always best.
Practice
Use Labs 18 and 25 to vary prompt shape and recurrent work, keeping the request and output accounting explicit.
ISL drives prompt processing and initial KV; OSL drives decode iterations and KV growth; concurrency controls batching, queueing, and capacity pressure.
6. Model-serving architecture
Objective
Start a pinned serving stack, verify readiness, and benchmark through its public request boundary.
How it works
Model serving keeps a model available to answer requests from applications. An execution engine performs the model computation and manages resources such as batching and key/value (KV) state; a server receives requests, invokes execution and returns responses. vLLM provides a large language model (LLM) execution engine and a serving interface. NVIDIA TensorRT-LLM provides optimized LLM execution components and serving workflows. NVIDIA Triton Inference Server supplies a serving layer that can use a TensorRT-LLM backend. Triton Inference Server is a different project from the Triton GPU-programming language used in some kernel examples.
An endpoint is an addressable service entry point. Its application programming interface (API) schema defines request and response fields. Readiness means the service can accept the intended requests, not merely that a process exists; warm-up prepares first-use work before measurement. A container packages an execution environment, and its digest identifies exact image content. These roles must be understood before combining versions, launchers and deployment options.
Artifact identity, generation, sampling, KV capacity and the workload matrix are established. Start a controlled single-GPU engine so the next lesson has a real endpoint to measure. Its paging and scheduler internals are introduced only at a high level here and studied in Lessons 8–10.
Separate request handling from model execution
A serving request reaches an API, is checked against its schema, and is passed to the model's execution path. vLLM supplies an engine and serving interface with continuous scheduling and paged KV management. TensorRT-LLM supplies NVIDIA-optimized model execution, while Triton Inference Server can manage the request boundary and model repository around a supported backend. Their components must be combined through a supported version contract.
Hypertext Transfer Protocol (HTTP) carries requests and responses; JavaScript Object Notation (JSON) represents structured request fields and results. A client supplies a model name, prompt and generation settings, and receives output plus available usage metadata. Offline generation calls the engine directly and omits that service boundary. OpenAI-compatible and Triton APIs can both use HTTP while requiring different payload schemas.
Serving stack
Read downward through a request's execution layers. The client observes the service boundary, the engine schedules work and KV state, and the device executes kernels. Client metrics do not by themselves identify the internal bottleneck.
Establish readiness before measuring service
A process starts before all its model state and kernels are necessarily ready. The controlled lifecycle loads the pinned model, establishes a real readiness condition, checks a deterministic request, warms intended shapes and then starts the load client. Container digest, engine/framework/CUDA versions, build flags, dtype/quantization and scheduler/cache settings identify that execution. Independent restarts separate policy A/B trials so retained state does not bias the comparison. The interface stays non-public; logs remain private and shared evidence contains only sanitized configuration and aggregates.
Extend the request contract for adapters and media
Low-rank adaptation (LoRA) represents a task-specific weight update as the product of two small matrix factors, added to the transformation performed by a fixed base model. Multi-LoRA serving selects different adapters for different requests while sharing the base weights. This is an advanced, engine-specific extension: qualify each adapter against its exact base-model identity, isolate cache entries between adapters, and measure adapter-switch scheduling, memory pressure, and output quality under concurrent requests. An adapter fitting alone does not prove that many adapters can serve together safely.
Multimodal inference accepts more than one kind of input, such as text and images. A model-specific processor prepares each input type, often using an encoder to turn media into representations the language model can consume. Serving these requests therefore needs a model-specific workload contract. Record how authorized images or other media expand into model tokens, include encoder latency and encoder/cache state, and test scheduling and quality with the actual supported engine. Text-only input sequence length (ISL), cache, and throughput measurements do not automatically describe a multimodal request; avoid collecting or publishing private media.
A process can be alive before weights, engines, graphs, and caches are ready. Benchmarking an unpinned or warming server mixes startup failures with steady-state latency and makes results irreproducible.
Practice
Use Lab 10 for offline batching and Lab 11’s server workflow to prepare a live engine. Run the Lab 30 readiness/schema probe before interpreting client performance.
The serving engine owns model loading, KV management, scheduling, kernels, and metrics; Triton can provide model lifecycle and request handling around TensorRT-LLM.
7. Serving latency and useful throughput
Objective
Use user-facing latency and server-capacity metrics with explicit boundaries.
How it works
Latency measures how long a request or stage takes. Time to first token (TTFT) measures from a declared request boundary to the first generated token. Inter-token latency (ITL) and time per output token (TPOT) describe generation latency using tool-specific timing and averaging conventions. Distinguish individual token-arrival gaps from an average over one request. Throughput measures completed work per unit time, while goodput counts only work meeting the specified service and validity criteria.
A percentile describes a position in the observed latency distribution: p95 is a boundary at or below which 95 percent of observations lie. Open-loop load schedules arrivals independently of response completion; closed-loop load allows completions to determine when more work is sent. AIPerf is a client-side tool for generating controlled inference requests and reporting service measurements. Network chunks may contain zero, one or several tokens, so chunk timing and true token timing are not automatically the same metric.
The workload matrix defines requests and the engine lifecycle provides a controlled endpoint. Metrics now define when clocks start, what each duration represents and how concurrent requests share capacity. Establish these boundaries before changing cache or scheduling policy.
Place timestamps on the request path
TTFT starts at the declared request-submission boundary and ends when the first output token is observed there. It can include queueing, preprocessing, prefill, first-token selection/postprocessing and transport. Prefill already supplies the first-token logits; a separate mandatory decode pass is not part of that sequence.
After the first token, individual token-arrival gaps show how evenly output arrives. For N > 1 output tokens, mean TPOT is (last_token_time - first_token_time)/(N-1): N tokens contain N−1 post-first-token gaps. A single-token output has no such interval. Last-token latency ends at the final content token, while response-completion latency can extend to later protocol or finish metadata. Substituting completion time into TPOT includes that extra overhead unless the timestamps coincide.
LLM request latency decomposition
Request start t0, first observed token t1, final content token tN and protocol completion tc are distinct timestamps. TTFT=t1-t0; last-token latency=tN-t0; response completion latency=tc-t0. With N greater than one, TPOT=(tN-t1)/(N-1). Streaming chunks can bundle tokens. AIPerf reports request-average ITL and chunk-gap ICL; the lesson explains its timestamp and token-count conventions.
Distinguish tokens from transport events
Server-Sent Events (SSE) carries successive events on a Hypertext Transfer Protocol (HTTP) response. An event can contain metadata, several tokens or no content token, and transport chunks need not match event or token boundaries. First-content timestamps and inter-chunk gaps are therefore proxies unless the client has appropriate per-token accounting. Bundled tokens do not provide enough information to invent individual arrival times.
Read AIPerf metric names precisely
AIPerf reports inter_token_latency as one average per request. Its documented default calculation is (request_latency - time_to_first_token)/(output_sequence_length - 1), requiring at least two output tokens. Check the metric definition for the installed version and configuration, and use its timestamp endpoints rather than silently substituting the last-token timestamp in the conceptual TPOT calculation above. A percentile of these ITL values describes request averages, not every individual token gap. AIPerf's inter-chunk latency (ICL) instead records gaps between content-bearing response chunks. Token counts normalize ITL; they do not reconstruct arrival times for tokens delivered together.
Service metrics
Read downward through observable events. TTFT ends at the first token; AIPerf ITL averages later latency per output-token interval. Protocol completion may occur after the last content token, and transport chunks do not necessarily identify individual tokens.
Count completed work under a defined load
System output throughput divides completed output tokens by a shared measurement interval. A per-request generation rate has a different denominator and must be labeled. Goodput counts only work satisfying the declared latency, error and quality criteria, so high raw throughput can coexist with poor goodput.
Open-loop load schedules new arrivals independently of previous completions and can expose queue growth under overload. Closed-loop clients wait for completions before sending more work; their waiting can conceal a server's inability to handle an independent arrival stream. The load model, warm-up treatment, measurement window and latency distributions are part of the meaning of every reported rate.
Tools disagree about ITL/TPOT boundaries, empty chunks, warm-up, and throughput windows. Open-loop and closed-loop generators also produce different queueing behavior, so unlabeled numbers cannot be compared.
Practice
Use Labs 11 and 15 for request latency and streaming boundaries, including the introductory AIPerf comparison through Lab 15’s --experiment aiperf route in Readiness checks. The default lab commands use the supplied clients; the AIPerf route uses the prepared serving runtime and its pinned default model. Lab 15's supplied client runs a finite closed-loop workload and reports median/p90 first-content and completion latency, inter-chunk gaps and requests/s. It does not implement open-loop arrivals or measure token throughput or SLO goodput. Revisit Lab 25 only as an operator-level contrast, not a serving benchmark.
TTFT measures the wait for first output. Specify whether later latency values are individual gaps or request averages: AIPerf calls its request average ITL and its chunk-gap metric ICL. Throughput counts completed work; goodput counts work meeting service objectives.
8. Attention-cache allocation and reclamation
Objective
Explain how block allocation reduces unusable reserved capacity and where fragmentation remains.
How it works
Paged key/value (KV) management divides available cache storage into fixed-size blocks instead of reserving one maximum-length contiguous region for every request. Each request maps logical token positions to physical cache blocks, obtains additional blocks as it grows, and returns blocks when they are no longer needed. Logical positions describe the sequence seen by the model; physical blocks describe where its cached values are stored. This is an allocation strategy, not a change to the attention equation.
A free list tracks reusable blocks. Fragmentation is storage wasted by an allocation layout, including unused slots at a block's end. Reference counts record shared ownership; copy-on-write creates a private copy before modifying shared state. Eviction removes cached state, preemption pauses work, and offload or swapping moves state to another storage tier. Their costs differ: freeing cache without preserving or recomputing required state would change the computation, not merely its memory use.
The KV formula predicts bytes. Paged allocation decides how those bytes are divided, mapped to requests, and reclaimed as variable-length sequences change.
A paged cache starts with a pool of fixed-size physical KV blocks. A request's logical block table maps its token positions to blocks in that pool. As processed tokens need more space, the allocator obtains another free block and extends the mapping. Consecutive logical positions can therefore live in noncontiguous physical blocks without changing attention's logical sequence.
The last block may be only partly filled. That unused tail is real capacity overhead even though the request no longer reserves its entire maximum sequence length. Block size trades this waste against mapping and allocation overhead.
Completion releases a request's ownership of its blocks. A block returns to the free list only when no active owner or retention policy still needs it. Shared prefixes may remain for other requests or later reuse, using reference counts to track ownership. Copy-on-write creates private storage before a request changes shared state. These rules prevent one completed request from freeing values another still needs.
Paged KV
Follow allocation and release around the loop. Completion releases a request's ownership; a block returns to the free pool only when no active user or retention policy needs it. Partial final blocks still waste capacity.
When the pool is under pressure, an engine can reject new admission, preempt and later recompute a request, swap retained state to another tier, or evict reusable prefixes. Each choice preserves required state differently and has a different cost. Free and active blocks, churn, partial-block waste, preemption, recomputation, swapping and allocation failures show how the policy behaves over scheduler rounds.
Reserving one contiguous maximum-length buffer per request wastes capacity and makes growth difficult. Paged KV improves flexibility but still has partial-block waste, metadata, eviction, and admission limits.
Priority, eviction, host offload, and attention-window reclamation decide which blocks remain resident; every policy trades capacity, recomputation, transfer, and quality semantics.
Attention-window reclamation discards positions that the model's declared attention rule can no longer read. A sliding-window model can stop needing older positions; ordinary full-context attention cannot discard them merely because memory is tight without changing its outputs.
Practice
Run Lab 27 to follow physical cache blocks through growth, release and reuse; check conserved ownership before discussing capacity.
A request grows through mapped cache blocks. Finishing releases its ownership, but a block is reusable only when active requests and retention rules no longer need its contents.
9. Request scheduling and prompt chunking
Objective
Compare scheduling policies under mixed prompt and decode work.
How it works
Continuous batching, called in-flight batching or iteration-level batching in TensorRT-LLM, updates the group of active requests between model iterations: completed requests leave and new requests can enter instead of waiting for an entire fixed batch to finish. Chunked prefill divides a long prompt into smaller pieces of prompt-processing work that can be scheduled between other work. The two ideas address different scheduling choices and can be combined. Neither means that one autoregressive request generates all of its dependent output tokens at once.
A token budget limits the token work admitted to a scheduling step. Admission decides which waiting work can start; backpressure slows or rejects new work when capacity is exhausted; fairness describes how capacity and waiting time are shared. A long prefill may delay other requests even if it is individually efficient. The lesson examines that trade-off while preserving total token work and separating an abstract scheduler model from a real engine.
Paged key/value (KV) storage helps allocate and reclaim cache capacity as requests enter and leave. The scheduler decides which prefill chunks and decode tokens share each model iteration under a token and capacity budget.
At the end of a model iteration, the scheduler removes completed requests and decides which waiting requests can join the next active batch. It has a token-work budget and a finite amount of KV space. Continuous batching changes membership between iterations so a short request can leave without forcing every request in a fixed batch to finish first.
Continuous batching
Follow one scheduling round downward, then repeat. Admission needs token budget and KV capacity; finished requests leave, making room for new work. Chunked prefill changes how prompt work shares rounds with decode.
Prompt processing and decode compete within that budget. One long prefill can occupy the device while existing requests wait for their next token. Chunked prefill divides the prompt into smaller segments, allowing decode work to be scheduled between them. Smaller chunks can reduce waiting but add scheduling and kernel-launch overhead. They do not remove the prompt tokens or let one request generate dependent output tokens simultaneously.
Continuous batching changes membership at scheduler iterations
Three requests enter at different times. The scheduled mixed batch can include A and B decoding while C is prefilling. In this schematic A and B finish together, then C continues; completed requests release KV blocks. Intervals are illustrative, not measured.
Admission also needs an overload policy. A bounded queue, rejection or backpressure limits what happens when arrivals exceed capacity. Queue arrival, admission, phase-specific scheduled tokens, active requests, free blocks, preemptions and completion connect that policy to observed waiting.
A scheduling comparison must preserve outputs as well as token counts. A deterministic policy-equivalence check can compare matching greedy responses or their exact text digests, hashes of the returned text bytes. A matching digest is a bounded equality check, not proof of stochastic-distribution or task-quality equivalence. Fresh server restarts and counterbalanced A/B order prevent cache, graph or allocator warmth from consistently favoring one configuration. The campaign guides apply those controls to real serving; a scheduler model alone does not establish engine performance.
Prefill-first scheduling can block decode behind one long prompt; decode-first scheduling can starve new requests. Chunking changes head-of-line delay but adds scheduling and kernel-launch overhead.
An overlap scheduler prepares upcoming work on the CPU while already-submitted GPU work runs. Piecewise compilation or graph capture divides model execution into eligible compiled or captured regions and other regions. This partitions the execution graph; chunked prefill partitions prompt-token work. The serving engine must qualify its CUDA Graph capture sizes and its compiled shape ranges or fallback paths separately.
Practice
Compare the scheduling model in Lab 28 with the real-engine policy check in Lab 34. Revisit Lab 18 to separate padding savings from scheduling effects.
Lab 34 fixes batch-invariant execution, TRITON_ATTN, and eager execution for both chunking policies, including their load-generator trials. This holds the numerical execution mode constant while the prompt scheduling changes. Its measurements do not qualify compiled or CUDA Graph serving performance; those execution modes need their own output-equivalence and timing checks.
The scheduler chooses which ready requests run in each iteration. Prompt chunks bound work per turn; admission, cache capacity and completion determine how much useful work can share the next batch.
10. Prefix reuse and cache retention
Objective
Identify reusable prefixes and measure hit benefits without changing request semantics.
How it works
Prefix caching reuses attention state for a beginning token sequence already processed under compatible model and execution settings. A cache hit finds reusable state; a miss requires computation. For example, two requests with identical initial token IDs may reuse part of prefill, but matching visible text alone is insufficient if tokenization or model settings differ. This is reuse of previously computed key/value (KV) state, not returning a previously generated answer.
Reuse identity is the information proving two cache entries mean the same computation. A hash is a compact content fingerprint used for indexing or identity checks. A radix tree organizes sequences by shared prefixes and can help find the longest reusable beginning. Eviction removes retained entries to recover capacity. Longer retention can save more prompt work or reduce room for active requests, so a successful cache policy must balance reuse with storage and isolation.
Cache tiering retains reusable KV state outside its fastest memory tier. High-bandwidth memory (HBM) is device memory used by attention; host dynamic random-access memory (DRAM) and storage can retain inactive state for later restoration. Eviction discards an entry, offload moves or copies it, and restoration brings compatible state back before reuse. A time-to-live (TTL) limits retention; least recently used (LRU) eviction selects the least recently accessed eligible entry under capacity pressure. A TTL is not a guarantee that capacity will retain an entry that long.
Paged KV blocks can outlive or be shared across request prefixes. Prefix caching avoids repeated prefill only when the model’s exact token-level computation is identical.
Greedy decoding selects the largest logit, but different attention shapes can still change floating-point results and the selected token. Lab 20 therefore holds batch-invariant execution and the TRITON_ATTN backend fixed across cache-disabled and cache-enabled runs. It still checks exact response digests before measuring performance; those settings do not replace the equality check or establish model quality.
Find an exact, compatible beginning
A new request first identifies its model/engine artifact, adapter, tokenized template result, position scheme, relevant multimodal inputs and other computation-affecting metadata. Cache lookup then seeks matching token blocks under that identity. Only the common complete prefix is reusable; a changed token invalidates the state derived from that token and its following context.
A match must still have valid retained storage. Shared immutable blocks need reference tracking so an entry is not reclaimed while a request uses it. A miss, expired entry or incompatible identity requires recomputing the affected prefix. Lookup outcome, matched tokens/blocks, miss reason and occupancy explain how much prefill can actually be saved.
Prefix reuse
Read downward only for an exact compatible hit. Reuse skips the matched complete prefix and computes the remaining prompt. A missing, expired or incompatible entry needs recomputation; a slow-tier hit also needs a justified restore.
Locate the retained state
Prefix reuse needs an index from an exact token prefix and its model context to reusable KV state. A hash/block design identifies reusable complete token blocks; a radix tree shares a path of token prefixes and branches where requests diverge. SGLang calls its radix-tree-based reuse approach RadixAttention. These are alternative indexing organizations, not alternatives to computing attention itself. Both require valid ownership, eviction and isolation rules. A similar-looking prompt or a hash without the complete identity contract is insufficient. The supplied prefix experiments use the course's pinned serving path; an SGLang comparison is optional source study, not an installed or qualified engine lab.
Compare restoration with recomputation
A valid device-resident hit can be used without a host or storage restore. A hit in a slower tier must be restored before attention consumes it. Cache value depends on whether a compatible prefix is still present when the next request arrives and whether restoration costs less than recomputing prefill. Account for bytes per token, reused length, transfer bandwidth and startup, cache lookup/reconstruction, write traffic, queueing and active-request headroom. Report device, host and storage hits separately: a slow-tier hit can still be slower than recomputation. Saving prefill does not directly remove decode steps. A larger working set or longer reuse interval may require more retention capacity, but more cache can also create churn, disk writes or resource contention.
Retain only compatible reusable state
Follow the labeled branches from the top. A miss, expired entry or incompatible identity requires recomputation. A valid device-resident hit goes directly to reuse. A host or storage hit is restored only when its complete restoration cost is justified against recomputing prefill. Reuse covers only the matching prefix. Arrows show decisions, not physical storage links; retention and eviction are separate policies.
Cold and warm trials must be independent, preserve output equivalence and expose eviction and admission effects. A warmer inherited cache cannot fairly demonstrate a better policy.
Qualify any direct storage path separately
GPUDirect Storage (GDS) provides supported direct memory access (DMA) paths between storage and GPU memory that can avoid a CPU-memory bounce buffer. GPUDirect RDMA uses remote direct memory access for direct device-memory access by devices such as network adapters; network storage may use RDMA as part of a GDS path, but the two names are not interchangeable. CPU software still coordinates the control path. A cuFile call or a fast read does not itself prove the direct path: filesystem, driver, topology and operation support matter, and compatibility paths can stage through host memory. An optional qualified experiment must independently establish the selected path and compare actual restore latency, write cost and serving quality under the same workload.
Text that looks the same can tokenize differently, and one changed token invalidates all following KV state. Incorrect reuse is a correctness bug; aggressive retention also competes with active-request capacity.
Practice
Begin with Lab 36’s CPU retention model, then test live prefix reuse with Lab 20. Revisit Lab 34 for the same output-equivalence discipline applied to chunked-prefill scheduling. Keep model predictions separate from observed engine behavior.
Prefix caching reuses KV for identical token prefixes under compatible model, adapter, position, and cache settings.
11. Efficient attention execution
Objective
Compare materialized attention and supported fused backends for prefill and decode shapes.
How it works
Scaled dot-product attention (SDPA) is an operation: compare query vectors with key vectors using dot products, scale the scores, apply the allowed-position mask and softmax, then use the resulting weights to mix value vectors. Softmax converts scores into nonnegative weights that sum to one across the considered keys. An attention backend is the concrete implementation that executes this operation. PyTorch's SDPA application programming interface (API) can dispatch—select at runtime—among supported backends based on inputs and configuration.
A straightforward implementation materializes the full score matrix in memory. Tiled or fused implementations process pieces and combine stages to reduce intermediate storage and traffic. FlashAttention is an algorithm family for such memory-efficient attention; SDPA does not mean that FlashAttention was necessarily selected. TensorRT-LLM's XQA names a specialized generation-attention path with its own support conditions. Prefill and decode have different query/cache shapes, so the chosen implementation must be observed for each phase.
The generation and key/value (KV) lessons explain Q queries and stored K/V state; batching and prefix reuse explain which requests share execution. Establish an uncompressed, fixed-dtype attention baseline now, before Lesson 12 changes numerical representation through quantization.
A straightforward attention implementation computes QK scores, writes the full score matrix, reads it for masking and softmax, then combines the resulting weights with V. That intermediate can be large even though it is not part of the final output.
A fused tiled implementation works on pieces of those scores and keeps intermediate fragments on chip. It combines the stages without materializing the entire matrix in high-bandwidth memory (HBM), while preserving the specified attention and causal semantics. The saving comes from intermediate storage and traffic; the model still performs attention over the allowed positions.
Prefill offers many query positions at once, enabling large matrix-like tiles. Decode often has one or a few queries against an increasingly long KV history, making memory traffic and latency more prominent. A backend efficient for one shape need not be efficient or eligible for the other. Dtype, head dimension, grouped-query attention (GQA) layout, mask and dropout/training settings also affect selection.
PyTorch SDPA controls or engine logs and profiler evidence identify which backend actually ran. Kernel names, score/intermediate allocations, shapes and output comparisons establish what changed. Holding tokenizer, scheduler and cache policy fixed keeps an attention improvement attributable to the attention implementation.
Attention-backend selection and CUDA Graph eligibility are separate decisions. A captured graph records GPU operations and their dependencies for replay with fixed shapes and memory addresses. An engine may group supported shapes into capture buckets; a request outside those buckets needs an eligible execution path instead of an incompatible replay. The diagram first separates prefill from decode, then shows backend and graph routing as distinct choices.
Phase-specific attention and CUDA Graph routing
Prefill processes many prompt positions through an SDPA or engine API selecting a supported fused or math backend and writes key-value state. Decode processes one new position per active sequence through a selected decode backend; paged KV is an engine example, not a universal requirement. The scheduler sends stable shape and address buckets to a captured CUDA Graph and unmatched work to a fallback path.
“Flash attention” or SDPA is not one universal kernel. Masks, dtype, head dimension, sequence, GQA layout, dropout/training mode, and software version can select different implementations or fall back.
TensorRT-LLM's XQA is a multi-query attention (MQA)/GQA generation optimization with a limited support matrix and heuristic dispatch, so it must be observed rather than assumed.
Tiling must preserve one softmax normalization across all allowed keys. For each query, maintain a running maximum score, a sum of exponentials relative to that maximum, and the correspondingly weighted value sum. If a new tile raises the maximum, rescale the old sums before adding the new tile's contributions. Divide the accumulated weighted values by the accumulated exponential sum at the end. Keeping these running quantities avoids storing the full score matrix. Independently normalizing each tile and averaging its output would generally give the wrong attention result.
Practice
Run Lab 24 with fixed attention inputs and shapes, then establish the actual selected backend before explaining any measured difference.
Attention backends perform the same specified operation with different storage and execution strategies. Tiling preserves global normalization while avoiding a full score matrix; workload shape and supported inputs determine the suitable implementation.
12. Quantized inference representations
Objective
Compare memory, kernel support, latency, throughput, and output quality for supported quantization paths.
How it works
Quantization represents values using a smaller set of numerical levels, often reducing storage. A scale—and sometimes a zero point mapping real zero into that representation—relates stored values to approximate original values. Dequantization reconstructs those approximations for computation. Calibration uses representative data to choose useful ranges or scales; an outlier is a value unusually large or small relative to most others and can make a shared scale less accurate.
Weight-only quantization changes stored model weights; activation quantization changes intermediate computation values; key/value (KV) quantization changes cached attention state. Notation such as W4A16 means four-bit weights and sixteen-bit activations, while W8A8 means eight-bit weights and activations. Activation-aware Weight Quantization (AWQ) uses activation statistics from calibration inputs to choose weight scaling that protects important channels, meaning selected feature dimensions. GPTQ is a post-training weight-quantization method that uses calibration-derived sensitivity information to compensate for rounding error by adjusting weights not yet quantized. Both use model behavior to limit error, but their calibration and weight-adjustment procedures differ. Quantized storage alone does not prove native low-bit arithmetic: the execution path may unpack or dequantize first. Memory, latency and output quality therefore need separate checks.
The serving ledger separates weights, activations, and KV. Quantization can target each independently, with different scale metadata, kernels, and quality risks.
Quantization first maps values into a smaller set of representable levels. The stored codes need scale metadata and sometimes a zero point to reconstruct their approximate numerical values. The kernel must either consume that representation directly or unpack/dequantize it before computation. Smaller stored weights do not by themselves demonstrate faster arithmetic.
For symmetric per-tensor 8-bit integer (INT8), one positive scale serves the tensor. For nonzero values, choose scale = max(abs(values))/127, encode clamp(round(values/scale), -127, 127), and reconstruct integer*scale. An all-zero tensor needs an explicit positive-scale convention to avoid division by zero. With an illustrative scale of 0.10, 0.26 rounds to code 3 and reconstructs as 0.30. That approximation and the extra scale storage are both part of the representation.
Quantized representation
Read downward from representation to use. A scale and optional offset map values to limited codes. Storage contains both those codes and required metadata. A supported kernel reconstructs values or computes directly with the representation; rounding and clipping must remain within the quality contract.
The state being quantized determines the consequences. Weight quantization changes model storage; per-channel, group or block scales can fit local ranges more closely than one tensor-wide scale. Activation quantization changes intermediate computation and may require calibration or dynamic scales. KV quantization changes cache bytes read and written for each token, adding conversion work and potentially altering long-context attention.
A complete recipe fixes calibration data, excluded layers, metadata, engine support and fallback behavior. Artifact/load size, resident high-bandwidth memory (HBM), peak memory, admitted concurrency, phase latency and task quality can move differently. The same prompts and stopping policy are needed to interpret those changes. The linked mechanics lab explains storage and reconstruction; native low-bit engine performance requires its own qualified path.
Smaller tensors do not guarantee faster requests. Dequantization, calibration, fallback kernels, irregular shapes, or memory-bound phase changes can erase gains; additional capacity may be the primary benefit even when single-request latency is unchanged.
NVIDIA Model Optimizer quantizes models and exports supported representations for deployment frameworks such as TensorRT-LLM. Quantization, export and engine execution are distinct stages. FP8 is a numerical format; activation-aware weight quantization (AWQ) and GPTQ are quantization methods. Supported combinations depend on the selected workflow, and a quantized artifact alone does not prove H100 kernel dispatch or quality.
Practice
Use Lab 29 to compare codes, scales, storage and reconstruction error; keep representation savings distinct from a qualified serving speedup.
Quantization replaces a numerical representation with limited codes plus scale information. Storage savings become a useful optimization only when supported computation and acceptable output quality preserve the full inference contract.
Speculative decoding tries to reduce sequential target-model calls by proposing several tokens cheaply and asking the target model to verify them together. The draft or proposal mechanism supplies candidate tokens; the target is the model whose intended output behavior must be preserved. An accepted prefix is the consecutive beginning of the proposal that passes verification. A rejection requires a defined recovery step before generation continues. Some schemes also obtain a bonus token from the target after all proposed tokens are accepted.
Acceptance rate is the fraction of proposed tokens accepted, but it does not include the cost of producing or checking them. Greedy verification can compare token choices directly; stochastic verification needs a correction rule that preserves the target probability distribution, not just plausible-looking text. Drafting can come from another model or another supported proposal mechanism. This is an execution technique, not permission to replace the target's semantics with a faster model's answers.
After prefill supplies the first output token, ordinary decode uses one target-model forward pass for each subsequent token. Speculation attempts to amortize target calls by verifying several cheaper draft proposals at once without changing the target distribution.
Propose, verify and recover in order
The proposal mechanism drafts k candidate tokens from the current accepted history. The target evaluates their conditional probabilities in a verification pass. The acceptance rule checks a consecutive prefix; accepting a later token cannot repair an earlier rejected context.
Speculative decoding
The draft proposes a sequence, and the target verifies its conditional choices. Accept only a consecutive prefix; at the first rejection, emit the valid recovery token and discard later proposals. Draft, verify and recovery costs all affect the result.
At the first rejection, the algorithm emits a recovery token selected by the appropriate target or corrected sampling rule, discards later draft tokens and resumes from the accepted history. If every proposal is accepted, the algorithm may also supply a target bonus token, subject to the output budget and stopping rules. Greedy equality and stochastic distribution preservation need different acceptance arguments.
Speculative decoding proposal, verification, recovery, and bonus paths
A cheaper proposer drafts several tokens. The target evaluates proposed positions under the selected acceptance rule. Commit the accepted prefix; recover at the first rejection or, if the algorithm allows, sample a bonus after full acceptance. Stochastic acceptance is not simple token equality; stop rules also apply.
Choose a proposal method compatible with the target
Proposal methods vary. A smaller draft model can generate candidate tokens; prompt lookup or n-gram methods reuse matching token sequences without running a separate neural draft. Medusa adds proposal heads to a model. EAGLE-family methods use model features in an auxiliary drafting process rather than simply attaching independent next-token classifiers. Multi-token prediction (MTP) uses model-specific heads or modules trained to propose future tokens. These labels do not establish identical algorithms, supported models or distribution guarantees. The target still needs the appropriate verification and acceptance/recovery procedure. Select a proposal mechanism supported by the pinned engine and model; compare acceptance, extra work, memory and output semantics before interpreting a speedup.
Follow a small rejection example
For the greedy mechanics case, think of the target as a transition function: the current token determines its next-token scores. Check draft tokens in order against the target's greedy choices. For draft [b,c,d], if b matches and c does not, emit b and the target's replacement for c, discard d, and restart drafting from the accepted history. If all draft tokens match and the output budget permits, append the available target bonus token. This preserves the target-only sequence for this illustrative first-order model. A full transformer must condition verification on the complete causal history; the toy transition property is not a general model assumption. Proposed, accepted, rejected, recovery and bonus counts explain the token path; final token IDs and finish reasons check its result. Draft time, verification time and target-call count expose its cost in each workload cell. Measure drafting, verification and recovery together rather than inferring speed from acceptance alone.
Draft generation and verification are not free. Low acceptance, large batches, mismatched tokenizers, or recovery mistakes can make speculation slower or incorrect.
For exact stochastic sampling, let p(x) be the target probability of a proposed token x and q(x) its draft probability at the same accepted history, after the declared sampling transformations. Accept x with probability min(1, p(x)/q(x)). A sampled draft token has q(x) > 0. If rejected, sample a replacement from probabilities proportional to max(p(x) − q(x), 0), then discard later proposals. This correction fills probability mass underrepresented by the draft. For two tokens with target probabilities [0.6, 0.4] and draft probabilities [0.8, 0.2], the first is accepted with probability 0.75 and the second with probability 1. Rejection mass is 0.2 and goes to the second token, recovering target probabilities [0.6, 0.4]. This teaches the exact sampling rule; the supplied greedy mechanics lab does not implement or verify it.
Practice
Use Lab 23 to inspect acceptance, rejection and recovery, then Lab 33 to test greedy equivalence in the separately prepared serving engine.
A draft proposes several tokens; the target scores them together; the algorithm accepts a prefix under its sampling rule and recovers correctly after rejection.
14. Distributed inference placement
Objective
Select placement from model fit, request rate, latency, and communication.
How it works
Serving data parallelism (DP) replicates a complete model and routes independent requests to replicas. Tensor parallelism (TP) divides a model operation's tensors across workers, pipeline parallelism (PP) divides layers into stages, and expert parallelism (EP) places different mixture-of-experts (MoE) components on different workers. In an MoE layer, a router chooses which expert networks process each token. These strategies change whether a request stays within one replica or requires several workers to cooperate.
A collective is group communication, and topology is the actual path connecting the workers' devices. Key/value (KV) ownership describes which worker holds the attention state needed to continue a request. Serving replicas do not average training gradients per request: their model weights are fixed during inference. Partitioning can help a model fit while adding communication on its token-generation path, so parallelism must be understood as a placement decision before it is treated as a performance feature.
Inference placement
The arrows connect a placement choice to its communication and service consequences. Replicas handle independent requests; partitions cooperate within a request. More workers can improve fit while adding latency to token generation.
Scheduling shares one engine instance. Parallelism decides whether to replicate that instance or partition its weights, layers, context, or experts across devices.
Decide whether a request needs one replica or several workers
Serving DP creates complete model replicas and routes independent requests to them. When one model fits per GPU, extra replicas can increase aggregate capacity without splitting each request's model operations. Their weights remain fixed; they do not synchronize training gradients per request.
TP instead splits matrices within a layer. Ranks exchange the output pieces or partial sums needed to continue the same request, adding latency-sensitive collectives to its execution. PP divides layers into stages and transfers activations between them; fill/drain bubbles and the time to traverse the stages matter. EP places different MoE experts on ranks and sends tokens to their selected owners. Request ownership, KV placement and communication follow these assignments.
Serving replicas versus model parallelism
The data-parallel side shows a request router assigning independent requests to two full-model replicas with no per-request cross-rank synchronization. The model-parallel side shows one request traversing two model partitions and adding inter-node communication to its critical path.
Derive the tensor exchange from the calculation
For stored weights shaped [output_features,input_features], a linear layer computes Y = X @ W.T. Column parallelism splits output features, producing different columns of Y that an all-gather concatenates in rank order. Row parallelism splits input features and the corresponding weight columns; each rank produces a partial dot product and all-reduce sums them. For X=[2,3] and one weight row [5,7], the two row-partial results are 10 and 21 and their sum is 31.
Return expert outputs to the original token order
All-to-all sends different token groups to their chosen expert owners. The receiving rank applies its local expert operation and sends results back according to the inverse routing, restoring each token to its original position. Keep split counts, order and reference values explicit. Correct reconstruction and slowest-rank timing are separate requirements: every token must return to its intended position, and the group result is not ready until its slowest required rank finishes. Parallel groups use the trusted private fabric and a controlled readiness endpoint; a loopback client boundary does not expose a public service.
Two-node serving communication by parallelism type
Serving data parallel has two full-model replicas handling independent requests and no mandatory edge between ranks. Tensor parallel uses bidirectional collectives inside layers. Pipeline parallel sends activations forward from early to later layers. Expert parallel dispatches tokens to expert owners and combines results through bidirectional all-to-all traffic.
Training parallelism names are reused in serving but the synchronization contract differs. Serving data parallel replicas do not all-reduce gradients per request, while TP communication lies on every decode token’s latency path.
Context-parallel serving partitions long prefill or decode context with different KV and communication effects. In context-parallel serving, workers own different portions of a request's stored keys and values. A decode query still needs information from every allowed portion, so workers exchange the query or cache blocks and combine properly normalized attention contributions. Splitting cache ownership can increase the context that fits, but adds communication on that request's path; it does not create independent replicas.
Practice
On the fabric cluster, complete Advanced Lab 04 before Labs 23 and 24; trace request and tensor ownership before comparing communication.
Replicas serve independent requests; partitioned workers cooperate on one request. Choose placement from model and cache fit, communication dependencies, request load and latency.
15. Serving workloads and phase separation
Objective
Generate controlled load and explain when prefill/decode disaggregation or KV-aware routing might help.
How it works
AIPerf is a workload-generation and measurement client: it sends controlled requests to an inference endpoint and records service behavior. It is not the model execution engine. Disaggregated serving assigns prefill and decode to separate workers, transferring the request's key/value (KV) state between them. A worker pool is a set of instances assigned a role; a handoff transfers the state and responsibility needed for the next stage. KV-aware routing chooses a worker partly by considering reusable cached prefixes.
NVIDIA Dynamo supplies components for coordinating distributed inference workflows, including routing and disaggregated serving. Rate matching means keeping one stage's service capacity compatible with the work arriving from another. Remote direct memory access (RDMA) lets supported network hardware access registered remote memory without the remote CPU copying each transferred payload. Registration makes a memory region eligible for authorized transfers; setup, permissions and synchronization still matter. RDMA is not supplied automatically by an H100. Separating workers can improve specialization or create a larger transfer and queueing cost. This advanced architecture needs its own qualification beyond a local mechanics lab.
The first AIPerf profile and metric definitions were introduced in Lesson 7, then reused for controlled scheduling experiments. Now combine workload design, concurrency and parallel placement in a broader benchmark; optional disaggregation changes where requests and KV state travel.
Connect client observations to server work
AIPerf sends requests according to a declared workload: endpoint/model identity, input/output distributions, concurrency or arrival rate, warm-up, duration/count, sampling and stops. Its time to first token (TTFT), inter-token latency (ITL)/time per output token (TPOT), completion latency, throughput and errors describe the client boundary. Server queues, scheduled tokens, KV use and preemptions explain which internal work could have produced those observations.
Follow a disaggregated request through its handoff
A prefill worker processes the prompt and produces KV state. The request and required state then move to a decode worker, which cannot continue until transfer and reconstruction finish. The handoff adds work and waiting; phase specialization helps only if its benefit exceeds those costs. Capacity must be compared in prompt-token and output-token units because a rate of prompt completion alone does not describe the amount of decode work arriving.
Disaggregation
Read downward in the direction of the KV handoff: prefill produces state, transfer/reconstruction makes it available, and decode continues the request. Coordination can travel separately in either direction. Added handoff and queueing costs can exceed specialization gains.
KV-aware routing considers both reusable prefixes and active load. A cache-hot worker may still be a poor destination if its queue is long. The first growing queue identifies a rate mismatch worth investigating, whether at prefill, handoff or decode.
Include later model turns in an application measurement
In an agentic tool loop, the model requests a permitted external operation and the application validates and executes it under its own authority. The returned data becomes untrusted input to a later model invocation. Schema and authority checks, tool latency, new tokenization/prefill work and task-success criteria extend the request path beyond one generation call.
Disaggregated prefill, decode, and agentic queues
A request moves through admission, tokenization and prefill, optional KV transfer, decode, and streaming or completion. A validated tool call moves to an authority-controlled tool, and the untrusted result is formatted and tokenized before it re-enters prefill. No tool result bypasses tokenization or prefill to enter decode directly.
Keep benchmark conventions consistent
GenAI-Perf is another NVIDIA generative-model benchmarking client and appears in performance-engineering material. It does not define a separate model-execution phase. This course uses AIPerf as its canonical workload/reporting path; NVIDIA documents differences in input formats, metric names and CLI behavior between them. Do not mix files, percentile definitions or token/chunk boundaries across tools. MLPerf Inference provides standardized workload and quality scenarios for comparable benchmark submissions; an ad hoc course small run is not an MLPerf-compliant result. The goal is to borrow disciplined workload definitions without relabeling unqualified measurements.
A single successful request says nothing about capacity. Disaggregation and cache-aware routing can also add KV transfer, coordination, and queueing that exceed any phase specialization benefit.
Suppose a stable workload admits ten requests per second, each with 1,000 prompt tokens and 100 output tokens. Ignoring prefix reuse and retries, the prefill pool must sustain 10,000 prompt tokens per second and the service must deliver 1,000 output tokens per second. If prefill selects each request’s first output token, as in the workflow taught here, the decode pool must sustain ten times the remaining 99 positions, or 990 continuation positions per second. Equal request counts do not imply equal token-processing rates or equal worker counts. If either pool falls behind its required rate, its queue grows; cache transfer and latency targets add constraints beyond this simple average-rate calculation.
Practice
Revisit local Lab 30 for the engine contract, then use Advanced Labs 32–34 on the fabric cluster for phase separation, cache-aware routing and latency-constrained goodput.
AIPerf describes request distributions and reports client metrics. Disaggregation separates phase workers and introduces transfer, routing, and queueing; KV-aware routing tries to preserve useful cache locality.
16. Evidence-based inference optimization
Objective
Select one measured inference change and defend keep or reject across latency, throughput, capacity, and quality.
How it works
A causal inference report tests whether a specified implementation change caused an improvement under a fixed workload and output-quality contract. The baseline is the reference path and the candidate contains the change. An independent trial starts a fresh run; repeated samples inside one run describe a different level of variation. Counterbalancing alternates variant order to reduce systematic first-run or time-order bias. A rejection criterion states when correctness, comparability or performance evidence is insufficient to keep the change.
An attention microbenchmark measures one bounded operation with fixed tensors. A serving experiment includes the model, cache, scheduler, request arrivals and client-visible completion. A faster attention kernel can have a small or absent effect on service latency if another stage dominates. The required capstone report therefore names its measurement boundary before presenting a result; it does not convert an operator timing into time to first token (TTFT) or service throughput.
The course now supplies phase mechanics, workload distributions, metrics, cache/scheduler controls, quality gates, and live-engine boundaries. The required mechanics capstone connects one profiler observation to a controlled attention-kernel decision. A separate qualified live-engine campaign is needed for a serving decision.
A causal decision begins by naming the boundary being optimized. The required mechanics capstone compares attention implementations on fixed tensors. Its baseline, candidate and correctness reference must perform the same attention calculation. That evidence can support an operator-level decision; it cannot establish client TTFT or serving capacity.
A serving decision requires a separate qualified campaign. Artifact and engine/container identity, tokenizer/template, quantization, the input sequence length (ISL)/output sequence length (OSL) workload mix, sampling/stops, hardware allocation and metric definitions fix the comparison. At least three independent baseline campaigns reveal variation across runs, while throughput plotted against p50/p95 TTFT, inter-token latency (ITL) and completion latency shows the latency cost of increasing load.
A short profile connects an observed delay to one candidate change, such as chunking, cache policy, quantization or placement. Fresh restarts, counterbalanced order and a disconfirming control test whether that change caused the result. Output tokens, finish reasons, errors, queues, scheduled tokens, key/value (KV) occupancy, block churn, preemptions and memory reveal changes that a single throughput number would hide.
The final keep/reject decision must satisfy correctness, quality and capacity gates as well as performance goals. It includes the rejected hypothesis, uncertainty, the limits of the available cluster and the next experiment. A valid rejection or an inconclusive result is useful evidence; a speedup is not required to complete the investigation.
Inference decision evidence
Arrows show evaluation order, not guaranteed improvement. Compare a candidate against fixed workload and output semantics, then check quality, latency, throughput, capacity and failure evidence. Keep only a supported improvement; reject a harmful change or remain inconclusive when evidence is insufficient.
Maximum tokens/s can hide unacceptable TTFT/ITL tails, queue growth, quality drift, or fragile capacity. A causal report must include a rejected hypothesis and the limits of the two-node test.
Practice
Complete Lab 32 with one controlled attention change, correct outputs and separate diagnostic and clean runs. Bound the conclusion to this attention workload.
An inference decision connects artifact identity and decoding equivalence to ISL/OSL/concurrency, TTFT, ITL/TPOT, throughput, memory, failures, and quality.
17. Parallel generation and serving placement
Objective
Distinguish replication from partitioning and explain how placement changes model fit, communication, throughput and request latency.
How it works
Replicas improve aggregate capacity by serving independent requests with complete model copies. Tensor parallelism partitions model operations, introducing communication at each dependent layer or decode step. Pipeline parallelism places stages on different devices and introduces pipeline fill, drain and stage imbalance. The tensor-parallel (TP) degree is the number of cooperating ranks, or processes, in each tensor group; the pipeline-parallel (PP) degree is the number of sequential stages. On two eight-H100 nodes, TP8/PP2 means eight cooperating ranks in each of two stages. Placing one stage per node can keep tensor collectives local while passing activations between nodes. TP16/PP1 means one stage spanning sixteen ranks, so its tensor collectives cross InfiniBand. Neither layout wins universally. The supplied lab isolates replication and tensor partitioning with identical recurrent projection work. It does not implement a language-model server or pipeline parallelism. Comparing the TP/PP layouts above is an optional extension requiring a separately implemented and qualified real-model serving experiment with fixed prompt lengths, output lengths, request count and concurrency. Time to first token (TTFT) measures the interval from the client request to its first output token. In that serving extension, compare successful output-token throughput with TTFT and inter-token latency, not throughput alone. A capacity benefit and a latency benefit are different claims.
Parallel generation and serving placement
Compare three ownership patterns, not three timed stages. Replicas hold complete models and split requests; tensor ranks share each operation; pipeline stages pass intermediate values onward. Combined TP8/PP2 placement has eight ranks per stage and two stages, while useful outputs are counted once.
The linked advanced labs require the separate two-node, sixteen-H100 cluster. Confirm eight full GPUs per worker, healthy NVLink/NVSwitch and active InfiniBand. Capture each rank separately; profiler overhead belongs to diagnostic evidence. Grafana provides measured comparison summaries and job-window context. State what the evidence can establish before choosing the next change.
Consider the lab's 32 synthetic requests and eight projection steps each: useful work is 256 request-steps, regardless of the number of tensor-parallel ranks. The lab reports these modeled steps as tokens; they are not language-model output tokens. Reporting sixteen copies of that count would invent a throughput gain. With replicas, requests partition across ranks; with tensor parallelism, ranks collaborate on the same requests. On small shapes, collective latency can outweigh the saved matrix work. On a model that cannot fit one GPU, partitioning may be necessary even if latency increases. For the optional real-server extension, preserve completed request count, prompt distribution and output length, then inspect p50 and p95 latency alongside output-token throughput. Keep model-startup time separate from warmed serving measurements.
Practice
Use Advanced Lab 25 on the fabric cluster to compare request replication and tensor partitioning in the recurrent projection workload. Count each request-step once, compare batch latency and modeled throughput, and check outputs against the full-weight reference. This lab does not measure client TTFT or inter-token latency.
Replicas serve independent requests; partitions cooperate on each request. Placement trades memory ownership against communication, so capacity and latency must be evaluated separately.
Lab 08: Compare cached attention with full recomputation
Autoregressive generation repeatedly needs keys and values for earlier positions. A KV cache preserves those tensors so each new step can reuse them instead of recomputing the entire prefix.
Complete source: labs/08_kv_cache.py
"""Measure cached decoding and prove that the cache contains keys and values."""
from __future__ import annotations
import argparse
import math
from common import (
add_common_args,
cuda_times_ms,
load_torch,
require_course_gpu,
seed_everything,
summarize_ms,
validate_common_args,
write_result,
)
from course_evidence import annotated_operation
def main() -> None:
parser = argparse.ArgumentParser(description=__doc__)
add_common_args(parser)
parser.set_defaults(warmup=1, iterations=3)
# Read the experiment controls before allocating inputs.
args = parser.parse_args()
validate_common_args(args)
torch = load_torch()
environment = require_course_gpu(torch)
# Keep random inputs repeatable across comparable runs.
seed_everything(torch, args.seed)
with torch.inference_mode():
batch, heads, head_dim = 1, 16, 64
prompt, generated = (256, 64) if args.workload == "small" else (2_048, 256)
hidden = heads * head_dim
qkv = torch.nn.Linear(
hidden, 3 * hidden, bias=False, device="cuda", dtype=torch.bfloat16
)
# Create the synthetic tensors used by this experiment.
values = torch.randn(
(batch, prompt + generated, hidden), device="cuda", dtype=torch.bfloat16
)
def project(tokens: object) -> tuple[object, object, object]:
projected = qkv(tokens).view(batch, tokens.shape[1], 3, heads, head_dim)
query, key, value = projected.unbind(dim=2)
return query.transpose(1, 2), key.transpose(1, 2), value.transpose(1, 2)
def full(prefix_length: int) -> object:
query, key, value = project(values[:, :prefix_length])
return torch.nn.functional.scaled_dot_product_attention(
query, key, value, is_causal=True
)[:, :, -1]
def build_prompt_cache() -> tuple[object, object, object]:
query, key, value = project(values[:, :prompt])
output = torch.nn.functional.scaled_dot_product_attention(
query, key, value, is_causal=True
)[:, :, -1]
return output, key, value
full_prompt = full(prompt)
cached_prompt, key_cache, value_cache = build_prompt_cache()
max_error = float((full_prompt - cached_prompt).abs().max())
if not math.isfinite(max_error) or max_error > 2e-2:
raise SystemExit(
f"Cached and full prompt outputs diverged: {max_error:.6f}"
)
def recompute_decode() -> object:
output = None
for step in range(generated):
output = full(prompt + step + 1)
return output
def cached_decode() -> object:
key = key_cache
value = value_cache
output = None
for step in range(generated):
query, next_key, next_value = project(
values[:, prompt + step : prompt + step + 1]
)
key = torch.cat((key, next_key), dim=2)
value = torch.cat((value, next_value), dim=2)
output = torch.nn.functional.scaled_dot_product_attention(
query, key, value, is_causal=False
)
return output
recomputed_final = recompute_decode()
cached_final = cached_decode().squeeze(2)
decode_error = float((recomputed_final - cached_final).abs().max())
if not math.isfinite(decode_error) or decode_error > 2e-2:
raise SystemExit(
f"Cached and recomputed decode outputs diverged: {decode_error:.6f}"
)
recompute = summarize_ms(
cuda_times_ms(
torch,
recompute_decode,
warmup=args.warmup,
iterations=args.iterations,
)
)
cached = summarize_ms(
cuda_times_ms(
torch,
cached_decode,
warmup=args.warmup,
iterations=args.iterations,
)
)
cache_bytes = 2 * batch * heads * (prompt + generated) * head_dim * 2
# Save the actual measurements together with their correctness checks.
target = write_result(
args,
lab_id="08_kv_cache",
environment=environment,
measurements={
"prompt_tokens": prompt,
"generated_tokens": generated,
"recompute_decode": recompute,
"cached_decode": cached,
"key_value_cache_mib": round(cache_bytes / 2**20, 3),
"prompt_max_absolute_error": round(max_error, 7),
"decode_max_absolute_error": round(decode_error, 7),
},
correctness={
"cached_prompt_matches_full_attention": True,
"cached_decode_matches_recomputation": True,
},
)
print(f"Completed KV-cache experiment: {target}")
if __name__ == "__main__":
annotated_operation(main, "lab_workload")()
# Normal execution
sbatch slurm/08_kv_cache.sbatch --workload small
# Optional profiling
sbatch slurm/08_kv_cache.sbatch --workload small --profiler all
Lab 09: Follow real-model prefill and continuation
The first generated token normally comes from the final-position logits produced by prefill. Subsequent tokens require continuation passes that consume the previously selected token. The two-token example below performs prefill and one continuation pass.
Complete source: labs/09_hf_prefill_decode.py
"""Measure prefill and token-by-token decode with a real Hugging Face model."""
from __future__ import annotations
import argparse
from typing import NamedTuple
from common import (
DEFAULT_MODEL,
DEFAULT_REVISION,
add_common_args,
load_torch,
require_course_gpu,
require_hf_commit_revision,
resolve_int_override,
summarize_ms,
validate_common_args,
write_result,
)
from course_evidence import annotated_operation
class GenerationStep(NamedTuple):
phase: str
input_tokens: int
attention_tokens: int
cache_start: int
def generation_schedule(*, prompt_tokens: int, new_tokens: int) -> list[GenerationStep]:
if prompt_tokens < 1:
raise ValueError("prompt_tokens must be positive")
if new_tokens < 1:
raise ValueError("new_tokens must be positive")
steps = [
GenerationStep(
phase="prefill",
input_tokens=prompt_tokens,
attention_tokens=prompt_tokens,
cache_start=0,
)
]
steps.extend(
GenerationStep(
phase="decode",
input_tokens=1,
attention_tokens=prompt_tokens + generated_index,
cache_start=prompt_tokens + generated_index - 1,
)
for generated_index in range(1, new_tokens)
)
return steps
def main() -> None:
parser = argparse.ArgumentParser(description=__doc__)
add_common_args(parser)
parser.add_argument("--model", default=DEFAULT_MODEL)
parser.add_argument("--revision", default=DEFAULT_REVISION)
parser.add_argument("--new-tokens", type=int, default=None)
# Read the experiment controls before allocating inputs.
args = parser.parse_args()
validate_common_args(args)
require_hf_commit_revision(args.revision)
new_tokens = resolve_int_override(
args.new_tokens,
32 if args.workload == "small" else 128,
option="--new-tokens",
)
torch = load_torch()
environment = require_course_gpu(torch)
try:
from transformers import AutoModelForCausalLM, AutoTokenizer, DynamicCache
except ImportError as exc:
raise SystemExit(
"Activate the pinned inference mechanics environment from "
"requirements-mechanics.txt."
) from exc
tokenizer = AutoTokenizer.from_pretrained(
args.model, revision=args.revision, trust_remote_code=False
)
model = (
AutoModelForCausalLM.from_pretrained(
args.model,
revision=args.revision,
dtype=torch.bfloat16,
attn_implementation="sdpa",
trust_remote_code=False,
)
.to("cuda")
.eval()
)
model_forward = annotated_operation(model, "model_forward")
base_prompt = "Explain in two sentences why GPU benchmarks need warm-up iterations."
prompt = base_prompt if args.workload == "small" else " ".join([base_prompt] * 64)
tokenized = tokenizer(prompt, return_tensors="pt").to("cuda")
prompt_tokens = int(tokenized.input_ids.shape[1])
schedule = generation_schedule(prompt_tokens=prompt_tokens, new_tokens=new_tokens)
prefill_samples: list[float] = []
decode_samples: list[float] = []
def run_request(*, record_timings: bool) -> int:
cache = DynamicCache(config=model.config)
inputs = {
"input_ids": tokenized.input_ids,
"attention_mask": tokenized.attention_mask,
}
generated = []
for step_index, step in enumerate(schedule):
if int(inputs["input_ids"].shape[1]) != step.input_tokens:
raise SystemExit("Generation input length diverged from its schedule.")
if int(inputs["attention_mask"].shape[1]) != step.attention_tokens:
raise SystemExit("Attention-mask length diverged from its schedule.")
cache_position = torch.arange(
step.cache_start,
step.cache_start + step.input_tokens,
dtype=torch.int64,
device="cuda",
)
start = torch.cuda.Event(enable_timing=True) if record_timings else None
end = torch.cuda.Event(enable_timing=True) if record_timings else None
if start is not None:
start.record()
output = model_forward(
**inputs,
cache_position=cache_position,
past_key_values=cache,
use_cache=True,
)
if end is not None:
end.record()
end.synchronize()
sample = float(start.elapsed_time(end))
if step.phase == "prefill":
prefill_samples.append(sample)
else:
decode_samples.append(sample)
cache = output.past_key_values
if cache is None or not hasattr(cache, "get_seq_length"):
raise SystemExit("The model did not return a supported cache object.")
expected_cache_tokens = step.cache_start + step.input_tokens
if int(cache.get_seq_length()) != expected_cache_tokens:
raise SystemExit("Cache length diverged from the generation schedule.")
next_token = output.logits[:, -1:].argmax(dim=-1)
generated.append(next_token)
if step_index + 1 < len(schedule):
attention_mask = torch.cat(
[
inputs["attention_mask"],
inputs["attention_mask"].new_ones(
(inputs["attention_mask"].shape[0], 1)
),
],
dim=-1,
)
inputs = {
"input_ids": next_token,
"attention_mask": attention_mask,
}
generated_ids = torch.cat(generated, dim=-1)
return int(generated_ids.shape[1])
with torch.inference_mode():
for _ in range(args.warmup):
run_request(record_timings=False)
# Wait for queued GPU work to finish at this measurement boundary.
torch.cuda.synchronize()
generated_token_counts = []
for _ in range(args.iterations):
generated_token_counts.append(run_request(record_timings=True))
generated_requested_token_count = all(
count == new_tokens for count in generated_token_counts
)
if not generated_requested_token_count:
raise SystemExit("Generated token count diverged from --new-tokens.")
# Save the actual measurements together with their correctness checks.
target = write_result(
args,
lab_id="09_hf_prefill_decode",
environment=environment,
measurements={
"model": args.model,
"revision": args.revision,
"prompt_tokens": prompt_tokens,
"requested_new_tokens_per_request": new_tokens,
"generated_new_tokens_per_request": new_tokens,
"decode_steps_per_request": new_tokens - 1,
"total_generated_tokens": sum(generated_token_counts),
"output_shape": [int(tokenized.input_ids.shape[0]), new_tokens],
"requests": args.iterations,
"prefill_timing": summarize_ms(prefill_samples),
"decode_timing": (summarize_ms(decode_samples) if decode_samples else None),
},
correctness={
"generated_requested_token_count": True,
"attention_mask_advanced": True,
"cache_position_advanced": True,
"cache_length_advanced": True,
},
)
print(f"Completed prefill/decode measurement: {target}")
if __name__ == "__main__":
annotated_operation(main, "lab_workload")()
# Normal execution
sbatch slurm/09_hf_prefill_decode.sbatch --workload small --new-tokens 2
# Optional profiling
sbatch slurm/09_hf_prefill_decode.sbatch --workload small --new-tokens 2 --profiler all
Lab 10: Measure batched offline generation with vLLM
Offline inference submits a known collection of prompts to an engine without exposing an HTTP service. This lab runs real vLLM generation in the prepared native runtime and accounts for all measured requests and output tokens.
Complete source: labs/10_vllm_offline.py
"""Run batched offline generation inside the pinned vLLM engine container."""
from __future__ import annotations
import argparse
import os
import statistics
import time
from common import (
DEFAULT_MODEL,
DEFAULT_REVISION,
add_common_args,
load_torch,
require_course_gpu,
require_hf_commit_revision,
validate_common_args,
write_result,
)
from course_evidence import annotated_operation
def aggregate_outputs(outputs: list[object], *, max_tokens: int) -> dict[str, object]:
prompt_token_counts = []
output_token_counts = []
finish_reasons = []
for output in outputs:
prompt_token_ids = output.prompt_token_ids
if prompt_token_ids is None or not prompt_token_ids:
raise ValueError("Every request must expose a positive prompt token count.")
if len(output.outputs) != 1:
raise ValueError("Every request must contain exactly one completion.")
completion = output.outputs[0]
output_tokens = len(completion.token_ids)
if output_tokens < 1 or output_tokens > max_tokens:
raise ValueError(
"Every request must contain a positive bounded output token count."
)
prompt_token_counts.append(len(prompt_token_ids))
output_token_counts.append(output_tokens)
finish_reasons.append(completion.finish_reason)
return {
"request_count": len(outputs),
"prompt_tokens_total": sum(prompt_token_counts),
"output_tokens_total": sum(output_token_counts),
"prompt_tokens_per_request": prompt_token_counts,
"output_tokens_per_request": output_token_counts,
"finish_reasons": finish_reasons,
}
def summarize_counts(values: list[int]) -> dict[str, int | float]:
return {
"min": min(values),
"median": statistics.median(values),
"max": max(values),
}
def main() -> None:
parser = argparse.ArgumentParser(description=__doc__)
add_common_args(parser)
parser.add_argument("--model", default=DEFAULT_MODEL)
parser.add_argument("--revision", default=DEFAULT_REVISION)
parser.add_argument("--max-model-len", type=int, default=2_048)
parser.add_argument("--enforce-eager", action="store_true")
parser.add_argument(
"--in-process",
action="store_true",
help="Keep the single-GPU engine in this process for NVTX-scoped diagnostics.",
)
# Read the experiment controls before allocating inputs.
args = parser.parse_args()
validate_common_args(args)
require_hf_commit_revision(args.revision)
if os.environ.get("COURSE_CAPTURE") == "1" and not args.in_process:
raise SystemExit(
"Offline vLLM capture requires --in-process so the selected NVTX range "
"contains GPU launches; retain the default process mode for clean timing."
)
if args.in_process:
# vLLM reads this setting when constructing the engine. Parent NVTX# ranges do not propagate into the default EngineCore child process.
os.environ["VLLM_ENABLE_V1_MULTIPROCESSING"] = "0"
torch = load_torch()
environment = require_course_gpu(torch)
try:
from vllm import LLM, SamplingParams
except ImportError as exc:
raise SystemExit(
"Run this lab with slurm/vllm_offline.sbatch and a qualified vLLM image digest."
) from exc
base_prompts = [
"Explain why CUDA events are useful for timing GPU kernels.",
"Name one symptom of a memory-bound GPU workload.",
"Explain the difference between LLM prefill and decode.",
"Why should inference benchmarks report latency percentiles?",
]
copies = 1 if args.workload == "small" else 4
prompts = [
f"{prompt} Example request {index}."
for index, prompt in enumerate(base_prompts * copies, start=1)
]
engine = LLM(
model=args.model,
revision=args.revision,
tokenizer_revision=args.revision,
dtype="bfloat16",
max_model_len=args.max_model_len,
gpu_memory_utilization=0.80,
trust_remote_code=False,
enforce_eager=args.enforce_eager,
)
max_tokens = 64
sampling = SamplingParams(temperature=0.0, max_tokens=max_tokens)
for _ in range(args.warmup):
engine.generate(prompts, sampling)
measured_generate = annotated_operation(engine.generate, "vllm_generate")
elapsed = 0.0
prompt_token_counts: list[int] = []
output_token_counts: list[int] = []
finish_reasons: list[str | None] = []
for _ in range(args.iterations):
started = time.perf_counter()
outputs = measured_generate(prompts, sampling)
elapsed += time.perf_counter() - started
if len(outputs) != len(prompts):
raise SystemExit(
"vLLM returned a different number of results than prompts."
)
try:
aggregate = aggregate_outputs(outputs, max_tokens=max_tokens)
except ValueError as exc:
raise SystemExit(str(exc)) from exc
prompt_token_counts.extend(aggregate["prompt_tokens_per_request"])
output_token_counts.extend(aggregate["output_tokens_per_request"])
finish_reasons.extend(aggregate["finish_reasons"])
requests = len(prompts) * args.iterations
prompt_tokens_total = sum(prompt_token_counts)
output_tokens_total = sum(output_token_counts)
# Save the actual measurements together with their correctness checks.
target = write_result(
args,
lab_id="10_vllm_offline",
environment=environment,
measurements={
"model": args.model,
"revision": args.revision,
"requests": requests,
"prompt_tokens_total": prompt_tokens_total,
"output_tokens_total": output_tokens_total,
"prompt_tokens_per_request": summarize_counts(prompt_token_counts),
"output_tokens_per_request": summarize_counts(output_token_counts),
"finish_reasons": finish_reasons,
"elapsed_seconds": round(elapsed, 4),
"output_tokens_per_second": round(output_tokens_total / elapsed, 2),
},
correctness={
"one_output_per_prompt": True,
"one_completion_per_request": True,
"positive_prompt_token_counts": prompt_tokens_total > 0,
"bounded_positive_output_token_counts": output_tokens_total > 0,
"all_iterations_completed": len(output_token_counts) == requests,
},
)
print(f"Completed vLLM offline inference: {target}")
if __name__ == "__main__":
annotated_operation(main, "lab_workload")()
# Normal execution
sbatch slurm/10_vllm_offline.sbatch --workload small
# Optional profiling
sbatch slurm/10_vllm_offline.sbatch --workload small --profiler all
Lab 11: Measure concurrent completion requests
A serving system's performance includes request handling and completion delivery, not just GPU kernels. This lab sends bounded concurrent requests to a local OpenAI-compatible endpoint and measures the entire client campaign.
Complete source: labs/11_serving_client.py
"""Benchmark a local OpenAI-compatible completion endpoint with concurrent requests."""
from __future__ import annotations
import argparse
import json
import math
import statistics
import time
import urllib.parse
import urllib.request
from concurrent.futures import ThreadPoolExecutor
from pathlib import Path
from common import require_hf_commit_revision, resolve_run_id, write_json_exclusive
from course_evidence import begin_experiment
DEFAULT_REVISION = "7ae557604adf67be50417f59c2c2f167def9a775"
def main() -> None:
parser = argparse.ArgumentParser(description=__doc__)
parser.add_argument("--base-url", default="http://127.0.0.1:8000")
parser.add_argument("--model", default="Qwen/Qwen2.5-0.5B-Instruct")
parser.add_argument("--revision", default=DEFAULT_REVISION)
parser.add_argument("--requests", type=int, default=16)
parser.add_argument("--concurrency", type=int, default=4)
parser.add_argument("--output", type=Path, default=None)
# Read the experiment controls before allocating inputs.
args = parser.parse_args()
begin_experiment(args)
require_hf_commit_revision(args.revision)
parsed = urllib.parse.urlparse(args.base_url)
if parsed.scheme != "http" or parsed.hostname not in {
"127.0.0.1",
"localhost",
"::1",
}:
raise SystemExit(
"For safety this teaching client only connects to a loopback HTTP endpoint."
)
if args.requests < 1 or args.concurrency < 1:
raise SystemExit("--requests and --concurrency must be positive")
run_id = resolve_run_id()
endpoint = args.base_url.rstrip("/") + "/v1/completions"
def send(index: int) -> tuple[float, int]:
payload = json.dumps(
{
"model": args.model,
"prompt": f"Request {index}: explain one GPU benchmarking rule in one sentence.",
"max_tokens": 32,
"temperature": 0,
}
).encode()
request = urllib.request.Request(
endpoint,
data=payload,
headers={"Content-Type": "application/json"},
method="POST",
)
started = time.perf_counter()
with urllib.request.urlopen(request, timeout=120) as response:
body = json.loads(response.read())
latency = time.perf_counter() - started
return latency, int(body.get("usage", {}).get("completion_tokens", 0))
wall_started = time.perf_counter()
with ThreadPoolExecutor(max_workers=args.concurrency) as executor:
results = list(executor.map(send, range(args.requests)))
wall_seconds = time.perf_counter() - wall_started
latencies = sorted(latency for latency, _ in results)
completion_tokens = sum(tokens for _, tokens in results)
all_responses_nonempty = all(tokens > 0 for _, tokens in results)
if len(results) != args.requests or not all_responses_nonempty:
raise SystemExit("At least one serving response had no generated tokens.")
p90 = latencies[max(0, math.ceil(0.9 * len(latencies)) - 1)]
payload = {
"schema": "gpu-course-result/v1",
"lab_id": "11_serving_client",
"run_id": run_id,
"measurements": {
"model": args.model,
"revision": args.revision,
"requests": args.requests,
"concurrency": args.concurrency,
"median_e2e_ms": round(statistics.median(latencies) * 1_000, 3),
"p90_e2e_ms": round(p90 * 1_000, 3),
"request_throughput_per_second": round(args.requests / wall_seconds, 3),
"output_tokens_per_second": round(completion_tokens / wall_seconds, 3),
},
"correctness": {
"all_requests_completed": True,
"all_responses_nonempty": True,
},
}
output = args.output or Path(f"results/11_serving_client-run-{run_id}.json")
# Write this run’s evidence without overwriting an earlier result.
write_json_exclusive(output, payload)
print(f"Completed local serving benchmark: {output}")
if __name__ == "__main__":
main()
# Normal execution
sbatch slurm/11_serving_client.sbatch --workload small
# Optional profiling
sbatch slurm/11_serving_client.sbatch --workload small --profiler all
Lab 15: Observe first content and streaming gaps
Users experience streamed generation as a wait for first content followed by a sequence of arrivals. This lab records those client-side events from a loopback service.
Complete source: labs/15_streaming_client.py
"""Measure TTFT, inter-chunk gaps, and E2E latency from a loopback stream."""
from __future__ import annotations
import argparse
import json
import math
import statistics
import time
import urllib.parse
import urllib.request
from concurrent.futures import ThreadPoolExecutor
from pathlib import Path
from common import require_hf_commit_revision, resolve_run_id, write_json_exclusive
from course_evidence import begin_experiment
DEFAULT_REVISION = "7ae557604adf67be50417f59c2c2f167def9a775"
def percentile(values: list[float], fraction: float) -> float:
ordered = sorted(values)
return ordered[max(0, math.ceil(fraction * len(ordered)) - 1)]
def main() -> None:
parser = argparse.ArgumentParser(description=__doc__)
parser.add_argument("--base-url", default="http://127.0.0.1:8000")
parser.add_argument("--model", default="Qwen/Qwen2.5-0.5B-Instruct")
parser.add_argument("--revision", default=DEFAULT_REVISION)
parser.add_argument("--requests", type=int, default=8)
parser.add_argument("--concurrency", type=int, default=2)
parser.add_argument("--output", type=Path, default=None)
# Read the experiment controls before allocating inputs.
args = parser.parse_args()
begin_experiment(args)
require_hf_commit_revision(args.revision)
parsed = urllib.parse.urlparse(args.base_url)
if parsed.scheme != "http" or parsed.hostname not in {
"127.0.0.1",
"localhost",
"::1",
}:
raise SystemExit("This teaching client only connects to loopback HTTP.")
if args.requests < 1 or args.concurrency < 1:
raise SystemExit("--requests and --concurrency must be positive")
run_id = resolve_run_id()
endpoint = args.base_url.rstrip("/") + "/v1/completions"
def send(index: int) -> dict[str, object]:
payload = json.dumps(
{
"model": args.model,
"prompt": f"Request {index}: give two rules for a valid GPU benchmark.",
"max_tokens": 48,
"temperature": 0,
"stream": True,
}
).encode()
request = urllib.request.Request(
endpoint,
data=payload,
headers={"Content-Type": "application/json"},
method="POST",
)
started = time.perf_counter()
first_content = None
prior_content = None
gaps = []
characters = 0
completed = False
with urllib.request.urlopen(request, timeout=120) as response:
for raw_line in response:
line = raw_line.decode("utf-8").strip()
if not line.startswith("data:"):
continue
data = line[5:].strip()
if data == "[DONE]":
completed = True
break
chunk = json.loads(data)
if "error" in chunk:
raise RuntimeError("The stream reported an engine error.")
text = chunk.get("choices", [{}])[0].get("text", "")
if not text:
continue
now = time.perf_counter()
if first_content is None:
first_content = now
if prior_content is not None:
gaps.append(now - prior_content)
prior_content = now
characters += len(text)
finished = time.perf_counter()
if not completed:
raise RuntimeError("The stream ended before its completion marker.")
if first_content is None:
raise RuntimeError("The stream completed without a content chunk.")
return {
"ttft_s": first_content - started,
"e2e_s": finished - started,
"inter_chunk_gaps_s": gaps,
"characters": characters,
}
wall_started = time.perf_counter()
with ThreadPoolExecutor(max_workers=args.concurrency) as executor:
results = list(executor.map(send, range(args.requests)))
wall_seconds = time.perf_counter() - wall_started
ttft = [float(result["ttft_s"]) for result in results]
e2e = [float(result["e2e_s"]) for result in results]
gaps = [float(gap) for result in results for gap in result["inter_chunk_gaps_s"]]
payload = {
"schema": "gpu-course-result/v1",
"lab_id": "15_streaming_client",
"run_id": run_id,
"measurements": {
"model": args.model,
"revision": args.revision,
"requests": args.requests,
"concurrency": args.concurrency,
"median_ttft_ms": round(statistics.median(ttft) * 1_000, 3),
"p90_ttft_ms": round(percentile(ttft, 0.9) * 1_000, 3),
"median_e2e_ms": round(statistics.median(e2e) * 1_000, 3),
"p90_e2e_ms": round(percentile(e2e, 0.9) * 1_000, 3),
"median_inter_chunk_gap_ms": (
round(statistics.median(gaps) * 1_000, 3) if gaps else None
),
"request_throughput_per_second": round(args.requests / wall_seconds, 3),
"received_characters": sum(int(result["characters"]) for result in results),
},
"correctness": {
"all_streams_produced_content": len(results) == args.requests,
"note": "An HTTP chunk is not guaranteed to equal one model token.",
},
}
output = args.output or Path(f"results/15_streaming_client-run-{run_id}.json")
# Write this run’s evidence without overwriting an earlier result.
write_json_exclusive(output, payload)
print(f"Completed streaming benchmark: {output}")
if __name__ == "__main__":
main()
# Normal execution
sbatch slurm/15_streaming_client.sbatch --workload small
# Optional profiling
sbatch slurm/15_streaming_client.sbatch --workload small --profiler all
Lab 16: Audit model, tokenizer, configuration, and license identity
A model name alone does not fully identify an inference workload. Weights, tokenizer, configuration, generation settings, and code-loading policy can all affect behavior.
Complete source: labs/16_model_artifact_audit.py
"""Audit a pinned public model's artifacts, config, tokenizer, and license."""
from __future__ import annotations
import argparse
from typing import Any
from common import (
DEFAULT_MODEL,
DEFAULT_REVISION,
add_common_args,
load_torch,
require_course_gpu,
require_hf_commit_revision,
validate_common_args,
write_result,
)
def main() -> None:
parser = argparse.ArgumentParser(description=__doc__)
add_common_args(parser, include_measurement=False)
parser.add_argument("--model", default=DEFAULT_MODEL)
parser.add_argument("--revision", default=DEFAULT_REVISION)
# Read the experiment controls before allocating inputs.
args = parser.parse_args()
validate_common_args(args)
require_hf_commit_revision(args.revision)
torch = load_torch()
environment = require_course_gpu(torch)
try:
from huggingface_hub import HfApi
from transformers import AutoConfig, AutoTokenizer, GenerationConfig
except ImportError as exc:
raise SystemExit(
"Activate the pinned inference mechanics environment from "
"requirements-mechanics.txt."
) from exc
try:
info = HfApi().model_info(
args.model,
revision=args.revision,
files_metadata=False,
)
config = AutoConfig.from_pretrained(
args.model,
revision=args.revision,
trust_remote_code=False,
)
tokenizer = AutoTokenizer.from_pretrained(
args.model,
revision=args.revision,
trust_remote_code=False,
)
generation_config = GenerationConfig.from_pretrained(
args.model,
revision=args.revision,
)
except Exception as exc:
raise SystemExit(
"The pinned model metadata must be reachable on the Hub; "
"this audit requires online HfApi access even when artifacts are cached."
) from exc
files = sorted(sibling.rfilename for sibling in info.siblings)
weight_files = [name for name in files if name.endswith(".safetensors")]
index_files = [name for name in files if name.endswith(".index.json")]
card_data: Any = info.card_data
license_id = getattr(card_data, "license", None) if card_data else None
pinned_revision_matches = info.sha == args.revision
expected_artifacts = all(
any(name == expected for name in files)
for expected in ("config.json", "tokenizer.json", "README.md")
)
safe_loading_policy = not bool(getattr(config, "auto_map", None))
if not pinned_revision_matches or not expected_artifacts or not weight_files:
raise SystemExit("The pinned model artifact contract was not satisfied.")
# Save the actual measurements together with their correctness checks.
target = write_result(
args,
lab_id="16_model_artifact_audit",
environment=environment,
measurements={
"model": args.model,
"revision": args.revision,
"resolved_commit": info.sha,
"model_type": getattr(config, "model_type", None),
"hidden_size": getattr(config, "hidden_size", None),
"layers": getattr(config, "num_hidden_layers", None),
"attention_heads": getattr(config, "num_attention_heads", None),
"key_value_heads": getattr(config, "num_key_value_heads", None),
"maximum_positions": getattr(config, "max_position_embeddings", None),
"rope_theta": getattr(config, "rope_theta", None),
"rope_scaling": getattr(config, "rope_scaling", None),
"config_vocab_size": getattr(config, "vocab_size", None),
"tokenizer_vocab_size": tokenizer.vocab_size,
"tokenizer_class": tokenizer.__class__.__name__,
"has_chat_template": bool(tokenizer.chat_template),
"generation_max_length": generation_config.max_length,
"generation_eos_token_id": generation_config.eos_token_id,
"weight_files": weight_files,
"weight_index_files": index_files,
"license_identifier": license_id,
"remote_model_code_declared": bool(getattr(config, "auto_map", None)),
},
correctness={
"pinned_revision_matches": pinned_revision_matches,
"expected_artifacts_present": expected_artifacts,
"safetensors_weights_present": bool(weight_files),
"remote_code_was_not_enabled": True,
"model_uses_standard_transformers_code": safe_loading_policy,
"license_metadata_was_inspected": True,
},
)
print(f"Completed model-artifact audit: {target}")
if __name__ == "__main__":
main()
Teaching diagramVerify every model artifact before loading
Model card and license, configuration and generation defaults, tokenizer and template, weights and index, and optional adapters or quantization metadata all enter one verify-and-pin gate before CPU staging, GPU materialization, warm-up, readiness, and request serving.
# Normal execution
sbatch slurm/16_model_artifact_audit.sbatch --workload small
# Optional profiling
sbatch slurm/16_model_artifact_audit.sbatch --workload small --profiler all
Lab 17: Compare greedy and seeded stochastic generation
Generation settings change both output behavior and the amount of work performed, so a performance comparison must declare them. This lab compares greedy decoding with a seeded stochastic profile on a pinned model.
Complete source: labs/17_sampling_semantics.py
"""Compare greedy and seeded stochastic generation under fixed token budgets."""
from __future__ import annotations
import argparse
import time
from typing import Any
from common import (
DEFAULT_MODEL,
DEFAULT_REVISION,
add_common_args,
load_torch,
require_course_gpu,
require_hf_commit_revision,
seed_everything,
validate_common_args,
write_result,
)
from course_evidence import annotated_operation
def main() -> None:
parser = argparse.ArgumentParser(description=__doc__)
add_common_args(parser)
parser.add_argument("--model", default=DEFAULT_MODEL)
parser.add_argument("--revision", default=DEFAULT_REVISION)
parser.add_argument("--max-new-tokens", type=int, default=32)
# Read the experiment controls before allocating inputs.
args = parser.parse_args()
validate_common_args(args)
require_hf_commit_revision(args.revision)
if args.max_new_tokens < 1:
raise SystemExit("--max-new-tokens must be positive")
torch = load_torch()
environment = require_course_gpu(torch)
# Keep random inputs repeatable across comparable runs.
seed_everything(torch, args.seed)
try:
from transformers import AutoModelForCausalLM, AutoTokenizer
except ImportError as exc:
raise SystemExit(
"Activate the pinned inference mechanics environment from "
"requirements-mechanics.txt."
) from exc
tokenizer = AutoTokenizer.from_pretrained(
args.model,
revision=args.revision,
trust_remote_code=False,
)
model = (
AutoModelForCausalLM.from_pretrained(
args.model,
revision=args.revision,
dtype=torch.bfloat16,
attn_implementation="sdpa",
trust_remote_code=False,
)
.to("cuda")
.eval()
)
encoded = tokenizer(
"Explain one reason to record output-token counts in a benchmark.",
return_tensors="pt",
).to("cuda")
prompt_tokens = int(encoded.input_ids.shape[1])
generate_model = annotated_operation(model.generate, "generation")
def generate(**settings: Any) -> tuple[list[int], float]:
# Wait for queued GPU work to finish at this measurement boundary.
torch.cuda.synchronize()
started = time.perf_counter()
with torch.inference_mode():
output = generate_model(
**encoded,
max_new_tokens=args.max_new_tokens,
pad_token_id=tokenizer.eos_token_id,
**settings,
)
torch.cuda.synchronize()
return output[0, prompt_tokens:].tolist(), time.perf_counter() - started
for _ in range(args.warmup):
generate(do_sample=False)
greedy_a, greedy_seconds = generate(do_sample=False)
greedy_b, _ = generate(do_sample=False)
seed_everything(torch, args.seed)
sampled_a, sampled_seconds = generate(
do_sample=True,
temperature=0.7,
top_k=40,
top_p=0.9,
)
seed_everything(torch, args.seed)
sampled_b, _ = generate(
do_sample=True,
temperature=0.7,
top_k=40,
top_p=0.9,
)
greedy_repeatable = greedy_a == greedy_b
seeded_sampling_repeatable = sampled_a == sampled_b
nonempty = bool(greedy_a and sampled_a)
if not (greedy_repeatable and seeded_sampling_repeatable and nonempty):
raise SystemExit("Generation repeatability or non-empty output gate failed.")
# Save the actual measurements together with their correctness checks.
target = write_result(
args,
lab_id="17_sampling_semantics",
environment=environment,
measurements={
"model": args.model,
"revision": args.revision,
"prompt_tokens": prompt_tokens,
"maximum_new_tokens": args.max_new_tokens,
"greedy_output_tokens": len(greedy_a),
"seeded_sample_output_tokens": len(sampled_a),
"greedy_seconds": round(greedy_seconds, 4),
"seeded_sample_seconds": round(sampled_seconds, 4),
"greedy_token_ids": greedy_a,
"seeded_sample_token_ids": sampled_a,
},
correctness={
"greedy_repeatable": greedy_repeatable,
"seeded_sampling_repeatable": seeded_sampling_repeatable,
"both_outputs_nonempty": nonempty,
},
)
print(f"Completed sampling-semantics experiment: {target}")
if __name__ == "__main__":
annotated_operation(main, "lab_workload")()
# Normal execution
sbatch slurm/17_sampling_semantics.sbatch --workload small --max-new-tokens 32
# Optional profiling
sbatch slurm/17_sampling_semantics.sbatch --workload small --max-new-tokens 32 --profiler all
Lab 18: Reduce padded prefill work with length buckets
A single batch rectangle can waste substantial work when one prompt is much longer than the others. This lab compares one padded prefill batch with two length buckets containing the same prompts.
Complete source: labs/18_padding_bucketing.py
"""Compare one padded prefill batch with length-bucketed equivalent prompts."""
from __future__ import annotations
import argparse
import math
from common import (
DEFAULT_MODEL,
DEFAULT_REVISION,
add_common_args,
cuda_times_ms,
load_torch,
require_course_gpu,
require_hf_commit_revision,
seed_everything,
summarize_ms,
validate_common_args,
write_result,
)
from course_evidence import annotated_operation
def validate_last_token_logits(
torch: object,
padded_logits: object,
bucket_last_logits: dict[int, object],
lengths: list[int],
) -> float:
"""Check every prompt before aggregating the last-token relative error."""
errors = []
for index, length in enumerate(lengths):
padded_last = padded_logits[index, length - 1].float()
bucket_last = bucket_last_logits[index].float()
if not bool(
torch.isfinite(padded_last).all() and torch.isfinite(bucket_last).all()
):
raise SystemExit(f"Prompt {index} logits must be finite.")
numerator = torch.linalg.vector_norm(padded_last - bucket_last)
denominator = torch.linalg.vector_norm(padded_last).clamp_min(1e-12)
if not bool(torch.isfinite(numerator) and torch.isfinite(denominator)):
raise SystemExit(f"Prompt {index} logit norms must be finite.")
error = float((numerator / denominator).item())
if not math.isfinite(error) or error > 0.02:
raise SystemExit(
f"Equivalent prompt {index} logits diverged: relative L2={error}"
)
errors.append(error)
return max(errors)
def main() -> None:
parser = argparse.ArgumentParser(description=__doc__)
add_common_args(parser)
parser.add_argument("--model", default=DEFAULT_MODEL)
parser.add_argument("--revision", default=DEFAULT_REVISION)
# Read the experiment controls before allocating inputs.
args = parser.parse_args()
validate_common_args(args)
require_hf_commit_revision(args.revision)
torch = load_torch()
environment = require_course_gpu(torch)
# Keep random inputs repeatable across comparable runs.
seed_everything(torch, args.seed)
try:
from transformers import AutoModelForCausalLM, AutoTokenizer
except ImportError as exc:
raise SystemExit(
"Activate the pinned inference mechanics environment from "
"requirements-mechanics.txt."
) from exc
tokenizer = AutoTokenizer.from_pretrained(
args.model,
revision=args.revision,
trust_remote_code=False,
)
tokenizer.padding_side = "right"
model = (
AutoModelForCausalLM.from_pretrained(
args.model,
revision=args.revision,
dtype=torch.bfloat16,
attn_implementation="sdpa",
trust_remote_code=False,
)
.to("cuda")
.eval()
)
base = "Explain why equivalent GPU benchmarks preserve token counts."
repeats = (1, 4, 12, 32) if args.workload == "small" else (8, 32, 96, 192)
prompts = [" ".join([base] * repeat) for repeat in repeats]
lengths = [
len(tokenizer(prompt, add_special_tokens=True).input_ids) for prompt in prompts
]
padded = tokenizer(prompts, padding=True, return_tensors="pt").to("cuda")
order = sorted(range(len(prompts)), key=lengths.__getitem__)
buckets = (order[:2], order[2:])
bucket_inputs = [
tokenizer(
[prompts[index] for index in bucket],
padding=True,
return_tensors="pt",
).to("cuda")
for bucket in buckets
]
def padded_prefill() -> None:
with torch.inference_mode():
model(**padded, use_cache=False)
def bucketed_prefill() -> None:
with torch.inference_mode():
for inputs in bucket_inputs:
model(**inputs, use_cache=False)
padded_samples = cuda_times_ms(
torch,
padded_prefill,
warmup=args.warmup,
iterations=args.iterations,
)
bucket_samples = cuda_times_ms(
torch,
bucketed_prefill,
warmup=args.warmup,
iterations=args.iterations,
)
with torch.inference_mode():
padded_logits = model(**padded, use_cache=False).logits
bucket_last_logits: dict[int, object] = {}
for bucket, inputs in zip(buckets, bucket_inputs, strict=True):
logits = model(**inputs, use_cache=False).logits
local_lengths = inputs.attention_mask.sum(dim=1)
for local_index, original_index in enumerate(bucket):
bucket_last_logits[original_index] = logits[
local_index, int(local_lengths[local_index].item()) - 1
]
max_relative_l2 = validate_last_token_logits(
torch, padded_logits, bucket_last_logits, lengths
)
true_tokens = sum(lengths)
padded_tokens = int(padded.input_ids.numel())
bucket_tokens = sum(int(inputs.input_ids.numel()) for inputs in bucket_inputs)
# Save the actual measurements together with their correctness checks.
target = write_result(
args,
lab_id="18_padding_bucketing",
environment=environment,
measurements={
"model": args.model,
"revision": args.revision,
"prompt_token_lengths": lengths,
"true_prompt_tokens": true_tokens,
"single_padded_rectangle_tokens": padded_tokens,
"bucketed_rectangle_tokens": bucket_tokens,
"single_batch_padding_tokens": padded_tokens - true_tokens,
"bucketed_padding_tokens": bucket_tokens - true_tokens,
"single_padded_batch": summarize_ms(padded_samples),
"two_length_buckets": summarize_ms(bucket_samples),
"maximum_last_logit_relative_l2": round(max_relative_l2, 8),
},
correctness={"equivalent_last_token_logits": True},
)
print(f"Completed padding/bucketing experiment: {target}")
if __name__ == "__main__":
annotated_operation(main, "lab_workload")()
# Normal execution
sbatch slurm/18_padding_bucketing.sbatch --workload small
# Optional profiling
sbatch slurm/18_padding_bucketing.sbatch --workload small --profiler all
Lab 20: Investigate reusable prompt prefixes in a live engine
Repeated prompt prefixes can reuse previously computed KV state, but visible text repetition alone does not prove a cache hit. This lab compares repeated-prefix and unique-prefix request cohorts against a local engine.
Complete source: labs/20_prefix_cache_client.py
"""Compare repeated-prefix and unique-prefix requests against local vLLM."""
from __future__ import annotations
import argparse
import hashlib
import json
import statistics
import time
import urllib.parse
import urllib.request
from pathlib import Path
from common import require_hf_commit_revision, resolve_run_id, write_json_exclusive
from course_evidence import begin_experiment
DEFAULT_REVISION = "7ae557604adf67be50417f59c2c2f167def9a775"
def main() -> None:
parser = argparse.ArgumentParser(description=__doc__)
parser.add_argument("--base-url", default="http://127.0.0.1:8000")
parser.add_argument("--model", default="Qwen/Qwen2.5-0.5B-Instruct")
parser.add_argument("--revision", default=DEFAULT_REVISION)
parser.add_argument("--requests-per-cohort", type=int, default=8)
parser.add_argument("--output", type=Path, required=True)
parser.add_argument("--variant", choices=("disabled", "enabled"), required=True)
# Read the experiment controls before allocating inputs.
args = parser.parse_args()
begin_experiment(args)
require_hf_commit_revision(args.revision)
parsed = urllib.parse.urlparse(args.base_url)
if parsed.scheme != "http" or parsed.hostname not in {
"127.0.0.1",
"localhost",
"::1",
}:
raise SystemExit("This teaching client only connects to loopback HTTP.")
if not 2 <= args.requests_per_cohort <= 64:
raise SystemExit("--requests-per-cohort must be between two and 64")
run_id = resolve_run_id()
endpoint = args.base_url.rstrip("/") + "/v1/completions"
shared_prefix = "GPU evidence requires a fixed workload. " * 96
def send(prompt: str) -> tuple[float, int, int, str]:
body = json.dumps(
{
"model": args.model,
"prompt": prompt,
"max_tokens": 16,
"temperature": 0,
}
).encode()
request = urllib.request.Request(
endpoint,
data=body,
headers={"Content-Type": "application/json"},
method="POST",
)
started = time.perf_counter()
with urllib.request.urlopen(request, timeout=120) as response:
payload = json.loads(response.read())
elapsed = time.perf_counter() - started
usage = payload.get("usage", {})
choices = payload.get("choices", [])
if (
not isinstance(choices, list)
or len(choices) != 1
or not isinstance(choices[0], dict)
or not isinstance(choices[0].get("text"), str)
or not choices[0]["text"]
):
raise SystemExit("A request did not return one comparable text completion.")
return (
elapsed,
int(usage.get("prompt_tokens", 0)),
int(usage.get("completion_tokens", 0)),
hashlib.sha256(choices[0]["text"].encode()).hexdigest(),
)
send(shared_prefix + " Warm the shared prefix.")
repeated = [
send(shared_prefix + f" Explain measurement rule {index}.")
for index in range(args.requests_per_cohort)
]
unique = [
send(
f"Unique request marker {index}; do not reuse this prefix. "
+ ("GPU evidence requires a fixed workload. " * 95)
+ f"Explain measurement rule {index}."
)
for index in range(args.requests_per_cohort)
]
if not all(item[2] > 0 for item in repeated + unique):
raise SystemExit("At least one request returned no generated tokens.")
repeated_prompt_median = statistics.median(item[1] for item in repeated)
unique_prompt_median = statistics.median(item[1] for item in unique)
prompt_ratio = repeated_prompt_median / max(unique_prompt_median, 1)
if not 0.8 <= prompt_ratio <= 1.2:
raise SystemExit(
"Repeated and unique prompt cohorts differ by more than 20% in tokens."
)
def cohort(values: list[tuple[float, int, int, str]]) -> dict[str, float]:
return {
"median_e2e_ms": round(
statistics.median(item[0] for item in values) * 1_000, 3
),
"median_prompt_tokens": statistics.median(item[1] for item in values),
"completion_tokens": sum(item[2] for item in values),
}
payload = {
"schema": "gpu-course-result/v1",
"lab_id": "20_prefix_cache_client",
"run_id": run_id,
"measurements": {
"model": args.model,
"revision": args.revision,
"requests_per_cohort": args.requests_per_cohort,
"response_digests": [item[3] for item in repeated + unique],
"repeated_prefix": cohort(repeated),
"unique_prefix": cohort(unique),
"prompt_token_ratio": round(prompt_ratio, 4),
},
"correctness": {
"all_responses_nonempty": True,
"prompt_token_cohorts_comparable": True,
},
}
# Write this run’s evidence without overwriting an earlier result.
write_json_exclusive(args.output, payload)
print(f"Completed prefix-cache client experiment: {args.output}")
if __name__ == "__main__":
main()
# Normal execution
sbatch slurm/20_prefix_cache_client.sbatch --workload small
# Optional profiling
sbatch slurm/20_prefix_cache_client.sbatch --workload small --profiler all
Lab 23: Trace speculative acceptance, rejection, and recovery
Speculative decoding proposes several tokens with a cheaper draft and asks the target to verify them. This lab uses a small synthetic greedy target to make acceptance and recovery visible.
Complete source: labs/23_speculative_decoding.py
"""Expose accepted-prefix mechanics and regression conditions in greedy speculation."""
from __future__ import annotations
import argparse
import statistics
import time
from collections import Counter
from typing import Any
from common import (
add_common_args,
load_torch,
require_course_gpu,
seed_everything,
validate_common_args,
write_result,
)
from course_evidence import annotated_operation
def main() -> None:
parser = argparse.ArgumentParser(description=__doc__)
add_common_args(parser)
parser.add_argument("--draft-length", type=int, default=4)
parser.add_argument("--max-new-tokens", type=int, default=32)
# Read the experiment controls before allocating inputs.
args = parser.parse_args()
validate_common_args(args)
if (
args.draft_length < 1
or args.max_new_tokens < 2
or args.max_new_tokens <= args.draft_length
):
raise SystemExit(
"--draft-length must be positive and --max-new-tokens must be greater "
"than --draft-length so the full-acceptance path has room for a target "
"bonus token."
)
torch = load_torch()
environment = require_course_gpu(torch)
# Keep random inputs repeatable across comparable runs.
seed_everything(torch, args.seed)
vocab_size, hidden = (2_048, 512) if args.workload == "small" else (8_192, 2_048)
class TargetTransition(torch.nn.Module):
def __init__(self) -> None:
super().__init__()
self.embedding = torch.nn.Embedding(vocab_size, hidden)
self.projection = torch.nn.Linear(hidden, vocab_size, bias=False)
def forward(self, token_ids: Any) -> Any:
return self.projection(torch.nn.functional.gelu(self.embedding(token_ids)))
target_model = TargetTransition().to("cuda").eval()
with torch.inference_mode():
all_tokens = torch.arange(vocab_size, device="cuda")
ideal_draft = target_model(all_tokens).argmax(dim=-1).cpu().tolist()
poor_draft = [int((token + 1) % vocab_size) for token in ideal_draft]
start_token = args.seed % vocab_size
@torch.inference_mode()
def target_only() -> tuple[list[int], int]:
current = start_token
generated: list[int] = []
calls = 0
while len(generated) < args.max_new_tokens:
token = int(
target_model(torch.tensor([current], device="cuda"))
.argmax(dim=-1)
.item()
)
generated.append(token)
current = token
calls += 1
return generated, calls
target_only = annotated_operation(target_only, "target_only")
@torch.inference_mode()
def speculative(
draft_table: list[int],
) -> tuple[list[int], int, list[int], int, int, int]:
current = start_token
generated: list[int] = []
target_calls = 0
accepted_lengths: list[int] = []
proposal_count = 0
bonus_count = 0
recovered_count = 0
while len(generated) < args.max_new_tokens:
limit = min(args.draft_length, args.max_new_tokens - len(generated))
proposals: list[int] = []
draft_current = current
for _ in range(limit):
draft_current = draft_table[draft_current]
proposals.append(draft_current)
proposal_count += len(proposals)
verification_inputs = [current, *proposals]
verified = (
target_model(torch.tensor(verification_inputs, device="cuda"))
.argmax(dim=-1)
.cpu()
.tolist()
)
target_calls += 1
accepted = 0
for proposed, target_token in zip(proposals, verified[:-1], strict=True):
if proposed == target_token:
generated.append(proposed)
current = proposed
accepted += 1
else:
generated.append(target_token)
current = target_token
recovered_count += 1
break
else:
if len(generated) < args.max_new_tokens:
bonus_token = verified[-1]
generated.append(bonus_token)
current = bonus_token
bonus_count += 1
accepted_lengths.append(accepted)
return (
generated,
target_calls,
accepted_lengths,
proposal_count,
bonus_count,
recovered_count,
)
def time_case(operation: Any) -> tuple[list[float], Any, float]:
for _ in range(args.warmup):
operation()
# Wait for queued GPU work to finish at this measurement boundary.
torch.cuda.synchronize()
torch.cuda.reset_peak_memory_stats()
samples: list[float] = []
last_result: Any = None
for _ in range(args.iterations):
torch.cuda.synchronize()
started = time.perf_counter()
last_result = operation()
torch.cuda.synchronize()
samples.append((time.perf_counter() - started) * 1_000)
peak_mib = torch.cuda.max_memory_allocated() / 2**20
return samples, last_result, peak_mib
baseline_samples, baseline_result, baseline_peak = time_case(target_only)
high_samples, high_result, high_peak = time_case(lambda: speculative(ideal_draft))
low_samples, low_result, low_peak = time_case(lambda: speculative(poor_draft))
baseline_tokens, baseline_calls = baseline_result
(
high_tokens,
high_calls,
high_accepts,
high_proposals,
high_bonuses,
high_recovered,
) = high_result
(
low_tokens,
low_calls,
low_accepts,
low_proposals,
low_bonuses,
low_recovered,
) = low_result
exact = baseline_tokens == high_tokens == low_tokens
high_reduces_calls = high_calls < baseline_calls
low_preserves_calls = low_calls == baseline_calls
high_emits_bonus = high_bonuses > 0
low_emits_recovery = low_recovered > 0
if (
not exact
or baseline_calls != args.max_new_tokens
or not high_reduces_calls
or not low_preserves_calls
or not high_emits_bonus
or not low_emits_recovery
):
raise SystemExit(
"Speculative output or target-call acceptance gates did not pass."
)
def case_record(
samples: list[float],
calls: int,
accepted: list[int],
proposals: int,
bonus_tokens: int,
recovered_tokens: int,
) -> dict[str, Any]:
histogram = Counter(accepted)
return {
"median_e2e_ms": round(statistics.median(samples), 4),
"target_forward_calls": calls,
"draft_tokens_proposed": proposals,
"accepted_draft_tokens": sum(accepted),
"target_bonus_tokens": bonus_tokens,
"target_recovered_tokens": recovered_tokens,
"mean_accepted_prefix": round(statistics.mean(accepted), 3),
"accepted_prefix_histogram": {
str(length): count for length, count in sorted(histogram.items())
},
}
# Save the actual measurements together with their correctness checks.
target = write_result(
args,
lab_id="23_speculative_decoding",
environment=environment,
measurements={
"mechanism_scope": "greedy first-order synthetic target",
"vocab_size": vocab_size,
"hidden_size": hidden,
"draft_length": args.draft_length,
"generated_tokens": args.max_new_tokens,
"target_only": {
"median_e2e_ms": round(statistics.median(baseline_samples), 4),
"target_forward_calls": baseline_calls,
"peak_allocated_mib": round(baseline_peak, 1),
},
"high_acceptance": {
**case_record(
high_samples,
high_calls,
high_accepts,
high_proposals,
high_bonuses,
high_recovered,
),
"peak_allocated_mib": round(high_peak, 1),
},
"low_acceptance": {
**case_record(
low_samples,
low_calls,
low_accepts,
low_proposals,
low_bonuses,
low_recovered,
),
"peak_allocated_mib": round(low_peak, 1),
},
},
correctness={
"both_speculative_paths_match_target_only_greedy_output": exact,
"high_acceptance_reduces_target_calls": high_reduces_calls,
"low_acceptance_does_not_reduce_target_calls": low_preserves_calls,
"full_acceptance_emits_target_bonus_tokens": high_emits_bonus,
"first_rejection_emits_target_recovery_tokens": low_emits_recovery,
},
)
print(f"Completed speculative-decoding mechanics comparison: {target}")
if __name__ == "__main__":
annotated_operation(main, "lab_workload")()
# Normal execution
sbatch slurm/23_speculative_decoding.sbatch --workload small --draft-length 4 --max-new-tokens 32
# Optional profiling
sbatch slurm/23_speculative_decoding.sbatch --workload small --draft-length 4 --max-new-tokens 32 --profiler all
Lab 24: Compare materialized attention with SDPA dispatch
Attention can either materialize a large score matrix or use a more memory-efficient implementation that avoids keeping the entire matrix. This lab compares an explicit reference with PyTorch scaled-dot-product attention for prefill-like and decode-like shapes.
Complete source: labs/24_sdpa_attention.py
"""Profile prefill- and decode-shaped attention against PyTorch SDPA dispatch."""
from __future__ import annotations
import argparse
import math
from contextlib import nullcontext
from common import (
add_common_args,
cuda_times_ms,
load_torch,
require_course_gpu,
seed_everything,
summarize_ms,
validate_common_args,
write_result,
)
from course_evidence import annotated_operation
def peak_bytes(torch: object, operation: object) -> int:
torch.cuda.empty_cache()
baseline_bytes = int(torch.cuda.memory_allocated())
torch.cuda.reset_peak_memory_stats()
operation()
# Wait for queued GPU work to finish at this measurement boundary.
torch.cuda.synchronize()
return int(torch.cuda.max_memory_allocated()) - baseline_bytes
def main() -> None:
parser = argparse.ArgumentParser(description=__doc__)
add_common_args(parser)
parser.add_argument("--external-only", action="store_true", help="Skip the internal CUDA profiler during a separate Nsight capture.")
# Read the experiment controls before allocating inputs.
args = parser.parse_args()
validate_common_args(args)
torch = load_torch()
environment = require_course_gpu(torch)
# Keep random inputs repeatable across comparable runs.
seed_everything(torch, args.seed)
sequence = 512 if args.workload == "small" else 2_048
batch, heads, head_dim = 2, 8, 64
rows = []
for label, query_length, causal in (
("prefill", sequence, True),
("decode", 1, False),
):
# Create the synthetic tensors used by this experiment.
query = torch.randn(
(batch, heads, query_length, head_dim),
device="cuda",
dtype=torch.bfloat16,
)
key = torch.randn(
(batch, heads, sequence, head_dim),
device="cuda",
dtype=torch.bfloat16,
)
value = torch.randn_like(key)
causal_mask = (
torch.ones((query_length, sequence), device="cuda", dtype=torch.bool).tril()
if causal
else None
)
def materialized() -> object:
scores = (query @ key.transpose(-2, -1)) / math.sqrt(head_dim)
if causal_mask is not None:
scores = scores.masked_fill(~causal_mask, float("-inf"))
return torch.softmax(scores, dim=-1) @ value
def sdpa() -> object:
return torch.nn.functional.scaled_dot_product_attention(
query, key, value, is_causal=causal
)
reference = materialized()
observed = sdpa()
max_error = float((reference.float() - observed.float()).abs().max().item())
correct = bool(torch.allclose(reference, observed, rtol=1e-2, atol=1e-2))
if not correct:
raise SystemExit(
f"Materialized and SDPA {label} paths diverged: {max_error=}"
)
with (nullcontext() if args.external_only else torch.profiler.profile(
activities=[
torch.profiler.ProfilerActivity.CPU,
torch.profiler.ProfilerActivity.CUDA,
]
)) as profile:
sdpa()
torch.cuda.synchronize()
dispatch = sorted(
event.key
for event in (profile.key_averages() if profile is not None else [])
if "scaled_dot_product" in event.key.lower()
or "flash" in event.key.lower()
or "attention" in event.key.lower()
)
timings = {}
peaks = {}
for mode, operation in (("materialized", materialized), ("sdpa", sdpa)):
timings[mode] = summarize_ms(
cuda_times_ms(
torch,
operation,
warmup=args.warmup,
iterations=args.iterations,
)
)
peaks[mode] = peak_bytes(torch, operation)
rows.append(
{
"phase": label,
"query_length": query_length,
"key_value_length": sequence,
"causal": causal,
"timing": timings,
"incremental_peak_bytes": peaks,
"dispatch_keys": dispatch,
"max_abs_error": round(max_error, 6),
}
)
# Save the actual measurements together with their correctness checks.
target_path = write_result(
args,
lab_id="24_sdpa_attention",
environment=environment,
measurements={"shape": [batch, heads, sequence, head_dim], "cases": rows},
correctness={"all_cases_close": True, "bf16_rtol_atol": [1e-2, 1e-2]},
)
print(f"Completed SDPA backend experiment: {target_path}")
if __name__ == "__main__":
annotated_operation(main, "lab_workload")()
# Normal execution
sbatch slurm/24_sdpa_attention.sbatch --workload small
# Optional profiling
sbatch slurm/24_sdpa_attention.sbatch --workload small --profiler all
Lab 25: Explore input length and recurrent operator work
Long inputs and long output sequences stress different parts of an inference workload, but a small operator model must not be mislabeled as a language model. A recurrent update feeds the previous hidden state (the intermediate values retained between steps) into the next computation.
Complete source: labs/25_workload_metrics.py
"""Measure input projection and recurrent operator work, not language-model tokens."""
from __future__ import annotations
import argparse
import math
from common import (
add_common_args,
cuda_times_ms,
load_torch,
require_course_gpu,
seed_everything,
summarize_ms,
validate_common_args,
write_result,
)
from course_evidence import annotated_operation
def operator_rates(
batch: int, steps: int, sequence_ms: float, joined_ms: float
) -> dict[str, float]:
"""Count independent row updates, never label synthetic work as generated tokens."""
if (
batch < 1
or steps < 1
or any(
not math.isfinite(value) or value <= 0 for value in (sequence_ms, joined_ms)
)
):
raise ValueError(
"operator counts and measured durations must be positive and finite"
)
return {
"mean_recurrent_iteration_ms": sequence_ms / steps,
"recurrent_row_updates_per_second": batch * steps * 1000 / sequence_ms,
"joined_row_updates_per_second": batch * steps * 1000 / joined_ms,
}
def main() -> None:
parser = argparse.ArgumentParser(description=__doc__)
add_common_args(parser)
parser.add_argument(
"--concurrency",
type=int,
default=4,
help="Batch rows of synthetic operator work, not concurrent service requests.",
)
# Read the experiment controls before allocating inputs.
args = parser.parse_args()
validate_common_args(args)
if args.concurrency < 1:
raise SystemExit("--concurrency must be positive")
torch = load_torch()
# Keep random inputs repeatable across comparable runs.
seed_everything(torch, args.seed)
environment = require_course_gpu(torch)
hidden = 256 if args.workload == "small" else 1_024
# Create the synthetic tensors used by this experiment.
weight = torch.randn((hidden, hidden), device="cuda", dtype=torch.bfloat16)
def incremental_peak(operation: object) -> int:
torch.cuda.empty_cache()
baseline = int(torch.cuda.memory_allocated())
torch.cuda.reset_peak_memory_stats()
operation()
# Wait for queued GPU work to finish at this measurement boundary.
torch.cuda.synchronize()
return int(torch.cuda.max_memory_allocated()) - baseline
rows = []
for isl, osl in ((128, 32), (2_048, 32), (128, 512), (2_048, 512)):
prompt = torch.randn(
(args.concurrency, isl, hidden), device="cuda", dtype=torch.bfloat16
)
def project_prompt() -> object:
return prompt @ weight
projected_state = project_prompt()[:, -1, :].contiguous()
def one_recurrent_step() -> object:
return torch.tanh(projected_state @ weight)
def recurrent_sequence() -> object:
state = projected_state
for _ in range(osl):
state = torch.tanh(state @ weight)
return state
def joined_workload() -> object:
state = project_prompt()[:, -1, :].contiguous()
for _ in range(osl):
state = torch.tanh(state @ weight)
return state
projection_timing = summarize_ms(
cuda_times_ms(
torch, project_prompt, warmup=args.warmup, iterations=args.iterations
)
)
recurrent_step_timing = summarize_ms(
cuda_times_ms(
torch,
one_recurrent_step,
warmup=args.warmup,
iterations=args.iterations,
)
)
recurrent_timing = summarize_ms(
cuda_times_ms(
torch,
recurrent_sequence,
warmup=args.warmup,
iterations=args.iterations,
)
)
joined_timing = summarize_ms(
cuda_times_ms(
torch, joined_workload, warmup=args.warmup, iterations=args.iterations
)
)
observed = recurrent_sequence()
finite = bool(torch.isfinite(observed).all())
if not finite:
raise SystemExit(
f"Recurrent operator work produced non-finite output for {isl=}, {osl=}."
)
rows.append(
{
"input_length": isl,
"recurrent_iterations": osl,
"batch_rows": args.concurrency,
"projected_input_rows": args.concurrency * isl,
"recurrent_row_updates": args.concurrency * osl,
"input_projection": projection_timing,
"one_recurrent_step": recurrent_step_timing,
"recurrent_sequence": recurrent_timing,
"joined_projection_and_recurrence": joined_timing,
**operator_rates(
args.concurrency,
osl,
recurrent_timing["median_ms"],
joined_timing["median_ms"],
),
"projection_incremental_peak_bytes": incremental_peak(project_prompt),
"recurrent_incremental_peak_bytes": incremental_peak(
recurrent_sequence
),
"finite": finite,
}
)
# Save the actual measurements together with their correctness checks.
target_path = write_result(
args,
lab_id="25_workload_metrics",
environment=environment,
measurements={
"metric_boundary": "synthetic device operators: dense input projection followed by recurrent tanh matmuls; no attention, KV cache, vocabulary head, sampling, or generated tokens",
"concurrency_scope": "batch rows, not concurrent service requests",
"live_service_metrics_owner": "vLLM/AIPerf serving labs",
"workload_cells": rows,
},
correctness={
"four_cells_executed": len(rows) == 4,
"all_declared_operator_work_counted": all(
row["projected_input_rows"] == row["batch_rows"] * row["input_length"]
and row["recurrent_row_updates"]
== row["batch_rows"] * row["recurrent_iterations"]
for row in rows
),
},
)
print(f"Wrote workload-matrix evidence: {target_path}")
if __name__ == "__main__":
annotated_operation(main, "lab_workload")()
# Normal execution
sbatch slurm/25_workload_metrics.sbatch --workload small --concurrency 1
# Optional profiling
sbatch slurm/25_workload_metrics.sbatch --workload small --concurrency 1 --profiler all
Lab 26: Calculate ideal KV storage for MHA, GQA, and MQA
KV-cache capacity depends on stored key/value heads, not simply the number of query heads. This lab calculates ideal storage for multi-head, grouped-query, and multi-query attention and checks a small tensor allocation's byte arithmetic.
Complete source: labs/26_kv_capacity.py
"""Calculate and verify KV-cache capacity for MHA, GQA, and MQA layouts."""
from __future__ import annotations
import argparse
from common import (
add_common_args,
load_torch,
require_course_gpu,
validate_common_args,
write_result,
)
def kv_bytes_per_token(
layers: int, kv_heads: int, head_dim: int, bytes_per_value: int
) -> int:
"""Return key plus value bytes for one token and one sequence."""
return 2 * layers * kv_heads * head_dim * bytes_per_value
def main() -> None:
parser = argparse.ArgumentParser(description=__doc__)
add_common_args(parser, include_measurement=False)
parser.add_argument("--sequence", type=int, default=4096)
parser.add_argument("--concurrency", type=int, default=8)
# Read the experiment controls before allocating inputs.
args = parser.parse_args()
validate_common_args(args)
if args.sequence < 1 or args.concurrency < 1:
raise SystemExit("--sequence and --concurrency must be positive")
torch = load_torch()
environment = require_course_gpu(torch)
cases = {}
for name, kv_heads in (("mha", 32), ("gqa", 8), ("mqa", 1)):
per_token = kv_bytes_per_token(32, kv_heads, 128, 2)
cases[name] = {
"kv_heads": kv_heads,
"bytes_per_token": per_token,
"ideal_gib": round(per_token * args.sequence * args.concurrency / 2**30, 4),
}
probe = torch.empty((2, 32, 8, 128), device="cuda", dtype=torch.bfloat16)
# Save the actual measurements together with their correctness checks.
target = write_result(
args,
lab_id="26_kv_capacity",
environment=environment,
measurements={
"layers": 32,
"query_heads": 32,
"head_dim": 128,
"dtype_bytes": 2,
"sequence": args.sequence,
"concurrency": args.concurrency,
"cases": cases,
"runtime_overhead_excluded": [
"weights",
"temporaries",
"allocator reserve",
"block rounding",
],
},
correctness={
"probe_bytes_match": probe.numel() * probe.element_size()
== kv_bytes_per_token(32, 8, 128, 2)
},
)
print(f"Wrote KV-capacity evidence: {target}")
if __name__ == "__main__":
main()
# Normal execution
sbatch slurm/26_kv_capacity.sbatch --workload small --sequence 4096 --concurrency 8
# Optional profiling
sbatch slurm/26_kv_capacity.sbatch --workload small --sequence 4096 --concurrency 8 --profiler all
Lab 27: Follow paged-cache allocation, growth, and recycling
Paged KV storage gives each request a logical block table that points to physical cache pages. This lab implements that ownership lifecycle in a deterministic Python model, including failed growth and page reuse.
Complete source: labs/27_paged_kv.py
"""Simulate paged KV allocation, growth, recycling, and internal waste."""
from __future__ import annotations
import argparse
from common import (
add_common_args,
load_torch,
require_course_gpu,
validate_common_args,
write_result,
)
def allocate(
lengths: list[int], block_tokens: int, total_blocks: int
) -> dict[str, int | bool]:
"""Static demand worksheet, independently cross-checked against live state."""
if block_tokens < 1 or total_blocks < 1 or any(length < 0 for length in lengths):
raise ValueError("positive capacity and nonnegative lengths required")
required = sum((length + block_tokens - 1) // block_tokens for length in lengths)
useful = sum(lengths)
return {
"required_blocks": required,
"free_blocks": max(0, total_blocks - required),
"shortfall_blocks": max(0, required - total_blocks),
"useful_tokens": useful,
"allocated_tokens": required * block_tokens,
"internal_waste_tokens": required * block_tokens - useful,
"fits": required <= total_blocks,
}
class PagedKVPool:
"""Small deterministic allocator: logical request pages map to physical IDs.
It models exclusive ownership only: no prefix sharing, swapping, tensors,
preemption or engine timing. Capacity failures must leave all state intact.
"""
def __init__(self, block_tokens: int, total_blocks: int):
allocate([], block_tokens, total_blocks)
self.block_tokens = block_tokens
self.total_blocks = total_blocks
self._free = list(range(total_blocks))
self._tables: dict[str, list[int]] = {}
self._lengths: dict[str, int] = {}
def _reserve(self, blocks: int) -> list[int]:
if blocks > len(self._free):
raise MemoryError("KV capacity exhausted; no blocks were changed")
chosen = self._free[:blocks]
del self._free[:blocks]
return chosen
def admit(self, request: str, tokens: int) -> None:
if not request or request in self._tables or tokens < 0:
raise ValueError("unique nonempty request and nonnegative tokens required")
blocks = (tokens + self.block_tokens - 1) // self.block_tokens
reserved = self._reserve(blocks)
self._tables[request] = reserved
self._lengths[request] = tokens
self.check_invariants()
def grow(self, request: str, tokens: int) -> None:
if tokens < self._lengths[request]:
raise ValueError("growth cannot shrink a request")
blocks = (tokens + self.block_tokens - 1) // self.block_tokens
# Reserve before changing either the logical length or the block table.
extra = self._reserve(blocks - len(self._tables[request]))
self._tables[request].extend(extra)
self._lengths[request] = tokens
self.check_invariants()
def release(self, request: str) -> None:
released = self._tables.pop(request)
del self._lengths[request]
self._free = sorted(self._free + released)
self.check_invariants()
def check_invariants(self) -> None:
used = [block for table in self._tables.values() for block in table]
all_blocks = used + self._free
if sorted(all_blocks) != list(range(self.total_blocks)):
raise RuntimeError("physical block is lost, duplicated, or out of range")
for request, table in self._tables.items():
needed = (
self._lengths[request] + self.block_tokens - 1
) // self.block_tokens
if len(table) != needed:
raise RuntimeError("logical block table does not match token length")
def snapshot(self) -> dict[str, object]:
self.check_invariants()
return {
"block_tables": {key: value[:] for key, value in self._tables.items()},
"lengths": self._lengths.copy(),
"free_block_ids": self._free[:],
"accounting": allocate(
list(self._lengths.values()), self.block_tokens, self.total_blocks
),
}
def lifecycle_demo(block_tokens: int, total_blocks: int) -> dict[str, object]:
if total_blocks < 4:
raise ValueError("the lifecycle demonstration requires at least four blocks")
pool = PagedKVPool(block_tokens, total_blocks)
events = []
def record(event: str) -> None:
events.append({"event": event, "state": pool.snapshot()})
record("empty pool")
pool.admit("a", block_tokens)
record("admit a: one block")
pool.admit("b", block_tokens + 1)
record("admit b: two blocks")
pool.grow("a", block_tokens + 1)
record("grow a across page boundary: preserve block 0, append block 3")
before = pool.snapshot()
rejected = False
try:
pool.grow("b", block_tokens * total_blocks + 1)
except MemoryError:
rejected = True
unchanged = before == pool.snapshot()
record("reject oversized growth without partial mutation")
pool.release("a")
record("complete a: return physical IDs 0 and 3")
pool.admit("c", block_tokens + 1)
record("admit c: reuse physical IDs 0 and 3")
after = pool.snapshot()
return {
"events": events,
"checks": {
"growth_preserves_mapping": before["block_tables"]["a"] == [0, 3],
"capacity_failure_detected": rejected,
"capacity_failure_is_atomic": unchanged,
"completion_recycles_physical_blocks": after["block_tables"]["c"] == [0, 3],
"unrelated_request_mapping_preserved": before["block_tables"]["b"]
== after["block_tables"]["b"],
},
}
def main() -> None:
parser = argparse.ArgumentParser(description=__doc__)
add_common_args(parser, include_measurement=False)
parser.add_argument("--block-tokens", type=int, default=16)
parser.add_argument("--total-blocks", type=int, default=128)
# Read the experiment controls before allocating inputs.
args = parser.parse_args()
validate_common_args(args)
if args.block_tokens < 1 or args.total_blocks < 4:
raise SystemExit(
"--block-tokens must be positive; --total-blocks must be at least 4"
)
torch = load_torch()
environment = require_course_gpu(torch)
demonstration = lifecycle_demo(args.block_tokens, args.total_blocks)
if not all(demonstration["checks"].values()):
raise SystemExit("Paged-KV lifecycle correctness failed")
# Save the actual measurements together with their correctness checks.
target = write_result(
args,
lab_id="27_paged_kv",
environment=environment,
measurements={
"block_tokens": args.block_tokens,
"total_blocks": args.total_blocks,
"lifecycle_events": demonstration["events"],
"demand_worksheet": allocate(
[31, 65, 127, 9], args.block_tokens, args.total_blocks
),
"scope": "CPU allocator mechanics, not live KV tensors or engine performance",
},
correctness=demonstration["checks"],
)
print(f"Wrote paged-KV evidence: {target}")
if __name__ == "__main__":
main()
Teaching diagramPaged KV blocks before release and after reuse
Request B's logical blocks 0 and 1 map to stable physical blocks P2 and P5. When B completes, P2 and P5 return to the free list. Request D then maps its logical blocks 0 and 1 to those same physical IDs. The mappings for A and C do not change; physical identity and logical ownership are distinct.
# Normal execution
sbatch slurm/27_paged_kv.sbatch --workload small --block-tokens 16 --total-blocks 4
# Optional profiling
sbatch slurm/27_paged_kv.sbatch --workload small --block-tokens 16 --total-blocks 4 --profiler all
Lab 28: Compare full-prefill and chunked scheduling
Long prompt processing can delay requests that are ready to generate another token. This lab models how full non-preemptible prefill and bounded prefill chunks affect admission opportunities under fixed arrivals.
Complete source: labs/28_continuous_batching.py
"""Simulate continuous batching and chunked-prefill scheduling tradeoffs."""
from __future__ import annotations
import argparse
import math
import statistics
from common import (
add_common_args,
load_torch,
require_course_gpu,
validate_common_args,
write_result,
)
def simulate(
prompts: list[int],
outputs: list[int],
chunk: int | None,
token_budget: int,
arrivals: list[int] | None = None,
) -> dict[str, object]:
"""Compare full prefill (chunk=None) with bounded decode-first chunks.
One service quantum supplies token_budget abstract work units. Each prompt
or decode token costs one unit, deliberately NOT an H100 latency model.
A dispatch lasts ceil(work/budget) quanta; arrivals during it cannot join.
Full prefill may exceed the budget only as a solitary, non-preemptible job.
"""
if (
len(prompts) != len(outputs)
or (chunk is not None and chunk < 1)
or token_budget < 1
):
raise ValueError("prompts/outputs must align and budgets must be positive")
arrivals = [0] * len(prompts) if arrivals is None else arrivals
if len(arrivals) != len(prompts) or any(value < 0 for value in arrivals):
raise ValueError("nonnegative arrivals must align with prompts")
if any(value < 0 for value in prompts) or any(value < 1 for value in outputs):
raise ValueError("prompts must be nonnegative; outputs must be positive")
remaining_prefill = prompts[:]
remaining_decode = outputs[:]
first_token_times = [-1] * len(prompts)
completion_times = [-1] * len(prompts)
clock = 0
scheduled_tokens = 0
maximum_active = 0
trace = []
while any(remaining_prefill) or any(remaining_decode):
budget = token_budget
active = [
index
for index in range(len(prompts))
if arrivals[index] <= clock
and (remaining_prefill[index] or remaining_decode[index])
]
if not active:
clock = min(
arrivals[index]
for index in range(len(prompts))
if remaining_prefill[index] or remaining_decode[index]
)
continue
maximum_active = max(maximum_active, len(active))
prefill = {}
decode = []
# Keep one decode token per ready request moving before spending the# remaining round budget on prompt chunks.
for index in active:
if remaining_prefill[index] == 0 and remaining_decode[index] > 0 and budget:
remaining_decode[index] -= 1
decode.append(index)
budget -= 1
for index in active:
if remaining_prefill[index] > 0 and budget:
if chunk is None:
amount = remaining_prefill[index]
if amount > budget and budget != token_budget:
# Do not enlarge a batch that already contains work.
continue
else:
amount = min(chunk, remaining_prefill[index], budget)
remaining_prefill[index] -= amount
prefill[str(index)] = amount
budget = max(0, budget - amount)
work = sum(prefill.values()) + len(decode)
duration = math.ceil(work / token_budget)
end = clock + duration
for index in decode:
if first_token_times[index] < 0:
first_token_times[index] = end
if remaining_decode[index] == 0:
completion_times[index] = end
trace.append(
{
"start": clock,
"end": end,
"prefill": prefill,
"decode": decode,
"work": work,
"active_requests": active,
}
)
scheduled_tokens += work
clock = end
latencies = [
time - arrival
for time, arrival in zip(first_token_times, arrivals, strict=True)
]
return {
"policy": "nonpreemptible-full-prefill"
if chunk is None
else f"chunked-{chunk}",
"scheduler_dispatches": len(trace),
"elapsed_service_quanta": clock,
"scheduled_tokens": scheduled_tokens,
"first_token_times": first_token_times,
"first_token_latencies": latencies,
"median_first_token_latency_quanta": statistics.median(latencies)
if latencies
else None,
"completion_times": completion_times,
"completed_requests": sum(time >= 0 for time in completion_times),
"maximum_active_requests": maximum_active,
"work_units_per_service_quantum": token_budget,
"trace": trace,
}
def main() -> None:
parser = argparse.ArgumentParser(description=__doc__)
add_common_args(parser, include_measurement=False)
# Read the experiment controls before allocating inputs.
args = parser.parse_args()
validate_common_args(args)
torch = load_torch()
environment = require_course_gpu(torch)
prompts = [64, 2048, 128, 1024]
outputs = [128, 32, 256, 64]
arrivals = [0, 0, 1, 3]
token_budget = 256
unchunked = simulate(prompts, outputs, None, token_budget, arrivals)
chunked = simulate(prompts, outputs, 64, token_budget, arrivals)
control = simulate(prompts, outputs, 256, token_budget, arrivals)
checks = {
"equivalent_tokens": all(
result["scheduled_tokens"] == sum(prompts) + sum(outputs)
for result in (unchunked, chunked, control)
),
"all_requests_complete": all(
result["completed_requests"] == len(prompts)
for result in (unchunked, chunked, control)
),
}
if not all(checks.values()):
raise SystemExit("Scheduling comparison lost work or request completion")
# Save the actual measurements together with their correctness checks.
target = write_result(
args,
lab_id="28_continuous_batching",
environment=environment,
measurements={
"prompts": prompts,
"outputs": outputs,
"arrival_service_quanta": arrivals,
"work_units_per_service_quantum": token_budget,
"nonpreemptible_full_prefill": unchunked,
"chunked_64": chunked,
"chunked_256_control": control,
"note": (
"abstract scheduler mechanics, not milliseconds or vLLM emulation; "
"prefill/decode tokens have equal modeled cost; full prefills exceeding "
"budget occupy multiple service quanta; arrivals wait until dispatch ends; "
"a pinned live engine A/B remains a separate gate"
),
},
correctness=checks,
)
print(f"Wrote scheduling evidence: {target}")
if __name__ == "__main__":
main()
# Normal execution
sbatch slurm/28_continuous_batching.sbatch --workload small
# Optional profiling
sbatch slurm/28_continuous_batching.sbatch --workload small --profiler all
Lab 29: Inspect quantized weight and KV storage mechanics
Quantization can reduce stored payload size while adding scale metadata, conversion work, and numerical error. This lab implements symmetric INT8 weight and KV representations and compares their reconstruction with BF16 references.
Complete source: labs/29_quantization.py
"""Compare BF16 with symmetric INT8 weight and KV-cache mechanics."""
from __future__ import annotations
import argparse
from common import (
add_common_args,
cuda_times_ms,
load_torch,
require_course_gpu,
seed_everything,
summarize_ms,
validate_common_args,
write_result,
)
from course_evidence import annotated_operation
def main() -> None:
parser = argparse.ArgumentParser(description=__doc__)
add_common_args(parser)
# Read the experiment controls before allocating inputs.
args = parser.parse_args()
validate_common_args(args)
torch = load_torch()
# Keep random inputs repeatable across comparable runs.
seed_everything(torch, args.seed)
environment = require_course_gpu(torch)
width = 512 if args.workload == "small" else 4096
# Create the synthetic tensors used by this experiment.
x = torch.randn((64, width), device="cuda", dtype=torch.bfloat16)
weight = torch.randn((width, width), device="cuda", dtype=torch.bfloat16)
weight_scale = weight.abs().max().clamp_min(1e-12) / 127
quantized_weight = torch.clamp((weight / weight_scale).round(), -127, 127).to(
torch.int8
)
layers = 8 if args.workload == "small" else 32
sequence = 512 if args.workload == "small" else 2_048
kv = torch.randn((layers, 2, 8, sequence, 64), device="cuda", dtype=torch.bfloat16)
kv_scale = kv.abs().max().clamp_min(1e-12) / 127
quantized_kv = torch.clamp((kv / kv_scale).round(), -127, 127).to(torch.int8)
def baseline() -> object:
return x @ weight
def candidate() -> object:
return x @ (quantized_weight.to(torch.bfloat16) * weight_scale)
def kv_dequantize() -> object:
return quantized_kv.to(torch.bfloat16) * kv_scale
reference = baseline()
observed = candidate()
relative_l2 = float(
(observed.float() - reference.float()).norm() / reference.float().norm()
)
kv_observed = kv_dequantize()
kv_relative_l2 = float(
(kv_observed.float() - kv.float()).norm() / kv.float().norm()
)
if relative_l2 >= 0.02 or kv_relative_l2 >= 0.02:
raise SystemExit("INT8 mechanics failed the declared 0.02 relative-L2 gate.")
timing = {
name: summarize_ms(
cuda_times_ms(
torch, operation, warmup=args.warmup, iterations=args.iterations
)
)
for name, operation in (
("bf16", baseline),
("int8_weight_dequantize_then_matmul", candidate),
)
}
kv_timing = summarize_ms(
cuda_times_ms(
torch,
kv_dequantize,
warmup=args.warmup,
iterations=args.iterations,
)
)
# Save the actual measurements together with their correctness checks.
target = write_result(
args,
lab_id="29_quantization",
environment=environment,
measurements={
"shape": [width, width],
"bf16_weight_bytes": weight.numel() * weight.element_size(),
"int8_weight_and_scale_bytes": quantized_weight.numel()
* quantized_weight.element_size()
+ weight_scale.numel() * weight_scale.element_size(),
"bf16_kv_bytes": kv.numel() * kv.element_size(),
"int8_kv_and_scale_bytes": quantized_kv.numel()
* quantized_kv.element_size()
+ kv_scale.numel() * kv_scale.element_size(),
"weight_relative_l2_error": relative_l2,
"kv_relative_l2_error": kv_relative_l2,
"weight_timing": timing,
"kv_dequantization_timing": kv_timing,
"memory_scope": "logical payload; both BF16 and INT8 copies remain resident for this A/B",
"kernel_claim": "mechanics only; engine-supported weight and KV kernels are required for production latency claims",
},
correctness={
"finite": bool(torch.isfinite(observed).all()),
"weight_quality_gate": relative_l2 < 0.02,
"kv_quality_gate": kv_relative_l2 < 0.02,
},
)
print(f"Wrote quantization evidence: {target}")
if __name__ == "__main__":
annotated_operation(main, "lab_workload")()
# Normal execution
sbatch slurm/29_quantization.sbatch --workload small
# Optional profiling
sbatch slurm/29_quantization.sbatch --workload small --profiler all
Lab 30: Probe an engine's readiness and request schema
Different inference servers expose different readiness endpoints and request schemas even when they host similar models. This lab sends one bounded request through either an OpenAI-compatible API or a declared TensorRT-LLM/Triton repository profile.
Complete source: labs/30_engine_profile.py
"""Probe an OpenAI-compatible inference engine and measure a bounded request."""
from __future__ import annotations
import argparse
import json
import time
import urllib.parse
import urllib.request
from common import add_common_args, validate_common_args, write_result
def request_bytes(url: str, payload: dict[str, object] | None = None) -> bytes:
data = None if payload is None else json.dumps(payload).encode("utf-8")
request = urllib.request.Request(
url,
data=data,
headers={"Content-Type": "application/json"},
method="GET" if data is None else "POST",
)
with urllib.request.urlopen(request, timeout=60) as response:
return response.read()
def request_json(
url: str, payload: dict[str, object] | None = None
) -> dict[str, object]:
body = request_bytes(url, payload)
return json.loads(body) if body else {}
def main() -> None:
parser = argparse.ArgumentParser(description=__doc__)
add_common_args(parser, include_measurement=False)
parser.add_argument("--server-url", default="http://127.0.0.1:8000")
parser.add_argument("--model", required=True)
parser.add_argument("--max-tokens", type=int, default=16)
parser.add_argument(
"--protocol",
choices=("openai", "triton"),
default="openai",
help="Use OpenAI-compatible v1 or Triton v2 generate endpoints.",
)
parser.add_argument(
"--triton-max-token-field",
choices=("sampling_param_max_tokens", "max_tokens"),
default=None,
help="Match the field declared by the pinned TensorRT-LLM model repository.",
)
parser.add_argument(
"--triton-repository-profile",
choices=("llmapi", "inflight_batcher"),
default=None,
help="Declare the reviewed TensorRT-LLM repository schema.",
)
# Read the experiment controls before allocating inputs.
args = parser.parse_args()
validate_common_args(args)
if args.max_tokens < 1:
raise SystemExit("--max-tokens must be positive")
server_url = args.server_url.rstrip("/")
model_count: int | None = None
if args.protocol == "openai":
models = request_json(f"{server_url}/v1/models")
model_count = len(models.get("data", []))
else:
if (
args.triton_repository_profile is None
or args.triton_max_token_field is None
):
raise SystemExit(
"Triton requires an explicit repository profile and max-token field."
)
valid_profile = (
args.triton_repository_profile == "llmapi"
and args.model == "tensorrt_llm"
and args.triton_max_token_field == "sampling_param_max_tokens"
) or (
args.triton_repository_profile == "inflight_batcher"
and args.model in {"ensemble", "tensorrt_llm_bls"}
and args.triton_max_token_field == "max_tokens"
)
if not valid_profile:
raise SystemExit(
"Triton profile/model/token-field combination is not a supported "
"course contract."
)
model_path = urllib.parse.quote(args.model, safe="")
request_bytes(f"{server_url}/v2/health/ready")
request_bytes(f"{server_url}/v2/models/{model_path}/ready")
start = time.perf_counter()
if args.protocol == "openai":
response = request_json(
f"{server_url}/v1/completions",
{
"model": args.model,
"prompt": "Explain one benefit of GPU memory coalescing.",
"max_tokens": args.max_tokens,
"temperature": 0,
},
)
choices = response.get("choices", [])
response_valid = bool(
choices and isinstance(choices[0].get("text"), str) and choices[0]["text"]
)
else:
response = request_json(
f"{server_url}/v2/models/{model_path}/generate",
{
"text_input": "Explain one benefit of GPU memory coalescing.",
args.triton_max_token_field: args.max_tokens,
},
)
text_output = response.get("text_output")
response_valid = isinstance(text_output, str) and bool(text_output)
elapsed_ms = (time.perf_counter() - start) * 1000
if not response_valid:
raise SystemExit(f"{args.protocol} response did not contain generated text.")
usage = response.get("usage", {})
# Save the actual measurements together with their correctness checks.
target = write_result(
args,
lab_id="30_engine_profile",
environment={
"client": "standard-library HTTP",
"engine_runtime": "server-owned",
},
measurements={
"protocol": args.protocol,
"model_count": model_count,
"triton_max_token_field": (
args.triton_max_token_field if args.protocol == "triton" else None
),
"triton_repository_profile": (
args.triton_repository_profile if args.protocol == "triton" else None
),
"elapsed_ms": round(elapsed_ms, 3),
"usage": usage,
"response_text_published": False,
"trials_required_for_public_claim": 3,
},
correctness={"response_has_generated_text": True},
)
print(f"Wrote engine-client evidence: {target}")
if __name__ == "__main__":
main()
# Normal execution
sbatch slurm/30_engine_profile.sbatch Qwen/Qwen2.5-0.5B-Instruct 7ae557604adf67be50417f59c2c2f167def9a775 --workload small
# Optional profiling
sbatch slurm/30_engine_profile.sbatch Qwen/Qwen2.5-0.5B-Instruct 7ae557604adf67be50417f59c2c2f167def9a775 --workload small --profiler all
Lab 32: Build a causal attention optimization report
This capstone deliberately reuses Lab 24's explicit-attention versus SDPA comparison with the same BF16 tensors and mathematical mask. Lab 24 establishes backend and numerical behavior; the new competency here is making a defensible decision from independent trials, reversed variant order and an aggregate result that passes evidence validation.
Complete source: labs/32_inference_capstone.py
"""Measure one fresh-process attention capstone trial for a later decision."""
from __future__ import annotations
import argparse
import math
from common import (
add_common_args,
cuda_times_ms,
load_torch,
require_course_gpu,
seed_everything,
summarize_ms,
validate_common_args,
write_result,
)
from course_evidence import annotated_operation
def main() -> None:
parser = argparse.ArgumentParser(description=__doc__)
add_common_args(parser)
parser.add_argument(
"--variant-order",
choices=("baseline-first", "candidate-first"),
required=True,
help="Counterbalanced order selected by the three-trial launcher.",
)
# Read the experiment controls before allocating inputs.
args = parser.parse_args()
validate_common_args(args)
torch = load_torch()
environment = require_course_gpu(torch)
# Keep random inputs repeatable across comparable runs.
seed_everything(torch, args.seed)
sequence = 256 if args.workload == "small" else 2_048
# Create the synthetic tensors used by this experiment.
query = torch.randn((1, 8, sequence, 64), device="cuda", dtype=torch.bfloat16)
key = torch.randn_like(query)
value = torch.randn_like(query)
mask = torch.ones((sequence, sequence), device="cuda", dtype=torch.bool).tril()
def baseline() -> object:
scores = (query @ key.transpose(-2, -1)) / math.sqrt(64)
scores = scores.masked_fill(~mask, float("-inf"))
return torch.softmax(scores, dim=-1) @ value
def candidate() -> object:
return torch.nn.functional.scaled_dot_product_attention(
query, key, value, is_causal=True
)
reference = baseline()
observed = candidate()
close = bool(torch.allclose(reference, observed, rtol=1e-2, atol=1e-2))
if not close:
raise SystemExit("The SDPA capstone trial failed output equivalence.")
order = (
("materialized", "sdpa")
if args.variant_order == "baseline-first"
else ("sdpa", "materialized")
)
operations = {"materialized": baseline, "sdpa": candidate}
timing: dict[str, dict[str, float]] = {}
incremental_peak: dict[str, int] = {}
for name in order:
timing[name] = summarize_ms(
cuda_times_ms(
torch,
operations[name],
warmup=args.warmup,
iterations=args.iterations,
)
)
torch.cuda.empty_cache()
memory_before = int(torch.cuda.memory_allocated())
torch.cuda.reset_peak_memory_stats()
operations[name]()
# Wait for queued GPU work to finish at this measurement boundary.
torch.cuda.synchronize()
incremental_peak[name] = int(torch.cuda.max_memory_allocated()) - memory_before
provisional_observation = (
"sdpa-median-lower-in-this-trial"
if timing["sdpa"]["median_ms"] < timing["materialized"]["median_ms"]
else "sdpa-median-not-lower-in-this-trial"
)
# Save the actual measurements together with their correctness checks.
target_path = write_result(
args,
lab_id="32_inference_capstone",
environment=environment,
measurements={
"isl": sequence,
"osl": 1,
"concurrency": 1,
"warmup": args.warmup,
"iterations": args.iterations,
"trial_kind": "one fresh Python process",
"variant_order": args.variant_order,
"timing": timing,
"incremental_peak_bytes": incremental_peak,
"max_abs_error": round(
float((reference.float() - observed.float()).abs().max()), 6
),
"provisional_observation": provisional_observation,
"publication_decision": "pending three independent run records",
"service_claim": (
"not made; live engine TTFT, ITL, throughput, and quality "
"remain separate"
),
},
correctness={"output_allclose": True, "rtol": 1e-2, "atol": 1e-2},
)
print(f"Wrote one inference capstone trial: {target_path}")
if __name__ == "__main__":
annotated_operation(main, "lab_workload")()
# Normal execution
sbatch slurm/32_inference_capstone.sbatch --workload small --variant-order baseline-first
# Optional profiling
sbatch slurm/32_inference_capstone.sbatch --workload small --variant-order baseline-first --profiler all
Lab 33: Check greedy equivalence in a speculative engine campaign
Real-engine speculation must preserve the intended target output before a throughput comparison is accepted. This optional lab sends a fixed greedy workload to one engine variant and records private response digests.
"""Record private greedy-output digests from a loopback serving-engine variant."""
from __future__ import annotations
import argparse
import hashlib
import json
import urllib.parse
import urllib.request
from pathlib import Path
from common import require_hf_commit_revision, resolve_run_id, write_json_exclusive
from course_evidence import begin_experiment
def main() -> None:
parser = argparse.ArgumentParser(description=__doc__)
parser.add_argument("--base-url", default="http://127.0.0.1:8000")
parser.add_argument("--model", required=True)
parser.add_argument("--target-revision", required=True)
parser.add_argument("--draft-model", required=True)
parser.add_argument("--draft-revision", required=True)
parser.add_argument(
"--variant", choices=("target-only", "speculative"), required=True
)
parser.add_argument("--requests", type=int, default=4)
parser.add_argument("--output", type=Path, required=True)
# Read the experiment controls before allocating inputs.
args = parser.parse_args()
begin_experiment(args)
require_hf_commit_revision(args.target_revision, option="--target-revision")
require_hf_commit_revision(args.draft_revision, option="--draft-revision")
parsed = urllib.parse.urlparse(args.base_url)
if parsed.scheme != "http" or parsed.hostname not in {
"127.0.0.1",
"localhost",
"::1",
}:
raise SystemExit("This client only connects to a loopback HTTP endpoint.")
if args.requests < 1:
raise SystemExit("--requests must be positive")
endpoint = args.base_url.rstrip("/") + "/v1/completions"
response_digests = []
for index in range(args.requests):
payload = json.dumps(
{
"model": args.model,
"prompt": (
f"Case {index}: explain one controlled GPU benchmark rule "
"in exactly two short sentences."
),
"max_tokens": 64,
"temperature": 0,
"seed": 17,
}
).encode()
request = urllib.request.Request(
endpoint,
data=payload,
headers={"Content-Type": "application/json"},
method="POST",
)
with urllib.request.urlopen(request, timeout=120) as response:
body = json.loads(response.read())
choices = body.get("choices", [])
if not choices or not choices[0].get("text"):
raise SystemExit("A greedy request returned no generated text.")
response_digests.append(
hashlib.sha256(choices[0]["text"].encode("utf-8")).hexdigest()
)
result = {
"schema": "gpu-course-result/v1",
"lab_id": "33_speculative_engine_client",
"run_id": resolve_run_id(),
"measurements": {
"variant": args.variant,
"model": args.model,
"target_revision": args.target_revision,
"draft_model": args.draft_model,
"draft_revision": args.draft_revision,
"requests": args.requests,
"response_digests": response_digests,
"response_text_published": False,
},
"correctness": {
"all_responses_nonempty": True,
"greedy_equivalence_requires_launcher_pair_comparison": True,
},
}
# Write this run’s evidence without overwriting an earlier result.
write_json_exclusive(args.output, result)
print(f"Wrote private {args.variant} output digests: {args.output}")
if __name__ == "__main__":
main()
# Normal execution
sbatch slurm/33_speculative_engine_client.sbatch --workload small
# Optional profiling
sbatch slurm/33_speculative_engine_client.sbatch --workload small --profiler all
Lab 34: Preserve outputs while changing a serving policy
A scheduling or caching policy should not silently change the intended greedy response while appearing to improve latency. This lab collects greedy response digests for one policy variant.
"""Hash private greedy outputs before accepting a serving-policy comparison."""
from __future__ import annotations
import argparse
import hashlib
import json
import urllib.parse
import urllib.request
from pathlib import Path
from common import require_hf_commit_revision, resolve_run_id, write_json_exclusive
from course_evidence import begin_experiment
def main() -> None:
parser = argparse.ArgumentParser(description=__doc__)
parser.add_argument("--base-url", default="http://127.0.0.1:8000")
parser.add_argument("--model", required=True)
parser.add_argument("--revision", required=True)
parser.add_argument(
"--workload", choices=("prefix-cache", "chunked-prefill"), required=True
)
parser.add_argument("--variant", required=True)
parser.add_argument("--output", type=Path, required=True)
# Read the experiment controls before allocating inputs.
args = parser.parse_args()
begin_experiment(args)
require_hf_commit_revision(args.revision)
parsed = urllib.parse.urlparse(args.base_url)
if parsed.scheme != "http" or parsed.hostname not in {
"127.0.0.1",
"localhost",
"::1",
}:
raise SystemExit("This client only connects to a loopback HTTP endpoint.")
if args.workload == "prefix-cache":
shared = "A controlled cache comparison preserves exact tokens. " * 96
prompts = [f"{shared} Case {index}." for index in range(4)]
else:
shared = "A long prompt exercises bounded prefill scheduling. " * 128
prompts = [f"{shared} Case {index}." for index in range(4)]
endpoint = args.base_url.rstrip("/") + "/v1/completions"
digests = []
for prompt in prompts:
request = urllib.request.Request(
endpoint,
data=json.dumps(
{
"model": args.model,
"prompt": prompt,
"max_tokens": 32,
"temperature": 0,
"seed": 17,
}
).encode(),
headers={"Content-Type": "application/json"},
method="POST",
)
with urllib.request.urlopen(request, timeout=120) as response:
body = json.loads(response.read())
choices = body.get("choices", [])
if not choices or not choices[0].get("text"):
raise SystemExit("A greedy equivalence request returned no text.")
digests.append(hashlib.sha256(choices[0]["text"].encode()).hexdigest())
# Write this run’s evidence without overwriting an earlier result.
write_json_exclusive(
args.output,
{
"schema": "gpu-course-result/v1",
"lab_id": "34_policy_equivalence_client",
"run_id": resolve_run_id(),
"measurements": {
"model": args.model,
"revision": args.revision,
"workload": args.workload,
"variant": args.variant,
"response_digests": digests,
"response_text_published": False,
},
"correctness": {"all_greedy_responses_nonempty": True},
},
)
print(f"Wrote private {args.workload}/{args.variant} output digests: {args.output}")
if __name__ == "__main__":
main()
# Normal execution
sbatch slurm/34_policy_equivalence_client.sbatch --workload small
# Optional profiling
sbatch slurm/34_policy_equivalence_client.sbatch --workload small --profiler all
This exercise shows how repeated predictions create a token sequence while the model's parameters stay unchanged. It uses an explicit four-token vocabulary and a fixed table of next-token scores, so every decision can be checked by hand. Normal execution defaults to CPU; use --device cuda for the optional GPU path, which external diagnostics capture.
Complete source: labs/35_inference_basics.py
"""Trace a fixed four-token autoregressive model without downloads or an engine."""
from __future__ import annotations
import argparse
from typing import Any
from common import (
add_common_args,
load_torch,
require_course_gpu,
validate_common_args,
write_result,
)
from course_evidence import annotated_operation
def run_experiment(torch: Any, device: str, max_new_tokens: int) -> dict[str, Any]:
if max_new_tokens < 1:
raise ValueError("max_new_tokens must be positive")
vocabulary = ["I", "like", "GPUs", "<eos>"]
# A fixed bigram score table, not a transformer or a KV-cache implementation.
model = torch.nn.Embedding(4, 4, device=device)
with torch.no_grad():
model.weight.copy_(
torch.tensor(
[
[-2.0, 4.0, -2.0, -2.0],
[-2.0, -2.0, 4.0, -2.0],
[-2.0, -2.0, -2.0, 4.0],
[-2.0, -2.0, -2.0, 4.0],
],
device=device,
)
)
model.eval()
before = model.weight.detach().clone()
current = 0
generated = []
steps = []
stop_reason = "length"
with torch.inference_mode():
for _ in range(max_new_tokens):
# Create explicit input values on the selected device.
logits = model(torch.tensor(current, device=device))
probabilities = logits.softmax(dim=-1)
chosen = int(probabilities.argmax())
steps.append(
{
"input_token": vocabulary[current],
"logits": logits.cpu().tolist(),
"probabilities": probabilities.cpu().tolist(),
"chosen_token": vocabulary[chosen],
}
)
generated.append(vocabulary[chosen])
if chosen == 3:
stop_reason = "eos"
break
current = chosen
unchanged = bool(torch.equal(model.weight.detach(), before))
gradients_created = any(
parameter.grad is not None for parameter in model.parameters()
)
expected = ["like", "GPUs", "<eos>"][:max_new_tokens]
if generated != expected or not unchanged or gradients_created:
raise AssertionError("Fixed-parameter generation contract failed")
return {
"prompt_tokens": ["I"],
"generated_tokens": generated,
"steps": steps,
"stop_reason": stop_reason,
"parameters_unchanged": unchanged,
"gradients_created": gradients_created,
"scope": "fixed bigram mechanics; no attention, KV cache, TTFT or serving benchmark",
}
def main() -> None:
parser = argparse.ArgumentParser(description=__doc__)
add_common_args(parser, include_measurement=False)
parser.add_argument("--device", choices=("cpu", "cuda"), default="cpu")
parser.add_argument("--max-new-tokens", type=int, default=5)
# Read the experiment controls before allocating inputs.
args = parser.parse_args()
if args.max_new_tokens < 1:
parser.error("--max-new-tokens must be positive")
validate_common_args(args)
torch = load_torch()
environment = (
require_course_gpu(torch)
if args.device == "cuda"
else {"device": "cpu", "torch_version": torch.__version__}
)
operation = annotated_operation(run_experiment, "lab_workload")
measurements = operation(torch, args.device, args.max_new_tokens)
# Save the actual measurements together with their correctness checks.
target = write_result(
args,
lab_id="35_inference_basics",
environment=environment,
measurements=measurements,
correctness={
"expected_token_sequence": True,
"parameters_unchanged": True,
"no_gradients": True,
},
)
print(f"Completed inference-mechanics experiment: {target}")
if __name__ == "__main__":
main()
# Normal execution
sbatch slurm/35_inference_basics.sbatch --device cpu --workload small
# Optional profiling
sbatch slurm/35_inference_basics.sbatch --workload small --profiler all
Lab 36: Model KV retention and restore decisions
A reusable prefix is valuable only if compatible cached state survives until the next request and restoring it is worthwhile. This CPU lab models those decisions explicitly.
Complete source: labs/36_kv_tiering.py
"""Model KV-prefix retention, expiry and restore cost without storage I/O or an engine."""
from __future__ import annotations
import argparse
from collections import OrderedDict
from dataclasses import dataclass
import math
from typing import Any
from common import add_common_args, validate_common_args, write_result
@dataclass(frozen=True)
class Policy:
capacities: tuple[int, int, int] = (2, 2, 8)
ttl_ms: float = 500.0
prefix_bytes: int = 4 * 2**20
prefill_ms: float = 8.0
host_gbps: float = 20.0
storage_gbps: float = 2.0
latency_ms: float = 0.2
def __post_init__(self) -> None:
if len(self.capacities) != 3 or any(
type(c) is not int or not 0 <= c <= 1024 for c in self.capacities
):
raise ValueError("Provide three capacities from 0 through 1024")
if type(self.prefix_bytes) is not int or not 1 <= self.prefix_bytes <= 2**40:
raise ValueError("Prefix bytes must be an integer from 1 through 2**40")
for value in (self.ttl_ms, self.prefill_ms, self.host_gbps, self.storage_gbps):
if not math.isfinite(value) or not 1e-6 <= value <= 1e9:
raise ValueError(
"TTL, prefill and bandwidth must be finite values in 1e-6..1e9"
)
if not math.isfinite(self.latency_ms) or not 0 <= self.latency_ms <= 1e9:
raise ValueError("Latency must be finite and nonnegative")
def transfer_ms(self, tier: int) -> float:
if tier == 0:
return 0.0
rate = self.host_gbps if tier == 1 else self.storage_gbps
# GB/s is decimal, bytes are bytes; result is milliseconds.
return self.latency_ms + self.prefix_bytes / (rate * 1e9) * 1000
class TierCache:
"""Exclusive whole-prefix LRU tiers; only inactive, reusable entries exist."""
def __init__(self, policy: Policy) -> None:
self.policy = policy
self.tiers: list[OrderedDict[tuple[str, int], float]] = [
OrderedDict() for _ in range(3)
]
self.last_time = -1.0
def assert_invariants(self) -> None:
keys = [key for tier in self.tiers for key in tier]
if len(set(keys)) != len(keys):
raise RuntimeError("A prefix is owned by multiple exclusive tiers")
if any(
len(tier) > capacity
for tier, capacity in zip(self.tiers, self.policy.capacities, strict=True)
):
raise RuntimeError("Cache capacity exceeded")
def restart_worker(self) -> None:
self.tiers[0].clear()
self.tiers[1].clear()
def insert(
self, key: tuple[str, int], expires: float, tier_index: int = 0
) -> tuple[int, float, int]:
if tier_index == 3:
return 0, 0.0, 1
if self.policy.capacities[tier_index] == 0:
return self.insert(key, expires, tier_index + 1)
tier = self.tiers[tier_index]
bytes_written = self.policy.prefix_bytes if tier_index > 0 else 0
write_ms = self.policy.transfer_ms(tier_index)
evictions = 0
if len(tier) == self.policy.capacities[tier_index]:
evicted, deadline = tier.popitem(last=False)
extra_bytes, extra_ms, evictions = self.insert(
evicted, deadline, tier_index + 1
)
bytes_written += extra_bytes
write_ms += extra_ms
tier[key] = expires
return bytes_written, write_ms, evictions
def access(self, namespace: str, prefix: int, now_ms: float) -> dict[str, Any]:
if not namespace or type(prefix) is not int or prefix < 0:
raise ValueError(
"A nonempty cache identity and nonnegative prefix ID are required"
)
if not math.isfinite(now_ms) or now_ms < 0 or now_ms < self.last_time:
raise ValueError(
"Arrival time must be finite, nonnegative and nondecreasing"
)
self.last_time = now_ms
expired = 0
for tier in self.tiers:
for key in list(tier):
if tier[key] <= now_ms:
del tier[key]
expired += 1
key = (namespace, prefix)
found = next((i for i, tier in enumerate(self.tiers) if key in tier), None)
if found is not None:
del self.tiers[found][key]
restore_ms = self.policy.transfer_ms(found) if found is not None else None
reuse = restore_ms is not None and restore_ms < self.policy.prefill_ms
cost = restore_ms if reuse else self.policy.prefill_ms
read_bytes = self.policy.prefix_bytes if reuse and found != 0 else 0
write_bytes, write_ms, evictions = self.insert(key, now_ms + self.policy.ttl_ms)
self.assert_invariants()
return {
"prefix": prefix,
"namespace": namespace,
"arrival_ms": now_ms,
"found_tier": ("device", "host", "storage")[found]
if found is not None
else "miss",
"decision": "reuse" if reuse else "recompute",
"modeled_foreground_ms": cost,
"modeled_write_service_ms": write_ms,
"read_bytes": read_bytes,
"write_bytes": write_bytes,
"expired_prefixes": expired,
"capacity_evictions": evictions,
"tier_occupancy_prefixes": [len(tier) for tier in self.tiers],
}
def simulate(
policy: Policy,
*,
prefixes: int,
rounds: int,
gap_ms: float,
restart_at: int = -1,
revision_change_at: int = -1,
) -> dict[str, Any]:
if not 1 <= prefixes <= 128 or not 1 <= rounds <= 20:
raise ValueError("Use 1..128 prefixes and 1..20 rounds")
if not math.isfinite(gap_ms) or not 0 <= gap_ms <= 1e9:
raise ValueError("Gap must be finite and nonnegative <= 1e9")
count = prefixes * rounds
if any(
value != -1 and not 0 <= value < count
for value in (restart_at, revision_change_at)
):
raise ValueError(
"Restart/revision index must be -1 or an existing request index"
)
cache = TierCache(policy)
records = []
for index in range(count):
if index == restart_at:
cache.restart_worker()
namespace = (
"model-B"
if revision_change_at >= 0 and index >= revision_change_at
else "model-A"
)
row = cache.access(namespace, index % prefixes, index * gap_ms)
row["worker_restart"] = index == restart_at
records.append(row)
return {
"evidence_kind": "deterministic_policy_model",
"requests": records,
"reuse_fraction": sum(row["decision"] == "reuse" for row in records) / count,
"modeled_foreground_total_ms": sum(
row["modeled_foreground_ms"] for row in records
),
"modeled_write_service_total_ms": sum(
row["modeled_write_service_ms"] for row in records
),
"no_cache_prefill_total_ms": count * policy.prefill_ms,
"read_bytes": sum(row["read_bytes"] for row in records),
"write_bytes": sum(row["write_bytes"] for row in records),
"boundary": "whole inactive prefixes, exclusive tiers, fixed arrival times and declared costs; no queueing, decode, live TTFT or GDS measurement",
}
def main() -> None:
parser = argparse.ArgumentParser(description=__doc__)
add_common_args(parser, include_measurement=False)
parser.add_argument("--device-prefixes", type=int, default=2)
parser.add_argument("--host-prefixes", type=int, default=2)
parser.add_argument("--storage-prefixes", type=int, default=8)
parser.add_argument("--prefixes", type=int, default=6)
parser.add_argument("--rounds", type=int, default=3)
parser.add_argument("--ttl-ms", type=float, default=500)
parser.add_argument("--gap-ms", type=float, default=50)
parser.add_argument("--prefix-mib", type=int, default=4)
parser.add_argument("--prefill-ms", type=float, default=8)
parser.add_argument("--host-gbps", type=float, default=20)
parser.add_argument("--storage-gbps", type=float, default=2)
parser.add_argument("--latency-ms", type=float, default=0.2)
parser.add_argument("--restart-at", type=int, default=-1)
parser.add_argument("--revision-change-at", type=int, default=-1)
# Read the experiment controls before allocating inputs.
args = parser.parse_args()
validate_common_args(args)
try:
policy = Policy(
capacities=(
args.device_prefixes,
args.host_prefixes,
args.storage_prefixes,
),
ttl_ms=args.ttl_ms,
prefix_bytes=args.prefix_mib * 2**20,
prefill_ms=args.prefill_ms,
host_gbps=args.host_gbps,
storage_gbps=args.storage_gbps,
latency_ms=args.latency_ms,
)
measurements = simulate(
policy,
prefixes=args.prefixes,
rounds=args.rounds,
gap_ms=args.gap_ms,
restart_at=args.restart_at,
revision_change_at=args.revision_change_at,
)
except ValueError as exc:
parser.error(str(exc))
measurements["policy"] = vars(policy)
# Save the actual measurements together with their correctness checks.
target = write_result(
args,
lab_id="36_kv_tiering",
environment={"execution": "CPU model; no CUDA, engine or storage access"},
measurements=measurements,
correctness={"exclusive_ownership_and_capacity": True},
)
print(f"Completed modeled KV policy: {target}")
if __name__ == "__main__":
main()
# Normal execution
sbatch slurm/36_kv_tiering.sbatch --host-prefixes 0 --storage-prefixes 0 --workload small
# Optional profiling
sbatch slurm/36_kv_tiering.sbatch --host-prefixes 0 --storage-prefixes 0 --workload small --profiler all
Follow a request from model artifacts and tokens to generation, cache use and serving. Take GPU Fundamentals and GPU Performance Optimization first. Use GPU Performance Tools for profiling and PyTorch for GPU Performance Engineering for a tensor-reading refresher.
Learning route
Audit artifacts, follow generation and sampling, estimate cache capacity, then define the workload. Learn engine readiness and client metrics before comparing scheduling, quantization or speculation.
Begin with Lab 35's download-free CPU generation exercise: "$COURSE_PYTHON" labs/35_inference_basics.py --device cpu in the mechanics runtime.
After Lesson 5, fix the model, sampling contract, cache estimate and workload.
After Lesson 7, distinguish client latency from model-forward time; try the introductory AIPerf profile through Lab 15’s --experiment aiperf route before a policy comparison.
Change scheduling, backend or precision one at a time. CPU cache models and mechanics experiments do not establish live serving performance.
Before the first lab
Complete the Lab Guide and check Versions and environment. Use the approved runtime on one full H100; a qualified advanced cluster can also supply one-GPU allocations.
sbatch slurm/09_hf_prefill_decode.sbatch --workload small
Lab 16 needs online Hub metadata access even when artifacts are cached. Keep that exception separate from the other offline runs.
Serving runtime preparation
Mechanics uses requirements-mechanics.txt; lightweight clients use requirements-serving.txt. Native vLLM and AIPerf keep separate prepared environments and vendor-matched dependencies. The Lab Guide's single setup command prepares these environments and their declared model artifacts, including Lab 33's larger target model. Jobs restore their saved runtime and private caches automatically.
TensorRT-LLM/Triton and Dynamo exercises are optional, with dependencies included in default preparation. Their prepared artifacts need their own readiness, response-correctness and GPU checks; preparation does not build a GPU engine or qualify serving performance.
Native Nsight Systems serving captures wait for graceful server shutdown and report export. The 900-second watchdog still fails the job if its deadline expires, even when the server writes a report while stopping. Inspect both the server log and its .watchdog companion when capture shutdown fails.
Completion
Keep mechanics and serving evidence separate. Use Lab 32's trials experiment for at least three equivalent-work, unprofiled runs and a quality/latency/memory decision. Qualify real engines independently. Lesson 17's Advanced Lab 25 compares synthetic recurrent projections, not a complete model server or pipeline-parallel layouts. Distributed serving belongs to Advanced Labs; optional real-model and Dynamo experiments are not a core completion gate.
All 22 practical labs completed both small and large profiles (44 verified exports) on the prepared NVIDIA H200 cluster. See lab results and the catalog validation record for evidence scope and limitations.
Recorded mechanics runs include PyTorch 2.14.0+cu130 and 2.13.0+cu130, both with CUDA runtime 13.0. Serving profiles use their own prepared environments; an empty software field in an export is not evidence of a particular engine or framework version. CPU-only lessons remain CPU evidence.
The observed profiler CLI/viewer pairs were Nsight Systems 2026.4.1 and Nsight Compute 2026.2.1; the scheduler reported Slurm 25.11.3. These runs qualify the recorded experiments in their prepared environments. They do not establish a clean installation, every optional extension, or performance on H100.
H100 target and installation candidates
The following targets and pending checks describe the H100 teaching environment. Keep them separate from the completed H200 evidence above.
The introductory Lab 35 was executed locally on CPU with an existing PyTorch 2.13.0 environment. This is algorithmic smoke evidence only: it does not qualify the separate mechanics/serving environments, authorize a dependency fallback or establish CUDA/H100 behavior. It downloads no model or engine.
Component
Course target
Evidence status
Python
3.12
Local serving environment exists; cluster parity pending
PyTorch
2.14.0 mechanics-manifest authority
Clean Linux/H100 install and qualification pending; no fallback approved
Transformers
Pinned mechanics candidate set
Target installation and joint compatibility pending
Native vLLM
0.28.0
Linux/H100 install and engine activation pending
TensorRT-LLM and Triton
Pinned container for an optional exercise; included in default preparation
Installation and target qualification are separate
Native AIPerf
0.12.0
Target qualification pending
Dynamo container preflight
Pinned container for an optional exercise; included in default preparation
Deferred pending transport/topology qualification
For optional containers, do not substitute an unqualified “latest” image. Once validated, record the full immutable digest, model revision, driver, runtime, and launch arguments.
KV-retention policy qualification
Lab 36 uses only Python standard-library code and course result helpers. Its capacities, transfer rates and prefill costs are declared modeling inputs, not measurements. Running the model does not qualify CUDA, a serving engine, persistent KV recovery or a GPUDirect Storage path.
Shared profiling qualification
Use the Lab Guide for the preparation and cluster-managed profiling route. Keep the matching CLI/viewer identities recorded with each run. Installation does not qualify the driver, either worker, the selected native runtime or optional container, or hardware-counter access; those claims require the relevant canaries and report inspections. Keep the existing AI runtime identities above; changing a profiler does not authorize changing those environments or adding collectors and metrics databases.
Prepared H200 runtime and applicable live profiler captures are recorded above. This campaign did not rerun the complete infrastructure installer or qualify the H100 target.
Advanced fabric qualification
The documented base target uses two one-H100 workers; all distributed GPU experiments now belong to the separate two-eight-H100 route. Eight-/sixteen-rank launchers require full devices with MIG disabled, NVLink peer paths and active InfiniBand. Physical topology checks do not replace Fabric Manager health, MPI/NCCL compatibility or GPUDirect registration qualification. No live 16-H100 qualification is claimed by these source changes.
The advanced course owns these fabric experiments and their selected native tool dependencies. Use the Lab Guide for preparation, retain the component build receipts, and qualify the same runtime on both nodes before accepting a comparison.
Readiness checks
Hardware scope: local GPU checks use one full, non-MIG H100. A qualified advanced cluster can supply one-GPU allocations. Distributed work follows the advanced course's separate fabric qualification.
This is a target-qualification checklist, not the lesson execution order. Follow the course for the learning route and complete each exercise's relevant safety/setup gate before running it. Distributed and optional checks qualify those paths; they are not prerequisites for earlier single-GPU lessons that do not use them.
Run from this course root after the Lab Guide has prepared the available lab software. Check its completion summary for failures or hardware skips affecting the selected lab. Launchers restore the saved runtime automatically; VERSIONS.md describes its scope. Preparation creates private log directories before Slurm opens its output. For these read-only local dependency checks, select the ordinary lab runtime:
Raw model data, prompts, outputs, Slurm logs, server logs, metrics, and profiler reports remain private. Fill in benchmark-record.md and follow evidence-security.md before sharing aggregates.
Allocation and artifact identity
sbatch slurm/16_model_artifact_audit.sbatch --workload small
Require a full non-MIG H100, compute capability 9.0, immutable model/tokenizer identity, compatible configuration and weights, and the stated remote-code policy. Separate artifact resolution, CPU staging, GPU loading, warm-up, and readiness. Reaching readiness does not establish request correctness. Lab 16 checks the local H100 and needs online Hub metadata access even when model artifacts are cached.
Generation and cache semantics
sbatch slurm/35_inference_basics.sbatch --device cuda
sbatch slurm/08_kv_cache.sbatch --workload small
sbatch slurm/09_hf_prefill_decode.sbatch --workload small
sbatch slurm/17_sampling_semantics.sbatch --workload small
sbatch slurm/18_padding_bucketing.sbatch --workload small
sbatch slurm/23_speculative_decoding.sbatch --workload small
sbatch slurm/24_sdpa_attention.sbatch --workload small
Lab 35 can first be studied with --device cpu without downloads or an engine. Require the declared token sequence, EOS/length stopping and unchanged parameters. Its fixed table contains no attention or KV cache and its CPU result does not qualify the H100 path or serving performance.
Require cache/no-cache agreement and fixed decoding semantics. Lab 09 checks the requested new-token count, attention mask, cache position, and advancing cache length. The synthetic speculative lab must match the target-greedy sequence and exercise partial rejection, recovery, and full-acceptance bonus paths. High acceptance must reduce target forward calls, while the low-acceptance control must demonstrate why proposal overhead can remove that benefit. It is not real-engine speedup evidence. SDPA comparisons hold mask, shape, dtype, and correctness tolerances fixed.
Workload, capacity, and scheduling mechanics
sbatch slurm/25_workload_metrics.sbatch --workload small
sbatch slurm/26_kv_capacity.sbatch --workload small
sbatch slurm/27_paged_kv.sbatch --workload small
sbatch slurm/28_continuous_batching.sbatch --workload small
sbatch slurm/29_quantization.sbatch --workload small
Define ISL/OSL, arrival pattern, concurrency, TTFT/ITL timestamp endpoints and AIPerf aggregation conventions, and output tokens for the later live campaign. Lab 25 itself measures synthetic projection and recurrent operator work, with batch rows rather than service requests and no generated tokens or TTFT/ITL. Check MHA/GQA/MQA arithmetic, allocation/recycling invariants, and scheduler semantics before live-engine comparisons. Lab 29 must pass its declared tensor-error gates; inspect its logical byte counts and timing observations separately. Actual resident-memory savings, service latency and model quality require a qualified engine experiment; smaller weights alone do not establish a faster service.
Lab 36 is a separate local policy gate with no GPU or serving engine requirement:
Hold the arrival sequence and capacities fixed. Verify TTL expiry, LRU demotion, namespace isolation and restore-versus-recompute decisions using the complete guide's restart and revision controls. Record modeled foreground and write costs separately. Neither modeled hits nor assumed bandwidth prove real KV persistence, GPUDirect Storage activation, TTFT or storage performance.
One-GPU serving and streaming
sbatch slurm/10_vllm_offline.sbatch --workload small
sbatch slurm/11_serving_client.sbatch
sbatch slurm/15_streaming_client.sbatch
sbatch slurm/20_prefix_cache_client.sbatch
Use the launchers' documented model and immutable revision inputs. Keep cold startup separate from steady state. Offline vLLM must aggregate all measured requests, prompt and output tokens, and the full measured-window throughput. Serving launchers retain Prometheus snapshots and request failures. For prefix A/B, compare prompt-token cohorts within the lab's declared 0.8–1.2 median-count ratio and report the actual ratio. Inspect cache queries/hits rather than assuming visible repeated text guarantees reuse. Streaming chunks do not necessarily correspond one-to-one with model tokens.
Engine qualification and causal report
Inspect the specialized launcher selections, submit the introductory AIPerf comparison, and run the local capstone trials:
Lab 30 owns TensorRT-LLM/Triton profiling; Lab 15’s --experiment aiperf route owns the introductory AIPerf comparison from Lesson 7. The submission above starts the pinned default model on loopback, runs a bounded streaming profile, and stops the server. It needs the prepared serving runtime. The default Lab 15 submission uses the supplied streaming client. The separate Dynamo preflight checks conditional qualification. Real-engine speculative decoding is optional and requires compatible target/draft artifacts. Dynamo disaggregation remains an advanced exercise with capacity, transport, and routing prerequisites.
Keep three independent attention-capstone records with matching shapes, numerical checks, timing distributions, memory observations and a profiler-backed explanation. For a separately qualified serving campaign, also retain throughput/latency curves, queue/KV/preemption evidence, errors and quality checks. Preserve the rejected hypothesis and counterbalance baseline/candidate trial order. Record unsupported engine or topology gates as pending rather than substituting simulation or CPU mechanics for live serving proof.
Distributed practice
Use Advanced Labs for placement, transport, collective and application checks on its qualified two-worker, sixteen-H100 fabric. Follow its lab-specific acceptance criteria; two one-GPU TCP workers do not establish fabric performance. These checks are not gates for the local experiments above.
Lab mechanisms and evidence
Lab 27: watch physical KV blocks change ownership
Objective: explain allocation, growth, completion and recycling using stable block identities. The paged-KV lab models a pool of physical blocks and a logical block table per request. It does not allocate real engine KV tensors, share prefixes, move data between devices, or benchmark an attention kernel. This small model makes ownership visible before a live engine hides it behind optimized metadata.
Worked lifecycle
Run the smoke lab with --block-tokens 16 --total-blocks 4. Each block stores 16 token positions for one request's modeled KV allocation. A 17-token request needs two blocks: 32 reserved positions, 17 useful positions, 15 unused tail positions. Only the final partial block creates internal waste in this model.
Event
Request A
Request B
Request C
Free physical IDs
Empty pool
—
—
—
0,1,2,3
Admit A with 16 tokens
[0]
—
—
1,2,3
Admit B with 17 tokens
[0]
[1,2]
—
3
Grow A to 17 tokens
[0,3]
[1,2]
—
None
Reject B growth to 65 tokens
[0,3]
[1,2]
—
None
A completes
—
[1,2]
—
0,3
Admit C with 17 tokens
—
[1,2]
[0,3]
None
A's first physical block remains 0 when it grows. Its second logical block maps to physical block 3; physical adjacency is unnecessary. On completion, both blocks return to the free list. C subsequently receives those exact IDs, while B's mapping remains unchanged. This proves recycling more strongly than comparing two unrelated totals of free capacity.
Follow lifecycle_events in the result. Check ownership uniqueness and that used IDs plus free IDs always partition the configured pool.
Inspect the deliberately rejected growth. The length, existing table and free list must all remain unchanged; partial mutation would leak capacity or leave a request claiming tokens it cannot store.
Repeat with another positive block size and at least four total blocks. Explain how rounding waste changes. The demand worksheet for lengths 31,65,127,9 remains a separate arithmetic exercise, not a lifecycle trace.
Inspect live engine memory/cache metrics later; do not treat these Python object counts as measured H100 bytes, allocation overhead, or throughput.
Common failure: confusing a request's logical token offset with a physical block ID, or allowing two unrelated requests to own one block. Production prefix sharing needs reference counts and identity rules not implemented here. Review answer: growth appends only needed pages, release returns owned pages, and failed reservation is atomic. Paging reduces fixed reservation waste but does not remove KV capacity limits.
Lab 28: compare a real policy difference, not two mislabeled chunk sizes
Objective: show why non-preemptible prompt work can delay later requests and how chunking creates admission opportunities. The scheduler lab runs three controlled policies: full prefill, 64-token chunks, and a 256-token chunk-size control. Arrivals, prompts and outputs are identical. Each dispatch prioritizes ready decode tokens before admitting prefill work.
Understand the model clock
One service quantum supplies 256 abstract token-work units. Prefill and decode tokens each cost one unit here. That equality is a teaching simplification: real prefill and decode have different shape, memory and compute costs. Ordinary chunked dispatches have at most 256 units and last one quantum. A full prompt larger than that is admitted alone and runs without interruption for ceil(prompt_tokens / 256) quanta. Arrivals during any dispatch wait until it ends. Tokens become visible at the end, not the beginning, of a dispatch.
Given request A with 2048 prompt tokens arriving at time zero and request B with one prompt token arriving at time one, full prefill occupies time 0–8. B cannot be admitted while it runs. Under 64-token chunking, A processes its first chunk during 0–1; B can join at time one and start producing tokens shortly after its own prefill. Change only the policy. Expected observation: B's first token arrives sooner in modeled time, while A may take more dispatches. This does not predict a numerical H100 TTFT improvement.
The 256-token control still splits a 2048-token prompt into eight chunks. It is therefore chunked, not unchunked. Likewise, counting a full 2048-token prefill as one unit of elapsed time would give it eight times the service capacity for free. The lab charges its occupied quanta explicitly.
Run Lab 28 and inspect each policy's trace: start/end, work units, prefill by request, decode requests, and active request IDs.
Sum scheduled work and verify sum(prompts) + sum(outputs) and complete request counts for all policies. A policy cannot win by dropping work.
Compare arrival-relative first-token latencies, not just absolute timestamps. A late arrival naturally has a later completion time even without queueing.
Explain the maximum contiguous scheduling interval and the chunk-size control. Request-order prefill selection is simple, not a production fairness algorithm; short requests can wait behind earlier requests.
Run slurm/34_policy_equivalence_client.sbatch only in the qualified serving environment to measure actual TTFT, ITL, throughput, quality and memory, using Lesson 7's tool-specific metric definitions. Its independent server restarts and at least three trials per policy are separate evidence from these deterministic mechanics.
See the official vLLM optimization guide for the pinned engine's scheduling controls. This simulator is not a replica of vLLM's scheduler or a replacement for that live A/B experiment.
Review answer: conserve work and offered arrivals, charge occupied service, and separate policy mechanics from measured latency. Smaller chunks create more decision points but can sacrifice batching efficiency and add real launch and scheduler overhead, neither of which is priced by this model.
Keep mechanics, serving and diagnostics separate
Lab 15's streaming client measures closed-loop request latency and requests/s; it does not establish open-loop overload, token throughput or SLO goodput. Its optional AIPerf experiment has separate native exports.
Labs 33–34 put greedy-equivalence evidence on their dashboards; latency and throughput come from native AIPerf exports. Lab 34 compares three fresh-server correctness probes and three trials per policy in counterbalanced order.
Labs 20 and 34 hold batch-invariant execution and TRITON_ATTN fixed. Lab 34 also fixes eager mode; keep the exact-output gate and do not generalize to compiled serving performance.
Lab 30 requires a nonempty text response, not just a healthy endpoint. Its launcher owns startup, the bounded probe and cleanup.
Lab 36 is a CPU cache-retention model: it measures neither TTFT nor storage throughput and does not qualify GPU Direct Storage.
Lab 32's capstone accepts three independent unprofiled mechanics trials with matching environments; it makes no serving claim.
Compute captures in Labs 09, 17 and 23 cover a selected first-invocation matrix operation, not the whole decode or speculative path. Lab 10's diagnostic --in-process mode places engine work in its NVTX range; use the normal engine process mode for clean throughput comparisons. Its Compute job requests extra host memory for kernel replay while keeping the GPU count and workload fixed.
For the chunked-prefill campaign, inspect request activity in every policy's server report. Captures begin after readiness and end after the trial; the existence of a report alone does not prove it contains the measured requests.
Benchmark worksheet
Record model, tokenizer, immutable revisions, engine/image, generation settings, ISL/OSL distribution, concurrency, arrival model, warm-up, completions/failures, TTFT, ITL/TPOT formula, timestamp endpoints, token denominator, percentile population, request and token throughput, goodput objective, weight/KV memory, cache behavior, output/quality checks, profiler evidence, and keep/reject decision. Keep prompts, outputs, raw logs, and host details private.
Comparison worksheet
Copy this worksheet into the private experiment record before changing one factor. Fill both columns for equivalent work; mark unavailable evidence explicitly. Retain raw artifacts privately and publish only separately reviewed aggregates following evidence-security.md.
Field
Baseline
Candidate / observation
Date and random course run ID (keep artifact location private)
To record
To record
Lab, source/commit identity, exact arguments, single change
To record
To record
H100 SKU, node/rank count, MIG state, topology class (no asset IDs)
To record
To record
Approved environment lock or immutable image; driver/CUDA/framework/NCCL/Slurm versions
Lab 28 modeled service quanta, arrival-relative first token, conserved work, full/chunked dispatch trace; not engine milliseconds
To record
To record
Cold startup versus readiness/steady state; replication/TP/PP/EP placement
To record
To record
Lab 36 tier capacities, TTL/LRU, namespace/restart, hit source, modeled foreground/write costs and assumed bandwidth; no engine timing
To record
To record
A faster result is accepted only when its declared correctness, workload, timed operations, and environment constraints all hold. Record rejected hypotheses and slower candidates; they are useful evidence for the next choice.
Evidence and privacy
The course source is designed to be public, but runtime evidence is sensitive by default. Slurm output, checkpoints, model-cache paths, server logs, metrics, and request traces can contain infrastructure identifiers, filesystem paths, model names, prompts, or environment details.
Collect privately
Use synthetic or explicitly public prompts, datasets, and models. Do not use customer prompts, credentials, proprietary model inputs, or regulated data.
Complete software preparation in the Lab Guide and review its completion summary. Follow the Lab Guide’s guidance for any failures or hardware skips before submitting. Its private parent directories protect scheduler logs even when Slurm opens them before the job body starts.
Keep results/, checkpoints, model caches, metrics, server logs, and Slurm output in storage that only approved course participants can read.
Do not pass credentials on command lines or enable shell tracing. Remove unrelated secret-bearing environment variables according to site policy.
Never commit generated evidence. The course .gitignore is not an access-control or redaction boundary.
Shared viewer copies
A successful profiling stage automatically delivers a verified copy of its native reports to the installed Nsight viewer directory. These copies are readable by the existing shared viewer audience; the viewer does not provide per-user report isolation. Submit only workloads whose report contents are approved for that audience. Private originals, logs and other results remain in the job directory. Check viewer_delivery and use the exact viewer paths printed by the job; no manual copy or permission change is needed after sbatch.
Share summaries, not raw artifacts
Before material leaves the approved environment, create a separate summary that excludes:
hostnames, node lists, job IDs, GPU UUIDs, serial numbers, and account or project identifiers;
usernames, home directories, executable paths, internal endpoints, and private repository or model-cache paths;
environment-variable values, tokens, cookies, request headers, credentials, and command lines that expose them;
customer data, private prompts, unpublished model names, raw traces, raw server logs, and generated text that is not explicitly public.
Report only the evidence needed for the learning decision: anonymized run ID, node count, GPU family, software versions, public workload definition, correctness result, aggregate training or serving metrics, and a written interpretation. Redact by creating a new file; do not overwrite the private original.
Course-specific safeguards
JSON, checkpoints, client results, server logs, and metrics use a random run ID instead of a Slurm job ID.
New private artifacts are created exclusively with owner-only permissions; verified viewer copies use the shared access described above.
Serving endpoints are loopback-only; distributed worker traffic still requires a trusted private fabric and site-approved network controls.
The normal course validator performs static validation and does not execute Python labs, load models, start servers, or submit Slurm launchers.
The portable tree rejects generated caches, and launchers disable Python bytecode creation before Python starts.
Live site policy remains authoritative. If model access, serving, or evidence collection is not approved, record a sanitized blocker and ask the cluster owner rather than weakening permissions.
Where to Go Next
These optional directions extend inference mechanics into evolving serving systems and established advanced measurement concepts. They do not change the course's pinned environments or add completion gates. Documentation support is not proof of a working H100 deployment. Start with goodput or kernel selection; approach the distributed topics only after understanding request timelines, cache ownership and transport costs.
Choose one direction and apply the course’s reasoning to a new example. Keep its stated scope and qualification limits in your comparison.
Dynamo cache-aware routing across memory tiers
Cache-aware routing selects a worker using both reusable prefix state and current load. When cached state can move between GPU memory, CPU memory and storage, the router also needs accurate information about where that state resides. Working offload and useful routing visibility are separate capabilities. Investigate: Could offloading succeed while the router remains unaware of the reusable prefix, and how would that change request placement? Scope: Evolving distributed serving. Support is backend/version-specific; development documentation includes planned or incompletely validated paths. Extra capacity and transport must be qualified beyond the two-node baseline. Study KV-aware routing and the offloading support matrix.
FlashInfer and inference-kernel selection
FlashInfer supplies optimized building blocks for attention, matrix multiplication and MoE execution. It is a kernel layer, not a complete replacement for a serving engine. Moving beyond the SDPA lab means checking shape eligibility, cache layout, initialization cost and whether a faster kernel improves whole requests. Investigate: How would you separate first-use compilation, warmed kernel time and end-to-end request latency? Scope: Evolving open-source project; its release page records v0.6.18 on August 29, 2026. H100 is supported, but individual low-bit or architecture-specific paths have narrower requirements. Read FlashInfer's support information and release highlights.
Speculative decoding beyond one draft model
Speculative decoding proposes candidate tokens and uses a target model to verify them. Newer proposal methods use learned draft features, model-specific multi-token prediction (MTP), or repeated token patterns. Their setup costs and acceptance behavior differ, so selecting a method is a workload decision rather than an automatic speedup. Investigate: When could a repetition-based proposal outperform a neural draft, and what happens on nonrepetitive prompts? Scope: Evolving TensorRT-LLM features, including EAGLE 3 and MTP-related paths. Check the exact model, draft, backend and sampling guarantees; a method name alone establishes neither H100 support nor distribution-preserving output. Compare TensorRT-LLM speculative methods.
Quantization-aware distillation with Model Optimizer
Quantization-aware distillation uses a higher-precision teacher's outputs to help a quantized student recover quality lost during compression. It extends post-training quantization evaluation into a deployment decision that also has a training cost. The goal is preserved application behavior, not merely a smaller checkpoint. Investigate: Does recovered benchmark accuracy also preserve the quality of the intended application? Scope: Evolving NVIDIA Model Optimizer workflow. FP8 deployment can target Hopper; native NVFP4 compute targets Blackwell. Budget teacher/student memory and training separately. This is deployment-oriented reading; training mechanics remain owned by the Training course. Study Model Optimizer's QAT and QAD recipes.
Multimodal encode–prefill–decode serving
Multimodal requests may require an encoder to turn images or other inputs into representations the language model consumes. Separating encoding from prefill and decode creates another worker pool, queue and transfer boundary. Text-token throughput alone no longer describes the whole request. Investigate: Where should encoder waiting, execution and transfer time appear in time to first token? Scope: Evolving, model-specific distributed architecture. Backend support differs for input forms such as image URLs and precomputed embeddings. Transport, resource allocation and GPU capacity require separate qualification; this is not a required two-H100 exercise. Read Dynamo's encoder-disaggregation guide.
AIPerf goodput and service-level attainment
Goodput counts acceptable requests completed per unit time. Service-level attainment is the fraction of requests meeting a stated target, such as both time-to-first-token and AIPerf per-request inter-token latency limits. These measures complement aggregate throughput: more acceptable completions per second can coexist with an unacceptable fraction of slow requests. Investigate: Can the highest-goodput configuration fail a requirement that 99% of requests meet every service-level objective (SLO)? Scope: Established measurement distinction in evolving AIPerf tooling, not Blackwell-specific. Use a qualified endpoint and check the client's metric definitions, denominator and version. Study AIPerf goodput and attainment.
Glossary
AIPerf
NVIDIA's current client workflow for measuring generative-AI endpoint latency and throughput under a declared request distribution.
API
Application programming interface; the request and response contract exposed by a service or software component.
Autoregressive generation
Selecting a next token conditioned on preceding tokens, appending it and repeating until a stopping condition is met.
AWQ
Activation-aware Weight Quantization; uses calibration activation statistics to choose weight scaling that protects important channels.
Cache restoration
Making compatible retained KV state available again before attention uses it; this has transfer and reconstruction costs.
Calibration
Using representative data to choose quantization ranges or scales.
Chunked prefill
Processing a long prompt in smaller token segments so a scheduler can interleave that work with other requests.
Closed-loop load
Each client waits for completion before sending again, which can hide overload behind client pacing.
Continuous batching
Admitting and retiring requests between model iterations instead of waiting for a fixed batch to finish together; TensorRT-LLM also calls this in-flight batching or iteration-level batching.
Copy-on-write
Creating a private copy before modifying state that is shared with another owner.
CUDA Graph
A graph of operations and dependencies that can be instantiated and launched repeatedly. CUDA supports explicit construction and stream capture; these labs use PyTorch capture with its storage and operation constraints.
DCGM
NVIDIA Data Center GPU Manager; provides GPU health and telemetry facilities.
Decode
Autoregressive processing after prefill, usually producing one new token per sequence per iteration; also called the generation phase in TensorRT-LLM.
Dequantization
Reconstructing approximate numerical values from quantized codes and their scale metadata.
Detokenization
Converting generated token IDs back into text using the tokenizer’s decoding rules.
Disaggregated serving
Separate prefill and decode worker pools connected by request and KV-state handoff.
DMA
Direct memory access; transfer hardware moves bytes without CPU instructions copying each byte.
DP
Data parallel serving: independent model replicas process different requests; a request does not require gradient synchronization across replicas.
DRAM
Dynamic random-access memory; in the host-offload examples, CPU-side memory that trades GPU capacity relief for transfer and reconstruction costs.
E2E latency
End-to-end latency from the declared request or workload start to completion at the declared observation boundary.
EOS
End-of-sequence token; one possible stopping signal, distinct from an output-length limit or service cancellation.
EP
Expert parallelism; distributing the experts in a mixture-of-experts model across ranks and routing tokens to their owners.
Execution engine
The component that performs model computation and manages execution resources.
FP8
Eight-bit floating-point formats requiring a supported format, scaling recipe and execution path; the name alone does not establish accuracy or speed.
Fragmentation
Storage wasted by an allocation layout, including unused slots in a partially filled block.
Free list
A collection of reusable cache blocks available for allocation.
GDS
GPUDirect Storage; supported direct DMA paths between storage and GPU memory, with CPU-coordinated control work.
Goodput
Completed work that meets declared service objectives.
GPTQ
A post-training weight-quantization method that uses calibration-derived sensitivity information to compensate rounding error by adjusting weights not yet quantized.
GQA/MQA
Grouped-query attention / multi-query attention; layouts with fewer key/value heads than query heads.
Greedy decoding
Choosing the highest-scoring allowed token at each step, rather than randomly sampling from the distribution.
HBM
High-bandwidth memory attached to the GPU and used for model state, activations, workspaces, and caches.
HTTP
Hypertext Transfer Protocol; carries service requests and responses, with protocol completion distinct from the first generated content.
ICL
Inter-chunk latency; gaps between streaming content chunks, which can contain multiple tokens.
Idle TTL
Idle time-to-live; an expiry interval renewed on access in the supplied cache model, with capacity eviction able to remove an entry sooner.
Inference
Using a model's learned parameters to compute outputs for inputs, normally without updating those parameters.
INT8
Eight-bit integer representation used by supported quantization schemes together with scale and, where applicable, zero-point metadata.
ISL/OSL
Input and output sequence lengths used to describe request work.
ITL
Inter-token latency; AIPerf reports a per-request average, with the formula and timestamp convention explained in Lesson 7. Individual token gaps are a different distribution.
JSON
JavaScript Object Notation; the structured text format used for request bodies and result artifacts.
KV cache
Cached attention keys and values from earlier positions, avoiding repeated projection work while consuming memory that grows with active sequence state.
KV-aware routing
Worker selection that combines reusable-prefix state with projected active load.
Length bucketing
Grouping examples or requests with similar token lengths to reduce padding while balancing extra batches and launches.
LLM
Large language model; a model trained to process and generate language tokens.
Logit
An unnormalized model score; softmax converts logits to probabilities.
LoRA
Low-rank adaptation; a task-specific weight update represented by two small matrix factors and added to a fixed base transformation.
LRU eviction
Least recently used eviction; discarding or demoting the eligible cache entry with the oldest access under capacity pressure.
MHA
Multi-head attention; each query head has corresponding key/value heads, unlike the sharing used in GQA or MQA.
Model artifact bundle
The pinned config, tokenizer, generation defaults, weight shards/indexes, model card/license metadata, and optional adapters or quantization data required to reproduce loading and serving.
MoE
Mixture of experts; a model layer that routes tokens to a subset of specialized expert networks.
MTP
Multi-token prediction; a model capability that predicts multiple future positions and may supply proposals for target-verified speculative generation.
Nsight Compute
A kernel profiler used for selected-kernel metrics, including roofline, traffic, instruction, scheduler, stall, and occupancy evidence.
Nsight Systems
A system profiler used to inspect the temporal relationship among CPU work, CUDA APIs, kernels, copies, synchronization, NVTX ranges, and communication.
NVTX
NVIDIA Tools Extension Library, an annotation API for named markers and ranges; it does not synchronize or time GPU work by itself.
Open-loop load
Arrivals generated independently of response completion, exposing queue growth beyond service capacity.
Paged KV cache
Managing KV storage in blocks/pages to reduce fragmentation and support dynamic request scheduling.
PP
Pipeline parallelism; placing different layer ranges on different ranks and scheduling microbatches through the stages.
Preemption
Temporarily suspending a running request to free resources; resumption may require restoring or recomputing KV state. Rejecting a new request is a separate admission decision.
Prefill
Processing prompt tokens to form KV state and the logits for the first output token; also called the context phase in TensorRT-LLM.
Prefix caching
Reusing KV state for an exactly matching reusable prefix under the serving engine's cache rules.
PyTorch Profiler
The framework profiler that attributes CPU and CUDA activity, calls, shapes, memory, and stacks to PyTorch operators.
Quantization
Representing values using a smaller set of numerical levels, with metadata that maps stored codes to approximate original values.
Radix tree
A compressed prefix tree whose edges can represent token sequences, allowing an engine to find reusable shared-prefix state.
RDMA
Remote direct memory access; supported network hardware transfers data between registered memory regions.
Readiness
The ability of a service to accept the intended requests, beyond merely having a running process.
Reference count
A count of owners that still require a shared block or object.
Remote model code
Python supplied by a model repository and executed when an operator explicitly enables a trust option; it requires an exact-revision review and is disabled in these labs.
Response completion
The final protocol event, which can occur after the last generated content token.
RNG
Random number generator; supplies the random draws used by sampling, with state that matters for reproducibility.
SDPA
Scaled dot-product attention, the query/key/value attention operation. PyTorch's SDPA API selects among supported implementations for the actual inputs and configuration.
Service correctness
Correct tokenization, sampling, stopping, streaming, errors, and protocol behavior around a valid model computation.
SLO
Service-level objective; a declared target such as a latency percentile, throughput, error rate, or goodput threshold.
Softmax
A function that converts scores into nonnegative probabilities summing to one by normalizing their exponentials.
Speculative decoding
Proposing several tokens with a cheaper source and verifying them with the target model, accepting only a target-valid prefix under the declared sampling contract.
SSE
Server-Sent Events; an HTTP event-stream format that can carry generated content in chunks, which need not correspond one-to-one to tokens.
Temperature
Positive divisor applied to logits before softmax; lower values sharpen the distribution.
Throughput
Completed requests or tokens per second for a declared workload and boundary.
Token
A model's unit of text representation, mapped to an integer by its tokenizer; a token need not be a whole word.
Tokenization
Converting input text into token IDs using the selected vocabulary and tokenization rules.
Top-k
Sampling filter retaining the k highest-scoring candidates, followed by renormalization.
Top-p
Sampling filter retaining the smallest ranked prefix reaching a declared cumulative probability threshold.
TP (tensor parallelism)
Splitting selected tensor operations within model layers across ranks, requiring communication during inference or training.
TPOT
Time per output token; an average generation interval per subsequent token. Tool conventions vary, so compare its formula and endpoints with ITL rather than assuming the names imply different aggregations.
TTFT
Time to first token, measured from the declared request boundary to the first observed output token. First-nonempty-content timing is a proxy unless its correspondence to token arrival is established. TTFT is distinct from steady-state inter-token latency and end-to-end latency.
Warm-up
Untimed execution used to exclude initialization, compilation, allocation, and cache setup according to a declared policy.
Zero point
A stored offset that maps real zero into a quantized representation.