Skip to content

feat(tenstorrent): run bf8/bf4 checkpoints on CUDA kernels - #3810

Merged
Qubitium merged 3 commits into
mainfrom
feat/tt-blockfloat-cuda-emulation
Nov 13, 2026
Merged

Qubitium merged 3 commits into
mainfrom
feat/tt-blockfloat-cuda-emulation

Conversation

@Qubitium

@Qubitium Qubitium commented Nov 13, 2026 •

Copy link
Copy Markdown
Collaborator

Summary

bf4_b / bf8_b checkpoints could only be executed on a Tenstorrent device, so
the 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 main now that
#3760 has landed, and named to match the vocabulary it settled on: bf4_b /
bf8_b for the dtypes, blockfloat_* for the exported C entry points, and
hw/dtypes.md section 8 as the single definition of the bit layout. The host
contract in tt_blockfloat_cuda.h is otherwise identical to the HIP header;
only the runtime types differ.

What Changed

  • gptqmodel_ext/tt_blockfloat_cuda/ — new CUDA extension. It consumes the
    checkpoint exactly as the Tenstorrent runtime does: packed uint8 codes plus
    one 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 a blockfloat_selftest sentinel.
  • gptqmodel/utils/tt_blockfloat_cuda.py — JIT loader and Python API.
  • tt_blockfloat.py — TTBlockfloatLinear / Embedding / TiedHead use
    the 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 at hw/dtypes.md
    for 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_blockfloat bit for bit, including its
three-candidate exponent search (base, base - 1, base + 1) and its strict
< tie-break, so the tests assert exact equality rather than a tolerance.
blockfloat_decompose is the exact inverse of blockfloat_dequant and reports
failure for any block that is not already on the grid.

The GEMM: cuBLAS for prefill, fused MMA as the fallback

blockfloat_linear has two implementations behind one entry point.

Prefill expands the packed weights once into a bf16/f16 scratch buffer and
hands the GEMM to cublasGemmEx with fp32 accumulate. A hand-written
128x128x32 mma.m16n8k16 tile was measured at roughly half of what cuBLAS
reaches on the same shape (63 vs 146 TFLOP/s at m = 1024), and competing with
cuBLAS 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/dlsym rather than a link-time -lcublas.
pip CUDA wheels ship libcublas.so.13 with no libcublas.so symlink, so
-lcublas fails to link there, and the soname follows the CUDA major. Every
process 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-only shows none), so a bare toolkit still builds.

Fallback — if cuBLAS cannot be resolved, the fused dequant + mma.m16n8k16
kernel runs instead (128x128x32 tile, 8 warps, cp.async double 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_b unpack
(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:

tokens before after TFLOP/s
1 218 us 48 us 0.7
16 217 us 52 us 10.3
32 273 us 46 us 23.3
64 297 us 47 us 45.7
128 423 us 64 us 67.1
256 422 us 93 us 92.4
512 350 us 145 us 118.5
1024 542 us 253 us 135.8

The GPU was shared with another job throughout, which swings absolute timings by
up to 3x between runs (one quiet run put m = 1 at 44 us); relative behaviour
was 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

  • Split-K for m <= 16. Implemented, measured, and removed: a 16x128 tile
    with a split over K reached 84 us at m = 1, while the dense path — expand
    the 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.
  • Tenstorrent face order. The checkpoint layout is row-major as GPT-QModel
    writes it; permuting codes into 32x32 face order is a device layout concern and
    not part of the dtype emulation.

bf2_b

Not added, and bits == 2 is rejected. Blackhole's LLK can pack Bfp2_b
(pack_as_bfp2_tiles in tt-metalium/bfloat2.hpp), so the p300c silicon can
hold it, but nothing above the kernel exposes it: tt::tt_metal::DataType has no
BFLOAT2_B, and ttnn.types offers only bfloat16, bfloat8_b and
bfloat4_b. With no consumer in the stack and no oracle to validate a kernel
against, 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**exponent in any case.

Two latent bugs fixed

Surfaced while validating, both in the pre-existing kernels:

  • The fp32 SIMT kernel offset into the packed bf4_b code buffer with an
    unpacked element index, so every bf4_b fp32 GEMM read the wrong nibbles.
  • The fused kernel always packed bf16 bit patterns into the shared tile, so the
    fp16 fallback fed bf16 data to the f16.f16.f32 MMA. It now packs through T.

Tests

python -m pytest tests/test_tt_blockfloat_cuda.py -q
# -> 78 passed

tests/test_tt_blockfloat_cuda.py compares quantise and decompose bit for bit
against gptqmodel.utils.tt_blockfloat_quant over 5 geometries (including
rows = 1, rows = 17 and k = 16), and the GEMM against a float32 matmul
over the same grid weights for bf4_b/bf8_b x bf16/fp16/fp32 at
m = 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:

ruff check gptqmodel/utils/tt_blockfloat_cuda.py tests/test_tt_blockfloat_cuda.py
git diff --check
  • Unit tests have been executed and passed, or the reason they are not applicable is documented.
  • I added a new simple/fast unit test for this change, or documented why that is not applicable.

Four tests in tests/test_tenstorrent_support.py fail in this environment. They
fail identically on main (4 failed / 92 passed there too), because torch_xla
is not installed.

Model Support / Module Plan

Not applicable — no MODEL_MAP entry, 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

  • Reviewed this PR.
  • Checked that the code matches existing project structure, APIs, and conventions.
  • Avoided unnecessary monkeypatching and used the project's normal extension points where possible.
  • Minimized and compacted the impacted code surface.
  • Considered and eliminated potential regressions.

Kernel Accuracy Requirements

  • For kernel-related changes, accuracy drift was measured against an applicable independent Torch FP32/FP64 oracle, or the reason this is not applicable is documented.
  • Fusion support changes preserve AUTO's native class and add actual-device FP16/BF16 tests where supported, native shape/workspace/descriptor checks, mutation, direct source calls, exact restoration and packed-storage checks. — not applicable, no fusion change.
  • The complete kernel inventory/device report lists unavailable dependencies, architecture restrictions and unqualified formats; skips are not validation.

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_b
values 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

  • Reviewer caveat: CI has no GPU here, so the evidence in this PR comes from
    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.
  • The extension requires sm_80 (mma.sync.m16n8k16 with bf16 inputs) and is
    gated on torch.cuda.get_device_capability; ROCm reports a gfx-derived
    capability, so the loader explicitly excludes torch.version.hip to avoid
    sending a ROCm build at a CUDA kernel.
  • Follow-up worth doing: a cuBLASLt path with CUBLASLT_EPILOGUE_BIAS, which
    would 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 a
regression test that fails against the previous implementation.

  • [P1] stream-independent workspace. Scratch is per call (a TemporaryBuffer
    freed with cudaFreeAsync on the calling stream), and the cuBLAS handle is now
    per (device, stream) instead of per device, since a handle carries its own
    device-side workspace. test_overlapping_streams_get_independent_scratch
    reproduces the reported scenario (two streams, M=1024, N=K=4096, constant
    weights 1.0 and 1.5, exact expected sums); it corrupted output before the fix.
  • [P2] live workspace. Nothing is retained between calls:
    cudaMemPoolAttrUsedMemCurrent returns to zero once the stream drains.
    test_scratch_is_not_left_live_in_the_async_pool measured 48 MB live in the
    default 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).
  • [P2] strided activations. The binding materialises the activation with
    contiguous(), a no-op when already packed, so x[:, ::2] keeps working.
    test_linear_accepts_strided_activations covers the module and the raw op.
  • [P2] grid.y limit. The epilogue strides rows across at most 65535 blocks
    instead of mapping one row per blockIdx.y.
    test_linear_handles_a_full_grid_y covers M = 65536, N = 1, K = 16.

Re-validated after the change: 84 CUDA tests pass
(tests/test_tt_blockfloat_cuda.py); tests/test_tenstorrent_support.py
gives 106 passed / 15 skipped with only the same 4 pre-existing torch_xla
failures that also fail on main; the forced no-cuBLAS fallback still matches
the 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:

  • [P1] Odd n in the fused fallback. The MMA epilogue owns a pair of
    adjacent 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=1 forces the fallback at run time, which is
    how test_fused_fallback_masks_an_odd_output_width reaches it; the whole
    linear validation was re-run through the forced fallback as well.
  • [P2] Empty forwards. TTBlockfloatEmbedding and TTBlockfloatTiedHead
    returned to the dense paths' (0, 16) / (1, 0, 3) shapes instead of
    launching a zero-block kernel or rejecting a zero-row activation, and the
    bindings tolerate empty operands for direct callers.
    test_empty_inputs_keep_their_shapes covers both modules and the raw op.

Rebased onto main at e5e13ca6 (the ROCm/HIP merge, #3806), head 67004a01.
Two conflicts, both resolved by keeping both backends rather than choosing one:

Base automatically changed from feat/tenstorrent-investigation to main November 13, 2026 04:39
@Qubitium
Qubitium force-pushed the feat/tt-blockfloat-cuda-emulation branch from fa38994 to a2adce5 Compare November 13, 2026 04:48

Copy link
Copy Markdown
Collaborator Author

Review of a2adce584912171bf00acbda31242a94152395fc against 276605140c04d8b58b145f7245c7e3b11dd5cfee. Four findings reproduced on an RTX 4090:

  1. [P1] Give overlapping CUDA calls independent workspace lifetimes. tt_blockfloat_cuda.cu:762–781 returns the same scratch pointer for every stream on a device. The mutex protects allocation only; it does not order the queued dequantization, GEMM and epilogue. Two ordinary stream-scoped forwards can overwrite each other's decoded weights/accumulators. Reproduction: BF16 activations, bf8 weights, M=1024,N=K=4096, two streams, all-one activations, weights equal to 1 and 1.5 respectively (valid codes 191 and 223, exponent 0). The Torch reference is exact on both streams, while the new kernel corrupted 2,384,512; 2,447,488; and 4,194,304 output values in three trials. This occurs from one Python thread with the GIL enabled. Use call-local stream-aware storage or properly leased workspace with completion events; a host-only lock around allocation cannot make asynchronous use safe. The shared mutable cuBLAS handle also needs an explicit concurrency policy.

  2. [P2] Release dense workspace after its consuming operation. tt_blockfloat_cuda.cu:756–788 retains a live raw allocation at the largest size ever requested on each device, with no release path. It contains expanded weights and accumulators after the forward returns, contrary to the repository's persistent quantized-storage rule. A 1 × 8192 FP16 activation against an 8192 × 8192 weight left 134,250,496 bytes live in the CUDA async pool after deleting every input/output, synchronizing, collecting garbage and calling torch.cuda.empty_cache(); Torch reported zero allocated bytes. A subsequent tiny forward did not release it. This is live allocation, not merely allocator-reserved free memory. Use temporary storage whose ownership ends after GPU consumption and let the allocator reuse freed blocks; retain only packed representations between calls.

  3. [P2] Preserve support for strided activations. tt_blockfloat.py:165–167 reshapes the activation but does not ensure contiguity. For a valid x = torch.randn(3,64,device="cuda")[:,::2], the resulting (3,32) tensor retains stride (64,2). The previous F.linear path succeeds; the new module forward raises x must be a contiguous 2D CUDA tensor. Materialize a contiguous activation before dispatch, or retain the fallback for unsupported strides. The helper is also used by the tied head.

  4. [P2] Avoid placing the entire token count in CUDA grid.y. tt_blockfloat_cuda.cu:903–905 launches the cuBLAS epilogue with grid.y = m, exceeding CUDA's limit at 65,536 rows. M=65536,N=1,K=16 with all-one inputs fails with invalid argument for FP16 and BF16; M=65535 succeeds, and the Torch reference returns 16 for both sizes. Flattened batch/sequence dimensions can reach this boundary in normal long-context workloads. Use a one-dimensional/grid-stride epilogue or chunk the row dimension.

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.

@Qubitium

Copy link
Copy Markdown
Collaborator Author

Fixed all four in e6d836ac, each with a regression test that fails against the previous build.

1. [P1] Overlapping streams. Scratch is now owned by the call: a TemporaryBuffer allocated per call and freed with cudaFreeAsync on the calling stream, so nothing is shared and the free is ordered behind the kernels that read it. The cuBLAS handle is now per (device, stream) rather than per device — a handle carries a device-side workspace, so serialising the enqueue alone was not enough, as you noted.

2. [P2] Live workspace. Nothing is retained: cudaMemPoolAttrUsedMemCurrent returns to zero once the stream drains. I kept a pool, but a private per-device one rather than the default. Your instinct that this is allocator territory is right — the reason I had cached it is measurable: the default pool returns every freed block to the driver, so a fresh 34 MB alloc/free pair costs 1862 us, against 12 us from a pool that keeps its blocks. The private pool is also what stops us perturbing the process default pool (relevant when torch is configured with backend:cudaMallocAsync). It holds reserved memory, not live allocations.

3. [P2] Strided activations. The binding materialises the activation with contiguous() (a no-op when already packed), so x[:, ::2] keeps the behaviour the dense path had. Covered at both the module and the raw-op level.

4. [P2] grid.y. The epilogue strides rows across at most 65535 blocks instead of mapping one row per blockIdx.y; M = 65536, N = 1, K = 16 now works.

Verification: I confirmed the two new behavioural tests are not tautological by rebuilding with the old shared-buffer behaviour — test_overlapping_streams_get_independent_scratch corrupted, and test_scratch_is_not_left_live_in_the_async_pool read 48 MB live. Both pass now. 82 CUDA tests pass (174 with test_tenstorrent_support.py, plus the same 4 pre-existing torch_xla failures that also fail on main). I also rebuilt with the cuBLAS probe forced to fail, since you flagged the fallback as unrequalified: it matches the reference on all 10 shape/dtype cases. Throughput is unchanged — 46/58/52/54/72/96/147/254 us for 1/16/32/64/128/256/512/1024 tokens.

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, cudaMemPoolTrimTo after a shrink is a small follow-up.

Copy link
Copy Markdown
Collaborator Author

Review of e6d836ace7bcf209e76cd0c5a4ea42478b807842 against 276605140c04d8b58b145f7245c7e3b11dd5cfee. The four earlier findings have fixes in this head, and their regression tests pass. Two additional findings:

  1. [P1] Mask the second output column in the fused fallback. In tt_blockfloat_cuda.cu:595–604, the gn < n guard covers two stores, but gn + 1 is out of bounds whenever n is odd. The corresponding bias[gn + 1] read is also unguarded. Odd output widths are supported by the module. This becomes a memory overwrite when cuBLAS is unavailable or returns CUBLAS_STATUS_NOT_SUPPORTED, selecting the advertised fused fallback. Actual SM80 reproduction: BF16 activations of ones, M=1,K=16,N=1/3/5, bf4 codes 0x88, exponent zero, no bias. A separately allocated output with one trailing canary returned the correct 4.0 for every valid element but overwrote the canary from 123 to -28 in all three cases. The probe compiled an isolated copy with only the cuBLAS dispatch predicate disabled; the fused kernel was unchanged. Guard the second bias load and both second-column stores with gn + 1 < n, and add odd-N fallback coverage with an output boundary check.

  2. [P2] Preserve empty embedding and tied-head forwards. The new embedding dispatch reaches a zero-block kernel launch for empty IDs, while the linear binding rejects the empty activation passed by TTBlockfloatTiedHead. With e = TTBlockfloatEmbedding(3,16,bits=4).cuda(), e(torch.empty(0,device='cuda',dtype=torch.int64)) raises blockfloat_embedding failed: invalid argument; TTBlockfloatTiedHead(e)(torch.empty(1,0,16,device='cuda',dtype=torch.bfloat16)) raises x must not be empty. The existing dense paths return shapes (0,16) and (1,0,3) respectively. Return correctly shaped empty outputs before native dispatch, as TTBlockfloatLinear.forward already does, and cover both public modules.

Validation: 82/82 supplied CUDA tests passed on NVIDIA PG506-230 (SM80), Python 3.14.7 with PYTHON_GIL=0, Torch 2.15.0.dev20260928+cu130; git diff --check passed. The empty-input failures were reproduced through the actual Torch extension, and the fallback overwrite through the standalone native kernel. The local sccache/NVCC invocation initially failed to produce its cubin; rebuilding the generated build commands without sccache succeeded with unchanged repository sources. This review did not requalify all fallback shapes, other GPU architectures, or concurrent Python-thread safety. No tracked source edits.

@Qubitium

Copy link
Copy Markdown
Collaborator Author

Both fixed in b991a9fd, each with a test verified to fail against e6d836ac.

1. [P1] Odd-N overwrite in the fused fallback. Correct, and the guard was only on the first column of the pair: bias[gn + 1] and both second-column stores are now behind gn + 1 < n. Your diagnosis of why it survived review is exactly right — every test I had went through cuBLAS, so the fallback was only ever checked at even widths.

To stop that happening again I added GPTQMODEL_BLOCKFLOAT_NO_CUBLAS=1, which forces the fused path at runtime. The new test spawns a subprocess with it set, reproduces your case (M=1, K=16, bf4 0x88, exponent 0, no bias, N=1/3/5, 4.0 expected) and asserts a trailing sentinel is untouched. It reports a written canary against e6d836ac and passes now. I also re-ran the whole linear validation through the forced fallback — 10/10 shape and dtype cases match the reference, so the other fallback shapes are requalified too.

2. [P2] Empty embedding and tied-head forwards. Both now return the dense path's shape and dtype before dispatch — (0, 16) float32 for the embedding, (1, 0, 3) in the activation's dtype for the tied head — matching what F.embedding/F.linear produce. I also made the bindings tolerate empty operands (m == 0, tokens == 0 return early instead of launching a zero-block grid or raising), so direct torch.ops callers behave the same way. The test asserts shape, dtype and equality with the dense path for both modules plus the raw op; it raises against e6d836ac.

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 sccache to the compile line when it finds it on PATH, and sccache breaks nvcc's fatbinary step for any extension here (Could not open ... .cubin). Removing sccache from PATH makes the normal build work with unchanged sources, which matches what you saw.

@Qubitium
Qubitium marked this pull request as ready for review November 13, 2026 06:28
@Qubitium Qubitium changed the title feat(tenstorrent): run bf8/bf4 checkpoints on CUDA with emulation kernels feat(tenstorrent): run bf8/bf4 checkpoints on CUDA kernels Nov 13, 2026
@Qubitium
Qubitium force-pushed the feat/tt-blockfloat-cuda-emulation branch from b991a9f to f23cf52 Compare November 13, 2026 06:33
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.
@Qubitium
Qubitium force-pushed the feat/tt-blockfloat-cuda-emulation branch from f23cf52 to 67004a0 Compare November 13, 2026 06:40
@Qubitium

Copy link
Copy Markdown
Collaborator Author

Rebased onto main at e5e13ca6 (the ROCm/HIP merge, #3806); head is now 67004a01, and GitHub reports the PR as mergeable.

Two conflicts, both resolved by keeping both backends:

  • docs/tenstorrent.md: the ROCm section from feat(tenstorrent): run bf8/bf4 checkpoints on ROCm with HIP kernels #3806 is kept, and the CUDA emulation text follows as its own section.
  • tt_blockfloat.py: the HIP dispatch moved into the shared _kernel_linear / _kernel_embedding helpers, so one call site tries HIP first and then CUDA. No behaviour change on either device.

The TTBlockfloatEmbedding.output_dtype behaviour from #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 == 2 module still takes the torch path, since neither kernel implements it.

Re-ran after the rebase: tests/test_tt_blockfloat_cuda.py 84 passed; tests/test_tenstorrent_support.py 106 passed / 15 skipped with only the same 4 pre-existing torch_xla failures that also fail on main; ruff check clean.

@Qubitium
Qubitium merged commit ceb54e8 into main Nov 13, 2026
6 checks passed
@Qubitium
Qubitium deleted the feat/tt-blockfloat-cuda-emulation branch November 13, 2026 06:54
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.

1 participant