File size: 63,094 Bytes
40da26e | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 1198 1199 1200 1201 1202 1203 1204 1205 1206 1207 1208 1209 1210 1211 1212 1213 1214 1215 1216 1217 1218 1219 1220 1221 1222 1223 1224 1225 1226 1227 1228 1229 1230 1231 1232 1233 1234 1235 1236 1237 1238 1239 1240 1241 1242 1243 1244 1245 1246 1247 1248 1249 1250 1251 1252 1253 1254 1255 1256 1257 1258 1259 1260 1261 1262 1263 1264 1265 1266 1267 1268 1269 1270 1271 1272 1273 1274 1275 1276 1277 1278 1279 1280 1281 1282 1283 1284 1285 1286 1287 1288 1289 1290 1291 1292 1293 1294 1295 1296 1297 1298 1299 1300 1301 1302 1303 1304 1305 1306 1307 1308 1309 1310 1311 1312 1313 1314 1315 1316 1317 1318 1319 1320 1321 1322 1323 1324 1325 1326 1327 1328 1329 1330 1331 1332 1333 1334 1335 1336 1337 1338 1339 1340 1341 1342 1343 1344 1345 1346 1347 1348 1349 1350 1351 1352 1353 1354 1355 1356 1357 1358 1359 1360 | #!/usr/bin/env python3
"""PTQ quantization for ONNX embedding models β produces TRT-compatible INT8 Q/DQ ONNX.
Solves Gemma-family NaN problem: implicit TRT INT8/FP8 quantization runs RMSNorm in low
precision β NaN. Explicit Q/DQ nodes place quantization boundaries only around MatMul/Gemm:
Float β [QuantizeLinear] β INT8 β MatMul β [DequantizeLinear] β Float
RMSNorm (outside Q/DQ brackets) β stays in BF16/float β no NaN
TRT reads the Q/DQ nodes directly β no calibrator, no per-layer hint system.
Expected: ~900 emb/s vs 480 emb/s BF16-only.
Usage:
python scripts/quantize_onnx.py --model-dir PATH
python scripts/quantize_onnx.py --model-dir PATH --calib-db db1.db db2.db
python scripts/quantize_onnx.py --model-dir PATH --calib-dir PATH\\ultracode.zig\\projects
Calibration data is pulled from UltraCode graph.db files (entities raw_content + names).
Auto-detects UltraCode projects dir if --calib-db / --calib-dir are omitted.
Output: {model_dir}/onnx/model_int8qdt.onnx
"""
import argparse
import os
import platform
import random
import sqlite3
import subprocess
import sys
# βββ Experimental switches βββββββββββββββββββββββββββββββββββββββββββββββββββ
# 2026-05-19: First FP8 production build showed -21 % vs INT8 (3584 vs 4541
# emb/s). Root cause: ModelOpt's default `disable_mha_qdq=True` keeps all MHA
# inner BMMs in BF16. For FP8 path this is too conservative β INT8 STRONGLY_TYPED
# does NOT disable MHA and wins. Flip this to True to let MHA inner BMMs also
# go through FP8 Q/DQ. RISK: 2026-04-28 NaN was on Gemma softmax/RMSNorm under
# implicit FP8; with explicit Q/DQ around BMMs only (softmax stays in BF16 via
# high_precision_dtype), the NaN path is closed. Validate empirically via the
# first-batch smoke check below before shipping. Hardcoded per
# `feedback_hardcode_over_env_var` β flip a const, rebuild, measure.
EXPERIMENTAL_QUANTIZE_MHA_FP8 = True
import warnings
if hasattr(sys.stdout, "reconfigure"):
sys.stdout.reconfigure(encoding="utf-8", errors="replace")
if hasattr(sys.stderr, "reconfigure"):
sys.stderr.reconfigure(encoding="utf-8", errors="replace")
warnings.filterwarnings("ignore", category=DeprecationWarning)
warnings.filterwarnings("ignore", message=".*onnxruntime.*", category=UserWarning)
# βββ CUDA DLL path fix + auto-install (Windows) ββββββββββββββββββββββββββββββ
def _detect_torch_cuda_major() -> "str | None":
"""PyTorch's CUDA major ('12', '13', β¦), or None on a CPU build.
PyTorch is installed first in every pipeline that reaches this script
(training needs it), so its CUDA version is the source of truth for what the
host driver supports. ONNX Runtime should be matched to THAT, not the other
way round.
"""
try:
import torch
ver = getattr(torch, "version", None)
cuda = getattr(ver, "cuda", None) if ver is not None else None
return cuda.split(".")[0] if cuda else None
except Exception:
return None
def _detect_ort_cuda_suffix_raw() -> str:
"""Read onnxruntime-gpu's declared requirements to find its CUDA channel."""
try:
import importlib.metadata
import re
for pkg_name in ("onnxruntime-gpu", "onnxruntime_gpu"):
try:
reqs = importlib.metadata.requires(pkg_name) or []
for req in reqs:
m = re.search(r"nvidia-cuda-runtime-cu(\d+)", req)
if m:
return m.group(1)
except importlib.metadata.PackageNotFoundError:
continue
except Exception:
pass
return ""
def _ensure_ort_matches_torch_cuda() -> None:
"""Reinstall onnxruntime-gpu on the channel that matches PyTorch's CUDA.
On Blackwell (sm_120) PyTorch is cu130. A mismatched cu12 ORT still loads
through preload_dlls, but the TensorRT execution provider fails to register
and CUDA falls back to a compatibility layer β calibration then runs 15-30%
slower on the very path that PTQ spends all its time in.
"""
torch_cu = _detect_torch_cuda_major()
ort_cu = _detect_ort_cuda_suffix_raw()
if not torch_cu or not ort_cu or torch_cu == ort_cu:
return
print(f" [cuda-ep] PyTorch is cu{torch_cu} but ORT GPU is cu{ort_cu} β "
f"switching ORT to the matching channel")
cmd = [sys.executable, "-m", "pip", "install", "--quiet", "--upgrade",
"onnxruntime-gpu"]
if torch_cu == "13":
# cu13 ORT wheels are not on PyPI; they live on the ONNX Runtime feed.
cmd += ["--extra-index-url",
"https://aiinfra.pkgs.visualstudio.com/PublicPackages/"
"_packaging/onnxruntime-cuda-13/pypi/simple/"]
try:
result = subprocess.run(cmd, capture_output=True, text=True)
if result.returncode == 0:
print(f" [cuda-ep] ORT GPU re-installed for cu{torch_cu}")
else:
print(f" [cuda-ep] WARN: re-install failed: {result.stderr[:300]}")
except Exception as e:
print(f" [cuda-ep] WARN: re-install attempt errored: {e}")
def _detect_ort_cuda_suffix() -> str:
"""The CUDA pip-package suffix to use for every nvidia-* package."""
_ensure_ort_matches_torch_cuda()
return _detect_ort_cuda_suffix_raw() or "12"
def _cuda_ep_packages(cu: str) -> "list[tuple[str, str, str]]":
"""(pip package, nvidia subdirectory, sentinel DLL) for one CUDA suffix.
NVIDIA changed the naming convention at CUDA 13:
cu12 and earlier nvidia-cufft-cu12, nvidia-cublas-cu12, ...
cu13 and later nvidia-cufft, nvidia-cublas, ...
The suffixed variants are deprecated from 13 on, so asking for
`nvidia-cufft-cu13` on a cu13 host installs nothing and the DLL search then
silently falls through to the CPU provider.
DLL filenames follow the CUDA major, except cuFFT whose API version lags by
one (cu13 ships cufft64_12.dll).
"""
cufft_api = str(int(cu) - 1)
if int(cu) >= 13:
return [
("nvidia-cufft", "cufft", f"cufft64_{cufft_api}.dll"),
("nvidia-cublas", "cublas", f"cublas64_{cu}.dll"),
("nvidia-cuda-runtime", "cuda_runtime", f"cudart64_{cu}.dll"),
]
return [
(f"nvidia-cufft-cu{cu}", "cufft", f"cufft64_{cufft_api}.dll"),
(f"nvidia-cublas-cu{cu}", "cublas", f"cublas64_{cu}.dll"),
(f"nvidia-cuda-runtime-cu{cu}", "cuda_runtime", f"cudart64_{cu}.dll"),
]
def _collect_nvidia_bin_dirs() -> list[str]:
"""Return all site-packages/nvidia/*/bin dirs + CUDA Toolkit bin (if present)."""
import site
dirs: list[str] = []
for sp in site.getsitepackages():
nvidia_root = os.path.join(sp, "nvidia")
if not os.path.isdir(nvidia_root):
continue
for pkg in os.listdir(nvidia_root):
bin_dir = os.path.join(nvidia_root, pkg, "bin")
if os.path.isdir(bin_dir):
dirs.append(bin_dir)
# Scan the toolkit root instead of testing a hardcoded version list: that
# list stopped at 12.9, so a CUDA 13 host β every Blackwell box β found no
# toolkit at all and fell back to whatever DLLs happened to be on PATH.
toolkit_root = os.path.join(os.environ.get("ProgramFiles", ""), "NVIDIA GPU Computing Toolkit", "CUDA")
if os.path.isdir(toolkit_root):
versions = []
for name in os.listdir(toolkit_root):
if not name.startswith("v"):
continue
try:
versions.append((tuple(int(p) for p in name[1:].split(".")), name))
except ValueError:
continue
for _key, name in sorted(versions, reverse=True):
cuda_bin = os.path.join(toolkit_root, name, "bin")
if os.path.isdir(cuda_bin):
dirs.append(cuda_bin)
break
cuda_path = os.environ.get("CUDA_PATH")
if cuda_path and os.path.isdir(os.path.join(cuda_path, "bin")):
dirs.append(os.path.join(cuda_path, "bin"))
return dirs
def _dll_exists(dll_name: str, search_dirs: list[str]) -> bool:
for d in search_dirs:
if os.path.isfile(os.path.join(d, dll_name)):
return True
return False
def _setup_cuda_ep() -> None:
"""Ensure ORT CUDA EP DLLs are installed and on PATH (Windows only).
1. Auto-detects which CUDA suffix (cu12/cu13/β¦) onnxruntime-gpu was built against.
2. Scans existing nvidia pip-package bin dirs.
3. Checks sentinel DLLs; pip-installs any missing packages.
4. Rescans after install and prepends all bin dirs to PATH.
"""
if platform.system() != "Windows":
return
cu = _detect_ort_cuda_suffix()
pkgs = _cuda_ep_packages(cu)
dirs = _collect_nvidia_bin_dirs()
missing_pkgs = [pip_pkg for pip_pkg, _, dll in pkgs if not _dll_exists(dll, dirs)]
if missing_pkgs:
print(f" [cuda-ep] ORT built against CUDA cu{cu}. "
f"Installing: {', '.join(missing_pkgs)}")
result = subprocess.run(
[sys.executable, "-m", "pip", "install", "--quiet"] + missing_pkgs,
capture_output=True, text=True,
)
if result.returncode != 0:
print(f" [cuda-ep] WARNING: pip install failed:\n{result.stderr[:400]}")
else:
print(f" [cuda-ep] Installed: {', '.join(missing_pkgs)}")
dirs = _collect_nvidia_bin_dirs() # rescan after install
# Verify
still_missing = [dll for _, _, dll in pkgs if not _dll_exists(dll, dirs)]
if still_missing:
print(f" [cuda-ep] WARNING: DLLs still missing after install: {still_missing}")
else:
print(f" [cuda-ep] OK (cu{cu}): {', '.join(dll for _, _, dll in pkgs)}")
# Prepend all bin dirs to PATH (must happen before `import onnxruntime`)
path_env = os.environ.get("PATH", "")
new_dirs = [d for d in dirs if d not in path_env]
if new_dirs:
os.environ["PATH"] = os.pathsep.join(new_dirs) + os.pathsep + path_env
_setup_cuda_ep()
# βββ Calibration data ββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
def _default_projects_dir():
if platform.system() == "Windows":
base = os.environ.get("LOCALAPPDATA", os.path.expanduser("~"))
elif platform.system() == "Darwin":
base = os.path.expanduser("~/Library/Application Support")
else:
base = os.environ.get("XDG_DATA_HOME", os.path.expanduser("~/.local/share"))
return os.path.join(base, "ultracode.zig", "projects")
def find_calib_dbs(projects_dir):
"""Scan UltraCode projects dir for all graph.db files."""
dbs = []
if not os.path.isdir(projects_dir):
return dbs
for entry in os.scandir(projects_dir):
if entry.is_dir():
db = os.path.join(entry.path, "graph.db")
if os.path.exists(db):
dbs.append(db)
return sorted(dbs)
def _read_file_chunk(path, offset, length=400):
"""Read a slice of a source file, returning clean text or None."""
try:
with open(path, "r", encoding="utf-8", errors="replace") as f:
f.seek(offset)
chunk = f.read(length).strip()
return chunk if len(chunk) >= 10 else None
except Exception:
return None
def collect_texts(db_paths, per_db=80, min_len=10, max_len=400):
"""Collect calibration texts from UltraCode graph.db files.
Strategy (in order of richness):
1. Entity names β always present, covers short-token distribution
(function/class/variable names, 2-15 tokens each)
2. Source file chunks β read via file_path column, covers longer
code blocks (50-128 tokens). Skipped if file not on disk.
Deliberately avoids metadata BLOB (CBOR-encoded, requires cbor2)
and raw_content (column not present in current schema).
"""
texts = []
for db_path in db_paths:
try:
con = sqlite3.connect(f"file:{db_path}?mode=ro", uri=True,
check_same_thread=False)
# 1. Entity names (short texts β always available)
rows = con.execute(
"SELECT name FROM entities "
"WHERE name IS NOT NULL AND length(name) BETWEEN 5 AND 120 "
"ORDER BY RANDOM() LIMIT ?",
(per_db // 2,)
).fetchall()
texts += [r[0] for r in rows]
# 2. Source file chunks (longer texts β read from disk via file_path)
file_rows = con.execute(
"SELECT DISTINCT file_path, size FROM entities "
"WHERE file_path IS NOT NULL AND size > 200 "
"ORDER BY RANDOM() LIMIT ?",
(per_db,)
).fetchall()
file_chunks_added = 0
for (fpath, fsize) in file_rows:
if file_chunks_added >= per_db // 2:
break
if not fpath or not os.path.exists(fpath):
continue
# Sample a random offset within the file (avoid last 400 bytes)
safe_size = max(0, (fsize or 0) - max_len)
offset = random.randint(0, safe_size) if safe_size > 0 else 0
chunk = _read_file_chunk(fpath, offset, max_len)
if chunk and min_len <= len(chunk) <= max_len * 2:
texts.append(chunk[:max_len])
file_chunks_added += 1
con.close()
except Exception as e:
print(f" WARN: skipping {db_path}: {e}")
random.shuffle(texts)
return texts
# βββ Tokenizer βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
def load_tokenizer(model_dir):
"""Load HuggingFace tokenizer. Tries transformers first, falls back to tokenizers."""
try:
from transformers import AutoTokenizer
tok = AutoTokenizer.from_pretrained(model_dir, local_files_only=True)
# Gemma and similar models don't define pad_token (SentencePiece without <pad>).
# Use eos_token as pad β semantically neutral at padding positions for calibration.
if tok.pad_token is None:
tok.pad_token = tok.eos_token
print(" tokenizer backend: transformers")
return ("transformers", tok)
except Exception as e:
print(f" transformers failed ({e}), trying tokenizers library")
tok_path = os.path.join(model_dir, "tokenizer.json")
if not os.path.exists(tok_path):
raise FileNotFoundError(
f"tokenizer.json not found in {model_dir}. "
"Install transformers or provide tokenizer.json."
)
from tokenizers import Tokenizer
tok = Tokenizer.from_file(tok_path)
print(" tokenizer backend: tokenizers (raw)")
return ("tokenizers_raw", tok)
def tokenize(tok_tuple, texts, max_seq):
"""Tokenize list of texts -> (input_ids, attention_mask) as numpy int64."""
import numpy as np
kind, tok = tok_tuple
if kind == "transformers":
# Gemma / LLaMA-family tokenizers don't define pad_token in tokenizer.json.
# add_special_tokens updates both the Python wrapper and the Rust fast-tokenizer
# backend β plain attribute assignment only sets the Python side and may be
# ignored by _get_padding_truncation_strategies when the fast tokenizer checks
# its own registry. Reuse eos_token when present; fall back to a literal string
# so the assignment is never a no-op (e.g. when eos_token is also None).
if tok.pad_token is None:
pad_candidate = tok.eos_token or tok.bos_token or "<pad>"
tok.add_special_tokens({"pad_token": pad_candidate})
enc = tok(texts, padding="max_length", truncation=True,
max_length=max_seq, return_tensors="np")
return enc["input_ids"].astype(np.int64), enc["attention_mask"].astype(np.int64)
# tokenizers_raw: encode_batch + manual padding
encs = tok.encode_batch(texts)
max_len = min(max(len(e.ids) for e in encs), max_seq)
pad_id = tok.token_to_id("[PAD]") or tok.token_to_id("<pad>") or 0
ids, masks = [], []
for e in encs:
seq = e.ids[:max_seq]
mask = e.attention_mask[:max_seq]
pad = max_len - len(seq)
ids.append(seq + [pad_id] * pad)
masks.append(mask + [0] * pad)
return np.array(ids, dtype=np.int64), np.array(masks, dtype=np.int64)
# βββ ONNX helpers ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
def get_onnx_input_names(onnx_path):
"""Read input tensor names from ONNX graph (without loading weights)."""
try:
import onnx
model = onnx.load(onnx_path, load_external_data=False)
return [inp.name for inp in model.graph.input]
except Exception:
return ["input_ids", "attention_mask"]
def find_onnx(model_dir, onnx_name="model.onnx"):
"""Find source ONNX in model_dir, prioritising onnx/ subdirectory.
`onnx_name` allows callers to point at a non-default filename, e.g.
`model_static.onnx` for the TRT INT8 MHA fusion path that requires
a static-shape source (see .autodoc/archive/ner.md). External-data
sidecar (e.g. model_static.onnx_data) is expected to sit alongside.
"""
candidates = [
os.path.join(model_dir, "onnx", onnx_name),
os.path.join(model_dir, onnx_name),
]
for p in candidates:
if os.path.exists(p):
return p
return None
def get_onnx_vocab_size(onnx_path):
"""Read embedding vocab size from ONNX proto without loading external data.
Needed to clamp calibration token IDs when HF tokenizer vocab > ONNX
embedding table (e.g. Qwen3 tokenizer=151936 vs ONNX table=151669).
Dims are stored inline in proto even when weights are external.
"""
try:
import onnx
model = onnx.load(onnx_path, load_external_data=False)
for init in model.graph.initializer:
name_l = init.name.lower()
if (("embed_token" in name_l or "word_embed" in name_l or
("embedding" in name_l and "weight" in name_l))
and len(init.dims) == 2):
return int(init.dims[0])
except Exception:
pass
return None
# βββ CalibrationDataReader βββββββββββββββββββββββββββββββββββββββββββββββββββ
class CodeCalibrationReader:
"""ORT CalibrationDataReader backed by UltraCode-indexed code entities.
Feeds one text at a time (batch_size=1) to ensure stable activation
statistics across the full calibration set without memory pressure.
"""
def __init__(self, texts, tok_tuple, input_names, max_seq, max_token_id=None):
self._texts = texts
self._tok = tok_tuple
self._input_names = input_names
self._max_seq = max_seq
self._max_token_id = max_token_id # clamp OOB IDs (tokenizer vocab > ONNX embed table)
self._idx = 0
self._total = len(texts)
def get_next(self):
if self._idx >= self._total:
return None
text = self._texts[self._idx]
self._idx += 1
if self._idx % 50 == 0 or self._idx == self._total:
print(f" calibrating {self._idx}/{self._total}...", end="\r")
ids, masks = tokenize(self._tok, [text], self._max_seq)
if self._max_token_id is not None:
import numpy as np
ids = np.clip(ids, 0, self._max_token_id)
data = {}
for name in self._input_names:
if "attention" in name.lower() or "mask" in name.lower():
data[name] = masks
else:
data[name] = ids
return data
def rewind(self):
self._idx = 0
# βββ Quantization ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
def run_quantization(onnx_path, output_path, reader):
try:
from onnxruntime.quantization import (
quantize_static, QuantType, QuantFormat, CalibrationMethod,
quant_pre_process,
)
except ImportError:
print("ERROR: onnxruntime.quantization not available.")
print(" Install: pip install onnxruntime-tools")
print(" Or: pip install onnxruntime[quantization]")
sys.exit(1)
# Pre-process: shape inference + type annotation fix.
# Without this, ORT annotates DequantizeLinear SCALE tensors with INT8
# in the ONNX type system (inherited from quantization path), causing TRT's
# ONNX parser to emit "[SCALE] has invalid precision Int8, ignored" and
# silently skip all Q/DQ nodes. quant_pre_process runs ONNX shape inference
# which corrects the type annotations before Q/DQ nodes are inserted.
preprocessed_path = output_path.replace(".onnx", "_preproc.onnx")
print(f" Pre-processing ONNX (shape inference for TRT-compatible Q/DQ)...")
src_path = onnx_path
try:
quant_pre_process(
onnx_path,
preprocessed_path,
skip_optimization=True, # only shape inference, skip full ONNX optimizer
)
# Verify output is valid: quant_pre_process on external-data models can
# produce a proto with missing opset_import, causing ORT's augmented-model
# step to fail with "Missing opset in the model".
import onnx as _onnx_check
_pre = _onnx_check.load(preprocessed_path, load_external_data=False)
if not any(i.domain in ("", "ai.onnx") for i in _pre.opset_import):
raise ValueError("preprocessed model missing ONNX domain opset β using original")
src_path = preprocessed_path
print(f" Pre-processing done.")
except Exception as e:
print(f" WARNING: quant_pre_process failed or produced invalid model ({e}), using original ONNX")
if os.path.exists(preprocessed_path):
os.remove(preprocessed_path)
try:
quantize_static(
src_path,
output_path,
calibration_data_reader=reader,
quant_format=QuantFormat.QDQ,
activation_type=QuantType.QInt8,
weight_type=QuantType.QInt8,
# MatMul and Gemm only β RMSNorm/LayerNorm excluded, stay in float,
# which is the only way to avoid NaN in Gemma-family RMSNorm (confirmed
# 2026-04-28: implicit INT8/FP8 saturates at Β±127/Β±448 β NaN after division)
op_types_to_quantize=["MatMul", "Gemm"],
per_channel=False,
calibrate_method=CalibrationMethod.MinMax,
extra_options={"ActivationSymmetric": True},
# External-data models (>2GB float32 like Qwen3-0.6B) cause ORT's
# internal augmented_model.onnx to exceed protobuf 2GB limit when
# saved inline. use_external_data_format makes ORT save the augmented
# model as proto+data file pair, avoiding "Protobuf parsing failed".
use_external_data_format=True,
)
finally:
if os.path.exists(preprocessed_path):
os.remove(preprocessed_path)
# ORT preserves input model opset (e.g. 14 for Qwen3). TRT 10.x correctly
# handles explicit Q/DQ only at opset β₯ 18 β at opset 14 the legacy ONNX
# parser propagates INT8 type from the quantized X input onto the scale
# input of DequantizeLinear β "[SCALE] has invalid precision Int8, ignored"
# β all Q/DQ discarded. ModelOpt (Gemma path) always writes opset 19 and
# never hits this. Upgrade the quantized model before TRT engine build.
# The quantized model is ~1 GB (INT8 weights) β safe to inline-save (<2GB).
try:
upgraded, tmp = _preupgrade_onnx_opset(output_path, target_opset=19)
if tmp:
import shutil as _shutil
_shutil.move(tmp, output_path)
print(f" Upgraded quantized model to opset 19 (TRT Q/DQ requires β₯18).")
except Exception as e:
print(f" WARNING: opset-19 upgrade failed ({e}), TRT may ignore Q/DQ nodes.")
# Post-process: add explicit value_info for Q/DQ scale/zero_point initializers.
# quantize_static adds scale constants as graph initializers without value_info.
# TRT's ONNX parser, finding no value_info for scale, propagates the data type
# of the quantized tensor (INT8) to the scale input β emits
# "[SCALE] has invalid precision Int8, ignored" and discards the Q/DQ node.
# Explicit FLOAT32 value_info for scale initializers stops this type propagation.
_fix_qdq_scale_value_info(output_path)
def _fix_modelopt_scale_precision(onnx_path):
"""Convert ModelOpt FLOAT16 Q/DQ scale initializers to FLOAT32.
ModelOpt with high_precision_dtype="fp16" converts scales to FLOAT16.
TRT weakly-typed mode requires FLOAT32 scales for Q/DQ fusion.
FP16 scales cause "[SCALE] has invalid precision ..., ignored" warnings.
BFLOAT16 scales (from high_precision_dtype="bf16") are NOT converted.
In opset-22, BF16 scale β DQ output = BF16, which is correct for BF16 models.
Converting BF16 β F32 makes DQ output F32, causing Float+BF16 type mismatch
in STRONGLY_TYPED mode at q_norm/Add (RMSNorm epsilon remains BF16).
BF16 scales work correctly with TRT STRONGLY_TYPED mode (no backward INT8
propagation to scale, Q/DQ fusion proceeds normally).
This function converts only scale tensors (not zero-point β those stay INT8).
Does NOT add graph.input entries β TRT treats pure initializers as constants,
which is a REQUIREMENT for Q/DQ fusion. Adding graph.input makes the tensor a
runtime input, preventing constant-folding and breaking Q/DQ fusion entirely.
"""
try:
import onnx
import onnx.numpy_helper
import numpy as np
from onnx import TensorProto
except ImportError:
return 0
model = onnx.load(onnx_path, load_external_data=True)
scale_names: set = set()
for node in model.graph.node:
if node.op_type in ("QuantizeLinear", "DequantizeLinear"):
if len(node.input) > 1 and node.input[1]:
scale_names.add(node.input[1])
init_by_name = {init.name: init for init in model.graph.initializer}
converted = 0
for name in scale_names:
if name not in init_by_name:
continue
init = init_by_name[name]
if init.data_type == TensorProto.FLOAT16:
arr = onnx.numpy_helper.to_array(init).astype(np.float16).astype(np.float32)
new_init = onnx.numpy_helper.from_array(arr, name=name)
else:
# BFLOAT16 scales: keep as-is. In opset-22, BF16 scale β DQ output BF16,
# which is correct for BF16 models and required for STRONGLY_TYPED mode.
continue
idx = list(model.graph.initializer).index(init)
model.graph.initializer.remove(init)
model.graph.initializer.insert(idx, new_init)
converted += 1
print(f" ModelOpt scale fix: {converted}/{len(scale_names)} scales βFLOAT32")
if converted:
onnx.save(model, onnx_path)
print(f" Saved: {os.path.basename(onnx_path)}")
return converted
def _fix_qdq_scale_value_info(onnx_path):
"""Ensure Q/DQ scale tensors have correct graph.input type annotations for TRT.
Used ONLY for the ORT quantize_static fallback path. ORT produces FLOAT32 scale
initializers without graph.input entries. Without graph.input, TRT's ONNX parser
may propagate INT8 from quantized context to the scale, emitting:
[SCALE] has invalid precision Int8, ignored
NOT called for ModelOpt output β ModelOpt scales must stay as pure initializers
(no graph.input) so TRT treats them as constants, enabling Q/DQ constant-folding.
This function:
(a) Collects all scale/zero_point tensor names from QuantizeLinear/DequantizeLinear
(b) Inlines any Constant-node outputs β initializers (so they appear as constants)
(c) Adds missing graph.input entries with the correct type (FLOAT for scales, INT8 for zp)
(d) Fixes graph.input entries that have wrong type declarations
"""
try:
import onnx
from onnx import TensorProto, helper
except ImportError:
return
model = onnx.load(onnx_path, load_external_data=True)
scale_names: set = set()
zp_names: set = set()
for node in model.graph.node:
if node.op_type in ("QuantizeLinear", "DequantizeLinear"):
if len(node.input) > 1 and node.input[1]:
scale_names.add(node.input[1])
if len(node.input) > 2 and node.input[2]:
zp_names.add(node.input[2])
# Inline Constant nodes β initializers so TRT treats them as constants, not ops
const_node_for: dict = {}
for node in model.graph.node:
if node.op_type == "Constant":
for out in node.output:
if out in scale_names or out in zp_names:
const_node_for[out] = node
nodes_to_remove = []
for name, node in const_node_for.items():
for attr in node.attribute:
if attr.name == "value":
t = onnx.TensorProto()
t.CopyFrom(attr.t)
t.name = name
model.graph.initializer.append(t)
nodes_to_remove.append(node)
break
for node in nodes_to_remove:
model.graph.node.remove(node)
init_by_name: dict = {init.name: init for init in model.graph.initializer}
inp_by_name: dict = {inp.name: inp for inp in model.graph.input}
added = 0
fixed_input = 0
for name in scale_names:
if name not in init_by_name:
continue # truly dynamic β skip
# Ensure graph.input entry exists and declares FLOAT (FLOAT32)
# TRT reads scale precision from graph.input; without it, type propagation
# from the quantized INT8 tensor may override the scale to INT8.
if name not in inp_by_name:
model.graph.input.append(helper.make_tensor_value_info(name, TensorProto.FLOAT, []))
inp_by_name[name] = model.graph.input[-1]
added += 1
elif inp_by_name[name].type.tensor_type.elem_type != TensorProto.FLOAT:
inp_by_name[name].type.tensor_type.elem_type = TensorProto.FLOAT
fixed_input += 1
for name in zp_names:
if name not in init_by_name:
continue
zp_type = init_by_name[name].data_type
if name not in inp_by_name:
model.graph.input.append(helper.make_tensor_value_info(name, zp_type, []))
inp_by_name[name] = model.graph.input[-1]
added += 1
elif inp_by_name[name].type.tensor_type.elem_type != zp_type:
inp_by_name[name].type.tensor_type.elem_type = zp_type
fixed_input += 1
print(f" Q/DQ fix: scales={len(scale_names)} zp={len(zp_names)} "
f"const_inlined={len(nodes_to_remove)} added={added} fixed_input={fixed_input}")
if added or fixed_input or nodes_to_remove:
onnx.save(model, onnx_path)
print(f" Q/DQ fix: saved")
# βββ nvidia-modelopt backend βββββββββββββββββββββββββββββββββββββββββββββββββ
def _has_modelopt():
try:
import modelopt.onnx.quantization # noqa: F401
return True
except ImportError:
return False
def _setup_trt_for_modelopt():
"""Expose TRT Python bindings to ModelOpt before it tries to import them.
ModelOpt does `import tensorrt` for ORT TensorRT-EP calibration and for
TRT-specific GEMV pattern optimization. Without this, it falls back to CPU
calibration (correct but slow). We re-use vendor/tensorrt DLLs + any pip
tensorrt_bindings package β same approach as build_trt_engine._add_nvinfer_to_path.
"""
if "tensorrt" in sys.modules:
return
# 1. Add vendor/tensorrt/lib DLLs to search path.
# Found by walking up to build.zig rather than by counting `..`: this file
# moved from scripts/ to models/_compile/backends/workers/, and a fixed
# depth fails silently because a missing directory reads as "not vendored".
_d = os.path.dirname(os.path.abspath(__file__))
vendor_lib = ""
for _ in range(6):
if os.path.isfile(os.path.join(_d, "build.zig")):
vendor_lib = os.path.join(_d, "vendor", "tensorrt", "lib")
break
_d = os.path.dirname(_d)
if os.path.isdir(vendor_lib):
if sys.platform == "win32" and hasattr(os, "add_dll_directory"):
try:
os.add_dll_directory(vendor_lib)
except OSError:
pass
os.environ["PATH"] = vendor_lib + os.pathsep + os.environ.get("PATH", "")
# 2. Add pip tensorrt_libs to DLL search (nvinfer_plugin_10.dll etc.)
try:
import site
for sp in site.getsitepackages() + [site.getusersitepackages()]:
trt_libs = os.path.join(sp, "tensorrt_libs")
if os.path.isdir(trt_libs):
if sys.platform == "win32" and hasattr(os, "add_dll_directory"):
try:
os.add_dll_directory(trt_libs)
except OSError:
pass
os.environ["PATH"] = trt_libs + os.pathsep + os.environ.get("PATH", "")
break
except Exception:
pass
# 3. Add nvidia/cudnn/bin to PATH (ModelOpt checks system PATH for cuDNN before
# falling back to onnxruntime.preload_dlls). nvidia-cudnn-cu12 installs DLLs
# to site-packages/nvidia/cudnn/bin/ β adding here silences the PATH warning.
try:
import site
for _sp in site.getsitepackages() + [site.getusersitepackages()]:
_cudnn_bin = os.path.join(_sp, "nvidia", "cudnn", "bin")
if os.path.isdir(_cudnn_bin) and any(
f.startswith("cudnn64_") and f.endswith(".dll")
for f in os.listdir(_cudnn_bin)
):
os.environ["PATH"] = _cudnn_bin + os.pathsep + os.environ.get("PATH", "")
if sys.platform == "win32" and hasattr(os, "add_dll_directory"):
try:
os.add_dll_directory(_cudnn_bin)
except OSError:
pass
break
except Exception:
pass
# 4. Add nvidia/cublas/bin to PATH (ORT CUDA EP loads cublasLt64_12.dll from here).
# nvidia-cublas-cu12 installs to site-packages/nvidia/cublas/bin/.
try:
import site
for _sp in site.getsitepackages() + [site.getusersitepackages()]:
_cublas_bin = os.path.join(_sp, "nvidia", "cublas", "bin")
if os.path.isdir(_cublas_bin) and any(
f.startswith("cublasLt") and f.endswith(".dll")
for f in os.listdir(_cublas_bin)
):
os.environ["PATH"] = _cublas_bin + os.pathsep + os.environ.get("PATH", "")
if sys.platform == "win32" and hasattr(os, "add_dll_directory"):
try:
os.add_dll_directory(_cublas_bin)
except OSError:
pass
break
except Exception:
pass
# 5. Alias tensorrt_bindings β tensorrt (tensorrt-cu12-bindings pip package)
try:
from tensorrt_bindings import tensorrt as _trt
sys.modules["tensorrt"] = _trt
import tensorrt_bindings as _trt_pkg
_ver = getattr(_trt_pkg, "__version__", None) or getattr(_trt, "__version__", "unknown")
print(f" TensorRT {_ver} exposed to ModelOpt via tensorrt_bindings")
except ImportError:
try:
import tensorrt # noqa: F401 (direct install)
print(f" TensorRT ready for ModelOpt")
except ImportError:
pass # ModelOpt will fall back to CPU calibration β still correct
def _preupgrade_onnx_opset(onnx_path, target_opset=19):
"""Manually upgrade Reduce* axes from attribute to input (opset 14 β 18+).
ModelOpt's internal upgrader bumps opset_import but doesn't convert
ReduceMean axes-as-attribute β axes-as-input (required for opset 18+).
onnx.version_converter also fails on old IR versions. Manual conversion:
for each Reduce node with axes attribute, insert a Constant node and
rewire it as the second input.
Returns (new_onnx_path, tmp_path_or_None) β caller must delete tmp.
"""
import onnx
import onnx.helper
model = onnx.load(onnx_path, load_external_data=True)
cur_opset = max(
(i.version for i in model.opset_import if i.domain in ("", "ai.onnx")),
default=0,
)
if cur_opset >= target_opset:
return onnx_path, None
print(f" Pre-upgrading opset {cur_opset} β {target_opset} (manual Reduce axes fix)...")
# Reduce ops that moved axes from attribute to input in opset 18
_REDUCE_OPS = {
"ReduceMean", "ReduceSum", "ReduceMax", "ReduceMin", "ReduceProd",
"ReduceL1", "ReduceL2", "ReduceLogSum", "ReduceLogSumExp", "ReduceSumSquare",
}
extra_nodes: list = [] # Constant axes nodes β must precede consumers
new_nodes: list = []
for node in model.graph.node:
if node.op_type in _REDUCE_OPS:
axes_attr = next((a for a in node.attribute if a.name == "axes"), None)
if axes_attr and len(axes_attr.ints) > 0:
axes_vals = list(axes_attr.ints)
const_out = f"_axes_cst_{node.output[0]}"
axes_tensor = onnx.helper.make_tensor(
const_out, onnx.TensorProto.INT64, [len(axes_vals)], axes_vals
)
extra_nodes.append(
onnx.helper.make_node("Constant", inputs=[], outputs=[const_out],
value=axes_tensor)
)
# Rebuild node: axes as second input, strip axes attribute
rebuilt = onnx.helper.make_node(
node.op_type,
inputs=list(node.input) + [const_out],
outputs=list(node.output),
name=node.name,
)
for a in node.attribute:
if a.name != "axes":
rebuilt.attribute.append(a)
new_nodes.append(rebuilt)
continue
new_nodes.append(node)
del model.graph.node[:]
model.graph.node.extend(extra_nodes + new_nodes)
# Bump declared opset and IR version
for imp in model.opset_import:
if imp.domain in ("", "ai.onnx"):
imp.version = target_opset
model.ir_version = 9 # required for opset 19
tmp_path = onnx_path.replace(".onnx", f"_opset{target_opset}_pre.onnx")
onnx.save_model(model, tmp_path)
print(f" Pre-upgraded: {os.path.basename(tmp_path)}")
return tmp_path, tmp_path
def _preupgrade_onnx_structural(onnx_path, target_opset=18):
"""Upgrade Reduce* axes attributeβinput (opset 14β18) without loading weights.
Loads only the ONNX proto (no external weight data), fixes ReduceMean/etc.
axes-as-attribute nodes, bumps declared opset/IR, then saves a new proto that
still references the ORIGINAL external-data blob. No 2 GB protobuf limit
because weight tensors are never materialised in Python memory.
Returns (upgraded_path, tmp_path_or_None). Caller should delete tmp after use.
If the model is already at target_opset, returns (onnx_path, None) immediately.
"""
import onnx
import onnx.helper
# Quick check without loading weights
model_hdr = onnx.load(onnx_path, load_external_data=False)
cur_opset = max(
(i.version for i in model_hdr.opset_import if i.domain in ("", "ai.onnx")),
default=0,
)
if cur_opset >= target_opset:
return onnx_path, None
print(f" Structural pre-upgrade opset {cur_opset}β{target_opset} (no weights loaded)...")
_REDUCE_OPS = {
"ReduceMean", "ReduceSum", "ReduceMax", "ReduceMin", "ReduceProd",
"ReduceL1", "ReduceL2", "ReduceLogSum", "ReduceLogSumExp", "ReduceSumSquare",
}
extra_nodes: list = []
new_nodes: list = []
for node in model_hdr.graph.node:
if node.op_type in _REDUCE_OPS:
axes_attr = next((a for a in node.attribute if a.name == "axes"), None)
if axes_attr and len(axes_attr.ints) > 0:
axes_vals = list(axes_attr.ints)
const_out = f"_axes_cst_{node.output[0]}"
axes_tensor = onnx.helper.make_tensor(
const_out, onnx.TensorProto.INT64, [len(axes_vals)], axes_vals
)
extra_nodes.append(
onnx.helper.make_node("Constant", inputs=[], outputs=[const_out],
value=axes_tensor)
)
rebuilt = onnx.helper.make_node(
node.op_type,
inputs=list(node.input) + [const_out],
outputs=list(node.output),
name=node.name,
)
for a in node.attribute:
if a.name != "axes":
rebuilt.attribute.append(a)
new_nodes.append(rebuilt)
continue
new_nodes.append(node)
del model_hdr.graph.node[:]
model_hdr.graph.node.extend(extra_nodes + new_nodes)
for imp in model_hdr.opset_import:
if imp.domain in ("", "ai.onnx"):
imp.version = target_opset
# IR version must match opset: opset 17-18 β ir 8, opset 19+ β ir 9
model_hdr.ir_version = 9 if target_opset >= 19 else 8
# Save proto only; keep external-data blob in place.
# location= must be relative to the directory of the new proto file.
# We save alongside the original model so the existing .onnx_data is found.
ext_data_filename = os.path.basename(onnx_path) + "_data"
tmp_path = onnx_path.replace(".onnx", f"_opset{target_opset}_struct.onnx")
onnx.save_model(
model_hdr,
tmp_path,
save_as_external_data=True,
all_tensors_to_one_file=True,
location=ext_data_filename, # same relative name as the original blob
size_threshold=0,
convert_attribute=False,
)
print(f" Structural upgrade saved: {os.path.basename(tmp_path)} "
f"(dataβ{ext_data_filename})")
return tmp_path, tmp_path
def _quantize_modelopt(onnx_path, output_path, texts, tok_tuple, input_names, max_seq,
quantize_mode="int8", high_precision="bf16", calib_method="max"):
"""PTQ using nvidia-modelopt β produces Q/DQ ONNX following TensorRT rules.
ORT quantize_static produces Q/DQ with scale type annotations that TRT's
ONNX parser rejects ("[SCALE] has invalid precision Int8, ignored"), silently
discarding all Q/DQ nodes. ModelOpt generates the same Q/DQ structure but
with correct TRT-compatible annotations β no parser warnings, INT8/FP8 engaged.
quantize_mode: "int8" (default) or "fp8" (E4M3, sm_89+, best on sm_120 Blackwell).
FP8 requires ONNX opset 20+ and TRT 10.x --fp8 builder flag.
Calibration data: full numpy batch (not one-at-a-time like ORT CalibDataReader).
"""
_setup_trt_for_modelopt()
import modelopt.onnx.quantization as moq
import numpy as np
# FP8 only: pre-upgrade to opset 20 (FLOAT8E4M3FN type added in opset 20).
# INT8: let ModelOpt handle the opset upgrade internally. ModelOpt's internal
# upgrade ("Updating minimum opset from 13 to 19") includes TRT-specific structural
# transformations beyond just bumping the opset number. Pre-upgrading externally
# skips those transformations, producing Q/DQ with scale tensors that TRT's type
# inference misclassifies as INT8 β "[SCALE] has invalid precision Int8, ignored"
# β fusion fails β FP16 fallback. For INT8 pass the original opset-14 ONNX
# (with external data) directly to ModelOpt.
if quantize_mode in ("fp8", "nvfp4", "int4"):
# FP8 / NVFP4 / INT4 need opset 20+ (FLOAT8E4M3FN / FLOAT4E2M1 dtypes).
# INT8 lets ModelOpt do the opset upgrade internally (TRT structural transforms).
upgraded_path, _struct_tmp = _preupgrade_onnx_opset(onnx_path, target_opset=20)
else:
upgraded_path, _struct_tmp = onnx_path, None
print(f" Backend: nvidia-modelopt (TRT-native QDQ, mode={quantize_mode})")
print(f" Tokenizing {len(texts)} calibration samples...")
ids, masks = tokenize(tok_tuple, texts, max_seq)
# Clamp OOB token IDs (tokenizer vocab > ONNX embedding table) for the ModelOpt path
# too. The ORT CalibrationDataReader clamps via max_token_id, but ModelOpt gets the raw
# `ids` and would otherwise hit a Gather OOB (idx=vocab must be in [0, vocab-1]) β e.g.
# an XLM-R <mask> at id=vocab β which aborts ModelOpt β ORT fallback β LayerNorm failure.
_mo_vocab = get_onnx_vocab_size(onnx_path)
if _mo_vocab:
ids = np.clip(ids, 0, _mo_vocab - 1)
calib: dict = {}
for name in input_names:
if "attention" in name.lower() or "mask" in name.lower():
calib[name] = masks
else:
calib[name] = ids
print(f" Calibration shape: {ids.shape[0]} samples Γ {ids.shape[1]} tokens")
# disable_mha_qdq: skip MHA inner BMM quantization (QΒ·Kα΅, attnΒ·V).
# Default True for INT8: dynamic "weights" can hurt quality there.
# 2026-05-19 FP8 override: with EXPERIMENTAL_QUANTIZE_MHA_FP8 we flip to
# False so MHA inner BMMs also go through FP8 Q/DQ. softmax/RMSNorm stay
# in BF16 via high_precision_dtype (NaN-safe). Without this, FP8 mode
# only quantizes ~48/168 matmuls and loses to INT8 STRONGLY_TYPED which
# has no such exclusion (measured 2026-05-19: 3584 vs 4541 emb/s).
disable_mha_qdq_flag = True
if quantize_mode == "fp8" and EXPERIMENTAL_QUANTIZE_MHA_FP8:
disable_mha_qdq_flag = False
print(" [EXPERIMENTAL] disable_mha_qdq=False β quantizing MHA inner BMMs in FP8")
moq.quantize(
onnx_path=upgraded_path,
calibration_data=calib,
output_path=output_path,
quantize_mode=quantize_mode,
# MatMul + Gemm only β RMSNorm/LayerNorm excluded, stay in high-precision float.
# Gemma RMSNorm uses weights with +1.0 offset (TRT-LLM issue #4815); quantizing
# these ops causes silent accuracy loss.
op_types_to_quantize=["MatMul", "Gemm"],
# "entropy" (--calib-method): KL-divergence clipping of activation ranges β
# for outlier-heavy pretrained bodies (XLM-R/e5) where "max" saturates the
# int8 grid and collapses top-rank (v2-p4: h1 .227β.160 under max, 2026-07-22).
calibration_method=calib_method,
# high_precision_dtype="bf16": non-quantized ops (RMSNorm, SiLU, softmax) in BF16.
# Gemma model card: activations do not support float16 β use bfloat16.
# BF16 has same exponent range as Float32, preventing RMSNorm overflow.
#
# ModelOpt with "bf16" upgrades to opset-22 and stores scale initializers as BF16.
# In ONNX opset-22, DQ output type = scale type β BF16 scale β BF16 DQ output.
# This means q_norm/Add receives BF16 + BF16 (both ReduceMean and epsilon in BF16).
# TRT STRONGLY_TYPED mode reads these types without backward INT8 propagation β
# 0 [SCALE] warnings β INT8 Q/DQ fusion works β ~1300 emb/s on sm_120 (3Γ BF16).
#
# DO NOT call _fix_modelopt_scale_precision after this: converting BF16βF32 scales
# makes DQ output F32 β q_norm/Add gets F32+BF16 β STRONGLY_TYPED fails.
#
# high_precision="fp16" (--high-precision, 2026-07-22): for fp16-safe encoders
# (XLM-R/LayerNorm embed models). Keeps ModelOpt's internal opset-19 upgrade
# (TRT-11 parseable, ORT-runnable) + FLOAT16 scales that
# _fix_modelopt_scale_precision converts to FP32. bf16 on the v2-p3/p4 embed
# body produced a cos=-0.06 garbage TRT engine + un-runnable-in-ORT QDQ.
high_precision_dtype=high_precision,
mha_accumulation_dtype=high_precision,
disable_mha_qdq=disable_mha_qdq_flag,
)
print(f" modelopt quantization done ({quantize_mode}).", flush=True)
# Clean up structural-upgrade temp file (the original data blob is shared)
if _struct_tmp and os.path.exists(_struct_tmp):
try:
os.remove(_struct_tmp)
except Exception:
pass
def _ensure_modelopt():
"""Auto-install nvidia-modelopt[onnx] if not present. Returns True if available."""
if _has_modelopt():
return True
print(" nvidia-modelopt not found β installing...")
result = subprocess.run(
[sys.executable, "-m", "pip", "install", "--quiet", "nvidia-modelopt[onnx]"],
capture_output=True, text=True,
)
if result.returncode != 0:
print(f" Install failed: {result.stderr.strip()[:200]}")
return False
if _has_modelopt():
print(" nvidia-modelopt installed.")
return True
print(" nvidia-modelopt still not importable after install.")
return False
# βββ Main ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
def main():
ap = argparse.ArgumentParser(
description="PTQ INT8 Q/DQ quantization for ONNX embedding models",
formatter_class=argparse.RawDescriptionHelpFormatter,
epilog=__doc__,
)
ap.add_argument("--model-dir", required=True,
help="Output directory (tokenizer.json; model_int8qdt.onnx written here by default)")
ap.add_argument("--onnx-dir", metavar="PATH",
help="Directory containing the source model.onnx WITH external data files "
"(e.g. scripts/.cache/<model-id>). When omitted, --model-dir is searched.")
ap.add_argument("--calib-db", nargs="*", metavar="PATH",
help="Explicit paths to UltraCode graph.db calibration files")
ap.add_argument("--calib-dir", metavar="PATH",
help="UltraCode projects dir to scan (auto-detected if omitted)")
ap.add_argument("--calib-texts", metavar="PATH",
help="JSONL of calibration texts ({'text': ...} per line, or plain "
"lines) β bypasses graph.db collection entirely. Use the REAL "
"serve strings (entities_serve.jsonl): the 2026-07-2x p5_c PTQ "
"collapse calibrated on entity NAMES + raw 400-char file chunks, "
"not the label(+desc) texts the model actually serves "
"(deep-research report Β§4 arm 0 β the de-confounder).")
ap.add_argument("--samples", type=int, default=500,
help="Target calibration sample count (default: 500)")
ap.add_argument("--max-seq", type=int, default=128,
help="Max token sequence length (default: 128, matches TRT profile 2)")
ap.add_argument("--output", metavar="PATH",
help="Output ONNX path (default: {model_dir}/model_int8qdt.onnx or model_fp8qdt.onnx)")
ap.add_argument("--fp8", action="store_true",
help="Use FP8 E4M3 quantization instead of INT8 (requires sm_89+, best on sm_120 Blackwell). "
"Produces model_fp8qdt.onnx. Build TRT engine with --fp8 flag afterwards.")
ap.add_argument("--nvfp4", action="store_true",
help="EXPERIMENTAL (TRT 11): NVFP4 4-bit (E2M1) quantization. Produces "
"model_nvfp4qdt.onnx -> strongly-typed engine. Requires ml_dtypes with "
"float4_e2m1fn + CUDA 13.3 cuBLAS NVFP4-scaling fix (the 13.2 bug is fixed "
"in cuBLAS 13.5.1). GATED: ship only if the 256d quality check holds "
"(sim-pass skipped_empty=0 + min_cos>=0.5 + MTEB/MIRACL-RU vs INT8 baseline).")
ap.add_argument("--int4", action="store_true",
help="EXPERIMENTAL (TRT 11): INT4 weight quantization. Produces "
"model_int4qdt.onnx. Same 256d quality gate as --nvfp4.")
ap.add_argument("--onnx-name", default="model.onnx",
help="Source ONNX filename to look for in --onnx-dir/--model-dir. "
"Default 'model.onnx'. Use 'model_static.onnx' for the TRT INT8 "
"MHA fusion path (static-shape ONNX is required for fusion in "
"TRT 10.15.1+; see .autodoc/archive/ner.md).")
ap.add_argument("--calib-method", choices=["max", "entropy"], default="max",
help="ModelOpt activation calibration. 'entropy' clips outlier ranges "
"(KL) β use for pretrained XLM-R/e5 bodies where 'max' saturates.")
ap.add_argument("--high-precision", choices=["bf16", "fp16", "fp32"], default="bf16",
help="ModelOpt high_precision_dtype for non-quantized ops. Default 'bf16' "
"(Gemma/RMSNorm NaN-safety; bumps opset to 22, BF16 scales β the "
"NER/LLM path). Use 'fp16' for fp16-safe encoders (XLM-R/LayerNorm "
"embed models): keeps ModelOpt's internal opset-19 upgrade (TRT-11 "
"parseable, ORT-runnable) and FLOAT16 scales, which "
"_fix_modelopt_scale_precision then converts to FP32 for Q/DQ fusion. "
"bf16 on the v2-p3/p4 embed body produced a cos=-0.06 garbage engine "
"(2026-07-22, PHASE3_REDISTILL_RUNBOOK Β§SESSION 2).")
args = ap.parse_args()
# Precision selection (priority: nvfp4 > int4 > fp8 > int8). nvfp4/int4 are
# experimental TRT-11 tracks (see flag help + .autodoc/archive/embed-encoder.md); they
# need a newer ml_dtypes (float4_e2m1fn) and pass through a 256d quality gate.
if args.nvfp4:
quantize_mode = "nvfp4"
elif args.int4:
quantize_mode = "int4"
elif args.fp8:
quantize_mode = "fp8"
else:
quantize_mode = "int8"
# ββ Find source ONNX (prefer --onnx-dir when provided; it has external data)
search_dirs = []
if args.onnx_dir:
search_dirs.append(args.onnx_dir)
search_dirs.append(args.model_dir)
onnx_path = None
for d in search_dirs:
onnx_path = find_onnx(d, onnx_name=args.onnx_name)
if onnx_path:
break
if not onnx_path:
searched = ", ".join(search_dirs)
print(f"ERROR: {args.onnx_name} not found in {searched}")
sys.exit(1)
print(f"Input ONNX: {onnx_path} ({os.path.getsize(onnx_path) / 1e6:.0f} MB)")
# ββ Output path β always under model_dir (production), not onnx_dir (cache)
default_out_name = {
"nvfp4": "model_nvfp4qdt.onnx", "int4": "model_int4qdt.onnx",
"fp8": "model_fp8qdt.onnx", "int8": "model_int8qdt.onnx",
}[quantize_mode]
output_path = args.output or os.path.join(args.model_dir, default_out_name)
print(f"Output ONNX: {output_path} (mode={quantize_mode})")
# ββ Collect texts: explicit serve-text file beats DB scraping
if args.calib_texts:
import json as _json
texts = []
with open(args.calib_texts, encoding="utf-8") as f:
for line in f:
line = line.strip()
if not line:
continue
try:
obj = _json.loads(line)
t = obj.get("text") if isinstance(obj, dict) else None
except ValueError:
t = line
if t:
texts.append(t)
if not texts:
print(f"ERROR: no texts in {args.calib_texts}")
sys.exit(1)
# Even spread across the file (it is ordered by file path β a head
# slice would calibrate on one corner of the repo).
if len(texts) > args.samples:
step = len(texts) / args.samples
texts = [texts[int(i * step)] for i in range(args.samples)]
print(f"Texts: {len(texts)} serve strings from {args.calib_texts}")
else:
# ββ Calibration DBs
if args.calib_db:
db_paths = args.calib_db
else:
calib_dir = args.calib_dir or _default_projects_dir()
db_paths = find_calib_dbs(calib_dir)
if not db_paths:
print(f"\nERROR: no graph.db files found in {calib_dir}")
print(" Index some projects first:")
print(" mcp__ultracode__index --directory /path/to/project")
print(" Or pass --calib-db explicitly.")
sys.exit(1)
print(f"Calib DBs: {len(db_paths)} files")
per_db = max(10, (args.samples * 4 // 3) // max(len(db_paths), 1))
texts = collect_texts(db_paths, per_db=per_db)
if not texts:
print("ERROR: no calibration texts collected. Check DB paths and entity data.")
sys.exit(1)
texts = texts[:args.samples]
print(f"Texts: {len(texts)} samples from {len(db_paths)} projects")
# ββ Tokenizer β prefer onnx_dir (HF cache, has tokenizer.json), fall back to model_dir
tok_dir = args.onnx_dir if args.onnx_dir else args.model_dir
print(f"Tokenizer: {tok_dir}")
tok = load_tokenizer(tok_dir)
# ββ ONNX input names + vocab size (for calibration token ID clamping)
input_names = get_onnx_input_names(onnx_path)
print(f"ONNX inputs: {input_names}")
vocab_size = get_onnx_vocab_size(onnx_path)
if vocab_size:
print(f"ONNX vocab: {vocab_size} (token IDs clamped to [0, {vocab_size - 1}])")
# ββ Quantize
print(f"\nQuantizing (op_types: MatMul, Gemm | format: QDQ | mode: {quantize_mode})...")
if args.fp8:
print(" FP8 mode: E4M3, requires sm_89+ (Ada/Hopper/Blackwell)")
print(" After quantization build TRT with: --fp8 --onnx <model_fp8qdt.onnx>")
modelopt_ok = False
if _ensure_modelopt():
try:
_quantize_modelopt(onnx_path, output_path, texts, tok, input_names, args.max_seq,
quantize_mode=quantize_mode, high_precision=args.high_precision,
calib_method=args.calib_method)
modelopt_ok = True
except BaseException as e:
print(f" ModelOpt failed ({type(e).__name__}: {e})", flush=True)
if quantize_mode != "int8":
if "Invalid quantization mode" in str(e) or quantize_mode == "nvfp4":
# ModelOpt's ONNX quantize() routes only int8/fp8/int4 (as of
# 0.43/0.44). NVFP4 is a PyTorch-quant feature, NOT ONNX PTQ β
# quantize_mode="nvfp4" hits `raise RuntimeError(Invalid
# quantization mode choice)`. INT4 IS routed (elif "int4").
print(f" '{quantize_mode}' is NOT supported by this nvidia-modelopt's ONNX path")
print(f" (onnx quantize() routes only int8/fp8/int4; nvfp4 is torch-quant only).")
print(f" Use --int4 for a 4-bit ONNX experiment, or stay on INT8.")
else:
print(f" {quantize_mode} requires nvidia-modelopt with matching opset/ml_dtypes support.")
print(f" Cannot fall back to ORT for {quantize_mode} β ORT quantize_static is INT8-only.")
sys.exit(1)
print(" Falling back to onnxruntime.quantization (ORT path)...")
if modelopt_ok and quantize_mode == "int8":
# ModelOpt with high_precision_dtype="fp16" stores scales as FLOAT16.
# TRT requires FLOAT32 scales for Q/DQ fusion in weakly-typed mode.
# For bf16 mode (opset-22): scales stay as BFLOAT16 β DO NOT convert.
# BF16 scales β DQ output = BF16 β q_norm/Add: BF16+BF16 = STRONGLY_TYPED OK.
# Converting BF16βF32 would make DQ output F32 β q_norm/Add F32+BF16 = FAIL.
#
# --high-precision fp16 (2026-07-22): SKIP the fix too. ModelOpt stores the
# weights AND scales in FP16 β self-consistent per the opset-19 QuantizeLinear
# spec (input/scale share T1). Converting scales to F32 breaks that binding
# (ORT: "Type parameter (T1) bound to different types (float16 and float)")
# and our TRT-11 build is STRONGLY_TYPED (precision from graph types), which
# never needed the weakly-typed F32-scale workaround in the first place.
if args.high_precision == "bf16":
_fix_modelopt_scale_precision(output_path)
if not modelopt_ok:
# ORT-based PTQ: file-path API handles external-data models (no 2GB proto limit).
# quant_pre_process + quantize_static + _fix_qdq_scale_value_info produces
# TRT-compatible Q/DQ without [SCALE] warnings.
max_tok_id = vocab_size - 1 if vocab_size else None
reader = CodeCalibrationReader(texts, tok, input_names, args.max_seq,
max_token_id=max_tok_id)
run_quantization(onnx_path, output_path, reader)
print()
size_mb = os.path.getsize(output_path) / 1e6
print(f"Done: {output_path} ({size_mb:.0f} MB)")
if args.fp8:
print("Next: build TRT engine from model_fp8qdt.onnx")
print(" python scripts/build_trt_engine.py --model-dir dist/models/<model> \\")
print(" --onnx dist/models/<model>/model_fp8qdt.onnx --cuda-arch sm_120 --fp8 --force")
print(" Expected: ~1000+ emb/s on sm_120 Blackwell (2Γ INT8 TFLOPS)")
else:
print("Next: run models/compile to build TRT engine from model_int8qdt.onnx")
print(" Expected: ~900 emb/s vs 480 emb/s BF16")
if __name__ == "__main__":
main()
|