A straightforward method for training your LLM, from downloading data to generating text.
feat(inference): shared sampling helpers with min-p
FareedKhan-dev5b2fe8363e86
diff --git a/src/inference/__init__.py b/src/inference/__init__.pynew file mode 100644index 0000000..d1b9f12--- /dev/null+++ b/src/inference/__init__.py@@ -0,0 +1,5 @@+"""Inference helpers: sampling, speculative decoding and weight quantization."""++from src.inference.sampling import filter_logits, sample_next_token++__all__ = ["filter_logits", "sample_next_token"]diff --git a/src/inference/sampling.py b/src/inference/sampling.pynew file mode 100644index 0000000..e3ff9ee--- /dev/null+++ b/src/inference/sampling.py@@ -0,0 +1,72 @@+"""+Turning next-token logits into a choice.++All the knobs act on the logits of one step, in this order:++- ``temperature`` divides the logits. Below 1 sharpens the distribution, above 1 flattens it.+- ``top_k`` keeps only the k most likely tokens.+- ``top_p`` (nucleus sampling) keeps the smallest set of tokens whose probabilities add up to p.+- ``min_p`` keeps tokens whose probability is at least ``min_p`` times the top token's+ probability (Nguyen et al. 2024). Unlike top-p it adapts to how confident the model is:+ a confident step keeps few tokens, an uncertain step keeps many.+- ``greedy`` skips sampling and takes the argmax, for reproducible evaluation.++Filtered tokens get a logit of ``-inf`` so they have probability zero after the softmax.+"""++from __future__ import annotations++import torch+import torch.nn.functional as F+from jaxtyping import Float, Int+from torch import Tensor+++def filter_logits(+ logits: Float[Tensor, "batch vocab"],+ temperature: float = 1.0,+ top_k: int | None = None,+ top_p: float | None = None,+ min_p: float | None = None,+) -> Float[Tensor, "batch vocab"]:+ """Apply temperature, then top-k, top-p and min-p filtering. Returns new logits."""+ if temperature != 1.0:+ logits = logits / max(temperature, 1e-6)++ if top_k is not None and top_k > 0:+ k = min(top_k, logits.size(-1))+ kth = torch.topk(logits, k, dim=-1).values[..., -1, None]+ logits = logits.masked_fill(logits < kth, float("-inf"))++ if top_p is not None and 0.0 < top_p < 1.0:+ sorted_logits, sorted_idx = torch.sort(logits, descending=True, dim=-1)+ cumprobs = sorted_logits.softmax(dim=-1).cumsum(dim=-1)+ remove = cumprobs > top_p+ # Keep at least the top token; shift so the token that crosses top_p stays.+ remove[..., 1:] = remove[..., :-1].clone()+ remove[..., 0] = False+ remove = remove.scatter(-1, sorted_idx, remove)+ logits = logits.masked_fill(remove, float("-inf"))++ if min_p is not None and 0.0 < min_p < 1.0:+ probs = logits.softmax(dim=-1)+ threshold = min_p * probs.max(dim=-1, keepdim=True).values+ logits = logits.masked_fill(probs < threshold, float("-inf"))++ return logits+++def sample_next_token(+ logits: Float[Tensor, "batch vocab"],+ temperature: float = 1.0,+ top_k: int | None = None,+ top_p: float | None = None,+ min_p: float | None = None,+ greedy: bool = False,+ generator: torch.Generator | None = None,+) -> Int[Tensor, "batch 1"]:+ """Pick the next token id for every row of ``logits``."""+ if greedy:+ return logits.argmax(dim=-1, keepdim=True)+ probs = F.softmax(filter_logits(logits.float(), temperature, top_k, top_p, min_p), dim=-1)+ return torch.multinomial(probs, num_samples=1, generator=generator)diff --git a/src/post_training/rollout.py b/src/post_training/rollout.pyindex 2dbbc65..779a2c4 100644--- a/src/post_training/rollout.py+++ b/src/post_training/rollout.py@@ -26,8 +26,19 @@ from dataclasses import dataclassimport torchimport torch.nn.functional as F+from src.inference.sampling import filter_logitsfrom src.post_training.chat_template import EOT_ID+__all__ = [+ "RolloutBatch",+ "compute_logprobs",+ "filter_logits",+ "generate_with_logprobs",+ "rollout_prompts",+ "sequence_entropy",+ "sequence_logprobs",+]+@dataclassclass RolloutBatch:@@ -56,38 +67,9 @@ def _logits_from(model, idx: torch.Tensor) -> torch.Tensor:return out[0] if isinstance(out, tuple) else out-def filter_logits(- logits: torch.Tensor,- temperature: float = 1.0,- top_k: int | None = None,- top_p: float | None = None,-) -> torch.Tensor:- """- Apply temperature, then optional top-k and nucleus (top-p) filtering to a batch of- next-token logits ``(B, vocab)``. Returns logits with filtered entries set to -inf,- ready to softmax-and-sample. Used ONLY to build the sampling distribution; the- log-prob we record for the ratio is the full-distribution log-prob (see- :func:`generate_with_logprobs`).- """- if temperature != 1.0:- logits = logits / max(temperature, 1e-6)-- if top_k is not None and top_k > 0:- k = min(top_k, logits.size(-1))- kth = torch.topk(logits, k, dim=-1).values[..., -1, None]- logits = logits.masked_fill(logits < kth, float("-inf"))-- if top_p is not None and 0.0 < top_p < 1.0:- sorted_logits, sorted_idx = torch.sort(logits, descending=True, dim=-1)- cumprobs = sorted_logits.softmax(dim=-1).cumsum(dim=-1)- remove = cumprobs > top_p- # Keep at least the top token; shift so the token that crosses top_p stays.- remove[..., 1:] = remove[..., :-1].clone()- remove[..., 0] = False- remove = remove.scatter(-1, sorted_idx, remove)- logits = logits.masked_fill(remove, float("-inf"))-- return logits+# ``filter_logits`` (temperature, top-k, top-p, min-p) lives in src/inference/sampling.py and is+# re-exported here. It only shapes the distribution we SAMPLE from; the log-prob recorded for+# the PPO/GRPO ratio is always the full-distribution log-prob (see generate_with_logprobs).@torch.no_grad()diff --git a/tests/test_sampling.py b/tests/test_sampling.pynew file mode 100644index 0000000..9312e81--- /dev/null+++ b/tests/test_sampling.py@@ -0,0 +1,38 @@+"""Sampling filters: temperature, top-k, top-p (nucleus), min-p and greedy."""++from __future__ import annotations++import torch++from src.inference.sampling import filter_logits, sample_next_token++PROBS = torch.tensor([[0.50, 0.25, 0.15, 0.06, 0.04]])+LOGITS = PROBS.log()+++def _kept(logits: torch.Tensor) -> list[int]:+ return torch.isfinite(logits[0]).nonzero().flatten().tolist()+++def test_top_k_keeps_the_k_most_likely() -> None:+ assert _kept(filter_logits(LOGITS, top_k=2)) == [0, 1]+++def test_top_p_keeps_the_smallest_set_reaching_p() -> None:+ assert _kept(filter_logits(LOGITS, top_p=0.7)) == [0, 1] # 0.50 + 0.25 crosses 0.7+ assert _kept(filter_logits(LOGITS, top_p=0.1)) == [0] # always keeps the top token+++def test_min_p_scales_with_the_top_probability() -> None:+ assert _kept(filter_logits(LOGITS, min_p=0.4)) == [0, 1] # keep p >= 0.4 * 0.50 = 0.20+ flat = torch.zeros(1, 5) # an uncertain step keeps everything+ assert _kept(filter_logits(flat, min_p=0.4)) == [0, 1, 2, 3, 4]+++def test_temperature_and_greedy() -> None:+ sharp = filter_logits(LOGITS, temperature=0.5).softmax(-1)+ assert sharp[0, 0] > PROBS[0, 0]+ assert sample_next_token(LOGITS, greedy=True).item() == 0+ torch.manual_seed(0)+ draws = torch.cat([sample_next_token(LOGITS, top_k=1) for _ in range(20)])+ assert (draws == 0).all()