Repository navigation
feat: Add an INT8 Gemma 4 PLE runtime sidecar - #249
Closed
mihai-chiorean wants to merge 2 commits into
Closed
mihai-chiorean wants to merge 2 commits into
mihai-chiorean wants to merge 2 commits into
Conversation
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]>
With `--int8-embedding`, a Gemma 4 E-model export also writes ple_embedding.safetensors as symmetric INT8 with one FP32 scale per vocabulary row and layer input, so an outlier in one layer does not cost precision in the others. Gemma4EmbeddingPreprocessor loads `weight` plus `weight_scale`, validates the scale dtype and shape against the table, and gemma4PleGather dequantizes only the gathered rows into the FP16 per-layer inputs. FP16 and BF16 PLE sidecars load and gather unchanged. Signed-off-by: Mihai Chiorean <[email protected]>
Collaborator
|
Thanks @mihai-chiorean . This MR is recognized in our latest release/0.12.0 notes. We have integrated both quantize time embedding quantization and build time embedding quantization, and disk offloading to support PLE well. Thanks a lot for your contribution! |
Author
|
Thanks @nvluxiaoz, and thank you for the credit in the 0.12.0 release notes. I appreciate it. I tried 0.12.0 on a Jetson AGX Orin with Gemma 4 E2B. The cached PLE residency does what this PR was after: the per-layer table no longer sits in memory (about 5.4 GiB down to 2.0 GiB of system memory during a run, same replies), and |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
What does this PR do?
Type of change: new feature
This is the second of the two PRs for #188. It is stacked on #235 (the INT8 token-embedding sidecar), so until that PR lands the diff here shows two commits:
cadb959belongs to that PR and only33b7272belongs to this one. The second commit alone can be read at https://github.com/mihai-chiorean/TensorRT-Edge-LLM/pull/1/files (13 files). I will rebase ontomainonce the first PR lands, and I am keeping this one a draft until then.Overview: Extends
--int8-embeddingto the Gemma 4 per-layer embedding (PLE) table.--int8-embeddingnow also writesple_embedding.safetensorsas symmetric INT8 (weight,[vocab, layers * ple_hidden]) with FP32 scalesweight_scaleof shape[vocab, layers]: one scale per vocabulary row and per layer input, kept two-dimensional also for a single layer. A PLE row is the concatenation of every layer's input, so a single row scale would let an outlier in one layer cost precision in all the others. The quantizer gains a keyword-onlynum_groupsparameter; the token embedding keeps the one-scale-per-row contract and metadata format (int8_symmetric_per_row) of feat: Add an INT8 token-embedding runtime sidecar #235, the PLE sidecar recordsint8_symmetric_column_groups_per_row. Unlike--fp8-embedding, which stores FP8 values with block scales for the token embedding only, this format covers the per-layer table, which has no FP8 option.Gemma4EmbeddingPreprocessorloadsweightplusweight_scale, validates the scale dtype (FP32) and shape ([vocab, num_ple_inputs]) against the table at construction, and keeps its FP16 output buffer.gemma4PleGathertakes an optional scales tensor as a new last parameter with a default (existing callers compile unchanged) and dispatches togemma4PleGatherInt8Kernel, which dequantizes only the gathered rows into the FP16 per-layer inputs. As in the FP16/BF16 PLE gather, every image/audio placeholder position and out-of-vocabulary id is written as zeros (the PLE table has no multimodal rows; this differs from the token-embedding lookup, where placeholders receive encoder features).pleHiddenSizemust be a multiple of 8, which the launcher checks. FP16/BF16 PLE sidecars load and gather exactly as before: an FP16/BF16 table with aweight_scaletensor, or an INT8 table without one, is rejected. A checkpoint-backed INT8 PLE table (direct checkpoint builder path) is rejected because that path owns no scales.gemma4PleGather's rejections (scales with an FP16 table, INT8 without scales, 1-D scales, wrong columns, non-FP16 output).tests/defsalso checks the INT8 PLE sidecar for Gemma 4 E-models, and the test lists gaintest_checkpoint_export[gemma-4-E2B-it-fp16-int8emb]inl0_onnx_export_1.ymlplus the matchingtest_engine_buildandtest_inference[...-int8emb-llm_basic]cases next to the existing Gemma 4 E2B FP16 smoke cases inl0_pipeline_thor_2_trt11.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 with Gemma 4 E4B and E2B (below).Memory for Gemma 4 E4B (vocabulary 262,144): PLE
[262144, 10752]5,637,144,576 bytes FP16 -> 2,862,612,480 bytes INT8 plus scales; together with the token embedding from the first PR, 6,979,321,856 -> 3,534,749,696 bytes.Usage
ple_embedding.safetensorsthen holds:weight[vocab, layers * ple_hidden]weight_scale[vocab, layers]The runtime selects the INT8 path from the
weightdtype; no runtime flag is needed.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
33b727203027e3ffbc54d5833042ca568561a48a(on top of the first PR'scadb9590) built natively with-DBUILD_UNIT_TESTS=ON, baseline0f52705where stated.unitTest*binaries were last run in full at93f0582(11 of 12 exit 0: unitTestCommon 149 passed; unitTestContextCache 203; unitTestCuteDslKernels 59; unitTestExamples 3; unitTestKernelsAttention 108 passed, 24 skipped (FP8 decode kernels); unitTestKernelsMisc 340 passed, 23 skipped, 1 failed; unitTestKernelsMoe 41 passed, 24 skipped; unitTestKernelsSpeculative 114; unitTestPlugins 17 passed, 1 skipped; unitTestRuntime 594 passed, 1 skipped; unitTestRuntimeState 113; unitTestScheduler 59). The one failure,RopePackedFusedNorm.PostRopeAccuracy, is a pre-existing flaky test with unseeded random inputs (0 failures in 30 repeats on this binary, 1 in 30 on the first PR's;posEncodingis untouched by both PRs). The only binary whose sources changed since then is unitTestKernelsMisc; at the final head it was rebuilt and run in full: 347 passed, 23 skipped, 0 failed (370 ran; the flaky RoPE test passed in this run). The embedding/PLE filter (--gtest_filter='*Embedding*:*Int8*:*Ple*:*Fp16Lookup*:*SidecarLoader*:*GatherRejects*'): 40 passed, includingDequantizesInt8RowsAndZeroFillsSpecialTokens,DequantizesInt8RowsAtGemma4E4BGeometry(42 layers x 256, exact FP16 comparison),DequantizesInt8RowsWithPartialFinalIteration(2056),Int8SidecarLoadsThroughPreprocessor,Int8SidecarWithOneLayerLoadsThroughPreprocessor,Int8PleSidecarLoaderRejectsMalformedFilesandGatherRejectsMismatchedScalesAndOutputTypes.google/gemma-4-E4B-it, W4A16 AWQ checkpoint (quant_algo W4A16_AWQ, group size 128, LM head FP16), text model exported on the device twice with this branch's exporter, with and without--int8-embedding(--skip-visual);model.onnxSHA256b4c5c5897652d1761b2d41d75fd53f6e486a832899b45caf4b129b372985eefaandmodel.onnx.dataSHA2562033965e65ec6bc3d4af8c047d94e2c3945eb8d3bd4735f01a993ad2029a7172identical for both exports; only the two sidecars differ. Both built withllm_build --maxBatchSize 1 --maxInputLen 2048 --maxKVCacheCapacity 4096and run withllm_inference(temperature 0, 64 new tokens). INT8 engine log:Loaded INT8 embedding: [262144, 2560], scales: [262144]andInitialized Gemma4 PLE preprocessor: table=[262144, 10752] outputBuffer=[42, 1, 2048, 256]. The vision tower was exported separately (--skip-llm) and built withvisual_buildfor the image runs below.examples/multimodal/picsx 2 questions, greedy, 48 new tokens, accuracy engines plus the visual engine): 7 of 8 token-identical, 261 (FP16) / 258 (INT8) generated tokens; the one divergence is a different wording of the same description. Image placeholder positions in the PLE gather are zero-filled in both arms.0f52705runtime vs this branch 24 of 24 identical.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 53.0 % (265/500), INT8 53.0 % (265/500); identical predictions on 489/500; flips 1 (FP16-only correct) / 1 (INT8-only correct), exact McNemar p = 1.0; 428/500 (FP16) and 429/500 (INT8) answers parsed to a letter, the rest are explanations cut by the budget. At 8 new tokens the same subset gives 254 / 255 with 497/500 identical (389/500 parsed). Wall time per arm 437 s / 412 s.33b7272; 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): FP16 64.6 % (323/500), INT8 64.6 % (323/500); identical predictions and identical output text on 500/500; flips 0 / 0, exact McNemar p = 1.0; 500/500 answers parsed in both arms. Wall time per arm 212 s. In this form the model answers with the letter instead of starting an explanation, which is where the parse misses and the 11 differing predictions of the run above came from.prepare_dataset.py --dataset MMStarwith the instruction "Answer with the option's letter from the given choices directly. Reply with the letter only." as a system turn, chat template, thinking off (the template's default), greedy, 32 new tokens, visual engine from this branch's exporter; scored withcalculate_correctness.pyas shipped): FP16 38.7 % (116/300), INT8 38.3 % (115/300); identical predictions on 299/300; flips 1 (FP16-only correct) / 0, exact McNemar p = 1.0; the parser scores 299/300 answers in both arms. With the same instruction appended to the user message instead, the model answers two thirds of the items with reasoning that reaches no letter within 8 or 128 new tokens (177/300 and 178/300 scored; FP16 87, INT8 86, identical 295/300 and 256/300). Wall time per arm 151 s.llm_inferenceexit 1 before any request: INT32 PLE table ->gemma4EmbeddingPreprocessor.cpp:91: PLE table must be FP16, BF16, or INT8; INT8 PLE without scales ->:73: INT8 ple_embedding.safetensors must contain exactly weight and weight_scale; FP16 PLE with aweight_scaletensor ->:79: FP16/BF16 ple_embedding.safetensors must contain exactly one tensor named weight; INT8 PLE with[vocab]scales ->:97: INT8 PLE scales must be 2D [vocab, num_layers].llm_benchcannot run Gemma 4 engines (bindingple_token_embeds_0is not handled; the same failure for FP16 and INT8, llm_bench crashes on Gemma-4 engines due to missing PLE bindings (ple_token_embeds_0) #230), so speed comes fromllm_inference --dumpProfile.tests/python-unittests/test_embedding_quantization.pyandtest_export_embedding_flags.py, 35 passed; the 9 cases added by this PR fail against the first PR's sources, the 26 shared cases pass there.Memory, Gemma 4 E4B (0.5 s sampler of
MemTotal - MemAvailable,MemFreeand process VmRSS during the 24-prompt run;--dumpProfilepeaks; the run was repeated with both sidecar sets already in the page cache, which is the state reported here):embedding.safetensorsple_embedding.safetensorspeak_gpu_memory(cudaMemGetInfofree-memory delta, tool unit "MB")The profiler's figure is the drop of
cudaMemGetInfofree memory from the start of the run to its minimum; on unified memory that drop also contains the page cache filled while the mmap'd sidecar files are first read, so a cold first run reported 10156 (FP16) vs 4536 (INT8). The warm-cache repeat above and theMemAvailable-based system figure agree with each other and with the file-size difference.Second model, Gemma 4 E2B (W4A16 AWQ, 35 layers, hidden 1536, PLE 256 per layer; same device, same engine parameters, candidate
93f0582build; cosine over all 262,144 token rows and 8,192 seeded PLE rows):--maxInputLen 8192 --maxKVCacheCapacity 10240Quality of the E4B sidecars (FP16 table vs dequantized INT8, product rounded to FP16):
Speed, E4B (
llm_inference --dumpProfile, 20 identical requests after 2 warmup, GPU stage times; separately built engines):Load time, E4B, process start to "Runtime initialized", 5 runs (run 1 after other work on the device, runs 2-5 warm): FP16 15.77 s then 6.93-7.61 s; INT8 9.40 s then 5.34-5.57 s.
Reproduce:
Validation on a 16 GB Jetson Orin NX
Jetson Orin NX 16 GB, JetPack 7.2 (L4T R39.2.1), CUDA 13.2.86, TensorRT 10.16.2.10, 40 W power mode, 2 GB swap; binaries and plugin from this branch at
33b727203027e3ffbc54d5833042ca568561a48a, built natively on a Jetson AGX Orin. The Gemma 4 E4B W4A16 engine (llm_build --maxBatchSize 1 --maxInputLen 2048 --maxKVCacheCapacity 4096,llm.engine3,432,620,228 bytes, the one validated above) was also built on the AGX Orin and copied over; one engine served both sidecar sets, since the ONNX graph does not contain the tables. TensorRT accepted it with two warnings on every load, quoted verbatim:No deadlock or error followed in any of the 16 runs, and the generated text is identical to the AGX Orin's for every prompt that completed (12 of 12, both sidecar sets), so the INT8-vs-FP16 comparison on this device is on equal footing; the absolute latency figures are from a plan built for another device and should be read as provisional until an engine is built on an Orin NX (
llm_buildfor E4B peaked near 12 GiB on the AGX Orin, which this device could not spare safely during the window).The device was in use by another deployment: two other inference services kept running throughout (about 2 GB of RAM between them), and that deployment's own 10.7 GB LLM service was stopped for the 17-minute test window. Memory figures are therefore "with about 2 GB of other inference load present". Every test process ran with
oom_score_adj1000 under a 0.5 s watchdog that kills it below 500 MBMemAvailableor at 92 C junction temperature.Memory (MiB;
MemAvailablefrom/proc/meminfo, processVmRSS, profilepeak_gpu_memory_mb=cuda_free_memory_delta):MemAvailablebefore the processVmRSSBoth sets fit. The difference in peak drop between the two runs (5.2 GB) is larger than the 3.2 GiB difference between the sidecar files: the FP16 run started from a cold page cache and read 7 GB of sidecar files for the first time, and on the AGX Orin the same comparison with a warm cache gave 3.0 GB. I did not separate the two effects on this device, so the figure to rely on here is the minimum available memory observed, 3,947 MiB with INT8 and 1,182 MiB with FP16. The FP16 run was not stopped by memory: the 500 MB guard never fired and
cudaMallocnever failed.Latency (same engine, greedy, 64 new tokens; profile JSON after 2 warm-up runs where stated):
No decode-speed difference between the two sidecar sets at this resolution (the sidecar is read once per token for a handful of rows). The long-prompt profile (20 x 2,000-token prompt) and the FP16 short-prompt profile could not be completed: the device started every run at 79–81 C junction temperature and reached the 92 C guard after 25–130 s of sustained generation (INT8 long x20 stopped at 1/20, INT8 100-request soak at 40/100 after 63 s with no errors, FP16 24 prompts at 14/24, FP16 short x20 at 18/20). The AGX Orin numbers above remain the only long-prompt and soak figures.
Output agreement, FP16 vs INT8, 12 prompts (both completed on this device): 10 of 12 identical; the two divergences are at token 8 (prompt 7: 23 vs 21 tokens) and token 54 (prompt 9: 64 vs 64), 581 re-tokenized positions compared, 588 vs 586 tokens generated. The AGX Orin gave the same 10 of 12 on these prompts, and the text from this device is identical to the AGX Orin's for all 12 prompts with the FP16 set and all 12 with the INT8 set. Of the remaining 12 prompts, FP16 completed 11 before the thermal guard and the file was not written; INT8 completed all 24.
Load time (first log line to "Runtime initialized", 3 runs each, warm page cache): INT8 10.5 / 11.4 / 11.5 s (process wall 14.1–15.9 s); FP16 21.7 / 23.7 / 24.8 s (wall 27.1–35.7 s). The FP16 PLE table alone is 5.6 GB to read and stage.
Temperatures: junction 74 C before the window, 79–81 C between runs with the two other inference services, 91–94 C under sustained generation (the guard fired at 92 C, 94.4 C was the highest sample). Power mode 40 W throughout, not changed.
Scope of this section. Both sidecar sets fit a 16 GB Orin NX with about 2 GB of other inference load present: INT8 with 3.9 GB available at the minimum, FP16 with 1.2 GB. Not covered here: the long-prompt profile, a completed soak (the thermal guard ended both), and an engine built on the Orin NX itself (the AGX-built plan ran correctly but with the TensorRT device-mismatch warning quoted above). The FP16-vs-INT8 agreement set is 12 prompts on this device; the other 12 are covered on the AGX Orin.
Orin NX 16 GB, second run: engines built on the device
Jetson Orin NX 16 GB, JetPack 7.2 (L4T R39.2.1), CUDA 13.2.86, TensorRT 10.16.2.10, 40 W power mode, this branch at
33b7272. Unlike the earlier Orin NX numbers above (engine built on an AGX Orin, about 2 GB of other inference load present), herellm_buildandvisual_buildran on the Orin NX itself and no other inference load was on the device. Gemma 4 E4B W4A16,--maxInputLen 3072 --maxKVCacheCapacity 3328. One engine served both sidecar sets; the two arms differ only in the two sidecar files.Build on the device:
llm_build227 s, peak RSS 12,250 MiB;visual_build533 s, peak RSS 3,080 MiB.Memory and load
MemAvailableduring any runSpeed (greedy, 19-token prompt x20, 2 warm-up runs)
The engine built on the device decodes about 1.46x faster than the AGX-built plan used in the earlier Orin NX run (41.1 vs 60.0 ms/token), so the earlier absolute speed figures should not be read as this device's speed.
Accuracy, paired (same seeded subsets and harness as the AGX Orin section, letter instruction in a system turn, 16 new tokens, greedy)
On the one MMLU question where the arms differ, both are wrong. The Orin NX INT8 predictions equal the AGX Orin INT8 predictions on all 500 MMLU questions.
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 AGX Orin section. 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.Output agreement, 24 greedy prompts, 64 new tokens: 22 of 24 identical between the FP16 and INT8 sets.
Other INT8 runs that completed: 846-token prompt x20 (prefill 778.7 ms), and a 100-request soak with no errors.
Not covered: the FP16 long-prompt profile and FP16 soak. At 40 W the board reaches my 88 C stop limit under sustained generation, so the accuracy runs were paced with cooling pauses and those two FP16 runs were cut short by heat, not memory.
Scope and remaining validation
93f0582); no engine could be built on that device with its TensorRT, so no inference numbers from it.llm_inferencedoes not expose logits.Qwen3OmniTTSRuntimeneeds engines.llm_benchprefill/decode micro-benchmarks are not available for Gemma 4 engines (llm_bench crashes on Gemma-4 engines due to missing PLE bindings (ple_token_embeds_0) #230).l0_pipeline_thor_2_trt11.ymlandl0_onnx_export_1.ymlentries were not run in NVIDIA's CI; the commands above are their manual equivalent.--fp8-embeddingran end to end on the AGX Orin (see feat: Add an INT8 token-embedding runtime sidecar #235). It covers the token embedding only; there is no FP8 option for the PLE table.🚀 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
RopePackedFusedNorm.PostRopeAccuracynoted; the three new CI test-list entries have not run in NVIDIA's CI.)📄 Documentation
⚙️ Compatibility
gemma4PleGathergains a trailing defaulted parameter;quantize_embedding_to_int8gains a keyword-only one). Behaviour that does change, all verified: an FP16/BF16 PLE table with a strayweight_scaletensor now fails at construction where the extra tensor was previously rejected by the "exactly one tensor" check with a different message; an INT8 PLE table is accepted where it was previously rejected; a checkpoint-backed INT8 PLE table is rejected;gemma4PleGatherrejects scales passed with an FP16/BF16 table.Additional Information
Related issue: #188. The first PR is #235.
Two implementation notes:
pleHiddenSize / 8vectors rounded up to whole warps, at most 256 threads) instead of a fixed 256 threads, because for Gemma 4 E4B a slice is 256 elements, i.e. 32 vectors, and a 256-thread block would leave seven of its eight warps idle. The existing FP16/BF16 launcher is not changed.--fp8-embeddingpass-through that my fork added totests/defs/test_checkpoint_export.pyis not included; it is unrelated to this change.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 in the first PR, and FP8 on the per-layer table was not measured.