Repository navigation
fix(nf12): mask out-of-range IDs in the embedding fallback (#3922) - #3940
Merged
Merged
Conversation
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
…rt' and 'import from'' Co-authored-by: Copilot Autofix powered by AI <223894421+github-code-quality[bot]@users.noreply.github.com>
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
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 #3922
Root cause
AutoNF12Embedding.forward(gptqmodel/utils/auto_dtype_cast.py) ends in a portable fallback:F.embeddinggathers the raw ID. Every native NF12 embedding operator documents the opposite contract —gptqmodel_nf12/api.py::embeddingandgptqmodel/utils/nf12_hip.pyboth state that IDs outside[0, N)produce+0.0rows — so the fallback changed public behavior:IndexError: index out of range in selfindexSelectSmallIndex: Assertion 'srcIndex < srcSelectDimSize' failed, which is a device-side assert and poisons the context for the rest of the processThe issue's repro (
tests/test_auto_dtype_cast.py::test_cuda_embedding_uses_only_packed_storageon a runtime-only CUDA host) usesids = [[-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:
torch.whereis used instead of multiplying by a mask so an invalid row is exactly+0.0and not-0.0. The all-valid fast path skips the secondwhere. 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]]:Host path, same table:
Tests
tests/test_auto_dtype_cast.py::test_cpu_embedding_fallback_masks_out_of_range_ids(new)tests/test_auto_dtype_cast.py::test_dense_embedding_fallback_masks_out_of_range_ids(new)+0.0rows for negative andnum_embeddingsIDs, plus all-invalid and 0-dim inputs; forces the fallback so it also runs where the extension is builttests/test_auto_dtype_cast.py::test_cuda_embedding_uses_only_packed_storageBoth new tests assert
+0.0bit 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+cu130Py3.14.10t; R9700 gfx1201torch 2.16.0.dev20261025+rocm10.1.pytest tests/test_auto_dtype_cast.py -q(4090)pytest tests/test_auto_dtype_cast.py -q(R9700)pytest tests/test_auto_dtype_cast.py -qwithPATH=/usr/bin:/bin CUDA_HOME=/nonexistent(forces the fallback)origin/mainpytest tests/test_auto_dtype_cast.py -k masks_out_of_range -q, source revertedruff check gptqmodel/utils/auto_dtype_cast.py tests/test_auto_dtype_cast.pyThe 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) neednvcc/native NF12 and fail identically on unmodifiedmain. Onmainthe same run also losestest_cuda_embedding_uses_only_packed_storageandtest_pinned_cpu_offload_preserves_bits_and_pins_large_tensorsto the poisoned context — the assert takes the whole process down, which is why the fix also stops that collateral damage.Notes
gptqmodel_nf12/api.py, and I added an "Embedding index contract" table todocs/auto-nf12-dtype-cast.mdso the parity is recorded in one place.GPTQMODEL_*switch, no new cache, and no change to the native paths.