Installs into .claude/skills of the current project.
Sponsors
SSkills DirectorySkills Directory
Know which skills are safe — weekly.
SSkills DirectorySkills Directory
Is that skill safe to install?
Are you the author of Transformers Knowledge Patch?
Add the live security badge to your README. It updates with every re-scan.
[](https://www.skillsdirectory.com/skills/nevaberry-transformers-knowledge-patch)
---
name: transformers-knowledge-patch
description: Transformers
version: "5.24.1"
license: MIT
metadata:
author: Nevaberry
---
# Transformers compatibility guidance
Load this skill when migrating Transformers code or working with model loading,
generation, caches, attention, tokenizers, multimodal processors, serving,
exporters, or distributed training. Use the topic references for detailed
model-specific conditions, examples, and version-dependent behavior.
## Reference index
| Reference | Topics |
| --- | --- |
| [Generation, attention, and caches](references/generation-attention-and-caches.md) | Cache APIs, masks, attention backends, rotary settings, custom and speculative decoding |
| [Loading, quantization, and kernels](references/loading-quantization-and-kernels.md) | Precision, quantizers, GGUF, device placement, weight conversion, kernel configuration |
| [Migration and runtime](references/migration-and-runtime.md) | Dependencies, configuration, model outputs, custom code, compilation, export |
| [Model and task integrations](references/model-and-task-integrations.md) | Text, vision-language, audio, OCR, retrieval, segmentation, forecasting, proteins, robotics |
| [Serving, pipelines, and tools](references/serving-pipelines-and-tools.md) | Continuous batching, server endpoints, CLI, pipeline behavior, tool schemas, response parsing |
| [Tokenizers, processors, and multimodal inputs](references/tokenizers-processors-and-multimodal.md) | Tokenizer migration, chat templates, processor loading, image/video/audio preprocessing |
| [Training and distributed execution](references/training-and-distributed.md) | Tensor/expert/pipeline parallelism, FSDP, losses, optimizers, callbacks, checkpointing |
## Cache migration
In 5.24.0, use `cache` in model calls, `generate()`,
`prepare_inputs_for_generation()`, masking utilities, and model outputs.
Upgrade to `peft>=0.22.0` for PEFT integration.
```python
outputs = model(input_ids, cache=cache, use_cache=True)
cache = outputs.cache
```
The legacy names `past_key_values` and `cache_params` warn and remain accepted
until 5.40.0 in `forward()` and `prepare_inputs_for_generation()`, and until
6.0.0 in `generate()`. Combining a legacy name with `cache` raises `ValueError`.
Legacy output field names still work for reads and construction; 5.24.1 improves
compatibility with remote code using old cache names.
Custom `Cache.update()` overrides must accept the keyword argument in
`cache.update(key_states, value_states, layer_idx, kwargs=kwargs)`.
Use `get_max_length()` to query cache capacity. Deprecated methods were removed
from `cache_utils.py` in 5.20.0.
`cache.crop()` takes a strictly negative offset. To migrate a target length:
```python
offset = target_length - cache.get_seq_length()
if offset < 0:
cache.crop(offset)
```
A static cache created by `generate()` belongs to that call. Manage an explicit
cache when later calls need to reuse it. Construct `StaticCache` with keyword
arguments because its positional argument order changed.
## Model, mask, and configuration contracts
Drop `cache_position` from direct `forward()` and `generate()` calls to affected
built-in models. Generation retains compatibility for remote-code models that
still expect it. `generate()` passes full `input_ids` to input preparation.
Migrate mask-helper imports to `transformers.masking_utils`.
`modeling_attn_mask_utils.py` was removed in 5.24.0 and restored in 5.24.1 for
remote-code compatibility. When passing a prebuilt eager-attention mask, make it
broadcastable to attention scores at the actual query and key lengths.
Generative multimodal `forward()` outputs use `MultimodalBaseModelOutputWithPast`,
`MultimodalCausalLMOutputWithPast`, or their MoE variants in 5.24.0.
Update type checks; `ModelOutput` dropped `rope_deltas` in 5.23.0.
Import affected shared modeling components from the modules that define them.
Use keyword arguments for `PreTrainedConfig` and model-specific config
constructors. Composite configs use the regular constructor; their
`from_xxx_config()` helpers were removed. Load configs from a local path or Hub
repository, since direct config-file URLs are unsupported.
For affected composite configs, declare nested defaults in dataclass fields for
`SubConfigSpec`. Read nested text settings from `config.text_config` and rotary
settings from `config.rope_parameters`. A config's `num_labels` can be `None`
when `id2label` is unset.
## Loading and quantization migration
Use `dtype` in place of `torch_dtype`; existing `torch_dtype` calls continue
during the transition. `from_pretrained()` defaults to `dtype="auto"`, using
the checkpoint's saved precision. Set `dtype` explicitly for fixed precision.
Pass `load_in_4bit` or `load_in_8bit` through `quantization_config`, rather than
directly to `from_pretrained()`. For example:
```python
from_pretrained(checkpoint, quantization_config=BitsAndBytesConfig(load_in_4bit=True))
```
Quantizing an already quantized model raises an error. The torchao integration
requires torchao 0.15.0 or later and no longer supports `torchao.autoquant`.
See the loading reference for format-specific FP8, MXFP4, NVFP4, and GGUF rules.
## Tokenizer and processor migration
`AutoTokenizer.from_pretrained()` chooses among `TokenizersBackend`,
`SentencePieceBackend`, `PythonBackend`, and `MistralCommonBackend` based on files
and dependencies. Custom Python tokenizers can subclass `PythonBackend`.
For legacy configs that relied on directory-name inference, set `model_type`
in `config.json`.
Use `tokenizer(...)` instead of deprecated `encode_plus()`. Migrate
`batch_decode()` to `decode()`; decode generated sequences individually when
held in a nested Python list. Tokenized `tokenizer.apply_chat_template()` returns
a `BatchEncoding` by default: read `inputs["input_ids"]` or unpack it into
`generate()` to include the attention mask.
Replace target-mode helpers with `tokenizer(text_target=targets)`.
Tokenizer calls no longer accept `pad_to_max_length`. The tokenizer reference
details removed methods, special-token access, and serialization changes.
Migrate `transformers.image_processing_utils_fast` imports to
`transformers.image_processing_utils`; full-path imports of model-specific fast
processors remain supported. Processing defaults move to processor class
attributes in 5.23.0. Supply one metadata entry per video; the affected video
processing path rejects `return_metadata=False`.
## Attention, kernels, and removed integrations
Installing `kernels` does not activate supported kernels automatically. Load
compatible models with `use_kernels=True`. `use_mamba_kernels` is deprecated
and has no effect in 5.18.0. Kernel integration requires `kernels>=0.17.2` in
5.20.0; `use_fallback=KernelizeFallback.ALL` uses the original implementation
when a kernel fails to load.
An incompatible attention backend raises on `output_attentions=True`.
Select `attn_implementation="eager"` when the backend cannot return weights;
automatic fallback to eager attention was removed. On supported models,
`set_attn_implementation()` switches the backend after loading.
DoLa and contrastive search load through `custom_generate`, using
`transformers-community/dola` or `transformers-community/contrastive-search`.
Built-in group beam search and constrained beam search were removed.
For repository-hosted generation, set `trust_remote_code=True` to authorize
running the repository's code. Custom implementations no longer receive
`custom_generate` or `trust_remote_code`.
`transformers.agents` was removed; migrate agent code to `smolagents`.
TensorFlow and JAX backends are deprecated. IPEX, CCL, and Apex integrations
were removed. Migrate Apex mixed precision and fused operations to native
PyTorch equivalents. TorchScript and `torch.fx` support were dropped in favor
of Dynamo and `torch.export`.
## Distributed training and loss behavior
Tensor-parallel inference and training use DTensor; the legacy `tp_plan`
argument to `from_pretrained()` enters deprecation. In 5.23.0, migrate
`ep_router` plans to `ep_dispatch_experts`. `ep_implementation` offers all-reduce
for inference and all-to-all for training, with `deepgemm_megamoe` for compatible
experts. In 5.24.1, `tp_plan={}` supports expert parallelism on its own.
Use `dp_replicate_size` on `DistributedConfig` for the replication dimension of
hybrid sharded data parallelism, which can combine with expert parallelism.
Combined FSDP and tensor-parallel model and optimizer checkpoints can move
between parallel configurations. Distributed checkpointing requires PyTorch 2.8
or newer; 5.20.1 restores model loading on PyTorch 2.6 and 2.7.
`TrainingArguments.average_tokens_across_devices` defaults to `True`; set it to
`False` for per-device normalization. Trainer scales partial accumulation
windows by their actual size. Use `Trainer.loss_is_scaled_for_ga` to declare
whether custom `compute_loss()` already scales loss for gradient accumulation.
## Continuous batching and serving
In 5.19.0, continuous batching uses `sdpa` or `flash_attention_2` directly.
Their `paged|` aliases are deprecated; eager attention still uses `paged|eager`.
```python
from transformers import AutoModelForCausalLM
model = AutoModelForCausalLM.from_pretrained(checkpoint, attn_implementation="sdpa")
outputs = model.generate_batch(inputs=token_id_batches)
```
Pass one token-ID list per request. Results map request IDs to objects with
`generated_tokens`. Continuous batching supports per-request sampling, CPU
offloading, tensor parallelism, and mixed attention-type caches. It can run
inside `torch.inference_mode()` in 5.24.0. Configuring it on `GenerationConfig`
is deprecated, and its OpenTelemetry integration was removed.
`transformers serve` supports text and vision-language inference, with audio and
video inputs for compatible checkpoints. Its routes include `/v1/chat/completions`,
`/v1/responses`, `/v1/audio/transcriptions`, `/v1/models`, and legacy
`POST /v1/completions`, whose prompt belongs in `prompt`.
Requests naming a different model from a pinned server receive HTTP 400.
Use `--compile` and `--model-timeout` for the corresponding serving options.
## Pipelines, tools, and assisted generation
`model.generation_config` takes precedence over pipeline defaults.
`pipeline()` forwards `code_revision` to every loader it invokes.
The any-to-any pipeline accepts media-only inputs; multimodal pipelines accept
string assistant prefills and return input messages in `input_text` for chat
tensor returns. Image, video, and audio classification honor `problem_type`.
Serving supports `response_template`; the old `response_schema` is deprecated.
Tool arguments are typed according to the called tool's JSON Schema.
`get_json_schema()` supports methods, container annotations, and `Enum`, and
raises on unsupported custom classes. The experimental
`pipeline("decision", model=checkpoint)` or model `decide()` scores single-token
labels at the final prompt token.
Assisted generation supports different target and assistant tokenizers for
sampling and greedy decoding. In 5.24.0, assistant models can use
`cache_implementation="static"`, and generation can pair static caches with
flex attention. Consult the generation reference for model-specific restrictions,
shared-cache assistants, MTP, and sliding-window rollback.
## Export and task-specific guidance
In 5.23.0, `export()` returns an `ExportedModel` preserving the original model's
call keywords and output class; its ONNX program is an `onnx_ir.Model`.
Use `save_pretrained()` instead of old ONNX/OpenVINO `output_path` settings,
`push_to_hub()` to publish, and `register_backend()` for a custom backend.
`export_for_generation()` captures separate `prefill` and `decode` programs for
causal language models and additional components for multimodal models.
Loading pickled `.pt2` exports requires `trust_remote_code=True` because
unpickling can execute code. ONNX, OpenVINO, and ExecuTorch exports load without
that flag. See the runtime reference for export quantization and runtime fusions.
Use the model/task reference for checkpoint-specific input limits, output modes,
OCR prompts, retrieval scoring, audio rates, and architecture availability.
The processor reference preserves image budgets, audio sampling controls,
video frame handling, and supported multimodal message forms.