Cognibiz

Hugging Face Transformers v4.45: from model selection to controlled resultshuggingface.co

AI technologies, organized by technology area.

Hugging Face Hub: the real “Use this model” panel, showing Transformers code for sentiment analysis with DistilBERT. No model was run.Inset: Educational pipeline, not a complete internal architecture. The cover panel belongs to the Hub; Transformers is a library used by the code.Credit and source

The sketch explained

Transformers: connecting text to a model

The tokenizer turns text into token IDs. The model uses these inputs to produce a task-specific output, here a sentiment prediction.

On a small screen, scroll the diagram horizontally to read its labels.

Transformers: connecting text to a modelInput text · Tokenizer · Pretrained model · Task outputInput textTokenizerPretrained modelTask output
Input text
Text is the input to this sentiment-analysis example.
Tokenizer
The model’s tokenizer prepares the required IDs and masks.
Pretrained model
Loaded weights and configuration determine the model’s operations.
Task output
Output depends on the task and checkpoint; not every model generates text.
Educational pipeline, not a complete internal architecture. The cover panel belongs to the Hub; Transformers is a library used by the code.Technical documentation
Updated

UNDERSTANDING THE SYSTEM

Hugging Face Transformers v4.45: from model selection to controlled results

Transformers provides a common interface for preparing inputs, loading pretrained architectures and adapting them to a task. Its apparent simplicity depends on a precise contract between tokenizer, configuration, weights, output head and compute backend; generation adds context and memory constraints.

02 / CHAPTER

Library, architecture and Hub: three different objects

Transformers is Hugging Face’s software library. Transformer denotes a family of architectures that notably use attention; the Hub is a service for hosting and discovering artifacts. A Hub repository may contain weights, a configuration, a tokenizer and a model card. Installing the library therefore supplies neither every set of weights nor a hosted inference service.

The 4.45 series adds integrations including Llama 3.2 and Qwen2-VL, as well as Modular Transformers for contributors. These additions do not mean that an existing program accepts every model: architecture, task, backend and dependencies must match. This dossier retains the catalog version and does not attribute later capabilities to 4.45.

The library relies on compute frameworks including PyTorch, TensorFlow and Flax, with different model coverage. An Auto class simplifies the interface; it does not automatically convert weights, operators or backend capabilities. A qualified configuration must identify the versions actually used together.

References for this chapter[1][2][3]

03 / CHAPTER

Choose the task before choosing an output head

An encoder such as BERT produces contextualized representations by consulting permitted positions on both sides. A classification head can turn a sequence representation into category scores. A causal decoder predicts the next token from the permitted past. An encoder-decoder architecture encodes an input and then generates an output, for example in translation.

The head is the module that adapts an internal representation to an objective. A base model does not necessarily provide the classification scores an application expects; a newly initialized head is not already trained. Warnings about missing or unexpected weights need interpretation, even when loading completes.

To route messages, start with defined categories and a representative validation set; to draft a response, define the required format, stopping conditions and acceptable errors. A classification score is not a calibrated probability by convention alone, and fluent text does not establish truth.

References for this chapter[3][5][8]

04 / CHAPTER

Configuration, tokenizer and weights must agree

The configuration describes the model type and dimensions, among other settings; weights hold learned parameters. The tokenizer carries a vocabulary and rules for segmentation, normalization and special tokens. Replacing it while keeping the weights can change what token IDs mean without immediately causing a shape error.

Auto classes select an implementation from the supplied artifacts. The task-specific variant also selects the appropriate head. Building a model from its configuration alone initializes parameters: it does not recover pretrained knowledge. For images, audio or multimodal inputs, a processor can combine the necessary transformations beyond text.

For reproducibility, pin a repository revision and preserve configuration, tokenizer or processor, weights, label mapping and generation parameters together. Also keep the license, model card and data provenance. The library’s license does not automatically grant the same rights over every model and dataset.

A successful load starts with a coherent contract

Three complementary checks; geometric shapes represent artifacts, not services to call.

  1. Describe

    Configuration specifies an architecture and dimensions; it does not contain learned parameters.

  2. Encode

    The tokenizer transforms text with the associated vocabulary. The same IDs must denote the same tokens for the selected weights.

  3. Connect

    The task class connects architecture, weights and output head. A pinned revision makes this bundle retrievable.

References for this chapter[3][4][16]

05 / CHAPTER

Padding, truncation and masks serve different purposes

A token can be a word fragment, character or another unit depending on the tokenizer. Word count therefore cannot reliably predict input length, especially across languages. Padding adds positions to create a rectangular tensor; truncation removes tokens. A poorly chosen limit can remove exactly the negation or clause that determines a category.

The input attention mask generally distinguishes real positions from padding. A causal mask imposes a different constraint: a position must not consult future tokens. Masking loss labels is a third operation. A zero in the input mask does not automatically exclude that position from every loss function.

Constructed example: sequences of lengths 3 and 5 occupy 10 positions with right padding, including 8 useful positions and 2 added positions, or 20% of allocated positions. This is a layout calculation, with no measured speedup. Grouping similar lengths can reduce this waste. For batched generation with decoder-only models, the 4.45 guide recommends left padding; that choice does not generalize to BERT.

Two masks, two questions

An abstract five-position example. Numbers describe layout and attention permissions, with no real vocabulary or performance measurement.

  1. Make the batch rectangular

    Sequences 11, 12, 13 and 21, 22, 23, 24, 25 align to five positions; two zeros represent right padding here.

  2. Identify useful positions

    The mask 1, 1, 1, 0, 0 distinguishes three real tokens from padding; it is not the causal mask.

  3. Block the future

    The triangular matrix illustrates causal attention: row i can consult columns through i. Padding imposes an additional constraint.

sequences = [[11, 12, 13], [21, 22, 23, 24, 25]]
pad_id = 0
width = max(map(len, sequences))
input_ids = [s + [pad_id] * (width - len(s)) for s in sequences]
attention_mask = [[1] * len(s) + [0] * (width - len(s)) for s in sequences]
useful = sum(map(sum, attention_mask))
allocated = len(sequences) * width
assert input_ids[0] == [11, 12, 13, 0, 0]
assert attention_mask[0] == [1, 1, 1, 0, 0]
assert (useful, allocated) == (8, 10)
assert allocated - useful == 2
Dependency-free Python: explicit construction of padding and the input mask. IDs are invented for demonstration; no real tokenization or model execution.

References for this chapter[6][5][8]

06 / CHAPTER

From a convenient pipeline to inspectable inference

A pipeline brings preprocessing, model execution and postprocessing together for a task. It helps establish initial behavior, but defaults may select a model and load artifacts. For a controlled application, supply the components, task and options explicitly; inspect results before connecting them to a business process.

The documentary example below assumes a previously reviewed local classifier with a trained head, compatible tokenizer and safetensors files. It rejects a missing directory and network access during loading. The two strings A and B check batch shape only; they demonstrate no classification quality. The example length of 128 must be checked against the model and data.

Model evaluation mode and disabling gradient recording are separate operations in PyTorch. Raw outputs, or logits, then require task-specific interpretation: mutually exclusive categories, multiple labels and regression need different processing. A larger batch can improve throughput or exhaust memory; measure it with the lengths actually encountered.

from pathlib import Path
import torch
from transformers import AutoTokenizer, AutoModelForSequenceClassification

artifact = Path("reviewed_local_classifier")
if not artifact.is_dir():
    raise FileNotFoundError(artifact)
tokenizer = AutoTokenizer.from_pretrained(
    artifact, local_files_only=True, trust_remote_code=False
)
model = AutoModelForSequenceClassification.from_pretrained(
    artifact, local_files_only=True, trust_remote_code=False,
    use_safetensors=True
)
model.eval()
inputs = tokenizer(
    ["A", "B"], padding=True, truncation=True,
    max_length=128, return_tensors="pt"
)
with torch.inference_mode():
    logits = model(**inputs).logits
assert logits.shape[0] == 2
Unexecuted example for review: CPU loading of previously inspected local files, without remote code or fallback to another weight format. This directory is an explicit prerequisite, not a model supplied with the dossier.

References for this chapter[7][4][16]

07 / CHAPTER

Prefill, decoding and the KV cache: context has a cost

For a causal decoder, prefill processes prompt tokens and prepares attention keys and values. Decoding then selects a token, feeds it back and continues. The KV cache retains past keys and values to avoid recomputing them; it is neither a document database nor durable conversation memory. A new request does not automatically inherit it.

Cache memory depends on length, batch size, layers, KV head count, head dimension and numeric type. Educational assumption excluding overhead: 2 × 24 layers × 1 sequence × 1,024 tokens × 8 KV heads × 64 values × 2 bytes = 50,331,648 bytes, or 48 MiB. Doubling length gives 96 MiB in this calculation alone; this is neither total memory nor a property of every model.

Dynamic, static, offloaded and quantized caches trade memory, allocation behavior and compatibility constraints. A static cache may reserve more than the used context; an offloaded cache adds transfers. Quantizing weights does not automatically quantize the cache. Even with caching, decoding must consult permitted context and remains bounded by architecture, memory and the requested workload.

What caching avoids, and what grows

The sequence 1, 2, 3 then 4 then 5 is schematic. The two rows are K and V; no width represents measured time.

  1. Prefill

    The three-token prompt produces keys and values for the relevant layers. The first output token is selected from this context.

  2. Reuse

    On the next pass, the selected token is processed with previously retained keys and values. The full history is not recomputed.

  3. Append and bound

    The new token’s KV entries join the cache. Permitted length and memory budget still apply.

References for this chapter[8][10][17]

08 / CHAPTER

Chat is a learned format, not a list of sentences

A chat template turns messages and roles into the control sequence expected by a model. Two models derived from the same base can use different templates. Manually concatenating text or duplicating special tokens can produce a readable input that differs from the training format.

Starting a new assistant turn and continuing a partially filled assistant message are different operations. Where the template supports it, a generation prompt adds the beginning of a new turn; continuation removes the final message’s termination so it can be extended. In 4.45 these options are mutually exclusive. The text-generation pipeline may treat a final assistant role as continuation: verify this behavior instead of assuming a new turn.

The decoding strategy chooses among tokens: greedy selection, sampling or beam search according to the configuration. It does not retrain weights. Define a new-token limit and stopping conditions before comparing outputs. Neither lower temperature nor a request for JSON guarantees correctness; validate required structure and facts separately.

References for this chapter[11][9][8]

09 / CHAPTER

Adapt weights without distorting evaluation

Fine-tuning continues learning on targeted data. Trainer organizes a PyTorch loop with training arguments, batches, evaluations and checkpoints; it does not guarantee improvement. The data collator builds the batches and labels required by the objective. A PEFT adapter can train a small set of added parameters while freezing base weights, subject to its own model and dependency constraints.

Split training, validation and test data before transformations that learn statistics or create variants. For customer tickets, also separate conversations or customers that might otherwise appear on both sides. A falling training loss establishes neither generalization, robustness to an underrepresented language nor freedom from memorization.

Preserve the baseline model, truncation policy, seeds, versions, learning rate and selection criterion. Measure by language and error type, rather than an average alone. Weights alone may not provide a complete training resume: optimizer, scheduler, step and random states may be needed. Evaluate the actual deployed artifact after export or quantization.

Adapt weights without distorting evaluation
CaseUseful measureFailure to investigate
Ticket classificationPrecision and recall by category; confusion matrixA rare category hidden by overall accuracy.
Structured extractionSchema validity and correctness of each fieldWell-formed output with an invented value.
Multilingual chatSeparate assessment of languages, refusals and factual supportA favorable average hiding deterioration in one language.

References for this chapter[12][13][14][18]

10 / CHAPTER

Deploy a verified bundle, not just weights

The service must retain the preprocessing and interpretation rules that were evaluated. Load components once, bound the queue, lengths and concurrency, and handle saturation errors. Cold-start loading, tokenization, compute and network transfer are different contributors to perceived latency.

Optimum can help export to ONNX for a specialized runtime, subject to architecture, operator and shape support. Successful export does not establish parity for all outputs. Transformers alone is not a high-throughput service scheduler; compare a specialized engine when concurrency and dynamic request batching become decisive.

The safetensors format reduces weight-deserialization execution risks; it certifies neither licensing, quality nor the safety of the rest of a repository. Custom code requires a separate review. Do not enable remote-code permission merely to remove an error. A historical version defines this dossier’s scope; it is not a security recommendation for a new deployment.

Deploy a verified bundle, not just weights
OptionIntended benefitCondition to check
Transformers with explicit componentsFlexibility and access to internal outputsMemory, load and latency in the actual application.
ONNX export with OptimumExecution in a targeted runtimeOperators, shapes, preprocessing and output parity.
Specialized serving engineConcurrent requests and schedulingCompatible architecture, cache, parameters and quality.

References for this chapter[14][15][16][17]

11 / CHAPTER

A selection protocol that makes results comparable

For a message classifier, establish a simple baseline, then pin the model revision, tokenizer, categories and truncation rule. Examine short, long, empty and multilingual examples. Testing an input near the limit often reveals an error that loading alone misses.

For an assistant, add the chat template, generation policy, context and output limits, and cache implementation. Measure time to first token, inter-token latency, total throughput and memory separately under documented concurrency. Distinguish cold starts from steady operation; report length distributions and failures rather than turning one tokens/s figure into a general ranking.

Choose Transformers when access to models, consistent interfaces and adaptation serve the project. Choose a more specialized integration when service or platform constraints require it, after comparing at equal quality. The exit criterion is a reproducible artifact that meets the task and budget, with observed limits; no demonstration in this dossier replaces that trial.

References for this chapter[7][10][15][13]

ORIGINAL DOCUMENT

Catalog record

2. Low-level software, compilers and training frameworks

Hugging Face huggingface.co Transformers v4.45 — Innovation: 8, Adoption: 10

8/10Innovation
10/10Adoption

Editorial source: Taxonomie des Technologies d'Intelligence Artificielle · § 5816. Addresses restored with dots; innovation and adoption scores remain those of the document.

VERIFY AND EXPLORE

References

Historical scope: the 4.45 series, with 4.45.0 release notes and archived 4.45.2 documentation consulted on November 4, 2026. Calculations and diagrams are educational. No model was downloaded, trained or run, no cloud service was used and no performance was measured for this dossier.

  1. 01
    Transformers 4.45.0 release notes

    New models, Modular Transformers and cache changes; not evidence of local performance or compatibility across the Hub.

    github.com ·
  2. 02
    Transformers 4.45.2: philosophy

    Library scope and relationship with compute frameworks.

    huggingface.co ·
  3. 03
    Transformers 4.45.2: Auto classes

    Class selection by configuration and task, without universal portability claims.

    huggingface.co ·
  4. 04
    Transformers 4.45.2: model loading

    Configuration, weights, revisions, local loading and saving.

    huggingface.co ·
  5. 05
    Transformers 4.45.2: BERT

    Bidirectional attention and BERT-specific preparation constraints.

    raw.githubusercontent.com ·
  6. 06
    Transformers 4.45.2: padding and truncation

    Strategies for batches of unequal sequences; supports the educational calculation, not a benchmark.

    raw.githubusercontent.com ·
  7. 07
    Transformers 4.45.2: inference pipelines

    Preprocessing, model and postprocessing; explicit components and batching caveats.

    huggingface.co ·
  8. 08
    Transformers 4.45.2: generation with LLMs

    Autoregressive loop, output limits and left padding for batched decoder-only generation.

    huggingface.co ·
  9. 09
    Transformers 4.45.2: generation strategies

    Token selection, generation configuration and distinction from learning weights.

    raw.githubusercontent.com ·
  10. 10
    Transformers 4.45.2: KV cache

    Operation, positions and cache variants; this dossier’s memory calculations use stated assumptions.

    huggingface.co ·
  11. 11
    Transformers 4.45.2: chat templates

    Roles, control tokens, new turns and continuation of the final message.

    raw.githubusercontent.com ·
  12. 12
    Transformers 4.45.2: fine-tuning

    Data preparation and fine-tuning with Trainer, PyTorch or TensorFlow.

    raw.githubusercontent.com ·
  13. 13
    Transformers 4.45.2: Trainer

    PyTorch loop, arguments, collator, evaluation and metrics.

    huggingface.co ·
  14. 14
    Transformers 4.45.2: ONNX export

    Role of Optimum and the need to check architecture and operator support.

    huggingface.co ·
  15. 15
    Transformers 4.45.2: pipelines and web servers

    Separation of web handling and computation, queueing and load limits.

    huggingface.co ·
  16. 16
    Transformers 4.45.2: security policy

    Remote artifacts, preference for safetensors and review before permitting custom code.

    github.com ·
  17. 17
    Transformers 4.45.2: quantization

    Different methods and hardware support; lower precision does not guarantee higher speed.

    raw.githubusercontent.com ·
  18. 18
    Transformers 4.45.2: PEFT adapters

    Frozen base weights and trainable adapters; integration and dependencies must be checked for the selected model.

    raw.githubusercontent.com ·

Catalog provenance

Taxonomie des Technologies d'Intelligence Artificielle · Google Docs

Source document consulted on . § 5816.

Websites cited in the record

A website’s inclusion in the catalog does not verify the versions, projections or results mentioned in the document.

FROM KNOWLEDGE TO PROJECT

Apply this knowledge to your context.

Scope, architecture, roadmap and notes: keep your decisions in the dedicated space.

Open dedicated space