Skip to content

Resolve remote-code model classes, reach per-expert submodules with LoRA, run the root dispatch hook on the embedding's device (Nemotron-Labs-Teacher) - #11543

Merged
danielhanchen merged 75 commits into
mainfrom
forkT-nemotron-teacher
Sep 25, 2026
Merged

danielhanchen merged 75 commits into
mainfrom
forkT-nemotron-teacher

Conversation

@danielhanchen

@danielhanchen danielhanchen commented Sep 22, 2026 •

Copy link
Copy Markdown
Member

What

nvidia/NVIDIA-Nemotron-Labs-Teacher-Instruction-Following (nemotron_h remote code, 108 layers, 512 routed experts, 1.1 TB bf16) did not load under Unsloth and, once it did, trained none of its routed experts and could not run split over three cards. Four changes, each general:

  1. resolve_model_class returns the class transformers actually builds for a remote-code config. transformers' auto mapping is keyed by config class name, so a remote NemotronHConfig resolved to the native NemotronHForCausalLM, and the attention implementation was chosen from the flags of a class that is never instantiated. The remote class is what auto_model.from_pretrained(..., trust_remote_code = True) builds: an auto_map entry for the requested auto class on a config whose class came out of transformers_modules. It is looked up from the already materialised sibling module first, then through get_class_from_dynamic_module, and everything native keeps the old resolution.

  2. Flash attention support is read from the flag the installed transformers dispatches on. The remote class only carries the 4.x era _supports_flash_attn_2 = True; _flash_attn_can_dispatch reads _supports_flash_attn (since 4.53), so Unsloth requested flash_attention_2 and transformers refused it: NemotronHForCausalLM does not support Flash Attention 2 yet. Where PreTrainedModel has _supports_flash_attn, only that flag counts; older transformers keep reading both.

  3. Per-expert submodule LoRA targets. The Teacher keeps its routed experts as mixer.experts.<i>.up_proj / down_proj (NemotronHMLP per expert, plus shared_experts). The regex FastModel.get_peft_model builds for a text-only model reaches a leaf directly under the block (layers.<n>.mixer.in_proj) and nothing deeper, so the experts were frozen with only the warning resolved no expert parameters ... The expert weights will NOT be trained. The same modeling code inside Nemotron-3-Nano-Omni trains its experts, because the language_model prefix satisfies the tagged branch of the regex. get_moe_expert_submodule_leaves finds the requested MLP leaves that live under experts.<i> or shared_experts, and the nested alternative is appended to the regex only when it does not already reach them. A caller's explicit leaf list already reaches them by suffix and is untouched.

  4. The root dispatch hook runs where the input embedding lives. accelerate picks the root execution device as the first member of the SET of devices in the map, so the plan that put the Teacher's embedding on cuda:1 (head on cuda:2, a few blocks on cuda:0) sent every batch to cuda:0 first; the embedding hook then carried input_ids on while attention_mask and labels stayed behind, and the hub _update_causal_mask raised Expected all tensors to be on the same device, but found at least two devices, cuda:1 and cuda:0. Native transformers moves the mask itself, which is what kept the extra hop invisible on every other split model. _align_root_hook_with_input_embeddings points the root hook at the embedding's device after the load. Single-device, unhooked, offloaded and meta embeddings are left alone.

Differential

Tiny random Nemotron-H Teacher (the hub modeling files, 8 layers, 8 experts), one process per arm, from a neutral directory, scripts/model_sweep/run_cell.py 4-bit recipe:

arm result
base (#11526 head) ValueError: NemotronHForCausalLM does not support Flash Attention 2 yet
+ flash flag same error: the native class was still being consulted
+ remote class resolution RuntimeError: index_add_(): self (BFloat16) and source (Float) must have the same scalar type (fixed in unslothai/unsloth-zoo#1340)
+ zoo relu2 patch PASS, 133 k trainable parameters, 0 on the experts, warning printed
+ nested expert targets PASS, 563 k trainable parameters, 430 k on the experts, same loss curve to the last digit, no warning

The real model then added two more, each reproduced and fixed on its own:

arm (real model, three B200s) result
+ all of the above RuntimeError: Expected all tensors to be on the same device, but found at least two devices, cuda:1 and cuda:0 in _update_causal_mask (root hook on cuda:0, embedding on cuda:1)
+ root hook alignment RuntimeError: expected mat1 and mat2 to have the same dtype, but got: unsigned char != c10::BFloat16 from the idle-expert path (fixed in the companion unsloth-zoo PR; reproduced on a 64-expert tiny model)
+ zoo integer-input cast (this head) trains, see below

The expert count matches what plain PEFT with a leaf list attaches on the same model (430 080).

Measurements

The real model, NF4 (out_proj kept in bf16 for the Mamba kernels), LoRA r = 16 on every projection including the 49 152 expert projections, 10 steps of 4 x 512 tokens on three B200s, this head plus the companion zoo head:

losses, steps 1 to 10 4.533, 3.722, 4.516, 3.027, 3.211, 2.105, 2.299, 2.950, 2.888, 1.793
grad norms 0.77, 0.62, 1.00, 1.00, 1.00, 0.57, 0.67, 0.71, 0.55, 0.57
trainable 5.72 B LoRA parameters, 5.67 B of them on the experts, of 284.8 B
peak memory 137.5 / 117.5 / 156.4 GB
load 382 s; a step (4 micro-batches through the 512-expert per-expert loop) 250 to 273 s after the first

The 16-bit cell needs 1.1 TB of weights and does not fit three cards; the HF + bitsandbytes baseline stops in the Mamba fused kernel because plain BitsAndBytesConfig quantizes out_proj (mat1 and mat2 shapes cannot be multiplied (512x256 and 1x32768)), which is the same reason Unsloth skips that module for nemotron_h.

Tests

tests/test_root_hook_follows_input_embedding.py: the root moves to the embedding's device (int, torch.device and string forms), stays when already there, and single-device, unhooked, offloaded, meta and accessor-less models are untouched; all fail on base. tests/test_remote_code_class_and_expert_submodules.py: the flash flag on old and new class layouts, the resolver never requesting flash for an old-flag remote class, a remote config whose class name collides with LlamaConfig resolving to the remote model class while native configs and remote configs without an auto class entry stay native, and the nested expert leaves and regex on a Nemotron-H shaped module tree (routed and shared experts reached, the Parameter router and the nn.Identity latent placeholder not, block-level leaves kept). 10 of 13 fail on the base branch. Two existing flash fixtures gained the _supports_flash_attn flag they were standing in for. 255 tests pass across the neighbouring attention, MoE target, class resolution and dispatch-hook files.

Compatibility

Pure Python over class attributes and config fields. transformers 4.57.6 and 5.x (both dispatch flash on _supports_flash_attn; the old-flag path is kept for anything older), TRL 0.22.2 and 1.x, PEFT 0.18 to 0.21, torch 2.6 and later, Linux, macOS, Windows and WSL. Only MoE blocks whose expert classes come from the checkpoint's own code are widened, so native per-expert layouts (Qwen3-MoE, Qwen2-MoE, OLMoE and DeepSeek-V3 on transformers 4.57.6) and models that already reached their experts, or have none, build the same regex as before: a Qwen3-30B-A3B shape on 4.57.6 keeps its 240 targets.

Built on #11526 (Fork N's Nemotron and Phi-4 fixes); companion unsloth-zoo PR: unslothai/unsloth-zoo#1340 (relu2 dtype under autocast and the integer-input cast on 4-bit LoRA layers).

danielhanchen and others added 9 commits September 22, 2026 11:08
…oats

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.
…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.
…t 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.
…ting 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.
main reworked the branch that names why packing was ignored so a string
`model=` reports the resolved class instead of `str`, while this branch
had rewritten the same elif around forward_takes_packed_seq_lengths.

`blocked` tests both conditions, so naming only one lets the other fall
through to the UNSLOTH_RETURN_LOGITS branch and point at a flag nobody
set. The resolved branch fires on either and keeps main's blocker name.
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.
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.
@chatgpt-codex-connector

chatgpt-codex-connector Bot commented Sep 22, 2026 •

Copy link
Copy Markdown

Codex Review Summary

This comment shows the latest Codex review activity on this pull request.

Review Status Commit Review trigger
📝 Code Review ⚠️ Failed 2026-09-25T19:59:15.027191Z 2e86838 New commits
ℹ️ 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" or "@codex security review".

Codex reacts with 👀 while any review is running, comments if it has suggestions, and reacts with 👍 once all reviews finish with no findings.

chatgpt-codex-connector[bot]

This comment was marked as resolved.

@unslothai unslothai deleted a comment from chatgpt-codex-connector Bot Sep 22, 2026
@danielhanchen

Copy link
Copy Markdown
Member Author

@codex security review

@danielhanchen
danielhanchen force-pushed the forkT-nemotron-teacher branch 2 times, most recently from 06137c8 to 1c9dea0 Compare September 22, 2026 15:08
chatgpt-codex-connector[bot]

This comment was marked as resolved.

…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.
…raining

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.
chatgpt-codex-connector[bot]

This comment was marked as resolved.

…ount 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.
chatgpt-codex-connector[bot]

This comment was marked as resolved.

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.
…h 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.
… nested-expert test off a stubbed peft_utils
@unslothai unslothai deleted a comment from chatgpt-codex-connector Bot Sep 25, 2026
@danielhanchen

Copy link
Copy Markdown
Member Author

@codex review

@chatgpt-codex-connector chatgpt-codex-connector Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

💡 Codex Review

Here are some automated review suggestions for this pull request.

Reviewed commit: 00a5057d29

ℹ️ 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".

# Remote-class probes must use this load's trust, revision and hub options.
_remote_class_probe_kwargs = dict(
trust_remote_code = trust_remote_code,
revision = revision,

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 Badge Load the probe config from the pinned revision

For a remote-code SentenceTransformer loaded with a non-default revision, this passes the pin to the dynamic model-class resolver, but the config supplied to that resolver is later fetched at lines 1550-1552 without revision or the other Hub options. If the pinned revision and default branch have different auto_map entries or config classes, the probe combines the default config with code from the pinned revision and can select the wrong attention implementation or add_pooling_layer behavior, while SentenceTransformer subsequently loads the actual pinned config. Fetch the probe config using the same options as this dictionary.

Useful? React with 👍 / 👎.

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Not changing: this only diverges when a repo's auto_map or config class differs between the pinned revision and the default branch; the resolver already receives the pin, and SentenceTransformer loads the pinned config itself.

Comment thread unsloth/models/_utils.py
Comment on lines +1149 to +1150
if not str(getattr(type(config), "__module__", "")).startswith("transformers_modules"):
return None

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P1 Badge Resolve auto_map classes for native config types

When a repository uses a standard Transformers config such as LlamaConfig but supplies a custom model through auto_map, AutoModel.from_pretrained(..., trust_remote_code=True) still instantiates that remote class. This check rejects it solely because the config class lives under transformers.models, so the resolver falls back to the native model class and can select unsupported attention settings (including Flash Attention), causing the subsequent remote-model load to fail. With trust enabled, the auto_map entry should be resolved even when the config class itself is native.

Useful? React with 👍 / 👎.

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Not changing, by design: only configs materialised from transformers_modules are widened, so every native config class keeps exactly the resolution it had on main (no regression for LlamaConfig-based remote repos).

Comment thread unsloth/models/_utils.py
if not auto_regex or not isinstance(target_modules, str):
return target_modules, detect_targets, []
# Remote expert blocks only: widening native ones (Qwen3-MoE on 4.x) LoRAs every routed expert.
parents = _remote_expert_parents(model)

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 Badge Preserve modality filters when widening expert targets

For a remote multimodal MoE containing remote-code experts in both its language and vision/audio towers, this collects every remote expert parent without considering the modality constraints encoded in the generated target regex. If language tuning is enabled but finetune_vision_layers=False or finetune_audio_layers=False, and the generated regex misses the nested expert layout, the appended alternative consequently attaches LoRA to the disabled tower's experts as well, unexpectedly training parameters the caller excluded. Restrict the collected parents to the modalities selected by the original generated regex.

Useful? React with 👍 / 👎.

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Not changing: this needs remote-code experts inside a vision or audio tower; the MoE models this targets (Nemotron-H Teacher, Nemotron-3-Nano-Omni) keep their experts in the language model only.

Comment thread unsloth/models/_utils.py
Comment on lines +5116 to +5119
parent = name[: matched.start()]
parents.add(
r"\.".join(r"\d+" if part.isdigit() else re.escape(part) for part in parent.split("."))
)

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 Badge Match expert containers attached at the model root

For a remote MoE whose experts or shared_experts container is attached directly to the top-level model, parent is the empty string and this constructs an empty parent alternative followed by a mandatory escaped dot. The resulting regex expects names such as .experts.0.up_proj, while named_modules() yields experts.0.up_proj, so no expert adapter is attached despite the preceding detection message. Build the separator conditionally when the matched expert block has no parent.

Useful? React with 👍 / 👎.

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Not changing: no MoE attaches its experts or shared_experts container directly to the model root; they live under a decoder layer, which is what the nested alternative matches.

@danielhanchen

Copy link
Copy Markdown
Member Author

@codex review

@chatgpt-codex-connector chatgpt-codex-connector Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

💡 Codex Review

Here are some automated review suggestions for this pull request.

Reviewed commit: 0a8d798329

ℹ️ 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".

Comment on lines +1453 to +1457
revision = revision,
token = token,
cache_dir = kwargs.get("cache_folder", kwargs.get("cache_dir", None)),
local_files_only = kwargs.get("local_files_only", None),
proxies = kwargs.get("proxies", None),

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 Badge Forward code_revision to the remote-class probes

When a fallback SentenceTransformer load specifies trust_remote_code=True with a distinct code_revision, that option remains in kwargs and is forwarded to FastModel.from_pretrained, but this probe dictionary omits it. The resolver therefore reuses or fetches the model class from revision/the default branch while the actual load builds the class from code_revision; if those class constructors differ, _has_add_pooling_layer can inject an unsupported add_pooling_layer argument or omit a required override. Include code_revision = kwargs.get("code_revision") so the probe inspects the class that will actually be loaded.

Useful? React with 👍 / 👎.

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Not changing: this needs a code_revision whose remote class constructor differs from the one at revision in its add_pooling_layer handling; the probe already follows the pinned revision and trust decision.

@unslothai unslothai deleted a comment from chatgpt-codex-connector Bot Sep 25, 2026
@chatgpt-codex-connector

Copy link
Copy Markdown

Codex Review: Didn't find any major issues. Bravo.

Reviewed commit: c37559936b

ℹ️ 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".

chatgpt-codex-connector[bot]

This comment was marked as resolved.

@unslothai unslothai deleted a comment from chatgpt-codex-connector Bot Sep 25, 2026
@danielhanchen

Copy link
Copy Markdown
Member Author

@codex review

@chatgpt-codex-connector

Copy link
Copy Markdown

Codex Review: Didn't find any major issues. Another round soon, please!

Reviewed commit: c0d13f4916

ℹ️ 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".

@danielhanchen
danielhanchen changed the base branch from phi4-vision-4bit-cast to main September 25, 2026 19:16
@danielhanchen
danielhanchen merged commit 98fc7fe into main Sep 25, 2026
32 of 35 checks passed
@danielhanchen
danielhanchen deleted the forkT-nemotron-teacher branch September 25, 2026 19:59
shaojun pushed a commit to shaojun/unsloth that referenced this pull request Sep 29, 2026
…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>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant