52 / 90

Day 52: Autoregressive Text Generation: Temperature, Top-k, and Nucleus (Top-p) Sampling

Trace greedy decoding loops, formulate temperature scaling z / T, derive cumulative probability truncation in Top-p nucleus sampling, and verify seed repeatability.

Models, Pretraining & LoRA 480 active minutes (8 hours focused study)
01 120 min

Autoregressive Sampling: Greedy Decoding vs Temperature Scaling

Agent-Assisted Engineering Check

Prerequisites

Day 48 Decoder-Only Forward Pass and Day 41 Softmax.

Learning Objective

Formulate next-token prediction p_i = softmax(z_i / T) and explain how temperature T controls the entropy of the output distribution.

Instructions

Given logits z = [2.0, 1.0, 0.0]: (1) Compute greedy argmax index 0. (2) Compute probabilities at T=1.0: exp([2,1,0]) = [7.389, 2.718, 1.0], sum=11.107 -> p = [0.665, 0.245, 0.090]. (3) Compute at T=0.5: z/0.5 = [4.0, 2.0, 0.0], exp([4,2,0]) = [54.598, 7.389, 1.0], sum=62.987 -> p = [0.867, 0.117, 0.016]. (4) Explain T -> 0 as greedy argmax and T -> inf as uniform.

Practice & Prediction Log

1. Compute softmax probabilities for z = [2.0, 1.0, 0.0] at T=2.0.
2. Why does low temperature (e.g. T=0.2) reduce hallucinations while increasing repetitive loops?
3. What runtime error occurs if T=0.0 is passed directly into division z / T?

Independent Mastery Criterion

Derives temperature scaling analytically and explains the trade-off between diversity and repetition.

Authoritative Source Resources & Provenance

linking arXiv non-exclusive license / Open Access

The Curious Case of Neural Text Degeneration

Author: Ari Holtzman, Jan Buys, Li Du, Maxwell Forbes, Yejin Choi | Original Source Link ↗

Relevant Section / Range: Section 2.1 Text Generation Decoding Strategies and Section 3.3 Sampling with Temperature

Verified Version & Date: ICLR 2020 / arXiv:1904.09751v2 (Verified: 2026-10-30)

Selection Rationale:

Primary source introducing Nucleus (Top-p) sampling and analyzing the failure of greedy decoding (loops, repetition).

Source Prerequisites:

Softmax probabilities, cumulative probability distributions from Days 25-27 and 41-42.

Safe Fallback (Offline Resilience):

Top-p truncation algorithms and worked probability cutoffs are completely explained in the lesson.

Compared Candidate Sources & Selection Analysis (2)

Introduces top-k sampling; Holtzman et al. dynamic nucleus threshold is compared directly against top-k.

Hugging Face Generation Strategies Guide ↗ compared_alternative [Apache 2.0]

Practical library guide; Holtzman provides the foundational mathematical reasoning.

linking MIT

nanoGPT: sample.py autoregressive generation script

Author: Andrej Karpathy | Original Source Link ↗

Relevant Section / Range: sample.py: temperature and top_k settings passed to model.generate (model.py: GPT.generate)

Verified Version & Date: Git master (Verified: 2026-10-30)

Selection Rationale:

Compact historical code reference for the named implementation functions; CS336 spring2025 provides the lead component exercises. Do not infer top-p, atomic persistence or cloud budget enforcement from nanoGPT.

Source Prerequisites:

PyTorch inference, torch.multinomial, and Day 48 decoder-only forward pass.

Safe Fallback (Offline Resilience):

The generation loop is implemented in runnable local scripts.

Compared Candidate Sources & Selection Analysis (2)
llama.cpp sampling implementation ↗ compared_alternative [MIT]

C++ implementation with high performance; nanoGPT is readable Python matched to our curriculum.

PyTorch text generation tutorial ↗ compared_alternative [Modified BSD]

Encoder-decoder model; nanoGPT decoder-only autoregressive loop is the direct fit for modern LLMs.

02 120 min

Truncation Strategies: Top-k and Nucleus (Top-p) Sampling

Agent-Assisted Engineering Check

Prerequisites

Activity 52-01.

Learning Objective

Implement Top-k and Nucleus (Top-p) truncation algorithms and explain why Top-p adapts dynamically to distribution flatness.

Instructions

Given sorted probabilities p = [0.40, 0.30, 0.15, 0.10, 0.05] for tokens A, B, C, D, E: (1) With k=2, truncate to {A, B} and renormalize to p = [0.4/0.7, 0.3/0.7] = [0.571, 0.429]. (2) With nucleus threshold p_cutoff=0.80, cumulative sums are A: 0.40, B: 0.70, C: 0.85 (>0.80) -> retain {A, B, C}, sum=0.85, renormalize to [0.471, 0.353, 0.176].

Practice & Prediction Log

1. What tokens are kept under Top-p with p=0.60?
2. What failure mode of Top-k does Top-p solve when the distribution is highly peaked (e.g. p = [0.98, 0.01, 0.01])?
3. State the algorithmic steps of Nucleus sampling in 3 lines.

Independent Mastery Criterion

Accurately computes Top-p cutoffs and articulates the dynamic vocabulary advantage.

Authoritative Source Resources & Provenance

linking arXiv non-exclusive license / Open Access

The Curious Case of Neural Text Degeneration

Author: Ari Holtzman, Jan Buys, Li Du, Maxwell Forbes, Yejin Choi | Original Source Link ↗

Relevant Section / Range: Section 3.1 Nucleus Sampling (with Section 2.1 Text Generation Decoding Strategies)

Verified Version & Date: ICLR 2020 / arXiv:1904.09751v2 (Verified: 2026-10-30)

Selection Rationale:

Primary source introducing Nucleus (Top-p) sampling and analyzing the failure of greedy decoding (loops, repetition).

Source Prerequisites:

Softmax probabilities, cumulative probability distributions from Days 25-27 and 41-42.

Safe Fallback (Offline Resilience):

Top-p truncation algorithms and worked probability cutoffs are completely explained in the lesson.

Compared Candidate Sources & Selection Analysis (2)

Introduces top-k sampling; Holtzman et al. dynamic nucleus threshold is compared directly against top-k.

Hugging Face Generation Strategies Guide ↗ compared_alternative [Apache 2.0]

Practical library guide; Holtzman provides the foundational mathematical reasoning.

linking MIT

nanoGPT: sample.py autoregressive generation script

Author: Andrej Karpathy | Original Source Link ↗

Relevant Section / Range: sample.py: temperature and top_k settings passed to model.generate (model.py: GPT.generate)

Verified Version & Date: Git master (Verified: 2026-10-30)

Selection Rationale:

Compact historical code reference for the named implementation functions; CS336 spring2025 provides the lead component exercises. Do not infer top-p, atomic persistence or cloud budget enforcement from nanoGPT.

Source Prerequisites:

PyTorch inference, torch.multinomial, and Day 48 decoder-only forward pass.

Safe Fallback (Offline Resilience):

The generation loop is implemented in runnable local scripts.

Compared Candidate Sources & Selection Analysis (2)
llama.cpp sampling implementation ↗ compared_alternative [MIT]

C++ implementation with high performance; nanoGPT is readable Python matched to our curriculum.

PyTorch text generation tutorial ↗ compared_alternative [Modified BSD]

Encoder-decoder model; nanoGPT decoder-only autoregressive loop is the direct fit for modern LLMs.

03 120 min

Repetition Penalties and Generation Invariance Under Random Seeds

Agent-Assisted Engineering Check

Prerequisites

Activities 52-01 and 52-02.

Learning Objective

Apply multiplicative repetition penalty theta to logits and verify that fixing the random seed guarantees deterministic sampling traces.

Instructions

For token i already present in the context, if logit z_i > 0, set z_i = z_i / theta; if z_i < 0, set z_i = z_i * theta (where theta > 1.0, e.g. 1.2). Verify that torch.manual_seed(42) produces identical generated token sequences across runs.

Practice & Prediction Log

1. Apply penalty theta=1.2 to generated logits z = [3.0, -2.0, 1.0] where token 0 and token 1 appeared previously.
2. Why is penalty division used for positive logits and multiplication for negative logits?
3. Write a two-line test demonstrating that seed=42 yields bitwise identical generated tokens.

Independent Mastery Criterion

Applies penalty rules correctly and proves reproducibility via seed pinning.

Authoritative Source Resources & Provenance

linking arXiv non-exclusive license / Open Access

The Curious Case of Neural Text Degeneration

Author: Ari Holtzman, Jan Buys, Li Du, Maxwell Forbes, Yejin Choi | Original Source Link ↗

Relevant Section / Range: Section 5.3 Repetition and Appendix B Example Generations

Verified Version & Date: ICLR 2020 / arXiv:1904.09751v2 (Verified: 2026-10-30)

Selection Rationale:

Primary source introducing Nucleus (Top-p) sampling and analyzing the failure of greedy decoding (loops, repetition).

Source Prerequisites:

Softmax probabilities, cumulative probability distributions from Days 25-27 and 41-42.

Safe Fallback (Offline Resilience):

Top-p truncation algorithms and worked probability cutoffs are completely explained in the lesson.

Compared Candidate Sources & Selection Analysis (2)

Introduces top-k sampling; Holtzman et al. dynamic nucleus threshold is compared directly against top-k.

Hugging Face Generation Strategies Guide ↗ compared_alternative [Apache 2.0]

Practical library guide; Holtzman provides the foundational mathematical reasoning.

linking MIT

nanoGPT: sample.py autoregressive generation script

Author: Andrej Karpathy | Original Source Link ↗

Relevant Section / Range: sample.py: temperature and top_k settings passed to model.generate (model.py: GPT.generate)

Verified Version & Date: Git master (Verified: 2026-10-30)

Selection Rationale:

Compact historical code reference for the named implementation functions; CS336 spring2025 provides the lead component exercises. Do not infer top-p, atomic persistence or cloud budget enforcement from nanoGPT.

Source Prerequisites:

PyTorch inference, torch.multinomial, and Day 48 decoder-only forward pass.

Safe Fallback (Offline Resilience):

The generation loop is implemented in runnable local scripts.

Compared Candidate Sources & Selection Analysis (2)
llama.cpp sampling implementation ↗ compared_alternative [MIT]

C++ implementation with high performance; nanoGPT is readable Python matched to our curriculum.

PyTorch text generation tutorial ↗ compared_alternative [Modified BSD]

Encoder-decoder model; nanoGPT decoder-only autoregressive loop is the direct fit for modern LLMs.

04 120 min

Independent Sampling Strategy Implementation and Verification

Independent Mastery Check

Prerequisites

Complete activities 52-01 through 52-03.

Learning Objective

Write a complete generate() function in PyTorch implementing temperature, Top-k, and Top-p sampling with KV-cache / autoregressive loop.

Instructions

Implement def generate(model, idx, max_new_tokens, temperature=1.0, top_k=None, top_p=None). Assert generated output matches expected shape (B, T + max_new_tokens).

Practice & Prediction Log

1. Provide the complete generate function code.
2. Verify that top_k=1 produces identical output to greedy argmax.
3. What guard is required when context length exceeds model block_size?

Independent Mastery Criterion

Fully functional generate function passing greedy equivalence and context cropping tests.

Authoritative Source Resources & Provenance

linking MIT

nanoGPT: sample.py autoregressive generation script

Author: Andrej Karpathy | Original Source Link ↗

Relevant Section / Range: sample.py: temperature and top_k settings passed to model.generate (model.py: GPT.generate)

Verified Version & Date: Git master (Verified: 2026-10-30)

Selection Rationale:

Compact historical code reference for the named implementation functions; CS336 spring2025 provides the lead component exercises. Do not infer top-p, atomic persistence or cloud budget enforcement from nanoGPT.

Source Prerequisites:

PyTorch inference, torch.multinomial, and Day 48 decoder-only forward pass.

Safe Fallback (Offline Resilience):

The generation loop is implemented in runnable local scripts.

Compared Candidate Sources & Selection Analysis (2)
llama.cpp sampling implementation ↗ compared_alternative [MIT]

C++ implementation with high performance; nanoGPT is readable Python matched to our curriculum.

PyTorch text generation tutorial ↗ compared_alternative [Modified BSD]

Encoder-decoder model; nanoGPT decoder-only autoregressive loop is the direct fit for modern LLMs.

linking arXiv non-exclusive license / Open Access

The Curious Case of Neural Text Degeneration

Author: Ari Holtzman, Jan Buys, Li Du, Maxwell Forbes, Yejin Choi | Original Source Link ↗

Relevant Section / Range: Section 3.1 Nucleus Sampling (with Section 2.1 Text Generation Decoding Strategies)

Verified Version & Date: ICLR 2020 / arXiv:1904.09751v2 (Verified: 2026-10-30)

Selection Rationale:

Primary source introducing Nucleus (Top-p) sampling and analyzing the failure of greedy decoding (loops, repetition).

Source Prerequisites:

Softmax probabilities, cumulative probability distributions from Days 25-27 and 41-42.

Safe Fallback (Offline Resilience):

Top-p truncation algorithms and worked probability cutoffs are completely explained in the lesson.

Compared Candidate Sources & Selection Analysis (2)

Introduces top-k sampling; Holtzman et al. dynamic nucleus threshold is compared directly against top-k.

Hugging Face Generation Strategies Guide ↗ compared_alternative [Apache 2.0]

Practical library guide; Holtzman provides the foundational mathematical reasoning.