Merged
feat: add int4 weight only inference example #54
feat: add int4 weight only inference example #54
Merged
LennonAdd on Oct 28
Lennon
Lennon
Oct 28

【合入来源】

【修改方案】

融合专家转换通过样例配置 QwenInt4ExpertConfig 分发。样例使用 register_quantize_module_handler 注册转换函数,调用 quantize_ 选择对应专家,执行模块负责已有的量化计算。

设计原因。 单卡样例的输入是 Qwen2.5-0.5B-Instruct 的 BF16 预训练权重。为了用这份权重验证 INT4 推理,样例在加载后先执行训练后量化(PTQ):通过 TorchAO 的 Int4WeightOnlyConfig 和 quantize_ 将目标 Linear 的权重转换为打包的 INT4 表示,激活保持 BF16。转换在构建量化模型时完成,后续前向和逐 token 生成复用该模型的 INT4 权重及量化参数。若输入已是与当前 TorchAO/NPU 表示兼容的 INT4 checkpoint,则可在恢复相应的量化模型结构和参数后直接推理。

  1. 在 examples/qwen2_5/ 下新增 qwen2_5_int4_weight_only_inference.py、int4_weight_only_inference.sh 和对应配置;MoE 配置为 examples/qwen3_5/qwen3_5_int4_weight_only_inference_moe_config.yaml。

  2. 单卡配置使用完整 Qwen2.5-0.5B-Instruct;8 卡 FSDP2 配置使用完整 Qwen2.5-72B-Instruct 或 Qwen3.5-35B-A3B 文本模型,默认使用完整层数。

  3. 以 BF16 为对照,测量量化推理的耗时和逐卡显存。保存和恢复量化 checkpoint,对同一输入比较 logits,再执行四个 token 的贪心生成。

  4. MoE 将两组三维专家权重按 K 轴每 128 个值做 INT4 量化,保存每组的 scale 和 offset。沿用原有 router 的 top-k 选择和权重,在样例内执行两次 npu_grouped_matmul 并合并输出。

  5. 公共 helper PR #57 仅提供通用加载、step 回调测量、DCP 状态读写和权重采样。当前样例自行实现量化层筛选、Qwen3.5 模型及 grouped_mm 后端适配、block/FSDP2 编排、forward/loss/logits 和适用的训练检查;测量显式传入 torch.npu 及数据并行 token 数。生成和量化步骤由本样例编排。

启动接口与填写示例

在仓库根目录运行以下命令,将模型目录替换为本机已下载的权重和 tokenizer 所在目录。

bash examples/qwen2_5/int4_weight_only_inference.sh single --model-path /models/Qwen2.5-0.5B-Instruct
入口参数 可选值与填写方式
Shell 第一个位置参数 省略时为 single(Qwen2.5-0.5B 单卡)。dense 选择 Qwen2.5-72B 的八进程配置,moe 选择 Qwen3.5-35B-A3B 的八进程配置。
--config PATH Python 入口读取的 YAML 文件。直接运行 python examples/qwen2_5/qwen2_5_int4_weight_only_inference.py 时默认读取同目录的 qwen2_5_int4_weight_only_inference_config.yaml。使用自定义配置可在启动模式后传 --config ./my_config.yaml。
--model-path PATH 可选,覆盖 YAML 的 model_path。填写启动模式所对应模型的本地目录。

下列单卡 YAML 给出了所有对外配置字段的一组填写值。

model_path: /path/to/Qwen2.5-0.5B-Instruct
model_kind: dense
world_size: 1
packing: plain_int32
batch_size: 1
sequence_length: 64
seed: 42
warmup: 3
iterations: 10
output: ./results/int4_weight_only_inference_single
YAML 字段 类型、候选值与用途
model_path、model_kind、world_size 路径填本地目录。model_kind 填 dense 或 moe。world_size 填实际启动的进程数,随附配置的三组分别为 dense/1、dense/8、moe/8。
batch_size、sequence_length 每个 rank 的样本数和输入 token 长度;填写正整数。训练或计算 causal loss 时长度至少为 2,并在模型上下文范围内。
seed、warmup、iterations 随机种子填整数;预热和正式计时次数分别填正整数。
output 可写结果目录,接受绝对路径或相对启动工作目录的路径。
packing 在 YAML 中设置。随附 Dense/MoE 的 A5 配置均填 plain_int32,MoE 强制使用该值。Dense 将字符串传给 TorchAO;其 v0.18 枚举另有 plain、preshuffled、tile_packed_to_4d。这些名称不代表对应内核已在本示例 A5 环境验证,plain 路径依赖 MSLK。

Python 量化 API 与对应参数

以下为该工作流实际传给框架的参数。修改 CLI 或 YAML 即可改变上表开放的选项;表中标为固定的值由 Python 配方提供。

API 参数如何填写
quantize_(model, config, filter_fn=select) 第一个参数填待转换的模型或子模块,第二个参数按下表所述阶段构造。普通层使用 select(module, name),其中 module 是当前模块,name 是模块路径,返回布尔值;选中 Linear 并排除以 lm_head、shared_expert_gate、.gate 结尾的名称。
Int4WeightOnlyConfig(group_size=128, int4_packing_format=..., version=2) int4_packing_format 取 YAML 的 packing。上游 group size 可选 32、64、128、256;本例的打包和专家 scale 布局固定用 128,版本固定为 2。激活保留 BF16。
QwenInt4ExpertConfig() 无需填写参数。将实例传给 quantize_(model, QwenInt4ExpertConfig(), filter_fn=...),筛选回调只匹配 Qwen3_5MoeExperts。
Int4PlainInt32Tensor.from_hp(...)、npu_grouped_matmul(...) 专家打包传展平的二维浮点权重和块大小 [1, 128]。专家前向传单元素输入列表、转置后的打包权重列表、每组 antiquant_scale、antiquant_offset 及每专家 token 数 group_list。本例固定 group_list_type=1, group_type=0, split_item=2;各张量由模型产生。

加载、测量和恢复接口。 load_model(model_path, *, model_cls, dtype, attn_implementation, use_cache, **model_kwargs) 接受本地路径。Dense 传 AutoModelForCausalLM,MoE 传 Qwen3_5MoeForCausalLM 和 experts_implementation="grouped_mm"。本例使用 torch.bfloat16、"eager"、False;公共接口也接受 attn_implementation=None 或 use_cache=None 来保留模型默认值。

measure(step, *, device_api, warmup, iterations, tokens_per_step, before_measure=None) 的 step 填无参执行回调,device_api=torch.npu,次数取 YAML;tokens_per_step 填单 rank 输入 token 数乘数据并行 rank 数。before_measure 可省略或传无参清理回调。 model_checkpoint(model, directory, load=False) 传模型和 checkpoint 目录;False 保存,True 恢复到已重建的量化模型。

【资料变更】

新增 examples/qwen2_5/int4_weight_only_inference.md,说明三种启动模式、依赖、配置、测量范围及资源要求。每个 rank 当前在 CPU 加载完整模型,须考虑主机内存开销。

【接口变更】

不修改生产 API,新增 example 命令行入口。

【功能验证】

Qwen2.5-0.5B-Instruct · A5 单卡

以下为此前使用完整预训练模型和配套 tokenizer 运行样例的记录。使用 plain_int32 打包,完成 INT4 权重量化推理、量化模型保存恢复和生成。

bash examples/qwen2_5/int4_weight_only_inference.sh single --model-path /models/Qwen2.5-0.5B-Instruct

单卡运行记录(pretrained-results.json 摘录,exit_code 为整个样例进程的退出码):

{"case": "int4_weight_only_inference", "exit_code": 0, "seconds": 24.244094133377075, "device": 5}

量化阶段的原始输出(节选一组配置):

int4_weight_only_inference_single/metrics.jsonl
{"stage": "quantized", "per_rank": [{"seconds": 0.2954106900142506, "resident_bytes": 467816960, "peak_allocated_bytes": 502233600, "peak_reserved_bytes": 557842432}], "ms_per_step": 29.541069001425058, "tokens_per_second": 2166.4754243291823, "speedup": 0.5470009226447372, "max_rank_peak_memory_saving_fraction": 0.5125899057154569}

Qwen3.5-35B-A3B · 完整 40 层单卡(此前运行)

完整 40 层,A5 单卡,batch=1、序列长度 32、预热和计时各一次。正式推理入口完成 BF16 对照、量化推理、checkpoint 保存及恢复、logits 对比和 4 token 生成。以下为 summary.json 指标摘录,单次计时仅用于功能验证。

{"stage": "bf16", "ms_per_step": 524.4496699888259, "peak_allocated_bytes": [69355939328]}
{"stage": "quantized", "ms_per_step": 194.90870996378362, "peak_allocated_bytes": [19974686208]}

Qwen3.5-35B-A3B · 两层单卡(提交 12279988)

Qwen3.5-35B-A3B 原始层 0、3 的真实权重,单卡,batch 1,序列长 32,预热和计时各 1 次。推理样例完成 BF16 对照、量化推理、checkpoint 恢复、logits 比对和 4 token 生成。以下摘录本次 summary.json 的计时字段,单位为毫秒,仅用于识别已完成的阶段。

exit_code=0
bf16: {"ms_per_step": 20.226960070431232}
quantized: {"ms_per_step": 10.83251996897161}

完整 40 层 MoE 的八卡 FSDP2 配置尚未完成端到端验证。

【CheckList】

likedislike
Pull Request has been successfully merged by ascend-robot.
(Thank you for Lennon's contribution.)
LennonLennon
Oct 28 Associated issue: [Test]: 补充 FP8 量化训练与 FP8、INT4 QAT 工作流测试
ascend-robotascend-robotCollaborators
Oct 28 Added label: ascend-cla/yes
ascend-robot
ascend-robotCollaborators
Oct 28 Comments:

CLA Signature Pass

ll-pen, thanks for your pull request. All authors of the commits have signed the CLA. 👍

likedislike
ascend-robot
ascend-robotCollaborators
Oct 28 Comments:

Thanks for your pull-request.
The full list of commands accepted by me can be found at here.
You can get sig-info at here.
You can self-configure the PR merge rules for this repository. For more details, please refer to Here.


PR Approval Progress

✅ Congratulations! All modules have met the lgtm and approve requirements.

Module Approval Details

module lgtm status approve status
repo-Ascend/torchao-ascend ✅ wanglijun55, sylvia_wei (2/2) ✅ wanglijun55 (1/1)

💡 Tip:

  • Committer can comment /approve or /lgtm
  • Commenting /approve implies both code review (lgtm) and intent to merge (approve)

CLA Signature Pass

ll-pen, thanks for your pull request. All authors of the commits have signed the CLA. 👍

likedislike
LennonLennon
Oct 31 Modify description of pull request
95 messages are collapsed here。 See more
AtlasAccountAtlasAccountCollaborators
1 day ago Added label: ci-pipeline-passed
ascend-robotascend-robotCollaborators
1 day ago Merged pull request
ascend-robot
ascend-robotCollaborators
1 day ago Comments:

Pull Request 已合并或已关闭。

If you want to solve this problem, you can click here to do it in the FAQs.

likedislike
ascend-robot
ascend-robotCollaborators
1 day ago Comments:

Pull Request 已合并或已关闭。

If you want to solve this problem, you can click here to do it in the FAQs.

likedislike
AtlasAccount
AtlasAccountCollaborators
1 day ago Comments:
流水线 PR-pipeline_torchao_npu#305 [ commitID:c0461f83 ] 已完成
>>>代码风格自动修复执行成功(无修复内容)
阶段 任务名 状态 详情
编译构建 Build_x86 ✅ COMPLETED >>>
恶意代码检查 Antipoison ✅ COMPLETED >>>
编码安全与规范检查 pre-commit ✅ COMPLETED >>>
开源片段检查 SCA ✅ COMPLETED >>>
流水线 PR-pipeline_torchao_npu ✅ COMPLETED >>>
此流水线已支持下列评论快捷指令,仅PR创建者和白名单成员[wujinyuan1, wanglijun55, wss_321]评论有效
  • compile : 运行流水线
  • retry : 重试流水线所有失败子任务
  • retry <任务名> : 仅重试指定失败子任务
  • stop : 停止流水线
likedislike