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.

Train Kimi-K3 with its MXFP4 experts kept packed and dequantized on the fly (#11750)

Daniel Hanf7da293881e1
diff --git a/tests/python/test_get_lora_parameters_bias_fp8_block_size.py b/tests/python/test_get_lora_parameters_bias_fp8_block_size.py
index d2e3ad8b1b6..ccc47cccf22 100644
--- a/tests/python/test_get_lora_parameters_bias_fp8_block_size.py
+++ b/tests/python/test_get_lora_parameters_bias_fp8_block_size.py
@@ -2,14 +2,19 @@ import ast
from pathlib import Path
+_HELPERS = ("_packed_base", "_is_packed_state")
+
+
def _load_function(name):
# Extract a function from kernels/utils.py without importing unsloth (which needs a GPU / torch / bitsandbytes).
source = Path(__file__).parents[2] / "unsloth" / "kernels" / "utils.py"
tree = ast.parse(source.read_text(encoding = "utf-8"))
funcs = [
- node for node in ast.walk(tree) if isinstance(node, ast.FunctionDef) and node.name == name
+ node
+ for node in ast.walk(tree)
+ if isinstance(node, ast.FunctionDef) and node.name in (name, *_HELPERS)
]
- assert len(funcs) == 1, (name, funcs)
+ assert [f.name for f in funcs].count(name) == 1, (name, funcs)
namespace = {"getattr": getattr, "_FP8_WEIGHT_DTYPES": ()}
module = ast.Module(body = funcs, type_ignores = [])
ast.fix_missing_locations(module)
diff --git a/tests/python/test_get_lora_parameters_fp8_block_size.py b/tests/python/test_get_lora_parameters_fp8_block_size.py
index abc55370a17..82984c57526 100644
--- a/tests/python/test_get_lora_parameters_fp8_block_size.py
+++ b/tests/python/test_get_lora_parameters_fp8_block_size.py
@@ -2,14 +2,19 @@ import ast
from pathlib import Path
+_HELPERS = ("_packed_base", "_is_packed_state")
+
+
def _load_function(name):
# Extract a function from kernels/utils.py without importing unsloth (which needs a GPU / torch / bitsandbytes).
source = Path(__file__).parents[2] / "unsloth" / "kernels" / "utils.py"
tree = ast.parse(source.read_text(encoding = "utf-8"))
funcs = [
- node for node in ast.walk(tree) if isinstance(node, ast.FunctionDef) and node.name == name
+ node
+ for node in ast.walk(tree)
+ if isinstance(node, ast.FunctionDef) and node.name in (name, *_HELPERS)
]
- assert len(funcs) == 1, (name, funcs)
+ assert [f.name for f in funcs].count(name) == 1, (name, funcs)
namespace = {"getattr": getattr, "hasattr": hasattr, "_FP8_WEIGHT_DTYPES": ()}
module = ast.Module(body = funcs, type_ignores = [])
ast.fix_missing_locations(module)
diff --git a/tests/test_compressed_tensors_bnb.py b/tests/test_compressed_tensors_bnb.py
index 014ce558f0c..06929e7c3f0 100644
--- a/tests/test_compressed_tensors_bnb.py
+++ b/tests/test_compressed_tensors_bnb.py
@@ -103,6 +103,29 @@ def test_plan_accepts_w4a16_pack_quantized():
assert compressed_tensors_bnb_plan(_Config(quantization_config = _w4a16())) is not None
+def _mxfp4(**weights):
+ """moonshotai/Kimi-K3's layout: MXFP4 routed experts, everything else left in bf16."""
+ quant = _w4a16(
+ format = "mxfp4-pack-quantized",
+ weights = {"type": "float", "num_bits": 4, "group_size": 32, "scale_dtype": "torch.uint8"},
+ )
+ quant["config_groups"]["group_0"]["format"] = "mxfp4-pack-quantized"
+ quant["config_groups"]["group_0"]["weights"].update(weights)
+ return quant
+
+
+def test_plan_accepts_mxfp4_pack_quantized():
+ plan = compressed_tensors_bnb_plan(_Config(quantization_config = _mxfp4()))
+ assert plan is not None and plan["format"] == "mxfp4-pack-quantized"
+
+
+def test_plan_declines_mxfp4_with_a_layout_it_cannot_decode():
+ for weights in ({"group_size": 16}, {"type": "int"}, {"num_bits": 8}):
+ assert (
+ compressed_tensors_bnb_plan(_Config(quantization_config = _mxfp4(**weights))) is None
+ ), weights
+
+
def test_plan_accepts_int8_and_asymmetric_and_actorder():
for weights in (
{"num_bits": 8},
@@ -589,6 +612,7 @@ def _write_tiny_packed_llama(
actorder = False,
num_bits = 4,
group_size = 32,
+ mxfp4 = False,
):
"""A 2-layer Llama with every Linear but lm_head packed by compressed-tensors' compressor.
Returns (packed_dir, bf16_dir) where bf16_dir holds the exact decompressed weights."""
@@ -621,9 +645,11 @@ def _write_tiny_packed_llama(
"actorder": "weight" if actorder else None,
}
)
+ if mxfp4:
+ quant = _mxfp4()
ctc = QuantizationConfig.model_validate(quant)
scheme = list(ctc.config_groups.values())[0]
- comp = BaseCompressor.get_value_from_registry("pack-quantized")
+ comp = BaseCompressor.get_value_from_registry(quant["format"])
linears = {n for n, m in model.named_modules() if isinstance(m, torch.nn.Linear)}
packed, plain = {}, {}
for k, w in sd.items():
@@ -641,7 +667,12 @@ def _write_tiny_packed_llama(
grouped = wf[:, torch.argsort(g_idx)].reshape(out_f, in_f // group_size, group_size)
else:
grouped = wf.reshape(out_f, in_f // group_size, group_size)
- scale, zp = calculate_qparams(grouped.amin(-1), grouped.amax(-1), scheme.weights)
+ if mxfp4:
+ # One power-of-two scale per 32 so the group maximum lands in E2M1's top binade.
+ amax = grouped.abs().amax(-1).clamp_min(2**-126)
+ scale, zp = 2.0 ** (torch.floor(torch.log2(amax)) - 2), None
+ else:
+ scale, zp = calculate_qparams(grouped.amin(-1), grouped.amax(-1), scheme.weights)
state = {"weight": wf, "weight_scale": scale.to(torch.bfloat16)}
if asymmetric:
state["weight_zero_point"] = zp.to(torch.int8)
@@ -703,13 +734,15 @@ def _tokenizer_free_load(path, root):
@pytest.mark.skipif(
not (HAS_CT and HAS_CONVERTERS), reason = "needs compressed-tensors and the transformers 5 loader"
)
[email protected]("variant", ["symmetric", "asymmetric", "actorder", "int8"])
[email protected]("variant", ["symmetric", "asymmetric", "actorder", "int8", "mxfp4"])
@pytest.mark.usefixtures("restore_llama_patches")
def test_packed_checkpoint_loads_as_linear4bit_bit_identical_to_disk_route(
variant, tmp_path, monkeypatch
):
from unsloth import FastLanguageModel
+ if variant == "mxfp4":
+ monkeypatch.setenv("UNSLOTH_MXFP4_KEEP_PACKED", "0")
monkeypatch.setenv("UNSLOTH_COMPRESSED_TENSORS_INT4", "nf4")
packed_dir, bf16_dir = _write_tiny_packed_llama(
@@ -717,6 +750,7 @@ def test_packed_checkpoint_loads_as_linear4bit_bit_identical_to_disk_route(
asymmetric = variant == "asymmetric",
actorder = variant == "actorder",
num_bits = 8 if variant == "int8" else 4,
+ mxfp4 = variant == "mxfp4",
)
for d in (packed_dir, bf16_dir):
_tokenizer_free_load(d, str(tmp_path))
diff --git a/tests/test_k3_mxfp4_stacked_experts.py b/tests/test_k3_mxfp4_stacked_experts.py
new file mode 100644
index 00000000000..b0c1df09596
--- /dev/null
+++ b/tests/test_k3_mxfp4_stacked_experts.py
@@ -0,0 +1,964 @@
+# SPDX-License-Identifier: AGPL-3.0-only
+# Copyright 2023-present Daniel 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/>.
+
+"""Kimi-K3 style remote-code MXFP4 experts load packed into one Mxfp4StackedExperts per MoE layer."""
+
+import json
+import os
+import sys
+import types
+
+import re
+
+import pytest
+from real_accelerator import has_real_cuda # tests/_shared, on sys.path via tests/conftest.py
+import torch
+from torch import nn
+
+import unsloth # noqa: F401
+from unsloth.models.compressed_tensors_bnb import (
+ _StackPackedExperts,
+ _swap_in_stacks,
+ _transformers_supports_weight_converters,
+ arm_compressed_tensors_bnb_loading,
+ keep_mxfp4_experts_packed,
+ packed_expert_prefixes,
+ plan_mxfp4_keep_packed,
+)
+from unsloth.models.remote_moe_shims import (
+ is_remote_deepseek_moe,
+ packed_expert_target_parameters,
+ prepare_remote_moe_for_training,
+)
+
+zoo_stacked = pytest.importorskip("unsloth_zoo.mxfp4_stacked_experts")
+Mxfp4StackedExperts = zoo_stacked.Mxfp4StackedExperts
+
+try:
+ from compressed_tensors.config import CompressionFormat
+
+ # Releases before MXFP4 (0.12.x, which vllm 0.11.2 pins) reject its config outright.
+ HAS_CT = any(f.value == "mxfp4-pack-quantized" for f in CompressionFormat)
+except Exception:
+ HAS_CT = False
+
+# The quantizer hook that adds converters (HfQuantizer.update_weight_conversions) is 5.8+.
+HAS_CONVERTERS = _transformers_supports_weight_converters()
+
+H, I, E, K = 64, 64, 4, 2
+
+
+def _swap_planned_stacks(model, keys, dtype):
+ """What a kept-packed load does before the weights load: swap in the planned stacks."""
+ plan = plan_mxfp4_keep_packed(model, keys)
+ return _swap_in_stacks(plan.blocks if plan is not None else [], dtype)
+
+
+MODELING = """
+import torch
+import torch.nn as nn
+import torch.nn.functional as F
+from transformers import PretrainedConfig, PreTrainedModel
+from transformers.modeling_outputs import CausalLMOutput
+
+
+class TinyMoeConfig(PretrainedConfig):
+ model_type = "tiny_mxfp4_moe"
+
+ def __init__(self, vocab_size=128, hidden_size=64, moe_intermediate_size=64, num_experts=4,
+ num_experts_per_tok=2, num_hidden_layers=2, hidden_act="situ", **kwargs):
+ self.vocab_size = vocab_size
+ self.hidden_size = hidden_size
+ self.moe_intermediate_size = moe_intermediate_size
+ self.num_experts = num_experts
+ self.num_experts_per_tok = num_experts_per_tok
+ self.num_hidden_layers = num_hidden_layers
+ self.hidden_act = hidden_act
+ super().__init__(**kwargs)
+
+
+class SituAndMul(nn.Module):
+ def forward(self, x):
+ d = x.shape[-1] // 2
+ gate, up = x[..., :d].float(), x[..., d:].float()
+ return (torch.tanh(gate) * torch.sigmoid(gate) * up).to(x.dtype)
+
+
+class Expert(nn.Module):
+ def __init__(self, config):
+ super().__init__()
+ self.config = config
+ self.w1 = nn.Linear(config.hidden_size, config.moe_intermediate_size, bias=False)
+ self.w2 = nn.Linear(config.moe_intermediate_size, config.hidden_size, bias=False)
+ self.w3 = nn.Linear(config.hidden_size, config.moe_intermediate_size, bias=False)
+ self.act_fn = SituAndMul()
+
+ def forward(self, x):
+ return self.w2(self.act_fn(torch.cat([self.w1(x), self.w3(x)], dim=-1)))
+
+
+class Gate(nn.Module):
+ def __init__(self, config):
+ super().__init__()
+ self.top_k = config.num_experts_per_tok
+ self.weight = nn.Parameter(torch.randn(config.num_experts, config.hidden_size) * 0.1)
+
+ def forward(self, hidden_states):
+ h = hidden_states.view(-1, hidden_states.shape[-1])
+ scores = F.linear(h.float(), self.weight.float()).softmax(dim=-1)
+ assert not self.training
+ weight, idx = scores.topk(self.top_k, dim=-1)
+ return idx, weight
+
+
+class SparseMoe(nn.Module):
+ def __init__(self, config):
+ super().__init__()
+ self.experts = nn.ModuleList([Expert(config) for _ in range(config.num_experts)])
+ self.gate = Gate(config)
+
+ def forward(self, hidden_states):
+ shape = hidden_states.shape
+ topk_idx, topk_weight = self.gate(hidden_states)
+ hidden_states = hidden_states.view(-1, shape[-1])
+ if not self.training:
+ y = self.moe_infer(hidden_states, topk_idx, topk_weight)
+ else:
+ raise NotImplementedError("inference only")
+ return y.view(*shape)
+
+ @torch.no_grad()
+ def moe_infer(self, x, topk_ids, topk_weight):
+ cnts = topk_ids.new_zeros((topk_ids.shape[0], len(self.experts)))
+ cnts.scatter_(1, topk_ids, 1)
+ tokens_per_expert = cnts.sum(dim=0).cpu().numpy()
+ idxs = topk_ids.view(-1).argsort()
+ sorted_tokens = x[idxs // topk_ids.shape[1]]
+ outputs, start = [], 0
+ for i, n in enumerate(tokens_per_expert):
+ if n == 0:
+ continue
+ outputs.append(self.experts[i](sorted_tokens[start:start + n]))
+ start += n
+ outs = torch.cat(outputs, dim=0)
+ new_x = torch.empty_like(outs)
+ new_x[idxs] = outs
+ return (new_x.view(*topk_ids.shape, -1).type(topk_weight.dtype)
+ .mul_(topk_weight.unsqueeze(dim=-1)).sum(dim=1).type(new_x.dtype))
+
+
+class Layer(nn.Module):
+ def __init__(self, config):
+ super().__init__()
+ self.proj = nn.Linear(config.hidden_size, config.hidden_size, bias=False)
+ self.mlp = SparseMoe(config)
+
+ def forward(self, x):
+ return x + self.mlp(self.proj(x))
+
+
+class TinyMoeForCausalLM(PreTrainedModel):
+ config_class = TinyMoeConfig
+ base_model_prefix = "model"
+ _no_split_modules = ["Layer"]
+
+ def __init__(self, config):
+ super().__init__(config)
+ self.embed = nn.Embedding(config.vocab_size, config.hidden_size)
+ self.layers = nn.ModuleList([Layer(config) for _ in range(config.num_hidden_layers)])
+ self.lm_head = nn.Linear(config.hidden_size, config.vocab_size, bias=False)
+ self.post_init()
+
+ def _init_weights(self, module):
+ pass
+
+ def forward(self, input_ids, labels=None, **kwargs):
+ h = self.embed(input_ids)
+ for layer in self.layers:
+ h = layer(h)
+ logits = self.lm_head(h).float()
+ loss = None
+ if labels is not None:
+ loss = F.cross_entropy(logits.view(-1, logits.shape[-1]), labels.view(-1))
+ return CausalLMOutput(loss=loss, logits=logits)
+"""
+
+
+def _mxfp4_plan():
+ return {
+ "quant_method": "compressed-tensors",
+ "format": "mxfp4-pack-quantized",
+ "quantization_status": "compressed",
+ "config_groups": {
+ "group_0": {
+ "format": "mxfp4-pack-quantized",
+ "targets": ["Linear"],
+ "input_activations": None,
+ "output_activations": None,
+ "weights": {
+ "num_bits": 4,
+ "type": "float",
+ "strategy": "group",
+ "group_size": 32,
+ "symmetric": True,
+ "dynamic": False,
+ "scale_dtype": "torch.uint8",
+ "actorder": None,
+ "observer": "minmax",
+ },
+ }
+ },
+ "ignore": ["re:.*\\.proj$", "re:.*lm_head.*"],
+ }
+
+
+def _remote_module(name, source = MODELING):
+ import linecache
+
+ mod = types.ModuleType(name)
+ filename = f"<{name}>"
+ linecache.cache[filename] = (len(source), None, source.splitlines(True), filename)
+ exec(compile(source, filename, "exec"), mod.__dict__)
+ sys.modules[name] = mod
+ for cls in (
+ mod.SparseMoe,
+ mod.Gate,
+ mod.Expert,
+ mod.Layer,
+ mod.TinyMoeForCausalLM,
+ mod.SituAndMul,
+ ):
+ cls.__module__ = name
+ return mod
+
+
+def _keys(
+ layers = 2,
+ experts = E,
+ drop = None,
+ extra = (),
+):
+ keys = []
+ for layer in range(layers):
+ for e in range(experts):
+ for w in ("w1", "w2", "w3"):
+ for kind in ("weight_packed", "weight_scale"):
+ keys.append(f"model.layers.{layer}.mlp.experts.{e}.{w}.{kind}")
+ keys.append(f"model.layers.{layer}.proj.weight")
+ if drop:
+ keys.remove(drop)
+ return keys + list(extra)
+
+
+def test_key_scan_needs_every_expert_projection_and_nothing_else():
+ assert packed_expert_prefixes(_keys()) == {"model.layers.0.mlp": E, "model.layers.1.mlp": E}
+ assert packed_expert_prefixes(_keys(drop = "model.layers.1.mlp.experts.2.w3.weight_scale")) == {}
+ extra = ("model.layers.0.mlp.experts.0.w1.weight_shape",)
+ assert packed_expert_prefixes(_keys(extra = extra)) == {}
+ assert packed_expert_prefixes(["model.layers.0.proj.weight"]) == {}
+
+
+def test_keep_packed_is_mxfp4_only_and_switchable(monkeypatch):
+ monkeypatch.delenv("UNSLOTH_MXFP4_KEEP_PACKED", raising = False)
+ assert keep_mxfp4_experts_packed(_mxfp4_plan())
+ int4 = dict(_mxfp4_plan(), format = "pack-quantized")
+ int4["config_groups"] = {
+ "group_0": dict(int4["config_groups"]["group_0"], format = "pack-quantized")
+ }
+ assert not keep_mxfp4_experts_packed(int4)
+ monkeypatch.setenv("UNSLOTH_MXFP4_KEEP_PACKED", "0")
+ assert not keep_mxfp4_experts_packed(_mxfp4_plan())
+
+
+def _tiny_model(
+ name,
+ layers = 2,
+ source = MODELING,
+):
+ mod = _remote_module(name, source)
+ config = mod.TinyMoeConfig(num_hidden_layers = layers)
+ with torch.device("meta"):
+ model = mod.TinyMoeForCausalLM(config)
+ return mod, model
+
+
+def test_swap_replaces_every_packed_layer_on_meta():
+ mod, model = _tiny_model("transformers_modules.k3c_swap_a.modeling_tinymoe")
+ swapped = _swap_planned_stacks(model, _keys(), torch.bfloat16)
+ assert swapped == ["layers.0.mlp", "layers.1.mlp"]
+ for layer in model.layers:
+ experts = layer.mlp.experts
+ assert isinstance(experts, Mxfp4StackedExperts)
+ assert experts.fused_gate_up_act and len(experts) == E
+ assert experts.gate_up_blocks.shape == (E, 2 * I, H // 32, 16)
+ assert experts.down_scales.shape == (E, H, I // 32)
+ assert experts.gate_up_blocks.dtype == torch.uint8 and experts.gate_up_blocks.is_meta
+ assert isinstance(layer.proj, nn.Linear)
+
+
+def test_swap_is_all_or_nothing():
+ _, model = _tiny_model("transformers_modules.k3c_swap_b.modeling_tinymoe")
+ keys = _keys(drop = "model.layers.1.mlp.experts.0.w2.weight_packed")
+ assert _swap_planned_stacks(model, keys, torch.bfloat16) == []
+ keys = _keys(layers = 3)
+ assert _swap_planned_stacks(model, keys, torch.bfloat16) == []
+ assert all(isinstance(layer.mlp.experts, nn.ModuleList) for layer in model.layers)
+ _, model = _tiny_model("transformers_modules.k3c_swap_c.modeling_tinymoe")
+ for layer in model.layers:
+ for expert in layer.mlp.experts:
+ expert.w2 = nn.Linear(I, H, bias = True, device = "meta")
+ assert _swap_planned_stacks(model, _keys(), torch.bfloat16) == []
+
+
+def test_stacking_op_keeps_w1_then_w3_and_expert_order():
+ g = torch.Generator().manual_seed(0)
+ per = {
+ w: [torch.randint(0, 256, (I, H // 2), dtype = torch.uint8, generator = g) for _ in range(E)]
+ for w in ("w1", "w3")
+ }
+ sources = ["experts.*.w1.weight_packed$", "experts.*.w3.weight_packed$"]
+ got = _StackPackedExperts(False).convert(
+ {sources[1]: per["w3"], sources[0]: per["w1"]},
+ source_patterns = sources,
+ target_patterns = ["experts.gate_up_blocks"],
+ )["experts.gate_up_blocks"]
+ assert got.shape == (E, 2 * I, H // 32, 16)
+ for e in range(E):
+ assert torch.equal(got[e, :I].reshape(I, H // 2), per["w1"][e])
+ assert torch.equal(got[e, I:].reshape(I, H // 2), per["w3"][e])
+ scales = [torch.randint(0, 256, (H, I // 32), dtype = torch.uint8, generator = g) for _ in range(E)]
+ got = _StackPackedExperts(True).convert(
+ {"experts.*.w2.weight_scale$": scales},
+ source_patterns = ["experts.*.w2.weight_scale$"],
+ target_patterns = ["experts.down_scales"],
+ )["experts.down_scales"]
+ assert torch.equal(got, torch.stack(scales))
+
+
+def test_expert_lora_stays_opt_in():
+ _, model = _tiny_model("transformers_modules.k3c_lora.modeling_tinymoe")
+ _swap_planned_stacks(model, _keys(), torch.bfloat16)
+ auto = ["experts.gate_up_proj", "experts.down_proj"]
+ assert packed_expert_target_parameters(model, auto, ["q_proj", "down_proj"]) is None
+ assert packed_expert_target_parameters(model, auto, ["w1"]) == ["experts.gate_up_proj"]
+ assert packed_expert_target_parameters(model, None, ["w2", "w3"]) == auto
+ assert packed_expert_target_parameters(model, ["mlp.other"], None) == ["mlp.other"]
+ assert packed_expert_target_parameters(model, auto, r".*experts.*w1") == [
+ "experts.gate_up_proj"
+ ]
+ assert packed_expert_target_parameters(model, auto, r".*\.(w1|w2)") == auto
+ assert packed_expert_target_parameters(model, auto, r".*(q_proj|down_proj)") is None
+ # A regex naming only a later expert matched that expert's Linear before stacking.
+ last = len(next(m for m in model.modules() if type(m).__name__ == "Mxfp4StackedExperts")) - 1
+ assert packed_expert_target_parameters(model, auto, rf".*experts\.{last}\.w2") == [
+ "experts.down_proj"
+ ]
+ _, plain = _tiny_model("transformers_modules.k3c_lora_b.modeling_tinymoe")
+ assert packed_expert_target_parameters(plain, auto, None) is auto
+
+
+def test_a_target_list_naming_expert_paths_opts_packed_experts_in():
+ _, model = _tiny_model("transformers_modules.k3c_lora_paths.modeling_tinymoe")
+ _swap_planned_stacks(model, _keys(), torch.bfloat16)
+ stack = next(n for n, m in model.named_modules() if type(m).__name__ == "Mxfp4StackedExperts")
+ auto = ["experts.gate_up_proj", "experts.down_proj"]
+ assert packed_expert_target_parameters(model, auto, ["q_proj", f"{stack}.1.w1"]) == [
+ f"{stack}.gate_up_proj"
+ ]
+ scoped = packed_expert_target_parameters(model, auto, rf"{re.escape(stack)}\.\d+\.w2")
+ assert scoped == [f"{stack}.down_proj"]
+ assert packed_expert_target_parameters(model, None, ["experts.0.w2"]) == ["experts.down_proj"]
+ # Suffixes that name something else, and a non-index where the expert index goes, do not.
+ assert packed_expert_target_parameters(model, auto, ["mlp.w1", "experts.x.w1", "0.w1x"]) is None
+
+
+def test_packed_experts_are_found_under_peft_wrappers():
+ from unsloth.models.remote_moe_shims import _is_packed_experts
+
+ _, model = _tiny_model("transformers_modules.k3c_wrapped.modeling_tinymoe")
+ _swap_planned_stacks(model, _keys(), torch.bfloat16)
+
+ class Wrapper(nn.Module):
+ def __init__(self, base_layer):
+ super().__init__()
+ self.base_layer = base_layer
+
+ block = model.layers[0].mlp
+ block.experts = Wrapper(Wrapper(block.experts))
+ assert _is_packed_experts(block.experts)
+ assert is_remote_deepseek_moe(block)
+
+
+def _materialize_packed(model, seed = 0):
+ """Fill the meta stacks with random MXFP4 bytes (scales near 1) and finalize."""
+ g = torch.Generator().manual_seed(seed)
+ for layer in model.layers:
+ experts = layer.mlp.experts
+ for name, param in list(experts.named_parameters()):
+ if name.endswith("scales"):
+ value = torch.randint(118, 125, param.shape, dtype = torch.uint8, generator = g)
+ else:
+ value = torch.randint(0, 256, param.shape, dtype = torch.uint8, generator = g)
+ setattr(experts, name, nn.Parameter(value, requires_grad = False))
+ experts.finalize()
+
+
+def test_packed_block_trains_and_matches_its_per_expert_view():
+ torch.manual_seed(0)
+ mod, _ = _tiny_model("transformers_modules.k3c_dispatch.modeling_tinymoe")
+ config = mod.TinyMoeConfig(num_hidden_layers = 1)
+ model = mod.TinyMoeForCausalLM(config).to(torch.bfloat16)
+ assert _swap_planned_stacks(model, _keys(layers = 1), torch.bfloat16) == ["layers.0.mlp"]
+ _materialize_packed(model)
+ block = model.layers[0].mlp
+ assert is_remote_deepseek_moe(block)
+ x = torch.randn(2, 6, H).to(torch.bfloat16)
+ block.eval()
+ with torch.no_grad():
+ port = mod.SparseMoe.moe_infer(block, x.view(-1, H), *block.gate(x))
+ assert "SparseMoe" in prepare_remote_moe_for_training(model, verbose = False)
+ with torch.no_grad():
+ packed_eval = block(x)
+ torch.testing.assert_close(packed_eval.view(-1, H).float(), port.float(), atol = 2e-2, rtol = 2e-2)
+ block.train()
+ xi = x.clone().requires_grad_(True)
+ out = block(xi)
+ torch.testing.assert_close(out.detach().float(), packed_eval.float(), atol = 0, rtol = 0)
+ out.float().square().sum().backward()
+ assert xi.grad is not None and xi.grad.abs().sum() > 0
+ assert block.gate.weight.grad is not None and block.training and block.gate.training
+
+
+def _write_checkpoint(root):
+ from safetensors.torch import save_file
+
+ d = os.path.join(root, "tiny_mxfp4_moe")
+ os.makedirs(d, exist_ok = True)
+ with open(os.path.join(d, "modeling_tinymoe.py"), "w") as f:
+ f.write(MODELING)
+ g = torch.Generator().manual_seed(0)
+ tensors = {
+ "embed.weight": torch.randn(128, H, generator = g).to(torch.bfloat16),
+ "lm_head.weight": (torch.randn(128, H, generator = g) * 0.1).to(torch.bfloat16),
+ }
+ for key in _keys():
+ if key.endswith("proj.weight"):
+ tensors[key] = (torch.randn(H, H, generator = g) * 0.1).to(torch.bfloat16)
+ continue
+ out_f, in_f = (H, I) if ".w2." in key else (I, H)
+ if key.endswith("weight_packed"):
+ tensors[key] = torch.randint(0, 256, (out_f, in_f // 2), dtype = torch.uint8, generator = g)
+ else:
+ tensors[key] = torch.randint(
+ 118, 125, (out_f, in_f // 32), dtype = torch.uint8, generator = g
+ )
+ for layer in range(2):
+ tensors[f"model.layers.{layer}.mlp.gate.weight"] = (
+ torch.randn(E, H, generator = g) * 0.1
+ ).to(torch.bfloat16)
+ # The module tree has no `model.` level: the loader strips the base-model prefix.
+ tensors = {k.replace("model.layers.", "layers.", 1): v for k, v in tensors.items()}
+ save_file(tensors, os.path.join(d, "model.safetensors"), metadata = {"format": "pt"})
+ config = {
+ "architectures": ["TinyMoeForCausalLM"],
+ "model_type": "tiny_mxfp4_moe",
+ "auto_map": {
+ "AutoConfig": "modeling_tinymoe.TinyMoeConfig",
+ "AutoModelForCausalLM": "modeling_tinymoe.TinyMoeForCausalLM",
+ },
+ "vocab_size": 128,
+ "hidden_size": H,
+ "moe_intermediate_size": I,
+ "num_experts": E,
+ "num_experts_per_tok": K,
+ "num_hidden_layers": 2,
+ "hidden_act": "situ",
+ "torch_dtype": "bfloat16",
+ "quantization_config": _mxfp4_plan(),
+ }
+ json.dump(config, open(os.path.join(d, "config.json"), "w"))
+ return d, tensors
+
+
+def _load(path):
+ from transformers import AutoConfig, AutoModelForCausalLM, BitsAndBytesConfig
+
+ config = AutoConfig.from_pretrained(path, trust_remote_code = True)
+ assert arm_compressed_tensors_bnb_loading(config, verbose = False) is not None
+ return AutoModelForCausalLM.from_pretrained(
+ path,
+ config = config,
+ trust_remote_code = True,
+ dtype = torch.bfloat16,
+ device_map = {"": 0},
+ quantization_config = BitsAndBytesConfig(
+ load_in_4bit = True,
+ bnb_4bit_quant_type = "nf4",
+ bnb_4bit_compute_dtype = torch.bfloat16,
+ ),
+ )
+
+
[email protected](not has_real_cuda(), reason = "needs a CUDA device")
+ not (HAS_CT and HAS_CONVERTERS),
+ reason = "needs compressed-tensors and the transformers 5.8+ loader",
+)
+def test_remote_code_checkpoint_loads_packed_bytes_verbatim(tmp_path, monkeypatch):
+ import bitsandbytes as bnb
+
+ monkeypatch.delenv("UNSLOTH_MXFP4_KEEP_PACKED", raising = False)
+ path, tensors = _write_checkpoint(str(tmp_path))
+ model = _load(path)
+ for layer_index, layer in enumerate(model.layers):
+ experts = layer.mlp.experts
+ assert isinstance(experts, Mxfp4StackedExperts), type(experts)
+ assert isinstance(layer.proj, bnb.nn.Linear4bit)
+ prefix = f"layers.{layer_index}.mlp.experts"
+ for e in range(E):
+ gate_up = experts.gate_up_proj.data[e].reshape(2 * I, H // 2).cpu()
+ assert torch.equal(gate_up[:I], tensors[f"{prefix}.{e}.w1.weight_packed"])
+ assert torch.equal(gate_up[I:], tensors[f"{prefix}.{e}.w3.weight_packed"])
+ down = experts.down_proj.data[e].reshape(H, I // 2).cpu()
+ assert torch.equal(down, tensors[f"{prefix}.{e}.w2.weight_packed"])
+ scales = experts.gate_up_proj.mxfp4_scales[e].cpu()
+ assert torch.equal(scales[:I], tensors[f"{prefix}.{e}.w1.weight_scale"])
+ assert torch.equal(
+ experts.down_proj.mxfp4_scales[e].cpu(), tensors[f"{prefix}.{e}.w2.weight_scale"]
+ )
+ assert not any("weight_packed" in n for n, _ in model.named_parameters())
+ assert not getattr(model, "_weight_conversions", None) or not any(
+ type(op).__name__ == "StackPackedExperts"
+ for conv in model._weight_conversions
+ for op in getattr(conv, "operations", [])
+ )
+ ids = torch.randint(0, 128, (2, 8), device = "cuda:0")
+ model.eval()
+ with torch.no_grad():
+ port = model(input_ids = ids).logits
+ prepare_remote_moe_for_training(model, verbose = False)
+ with torch.no_grad():
+ grouped = model(input_ids = ids).logits
+ torch.testing.assert_close(grouped, port, atol = 5e-2, rtol = 5e-2)
+ model.train()
+ loss = model(input_ids = ids, labels = ids).loss
+ loss.backward()
+ assert torch.isfinite(loss)
+ assert model.layers[0].mlp.gate.weight.grad is not None
+
+
[email protected](not has_real_cuda(), reason = "needs a CUDA device")
+ not (HAS_CT and HAS_CONVERTERS),
+ reason = "needs compressed-tensors and the transformers 5.8+ loader",
+)
+def test_keep_packed_off_restores_the_nf4_experts(tmp_path, monkeypatch):
+ import bitsandbytes as bnb
+
+ monkeypatch.setenv("UNSLOTH_MXFP4_KEEP_PACKED", "0")
+ path, _ = _write_checkpoint(str(tmp_path))
+ model = _load(path)
+ experts = model.layers[0].mlp.experts
+ assert isinstance(experts, nn.ModuleList)
+ assert isinstance(experts[0].w1, bnb.nn.Linear4bit)
+
+
+def test_plan_stacks_the_experts_and_keeps_every_other_packed_linear_all_or_nothing():
+ _, model = _tiny_model("transformers_modules.k3s_plan_a.modeling_tinymoe")
+ plan = plan_mxfp4_keep_packed(model, _keys())
+ assert [name for name, *_ in plan.blocks] == ["layers.0.mlp", "layers.1.mlp"]
+ assert plan.linears == []
+ extra = ("model.layers.0.proj.weight_packed", "model.layers.0.proj.weight_scale")
+ plan = plan_mxfp4_keep_packed(model, _keys(extra = extra))
+ assert len(plan.blocks) == 2 and plan.linears == ["layers.0.proj"]
+ # A layer packed only in part, or a packed module with no home: nothing stays packed.
+ assert (
+ plan_mxfp4_keep_packed(model, _keys(drop = "model.layers.1.mlp.experts.0.w2.weight_packed"))
+ is None
+ )
+ assert plan_mxfp4_keep_packed(model, _keys(extra = ("model.nowhere.weight_packed",))) is None
+ assert plan_mxfp4_keep_packed(model, ["model.layers.0.proj.weight"]) is None
+ # Experts that are not the plain layout a stack replaces stay packed one Linear each.
+ _, model = _tiny_model("transformers_modules.k3s_plan_b.modeling_tinymoe")
+ for layer in model.layers:
+ for expert in layer.mlp.experts:
+ expert.w2 = nn.Linear(I, H, bias = True, device = "meta")
+ plan = plan_mxfp4_keep_packed(model, _keys())
+ assert plan.blocks == [] and len(plan.linears) == 2 * E * 3
+
+
+def _packed_expert_linears(model, seed = 0):
+ """Every expert Linear as a filled Mxfp4PackedLinear, as the compressed-tensors route adopts them."""
+ from unsloth.models.mxfp4_compressed_linear import make_mxfp4_packed_linear
+
+ g = torch.Generator().manual_seed(seed)
+ for layer in model.layers:
+ for expert in layer.mlp.experts:
+ for proj in ("w1", "w2", "w3"):
+ old = getattr(expert, proj)
+ new = make_mxfp4_packed_linear(
+ old.in_features, old.out_features, dtype = torch.bfloat16
+ )
+ new.weight_packed.data.copy_(
+ torch.randint(0, 256, new.weight_packed.shape, dtype = torch.uint8, generator = g)
+ )
+ new.weight_scale.data.copy_(
+ torch.randint(118, 125, new.weight_scale.shape, dtype = torch.uint8, generator = g)
+ )
+ setattr(expert, proj, new)
+
+
+def test_compressed_tensors_route_stacks_the_adopted_experts_verbatim():
+ from unsloth.models.mxfp4_compressed_linear import stack_packed_expert_linears
+
+ torch.manual_seed(0)
+ mod, _ = _tiny_model("transformers_modules.k3s_ct_stack.modeling_tinymoe")
+ model = mod.TinyMoeForCausalLM(mod.TinyMoeConfig(num_hidden_layers = 2)).to(torch.bfloat16)
+ _packed_expert_linears(model)
+ before = [
+ {
+ (e, p): types.SimpleNamespace(
+ weight_packed = getattr(x, p).weight_packed.clone(),
+ weight_scale = getattr(x, p).weight_scale.clone(),
+ )
+ for e, x in enumerate(layer.mlp.experts)
+ for p in ("w1", "w2", "w3")
+ }
+ for layer in model.layers
+ ]
+ x = torch.randn(5, H).to(torch.bfloat16)
+ want = [[expert(x) for expert in layer.mlp.experts] for layer in model.layers]
+ old_experts = list(model.layers[0].mlp.experts)
+ assert stack_packed_expert_linears(model, ["layers.0.mlp", "layers.1.mlp"]) == [
+ "layers.0.mlp",
+ "layers.1.mlp",
+ ]
+ assert all("weight_packed" not in x.w1._parameters for x in old_experts)
+ for index, layer in enumerate(model.layers):
+ experts = layer.mlp.experts
+ assert isinstance(experts, Mxfp4StackedExperts)
+ for e in range(E):
+ gate_up = experts.gate_up_proj.data[e].reshape(2 * I, H // 2)
+ assert torch.equal(gate_up[:I], before[index][(e, "w1")].weight_packed)
+ assert torch.equal(gate_up[I:], before[index][(e, "w3")].weight_packed)
+ assert torch.equal(
+ experts.down_proj.data[e].reshape(H, I // 2), before[index][(e, "w2")].weight_packed
+ )
+ assert torch.equal(
+ experts.down_proj.mxfp4_scales[e], before[index][(e, "w2")].weight_scale
+ )
+ torch.testing.assert_close(experts[e](x), want[index][e], atol = 1e-2, rtol = 1e-2)
+
+
[email protected](not has_real_cuda(), reason = "needs a CUDA device")
+ not (HAS_CT and HAS_CONVERTERS), reason = "needs compressed-tensors and the transformers 5 loader"
+)
+def test_remote_code_checkpoint_16bit_load_keeps_packed_stacks(tmp_path, monkeypatch):
+ from transformers import AutoModelForCausalLM
+ from unsloth.models.mxfp4_compressed_linear import install_compressed_tensors_keep_packed
+
+ monkeypatch.delenv("UNSLOTH_MXFP4_KEEP_PACKED", raising = False)
+ assert install_compressed_tensors_keep_packed()
+ path, tensors = _write_checkpoint(str(tmp_path))
+ model = AutoModelForCausalLM.from_pretrained(
+ path, trust_remote_code = True, dtype = torch.bfloat16, device_map = {"": 0}
+ )
+ for layer_index, layer in enumerate(model.layers):
+ experts = layer.mlp.experts
+ assert isinstance(experts, Mxfp4StackedExperts), type(experts)
+ assert type(layer.proj) is nn.Linear and layer.proj.weight.dtype == torch.bfloat16
+ prefix = f"layers.{layer_index}.mlp.experts"
+ for e in range(E):
+ gate_up = experts.gate_up_proj.data[e].reshape(2 * I, H // 2).cpu()
+ assert torch.equal(gate_up[:I], tensors[f"{prefix}.{e}.w1.weight_packed"])
+ assert torch.equal(gate_up[I:], tensors[f"{prefix}.{e}.w3.weight_packed"])
+ assert torch.equal(
+ experts.down_proj.mxfp4_scales[e].cpu(), tensors[f"{prefix}.{e}.w2.weight_scale"]
+ )
+ assert not any("weight_packed" in n for n, _ in model.named_parameters())
+ ids = torch.randint(0, 128, (2, 8), device = "cuda:0")
+ model.eval()
+ with torch.no_grad():
+ port = model(input_ids = ids).logits
+ prepare_remote_moe_for_training(model, verbose = False)
+ with torch.no_grad():
+ grouped = model(input_ids = ids).logits
+ torch.testing.assert_close(grouped, port, atol = 5e-2, rtol = 5e-2)
+
+
+def _saved_state(path):
+ from safetensors.torch import load_file
+
+ state = {}
+ for name in os.listdir(path):
+ if name.endswith(".safetensors"):
+ state.update(load_file(os.path.join(path, name)))
+ return state
+
+
+def _packed_tiny_model(name):
+ mod, _ = _tiny_model(name)
+ config = mod.TinyMoeConfig(num_hidden_layers = 2)
+ model = mod.TinyMoeForCausalLM(config).to(torch.bfloat16)
+ _swap_planned_stacks(model, _keys(), torch.bfloat16)
+ _materialize_packed(model)
+ return mod, model
+
+
+def test_full_save_writes_the_checkpoints_per_expert_keys(tmp_path):
+ from unsloth_zoo.temporary_patches import mxfp4 as mx
+
+ mx.patch_save_pretrained_mxfp4()
+ mod, model = _packed_tiny_model("transformers_modules.k3s_save_a.modeling_tinymoe")
+ model.config.quantization_config = _mxfp4_plan()
+ stacks = [layer.mlp.experts for layer in model.layers]
+ model.save_pretrained(str(tmp_path / "packed"))
+ assert [layer.mlp.experts for layer in model.layers] == stacks
+ assert model.config.quantization_config == _mxfp4_plan()
+ state = _saved_state(str(tmp_path / "packed"))
+ assert not any("gate_up" in k or "down_proj" in k or "blocks" in k for k in state)
+ assert "quantization_config" not in json.load(open(tmp_path / "packed" / "config.json"))
+ for index, layer in enumerate(model.layers):
+ gate_up = layer.mlp.experts.gate_up_proj.dequantize(torch.bfloat16).cpu() # (E, H, 2I)
+ down = layer.mlp.experts.down_proj.dequantize(torch.bfloat16).cpu() # (E, I, H)
+ for e in range(E):
+ prefix = f"layers.{index}.mlp.experts.{e}"
+ assert torch.equal(state[f"{prefix}.w1.weight"], gate_up[e, :, :I].t())
+ assert torch.equal(state[f"{prefix}.w3.weight"], gate_up[e, :, I:].t())
+ assert torch.equal(state[f"{prefix}.w2.weight"], down[e].t())
+ # The remote code's own per-expert loop on the saved weights gives the packed model's output.
+ plain = mod.TinyMoeForCausalLM(mod.TinyMoeConfig(num_hidden_layers = 2)).to(torch.bfloat16)
+ plain.load_state_dict(state, strict = True)
+ ids = torch.randint(0, 128, (2, 8))
+ model.eval(), plain.eval()
+ with torch.no_grad():
+ torch.testing.assert_close(
+ plain(input_ids = ids).logits, model(input_ids = ids).logits, atol = 0, rtol = 0
+ )
+
+ experts = model.layers[0].mlp.experts
+ dense = experts.gate_up_proj.dequantize(torch.bfloat16) + 0.25
+ packed_param = experts.gate_up_proj
+ experts.gate_up_proj = nn.Parameter(dense, requires_grad = False)
+ model.save_pretrained(str(tmp_path / "merged"))
+ state = _saved_state(str(tmp_path / "merged"))
+ assert torch.equal(state["layers.0.mlp.experts.1.w3.weight"], dense[1, :, I:].t().cpu())
+ experts.gate_up_proj = packed_param
+
+ class Wrapper(nn.Module):
+ def __init__(self, base_layer):
+ super().__init__()
+ self.base_layer = base_layer
+
+ model.layers[1].mlp.experts = Wrapper(model.layers[1].mlp.experts)
+ with pytest.raises(RuntimeError, match = "merge_and_unload"):
+ model.save_pretrained(str(tmp_path / "wrapped"))
+
+
+def test_dense_save_config_skips_the_dense_modules_under_bitsandbytes():
+ from transformers import BitsAndBytesConfig, PretrainedConfig
+ from unsloth_zoo.temporary_patches.mxfp4 import _config_for_dense_save
+
+ config = PretrainedConfig()
+ config.quantization_config = BitsAndBytesConfig(
+ load_in_4bit = True, llm_int8_skip_modules = ["lm_head"]
+ )
+ restore = _config_for_dense_save(config, ["layers.0.mlp.experts"])
+ assert config.quantization_config.llm_int8_skip_modules == ["lm_head", "layers.0.mlp.experts"]
+ restore()
+ assert config.quantization_config.llm_int8_skip_modules == ["lm_head"]
+ text = PretrainedConfig()
+ config = PretrainedConfig(text_config = text)
+ config.text_config = text
+ config.quantization_config, text.quantization_config = _mxfp4_plan(), _mxfp4_plan()
+ restore = _config_for_dense_save(config, [])
+ assert not hasattr(config, "quantization_config") and not hasattr(text, "quantization_config")
+ restore()
+ assert config.quantization_config == text.quantization_config == _mxfp4_plan()
+
+
+ not (HAS_CT and HAS_CONVERTERS),
+ reason = "needs compressed-tensors and the transformers 5.8+ loader",
+)
+def test_a_kept_packed_load_registers_no_decompress_op():
+ from transformers import BitsAndBytesConfig
+ from transformers.quantizers import auto as quantizers_auto
+ from unsloth.models.compressed_tensors_bnb import (
+ _build_quantization_config,
+ install_compressed_tensors_bnb_quantizer,
+ )
+
+ assert install_compressed_tensors_bnb_quantizer()
+ cls = quantizers_auto.AUTO_QUANTIZER_MAPPING["bitsandbytes_4bit"]
+ quantizer = cls(BitsAndBytesConfig(load_in_4bit = True))
+ quantizer._unsloth_ct_config = _build_quantization_config(_mxfp4_plan())
+ quantizer._unsloth_ct_dtype = torch.bfloat16
+ quantizer._unsloth_dtype_plan, quantizer._unsloth_plan_dicts = {}, []
+ ops = lambda convs: [type(op).__name__ for c in convs for op in getattr(c, "operations", [])] # noqa: E731
+ quantizer._unsloth_keep_packed, quantizer._unsloth_packed_experts = True, ["layers.0.mlp"]
+ kept = ops(quantizer.update_weight_conversions([]))
+ assert kept.count("StackPackedExperts") == 4 and "DecompressPackedWeights" not in kept
+ quantizer._unsloth_keep_packed, quantizer._unsloth_packed_experts = False, []
+ assert "DecompressPackedWeights" in ops(quantizer.update_weight_conversions([]))
+
+
+def _peft_target_parameters(model, monkeypatch, **kwargs):
+ """The `target_parameters` FastBaseModel.get_peft_model hands PEFT, captured at LoraConfig."""
+ import functools
+ import unsloth.models.vision as vision
+
+ class _Captured(Exception):
+ pass
+
+ real = vision.LoraConfig
+
+ @functools.wraps(real)
+ def capture(**config):
+ raise _Captured(config.get("target_parameters"))
+
+ monkeypatch.setattr(vision, "LoraConfig", capture)
+ with pytest.raises(_Captured) as captured:
+ vision.FastBaseModel.get_peft_model(model, r = 4, **kwargs)
+ return captured.value.args[0]
+
+
+ "flags, experts",
+ [
+ ({}, True),
+ ({"finetune_mlp_modules": False}, False),
+ ({"finetune_language_layers": False}, False),
+ ],
+)
+def test_packed_expert_targets_follow_the_finetune_family_flags(flags, experts, monkeypatch):
+ mod, _ = _tiny_model("transformers_modules.k3s_scope.modeling_tinymoe")
+ model = mod.TinyMoeForCausalLM(mod.TinyMoeConfig(num_hidden_layers = 1)).to(torch.bfloat16)
+ _swap_planned_stacks(model, _keys(layers = 1), torch.bfloat16)
+ _materialize_packed(model)
+ model.max_seq_length = 64
+ model.vision_tower = nn.Module()
+ model.vision_tower.attn = nn.Module()
+ model.vision_tower.attn.q_proj = nn.Linear(H, H, bias = False)
+ got = _peft_target_parameters(
+ model, monkeypatch, target_modules = ["q_proj", "w1", "w2"], **flags
+ )
+ want = ["experts.gate_up_proj", "experts.down_proj"] if experts else []
+ assert sorted(got or []) == sorted(want)
+
+
+ "kwargs, experts",
+ [
+ ({}, True),
+ ({"target_modules": "all-linear"}, True),
+ ({"finetune_mlp_modules": False}, False),
+ ],
+)
+def test_auto_targets_keep_packed_experts_as_they_kept_the_per_expert_linears(
+ kwargs, experts, monkeypatch
+):
+ mod, _ = _tiny_model("transformers_modules.k3s_auto.modeling_tinymoe")
+ model = mod.TinyMoeForCausalLM(mod.TinyMoeConfig(num_hidden_layers = 1)).to(torch.bfloat16)
+ _swap_planned_stacks(model, _keys(layers = 1), torch.bfloat16)
+ _materialize_packed(model)
+ model.max_seq_length = 64
+ # Real Kimi layers carry attention Linears; without any, get_peft_regex has nothing to target.
+ model.layers[0].self_attn = nn.Module()
+ model.layers[0].self_attn.q_proj = nn.Linear(H, H, bias = False)
+ model.vision_tower = nn.Module()
+ model.vision_tower.attn = nn.Module()
+ model.vision_tower.attn.q_proj = nn.Linear(H, H, bias = False)
+ got = _peft_target_parameters(model, monkeypatch, **kwargs)
+ want = ["experts.gate_up_proj", "experts.down_proj"] if experts else []
+ assert sorted(got or []) == sorted(want)
+
+
+def test_a_regex_target_string_opts_packed_experts_in(monkeypatch):
+ """get_peft_model with a regex string naming the per-expert Linears trains the stacks."""
+ mod, _ = _tiny_model("transformers_modules.k3s_regex.modeling_tinymoe")
+ model = mod.TinyMoeForCausalLM(mod.TinyMoeConfig(num_hidden_layers = 1)).to(torch.bfloat16)
+ _swap_planned_stacks(model, _keys(layers = 1), torch.bfloat16)
+ _materialize_packed(model)
+ model.max_seq_length = 64
+ got = _peft_target_parameters(model, monkeypatch, target_modules = r".*(q_proj|experts\.\d+\.w1)")
+ assert sorted(got or []) == ["experts.gate_up_proj"]
+
+
+def test_nothing_stays_packed_without_the_zoo_full_save_support(monkeypatch):
+ from unsloth_zoo.temporary_patches import mxfp4 as zoo_mxfp4
+
+ monkeypatch.delenv("UNSLOTH_MXFP4_KEEP_PACKED", raising = False)
+ assert keep_mxfp4_experts_packed(_mxfp4_plan())
+ monkeypatch.delattr(zoo_mxfp4, "_densified_module_names")
+ assert not keep_mxfp4_experts_packed(_mxfp4_plan())
+
+
+TRAINING_MODELING = MODELING.replace(
+ """ if not self.training:
+ y = self.moe_infer(hidden_states, topk_idx, topk_weight)
+ else:
+ raise NotImplementedError("inference only")""",
+ """ if self.training:
+ flat = topk_idx.view(-1)
+ x = hidden_states.repeat_interleave(topk_idx.shape[1], dim=0)
+ y = torch.empty_like(x)
+ for i, expert in enumerate(self.experts):
+ y[flat == i] = expert(x[flat == i]).to(y.dtype)
+ y = (y.view(*topk_weight.shape, -1) * topk_weight.unsqueeze(-1)).sum(dim=1).to(y.dtype)
+ else:
+ y = self.moe_infer(hidden_states, topk_idx, topk_weight)""",
+).replace(" assert not self.training\n", "")
+
+
+def test_only_blocks_the_remote_moe_shim_dispatches_are_stacked():
+ assert TRAINING_MODELING != MODELING
+ _, model = _tiny_model(
+ "transformers_modules.k3s_train_branch.modeling_tinymoe", source = TRAINING_MODELING
+ )
+ assert not is_remote_deepseek_moe(model.layers[0].mlp)
+ plan = plan_mxfp4_keep_packed(model, _keys())
+ assert plan.blocks == [] and len(plan.linears) == 2 * E * 3
+ _, model = _tiny_model("transformers_modules.k3s_ep.modeling_tinymoe")
+ model.layers[1].mlp.ep_size = 2
+ plan = plan_mxfp4_keep_packed(model, _keys())
+ assert plan.blocks == [] and len(plan.linears) == 2 * E * 3
+
+
+def test_a_packed_linear_without_its_scale_is_not_kept_packed():
+ _, model = _tiny_model("transformers_modules.k3s_noscale.modeling_tinymoe")
+ extra = ("model.layers.0.proj.weight_packed", "model.layers.0.proj.weight_scale")
+ assert plan_mxfp4_keep_packed(model, _keys(extra = extra)).linears == ["layers.0.proj"]
+ assert plan_mxfp4_keep_packed(model, _keys(extra = extra[:1])) is None
+
+
[email protected](not has_real_cuda(), reason = "needs a CUDA device")
+def test_compressed_tensors_route_stacking_stages_gate_up_then_down():
+ from unsloth.models.mxfp4_compressed_linear import stack_packed_expert_linears
+
+ mod, _ = _tiny_model("transformers_modules.k3s_ct_peak.modeling_tinymoe")
+ model = mod.TinyMoeForCausalLM(mod.TinyMoeConfig(num_hidden_layers = 1)).to(torch.bfloat16)
+ _packed_expert_linears(model)
+ model.cuda()
+ experts = model.layers[0].mlp.experts
+ size = lambda *ts: sum(t.numel() * t.element_size() for t in ts) # noqa: E731
+ gate_up = size(*[getattr(e, w).weight_packed for e in experts for w in ("w1", "w3")])
+ gate_up += size(*[getattr(e, w).weight_scale for e in experts for w in ("w1", "w3")])
+ torch.cuda.synchronize()
+ torch.cuda.reset_peak_memory_stats()
+ start = torch.cuda.memory_allocated()
+ assert stack_packed_expert_linears(model, ["layers.0.mlp"]) == ["layers.0.mlp"]
+ torch.cuda.synchronize()
+ assert torch.cuda.max_memory_allocated() - start <= gate_up + 1024
+ assert torch.cuda.memory_allocated() <= start + 1024 # every per-expert byte moved, none kept
diff --git a/tests/test_mxfp4_compressed_linear.py b/tests/test_mxfp4_compressed_linear.py
new file mode 100644
index 00000000000..0fda111399a
--- /dev/null
+++ b/tests/test_mxfp4_compressed_linear.py
@@ -0,0 +1,1205 @@
+# SPDX-License-Identifier: AGPL-3.0-only
+# Copyright 2023-present Daniel 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/>.
+
+"""compressed-tensors ``mxfp4-pack-quantized`` Linears stay packed and train through."""
+
+import copy
+import json
+import os
+import shutil
+
+import pytest
+from llama_patch_isolation import restore_llama_patches # noqa: F401
+from real_accelerator import has_real_cuda # tests/_shared, on sys.path via tests/conftest.py
+import torch
+from torch import nn
+
+import unsloth # noqa: F401
+from unsloth.models.mxfp4_compressed_linear import (
+ Mxfp4PackedLinear,
+ _dequantize_torch,
+ adopt_compressed_mxfp4_modules,
+ dequantize_mxfp4_packed,
+ make_mxfp4_packed_linear,
+)
+
+try:
+ from compressed_tensors.config import CompressionFormat
+
+ # Releases before MXFP4 (0.12.x, which vllm 0.11.2 pins) reject its config outright.
+ HAS_CT = any(f.value == "mxfp4-pack-quantized" for f in CompressionFormat)
+ if HAS_CT:
+ # compressed-tensors < 0.16 (the newest on torch 2.6) has the format but its decompress raises.
+ from compressed_tensors.compressors import BaseCompressor
+ from compressed_tensors.quantization import QuantizationArgs, QuantizationScheme
+ BaseCompressor.get_value_from_registry("mxfp4-pack-quantized").decompress(
+ {
+ "weight_packed": torch.zeros(1, 16, dtype = torch.uint8),
+ "weight_scale": torch.full((1, 1), 127, dtype = torch.uint8),
+ },
+ QuantizationScheme(
+ targets = ["Linear"],
+ weights = QuantizationArgs(
+ num_bits = 4,
+ type = "float",
+ strategy = "group",
+ group_size = 32,
+ symmetric = True,
+ scale_dtype = torch.uint8,
+ ),
+ format = "mxfp4-pack-quantized",
+ ),
+ )
+except Exception:
+ HAS_CT = False
+
+from unsloth.models.compressed_tensors_bnb import _transformers_supports_weight_converters
+
+pytestmark = pytest.mark.usefixtures("restore_llama_patches")
+
+HAS_CONVERTERS = _transformers_supports_weight_converters()
+
+try:
+ from unsloth_zoo.temporary_patches import mxfp4 as _zoo_mxfp4
+ HAS_ZOO_PACKED_SAVE = hasattr(_zoo_mxfp4, "_densified_module_names")
+except Exception:
+ HAS_ZOO_PACKED_SAVE = False
+# Without the zoo save support (unsloth-zoo#1371) the packed route declines by design.
+needs_zoo_packed_save = pytest.mark.skipif(
+ not HAS_ZOO_PACKED_SAVE, reason = "needs unsloth-zoo's packed-module save support"
+)
+
+DEVICES = ["cpu"] + (["cuda"] if has_real_cuda() else [])
+_E2M1 = [0.0, 0.5, 1.0, 1.5, 2.0, 3.0, 4.0, 6.0]
+
+
+def _random_packed(
+ out_features,
+ in_features,
+ seed = 0,
+ low = 100,
+ high = 150,
+):
+ g = torch.Generator().manual_seed(seed)
+ packed = torch.randint(0, 256, (out_features, in_features // 2), generator = g, dtype = torch.uint8)
+ scale = torch.randint(
+ low, high, (out_features, in_features // 32), generator = g, dtype = torch.uint8
+ )
+ return packed, scale
+
+
+def _reference_decode(packed, scale):
+ """Element by element, in float64: low nibble first, sign in bit 3, times 2**(e - 127)."""
+ out_features, half = packed.shape
+ w = torch.empty(out_features, half * 2, dtype = torch.float64)
+ for i in range(out_features):
+ for j in range(half):
+ byte = int(packed[i, j])
+ for k, nib in enumerate((byte & 0x0F, byte >> 4)):
+ col = 2 * j + k
+ v = _E2M1[nib & 0x07] * (-1.0 if nib & 0x08 else 1.0)
+ w[i, col] = v * 2.0 ** (int(scale[i, col // 32]) - 127)
+ return w
+
+
[email protected]("device", DEVICES)
+def test_dequant_matches_an_independent_float64_decode(device):
+ packed, scale = _random_packed(8, 64, low = 1, high = 254)
+ packed[0, :16] = torch.arange(0, 256, 16, dtype = torch.uint8)
+ packed[1, :16] = torch.arange(0, 16, dtype = torch.uint8)
+ want = _reference_decode(packed, scale)
+ for dtype in (torch.bfloat16, torch.float32):
+ got = dequantize_mxfp4_packed(packed.to(device), scale.to(device), dtype).cpu()
+ assert got.dtype == dtype and got.shape == (8, 64)
+ assert torch.equal(got.double(), want.to(dtype).double()), dtype
+
+
[email protected](not HAS_CT, reason = "needs compressed-tensors")
[email protected]("device", DEVICES)
+def test_dequant_matches_compressed_tensors_decompress(device):
+ from compressed_tensors.compressors import BaseCompressor
+ from compressed_tensors.quantization import QuantizationArgs, QuantizationScheme
+
+ scheme = QuantizationScheme(
+ targets = ["Linear"],
+ weights = QuantizationArgs(
+ num_bits = 4,
+ type = "float",
+ strategy = "group",
+ group_size = 32,
+ symmetric = True,
+ scale_dtype = torch.uint8,
+ ),
+ format = "mxfp4-pack-quantized",
+ )
+ comp = BaseCompressor.get_value_from_registry("mxfp4-pack-quantized")
+ for seed, (o, i) in enumerate([(128, 128), (96, 256), (3, 64)]):
+ packed, scale = _random_packed(o, i, seed = seed, low = 1, high = 254)
+ state = {
+ "weight_packed": packed,
+ "weight_scale": scale,
+ "weight_shape": torch.tensor([o, i]),
+ }
+ want = comp.decompress(state, scheme)["weight"].to(torch.bfloat16)
+ got = dequantize_mxfp4_packed(packed.to(device), scale.to(device), torch.bfloat16).cpu()
+ assert torch.equal(got.view(torch.int16), want.view(torch.int16)), (o, i)
+
+
[email protected](not has_real_cuda(), reason = "needs a CUDA device")
+def test_zoo_kernel_and_torch_path_agree():
+ packed, scale = _random_packed(256, 512, low = 1, high = 254)
+ packed, scale = packed.cuda(), scale.cuda()
+ blocks = packed.view(256, 16, 16)
+ for dtype in (torch.bfloat16, torch.float16):
+ a = dequantize_mxfp4_packed(packed, scale, dtype)
+ b = _dequantize_torch(blocks, scale, dtype)
+ assert torch.equal(a.view(torch.int16), b.view(torch.int16)), dtype
+
+
[email protected]("device", DEVICES)
[email protected]("bias", [False, True])
+def test_forward_and_input_gradient_are_exact_and_save_only_packed_bytes(device, bias, monkeypatch):
+ import unsloth.models.mxfp4_compressed_linear as mcl
+
+ # The decode + cuBLAS route is bit-exact; skinny inputs on CUDA take the fused GEMM (tested below).
+ monkeypatch.setattr(mcl, "_FUSED_MAX_ROWS", 0)
+ torch.manual_seed(0)
+ out_f, in_f = 96, 64
+ packed, scale = _random_packed(out_f, in_f)
+ module = make_mxfp4_packed_linear(in_f, out_f, device = device)
+ module.weight_packed.data.copy_(packed)
+ module.weight_scale.data.copy_(scale)
+ ref = nn.Linear(in_f, out_f, bias = bias, device = device, dtype = torch.bfloat16)
+ ref.weight.data.copy_(module.dequantize_weight(torch.bfloat16))
+ ref.weight.requires_grad_(False)
+ if bias:
+ module.bias = nn.Parameter(ref.bias.detach().clone())
+ x = torch.randn(5, 7, in_f, device = device, dtype = torch.bfloat16)
+ xa, xb = x.clone().requires_grad_(), x.clone().requires_grad_()
+
+ saved = []
+ with torch.autograd.graph.saved_tensors_hooks(lambda t: saved.append(t) or t, lambda t: t):
+ ya = module(xa)
+ yb = ref(xb)
+ assert torch.equal(ya, yb)
+ # Only the uint8 packed bytes and scales are kept for backward, never a float weight.
+ assert saved and all(t.dtype == torch.uint8 for t in saved), [t.dtype for t in saved]
+ g = torch.randn_like(ya)
+ ya.backward(g)
+ yb.backward(g)
+ assert torch.equal(xa.grad, xb.grad)
+ if bias:
+ assert torch.allclose(module.bias.grad.float(), ref.bias.grad.float(), rtol = 1e-2, atol = 1e-2)
+ assert module.weight_packed.grad is None and not module.weight_packed.requires_grad
+
+
[email protected](not has_real_cuda(), reason = "needs a CUDA device")
+def test_autocast_runs_the_matmul_in_the_autocast_dtype():
+ packed, scale = _random_packed(64, 64)
+ module = make_mxfp4_packed_linear(64, 64, device = "cuda")
+ module.weight_packed.data.copy_(packed)
+ module.weight_scale.data.copy_(scale)
+ ref = nn.Linear(64, 64, bias = False, device = "cuda", dtype = torch.float32)
+ ref.weight.data.copy_(module.dequantize_weight(torch.float32))
+ x = torch.randn(4, 64, device = "cuda", requires_grad = True)
+ x2 = x.detach().clone().requires_grad_()
+ with torch.autocast("cuda", dtype = torch.bfloat16):
+ ya, yb = module(x), ref(x2)
+ assert ya.dtype == yb.dtype == torch.bfloat16
+ assert torch.equal(ya, yb)
+ ya.float().sum().backward()
+ yb.float().sum().backward()
+ assert x.grad.dtype == torch.float32
+ assert torch.equal(x.grad, x2.grad)
+
+
+def test_weight_property_is_an_exact_read_only_decode():
+ packed, scale = _random_packed(32, 64)
+ module = make_mxfp4_packed_linear(64, 32)
+ module.weight_packed.data.copy_(packed)
+ module.weight_scale.data.copy_(scale)
+ w = module.weight
+ assert w.dtype == torch.bfloat16 and w.shape == (32, 64)
+ assert torch.equal(w.double(), _reference_decode(packed, scale).to(torch.bfloat16).double())
+ assert "weight" not in dict(module.named_parameters())
+ assert {n for n, _ in module.named_parameters()} == {"weight_packed", "weight_scale"}
+ with pytest.raises(ValueError):
+ make_mxfp4_packed_linear(48, 32)
+
+
+def _ct_compressed_model(targets_ignore = (), groups = None):
+ from compressed_tensors.compressors import ModelCompressor
+ from compressed_tensors.quantization import QuantizationConfig, apply_quantization_config
+
+ torch.manual_seed(0)
+
+ class Tiny(nn.Module):
+ def __init__(self):
+ super().__init__()
+ self.a = nn.Linear(64, 32, bias = False)
+ self.b = nn.Linear(32, 64, bias = False)
+ self.latent = nn.Linear(64, 64, bias = False)
+
+ def forward(self, x):
+ return self.latent(self.b(self.a(x)))
+
+ model = Tiny().to(torch.bfloat16)
+ quant = {
+ "quant_method": "compressed-tensors",
+ "format": "mxfp4-pack-quantized",
+ "quantization_status": "compressed",
+ "ignore": list(targets_ignore),
+ "config_groups": {
+ "group_0": {
+ "targets": ["Linear"],
+ "weights": {
+ "num_bits": 4,
+ "type": "float",
+ "strategy": "group",
+ "group_size": 32,
+ "symmetric": True,
+ "scale_dtype": "torch.uint8",
+ },
+ }
+ },
+ }
+ if groups is not None:
+ quant["config_groups"] = groups
+ qc = QuantizationConfig.model_validate(quant)
+ apply_quantization_config(model, qc, run_compressed = False)
+ for m in (model.a, model.b, model.latent):
+ m.weight_scale.data.fill_(125 if m.weight_scale.dtype == torch.uint8 else 0.01)
+ ModelCompressor(quantization_config = qc).compress_model(model)
+ return model
+
+
+_MXFP4_WEIGHTS = {
+ "num_bits": 4,
+ "type": "float",
+ "strategy": "group",
+ "group_size": 32,
+ "symmetric": True,
+ "scale_dtype": "torch.uint8",
+}
+
+
[email protected](not HAS_CT, reason = "needs compressed-tensors")
+def test_adopting_compressed_tensors_modules_keeps_them_packed_and_matches_its_decompress():
+ model = _ct_compressed_model()
+ assert hasattr(model, "ct_decompress_hook")
+ assert "weight_packed" in model.a._parameters and "weight" not in model.a._parameters
+ reference = copy.deepcopy(model)
+ x = torch.randn(3, 64, dtype = torch.bfloat16)
+ with torch.no_grad():
+ want = reference(x)
+ assert "weight" in reference.a._parameters
+
+ n = adopt_compressed_mxfp4_modules(model, packed_names = {"a", "b"}, dtype = torch.bfloat16)
+ assert n == 2
+ assert type(model.a) is Mxfp4PackedLinear and type(model.b) is Mxfp4PackedLinear
+ assert type(model.latent) is nn.Linear and "weight" in model.latent._parameters
+ assert "weight_packed" not in model.latent._parameters
+ assert not hasattr(model.latent, "quantization_scheme")
+ assert all("forward" not in m.__dict__ for m in (model.a, model.b, model.latent))
+ assert not hasattr(model, "ct_decompress_hook")
+ model.latent.weight.data.copy_(reference.latent.weight.data)
+ with torch.no_grad():
+ got = model(x)
+ assert torch.equal(got, want)
+ assert "weight_packed" in model.a._parameters
+
+
[email protected](not HAS_CT, reason = "needs compressed-tensors")
+def test_adoption_is_all_or_nothing(monkeypatch):
+ model = _ct_compressed_model()
+ model.b.__class__ = type("Other", (nn.Linear,), {})
+ assert adopt_compressed_mxfp4_modules(model) == 0
+ assert type(model.a) is nn.Linear and hasattr(model, "ct_decompress_hook")
+ model = _ct_compressed_model()
+ monkeypatch.setenv("UNSLOTH_MXFP4_KEEP_PACKED", "0")
+ assert adopt_compressed_mxfp4_modules(model) == 0
+ assert type(model.a) is nn.Linear
+
+
+def _nested_model():
+ class Block(nn.Module):
+ def __init__(self):
+ super().__init__()
+ self.w1 = nn.Linear(64, 32, bias = False)
+ self.proj = nn.Linear(64, 64, bias = False)
+
+ class Inner(nn.Module):
+ def __init__(self):
+ super().__init__()
+ self.layers = nn.ModuleList([Block(), Block()])
+
+ class Outer(nn.Module):
+ def __init__(self):
+ super().__init__()
+ self.model = Inner()
+
+ return Outer()
+
+
[email protected](not HAS_CT, reason = "needs compressed-tensors")
+def test_loader_matches_packed_checkpoint_names_and_swaps_in_empty_packed_modules():
+ from unsloth.models.compressed_tensors_bnb import (
+ _build_quantization_config,
+ _keep_packed_linears,
+ _match_packed_linears,
+ plan_mxfp4_keep_packed,
+ )
+
+ with torch.device("meta"):
+ model = _nested_model()
+ keys = [
+ "language_model.model.layers.0.w1.weight_packed",
+ "language_model.model.layers.0.w1.weight_scale",
+ "language_model.model.layers.1.w1.weight_packed",
+ "language_model.model.layers.1.w1.weight_scale",
+ "language_model.model.layers.0.proj.weight",
+ ]
+ assert set(_match_packed_linears(model, keys)) == {"model.layers.0.w1", "model.layers.1.w1"}
+ # A packed module with no per-Linear home (a merged expert stack) keeps the old route.
+ assert _match_packed_linears(model, keys + ["model.experts.gate_up_proj.weight_packed"]) is None
+ assert _match_packed_linears(model, ["model.layers.0.proj.weight"]) is None
+ plan = plan_mxfp4_keep_packed(model, keys)
+ assert plan.blocks == [] and plan.linears == ["model.layers.0.w1", "model.layers.1.w1"]
+ assert (
+ plan_mxfp4_keep_packed(model, keys + ["model.experts.gate_up_proj.weight_packed"]) is None
+ )
+ assert plan_mxfp4_keep_packed(model, ["model.layers.0.proj.weight"]) is None
+
+ ct_plan = {
+ "quant_method": "compressed-tensors",
+ "format": "mxfp4-pack-quantized",
+ "config_groups": {
+ "group_0": {
+ "targets": ["Linear"],
+ "weights": {
+ "num_bits": 4,
+ "type": "float",
+ "strategy": "group",
+ "group_size": 32,
+ "symmetric": True,
+ "scale_dtype": "torch.uint8",
+ },
+ }
+ },
+ }
+ config = _build_quantization_config(ct_plan)
+ assert _keep_packed_linears(model, plan.linears, config, torch.float16) == 2
+ w1 = model.model.layers[1].w1
+ assert type(w1) is Mxfp4PackedLinear and w1.compute_dtype == torch.float16
+ assert w1.weight_packed.shape == (32, 32) and w1.weight_packed.dtype == torch.uint8
+ assert w1.weight_scale.shape == (32, 2) and w1.weight_packed.is_meta
+ assert type(model.model.layers[0].proj) is nn.Linear
+ assert str(getattr(w1.quantization_status, "value", w1.quantization_status)) == "compressed"
+
+
+def _filled(
+ out_features,
+ in_features,
+ seed = 0,
+ bias = False,
+ device = "cpu",
+ dtype = None,
+):
+ packed, scale = _random_packed(out_features, in_features, seed = seed)
+ module = make_mxfp4_packed_linear(in_features, out_features, device = device, dtype = dtype)
+ module.weight_packed.data.copy_(packed)
+ module.weight_scale.data.copy_(scale)
+ if bias:
+ module.bias = nn.Parameter(torch.randn(out_features, device = device, dtype = torch.bfloat16))
+ return module
+
+
+def test_torch_fallback_without_the_zoo_kernel(monkeypatch):
+ import unsloth.models.mxfp4_compressed_linear as mcl
+
+ packed, scale = _random_packed(16, 64, low = 1, high = 254)
+ with_zoo = dequantize_mxfp4_packed(packed, scale, torch.bfloat16)
+ monkeypatch.setattr(mcl, "_zoo_mxfp4_dequantize", None)
+ assert torch.equal(dequantize_mxfp4_packed(packed, scale, torch.bfloat16), with_zoo)
+
+
+def test_dtype_casts_keep_the_packed_bytes_and_set_the_decode_dtype():
+ module = _filled(32, 64, dtype = torch.float16)
+ module.weight_scale.data.clamp_(110, 130) # stay inside fp16's range
+ before = module.weight_packed.clone(), module.weight_scale.clone()
+ module.to(torch.bfloat16).half()
+ assert module.weight_packed.dtype == torch.uint8 and torch.equal(
+ module.weight_packed, before[0]
+ )
+ assert torch.equal(module.weight_scale, before[1])
+ # `weight` (what PEFT and the fast paths read) decodes in the model's dtype, not always bf16.
+ assert module.weight.dtype == torch.float16
+ assert torch.equal(module.weight.float(), module.dequantize_weight(torch.bfloat16).float())
+
+
[email protected](not has_real_cuda(), reason = "needs a CUDA device")
+def test_device_move_carries_bytes_and_scales():
+ module = _filled(32, 64).cuda()
+ assert module.weight_packed.is_cuda and module.weight_scale.is_cuda
+ assert module.weight.is_cuda
+
+
+def test_fast_lora_paths_get_the_packed_bytes_and_a_decoder_not_a_16bit_weight():
+ peft = pytest.importorskip("peft")
+ from unsloth.kernels.utils import (
+ fast_dequantize,
+ get_lora_parameters,
+ get_lora_parameters_bias,
+ has_mxfp4_base,
+ )
+
+ class Block(nn.Module):
+ def __init__(self):
+ super().__init__()
+ self.proj = _filled(32, 64)
+ self.dense = nn.Linear(64, 64, bias = False)
+
+ model = peft.get_peft_model(Block(), peft.LoraConfig(r = 4, target_modules = ["proj", "dense"]))
+ proj = model.base_model.model.proj
+ W, quant_state, A, B, scale = get_lora_parameters(proj)
+ # The fused kernels save W for backward: it must be the packed bytes, never a 16-bit decode.
+ assert W is proj.base_layer.weight_packed and A is not None
+ assert getattr(quant_state, "_unsloth_packed_weight_state", False)
+ dense = proj.base_layer.dequantize_weight()
+ assert torch.equal(fast_dequantize(W, quant_state), dense)
+ assert torch.equal(fast_dequantize(W.t(), quant_state), dense.t())
+ assert get_lora_parameters_bias(proj)[1] is quant_state
+ assert not has_mxfp4_base(proj) and not has_mxfp4_base(model.base_model.model.dense)
+
+
+def _mlp_lora_pair(hidden, inter):
+ peft = pytest.importorskip("peft")
+
+ class MLP(nn.Module):
+ def __init__(self, gate, up, down):
+ super().__init__()
+ self.gate_proj, self.up_proj, self.down_proj = gate, up, down
+
+ packed = [
+ _filled(inter, hidden, seed = 1),
+ _filled(inter, hidden, seed = 2),
+ _filled(hidden, inter, seed = 3),
+ ]
+ for module in packed:
+ module.weight_scale.data.clamp_(118, 126)
+ dense = []
+ for module in packed:
+ linear = nn.Linear(
+ module.in_features, module.out_features, bias = False, dtype = torch.bfloat16
+ )
+ linear.weight.data.copy_(module.dequantize_weight())
+ dense.append(linear)
+ models = []
+ for layers in (packed, dense):
+ model = peft.get_peft_model(
+ MLP(*layers),
+ peft.LoraConfig(
+ r = 8, lora_alpha = 16, target_modules = ["gate_proj", "up_proj", "down_proj"]
+ ),
+ ).cuda()
+ g = torch.Generator().manual_seed(5)
+ with torch.no_grad():
+ for name, param in sorted(model.named_parameters()):
+ if "lora_" in name:
+ param.copy_((torch.randn(param.shape, generator = g) * 0.05).to(param.dtype))
+ models.append(model.base_model.model)
+ return models
+
+
[email protected](not has_real_cuda(), reason = "needs a CUDA device")
[email protected]("rows", [8, 256])
+def test_fused_lora_mlp_on_a_packed_base_matches_the_dense_base(rows):
+ """8 rows run the fused MXFP4 GEMM (bf16-rounding-level), 256 decode for cuBLAS (bit-exact)."""
+ from unsloth.kernels.fast_lora import apply_lora_mlp_swiglu, apply_lora_o
+
+ packed, dense = _mlp_lora_pair(64, 128)
+ x = torch.randn(
+ 1, rows, 64, device = "cuda", generator = torch.Generator("cuda").manual_seed(0)
+ ).to(torch.bfloat16)
+ results = []
+ for mlp in (packed, dense):
+ xa = x.clone().requires_grad_()
+ with torch.autocast("cuda", dtype = torch.bfloat16):
+ y = apply_lora_mlp_swiglu(mlp, xa, inplace = False)
+ y = y + apply_lora_o(
+ type("O", (), {"o_proj": mlp.down_proj})(), y.new_ones(1, rows, 128) * 0.01
+ )
+ y.float().square().sum().backward()
+ lora_grads = [p.grad.float() for n, p in sorted(mlp.named_parameters()) if "lora_" in n]
+ results.append((y.float(), xa.grad.float(), lora_grads))
+ (ya, ga, la), (yb, gb, lb) = results
+ assert len(la) == len(lb) == 6
+ if rows > 64:
+ assert torch.equal(ya, yb) and torch.equal(ga, gb)
+ assert all(torch.equal(a, b) for a, b in zip(la, lb))
+ else:
+ rel = lambda a, b: ((a - b).abs().max() / b.abs().max().clamp_min(1e-6)).item() # noqa: E731
+ assert rel(ya, yb) < 2e-2 and rel(ga, gb) < 2e-2
+ assert all(rel(a, b) < 3e-2 for a, b in zip(la, lb))
+
+
[email protected](not has_real_cuda(), reason = "needs a CUDA device")
[email protected]("rows", [1, 3, 64, 65, 300])
[email protected]("bias", [False, True])
+def test_packed_linear_forward_backward_close_to_the_dense_decode_on_cuda(rows, bias):
+ module = _filled(96, 160, bias = bias).cuda()
+ module.weight_scale.data.clamp_(118, 126)
+ dense = module.dequantize_weight()
+ x = torch.randn(rows, 160, device = "cuda", generator = torch.Generator("cuda").manual_seed(1)).to(
+ torch.bfloat16
+ )
+ xa, xb = x.clone().requires_grad_(), x.clone().requires_grad_()
+ ya = module(xa)
+ yb = torch.nn.functional.linear(
+ xb, dense, None if module.bias is None else module.bias.to(torch.bfloat16)
+ )
+ go = torch.randn_like(ya)
+ ya.backward(go)
+ yb.backward(go)
+ tol = dict(atol = 1e-1, rtol = 2e-2) if rows <= 64 else dict(atol = 0, rtol = 0)
+ torch.testing.assert_close(ya.float(), yb.float(), **tol)
+ torch.testing.assert_close(xa.grad.float(), xb.grad.float(), **tol)
+ with torch.no_grad():
+ torch.testing.assert_close(module(x).float(), ya.float(), atol = 0, rtol = 0)
+
+
+def _lora_pair(bias = False, scale_range = None):
+ peft = pytest.importorskip("peft")
+ packed = _filled(32, 64, bias = bias)
+ if scale_range is not None:
+ packed.weight_scale.data.clamp_(*scale_range)
+ dense = nn.Linear(64, 32, bias = bias, dtype = torch.bfloat16)
+ dense.weight.data.copy_(packed.dequantize_weight())
+ if bias:
+ dense.bias.data.copy_(packed.bias.data)
+ models = []
+ for base in (packed, dense):
+ holder = nn.Sequential(base)
+ model = peft.get_peft_model(
+ holder, peft.LoraConfig(r = 4, lora_alpha = 8, target_modules = ["0"])
+ )
+ g = torch.Generator().manual_seed(3)
+ with torch.no_grad():
+ for name, param in sorted(model.named_parameters()):
+ if "lora_" in name:
+ param.copy_((torch.randn(param.shape, generator = g) * 0.1).to(param.dtype))
+ models.append(model)
+ return models
+
+
[email protected]("bias", [False, True])
+def test_peft_lora_on_a_packed_linear_matches_the_dense_decode(bias):
+ packed_model, dense_model = _lora_pair(bias)
+ x = torch.randn(3, 64, dtype = torch.bfloat16)
+ xa, xb = x.clone().requires_grad_(), x.clone().requires_grad_()
+ ya, yb = packed_model(xa), dense_model(xb)
+ assert torch.equal(ya, yb)
+ ya.float().sum().backward()
+ yb.float().sum().backward()
+ assert torch.equal(xa.grad, xb.grad)
+ grads = lambda m: {n: p.grad for n, p in m.named_parameters() if "lora_" in n} # noqa: E731
+ ga, gb = grads(packed_model), grads(dense_model)
+ assert ga.keys() == gb.keys() and all(torch.equal(ga[n], gb[n]) for n in ga)
+
+
+def test_peft_merge_densifies_exactly_and_unmerge_restores_the_packed_bytes():
+ packed_model, dense_model = _lora_pair(scale_range = (118, 134))
+ x = torch.randn(3, 64, generator = torch.Generator().manual_seed(0)).to(torch.bfloat16)
+ base = packed_model.base_model.model[0].base_layer
+ packed_bytes, scale = base.weight_packed, base.weight_scale
+ with torch.no_grad():
+ with_lora = packed_model(x)
+ packed_model.merge_adapter()
+ dense_model.merge_adapter()
+ merged_base = packed_model.base_model.model[0].base_layer
+ # The delta lands in a real weight (a write into a fresh decode would be lost).
+ assert type(merged_base) is nn.Linear and "weight_packed" not in merged_base._parameters
+ assert torch.equal(merged_base.weight, dense_model.base_model.model[0].base_layer.weight)
+ merged = packed_model(x)
+ packed_model.unmerge_adapter()
+ restored = packed_model.base_model.model[0].base_layer
+ assert type(restored) is Mxfp4PackedLinear
+ assert restored.weight_packed is packed_bytes and restored.weight_scale is scale
+ assert "weight" not in restored._parameters
+ assert torch.equal(packed_model(x), with_lora)
+ assert not torch.equal(merged, packed_model.base_model.model[0].base_layer(x))
+ torch.testing.assert_close(merged.float(), with_lora.float(), atol = 2e-2, rtol = 2e-2)
+ unloaded = packed_model.merge_and_unload()
+ assert type(unloaded[0]) is nn.Linear
+ assert torch.equal(unloaded[0].weight, dense_model.base_model.model[0].base_layer.weight)
+
+
+def _write_tiny_mxfp4_llama(root):
+ from safetensors.torch import save_file
+ from transformers import LlamaConfig, LlamaForCausalLM
+ from compressed_tensors.compressors import BaseCompressor
+ from compressed_tensors.quantization import QuantizationConfig
+
+ torch.manual_seed(0)
+ config = LlamaConfig(
+ hidden_size = 64,
+ num_hidden_layers = 2,
+ num_attention_heads = 4,
+ num_key_value_heads = 2,
+ intermediate_size = 128,
+ vocab_size = 32000,
+ max_position_embeddings = 128,
+ tie_word_embeddings = False,
+ )
+ model = LlamaForCausalLM(config).to(torch.bfloat16)
+ quant = {
+ "quant_method": "compressed-tensors",
+ "format": "mxfp4-pack-quantized",
+ "quantization_status": "compressed",
+ "ignore": ["lm_head"],
+ "config_groups": {
+ "group_0": {
+ "targets": ["Linear"],
+ "weights": {
+ "num_bits": 4,
+ "type": "float",
+ "strategy": "group",
+ "group_size": 32,
+ "symmetric": True,
+ "scale_dtype": "torch.uint8",
+ "dynamic": False,
+ "observer": "minmax",
+ "observer_kwargs": {},
+ "actorder": None,
+ "block_structure": None,
+ },
+ "input_activations": None,
+ "output_activations": None,
+ }
+ },
+ }
+ scheme = list(QuantizationConfig.model_validate(quant).config_groups.values())[0]
+ comp = BaseCompressor.get_value_from_registry("mxfp4-pack-quantized")
+ linears = {n for n, m in model.named_modules() if isinstance(m, nn.Linear)}
+ packed, plain = {}, {}
+ for k, w in model.state_dict().items():
+ mod = k[: -len(".weight")] if k.endswith(".weight") else None
+ if mod is None or mod not in linears or mod == "lm_head":
+ packed[k] = plain[k] = w.contiguous()
+ continue
+ out_f, in_f = w.shape
+ amax = w.float().reshape(out_f, in_f // 32, 32).abs().amax(-1).clamp_min(1e-8)
+ exp = (torch.ceil(torch.log2(amax / 6.0)) + 127).clamp(1, 254).to(torch.uint8)
+ state = {"weight": w.float(), "weight_scale": 2.0 ** (exp.float() - 127)}
+ out = comp.compress(state, scheme)
+ out["weight_scale"] = exp
+ for pk, pv in out.items():
+ if pk == "weight_shape":
+ continue
+ packed[mod + "." + pk] = pv.contiguous()
+ plain[k] = (
+ comp.decompress(
+ {
+ "weight_packed": out["weight_packed"],
+ "weight_scale": exp,
+ "weight_shape": torch.tensor([out_f, in_f]),
+ },
+ scheme,
+ )["weight"]
+ .to(torch.bfloat16)
+ .contiguous()
+ )
+ packed_dir, bf16_dir = os.path.join(root, "packed"), os.path.join(root, "bf16")
+ os.makedirs(packed_dir)
+ os.makedirs(bf16_dir)
+ save_file(packed, os.path.join(packed_dir, "model.safetensors"), metadata = {"format": "pt"})
+ save_file(plain, os.path.join(bf16_dir, "model.safetensors"), metadata = {"format": "pt"})
+ cfg = config.to_dict()
+ json.dump(cfg, open(os.path.join(bf16_dir, "config.json"), "w"))
+ cfg["quantization_config"] = quant
+ json.dump(cfg, open(os.path.join(packed_dir, "config.json"), "w"))
+ return packed_dir, bf16_dir
+
+
+def _add_tokenizer(path, root):
+ from transformers import AutoTokenizer
+
+ tok_dir = os.path.join(root, "tok")
+ if not os.path.isdir(tok_dir):
+ AutoTokenizer.from_pretrained("hf-internal-testing/llama-tokenizer").save_pretrained(
+ tok_dir
+ )
+ for f in os.listdir(tok_dir):
+ if not os.path.exists(os.path.join(path, f)):
+ shutil.copy(os.path.join(tok_dir, f), os.path.join(path, f))
+
+
+def _lora_losses(model, steps = 3):
+ from unsloth import FastLanguageModel
+
+ model = FastLanguageModel.get_peft_model(
+ model,
+ r = 4,
+ lora_alpha = 8,
+ random_state = 3407,
+ target_modules = [
+ "q_proj",
+ "k_proj",
+ "v_proj",
+ "o_proj",
+ "gate_proj",
+ "up_proj",
+ "down_proj",
+ ],
+ )
+ model.train()
+ opt = torch.optim.AdamW([p for p in model.parameters() if p.requires_grad], lr = 1e-2)
+ torch.manual_seed(1)
+ ids = torch.randint(0, 256, (2, 24), device = "cuda:0")
+ losses = []
+ for _ in range(steps):
+ loss = model(input_ids = ids, labels = ids).loss
+ loss.backward()
+ opt.step()
+ opt.zero_grad(set_to_none = True)
+ losses.append(loss.item())
+ return losses
+
+
+needs_gpu_loader_any = [
+ pytest.mark.skipif(not has_real_cuda(), reason = "needs a CUDA device"),
+ pytest.mark.skipif(
+ not HAS_CT
+ or not hasattr(__import__("transformers"), "__version__")
+ or int(__import__("transformers").__version__.split(".")[0]) < 5,
+ reason = "needs compressed-tensors and transformers 5",
+ ),
+]
+needs_gpu_loader = [
+ pytest.mark.skipif(not has_real_cuda(), reason = "needs a CUDA device"),
+ pytest.mark.skipif(
+ not (HAS_CT and HAS_CONVERTERS),
+ reason = "needs compressed-tensors and the transformers 5 loader",
+ ),
+]
+
+
+def _apply(marks):
+ def wrap(fn):
+ for m in marks:
+ fn = m(fn)
+ return fn
+
+ return wrap
+
+
+@needs_zoo_packed_save
+@_apply(needs_gpu_loader_any)
[email protected]("load_in_4bit", [True, False])
+def test_mxfp4_checkpoint_stays_packed_and_matches_its_bf16_decode(
+ load_in_4bit, tmp_path, monkeypatch
+):
+ import unsloth.models.llama as llama_module
+ from unsloth import FastLanguageModel
+
+ packed_dir, bf16_dir = _write_tiny_mxfp4_llama(str(tmp_path))
+ for d in (packed_dir, bf16_dir):
+ _add_tokenizer(d, str(tmp_path))
+ kw = dict(max_seq_length = 64, dtype = torch.bfloat16)
+ model_a, _ = FastLanguageModel.from_pretrained(packed_dir, load_in_4bit = load_in_4bit, **kw)
+ kept = [n for n, m in model_a.named_modules() if isinstance(m, Mxfp4PackedLinear)]
+ assert len(kept) == 2 * 7, kept
+ assert all(
+ p.dtype == torch.uint8 for n, p in model_a.named_parameters() if "weight_packed" in n
+ )
+ model_b, _ = FastLanguageModel.from_pretrained(bf16_dir, load_in_4bit = False, **kw)
+ ids = torch.randint(0, 256, (1, 16), device = "cuda:0")
+ import unsloth.models.mxfp4_compressed_linear as mcl
+
+ with torch.no_grad():
+ # 16 rows run the fused MXFP4 GEMM: bf16-rounding-level; the decode + cuBLAS route is bit-exact.
+ fused = model_a(input_ids = ids).logits
+ want = model_b(input_ids = ids).logits
+ torch.testing.assert_close(fused.float(), want.float(), atol = 5e-2, rtol = 2e-2)
+ monkeypatch.setattr(mcl, "_FUSED_MAX_ROWS", 0)
+ assert torch.equal(model_a(input_ids = ids).logits, want)
+ losses_a = _lora_losses(model_a)
+ from unsloth.kernels import apply_lora_o, apply_lora_qkv
+
+ # The fused LoRA kernels take packed bases: weight_packed + a decoder, never a held 16-bit weight.
+ for layer in model_a.model.layers:
+ assert "_unsloth_forward" in layer.mlp.__dict__ or "forward" in layer.mlp.__dict__
+ assert getattr(layer.self_attn, "apply_qkv", None) is apply_lora_qkv
+ assert getattr(layer.self_attn, "apply_o", None) is apply_lora_o
+ assert losses_a == _lora_losses(model_b)
+
+
+@_apply(needs_gpu_loader)
+def test_keep_packed_off_restores_the_bitsandbytes_route(tmp_path, monkeypatch):
+ import bitsandbytes as bnb
+ from unsloth import FastLanguageModel
+
+ monkeypatch.setenv("UNSLOTH_MXFP4_KEEP_PACKED", "0")
+ packed_dir, _ = _write_tiny_mxfp4_llama(str(tmp_path))
+ _add_tokenizer(packed_dir, str(tmp_path))
+ model, _ = FastLanguageModel.from_pretrained(
+ packed_dir, max_seq_length = 64, dtype = torch.bfloat16, load_in_4bit = True
+ )
+ assert not any(isinstance(m, Mxfp4PackedLinear) for m in model.modules())
+ assert sum(isinstance(m, bnb.nn.Linear4bit) for m in model.modules()) == 2 * 7
+
+
+def _plain_logits(path, ids):
+ from transformers import AutoModelForCausalLM
+ model = AutoModelForCausalLM.from_pretrained(path, dtype = torch.bfloat16, device_map = {"": 0})
+ with torch.no_grad():
+ return model(input_ids = ids).logits
+
+
+@needs_zoo_packed_save
+@_apply(needs_gpu_loader_any)
+def test_full_and_merged_saves_reload_in_plain_transformers(tmp_path, monkeypatch):
+ from safetensors import safe_open
+ from unsloth import FastLanguageModel
+
+ packed_dir, bf16_dir = _write_tiny_mxfp4_llama(str(tmp_path))
+ _add_tokenizer(packed_dir, str(tmp_path))
+ model, tokenizer = FastLanguageModel.from_pretrained(
+ packed_dir, max_seq_length = 64, dtype = torch.bfloat16, load_in_4bit = False
+ )
+ ids = torch.randint(0, 256, (1, 16), device = "cuda:0")
+ with torch.no_grad():
+ base_logits = model(input_ids = ids).logits
+ full = str(tmp_path / "full")
+ model.save_pretrained(full)
+ assert sum(isinstance(m, Mxfp4PackedLinear) for m in model.modules()) == 2 * 7
+ with safe_open(os.path.join(full, "model.safetensors"), "pt") as f:
+ keys = list(f.keys())
+ assert not any("weight_packed" in k or "weight_scale" in k for k in keys)
+ assert "quantization_config" not in json.load(open(os.path.join(full, "config.json")))
+ assert torch.equal(_plain_logits(full, ids), _plain_logits(bf16_dir, ids))
+
+ model = FastLanguageModel.get_peft_model(
+ model,
+ r = 4,
+ lora_alpha = 8,
+ random_state = 3407,
+ target_modules = ["q_proj", "v_proj", "o_proj", "gate_proj", "up_proj", "down_proj"],
+ )
+ with torch.no_grad():
+ for name, param in model.named_parameters():
+ if "lora_B" in name:
+ param.normal_(0, 0.05)
+ merged_dir = str(tmp_path / "merged")
+ model.save_pretrained_merged(merged_dir, tokenizer, save_method = "merged_16bit")
+ unloaded = model.merge_and_unload()
+ assert [n for n, m in unloaded.named_modules() if isinstance(m, Mxfp4PackedLinear)] == [
+ f"model.layers.{i}.self_attn.k_proj" for i in range(2)
+ ]
+ with torch.no_grad():
+ unloaded_logits = unloaded(input_ids = ids).logits
+ assert not torch.equal(unloaded_logits, base_logits)
+ with safe_open(os.path.join(merged_dir, "model.safetensors"), "pt") as f:
+ assert not any("weight_packed" in k or "weight_scale" in k for k in f.keys())
+ unloaded_dir = str(tmp_path / "unloaded")
+ unloaded.save_pretrained(unloaded_dir)
+ merged_logits, unloaded_reload = (
+ _plain_logits(merged_dir, ids),
+ _plain_logits(unloaded_dir, ids),
+ )
+ torch.testing.assert_close(merged_logits, unloaded_reload, atol = 2e-2, rtol = 2e-2)
+ torch.testing.assert_close(unloaded_reload, unloaded_logits, atol = 2e-2, rtol = 2e-2)
+ assert not torch.equal(merged_logits, _plain_logits(full, ids))
+
+
+@needs_zoo_packed_save
+@_apply(needs_gpu_loader_any)
+def test_full_finetuning_keeps_the_stock_compressed_tensors_route(tmp_path, monkeypatch):
+ from unsloth.models.mxfp4_compressed_linear import install_compressed_tensors_keep_packed
+ from transformers import AutoModelForCausalLM
+
+ packed_dir, _ = _write_tiny_mxfp4_llama(str(tmp_path))
+ assert install_compressed_tensors_keep_packed()
+ monkeypatch.setenv("UNSLOTH_ENABLE_FULL_FINETUNING", "1")
+ model = AutoModelForCausalLM.from_pretrained(packed_dir, dtype = torch.bfloat16)
+ assert not any(isinstance(m, Mxfp4PackedLinear) for m in model.modules())
+ monkeypatch.setenv("UNSLOTH_ENABLE_FULL_FINETUNING", "0")
+ model = AutoModelForCausalLM.from_pretrained(packed_dir, dtype = torch.bfloat16)
+ assert sum(isinstance(m, Mxfp4PackedLinear) for m in model.modules()) == 2 * 7
+
+
+def _decompress_requests():
+ """The ways this transformers asks compressed-tensors to decompress at load."""
+ try:
+ import inspect
+ from transformers import CompressedTensorsConfig
+ except Exception:
+ return []
+ params = inspect.signature(CompressedTensorsConfig).parameters
+ return [{k: v} for k, v in (("run_compressed", False), ("dequantize", True)) if k in params]
+
+
[email protected](not HAS_CT, reason = "needs compressed-tensors")
[email protected]("request_kwargs", _decompress_requests(), ids = lambda kw: next(iter(kw)))
+def test_an_explicit_decompress_request_keeps_the_stock_route(request_kwargs, tmp_path):
+ from transformers import AutoModelForCausalLM, CompressedTensorsConfig
+ from unsloth.models.mxfp4_compressed_linear import install_compressed_tensors_keep_packed
+
+ packed_dir, bf16_dir = _write_tiny_mxfp4_llama(str(tmp_path))
+ assert install_compressed_tensors_keep_packed()
+ # On the GPU when there is one: an earlier FastLanguageModel load patches Llama's forward.
+ device = "cuda:0" if has_real_cuda() else "cpu"
+ model = AutoModelForCausalLM.from_pretrained(
+ packed_dir,
+ dtype = torch.bfloat16,
+ device_map = {"": device},
+ quantization_config = CompressedTensorsConfig(**request_kwargs),
+ )
+ assert not any(isinstance(m, Mxfp4PackedLinear) for m in model.modules())
+ reference = AutoModelForCausalLM.from_pretrained(
+ bf16_dir, dtype = torch.bfloat16, device_map = {"": device}
+ )
+ ids = torch.randint(0, 256, (1, 12), device = device)
+ with torch.no_grad():
+ assert torch.equal(model(input_ids = ids).logits, reference(input_ids = ids).logits)
+
+
[email protected]("cast", [torch.float16, torch.float32])
+def test_a_dtype_cast_reaches_the_merge_and_unmerge(cast):
+ packed_model, dense_model = _lora_pair(scale_range = (118, 134)) # inside fp16's range
+ packed_model.to(cast)
+ dense_model.to(cast)
+ base = packed_model.base_model.model[0].base_layer
+ assert base.compute_dtype == cast and base.weight.dtype == cast
+ x = torch.randn(3, 64, dtype = cast)
+ with torch.no_grad():
+ packed_model.merge_adapter()
+ dense_model.merge_adapter()
+ assert packed_model.base_model.model[0].base_layer.weight.dtype == cast
+ assert torch.equal(packed_model(x), dense_model(x))
+ # Cast while merged, then unmerge: the packed module decodes in the model's new dtype.
+ packed_model.to(torch.bfloat16)
+ packed_model.unmerge_adapter()
+ restored = packed_model.base_model.model[0].base_layer
+ assert type(restored) is Mxfp4PackedLinear and restored.compute_dtype == torch.bfloat16
+ packed_model.merge_adapter()
+ assert packed_model(x.to(torch.bfloat16)).dtype == torch.bfloat16
+
+
+@needs_zoo_packed_save
+ not (HAS_CT and HAS_CONVERTERS), reason = "needs compressed-tensors and the transformers 5 loader"
+)
+def test_the_sixteen_bit_route_decodes_in_the_load_dtype(tmp_path):
+ peft = pytest.importorskip("peft")
+ from transformers import AutoModelForCausalLM
+ from unsloth.models.mxfp4_compressed_linear import install_compressed_tensors_keep_packed
+
+ packed_dir, _ = _write_tiny_mxfp4_llama(str(tmp_path))
+ assert install_compressed_tensors_keep_packed()
+ device = "cuda:0" if has_real_cuda() else "cpu"
+ model = AutoModelForCausalLM.from_pretrained(
+ packed_dir, dtype = torch.float16, device_map = {"": device}
+ )
+ packed = [m for m in model.modules() if isinstance(m, Mxfp4PackedLinear)]
+ assert len(packed) == 2 * 7
+ assert {m.compute_dtype for m in packed} == {torch.float16}
+ assert {m.weight.dtype for m in packed} == {torch.float16}
+ assert model.model.layers[0].input_layernorm.weight.dtype == torch.float16
+ model = peft.get_peft_model(model, peft.LoraConfig(r = 2, target_modules = ["q_proj"]))
+ merged = model.merge_and_unload()
+ with torch.no_grad():
+ assert merged(input_ids = torch.tensor([[1, 2, 3, 4]], device = device)).logits.isfinite().all()
+
+
[email protected](not HAS_CT, reason = "needs compressed-tensors")
+def test_adoption_declines_a_scheme_that_also_quantizes_activations():
+ from unsloth.models.mxfp4_compressed_linear import is_mxfp4_scheme
+
+ activations = {
+ "num_bits": 8,
+ "type": "int",
+ "strategy": "token",
+ "dynamic": True,
+ "symmetric": True,
+ }
+ groups = {
+ "group_0": {
+ "targets": ["Linear"],
+ "weights": _MXFP4_WEIGHTS,
+ "input_activations": activations,
+ }
+ }
+ model = _ct_compressed_model(groups = groups)
+ assert not is_mxfp4_scheme(model.a.quantization_scheme, "mxfp4-pack-quantized")
+ reference = copy.deepcopy(model)
+ assert adopt_compressed_mxfp4_modules(model, dtype = torch.bfloat16) == 0
+ assert type(model.a) is nn.Linear and hasattr(model, "ct_decompress_hook")
+ x = torch.randn(3, 64, dtype = torch.bfloat16)
+ with torch.no_grad():
+ assert torch.equal(model(x), reference(x))
+
+
[email protected](not HAS_CT, reason = "needs compressed-tensors")
+def test_adoption_declines_when_another_compressed_format_needs_the_hook():
+ fp8 = {
+ "num_bits": 8,
+ "type": "float",
+ "strategy": "channel",
+ "symmetric": True,
+ "dynamic": False,
+ }
+ groups = {
+ "group_0": {
+ "targets": ["re:^a$", "re:^b$"],
+ "weights": _MXFP4_WEIGHTS,
+ "format": "mxfp4-pack-quantized",
+ },
+ "group_1": {"targets": ["re:^latent$"], "weights": fp8, "format": "float-quantized"},
+ }
+ model = _ct_compressed_model(groups = groups)
+ assert model.latent.weight.dtype == torch.float8_e4m3fn
+ reference = copy.deepcopy(model)
+ assert adopt_compressed_mxfp4_modules(model, dtype = torch.bfloat16) == 0
+ assert type(model.a) is nn.Linear and hasattr(model, "ct_decompress_hook")
+ x = torch.randn(3, 64, dtype = torch.bfloat16)
+ with torch.no_grad():
+ assert torch.equal(model(x), reference(x))
+
+
[email protected]("init", ["pissa", "olora"])
+def test_initialisers_that_rewrite_the_base_weight_refuse_a_packed_base(init):
+ peft = pytest.importorskip("peft")
+ holder = nn.Sequential(_filled(32, 64))
+ with pytest.raises(NotImplementedError, match = "packed in MXFP4"):
+ peft.get_peft_model(
+ holder, peft.LoraConfig(r = 4, target_modules = ["0"], init_lora_weights = init)
+ )
+ peft.get_peft_model(nn.Sequential(_filled(32, 64)), peft.LoraConfig(r = 4, target_modules = ["0"]))
+ dense = nn.Sequential(nn.Linear(64, 32, bias = False))
+ peft.get_peft_model(dense, peft.LoraConfig(r = 4, target_modules = ["0"], init_lora_weights = init))
+
+
+@_apply(needs_gpu_loader_any)
+def test_the_sixteen_bit_route_declines_without_the_zoo_full_save_support(tmp_path, monkeypatch):
+ from transformers import AutoModelForCausalLM
+ from unsloth_zoo.temporary_patches import mxfp4 as zoo_mxfp4
+ from unsloth.models.mxfp4_compressed_linear import install_compressed_tensors_keep_packed
+
+ packed_dir, _ = _write_tiny_mxfp4_llama(str(tmp_path))
+ assert install_compressed_tensors_keep_packed()
+ monkeypatch.delattr(zoo_mxfp4, "_densified_module_names", raising = False)
+ model = AutoModelForCausalLM.from_pretrained(
+ packed_dir, dtype = torch.bfloat16, device_map = {"": 0}
+ )
+ assert not any(isinstance(m, Mxfp4PackedLinear) for m in model.modules())
+
+
+@needs_zoo_packed_save
+@_apply(needs_gpu_loader)
+def test_a_partly_merged_bitsandbytes_route_model_saves_and_reloads(tmp_path):
+ from transformers import AutoModelForCausalLM
+ from unsloth import FastLanguageModel
+
+ packed_dir, _ = _write_tiny_mxfp4_llama(str(tmp_path))
+ _add_tokenizer(packed_dir, str(tmp_path))
+ model, _ = FastLanguageModel.from_pretrained(
+ packed_dir, max_seq_length = 64, dtype = torch.bfloat16, load_in_4bit = True
+ )
+ model = FastLanguageModel.get_peft_model(model, r = 4, lora_alpha = 8, target_modules = ["q_proj"])
+ with torch.no_grad():
+ for name, param in model.named_parameters():
+ if "lora_B" in name:
+ param.normal_(0, 0.05)
+ unloaded = model.merge_and_unload()
+ ids = torch.randint(0, 256, (1, 16), device = "cuda:0")
+ with torch.no_grad():
+ want = unloaded(input_ids = ids).logits
+ out = str(tmp_path / "unloaded")
+ unloaded.save_pretrained(out)
+ reloaded = AutoModelForCausalLM.from_pretrained(out, dtype = torch.bfloat16, device_map = {"": 0})
+ attn = reloaded.model.layers[0].self_attn
+ assert type(attn.q_proj) is nn.Linear and type(attn.k_proj) is nn.Linear
+ with torch.no_grad():
+ got = reloaded(input_ids = ids).logits
+ torch.testing.assert_close(got, want, atol = 2e-2, rtol = 2e-2)
+
+
+def test_merge_and_unmerge_under_an_accelerate_hook():
+ pytest.importorskip("accelerate")
+ from accelerate.hooks import AlignDevicesHook, add_hook_to_module
+
+ packed_model, dense_model = _lora_pair(scale_range = (118, 134))
+ add_hook_to_module(
+ packed_model.base_model.model[0].base_layer, AlignDevicesHook(io_same_device = True)
+ )
+ x = torch.randn(3, 64, generator = torch.Generator().manual_seed(0)).to(torch.bfloat16)
+ with torch.no_grad():
+ with_lora = packed_model(x)
+ packed_model.merge_adapter()
+ dense_model.merge_adapter()
+ assert torch.equal(packed_model(x), dense_model(x))
+ packed_model.unmerge_adapter()
+ assert torch.equal(packed_model(x), with_lora)
+
+
+@needs_zoo_packed_save
+@_apply(needs_gpu_loader_any)
+def test_the_sixteen_bit_route_plans_only_mxfp4_checkpoints(tmp_path, monkeypatch):
+ import importlib.util
+ import unsloth.models.compressed_tensors_bnb as ctb
+ from transformers import AutoModelForCausalLM
+ from unsloth.models.mxfp4_compressed_linear import install_compressed_tensors_keep_packed
+
+ path = os.path.join(
+ os.path.dirname(os.path.abspath(__file__)), "test_compressed_tensors_bnb.py"
+ )
+ spec = importlib.util.spec_from_file_location("_k3s_ct_bnb_tests", path)
+ ct_bnb_tests = importlib.util.module_from_spec(spec)
+ spec.loader.exec_module(ct_bnb_tests)
+
+ calls = []
+ real = ctb._checkpoint_keys
+ monkeypatch.setattr(ctb, "_checkpoint_keys", lambda files: calls.append(files) or real(files))
+ assert install_compressed_tensors_keep_packed()
+ int4_dir, _ = ct_bnb_tests._write_tiny_packed_llama(str(tmp_path / "int4"))
+ AutoModelForCausalLM.from_pretrained(int4_dir, dtype = torch.bfloat16, device_map = {"": 0})
+ assert calls == []
+ mxfp4_dir, _ = _write_tiny_mxfp4_llama(str(tmp_path / "mxfp4"))
+ model = AutoModelForCausalLM.from_pretrained(
+ mxfp4_dir, dtype = torch.bfloat16, device_map = {"": 0}
+ )
+ assert (
+ len(calls) == 1 and sum(isinstance(m, Mxfp4PackedLinear) for m in model.modules()) == 2 * 7
+ )
+
+
[email protected]("spelling", ["compressed-tensors", "compressed_tensors", "sparseml"])
+def test_every_compressed_tensors_spelling_installs_the_keep_packed_hook(spelling, monkeypatch):
+ from types import SimpleNamespace
+ from unsloth.models import loader_utils, mxfp4_compressed_linear
+
+ calls = []
+ monkeypatch.setattr(
+ mxfp4_compressed_linear, "install_compressed_tensors_keep_packed", lambda: calls.append(1)
+ )
+ config = SimpleNamespace(
+ quantization_config = {"quant_method": spelling, "format": "mxfp4-pack-quantized"}
+ )
+ loader_utils.check_and_disable_bitsandbytes_loading(
+ config,
+ load_in_4bit = False,
+ verbose = False,
+ requantize_packed = False,
+ )
+ assert calls == [1]
diff --git a/tests/test_remote_code_model_api.py b/tests/test_remote_code_model_api.py
new file mode 100644
index 00000000000..1050b444e5f
--- /dev/null
+++ b/tests/test_remote_code_model_api.py
@@ -0,0 +1,148 @@
+# SPDX-License-Identifier: AGPL-3.0-only
+# Copyright 2023-present Daniel 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/>.
+
+"""Transformers 4.x remote code (Kimi-K3) against the transformers 5 model API, offline on CPU."""
+
+import inspect
+import linecache
+import sys
+import types
+
+import torch
+
+import unsloth # noqa: F401
+from transformers import PreTrainedModel
+
+_SRC = """
+import torch
+from torch import nn
+from transformers import PretrainedConfig, PreTrainedModel
+from transformers.utils.generic import OutputRecorder
+
+class TinyRemoteConfig(PretrainedConfig):
+ model_type = "tiny_remote_k3"
+ def __init__(self, vocab_size=32, hidden_size=8, tie_word_embeddings=True, **kwargs):
+ self.vocab_size = vocab_size; self.hidden_size = hidden_size
+ super().__init__(tie_word_embeddings=tie_word_embeddings, **kwargs)
+
+class TinyRemoteModel(nn.Module):
+ def __init__(self, config):
+ super().__init__()
+ self.embed_tokens = nn.Embedding(config.vocab_size, config.hidden_size)
+
+class TinyRemoteForCausalLM(PreTrainedModel):
+ config_class = TinyRemoteConfig
+ _tied_weights_keys = ["lm_head.weight"]
+ tie_calls = 0
+ def __init__(self, config):
+ super().__init__(config)
+ self.model = TinyRemoteModel(config)
+ self.lm_head = nn.Linear(config.hidden_size, config.vocab_size, bias=False)
+ self.post_init()
+ def get_input_embeddings(self):
+ return self.model.embed_tokens
+ def get_output_embeddings(self):
+ return self.lm_head
+ def tie_weights(self):
+ type(self).tie_calls += 1
+ if self.config.tie_word_embeddings:
+ self.lm_head.weight = self.model.embed_tokens.weight
+ def forward(self, input_ids):
+ return self.lm_head(self.model.embed_tokens(input_ids))
+"""
+
+
+def _remote_module(name):
+ filename = f"<{name}>"
+ linecache.cache[filename] = (len(_SRC), None, _SRC.splitlines(True), filename)
+ mod = types.ModuleType(name)
+ sys.modules[name] = mod
+ exec(compile(_SRC, filename, "exec"), mod.__dict__)
+ for cls in (mod.TinyRemoteConfig, mod.TinyRemoteModel, mod.TinyRemoteForCausalLM):
+ cls.__module__ = name
+ return mod
+
+
+def _is_transformers5():
+ return "recompute_mapping" in inspect.signature(PreTrainedModel.tie_weights).parameters
+
+
+def test_output_recorder_imports_from_the_4x_location():
+ from transformers.utils.generic import OutputRecorder # noqa: F401
+ mod = _remote_module("transformers_modules.tiny_remote_a.modeling_tiny")
+ assert mod.OutputRecorder is not None
+
+
+def test_a_4x_remote_model_builds_and_ties_on_this_transformers():
+ mod = _remote_module("transformers_modules.tiny_remote_b.modeling_tiny")
+ model = mod.TinyRemoteForCausalLM(mod.TinyRemoteConfig())
+ assert model.lm_head.weight is model.model.embed_tokens.weight
+ # transformers 5 calls tie_weights with keywords the 4.x override does not take.
+ kwargs = {"recompute_mapping": False} if _is_transformers5() else {}
+ model.tie_weights(**kwargs)
+ assert model.lm_head.weight is model.model.embed_tokens.weight
+ assert mod.TinyRemoteForCausalLM.tie_calls >= 1
+ if _is_transformers5():
+ assert model._tied_weights_keys == {"lm_head.weight": "model.embed_tokens.weight"}
+ else:
+ # 4.x reads the list itself and must keep it.
+ assert model._tied_weights_keys == ["lm_head.weight"]
+ ids = torch.tensor([[1, 2, 3]])
+ assert model(ids).shape == (1, 3, 32)
+
+
+def test_an_untied_remote_model_keeps_its_own_head():
+ mod = _remote_module("transformers_modules.tiny_remote_c.modeling_tiny")
+ model = mod.TinyRemoteForCausalLM(mod.TinyRemoteConfig(tie_word_embeddings = False))
+ assert model.lm_head.weight is not model.model.embed_tokens.weight
+
+
+def test_native_classes_are_left_alone():
+ """Only `transformers_modules` classes get the tie_weights wrapper or the mapping."""
+ from transformers import LlamaConfig, LlamaForCausalLM
+
+ cfg = LlamaConfig(
+ hidden_size = 16,
+ intermediate_size = 32,
+ num_hidden_layers = 1,
+ num_attention_heads = 2,
+ num_key_value_heads = 2,
+ vocab_size = 32,
+ )
+ before = LlamaForCausalLM.__dict__.get("tie_weights")
+ keys = LlamaForCausalLM._tied_weights_keys
+ LlamaForCausalLM(cfg)
+ assert LlamaForCausalLM.__dict__.get("tie_weights") is before
+ assert LlamaForCausalLM._tied_weights_keys == keys
+
+
+def test_only_the_output_embedding_is_mapped_onto_the_input_embedding():
+ if not _is_transformers5():
+ return
+ mod = _remote_module("transformers_modules.tiny_remote_d.modeling_tiny")
+
+ class SharedProjection(mod.TinyRemoteForCausalLM):
+ _tied_weights_keys = ["lm_head.weight", "proj.weight"]
+
+ def __init__(self, config):
+ PreTrainedModel.__init__(self, config)
+ self.model = mod.TinyRemoteModel(config)
+ self.lm_head = torch.nn.Linear(config.hidden_size, config.vocab_size, bias = False)
+ self.proj = torch.nn.Linear(config.hidden_size, config.hidden_size, bias = False)
+ self.post_init()
+
+ SharedProjection.__module__ = mod.__name__
+ model = SharedProjection(mod.TinyRemoteConfig())
+ assert model._tied_weights_keys == {"lm_head.weight": "model.embed_tokens.weight"}
+ assert model.proj.weight is not model.model.embed_tokens.weight
+ assert model.lm_head.weight is model.model.embed_tokens.weight
diff --git a/tests/test_remote_moe_shims.py b/tests/test_remote_moe_shims.py
index 2fad9243639..af773d456f1 100644
--- a/tests/test_remote_moe_shims.py
+++ b/tests/test_remote_moe_shims.py
@@ -394,6 +394,52 @@ def test_an_eval_first_training_capable_remote_moe_is_left_alone():
sys.modules.pop(module.__name__, None)
+ "training_branch, shimmed",
+ [
+ ('raise NotImplementedError("Training mode is not supported")', True),
+ ("pass", True),
+ ("y = self.experts[0](hidden_states)", False),
+ ],
+)
+def test_a_training_branch_that_only_raises_is_not_a_dispatch(training_branch, shimmed):
+ """Kimi-K3's port: `if not self.training: moe_infer(...) else: raise ...` is inference-only."""
+ import sys, textwrap, types
+ from unsloth.models.remote_moe_shims import is_remote_deepseek_moe
+
+ module = types.ModuleType("transformers_modules.raise_only.modeling_kimi")
+ source = textwrap.dedent(f"""
+ class RaiseOnlyMoE(nn.Module):
+ def __init__(self):
+ super().__init__()
+ self.experts = nn.ModuleList([nn.Linear(2, 2)])
+ self.gate = nn.Linear(2, 1)
+
+ def forward(self, hidden_states):
+ y = hidden_states
+ if not self.training:
+ y = self.moe_infer(hidden_states)
+ else:
+ {training_branch}
+ return y
+
+ def moe_infer(self, x):
+ return x
+ """)
+ path = os.path.join(tempfile.mkdtemp(dir = os.environ.get("TMPDIR")), "modeling_kimi.py")
+ with open(path, "w") as f:
+ f.write("import torch.nn as nn\n" + source)
+ namespace = {"nn": nn, "__name__": module.__name__}
+ exec(compile("import torch.nn as nn\n" + source, path, "exec"), namespace)
+ RaiseOnlyMoE = namespace["RaiseOnlyMoE"]
+ RaiseOnlyMoE.__module__ = module.__name__
+ sys.modules[module.__name__] = module
+ try:
+ assert is_remote_deepseek_moe(RaiseOnlyMoE()) is shimmed
+ finally:
+ sys.modules.pop(module.__name__, None)
+
+
@pytest.mark.parametrize(
"predicate, trains_in_body",
[
@@ -446,3 +492,132 @@ def test_a_compound_training_predicate_is_recognised(predicate, trains_in_body):
assert not is_remote_deepseek_moe(CompoundMoE())
finally:
sys.modules.pop(module.__name__, None)
+
+
+_KIMI_SRC = """
+import torch
+import torch.nn.functional as F
+from torch import nn
+
+class Cfg:
+ hidden_size = 16; routed_expert_hidden_size = 8; moe_intermediate_size = 12
+ num_experts = 6; num_experts_per_token = 2; num_shared_experts = 1; routed_scaling_factor = 2.0
+
+class KimiRMSNorm(nn.Module):
+ def __init__(self, n, eps=1e-6):
+ super().__init__(); self.weight = nn.Parameter(torch.ones(n)); self.variance_epsilon = eps
+ def forward(self, x):
+ v = x.float().pow(2).mean(-1, keepdim=True)
+ return (self.weight * (x.float() * torch.rsqrt(v + self.variance_epsilon))).to(x.dtype)
+
+class KimiMLP(nn.Module):
+ def __init__(self, hidden, inter):
+ super().__init__()
+ self.w1 = nn.Linear(hidden, inter, bias=False); self.w3 = nn.Linear(hidden, inter, bias=False)
+ self.w2 = nn.Linear(inter, hidden, bias=False)
+ def forward(self, x):
+ return self.w2(F.silu(self.w1(x)) * self.w3(x))
+
+class KimiMoEGate(nn.Module):
+ def __init__(self, config):
+ super().__init__()
+ self.top_k = config.num_experts_per_token; self.routed_scaling_factor = config.routed_scaling_factor
+ self.weight = nn.Parameter(torch.randn(config.num_experts, config.hidden_size) * 0.3)
+ self.e_score_correction_bias = nn.Parameter(torch.zeros(config.num_experts))
+ def forward(self, hidden_states):
+ bsz, seq_len, h = hidden_states.shape
+ logits = F.linear(hidden_states.view(-1, h).float(), self.weight.float())
+ scores = logits.sigmoid()
+ assert not self.training
+ _, topk_idx = torch.topk(scores + self.e_score_correction_bias, k=self.top_k, dim=-1, sorted=False)
+ topk_weight = scores.gather(1, topk_idx)
+ topk_weight = topk_weight / (topk_weight.sum(dim=-1, keepdim=True) + 1e-20)
+ return topk_idx, topk_weight * self.routed_scaling_factor
+
+class KimiSparseMoeBlock(nn.Module):
+ def __init__(self, config):
+ super().__init__()
+ self.config = config; self.ep_size = 1; self.ep_rank = 0; self.experts_per_rank = config.num_experts
+ self.experts = nn.ModuleList([KimiMLP(config.routed_expert_hidden_size, config.moe_intermediate_size) for _ in range(config.num_experts)])
+ self.gate = KimiMoEGate(config)
+ self.shared_experts = KimiMLP(config.hidden_size, config.moe_intermediate_size)
+ self.routed_expert_down_proj = nn.Linear(config.hidden_size, config.routed_expert_hidden_size, bias=False)
+ self.routed_expert_up_proj = nn.Linear(config.routed_expert_hidden_size, config.hidden_size, bias=False)
+ self.routed_expert_norm = KimiRMSNorm(config.routed_expert_hidden_size)
+ def forward(self, hidden_states):
+ identity = hidden_states
+ orig_shape = hidden_states.shape
+ topk_idx, topk_weight = self.gate(hidden_states)
+ hidden_states = hidden_states.view(-1, hidden_states.shape[-1])
+ hidden_states = self.routed_expert_down_proj(hidden_states)
+ if not self.training:
+ y = self.moe_infer(hidden_states, topk_idx, topk_weight)
+ else:
+ raise NotImplementedError("Training mode is not supported in KimiSparseMoeBlock")
+ y = self.routed_expert_norm(y)
+ y = self.routed_expert_up_proj(y)
+ y = y.view(*orig_shape)
+ if self.config.num_shared_experts is not None:
+ y = y + self.shared_experts(identity)
+ return y
+ @torch.no_grad()
+ def moe_infer(self, x, topk_ids, topk_weight):
+ cnts = topk_ids.new_zeros((topk_ids.shape[0], len(self.experts))); cnts.scatter_(1, topk_ids, 1)
+ tokens_per_expert = cnts.sum(dim=0); idxs = topk_ids.view(-1).argsort()
+ sorted_tokens = x[idxs // topk_ids.shape[1]]
+ outputs = []; start_idx = 0
+ for i, num_tokens in enumerate(tokens_per_expert.cpu().numpy()):
+ end_idx = start_idx + num_tokens
+ if num_tokens == 0: continue
+ outputs.append(self.experts[i](sorted_tokens[start_idx:end_idx])); start_idx = end_idx
+ outs = torch.cat(outputs, dim=0) if len(outputs) else sorted_tokens.new_empty(0)
+ new_x = torch.empty_like(outs); new_x[idxs] = outs
+ return new_x.view(*topk_ids.shape, -1).type(topk_weight.dtype).mul_(topk_weight.unsqueeze(dim=-1)).sum(dim=1).type(new_x.dtype)
+"""
+
+
+def _kimi_module(name):
+ import linecache
+
+ filename = f"<{name}>"
+ linecache.cache[filename] = (len(_KIMI_SRC), None, _KIMI_SRC.splitlines(True), filename)
+ mod = types.ModuleType(name)
+ exec(compile(_KIMI_SRC, filename, "exec"), mod.__dict__)
+ for cls in (mod.KimiRMSNorm, mod.KimiMLP, mod.KimiMoEGate, mod.KimiSparseMoeBlock):
+ cls.__module__ = name
+ sys.modules[name] = mod
+ return mod
+
+
+def test_a_latent_moe_trains_through_its_own_projections():
+ torch.manual_seed(0)
+ mod = _kimi_module("transformers_modules.tiny_kimi_k3.modeling_kimi_linear")
+ block = mod.KimiSparseMoeBlock(mod.Cfg())
+ x = torch.randn(2, 5, 16)
+ block.train()
+ with pytest.raises((AssertionError, NotImplementedError)):
+ block(x)
+ assert prepare_remote_moe_for_training(block, verbose = False) == ["KimiSparseMoeBlock"]
+ block.eval()
+ with torch.no_grad():
+ reference = block(x)
+ block.train()
+ out = block(x)
+ assert torch.allclose(out, reference, atol = 1e-5, rtol = 1e-5)
+ out.float().pow(2).sum().backward()
+ for p in (
+ block.gate.weight,
+ block.routed_expert_down_proj.weight,
+ block.routed_expert_up_proj.weight,
+ block.routed_expert_norm.weight,
+ block.shared_experts.w2.weight,
+ ):
+ assert p.grad is not None and torch.isfinite(p.grad).all() and p.grad.abs().sum() > 0
+ assert any(
+ e.w2.weight.grad is not None and e.w2.weight.grad.abs().sum() > 0 for e in block.experts
+ )
+ assert block.training and block.gate.training
+ assert "moe_infer" not in vars(block)
+ block.eval()
+ with torch.no_grad():
+ assert torch.allclose(block(x), reference)
diff --git a/unsloth/_gpu_init.py b/unsloth/_gpu_init.py
index cb58166ae4b..ba918a498a5 100644
--- a/unsloth/_gpu_init.py
+++ b/unsloth/_gpu_init.py
@@ -264,6 +264,7 @@ from .import_fixes import (
fix_transformers_config_only_remote_code,
fix_transformers_remote_rope_scaling_none,
fix_transformers_is_torch_fx_available,
+ fix_transformers5_remote_code_model_api,
fix_xformers_performance_issue,
fix_flash_attn_4_namespace_shadow,
fix_vllm_aimv2_issue,
@@ -339,6 +340,7 @@ fix_transformers_is_torch_fx_available()
# modules are imported and patched when a checkpoint's own modeling file runs,
# not on every `import unsloth`.
fix_transformers5_image_processing_reexports()
+fix_transformers5_remote_code_model_api()
fix_xformers_performance_issue()
# Must run AFTER fix_xformers_performance_issue (it rewrites xformers' cutlass.py on disk) and
# BEFORE models/_utils.py imports xformers.ops.
@@ -400,6 +402,7 @@ del fix_transformers_validate_rope_ignore_keys
del fix_transformers_longcat_lsa_config
del fix_transformers_remote_rope_scaling_none
del fix_transformers_is_torch_fx_available
+del fix_transformers5_remote_code_model_api
del fix_xformers_performance_issue
del fix_flash_attn_4_namespace_shadow
del fix_vllm_aimv2_issue
diff --git a/unsloth/import_fixes.py b/unsloth/import_fixes.py
index 439d75e2e3e..6ca081fab70 100644
--- a/unsloth/import_fixes.py
+++ b/unsloth/import_fixes.py
@@ -2693,6 +2693,109 @@ def _transformers_rope_scaling_assignment_drops_theta():
return False
+_REMOTE_MODEL_API_FLAG = "_unsloth_remote_model_api"
+
+
+def _tie_weights_accepting_new_keywords(own, accepted):
+ @functools.wraps(own)
+ def tie_weights(self, *args, **kwargs):
+ return own(self, *args, **{k: v for k, v in kwargs.items() if k in accepted})
+
+ setattr(tie_weights, _REMOTE_MODEL_API_FLAG, True)
+ return tie_weights
+
+
+def _patch_remote_model_class(cls, new_keywords):
+ if "transformers_modules" not in (getattr(cls, "__module__", "") or ""):
+ return
+ own = cls.__dict__.get("tie_weights")
+ if own is None or getattr(own, _REMOTE_MODEL_API_FLAG, False):
+ return
+ try:
+ params = inspect.signature(own).parameters
+ except (TypeError, ValueError):
+ return
+ if any(p.kind == p.VAR_KEYWORD for p in params.values()):
+ return
+ if all(k in params for k in new_keywords):
+ return
+ cls.tie_weights = _tie_weights_accepting_new_keywords(own, set(params))
+
+
+def _legacy_tied_weights_mapping(model, keys):
+ """4.x list -> 5.x {target: source}; only the output embedding is tied (the one tie 4.x made), other keys get no source rather than a wrong one."""
+ try:
+ embedding = model.get_input_embeddings()
+ output = model.get_output_embeddings()
+ except Exception:
+ return {}
+ weight = getattr(embedding, "weight", None)
+ output_weight = getattr(output, "weight", None)
+ if weight is None or output_weight is None:
+ return {}
+ names = {}
+ for name, param in model.named_parameters(remove_duplicate = False):
+ names.setdefault(id(param), name)
+ source = names.get(id(weight))
+ if source is None:
+ return {}
+ output_names = {
+ name
+ for name, param in model.named_parameters(remove_duplicate = False)
+ if param is output_weight
+ }
+ return {key: source for key in keys if key in output_names and key != source}
+
+
+def fix_transformers5_remote_code_model_api():
+ """Transformers 5 shims for 4.x remote code (Kimi-K3): OutputRecorder alias (before remote import),
+ tie_weights dropping new keywords, list _tied_weights_keys -> mapping. Only transformers_modules
+ classes; no-op on 4.57."""
+ try:
+ import transformers.utils.generic as generic
+ except Exception:
+ return
+ if not hasattr(generic, "OutputRecorder"):
+ try:
+ from transformers.utils.output_capturing import OutputRecorder
+ generic.OutputRecorder = OutputRecorder
+ except Exception:
+ pass
+ try:
+ from transformers import PreTrainedModel
+ except Exception:
+ return
+ if getattr(PreTrainedModel, _REMOTE_MODEL_API_FLAG, False):
+ return
+ try:
+ params = inspect.signature(PreTrainedModel.tie_weights).parameters
+ except (TypeError, ValueError):
+ params = {}
+ new_keywords = tuple(k for k in ("missing_keys", "recompute_mapping") if k in params)
+ original_post_init = PreTrainedModel.post_init
+
+ @functools.wraps(original_post_init)
+ def post_init(self, *args, **kwargs):
+ keys = getattr(self, "_tied_weights_keys", None)
+ if (
+ new_keywords
+ and isinstance(keys, (list, tuple))
+ and "transformers_modules" in (type(self).__module__ or "")
+ ):
+ self._tied_weights_keys = _legacy_tied_weights_mapping(self, keys)
+ if new_keywords:
+ for klass in type(self).__mro__:
+ _patch_remote_model_class(klass, new_keywords)
+ return original_post_init(self, *args, **kwargs)
+
+ PreTrainedModel.post_init = post_init
+ setattr(PreTrainedModel, _REMOTE_MODEL_API_FLAG, True)
+ if UNSLOTH_ENABLE_LOGGING:
+ logger.info(
+ "Unsloth: Remote modeling code written for transformers 4.x gets the 5.x model API shims."
+ )
+
+
def _fp8_replace_swaps_named_experts(fn) -> bool:
try:
return 'endswith(".experts")' in inspect.getsource(fn)
diff --git a/unsloth/kernels/utils.py b/unsloth/kernels/utils.py
index c0452830366..45cb36a722f 100644
--- a/unsloth/kernels/utils.py
+++ b/unsloth/kernels/utils.py
@@ -336,13 +336,41 @@ _FP8_WEIGHT_DTYPES = tuple(
)
+def has_mxfp4_base(*projs):
+ """A packed MXFP4 base that cannot hand its bytes to the fused LoRA kernels (they would then hold a 16-bit
+ weight until backward): use PEFT. Bases with ``mxfp4_quant_state`` pass ``weight_packed`` + that state instead."""
+ return any(
+ getattr(type(base), "_unsloth_mxfp4_packed_linear", False)
+ and getattr(type(base), "mxfp4_quant_state", None) is None
+ for base in (getattr(p, "base_layer", p) for p in projs)
+ )
+
+
+def _packed_base(base_layer):
+ """(weight_packed, quant state) of a packed MXFP4 base, else None; QAT fake-quantizes the decoded weight instead."""
+ cls = type(base_layer)
+ if (
+ not getattr(cls, "_unsloth_mxfp4_packed_linear", False)
+ or getattr(cls, "mxfp4_quant_state", None) is None
+ ):
+ return None
+ if getattr(base_layer, "weight_fake_quantizer", None) is not None:
+ return None
+ return base_layer.weight_packed, base_layer.mxfp4_quant_state()
+
+
+def _is_packed_state(quant_state):
+ return getattr(type(quant_state), "_unsloth_packed_weight_state", False)
+
+
def get_lora_parameters(proj):
"""Return (weight, weight quant_state, lora A, lora B, lora scale).
With QAT enabled, also fake-quantizes the base layer and lora weights.
"""
# For DPO or disabled adapters.
base_layer = getattr(proj, "base_layer", proj)
- W = base_layer.weight
+ packed = _packed_base(base_layer)
+ W = base_layer.weight if packed is None else packed[0]
# Optionally apply fake quantization to base layer weights for QAT.
if hasattr(base_layer, "weight_fake_quantizer"):
@@ -365,6 +393,9 @@ def get_lora_parameters(proj):
if W_quant is not None:
W_quant.block_size = W.block_size
+ if packed is not None:
+ W_quant = packed[1]
+
if getattr(proj, "disable_adapters", True) or proj.merged:
return W, W_quant, None, None, None
@@ -399,7 +430,8 @@ def get_lora_parameters(proj):
def get_lora_parameters_bias(proj):
# For DPO or disabled adapters.
base_layer = getattr(proj, "base_layer", proj)
- W = base_layer.weight
+ packed = _packed_base(base_layer)
+ W = base_layer.weight if packed is None else packed[0]
# Only fall back to a weight_scale(_inv) when the weight is still fp8; a bf16 weight (a decompressed
# compressed-tensors layer) must not carry a scale as its quant state or fast_gemv crashes.
@@ -416,6 +448,9 @@ def get_lora_parameters_bias(proj):
if W_quant is not None:
W_quant.block_size = W.block_size
+ if packed is not None:
+ W_quant = packed[1]
+
if getattr(proj, "disable_adapters", True) or proj.merged:
return W, W_quant, None, None, None, base_layer.bias
@@ -1053,8 +1088,12 @@ def fast_dequantize(
out = None,
use_global_buffer = False,
):
- if type(quant_state) is Int4QuantState:
+ quant_type = type(quant_state)
+ if quant_type is Int4QuantState:
return _int4_dequantize_weight(W, quant_state)
+ # A packed MXFP4 base hands in weight_packed (or its .t()) with a decoder as the quant state.
+ if getattr(quant_type, "_unsloth_packed_weight_state", False):
+ return quant_state.dequantize(W)
return _fast_dequantize_bnb(W, quant_state, out = out, use_global_buffer = use_global_buffer)
@@ -1082,6 +1121,8 @@ def fast_linear_forward(
if W_quant is None:
out = torch_matmul(X, W.t(), out = out)
+ elif _is_packed_state(W_quant):
+ out = W_quant.matmul(X, W, out = out)
elif W.dtype == torch.float8_e4m3fn:
# The bias is added once below; the per-channel fp8_linear path would add it a second time.
if can_use_fp8_rowwise_gemv(X, W, W_quant):
@@ -1151,6 +1192,8 @@ def matmul_lora(
elif type(W_quant) is Int4QuantState and W.stride(-1) == 1:
# Forward orientation: few rows use the fused kernel, the rest decode once + cuBLAS.
out = _int4_matmul(X, W, W_quant, out = out)
+ elif _is_packed_state(W_quant):
+ out = W_quant.matmul(X, W, out = out)
else:
W = fast_dequantize(W, W_quant, use_global_buffer = True)
out = torch_matmul(X, W.t(), out = out)
diff --git a/unsloth/models/compressed_tensors_bnb.py b/unsloth/models/compressed_tensors_bnb.py
index 2f32a50a75f..660384c2d60 100644
--- a/unsloth/models/compressed_tensors_bnb.py
+++ b/unsloth/models/compressed_tensors_bnb.py
@@ -31,7 +31,28 @@ __all__ = [
# Popped by the quantizer after loading so it never reaches a saved config.
UNSLOTH_COMPRESSED_TENSORS_ATTR = "_unsloth_compressed_tensors_bnb"
-_SUPPORTED_FORMATS = ("pack-quantized",)
+_SUPPORTED_FORMATS = ("pack-quantized", "mxfp4-pack-quantized")
+
+
+def _weights_supported(fmt: str, weights: dict) -> bool:
+ kind = str(weights.get("type", "int")).lower()
+ bits = int(weights.get("num_bits", 0) or 0)
+ if fmt == "mxfp4-pack-quantized":
+ return kind == "float" and bits == 4 and int(weights.get("group_size", 0) or 0) == 32
+ return kind == "int" and bits in (2, 3, 4, 5, 6, 7, 8)
+
+
+def _describe(plan: dict) -> str:
+ names = set()
+ top = plan.get("format")
+ for group in (plan.get("config_groups") or {}).values():
+ fmt = group.get("format") or top
+ weights = group.get("weights") or {}
+ if fmt == "mxfp4-pack-quantized":
+ names.add("MXFP4")
+ else:
+ names.add(f"INT{int(weights.get('num_bits', 0) or 0)}")
+ return "/".join(sorted(names)) or "INT"
def _quant_dict(config) -> Optional[dict]:
@@ -86,7 +107,7 @@ def _transformers_supports_weight_converters() -> bool:
def compressed_tensors_bnb_plan(config) -> Optional[dict]:
- """Quant dict for integer weight-only pack-quantized, non-sparse checkpoints; else ``None``."""
+ """Quant dict for weight-only, non-sparse pack-quantized (int) or mxfp4-pack-quantized checkpoints; else ``None``."""
quant = _quant_dict(config)
if quant is None:
return None
@@ -105,17 +126,15 @@ def compressed_tensors_bnb_plan(config) -> Optional[dict]:
weights = group.get("weights")
if not isinstance(weights, dict):
return None
- if str(weights.get("type", "int")).lower() != "int":
+ group_format = group.get("format")
+ if group_format is not None and group_format not in _SUPPORTED_FORMATS:
return None
- if int(weights.get("num_bits", 0)) not in (2, 3, 4, 5, 6, 7, 8):
+ if not _weights_supported(group_format or fmt, weights):
return None
if group.get("input_activations") is not None:
return None
if group.get("output_activations") is not None:
return None
- group_format = group.get("format")
- if group_format is not None and group_format not in _SUPPORTED_FORMATS:
- return None
sparsity = quant.get("sparsity_config")
if isinstance(sparsity, dict):
if str(sparsity.get("format", "dense")) != "dense":
@@ -131,7 +150,7 @@ def arm_compressed_tensors_bnb_loading(config, verbose: bool = True) -> Optional
if not _transformers_supports_weight_converters():
if verbose:
print(
- "Unsloth: This checkpoint is compressed-tensors packed INT4/INT8. Re-quantizing it "
+ f"Unsloth: This checkpoint is compressed-tensors packed {_describe(plan)}. Re-quantizing it "
"to bitsandbytes 4-bit on the fly needs transformers 5.8 or later; loading it as published instead."
)
return None
@@ -140,7 +159,7 @@ def arm_compressed_tensors_bnb_loading(config, verbose: bool = True) -> Optional
except Exception:
if verbose:
print(
- "Unsloth: This checkpoint is compressed-tensors packed INT4/INT8 but `compressed_tensors` "
+ f"Unsloth: This checkpoint is compressed-tensors packed {_describe(plan)} but `compressed_tensors` "
"is not installed; loading it as published. `pip install compressed-tensors` to train it in 4-bit."
)
return None
@@ -150,7 +169,7 @@ def arm_compressed_tensors_bnb_loading(config, verbose: bool = True) -> Optional
except Exception as error:
if verbose:
print(
- "Unsloth: This checkpoint is compressed-tensors packed INT4/INT8 but the installed "
+ f"Unsloth: This checkpoint is compressed-tensors packed {_describe(plan)} but the installed "
f"compressed-tensors cannot read its quantization config ({type(error).__name__}); "
"loading it as published. Upgrading or downgrading `compressed-tensors` may help."
)
@@ -163,7 +182,7 @@ def arm_compressed_tensors_bnb_loading(config, verbose: bool = True) -> Optional
else:
reason = "another library owns the bitsandbytes quantizer"
print(
- "Unsloth: This checkpoint is compressed-tensors packed INT4/INT8 but "
+ f"Unsloth: This checkpoint is compressed-tensors packed {_describe(plan)} but "
f"{reason}; loading it as published."
)
return None
@@ -176,11 +195,14 @@ def arm_compressed_tensors_bnb_loading(config, verbose: bool = True) -> Optional
if "quantization_config" in getattr(sub, "__dict__", {}):
sub.__dict__.pop("quantization_config", None)
setattr(config, UNSLOTH_COMPRESSED_TENSORS_ATTR, plan)
- if verbose:
- bits = sorted({int(g["weights"]["num_bits"]) for g in plan["config_groups"].values()})
- from .compressed_tensors_int4 import int4_packed_route_enabled, int4_packed_supported_plan
-
- if int4_packed_route_enabled() and int4_packed_supported_plan(plan):
+ if verbose and keep_mxfp4_experts_packed(plan):
+ print(
+ "Unsloth: Checkpoint is compressed-tensors packed MXFP4. Keeping the MXFP4 weights packed "
+ "and dequantizing them on the fly; 16-bit weights go to bitsandbytes 4-bit. "
+ "Set UNSLOTH_MXFP4_KEEP_PACKED=0 to re-quantize everything to bitsandbytes 4-bit."
+ )
+ elif verbose:
+ if _int4_packed_plan(plan):
how = (
"Keeping its Linear weights packed and decoding them exactly per use "
f"(set {'UNSLOTH_COMPRESSED_TENSORS_INT4'}=nf4 to re-quantize to bitsandbytes 4-bit instead)."
@@ -190,9 +212,7 @@ def arm_compressed_tensors_bnb_loading(config, verbose: bool = True) -> Optional
"Decompressing each weight on the fly and re-quantizing to bitsandbytes 4-bit "
"(no 16-bit copy on disk)."
)
- print(
- f"Unsloth: Checkpoint is compressed-tensors packed INT{'/'.join(map(str, bits))}. {how}"
- )
+ print(f"Unsloth: Checkpoint is compressed-tensors packed {_describe(plan)}. {how}")
return plan
@@ -435,7 +455,10 @@ def drop_load_only_conversions(model) -> int:
kept, dropped = [], 0
for conv in conversions:
ops = getattr(conv, "operations", None) or []
- if any(isinstance(op, (_DecompressPackedWeights, _WithOriginalSources)) for op in ops):
+ if any(
+ isinstance(op, (_DecompressPackedWeights, _WithOriginalSources, _StackPackedExperts))
+ for op in ops
+ ):
dropped += 1
continue
kept.append(conv)
@@ -484,6 +507,9 @@ def _decompress_one_triton(scheme, packed, scale, shape, zero_point, g_idx, dtyp
strategy = str(getattr(weights.strategy, "value", weights.strategy)).lower()
if bits not in (2, 4, 8) or strategy not in ("group", "channel") or scale.dim() != 2:
return None
+ # MXFP4 is 4-bit group too, but e2m1 values with e8m0 scales, not integers.
+ if str(getattr(weights.type, "value", weights.type)).lower() != "int":
+ return None
if getattr(torch.version, "hip", None):
return None
try:
@@ -523,7 +549,8 @@ def _decompress_one(compressor, scheme, packed, scale, shape, zero_point, g_idx,
if shape is not None and shape.numel():
state["weight_shape"] = shape
else:
- pack_factor = 32 // int(scheme.weights.num_bits)
+ storage_bits = 8 if packed.dtype == torch.uint8 else 32
+ pack_factor = storage_bits // int(scheme.weights.num_bits)
state["weight_shape"] = torch.tensor([packed.shape[0], packed.shape[1] * pack_factor])
if zero_point is not None:
state["weight_zero_point"] = zero_point
@@ -551,7 +578,7 @@ class _DecompressPackedWeights:
def _compressor(self, scheme):
from compressed_tensors.compressors import BaseCompressor
- fmt = scheme.format or "pack-quantized"
+ fmt = scheme.format or getattr(self.ct_config, "format", None) or "pack-quantized"
return BaseCompressor.get_value_from_registry(str(fmt))
def convert(
@@ -716,6 +743,300 @@ class _WithOriginalSources:
return getattr(op, name)
+# MXFP4 stays packed: MoE experts -> Mxfp4StackedExperts, other Linears -> Mxfp4PackedLinear (UNSLOTH_MXFP4_KEEP_PACKED=0 opts out).
+
+_PACKED_EXPERT_KEY = re.compile(r"^(.*)\.experts\.(\d+)\.(w[123])\.weight_(packed|scale)$")
+_STACKED_EXPERT_TARGETS = (
+ "experts.gate_up_blocks",
+ "experts.gate_up_scales",
+ "experts.down_blocks",
+ "experts.down_scales",
+)
+
+
+def _plan_is_mxfp4(plan) -> bool:
+ if not isinstance(plan, dict):
+ return False
+ top = plan.get("format")
+ groups = (plan.get("config_groups") or {}).values()
+ return bool(groups) and all(
+ (group.get("format") or top) == "mxfp4-pack-quantized" for group in groups
+ )
+
+
+def _int4_packed_plan(plan) -> bool:
+ """Packed INT route: INT groups only (MXFP4 groups also have 4 bits but take the MXFP4 route)."""
+ if not isinstance(plan, dict):
+ return False
+ top = plan.get("format")
+ for group in (plan.get("config_groups") or {}).values():
+ weights = group.get("weights") or {}
+ if (group.get("format") or top) == "mxfp4-pack-quantized" or str(
+ weights.get("type", "int")
+ ).lower() != "int":
+ return False
+ from .compressed_tensors_int4 import int4_packed_route_enabled, int4_packed_supported_plan
+
+ return int4_packed_route_enabled() and int4_packed_supported_plan(plan)
+
+
+def _zoo_saves_packed_modules() -> bool:
+ """Without unsloth_zoo's packed save patch a full save writes a checkpoint nothing reloads."""
+ try:
+ from transformers import PreTrainedModel
+ from unsloth_zoo.temporary_patches import mxfp4 as zoo_mxfp4
+
+ zoo_mxfp4._densified_module_names
+ zoo_mxfp4.patch_save_pretrained_mxfp4()
+ except Exception:
+ return False
+ return getattr(PreTrainedModel.save_pretrained, "_unsloth_mxfp4_patched", False)
+
+
+def keep_mxfp4_experts_packed(plan) -> bool:
+ from .mxfp4_compressed_linear import mxfp4_keep_packed_enabled
+ return mxfp4_keep_packed_enabled() and _plan_is_mxfp4(plan) and _zoo_saves_packed_modules()
+
+
+def packed_expert_prefixes(keys) -> dict:
+ """{moe prefix: expert count}; empty if any layer is only partly packed (converters would claim its keys)."""
+ seen: dict = {}
+ for key in keys:
+ match = _PACKED_EXPERT_KEY.match(key)
+ if match is not None:
+ prefix, index, proj, kind = match.groups()
+ seen.setdefault(prefix, set()).add((int(index), proj, kind))
+ extras = {
+ k.rsplit(".experts.", 1)[0]
+ for k in keys
+ if ".experts." in k and k.endswith(("weight_shape", "weight_zero_point", "weight_g_idx"))
+ }
+ prefixes = {}
+ for prefix, entries in seen.items():
+ count = 1 + max(index for index, _, _ in entries)
+ complete = len(entries) == count * 6
+ if not complete or prefix in extras:
+ return {}
+ prefixes[prefix] = count
+ return prefixes
+
+
+def _prefix_for(name: str, prefixes: dict) -> Optional[str]:
+ for prefix in prefixes:
+ if prefix == name or prefix.endswith("." + name) or name.endswith("." + prefix):
+ return prefix
+ return None
+
+
+def _plain_expert_shape(experts) -> Optional[tuple]:
+ first = experts[0]
+ hidden = intermediate = None
+ for expert in experts:
+ w1, w2, w3 = (getattr(expert, n, None) for n in ("w1", "w2", "w3"))
+ if not all(isinstance(w, torch.nn.Linear) and w.bias is None for w in (w1, w2, w3)):
+ return None
+ if not hasattr(expert, "act_fn") or type(expert) is not type(first):
+ return None
+ shape = (w1.in_features, w1.out_features)
+ if (w3.in_features, w3.out_features) != shape or (w2.in_features, w2.out_features) != shape[
+ ::-1
+ ]:
+ return None
+ if hidden is None:
+ hidden, intermediate = shape
+ elif (hidden, intermediate) != shape:
+ return None
+ if hidden % 32 or intermediate % 32:
+ return None
+ return hidden, intermediate
+
+
+def _swappable_expert_blocks(model, prefixes) -> Optional[list]:
+ """``None`` unless every packed MoE block is the plain remote-code layout: all or nothing."""
+ try:
+ from unsloth_zoo.mxfp4_stacked_experts import Mxfp4StackedExperts # noqa: F401
+ except Exception:
+ return None
+ from .remote_moe_shims import is_remote_deepseek_moe
+
+ plan = []
+ for name, module in model.named_modules():
+ experts = getattr(module, "experts", None)
+ if not isinstance(experts, torch.nn.ModuleList) or len(experts) == 0:
+ continue
+ prefix = _prefix_for(name, prefixes)
+ if prefix is None:
+ continue
+ # A stack runs only through the remote MoE shim's dispatch.
+ if (
+ prefixes[prefix] != len(experts)
+ or getattr(module, "ep_size", 1) > 1
+ or not is_remote_deepseek_moe(module)
+ ):
+ return None
+ dims = _plain_expert_shape(experts)
+ if dims is None:
+ return None
+ plan.append((name, module, prefix, dims))
+ if len({prefix for _, _, prefix, _ in plan}) != len(prefixes):
+ return None
+ return plan
+
+
+def _new_stacked_experts(experts, dims, dtype, device):
+ from unsloth_zoo.mxfp4_stacked_experts import Mxfp4StackedExperts
+
+ first = experts[0]
+ # Kimi's SiTU takes the concatenated [gate, up]; any other act_fn is act(gate) * up.
+ fused = getattr(getattr(first, "config", None), "hidden_act", None) == "situ"
+ return Mxfp4StackedExperts(
+ len(experts),
+ dims[0],
+ dims[1],
+ first.act_fn,
+ fused,
+ dtype = dtype,
+ device = device,
+ )
+
+
+def _swap_in_stacks(blocks, dtype) -> list:
+ swapped = []
+ for name, module, _, dims in blocks:
+ first = module.experts[0]
+ module.experts = _new_stacked_experts(module.experts, dims, dtype, first.w1.weight.device)
+ swapped.append(name)
+ return swapped
+
+
+def _match_packed_linears(model, keys) -> Optional[dict]:
+ """Linear per packed checkpoint module (names may differ by leading prefixes); ``None`` if any has no home."""
+ prefixes = [k[: -len(".weight_packed")] for k in keys if k.endswith(".weight_packed")]
+ if not prefixes:
+ return None
+ linears = {
+ name: module
+ for name, module in model.named_modules()
+ if name and isinstance(module, torch.nn.Linear)
+ }
+ by_suffix: dict = {}
+ for name in linears:
+ parts = name.split(".")
+ for i in range(1, len(parts)):
+ by_suffix.setdefault(".".join(parts[i:]), []).append(name)
+ matched = {}
+ for prefix in prefixes:
+ found = prefix if prefix in linears else None
+ if found is None:
+ owners = by_suffix.get(prefix, ())
+ found = owners[0] if len(owners) == 1 else None
+ if found is None:
+ parts = prefix.split(".")
+ for i in range(1, len(parts)):
+ if ".".join(parts[i:]) in linears:
+ found = ".".join(parts[i:])
+ break
+ if found is None or found in matched:
+ return None
+ matched[found] = linears[found]
+ return matched
+
+
+class Mxfp4KeepPackedPlan:
+ def __init__(self, blocks, linears):
+ self.blocks = blocks
+ self.linears = linears
+
+
+def plan_mxfp4_keep_packed(model, keys) -> Optional[Mxfp4KeepPackedPlan]:
+ """All-or-nothing keep-packed plan; ``None`` falls back to the existing decompress route."""
+ packed = [k[: -len(".weight_packed")] for k in keys if k.endswith(".weight_packed")]
+ if not packed:
+ return None
+ # Kept packed, a scale missing from the checkpoint would stay uninitialised bytes.
+ present = set(keys)
+ if any(prefix + ".weight_scale" not in present for prefix in packed):
+ return None
+ prefixes = packed_expert_prefixes(keys)
+ if not prefixes and any(_PACKED_EXPERT_KEY.match(k) for k in keys):
+ return None
+ blocks = (_swappable_expert_blocks(model, prefixes) or []) if prefixes else []
+ stacked = {prefix for _, _, prefix, _ in blocks}
+
+ def _stacked(key):
+ match = _PACKED_EXPERT_KEY.match(key)
+ return match is not None and match.group(1) in stacked
+
+ rest = [k for k in keys if not _stacked(k)]
+ linears = {}
+ if any(k.endswith(".weight_packed") for k in rest):
+ linears = _match_packed_linears(model, rest)
+ if linears is None or any(m.in_features % 32 for m in linears.values()):
+ return None
+ return Mxfp4KeepPackedPlan(blocks, sorted(linears))
+
+
+def _keep_packed_linears(
+ model,
+ names,
+ ct_config,
+ dtype = None,
+) -> int:
+ from .mxfp4_compressed_linear import make_mxfp4_packed_linear
+ for name in names:
+ old = model.get_submodule(name)
+ parent_name, _, child = name.rpartition(".")
+ parent = model.get_submodule(parent_name) if parent_name else model
+ device = next(iter(old.parameters()), torch.empty(0, device = "meta")).device
+ new = make_mxfp4_packed_linear(
+ old.in_features,
+ old.out_features,
+ bias = old.bias,
+ scheme = _scheme_for_module(ct_config, name, old),
+ device = device,
+ dtype = dtype,
+ )
+ setattr(parent, child, new)
+ return len(names)
+
+
+class _StackPackedExperts:
+ def __init__(self, scales: bool):
+ self.scales = scales
+
+ def convert(
+ self,
+ input_dict,
+ source_patterns = None,
+ target_patterns = None,
+ **kwargs,
+ ):
+ from unsloth_zoo.mxfp4_stacked_experts import stack_packed_experts
+
+ as_list = lambda v: v if isinstance(v, list) else [v] # noqa: E731
+ per_projection = [
+ as_list(input_dict.pop(pattern)) for pattern in source_patterns if pattern in input_dict
+ ]
+ return {target_patterns[0]: stack_packed_experts(per_projection, blocks = not self.scales)}
+
+ @property
+ def reverse_op(self):
+ try:
+ from transformers.core_model_loading import _IdentityOp
+ return _IdentityOp()
+ except Exception:
+ return None
+
+
+def finalize_packed_mxfp4_experts(model) -> int:
+ count = 0
+ for module in model.modules():
+ if getattr(type(module), "_unsloth_mxfp4_stacked_experts", False):
+ module.finalize()
+ count += 1
+ return count
+
+
_with_sources_classes = {}
@@ -764,12 +1085,16 @@ def install_compressed_tensors_bnb_quantizer() -> bool:
op_cls = type("DecompressPackedWeights", (_DecompressPackedWeights, ConversionOps), {})
with_sources_cls = _with_original_sources
+ stack_cls = type("StackPackedExperts", (_StackPackedExperts, ConversionOps), {})
class UnslothBnb4BitHfQuantizer(Bnb4BitHfQuantizer):
_unsloth_ct_config = None
_unsloth_ct_dtype = None
_unsloth_dtype_plan = None
_unsloth_plan_dicts = ()
+ _unsloth_packed_experts = ()
+ _unsloth_packed_linears = ()
+ _unsloth_keep_packed = False
_unsloth_int4_packed = ()
_unsloth_int4_leftover = ()
@@ -787,9 +1112,14 @@ def install_compressed_tensors_bnb_quantizer() -> bool:
if not isinstance(dtype, torch.dtype):
dtype = getattr(model, "dtype", None) or torch.bfloat16
self._unsloth_ct_dtype = dtype
- self._unsloth_dtype_plan = packed_weight_dtype_plan(
- _checkpoint_keys(kwargs.get("checkpoint_files"))
+ keys = _checkpoint_keys(kwargs.get("checkpoint_files"))
+ self._unsloth_dtype_plan = packed_weight_dtype_plan(keys)
+ keep = (
+ plan_mxfp4_keep_packed(model, keys) if keep_mxfp4_experts_packed(plan) else None
)
+ self._unsloth_packed_experts = _swap_in_stacks(keep.blocks, dtype) if keep else []
+ self._unsloth_packed_linears = keep.linears if keep else []
+ self._unsloth_keep_packed = keep is not None
self._unsloth_plan_dicts = []
original_get_dtype_plan = model._get_dtype_plan
quantizer = self
@@ -802,13 +1132,8 @@ def install_compressed_tensors_bnb_quantizer() -> bool:
model._get_dtype_plan = _get_dtype_plan
self._unsloth_int4_packed = []
- from .compressed_tensors_int4 import (
- int4_packed_route_enabled,
- int4_packed_supported_plan,
- )
-
self._unsloth_int4_leftover = []
- if int4_packed_route_enabled() and int4_packed_supported_plan(plan):
+ if keep is None and _int4_packed_plan(plan):
swapped, leftover = adopt_int4_packed_linears(
model,
self._unsloth_ct_config,
@@ -823,7 +1148,17 @@ def install_compressed_tensors_bnb_quantizer() -> bool:
self._unsloth_dtype_plan[
r"\.weight_(packed|scale|zero_point|g_idx|shape)$"
] = None
- return super()._process_model_before_weight_loading(model, **kwargs)
+ else:
+ self._unsloth_keep_packed = False
+ result = super()._process_model_before_weight_loading(model, **kwargs)
+ if plan is not None and self._unsloth_packed_linears:
+ _keep_packed_linears(
+ model,
+ self._unsloth_packed_linears,
+ self._unsloth_ct_config,
+ self._unsloth_ct_dtype,
+ )
+ return result
def _process_model_after_weight_loading(self, model, **kwargs):
config = getattr(model, "config", None)
@@ -851,8 +1186,35 @@ def install_compressed_tensors_bnb_quantizer() -> bool:
save_packed_with_checkpoint_config(model, plan)
else:
refuse_mixed_packed_full_save(model)
+ stacks = finalize_packed_mxfp4_experts(model)
+ if stacks or self._unsloth_packed_linears:
+ print(
+ f"Unsloth: Kept the MXFP4 weights packed ({stacks} expert stacks, "
+ f"{len(self._unsloth_packed_linears)} Linears); they are dequantized on the fly "
+ "(UNSLOTH_MXFP4_KEEP_PACKED=0 re-quantizes them to bitsandbytes 4-bit instead)."
+ )
return super()._process_model_after_weight_loading(model, **kwargs)
+ def _unsloth_stacking_converters(self, WeightConverter, stack_cls):
+ if not self._unsloth_packed_experts:
+ return []
+ converters = []
+ for suffix, is_scale in (("weight_packed", False), ("weight_scale", True)):
+ kind = "scales" if is_scale else "blocks"
+ for projections, target in (
+ (("w1", "w3"), f"experts.gate_up_{kind}"),
+ (("w2",), f"experts.down_{kind}"),
+ ):
+ converters.append(
+ WeightConverter(
+ source_patterns = [f"experts.*.{w}.{suffix}$" for w in projections],
+ target_patterns = target,
+ operations = [stack_cls(is_scale)],
+ )
+ )
+ self._unsloth_keep_storage_dtype(list(_STACKED_EXPERT_TARGETS))
+ return converters
+
def _unsloth_keep_storage_dtype(self, target_patterns):
for target in target_patterns:
key = re.escape(target) + r"$"
@@ -864,6 +1226,12 @@ def install_compressed_tensors_bnb_quantizer() -> bool:
ct_config = self._unsloth_ct_config
if ct_config is None:
return super().update_weight_conversions(weight_conversions)
+ if getattr(self, "_unsloth_keep_packed", False):
+ return (
+ list(weight_conversions)
+ + self._unsloth_stacking_converters(WeightConverter, stack_cls)
+ + self.get_weight_conversions()
+ )
dtype = self._unsloth_ct_dtype
updated = []
for conv in weight_conversions:
diff --git a/unsloth/models/llama.py b/unsloth/models/llama.py
index 431081f91d4..b197f2a68a0 100644
--- a/unsloth/models/llama.py
+++ b/unsloth/models/llama.py
@@ -108,6 +108,7 @@ from unsloth.models._attn_mask_compat import (
_prepare_4d_causal_attention_mask_for_sdpa,
)
from ..kernels import *
+from ..kernels.utils import has_mxfp4_base
from ..tokenizer_utils import *
from .vision import FastBaseModel
@@ -3634,6 +3635,12 @@ class FastLlamaModel:
target_modules,
moe_module_targets = _moe_module_targets,
)
+ from .remote_moe_shims import packed_expert_target_parameters
+ target_parameters = packed_expert_target_parameters(
+ model,
+ target_parameters,
+ target_modules if isinstance(target_modules, (list, tuple, str)) else None,
+ )
if _moe_module_targets:
_added = [t for t in _moe_module_targets if t not in final_modules]
@@ -3931,6 +3938,7 @@ class FastLlamaModel:
and (len(getattr(gate_proj, "lora_magnitude_vector", []) or []) == 0)
and (len(getattr(up_proj, "lora_magnitude_vector", []) or []) == 0)
and (len(getattr(down_proj, "lora_magnitude_vector", []) or []) == 0)
+ and not has_mxfp4_base(gate_proj, up_proj, down_proj)
):
# See stackoverflow.com/questions/50599045 on replacing a function within a class of a module.
if hasattr(mlp_module, "_unsloth_forward"):
@@ -3960,6 +3968,7 @@ class FastLlamaModel:
and (len(getattr(q_proj, "lora_magnitude_vector", []) or []) == 0)
and (len(getattr(k_proj, "lora_magnitude_vector", []) or []) == 0)
and (len(getattr(v_proj, "lora_magnitude_vector", []) or []) == 0)
+ and not has_mxfp4_base(q_proj, k_proj, v_proj)
):
layer.self_attn.apply_qkv = apply_lora_qkv
n_qkv += 1
@@ -3977,6 +3986,7 @@ class FastLlamaModel:
hasattr(o_proj, "lora_A")
and (getattr(o_proj, "base_layer", o_proj).bias is None)
and (len(getattr(o_proj, "lora_magnitude_vector", []) or []) == 0)
+ and not has_mxfp4_base(o_proj)
):
layer.self_attn.apply_o = apply_lora_o
n_o += 1
diff --git a/unsloth/models/loader_utils.py b/unsloth/models/loader_utils.py
index 44f550b83f5..f57af4b6f3a 100644
--- a/unsloth/models/loader_utils.py
+++ b/unsloth/models/loader_utils.py
@@ -1918,6 +1918,9 @@ def _decompress_compressed_tensors_model(model):
method = getattr(quant_config, "quant_method", None)
if getattr(method, "value", method) != "compressed-tensors":
return False
+ # MXFP4 kept packed on purpose (all-or-nothing plan): decompress_model would drop weight_packed.
+ if any(getattr(module, "_unsloth_mxfp4_packed_linear", False) for module in model.modules()):
+ return False
if not any(
str(getattr(getattr(module, "quantization_status", None), "value", "")) == "compressed"
for module in model.modules()
@@ -2383,6 +2386,10 @@ def check_and_disable_bitsandbytes_loading(
if quant_method is None or quant_method == "bitsandbytes":
return load_in_4bit, load_in_8bit, quant_method
+ if str(quant_method).lower() in ("compressed-tensors", "compressed_tensors", "sparseml"):
+ from .mxfp4_compressed_linear import install_compressed_tensors_keep_packed
+ install_compressed_tensors_keep_packed()
+
# Packed compressed-tensors: drop its quant config here and keep load_in_4bit for on-the-fly bnb re-quantization.
if (
requantize_packed
diff --git a/unsloth/models/mxfp4_compressed_linear.py b/unsloth/models/mxfp4_compressed_linear.py
new file mode 100644
index 00000000000..14eb65910c9
--- /dev/null
+++ b/unsloth/models/mxfp4_compressed_linear.py
@@ -0,0 +1,638 @@
+# SPDX-License-Identifier: AGPL-3.0-only
+# Copyright 2023-present Daniel 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/>.
+
+"""Train through compressed-tensors ``mxfp4-pack-quantized`` Linears without unpacking them.
+
+Forward and backward dequantize the frozen weight per use (exact in bf16/fp16), so no 16-bit copy is kept.
+Remote-code MoE experts are stacked into unsloth_zoo ``Mxfp4StackedExperts`` instead (see ``compressed_tensors_bnb``).
+"""
+
+import functools
+import os
+import types
+from typing import Optional
+
+import torch
+from torch import nn
+
+__all__ = [
+ "Mxfp4PackedLinear",
+ "Mxfp4PackedState",
+ "mxfp4_packed_matmul",
+ "mxfp4_keep_packed_enabled",
+ "dequantize_mxfp4_packed",
+ "is_mxfp4_scheme",
+ "make_mxfp4_packed_linear",
+ "adopt_compressed_mxfp4_modules",
+ "stack_packed_expert_linears",
+ "install_compressed_tensors_keep_packed",
+ "patch_peft_merge_for_mxfp4_packed_linears",
+ "patch_peft_inits_for_mxfp4_packed_linears",
+]
+
+MXFP4_KEEP_PACKED_ENV = "UNSLOTH_MXFP4_KEEP_PACKED"
+MXFP4_FORMAT = "mxfp4-pack-quantized"
+
+try:
+ from unsloth_zoo.mxfp4_dequant import mxfp4_dequantize as _zoo_mxfp4_dequantize
+except Exception:
+ _zoo_mxfp4_dequantize = None
+try:
+ from unsloth_zoo.mxfp4_gemm import mxfp4_gemm_available, mxfp4_matmul as _zoo_mxfp4_matmul
+except Exception:
+ _zoo_mxfp4_matmul = None
+
+_FP4_VALUES = (
+ 0.0, 0.5, 1.0, 1.5, 2.0, 3.0, 4.0, 6.0,
+ -0.0, -0.5, -1.0, -1.5, -2.0, -3.0, -4.0, -6.0,
+) # fmt: skip
+_LUT_CACHE = {}
+
+
+def mxfp4_keep_packed_enabled() -> bool:
+ return os.environ.get(MXFP4_KEEP_PACKED_ENV, "1").strip() != "0"
+
+
+def _dequantize_torch(blocks, scales, dtype):
+ key = (blocks.device, dtype)
+ lut = _LUT_CACHE.get(key)
+ if lut is None:
+ lut = _LUT_CACHE[key] = torch.tensor(_FP4_VALUES, dtype = dtype, device = blocks.device)
+ *prefix, G, B = blocks.shape
+ out = torch.empty(*prefix, G, B * 2, dtype = dtype, device = blocks.device)
+ out[..., 0::2] = lut[(blocks & 0x0F).long()]
+ out[..., 1::2] = lut[(blocks >> 4).long()]
+ out = torch.ldexp(out, (scales.to(torch.int32) - 127).unsqueeze(-1)).to(dtype)
+ return out.reshape(*prefix, G * B * 2)
+
+
+def dequantize_mxfp4_packed(
+ packed,
+ scale,
+ dtype = torch.bfloat16,
+):
+ """Packed ``[out, in / 2]`` + E8M0 scales ``[out, in / 32]`` -> ``[out, in]``; zoo kernel if self-verified, else torch."""
+ out_features, half = packed.shape
+ blocks = packed.view(out_features, half // 16, 16)
+ if _zoo_mxfp4_dequantize is not None and dtype in (torch.bfloat16, torch.float16):
+ return _zoo_mxfp4_dequantize(blocks, scale, dtype = dtype)
+ return _dequantize_torch(blocks, scale, dtype)
+
+
+def _fused_max_rows():
+ # Rows up to which the fused GEMM (bytes decoded in registers) beats decode + cuBLAS; B200 sweep.
+ try:
+ return int(os.environ.get("UNSLOTH_MXFP4_FUSED_MAX_ROWS", "64"))
+ except ValueError:
+ return 64
+
+
+_FUSED_MAX_ROWS = _fused_max_rows()
+
+
+def mxfp4_packed_matmul(
+ x,
+ packed,
+ scale,
+ transpose = False,
+ out = None,
+ bias = None,
+):
+ """``x @ W^T (+ bias)`` (``transpose=False``) or ``x @ W`` for the packed ``[out, in / 2]`` weight, in x's dtype.
+ Skinny forward inputs (decode, small batches) never build the 16-bit weight; the rest decode it once for cuBLAS."""
+ rows = x.numel() // x.shape[-1] if x.shape[-1] else 0
+ # dX (transpose) stays on decode + cuBLAS: the fused kernel only wins it for a few wide shapes.
+ if (
+ not transpose
+ and _zoo_mxfp4_matmul is not None
+ and rows <= _FUSED_MAX_ROWS
+ and x.is_cuda
+ and mxfp4_gemm_available(x.device, x.dtype)
+ ):
+ return _zoo_mxfp4_matmul(x, packed, scale, trans = transpose, out = out, bias = bias)
+ weight = dequantize_mxfp4_packed(packed, scale, x.dtype)
+ if transpose:
+ return torch.matmul(x, weight, out = out)
+ if bias is not None or out is None:
+ return torch.nn.functional.linear(x, weight, bias)
+ return torch.matmul(x, weight.t(), out = out)
+
+
+def _compute_dtype(x):
+ device_type = x.device.type
+ try:
+ if torch.is_autocast_enabled(device_type):
+ return torch.get_autocast_dtype(device_type)
+ except Exception:
+ pass
+ return x.dtype
+
+
+def _packed_linear(x, packed, scale, bias, dtype):
+ return mxfp4_packed_matmul(
+ x.to(dtype), packed, scale, bias = None if bias is None else bias.to(dtype)
+ )
+
+
+class _Mxfp4PackedLinearFunction(torch.autograd.Function):
+ @staticmethod
+ def forward(ctx, x, packed, scale, bias):
+ out = _packed_linear(x, packed, scale, bias, _compute_dtype(x))
+ ctx.save_for_backward(packed, scale)
+ ctx.x_dtype = x.dtype
+ return out
+
+ @staticmethod
+ def backward(ctx, grad_output):
+ packed, scale = ctx.saved_tensors
+ grad_x = grad_bias = None
+ if ctx.needs_input_grad[0]:
+ grad_x = mxfp4_packed_matmul(grad_output, packed, scale, transpose = True).to(ctx.x_dtype)
+ if ctx.needs_input_grad[3]:
+ grad_bias = grad_output.reshape(-1, grad_output.shape[-1]).sum(0)
+ return grad_x, None, None, grad_bias
+
+
+class Mxfp4PackedLinear(nn.Linear):
+ _unsloth_mxfp4_packed_linear = True
+ compute_dtype = torch.bfloat16
+
+ def forward(self, x):
+ bias = self.bias
+ if torch.is_grad_enabled() and (
+ x.requires_grad or (bias is not None and bias.requires_grad)
+ ):
+ return _Mxfp4PackedLinearFunction.apply(x, self.weight_packed, self.weight_scale, bias)
+ # Inference / frozen input: no autograd node, less per-call overhead on the decode path.
+ return _packed_linear(x, self.weight_packed, self.weight_scale, bias, _compute_dtype(x))
+
+ def mxfp4_quant_state(self):
+ """What kernels.utils passes as the quant state next to ``weight_packed``, so fused LoRA never holds a 16-bit weight."""
+ state = self.__dict__.get("_unsloth_packed_state")
+ packed, scale = self._parameters["weight_packed"], self._parameters["weight_scale"]
+ if (
+ state is None
+ or state.packed is not packed
+ or state.scale is not scale
+ or state.dtype != self.compute_dtype
+ ):
+ state = self.__dict__["_unsloth_packed_state"] = Mxfp4PackedState(
+ packed, scale, self.compute_dtype
+ )
+ return state
+
+ def dequantize_weight(self, dtype = None):
+ return dequantize_mxfp4_packed(
+ self.weight_packed, self.weight_scale, dtype or self.compute_dtype
+ )
+
+ @property
+ def weight(self):
+ # Fresh exact decode per read, never kept: writes are lost (merge densifies first).
+ return self.dequantize_weight()
+
+ def reset_parameters(self):
+ return
+
+ def _apply(self, fn, *args, **kwargs):
+ try:
+ dtype = fn(torch.empty(0, dtype = self.compute_dtype)).dtype
+ except Exception:
+ dtype = self.compute_dtype
+ result = super()._apply(fn, *args, **kwargs)
+ if dtype.is_floating_point:
+ self.compute_dtype = dtype
+ return result
+
+ def extra_repr(self):
+ return (
+ f"in_features={self.in_features}, out_features={self.out_features}, "
+ f"bias={self.bias is not None}, format={MXFP4_FORMAT}"
+ )
+
+
+def _is_transposed(W):
+ # W is weight_packed [out, in / 2] or its .t() view; only the view has a unit leading stride.
+ return W.dim() == 2 and W.stride(0) == 1 and W.stride(1) != 1
+
+
+class Mxfp4PackedState:
+ """Quant state for a packed base in Unsloth's LoRA kernels: ``W`` is ``weight_packed`` (or its ``.t()``)."""
+
+ _unsloth_packed_weight_state = True
+
+ def __init__(self, packed, scale, dtype):
+ self.packed, self.scale, self.dtype = packed, scale, dtype
+
+ def dequantize(
+ self,
+ W = None,
+ dtype = None,
+ ):
+ weight = dequantize_mxfp4_packed(self.packed, self.scale, dtype or self.dtype)
+ return weight.t() if W is not None and _is_transposed(W) else weight
+
+ def matmul(
+ self,
+ X,
+ W,
+ out = None,
+ ):
+ """``X @ D(W).t()`` where D(W) is W's 16-bit value, as matmul_lora computes it."""
+ return mxfp4_packed_matmul(X, self.packed, self.scale, transpose = _is_transposed(W), out = out)
+
+
+def is_mxfp4_scheme(scheme, default_format = None) -> bool:
+ if any(
+ getattr(scheme, f, None) is not None for f in ("input_activations", "output_activations")
+ ):
+ return False
+ fmt = getattr(scheme, "format", None) or default_format
+ fmt = getattr(fmt, "value", fmt)
+ if fmt != MXFP4_FORMAT:
+ return False
+ weights = getattr(scheme, "weights", None)
+ if weights is None:
+ return True
+ kind = getattr(weights, "type", "float")
+ kind = str(getattr(kind, "value", kind)).lower()
+ return (
+ kind == "float"
+ and int(getattr(weights, "num_bits", 4) or 4) == 4
+ and int(getattr(weights, "group_size", 32) or 32) == 32
+ )
+
+
+def _set_compressed_attributes(module, scheme):
+ module.quantization_scheme = scheme
+ try:
+ from compressed_tensors.quantization import QuantizationStatus
+ module.quantization_status = QuantizationStatus.COMPRESSED
+ except Exception:
+ module.quantization_status = "compressed"
+
+
+def make_mxfp4_packed_linear(
+ in_features: int,
+ out_features: int,
+ bias: Optional[torch.Tensor] = None,
+ scheme = None,
+ device = None,
+ dtype = None,
+) -> Mxfp4PackedLinear:
+ if in_features % 32 != 0:
+ raise ValueError(
+ f"Unsloth: an MXFP4 Linear needs in_features divisible by 32, got {in_features}."
+ )
+ module = Mxfp4PackedLinear.__new__(Mxfp4PackedLinear)
+ nn.Module.__init__(module)
+ module.in_features = in_features
+ module.out_features = out_features
+ module.weight_packed = nn.Parameter(
+ torch.empty(out_features, in_features // 2, dtype = torch.uint8, device = device),
+ requires_grad = False,
+ )
+ module.weight_scale = nn.Parameter(
+ torch.empty(out_features, in_features // 32, dtype = torch.uint8, device = device),
+ requires_grad = False,
+ )
+ if isinstance(bias, nn.Parameter):
+ module.bias = bias
+ else:
+ module.register_parameter("bias", None)
+ if dtype is not None and dtype.is_floating_point:
+ module.compute_dtype = dtype
+ _set_compressed_attributes(module, scheme)
+ return module
+
+
+def _drop_compressed_tensors_forward(module):
+ """Drop compressed-tensors' per-instance forward; other instance wrappers (offload) stay."""
+ forward = module.__dict__.get("forward")
+ code = getattr(getattr(forward, "__func__", forward), "__code__", None)
+ if code is not None and code.co_name == "quantized_forward":
+ del module.__dict__["forward"]
+
+
+def _restore_dense_linear(module, dtype):
+ device = module._parameters["weight_packed"].device
+ for name in [n for n in module._parameters if n.startswith("weight_")]:
+ del module._parameters[name]
+ module.weight = nn.Parameter(
+ torch.empty(module.out_features, module.in_features, dtype = dtype, device = device),
+ requires_grad = False,
+ )
+ for name in ("quantization_scheme", "quantization_status"):
+ module.__dict__.pop(name, None)
+ _drop_compressed_tensors_forward(module)
+
+
+def adopt_compressed_mxfp4_modules(
+ model,
+ default_format = None,
+ packed_names = None,
+ dtype = None,
+) -> int:
+ """Adopt every MXFP4 Linear as ``Mxfp4PackedLinear`` and drop the decompress hook; all or nothing (0).
+ Linears not in ``packed_names`` go dense: Kimi-K3 ships its latent MoE projections in bf16."""
+ if not mxfp4_keep_packed_enabled():
+ return 0
+ candidates, others, dense = [], 0, []
+ for name, module in model.named_modules():
+ if isinstance(module, Mxfp4PackedLinear):
+ continue
+ packed = getattr(module, "_parameters", {}).get("weight_packed")
+ if packed is None:
+ if getattr(module, "quantization_scheme", None) is not None:
+ others += 1
+ continue
+ scale = module._parameters.get("weight_scale")
+ scheme = getattr(module, "quantization_scheme", None)
+ if not (
+ type(module) is nn.Linear
+ and "weight" not in module._parameters
+ and packed.dtype == torch.uint8
+ and scale is not None
+ and scale.dtype == torch.uint8
+ and is_mxfp4_scheme(scheme, default_format)
+ ):
+ others += 1
+ elif packed_names is not None and name not in packed_names:
+ dense.append(module)
+ else:
+ candidates.append(module)
+ # The hook would decompress adopted modules too, so adopt only when it can be dropped.
+ if others or not candidates:
+ return 0
+ for module in dense:
+ _restore_dense_linear(module, dtype or torch.get_default_dtype())
+ for module in candidates:
+ module.__class__ = Mxfp4PackedLinear
+ if dtype is not None and dtype.is_floating_point:
+ module.compute_dtype = dtype
+ _drop_compressed_tensors_forward(module)
+ hook = getattr(model, "ct_decompress_hook", None)
+ if hook is not None:
+ hook.remove()
+ try:
+ delattr(model, "ct_decompress_hook")
+ except AttributeError:
+ pass
+ return len(candidates)
+
+
+def stack_packed_expert_linears(
+ model,
+ block_names,
+ dtype = None,
+) -> list:
+ """Stack adopted per-expert Linears; gate_up is released before down is allocated (one-layer transient)."""
+ from .compressed_tensors_bnb import _new_stacked_experts, _plain_expert_shape
+
+ stacked = []
+ for name in block_names:
+ block = model.get_submodule(name)
+ experts = block.experts
+ if not isinstance(experts, nn.ModuleList) or not all(
+ isinstance(getattr(e, w, None), Mxfp4PackedLinear)
+ for e in experts
+ for w in ("w1", "w2", "w3")
+ ):
+ continue
+ dims = _plain_expert_shape(experts)
+ if dims is None:
+ continue
+ hidden, inter = dims
+ E, device = len(experts), experts[0].w1.weight_packed.device
+ new = _new_stacked_experts(experts, dims, dtype or experts[0].w1.compute_dtype, "meta")
+ empty = lambda *shape: torch.empty(shape, dtype = torch.uint8, device = device) # noqa: E731
+ for target, out_rows, in_features, projections in (
+ (
+ "gate_up",
+ 2 * inter,
+ hidden,
+ (("w1", slice(0, inter)), ("w3", slice(inter, 2 * inter))),
+ ),
+ ("down", hidden, inter, (("w2", slice(None)),)),
+ ):
+ stacked_blocks = empty(E, out_rows, in_features // 32, 16)
+ stacked_scales = empty(E, out_rows, in_features // 32)
+ with torch.no_grad():
+ for e, expert in enumerate(experts):
+ for proj, rows in projections:
+ linear = getattr(expert, proj)
+ blocks = stacked_blocks[e, rows]
+ blocks.copy_(linear.weight_packed.view(blocks.shape))
+ stacked_scales[e, rows].copy_(linear.weight_scale)
+ del linear._parameters["weight_packed"], linear._parameters["weight_scale"]
+ setattr(new, f"{target}_blocks", nn.Parameter(stacked_blocks, requires_grad = False))
+ setattr(new, f"{target}_scales", nn.Parameter(stacked_scales, requires_grad = False))
+ block.experts = new.finalize()
+ stacked.append(name)
+ return stacked
+
+
+def _full_finetuning() -> bool:
+ return os.environ.get("UNSLOTH_ENABLE_FULL_FINETUNING", "0") == "1"
+
+
+def install_compressed_tensors_keep_packed() -> bool:
+ """Stock compressed-tensors loader keeps MXFP4 packed (adopt, then stack experts) under the same
+ all-or-nothing plan; declined, full finetuning or explicit dequantize = stock. Idempotent."""
+ try:
+ from transformers.quantizers.quantizer_compressed_tensors import (
+ CompressedTensorsHfQuantizer,
+ )
+ except Exception:
+ return False
+ if "_unsloth_keep_packed" in CompressedTensorsHfQuantizer.__dict__:
+ return True
+ original_before = CompressedTensorsHfQuantizer._process_model_before_weight_loading
+ original_after = CompressedTensorsHfQuantizer._process_model_after_weight_loading
+
+ def _process_model_before_weight_loading(self, model, **kwargs):
+ result = original_before(self, model, **kwargs)
+ self._unsloth_mxfp4_blocks = []
+ config = getattr(self, "quantization_config", None)
+ # `dequantize=True` (transformers 5.5+) or `run_compressed=False` (older).
+ if (
+ not mxfp4_keep_packed_enabled()
+ or _full_finetuning()
+ or getattr(config, "dequantize", False)
+ or getattr(self, "run_compressed", True) is False
+ ):
+ return result
+ fmt = getattr(config, "format", None) or getattr(
+ getattr(config, "quantization_config", None), "format", None
+ )
+ try:
+ from .compressed_tensors_bnb import (
+ _checkpoint_keys,
+ keep_mxfp4_experts_packed,
+ plan_mxfp4_keep_packed,
+ )
+
+ # Skip planning non-MXFP4 checkpoints: key matching is slow on large ones.
+ if not keep_mxfp4_experts_packed(config.to_dict()):
+ return result
+ keys = _checkpoint_keys(kwargs.get("checkpoint_files"))
+ plan = plan_mxfp4_keep_packed(model, keys) if keys else None
+ except Exception:
+ plan = None
+ if plan is None:
+ return result
+ packed_names = set(plan.linears) | {
+ f"{name}.experts.{index}.{proj}"
+ for name, block, _, _ in plan.blocks
+ for index in range(len(block.experts))
+ for proj in ("w1", "w2", "w3")
+ }
+ # transformers 5.x does not pass the load dtype here.
+ dtype = kwargs.get("dtype")
+ if not isinstance(dtype, torch.dtype):
+ dtype = getattr(model, "dtype", None)
+ adopted = adopt_compressed_mxfp4_modules(
+ model,
+ default_format = fmt,
+ packed_names = packed_names,
+ dtype = dtype if isinstance(dtype, torch.dtype) else None,
+ )
+ if adopted:
+ self._unsloth_mxfp4_blocks = [name for name, _, _, _ in plan.blocks]
+ return result
+
+ def _process_model_after_weight_loading(self, model, **kwargs):
+ result = original_after(self, model, **kwargs)
+ blocks = getattr(self, "_unsloth_mxfp4_blocks", None)
+ if blocks:
+ self._unsloth_mxfp4_blocks = []
+ stacked = stack_packed_expert_linears(model, blocks)
+ print(
+ f"Unsloth: Kept the MXFP4 weights packed ({len(stacked)} expert stacks); "
+ "they are dequantized on the fly."
+ )
+ return result
+
+ CompressedTensorsHfQuantizer._process_model_before_weight_loading = (
+ _process_model_before_weight_loading
+ )
+ CompressedTensorsHfQuantizer._process_model_after_weight_loading = (
+ _process_model_after_weight_loading
+ )
+ CompressedTensorsHfQuantizer._unsloth_keep_packed = True
+ return True
+
+
+# PEFT merge on a packed base: `weight.data += delta` would hit a throwaway decode, silently a no-op.
+# Merge densifies to an exact-decode nn.Linear (bytes kept aside); unmerging the last adapter restores them.
+
+_PACKED_STATE = "_unsloth_mxfp4_packed_state"
+
+
+def _swap_class(module, cls):
+ # accelerate keeps the wrapped forward as `_old_forward`; it must follow the class.
+ old = module.__dict__.get("_old_forward")
+ hooked = old is not None and getattr(old, "__func__", None) is type(module).forward
+ module.__class__ = cls
+ if hooked:
+ module._old_forward = types.MethodType(cls.forward, module)
+
+
+def _densify(module):
+ weight = module.dequantize_weight()
+ packed = module._parameters.pop("weight_packed")
+ scale = module._parameters.pop("weight_scale")
+ module.__dict__[_PACKED_STATE] = (packed, scale, module.compute_dtype)
+ _swap_class(module, nn.Linear)
+ module.weight = nn.Parameter(weight, requires_grad = False)
+
+
+def _restore_packed(module):
+ packed, scale, _ = module.__dict__.pop(_PACKED_STATE)
+ device, dtype = module.weight.device, module.weight.dtype
+ del module._parameters["weight"]
+ _swap_class(module, Mxfp4PackedLinear)
+ module.compute_dtype = dtype
+ for name, param in (("weight_packed", packed), ("weight_scale", scale)):
+ if param.device != device:
+ param = nn.Parameter(param.data.to(device), requires_grad = False)
+ module.register_parameter(name, param)
+
+
+def patch_peft_merge_for_mxfp4_packed_linears() -> bool:
+ try:
+ from peft.tuners.lora.layer import Linear as LoraLinear
+ except Exception:
+ return False
+ if getattr(LoraLinear.merge, "_unsloth_mxfp4_patched", False):
+ return True
+ original_merge = LoraLinear.merge
+ original_unmerge = LoraLinear.unmerge
+
+ def merge(self, *args, **kwargs):
+ base = self.get_base_layer()
+ if not isinstance(base, Mxfp4PackedLinear):
+ return original_merge(self, *args, **kwargs)
+ _densify(base)
+ try:
+ return original_merge(self, *args, **kwargs)
+ finally:
+ if not self.merged_adapters:
+ _restore_packed(base)
+
+ def unmerge(self, *args, **kwargs):
+ result = original_unmerge(self, *args, **kwargs)
+ base = self.get_base_layer()
+ if _PACKED_STATE in base.__dict__ and not self.merged_adapters:
+ _restore_packed(base)
+ return result
+
+ merge._unsloth_mxfp4_patched = True
+ unmerge._unsloth_mxfp4_patched = True
+ LoraLinear.merge = merge
+ LoraLinear.unmerge = unmerge
+ return True
+
+
+# These inits subtract the adapter from `weight.data`, a throwaway decode on a packed base: silent model change.
+_BASE_WEIGHT_INITS = ("pissa_init", "olora_init", "corda_init", "loftq_init", "lora_ga_init")
+
+
+def _refuse_on_packed_base(original):
+ @functools.wraps(original)
+ def init(self, *args, **kwargs):
+ if isinstance(self.get_base_layer(), Mxfp4PackedLinear):
+ raise NotImplementedError(
+ f"Unsloth: `{original.__name__}` rewrites the base weight, which stays packed in "
+ "MXFP4 here and cannot be written. Use the default LoRA initialisation."
+ )
+ return original(self, *args, **kwargs)
+
+ init._unsloth_mxfp4_patched = True
+ return init
+
+
+def patch_peft_inits_for_mxfp4_packed_linears() -> bool:
+ try:
+ from peft.tuners.lora.layer import LoraLayer
+ except Exception:
+ return False
+ for name in _BASE_WEIGHT_INITS:
+ original = getattr(LoraLayer, name, None)
+ if original is not None and not getattr(original, "_unsloth_mxfp4_patched", False):
+ setattr(LoraLayer, name, _refuse_on_packed_base(original))
+ return True
+
+
+patch_peft_merge_for_mxfp4_packed_linears()
+patch_peft_inits_for_mxfp4_packed_linears()
diff --git a/unsloth/models/remote_moe_shims.py b/unsloth/models/remote_moe_shims.py
index 6598d1a8cf1..cafaf8a98a4 100644
--- a/unsloth/models/remote_moe_shims.py
+++ b/unsloth/models/remote_moe_shims.py
@@ -18,7 +18,12 @@ import functools
import torch
-__all__ = ["prepare_remote_moe_for_training", "is_remote_deepseek_gate", "is_remote_deepseek_moe"]
+__all__ = [
+ "prepare_remote_moe_for_training",
+ "is_remote_deepseek_gate",
+ "is_remote_deepseek_moe",
+ "packed_expert_target_parameters",
+]
def _is_remote_code(cls) -> bool:
@@ -80,12 +85,19 @@ def _has_own_training_dispatch(body) -> bool:
return [branch.body, branch.orelse]
return [branch.body] if value else [branch.orelse]
+ def only_raises(branch):
+ return all(
+ isinstance(stmt, (ast.Raise, ast.Pass))
+ or (isinstance(stmt, ast.Expr) and isinstance(stmt.value, ast.Constant))
+ for stmt in branch
+ )
+
for node in body:
for sub in ast.walk(node):
if not isinstance(sub, ast.If):
continue
for branch in training_branches(sub):
- if branch and not _calls_moe_infer(branch):
+ if branch and not only_raises(branch) and not _calls_moe_infer(branch):
return True
return False
@@ -109,9 +121,10 @@ def _forward_has_no_training_branch(cls) -> bool:
def is_remote_deepseek_moe(module) -> bool:
# Structural match: derived code renames the block (sarvam's `SarvamMLAMoE`).
cls = type(module)
+ experts = getattr(module, "experts", None)
return (
_is_remote_code(cls)
- and isinstance(getattr(module, "experts", None), torch.nn.ModuleList)
+ and (isinstance(experts, torch.nn.ModuleList) or _is_packed_experts(experts))
and hasattr(module, "moe_infer")
and hasattr(module, "gate")
and _forward_has_no_training_branch(cls)
@@ -134,6 +147,20 @@ def _gate_forward_without_training_assert(original):
return forward
+_MISSING = object()
+
+
+def _is_packed_experts(experts) -> bool:
+ while hasattr(experts, "base_layer"):
+ experts = experts.base_layer
+ return getattr(type(experts), "_unsloth_mxfp4_stacked_experts", False) is True
+
+
+def _packed_moe_dispatch(block, x, topk_idx, topk_weight):
+ # Through the experts module so a PEFT expert LoRA wrapper still applies.
+ return block.experts(x, topk_idx, topk_weight)
+
+
def _moe_train_dispatch(block, x, topk_idx, topk_weight):
num_tokens, top_k = topk_idx.shape
experts = block.experts
@@ -162,20 +189,34 @@ def _moe_train_dispatch(block, x, topk_idx, topk_weight):
def _moe_forward_with_training_path(original):
+ # Reuse the port's forward (eval flags, swapped moe_infer): rebuilding it would skip Kimi-K3's latent projections.
@functools.wraps(original)
def forward(self, hidden_states):
- if not self.training or getattr(self, "ep_size", 1) > 1:
+ if getattr(self, "ep_size", 1) > 1:
+ return original(self, hidden_states)
+ packed = _is_packed_experts(getattr(self, "experts", None))
+ if not self.training and not packed:
+ return original(self, hidden_states)
+ was_training = self.training
+ gate = getattr(self, "gate", None)
+ gate_was_training = isinstance(gate, torch.nn.Module) and gate.training
+ own = self.__dict__.get("moe_infer", _MISSING)
+ # Plain attribute flip: children keep their train-mode flags.
+ self.training = False
+ if gate_was_training:
+ gate.training = False
+ dispatch = _packed_moe_dispatch if packed else _moe_train_dispatch
+ self.__dict__["moe_infer"] = functools.partial(dispatch, self)
+ try:
return original(self, hidden_states)
- identity = hidden_states
- orig_shape = hidden_states.shape
- topk_idx, topk_weight = self.gate(hidden_states)
- flat = hidden_states.view(-1, hidden_states.shape[-1])
- y = _moe_train_dispatch(self, flat, topk_idx, topk_weight).view(*orig_shape)
- # Config key varies (sarvam: `num_shared_experts`); the module decides.
- shared = getattr(self, "shared_experts", None)
- if shared is not None:
- y = y + shared(identity)
- return y
+ finally:
+ self.training = was_training
+ if gate_was_training:
+ gate.training = True
+ if own is _MISSING:
+ self.__dict__.pop("moe_infer", None)
+ else:
+ self.__dict__["moe_infer"] = own
forward._unsloth_remote_moe_shim = True
return forward
@@ -230,3 +271,51 @@ def prepare_remote_moe_for_training(model, verbose = True):
+ "."
)
return patched
+
+
+def _names_a_packed_expert(entry, stack, leaf):
+ parts = entry.split(".")
+ template = stack.split(".") + [None, leaf]
+ if len(parts) > len(template):
+ return False
+ return all(
+ part.isdigit() if want is None else part == want
+ for part, want in zip(parts, template[len(template) - len(parts) :])
+ )
+
+
+def packed_expert_target_parameters(model, target_parameters, requested_leaves):
+ """Packed MXFP4 expert LoRA stays opt in: keep a stack's gate_up_proj (w1/w3) / down_proj (w2) only if
+ the request named its pre-stacking expert Linears, matched as PEFT would (regex fullmatch / dotted suffix)."""
+ counts = {}
+ for name, m in model.named_modules():
+ if _is_packed_experts(m):
+ while hasattr(m, "base_layer"):
+ m = m.base_layer
+ counts[name] = max(int(getattr(m, "num_experts", 1) or 1), 1)
+ stacks = list(counts)
+ if not stacks:
+ return target_parameters
+ names = ("experts.gate_up_proj", "experts.down_proj")
+ kept = [p for p in (target_parameters or []) if not p.endswith(names)]
+ if isinstance(requested_leaves, str):
+ import re
+ def named(stack, leaf):
+ return any(
+ re.fullmatch(requested_leaves, f"{stack}.{e}.{leaf}") for e in range(counts[stack])
+ )
+ else:
+
+ def named(stack, leaf):
+ return any(
+ _names_a_packed_expert(str(entry), stack, leaf) for entry in requested_leaves or ()
+ )
+
+ for leaves, projection in ((("w1", "w3"), "gate_up_proj"), (("w2",), "down_proj")):
+ chosen = [stack for stack in stacks if any(named(stack, leaf) for leaf in leaves)]
+ # PEFT suffix-matches target_parameters, so a request scoped to some layers stays scoped.
+ if len(chosen) == len(stacks):
+ kept.append(f"experts.{projection}")
+ else:
+ kept.extend(f"{stack}.{projection}" for stack in chosen)
+ return kept or None
diff --git a/unsloth/models/vision.py b/unsloth/models/vision.py
index 5853291aa47..add9afa8e32 100644
--- a/unsloth/models/vision.py
+++ b/unsloth/models/vision.py
@@ -1409,6 +1409,9 @@ def _architecture_skip_modules(model_types):
# LongCat-Flash MLA: NF4 on q_b_proj / kv_b_proj badly hurts loss; both are small.
if any(mt in ("longcat_flash", "longcat_flash_lsa") for mt in model_types):
skip.extend(("q_b_proj", "kv_b_proj"))
+ # Kimi-K3's attention residuals read the Linear(hidden, 1) projections' .weight as a score vector, which a packed Params4bit cannot be.
+ if any(mt in ("kimi_k3", "kimi_linear") for mt in model_types):
+ skip.extend(("self_attention_res_proj", "mlp_res_proj", "output_attn_res_proj"))
return skip
@@ -3185,6 +3188,8 @@ class FastBaseModel:
]
# Remember the caller's ORIGINAL explicit leaf list for MoE expert detection: routing it through get_peft_regex adds the full "mlp|feed_forward|ffn|dense" block even for attention-only leaves, so keying on that regex would train the experts. Only the auto path relies on the regex.
_moe_detect_target = target_modules if type(target_modules) in (list, tuple) else None
+ # Auto regex is built after MXFP4 expert stacking, so it no longer names per-expert Linears.
+ _auto_targets = target_modules is None or target_modules == "all-linear"
# get_peft_regex drops these (no attention/MLP ancestor) and LoRA on them never trains, so redirect before scoping, matching FastLanguageModel.
target_modules, modules_to_save, _moved = _redirect_embedding_targets(
@@ -3334,6 +3339,17 @@ class FastBaseModel:
for name, _ in _core.named_parameters()
if any(name == t or name.endswith("." + t) for t in _core_parameters)
] or None
+ from .remote_moe_shims import packed_expert_target_parameters
+
+ if _auto_targets and finetune_mlp_modules and finetune_language_layers:
+ _packed_leaves = ("w1", "w2", "w3")
+ elif isinstance(_moe_module_detect, (list, tuple, str)):
+ _packed_leaves = _moe_module_detect
+ else:
+ _packed_leaves = None
+ target_parameters = packed_expert_target_parameters(
+ model, target_parameters, _packed_leaves
+ )
if _moe_module_targets:
if isinstance(target_modules, (list, tuple)):