Repository navigation
feat(tenstorrent): run bf8/bf4 checkpoints on ROCm with HIP kernels - #3806
Conversation
1b44e46 to
ed9fd72
Compare
|
Review of
Validation: built the unchanged native kernels with HIP 7.16.26385 for an AMD Radeon AI PRO R9700 ( Limits: the installed Torch is CUDA-only ( |
|
All five findings are fixed in
Detail worth calling outFinding 3 root cause. Finding 4 root cause. The harness's own reference quantiser had the identical strict comparison against Finding 5 scope. Incidental performanceHoisting the per-element
Min of 6 runs each, old and new binaries interleaved. Re-validated
|
|
Reviewed current head
Validation: 12 selected tests passed from |
|
Both fixed in 1. int32 embedding indices. Fixed in the binding and the module forward. 2. Empty batches. Two separate guards, both fixed:
Regression coverage, all failing on
The empty-batch harness check calls Re-validated: harness 57 PASS / 0 FAIL, Still not exercised here, as before: the Torch C++ binding and JIT extension, because this host's Torch is CUDA-only. Findings 1 and 2's binding changes are covered by reading the guards and by the module-level tests; the native launcher changes are covered on real gfx1201 hardware. |
bfloat8_b / bfloat4_b checkpoints could only be executed on a Tenstorrent device, so the formats could not be tested or emulated on any other hardware. Add a torch-free HIP implementation that consumes the checkpoint exactly as the Tenstorrent runtime does -- packed uint8 codes plus one int8 exponent per 16 consecutive K values -- with nothing requantised, converted to int4, or expanded on the host. It covers dequant, quantize, decompose, an embedding gather, and a fused unpack+GEMM. TTBlockfloatLinear / Embedding / TiedHead dispatch to the extension when the module is on a ROCm device and keep the torch path everywhere else. Prefill on gfx1200/gfx1201 uses the RDNA4 bf16 matrix cores. The tile shape is chosen from the token count because two properties dominate: the M block fixes how often the packed weight is re-read (once per block, and the 9 MiB bf4 weight no longer fits the 8 MiB L2), and the warp block fixes LDS traffic per WMMA (1 KiB at 16x16, 512 B at 32x32). 128x128 CTA blocks with 32x32 warp tiles take a 4096x4096 bf4 layer from 444 us to 185 us at 512 tokens (38 -> 93 TFLOP/s); decode is at the memory roofline at ~18 us. Validation works without a ROCm-built PyTorch: a standalone hipcc harness compares every kernel against an independent CPU implementation, and verify_against_torch.py cross-checks the same outputs against gptqmodel.utils.tt_blockfloat_quant. The .hip/.h sources are added to the .gitignore allow-list. That list is the only thing keeping hand-written ROCm sources in the repo, so without the entry the checkout would not build.
bfloat2_b is the third block-float width the Tensix packer understands
(DataFormat::Bfp2_b in the Blackhole LLK, and Block FP2 appears among the
Blackhole matrix-engine input formats), so the p300c silicon can hold it. Two
bits are one sign and one magnitude, so a 16-value block holds only
{-1, 0, +1} x 2**exponent -- three levels, not a usable weight format.
Add the grid so its cost can be measured: stored_mantissa_bits(2) is 0, the
quantiser and decompose accept two bits, and codes pack four per byte. The
pack/unpack round-trips exactly.
The HIP kernels deliberately do not implement it. ttnn exposes only
bfloat16, bfloat8_b, bfloat4_b, float32 and the integer types, so no checkpoint
can contain bfloat2_b and there is no oracle to validate a kernel against;
supports_bits() keeps a bits == 2 module on the torch path.
The kernel is unchanged. Four more shapes were measured and rejected, so the next person does not have to repeat them: 64x32 and 32x64 warp blocks (384 B of fragments per WMMA, but 24 warps per CU), 64x128 and 128x256 CTA blocks, a depth-2 register prefetch, and swapping the grid axes. The binding constraints are 64 KB of LDS per workgroup and 128 VGPRs per thread at the three CTAs per CU that footprint allows, and the single shared buffer still serialises the store behind the load. Also document why bfloat2_b has a grid but no kernel.
…ming #3760 landed with `bf4_b` / `bf8_b` as the canonical names and the vendor spellings `bfloat4_b` / `bfloat8_b` kept only for the `getattr(ttnn, ...)` call site. Follow that here: the kernel headers, the loader docstring and the extension README now say `bf8_b` / `bf4_b`, and the README records the vendor spelling once. `bf2_b` is folded into the same structure: it is a canonical name in `TT_BLOCKFLOAT_DTYPES` but has no entry in `TT_BLOCKFLOAT_VENDOR_ATTRS`, since ttnn exposes no `bfloat2_b` attribute. Its bit-level definition moves to `hw/dtypes.md` §8.6, which is where #3760 put the format reference. `packed_code_bytes` now follows the merged round-up rule (the packer pads), with a two-bit case added, instead of the round-down form this branch had. The loader also adopts the sibling HIP modules' typing style (`Path | None`, builtin generics) so the three loaders read the same.
…date Two correctness bugs found in review, both reproduced on gfx1201 before the fix and covered by the harness afterwards. The API only promises ``k % 16 == 0``, but a thread stages a ``kCodes``-wide span -- 16, 32, 64 or 128 depending on the tile -- so a k that is not a multiple of the tile width ends the last tile mid-span. ``issue`` only loaded a span when the whole span fitted, and ``store`` then wrote zeros for the entire span, discarding the valid leading columns with it. With bf4 weights and bf16 activations at n=3, k=16 returned 0 instead of the full dot product, and k=144 returned 128 instead of 144. Partial spans now zero-fill past k and keep the columns below it. The quantiser took the base exponent candidate only when its squared error compared strictly below infinity. For inputs near FLT_MAX every candidate's error overflows, so the winning codes were never initialised and a 1e30 block reconstructed as zero where Torch gives 9.507e29 (bf4) and 1.0003e30 (bf8). The base candidate is now taken unconditionally, matching the Torch reference. The harness's own reference quantiser had the same strict comparison, which is why the existing checks never caught the second bug; it is fixed too. New probes: a K sweep over 16/32/48/80/144/160/272 at one m per launcher tier, and a 1e30 block checked against the reference and against the expected magnitude. Both fail on the previous kernel (16 failures) and pass now. Hoisting the per-element ``w_ok`` test out of the staging loop while fixing the span bug also helped the shapes with the widest spans: m=16 went from 44.8 us to 32.1 us and m=32 from 39.0 us to 34.4 us.
Three routing bugs found in review. The binding requires a 2-D activation, but ``TTBlockfloatLinear.forward`` passed ``x`` through unchanged, so a normal ``[batch, sequence, hidden]`` input raised "activation must be 2-D" once the HIP path was available; the previous ``F.linear`` path accepted it. Flatten the leading dimensions and restore them afterwards, in both the linear and the tied-head path, including the 1-D case where ``F.linear`` returns ``[out_features]``. ``TTBlockfloatTiedHead`` has no ``bits`` attribute -- it only holds a reference to the embedding -- so the dispatch guard raised ``AttributeError`` on every forward that reached it. Use the embedding's storage. The dispatch also ignored ``block``. The kernels bind one exponent per 16 values, so ``TTBlockfloatEmbedding(3, 32, bits=4, block=32)``, which the Torch path handles, was routed to a binding that rejects its exponent shape. The guard is now one ``hip_dispatch`` helper used by every call site (linear, pack, embedding, dequantize, tied head) that checks device, block and width. Tests are CPU-only: they mock backend availability and the kernel entry points so the routing is exercised without a ROCm Torch build. They fail on the previous code and pass now.
The staging rewrite moved the small-M shapes: m=16 is 32 us (was 45) and m=32 is 35 us (was 39), because those two have the widest per-thread spans and the store loop is the largest share of their work. The rest are unchanged within run-to-run noise, which on this card is bimodal (two clock states), so the table reports the fast mode. Also record what the review fixes guarantee: any in_features that is a multiple of 16 works, including one that is not a multiple of the tile width, and a block whose squared error overflows still produces the reference codes. Document that storage with block != 16 stays on the Torch path, and spell bf2_b the way the merged branch does.
Two compatibility regressions found in review: the HIP path rejected inputs the Torch fallback accepted. ``F.embedding`` accepts int32 or int64 indices, but the binding required int64 while ``TTBlockfloatEmbedding.forward`` forwarded the caller's dtype unchanged, so an int32 index tensor raised where the fallback worked. The binding now widens int32 to int64 itself, and the module forward does the same before the call so the conversion is visible and testable on a CPU-only host. An empty batch is a success with correctly shaped output, but two guards ran before the empty short-circuit. ``ttbf_embedding`` checked ``ids``/``out`` for null before its ``tokens == 0`` branch, and ``ttbf_linear`` rejected ``m <= 0`` outright; a fresh empty Torch tensor has null data pointers, so both failed. The launchers now return success for an empty batch before the pointer checks, and the embedding and tied-head forwards short-circuit an empty batch the way ``TTBlockfloatLinear`` already did. New coverage: a native empty-batch check in the harness (fails on the previous kernel, 2/2), plus CPU routing tests for int32 indices and empty embedding and tied-head batches (both fail on the previous module code).
6312369 to
fa21a78
Compare
|
Rebased onto One conflict, in That also corrected the empty-batch short-circuit from the previous commit, which returned Re-validated after the rebase: harness 57 PASS / 0 FAIL, |
Summary
bf8_b/bf4_bcheckpoints could only be executed on a Tenstorrent device, sothe formats could not be tested or emulated on any other hardware.
This adds a torch-free HIP implementation so they can run on AMD GPUs.
#3760 is merged into
main; this branch is rebased onto it and follows itsconventions:
bf4_b/bf8_bare the canonical names, the vendor spellingsbfloat4_b/bfloat8_bappear only at thegetattr(ttnn, ...)call site, andthe bit-level format reference lives in
hw/dtypes.md.What Changed
gptqmodel_ext/tt_blockfloat_hip/— new HIP 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:
dequant,quantize,decompose,embedding,linear(fused unpack + GEMM), and aselftestsentinel.gptqmodel/utils/tt_blockfloat_hip.py— JIT loader and Python API.tt_blockfloat.py—TTBlockfloatLinear/Embedding/TiedHeadusethe extension when the module is on a ROCm device; the torch path is
unchanged and remains the fallback everywhere else.
.gitignore— added the two hand-written sources to the explicitallow-list. That list is the only thing keeping non-hipified ROCm sources in
the repo, so without the entry the checkout does not build.
MANIFEST.in— ship the new sources in the sdist.gptqmodel_ext/tt_blockfloat_hip/README.mdanddocs/tenstorrent.mddescribe the format, the kernels, the tile choices andthe measured numbers.
Prefill tile shape
The RDNA4 bf16 matrix-core path picks its CTA block, warp block and K tile from
the token count:
m <= 16m <= 32m <= 64m > 64Two properties dominate. The M block sets how often the packed weight is
re-read, once per block: at 32 rows and 512 tokens the 9 MiB bf4 weight is
streamed sixteen times and no longer fits the 8 MiB L2. The warp block sets
LDS traffic per WMMA: 16x16 needs one A and one W fragment (1 KiB) for a single
WMMA, which at 128 B/cycle is longer than the WMMA itself, while 32x32 reuses
each fragment across two quadrants (512 B).
4096x4096 bf4, bf16 activations, Radeon AI PRO R9700 (
gfx1201), median of 5:Decode (
m == 1) is at the memory roofline: ~18 us, ~477 GB/s on the packedcode stream (~552 GB/s counting exponents) against 607 GB/s measured for a pure
float4read loop.Out of scope
m <= 32. Those shapes have 256 and 512 output tiles, so thecard only gets 8 and 16 warps per CU and reaches 12 / 27 TFLOP/s. That is a
parallelism ceiling, not a tuning miss (a 32x32 warp block at 32 tokens halves
LDS traffic but leaves four warps on the card and measured slower). Raising it
needs a partial-sum workspace and a reduction pass, which changes the public
API, so it is deliberately not included.
writes it; permuting codes into 32x32 face order is a device layout concern
and not part of the dtype emulation.
bfloat2_b
bfloat2_bis the third block-float width the Tensix packer understands(
DataFormat::Bfp2_bin the Blackhole LLK, and Block FP2 is listed among theBlackhole matrix-engine input formats), so the p300c silicon can hold it. It is
not a usable weight format and not reachable through
ttnn: two bits areone sign and one magnitude, so a 16-value block holds only
{-1, 0, +1} x 2**exponent, andttnnexposes onlybfloat16,bfloat8_b,bfloat4_b,float32and the integer types.This PR defines the grid --
stored_mantissa_bits(2) == 0, quantise/decomposeaccept two bits, four codes per byte, exact pack/unpack,
quantize_bf2with thequantize_bfloat2_balias -- so the cost of that grid can be measured.bf2_bis a canonical name in
TT_BLOCKFLOAT_DTYPESbut has noTT_BLOCKFLOAT_VENDOR_ATTRSentry, because ttnn exposes nobfloat2_battribute. It deliberately does not add a HIP kernel: no checkpoint can
contain
bfloat2_band there is no oracle to validate a kernel against.supports_bits()keeps abits == 2module on the torch path.Where large-M prefill stops
The kernel is unchanged from the previous revision; four more shapes were
measured and rejected, and are recorded in the README so they are not repeated.
The binding limits are 64 KB of LDS per workgroup and 128 VGPRs per thread at
the three CTAs per CU that footprint allows.
With staging or the matrix-core block compiled out, staging costs 15 us and the
matrix core 92 us, but together 184 us: with one shared buffer the store at the
bottom of each step waits on a load issued one step earlier. Removing that wait
needs a second shared buffer (does not fit) or a second set of staging registers
(does not fit either).
Tests
Every kernel is checked against an independent CPU implementation, and the same
outputs are cross-checked against
gptqmodel.utils.tt_blockfloat_quant.Correctness is checked at
m = 1, 15, 16, 17, 31, 32, 33, 64, 65, 100, 128, 256— every launcher boundary and both sides of it — for bf4 and bf8, andseparately with
n = 100to exercise partial-N masking in the 128-wide block.A
ksweep over 16/32/48/80/144/160/272 covers partial K tiles at onemperlauncher tier, a
1e30block covers the quantiser's overflowing-error path, anda null-pointer
tokens=0/m=0call covers the empty-batch launchers.Portability and lint:
tests/test_tenstorrent_support.py::test_bfloat2_b_grid_is_three_levels_and_packs_four_per_bytecovers the new grid on CPU, and
test_blockfloat_mantissa_widths/test_blockfloat_dtype_names_are_canonicalare updated for the third width.That file also has seven pre-existing failures (XLA / transformers loading,
unrelated to this PR);
mainfails the same seven, and this branch adds onemore passing test.
tests/test_tt_blockfloat_hip.pyparametrises the same M set. Note that theCI host has a CUDA-only PyTorch build, so the ROCm tests skip there and report
64 collected / skipped. That is why the
hipccharness above is the primaryevidence: it needs only a ROCm compiler, no ROCm PyTorch.
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.
Review Requirements
Kernel Accuracy Requirements
bf8/bf4 values are exact grid points and exactly representable in bf16 (7 and 3
significant bits), so the matrix-core path adds no rounding of its own; the
harness reports
norm_l1 = 0against the fp32 oracle. The WMMA path is selectedat runtime from
gcnArchName; CDNA and RDNA3 keep the register-tiled fp32 GEMM,which is also what fp16/fp32 activations use.
Notes
PR comes from a Radeon AI PRO R9700 (
gfx1201) with ROCm 7.16 / HIP 7.16.26385,via the standalone harness. Please do not treat the green CUDA jobs as
coverage of the new kernels.
m <= 32, and a packed-code shared tile(halves bf4 LDS) to allow more resident CTAs.