Free self-study · No account needed · Progress stays in this browser. Back it up before clearing site data or changing devices.

← Week 4: Training, Alignment, and Inference

Week 04 / Lesson 3

Inference, sampling, and computation

Choose decoding settings and explain the memory and latency of generation.

Section 3.1 1 of 8

Overview

Focus

Choose decoding settings and explain the memory and latency of generation.

Your route through the lesson

  • 3.2 Temperature and nucleus sampling
  • 3.3 Prompt processing and sequential decoding
  • 3.4 Key and value caching and weight quantization
  • 3.5 Training computation and inference computation
  • 3.6 Put it into practice
  • 3.7 Guided comparison
  • 3.8 A long prompt with slow first-token response

All required teaching is included here. Review selections are saved. Choose a correct answer for every question to continue; retries are unlimited. Study time and personal notes are optional.

Section 3.2 2 of 8

Temperature and nucleus sampling

Focus

Calculate how temperature and nucleus selection alter a next-token distribution.

A model first emits logits, numerical scores before probability normalization. For positive temperature T, divide logits by T and apply softmax. Lower temperature makes differences sharper; higher temperature flattens the distribution. With logits [2,0], temperature one gives approximately [0.881,0.119], while temperature two gives approximately [0.731,0.269].

Temperature zero is handled as a special greedy choice in the lab, not literal division by zero. Nucleus selection sorts probabilities and retains the smallest leading set whose cumulative mass reaches a chosen threshold. For [0.6,0.3,0.1] and threshold 0.8, keep the first two entries and renormalize them to [2/3,1/3].

Both settings affect variety and frequency of continuations. They do not add evidence or guarantee truth. Use repeated runs when comparing stochastic behavior and preserve the actual settings. A single preferred sample cannot estimate a configuration's reliability or diversity.

// Quick review

Check your understanding.

Choose an answer for immediate feedback. Retry freely; a correct answer for every question unlocks the next section.

1. Logits [2,0] are divided by temperature two. What scores enter softmax?
2. Probabilities [0.6,0.3,0.1] use nucleus threshold 0.8. Which entries remain?
3. Does increasing temperature supply more factual evidence?

Section 3.3 3 of 8

Prompt processing and sequential decoding

Focus

Separate prompt processing from sequential token decoding.

Generation has two useful timing stages. Prompt processing computes representations for the supplied prefix before the first output token. Decoding then repeatedly selects a new token and advances the model. Time to first token includes work before the first result; decode throughput measures generated tokens per unit time after generation starts.

A longer prompt can increase first-token delay even when later decode throughput is similar. Conversely, a slow sequential decoder can produce a short first response quickly but complete a long answer slowly. Record loading and warm-up separately so a one-time initialization is not mistaken for every request's model cost.

Python's time.perf_counter measures elapsed durations. For asynchronous accelerator execution, timing needs appropriate synchronization; the processor-only lab avoids that particular issue. Compare equal output lengths and fixed settings. The tiny lab recomputes the prefix at each step as a reference implementation; its timings should not be described as a production cached server benchmark.

// Quick review

Check your understanding.

Choose an answer for immediate feedback. Retry freely; a correct answer for every question unlocks the next section.

1. What does time to first token emphasize?
2. Why record model loading separately from a warmed request benchmark?
3. Two runs generate different numbers of output tokens. What should be controlled or reported when comparing throughput?

Section 3.4 4 of 8

Key and value caching and weight quantization

Focus

Estimate key-value cache memory and distinguish it from weight storage.

A key-value cache stores previously computed attention keys and values during autoregressive decoding. With a compatible cached decoder, a new token can use those stored representations rather than recomputing all prior projections. The cache is runtime state for a request, not an update to learned model weights.

A simple memory estimate is 2×layers×batch×sequence_length×key_value_heads×head_width×bytes_per_value. The leading two accounts for keys and values. For two layers, one sequence, ten tokens, two key/value heads, width four, and four-byte values, the estimate is 2×2×1×10×2×4×4=1280 bytes.

Actual allocation includes implementation overhead and architecture details. Cache memory grows with active sequences and length even when model weights stay fixed. Weight quantization reduces representation precision for weights; it does not by itself remove cache memory. Keep weight storage, cache state, activations, and runtime overhead separate when sizing an application.

// Quick review

Check your understanding.

Choose an answer for immediate feedback. Retry freely; a correct answer for every question unlocks the next section.

1. A key-value cache is populated while generating a request. What kind of state is it?
2. With all other terms fixed, doubling sequence length does what to the simple cache estimate?
3. Does lower-precision weight storage automatically eliminate key-value cache growth?

Section 3.5 5 of 8

Training computation and inference computation

Focus

Distinguish training updates from additional computation at inference time.

Training computation changes learned parameters according to a loss. Inference computation uses a fixed model to process a request. A longer prompt, more generated tokens, several sampled candidates, or an application verification step can increase inference work without training the model.

Quantization represents values at lower numerical precision, reducing ideal storage. Distillation trains another model from teacher signal. Prompting supplies input context. These interventions act at different places: changing precision is not the same as adding current facts, and generating multiple candidates is not the same as parameter fitting.

Suppose a solver generates three candidate calculations and a deterministic checker rejects two. The application spent more inference and verification computation, while model weights may remain unchanged. If the accepted examples are later used in an explicit training run, that later phase is a separate parameter update. Record which phase actually occurred so improved output is attributed to the right mechanism.

// Quick review

Check your understanding.

Choose an answer for immediate feedback. Retry freely; a correct answer for every question unlocks the next section.

1. A fixed model generates three candidates and an application checks them. What increased?
2. Which action directly changes learned parameters through a loss?
3. How does distillation differ from ordinary weight quantization?

Section 3.6 6 of 8

Put it into practice

Focus

Run sampling arithmetic, cache estimates, and controlled local timing.

Keep week03.py beside week04.py. Run python week04.py --lesson 3. This path calculates temperature-adjusted probabilities, retained nucleus entries, and the simple cache-size estimate, checking exact or tolerance-based invariants.

It also times a tiny local decoder with a short and longer prefix after warm-up. If a compatible checkpoint path is supplied, the lab can use its saved state; otherwise the benchmark explicitly uses an untrained toy model and makes no language-quality claim. The timed computation is still real processor work.

Inspect reported prefix length, output-token count, first-forward computation time, and full reference generation time. The first-forward measurement ends before token selection, and the full generation measurement includes every generated token; neither is a streamed time-to-first-token measurement. Compare like with like. The TinyDecoder reference loop recomputes context and is useful for understanding the stages, while the cache calculation is an estimate rather than proof that this reference decoder implements caching. Save these distinctions with the measured output.

Download this week’s Python lab ↓

// Quick review

Check your understanding.

Choose an answer for immediate feedback. Retry freely; a correct answer for every question unlocks the next section.

1. A tiny untrained decoder is timed on a processor. Which claim is supported?
2. A cache calculator checks a linear memory formula. What has it demonstrated?
3. Why report whether a saved trained checkpoint or random initialization was used?

Section 3.7 7 of 8

Guided comparison

Focus

Interpret probabilities and timings with their exact denominators and assumptions.

The distribution [0.6,0.3,0.1] under nucleus threshold 0.8 retains mass 0.9, then divides the retained probabilities by 0.9. The new probabilities are 2/3 and 1/3. Keeping the original 0.6 and 0.3 without renormalization would not form a complete distribution over the retained choices.

For the cache estimate, doubling ten tokens to twenty doubles 1280 bytes to 2560 under the same layer, head, batch, and numerical-width assumptions. It does not double weight storage. If actual memory is larger, investigate runtime overhead and implementation allocations rather than changing observed values to match the ideal formula.

For timing, distinguish a wall-clock total from a per-token rate. Generating ten tokens in half a second averages twenty tokens per second over that measured interval, but a separate first-token delay may need to be reported as well. This rate describes the measured workload and machine; it is not a universal property of a model name.

// Quick review

Check your understanding.

Choose an answer for immediate feedback. Retry freely; a correct answer for every question unlocks the next section.

1. After retaining probabilities 0.6 and 0.3, what are their renormalized values?
2. A simple cache estimate is 1280 bytes at ten tokens. What is it at twenty with other assumptions fixed?
3. Ten generated tokens take half a second in a specified interval. What is the average throughput for that interval?

Section 3.8 8 of 8

A long prompt with slow first-token response

Focus

Diagnose a long prompt that delays the first visible token.

An assistant processes a ten-token prompt quickly but a thousand-token document causes a long wait before output starts. Later token delivery is similar. This pattern points toward prompt processing or request preparation rather than necessarily slower steady-state decoding.

Check source retrieval, tokenization, queue time, and model prompt computation separately. A single end-to-end timer cannot identify which stage caused the change. Record prompt length using the actual tokenizer, not an approximate word count. Ensure the output limits and model configuration match before comparing two runs.

A longer context also increases runtime memory needs, including attention state in a cached server. Lower-precision weights may help fit the model but do not erase the prompt-processing work or guarantee the same latency. A useful improvement is judged against measured task quality and operation costs; dropping the only relevant evidence to make the first token faster would damage the application’s purpose.

// Quick review

Check your understanding.

Choose an answer for immediate feedback. Retry freely; a correct answer for every question unlocks the next section.

1. Longer prompts greatly delay the first token while later delivery rate stays similar. Which stage deserves investigation?
2. Why separate retrieval, queue, prompt, and decode timings?
3. A proposed optimization drops the only passage supporting the answer. What tradeoff must be evaluated?

Your personal notes

Optional, ungraded, and saved only in this browser. Export a backup from the Academy homepage to keep them.

References and further reading
Ask your own AI assistant

Copy this prompt into an assistant you already use. Nothing is sent automatically, and your personal notes are not included.

Next lesson: Writing clear model requests →