Skip to content

fix(security): validate checkpoint index tensors before native indexing (#3971) - #3988

Merged
Qubitium merged 9 commits into
mainfrom
fix/issue-3971
Nov 14, 2026
Merged

Qubitium merged 9 commits into
mainfrom
fix/issue-3971

Conversation

@Qubitium

Copy link
Copy Markdown
Collaborator

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 trellis K (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 from README.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;
Loading

Old mechanisms, with file:line evidence:

Sink Old behaviour (origin/main)
ExLlamaV2 g_idx ext_gptq.cpp:10 only checked int32; q_matrix.cu:553 calloc(groups, 4), :559 cpu_g_idx_map[cpu_g_idx[i]]++, :582 cpu_x_map[cpu_x_map_inv[row]] = row
ExLlamaV2 short truncation q_matrix.cu:565 short tmp = cpu_g_idx_map[i]; a group with >= 32768 rows made the prefix sum negative
NF12 g.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:670
NF12 g.lo0 (HIP) nf12_format_hip.cuh:134-145 escapes[g.lo0]
NF12 MoE escape_offsets nf12/csrc/torch/ops.cpp:484-517 checked only contiguity/int64/E+1
ParoQuant pairs rotation.cu:1003-1030 checked device/dtype/rank; rotation.cuh:73-81,148-160 used int16 pairs as shared-memory rows
VPTQ outlier_indices vptq_kernel.cu:428,491 passed any int32 to :73 code * outlier_vector_len; loader checked only shape
EXL3 trellis K reconstruct.cu:100 checked only packed.size(2); :124-130 indexed a 24-entry std::array
FloatX empty scale floatx_cpu.cpp:205,237,244,261 took % count with count == 0
EXL3 device tables exl3_devctx.cu:25-68, exl3_gemm.cu:37,131-143 indexed MAX_DEVICES arrays unchecked

2. 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;
Loading

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 mapping
Loading

q_matrix.cu now uses uint32_t tmp/acc (not short), rejects acc != height, bounds every cpu_x_map/cpu_x_map_inv write, and frees on failure. ext_gptq.cpp rejects a CUDA, short, or out-of-range g_idx before QMatrix is built and raises if m->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;
Loading

num_escapes is 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 --> [*]
Loading
Situation Before After
g_idx value outside [0, groups) host heap write at chosen offset ValueError at load, TORCH_CHECK at op entry
one group holds >= 32768 rows short prefix sum goes negative uint32_t prefix sum, acc == height check
NF12 lo0 past escape table GPU OOB read ValueError at load, kernel clamps to decode_bulk
MoE escape_offsets negative/decreasing/past table OOB expert slice ValueError at load, TORCH_CHECK at op entry
ParoQuant pair outside [0, group_size) shared-memory OOB write ValueError at load, kernel masks with % GROUP_SIZE
VPTQ outlier code outside codebook codebook OOB read ValueError at load, TORCH_CHECK at op entry
EXL3 K = 0 or K > 8, or mcg and mul1 garbage function pointer ValueError at load, TORCH_CHECK at op entry
FloatX empty scale SIGFPE TORCH_CHECK scale tensor must not be empty
EXL3 device ordinal >= 16 host OOB write TORCH_CHECK before every MAX_DEVICES array

5. Change inventory

Area Files Purpose
ExLlamaV2 _g_idx.py, exllamav2.py, ext_gptq.cpp, q_matrix.cu load + op-entry g_idx checks, uint32_t prefix sum, bounded remap writes
NF12 CUDA format.cuh, gemv.cu, mma.cuh, sm100/..., decode.cu, moe/small.cu, torch/ops.cpp, api.py, moe.py num_escapes plumbing, MoE offset validation, escape-index load check
NF12 HIP nf12_format_hip.cuh, nf12_decode.hip, nf12_moe.hip, nf12_wmma.hip, nf12_torch.cpp same bounds on the ROCm path
ParoQuant rotation.cu, rotation.cuh, utils/paroquant.py, paroquant.py pair/theta/scale geometry checks, % GROUP_SIZE mask
VPTQ vptq_kernel.cu, vptq_torch.py load-time and op-entry outlier range checks
EXL3 trellis.py, exl3.py, exllamav3.py, reconstruct.cu, exl3_devctx.cu, exl3_gemm.cu validate_trellis_k, TORCH_CHECK on K, device-ordinal bounds
FloatX floatx_cpu.cpp reject empty 1D/2D scale specs
Docs/tests docs/checkpoint-index-validation.md, README.md, 7 test files reference page + regression tests

6. Tests / guarantees

Test Invariant
tests/test_exllamav2_g_idx_bounds.py ExLlamaV2 accepts [0, groups) only; Triton keeps its negative-wrap contract
tests/test_nf12_escape_bounds.py escape index must be < escapes.size(0); empty table rejects any escape
tests/test_nf12_moe_offsets.py offsets non-negative, non-decreasing, offsets[-1] <= escapes.size(0)
tests/test_paroquant_rotation_pairs.py pairs in [0, group_size), theta/scales geometry
tests/test_vptq_outlier_bounds.py outlier code in [0, outlier_num_centroids)
tests/test_exl3_trellis_k.py K in [1, 8], never both mcg and mul1
tests/test_floatx_cpu_empty_scale.py empty scale raises RuntimeError instead of SIGFPE

7. Validation

Hardware: NVIDIA RTX 4090 GPU-d458708b-c760-bbf1-08fb-8b8803a2157d (pinned by UUID; the RTX 5090 was never selected) and AMD R9700 HIP_VISIBLE_DEVICES=2.

New tests, both venvs:

CUDA: CUDA_VISIBLE_DEVICES=GPU-d458708b-c760-bbf1-08fb-8b8803a2157d PYTHONPATH=$PWD /opt/venvs/cu130t/bin/python -m pytest -q tests/test_exllamav2_g_idx_bounds.py tests/test_nf12_escape_bounds.py tests/test_nf12_moe_offsets.py tests/test_paroquant_rotation_pairs.py tests/test_vptq_outlier_bounds.py tests/test_exl3_trellis_k.py tests/test_floatx_cpu_empty_scale.py
  -> 31 passed
ROCm: HIP_VISIBLE_DEVICES=2 PYTHONPATH=$PWD /opt/venvs/rocm101t/bin/python -m pytest -q <same files>
  -> 31 passed

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 clean origin/main worktree (15 identical failures: native backend unavailable / resolve_module_config mock 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 clean origin/main. HIP NF12 suites: tests/test_nf12_hip_embedding.py tests/test_nf12_hip_review_contracts.py -> 113 passed, 2 skipped.

Lint gate:

ruff check gptqmodel docs/eora tests setup.py
  -> 1 error: F401 audioread imported but unused (gptqmodel/utils/audio.py:16)

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

  1. Load-time validators. Reverting the 10 Python validator/loader files to origin/main and moving trellis.py aside, then running the 7 new tests:
    16 failed, 2 passed, 2 errors (collection errors for the absent validate_rotation_buffers / validate_trellis_k). Restored tree: 31 passed.
  2. ExLlamaV2 short truncation (native). height=40000, groups=2, group 0 = 33000 rows, valid g_idx:
    origin/main -> Segmentation fault (exit 139) in make_sequential;
    this branch -> handle built successfully.
  3. NF12 escape index (native). escape index 3 with a 0-row table:
    origin/main -> CUDA error: an illegal memory access was encountered;
    this branch -> finite [16, 64] decode.
  4. NF12 MoE offsets (native). 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.
  5. ParoQuant pair 300 (native). group_size=128:
    origin/main -> CUDA error: an illegal memory access was encountered;
    this branch -> finite output (masked).
  6. EXL3 K (native). K = 0, 9, 16 and mcg+mul1 -> RuntimeError: EXL3 reconstruct requires 1 <= K <= 8 ...; K = 2 completes.
  7. VPTQ outlier code (native op entry). outlier 3 with 3 centroids -> RuntimeError: VPTQ CUDA outlier index is outside [0, 3).
  8. FloatX empty scale. origin/main extension -> 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

  • The ExLlamaV2 Python check skips an all-zero 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.cpp validates g_idx whenever 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.
  • The op-entry MoE offset check copies E + 1 int64 values to the host; it is a one-time-per-call cost, not a per-element scan.
  • Follow-up, not in this PR: none required for [Memory safety] Native kernels index with unchecked checkpoint tensors (ExLlamaV2 g_idx, NF12 escapes, ParoQuant pairs, VPTQ outliers, EXL3 K) #3971. The pre-existing lint failure and the pre-existing paroquant/mock test failures are outside this change's scope.

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.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

[Memory safety] Native kernels index with unchecked checkpoint tensors (ExLlamaV2 g_idx, NF12 escapes, ParoQuant pairs, VPTQ outliers, EXL3 K)

1 participant