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.

Save int4 QAT LoRA models as real int4 with save_pretrained_torchao (#13413)

Daniel Hanbb4398f7866a
diff --git a/tests/saving/test_qat_torchao_save.py b/tests/saving/test_qat_torchao_save.py
new file mode 100644
index 00000000000..a47b94c354b
--- /dev/null
+++ b/tests/saving/test_qat_torchao_save.py
@@ -0,0 +1,190 @@
+# SPDX-License-Identifier: AGPL-3.0-only
+# Copyright 2026-present the Unsloth AI Inc. team. All rights reserved.
+
+"""save_pretrained_torchao on QAT models (unslothai/unsloth#4980), CPU only."""
+
+from __future__ import annotations
+
+import importlib.util
+
+import pytest
+import torch
+
+pytestmark = pytest.mark.skipif(
+ importlib.util.find_spec("torchao") is None, reason = "require torchao"
+)
+
+import unsloth.save as save_mod
+from unsloth.models._utils import (
+ _convert_torchao_model,
+ _merged_torchao_config_for_peft_qat,
+ _prepare_model_for_qat,
+)
+
+
+class _Block(torch.nn.Module):
+ def __init__(self):
+ super().__init__()
+ self.q_proj = torch.nn.Linear(256, 256, bias = False)
+ self.down_proj = torch.nn.Linear(256, 256, bias = False)
+ self.small = torch.nn.Linear(64, 64, bias = False)
+
+
+class _Model(torch.nn.Module):
+ def __init__(self):
+ super().__init__()
+ self.embed_tokens = torch.nn.Embedding(32, 256)
+ self.layers = torch.nn.ModuleList([_Block()])
+ self.config = type("cfg", (), {"model_type": "llama"})()
+
+ def get_input_embeddings(self):
+ return self.embed_tokens
+
+ def get_output_embeddings(self):
+ return None
+
+
+def _int8_qat_config():
+ from torchao.quantization import IntxWeightOnlyConfig
+ from torchao.quantization.granularity import PerAxis
+
+ from unsloth.models._utils import TorchAOConfig
+
+ return TorchAOConfig(
+ qat_scheme = "int8",
+ base_config_and_filter_fns = [
+ (
+ IntxWeightOnlyConfig(weight_dtype = torch.int8, granularity = PerAxis(0)),
+ lambda m, _: isinstance(m, torch.nn.Linear) and m.in_features >= 128,
+ )
+ ],
+ )
+
+
+def _is_quantized(weight):
+ from torchao.utils import TorchAOBaseTensor
+ return isinstance(weight, TorchAOBaseTensor)
+
+
[email protected]("manual_convert", [False, True])
+def test_convert_quantizes_after_manual_convert(manual_convert):
+ # The QAT notebook runs quantize_(model, QATConfig(step = "convert")) before saving.
+ from torchao.quantization import quantize_
+ from torchao.quantization.qat import QATConfig
+
+ model = _prepare_model_for_qat(_Model(), _int8_qat_config())
+ if manual_convert:
+ quantize_(model, QATConfig(step = "convert"))
+ assert not _is_quantized(model.layers[0].q_proj.weight)
+ _convert_torchao_model(model)
+ block = model.layers[0]
+ assert _is_quantized(block.q_proj.weight)
+ assert _is_quantized(block.down_proj.weight)
+ assert not _is_quantized(block.small.weight)
+
+
+def _peft_qat_model(qat_config, **lora_kwargs):
+ from peft import LoraConfig, get_peft_model
+ peft_model = get_peft_model(
+ _Model(),
+ LoraConfig(r = 8, target_modules = ["q_proj", "down_proj", "small"], **lora_kwargs),
+ )
+ return _prepare_model_for_qat(peft_model, qat_config)
+
+
+def test_peft_qat_config_uses_merged_module_names():
+ qat_config = _int8_qat_config()
+ config = _merged_torchao_config_for_peft_qat(_peft_qat_model(qat_config))
+ assert config.quant_type is qat_config.base_config_and_filter_fns[0][0]
+ # Everything the QAT filter left alone, named as in the merged checkpoint.
+ assert sorted(config.modules_to_not_convert) == ["embed_tokens", "layers.0.small"]
+
+
[email protected]("modules_to_save", [None, ["embed_tokens"]])
+def test_peft_qat_multi_config_uses_merged_module_names(modules_to_save):
+ from torchao.quantization import IntxWeightOnlyConfig
+ from torchao.quantization.granularity import PerAxis
+
+ qat_config = _int8_qat_config()
+ embedding_config = IntxWeightOnlyConfig(weight_dtype = torch.int8, granularity = PerAxis(0))
+ qat_config.base_config_and_filter_fns.append(
+ (embedding_config, lambda m, _: isinstance(m, torch.nn.Embedding))
+ )
+ peft_model = _peft_qat_model(qat_config, modules_to_save = modules_to_save)
+ config = _merged_torchao_config_for_peft_qat(peft_model)
+ names = {
+ k.removesuffix(".weight"): v for k, v in config.quant_type.module_fqn_to_config.items()
+ }
+ assert set(names) == {"layers.0.q_proj", "layers.0.down_proj", "embed_tokens"}
+ assert names["embed_tokens"] is embedding_config
+ assert config.include_input_output_embeddings
+
+
+def test_peft_qat_default_config_keys_every_linear_weight():
+ # int8-int4 shape: an Embedding entry plus a default for Linears.
+ from torchao.quantization import IntxWeightOnlyConfig
+ from torchao.quantization.granularity import PerAxis
+
+ from unsloth.models._utils import TorchAOConfig
+
+ embedding_config = IntxWeightOnlyConfig(weight_dtype = torch.int8, granularity = PerAxis(0))
+ linear_config = IntxWeightOnlyConfig(weight_dtype = torch.int8, granularity = PerAxis(0))
+ qat_config = TorchAOConfig(
+ qat_scheme = "int8-int4",
+ base_config_and_filter_fns = [
+ (embedding_config, lambda m, _: isinstance(m, torch.nn.Embedding)),
+ (linear_config, None),
+ ],
+ )
+ names = _merged_torchao_config_for_peft_qat(
+ _peft_qat_model(qat_config)
+ ).quant_type.module_fqn_to_config
+ if "_default" in names: # transformers 4.x / torchao < 0.15: module names only
+ assert names == {"embed_tokens": embedding_config, "_default": linear_config}
+ else:
+ assert names == {
+ "embed_tokens.weight": embedding_config,
+ "layers.0.q_proj.weight": linear_config,
+ "layers.0.down_proj.weight": linear_config,
+ "layers.0.small.weight": linear_config,
+ }
+
+
+def test_qat_model_accepts_torchao_config(monkeypatch, tmp_path):
+ # The QAT notebook passes torchao_config = Int4WeightOnlyConfig() to a QAT model.
+ seen = {}
+ monkeypatch.setattr(
+ save_mod, "_unsloth_save_torchao_with_given_config", lambda **kw: seen.update(kw)
+ )
+ monkeypatch.setattr(
+ save_mod,
+ "_strip_torchao_fake_quantization",
+ lambda model: seen.update(stripped = model),
+ )
+ model = _Model()
+ model._torchao_config = _int8_qat_config()
+ config = object()
+ save_mod.unsloth_save_pretrained_torchao(
+ model, str(tmp_path), tokenizer = object(), torchao_config = config
+ )
+ assert seen["torchao_config"] is config
+ assert seen["stripped"] is model
+
+
+def test_peft_qat_save_reloads_with_merged_names(monkeypatch, tmp_path):
+ seen = {}
+ monkeypatch.setattr(
+ save_mod, "_unsloth_save_torchao_with_given_config", lambda **kw: seen.update(kw)
+ )
+ qat_config = _int8_qat_config()
+ peft_model = _peft_qat_model(qat_config)
+ save_mod._unsloth_save_torchao_with_attached_config(
+ model = peft_model, save_directory = str(tmp_path), tokenizer = object()
+ )
+ config = seen["torchao_config"]
+ assert config.quant_type is qat_config.base_config_and_filter_fns[0][0]
+ assert sorted(config.modules_to_not_convert) == ["embed_tokens", "layers.0.small"]
+ # The merge reads 16-bit base layers: nothing fake-quantized or already quantized is left.
+ for module in peft_model.modules():
+ assert not hasattr(module, "weight_fake_quantizer")
+ assert not _is_quantized(getattr(module, "weight", None))
diff --git a/unsloth/models/_utils.py b/unsloth/models/_utils.py
index a743873288a..e1e776c372d 100644
--- a/unsloth/models/_utils.py
+++ b/unsloth/models/_utils.py
@@ -7276,6 +7276,113 @@ def _filter_fn_to_fqns(
yield fqn
+def _unquantized_filter(filter_fn):
+ from torchao.quantization.quant_api import _is_linear
+ from torchao.utils import TorchAOBaseTensor
+
+ filter_fn = filter_fn or _is_linear
+
+ def _filter(module, fqn):
+ if not filter_fn(module, fqn):
+ return False
+ weight = getattr(module, "weight", None)
+ return isinstance(weight, torch.Tensor) and not isinstance(weight, TorchAOBaseTensor)
+
+ return _filter
+
+
+def _strip_torchao_fake_quantization(model):
+ """Swap fake-quantized modules back to plain ones, weights untouched (QATConfig(step = "convert") without a base config)."""
+ from torchao.quantization import quantize_
+ from torchao.quantization.qat import QATConfig
+
+ quantize_(
+ model,
+ QATConfig(step = "convert"),
+ filter_fn = lambda m, _: hasattr(m, "weight_fake_quantizer"),
+ )
+
+
+def _merged_torchao_config_for_peft_qat(model):
+ """TorchAoConfig for the merged 16-bit reload of a QAT LoRA model, naming modules as the reload does (PEFT wrappers removed)."""
+ from transformers import TorchAoConfig
+ from torchao.quantization import ModuleFqnToConfig
+ from torchao.quantization.quant_api import _is_linear
+
+ def _merged_name(fqn):
+ parts = fqn.split(".")
+ if parts[:2] == ["base_model", "model"]:
+ parts = parts[2:]
+ # Adapter weights are merged into their base layer; a modules_to_save copy is saved under its wrapper's name.
+ if any(p.startswith("lora_") or p == "original_module" for p in parts):
+ return None
+ if "modules_to_save" in parts:
+ i = parts.index("modules_to_save")
+ parts = parts[:i] + parts[i + 2 :]
+ return ".".join(p for p in parts if p != "base_layer")
+
+ configs = model._torchao_config.base_config_and_filter_fns
+ if len(configs) == 1:
+ # Plain config + skip list, not FqnToConfig: transformers 5 applies a module entry to its bias too.
+ base_config, filter_fn = configs[0]
+ filter_fn = filter_fn or _is_linear
+ skip = [
+ name
+ for fqn, module in model.named_modules()
+ if isinstance(module, (torch.nn.Linear, torch.nn.Embedding))
+ and (name := _merged_name(fqn))
+ and not filter_fn(module, fqn)
+ ]
+ return TorchAoConfig(quant_type = base_config, modules_to_not_convert = skip)
+
+ embeddings = set()
+ for getter in ("get_input_embeddings", "get_output_embeddings"):
+ try:
+ embedding = getattr(model, getter)()
+ except Exception:
+ embedding = None
+ embeddings.update(_merged_name(fqn) for fqn, m in model.named_modules() if m is embedding)
+
+ # transformers 5 also applies module and "_default" entries to a Linear bias; 4.x reads module names only.
+ weight_keys = Version(importlib_version("transformers")) >= Version("5.0.0") and Version(
+ importlib_version("torchao")
+ ) >= Version("0.15.0")
+ suffix = ".weight" if weight_keys else ""
+
+ module_to_fqn_dict = {}
+ include_embeddings = False
+ default_config = None
+ for base_config, filter_fn in configs:
+ if filter_fn is None:
+ if default_config is not None:
+ raise ValueError("Cannot use multiple default quantization configs")
+ default_config = base_config
+ continue
+ for fqn, module in model.named_modules():
+ if not filter_fn(module, fqn):
+ continue
+ name = _merged_name(fqn)
+ if not name:
+ continue
+ if name + suffix in module_to_fqn_dict:
+ raise ValueError(f"Found multiple quantization configs for {name}")
+ module_to_fqn_dict[name + suffix] = base_config
+ include_embeddings = include_embeddings or name in embeddings
+ if default_config is not None and not weight_keys:
+ module_to_fqn_dict["_default"] = default_config
+ elif default_config is not None:
+ for fqn, module in model.named_modules():
+ name = _merged_name(fqn)
+ if name and _is_linear(module, fqn) and name + suffix not in module_to_fqn_dict:
+ module_to_fqn_dict[name + suffix] = default_config
+
+ kwargs = {}
+ if include_embeddings:
+ kwargs["include_input_output_embeddings"] = True
+ kwargs["modules_to_not_convert"] = []
+ return TorchAoConfig(quant_type = ModuleFqnToConfig(module_to_fqn_dict), **kwargs)
+
+
def _convert_torchao_model(model):
from transformers import TorchAoConfig
from torchao.quantization import quantize_, ModuleFqnToConfig
@@ -7285,6 +7392,8 @@ def _convert_torchao_model(model):
module_to_fqn_dict = {}
for base_config, filter_fn in model._torchao_config.base_config_and_filter_fns:
quantize_(model, QATConfig(base_config, step = "convert"), filter_fn = filter_fn)
+ # The QAT notebook's manual QATConfig(step = "convert") leaves plain, unquantized modules.
+ quantize_(model, base_config, filter_fn = _unquantized_filter(filter_fn))
if filter_fn is None:
if "_default" in module_to_fqn_dict:
diff --git a/unsloth/save.py b/unsloth/save.py
index 0274aa171d1..79768d63530 100644
--- a/unsloth/save.py
+++ b/unsloth/save.py
@@ -68,7 +68,12 @@ from .models.loader_utils import (
_tokenizer_revision,
_tokenizer_wants_local_only,
)
-from .models._utils import _convert_torchao_model, lora_relative_to_original_base
+from .models._utils import (
+ _convert_torchao_model,
+ _merged_torchao_config_for_peft_qat,
+ _strip_torchao_fake_quantization,
+ lora_relative_to_original_base,
+)
from .models.mistral_format import raise_if_merging_mistral_format_view
from .ollama_template_mappers import OLLAMA_TEMPLATES, MODEL_TO_OLLAMA_TEMPLATE_MAPPER
from .device_type import clean_gpu_cache
@@ -6036,18 +6041,22 @@ def _unsloth_save_torchao_with_attached_config(
token: Optional[Union[str, bool]] = None,
):
"""Save a QAT-trained model by converting fake-quantized weights to real quantized weights."""
- _convert_torchao_model(model)
- if isinstance(model, PeftModelForCausalLM):
+ if isinstance(model, (PeftModelForCausalLM, PeftModel)):
+ # Quantizing in place leaves int4 base layers the LoRA merge cannot read, so merge in 16-bit and quantize the reload with the QAT configs.
+ torchao_config = _merged_torchao_config_for_peft_qat(model)
+ _strip_torchao_fake_quantization(model)
_unsloth_save_torchao_with_given_config(
model = model,
save_directory = save_directory,
tokenizer = tokenizer,
- torchao_config = model.config.quantization_config,
+ torchao_config = torchao_config,
push_to_hub = push_to_hub,
token = token,
)
return
+ _convert_torchao_model(model)
+
# TorchAO does not support safe_serialization reliably.
safe_serialization = False
@@ -6933,10 +6942,10 @@ def unsloth_save_pretrained_torchao(
push_to_hub: bool = False,
token: Optional[Union[str, bool]] = None,
):
- """Save a torchao quantized model checkpoint. Two mutually exclusive workflows: a model trained with `qat_scheme` must NOT be given a `torchao_config` and has its fake-quantized weights converted to real quantized ones; any other model must be given one, and is quantized here.
+ """Save a torchao quantized model checkpoint. A model trained with `qat_scheme` may omit `torchao_config` and is quantized with its QAT scheme; any other model must be given one, and is quantized here.
`save_directory`: local folder, or a hub id when `push_to_hub` is True.
- `torchao_config` (TorchAOBaseConfig): required for PTQ, None for QAT. https://docs.pytorch.org/ao/main/api_ref_quantization.html#inference-apis-for-quantize
+ `torchao_config` (TorchAOBaseConfig): required for PTQ, optional for QAT. https://docs.pytorch.org/ao/main/api_ref_quantization.html#inference-apis-for-quantize
"""
_assert_export_target_is_not_base_with_lora_layers(self)
if isinstance(tokenizer, (PreTrainedTokenizerBase, ProcessorMixin)):
@@ -6948,11 +6957,9 @@ def unsloth_save_pretrained_torchao(
has_qat_config = hasattr(self, "_torchao_config") and self._torchao_config is not None
if torchao_config is not None:
- assert not has_qat_config, (
- "Unsloth: You passed `torchao_config` but this model was trained with `qat_scheme`. "
- "For QAT models, do not pass `torchao_config` - the quantization config is already "
- "attached to the model from training."
- )
+ if has_qat_config:
+ # The 16-bit save below must see plain modules, not fake-quantized ones.
+ _strip_torchao_fake_quantization(self)
_unsloth_save_torchao_with_given_config(
model = self,
save_directory = save_directory,