civic-backup / src /export /quantize_int8.py
khiemdztv's picture
Backup source code and docs
cf29045 verified
Raw History Blame Contribute Delete
1.69 kB
"""T-82 — Lượng tử hoá động INT8 cho CPU."""
from __future__ import annotations
import argparse
from pathlib import Path
from typing import Any, Dict
from ..common.config import add_config_args, load_config
from ..common.io_utils import atomic_save_json
from ..common.logging_utils import Timer, get_logger
LOG = get_logger("quantize_int8")
def quantize(src: str, dst: str) -> Dict[str, Any]:
from onnxruntime.quantization import QuantType, quantize_dynamic
with Timer(LOG, f"lượng tử hoá {Path(src).name}"):
quantize_dynamic(src, dst, weight_type=QuantType.QInt8)
s_mb = Path(src).stat().st_size / 2 ** 20
d_mb = Path(dst).stat().st_size / 2 ** 20
LOG.info("%s: %.1f MB -> %.1f MB (giảm %.0f%%)", Path(dst).name, s_mb, d_mb,
100 * (1 - d_mb / s_mb))
return {"src": src, "dst": dst, "size_fp32_mb": round(s_mb, 1),
"size_int8_mb": round(d_mb, 1), "reduction_pct": round(100 * (1 - d_mb / s_mb), 1)}
def main() -> None:
ap = argparse.ArgumentParser(description="T-82 lượng tử hoá INT8")
add_config_args(ap)
args = ap.parse_args()
cfg = load_config("civic_nlu", args.overrides)
report: Dict[str, Any] = {}
for key, d in (("civic_nlu", cfg["models"]["civic_nlu"]),
("legal_verifier", cfg["models"]["verifier"])):
src = Path(d) / "model.onnx"
if not src.exists():
LOG.warning("Bỏ qua %s — chưa có %s", key, src)
continue
report[key] = quantize(str(src), str(Path(d) / "model_int8.onnx"))
atomic_save_json(f"{cfg['reports']['dir']}/onnx_quantize.json", report)
if __name__ == "__main__":
main()