Repository navigation
Hand a composition with no forward of its own to its thinker (Qwen3-Omni) - #11523
Conversation
…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.
Codex Review SummaryThis comment shows the latest Codex review activity on this pull request.
ℹ️ About Codex in GitHubYour team has set up Codex to review pull requests in this repo. Reviews are triggered when you
Codex reacts with 👀 while any review is running, comments if it has suggestions, and reacts with 👍 once all reviews finish with no findings. |
…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.
c2a15cb to
76da9d1
Compare
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.
7896f59 to
ddfadbe
Compare
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.
4fb9653 to
41890e1
Compare
|
@codex security review |
…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.
fc1275a to
e93640f
Compare
…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.
e4c76e8 to
64f286b
Compare
…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.
64f286b to
f405716
Compare
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.
# Conflicts: # unsloth/models/loader.py # unsloth/models/vision.py
|
Codex Review: Didn't find any major issues. Keep them coming! Reviewed commit: ℹ️ About Codex in GitHubYour team has set up Codex to review pull requests in this repo. Reviews are triggered when you
If Codex has suggestions, it will comment; otherwise it will react with 👍. Codex can also answer questions or update the PR. Try commenting "@codex address that feedback". |
… only in remote code
…orwards its locals() as keywords, which broke every push_to_hub_merged
…es torch.cuda.is_available() true
|
@codex review |
1 similar comment
|
@codex review |
There was a problem hiding this comment.
💡 Codex Review
Here are some automated review suggestions for this pull request.
Reviewed commit: 703b92b91e
ℹ️ 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".
| if _total_layers is None and isinstance(_core_name, str): | ||
| # A kept wrapper's config nests the count (Qwen3-Omni: thinker.config.text_config). | ||
| _total_layers = _get_total_transformer_layers(getattr(model, _core_name, None)) |
There was a problem hiding this comment.
Keep last-layer selection compatible with the generated regex
On a retained Qwen3-Omni wrapper, finetune_last_n_layers now reaches this fallback and populates layers_to_transform, but both the default target selection and the newly scoped explicit-list path produce a regex string. The supported PEFT LoraConfig rejects that combination with ValueError: `layers_to_transform` cannot be used when `target_modules` is a str., so every attempt to use finetune_last_n_layers on this newly supported wrapper fails during adapter construction. The layer restriction needs to be incorporated into the regex or the target representation must remain list-based.
Useful? React with 👍 / 👎.
There was a problem hiding this comment.
Not in this PR: finetune_last_n_layers with the default (regex) targets raises the same layers_to_transform ValueError on main for every model, e.g. tiny Qwen3 through FastBaseModel.get_peft_model. It is a pre-existing limitation of that option, not something the kept-wrapper path introduced; it needs its own fix that folds the layer range into the regex.
…scope modules_to_save to the text core
|
@codex review |
1 similar comment
|
@codex review |
# Conflicts: # unsloth/models/vision.py
There was a problem hiding this comment.
💡 Codex Review
Here are some automated review suggestions for this pull request.
Reviewed commit: 2ae6a74d36
ℹ️ 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".
| elif ( | ||
| is_vlm | ||
| and resolve_model_class(AutoModelForCausalLM, model_config) is None | ||
| and _resolve_omni_auto_model(model_config) is not None | ||
| ): |
There was a problem hiding this comment.
Resolve Omni before offline FP8 quantization
When text_only=True is combined with on-the-fly load_in_fp8 for an unmapped Qwen3-Omni checkpoint, this special case is reached too late: FastModel.from_pretrained first calls _offline_quantize_to_fp8, which sees the Omni architecture as multimodal but no top-level vision_config and therefore loads it with AutoModelForImageTextToText. Qwen3-Omni is mapped through AutoModelForTextToWaveform, as _resolve_omni_auto_model documents, so that preliminary load raises an unrecognized-configuration error and the newly supported text-only path never runs. The offline FP8 loader needs to use the same Omni auto-class resolution (and preserve the caller's text intent).
Useful? React with 👍 / 👎.
There was a problem hiding this comment.
Not in this PR: on-the-fly FP8 has its own preliminary loader, and Qwen3-Omni does not load on main through any path. This PR adds bf16/4-bit training for these compositions and makes no FP8 claim; routing the offline FP8 quantizer through the Omni auto class is a separate change.
…, keep a kept wrapper's siblings frozen after full-finetuning setup, and scope explicit target_parameters to the text core
|
@codex review |
|
Codex Review: Didn't find any major issues. 🚀 Reviewed commit: ℹ️ About Codex in GitHubYour team has set up Codex to review pull requests in this repo. Reviews are triggered when you
If Codex has suggestions, it will comment; otherwise it will react with 👍. Codex can also answer questions or update the PR. Try commenting "@codex address that feedback". |
…mni) (unslothai#11523) * Let a remote-code from_pretrained cast a 4-bit model's unquantized floats microsoft/Phi-4-reasoning-vision-15B overrides from_pretrained and ends it with model.to(dtype), where dtype falls back to the model's own dtype. transformers refuses every dtype cast on a bitsandbytes model, so the 4-bit load stopped with "You cannot cast a bitsandbytes model in a new dtype" while the 16-bit load was fine. For the duration of Unsloth's own from_pretrained call, and only when the model is loaded with trust_remote_code in 4-bit or 8-bit, PreTrainedModel.to casts the floating tensors that are not packed bitsandbytes weights (Params4bit with a quant_state, Int8Params with an SCB) and leaves the packed weights alone. Device moves and unquantized models keep transformers' own path, and the original method is restored when the load returns. * Keep padding-free off a forward that cannot take packed_seq_lengths, and let a wrapper inherit gradient checkpointing support Padding-free batching adds packed_seq_lengths to every batch. A remote-code forward with a fixed signature (microsoft/Phi-4-reasoning-vision-15B) raised "got an unexpected keyword argument 'packed_seq_lengths'" on the first step after the 4-bit load was fixed. Auto padding-free and packing now stay off when the model's forward, looked through PEFT, accepts neither that key nor **kwargs; a string model or an unreadable signature leaves the decision as it was. nvidia/Nemotron-3-Nano-Omni-30B-A3B wraps a complete NemotronHForCausalLM in a PreTrainedModel that keeps transformers' default supports_gradient_checkpointing = False, so Trainer's gradient_checkpointing_enable raised "does not support gradient checkpointing" although every layer underneath supports it. After the load, a wrapper that says no while a nested model says yes now says yes on the instance; transformers enables checkpointing by walking modules, so every layer is switched on as before. * Train the language model of a wrapper whose forward cannot take a text batch nvidia/Nemotron-3-Nano-Omni-30B-A3B wraps a complete NemotronHForCausalLM as language_model behind a forward whose first parameter, pixel_values, has no default and whose body indexes image_flags. A text-only SFT batch stopped on the first step with "missing 1 required positional argument: 'pixel_values'" once the load, the LoRA targets and the trainer setup were fixed. After the load, a wrapper whose forward requires an input that a text batch does not carry, with exactly one direct child that is a PreTrainedModel with its own forward and both embedding accessors (language_model or thinker when several qualify), hands training to that child, and the generation-time siblings are dropped so their weights are freed. Every transformers VLM defaults its image inputs to None and is returned unchanged, as is anything ambiguous. UNSLOTH_KEEP_COMPOSED_WRAPPER=1 turns this off. * Recognise gradient checkpointing support from transformers' checkpointing layer NemotronHForCausalLM's remote code builds every NemotronHBlock on transformers' GradientCheckpointingLayer but never sets supports_gradient_checkpointing on the model class, so Trainer's gradient_checkpointing_enable raised "NemotronHForCausalLM does not support gradient checkpointing" once training reached it. A model built on that layer now counts as supporting it, alongside a nested model that says so itself. * [pre-commit.ci] auto fixes from pre-commit.com hooks for more information, see https://pre-commit.ci * [pre-commit.ci] auto fixes from pre-commit.com hooks for more information, see https://pre-commit.ci * Carry the wrapper's loader state onto the core that replaces it from_pretrained records is_loaded_in_4bit, is_quantized, quantization_method, hf_quantizer and hf_device_map on the object it returns, not on its children. PEFT reads is_loaded_in_4bit off the model it is given to pick lora.bnb.Linear4bit over the plain lora.Linear, so a core returned without the flags trained through the wrong LoRA layer: the forward ran, but merging wrote a 16-bit delta into packed 4-bit weights and the fast QLoRA path was skipped. The flags now move to the core, the device map is re-keyed from the wrapper's names to the core's, and the wrapper config's quantization_config is carried so a saved core still says it is 4-bit. Tests: the carried state on a synthetic wrapper, no state invented when the wrapper has none, and PEFT dispatching Linear4bit on a real 4-bit core; the last two fail on the branch before this commit. * Keep the composed wrapper when the load asked for the multimodal model Unwrapping a wrapper whose forward requires pixel_values was unconditional, so a FastVisionModel load of Nemotron-Omni meant for image batches lost its vision tower at load and trained the text core. The unwrap now runs only when the load carries text intent: text_only = True, or a model with no vision config. A multimodal load keeps the wrapper and prints the text_only hint, and the UNSLOTH_KEEP_COMPOSED_WRAPPER opt-out is unchanged. The two new test files also get the SPDX line the other tests carry. Test: text_intent = False returns the wrapper with its vision tower and names text_only = True; a wrapper that takes a text batch prints nothing. * Keep an unquantized keyword cast inside the tolerated load, and read the bound forward for the packing gate _tolerate_dtype_cast_on_quantized_model popped dtype out of kwargs and then, on an ordinary model, handed the call on without it, so model.to(dtype = ...) made inside a remote-code from_pretrained was a silent no-op: the model stayed float32. The pass-through now forwards the call exactly as it arrived. _forward_accepts_packed_seq_lengths read type(model).forward, which on an nn.Module is never absent (it falls back to _forward_unimplemented, whose signature takes no keywords), so a torch.compile'd model, which sets forward on the instance, was read as a fixed signature and padding-free was switched off for every compiled model. It now reads the bound forward first, as the merged _forward_accepts_packing_kwargs does. Tests: the three cast spellings on an unquantized model inside the context, a compiled kwargs forward keeps padding-free, and the fixed-signature control. Three fail on the previous commit. * Unwrap a remote-code composition only when the caller asks for text training The gate keyed off the wrapper's vision_config, which an audio-only composition does not have either, so a multimodal load still lost its wrapper. Only the caller knows the intent: unwrap on text_only = True and keep the composition whole otherwise. * Carry the caller's text intent past the loader's normalisation, and count token_type_ids as text loader.py turns text_only off for a family without its own text decoder so the full wrapper loads, and forwarded that normalised value as the intent: a text_only request for such a model kept a wrapper whose forward needs pixel_values. The caller's own request now travels separately. token_type_ids is a standard tokenizer field the Trainer supplies, so a wrapper that requires it can take a text batch and is not unwrapped. * Only a field the collator supplies excuses a required forward parameter A required cache_position, use_cache, past_key_values or return_dict is not something the Trainer puts in a text batch, so a forward that demands one without a default cannot take a text batch either. * Hand a composition with no forward of its own to its thinker Qwen3OmniMoeForConditionalGeneration composes a thinker, a talker and a speech decoder and only generates, so a trainer's forward reached nn.Module.forward. The text-core handoff now treats a wrapper with no forward the same as one whose forward cannot take a text batch. * Hand over a composition with no forward regardless of load intent The multimodal gate keeps a wrapper whose forward takes image batches; a composition with no forward trains nothing on any batch, so it always goes to its thinker. Test added. * Add the SPDX line the other test files carry * Keep the composition whole on a multimodal load A load without text intent may still generate through the wrapper, and Qwen3-Omni does that with its talker and speech decoder, so the handoff to the thinker now happens only when the load asked for the text model. The multimodal load prints the text_only hint instead. Test updated. * [pre-commit.ci] auto fixes from pre-commit.com hooks for more information, see https://pre-commit.ci * [pre-commit.ci] auto fixes from pre-commit.com hooks for more information, see https://pre-commit.ci * [pre-commit.ci] auto fixes from pre-commit.com hooks for more information, see https://pre-commit.ci * [pre-commit.ci] auto fixes from pre-commit.com hooks for more information, see https://pre-commit.ci * Carry the checkpoint identity onto the thinker PEFT copies name_or_path into the adapter's base_model_name_or_path, and a thinker built from thinker_config has none, so a saved adapter pointed at an empty base model. The wrapper's name is carried over with the loader state. * [pre-commit.ci] auto fixes from pre-commit.com hooks for more information, see https://pre-commit.ci * Find a thinker by its lm_head when its output accessor says None transformers 4.x returns None from get_output_embeddings unless a class overrides it, and Qwen3-Omni's thinker only overrides the input side. * [pre-commit.ci] auto fixes from pre-commit.com hooks for more information, see https://pre-commit.ci * Trim comments * Trim comments * Free memory through clean_gpu_cache() in _text_trainable_core torch.cuda.empty_cache() skipped XPU and failed the shared cache dispatch test. * Load Qwen3-Omni with text_only, and give a kept wrapper a text forward text_only = True sent Qwen3-Omni to AutoModelForCausalLM because its vision config sits under thinker_config, so the hint the multimodal load prints pointed at a path that raised "Unrecognized configuration class". It now loads through the composition's own auto class and the text intent hands it to the thinker, as the hint says. A default load keeps the wrapper for audio generation. It now takes the thinker's forward and embedding accessors on the instance, so eval, KD and a custom loop can call model(input_ids = ...), and get_peft_model scopes LoRA to thinker.model instead of only the vision tower. A thinker built from a sub-config also gets its architectures, which generate reads. * Reload a thinker-only Qwen3-Omni adapter onto the thinker An adapter trained with text_only = True has targets and weights rooted at model.layers, which a default reload of the composition names thinker.model.layers, so PEFT found no targets. Unsloth's target regex for a kept wrapper names thinker.model; one trained on the thinker alone never names thinker, so an Omni base reloaded for such an adapter loads as text_only. * [pre-commit.ci] auto fixes from pre-commit.com hooks for more information, see https://pre-commit.ci * Decide a Qwen3-Omni adapter's reload target from its saved weight keys A leaf-name list such as ["q_proj", "v_proj"] reloads as a set that matches either layout, so the regex alone could not tell a thinker-trained adapter from a wrapper-trained one. Read the tensor names from the adapter's safetensors header (locally, or the Hub metadata): thinker-trained keys never contain thinker., wrapper-trained keys always do. The regex check stays as the fallback when the keys cannot be read. * [pre-commit.ci] auto fixes from pre-commit.com hooks for more information, see https://pre-commit.ci * Read a Hub adapter's keys from adapter_model.safetensors get_safetensors_metadata only looks for model.safetensors, so every Hub adapter raised NotASafetensorsRepoError and fell back to the regex. Read the header of adapter_model.safetensors by name instead, and read a local adapter_model.bin's keys on the meta device. * [pre-commit.ci] auto fixes from pre-commit.com hooks for more information, see https://pre-commit.ci * Keep audio-only Omni adapters on the wrapper, and read cached adapters offline Decide from the first key segment after base_model.model.: a key rooted at any of the composition's children (thinker, talker, code2wav, from its sub-configs) means the adapter was trained on the kept wrapper, so an audio-only adapter is no longer mistaken for a thinker one. Look in the Hub cache before the network, so local_files_only still reads the saved keys. * [pre-commit.ci] auto fixes from pre-commit.com hooks for more information, see https://pre-commit.ci * Resolve an Omni adapter's weight file with hf_hub_download, either format PEFT fetches the same file right after, so resolve adapter_model.safetensors and then adapter_model.bin through hf_hub_download (cache first, offline honoured) and read their names without materialising weights. When no file can be read and the targets are a leaf list, say how to load a thinker-only adapter instead of guessing. * [pre-commit.ci] auto fixes from pre-commit.com hooks for more information, see https://pre-commit.ci * Gate the CUDA-only tests on the real accelerator probe, not the spoofable torch.cuda check * Gate the CUDA-only tests on the real accelerator probe, not the spoofable torch.cuda check * Drop the duplicate inspect import in vision.py * Trim comments * Trim comments * Drop the packed_seq_lengths gate: unslothai#11468's _forward_accepts_packing_kwargs already refuses every shape it does * Append text_intent after the existing from_pretrained parameters so their positions do not move * Carry the wrapper dtype and repo path onto a text core, engage the cast shim for quantization_config loads, refuse merged saves of a text core * [pre-commit.ci] auto fixes from pre-commit.com hooks for more information, see https://pre-commit.ci * Redirect adapter reloads only for forward-less compositions, and target the thinker's experts on a kept wrapper * Limit the cast shim to bitsandbytes, carry the wrapper generation_config to the text core, accept every adapter save spelling * Freeze a kept wrapper's unused siblings, and read finetune_last_n_layers' layer count through the text core * Scope explicit LoRA leaves on a kept wrapper to its text core, and delegate the embedding setters so vocab resizing works * Refuse only PEFT merges of a text core: a full finetune saves its resident weights * Refuse a full-finetuned text core's merged save when its class exists only in remote code * Move the text-core save refusal into a helper: unsloth_generic_save forwards its locals() as keywords, which broke every push_to_hub_merged * Gate the Qwen3-Omni GPU tests on has_real_cuda: the CI CUDA spoof makes torch.cuda.is_available() true * On a kept wrapper, pass qualified LoRA targets to PEFT unchanged and scope modules_to_save to the text core * Forward the trust decision through the forwardless-composition probes, keep a kept wrapper's siblings frozen after full-finetuning setup, and scope explicit target_parameters to the text core --------- Co-authored-by: pre-commit-ci[bot] <66853113+pre-commit-ci[bot]@users.noreply.github.com>
What
Qwen3OmniMoeForConditionalGenerationcomposes a thinker (the language model with its vision and audio towers), a talker and a speech decoder, and defines noforwardof its own: it only generates. A trainer callingmodel(input_ids = ...)reachednn.Module.forwardand failed with_forward_unimplemented() got an unexpected keyword argument 'input_ids', on both the 4-bit and 16-bit cells and on the plain transformers baseline.#11526 already hands training to a wrapper's language model when the wrapper's forward requires an input a text batch does not carry. A wrapper with no forward at all is the same situation, so this extends
_text_trainable_coreto treat it that way: when the loaded class has no forward and exactly one direct child is aPreTrainedModelwith a forward and both embedding accessors (thinkerwhen that name exists), training uses that child and the generation-only siblings are freed. Fine-tuning Qwen3-Omni means fine-tuning the thinker; transformers' own recipes trainmodel.thinkerand save a thinker checkpoint. Everything else keeps #11526's behaviour, includingUNSLOTH_KEEP_COMPOSED_WRAPPER=1.Stacked on #11526 (branch
phi4-vision-4bit-cast) so the two edits to the same region do not compete; it rebases cleanly onto main once #11526 lands. Loading an omni checkpoint throughFastModelat all needs #11467, which is merged.Verification
Differential on
optimum-intel-internal-testing/tiny-random-qwen3-omni, one process per arm, with #11467 in both arms:Qwen/Qwen3-Omni-30B-A3B-Instruct, 16-bit LoRA, seq 512, 10 steps on one B200:
The 4-bit cell now gets past the forward and stops in the expert path:
Qwen3OmniMoeThinkerTextExpertsis not one of the expert families the zoo patches, so its packed NF4 weights reach transformers' grouped_mm forward (Expected mat_a to be Float32, BFloat16 or Float16 matrix, got Byte). That is the structural expert dispatch being fixed separately and is not specific to this change.tests/test_omni_trains_through_thinker.py: the no-forward composition hands off to the thinker, a model with a text forward is unchanged, an ambiguous composition is left alone, the off switch keeps the wrapper. #11526's 19 tests still pass.text_only=True and the default load
text_only=Trueused to fail with "Unrecognized configuration class": the Omni config keeps its vision config underthinker_config, so the loader pickedAutoModelForCausalLM. It now loads through the model's own auto class and hands the thinker over at load. That input was a hard error before, so nothing that worked changes.get_peft_modelalso targetsthinker.model; before this LoRA only reached the vision tower and the text gradients were 0.architecturesentry, and generate tolerates a missing one.UNSLOTH_KEEP_COMPOSED_WRAPPER=1still turns all of this off.Qwen/Qwen3-Omni-30B-A3B-Instruct in 4-bit on one B200:
return_audio=False(transformers' wrapper generates audio by default)3 QLoRA steps: 1.103, 0.667, 1.172.
tests/test_omni_text_only_load.py(9 tests) builds a tiny real Qwen3-Omni; with the source reverted 8 of 9 fail. 48 passed on transformers 5.17 and 5.4, 45 passed and 3 skipped on 4.57.6 CPU.Compatibility
transformers 4.57.6 and 5.x, TRL 0.22.2 and 1.x, PEFT 0.18 to 0.21, torch 2.6 and later. Pure Python on the load path, no kernels, so Linux, Mac, Windows, WSL and every accelerator behave the same.
Follow-up fixes
Gemma3ForCausalLMwithout its vision tower (max logit difference 0.18 against the trained model). It reloads asGemma3ForConditionalGenerationagain (0.0098, the same as main).Qwen3OmniMoeConfigkeepsnum_expertsunderthinker_config, so the wrapper was not detected as MoE and only attention was trained. The expert parameters are named by full path underthinkerso the talker's experts stay untouched. Default andtext_onlyloads of tiny Qwen3-Omni now train the same 22,528 parameters with identical losses (11.904, 11.924, 11.922, 11.913, 11.902).text_onlyis refused instead of silently writing the unmerged thinker; the LoRA adapter reloads withtext_only = True(max logit difference 0.0039).