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:

  1. top_k_filter(logits: np.ndarray, k: int) -> np.ndarray Return a new [batch_size, vocab_size] array where every entry strictly smaller (<) than the k-th largest logit in its row becomes -np.inf. Any entry tied with the k-th largest score is retained. When k >= vocab_size, return an unmodified copy.

  2. top_p_filter(logits: np.ndarray, p: float) -> np.ndarray Return 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 least p, 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 when p >= 1.0, retain every token in the row.

  3. 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.ndarray Repeatedly generate and append one token per batch row for up to max_new_tokens steps, returning an int64 array of shape [batch_size, prompt_len + steps_run]:

    • Greedy mode (do_sample=False): Choose the lowest vocabulary index achieving the maximum logit via argmax along the last axis. Ignore temperature, top_k, and top_p.
    • Sampling mode (do_sample=True): In exact order, divide logits[:, -1, :] by temperature, apply top_k_filter if top_k is provided, apply top_p_filter if top_p is provided, compute numerically stable row-wise softmax probabilities, and draw one token ID per row 0 .. batch_size - 1 using rng.choice(vocab_size, p=probs[row]) (initializing np.random.default_rng() when rng is None).
    • End-of-sequence (eos_token_id) & padding: When eos_token_id is given, a row becomes finished once it emits eos_token_id during decoding (occurrences already inside input_ids do not finish the row). On later steps, any already-finished row has its emitted token replaced by pad_token_id (defaulting to eos_token_id when pad_token_id is None). Stop the loop immediately once every row in the batch is finished.

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_ids must be a 2D array with batch_size >= 1 and prompt_len >= 1; max_new_tokens must satisfy max_new_tokens >= 0 (max_new_tokens == 0 returns a copy of input_ids without calling model).
  • model(tokens) must return a 3D array whose first two dimensions match tokens.shape, with vocab_size >= 1.
  • When do_sample=True, require temperature > 0 (finite, non-NaN), top_k >= 1 (if not None), and 0.0 < top_p <= 1.0 (if not None).
  • Raise ValueError whenever any shape or hyperparameter constraint above is violated (when do_sample=False, skip validation of temperature, top_k, and top_p).

Step-by-step walkthrough

  1. 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 position i. Because positions 0 through T - 2 already 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 -> sample
    

    Here B is batch_size, T is current_sequence_length (growing by 1 each step), and V is vocab_size.

    Because this practice sandbox provides NumPy rather than PyTorch, solution.py uses 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.

  2. 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 via argmax. Greedy decoding is deterministic and never uses temperature, top_k, or top_p, so we validate sampling hyperparameters only when do_sample=True.

    Up front, we also verify that input_ids is a non-empty 2D batch (batch_size >= 1 and seq_len >= 1, since an empty sequence has no -1 position to read logits from) and that max_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.

  3. Scale with temperature and compute a stable softmax

    To sample randomly, we convert a row of logits z into probabilities using softmax: p_i = exp(z_i) / sum_j exp(z_j). Temperature T > 0 reshapes those probabilities by dividing the raw logits z / T before 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 T and dividing by their new sum cancels T out completely!
    • Subtract the row maximum before exp(): Because exp(z_i - m) / sum_j exp(z_j - m) cancels exp(-m) from top and bottom, subtracting row_max leaves probabilities unchanged while preventing exp(1000) from overflowing to inf. Better still, any filtered logit set to -inf becomes exp(-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
    
  4. Cut off the unlikely tail with top-k filtering

    Real vocabularies hold 32,000 to 200,000 tokens. Even if each nonsensical word has only a 0.0002 chance, 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 k highest logits in each row and masks every strictly smaller logit to -inf (never 0, because exp(0) = 1 would give masked tokens positive probability!). Sorting a row in ascending order places the k-th largest score at column vocab_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 the k-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 filtered
    
  5. Adapt to model confidence with top-p (nucleus) filtering

    A fixed k = 50 is too wide when one token holds 99% 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 least p.

    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 have mass_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 0 always has mass_before = 0.0 < p (since p > 0), so the top token is never dropped even if its probability alone exceeds p. We also return early when p >= 1.0, because floating-point addition can round 1.0 - 1e-20 up to 1.0 and 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_tokens
    
  6. Track batched EOS stopping, padding, and trace a batch

    In a batch of B prompts, one sequence may emit eos_token_id (end-of-sequence) on step 1 while another keeps generating until step 3. Because a 2D tensor must keep the same length across every row, we maintain a boolean array finished of shape [B]:

    1. Replace next_tokens[b] with pad_token_id (defaulting to eos_token_id) for rows that were already finished before this step.
    2. Update finished = finished | (next_tokens == eos_token_id).
    3. Append next_tokens[:, None] and break out of the loop as soon as finished.all() is True.

    Doing step 1 before step 2 is essential: reversing them would overwrite the brand-new eos_token_id itself with pad_token_id!

    Trace Example 1's 2-row batch [[0], [2]] under the toy model whose greedy transitions are 0 -> 1 -> 2 -> 3 -> 0, with eos_token_id = 3, pad_token_id = 0, and max_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!
    
  7. 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 tokens
    

    In 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 creating finished and generator on input_ids.device.

  8. 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:

  1. Sort tokens from most likely to least likely: token 1 (0.45), token 3 (0.30), token 0 (0.15), token 2 (0.10).
  2. Track the probability mass strictly before each ranked token: [0.00, 0.45, 0.75, 0.90].
  3. Keep tokens whose mass_before < 0.70: token 1 (0.00 < 0.70) and token 3 (0.45 < 0.70) survive because together they reach 0.75 >= 0.70, while tokens 0 and 2 become -inf.
  4. 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 (or O(N * (F + B * V)) for greedy): Let B be batch size, L be prompt length, N be max_new_tokens, V be vocab_size, and F be the cost of one model forward pass. The loop runs at most N steps (stopping earlier if all B rows emit eos_token_id). Without a cache, re-feeding the growing sequence processes L + (L + 1) + ... + (L + N - 1) = N * L + N * (N - 1) / 2 token positions in total (14,950 token positions when L = N = 100). Outside the model itself, each step scans V logits per row in O(B * V) time for greedy argmax, softmax, and categorical sampling, plus O(B * V log V) when sorting rows for top_p (or top_k via np.sort; torch.topk / np.partition lowers top_k alone to O(B * V log k) / O(B * V)).
  • Space — O(B * (L + N) + B * V) in the decoder, plus O(B * (L + N) * V) for full-sequence model logits: Storing the growing token buffer takes O(B * (L + N)) integers (np.concatenate allocates a fresh copy up to size B * (L + N) each step, which can be preallocated into one [B, L + N] buffer if desired), and filtering buffers (sorted_logits, order, probs) use O(B * V) floats. Notice that model(tokens) itself returns shape [B, T, V], which is 8 * 2048 * 50,000 * 4 ≈ 3.3 GB in 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 of input_ids immediately without calling model at all, leaving the caller's array unmutated.
  • Empty batch (batch_size = 0) or empty prompt (seq_len = 0): Raises ValueError up front because an empty prompt has no -1 position 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 1 emits eos_token_id at step 1 while row 0 finishes at step 3, row 1's outputs on steps 2 and 3 are overwritten with pad_token_id (or eos_token_id if pad_token_id is None), and the loop halts right after step 3.
  • eos_token_id already present inside the prompt: Ignored when initializing finished; a row finishes only when it generates eos_token_id during the decoding loop.
  • top_k >= vocab_size or top_p = 1.0: Both return an unfiltered copy early; in particular, guarding p >= 1.0 prevents IEEE-754 float rounding (1.0 - 1e-20 == 1.0) from wrongly masking ultra-low-probability tail tokens.
  • Tied logits: top_k_filter uses strict < so all tokens tied at the k-th largest logit survive (top_k = 1 samples uniformly among tied maxima, whereas greedy argmax deterministically picks the lowest vocabulary index). top_p_filter uses kind="stable" so ties break by vocabulary index and keep the minimum number of tokens needed to reach p.
  • temperature <= 0 or NaN when do_sample=True: Rejected with ValueError (zero divides by zero; negative temperatures invert the model's preferences), whereas do_sample=False ignores temperature, top_k, and top_p.

Common mistakes

  • Slicing the wrong sequence index: Reading logits[:, 0, :] or applying argmax across all time steps instead of taking logits[:, -1, :].
  • Scaling probabilities instead of logits by temperature: Dividing softmax(logits) by T and renormalizing cancels T out and leaves the distribution unchanged.
  • Off-by-one nucleus masking (cumsum >= p instead of cumsum - probs >= p): Masking wherever cumsum >= p deletes the exact token that pushed cumulative mass past p — and when the single most likely token already has prob >= p, it masks every token to -inf, producing NaNs in softmax!
  • Forgetting to un-sort the top_p mask: Applying remove_sorted directly to logits without scattering back through order masks arbitrary vocabulary indices instead of the low-ranked tokens.
  • Setting filtered logits to 0.0 instead of -inf: Because exp(0.0) = 1.0, setting a negative logit like -5.0 to 0.0 actually boosts that token's probability instead of zeroing it out.
  • Updating finished before applying pad_token_id: Checking finished = finished | (next_tokens == eos_token_id) first causes np.where(finished, pad_token_id, next_tokens) to overwrite the newly generated eos_token_id itself with pad_token_id.
  • Forgetting @torch.no_grad() and model.eval() in PyTorch: Leaving autograd enabled retains the computation graph across all max_new_tokens forward 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)) for U ~ Uniform(0, 1)) to filtered_logits and taking argmax along the last axis draws an exact categorical sample from softmax(filtered_logits) without computing softmax or looping over rows.
  • Partial selection (np.partition / torch.topk) for top_k: Finding the k-th largest threshold with np.partition(logits, vocab_size - k, axis=-1) runs in O(B * V) average time instead of O(B * V log V) for a full row sort.
  • Min-p sampling: Keeping all tokens with prob >= min_p * max_prob adapts dynamically to model confidence like top_p without needing O(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 past K and V tensors across every layer: step 1 ("prefill") processes the full prompt [B, L] to populate the cache, and every subsequent step ("decode") feeds only the newest single token tokens[:, -1:] of shape [B, 1] along with past_key_values, avoiding recomputing projections and self-attention over all prior positions. That cuts total Transformer work across N generated tokens from quadratic-in-steps O(N * (L + N)^2) to O(L^2 + N * (L + N)), trading GPU memory of 2 * num_layers * num_kv_heads * head_dim * seq_len * batch_size floats.
  • 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 (0 on left-pad slots, 1 on real tokens) plus adjusted position_ids so real tokens start at position 0 and ignore pad tokens during attention. Left padding guarantees every prompt's final real token sits at column -1, so logits[:, -1, :] still gives the true next-token distribution for every row in the batch; with right padding, column -1 of 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_width highest 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 by length^alpha, so beams do not unfairly favor short outputs that hit EOS early). For open-ended chat or creative writing, beam search costs roughly beam_width times 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

Similar questions

More Inception interview questions

All 1 Inception questions →