已合并
feat: 新增 FP8 PTQ 精度评测(对齐上游 lm_eval 流程) #159
feat: 新增 FP8 PTQ 精度评测(对齐上游 lm_eval 流程) #159
已合并
Chun Li创建于 5 天前
共 7 个文件变更+519-0
@@ -10,3 +10,5 @@ dist/
10.eggs/10.eggs/
11*.egg-info/11*.egg-info/
12.DS_Store12.DS_Store
13+benchmarks/.data
14+benchmarks/data
@@ -0,0 +1,65 @@
1+# FP8 PTQ 精度评测(NPU)
2+ 
3+对齐上游 `torchao/benchmarks/quantization/measure_accuracy_and_performance.sh` 的精度评测:create(量化落盘)→ lm_eval(wikitext ppl + winogrande acc 等,paper 可比)。
4+ 
5+## 测什么
6+ 
7+torchao PTQ recipe 的 **lm_eval 精度**:进程内量化或从落盘 ckpt 直载,交给 `HFLM`。recipe 覆盖:上游的 dynamic 系列(`None` 基线 / `float8_rowwise`)。
8+ 
9+## 文件
10+ 
11+| 文件 | 作用 |
12+|---|---|
13+| `measure_accuracy_and_performance.sh` | orchestrator:遍历 recipe → create → eval_accuracy → parse |
14+| `create_quantized_model.py` | load → `quantize_` → 落盘(上游对齐工件:`pytorch_model.bin` 存 pickle 的量化子类权重 + `config.json` 带 `quantization_config` + tokenizer) |
15+| `eval_accuracy.py` | 精度:lm_eval(`--model_path --recipe` in-memory 或 `--ckpt_dir` 直载) |
16+| `utils.py` | 共享:recipe 映射、模型加载/量化(`import torchao_ascend` 激活 NPU patch) |
17+| `parse_log.py` | 汇总 lm_eval 精度表(含 ckpt 体积列、库版本头) |
18+ 
19+## 环境要求
20+ 
21+- 已装 torch / torch_npu / torchao / torchao_ascend / transformers 的 python 环境;精度阶段额外安装 `lm-eval==0.4.13`(`pip install lm-eval==0.4.13`,PyPI 慢时可用国内镜像)。
22+ - ⚠️ lm-eval 的传递依赖会把 **fsspec 2026.9.0 → 2024.9.0、python-dateutil 3.0.0 → 2.9.0** 降级;若随后 datasets / HF 加载异常,将 fsspec 钉回原版本即可恢复。
23+- **实测版本组合**:torch 2.11.0 / torch_npu 2.11.0.post3 / torchao 0.18.0 / torchao_ascend 0.18.0 / transformers 5.21.0(运行日志头会自动记录实际版本;transformers 不钉版,落盘格式一节的 3 个 shim 兼容新旧版本)。
24+- **会话环境变量**(脚本不内置,按需在运行前 export):
25+ - `PYTHONPATH=<仓根>` —— torchao_ascend 未 pip 安装(源码仓直用)时必须;
26+ - `HF_ENDPOINT=https://hf-mirror.com` —— HF Hub 不通时用(lm_eval 任务数据**首次**运行在线下载);之后缓存于 `~/.cache/huggingface`,加 `HF_HUB_OFFLINE=1` 可完全离线运行;
27+ - `TORCH_DEVICE_BACKEND_AUTOLOAD=0` —— torch import 报 `Failed to load the backend extension: torchao_npu` 时(旧 editable 安装残留触发);
28+ - CANN:非交互 shell(如 ssh 直跑)需先 `source <cann路径>/set_env.sh`(`.bashrc` 不会加载)。
29+ 
30+## 用法(仓根目录)
31+ 
32+```bash
33+# 默认 None(bf16 基线) + float8_rowwise
34+MODEL_ID=/path/to/Qwen2.5-7B \
35+ bash benchmarks/quantization/measure_accuracy_and_performance.sh
36+ 
37+# 单 recipe / 限样本数快跑
38+LIMIT=500 MODEL_ID=... \
39+ bash benchmarks/quantization/measure_accuracy_and_performance.sh float8_rowwise
40+ 
41+# 或单独调用
42+python benchmarks/quantization/eval_accuracy.py \
43+ --model_path /path/to/bf16 --recipe float8_rowwise \
44+ --tasks wikitext,winogrande --device npu:0
45+```
46+ 
47+`SKIP_CREATE` / `SKIP_LM_EVAL`(镜像上游旗标)、`CARD`(默认 0)、`DATA_DIR`、`LOG_FILE` 可用环境变量覆盖,详见 sh 头注释。
48+ 
49+## Qwen2.5-7B-Instruct 实测(Ascend 950DT,lm_eval limit 500)
50+ 
51+| | winogrande acc | wikitext word_ppl | bits_per_byte | ckpt 大小 |
52+|---|---|---|---|---|
53+| BF16 | 0.740 (±0.020) | 9.404 | 0.605 | 15.24 GB |
54+| FP8 rowwise | 0.744 (±0.020) | 9.643 | 0.611 | 8.18 GB |
55+ 
56+→ **精度持平**(winogrande 在 stderr 内;ppl Δ +2.5% word / +1.1% bits);权重体积 0.54x(上游 Llama-3.1-8B 表为 16.1 → 9.1 GB,同量级)。
57+ 
58+## 落盘格式(上游对齐)
59+ 
60+`pytorch_model.bin` pickle 保存 Float8Tensor 子类权重,`config.json` 记录 `quantization_config`;加载走 `from_pretrained`,transformers quantizer 触发的 `quantize_` 对已量子类权重是 **no-op**(torchao 显式行为)——**量化值零重算**(NPU 实测 logits 逐位一致)。与上游 `save_pretrained(safe_serialization=False)` 相比有 3 个环境 shim(根因都是新版 transformers(实测 5.21.0)+ wrapper 子类,非 NPU 特有,CUDA 同版本同样触发;详见 `create_quantized_model.py` 内 Gap 1/2/3 注释):①量化在加载后手动做(该版本 quantize-at-load 会被 loading report raise);②`torch.save` 直写(`save_pretrained` 的 tied-weights 清理对无 storage 的 wrapper 子类调 `storage_ptr` 崩溃);③保存的 config 里 `tie_word_embeddings=False`(`tie_weights` 用 `aten.equal` 比较共享权重,Float8Tensor 未实现;两份权重在 bin 中仍是同一 pickle 对象)。
61+ 
62+## 注意 / 后续
63+ 
64+- **NaN**:若任务分数异常,多为某层 FP8 量化发散(lm_head / attention)。在 `utils.quantize_model` 的 `quantize_` 处加 `filter_fn` 排查排除。
65+- **后续计划**:throughput 性能评测(HF 前向计时);vllm-ascend serving 性能因 Ascend 950DT 无 torchao rowwise 执行路径暂缓。
@@ -0,0 +1,115 @@
1+# Copyright (c) 2026, Huawei Technologies Co., Ltd
2+ 
3+"""Load a HF causal LM, apply a torchao PTQ recipe, save to disk.
4+ 
5+NPU adaptation of ``torchao/benchmarks/quantization/create_quantized_model.py``.
6+The saved artifact matches upstream's: ``pytorch_model.bin`` holding pickled
7+Float8Tensor subclass weights, ``config.json`` carrying the ``TorchAoConfig``
8+quantization config (so a subsequent ``from_pretrained`` restores the quantized
9+weights directly -- the transformers quantizer's ``quantize_`` call is a no-op
10+on already-quantized weights), and the tokenizer files.
11+ 
12+Three deviations from upstream's exact code ("gaps"), all rooted in the new
13+transformers (validated on 5.21.0) + wrapper-subclass weights -- not
14+NPU-specific: CUDA with the same transformers version hits them too. Upstream
15+leaves transformers unpinned (dev-requirements.txt) and does not run these
16+benchmark scripts in CI, so this code path is unexercised there on
17+transformers 5.x:
18+ 
19+1. ``quantize_`` runs post-load, on the NPU device, instead of upstream's
20+ ``from_pretrained(quantization_config=...)`` quantize-at-load: transformers
21+ 5.21.0 raises RuntimeError in its loading report on that flow. Also, the
22+ torchao_ascend from_hp patch routes to npu_dynamic_quant,
23+ which has no CPU backend, so quantization must run on the device;
24+2. the state dict is written via ``torch.save`` directly: ``save_pretrained``
25+ runs its tied-weights cleanup (``id_tensor_storage`` -> safetensors
26+ ``storage_ptr``), which crashes on Float8Tensor because wrapper subclasses
27+ carry no storage;
28+3. ``tie_word_embeddings=False`` in the saved config: ``tie_weights`` compares
29+ tied params with ``aten.equal``, unimplemented for Float8Tensor. Both tied
30+ keys still land in the bin as the same pickled object, so values stay
31+ shared after load.
32+ 
33+Each deviation carries a short "Gap N/3" comment at its site.
34+ 
35+A tiny ``meta.json`` records {base_model, recipe} for benchmark result
36+labeling only.
37+ 
38+Usage (run from the repo root; the sibling ``utils`` module imports
39+``torch_npu``/``torchao_ascend``, so the patches are active)::
40+ 
41+ python benchmarks/quantization/create_quantized_model.py \
42+ --model_id /path/to/Qwen2.5-7B --quant_recipe_name float8_rowwise \
43+ --output_dir benchmarks/data/quantized_model/Qwen2.5-7B-float8_rowwise
44+"""
45+from __future__ import annotations
46+ 
47+import argparse
48+import json
49+import os
50+ 
51+import torch
52+from transformers import AutoModelForCausalLM, AutoTokenizer, TorchAoConfig
53+ 
54+from utils import get_size_of_dir, quantize_model, string_to_config
55+ 
56+ 
57+def quantize_model_and_save(model_id, recipe, output_dir, device, dtype):
58+ print(f"Quantizing {model_id} with recipe: {recipe}")
59+ # Gap 1/3 (see module docstring): quantize post-load, on the NPU device.
60+ model = AutoModelForCausalLM.from_pretrained(model_id, dtype=dtype).to(device)
61+ model.eval()
62+ tokenizer = AutoTokenizer.from_pretrained(model_id)
63+ 
64+ # quantize_model targets every nn.Linear by default (matches upstream
65+ # ``float8_rowwise`` via TorchAoConfig, including attention projections +
66+ # lm_head). If a layer NaNs, restrict it with a filter_fn there.
67+ model = quantize_model(model, recipe, device)
68+ 
69+ if recipe not in (None, "None"):
70+ config = string_to_config(recipe)
71+ model.config.quantization_config = TorchAoConfig(quant_type=config)
72+ # Gap 3/3 (see module docstring): disable config-level tying.
73+ model.config.tie_word_embeddings = False
74+ 
75+ model = model.cpu()
76+ os.makedirs(output_dir, exist_ok=True)
77+ # Gap 2/3 (see module docstring): torch.save directly, not save_pretrained.
78+ torch.save(model.state_dict(), os.path.join(output_dir, "pytorch_model.bin"))
79+ model.config.save_pretrained(output_dir)
80+ tokenizer.save_pretrained(output_dir)
81+ with open(os.path.join(output_dir, "meta.json"), "w") as fh:
82+ json.dump({"base_model": model_id, "recipe": recipe}, fh, indent=2)
83+ return model, tokenizer
84+ 
85+ 
86+def run(model_id, quant_recipe_name, model_output_dir, device, dtype):
87+ print(f"\nRunning {model_id=} with {quant_recipe_name=}\n")
88+ quantize_model_and_save(
89+ model_id, quant_recipe_name, model_output_dir, device, dtype,
90+ )
91+ size_gb = get_size_of_dir(model_output_dir) / 1e9
92+ print(f"saved {model_id} ({quant_recipe_name}) to {model_output_dir}")
93+ print(f"checkpoint size: {size_gb:.2f} GB")
94+ 
95+ 
96+if __name__ == "__main__":
97+ p = argparse.ArgumentParser(
98+ description="Load a HF model, quantize it with a torchao recipe, save to disk."
99+ )
100+ p.add_argument("--model_id", type=str, required=True,
101+ help="bf16 base model dir")
102+ p.add_argument(
103+ "--quant_recipe_name", type=str, default="float8_rowwise",
104+ help="'None' = bf16 baseline, 'float8_rowwise' = dynamic FP8 PTQ",
105+ )
106+ p.add_argument("--output_dir", type=str, required=True)
107+ p.add_argument("--device", type=str, default="npu")
108+ p.add_argument(
109+ "--dtype", type=str, default="bfloat16",
110+ choices=["bfloat16", "float16", "float32"],
111+ )
112+ args = p.parse_args()
113+ dtype = getattr(torch, args.dtype)
114+ device = torch.device(args.device)
115+ run(args.model_id, args.quant_recipe_name, args.output_dir, device, dtype)
@@ -0,0 +1,76 @@
1+# Copyright (c) 2026, Huawei Technologies Co., Ltd
2+ 
3+"""lm_eval accuracy eval (upstream-standard) for PTQ on NPU.
4+ 
5+The accuracy stage of the benchmark, matching upstream
6+``torchao/benchmarks/quantization/measure_accuracy_and_performance.sh``:
7+lm_eval tasks (wikitext ppl + winogrande acc, paper-comparable).
8+ 
9+Two model sources, both handing a live model to ``HFLM(pretrained=model)``
10+(lm_eval accepts a ``PreTrainedModel`` object, not just a path):
11+- ``--model_path`` + ``--recipe``: load bf16 + ``quantize_`` in-memory;
12+- ``--ckpt_dir``: ``from_pretrained`` on a checkpoint saved by
13+ ``create_quantized_model.py`` -- the pickled Float8Tensor weights are
14+ restored directly (the config.json ``quantization_config`` makes the
15+ quantizer's ``quantize_`` call a no-op), matching the upstream
16+ create -> eval round-trip with no re-quantization.
17+ 
18+The sibling ``utils`` module imports ``torchao_ascend`` (and ``torch_npu``),
19+so the NPU device and the Float8Tensor patches are active for both the
20+quantize step and the forward passes.
21+ 
22+NPU device quirk: lm_eval's valid-device list contains indexed devices
23+(e.g. ``npu:0``) but not bare ``npu``, so an indexed form is required.
24+"""
25+import argparse
26+ 
27+import torch
28+import lm_eval
29+from lm_eval.models.huggingface import HFLM
30+ 
31+from utils import load_model, quantize_model, recipe_from_meta
32+ 
33+ 
34+def run(args):
35+ device = torch.device(args.device)
36+ dtype = getattr(torch, args.dtype)
37+ if args.ckpt_dir:
38+ # upstream load: from_pretrained restores the quantized weights directly
39+ # (quantize_ no-op); the recipe label travels in meta.json
40+ model, tokenizer = load_model(args.ckpt_dir, None, device, dtype)
41+ args.recipe = recipe_from_meta(args.ckpt_dir)
42+ else:
43+ model, tokenizer = load_model(args.model_path, None, device, dtype)
44+ model = quantize_model(model, args.recipe, device)
45+ 
46+ # Hand the live (optionally quantized) model to lm_eval's HFLM. HFLM accepts
47+ # a PreTrainedModel object via `pretrained=` (skips from_pretrained).
48+ hl = HFLM(pretrained=model, tokenizer=tokenizer, device=args.device, batch_size=args.batch_size)
49+ tasks = [t.strip() for t in args.tasks.split(",") if t.strip()]
50+ res = lm_eval.simple_evaluate(model=hl, tasks=tasks, limit=args.limit)
51+ src = args.ckpt_dir or args.model_path
52+ print(f"[lm_eval] model={src} recipe={args.recipe} device={args.device}")
53+ for task, metrics in res["results"].items():
54+ for m, v in metrics.items():
55+ if isinstance(v, (int, float)) and not m.endswith("_stderr"):
56+ print(f"[lm_eval] task={task} {m}={v}")
57+ 
58+ 
59+if __name__ == "__main__":
60+ p = argparse.ArgumentParser(description="lm_eval accuracy on NPU (upstream-standard).")
61+ p.add_argument("--model_path", help="BF16 model dir (quantized in-memory)")
62+ p.add_argument("--ckpt_dir", default=None,
63+ help="checkpoint dir saved by create_quantized_model.py "
64+ "(restored, not re-quantized)")
65+ p.add_argument("--recipe", default="None", help="None / float8_rowwise")
66+ p.add_argument("--tasks", default="wikitext,winogrande",
67+ help="comma-separated lm_eval tasks")
68+ p.add_argument("--device", default="npu:0",
69+ help="must be npu:x with a device index (not bare npu)")
70+ p.add_argument("--dtype", default="bfloat16", choices=["bfloat16", "float16"])
71+ p.add_argument("--batch_size", type=int, default=1)
72+ p.add_argument("--limit", type=int, default=None)
73+ args = p.parse_args()
74+ if not args.ckpt_dir and not args.model_path:
75+ p.error("one of --model_path / --ckpt_dir is required")
76+ run(args)
@@ -0,0 +1,83 @@
1+# Copyright (c) 2026, Huawei Technologies Co., Ltd
2+ 
3+# measure_accuracy_and_performance.sh - PTQ accuracy eval (lm_eval), mirroring
4+# torchao/benchmarks/quantization/measure_accuracy_and_performance.sh:
5+# per recipe, create the quantized checkpoint, then run lm_eval on it.
6+#
7+# Recipes: upstream's dynamic set (None, float8_rowwise).
8+# The throughput stage is a planned follow-up.
9+#
10+# Usage (from the repo root):
11+# MODEL_ID=/path/to/Qwen2.5-7B \
12+# bash benchmarks/quantization/measure_accuracy_and_performance.sh
13+# bash benchmarks/quantization/measure_accuracy_and_performance.sh float8_rowwise
14+#
15+# Env:
16+# MODEL_ID bf16 base model dir (required)
17+# TASKS lm_eval tasks (default "wikitext,winogrande")
18+# LIMIT lm_eval per-task sample limit (default: full)
19+# DATA_DIR ckpt output dir (default benchmarks/data/quantized_model;
20+# point elsewhere, e.g. /tmp, if the repo disk is tight)
21+# SKIP_CREATE=1 / SKIP_LM_EVAL=1 mirror upstream skip flags
22+# CARD ASCEND_RT_VISIBLE_DEVICES (default 0)
23+# LOG_FILE (default benchmarks/data/measure_log.txt)
24+#
25+# Session env (NOT set here; see README 环境要求): HF_ENDPOINT for an HF mirror
26+# when the Hub is unreachable, and TORCH_DEVICE_BACKEND_AUTOLOAD=0 when an old
27+# torchao_npu editable install triggers a backend-autoload error.
28+ 
29+set -e
30+cd "$(dirname "$0")/../.." # repo root, so relative output dirs land right
31+ 
32+if [ $# -eq 0 ]; then
33+ RECIPES="None float8_rowwise"
34+else
35+ RECIPES="$*"
36+fi
37+ 
38+MODEL_ID="${MODEL_ID:?set MODEL_ID=<bf16 model dir>}"
39+TASKS="${TASKS:-wikitext,winogrande}"
40+LIMIT="${LIMIT:-}"
41+DATA_DIR="${DATA_DIR:-benchmarks/data/quantized_model}"
42+CARD="${CARD:-0}"
43+# lm_eval requires an indexed device (not bare "npu"); with
44+# ASCEND_RT_VISIBLE_DEVICES set, logical device 0 IS the card selected by CARD.
45+DEVICE=npu:0
46+LOG_FILE="${LOG_FILE:-benchmarks/data/measure_log.txt}"
47+ 
48+export ASCEND_RT_VISIBLE_DEVICES=$CARD
49+ 
50+LIMIT_ARG=""
51+[ -n "$LIMIT" ] && LIMIT_ARG="--limit $LIMIT"
52+ 
53+mkdir -p "$(dirname "$LOG_FILE")" "$DATA_DIR"
54+rm -f "$LOG_FILE"; touch "$LOG_FILE"
55+ 
56+echo "model=$MODEL_ID tasks=$TASKS card=$CARD" | tee -a "$LOG_FILE"
57+ 
58+# library versions for the log header (parsed by parse_log.py)
59+python -c "import torch, torch_npu, torchao, torchao_ascend, transformers; print(f'{torch.__version__=}\n{torch_npu.__version__=}\n{torchao.__version__=}\n{torchao_ascend.__version__=}\n{transformers.__version__=}')" | tee -a "$LOG_FILE"
60+ 
61+for recipe in $RECIPES; do
62+ echo | tee -a "$LOG_FILE"
63+ echo "=== recipe=$recipe ===" | tee -a "$LOG_FILE"
64+ 
65+ OUT="$DATA_DIR/$(basename "$MODEL_ID")-$recipe/"
66+ 
67+ if [ "${SKIP_CREATE:-0}" != "1" ]; then
68+ rm -rf "$OUT"
69+ python -u benchmarks/quantization/create_quantized_model.py \
70+ --model_id "$MODEL_ID" --quant_recipe_name "$recipe" \
71+ --output_dir "$OUT" --device npu \
72+ 2>&1 | tee -a "$LOG_FILE"
73+ else
74+ echo "Skipping model creation (SKIP_CREATE=1), using existing model at $OUT" | tee -a "$LOG_FILE"
75+ fi
76+ 
77+ if [ "${SKIP_LM_EVAL:-0}" != "1" ]; then
78+ python -u benchmarks/quantization/eval_accuracy.py \
79+ --ckpt_dir "$OUT" --tasks "$TASKS" $LIMIT_ARG --device $DEVICE 2>&1 | tee -a "$LOG_FILE"
80+ fi
81+done
82+ 
83+python benchmarks/quantization/parse_log.py "$LOG_FILE"
@@ -0,0 +1,93 @@
1+# Copyright (c) 2026, Huawei Technologies Co., Ltd
2+ 
3+"""Parse the benchmark log and print the lm_eval accuracy summary table.
4+ 
5+Input lines:
6+- ``mod.__version__='v'`` header lines from the sh's version probe;
7+- per-recipe ``checkpoint size: N GB`` lines from ``create_quantized_model.py``;
8+- ``[lm_eval] model=... recipe=X`` followed by ``[lm_eval] task=T metric=v``
9+ lines emitted by ``eval_accuracy.py``.
10+"""
11+from __future__ import annotations
12+ 
13+import argparse
14+import re
15+import sys
16+ 
17+_LM_HEADER = re.compile(r"\[lm_eval\] model=\S+ recipe=(\S+)")
18+_LM_METRIC = re.compile(r"\[lm_eval\] task=(\S+) (\S+?)=([0-9.eE+-]+)")
19+_VERSION = re.compile(r"(\S+)\.__version__='([^']+)'")
20+_CKPT_GB = re.compile(r"checkpoint size:\s+([\d.]+)\s+GB")
21+ 
22+ 
23+def parse(log_text: str):
24+ """Return (versions, {recipe: {"ckpt_gb"?, "task.metric": value}})."""
25+ versions: dict = {}
26+ acc: dict = {}
27+ cur = None
28+ pending_ckpt = None
29+ for line in log_text.splitlines():
30+ m = _VERSION.search(line)
31+ if m:
32+ versions[m.group(1)] = m.group(2)
33+ continue
34+ m = _CKPT_GB.search(line)
35+ if m:
36+ # emitted between the recipe header and its [lm_eval] block
37+ pending_ckpt = float(m.group(1))
38+ continue
39+ m = _LM_HEADER.search(line)
40+ if m:
41+ cur = m.group(1)
42+ row = acc.setdefault(cur, {})
43+ if pending_ckpt is not None:
44+ row["ckpt_gb"] = pending_ckpt
45+ pending_ckpt = None
46+ continue
47+ m = _LM_METRIC.search(line)
48+ if m and cur:
49+ metric = m.group(2).split(",")[0]
50+ if metric == "sample_len" or metric.endswith("stderr"):
51+ continue # noise columns
52+ acc[cur][f"{m.group(1)}.{metric}"] = float(m.group(3))
53+ return versions, acc
54+ 
55+ 
56+def _f(x, decimals=4):
57+ return f"{x:.{decimals}f}" if isinstance(x, float) else str(x)
58+ 
59+ 
60+def summarize(versions: dict, acc: dict) -> None:
61+ if not acc:
62+ print("no [lm_eval] lines found")
63+ return
64+ if versions:
65+ print("versions: " + " ".join(f"{k}={v}" for k, v in versions.items()))
66+ cols = sorted({k for m in acc.values() for k in m if k != "ckpt_gb"})
67+ if any("ckpt_gb" in m for m in acc.values()):
68+ cols = ["ckpt_gb"] + cols
69+ width = max([16] + [len(c) + 2 for c in cols])
70+ print(f"\n{'=' * 90}")
71+ print("=== accuracy (lm_eval) ===\n")
72+ hdr = f"{'recipe':<18}" + "".join(f"{c:>{width}}" for c in cols)
73+ print(hdr)
74+ print("-" * len(hdr))
75+ for recipe in sorted(acc, key=lambda r: (r == "None", r)):
76+ cells = []
77+ for c in cols:
78+ decimals = 2 if c == "ckpt_gb" else 4
79+ v = acc[recipe].get(c, float("nan"))
80+ cells.append(f"{_f(v, decimals):>{width}}")
81+ print(f"{recipe:<18}" + "".join(cells))
82+ 
83+ 
84+if __name__ == "__main__":
85+ p = argparse.ArgumentParser()
86+ p.add_argument("log_file", nargs="?", default="benchmarks/data/measure_log.txt")
87+ args = p.parse_args()
88+ try:
89+ with open(args.log_file) as fh:
90+ summarize(*parse(fh.read()))
91+ except FileNotFoundError:
92+ print(f"log not found: {args.log_file}", file=sys.stderr)
93+ sys.exit(1)
@@ -0,0 +1,85 @@
1+# Copyright (c) 2026, Huawei Technologies Co., Ltd
2+ 
3+"""Shared helpers for the PTQ accuracy (lm_eval) benchmark.
4+ 
5+Imports ``torch_npu`` / ``torchao_ascend`` on load so every entry point
6+(create_quantized_model.py, eval_accuracy.py) gets the NPU device and the
7+Float8Tensor patches activated before any quantize_/forward runs.
8+"""
9+from __future__ import annotations
10+ 
11+import json
12+import subprocess
13+ 
14+import torch # noqa: F401 -- imported first; torch_npu builds on it
15+import torch_npu # noqa: F401 -- registers the npu device
16+import torchao_ascend # noqa: F401 -- activates the Float8Tensor patch
17+from torchao.quantization import (
18+ Float8DynamicActivationFloat8WeightConfig,
19+ PerRow,
20+ quantize_,
21+)
22+from transformers import AutoModelForCausalLM, AutoTokenizer
23+ 
24+ 
25+def string_to_config(s: str | None):
26+ """Map a recipe name to an AOBaseConfig (``None`` = bf16 baseline)."""
27+ if s in (None, "None"):
28+ return None
29+ if s == "float8_rowwise":
30+ # Dynamic-activation FP8 PTQ (W8A8): weight scale fixed at quantize_
31+ # time, activation scale recomputed every forward via npu_dynamic_quant
32+ # (NPU patch on Float8Tensor.from_hp, activated by ``import torchao_ascend``).
33+ return Float8DynamicActivationFloat8WeightConfig(granularity=PerRow())
34+ # TODO: add float8_static (prepare -> calibrate -> convert) in a follow-up
35+ # change.
36+ raise AssertionError(f"unsupported recipe {s!r}")
37+ 
38+ 
39+def get_size_of_dir(model_output_dir: str) -> int:
40+ """Dir size in bytes via shell (skip tensor introspection)."""
41+ result = subprocess.run(
42+ ["du", "-sb", model_output_dir], capture_output=True, text=True
43+ )
44+ return int(result.stdout.split()[0])
45+ 
46+ 
47+def recipe_from_meta(model_dir: str) -> str:
48+ """Recipe label recorded by ``create_quantized_model.py``.
49+ 
50+ Labeling only: the loadable artifact is the upstream-style
51+ ``pytorch_model.bin`` + ``config.json`` (quantization_config) pair.
52+ """
53+ try:
54+ with open(f"{model_dir}/meta.json") as fh:
55+ return json.load(fh).get("recipe", "ckpt")
56+ except (FileNotFoundError, json.JSONDecodeError):
57+ return "ckpt"
58+ 
59+ 
60+# ---------------- model load / quantize (shared by create + eval) ----------------
61+ 
62+def load_model(model_dir, model_id, device, dtype):
63+ """Load a causal LM from a checkpoint dir or a bf16 base dir."""
64+ src = model_dir if model_dir else model_id
65+ model = AutoModelForCausalLM.from_pretrained(src, dtype=dtype)
66+ model = model.to(device).eval()
67+ print(f"[load] model on {device}, dtype={dtype}", flush=True)
68+ tokenizer = AutoTokenizer.from_pretrained(src)
69+ return model, tokenizer
70+ 
71+ 
72+def quantize_model(model, recipe, device):
73+ """Apply quantization in place.
74+ 
75+ Dynamic recipes (``float8_rowwise``) are 1-phase:
76+ ``quantize_`` swaps each nn.Linear weight for a Float8Tensor subclass and
77+ must run on the NPU device (the from_hp patch has no CPU backend).
78+ """
79+ if not recipe or recipe == "None":
80+ return model
81+ print(f"[load] applying quantize_ ({recipe}) ...", flush=True)
82+ quantize_(model, string_to_config(recipe))
83+ model = model.to(device) # re-land after weight subclass swap
84+ print("[load] quantize_ done", flush=True)
85+ return model