Transformers Knowledge Patch
Use this skill when writing, migrating, reviewing, or debugging Python that uses
Hugging Face Transformers. It emphasizes API removals, changed defaults,
loading and generation contracts, cache and attention behavior, distributed
execution, multimodal processing, serving, and newly integrated model families.
How to use this skill
- Inspect the project's pinned
transformers, Python, PyTorch, quantization,
and accelerator versions before changing code.
- Start with the breaking-change checks below when moving from a 4.x project
or when old examples fail under 5.x.
- Open the topic reference that matches the code path under review.
- Prefer public APIs and explicit configuration over private helpers, inferred
defaults, or model-specific cache workarounds.
- Re-run numerical, generation, preprocessing, and distributed tests after an
upgrade; several fixes intentionally change results.
Reference index
| Reference |
Topics |
| Migration and runtime |
Runtime floors, loading defaults, configuration migrations, removed APIs, serialization, backend behavior |
| Generation, attention, and caches |
Decoding, attention backends, custom attention, KV caches, speculative decoding, continuous batching |
| Loading, quantization, and kernels |
Checkpoint conversion, quantizers, GGUF, FP8/MXFP4/NVFP4, torchao, downloadable and custom kernels |
| Tokenizers, processors, and multimodal inputs |
Tokenizer backend migration, chat templates, image/video/audio preprocessing, embedding and position-ID contracts |
| Training and distributed execution |
Trainer changes, tensor/expert/sequence parallelism, FSDP, compilation, weight tying and export |
| Serving, pipelines, and tools |
transformers serve, chat CLI, pipelines, observability, visualization and callbacks |
| Model and task integrations |
Language, vision, document, audio, multimodal, time-series, robotics and scientific architectures |
Breaking-change checklist
Use dtype, not torch_dtype
Pass dtype= to loading and pipeline APIs. Loading now defaults to auto, so
it preserves the checkpoint dtype rather than forcing float32. Specify a dtype
when exact precision is required.
model = AutoModelForCausalLM.from_pretrained(model_id, dtype="auto")
Move quantization flags into a configuration
Top-level load_in_4bit and load_in_8bit arguments are removed. Use a
quantization configuration.
from transformers import BitsAndBytesConfig
model = AutoModelForCausalLM.from_pretrained(
model_id,
quantization_config=BitsAndBytesConfig(load_in_4bit=True),
)
Replace authentication and agent APIs
- Replace
use_auth_token= with token=.
- Use
smolagents; transformers.agents is removed.
- Treat every custom generation implementation as executable code. Whether it
comes from the Hub or a local directory, opt in with
trust_remote_code=True only after reviewing it.
Update tokenizer calls and outputs
- Call the tokenizer instead of
encode_plus.
- Use
text_target= instead of as_target_tokenizer() or target-mode helpers.
- Use
word_ids() instead of BatchEncoding.words().
- Expect
apply_chat_template() to return a BatchEncoding; read
input_ids or the required field explicitly.
- Use
extra_special_tokens for unnamed additions. Newly saved tokenizers no
longer write special_tokens_map.json or added_tokens.json.
chat = tokenizer.apply_chat_template(messages, return_tensors="pt")
input_ids = chat["input_ids"]
Migrate configuration access
- Construct configuration dataclasses with keyword arguments only.
- Read rotary settings from
config.rope_parameters.
- Read multimodal values from their subconfigurations, such as
config.text_config.vocab_size.
- Use
config.backbone_config as the source of backbone selection.
- Do not assume non-generative configs contain
generation_config.
- Preserve heterogeneous
per_layer_config instead of flattening it into one
global attention configuration.
Remove legacy model and pipeline hooks
- Head masking, head pruning, and BERT-style relative positional biases are not
supported; keep such workloads on 4.x or redesign them.
- Replace Transformers
torchscript and torch.fx integrations with PyTorch
dynamo or export.
- Replace imports from removed
image_processing_utils_fast with
image_processing_utils.
- Audit removed or renamed pipeline tasks, especially question answering,
visual question answering, and image-to-image.
- Replace Apex mixed precision and fused operations with native PyTorch.
Generation and cache essentials
Let generation own cache positions
Custom prepare_inputs_for_generation implementations now receive full
input_ids; do not slice them by cache_position. Most model forward methods
also no longer accept cache_position because generate manages it.
Cache objects are first-class and per-layer. Use native dynamic,
sliding-window, hybrid, Mamba, and paged cache types instead of legacy tuples or
model-specific workarounds. Crop caches with a negative relative offset:
cache.crop(-tokens_to_remove)
Supply token IDs when penalties need them
Repetition penalties require input_ids, even when a generation path otherwise
starts from embeddings. Gemma 4 generation additionally supports
inputs_embeds and per_layer_inputs.
Select attention explicitly when reproducibility matters
Unsupported attention/output combinations fail instead of silently falling
back. T5-family models can dispatch to SDPA and registered backends; set
attn_implementation="eager" when the eager path is required. Hub kernel
references may include a revision suffix.
model.set_attn_implementation("kernels-community/flash-attn3@main")
Linear-attention and convolution-only families use native fallbacks unless
loaded with use_kernels=True.
Loading and quantization essentials
Treat checkpoint conversion as declarative
Use WeightConverter operations for reversible key mapping, tensor reshape,
merge, split, quantization, and parallelism conversion. Conversion applies
recursively to nested model structures.
Validate device and quantizer combinations
- GGUF cannot be disk-offloaded.
- Quantized tensor parallelism is method-dependent.
- Do not quantize a model that is already quantized.
- MXFP4 can dequantize on CPU when the device map includes CPU.
- Torchao requires a recent compatible release; validate serialization paths
for NVFP4 and custom parameter names.
- FP-Quant acceleration is hardware- and library-dependent; pseudoquant is an
emulation path, not accelerated quantization.
Training and distributed essentials
TrainingArguments.average_tokens_across_devices is enabled by default.
- The final partial gradient-accumulation window now receives correct loss
scaling; expect changed results for uneven batch counts.
- Review tensor-parallel conversion mappings after corrected decoder all-reduce
handling.
- Treat expert-parallel and FSDP upgrades as numerically significant because
fixes address silent wrong results, NaNs, and non-primary-rank weight damage.
- Use
ddp_static_graph only when the graph is actually static.
- Prefer the native FSDP2 migration path for new distributed work.
- Compilation defaults to
fullgraph=False; continuous batching has its own
configurable compile level.
Multimodal and preprocessing essentials
- Standardize embedding arguments on plural
inputs_embeds.
- Use full text embeddings, not pooled outputs, for SAM3-family
text_embeds.
- Preserve model-specific preprocessing: Gemma 4 has fixed patch budgets,
divisible-by-48 dimensions, and internal
[-1, 1] scaling, so do not apply
ordinary ImageNet normalization.
- Expect CUDA Lanczos requests to fall back to bicubic; CPU and accelerator
preprocessing can differ.
- Use the shared 3D position-ID interface for affected vision-language models.
- Keep heterogeneous image, video, and audio chat inputs in processor-supported
message structures rather than private helper calls.
Serving and batching essentials
transformers serve is a local experimentation and private-use server with
OpenAI-compatible model, chat, response, transcription, and completion APIs.
Its pinned model is authoritative; mismatched request model names receive HTTP
400. The models response reports owned_by as a string.
Continuous batching supports paged attention, sliding windows, CPU offload,
tensor parallelism, request ordering, per-request sampling, and request-count
limits. Validate long-context memory estimates and do not depend on the removed
continuous-batching OpenTelemetry integration.
Upgrade validation
After changing versions, exercise all applicable paths:
- load/save round trips, tied weights, sharding, GGUF and quantized checkpoints;
- tokenizer serialization, special tokens, chat templates, and target encoding;
- cached and uncached generation, long sliding-window prompts, speculative
rollback, repetition penalties, stop strings, and selected attention backend;
- CPU/CUDA image preprocessing plus batched image, video, and audio inputs;
- the final partial accumulation window and every distributed rank;
- serving schemas, model-name rejection, tool-call parsing, timeouts, and batch
request ordering;
- numerical regression fixtures for model-specific attention, RoPE, cache,
resizing, and interpolation corrections.
1---2name: transformers-knowledge-patch-23description: Transformers4license: MIT5---678# Transformers Knowledge Patch910Use this skill when writing, migrating, reviewing, or debugging Python that uses11Hugging Face Transformers. It emphasizes API removals, changed defaults,12loading and generation contracts, cache and attention behavior, distributed13execution, multimodal processing, serving, and newly integrated model families.1415## How to use this skill16171. Inspect the project's pinned `transformers`, Python, PyTorch, quantization,18 and accelerator versions before changing code.192. Start with the breaking-change checks below when moving from a 4.x project20 or when old examples fail under 5.x.213. Open the topic reference that matches the code path under review.224. Prefer public APIs and explicit configuration over private helpers, inferred23 defaults, or model-specific cache workarounds.245. Re-run numerical, generation, preprocessing, and distributed tests after an25 upgrade; several fixes intentionally change results.2627## Reference index2829| Reference | Topics |30| --- | --- |31| [Migration and runtime](references/migration-and-runtime.md) | Runtime floors, loading defaults, configuration migrations, removed APIs, serialization, backend behavior |32| [Generation, attention, and caches](references/generation-attention-and-caches.md) | Decoding, attention backends, custom attention, KV caches, speculative decoding, continuous batching |33| [Loading, quantization, and kernels](references/loading-quantization-and-kernels.md) | Checkpoint conversion, quantizers, GGUF, FP8/MXFP4/NVFP4, torchao, downloadable and custom kernels |34| [Tokenizers, processors, and multimodal inputs](references/tokenizers-processors-and-multimodal.md) | Tokenizer backend migration, chat templates, image/video/audio preprocessing, embedding and position-ID contracts |35| [Training and distributed execution](references/training-and-distributed.md) | Trainer changes, tensor/expert/sequence parallelism, FSDP, compilation, weight tying and export |36| [Serving, pipelines, and tools](references/serving-pipelines-and-tools.md) | `transformers serve`, chat CLI, pipelines, observability, visualization and callbacks |37| [Model and task integrations](references/model-and-task-integrations.md) | Language, vision, document, audio, multimodal, time-series, robotics and scientific architectures |3839## Breaking-change checklist4041### Use `dtype`, not `torch_dtype`4243Pass `dtype=` to loading and pipeline APIs. Loading now defaults to `auto`, so44it preserves the checkpoint dtype rather than forcing float32. Specify a dtype45when exact precision is required.4647```python48model = AutoModelForCausalLM.from_pretrained(model_id, dtype="auto")49```5051### Move quantization flags into a configuration5253Top-level `load_in_4bit` and `load_in_8bit` arguments are removed. Use a54quantization configuration.5556```python57from transformers import BitsAndBytesConfig5859model = AutoModelForCausalLM.from_pretrained(60 model_id,61 quantization_config=BitsAndBytesConfig(load_in_4bit=True),62)63```6465### Replace authentication and agent APIs6667- Replace `use_auth_token=` with `token=`.68- Use `smolagents`; `transformers.agents` is removed.69- Treat every custom generation implementation as executable code. Whether it70 comes from the Hub or a local directory, opt in with71 `trust_remote_code=True` only after reviewing it.7273### Update tokenizer calls and outputs7475- Call the tokenizer instead of `encode_plus`.76- Use `text_target=` instead of `as_target_tokenizer()` or target-mode helpers.77- Use `word_ids()` instead of `BatchEncoding.words()`.78- Expect `apply_chat_template()` to return a `BatchEncoding`; read79 `input_ids` or the required field explicitly.80- Use `extra_special_tokens` for unnamed additions. Newly saved tokenizers no81 longer write `special_tokens_map.json` or `added_tokens.json`.8283```python84chat = tokenizer.apply_chat_template(messages, return_tensors="pt")85input_ids = chat["input_ids"]86```8788### Migrate configuration access8990- Construct configuration dataclasses with keyword arguments only.91- Read rotary settings from `config.rope_parameters`.92- Read multimodal values from their subconfigurations, such as93 `config.text_config.vocab_size`.94- Use `config.backbone_config` as the source of backbone selection.95- Do not assume non-generative configs contain `generation_config`.96- Preserve heterogeneous `per_layer_config` instead of flattening it into one97 global attention configuration.9899### Remove legacy model and pipeline hooks100101- Head masking, head pruning, and BERT-style relative positional biases are not102 supported; keep such workloads on 4.x or redesign them.103- Replace Transformers `torchscript` and `torch.fx` integrations with PyTorch104 `dynamo` or `export`.105- Replace imports from removed `image_processing_utils_fast` with106 `image_processing_utils`.107- Audit removed or renamed pipeline tasks, especially question answering,108 visual question answering, and image-to-image.109- Replace Apex mixed precision and fused operations with native PyTorch.110111## Generation and cache essentials112113### Let generation own cache positions114115Custom `prepare_inputs_for_generation` implementations now receive full116`input_ids`; do not slice them by `cache_position`. Most model `forward` methods117also no longer accept `cache_position` because `generate` manages it.118119Cache objects are first-class and per-layer. Use native dynamic,120sliding-window, hybrid, Mamba, and paged cache types instead of legacy tuples or121model-specific workarounds. Crop caches with a negative relative offset:122123```python124cache.crop(-tokens_to_remove)125```126127### Supply token IDs when penalties need them128129Repetition penalties require `input_ids`, even when a generation path otherwise130starts from embeddings. Gemma 4 generation additionally supports131`inputs_embeds` and `per_layer_inputs`.132133### Select attention explicitly when reproducibility matters134135Unsupported attention/output combinations fail instead of silently falling136back. T5-family models can dispatch to SDPA and registered backends; set137`attn_implementation="eager"` when the eager path is required. Hub kernel138references may include a revision suffix.139140```python141model.set_attn_implementation("kernels-community/flash-attn3@main")142```143144Linear-attention and convolution-only families use native fallbacks unless145loaded with `use_kernels=True`.146147## Loading and quantization essentials148149### Treat checkpoint conversion as declarative150151Use `WeightConverter` operations for reversible key mapping, tensor reshape,152merge, split, quantization, and parallelism conversion. Conversion applies153recursively to nested model structures.154155### Validate device and quantizer combinations156157- GGUF cannot be disk-offloaded.158- Quantized tensor parallelism is method-dependent.159- Do not quantize a model that is already quantized.160- MXFP4 can dequantize on CPU when the device map includes CPU.161- Torchao requires a recent compatible release; validate serialization paths162 for NVFP4 and custom parameter names.163- FP-Quant acceleration is hardware- and library-dependent; pseudoquant is an164 emulation path, not accelerated quantization.165166## Training and distributed essentials167168- `TrainingArguments.average_tokens_across_devices` is enabled by default.169- The final partial gradient-accumulation window now receives correct loss170 scaling; expect changed results for uneven batch counts.171- Review tensor-parallel conversion mappings after corrected decoder all-reduce172 handling.173- Treat expert-parallel and FSDP upgrades as numerically significant because174 fixes address silent wrong results, NaNs, and non-primary-rank weight damage.175- Use `ddp_static_graph` only when the graph is actually static.176- Prefer the native FSDP2 migration path for new distributed work.177- Compilation defaults to `fullgraph=False`; continuous batching has its own178 configurable compile level.179180## Multimodal and preprocessing essentials181182- Standardize embedding arguments on plural `inputs_embeds`.183- Use full text embeddings, not pooled outputs, for SAM3-family `text_embeds`.184- Preserve model-specific preprocessing: Gemma 4 has fixed patch budgets,185 divisible-by-48 dimensions, and internal `[-1, 1]` scaling, so do not apply186 ordinary ImageNet normalization.187- Expect CUDA Lanczos requests to fall back to bicubic; CPU and accelerator188 preprocessing can differ.189- Use the shared 3D position-ID interface for affected vision-language models.190- Keep heterogeneous image, video, and audio chat inputs in processor-supported191 message structures rather than private helper calls.192193## Serving and batching essentials194195`transformers serve` is a local experimentation and private-use server with196OpenAI-compatible model, chat, response, transcription, and completion APIs.197Its pinned model is authoritative; mismatched request model names receive HTTP198400. The models response reports `owned_by` as a string.199200Continuous batching supports paged attention, sliding windows, CPU offload,201tensor parallelism, request ordering, per-request sampling, and request-count202limits. Validate long-context memory estimates and do not depend on the removed203continuous-batching OpenTelemetry integration.204205## Upgrade validation206207After changing versions, exercise all applicable paths:208209- load/save round trips, tied weights, sharding, GGUF and quantized checkpoints;210- tokenizer serialization, special tokens, chat templates, and target encoding;211- cached and uncached generation, long sliding-window prompts, speculative212 rollback, repetition penalties, stop strings, and selected attention backend;213- CPU/CUDA image preprocessing plus batched image, video, and audio inputs;214- the final partial accumulation window and every distributed rank;215- serving schemas, model-name rejection, tool-call parsing, timeouts, and batch216 request ordering;217- numerical regression fixtures for model-specific attention, RoPE, cache,218 resizing, and interpolation corrections.