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.

Let FastModel and FastLanguageModel load the same family in one process, in either order (#12219)

Daniel Hand2e127d18fdb
diff --git a/tests/test_fast_language_model_after_fast_model.py b/tests/test_fast_language_model_after_fast_model.py
new file mode 100644
index 00000000000..085629c0c36
--- /dev/null
+++ b/tests/test_fast_language_model_after_fast_model.py
@@ -0,0 +1,102 @@
+# SPDX-License-Identifier: AGPL-3.0-only
+# Copyright 2026-present the Unsloth AI Inc. team. All rights reserved.
+
+"""FastModel and FastLanguageModel load the same family one after the other in one process, in either order."""
+
+import subprocess
+import sys
+import types
+
+import pytest
+from real_accelerator import has_real_cuda
+
+
+def test_compiled_classes_are_swapped_back_for_the_fast_patcher(monkeypatch):
+ from unsloth.models.llama import _restore_uncompiled_transformers_classes
+
+ modeling = types.ModuleType("transformers.models.fakearch.modeling_fakearch")
+ patcher_module = types.ModuleType("unsloth.models.fakearch")
+ original = type("FakeAttention", (), {"__module__": modeling.__name__})
+ compiled = type("FakeAttention", (), {"__module__": "unsloth_compiled_module_fakearch"})
+ other = type("FakeMLP", (), {"__module__": "somewhere_else"})
+ modeling.FakeAttention = compiled
+ modeling.FakeMLP = other
+ modeling.CLASSES = {"eager": compiled, "mlp": other}
+ patcher = type("FastFakeModel", (), {"__module__": patcher_module.__name__})
+ patcher_module.FakeAttention = original
+ patcher_module.FastFakeModel = patcher
+ monkeypatch.setitem(sys.modules, modeling.__name__, modeling)
+ monkeypatch.setitem(sys.modules, patcher_module.__name__, patcher_module)
+
+ _restore_uncompiled_transformers_classes(patcher)
+ assert modeling.FakeAttention is original
+ assert modeling.CLASSES == {"eager": original, "mlp": other}
+ assert modeling.FakeMLP is other
+
+
+def test_pre_patch_changes_are_recorded_once_and_undone_for_the_compiler(monkeypatch):
+ from unsloth.models import llama as unsloth_llama
+
+ modeling = types.ModuleType("transformers.models.fakefam.modeling_fakefam")
+ patcher_module = types.ModuleType("unsloth.models.fakefam")
+
+ def hf_forward(self):
+ return "hf"
+
+ attention = type("FakeAttention", (), {"__module__": modeling.__name__, "forward": hf_forward})
+ rotary = type("FakeRotary", (), {"__module__": modeling.__name__})
+ modeling.FakeAttention, modeling.FakeRotary = attention, rotary
+ patcher = type("FastFakeModel", (), {"__module__": patcher_module.__name__})
+ patcher_module.FakeAttention, patcher_module.FastFakeModel = attention, patcher
+ monkeypatch.setitem(sys.modules, modeling.__name__, modeling)
+ monkeypatch.setitem(sys.modules, patcher_module.__name__, patcher_module)
+ unsloth_rotary = type("FakeRotary", (), {})
+
+ def pre_patch():
+ attention.forward = lambda self: "fast"
+ attention.extra = lambda self: "added"
+ modeling.FakeRotary = unsloth_rotary
+
+ for _ in range(
+ 2
+ ): # a second FastLanguageModel load must not record its own patches as the originals
+ snapshot = unsloth_llama._snapshot_transformers_modules(patcher)
+ pre_patch()
+ unsloth_llama._record_pre_patch_changes(snapshot)
+ assert attention().forward() == "fast" and modeling.FakeRotary is unsloth_rotary
+
+ unsloth_llama.restore_transformers_family(["fakefam", "notloaded"])
+ assert attention().forward() == "hf"
+ assert "extra" not in vars(attention)
+ assert modeling.FakeRotary is rotary
+
+
[email protected](not has_real_cuda(), reason = "FastModel / FastLanguageModel loads need CUDA")
[email protected]("order", ["FastModel,FastLanguageModel", "FastLanguageModel,FastModel"])
+def test_both_loaders_on_the_same_family_in_one_process(tmp_path, order):
+ """Subprocess: both loaders patch the Llama classes process-wide."""
+ code = f"""
+import os
+os.environ["UNSLOTH_COMPILE_LOCATION"] = {str(tmp_path / "compiled")!r}
+from unsloth import FastModel, FastLanguageModel
+import torch
+from tokenizers import Tokenizer, models
+from transformers import LlamaConfig, LlamaForCausalLM, PreTrainedTokenizerFast
+vocab = {{"<unk>": 0, "<s>": 1, "</s>": 2, **{{f"w{{i}}": i + 3 for i in range(125)}}}}
+tok = PreTrainedTokenizerFast(tokenizer_object = Tokenizer(models.WordLevel(vocab, unk_token = "<unk>")),
+ unk_token = "<unk>", bos_token = "<s>", eos_token = "</s>", pad_token = "</s>")
+config = LlamaConfig(vocab_size = len(vocab), hidden_size = 64, intermediate_size = 128, num_hidden_layers = 2,
+ num_attention_heads = 4, num_key_value_heads = 2, head_dim = 16, max_position_embeddings = 128,
+ bos_token_id = 1, eos_token_id = 2, pad_token_id = 2)
+path = {str(tmp_path / "tiny")!r}
+LlamaForCausalLM(config).save_pretrained(path)
+tok.save_pretrained(path)
+x = {{"input_ids": torch.tensor([[1, 5, 6, 7]], device = "cuda")}}
+kwargs = {{"FastModel": dict(load_in_16bit = True), "FastLanguageModel": dict()}}
+loaders = {{"FastModel": FastModel, "FastLanguageModel": FastLanguageModel}}
+for name in {order!r}.split(","):
+ model, _ = loaders[name].from_pretrained(path, load_in_4bit = False, max_seq_length = 64, **kwargs[name])
+ print(name, "LOGITS", tuple(model(**x).logits.shape))
+"""
+ out = subprocess.run([sys.executable, "-c", code], capture_output = True, text = True, timeout = 900)
+ assert out.stdout.count("LOGITS") == 2, (out.stdout[-2000:], out.stderr[-3000:])
diff --git a/tests/test_modelopt_fp8_loading.py b/tests/test_modelopt_fp8_loading.py
index 9f375738730..e22e282e1b7 100644
--- a/tests/test_modelopt_fp8_loading.py
+++ b/tests/test_modelopt_fp8_loading.py
@@ -481,8 +481,11 @@ def test_rewrite_follows_who_loads_the_weights():
@pytest.mark.skipif(not has_real_cuda(), reason = "FastModel loads need an accelerator")
def test_a_declined_modelopt_format_still_refuses_to_load_in_process(tmp_path):
+ """Subprocess: FastModel compiles and rebinds the Llama classes process-wide before it refuses."""
+ import subprocess
+ import sys
+
from transformers import LlamaConfig, LlamaForCausalLM
- from unsloth import FastModel
config = LlamaConfig(
hidden_size = 64,
@@ -496,8 +499,19 @@ def test_a_declined_modelopt_format_still_refuses_to_load_in_process(tmp_path):
raw = json.loads((tmp_path / "config.json").read_text())
raw["quantization_config"] = {"quant_method": "modelopt", "quant_algo": "NVFP4"}
(tmp_path / "config.json").write_text(json.dumps(raw))
- with pytest.raises(KeyError, match = "cannot load this `modelopt` checkpoint"):
- FastModel.from_pretrained(str(tmp_path), load_in_4bit = False, load_in_16bit = True)
+ code = f"""
+import os
+os.environ["UNSLOTH_COMPILE_LOCATION"] = {str(tmp_path / "compiled")!r}
+from unsloth import FastModel
+try:
+ FastModel.from_pretrained({str(tmp_path)!r}, load_in_4bit = False, load_in_16bit = True)
+except KeyError as error:
+ print("REFUSED", "cannot load this `modelopt` checkpoint" in str(error))
+else:
+ print("LOADED")
+"""
+ out = subprocess.run([sys.executable, "-c", code], capture_output = True, text = True, timeout = 600)
+ assert "REFUSED True" in out.stdout, (out.stdout[-2000:], out.stderr[-2000:])
@needs_per_tensor_fp8
diff --git a/unsloth/models/llama.py b/unsloth/models/llama.py
index 02e73f90c94..2d631f058f3 100644
--- a/unsloth/models/llama.py
+++ b/unsloth/models/llama.py
@@ -2413,6 +2413,88 @@ def _fused_lora_skip_reason(
)
+def _patched_transformers_modules(model_patcher):
+ patcher_module = sys.modules.get(getattr(model_patcher, "__module__", ""))
+ if patcher_module is None:
+ return {}
+ originals = {}
+ for original in list(vars(patcher_module).values()):
+ if isinstance(original, type) and original.__module__.startswith("transformers.models."):
+ modeling = sys.modules.get(original.__module__)
+ if modeling is not None:
+ originals.setdefault(modeling, []).append(original)
+ return originals
+
+
+def _restore_uncompiled_transformers_classes(model_patcher):
+ """FastModel rebinds the modeling module's classes to compiled copies, but pre_patch patches the originals."""
+ for modeling, originals in _patched_transformers_modules(model_patcher).items():
+ for original in originals:
+ current = getattr(modeling, original.__name__, None)
+ if current is None or current is original:
+ continue
+ if not getattr(current, "__module__", "").startswith("unsloth_compiled_module"):
+ continue
+ setattr(modeling, original.__name__, original)
+ for value in vars(modeling).values():
+ if type(value) is dict:
+ for key, item in list(value.items()):
+ if item is current:
+ value[key] = original
+
+
+_MISSING = object()
+
+
+def _snapshot_transformers_modules(model_patcher):
+ snapshot = {}
+ for modeling in _patched_transformers_modules(model_patcher):
+ classes = [
+ v
+ for v in vars(modeling).values()
+ if isinstance(v, type) and v.__module__ == modeling.__name__
+ ]
+ snapshot[modeling] = (dict(vars(modeling)), {cls: dict(vars(cls)) for cls in classes})
+ return snapshot
+
+
+def _record_pre_patch_changes(snapshot):
+ """Record the originals of whatever pre_patch changed; the first load wins, so later loads never record patches."""
+ for modeling, (module_globals, class_dicts) in snapshot.items():
+ record = vars(modeling).get("_unsloth_pre_patch_originals")
+ if record is None:
+ record = modeling._unsloth_pre_patch_originals = ({}, {})
+ changed_globals, changed_attrs = record
+ for name, value in module_globals.items():
+ if vars(modeling).get(name, _MISSING) is not value:
+ changed_globals.setdefault(name, value)
+ for cls, saved in class_dicts.items():
+ now = vars(cls)
+ for name in set(saved) | set(now):
+ if now.get(name, _MISSING) is not saved.get(name, _MISSING):
+ changed_attrs.setdefault((cls, name), saved.get(name, _MISSING))
+
+
+def restore_transformers_family(model_types):
+ """Undo pre_patch before FastModel compiles a family: the compiler copies whatever forwards the classes hold."""
+ for model_type in model_types:
+ modeling = sys.modules.get(f"transformers.models.{model_type}.modeling_{model_type}")
+ record = (
+ vars(modeling).get("_unsloth_pre_patch_originals") if modeling is not None else None
+ )
+ if record is None:
+ continue
+ changed_globals, changed_attrs = record
+ for name, value in changed_globals.items():
+ setattr(modeling, name, value)
+ for (cls, name), value in changed_attrs.items():
+ if value is _MISSING:
+ if name in vars(cls):
+ delattr(cls, name)
+ else:
+ setattr(cls, name, value)
+
+
def _base_weight_dtype(proj):
weight = getattr(proj, "base_layer", proj).weight
quant_state = getattr(weight, "quant_state", None)
@@ -2601,7 +2683,10 @@ class FastLlamaModel:
if old_hf_transfer != "0":
os.environ["HF_HUB_ENABLE_HF_TRANSFER"] = "1"
+ _restore_uncompiled_transformers_classes(model_patcher)
+ snapshot = _snapshot_transformers_modules(model_patcher)
model_patcher.pre_patch()
+ _record_pre_patch_changes(snapshot)
# A download counter, to see whether environments are breaking or HF is down.
get_statistics(kwargs.get("local_files_only", False))
diff --git a/unsloth/models/loader.py b/unsloth/models/loader.py
index b4754990866..c01d8c2649f 100644
--- a/unsloth/models/loader.py
+++ b/unsloth/models/loader.py
@@ -23,7 +23,7 @@ from ._utils import (
)
from ._custom_dtype import register_custom_dtype
from .granite import FastGraniteModel
-from .llama import FastLlamaModel, logger, _vllm_will_load_weights
+from .llama import FastLlamaModel, logger, _vllm_will_load_weights, restore_transformers_family
from .mistral import FastMistralModel
from .qwen2 import FastQwen2Model
from .qwen3 import FastQwen3Model
@@ -2223,6 +2223,7 @@ class FastModel(FastBaseModel):
use_gradient_checkpointing = apply_unsloth_gradient_checkpointing(
use_gradient_checkpointing, max_seq_length, dtype
)
+ restore_transformers_family(model_types)
with redirector:
patch_loss_functions(torch_compile = False)
model_types, supports_sdpa = unsloth_compile_transformers(