Skip to content

armgit / Soup

Public Imported from GitHub
0

Fine-tune LLMs from one YAML. Layer streaming trains an 8B model on a 4 GB laptop GPU.

fix(merge): pass llm_int8_skip_modules=[] for 4bit_forced save format (#1448) (#1606)

Nariman Abdikarim5faf6b1f7c9f
diff --git a/changelog.d/0.75.1/1606.fixed.md b/changelog.d/0.75.1/1606.fixed.md
new file mode 100644
index 00000000..47d17e9c
--- /dev/null
+++ b/changelog.d/0.75.1/1606.fixed.md
@@ -0,0 +1 @@
+- `soup merge --save-format 4bit_forced`: pass `llm_int8_skip_modules=[]` to `BitsAndBytesConfig` so transformers quantizes all linear modules including `lm_head` rather than silently skipping them, and refuse models with tied embeddings (`tie_word_embeddings=True`) by name before loading weights (part of #1448 by @Nari-Ab in #1606).
diff --git a/docs/performance-and-quantization.md b/docs/performance-and-quantization.md
index 0e765188..7fbb3089 100644
--- a/docs/performance-and-quantization.md
+++ b/docs/performance-and-quantization.md
@@ -1293,7 +1293,7 @@ Cross-validator ordering picks the most actionable error: `quantization_aware='f
## Advanced Save Formats (v0.53.0)
-`soup merge --save-format 4bit` and `--save-format 4bit_forced` will write a single BNB-4bit-quantized merged checkpoint without the wasteful dequant → merge → requant cycle (unsloth `merged_4bit` recipe). v0.53.0 ships the closed allowlist + spec metadata; the live writer lands in v0.53.1.
+`soup merge --save-format 4bit` and `--save-format 4bit_forced` will write a single BNB-4bit-quantized merged checkpoint without the wasteful dequant → merge → requant cycle (unsloth `merged_4bit` recipe). `4bit_forced` quantizes all linear layers including `lm_head`; models with tied embeddings (`tie_word_embeddings: true`) cannot hold a 4-bit `lm_head` sharing weights with embeddings and are explicitly refused by name with `ValueError`. v0.53.0 ships the closed allowlist + spec metadata; the live writer lands in v0.53.1.
`soup export --format torchao --quant-config <yaml>` is the planned PTQ export surface for `torchao.quantize_` + `save_pretrained`. Four schemes are allowlisted: `Int4WeightOnly`, `Int8DynActInt4`, `Float8DynActFloat8`, `NVFP4`. CASE-SENSITIVE — these are Soup's scheme names, mapped to the torchao class that implements each one in `utils/torchao_compat.py` (three of the four names Soup used to look up by `hasattr` do not exist in torchao; #826). `Int4WeightOnly` accepts `group_size`; `inner_k_tiles` was removed, because `Int4WeightOnlyConfig` raises `TypeError` for it. Diverges from `--save-format` (lowercase-normalised) on purpose; documented at both validators.
diff --git a/src/soup_cli/utils/save_formats.py b/src/soup_cli/utils/save_formats.py
index 9e0f9bd1..b79e1b48 100644
--- a/src/soup_cli/utils/save_formats.py
+++ b/src/soup_cli/utils/save_formats.py
@@ -283,10 +283,11 @@ def _build_merge_4bit_bnb_kwargs(
}
if forced:
# ``forced`` => no skip-modules, so every Linear (incl. lm_head) is
- # 4-bit quantized. BNB 4-bit uses ``bnb_4bit_skip_modules`` (the
- # legacy 8-bit name was ``llm_int8_skip_modules`` — only emit it
- # when the installed BNB exposes the 8-bit kwarg as a fallback).
- bnb_kwargs["bnb_4bit_skip_modules"] = []
+ # 4-bit quantized. Transformers' BitsAndBytesConfig reads
+ # ``llm_int8_skip_modules`` for linear layer skipping across both
+ # 4-bit and 8-bit quantization. Passing an empty list ensures no
+ # module (including lm_head) is skipped.
+ bnb_kwargs["llm_int8_skip_modules"] = []
return bnb_kwargs
@@ -303,11 +304,11 @@ def merge_4bit(
Unsloth ``merged_4bit`` / ``4bit_forced`` recipe — no
dequant → merge → requant cycle. ``forced=True`` quantizes ALL linear
- layers including embeddings; default ``False`` follows BNB's default
- skip-modules behaviour. ``double_quant`` mirrors
- ``training.bnb_4bit_use_double_quant`` (#321) so the save path agrees with
- the resident and streamed loaders; it defaults True to match shipped
- behaviour.
+ layers (including ``lm_head``; embeddings are not quantized); default
+ ``False`` follows BNB's default skip-modules behaviour. ``double_quant``
+ mirrors ``training.bnb_4bit_use_double_quant`` (#321) so the save path
+ agrees with the resident and streamed loaders; it defaults True to match
+ shipped behaviour.
"""
if not isinstance(forced, bool):
raise TypeError(f"forced must be bool, got {type(forced).__name__}")
@@ -332,11 +333,23 @@ def merge_4bit(
import torch
from transformers import ( # type: ignore[import-not-found]
+ AutoConfig,
AutoModelForCausalLM,
AutoTokenizer,
BitsAndBytesConfig,
)
+ if forced:
+ cfg = AutoConfig.from_pretrained(
+ merged_dir, trust_remote_code=trust_remote_code
+ )
+ if getattr(cfg, "tie_word_embeddings", False):
+ raise ValueError(
+ "4bit_forced cannot quantize models with tie_word_embeddings=True: "
+ "a tied lm_head shares embedding weights which 4-bit Linear cannot hold; "
+ "use --save-format 4bit instead."
+ )
+
dtype_map = {
"float16": torch.float16,
"bfloat16": torch.bfloat16,
diff --git a/tests/test_issue1448_merge_4bit_forced.py b/tests/test_issue1448_merge_4bit_forced.py
new file mode 100644
index 00000000..36ef6be2
--- /dev/null
+++ b/tests/test_issue1448_merge_4bit_forced.py
@@ -0,0 +1,117 @@
+"""Tests for issue #1448: soup merge --save-format 4bit_forced.
+
+Acceptance criteria:
+- 4bit_forced sets llm_int8_skip_modules=[] in BitsAndBytesConfig kwargs.
+- merge_4bit passes llm_int8_skip_modules=[] to BitsAndBytesConfig when forced=True.
+- When forced=False, llm_int8_skip_modules is not set in kwargs.
+"""
+
+from unittest.mock import MagicMock, patch
+
+import pytest
+
+from soup_cli.utils.save_formats import _build_merge_4bit_bnb_kwargs, merge_4bit
+
+
+def test_build_merge_4bit_bnb_kwargs_forced_sets_llm_int8_skip_modules():
+ """forced=True must set llm_int8_skip_modules=[] so transformers quantizes all modules."""
+ kw_forced = _build_merge_4bit_bnb_kwargs(
+ compute_dtype="bfloat16", forced=True, double_quant=True
+ )
+ assert "llm_int8_skip_modules" in kw_forced
+ assert kw_forced["llm_int8_skip_modules"] == []
+
+ kw_unforced = _build_merge_4bit_bnb_kwargs(
+ compute_dtype="bfloat16", forced=False, double_quant=True
+ )
+ assert "llm_int8_skip_modules" not in kw_unforced
+
+
+def test_merge_4bit_forced_passes_llm_int8_skip_modules_to_transformers(tmp_path, monkeypatch):
+ """merge_4bit(forced=True) must pass llm_int8_skip_modules=[] to BitsAndBytesConfig."""
+ import sys
+ import types
+
+ monkeypatch.chdir(tmp_path)
+ src = tmp_path / "src"
+ src.mkdir()
+ out = tmp_path / "out"
+
+ fake_model = MagicMock()
+ fake_tokenizer = MagicMock()
+ mock_bnb_cls = MagicMock(return_value=MagicMock())
+ fake_config = types.SimpleNamespace(tie_word_embeddings=False)
+
+ fake_torch = types.SimpleNamespace(
+ float16="float16",
+ bfloat16="bfloat16",
+ float32="float32",
+ cuda=types.SimpleNamespace(is_available=lambda: False),
+ )
+ monkeypatch.setitem(sys.modules, "torch", fake_torch)
+
+ fake_transformers = types.SimpleNamespace(
+ AutoConfig=MagicMock(from_pretrained=MagicMock(return_value=fake_config)),
+ AutoModelForCausalLM=MagicMock(from_pretrained=MagicMock(return_value=fake_model)),
+ AutoTokenizer=MagicMock(from_pretrained=MagicMock(return_value=fake_tokenizer)),
+ BitsAndBytesConfig=mock_bnb_cls,
+ )
+ monkeypatch.setitem(sys.modules, "transformers", fake_transformers)
+
+ merge_4bit(
+ merged_dir=str(src),
+ output_dir=str(out),
+ forced=True,
+ dtype="bfloat16",
+ double_quant=True,
+ )
+
+ mock_bnb_cls.assert_called_once()
+ _, kwargs = mock_bnb_cls.call_args
+ assert kwargs.get("llm_int8_skip_modules") == []
+ fake_transformers.AutoConfig.from_pretrained.assert_called_once_with(
+ str(src), trust_remote_code=False
+ )
+
+
+def test_merge_4bit_forced_refuses_tied_embeddings(tmp_path, monkeypatch):
+ """A tied lm_head shares the input-embedding weight, which a 4-bit Linear cannot hold:
+ the checkpoint would load and then fail on its first forward pass. Refuse by name,
+ before merge_4bit loads any weights."""
+ pytest.importorskip("transformers")
+ from transformers import LlamaConfig
+
+ monkeypatch.chdir(tmp_path)
+ LlamaConfig(vocab_size=64, hidden_size=64, intermediate_size=128, num_hidden_layers=1,
+ num_attention_heads=2, num_key_value_heads=2,
+ tie_word_embeddings=True).save_pretrained("merged")
+ with patch("transformers.AutoModelForCausalLM.from_pretrained") as load, \
+ patch("transformers.AutoTokenizer.from_pretrained"):
+ with pytest.raises(ValueError, match="4bit_forced") as err:
+ merge_4bit(merged_dir="merged", output_dir="out", forced=True)
+ assert "tie_word_embeddings" in str(err.value)
+ load.assert_not_called()
+
+
+def test_merge_4bit_plain_still_merges_tied_embeddings(tmp_path, monkeypatch):
+ """The refusal belongs to 4bit_forced only: plain 4bit keeps BNB's default
+ lm_head skip, so a tied model must still reach the weight load."""
+ pytest.importorskip("transformers")
+ from transformers import LlamaConfig
+
+ monkeypatch.chdir(tmp_path)
+ LlamaConfig(
+ vocab_size=64,
+ hidden_size=64,
+ intermediate_size=128,
+ num_hidden_layers=1,
+ num_attention_heads=2,
+ num_key_value_heads=2,
+ tie_word_embeddings=True,
+ ).save_pretrained("merged")
+ with patch("transformers.AutoModelForCausalLM.from_pretrained") as load, \
+ patch("transformers.AutoTokenizer.from_pretrained"), \
+ patch("transformers.BitsAndBytesConfig"):
+ merge_4bit(merged_dir="merged", output_dir="out", forced=False)
+ load.assert_called_once()
+
diff --git a/tests/test_v0530.py b/tests/test_v0530.py
index 8b8821f1..d70dd1c8 100644
--- a/tests/test_v0530.py
+++ b/tests/test_v0530.py
@@ -956,13 +956,15 @@ class TestSaveFormats:
assert off["load_in_4bit"] is True
assert off["bnb_4bit_quant_type"] == "nf4"
assert "bnb_4bit_skip_modules" not in off
+ assert "llm_int8_skip_modules" not in off
on = _build_merge_4bit_bnb_kwargs(
compute_dtype="bfloat16", forced=True, double_quant=True
)
assert on["bnb_4bit_use_double_quant"] is True
# ``forced`` still quantizes every Linear (empty skip list) — unchanged.
- assert on["bnb_4bit_skip_modules"] == []
+ assert "bnb_4bit_skip_modules" not in on
+ assert on["llm_int8_skip_modules"] == []
def test_merge_4bit_rejects_non_bool_double_quant(self):
"""Matches the existing ``forced``/``dtype`` type guards."""