Generation utilities

This part handles the generation loop, selecting the next tokens and managing the cache of past computations.

Columns are parts of the code, grouped by process. Read top to bottom. Solid arrow: hands work over. Dashed: the reply. Purple: crosses between processes. Hook: work inside one part. Dashed boxes repeat. Hover a column name or a step for its full text.

MAIN PROCESSToken generation loopInitialize componentsPass generation argumentsValidate configurationStart generation runDispatch to strategySelect decoding modeCompute attention m…Request memory alloca…All…Process next token
Pipeline
Generation
Model
Paged Attn
1Initialize pipeline and device — The pipeline wrapper initializes the model components and selects the best available processing device, prioritizing accelerators like CUDA or MPS before falling back to CPU. It sets up default generation parameters and stores the tokenizer and other preprocessing tools. This setup happens once when you first create the pipeline object.
2Validate generation settings — The generation utilities receive the keyword arguments and validate all settings, checking for invalid combinations like negative token limits or unsupported stopping criteria. It converts configuration dictionaries into proper objects and logs warnings for deprecated options. Any invalid values cause an immediate error before generation begins.
3Run model generation — The pipeline wrapper runs the generation process, converting your prompt into input tokens and preparing the attention mask. It determines whether to use continuous batching or standard generation based on the configuration. The wrapper then dispatches to the appropriate decoding strategy to produce the output sequences.
4Dispatch decoding strategy — The generation utilities select the appropriate decoding strategy, such as greedy search or beam search, and build the necessary logits processors to modify token probabilities. It constructs stopping criteria to determine when generation should end, such as reaching maximum length or encountering an end-of-sentence token. The utilities then enter the main generation loop.
5Manage paged attention memory — The continuous batching system estimates memory requirements and allocates storage for the attention cache, organizing it into pages for efficient access. It normalizes attention masks and computes the offsets needed for query and key-value operations. This system enables multiple sequences to be processed together without memory conflicts.
6Iterate generation loop — The generation utilities run the main loop, repeatedly calling the model forward pass to compute logits for each candidate token. It applies logits processors to modify probabilities, samples or selects the next token, and updates the cache of past computations. The loop continues until all stopping criteria are met.
STEP · hover for full text