Local UI to run and train LLMs and diffusion models. Supports GGUF, MLX, Qwen3.8, DeepSeek-V4.1, MiniMax-H3, Gemma 4, FLUX and more.
Python agentaichatgptdeepseekfine-tuninggemmaimage-generationllamallmllmsopenaipythonqwenreinforcement-learningself-hostedstable-diffusiontext-to-speechttsuiunsloth
Unsloth Studio: train and export LFM3-Audio-2B (LoRA, merged 16-bit, GGUF) (#16973)
Leo Borcherding3faa62e3d221
diff --git a/studio/backend/core/export/export.py b/studio/backend/core/export/export.pyindex 71715986e96..4b150be02b4 100644--- a/studio/backend/core/export/export.py+++ b/studio/backend/core/export/export.py@@ -31,7 +31,7 @@ from huggingface_hub import HfApi, ModelCardfrom hub.utils.hf_tokens import HfTokenArg, apply_token_to_child_env, is_anonymous, normalize_tokenfrom utils.hardware import clear_gpu_cache-from utils.models import is_vision_model, get_base_model_from_lora+from utils.models import is_vision_model, audio_vlm_multimodal_lm_checked, get_base_model_from_lorafrom utils.models.model_identity import restore_hf_cache_repo_identityfrom utils.models.model_config import (detect_audio_type,@@ -1075,6 +1075,13 @@ class ExportBackend:self.is_vision = self._audio_type in (None, "audio_vlm") and is_vision_model(model_id, hf_token = probe_token, local_files_only = local_files_only)+ # Only a definitive no (not an unreadable config) takes the multimodal load below.+ audio_vlm_multimodal = False+ if self._audio_type == "audio_vlm" and not self.is_vision:+ takes, known = audio_vlm_multimodal_lm_checked(+ model_id, hf_token = probe_token, local_files_only = local_files_only+ )+ audio_vlm_multimodal = known and takesfrom utils.models.diffusion_lm import diffusion_lm_profile_for_modelself.diffusion_lm_profile = (@@ -1178,6 +1185,34 @@ class ExportBackend:**_offload_kw,)+ elif self._audio_type == "audio_vlm" and audio_vlm_multimodal:+ # LFM3-Audio: the text load builds the bare backbone with no LM head; Training and Chat use this class.+ from unsloth import FastModel+ from transformers import AutoModelForMultimodalLM++ logger.info("Loading as audio-input model (AutoModelForMultimodalLM)...")+ model, tokenizer = FastModel.from_pretrained(+ model_name = checkpoint_path,+ auto_model = AutoModelForMultimodalLM,+ max_seq_length = max_seq_length,+ dtype = None,+ **_load_in_4bit_kwargs(load_in_4bit),+ trust_remote_code = trust_remote_code,+ token = token,+ local_files_only = local_files_only,+ **_device_map_kw,+ **_offload_kw,+ )+ if base_model and not hasattr(tokenizer, "feature_extractor"):+ with _offline_window_if(local_files_only):+ tokenizer = _with_base_processor(+ tokenizer,+ base_model,+ trust_remote_code = trust_remote_code,+ token = token,+ local_files_only = local_files_only,+ )+elif self.diffusion_lm_profile:from unsloth import FastModellogger.info(f"Loading as text-diffusion model ({self.diffusion_lm_profile})...")diff --git a/studio/backend/core/training/trainer.py b/studio/backend/core/training/trainer.pyindex fa41cffe76e..da0b0dd01be 100644--- a/studio/backend/core/training/trainer.py+++ b/studio/backend/core/training/trainer.py@@ -73,7 +73,7 @@ from utils.third_party_source import (import_sparktts_module,)-from utils.models import is_vision_model, detect_audio_type_checked+from utils.models import is_vision_model, audio_vlm_multimodal_lm_checked, detect_audio_type_checkedfrom utils.models.diffusion_lm import (diffusion_lm_profile_for_model,loaded_diffusion_profile,@@ -229,6 +229,16 @@ def _drop_hf_stdout_callbacks(trainer) -> None:_FORCED_16BIT_AUDIO_TYPES = frozenset({"csm", "whisper", "bicodec", "dac"})+def _audio_vlm_auto_model_kwargs(multimodal: bool) -> dict:+ """No vision tower (LFM3-Audio): the default load builds a backbone with no LM head, so use Chat's class."""+ if not multimodal:+ return {}+ import transformers++ auto_model = getattr(transformers, "AutoModelForMultimodalLM", None)+ return {"auto_model": auto_model} if auto_model is not None else {}++def _bitsandbytes_allows_4bit() -> bool:"""from_pretrained drops 4-bit when bitsandbytes is unusable, so the metadata read must check it."""try:@@ -1262,6 +1272,16 @@ class UnslothTrainer:else False)self.is_vlm = not self.is_audio_vlm and vision and is_dataset_image+ # Only a definitive no (not an unreadable config) takes the multimodal class.+ audio_vlm_multimodal = False+ if self.is_audio_vlm and not vision:+ takes, known = audio_vlm_multimodal_lm_checked(+ metadata_name,+ hf_token = hf_token,+ local_files_only = local_files_only,+ revision = model_revision,+ )+ audio_vlm_multimodal = known and takesself._detect_diffusion_lm(metadata_name, hf_token, local_files_only, model_revision)self.model_name = model_nameself.max_seq_length = max_seq_length@@ -1465,7 +1485,10 @@ class UnslothTrainer:elif self.is_audio_vlm:from unsloth import FastModel++ audio_vlm_kwargs = _audio_vlm_auto_model_kwargs(audio_vlm_multimodal)self.model, self.tokenizer = FastModel.from_pretrained(+ **audio_vlm_kwargs,model_name = lookup_name,max_seq_length = max_seq_length,dtype = _auto_dtype,@@ -1480,7 +1503,9 @@ class UnslothTrainer:on_model_resolved = on_model_resolved,**self._offload_load_kwargs(device_map),)- logger.info("Loaded audio VLM model (FastModel)")+ logger.info(+ f"Loaded audio VLM model (FastModel{', AutoModelForMultimodalLM' if audio_vlm_kwargs else ''})"+ )elif self.diffusion_lm_profile:# FastModel routes every registered text-diffusion family to its diffusion loader.@@ -4542,6 +4567,19 @@ class UnslothTrainer:audio_col_name = getattr(self, "_audio_vlm_audio_col", "audio")image_col_name = getattr(self, "_audio_vlm_image_col", None)+ # Placeholder ids stay out of the loss; LFM3-Audio keeps them on the processor, Gemma 3n on its tokenizer.+ placeholder_ids = set()+ for holder in (processor, getattr(processor, "tokenizer", None)):+ for attr in (+ "audio_token_id",+ "audio_out_token_id",+ "image_token_id",+ "boi_token_id",+ "eoi_token_id",+ ):+ token_id = getattr(holder, attr, None)+ if type(token_id) is int:+ placeholder_ids.add(token_id)if training_args.get("train_on_completions", False) and not training_args.get("is_cpt", False):@@ -4603,15 +4641,8 @@ class UnslothTrainer:labels = batch["input_ids"].clone()labels[labels == processor.tokenizer.pad_token_id] = -100- for attr in (- "audio_token_id",- "image_token_id",- "boi_token_id",- "eoi_token_id",- ):- token_id = getattr(processor.tokenizer, attr, None)- if token_id is not None:- labels[labels == token_id] = -100+ for token_id in placeholder_ids:+ labels[labels == token_id] = -100batch["labels"] = labelsif audio_response_masker is not None:batch["labels"] = audio_response_masker(batch)["labels"]diff --git a/studio/backend/tests/test_audio_vlm_completion_masking.py b/studio/backend/tests/test_audio_vlm_completion_masking.pyindex 78131c81602..2cd7add05c4 100644--- a/studio/backend/tests/test_audio_vlm_completion_masking.py+++ b/studio/backend/tests/test_audio_vlm_completion_masking.py@@ -178,3 +178,32 @@ def test_undetectable_markers_warn_and_train_full_sequences(fake_unsloth, monkeyassert "could not be applied" in caplog.textfor ids, labels in zip(batch["input_ids"].tolist(), batch["labels"].tolist()):assert labels == [-100 if token in (PAD, AUDIO) else token for token in ids]+++class _Lfm3Tokenizer(_Tokenizer):+ audio_token_id = None # LFM3-Audio's tokenizer names no placeholder id+++class _Lfm3Processor(_Processor):+ """LFM3-Audio-2B: the processor, not its tokenizer, holds audio_token_id; its __call__ is text-first."""++ audio_token_id = AUDIO++ def __init__(self):+ self.tokenizer = _Lfm3Tokenizer(preset_markers = True)++ def __call__(+ self,+ text = None,+ audio = None,+ return_tensors = None,+ padding = None,+ ):+ return super().__call__(text, audio, return_tensors, padding)+++def test_lfm3_audio_placeholders_on_the_processor_stay_out_of_the_loss(fake_unsloth):+ batch = _collate(_Lfm3Processor())+ for ids, labels in zip(batch["input_ids"].tolist(), batch["labels"].tolist()):+ assert AUDIO in ids+ assert labels == [-100 if token in (PAD, AUDIO) else token for token in ids]diff --git a/studio/backend/tests/test_audio_vlm_multimodal_lm_checked.py b/studio/backend/tests/test_audio_vlm_multimodal_lm_checked.pynew file mode 100644index 00000000000..80ddab0e686--- /dev/null+++ b/studio/backend/tests/test_audio_vlm_multimodal_lm_checked.py@@ -0,0 +1,60 @@+# SPDX-License-Identifier: AGPL-3.0-only+# Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0++# Raw config.json decides, not the sidecar probe, which can't run LFM3-Audio's repo code.++import pytest++import utils.models.model_config as mc++LFM3_AUDIO = {+ "model_type": "lfm3_audio",+ "architectures": ["Lfm3AudioForConditionalGeneration"],+ "auto_map": {+ "AutoModelForMultimodalLM": "modeling_lfm3_audio.Lfm3AudioForConditionalGeneration"+ },+}+AUDIO_FLAMINGO_3 = {"model_type": "audioflamingo3", "audio_config": {}, "text_config": {}}+GEMMA_3N = {"model_type": "gemma3n", "vision_config": {}, "audio_config": {}}+LFM3_OMNI = {"model_type": "lfm3_omni", "vision_config": {}}+++def config(monkeypatch):+ def use(raw):+ monkeypatch.setattr(mc, "_read_raw_config_json", lambda *a, **k: raw)++ def probe(*a, **k):+ raise AssertionError("sidecar probe must not run")++ monkeypatch.setattr(mc, "_is_vision_model_subprocess", probe)+ return use+++def test_lfm3_audio_takes_the_multimodal_class(config):+ config(LFM3_AUDIO)+ assert mc.audio_vlm_multimodal_lm_checked("LiquidAI/LFM3-Audio-2B") == (True, True)+++def test_a_native_multimodal_mapping_takes_it(config):+ names = pytest.importorskip("transformers.models.auto.modeling_auto")+ if "qwen2_audio" not in getattr(names, "MODEL_FOR_MULTIMODAL_LM_MAPPING_NAMES", {}):+ pytest.skip("this transformers has no AutoModelForMultimodalLM mapping for qwen2_audio")+ config({"model_type": "qwen2_audio", "audio_config": {}})+ assert mc.audio_vlm_multimodal_lm_checked("m") == (True, True)+++def test_audio_without_a_multimodal_class_keeps_the_default(config):+ config(AUDIO_FLAMINGO_3)+ assert mc.audio_vlm_multimodal_lm_checked("nvidia/audio-flamingo-3-hf") == (False, True)++[email protected]("raw", [GEMMA_3N, LFM3_OMNI])+def test_declared_vision_keeps_the_default(config, raw):+ config(raw)+ assert mc.audio_vlm_multimodal_lm_checked("m") == (False, True)+++def test_unreadable_config_is_unknown(config):+ config(None)+ assert mc.audio_vlm_multimodal_lm_checked("m") == (False, False)diff --git a/studio/backend/tests/test_audio_vlm_train_load.py b/studio/backend/tests/test_audio_vlm_train_load.pynew file mode 100644index 00000000000..d9af2989e76--- /dev/null+++ b/studio/backend/tests/test_audio_vlm_train_load.py@@ -0,0 +1,143 @@+# SPDX-License-Identifier: AGPL-3.0-only+# Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0++"""Training LFM3-Audio-2B (audio in, no vision tower) loads through AutoModelForMultimodalLM, like Chat;+Gemma 3n / 4 (audio + vision) keep the default FastModel load."""++from __future__ import annotations++import importlib+import sys+import types+from unittest.mock import MagicMock++import pytest++_STUBBED: list[str] = []+++def _stub_if_missing(name, attrs):+ if name in sys.modules:+ return+ try:+ importlib.import_module(name)+ return+ except Exception: # noqa: BLE001+ pass+ _STUBBED.append(name)+ mod = types.ModuleType(name)+ mod.__spec__ = None+ for attr in attrs:+ setattr(mod, attr, MagicMock())+ sys.modules[name] = mod+++_stub_if_missing(+ "unsloth", ("FastLanguageModel", "FastVisionModel", "FastModel", "is_bfloat16_supported")+)+_stub_if_missing("unsloth.chat_templates", ("get_chat_template",))+_stub_if_missing("trl", ("SFTTrainer", "SFTConfig"))++import core.training.trainer as trainer_mod # noqa: E402++for _name in reversed(_STUBBED):+ sys.modules.pop(_name, None)++import transformers # noqa: E402++transformers = sys.modules["transformers"]+++class _Lfm3AudioForConditionalGeneration:+ pass+++class _Lfm3AudioProcessor:+ feature_extractor = object()+ tokenizer = object()+++def load(monkeypatch):+ calls = {}++ def from_pretrained(**kwargs):+ calls.setdefault("from_pretrained", []).append(kwargs)+ return _Lfm3AudioForConditionalGeneration(), calls.get("returns", _Lfm3AudioProcessor())++ fake_unsloth = types.ModuleType("unsloth")+ fake_unsloth.FastModel = types.SimpleNamespace(from_pretrained = from_pretrained)+ monkeypatch.setitem(sys.modules, "unsloth", fake_unsloth)++ noop = lambda *a, **k: None+ for name, value in {+ "detect_audio_type_checked": lambda *a, **k: ("audio_vlm", True),+ "clear_gpu_cache": noop,+ "get_device_map": lambda gpu_ids: "auto",+ "get_visible_gpu_count": lambda: 1,+ "raise_if_offloaded": noop,+ "restore_hf_cache_repo_identity": lambda *a, **k: None,+ "is_bfloat16_supported": lambda: True,+ "should_use_mlx_training_backend": lambda: False,+ }.items():+ monkeypatch.setattr(trainer_mod, name, value)+ import utils.cache_cleanup as cache_cleanup++ monkeypatch.setattr(cache_cleanup, "clear_unsloth_compiled_cache", noop)++ def run(+ vision,+ returns = None,+ vision_known = True,+ multimodal = None,+ ):+ multimodal = not vision if multimodal is None else multimodal+ monkeypatch.setattr(trainer_mod, "is_vision_model", lambda *a, **k: vision)+ monkeypatch.setattr(+ trainer_mod,+ "audio_vlm_multimodal_lm_checked",+ lambda *a, **k: (multimodal, vision_known),+ )+ if returns is not None:+ calls["returns"] = returns+ trainer = trainer_mod.UnslothTrainer()+ trainer._detect_diffusion_lm = noop+ trainer._update_progress = lambda **kw: calls.setdefault("errors", []).append(+ kw.get("error")+ )+ ok = trainer.load_model(+ "LiquidAI/LFM3-Audio-2B",+ is_dataset_audio = True,+ load_in_4bit = False,+ trust_remote_code = True,+ local_files_only = True,+ )+ assert ok, [e for e in calls.get("errors", []) if e]+ assert trainer.is_audio_vlm+ return trainer, calls["from_pretrained"][-1]++ return run+++def test_audio_without_vision_loads_the_multimodal_class(load):+ if getattr(transformers, "AutoModelForMultimodalLM", None) is None:+ pytest.skip("transformers without AutoModelForMultimodalLM")+ trainer, kwargs = load(vision = False)+ assert kwargs.get("auto_model") is transformers.AutoModelForMultimodalLM+ assert isinstance(trainer.tokenizer, _Lfm3AudioProcessor)+++def test_audio_with_vision_keeps_the_default_load(load):+ _, kwargs = load(vision = True) # Gemma 3n / Gemma 4+ assert "auto_model" not in kwargs+++def test_an_inconclusive_vision_probe_keeps_the_default_load(load):+ # A transient probe failure reads as no vision; Gemma 3n / 4 must not lose their default load to it.+ _, kwargs = load(vision = False, vision_known = False)+ assert "auto_model" not in kwargs+++def test_audio_without_a_multimodal_class_keeps_the_default_load(load):+ _, kwargs = load(vision = False, multimodal = False) # AudioFlamingo3+ assert "auto_model" not in kwargsdiff --git a/studio/backend/tests/test_export_absolute_paths.py b/studio/backend/tests/test_export_absolute_paths.pyindex 8659bb5314c..0c19d2bac83 100644--- a/studio/backend/tests/test_export_absolute_paths.py+++ b/studio/backend/tests/test_export_absolute_paths.py@@ -175,6 +175,7 @@ def _install_lightweight_backend_stubs(monkeypatch):):setattr(utils_models, name, lambda *args, **kwargs: None)utils_models.is_vision_model = lambda *args, **kwargs: False+ utils_models.audio_vlm_multimodal_lm_checked = lambda *args, **kwargs: (False, True)utils_models.is_embedding_model = lambda *args, **kwargs: Falseutils_models.ModelConfig = objectmonkeypatch.setitem(sys.modules, "utils.models", utils_models)@@ -300,6 +301,7 @@ def _install_export_backend_stubs(monkeypatch):utils_models = sys.modules["utils.models"]utils_models.get_base_model_from_lora = lambda *args, **kwargs: Noneutils_models.is_vision_model = lambda *args, **kwargs: False+ utils_models.audio_vlm_multimodal_lm_checked = lambda *args, **kwargs: (False, True)utils_model_config = sys.modules["utils.models.model_config"]utils_model_config.detect_audio_type = lambda *args, **kwargs: Nonediff --git a/studio/backend/tests/test_export_audio_vlm_loads_as_vision.py b/studio/backend/tests/test_export_audio_vlm_loads_as_vision.pyindex 026c99f1337..0b4bdbaf4da 100644--- a/studio/backend/tests/test_export_audio_vlm_loads_as_vision.py+++ b/studio/backend/tests/test_export_audio_vlm_loads_as_vision.py@@ -30,13 +30,22 @@ class _Loader:def from_pretrained(self, **kwargs):self.calls.append(kwargs)- return types.SimpleNamespace(), types.SimpleNamespace()+ return types.SimpleNamespace(), types.SimpleNamespace(feature_extractor = object())-def _load(monkeypatch, tmp_path, audio_type, is_vision):+def _load(+ monkeypatch,+ tmp_path,+ audio_type,+ is_vision,+ vision_known = True,+ multimodal = None,+):+ multimodal = not is_vision if multimodal is None else multimodal_install_export_backend_stubs(monkeypatch)mod = _load_module("test_core_export_audio_vlm_vision", "core/export/export.py", monkeypatch)- text, vision = _Loader(), _Loader()+ text, vision, fast = _Loader(), _Loader(), _Loader()+ sys.modules["unsloth"].FastModel = fastmonkeypatch.setattr(mod, "FastLanguageModel", text)monkeypatch.setattr(mod, "FastVisionModel", vision)monkeypatch.setattr(mod, "_IS_MLX", False)@@ -44,6 +53,9 @@ def _load(monkeypatch, tmp_path, audio_type, is_vision):monkeypatch.setattr(mod, name, type(name, (), {}), raising = False)monkeypatch.setattr(mod, "detect_audio_type", lambda *a, **k: audio_type)monkeypatch.setattr(mod, "is_vision_model", lambda *a, **k: is_vision)+ monkeypatch.setattr(+ mod, "audio_vlm_multimodal_lm_checked", lambda *a, **k: (multimodal, vision_known)+ )monkeypatch.setattr(mod, "_hf_offline", lambda *a, **k: False)monkeypatch.setattr(mod, "_offline_window_if", lambda flag: contextlib.nullcontext())monkeypatch.setattr(mod, "_multi_gpu_device_map_kwargs", lambda: {})@@ -53,14 +65,13 @@ def _load(monkeypatch, tmp_path, audio_type, is_vision):backend.cleanup_memory = lambda: Noneok, message = backend.load_checkpoint(str(checkpoint))assert ok, message- return backend, text, vision+ return backend, text, vision, fast@pytest.mark.parametrize("audio_type, is_vision, expect_vision",[("audio_vlm", True, True), # LFM3-Omni, Gemma 3n/4- ("audio_vlm", False, False),(None, True, True),(None, False, False),],@@ -68,6 +79,32 @@ def _load(monkeypatch, tmp_path, audio_type, is_vision):def test_audio_vlm_with_vision_takes_the_vision_load(monkeypatch, tmp_path, audio_type, is_vision, expect_vision):- backend, text, vision = _load(monkeypatch, tmp_path, audio_type, is_vision)+ backend, text, vision, fast = _load(monkeypatch, tmp_path, audio_type, is_vision)assert backend.is_vision is expect_vision- assert (len(vision.calls), len(text.calls)) == ((1, 0) if expect_vision else (0, 1))+ assert (len(vision.calls), len(text.calls), len(fast.calls)) == (+ (1, 0, 0) if expect_vision else (0, 1, 0)+ )+++def test_audio_vlm_without_vision_takes_the_multimodal_load(monkeypatch, tmp_path):+ transformers = pytest.importorskip("transformers")+ if getattr(transformers, "AutoModelForMultimodalLM", None) is None:+ pytest.skip("transformers without AutoModelForMultimodalLM")+ backend, text, vision, fast = _load(monkeypatch, tmp_path, "audio_vlm", False)+ assert (len(vision.calls), len(text.calls), len(fast.calls)) == (0, 0, 1)+ assert fast.calls[0]["auto_model"] is transformers.AutoModelForMultimodalLM+ assert hasattr(backend.current_tokenizer, "feature_extractor")+++def test_audio_without_a_multimodal_class_keeps_the_text_load(monkeypatch, tmp_path):+ # AudioFlamingo3: no vision tower, no AutoModelForMultimodalLM mapping; FastModel resolves it.+ backend, text, vision, fast = _load(monkeypatch, tmp_path, "audio_vlm", False, multimodal = False)+ assert (len(vision.calls), len(text.calls), len(fast.calls)) == (0, 1, 0)+++def test_an_inconclusive_vision_probe_keeps_the_text_load(monkeypatch, tmp_path):+ # A transient probe failure reads as no vision; it must not send Gemma 3n / 4 to the multimodal class.+ backend, text, vision, fast = _load(+ monkeypatch, tmp_path, "audio_vlm", False, vision_known = False+ )+ assert (len(vision.calls), len(text.calls), len(fast.calls)) == (0, 1, 0)diff --git a/studio/backend/utils/models/__init__.py b/studio/backend/utils/models/__init__.pyindex 38f8acdbe73..0aea3f27553 100644--- a/studio/backend/utils/models/__init__.py+++ b/studio/backend/utils/models/__init__.py@@ -9,6 +9,7 @@ from .model_config import (GgufVariantInfo,is_vision_model,is_vision_model_checked,+ audio_vlm_multimodal_lm_checked,is_embedding_model,detect_audio_type,detect_audio_type_checked,@@ -34,6 +35,7 @@ __all__ = ["GgufVariantInfo","is_vision_model","is_vision_model_checked",+ "audio_vlm_multimodal_lm_checked","is_embedding_model","detect_audio_type","detect_audio_type_checked",diff --git a/studio/backend/utils/models/model_config.py b/studio/backend/utils/models/model_config.pyindex 261ab0ce1a8..89851a6ed2b 100644--- a/studio/backend/utils/models/model_config.py+++ b/studio/backend/utils/models/model_config.py@@ -1518,6 +1518,33 @@ def is_vision_model()+def audio_vlm_multimodal_lm_checked(+ model_name: str,+ hf_token: Optional[str] = None,+ local_files_only: bool = False,+ revision: Optional[str] = None,+) -> Tuple[bool, bool]:+ """(loads through AutoModelForMultimodalLM, config.json readable): no vision tower and a class registered there,+ natively or by auto_map. AudioFlamingo3 has none and keeps FastModel's resolver. Raw config: no repo code runs."""+ vision = _raw_config_has_vision_config(model_name, hf_token, local_files_only, revision)+ if vision is None:+ return False, False+ if vision:+ return False, True+ try:+ config = _read_raw_config_json(model_name, hf_token, local_files_only, revision) or {}+ except Exception:+ return False, False+ auto_map = config.get("auto_map")+ if isinstance(auto_map, dict) and "AutoModelForMultimodalLM" in auto_map:+ return True, True+ try:+ from transformers.models.auto.modeling_auto import MODEL_FOR_MULTIMODAL_LM_MAPPING_NAMES+ except ImportError:+ return False, True+ return config.get("model_type") in MODEL_FOR_MULTIMODAL_LM_MAPPING_NAMES, True++def is_vision_model_checked(model_name: str,hf_token: Optional[str] = None,diff --git a/tests/saving/test_lfm3_audio_gguf_config.py b/tests/saving/test_lfm3_audio_gguf_config.pynew file mode 100644index 00000000000..dd55900f269--- /dev/null+++ b/tests/saving/test_lfm3_audio_gguf_config.py@@ -0,0 +1,213 @@+# SPDX-License-Identifier: AGPL-3.0-only+# Copyright 2026-present the Unsloth AI Inc. team. All rights reserved.++"""GGUF conversion of LFM3-Audio reads the release config.json layout: llama.cpp's converter registers+Lfm3AudioForConditionalGeneration through an hparams loader that matches only `lfm` / `encoder` /+`depthformer`, while the remote config class saves `text_config` / `audio_encoder_config` /+`depth_config`."""++from __future__ import annotations++import json+import os+import types++import pytest++save_mod = pytest.importorskip("unsloth.save")++RELEASE = {+ "architectures": ["Lfm3AudioForConditionalGeneration"],+ "model_type": "lfm3_audio",+ "codebooks": 8,+ "lfm": {"architectures": ["Lfm3ForCausalLM"], "model_type": "lfm3", "vocab_size": 128000},+ "encoder": {"dim_in": 128},+ "depthformer": {"layers": 4},+}+SAVED = {+ "architectures": ["Lfm3AudioForConditionalGeneration"],+ "model_type": "lfm3_audio",+ "num_codebooks": 8,+ "text_config": {"model_type": "lfm3", "vocab_size": 128000},+ "audio_encoder_config": {"num_mel_bins": 128},+ "depth_config": {"model_type": "lfm3"},+}+++def _write(directory, config):+ directory.mkdir(parents = True, exist_ok = True)+ (directory / "config.json").write_text(json.dumps(config), encoding = "utf-8")+ return directory+++def _peft_model(base):+ return types.SimpleNamespace(+ peft_config = {"default": types.SimpleNamespace(base_model_name_or_path = str(base))},+ config = types.SimpleNamespace(_name_or_path = str(base)),+ )+++def _saved(directory):+ return json.loads((directory / "config.json").read_text(encoding = "utf-8"))+++def test_the_transformers_layout_is_replaced_by_the_release_config(tmp_path):+ base = _write(tmp_path / "base", RELEASE)+ merged = _write(tmp_path / "merged", SAVED)+ assert save_mod._restore_lfm3_audio_release_config(_peft_model(base), str(merged))+ assert _saved(merged) == RELEASE+++def test_the_effective_text_settings_survive_the_restore(tmp_path):+ rope = {"rope_type": "yarn", "factor": 4.0, "original_max_position_embeddings": 32768}+ base = _write(tmp_path / "base", RELEASE)+ merged = _write(+ tmp_path / "merged",+ {**SAVED, "text_config": {**SAVED["text_config"], "rope_parameters": rope}},+ )+ assert save_mod._restore_lfm3_audio_release_config(_peft_model(base), str(merged))+ assert _saved(merged)["lfm"] == {**RELEASE["lfm"], "rope_parameters": rope}+++def test_a_release_layout_is_left_alone(tmp_path):+ base = _write(tmp_path / "base", {**RELEASE, "codebooks": 99})+ merged = _write(tmp_path / "merged", RELEASE)+ assert not save_mod._restore_lfm3_audio_release_config(_peft_model(base), str(merged))+ assert _saved(merged) == RELEASE+++def test_resized_embeddings_keep_the_saved_config(tmp_path):+ base = _write(tmp_path / "base", RELEASE)+ resized = {**SAVED, "text_config": {**SAVED["text_config"], "vocab_size": 128008}}+ merged = _write(tmp_path / "merged", resized)+ assert not save_mod._restore_lfm3_audio_release_config(_peft_model(base), str(merged))+ assert _saved(merged) == resized++[email protected]("model_type", ["lfm3_omni", "lfm3", "llama"])+def test_other_models_are_untouched(tmp_path, model_type):+ base = _write(tmp_path / "base", {**RELEASE, "model_type": model_type})+ other = {**SAVED, "model_type": model_type}+ merged = _write(tmp_path / "merged", other)+ assert not save_mod._restore_lfm3_audio_release_config(_peft_model(base), str(merged))+ assert _saved(merged) == other+++def test_the_gguf_export_restores_it_before_converting():+ import inspect+ src = inspect.getsource(save_mod.unsloth_save_pretrained_gguf)+ assert src.index("_restore_lfm3_audio_release_config(") < src.index("save_to_gguf(")+++def test_a_hub_base_is_read_at_the_loaded_commit(tmp_path, monkeypatch):+ import huggingface_hub++ calls = []++ def hf_hub_download(+ repo,+ filename,+ revision = None,+ local_files_only = False,+ ):+ calls.append((repo, filename, revision))+ return str(_write(tmp_path / "snap", RELEASE) / "config.json")++ monkeypatch.setattr(huggingface_hub, "hf_hub_download", hf_hub_download)+ model = types.SimpleNamespace(+ peft_config = {+ "default": types.SimpleNamespace(base_model_name_or_path = "LiquidAI/LFM3-Audio-2B")+ },+ config = types.SimpleNamespace(+ _name_or_path = "LiquidAI/LFM3-Audio-2B", _commit_hash = "cddb56b5ec"+ ),+ )+ merged = _write(tmp_path / "merged", SAVED)+ assert save_mod._restore_lfm3_audio_release_config(model, str(merged))+ assert calls[0] == ("LiquidAI/LFM3-Audio-2B", "config.json", "cddb56b5ec")+++def test_a_reloaded_merged_checkpoint_still_exports(tmp_path):+ # The merged folder carries the release layout: a later GGUF export of it has no PEFT base to read.+ base = _write(tmp_path / "base", RELEASE)+ merged = _write(tmp_path / "merged", {**SAVED, "dtype": "float32"})+ assert save_mod._release_layout_for_merged_save(_peft_model(base), str(merged), "merged_16bit")+ assert _saved(merged) == {**RELEASE, "dtype": "float32"}++ reloaded = types.SimpleNamespace(config = types.SimpleNamespace(_name_or_path = str(merged)))+ staged = _write(tmp_path / "staged", SAVED)+ assert save_mod._restore_lfm3_audio_release_config(reloaded, str(staged))+ assert _saved(staged)["lfm"] == RELEASE["lfm"]+++def test_a_4bit_merge_keeps_its_saved_config(tmp_path):+ base = _write(tmp_path / "base", RELEASE)+ quantized = {**SAVED, "quantization_config": {"load_in_4bit": True}}+ merged = _write(tmp_path / "merged", quantized)+ assert not save_mod._release_layout_for_merged_save(+ _peft_model(base), str(merged), "merged_4bit"+ )+ assert _saved(merged) == quantized+++def test_a_peft_merged_push_uploads_the_release_config(tmp_path, monkeypatch):+ import shutil+ import huggingface_hub++ base = _write(tmp_path / "base", RELEASE)+ hub = _write(+ tmp_path / "hub",+ {+ **SAVED,+ "dtype": "bfloat16",+ "auto_map": {"AutoConfig": "configuration_lfm3_audio.Lfm3AudioConfig"},+ },+ )+ uploads = []++ def download(+ repo_id,+ filename,+ token = None,+ local_dir = None,+ force_download = False,+ **kw,+ ):+ assert (repo_id, filename, force_download) == ("leo/merged", "config.json", True)+ target = os.path.join(local_dir, filename)+ shutil.copy(hub / filename, target)+ return target++ class Api:+ def __init__(self, token = None):+ pass++ def upload_file(self, path_or_fileobj, path_in_repo, repo_id, **kw):+ uploads.append((repo_id, path_in_repo, json.loads(open(path_or_fileobj).read())))++ monkeypatch.setattr(huggingface_hub, "hf_hub_download", download)+ monkeypatch.setattr(huggingface_hub, "HfApi", Api)+ model = _peft_model(base)+ model.config.model_type = "lfm3_audio"+ assert save_mod._push_lfm3_audio_release_config(model, "leo/merged", token = None)+ assert uploads == [+ (+ "leo/merged",+ "config.json",+ {+ **RELEASE,+ "dtype": "bfloat16",+ "auto_map": {"AutoConfig": "configuration_lfm3_audio.Lfm3AudioConfig"},+ },+ )+ ]++ other = _peft_model(base)+ other.config.model_type = "llama"++ def no_whoami(*args):+ raise AssertionError("a non LFM3-Audio push resolved the repo id")++ monkeypatch.setattr(save_mod, "_determine_username", no_whoami)+ assert not save_mod._push_lfm3_audio_release_config(other, "merged", token = None)+ assert len(uploads) == 1diff --git a/tests/saving/test_save_method_lora_routing.py b/tests/saving/test_save_method_lora_routing.pyindex c941fcb88df..e7daebe45e4 100644--- a/tests/saving/test_save_method_lora_routing.py+++ b/tests/saving/test_save_method_lora_routing.py@@ -219,6 +219,9 @@ _GENERIC_SAVE_STUBBED_HELPERS = frozenset("_stitch_mtp_head","_mtp_head_tensor_names","_unmerge_flags_on_error",+ # LFM3-Audio config rewrite: no LFM3-Audio checkpoint in these fixtures.+ "_release_layout_for_merged_save",+ "_push_lfm3_audio_release_config",# Decorator factory; _load strips decorators."_model_parallel_refuses_save",}@@ -259,6 +262,8 @@ def _routing_environment(monkeypatch, model):_internal_mtp_save = contextlib.nullcontext,_stitch_mtp_head = lambda model, directory: None,_mtp_head_tensor_names = lambda model: [],+ _release_layout_for_merged_save = lambda model, directory, method: False,+ _push_lfm3_audio_release_config = lambda model, save_directory, token = None: False,lora_relative_to_original_base = lambda model: (calls["convert"].append(model) or contextlib.nullcontext()),diff --git a/tests/test_merged_hub_destination.py b/tests/test_merged_hub_destination.pyindex 58e2b76c802..67cad85a2d0 100644--- a/tests/test_merged_hub_destination.py+++ b/tests/test_merged_hub_destination.py@@ -146,6 +146,7 @@ def saving(monkeypatch, tmp_path):env = dict(os = os,+ json = json,sys = sys,gc = gc,Path = Path,@@ -197,6 +198,11 @@ def saving(monkeypatch, tmp_path):"_cast_state_dict_16bit","_requests_float32","_collect_garbage",+ # Real code: a non-LFM3-Audio save leaves config.json alone and pushes nothing extra.+ "_base_config_dicts",+ "_restore_lfm3_audio_release_config",+ "_release_layout_for_merged_save",+ "_push_lfm3_audio_release_config",}nodes = []for node in tree.body:@@ -286,6 +292,19 @@ def test_default_push_keeps_streaming_merger(saving):assert records["repos"] == []+def test_a_merged_push_of_another_model_resolves_no_extra_repo_id(saving):+ env, records, _ = saving++ def no_whoami(*args):+ raise AssertionError("a non LFM3-Audio merged push resolved the repo id again")++ env["_determine_username"] = no_whoami+ env["unsloth_generic_save"](+ PeftModel(), None, "model", push_to_hub = True, save_method = "merged_16bit"+ )+ assert records["merges"][0]["push_to_hub"] is True++def test_non_main_rank_does_not_create_or_upload(saving):env, records, _ = savingenv["unsloth_generic_save"](diff --git a/unsloth/save.py b/unsloth/save.pyindex cf109c5d519..5a5c6105634 100644--- a/unsloth/save.py+++ b/unsloth/save.py@@ -4006,6 +4006,105 @@ def _requests_float32(dtype):return dtype is torch.float32+def _base_config_dicts(model):+ """config.json of each base the model names (PEFT base, then _name_or_path), at the loaded commit, cache first."""+ config = getattr(model, "config", None)+ loaded = getattr(config, "_name_or_path", None)+ names = [+ getattr(peft_config, "base_model_name_or_path", None)+ for peft_config in (getattr(model, "peft_config", None) or {}).values()+ ]+ names.append(loaded)+ for name in dict.fromkeys(n for n in names if isinstance(n, str) and n):+ # The loaded config's _commit_hash pins the snapshot it came from; another repo has no pin.+ revision = getattr(config, "_commit_hash", None) if name == loaded else None+ try:+ if os.path.isdir(name):+ path = os.path.join(name, "config.json")+ else:+ from huggingface_hub import hf_hub_download+ try:+ path = hf_hub_download(+ name, "config.json", revision = revision, local_files_only = True+ )+ except Exception:+ path = hf_hub_download(name, "config.json", revision = revision)+ with open(path, encoding = "utf-8") as f:+ yield json.load(f)+ except Exception:+ continue+++def _restore_lfm3_audio_release_config(model, save_directory):+ """Swap LFM3-Audio's saved text_config layout for the base's release (lfm / encoder) one, the only one llama.cpp reads."""+ path = os.path.join(save_directory, "config.json")+ try:+ with open(path, encoding = "utf-8") as f:+ saved = json.load(f)+ except (OSError, ValueError):+ return False+ if saved.get("model_type") != "lfm3_audio" or "lfm" in saved:+ return False+ vocab = (saved.get("text_config") or {}).get("vocab_size")+ for release in _base_config_dicts(model):+ if release.get("model_type") != "lfm3_audio" or not isinstance(release.get("lfm"), dict):+ continue+ if vocab is not None and release["lfm"].get("vocab_size") != vocab:+ continue # resized embeddings: the release config no longer describes these weights+ # The dtype the weights were written in and the code modules the save copied, not the release's.+ # `lfm` takes text_config's schema: the effective text settings (e.g. a user rope_scaling) win over the release's.+ text = {k: v for k, v in (saved.get("text_config") or {}).items() if k != "_name_or_path"}+ release = {+ **release,+ "lfm": {**release["lfm"], **text},+ **{k: saved[k] for k in ("dtype", "torch_dtype", "auto_map") if k in saved},+ }+ with open(path, "w", encoding = "utf-8") as f:+ json.dump(release, f, indent = 2)+ return True+ print(+ "Unsloth: LFM3-Audio config.json is not in its release layout and the base's could not be read; "+ "llama.cpp's converter will not recognize it."+ )+ return False+++def _release_layout_for_merged_save(model, save_directory, save_method):+ # A merged folder has no PEFT base to read the release config from later. 4-bit keeps its quantization_config.+ if "16bit" not in str(save_method) or not os.path.isdir(str(save_directory)):+ return False+ return _restore_lfm3_audio_release_config(model, save_directory)+++def _push_lfm3_audio_release_config(+ model,+ save_directory,+ token = None,+):+ # The PEFT merged push uploads straight from the merge, so the release config follows it.+ if getattr(getattr(model, "config", None), "model_type", None) != "lfm3_audio":+ return False+ # Only now: for other models this whoami could raise after a finished upload.+ repo_id = _determine_username(save_directory, None, token)[0]+ import tempfile++ from huggingface_hub import HfApi, hf_hub_download++ with tempfile.TemporaryDirectory(prefix = "unsloth-lfm3-config-") as directory:+ hf_hub_download(+ repo_id, "config.json", token = token, local_dir = directory, force_download = True+ )+ if not _restore_lfm3_audio_release_config(model, directory):+ return False+ HfApi(token = token).upload_file(+ path_or_fileobj = os.path.join(directory, "config.json"),+ path_in_repo = "config.json",+ repo_id = repo_id,+ commit_message = "Unsloth: LFM3-Audio config in its release layout",+ )+ return True++def _stamp_saved_config_float32(save_directory):# save_pretrained writes the resident model's 16-bit dtype, and dtype = "auto" would then# cast the float32 tensors back down on load.@@ -5231,6 +5330,12 @@ def unsloth_save_pretrained_gguf(_drop_staged_checkpoint(staged_directory)raise+ try:+ _restore_lfm3_audio_release_config(self, save_directory)+ except BaseException:+ _drop_staged_checkpoint(staged_directory)+ raise+try:all_file_locations, want_full_precision, is_vlm_update = save_to_gguf(model_name = model_name,@@ -6868,6 +6973,7 @@ def unsloth_generic_save(print(f"Unsloth: Saving full fine-tuned model to '{save_directory}' ...")with _internal_mtp_save():model.save_pretrained(save_directory, **_save_kwargs)+ _release_layout_for_merged_save(model, save_directory, save_method)if "16bit" in save_method and _requests_float32(dtype):_stamp_saved_config_float32(save_directory)if (@@ -6961,6 +7067,9 @@ def unsloth_generic_save(# Pushes with an attached head were rerouted to a local save above.if not push_to_hub:_stitch_mtp_head(model, save_directory)+ _release_layout_for_merged_save(model, save_directory, save_method)+ elif "16bit" in save_method and is_main_process:+ _push_lfm3_audio_release_config(model, save_directory, token = token)if push_to_hub and datasets:try: