Open
【11月贡献大赛-缺陷修复】fix(w8a8-llm-quant-npu): [Bug] compute scale product in fp32, drop consumed weight_scale keys, and support sharded safetensors in dequantize_w8a8.py #7334
liuhongweiAdd on 7 hours ago
【11月贡献大赛-缺陷修复】fix(w8a8-llm-quant-npu): [Bug] compute scale product in fp32, drop consumed weight_scale keys, and support sharded safetensors in dequantize_w8a8.py #7334
Open
Total: 2 files changed+173-20
| @@ -2,7 +2,7 @@ | |||
| 2 | # -*- coding: utf-8 -*- | 2 | # -*- coding: utf-8 -*- |
| 3 | """ | 3 | """ |
| 4 | W8A8(compressed-tensors 格式)LLM 权重离线反量化脚本 | 4 | W8A8(compressed-tensors 格式)LLM 权重离线反量化脚本 |
| 5 | -==================================================== | 5 | +---------------------------------------------------- |
| 6 | 将公开 W8A8 量化权重(int8 权重 + per-tensor scale)离线反量化为 fp16/bf16 | 6 | 将公开 W8A8 量化权重(int8 权重 + per-tensor scale)离线反量化为 fp16/bf16 |
| 7 | 普通权重,供昇腾 NPU 直接加载推理(transformers + torch_npu 路线)。 | 7 | 普通权重,供昇腾 NPU 直接加载推理(transformers + torch_npu 路线)。 |
| 8 | 8 | ||
| @@ -16,6 +16,7 @@ W8A8(compressed-tensors 格式)LLM 权重离线反量化脚本 | |||
| 16 | python dequantize_w8a8.py --src <量化权重目录> --dst <输出目录> | 16 | python dequantize_w8a8.py --src <量化权重目录> --dst <输出目录> |
| 17 | """ | 17 | """ |
| 18 | import argparse | 18 | import argparse |
| 19 | +import glob | ||
| 19 | import json | 20 | import json |
| 20 | import os | 21 | import os |
| 21 | import shutil | 22 | import shutil |
| @@ -23,8 +24,42 @@ import shutil | |||
| 23 | import torch | 24 | import torch |
| 24 | 25 | ||
| 25 | 26 | ||
| 27 | +def _find_weight_shards(src: str) -> list: | ||
| 28 | + """定位单分片 model.safetensors 或多分片 model-*.safetensors 权重文件。""" | ||
| 29 | + single = os.path.join(src, "model.safetensors") | ||
| 30 | + if os.path.isfile(single): | ||
| 31 | + return [single] | ||
| 32 | + shards = sorted(glob.glob(os.path.join(src, "model-*.safetensors"))) | ||
| 33 | + if not shards: | ||
| 34 | + raise FileNotFoundError(f"未在目录中找到 model.safetensors 或 model-*.safetensors: {src}") | ||
| 35 | + return shards | ||
| 36 | + | ||
| 37 | + | ||
| 38 | +def _index_shards_and_consumed_scales(shards: list, safe_open) -> tuple: | ||
| 39 | + """预扫描所有分片,构建 key -> 分片路径索引,并收集将被 int8 权重消费的 weight_scale 键。""" | ||
| 40 | + key_to_shard = {} | ||
| 41 | + int8_weight_keys = [] | ||
| 42 | + for sp in shards: | ||
| 43 | + with safe_open(sp, framework="pt") as f: | ||
| 44 | + for k in f.keys(): | ||
| 45 | + key_to_shard[k] = sp | ||
| 46 | + if k.endswith(".weight") and f.get_slice(k).get_dtype() == "I8": | ||
| 47 | + int8_weight_keys.append(k) | ||
| 48 | + consumed_scales = { | ||
| 49 | + scale_key | ||
| 50 | + for k in int8_weight_keys | ||
| 51 | + for scale_key in (k[: -len(".weight")] + ".weight_scale",) | ||
| 52 | + if scale_key in key_to_shard | ||
| 53 | + } | ||
| 54 | + return key_to_shard, consumed_scales | ||
| 55 | + | ||
| 56 | + | ||
| 26 | def dequantize_model(src: str, dst: str): | 57 | def dequantize_model(src: str, dst: str): |
| 27 | """读取 safetensors,反量化 int8 权重到 fp16/bf16,写入普通权重目录。""" | 58 | """读取 safetensors,反量化 int8 权重到 fp16/bf16,写入普通权重目录。""" |
| 59 | + if os.path.realpath(src) == os.path.realpath(dst): | ||
| 60 | + raise ValueError(f"输入目录与输出目录不能相同: {src}") | ||
| 61 | + shards = _find_weight_shards(src) | ||
| 62 | + | ||
| 28 | os.makedirs(dst, exist_ok=True) | 63 | os.makedirs(dst, exist_ok=True) |
| 29 | from safetensors import safe_open | 64 | from safetensors import safe_open |
| 30 | from safetensors.torch import save_file | 65 | from safetensors.torch import save_file |
| @@ -35,27 +70,48 @@ def dequantize_model(src: str, dst: str): | |||
| 35 | if os.path.isfile(sp) and not name.endswith(".safetensors"): | 70 | if os.path.isfile(sp) and not name.endswith(".safetensors"): |
| 36 | shutil.copy2(sp, os.path.join(dst, name)) | 71 | shutil.copy2(sp, os.path.join(dst, name)) |
| 37 | cfg_path = os.path.join(dst, "config.json") | 72 | cfg_path = os.path.join(dst, "config.json") |
| 38 | - with open(cfg_path, encoding="utf-8") as f: | 73 | + if os.path.isfile(cfg_path): |
| 39 | - cfg = json.load(f) | 74 | + with open(cfg_path, encoding="utf-8") as f: |
| 40 | - cfg.pop("quantization_config", None) | 75 | + cfg = json.load(f) |
| 41 | - with open(cfg_path, "w", encoding="utf-8") as f: | 76 | + cfg.pop("quantization_config", None) |
| 42 | - json.dump(cfg, f, indent=2) | 77 | + with open(cfg_path, "w", encoding="utf-8") as f: |
| 78 | + json.dump(cfg, f, indent=2) | ||
| 43 | 79 | ||
| 44 | - sf_path = os.path.join(src, "model.safetensors") | 80 | + key_to_shard, consumed_scales = _index_shards_and_consumed_scales(shards, safe_open) |
| 45 | - tensors = {} | ||
| 46 | n_int8 = 0 | 81 | n_int8 = 0 |
| 47 | - with safe_open(sf_path, framework="pt") as f: | 82 | + for sp in shards: |
| 48 | - for k in f.keys(): | 83 | + tensors = {} |
| 49 | - t = f.get_tensor(k) | 84 | + with safe_open(sp, framework="pt") as f: |
| 50 | - if t.dtype == torch.int8: | 85 | + shard_keys = list(f.keys()) |
| 51 | - # 该层有对应的 weight_scale(per-tensor) | 86 | + for k in shard_keys: |
| 52 | - scale_key = k.replace(".weight", ".weight_scale") | 87 | + if k in consumed_scales: |
| 53 | - if scale_key in f.keys(): | 88 | + continue |
| 54 | - scale = f.get_tensor(scale_key) | 89 | + t = f.get_tensor(k) |
| 55 | - t = t.to(torch.float16) * scale.float().to(torch.float16) | 90 | + if t.dtype == torch.int8 and k.endswith(".weight"): |
| 56 | - n_int8 += 1 | 91 | + scale_key = k[: -len(".weight")] + ".weight_scale" |
| 57 | - tensors[k] = t.contiguous() | 92 | + scale_shard = key_to_shard.get(scale_key) |
| 58 | - save_file(tensors, os.path.join(dst, "model.safetensors")) | 93 | + if scale_shard is not None: |
| 94 | + if scale_shard == sp: | ||
| 95 | + scale = f.get_tensor(scale_key) | ||
| 96 | + else: | ||
| 97 | + with safe_open(scale_shard, framework="pt") as sf: | ||
| 98 | + scale = sf.get_tensor(scale_key) | ||
| 99 | + t = (t.float() * scale.float()).to(torch.float16) | ||
| 100 | + n_int8 += 1 | ||
| 101 | + tensors[k] = t.contiguous() | ||
| 102 | + save_file(tensors, os.path.join(dst, os.path.basename(sp))) | ||
| 103 | + | ||
| 104 | + index_path = os.path.join(dst, "model.safetensors.index.json") | ||
| 105 | + if os.path.isfile(index_path) and consumed_scales: | ||
| 106 | + with open(index_path, encoding="utf-8") as f: | ||
| 107 | + index_data = json.load(f) | ||
| 108 | + weight_map = index_data.get("weight_map") | ||
| 109 | + if isinstance(weight_map, dict): | ||
| 110 | + for sk in consumed_scales: | ||
| 111 | + weight_map.pop(sk, None) | ||
| 112 | + with open(index_path, "w", encoding="utf-8") as f: | ||
| 113 | + json.dump(index_data, f, indent=2) | ||
| 114 | + | ||
| 59 | print(f"[INFO] 反量化完成: int8 层 {n_int8} 个 -> fp16;输出: {dst}") | 115 | print(f"[INFO] 反量化完成: int8 层 {n_int8} 个 -> fp16;输出: {dst}") |
| 60 | 116 | ||
| 61 | 117 | ||
| @@ -0,0 +1,97 @@ | |||
| 1 | +import json | ||
| 2 | +import sys | ||
| 3 | +from pathlib import Path | ||
| 4 | + | ||
| 5 | +import pytest | ||
| 6 | +import torch | ||
| 7 | +from safetensors import safe_open | ||
| 8 | +from safetensors.torch import save_file | ||
| 9 | + | ||
| 10 | +SCRIPT_DIR = Path(__file__).resolve().parents[1] / "scripts" | ||
| 11 | +sys.path.insert(0, str(SCRIPT_DIR)) | ||
| 12 | + | ||
| 13 | +import dequantize_w8a8 as dq # noqa: E402 | ||
| 14 | + | ||
| 15 | + | ||
| 16 | +def test_small_scale_fp32_product_and_weight_scale_removed(tmp_path: Path): | ||
| 17 | + src = tmp_path / "src" | ||
| 18 | + dst = tmp_path / "dst" | ||
| 19 | + src.mkdir() | ||
| 20 | + (src / "config.json").write_text( | ||
| 21 | + json.dumps({"model_type": "llama", "quantization_config": {"quant_method": "compressed-tensors"}}), | ||
| 22 | + encoding="utf-8", | ||
| 23 | + ) | ||
| 24 | + save_file( | ||
| 25 | + { | ||
| 26 | + "model.layers.0.weight_proj.weight": torch.tensor([[100, -100]], dtype=torch.int8), | ||
| 27 | + "model.layers.0.weight_proj.weight_scale": torch.tensor([1e-5], dtype=torch.float32), | ||
| 28 | + "model.embed_tokens.weight": torch.tensor([[0.5, 1.5]], dtype=torch.float16), | ||
| 29 | + }, | ||
| 30 | + str(src / "model.safetensors"), | ||
| 31 | + ) | ||
| 32 | + | ||
| 33 | + dq.dequantize_model(str(src), str(dst)) | ||
| 34 | + | ||
| 35 | + cfg = json.loads((dst / "config.json").read_text(encoding="utf-8")) | ||
| 36 | + assert "quantization_config" not in cfg | ||
| 37 | + | ||
| 38 | + with safe_open(str(dst / "model.safetensors"), framework="pt") as f: | ||
| 39 | + keys = set(f.keys()) | ||
| 40 | + assert "model.layers.0.weight_proj.weight_scale" not in keys | ||
| 41 | + w = f.get_tensor("model.layers.0.weight_proj.weight") | ||
| 42 | + assert w.dtype == torch.float16 | ||
| 43 | + assert torch.allclose(w, torch.tensor([[1e-3, -1e-3]], dtype=torch.float16), atol=1e-5) | ||
| 44 | + | ||
| 45 | + | ||
| 46 | +def test_sharded_safetensors_and_index_cleanup(tmp_path: Path): | ||
| 47 | + src = tmp_path / "src_sharded" | ||
| 48 | + dst = tmp_path / "dst_sharded" | ||
| 49 | + src.mkdir() | ||
| 50 | + save_file( | ||
| 51 | + { | ||
| 52 | + "layer0.weight": torch.tensor([[10, 20]], dtype=torch.int8), | ||
| 53 | + "layer0.weight_scale": torch.tensor([0.5], dtype=torch.float32), | ||
| 54 | + }, | ||
| 55 | + str(src / "model-00001-of-00002.safetensors"), | ||
| 56 | + ) | ||
| 57 | + save_file( | ||
| 58 | + { | ||
| 59 | + "layer1.weight": torch.tensor([[4, -4]], dtype=torch.int8), | ||
| 60 | + "layer1.weight_scale": torch.tensor([0.25], dtype=torch.float32), | ||
| 61 | + }, | ||
| 62 | + str(src / "model-00002-of-00002.safetensors"), | ||
| 63 | + ) | ||
| 64 | + (src / "model.safetensors.index.json").write_text( | ||
| 65 | + json.dumps( | ||
| 66 | + { | ||
| 67 | + "metadata": {"total_size": 100}, | ||
| 68 | + "weight_map": { | ||
| 69 | + "layer0.weight": "model-00001-of-00002.safetensors", | ||
| 70 | + "layer0.weight_scale": "model-00001-of-00002.safetensors", | ||
| 71 | + "layer1.weight": "model-00002-of-00002.safetensors", | ||
| 72 | + "layer1.weight_scale": "model-00002-of-00002.safetensors", | ||
| 73 | + }, | ||
| 74 | + } | ||
| 75 | + ), | ||
| 76 | + encoding="utf-8", | ||
| 77 | + ) | ||
| 78 | + | ||
| 79 | + dq.dequantize_model(str(src), str(dst)) | ||
| 80 | + | ||
| 81 | + idx = json.loads((dst / "model.safetensors.index.json").read_text(encoding="utf-8")) | ||
| 82 | + assert "layer0.weight_scale" not in idx["weight_map"] | ||
| 83 | + assert "layer1.weight_scale" not in idx["weight_map"] | ||
| 84 | + assert set(idx["weight_map"].keys()) == {"layer0.weight", "layer1.weight"} | ||
| 85 | + | ||
| 86 | + with safe_open(str(dst / "model-00001-of-00002.safetensors"), framework="pt") as f1: | ||
| 87 | + assert "layer0.weight_scale" not in f1.keys() | ||
| 88 | + assert torch.allclose(f1.get_tensor("layer0.weight"), torch.tensor([[5.0, 10.0]], dtype=torch.float16)) | ||
| 89 | + | ||
| 90 | + | ||
| 91 | +def test_same_path_and_missing_shards_rejected(tmp_path: Path): | ||
| 92 | + empty = tmp_path / "empty" | ||
| 93 | + empty.mkdir() | ||
| 94 | + with pytest.raises(ValueError): | ||
| 95 | + dq.dequantize_model(str(empty), str(empty)) | ||
| 96 | + with pytest.raises(FileNotFoundError): | ||
| 97 | + dq.dequantize_model(str(empty), str(tmp_path / "out")) | ||