Skip to content

Load and train remote-code multimodal wrappers: Phi-4-reasoning-vision in 4-bit and Nemotron-3-Nano-Omni - #11526

Merged
danielhanchen merged 32 commits into
mainfrom
phi4-vision-4bit-cast
Sep 25, 2026
Merged

danielhanchen merged 32 commits into
mainfrom
phi4-vision-4bit-cast

Conversation

@danielhanchen

@danielhanchen danielhanchen commented Sep 22, 2026 •

Copy link
Copy Markdown
Member

What

Four changes on the load-time and trainer-side path of remote-code multimodal models, surfaced in order by microsoft/Phi-4-reasoning-vision-15B in 4-bit and by nvidia/Nemotron-3-Nano-Omni-30B-A3B-Reasoning-BF16. Each is general and none names a repo.

1. A remote from_pretrained may cast a 4-bit model's unquantized floats

Phi-4-reasoning-vision 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.

2. Padding-free on a forward that cannot take packed_seq_lengths (already on main)

Phi-4's fixed-signature forward raised got an unexpected keyword argument 'packed_seq_lengths' on the first step. #11468 (_forward_accepts_packing_kwargs) already keeps auto padding-free and packing off for that shape on main, and refuses every shape this PR's own gate refused, so that gate was dropped; its tests now pin #11468's gate on the Phi-4 shape.

3. A wrapper whose forward cannot take a text batch trains its language model

Nemotron-Omni 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 died with missing 1 required positional argument: 'pixel_values'. After the load, a wrapper whose forward requires an input 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 it off. A LoRA adapter saved from the language model reloads with text_only = True. A merged save of it is refused with a message pointing at the adapter save, because the merge re-reads the repo's shards, which hold the wrapper's layout.

4 and 5. Gradient checkpointing support is recognised where the class forgot to advertise it

The Omni wrapper keeps transformers' default supports_gradient_checkpointing = False around a model that supports it, and NemotronHForCausalLM itself builds every block on transformers' GradientCheckpointingLayer but never sets the flag, so Trainer's gradient_checkpointing_enable raised does not support gradient checkpointing in both shapes. After the load, a model that says no while a nested model says yes, or that is built on that layer, says yes on the instance; transformers enables checkpointing by walking modules, so every layer is switched on as before and the class default is untouched.

Differential

10-step LoRA, trust_remote_code = True, seq 512, B200, one process per arm from a neutral directory.

microsoft/Phi-4-reasoning-vision-15B (main here is main with #11469, which the processor path needs before the cast is reached; the 16-bit load already passed on that tree):

arm outcome
main, 4-bit You cannot cast a bitsandbytes model in a new dtype in the remote from_pretrained
main + change 1, 4-bit Phi4ForCausalLMV.forward() got an unexpected keyword argument 'packed_seq_lengths' on step 1
this PR, 4-bit PASS, loss 0.802, 0.597, 0.490, 0.420, 0.361, 0.294, 0.325, 0.370, 0.298, 0.280
this PR, 16-bit PASS, loss 0.761, 0.568, 0.500, 0.428, 0.360, 0.296, 0.322, 0.372, 0.299, 0.282

nvidia/Nemotron-3-Nano-Omni-30B-A3B-Reasoning-BF16, with the companion unsloth-zoo PR on both arms:

arm outcome
main ValueError: NemotronH_Nano_Omni_Reasoning_V3 does not support gradient checkpointing
main + change 4 NemotronH_Nano_Omni_Reasoning_V3.forward() missing 1 required positional argument: 'pixel_values'
main + changes 3, 4 NemotronHForCausalLM does not support gradient checkpointing
this PR, 4-bit PASS, loss 1.309, 1.015, 1.345, 1.172, 1.325, 1.075, 0.946, 1.250, 1.060, 0.837
this PR, 16-bit PASS, loss 1.297, 1.025, 1.331, 1.164, 1.307, 1.080, 0.943, 1.251, 1.060, 0.818

Grad norms finite throughout. The Phi-4 16-bit losses match the earlier passing sweep cell to the third decimal, so padding-free being off for this model did not move its numbers.

Tests

tests/test_remote_code_dtype_cast_on_quantized_model.py and tests/test_remote_code_training_gates.py: plus tests/test_tolerated_cast_and_compiled_packing.py: 33 tests on small models in the failing shapes. The existing padding-free and packing tests are unchanged (the five failures in tests/utils/test_packing.py and tests/version_compat/test_trl_padding_free_max_length.py are identical on main).

Compatibility

Run on transformers 5.17.0 with PEFT 0.21.0, TRL 0.25.1 and torch 2.13, and on transformers 4.57.6 with PEFT 0.18.0, TRL 0.22.2 and torch 2.6 (CPU): all tests pass on both. The cast shim is scoped to one call and gated on trust_remote_code with a bitsandbytes load, so CUDA, ROCm, XPU, MPS and CPU loads without it are untouched; the other changes run at model construction on any device.

Companion: unslothai/unsloth-zoo#1335 (the LoRA target and mask-builder half, needed for the Nemotron rows).

The two lines this adds after from_pretrained in vision.py and the remote-code shim call that #11528 adds a few lines later do not touch, so the two PRs merge in either order; #11523 is stacked on this branch.

Multimodal loads keep the wrapper

The unwrap to the language model runs only when the load carries text intent: text_only = True, or a checkpoint with no vision config. A FastVisionModel load of the same checkpoint keeps the wrapper and its vision tower for image batches, and prints the text_only = True hint for the text case. Text-only training of Nemotron-Omni and Phi-4-reasoning-vision therefore passes text_only = True.

Follow-up fixes

  • The text core inherits the wrapper's dtype when its sub-config has none (4-bit text_only crashed in backward with Blockwise 4bit dequantization only supports 16/32-bit floats, but got None) and the wrapper's repo path (the adapter's base_model_name_or_path was None, so it could not be reloaded).
  • The cast shim also engages for a 4-bit load passed as quantization_config = BitsAndBytesConfig(...).
  • text_intent is appended after the existing FastBaseModel.from_pretrained parameters, so no positional slot moves.
  • Merged saves of a text core are refused (see change 3).

Verified on tiny remote-code models in each failing shape through FastModel.from_pretrained + get_peft_model + 5 SFT steps: the 4-bit text_only wrapper trains (losses 10.370, 10.389, 10.408, 10.368, 10.409), the quantization_config load trains, 16-bit losses are unchanged, and a LoRA saved after text_only reloads with a max logit difference of 0.0. Native models (tiny Qwen3, Llama 3.2, Qwen2.5-VL, Gemma 3) give identical classes, targets, losses and grad norms on base and head.

…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.
@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:16:30.300817Z d65ade1 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.

pre-commit-ci Bot and others added 2 commits September 22, 2026 12:14
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.
pre-commit-ci Bot and others added 3 commits September 22, 2026 13:54
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.
@danielhanchen

Copy link
Copy Markdown
Member Author

@codex review

@danielhanchen

Copy link
Copy Markdown
Member Author

@codex security review

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

@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: 180f543540

ℹ️ 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 thread unsloth/models/vision.py
return original_to(self, *rest, **kwargs)
return self

PreTrainedModel.to = to

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 Serialize the process-wide PreTrainedModel.to patch

If two trusted quantized loads overlap in different threads, both contexts mutate the same class method without synchronization. When the first context exits before the second, it restores the real method, but the second later restores the first context's shim, leaving PreTrainedModel.to patched process-wide after both loads have completed; subsequent quantized dtype casts can then bypass Transformers' safeguard unexpectedly. A lock or otherwise non-global interception is needed around this temporary replacement.

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.

Two loads of the same model racing on one process from different threads is not a supported pattern anywhere in the loader; the gate is restored on the same path as before. Leaving as is.

…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.
@chatgpt-codex-connector

Copy link
Copy Markdown

Codex Review: Didn't find any major issues. More of your lovely PRs please.

Reviewed commit: 4804fb8084

ℹ️ 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 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: f5d5f6d655

ℹ️ 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 thread unsloth/models/loader.py
disable_log_stats = disable_log_stats,
load_in_fp8 = load_in_fp8,
text_only = load_text_only,
text_intent = bool(text_only),

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 language-loader intent when delegating

When FastLanguageModel.from_pretrained delegates an unsupported or remote model type to FastModel, its default text_only=False reaches this line even though the selected public loader establishes text-training intent. Consequently, a text-only composed checkpoint whose wrapper requires an input such as pixel_values is passed to _text_trainable_core with text_intent=False; the helper keeps the unusable wrapper and the first ordinary text batch still fails on the missing argument. Carry an explicit language-loader intent through this delegation rather than deriving intent solely from the optional text_only flag.

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. Main fails on this path too, and this PR prints an explicit hint naming text_only = True. Having FastLanguageModel silently return a different class for these wrappers is a design choice, not a correctness fix; text_only = True is the supported spelling.

Comment thread unsloth/models/vision.py
or type(tensor).__name__ in ("Params4bit", "Int8Params")
):
continue
tensor.data = tensor.data.to(dtype)

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 modules explicitly kept in FP32

For a trusted remote-code bitsandbytes load that ends in model.to(dtype), this assignment also casts ordinary parameters that Transformers deliberately excluded from quantization and retained in FP32. This includes model-defined _keep_in_fp32_modules and modules placed on CPU/disk under llm_int8_enable_fp32_cpu_offload; those weights are regular floating tensors, so none of the checks above skip them. Such loads silently lose their required FP32 modules and can suffer numerical failures or invalid CPU-offload execution, so the tolerated cast must exclude the quantizer's modules_to_not_convert entries that are designated to remain FP32.

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. The cast is the remote code's own model.to(dtype) at the end of its from_pretrained; a 16-bit load of the same repo casts those modules identically. The shim only stops the quantized load from raising, so it does what the model author asked.

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

@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: fb1d527f78

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

Copy link
Copy Markdown

Codex Review: Didn't find any major issues. Delightful!

Reviewed commit: 84deb0e057

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

…orwards its locals() as keywords, which broke every push_to_hub_merged
@unslothai unslothai deleted a comment from chatgpt-codex-connector Bot Sep 25, 2026
@unslothai unslothai deleted a comment from danielhanchen Sep 25, 2026
@unslothai unslothai deleted a comment from danielhanchen Sep 25, 2026
@unslothai unslothai deleted a comment from danielhanchen Sep 25, 2026
@unslothai unslothai deleted a comment from danielhanchen Sep 25, 2026
@unslothai unslothai deleted a comment from danielhanchen 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. Hooray!

Reviewed commit: d905037f79

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

# Conflicts:
#	unsloth/models/vision.py
@danielhanchen
danielhanchen merged commit b53a6d7 into main Sep 25, 2026
32 of 35 checks passed
@danielhanchen
danielhanchen deleted the phi4-vision-4bit-cast branch September 25, 2026 19:16
danielhanchen added a commit that referenced this pull request Sep 25, 2026
…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>
shimmyshimmer pushed a commit to shimmyshimmer/unsloth-staging-4 that referenced this pull request Sep 25, 2026
…oint (unslothai#11955)

tests/test_formatter_fixed_point.py fails on main for unsloth/save.py and
tests/test_remote_code_training_gates.py. Formatting only; the AST is unchanged.
danielhanchen added a commit that referenced this pull request Sep 26, 2026
…and a real message for Mistral-format checkpoints (#11528)

* Name a Mistral-format checkpoint instead of reporting two failed config loads

A repo that ships params.json and no config.json is a checkpoint in Mistral's
own format, loaded through mistral-common and vLLM; transformers has no
modeling code for it. Mistral-Large-3 is published that way and its card says
so. AutoConfig and PeftConfig both fail on it, and the generic message pointed
the user at upgrading transformers, which cannot help. The loader now names
the format, says why training is not possible yet and which route works for
inference. Answers false on any doubt, including offline, so the generic
message is never hidden.

* Grouped-linear LoRA and remote-code shims for DeepSeek-V4 and Step-3.7

DeepSeek-V4's grouped output projection subclasses nn.Linear with a
block-diagonal forward, so PEFT's dense LoRA delta had the wrong shape.
GroupedLinearLoRA keeps PEFT's parameters and checkpoint layout and only
groups the forward.

Step-3.7's remote code embeds tokens in get_input_embeddings and returns
no loss from forward; both are repaired on the checkpoint's own classes.

* Repair a remote-code get_output_embeddings that returns None

Step-3.7 delegates it to the inner model, which owns no head, so vocab
repair and resizing dereferenced None. When the class owns an lm_head
and the accessor returns nothing, the head is returned.

* Reach the repaired remote-code forward through an accelerate hook

device_map loading wraps forward before the shims run and keeps the bound
original as _old_forward, so the class-level loss repair was never called
from model(...). Rebind it to the repaired forward.

* Apply the remote-code shims after the offload comment so the hunk merges independently of #11526

Same position in the load sequence: right after from_pretrained and before
the offload decision reads the input embeddings. The two lines that #11526
adds after the load and these two no longer touch, so either PR can merge
first.

* [pre-commit.ci] auto fixes from pre-commit.com hooks

for more information, see https://pre-commit.ci

* Refuse DoRA on grouped linears instead of training it wrong

The grouped LoRA forward computes the plain LoRA sum. With use_dora = True
PEFT still created the magnitude vector, which then never received a
gradient, and PEFT's DoRA-aware merge produced a weight the training forward
had never used. register_grouped_linear_lora now raises NotImplementedError
for a DoRA config, and the forward raises if a LoRA variant reaches it.

Tests: both refusals; fail on the branch before this commit.

* Scope the grouped LoRA mapping to targeted modules, register it on adapter reload, and put the synthesized loss first

register_grouped_linear_lora scanned the whole model, so use_dora = True on a
model that merely contains a grouped linear was refused even when
target_modules never selected it. The scan now goes through PEFT's own
check_target_module_exists, so DoRA on the dense layers of DeepSeek-V4 trains
as before and only a targeted grouped linear is refused.

PEFT's custom module mapping holds class objects and is not part of the saved
adapter config, so a saved DeepSeek-V4 adapter reloaded through
PeftModel.from_pretrained wrapped o_a_proj with the dense LoRA layer again and
hit the original shape mismatch. Both adapter-load paths in loader.py now read
the adapter config, register the mapping on it and pass it to the load.

The synthesized causal LM loss was appended after logits, so output[0] and
to_tuple()[0] were the logits even with labels given; the output is rebuilt
with loss as its first entry.

Tests: DoRA allowed when no grouped linear is targeted (list and regex forms)
and refused for target_modules = None; a saved adapter reloads onto the
grouped forward with identical outputs; loss is the first ordered entry.
Three fail on the previous commit.

* Require a Mistral marker file before claiming the Mistral format, and bind positional labels

params.json alone also describes Meta's original Llama layout, so the format
is claimed only next to tekken.json or consolidated.safetensors. The loss shim
binds the call against the wrapped signature so labels passed positionally
are seen and removed the same as keyword ones.

* Register the fake remote module, gate the Mistral loader test on a real accelerator, pin the reload device

* [pre-commit.ci] auto fixes from pre-commit.com hooks

for more information, see https://pre-commit.ci

* Trim comments

* Keep a remote model's own loss when it returns a tuple

With return_dict = False a forward returns (loss, logits, ...), which the probe did not
recognise, so the model's own objective was replaced by the generic causal loss. A leading
0-d floating tensor now counts as the model's loss. The already-wrapped check also reads the
class's own dict, so a remote subclass of a repaired class is still probed.

* Decide a remote model's loss support per instance, not per class

Two configs of one remote class can differ in whether the model's own loss works, and the
first labelled call used to decide for every instance.

* Refuse an in-place LoRA merge into an fp8 grouped linear

PEFT's merge adds B @ A to the stored weight, but an FP8GroupedLinear's weight is fp8 read
with an unchanged weight_scale_inv. The merge now raises a clear error and leaves the layer
unmerged; bf16 grouped linears merge as before.

* Repair a subclass's own accessor override even when its parent was repaired

The already-repaired checks for get_input_embeddings and get_output_embeddings read the
marker through getattr, so a remote subclass that overrides the accessor inherited its
parent's marker and kept the missing-argument error. Both now read the class's own dict.

* Refuse an fp8 grouped merge before PEFT merges any layer

PEFT merges and unloads layer by layer, so refusing from the grouped layer left earlier
dense layers already merged. merge_and_unload and merge_adapter now check the whole model
first when grouped LoRA is registered.

* Add the SPDX line the other test files carry

* Trim comments further

* Use the SPDX header on the new modules and drop restating docstrings

* [pre-commit.ci] auto fixes from pre-commit.com hooks

for more information, see https://pre-commit.ci

* Reuse the probing call's logits instead of running a remote forward twice

* Reset fan_in_fan_out on grouped LoRA, synthesize a loss only for token-level logits, and cache the fallback only after a working forward

* Drop two restating docstrings

---------

Co-authored-by: pre-commit-ci[bot] <66853113+pre-commit-ci[bot]@users.noreply.github.com>
danielhanchen added a commit that referenced this pull request Sep 27, 2026
…12077)

The routing tests exec unsloth_generic_save against fakes with a listed set of
save.py helpers. #11526 added a call to _refuse_unsaveable_text_core and
updated test_merged_hub_destination's harness but not this one, so every
routing test raised NameError in the Core jobs. Load it (and
_honours_safe_serialization) as real code, stub the Qwen3.5 VLM state dict
helper the harness never reaches, and add a guard that names any save.py
helper the generic save calls that the harness neither loads nor stubs.
shaojun pushed a commit to shaojun/unsloth that referenced this pull request Sep 29, 2026
…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>
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>
shaojun pushed a commit to shaojun/unsloth that referenced this pull request Sep 29, 2026
…oint (unslothai#11955)

tests/test_formatter_fixed_point.py fails on main for unsloth/save.py and
tests/test_remote_code_training_gates.py. Formatting only; the AST is unchanged.
shaojun pushed a commit to shaojun/unsloth that referenced this pull request Sep 29, 2026
…and a real message for Mistral-format checkpoints (unslothai#11528)

* Name a Mistral-format checkpoint instead of reporting two failed config loads

A repo that ships params.json and no config.json is a checkpoint in Mistral's
own format, loaded through mistral-common and vLLM; transformers has no
modeling code for it. Mistral-Large-3 is published that way and its card says
so. AutoConfig and PeftConfig both fail on it, and the generic message pointed
the user at upgrading transformers, which cannot help. The loader now names
the format, says why training is not possible yet and which route works for
inference. Answers false on any doubt, including offline, so the generic
message is never hidden.

* Grouped-linear LoRA and remote-code shims for DeepSeek-V4 and Step-3.7

DeepSeek-V4's grouped output projection subclasses nn.Linear with a
block-diagonal forward, so PEFT's dense LoRA delta had the wrong shape.
GroupedLinearLoRA keeps PEFT's parameters and checkpoint layout and only
groups the forward.

Step-3.7's remote code embeds tokens in get_input_embeddings and returns
no loss from forward; both are repaired on the checkpoint's own classes.

* Repair a remote-code get_output_embeddings that returns None

Step-3.7 delegates it to the inner model, which owns no head, so vocab
repair and resizing dereferenced None. When the class owns an lm_head
and the accessor returns nothing, the head is returned.

* Reach the repaired remote-code forward through an accelerate hook

device_map loading wraps forward before the shims run and keeps the bound
original as _old_forward, so the class-level loss repair was never called
from model(...). Rebind it to the repaired forward.

* Apply the remote-code shims after the offload comment so the hunk merges independently of unslothai#11526

Same position in the load sequence: right after from_pretrained and before
the offload decision reads the input embeddings. The two lines that unslothai#11526
adds after the load and these two no longer touch, so either PR can merge
first.

* [pre-commit.ci] auto fixes from pre-commit.com hooks

for more information, see https://pre-commit.ci

* Refuse DoRA on grouped linears instead of training it wrong

The grouped LoRA forward computes the plain LoRA sum. With use_dora = True
PEFT still created the magnitude vector, which then never received a
gradient, and PEFT's DoRA-aware merge produced a weight the training forward
had never used. register_grouped_linear_lora now raises NotImplementedError
for a DoRA config, and the forward raises if a LoRA variant reaches it.

Tests: both refusals; fail on the branch before this commit.

* Scope the grouped LoRA mapping to targeted modules, register it on adapter reload, and put the synthesized loss first

register_grouped_linear_lora scanned the whole model, so use_dora = True on a
model that merely contains a grouped linear was refused even when
target_modules never selected it. The scan now goes through PEFT's own
check_target_module_exists, so DoRA on the dense layers of DeepSeek-V4 trains
as before and only a targeted grouped linear is refused.

PEFT's custom module mapping holds class objects and is not part of the saved
adapter config, so a saved DeepSeek-V4 adapter reloaded through
PeftModel.from_pretrained wrapped o_a_proj with the dense LoRA layer again and
hit the original shape mismatch. Both adapter-load paths in loader.py now read
the adapter config, register the mapping on it and pass it to the load.

The synthesized causal LM loss was appended after logits, so output[0] and
to_tuple()[0] were the logits even with labels given; the output is rebuilt
with loss as its first entry.

Tests: DoRA allowed when no grouped linear is targeted (list and regex forms)
and refused for target_modules = None; a saved adapter reloads onto the
grouped forward with identical outputs; loss is the first ordered entry.
Three fail on the previous commit.

* Require a Mistral marker file before claiming the Mistral format, and bind positional labels

params.json alone also describes Meta's original Llama layout, so the format
is claimed only next to tekken.json or consolidated.safetensors. The loss shim
binds the call against the wrapped signature so labels passed positionally
are seen and removed the same as keyword ones.

* Register the fake remote module, gate the Mistral loader test on a real accelerator, pin the reload device

* [pre-commit.ci] auto fixes from pre-commit.com hooks

for more information, see https://pre-commit.ci

* Trim comments

* Keep a remote model's own loss when it returns a tuple

With return_dict = False a forward returns (loss, logits, ...), which the probe did not
recognise, so the model's own objective was replaced by the generic causal loss. A leading
0-d floating tensor now counts as the model's loss. The already-wrapped check also reads the
class's own dict, so a remote subclass of a repaired class is still probed.

* Decide a remote model's loss support per instance, not per class

Two configs of one remote class can differ in whether the model's own loss works, and the
first labelled call used to decide for every instance.

* Refuse an in-place LoRA merge into an fp8 grouped linear

PEFT's merge adds B @ A to the stored weight, but an FP8GroupedLinear's weight is fp8 read
with an unchanged weight_scale_inv. The merge now raises a clear error and leaves the layer
unmerged; bf16 grouped linears merge as before.

* Repair a subclass's own accessor override even when its parent was repaired

The already-repaired checks for get_input_embeddings and get_output_embeddings read the
marker through getattr, so a remote subclass that overrides the accessor inherited its
parent's marker and kept the missing-argument error. Both now read the class's own dict.

* Refuse an fp8 grouped merge before PEFT merges any layer

PEFT merges and unloads layer by layer, so refusing from the grouped layer left earlier
dense layers already merged. merge_and_unload and merge_adapter now check the whole model
first when grouped LoRA is registered.

* Add the SPDX line the other test files carry

* Trim comments further

* Use the SPDX header on the new modules and drop restating docstrings

* [pre-commit.ci] auto fixes from pre-commit.com hooks

for more information, see https://pre-commit.ci

* Reuse the probing call's logits instead of running a remote forward twice

* Reset fan_in_fan_out on grouped LoRA, synthesize a loss only for token-level logits, and cache the fallback only after a working forward

* Drop two restating docstrings

---------

Co-authored-by: pre-commit-ci[bot] <66853113+pre-commit-ci[bot]@users.noreply.github.com>
shaojun pushed a commit to shaojun/unsloth that referenced this pull request Sep 29, 2026
…arness (unslothai#12077)

The routing tests exec unsloth_generic_save against fakes with a listed set of
save.py helpers. unslothai#11526 added a call to _refuse_unsaveable_text_core and
updated test_merged_hub_destination's harness but not this one, so every
routing test raised NameError in the Core jobs. Load it (and
_honours_safe_serialization) as real code, stub the Qwen3.5 VLM state dict
helper the harness never reaches, and add a guard that names any save.py
helper the generic save calls that the harness neither loads nor stubs.
rhsCZ pushed a commit to rhsCZ/unsloth that referenced this pull request Sep 29, 2026
…ing tested (unslothai#11137)

* Keep more VRAM headroom on Windows CUDA, and say when a hand-set context does not fit (#11368)

* Stop a Windows host-RAM spill from looking like a healthy load

On Windows, cudaMalloc does not allocate device memory directly. It asks the
WDDM kernel memory manager, which treats VRAM and system RAM as one demand
paged pool, and since driver 536.40 an allocation past the end of VRAM
succeeds out of host RAM instead of returning out of memory. The load starts,
exits 0, answers /health, and nvidia-smi shows a healthy card, while decode
re-reads the spilled bytes over PCIe on every token.

Linux has no such path. The same allocation fails with "cudaMalloc failed:
out of memory" and llama-server exits, which is measurable: with 12 GiB free,
Qwen3-VL-8B at -c 65536 asks for 9216.00 MiB in one allocation and refuses to
start. That is why every rung of the spawn loop's recovery ladder is gated on
a non-zero exit code, and why the whole ladder is dead on the one platform
that needs it.

Three changes:

Raise the per-device reserve to 1024 MiB on Windows with a discrete CUDA
build, capped at an eighth of the card so it stays proportionate on small
GPUs. This is not a new magic number, it is the per-device margin llama.cpp's
own fitter keeps when nobody tells it otherwise, and where our estimate
carries all the risk we should be at least as conservative as the child would
have been. Linux and macOS budgets are unchanged, and the monotonicity
property in _vram_reserve_floor_mib still holds at every fraction.

After a full GPU pin comes up healthy, check that the load is actually
resident. Windows exposes the spilled bytes itself through the
'\GPU Adapter Memory(*)\Shared Usage' counter behind Task Manager's shared
memory figure, which nvidia-smi cannot see because on WDDM it reports
dedicated VRAM only. That counter is per adapter rather than per process, so
it is believed only when the device side independently shows the child short
of the weights plus KV cache that full offload must place on the card. Report
only, no recovery.

Warn when a hand-set context does not fit. The planner already prices this
correctly and already hands the load to --fit, but said nothing about why the
context was flexed. The notice also re-prices at q8_0 and mentions it when
that would make the configuration fit, rather than changing a user's cache
dtype for them.

Refs #11349, #11336

* [pre-commit.ci] auto fixes from pre-commit.com hooks

for more information, see https://pre-commit.ci

* Trim comments in the Windows sysmem fallback change

* Keep the residency check and context notice from making false claims

The residency check read only -ngl and --fit, so a user extra appended after the
pin that keeps weights or the KV cache on the host (--cpu-moe, -ot, -ncmoe,
-nkvo, --device none, or their LLAMA_ARG_ env twins) was reported as a host RAM
spill. The =-form overrides (--gpu-layers=10, --fit=on) were missed the same way.

The overcommit notice offered the Auto fallback anchor as the largest context
that fits when the weights alone overflow every GPU subset, so lowering the
context to that figure would still not fit. Only offer a context when one fits.

* Scope the residency check to CUDA builds, the loaded adapter and its own process

Arm only when the resolved build is CUDA: a Vulkan launch on an NVIDIA host has
no CUDA sysmem fallback and its ordinals are not NVML indices.

Read Dedicated Usage beside Shared Usage and count shared growth only on the
adapters whose VRAM grew across the spawn, so a display iGPU's churn on an
Optimus laptop is no longer booked as the model's spill.

Hand the verifier thread a snapshot of the armed state and the child it was
started for, and drop its result if that child has since been replaced.

* Check residency before the load returns, and keep its advice accurate

Run the residency check synchronously once the final child is ready, after
every post-health respawn, so the verdict describes the process that is
actually serving and reaches the load response. A warning written after the
response was never shown. The spill notice is appended to an earlier one
instead of losing first-notice-wins.

Offer q8_0 only when the cache is still f16, cap the counted adapters at the
number of pinned cards, key the sysmem-fallback cache by the resolved binary,
and use the Windows wording in the context notice only for CUDA builds.

* Gate the direct spill signal on a full card, and settle before re-baselining

The measured delta carries the CUDA context and compute buffers, so requiring
it to fall short of the weights+KV floor masked small spills such as the 74 MiB
case. WDDM only spills once dedicated VRAM is exhausted, so count shared growth
when a pinned card is nearly full instead.

Wait for a killed retry child's VRAM to settle before sampling the next
baseline, and price the q8_0 hint's compute scratch at q8_0.

* Report the measured spill, judge a full card by its own reserve, drop a stale notice

Name the counter's measured shared-memory growth as the spill amount on a
direct hit; the floor delta can be negative there, since it carries the CUDA
context and compute buffers. Treat a card as full below its proportional
sysmem-fallback reserve rather than a flat 1 GiB, so small cards are not
flagged. Publish the context overcommit notice only when the final plan still
hands the load to --fit on, since slot reduction can re-pin it.

* Word the context notice for planned offload, and tighten the spill report

The overcommit notice fires only once the load was handed to --fit on or a
spill plan, both of which place host tensors deliberately, so the Windows
driver-fallback wording and NVIDIA setting never applied there. Use the CPU
offload wording on every OS.

Sum only positive shared growth across pinned adapters, report spills under
1 GiB in MiB instead of rounding them to 0.0 GB, and key the fallback
classification by build revision so an in-place runtime update is re-read.

* Disarm the residency check on a KV layout change, skip the notice under -nkvo

A retry that respawns with a different slot count or unified-KV setting holds a
different cache than the floor was priced for, so disarm instead of comparing
against the stale floor. With KV offload disabled the cache stays on the host,
so the context overcommit priced from GPU KV bytes is not real.

* Do not cache an empty backend scan

_installed_ggml_backends returns an empty set for an unreadable lib dir instead
of raising, so the transient-failure rule has to cover that result too. Also let
the residency tests import their sibling harness when run on their own.

* Keep host-only tensors out of the residency floor, and tighten the notices

Subtract an untied token_embd (kept on the CPU at full offload) and MTP blocks
that do not load from the floor, by the same rules _unified_need_now uses, so a
healthy load is not flagged as a spill. Skip the context notice when the user
placed tensors on the CPU or fixed the layer count, offer q8_0 only when flash
attention is planned on, and name the executable actually launched in the
driver-setting advice.

* Trim comments added during review

* Drop the post-load residency check; keep the Windows reserve and the context notice

The spill detector could not be validated on Windows NVIDIA hardware and was most
of this change's size and risk. Keep the two parts that stand on their own: the
raised sysmem-fallback reserve on Windows CUDA builds, and the advisory when a
hand-set context does not fit. The backend classifier tests move to the reserve's
test file.

* Skip the context notice for an env-fixed layer count or at the native ceiling

An inherited LLAMA_ARG_N_GPU_LAYERS is a deliberate placement like the argv
flags. When the ceiling sweep stopped at the native context, a larger rope-
scaled window was never searched, so the largest context that fits is unknown.

* Skip the context notice when the user turns the fitter off

User extras follow the generated --fit on, so a trailing --fit off disables the
fitter and nothing moves layers to the CPU; the notice would claim otherwise.

* Register the q8_0 what-if in the split-rate call-site guard

* Trim comments in the Windows reserve change

---------

Co-authored-by: pre-commit-ci[bot] <66853113+pre-commit-ci[bot]@users.noreply.github.com>

* Unsloth Studio (AMD): keep export off a GPU PyTorch has no kernels for, like the iGPU (#11946)

* Studio: keep export off a GPU the installed PyTorch has no kernels for

* Trim comments restating the code

* [pre-commit.ci] auto fixes from pre-commit.com hooks

for more information, see https://pre-commit.ci

---------

Co-authored-by: Daniel Han <[email protected]>
Co-authored-by: pre-commit-ci[bot] <66853113+pre-commit-ci[bot]@users.noreply.github.com>

* Read the hot-path I/O cost at its steady minimum across repeats (#12029)

* Unsloth Studio: a companion fetch with no denoiser no longer blocks deleting its base (#11828)

A cached repo counts as needing a companion base only if it holds a runnable denoiser. The VAE-only fetch the native engine leaves in unsloth/Qwen-Image-2.1-FP8, and the default pre-cast fp8 text encoder a diffusers load caches at that repo's root, no longer pin Qwen/Qwen-Image-2.1 from a row the On Device list cannot act on. A prequant repo holding its DiT checkpoint still pins its base.

Fixes #11825.

* Studio: stop Python tool network calls from skipping the host allowlist (#11172)

* Studio: check the sandbox host allowlist for keyword, variable and aliased hosts in Python network calls

* Drop two sandbox comments that restate the code below them

* Keep resolving a network alias when the name is rebound elsewhere

* Rank network alias stores by the call they reach and ask on depth exhaustion

* Refuse a network target that is out of policy on any competing store

* Check a connect receiver that is a tracked client on any path

* Keep a valueless store unresolved instead of dropping it

* Read class-body names in source order and match only urllib3 calls that connect

* Check every candidate signature and scope attribute receivers to their owner

* Check the proxy and pool entry points urllib3 exports

* Carry unpacked values to the target they bind

* Memoize alias resolution so a branching chain stays linear

* Ask when alias resolution gives up on the callee

* Expand conditionals so every branch of a target is checked

* Let an unconditional rebinding replace the value a later read sees

* Check session and pool request methods, and only supersede on a certain binding

* Keep the enclosing binding when a class store may not run

* Take each client method's URL position from its real signature

* Check client base URLs, parameter defaults and self-referential stores

* Resolve prebuilt requests and check explicit proxy destinations

* Cover OPTIONS and the modules these APIs are actually defined in

* Resolve a client kept on an attribute

* Follow base classes, cover session uploads and websockets, drop the quadratic scan

* Make a binding take effect at the end of its statement

* Resolve a walrus callee to the callable it assigns

* Apply the literal-target fallback only to listed entry points

* Only read a call result as its constructor when that names a known client

* Cover raw urllib3 connections, renamed receivers and disabled proxies

* Treat the lowercase session factory and aiohttp's request helper as entry points

* Resolve constant getattr dispatch and cover aiohttp uploads

* Check the payload where a request is built

* Bind a definition name after its header runs

* Keep the stores that resolved when a sibling store hits a cycle

* Resolve a connect receiver with the same resolver as every other callee

* Put a client's connect in the target table and stop reading stores that have not run

* Generate the urllib3 URL factory specs from the module that defines each

* Keep source order inside the body that does the reading

* Check the encoded pool helpers and a proxy set on the session

* Give attribute stores the same reaching rule as name stores

* Tie a receiver's attributes to the binding in effect at the call

* Parse the URL the client will send, and follow a mutated proxy mapping

* Sequence a finally block with the statements that follow the try

* Key attribute stores on the whole receiver path

* Read attribute stores under the dotted paths they are recorded with

* Port client, proxy and SSH egress coverage onto the alias screen from main

* Trim comments on the ported egress tables

* Track annotated assignments, share proxies across client copies, skip static methods

* Treat local client subclasses as the client, and follow aliased proxy mappings

* Read base_url stores on a client and in-place proxy merges

* Scope client destination attributes to the client that reads them, and cover asyncssh.connection

* Resolve network submodule paths to the names their package re-exports

* Read a proxy without a scheme as a host

* Skip mapping keys and None destinations

* Skip no_proxy entries in proxy mappings

* Screen uploads through httpx stream, and follow clients passed to local functions

* Track subclasses of connecting classes, and read httpx transport proxies

* Follow clients passed to local methods

* Propagate clients along every recorded copy, and bind unbound method calls

* Track clients bound by loop and comprehension targets

* Follow clients returned by local factories, and link helper parameters to their callers

* Follow factory methods and awaited factories

* Follow aliases of local functions

* Read class-body clients in their own body, and read authority-relative URLs

* Screen PoolManager.connection_from_host

* Bind calls and index flows after every alias is collected

* Tighten comments on the egress screen additions

* Screen datagram destinations on sendto and sendmsg

* Apply proxy stores after binding, and read proxy environment variables

* Resolve os and environ aliases for proxy environment stores

* Screen urllib openers and ProxyHandler mappings

* Follow wrapper instances, read environment mappings, and scope environment proxies

* Reach inherited client methods through self, and read expanded environment updates

* Read mutated environment mappings and os.environ merges, and honour aiohttp trust_env

* Resolve environment keys held in variables, and bind local constructor arguments

* Treat lambdas bound to a name as local functions

* Handle annotated assignments through the same binding path as plain ones

* Follow inherited initializers, inline wrappers, environ aliases and super()

* Carry os.environ through helper parameters

* Check asyncssh tunnel and proxy_command, and honour httpx trust_env=False

* Treat a paramiko sock argument as unreadable

* Screen asyncssh.connect_reverse, and follow clients returned by properties

* Carry the os module through assignments and helper parameters

* Check SSH routing keywords from one table, including Fabric gateway

* Limit the sock routing rule to SSHClient.connect

* Check asyncssh connection options, and read named proxy mappings

* Follow bound local methods saved under another name

* Track proxy-manager factories and SOCKSProxyManager as pool clients

* Read a path with a relative literal prefix as hostless

* Read a wholesale os.environ replacement

* Trim comments in the egress screen additions

* Index shadowed names by scope so the egress screen stays linear on class-heavy code

* Read a backslash as the end of the host, and follow class attributes and unpacked factory tuples

* [pre-commit.ci] auto fixes from pre-commit.com hooks

for more information, see https://pre-commit.ci

* Read proxy writes through os.environb, and fail closed on a Fabric connect_kwargs sock

* Never trust a host with a backslash, and read filled-in Fabric kwargs and getattr environ writes

* Check positional SSH route arguments for paramiko connect and Fabric Connection

* Read an explicit environ __ior__ call like update

* Trim comments in the egress screen fixes

* [pre-commit.ci] auto fixes from pre-commit.com hooks

for more information, see https://pre-commit.ci

---------

Co-authored-by: Maheswar Kumar <[email protected]>
Co-authored-by: Daniel Han <[email protected]>
Co-authored-by: pre-commit-ci[bot] <66853113+pre-commit-ci[bot]@users.noreply.github.com>

* Studio: center collapsed sidebar icons and tighten the rail (#12031)

* Studio: center collapsed sidebar icons and tighten the rail

The nav icon's expanded-row nudge also applied in the collapsed rail,
leaving each icon 2px right of its hover circle. Drop it there, use
30px round hover targets throughout the rail (including the open
sidebar toggle), and sit the settings cog one nav row above the avatar.

* Studio: shrink collapsed sidebar hover circles to 28px

* Unsloth Studio: list a GGUF with no header metadata under On Device on the Images page (#11830)

* Studio Hub: classify a GGUF whose header names no architecture from its name

unsloth/Qwen-Image-2.1-GGUF files carry no general.* keys at all, so _arch_to_task answered None. The Images picker filters On Device rows on an exact task and dropped the row; the unfiltered Chat picker listed it and refused it. A readable header that names nothing now takes the same name-only route as a cloud placeholder.

* Trim comments on the no-architecture GGUF classification

* Keep the MiniMax-H3 conditioner out of the name-only video route

---------

Co-authored-by: Daniel Han <[email protected]>

* Keep the conversion backfill's donor stub off the transformers package (#12034)

* Unsloth Desktop: show Stopping… after Stop so a pending cancel doesn't look ignored (#11976)

* Studio: show Stopping… after Stop so a pending cancel doesn't look ignored

* Studio: tighten stop-label comments

---------

Co-authored-by: Daniel Han <[email protected]>

* Studio: stop edit_file writing a compacted-argument placeholder into files (#11950)

* Studio: stop edit_file writing a compacted-argument placeholder into files

* Trim comments in the compaction receipt guard

---------

Co-authored-by: Daniel Han <[email protected]>

* Studio: decode Wan video in fp16 with channels_last_3d convs (#11999)

* Studio: decode the Wan video VAE in fp16 with channels_last_3d convs

* Format

* Trim the fp16 decode docstring

* Trim fp16 decode comments

* Unsloth Studio: refuse picking a hosted FP8/INT8 checkpoint repo as a pipeline before it downloads (#11829)

* Studio: refuse a pipeline pick of a hosted prequant repo before it stages anything

A pick of unsloth/Qwen-Image-2.1-FP8 with no file name is a pipeline load, and validate_load_request let it through: the family detects from the id and unsloth/ clears the trust gate. The plan staged the repo's 14 GB of checkpoints, then from_pretrained 404d on the model_index.json the repo does not have. The hosted prequant repos are now a table (prequant_only_repo_ids) and a pipeline pick of one is refused with the base repo and precision to pick instead.

* Skip the hosted prequant-repo pipeline refusal when repo_id is an existing local path

- The new prequant-repo pipeline refusal matched the repo id by exact string, so a local pipeline directory cloned to that same relative name (e.g. ./unsloth/Qwen-Image-2.1-FP8 with a valid model_index.json) was wrongly rejected. It now skips the refusal for local paths and lets the existing local manifest validation handle them.

* [pre-commit.ci] auto fixes from pre-commit.com hooks

for more information, see https://pre-commit.ci

* Studio: trim comments in prequant pipeline-pick refusal

---------

Co-authored-by: pre-commit-ci[bot] <66853113+pre-commit-ci[bot]@users.noreply.github.com>
Co-authored-by: danielhanchen <[email protected]>

* Studio: stop the second prompt length recompiling Qwen-Image on the max tier and with int8 (#11842)

* Studio: compile the prompt-length dims of Qwen-Image DiT blocks dynamic from the first render

The max tier (and torchao weights on the default tier) compiles DiT blocks with
automatic dynamic, so the first prompt's token count was compiled static and the
first prompt of a different length recompiled every block graph into the
generalised form it then kept (Qwen-Image-2.1: 14 s int8 default, 31 s bf16 max,
51 s int8 max; Qwen-Image: 52-57 s max).

Name the block inputs whose size follows the prompt in
torch.compiler.config.dynamic_sources, set only around the owning transformer's
forward and restored even when it raises, so the first compile already builds the
generalised graphs. The first segment start of Qwen-Image-2.1 stays static, which
keeps clear of the torchao CantSplit that dynamic=True hits. The compile-cache key
gains the allowlist only for these families. torch without the knob (2.6) is
unchanged.

* Studio: also mark Qwen-Image's text inputs dynamic when FBCache calls the blocks through hooks

FBCache is on by default for Qwen-Image, and its hooks pass the block inputs as
kwargs (or a resumed frame's stack after a graph break), so the plain L[...]
names never matched and the second prompt length still recompiled. Suffix
patterns cover those paths on torch 2.8+.

* [pre-commit.ci] auto fixes from pre-commit.com hooks

for more information, see https://pre-commit.ci

* Studio: ruff format

* Arm the prompt-length allowlist only on torch 2.8+

torch 2.7 caches its first read of compiler.config.dynamic_sources for the
life of the process, so scoping the list to one forward is either ignored or
leaks it into every later compile. 2.8 re-reads it when it changes and adds
regex matching (is_dynamic_source), which the FBCache hook paths also need.
Older torch keeps today's behaviour.

* Trim comments

* Trim comments on the prompt-length allowlist

* Trim dynamic text dims comments

* Drop dead torch<2.1 hook fallback and redundant in-test skips

* [pre-commit.ci] auto fixes from pre-commit.com hooks

for more information, see https://pre-commit.ci

* Tighten dynamic text dims docstrings

---------

Co-authored-by: pre-commit-ci[bot] <66853113+pre-commit-ci[bot]@users.noreply.github.com>

* Studio: size the image memory plan at the dtype the pipeline loads in (SDXL resident on 24 GB) (#11922)

* Studio: size the diffusion memory plan at the dtype the pipeline loads in

The pipeline memory plan summed the cached shard bytes, which is what a repo
stores rather than what the load holds. SDXL and SDXL-Turbo publish fp32
weights (12.9 GB) that load as 6.5 GB in bf16/fp16, so 20-24 GB cards planned
whole-model offload for a model that fits resident, and a 16 GB unified-memory
Mac refused it outright. Lumina-2 and Z-Image-Turbo ship fp32 shards the same
way, and a cache holding fp16 variant twins, .bin twins or a single-file
checkpoint beside the pipeline counted weights the loader never opens.

Price each cached weight file the way from_pretrained materialises it:
default-variant component files only, safetensors over a .bin twin, and a
file whose floats are all wider than the load dtype at that dtype. Mixed
precision, quantised and fp8 files, components whose class pins modules in
fp32, and fp32 loads keep their stored size, and the estimate only ever
lowers. Download sizes and disk checks are unchanged.

* Studio: let the mirrored companion stub take the load itemsize

* Studio: shorten the load-dtype sizing comments

* Studio: widen half-precision weights on an fp32 load, keep a .bin the loader falls back to

An fp32 target (a Mac without bf16, an fp16-incompatible family on an fp16
card) materialises bf16/fp16 shards at four bytes per element, so price every
float at the load width there. A .bin is dropped only when its folder holds a
safetensors checkpoint the loader can select: an unsharded file, or shards with
their index.

* Studio: honour Transformers' non-strict fp32 pins only on fp16 loads

Transformers upcasts _keep_in_fp32_modules only when the load dtype is fp16
and _keep_in_fp32_modules_strict for both halves; Diffusers upcasts its set
for both. A bf16 load of an fp32 T5 checkpoint is therefore priced at bf16.

* Studio: price fp32-pinned modules at four bytes in half-precision loads

A component whose class keeps modules in fp32 (T5's wo at fp16, a strict or
Diffusers pin at either half) holds those tensors at four bytes whatever the
checkpoint stores, so price them per tensor instead of leaving the file at
its stored size.

* Studio: match fp32 pins against the parameter path the way each loader does

* Studio: price a surviving .bin checkpoint at the load dtype too

* Studio: count a tied .bin weight once when pricing it

* Studio: trim comments in the load-dtype memory plan

* Studio: stop MiniMax-H3 recompiling on the second caption and the first i2v (#11880)

* Studio: compile the prompt-length dims of Qwen-Image DiT blocks dynamic from the first render

The max tier (and torchao weights on the default tier) compiles DiT blocks with
automatic dynamic, so the first prompt's token count was compiled static and the
first prompt of a different length recompiled every block graph into the
generalised form it then kept (Qwen-Image-2.1: 14 s int8 default, 31 s bf16 max,
51 s int8 max; Qwen-Image: 52-57 s max).

Name the block inputs whose size follows the prompt in
torch.compiler.config.dynamic_sources, set only around the owning transformer's
forward and restored even when it raises, so the first compile already builds the
generalised graphs. The first segment start of Qwen-Image-2.1 stays static, which
keeps clear of the torchao CantSplit that dynamic=True hits. The compile-cache key
gains the allowlist only for these families. torch without the knob (2.6) is
unchanged.

* Studio: also mark Qwen-Image's text inputs dynamic when FBCache calls the blocks through hooks

FBCache is on by default for Qwen-Image, and its hooks pass the block inputs as
kwargs (or a resumed frame's stack after a graph break), so the plain L[...]
names never matched and the second prompt length still recompiled. Suffix
patterns cover those paths on torch 2.8+.

* [pre-commit.ci] auto fixes from pre-commit.com hooks

for more information, see https://pre-commit.ci

* Studio: ruff format

* Arm the prompt-length allowlist only on torch 2.8+

torch 2.7 caches its first read of compiler.config.dynamic_sources for the
life of the process, so scoping the list to one forward is either ignored or
leaks it into every later compile. 2.8 re-reads it when it changes and adds
regex matching (is_dynamic_source), which the FBCache hook paths also need.
Older torch keeps today's behaviour.

* Trim comments

* Studio: compile MiniMax-H3's packed length dynamic from the first render

A new caption changes H3's packed video + audio + caption length, and the
first new caption after load recompiled the denoiser blocks (about 11 to 22 s).
Name those inputs in the prompt-length allowlist so the first compile is
already general, and keep the small-M int8 padding free of a branch on the
row count when traced, which otherwise guarded the caption length to <= 31
rows and recompiled the refiner on the first i2v (a 540-row caption).

* Pad traced rows with arithmetic max so a concrete row count still compiles

torch.sym_max on a concrete int is rejected by dynamo on torch 2.8 and older,
so a static compile of a padded int8 Linear broke (fullgraph drops the DiT to
eager). builtin max() compiles but left an m <= pad_to guard behind on an
inductor cache hit. (m + p + |m - p|) // 2 does neither.

* Trim comments on the prompt-length allowlist

* Trim comments on the H3 allowlist and traced row padding

* [pre-commit.ci] auto fixes from pre-commit.com hooks

for more information, see https://pre-commit.ci

* Trim dynamic text dims comments

* Drop dead torch<2.1 hook fallback and redundant in-test skips

* [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

* Tighten dynamic text dims docstrings

---------

Co-authored-by: pre-commit-ci[bot] <66853113+pre-commit-ci[bot]@users.noreply.github.com>

* Unsloth Studio / Desktop: log what an image load and each generation actually resolved to (#11994)

* Studio: log what an image load and each generation actually resolved to

* Studio: trim comments on the resolved and generation log lines

* Studio: build the diffusion.loaded resolved field from the committed load state

* Studio: log the applied denoise strength and native sd.cpp LoRAs in diffusion.generated

* Studio: log the effective upscale factor, and only for the upscale workflow

* [pre-commit.ci] auto fixes from pre-commit.com hooks

for more information, see https://pre-commit.ci

---------

Co-authored-by: Daniel Han <[email protected]>
Co-authored-by: pre-commit-ci[bot] <66853113+pre-commit-ci[bot]@users.noreply.github.com>

* Unsloth Studio: stop offering "Continue" on a base repo that only holds a GGUF's text encoder and VAE (#11644)

* Unsloth Studio: stop offering "Continue" on a base repo that only holds a GGUF's text encoder and VAE

A companion-only snapshot stays partial so no picker loads it, but a new
companion_prefetch flag keeps the Hub from presenting it as an unfinished
download whose Continue pulls the denoiser the GGUF replaces.

* Carry companion_prefetch through the local listing the Hub merges

The Hub merges /api/hub/cached-models with /api/hub/local, and the local
scanner knew nothing about companion-only snapshots. After a real GGUF
load, its row for the base repo stayed Partial, and the detail pane still
offered Continue at 33 GB. When the base repo held VAE and encoder shards,
the same scanner classified it as a complete safetensors model instead,
and the Hub offered Run on a pipeline with no denoiser.

The local scanner now reads the same signal on the snapshot it lists:
such rows are partial, as the cached listing marks them, and carry
companion_prefetch. The frontend honours the flag on local rows too.

* Keep a companion-only base repo out of model Discover's on-device and partial states

buildDiscoverRows read partial and on-device straight off the cached or
local row, so the new flag never reached the model Discover grid: the repo
still read as a partial download there.

* Show a companion-only base repo as a plain Download, not On device with Run

Excluding the flag from the partial hf_cache branch sent the local row into the
fully local view, which claims the repo is on device and offers Run on a
pipeline with no denoiser. Keep the branch and clear only the partial state.

* Key the Discover memo on the companion flag

A companion fetch finishing leaves partial true on both listings and flips only
companion_prefetch, so the signature the model Discover memo is keyed on did not
change and the grid kept the repo as on device and partial.

* Trim companion_prefetch comments

* Keep Delete on a companion-only repo's download card

The card gated its repo menu (Delete, path) on isDownloaded || isPartial,
and a companion-only repo is now neither, so 19 GB of borrowed text
encoder and VAE could no longer be deleted from the detail pane.

* Drop the green On device dot from a companion-only inventory row

* Trim comments

---------

Co-authored-by: Daniel Han <[email protected]>
Co-authored-by: Daniel Han <[email protected]>

* Apply SFTConfig.router_aux_loss_coef to MoE models that cache it at init (#12006)

* Apply SFTConfig.router_aux_loss_coef to MoE models that cache it at init

* [pre-commit.ci] auto fixes from pre-commit.com hooks

for more information, see https://pre-commit.ci

* Tighten router_aux_loss_coef sync comments

---------

Co-authored-by: pre-commit-ci[bot] <66853113+pre-commit-ci[bot]@users.noreply.github.com>

* Load only the language model for text_only on repo-code composites (#11861)

* Load only the language model for text_only on repo-code composites

FastModel.from_pretrained(text_only = True) skipped the vision tower only for
families with their own text decoder (gemma3 -> gemma3_text). A repo-code
composite such as Nemotron-3-Nano-Omni (llm_config + vision_config +
sound_config, one wrapper class in auto_map) failed that test, so the whole
wrapper was loaded and its forward required pixel_values.

When trust_remote_code is set, the parent config is repo code, and every
parameter of the text sub-config's causal LM (built on the meta device) is
stored under exactly one checkpoint prefix, load that causal LM alone with a
key_mapping stripping the prefix. Anything else keeps the previous full-model
load, so no text weight can be left randomly initialised.

* Also find the decoder of a repo-code composite under llm_config

InternVL and Llama-Nemotron-Nano-VL keep the decoder config as llm_config
without the text_config alias get_text_config() reads, so the text-only
plan never saw it. Fall back to llm_config / language_config; the
full-coverage checkpoint check still decides whether the branch is taken.

* Keep the full-model load for repo-code composites on transformers 4.x

transformers 4.x decides base-model vs task-model prefix handling from the
checkpoint keys before key_mapping renames them, so a language_model.
prefixed checkpoint either raises "state dictionary ... corrupted" or, with
tied embeddings, loads every text weight as missing. Decline the text-only
plan below 5.0 and skip the positive tests there.

* [pre-commit.ci] auto fixes from pre-commit.com hooks

for more information, see https://pre-commit.ci

* Record the commit a trusted load ran repo code at

A merged export that re-reads the repo's config with its code pins it
to this commit instead of the branch head. Under text_only the model's
config is the nested text config, which carries no commit, so the
composite config's commit is taken before the remap.

* [pre-commit.ci] auto fixes from pre-commit.com hooks

for more information, see https://pre-commit.ci

* Pin the text-only config of a repo-code composite to the parent commit

* Read a cached unsharded checkpoint when the text-only plan runs offline

* Keep the full composite for adapters trained on it under text_only

* Decline the text-only plan for repo-code composites under fast_inference

* Accept sequence-valued auto_map entries in the text-only self-reference check

* Rebase llm_int8_skip_modules once from the parent names for nested text prefixes

* Pass torch_device to PeftModel.from_pretrained in the text-only adapter test

* Probe sharded .bin composites for the text-only plan from their index

* Pass local_files_only to the nested text class lookup of the text-only plan

* Read adapter_model.bin names when deciding whether an adapter fits the text model

* Probe the text-only plan at the commit its config was resolved at

* Decline the text-only plan when the nested text class lives in another repository

* Probe the text-only plan checkpoint under the requested subfolder

* Keep the full composite for a device_map keyed on its module names

* Probe the text-only plan checkpoint at the requested variant and cache_dir

* Resolve the nested text class at the requested code_revision

* Keep the full composite for an adapter on wrapper-only modules

* Rebase the caller's quantization_config skip modules for the text-only plan

* Stamp the code_revision commit as the trusted remote code commit

* Stamp the rebased quantization_config on the text-only decoder

* Save the text-only decoder under its standalone weight names

* Pin the wrapper-only adapter test's PEFT load to the CPU

* Give the text-only test namespace the remote class resolver resolve_model_class now calls

* Trim comments in text-only remote composite loading

* Add the license header to the text-only remote composite tests

* [pre-commit.ci] auto fixes from pre-commit.com hooks

for more information, see https://pre-commit.ci

* Try the text-only plan when a repo-code wrapper is its own text config (InternVL)

* Rebase every quantization module-name list on the text model, and keep the full model for a regex that names the prefix

* Detect a quantization regex that escapes any dot of a nested text prefix

* Tighten comments in the text-only remote composite path

---------

Co-authored-by: pre-commit-ci[bot] <66853113+pre-commit-ci[bot]@users.noreply.github.com>

* Put back the unsloth_zoo modules the device map opt-in tests stub (#12038)

* Studio: pass tool_result is_error through to the model on /v1/messages (#11962)

Keep the Anthropic tool_result is_error flag on /v1/messages and mark failed tool output with an Error: prefix (or a short note when the output is empty) so the local model can tell a failed tool call from an empty success.

* SentenceTransformer: add opt-in FP32 merged-pair ranking loss (#11867)

* SentenceTransformer: add opt-in FP32 merged-pair ranking loss

* Trim comments in merged-pair ranking loss

* Use SPDX AGPL-3.0 header on merged-pair loss files

* Check autocast and dtype before the BatchNorm module walk in merged-pair loss

* Drop restating docstrings and comment in merged-pair loss

* Skip gather test on SentenceTransformers without gather_across_devices

---------

Co-authored-by: Daniel Han <[email protected]>

* Studio: opt-in Hadamard rotation for Qwen-Image-2.1's int8 transformer so it matches bf16 (#11835)

* Studio: rotate Qwen-Image-2.1's outlier int8 inputs with ConvRot

Plain W8A8 int8 on Qwen-Image-2.1 loses most of its accuracy on a few
Linears whose inputs carry outlier channels (the SiLU-gated img_mlp.out
above all). A group-256 block Hadamard on the q/k/v and img_mlp.out
inputs spreads those outliers before the per-token quantizer sees them.

- runtime int8 quantize path rotates the family's declared Linears
  before quantize_, and fills the Hadamard cache for the target device
  so the first compile does not guard on its absence
- the family names the rotated artifact first; the plain one stays
  behind it in the derived chain
- the checkpoint builder follows the same spec unless told otherwise
- an unreachable Hub falls back to a later name already in the cache

* Studio: rotate every Qwen-Image-2.1 block Linear, and warm the Hadamard on the indexed device

Over 48 prompt-seed pairs the all-block rotation beats q/k/v + img_mlp.out
alone (LPIPS 0.031 vs 0.044 against the bf16 transformer, paired CI
excludes zero) for about 4% more step time. The cache is warmed for
target.torch_device, so a card picked by ordinal gets the same key the
forward will ask for.

* Builder: publish a plain Qwen-Image-2.1 int8 build under the plain name

The family's declared int8 name is now the rotated artifact, so a plain
safetensors build asked for with --convrot-groupsize 0 would have been
uploaded over it. It goes to the derived plain name instead, which the
loader still tries after the rotated one.

* Format

* Rotate the PEFT base_layer of a LoRA-baked Qwen-Image-2.1 target too

Adapters are attached before quantize_, so an adapted projection is
'<suffix>.base_layer' and was quantized without its rotation. The adapter
reads the unrotated input, so rotating the base layer stays exact.

* Pin prequant readability in the offline-fallback test

Runners without torchao answer that no safetensors prequant is readable,
so the cached plain artifact was correctly skipped there.

* Test the LoRA rotation without depending on peft's torchao dispatcher

peft 0.18.1 raises on torchao 0.18 until unsloth's import fix is applied,
so the base_layer check now runs on a PEFT-shaped stand-in, and the real
peft variant skips only on that ImportError.

* [pre-commit.ci] auto fixes from pre-commit.com hooks

for more information, see https://pre-commit.ci

* Trim comments in the int8 ConvRot change

* Trim comments in int8 ConvRot changes

* Accept base_repo in the int8 ConvRot test scheme stubs

* [pre-commit.ci] auto fixes from pre-commit.com hooks

for more information, see https://pre-commit.ci

* Trim comments in int8 ConvRot changes further

* Make Qwen-Image-2.1 int8 ConvRot opt-in via UNSLOTH_DIFFUSION_INT8_CONVROT

Unset keeps the plain int8 runtime path and asks the Hub for the plain
Qwen-Image-2.1-INT8.safetensors exactly as main does. Set to 1, the runtime
quantize path rotates the family's block Linears and the loader asks for
Qwen-Image-2.1-INT8-ConvRot.safetensors first, falling back to the plain file.
The builder defaults to plain again; --convrot-groupsize 256 builds the
rotated artifact over the family spec and uploads it under the ConvRot name.

* Reserve the ConvRot artifact name for the family's runtime spec group

* Trim comments in the ConvRot opt-in changes

* Clear peft's cached torchao probe around the real-peft ConvRot test

peft caches is_torchao_available(); calling inject_adapter_in_model here cached
True, so later tests in the same worker that block torchao.quantization reached
peft 0.18's dispatcher import and failed (test_diffusion_native_quant's peft
and DoRA cases on the CI shard).

---------

Co-authored-by: pre-commit-ci[bot] <66853113+pre-commit-ci[bot]@users.noreply.github.com>

* Grouped-linear LoRA for DeepSeek-V4, remote-code shims for Step-3.7, and a real message for Mistral-format checkpoints (#11528)

* Name a Mistral-format checkpoint instead of reporting two failed config loads

A repo that ships params.json and no config.json is a checkpoint in Mistral's
own format, loaded through mistral-common and vLLM; transformers has no
modeling code for it. Mistral-Large-3 is published that way and its card says
so. AutoConfig and PeftConfig both fail on it, and the generic message pointed
the user at upgrading transformers, which cannot help. The loader now names
the format, says why training is not possible yet and which route works for
inference. Answers false on any doubt, including offline, so the generic
message is never hidden.

* Grouped-linear LoRA and remote-code shims for DeepSeek-V4 and Step-3.7

DeepSeek-V4's grouped output projection subclasses nn.Linear with a
block-diagonal forward, so PEFT's dense LoRA delta had the wrong shape.
GroupedLinearLoRA keeps PEFT's parameters and checkpoint layout and only
groups the forward.

Step-3.7's remote code embeds tokens in get_input_embeddings and returns
no loss from forward; both are repaired on the checkpoint's own classes.

* Repair a remote-code get_output_embeddings that returns None

Step-3.7 delegates it to the inner model, which owns no head, so vocab
repair and resizing dereferenced None. When the class owns an lm_head
and the accessor returns nothing, the head is returned.

* Reach the repaired remote-code forward through an accelerate hook

device_map loading wraps forward before the shims run and keeps the bound
original as _old_forward, so the class-level loss repair was never called
from model(...). Rebind it to the repaired forward.

* Apply the remote-code shims after the offload comment so the hunk merges independently of #11526

Same position in the load sequence: right after from_pretrained and before
the offload decision reads the input embeddings. The two lines that #11526
adds after the load and these two no longer touch, so either PR can merge
first.

* [pre-commit.ci] auto fixes from pre-commit.com hooks

for more information, see https://pre-commit.ci

* Refuse DoRA on grouped linears instead of training it wrong

The grouped LoRA forward computes the plain LoRA sum. With use_dora = True
PEFT still created the magnitude vector, which then never received a
gradient, and PEFT's DoRA-aware merge produced a weight the training forward
had never used. register_grouped_linear_lora now raises NotImplementedError
for a DoRA config, and the forward raises if a LoRA variant reaches it.

Tests: both refusals; fail on the branch before this commit.

* Scope the grouped LoRA mapping to targeted modules, register it on adapter reload, and put the synthesized loss first

register_grouped_linear_lora scanned the whole model, so use_dora = True on a
model that merely contains a grouped linear was refused even when
target_modules never selected it. The scan now goes through PEFT's own
check_target_module_exists, so DoRA on the dense layers of DeepSeek-V4 trains
as before and only a targeted grouped linear is refused.

PEFT's custom module mapping holds class objects and is not part of the saved
adapter config, so a saved DeepSeek-V4 adapter reloaded through
PeftModel.from_pretrained wrapped o_a_proj with the dense LoRA layer again and
hit the original shape mismatch. Both adapter-load paths in loader.py now read
the adapter config, register the mapping on it and pass it to the load.

The synthesized causal LM loss was appended after logits, so output[0] and
to_tuple()[0] were the logits even with labels given; the output is rebuilt
with loss as its first entry.

Tests: DoRA allowed when no grouped linear is targeted (list and regex forms)
and refused for target_modules = None; a saved adapter reloads onto the
grouped forward with identical outputs; loss is the first ordered entry.
Three fail on the previous commit.

* Require a Mistral marker file before claiming the Mistral format, and bind positional labels

params.json alone also describes Meta's original Llama layout, so the format
is claimed only next to tekken.json or consolidated.safetensors. The loss shim
binds the call against the wrapped signature so labels passed positionally
are seen and removed the same as keyword ones.

* Register the fake remote module, gate the Mistral loader test on a real accelerator, pin the reload device

* [pre-commit.ci] auto fixes from pre-commit.com hooks

for more information, see https://pre-commit.ci

* Trim comments

* Keep a remote model's own loss when it returns a tuple

With return_dict = False a forward returns (loss, logits, ...), which the probe did not
recognise, so the model's own objective was replaced by the generic causal loss. A leading
0-d floating tensor now counts as the model's loss. The already-wrapped check also reads the
class's own dict, so a remote subclass of a repaired class is still probed.

* Decide a remote model's loss support per instance, not per class

Two configs of one remote class can differ in whether the model's own loss works, and the
first labelled call used to decide for every instance.

* Refuse an in-place LoRA merge into an fp8 grouped linear

PEFT's merge adds B @ A to the stored weight, but an FP8GroupedLinear's weight is fp8 read
with an unchanged weight_scale_inv. The merge now raises a clear error and leaves the layer
unmerged; bf16 grouped linears merge as before.

* Repair a subclass's own accessor override even when its parent was repaired

The already-repaired checks for get_input_embeddings and get_output_embeddings read the
marker through getattr, so a remote subclass that overrides the accessor inherited its
parent's marker and kept the missing-argument error. Both now read the class's own dict.

* Refuse an fp8 grouped merge before PEFT merges any layer

PEFT merges and unloads layer by layer, so refusing from the grouped layer left earlier
dense layers already merged. merge_and_unload and merge_adapter now check the whole model
first when grouped LoRA is registered.

* Add the SPDX line the other test files carry

* Trim comments further

* Use the SPDX header on the new modules and drop restating docstrings

* [pre-commit.ci] auto fixes from pre-commit.com hooks

for more information, see https://pre-commit.ci

* Reuse the probing call's logits instead of running a remote forward twice

* Reset fan_in_fan_out on grouped LoRA, synthesize a loss only for token-level logits, and cache the fallback only after a working forward

* Drop two restating docstrings

---------

Co-authored-by: pre-commit-ci[bot] <66853113+pre-commit-ci[bot]@users.noreply.github.com>

* Studio: fall back to native when SageAttention does not run on this GPU (#11997)

* Studio: fall back to native when SageAttention does not run on this GPU

diffusers accepts the sage backend at set time on any CUDA card with sageattention >= 2.1.1,
but the kernel dispatches by exact CUDA arch and raises 'Unsupported CUDA architecture' on
cards its build does not serve (the reference 2.2.0 build on sm75 and sm100), so every
generation failed. The supported set differs between builds, so probe the installed kernel
once per device and dtype when sage is requested and fall back to native only when it raises.
An unanswerable probe keeps the request.

* Key the SageAttention probe by the pinned card, not bare cuda

Video loads pin the selected ordinal with set_device and pass device="cuda", so the memo keyed on
the bare name would carry one card's verdict to another on a mixed-GPU host.

* Trim comments in the SageAttention probe

* Keep flash attention off sub-models that do not support it (LFM2.5-VL SigLIP2 tower) (#11959)

* Keep flash attention off sub-models that do not support it (LFM2-VL SigLIP2 tower)

With flash-attn installed, resolve_attention_implementation picks flash_attention_2 whenever
the top-level class supports it. Transformers applies a plain string to every sub-config and
raises at init for a tower that does not, so LFM2.5-VL fails to load:
'Siglip2VisionModel does not support Flash Attention 2 yet'.

Scope flash attention with the mapping form instead: sub-configs whose AutoModel class lacks
flash support get sdpa (or eager). Explicit flash_attention_2 requests are scoped the same way.
Models whose sub-models all support flash keep the plain string.

* [pre-commit.ci] auto fixes from pre-commit.com hooks

for more information, see https://pre-commit.ci

* Trim comments in flash attention sub-config fallback

* Run the LFM2-VL construction test without flash_attn installed

* Fall back to eager when any tower lacks SDPA and Transformers has no attention mapping

* Scope flash attention on encoder-decoder towers named by sub_configs (Donut, TrOCR)

* Use a GPT-2 decoder in the Donut scoping test so it builds on Transformers 5.4

---------

Co-authored-by: pre-commit-ci[bot] <66853113+pre-commit-ci[bot]@users.noreply.github.com>

* Studio: stop trading the denoiser's quantisation away to pay for offload (#11558)

* Studio: stop trading the denoiser's quantisation away to pay for offload

* [pre-commit.ci] auto fixes from pre-commit.com hooks

for more information, see https://pre-commit.ci

* Size the quant replan's text encoder from the loaded pipeline

* Admit a pinned pipeline quant under forced offload in the precision gate

* Trim comments

* Quantise only under whole-module offload, and render it outside inference_mode

* Count runtime headroom when quantising under whole-module offload

* Keep the transformer dense when a text encoder needs streaming

* Trim comments

* Trim comments

* Price a pre-cast text encoder once in the offload quant replan

Main now scales the pre-cast encoder in _candidate_companion_overrides, so
also swapping in the pipe's measured fp8 size discounted it twice (5144 MiB
instead of 10289 MiB for Qwen-Image), under-budgeting the replan.

* [pre-commit.ci] auto fixes from pre-commit.com hooks

for more information, see https://pre-commit.ci

* Keep inference_mode unless whole-module offload moves the quantised weights

A resident transformer beside streamed encoders and the native int8 path under
group offload never move torchao tensors, so they keep main's inference_mode.

* Keep main's gate and protect-lever tests in step with whole-module offload quant

The image gate now admits fp8, nvfp4 and mxfp8 under low_vram and the legacy
cpu_offload flag and still refuses them under balanced. The render's grad
mode is chosen inline so the protect lever test still sees inference_mode in
the with statement that enters protect_ctx.

---------

Co-authored-by: pre-commit-ci[bot] <66853113+pre-commit-ci[bot]@users.noreply.github.com>
Co-authored-by: oobabooga <[email protected]>

* Unsloth Studio: report the VAE decode on the image progress bar (#11740)

The image progress bar now reports the VAE decode. It used to sit on Step N/N while the decode ran inside pipe(), which on a batch reads as a hang.

- Move the decoder hook from video.py into core/inference/media_decode_phase.py and use it for image generation, reset per chunk.
- Add phase to _GenState, generate_progress and DiffusionGenerateProgressResponse (null for engines that report none, such as sd.cpp).
- Show "Decoding…" in the Images progress label, and include phase in the progress dedup so a 1-step render's decode is not dropped.

Fixes #11739.

* Translate the Library toolbar Sort menu in every locale (#12045)

* Read the partial safetensors delete-menu guard by operator, not verbatim (#12042)

* Read the partial safetensors delete-menu guard by operator, not verbatim

* Fail the partial delete-menu guard on any extra conjunct in the stopped-partial branch

* Parse the delete-menu guard with JavaScript's precedence, OR before AND

* Evaluate the partial delete-menu guard instead of matching its shape

* Keep the options menu off a safetensors row with nothing cached

* Keep the partial delete-menu test holding the managed-repo gate

* Resolve the macOS app menu's chords as a Mac in its test (#12046)

* Advertise NVFP4 diffusion on the text encoder driver's mocked host (#12047)

* Keep peft's is_torchao_available cache API through the stale-torchao patch (#12049)

* Keep peft's is_torchao_available cache API through the stale-torchao patch

* Keep the direct-run guard last so it collects the cache API tests

* Run the formatter fixed-point guard's batches side by side (#12050)

* Run the formatter fixed-point guard's batches side by side

* Drive the formatter batches from the test thread so pytest-timeout can stop them

* Stop a timed-out formatter batch's whole process tree

* Hold a timeout across each formatter launch, and publish the probe PID whole

* Let the macOS tab sampler ride out a navigation still in flight after login (#12053)

* Studio: let Deep Research finish a turn handed off from a chat generation (#11923)

* Studio: let Deep Research finish a turn handed off from a chat generation

Deep Research takes over the assistant message of the chat generation
that called the deep_research tool, so that message is referenced by
both a chat_generation_runs row and a research_runs row. The write guard
held every update to it to the generation's monotonic-update rules, even
the research run's own authorized update, so a finished report failed
with "server-managed generation messages cannot be edited" and the run
was marked failed.

Once the generation has settled, exempt the research run's assistant
message from those rules when the caller is the verified research run
(allow_research_update). Active generations and ordinary client edits
are still rejected.

Fixes #11919

* Settle the handed-off generation when research writes its report

* Drop the acknowledgement incomplete mark when research takes over the message

* [pre-commit.ci] auto fixes from pre-commit.com hooks

for more information, see https://pre-commit.ci

---------

Co-authored-by: Nilay Yadav <[email protected]>
Co-authored-by: Nilay <[email protected]>
Co-authored-by: pre-commit-ci[bot] <66853113+pre-commit-ci[bot]@users.noreply.github.com>

* Studio: custom sidebar sections, section menus and drag to reorder (#12016)

* Studio: custom sidebar sections, section menus and drag to reorder

* Studio: flat sidebar and account menus, ChatGPT-style section menu, no Priority sort, even menu padding and row gaps

* Studio: use the standard info icon for About Unsloth

* Studio: sidebar section drag redraws only on a new landing, undo restores a section's place

- A section header drag set state on every pointer move, redrawing the whole sidebar; it now
  sets it only when the landing line moves.
- Undoing Remove section puts the section back above the section that followed it, not at the
  default slot above Projects.
- The section name dialog keeps its title and button while it closes, so a rename no longer
  flips to "New section" as it fades.
- Drops the four organize strings the removed sort menus left unused in every locale.
- The Help icon test fails when a regex misses, instead of comparing two misses as equal.

* Studio: section drag lifts its header and marks the gap, sidebar menus open clear with white rows

Section drag, now useSectionDrag:
- The grabbed header lifts and follows the pointer, the section dims in place, and one line
  glides to the gap above the header it would land on, instead of a line on the block's edge.
- Drawn straight onto the DOM, so the sidebar re-renders once, on the drop.
- As the row drag: pointer capture, edge scroll from the frame loop, one gesture per pointer,
  and Escape puts it down without the release folding the section.
- The dropped section slides into its slot, unless motion is reduced.

Sidebar and account menus:
- Submenus open 6px clear of their menu with their first row level with the trigger; the
  offset was measured from the trigger row, so every one overlapped its menu.
- Dark surface a step lighter, rows in full white, and tick rows hover like the rest.
- Ticks sit as far in from the right as the text from the left.
- No section gets an icon so its text lines up with the rows below.

* Studio: trailing menu glyphs sit level with the row's icon, chat and folder drags lift the row, layer icon for sections

Submenu chevrons, ticks and shortcuts end as far from a row's right edge as its icon starts from
the left, in every dropdown, context menu, menubar, select, combobox and command list. The arrow
and tick are drawn inset like a leading icon (MenuChevronRightIcon, MenuTickIcon) and set flush on
the row's own padding, so they line up at any icon size instead of by a pixel pull; shortcuts
take back the trailing letter-spacing.

A carried chat or project folder lifts a copy of its row that follows the pointer, as a section
header does, while the row it came from dims; the drop slides it into its slot, a folder's open
chats with it. The copy is drawn and moved outside React, so the sidebar does not redraw per move.

* Studio: menu hover pills sit the same distance from both edges at every UI size

A menu's padding and the margin that aligns it to its trigger scale with the UI font size, so at
any size but the default they were fractional (8px is 7.47px at 14). Chromium draws a row's
rounded hover pill on whole CSS pixels while the menu keeps its fraction, leaving the pill a device
pixel nearer one edge; Firefox does the same for a fractional width. Dropdown, context menu,
menubar and select surfaces round their side padding and margin as they mount, and the default
dropdown and account menu widths round to whole pixels.

* Studio: popover pickers and comboboxes keep the hover pill centred too

The model picker's panel is padded 16px on the left but 8px on the right (16px with external
providers) so its scroller runs near the edge for its scrollbar, leaving every row 18px from the
left and 14px from the right; the list's own right inset now makes up the difference.

Popover and combobox surfaces get the same whole-pixel treatment as menus, and every surface now
balances by its rows' measured inset rather than rounding each layer: a picker's rows sit in lists
inside the surface, and rounding the layers one by one could round the two sides apart. Insets
meant to match land on the same whole pixel; a bare surface around a padded list rounds up; a list
still loading is waited for, briefly.

* Studio sidebar: address review on section filing, hidden Projects, keyboard reorder

- A pinned row keeps its section while Pinned draws it; its section menu now offers that section so filing there unpins it back.
- A hidden Projects section no longer feeds its chats to the keyboard walk and selection.
- Alt+Up/Down on a section header moves the section.
- Saved sections keyed like Pinned or Projects are dropped; automatic project sorts fall back to Manual.
- A chat filed from its menu during a drop into a folder keeps that filing; undo restores a removed section in drawn order; the bottom fade re-measures as custom sections change.

* Studio sidebar: show where a carried chat lands, and let it land past the end of Recents

The lifted copy of a dragged row covered the spot it was aimed at, so the insertion line under the last row, and the outline of a folder about to take the chat, were hidden. Each cue's border is now drawn again above the copy, as the section drag draws its line.

Recents had nowhere to aim past its last row: releasing just below it, or in the empty sidebar underneath, did nothing. It now draws an end strip like Pinned and custom sections, and the empty list below it aims there.

* Studio sidebar: Remove from section only where a row is in one

The Section submenu always listed a greyed-out "No section" on rows filed nowhere, which read as a status label rather than an action. It is now "Remove from section", shown only when the row is drawn in a section it was filed in; a pinned row, drawn in Pinned, does not get it.

* Studio sidebar: one Move to submenu for projects and sections

A chat's row menu had separate Project and Section submenus. They are now one "Move to": New project, New section and Project sources above the rule, then the projects and the sections under their own headings. The greyed-out "Recents" destination becomes "Remove from project", shown only when the chat is in one, as Remove from section is. Folder rows and selections, which only sections take, use the same Move to name.

* Studio sidebar: chat and folder drags only change how the drag looks

Reverts every change this branch made to how a dragged chat or folder is handled, keeping only the section-style indicator: the row lifts as a copy that follows the pointer, the row it came from dims, and the drop line or outline is drawn above the copy.

Reverted: the slide into place after a drop, the end strip under Recents and the drop into the empty sidebar below it, and the drop's stand-down for a section filed from the menu while its move was in flight. Drops land and commit exactly as before.

* Revert "Studio sidebar: chat and folder drags only change how the drag looks"

This reverts commit 8508797e92d8ee860eecb04db689c51fab6b5f7e.

* Studio sidebar: tell a drop into a project from one below it

Under a project's last chat, a line meant either "into the project, last" or "below the project, in its list", drawn the same in the same place. A line that lands inside a project now starts where its chats' names do and outlines the project, a reorder among its own chats included; one that lands below it runs the full width with no outline. Only the cue changes: where a drop lands is as before.

* Studio sidebar: Move to groups projects and sections, New first and Remove last

Each group has its heading, its New (the same + icon for both, and no ellipsis on New section), its destinations, and its Remove last, shown only when the chat is in a project or section to leave. Project sources is no longer in the menu.

* Studio sidebar: Move to names what a row leaves, and its lists scroll

"Remove from project" and "Remove from section" now name the project or section ("Remove from Website"); a selection spread over several sections keeps "Remove from section".

The submenu had no height limit: with 40 projects it ran past the window and the Sections group and both Removes could not be reached. Each group's list now scrolls past about seven rows, the next half showing, without a scrollbar that would take the rows' right padding, and the submenu as a whole stays inside the window.

* Studio sidebar: Move to leaves out where a row already is; more room above menu headings

The project or section a row is already in is no longer listed, greyed out, as a place to move it to. Sidebar menu headings get 8px above them (was 4px), so they read with the rows below rather than the rule above.

* Studio sidebar: X for Move to's Remove, one gap between every row

Remove from <project/section> uses the X icon. The scrolling project and section lists kept their rows' 2px margins from meeting the rows beside them, so New project, New section and Remove sat 4px away where every other row sits 2px; the lists give that 2px back.

* Sidebar drag: stop whole-page restyles on drag start and drop, anchor lifted copies

Marking a drag with a body class, and adding or removing drag visuals as body
children, restyled every element on the page (about 230ms under 4x CPU
throttle with a long chat open), which made section and row drags hitch as
they started and ended. The drag is now marked on the sidebar (or the model
picker's list), text selection is refused via selectstart, and the lifted
copy, cue overlays and section line live in one persistent fixed layer.

The lifted copies and section line are placed by top where they lift, so a
frame drawn before the first transform can no longer show them at the top of
the window.

* Sidebar: cog for a project's Edit; a folder's section submenu is Section

A project…
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.

2 participants