faxenoff commited on
Commit
40da26e
·
verified ·
1 Parent(s): d830b42

cloud build tools (matrix trt11.3, 5 archs); the tools bucket is read-only since 10-07

Browse files
_build-tools/bootstrap_linux.sh ADDED
@@ -0,0 +1,185 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env bash
2
+ # bootstrap_linux.sh - turn a bare Linux GPU VM into a linux_x64 TRT engine builder.
3
+ #
4
+ # The Linux twin of bootstrap_win.ps1, and the fallback when a Windows VM's WSL
5
+ # cannot see the GPU (Tesla cards in TCC mode, vGPU profiles, nested virt off -
6
+ # bootstrap_win diagnoses which). Everything it needs comes over HTTPS: the tools
7
+ # from TOOLS_URL, the ONNX from the public HF model repos, and the engines go back
8
+ # to those same repos. No S3 credentials touch the box.
9
+ #
10
+ # ── On-VM usage (the only command you type) ───────────────────────────────────────────
11
+ # export TOOLS_URL=https://<bucket>.s3.twcstorage.ru/_build-tools
12
+ # export HF_TOKEN=hf_...write...
13
+ # curl -fsSL "$TOOLS_URL/bootstrap_linux.sh" | bash
14
+ #
15
+ # Optional:
16
+ # DEST_PREFIX also copy the engines to S3 (needs S3_* creds too)
17
+ # DISTRO_PY python to use (default: python3)
18
+ # ONLY / SKIP space-separated model ids, passed through to run_matrix.py
19
+ set -uo pipefail
20
+
21
+ C='\033[0;36m'; G='\033[0;32m'; R='\033[0;31m'; Y='\033[0;33m'; D='\033[0;90m'; Z='\033[0m'
22
+ head_() { echo; echo -e "${D}$(printf '=%.0s' {1..72})${Z}"; echo -e "${C} $*${Z}"; echo -e "${D}$(printf '=%.0s' {1..72})${Z}"; }
23
+ step() { echo -e "\n${C}[>] $*${Z}"; }
24
+ ok() { echo -e " ${G}[OK]${Z} $*"; }
25
+ warn() { echo -e " ${Y}[!] ${Z} $*"; }
26
+ die() { echo -e " ${R}[!!]${Z} $*" >&2; exit 1; }
27
+
28
+ TOOLS_URL="${TOOLS_URL:-}"
29
+ HF_TOKEN="${HF_TOKEN:-}"
30
+ DEST_PREFIX="${DEST_PREFIX:-}"
31
+ PY="${DISTRO_PY:-python3}"
32
+ WORK="${WORKDIR:-$HOME/uc-build}"
33
+ TOOLS="$WORK/_tools"
34
+
35
+ # build_matrix.json is what makes the run self-describing: precision per model per
36
+ # arch comes from the catalog, not from whatever the operator remembered to export.
37
+ TOOL_FILES="run_matrix.py build_matrix.json build_engines.sh build_trt_engine.py onnx_fp16.py quantize_onnx.py calib_corpus.jsonl"
38
+ # fp16-only archs never touch the quantizer or the corpus - a 404 there must not
39
+ # block a Turing run. onnx_fp16.py is NOT optional: it is a local repo module the
40
+ # worker imports inside a try, so a missing one skips the FP16 pass silently and
41
+ # ships an FP32 engine under an FP16 name.
42
+ TOOL_OPTIONAL="quantize_onnx.py calib_corpus.jsonl"
43
+
44
+ head_ "ultracode cloud builder - Linux VM bootstrap"
45
+
46
+ [ -n "$TOOLS_URL" ] || die "set TOOLS_URL first, e.g. export TOOLS_URL=https://<bucket>.s3.twcstorage.ru/_build-tools"
47
+ if [ -z "$HF_TOKEN" ] && [ -z "$DEST_PREFIX" ]; then
48
+ die "set HF_TOKEN (a WRITE token) or DEST_PREFIX - otherwise the engines are built and discarded."
49
+ fi
50
+
51
+ # ── 0. preflight ──────────────────────────────────────────────────────────────────────
52
+ step "Preflight"
53
+ [ "$(id -u)" = "0" ] && SUDO="" || SUDO="sudo"
54
+ if [ -n "$SUDO" ] && ! command -v sudo >/dev/null 2>&1; then
55
+ die "not root and no sudo - run as root or install sudo."
56
+ fi
57
+
58
+ # Install the driver rather than demanding one. The Terraform lane has
59
+ # cloud-init's engine-build.sh do this before calling us, so the ordering never
60
+ # showed - but this script is also the MANUAL entry point, and there it ran on a
61
+ # machine whose image carries no driver and simply refused to continue.
62
+ if ! command -v nvidia-smi >/dev/null 2>&1; then
63
+ if ! lspci 2>/dev/null | grep -qi nvidia; then
64
+ die "no NVIDIA device on the PCI bus - this is not a GPU instance."
65
+ fi
66
+ step "NVIDIA driver not present - installing (ubuntu-drivers --gpgpu)"
67
+ export DEBIAN_FRONTEND=noninteractive
68
+ $SUDO apt-get update -qq
69
+ $SUDO apt-get install -y -qq ubuntu-drivers-common pciutils >/dev/null
70
+ # ⛔ The fallback pin must satisfy the CUDA the TensorRT WHEELS link against,
71
+ # not merely boot the card. Our pin is a cu13 wheel (TensorRT 11.x), and
72
+ # `build_engines.sh` picks cu12 vs cu13 from the CUDA version the DRIVER
73
+ # reports. A 570 driver reports CUDA 12.x, so the pinned cu13 install would
74
+ # never be attempted: the script would ask for a cu12 wheel at our pin, fail,
75
+ # retry UNPINNED, and the version guard in build_trt_engine.py would then
76
+ # kill the run after the VM was already paid for. 595-server reports CUDA 13.2
77
+ # and is what `ubuntu-drivers --gpgpu` selects on Ubuntu 24.04 today
78
+ # (measured on an A5000, 2026-09-18).
79
+ $SUDO ubuntu-drivers install --gpgpu || $SUDO apt-get install -y -qq nvidia-driver-595-server
80
+
81
+ # ubuntu-drivers --gpgpu installs the kernel module and the compute libs but
82
+ # NOT nvidia-utils, which is the package that owns /usr/bin/nvidia-smi. The
83
+ # module then loads fine and the GPU works, while every arch-detection step
84
+ # here and in build_engines.sh keys off nvidia-smi and reads the machine as
85
+ # having no GPU. Measured 2026-08-28: lsmod showed nvidia/nvidia_uvm loaded
86
+ # and `nvidia-smi` was command-not-found.
87
+ BRANCH="$($SUDO dpkg -l 2>/dev/null | grep -o 'nvidia-compute-utils-[0-9]*-server' | head -1 | sed 's/nvidia-compute-utils-//')"
88
+ if [ -n "$BRANCH" ]; then
89
+ $SUDO apt-get install -y -qq "nvidia-utils-$BRANCH" >/dev/null 2>&1 || warn "could not install nvidia-utils-$BRANCH - nvidia-smi may be missing"
90
+ fi
91
+
92
+ if command -v nvidia-smi >/dev/null 2>&1 && nvidia-smi >/dev/null 2>&1; then
93
+ ok "driver active without a reboot"
94
+ else
95
+ echo
96
+ warn "Driver installed, but the kernel module is not live until a REBOOT."
97
+ warn "Reboot, then run this script again - it will skip straight to the build:"
98
+ warn " reboot"
99
+ warn " curl -fsSL \"\$TOOLS_URL/bootstrap_linux.sh\" | bash"
100
+ exit 2
101
+ fi
102
+ fi
103
+ CC="$(nvidia-smi --query-gpu=compute_cap --format=csv,noheader 2>/dev/null | head -1 | tr -d ' ')"
104
+ GPU="$(nvidia-smi --query-gpu=name --format=csv,noheader 2>/dev/null | head -1 | sed 's/^ *//')"
105
+ DRV="$(nvidia-smi --query-gpu=driver_version --format=csv,noheader 2>/dev/null | head -1 | tr -d ' ')"
106
+ [ -n "$CC" ] || die "nvidia-smi reported no compute capability - driver present but GPU unusable."
107
+ SM="sm_${CC//./}"
108
+ ok "GPU: $GPU compute_cap $CC -> $SM driver $DRV"
109
+
110
+ . /etc/os-release 2>/dev/null || true
111
+ ok "OS: ${PRETTY_NAME:-unknown}"
112
+
113
+ # ── 1. system packages ────────────────────────────────────────────────────────────────
114
+ # python3 + pip + curl only. TensorRT arrives as a pip wheel from
115
+ # build_trt_engine.py and CUDA comes from the driver - installing a CUDA toolkit
116
+ # would only add a second, possibly mismatched, libcuda to the search path.
117
+ step "System packages"
118
+ if command -v apt-get >/dev/null 2>&1; then
119
+ export DEBIAN_FRONTEND=noninteractive
120
+ $SUDO apt-get update -qq || warn "apt-get update failed - continuing with what is installed"
121
+ $SUDO apt-get install -y -qq python3 python3-pip python3-venv curl ca-certificates >/dev/null \
122
+ || warn "apt-get install returned non-zero - continuing"
123
+ elif command -v dnf >/dev/null 2>&1; then
124
+ $SUDO dnf install -y -q python3 python3-pip curl ca-certificates >/dev/null || warn "dnf install returned non-zero"
125
+ elif command -v yum >/dev/null 2>&1; then
126
+ $SUDO yum install -y -q python3 python3-pip curl ca-certificates >/dev/null || warn "yum install returned non-zero"
127
+ else
128
+ warn "unknown package manager - assuming python3/pip/curl are already present"
129
+ fi
130
+
131
+ command -v "$PY" >/dev/null 2>&1 || die "$PY not found after package install."
132
+ ok "python: $($PY --version 2>&1)"
133
+
134
+ # PEP 668 marks distro pythons as externally managed; --break-system-packages is
135
+ # the sanctioned override and is exactly right on a throwaway build box.
136
+ PIPFLAGS=""
137
+ $PY -m pip install --dry-run --break-system-packages -q pip >/dev/null 2>&1 && PIPFLAGS="--break-system-packages"
138
+ $PY -m pip install $PIPFLAGS -q -U pip huggingface_hub >/dev/null 2>&1 \
139
+ || warn "pip bootstrap returned non-zero - run_matrix will retry per-package"
140
+ ok "pip ready${PIPFLAGS:+ ($PIPFLAGS)}"
141
+
142
+ # ── 2. fetch the build tools ──────────────────────────────────────────────────────────
143
+ step "Fetching build tools from $TOOLS_URL"
144
+ mkdir -p "$TOOLS"
145
+ cd "$TOOLS"
146
+ GOT=""; MISSING=""
147
+ for f in $TOOL_FILES; do
148
+ if curl -fsSL -o "$f" "${TOOLS_URL%/}/$f"; then
149
+ GOT="$GOT $f"
150
+ else
151
+ case " $TOOL_OPTIONAL " in
152
+ *" $f "*) MISSING="$MISSING $f" ;;
153
+ *) die "could not fetch $f from $TOOLS_URL - is the prefix public?" ;;
154
+ esac
155
+ fi
156
+ done
157
+ ok "fetched:$GOT"
158
+ [ -n "$MISSING" ] && warn "absent (fine unless an INT8 arch needs PTQ):$MISSING"
159
+ chmod +x build_engines.sh 2>/dev/null || true
160
+
161
+ # ── 3. build ──────────────────────────────────────────────────────────────────────────
162
+ head_ "Linux lane - building linux_x64 engines on $SM"
163
+ ARGS=""
164
+ for m in ${ONLY:-}; do ARGS="$ARGS --only $m"; done
165
+ for m in ${SKIP:-}; do ARGS="$ARGS --skip $m"; done
166
+
167
+ TOOLS_URL="$TOOLS_URL" HF_TOKEN="$HF_TOKEN" DEST_PREFIX="$DEST_PREFIX" WORKDIR="$WORK" \
168
+ $PY run_matrix.py $ARGS
169
+ RC=$?
170
+
171
+ # ── 4. report ─────────────────────────────────────────────────────────────────────────
172
+ head_ "RESULT - $GPU / $SM"
173
+ if [ "$RC" = "0" ]; then
174
+ echo -e " linux_x64 : ${G}OK${Z} (all models)"
175
+ else
176
+ echo -e " linux_x64 : ${R}$RC model(s) FAILED${Z}"
177
+ fi
178
+ echo
179
+ echo -e "${D} Verify what actually landed:${Z}"
180
+ echo -e "${D} https://huggingface.co/faxenoff/code-daemon-embed-v1/tree/main${Z}"
181
+ echo -e "${D} every name must end in _${SM}.engine and contain _linux_x64 for this box${Z}"
182
+ echo
183
+ echo -e "${D} The matching win_x64 cells come from bootstrap_win.ps1 on a Windows GPU VM${Z}"
184
+ echo -e "${D} with the same card - an engine built here will NOT load on Windows.${Z}"
185
+ exit $RC
_build-tools/bootstrap_win.ps1 ADDED
@@ -0,0 +1,411 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # bootstrap_win.ps1 - turn a bare Windows GPU VM into a two-OS TRT engine builder.
2
+ #
3
+ # One rented Windows box can produce BOTH halves of a {win_x64, linux_x64} pair:
4
+ # the Windows engines natively, the Linux engines inside WSL2 against the same
5
+ # physical GPU. That halves the rental - and, more importantly, it guarantees the
6
+ # two halves saw the identical GPU, driver and ONNX, so a difference between them
7
+ # is a real difference and not a difference between two rented machines.
8
+ #
9
+ # The WSL half is BEST EFFORT and says so loudly. GPU passthrough into WSL needs a
10
+ # WDDM-mode driver and nested virtualization on the hypervisor; a Tesla card left
11
+ # in TCC mode or a VM without nested virt will not have it, and this script
12
+ # diagnoses which of those it is rather than reporting a mysterious skip.
13
+ #
14
+ # -- On-VM usage (the only command you type) -------------------------------------------
15
+ # $env:TOOLS_URL = "https://<bucket>.s3.twcstorage.ru/_build-tools"
16
+ # $env:HF_TOKEN = "hf_...write..."
17
+ # irm "$($env:TOOLS_URL)/bootstrap_win.ps1" | iex
18
+ #
19
+ # Everything else is discovered: GPU arch, which models to build, at what precision.
20
+ #
21
+ # To pass a switch through the pipe, `iex` is not enough - it takes no arguments:
22
+ # & ([scriptblock]::Create((irm "$($env:TOOLS_URL)/bootstrap_win.ps1"))) -Stage wsl
23
+ #
24
+ # -Stage win Windows lane only (skip WSL entirely)
25
+ # -Stage wsl WSL lane only (assumes the Windows lane already ran)
26
+ # -Stage all both (default)
27
+ # -NoReboot never schedule a reboot; report what WSL still needs instead
28
+ # -Distro WSL distribution (default Ubuntu-24.04)
29
+ [CmdletBinding()]
30
+ param(
31
+ [ValidateSet("all", "win", "wsl")] [string] $Stage = "all",
32
+ [switch] $NoReboot,
33
+ [string] $Distro = "Ubuntu-24.04"
34
+ )
35
+
36
+ $ErrorActionPreference = "Stop"
37
+ $ProgressPreference = "SilentlyContinue" # Invoke-WebRequest is ~10x faster without it
38
+
39
+ # -- output helpers --------------------------------------------------------------------
40
+ function Head($m) { Write-Host ""; Write-Host ("=" * 72) -ForegroundColor DarkGray; Write-Host " $m" -ForegroundColor Cyan; Write-Host ("=" * 72) -ForegroundColor DarkGray }
41
+ function Step($m) { Write-Host "`n[>] $m" -ForegroundColor Cyan }
42
+ function Ok($m) { Write-Host " [OK] $m" -ForegroundColor Green }
43
+ function Warn($m) { Write-Host " [!] $m" -ForegroundColor Yellow }
44
+ function Die($m) { Write-Host " [!!] $m" -ForegroundColor Red; exit 1 }
45
+
46
+ $TOOLS_URL = [Environment]::GetEnvironmentVariable("TOOLS_URL")
47
+ $HF_TOKEN = [Environment]::GetEnvironmentVariable("HF_TOKEN")
48
+ $DEST_PREFIX = [Environment]::GetEnvironmentVariable("DEST_PREFIX")
49
+ $WORK = Join-Path $env:USERPROFILE "uc-build"
50
+ $TOOLS = Join-Path $WORK "_tools"
51
+ $STATE = Join-Path $WORK "bootstrap-state.json"
52
+
53
+ # The files a build needs on the box. build_matrix.json is what makes the run
54
+ # self-describing: precision per model per arch comes from the catalog, not from
55
+ # whatever the operator remembered to export.
56
+ $TOOL_FILES = @(
57
+ "run_matrix.py", "build_matrix.json",
58
+ "build_engines.ps1", "build_engines.sh",
59
+ "build_trt_engine.py", "quantize_onnx.py", "onnx_fp16.py", "calib_corpus.jsonl"
60
+ )
61
+ # Missing one of these is not fatal: fp16-only archs never touch the quantizer or
62
+ # the corpus, and paying for a 404 there would block a Turing run for no reason.
63
+ $TOOL_OPTIONAL = @("quantize_onnx.py", "calib_corpus.jsonl")
64
+
65
+ Head "ultracode cloud builder - Windows VM bootstrap"
66
+
67
+ if (-not $TOOLS_URL) { Die "set TOOLS_URL first, e.g. `$env:TOOLS_URL='https://<bucket>.s3.twcstorage.ru/_build-tools'" }
68
+ if (-not $HF_TOKEN -and -not $DEST_PREFIX) {
69
+ Die "set HF_TOKEN (a WRITE token) or DEST_PREFIX - otherwise the engines are built and discarded."
70
+ }
71
+
72
+ # -- 0. preflight: is this machine even eligible? --------------------------------------
73
+ Step "Preflight"
74
+
75
+ $isAdmin = ([Security.Principal.WindowsPrincipal] [Security.Principal.WindowsIdentity]::GetCurrent()
76
+ ).IsInRole([Security.Principal.WindowsBuiltInRole]::Administrator)
77
+ if (-not $isAdmin) { Die "run this in an ELEVATED PowerShell - installing Python and WSL needs it." }
78
+ Ok "elevated"
79
+
80
+ $osv = [Environment]::OSVersion.Version
81
+ $caption = (Get-CimInstance Win32_OperatingSystem).Caption
82
+ Ok ("{0} (build {1})" -f $caption, $osv.Build)
83
+ if ($osv.Build -lt 19041) {
84
+ # Server 2019 is 17763 and is what Selectel offers, so this is the normal
85
+ # case there rather than a problem: win_x64 builds here, linux_x64 comes from
86
+ # a separate Ubuntu VM. Stated once, plainly, so it does not read as a fault.
87
+ Write-Host " [i] build < 19041 - no WSL2 on this image. win_x64 builds here;" -ForegroundColor DarkGray
88
+ Write-Host " linux_x64 comes from a Linux VM (bootstrap_linux.sh). Expected on Server 2019." -ForegroundColor DarkGray
89
+ }
90
+
91
+ if (-not (Get-Command nvidia-smi -ErrorAction SilentlyContinue)) {
92
+ Die "nvidia-smi not on PATH - install the NVIDIA driver first. On a fresh cloud VM the driver is often NOT preinstalled; ask the provider for a GPU image or install from nvidia.com."
93
+ }
94
+ $cc = (& nvidia-smi --query-gpu=compute_cap --format=csv,noheader | Select-Object -First 1).Trim()
95
+ $gpu = (& nvidia-smi --query-gpu=name --format=csv,noheader | Select-Object -First 1).Trim()
96
+ $drv = (& nvidia-smi --query-gpu=driver_version --format=csv,noheader | Select-Object -First 1).Trim()
97
+ if (-not $cc) { Die "nvidia-smi reported no compute capability - the driver is present but the GPU is not usable." }
98
+ $SM = "sm_" + ($cc -replace '\.', '')
99
+ Ok ("GPU: {0} compute_cap {1} -> {2} driver {3}" -f $gpu, $cc, $SM, $drv)
100
+
101
+ # The driver model decides whether WSL can see this GPU at all. TCC (Tesla Compute
102
+ # Cluster) has no WDDM display stack, and /dev/dxg - the whole basis of WSL GPU
103
+ # passthrough - is a WDDM construct. Read it now so the WSL stage can explain
104
+ # itself instead of just failing.
105
+ $driverModel = ""
106
+ try {
107
+ $dm = (& nvidia-smi --query-gpu=driver_model.current --format=csv,noheader 2>$null | Select-Object -First 1)
108
+ if ($dm) { $driverModel = $dm.Trim() }
109
+ } catch { }
110
+ if ($driverModel) { Ok ("driver model: {0}" -f $driverModel) }
111
+
112
+ # -- 1. Python 3.13 - the cu13 TensorRT wheels are built for it ------------------------
113
+ Step "Python"
114
+
115
+ function Find-Py313 {
116
+ # Return the FULL PATH, never the bare name "py".
117
+ #
118
+ # PowerShell resolves a command as alias -> FUNCTION -> cmdlet -> program, and
119
+ # is case-insensitive. With `$PyExe = "py"` and a helper function named `Py`
120
+ # in scope, `& $PyExe` calls the FUNCTION, which calls `& $PyExe` again:
121
+ # infinite recursion, ending in "The script failed due to call depth
122
+ # overflow" right after the Python step announces itself. A path can never
123
+ # resolve to a function.
124
+ $launcher = Get-Command py.exe -CommandType Application -ErrorAction SilentlyContinue |
125
+ Select-Object -First 1
126
+ if ($launcher) {
127
+ & $launcher.Source -3.13 -c "import sys" *> $null
128
+ if ($LASTEXITCODE -eq 0) { return @{ Exe = $launcher.Source; Pre = @("-3.13") } }
129
+ }
130
+ $direct = Join-Path $env:LOCALAPPDATA "Programs\Python\Python313\python.exe"
131
+ if (Test-Path $direct) { return @{ Exe = $direct; Pre = @() } }
132
+ $direct = Join-Path $env:ProgramFiles "Python313\python.exe"
133
+ if (Test-Path $direct) { return @{ Exe = $direct; Pre = @() } }
134
+ return $null
135
+ }
136
+
137
+ $py = Find-Py313
138
+ if (-not $py) {
139
+ Warn "Python 3.13 not found - installing (the cu13 tensorrt wheels have no 3.12/3.11 build)"
140
+ $installer = Join-Path $env:TEMP "python-3.13-amd64.exe"
141
+ # python.org direct, not winget: winget is absent on Server images and its
142
+ # Store-backed Python is a stub that answers `python` with a store page.
143
+ $url = "https://www.python.org/ftp/python/3.13.7/python-3.13.7-amd64.exe"
144
+ Invoke-WebRequest -Uri $url -OutFile $installer -UseBasicParsing
145
+ # PrependPath so the WSL side and any later shell find it too; Include_launcher
146
+ # gives us `py -3.13`, which is what build_engines.ps1 looks for.
147
+ $p = Start-Process -FilePath $installer -Wait -PassThru -ArgumentList @(
148
+ "/quiet", "InstallAllUsers=1", "PrependPath=1", "Include_launcher=1", "Include_pip=1"
149
+ )
150
+ if ($p.ExitCode -ne 0) { Die ("python installer exited {0}" -f $p.ExitCode) }
151
+ $env:Path = [Environment]::GetEnvironmentVariable("Path", "Machine") + ";" +
152
+ [Environment]::GetEnvironmentVariable("Path", "User")
153
+ $py = Find-Py313
154
+ if (-not $py) { Die "Python 3.13 still not found after install." }
155
+ }
156
+ $PyExe = $py.Exe; $PyPre = $py.Pre
157
+ function Invoke-Py { & $PyExe @PyPre @args; if ($LASTEXITCODE -ne 0) { throw ("python exited {0}" -f $LASTEXITCODE) } }
158
+ Ok ("python: {0}" -f ((& $PyExe @PyPre --version) 2>&1))
159
+
160
+ # -- 2. fetch the build tools ----------------------------------------------------------
161
+ Step "Fetching build tools from $TOOLS_URL"
162
+ New-Item -ItemType Directory -Force -Path $WORK, $TOOLS | Out-Null
163
+ $fetched = @(); $missing = @()
164
+ foreach ($f in $TOOL_FILES) {
165
+ $dst = Join-Path $TOOLS $f
166
+ try {
167
+ Invoke-WebRequest -Uri ("{0}/{1}" -f $TOOLS_URL.TrimEnd('/'), $f) -OutFile $dst -UseBasicParsing
168
+ $fetched += $f
169
+ } catch {
170
+ if ($TOOL_OPTIONAL -contains $f) { $missing += $f } else { Die ("could not fetch {0} from {1} - is the prefix public? ({2})" -f $f, $TOOLS_URL, $_.Exception.Message) }
171
+ }
172
+ }
173
+ Ok ("fetched: {0}" -f ($fetched -join ", "))
174
+ if ($missing) { Warn ("absent (fine unless an INT8 arch needs PTQ): {0}" -f ($missing -join ", ")) }
175
+
176
+ # -- 3. the Windows lane ---------------------------------------------------------------
177
+ $winRc = $null
178
+ if ($Stage -eq "all" -or $Stage -eq "win") {
179
+ Head "Windows lane - building win_x64 engines on $SM"
180
+ $env:TOOLS_URL = $TOOLS_URL
181
+ $env:WORKDIR = $WORK
182
+ Push-Location $TOOLS
183
+ try {
184
+ & $PyExe @PyPre "run_matrix.py"
185
+ $winRc = $LASTEXITCODE
186
+ } finally { Pop-Location }
187
+ if ($winRc -eq 0) { Ok "win_x64 lane complete - every model uploaded" }
188
+ else { Warn ("win_x64 lane: {0} model(s) FAILED - see the log above" -f $winRc) }
189
+ }
190
+
191
+ # -- 4. the WSL lane -------------------------------------------------------------------
192
+ function Test-WslFeatures {
193
+ <# Both features must be Enabled before a distro can run in WSL2 mode.
194
+ Reported separately because the failure modes differ: no VirtualMachinePlatform
195
+ usually means nested virtualization is off on the hypervisor, which is a
196
+ provider-side setting no amount of local work fixes. #>
197
+ $res = @{}
198
+ foreach ($n in @("Microsoft-Windows-Subsystem-Linux", "VirtualMachinePlatform")) {
199
+ try { $res[$n] = (Get-WindowsOptionalFeature -Online -FeatureName $n).State }
200
+ catch { $res[$n] = "Unknown" }
201
+ }
202
+ return $res
203
+ }
204
+
205
+ function Enable-WslFeatures {
206
+ $needReboot = $false
207
+ foreach ($n in @("Microsoft-Windows-Subsystem-Linux", "VirtualMachinePlatform")) {
208
+ $st = (Get-WindowsOptionalFeature -Online -FeatureName $n).State
209
+ if ($st -ne "Enabled") {
210
+ Step "Enabling Windows feature $n"
211
+ $r = Enable-WindowsOptionalFeature -Online -FeatureName $n -All -NoRestart
212
+ if ($r.RestartNeeded) { $needReboot = $true }
213
+ }
214
+ }
215
+ return $needReboot
216
+ }
217
+
218
+ function Register-Resume {
219
+ <# A RunOnce entry, not a scheduled task: RunOnce fires on the next
220
+ interactive logon of THIS user with the console attached, which is what an
221
+ operator reconnecting over RDP actually gets. A SYSTEM scheduled task
222
+ would run headless and its output would go nowhere.
223
+
224
+ The token does NOT go in the registry. A RunOnce value is world-readable
225
+ and survives in registry backups and any image the provider snapshots; a
226
+ file with an Administrators-only ACL, deleted by the resume script as its
227
+ first act, keeps the blast radius to the reboot window. #>
228
+ $tokFile = Join-Path $WORK "resume-token.txt"
229
+ Set-Content -Path $tokFile -Value $HF_TOKEN -Encoding ascii -NoNewline
230
+ $acl = Get-Acl $tokFile
231
+ $acl.SetAccessRuleProtection($true, $false) # drop inherited user-readable ACEs
232
+ $acl.SetAccessRule((New-Object System.Security.AccessControl.FileSystemAccessRule(
233
+ "BUILTIN\Administrators", "FullControl", "Allow")))
234
+ Set-Acl -Path $tokFile -AclObject $acl
235
+
236
+ # `iex` takes no -Args; a scriptblock does. This is the only shape that can
237
+ # pass -Stage through a piped one-liner.
238
+ $inner = ("`$env:TOOLS_URL='{0}'; " +
239
+ "`$env:HF_TOKEN=(Get-Content '{1}' -Raw); Remove-Item '{1}' -Force; " +
240
+ "& ([scriptblock]::Create((irm '{0}/bootstrap_win.ps1'))) -Stage wsl") -f $TOOLS_URL, $tokFile
241
+ $enc = [Convert]::ToBase64String([Text.Encoding]::Unicode.GetBytes($inner))
242
+ $cmd = "powershell -NoProfile -ExecutionPolicy Bypass -EncodedCommand $enc"
243
+
244
+ New-ItemProperty -Path "HKLM:\SOFTWARE\Microsoft\Windows\CurrentVersion\RunOnce" `
245
+ -Name "UltracodeBuildResume" -Value $cmd -PropertyType String -Force | Out-Null
246
+ Warn "the WSL lane will resume automatically at the next logon (RunOnce)"
247
+ Warn ("token parked at {0} (Administrators only); the resume deletes it before building" -f $tokFile)
248
+ }
249
+
250
+ $wslRc = $null
251
+ $wslSkipReason = $null
252
+
253
+ if ($Stage -eq "all" -or $Stage -eq "wsl") {
254
+ Head "WSL lane - building linux_x64 engines on the same $SM GPU"
255
+
256
+ if ($osv.Build -lt 19041) {
257
+ $wslSkipReason = "Windows build $($osv.Build) < 19041 - WSL2 unavailable on this image"
258
+ } else {
259
+ $feat = Test-WslFeatures
260
+ foreach ($k in $feat.Keys) { Write-Host (" feature {0,-38} {1}" -f $k, $feat[$k]) }
261
+
262
+ if ($feat["VirtualMachinePlatform"] -ne "Enabled" -or
263
+ $feat["Microsoft-Windows-Subsystem-Linux"] -ne "Enabled") {
264
+ if ($NoReboot) {
265
+ $wslSkipReason = "WSL features are off and -NoReboot was given. Enable them and rerun with -Stage wsl."
266
+ } else {
267
+ $need = Enable-WslFeatures
268
+ if ($need) {
269
+ Register-Resume
270
+ Head "REBOOT REQUIRED"
271
+ Write-Host " Windows features were just enabled. The machine reboots in 15 seconds;"
272
+ Write-Host " log back in and the WSL lane resumes on its own."
273
+ if ($winRc -ne $null -and $winRc -ne 0) {
274
+ Warn ("the Windows lane had {0} failure(s) - re-run -Stage win after the reboot" -f $winRc)
275
+ }
276
+ Start-Sleep -Seconds 15
277
+ Restart-Computer -Force
278
+ exit 0
279
+ }
280
+ }
281
+ }
282
+ }
283
+
284
+ if (-not $wslSkipReason) {
285
+ # Is a distro registered? `wsl -l -q` output is UTF-16 on older builds -
286
+ # match loosely rather than parsing it as a clean list.
287
+ $distros = (& wsl.exe -l -q 2>$null) -join "`n"
288
+ $haveDistro = $distros -match [regex]::Escape($Distro.Split('-')[0])
289
+
290
+ if (-not $haveDistro) {
291
+ Step "Installing WSL distribution $Distro"
292
+ # --no-launch registers without dropping into the interactive
293
+ # "create a user" prompt, which would hang an unattended run forever.
294
+ # --web-download avoids the Microsoft Store, absent on Server images.
295
+ & wsl.exe --install --no-launch --web-download -d $Distro
296
+ if ($LASTEXITCODE -ne 0) {
297
+ Warn "wsl --install -d $Distro failed; retrying without --web-download"
298
+ & wsl.exe --install --no-launch -d $Distro
299
+ }
300
+ if ($LASTEXITCODE -ne 0) { $wslSkipReason = "could not install the $Distro distribution (wsl --install exited $LASTEXITCODE)" }
301
+ else {
302
+ # First run finishes registration. -u root skips user creation.
303
+ & wsl.exe -d $Distro -u root -- true 2>$null | Out-Null
304
+ }
305
+ }
306
+ }
307
+
308
+ if (-not $wslSkipReason) {
309
+ Step "Probing the GPU inside WSL"
310
+ $wslSmi = (& wsl.exe -d $Distro -u root -- bash -lc "nvidia-smi --query-gpu=name,compute_cap --format=csv,noheader 2>&1") -join " "
311
+ if ($LASTEXITCODE -ne 0 -or $wslSmi -notmatch '\d\.\d') {
312
+ # This is the failure worth diagnosing precisely - it is the single
313
+ # most likely reason the Linux half of the matrix does not get built.
314
+ Warn "nvidia-smi inside WSL did not report a GPU."
315
+ Write-Host " raw: $wslSmi" -ForegroundColor DarkGray
316
+ Write-Host ""
317
+ Write-Host " Why this happens, in order of likelihood on a cloud VM:" -ForegroundColor Yellow
318
+ if ($driverModel -match "TCC") {
319
+ Write-Host " 1. THIS ONE: the driver is in TCC mode ($driverModel). WSL needs WDDM." -ForegroundColor Red
320
+ Write-Host " Try: nvidia-smi -dm 0 then reboot, then rerun with -Stage wsl"
321
+ Write-Host " (Datacenter cards default to TCC; some vGPU profiles cannot switch.)"
322
+ } else {
323
+ Write-Host " 1. Driver model must be WDDM, not TCC. Check: nvidia-smi -q | findstr /i `"Driver Model`""
324
+ Write-Host " Switch with: nvidia-smi -dm 0 (then reboot)"
325
+ }
326
+ Write-Host " 2. NVIDIA vGPU / GRID profiles do not expose /dev/dxg to WSL at all."
327
+ Write-Host " If this is a vGPU VM, the Linux engines need a separate Linux VM."
328
+ Write-Host " 3. Nested virtualization off on the hypervisor. In VMware/Cloud Director:"
329
+ Write-Host " the VM needs 'Expose hardware assisted virtualization' (nested_hypervisor_enabled)."
330
+ Write-Host " 4. Driver older than 465 - no WSL CUDA support at all. This one is $drv."
331
+ Write-Host ""
332
+ $wslSkipReason = "no GPU visible inside WSL (see the diagnosis above)"
333
+ } else {
334
+ Ok ("WSL sees: {0}" -f $wslSmi.Trim())
335
+ }
336
+ }
337
+
338
+ if (-not $wslSkipReason) {
339
+ Step "Preparing the WSL toolchain"
340
+ # python3-pip + venv only. TensorRT arrives as a pip wheel from
341
+ # build_trt_engine.py, and CUDA itself comes from the Windows driver via
342
+ # /usr/lib/wsl/lib - installing a CUDA toolkit in the distro would only
343
+ # shadow it with a second, wrong libcuda.
344
+ $prep = @(
345
+ "export DEBIAN_FRONTEND=noninteractive",
346
+ "apt-get update -qq",
347
+ "apt-get install -y -qq python3 python3-pip python3-venv curl ca-certificates >/dev/null",
348
+ "python3 -m pip install --break-system-packages -q -U pip huggingface_hub 2>/dev/null || python3 -m pip install -q -U pip huggingface_hub"
349
+ ) -join " && "
350
+ & wsl.exe -d $Distro -u root -- bash -lc "$prep"
351
+ if ($LASTEXITCODE -ne 0) { Warn "apt/pip prep returned $LASTEXITCODE - continuing, the build may still work" }
352
+
353
+ Step "Running the Linux matrix inside WSL"
354
+ # The tools are re-fetched INSIDE the distro rather than read across
355
+ # /mnt/c: DrvFs has no executable bit and its inode semantics confuse
356
+ # anything that stats a file twice. A second download costs seconds.
357
+ # Single-quoted: `$HOME` is expanded by bash inside the distro (root's home
358
+ # there), never by PowerShell, whose own $HOME is the Windows profile.
359
+ $wslWork = '$HOME/uc-build'
360
+ $fetch = "mkdir -p $wslWork/_tools && cd $wslWork/_tools && for f in " +
361
+ ($TOOL_FILES -join " ") +
362
+ "; do curl -fsSL -o `$f `"$($TOOLS_URL.TrimEnd('/'))/`$f`" || echo `" [!] optional/absent: `$f`"; done"
363
+ & wsl.exe -d $Distro -u root -- bash -lc "$fetch"
364
+
365
+ $run = "cd $wslWork/_tools && HF_TOKEN='$HF_TOKEN' TOOLS_URL='$TOOLS_URL' " +
366
+ ($(if ($DEST_PREFIX) { "DEST_PREFIX='$DEST_PREFIX' " } else { "" })) +
367
+ "WORKDIR=$wslWork python3 run_matrix.py"
368
+ & wsl.exe -d $Distro -u root -- bash -lc "$run"
369
+ $wslRc = $LASTEXITCODE
370
+ if ($wslRc -eq 0) { Ok "linux_x64 lane complete - every model uploaded" }
371
+ else { Warn ("linux_x64 lane: {0} model(s) FAILED" -f $wslRc) }
372
+ }
373
+ }
374
+
375
+ # -- 5. report -------------------------------------------------------------------------
376
+ Head "RESULT - $gpu / $SM"
377
+ if ($winRc -ne $null) {
378
+ if ($winRc -eq 0) { Write-Host " win_x64 : OK (all models)" -ForegroundColor Green }
379
+ else { Write-Host (" win_x64 : {0} model(s) FAILED" -f $winRc) -ForegroundColor Red }
380
+ } else { Write-Host " win_x64 : not run (-Stage $Stage)" -ForegroundColor DarkGray }
381
+
382
+ if ($wslSkipReason) {
383
+ # An OS that cannot run WSL2 at all is a FACT about the image, not a failure
384
+ # of this run - Windows Server 2019 (17763) is below the 19041 floor and no
385
+ # amount of retrying changes that. Colour and exit code below treat the two
386
+ # kinds of skip differently, because a caller that branches on the exit code
387
+ # would otherwise see every single Server 2019 build as a failure.
388
+ $expectedSkip = $wslSkipReason -match "19041|WSL2 unavailable"
389
+ $c = if ($expectedSkip) { "DarkGray" } else { "Yellow" }
390
+ Write-Host (" linux_x64 : SKIPPED{0}" -f $(if ($expectedSkip) { " (expected on this Windows version)" } else { "" })) -ForegroundColor $c
391
+ Write-Host (" {0}" -f $wslSkipReason) -ForegroundColor $c
392
+ Write-Host " -> build these cells on a separate Linux GPU VM with bootstrap_linux.sh" -ForegroundColor $c
393
+ } elseif ($wslRc -ne $null) {
394
+ if ($wslRc -eq 0) { Write-Host " linux_x64 : OK (all models)" -ForegroundColor Green }
395
+ else { Write-Host (" linux_x64 : {0} model(s) FAILED" -f $wslRc) -ForegroundColor Red }
396
+ } else { Write-Host " linux_x64 : not run (-Stage $Stage)" -ForegroundColor DarkGray }
397
+
398
+ Write-Host ""
399
+ Write-Host " Verify what actually landed:" -ForegroundColor DarkGray
400
+ Write-Host " https://huggingface.co/faxenoff/code-daemon-embed-v1/tree/main" -ForegroundColor DarkGray
401
+ Write-Host (" every name must end in _{0}.engine for this box" -f $SM) -ForegroundColor DarkGray
402
+
403
+ $fail = 0
404
+ if ($winRc) { $fail += $winRc }
405
+ if ($wslRc) { $fail += $wslRc }
406
+ # A skip the OS makes unavoidable is not counted. A skip caused by something
407
+ # fixable - TCC driver mode, nested virtualization off, an install that failed -
408
+ # still is, because those are worth acting on and the operator may only be
409
+ # watching the exit code.
410
+ if ($wslSkipReason -and -not ($wslSkipReason -match "19041|WSL2 unavailable")) { $fail += 1 }
411
+ exit $fail
_build-tools/build_engines.ps1 ADDED
@@ -0,0 +1,732 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # build_engines.ps1 - standalone TRT-engine builder for a rented Windows GPU VM.
2
+ #
3
+ # Windows twin of build_engines.sh. A TRT engine is locked to {GPU arch x OS x TRT
4
+ # version}, so the Windows (win_x64) engines must be built ON Windows - a Linux build
5
+ # can never produce them. This script: pulls a distilled FP32 ONNX from OUR S3,
6
+ # (optionally) PTQ-quantizes to INT8, builds the TensorRT engines for THIS VM's GPU
7
+ # architecture (auto-detected via nvidia-smi), and uploads the .engine files back to S3.
8
+ #
9
+ # Targets Windows PowerShell 5.1 (the default on a fresh Windows VM) - no pwsh-7-only syntax.
10
+ #
11
+ # -- On-VM usage (the ONLY file you must get onto the VM) --
12
+ # 1. Install prerequisites yourself (README.md ?Prereqs): NVIDIA driver + CUDA 13,
13
+ # Python 3.13 (cu13 TensorRT wheels match the daemon's nvinfer_11), rclone.exe on PATH.
14
+ # (TensorRT itself is auto-installed by build_trt_engine.py.)
15
+ # 2. Set S3 creds + which model/run to build, then run:
16
+ # $env:S3_BUCKET="fedor-ml"; $env:S3_ACCESS_KEY="..."; $env:S3_SECRET_KEY="..."
17
+ # $env:MODEL_ID="code-daemon-embed-v1"; $env:RUN_ID="run-1781916112"; $env:TRAIN_VARIANT="4l-768h"
18
+ # powershell -ExecutionPolicy Bypass -File build_engines.ps1
19
+ #
20
+ # Everything is env-driven; the GPU arch is DETECTED on the VM (you never pass it).
21
+ $ErrorActionPreference = "Stop"
22
+
23
+ # -- Stage 0: optional remote config - pull creds + params from your domain ------------
24
+ # On-VM command becomes two lines (no creds typed on the box):
25
+ # $env:TOOLS_URL="https://app.fabuza.ru/ml"
26
+ # irm "$($env:TOOLS_URL)/build_engines.ps1" | iex
27
+ # build.env is a KEY=VALUE file you serve ONLY during a build (then close / IP-lock). Skipped when
28
+ # S3_ACCESS_KEY is already set. Override the URL with CONFIG_URL (if your host won't serve ".env").
29
+ if (-not [Environment]::GetEnvironmentVariable('S3_ACCESS_KEY')) {
30
+ $cfgUrl = [Environment]::GetEnvironmentVariable('CONFIG_URL')
31
+ if (-not $cfgUrl) { $tu = [Environment]::GetEnvironmentVariable('TOOLS_URL'); if ($tu) { $cfgUrl = $tu.TrimEnd('/') + '/build.env' } }
32
+ if ($cfgUrl) {
33
+ try {
34
+ $txt = (Invoke-WebRequest -Uri $cfgUrl -UseBasicParsing).Content
35
+ foreach ($line in ($txt -split "`n")) {
36
+ if ($line -match '^\s*([A-Za-z_][A-Za-z0-9_]*)\s*=\s*(.*)$') {
37
+ [Environment]::SetEnvironmentVariable($matches[1], $matches[2].Trim().Trim('"').Trim("'"))
38
+ }
39
+ }
40
+ Write-Host "[cfg] loaded remote config from $cfgUrl"
41
+ } catch { }
42
+ }
43
+ }
44
+
45
+ # -- CONFIG (all overridable via env) -----------------------------------------------
46
+ function Env-Or($name, $default) { $v = [Environment]::GetEnvironmentVariable($name); if ([string]::IsNullOrEmpty($v)) { return $default } else { return $v } }
47
+
48
+ # Same, but an EMPTY value is a value. BUCKETS="" means "one engine, no bucket
49
+ # suffix" - which is what a reranker or NER model needs. Env-Or would swallow
50
+ # that and hand back the "s m l" default, producing three suffixed engines while
51
+ # the daemon looks for the un-suffixed name and finds nothing.
52
+ function Env-OrExact($name, $default) {
53
+ $v = [Environment]::GetEnvironmentVariable($name)
54
+ if ($null -eq $v) { return $default } else { return $v }
55
+ }
56
+
57
+ # S3 is OPTIONAL. On the all-HuggingFace lane (ONNX in from a public model repo,
58
+ # engines out to the same repo) the VM holds no S3 credentials at all - which is
59
+ # the point: a rented box we do not own should carry exactly one secret, and that
60
+ # secret should be scoped to the repos it writes. The requirement is re-derived
61
+ # below, after the source/destination modes are known, so a missing key fails with
62
+ # "you asked for the S3 lane" rather than at the top of a run that never needed it.
63
+ $S3_BUCKET = Env-Or "S3_BUCKET" ""
64
+ $S3_ACCESS_KEY = Env-Or "S3_ACCESS_KEY" ""
65
+ $S3_SECRET_KEY = Env-Or "S3_SECRET_KEY" ""
66
+ $S3_ENDPOINT = Env-Or "S3_ENDPOINT" "https://storage.yandexcloud.net"
67
+
68
+ $MODEL_ID = Env-Or "MODEL_ID" "code-daemon-embed-v1" # engine filename prefix + local dir
69
+ $S3_MODEL_DIR = Env-Or "S3_MODEL_DIR" "code-daemon-embed" # distill MODEL_DIR (S3 path segment)
70
+ $RUN_ID = Env-Or "RUN_ID" "" # distill run id (e.g. run-1781916112)
71
+ $TRAIN_VARIANT = Env-Or "TRAIN_VARIANT" "4l-768h" # distill student variant subdir in S3
72
+ $SRC_ONNX_S3 = Env-Or "SRC_ONNX_S3" "" # full S3 path to final/ (overrides RUN_ID/TRAIN_VARIANT)
73
+
74
+ $BUCKETS = Env-OrExact "BUCKETS" "s m l" # "" is meaningful - see Env-OrExact # TRT length buckets; "" = single-engine (NER/reranker)
75
+ $ROLE = Env-Or "ROLE" "embedding" # embedding | ner | reranker
76
+ # Capture whether PRECISION was set explicitly BEFORE defaulting - the sm_75
77
+ # auto-pick (after GPU detection) must not override an explicit caller choice.
78
+ $PRECISION_EXPLICIT = -not [string]::IsNullOrEmpty([Environment]::GetEnvironmentVariable("PRECISION"))
79
+ $PRECISION = Env-Or "PRECISION" "int8" # int8 | fp16 | fp8
80
+
81
+ $CALIB_DB_S3 = Env-Or "CALIB_DB_S3" "" # Mode A: staged graph.db for INT8 calibration
82
+ $INT8_ONNX_S3 = Env-Or "INT8_ONNX_S3" "" # Mode B (S3): reuse pre-quantized int8 ONNX (no PTQ)
83
+ $HF_MODEL_REPO = Env-Or "HF_MODEL_REPO" "" # Mode HF (recommended): pull ONNX from the public HF repo (no S3/creds); wins over all
84
+ # Exact TensorRT pin, from build_matrix.json (generated from
85
+ # vendor/tensorrt/VERSION). Read HERE, with the rest of the config, because
86
+ # it is needed both to install TensorRT and - earlier - to write the pin file
87
+ # the worker reads. Defining it further down left that file unwritten and the
88
+ # failure looked identical to TensorRT not being installed at all.
89
+ $TRT_PIP = Env-Or "TRT_PIP_VERSION" ""
90
+ $PTQ_SAMPLES = Env-Or "PTQ_SAMPLES" "500"
91
+ $PTQ_MAX_SEQ = Env-Or "PTQ_MAX_SEQ" "128"
92
+
93
+ # Build tools come from, in order: a file next to this script -> TOOLS_URL (http) -> TOOLS_PREFIX (S3).
94
+ # TOOLS_URL lets you `irm <url>/build_engines.ps1 | iex` and have it pull its .py from the same host.
95
+ # Host ONLY these non-secret files there; never creds/ONNX/calib.db.
96
+ $TOOLS_URL = Env-Or "TOOLS_URL" ""
97
+ $TOOLS_PREFIX = Env-Or "TOOLS_PREFIX" ("s3:{0}/_build-tools" -f $S3_BUCKET)
98
+ $DEST_PREFIX = Env-Or "DEST_PREFIX" "" # S3 upload root; empty + HF_UPLOAD_REPO = HF-only lane
99
+ $WORKDIR = Env-Or "WORKDIR" (Join-Path $env:USERPROFILE "uc-build")
100
+
101
+ # -- HuggingFace destination - the default lane ----------------------------------------
102
+ # Engines go back to the SAME public repo the ONNX came from, which is where the
103
+ # daemon looks for them (`model_manager.downloadModel` builds the URL from the
104
+ # catalog id). That removes the S3 round-trip entirely: nothing has to be copied
105
+ # from a bucket to HF afterwards, and no step can be forgotten in between.
106
+ # HF_TOKEN must be a WRITE token - prefer a fine-grained one scoped to these repos.
107
+ $HF_UPLOAD_REPO = Env-Or "HF_UPLOAD_REPO" $HF_MODEL_REPO
108
+ $HF_TOKEN = Env-Or "HF_TOKEN" ""
109
+ $HF_UPLOAD = ($HF_UPLOAD_REPO -and $HF_TOKEN)
110
+
111
+ # -- helpers -------------------------------------------------------------------------
112
+ function Step($m) { Write-Host "`n[>] $m" -ForegroundColor Cyan }
113
+ function Ok($m) { Write-Host " [OK] $m" -ForegroundColor Green }
114
+ function Die($m) { Write-Host " [!!] $m" -ForegroundColor Red; exit 1 }
115
+ function Warn($m) { Write-Host " [!] $m" -ForegroundColor Yellow }
116
+
117
+ # -- is S3 needed at all? --------------------------------------------------------------
118
+ # Three independent consumers. Each is skipped when its HF/HTTP equivalent is set,
119
+ # so the common case (HF in, HF out, tools over HTTPS) needs no bucket.
120
+ $SelfDirEarly = ""
121
+ if ($MyInvocation.MyCommand.Path) { $SelfDirEarly = Split-Path -Parent $MyInvocation.MyCommand.Path }
122
+ $s3_for_src = (-not $HF_MODEL_REPO) # ONNX source
123
+ $s3_for_dest = ($DEST_PREFIX -ne "") # engine upload
124
+ $s3_for_tools = ((-not $TOOLS_URL) -and (-not $SelfDirEarly)) # the .py workers
125
+ $NEEDS_S3 = ($s3_for_src -or $s3_for_dest -or $s3_for_tools)
126
+
127
+ if (-not ($HF_UPLOAD -or $s3_for_dest)) {
128
+ Die ("no destination: set HF_UPLOAD_REPO + HF_TOKEN (recommended), or DEST_PREFIX for S3. " +
129
+ "Engines built and thrown away is the one outcome worth failing early on.")
130
+ }
131
+ if ($NEEDS_S3) {
132
+ $why = @(); if ($s3_for_src) { $why += "ONNX source" }; if ($s3_for_dest) { $why += "engine upload" }; if ($s3_for_tools) { $why += "build tools" }
133
+ if (-not $S3_BUCKET) { Die ("S3_BUCKET required for: {0}. Set HF_MODEL_REPO / TOOLS_URL to avoid S3 entirely." -f ($why -join ', ')) }
134
+ if (-not $S3_ACCESS_KEY) { Die ("S3_ACCESS_KEY required for: {0}" -f ($why -join ', ')) }
135
+ if (-not $S3_SECRET_KEY) { Die ("S3_SECRET_KEY required for: {0}" -f ($why -join ', ')) }
136
+ if (-not (Get-Command rclone -ErrorAction SilentlyContinue)) { Die "rclone not found on PATH - required for the S3 lane (README ?Prereqs)." }
137
+ }
138
+ if (-not (Get-Command nvidia-smi -ErrorAction SilentlyContinue)) { Die "nvidia-smi not found - no NVIDIA driver? TRT needs a GPU." }
139
+
140
+ # -- 1. resolve python - prefer py -3.13 (cu13 TensorRT matches the daemon) ------------
141
+ # FULL PATHS, never bare names. PowerShell resolves alias -> FUNCTION -> cmdlet
142
+ # -> program and ignores case, so `$PyExe = "py"` plus a helper named `Py` makes
143
+ # `& $PyExe` call the helper, which calls itself: "The script failed due to call
144
+ # depth overflow". A resolved path cannot collide with a function name.
145
+ $PyExe = (Get-Command python.exe -CommandType Application -ErrorAction SilentlyContinue |
146
+ Select-Object -First 1).Source
147
+ $PyPre = @()
148
+ $launcher = Get-Command py.exe -CommandType Application -ErrorAction SilentlyContinue |
149
+ Select-Object -First 1
150
+ if ($launcher) {
151
+ & $launcher.Source -3.13 --version *> $null
152
+ if ($LASTEXITCODE -eq 0) { $PyExe = $launcher.Source; $PyPre = @("-3.13") }
153
+ }
154
+ if (-not $PyExe) { Die "no python found on PATH (looked for py.exe and python.exe)" }
155
+ # The verdict on an external program is its EXIT CODE, never the fact that it
156
+ # wrote to stderr. Under ErrorActionPreference=Stop those are conflated: one
157
+ # stderr line - a TensorRT deprecation notice, a pip advisory, a traceback from
158
+ # a deliberate probe - becomes a terminating error before this function's own
159
+ # check ever runs. Continue inside; throw only on a real non-zero exit.
160
+ # ---- running Python snippets --------------------------------------------------
161
+ # Never `python -c <multi-line string>`. PowerShell's quoting of a multi-line
162
+ # argument to a NATIVE program is not reliable: Python receives a truncated
163
+ # program and reports `SyntaxError: '(' was never closed`, which looks like a bug
164
+ # in the snippet instead of in its delivery. A temp file has no such ambiguity.
165
+ function Invoke-PyCode {
166
+ param([string] $Code, [string[]] $CodeArgs = @())
167
+ $f = Join-Path $env:TEMP ("uc-py-{0}.py" -f ([guid]::NewGuid().ToString('N').Substring(0, 8)))
168
+ # ASCII + no BOM: the snippets are ASCII by construction, and a BOM would be
169
+ # the first thing Python 3.13 complains about.
170
+ [IO.File]::WriteAllText($f, $Code, (New-Object Text.UTF8Encoding($false)))
171
+ try {
172
+ $prev = $ErrorActionPreference
173
+ $ErrorActionPreference = "Continue"
174
+ try {
175
+ & $PyExe @PyPre $f @CodeArgs
176
+ return $LASTEXITCODE
177
+ } finally { $ErrorActionPreference = $prev }
178
+ } finally { Remove-Item $f -ErrorAction SilentlyContinue }
179
+ }
180
+
181
+ function Invoke-Py {
182
+ $prev = $ErrorActionPreference
183
+ $ErrorActionPreference = "Continue"
184
+ try {
185
+ & $PyExe @PyPre @args
186
+ if ($LASTEXITCODE -ne 0) { throw "python exited $LASTEXITCODE" }
187
+ } finally { $ErrorActionPreference = $prev }
188
+ }
189
+ $pyver = (& $PyExe @PyPre --version) 2>&1
190
+ Ok ("python: {0}" -f $pyver)
191
+
192
+ # -- 2. detect GPU arch (sm_XX) + OS arch - the script figures out the GPU itself ------
193
+ Step "Detecting GPU + platform"
194
+ $cc = (& nvidia-smi --query-gpu=compute_cap --format=csv,noheader | Select-Object -First 1).Trim()
195
+ if (-not $cc) { Die "could not read compute_cap from nvidia-smi." }
196
+ $SM = "sm_" + ($cc -replace '\.','') # 8.6 -> sm_86, 8.9 -> sm_89, 12.0 -> sm_120
197
+ $gpuName = (& nvidia-smi --query-gpu=name --format=csv,noheader | Select-Object -First 1).Trim()
198
+ $OS_ARCH = "win_x64"
199
+ Ok ("GPU: {0} -> {1} platform: {2}" -f $gpuName, $SM, $OS_ARCH)
200
+
201
+ # sm_75 (Turing) ships FP16, not INT8: no W8A16 attention-fusion win on Turing
202
+ # for small encoders, and FP16 skips PTQ/calibration entirely (no CALIB_DB /
203
+ # INT8_ONNX needed). Auto-pick fp16 for Turing unless PRECISION was set explicitly.
204
+ if ($SM -eq "sm_75" -and -not $PRECISION_EXPLICIT -and $PRECISION -eq "int8") {
205
+ $PRECISION = "fp16"
206
+ Ok "Turing sm_75 -> PRECISION=fp16 (auto; INT8 has no Turing win, FP16 needs no calib)"
207
+ }
208
+
209
+ # -- 3. one-off rclone.conf from env - only on the S3 lane -----------------------------
210
+ # Written even when only ONE of the three S3 consumers is active; `RC` then simply
211
+ # goes unused. Guarded so the HF-only lane never materialises a credentials file on
212
+ # a machine we are about to hand back to the provider.
213
+ $Conf = $null
214
+ if ($NEEDS_S3) {
215
+ $Conf = Join-Path $env:TEMP ("rclone-build-{0}.conf" -f ([guid]::NewGuid().ToString('N').Substring(0,8)))
216
+ @"
217
+ [s3]
218
+ type = s3
219
+ provider = Other
220
+ access_key_id = $S3_ACCESS_KEY
221
+ secret_access_key = $S3_SECRET_KEY
222
+ endpoint = $S3_ENDPOINT
223
+ acl = private
224
+ "@ | Set-Content -Path $Conf -Encoding ascii
225
+ }
226
+ function RC {
227
+ if (-not $Conf) { throw "S3 requested but no credentials were configured" }
228
+ $prev = $ErrorActionPreference
229
+ $ErrorActionPreference = "Continue" # rclone reports progress on stderr
230
+ try {
231
+ & rclone --config $Conf @args
232
+ if ($LASTEXITCODE -ne 0) { throw ("rclone failed: {0}" -f ($args -join ' ')) }
233
+ } finally { $ErrorActionPreference = $prev }
234
+ }
235
+ function RCsoft { if ($Conf) { & rclone --config $Conf @args *> $null } } # best-effort (optional sidecars)
236
+
237
+ # -- HuggingFace upload helper ---------------------------------------------------------
238
+ # `HfApi.upload_file` rather than a hand-rolled REST PUT: it does the multipart /
239
+ # LFS dance an .engine needs, and it is the same call `models/_compile/publish.py`
240
+ # makes at a desk, so a cloud-built engine lands byte-identically to a local one.
241
+ # Installed lazily - a Turing VM builds FP16 only and would otherwise pay for a
242
+ # wheel it never imports.
243
+ $script:HfReady = $false
244
+ function Ensure-Hf {
245
+ # Idempotent and quiet. pip is fast when the package is already present, and
246
+ # that beats probing with an import whose failure prints a traceback that
247
+ # looks like an error but is the expected answer.
248
+ if ($script:HfReady) { return }
249
+ $prev = $ErrorActionPreference
250
+ $ErrorActionPreference = "Continue"
251
+ try {
252
+ & $PyExe @PyPre -m pip install -q --disable-pip-version-check huggingface_hub 2>&1 |
253
+ Where-Object { $_ -notmatch "^\[notice\]" } | ForEach-Object { Write-Host (" " + $_) }
254
+ } finally { $ErrorActionPreference = $prev }
255
+ $script:HfReady = $true
256
+ }
257
+ # The uploader, kept identical to the one in build_engines.sh so the two OS lanes
258
+ # cannot drift in how they write to the same repository.
259
+ #
260
+ # RETRY IS NOT OPTIONAL HERE. Windows Server 2019 cannot run WSL2, so win_x64 and
261
+ # linux_x64 are built on two machines, and the sensible thing is to run them at
262
+ # the same time - which means two writers committing to ONE HuggingFace repo. The
263
+ # filenames never collide (_win_x64_ vs _linux_x64_), but a commit does: HF
264
+ # rejects a write against a revision that moved under it. That is a transient
265
+ # conflict, not a failure, and losing a 40-minute engine to it would be absurd.
266
+ $HfPutPy = @'
267
+ import os, sys, time, random
268
+ from huggingface_hub import HfApi
269
+
270
+ local, repo, remote = sys.argv[1], sys.argv[2], sys.argv[3]
271
+ api = HfApi(token=os.environ["HF_TOKEN"])
272
+
273
+ ATTEMPTS = 6
274
+ for attempt in range(1, ATTEMPTS + 1):
275
+ try:
276
+ api.upload_file(path_or_fileobj=local, path_in_repo=remote,
277
+ repo_id=repo, repo_type="model",
278
+ commit_message="engines: " + remote)
279
+ break
280
+ except Exception as e:
281
+ text = "%s %s" % (type(e).__name__, e)
282
+ # A revision conflict / rate limit is worth retrying; a 401 or a missing
283
+ # repo is not, and retrying it six times only delays the real message.
284
+ transient = any(m in text for m in (
285
+ "409", "412", "429", "Conflict", "precondition",
286
+ "revision", "try again", "Timeout", "Connection"))
287
+ if attempt == ATTEMPTS or not transient:
288
+ print("upload failed (%s): %s" % (remote, text), file=sys.stderr)
289
+ raise
290
+ # Jittered backoff: two VMs that collided once would otherwise collide
291
+ # again on the same schedule.
292
+ delay = min(60, 2 ** attempt) + random.uniform(0, 3)
293
+ print(" [retry %d/%d in %.1fs] %s: %s" % (attempt, ATTEMPTS, delay, remote, text),
294
+ file=sys.stderr)
295
+ time.sleep(delay)
296
+ '@
297
+
298
+ function HFPut($localPath, $repo, $remoteName) {
299
+ Ensure-Hf
300
+ # Token via env, never on the command line: a rented box's shell history and
301
+ # process list are not ours to trust.
302
+ $env:HF_TOKEN = $HF_TOKEN
303
+ $rc = Invoke-PyCode $HfPutPy @($localPath, $repo, $remoteName)
304
+ if ($rc -ne 0) { throw ("HF upload failed: {0}" -f $remoteName) }
305
+ }
306
+
307
+ # ---- HuggingFace download, with the size actually checked -------------------
308
+ # Invoke-WebRequest silently truncated model_int8qdt.onnx to 107 MB of 179 MB.
309
+ # Nothing noticed: the file existed, the script moved on, and the failure
310
+ # surfaced later as "Wire format was corrupt" from the ONNX parser - which reads
311
+ # like a bad model rather than a bad download.
312
+ #
313
+ # huggingface_hub instead: it follows the xet/CDN redirect, resumes, and
314
+ # verifies. The size assertion afterwards is belt and braces, because a
315
+ # half-downloaded 179 MB file is the one outcome that must never reach a build.
316
+ $HfGetPy = @'
317
+ import os, sys
318
+ from huggingface_hub import hf_hub_download, HfApi
319
+
320
+ repo, filename, dest = sys.argv[1], sys.argv[2], sys.argv[3]
321
+
322
+ expected = None
323
+ try:
324
+ info = HfApi().model_info(repo, files_metadata=True)
325
+ for s in info.siblings:
326
+ if s.rfilename == filename:
327
+ expected = s.size
328
+ break
329
+ except Exception as e:
330
+ print(" [warn] could not read expected size: %s" % e, file=sys.stderr)
331
+
332
+ path = hf_hub_download(repo_id=repo, filename=filename, local_dir=dest)
333
+ got = os.path.getsize(path)
334
+ print(" %s -> %s (%.1f MB)" % (filename, path, got / 1048576.0))
335
+
336
+ if expected and got != expected:
337
+ raise SystemExit(
338
+ "TRUNCATED: %s is %d bytes, HuggingFace reports %d. A partial ONNX parses\n"
339
+ "as 'Wire format was corrupt' much later, so stopping here." % (filename, got, expected))
340
+ '@
341
+
342
+ function HFGet {
343
+ param([string] $repo, [string] $filename, [string] $destDir, [switch] $Optional)
344
+ Ensure-Hf
345
+ # Invoke-PyCode returns the exit code as a value, so the captured stream holds
346
+ # both python's output AND that integer. Separate them rather than printing
347
+ # a stray number among the diagnostics.
348
+ $captured = Invoke-PyCode $HfGetPy @($repo, $filename, $destDir) 2>&1
349
+ $rc = ($captured | Where-Object { $_ -is [int] } | Select-Object -Last 1)
350
+ if ($null -eq $rc) { $rc = $LASTEXITCODE }
351
+ $out = @($captured | Where-Object { $_ -isnot [int] })
352
+ if (-not ($Optional -and $rc -ne 0)) {
353
+ $out | ForEach-Object { Write-Host (" " + $_) }
354
+ }
355
+ if ($rc -ne 0) {
356
+ if ($Optional) {
357
+ Write-Host (" (optional) {0} not in {1} - skipping" -f $filename, $repo) -ForegroundColor DarkGray
358
+ return
359
+ }
360
+ $tail = ($out | Select-Object -Last 6) -join " | "
361
+ throw ("HF download failed ({0} from {1}), rc={2}: {3}" -f $filename, $repo, $rc, $tail)
362
+ }
363
+ }
364
+
365
+ # -- 4. workdir + fetch build tools (reuse the production .py, don't reinvent) ---------
366
+ $MODEL_DIR = Join-Path $WORKDIR (Join-Path $MODEL_ID "final")
367
+ $TOOLS_DIR = Join-Path $WORKDIR "_tools"
368
+ New-Item -ItemType Directory -Force -Path $MODEL_DIR, $TOOLS_DIR | Out-Null
369
+
370
+ Step "Fetching build tools"
371
+ # $MyInvocation.MyCommand.Path is null when piped (irm ... | iex) - guard it.
372
+ $SelfDir = ""
373
+ if ($MyInvocation.MyCommand.Path) { $SelfDir = Split-Path -Parent $MyInvocation.MyCommand.Path }
374
+ $toolFiles = @("build_trt_engine.py", "onnx_fp16.py")
375
+ # quantize_onnx.py only for Mode A PTQ (int8/fp8 from FP32); Mode B (INT8_ONNX_S3) / fp16 skip it.
376
+ if ((-not $INT8_ONNX_S3) -and (-not $HF_MODEL_REPO) -and ($PRECISION -ne "fp16")) { $toolFiles += "quantize_onnx.py" }
377
+ # `SamePath` is not paranoia: bootstrap_win.ps1 downloads the tools into
378
+ # ~/uc-build/_tools and then runs build_engines.ps1 FROM that directory, so
379
+ # "the file next to me" and "where I am copying it" are the same file. Copy-Item
380
+ # refuses with "Cannot overwrite the item ... with itself" and takes the run
381
+ # down. When they match, the file is already where it belongs - nothing to do.
382
+ function SamePath($a, $b) {
383
+ if (-not (Test-Path $a) -or -not (Test-Path $b)) { return $false }
384
+ return ((Resolve-Path $a).ProviderPath -eq (Resolve-Path $b).ProviderPath)
385
+ }
386
+
387
+ foreach ($f in $toolFiles) {
388
+ $dst = Join-Path $TOOLS_DIR $f
389
+ $beside = $null; if ($SelfDir) { $beside = Join-Path $SelfDir $f }
390
+ if ($beside -and (SamePath $beside $dst)) { } # already in place
391
+ elseif ($beside -and (Test-Path $beside)) { Copy-Item $beside $dst -Force }
392
+ elseif ($TOOLS_URL) { Invoke-WebRequest -Uri ("{0}/{1}" -f $TOOLS_URL, $f) -OutFile $dst -UseBasicParsing }
393
+ else { try { RC copyto ("{0}/{1}" -f $TOOLS_PREFIX, $f) $dst --quiet } catch { Die "could not fetch $f - set TOOLS_URL or stage to S3 (README ?Stage tools)." } }
394
+ }
395
+ # The committed calibration corpus, fetched alongside the tools. It replaces the
396
+ # staged graph.db: ~1.6 MB of plain JSONL instead of a multi-hundred-MB database,
397
+ # it carries no source paths or project names, and every VM calibrates on exactly
398
+ # the same samples - so an engine built on a rented sm_86 box is comparable with
399
+ # one built at a desk. Falls back to CALIB_DB_S3 when it is not hosted.
400
+ $CALIB_TEXTS = ""
401
+ if ($toolFiles -contains "quantize_onnx.py") {
402
+ $corpus = Join-Path $TOOLS_DIR "calib_corpus.jsonl"
403
+ $beside = $null; if ($SelfDir) { $beside = Join-Path $SelfDir "calib_corpus.jsonl" }
404
+ if ($beside -and (SamePath $beside $corpus)) { } # already in place
405
+ elseif ($beside -and (Test-Path $beside)) { Copy-Item $beside $corpus -Force }
406
+ elseif ($TOOLS_URL) {
407
+ try { Invoke-WebRequest -Uri ("{0}/calib_corpus.jsonl" -f $TOOLS_URL) -OutFile $corpus -UseBasicParsing } catch { }
408
+ } else {
409
+ try { RC copyto ("{0}/calib_corpus.jsonl" -f $TOOLS_PREFIX) $corpus --quiet } catch { }
410
+ }
411
+ if ((Test-Path $corpus) -and ((Get-Item $corpus).Length -gt 0)) { $CALIB_TEXTS = $corpus }
412
+ }
413
+ Ok "tools ready: build_trt_engine.py, quantize_onnx.py"
414
+ $env:ULTRACODE_NO_BOOTSTRAP = "1" # don't look for the repo's models/.../_bootstrap.py
415
+
416
+ # Quiet the two things that shred the console. huggingface_hub redraws progress
417
+ # bars with carriage returns, and onnxconverter_common warns once per subnormal
418
+ # constant while converting to FP16 - hundreds of lines, all of them expected
419
+ # (a float32 value below FP16's range IS truncated; that is the conversion).
420
+ # Interleaved on one stream they overwrite each other mid-word and the real
421
+ # messages become unreadable.
422
+ $env:HF_HUB_DISABLE_PROGRESS_BARS = "1"
423
+ $env:HF_HUB_DISABLE_TELEMETRY = "1"
424
+ # All UserWarnings, not just that module. The per-module form of PYTHONWARNINGS
425
+ # matches on the module doing the warning, which for a library that re-exports
426
+ # its warn() is not reliably the module in the traceback. Nothing in an engine
427
+ # build communicates through UserWarning - TensorRT uses its own logger and the
428
+ # worker prints its own diagnostics - so this loses no signal.
429
+ $env:PYTHONWARNINGS = "ignore::UserWarning"
430
+
431
+ # ---- give build_trt_engine.py the version pin it looks for -------------------
432
+ # It resolves the TRT tag as `_pinned_trt_tag() or _installed_trt_tag()`, and the
433
+ # second one does a FLAT `import tensorrt` with no fallback - unlike
434
+ # _import_tensorrt(), which also accepts tensorrt_bindings. So a bindings-only
435
+ # install (the only one available at our pin on pypi.nvidia.com) can BUILD an
436
+ # engine but cannot NAME one.
437
+ #
438
+ # _pinned_trt_tag() walks up to six directories from the worker looking for
439
+ # vendor/tensorrt/VERSION. The worker sits in $TOOLS_DIR, so one directory is
440
+ # enough - and the value comes from build_matrix.json, generated from that very
441
+ # file in the repo. Same pin, same tag, no second source of truth.
442
+ if ($TRT_PIP) {
443
+ $pinDir = Join-Path $TOOLS_DIR "vendor\tensorrt"
444
+ New-Item -ItemType Directory -Force -Path $pinDir | Out-Null
445
+ [IO.File]::WriteAllText((Join-Path $pinDir "VERSION"), $TRT_PIP, (New-Object Text.UTF8Encoding($false)))
446
+ Ok ("pinned TRT version for the worker: {0} ({1})" -f $TRT_PIP, (Join-Path $pinDir "VERSION"))
447
+ }
448
+
449
+ # ---- TensorRT, installed BEFORE the first build ------------------------------
450
+ # build_trt_engine.py needs the TRT version to NAME the engine, and only installs
451
+ # TensorRT later, while building. On a machine with the repo it reads
452
+ # vendor/tensorrt/VERSION instead, so the ordering never shows; on a bare VM
453
+ # there is no repo and it dies with
454
+ #
455
+ # ERROR: cannot determine the TensorRT version
456
+ #
457
+ # before a single engine is attempted. TRT_PIP_VERSION comes from
458
+ # build_matrix.json, generated from that same vendor/tensorrt/VERSION - so the
459
+ # version in the filename and the version doing the build cannot drift apart.
460
+ #
461
+ # ULTRACODE_NO_BOOTSTRAP above stays set: the worker's own dependency bootstrap
462
+ # looks for a repo checkout that is not here. This block is its stand-in.
463
+
464
+ # Same two-step import build_trt_engine.py performs. Checking only the flat
465
+ # 'import tensorrt' would reject a bindings-only install that the worker is
466
+ # perfectly happy with - and bindings-only is what the NVIDIA index offers at
467
+ # our pin.
468
+ $TrtProbePy = @'
469
+ import sys
470
+ try:
471
+ import tensorrt as t
472
+ except Exception:
473
+ try:
474
+ from tensorrt_bindings import tensorrt as t
475
+ except Exception as e:
476
+ print("neither import worked: %s" % e); sys.exit(1)
477
+ print(getattr(t, "__version__", "unknown"))
478
+ '@
479
+ # Probing for an absent module means Python prints a traceback to stderr - and
480
+ # under ErrorActionPreference=Stop, ANY stderr write by a native program is a
481
+ # terminating error before the redirect even applies. So the check for "is
482
+ # TensorRT installed" killed the run precisely when the answer was "no".
483
+ #
484
+ # Continue for the whole install section; every step below judges by
485
+ # $LASTEXITCODE, which is the honest signal for an external program anyway.
486
+ $PrevEAP = $ErrorActionPreference
487
+ $ErrorActionPreference = "Continue"
488
+
489
+ $probe = Invoke-PyCode $TrtProbePy 2>&1
490
+ $probeVer = ($probe | Where-Object { $_ -isnot [int] } | Select-Object -Last 1)
491
+ # A version of "0" or "unknown" means something imported but is not a usable
492
+ # TensorRT - treat that as absent rather than trusting it and failing later
493
+ # inside trt.Builder with a nullptr from pybind11.
494
+ $needTrt = ($LASTEXITCODE -ne 0) -or ("$probeVer" -notmatch '^\d+\.\d+')
495
+
496
+ if ($needTrt) {
497
+ Step ("Installing TensorRT{0} + onnx (from pypi.nvidia.com)" -f $(if ($TRT_PIP) { " $TRT_PIP" } else { "" }))
498
+ # cu13 to match the daemon's nvinfer_11. Mixing cu12 and cu13 packages
499
+ # produces a version mismatch at deserialize, because the plan encodes the
500
+ # build-time DLL version and 'import tensorrt' then finds the other one.
501
+ # cu12 or cu13, decided by the DRIVER - the same test build_trt_engine.py
502
+ # makes. Hardcoding cu13 produced a clean install that then failed inside
503
+ # TensorRT with "CUDA initialization failure with error: 35", which is
504
+ # cudaErrorInsufficientDriver: the wheels needed a newer driver than the
505
+ # image ships. The TRT version (and therefore the engine's trt11.0 tag) is
506
+ # identical either way; only the CUDA runtime they link differs.
507
+ $cudaMajor = 0
508
+ $smiCuda = ""
509
+ try {
510
+ $smi = (& nvidia-smi 2>&1) -join "`n"
511
+ if ($smi -match "CUDA Version:\s*(\d+)\.(\d+)") {
512
+ $cudaMajor = [int]$Matches[1]
513
+ $smiCuda = "$($Matches[1]).$($Matches[2])"
514
+ }
515
+ } catch { }
516
+ $cu = if ($cudaMajor -ge 13) { "cu13" } else { "cu12" }
517
+ Ok ("driver supports CUDA {0} -> installing tensorrt-{1} wheels" -f $(if ($smiCuda) { $smiCuda } else { "unknown" }), $cu)
518
+
519
+ $pin = if ($TRT_PIP) { "==$TRT_PIP" } else { "" }
520
+ # bindings + libs, and NOT the `tensorrt-cu13` meta-package. On
521
+ # pypi.nvidia.com that meta is a placeholder (only 0.0.0a0 exists), so asking
522
+ # for it at our pin fails the whole pip invocation - taking the two packages
523
+ # that WOULD have installed down with it. The real 11.2.x meta lives on
524
+ # pypi.org, but that is a different version from our pin and the engine
525
+ # filename must match the builder.
526
+ #
527
+ # bindings alone is enough: build_trt_engine.py falls back to
528
+ # 'from tensorrt_bindings import tensorrt' when the flat 'import tensorrt'
529
+ # is unavailable (see _import_tensorrt there).
530
+ $pkgs = @("tensorrt-$cu-bindings$pin", "tensorrt-$cu-libs$pin")
531
+
532
+ # pip writes routine notices to stderr, and Invoke-Py throws on a non-zero
533
+ # exit. Neither should end the run on its own: judge by the exit code, and
534
+ # let stderr be output. Without this, a "new release available" line is
535
+ # indistinguishable from a failed install.
536
+ function Pip {
537
+ $prev = $ErrorActionPreference
538
+ $ErrorActionPreference = "Continue"
539
+ try {
540
+ & $PyExe @PyPre -m pip install --disable-pip-version-check --no-warn-script-location @args 2>&1 |
541
+ ForEach-Object { Write-Host (" " + $_) }
542
+ return $LASTEXITCODE
543
+ } finally { $ErrorActionPreference = $prev }
544
+ }
545
+
546
+ $rc = Pip -q --only-binary ":all:" --extra-index-url https://pypi.nvidia.com @pkgs
547
+ if ($rc -ne 0 -and $TRT_PIP) {
548
+ Warn "pinned install failed (rc=$rc) - retrying unpinned; the engine tag then follows what installs"
549
+ $rc = Pip -q --only-binary ":all:" --extra-index-url https://pypi.nvidia.com "tensorrt-$cu-bindings" "tensorrt-$cu-libs"
550
+ }
551
+ if ($rc -ne 0) { Die "could not install TensorRT (pip rc=$rc) - see the pip output above" }
552
+
553
+ # onnx reads the graph for the shape checks; without it the worker warns
554
+ # "onnx.load failed" and proceeds half-blind. huggingface_hub is what pulls
555
+ # the ONNX and pushes the engines - installed HERE rather than lazily,
556
+ # because a lazy install makes the first download fail with a traceback and
557
+ # only then fix itself, which is indistinguishable from a real failure.
558
+ $null = Pip -q onnx numpy huggingface_hub onnxconverter-common
559
+ # pip exiting 0 is not proof the module resolves. Probe it exactly the way
560
+ # build_trt_engine.py does - flat import first, tensorrt_bindings second -
561
+ # so this check passes for precisely the installs the worker can use, and
562
+ # fails here rather than 40 minutes later inside a build.
563
+ $v = (Invoke-PyCode $TrtProbePy 2>&1 | Where-Object { $_ -isnot [int] } | Select-Object -Last 1)
564
+ if ($LASTEXITCODE -ne 0) {
565
+ Die ("TensorRT is installed but neither 'import tensorrt' nor 'from tensorrt_bindings import tensorrt' works: {0}" -f $v)
566
+ }
567
+ Ok ("tensorrt {0}" -f $v)
568
+ } else {
569
+ $v = (Invoke-PyCode $TrtProbePy 2>&1 | Where-Object { $_ -isnot [int] } | Select-Object -Last 1)
570
+ Ok ("tensorrt already present: {0}" -f $v)
571
+ }
572
+ $ErrorActionPreference = $PrevEAP
573
+
574
+ # -- 5+6. obtain the ONNX to build from. Priority: HF_MODEL_REPO > INT8_ONNX_S3 > S3 FP32.
575
+ # Mode HF (recommended): pull model_int8qdt.onnx (int8) / model.onnx (fp16) from the public HF repo.
576
+ # Mode B (S3): reuse a pre-quantized model_int8qdt.onnx from S3. Mode A (S3): FP32 + PTQ on the VM.
577
+ $INT8_FLAG = "--int8"
578
+ if ($HF_MODEL_REPO) {
579
+ # Mode HF - pull the ONNX straight from the model's public HF repo (no S3, no creds).
580
+ $hfBase = "https://huggingface.co/$HF_MODEL_REPO/resolve/main"
581
+ if ($PRECISION -eq "fp16") {
582
+ Step "Mode HF (fp16) - pulling FP32 ONNX from $hfBase"
583
+ HFGet $HF_MODEL_REPO "model.onnx" $MODEL_DIR
584
+ # The external-data sidecar exists only for models above the 2 GB proto
585
+ # limit. Absent is the normal case, so ask quietly instead of printing a
586
+ # traceback that looks like a failure.
587
+ HFGet $HF_MODEL_REPO "model.onnx.data" $MODEL_DIR -Optional
588
+
589
+ # Optional-for-everyone means a FAILED fetch of a REQUIRED sidecar looks
590
+ # exactly like a model that never had one. The builder would then parse a
591
+ # valid graph with no initialisers and write a correctly-named engine full
592
+ # of nothing. A split graph is single-digit MB where a whole model is
593
+ # hundreds, so the size is the discriminator.
594
+ $graphPath = Join-Path $MODEL_DIR "model.onnx"
595
+ $dataPath = Join-Path $MODEL_DIR "model.onnx.data"
596
+ $graphBytes = (Get-Item $graphPath -ErrorAction SilentlyContinue).Length
597
+ $dataBytes = (Get-Item $dataPath -ErrorAction SilentlyContinue).Length
598
+ if ($graphBytes -lt 10485760 -and -not $dataBytes) {
599
+ Die ("model.onnx is only {0} bytes and model.onnx.data is absent - this is a SPLIT onnx whose weights did not download. Building from it would yield an engine with no weights." -f $graphBytes)
600
+ }
601
+ if ($dataBytes) { Ok ("external-data sidecar: {0} bytes" -f $dataBytes) }
602
+
603
+ $INT8_FLAG = "--no-int8"; Ok "FP32 ONNX pulled from HF - FP16 engines (no PTQ)"
604
+ } else {
605
+ Step "Mode HF (int8) - pulling prebuilt INT8 ONNX from $HF_MODEL_REPO (byte-identical to sm_120)"
606
+ HFGet $HF_MODEL_REPO "model_int8qdt.onnx" $MODEL_DIR
607
+ Ok "INT8 ONNX pulled from HF -> build is byte-identical-precision to sm_120"
608
+ }
609
+ }
610
+ elseif ($INT8_ONNX_S3) {
611
+ Step "Mode B (S3) - reusing pre-quantized INT8 ONNX from $INT8_ONNX_S3"
612
+ RC copyto $INT8_ONNX_S3 (Join-Path $MODEL_DIR "model_int8qdt.onnx") --quiet
613
+ RCsoft copyto ("{0}_data" -f $INT8_ONNX_S3) (Join-Path $MODEL_DIR "model_int8qdt.onnx_data") --quiet
614
+ Ok "INT8 ONNX pulled (S3) -> byte-identical-precision to sm_120"
615
+ }
616
+ else {
617
+ # Mode A (S3) - FP32 + PTQ on the VM.
618
+ if ($SRC_ONNX_S3) { $SRC = $SRC_ONNX_S3 }
619
+ else {
620
+ if (-not $RUN_ID) { Die "set HF_MODEL_REPO (mode HF), INT8_ONNX_S3 (mode B), or RUN_ID/SRC_ONNX_S3 (mode A)." }
621
+ $SRC = "s3:{0}/{1}/runs/{2}/variants/{3}/final" -f $S3_BUCKET, $S3_MODEL_DIR, $RUN_ID, $TRAIN_VARIANT
622
+ }
623
+ Step "Mode A (S3) - pulling FP32 ONNX from $SRC"
624
+ RC copy $SRC $MODEL_DIR --transfers 8 --quiet
625
+ if (-not (Test-Path (Join-Path $MODEL_DIR "model.onnx"))) { Die "model.onnx not found under $SRC (check RUN_ID / TRAIN_VARIANT)." }
626
+ Ok ("ONNX at {0}\model.onnx" -f $MODEL_DIR)
627
+
628
+ if ($PRECISION -eq "fp16") { $INT8_FLAG = "--no-int8"; Warn "PRECISION=fp16 - FP16 engines (no INT8 PTQ); differs from sm_120 INT8." }
629
+ elseif ($PRECISION -eq "fp8") { $INT8_FLAG = "--fp8" }
630
+
631
+ if ($PRECISION -eq "int8" -or $PRECISION -eq "fp8") {
632
+ try { Invoke-Py -c "import onnx, onnxruntime, numpy" } catch { Step "Installing PTQ deps"; Invoke-Py -m pip install -q onnx onnxruntime numpy }
633
+ # Corpus first; a staged graph.db only when it is not hosted - that route
634
+ # needs a database copied off a machine that has indexed something, which
635
+ # a rented GPU box by definition has not.
636
+ if ($CALIB_TEXTS) {
637
+ $calibArgs = @("--calib-texts", $CALIB_TEXTS)
638
+ Ok ("calibration: corpus ({0} samples)" -f (Get-Content $CALIB_TEXTS | Measure-Object -Line).Lines)
639
+ } elseif ($CALIB_DB_S3) {
640
+ Step "Pulling calibration graph.db from $CALIB_DB_S3"
641
+ $CalibLocal = Join-Path $WORKDIR "calib.db"
642
+ RC copyto $CALIB_DB_S3 $CalibLocal --quiet
643
+ $calibArgs = @("--calib-db", $CalibLocal)
644
+ } else {
645
+ Die "PRECISION=$PRECISION (mode A) needs calibration data: host calib_corpus.jsonl beside the tools (recommended), or set CALIB_DB_S3; or use HF_MODEL_REPO / INT8_ONNX_S3, or PRECISION=fp16."
646
+ }
647
+ if ($PRECISION -eq "fp8") { $ptqMode = @("--fp8"); $ptqOut = Join-Path $MODEL_DIR "model_fp8qdt.onnx"; $INT8_FLAG = "--fp8" }
648
+ else { $ptqMode = @(); $ptqOut = Join-Path $MODEL_DIR "model_int8qdt.onnx" }
649
+ Step ("PTQ {0} quantization (quantize_onnx.py)" -f $PRECISION.ToUpper())
650
+ Invoke-Py (Join-Path $TOOLS_DIR "quantize_onnx.py") `
651
+ --model-dir $MODEL_DIR --onnx-dir $MODEL_DIR `
652
+ @calibArgs --max-seq $PTQ_MAX_SEQ --samples $PTQ_SAMPLES `
653
+ @ptqMode --output $ptqOut
654
+ Ok "PTQ ONNX written"
655
+ }
656
+ }
657
+
658
+ # -- 7. build the engine(s) - arch passed explicitly so filenames are deterministic ---
659
+ # Remove engines from earlier runs for this os x arch. The upload step collects
660
+ # by glob rather than by remembering what it built, so a leftover file is
661
+ # re-uploaded as though it were fresh - which is how three bucketed reranker
662
+ # engines, built by a bug and unloadable by name, would return after the fix.
663
+ # Only this cell's files: another arch's engines in the same directory are not
664
+ # ours to delete.
665
+ $stale = Get-ChildItem -Path $MODEL_DIR -Filter ("*_{0}_trt*_{1}.engine" -f $OS_ARCH, $SM) -ErrorAction SilentlyContinue
666
+ if ($stale) {
667
+ Step ("Clearing {0} engine(s) from a previous run ({1} / {2})" -f $stale.Count, $OS_ARCH, $SM)
668
+ foreach ($f in $stale) {
669
+ Write-Host (" rm {0}" -f $f.Name) -ForegroundColor DarkGray
670
+ Remove-Item $f.FullName -Force -ErrorAction SilentlyContinue
671
+ $lj = [IO.Path]::ChangeExtension($f.FullName, ".layers.json")
672
+ if (Test-Path $lj) { Remove-Item $lj -Force -ErrorAction SilentlyContinue }
673
+ }
674
+ }
675
+
676
+ $bucketList = @()
677
+ if ([string]::IsNullOrWhiteSpace($BUCKETS)) { $bucketList = @("__single__") } else { $bucketList = $BUCKETS.Split(" ") | Where-Object { $_ } }
678
+ foreach ($b in $bucketList) {
679
+ $variantArgs = @(); $label = "(single)"
680
+ if ($b -ne "__single__") { $variantArgs = @("--variant", $b); $label = $b }
681
+ Step ("Building TRT engine: {0} {1} -> {2} ({3}, {4})" -f $MODEL_ID, $label, $SM, $OS_ARCH, $PRECISION)
682
+ Invoke-Py (Join-Path $TOOLS_DIR "build_trt_engine.py") `
683
+ --model-dir $MODEL_DIR --model-id $MODEL_ID `
684
+ --role $ROLE --os-arch $OS_ARCH --cuda-arch $SM `
685
+ $INT8_FLAG @variantArgs
686
+ }
687
+
688
+ # Collect everything build_trt_engine.py emitted for this os x arch.
689
+ # The `trt*` wildcard is load-bearing. Engine names carry the runtime version
690
+ # between the os_arch and the sm (..._win_x64_trt11.0_sm_89.engine), and the
691
+ # version is only knowable AFTER the build on a bare VM. A pattern without it
692
+ # matched nothing while four freshly built engines sat in the directory, and the
693
+ # run reported "no .engine produced". build_engines.sh had this right; the
694
+ # PowerShell twin did not - the exact drift a shared driver was meant to prevent.
695
+ $engines = Get-ChildItem -Path $MODEL_DIR -Filter ("*_{0}_trt*_{1}.engine" -f $OS_ARCH, $SM) -ErrorAction SilentlyContinue
696
+ if (-not $engines) { Die "no .engine produced - check the build log above." }
697
+ foreach ($e in $engines) { Ok ("engine: {0} ({1:N1} MB)" -f $e.Name, ($e.Length / 1MB)) }
698
+
699
+ # -- 8. upload the engines - FLAT list; the filename carries the tag info --------------
700
+ # The runtime forms trt-cuda-$SM and matches _win/_linux in the filename, so a flat dir with
701
+ # correct names is all the CDN needs. Diagnostic sidecars go under _meta/ to keep the list clean.
702
+ # HF and S3 are independent: both can run, either can be the only one.
703
+ $dests = @()
704
+ if ($HF_UPLOAD) {
705
+ Step "Uploading engines -> huggingface.co/$HF_UPLOAD_REPO (flat, repo root)"
706
+ foreach ($e in $engines) {
707
+ HFPut $e.FullName $HF_UPLOAD_REPO $e.Name
708
+ Ok ("HF <- {0}" -f $e.Name)
709
+ }
710
+ $dests += ("hf:{0}" -f $HF_UPLOAD_REPO)
711
+ }
712
+ if ($DEST_PREFIX) {
713
+ Step "Uploading engines -> $DEST_PREFIX/ (flat)"
714
+ foreach ($e in $engines) {
715
+ RC copyto $e.FullName ("{0}/{1}" -f $DEST_PREFIX, $e.Name) --quiet
716
+ $lj = [IO.Path]::ChangeExtension($e.FullName, ".layers.json")
717
+ if (Test-Path $lj) { RCsoft copyto $lj ("{0}/_meta/{1}" -f $DEST_PREFIX, (Split-Path $lj -Leaf)) --quiet }
718
+ }
719
+ $tc = Join-Path $MODEL_DIR "timing.cache"
720
+ if (Test-Path $tc) { RCsoft copyto $tc ("{0}/_meta/timing_{1}_{2}.cache" -f $DEST_PREFIX, $SM, $OS_ARCH) --quiet }
721
+ $dests += $DEST_PREFIX
722
+ }
723
+
724
+ # -- 9. summary ------------------------------------------------------------------------
725
+ Write-Host ""
726
+ Write-Host "================================================================"
727
+ Write-Host (" DONE - {0} engine(s), {1} {2} / {3} ({4})" -f $engines.Count, $MODEL_ID, $SM, $OS_ARCH, $PRECISION)
728
+ Write-Host (" flat upload -> {0}" -f ($dests -join ' + '))
729
+ foreach ($e in $engines) { Write-Host (" {0}" -f $e.Name) }
730
+ Write-Host (" CDN tag for ALL of these: trt-cuda-{0} (OS disambiguated by _{1} in the filename)" -f $SM, $OS_ARCH)
731
+ Write-Host "================================================================"
732
+ if ($Conf) { Remove-Item $Conf -ErrorAction SilentlyContinue }
_build-tools/build_engines.sh ADDED
@@ -0,0 +1,560 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env bash
2
+ # build_engines.sh — standalone TRT-engine builder for a rented Linux GPU VM.
3
+ #
4
+ # Purpose: on a fresh GPU VM (Timeweb / Selectel / RunPod / Vast / any Linux + NVIDIA),
5
+ # pull a distilled FP32 ONNX from OUR S3, (optionally) PTQ-quantize it to INT8, build the
6
+ # TensorRT engines for THIS VM's GPU architecture, and upload the .engine files back to S3.
7
+ #
8
+ # The whole point is portability of TRT engines: a TRT plan is locked to {GPU arch × OS ×
9
+ # TRT version}. We have sm_120 locally (built on Windows); this script produces the cells
10
+ # we can't build at home — sm_86 (RTX 3090 / A-series) and sm_89 (RTX 4090) on LINUX.
11
+ # The matching Windows engines come from build_engines.ps1 on a Windows GPU VM.
12
+ #
13
+ # ── On-VM usage (the ONLY file you must get onto the VM; it self-bootstraps the rest) ──
14
+ # 1. Install prerequisites yourself (see README.md §Prereqs): NVIDIA driver + CUDA,
15
+ # python3 (3.10+), pip, rclone. (TensorRT is auto-installed by build_trt_engine.py.)
16
+ # 2. Export S3 creds + which model/run to build:
17
+ # export S3_BUCKET=fedor-ml S3_ACCESS_KEY=... S3_SECRET_KEY=...
18
+ # export MODEL_ID=code-daemon-embed-v1 RUN_ID=run-1781916112 TRAIN_VARIANT=4l-768h
19
+ # 3. bash build_engines.sh
20
+ #
21
+ # Everything is env-driven (no flags needed). The GPU arch is DETECTED on the VM via
22
+ # nvidia-smi — you never pass it. See the CONFIG block for every knob + default.
23
+ set -euo pipefail
24
+
25
+ # ── Stage 0: optional remote config — pull creds + params from your domain ────────────
26
+ # Lets the on-VM command be just two lines (no creds typed on the box):
27
+ # export TOOLS_URL=https://app.fabuza.ru/ml
28
+ # curl -fsSL "$TOOLS_URL/build_engines.sh" | bash
29
+ # build.env is a KEY=VALUE file (S3 creds + MODEL_ID + INT8_ONNX_S3 + …) you serve from that host
30
+ # ONLY during a build (then close / IP-lock). Skipped when S3_ACCESS_KEY is already in the env, so
31
+ # an explicit `export S3_…` still wins. Override the URL with CONFIG_URL (e.g. if your host won't
32
+ # serve a ".env" file — point it at build.cfg instead).
33
+ if [ -z "${S3_ACCESS_KEY:-}" ]; then
34
+ _cfg_url="${CONFIG_URL:-}"
35
+ [ -z "$_cfg_url" ] && [ -n "${TOOLS_URL:-}" ] && _cfg_url="${TOOLS_URL%/}/build.env"
36
+ if [ -n "$_cfg_url" ]; then
37
+ _cfg="$(mktemp)"
38
+ if curl -fsSL "$_cfg_url" -o "$_cfg" 2>/dev/null; then
39
+ set -a; . "$_cfg"; set +a
40
+ echo "[cfg] loaded remote config from $_cfg_url"
41
+ fi
42
+ rm -f "$_cfg"
43
+ fi
44
+ fi
45
+
46
+ # ── CONFIG (all overridable via env) ───────────────────────────────────────────────
47
+ # S3 is OPTIONAL. On the all-HuggingFace lane (ONNX in from a public model repo,
48
+ # engines out to the same repo) the VM holds no S3 credentials at all — which is
49
+ # the point: a rented box we do not own should carry exactly one secret, and that
50
+ # secret should be scoped to the repos it writes. The requirement is re-derived
51
+ # below, after the source/destination modes are known, so a missing key fails with
52
+ # "you asked for the S3 lane" rather than at the top of a run that never needed it.
53
+ S3_BUCKET="${S3_BUCKET:-}"
54
+ S3_ACCESS_KEY="${S3_ACCESS_KEY:-}"
55
+ S3_SECRET_KEY="${S3_SECRET_KEY:-}"
56
+ S3_ENDPOINT="${S3_ENDPOINT:-https://storage.yandexcloud.net}"
57
+
58
+ # Model identity + where the FP32 ONNX lives in S3.
59
+ MODEL_ID="${MODEL_ID:-code-daemon-embed-v1}" # engine filename prefix + local dir name
60
+ S3_MODEL_DIR="${S3_MODEL_DIR:-code-daemon-embed}" # the distill MODEL_DIR (S3 path segment)
61
+ RUN_ID="${RUN_ID:-}" # distill run id (e.g. run-1781916112)
62
+ TRAIN_VARIANT="${TRAIN_VARIANT:-4l-768h}" # distill student variant subdir in S3
63
+ # Full S3 path to the final/ dir holding model.onnx (override to bypass RUN_ID/TRAIN_VARIANT).
64
+ SRC_ONNX_S3="${SRC_ONNX_S3:-}"
65
+
66
+ # TRT length-bucket variants (build_trt_engine.py --variant). Space-separated.
67
+ # Embedding ships s/m/l; set to empty ("") for single-engine models (NER/reranker).
68
+ BUCKETS="${BUCKETS:-s m l}"
69
+ ROLE="${ROLE:-embedding}" # embedding | ner | reranker
70
+ # Remember whether the caller set PRECISION explicitly BEFORE we default it —
71
+ # the sm_75 auto-pick (after GPU detection) must not override an explicit choice.
72
+ [ -n "${PRECISION:-}" ] && PRECISION_EXPLICIT=1
73
+ PRECISION="${PRECISION:-int8}" # int8 | fp16 | fp8
74
+
75
+ # INT8 PTQ calibration: a graph.db snapshot you staged to S3 (see README §Calibration).
76
+ # Without it, INT8 cannot calibrate on a clean VM. fp16 needs no calib.
77
+ CALIB_DB_S3="${CALIB_DB_S3:-}"
78
+ # Mode B (S3): reuse a pre-quantized model_int8qdt.onnx from S3 → byte-identical INT8 to the
79
+ # sm_120 ship, NO PTQ/calib on the VM.
80
+ INT8_ONNX_S3="${INT8_ONNX_S3:-}"
81
+ # Mode HF (recommended): pull the ONNX straight from the model's PUBLIC HF repo — no S3, no creds.
82
+ # int8 → model_int8qdt.onnx (byte-identical to sm_120); fp16 → model.onnx (+ .data). Wins over all.
83
+ HF_MODEL_REPO="${HF_MODEL_REPO:-}"
84
+ PTQ_SAMPLES="${PTQ_SAMPLES:-500}"
85
+ PTQ_MAX_SEQ="${PTQ_MAX_SEQ:-128}"
86
+
87
+ # Exact TensorRT pip version (e.g. 11.0.0.114), passed by run_matrix.py from
88
+ # build_matrix.json - which gen_build_matrix.py read out of vendor/tensorrt/VERSION.
89
+ # Empty when this script is driven by hand; then whatever installs decides the tag.
90
+ TRT_PIP="${TRT_PIP_VERSION:-}"
91
+
92
+ # Build tools (build_trt_engine.py + quantize_onnx.py) come from, in order:
93
+ # a file next to this script → TOOLS_URL (http, e.g. your hidden dir) → TOOLS_PREFIX (S3).
94
+ # TOOLS_URL lets you `curl … | bash` this wrapper AND have it pull its .py from the same host —
95
+ # no S3 staging of tools needed. Host ONLY these non-secret files there; never creds/ONNX/calib.
96
+ TOOLS_URL="${TOOLS_URL:-}"
97
+ TOOLS_PREFIX="${TOOLS_PREFIX:-s3:${S3_BUCKET}/_build-tools}"
98
+ # Where to upload the built engines. Empty + HF_UPLOAD_REPO = the HF-only lane.
99
+ DEST_PREFIX="${DEST_PREFIX:-}"
100
+
101
+ # ── HuggingFace destination — the default lane ────────────────────────────────────────
102
+ # Engines go back to the SAME public repo the ONNX came from, which is where the
103
+ # daemon looks for them (`model_manager.downloadModel` builds the URL from the
104
+ # catalog id). That removes the S3 round-trip entirely: nothing has to be copied
105
+ # from a bucket to HF afterwards, and no step can be forgotten in between.
106
+ # HF_TOKEN must be a WRITE token — prefer a fine-grained one scoped to these repos.
107
+ HF_UPLOAD_REPO="${HF_UPLOAD_REPO:-$HF_MODEL_REPO}"
108
+ HF_TOKEN="${HF_TOKEN:-}"
109
+ HF_UPLOAD=0
110
+ [ -n "$HF_UPLOAD_REPO" ] && [ -n "$HF_TOKEN" ] && HF_UPLOAD=1
111
+
112
+ WORKDIR="${WORKDIR:-$HOME/uc-build}"
113
+ PY="${PY:-}" # python override; auto-detected if empty
114
+
115
+ # ── helpers ─────────────────────────────────────────────────────────────────────────
116
+ C='\033[0;36m'; G='\033[0;32m'; R='\033[0;31m'; Y='\033[0;33m'; Z='\033[0m'
117
+ step() { echo -e "\n${C}[>] $*${Z}"; }
118
+ ok() { echo -e " ${G}[OK]${Z} $*"; }
119
+ die() { echo -e " ${R}[!!]${Z} $*" >&2; exit 1; }
120
+ warn() { echo -e " ${Y}[!]${Z} $*" >&2; }
121
+
122
+ # ── is S3 needed at all? ──────────────────────────────────────────────────────────────
123
+ # Three independent consumers. Each is skipped when its HF/HTTP equivalent is set,
124
+ # so the common case (HF in, HF out, tools over HTTPS) needs no bucket.
125
+ SELF_DIR_EARLY=""
126
+ [ -n "${BASH_SOURCE[0]:-}" ] && [ -f "${BASH_SOURCE[0]}" ] && SELF_DIR_EARLY="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
127
+ NEEDS_S3=0; S3_WHY=""
128
+ [ -z "$HF_MODEL_REPO" ] && { NEEDS_S3=1; S3_WHY="$S3_WHY ONNX-source"; }
129
+ [ -n "$DEST_PREFIX" ] && { NEEDS_S3=1; S3_WHY="$S3_WHY engine-upload"; }
130
+ [ -z "$TOOLS_URL" ] && [ -z "$SELF_DIR_EARLY" ] && { NEEDS_S3=1; S3_WHY="$S3_WHY build-tools"; }
131
+
132
+ if [ "$HF_UPLOAD" = "0" ] && [ -z "$DEST_PREFIX" ]; then
133
+ die "no destination: set HF_UPLOAD_REPO + HF_TOKEN (recommended), or DEST_PREFIX for S3. Engines built and thrown away is the one outcome worth failing early on."
134
+ fi
135
+ if [ "$NEEDS_S3" = "1" ]; then
136
+ [ -n "$S3_BUCKET" ] || die "S3_BUCKET required for:$S3_WHY. Set HF_MODEL_REPO / TOOLS_URL to avoid S3 entirely."
137
+ [ -n "$S3_ACCESS_KEY" ] || die "S3_ACCESS_KEY required for:$S3_WHY"
138
+ [ -n "$S3_SECRET_KEY" ] || die "S3_SECRET_KEY required for:$S3_WHY"
139
+ command -v rclone >/dev/null 2>&1 || die "rclone not found — required for the S3 lane (README §Prereqs)."
140
+ fi
141
+ command -v nvidia-smi >/dev/null 2>&1 || die "nvidia-smi not found — no NVIDIA driver? TRT needs a GPU."
142
+
143
+ # ── 1. resolve python ────────────────────────────────────────────────────────────────
144
+ if [ -z "$PY" ]; then
145
+ for c in python3 python; do command -v "$c" >/dev/null 2>&1 && PY="$c" && break; done
146
+ fi
147
+ [ -n "$PY" ] || die "python3 not found."
148
+ ok "python: $($PY --version 2>&1)"
149
+
150
+ # ── 2. detect GPU arch (sm_XX) + OS arch — the script figures out the GPU itself ──────
151
+ step "Detecting GPU + platform"
152
+ CC="$(nvidia-smi --query-gpu=compute_cap --format=csv,noheader 2>/dev/null | head -1 | tr -d ' ')"
153
+ [ -n "$CC" ] || die "could not read compute_cap from nvidia-smi."
154
+ SM="sm_${CC/./}" # 8.6 -> sm_86, 8.9 -> sm_89, 12.0 -> sm_120
155
+ GPU_NAME="$(nvidia-smi --query-gpu=name --format=csv,noheader 2>/dev/null | head -1)"
156
+ case "$(uname -m)" in aarch64|arm64) OS_ARCH=linux_arm64 ;; *) OS_ARCH=linux_x64 ;; esac
157
+ ok "GPU: ${GPU_NAME} → ${SM} platform: ${OS_ARCH}"
158
+
159
+ # sm_75 (Turing) ships FP16, not INT8: on Turing the W8A16 INT8 path has no
160
+ # attention-fusion win for small encoders, and FP16 skips PTQ/calibration
161
+ # entirely (no CALIB_DB / INT8_ONNX needed on the VM). Auto-pick fp16 for Turing
162
+ # unless the caller set PRECISION explicitly.
163
+ if [ "$SM" = "sm_75" ] && [ -z "${PRECISION_EXPLICIT:-}" ] && [ "$PRECISION" = "int8" ]; then
164
+ PRECISION=fp16
165
+ ok "Turing sm_75 → PRECISION=fp16 (auto; INT8 has no Turing win, FP16 needs no calib)"
166
+ fi
167
+
168
+ # ── 3. one-off rclone.conf from env — only on the S3 lane ─────────────────────────────
169
+ # Guarded so the HF-only lane never materialises a credentials file on a machine we
170
+ # are about to hand back to the provider.
171
+ CONF=""
172
+ if [ "$NEEDS_S3" = "1" ]; then
173
+ CONF="$(mktemp /tmp/rclone-build-XXXXXX.conf)"
174
+ trap 'rm -f "$CONF"' EXIT
175
+ cat > "$CONF" <<EOF
176
+ [s3]
177
+ type = s3
178
+ provider = Other
179
+ access_key_id = ${S3_ACCESS_KEY}
180
+ secret_access_key = ${S3_SECRET_KEY}
181
+ endpoint = ${S3_ENDPOINT}
182
+ acl = private
183
+ EOF
184
+ chmod 0600 "$CONF"
185
+ fi
186
+ RC() { [ -n "$CONF" ] || die "S3 requested but no credentials were configured"; rclone --config "$CONF" "$@"; }
187
+
188
+ # ── HuggingFace upload helper ─────────────────────────────────────────────────────────
189
+ # `HfApi.upload_file` rather than a hand-rolled REST PUT: it does the multipart /
190
+ # LFS dance an .engine needs, and it is the same call `models/_compile/publish.py`
191
+ # makes at a desk, so a cloud-built engine lands byte-identically to a local one.
192
+ # Installed lazily — a Turing VM builds FP16 only and would otherwise pay for a
193
+ # wheel it never imports.
194
+ HF_READY=0
195
+ hf_put() { # hf_put <local> <repo> <remote-name>
196
+ if [ "$HF_READY" = "0" ]; then
197
+ $PY -c "import huggingface_hub" 2>/dev/null || {
198
+ step "Installing huggingface_hub"
199
+ $PY -m pip install -q -U huggingface_hub || die "pip install huggingface_hub failed"
200
+ }
201
+ HF_READY=1
202
+ fi
203
+ # Token via env, never on the command line: a rented box's shell history and
204
+ # process list are not ours to trust.
205
+ HF_TOKEN="$HF_TOKEN" $PY -c "$HF_PUT_PY" "$1" "$2" "$3" || die "HF upload failed: $3"
206
+ }
207
+
208
+ # The uploader, shared verbatim with build_engines.ps1 so the two OS lanes cannot
209
+ # drift in how they write to the same repository.
210
+ #
211
+ # RETRY IS NOT OPTIONAL HERE. Windows Server 2019 cannot run WSL2, so win_x64 and
212
+ # linux_x64 are built on two machines, and the sensible thing is to run them at
213
+ # the same time - which means two writers committing to ONE HuggingFace repo. The
214
+ # filenames never collide (_win_x64_ vs _linux_x64_), but a commit does: HF
215
+ # rejects a write against a revision that moved under it. That is a transient
216
+ # conflict, not a failure, and losing a 40-minute engine to it would be absurd.
217
+ read -r -d '' HF_PUT_PY <<'HFPY' || true
218
+ import os, sys, time, random
219
+ from huggingface_hub import HfApi
220
+
221
+ local, repo, remote = sys.argv[1], sys.argv[2], sys.argv[3]
222
+ api = HfApi(token=os.environ["HF_TOKEN"])
223
+
224
+ ATTEMPTS = 6
225
+ for attempt in range(1, ATTEMPTS + 1):
226
+ try:
227
+ api.upload_file(path_or_fileobj=local, path_in_repo=remote,
228
+ repo_id=repo, repo_type="model",
229
+ commit_message="engines: " + remote)
230
+ break
231
+ except Exception as e:
232
+ text = "%s %s" % (type(e).__name__, e)
233
+ # A revision conflict / rate limit is worth retrying; a 401 or a missing
234
+ # repo is not, and retrying it six times only delays the real message.
235
+ transient = any(m in text for m in (
236
+ "409", "412", "429", "Conflict", "precondition",
237
+ "revision", "try again", "Timeout", "Connection"))
238
+ if attempt == ATTEMPTS or not transient:
239
+ print("upload failed (%s): %s" % (remote, text), file=sys.stderr)
240
+ raise
241
+ # Jittered backoff: two VMs that collided once would otherwise collide
242
+ # again on the same schedule.
243
+ delay = min(60, 2 ** attempt) + random.uniform(0, 3)
244
+ print(" [retry %d/%d in %.1fs] %s: %s" % (attempt, ATTEMPTS, delay, remote, text),
245
+ file=sys.stderr)
246
+ time.sleep(delay)
247
+ HFPY
248
+
249
+ # ── 4. workdir + fetch build tools (reuse the production .py, don't reinvent) ─────────
250
+ MODEL_DIR="$WORKDIR/$MODEL_ID/final"
251
+ TOOLS_DIR="$WORKDIR/_tools"
252
+ mkdir -p "$MODEL_DIR" "$TOOLS_DIR"
253
+
254
+ step "Fetching build tools"
255
+ # ${BASH_SOURCE[0]:-} is empty when this script is piped (curl … | bash) — guard it.
256
+ SELF_DIR="$(cd "$(dirname "${BASH_SOURCE[0]:-.}")" 2>/dev/null && pwd || true)"
257
+ fetch_tool() {
258
+ local f="$1" dst="$TOOLS_DIR/$1"
259
+ if [ -n "$SELF_DIR" ] && [ -f "$SELF_DIR/$f" ]; then
260
+ # `-ef` (same device+inode), not a string compare: bootstrap_linux.sh
261
+ # stages the tools INTO $WORKDIR/_tools and runs build_engines.sh from
262
+ # there, so $SELF_DIR and $TOOLS_DIR are the same directory and cp is
263
+ # asked to copy a file onto itself. It refuses with
264
+ # cp: 'x' and 'x' are the same file
265
+ # and the non-zero exit killed all four models in 0.2s each. The
266
+ # PowerShell twin grew this guard during the sm_89 Windows run; this one
267
+ # had not.
268
+ [ "$SELF_DIR/$f" -ef "$dst" ] || cp "$SELF_DIR/$f" "$dst"
269
+ return # sitting next to this script
270
+ fi
271
+ if [ -n "$TOOLS_URL" ]; then
272
+ curl -fsSL "$TOOLS_URL/$f" -o "$dst" || die "download failed: $TOOLS_URL/$f"; return
273
+ fi
274
+ RC copyto "$TOOLS_PREFIX/$f" "$dst" --quiet \
275
+ || die "could not fetch $f — set TOOLS_URL or stage to $TOOLS_PREFIX (README §Stage tools)."
276
+ }
277
+ fetch_tool build_trt_engine.py
278
+ # onnx_fp16.py is a LOCAL repo module (models/_compile/tools/), not a PyPI
279
+ # package: build_trt_engine.py does `from onnx_fp16 import ensure_fp16_onnx`
280
+ # inside a try, so on a VM without it the import quietly fails and the FP16 pass
281
+ # is skipped. The build then SUCCEEDS and writes a correctly-named engine that is
282
+ # secretly FP32 - caught on Windows only because denoise came out 293 MB instead
283
+ # of 150. Fetch it next to the worker, where that import will find it.
284
+ fetch_tool onnx_fp16.py
285
+ # quantize_onnx.py is only needed for Mode A PTQ (int8/fp8 from FP32). Mode B (INT8_ONNX_S3)
286
+ # and fp16 never call it — skip the fetch, so you needn't even host it for the Mode-B path.
287
+ if [ -z "$INT8_ONNX_S3" ] && [ -z "$HF_MODEL_REPO" ] && [ "$PRECISION" != "fp16" ]; then
288
+ fetch_tool quantize_onnx.py
289
+ # The committed calibration corpus, alongside the tools. It replaces the
290
+ # staged graph.db: it is ~1.6 MB of plain JSONL instead of a multi-hundred-MB
291
+ # database, it carries no source paths or project names, and every VM
292
+ # calibrates on exactly the same samples — so an engine built on a rented
293
+ # sm_86 box is comparable with one built at a desk.
294
+ # Falls back to CALIB_DB_S3 when it is not hosted.
295
+ if [ -n "$SELF_DIR" ] && [ -f "$SELF_DIR/calib_corpus.jsonl" ]; then
296
+ # Same self-copy trap as fetch_tool above - and this one is on the
297
+ # INT8 path, so it fires for embed on every non-Turing arch.
298
+ [ "$SELF_DIR/calib_corpus.jsonl" -ef "$TOOLS_DIR/calib_corpus.jsonl" ] \n || cp "$SELF_DIR/calib_corpus.jsonl" "$TOOLS_DIR/calib_corpus.jsonl"
299
+ elif [ -n "$TOOLS_URL" ]; then
300
+ curl -fsSL "$TOOLS_URL/calib_corpus.jsonl" -o "$TOOLS_DIR/calib_corpus.jsonl" 2>/dev/null || true
301
+ else
302
+ RC copyto "$TOOLS_PREFIX/calib_corpus.jsonl" "$TOOLS_DIR/calib_corpus.jsonl" --quiet 2>/dev/null || true
303
+ fi
304
+ [ -s "$TOOLS_DIR/calib_corpus.jsonl" ] && CALIB_TEXTS="$TOOLS_DIR/calib_corpus.jsonl"
305
+ fi
306
+ ok "tools ready"
307
+ export ULTRACODE_NO_BOOTSTRAP=1 # don't look for the repo's models/.../_bootstrap.py
308
+
309
+ # ---- give build_trt_engine.py the version pin, and TensorRT itself ----------
310
+ # ULTRACODE_NO_BOOTSTRAP above disables the worker's own dependency install (it
311
+ # looks for a repo checkout that is not here), so nothing else would install
312
+ # TensorRT. And the worker needs the TRT version to NAME the engine before it
313
+ # builds one: it resolves `_pinned_trt_tag() or _installed_trt_tag()` and dies with
314
+ #
315
+ # ERROR: cannot determine the TensorRT version
316
+ #
317
+ # when neither answers. This block supplies both halves. The PowerShell twin has
318
+ # had it since the sm_89 Windows run; this one had not, and would have failed the
319
+ # same way on the first Linux cell.
320
+ if [ -n "$TRT_PIP" ]; then
321
+ # _pinned_trt_tag() walks up to six directories from the worker looking for
322
+ # vendor/tensorrt/VERSION. The worker sits in $TOOLS_DIR, so one is enough.
323
+ mkdir -p "$TOOLS_DIR/vendor/tensorrt"
324
+ printf '%s' "$TRT_PIP" > "$TOOLS_DIR/vendor/tensorrt/VERSION"
325
+ ok "pinned TRT version for the worker: $TRT_PIP"
326
+ fi
327
+
328
+ # PEP 668: Ubuntu 24.04 marks the distro python externally managed, and pip then
329
+ # refuses every install with a wall of text rather than a useful exit code.
330
+ PIPF=""
331
+ $PY -m pip install --dry-run --break-system-packages -q pip >/dev/null 2>&1 && PIPF="--break-system-packages"
332
+
333
+ # Same two-step import the worker performs. Checking only the flat `import
334
+ # tensorrt` would reject a bindings-only install that it is perfectly happy with -
335
+ # and bindings-only is what the NVIDIA index offers at our pin.
336
+ TRT_VER="$($PY - <<'EOF' 2>/dev/null
337
+ import sys
338
+ try:
339
+ import tensorrt as t
340
+ except Exception:
341
+ try:
342
+ from tensorrt_bindings import tensorrt as t
343
+ except Exception:
344
+ sys.exit(1)
345
+ print(getattr(t, "__version__", "unknown"))
346
+ EOF
347
+ )" || TRT_VER=""
348
+ # `|| TRT_VER=""` is load-bearing. This file runs under `set -euo pipefail`, and a
349
+ # command substitution that exits non-zero takes the ASSIGNMENT down with it - so
350
+ # the probe for "is TensorRT missing?" killed the script, silently and in 0.7s,
351
+ # precisely when the answer was "yes, missing". Same shape as the PowerShell
352
+ # twin's ErrorActionPreference=Stop bug: a check for an absent thing must not be
353
+ # fatal on absence. Measured: `false && x=1` survives set -e, `x="$(exit 1)"` does
354
+ # not.
355
+ case "$TRT_VER" in
356
+ [0-9]*.[0-9]*) ok "TensorRT already present: $TRT_VER" ;;
357
+ *)
358
+ # cu12 or cu13 decided by the DRIVER, the same test build_trt_engine.py
359
+ # makes. Hardcoding cu13 gave a clean install that then failed inside
360
+ # TensorRT with "CUDA initialization failure with error: 35" -
361
+ # cudaErrorInsufficientDriver: the wheels wanted a newer driver than the
362
+ # image ships. The TRT version, and so the trt11.0 tag, is identical
363
+ # either way; only the CUDA runtime they link against differs.
364
+ # ⛔ The header LABEL is being renamed across driver generations: a 595
365
+ # Linux driver prints `CUDA Version: 13.2`, a 616 Windows driver prints
366
+ # `CUDA UMD Version: 13.4`, and `nvidia-smi -q` marks the old spelling
367
+ # "Deprecated; will be removed in CUDA 14.0". Anchoring on the old label
368
+ # alone returns EMPTY on a newer driver, which reads below as "no CUDA
369
+ # version" and silently selects cu12 — the NEWEST drivers taking the
370
+ # OLDEST branch, and a cu13-only TensorRT pin then failing to install.
371
+ # Both spellings, verified against both header forms 2026-09-18.
372
+ SMI_CUDA="$(nvidia-smi 2>/dev/null | sed -n 's/.*CUDA \(UMD \)\{0,1\}Version:[[:space:]]*\([0-9][0-9]*\.[0-9][0-9]*\).*/\2/p' | head -1)" || SMI_CUDA=""
373
+ CU_MAJOR="${SMI_CUDA%%.*}"
374
+ if [ -n "$CU_MAJOR" ] && [ "$CU_MAJOR" -ge 13 ] 2>/dev/null; then CU=cu13; else CU=cu12; fi
375
+ # ⛔ DO NOT add a "the pin is cu13-only" guard here. One was added on
376
+ # 2026-09-18 and removed the same day: `pip index versions` shows the SAME
377
+ # TensorRT version published for BOTH branches — 11.3.0.99 exists as
378
+ # `tensorrt-cu12-libs` and as `tensorrt-cu13-libs`. The guard turned a
379
+ # working configuration into a refusal on the Selectel Windows images,
380
+ # whose driver is 539.19 / CUDA 12.2 and for which no newer image exists.
381
+ # The line above already says what matters: the TRT version, and therefore
382
+ # the `trt11.3` filename tag, is identical either way; only the CUDA
383
+ # runtime the builder links against differs, and the engine is keyed on
384
+ # {arch × OS × TRT version}, never on that.
385
+ step "Installing TensorRT ${TRT_PIP:-(unpinned)} for ${CU} (driver reports CUDA ${SMI_CUDA:-unknown})"
386
+
387
+ # bindings + libs, and NOT the `tensorrt-$CU` meta-package: on
388
+ # pypi.nvidia.com that meta is a 0.0.0a0 placeholder, so asking for it at
389
+ # our pin fails the WHOLE pip invocation and takes the two packages that
390
+ # would have installed down with it.
391
+ PIN="${TRT_PIP:+==$TRT_PIP}"
392
+ if ! $PY -m pip install $PIPF -q --only-binary ":all:" \
393
+ --extra-index-url https://pypi.nvidia.com \
394
+ "tensorrt-${CU}-bindings${PIN}" "tensorrt-${CU}-libs${PIN}"; then
395
+ if [ -n "$TRT_PIP" ]; then
396
+ warn "pinned install failed - retrying unpinned; the engine tag then follows what installs"
397
+ $PY -m pip install $PIPF -q --only-binary ":all:" \
398
+ --extra-index-url https://pypi.nvidia.com \
399
+ "tensorrt-${CU}-bindings" "tensorrt-${CU}-libs" \
400
+ || die "could not install TensorRT - see the pip output above"
401
+ else
402
+ die "could not install TensorRT - see the pip output above"
403
+ fi
404
+ fi
405
+ ;;
406
+ esac
407
+
408
+ # onnx reads the graph for the shape checks; without it the worker warns
409
+ # "onnx.load failed" and proceeds half-blind. onnxconverter-common is what
410
+ # onnx_fp16.py uses. huggingface_hub pulls the ONNX and pushes the engines -
411
+ # installed HERE rather than lazily, because a lazy install makes the first
412
+ # download fail with a traceback and only then fix itself, which is
413
+ # indistinguishable from a real failure.
414
+ $PY -m pip install $PIPF -q onnx numpy huggingface_hub onnxconverter-common \
415
+ || warn "pip install of the support packages returned non-zero - continuing"
416
+
417
+ # ── 5+6. obtain the ONNX to build from. Priority: HF_MODEL_REPO > INT8_ONNX_S3 > S3 FP32.
418
+ # Mode HF (recommended): pull model_int8qdt.onnx (int8) / model.onnx (fp16) from the public HF repo.
419
+ # Mode B (S3): reuse a pre-quantized model_int8qdt.onnx from S3 → byte-identical INT8, no PTQ.
420
+ # Mode A (S3): pull the FP32 ONNX and, for int8/fp8, run PTQ here (needs CALIB_DB_S3).
421
+ INT8_FLAG="--int8"
422
+ if [ -n "$HF_MODEL_REPO" ]; then
423
+ # Mode HF — pull the ONNX straight from the model's public HF repo (no S3, no creds).
424
+ HF_BASE="https://huggingface.co/${HF_MODEL_REPO}/resolve/main"
425
+ if [ "$PRECISION" = "fp16" ]; then
426
+ step "Mode HF (fp16) — pulling FP32 ONNX from $HF_BASE"
427
+ curl -fsSL "$HF_BASE/model.onnx" -o "$MODEL_DIR/model.onnx" || die "pull failed: $HF_BASE/model.onnx"
428
+ # Optional on purpose: only models above the 2 GB proto limit have one.
429
+ curl -fsSL "$HF_BASE/model.onnx.data" -o "$MODEL_DIR/model.onnx.data" 2>/dev/null || true
430
+
431
+ # ...but optional-for-everyone means a FAILED fetch of a REQUIRED sidecar
432
+ # looks exactly like a model that never had one. The builder would then
433
+ # parse a valid graph with no initialisers and write a correctly-named
434
+ # engine full of nothing. A split graph is single-digit MB where a whole
435
+ # model is hundreds, so the size is the discriminator.
436
+ _graph_bytes=$(stat -c%s "$MODEL_DIR/model.onnx" 2>/dev/null || echo 0)
437
+ if [ "$_graph_bytes" -lt 10485760 ] && [ ! -s "$MODEL_DIR/model.onnx.data" ]; then
438
+ die "model.onnx is only $_graph_bytes bytes and model.onnx.data is absent - this is a SPLIT onnx whose weights did not download. Building from it would yield an engine with no weights."
439
+ fi
440
+ [ -s "$MODEL_DIR/model.onnx.data" ] && ok "external-data sidecar: $(stat -c%s "$MODEL_DIR/model.onnx.data") bytes"
441
+
442
+ INT8_FLAG="--no-int8"
443
+ ok "FP32 ONNX pulled from HF — FP16 engines (no PTQ)"
444
+ else
445
+ step "Mode HF (int8) — pulling prebuilt INT8 ONNX from $HF_BASE (byte-identical to sm_120)"
446
+ curl -fsSL "$HF_BASE/model_int8qdt.onnx" -o "$MODEL_DIR/model_int8qdt.onnx" || die "pull failed: $HF_BASE/model_int8qdt.onnx"
447
+ ok "INT8 ONNX: $(du -h "$MODEL_DIR/model_int8qdt.onnx" | cut -f1) — build is byte-identical-precision to sm_120"
448
+ fi
449
+ elif [ -n "$INT8_ONNX_S3" ]; then
450
+ step "Mode B (S3) — reusing pre-quantized INT8 ONNX from $INT8_ONNX_S3"
451
+ RC copyto "$INT8_ONNX_S3" "$MODEL_DIR/model_int8qdt.onnx" --quiet || die "pull failed: $INT8_ONNX_S3"
452
+ # external-data sidecar, only if the quantizer wrote one (>2 GB models); harmless if absent
453
+ RC copyto "${INT8_ONNX_S3}_data" "$MODEL_DIR/model_int8qdt.onnx_data" --quiet 2>/dev/null || true
454
+ ok "INT8 ONNX: $(du -h "$MODEL_DIR/model_int8qdt.onnx" | cut -f1) — build is byte-identical-precision to sm_120"
455
+ else
456
+ SRC="${SRC_ONNX_S3:-s3:${S3_BUCKET}/${S3_MODEL_DIR}/runs/${RUN_ID}/variants/${TRAIN_VARIANT}/final}"
457
+ [ -n "$RUN_ID" ] || [ -n "$SRC_ONNX_S3" ] || die "set HF_MODEL_REPO (mode HF), INT8_ONNX_S3 (mode B), or RUN_ID/SRC_ONNX_S3 (mode A)."
458
+ step "Mode A — pulling FP32 ONNX from $SRC"
459
+ RC copy "$SRC" "$MODEL_DIR" --transfers 8 --quiet || die "pull failed from $SRC"
460
+ [ -f "$MODEL_DIR/model.onnx" ] || die "model.onnx not found under $SRC (check RUN_ID / TRAIN_VARIANT)."
461
+ ok "ONNX: $(du -h "$MODEL_DIR/model.onnx" | cut -f1) at $MODEL_DIR/model.onnx"
462
+
463
+ if [ "$PRECISION" = "fp16" ]; then
464
+ INT8_FLAG="--no-int8"
465
+ warn "PRECISION=fp16 — FP16 engines (no INT8 PTQ). Note sm_120 ships INT8; this differs."
466
+ elif [ "$PRECISION" = "fp8" ]; then
467
+ INT8_FLAG="--fp8"
468
+ fi
469
+
470
+ if [ "$PRECISION" = "int8" ] || [ "$PRECISION" = "fp8" ]; then
471
+ $PY -c "import onnx, onnxruntime, numpy" >/dev/null 2>&1 \
472
+ || { step "Installing PTQ deps (onnx onnxruntime numpy)"; $PY -m pip install -q onnx onnxruntime numpy; }
473
+ # Preferred: the committed corpus fetched with the tools. Only fall back
474
+ # to a staged graph.db when it is not hosted — that route needs a
475
+ # database copied off a machine that has indexed something, which a
476
+ # rented GPU box by definition has not.
477
+ if [ -n "${CALIB_TEXTS:-}" ]; then
478
+ CALIB_ARGS=(--calib-texts "$CALIB_TEXTS")
479
+ ok "calibration: corpus ($(wc -l < "$CALIB_TEXTS") samples, $(sha256sum "$CALIB_TEXTS" | cut -c1-12))"
480
+ elif [ -n "$CALIB_DB_S3" ]; then
481
+ step "Pulling calibration graph.db from $CALIB_DB_S3"
482
+ CALIB_LOCAL="$WORKDIR/calib.db"
483
+ RC copyto "$CALIB_DB_S3" "$CALIB_LOCAL" --quiet || die "calib db pull failed from $CALIB_DB_S3"
484
+ CALIB_ARGS=(--calib-db "$CALIB_LOCAL")
485
+ else
486
+ die "PRECISION=$PRECISION (mode A) needs calibration data: host calib_corpus.jsonl beside the tools (recommended), or set CALIB_DB_S3; or use INT8_ONNX_S3 (mode B), or PRECISION=fp16."
487
+ fi
488
+ PTQ_MODE_FLAG=""; PTQ_OUT="$MODEL_DIR/model_int8qdt.onnx"
489
+ [ "$PRECISION" = "fp8" ] && { PTQ_MODE_FLAG="--fp8"; PTQ_OUT="$MODEL_DIR/model_fp8qdt.onnx"; INT8_FLAG="--fp8"; }
490
+ step "PTQ ${PRECISION^^} quantization (quantize_onnx.py)"
491
+ $PY "$TOOLS_DIR/quantize_onnx.py" \
492
+ --model-dir "$MODEL_DIR" --onnx-dir "$MODEL_DIR" \
493
+ "${CALIB_ARGS[@]}" --max-seq "$PTQ_MAX_SEQ" --samples "$PTQ_SAMPLES" \
494
+ $PTQ_MODE_FLAG --output "$PTQ_OUT" || die "PTQ failed."
495
+ ok "PTQ ONNX: $(du -h "$PTQ_OUT" | cut -f1)"
496
+ fi
497
+ fi
498
+
499
+ # ── 7. build the engine(s) — arch passed explicitly so filenames are deterministic ───
500
+ # build_trt_engine.py picks up model_int8qdt.onnx / model_fp8qdt.onnx automatically and,
501
+ # on a strongly-typed TRT 11 build, reads precision from the ONNX Q/DQ nodes.
502
+ [ -z "$BUCKETS" ] && BUCKETS="__single__" # sentinel: one build, no --variant
503
+ BUILT=()
504
+ for b in $BUCKETS; do
505
+ VARIANT_ARGS=(); LABEL="(single)"
506
+ if [ "$b" != "__single__" ]; then VARIANT_ARGS=(--variant "$b"); LABEL="$b"; fi
507
+ step "Building TRT engine: ${MODEL_ID} ${LABEL} → ${SM} (${OS_ARCH}, ${PRECISION})"
508
+ $PY "$TOOLS_DIR/build_trt_engine.py" \
509
+ --model-dir "$MODEL_DIR" --model-id "$MODEL_ID" \
510
+ --role "$ROLE" --os-arch "$OS_ARCH" --cuda-arch "$SM" \
511
+ $INT8_FLAG "${VARIANT_ARGS[@]}" \
512
+ || die "engine build failed for variant ${LABEL}"
513
+ done
514
+
515
+ # Collect everything build_trt_engine.py emitted for this os×arch.
516
+ #
517
+ # The glob spans the runtime-version tag (`_trt11.0_`) instead of pinning it:
518
+ # build_trt_engine.py stamps that tag from the repo pin when a repo is present
519
+ # and from the building TensorRT otherwise — and this script runs on a bare VM
520
+ # with no vendor/ tree, so the value is only knowable AFTER the build. Collect
521
+ # whatever the builder produced for this os×arch, and let the version travel in
522
+ # the filename to the daemon that has to deserialize it.
523
+ shopt -s nullglob
524
+ ENGINES=( "$MODEL_DIR"/*"_${OS_ARCH}_trt"*"_${SM}.engine" )
525
+ [ ${#ENGINES[@]} -gt 0 ] || die "no .engine produced — check the build log above."
526
+ for e in "${ENGINES[@]}"; do BUILT+=("$e"); ok "engine: $(basename "$e") ($(du -h "$e" | cut -f1))"; done
527
+
528
+ # ── 8. upload engines back to S3 — FLAT list; the filename carries the tag info ───────
529
+ # CDN is a flat list keyed by tag: the runtime forms trt-cuda-$SM from the detected GPU and
530
+ # matches the _win/_linux substring in the filename, so a flat dir with correct names is all
531
+ # it needs. Diagnostic sidecars go under _meta/ so the engine list stays clean.
532
+ # HF and S3 are independent: both can run, either can be the only one.
533
+ DESTS=""
534
+ if [ "$HF_UPLOAD" = "1" ]; then
535
+ step "Uploading engines → huggingface.co/$HF_UPLOAD_REPO (flat, repo root)"
536
+ for e in "${BUILT[@]}"; do
537
+ hf_put "$e" "$HF_UPLOAD_REPO" "$(basename "$e")"
538
+ ok "HF ← $(basename "$e")"
539
+ done
540
+ DESTS="hf:$HF_UPLOAD_REPO"
541
+ fi
542
+ if [ -n "$DEST_PREFIX" ]; then
543
+ step "Uploading engines → $DEST_PREFIX/ (flat)"
544
+ for e in "${BUILT[@]}"; do
545
+ RC copyto "$e" "$DEST_PREFIX/$(basename "$e")" --quiet || die "upload failed: $e"
546
+ lj="${e%.engine}.layers.json"
547
+ [ -f "$lj" ] && RC copyto "$lj" "$DEST_PREFIX/_meta/$(basename "$lj")" --quiet || true
548
+ done
549
+ [ -f "$MODEL_DIR/timing.cache" ] && RC copyto "$MODEL_DIR/timing.cache" "$DEST_PREFIX/_meta/timing_${SM}_${OS_ARCH}.cache" --quiet || true
550
+ DESTS="${DESTS:+$DESTS + }$DEST_PREFIX"
551
+ fi
552
+
553
+ # ── 9. summary ────────────────────────────────────────────────────────────────────────
554
+ echo ""
555
+ echo "================================================================"
556
+ echo " DONE — ${#BUILT[@]} engine(s), ${MODEL_ID} ${SM} / ${OS_ARCH} (${PRECISION})"
557
+ echo " flat upload → $DESTS"
558
+ for e in "${BUILT[@]}"; do echo " $(basename "$e")"; done
559
+ echo " CDN tag for ALL of these: trt-cuda-${SM} (OS is disambiguated by _${OS_ARCH} in the filename)"
560
+ echo "================================================================"
_build-tools/build_matrix.json ADDED
@@ -0,0 +1,278 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "_generated_by": "models/_cloud_shared/build-tools/gen_build_matrix.py",
3
+ "_source": "models.json (itself generated from src/config/semantic_config.zig)",
4
+ "_note": "Do not hand-edit. Regenerate after any catalog or runtime-pin change.",
5
+ "trt_tag": "trt11.3",
6
+ "trt_pip_version": "11.3.0.99",
7
+ "cuda_archs": [
8
+ "sm_75",
9
+ "sm_80",
10
+ "sm_86",
11
+ "sm_89",
12
+ "sm_90"
13
+ ],
14
+ "hf_account": "faxenoff",
15
+ "models": [
16
+ {
17
+ "model_id": "code-daemon-embed-v1",
18
+ "hf_repo": "faxenoff/code-daemon-embed-v1",
19
+ "role": "embedding",
20
+ "buckets": [
21
+ "s",
22
+ "m",
23
+ "l",
24
+ "xl"
25
+ ],
26
+ "needs_ptq": false,
27
+ "trt": {
28
+ "sm_75": {
29
+ "mode": "fp16",
30
+ "precision": "fp16",
31
+ "source": {
32
+ "file": "model.onnx",
33
+ "ptq_on_vm": false
34
+ }
35
+ },
36
+ "sm_80": {
37
+ "mode": "int8_qdq",
38
+ "precision": "int8",
39
+ "source": {
40
+ "file": "model_int8qdt.onnx",
41
+ "ptq_on_vm": false
42
+ }
43
+ },
44
+ "sm_86": {
45
+ "mode": "int8_qdq",
46
+ "precision": "int8",
47
+ "source": {
48
+ "file": "model_int8qdt.onnx",
49
+ "ptq_on_vm": false
50
+ }
51
+ },
52
+ "sm_89": {
53
+ "mode": "int8_qdq",
54
+ "precision": "int8",
55
+ "source": {
56
+ "file": "model_int8qdt.onnx",
57
+ "ptq_on_vm": false
58
+ }
59
+ },
60
+ "sm_90": {
61
+ "mode": "int8_qdq",
62
+ "precision": "int8",
63
+ "source": {
64
+ "file": "model_int8qdt.onnx",
65
+ "ptq_on_vm": false
66
+ }
67
+ }
68
+ },
69
+ "hf_public": true
70
+ },
71
+ {
72
+ "model_id": "code-daemon-denoise-v1",
73
+ "hf_repo": "faxenoff/code-daemon-denoise-v1",
74
+ "role": "embedding",
75
+ "buckets": [
76
+ "s"
77
+ ],
78
+ "needs_ptq": false,
79
+ "trt": {
80
+ "sm_75": {
81
+ "mode": "fp16",
82
+ "precision": "fp16",
83
+ "source": {
84
+ "file": "model.onnx",
85
+ "ptq_on_vm": false
86
+ }
87
+ },
88
+ "sm_80": {
89
+ "mode": "fp16",
90
+ "precision": "fp16",
91
+ "source": {
92
+ "file": "model.onnx",
93
+ "ptq_on_vm": false
94
+ }
95
+ },
96
+ "sm_86": {
97
+ "mode": "fp16",
98
+ "precision": "fp16",
99
+ "source": {
100
+ "file": "model.onnx",
101
+ "ptq_on_vm": false
102
+ }
103
+ },
104
+ "sm_89": {
105
+ "mode": "fp16",
106
+ "precision": "fp16",
107
+ "source": {
108
+ "file": "model.onnx",
109
+ "ptq_on_vm": false
110
+ }
111
+ },
112
+ "sm_90": {
113
+ "mode": "fp16",
114
+ "precision": "fp16",
115
+ "source": {
116
+ "file": "model.onnx",
117
+ "ptq_on_vm": false
118
+ }
119
+ }
120
+ },
121
+ "hf_public": true
122
+ },
123
+ {
124
+ "model_id": "code-daemon-reranker-v1",
125
+ "hf_repo": "faxenoff/code-daemon-reranker-v1",
126
+ "role": "reranker",
127
+ "buckets": [],
128
+ "needs_ptq": false,
129
+ "trt": {
130
+ "sm_75": {
131
+ "mode": "fp16",
132
+ "precision": "fp16",
133
+ "source": {
134
+ "file": "model.onnx",
135
+ "ptq_on_vm": false
136
+ }
137
+ },
138
+ "sm_80": {
139
+ "mode": "fp16",
140
+ "precision": "fp16",
141
+ "source": {
142
+ "file": "model.onnx",
143
+ "ptq_on_vm": false
144
+ }
145
+ },
146
+ "sm_86": {
147
+ "mode": "fp16",
148
+ "precision": "fp16",
149
+ "source": {
150
+ "file": "model.onnx",
151
+ "ptq_on_vm": false
152
+ }
153
+ },
154
+ "sm_89": {
155
+ "mode": "fp16",
156
+ "precision": "fp16",
157
+ "source": {
158
+ "file": "model.onnx",
159
+ "ptq_on_vm": false
160
+ }
161
+ },
162
+ "sm_90": {
163
+ "mode": "fp16",
164
+ "precision": "fp16",
165
+ "source": {
166
+ "file": "model.onnx",
167
+ "ptq_on_vm": false
168
+ }
169
+ }
170
+ },
171
+ "hf_public": true
172
+ },
173
+ {
174
+ "model_id": "code-daemon-relation-v1",
175
+ "hf_repo": "faxenoff/code-daemon-relation-v1",
176
+ "role": "reranker",
177
+ "buckets": [
178
+ "s",
179
+ "m",
180
+ "l"
181
+ ],
182
+ "needs_ptq": false,
183
+ "trt": {
184
+ "sm_75": {
185
+ "mode": "fp16",
186
+ "precision": "fp16",
187
+ "source": {
188
+ "file": "model.onnx",
189
+ "ptq_on_vm": false
190
+ }
191
+ },
192
+ "sm_80": {
193
+ "mode": "fp16",
194
+ "precision": "fp16",
195
+ "source": {
196
+ "file": "model.onnx",
197
+ "ptq_on_vm": false
198
+ }
199
+ },
200
+ "sm_86": {
201
+ "mode": "fp16",
202
+ "precision": "fp16",
203
+ "source": {
204
+ "file": "model.onnx",
205
+ "ptq_on_vm": false
206
+ }
207
+ },
208
+ "sm_89": {
209
+ "mode": "fp16",
210
+ "precision": "fp16",
211
+ "source": {
212
+ "file": "model.onnx",
213
+ "ptq_on_vm": false
214
+ }
215
+ },
216
+ "sm_90": {
217
+ "mode": "fp16",
218
+ "precision": "fp16",
219
+ "source": {
220
+ "file": "model.onnx",
221
+ "ptq_on_vm": false
222
+ }
223
+ }
224
+ },
225
+ "hf_public": true
226
+ },
227
+ {
228
+ "model_id": "code-daemon-ner-v1",
229
+ "hf_repo": "faxenoff/code-daemon-ner-v1",
230
+ "role": "ner",
231
+ "buckets": [],
232
+ "needs_ptq": true,
233
+ "trt": {
234
+ "sm_75": {
235
+ "mode": "fp16",
236
+ "precision": "fp16",
237
+ "source": {
238
+ "file": "model.onnx",
239
+ "ptq_on_vm": false
240
+ }
241
+ },
242
+ "sm_80": {
243
+ "mode": "int8_qdq",
244
+ "precision": "int8",
245
+ "source": {
246
+ "file": "model.onnx",
247
+ "ptq_on_vm": true
248
+ }
249
+ },
250
+ "sm_86": {
251
+ "mode": "int8_qdq",
252
+ "precision": "int8",
253
+ "source": {
254
+ "file": "model.onnx",
255
+ "ptq_on_vm": true
256
+ }
257
+ },
258
+ "sm_89": {
259
+ "mode": "int8_qdq",
260
+ "precision": "int8",
261
+ "source": {
262
+ "file": "model.onnx",
263
+ "ptq_on_vm": true
264
+ }
265
+ },
266
+ "sm_90": {
267
+ "mode": "int8_qdq",
268
+ "precision": "int8",
269
+ "source": {
270
+ "file": "model.onnx",
271
+ "ptq_on_vm": true
272
+ }
273
+ }
274
+ },
275
+ "hf_public": true
276
+ }
277
+ ]
278
+ }
_build-tools/build_trt_engine.py ADDED
@@ -0,0 +1,1223 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env python3
2
+ """Build TensorRT engine from ONNX model with multi-profile bucketing.
3
+
4
+ Usage:
5
+ python scripts/build_trt_engine.py [--model-dir PATH] [--cuda-arch sm_120]
6
+
7
+ Two modes:
8
+ 1. trtexec (if in PATH) — NVIDIA's official CLI tool
9
+ 2. Python TensorRT API (fallback) — uses tensorrt pip package
10
+
11
+ Profiles (3 buckets matching tensorrt_runtime.zig default_profiles):
12
+ 0: batch 1-32, seq 1-32 (opt: 16x32) — short entity names
13
+ 1: batch 1-64, seq 1-64 (opt: 32x64) — entity descriptions
14
+ 2: batch 1-128, seq 1-128 (opt: 128x128) — docstrings / function bodies
15
+
16
+ Output: {model_id}_{os_arch}_trt{VER}_{cuda_arch}.engine in the model directory
17
+ (os_arch = win_x64 / linux_x64 / linux_arm64 / mac_arm64;
18
+ VER = TensorRT major.minor from vendor/tensorrt/VERSION, e.g. trt11.0).
19
+
20
+ A serialized plan is keyed on {GPU arch x OS x TRT version} and TensorRT offers
21
+ no compat fallback on deserialize, so the version belongs in the filename next
22
+ to the arch: the daemon then resolves an engine it can actually load instead of
23
+ opening a same-named plan from another TRT and failing inside the runtime.
24
+ """
25
+
26
+ import argparse
27
+ import os
28
+ import shutil
29
+ import subprocess
30
+ import sys
31
+ import warnings
32
+ from pathlib import Path
33
+
34
+ # Force UTF-8 output on Windows (default console encoding is CP1251/CP1252)
35
+ if hasattr(sys.stdout, "reconfigure"):
36
+ sys.stdout.reconfigure(encoding="utf-8", errors="replace")
37
+ if hasattr(sys.stderr, "reconfigure"):
38
+ sys.stderr.reconfigure(encoding="utf-8", errors="replace")
39
+
40
+ # Auto-install pip deps on first run when this script is invoked directly
41
+ # (i.e. without going through models/code-daemon-embed/run.ps1 / run.sh which
42
+ # already install everything). Idempotent — skips packages that are already importable.
43
+ if os.environ.get("ULTRACODE_NO_BOOTSTRAP") != "1":
44
+ # Repo root by walking up to build.zig, not by counting `..` — this file has
45
+ # moved once already (scripts/ -> models/_compile/backends/workers/) and a
46
+ # hardcoded depth breaks silently, since a missing directory just means "no
47
+ # bootstrap available".
48
+ _root = Path(__file__).resolve()
49
+ for _ in range(6):
50
+ _root = _root.parent
51
+ if (_root / "build.zig").is_file():
52
+ break
53
+ _bootstrap_dir = _root / "models" / "code-daemon-embed"
54
+ if (_bootstrap_dir / "_bootstrap.py").exists():
55
+ sys.path.insert(0, str(_bootstrap_dir))
56
+ try:
57
+ from _bootstrap import ensure_deps, ensure_nvidia_deps
58
+ # onnx is needed for ensure_single_file_onnx() and proto inspection;
59
+ # torch is not required by this script — skip the torch install.
60
+ ensure_deps(extra=["onnx"], torch_required=False)
61
+ # tensorrt + cuda-python (NVIDIA-only). No-op on macOS / CPU hosts.
62
+ ensure_nvidia_deps()
63
+ except Exception as _bs_err:
64
+ print(f"[bootstrap] WARNING: {_bs_err}", flush=True)
65
+ finally:
66
+ sys.path.remove(str(_bootstrap_dir))
67
+
68
+ # Suppress TRT deprecation warnings: implicit INT8 calibration (superseded by QAT/explicit
69
+ # quantization in TRT 10.1+) and per-layer precision (superseded by strong typing in TRT 10.12+).
70
+ # Replacements require ONNX QAT nodes / STRONGLY_TYPED mode — not applicable here.
71
+ warnings.filterwarnings("ignore", message=".*Deprecated.*", category=DeprecationWarning)
72
+ warnings.filterwarnings("ignore", message=".*deprecated.*", category=DeprecationWarning)
73
+
74
+
75
+ def ensure_single_file_onnx(onnx_path):
76
+ """Convert split ONNX (model.onnx + model.onnx_data) to single-file if needed."""
77
+ data_file = onnx_path + "_data"
78
+ if not os.path.exists(data_file):
79
+ return onnx_path
80
+
81
+ merged_path = onnx_path.replace(".onnx", "_merged.onnx")
82
+ if os.path.exists(merged_path):
83
+ merged_size = os.path.getsize(merged_path)
84
+ if merged_size < 1024 or merged_size > 2_000_000_000:
85
+ # Empty/corrupted or >2GB (protobuf can't parse) — delete stale cache
86
+ os.remove(merged_path)
87
+ print(f" Removed stale merged ONNX ({merged_size / 1e6:.0f} MB)")
88
+ else:
89
+ merged_mtime = os.path.getmtime(merged_path)
90
+ if (merged_mtime > os.path.getmtime(onnx_path) and
91
+ merged_mtime > os.path.getmtime(data_file)):
92
+ print(f" Split ONNX: using cached merged file")
93
+ return merged_path
94
+
95
+ try:
96
+ import onnx
97
+ print(f" Split ONNX detected: merging into single file...")
98
+ model = onnx.load(onnx_path, load_external_data=True)
99
+ onnx.save(model, merged_path)
100
+ merged_size = os.path.getsize(merged_path)
101
+ if merged_size > 2_000_000_000:
102
+ # >2GB: protobuf can't parse it back, trtexec may fail. Use original + external data.
103
+ os.remove(merged_path)
104
+ print(f" Merged {merged_size / 1e6:.0f} MB > 2GB limit, using split ONNX (parse_from_file handles external data)")
105
+ return onnx_path
106
+ print(f" Merged: {merged_size / (1024*1024):.1f} MB")
107
+ return merged_path
108
+ except Exception as e:
109
+ print(f" Split ONNX merge failed: {e}")
110
+ return onnx_path
111
+
112
+ # Profile specs: (max_batch, max_seq, opt_batch, opt_seq)
113
+ #
114
+ # Single rectangular profile per model type — no multi-profile bucketing.
115
+ # The daemon accumulates up to batch=128 before dispatch; buildEmbedInput
116
+ # caps at 420 chars ≈ 64 tokens so seq=64 covers all real traffic.
117
+ # Fewer profiles = less VRAM, faster compile, trivial selectProfile (always 0).
118
+ # Multi-profile builds were tried and produce slower kernels for the seq=64 path
119
+ # on Gemma sm_120 (autotuner picks kernels optimized for the broader shape range).
120
+ #
121
+ # Profile specs: (max_batch, max_seq, opt_batch, opt_seq).
122
+ #
123
+ # 2026-05-05 — half-batch-zero saga resolved. The "TRT sm_120 regression"
124
+ # we chased turned out to be a Zig-side dtype mismatch: engine input
125
+ # binding is INT64 (verified via getTensorDtype), but our worker copied
126
+ # host buffers as INT32 stride. Engine read 8 bytes per token from a
127
+ # buffer where we'd written 4 → got 2× rows of garbage from uninit
128
+ # memory, manifesting as "second half of every batch is zero". Fixed
129
+ # in tensorrt_runtime.zig + embed_worker.zig (i32 → i64 throughout the
130
+ # TRT input chain). Engine itself is fine; restore full 128 batch.
131
+ PROFILES = [
132
+ (128, 64, 128, 64), # 0: rectangular fast path — batch 128, seq 64
133
+ ]
134
+ RECTANGULAR_PROFILE = True
135
+
136
+ # Dynamic-seq probe (2026-07-28). Set `DYNSEQ_OVERRIDE="batch,min_seq,opt_seq,max_seq"`
137
+ # to build ONE engine whose SEQUENCE dimension is a range while the batch stays
138
+ # rectangular. Purpose: a chunk could then be dispatched at its own longest text
139
+ # instead of the bucket's ceiling — live telemetry says 15.3% of GPU token-work
140
+ # is padding (avg 42/48, 56/64, 70/80, 95/128). The question this answers is
141
+ # whether TRT's broader-range kernel choice costs more than the padding it saves;
142
+ # the file header already records that multi-PROFILE builds regressed seq=64 on
143
+ # sm_120. Applied AFTER --variant in main() so the engine still gets a suffixed
144
+ # filename. Production builds leave it unset.
145
+ DYNSEQ_MIN_SEQ = None
146
+
147
+ # ─── Experimental switches (hardcoded) ──────────────────────────────────
148
+ # Project preference: in-source const flip is cleaner than env-var dance
149
+ # for one-off experiments. Each switch documents its evidence + revert.
150
+ # Flip the value, save, run models/compile or build_trt_engine directly.
151
+
152
+ # Builder workspace pool. Default 4 GB; bump to 8-12 GB to widen TRT
153
+ # tactic search on autotuning. Build-time only — does NOT affect engine
154
+ # size or runtime VRAM. Risk: build OOM if value > free VRAM at build time.
155
+ # REVERT: change back to 4.
156
+ TRT_WORKSPACE_GB = 8
157
+
158
+ # TRT max_aux_streams config.
159
+ # 0 — workaround for the 2026-04-28 "5 valid + N zeros" sm_120 codegen
160
+ # bug (TRT 10.13.3). Forces single-stream kernel generation.
161
+ # 4 — TRT default. Researcher confirmed 2026-05-19 that post-fusion
162
+ # embedding graphs (BGE/Qwen3/Gemma) are too linear for aux streams
163
+ # to help, and TRT 10.16 gracefully self-disables ("Multi stream is
164
+ # disabled because the stream assignment failed" warning). Either
165
+ # value produces functionally identical engines on this family.
166
+ # Kept as probe knob — REVERT: 0.
167
+ TRT_MAX_AUX_STREAMS = 0
168
+
169
+ # Env override for sweep experiments. Format: RECT_PROFILE_OVERRIDE="batch,seq"
170
+ # — collapses PROFILES to a single (batch, seq, batch, seq) entry. Production
171
+ # builds leave this unset. Example: RECT_PROFILE_OVERRIDE="32,32".
172
+ _rect_override = os.environ.get("RECT_PROFILE_OVERRIDE", "").strip()
173
+ if _rect_override:
174
+ try:
175
+ _b, _s = (int(x) for x in _rect_override.split(","))
176
+ PROFILES = [(_b, _s, _b, _s)]
177
+ print(f"[build_trt] PROFILES overridden via env: rectangular ({_b}, {_s})", flush=True)
178
+ except (ValueError, AttributeError) as _e:
179
+ print(f"[build_trt] WARN: bad RECT_PROFILE_OVERRIDE='{_rect_override}': {_e}", flush=True)
180
+
181
+ # Length-aware bucket variants — when `--variant {s,m,l}` is passed, PROFILES
182
+ # collapses to that variant's rectangular (max_batch, max_seq). Single source
183
+ # of truth lives in `models/code-daemon-embed/embed_bucket_config.py`. We
184
+ # duplicate the tuples here to avoid forcing the build to import from a model
185
+ # subdirectory at parse-time (the bootstrap path may not yet be on sys.path).
186
+ # `models/_compile/preflight_bucket_sync.py` runs as a pre-build gate to catch drift.
187
+ BUCKET_VARIANT_PROFILES = {
188
+ # 2026-07-27: grid 40/64/128 → 32/48/80/128, measured on real engines
189
+ # (see the header comment in src/inference/embed_bucket_config.zig).
190
+ "s": (96, 48),
191
+ "m": (128, 64),
192
+ "l": (128, 80),
193
+ "xl": (256, 128),
194
+ }
195
+
196
+ # (min_seq, opt_seq) per embed bucket — the SEQUENCE dimension is a range while
197
+ # the batch stays rectangular, so a chunk is dispatched at its own longest text
198
+ # instead of the bucket ceiling. Live telemetry put 15.3% of GPU token-work in
199
+ # sequence padding; recovering it measured +10.2% end to end (9,738 -> 10,731
200
+ # emb/s on mysql-server) and is quality-neutral by construction — padding is
201
+ # masked in attention, verified at cosine 1.000000 on 128 rows of real ids.
202
+ #
203
+ # Two rules produced these numbers and neither is guessable:
204
+ # - `opt` sits at the bucket's histogram-weighted MEAN, not its ceiling. The
205
+ # tax is paid for being far from the opt point, not for being dynamic: one
206
+ # wide 16→64→128 engine costs +0.8% at seq 64 and +15.4% at seq 80.
207
+ # - `min` is the bucket FLOOR, not the observed corpus minimum — `s` gets 8
208
+ # rather than the measured 24, because the router must accept a 3-token text.
209
+ #
210
+ # This lived in a DYNSEQ_OVERRIDE env var and was deployed by copying files over
211
+ # the rectangular ones. A later `models/compile` run rebuilt them rectangular and
212
+ # the +10.2% was silently gone; the engines still loaded, still returned 768-dim
213
+ # vectors, and reported 54 layers instead of 69 where nobody was looking. Hence
214
+ # the table: a plain build now produces the shape that is meant to ship.
215
+ BUCKET_VARIANT_DYNSEQ = {
216
+ "s": (8, 48),
217
+ "m": (56, 56),
218
+ "l": (72, 72),
219
+ "xl": (88, 96),
220
+ }
221
+
222
+ # NER single profile: batch=32 (NER worker --batch-size 32), seq=128.
223
+ # Bumped from seq=64 (2026-05-05) — ~20% of incoming chunks exceed 64
224
+ # tokens (long entity descriptions, function bodies, docstrings), causing
225
+ # `SetShapeFailed` at runtime and DocGraph falling back to rules-only for
226
+ # those entities. The OV NER variants ship as `_b32_s128`, so the ONNX
227
+ # already supports seq=128. Opt point sits at 96 — middle of the 1..128
228
+ # range, biasing the autotuner toward the typical mass of inputs without
229
+ # regressing the long tail.
230
+ NER_PROFILES = [
231
+ # 0: NER main path — RECTANGULAR (max == opt) to avoid an invalid
232
+ # min<=opt<=max profile. The previous value (32, 128, 32, 96) set
233
+ # opt_seq=96 < max_seq=128, which under RECTANGULAR_PROFILE (min==max==128)
234
+ # makes opt_seq < min_seq → TRT 11 rejects with "Invalid optimization
235
+ # profiles ... ensure MIN<=OPT<=MAX". The NER worker always pads to
236
+ # batch=32 seq=128, so a static 32x128 profile is correct.
237
+ (32, 128, 32, 128),
238
+ ]
239
+
240
+ # Reranker single profile: batch=16 (reranker worker max_batch=16, matches the OV engine
241
+ # `_b16_s256` and models/compile.cmd's $ovChkBatch=16), seq=256. The cross-encoder scores
242
+ # (query, document) PAIRS, which are long, so seq must be 256 — NOT the embedding default
243
+ # (128, 64). Without a reranker-specific profile, `--role reranker` fell through to the
244
+ # embedding PROFILES (128, 64); the engine bound seq=64 while handleRerank pads to
245
+ # max_seq_len=256 → SetShapeFailed at runtime → search degraded to no-rerank. RECTANGULAR
246
+ # (min==opt==max) per handleRerank's rectangular-engine contract (embed_worker.zig:4867).
247
+ RERANKER_PROFILES = [
248
+ (16, 256, 16, 256),
249
+ ]
250
+
251
+
252
+ def _installed_trt_tag():
253
+ """`trt{major}.{minor}` of the TensorRT in THIS interpreter, or None."""
254
+ try:
255
+ import tensorrt as trt
256
+ parts = str(trt.__version__).split(".")
257
+ except Exception:
258
+ return None
259
+ return f"trt{parts[0]}.{parts[1]}" if len(parts) >= 2 and parts[0] else None
260
+
261
+
262
+ def _pinned_trt_tag():
263
+ """`trt{major}.{minor}` from `vendor/tensorrt/VERSION`, or None if no repo.
264
+
265
+ This is the pin build.zig turns into the daemon's `runtime_versions.trt_tag`,
266
+ so naming from it guarantees the engine we write is the engine the worker
267
+ looks for. Absent when the script runs standalone — the cloud sm_86/sm_89
268
+ builder (models/_cloud_shared/build-tools/build_engines.sh) copies only this
269
+ .py onto a bare VM, with no vendor/ tree to read.
270
+ """
271
+ d = os.path.dirname(os.path.abspath(__file__))
272
+ for _ in range(6): # walk up to repo root
273
+ pin = os.path.join(d, "vendor", "tensorrt", "VERSION")
274
+ if os.path.isfile(pin):
275
+ try:
276
+ parts = open(pin).read().strip().split(".")
277
+ except OSError:
278
+ return None
279
+ return f"trt{parts[0]}.{parts[1]}" if len(parts) >= 2 and parts[0] else None
280
+ parent = os.path.dirname(d)
281
+ if parent == d:
282
+ return None
283
+ d = parent
284
+ return None
285
+
286
+
287
+ def _trt_runtime_tag():
288
+ """Runtime-version tag embedded in every engine filename, e.g. `trt11.0`.
289
+
290
+ Prefers the repo pin (what the DAEMON will deserialize with); falls back to
291
+ the TensorRT actually doing the build, so a standalone/cloud run still
292
+ produces a correctly-labelled engine instead of failing. Only when neither is
293
+ knowable do we stop: an untagged engine is invisible to the daemon, and TRT
294
+ builds are far too slow to discover that afterwards.
295
+ """
296
+ tag = _pinned_trt_tag() or _installed_trt_tag()
297
+ if tag:
298
+ return tag
299
+ print("ERROR: cannot determine the TensorRT version — neither vendor/tensorrt/VERSION")
300
+ print(" nor an importable `tensorrt` package. Engine filenames carry the")
301
+ print(" TensorRT major.minor and the daemon only loads its own version.")
302
+ sys.exit(1)
303
+
304
+
305
+ def _refuse_trt_version_skew(rt_tag):
306
+ """Stop when the TensorRT building this engine is not the pinned one.
307
+
308
+ Matters more here than anywhere else: the plan is produced by the `tensorrt`
309
+ package in THIS interpreter but deserialized by the vendored nvinfer the
310
+ daemon links. If they differ, the file gets a name promising a runtime that
311
+ cannot read it — a load failure the version tag exists to prevent.
312
+
313
+ This was a WARNING until 2026-09-12. It printed on every Linux build for
314
+ weeks while every Linux engine was built by 11.2 and named trt11.0
315
+ (`models/_compile/deps/wsl.py:_trt_pin`), because nothing consumed it. There
316
+ is no legitimate skew: a patch-level difference yields the same tag and never
317
+ reaches this branch, and a standalone cloud run has no pin, so `rt_tag` IS the
318
+ installed tag there. A missing package is handled elsewhere.
319
+ """
320
+ installed_tag = _installed_trt_tag()
321
+ if installed_tag and installed_tag != rt_tag:
322
+ print(f"ERROR: TensorRT version skew — this interpreter has {installed_tag} "
323
+ f"but the engine would be named {rt_tag} (from vendor/tensorrt/VERSION).")
324
+ print(f" The daemon deserializes with the pinned runtime and would "
325
+ f"REJECT the plan. Install tensorrt-cu13 at the pin, or bump the pin.")
326
+ sys.exit(1)
327
+
328
+
329
+ def get_cuda_arch():
330
+ """Detect CUDA compute capability via nvidia-smi."""
331
+ try:
332
+ out = subprocess.check_output(
333
+ ["nvidia-smi", "--query-gpu=compute_cap", "--format=csv,noheader"],
334
+ text=True,
335
+ ).strip().split("\n")[0]
336
+ major, minor = out.split(".")
337
+ return f"sm_{major}{minor}"
338
+ except Exception:
339
+ return None
340
+
341
+
342
+ def _onnx_is_valid(path):
343
+ """Quick-check that an ONNX file is parseable (not truncated).
344
+ Files >1 MB that fail onnx.load are assumed valid: Python protobuf has a 2 GB
345
+ parse limit but trtexec uses the C++ ONNX parser which has no such limit."""
346
+ try:
347
+ import onnx
348
+ onnx.load(path, load_external_data=False)
349
+ return True
350
+ except Exception as e:
351
+ try:
352
+ size = os.path.getsize(path)
353
+ if size > 1024 * 1024:
354
+ print(f" NOTE: onnx.load failed ({e}), file is {size / (1024*1024):.0f} MB "
355
+ f"— assuming valid (trtexec uses C++ parser, no 2 GB limit)")
356
+ return True
357
+ except Exception:
358
+ pass
359
+ return False
360
+
361
+
362
+ def _has_all_external_data(onnx_path):
363
+ """Return True if every external-data file referenced by the ONNX header exists
364
+ in the same directory. Returns True (optimistic) when the header itself cannot
365
+ be loaded (e.g. 2 GB+ merged file — no external refs to check)."""
366
+ try:
367
+ import onnx as _onnx
368
+ header = _onnx.load(onnx_path, load_external_data=False)
369
+ except Exception:
370
+ return True # can't check — assume ok (2 GB+ merged, no external refs)
371
+ onnx_dir = os.path.dirname(os.path.abspath(onnx_path))
372
+ for t in header.graph.initializer:
373
+ if t.data_location == _onnx.TensorProto.EXTERNAL:
374
+ for entry in t.external_data:
375
+ if entry.key == "location":
376
+ if not os.path.exists(os.path.join(onnx_dir, entry.value)):
377
+ return False
378
+ return True
379
+
380
+
381
+ def find_onnx(model_dir, mode="int8"):
382
+ """Find ONNX model in model directory, with validation and cache fallback.
383
+
384
+ `mode` controls preference order:
385
+ - "fp8": prefer `model_fp8qdt.onnx` (ModelOpt FP8 PTQ output) over INT8.
386
+ - "int8" (default): prefer `model_int8qdt.onnx` (ModelOpt INT8 PTQ output).
387
+ - "bf16": prefer plain `model.onnx`.
388
+ Falls back through the alternate-precision PTQ ONNX before raw `model.onnx`
389
+ so that a misconfigured catalog still produces a build (TRT will pick up
390
+ whatever Q/DQ nodes are in the file).
391
+ """
392
+ # Last-resort fallback: the compiler's download cache for third-party models
393
+ # (`models/_compile/.cache/models/<id>/`). The compiler itself always passes
394
+ # `--onnx` explicitly and the cloud builder stages the ONNX into --model-dir,
395
+ # so this is only reached by a hand-run invocation.
396
+ #
397
+ # It used to be derived as `<this script's dir>/.cache/<id>`, which pointed
398
+ # at `scripts/.cache` while the script lived there and became a path that can
399
+ # never exist once it moved.
400
+ model_name = os.path.basename(os.path.normpath(model_dir))
401
+ _pkg_dir = os.path.dirname(os.path.abspath(__file__)) # …/backends/workers
402
+ _compile_root = os.path.dirname(os.path.dirname(_pkg_dir)) # …/models/_compile
403
+ cache_dir = os.environ.get("ULTRACODE_COMPILE_CACHE") or \
404
+ os.path.join(_compile_root, ".cache")
405
+ cache_path = os.path.join(cache_dir, "models", model_name, "model.onnx")
406
+
407
+ int8_candidates = [
408
+ os.path.join(model_dir, "onnx", "model_int8qdt.onnx"),
409
+ os.path.join(model_dir, "model_int8qdt.onnx"),
410
+ os.path.join(cache_dir, "models", model_name, "model_int8qdt.onnx"),
411
+ ]
412
+ fp8_candidates = [
413
+ os.path.join(model_dir, "onnx", "model_fp8qdt.onnx"),
414
+ os.path.join(model_dir, "model_fp8qdt.onnx"),
415
+ os.path.join(cache_dir, "models", model_name, "model_fp8qdt.onnx"),
416
+ ]
417
+ plain_candidates = [
418
+ os.path.join(model_dir, "model.onnx"),
419
+ os.path.join(model_dir, "onnx", "model.onnx"),
420
+ cache_path,
421
+ ]
422
+
423
+ if mode == "fp8":
424
+ candidates = fp8_candidates + int8_candidates + plain_candidates
425
+ elif mode == "bf16":
426
+ candidates = plain_candidates + int8_candidates + fp8_candidates
427
+ else:
428
+ candidates = int8_candidates + plain_candidates + fp8_candidates
429
+
430
+ for p in candidates:
431
+ if os.path.exists(p):
432
+ if not _onnx_is_valid(p):
433
+ print(f" WARNING: {p} is corrupted (truncated?), trying next candidate")
434
+ continue
435
+ if not _has_all_external_data(p):
436
+ print(f" NOTE: {p} has missing external data files — trying next candidate")
437
+ continue
438
+ return p
439
+ return None
440
+
441
+
442
+ def onnx_has_qdq(onnx_path):
443
+ """True if the ONNX model contains explicit Q/DQ nodes (PTQ quantized).
444
+
445
+ When Q/DQ nodes are present, TRT must have a matching precision builder
446
+ flag enabled (INT8 for int8qdt, FP8 for fp8qdt). Without it, TRT silently
447
+ ignores DequantizeLinear/QuantizeLinear and builds a plain BF16/FP16
448
+ engine, wasting the calibration work.
449
+ Detection by filename is sufficient — quantize_onnx.py always writes
450
+ 'model_int8qdt.onnx' (INT8 mode) or 'model_fp8qdt.onnx' (FP8 mode).
451
+ """
452
+ name = os.path.basename(onnx_path)
453
+ return any(tag in name for tag in ("int8qdt", "fp8qdt", "nvfp4qdt", "int4qdt"))
454
+
455
+
456
+ def onnx_is_fp8(onnx_path):
457
+ """True if the ONNX model is a ModelOpt FP8 PTQ output (fp8qdt naming).
458
+
459
+ Used to distinguish FP8-quantized ONNX (needs --fp8 builder flag) from
460
+ INT8-quantized ONNX (needs --int8). When neither, fallback paths apply.
461
+ """
462
+ return "fp8qdt" in os.path.basename(onnx_path)
463
+
464
+
465
+ def build_with_trtexec(onnx_path, engine_path, trtexec_bin="trtexec"):
466
+ """Build engine using trtexec CLI (TRT 11: strongly-typed only)."""
467
+ onnx_path = ensure_single_file_onnx(onnx_path)
468
+ cmd = [trtexec_bin, f"--onnx={onnx_path}", f"--saveEngine={engine_path}"]
469
+ # TRT 11: precision is read entirely from the ONNX Q/DQ nodes. Strongly typed
470
+ # is the only typing mode — the per-precision flags (--int8/--fp16/--bf16/--fp8)
471
+ # and the INT8 calibrator (--calib) were removed. `--stronglyTyped` is not
472
+ # passed: TRT 11.3 release notes list it as a flag with no effect.
473
+
474
+ # Timing cache: speeds up rebuilds dramatically (minutes → seconds)
475
+ timing_cache = os.path.join(os.path.dirname(engine_path), "timing.cache")
476
+ cmd.append(f"--timingCacheFile={timing_cache}")
477
+ # Max builder optimization level for best engine quality
478
+ cmd.append("--builderOptimizationLevel=5")
479
+ # 2026-04-28 — sm_120 aux-stream regression fix (researcher rec #4 in
480
+ # .autodoc/archive/inference-backends.md). TRT 10.13.3 / 10.16.1 release notes
481
+ # document a multi-stream codegen bug on consumer Blackwell (sm_120)
482
+ # that affects pooling/attention subgraphs and produces partial
483
+ # outputs (the embeddinggemma "5 valid + N-5 zeros" symptom matches
484
+ # this signature: kernel runs but writes zeros to trailing rows).
485
+ # Disabling aux streams bypasses the buggy codegen path; cost is
486
+ # one stream of dispatch concurrency we don't currently exploit.
487
+ #
488
+ # 2026-05-19 — value lives at module top as TRT_MAX_AUX_STREAMS const.
489
+ # Flip there + rebuild to probe (researcher confirmed it's effectively
490
+ # a no-op on embedding models; TRT 10.16 self-disables anyway).
491
+ cmd.append(f"--maxAuxStreams={TRT_MAX_AUX_STREAMS}")
492
+ if TRT_MAX_AUX_STREAMS != 0:
493
+ print(f" [build_trt] TRT_MAX_AUX_STREAMS={TRT_MAX_AUX_STREAMS} — sm_120 workaround DISABLED")
494
+ # `--useCudaGraph` / `--useSpinWait` were passed here until 2026-09-22. They
495
+ # only shaped trtexec's post-build benchmark, never the saved engine, and
496
+ # TRT 11.3 release notes list both as flags with no effect — so a benchmark
497
+ # line printed by an 11.3 trtexec is measured WITHOUT graphs and does not
498
+ # compare with 10.16/11.0 logs. The runtime counterpart was measured and
499
+ # left off: `cuda_graphs_enabled` in src/inference/tensorrt_runtime.zig.
500
+
501
+ for max_b, max_s, opt_b, opt_s in PROFILES:
502
+ cmd.extend([
503
+ f"--minShapes=input_ids:1x1,attention_mask:1x1",
504
+ f"--optShapes=input_ids:{opt_b}x{opt_s},attention_mask:{opt_b}x{opt_s}",
505
+ f"--maxShapes=input_ids:{max_b}x{max_s},attention_mask:{max_b}x{max_s}",
506
+ ])
507
+
508
+ print(f" trtexec command: {' '.join(cmd[:5])} ...")
509
+ result = subprocess.run(cmd)
510
+ return result.returncode == 0
511
+
512
+
513
+ def _add_nvinfer_to_path():
514
+ """Add vendor/tensorrt/lib AND pip tensorrt_libs to DLL search path."""
515
+ added = []
516
+
517
+ # 1. vendor/tensorrt/lib (our bundled runtime DLLs).
518
+ # This file lives at models/_compile/backends/workers/, so the repo root is
519
+ # four levels up. It used to be one (`scripts/../vendor`), which stopped
520
+ # resolving the moment the script moved — silently, because the directory
521
+ # simply "was not there" and the pip tensorrt_libs below usually covered it.
522
+ _here = os.path.dirname(os.path.abspath(__file__))
523
+ _repo_root = os.path.abspath(os.path.join(_here, "..", "..", "..", ".."))
524
+ vendor_lib = os.path.join(_repo_root, "vendor", "tensorrt", "lib")
525
+ if os.path.isdir(vendor_lib):
526
+ added.append(vendor_lib)
527
+
528
+ # 2. pip tensorrt_libs (contains nvinfer_plugin_10.dll needed for builder)
529
+ try:
530
+ import site
531
+ for sp in site.getsitepackages() + [site.getusersitepackages()]:
532
+ trt_libs = os.path.join(sp, "tensorrt_libs")
533
+ if os.path.isdir(trt_libs):
534
+ added.append(trt_libs)
535
+ break
536
+ except Exception:
537
+ pass
538
+
539
+ # Register all paths
540
+ for lib_dir in added:
541
+ if sys.platform == "win32" and hasattr(os, "add_dll_directory"):
542
+ try:
543
+ os.add_dll_directory(lib_dir)
544
+ except OSError:
545
+ pass
546
+ os.environ["PATH"] = lib_dir + os.pathsep + os.environ.get("PATH", "")
547
+
548
+ return added[0] if added else None
549
+
550
+
551
+ def _import_tensorrt():
552
+ """Import tensorrt, handling the cu12_bindings layout."""
553
+ _add_nvinfer_to_path()
554
+
555
+ # Try direct import first (tensorrt meta-package installed)
556
+ try:
557
+ import tensorrt
558
+ return tensorrt
559
+ except (ImportError, ModuleNotFoundError, FileNotFoundError, OSError):
560
+ pass
561
+
562
+ # Try bindings-only import (tensorrt_cu12_bindings installed)
563
+ try:
564
+ from tensorrt_bindings import tensorrt
565
+ return tensorrt
566
+ except (ImportError, ModuleNotFoundError, FileNotFoundError, OSError):
567
+ pass
568
+
569
+ return None
570
+
571
+
572
+ def _has_cuda_runtime():
573
+ """Check if CUDA runtime is available (libcudart loadable)."""
574
+ import ctypes
575
+ for lib in ["libcudart.so", "libcudart.so.13", "libcudart.so.12", "libcudart.so.11",
576
+ "cudart64_13.dll", "cudart64_12.dll", "cudart64_110.dll"]:
577
+ try:
578
+ ctypes.cdll.LoadLibrary(lib)
579
+ return True
580
+ except OSError:
581
+ pass
582
+ # Also check if nvcc is in PATH (CUDA toolkit installed)
583
+ if shutil.which("nvcc"):
584
+ return True
585
+ return False
586
+
587
+
588
+ def ensure_tensorrt_package():
589
+ """Auto-install tensorrt Python bindings + libs if missing."""
590
+ trt = _import_tensorrt()
591
+ if trt is not None:
592
+ return True
593
+
594
+ if not _has_cuda_runtime():
595
+ print(" tensorrt not available: CUDA runtime not found (no libcudart/nvcc)", file=sys.stderr)
596
+ print(" Install CUDA toolkit or add trtexec to PATH", file=sys.stderr)
597
+ return False
598
+
599
+ print(" tensorrt not found — installing via pip...")
600
+ nvidia_idx = "https://pypi.nvidia.com"
601
+
602
+ # Detect CUDA major version to pick matching tensorrt build. Mixing cu12
603
+ # and cu13 packages produces version-mismatch errors at engine deserialize
604
+ # because the engine plan encodes the build-time native DLL version, and
605
+ # `import tensorrt` then resolves to a different package's DLL at runtime.
606
+ cuda_major = None
607
+ try:
608
+ nvsmi = subprocess.check_output(
609
+ ["nvidia-smi"], stderr=subprocess.DEVNULL, text=True, timeout=5,
610
+ )
611
+ import re
612
+ m = re.search(r"CUDA Version:\s*(\d+)\.(\d+)", nvsmi)
613
+ if m:
614
+ cuda_major = int(m.group(1))
615
+ except Exception:
616
+ pass
617
+
618
+ if cuda_major and cuda_major >= 13:
619
+ candidates = [
620
+ ["tensorrt-cu13-bindings==11.0.0.114", "tensorrt-cu13-libs==11.0.0.114"],
621
+ ["tensorrt-cu13-bindings", "tensorrt-cu13-libs"],
622
+ ]
623
+ else:
624
+ candidates = [
625
+ ["tensorrt-cu12-bindings==11.0.0.114", "tensorrt-cu12-libs==11.0.0.114"],
626
+ ["tensorrt-cu12-bindings", "tensorrt-cu12-libs"],
627
+ ]
628
+
629
+ for pkgs in candidates:
630
+ result = subprocess.run(
631
+ [sys.executable, "-m", "pip", "install", "--quiet",
632
+ "--only-binary", ":all:",
633
+ "--extra-index-url", nvidia_idx] + pkgs,
634
+ capture_output=True, text=True,
635
+ )
636
+ if result.returncode == 0:
637
+ break
638
+ else:
639
+ # Last resort: try the meta-package
640
+ subprocess.run(
641
+ [sys.executable, "-m", "pip", "install", "--quiet",
642
+ "--only-binary", ":all:",
643
+ "--extra-index-url", nvidia_idx,
644
+ "tensorrt"],
645
+ capture_output=True, text=True,
646
+ )
647
+
648
+ trt = _import_tensorrt()
649
+ if trt is not None:
650
+ print(f" tensorrt {trt.__version__} ready")
651
+ return True
652
+
653
+ print(" tensorrt still not importable after install", file=sys.stderr)
654
+ return False
655
+
656
+
657
+ def _upgrade_onnx_opset(onnx_path, target_opset=17):
658
+ """Upgrade ONNX model to target opset if needed (fixes LayerNorm FP16 overflow)."""
659
+ # Handle split ONNX first — skip upgrade if merge fails (>2GB models)
660
+ data_file = onnx_path + "_data"
661
+ if os.path.exists(data_file):
662
+ merged = ensure_single_file_onnx(onnx_path)
663
+ if merged == onnx_path:
664
+ # Merge failed (protobuf 2GB limit) — skip opset upgrade, TRT will parse directly
665
+ print(f" Opset upgrade skipped: split ONNX too large to merge")
666
+ return onnx_path
667
+ onnx_path = merged
668
+ else:
669
+ onnx_path = ensure_single_file_onnx(onnx_path)
670
+ try:
671
+ import onnx
672
+ from onnx import version_converter
673
+ model = onnx.load(onnx_path)
674
+ current_opset = model.opset_import[0].version if model.opset_import else 0
675
+ if current_opset >= target_opset:
676
+ return onnx_path # already sufficient
677
+ print(f" Upgrading ONNX opset {current_opset} → {target_opset} (fixes LayerNorm FP16 overflow)")
678
+ model = version_converter.convert_version(model, target_opset)
679
+ upgraded_path = onnx_path.replace(".onnx", f"_opset{target_opset}.onnx")
680
+ onnx.save(model, upgraded_path)
681
+ return upgraded_path
682
+ except Exception as e:
683
+ print(f" ONNX opset upgrade skipped: {e}")
684
+ return onnx_path
685
+
686
+
687
+ def build_with_python_api(onnx_path, engine_path, fp16=True, int8=False, fp8=False, bf16=False, per_layer_norm=False, strongly_typed=False):
688
+ """Build engine using TensorRT Python API (no trtexec needed)."""
689
+ if not ensure_tensorrt_package():
690
+ return False
691
+
692
+ trt = _import_tensorrt()
693
+
694
+ # Upgrade ONNX opset to 17+ for native INormalizationLayer (fixes FP16 LayerNorm overflow)
695
+ onnx_path = _upgrade_onnx_opset(onnx_path, target_opset=17)
696
+
697
+ logger = trt.Logger(trt.Logger.WARNING)
698
+ builder = trt.Builder(logger)
699
+
700
+ # TRT 11: EXPLICIT_BATCH was removed (explicit batch is the only mode) and
701
+ # STRONGLY_TYPED is the default + only typing mode. Precision comes entirely
702
+ # from the ONNX Q/DQ nodes — TRT reads each tensor's data_type as-is, with no
703
+ # backward type-inference that would propagate INT8 onto a DequantizeLinear's
704
+ # shared scale tensor. Per-precision BuilderFlags, the INT8 calibrator, and
705
+ # per-layer precision were ALL removed in TRT 11; this is now the only path.
706
+ network_flags = 1 << int(trt.NetworkDefinitionCreationFlag.STRONGLY_TYPED)
707
+ network = builder.create_network(network_flags)
708
+ print(" STRONGLY_TYPED: enabled (TRT 11 default; precision from Q/DQ ONNX nodes)")
709
+ parser = trt.OnnxParser(network, logger)
710
+
711
+ print(f" Parsing ONNX: {onnx_path}")
712
+ # Use parse_from_file if available (TRT 8.6+) — resolves external data (model.onnx_data)
713
+ # relative to the ONNX file directory. Falls back to parse(bytes) + chdir for older TRT.
714
+ parsed_ok = False
715
+ if hasattr(parser, "parse_from_file"):
716
+ parsed_ok = parser.parse_from_file(onnx_path)
717
+ else:
718
+ # Older TRT: chdir to model directory so external data is found
719
+ prev_cwd = os.getcwd()
720
+ os.chdir(os.path.dirname(os.path.abspath(onnx_path)))
721
+ try:
722
+ with open(onnx_path, "rb") as f:
723
+ parsed_ok = parser.parse(f.read())
724
+ finally:
725
+ os.chdir(prev_cwd)
726
+ if not parsed_ok:
727
+ for i in range(parser.num_errors):
728
+ print(f" ONNX parse error: {parser.get_error(i)}", file=sys.stderr)
729
+ return False
730
+
731
+ config = builder.create_builder_config()
732
+ # Workspace pool — bigger = wider tactic search. Const TRT_WORKSPACE_GB
733
+ # at module top. Default 4 GB; bumping to 8-12 GB widens tactic search.
734
+ # Build-time only — freed when builder exits.
735
+ config.set_memory_pool_limit(trt.MemoryPoolType.WORKSPACE, TRT_WORKSPACE_GB << 30)
736
+ print(f" Workspace pool: {TRT_WORKSPACE_GB} GB" + (" (default)" if TRT_WORKSPACE_GB == 4 else " (probe value)"))
737
+ # Max builder optimization level for best engine quality
738
+ config.builder_optimization_level = 5
739
+ # Detailed profiling info — needed for the engine_inspector dump below
740
+ # to enumerate fused layers (MHA, GEMM, SkipLayerNormalization, etc).
741
+ # Negligible build-time overhead; engine itself is unchanged.
742
+ try:
743
+ config.profiling_verbosity = trt.ProfilingVerbosity.DETAILED
744
+ except AttributeError:
745
+ pass
746
+ # 2026-04-28 — sm_120 aux-stream regression fix (researcher rec #4).
747
+ # TRT 10.13.3 / 10.16.1 release notes document a multi-stream
748
+ # codegen bug on consumer Blackwell (sm_120). Setting max_aux_streams
749
+ # to 0 bypasses the buggy path. Property added in TRT 8.6+; older
750
+ # versions silently ignore (try/except for safety).
751
+ #
752
+ # 2026-05-19 — value from module-top const TRT_MAX_AUX_STREAMS.
753
+ try:
754
+ config.max_aux_streams = TRT_MAX_AUX_STREAMS
755
+ if TRT_MAX_AUX_STREAMS == 0:
756
+ print(" max_aux_streams: 0 (sm_120 regression workaround)")
757
+ else:
758
+ print(f" max_aux_streams: {TRT_MAX_AUX_STREAMS} (probe value — TRT may auto-disable on linear graphs)")
759
+ except AttributeError:
760
+ pass
761
+
762
+ # Precision: TRT 11 reads every tensor type from the strongly-typed network
763
+ # (the ONNX Q/DQ nodes). The per-precision BuilderFlags (INT8/FP16/BF16/FP8),
764
+ # the INT8 calibrator (IInt8EntropyCalibrator2 + int8_calibrator +
765
+ # set_calibration_profile), and per-layer precision (layer.precision /
766
+ # set_output_type) were ALL removed in TRT 11 — there are no builder flags to
767
+ # set here. The INT8 W8A16 / FP8 E4M3 / NVFP4 path is selected purely by which
768
+ # *_qdt.onnx was produced by quantize_onnx.py.
769
+ print(" Precision: from ONNX Q/DQ nodes (strongly-typed; no builder flags)")
770
+
771
+ # Timing cache: speeds up rebuilds dramatically
772
+ timing_cache_path = os.path.join(os.path.dirname(engine_path), "timing.cache")
773
+ if os.path.exists(timing_cache_path):
774
+ with open(timing_cache_path, "rb") as f:
775
+ cache = config.create_timing_cache(f.read())
776
+ print(f" Timing cache: loaded ({os.path.getsize(timing_cache_path)} bytes)")
777
+ else:
778
+ cache = config.create_timing_cache(b"")
779
+ config.set_timing_cache(cache, ignore_mismatch=False)
780
+
781
+ # Create optimization profiles
782
+ for i, (max_b, max_s, opt_b, opt_s) in enumerate(PROFILES):
783
+ profile = builder.create_optimization_profile()
784
+ # RECTANGULAR_PROFILE: min == opt == max. TRT autotuner picks a
785
+ # single set of tactics for the exact (batch, seq) shape — no
786
+ # variable-batch search, no autotuner regression on sm_120.
787
+ # Trapezoid mode: min=(1,1) → opt → max. Lets TRT accept smaller
788
+ # real batches at runtime, but autotuner must cover the whole
789
+ # range and on consumer Blackwell that range produces broken
790
+ # kernels for the upper half of the batch dimension.
791
+ if DYNSEQ_MIN_SEQ is not None:
792
+ # Batch stays rectangular (the sm_120 batch-range codegen problem
793
+ # above is untouched); only seq becomes a range.
794
+ min_b, min_s = max_b, DYNSEQ_MIN_SEQ
795
+ elif RECTANGULAR_PROFILE:
796
+ min_b, min_s = max_b, max_s
797
+ else:
798
+ min_b, min_s = 1, 1
799
+ profile.set_shape("input_ids", (min_b, min_s), (opt_b, opt_s), (max_b, max_s))
800
+ profile.set_shape("attention_mask", (min_b, min_s), (opt_b, opt_s), (max_b, max_s))
801
+ # token_type_ids if present in the model
802
+ for j in range(network.num_inputs):
803
+ inp = network.get_input(j)
804
+ if inp.name == "token_type_ids":
805
+ profile.set_shape("token_type_ids", (min_b, min_s), (opt_b, opt_s), (max_b, max_s))
806
+ break
807
+ config.add_optimization_profile(profile)
808
+ shape_kind = "RECTANGULAR" if RECTANGULAR_PROFILE else "trapezoid"
809
+ print(f" Profile {i}: {shape_kind} {min_b}x{min_s} → {opt_b}x{opt_s} → {max_b}x{max_s}")
810
+
811
+ print(f" Building engine (this may take several minutes)...")
812
+ serialized = builder.build_serialized_network(network, config)
813
+ if serialized is None:
814
+ print("ERROR: Engine build failed", file=sys.stderr)
815
+ return False
816
+
817
+ os.makedirs(os.path.dirname(engine_path), exist_ok=True)
818
+ with open(engine_path, "wb") as f:
819
+ f.write(serialized)
820
+
821
+ # Save timing cache for future rebuilds
822
+ with open(timing_cache_path, "wb") as f:
823
+ f.write(cache.serialize())
824
+ print(f" Timing cache saved: {timing_cache_path}")
825
+
826
+ # Layer-info sidecar (for MHA fusion verification, autotuner tactic
827
+ # inspection). Deserialize the just-saved engine, dump full JSON of
828
+ # all layers via engine_inspector. Needs profiling_verbosity=DETAILED
829
+ # at build time (set above) for tactic names + dtypes to be present.
830
+ layers_json_path = engine_path.replace(".engine", ".layers.json")
831
+ try:
832
+ runtime = trt.Runtime(trt.Logger(trt.Logger.WARNING))
833
+ eng = runtime.deserialize_cuda_engine(serialized)
834
+ if eng is not None:
835
+ inspector = eng.create_engine_inspector()
836
+ layer_json = inspector.get_engine_information(trt.LayerInformationFormat.JSON)
837
+ with open(layers_json_path, "w", encoding="utf-8") as fj:
838
+ fj.write(layer_json)
839
+ n_layers = layer_json.count('"LayerType"')
840
+ n_int8 = layer_json.count('"Int8"')
841
+ n_fp8 = layer_json.count('"Fp8"') + layer_json.count('"FP8"')
842
+ n_bf16 = layer_json.count('"BFloat16"') + layer_json.count('"BF16"')
843
+ # Half and Float were missing from this verdict, so an all-FP32 engine and
844
+ # a fully-FP16 one printed the identical "Int8=0 BF16=0 FP8=0" line. That
845
+ # blind spot is how the FP16 lane shipped FP32 engines unnoticed — the one
846
+ # report that could have caught it did not look at the two types involved.
847
+ n_half = layer_json.count('"Half"')
848
+ n_float = layer_json.count('"Float"')
849
+ # TRT 11's Myelin names the fused kernel `_gemm_mha_v2_*`; the two older
850
+ # spellings never appear in a TRT 11 dump, so counting only them printed
851
+ # NOT DETECTED for every engine on 2026-09-11 - including all eleven
852
+ # XLM-R engines that carry 24 of these kernels each.
853
+ lj = layer_json.lower()
854
+ n_fmha = lj.count('fmha') + lj.count('fused_multi_head_attention') + lj.count('_gemm_mha')
855
+ print(f" Layer info: {layers_json_path}")
856
+ print(f" {n_layers} layers — Half={n_half} Float={n_float} "
857
+ f"Int8={n_int8} BF16={n_bf16} FP8={n_fp8}")
858
+ if n_half == 0 and n_int8 == 0 and n_bf16 == 0 and n_fp8 == 0 and n_float > 0:
859
+ print(" WARNING: engine is ENTIRELY FP32 — no reduced precision took "
860
+ "effect. TRT 11 reads precision from the ONNX types only.")
861
+ if n_fmha > 0:
862
+ print(f" MHA fusion: DETECTED ({n_fmha} fmha tactic refs)")
863
+ else:
864
+ print(f" MHA fusion: NOT DETECTED — consider ONNX-level attention export")
865
+ except Exception as e:
866
+ print(f" Layer-info dump SKIPPED: {e}")
867
+
868
+ return True
869
+
870
+
871
+ def main():
872
+ parser = argparse.ArgumentParser(description="Build TRT engine from ONNX")
873
+ parser.add_argument(
874
+ "--model-dir",
875
+ default="dist/models/multilingual-e5-small",
876
+ help="Path to model directory containing model.onnx",
877
+ )
878
+ parser.add_argument("--cuda-arch", default=None, help="CUDA arch (e.g. sm_120)")
879
+ parser.add_argument("--fp16", action="store_true", default=True, help="Enable FP16")
880
+ parser.add_argument("--int8", action="store_true", default=True, help="Enable INT8 mixed precision")
881
+ parser.add_argument("--no-int8", action="store_true", help="Disable INT8 (FP16 only)")
882
+ parser.add_argument("--fp8", action="store_true", help="Enable FP8 (E4M3) — Hopper/Blackwell only. Implies --no-int8.")
883
+ parser.add_argument("--bf16", action="store_true", help="Enable BF16 (FP32-range half-storage) — required for Gemma RMSNorm. Disables FP16/INT8/FP8.")
884
+ parser.add_argument("--per-layer-norm", action="store_true",
885
+ help="Per-layer precision: norm layers → BF16, rest → INT8. "
886
+ "Requires --int8. Bypasses trtexec (Python API only). "
887
+ "Experimental fix for Gemma RMSNorm NaN under INT8.")
888
+ parser.add_argument("--force", action="store_true", help="Rebuild even if engine exists")
889
+ parser.add_argument("--reset-timing-cache", action="store_true",
890
+ help="Delete existing timing.cache before build. Use when switching "
891
+ "from single-profile to multi-profile builds: the cached kernel "
892
+ "selection for profile 0 shape from a single-profile build is "
893
+ "suboptimal (693 emb/s) vs a fresh multi-profile build (3800 emb/s).")
894
+ parser.add_argument("--onnx", default=None, help="Override ONNX path (bypasses find_onnx priority order)")
895
+ parser.add_argument(
896
+ "--role", default="embedding", choices=["embedding", "ner", "reranker"],
897
+ help="Model role — selects optimization profile set. "
898
+ "ner: batch≤32, seq≤128 (doc chunks). "
899
+ "embedding: batch≤256, seq≤128 (default). "
900
+ "reranker: same as embedding.",
901
+ )
902
+ parser.add_argument("--model-id", default=None,
903
+ help="Model ID for engine filename (default: basename of --model-dir)")
904
+ parser.add_argument("--os-arch", default=None,
905
+ help="OS+arch tag for engine filename (win_x64/linux_x64/linux_arm64/mac_arm64). Auto-detected if omitted.")
906
+ parser.add_argument("--variant", default=None,
907
+ help="Length-aware bucket variant name (embed: s/m/l; relation: s/m/l/xl). "
908
+ "When set, collapses PROFILES to a rectangular (max_batch, max_seq) and "
909
+ "appends `-{variant}` to the engine filename. The shape is taken from "
910
+ "--variant-batch/--variant-seq when provided (config-driven, per-model "
911
+ "from semantic_config.bucket_variants), else falls back to the embed-only "
912
+ "BUCKET_VARIANT_PROFILES table. Enables cross-worker bucketed routing.")
913
+ parser.add_argument("--variant-batch", type=int, default=None,
914
+ help="Explicit rectangular batch for --variant (overrides BUCKET_VARIANT_PROFILES).")
915
+ parser.add_argument("--variant-seq", type=int, default=None,
916
+ help="Explicit rectangular seq for --variant (overrides BUCKET_VARIANT_PROFILES).")
917
+ parser.add_argument("--no-dynseq", action="store_true",
918
+ help="Bake a rectangular sequence dimension instead of the "
919
+ "bucket's dynamic range (BUCKET_VARIANT_DYNSEQ). Costs "
920
+ "about 10%% of embedding throughput; for A/B controls.")
921
+ args = parser.parse_args()
922
+
923
+ # Select profile set based on model role before any build function is called.
924
+ # build_with_trtexec and build_with_python_api both read the global PROFILES.
925
+ global PROFILES, DYNSEQ_MIN_SEQ
926
+ if args.role == "ner":
927
+ PROFILES = NER_PROFILES
928
+ elif args.role == "reranker":
929
+ PROFILES = RERANKER_PROFILES
930
+
931
+ # --variant takes precedence over the role-default PROFILES. Bucketed variants
932
+ # apply to embedding AND reranker (relation-CE length bucketing, 2026-07-10);
933
+ # rejected for `--role ner` (NER is single-shape). The shape is config-driven:
934
+ # --variant-batch/--variant-seq (forwarded by models/compile.cmd from the model's
935
+ # semantic_config.bucket_variants) win; else fall back to the embed-only table.
936
+ if args.variant is not None:
937
+ if args.role not in ("embedding", "reranker"):
938
+ print(
939
+ f"ERROR: --variant {args.variant!r} is incompatible with --role {args.role!r}; "
940
+ f"bucketed variants are for embedding/reranker only.",
941
+ file=sys.stderr,
942
+ )
943
+ sys.exit(1)
944
+ if args.variant_batch is not None and args.variant_seq is not None:
945
+ _vb, _vs = args.variant_batch, args.variant_seq
946
+ elif args.variant in BUCKET_VARIANT_PROFILES:
947
+ _vb, _vs = BUCKET_VARIANT_PROFILES[args.variant]
948
+ else:
949
+ print(
950
+ f"ERROR: --variant {args.variant!r} has no shape: pass --variant-batch/--variant-seq "
951
+ f"or use a known embed variant {list(BUCKET_VARIANT_PROFILES.keys())}.",
952
+ file=sys.stderr,
953
+ )
954
+ sys.exit(1)
955
+ PROFILES = [(_vb, _vs, _vb, _vs)]
956
+ print(f"[build_trt] --variant {args.variant} → rectangular ({_vb}, {_vs})", flush=True)
957
+
958
+ # Dynamic sequence for the embed grid. Keyed on the SHAPE, not the bucket
959
+ # name: relation-CE reuses s/m/l/xl at seq 64/128/256/320 and its opt
960
+ # points are not these. A shape that does not match the embed table
961
+ # stays rectangular.
962
+ _dyn = BUCKET_VARIANT_DYNSEQ.get(args.variant)
963
+ if _dyn and not args.no_dynseq and \
964
+ BUCKET_VARIANT_PROFILES.get(args.variant) == (_vb, _vs):
965
+ DYNSEQ_MIN_SEQ, _opt = _dyn
966
+ PROFILES = [(_vb, _vs, _vb, _opt)]
967
+ print(f"[build_trt] --variant {args.variant} → dynamic seq "
968
+ f"{DYNSEQ_MIN_SEQ}→{_opt}→{_vs} at batch {_vb}", flush=True)
969
+
970
+ # Dynamic-seq probe — applied last so it wins over both the rectangular
971
+ # --variant shape and the BUCKET_VARIANT_DYNSEQ table. This is the knob for
972
+ # sweeping a candidate grid; production builds get their shape from the
973
+ # table and leave it unset.
974
+ _dynseq = os.environ.get("DYNSEQ_OVERRIDE", "").strip()
975
+ if _dynseq:
976
+ try:
977
+ _db, _dmin, _dopt, _dmax = (int(x) for x in _dynseq.split(","))
978
+ PROFILES = [(_db, _dmax, _db, _dopt)]
979
+ DYNSEQ_MIN_SEQ = _dmin
980
+ print(
981
+ f"[build_trt] DYNSEQ probe: batch {_db} rectangular, seq {_dmin}→{_dopt}→{_dmax}",
982
+ flush=True,
983
+ )
984
+ except (ValueError, AttributeError) as _e:
985
+ print(f"[build_trt] WARN: bad DYNSEQ_OVERRIDE='{_dynseq}': {_e}", flush=True)
986
+
987
+ use_bf16 = args.bf16
988
+ use_fp8 = args.fp8 and not use_bf16
989
+ use_int8 = args.int8 and not args.no_int8 and not use_fp8 and not use_bf16
990
+ use_fp16 = args.fp16 and not use_bf16
991
+ use_per_layer_norm = args.per_layer_norm and use_int8 and not use_bf16
992
+ use_strongly_typed = False
993
+ cuda_arch = args.cuda_arch or get_cuda_arch()
994
+ if not cuda_arch:
995
+ print("ERROR: Cannot detect CUDA arch. Pass --cuda-arch sm_XXX", file=sys.stderr)
996
+ sys.exit(1)
997
+
998
+ # `--cuda-arch` names the FILE; TensorRT always builds for the GPU that is
999
+ # present. So the detected architecture is the ONLY one this machine may
1000
+ # produce, and a request for any other is refused rather than honoured with
1001
+ # a rename. There is no override: an engine carrying an architecture it was
1002
+ # not built for fails `deserializeEngine` on the real card with no fallback,
1003
+ # and it fails there, on a user's machine, not here. Every other arch is
1004
+ # built on a host that has it (Selectel VMs for sm_75/86/89).
1005
+ #
1006
+ # This is not hypothetical: dist/ held 30 engines across four models named
1007
+ # sm_75/sm_86/sm_89 that were byte-identical to their sm_120 twins.
1008
+ _detected = get_cuda_arch()
1009
+ if _detected and args.cuda_arch and args.cuda_arch != _detected:
1010
+ print(f"ERROR: --cuda-arch {args.cuda_arch} but this machine is "
1011
+ f"{_detected}. TensorRT cannot build for an absent architecture; "
1012
+ f"the engine would be a mislabelled {_detected} plan. Build it on "
1013
+ f"a {args.cuda_arch} host.", file=sys.stderr)
1014
+ sys.exit(2)
1015
+
1016
+ if args.onnx:
1017
+ onnx_path = args.onnx
1018
+ if not os.path.exists(onnx_path):
1019
+ print(f"ERROR: --onnx path not found: {onnx_path}", file=sys.stderr)
1020
+ sys.exit(1)
1021
+ else:
1022
+ # Mode-aware ONNX discovery: FP8 build → prefer model_fp8qdt.onnx;
1023
+ # INT8 → model_int8qdt.onnx; BF16 → plain model.onnx.
1024
+ # Without this, --fp8 mode would pick up model_int8qdt.onnx whose
1025
+ # Q/DQ nodes are INT8-typed, defeating the FP8 builder flag and
1026
+ # silently producing an INT8 engine.
1027
+ _discover_mode = "fp8" if use_fp8 else ("bf16" if use_bf16 else "int8")
1028
+ onnx_path = find_onnx(args.model_dir, mode=_discover_mode)
1029
+ if onnx_path is not None and use_fp8 and not onnx_is_fp8(onnx_path):
1030
+ # FP8 requested but no model_fp8qdt.onnx — find_onnx fell back
1031
+ # to INT8 Q/DQ ONNX. Per line 1124 logic this auto-enables
1032
+ # both --int8 and --fp8 builder flags, but TRT will only run
1033
+ # INT8 (no FP8 Q/DQ nodes in the file). The resulting engine
1034
+ # is INT8 disguised as FP8. Warn loudly so the user can run
1035
+ # `quantize_onnx.py --fp8` first.
1036
+ print(f"WARNING: --fp8 requested but {os.path.basename(onnx_path)} is INT8 Q/DQ.")
1037
+ print(f"WARNING: Resulting engine will be INT8 (no FP8 Tensor Cores).")
1038
+ print(f"WARNING: Run `scripts/quantize_onnx.py --fp8 --model-dir {args.model_dir}` first.")
1039
+ if not onnx_path:
1040
+ print(f"ERROR: ONNX model not found in {args.model_dir}", file=sys.stderr)
1041
+ sys.exit(1)
1042
+
1043
+ # ⭐ MAKE THE FP16 LANE ACTUALLY FP16.
1044
+ #
1045
+ # TRT 11 is STRONGLY-TYPED ONLY: the per-precision builder flags were removed and
1046
+ # precision is read entirely from the ONNX tensor types. `catalog.py` routes
1047
+ # rerankers and `trt_fp16_only` models here with `--no-int8` and labels the build
1048
+ # FP16, but nothing converted the graph — so every engine on this lane shipped as
1049
+ # FP32. Measured 2026-08-03 across the deployed set: relation-v1 Float=335 Half=0,
1050
+ # reranker-v1 Float=325 Half=0, denoise-v1 Float=331 Half=0 (its catalog entry even
1051
+ # says BF16). Only embed-v1 was genuinely quantized, because its ONNX carries Q/DQ
1052
+ # nodes and strong typing therefore has something to read.
1053
+ #
1054
+ # Converting and rebuilding: relation 20.74 -> 5.44 ms/chunk (3.81x), reranker
1055
+ # 21.14 -> 5.40 (3.91x), denoise 8.56 -> 3.60 (2.38x), each verified against the
1056
+ # previously deployed engine at cos >= 0.999995 with argmax fully preserved.
1057
+ # Engines halve on disk too. It is ~4x rather than the ~1.4x a DRAM argument
1058
+ # predicts because FP32 matmuls do not use the tensor cores at all.
1059
+ #
1060
+ # The tag drives it, as it always did — this only makes the flag mean its label.
1061
+ # Re-verify a converted model with:
1062
+ # models/_compile/tools/build_fp16_engine.py --stage verify --model <name>
1063
+ if not use_int8 and not use_fp8 and not use_bf16:
1064
+ try:
1065
+ sys.path.insert(0, os.path.join(
1066
+ os.path.dirname(os.path.dirname(os.path.dirname(
1067
+ os.path.abspath(__file__)))), "tools"))
1068
+ from onnx_fp16 import ensure_fp16_onnx
1069
+ onnx_path = ensure_fp16_onnx(onnx_path)
1070
+ except Exception as e: # noqa: BLE001 - never block a build on the conversion
1071
+ print(f"WARNING: FP16 ONNX conversion failed ({e}); "
1072
+ f"building FP32 from {os.path.basename(onnx_path)}")
1073
+
1074
+ model_id = args.model_id or os.path.basename(os.path.normpath(args.model_dir))
1075
+ if args.os_arch:
1076
+ os_arch = args.os_arch
1077
+ else:
1078
+ import platform as _platform
1079
+ _machine = _platform.machine().lower()
1080
+ _is_arm = _machine in ("arm64", "aarch64")
1081
+ if sys.platform == "win32":
1082
+ os_arch = "win_arm64" if _is_arm else "win_x64"
1083
+ elif sys.platform == "darwin":
1084
+ os_arch = "mac_arm64"
1085
+ else:
1086
+ os_arch = "linux_arm64" if _is_arm else "linux_x64"
1087
+ # Length-aware variant suffix slotted into filename BEFORE the runtime
1088
+ # tag — keeps the established `..._{os_arch}_trt{VER}_{cuda_arch}.engine`
1089
+ # cluster intact so existing CDN tooling continues to glob by suffix.
1090
+ # Layout: `{model_id}-{variant}_{os_arch}_trt{VER}_{cuda_arch}.engine`.
1091
+ variant_tag = f"-{args.variant}" if args.variant else ""
1092
+ rt_tag = _trt_runtime_tag()
1093
+ _refuse_trt_version_skew(rt_tag)
1094
+ engine_path = os.path.join(args.model_dir, f"{model_id}{variant_tag}_{os_arch}_{rt_tag}_{cuda_arch}.engine")
1095
+
1096
+ if os.path.exists(engine_path) and not args.force:
1097
+ size_mb = os.path.getsize(engine_path) / (1024 * 1024)
1098
+ print(f"Engine already exists: {engine_path} ({size_mb:.1f} MB)")
1099
+ print("Use --force to rebuild")
1100
+ sys.exit(0)
1101
+
1102
+ if args.reset_timing_cache:
1103
+ timing_cache_path = os.path.join(args.model_dir, "timing.cache")
1104
+ if os.path.exists(timing_cache_path):
1105
+ os.remove(timing_cache_path)
1106
+ print(f" Timing cache deleted: {timing_cache_path} (fresh kernel selection)")
1107
+
1108
+ # Explicit Q/DQ ONNX detected: override precision mode based on Q/DQ flavour.
1109
+ # INT8 Q/DQ path → STRONGLY_TYPED: prevents TRT's backward type-inference from propagating
1110
+ # INT8 from DequantizeLinear's input to the shared Q/DQ scale initializer.
1111
+ # ORT's quantize_static creates one scale initializer shared by both Q and DQ in each pair.
1112
+ # In weakly-typed mode this causes "[SCALE] has invalid precision Int8, ignored" and disables
1113
+ # W8A16 fusion (verified 363 warnings = 363 DQ nodes, TRT 10.16, sm_120).
1114
+ # With STRONGLY_TYPED, TRT reads precision from ONNX data_type; no builder flags needed.
1115
+ #
1116
+ # FP8 Q/DQ path → also STRONGLY_TYPED (corrected 2026-05-19): the prior
1117
+ # "FP8 STRONGLY_TYPED = 171 emb/s" datum was measured on a plain `model.onnx`
1118
+ # WITHOUT Q/DQ nodes — TRT fell through to the generic codepath. With a
1119
+ # real FP8 Q/DQ ONNX from ModelOpt, STRONGLY_TYPED reads FP8 precision +
1120
+ # BF16 scale initializers directly from the graph, avoiding the
1121
+ # weakly-typed validate-error trap: `bf16 precision has been set ... but
1122
+ # bf16 is not configured in the builder` (TRT 10.16 silently rejects
1123
+ # `config.set_flag(BF16)` when also FP8+INT8+FP16 are set, sm_120).
1124
+ # No precision builder flags are set in this mode — TRT honours the
1125
+ # ONNX types as-is.
1126
+ #
1127
+ # INT8 Q/DQ ONNX + --fp8 (legacy mixed path) → keep weakly-typed
1128
+ # FP16+INT8+FP8: meaningful only when caller mixes an INT8 Q/DQ ONNX with
1129
+ # --fp8 hint. Currently no production model hits this branch; preserved
1130
+ # for backward compatibility.
1131
+ if onnx_has_qdq(onnx_path):
1132
+ use_bf16 = False
1133
+ use_per_layer_norm = False
1134
+ if onnx_is_fp8(onnx_path):
1135
+ # FP8 Q/DQ ONNX — STRONGLY_TYPED reads everything from graph.
1136
+ use_fp16 = False
1137
+ use_int8 = False
1138
+ use_fp8 = False # builder flags suppressed; FP8 comes from Q/DQ nodes
1139
+ use_strongly_typed = True
1140
+ print(f"[PTQ] Explicit FP8 Q/DQ ONNX → STRONGLY_TYPED (FP8 Tensor Cores + BF16 scales from ONNX)")
1141
+ elif use_fp8:
1142
+ # INT8 Q/DQ ONNX + --fp8: weakly-typed mixed path (legacy).
1143
+ use_fp16 = True
1144
+ use_int8 = True
1145
+ use_strongly_typed = False
1146
+ print(f"[PTQ] INT8 Q/DQ ONNX + --fp8 → FP16+INT8+FP8 (kFP8 Tensor Cores for Q/DQ layers)")
1147
+ else:
1148
+ # INT8 Q/DQ ONNX, current production path.
1149
+ use_fp16 = False
1150
+ use_int8 = False
1151
+ use_strongly_typed = True
1152
+ print(f"[PTQ] Explicit Q/DQ ONNX — STRONGLY_TYPED (W8A16 path, no [SCALE] type-inference warnings)")
1153
+
1154
+ if use_strongly_typed:
1155
+ # Differentiate between INT8 Q/DQ (W8A16) and FP8 Q/DQ (E4M3+BF16).
1156
+ # `onnx_is_fp8` is filename-based and was already evaluated before
1157
+ # the flag-resolution block above.
1158
+ precision = "STRONGLY_TYPED+FP8" if onnx_is_fp8(onnx_path) else "STRONGLY_TYPED+W8A16"
1159
+ elif use_bf16:
1160
+ precision = "BF16"
1161
+ elif use_fp8:
1162
+ precision = "FP8+FP16"
1163
+ elif use_int8 and use_per_layer_norm:
1164
+ precision = "INT8+BF16-norm"
1165
+ elif use_int8:
1166
+ precision = "FP16+INT8"
1167
+ else:
1168
+ precision = "FP16"
1169
+ print(f"Building TRT engine: {cuda_arch} ({precision})")
1170
+ print(f" ONNX: {onnx_path}")
1171
+ print(f" Engine: {engine_path}")
1172
+ print()
1173
+
1174
+ ok = False
1175
+
1176
+ # Per-layer-norm mode requires Python API (trtexec has no per-layer precision CLI).
1177
+ # FP8 (weakly-typed kFP8+kFP16) and all other modes can use trtexec.
1178
+ trtexec = None
1179
+ if not use_per_layer_norm:
1180
+ trtexec = shutil.which("trtexec")
1181
+ if not trtexec:
1182
+ for p in [
1183
+ "/usr/bin/trtexec",
1184
+ "/usr/local/bin/trtexec",
1185
+ ]:
1186
+ if os.path.isfile(p) and os.access(p, os.X_OK):
1187
+ trtexec = p
1188
+ break
1189
+ if not trtexec:
1190
+ import glob
1191
+ for pattern in [
1192
+ "/usr/local/TensorRT-*/bin/trtexec",
1193
+ "/opt/tensorrt/bin/trtexec",
1194
+ "/usr/local/cuda/bin/trtexec",
1195
+ ]:
1196
+ matches = glob.glob(pattern)
1197
+ if matches:
1198
+ trtexec = matches[-1] # latest version
1199
+ break
1200
+
1201
+ if trtexec:
1202
+ print(f"Using trtexec: {trtexec}")
1203
+ ok = build_with_trtexec(onnx_path, engine_path, trtexec_bin=trtexec)
1204
+ else:
1205
+ print("trtexec not in PATH — using Python TensorRT API")
1206
+ ok = build_with_python_api(onnx_path, engine_path)
1207
+
1208
+ # TRT 11 has a SINGLE build path: strongly-typed, precision read from the
1209
+ # ONNX Q/DQ nodes. The TRT-10 fallback cascade (retry as weakly-typed
1210
+ # FP16+INT8 / BF16 / FP8 / calibrated-INT8) was removed along with those
1211
+ # builder flags + the calibrator — there is nothing weaker to fall back to.
1212
+ # If the strongly-typed build fails, it fails; the caller surfaces the TRT
1213
+ # error from the log above.
1214
+ if not ok or not os.path.exists(engine_path):
1215
+ print("ERROR: Engine build failed", file=sys.stderr)
1216
+ sys.exit(1)
1217
+
1218
+ size_mb = os.path.getsize(engine_path) / (1024 * 1024)
1219
+ print(f"\nSUCCESS: {engine_path} ({size_mb:.1f} MB)")
1220
+
1221
+
1222
+ if __name__ == "__main__":
1223
+ main()
_build-tools/go.ps1 ADDED
@@ -0,0 +1,59 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # go.ps1 - the shortest thing that can be typed on a rented VM.
2
+ #
3
+ # RDP clipboard and the legacy PowerShell console disagree about multi-line
4
+ # pastes: the first line executes, the rest lands as garbage or not at all. So
5
+ # the multi-line bootstrap invocation moves here, and the operator types ONE
6
+ # short line plus a token.
7
+ #
8
+ # $env:HF_TOKEN='hf_...'
9
+ # irm https://cdn.code-daemon.com/tools/go.ps1 | iex
10
+ #
11
+ # TOOLS_URL is baked in because this file already lives at that URL - if you can
12
+ # fetch this, that is the base you fetched it from.
13
+ $ErrorActionPreference = "Stop"
14
+ [Net.ServicePointManager]::SecurityProtocol = [Net.SecurityProtocolType]::Tls12
15
+ $ProgressPreference = "SilentlyContinue"
16
+
17
+ $base = "https://cdn.code-daemon.com/tools"
18
+ if (-not $env:TOOLS_URL) { $env:TOOLS_URL = $base }
19
+
20
+ if (-not $env:HF_TOKEN) {
21
+ Write-Host "HF_TOKEN is not set." -ForegroundColor Red
22
+ Write-Host "Set it first, then re-run:" -ForegroundColor Yellow
23
+ Write-Host " `$env:HF_TOKEN='hf_...'" -ForegroundColor Yellow
24
+ Write-Host " irm $base/go.ps1 | iex" -ForegroundColor Yellow
25
+ exit 1
26
+ }
27
+
28
+ Write-Host "[go] TOOLS_URL = $($env:TOOLS_URL)" -ForegroundColor Cyan
29
+
30
+ # Download and run AS A FILE, not `irm | iex`.
31
+ #
32
+ # `iex` compiles the fetched script inside the CURRENT scope, and bootstrap_win
33
+ # is large enough that PowerShell hits its call-depth ceiling partway through:
34
+ #
35
+ # The script failed due to call depth overflow.
36
+ #
37
+ # Ironically this file is itself usually run through `iex`, which is fine - it
38
+ # is small. The child process below starts with a fresh stack, so the build gets
39
+ # the whole depth budget to itself, Ctrl-C reaches the build rather than this
40
+ # wrapper, and the exit code comes back directly instead of through a pipeline.
41
+ $boot = Join-Path $env:SystemDrive "uc-bootstrap_win.ps1"
42
+ $log = Join-Path $env:SystemDrive "uc-build.log"
43
+
44
+ Invoke-WebRequest -Uri "$($env:TOOLS_URL)/bootstrap_win.ps1" -OutFile $boot -UseBasicParsing
45
+ Write-Host "[go] log: $log" -ForegroundColor DarkGray
46
+ Write-Host "[go] disconnect with the X, do NOT Sign out" -ForegroundColor Yellow
47
+
48
+ # Tee, not Start-Transcript: a transcript wraps every write and adds frames to
49
+ # the same stack the overflow came from.
50
+ # `2>&1` turns the child's stderr into error OBJECTS in this pipeline, and with
51
+ # ErrorActionPreference=Stop the first one is fatal HERE - so pip writing a
52
+ # routine notice kills the wrapper while the build itself is fine. The symptom
53
+ # is an empty "NativeCommandError" naming this line and nothing else.
54
+ #
55
+ # Continue for the duration of the build: the child's own exit code is the real
56
+ # verdict, and it is checked below.
57
+ $ErrorActionPreference = "Continue"
58
+ & powershell.exe -NoProfile -ExecutionPolicy Bypass -File $boot 2>&1 | Tee-Object -FilePath $log
59
+ exit $LASTEXITCODE
_build-tools/onnx_fp16.py ADDED
@@ -0,0 +1,131 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env python3
2
+ """Convert an ONNX graph to FP16 — the recipe that survived four traps.
3
+
4
+ TRT 11 is STRONGLY-TYPED ONLY: the `--fp16`/`--bf16`/`--int8` builder flags were
5
+ removed and precision is read entirely from the ONNX tensor types. So "build an FP16
6
+ engine" means "hand TensorRT an FP16 graph", and this is where that happens. The
7
+ compile pipeline's FP16 lane called itself FP16 for a long time while shipping FP32
8
+ engines, because nothing did this step.
9
+
10
+ Measured worth, 2026-08-03 (each verified against the previously deployed FP32 engine
11
+ by `build_fp16_engine.py --stage verify`, which gates on logit scale and p_rel, not
12
+ just cosine):
13
+
14
+ code-daemon-relation-v1 20.74 -> 5.44 ms/chunk 3.81x
15
+ code-daemon-reranker-v1 21.14 -> 5.40 ms/chunk 3.91x
16
+ code-daemon-denoise-v1 8.56 -> 3.60 ms/chunk 2.38x
17
+
18
+ Engines also halve on disk. The gain is bigger than a DRAM argument predicts because
19
+ FP32 matmuls do not use the tensor cores at all — the whole encoder was on the slow
20
+ path, not merely reading twice the bytes.
21
+ """
22
+
23
+ import os
24
+
25
+ import numpy as np
26
+ import onnx
27
+ from onnx import numpy_helper
28
+
29
+ FP16_MAX = 65504.0
30
+
31
+
32
+ def convert_to_fp16(src_path, dst_path, verbose=True):
33
+ """Write an FP16 copy of `src_path` to `dst_path`. Returns dst_path.
34
+
35
+ Four things here are load-bearing; each one cost a wrong engine to find:
36
+
37
+ 1. CLAMP THE OUT-OF-RANGE CONSTANTS FIRST. Attention masks are stored as
38
+ -3.4e38, which is +inf in fp16. Everything else in these graphs is tiny
39
+ (real weights peak around 16 against a 65504 ceiling), so this is usually
40
+ the only tensor that needs it — but it needs it explicitly, not left to a
41
+ library default.
42
+ 2. RETYPE THE ORIGINAL `Cast` NODES. onnxconverter_common rewrites tensors but
43
+ not a Cast's `to` attribute, so an existing `Cast(int64 -> FLOAT)` keeps
44
+ emitting FP32 into now-Half consumers and TRT refuses the graph outright:
45
+ "SUB must have same input types. But they are of types Half and Float".
46
+ 3. USE FP16'S REAL LIMITS. The library defaults to `min_positive_val=1e-7` and
47
+ clamps small magnitudes UP to it instead of letting them underflow to zero.
48
+ 4. SAVE ONE FILE. `save_as_external_data` corrupted exactly one initializer of
49
+ 204 — a (384,384) weight reloading at |max| 24144 instead of 0.669. The
50
+ in-memory graph was clean; only the saved pair was wrong. FP16 weights fit
51
+ inside protobuf's 2 GB, so the sidecar buys nothing and costs correctness.
52
+
53
+ The weight audit at the end is not paranoia: it is the check that would have
54
+ caught #4 on the first build instead of the fifth.
55
+ """
56
+ from onnxconverter_common import float16 as f16
57
+
58
+ model = onnx.load(src_path)
59
+
60
+ clamped = 0
61
+ for init in model.graph.initializer:
62
+ if init.data_type != onnx.TensorProto.FLOAT:
63
+ continue
64
+ arr = numpy_helper.to_array(init)
65
+ if arr.size and float(np.abs(arr).max()) > FP16_MAX:
66
+ init.CopyFrom(numpy_helper.from_array(
67
+ np.clip(arr, -FP16_MAX, FP16_MAX).astype(np.float32), init.name))
68
+ clamped += 1
69
+
70
+ original_casts = {n.name for n in model.graph.node if n.op_type == "Cast"}
71
+ # Snapshot BEFORE converting: the converter mutates the model in place, so a
72
+ # later comparison against `model` would compare the result with itself.
73
+ fp32_weights = {i.name: numpy_helper.to_array(i).astype(np.float64)
74
+ for i in model.graph.initializer
75
+ if i.data_type == onnx.TensorProto.FLOAT}
76
+
77
+ converted = f16.convert_float_to_float16(
78
+ model, keep_io_types=True, disable_shape_infer=True,
79
+ min_positive_val=float(np.finfo(np.float16).smallest_subnormal),
80
+ max_finite_val=FP16_MAX)
81
+
82
+ graph_outputs = {o.name for o in converted.graph.output}
83
+ retyped = 0
84
+ for node in converted.graph.node:
85
+ if node.op_type != "Cast" or node.name not in original_casts:
86
+ continue
87
+ if any(o in graph_outputs for o in node.output):
88
+ continue
89
+ for attr in node.attribute:
90
+ if attr.name == "to" and attr.i == onnx.TensorProto.FLOAT:
91
+ attr.i = onnx.TensorProto.FLOAT16
92
+ retyped += 1
93
+
94
+ repaired = 0
95
+ for init in converted.graph.initializer:
96
+ if init.data_type != onnx.TensorProto.FLOAT16:
97
+ continue
98
+ ref = fp32_weights.get(init.name)
99
+ if ref is None or ref.size == 0:
100
+ continue
101
+ got = numpy_helper.to_array(init).astype(np.float64)
102
+ if ref.shape != got.shape:
103
+ continue
104
+ n_ref = np.linalg.norm(ref)
105
+ if n_ref < 1e-30:
106
+ continue
107
+ if abs(float(np.linalg.norm(got) / n_ref) - 1.0) > 0.01:
108
+ init.CopyFrom(numpy_helper.from_array(
109
+ np.clip(ref, -FP16_MAX, FP16_MAX).astype(np.float16), init.name))
110
+ repaired += 1
111
+
112
+ onnx.save(converted, dst_path) # single file — see #4 above
113
+
114
+ if verbose:
115
+ n16 = sum(1 for i in converted.graph.initializer
116
+ if i.data_type == onnx.TensorProto.FLOAT16)
117
+ print(f" FP16 ONNX: {os.path.basename(dst_path)} "
118
+ f"(fp16_inits={n16} clamped={clamped} casts_retyped={retyped} "
119
+ f"weights_repaired={repaired})")
120
+ return dst_path
121
+
122
+
123
+ def ensure_fp16_onnx(src_path, verbose=True):
124
+ """Return an FP16 sibling of `src_path`, converting once and caching by mtime."""
125
+ base, ext = os.path.splitext(src_path)
126
+ dst = f"{base}_fp16{ext}"
127
+ if os.path.exists(dst) and os.path.getmtime(dst) >= os.path.getmtime(src_path):
128
+ if verbose:
129
+ print(f" FP16 ONNX: reusing {os.path.basename(dst)}")
130
+ return dst
131
+ return convert_to_fp16(src_path, dst, verbose=verbose)
_build-tools/quantize_onnx.py ADDED
@@ -0,0 +1,1359 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env python3
2
+ """PTQ quantization for ONNX embedding models — produces TRT-compatible INT8 Q/DQ ONNX.
3
+
4
+ Solves Gemma-family NaN problem: implicit TRT INT8/FP8 quantization runs RMSNorm in low
5
+ precision → NaN. Explicit Q/DQ nodes place quantization boundaries only around MatMul/Gemm:
6
+
7
+ Float → [QuantizeLinear] → INT8 → MatMul → [DequantizeLinear] → Float
8
+ RMSNorm (outside Q/DQ brackets) → stays in BF16/float → no NaN
9
+
10
+ TRT reads the Q/DQ nodes directly — no calibrator, no per-layer hint system.
11
+ Expected: ~900 emb/s vs 480 emb/s BF16-only.
12
+
13
+ Usage:
14
+ python scripts/quantize_onnx.py --model-dir PATH
15
+ python scripts/quantize_onnx.py --model-dir PATH --calib-db db1.db db2.db
16
+ python scripts/quantize_onnx.py --model-dir PATH --calib-dir PATH\\ultracode.zig\\projects
17
+
18
+ Calibration data is pulled from UltraCode graph.db files (entities raw_content + names).
19
+ Auto-detects UltraCode projects dir if --calib-db / --calib-dir are omitted.
20
+
21
+ Output: {model_dir}/onnx/model_int8qdt.onnx
22
+ """
23
+
24
+ import argparse
25
+ import os
26
+ import platform
27
+ import random
28
+ import sqlite3
29
+ import subprocess
30
+ import sys
31
+
32
+ # ─── Experimental switches ───────────────────────────────────────────────────
33
+ # 2026-05-19: First FP8 production build showed -21 % vs INT8 (3584 vs 4541
34
+ # emb/s). Root cause: ModelOpt's default `disable_mha_qdq=True` keeps all MHA
35
+ # inner BMMs in BF16. For FP8 path this is too conservative — INT8 STRONGLY_TYPED
36
+ # does NOT disable MHA and wins. Flip this to True to let MHA inner BMMs also
37
+ # go through FP8 Q/DQ. RISK: 2026-04-28 NaN was on Gemma softmax/RMSNorm under
38
+ # implicit FP8; with explicit Q/DQ around BMMs only (softmax stays in BF16 via
39
+ # high_precision_dtype), the NaN path is closed. Validate empirically via the
40
+ # first-batch smoke check below before shipping. Hardcoded per
41
+ # `feedback_hardcode_over_env_var` — flip a const, rebuild, measure.
42
+ EXPERIMENTAL_QUANTIZE_MHA_FP8 = True
43
+ import warnings
44
+
45
+ if hasattr(sys.stdout, "reconfigure"):
46
+ sys.stdout.reconfigure(encoding="utf-8", errors="replace")
47
+ if hasattr(sys.stderr, "reconfigure"):
48
+ sys.stderr.reconfigure(encoding="utf-8", errors="replace")
49
+
50
+ warnings.filterwarnings("ignore", category=DeprecationWarning)
51
+ warnings.filterwarnings("ignore", message=".*onnxruntime.*", category=UserWarning)
52
+
53
+
54
+ # ─── CUDA DLL path fix + auto-install (Windows) ──────────────────────────────
55
+
56
+ def _detect_torch_cuda_major() -> "str | None":
57
+ """PyTorch's CUDA major ('12', '13', …), or None on a CPU build.
58
+
59
+ PyTorch is installed first in every pipeline that reaches this script
60
+ (training needs it), so its CUDA version is the source of truth for what the
61
+ host driver supports. ONNX Runtime should be matched to THAT, not the other
62
+ way round.
63
+ """
64
+ try:
65
+ import torch
66
+ ver = getattr(torch, "version", None)
67
+ cuda = getattr(ver, "cuda", None) if ver is not None else None
68
+ return cuda.split(".")[0] if cuda else None
69
+ except Exception:
70
+ return None
71
+
72
+
73
+ def _detect_ort_cuda_suffix_raw() -> str:
74
+ """Read onnxruntime-gpu's declared requirements to find its CUDA channel."""
75
+ try:
76
+ import importlib.metadata
77
+ import re
78
+ for pkg_name in ("onnxruntime-gpu", "onnxruntime_gpu"):
79
+ try:
80
+ reqs = importlib.metadata.requires(pkg_name) or []
81
+ for req in reqs:
82
+ m = re.search(r"nvidia-cuda-runtime-cu(\d+)", req)
83
+ if m:
84
+ return m.group(1)
85
+ except importlib.metadata.PackageNotFoundError:
86
+ continue
87
+ except Exception:
88
+ pass
89
+ return ""
90
+
91
+
92
+ def _ensure_ort_matches_torch_cuda() -> None:
93
+ """Reinstall onnxruntime-gpu on the channel that matches PyTorch's CUDA.
94
+
95
+ On Blackwell (sm_120) PyTorch is cu130. A mismatched cu12 ORT still loads
96
+ through preload_dlls, but the TensorRT execution provider fails to register
97
+ and CUDA falls back to a compatibility layer — calibration then runs 15-30%
98
+ slower on the very path that PTQ spends all its time in.
99
+ """
100
+ torch_cu = _detect_torch_cuda_major()
101
+ ort_cu = _detect_ort_cuda_suffix_raw()
102
+ if not torch_cu or not ort_cu or torch_cu == ort_cu:
103
+ return
104
+ print(f" [cuda-ep] PyTorch is cu{torch_cu} but ORT GPU is cu{ort_cu} — "
105
+ f"switching ORT to the matching channel")
106
+ cmd = [sys.executable, "-m", "pip", "install", "--quiet", "--upgrade",
107
+ "onnxruntime-gpu"]
108
+ if torch_cu == "13":
109
+ # cu13 ORT wheels are not on PyPI; they live on the ONNX Runtime feed.
110
+ cmd += ["--extra-index-url",
111
+ "https://aiinfra.pkgs.visualstudio.com/PublicPackages/"
112
+ "_packaging/onnxruntime-cuda-13/pypi/simple/"]
113
+ try:
114
+ result = subprocess.run(cmd, capture_output=True, text=True)
115
+ if result.returncode == 0:
116
+ print(f" [cuda-ep] ORT GPU re-installed for cu{torch_cu}")
117
+ else:
118
+ print(f" [cuda-ep] WARN: re-install failed: {result.stderr[:300]}")
119
+ except Exception as e:
120
+ print(f" [cuda-ep] WARN: re-install attempt errored: {e}")
121
+
122
+
123
+ def _detect_ort_cuda_suffix() -> str:
124
+ """The CUDA pip-package suffix to use for every nvidia-* package."""
125
+ _ensure_ort_matches_torch_cuda()
126
+ return _detect_ort_cuda_suffix_raw() or "12"
127
+
128
+
129
+ def _cuda_ep_packages(cu: str) -> "list[tuple[str, str, str]]":
130
+ """(pip package, nvidia subdirectory, sentinel DLL) for one CUDA suffix.
131
+
132
+ NVIDIA changed the naming convention at CUDA 13:
133
+ cu12 and earlier nvidia-cufft-cu12, nvidia-cublas-cu12, ...
134
+ cu13 and later nvidia-cufft, nvidia-cublas, ...
135
+ The suffixed variants are deprecated from 13 on, so asking for
136
+ `nvidia-cufft-cu13` on a cu13 host installs nothing and the DLL search then
137
+ silently falls through to the CPU provider.
138
+
139
+ DLL filenames follow the CUDA major, except cuFFT whose API version lags by
140
+ one (cu13 ships cufft64_12.dll).
141
+ """
142
+ cufft_api = str(int(cu) - 1)
143
+ if int(cu) >= 13:
144
+ return [
145
+ ("nvidia-cufft", "cufft", f"cufft64_{cufft_api}.dll"),
146
+ ("nvidia-cublas", "cublas", f"cublas64_{cu}.dll"),
147
+ ("nvidia-cuda-runtime", "cuda_runtime", f"cudart64_{cu}.dll"),
148
+ ]
149
+ return [
150
+ (f"nvidia-cufft-cu{cu}", "cufft", f"cufft64_{cufft_api}.dll"),
151
+ (f"nvidia-cublas-cu{cu}", "cublas", f"cublas64_{cu}.dll"),
152
+ (f"nvidia-cuda-runtime-cu{cu}", "cuda_runtime", f"cudart64_{cu}.dll"),
153
+ ]
154
+
155
+
156
+ def _collect_nvidia_bin_dirs() -> list[str]:
157
+ """Return all site-packages/nvidia/*/bin dirs + CUDA Toolkit bin (if present)."""
158
+ import site
159
+ dirs: list[str] = []
160
+ for sp in site.getsitepackages():
161
+ nvidia_root = os.path.join(sp, "nvidia")
162
+ if not os.path.isdir(nvidia_root):
163
+ continue
164
+ for pkg in os.listdir(nvidia_root):
165
+ bin_dir = os.path.join(nvidia_root, pkg, "bin")
166
+ if os.path.isdir(bin_dir):
167
+ dirs.append(bin_dir)
168
+ # Scan the toolkit root instead of testing a hardcoded version list: that
169
+ # list stopped at 12.9, so a CUDA 13 host — every Blackwell box — found no
170
+ # toolkit at all and fell back to whatever DLLs happened to be on PATH.
171
+ toolkit_root = os.path.join(os.environ.get("ProgramFiles", ""), "NVIDIA GPU Computing Toolkit", "CUDA")
172
+ if os.path.isdir(toolkit_root):
173
+ versions = []
174
+ for name in os.listdir(toolkit_root):
175
+ if not name.startswith("v"):
176
+ continue
177
+ try:
178
+ versions.append((tuple(int(p) for p in name[1:].split(".")), name))
179
+ except ValueError:
180
+ continue
181
+ for _key, name in sorted(versions, reverse=True):
182
+ cuda_bin = os.path.join(toolkit_root, name, "bin")
183
+ if os.path.isdir(cuda_bin):
184
+ dirs.append(cuda_bin)
185
+ break
186
+ cuda_path = os.environ.get("CUDA_PATH")
187
+ if cuda_path and os.path.isdir(os.path.join(cuda_path, "bin")):
188
+ dirs.append(os.path.join(cuda_path, "bin"))
189
+ return dirs
190
+
191
+
192
+ def _dll_exists(dll_name: str, search_dirs: list[str]) -> bool:
193
+ for d in search_dirs:
194
+ if os.path.isfile(os.path.join(d, dll_name)):
195
+ return True
196
+ return False
197
+
198
+
199
+ def _setup_cuda_ep() -> None:
200
+ """Ensure ORT CUDA EP DLLs are installed and on PATH (Windows only).
201
+
202
+ 1. Auto-detects which CUDA suffix (cu12/cu13/…) onnxruntime-gpu was built against.
203
+ 2. Scans existing nvidia pip-package bin dirs.
204
+ 3. Checks sentinel DLLs; pip-installs any missing packages.
205
+ 4. Rescans after install and prepends all bin dirs to PATH.
206
+ """
207
+ if platform.system() != "Windows":
208
+ return
209
+
210
+ cu = _detect_ort_cuda_suffix()
211
+ pkgs = _cuda_ep_packages(cu)
212
+ dirs = _collect_nvidia_bin_dirs()
213
+
214
+ missing_pkgs = [pip_pkg for pip_pkg, _, dll in pkgs if not _dll_exists(dll, dirs)]
215
+
216
+ if missing_pkgs:
217
+ print(f" [cuda-ep] ORT built against CUDA cu{cu}. "
218
+ f"Installing: {', '.join(missing_pkgs)}")
219
+ result = subprocess.run(
220
+ [sys.executable, "-m", "pip", "install", "--quiet"] + missing_pkgs,
221
+ capture_output=True, text=True,
222
+ )
223
+ if result.returncode != 0:
224
+ print(f" [cuda-ep] WARNING: pip install failed:\n{result.stderr[:400]}")
225
+ else:
226
+ print(f" [cuda-ep] Installed: {', '.join(missing_pkgs)}")
227
+ dirs = _collect_nvidia_bin_dirs() # rescan after install
228
+
229
+ # Verify
230
+ still_missing = [dll for _, _, dll in pkgs if not _dll_exists(dll, dirs)]
231
+ if still_missing:
232
+ print(f" [cuda-ep] WARNING: DLLs still missing after install: {still_missing}")
233
+ else:
234
+ print(f" [cuda-ep] OK (cu{cu}): {', '.join(dll for _, _, dll in pkgs)}")
235
+
236
+ # Prepend all bin dirs to PATH (must happen before `import onnxruntime`)
237
+ path_env = os.environ.get("PATH", "")
238
+ new_dirs = [d for d in dirs if d not in path_env]
239
+ if new_dirs:
240
+ os.environ["PATH"] = os.pathsep.join(new_dirs) + os.pathsep + path_env
241
+
242
+
243
+ _setup_cuda_ep()
244
+
245
+
246
+ # ─── Calibration data ────────────────────────────────────────────────────────
247
+
248
+ def _default_projects_dir():
249
+ if platform.system() == "Windows":
250
+ base = os.environ.get("LOCALAPPDATA", os.path.expanduser("~"))
251
+ elif platform.system() == "Darwin":
252
+ base = os.path.expanduser("~/Library/Application Support")
253
+ else:
254
+ base = os.environ.get("XDG_DATA_HOME", os.path.expanduser("~/.local/share"))
255
+ return os.path.join(base, "ultracode.zig", "projects")
256
+
257
+
258
+ def find_calib_dbs(projects_dir):
259
+ """Scan UltraCode projects dir for all graph.db files."""
260
+ dbs = []
261
+ if not os.path.isdir(projects_dir):
262
+ return dbs
263
+ for entry in os.scandir(projects_dir):
264
+ if entry.is_dir():
265
+ db = os.path.join(entry.path, "graph.db")
266
+ if os.path.exists(db):
267
+ dbs.append(db)
268
+ return sorted(dbs)
269
+
270
+
271
+ def _read_file_chunk(path, offset, length=400):
272
+ """Read a slice of a source file, returning clean text or None."""
273
+ try:
274
+ with open(path, "r", encoding="utf-8", errors="replace") as f:
275
+ f.seek(offset)
276
+ chunk = f.read(length).strip()
277
+ return chunk if len(chunk) >= 10 else None
278
+ except Exception:
279
+ return None
280
+
281
+
282
+ def collect_texts(db_paths, per_db=80, min_len=10, max_len=400):
283
+ """Collect calibration texts from UltraCode graph.db files.
284
+
285
+ Strategy (in order of richness):
286
+ 1. Entity names — always present, covers short-token distribution
287
+ (function/class/variable names, 2-15 tokens each)
288
+ 2. Source file chunks — read via file_path column, covers longer
289
+ code blocks (50-128 tokens). Skipped if file not on disk.
290
+
291
+ Deliberately avoids metadata BLOB (CBOR-encoded, requires cbor2)
292
+ and raw_content (column not present in current schema).
293
+ """
294
+ texts = []
295
+ for db_path in db_paths:
296
+ try:
297
+ con = sqlite3.connect(f"file:{db_path}?mode=ro", uri=True,
298
+ check_same_thread=False)
299
+
300
+ # 1. Entity names (short texts — always available)
301
+ rows = con.execute(
302
+ "SELECT name FROM entities "
303
+ "WHERE name IS NOT NULL AND length(name) BETWEEN 5 AND 120 "
304
+ "ORDER BY RANDOM() LIMIT ?",
305
+ (per_db // 2,)
306
+ ).fetchall()
307
+ texts += [r[0] for r in rows]
308
+
309
+ # 2. Source file chunks (longer texts — read from disk via file_path)
310
+ file_rows = con.execute(
311
+ "SELECT DISTINCT file_path, size FROM entities "
312
+ "WHERE file_path IS NOT NULL AND size > 200 "
313
+ "ORDER BY RANDOM() LIMIT ?",
314
+ (per_db,)
315
+ ).fetchall()
316
+ file_chunks_added = 0
317
+ for (fpath, fsize) in file_rows:
318
+ if file_chunks_added >= per_db // 2:
319
+ break
320
+ if not fpath or not os.path.exists(fpath):
321
+ continue
322
+ # Sample a random offset within the file (avoid last 400 bytes)
323
+ safe_size = max(0, (fsize or 0) - max_len)
324
+ offset = random.randint(0, safe_size) if safe_size > 0 else 0
325
+ chunk = _read_file_chunk(fpath, offset, max_len)
326
+ if chunk and min_len <= len(chunk) <= max_len * 2:
327
+ texts.append(chunk[:max_len])
328
+ file_chunks_added += 1
329
+
330
+ con.close()
331
+ except Exception as e:
332
+ print(f" WARN: skipping {db_path}: {e}")
333
+ random.shuffle(texts)
334
+ return texts
335
+
336
+
337
+ # ─── Tokenizer ───────────────────────────────────────────────────────────────
338
+
339
+ def load_tokenizer(model_dir):
340
+ """Load HuggingFace tokenizer. Tries transformers first, falls back to tokenizers."""
341
+ try:
342
+ from transformers import AutoTokenizer
343
+ tok = AutoTokenizer.from_pretrained(model_dir, local_files_only=True)
344
+ # Gemma and similar models don't define pad_token (SentencePiece without <pad>).
345
+ # Use eos_token as pad — semantically neutral at padding positions for calibration.
346
+ if tok.pad_token is None:
347
+ tok.pad_token = tok.eos_token
348
+ print(" tokenizer backend: transformers")
349
+ return ("transformers", tok)
350
+ except Exception as e:
351
+ print(f" transformers failed ({e}), trying tokenizers library")
352
+
353
+ tok_path = os.path.join(model_dir, "tokenizer.json")
354
+ if not os.path.exists(tok_path):
355
+ raise FileNotFoundError(
356
+ f"tokenizer.json not found in {model_dir}. "
357
+ "Install transformers or provide tokenizer.json."
358
+ )
359
+ from tokenizers import Tokenizer
360
+ tok = Tokenizer.from_file(tok_path)
361
+ print(" tokenizer backend: tokenizers (raw)")
362
+ return ("tokenizers_raw", tok)
363
+
364
+
365
+ def tokenize(tok_tuple, texts, max_seq):
366
+ """Tokenize list of texts -> (input_ids, attention_mask) as numpy int64."""
367
+ import numpy as np
368
+ kind, tok = tok_tuple
369
+ if kind == "transformers":
370
+ # Gemma / LLaMA-family tokenizers don't define pad_token in tokenizer.json.
371
+ # add_special_tokens updates both the Python wrapper and the Rust fast-tokenizer
372
+ # backend — plain attribute assignment only sets the Python side and may be
373
+ # ignored by _get_padding_truncation_strategies when the fast tokenizer checks
374
+ # its own registry. Reuse eos_token when present; fall back to a literal string
375
+ # so the assignment is never a no-op (e.g. when eos_token is also None).
376
+ if tok.pad_token is None:
377
+ pad_candidate = tok.eos_token or tok.bos_token or "<pad>"
378
+ tok.add_special_tokens({"pad_token": pad_candidate})
379
+ enc = tok(texts, padding="max_length", truncation=True,
380
+ max_length=max_seq, return_tensors="np")
381
+ return enc["input_ids"].astype(np.int64), enc["attention_mask"].astype(np.int64)
382
+
383
+ # tokenizers_raw: encode_batch + manual padding
384
+ encs = tok.encode_batch(texts)
385
+ max_len = min(max(len(e.ids) for e in encs), max_seq)
386
+ pad_id = tok.token_to_id("[PAD]") or tok.token_to_id("<pad>") or 0
387
+ ids, masks = [], []
388
+ for e in encs:
389
+ seq = e.ids[:max_seq]
390
+ mask = e.attention_mask[:max_seq]
391
+ pad = max_len - len(seq)
392
+ ids.append(seq + [pad_id] * pad)
393
+ masks.append(mask + [0] * pad)
394
+ return np.array(ids, dtype=np.int64), np.array(masks, dtype=np.int64)
395
+
396
+
397
+ # ─── ONNX helpers ────────────────────────────────────────────────────────────
398
+
399
+ def get_onnx_input_names(onnx_path):
400
+ """Read input tensor names from ONNX graph (without loading weights)."""
401
+ try:
402
+ import onnx
403
+ model = onnx.load(onnx_path, load_external_data=False)
404
+ return [inp.name for inp in model.graph.input]
405
+ except Exception:
406
+ return ["input_ids", "attention_mask"]
407
+
408
+
409
+ def find_onnx(model_dir, onnx_name="model.onnx"):
410
+ """Find source ONNX in model_dir, prioritising onnx/ subdirectory.
411
+
412
+ `onnx_name` allows callers to point at a non-default filename, e.g.
413
+ `model_static.onnx` for the TRT INT8 MHA fusion path that requires
414
+ a static-shape source (see .autodoc/archive/ner.md). External-data
415
+ sidecar (e.g. model_static.onnx_data) is expected to sit alongside.
416
+ """
417
+ candidates = [
418
+ os.path.join(model_dir, "onnx", onnx_name),
419
+ os.path.join(model_dir, onnx_name),
420
+ ]
421
+ for p in candidates:
422
+ if os.path.exists(p):
423
+ return p
424
+ return None
425
+
426
+
427
+ def get_onnx_vocab_size(onnx_path):
428
+ """Read embedding vocab size from ONNX proto without loading external data.
429
+
430
+ Needed to clamp calibration token IDs when HF tokenizer vocab > ONNX
431
+ embedding table (e.g. Qwen3 tokenizer=151936 vs ONNX table=151669).
432
+ Dims are stored inline in proto even when weights are external.
433
+ """
434
+ try:
435
+ import onnx
436
+ model = onnx.load(onnx_path, load_external_data=False)
437
+ for init in model.graph.initializer:
438
+ name_l = init.name.lower()
439
+ if (("embed_token" in name_l or "word_embed" in name_l or
440
+ ("embedding" in name_l and "weight" in name_l))
441
+ and len(init.dims) == 2):
442
+ return int(init.dims[0])
443
+ except Exception:
444
+ pass
445
+ return None
446
+
447
+
448
+ # ─── CalibrationDataReader ───────────────────────────────────────────────────
449
+
450
+ class CodeCalibrationReader:
451
+ """ORT CalibrationDataReader backed by UltraCode-indexed code entities.
452
+
453
+ Feeds one text at a time (batch_size=1) to ensure stable activation
454
+ statistics across the full calibration set without memory pressure.
455
+ """
456
+
457
+ def __init__(self, texts, tok_tuple, input_names, max_seq, max_token_id=None):
458
+ self._texts = texts
459
+ self._tok = tok_tuple
460
+ self._input_names = input_names
461
+ self._max_seq = max_seq
462
+ self._max_token_id = max_token_id # clamp OOB IDs (tokenizer vocab > ONNX embed table)
463
+ self._idx = 0
464
+ self._total = len(texts)
465
+
466
+ def get_next(self):
467
+ if self._idx >= self._total:
468
+ return None
469
+ text = self._texts[self._idx]
470
+ self._idx += 1
471
+ if self._idx % 50 == 0 or self._idx == self._total:
472
+ print(f" calibrating {self._idx}/{self._total}...", end="\r")
473
+ ids, masks = tokenize(self._tok, [text], self._max_seq)
474
+ if self._max_token_id is not None:
475
+ import numpy as np
476
+ ids = np.clip(ids, 0, self._max_token_id)
477
+ data = {}
478
+ for name in self._input_names:
479
+ if "attention" in name.lower() or "mask" in name.lower():
480
+ data[name] = masks
481
+ else:
482
+ data[name] = ids
483
+ return data
484
+
485
+ def rewind(self):
486
+ self._idx = 0
487
+
488
+
489
+ # ─── Quantization ────────────────────────────────────────────────────────────
490
+
491
+ def run_quantization(onnx_path, output_path, reader):
492
+ try:
493
+ from onnxruntime.quantization import (
494
+ quantize_static, QuantType, QuantFormat, CalibrationMethod,
495
+ quant_pre_process,
496
+ )
497
+ except ImportError:
498
+ print("ERROR: onnxruntime.quantization not available.")
499
+ print(" Install: pip install onnxruntime-tools")
500
+ print(" Or: pip install onnxruntime[quantization]")
501
+ sys.exit(1)
502
+
503
+ # Pre-process: shape inference + type annotation fix.
504
+ # Without this, ORT annotates DequantizeLinear SCALE tensors with INT8
505
+ # in the ONNX type system (inherited from quantization path), causing TRT's
506
+ # ONNX parser to emit "[SCALE] has invalid precision Int8, ignored" and
507
+ # silently skip all Q/DQ nodes. quant_pre_process runs ONNX shape inference
508
+ # which corrects the type annotations before Q/DQ nodes are inserted.
509
+ preprocessed_path = output_path.replace(".onnx", "_preproc.onnx")
510
+ print(f" Pre-processing ONNX (shape inference for TRT-compatible Q/DQ)...")
511
+ src_path = onnx_path
512
+ try:
513
+ quant_pre_process(
514
+ onnx_path,
515
+ preprocessed_path,
516
+ skip_optimization=True, # only shape inference, skip full ONNX optimizer
517
+ )
518
+ # Verify output is valid: quant_pre_process on external-data models can
519
+ # produce a proto with missing opset_import, causing ORT's augmented-model
520
+ # step to fail with "Missing opset in the model".
521
+ import onnx as _onnx_check
522
+ _pre = _onnx_check.load(preprocessed_path, load_external_data=False)
523
+ if not any(i.domain in ("", "ai.onnx") for i in _pre.opset_import):
524
+ raise ValueError("preprocessed model missing ONNX domain opset — using original")
525
+ src_path = preprocessed_path
526
+ print(f" Pre-processing done.")
527
+ except Exception as e:
528
+ print(f" WARNING: quant_pre_process failed or produced invalid model ({e}), using original ONNX")
529
+ if os.path.exists(preprocessed_path):
530
+ os.remove(preprocessed_path)
531
+
532
+ try:
533
+ quantize_static(
534
+ src_path,
535
+ output_path,
536
+ calibration_data_reader=reader,
537
+ quant_format=QuantFormat.QDQ,
538
+ activation_type=QuantType.QInt8,
539
+ weight_type=QuantType.QInt8,
540
+ # MatMul and Gemm only — RMSNorm/LayerNorm excluded, stay in float,
541
+ # which is the only way to avoid NaN in Gemma-family RMSNorm (confirmed
542
+ # 2026-04-28: implicit INT8/FP8 saturates at ±127/±448 → NaN after division)
543
+ op_types_to_quantize=["MatMul", "Gemm"],
544
+ per_channel=False,
545
+ calibrate_method=CalibrationMethod.MinMax,
546
+ extra_options={"ActivationSymmetric": True},
547
+ # External-data models (>2GB float32 like Qwen3-0.6B) cause ORT's
548
+ # internal augmented_model.onnx to exceed protobuf 2GB limit when
549
+ # saved inline. use_external_data_format makes ORT save the augmented
550
+ # model as proto+data file pair, avoiding "Protobuf parsing failed".
551
+ use_external_data_format=True,
552
+ )
553
+ finally:
554
+ if os.path.exists(preprocessed_path):
555
+ os.remove(preprocessed_path)
556
+
557
+ # ORT preserves input model opset (e.g. 14 for Qwen3). TRT 10.x correctly
558
+ # handles explicit Q/DQ only at opset ≥ 18 — at opset 14 the legacy ONNX
559
+ # parser propagates INT8 type from the quantized X input onto the scale
560
+ # input of DequantizeLinear → "[SCALE] has invalid precision Int8, ignored"
561
+ # → all Q/DQ discarded. ModelOpt (Gemma path) always writes opset 19 and
562
+ # never hits this. Upgrade the quantized model before TRT engine build.
563
+ # The quantized model is ~1 GB (INT8 weights) — safe to inline-save (<2GB).
564
+ try:
565
+ upgraded, tmp = _preupgrade_onnx_opset(output_path, target_opset=19)
566
+ if tmp:
567
+ import shutil as _shutil
568
+ _shutil.move(tmp, output_path)
569
+ print(f" Upgraded quantized model to opset 19 (TRT Q/DQ requires ≥18).")
570
+ except Exception as e:
571
+ print(f" WARNING: opset-19 upgrade failed ({e}), TRT may ignore Q/DQ nodes.")
572
+
573
+ # Post-process: add explicit value_info for Q/DQ scale/zero_point initializers.
574
+ # quantize_static adds scale constants as graph initializers without value_info.
575
+ # TRT's ONNX parser, finding no value_info for scale, propagates the data type
576
+ # of the quantized tensor (INT8) to the scale input → emits
577
+ # "[SCALE] has invalid precision Int8, ignored" and discards the Q/DQ node.
578
+ # Explicit FLOAT32 value_info for scale initializers stops this type propagation.
579
+ _fix_qdq_scale_value_info(output_path)
580
+
581
+
582
+ def _fix_modelopt_scale_precision(onnx_path):
583
+ """Convert ModelOpt FLOAT16 Q/DQ scale initializers to FLOAT32.
584
+
585
+ ModelOpt with high_precision_dtype="fp16" converts scales to FLOAT16.
586
+ TRT weakly-typed mode requires FLOAT32 scales for Q/DQ fusion.
587
+ FP16 scales cause "[SCALE] has invalid precision ..., ignored" warnings.
588
+
589
+ BFLOAT16 scales (from high_precision_dtype="bf16") are NOT converted.
590
+ In opset-22, BF16 scale → DQ output = BF16, which is correct for BF16 models.
591
+ Converting BF16 → F32 makes DQ output F32, causing Float+BF16 type mismatch
592
+ in STRONGLY_TYPED mode at q_norm/Add (RMSNorm epsilon remains BF16).
593
+ BF16 scales work correctly with TRT STRONGLY_TYPED mode (no backward INT8
594
+ propagation to scale, Q/DQ fusion proceeds normally).
595
+
596
+ This function converts only scale tensors (not zero-point — those stay INT8).
597
+ Does NOT add graph.input entries — TRT treats pure initializers as constants,
598
+ which is a REQUIREMENT for Q/DQ fusion. Adding graph.input makes the tensor a
599
+ runtime input, preventing constant-folding and breaking Q/DQ fusion entirely.
600
+ """
601
+ try:
602
+ import onnx
603
+ import onnx.numpy_helper
604
+ import numpy as np
605
+ from onnx import TensorProto
606
+ except ImportError:
607
+ return 0
608
+
609
+ model = onnx.load(onnx_path, load_external_data=True)
610
+
611
+ scale_names: set = set()
612
+ for node in model.graph.node:
613
+ if node.op_type in ("QuantizeLinear", "DequantizeLinear"):
614
+ if len(node.input) > 1 and node.input[1]:
615
+ scale_names.add(node.input[1])
616
+
617
+ init_by_name = {init.name: init for init in model.graph.initializer}
618
+ converted = 0
619
+ for name in scale_names:
620
+ if name not in init_by_name:
621
+ continue
622
+ init = init_by_name[name]
623
+ if init.data_type == TensorProto.FLOAT16:
624
+ arr = onnx.numpy_helper.to_array(init).astype(np.float16).astype(np.float32)
625
+ new_init = onnx.numpy_helper.from_array(arr, name=name)
626
+ else:
627
+ # BFLOAT16 scales: keep as-is. In opset-22, BF16 scale → DQ output BF16,
628
+ # which is correct for BF16 models and required for STRONGLY_TYPED mode.
629
+ continue
630
+ idx = list(model.graph.initializer).index(init)
631
+ model.graph.initializer.remove(init)
632
+ model.graph.initializer.insert(idx, new_init)
633
+ converted += 1
634
+
635
+ print(f" ModelOpt scale fix: {converted}/{len(scale_names)} scales →FLOAT32")
636
+ if converted:
637
+ onnx.save(model, onnx_path)
638
+ print(f" Saved: {os.path.basename(onnx_path)}")
639
+ return converted
640
+
641
+
642
+ def _fix_qdq_scale_value_info(onnx_path):
643
+ """Ensure Q/DQ scale tensors have correct graph.input type annotations for TRT.
644
+
645
+ Used ONLY for the ORT quantize_static fallback path. ORT produces FLOAT32 scale
646
+ initializers without graph.input entries. Without graph.input, TRT's ONNX parser
647
+ may propagate INT8 from quantized context to the scale, emitting:
648
+ [SCALE] has invalid precision Int8, ignored
649
+
650
+ NOT called for ModelOpt output — ModelOpt scales must stay as pure initializers
651
+ (no graph.input) so TRT treats them as constants, enabling Q/DQ constant-folding.
652
+
653
+ This function:
654
+ (a) Collects all scale/zero_point tensor names from QuantizeLinear/DequantizeLinear
655
+ (b) Inlines any Constant-node outputs → initializers (so they appear as constants)
656
+ (c) Adds missing graph.input entries with the correct type (FLOAT for scales, INT8 for zp)
657
+ (d) Fixes graph.input entries that have wrong type declarations
658
+ """
659
+ try:
660
+ import onnx
661
+ from onnx import TensorProto, helper
662
+ except ImportError:
663
+ return
664
+
665
+ model = onnx.load(onnx_path, load_external_data=True)
666
+
667
+ scale_names: set = set()
668
+ zp_names: set = set()
669
+ for node in model.graph.node:
670
+ if node.op_type in ("QuantizeLinear", "DequantizeLinear"):
671
+ if len(node.input) > 1 and node.input[1]:
672
+ scale_names.add(node.input[1])
673
+ if len(node.input) > 2 and node.input[2]:
674
+ zp_names.add(node.input[2])
675
+
676
+ # Inline Constant nodes → initializers so TRT treats them as constants, not ops
677
+ const_node_for: dict = {}
678
+ for node in model.graph.node:
679
+ if node.op_type == "Constant":
680
+ for out in node.output:
681
+ if out in scale_names or out in zp_names:
682
+ const_node_for[out] = node
683
+ nodes_to_remove = []
684
+ for name, node in const_node_for.items():
685
+ for attr in node.attribute:
686
+ if attr.name == "value":
687
+ t = onnx.TensorProto()
688
+ t.CopyFrom(attr.t)
689
+ t.name = name
690
+ model.graph.initializer.append(t)
691
+ nodes_to_remove.append(node)
692
+ break
693
+ for node in nodes_to_remove:
694
+ model.graph.node.remove(node)
695
+
696
+ init_by_name: dict = {init.name: init for init in model.graph.initializer}
697
+ inp_by_name: dict = {inp.name: inp for inp in model.graph.input}
698
+
699
+ added = 0
700
+ fixed_input = 0
701
+
702
+ for name in scale_names:
703
+ if name not in init_by_name:
704
+ continue # truly dynamic — skip
705
+ # Ensure graph.input entry exists and declares FLOAT (FLOAT32)
706
+ # TRT reads scale precision from graph.input; without it, type propagation
707
+ # from the quantized INT8 tensor may override the scale to INT8.
708
+ if name not in inp_by_name:
709
+ model.graph.input.append(helper.make_tensor_value_info(name, TensorProto.FLOAT, []))
710
+ inp_by_name[name] = model.graph.input[-1]
711
+ added += 1
712
+ elif inp_by_name[name].type.tensor_type.elem_type != TensorProto.FLOAT:
713
+ inp_by_name[name].type.tensor_type.elem_type = TensorProto.FLOAT
714
+ fixed_input += 1
715
+
716
+ for name in zp_names:
717
+ if name not in init_by_name:
718
+ continue
719
+ zp_type = init_by_name[name].data_type
720
+ if name not in inp_by_name:
721
+ model.graph.input.append(helper.make_tensor_value_info(name, zp_type, []))
722
+ inp_by_name[name] = model.graph.input[-1]
723
+ added += 1
724
+ elif inp_by_name[name].type.tensor_type.elem_type != zp_type:
725
+ inp_by_name[name].type.tensor_type.elem_type = zp_type
726
+ fixed_input += 1
727
+
728
+ print(f" Q/DQ fix: scales={len(scale_names)} zp={len(zp_names)} "
729
+ f"const_inlined={len(nodes_to_remove)} added={added} fixed_input={fixed_input}")
730
+ if added or fixed_input or nodes_to_remove:
731
+ onnx.save(model, onnx_path)
732
+ print(f" Q/DQ fix: saved")
733
+
734
+
735
+ # ─── nvidia-modelopt backend ─────────────────────────────────────────────────
736
+
737
+ def _has_modelopt():
738
+ try:
739
+ import modelopt.onnx.quantization # noqa: F401
740
+ return True
741
+ except ImportError:
742
+ return False
743
+
744
+
745
+ def _setup_trt_for_modelopt():
746
+ """Expose TRT Python bindings to ModelOpt before it tries to import them.
747
+
748
+ ModelOpt does `import tensorrt` for ORT TensorRT-EP calibration and for
749
+ TRT-specific GEMV pattern optimization. Without this, it falls back to CPU
750
+ calibration (correct but slow). We re-use vendor/tensorrt DLLs + any pip
751
+ tensorrt_bindings package — same approach as build_trt_engine._add_nvinfer_to_path.
752
+ """
753
+ if "tensorrt" in sys.modules:
754
+ return
755
+
756
+ # 1. Add vendor/tensorrt/lib DLLs to search path.
757
+ # Found by walking up to build.zig rather than by counting `..`: this file
758
+ # moved from scripts/ to models/_compile/backends/workers/, and a fixed
759
+ # depth fails silently because a missing directory reads as "not vendored".
760
+ _d = os.path.dirname(os.path.abspath(__file__))
761
+ vendor_lib = ""
762
+ for _ in range(6):
763
+ if os.path.isfile(os.path.join(_d, "build.zig")):
764
+ vendor_lib = os.path.join(_d, "vendor", "tensorrt", "lib")
765
+ break
766
+ _d = os.path.dirname(_d)
767
+ if os.path.isdir(vendor_lib):
768
+ if sys.platform == "win32" and hasattr(os, "add_dll_directory"):
769
+ try:
770
+ os.add_dll_directory(vendor_lib)
771
+ except OSError:
772
+ pass
773
+ os.environ["PATH"] = vendor_lib + os.pathsep + os.environ.get("PATH", "")
774
+
775
+ # 2. Add pip tensorrt_libs to DLL search (nvinfer_plugin_10.dll etc.)
776
+ try:
777
+ import site
778
+ for sp in site.getsitepackages() + [site.getusersitepackages()]:
779
+ trt_libs = os.path.join(sp, "tensorrt_libs")
780
+ if os.path.isdir(trt_libs):
781
+ if sys.platform == "win32" and hasattr(os, "add_dll_directory"):
782
+ try:
783
+ os.add_dll_directory(trt_libs)
784
+ except OSError:
785
+ pass
786
+ os.environ["PATH"] = trt_libs + os.pathsep + os.environ.get("PATH", "")
787
+ break
788
+ except Exception:
789
+ pass
790
+
791
+ # 3. Add nvidia/cudnn/bin to PATH (ModelOpt checks system PATH for cuDNN before
792
+ # falling back to onnxruntime.preload_dlls). nvidia-cudnn-cu12 installs DLLs
793
+ # to site-packages/nvidia/cudnn/bin/ — adding here silences the PATH warning.
794
+ try:
795
+ import site
796
+ for _sp in site.getsitepackages() + [site.getusersitepackages()]:
797
+ _cudnn_bin = os.path.join(_sp, "nvidia", "cudnn", "bin")
798
+ if os.path.isdir(_cudnn_bin) and any(
799
+ f.startswith("cudnn64_") and f.endswith(".dll")
800
+ for f in os.listdir(_cudnn_bin)
801
+ ):
802
+ os.environ["PATH"] = _cudnn_bin + os.pathsep + os.environ.get("PATH", "")
803
+ if sys.platform == "win32" and hasattr(os, "add_dll_directory"):
804
+ try:
805
+ os.add_dll_directory(_cudnn_bin)
806
+ except OSError:
807
+ pass
808
+ break
809
+ except Exception:
810
+ pass
811
+
812
+ # 4. Add nvidia/cublas/bin to PATH (ORT CUDA EP loads cublasLt64_12.dll from here).
813
+ # nvidia-cublas-cu12 installs to site-packages/nvidia/cublas/bin/.
814
+ try:
815
+ import site
816
+ for _sp in site.getsitepackages() + [site.getusersitepackages()]:
817
+ _cublas_bin = os.path.join(_sp, "nvidia", "cublas", "bin")
818
+ if os.path.isdir(_cublas_bin) and any(
819
+ f.startswith("cublasLt") and f.endswith(".dll")
820
+ for f in os.listdir(_cublas_bin)
821
+ ):
822
+ os.environ["PATH"] = _cublas_bin + os.pathsep + os.environ.get("PATH", "")
823
+ if sys.platform == "win32" and hasattr(os, "add_dll_directory"):
824
+ try:
825
+ os.add_dll_directory(_cublas_bin)
826
+ except OSError:
827
+ pass
828
+ break
829
+ except Exception:
830
+ pass
831
+
832
+ # 5. Alias tensorrt_bindings → tensorrt (tensorrt-cu12-bindings pip package)
833
+ try:
834
+ from tensorrt_bindings import tensorrt as _trt
835
+ sys.modules["tensorrt"] = _trt
836
+ import tensorrt_bindings as _trt_pkg
837
+ _ver = getattr(_trt_pkg, "__version__", None) or getattr(_trt, "__version__", "unknown")
838
+ print(f" TensorRT {_ver} exposed to ModelOpt via tensorrt_bindings")
839
+ except ImportError:
840
+ try:
841
+ import tensorrt # noqa: F401 (direct install)
842
+ print(f" TensorRT ready for ModelOpt")
843
+ except ImportError:
844
+ pass # ModelOpt will fall back to CPU calibration — still correct
845
+
846
+
847
+ def _preupgrade_onnx_opset(onnx_path, target_opset=19):
848
+ """Manually upgrade Reduce* axes from attribute to input (opset 14 → 18+).
849
+
850
+ ModelOpt's internal upgrader bumps opset_import but doesn't convert
851
+ ReduceMean axes-as-attribute → axes-as-input (required for opset 18+).
852
+ onnx.version_converter also fails on old IR versions. Manual conversion:
853
+ for each Reduce node with axes attribute, insert a Constant node and
854
+ rewire it as the second input.
855
+
856
+ Returns (new_onnx_path, tmp_path_or_None) — caller must delete tmp.
857
+ """
858
+ import onnx
859
+ import onnx.helper
860
+
861
+ model = onnx.load(onnx_path, load_external_data=True)
862
+ cur_opset = max(
863
+ (i.version for i in model.opset_import if i.domain in ("", "ai.onnx")),
864
+ default=0,
865
+ )
866
+ if cur_opset >= target_opset:
867
+ return onnx_path, None
868
+
869
+ print(f" Pre-upgrading opset {cur_opset} → {target_opset} (manual Reduce axes fix)...")
870
+
871
+ # Reduce ops that moved axes from attribute to input in opset 18
872
+ _REDUCE_OPS = {
873
+ "ReduceMean", "ReduceSum", "ReduceMax", "ReduceMin", "ReduceProd",
874
+ "ReduceL1", "ReduceL2", "ReduceLogSum", "ReduceLogSumExp", "ReduceSumSquare",
875
+ }
876
+
877
+ extra_nodes: list = [] # Constant axes nodes — must precede consumers
878
+ new_nodes: list = []
879
+
880
+ for node in model.graph.node:
881
+ if node.op_type in _REDUCE_OPS:
882
+ axes_attr = next((a for a in node.attribute if a.name == "axes"), None)
883
+ if axes_attr and len(axes_attr.ints) > 0:
884
+ axes_vals = list(axes_attr.ints)
885
+ const_out = f"_axes_cst_{node.output[0]}"
886
+ axes_tensor = onnx.helper.make_tensor(
887
+ const_out, onnx.TensorProto.INT64, [len(axes_vals)], axes_vals
888
+ )
889
+ extra_nodes.append(
890
+ onnx.helper.make_node("Constant", inputs=[], outputs=[const_out],
891
+ value=axes_tensor)
892
+ )
893
+ # Rebuild node: axes as second input, strip axes attribute
894
+ rebuilt = onnx.helper.make_node(
895
+ node.op_type,
896
+ inputs=list(node.input) + [const_out],
897
+ outputs=list(node.output),
898
+ name=node.name,
899
+ )
900
+ for a in node.attribute:
901
+ if a.name != "axes":
902
+ rebuilt.attribute.append(a)
903
+ new_nodes.append(rebuilt)
904
+ continue
905
+ new_nodes.append(node)
906
+
907
+ del model.graph.node[:]
908
+ model.graph.node.extend(extra_nodes + new_nodes)
909
+
910
+ # Bump declared opset and IR version
911
+ for imp in model.opset_import:
912
+ if imp.domain in ("", "ai.onnx"):
913
+ imp.version = target_opset
914
+ model.ir_version = 9 # required for opset 19
915
+
916
+ tmp_path = onnx_path.replace(".onnx", f"_opset{target_opset}_pre.onnx")
917
+ onnx.save_model(model, tmp_path)
918
+ print(f" Pre-upgraded: {os.path.basename(tmp_path)}")
919
+ return tmp_path, tmp_path
920
+
921
+
922
+ def _preupgrade_onnx_structural(onnx_path, target_opset=18):
923
+ """Upgrade Reduce* axes attribute→input (opset 14→18) without loading weights.
924
+
925
+ Loads only the ONNX proto (no external weight data), fixes ReduceMean/etc.
926
+ axes-as-attribute nodes, bumps declared opset/IR, then saves a new proto that
927
+ still references the ORIGINAL external-data blob. No 2 GB protobuf limit
928
+ because weight tensors are never materialised in Python memory.
929
+
930
+ Returns (upgraded_path, tmp_path_or_None). Caller should delete tmp after use.
931
+ If the model is already at target_opset, returns (onnx_path, None) immediately.
932
+ """
933
+ import onnx
934
+ import onnx.helper
935
+
936
+ # Quick check without loading weights
937
+ model_hdr = onnx.load(onnx_path, load_external_data=False)
938
+ cur_opset = max(
939
+ (i.version for i in model_hdr.opset_import if i.domain in ("", "ai.onnx")),
940
+ default=0,
941
+ )
942
+ if cur_opset >= target_opset:
943
+ return onnx_path, None
944
+
945
+ print(f" Structural pre-upgrade opset {cur_opset}→{target_opset} (no weights loaded)...")
946
+
947
+ _REDUCE_OPS = {
948
+ "ReduceMean", "ReduceSum", "ReduceMax", "ReduceMin", "ReduceProd",
949
+ "ReduceL1", "ReduceL2", "ReduceLogSum", "ReduceLogSumExp", "ReduceSumSquare",
950
+ }
951
+
952
+ extra_nodes: list = []
953
+ new_nodes: list = []
954
+ for node in model_hdr.graph.node:
955
+ if node.op_type in _REDUCE_OPS:
956
+ axes_attr = next((a for a in node.attribute if a.name == "axes"), None)
957
+ if axes_attr and len(axes_attr.ints) > 0:
958
+ axes_vals = list(axes_attr.ints)
959
+ const_out = f"_axes_cst_{node.output[0]}"
960
+ axes_tensor = onnx.helper.make_tensor(
961
+ const_out, onnx.TensorProto.INT64, [len(axes_vals)], axes_vals
962
+ )
963
+ extra_nodes.append(
964
+ onnx.helper.make_node("Constant", inputs=[], outputs=[const_out],
965
+ value=axes_tensor)
966
+ )
967
+ rebuilt = onnx.helper.make_node(
968
+ node.op_type,
969
+ inputs=list(node.input) + [const_out],
970
+ outputs=list(node.output),
971
+ name=node.name,
972
+ )
973
+ for a in node.attribute:
974
+ if a.name != "axes":
975
+ rebuilt.attribute.append(a)
976
+ new_nodes.append(rebuilt)
977
+ continue
978
+ new_nodes.append(node)
979
+
980
+ del model_hdr.graph.node[:]
981
+ model_hdr.graph.node.extend(extra_nodes + new_nodes)
982
+
983
+ for imp in model_hdr.opset_import:
984
+ if imp.domain in ("", "ai.onnx"):
985
+ imp.version = target_opset
986
+ # IR version must match opset: opset 17-18 → ir 8, opset 19+ → ir 9
987
+ model_hdr.ir_version = 9 if target_opset >= 19 else 8
988
+
989
+ # Save proto only; keep external-data blob in place.
990
+ # location= must be relative to the directory of the new proto file.
991
+ # We save alongside the original model so the existing .onnx_data is found.
992
+ ext_data_filename = os.path.basename(onnx_path) + "_data"
993
+ tmp_path = onnx_path.replace(".onnx", f"_opset{target_opset}_struct.onnx")
994
+ onnx.save_model(
995
+ model_hdr,
996
+ tmp_path,
997
+ save_as_external_data=True,
998
+ all_tensors_to_one_file=True,
999
+ location=ext_data_filename, # same relative name as the original blob
1000
+ size_threshold=0,
1001
+ convert_attribute=False,
1002
+ )
1003
+ print(f" Structural upgrade saved: {os.path.basename(tmp_path)} "
1004
+ f"(data→{ext_data_filename})")
1005
+ return tmp_path, tmp_path
1006
+
1007
+
1008
+ def _quantize_modelopt(onnx_path, output_path, texts, tok_tuple, input_names, max_seq,
1009
+ quantize_mode="int8", high_precision="bf16", calib_method="max"):
1010
+ """PTQ using nvidia-modelopt — produces Q/DQ ONNX following TensorRT rules.
1011
+
1012
+ ORT quantize_static produces Q/DQ with scale type annotations that TRT's
1013
+ ONNX parser rejects ("[SCALE] has invalid precision Int8, ignored"), silently
1014
+ discarding all Q/DQ nodes. ModelOpt generates the same Q/DQ structure but
1015
+ with correct TRT-compatible annotations — no parser warnings, INT8/FP8 engaged.
1016
+
1017
+ quantize_mode: "int8" (default) or "fp8" (E4M3, sm_89+, best on sm_120 Blackwell).
1018
+ FP8 requires ONNX opset 20+ and TRT 10.x --fp8 builder flag.
1019
+
1020
+ Calibration data: full numpy batch (not one-at-a-time like ORT CalibDataReader).
1021
+ """
1022
+ _setup_trt_for_modelopt()
1023
+ import modelopt.onnx.quantization as moq
1024
+ import numpy as np
1025
+
1026
+ # FP8 only: pre-upgrade to opset 20 (FLOAT8E4M3FN type added in opset 20).
1027
+ # INT8: let ModelOpt handle the opset upgrade internally. ModelOpt's internal
1028
+ # upgrade ("Updating minimum opset from 13 to 19") includes TRT-specific structural
1029
+ # transformations beyond just bumping the opset number. Pre-upgrading externally
1030
+ # skips those transformations, producing Q/DQ with scale tensors that TRT's type
1031
+ # inference misclassifies as INT8 → "[SCALE] has invalid precision Int8, ignored"
1032
+ # → fusion fails → FP16 fallback. For INT8 pass the original opset-14 ONNX
1033
+ # (with external data) directly to ModelOpt.
1034
+ if quantize_mode in ("fp8", "nvfp4", "int4"):
1035
+ # FP8 / NVFP4 / INT4 need opset 20+ (FLOAT8E4M3FN / FLOAT4E2M1 dtypes).
1036
+ # INT8 lets ModelOpt do the opset upgrade internally (TRT structural transforms).
1037
+ upgraded_path, _struct_tmp = _preupgrade_onnx_opset(onnx_path, target_opset=20)
1038
+ else:
1039
+ upgraded_path, _struct_tmp = onnx_path, None
1040
+
1041
+ print(f" Backend: nvidia-modelopt (TRT-native QDQ, mode={quantize_mode})")
1042
+ print(f" Tokenizing {len(texts)} calibration samples...")
1043
+ ids, masks = tokenize(tok_tuple, texts, max_seq)
1044
+ # Clamp OOB token IDs (tokenizer vocab > ONNX embedding table) for the ModelOpt path
1045
+ # too. The ORT CalibrationDataReader clamps via max_token_id, but ModelOpt gets the raw
1046
+ # `ids` and would otherwise hit a Gather OOB (idx=vocab must be in [0, vocab-1]) — e.g.
1047
+ # an XLM-R <mask> at id=vocab — which aborts ModelOpt → ORT fallback → LayerNorm failure.
1048
+ _mo_vocab = get_onnx_vocab_size(onnx_path)
1049
+ if _mo_vocab:
1050
+ ids = np.clip(ids, 0, _mo_vocab - 1)
1051
+
1052
+ calib: dict = {}
1053
+ for name in input_names:
1054
+ if "attention" in name.lower() or "mask" in name.lower():
1055
+ calib[name] = masks
1056
+ else:
1057
+ calib[name] = ids
1058
+ print(f" Calibration shape: {ids.shape[0]} samples × {ids.shape[1]} tokens")
1059
+
1060
+ # disable_mha_qdq: skip MHA inner BMM quantization (Q·Kᵀ, attn·V).
1061
+ # Default True for INT8: dynamic "weights" can hurt quality there.
1062
+ # 2026-05-19 FP8 override: with EXPERIMENTAL_QUANTIZE_MHA_FP8 we flip to
1063
+ # False so MHA inner BMMs also go through FP8 Q/DQ. softmax/RMSNorm stay
1064
+ # in BF16 via high_precision_dtype (NaN-safe). Without this, FP8 mode
1065
+ # only quantizes ~48/168 matmuls and loses to INT8 STRONGLY_TYPED which
1066
+ # has no such exclusion (measured 2026-05-19: 3584 vs 4541 emb/s).
1067
+ disable_mha_qdq_flag = True
1068
+ if quantize_mode == "fp8" and EXPERIMENTAL_QUANTIZE_MHA_FP8:
1069
+ disable_mha_qdq_flag = False
1070
+ print(" [EXPERIMENTAL] disable_mha_qdq=False — quantizing MHA inner BMMs in FP8")
1071
+
1072
+ moq.quantize(
1073
+ onnx_path=upgraded_path,
1074
+ calibration_data=calib,
1075
+ output_path=output_path,
1076
+ quantize_mode=quantize_mode,
1077
+ # MatMul + Gemm only — RMSNorm/LayerNorm excluded, stay in high-precision float.
1078
+ # Gemma RMSNorm uses weights with +1.0 offset (TRT-LLM issue #4815); quantizing
1079
+ # these ops causes silent accuracy loss.
1080
+ op_types_to_quantize=["MatMul", "Gemm"],
1081
+ # "entropy" (--calib-method): KL-divergence clipping of activation ranges —
1082
+ # for outlier-heavy pretrained bodies (XLM-R/e5) where "max" saturates the
1083
+ # int8 grid and collapses top-rank (v2-p4: h1 .227→.160 under max, 2026-07-22).
1084
+ calibration_method=calib_method,
1085
+ # high_precision_dtype="bf16": non-quantized ops (RMSNorm, SiLU, softmax) in BF16.
1086
+ # Gemma model card: activations do not support float16 — use bfloat16.
1087
+ # BF16 has same exponent range as Float32, preventing RMSNorm overflow.
1088
+ #
1089
+ # ModelOpt with "bf16" upgrades to opset-22 and stores scale initializers as BF16.
1090
+ # In ONNX opset-22, DQ output type = scale type → BF16 scale → BF16 DQ output.
1091
+ # This means q_norm/Add receives BF16 + BF16 (both ReduceMean and epsilon in BF16).
1092
+ # TRT STRONGLY_TYPED mode reads these types without backward INT8 propagation →
1093
+ # 0 [SCALE] warnings → INT8 Q/DQ fusion works → ~1300 emb/s on sm_120 (3× BF16).
1094
+ #
1095
+ # DO NOT call _fix_modelopt_scale_precision after this: converting BF16→F32 scales
1096
+ # makes DQ output F32 → q_norm/Add gets F32+BF16 → STRONGLY_TYPED fails.
1097
+ #
1098
+ # high_precision="fp16" (--high-precision, 2026-07-22): for fp16-safe encoders
1099
+ # (XLM-R/LayerNorm embed models). Keeps ModelOpt's internal opset-19 upgrade
1100
+ # (TRT-11 parseable, ORT-runnable) + FLOAT16 scales that
1101
+ # _fix_modelopt_scale_precision converts to FP32. bf16 on the v2-p3/p4 embed
1102
+ # body produced a cos=-0.06 garbage TRT engine + un-runnable-in-ORT QDQ.
1103
+ high_precision_dtype=high_precision,
1104
+ mha_accumulation_dtype=high_precision,
1105
+ disable_mha_qdq=disable_mha_qdq_flag,
1106
+ )
1107
+ print(f" modelopt quantization done ({quantize_mode}).", flush=True)
1108
+
1109
+ # Clean up structural-upgrade temp file (the original data blob is shared)
1110
+ if _struct_tmp and os.path.exists(_struct_tmp):
1111
+ try:
1112
+ os.remove(_struct_tmp)
1113
+ except Exception:
1114
+ pass
1115
+
1116
+
1117
+ def _ensure_modelopt():
1118
+ """Auto-install nvidia-modelopt[onnx] if not present. Returns True if available."""
1119
+ if _has_modelopt():
1120
+ return True
1121
+ print(" nvidia-modelopt not found — installing...")
1122
+ result = subprocess.run(
1123
+ [sys.executable, "-m", "pip", "install", "--quiet", "nvidia-modelopt[onnx]"],
1124
+ capture_output=True, text=True,
1125
+ )
1126
+ if result.returncode != 0:
1127
+ print(f" Install failed: {result.stderr.strip()[:200]}")
1128
+ return False
1129
+ if _has_modelopt():
1130
+ print(" nvidia-modelopt installed.")
1131
+ return True
1132
+ print(" nvidia-modelopt still not importable after install.")
1133
+ return False
1134
+
1135
+
1136
+ # ─── Main ────────────────────────────────────────────────────────────────────
1137
+
1138
+ def main():
1139
+ ap = argparse.ArgumentParser(
1140
+ description="PTQ INT8 Q/DQ quantization for ONNX embedding models",
1141
+ formatter_class=argparse.RawDescriptionHelpFormatter,
1142
+ epilog=__doc__,
1143
+ )
1144
+ ap.add_argument("--model-dir", required=True,
1145
+ help="Output directory (tokenizer.json; model_int8qdt.onnx written here by default)")
1146
+ ap.add_argument("--onnx-dir", metavar="PATH",
1147
+ help="Directory containing the source model.onnx WITH external data files "
1148
+ "(e.g. scripts/.cache/<model-id>). When omitted, --model-dir is searched.")
1149
+ ap.add_argument("--calib-db", nargs="*", metavar="PATH",
1150
+ help="Explicit paths to UltraCode graph.db calibration files")
1151
+ ap.add_argument("--calib-dir", metavar="PATH",
1152
+ help="UltraCode projects dir to scan (auto-detected if omitted)")
1153
+ ap.add_argument("--calib-texts", metavar="PATH",
1154
+ help="JSONL of calibration texts ({'text': ...} per line, or plain "
1155
+ "lines) — bypasses graph.db collection entirely. Use the REAL "
1156
+ "serve strings (entities_serve.jsonl): the 2026-07-2x p5_c PTQ "
1157
+ "collapse calibrated on entity NAMES + raw 400-char file chunks, "
1158
+ "not the label(+desc) texts the model actually serves "
1159
+ "(deep-research report §4 arm 0 — the de-confounder).")
1160
+ ap.add_argument("--samples", type=int, default=500,
1161
+ help="Target calibration sample count (default: 500)")
1162
+ ap.add_argument("--max-seq", type=int, default=128,
1163
+ help="Max token sequence length (default: 128, matches TRT profile 2)")
1164
+ ap.add_argument("--output", metavar="PATH",
1165
+ help="Output ONNX path (default: {model_dir}/model_int8qdt.onnx or model_fp8qdt.onnx)")
1166
+ ap.add_argument("--fp8", action="store_true",
1167
+ help="Use FP8 E4M3 quantization instead of INT8 (requires sm_89+, best on sm_120 Blackwell). "
1168
+ "Produces model_fp8qdt.onnx. Build TRT engine with --fp8 flag afterwards.")
1169
+ ap.add_argument("--nvfp4", action="store_true",
1170
+ help="EXPERIMENTAL (TRT 11): NVFP4 4-bit (E2M1) quantization. Produces "
1171
+ "model_nvfp4qdt.onnx -> strongly-typed engine. Requires ml_dtypes with "
1172
+ "float4_e2m1fn + CUDA 13.3 cuBLAS NVFP4-scaling fix (the 13.2 bug is fixed "
1173
+ "in cuBLAS 13.5.1). GATED: ship only if the 256d quality check holds "
1174
+ "(sim-pass skipped_empty=0 + min_cos>=0.5 + MTEB/MIRACL-RU vs INT8 baseline).")
1175
+ ap.add_argument("--int4", action="store_true",
1176
+ help="EXPERIMENTAL (TRT 11): INT4 weight quantization. Produces "
1177
+ "model_int4qdt.onnx. Same 256d quality gate as --nvfp4.")
1178
+ ap.add_argument("--onnx-name", default="model.onnx",
1179
+ help="Source ONNX filename to look for in --onnx-dir/--model-dir. "
1180
+ "Default 'model.onnx'. Use 'model_static.onnx' for the TRT INT8 "
1181
+ "MHA fusion path (static-shape ONNX is required for fusion in "
1182
+ "TRT 10.15.1+; see .autodoc/archive/ner.md).")
1183
+ ap.add_argument("--calib-method", choices=["max", "entropy"], default="max",
1184
+ help="ModelOpt activation calibration. 'entropy' clips outlier ranges "
1185
+ "(KL) — use for pretrained XLM-R/e5 bodies where 'max' saturates.")
1186
+ ap.add_argument("--high-precision", choices=["bf16", "fp16", "fp32"], default="bf16",
1187
+ help="ModelOpt high_precision_dtype for non-quantized ops. Default 'bf16' "
1188
+ "(Gemma/RMSNorm NaN-safety; bumps opset to 22, BF16 scales — the "
1189
+ "NER/LLM path). Use 'fp16' for fp16-safe encoders (XLM-R/LayerNorm "
1190
+ "embed models): keeps ModelOpt's internal opset-19 upgrade (TRT-11 "
1191
+ "parseable, ORT-runnable) and FLOAT16 scales, which "
1192
+ "_fix_modelopt_scale_precision then converts to FP32 for Q/DQ fusion. "
1193
+ "bf16 on the v2-p3/p4 embed body produced a cos=-0.06 garbage engine "
1194
+ "(2026-07-22, PHASE3_REDISTILL_RUNBOOK §SESSION 2).")
1195
+ args = ap.parse_args()
1196
+
1197
+ # Precision selection (priority: nvfp4 > int4 > fp8 > int8). nvfp4/int4 are
1198
+ # experimental TRT-11 tracks (see flag help + .autodoc/archive/embed-encoder.md); they
1199
+ # need a newer ml_dtypes (float4_e2m1fn) and pass through a 256d quality gate.
1200
+ if args.nvfp4:
1201
+ quantize_mode = "nvfp4"
1202
+ elif args.int4:
1203
+ quantize_mode = "int4"
1204
+ elif args.fp8:
1205
+ quantize_mode = "fp8"
1206
+ else:
1207
+ quantize_mode = "int8"
1208
+
1209
+ # ── Find source ONNX (prefer --onnx-dir when provided; it has external data)
1210
+ search_dirs = []
1211
+ if args.onnx_dir:
1212
+ search_dirs.append(args.onnx_dir)
1213
+ search_dirs.append(args.model_dir)
1214
+ onnx_path = None
1215
+ for d in search_dirs:
1216
+ onnx_path = find_onnx(d, onnx_name=args.onnx_name)
1217
+ if onnx_path:
1218
+ break
1219
+ if not onnx_path:
1220
+ searched = ", ".join(search_dirs)
1221
+ print(f"ERROR: {args.onnx_name} not found in {searched}")
1222
+ sys.exit(1)
1223
+ print(f"Input ONNX: {onnx_path} ({os.path.getsize(onnx_path) / 1e6:.0f} MB)")
1224
+
1225
+ # ── Output path — always under model_dir (production), not onnx_dir (cache)
1226
+ default_out_name = {
1227
+ "nvfp4": "model_nvfp4qdt.onnx", "int4": "model_int4qdt.onnx",
1228
+ "fp8": "model_fp8qdt.onnx", "int8": "model_int8qdt.onnx",
1229
+ }[quantize_mode]
1230
+ output_path = args.output or os.path.join(args.model_dir, default_out_name)
1231
+ print(f"Output ONNX: {output_path} (mode={quantize_mode})")
1232
+
1233
+ # ── Collect texts: explicit serve-text file beats DB scraping
1234
+ if args.calib_texts:
1235
+ import json as _json
1236
+ texts = []
1237
+ with open(args.calib_texts, encoding="utf-8") as f:
1238
+ for line in f:
1239
+ line = line.strip()
1240
+ if not line:
1241
+ continue
1242
+ try:
1243
+ obj = _json.loads(line)
1244
+ t = obj.get("text") if isinstance(obj, dict) else None
1245
+ except ValueError:
1246
+ t = line
1247
+ if t:
1248
+ texts.append(t)
1249
+ if not texts:
1250
+ print(f"ERROR: no texts in {args.calib_texts}")
1251
+ sys.exit(1)
1252
+ # Even spread across the file (it is ordered by file path — a head
1253
+ # slice would calibrate on one corner of the repo).
1254
+ if len(texts) > args.samples:
1255
+ step = len(texts) / args.samples
1256
+ texts = [texts[int(i * step)] for i in range(args.samples)]
1257
+ print(f"Texts: {len(texts)} serve strings from {args.calib_texts}")
1258
+ else:
1259
+ # ── Calibration DBs
1260
+ if args.calib_db:
1261
+ db_paths = args.calib_db
1262
+ else:
1263
+ calib_dir = args.calib_dir or _default_projects_dir()
1264
+ db_paths = find_calib_dbs(calib_dir)
1265
+ if not db_paths:
1266
+ print(f"\nERROR: no graph.db files found in {calib_dir}")
1267
+ print(" Index some projects first:")
1268
+ print(" mcp__ultracode__index --directory /path/to/project")
1269
+ print(" Or pass --calib-db explicitly.")
1270
+ sys.exit(1)
1271
+ print(f"Calib DBs: {len(db_paths)} files")
1272
+
1273
+ per_db = max(10, (args.samples * 4 // 3) // max(len(db_paths), 1))
1274
+ texts = collect_texts(db_paths, per_db=per_db)
1275
+ if not texts:
1276
+ print("ERROR: no calibration texts collected. Check DB paths and entity data.")
1277
+ sys.exit(1)
1278
+ texts = texts[:args.samples]
1279
+ print(f"Texts: {len(texts)} samples from {len(db_paths)} projects")
1280
+
1281
+ # ── Tokenizer — prefer onnx_dir (HF cache, has tokenizer.json), fall back to model_dir
1282
+ tok_dir = args.onnx_dir if args.onnx_dir else args.model_dir
1283
+ print(f"Tokenizer: {tok_dir}")
1284
+ tok = load_tokenizer(tok_dir)
1285
+
1286
+ # ── ONNX input names + vocab size (for calibration token ID clamping)
1287
+ input_names = get_onnx_input_names(onnx_path)
1288
+ print(f"ONNX inputs: {input_names}")
1289
+ vocab_size = get_onnx_vocab_size(onnx_path)
1290
+ if vocab_size:
1291
+ print(f"ONNX vocab: {vocab_size} (token IDs clamped to [0, {vocab_size - 1}])")
1292
+
1293
+ # ── Quantize
1294
+ print(f"\nQuantizing (op_types: MatMul, Gemm | format: QDQ | mode: {quantize_mode})...")
1295
+ if args.fp8:
1296
+ print(" FP8 mode: E4M3, requires sm_89+ (Ada/Hopper/Blackwell)")
1297
+ print(" After quantization build TRT with: --fp8 --onnx <model_fp8qdt.onnx>")
1298
+ modelopt_ok = False
1299
+ if _ensure_modelopt():
1300
+ try:
1301
+ _quantize_modelopt(onnx_path, output_path, texts, tok, input_names, args.max_seq,
1302
+ quantize_mode=quantize_mode, high_precision=args.high_precision,
1303
+ calib_method=args.calib_method)
1304
+ modelopt_ok = True
1305
+ except BaseException as e:
1306
+ print(f" ModelOpt failed ({type(e).__name__}: {e})", flush=True)
1307
+ if quantize_mode != "int8":
1308
+ if "Invalid quantization mode" in str(e) or quantize_mode == "nvfp4":
1309
+ # ModelOpt's ONNX quantize() routes only int8/fp8/int4 (as of
1310
+ # 0.43/0.44). NVFP4 is a PyTorch-quant feature, NOT ONNX PTQ —
1311
+ # quantize_mode="nvfp4" hits `raise RuntimeError(Invalid
1312
+ # quantization mode choice)`. INT4 IS routed (elif "int4").
1313
+ print(f" '{quantize_mode}' is NOT supported by this nvidia-modelopt's ONNX path")
1314
+ print(f" (onnx quantize() routes only int8/fp8/int4; nvfp4 is torch-quant only).")
1315
+ print(f" Use --int4 for a 4-bit ONNX experiment, or stay on INT8.")
1316
+ else:
1317
+ print(f" {quantize_mode} requires nvidia-modelopt with matching opset/ml_dtypes support.")
1318
+ print(f" Cannot fall back to ORT for {quantize_mode} — ORT quantize_static is INT8-only.")
1319
+ sys.exit(1)
1320
+ print(" Falling back to onnxruntime.quantization (ORT path)...")
1321
+ if modelopt_ok and quantize_mode == "int8":
1322
+ # ModelOpt with high_precision_dtype="fp16" stores scales as FLOAT16.
1323
+ # TRT requires FLOAT32 scales for Q/DQ fusion in weakly-typed mode.
1324
+ # For bf16 mode (opset-22): scales stay as BFLOAT16 — DO NOT convert.
1325
+ # BF16 scales → DQ output = BF16 → q_norm/Add: BF16+BF16 = STRONGLY_TYPED OK.
1326
+ # Converting BF16→F32 would make DQ output F32 → q_norm/Add F32+BF16 = FAIL.
1327
+ #
1328
+ # --high-precision fp16 (2026-07-22): SKIP the fix too. ModelOpt stores the
1329
+ # weights AND scales in FP16 — self-consistent per the opset-19 QuantizeLinear
1330
+ # spec (input/scale share T1). Converting scales to F32 breaks that binding
1331
+ # (ORT: "Type parameter (T1) bound to different types (float16 and float)")
1332
+ # and our TRT-11 build is STRONGLY_TYPED (precision from graph types), which
1333
+ # never needed the weakly-typed F32-scale workaround in the first place.
1334
+ if args.high_precision == "bf16":
1335
+ _fix_modelopt_scale_precision(output_path)
1336
+ if not modelopt_ok:
1337
+ # ORT-based PTQ: file-path API handles external-data models (no 2GB proto limit).
1338
+ # quant_pre_process + quantize_static + _fix_qdq_scale_value_info produces
1339
+ # TRT-compatible Q/DQ without [SCALE] warnings.
1340
+ max_tok_id = vocab_size - 1 if vocab_size else None
1341
+ reader = CodeCalibrationReader(texts, tok, input_names, args.max_seq,
1342
+ max_token_id=max_tok_id)
1343
+ run_quantization(onnx_path, output_path, reader)
1344
+ print()
1345
+
1346
+ size_mb = os.path.getsize(output_path) / 1e6
1347
+ print(f"Done: {output_path} ({size_mb:.0f} MB)")
1348
+ if args.fp8:
1349
+ print("Next: build TRT engine from model_fp8qdt.onnx")
1350
+ print(" python scripts/build_trt_engine.py --model-dir dist/models/<model> \\")
1351
+ print(" --onnx dist/models/<model>/model_fp8qdt.onnx --cuda-arch sm_120 --fp8 --force")
1352
+ print(" Expected: ~1000+ emb/s on sm_120 Blackwell (2× INT8 TFLOPS)")
1353
+ else:
1354
+ print("Next: run models/compile to build TRT engine from model_int8qdt.onnx")
1355
+ print(" Expected: ~900 emb/s vs 480 emb/s BF16")
1356
+
1357
+
1358
+ if __name__ == "__main__":
1359
+ main()
_build-tools/run_matrix.py ADDED
@@ -0,0 +1,234 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env python3
2
+ """Build every TRT engine this VM's GPU can produce, straight from build_matrix.json.
3
+
4
+ `build_engines.{ps1,sh}` builds ONE model per invocation from environment
5
+ variables. This driver reads the generated matrix and makes those invocations —
6
+ five models, the right buckets, the right per-arch precision — so the operator
7
+ types a GPU arch's worth of work as one command and cannot mistype a precision.
8
+
9
+ One driver for both operating systems on purpose. The Windows and Linux lanes
10
+ differ only in which wrapper they exec; duplicating the matrix walk in PowerShell
11
+ and bash is how the two halves of a {win_x64, linux_x64} pair start disagreeing
12
+ about what "the same engine" means.
13
+
14
+ python run_matrix.py # everything the matrix lists
15
+ python run_matrix.py --only code-daemon-embed-v1
16
+ python run_matrix.py --skip ultracode-ner
17
+ python run_matrix.py --dry-run # print the invocations, build nothing
18
+
19
+ Environment it passes through untouched (set them before calling):
20
+ HF_TOKEN write token — required unless DEST_PREFIX is set
21
+ HF_UPLOAD_REPO override the destination repo (default: the source repo)
22
+ DEST_PREFIX S3 upload root, if you also want a bucket copy
23
+ TOOLS_URL where build_engines + the .py workers are hosted
24
+ WORKDIR scratch dir (default: ~/uc-build)
25
+
26
+ Exit code is the number of FAILED models, so a wrapper can branch on it. A model
27
+ that fails does not stop the rest: on a rented box the expensive resource is the
28
+ hour, and one bad model should not cost the other four.
29
+ """
30
+
31
+ import argparse
32
+ import json
33
+ import os
34
+ import platform
35
+ import subprocess
36
+ import sys
37
+ import time
38
+ import urllib.request
39
+
40
+ HERE = os.path.dirname(os.path.abspath(__file__))
41
+
42
+
43
+ def log(msg):
44
+ print(msg, flush=True)
45
+
46
+
47
+ def detect_sm():
48
+ """`sm_86` from nvidia-smi's compute_cap. The engine name depends on it, so a
49
+ guess is not acceptable - no GPU means no build, not a default."""
50
+ try:
51
+ out = subprocess.check_output(
52
+ ["nvidia-smi", "--query-gpu=compute_cap,name", "--format=csv,noheader"],
53
+ stderr=subprocess.STDOUT, universal_newlines=True)
54
+ except Exception as e:
55
+ raise SystemExit("nvidia-smi failed (%s) - no NVIDIA driver on this VM?" % e)
56
+ first = out.strip().splitlines()[0]
57
+ cap, _, name = first.partition(",")
58
+ return "sm_" + cap.strip().replace(".", ""), name.strip()
59
+
60
+
61
+ def host_os_arch():
62
+ return "win_x64" if platform.system() == "Windows" else "linux_x64"
63
+
64
+
65
+ def load_matrix(path_or_url):
66
+ if path_or_url.startswith("http://") or path_or_url.startswith("https://"):
67
+ with urllib.request.urlopen(path_or_url, timeout=30) as r:
68
+ return json.loads(r.read().decode("utf-8"))
69
+ with open(path_or_url, encoding="utf-8") as f:
70
+ return json.load(f)
71
+
72
+
73
+ def resolve_matrix_path(explicit, tools_url):
74
+ if explicit:
75
+ return explicit
76
+ beside = os.path.join(HERE, "build_matrix.json")
77
+ if os.path.isfile(beside):
78
+ return beside
79
+ if tools_url:
80
+ return tools_url.rstrip("/") + "/build_matrix.json"
81
+ raise SystemExit(
82
+ "build_matrix.json not found beside this script and TOOLS_URL is unset - "
83
+ "pass --matrix <path|url>")
84
+
85
+
86
+ def wrapper_cmd(os_arch):
87
+ """The per-OS wrapper, taken from beside this file (staged together)."""
88
+ if os_arch == "win_x64":
89
+ script = os.path.join(HERE, "build_engines.ps1")
90
+ if not os.path.isfile(script):
91
+ raise SystemExit("build_engines.ps1 not found beside run_matrix.py")
92
+ return ["powershell", "-NoProfile", "-ExecutionPolicy", "Bypass", "-File", script]
93
+ script = os.path.join(HERE, "build_engines.sh")
94
+ if not os.path.isfile(script):
95
+ raise SystemExit("build_engines.sh not found beside run_matrix.py")
96
+ return ["bash", script]
97
+
98
+
99
+ def env_for(entry, arch, base_env):
100
+ """Translate one matrix row into the wrapper's environment contract."""
101
+ cell = entry["trt"][arch]
102
+ env = dict(base_env)
103
+ env["MODEL_ID"] = entry["model_id"]
104
+ env["ROLE"] = entry["role"]
105
+ # "__single__", not "": Windows does not store empty environment variables -
106
+ # SetEnvironmentVariable(name, "") DELETES the variable, so the wrapper sees
107
+ # "unset" and falls back to its "s m l" default. That built three bucketed
108
+ # engines for a single-profile model, under names the daemon never looks up.
109
+ # Both wrappers already treat __single__ as "one engine, no bucket suffix".
110
+ env["BUCKETS"] = " ".join(entry["buckets"]) if entry["buckets"] else "__single__"
111
+ env["PRECISION"] = cell["precision"]
112
+ env["HF_MODEL_REPO"] = entry["hf_repo"]
113
+ # Destination defaults to the source repo - the daemon reads engines from the
114
+ # same place it reads the ONNX. An explicit HF_UPLOAD_REPO still wins.
115
+ env.setdefault("HF_UPLOAD_REPO", entry["hf_repo"])
116
+ if base_env.get("HF_UPLOAD_REPO"):
117
+ env["HF_UPLOAD_REPO"] = base_env["HF_UPLOAD_REPO"]
118
+ return env
119
+
120
+
121
+ def main():
122
+ ap = argparse.ArgumentParser(description=__doc__,
123
+ formatter_class=argparse.RawDescriptionHelpFormatter)
124
+ ap.add_argument("--matrix", default=None, help="path or URL to build_matrix.json")
125
+ ap.add_argument("--only", action="append", default=[], help="build only this model id (repeatable)")
126
+ ap.add_argument("--skip", action="append", default=[], help="skip this model id (repeatable)")
127
+ ap.add_argument("--arch", default=None, help="override the detected sm_XX (testing only)")
128
+ ap.add_argument("--dry-run", action="store_true", help="print invocations, build nothing")
129
+ args = ap.parse_args()
130
+
131
+ tools_url = os.environ.get("TOOLS_URL", "")
132
+ matrix = load_matrix(resolve_matrix_path(args.matrix, tools_url))
133
+
134
+ os_arch = host_os_arch()
135
+ if args.arch:
136
+ sm, gpu = args.arch, "(overridden)"
137
+ else:
138
+ sm, gpu = detect_sm()
139
+
140
+ log("=" * 70)
141
+ log(" ultracode cloud engine matrix")
142
+ log(" GPU : %s -> %s" % (gpu, sm))
143
+ log(" platform : %s" % os_arch)
144
+ log(" TRT tag : %s (engine names carry it; a mismatch is unloadable)" % matrix["trt_tag"])
145
+ log("=" * 70)
146
+
147
+ if sm not in matrix["cuda_archs"]:
148
+ log("")
149
+ log(" !! %s is not in the cloud matrix %s." % (sm, matrix["cuda_archs"]))
150
+ if sm == "sm_120":
151
+ log(" sm_120 is the LOCAL lane - it is built at a desk and already published.")
152
+ else:
153
+ log(" Add it to build_config.cuda_archs and regenerate, or rent a different card.")
154
+ return 1
155
+
156
+ base_env = dict(os.environ)
157
+ # The wrapper installs TensorRT before the first build; without the exact
158
+ # version it would either guess or let build_trt_engine.py fail on "cannot
159
+ # determine the TensorRT version".
160
+ if matrix.get("trt_pip_version"):
161
+ base_env["TRT_PIP_VERSION"] = matrix["trt_pip_version"]
162
+ if not base_env.get("HF_TOKEN") and not base_env.get("DEST_PREFIX"):
163
+ log("")
164
+ log(" !! neither HF_TOKEN nor DEST_PREFIX is set - the engines would be built and discarded.")
165
+ return 1
166
+
167
+ todo = []
168
+ for entry in matrix["models"]:
169
+ mid = entry["model_id"]
170
+ if args.only and mid not in args.only:
171
+ continue
172
+ if mid in args.skip:
173
+ log(" [skip] %s (--skip)" % mid)
174
+ continue
175
+ # A private HF repo cannot serve the ONNX to a machine holding only a
176
+ # write token for the OTHER repos. Say so once, here, instead of letting
177
+ # the wrapper fail on a 401 five minutes in.
178
+ if entry.get("hf_public") is False and not base_env.get("SRC_ONNX_S3"):
179
+ log(" [skip] %s - HF repo %s is not public and no SRC_ONNX_S3 given"
180
+ % (mid, entry["hf_repo"]))
181
+ continue
182
+ todo.append(entry)
183
+
184
+ if not todo:
185
+ log(" nothing to build")
186
+ return 0
187
+
188
+ cmd = wrapper_cmd(os_arch)
189
+ results = []
190
+ for entry in todo:
191
+ cell = entry["trt"][sm]
192
+ n = max(1, len(entry["buckets"]))
193
+ log("")
194
+ log("-" * 70)
195
+ log(" %s [%s] %d engine(s) buckets=%s"
196
+ % (entry["model_id"], cell["precision"],
197
+ n, ",".join(entry["buckets"]) or "(single)"))
198
+ log(" source: %s :: %s" % (entry["hf_repo"], cell["source"]["file"]))
199
+ if cell["source"]["ptq_on_vm"]:
200
+ log(" note : PTQ runs ON THIS VM - the calibration corpus must be staged")
201
+ log("-" * 70)
202
+
203
+ env = env_for(entry, sm, base_env)
204
+ if args.dry_run:
205
+ keys = ("MODEL_ID", "ROLE", "BUCKETS", "PRECISION", "HF_MODEL_REPO", "HF_UPLOAD_REPO")
206
+ for k in keys:
207
+ log(" %s=%s" % (k, env.get(k, "")))
208
+ results.append((entry["model_id"], "dry-run", 0.0))
209
+ continue
210
+
211
+ t0 = time.time()
212
+ rc = subprocess.call(cmd, env=env)
213
+ dt = time.time() - t0
214
+ results.append((entry["model_id"], "ok" if rc == 0 else "FAILED rc=%d" % rc, dt))
215
+ if rc != 0:
216
+ log(" !! %s failed (rc=%d) - continuing with the rest" % (entry["model_id"], rc))
217
+
218
+ log("")
219
+ log("=" * 70)
220
+ log(" SUMMARY %s / %s" % (sm, os_arch))
221
+ failed = 0
222
+ for mid, status, dt in results:
223
+ mark = "OK " if status in ("ok", "dry-run") else "FAIL"
224
+ if status.startswith("FAILED"):
225
+ failed += 1
226
+ log(" [%s] %-28s %-14s %6.1fs" % (mark, mid, status, dt))
227
+ log("=" * 70)
228
+ if failed:
229
+ log(" %d model(s) FAILED - engines for those cells are missing." % failed)
230
+ return failed
231
+
232
+
233
+ if __name__ == "__main__":
234
+ raise SystemExit(main())