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.
transformers/pipelinestransformers/generationtransformerstransformers/generation/continuous_batchingThe 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.
Pipeline.__init__ transformers/pipelines/base.py — Initializes pipeline components, execution device, generation defaults, and reusable processing parameters.GenerationConfig.__init__ transformers/generation/configuration_utils.py — Initializes generation settings from keyword arguments and validates the resulting configuration.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.
GenerationConfig.__init__ transformers/generation/configuration_utils.py — Initializes generation settings from keyword arguments and validates the resulting configuration.GenerationConfig.validate transformers/generation/configuration_utils.py — Checks the shown generation settings and combinations, raising for invalid values and collecting minor issues.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.
TextGenerationPipeline._forward transformers/pipelines/text_generation.py — Runs model generation and returns generated sequences grouped by input, together with prompt data and eligible auxiliary tensors.GenerationMixin.generate transformers/generation/utils.py — The shown portion dispatches generation to a custom Hub recipe, continuous batching, or a validated 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.
GenerationMixin.generate transformers/generation/utils.py — The shown portion dispatches generation to a custom Hub recipe, continuous batching, or a validated decoding strategy.GenerationMixin._get_logits_processor transformers/generation/utils.py — Builds the shown configuration-selected logits processors; the supplied excerpt omits the completed list and return.GenerationMixin._get_stopping_criteria transformers/generation/utils.py — Returns configuration-derived stopping criteria merged with caller-supplied criteria.GenerationConfig.__init__ transformers/generation/configuration_utils.py — Initializes generation settings from keyword arguments and validates the resulting configuration.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.
_preprocess_mask_arguments transformers/masking_utils.py — Returns an early-exit decision, normalized mask, packed-sequence indices, and query/key-value lengths and offsets.PagedAttentionCache.__init__ transformers/generation/continuous_batching/cache.py — Builds paged-attention allocators, determines cache capacity, allocates shared storage, and initializes scheduling limits.PagedAttentionMemoryHandler.__init__ transformers/generation/continuous_batching/cache.py — Initializes memory-estimation inputs and records available memory for paged attention.PagedAttentionMemoryHandler.infer_max_batch_tokens_and_num_sectors transformers/generation/continuous_batching/cache.py — Infers max_batch_tokens and num_sectors based on the available memory. Max batch tokens comes from the
config or a default of 8192. Unless the number of sectors is also fixed by the config, the memory left once
the M-proportional tensors are paid for becomes cache sectors, minus the sectors removed to pay for the
attention masks.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.
GenerationMixin._beam_search transformers/generation/utils.py — Begins beam-search generation and iteratively computes processed next-token log probabilities; the supplied excerpt omits completion and return behavior.GenerationMixin._assisted_decoding transformers/generation/utils.py — The shown portion sets up assisted decoding and repeatedly obtains and verifies candidate tokens, reaching speculative token selection when applicable.GenerationMixin._get_candidate_generator transformers/generation/utils.py — Constructs and returns the first candidate-generator implementation matching the generation settings and assistant inputs.AssistantVocabTranslatorCache.get_translator transformers/generation/candidate_generator.py — Returns the cached translator for a tokenizer pair, creating it when absent.