Repository navigation
feat(tenstorrent): run bf8/bf4 checkpoints on CUDA kernels - #3810
Conversation
fa38994 to
a2adce5
Compare
|
Review of
Design recommendation: allocate scratch through a stream-aware temporary-storage contract shared by the cuBLAS and fused paths. This addresses both correctness under overlap and the permanent dense-memory footprint without retaining model-sized decoded tensors. Validation: the supplied CUDA suite passed 78 tests. Additional quantize/dequantize comparisons matched Torch exactly for 160,000 sixteen-value blocks across 4/8 bits and scales 1, 1e20, 1e30 and 1e-20. Separate probes reproduced the stream race, live-memory retention, strided-input failure and 65,536-row launch boundary. Tests used Torch 2.15.0+cu132 on RTX 4090. The forced no-cuBLAS fallback and free-threaded Python were not requalified in this review. No source edits. |
|
Fixed all four in 1. [P1] Overlapping streams. Scratch is now owned by the call: a 2. [P2] Live workspace. Nothing is retained: 3. [P2] Strided activations. The binding materialises the activation with 4. [P2] grid.y. The epilogue strides rows across at most 65535 blocks instead of mapping one row per Verification: I confirmed the two new behavioural tests are not tautological by rebuilding with the old shared-buffer behaviour — One thing I did not do: trimming the private pool, so its reserved high-water mark persists (bounded by the largest call). If you would rather it be released, |
|
Review of
Validation: 82/82 supplied CUDA tests passed on NVIDIA PG506-230 (SM80), Python 3.14.7 with |
|
Both fixed in 1. [P1] Odd-N overwrite in the fused fallback. Correct, and the guard was only on the first column of the pair: To stop that happening again I added 2. [P2] Empty embedding and tied-head forwards. Both now return the dense path's shape and dtype before dispatch — 84 tests pass. Throughput unchanged: 46/53/48/49/66/85/129/255 us for 1/16/32/64/128/256/512/1024 tokens. On the sccache/NVCC failure you hit: that is this box, not the PR — torch prepends |
b991a9f to
f23cf52
Compare
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.
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.
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.
f23cf52 to
67004a0
Compare
|
Rebased onto Two conflicts, both resolved by keeping both backends:
The Re-ran after the rebase: |
Summary
bf4_b/bf8_bcheckpoints could only be executed on a Tenstorrent device, sothe formats could not be tested, validated or benchmarked on NVIDIA hardware.
This adds a CUDA implementation of the same storage, so a block-float checkpoint
produces the same numbers here as it will on Tensix.
Sibling of #3806, which does the same for ROCm. Retargeted to
mainnow that#3760 has landed, and named to match the vocabulary it settled on:
bf4_b/bf8_bfor the dtypes,blockfloat_*for the exported C entry points, andhw/dtypes.mdsection 8 as the single definition of the bit layout. The hostcontract in
tt_blockfloat_cuda.his otherwise identical to the HIP header;only the runtime types differ.
What Changed
gptqmodel_ext/tt_blockfloat_cuda/— new CUDA extension. It consumes thecheckpoint exactly as the Tenstorrent runtime does: packed uint8
codesplusone int8 exponent per 16 consecutive K values. Nothing is requantised,
converted to int4, or expanded on the host. Entry points:
blockfloat_dequant,blockfloat_quantize,blockfloat_decompose,blockfloat_embedding,blockfloat_linear, and ablockfloat_selftestsentinel.gptqmodel/utils/tt_blockfloat_cuda.py— JIT loader and Python API.tt_blockfloat.py—TTBlockfloatLinear/Embedding/TiedHeadusethe extension when the module is on a CUDA device; the torch path is unchanged
and remains the fallback everywhere else.
gptqmodel_ext/tt_blockfloat_cuda/README.md— points athw/dtypes.mdfor the layout rather than restating it, and records the two GEMM paths and
the measured numbers.
docs/tenstorrent.md— new "Emulation on non-Tenstorrent hardware"section, so this path is reachable from the same place as the card paths.
README.md— one paragraph next to the existing Tenstorrent text.MANIFEST.in— ship the new sources in the sdist.Quantise reproduces
quantize_blockfloatbit for bit, including itsthree-candidate exponent search (
base,base - 1,base + 1) and its strict<tie-break, so the tests assert exact equality rather than a tolerance.blockfloat_decomposeis the exact inverse ofblockfloat_dequantand reportsfailure for any block that is not already on the grid.
The GEMM: cuBLAS for prefill, fused MMA as the fallback
blockfloat_linearhas two implementations behind one entry point.Prefill expands the packed weights once into a bf16/f16 scratch buffer and
hands the GEMM to
cublasGemmExwith fp32 accumulate. A hand-written128x128x32
mma.m16n8k16tile was measured at roughly half of what cuBLASreaches on the same shape (63 vs 146 TFLOP/s at
m = 1024), and competing withcuBLAS is not the interesting part of this problem. That scratch is owned by the
call: allocated from a private per-device pool and freed on the calling
stream, so two overlapping streams never share a decoded weight and nothing
expanded survives the forward pass. The private pool is what makes it
affordable -- the default pool returns every freed block to the driver, which
puts a fresh ~34 MB allocation at ~1.9 ms, more than the GEMM it feeds, while
a pool that keeps its blocks makes the same alloc/free pair ~12 us.
cuBLAS is resolved with
dlopen/dlsymrather than a link-time-lcublas.pip CUDA wheels ship
libcublas.so.13with nolibcublas.sosymlink, so-lcublasfails to link there, and the soname follows the CUDA major. Everyprocess that loads this extension already has the library mapped through torch.
The extension therefore has no link-time cuBLAS dependency at all
(
nm -D --undefined-onlyshows none), so a bare toolkit still builds.Fallback — if cuBLAS cannot be resolved, the fused dequant +
mma.m16n8k16kernel runs instead (128x128x32 tile, 8 warps,
cp.asyncdouble buffering,register-prefetched dequantise for the weight tile). It is correct but slower; it
exists so the extension still works without cuBLAS. It was validated by building
a variant with the cuBLAS probe forced to fail: same results,
0 failures.The dequantiser is at the memory roofline: 26 us for a 4096x4096
bf4_bunpack(1285 GB/s), against 31 us for a plain 33.5 MB fill on the same part.
4096x4096
bf4_b, bf16 activations, PG506-230 (A100-class,sm_80), CUDA 13.3,best of six across two sessions:
The GPU was shared with another job throughout, which swings absolute timings by
up to 3x between runs (one quiet run put
m = 1at 44 us); relative behaviourwas stable. These are not comparable to #3806's R9700 table
(45.7 / 39.4 / 44.2 / 58.1 / 94.0 / 185.3 us for 16..512) — different silicon,
different rooflines. Taken at face value the two land in the same range.
Out of scope
m <= 16. Implemented, measured, and removed: a 16x128 tilewith a split over K reached 84 us at
m = 1, while the dense path — expandthe weights once, cuBLAS GEMV — takes 48 us, because the expansion is only
26 us and the fused kernel cannot beat it. Keeping it would have added ~200
lines and a partial-sum reduction for a slower result.
writes it; permuting codes into 32x32 face order is a device layout concern and
not part of the dtype emulation.
bf2_bNot added, and
bits == 2is rejected. Blackhole's LLK can packBfp2_b(
pack_as_bfp2_tilesintt-metalium/bfloat2.hpp), so the p300c silicon canhold it, but nothing above the kernel exposes it:
tt::tt_metal::DataTypehas noBFLOAT2_B, andttnn.typesoffers onlybfloat16,bfloat8_bandbfloat4_b. With no consumer in the stack and no oracle to validate a kernelagainst, there is nothing to emulate. Two bits are one sign and one magnitude,
so a 16-value block would hold only
{-1, 0, +1} x 2**exponentin any case.Two latent bugs fixed
Surfaced while validating, both in the pre-existing kernels:
bf4_bcode buffer with anunpacked element index, so every
bf4_bfp32 GEMM read the wrong nibbles.fp16 fallback fed bf16 data to the
f16.f16.f32MMA. It now packs throughT.Tests
python -m pytest tests/test_tt_blockfloat_cuda.py -q # -> 78 passedtests/test_tt_blockfloat_cuda.pycompares quantise and decompose bit for bitagainst
gptqmodel.utils.tt_blockfloat_quantover 5 geometries (includingrows = 1,rows = 17andk = 16), and the GEMM against a float32 matmulover the same grid weights for
bf4_b/bf8_bx bf16/fp16/fp32 atm = 1, 15, 16, 17, 64, 129— every launcher boundary and both sides of it.It also covers the embedding gather (including out-of-range ids reading as zero)
and asserts that the module classes actually route through the kernel rather than
dequantise-then-matmul.
Also run:
Four tests in
tests/test_tenstorrent_support.pyfail in this environment. Theyfail identically on
main(4 failed / 92 passed there too), becausetorch_xlais not installed.
Model Support / Module Plan
Not applicable — no
MODEL_MAPentry, model type, alias, or definition change.Logic Flow Documentation
Not applicable. This adds a device-gated fast path inside three existing methods;
it does not replace a decision mechanism or change resolution order. The torch
path is untouched and remains the fallback, and a failed extension build logs
once and falls back rather than failing a forward pass.
Review Requirements
Kernel Accuracy Requirements
Quantise/decompose are bit-exact against the torch reference. The GEMM's
remaining error is the bf16 output rounding: measured 2.0e-3 to 3.0e-3 relative
at max, against a 5e-3 bound, for every dtype and shape above.
bf4_b/bf8_bvalues are exact grid points and exactly representable in bf16 (7 and 3
significant bits), so the tensor-core path adds no rounding of its own.
Notes
a shared PG506-230 (
sm_80) via the standalone harness and the pytest file.Please do not treat green CUDA jobs as coverage of these kernels.
sm_80(mma.sync.m16n8k16with bf16 inputs) and isgated on
torch.cuda.get_device_capability; ROCm reports a gfx-derivedcapability, so the loader explicitly excludes
torch.version.hipto avoidsending a ROCm build at a CUDA kernel.
CUBLASLT_EPILOGUE_BIAS, whichwould drop the fp32 accumulator buffer and the separate epilogue kernel
(~6% of the time at
m = 1024).Review follow-up
All four findings from the review are fixed in
e6d836ac; each has aregression test that fails against the previous implementation.
TemporaryBufferfreed with
cudaFreeAsyncon the calling stream), and the cuBLAS handle is nowper
(device, stream)instead of per device, since a handle carries its owndevice-side workspace.
test_overlapping_streams_get_independent_scratchreproduces the reported scenario (two streams,
M=1024, N=K=4096, constantweights 1.0 and 1.5, exact expected sums); it corrupted output before the fix.
cudaMemPoolAttrUsedMemCurrentreturns to zero once the stream drains.test_scratch_is_not_left_live_in_the_async_poolmeasured 48 MB live in thedefault async pool before the fix and 0 after. Blocks are reused from a private
per-device pool rather than the default one, because the default pool returns
each freed block to the driver (~1.9 ms per 34 MB call versus ~12 us).
contiguous(), a no-op when already packed, sox[:, ::2]keeps working.test_linear_accepts_strided_activationscovers the module and the raw op.instead of mapping one row per
blockIdx.y.test_linear_handles_a_full_grid_ycoversM = 65536, N = 1, K = 16.Re-validated after the change: 84 CUDA tests pass
(
tests/test_tt_blockfloat_cuda.py);tests/test_tenstorrent_support.pygives 106 passed / 15 skipped with only the same 4 pre-existing
torch_xlafailures that also fail on
main; the forced no-cuBLAS fallback still matchesthe reference, and throughput is unchanged (46/58/52/54/72/96/147/254 us for
1/16/32/64/128/256/512/1024 tokens).
Second review round, fixed in
67004a01:nin the fused fallback. The MMA epilogue owns a pair ofadjacent columns, so an odd width stored past the last column and read
bias[n]. Both second-column stores and the second bias load are now guarded.GPTQMODEL_BLOCKFLOAT_NO_CUBLAS=1forces the fallback at run time, which ishow
test_fused_fallback_masks_an_odd_output_widthreaches it; the wholelinear validation was re-run through the forced fallback as well.
TTBlockfloatEmbeddingandTTBlockfloatTiedHeadreturned to the dense paths'
(0, 16)/(1, 0, 3)shapes instead oflaunching a zero-block kernel or rejecting a zero-row activation, and the
bindings tolerate empty operands for direct callers.
test_empty_inputs_keep_their_shapescovers both modules and the raw op.Rebased onto
mainate5e13ca6(the ROCm/HIP merge, #3806), head67004a01.Two conflicts, both resolved by keeping both backends rather than choosing one:
docs/tenstorrent.md: the ROCm section from feat(tenstorrent): run bf8/bf4 checkpoints on ROCm with HIP kernels #3806 is kept verbatim and theCUDA emulation text follows it as its own section.
gptqmodel/nn_modules/qlinear/tt_blockfloat.py: the HIP dispatch moved intothe shared
_kernel_linear/_kernel_embeddinghelpers, so one call sitetries HIP first and then CUDA. The
TTBlockfloatEmbedding.output_dtypebehaviour from fix(tenstorrent): load block-float checkpoints at their own precision, not fp32 #3813 is preserved — the kernel path and the empty-forward
path both use
output_dtype, so a bf16-cast table does not emit float32.A
bits == 2module still takes the torch path, since neither the HIP northe CUDA kernel implements it.