Repository navigation
feat: Add an INT8 token-embedding runtime sidecar - #235
mihai-chiorean wants to merge 1 commit into
Conversation
9e77570 to
8a04d06
Compare
Add `--int8-embedding` to tensorrt-edgellm-export. It writes embedding.safetensors as symmetric INT8 with one FP32 scale per row, mutually exclusive with `--fp8-embedding`. The runtime dequantizes only the gathered rows in the embedding lookup kernel, so the table never expands to FP16 in device memory. loadEmbeddingTable now validates the table dtype at load: FP16, FP8 and INT8 are accepted, anything else is rejected with the dtype and path, and an embedding_scale tensor beside an FP16 table is an error. The Qwen3-Omni talker rejects a quantized thinker embedding sidecar because it reads that table as dense FP16. Signed-off-by: Mihai Chiorean <[email protected]>
8a04d06 to
cadb959
Compare
|
Thanks! Q: Will this enable this model on Jetson Orin Nano, or this is a general improvement strategy? We will look into it in a next version. |
The goal is to fit Gemma 4 on the smaller Jetsons - E4B on a 16 GB Orin NX with room left for other workloads and E2B on an 8 GB Orin Nano. This PR on its own is the general part. It works for any model's token embedding table (I also tested Qwen2.5-0.5B). Most of the Gemma 4 saving comes from the follow-up PR for the PLE table (mihai-chiorean#1, based on this branch, I need to open a PR for that). With both, the tables go from 6.50 GiB to 3.29 GiB for E4B and from 5.13 GiB to 2.60 GiB for E2B. I need to re-measure these on a nano, but my nano is on jp6 right now and I didn't get a chance to upgrade, I have some workloads on it. |
Okay, I've now tested on my nano which is now on JetPack 7.2.1 / TensorRT 10.16. So yes, this is what lets Gemma 4 run on the Orin Nano, and the INT8 tables are still needed even with 4-bit weights. INT4 only applies to the transformer weights; the token and PLE tables are separate and stay large. For E2B the tables are 2.60 GiB in INT8 (5.13 GiB in FP16) next to a 1.31 GB INT4 engine. Here's what I measured on the Nano (E2B, 4096 input / 4608 KV engines, greedy):
Now this is not with JUST this PR, but this change is part of the work. Here are some notes. I can get into the changes and open PRs if that's desirable but I hear at least for the PLE side you guys are doing it for 0.12.0 anyway
The MMLU scores on the Nano use your examples/accuracy harness unchanged (0-shot, 16 tokens). The original's score is from an AGX Orin with the same harness. Fork PRs, all on top of this PR's branch:
Happy to split any of these into upstream PRs in whatever order suits your next release. |
|
Thanks! Since we are not GitHub first now, I will cherry-pick the core ideas into the current Edge-LLM main to be released in a next major release and quote on this. Sorry for this workflow inconvenience. |
What does this PR do?
Type of change: new feature
Overview: Adds an opt-in INT8 format for the runtime token-embedding sidecar,
embedding.safetensors.tensorrt-edgellm-export --int8-embeddingwrites the table as symmetric INT8 ([-127, 127]) with one FP32 scale per vocabulary row. The flag is mutually exclusive with--fp8-embedding. The ONNX graph, the engine and the checkpoint quantization are unchanged.embeddingLookupgains anInt8EmbeddingLoaderthat dequantizes only the gathered rows into the existing FP16 output; the table is never expanded to FP16 in device memory. Image and audio placeholder positions still receive their FP16 encoder features; out-of-vocabulary ids and placeholders without a mapped feature row are zero-filled, as with an FP16 table. The hidden size must be a multiple of 8 (one 8-byte load per lane), which the launcher checks.--fp8-embedding: per-row scales instead of 128-wide block scales; closer reconstruction on the table measured here (Qwen2.5-0.5B-Instruct, all 151,936 rows: cosine min 0.999738 vs 0.999582, max abs error 0.00079 vs 0.00476); a slightly smaller file (136,742,720 vs 140,389,048 bytes); and it is the format the follow-up PR extends to the Gemma 4 per-layer table, which has no FP8 option. Upstream'sfp8-embedding.mdlists FP8 embeddings as SM89+, although--fp8-embeddingran end to end on my AGX Orin.loadEmbeddingTablenow validates the table dtype at load. FP16, FP8 and INT8 are accepted; any other dtype is rejected with the dtype and file path, and anembedding_scaletensor beside an FP16 table is an error. Before this change a non-FP16 table was logged as "Loaded FP16 embedding" and only failed inside the first request, in the kernel's dtype check.embedding.safetensorsas dense FP16, so the exporter rejects--int8-embeddingfor Qwen3-Omni and the Talker runtime rejects a quantized sidecar at construction.docs/source/user_guide/features/int8-embedding.md(file contract, memory example, limitations), a pointer fromquantization.md, and the sidecar list incheckpoint-export.md.tests/defslearns anint8embtest parameter (export, build and inference; it appends-INT8-EMBto the model id and-int8embto the ONNX id, so the INT8 export lives beside the FP16 one, and verifies the sidecar's tensors, dtypes and shapes after export), and the test lists gaintest_checkpoint_export[Qwen2.5-0.5B-Instruct-fp16-int8emb]inl0_onnx_export_1.ymlplus the matchingtest_engine_buildandtest_inference[...-int8emb-llm_basic]cases inl0_pipeline_a30.yml. I cannot run NVIDIA's CI, so these entries are untested there; the same export -> build -> inference sequence was run manually on a Jetson AGX Orin (below).Memory for a
[262144, 2560]table (Gemma 4 E4B): 1,342,177,280 bytes FP16, 672,137,216 bytes INT8 plus FP32 row scales.Usage
The resulting
embedding.safetensorsholds two tensors, and the runtime selects the INT8 path from the table dtype:embedding[vocab, hidden]embedding_scale[vocab]Dequantization is
fp16(int8_value * row_scale); an all-zero row has scale1.0.Validation
Jetson AGX Orin 32 GB (SM87), JetPack 7.2 (L4T R39.2.1), CUDA 13.2.86, TensorRT 10.16.2.10, power mode MAXN with unlocked GPU clocks; candidate
cadb95902d0a216583ec484016a8adb002b58ab6built natively with-DBUILD_UNIT_TESTS=ON, baseline0f52705where stated.Unit tests. The 12
unitTest*binaries were last run in full at8a04d06(all exit 0: unitTestCommon 149 passed; unitTestContextCache 203; unitTestCuteDslKernels 59; unitTestExamples 3; unitTestKernelsAttention 108 passed, 24 skipped (FP8 decode kernels); unitTestKernelsMisc 337 passed, 23 skipped; unitTestKernelsMoe 41 passed, 24 skipped (FP8/FP4); unitTestKernelsSpeculative 114; unitTestPlugins 17 passed, 1 skipped; unitTestRuntime 594 passed, 1 skipped; unitTestRuntimeState 113; unitTestScheduler 59). The only binary whose sources changed since then is unitTestKernelsMisc; at the final head it was rebuilt and run in full: 340 passed, 23 skipped, 0 failed (363 ran). The embedding filter (--gtest_filter='*Embedding*:*Int8*:*Ple*:*Fp16Lookup*:*SidecarLoader*:*GatherRejects*'): 33 passed, including the eleven new INT8, loader-rejection and kernel-rejection cases (hidden sizes 16, 2560 and 2568; the three loader messages with the file path; malformed INT8 scales at the loader and atembeddingLookup; scales passed with an FP16 table).FP8 path on this device: the 13 FP8 unit tests in unitTestKernelsMisc pass (7 of them embedding-lookup tests), and
--fp8-embeddingran end to end (export,llm_build,llm_inference, logLoaded FP8 embedding: [151936, 896], scales: [151936, 7]); its numbers are in the tables below.Export -> build -> inference:
Qwen/Qwen2.5-0.5B-Instruct(BF16 checkpoint, no weight quantization), exported on the device three times, without a flag, with--int8-embeddingand with--fp8-embedding;model.onnxSHA2564140fdc2a62367a9d3bd7ebe7c18c168c640aea42a1d4132b30cdf12ff78d239andmodel.onnx.dataSHA2564ab2ce855ef82b721cd703a0665e725ed6518324636c2fb478388d89e718e309are identical across the three exports; onlyembedding.safetensorsdiffers. All built withllm_build --maxBatchSize 1 --maxInputLen 1024 --maxKVCacheCapacity 2048and run withllm_inference(temperature 0, 64 new tokens). The INT8 engine logsLoaded INT8 embedding: [151936, 896], scales: [151936].Output equivalence, 24 prompts (22 short, one ~250 tokens, one ~500 tokens), 64 new tokens, 1225 (FP16) / 1236 (INT8) generated tokens, 1218 positions compared pairwise. Across the separately built engines: INT8 vs FP16 16 of 24 prompts token-identical, FP8 vs FP16 16 of 24, FP8 vs INT8 14 of 24. On the same engine with the sidecar swapped (the engine binary serves either sidecar): FP16-built engine 20 of 24 identical (first differences at token 38, 31, 62, 21), INT8-built engine 19 of 24 (38, 31, 16, 14, 6); for reference, the same FP16 sidecar on the two builds gives 18 of 24 (TensorRT tactic selection differs between builds of identical ONNX). FP16 control run twice on one engine: 24 of 24 identical. Divergent continuations carry the same content.
Baseline vs candidate on the same FP16 engine and sidecar (24 prompts):
0f52705runtime vs this branch 24 of 24 identical; vs the follow-up PLE branch 24 of 24 identical.MMLU (N=500, stratified by subject with proportional allocation from the full 14,042-question test set, seed 0; 5-shot prompts from
examples/accuracy/scripts/prepare_dataset.py, chat template, greedy, 64 new tokens, engines built with--maxInputLen 8192 --maxKVCacheCapacity 10240 --maxBatchSize 1, the sentence "Answer with the option's letter from the given choices directly." appended to the end of each user message; scored withcalculate_correctness.pyas shipped): FP16 35.0 % (175/500), INT8 35.6 % (178/500); identical predictions on 471/500; flips 4 (FP16-only correct) / 7 (INT8-only correct), exact McNemar p = 0.55; 469/500 (FP16) and 471/500 (INT8) answers parsed to a letter. The same subset at 8 new tokens gives 174 / 177 with 482/500 identical (467/500 parsed); with the harness's default prompt (no instruction, 32 tokens) only 308/500 parse (138 / 137, 451/500 identical); without the chat template the model continues the few-shot list (2/500 parse).MMLU re-run with the letter instruction as a system turn (same 500 questions, this branch at
cadb959; the instruction "Answer with the option's letter from the given choices directly. Reply with the letter only." moved from the end of the user message to a system turn, 16 new tokens instead of 64, chat template, greedy):The Gemma row changes only this PR's table: one engine, the same FP16 PLE sidecar, and the token sidecar swapped. On the one question where its arms differ, both are wrong.
Load-time rejection,
llm_inferenceexit 1 before any request: INT32 table ->Embedding tensor must be FP16, FP8, or INT8, got dtype 3: <path>; INT8 table without scales ->INT8 embedding requires 'embedding_scale' tensor: <path>; FP16 table with scales ->FP16 embedding must not have an 'embedding_scale' tensor: <path>.Soak, 300 requests x 16 tokens on the INT8 engine, sampled every 0.5 s: VmRSS 2271 MiB at 10 % of the run, 2272 MiB at 50 %; system RAM above baseline 430 MiB -> 403 MiB; 300 of 300 responses.
Python unit tests, host:
tests/python-unittests/test_embedding_quantization.pyandtest_export_embedding_flags.py, 26 passed. Run againstmain's sources, 22 of the 26 fail; the 4 that pass are compatibility guards, including the positional-argument test forwrite_runtime_artifacts.Sidecar (file sizes for
[151936, 896]; reconstruction against the FP16 table over all 151,936 rows, dequantized product rounded to FP16):embedding.safetensorsLoaded FP16 embedding: [151936, 896]Loaded INT8 embedding: [151936, 896], scales: [151936]Loaded FP8 embedding: [151936, 896], scales: [151936, 7]Memory, FP16 vs INT8 (0.5 s sampler of
MemTotal - MemAvailableand process VmRSS during the 24-prompt run;--dumpProfilepeaks; FP8 not measured):peak_gpu_memory(cuda free-memory delta, tool unit "MB")The saving measured during inference is 99 MiB of system RAM, 97 of the profiler's "MB" of free-memory delta and 85 MiB of process VmRSS, against a file-size difference of 135,526,680 bytes; the remainder is allocation granularity of the runtime's device buffers (the soak shows no growth).
Speed, FP16 vs INT8 (
llm_bench: 20 iterations after 3 warmup, batch 1;llm_inference --dumpProfile: 20 identical requests after 2 warmup, GPU stage times; FP8 not measured):llm_benchprefill 64 tokens, 5 repeatsllm_benchprefill 1000 tokensllm_benchdecode, past KV 64llm_benchdecode, past KV 1000The 64-token prefill gap follows the engine binary, not the sidecar: the FP16-built engine with the INT8 sidecar measures 10.03-10.06 ms and the INT8-built engine with the FP16 sidecar 10.95-10.97 ms (3 repeats each); it is TensorRT tactic selection between two builds of identical ONNX.
Load time, process start to "Runtime initialized", 5 runs (run 1 after other work on the device, runs 2-5 warm): FP16 1.49 s then 1.31-1.38 s; INT8 1.29 s then 1.28-1.29 s.
Reproduce:
Validation on a 16 GB Jetson Orin NX
The Orin NX run (Jetson Orin NX 16 GB, JetPack 7.2, CUDA 13.2.86, TensorRT 10.16.2.10, 40 W power mode) was done with the follow-up branch's build at
33b7272, which stacks the Gemma 4 PLE sidecar on this PR, and with Gemma 4 E4B, whose INT8 set is the token table from this PR plus the PLE table from the follow-up. The two tables were not swapped independently (no FP16-PLE-plus-INT8-token set was run), so the memory and fit numbers belong to the follow-up PR and are reported there (mihai-chiorean#1): both sets fit, with 3.9 GB available at the minimum for INT8 and 1.2 GB for FP16, with about 2 GB of other inference load present. What this PR can take from the run:embeddingLookupINT8 path from this PR ran on an Orin NX (Loaded INT8 embedding: [262144, 2560], scales: [262144]), on an engine built on a Jetson AGX Orin, through 24 greedy prompts, a 20-request short-prompt profile, 3 load-time runs and 40 requests of a soak that the device's 92 C thermal guard ended; no errors, and every generated text identical to the AGX Orin's for the same inputs.The unit-test filter was not run on the Orin NX (the device was only available for a short window and the GPU unit-test binaries were not part of the kit). The unit-test line for this PR remains the AGX Orin one above.
Orin NX 16 GB, second run: engines built on the device
The follow-up PLE branch (
33b7272, which stacks on this PR) was run again on a Jetson Orin NX 16 GB (JetPack 7.2, CUDA 13.2.86, TensorRT 10.16.2.10, 40 W), this time withllm_buildandvisual_buildrun on the Orin NX itself and no other inference load on the device. The INT8 set there is this PR's token table plus the follow-up's PLE table; the two were not swapped independently, so the memory table is in the follow-up PR. What applies to this PR:Loaded INT8 embedding: [262144, 2560], scales: [262144]) through 24 greedy prompts, short- and long-prompt profiles, a 100-request soak and the paired accuracy runs, with no errors.Method: MMLU and MMStar are the public benchmarks, prepared with
examples/accuracy/scripts/prepare_dataset.pyand scored with the letter parser fromexamples/accuracy/scripts/calculate_correctness.py. The subsets are the stratified, seed-0 samples described in the follow-up PR. On the Orin NX the requests were sent through the Python binding by a small driver that keeps the model loaded and pauses for cooling, not throughllm_inference; the request files are the same.This PR's unit tests were not run on the Orin NX; that line remains the AGX Orin one above.
Scope and remaining validation
llm_inferencedoes not expose logits.Qwen3OmniTTSRuntimeneeds engines.l0_pipeline_a30.ymlandl0_onnx_export_1.ymlentries were not run in NVIDIA's CI; the commands above are their manual equivalent.--fp8-embeddingis not usable on Jetson Orin. That was wrong: it ran end to end on the AGX Orin, as reported under Validation.🚀 Pull Request Checklist
✅ Pre-commit Checks
pre-commitby runningpip install pre-commit.pre-commit install.pre-commit run --all-filesand fixed any reported issues. (Every file changed by this PR passes all hooks. On currentmain, yapf and clang-format reformat 13 files that this PR does not touch, and the same 13 are the only files reformatted on this branch.)🧪 Tests
📄 Documentation
⚙️ Compatibility
write_runtime_artifacts,export_onnx,_export_llmand_export_diffusion_gemmaare identical tomain;int8_embeddingis keyword-only). Behaviour that does change, all verified againstmain: an FP16 table with a strayembedding_scaletensor now fails at load where it was ignored before;kernel::embeddingLookuprejects scales passed with an FP16 table where it ignored them; a table dtype other than FP16, FP8 or INT8 fails at load instead of in the kernel at the first request; the Qwen3-Omni Talker rejects a quantized Thinker sidecar at construction where it previously failed at the first lookup (embeddingLookupwas called without scales); the DFlash/DSpark fold error for a quantized sidecar now names the flag that produced it.Additional Information
Related issue: #188. This is the first of two PRs; the second adds the INT8 Gemma 4 per-layer-embedding sidecar (
ple_embedding.safetensors, one scale per row and layer) on top of this one. With this PR alone,--int8-embeddingon a Gemma 4 model quantizes the token embedding and leaves the PLE table FP16.The loader dtype validation is included here rather than filed separately because the INT8 branch has to enumerate the accepted dtypes anyway, and the new C++ tests for the INT8 sidecar exercise the same load path. The FP8 branch's checks are unchanged.
Alternatives considered: extending
--fp8-embeddingto the per-layer table would be the other way to quantize it; per-row, per-layer INT8 scales match that table's structure and reconstructed more closely on the token table measured here, and FP8 on the per-layer table was not measured. Packed INT4 sidecars would save more but need an unpacking kernel and an accuracy study.