Prhub

#18139 Add Intel Quantization Support in SGLang

原始 PR 作者 mengniwang95 合并时间 2026-06-26 09:54 文件变更 8 提交数 55 评论 24 代码增减 +259 / -2

执行摘要

集成 Intel AutoRound 量化,新增 auto-round-int8 支持

基于 RFC #15725,Intel 团队希望将 AutoRound 量化算法深入集成到 SGLang 中,从仅支持加载预量化模型扩展到支持在 SGLang 内直接运行量化流程,提供统一的在线/离线量化体验。

值得精读,特别是 IncModelLoader 的实现展示了如何将外部量化库集成到 SGLang 的模型加载体系中。设计上采用了继承 DefaultModelLoader 的方式,复用权重加载后处理流程,值得借鉴。建议关注离线量化保存路径的约定(scheme 子文件夹)以及在线量化后如何重新初始化模型架构。

讨论亮点

Review 中主要讨论了两个问题:

  • 硬件兼容性文档:mingfeima 和 hshen14 要求在文档中列出已验证的硬件设备,mengniwang95 随后在文档中添加了验证表格。
  • CPU 测试:mingfeima 询问是否需要添加 CPU 测试,但该问题未得到明确答复,最终测试文件中未包含 CPU 场景。

实现拆解

  1. 新增 IncModelLoader:在 python/sglang/srt/model_loader/loader.py 中继承 DefaultModelLoader,重写 load_model 方法。若模型已量化则直接加载,否则执行 AutoRound 量化流程。
  2. 在线与离线量化分支_autoround_quantization_workflow 中根据 load_config.inc_save_path 判断:若为 offline 模式,调用 AutoRound.quantize_and_save 并返回模型;若为 online 模式,对模型量化后重新初始化 SGLang 模型架构,然后注入量化权重。
  3. 配置扩展:在 LoadConfig 新增 inc_save_pathinc_tuning_itersinc_disable_opt_rtn 字段;在 ModelConfig._verify_quantization 中将 auto-round-int8 加入支持列表和兼容映射;在 quantization/__init__.py 中映射到 W8A8Int8Config
  4. 测试覆盖:新增 test/registered/quant/test_autoround_quantization.py,包含 test_online_quant(启动服务器跑 MMLU 断言 score >= 0.7)和 test_offline_quant(加载并量化后检查 config.json 写出)。
  5. 文档更新quantization.mdx 新增 Intel 在线量化方法章节,提供示例代码和已验证硬件表格。
文件 模块 状态 重要度
python/sglang/srt/model_loader/loader.py 模型加载 modified 8.77
test/registered/quant/test_autoround_quantization.py 量化测试 added 7.42
python/sglang/srt/configs/model_config.py 模型配置 modified 6.26
python/sglang/srt/configs/load_config.py 加载配置 modified 5.13
python/sglang/srt/layers/quantization/__init__.py 量化注册 modified 4.35
docs_new/docs/advanced_features/quantization.mdx 文档 modified 4.21

关键符号

IncModelLoader.load_model IncModelLoader._parse_quantization IncModelLoader._autoround_quantization_workflow TestAutoRoundQuantization.test_online_quant TestAutoRoundQuantization.test_offline_quant

关键源码片段

python/sglang/srt/model_loader/loader.py core-logic

核心变更文件,实现 IncModelLoader 类,包含 load_model、_parse_quantization、_autoround_quantization_workflow 方法,是 Intel 量化集成的主入口。

class IncModelLoader(DefaultModelLoader):
    """
    Model loader that applies Intel AutoRound quantization.
    继承 DefaultModelLoader 并覆写 load_model,
    支持在线量化和离线量化两种模式。
    """
​
    def load_model(self, *, model_config, device_config):
        logger.info("IncModelLoader: Loading model...")
        # 如果模型已经量化(检测 config 中的 quantization_config),直接走默认流程
        if model_config._is_already_quantized():
            logger.info("Model is already quantized, loading directly...")
            return super().load_model(model_config=model_config, device_config=device_config)
​
        # 否则执行 AutoRound 量化工作流,返回量化后的模型 state_dict
        quant_model = self._autoround_quantization_workflow(model_config, device_config)
        target_device = torch.device(device_config.device)
​
        # 离线模式:仅量化并返回模型(不重新初始化 SGLang 架构)
        if self.load_config.inc_save_path is not None:
            quant_model.to(target_device)
            return quant_model.eval()
​
        # 在线模式:用量化后的 state_dict 重新初始化 SGLang 模型
        model_config.hf_config = quant_model.config
        quant_config = _get_quantization_config(model_config, self.load_config)
        with set_default_torch_dtype(model_config.dtype):
            with target_device:
                model = _initialize_model(model_config, self.load_config, quant_config)
            self.load_weights_and_postprocess(
                model, iter(quant_model.state_dict().items()), target_device
            )
        return model.eval()
​
    def _autoround_quantization_workflow(self, model_config, device_config):
        """Auto-round 量化工作流:导入库、解析参数、执行量化。"""
        try:
            from auto_round import AutoRound
        except ImportError:
            logger.error("Please install auto-round library: pip install auto-round")
            raise
​
        scheme, format = self._parse_quantization(model_config.quantization)
        autoround = AutoRound(
            model_config.model_path,
            scheme=scheme,
            iters=self.load_config.inc_tuning_iters,
            disable_opt_rtn=self.load_config.inc_disable_opt_rtn,
            low_cpu_mem_usage=False,
        )
        if self.load_config.inc_save_path is not None:
            # 离线模式:量化并保存到指定目录
            model, _ = autoround.quantize_and_save(
                output_dir=self.load_config.inc_save_path, format=format
            )
            return model
        else:
            # 在线模式:量化但不保存,直接返回模型
            model = autoround.quantize()
            return model
test/registered/quant/test_autoround_quantization.py test-coverage

新增单元测试,覆盖在线和离线量化场景,确保 auto-round-int8 功能正确。

class TestAutoRoundQuantization(CustomTestCase):
    @classmethod
    def setUpClass(cls):
        cls.base_url = DEFAULT_URL_FOR_TEST
        cls.model = DEFAULT_MODEL_NAME_FOR_TEST
        cls.output_dir = tempfile.mkdtemp()
​
    @classmethod
    def tearDownClass(cls):
        if os.path.isdir(cls.output_dir):
            shutil.rmtree(cls.output_dir)
​
    def test_online_quant(self):
        # 在线模式:启动服务器时指定 --quantization auto-round-int8
        process = popen_launch_server(
            self.model,
            self.base_url,
            timeout=DEFAULT_TIMEOUT_FOR_SERVER_LAUNCH,
            other_args=["--trust-remote-code", "--quantization", "auto-round-int8"],
        )
        try:
            args = SimpleNamespace(
                base_url=self.base_url,
                model=self.model,
                eval_name="mmlu",
                num_examples=32,
                num_threads=32,
                device="auto",
            )
            metrics = run_eval(args)
            # 断言 MMLU 得分不低于 0.7
            self.assertGreaterEqual(metrics["score"], 0.7)
        finally:
            kill_process_tree(process.pid)
​
    def test_offline_quant(self):
        # 离线模式:通过 LoadConfig 指定 inc_save_path
        model_config = ModelConfig(
            model_path=self.model,
            quantization="auto-round-int8",
            trust_remote_code=True,
        )
        load_config = LoadConfig(inc_save_path=self.output_dir)
        device_config = DeviceConfig(device="cuda")
        model_loader = get_model_loader(load_config, model_config)
        quantized_model = model_loader.load_model(
            model_config=model_config, device_config=device_config
        )
        # 验证量化后的 checkpoint 已保存(存在 config.json)
        config_found = any(
            "config.json" in files for _, _, files in os.walk(self.output_dir)
        )
        self.assertTrue(config_found)

评论区精华

硬件兼容性文档 documentation

mingfeima 询问是否需要在文档中指定支持的硬件设备,hshen14 要求添加已验证的硬件列表,mengniwang95 回复已添加验证硬件信息。

结论:已通过文档更新解决,最终版本包含已验证硬件表格。 · 已解决

CPU 测试覆盖 测试

mingfeima 询问是否需要添加 CPU 测试,mengniwang95 未直接答复。

结论:未解决,测试用例仅包含 CUDA 场景。 · unresolved

风险与影响

  1. 新依赖风险auto-round 库为新增依赖,版本兼容性和运行稳定性可能影响量化流程。
  2. 验证范围:目前文档仅列出了 Intel Xeon 和 NVIDIA A100 验证,其他硬件平台(如 AMD、NPU)可能存在兼容性问题。
  3. 与现有量化配置的交互auto-round-int8 被映射到 W8A8Int8Config,若用户同时使用其他量化相关参数,可能导致配置冲突或意外行为。

用户视角:Intel 平台用户可获得在线量化能力,降低模型部署门槛;其他平台可尝试使用但未充分验证。系统视角:仅新增量化路径,不影响现有默认行为。团队视角:为后续集成更多 Intel 量化方法(如 MXFP4/8)奠定基础。

新依赖风险 验证范围有限 可能与其他量化配置冲突

关联 Issue

#15725 [RFC] Add Intel Quantization Support in SGLang

完整报告

参与讨论