Skip to content

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.

Studio: load a 16-bit Continued Pretraining run in 16-bit in Chat (#11480)

Nilayaa745b8de46c
diff --git a/studio/backend/core/inference/worker.py b/studio/backend/core/inference/worker.py
index c27a5160e64..9a61c6c54b4 100644
--- a/studio/backend/core/inference/worker.py
+++ b/studio/backend/core/inference/worker.py
@@ -207,8 +207,9 @@ def _needs_nemotron_trust(model_name: str, hf_token: str | None = None) -> bool:
def _resolve_lora_4bit(mc, load_in_4bit: bool) -> bool:
"""Reconcile load_in_4bit with a LoRA adapter's recorded training method.
- lora -> base is full precision (4bit off); qlora -> base is quantized (4bit
- on); unknown method -> force off only when the base is not a -bnb-4bit repo.
+ A recorded unsloth_load_in_4bit wins; otherwise lora -> base is full precision
+ (4bit off); qlora -> base is quantized (4bit on); unknown method -> force off
+ only when the base is not a -bnb-4bit repo.
A missing or unreadable adapter_config.json leaves the value unchanged.
"""
from utils.models.checkpoints import is_full_finetune_output
@@ -228,6 +229,15 @@ def _resolve_lora_4bit(mc, load_in_4bit: bool) -> bool:
try:
with open(adapter_cfg_path, encoding = "utf-8-sig") as f:
adapter_cfg = json.load(f)
+ trained_in_4bit = adapter_cfg.get("unsloth_load_in_4bit")
+ if isinstance(trained_in_4bit, bool):
+ if trained_in_4bit != load_in_4bit:
+ logger.info(
+ "adapter_config.json says unsloth_load_in_4bit=%s — setting load_in_4bit=%s",
+ trained_in_4bit,
+ trained_in_4bit,
+ )
+ return trained_in_4bit
training_method = adapter_cfg.get("unsloth_training_method")
if training_method == "lora" and load_in_4bit:
logger.info("adapter_config.json says lora — setting load_in_4bit=False")
diff --git a/studio/backend/core/training/trainer.py b/studio/backend/core/training/trainer.py
index 2a1f8ac5523..fc8247f7017 100644
--- a/studio/backend/core/training/trainer.py
+++ b/studio/backend/core/training/trainer.py
@@ -173,6 +173,11 @@ def _drop_hf_stdout_callbacks(trainer) -> None:
pass
+# Audio types whose load_model branch hardcodes load_in_4bit=False into from_pretrained, so a
+# 4-bit request never reaches the loader and the base is always 16-bit (float32 for bicodec).
+_FORCED_16BIT_AUDIO_TYPES = frozenset({"csm", "whisper", "bicodec", "dac"})
+
+
def _bitsandbytes_allows_4bit() -> bool:
"""``loader.ALLOW_BITSANDBYTES``: False when bitsandbytes is absent or its native kernels
are unusable, which is the normal state on Studio's Mac, Intel and CPU installs and on
@@ -1020,6 +1025,13 @@ class UnslothTrainer:
)
_auto_dtype = torch.float16 if (_is_rocm and not is_bfloat16_supported()) else None
+ # The four branches below pass load_in_4bit=False to from_pretrained whatever was
+ # requested (Spark-TTS goes further and needs float32), so the base really is 16-bit.
+ # _patch_adapter_config saves self.load_in_4bit and Chat reloads the base at exactly
+ # that precision, so record what loaded, not what was asked for.
+ if self._audio_type in _FORCED_16BIT_AUDIO_TYPES:
+ self.load_in_4bit = False
+
if self._audio_type == "csm":
# Whisper: FastModel, auto_model=WhisperForConditionalGeneration, load_in_4bit=False
from unsloth import FastModel
@@ -4546,8 +4558,13 @@ class UnslothTrainer:
self.is_training = False
def _patch_adapter_config(self, output_dir: str) -> None:
- """Patch adapter_config.json with unsloth_training_method. Values: 'qlora', 'lora', 'FT',
- 'CPT', 'DPO', 'GRPO', etc. For LoRA/QLoRA, the distinction comes from load_in_4bit."""
+ """Patch adapter_config.json with unsloth_training_method and unsloth_load_in_4bit. Values:
+ 'qlora', 'lora', 'FT', 'CPT', 'DPO', 'GRPO', etc. For LoRA/QLoRA, the distinction comes
+ from load_in_4bit.
+
+ Both keys describe the base the run ACTUALLY trained on, so both read the same effective
+ flag: an install where bitsandbytes cannot run 4-bit trained on a 16-bit base and is a
+ 'lora', not a 'qlora' whose recorded precision happens to disagree with its own name."""
config_path = os.path.join(output_dir, "adapter_config.json")
if not os.path.exists(config_path):
logger.info("No adapter_config.json found — skipping training method patch")
@@ -4557,14 +4574,17 @@ class UnslothTrainer:
with open(config_path, "r", encoding = "utf-8") as f:
config = json.load(f)
+ trained_in_4bit = bool(self.load_in_4bit) and _bitsandbytes_allows_4bit()
+
if self.is_cpt:
method = "CPT"
- elif self.load_in_4bit:
+ elif trained_in_4bit:
method = "qlora"
else:
method = "lora"
config["unsloth_training_method"] = method
+ config["unsloth_load_in_4bit"] = trained_in_4bit
logger.info(f"Patching adapter_config.json with unsloth_training_method='{method}'")
with open(config_path, "w", encoding = "utf-8") as f:
diff --git a/studio/backend/routes/inference.py b/studio/backend/routes/inference.py
index 4753de0eaac..dd8be7253a2 100644
--- a/studio/backend/routes/inference.py
+++ b/studio/backend/routes/inference.py
@@ -10685,6 +10685,9 @@ def _effective_load_in_4bit(config: ModelConfig, requested: bool) -> bool:
except Exception as e:
logger.warning(f"Could not read adapter_config.json: {e}")
return load_in_4bit
+ trained_in_4bit = adapter_cfg.get("unsloth_load_in_4bit")
+ if isinstance(trained_in_4bit, bool):
+ return trained_in_4bit
training_method = adapter_cfg.get("unsloth_training_method")
if training_method == "lora":
return False
diff --git a/studio/backend/tests/test_adapter_training_precision.py b/studio/backend/tests/test_adapter_training_precision.py
new file mode 100644
index 00000000000..b17be229aa2
--- /dev/null
+++ b/studio/backend/tests/test_adapter_training_precision.py
@@ -0,0 +1,223 @@
+# SPDX-License-Identifier: AGPL-3.0-only
+# Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0
+
+"""A Studio adapter must load on the base precision it was trained on.
+
+A 16-bit Continued Pretraining run is tagged "CPT", which the resolvers treated as
+neither lora nor qlora, so Chat's load_in_4bit=True loaded the base in 4-bit.
+"""
+
+import ast
+import json
+import logging
+import os
+from pathlib import Path
+from types import SimpleNamespace
+
+import pytest
+
+from core.inference.worker import _resolve_lora_4bit
+
+_TRAINER = Path(__file__).resolve().parents[1] / "core/training/trainer.py"
+
+
+def _patch_adapter_config(bnb_usable = True):
+ tree = ast.parse(_TRAINER.read_text(encoding = "utf-8"))
+ cls = next(n for n in tree.body if isinstance(n, ast.ClassDef) and n.name == "UnslothTrainer")
+ fn = next(
+ n for n in cls.body if isinstance(n, ast.FunctionDef) and n.name == "_patch_adapter_config"
+ )
+ namespace = {
+ "os": os,
+ "json": json,
+ "logger": logging.getLogger(__name__),
+ "_bitsandbytes_allows_4bit": lambda: bnb_usable,
+ }
+ exec(compile(ast.Module(body = [fn], type_ignores = []), str(_TRAINER), "exec"), namespace)
+ return namespace["_patch_adapter_config"]
+
+
+def _adapter(tmp_path, payload, base_model):
+ (tmp_path / "adapter_config.json").write_text(json.dumps(payload))
+ return SimpleNamespace(is_lora = True, path = str(tmp_path), base_model = base_model)
+
+
+ "is_cpt, load_in_4bit, method",
+ [(True, False, "CPT"), (True, True, "CPT"), (False, False, "lora"), (False, True, "qlora")],
+)
+def test_trainer_records_training_precision(tmp_path, is_cpt, load_in_4bit, method):
+ (tmp_path / "adapter_config.json").write_text(json.dumps({"peft_type": "LORA"}))
+ trainer = SimpleNamespace(is_cpt = is_cpt, load_in_4bit = load_in_4bit)
+ _patch_adapter_config()(trainer, str(tmp_path))
+ cfg = json.loads((tmp_path / "adapter_config.json").read_text())
+ assert cfg["unsloth_training_method"] == method
+ assert cfg["unsloth_load_in_4bit"] is load_in_4bit
+
+
+def test_trainer_records_16bit_when_bitsandbytes_unusable(tmp_path):
+ (tmp_path / "adapter_config.json").write_text(json.dumps({"peft_type": "LORA"}))
+ trainer = SimpleNamespace(is_cpt = True, load_in_4bit = True)
+ _patch_adapter_config(bnb_usable = False)(trainer, str(tmp_path))
+ cfg = json.loads((tmp_path / "adapter_config.json").read_text())
+ assert cfg["unsloth_load_in_4bit"] is False
+
+
[email protected]("requested", [True, False])
+def test_worker_legacy_cpt_keeps_request(tmp_path, requested):
+ # A pre-flag CPT adapter may have been quantized on the fly from a non-bnb repo.
+ mc = _adapter(tmp_path, {"unsloth_training_method": "CPT"}, "unsloth/Qwen3-4B")
+ assert _resolve_lora_4bit(mc, requested) is requested
+
+
+def test_worker_cpt_on_bnb_base_keeps_4bit(tmp_path):
+ mc = _adapter(tmp_path, {"unsloth_training_method": "CPT"}, "unsloth/Qwen3-4B-unsloth-bnb-4bit")
+ assert _resolve_lora_4bit(mc, True) is True
+
+
[email protected]("recorded", [True, False])
[email protected]("requested", [True, False])
+def test_worker_recorded_precision_wins(tmp_path, recorded, requested):
+ payload = {"unsloth_training_method": "CPT", "unsloth_load_in_4bit": recorded}
+ mc = _adapter(tmp_path, payload, "unsloth/Qwen3-4B")
+ assert _resolve_lora_4bit(mc, requested) is recorded
+
+
+ "method, requested, expected",
+ [("lora", True, False), ("lora", False, False), ("qlora", True, True), ("qlora", False, True)],
+)
+def test_worker_lora_qlora_unchanged(tmp_path, method, requested, expected):
+ mc = _adapter(tmp_path, {"unsloth_training_method": method}, "unsloth/Qwen3-4B")
+ assert _resolve_lora_4bit(mc, requested) is expected
+
+
+def test_method_and_precision_never_disagree(tmp_path):
+ # bitsandbytes unusable (Mac, Intel, CPU, some AMD): the run trained on a 16-bit base, so
+ # it is a "lora". Tagging it "qlora" next to unsloth_load_in_4bit=false left the two keys
+ # contradicting each other, and the method is what the Hub card shows.
+ (tmp_path / "adapter_config.json").write_text(json.dumps({"peft_type": "LORA"}))
+ _patch_adapter_config(bnb_usable = False)(
+ SimpleNamespace(is_cpt = False, load_in_4bit = True), str(tmp_path)
+ )
+ cfg = json.loads((tmp_path / "adapter_config.json").read_text())
+ assert cfg["unsloth_training_method"] == "lora"
+ assert cfg["unsloth_load_in_4bit"] is False
+
+
+def _forced_16bit_branches_in_load_model():
+ """Audio branches of load_model that pass a literal load_in_4bit=False to from_pretrained."""
+ tree = ast.parse(_TRAINER.read_text(encoding = "utf-8"))
+ cls = next(n for n in tree.body if isinstance(n, ast.ClassDef) and n.name == "UnslothTrainer")
+ load_model = next(
+ n for n in cls.body if isinstance(n, ast.FunctionDef) and n.name == "load_model"
+ )
+ forced = set()
+ for node in ast.walk(load_model):
+ # `self._audio_type == "<name>"` guarding a from_pretrained(..., load_in_4bit = False)
+ if not (isinstance(node, ast.If) and isinstance(node.test, ast.Compare)):
+ continue
+ left, ops, comparators = node.test.left, node.test.ops, node.test.comparators
+ if not (
+ isinstance(left, ast.Attribute)
+ and left.attr == "_audio_type"
+ and len(ops) == 1
+ and isinstance(ops[0], ast.Eq)
+ and isinstance(comparators[0], ast.Constant)
+ and isinstance(comparators[0].value, str)
+ ):
+ continue
+ for call in (
+ c
+ for c in ast.walk(ast.Module(body = node.body, type_ignores = []))
+ if isinstance(c, ast.Call)
+ ):
+ if not (isinstance(call.func, ast.Attribute) and call.func.attr == "from_pretrained"):
+ continue
+ for kw in call.keywords:
+ if (
+ kw.arg == "load_in_4bit"
+ and isinstance(kw.value, ast.Constant)
+ and kw.value.value is False
+ ):
+ forced.add(comparators[0].value)
+ return forced
+
+
+def _declared_forced_16bit_audio_types():
+ """_FORCED_16BIT_AUDIO_TYPES read out of the source.
+
+ Read rather than imported: importing core.training.trainer pulls in torch and unsloth,
+ and a runner without them turns this assertion into a skip instead of a failure.
+ """
+ for node in ast.parse(_TRAINER.read_text(encoding = "utf-8")).body:
+ if isinstance(node, ast.Assign) and any(
+ getattr(t, "id", None) == "_FORCED_16BIT_AUDIO_TYPES" for t in node.targets
+ ):
+ value = node.value
+ # frozenset({...}) / set({...}) today, a bare literal if that is ever simplified
+ if isinstance(value, ast.Call) and value.args:
+ value = value.args[0]
+ return set(ast.literal_eval(value))
+ raise AssertionError("_FORCED_16BIT_AUDIO_TYPES is not defined in trainer.py")
+
+
+def test_forced_16bit_audio_types_match_the_loader():
+ # The constant is what _patch_adapter_config records for these runs; if a new audio type
+ # hardcodes a 16-bit load and is not listed, its adapter claims a 4-bit base it never used
+ # and Chat reloads it in 4-bit. Read the branches rather than trusting the list.
+ declared = _declared_forced_16bit_audio_types()
+ assert declared == _forced_16bit_branches_in_load_model()
+ # snac passes the request straight through, so it must NOT be in the set.
+ assert "snac" not in declared
+
+
+def test_load_model_records_the_forced_16bit_precision():
+ # _patch_adapter_config only ever sees self.load_in_4bit, so load_model has to correct it
+ # before the forced-16-bit branches run. Without this, the request is what gets recorded.
+ tree = ast.parse(_TRAINER.read_text(encoding = "utf-8"))
+ cls = next(n for n in tree.body if isinstance(n, ast.ClassDef) and n.name == "UnslothTrainer")
+ load_model = next(
+ n for n in cls.body if isinstance(n, ast.FunctionDef) and n.name == "load_model"
+ )
+ fixups = [
+ node
+ for node in ast.walk(load_model)
+ if isinstance(node, ast.If)
+ and any(
+ isinstance(n, ast.Name) and n.id == "_FORCED_16BIT_AUDIO_TYPES"
+ for n in ast.walk(node.test)
+ )
+ and any(
+ isinstance(n, ast.Assign)
+ and any(isinstance(t, ast.Attribute) and t.attr == "load_in_4bit" for t in n.targets)
+ and isinstance(n.value, ast.Constant)
+ and n.value.value is False
+ for n in node.body
+ )
+ ]
+ assert len(fixups) == 1, "load_model must set self.load_in_4bit = False for the forced types"
+ # It has to land before the branch chain it describes, or it records the wrong thing.
+ csm = next(
+ node
+ for node in ast.walk(load_model)
+ if isinstance(node, ast.If)
+ and isinstance(node.test, ast.Compare)
+ and isinstance(node.test.left, ast.Attribute)
+ and node.test.left.attr == "_audio_type"
+ and isinstance(node.test.comparators[0], ast.Constant)
+ and node.test.comparators[0].value == "csm"
+ )
+ assert fixups[0].lineno < csm.lineno
+
+
+def test_forced_16bit_audio_run_reloads_in_16bit(tmp_path):
+ # A csm/whisper/bicodec/dac run requested 4-bit, but the loader forced 16-bit. Recording the
+ # request would make Chat download a bnb-4bit base the run never trained on.
+ (tmp_path / "adapter_config.json").write_text(json.dumps({"peft_type": "LORA"}))
+ trainer = SimpleNamespace(is_cpt = False, load_in_4bit = False) # after the load_model fixup
+ _patch_adapter_config()(trainer, str(tmp_path))
+ cfg = json.loads((tmp_path / "adapter_config.json").read_text())
+ assert cfg["unsloth_load_in_4bit"] is False
+ mc = SimpleNamespace(is_lora = True, path = str(tmp_path), base_model = "unsloth/csm-1b")
+ assert _resolve_lora_4bit(mc, True) is False
diff --git a/studio/backend/tests/test_chat_load_during_training.py b/studio/backend/tests/test_chat_load_during_training.py
index e094f671aa3..cc49bf03f8b 100644
--- a/studio/backend/tests/test_chat_load_during_training.py
+++ b/studio/backend/tests/test_chat_load_during_training.py
@@ -895,6 +895,33 @@ class TestEffectiveLoadIn4bit(unittest.TestCase):
cfg = SimpleNamespace(is_lora = True, path = d, base_model = "meta/Llama-3-8B")
self.assertFalse(self.route._effective_load_in_4bit(cfg, True))
+ def test_legacy_cpt_method_non_bnb_base_keeps_request(self):
+ import tempfile
+ with tempfile.TemporaryDirectory() as d:
+ self._write_adapter(d, {"unsloth_training_method": "CPT"})
+ cfg = SimpleNamespace(is_lora = True, path = d, base_model = "unsloth/Qwen3-4B")
+ self.assertTrue(self.route._effective_load_in_4bit(cfg, True))
+
+ def test_cpt_method_bnb_base_keeps_4bit(self):
+ import tempfile
+ with tempfile.TemporaryDirectory() as d:
+ self._write_adapter(d, {"unsloth_training_method": "CPT"})
+ cfg = SimpleNamespace(
+ is_lora = True, path = d, base_model = "unsloth/Qwen3-4B-unsloth-bnb-4bit"
+ )
+ self.assertTrue(self.route._effective_load_in_4bit(cfg, True))
+
+ def test_recorded_precision_wins(self):
+ import tempfile
+ for recorded in (True, False):
+ for requested in (True, False):
+ with tempfile.TemporaryDirectory() as d:
+ self._write_adapter(
+ d, {"unsloth_training_method": "CPT", "unsloth_load_in_4bit": recorded}
+ )
+ cfg = SimpleNamespace(is_lora = True, path = d, base_model = "unsloth/Qwen3-4B")
+ self.assertIs(self.route._effective_load_in_4bit(cfg, requested), recorded)
+
def test_malformed_adapter_config_returns_request(self):
import tempfile
with tempfile.TemporaryDirectory() as d:
diff --git a/tests/test_cli_chat_compare_precision.py b/tests/test_cli_chat_compare_precision.py
new file mode 100644
index 00000000000..8428a2dd4ee
--- /dev/null
+++ b/tests/test_cli_chat_compare_precision.py
@@ -0,0 +1,37 @@
+# SPDX-License-Identifier: AGPL-3.0-only
+# Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0
+
+"""`unsloth chat --compare` must load the base column at the precision Studio loads the adapter at."""
+
+import json
+from types import SimpleNamespace
+
+import pytest
+
+from unsloth_cli.commands.chat import _get_base_load_in_4bit
+
+
+def _config(tmp_path, payload, base_model):
+ (tmp_path / "adapter_config.json").write_text(json.dumps(payload))
+ return SimpleNamespace(is_lora = True, path = str(tmp_path), base_model = base_model)
+
+
[email protected]("recorded", [True, False])
+def test_recorded_precision_wins(tmp_path, recorded):
+ payload = {"unsloth_training_method": "CPT", "unsloth_load_in_4bit": recorded}
+ assert _get_base_load_in_4bit(_config(tmp_path, payload, "unsloth/Qwen3-4B")) is recorded
+
+
+ "method, base_model, expected",
+ [
+ ("CPT", "unsloth/Qwen3-4B", True),
+ ("CPT", "unsloth/Qwen3-4B-unsloth-bnb-4bit", True),
+ ("lora", "unsloth/Qwen3-4B-unsloth-bnb-4bit", False),
+ ("qlora", "unsloth/Qwen3-4B", True),
+ (None, "unsloth/Qwen3-4B", False),
+ ],
+)
+def test_matches_studio_resolver(tmp_path, method, base_model, expected):
+ payload = {"unsloth_training_method": method} if method else {}
+ assert _get_base_load_in_4bit(_config(tmp_path, payload, base_model)) is expected
diff --git a/unsloth_cli/commands/chat.py b/unsloth_cli/commands/chat.py
index be6a86178ca..f3b855ddc0e 100644
--- a/unsloth_cli/commands/chat.py
+++ b/unsloth_cli/commands/chat.py
@@ -78,15 +78,20 @@ def _get_base_load_in_4bit(model_config) -> bool:
with open(adapter_cfg_path, encoding = "utf-8") as f:
adapter_cfg = json.load(f)
+ trained_in_4bit = adapter_cfg.get("unsloth_load_in_4bit")
+ if isinstance(trained_in_4bit, bool):
+ return trained_in_4bit
training_method = adapter_cfg.get("unsloth_training_method")
if training_method == "lora":
return False
- elif training_method == "qlora":
- return True
- elif not training_method:
- if model_config.base_model and "-bnb-4bit" not in model_config.base_model.lower():
- return False
+ if training_method == "qlora":
return True
+ if (
+ not training_method
+ and model_config.base_model
+ and "-bnb-4bit" not in model_config.base_model.lower()
+ ):
+ return False
return True
except Exception:
return True