Repository navigation
Fine-tune Whisper, Canary, Moonshine, CTC, audio classification, Dia and Higgs Audio through FastModel by default - #14744
Conversation
…nerate (CTC, audio classification)
… and warn when an audio processor needs a missing library
…and Canary train by default
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. |
… extractors right padded, refuse a second get_peft_model on a generic PeftModel
|
@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: 995f1118db
ℹ️ 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 any(type(m).__name__ in ("Linear4bit", "Linear8bitLt") for m in child.modules()): | ||
| continue |
There was a problem hiding this comment.
Keep quantized task projectors trainable
For 4-bit or 8-bit Wav2Vec2ForSequenceClassification and Wav2Vec2ForXVector loads, task-head components such as the top-level projector, tdnn, and feature_extractor are converted to Linear4bit/Linear8bitLt, so this branch discards them from modules_to_save. The automatic target regex also excludes these one-off projection layers as heads (and TDNN explicitly cannot use LoRA), leaving most of the task head frozen while only the unquantized classifier is trained and saved. Keep detected task-head subtrees unquantized or otherwise make their parameters trainable and saveable instead of omitting them under QLoRA.
Useful? React with 👍 / 👎.
There was a problem hiding this comment.
QLoRA on these small audio classifiers is a rare setup; the classifier itself is trained and saved, and a quantized projector stays frozen as before. Not widening the skip list for it.
| for name, child in model.named_children(): | ||
| if child is backbone or next(child.parameters(), None) is None: |
There was a problem hiding this comment.
Preserve direct task-head parameters
When audio classifiers, frame classifiers, or XVector models set config.use_weighted_layer_sum=True, Transformers stores the trainable layer_weights directly on the top-level model as an nn.Parameter, not as a child module. Iterating only over named_children() never discovers it; generic PEFT then freezes it with the rest of the base parameters, and it is neither trained nor included in the adapter. Include direct non-backbone task-head parameters in the automatic train-and-save handling so weighted layer aggregation can adapt.
Useful? React with 👍 / 👎.
There was a problem hiding this comment.
use_weighted_layer_sum is off by default for these heads; not handling that opt-in here.
… encoders on LoRA only, keep audio_processor processors on the tokenizer fallback
|
@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: 2f46cab6b4
ℹ️ 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".
| import transformers | ||
| for name in _AUDIO_AUTO_CLASS_NAMES: | ||
| try: | ||
| if type(config) in getattr(transformers, name)._model_mapping: | ||
| return True |
There was a problem hiding this comment.
Recognize remote-code audio mappings when choosing processors
For a trust_remote_code checkpoint that registers AutoModelForCTC or an audio-classification class only through config.auto_map, this native _model_mapping membership test returns false even though _resolve_audio_auto_model can resolve and select that remote class. needs_processor therefore remains false and the load uses AutoTokenizer; when the speech repository also contains a tokenizer, that succeeds but returns no feature extractor, leaving callers unable to construct audio inputs. Include remote auto_map/resolve_model_class mappings or directly recognize the selected audio auto class.
Useful? React with 👍 / 👎.
There was a problem hiding this comment.
Remote-code CTC or audio classification checkpoints are rare; not widening the processor probe for them here.
| if task_type in (TaskType.CAUSAL_LM, TaskType.SEQ_2_SEQ_LM) and ( | ||
| _is_speech_forward(model) or _cannot_generate | ||
| ): |
There was a problem hiding this comment.
Use the generic wrapper for audio SEQ_CLS requests
When a caller naturally passes task_type=TaskType.SEQ_CLS for an audio classifier, this condition does not clear the task type, so PEFT creates PeftModelForSequenceClassification. That wrapper forwards input_ids and inputs_embeds to the base model, while Wav2Vec2/AST classifiers accept input_values or input_features, causing every training forward to fail with an unexpected-argument error. Audio forwards should use the generic wrapper regardless of the requested PEFT classification task type, while retaining the automatic head-saving behavior.
Useful? React with 👍 / 👎.
There was a problem hiding this comment.
Not reproducible: on peft 0.21.2 + transformers 5.17, PeftModelForSequenceClassification on ASTForAudioClassification and Wav2Vec2ForSequenceClassification with input_values trains fine (finite loss, classifier in modules_to_save); input_ids = None lands in the model's **kwargs and is ignored.
|
pre-commit.ci run |
…ind Whisper classifier heads, skip names the backbone shares, load TDT models with their processor
|
@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: 789648ba2e
ℹ️ 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".
| auto_model = AutoModelForSequenceClassification | ||
| # Audio classifiers (AST, wav2vec2) map only under the audio classification auto class. | ||
| if resolve_model_class(auto_model, model_config, **_probe_hub_kwargs) is None: |
There was a problem hiding this comment.
Preserve specialized audio heads when changing label counts
When num_labels is supplied for a Wav2Vec2ForAudioFrameClassification or Wav2Vec2ForXVector checkpoint, Wav2Vec2Config also has a valid AutoModelForSequenceClassification mapping, so this fallback is skipped and the loader silently replaces the checkpoint's frame-level or XVector architecture with the sequence-classification model. That changes the task semantics and leaves the specialized checkpoint head unused or mismatched precisely when callers adjust its label set; architecture-specific audio resolution needs to run before this generic shortcut.
Useful? React with 👍 / 👎.
There was a problem hiding this comment.
num_labels on frame-classification or XVector checkpoints is a rare setup; leaving the sequence-classification shortcut as is for those.
…perForAudioClassification); mark the live Hub test slow
|
@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: 84732b584b
ℹ️ 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".
| tokenizer.padding_side = _padding_side | ||
| # A bare audio feature extractor pads waveforms, which must stay right padded (AutoProcessor's | ||
| # fallback to it keeps the padding_side = "left" we passed). | ||
| tokenizer.padding_side = "right" if _is_bare_feature_extractor(tokenizer) else _padding_side |
There was a problem hiding this comment.
Reset audio_processor frontends to right padding
When a processor exposes its audio frontend as audio_processor rather than feature_extractor (for example, Granite Speech), this leaves that frontend with the padding_side="left" supplied during loading: the bare-extractor special case does not apply to a processor wrapper, and the correction below only inspects feature_extractor. Such processors can therefore left-pad waveforms, shifting audio relative to masks or model expectations; normalize the audio_processor component to right padding as well.
Useful? React with 👍 / 👎.
There was a problem hiding this comment.
Fixed in b9f9261: audio_processor frontends are reset to right padding along with feature_extractor.
…tion format-insensitive
|
@codex review |
1 similar comment
|
@codex review |
|
Codex Review: Didn't find any major issues. Chef's kiss. 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". |
…helpers in the processor-selection test harness
…ough FastModel (unslothai#14781) Four audio models could not be loaded through `FastModel.from_pretrained` at all. This PR fixes the two causes. ## What was broken | Model | Before | Cause | |---|---|---| | VibeVoice-ASR | `ValueError: VibeVoiceAcousticTokenizerEncoderModel does not support an attention implementation through torch.nn.functional.scaled_dot_product_attention yet` | `resolve_attention_implementation` returns a plain `"sdpa"`, which transformers applies to every sub-config, including towers that cannot run SDPA. | | MusicGen | `ValueError: EncodecModel does not support ... scaled_dot_product_attention yet` | Same: the EnCodec audio encoder has no SDPA path. | | Audio Flamingo 3, Music Flamingo | `ValueError: Unrecognized configuration class AudioFlamingo3Config ...` | On transformers 5.x they register only under `AutoModelForSeq2SeqLM`, so the loader's fallback chain ended at `AutoModelForImageTextToText`. | ## Changes - `vision.py`: the sub-config class lookup the flash-attention scoping already does is now one shared generator, and a new `_scoped_sdpa` gives towers without SDPA `eager` through transformers' per-sub-config attention dict while every other tower keeps SDPA. Applied wherever the resolver settles on `"sdpa"`; transformers versions without the dict mapping get `eager`. - `loader.py`: `_resolve_audio_lm_auto_model` sits just before the final fallback and accepts `AutoModelForCausalLM` / `AutoModelForSeq2SeqLM` only when it builds the config's own class and the config has an `audio_config`, so the only path it can change is today's crash. - `vision.py`: `_audio_lm_class` makes processor selection pick `AutoProcessor` for those loads. Over the 114 SDPA-capable composite configs in transformers 5.17, the SDPA scoping changes only VibeVoice-ASR and VibeVoice TTS (0 false positives). ## Evidence Tiny random-weight copies (real config shrunk, real processor), 5 training steps per case on a Colab GPU in bf16, `main` vs this branch: | Model | LoRA 16 bit before / after | QLoRA 4 bit before / after | |---|---|---| | VibeVoice-ASR | load error / pass | load error / pass | | Audio Flamingo 3 | load error / pass | load error / pass | | Music Flamingo | load error / pass | load error / pass | | MusicGen | load error / loads and trains (eager) | load error / loads and trains (eager) | | Qwen2-Audio, Qwen3-ASR (controls) | pass / pass | pass / pass | MusicGen's compiled path also needs unslothai/unsloth-zoo#1978 (absolute imports in the generated module, EnCodec's LSTM left uncompiled, label masking only over matching positions); with both, MusicGen LoRA and QLoRA train compiled with 0 graph breaks. 14 models that already loaded (Whisper, Qwen2-Audio, Qwen3-ASR, Gemma 3n, Gemma 4, Orpheus, Qwen2.5-Omni, Granite Speech, CSM, Dia, SeamlessM4T v2, Moonshine, Canary, wav2vec2) load with the identical model class, processor class and per-tower attention on both sides. New CPU tests in `tests/test_audio_load_routing.py`; the 18 existing attention / processor routing test files pass (224 passed, 6 skipped). Related: unslothai#14744 (training fixes for speech, CTC and classification models).
…udio Flamingo and Granite Speech collator (unslothai#1978) Companion to unslothai/unsloth#14744: the unsloth_zoo side of fine-tuning audio models with the default `FastModel` flow, in LoRA (16 bit) and QLoRA (4 bit). ## What was broken and what changes | Model | Before | Fix | |---|---|---| | Sesame CSM | `get_peft_model` raises `NoMatchingPeftModuleError` | `get_peft_regex`'s untagged-decoder fallback checked its regex with `re.search`, but PEFT matches targets with `re.fullmatch`, so the fallback was judged to match and the empty regex reached PEFT. Now checked with `fullmatch`, like PEFT. | | CSM, Higgs Audio, Dia | The fallback could put LoRA on the frozen audio codec / tokenizer model | The fallback regex excludes `codec_model`, `audio_tokenizer`, `acoustic_tokenizer` and `semantic_tokenizer` submodules. | | Canary, Parakeet (QLoRA, compiled) | `RuntimeError: Expected weight to have type Float but got BFloat16` in the compiled `BatchNorm1d` forward | The compiler already casts the input to the weight dtype for norms on the eager path; BatchNorm now gets the same cast in the compiled path. No-op when the dtypes already match; `affine = False` (no weight) is left alone. | | Audio Flamingo 3, Music Flamingo | `UnslothVisionDataCollator`'s top-level `padding = True` shortened the audio features, which these towers need at the processor's full 30 s | Padding for these two model types goes to the text kwargs only. | | Dia (gradient checkpointing on, the default) | The text encoder's LoRA got no gradients (0 of 12 encoder adapters; 12 of 12 with checkpointing off) | The encoder takes only token ids and has no `get_input_embeddings`, so the checkpointing pre-hook found no float input to mark. Its own `Embedding` output is now made to require grad, outside torch.compile only. | | AST (compiled, the default) | `Unsupported: returning intermediate with requires_grad_()` on the first step | The input-embedding hook ran inside the compiled `ASTEmbeddings`. When the compiler swapped in the class that calls the input embedding, the hook now goes on that class's output, outside the compiled region. | | MusicGen (compiled) | `ImportError: attempted relative import with no known parent package`, then `Dynamo does not support RNN, GRU, or LSTM`, then `The shape of the mask [2, 7] ... does not match ... [2, 50, 4]` | The compiler copied `MusicgenForConditionalGeneration.__init__`'s function-local `from ..auto.modeling_auto import ...` into the generated module; those relative imports are now made absolute. Modules that own an `nn.LSTM` / `GRU` / `RNN` (EnCodec's `EncodecLSTM`) are left uncompiled. The generated `mask_attention_mask_out` now masks labels only when the attention mask covers the labels' positions (MusicGen's mask is the text encoder's; its labels are decoder codebook frames). | | Granite Speech, Granite Speech Plus | `ValueError: Audio features and audio tokens do not match, tokens: 0` | Their chat templates drop an `{"type": "audio"}` part (Plus) or print the content list's repr (3.3); the model expects the `<|audio|>` token inside a string turn. The collator now detects that once (render with and without an audio part) and flattens content to a string with the processor's audio token, through the existing string-content shim. Templates that render audio are untouched. | Detection for the Granite change was run against the real processors of Granite Speech, Granite Speech Plus, Qwen2-Audio, Qwen2.5-Omni, Qwen3-ASR, Gemma 3n, Gemma 4, GLM-ASR, Audio Flamingo 3, Music Flamingo, Fun-ASR-Nano and Voxtral: only the two Granite processors change. ## Evidence Tiny random-weight copies of each model (real config shrunk, real processor), 5 training steps per case on a Colab GPU in bf16, with unslothai/unsloth#14744: | Model | Before | After | |---|---|---| | Canary QLoRA | BatchNorm dtype error | pass | | Parakeet CTC QLoRA | BatchNorm dtype error | pass | | CSM LoRA / QLoRA | `NoMatchingPeftModuleError` | trains | | Dia LoRA / QLoRA | encoder adapters never move | pass (encoder and decoder adapters move) | | AST LoRA / QLoRA, compiled | `requires_grad_()` Dynamo error | pass, 0 graph breaks | | Granite Speech / Plus LoRA / QLoRA | audio token count mismatch | pass | | MusicGen LoRA / QLoRA, compiled (with unslothai/unsloth#14781) | load / compile errors | trains, 0 graph breaks | | Gemma 3n LoRA (control) | 6 graph breaks | 6 graph breaks | | Qwen2-Audio, Qwen3-ASR (controls) | pass | pass | New CPU tests (fail on `main`, pass here): `tests/test_peft_regex_untagged_decoders.py`, `tests/test_compiler_batchnorm_dtype.py`, `tests/test_vision_collator_audio_full_length.py`, `tests/test_vision_collator_audio_token_in_text.py`, `tests/test_requires_grad_token_id_tower.py`, `tests/test_requires_grad_compiled_embeddings.py`, `tests/test_compiler_relative_imports.py`, `tests/test_compiler_mask_labels_shape.py`. The existing collator, pad token and PEFT regex suites pass (324 passed, 5 skipped).
Several popular audio models could not be fine-tuned through
FastModelwith the default arguments: they failed at load, atget_peft_model, or at the first training step. This PR fixes the loader and the PEFT wrapping so they train out of the box in both LoRA (16 bit) and QLoRA (4 bit). The companion collator and LoRA target fixes are in unslothai/unsloth-zoo (linked below).What was broken
FastModelflow)TypeError: WhisperDecoder(...) got multiple values for keyword argument 'input_ids'on the first stepget_peft_modelwraps every model inPeftModelForCausalLM, which callsbase_model(input_ids=None, ...); these models takeinput_features/input_values, soinput_idslands in**kwargsand reaches the decoder twice. The Whisper notebook avoids it by passingtask_type = None.AttributeError: 'Wav2Vec2ForCTC' object has no attribute 'prepare_inputs_for_generation'inget_peft_model__init__; these heads cannot generate.RuntimeError: Unsloth: Could not load the tokenizer/processorYou need to specify either text or text_target)input_ids/attention_mask; the model returns no losspadding_side = "left"forwards it into the codec model's__init__, which rejects it, and Unsloth silently fell back to the text tokenizer.Changes
FastModel.from_pretrained(loader.py): when no causal-LM class maps the config, load the auto class whose mapped class is the checkpoint's own architecture (Wav2Vec2ForCTC->AutoModelForCTC,ASTForAudioClassification->AutoModelForAudioClassification, frame classification, XVector, a bareWavLMModel->AutoModel). Configs a causal-LM class maps keep their route.get_peft_model: when the task is still the defaultCAUSAL_LM(orSEQ_2_SEQ_LM) and the model'sforwardtakes audio features and noinput_ids, or the model cannot generate, use PEFT's genericPeftModel(task_type = None), exactly what the Whisper notebook already passes by hand. For heads that cannot generate (CTC, classification), their unquantized top-level head modules (lm_head,classifier,projector) go tomodules_to_saveunless the caller passes their own list, since the generic wrapper would otherwise freeze and drop a freshly initialized head. A bare encoder stays LoRA only, and a secondget_peft_modelon a genericPeftModelraises the usual error. Text models, VLMs and audio LLMs (Qwen2-Audio, Gemma 3n / 4, Voxtral) all keep their current wrapper.Request the processor for configs mapped to an audio auto class (speech seq2seq, CTC, audio classification and friends).
AutoModelForSeq2SeqLMkeeps its tokenizer, so SeamlessM4T's text-to-text route is unchanged.Fall back to
AutoFeatureExtractorbefore raising "Could not load the tokenizer/processor", and never setpadding_sideon a bare feature extractor (audio must stay right padded).Retry the processor load without
padding_sidewhen it is rejected (the inner tokenizer is set to left padding afterwards either way), and keep the processor wrapper when the tokenizer patch falls back toAutoTokenizer.Warn when an audio processor could not load because a library is missing.
Every change is a fallback that only runs on a path that previously crashed or silently dropped the processor, so models that load today take the same branch as before.
Evidence
Tiny random-weight copies of each model (real config shrunk, real processor), 5 training steps per case on a Colab GPU in bf16, unsloth_zoo pinned.
mainvs this branch:wav2vec2 / HuBERT / Parakeet / AST were loaded without
auto_model. Every passing case checks finite loss, finite grad norm, LoRA weights moved, and (16 bit) that the adapter reloaded with plain transformers + PEFT in a process that never imports Unsloth gives the same loss.New CPU tests:
tests/python/test_audio_processor_load.py,tests/python/test_peft_non_generative_heads.py,tests/python/test_feature_extractor_only_checkpoints.py(fail onmain, pass here).Companion: unslothai/unsloth-zoo#1978 (CSM LoRA targets, frozen audio codecs, BatchNorm dtype under compile, Audio Flamingo and Granite Speech collator fixes).