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.

gpt-oss: load_in_4bit from a BF16 checkpoint no longer loads random experts and router (#14400)

Daniel Han723a43b02ab0
diff --git a/tests/test_gpt_oss_bf16_load_in_4bit.py b/tests/test_gpt_oss_bf16_load_in_4bit.py
new file mode 100644
index 00000000000..0b2e5e7b4d6
--- /dev/null
+++ b/tests/test_gpt_oss_bf16_load_in_4bit.py
@@ -0,0 +1,229 @@
+# Unsloth Zoo - Utilities for Unsloth
+# Copyright 2023-present Daniel Han-Chen, Michael Han-Chen & the Unsloth team. All rights reserved.
+#
+# This program is free software: you can redistribute it and/or modify
+# it under the terms of the GNU Affero General Public License as published
+# by the Free Software Foundation, either version 3 of the License, or
+# (at your option) any later version.
+#
+# This program is distributed in the hope that it will be useful,
+# but WITHOUT ANY WARRANTY; without even the implied warranty of
+# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+# GNU Affero General Public License for more details.
+#
+# You should have received a copy of the GNU Affero General Public License
+# along with this program. If not, see <https://www.gnu.org/licenses/>.
+
+"""gpt-oss fused BF16 checkpoint + load_in_4bit must not go through zoo's bnb split-expert classes (random experts)."""
+
+import os
+from types import SimpleNamespace
+
+import pytest
+import torch
+
+import unsloth # noqa: F401 (patches before transformers)
+from unsloth.models import loader_utils
+
+
+def gpt_oss_checkpoint_has_fused_experts(config):
+ return loader_utils.gpt_oss_checkpoint_has_fused_experts(config)
+
+
+def sync_unsloth_model_name_bnb_flags(*args, **kwargs):
+ return loader_utils.sync_unsloth_model_name_bnb_flags(*args, **kwargs)
+
+
+BNB_QC = {"quant_method": "bitsandbytes", "load_in_4bit": True}
+MXFP4_QC = {"quant_method": "mxfp4"}
+
+
+def test_fused_4bit_refused_in_float16():
+ with pytest.raises(NotImplementedError, match = "overflow"):
+ loader_utils.refuse_gpt_oss_fused_4bit_float16(torch.float16)
+ loader_utils.refuse_gpt_oss_fused_4bit_float16(torch.bfloat16)
+ loader_utils.refuse_gpt_oss_fused_4bit_float16(torch.float32)
+
+
+def test_loader_refuses_before_the_fused_4bit_load():
+ import inspect
+
+ from unsloth.models import loader
+
+ source = inspect.getsource(loader)
+ branch = source.index("this gpt-oss checkpoint stores fused experts, so it loads")
+ assert "refuse_gpt_oss_fused_4bit_float16(dtype)" in source[branch - 300 : branch]
+
+
+def test_fused_checkpoint_detection():
+ assert gpt_oss_checkpoint_has_fused_experts(None) is None
+ assert gpt_oss_checkpoint_has_fused_experts(SimpleNamespace()) is True
+ assert gpt_oss_checkpoint_has_fused_experts(SimpleNamespace(quantization_config = None)) is True
+ assert (
+ gpt_oss_checkpoint_has_fused_experts(SimpleNamespace(quantization_config = BNB_QC)) is False
+ )
+ assert (
+ gpt_oss_checkpoint_has_fused_experts(SimpleNamespace(quantization_config = MXFP4_QC)) is False
+ )
+
+
+ "config, expected",
+ [
+ (SimpleNamespace(), "gpt_oss,"), # fused BF16: no bnb split classes
+ (SimpleNamespace(quantization_config = BNB_QC), "gpt_oss,_load_in_4bit_"),
+ (None, "gpt_oss,_load_in_4bit_"), # unknown config: unchanged behaviour
+ ],
+)
+def test_sync_token(monkeypatch, config, expected):
+ monkeypatch.setenv("UNSLOTH_MODEL_NAME", "gpt_oss,_load_in_4bit_")
+ monkeypatch.setenv("UNSLOTH_GPT_OSS_BNB4BIT_PATCHED", "0")
+ sync_unsloth_model_name_bnb_flags(True, False, config = config)
+ assert os.environ["UNSLOTH_MODEL_NAME"] == expected
+
+
+def test_sync_refuses_when_split_classes_already_installed(monkeypatch):
+ monkeypatch.setenv("UNSLOTH_MODEL_NAME", "gpt_oss,_load_in_4bit_")
+ monkeypatch.setenv("UNSLOTH_GPT_OSS_BNB4BIT_PATCHED", "1")
+ with pytest.raises(RuntimeError, match = "randomly initialised"):
+ sync_unsloth_model_name_bnb_flags(True, False, config = SimpleNamespace())
+
+
+def test_sync_ignores_other_models(monkeypatch):
+ monkeypatch.setenv("UNSLOTH_MODEL_NAME", "llama,_load_in_4bit_")
+ monkeypatch.setenv("UNSLOTH_GPT_OSS_BNB4BIT_PATCHED", "1")
+ sync_unsloth_model_name_bnb_flags(True, False, config = SimpleNamespace())
+ assert os.environ["UNSLOTH_MODEL_NAME"] == "llama,_load_in_4bit_"
+
+
[email protected](not torch.cuda.is_available(), reason = "needs a CUDA GPU for bitsandbytes")
+def test_bf16_checkpoint_loads_real_weights_in_4bit(tmp_path):
+ pytest.importorskip("bitsandbytes")
+ from safetensors.torch import load_file
+ from transformers import AutoModelForCausalLM, AutoTokenizer
+
+ src = "trl-internal-testing/tiny-GptOssForCausalLM"
+ ckpt = str(tmp_path / "tiny_gpt_oss_bf16")
+ ref = AutoModelForCausalLM.from_pretrained(src, dtype = torch.bfloat16)
+ torch.manual_seed(0)
+ with torch.no_grad():
+ for name, param in ref.named_parameters():
+ if "experts" in name or "router" in name:
+ param.normal_(0.0, 0.05)
+ ref.save_pretrained(ckpt)
+ AutoTokenizer.from_pretrained(src).save_pretrained(ckpt)
+ del ref
+ sd = load_file(os.path.join(ckpt, "model.safetensors"))
+
+ from unsloth import FastLanguageModel
+ import bitsandbytes.functional as bnbF
+
+ model, _ = FastLanguageModel.from_pretrained(
+ ckpt, max_seq_length = 64, load_in_4bit = True, dtype = torch.bfloat16
+ )
+ mlp = model.model.layers[0].mlp
+ router = mlp.router
+ router_w = router.linear.weight if hasattr(router, "linear") else router.weight
+ torch.testing.assert_close(
+ router_w.detach().float().cpu(), sd["model.layers.0.mlp.router.weight"].float()
+ )
+
+ experts = mlp.experts
+ assert hasattr(experts, "gate_up_proj"), type(experts)
+ w = experts.gate_up_proj
+ assert type(w).__name__ == "Params4bit" and w.quant_state is not None
+ deq = bnbF.dequantize_4bit(w.data, w.quant_state).float().cpu()
+ ck = sd["model.layers.0.mlp.experts.gate_up_proj"].float()
+ if deq.shape != ck.shape:
+ deq = deq.transpose(-1, -2)
+ assert float((deq - ck).abs().max()) < 0.25 * float(ck.abs().max())
+
+ model = FastLanguageModel.get_peft_model(
+ model,
+ r = 4,
+ lora_alpha = 8,
+ target_modules = ["q_proj", "gate_up_proj", "down_proj"],
+ )
+ FastLanguageModel.for_training(model)
+ ids = torch.randint(0, 200, (1, 16), device = "cuda")
+ loss = model(input_ids = ids, labels = ids).loss
+ loss.backward()
+ assert torch.isfinite(loss)
+ expert_grads = [
+ p.grad
+ for n, p in model.named_parameters()
+ if "experts" in n and "lora_B" in n and p.grad is not None
+ ]
+ assert expert_grads and any(float(g.abs().sum()) > 0 for g in expert_grads)
+
+
[email protected](not torch.cuda.is_available(), reason = "needs a CUDA GPU for bitsandbytes")
+def test_bf16_checkpoint_4bit_generate_matches_prefill(tmp_path):
+ """One-token decode on the fused Params4bit experts gives the prefill (module forward) logits."""
+ pytest.importorskip("bitsandbytes")
+ from transformers import AutoModelForCausalLM, AutoTokenizer
+
+ src = "trl-internal-testing/tiny-GptOssForCausalLM"
+ ckpt = str(tmp_path / "tiny_gpt_oss_bf16")
+ ref = AutoModelForCausalLM.from_pretrained(src, dtype = torch.bfloat16)
+ torch.manual_seed(0)
+ with torch.no_grad():
+ for name, param in ref.named_parameters():
+ if "experts" in name or "router" in name:
+ param.normal_(0.0, 0.05)
+ ref.save_pretrained(ckpt)
+ AutoTokenizer.from_pretrained(src).save_pretrained(ckpt)
+ del ref
+
+ from unsloth import FastLanguageModel
+
+ model, _ = FastLanguageModel.from_pretrained(
+ ckpt, max_seq_length = 64, load_in_4bit = True, dtype = torch.bfloat16
+ )
+ assert type(model.model.layers[0].mlp.experts.gate_up_proj).__name__ == "Params4bit"
+ FastLanguageModel.for_inference(model)
+ ids = torch.tensor([[1, 5, 9, 17, 33, 2, 40]], device = "cuda")
+ out = model.generate(
+ input_ids = ids,
+ max_new_tokens = 4,
+ do_sample = False,
+ output_logits = True,
+ return_dict_in_generate = True,
+ )
+ seq = out.sequences
+ assert seq.shape[1] == ids.shape[1] + 4
+ with torch.no_grad():
+ full = model(input_ids = seq, use_cache = False).logits.float()
+ n = ids.shape[1]
+ for step, step_logits in enumerate(out.logits):
+ expect = full[:, n - 1 + step]
+ got = step_logits.float()
+ assert torch.equal(got.argmax(-1), seq[:, n + step])
+ rel = float((got - expect).norm() / expect.norm())
+ assert rel < 2e-2, (step, rel)
+ assert torch.equal(full[:, n - 1 : -1].argmax(-1), seq[:, n:])
+
+
+ "name, config, load_in_4bit, keeps",
+ [
+ ("unsloth/gpt-oss-20b-BF16", SimpleNamespace(), True, False), # bnb 4-bit
+ ("unsloth/gpt-oss-20b-BF16", SimpleNamespace(), False, True), # 8-bit: as before the PR
+ ("openai/gpt-oss-20b", SimpleNamespace(quantization_config = MXFP4_QC), True, True),
+ ("openai/gpt-oss-120b", SimpleNamespace(quantization_config = MXFP4_QC), False, True),
+ ("unsloth/Llama-3.2-1B", SimpleNamespace(), False, False),
+ ],
+)
+def test_unquantized_gpt_oss_takes_bnb_only_for_4bit(name, config, load_in_4bit, keeps):
+ # bnb 8-bit replaces nn.Linear only, so the fused expert parameters would stay 16-bit.
+ assert loader_utils.gpt_oss_keeps_checkpoint_quantization(name, config, load_in_4bit) is keeps
+
+
+def test_vision_uses_the_gpt_oss_bnb_rule():
+ import inspect
+
+ from unsloth.models import vision
+
+ source = inspect.getsource(vision.FastBaseModel.from_pretrained)
+ assert "gpt_oss_keeps_checkpoint_quantization(model_name, auto_config, load_in_4bit)" in source
+ assert '"gpt-oss-20b" in model_name.lower()' not in source
diff --git a/tests/test_gpt_oss_bnb_checkpoint_layout.py b/tests/test_gpt_oss_bnb_checkpoint_layout.py
new file mode 100644
index 00000000000..9b052af00f9
--- /dev/null
+++ b/tests/test_gpt_oss_bnb_checkpoint_layout.py
@@ -0,0 +1,510 @@
+# Unsloth Zoo - Utilities for Unsloth
+# Copyright 2023-present Daniel Han-Chen, Michael Han-Chen & the Unsloth team. All rights reserved.
+#
+# This program is free software: you can redistribute it and/or modify
+# it under the terms of the GNU Affero General Public License as published
+# by the Free Software Foundation, either version 3 of the License, or
+# (at your option) any later version.
+#
+# This program is distributed in the hope that it will be useful,
+# but WITHOUT ANY WARRANTY; without even the implied warranty of
+# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+# GNU Affero General Public License for more details.
+#
+# You should have received a copy of the GNU Affero General Public License
+# along with this program. If not, see <https://www.gnu.org/licenses/>.
+
+"""A bitsandbytes gpt-oss checkpoint's expert layout comes from its tensor names, not from the
+presence of a quantization_config: a fused model quantized by Unsloth and saved keeps fused names."""
+
+import json
+import os
+import shutil
+from types import SimpleNamespace
+
+import pytest
+import torch
+from safetensors.torch import save_file
+
+import unsloth # noqa: F401 (patches before transformers)
+from unsloth.models import loader_utils
+
+BNB_QC = {"quant_method": "bitsandbytes", "load_in_4bit": True}
+MXFP4_QC = {"quant_method": "mxfp4"}
+P = "model.layers.0.mlp"
+
+SPLIT = [
+ f"{P}.experts.gate_up_projs.0.weight",
+ f"{P}.experts.down_projs.0.weight",
+ f"{P}.router.linear.weight",
+]
+# Fused experts packed to 4-bit with their quant state (what zoo's fused loader reads back).
+FUSED_QS = [
+ f"{P}.experts.gate_up_proj",
+ f"{P}.experts.gate_up_proj.absmax",
+ f"{P}.experts.gate_up_proj.quant_map",
+ f"{P}.experts.down_proj",
+ f"{P}.experts.down_proj.absmax",
+ f"{P}.router.weight",
+]
+# Dense fused experts beside 4-bit attention (the unsloth/gpt-oss-20b-bnb-4bit layout).
+FUSED_DENSE = [f"{P}.experts.gate_up_proj", f"{P}.experts.down_proj", f"{P}.router.weight"]
+# Packed bytes with no quant state: what save_pretrained writes for Unsloth's fused 4-bit experts.
+FUSED_PACKED = FUSED_DENSE
+
+
+def _tensors(names, packed):
+ return {
+ n: torch.zeros(4, 1, dtype = torch.uint8)
+ if packed and n.endswith(("experts.gate_up_proj", "experts.down_proj"))
+ else torch.zeros(2, 2, dtype = torch.bfloat16)
+ for n in names
+ }
+
+
+def _single(
+ tmp_path,
+ names,
+ packed = False,
+):
+ d = tmp_path / "ckpt"
+ d.mkdir()
+ save_file(_tensors(names, packed), str(d / "model.safetensors"))
+ return str(d)
+
+
+def _sharded(
+ tmp_path,
+ names,
+ packed = False,
+):
+ d = tmp_path / "ckpt"
+ d.mkdir()
+ shard = "model-00001-of-00001.safetensors"
+ save_file(_tensors(names, packed), str(d / shard))
+ (d / "model.safetensors.index.json").write_text(
+ json.dumps({"metadata": {}, "weight_map": {n: shard for n in names}})
+ )
+ return str(d)
+
+
+def _fused(config, path):
+ return loader_utils.gpt_oss_checkpoint_has_fused_experts(config, path)
+
+
[email protected]("write", [_single, _sharded])
+def test_bnb_split_prequantized_is_not_fused(tmp_path, write):
+ cfg = SimpleNamespace(quantization_config = BNB_QC)
+ assert _fused(cfg, write(tmp_path, SPLIT)) is False
+
+
[email protected]("write", [_single, _sharded])
+def test_bnb_fused_with_quant_state_is_fused(tmp_path, write):
+ cfg = SimpleNamespace(quantization_config = BNB_QC)
+ assert _fused(cfg, write(tmp_path, FUSED_QS)) is True
+
+
[email protected]("write", [_single, _sharded])
+def test_bnb_dense_fused_experts_are_fused(tmp_path, write):
+ cfg = SimpleNamespace(quantization_config = BNB_QC)
+ assert _fused(cfg, write(tmp_path, FUSED_DENSE)) is True
+
+
[email protected]("write", [_single, _sharded])
+def test_bnb_packed_fused_without_quant_state_refuses(tmp_path, write):
+ cfg = SimpleNamespace(quantization_config = BNB_QC)
+ with pytest.raises(RuntimeError, match = "quantization state"):
+ _fused(cfg, write(tmp_path, FUSED_PACKED, packed = True))
+
+
+def test_mxfp4_and_unreadable_keep_the_config_rule(tmp_path):
+ assert (
+ _fused(SimpleNamespace(quantization_config = MXFP4_QC), _single(tmp_path, FUSED_DENSE))
+ is False
+ )
+ empty = tmp_path / "empty"
+ empty.mkdir()
+ assert _fused(SimpleNamespace(quantization_config = BNB_QC), str(empty)) is False
+ assert _fused(SimpleNamespace(quantization_config = BNB_QC), None) is False
+ assert (
+ loader_utils._gpt_oss_bnb_checkpoint_expert_layout({f"{P}.self_attn.q_proj.weight": "U8"})
+ is None
+ )
+ assert _fused(SimpleNamespace(), str(empty)) is True
+ assert _fused(None, str(empty)) is None
+
+
+def test_sync_keeps_4bit_token_off_for_saved_fused_bnb(tmp_path, monkeypatch):
+ monkeypatch.setenv("UNSLOTH_MODEL_NAME", "gpt_oss,_load_in_4bit_")
+ monkeypatch.setenv("UNSLOTH_GPT_OSS_BNB4BIT_PATCHED", "0")
+ loader_utils.sync_unsloth_model_name_bnb_flags(
+ True,
+ False,
+ config = SimpleNamespace(quantization_config = BNB_QC),
+ model_name = _single(tmp_path, FUSED_QS),
+ )
+ assert os.environ["UNSLOTH_MODEL_NAME"] == "gpt_oss,"
+
+
+def test_hub_names_without_downloading_weights(monkeypatch):
+ import huggingface_hub
+
+ calls = []
+
+ def no_weights(repo_id, filename, *args, **kwargs):
+ calls.append((filename, kwargs.get("local_files_only")))
+ if filename.endswith(".safetensors") and not kwargs.get("local_files_only"):
+ raise AssertionError("downloaded weights")
+ raise FileNotFoundError(filename) # no index, weights not cached: header range read
+
+ monkeypatch.setattr(huggingface_hub, "hf_hub_download", no_weights)
+ seen = []
+ tensors = {n: SimpleNamespace(dtype = "BF16") for n in FUSED_DENSE}
+ monkeypatch.setattr(
+ huggingface_hub,
+ "get_safetensors_metadata",
+ lambda repo_id, **kw: seen.append(repo_id)
+ or SimpleNamespace(
+ weight_map = {n: "m" for n in FUSED_DENSE},
+ files_metadata = {"m": SimpleNamespace(tensors = tensors)},
+ ),
+ )
+ dtypes = loader_utils._checkpoint_tensor_dtypes("someone/gpt-oss-bnb")
+ assert seen == ["someone/gpt-oss-bnb"] and dtypes == {n: "BF16" for n in FUSED_DENSE}
+ assert calls == []
+ # Offline: only cached files, never the weights.
+ assert (
+ loader_utils._checkpoint_tensor_dtypes("someone/gpt-oss-bnb", local_files_only = True) is None
+ )
+ assert ("model.safetensors", True) in calls and seen == ["someone/gpt-oss-bnb"]
+
+
+def _expert_weight(experts, name):
+ import bitsandbytes.functional as bnbF
+
+ w = getattr(experts, name)
+ if getattr(w, "quant_state", None) is not None:
+ return bnbF.dequantize_4bit(w.data, w.quant_state).float().cpu()
+ return w.detach().float().cpu()
+
+
[email protected](not torch.cuda.is_available(), reason = "needs a CUDA GPU for bitsandbytes")
+def test_reload_of_saved_fused_4bit_checkpoints(tmp_path):
+ pytest.importorskip("bitsandbytes")
+ from safetensors.torch import load_file
+ from transformers import AutoModelForCausalLM, AutoTokenizer
+
+ src = "trl-internal-testing/tiny-GptOssForCausalLM"
+ ckpt = str(tmp_path / "bf16")
+ ref = AutoModelForCausalLM.from_pretrained(src, dtype = torch.bfloat16)
+ torch.manual_seed(0)
+ with torch.no_grad():
+ for name, param in ref.named_parameters():
+ if "experts" in name or "router" in name:
+ param.normal_(0.0, 0.05)
+ ref.save_pretrained(ckpt)
+ AutoTokenizer.from_pretrained(src).save_pretrained(ckpt)
+ del ref
+ original = load_file(os.path.join(ckpt, "model.safetensors"))
+
+ from unsloth import FastLanguageModel
+
+ load = dict(max_seq_length = 64, load_in_4bit = True, dtype = torch.bfloat16)
+ model, tokenizer = FastLanguageModel.from_pretrained(ckpt, **load)
+ saved = str(tmp_path / "saved_4bit")
+ model.save_pretrained(saved)
+ tokenizer.save_pretrained(saved)
+ del model
+ torch.cuda.empty_cache()
+
+ tensors_saved = load_file(os.path.join(saved, "model.safetensors"))
+
+ # bnb config with dense fused experts (the unsloth/gpt-oss-20b-bnb-4bit layout).
+ dense = str(tmp_path / "dense_experts_4bit")
+ os.makedirs(dense)
+ for f in os.listdir(saved):
+ if f != "model.safetensors":
+ shutil.copy(os.path.join(saved, f), dense)
+ tensors = dict(tensors_saved)
+ for name in list(tensors):
+ if name.endswith(("experts.gate_up_proj", "experts.down_proj")):
+ tensors[name] = original[name]
+ save_file(tensors, os.path.join(dense, "model.safetensors"), metadata = {"format": "pt"})
+
+ model, _ = FastLanguageModel.from_pretrained(dense, **load)
+ for layer_idx, layer in enumerate(model.model.layers):
+ mlp = layer.mlp
+ prefix = f"model.layers.{layer_idx}.mlp"
+ assert not hasattr(mlp.experts, "gate_up_projs"), type(mlp.experts)
+ router_w = mlp.router.linear.weight if hasattr(mlp.router, "linear") else mlp.router.weight
+ torch.testing.assert_close(
+ router_w.detach().float().cpu(), original[f"{prefix}.router.weight"].float()
+ )
+ for name in ("gate_up_proj", "down_proj"):
+ got = _expert_weight(mlp.experts, name)
+ want = original[f"{prefix}.experts.{name}"].float()
+ if got.shape != want.shape:
+ got = got.transpose(-1, -2)
+ assert float((got - want).abs().max()) < 0.25 * float(want.abs().max()), (
+ layer_idx,
+ name,
+ )
+ del model
+ torch.cuda.empty_cache()
+
+ # Unsloth's own 4-bit save: never split classes with random experts.
+ packed = tensors_saved["model.layers.0.mlp.experts.gate_up_proj"].dtype == torch.uint8
+ if packed and "model.layers.0.mlp.experts.gate_up_proj.absmax" not in tensors_saved:
+ with pytest.raises(RuntimeError, match = "quantization state"):
+ FastLanguageModel.from_pretrained(saved, **load)
+ else:
+ model, _ = FastLanguageModel.from_pretrained(saved, **load)
+ assert not hasattr(model.model.layers[0].mlp.experts, "gate_up_projs")
+ del model
+
+
+# pytorch_model.bin checkpoints, variants, and the float16 refusal for fused bnb checkpoints.
+
+
+def _variant(filename, variant):
+ # transformers' _add_variant: model.safetensors -> model.fp16.safetensors.
+ if not variant:
+ return filename
+ parts = filename.split(".")
+ return ".".join(parts[:-1] + [variant, parts[-1]])
+
+
+def _bin_sharded(
+ tmp_path,
+ names,
+ variant = None,
+):
+ d = tmp_path / "ckpt"
+ d.mkdir()
+ shard = "pytorch_model-00001-of-00001.bin"
+ torch.save(_tensors(names, False), str(d / shard))
+ index = _variant("pytorch_model.bin.index.json", variant)
+ (d / index).write_text(json.dumps({"metadata": {}, "weight_map": {n: shard for n in names}}))
+ return str(d)
+
+
[email protected]("names, expected", [(FUSED_QS, True), (SPLIT, False)])
+def test_bin_index_names_are_read(tmp_path, names, expected):
+ cfg = SimpleNamespace(quantization_config = BNB_QC)
+ assert _fused(cfg, _bin_sharded(tmp_path, names)) is expected
+
+
[email protected]("names, expected", [(FUSED_QS, True), (SPLIT, False)])
+def test_lone_bin_names_are_read_without_an_index(tmp_path, names, expected):
+ d = tmp_path / "ckpt"
+ d.mkdir()
+ torch.save(_tensors(names, False), str(d / "pytorch_model.bin"))
+ assert _fused(SimpleNamespace(quantization_config = BNB_QC), str(d)) is expected
+
+
+def test_lone_unreadable_bin_fails_closed(tmp_path):
+ d = tmp_path / "ckpt"
+ d.mkdir()
+ # Legacy (non zip) serialization cannot be memory mapped, so the names are unreadable.
+ torch.save(
+ _tensors(FUSED_QS, False),
+ str(d / "pytorch_model.bin"),
+ _use_new_zipfile_serialization = False,
+ )
+ cfg = SimpleNamespace(quantization_config = BNB_QC)
+ with pytest.raises(loader_utils.GptOssUnknownExpertLayoutError, match = "safe_serialization"):
+ _fused(cfg, str(d))
+ # Unsloth's split pre-quantized repos are named *-unsloth-bnb-4bit.
+ named = tmp_path / "gpt-oss-20b-unsloth-bnb-4bit"
+ shutil.copytree(d, named)
+ assert _fused(cfg, str(named)) is False
+
+
[email protected]("write", [_single, _sharded, _bin_sharded])
+def test_variant_files_are_read(tmp_path, write):
+ path = write(tmp_path, FUSED_QS)
+ for f in os.listdir(path):
+ if f.startswith(("model.safetensors", "pytorch_model.bin.index")):
+ os.rename(os.path.join(path, f), os.path.join(path, _variant(f, "fp16")))
+ cfg = SimpleNamespace(quantization_config = BNB_QC)
+ assert loader_utils.gpt_oss_checkpoint_has_fused_experts(cfg, path, variant = "fp16") is True
+
+
+def test_sync_passes_variant(tmp_path, monkeypatch):
+ path = _single(tmp_path, FUSED_QS)
+ os.rename(os.path.join(path, "model.safetensors"), os.path.join(path, "model.fp16.safetensors"))
+ monkeypatch.setenv("UNSLOTH_MODEL_NAME", "gpt_oss,_load_in_4bit_")
+ monkeypatch.setenv("UNSLOTH_GPT_OSS_BNB4BIT_PATCHED", "0")
+ loader_utils.sync_unsloth_model_name_bnb_flags(
+ True,
+ False,
+ config = SimpleNamespace(quantization_config = BNB_QC),
+ model_name = path,
+ variant = "fp16",
+ )
+ assert os.environ["UNSLOTH_MODEL_NAME"] == "gpt_oss,"
+
+
+def _hub(
+ monkeypatch,
+ files,
+ exists = (),
+):
+ """Fake Hub repo: `files` maps index json names to weight maps; nothing else is downloadable."""
+ import huggingface_hub
+
+ calls = []
+
+ def download(repo_id, filename, *args, **kwargs):
+ calls.append(filename)
+ if filename in files:
+ p = os.path.join(os.environ["TMPDIR"], "w17_hub_" + filename)
+ with open(p, "w") as f:
+ json.dump({"weight_map": files[filename]}, f)
+ return p
+ if not filename.endswith(".json") and not kwargs.get("local_files_only"):
+ raise AssertionError(f"downloaded weights {filename}")
+ raise FileNotFoundError(filename)
+
+ def no_metadata(*a, **k):
+ raise FileNotFoundError("no safetensors")
+
+ monkeypatch.setattr(huggingface_hub, "hf_hub_download", download)
+ monkeypatch.setattr(huggingface_hub, "get_safetensors_metadata", no_metadata)
+ monkeypatch.setattr(huggingface_hub, "file_exists", lambda repo, f, **k: f in exists)
+ monkeypatch.setattr(loader_utils, "_hub_safetensors_header_dtypes", no_metadata, raising = False)
+ return calls
+
+
+def test_hub_bin_index_and_variant_index(monkeypatch, tmp_path):
+ monkeypatch.setenv("TMPDIR", str(tmp_path))
+ cfg = SimpleNamespace(quantization_config = BNB_QC)
+ _hub(monkeypatch, {"pytorch_model.bin.index.json": {n: "x.bin" for n in FUSED_QS}})
+ assert _fused(cfg, "someone/gpt-oss-bin") is True
+ _hub(monkeypatch, {"model.safetensors.index.fp16.json": {n: "x" for n in FUSED_QS}})
+ assert (
+ loader_utils.gpt_oss_checkpoint_has_fused_experts(cfg, "someone/gpt-oss-v", variant = "fp16")
+ is True
+ )
+
+
+def test_hub_lone_bin_fails_closed(monkeypatch, tmp_path):
+ monkeypatch.setenv("TMPDIR", str(tmp_path))
+ cfg = SimpleNamespace(quantization_config = BNB_QC)
+ _hub(monkeypatch, {}, exists = ("pytorch_model.bin",))
+ with pytest.raises(loader_utils.GptOssUnknownExpertLayoutError):
+ _fused(cfg, "someone/gpt-oss-bin")
+ assert _fused(cfg, "unsloth/gpt-oss-20b-unsloth-bnb-4bit") is False
+ _hub(monkeypatch, {}) # nothing readable and no bin: unknown keeps the config rule
+ assert _fused(cfg, "someone/gpt-oss-none") is False
+
+
+def _fused_bnb_tiny(tmp_path):
+ from transformers import AutoConfig
+
+ d = tmp_path / "fused_bnb"
+ d.mkdir()
+ config = AutoConfig.from_pretrained("trl-internal-testing/tiny-GptOssForCausalLM")
+ config.quantization_config = dict(BNB_QC, bnb_4bit_compute_dtype = "float16")
+ config.save_pretrained(str(d))
+ save_file(_tensors(FUSED_QS, False), str(d / "model.safetensors"))
+ return str(d)
+
+
[email protected]("load_in_4bit", [True, False])
+def test_fused_bnb_checkpoint_refused_in_float16_without_load_in_4bit(tmp_path, load_in_4bit):
+ from unsloth import FastLanguageModel
+ with pytest.raises(NotImplementedError, match = "overflow"):
+ FastLanguageModel.from_pretrained(
+ _fused_bnb_tiny(tmp_path),
+ max_seq_length = 64,
+ load_in_4bit = load_in_4bit,
+ dtype = torch.float16,
+ )
+
+
+def test_bin_index_packed_without_quant_state_refuses(tmp_path):
+ # The fused dtype is read from the indexed .bin shard, so packed bytes without .absmax are caught.
+ d = tmp_path / "ckpt"
+ d.mkdir()
+ shard = "pytorch_model-00001-of-00001.bin"
+ torch.save(_tensors(FUSED_PACKED, True), str(d / shard))
+ (d / "pytorch_model.bin.index.json").write_text(
+ json.dumps({"metadata": {}, "weight_map": {n: shard for n in FUSED_PACKED}})
+ )
+ cfg = SimpleNamespace(quantization_config = BNB_QC)
+ with pytest.raises(RuntimeError, match = "quantization state"):
+ _fused(cfg, str(d))
+ # Dense 16-bit experts in the same layout stay fused.
+ torch.save(_tensors(FUSED_DENSE, False), str(d / shard))
+ assert _fused(cfg, str(d)) is True
+
+
+def test_hub_bin_index_with_unknown_fused_dtype_fails_closed(monkeypatch, tmp_path):
+ monkeypatch.setenv("TMPDIR", str(tmp_path))
+ cfg = SimpleNamespace(quantization_config = BNB_QC)
+ # Shard not cached and not a safetensors header: dense or packed is unknown.
+ _hub(monkeypatch, {"pytorch_model.bin.index.json": {n: "x.bin" for n in FUSED_PACKED}})
+ with pytest.raises(loader_utils.GptOssUnknownExpertLayoutError, match = "dtype"):
+ _fused(cfg, "someone/gpt-oss-bin")
+
+
+def _both_formats(tmp_path):
+ # Older split safetensors beside a newer fused .bin.
+ d = tmp_path / "ckpt"
+ d.mkdir()
+ save_file(_tensors(SPLIT, False), str(d / "model.safetensors"))
+ torch.save(_tensors(FUSED_QS, False), str(d / "pytorch_model.bin"))
+ return str(d)
+
+
+def test_use_safetensors_selects_the_probed_file(tmp_path):
+ path = _both_formats(tmp_path)
+ cfg = SimpleNamespace(quantization_config = BNB_QC)
+ assert loader_utils.gpt_oss_checkpoint_has_fused_experts(cfg, path) is False
+ assert (
+ loader_utils.gpt_oss_checkpoint_has_fused_experts(cfg, path, use_safetensors = True) is False
+ )
+ assert (
+ loader_utils.gpt_oss_checkpoint_has_fused_experts(cfg, path, use_safetensors = False) is True
+ )
+
+
+def test_sync_passes_use_safetensors(tmp_path, monkeypatch):
+ path = _both_formats(tmp_path)
+ monkeypatch.setenv("UNSLOTH_MODEL_NAME", "gpt_oss,_load_in_4bit_")
+ monkeypatch.setenv("UNSLOTH_GPT_OSS_BNB4BIT_PATCHED", "0")
+ loader_utils.sync_unsloth_model_name_bnb_flags(
+ True,
+ False,
+ config = SimpleNamespace(quantization_config = BNB_QC),
+ model_name = path,
+ use_safetensors = False,
+ )
+ assert os.environ["UNSLOTH_MODEL_NAME"] == "gpt_oss,"
+
+
+def test_loader_forwards_use_safetensors_to_the_probe(tmp_path, monkeypatch):
+ from unsloth import FastLanguageModel
+ from unsloth.models import loader
+
+ seen = []
+
+ def probe(
+ config,
+ model_name = None,
+ **kwargs,
+ ):
+ seen.append(kwargs.get("use_safetensors"))
+ return True
+
+ monkeypatch.setattr(loader, "gpt_oss_checkpoint_has_fused_experts", probe)
+ with pytest.raises(NotImplementedError, match = "overflow"):
+ FastLanguageModel.from_pretrained(
+ _fused_bnb_tiny(tmp_path),
+ max_seq_length = 64,
+ load_in_4bit = True,
+ dtype = torch.float16,
+ use_safetensors = False,
+ )
+ assert seen and all(v is False for v in seen)
diff --git a/unsloth/models/loader.py b/unsloth/models/loader.py
index 399dac45a33..04bf15cd070 100644
--- a/unsloth/models/loader.py
+++ b/unsloth/models/loader.py
@@ -54,6 +54,10 @@ from .loader_utils import (
_offline_quantize_to_fp8,
_tag_model_with_fp8_torchao_config,
get_model_name,
+ gpt_oss_checkpoint_has_fused_experts,
+ GptOssUnknownExpertLayoutError,
+ quantization_config_is_bnb_4bit,
+ refuse_gpt_oss_fused_4bit_float16,
_prefer_legacy_lowercase_cache,
is_distributed,
is_automatic_device_map,
@@ -2529,8 +2533,44 @@ class FastModel(FastBaseModel):
except Exception:
_bnb_compatible_quant = True
string = model_types_all
- if load_in_4bit and _bnb_compatible_quant:
+ # zoo's bnb split-expert classes load random experts on a fused gpt-oss checkpoint.
+ _gpt_oss_bnb_4bit = (
+ (load_in_4bit and _bnb_compatible_quant)
+ or quantization_config_is_bnb_4bit(getattr(model_config, "quantization_config", None))
+ or quantization_config_is_bnb_4bit(quantization_config)
+ )
+ _gpt_oss_fused = False
+ if "gpt_oss" in model_types_all:
+ try:
+ _gpt_oss_fused = bool(
+ gpt_oss_checkpoint_has_fused_experts(
+ model_config,
+ model_name,
+ token = token,
+ revision = base_revision,
+ subfolder = kwargs.get("subfolder"),
+ cache_dir = kwargs.get("cache_dir"),
+ local_files_only = local_files_only,
+ variant = kwargs.get("variant"),
+ use_safetensors = kwargs.get("use_safetensors"),
+ )
+ )
+ except GptOssUnknownExpertLayoutError:
+ # Only fatal where the layout decides the expert classes or the float16 refusal.
+ if (load_in_4bit and _bnb_compatible_quant) or (
+ _gpt_oss_bnb_4bit and dtype == torch.float16
+ ):
+ raise
+ if _gpt_oss_fused and _gpt_oss_bnb_4bit:
+ refuse_gpt_oss_fused_4bit_float16(dtype)
+ if load_in_4bit and _bnb_compatible_quant and not _gpt_oss_fused:
string += "_load_in_4bit_"
+ elif load_in_4bit and _bnb_compatible_quant:
+ print(
+ "Unsloth: this gpt-oss checkpoint stores fused experts, so it loads with its own "
+ "fused expert layout. A pre-quantized checkpoint such as "
+ "unsloth/gpt-oss-20b-unsloth-bnb-4bit loads faster and uses less memory."
+ )
if load_in_8bit and _bnb_compatible_quant:
string += "_load_in_8bit_"
if load_in_16bit:
diff --git a/unsloth/models/loader_utils.py b/unsloth/models/loader_utils.py
index 9f29a8109cb..ecbae785653 100644
--- a/unsloth/models/loader_utils.py
+++ b/unsloth/models/loader_utils.py
@@ -3869,11 +3869,330 @@ def quantization_config_selects_bnb_4bit(quantization_config):
return bool(get("load_in_4bit", False)) and not bool(get("load_in_8bit", False))
-def sync_unsloth_model_name_bnb_flags(load_in_4bit, load_in_8bit):
+_FUSED_EXPERT_SUFFIX = ".experts.gate_up_proj"
+
+
+def _safetensors_dtypes(path, names = None):
+ from safetensors import safe_open
+ with safe_open(path, framework = "pt") as f:
+ keys = f.keys() if names is None else names
+ return {k: f.get_slice(k).get_dtype() for k in keys}
+
+
+class GptOssUnknownExpertLayoutError(RuntimeError):
+ """A bitsandbytes gpt-oss checkpoint whose expert layout cannot be read without loading its weights."""
+
+
+class _UnreadableCheckpointNames(Exception):
+ """The checkpoint is a lone pytorch_model.bin whose tensor names cannot be read without loading it."""
+
+
+def _with_variant(filename, variant):
+ # Mirrors transformers' _add_variant.
+ if not variant:
+ return filename
+ parts = filename.split(".")
+ return ".".join(parts[:-1] + [variant, parts[-1]])
+
+
+def _index_weight_map(path):
+ import json
+ with open(path, "r", encoding = "utf-8") as f:
+ return json.load(f).get("weight_map", {}) or {}
+
+
+def _bin_dtypes(path):
+ # mmap + weights_only reads the pickle and storage metadata, not the tensor bytes.
+ state_dict = torch.load(path, map_location = "cpu", mmap = True, weights_only = True)
+ return {k: str(v.dtype) for k, v in state_dict.items() if isinstance(v, torch.Tensor)}
+
+
+def _hub_safetensors_header_dtypes(
+ repo_id,
+ filename,
+ revision = None,
+ token = None,
+):
+ """Range-reads one safetensors header from the Hub (never the tensor bytes)."""
+ import json
+ import struct
+ from huggingface_hub import HfFileSystem
+
+ fs = HfFileSystem(token = token)
+ with fs.open(f"{repo_id}/{filename}", "rb", revision = revision, block_size = 0) as f:
+ (size,) = struct.unpack("<Q", f.read(8))
+ header = json.loads(f.read(size))
+ return {k: v.get("dtype") for k, v in header.items() if k != "__metadata__"}
+
+
+def _checkpoint_tensor_dtypes(
+ model_name,
+ token = None,
+ revision = None,
+ subfolder = None,
+ cache_dir = None,
+ local_files_only = False,
+ variant = None,
+ use_safetensors = None,
+):
+ """{tensor name: dtype} (dtype only for fused experts) without downloading weights; mirrors transformers'
+ file order, `variant` and `use_safetensors`. Raises _UnreadableCheckpointNames for an unreadable lone .bin."""
+ if not isinstance(model_name, str) or not model_name:
+ return None
+ st_index, st_single = (
+ _with_variant(f, variant) for f in ("model.safetensors.index.json", "model.safetensors")
+ )
+ bin_index, bin_single = (
+ _with_variant(f, variant) for f in ("pytorch_model.bin.index.json", "pytorch_model.bin")
+ )
+ if use_safetensors is False:
+ st_index = st_single = None
+ elif use_safetensors:
+ bin_index = bin_single = None
+ index_files = [f for f in (st_index, bin_index) if f]
+
+ def _local_shard_dtypes(path, names):
+ if path.endswith(".safetensors"):
+ return _safetensors_dtypes(path, names)
+ found = _bin_dtypes(path)
+ return {n: found.get(n) for n in names}
+
+ def _fill_fused_dtypes(weight_map, shard_dtypes):
+ out = dict.fromkeys(weight_map)
+ shards = {}
+ for name, shard in weight_map.items():
+ if name.endswith(_FUSED_EXPERT_SUFFIX):
+ shards.setdefault(shard, []).append(name)
+ for shard, names in shards.items():
+ try:
+ found = shard_dtypes(shard, names)
+ except Exception:
+ continue
+ out.update({n: found.get(n) for n in names})
+ return out
+
+ try:
+ if os.path.isdir(model_name):
+ root = os.path.join(model_name, subfolder) if subfolder else model_name
+ for index_file in index_files:
+ index_path = os.path.join(root, index_file)
+ if not os.path.exists(index_path):
+ continue
+ weight_map = _index_weight_map(index_path)
+ return _fill_fused_dtypes(
+ weight_map,
+ lambda shard, names: _local_shard_dtypes(os.path.join(root, shard), names),
+ )
+ single_path = os.path.join(root, st_single) if st_single else None
+ if single_path and os.path.exists(single_path):
+ return _safetensors_dtypes(single_path)
+ single_path = os.path.join(root, bin_single) if bin_single else None
+ if single_path and os.path.exists(single_path):
+ try:
+ return _bin_dtypes(single_path)
+ except Exception:
+ raise _UnreadableCheckpointNames(single_path)
+ return None
+
+ if not local_files_only and not subfolder and not variant and st_single:
+ try:
+ from huggingface_hub import get_safetensors_metadata
+
+ metadata = get_safetensors_metadata(model_name, revision = revision, token = token)
+ out = dict.fromkeys(metadata.weight_map)
+ for file_metadata in metadata.files_metadata.values():
+ for name, info in file_metadata.tensors.items():
+ out[name] = info.dtype
+ return out
+ except Exception:
+ pass
+ from huggingface_hub import hf_hub_download
+
+ hub = dict(revision = revision, subfolder = subfolder, cache_dir = cache_dir, token = token)
+ for index_file in index_files:
+ try:
+ index_path = hf_hub_download(
+ model_name, index_file, local_files_only = local_files_only, **hub
+ )
+ except Exception:
+ continue
+ weight_map = _index_weight_map(index_path)
+
+ def _hub_shard_dtypes(shard, names):
+ try:
+ path = hf_hub_download(model_name, shard, local_files_only = True, **hub)
+ except Exception:
+ path = None
+ if path is not None:
+ return _local_shard_dtypes(path, names)
+ if local_files_only or not shard.endswith(".safetensors"):
+ return {}
+ remote = f"{subfolder}/{shard}" if subfolder else shard
+ return _hub_safetensors_header_dtypes(model_name, remote, revision, token)
+
+ return _fill_fused_dtypes(weight_map, _hub_shard_dtypes)
+ if st_single:
+ try:
+ return _safetensors_dtypes(
+ hf_hub_download(model_name, st_single, local_files_only = True, **hub)
+ )
+ except Exception:
+ pass
+ if not local_files_only:
+ remote = f"{subfolder}/{st_single}" if subfolder else st_single
+ try:
+ return _hub_safetensors_header_dtypes(model_name, remote, revision, token)
+ except Exception:
+ pass
+ if not bin_single:
+ return None
+ try:
+ cached_bin = hf_hub_download(model_name, bin_single, local_files_only = True, **hub)
+ except Exception:
+ cached_bin = None
+ if cached_bin is not None:
+ try:
+ return _bin_dtypes(cached_bin)
+ except Exception:
+ raise _UnreadableCheckpointNames(cached_bin)
+ if not local_files_only:
+ from huggingface_hub import file_exists
+
+ remote = f"{subfolder}/{bin_single}" if subfolder else bin_single
+ try:
+ exists = file_exists(model_name, remote, revision = revision, token = token)
+ except Exception:
+ exists = False
+ if exists:
+ raise _UnreadableCheckpointNames(f"{model_name}/{remote}")
+ return None
+ except _UnreadableCheckpointNames:
+ raise
+ except Exception:
+ return None
+
+
+def _gpt_oss_bnb_checkpoint_expert_layout(dtypes):
+ """'split', 'fused', 'fused_no_quant_state' (packed bytes, no quant state), 'fused_unknown_dtype' or None."""
+ if not dtypes:
+ return None
+ if any(".experts.gate_up_projs." in n or ".experts.down_projs." in n for n in dtypes):
+ return "split"
+ fused = [n for n in dtypes if n.endswith(_FUSED_EXPERT_SUFFIX)]
+ if not fused:
+ return None
+ for name in fused:
+ if name + ".absmax" in dtypes:
+ continue
+ if dtypes[name] is None:
+ return "fused_unknown_dtype"
+ if dtypes[name] in ("U8", "I8", "torch.uint8", "torch.int8"):
+ return "fused_no_quant_state"
+ return "fused"
+
+
+def gpt_oss_checkpoint_has_fused_experts(
+ config,
+ model_name = None,
+ **hub_kwargs,
+):
+ """True when a gpt-oss checkpoint stores fused experts (zoo's bnb split classes cannot load them); None if unknown."""
+ if config is None:
+ return None
+ quantization_config = getattr(config, "quantization_config", None)
+ if not quantization_config:
+ return True
+ if model_name is None:
+ return False
+ get = (
+ quantization_config.get
+ if isinstance(quantization_config, dict)
+ else lambda key, default = None: getattr(quantization_config, key, default)
+ )
+ quant_method = get("quant_method", None)
+ quant_method = getattr(quant_method, "value", quant_method)
+ if str(quant_method).lower() != "bitsandbytes":
+ return False
+ try:
+ dtypes = _checkpoint_tensor_dtypes(model_name, **hub_kwargs)
+ except _UnreadableCheckpointNames as exc:
+ # Anything not named *-unsloth-bnb-4bit may be a fused save; guessing split loads random experts.
+ if "unsloth-bnb-4bit" in str(model_name).lower():
+ return False
+ raise GptOssUnknownExpertLayoutError(
+ f"Unsloth: `{model_name}` is a bitsandbytes gpt-oss checkpoint saved as a single "
+ f"`{os.path.basename(str(exc))}` with no index, so its expert layout (fused or Unsloth's split "
+ "pre-quantized layout) cannot be read without loading the weights, and a wrong guess loads "
+ "random experts. Re-save it with `safe_serialization = True` (safetensors), add its "
+ "`pytorch_model.bin.index.json`, or download it locally first."
+ ) from None
+ layout = _gpt_oss_bnb_checkpoint_expert_layout(dtypes)
+ if layout == "fused_unknown_dtype":
+ raise GptOssUnknownExpertLayoutError(
+ f"Unsloth: `{model_name}` is a bitsandbytes gpt-oss checkpoint with fused experts and no "
+ "4-bit quantization state, and the dtype of its expert weights cannot be read without "
+ "downloading them, so packed 4-bit bytes (unrestorable) cannot be told apart from 16-bit "
+ "weights. Download it locally first, or re-save it with `safe_serialization = True`."
+ )
+ if layout == "fused_no_quant_state":
+ raise RuntimeError(
+ f"Unsloth: `{model_name}` is a 4-bit gpt-oss checkpoint whose fused expert weights were saved "
+ "without their bitsandbytes quantization state, so the experts cannot be restored. Reload the "
+ "original 16-bit checkpoint with `load_in_4bit = True` instead."
+ )
+ return layout == "fused"
+
+
+def quantization_config_is_bnb_4bit(quantization_config):
+ """True only for a present bitsandbytes 4-bit config (dict or BitsAndBytesConfig)."""
+ if quantization_config is None or (
+ isinstance(quantization_config, dict) and not quantization_config
+ ):
+ return False
+ return quantization_config_selects_bnb_4bit(quantization_config)
+
+
+def refuse_gpt_oss_fused_4bit_float16(dtype):
+ """Fused 4-bit experts compute in the model dtype and overflow float16 (split classes keep down_projs fp32)."""
+ if dtype != torch.float16:
+ return
+ raise NotImplementedError(
+ "Unsloth: this gpt-oss checkpoint stores fused experts, and in float16 (this GPU has no bfloat16, "
+ "or dtype = torch.float16) its fused 4-bit experts would overflow. Use the pre-quantized "
+ "unsloth/gpt-oss-20b-unsloth-bnb-4bit (or -120b), or a GPU with bfloat16."
+ )
+
+
+def gpt_oss_keeps_checkpoint_quantization(model_name, config, load_in_4bit):
+ """True when gpt-oss ignores load_in_4bit / load_in_8bit. Unquantized still takes bnb 4-bit, not 8-bit
+ (bnb 8-bit only replaces nn.Linear, leaving fused experts 16-bit)."""
+ name = str(model_name).lower()
+ if "gpt-oss-20b" not in name and "gpt-oss-120b" not in name:
+ return False
+ return bool(getattr(config, "quantization_config", None)) or not load_in_4bit
+
+
+def sync_unsloth_model_name_bnb_flags(
+ load_in_4bit,
+ load_in_8bit,
+ config = None,
+ model_name = None,
+ **hub_kwargs,
+):
"""Make UNSLOTH_MODEL_NAME's `_load_in_4bit_`/`_load_in_8bit_` tokens match the EFFECTIVE bnb state (after get_model_name remap + check_and_disable). The per-load env is built from the pre-remap config (None for adapter-only PEFT repos), so its tokens can be wrong once the base resolves. Only the gpt-oss patch reads them, so this is gated to gpt-oss."""
name = os.environ.get("UNSLOTH_MODEL_NAME", "")
if "gpt_oss" not in name.replace("-", "_"):
return
+ if load_in_4bit and gpt_oss_checkpoint_has_fused_experts(config, model_name, **hub_kwargs):
+ if os.environ.get("UNSLOTH_GPT_OSS_BNB4BIT_PATCHED", "0") == "1":
+ raise RuntimeError(
+ "Unsloth: this gpt-oss checkpoint is not quantized (fused experts), but the 4-bit gpt-oss "
+ "classes for pre-quantized checkpoints were already installed, so its experts and router "
+ "would load randomly initialised. Load the base model directly, use "
+ "`load_in_4bit = False`, or use a pre-quantized checkpoint such as "
+ "unsloth/gpt-oss-20b-unsloth-bnb-4bit."
+ )
+ load_in_4bit = False
for flag, present in (
("_load_in_4bit_", bool(load_in_4bit)),
("_load_in_8bit_", bool(load_in_8bit)),
diff --git a/unsloth/models/vision.py b/unsloth/models/vision.py
index 4e68abc3772..1c0c1c86aad 100644
--- a/unsloth/models/vision.py
+++ b/unsloth/models/vision.py
@@ -3494,6 +3494,7 @@ class FastBaseModel:
gptq_trainable_quantization_config,
quantization_config_selects_bnb_4bit,
sync_unsloth_model_name_bnb_flags,
+ gpt_oss_keeps_checkpoint_quantization,
)
from .fp8_to_nf4 import fp8_to_nf4_planner_quantization_config
@@ -3538,7 +3539,19 @@ class FastBaseModel:
keep_task_heads_unquantized(auto_config, auto_model, model_class)
pop_modelopt_key_mapping(auto_config, kwargs, model_class)
# Correct UNSLOTH_MODEL_NAME's bnb tokens now the effective bnb state is known (the per-load env was built before remap/disable). gpt-oss only.
- sync_unsloth_model_name_bnb_flags(load_in_4bit, load_in_8bit)
+ sync_unsloth_model_name_bnb_flags(
+ load_in_4bit,
+ load_in_8bit,
+ config = auto_config,
+ model_name = model_name,
+ token = token,
+ revision = _revision,
+ subfolder = kwargs.get("subfolder"),
+ cache_dir = kwargs.get("cache_dir"),
+ local_files_only = local_files_only,
+ variant = kwargs.get("variant"),
+ use_safetensors = kwargs.get("use_safetensors"),
+ )
if full_finetuning and (load_in_4bit or load_in_8bit):
print(
@@ -3784,7 +3797,7 @@ class FastBaseModel:
# Cannot be None, since HF now checks for the config.
if load_in_4bit or load_in_8bit:
# Ignore load_in_4bit / load_in_8bit for MXFP4; better to get the config file.
- if "gpt-oss-20b" in model_name.lower() or "gpt-oss-120b" in model_name.lower():
+ if gpt_oss_keeps_checkpoint_quantization(model_name, auto_config, load_in_4bit):
pass
else:
if user_quantization_config is None: