Repository navigation
fix(security): validate checkpoint index tensors before native indexing (#3971) - #3988
Merged
Merged
Conversation
make_sequential() indexed a host histogram with the checkpoint's g_idx and wrote cpu_x_map[cpu_x_map_inv[row]] without bounds, giving a host heap write at a chosen offset. A short prefix-sum accumulator also truncated at 32768 rows per group. Validate g_idx (CPU, int32, length == height, 0 <= value < groups) at the make_q_matrix entry and in ExllamaV2Linear.post_init, use uint32_t for the prefix sum, and fail make_sequential() instead of writing out of range.
…3971) The escape index lives in the packed stream (g.lo0 when g.meta == 0) and was dereferenced as escapes[g.lo0] with no bound in the CUDA decode/GEMV/MMA/SM100 paths and the HIP decode/WMMA/MoE paths. A crafted checkpoint therefore read up to 64 GiB past the escape table. Thread num_escapes through decode_group/decode_group_any_lane and the linear fragment helpers, guard the lookup with g.lo0 < num_escapes (the embedding kernel already did this), and pass the per-expert local count in the MoE kernels. Validate the checkpoint once at load in NF12Weight.from_state_dict and NF12Linear.post_init, where the index is decoded from the packed stream.
…3971) moe_weight_view() checked only contiguity, dtype and E+1 length. Negative, decreasing, or out-of-table offsets let an expert's escape slice walk past the table. Validate non-negativity, monotonicity and offsets[E] <= escapes.size(0) in moe_weight_view(), and once at load in NF12MoEWeight.__post_init__.
…ing (#3971) validate_rotation_inputs() checked only device, dtype and rank. The fused rotation used checkpoint int16 pair values directly as row indices into the x_grp shared tile, so a value outside [0, group_size) read and wrote shared memory out of bounds. Validate the pair/theta/scale geometry at the op entry, validate pair values once at load in ParoLinear.post_init, and mask the pair into the group inside apply_one() as the last guard.
…#3971) The dequantize/linear kernels used the checkpoint's int32 outlier code as a row into outlier_centroids. The quantizer bounded it, but the loader checked only the shape of `indices`, so a crafted checkpoint read the codebook out of bounds. Check 0 <= outlier_indices < outlier_num_centroids in VPTQLinear._validate_loaded_state() and in both CUDA op entries.
reconstruct() computed cbi = K - 1 (+8 mcg / +16 mul1) and indexed the 24-entry reconstruct_kernel_instances array unchecked. K = 0 or cbi >= 24 called a garbage function pointer; K = 9..16 ran the wrong kernel. The GEMM path already enforces 1 <= K <= 8. Validate the range and the mcg/mul1 exclusion at the reconstruct op entry, and at load in LinearEXL3 and ExllamaV3Linear._stored_features.
) FloatX CPU dequantization took `% count` with count == 0 for an empty scale tensor, raising SIGFPE and killing the process. Reject an empty scale with a clear TORCH_CHECK in both scale-spec builders. EXL3 indexed MAX_DEVICES-sized arrays (DevCtx state, kernel_attr_set) with an unchecked device ordinal, so ordinal >= 16 wrote host memory out of bounds. Check the ordinal at every entry.
Complete the num_escapes plumbing for the MoE small-M core and the fused decode path, which use the shared WeightTraits fragments.
This was referenced Nov 17, 2026
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.
Fixes #3971
TL;DR
A crafted quantized checkpoint could put arbitrary integers into index tensors that native kernels used without bounds checks: ExLlamaV2
g_idx(host heap write), NF12 escape indices and MoE escape offsets (GPU OOB reads), ParoQuant rotation pairs (shared-memory OOB write), VPTQ outlier codes (codebook OOB read), EXL3 trellisK(unchecked function-pointer table), FloatX empty scales (SIGFPE), and EXL3 per-device tables (host OOB write).Every format now fails closed at load and again at the op entry, and the kernels keep a last-resort bound. 52 files, +959/-161, 9 commits on top of
00163850. No environment-variable switches, no dequantized weight caches, no unrelated refactors.Committed reference page:
docs/checkpoint-index-validation.md, linked fromREADME.md.1. The problem
Old flow (at
origin/main,00163850): checkpoint tensors flowed straight into native indexing.flowchart TD A["checkpoint tensors"] --> B["module load<br/>no index validation"] B --> C["ExllamaV2Linear.post_init"] B --> D["NF12Weight.from_state_dict"] B --> E["NF12MoEWeight"] B --> F["ParoLinear"] B --> G["VPTQLinear._validate_loaded_state"] B --> H["LinearEXL3"] C --> C1["make_q_matrix<br/>only int32 dtype check"] C1 --> C2["QMatrix.make_sequential"] C2 --> C3["cpu_g_idx_map[cpu_g_idx[i]]++<br/>short tmp = histogram count"] D --> D1["decode_group / gemv / mma<br/>__ldg(escapes + g.lo0)"] E --> E1["escape_offsets[e] unchecked"] F --> F1["rotate_kernel<br/>x_grp[i * ROW_STRIDE + m]"] G --> G1["vptq_kernel<br/>outlier_centroids[code * len + c]"] H --> H1["reconstruct_kernel_instances[K - 1]"] C3 -. "crafted g_idx" .-> X["host heap corruption"] D1 -. "lo0 past table" .-> Y["GPU OOB read up to ~64 GiB"] E1 -. "bad offsets" .-> Y F1 -. "pair outside group" .-> Z["shared-memory OOB write<br/>illegal address"] G1 -. "code past codebook" .-> Y H1 -. "K = 0 or K > 8" .-> W["garbage function pointer"] classDef failure fill:#ffe8e8,stroke:#b30000,color:#111; class X,Y,Z,W failure;Old mechanisms, with
file:lineevidence:origin/main)g_idxext_gptq.cpp:10only checked int32;q_matrix.cu:553calloc(groups, 4),:559cpu_g_idx_map[cpu_g_idx[i]]++,:582cpu_x_map[cpu_x_map_inv[row]] = rowshorttruncationq_matrix.cu:565short tmp = cpu_g_idx_map[i]; a group with >= 32768 rows made the prefix sum negativeg.lo0(CUDA)format.cuh:78,107__ldg(escapes + g.lo0);gemv.cu:159,mma.cuh:523,720,868,1034,sm100/large_m_tc_kernel.cuh:670g.lo0(HIP)nf12_format_hip.cuh:134-145escapes[g.lo0]escape_offsetsnf12/csrc/torch/ops.cpp:484-517checked only contiguity/int64/E+1pairsrotation.cu:1003-1030checked device/dtype/rank;rotation.cuh:73-81,148-160used int16 pairs as shared-memory rowsoutlier_indicesvptq_kernel.cu:428,491passed any int32 to:73code * outlier_vector_len; loader checked only shapeKreconstruct.cu:100checked onlypacked.size(2);:124-130indexed a 24-entrystd::arrayfloatx_cpu.cpp:205,237,244,261took% countwithcount == 0exl3_devctx.cu:25-68,exl3_gemm.cu:37,131-143indexedMAX_DEVICESarrays unchecked2. The new flow
flowchart TD A["checkpoint tensors"] --> B{"module load"} B --> C["ExllamaV2Linear.post_init"] B --> D["NF12Weight.from_state_dict<br/>NF12Linear.post_init"] B --> E["NF12MoEWeight.__post_init__"] B --> F["ParoLinear.post_init"] B --> G["VPTQLinear._validate_loaded_state"] B --> H["LinearEXL3.__init__<br/>ExllamaV3Linear._stored_features"] C --> C1["validate_g_idx_bounds<br/>allow_negative_wrap=False"] D --> D1["validate_escape_indices"] E --> E1["escape_offsets range + monotonicity"] F --> F1["validate_rotation_buffers"] G --> G1["outlier_indices vs outlier_num_centroids"] H --> H1["validate_trellis_k"] C1 --> OK["module ready"] D1 --> OK E1 --> OK F1 --> OK G1 --> OK H1 --> OK C1 -. "outside [0, groups)" .-> X["ValueError<br/>checkpoint rejected before any op runs"] D1 -. "lo0 >= escapes rows" .-> X E1 -. "negative / decreasing / past table" .-> X F1 -. "outside [0, group_size)" .-> X G1 -. "outside codebook" .-> X H1 -. "K outside [1, 8] or mcg and mul1" .-> X OK --> OP{"direct op call?"} OP -- "yes" --> R["C++ op entry TORCH_CHECK"] OP -- "no" --> K["kernel last-resort bound"] R -. "invalid" .-> X2["RuntimeError<br/>no memory touched"] R --> K classDef failure fill:#ffe8e8,stroke:#b30000,color:#111; class X,X2 failure;3. Per-format detail
ExLlamaV2 act-order
make_sequential()runs at load time (post_init->_ensure_q_handle->exllamav2_make_q_matrix), so no forward pass is needed to trigger the write.sequenceDiagram participant L as ExllamaV2Linear.post_init participant P as validate_g_idx_bounds participant E as make_q_matrix participant M as QMatrix.make_sequential L->>P: g_idx, scales, allow_negative_wrap=False P-->>L: ValueError if outside [0, groups) L->>E: qweight, qzeros, scales, g_idx.cpu() E->>E: TORCH_CHECK CPU / int32 / numel == height / range E->>M: cpu_g_idx M->>M: bound histogram, uint32_t prefix sum, target_row < height M-->>E: false on failure E-->>L: TORCH_CHECK failed to build act-order row mappingq_matrix.cunow usesuint32_t tmp/acc(notshort), rejectsacc != height, bounds everycpu_x_map/cpu_x_map_invwrite, and frees on failure.ext_gptq.cpprejects a CUDA, short, or out-of-rangeg_idxbeforeQMatrixis built and raises ifm->failed.NF12 escapes
flowchart LR A["nf12_packed + nf12_escapes"] --> B["validate_escape_indices"] B --> C{"max lo0 where meta == 0 < escapes.size 0"} C -- "false" --> X["ValueError"] C -- "true" --> D["weight_view / moe_weight_view"] D --> E["decode_group / decode_group_any_lane"] E --> F{"g.meta == 0 and g.lo0 < num_escapes"} F -- "yes" --> G["__ldg(escapes + g.lo0)"] F -- "no" --> H["keep decode_bulk result"] classDef failure fill:#ffe8e8,stroke:#b30000,color:#111; class X failure;num_escapesis threaded through every CUDA and HIP decode/linear/MoE kernel and fused decode. The MoE decode kernels pass each expert's local slice length (escape_offsets[e+1] - escape_offsets[e]).4. Failure and ambiguity contract
stateDiagram-v2 state "checkpoint loaded" as Loaded state "validated" as Valid state "rejected at load" as LoadFail state "rejected at op entry" as OpFail state "kernel clamped" as Clamped [*] --> Loaded Loaded --> LoadFail: bad g_idx / escape / offsets / pairs / outlier / K Loaded --> Valid: all index tensors in range Valid --> OpFail: direct caller passes bad tensor Valid --> Clamped: kernel sees a missed bad index Clamped --> [*] OpFail --> [*] LoadFail --> [*]g_idxvalue outside[0, groups)ValueErrorat load,TORCH_CHECKat op entryshortprefix sum goes negativeuint32_tprefix sum,acc == heightchecklo0past escape tableValueErrorat load, kernel clamps todecode_bulkescape_offsetsnegative/decreasing/past tableValueErrorat load,TORCH_CHECKat op entry[0, group_size)ValueErrorat load, kernel masks with% GROUP_SIZEValueErrorat load,TORCH_CHECKat op entryK = 0orK > 8, ormcg and mul1ValueErrorat load,TORCH_CHECKat op entryTORCH_CHECK scale tensor must not be emptyTORCH_CHECKbefore everyMAX_DEVICESarray5. Change inventory
_g_idx.py,exllamav2.py,ext_gptq.cpp,q_matrix.cug_idxchecks,uint32_tprefix sum, bounded remap writesformat.cuh,gemv.cu,mma.cuh,sm100/...,decode.cu,moe/small.cu,torch/ops.cpp,api.py,moe.pynum_escapesplumbing, MoE offset validation, escape-index load checknf12_format_hip.cuh,nf12_decode.hip,nf12_moe.hip,nf12_wmma.hip,nf12_torch.cpprotation.cu,rotation.cuh,utils/paroquant.py,paroquant.py% GROUP_SIZEmaskvptq_kernel.cu,vptq_torch.pytrellis.py,exl3.py,exllamav3.py,reconstruct.cu,exl3_devctx.cu,exl3_gemm.cuvalidate_trellis_k,TORCH_CHECKonK, device-ordinal boundsfloatx_cpu.cppdocs/checkpoint-index-validation.md,README.md, 7 test files6. Tests / guarantees
tests/test_exllamav2_g_idx_bounds.py[0, groups)only; Triton keeps its negative-wrap contracttests/test_nf12_escape_bounds.py< escapes.size(0); empty table rejects any escapetests/test_nf12_moe_offsets.pyoffsets[-1] <= escapes.size(0)tests/test_paroquant_rotation_pairs.py[0, group_size), theta/scales geometrytests/test_vptq_outlier_bounds.py[0, outlier_num_centroids)tests/test_exl3_trellis_k.pyKin[1, 8], never bothmcgandmul1tests/test_floatx_cpu_empty_scale.pyRuntimeErrorinstead of SIGFPE7. Validation
Hardware: NVIDIA RTX 4090
GPU-d458708b-c760-bbf1-08fb-8b8803a2157d(pinned by UUID; the RTX 5090 was never selected) and AMD R9700HIP_VISIBLE_DEVICES=2.New tests, both venvs:
Affected existing suites (CUDA):
test_gptqmodel_nf12_api.py test_nf12_codec.py test_nf12_runtime_load.py test_validate_nf12.py test_paroquant.py test_paroquant_rotation_lifecycle.py test_vptq.py test_exllamav3.py test_exllamav3_cpu.py test_ret_idx_group_order.py test_gptq_static_group_order.py->
766 passed, 12 skipped, 16 failed. All 16 reproduce on a cleanorigin/mainworktree (15 identical failures:native backend unavailable/resolve_module_configmock gaps / a 1e-6 gradient tolerance); the one VPTQ numeric case passed on retry and on the baseline. None touch the changed code paths.Affected existing suites (ROCm): same files ->
574 passed, 203 skipped, 17 failed; all 17 reproduce identically on cleanorigin/main. HIP NF12 suites:tests/test_nf12_hip_embedding.py tests/test_nf12_hip_review_contracts.py->113 passed, 2 skipped.Lint gate:
That error is present on
origin/main(00163850) and is not touched by this PR; every file changed here is clean.Fail-before / pass-after
origin/mainand movingtrellis.pyaside, then running the 7 new tests:16 failed, 2 passed, 2 errors(collection errors for the absentvalidate_rotation_buffers/validate_trellis_k). Restored tree:31 passed.shorttruncation (native).height=40000,groups=2, group 0 = 33000 rows, validg_idx:origin/main->Segmentation fault(exit 139) inmake_sequential;this branch -> handle built successfully.
origin/main->CUDA error: an illegal memory access was encountered;this branch -> finite
[16, 64]decode.escape_offsets=[0, 5]with a 4-row table:this branch ->
RuntimeError: nf12: escape_offsets[E] = 5 exceeds the 4-row escape table; valid[0, 4]decodes.group_size=128:origin/main->CUDA error: an illegal memory access was encountered;this branch -> finite output (masked).
K(native).K = 0, 9, 16andmcg+mul1->RuntimeError: EXL3 reconstruct requires 1 <= K <= 8 ...;K = 2completes.RuntimeError: VPTQ CUDA outlier index is outside [0, 3).origin/mainextension ->Fatal Python error: Floating-point exception(exit 136); this branch ->RuntimeError: scale tensor must not be empty.Native extensions actually built and run from this tree: ExLlamaV2 CUDA, NF12 CUDA, NF12 HIP, ParoQuant CUDA, VPTQ CUDA, EXL3 CUDA, FloatX CPU. No claim is made for a native path that was not built and executed.
8. Reviewer notes
g_idx(the no-op act-order case); the C++ op entry still checks CPU/length/range, so a direct caller is covered.ext_gptq.cppvalidatesg_idxwhenever it is defined and the matrix is not already shuffled; for the non-GPTQ (q_scale) layout that is a consistency check, not a consumed tensor.E + 1int64 values to the host; it is a one-time-per-call cost, not a per-element scan.