Skip to content

PTQ-Level Efficiency, QAT-Level Accuracy | 训练后量化的效率,量化感知训练的精度

remove bagel specific constraints (#2372)

Weiwei4b3680b9af59
diff --git a/auto_round/envs.py b/auto_round/envs.py
index 6ffedd38b..0a64af5a8 100644
--- a/auto_round/envs.py
+++ b/auto_round/envs.py
@@ -35,6 +35,7 @@ if TYPE_CHECKING:
AR_DISABLE_META_LOAD: bool = False
AR_RESUME_DIR: Optional[str] = None
AR_FORCE_MOE_ROUTING_ALL_EXPERTS: bool = False
+ AR_QUANTIZE_BAGEL_MOE_GEN: bool = False
AR_NVFP4_FUSED_LAYER_GLOBAL_SCALE: bool = True
AR_ALLOW_W8_ASYM: bool = False
@@ -142,6 +143,10 @@ environment_variables: dict[str, Callable[[], Any]] = {
# to rotate token assignments across all experts for calibration coverage.
"AR_FORCE_MOE_ROUTING_ALL_EXPERTS": lambda: os.getenv("AR_FORCE_MOE_ROUTING_ALL_EXPERTS", "0").lower()
in ("1", "true", "yes"),
+ # BAGEL's image-generation experts are kept in BF16 by default because
+ # quantizing them can reduce image quality. Enable only for experiments
+ # that explicitly trade image quality for a smaller checkpoint.
+ "AR_QUANTIZE_BAGEL_MOE_GEN": lambda: os.getenv("AR_QUANTIZE_BAGEL_MOE_GEN", "0").lower() in ("1", "true", "yes"),
# Experts forward used for AutoRound's unfused per-expert nn.Linear MoE layout:
# "auto" - (default) same as "linear_grouped"
# "linear_grouped" - sort the routed (token, expert) pairs once and run one
diff --git a/auto_round/special_model_handler.py b/auto_round/special_model_handler.py
index ba344a39d..40a6c1565 100644
--- a/auto_round/special_model_handler.py
+++ b/auto_round/special_model_handler.py
@@ -1133,32 +1133,26 @@ register_ignore_layers(
def get_bagel_ignore_layers(model) -> list[str]:
- """Keep BAGEL generation-path modules in FP16.
+ """Keep BAGEL generation-path modules in BF16.
BAGEL uses `*_moe_gen` modules for the image-generation path. Quantizing
- them causes quality to collapse during the iterative denoising loop.
- The shared attention projections are also highly sensitive, and preserving
- the top 4 transformer blocks in FP16 gave acceptable image quality in
- validation runs.
- """
- top_fp16_layers = 0
-
- ignore_layers = [
- "moe_gen",
- "self_attn.q_proj",
- "self_attn.k_proj",
- "self_attn.v_proj",
- "self_attn.o_proj",
- ]
-
- num_layers = 0
- if hasattr(model, "language_model") and hasattr(model.language_model, "model"):
- num_layers = len(getattr(model.language_model.model, "layers", []))
+ them can reduce quality during the iterative denoising loop. Users can
+ explicitly opt in with ``AR_QUANTIZE_BAGEL_MOE_GEN=1``.
- if num_layers > 0:
- for layer_idx in range(max(0, num_layers - top_fp16_layers), num_layers):
- ignore_layers.append(f"language_model.model.layers.{layer_idx}")
+ The standard Qwen2 attention and MLP projections are deliberately not
+ ignored: they form BAGEL's normal text path and should follow AutoRound's
+ usual transformer-layer policy.
+ """
+ from auto_round import envs
+ ignore_layers = []
+ if not envs.AR_QUANTIZE_BAGEL_MOE_GEN:
+ ignore_layers.append("moe_gen")
+ else:
+ logger.warning(
+ "AR_QUANTIZE_BAGEL_MOE_GEN is enabled. Quantizing BAGEL's image-generation experts may reduce image "
+ "quality."
+ )
return ignore_layers
diff --git a/docs/environments.md b/docs/environments.md
index a9ceb17ae..c47fe1cb0 100644
--- a/docs/environments.md
+++ b/docs/environments.md
@@ -50,6 +50,17 @@ export AR_NVFP4_FUSED_LAYER_GLOBAL_SCALE=0
export AR_USE_MODELSCOPE=true
```
+### AR_QUANTIZE_BAGEL_MOE_GEN
+
+- **Description**: Enables quantization of BAGEL's `*_moe_gen` image-generation experts. By default, AutoRound keeps these modules in BF16 because quantizing them has been observed to reduce image-generation quality. BAGEL's normal transformer attention and MLP layers are still quantized by default.
+- **Default**: `False` (equivalent to `"0"`)
+- **Valid Values**: `"1"`, `"true"`, or `"yes"` (case-insensitive) for enabling; any other value keeps `*_moe_gen` in BF16
+- **Usage**: Enable only when experimenting with the checkpoint-size and image-quality tradeoff
+
+```bash
+export AR_QUANTIZE_BAGEL_MOE_GEN=1
+```
+
### AR_WORK_SPACE
- **Description**: Sets the workspace directory for AutoRound operations
- **Default**: `"ar_work_space"`
diff --git a/docs/environments_CN.md b/docs/environments_CN.md
index 27ac26672..2995f01a6 100644
--- a/docs/environments_CN.md
+++ b/docs/environments_CN.md
@@ -50,6 +50,17 @@ export AR_NVFP4_FUSED_LAYER_GLOBAL_SCALE=0
export AR_USE_MODELSCOPE=true
```
+### AR_QUANTIZE_BAGEL_MOE_GEN
+
+- **描述**:启用 BAGEL `*_moe_gen` 图像生成专家层的量化。AutoRound 默认将这些模块保留为 BF16,因为实际测试发现量化它们可能降低图像生成质量。BAGEL 的普通 transformer attention 和 MLP 层默认仍会量化。
+- **默认值**:`False`(等价于 `"0"`)
+- **有效值**:`"1"`、`"true"` 或 `"yes"`(不区分大小写)表示启用;其他值会让 `*_moe_gen` 保持 BF16
+- **用途**:仅在研究 checkpoint 大小与图像质量之间的取舍时启用
+
+```bash
+export AR_QUANTIZE_BAGEL_MOE_GEN=1
+```
+
### AR_WORK_SPACE
- **描述**:设置 AutoRound 操作的工作目录
- **默认值**:`"ar_work_space"`
diff --git a/test/unit/common/models/test_bagel.py b/test/unit/common/models/test_bagel.py
index 597bddfb1..137005a27 100644
--- a/test/unit/common/models/test_bagel.py
+++ b/test/unit/common/models/test_bagel.py
@@ -202,26 +202,6 @@ class TestBagelSpecialModelHandler:
assert blocks[0][0] == "language_model.model.layers.0"
assert blocks[0][1] == "language_model.model.layers.1"
- def test_get_bagel_ignore_layers_structure(self):
- """get_bagel_ignore_layers should return generation-path modules."""
-
- # Use minimal mock matching BAGEL's attribute structure
- class MockLanguageModel:
- def __init__(self):
- self.model = type("MockModel", (), {"layers": [None, None, None]})()
-
- class MockBagelModel:
- def __init__(self):
- self.language_model = MockLanguageModel()
-
- model = MockBagelModel()
- ignore = get_bagel_ignore_layers(model)
- assert "moe_gen" in ignore
- assert "self_attn.q_proj" in ignore
- assert "self_attn.k_proj" in ignore
- assert "self_attn.v_proj" in ignore
- assert "self_attn.o_proj" in ignore
-
def test_bagel_registered_in_special_multimodal_block(self):
"""BAGEL should be in SPECIAL_MULTIMODAL_BLOCK."""
from auto_round.special_model_handler import SPECIAL_MULTIMODAL_BLOCK
diff --git a/test/unit/common/models/test_special_model_handler.py b/test/unit/common/models/test_special_model_handler.py
index ad938ead5..159daa28b 100644
--- a/test/unit/common/models/test_special_model_handler.py
+++ b/test/unit/common/models/test_special_model_handler.py
@@ -958,18 +958,15 @@ class TestGetPredefinedIgnoreLayers:
assert "vision_tower" in layers
assert "mm_projector" in layers
- def test_bagel_matcher(self):
+ def test_bagel_matcher(self, monkeypatch):
from auto_round.special_model_handler import get_predefined_ignore_layers
+ monkeypatch.delenv("AR_QUANTIZE_BAGEL_MOE_GEN", raising=False)
mock_model = MagicMock()
mock_model.config.model_type = "bagel"
mock_model.language_model.model.layers = [MagicMock() for _ in range(32)]
layers = get_predefined_ignore_layers(mock_model)
- assert "moe_gen" in layers
- assert "self_attn.q_proj" in layers
- assert "self_attn.k_proj" in layers
- assert "self_attn.v_proj" in layers
- assert "self_attn.o_proj" in layers
+ assert layers == ["moe_gen"]
def test_moe_model_via_config(self):
from auto_round.special_model_handler import get_predefined_ignore_layers
@@ -1029,24 +1026,18 @@ class TestTorchCompileOff:
class TestGetBagelIgnoreLayers:
"""Test get_bagel_ignore_layers function."""
- def test_returns_expected_layers(self):
- from auto_round.special_model_handler import get_bagel_ignore_layers
-
- mock_model = MagicMock()
- mock_model.language_model.model.layers = [MagicMock() for _ in range(32)]
- layers = get_bagel_ignore_layers(mock_model)
- assert "moe_gen" in layers
- assert "self_attn.q_proj" in layers
- assert "self_attn.k_proj" in layers
- assert "self_attn.v_proj" in layers
- assert "self_attn.o_proj" in layers
-
- def test_no_language_model(self):
+ @pytest.mark.parametrize(
+ ("env_value", "expected"),
+ [(None, ["moe_gen"]), ("0", ["moe_gen"]), ("1", [])],
+ )
+ def test_moe_gen_policy(self, monkeypatch, env_value, expected):
from auto_round.special_model_handler import get_bagel_ignore_layers
- mock_model = MagicMock(spec=[])
- layers = get_bagel_ignore_layers(mock_model)
- assert "moe_gen" in layers
+ if env_value is None:
+ monkeypatch.delenv("AR_QUANTIZE_BAGEL_MOE_GEN", raising=False)
+ else:
+ monkeypatch.setenv("AR_QUANTIZE_BAGEL_MOE_GEN", env_value)
+ assert get_bagel_ignore_layers(MagicMock()) == expected
class TestGetGlmFlashIgnoreLayers: