Skip to content

feat(tenstorrent): run bf8/bf4 checkpoints on ROCm with HIP kernels - #3806

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

Qubitium merged 8 commits into
mainfrom
feat/tt-blockfloat-hip-emulation

Conversation

@Qubitium

@Qubitium Qubitium commented Nov 13, 2026 •

Copy link
Copy Markdown
Collaborator

Summary

bf8_b / bf4_b checkpoints could only be executed on a Tenstorrent device, so
the 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 its
conventions: bf4_b / bf8_b are the canonical names, the vendor spellings
bfloat4_b / bfloat8_b appear only at the getattr(ttnn, ...) call site, and
the bit-level format reference lives in hw/dtypes.md.

What Changed

  • gptqmodel_ext/tt_blockfloat_hip/ — new HIP 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: dequant,
    quantize, decompose, embedding, linear (fused unpack + GEMM), and a
    selftest sentinel.
  • gptqmodel/utils/tt_blockfloat_hip.py — JIT loader and Python API.
  • tt_blockfloat.py — TTBlockfloatLinear / Embedding / TiedHead use
    the 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 explicit
    allow-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.
  • Docs — gptqmodel_ext/tt_blockfloat_hip/README.md and
    docs/tenstorrent.md describe the format, the kernels, the tile choices and
    the measured numbers.

Prefill tile shape

The RDNA4 bf16 matrix-core path picks its CTA block, warp block and K tile from
the token count:

tokens CTA block warp block K threads
m <= 16 16x64 16x16 256 128
m <= 32 32x64 16x16 256 256
m <= 64 64x64 16x16 128 256
m > 64 128x128 32x32 64 512

Two 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:

tokens before after TFLOP/s speedup
16 51.2 us 45.7 us 11.8 1.12x
32 39.5 us 39.4 us 27.3 1.00x
64 64.9 us 44.2 us 48.6 1.47x
128 119.9 us 58.1 us 73.9 2.06x
256 232.9 us 94.0 us 91.4 2.48x
512 443.9 us 185.3 us 92.7 2.40x

Decode (m == 1) is at the memory roofline: ~18 us, ~477 GB/s on the packed
code stream (~552 GB/s counting exponents) against 607 GB/s measured for a pure
float4 read loop.

Out of scope

  • Split-K for m <= 32. Those shapes have 256 and 512 output tiles, so the
    card 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.
  • 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.

bfloat2_b

bfloat2_b is the third block-float width the Tensix packer understands
(DataFormat::Bfp2_b in the Blackhole LLK, and Block FP2 is listed among the
Blackhole 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 are
one sign and one magnitude, so a 16-value block holds only
{-1, 0, +1} x 2**exponent, and ttnn exposes only bfloat16, bfloat8_b,
bfloat4_b, float32 and the integer types.

This PR defines the grid -- stored_mantissa_bits(2) == 0, quantise/decompose
accept two bits, four codes per byte, exact pack/unpack, quantize_bf2 with the
quantize_bfloat2_b alias -- so the cost of that grid can be measured. bf2_b
is a canonical name in TT_BLOCKFLOAT_DTYPES but has no
TT_BLOCKFLOAT_VENDOR_ATTRS entry, because ttnn exposes no bfloat2_b
attribute. It deliberately does not add a HIP kernel: 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.

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.

variant m=512 why it is not used
32x32 warp block (baseline) 185 us 512 B of fragments per WMMA, 48 warps/CU
64x32 or 32x64 warp block 207-208 us 384 B per WMMA, but only 24 warps/CU
64x128 CTA block 262 us 4 CTAs/CU, but 8 warps each
128x256 CTA block 193 us 2 CTAs/CU
depth-2 register prefetch 262 us second staging tile pushes VGPRs past 128/thread, 3 CTAs -> 2
swap the grid axes 184 us neutral

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.

# kernels vs independent CPU oracle (57 checks, both dtypes)
hipcc --offload-arch=gfx1201 -O3 -std=c++17 \
    tt_blockfloat_hip.hip tt_blockfloat_hip_selftest.cpp -o ttbf_selftest
./ttbf_selftest --dump /tmp/ttbf_dump
# -> 57 PASS / 0 FAIL, "OK (0 failures)"

# same outputs vs the checkpoint oracle
python verify_against_torch.py /tmp/ttbf_dump
# -> OK; quantize/dequant/embedding bit-exact, WMMA bf16 norm_l1 = 0

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, and
separately with n = 100 to exercise partial-N masking in the 128-wide block.
A k sweep over 16/32/48/80/144/160/272 covers partial K tiles at one m per
launcher tier, a 1e30 block covers the quantiser's overflowing-error path, and
a null-pointer tokens=0 / m=0 call covers the empty-batch launchers.

Portability and lint:

hipcc --offload-arch=gfx1100 -O3 -std=c++17 -c tt_blockfloat_hip.hip   # OK
hipcc --offload-arch=gfx90a  -O3 -std=c++17 -c tt_blockfloat_hip.hip   # OK
hipcc --offload-arch=gfx1201 -O3 -std=c++20 -DENABLE_BF16 -c ...       # OK
ruff check gptqmodel/utils/tt_blockfloat_hip.py tests/test_tt_blockfloat_hip.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.

tests/test_tenstorrent_support.py::test_bfloat2_b_grid_is_three_levels_and_packs_four_per_byte
covers the new grid on CPU, and test_blockfloat_mantissa_widths /
test_blockfloat_dtype_names_are_canonical are updated for the third width.
That file also has seven pre-existing failures (XLA / transformers loading,
unrelated to this PR); main fails the same seven, and this branch adds one
more passing test.

tests/test_tt_blockfloat_hip.py parametrises the same M set. Note that the
CI host has a CUDA-only PyTorch build, so the ROCm tests skip there and report
64 collected / skipped. That is why the hipcc harness above is the primary
evidence: it needs only a ROCm compiler, no ROCm PyTorch.

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.

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.

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 = 0 against the fp32 oracle. The WMMA path is selected
at runtime from gcnArchName; CDNA and RDNA3 keep the register-tiled fp32 GEMM,
which is also what fp16/fp32 activations use.

Notes

  • Reviewer caveat: CI cannot exercise the ROCm paths. The evidence in this
    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.
  • Follow-up worth doing: split-K for m <= 32, and a packed-code shared tile
    (halves bf4 LDS) to allow more resident CTAs.

Base automatically changed from feat/tenstorrent-investigation to main November 13, 2026 04:39
@Qubitium
Qubitium force-pushed the feat/tt-blockfloat-hip-emulation branch from 1b44e46 to ed9fd72 Compare November 13, 2026 04:44
Comment thread gptqmodel/utils/tt_blockfloat_hip.py Dismissed

Copy link
Copy Markdown
Collaborator Author

Review of ed9fd7240ffe00d1974a115e0bd594d5fd040e16 against 276605140c04d8b58b145f7245c7e3b11dd5cfee, performed by a fresh subagent with parent verification. Five actionable findings:

  1. [P1] Flatten leading activation dimensions before HIP linear. tt_blockfloat.py:288 passes x unchanged, while the binding requires a two-dimensional activation. Ordinary transformer inputs such as [batch, sequence, hidden] = (1,2,16) therefore fail with activation must be 2-D once the HIP path is available; the previous F.linear path accepted them. Reshape to (-1,K) and restore leading dimensions afterward, including the tied-head path. Confirmed through the actual Python forward with a mocked native entry point and the binding's explicit check; this is a routing reproduction, not a ROCm Torch numerical test.

  2. [P1] Use the embedding's bit width in the tied-head dispatch. tt_blockfloat.py:383 evaluates self.bits, but TTBlockfloatTiedHead has no such attribute. Every forward that reaches this condition on an available HIP backend raises AttributeError before kernel execution. Constructing a tied head around TTBlockfloatEmbedding(3,16,bits=4) and mocking only backend availability reproduces the real Python exception. Use embedding.bits.

  3. [P1] Mask partial K spans instead of dropping them in WMMA staging. tt_blockfloat_hip.hip:908 loads a thread's weight span only when gk + kCodes <= k; otherwise the entire span becomes zero. The API permits K divisible by 16, while these spans can cover 64 or 128 weights. On actual gfx1201 hardware, BF16 activations and BF4 weights all equal to one, N=3: M=2,K=16 returns 0 instead of 16, and M=2,K=144 returns 128 instead of 144. The same failures occur at M=16,17,32; the targeted probe failed 12 of 40 configurations. Load valid elements in partial spans, or use a correct fallback for those K alignments.

  4. [P2] Initialize the base quantization candidate before comparing SSE. tt_blockfloat_hip.hip:298 starts with infinite error and uninitialized codes. For finite large inputs, every squared-error sum can overflow to infinity, so the strict comparison never initializes the winning codes. On gfx1201, quantizing a (1,16) matrix filled with 1e30 reconstructs zero for both widths. The Torch reference produces approximately 9.5073795e29 at four bits and 1.00025555e30 at eight bits. Initialize the first candidate unconditionally, matching Torch's behavior even when errors overflow.

  5. [P2] Keep non-16-block embeddings on the Torch fallback. tt_blockfloat.py:336 selects HIP without checking self.block; the new dequantization dispatch has the same omission. The existing API accepts TTBlockfloatEmbedding(3,32,bits=4,block=32) and its Torch path works with exponents shaped (3,1). The HIP binding requires one exponent per 16 values and rejects this storage. Guard both embedding and dequantization dispatch with block == 16. Constructor/storage/Torch behavior and routing were reproduced; the native rejection is explicit in check_weight.

Validation: built the unchanged native kernels with HIP 7.16.26385 for an AMD Radeon AI PRO R9700 (gfx1201). The supplied standalone harness passed 39 checks, and its dumps passed 9 Torch cross-checks. Additional native probes reproduced findings 3–4; the parent reran those probes. Python routing probes reproduced findings 1,2,5 with explicitly mocked availability/native validation.

Limits: the installed Torch is CUDA-only (2.15.0+cu132), so production ROCm Torch bindings/JIT and GIL=0 concurrency were not executed. Native HIP execution above is real hardware coverage, separate from the Python routing mocks. No source edits.

@Qubitium

Copy link
Copy Markdown
Collaborator Author

All five findings are fixed in 84c2cc0ef. Each fix is backed by a check that fails on the previous commit and passes now.

# finding fix regression evidence
1 [P1] HIP linear rejects non-2-D activations forward reshapes to (-1, K) and restores the caller's leading dims, in both the linear and tied-head paths test_hip_linear_flattens_leading_dimensions over (16,), (2,16), (1,2,16), (1,2,3,16) — 4/4 fail before, pass now
2 [P1] tied head reads self.bits, which does not exist dispatch moved onto the embedding's storage test_tied_head_uses_the_embedding_width_and_flattens asserts not hasattr(head, "bits") and that bits=4 reaches the kernel
3 [P1] partial K spans dropped in WMMA staging partial spans zero-fill past k and keep the columns below it harness K sweep 16/32/48/80/144/160/272 at one m per launcher tier: 14/14 fail before, pass now
4 [P2] base candidate never initialised on overflow base candidate taken unconditionally, matching the Torch reference harness 1e30 block: fails before, passes now
5 [P2] non-16 block routed to a binding that rejects it one hip_dispatch helper checks device, block and width for every call site test_embedding_with_a_wider_block_stays_on_the_torch_path (block=32)

Detail worth calling out

Finding 3 root cause. issue only loaded a span when the whole span fitted (gk + kCodes <= k) and store then wrote zeros for the span. The API only promises k % 16 == 0, so with k=16 and a 64-wide span the valid columns 0-15 were discarded along with the out-of-range ones. Reproduced at n=3: k=16 returned 0 and k=144 returned 128.

Finding 4 root cause. The harness's own reference quantiser had the identical strict comparison against INFINITY, which is why the existing checks never caught it — kernel and oracle were wrong in the same way. I fixed both. The Torch cross-check still reports quantize bit-exact, so the change is a no-op for finite errors (it only affects the case where error0 itself is infinite).

Finding 5 scope. TTBlockfloatLinear already rejected block != 16 in __init__, so the exposure was the embedding, dequantize and the tied head. The helper now covers all of them.

Incidental performance

Hoisting the per-element w_ok test out of the staging loop (needed for finding 3) helped the two shapes with the widest per-thread spans, where the store loop is the largest share of the work:

tokens before after
16 44.8 us 32.1 us (1.40x)
32 39.0 us 34.4 us (1.13x)
64 42.4 us 43.4 us
128 56.0 us 54.4 us
256 92.7 us 92.7 us
512 185.2 us 185.8 us

Min of 6 runs each, old and new binaries interleaved. m=64 is 2% slower in the fast clock state; this card's timings are bimodal (two clock states, ~13% apart) and both binaries show the same split, so I did not chase it.

Re-validated

  • Harness: 55 PASS / 0 FAIL (was 39; +14 partial-K, +2 overflow).
  • verify_against_torch.py: OK, quantize/dequant/embedding bit-exact, WMMA norm_l1 = 0.
  • tests/test_tenstorrent_support.py: 96 passed, 7 failed — the same 7 fail on main (XLA/transformers loading, unrelated).
  • gfx1100, gfx90a, and -std=c++20 -DENABLE_BF16 builds clean; ruff clean on every touched file.

Copy link
Copy Markdown
Collaborator Author

Reviewed current head 84c2cc0efd1705de561d4399f6a42fc2c07a6cba. The five findings in the earlier review have corresponding fixes. Two additional module-level compatibility issues remain:

  1. [P2] Preserve support for int32 embedding indices. embedding_dispatch:146–147 accepts only int64 IDs, but TTBlockfloatEmbedding.forward forwards the caller's indices unchanged whenever HIP is available. The existing F.embedding path accepts both int32 and int64. For example, TTBlockfloatEmbedding(3, 16, bits=4) with torch.tensor([0, 2], dtype=torch.int32) returns shape (2, 16) through the fallback, yet the new path reaches this check with int32 and raises. Normalize supported int32 IDs to int64 before the native call, support both widths in the binding, or retain the fallback for int32. Add a module-level regression test.

  2. [P2] Return empty outputs before rejecting null pointers/zero rows. ttbf_embedding:1408–1414 checks ids == nullptr || out == nullptr before its tokens == 0 success branch. Fresh empty Torch tensors have null data pointers, so an empty token batch fails despite that branch. The tied-head path similarly forwards hidden states of shape (1, 0, 16) as (0, 16) to ttbf_linear:1447, which rejects m <= 0. Both calls previously returned correctly shaped empty outputs ((0, 16) and (1, 0, 3)). Short-circuit empty results in the bindings/module forwards before calling the launchers, and cover both embedding and tied head.

Validation: 12 selected tests passed from tests/test_tenstorrent_support.py under Python 3.14.7 with GIL disabled and Torch 2.15.0.dev20260928+cu130. Separately exercised the real module fallbacks on CUDA tensors, then replaced HIP availability/native entry points with spies to confirm the exact dtype, shapes, and null pointers forwarded by the new branches. The failure conclusions above follow from the explicit native guards; these routing probes are not native ROCm execution. No HIP compiler/runtime was available here, so native HIP numerics, JIT integration, and ROCm concurrency were not revalidated. No source edits.

@Qubitium

Copy link
Copy Markdown
Collaborator Author

Both fixed in 63123699a.

1. int32 embedding indices. Fixed in the binding and the module forward. embedding_dispatch now accepts kInt as well as kLong and widens internally (ids.to(at::kLong)), so any caller of torch.ops.tt_blockfloat_hip.embedding gets the same acceptance as F.embedding. TTBlockfloatEmbedding.forward also widens int32 explicitly before the call, which keeps the conversion testable without a ROCm host. Non-integer dtypes still fail, with the received type in the message.

2. Empty batches. Two separate guards, both fixed:

  • ttbf_embedding checked ids/out for null before its tokens == 0 branch, and ttbf_linear rejected m <= 0 outright. Both now return hipSuccess for an empty batch before the pointer checks, so a fresh empty Torch tensor (null data pointers) is a success rather than hipErrorInvalidValue.
  • TTBlockfloatEmbedding.forward and TTBlockfloatTiedHead.forward now short-circuit an empty batch the way TTBlockfloatLinear.forward already did, so no launcher is reached at all.

Regression coverage, all failing on 84c2cc0ef and passing now:

check before after
harness bf4/bf8 empty batch succeeds (null ids/out, tokens=0; null x/out, m=0) 2 fail 2 pass
test_embedding_accepts_int32_indices fail pass
test_empty_batches_short_circuit_before_the_kernels (empty embedding + (1,0,16) tied head) fail pass

The empty-batch harness check calls ttbf_embedding/ttbf_linear directly with null pointers, so it exercises the native guard rather than the Python short-circuit.

Re-validated: harness 57 PASS / 0 FAIL, verify_against_torch.py OK, tests/test_tenstorrent_support.py 98 passed / 7 failed (the same 7 fail on main), gfx1100 / gfx90a / -std=c++20 -DENABLE_BF16 builds clean, ruff clean.

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).
@Qubitium
Qubitium force-pushed the feat/tt-blockfloat-hip-emulation branch from 6312369 to fa21a78 Compare November 13, 2026 06:18
@Qubitium

Copy link
Copy Markdown
Collaborator Author

Rebased onto 33df88865 (#3813) and pushed as fa21a787c — the branch had gone CONFLICTING after #3813 landed on the same files.

One conflict, in TTBlockfloatEmbedding.forward. #3813 changed the Torch path to dequantize(dtype=self.output_dtype) so a bf16 checkpoint no longer silently runs in fp32; my HIP dispatch was written against the older dequantize(). Resolved by keeping #3813's intent on both paths: the HIP branch now passes self.output_dtype to the kernel instead of the hard-coded torch.float32, and the fallback keeps dequantize(dtype=self.output_dtype).

That also corrected the empty-batch short-circuit from the previous commit, which returned torch.float32 unconditionally — it now returns self.output_dtype, so an empty batch matches the non-empty path for a bf16 table too.

Re-validated after the rebase: harness 57 PASS / 0 FAIL, verify_against_torch.py OK, tests/test_tenstorrent_support.py 103 passed / 7 failed — and the same 7 fail on 33df88865 itself (checked out in a separate worktree; 94 passed there). ruff and git diff --check clean.

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