Skip to content

feat(ext): add CPU kernels for Tenstorrent bf8_b/bf4_b/bf2_b block floats - #3808

Merged
Qubitium merged 11 commits into
mainfrom
feat/ttbfp-cpu-emulation
Nov 13, 2026
Merged

Qubitium merged 11 commits into
mainfrom
feat/ttbfp-cpu-emulation

Conversation

@Qubitium

@Qubitium Qubitium commented Nov 13, 2026 •

Copy link
Copy Markdown
Collaborator

Summary

Adds gptqmodel_ext/ttbfp/: a standalone, bit-exact CPU implementation of
Tenstorrent's bf8_b / bf4_b / bf2_b block-float formats. The kernels
execute the packed block-float representation directly; they are not an
emulator. Models and kernels that use these formats can therefore run on
non-Tenstorrent hardware.

The dtype names match the canonical bf8_b/bf4_b/bf2_b spelling from the
merged native TTNN backend (#3760) and hw/dtypes.md. TTBFP_TTBF8,
ttbfp.TTBF8, BFP8, and the "ttbf8" format strings remain accepted as
deprecated aliases, so existing callers keep working.

The change is purely additive. setup.py does not build the directory and the
gptqmodel package does not import it; no existing dispatch, inference, or
weight-storage path changes.

Review fixes

Addresses the five findings in the native-kernel review:

  • [P1] 9–15-row remainders. Both matmul dispatch switches now split a
    9–15-row tile into an 8-row tile plus the remaining 1–7 rows, so
    M = 16 + r writes every output row. Covered for every r = 1..15,
    both full and partial column blocks, and both FP32 and BF16 entry points.
  • [P1] bf2_b scalar decode. The scalar fallback now extracts four 2-bit
    fields per byte instead of reading nibbles from eight bytes. A scalar-path
    test decodes two bf2_b blocks whose second block is zero, which the old
    nibble path mis-read.
  • [P2] Subnormal intermediate scales. For e < 7 the scale table stores
    a normal high factor and the decode folds in 2^-6; table construction and
    the first multiply are independent of ambient FTZ/DAZ. A fresh-process test
    initializes the table under torch.set_flush_denormal(True) and checks
    2^126 * 2^-126 == 1 with FTZ on and off.
  • [P2] ftz=False under ambient FTZ/DAZ. Fixing the subnormal-scale
    path protected normal weights, but a genuinely subnormal decoded weight was
    still flushed by the final multiply, and DAZ zeroed it as an FMA input.
    ftz=False now clears MXCSR FTZ/DAZ per worker for the call and restores
    it on return; ftz=True is unchanged. Covered for bf8_b/bf4_b on
    AVX-512, AVX2, scalar and the int8 layout.
  • [P2] bf4_b/bf2_b stay packed. The int8 kernel-native layout is now
    bf8_b-only, where it does not expand the payload. bf4_b/bf2_b remain in the
    packed sign-magnitude block-major layout, and the s8 wrappers reject them.
  • [P2] Zero-length reductions. Every matmul wrapper returns a zero matrix
    for K == 0 instead of returning an uninitialized np.empty buffer; the C
    header now declares the K > 0 precondition for direct callers.
  • [P2] Packed-buffer validation. unpack, matmul, the BF16 and
    block-major variants, convert_s8 and tile_unpack now validate the
    complete format-specific shape/length before ctypes and raise
    ValueError.
  • [P2] Flat row stride. Row-major wrappers reject cols that would
    change the stored block count (cropping a whole block); trimming the final
    partial block remains supported. The review's 3×32 example now rejects
    cols=16 and returns [1,2,3] for cols=17.

What Changed

  • gptqmodel_ext/ttbfp/ — the library:
    • quantizer/dequantizer bit-exact with the upstream tt-llk helpers for
      bf8_b, bf4_b and bf2_b (P300C BLOCKFP8/4/2)
    • fused dequantize+GEMM (C = A @ dequant(B)) for scalar, AVX2+FMA and
      AVX-512, in row-major, block-major and int8 kernel-native layouts (int8 is
      bf8_b-only; bf4_b/bf2_b stay in the packed block-major layout)
    • exact 32x32 L1 tile pack/unpack
    • ctypes and PyTorch CPU bindings, NumPy reference
    • 280 tests asserting bitwise parity across every path and thread count,
      plus the review regressions above
    • bench/ab_compare.py same-process A/B and tools/verify_against_tt.py
      upstream validation
  • .agents/skills/ttbfp-perf/SKILL.md — measurement rules, tile-selection
    rationale, and measured dead ends for future work.
  • docs/tt-blockfloat-cpu.md — dtype naming (TT is not OCP MX), dispatch
    flow, layouts, and the performance model.
  • hw/dtypes.md — §8 covers bf2_b alongside bf4_b/bf8_b (layout,
    encode/decode, 0.3125 B/weight) and records that the CPU kernels implement
    bf2_b even though the TTNN and HIP backends do not.
  • docs/tenstorrent.md — short CPU-kernels section linking the page above.
  • README.md — one subsection under "Platform and HW Support".

No API or behavior changes to existing code.

Performance

Single thread, K = N = 4096, process CPU time, bitwise identical across
paths:

format layout M=1 M=4 M=16 M=64
bf8_b int8 kernel-native 0.80 ms 1.60 ms 6.48 ms 25.64 ms
bf4_b packed block-major 1.81 ms 2.59 ms 7.35 ms 29.31 ms
bf2_b packed block-major 2.33 ms 3.70 ms 8.08 ms 30.89 ms

That is 5.8x / 2.3x / 2.4x / 2.4x over the first row-major implementation for
bf8_b. int8 is bf8_b-only because a bf8_b block already occupies 16
bytes, so the expansion is free; bf4_b/bf2_b keep their packed payload
(8/4 bytes per block) and decode from it, which is why their M=1 times are
higher. The int8 kernel runs at ~70% of the measured pure-FMA floor (18.2 ms
for the M=64 problem); the extension README accounts for the remainder and
lists the alternatives that were measured and rejected. Going below the floor
would require integer dot products, which change the fp32 accumulation order
and break bitwise parity with tt-llk, so it is deliberately not done.

Tests

make -C gptqmodel_ext/ttbfp test PYTHON=python
# 280 passed

cd gptqmodel_ext/ttbfp
TTBFP_LIB=$PWD/libttbfp.so PYTHONPATH=$PWD/python python tools/verify_against_tt.py
# checked 200 seeds x 4 distributions x 3 formats: OK

The parity suite covers scalar / AVX2 / AVX-512, both decoders, every tile
shape and row remainder, several thread counts, partial N blocks, and tile
pack/unpack.

Model Support / Module Plan

Not applicable: no MODEL_MAP, model definition, or module-plan change.

Logic Flow Documentation

  • This change does not alter a major logic flow, or the required diagrams
    and docs page are included below.
  • New-flow Mermaid diagram(s) describe the shipped code using real symbol names.

The new dispatch flow is documented in docs/tt-blockfloat-cpu.md
(matmul_driver -> prepacked_tile -> mm_panel_*). It is a new standalone
entry point, not a change to an existing flow.

  • The removed/replaced mechanism is shown or tabulated with file:line evidence.
    Not applicable: nothing is removed or replaced.

@Qubitium
Qubitium force-pushed the feat/ttbfp-cpu-emulation branch from c8faf63 to 497a55a Compare November 13, 2026 03:55
@Qubitium Qubitium changed the title feat(ext): add ttbfp CPU emulation for Tenstorrent block floats feat(ext): add CPU kernels for Tenstorrent ttbf8/ttbf4/ttbf2 block floats Nov 13, 2026
@Qubitium
Qubitium force-pushed the feat/ttbfp-cpu-emulation branch from 497a55a to 6cb4058 Compare November 13, 2026 04:49
@Qubitium Qubitium changed the title feat(ext): add CPU kernels for Tenstorrent ttbf8/ttbf4/ttbf2 block floats feat(ext): add CPU kernels for Tenstorrent bf8_b/bf4_b/bf2_b block floats Nov 13, 2026
@Qubitium
Qubitium force-pushed the feat/ttbfp-cpu-emulation branch from 6cb4058 to 7e8a314 Compare November 13, 2026 04:50

Copy link
Copy Markdown
Collaborator Author

Review of head 7e8a314af2a9190f15b81d70ea7f1e2545f6224c against 276605140c04d8b58b145f7245c7e3b11dd5cfee, including a fresh independent native-kernel review. Five confirmed findings:

  1. [P1] Handle 9–15 remaining rows in both matmul dispatch switches. src/ttbfp_cpu.cpp:895. On AVX-512, the default sign-magnitude prepacked path selects a 16-row tile, but the switch handles only 16 and 1–8. With M=25,K=1,N=16 and all-one inputs, the final nine rows are never written: 144 outputs retain a prefilled sentinel. I reproduced this for bf8_b/bf4_b/bf2_b and FP32/BF16 activation entry points. The partial-column switch at line 922 has the same omission and copies uninitialized scratch. Add cases 9–15 or split the remainder into supported groups; test every remainder with full and partial column blocks.

  2. [P1] Decode bf2_b as two-bit fields in the scalar matmul fallback. src/ttbfp_cpu.cpp:540–544. The non-bf8 branch always extracts nibbles, so bf2_b reads eight bytes from a valid four-byte block and decodes the wrong fields. Reproduction: scalar path, M=K=1,N=16, exponent 127, data [0x55]*4, and activation 1; every output should be 1. Placing the correctly sized data buffer immediately before a guard page causes SIGSEGV (exit −11). This affects CPUs using the scalar fallback, not merely malformed inputs. Add an explicit bf2 branch using (d[i >> 2] >> (2 * (i & 3))) & 3, with scalar parity and buffer-boundary tests.

  3. [P2] Avoid subnormal intermediate scales for normal decoded values. src/ttbfp_cpu.cpp:69–73. bf8/bf4 decoding relies on subnormal scale factors even when the resulting weight is normal. With torch.set_flush_denormal(True), normal FP32 inputs A=2^126 and bf8_b B=2^-126 produce 0 instead of exactly 1. If the static scale table is first initialized with flushing enabled, the failure persists after flushing is disabled. Reproduced in fresh one-thread processes. Reconstruct decoded values without subnormal intermediates, and make table initialization independent of the ambient floating-point mode.

  4. [P2] Validate packed-buffer sizes before passing pointers into native code. python/ttbfp/init.py:188–202. unpack checks exponent rank and column capacity but never checks the data shape/length. A one-byte array is accepted for a bf8_b block requiring 16 bytes; the native decoder reads outside the array, and a guard-page probe terminates with SIGSEGV. Similar gaps exist in matmul/prepacked/s8 wrappers and tile_unpack; BF16 variants also omit several shape/column checks. Validate the complete format-specific layout and tile payload length before entering ctypes, and reject inconsistent buffers with ValueError.

  5. [P2] Preserve the stored row stride when accepting a smaller cols. python/ttbfp/init.py:195–202, also matmul at lines 221–227. The wrappers accept any column count below the packed capacity, but the native row-major code recomputes the input stride from that requested count. Pack a 3×32 bf8_b matrix whose two constant blocks per row are [1,11], [2,12], [3,13]; unpack(...,cols=16) and identity-activation matmul(...,cols=16) return first-column values [1,11,2] instead of [1,2,3]. Either reject counts that change the stored block count, or pass the original packed stride separately when supporting column cropping.

Design suggestion: a shared packed-weight descriptor carrying format, logical shape, layout and validated buffer sizes would prevent the independent shape/stride calculations that caused findings 4–5.

Validation: make test passed 252 tests; the bundled upstream-helper comparison passed 200 seeds × 4 distributions × 3 formats. Additional RTX 4090 checks passed nine cases each for CUDA quantization, dequantization and GEMM, plus six exponent sweeps (0–254, three formats, FTZ on/off); these were focused checks, not exhaustive CUDA coverage. The native failures above were independently reproduced after the passing suite. Free-threaded Python remains unverified. No repository source edits.

@Qubitium

Copy link
Copy Markdown
Collaborator Author

Addressed all five findings in b9c7c3fa (plus d298fa21 documenting the stride rule):

  1. 9–15-row remainders — mm_run_rows() splits them into an 8-row tile plus the remaining 1–7 rows; both the full- and partial-column switches now use it. Tests cover every r = 1..15, N = 16/17/33, all three formats, FP32 and BF16 entry points, with sentinel-filled outputs so an unwritten tile cannot pass.
  2. bf2_b scalar decode — explicit (d[i >> 2] >> (2 * (i & 3))) & 3 branch. The scalar-path regression test uses two blocks; the old nibble path read block 1 for lanes 8–15.
  3. Subnormal scales — for e < 7 the table stores a normal high factor and the decode folds in 2^-6; construction and the first multiply are FTZ/DAZ-independent. A fresh-process test initializes under torch.set_flush_denormal(True) and checks 2^126 * 2^-126 == 1 with FTZ on and off. The CUDA decode got the same split.
  4. Buffer validation — _flat_packed / _block_major validate the complete format-specific shapes; unpack, matmul, the BF16 variants, prepacked/s8 and tile_unpack raise ValueError before entering ctypes.
  5. Flat row stride — row-major wrappers reject cols that changes the stored block count; the 3×32 example now rejects cols=16 and returns [1,2,3] for cols=17. Block-major layouts are unaffected because they are indexed by block.

Verification: make test → 277 passed; tools/verify_against_tt.py → 200 seeds × 4 distributions × 3 formats OK; CUDA device-only compile check clean.

@Qubitium

Copy link
Copy Markdown
Collaborator Author

The remaining FTZ/DAZ case is fixed in c30f608c.

ftz=False now clears MXCSR FTZ/DAZ for the duration of the call (per OpenMP worker) and restores it on return; ftz=True keeps the explicit flush and leaves the ambient mode alone. This covers both the final scaling multiply and DAZ treating the subnormal weight as a zero FMA input.

Reproduction now: bf8_b e=1/mag=32, A=2^126 → 0.5 with ftz=False, 0 with ftz=True; same for bf4_b e=1/mag=2. Verified on AVX-512, AVX2, scalar and the int8 layout, plus a rows>1 dequantize case. make test → 283 passed; upstream-helper comparison still OK.

Copy link
Copy Markdown
Collaborator Author

Reviewed current head 52449c6d04ec31cf1e8aac2c1c99a7cf9b37a8cd, including the fixes discussed above. Two remaining findings:

  1. [P2] Keep bf4_b/bf2_b weights packed in the reusable inference layout. convert_s8, lines 353–358 expands every datum to one byte and returns the full-layer buffer for reuse by matmul_prepacked_s8. This is explicitly the recommended reusable fast path, rather than call-local scratch. For a 256×256 matrix, I measured 36,864 → 69,632 bytes for bf4_b and 20,480 → 69,632 bytes for bf2_b, including exponent metadata; the code payload itself expands 2×/4× and remains live and unchanged after repeated forwards. This violates the repository's storage requirement, which applies to every inference backend and explicitly includes integer expansion and opt-in paths. Numerical parity does not resolve this storage-contract issue. Keep persistent bf4/bf2 data packed and expand only bounded tiles during the consuming call; alternatively restrict the reusable s8 representation to bf8_b, where it does not expand the payload. Benchmark the eligible paths accordingly.

  2. [P2] Handle or reject zero-length reductions before returning an uninitialized result. matmul, lines 261–269 accepts A.shape == (2, 0) and a packed B.shape == (0, 16), allocates np.empty((2,16)), then calls a native function that immediately returns for K <= 0. The wrapper returns arbitrary old allocation contents instead of zeros or an error. Reproduction: e,d = ttbfp.pack(np.empty((0,16), np.float32), 4); then ttbfp.matmul(np.empty((2,0), np.float32), e,d,4,cols=16). With the output allocator prefilled to 12345, all 32 sentinel values survive. Confirmed for all six FP32/BF16 row-major/block-major/s8 entry points and all three formats (18 cases). Neither the Python contract nor the public header declares a positive-K precondition. Return a zero result for an empty reduction, or explicitly reject it before allocating/calling native code.

Validation: 283 tests passed with the GIL disabled on this AVX2+FMA host; the bundled Torch-helper comparison passed 200 seeds × 4 distributions × 3 formats. A focused shared-read-only-weight PyTorch wrapper probe also passed in three fresh GIL-disabled processes, each using 8 workers for 24 tasks × 8 forwards. This review did not execute AVX-512, non-x86, or the optional CUDA extension, and does not establish blanket thread safety. No repository source edits.

@Qubitium

Copy link
Copy Markdown
Collaborator Author

Both remaining findings are addressed in 8ed96745.

  1. Persistent storage for bf4_b/bf2_b. The int8 kernel-native layout is now bf8_b-only, where it does not expand the payload (16 bytes per block either way). convert_s8, prepack_s8, matmul_prepacked_s8 and _bf16 raise ValueError for bf4_b/bf2_b, and the C entry points return without writing. bf4_b/bf2_b remain in the packed sign-magnitude block-major layout (transpose_packed + matmul_prepacked), whose payload stays at 8/4 bytes per block. The bench scripts and docs now report s8 only for bf8_b and block-major for the other two formats.

  2. Zero-length reductions. All six matmul wrappers now return np.zeros((M, N)) when K == 0; the C header declares the K > 0 precondition for direct callers. Regression tests cover all three formats and both FP32/BF16 row-major/prepacked paths, plus the s8 path.

I also resolved the CodeQL import-style comments (import ttbfp.torch_ops as torch_ops, import ttbfp.reference as ref) and replaced the unused collect_ignore_glob with a pytest_ignore_collect hook.

Verification: make test → 280 passed; tools/verify_against_tt.py → 200 seeds × 4 distributions × 3 formats OK.

@Qubitium

Copy link
Copy Markdown
Collaborator Author

Final consistency pass on top of the review fixes (d56ea7bf):

  • README speedup corrected. The bf4_b M=64 row claimed 2.1x; 54.73/29.31
    is 1.9x. All other rows re-checked and unchanged.
  • PR performance table aligned with the s8 restriction. It previously
    listed bf4_b int8 and bf2_b int8 timings, which the shipped code no
    longer offers. It now shows bf8_b int8 plus the packed block-major path
    for bf4_b/bf2_b, with a note on why int8 is bf8_b-only.
  • The "What Changed" bullet now qualifies the int8 layout as bf8_b-only.

Verification at d56ea7bf (docs-only change since 8ed96745):

  • make test -> 280 passed
  • tools/verify_against_tt.py -> 200 seeds x 4 distributions x 3 formats: OK
  • CI: ruff-check, CodeQL, and all three Analyze jobs pass; PR is
    MERGEABLE / CLEAN.

The library executes the Tenstorrent block-float formats directly on CPU; it is not an emulator. Rename the reference page to ttbfp-cpu-kernels.md and update the README, extension README, NOTICE, Makefile and source headers.
Adopt the canonical Tenstorrent block-float names introduced with the
native TTNN backend (#3760), defined in hw/dtypes.md:

  - bf8_b  (Bfp8_b / BLOCKFP8)
  - bf4_b  (Bfp4_b / BLOCKFP4)
  - bf2_b  (Bfp2_b / BLOCKFP2)

The C enum, Python constants, format strings and examples now use these
names. TTBFP_TTBF8/BF4/BF2, ttbfp.TTBF8/BF4/BF2, BFP8/BFP4/BFP2 and the
"ttbf8"/"ttbf4"/"ttbf2" format strings remain accepted as deprecated
aliases, so existing callers keep working.

Also document bf2_b alongside bf4_b/bf8_b in hw/dtypes.md (layout,
encode/decode, 0.3125 B/weight storage), note that the CPU kernels
implement it even though this host's ttnn build does not expose it, and
link the CPU-kernel page from docs/tenstorrent.md. Rename the page to
docs/tt-blockfloat-cpu.md and fix the README link.

Verified: 252 tests pass; tools/verify_against_tt.py matches upstream
tt-llk over 200 seeds x 4 distributions x 3 formats.
- dispatch: split 9..15-row remainders into an 8-row tile plus the
  remaining 1..7 rows in both the full- and partial-column paths, so
  M = 16 + r (r = 1..15) writes every output row.
- scalar decode: bf2_b uses four 2-bit fields per byte; the nibble path
  read eight bytes from a four-byte block.
- scale: store a normal high factor for e < 7 and fold 2^-6 into the
  decode, so FTZ/DAZ no longer flushes normal weights through a
  subnormal scale. The table is FTZ-safe at construction.
- python: validate complete format-specific buffer shapes and tile
  payload sizes before ctypes; reject flat cols that would change the
  stored row stride (cropping a whole block).
- tests: cover every row remainder in both column switches, scalar bf2
  decode, ambient FTZ with the table initialized under FTZ, malformed
  buffers, and the flat-stride crop case.

277 tests pass; tools/verify_against_tt.py still matches upstream.
The library's ftz flag could not preserve genuinely subnormal weights when
the calling thread had MXCSR FTZ/DAZ enabled: the final scaling multiply
flushed them, and DAZ treated them as zero FMA inputs.  Clear FTZ/DAZ for
the duration of a call with ftz=False, per OpenMP worker, and restore the
caller's MXCSR on return.  ftz=True is unchanged.

Regression: bf8_b e=1/mag=32 and bf4_b e=1/mag=2 decode to 2^-127; with
A=2^126 the result is 0.5 for ftz=False and 0 for ftz=True, on AVX-512,
AVX2, scalar and the int8 layout.  283 tests pass.
- Restrict the int8 kernel-native layout (convert_s8/prepack_s8/
  matmul_prepacked_s8) to bf8_b.  bf4_b/bf2_b would expand the persistent
  payload 2x/4x; those formats stay in the packed sign-magnitude
  block-major layout, as required by the quantized-storage rule.
- Return zeros from every matmul wrapper when K == 0 instead of returning
  an uninitialized np.empty buffer; document the C-side K > 0 precondition.
- Update the bench scripts and docs to report s8 only for bf8_b and
  block-major for bf4_b/bf2_b.
- Resolve the CodeQL import-style warnings and replace the unused
  collect_ignore_glob with a pytest_ignore_collect hook.

280 tests pass; upstream-helper comparison still OK.
@Qubitium
Qubitium force-pushed the feat/ttbfp-cpu-emulation branch from d56ea7b to 81138fc Compare November 13, 2026 06:38
@Qubitium
Qubitium merged commit 0479006 into main Nov 13, 2026
6 checks passed
@Qubitium
Qubitium deleted the feat/ttbfp-cpu-emulation branch November 13, 2026 06:52
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