from_scratch.llm
Make it usable
10

Sampling strategies

temperature, top-k, top-p — one model, many writers
steps/05_make_usable/10_sampling.py ► Open as notebook (with output)

A trained model outputs a probability for every next token; how you pick from them transforms the text without touching a single weight. Greedy loops forever; temperature trades safety for creativity; top-k and top-p hit the sweet spot.

This is exactly the temperature / top_p knob you set when calling an LLM API. The model is frozen — you're reshaping how it samples from itself.

p ∝ exp(logits / T) · top-k: keep k highest · top-p: smallest set with Σp ≥ pdecoding shapes the model's own distribution; the weights never change.
The theory

Once trained, the model gives a distribution over the next token; decoding decides how to pick from it. Greedy (argmax) maximizes each local step but produces repetitive, globally sub-optimal text, and beam search — great for translation — degenerates for open-ended generation. So we sample, but shape the distribution first.

Temperature T divides the logits before softmax: T < 1 sharpens toward the top choices (safer, more repetitive), T > 1 flattens them (wilder, more diverse), and T→0 recovers greedy. Truncation then trims the unreliable tail — top-k keeps the k most likely tokens, top-p (nucleus) keeps the smallest set whose probability mass exceeds p, adapting how many options it considers to how confident the model is. None of this touches the weights; it's purely how you read the same model.

Animation
Temperature reshapes the same distribution without touching the weights: low T is peaked (confident, repetitive), high T is flat (diverse, riskier).
Visual walkthrough
Tallest probability bar looping back into repeated token choices.
Greedy loopAlways taking the top token is locally safe but can fall into repetition.
Probability bars reshaped from sharp to broad by heated particle flow.
TemperatureTemperature sharpens or flattens the distribution before sampling.
Probability distribution with tail candidates filtered behind a cutoff gate.
Top-k and top-pTruncation removes the unreliable tail while keeping enough variety.
The notebook · steps/05_make_usable/10_sampling.ipynb — code cells & their output. Open & run on GitHub →
In [1]
import importlib.util
import os
from pathlib import Path

import torch
import torch.nn.functional as F

# Resolve sibling steps from the repo root (works from any CWD and in notebooks).
ROOT = Path(__file__).resolve().parents[2] if "__file__" in globals() else Path.cwd()

# 09_tiny_gpt.py starts with a digit, so it can't be imported normally.
# Load it as a module to reuse its TinyGPT class, tokenizer, and config.
spec = importlib.util.spec_from_file_location(
    "tiny_gpt", str(ROOT / "steps" / "04_transformer" / "09_tiny_gpt.py"))
tg = importlib.util.module_from_spec(spec)
spec.loader.exec_module(tg)

DEVICE = tg.DEVICE
BLOCK_SIZE = tg.BLOCK_SIZE


def load_model():
    if not os.path.exists(tg.CKPT_PATH):
        raise SystemExit("No tiny_gpt.pt found — run `python 09_tiny_gpt.py` first.")
    model = tg.TinyGPT().to(DEVICE)
    ckpt = torch.load(tg.CKPT_PATH, map_location=DEVICE)
    model.load_state_dict(ckpt["model"])
    model.eval()
    return model


@torch.no_grad()
def sample(model, n_tokens=300, temperature=1.0, top_k=None, top_p=None, seed=0):
    """Generate text using the chosen decoding strategy."""
    torch.manual_seed(seed)
    idx = torch.zeros((1, 1), dtype=torch.long, device=DEVICE)  # newline seed

    for _ in range(n_tokens):
        logits, _ = model(idx[:, -BLOCK_SIZE:])
        logits = logits[:, -1, :]                  # scores for the next token

        # TEMPERATURE: scale logits. Lower = more confident/repetitive.
        logits = logits / max(temperature, 1e-6)

        # TOP-K: zero out everything except the k highest-scoring tokens.
        if top_k is not None:
            kth = torch.topk(logits, top_k).values[:, -1, None]
            logits = logits.masked_fill(logits < kth, float("-inf"))

        probs = F.softmax(logits, dim=-1)

        # TOP-P (nucleus): keep the smallest set of tokens covering prob mass p.
        if top_p is not None:
            sorted_probs, sorted_idx = torch.sort(probs, descending=True)
            cumulative = torch.cumsum(sorted_probs, dim=-1)
            remove = cumulative - sorted_probs > top_p   # keep through the crossover
            sorted_probs[remove] = 0
            probs = torch.zeros_like(probs).scatter(1, sorted_idx, sorted_probs)
            probs = probs / probs.sum(dim=-1, keepdim=True)

        next_id = torch.multinomial(probs, num_samples=1)
        idx = torch.cat([idx, next_id], dim=1)

    return tg.decode(idx[0].tolist())


@torch.no_grad()
def sample_greedy(model, n_tokens=300):
    """Always pick the argmax — deterministic, tends to repeat."""
    idx = torch.zeros((1, 1), dtype=torch.long, device=DEVICE)
    for _ in range(n_tokens):
        logits, _ = model(idx[:, -BLOCK_SIZE:])
        next_id = logits[:, -1, :].argmax(dim=-1, keepdim=True)
        idx = torch.cat([idx, next_id], dim=1)
    return tg.decode(idx[0].tolist())


def show(title, text):
    print(f"\n{'=' * 60}\n{title}\n{'=' * 60}")
    print(text.strip())
In [2]
model = load_model()
print(f"loaded {tg.CKPT_PATH} — comparing decoding strategies "
      f"(no retraining)\n")

show("GREEDY  (always the top token — watch it get stuck/repeat)",
     sample_greedy(model, 250))

show("TEMPERATURE 0.5  (timid, safe, more repetitive)",
     sample(model, 250, temperature=0.5))

show("TEMPERATURE 1.0  (the raw distribution)",
     sample(model, 250, temperature=1.0))

show("TEMPERATURE 1.5  (wild, creative, more typos)",
     sample(model, 250, temperature=1.5))

show("TOP-K = 10  (only the 10 likeliest tokens each step)",
     sample(model, 250, top_k=10))

show("TOP-P = 0.9  (nucleus: adaptive shortlist)",
     sample(model, 250, top_p=0.9))

print("\n\nSame weights, six different writers. This is why one model can "
      "be\nmade 'creative' or 'precise' just by changing decoding settings.")
Output
loaded /Users/anchitgupta/Documents/Github/learn_llm_code/assets/tiny_gpt.pt — comparing decoding strategies (no retraining)


============================================================
GREEDY  (always the top token — watch it get stuck/repeat)
============================================================
CLARENCE:
I will not the word, and the world of the world,
And the world of the world of the world of the world,
And the world of the world of the world of the world,
And the world of the world of the world of the world,
And the world of the world o

============================================================
TEMPERATURE 0.5  (timid, safe, more repetitive)
============================================================
POMPEY:
Not what the death earth was will strange of the house;
The charge of so in the good of strange of this perfaction
Where to not my father well stone.

CLARENCE:
And the contry of the care an I fearful him
Fill me to here their come shall me

============================================================
TEMPERATURE 1.0  (the raw distribution)
============================================================
thy farms the London, our moethan youd I tle ear
Thou would forgethre hath think of lifes. I have that
Why writ appeach of your foer nend hands
How purson to a man in hither.

DUCHESS OF YORK:
Branchant, praying and love,--
I'll am exception, for my

============================================================
TEMPERATURE 1.5  (wild, creative, more typos)
============================================================
thyremh, discops:
LeWlooke me hand, iddigels fendedom,--yond nameker? hath Do.
 O, else make him; that's your wakewell.
As idart, Ramn:- my father well yet for 'filioe?

LEONTESS:
Hows up the cre.Show
Good faith.

First Woe,not sayfeign of lively: O

============================================================
TOP-K = 10  (only the 10 likeliest tokens each step)
============================================================
Thy farms the prevence, and that's all whelse, I

Forse:
I din you nech the honour'd offender in stip forgeth
But we alcosency thee, send have too well stone.

SLY:
Methough the connossues,
I shall falmong fair in mily moon, heaven,
In to the flaim,

============================================================
TOP-P = 0.9  (nucleus: adaptive shortlist)
============================================================
That make hear seven to can expany,
Now here fell commend his tower.

KING HENRY VI:
There shall seek so your way weap.

KING EDWARD IV:
What thou well you for made of the wintes.

MENENIUS:
No, I for my praying and love,
So, the maring of lively me


Same weights, six different writers. This is why one model can be
made 'creative' or 'precise' just by changing decoding settings.