Skip to content

fix(tests): gate CUDA-only kernel tests by build and device ordinal - #3805

Merged
Qubitium merged 3 commits into
mainfrom
fix/rocm-test-gates-gfx1201
Nov 13, 2026
Merged

Qubitium merged 3 commits into
mainfrom
fix/rocm-test-gates-gfx1201

Conversation

@ZX-ModelCloud

@ZX-ModelCloud ZX-ModelCloud commented Nov 13, 2026 •

Copy link
Copy Markdown
Collaborator

Summary

Gate CUDA-only tests through GPT-QModel's explicit device-family resolver before
NVIDIA capability checks. Select a supported Swordfish ordinal and keep setup,
timing and graph capture on that device. Eligible build/load failures propagate.

NF12 initialization reuses loaded or registered operators, packaged libraries
and ready JIT caches before requiring compiler tools. Only a source build that
raises the private _MissingBuildTools exception produces a missing-tool skip.
Binary-load, registration and real compiler failures remain test failures.
Compiler discovery, including CUDACXX, stays owned by the source builder.

Scope: test gates, regression coverage, documentation, and a RuntimeError
subclass for the source builder's existing missing-tools error. Kernel math,
inference dispatch, persistent weight storage, model definitions and threaded
call sites are unchanged.

Reference: Accelerator test gates, linked from README.

Gate and failure flow

flowchart TD
    A["cuda_only_skip_reason: normalize_device(cuda)"] --> B{"DEVICE.ROCM?"}
    B -->|yes| SKIP["Skip with family or prerequisite reason"]
    B -->|no| C{"torch.cuda.is_available()?"}
    C -->|no| SKIP
    C -->|yes| S["swordfish_supported_devices: validate each ordinal"]
    C -->|yes| N["nf12_skip_reason: every visible device must be SM80+"]
    S --> D{"Any supported ordinal?"}
    D -->|no| SKIP
    D -->|yes| E["swordfish_test_device: first supported ordinal"]
    E --> F["setUpClass: device scope, prewarm_swordfish_extension"]
    F --> G{"swordfish_runtime_available(device)?"}
    F -->|load raises| FAIL["Test failure / setup error; never cached as skip"]
    G -->|no| FAIL
    G -->|yes| RUN["Run kernel tests"]
    N --> H{"All supported?"}
    H -->|no| SKIP
    H -->|yes| K["nf12.load"]
    K --> L{"Loaded or registered operators?"}
    L -->|yes| RUN
    L -->|no| P{"Packaged libraries or ready JIT cache?"}
    P -->|yes| LOAD["torch.ops.load_library and _register_fakes"]
    P -->|no| I["_jit._build: CUDACXX then CUDA_HOME then PATH"]
    I --> J{"cmake, ninja and nvcc present?"}
    J -->|no: _MissingBuildTools| SKIP
    J -->|yes| BUILD["_jit._build: configure and compile"]
    BUILD -->|success| LOAD
    BUILD -->|raises| FAIL
    LOAD -->|raises| FAIL
    LOAD -->|success| RUN
    K -->|other error| FAIL
    classDef failure fill:#ffe0e0,stroke:#b00020
    class FAIL failure
Loading

A failed or ambiguous Swordfish device-validation probe is ineligible; the
explicit-device gate reports the exception, and a sweep excludes that ordinal.
NF12 treats an unreadable capability as ineligible. These eligibility checks
happen before loading. Once eligible, compiler, source, registration and runtime
load failures propagate. nf12.load first reuses loaded or registered operators,
packaged libraries, or a ready JIT cache. Compiler tools are required only on a
source-build cache miss. _jit._build reports missing executables through the
private _MissingBuildTools exception, which alone becomes a prerequisite skip.
A present but incompatible compiler, corrupt binary or failed registration
produces a failure with its diagnostic, even if build tools are absent.

Keeping execution on the selected device

flowchart TD
    S["swordfish_test_device()"] --> P["setUpClass: torch.cuda.device(device)"]
    P --> V["prewarm and swordfish_runtime_available(device)"]
    S --> T["Allocate test tensors on device"]
    T --> M["_measure: torch.cuda.device(x.device)"]
    M --> E["Warmup, synchronize, record events, execute, measure"]
    T --> G["test_swordfish_cuda_graph_capture_and_replay: device scope"]
    G --> C["Explicit Stream(device), capture, replay, compare changed inputs"]
    E --> R["Context exit restores caller device"]
    C --> R
    E -->|raises| X["Propagate failure and restore caller device"]
    C -->|raises| X
    classDef failure fill:#ffe0e0,stroke:#b00020
    class X failure
Loading

Selecting a tensor device does not move the thread's current device. CUDA events
and the default graph capture stream must belong to the device doing the work.
The graph test supplies an explicit torch.cuda.Stream(device=device) because
PyTorch can reuse a process-wide default capture stream from an earlier test on
another device. The separate cross-device Swordfish kernel test deliberately keeps a different
current device to verify that production execution follows its tensors.

Before and after

The before pointers refer to commit d68031262 in PR #3805 unless marked
715a36e36.

Before: evidence and behavior After
tests/accelerator_gates.py:161: every NF12 load exception cached as a skip nf12_skip_reason lets errors propagate; nf12.load owns successful caching
tests/accelerator_gates.py:126: compiler lookup ignored CUDACXX The source builder owns compiler lookup and honors its compiler-override precedence
715a36e36, tests/accelerator_gates.py:151: unconditional build-tool checks skipped usable runtimes and hid binary-load failures nf12.load reuses available runtimes; only _jit._build raising _MissingBuildTools yields a tool-related skip, without duplicating compiler lookup
tests/kernels/test_swordfish.py:233, test_swordfish_speed.py:101, test_swordfish_speed_deepseek_v4.py:136: runtime checks used the current device, and setup errors became skips All three setUpClass methods scope prewarm to the selected device, validate that explicit target, and propagate errors
tests/kernels/test_swordfish_speed.py:106, test_swordfish_speed_deepseek_v4.py:111: timing events used the current device Both _measure functions scope warmup and timing to x.device
tests/kernels/test_swordfish.py:449: default graph stream could belong to another device Warmup, capture and replay share the selected device scope and an explicit capture stream

Validation contract

tests/test_accelerator_gates.py covers family rejection before NVIDIA capability
queries, ordinal selection, missing tools, the source builder's CUDACXX
precedence and propagated NF12 build failures. It also covers loaded and
registered operators, packaged libraries and ready JIT caches with no compiler
lookup, plus binary-load failures with missing tools. A native regression in
tests/test_gptqmodel_nf12_api.py runs NF12 linear after tool lookup is disabled.
tests/test_swordfish_test_devices.py checks all three
setup consumers and runs timing and graph tests on a non-current CUDA device.
The graph test changes its inputs between replays; the timing tests check that
the measured operation sees its input device and that the caller is restored.

The harness tests use a small Torch operation instead of a Swordfish kernel.
They establish device-context behavior, not Swordfish numerical correctness.
The source builder adds a private exception type for its existing missing-tools
error. Kernel math, inference dispatch, weight storage and threaded call sites
are unchanged.

Measured on 2026-11-13 with the GIL disabled:

Check Result
New regression cases applied to d68031262 12 failed
NF12 runtime regressions applied to 715a36e36 7 failed
Full targeted suite, CUDA 100 passed, 14 skipped
Full targeted suite, ROCm 29 passed, 85 skipped
Ruff on the eight targeted Python files Passed

The full set comprises test_accelerator_gates.py,
test_swordfish_test_devices.py, the three Swordfish suites and
test_gptqmodel_nf12_api.py. Native Swordfish execution was architecture-skipped
and remains unvalidated in this run. NF12 native CUDA tests executed; ROCm skips
are intentional for these CUDA-only suites.

Validation command, run separately with each runtime:

PYTHON_GIL=0 python -m pytest -q tests/test_accelerator_gates.py \
  tests/test_swordfish_test_devices.py tests/kernels/test_swordfish.py \
  tests/kernels/test_swordfish_speed.py tests/kernels/test_swordfish_speed_deepseek_v4.py \
  tests/test_gptqmodel_nf12_api.py

torch.cuda.is_available() is true under HIP and
torch.cuda.get_device_capability() returns an unrelated pair there
(gfx1201 reports (12, 0)), so the Swordfish speed tests classified an AMD
device as Blackwell/SM120 and attempted a HIP build the extension rejects.

Move the platform checks into tests/accelerator_gates.py:

- cuda_only_skip_reason rejects HIP builds before any capability probe.
- swordfish_supported_devices resolves support per visible ordinal through
  the extension loader's own Blackwell table, either mixed or uniform.
  swordfish_skip_reason sweeps every ordinal (reporting each one's SM) and
  still validates an explicit device, so a target is never misclassified.
- swordfish_test_device returns the first supported ordinal instead of
  hard-coded cuda:0 / the current device, so a Blackwell part behind an
  older GPU on a mixed host is exercised rather than skipped or failed.
- nf12_skip_reason skips ROCm and any visible GPU below SM80 (the JIT
  derives -gencode from every visible device and rejects the set), skips a
  missing cmake/ninja/nvcc toolchain, and probes the real load once for any
  other failure. With the toolchain present the native operators build and
  run instead of silently skipping.

The Swordfish suites and the NF12 API suite now use these gates, and the
DeepSeek-V4 sweep reports an unavailable runtime as a skip instead of a
setUpClass error. Unit tests pin that a HIP host never reaches
get_device_capability, that mixed-host ordinals are resolved individually,
and that the NVIDIA, pre-SM80 and toolchain paths report real reasons.

Co-Authored-By: ZX-ModelCloud <[email protected]>
Comment thread tests/accelerator_gates.py Fixed
@ZX-ModelCloud
ZX-ModelCloud marked this pull request as ready for review November 13, 2026 03:47

@ZX-ModelCloud ZX-ModelCloud left a comment •

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Review found two blockers: NF12/Swordfish build failures were converted to skips, and Swordfish setup/timing/graph capture could use the wrong device. The compiler gate also ignored CUDACXX.

Fixed and pushed in 715a36e. All 12 new regression cases fail on the original PR. After the fix: CUDA 92 passed / 14 skipped; ROCm 22 passed / 84 skipped; Ruff passed. Native Swordfish execution remains unvalidated because its architecture gate skipped it.

@ZX-ModelCloud ZX-ModelCloud left a comment •

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Reviewed 715a36e36: request changes. Both confirmed that tests/accelerator_gates.py:151 can skip usable NF12 operators/libraries and hide binary-load errors when build tools are absent.

Fixed and pushed in fa8b48e75. Seven regression cases fail before the fix. After: CUDA 100 passed / 14 skipped; ROCm 29 passed / 85 skipped; Ruff passed. Native Swordfish remains architecture-skipped.

Comment thread tests/test_accelerator_gates.py Dismissed
Comment thread tests/test_accelerator_gates.py Dismissed
Comment thread tests/test_accelerator_gates.py Dismissed

Copy link
Copy Markdown
Collaborator

Reviewed current head fa8b48e75b31cc307e70ecfc0e3754da4b6d40ab, including the complete diff, loader/device-support call paths, and the earlier review discussion. No new actionable correctness findings. The earlier NF12 prerequisite masking and Swordfish device-context findings are addressed in this head.

Validation: PYTHON_GIL=0 /root/venv-py3.14t-gil0/bin/python -m pytest -q tests/test_accelerator_gates.py tests/test_swordfish_test_devices.py — 31 passed on CPython 3.14.7 with the GIL disabled, Torch 2.15.0.dev20260928+cu130, and NVIDIA SM80 devices. This includes the actual two-device timing and graph-capture harness cases, not just mocked ordinal checks. git diff --check also passed.

Limits: this run validates the gates and test harness; it does not qualify native Swordfish execution on Blackwell. I did not rerun the native NF12 API suite or test on a ROCm runtime.

@Qubitium
Qubitium merged commit e1ebee5 into main Nov 13, 2026
6 checks passed
@Qubitium
Qubitium deleted the fix/rocm-test-gates-gfx1201 branch November 13, 2026 06:26
Qubitium added a commit that referenced this pull request Nov 13, 2026
* feat(tenstorrent): emulate bf8/bf4 block-float on CUDA

Add a CUDA sibling of the HIP block-float kernels so a `bf4_b` / `bf8_b`
checkpoint can be validated and benchmarked on an NVIDIA part without Tensix
hardware. The host contract in `tt_blockfloat_cuda.h` is identical to the HIP
header; only the runtime types differ.

Names follow the vocabulary #3760 settled on: `bf4_b` / `bf8_b` for the two
dtypes, `blockfloat_*` for the exported C entry points, and `hw/dtypes.md`
section 8 as the single definition of the bit layout. The extension README
points at that section instead of restating it, and `docs/tenstorrent.md` gains
a short section so the emulation path is reachable from the same place as the
card paths.

Storage and every rounding decision match
`gptqmodel.utils.tt_blockfloat_quant`: quantise reproduces the three-candidate
exponent search and its strict `<` tie-break, so the new tests can require
bit-exact agreement with the torch reference rather than a tolerance.

The GEMM expands the packed weights once and hands the matmul to cuBLAS, which
reaches roughly twice what a hand-written tile gets on the same shape. cuBLAS is
resolved with dlopen/dlsym: pip CUDA wheels ship `libcublas.so.13` with no
`libcublas.so` symlink, so a link-time `-lcublas` fails there and the soname
follows the CUDA major. A fused `mma.m16n8k16` kernel stays as the fallback when
it cannot be resolved.

`TTBlockfloatLinear`, `TTBlockfloatEmbedding` and `TTBlockfloatTiedHead` read
the packed codes directly on CUDA instead of materialising a dense weight, which
is the point of the emulation: a `bf4_b` layer then costs what it will cost on
Tensix. Every other device keeps the dense path.

Two latent bugs surfaced while validating and are fixed here: the fp32 SIMT
kernel offset into the packed `bf4_b` buffer with an unpacked element index, and
the fused kernel packed bf16 bit patterns into an fp16 shared tile, so the fp16
fallback was wrong.

Measured on a shared PG506-230 (sm_80), n = k = 4096, `bf4_b`, best of six:
48/52/46/47/64/93/145/253 us for 1/16/32/64/128/256/512/1024 tokens
(136 TFLOP/s at 1024), against 218 us and 542 us for the same two ends before
this change.

* fix(tenstorrent): make the CUDA scratch per-call and stream-safe

Addresses the four findings from the review of the CUDA block-float
kernels.

[P1] Overlapping streams shared one scratch buffer per device. The mutex
only serialised allocation, so two stream-scoped forwards could overwrite
each other's decoded weights while both were queued. Scratch is now owned
by the call -- a TemporaryBuffer that is freed with cudaFreeAsync on the
calling stream -- and the cuBLAS handle is per (device, stream) rather
than per device, because a handle carries a device-side workspace that
must not be shared either.

[P2] The cached scratch stayed live at the largest size ever requested,
holding an expanded copy of the weights between calls. Nothing is
retained now: cudaMemPoolAttrUsedMemCurrent returns to zero once the
stream drains. The buffer comes from a private per-device pool because
the default pool hands every freed block straight back to the driver,
which puts a fresh 34 MB allocation at ~1.9 ms; a pool that keeps its
blocks makes the same alloc/free pair ~12 us.

[P2] A strided activation was rejected: reshape(-1, k) can return a
non-contiguous view and the op refused it. The binding materialises it
with contiguous(), which is a no-op when the tensor is already packed, so
the kernel path keeps the layouts the dense path accepted.

[P2] The epilogue mapped every row onto grid.y, which caps at 65535, so
M = 65536 failed with "invalid argument". Rows are now strided across the
blocks that fit.

Four regression tests cover the findings, one per report. The stream and
memory tests fail against the previous implementation -- 48 MB left live
in the async pool and corrupted stream output -- so they are not
tautological. The forced no-cuBLAS fallback was re-validated too.

Perf is unchanged: 46/58/52/54/72/96/147/254 us for
1/16/32/64/128/256/512/1024 tokens.

* fix(tenstorrent): mask odd-N fallback stores and keep empty forwards

Addresses the two findings from the second review round, and resolves the
rebase onto #3813 (block-float checkpoints load at their own precision).

[P1] The fused fallback's epilogue owns a pair of adjacent output columns
per fragment, but only the first was range-checked, so an odd `n` stored
into `out[m * n]` and read `bias[n]`. The second bias load and both
second-column stores are now guarded by `gn + 1 < n`. This is the path
taken when cuBLAS is unavailable, which is why it went unnoticed: every
existing test ran through cuBLAS. `GPTQMODEL_BLOCKFLOAT_NO_CUBLAS=1` now
forces the fallback, so the tests can reach it on a machine that does
have cuBLAS, and the full linear validation was re-run through it.

[P2] Empty forwards raised: the embedding dispatch launched a zero-block
kernel and the linear binding rejected a zero-row activation, so
`TTBlockfloatEmbedding` and `TTBlockfloatTiedHead` broke where the dense
paths returned `(0, 16)` and `(1, 0, 3)`. Both modules now return the
dense path's shape and dtype before dispatch, and the bindings tolerate
empty operands so direct callers behave the same.

Rebase resolution: #3813 gave the embedding an `output_dtype` that follows
`Module.to`, so the gather kernel and the empty return now use
`self.output_dtype` rather than float32 -- otherwise a bf16 table would
have emitted float32 on both new paths. The suite also takes its skip
reason from `tests/accelerator_gates.py` now, per #3805, so a HIP build is
rejected before the capability probe.

Two regression tests, both verified to fail against the previous head:
the fallback canary test (`n = 1/3/5` with a sentinel after the last
element) and the empty-forward test (shape, dtype and equality with the
dense path, including a bf16-cast table). 84 tests pass; the forced
fallback still matches the reference on every shape/dtype case.
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.

2 participants