This part initializes the tokenizer that converts text into numbers and creates attention masks.
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/models/autotransformerstransformers/utilstransformers/models/llamatransformers/generationtransformers/integrationsThe system resolves the model identifier and retrieves its configuration file. It checks for a valid model type and ensures the requested revision is available, defaulting to the main branch if not specified. The configuration dictionary is loaded from a local file, cache, or downloaded from the Hub.
pipeline transformers/pipelines/__init__.py — Begins resolving the model, configuration, task, and custom implementation for a pipeline; construction and return are beyond the supplied excerpt.AutoConfig.from_pretrained transformers/models/auto/configuration_auto.py — Returns a configuration instance selected from trusted remote code or the registered model-type mapping.PreTrainedConfig.get_config_dict transformers/configuration_utils.py — Returns the resolved configuration dictionary and remaining keyword arguments, following a configuration-file redirect when present.The configuration dictionary is loaded from a JSON file, either locally or from the remote repository. The system handles file resolution, checking for redirects and ensuring the file exists. Default values are applied for missing keys, and the model type is validated against known architectures.
PreTrainedConfig.get_config_dict transformers/configuration_utils.py — Returns the resolved configuration dictionary and remaining keyword arguments, following a configuration-file redirect when present.PreTrainedConfig._get_config_dict transformers/configuration_utils.py — Returns a configuration dictionary loaded from a local file, directory, cache, or Hub, together with remaining keyword arguments.cached_file transformers/utils/hub.py — Returns the resolved path for one requested file, or None when the delegated lookup returns None.The system locates the requested configuration file, first checking the local filesystem and cache. If not found locally, it downloads the file from the remote repository, respecting offline mode settings. The resolved file path is returned for loading.
cached_file transformers/utils/hub.py — Returns the resolved path for one requested file, or None when the delegated lookup returns None.cached_files transformers/utils/hub.py — Locates requested files locally or through the Hub/cache, with final remote recovery and return logic truncated.The pipeline initializes its core components, selecting the appropriate execution device such as a GPU or CPU. Generation defaults are configured, including maximum length and sampling parameters. The system prepares reusable processing parameters and sets up the tokenizer for text conversion.
Pipeline.__init__ transformers/pipelines/base.py — Initializes pipeline components, execution device, generation defaults, and reusable processing parameters.load_assistant_model transformers/pipelines/base.py — Returns an assistant model and any needed assistant tokenizer, or (None, None) when assistance is inapplicable.AutoTokenizer.from_pretrained transformers/models/auto/tokenization_auto.py — Selects and sometimes loads a tokenizer through explicit choices, model metadata, and compatibility checks; the final selection path is truncated.AutoConfig.from_pretrained transformers/models/auto/configuration_auto.py — Returns a configuration instance selected from trusted remote code or the registered model-type mapping.A new tokenizer backend is initialized using the selected tokenizer file. The system configures tokenization settings including maximum sequence length, padding direction, and truncation behavior. Special tokens are identified and mapped to their corresponding IDs for proper text processing.
MistralCommonBackend.from_pretrained transformers/tokenization_mistral_common.py — Returns a new Mistral backend using a tokenizer file selected from a local directory or downloaded from a repository.MistralCommonBackend.__init__ transformers/tokenization_mistral_common.py — Initializes a Mistral tokenizer backend from a tokenizer file and configures its tokenization settings.The system selects the appropriate tokenizer assets from the model repository, including vocabulary files and merge rules. It resolves paths for both fast and legacy tokenizer formats, preferring the fast version when available. Tokenizer configuration is read to determine the correct tokenizer class.
PreTrainedTokenizerBase.from_pretrained transformers/tokenization_utils_base.py — Selects tokenizer assets and begins resolving their paths from a local source or model repository in the visible portion.AutoTokenizer.from_pretrained transformers/models/auto/tokenization_auto.py — Selects and sometimes loads a tokenizer through explicit choices, model metadata, and compatibility checks; the final selection path is truncated.PreTrainedTokenizerBase._from_pretrained transformers/tokenization_utils_base.py — Prepares tokenizer initialization settings and reconstructs added and special token metadata in the visible portion.TokenizersBackend.convert_to_native_format transformers/tokenization_utils_tokenizers.py — Returns backend initialization arguments for supported serialization paths, or begins preparing fallback conversion in the visible portion.The model processes the input batch through its decoder layers, computing hidden states and attention outputs. Each layer applies self-attention and feed-forward transformations to the input embeddings. The final layer produces logits that represent the probability distribution over the vocabulary.
LlamaForCausalLM.forward transformers/models/llama/modeling_llama.py — Returns language-model logits, optional label loss, and the underlying model's cache and auxiliary outputs.AutoTokenizer.from_pretrained transformers/models/auto/tokenization_auto.py — Selects and sometimes loads a tokenizer through explicit choices, model metadata, and compatibility checks; the final selection path is truncated.LlamaModel.forward transformers/models/llama/modeling_llama.py — Returns normalized decoder hidden states and the cache after processing the input batch through the configured layers.create_causal_mask transformers/masking_utils.py — Returns a backend-specific causal attention mask, or a bidirectional mask when the config disables causality.A 4D boolean attention mask is created for use with scaled dot-product attention. The system checks if the mask can be skipped for causal attention with single query tokens, allowing optimized kernel dispatch. The mask indicates which positions each token can attend to.
sdpa_mask transformers/masking_utils.py — Returns a 4D boolean SDPA mask or None when an allowed mask-skipping check succeeds._ignore_causal_mask_sdpa transformers/masking_utils.py — Detects whether the causal mask can be ignored in case PyTorch's SDPA is used, rather relying on SDPA's is_causal argument.
In case no token is masked in the 2D padding_mask argument, if query_length == 1 or
key_value_length == query_length, we rather rely on SDPA is_causal argument to use causal/non-causal masks,
allowing to dispatch to the flash attention kernel (that can otherwise not be used if a custom attn_mask is
passed).The system temporarily switches grouped matrix multiplication experts to batched implementation for improved decoding performance. This optimization is applied around the decoding work and restored afterward. The switch only occurs on non-CPU devices where applicable.
GenerationMixin._optimize_model_for_decode transformers/generation/utils.py — Temporarily switches grouped_mm experts to batched_mm around the yielded decoding work and restores their original implementations.PreTrainedModel.set_experts_implementation transformers/modeling_utils.py — Updates eligible model and submodel expert implementation configuration after validation.The model and submodel expert implementation configuration is updated after validation. The system checks top-level changes and iterates through modules to apply the requested implementation. Eligible descendants receive the resolved implementation setting.
PreTrainedModel.set_experts_implementation transformers/modeling_utils.py — Updates eligible model and submodel expert implementation configuration after validation.PreTrainedModel.__init__ transformers/modeling_utils.py — Initializes model configuration, implementation selections, optional generation settings, loss type, and output-recording registration.PreTrainedModel._check_and_adjust_attn_implementation transformers/modeling_utils.py — Resolves and validates an attention implementation, preloads Flash Attention where applicable, and returns its selected name.lazy_import_flash_attention transformers/modeling_flash_attention_utils.py — Returns cached or newly imported Flash Attention functions and keyword processors.A kernel module is loaded and its attention function is registered for optimized computation. The system parses the kernel name, resolves the correct revision, and imports the necessary functions. Mask implementation is configured based on the kernel type.
load_and_register_attn_kernel transformers/integrations/hub_kernels.py — Loads a kernel module and registers its attention function and mask implementation, or returns None for a non-kernel name.MTPCandidateGenerator.__init__ transformers/generation/candidate_generator.py — Initializes an MTP candidate generator with an MTP model, recording cache, and decoding settings.MtpModel.from_pretrained transformers/modeling_layers.py — Returns an MTP model loaded from the main model's checkpoint and retied to the main model.PreTrainedModel.set_experts_implementation transformers/modeling_utils.py — Updates eligible model and submodel expert implementation configuration after validation.The model weights are loaded from the checkpoint files, either locally or downloaded from the repository. The system handles sharded checkpoints by collecting all shards and their metadata. Weight conversion is applied as needed to match the model architecture.
MtpModel.from_pretrained transformers/modeling_layers.py — Returns an MTP model loaded from the main model's checkpoint and retied to the main model._get_resolved_checkpoint_files transformers/modeling_utils.py — Resolves a checkpoint filename or sharded index from a local path or repository, with the final return logic absent from the excerpt.auto_conversion transformers/safetensors_conversion.py — Resolves a converted safetensors checkpoint from a conversion PR reference and returns its path, revision, and sharding flag.get_checkpoint_shard_files transformers/utils/hub.py — For a given model:
- download and cache all the shards of a sharded checkpoint if pretrained_model_name_or_path is a model ID on the
Hub
- returns the list of paths to all the shards, as well as some metadata.
For the description of each arg, see [PreTrainedModel.from_pretrained]. index_filename is the full path to the
index (downloaded and cached if pretrained_model_name_or_path is a model ID on the Hub).All shards of a sharded checkpoint are downloaded and cached if the model is from a remote repository. The system returns the list of paths to all shards along with metadata. Local models use existing files without downloading.
get_checkpoint_shard_files transformers/utils/hub.py — For a given model:
- download and cache all the shards of a sharded checkpoint if pretrained_model_name_or_path is a model ID on the
Hub
- returns the list of paths to all the shards, as well as some metadata.
For the description of each arg, see [PreTrainedModel.from_pretrained]. index_filename is the full path to the
index (downloaded and cached if pretrained_model_name_or_path is a model ID on the Hub).cached_files transformers/utils/hub.py — Locates requested files locally or through the Hub/cache, with final remote recovery and return logic truncated.Checkpoint tensors are prepared for model loading by visiting entries in order and applying weight conversions. The system handles device mapping, dtype selection, and quantization settings. Unmatched converter targets are recorded for error reporting.
convert_and_load_state_dict_in_model transformers/core_model_loading.py — The shown portion prepares checkpoint tensors for model loading and starts converting collected weights.MtpModel.from_pretrained transformers/modeling_layers.py — Returns an MTP model loaded from the main model's checkpoint and retied to the main model.log_state_dict_report transformers/utils/loading_report.py — Logs a loading report when present and raises RuntimeError for recorded errors or disallowed loading issues.rename_source_key transformers/core_model_loading.py — Rename a checkpoint key by first applying all WeightRenamings, then at most one WeightConverter.
This means that the WeightConverter must specify the final name for the key, but some WeightRenamings can act on other
parts of that key beforehand. If reverse is True, i.e. when reverting all the WeightTransforms, the opposite is performed
to be coherent and correctly respect the scope_prefix of all WeightTransforms: first try to match 1 WeightConverter, and only
then try to apply all WeightRenamings. Indeed, in reverse mode, all reverse transforms should be applied in the opposite order to
be consistent.
Note that we proceed in this way because there is no need for a Converter-then-Rename order because Converters act only on specific
leaf patterns, so no subsequent Renamings should ever target their output.
Args:
source_key (str):
The original checkpoint key to rename.
weight_renamings (list[WeightRenaming]):
Applied in order; every matching renaming fires (they may chain).
weight_converters (list[WeightConverter]):
Applied after all renamings; at most one may match. Subsequent converters are skipped.
base_model_prefix (str, *optional*):
Base-model prefix to add or strip when both base_model_prefix and meta_state_dict are given.
meta_state_dict (dict, *optional*):
Meta state dict used to decide whether base_model_prefix should be added or stripped.
reverse (bool, *optional*):
This specifies if we are reverting all the WeightTransforms (saving back original format).
Returns:
tuple[str, str | None]: The renamed key and the matched converter's source pattern
(or None if no converter matched).A loading report is logged when present, showing information about missing, unexpected, or mismatched keys. The system raises a runtime error for recorded errors or disallowed loading issues. Conversion errors are highlighted with guidance for resolution.
log_state_dict_report transformers/utils/loading_report.py — Logs a loading report when present and raises RuntimeError for recorded errors or disallowed loading issues.LoadStateDictInfo.create_loading_report transformers/utils/loading_report.py — Returns a formatted loading report with explanatory notes, or None when no report rows exist.A dynamic cache is initialized with configured layers for storing key and value states during generation. The cache supports lazy layer creation and optional offloading for memory efficiency. Static cache layers are constructed for decoder configurations with maximum cache length.
DynamicCache.__init__ transformers/cache_utils.py — Initializes a dynamic cache with configured layers, supplied key/value data, or lazy layer creation.MTPCandidateGenerator.__init__ transformers/generation/candidate_generator.py — Initializes an MTP candidate generator with an MTP model, recording cache, and decoding settings.MtpModel.from_pretrained transformers/modeling_layers.py — Returns an MTP model loaded from the main model's checkpoint and retied to the main model.StaticCache.__init__ transformers/cache_utils.py — Initializes static cache layers selected from the decoder configuration with the supplied maximum cache length.