Batched Autoregressive Decoding and Sampling
Medium · Machine Learning · Machine Learning Engineer · Technical Screen
Problem Statement
Build a batched autoregressive sequence decoder along with its token-filtering helpers. Because this execution sandbox runs pure NumPy rather than PyTorch, arrays use np.ndarray as a direct 1-to-1 stand-in for torch.Tensor (np.argmax <-> torch.argmax, np.sort <-> torch.topk / torch.sort, np.cumsum <-> torch.cumsum, np.put_along_axis <-> Tensor.scatter, rng.choice <-> torch.multinomial, and np.concatenate <-> torch.cat).
A causal model callable model(ids) accepts a 2D integer array of shape [batch_size, seq_len] and returns a 3D floating-point array of unnormalized next-token scores (logits) of shape [batch_size, seq_len, vocab_size]. Only the final time step logits[:, -1, :] (shape [batch_size, vocab_size]) predicts the unseen token immediately following the current prefix.
Implement three functions without mutating caller inputs:
-
top_k_filter(logits: np.ndarray, k: int) -> np.ndarrayReturn a new[batch_size, vocab_size]array where every entry strictly smaller (<) than thek-th largest logit in its row becomes-np.inf. Any entry tied with thek-th largest score is retained. Whenk >= vocab_size, return an unmodified copy. -
top_p_filter(logits: np.ndarray, p: float) -> np.ndarrayReturn a new[batch_size, vocab_size]array that retains, independently per row, the smallest set of highest-probability tokens (under row-wise softmax) whose combined probability mass is at leastp, setting all other entries to-np.inf. Break logit ties in favor of smaller vocabulary indices. Always keep at least the single top-scoring token per row, and whenp >= 1.0, retain every token in the row. -
generate(model, input_ids, max_new_tokens, do_sample=False, temperature=1.0, top_k=None, top_p=None, eos_token_id=None, pad_token_id=None, rng=None) -> np.ndarrayRepeatedly generate and append one token per batch row for up tomax_new_tokenssteps, returning anint64array of shape[batch_size, prompt_len + steps_run]:- Greedy mode (
do_sample=False): Choose the lowest vocabulary index achieving the maximum logit viaargmaxalong the last axis. Ignoretemperature,top_k, andtop_p. - Sampling mode (
do_sample=True): In exact order, dividelogits[:, -1, :]bytemperature, applytop_k_filteriftop_kis provided, applytop_p_filteriftop_pis provided, compute numerically stable row-wise softmax probabilities, and draw one token ID per row0 .. batch_size - 1usingrng.choice(vocab_size, p=probs[row])(initializingnp.random.default_rng()whenrngisNone). - End-of-sequence (
eos_token_id) & padding: Wheneos_token_idis given, a row becomes finished once it emitseos_token_idduring decoding (occurrences already insideinput_idsdo not finish the row). On later steps, any already-finished row has its emitted token replaced bypad_token_id(defaulting toeos_token_idwhenpad_token_idisNone). Stop the loop immediately once every row in the batch is finished.
- Greedy mode (
Examples
Example 1
Suppose a 4-token lookup model maps the token at each position to next-token logits:
- 0 -> [0.5, 4.0, 1.5, 0.0] (greedy pick 1)
- 1 -> [1.0, 0.0, 3.5, 2.0] (greedy pick 2)
- 2 -> [0.0, 1.0, 0.5, 5.0] (greedy pick 3)
- 3 -> [3.0, 0.5, 1.0, 0.0] (greedy pick 0)
Input: input_ids = [[0], [2]], max_new_tokens = 6, do_sample = False,
eos_token_id = 3, pad_token_id = 0
Output: [[0, 1, 2, 3],
[2, 3, 0, 0]]
Walk-through: On step 1, prompts [0] and [2] greedily emit 1 and 3, giving [[0, 1], [2, 3]]; row 1 hits eos_token_id = 3 and becomes finished. On step 2, row 0 emits 2 while finished row 1 is padded with 0, giving [[0, 1, 2], [2, 3, 0]]. On step 3, row 0 emits 3 (finishing row 0) while row 1 gets 0, giving [[0, 1, 2, 3], [2, 3, 0, 0]]. Because both rows are now finished, decoding halts after 3 steps instead of running all 6.
Example 2
Input: logits = [[2.0, 4.5, 1.0, 4.5, 3.0],
[-1.0, 2.5, 0.5, 1.5, -2.0]], k = 2
Output: [[-inf, 4.5, -inf, 4.5, -inf],
[-inf, 2.5, -inf, 1.5, -inf]]
Walk-through: In row 0, the two highest scores are both 4.5, so the 2nd largest value is 4.5 and every entry < 4.5 is masked to -inf (note k = 1 produces the same row because ties with the cutoff survive). In row 1, the 2nd largest score is 1.5, keeping 2.5 and 1.5.
Example 3
Input: logits = log([[0.15, 0.45, 0.10, 0.30],
[0.55, 0.20, 0.15, 0.10]]), p = 0.70
Output: [[-inf, log(0.45), -inf, log(0.30)],
[log(0.55), log(0.20), -inf, -inf]]
Walk-through: Row 0's softmax probabilities sort descending as 0.45 (token 1), 0.30 (token 3), 0.15 (token 0), 0.10 (token 2); tokens 1 and 3 reach 0.45 + 0.30 = 0.75 >= 0.70, so tokens 0 and 2 become -inf. In row 1, tokens 0 and 1 reach 0.55 + 0.20 = 0.75 >= 0.70, masking tokens 2 and 3.
Constraints
input_idsmust be a 2D array withbatch_size >= 1andprompt_len >= 1;max_new_tokensmust satisfymax_new_tokens >= 0(max_new_tokens == 0returns a copy ofinput_idswithout callingmodel).model(tokens)must return a 3D array whose first two dimensions matchtokens.shape, withvocab_size >= 1.- When
do_sample=True, requiretemperature > 0(finite, non-NaN),top_k >= 1(if notNone), and0.0 < top_p <= 1.0(if notNone). - Raise
ValueErrorwhenever any shape or hyperparameter constraint above is violated (whendo_sample=False, skip validation oftemperature,top_k, andtop_p).
Step-by-step walkthrough
Understand the autoregressive loop and tensor shapes
A causal language model takes a batch of token ID sequences and outputs logits — raw, unnormalized real-number scores for every word in the vocabulary at every sequence position. Autoregressive decoding means generating text one token at a time by feeding each newly chosen token right back into the model as part of the input for the next step.
At step
t,logits[:, i, :]scores what should come after positioni. Because positions0throughT - 2already have their next token in the prompt, the only slice that predicts a brand-new token is the last position,logits[:, -1, :]:tokens [B, T] ---> model(tokens) [B, T, V] ---> slice logits[:, -1, :] [B, V] ^ | | v append next_tokens[:, None] <--- next_tokens [B] <--- greedy argmax OR T -> top-k -> top-p -> sampleHere
Bisbatch_size,Tiscurrent_sequence_length(growing by1each step), andVisvocab_size.Because this practice sandbox provides NumPy rather than PyTorch,
solution.pyuses NumPy arrays whose operations map one-to-one to PyTorch (np.argmax<->torch.argmax,np.sort<->torch.topk/torch.sort,np.cumsum<->torch.cumsum,np.put_along_axis<->Tensor.scatter,rng.choice<->torch.multinomial,np.concatenate<->torch.cat). We build the NumPy implementation piece by piece and also show the exact PyTorch version before the final step.Validate inputs and build the greedy baseline
The simplest decoding rule is greedy decoding (
do_sample=False): at every step, pick the vocabulary index with the highest score viaargmax. Greedy decoding is deterministic and never usestemperature,top_k, ortop_p, so we validate sampling hyperparameters only whendo_sample=True.Up front, we also verify that
input_idsis a non-empty 2D batch (batch_size >= 1andseq_len >= 1, since an empty sequence has no-1position to read logits from) and thatmax_new_tokens >= 0:from typing import Optional import numpy as np def check_arguments(input_ids: np.ndarray, max_new_tokens: int, do_sample: bool, temperature: float, top_k: Optional[int], top_p: Optional[float]) -> None: """Validate input tensor shapes and decoding hyperparameters before calling the model.""" if input_ids.ndim != 2 or input_ids.shape[0] == 0 or input_ids.shape[1] == 0: raise ValueError("input_ids must have shape [batch_size, seq_len] with both >= 1") if max_new_tokens < 0: raise ValueError("max_new_tokens must be >= 0") # Greedy mode ignores temperature, top_k, and top_p completely. if not do_sample: return # Writing `not temperature > 0` rejects <= 0 as well as NaN. if not temperature > 0.0: raise ValueError("temperature must be > 0 when sampling; use do_sample=False for greedy") if top_k is not None and top_k < 1: raise ValueError("top_k must be >= 1") if top_p is not None and not 0.0 < top_p <= 1.0: raise ValueError("top_p must be in (0, 1]")Greedy decoding works well for deterministic tasks, but in open-ended text generation it tends to fall into repetitive loops because it never explores slightly lower-scoring words. Sampling solves that.
Scale with temperature and compute a stable softmax
To sample randomly, we convert a row of logits
zinto probabilities using softmax:p_i = exp(z_i) / sum_j exp(z_j). TemperatureT > 0reshapes those probabilities by dividing the raw logitsz / Tbefore calling softmax:Raw logits z = [3.0, 1.5, 0.0] T = 0.5 -> z / T = [6.0, 3.0, 0.0] -> probs = [0.950, 0.047, 0.002] (sharper, more greedy) T = 1.0 -> z / T = [3.0, 1.5, 0.0] -> probs = [0.786, 0.175, 0.039] (unmodified distribution) T = 3.0 -> z / T = [1.0, 0.5, 0.0] -> probs = [0.506, 0.307, 0.186] (flatter, more random)Notice two crucial details:
- Divide logits, never probabilities: Dividing probabilities by
Tand dividing by their new sum cancelsTout completely! - Subtract the row maximum before
exp(): Becauseexp(z_i - m) / sum_j exp(z_j - m)cancelsexp(-m)from top and bottom, subtractingrow_maxleaves probabilities unchanged while preventingexp(1000)from overflowing toinf. Better still, any filtered logit set to-infbecomesexp(-inf) = 0.0:
import numpy as np def softmax(logits: np.ndarray) -> np.ndarray: """Convert raw logits [..., vocab_size] into probabilities along the last axis.""" # Subtract each row's maximum so exp() never overflows; -inf entries stay -inf -> exp(-inf) = 0. row_max = np.max(logits, axis=-1, keepdims=True) shifted = logits - row_max exps = np.exp(shifted) row_sums = np.sum(exps, axis=-1, keepdims=True) return exps / row_sums- Divide logits, never probabilities: Dividing probabilities by
Cut off the unlikely tail with top-k filtering
Real vocabularies hold
32,000to200,000tokens. Even if each nonsensical word has only a0.0002chance, tens of thousands of them add up to real probability mass, and drawing just one incoherent token throws off every token after it.Top-k sampling keeps only the
khighest logits in each row and masks every strictly smaller logit to-inf(never0, becauseexp(0) = 1would give masked tokens positive probability!). Sorting a row in ascending order places thek-th largest score at columnvocab_size - k:row = [2.0, 4.5, 1.0, 4.5, 3.0] (vocab_size = 5) sorted ascending = [1.0, 2.0, 3.0, 4.5, 4.5] k = 3 -> index 5 - 3 = 2 -> kth_largest = 3.0 -> [-inf, 4.5, -inf, 4.5, 3.0] k = 2 -> index 5 - 2 = 3 -> kth_largest = 4.5 -> [-inf, 4.5, -inf, 4.5, -inf] k = 1 -> index 5 - 1 = 4 -> kth_largest = 4.5 -> [-inf, 4.5, -inf, 4.5, -inf] (ties kept)Using
<rather than<=keeps all tokens tied with thek-th largest value:import numpy as np def top_k_filter(logits: np.ndarray, k: int) -> np.ndarray: """Return a copy of logits [batch, vocab] in which every entry smaller than the k-th largest value of its row is -inf. Entries tied with the k-th largest value are kept.""" vocab_size = logits.shape[-1] # Keeping >= vocab_size tokens filters nothing; return a copy so caller's array is never mutated. if k >= vocab_size: return logits.copy() # In ascending order per row, index `vocab_size - k` holds the k-th largest logit. sorted_logits = np.sort(logits, axis=-1) kth_largest = sorted_logits[:, vocab_size - k] # shape: [batch_size] # Use strict `<` so tokens tied with the k-th largest score are preserved. filtered = logits.copy() below_threshold = logits < kth_largest[:, None] filtered[below_threshold] = -np.inf return filteredAdapt to model confidence with top-p (nucleus) filtering
A fixed
k = 50is too wide when one token holds99%probability ("The capital of France is ___") and too narrow when hundreds of continuations are equally plausible. Top-p (nucleus) sampling adapts automatically: sort tokens from most likely to least likely, and keep the smallest prefix whose cumulative probability reaches at leastp.How do we avoid an off-by-one bug on the boundary token that crosses
p? Look at the probability mass strictly before each ranked token (mass_before = cumsum(sorted_probs) - sorted_probs). A token is redundant if and only if the higher-ranked tokens already havemass_before >= p:Original probs: [token 0: 0.15, token 1: 0.45, token 2: 0.10, token 3: 0.30], p = 0.70 Sorted rank: rank 0 (tok 1) rank 1 (tok 3) rank 2 (tok 0) rank 3 (tok 2) sorted_probs: 0.45 0.30 0.15 0.10 cumulative_probs: 0.45 0.75 0.90 1.00 mass_before: 0.00 0.45 0.75 0.90 mass_before >= .7: False (keep) False (keep) True (drop) True (drop) Scatter back to vocab order -> keep tokens 1 and 3: [-inf, log(0.45), -inf, log(0.30)]Notice that rank
0always hasmass_before = 0.0 < p(sincep > 0), so the top token is never dropped even if its probability alone exceedsp. We also return early whenp >= 1.0, because floating-point addition can round1.0 - 1e-20up to1.0and accidentally mask tiny tail tokens.from typing import Optional import numpy as np def top_p_filter(logits: np.ndarray, p: float) -> np.ndarray: """Return a copy of logits [batch, vocab] that keeps, in each row, the smallest set of most likely tokens whose total probability is at least p. Every other entry becomes -inf. The most likely token is always kept, and p = 1 keeps every token.""" # Guard p >= 1 early: float rounding can make cumulative mass before a 1e-20 token equal 1.0. if p >= 1.0: return logits.copy() # Sort descending (`-logits`) with kind="stable" so ties break by lower vocabulary index. order = np.argsort(-logits, axis=-1, kind="stable") # shape: [batch_size, vocab_size] sorted_logits = np.take_along_axis(logits, order, axis=-1) sorted_probs = softmax(sorted_logits) # Subtract `sorted_probs` so `mass_before[b, j]` is the probability strictly above rank j. # A token is dropped only when higher-ranked tokens ALREADY reach probability >= p without it. cumulative_probs = np.cumsum(sorted_probs, axis=-1) mass_before = cumulative_probs - sorted_probs remove_sorted = mass_before >= p # Scatter the boolean mask from sorted rank order back to original vocabulary positions. remove_vocab_order = np.zeros_like(remove_sorted) np.put_along_axis(remove_vocab_order, order, remove_sorted, axis=-1) filtered = logits.copy() filtered[remove_vocab_order] = -np.inf return filtered def sample_next_tokens(next_logits: np.ndarray, temperature: float, top_k: Optional[int], top_p: Optional[float], rng: np.random.Generator) -> np.ndarray: """Sample one token ID per batch row after temperature scaling, top-k, and top-p filtering.""" # Apply temperature to raw logits BEFORE top-k and top-p so nucleus mass reflects T. scaled = next_logits / temperature if top_k is not None: scaled = top_k_filter(scaled, top_k) if top_p is not None: scaled = top_p_filter(scaled, top_p) # Softmax renormalizes the surviving logits (masked -inf entries become probability 0). probs = softmax(scaled) batch_size, vocab_size = probs.shape next_tokens = np.zeros(batch_size, dtype=np.int64) for row in range(batch_size): next_tokens[row] = rng.choice(vocab_size, p=probs[row]) return next_tokensTrack batched EOS stopping, padding, and trace a batch
In a batch of
Bprompts, one sequence may emiteos_token_id(end-of-sequence) on step1while another keeps generating until step3. Because a 2D tensor must keep the same length across every row, we maintain a boolean arrayfinishedof shape[B]:- Replace
next_tokens[b]withpad_token_id(defaulting toeos_token_id) for rows that were alreadyfinishedbefore this step. - Update
finished = finished | (next_tokens == eos_token_id). - Append
next_tokens[:, None]and break out of the loop as soon asfinished.all()isTrue.
Doing step 1 before step 2 is essential: reversing them would overwrite the brand-new
eos_token_iditself withpad_token_id!Trace Example 1's 2-row batch
[[0], [2]]under the toy model whose greedy transitions are0 -> 1 -> 2 -> 3 -> 0, witheos_token_id = 3,pad_token_id = 0, andmax_new_tokens = 6:Step Model input Raw argmax finished (in) After pad finished (out) Appended tokens 1 [[0], [2]] [1, 3] [False, False] [1, 3] [False, True] [[0, 1], [2, 3]] 2 [[0, 1], [2, 3]] [2, 0] [False, True] [2, 0] [False, True] [[0, 1, 2], [2, 3, 0]] 3 [[0,1,2], [2,3,0]] [3, 1] [False, True] [3, 0] [True, True] [[0, 1, 2, 3], [2, 3, 0, 0]] -> finished.all() is True: stop after 3 forward passes instead of 6!- Replace
Translate line-by-line to PyTorch
In a live PyTorch environment, the exact same logic translates directly to tensor methods:
import torch @torch.no_grad() # Disable autograd graph tracking so activation memory does not grow each step. def generate_pytorch(model, input_ids: torch.Tensor, max_new_tokens: int, do_sample: bool = False, temperature: float = 1.0, top_k=None, top_p=None, eos_token_id=None, pad_token_id=None, generator=None) -> torch.Tensor: """PyTorch counterpart of generate() (after calling model.eval() and check_arguments).""" if pad_token_id is None: pad_token_id = eos_token_id tokens = input_ids.clone() finished = torch.zeros(tokens.shape[0], dtype=torch.bool, device=tokens.device) for _ in range(max_new_tokens): # Cast to float32 so half-precision (fp16/bf16) model logits stay accurate in softmax/cumsum. next_logits = model(tokens)[:, -1, :].float() if do_sample: next_logits = next_logits / temperature if top_k is not None and top_k < next_logits.shape[-1]: kth_vals = torch.topk(next_logits, top_k, dim=-1).values[:, -1:] next_logits = next_logits.masked_fill(next_logits < kth_vals, float("-inf")) if top_p is not None and top_p < 1.0: sorted_logits, order = torch.sort(next_logits, dim=-1, descending=True, stable=True) sorted_probs = torch.softmax(sorted_logits, dim=-1) mass_before = torch.cumsum(sorted_probs, dim=-1) - sorted_probs remove_sorted = mass_before >= top_p remove = torch.zeros_like(remove_sorted).scatter(1, order, remove_sorted) next_logits = next_logits.masked_fill(remove, float("-inf")) probs = torch.softmax(next_logits, dim=-1) next_tokens = torch.multinomial(probs, num_samples=1, generator=generator).squeeze(1) else: next_tokens = torch.argmax(next_logits, dim=-1) if eos_token_id is not None: next_tokens = next_tokens.masked_fill(finished, pad_token_id) finished = finished | (next_tokens == eos_token_id) tokens = torch.cat([tokens, next_tokens[:, None]], dim=1) if eos_token_id is not None and finished.all(): break return tokensIn PyTorch interviews, always mention calling
model.eval()(to disable dropout), decorating with@torch.no_grad()or@torch.inference_mode()(so autograd does not store activations across steps), and creatingfinishedandgeneratoroninput_ids.device.Complete solution
Putting all validated helpers and the generation loop together gives the complete sandbox solution:
from typing import Callable, Optional import numpy as np # This sandbox provides NumPy rather than PyTorch, so token IDs and logits are NumPy arrays. # Every operation maps 1-to-1 to PyTorch: # np.argmax -> torch.argmax # np.sort -> torch.topk / torch.sort # np.cumsum -> torch.cumsum # np.put_along_axis -> Tensor.scatter # rng.choice -> torch.multinomial # np.concatenate -> torch.cat def softmax(logits: np.ndarray) -> np.ndarray: """Convert raw logits [..., vocab_size] into probabilities along the last axis.""" # Subtract each row's maximum so exp() never overflows; -inf entries stay -inf -> exp(-inf) = 0. row_max = np.max(logits, axis=-1, keepdims=True) shifted = logits - row_max exps = np.exp(shifted) row_sums = np.sum(exps, axis=-1, keepdims=True) return exps / row_sums def top_k_filter(logits: np.ndarray, k: int) -> np.ndarray: """Return a copy of logits [batch, vocab] in which every entry smaller than the k-th largest value of its row is -inf. Entries tied with the k-th largest value are kept.""" vocab_size = logits.shape[-1] # Keeping >= vocab_size tokens filters nothing; return a copy so caller's array is never mutated. if k >= vocab_size: return logits.copy() # In ascending order per row, index `vocab_size - k` holds the k-th largest logit. sorted_logits = np.sort(logits, axis=-1) kth_largest = sorted_logits[:, vocab_size - k] # shape: [batch_size] # Use strict `<` so tokens tied with the k-th largest score are preserved. filtered = logits.copy() below_threshold = logits < kth_largest[:, None] filtered[below_threshold] = -np.inf return filtered def top_p_filter(logits: np.ndarray, p: float) -> np.ndarray: """Return a copy of logits [batch, vocab] that keeps, in each row, the smallest set of most likely tokens whose total probability is at least p. Every other entry becomes -inf. The most likely token is always kept, and p = 1 keeps every token.""" # Guard p >= 1 early: float rounding can make cumulative mass before a 1e-20 token equal 1.0. if p >= 1.0: return logits.copy() # Sort descending (`-logits`) with kind="stable" so ties break by lower vocabulary index. order = np.argsort(-logits, axis=-1, kind="stable") # shape: [batch_size, vocab_size] sorted_logits = np.take_along_axis(logits, order, axis=-1) sorted_probs = softmax(sorted_logits) # Subtract `sorted_probs` so `mass_before[b, j]` is the probability strictly above rank j. # A token is dropped only when higher-ranked tokens ALREADY reach probability >= p without it. cumulative_probs = np.cumsum(sorted_probs, axis=-1) mass_before = cumulative_probs - sorted_probs remove_sorted = mass_before >= p # Scatter the boolean mask from sorted rank order back to original vocabulary positions. remove_vocab_order = np.zeros_like(remove_sorted) np.put_along_axis(remove_vocab_order, order, remove_sorted, axis=-1) filtered = logits.copy() filtered[remove_vocab_order] = -np.inf return filtered def sample_next_tokens(next_logits: np.ndarray, temperature: float, top_k: Optional[int], top_p: Optional[float], rng: np.random.Generator) -> np.ndarray: """Sample one token ID per batch row after temperature scaling, top-k, and top-p filtering.""" # Apply temperature to raw logits BEFORE top-k and top-p so nucleus mass reflects T. scaled = next_logits / temperature if top_k is not None: scaled = top_k_filter(scaled, top_k) if top_p is not None: scaled = top_p_filter(scaled, top_p) # Softmax renormalizes the surviving logits (masked -inf entries become probability 0). probs = softmax(scaled) batch_size, vocab_size = probs.shape next_tokens = np.zeros(batch_size, dtype=np.int64) for row in range(batch_size): next_tokens[row] = rng.choice(vocab_size, p=probs[row]) return next_tokens def check_arguments(input_ids: np.ndarray, max_new_tokens: int, do_sample: bool, temperature: float, top_k: Optional[int], top_p: Optional[float]) -> None: """Validate input tensor shapes and decoding hyperparameters before calling the model.""" if input_ids.ndim != 2 or input_ids.shape[0] == 0 or input_ids.shape[1] == 0: raise ValueError("input_ids must have shape [batch_size, seq_len] with both >= 1") if max_new_tokens < 0: raise ValueError("max_new_tokens must be >= 0") # Greedy mode ignores temperature, top_k, and top_p completely. if not do_sample: return # Writing `not temperature > 0` rejects <= 0 as well as NaN. if not temperature > 0.0: raise ValueError("temperature must be > 0 when sampling; use do_sample=False for greedy") if top_k is not None and top_k < 1: raise ValueError("top_k must be >= 1") if top_p is not None and not 0.0 < top_p <= 1.0: raise ValueError("top_p must be in (0, 1]") def generate(model: Callable[[np.ndarray], np.ndarray], input_ids: np.ndarray, max_new_tokens: int, do_sample: bool = False, temperature: float = 1.0, top_k: Optional[int] = None, top_p: Optional[float] = None, eos_token_id: Optional[int] = None, pad_token_id: Optional[int] = None, rng: Optional[np.random.Generator] = None) -> np.ndarray: """Append up to max_new_tokens tokens to input_ids [batch, prompt_len], one at a time, and return the prompt followed by the new tokens: shape [batch, prompt_len + steps]. model(ids) returns logits [batch, len(ids[0]), vocab]; the next token comes from position -1. do_sample=False: greedy decoding (argmax); temperature, top_k and top_p are ignored. do_sample=True: divide the logits by temperature, keep the top_k tokens, then the top_p nucleus (each filter only if given), and sample from the softmax of what is left. A row that has produced eos_token_id is finished: its later positions get pad_token_id (eos_token_id if pad_token_id is None). Generation stops early once every row is finished. Raise ValueError for bad shapes, max_new_tokens < 0, and (when sampling) temperature <= 0, top_k < 1 or top_p outside (0, 1]. """ input_ids = np.asarray(input_ids, dtype=np.int64) check_arguments(input_ids, max_new_tokens, do_sample, temperature, top_k, top_p) if rng is None: rng = np.random.default_rng() if pad_token_id is None: pad_token_id = eos_token_id # tokens: [batch_size, current_seq_len] copy of prompt + generated tokens so far. tokens = input_ids.copy() # finished: [batch_size] bool mask; True once row b has generated eos_token_id. finished = np.zeros(tokens.shape[0], dtype=bool) for _ in range(max_new_tokens): logits = np.asarray(model(tokens), dtype=np.float64) if logits.ndim != 3 or logits.shape[:2] != tokens.shape: raise ValueError(f"model returned shape {logits.shape}; expected {tokens.shape} + (vocab,)") # Only the final sequence position `-1` predicts the unseen next token. next_logits = logits[:, -1, :] # shape: [batch_size, vocab_size] if do_sample: next_tokens = sample_next_tokens(next_logits, temperature, top_k, top_p, rng) else: next_tokens = np.argmax(next_logits, axis=-1) if eos_token_id is not None: # Pad rows that finished on an EARLIER step first, so a brand-new EOS is kept intact. next_tokens = np.where(finished, pad_token_id, next_tokens) finished = finished | (next_tokens == eos_token_id) tokens = np.concatenate([tokens, next_tokens[:, None]], axis=1) if eos_token_id is not None and finished.all(): break return tokens✅ Submit now — all tests should pass.
Intuition & how it works
Picture writing a story one word at a time with a panel of advisors. Every time you show the panel the words written so far, it hands back a scoreboard of logits (raw, unnormalized scores for every word in the dictionary) at every position. Because earlier words are already written, you look only at the scoreboard for the last position (logits[:, -1, :]), choose one next word, append it to your page, and hand the longer page back to the panel — a feedback loop called autoregressive decoding (meaning each generated token becomes part of the input for generating the next token).
Two naive selection rules fail in opposite ways. Always picking the single highest-scoring word (greedy decoding) is fast and deterministic, yet on open-ended prompts it easily locks into repetitive loops; conversely, sampling blindly from softmax (the formula exp(z_i) / sum_j exp(z_j) that turns raw logits into probabilities summing to 1) across 50,000+ vocabulary words lets thousands of tiny-probability nonsense words add up to enough collective probability to derail the text. Scaling logits by temperature T (sharpening when T < 1, flattening when T > 1), keeping at most the k best candidates (top-k), and keeping only the smallest prefix of top tokens whose probabilities reach p (top-p / nucleus sampling) preserve natural variety while setting every noisy tail token to -inf (probability 0).
Trace one sampling step over a 4-token vocabulary with temperature-scaled probabilities [0.15, 0.45, 0.10, 0.30] and top_p = 0.70:
- Sort tokens from most likely to least likely: token
1(0.45), token3(0.30), token0(0.15), token2(0.10). - Track the probability mass strictly before each ranked token:
[0.00, 0.45, 0.75, 0.90]. - Keep tokens whose
mass_before < 0.70: token1(0.00 < 0.70) and token3(0.45 < 0.70) survive because together they reach0.75 >= 0.70, while tokens0and2become-inf. - Re-running softmax over the survivors renormalizes
[0.45, 0.30]into[0.60, 0.40], from which one token ID is sampled and appended.
Complexity
- Time —
O(N * (F + B * V log V))with sorting (orO(N * (F + B * V))for greedy): LetBbe batch size,Lbe prompt length,Nbemax_new_tokens,Vbevocab_size, andFbe the cost of one model forward pass. The loop runs at mostNsteps (stopping earlier if allBrows emiteos_token_id). Without a cache, re-feeding the growing sequence processesL + (L + 1) + ... + (L + N - 1) = N * L + N * (N - 1) / 2token positions in total (14,950token positions whenL = N = 100). Outside the model itself, each step scansVlogits per row inO(B * V)time for greedyargmax,softmax, and categorical sampling, plusO(B * V log V)when sorting rows fortop_p(ortop_kvianp.sort;torch.topk/np.partitionlowerstop_kalone toO(B * V log k)/O(B * V)). - Space —
O(B * (L + N) + B * V)in the decoder, plusO(B * (L + N) * V)for full-sequence model logits: Storing the growing token buffer takesO(B * (L + N))integers (np.concatenateallocates a fresh copy up to sizeB * (L + N)each step, which can be preallocated into one[B, L + N]buffer if desired), and filtering buffers (sorted_logits,order,probs) useO(B * V)floats. Notice thatmodel(tokens)itself returns shape[B, T, V], which is8 * 2048 * 50,000 * 4 ≈ 3.3 GBin float32 — production inference engines compute the final linear projection only on the last token[:, -1:, :]to shrink that tensor to[B, 1, V].
Edge cases
max_new_tokens = 0: Returns a copy ofinput_idsimmediately without callingmodelat all, leaving the caller's array unmutated.- Empty batch (
batch_size = 0) or empty prompt (seq_len = 0): RaisesValueErrorup front because an empty prompt has no-1position and an empty batch has no sequences to decode (tokenizers prepend a beginning-of-sequence BOS token to handle empty user text). - Ragged EOS completion across a batch: If row
1emitseos_token_idat step1while row0finishes at step3, row1's outputs on steps2and3are overwritten withpad_token_id(oreos_token_idifpad_token_idisNone), and the loop halts right after step3. eos_token_idalready present inside the prompt: Ignored when initializingfinished; a row finishes only when it generateseos_token_idduring the decoding loop.top_k >= vocab_sizeortop_p = 1.0: Both return an unfiltered copy early; in particular, guardingp >= 1.0prevents IEEE-754 float rounding (1.0 - 1e-20 == 1.0) from wrongly masking ultra-low-probability tail tokens.- Tied logits:
top_k_filteruses strict<so all tokens tied at thek-th largest logit survive (top_k = 1samples uniformly among tied maxima, whereas greedyargmaxdeterministically picks the lowest vocabulary index).top_p_filteruseskind="stable"so ties break by vocabulary index and keep the minimum number of tokens needed to reachp. temperature <= 0orNaNwhendo_sample=True: Rejected withValueError(zero divides by zero; negative temperatures invert the model's preferences), whereasdo_sample=Falseignorestemperature,top_k, andtop_p.
Common mistakes
- Slicing the wrong sequence index: Reading
logits[:, 0, :]or applyingargmaxacross all time steps instead of takinglogits[:, -1, :]. - Scaling probabilities instead of logits by temperature: Dividing
softmax(logits)byTand renormalizing cancelsTout and leaves the distribution unchanged. - Off-by-one nucleus masking (
cumsum >= pinstead ofcumsum - probs >= p): Masking wherevercumsum >= pdeletes the exact token that pushed cumulative mass pastp— and when the single most likely token already hasprob >= p, it masks every token to-inf, producingNaNs insoftmax! - Forgetting to un-sort the
top_pmask: Applyingremove_sorteddirectly tologitswithout scattering back throughordermasks arbitrary vocabulary indices instead of the low-ranked tokens. - Setting filtered logits to
0.0instead of-inf: Becauseexp(0.0) = 1.0, setting a negative logit like-5.0to0.0actually boosts that token's probability instead of zeroing it out. - Updating
finishedbefore applyingpad_token_id: Checkingfinished = finished | (next_tokens == eos_token_id)first causesnp.where(finished, pad_token_id, next_tokens)to overwrite the newly generatedeos_token_iditself withpad_token_id. - Forgetting
@torch.no_grad()andmodel.eval()in PyTorch: Leaving autograd enabled retains the computation graph across allmax_new_tokensforward passes (quickly running out of GPU memory), and leaving training mode on keeps dropout active.
Alternative approaches
- Gumbel-max trick for vectorized sampling: Adding independent
Gumbel(0, 1)noise (-log(-log(U))forU ~ Uniform(0, 1)) tofiltered_logitsand takingargmaxalong the last axis draws an exact categorical sample fromsoftmax(filtered_logits)without computingsoftmaxor looping over rows. - Partial selection (
np.partition/torch.topk) fortop_k: Finding thek-th largest threshold withnp.partition(logits, vocab_size - k, axis=-1)runs inO(B * V)average time instead ofO(B * V log V)for a full row sort. - Min-p sampling: Keeping all tokens with
prob >= min_p * max_probadapts dynamically to model confidence liketop_pwithout needingO(V log V)sorting or cumulative sums (threshold_logit = max_logit + log(min_p)).
Follow-up questions
- How does adding a KV cache change autoregressive decoding and its complexity? In a causal Transformer, earlier tokens never attend to future tokens, so their attention key (
K) and value (V) vectors never change as new tokens are appended. A KV cache stores those pastKandVtensors across every layer: step1("prefill") processes the full prompt[B, L]to populate the cache, and every subsequent step ("decode") feeds only the newest single tokentokens[:, -1:]of shape[B, 1]along withpast_key_values, avoiding recomputing projections and self-attention over all prior positions. That cuts total Transformer work acrossNgenerated tokens from quadratic-in-stepsO(N * (L + N)^2)toO(L^2 + N * (L + N)), trading GPU memory of2 * num_layers * num_kv_heads * head_dim * seq_len * batch_sizefloats. - How would you batch prompts that start with different lengths? Pad shorter prompts on the left (not the right!) to match the longest prompt in the batch, and pass a binary attention mask (
0on left-pad slots,1on real tokens) plus adjustedposition_idsso real tokens start at position0and ignore pad tokens during attention. Left padding guarantees every prompt's final real token sits at column-1, sologits[:, -1, :]still gives the true next-token distribution for every row in the batch; with right padding, column-1of a shorter prompt would sit on a meaningless pad token. - When would you choose beam search over top-k / top-p sampling? Beam search is a deterministic breadth-first pruning algorithm that maintains the
beam_widthhighest total log-probability partial sequences at every step rather than committing to one token per step. It shines on closed-ended tasks with a tight target answer — such as machine translation, speech-to-text, or code transpilation — where maximizing sequence likelihood improves accuracy (paired with length normalization, dividing total log-probability bylength^alpha, so beams do not unfairly favor short outputs that hitEOSearly). For open-ended chat or creative writing, beam search costs roughlybeam_widthtimes more compute/KV-cache memory and tends to produce bland, repetitive text, making temperature + top-p/top-k sampling the standard choice.
Follow-up questions
- How does adding a KV cache change autoregressive decoding and its complexity?
- How would you batch prompts that start with different lengths?
- When would you choose beam search over top-k / top-p sampling?
Similar questions
- Low-Latency Tree Ensemble Inference
- Select Score Cutoff for Target Precision
- Payment Fraud Detection Under Class Imbalance and Drift
- Diagnosing and Fixing Overfitting in Supervised Learning
- Correlation Bounds, Equicorrelated Variables, and Box-Muller Sampling
- Feed Click-Through Rate Feature Engineering and Modeling