Skip to content

Upgrading transformers 4 to 5

Breaking4.57.6 β†’ 5.22.1Breaking127Security18Platform1Deprecated16New346Changed263Fixed1918Other825

Fetching 46 releases from GitHub…42 / 46
BreakingUpgrade verdict

125 breaking changes and a platform requirement change and 18 security fixes.

  • Old caching helpers were deleted, so code using them must switch to the current cache API.
  • Old caching helpers were deleted from the library.
  • Some model modules used to re-export names from other models by accident. Those shortcuts are gone, so import those names from their original modules.
  • Removes the examples directory.
Top 5 of 159 that need code or config changes

transformers publishes official migration guides for versions 5, 5. They cover more than the release notes do.

Migration guide β†—Migration guide β†—

Python requirement changed in 5.21.0: >=3.9.0 β†’ >=3.11.0.

Adds typer.

Drops filelock, requests.

Installs 26 packages in all (was 17).

Also installs annotated-doc, anyio, click, h11, httpcore2, httpx2, markdown-it-py, mdurl, pygments, rich, shellingham, truststore.

No longer installs certifi, charset-normalizer, urllib3.

Moves huggingface-hub 0.36.2 β†’ 2.4.0, tokenizers 0.22.2 β†’ 0.23.3. Your build may pick other versions.

Breaking125
Removes deprecated checks and methods from cache_utils.py, affecting models such as minimax_m3_vl and pi0.
cache_utils.py
Removes deprecated cache utils methods.
Removes accidental cross-model imports from several model files; the modular converter no longer adds them.
embedding_gemma2ijepalightglue
Removes the examples directory.
Removes deprecated data helpers.
Continuous batching internals changed in preparation for removing "paged".
Removes the deprecation cycle on mask and cache.
Removes the rotaries deprecation cycle.
Removes the image_patch_indices output from FuyuProcessor, so code depending on that field must be updated.
FuyuProcessorimage_patch_indices
Enables SDPA and other attention backends for T5 and the T5 family, which may change the default attention implementation.
T5MT5LongT5ALL_ATTENTION_FUNCTIONSattn_implementation
Removes small private helper functions such as _is_url and _build_image_tokens from multimodal processor files.
_is_url_build_image_tokens
Deletes old deprecations.
Removes deprecated training args and the is_fast property.
is_fast
Removes the deprecated package_name argument from the kernels call in LocalLayerRepository.
LocalLayerRepositorypackage_name
Syncs the Kernels integration to the latest version, which no longer accepts model-type repositories.
Kernels
Removes most Apex integration, including RMSNorm usage in T5 and related models.
RMSNorm
rotating_light: [LightGlue] Remove remote code execution.
LightGlue
[core] 🚨 Completely remove cache positions.
rotating_light: Modify ModernBERT's default attention implementation to stop using FA.
Prevent AutoTokenizer type mismatch from directory name substrin… If the config does not have a model-type field, we no longer check the name of the folder like for…
Delete duplicate code in backbone utils - This PR cleans up backbone utilities.
Remove deprecated AnnotionFormat - removes a missnamed class in favour of AnnotationFormat.
AnnotationFormat
create_token_type_ids_from_sequences(): Removed from base class.
create_token_type_ids_from_sequences()
_switch_to_input_mode(), _switch_to_target_mode(), as_target_tokenizer(): Removed from base class.
_switch_to_input_mode()_switch_to_target_mode()as_target_tokenizer()__call__()text_target
parse_response(): Removed from base class.
parse_response()
It is no longer possible to load a config class from a URL file.
Configurations of non-generative models (any model that doesn't call model.generate()) will no longer have a generation_config and model.config.generation_config will throw an attribute error.
model.generate()generation_configmodel.config.generation_config
Slow tokenizer files (aka: tokenization_.py ) will be removed in favor of using fast tokenizer files tokenization__fast.py --> will be renamed to tokenization_.py.
tokenization_<model>.pytokenization_<model>_fast.pytokenizers
Remove legacy files like special_tokens_map.json and added_tokens.json.
Remove _eventually_correct_t5_max_length.
XXXFeatureExtractors classes are completely removed in favor of XXXImageProcessor class for all vision models (.
XXXFeatureExtractorsXXXImageProcessor
Minor change: XXXFastImageProcessorKwargs is removed in favor of XXXImageProcessorKwargs which will be shared between fast and slow processors (.
XXXFastImageProcessorKwargsXXXImageProcessorKwargs
Old, deprecated output type aliases were removed (e.g.
GreedySearchEncoderDecoderOutput
Removed deprecated classes regarding decoding methods that were moved to the Hub due to low usage (constraints and beam scores) (.
Generation parameters are no longer accessible via model's config.
config.json
report_to now defaults to "none".
report_to"none"
overwrite_output_dir - > replaced by resume_from_checkpoint, and it was only used in the examples script, no impact on Trainer.
overwrite_output_dirresume_from_checkpoint
tpu_num_cores-> It is actually better to remove it, as it is not recommended to set the number of cores.
tpu_num_coresTPU_NUM_CORES
use_mps_device -> mps will be used by default if detected.
use_mps_device
sigpot integration for hp search was removed as the library was archived + the api stopped working.
Drop support for sagemaker API <1.10.
Image text to text pipelines will no longer accept images as a separate argument along with conversation chats.
Removed deprecated organization and repo_url from PushToHubMixin.
organizationrepo_urlPushToHubMixinrepo_id
Removed ignore_metadata_errors from PushToMixin.
ignore_metadata_errorsPushToMixin
Removed use_temp_dir argument from push_to_hub.
use_temp_dirpush_to_hub
Legacy environment variables like TRANSFORMERS_CACHE, PYTORCH_TRANSFORMERS_CACHE, and PYTORCH_PRETRAINED_BERT_CACHE have been removed.
TRANSFORMERS_CACHEPYTORCH_TRANSFORMERS_CACHEPYTORCH_PRETRAINED_BERT_CACHEHF_HOME
Constants HUGGINGFACE_CO_EXAMPLES_TELEMETRY, HUGGINGFACE_CO_EXAMPLES_TELEMETRY, HUGGINGFACE_CO_PREFIX, and HUGGINGFACE_CO_RESOLVE_ENDPOINT have been removed.
HUGGINGFACE_CO_EXAMPLES_TELEMETRYHUGGINGFACE_CO_PREFIXHUGGINGFACE_CO_RESOLVE_ENDPOINThuggingface_hub.constants.ENDPOINT
Some new models added stuff that was already removed.
Remove deprecated objects.
Remove unused imports.
Remove more deprecated objects/args.
Remove deprecated and unused position_ids in all apply_rotary_pos_emb.
position_idsapply_rotary_pos_emb
Fix ConvNeXt image processor default interpolation to BICUBIC.
clean_up_tokenization(): Removed from base class.
clean_up_tokenization()
Adds SubConfigSpec to centralize sub-config initialization from dataclass fields instead of class instantiation.
SubConfigSpec
LUKE and mLUKE tokenizers now treat entity special tokens like <ent> as special tokens, changing tokenization and decoding output.
<ent>skip_special_tokens
All MoE models whose routers compute logits now return them when output_router_logits=True, following the Qwen3-MoE pattern.
output_router_logitsrouter_logitsMoeModelOutputWithPast
Owlv2ForObjectDetection.embed_image_query now selects the query box with the highest objectness score instead of the OWL-ViT heuristic.
Owlv2ForObjectDetection.embed_image_query
In continuous batching, the cache update for the index-based and block-table paths is fused into a single call, changing the cache update function's behavior.
Speeds up DETR image processing, changing its behaviour.
DetrImageProcessor
Remaps indexers layer_type.
layer_type
Fixes video token counting for Transformers backend video inputs in vLLM (Part 1).
Brings several DINO models to modern standards.
Bumps the Kernels version.
Kernels
Replaces the legacy tensor-parallel implementation with a DTensor-native backend, requiring migration of the previous TP API.
Adds proper attn_implementation="sdpa" dispatch for wav2vec2_conformer, wav2vec2-bert, and SeamlessM4T/v2, which may change initialization behavior.
attn_implementationwav2vec2_conformerwav2vec2-bertSeamlessM4T
Makes kernels opt-in rather than mandatory for linear attention models such as Mamba, GDN and Conv-only, requiring explicit enabling to keep prior behavior.
MambaGDN
Changes the cache cropping API to accept only negative relative offsets instead of absolute sizes.
GPTNeoX remaps embed_out to lm_head and GPTBigCode enables _supports_attention_backend for vLLM compatibility.
GPTNeoXGPTBigCodeembed_outlm_head_supports_attention_backend
Fixes Gemma 3/4 image-token attention masking to respect sliding window boundaries, changing model behavior and reproducibility.
Corrects the Expert Parallelism router contract across many models and fixes FP8 scale format handling.
Reworks old cache getters and properties, consolidating redundant getters into get_max_length.
get_max_length
Requires trust_remote_code to run a local-directory custom_generate.
trust_remote_codecustom_generate
Gemma4 vision pooler now casts inputs to float32 before scaling, which may slightly change float16 outputs.
Audio Language Models now have a dedicated base model class without a language modeling head.
The text_embeds input for SAM3, EdgeTAM, and SAM3-Lite-Text now expects full text embeddings instead of pooler outputs.
text_embedsSAM3EdgeTAMSAM3-Lite-Text
Skips clean_up_tokenization for BPE tokenizers in PreTrainedTokenizerFast.
PreTrainedTokenizerFastclean_up_tokenization
[Cache] Native mamba & hybrid cache.
Refactor Image Processors to support different backends.
rotating_light: Validate config attributes.
rotating_light: [FA4] Initial support.
FA4
[tie weights] 🚨 If both weights are present with same weights, still tie them.
rotating_light: [Ernie 4.5 VL Moe] Fix up namings to vllm/sglang convention.
More V5 pipeline cleanup.
rotating_light: Unify 3D position ids.
rotating_light: [Attn] New attn mask interface everywhere.
Attn
T5Gemma2 model structure - Makes sure that the attn implementation is set to all sub-configs.
Generation cache preparation - Refactors cache initialization in generation to ensure sliding window configurations are now properly respected.
Refactor DETR to updated standards - standardizes the DETR model to be closer to other vision models in the library.
Fix floating-point precision in JanusImageProcessor resize - replaces an int() with round(), expect light numerical differences.
int()round()
Backwards Incompatible Changes.
special_tokens_map.json - special tokens are now stored in tokenizer_config.json.
special_tokens_map.jsontokenizer_config.json
added_tokens.json - added tokens are now stored in tokenizer.json.
added_tokens.jsontokenizer.json
added_tokens_decoder is only stored when there is no tokenizer.json.
added_tokens_decodertokenizer.json
prepare_for_model(), build_inputs_with_special_tokens(), truncate_sequences(): Moved from tokenization_utils_base.py to tokenization_python.py for PythonBackend tokenizers.
prepare_for_model()build_inputs_with_special_tokens()truncate_sequences()tokenization_utils_base.pytokenization_python.pyPythonBackend
mp_parameters -> legacy param that was later on added to the Sagemaker trainer.
mp_parameters
_n_gpu -> not intended for users to set, we will initialize it correctly instead of putting it in the TrainingArguments.
_n_gpuTrainingArguments
logging_dir -> only used for tensorboard, set TENSORBOARD_LOGGING_DIR env var instead.
logging_dirTENSORBOARD_LOGGING_DIR
jit_mode_eval -> use use_torch_compile instead, as torchscript is not recommended anymore.
jit_mode_evaluse_torch_compile
past_index -> it was only used for a very small number of models that have special architecture like transformersxl + it was not documented at all how to train those models.
past_index
ray_scope -> only for a minor arg for ray integration.
ray_scopeRAY_SCOPE
warmup_ratio -> use warmup_step instead.
warmup_ratiowarmup_step
fsdp_min_num_params and fsdp_transformer_layer_cls_to_wrap -> use fsdp_config.
fsdp_min_num_paramsfsdp_transformer_layer_cls_to_wrapfsdp_config
tpu_metrics_debug -> debug.
tpu_metrics_debugdebug
push_to_hub_token -> hub_token.
push_to_hub_tokenhub_token
push_to_hub_model_id and push_to_hub_organization -> hub_model_id.
push_to_hub_model_idpush_to_hub_organizationhub_model_id
include_inputs_for_metrics -> include_for_metrics.
include_inputs_for_metricsinclude_for_metrics
per_gpu_train_batch_size -> per_device_train_batch_size.
per_gpu_train_batch_sizeper_device_train_batch_size
per_gpu_eval_batch_size -> per_device_eval_batch_size.
per_gpu_eval_batch_sizeper_device_eval_batch_size
fp16_backend and half_precision_backend -> we will only rely on torch.amp as everything has been upstreamed to torch.
fp16_backendhalf_precision_backendtorch.amp
no_cuda -> use_cpu.
no_cudause_cpu
include_tokens_per_second -> include_num_input_tokens_seen.
include_tokens_per_secondinclude_num_input_tokens_seen
use_legacy_prediction_loop -> we only use evaluation_loop function from now on.
use_legacy_prediction_loopevaluation_loop
tokenizer in initialization -> processing_class.
tokenizerprocessing_class
model_path in train -> resume_from_checkpoint.
model_pathresume_from_checkpoint
bump accelerate minimum version to 1.1.0.
bump peft minimum version to 0.18.0.
bump bitsandbytes minimum version to 0.46.1.
Add fast version of convert_segmentation_map_to_binary_masks to EoMT.
convert_segmentation_map_to_binary_masks
tpu_metrics_debug -> debug.
tpu_metrics_debugdebug
no_cuda -> use_cpu.
no_cudause_cpu
Routes gpt-oss FA3 to aiter-flash-attn on ROCm and generates ROCm fixtures.
gpt-oss
Standardizes layer declarations, mask/cache construction and hybrid-attention handling, which may require updates for users of internal modeling APIs.
Stops registering the internal rotary_fn as a hidden kernel function, breaking code that calls self.rotary_fn(...) in Attention modules.
rotary_fn
Fix + tests dense & MoE TP all reduce (decoder only).
Security18
Adds sanitization of chat inputs.
Fixes kernel commit and repo paths for ESMFold2, pinning a hf kernel for security reasons.
ESMFold2
Adds a potential fix for code scanning alert no. 267 regarding artifact poisoning.
Fixes a potential ReDoS by escaping the tokenizer filename used as a regex pattern.
from_pretrained
Updates the doc preprocessing regex to prevent ReDoS.
Rejects path traversal in the transformers_weights config field.
transformers_weights
Fixes path traversal via vocab-file arguments in tokenizer_config.json.
tokenizer_config.json
Fixes path traversal when saving Bark voice preset embeddings.
Fixes path traversal when saving named chat templates.
Transformers save_pretrained path traversal allows arbitrary file writes through chat template names
High
Sets persist-credentials: false on actions/checkout and closes remaining template injection findings.
actions/checkout
Sets default workflow permissions to contents: read.
Removes template injection on pull_request_target workflows.
pull_request_target
Pins all GitHub Actions and reusable workflows by SHA.
Prevents untrusted users from triggering TRL CI dispatch.
TRL
Fix kernels security issue.
A critical remote code execution vulnerability exists in all versions of the HuggingFace transformers library prior to version 5.3.0. The vulnerability allows an attacker to craft a malicious config.json file containing the _attn_implementation_internal field set to an attacker-controlled HuggingFace Hub repository ID. When a victim loads this model using the standard AutoModelForCausalLM.from_pretrained() API, the library downloads and executes arbitrary Python code from the attacker's repository with the victim's full OS privileges. This issue arises due to unfiltered deserialization of configuration attributes, insufficient sanitization of internal fields, and unsandboxed execution of downloaded kernels. The vulnerability bypasses the trust_remote_code security mechanism, is invisible to the victim, and exploits the standard documented usage pattern, making it particularly severe. Users are advised to upgrade to version 5.3.0 or later to mitigate this issue.
High
A vulnerability in the HuggingFace Transformers library, specifically in the Trainer class, allows for arbitrary code execution. The _load_rng_state() method in src/transformers/trainer.py at line 3059 calls torch.load() without the weights_only=True parameter. This issue affects all versions of the library supporting torch>=2.2 when used with PyTorch versions below 2.6, as the safe_globals() context manager provides no protection in these versions. An attacker can exploit this vulnerability by supplying a malicious checkpoint file, such as rng_state.pth, which can execute arbitrary code when loaded. The issue is resolved in version v5.0.0rc3.
High
Platform1
Remove Python 3.9 classifier.
Deprecated15
Deprecates the unused get_uniform_frame_indices.
get_uniform_frame_indices
Deprecates the "paged|" prefix for SDPA and flash attention implementations.
paged|sdpapaged|flash_attention_2sdpaflash_attention_2
Deprecates min-max pixels.
Deprecates the use_mamba_kernels config flag that no longer has any effect.
use_mamba_kernels
Deprecates the old response_schema.
response_schema
Deprecates CB config in generation configuration.
Deprecates CB config in gen configuration.
SpecialTokensMixin: Merged into PreTrainedTokenizerBase to simplify the tokenizer architecture.
SpecialTokensMixinPreTrainedTokenizerBase
special_tokens_map: Now only stores named special token attributes (e.g., bos_token, eos_token).
special_tokens_mapbos_tokeneos_tokenextra_special_tokensadditional_special_tokensall_special_tokens
special_tokens_map_extended and all_special_tokens_extended: Removed.
special_tokens_map_extendedall_special_tokens_extendedAddedToken_special_tokens_map_extra_special_tokens
sanitize_special_tokens(): Already deprecated in v4, removed in v5.
sanitize_special_tokens()
prepare_seq2seq_batch(): Deprecated; use call() with text_target parameter instead.
prepare_seq2seq_batch()__call__()text_target
BatchEncoding.words(): Deprecated; use word_ids() instead.
BatchEncoding.words()word_ids()
[cache] Remove all deprecated classes.
Deprecate dtype per sub config.