Skip to content

fix(nf12): mask out-of-range IDs in the embedding fallback (#3922) - #3940

Merged
Qubitium merged 2 commits into
mainfrom
fix/issue-3922
Nov 14, 2026
Merged

Qubitium merged 2 commits into
mainfrom
fix/issue-3922

Conversation

@Qubitium

Copy link
Copy Markdown
Collaborator

Fixes #3922

Root cause

AutoNF12Embedding.forward (gptqmodel/utils/auto_dtype_cast.py) ends in a portable fallback:

dense = self.dequantize_weight(device=ids.device, dtype=torch.bfloat16)
return torch.nn.functional.embedding(ids, dense).to(self.output_dtype)

F.embedding gathers the raw ID. Every native NF12 embedding operator documents the opposite contract — gptqmodel_nf12/api.py::embedding and gptqmodel/utils/nf12_hip.py both state that IDs outside [0, N) produce +0.0 rows — so the fallback changed public behavior:

  • host: IndexError: index out of range in self
  • CUDA: indexSelectSmallIndex: Assertion 'srcIndex < srcSelectDimSize' failed, which is a device-side assert and poisons the context for the rest of the process

The issue's repro (tests/test_auto_dtype_cast.py::test_cuda_embedding_uses_only_packed_storage on a runtime-only CUDA host) uses ids = [[-1, 0, 7], [15, 31, 32]], so it hits exactly this path.

Fix

Mask the lookup before the gather and zero the invalid rows explicitly:

valid = (ids >= 0) & (ids < self.num_embeddings)
safe_ids = torch.where(valid, ids, torch.zeros_like(ids))
output = torch.nn.functional.embedding(safe_ids, dense)
if not bool(valid.all()):
    output = torch.where(valid.unsqueeze(-1), output, torch.zeros_like(output))

torch.where is used instead of multiplying by a mask so an invalid row is exactly +0.0 and not -0.0. The all-valid fast path skips the second where. Valid rows are unchanged: the codec decode is lossless, so they still carry the exact checkpoint BF16 bits.

This does not add a dense weight cache — the decoded table stays a local of the current forward, which is the same transient dequantization the fallback already performed.

Before / after

Runtime-only CUDA host (toolkit hidden), 32x128 BF16 table, ids = [[-1, 0, 7], [15, 31, 32]]:

# before
row_major False
torch.AcceleratorError: CUDA error: device-side assert triggered

# after
row_major False
maxdiff 0.0
invalid rows all zero True

Host path, same table:

# before
row_major False
IndexError: index out of range in self

# after
row_major False
bits equal True

Tests

Test Pins
tests/test_auto_dtype_cast.py::test_cpu_embedding_fallback_masks_out_of_range_ids (new) The shared fallback masks the lookup on the host; runs on any machine
tests/test_auto_dtype_cast.py::test_dense_embedding_fallback_masks_out_of_range_ids (new) The CUDA fallback returns +0.0 rows for negative and num_embeddings IDs, plus all-invalid and 0-dim inputs; forces the fallback so it also runs where the extension is built
tests/test_auto_dtype_cast.py::test_cuda_embedding_uses_only_packed_storage The issue's exact repro node

Both new tests assert +0.0 bit patterns (not just == 0) and re-check that valid rows are bit-identical to the source weight.

Validation

Hardware: RTX 4090 (SM 8.9) torch 2.16.0.dev20261102+cu130 Py3.14.10t; R9700 gfx1201 torch 2.16.0.dev20261025+rocm10.1.

Command Result
pytest tests/test_auto_dtype_cast.py -q (4090) 40 passed
pytest tests/test_auto_dtype_cast.py -q (R9700) 35 passed, 5 skipped (CUDA-only cases)
pytest tests/test_auto_dtype_cast.py -q with PATH=/usr/bin:/bin CUDA_HOME=/nonexistent (forces the fallback) 36 passed, 3 failed, 1 skipped
same command on unmodified origin/main 31 passed, 6 failed, 1 skipped
pytest tests/test_auto_dtype_cast.py -k masks_out_of_range -q, source reverted fails with the device-side assert
ruff check gptqmodel/utils/auto_dtype_cast.py tests/test_auto_dtype_cast.py All checks passed

The 3 remaining toolkit-hidden failures (test_native_gpu_encoding_keeps_packed_tensors_on_source_device, test_fused_w_minus_wq_matches_the_dense_difference, test_gptq_process_uses_the_fused_diff_with_a_bf16_reconstruction) need nvcc/native NF12 and fail identically on unmodified main. On main the same run also loses test_cuda_embedding_uses_only_packed_storage and test_pinned_cpu_offload_preserves_bits_and_pins_large_tensors to the poisoned context — the assert takes the whole process down, which is why the fix also stops that collateral damage.

Notes

  • Localized single-function fix. The embedding flow, layout selection, and native dispatch order are unchanged, so the logic-flow diagram requirement does not apply; the pre-existing contract is documented in gptqmodel_nf12/api.py, and I added an "Embedding index contract" table to docs/auto-nf12-dtype-cast.md so the parity is recorded in one place.
  • No GPTQMODEL_* switch, no new cache, and no change to the native paths.

Every native NF12 embedding operator returns a +0.0 row for an ID outside
[0, num_embeddings), and both the CUDA and HIP operator docs state that
contract. The portable nf12_codec fallback called F.embedding with the raw
IDs instead, which gathers directly: an out-of-range ID raised IndexError on
the host and tripped `indexSelectSmallIndex: Assertion srcIndex <
srcSelectDimSize failed` on CUDA, poisoning the context for the rest of the
process. Selecting the optional-extension fallback therefore changed public
behavior and could crash a generation run.

Mask the lookup and zero the invalid rows explicitly, so the fallback
matches the native contract bit-for-bit (exactly +0.0, not -0.0). Valid rows
still carry the exact decoded BF16 values.

Fixes #3922
Comment thread tests/test_auto_dtype_cast.py Resolved
…rt' and 'import from''

Co-authored-by: Copilot Autofix powered by AI <223894421+github-code-quality[bot]@users.noreply.github.com>
@Qubitium
Qubitium merged commit 62ebc14 into main Nov 14, 2026
4 of 5 checks passed
@Qubitium
Qubitium deleted the fix/issue-3922 branch November 14, 2026 09:50
Qubitium added a commit that referenced this pull request Nov 14, 2026
The layout probe asked whether the NF12 namespace was usable rather than
whether it could serve the row-major layout. `gptqmodel_nf12.available()` is
true whenever a namespace is registered, so a preloaded legacy library that
owns `torch.ops.nf12` without `rowmajor_pack`/`rowmajor_embedding` selected
the row-major path and the first pack raised AttributeError, aborting the
cast. The HIP branch had the same shape: `hasattr(nf12_hip, "rowmajor_pack")`
is always true because the wrapper exists whether or not the optional
extension can load, and the wrapper raises from `_op` on first use.

Probe the specific operators instead: `available_ops("rowmajor_pack",
"rowmajor_embedding")` on CUDA, and a new
`nf12_hip.rowmajor_available(device)` that loads the extension and checks
that it bound both operators. A pack that still fails (an optimistic probe,
or an extension that loads but omits an operator) now warns once and keeps
the generic packed buffers rather than aborting an otherwise supported
quantization run.

Review follow-up:
- The once-guard is a namespace set, `_ROWMAJOR_FALLBACK_REPORTED`, instead
  of a boolean only rebound behind a `global` statement. It was already live
  at runtime, but a set is mutated in place, so no `global` is needed and the
  guard is visible to static analysis. A new test counts the messages handed
  to the logger across three failed packs (3 -> 1), which fails if the guard
  is dropped.
- `tests/test_auto_dtype_cast.py` uses a single `import gptqmodel_nf12` form
  with attribute access; the `_library`/`_jit` aliases are attribute reads.
- Fixes the stub inherited from #3940: it patched
  `gptqmodel.quantization.nf12.available`, which does not exist, so the test
  failed on any GPU host. The fallback gate is `gptqmodel_nf12.available()`.

Fixes #3860
Qubitium added a commit that referenced this pull request Nov 14, 2026
…3946)

The layout probe asked whether the NF12 namespace was usable rather than
whether it could serve the row-major layout. `gptqmodel_nf12.available()` is
true whenever a namespace is registered, so a preloaded legacy library that
owns `torch.ops.nf12` without `rowmajor_pack`/`rowmajor_embedding` selected
the row-major path and the first pack raised AttributeError, aborting the
cast. The HIP branch had the same shape: `hasattr(nf12_hip, "rowmajor_pack")`
is always true because the wrapper exists whether or not the optional
extension can load, and the wrapper raises from `_op` on first use.

Probe the specific operators instead: `available_ops("rowmajor_pack",
"rowmajor_embedding")` on CUDA, and a new
`nf12_hip.rowmajor_available(device)` that loads the extension and checks
that it bound both operators. A pack that still fails (an optimistic probe,
or an extension that loads but omits an operator) now warns once and keeps
the generic packed buffers rather than aborting an otherwise supported
quantization run.

Review follow-up:
- The once-guard is a namespace set, `_ROWMAJOR_FALLBACK_REPORTED`, instead
  of a boolean only rebound behind a `global` statement. It was already live
  at runtime, but a set is mutated in place, so no `global` is needed and the
  guard is visible to static analysis. A new test counts the messages handed
  to the logger across three failed packs (3 -> 1), which fails if the guard
  is dropped.
- `tests/test_auto_dtype_cast.py` uses a single `import gptqmodel_nf12` form
  with attribute access; the `_library`/`_jit` aliases are attribute reads.
- Fixes the stub inherited from #3940: it patched
  `gptqmodel.quantization.nf12.available`, which does not exist, so the test
  failed on any GPU host. The fallback gate is `gptqmodel_nf12.available()`.

Fixes #3860
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.

AUTO_NF12 embedding fallback triggers CUDA device assert for out-of-range token IDs

1 participant