Repository navigation
Do not auto-enable padding-free for a model whose forward cannot take it - #11468
Conversation
Padding-free batching flattens the batch and passes packed_seq_lengths down to
the model. The auto-enable path checked a model-type blocklist and a structural
hybrid-attention probe, but never whether the model's forward can accept the
metadata, so a checkpoint that names neither packed_seq_lengths nor **kwargs
fails on the first training step, well after the trainer was built:
Phi4ForCausalLMV.forward() got an unexpected keyword argument
'packed_seq_lengths'
That is microsoft/Phi-4-reasoning-vision-15B. Ask the signature instead, in
the same spirit as _is_hybrid_linear_attention_model: structural evidence
rather than a name match.
The check unwraps through PEFT's get_base_model only. PeftModel.forward passes
**kwargs straight through so the wrapper always answers yes, while
PreTrainedModel.base_model is a property returning the inner decoder, whose
forward usually does take **kwargs and would answer for the wrong module. An
unreadable signature answers yes, since refusing there would silently turn
padding-free off for models that support it.
Verified on B200, torch 2.13.0+cu130, transformers 5.17.0: Phi-4-reasoning-vision-15B
goes from failing on step 1 to completing a 10 step 16-bit LoRA run, and
unsloth/gemma-3-27b-it, which does support padding-free, produces losses
identical to before to every digit.
Codex Review SummaryThis comment shows the latest Codex review activity on this pull request.
ℹ️ About Codex in GitHubYour team has set up Codex to review pull requests in this repo. Reviews are triggered when you
Codex reacts with 👀 while any review is running, comments if it has suggestions, and reacts with 👍 once all reviews finish with no findings. |
The gate shipped with no test. These pin all eleven shapes, including the two the implementation deliberately gets right and would be easy to regress: PEFT's get_base_model is unwrapped, PreTrainedModel.base_model is NOT (its inner decoder does take **kwargs, so following it answers for the wrong module), and anything unknown or uninspectable fails open to True so padding-free is never silently turned off.
When the signature gate was the sole blocker and the user asked for packing=True, the reason chain fell through to the catch-all branch and logged "packing=True ignored (UNSLOTH_RETURN_LOGITS=1)", pointing at an environment variable the user had not set. The gate is a new blocker, so it needed its own branch. The predicate is also hoisted to a variable rather than called twice.
|
@codex review |
|
@codex security review |
There was a problem hiding this comment.
💡 Codex Review
Here are some automated review suggestions for this pull request.
Reviewed commit: cbc1336946
ℹ️ About Codex in GitHub
Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you
- Open a pull request for review
- Mark a draft as ready
- Comment "@codex review".
If Codex has suggestions, it will comment; otherwise it will react with 👍.
Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".
| return True | ||
| if any(p.kind is inspect.Parameter.VAR_KEYWORD for p in parameters.values()): | ||
| return True | ||
| return "packed_seq_lengths" in parameters |
There was a problem hiding this comment.
Reject positional-only packing parameters
When a custom model declares forward(self, packed_seq_lengths, /, ...), this name check returns true even though the trainer supplies packed_seq_lengths as a keyword from the collator. Packing therefore remains enabled and the first training step raises TypeError; verify that the named parameter is not POSITIONAL_ONLY before treating it as accepted.
Useful? React with 👍 / 👎.
There was a problem hiding this comment.
Accurate about inspect, but I am not taking it. A forward declaring packed_seq_lengths as positional-only is a shape no real checkpoint has: the argument exists so that TRL can pass it as a keyword, so a model that accepts it positionally-only has gone out of its way to name it and then make it unusable. The gate's failure mode there is also the pre-existing one, since packing stays on exactly as it does on main today.
This PR turns padding-free off only where the signature positively shows it cannot work, and I would rather not widen that on a hypothetical. If a checkpoint like that turns up, the guard is one comparison against inspect.Parameter.POSITIONAL_ONLY and can be added with a test that names the model.
|
Codex Review: Didn't find any major issues. What shall we delve into next? Reviewed commit: ℹ️ About Codex in GitHubYour team has set up Codex to review pull requests in this repo. Reviews are triggered when you
If Codex has suggestions, it will comment; otherwise it will react with 👍. Codex can also answer questions or update the PR. Try commenting "@codex address that feedback". |
…the grant the same way twice Two problems with the resolution order and the trust check, both found by asking what this does with an attacker-controlled `config.json` rather than a cooperative one. Remote code was tried FIRST. A checkpoint can carry a native `architectures` and an `auto_map` at the same time, and TRL's own `create_model_from_path` resolves `getattr(transformers, config.architectures[0])` and consults `auto_map` not at all. So for such a checkpoint this imported and executed a module that nothing else in the stack would have run. That is a new code path, not the earlier timing of an existing one, and the comment claiming otherwise was wrong. Native names and the auto mappings are now tried first, and `auto_map` only once nothing else has answered. The grant was read by `is None` rather than by membership, so an explicit `model_init_kwargs["trust_remote_code"] = None` was discarded in favour of a truthy top-level attribute. `_resolve_string_model_config`, which decides whether the config itself may come from remote code, reads it by membership and keeps the None. The two disagreeing meant this could execute a module under a grant the config load had not accepted. Both now read it the same way. The remote auto-class order also now matches TRL's preference, image-text-to-text before causal LM.
repro_instr.py was a local harness for tracing the gate during review and was swept in by a broad add. It is not part of the change.
There was a problem hiding this comment.
💡 Codex Review
Here are some automated review suggestions for this pull request.
Reviewed commit: 9c81be69c4
ℹ️ About Codex in GitHub
Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you
- Open a pull request for review
- Mark a draft as ready
- Comment "@codex review".
If Codex has suggestions, it will comment; otherwise it will react with 👍.
Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".
… delegates to `get_peft_model(..., mixed = True)` returns a `PeftMixedModel`, which has no `get_base_model()`, so the PEFT unwrap stopped on it. Its own forward is `(*args, **kwargs)`, so the signature read answered yes while the checkpoint underneath was the one that rejects `packed_seq_lengths`. Padding-free therefore stayed enabled and training died on the first step, which is the exact failure this gate exists to prevent. Reproduced on real PEFT 0.21.0 before the fix: the gate answers True for a `PeftMixedModel` around a narrowed LlamaForCausalLM, against False for the same checkpoint under a plain `PeftModel`. The path followed is PEFT's own accessor, `self.base_model.model`, which it uses for every config that is not prompt-learning; mixed adapters cannot be prompt-learning, so that reaches the checkpoint rather than an inner decoder. Exact isinstance, and resolved tolerantly because peft is optional here.
There was a problem hiding this comment.
💡 Codex Review
Here are some automated review suggestions for this pull request.
Reviewed commit: 5b891d213f
ℹ️ About Codex in GitHub
Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you
- Open a pull request for review
- Mark a draft as ready
- Comment "@codex review".
If Codex has suggestions, it will comment; otherwise it will react with 👍.
Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".
`_resolve_string_model_config` forwards `use_auth_token` along with the other auth keys; the class resolution added here did not. transformers still honours it as a deprecated alias for `token` across the supported range (dynamic_module_utils.py:584 in 4.57.6 pops it and assigns it to `token`; removed only in 5.x), so on a private remote-code checkpoint authenticated that way the config fetch succeeded and the modeling-file fetch did not. The class then failed to resolve, resolution returned None, and the post-init backstop raised for a forward that rejects `packed_seq_lengths` even though padding-free had merely been auto-enabled, which is the refusal the pre-init resolution exists to avoid. The test asserts the two key lists against each other rather than against a copy, so they cannot drift apart silently.
|
@codex review |
|
Codex Review: Didn't find any major issues. What shall we delve into next? Reviewed commit: ℹ️ About Codex in GitHubYour team has set up Codex to review pull requests in this repo. Reviews are triggered when you
If Codex has suggestions, it will comment; otherwise it will react with 👍. Codex can also answer questions or update the PR. Try commenting "@codex address that feedback". |
Comments and docstrings only, AST-verified: 423 comment lines to 320 across the two files, and the inline comments added by this branch are now 10.1 percent of its own added lines against 7.8 percent already in trainer.py on main. Multi-line rationale collapsed to one line wherever the extra lines restated the code; every load-bearing fact kept, including the ones a reader would otherwise reintroduce as bugs: why base_model must not be followed, why the post-init check stays armed, why remote code is resolved last, and why the auth key lists must match.
…wargs already refuses every shape it does
…n in 4-bit and Nemotron-3-Nano-Omni (#11526) * Let a remote-code from_pretrained cast a 4-bit model's unquantized floats microsoft/Phi-4-reasoning-vision-15B overrides from_pretrained and ends it with model.to(dtype), where dtype falls back to the model's own dtype. transformers refuses every dtype cast on a bitsandbytes model, so the 4-bit load stopped with "You cannot cast a bitsandbytes model in a new dtype" while the 16-bit load was fine. For the duration of Unsloth's own from_pretrained call, and only when the model is loaded with trust_remote_code in 4-bit or 8-bit, PreTrainedModel.to casts the floating tensors that are not packed bitsandbytes weights (Params4bit with a quant_state, Int8Params with an SCB) and leaves the packed weights alone. Device moves and unquantized models keep transformers' own path, and the original method is restored when the load returns. * Keep padding-free off a forward that cannot take packed_seq_lengths, and let a wrapper inherit gradient checkpointing support Padding-free batching adds packed_seq_lengths to every batch. A remote-code forward with a fixed signature (microsoft/Phi-4-reasoning-vision-15B) raised "got an unexpected keyword argument 'packed_seq_lengths'" on the first step after the 4-bit load was fixed. Auto padding-free and packing now stay off when the model's forward, looked through PEFT, accepts neither that key nor **kwargs; a string model or an unreadable signature leaves the decision as it was. nvidia/Nemotron-3-Nano-Omni-30B-A3B wraps a complete NemotronHForCausalLM in a PreTrainedModel that keeps transformers' default supports_gradient_checkpointing = False, so Trainer's gradient_checkpointing_enable raised "does not support gradient checkpointing" although every layer underneath supports it. After the load, a wrapper that says no while a nested model says yes now says yes on the instance; transformers enables checkpointing by walking modules, so every layer is switched on as before. * Train the language model of a wrapper whose forward cannot take a text batch nvidia/Nemotron-3-Nano-Omni-30B-A3B wraps a complete NemotronHForCausalLM as language_model behind a forward whose first parameter, pixel_values, has no default and whose body indexes image_flags. A text-only SFT batch stopped on the first step with "missing 1 required positional argument: 'pixel_values'" once the load, the LoRA targets and the trainer setup were fixed. After the load, a wrapper whose forward requires an input that a text batch does not carry, with exactly one direct child that is a PreTrainedModel with its own forward and both embedding accessors (language_model or thinker when several qualify), hands training to that child, and the generation-time siblings are dropped so their weights are freed. Every transformers VLM defaults its image inputs to None and is returned unchanged, as is anything ambiguous. UNSLOTH_KEEP_COMPOSED_WRAPPER=1 turns this off. * Recognise gradient checkpointing support from transformers' checkpointing layer NemotronHForCausalLM's remote code builds every NemotronHBlock on transformers' GradientCheckpointingLayer but never sets supports_gradient_checkpointing on the model class, so Trainer's gradient_checkpointing_enable raised "NemotronHForCausalLM does not support gradient checkpointing" once training reached it. A model built on that layer now counts as supporting it, alongside a nested model that says so itself. * [pre-commit.ci] auto fixes from pre-commit.com hooks for more information, see https://pre-commit.ci * [pre-commit.ci] auto fixes from pre-commit.com hooks for more information, see https://pre-commit.ci * Carry the wrapper's loader state onto the core that replaces it from_pretrained records is_loaded_in_4bit, is_quantized, quantization_method, hf_quantizer and hf_device_map on the object it returns, not on its children. PEFT reads is_loaded_in_4bit off the model it is given to pick lora.bnb.Linear4bit over the plain lora.Linear, so a core returned without the flags trained through the wrong LoRA layer: the forward ran, but merging wrote a 16-bit delta into packed 4-bit weights and the fast QLoRA path was skipped. The flags now move to the core, the device map is re-keyed from the wrapper's names to the core's, and the wrapper config's quantization_config is carried so a saved core still says it is 4-bit. Tests: the carried state on a synthetic wrapper, no state invented when the wrapper has none, and PEFT dispatching Linear4bit on a real 4-bit core; the last two fail on the branch before this commit. * Keep the composed wrapper when the load asked for the multimodal model Unwrapping a wrapper whose forward requires pixel_values was unconditional, so a FastVisionModel load of Nemotron-Omni meant for image batches lost its vision tower at load and trained the text core. The unwrap now runs only when the load carries text intent: text_only = True, or a model with no vision config. A multimodal load keeps the wrapper and prints the text_only hint, and the UNSLOTH_KEEP_COMPOSED_WRAPPER opt-out is unchanged. The two new test files also get the SPDX line the other tests carry. Test: text_intent = False returns the wrapper with its vision tower and names text_only = True; a wrapper that takes a text batch prints nothing. * Keep an unquantized keyword cast inside the tolerated load, and read the bound forward for the packing gate _tolerate_dtype_cast_on_quantized_model popped dtype out of kwargs and then, on an ordinary model, handed the call on without it, so model.to(dtype = ...) made inside a remote-code from_pretrained was a silent no-op: the model stayed float32. The pass-through now forwards the call exactly as it arrived. _forward_accepts_packed_seq_lengths read type(model).forward, which on an nn.Module is never absent (it falls back to _forward_unimplemented, whose signature takes no keywords), so a torch.compile'd model, which sets forward on the instance, was read as a fixed signature and padding-free was switched off for every compiled model. It now reads the bound forward first, as the merged _forward_accepts_packing_kwargs does. Tests: the three cast spellings on an unquantized model inside the context, a compiled kwargs forward keeps padding-free, and the fixed-signature control. Three fail on the previous commit. * Unwrap a remote-code composition only when the caller asks for text training The gate keyed off the wrapper's vision_config, which an audio-only composition does not have either, so a multimodal load still lost its wrapper. Only the caller knows the intent: unwrap on text_only = True and keep the composition whole otherwise. * Carry the caller's text intent past the loader's normalisation, and count token_type_ids as text loader.py turns text_only off for a family without its own text decoder so the full wrapper loads, and forwarded that normalised value as the intent: a text_only request for such a model kept a wrapper whose forward needs pixel_values. The caller's own request now travels separately. token_type_ids is a standard tokenizer field the Trainer supplies, so a wrapper that requires it can take a text batch and is not unwrapped. * Only a field the collator supplies excuses a required forward parameter A required cache_position, use_cache, past_key_values or return_dict is not something the Trainer puts in a text batch, so a forward that demands one without a default cannot take a text batch either. * [pre-commit.ci] auto fixes from pre-commit.com hooks for more information, see https://pre-commit.ci * Trim comments * Free memory through clean_gpu_cache() in _text_trainable_core torch.cuda.empty_cache() skipped XPU and failed the shared cache dispatch test. * Gate the CUDA-only tests on the real accelerator probe, not the spoofable torch.cuda check * Drop the duplicate inspect import in vision.py * Trim comments * Drop the packed_seq_lengths gate: #11468's _forward_accepts_packing_kwargs already refuses every shape it does * Append text_intent after the existing from_pretrained parameters so their positions do not move * Carry the wrapper dtype and repo path onto a text core, engage the cast shim for quantization_config loads, refuse merged saves of a text core * [pre-commit.ci] auto fixes from pre-commit.com hooks for more information, see https://pre-commit.ci * Limit the cast shim to bitsandbytes, carry the wrapper generation_config to the text core, accept every adapter save spelling * Refuse only PEFT merges of a text core: a full finetune saves its resident weights * Refuse a full-finetuned text core's merged save when its class exists only in remote code * Move the text-core save refusal into a helper: unsloth_generic_save forwards its locals() as keywords, which broke every push_to_hub_merged --------- Co-authored-by: pre-commit-ci[bot] <66853113+pre-commit-ci[bot]@users.noreply.github.com>
…oRA, run the root dispatch hook on the embedding's device (Nemotron-Labs-Teacher) (#11543) * Let a remote-code from_pretrained cast a 4-bit model's unquantized floats microsoft/Phi-4-reasoning-vision-15B overrides from_pretrained and ends it with model.to(dtype), where dtype falls back to the model's own dtype. transformers refuses every dtype cast on a bitsandbytes model, so the 4-bit load stopped with "You cannot cast a bitsandbytes model in a new dtype" while the 16-bit load was fine. For the duration of Unsloth's own from_pretrained call, and only when the model is loaded with trust_remote_code in 4-bit or 8-bit, PreTrainedModel.to casts the floating tensors that are not packed bitsandbytes weights (Params4bit with a quant_state, Int8Params with an SCB) and leaves the packed weights alone. Device moves and unquantized models keep transformers' own path, and the original method is restored when the load returns. * Keep padding-free off a forward that cannot take packed_seq_lengths, and let a wrapper inherit gradient checkpointing support Padding-free batching adds packed_seq_lengths to every batch. A remote-code forward with a fixed signature (microsoft/Phi-4-reasoning-vision-15B) raised "got an unexpected keyword argument 'packed_seq_lengths'" on the first step after the 4-bit load was fixed. Auto padding-free and packing now stay off when the model's forward, looked through PEFT, accepts neither that key nor **kwargs; a string model or an unreadable signature leaves the decision as it was. nvidia/Nemotron-3-Nano-Omni-30B-A3B wraps a complete NemotronHForCausalLM in a PreTrainedModel that keeps transformers' default supports_gradient_checkpointing = False, so Trainer's gradient_checkpointing_enable raised "does not support gradient checkpointing" although every layer underneath supports it. After the load, a wrapper that says no while a nested model says yes now says yes on the instance; transformers enables checkpointing by walking modules, so every layer is switched on as before. * Train the language model of a wrapper whose forward cannot take a text batch nvidia/Nemotron-3-Nano-Omni-30B-A3B wraps a complete NemotronHForCausalLM as language_model behind a forward whose first parameter, pixel_values, has no default and whose body indexes image_flags. A text-only SFT batch stopped on the first step with "missing 1 required positional argument: 'pixel_values'" once the load, the LoRA targets and the trainer setup were fixed. After the load, a wrapper whose forward requires an input that a text batch does not carry, with exactly one direct child that is a PreTrainedModel with its own forward and both embedding accessors (language_model or thinker when several qualify), hands training to that child, and the generation-time siblings are dropped so their weights are freed. Every transformers VLM defaults its image inputs to None and is returned unchanged, as is anything ambiguous. UNSLOTH_KEEP_COMPOSED_WRAPPER=1 turns this off. * Recognise gradient checkpointing support from transformers' checkpointing layer NemotronHForCausalLM's remote code builds every NemotronHBlock on transformers' GradientCheckpointingLayer but never sets supports_gradient_checkpointing on the model class, so Trainer's gradient_checkpointing_enable raised "NemotronHForCausalLM does not support gradient checkpointing" once training reached it. A model built on that layer now counts as supporting it, alongside a nested model that says so itself. * [pre-commit.ci] auto fixes from pre-commit.com hooks for more information, see https://pre-commit.ci * [pre-commit.ci] auto fixes from pre-commit.com hooks for more information, see https://pre-commit.ci * Carry the wrapper's loader state onto the core that replaces it from_pretrained records is_loaded_in_4bit, is_quantized, quantization_method, hf_quantizer and hf_device_map on the object it returns, not on its children. PEFT reads is_loaded_in_4bit off the model it is given to pick lora.bnb.Linear4bit over the plain lora.Linear, so a core returned without the flags trained through the wrong LoRA layer: the forward ran, but merging wrote a 16-bit delta into packed 4-bit weights and the fast QLoRA path was skipped. The flags now move to the core, the device map is re-keyed from the wrapper's names to the core's, and the wrapper config's quantization_config is carried so a saved core still says it is 4-bit. Tests: the carried state on a synthetic wrapper, no state invented when the wrapper has none, and PEFT dispatching Linear4bit on a real 4-bit core; the last two fail on the branch before this commit. * Keep the composed wrapper when the load asked for the multimodal model Unwrapping a wrapper whose forward requires pixel_values was unconditional, so a FastVisionModel load of Nemotron-Omni meant for image batches lost its vision tower at load and trained the text core. The unwrap now runs only when the load carries text intent: text_only = True, or a model with no vision config. A multimodal load keeps the wrapper and prints the text_only hint, and the UNSLOTH_KEEP_COMPOSED_WRAPPER opt-out is unchanged. The two new test files also get the SPDX line the other tests carry. Test: text_intent = False returns the wrapper with its vision tower and names text_only = True; a wrapper that takes a text batch prints nothing. * Keep an unquantized keyword cast inside the tolerated load, and read the bound forward for the packing gate _tolerate_dtype_cast_on_quantized_model popped dtype out of kwargs and then, on an ordinary model, handed the call on without it, so model.to(dtype = ...) made inside a remote-code from_pretrained was a silent no-op: the model stayed float32. The pass-through now forwards the call exactly as it arrived. _forward_accepts_packed_seq_lengths read type(model).forward, which on an nn.Module is never absent (it falls back to _forward_unimplemented, whose signature takes no keywords), so a torch.compile'd model, which sets forward on the instance, was read as a fixed signature and padding-free was switched off for every compiled model. It now reads the bound forward first, as the merged _forward_accepts_packing_kwargs does. Tests: the three cast spellings on an unquantized model inside the context, a compiled kwargs forward keeps padding-free, and the fixed-signature control. Three fail on the previous commit. * Unwrap a remote-code composition only when the caller asks for text training The gate keyed off the wrapper's vision_config, which an audio-only composition does not have either, so a multimodal load still lost its wrapper. Only the caller knows the intent: unwrap on text_only = True and keep the composition whole otherwise. * Carry the caller's text intent past the loader's normalisation, and count token_type_ids as text loader.py turns text_only off for a family without its own text decoder so the full wrapper loads, and forwarded that normalised value as the intent: a text_only request for such a model kept a wrapper whose forward needs pixel_values. The caller's own request now travels separately. token_type_ids is a standard tokenizer field the Trainer supplies, so a wrapper that requires it can take a text batch and is not unwrapped. * Only a field the collator supplies excuses a required forward parameter A required cache_position, use_cache, past_key_values or return_dict is not something the Trainer puts in a text batch, so a forward that demands one without a default cannot take a text batch either. * Resolve remote-code model classes and reach per-expert submodules with LoRA A remote config that reuses a native class name (NemotronHConfig on the Nemotron-H hub checkpoints) resolved to the native model class through the name-keyed auto mapping, so the attention implementation was chosen from the flags of a class that is never built. The remote class only carries the old _supports_flash_attn_2 flag, which transformers 5 no longer dispatches on, and the load stopped with "does not support Flash Attention 2 yet". resolve_model_class now returns the class transformers instantiates for a remote config (auto_map entry plus a config class from transformers_modules), and flash support is read from the flag the installed transformers dispatches on. Routed experts kept as per-expert submodules (mixer.experts.<i>.up_proj) were silently left frozen on standalone text models: the regex FastModel builds only reaches a leaf directly under the block, while the same layout inside a vision-language wrapper matched through the language tag. The nested alternative is added when the requested MLP leaves exist inside experts and the regex does not already reach them. * Give the flash fixtures the flag transformers dispatches on, keep the nested-expert test off a stubbed peft_utils * Run the root dispatch hook where the input embedding lives accelerate picks the root execution device as the first member of the set of devices in the map, so a plan that keeps the embedding off that device sends every batch there first; the embedding hook then carries input_ids on while attention_mask and labels stay behind. Modeling code that builds its own mask on the embedding's device (the transformers 4.4x _update_causal_mask the Nemotron-H hub checkpoints ship) fails with "Expected all tensors to be on the same device". Native transformers moves the mask itself, which kept the extra hop invisible. Aligning the root with the embedding also drops both copies from every batch. * Fetch a missing remote modeling module with the load's own hub options When only the configuration module is materialised, the resolver asked get_class_from_dynamic_module for the repository's default revision with no token, cache directory or offline flag, so a load pinned to a revision or a code_revision could read another revision's flags and local_files_only = True could reach the network. The loader now passes revision, code_revision, token, cache_dir and local_files_only through, and a other/repo--module.Class reference no longer consults a same-named module next to the config, which belongs to a different repository. Tests: the fetch receives exactly the load's options; a cross-repository reference resolves in the other repository. Both fail on the previous commit. * Add the SPDX line the other test files carry * Widen only a generated target regex to the routed experts, and fetch a cross-repository auto_map class by its full reference A regex the caller wrote, such as one naming the shared expert alone, is their scope: widening it attached an adapter to every routed expert in every layer. The nested-expert alternative is now added only to the regex get_peft_regex built. A class reference of the form other/repo--module.Class is handed to get_class_from_dynamic_module unsplit with the model's own repo_id, which is how transformers resolves it, instead of splitting off the module and asking for a sibling file that the model repository does not have. * Do not widen onto the routed experts when the language layers are out of scope The experts live in the language model, so a vision-only request (finetune_language_layers = False) whose generated regex still names the MLP leaves must not gain the nested-expert alternative. * Keep gate and up expert leaves separate, and read the installed flash dispatch check A request for gate_proj alone no longer collects up_proj leaves (and the reverse); only the fused gate_up_proj spelling asks for both. transformers 5.0 to 5.3 still accept the legacy _supports_flash_attn_2 flag in the dispatch check, so the helper reads that function instead of inferring the answer from the presence of the new base-class attribute. * [pre-commit.ci] auto fixes from pre-commit.com hooks for more information, see https://pre-commit.ci * [pre-commit.ci] auto fixes from pre-commit.com hooks for more information, see https://pre-commit.ci * Honour trust_remote_code and force_download when resolving a remote model class A materialised remote config handed in with trust_remote_code = False no longer has its modeling module imported before transformers can refuse the load, and a forced download goes through transformers instead of returning an already imported sibling that is about to be replaced. * [pre-commit.ci] auto fixes from pre-commit.com hooks for more information, see https://pre-commit.ci * Forward the trust decision to every remote class probe in the loader The probes that pick the auto class did not pass trust_remote_code, so a materialised remote config could have its modeling module imported before transformers refused the load. * [pre-commit.ci] auto fixes from pre-commit.com hooks for more information, see https://pre-commit.ci * Forward trust, revision, token and offline options to every remote class probe * Ask transformers for the class when a code_revision is set instead of reusing the config's sibling module * Gate the legacy flash flag tests on the installed dispatch check, not on attribute presence * Trim comments * Trim comments * Widen generated LoRA targets to per-expert submodules only for remote code On transformers 4.x native per-expert layouts (Qwen3-MoE, Qwen2-MoE, OLMoE, DeepSeek-V3) nest experts the same way, and widening gave every routed expert LoRA: a Qwen3-30B-A3B shape went from 240 to 18,672 targets, +830M LoRA parameters at r=16. Only MoE blocks whose expert classes come from the checkpoint's own code are widened now. Also: the legacy-flash test fails on a reverted tree without flash-attn, _text_trainable_core frees memory through clean_gpu_cache(), and #11526's comments are kept as they are there. * Free memory through clean_gpu_cache() in _text_trainable_core torch.cuda.empty_cache() skipped XPU and failed the shared cache dispatch test. * Scope expert widening to the remote experts' parents and the root hook to remote text models The widened alternative now names the parent paths of the remote expert blocks instead of any parent, so a native expert tower next to remote code keeps its targets. The root dispatch hook is only moved for remote-code models without a vision or audio sub-config: the hook moves every input, and native code moves the mask itself. * Give the sentence-transformer class probes the load's options, and fetch only for trusted loads resolve_encoder_attention_implementation and _has_add_pooling_layer now pass FastSentenceTransformer.from_pretrained's trust_remote_code, revision, token, cache folder and local_files_only to the remote-class resolver, so a pinned or offline encoder is inspected with the code it loads. A probe that did not ask for remote code may reuse an imported sibling module but never fetches. * Skip the imported sibling module when the load names a revision transformers uses revision as the code revision for same-repo code, so a config loaded from one revision and a model loaded with another would be inspected with the wrong modeling class. * Forward the load's proxies to every remote-class probe * Gate the CUDA-only tests on the real accelerator probe, not the spoofable torch.cuda check * Gate the CUDA-only tests on the real accelerator probe, not the spoofable torch.cuda check * Reuse the gated revision for the class probes, and give the text-only test the remote class helper * Drop the duplicate inspect import in vision.py * Trim comments * Trim comments * Drop the packed_seq_lengths gate: #11468's _forward_accepts_packing_kwargs already refuses every shape it does * Append text_intent after the existing from_pretrained parameters so their positions do not move * [pre-commit.ci] auto fixes from pre-commit.com hooks for more information, see https://pre-commit.ci * Carry the wrapper dtype and repo path onto a text core, engage the cast shim for quantization_config loads, refuse merged saves of a text core * [pre-commit.ci] auto fixes from pre-commit.com hooks for more information, see https://pre-commit.ci * [pre-commit.ci] auto fixes from pre-commit.com hooks for more information, see https://pre-commit.ci * Limit the cast shim to bitsandbytes, carry the wrapper generation_config to the text core, accept every adapter save spelling * Leave omni configs with towers under thinker_config out of the root hook alignment * Refuse only PEFT merges of a text core: a full finetune saves its resident weights * Leave towers spelled vision_encoder_config / audio_encoder_config / encoder_config out of the root hook alignment * Refuse a full-finetuned text core's merged save when its class exists only in remote code * Move the text-core save refusal into a helper: unsloth_generic_save forwards its locals() as keywords, which broke every push_to_hub_merged --------- Co-authored-by: pre-commit-ci[bot] <66853113+pre-commit-ci[bot]@users.noreply.github.com>
…mni) (#11523) * Let a remote-code from_pretrained cast a 4-bit model's unquantized floats microsoft/Phi-4-reasoning-vision-15B overrides from_pretrained and ends it with model.to(dtype), where dtype falls back to the model's own dtype. transformers refuses every dtype cast on a bitsandbytes model, so the 4-bit load stopped with "You cannot cast a bitsandbytes model in a new dtype" while the 16-bit load was fine. For the duration of Unsloth's own from_pretrained call, and only when the model is loaded with trust_remote_code in 4-bit or 8-bit, PreTrainedModel.to casts the floating tensors that are not packed bitsandbytes weights (Params4bit with a quant_state, Int8Params with an SCB) and leaves the packed weights alone. Device moves and unquantized models keep transformers' own path, and the original method is restored when the load returns. * Keep padding-free off a forward that cannot take packed_seq_lengths, and let a wrapper inherit gradient checkpointing support Padding-free batching adds packed_seq_lengths to every batch. A remote-code forward with a fixed signature (microsoft/Phi-4-reasoning-vision-15B) raised "got an unexpected keyword argument 'packed_seq_lengths'" on the first step after the 4-bit load was fixed. Auto padding-free and packing now stay off when the model's forward, looked through PEFT, accepts neither that key nor **kwargs; a string model or an unreadable signature leaves the decision as it was. nvidia/Nemotron-3-Nano-Omni-30B-A3B wraps a complete NemotronHForCausalLM in a PreTrainedModel that keeps transformers' default supports_gradient_checkpointing = False, so Trainer's gradient_checkpointing_enable raised "does not support gradient checkpointing" although every layer underneath supports it. After the load, a wrapper that says no while a nested model says yes now says yes on the instance; transformers enables checkpointing by walking modules, so every layer is switched on as before. * Train the language model of a wrapper whose forward cannot take a text batch nvidia/Nemotron-3-Nano-Omni-30B-A3B wraps a complete NemotronHForCausalLM as language_model behind a forward whose first parameter, pixel_values, has no default and whose body indexes image_flags. A text-only SFT batch stopped on the first step with "missing 1 required positional argument: 'pixel_values'" once the load, the LoRA targets and the trainer setup were fixed. After the load, a wrapper whose forward requires an input that a text batch does not carry, with exactly one direct child that is a PreTrainedModel with its own forward and both embedding accessors (language_model or thinker when several qualify), hands training to that child, and the generation-time siblings are dropped so their weights are freed. Every transformers VLM defaults its image inputs to None and is returned unchanged, as is anything ambiguous. UNSLOTH_KEEP_COMPOSED_WRAPPER=1 turns this off. * Recognise gradient checkpointing support from transformers' checkpointing layer NemotronHForCausalLM's remote code builds every NemotronHBlock on transformers' GradientCheckpointingLayer but never sets supports_gradient_checkpointing on the model class, so Trainer's gradient_checkpointing_enable raised "NemotronHForCausalLM does not support gradient checkpointing" once training reached it. A model built on that layer now counts as supporting it, alongside a nested model that says so itself. * [pre-commit.ci] auto fixes from pre-commit.com hooks for more information, see https://pre-commit.ci * [pre-commit.ci] auto fixes from pre-commit.com hooks for more information, see https://pre-commit.ci * Carry the wrapper's loader state onto the core that replaces it from_pretrained records is_loaded_in_4bit, is_quantized, quantization_method, hf_quantizer and hf_device_map on the object it returns, not on its children. PEFT reads is_loaded_in_4bit off the model it is given to pick lora.bnb.Linear4bit over the plain lora.Linear, so a core returned without the flags trained through the wrong LoRA layer: the forward ran, but merging wrote a 16-bit delta into packed 4-bit weights and the fast QLoRA path was skipped. The flags now move to the core, the device map is re-keyed from the wrapper's names to the core's, and the wrapper config's quantization_config is carried so a saved core still says it is 4-bit. Tests: the carried state on a synthetic wrapper, no state invented when the wrapper has none, and PEFT dispatching Linear4bit on a real 4-bit core; the last two fail on the branch before this commit. * Keep the composed wrapper when the load asked for the multimodal model Unwrapping a wrapper whose forward requires pixel_values was unconditional, so a FastVisionModel load of Nemotron-Omni meant for image batches lost its vision tower at load and trained the text core. The unwrap now runs only when the load carries text intent: text_only = True, or a model with no vision config. A multimodal load keeps the wrapper and prints the text_only hint, and the UNSLOTH_KEEP_COMPOSED_WRAPPER opt-out is unchanged. The two new test files also get the SPDX line the other tests carry. Test: text_intent = False returns the wrapper with its vision tower and names text_only = True; a wrapper that takes a text batch prints nothing. * Keep an unquantized keyword cast inside the tolerated load, and read the bound forward for the packing gate _tolerate_dtype_cast_on_quantized_model popped dtype out of kwargs and then, on an ordinary model, handed the call on without it, so model.to(dtype = ...) made inside a remote-code from_pretrained was a silent no-op: the model stayed float32. The pass-through now forwards the call exactly as it arrived. _forward_accepts_packed_seq_lengths read type(model).forward, which on an nn.Module is never absent (it falls back to _forward_unimplemented, whose signature takes no keywords), so a torch.compile'd model, which sets forward on the instance, was read as a fixed signature and padding-free was switched off for every compiled model. It now reads the bound forward first, as the merged _forward_accepts_packing_kwargs does. Tests: the three cast spellings on an unquantized model inside the context, a compiled kwargs forward keeps padding-free, and the fixed-signature control. Three fail on the previous commit. * Unwrap a remote-code composition only when the caller asks for text training The gate keyed off the wrapper's vision_config, which an audio-only composition does not have either, so a multimodal load still lost its wrapper. Only the caller knows the intent: unwrap on text_only = True and keep the composition whole otherwise. * Carry the caller's text intent past the loader's normalisation, and count token_type_ids as text loader.py turns text_only off for a family without its own text decoder so the full wrapper loads, and forwarded that normalised value as the intent: a text_only request for such a model kept a wrapper whose forward needs pixel_values. The caller's own request now travels separately. token_type_ids is a standard tokenizer field the Trainer supplies, so a wrapper that requires it can take a text batch and is not unwrapped. * Only a field the collator supplies excuses a required forward parameter A required cache_position, use_cache, past_key_values or return_dict is not something the Trainer puts in a text batch, so a forward that demands one without a default cannot take a text batch either. * Hand a composition with no forward of its own to its thinker Qwen3OmniMoeForConditionalGeneration composes a thinker, a talker and a speech decoder and only generates, so a trainer's forward reached nn.Module.forward. The text-core handoff now treats a wrapper with no forward the same as one whose forward cannot take a text batch. * Hand over a composition with no forward regardless of load intent The multimodal gate keeps a wrapper whose forward takes image batches; a composition with no forward trains nothing on any batch, so it always goes to its thinker. Test added. * Add the SPDX line the other test files carry * Keep the composition whole on a multimodal load A load without text intent may still generate through the wrapper, and Qwen3-Omni does that with its talker and speech decoder, so the handoff to the thinker now happens only when the load asked for the text model. The multimodal load prints the text_only hint instead. Test updated. * [pre-commit.ci] auto fixes from pre-commit.com hooks for more information, see https://pre-commit.ci * [pre-commit.ci] auto fixes from pre-commit.com hooks for more information, see https://pre-commit.ci * [pre-commit.ci] auto fixes from pre-commit.com hooks for more information, see https://pre-commit.ci * [pre-commit.ci] auto fixes from pre-commit.com hooks for more information, see https://pre-commit.ci * Carry the checkpoint identity onto the thinker PEFT copies name_or_path into the adapter's base_model_name_or_path, and a thinker built from thinker_config has none, so a saved adapter pointed at an empty base model. The wrapper's name is carried over with the loader state. * [pre-commit.ci] auto fixes from pre-commit.com hooks for more information, see https://pre-commit.ci * Find a thinker by its lm_head when its output accessor says None transformers 4.x returns None from get_output_embeddings unless a class overrides it, and Qwen3-Omni's thinker only overrides the input side. * [pre-commit.ci] auto fixes from pre-commit.com hooks for more information, see https://pre-commit.ci * Trim comments * Trim comments * Free memory through clean_gpu_cache() in _text_trainable_core torch.cuda.empty_cache() skipped XPU and failed the shared cache dispatch test. * Load Qwen3-Omni with text_only, and give a kept wrapper a text forward text_only = True sent Qwen3-Omni to AutoModelForCausalLM because its vision config sits under thinker_config, so the hint the multimodal load prints pointed at a path that raised "Unrecognized configuration class". It now loads through the composition's own auto class and the text intent hands it to the thinker, as the hint says. A default load keeps the wrapper for audio generation. It now takes the thinker's forward and embedding accessors on the instance, so eval, KD and a custom loop can call model(input_ids = ...), and get_peft_model scopes LoRA to thinker.model instead of only the vision tower. A thinker built from a sub-config also gets its architectures, which generate reads. * Reload a thinker-only Qwen3-Omni adapter onto the thinker An adapter trained with text_only = True has targets and weights rooted at model.layers, which a default reload of the composition names thinker.model.layers, so PEFT found no targets. Unsloth's target regex for a kept wrapper names thinker.model; one trained on the thinker alone never names thinker, so an Omni base reloaded for such an adapter loads as text_only. * [pre-commit.ci] auto fixes from pre-commit.com hooks for more information, see https://pre-commit.ci * Decide a Qwen3-Omni adapter's reload target from its saved weight keys A leaf-name list such as ["q_proj", "v_proj"] reloads as a set that matches either layout, so the regex alone could not tell a thinker-trained adapter from a wrapper-trained one. Read the tensor names from the adapter's safetensors header (locally, or the Hub metadata): thinker-trained keys never contain thinker., wrapper-trained keys always do. The regex check stays as the fallback when the keys cannot be read. * [pre-commit.ci] auto fixes from pre-commit.com hooks for more information, see https://pre-commit.ci * Read a Hub adapter's keys from adapter_model.safetensors get_safetensors_metadata only looks for model.safetensors, so every Hub adapter raised NotASafetensorsRepoError and fell back to the regex. Read the header of adapter_model.safetensors by name instead, and read a local adapter_model.bin's keys on the meta device. * [pre-commit.ci] auto fixes from pre-commit.com hooks for more information, see https://pre-commit.ci * Keep audio-only Omni adapters on the wrapper, and read cached adapters offline Decide from the first key segment after base_model.model.: a key rooted at any of the composition's children (thinker, talker, code2wav, from its sub-configs) means the adapter was trained on the kept wrapper, so an audio-only adapter is no longer mistaken for a thinker one. Look in the Hub cache before the network, so local_files_only still reads the saved keys. * [pre-commit.ci] auto fixes from pre-commit.com hooks for more information, see https://pre-commit.ci * Resolve an Omni adapter's weight file with hf_hub_download, either format PEFT fetches the same file right after, so resolve adapter_model.safetensors and then adapter_model.bin through hf_hub_download (cache first, offline honoured) and read their names without materialising weights. When no file can be read and the targets are a leaf list, say how to load a thinker-only adapter instead of guessing. * [pre-commit.ci] auto fixes from pre-commit.com hooks for more information, see https://pre-commit.ci * Gate the CUDA-only tests on the real accelerator probe, not the spoofable torch.cuda check * Gate the CUDA-only tests on the real accelerator probe, not the spoofable torch.cuda check * Drop the duplicate inspect import in vision.py * Trim comments * Trim comments * Drop the packed_seq_lengths gate: #11468's _forward_accepts_packing_kwargs already refuses every shape it does * Append text_intent after the existing from_pretrained parameters so their positions do not move * Carry the wrapper dtype and repo path onto a text core, engage the cast shim for quantization_config loads, refuse merged saves of a text core * [pre-commit.ci] auto fixes from pre-commit.com hooks for more information, see https://pre-commit.ci * Redirect adapter reloads only for forward-less compositions, and target the thinker's experts on a kept wrapper * Limit the cast shim to bitsandbytes, carry the wrapper generation_config to the text core, accept every adapter save spelling * Freeze a kept wrapper's unused siblings, and read finetune_last_n_layers' layer count through the text core * Scope explicit LoRA leaves on a kept wrapper to its text core, and delegate the embedding setters so vocab resizing works * Refuse only PEFT merges of a text core: a full finetune saves its resident weights * Refuse a full-finetuned text core's merged save when its class exists only in remote code * Move the text-core save refusal into a helper: unsloth_generic_save forwards its locals() as keywords, which broke every push_to_hub_merged * Gate the Qwen3-Omni GPU tests on has_real_cuda: the CI CUDA spoof makes torch.cuda.is_available() true * On a kept wrapper, pass qualified LoRA targets to PEFT unchanged and scope modules_to_save to the text core * Forward the trust decision through the forwardless-composition probes, keep a kept wrapper's siblings frozen after full-finetuning setup, and scope explicit target_parameters to the text core --------- Co-authored-by: pre-commit-ci[bot] <66853113+pre-commit-ci[bot]@users.noreply.github.com>
… it (unslothai#11468) * Do not auto-enable padding-free for a model whose forward cannot take it Padding-free batching flattens the batch and passes packed_seq_lengths down to the model. The auto-enable path checked a model-type blocklist and a structural hybrid-attention probe, but never whether the model's forward can accept the metadata, so a checkpoint that names neither packed_seq_lengths nor **kwargs fails on the first training step, well after the trainer was built: Phi4ForCausalLMV.forward() got an unexpected keyword argument 'packed_seq_lengths' That is microsoft/Phi-4-reasoning-vision-15B. Ask the signature instead, in the same spirit as _is_hybrid_linear_attention_model: structural evidence rather than a name match. The check unwraps through PEFT's get_base_model only. PeftModel.forward passes **kwargs straight through so the wrapper always answers yes, while PreTrainedModel.base_model is a property returning the inner decoder, whose forward usually does take **kwargs and would answer for the wrong module. An unreadable signature answers yes, since refusing there would silently turn padding-free off for models that support it. Verified on B200, torch 2.13.0+cu130, transformers 5.17.0: Phi-4-reasoning-vision-15B goes from failing on step 1 to completing a 10 step 16-bit LoRA run, and unsloth/gemma-3-27b-it, which does support padding-free, produces losses identical to before to every digit. * Add the regression tests for the padding-free signature gate The gate shipped with no test. These pin all eleven shapes, including the two the implementation deliberately gets right and would be easy to regress: PEFT's get_base_model is unwrapped, PreTrainedModel.base_model is NOT (its inner decoder does take **kwargs, so following it answers for the wrong module), and anything unknown or uninspectable fails open to True so padding-free is never silently turned off. * Name the incompatible forward as the packing blocker When the signature gate was the sole blocker and the user asked for packing=True, the reason chain fell through to the catch-all branch and logged "packing=True ignored (UNSLOTH_RETURN_LOGITS=1)", pointing at an environment variable the user had not set. The gate is a new blocker, so it needed its own branch. The predicate is also hoisted to a variable rather than called twice. * Skip the gate tests where unsloth.trainer is the MLX shim * Re-ask the packing question once a string model has been materialized * Turn packing off too when the materialized forward rejects the metadata * Rebuild the trainer when the materialized forward rejects the metadata * Refuse the deferred case instead of undoing a trainer already built * Unwrap the distributed module wrappers before reading a forward * Close the delegating-wrapper family, torch.compile included * Answer the signature question for a string model before the trainer is built A string `model=` had no forward to read, so the gate failed open on it and the mismatch was only caught after `__init__`, where the one honest move left is to refuse: TRL has built its collator from the flags by then, and under packing it has transformed the datasets too, so turning padding-free back off would leave batches arriving flattened with nothing naming the sequence boundaries. That refusal fell on users who had configured nothing. Padding-free is auto-enabled when `padding_free` is left unset, so `SFTTrainer(model = "...")` on such a checkpoint raised for a feature the user never asked for. The class is reachable without the weights. `_resolve_string_model_config` already loads the config for this path, and from it `_resolve_string_model_class` names the class three ways: `auto_map` when trust_remote_code is already granted, which is the population this gate exists for, then the recorded `architectures`, then the auto mappings keyed by config class. `from_pretrained` is never called, so nothing is downloaded beyond the modeling module TRL is about to import anyway. The string case therefore becomes an ordinary silent block like every other reason, and the warning names the resolved class rather than `str`. Resolution is best-effort: anything unresolvable returns None and leaves the post-init check as the backstop, so the fallback is the previous behaviour rather than a guess. The signature reader is now shared by both callers, because a disagreement between them would show up as padding-free turning on for one spelling of a checkpoint and off for the other. * [pre-commit.ci] auto fixes from pre-commit.com hooks for more information, see https://pre-commit.ci * Keep the post-init check armed when the class was resolved from a name Resolving the class before `__init__` is a good guess about the instance, not proof of it. A checkpoint can name several classes in `auto_map`, and the one resolved is not guaranteed to be the one TRL builds. Clearing the deferred flag on a "yes" therefore disarmed the backstop exactly when it was needed: resolved class accepts the argument, built model does not, and the user gets the first-step TypeError this gate exists to prevent. Leaving the check armed costs nothing where the resolution was right. A correct "no" has already turned packing and padding-free off, and those two being off is the condition the check skips on, so it cannot fire there. * Resolve the class natively before reaching for remote code, and read the grant the same way twice Two problems with the resolution order and the trust check, both found by asking what this does with an attacker-controlled `config.json` rather than a cooperative one. Remote code was tried FIRST. A checkpoint can carry a native `architectures` and an `auto_map` at the same time, and TRL's own `create_model_from_path` resolves `getattr(transformers, config.architectures[0])` and consults `auto_map` not at all. So for such a checkpoint this imported and executed a module that nothing else in the stack would have run. That is a new code path, not the earlier timing of an existing one, and the comment claiming otherwise was wrong. Native names and the auto mappings are now tried first, and `auto_map` only once nothing else has answered. The grant was read by `is None` rather than by membership, so an explicit `model_init_kwargs["trust_remote_code"] = None` was discarded in favour of a truthy top-level attribute. `_resolve_string_model_config`, which decides whether the config itself may come from remote code, reads it by membership and keeps the None. The two disagreeing meant this could execute a module under a grant the config load had not accepted. Both now read it the same way. The remote auto-class order also now matches TRL's preference, image-text-to-text before causal LM. * Remove a scratch instrumentation script committed by mistake repro_instr.py was a local harness for tracing the gate during review and was swept in by a broad add. It is not part of the change. * Unwrap PeftMixedModel, whose forward answers for a checkpoint it only delegates to `get_peft_model(..., mixed = True)` returns a `PeftMixedModel`, which has no `get_base_model()`, so the PEFT unwrap stopped on it. Its own forward is `(*args, **kwargs)`, so the signature read answered yes while the checkpoint underneath was the one that rejects `packed_seq_lengths`. Padding-free therefore stayed enabled and training died on the first step, which is the exact failure this gate exists to prevent. Reproduced on real PEFT 0.21.0 before the fix: the gate answers True for a `PeftMixedModel` around a narrowed LlamaForCausalLM, against False for the same checkpoint under a plain `PeftModel`. The path followed is PEFT's own accessor, `self.base_model.model`, which it uses for every config that is not prompt-learning; mixed adapters cannot be prompt-learning, so that reaches the checkpoint rather than an inner decoder. Exact isinstance, and resolved tolerantly because peft is optional here. * Forward the legacy auth key to the class fetch as well `_resolve_string_model_config` forwards `use_auth_token` along with the other auth keys; the class resolution added here did not. transformers still honours it as a deprecated alias for `token` across the supported range (dynamic_module_utils.py:584 in 4.57.6 pops it and assigns it to `token`; removed only in 5.x), so on a private remote-code checkpoint authenticated that way the config fetch succeeded and the modeling-file fetch did not. The class then failed to resolve, resolution returned None, and the post-init backstop raised for a forward that rejects `packed_seq_lengths` even though padding-free had merely been auto-enabled, which is the refusal the pre-init resolution exists to avoid. The test asserts the two key lists against each other rather than against a copy, so they cannot drift apart silently. * Reduce comments on this branch's own additions Comments and docstrings only, AST-verified: 423 comment lines to 320 across the two files, and the inline comments added by this branch are now 10.1 percent of its own added lines against 7.8 percent already in trainer.py on main. Multi-line rationale collapsed to one line wherever the extra lines restated the code; every load-bearing fact kept, including the ones a reader would otherwise reintroduce as bugs: why base_model must not be followed, why the post-init check stays armed, why remote code is resolved last, and why the auth key lists must match. --------- Co-authored-by: pre-commit-ci[bot] <66853113+pre-commit-ci[bot]@users.noreply.github.com>
…n in 4-bit and Nemotron-3-Nano-Omni (unslothai#11526) * Let a remote-code from_pretrained cast a 4-bit model's unquantized floats microsoft/Phi-4-reasoning-vision-15B overrides from_pretrained and ends it with model.to(dtype), where dtype falls back to the model's own dtype. transformers refuses every dtype cast on a bitsandbytes model, so the 4-bit load stopped with "You cannot cast a bitsandbytes model in a new dtype" while the 16-bit load was fine. For the duration of Unsloth's own from_pretrained call, and only when the model is loaded with trust_remote_code in 4-bit or 8-bit, PreTrainedModel.to casts the floating tensors that are not packed bitsandbytes weights (Params4bit with a quant_state, Int8Params with an SCB) and leaves the packed weights alone. Device moves and unquantized models keep transformers' own path, and the original method is restored when the load returns. * Keep padding-free off a forward that cannot take packed_seq_lengths, and let a wrapper inherit gradient checkpointing support Padding-free batching adds packed_seq_lengths to every batch. A remote-code forward with a fixed signature (microsoft/Phi-4-reasoning-vision-15B) raised "got an unexpected keyword argument 'packed_seq_lengths'" on the first step after the 4-bit load was fixed. Auto padding-free and packing now stay off when the model's forward, looked through PEFT, accepts neither that key nor **kwargs; a string model or an unreadable signature leaves the decision as it was. nvidia/Nemotron-3-Nano-Omni-30B-A3B wraps a complete NemotronHForCausalLM in a PreTrainedModel that keeps transformers' default supports_gradient_checkpointing = False, so Trainer's gradient_checkpointing_enable raised "does not support gradient checkpointing" although every layer underneath supports it. After the load, a wrapper that says no while a nested model says yes now says yes on the instance; transformers enables checkpointing by walking modules, so every layer is switched on as before. * Train the language model of a wrapper whose forward cannot take a text batch nvidia/Nemotron-3-Nano-Omni-30B-A3B wraps a complete NemotronHForCausalLM as language_model behind a forward whose first parameter, pixel_values, has no default and whose body indexes image_flags. A text-only SFT batch stopped on the first step with "missing 1 required positional argument: 'pixel_values'" once the load, the LoRA targets and the trainer setup were fixed. After the load, a wrapper whose forward requires an input that a text batch does not carry, with exactly one direct child that is a PreTrainedModel with its own forward and both embedding accessors (language_model or thinker when several qualify), hands training to that child, and the generation-time siblings are dropped so their weights are freed. Every transformers VLM defaults its image inputs to None and is returned unchanged, as is anything ambiguous. UNSLOTH_KEEP_COMPOSED_WRAPPER=1 turns this off. * Recognise gradient checkpointing support from transformers' checkpointing layer NemotronHForCausalLM's remote code builds every NemotronHBlock on transformers' GradientCheckpointingLayer but never sets supports_gradient_checkpointing on the model class, so Trainer's gradient_checkpointing_enable raised "NemotronHForCausalLM does not support gradient checkpointing" once training reached it. A model built on that layer now counts as supporting it, alongside a nested model that says so itself. * [pre-commit.ci] auto fixes from pre-commit.com hooks for more information, see https://pre-commit.ci * [pre-commit.ci] auto fixes from pre-commit.com hooks for more information, see https://pre-commit.ci * Carry the wrapper's loader state onto the core that replaces it from_pretrained records is_loaded_in_4bit, is_quantized, quantization_method, hf_quantizer and hf_device_map on the object it returns, not on its children. PEFT reads is_loaded_in_4bit off the model it is given to pick lora.bnb.Linear4bit over the plain lora.Linear, so a core returned without the flags trained through the wrong LoRA layer: the forward ran, but merging wrote a 16-bit delta into packed 4-bit weights and the fast QLoRA path was skipped. The flags now move to the core, the device map is re-keyed from the wrapper's names to the core's, and the wrapper config's quantization_config is carried so a saved core still says it is 4-bit. Tests: the carried state on a synthetic wrapper, no state invented when the wrapper has none, and PEFT dispatching Linear4bit on a real 4-bit core; the last two fail on the branch before this commit. * Keep the composed wrapper when the load asked for the multimodal model Unwrapping a wrapper whose forward requires pixel_values was unconditional, so a FastVisionModel load of Nemotron-Omni meant for image batches lost its vision tower at load and trained the text core. The unwrap now runs only when the load carries text intent: text_only = True, or a model with no vision config. A multimodal load keeps the wrapper and prints the text_only hint, and the UNSLOTH_KEEP_COMPOSED_WRAPPER opt-out is unchanged. The two new test files also get the SPDX line the other tests carry. Test: text_intent = False returns the wrapper with its vision tower and names text_only = True; a wrapper that takes a text batch prints nothing. * Keep an unquantized keyword cast inside the tolerated load, and read the bound forward for the packing gate _tolerate_dtype_cast_on_quantized_model popped dtype out of kwargs and then, on an ordinary model, handed the call on without it, so model.to(dtype = ...) made inside a remote-code from_pretrained was a silent no-op: the model stayed float32. The pass-through now forwards the call exactly as it arrived. _forward_accepts_packed_seq_lengths read type(model).forward, which on an nn.Module is never absent (it falls back to _forward_unimplemented, whose signature takes no keywords), so a torch.compile'd model, which sets forward on the instance, was read as a fixed signature and padding-free was switched off for every compiled model. It now reads the bound forward first, as the merged _forward_accepts_packing_kwargs does. Tests: the three cast spellings on an unquantized model inside the context, a compiled kwargs forward keeps padding-free, and the fixed-signature control. Three fail on the previous commit. * Unwrap a remote-code composition only when the caller asks for text training The gate keyed off the wrapper's vision_config, which an audio-only composition does not have either, so a multimodal load still lost its wrapper. Only the caller knows the intent: unwrap on text_only = True and keep the composition whole otherwise. * Carry the caller's text intent past the loader's normalisation, and count token_type_ids as text loader.py turns text_only off for a family without its own text decoder so the full wrapper loads, and forwarded that normalised value as the intent: a text_only request for such a model kept a wrapper whose forward needs pixel_values. The caller's own request now travels separately. token_type_ids is a standard tokenizer field the Trainer supplies, so a wrapper that requires it can take a text batch and is not unwrapped. * Only a field the collator supplies excuses a required forward parameter A required cache_position, use_cache, past_key_values or return_dict is not something the Trainer puts in a text batch, so a forward that demands one without a default cannot take a text batch either. * [pre-commit.ci] auto fixes from pre-commit.com hooks for more information, see https://pre-commit.ci * Trim comments * Free memory through clean_gpu_cache() in _text_trainable_core torch.cuda.empty_cache() skipped XPU and failed the shared cache dispatch test. * Gate the CUDA-only tests on the real accelerator probe, not the spoofable torch.cuda check * Drop the duplicate inspect import in vision.py * Trim comments * Drop the packed_seq_lengths gate: unslothai#11468's _forward_accepts_packing_kwargs already refuses every shape it does * Append text_intent after the existing from_pretrained parameters so their positions do not move * Carry the wrapper dtype and repo path onto a text core, engage the cast shim for quantization_config loads, refuse merged saves of a text core * [pre-commit.ci] auto fixes from pre-commit.com hooks for more information, see https://pre-commit.ci * Limit the cast shim to bitsandbytes, carry the wrapper generation_config to the text core, accept every adapter save spelling * Refuse only PEFT merges of a text core: a full finetune saves its resident weights * Refuse a full-finetuned text core's merged save when its class exists only in remote code * Move the text-core save refusal into a helper: unsloth_generic_save forwards its locals() as keywords, which broke every push_to_hub_merged --------- Co-authored-by: pre-commit-ci[bot] <66853113+pre-commit-ci[bot]@users.noreply.github.com>
…oRA, run the root dispatch hook on the embedding's device (Nemotron-Labs-Teacher) (unslothai#11543) * Let a remote-code from_pretrained cast a 4-bit model's unquantized floats microsoft/Phi-4-reasoning-vision-15B overrides from_pretrained and ends it with model.to(dtype), where dtype falls back to the model's own dtype. transformers refuses every dtype cast on a bitsandbytes model, so the 4-bit load stopped with "You cannot cast a bitsandbytes model in a new dtype" while the 16-bit load was fine. For the duration of Unsloth's own from_pretrained call, and only when the model is loaded with trust_remote_code in 4-bit or 8-bit, PreTrainedModel.to casts the floating tensors that are not packed bitsandbytes weights (Params4bit with a quant_state, Int8Params with an SCB) and leaves the packed weights alone. Device moves and unquantized models keep transformers' own path, and the original method is restored when the load returns. * Keep padding-free off a forward that cannot take packed_seq_lengths, and let a wrapper inherit gradient checkpointing support Padding-free batching adds packed_seq_lengths to every batch. A remote-code forward with a fixed signature (microsoft/Phi-4-reasoning-vision-15B) raised "got an unexpected keyword argument 'packed_seq_lengths'" on the first step after the 4-bit load was fixed. Auto padding-free and packing now stay off when the model's forward, looked through PEFT, accepts neither that key nor **kwargs; a string model or an unreadable signature leaves the decision as it was. nvidia/Nemotron-3-Nano-Omni-30B-A3B wraps a complete NemotronHForCausalLM in a PreTrainedModel that keeps transformers' default supports_gradient_checkpointing = False, so Trainer's gradient_checkpointing_enable raised "does not support gradient checkpointing" although every layer underneath supports it. After the load, a wrapper that says no while a nested model says yes now says yes on the instance; transformers enables checkpointing by walking modules, so every layer is switched on as before. * Train the language model of a wrapper whose forward cannot take a text batch nvidia/Nemotron-3-Nano-Omni-30B-A3B wraps a complete NemotronHForCausalLM as language_model behind a forward whose first parameter, pixel_values, has no default and whose body indexes image_flags. A text-only SFT batch stopped on the first step with "missing 1 required positional argument: 'pixel_values'" once the load, the LoRA targets and the trainer setup were fixed. After the load, a wrapper whose forward requires an input that a text batch does not carry, with exactly one direct child that is a PreTrainedModel with its own forward and both embedding accessors (language_model or thinker when several qualify), hands training to that child, and the generation-time siblings are dropped so their weights are freed. Every transformers VLM defaults its image inputs to None and is returned unchanged, as is anything ambiguous. UNSLOTH_KEEP_COMPOSED_WRAPPER=1 turns this off. * Recognise gradient checkpointing support from transformers' checkpointing layer NemotronHForCausalLM's remote code builds every NemotronHBlock on transformers' GradientCheckpointingLayer but never sets supports_gradient_checkpointing on the model class, so Trainer's gradient_checkpointing_enable raised "NemotronHForCausalLM does not support gradient checkpointing" once training reached it. A model built on that layer now counts as supporting it, alongside a nested model that says so itself. * [pre-commit.ci] auto fixes from pre-commit.com hooks for more information, see https://pre-commit.ci * [pre-commit.ci] auto fixes from pre-commit.com hooks for more information, see https://pre-commit.ci * Carry the wrapper's loader state onto the core that replaces it from_pretrained records is_loaded_in_4bit, is_quantized, quantization_method, hf_quantizer and hf_device_map on the object it returns, not on its children. PEFT reads is_loaded_in_4bit off the model it is given to pick lora.bnb.Linear4bit over the plain lora.Linear, so a core returned without the flags trained through the wrong LoRA layer: the forward ran, but merging wrote a 16-bit delta into packed 4-bit weights and the fast QLoRA path was skipped. The flags now move to the core, the device map is re-keyed from the wrapper's names to the core's, and the wrapper config's quantization_config is carried so a saved core still says it is 4-bit. Tests: the carried state on a synthetic wrapper, no state invented when the wrapper has none, and PEFT dispatching Linear4bit on a real 4-bit core; the last two fail on the branch before this commit. * Keep the composed wrapper when the load asked for the multimodal model Unwrapping a wrapper whose forward requires pixel_values was unconditional, so a FastVisionModel load of Nemotron-Omni meant for image batches lost its vision tower at load and trained the text core. The unwrap now runs only when the load carries text intent: text_only = True, or a model with no vision config. A multimodal load keeps the wrapper and prints the text_only hint, and the UNSLOTH_KEEP_COMPOSED_WRAPPER opt-out is unchanged. The two new test files also get the SPDX line the other tests carry. Test: text_intent = False returns the wrapper with its vision tower and names text_only = True; a wrapper that takes a text batch prints nothing. * Keep an unquantized keyword cast inside the tolerated load, and read the bound forward for the packing gate _tolerate_dtype_cast_on_quantized_model popped dtype out of kwargs and then, on an ordinary model, handed the call on without it, so model.to(dtype = ...) made inside a remote-code from_pretrained was a silent no-op: the model stayed float32. The pass-through now forwards the call exactly as it arrived. _forward_accepts_packed_seq_lengths read type(model).forward, which on an nn.Module is never absent (it falls back to _forward_unimplemented, whose signature takes no keywords), so a torch.compile'd model, which sets forward on the instance, was read as a fixed signature and padding-free was switched off for every compiled model. It now reads the bound forward first, as the merged _forward_accepts_packing_kwargs does. Tests: the three cast spellings on an unquantized model inside the context, a compiled kwargs forward keeps padding-free, and the fixed-signature control. Three fail on the previous commit. * Unwrap a remote-code composition only when the caller asks for text training The gate keyed off the wrapper's vision_config, which an audio-only composition does not have either, so a multimodal load still lost its wrapper. Only the caller knows the intent: unwrap on text_only = True and keep the composition whole otherwise. * Carry the caller's text intent past the loader's normalisation, and count token_type_ids as text loader.py turns text_only off for a family without its own text decoder so the full wrapper loads, and forwarded that normalised value as the intent: a text_only request for such a model kept a wrapper whose forward needs pixel_values. The caller's own request now travels separately. token_type_ids is a standard tokenizer field the Trainer supplies, so a wrapper that requires it can take a text batch and is not unwrapped. * Only a field the collator supplies excuses a required forward parameter A required cache_position, use_cache, past_key_values or return_dict is not something the Trainer puts in a text batch, so a forward that demands one without a default cannot take a text batch either. * Resolve remote-code model classes and reach per-expert submodules with LoRA A remote config that reuses a native class name (NemotronHConfig on the Nemotron-H hub checkpoints) resolved to the native model class through the name-keyed auto mapping, so the attention implementation was chosen from the flags of a class that is never built. The remote class only carries the old _supports_flash_attn_2 flag, which transformers 5 no longer dispatches on, and the load stopped with "does not support Flash Attention 2 yet". resolve_model_class now returns the class transformers instantiates for a remote config (auto_map entry plus a config class from transformers_modules), and flash support is read from the flag the installed transformers dispatches on. Routed experts kept as per-expert submodules (mixer.experts.<i>.up_proj) were silently left frozen on standalone text models: the regex FastModel builds only reaches a leaf directly under the block, while the same layout inside a vision-language wrapper matched through the language tag. The nested alternative is added when the requested MLP leaves exist inside experts and the regex does not already reach them. * Give the flash fixtures the flag transformers dispatches on, keep the nested-expert test off a stubbed peft_utils * Run the root dispatch hook where the input embedding lives accelerate picks the root execution device as the first member of the set of devices in the map, so a plan that keeps the embedding off that device sends every batch there first; the embedding hook then carries input_ids on while attention_mask and labels stay behind. Modeling code that builds its own mask on the embedding's device (the transformers 4.4x _update_causal_mask the Nemotron-H hub checkpoints ship) fails with "Expected all tensors to be on the same device". Native transformers moves the mask itself, which kept the extra hop invisible. Aligning the root with the embedding also drops both copies from every batch. * Fetch a missing remote modeling module with the load's own hub options When only the configuration module is materialised, the resolver asked get_class_from_dynamic_module for the repository's default revision with no token, cache directory or offline flag, so a load pinned to a revision or a code_revision could read another revision's flags and local_files_only = True could reach the network. The loader now passes revision, code_revision, token, cache_dir and local_files_only through, and a other/repo--module.Class reference no longer consults a same-named module next to the config, which belongs to a different repository. Tests: the fetch receives exactly the load's options; a cross-repository reference resolves in the other repository. Both fail on the previous commit. * Add the SPDX line the other test files carry * Widen only a generated target regex to the routed experts, and fetch a cross-repository auto_map class by its full reference A regex the caller wrote, such as one naming the shared expert alone, is their scope: widening it attached an adapter to every routed expert in every layer. The nested-expert alternative is now added only to the regex get_peft_regex built. A class reference of the form other/repo--module.Class is handed to get_class_from_dynamic_module unsplit with the model's own repo_id, which is how transformers resolves it, instead of splitting off the module and asking for a sibling file that the model repository does not have. * Do not widen onto the routed experts when the language layers are out of scope The experts live in the language model, so a vision-only request (finetune_language_layers = False) whose generated regex still names the MLP leaves must not gain the nested-expert alternative. * Keep gate and up expert leaves separate, and read the installed flash dispatch check A request for gate_proj alone no longer collects up_proj leaves (and the reverse); only the fused gate_up_proj spelling asks for both. transformers 5.0 to 5.3 still accept the legacy _supports_flash_attn_2 flag in the dispatch check, so the helper reads that function instead of inferring the answer from the presence of the new base-class attribute. * [pre-commit.ci] auto fixes from pre-commit.com hooks for more information, see https://pre-commit.ci * [pre-commit.ci] auto fixes from pre-commit.com hooks for more information, see https://pre-commit.ci * Honour trust_remote_code and force_download when resolving a remote model class A materialised remote config handed in with trust_remote_code = False no longer has its modeling module imported before transformers can refuse the load, and a forced download goes through transformers instead of returning an already imported sibling that is about to be replaced. * [pre-commit.ci] auto fixes from pre-commit.com hooks for more information, see https://pre-commit.ci * Forward the trust decision to every remote class probe in the loader The probes that pick the auto class did not pass trust_remote_code, so a materialised remote config could have its modeling module imported before transformers refused the load. * [pre-commit.ci] auto fixes from pre-commit.com hooks for more information, see https://pre-commit.ci * Forward trust, revision, token and offline options to every remote class probe * Ask transformers for the class when a code_revision is set instead of reusing the config's sibling module * Gate the legacy flash flag tests on the installed dispatch check, not on attribute presence * Trim comments * Trim comments * Widen generated LoRA targets to per-expert submodules only for remote code On transformers 4.x native per-expert layouts (Qwen3-MoE, Qwen2-MoE, OLMoE, DeepSeek-V3) nest experts the same way, and widening gave every routed expert LoRA: a Qwen3-30B-A3B shape went from 240 to 18,672 targets, +830M LoRA parameters at r=16. Only MoE blocks whose expert classes come from the checkpoint's own code are widened now. Also: the legacy-flash test fails on a reverted tree without flash-attn, _text_trainable_core frees memory through clean_gpu_cache(), and unslothai#11526's comments are kept as they are there. * Free memory through clean_gpu_cache() in _text_trainable_core torch.cuda.empty_cache() skipped XPU and failed the shared cache dispatch test. * Scope expert widening to the remote experts' parents and the root hook to remote text models The widened alternative now names the parent paths of the remote expert blocks instead of any parent, so a native expert tower next to remote code keeps its targets. The root dispatch hook is only moved for remote-code models without a vision or audio sub-config: the hook moves every input, and native code moves the mask itself. * Give the sentence-transformer class probes the load's options, and fetch only for trusted loads resolve_encoder_attention_implementation and _has_add_pooling_layer now pass FastSentenceTransformer.from_pretrained's trust_remote_code, revision, token, cache folder and local_files_only to the remote-class resolver, so a pinned or offline encoder is inspected with the code it loads. A probe that did not ask for remote code may reuse an imported sibling module but never fetches. * Skip the imported sibling module when the load names a revision transformers uses revision as the code revision for same-repo code, so a config loaded from one revision and a model loaded with another would be inspected with the wrong modeling class. * Forward the load's proxies to every remote-class probe * Gate the CUDA-only tests on the real accelerator probe, not the spoofable torch.cuda check * Gate the CUDA-only tests on the real accelerator probe, not the spoofable torch.cuda check * Reuse the gated revision for the class probes, and give the text-only test the remote class helper * Drop the duplicate inspect import in vision.py * Trim comments * Trim comments * Drop the packed_seq_lengths gate: unslothai#11468's _forward_accepts_packing_kwargs already refuses every shape it does * Append text_intent after the existing from_pretrained parameters so their positions do not move * [pre-commit.ci] auto fixes from pre-commit.com hooks for more information, see https://pre-commit.ci * Carry the wrapper dtype and repo path onto a text core, engage the cast shim for quantization_config loads, refuse merged saves of a text core * [pre-commit.ci] auto fixes from pre-commit.com hooks for more information, see https://pre-commit.ci * [pre-commit.ci] auto fixes from pre-commit.com hooks for more information, see https://pre-commit.ci * Limit the cast shim to bitsandbytes, carry the wrapper generation_config to the text core, accept every adapter save spelling * Leave omni configs with towers under thinker_config out of the root hook alignment * Refuse only PEFT merges of a text core: a full finetune saves its resident weights * Leave towers spelled vision_encoder_config / audio_encoder_config / encoder_config out of the root hook alignment * Refuse a full-finetuned text core's merged save when its class exists only in remote code * Move the text-core save refusal into a helper: unsloth_generic_save forwards its locals() as keywords, which broke every push_to_hub_merged --------- Co-authored-by: pre-commit-ci[bot] <66853113+pre-commit-ci[bot]@users.noreply.github.com>
…mni) (unslothai#11523) * Let a remote-code from_pretrained cast a 4-bit model's unquantized floats microsoft/Phi-4-reasoning-vision-15B overrides from_pretrained and ends it with model.to(dtype), where dtype falls back to the model's own dtype. transformers refuses every dtype cast on a bitsandbytes model, so the 4-bit load stopped with "You cannot cast a bitsandbytes model in a new dtype" while the 16-bit load was fine. For the duration of Unsloth's own from_pretrained call, and only when the model is loaded with trust_remote_code in 4-bit or 8-bit, PreTrainedModel.to casts the floating tensors that are not packed bitsandbytes weights (Params4bit with a quant_state, Int8Params with an SCB) and leaves the packed weights alone. Device moves and unquantized models keep transformers' own path, and the original method is restored when the load returns. * Keep padding-free off a forward that cannot take packed_seq_lengths, and let a wrapper inherit gradient checkpointing support Padding-free batching adds packed_seq_lengths to every batch. A remote-code forward with a fixed signature (microsoft/Phi-4-reasoning-vision-15B) raised "got an unexpected keyword argument 'packed_seq_lengths'" on the first step after the 4-bit load was fixed. Auto padding-free and packing now stay off when the model's forward, looked through PEFT, accepts neither that key nor **kwargs; a string model or an unreadable signature leaves the decision as it was. nvidia/Nemotron-3-Nano-Omni-30B-A3B wraps a complete NemotronHForCausalLM in a PreTrainedModel that keeps transformers' default supports_gradient_checkpointing = False, so Trainer's gradient_checkpointing_enable raised "does not support gradient checkpointing" although every layer underneath supports it. After the load, a wrapper that says no while a nested model says yes now says yes on the instance; transformers enables checkpointing by walking modules, so every layer is switched on as before. * Train the language model of a wrapper whose forward cannot take a text batch nvidia/Nemotron-3-Nano-Omni-30B-A3B wraps a complete NemotronHForCausalLM as language_model behind a forward whose first parameter, pixel_values, has no default and whose body indexes image_flags. A text-only SFT batch stopped on the first step with "missing 1 required positional argument: 'pixel_values'" once the load, the LoRA targets and the trainer setup were fixed. After the load, a wrapper whose forward requires an input that a text batch does not carry, with exactly one direct child that is a PreTrainedModel with its own forward and both embedding accessors (language_model or thinker when several qualify), hands training to that child, and the generation-time siblings are dropped so their weights are freed. Every transformers VLM defaults its image inputs to None and is returned unchanged, as is anything ambiguous. UNSLOTH_KEEP_COMPOSED_WRAPPER=1 turns this off. * Recognise gradient checkpointing support from transformers' checkpointing layer NemotronHForCausalLM's remote code builds every NemotronHBlock on transformers' GradientCheckpointingLayer but never sets supports_gradient_checkpointing on the model class, so Trainer's gradient_checkpointing_enable raised "NemotronHForCausalLM does not support gradient checkpointing" once training reached it. A model built on that layer now counts as supporting it, alongside a nested model that says so itself. * [pre-commit.ci] auto fixes from pre-commit.com hooks for more information, see https://pre-commit.ci * [pre-commit.ci] auto fixes from pre-commit.com hooks for more information, see https://pre-commit.ci * Carry the wrapper's loader state onto the core that replaces it from_pretrained records is_loaded_in_4bit, is_quantized, quantization_method, hf_quantizer and hf_device_map on the object it returns, not on its children. PEFT reads is_loaded_in_4bit off the model it is given to pick lora.bnb.Linear4bit over the plain lora.Linear, so a core returned without the flags trained through the wrong LoRA layer: the forward ran, but merging wrote a 16-bit delta into packed 4-bit weights and the fast QLoRA path was skipped. The flags now move to the core, the device map is re-keyed from the wrapper's names to the core's, and the wrapper config's quantization_config is carried so a saved core still says it is 4-bit. Tests: the carried state on a synthetic wrapper, no state invented when the wrapper has none, and PEFT dispatching Linear4bit on a real 4-bit core; the last two fail on the branch before this commit. * Keep the composed wrapper when the load asked for the multimodal model Unwrapping a wrapper whose forward requires pixel_values was unconditional, so a FastVisionModel load of Nemotron-Omni meant for image batches lost its vision tower at load and trained the text core. The unwrap now runs only when the load carries text intent: text_only = True, or a model with no vision config. A multimodal load keeps the wrapper and prints the text_only hint, and the UNSLOTH_KEEP_COMPOSED_WRAPPER opt-out is unchanged. The two new test files also get the SPDX line the other tests carry. Test: text_intent = False returns the wrapper with its vision tower and names text_only = True; a wrapper that takes a text batch prints nothing. * Keep an unquantized keyword cast inside the tolerated load, and read the bound forward for the packing gate _tolerate_dtype_cast_on_quantized_model popped dtype out of kwargs and then, on an ordinary model, handed the call on without it, so model.to(dtype = ...) made inside a remote-code from_pretrained was a silent no-op: the model stayed float32. The pass-through now forwards the call exactly as it arrived. _forward_accepts_packed_seq_lengths read type(model).forward, which on an nn.Module is never absent (it falls back to _forward_unimplemented, whose signature takes no keywords), so a torch.compile'd model, which sets forward on the instance, was read as a fixed signature and padding-free was switched off for every compiled model. It now reads the bound forward first, as the merged _forward_accepts_packing_kwargs does. Tests: the three cast spellings on an unquantized model inside the context, a compiled kwargs forward keeps padding-free, and the fixed-signature control. Three fail on the previous commit. * Unwrap a remote-code composition only when the caller asks for text training The gate keyed off the wrapper's vision_config, which an audio-only composition does not have either, so a multimodal load still lost its wrapper. Only the caller knows the intent: unwrap on text_only = True and keep the composition whole otherwise. * Carry the caller's text intent past the loader's normalisation, and count token_type_ids as text loader.py turns text_only off for a family without its own text decoder so the full wrapper loads, and forwarded that normalised value as the intent: a text_only request for such a model kept a wrapper whose forward needs pixel_values. The caller's own request now travels separately. token_type_ids is a standard tokenizer field the Trainer supplies, so a wrapper that requires it can take a text batch and is not unwrapped. * Only a field the collator supplies excuses a required forward parameter A required cache_position, use_cache, past_key_values or return_dict is not something the Trainer puts in a text batch, so a forward that demands one without a default cannot take a text batch either. * Hand a composition with no forward of its own to its thinker Qwen3OmniMoeForConditionalGeneration composes a thinker, a talker and a speech decoder and only generates, so a trainer's forward reached nn.Module.forward. The text-core handoff now treats a wrapper with no forward the same as one whose forward cannot take a text batch. * Hand over a composition with no forward regardless of load intent The multimodal gate keeps a wrapper whose forward takes image batches; a composition with no forward trains nothing on any batch, so it always goes to its thinker. Test added. * Add the SPDX line the other test files carry * Keep the composition whole on a multimodal load A load without text intent may still generate through the wrapper, and Qwen3-Omni does that with its talker and speech decoder, so the handoff to the thinker now happens only when the load asked for the text model. The multimodal load prints the text_only hint instead. Test updated. * [pre-commit.ci] auto fixes from pre-commit.com hooks for more information, see https://pre-commit.ci * [pre-commit.ci] auto fixes from pre-commit.com hooks for more information, see https://pre-commit.ci * [pre-commit.ci] auto fixes from pre-commit.com hooks for more information, see https://pre-commit.ci * [pre-commit.ci] auto fixes from pre-commit.com hooks for more information, see https://pre-commit.ci * Carry the checkpoint identity onto the thinker PEFT copies name_or_path into the adapter's base_model_name_or_path, and a thinker built from thinker_config has none, so a saved adapter pointed at an empty base model. The wrapper's name is carried over with the loader state. * [pre-commit.ci] auto fixes from pre-commit.com hooks for more information, see https://pre-commit.ci * Find a thinker by its lm_head when its output accessor says None transformers 4.x returns None from get_output_embeddings unless a class overrides it, and Qwen3-Omni's thinker only overrides the input side. * [pre-commit.ci] auto fixes from pre-commit.com hooks for more information, see https://pre-commit.ci * Trim comments * Trim comments * Free memory through clean_gpu_cache() in _text_trainable_core torch.cuda.empty_cache() skipped XPU and failed the shared cache dispatch test. * Load Qwen3-Omni with text_only, and give a kept wrapper a text forward text_only = True sent Qwen3-Omni to AutoModelForCausalLM because its vision config sits under thinker_config, so the hint the multimodal load prints pointed at a path that raised "Unrecognized configuration class". It now loads through the composition's own auto class and the text intent hands it to the thinker, as the hint says. A default load keeps the wrapper for audio generation. It now takes the thinker's forward and embedding accessors on the instance, so eval, KD and a custom loop can call model(input_ids = ...), and get_peft_model scopes LoRA to thinker.model instead of only the vision tower. A thinker built from a sub-config also gets its architectures, which generate reads. * Reload a thinker-only Qwen3-Omni adapter onto the thinker An adapter trained with text_only = True has targets and weights rooted at model.layers, which a default reload of the composition names thinker.model.layers, so PEFT found no targets. Unsloth's target regex for a kept wrapper names thinker.model; one trained on the thinker alone never names thinker, so an Omni base reloaded for such an adapter loads as text_only. * [pre-commit.ci] auto fixes from pre-commit.com hooks for more information, see https://pre-commit.ci * Decide a Qwen3-Omni adapter's reload target from its saved weight keys A leaf-name list such as ["q_proj", "v_proj"] reloads as a set that matches either layout, so the regex alone could not tell a thinker-trained adapter from a wrapper-trained one. Read the tensor names from the adapter's safetensors header (locally, or the Hub metadata): thinker-trained keys never contain thinker., wrapper-trained keys always do. The regex check stays as the fallback when the keys cannot be read. * [pre-commit.ci] auto fixes from pre-commit.com hooks for more information, see https://pre-commit.ci * Read a Hub adapter's keys from adapter_model.safetensors get_safetensors_metadata only looks for model.safetensors, so every Hub adapter raised NotASafetensorsRepoError and fell back to the regex. Read the header of adapter_model.safetensors by name instead, and read a local adapter_model.bin's keys on the meta device. * [pre-commit.ci] auto fixes from pre-commit.com hooks for more information, see https://pre-commit.ci * Keep audio-only Omni adapters on the wrapper, and read cached adapters offline Decide from the first key segment after base_model.model.: a key rooted at any of the composition's children (thinker, talker, code2wav, from its sub-configs) means the adapter was trained on the kept wrapper, so an audio-only adapter is no longer mistaken for a thinker one. Look in the Hub cache before the network, so local_files_only still reads the saved keys. * [pre-commit.ci] auto fixes from pre-commit.com hooks for more information, see https://pre-commit.ci * Resolve an Omni adapter's weight file with hf_hub_download, either format PEFT fetches the same file right after, so resolve adapter_model.safetensors and then adapter_model.bin through hf_hub_download (cache first, offline honoured) and read their names without materialising weights. When no file can be read and the targets are a leaf list, say how to load a thinker-only adapter instead of guessing. * [pre-commit.ci] auto fixes from pre-commit.com hooks for more information, see https://pre-commit.ci * Gate the CUDA-only tests on the real accelerator probe, not the spoofable torch.cuda check * Gate the CUDA-only tests on the real accelerator probe, not the spoofable torch.cuda check * Drop the duplicate inspect import in vision.py * Trim comments * Trim comments * Drop the packed_seq_lengths gate: unslothai#11468's _forward_accepts_packing_kwargs already refuses every shape it does * Append text_intent after the existing from_pretrained parameters so their positions do not move * Carry the wrapper dtype and repo path onto a text core, engage the cast shim for quantization_config loads, refuse merged saves of a text core * [pre-commit.ci] auto fixes from pre-commit.com hooks for more information, see https://pre-commit.ci * Redirect adapter reloads only for forward-less compositions, and target the thinker's experts on a kept wrapper * Limit the cast shim to bitsandbytes, carry the wrapper generation_config to the text core, accept every adapter save spelling * Freeze a kept wrapper's unused siblings, and read finetune_last_n_layers' layer count through the text core * Scope explicit LoRA leaves on a kept wrapper to its text core, and delegate the embedding setters so vocab resizing works * Refuse only PEFT merges of a text core: a full finetune saves its resident weights * Refuse a full-finetuned text core's merged save when its class exists only in remote code * Move the text-core save refusal into a helper: unsloth_generic_save forwards its locals() as keywords, which broke every push_to_hub_merged * Gate the Qwen3-Omni GPU tests on has_real_cuda: the CI CUDA spoof makes torch.cuda.is_available() true * On a kept wrapper, pass qualified LoRA targets to PEFT unchanged and scope modules_to_save to the text core * Forward the trust decision through the forwardless-composition probes, keep a kept wrapper's siblings frozen after full-finetuning setup, and scope explicit target_parameters to the text core --------- Co-authored-by: pre-commit-ci[bot] <66853113+pre-commit-ci[bot]@users.noreply.github.com>
Problem
Padding-free batching is turned on automatically, which hands the model
packed_seq_lengths. A model whose forward neither declares that argument noraccepts
**kwargsthen raisesTypeErroron the first step. The decision wasmade from the config alone, so there was nothing to notice the mismatch.
Fix
_forward_accepts_packing_kwargs(model)inspects the forward that willactually be called and adds one more reason to the existing
blockedexpression. A model that takes
packed_seq_lengths, or takes**kwargsandso can absorb it, is unaffected and keeps padding-free exactly as today.
The unwrapping is deliberately limited to PEFT's own
get_base_model(), atmost a few levels. Following
PreTrainedModel.base_modelas well lookedtempting and is wrong: it is a property returning the inner decoder, whose
forward usually does take
**kwargs, so the check would answer confidentlyfor the wrong module and re-enable padding-free on exactly the models it is
meant to catch.
Unknown or uninspectable cases return True, so the gate only ever turns
padding-free off where the signature positively shows it cannot work, and
never turns it on anywhere it is off today.
A string
model=is answered before the trainer is builtA name has no forward to read, so the gate fails open on it. Left there, the
mismatch surfaces only after
__init__, and by that point the only honest moveis to refuse: TRL has built its collator from the flags, and under packing it
has transformed the train and eval datasets too, so clearing the flags would
leave batches arriving flattened while nothing names the sequence boundaries.
Attention and loss would then cross example boundaries with nothing raising,
which is worse than the
TypeErrorthe gate exists to prevent.That refusal fell on users who had configured nothing, since padding-free is
auto-enabled whenever
padding_freeis left unset._resolve_string_model_classavoids it._resolve_string_model_configalreadyloads the config on this path, and the class is reachable from it without the
weights: the recorded
architecturesagainst the transformers namespace, thenthe auto mappings keyed by config class, and only if nothing native has answered,
auto_map.from_pretrainedis never called, so no checkpoint is fetched.The ordering is the security-relevant part and is deliberate. TRL's own
create_model_from_pathresolvesgetattr(transformers, config.architectures[0])and consults
auto_mapnot at all, so trying remote code first would import andexecute a module for a natively-named checkpoint that nothing else in the stack
would ever load. The
auto_mapbranch is reached only withtrust_remote_codegranted, and the grant is read by membership in
model_init_kwargsrather thanby
is None, matching_resolve_string_model_configexactly: an explicit{"trust_remote_code": None}keeps its own unresolved meaning instead of beingoverwritten by a truthy top-level attribute.
The string case is therefore an ordinary silent block like every other reason,
and the warning names the resolved class rather than
str. Resolution isbest-effort: anything unresolvable returns None. The post-init check stays armed
either way, because a checkpoint can name several classes in
auto_mapand theone resolved is not guaranteed to be the one TRL builds, so a "yes" from the
class is a good guess about the instance rather than proof of it.
Evidence
A tiny real
LlamaForCausalLMwith a narrowed forward, driven through the realpatched
trl.SFTTrainerwithpadding_freeleft at its default:__init__trainer.train()main)padding_free=TrueTypeError: NarrowForwardLlama.forward() got an unexpected keyword argument 'packed_seq_lengths'padding_free=Falsetrained OK, loss=10.3201, steps=2LlamaForCausalLMpadding_free=Truetrained OK, loss=10.4254, steps=2The last row is the one that matters: the gate does not cost a normal model its
padding-free. Measured more broadly, all 178 classes in
MODEL_FOR_CAUSAL_LM_MAPPING_NAMESand all 75 inMODEL_FOR_IMAGE_TEXT_TO_TEXT_MAPPING_NAMESaccept the argument through**kwargs: Unpack[TransformersKwargs], so the gate blocks nothing in tree. Themotivating checkpoint,
microsoft/Phi-4-reasoning-vision-15B, istrust_remote_code, which is exactly the population outside those mappings.Measured again at the version corner CI actually pins,
HF=4.57.6 + TRL<1, wherethe answer is different and worth stating: there the gate blocks 21 classes, of
which 14 are already blocked by the existing
is_encoder_decoderterm. The 7genuine deltas are crashes prevented, not padding-free lost. Proven by binding
the real signature, which is what Python does at call time:
Platform coverage
Cross-platform staging CI is running for the current head; the executed counts are
posted once it reports, rather than carried over from a run that predates these
tests.