Repository navigation
feat(tenstorrent): native TTNN, packed XLA and block-float inference - #3760
Conversation
Record the validated TT-Metal/PJRT-XLA integration state for 4x Blackhole p300c, including the working inference path and six reproduced blockers. Validated on hardware (2026-11-10): - TorchLinear (SUPPORTS_DEVICES=[DEVICE.ALL]) selects on xla - exact nibble unpack yields bit-identical dequant vs CPU oracle - device matmul pcc=1.000000 in bfloat16 Key blockers documented: - B1 int32 >> is lowered via f32, corrupting GPTQ nibble unpack - B5 fp16 is silently rounded to bf16 on transfer; TT has no fp16 - B6 torch.stack over 8 slices fails to lower - B2/B3 unsupported ATen overloads (out_dtype=, mixed-dtype addmm) - B4 host readback needs explicit torch_xla.sync Also proposes a DEVICE.XLA family, an xla branch in _right_shift_unpack, and a native TT-NN kernel milestone.
Add BACKEND.GPTQ_TTNN / TTNNLinear as a second Tenstorrent backend that bypasses StableHLO and PJRT entirely and owns a ttnn.MeshDevice directly. The kernel uploads packed uint32 words only, extracts the eight nibbles with native logical_right_shift/bitwise_and (bit-exact on Blackhole, unlike TT's signed 32-bit path), expands g_idx through ttnn.embedding on the scale and zero tables, dequantizes to a transient BF16 tile, and runs ttnn.linear pinned to MathFidelity.HiFi4 with fp32_dest_acc_en. Tensor parallelism shards out_features across a 1xN mesh: each chip owns a contiguous output slice with its matching zero-point and scale columns, so every chip computes an already-correct GEMM and all_gather (FABRIC_1D) reassembles the output features. Measured on 4x Blackhole p300c with real OPT-125M layer-0 q_proj data: - device dequantized weights bit-identical to the CPU oracle, 1 and 4 chips - PCC 0.99999875 vs an FP32 oracle, normalized error 0.00056 - 4-chip output bit-identical to 1-chip - packed words 294912 B vs 1179648 B dense BF16 - forward 1.24 ms/layer on one chip after moving the nibble stack to dim 0 (was 4.51 ms; stacking on the trailing tile dim cost 3.35 ms) Fix a double GPTQ-v1 zero-point correction: _repack_zero_words already normalizes (stored + 1) & 0xF in packed space, so applying it again on device halved the reconstructed weight. ttnn_runtime owns the single-owner mesh lifecycle and translates TT-Metal ownership failures into TTNNUnavailable, since only one runtime may own a chip and initializing PJRT is irreversible. TTNNLinear stays out of AUTO until model-level token parity is measured.
`FusionKernelSpec.combine()` builds the fused shell with `copy.copy(first)`, so
it inherits the sources' `_fused_train_state` snapshot. That snapshot holds the
pre-transform GPTQ-v2 `qweight` `(in_features / 8, out_features)` and `qzeros`
`(groups, out_features)` that `transform_cpu()` replaced with int4pack storage.
`clear_weight_cache()` calls `restore_fused_train_state()`, which consumes the
snapshot and writes those stale shapes back over the correctly concatenated
int4pack tensors. `_share_operands()` then saw a `(64, 1024)` fused weight where
the sources expected `(1024, 256)` slices and raised
split_with_sizes expects split_sizes to sum exactly to 64
(input tensor's size at dimension 0), but got split_sizes=[1024, 1024]
The `discard_fused_train_state()` guard and the `suppress_restore` flag both
covered `cpu_aten` and `cpu_legacy` but omitted `cpu_avx512`, even though that
layout captures its snapshot from the same `TorchAtenLinear` base. Add it to
both. The fused layer now owns the combined int4pack allocations outright and
each source keeps a view into them, so the storage-aliasing contract holds.
Reproduced on clean base be3852b as three gate_up/qkv CPU failures. Full
focused suite goes from 3 failed to 55 passed, with the rest of the matrix
(rdisp, exllamav2, marlin, AWQ, int8, allspark) unchanged.
…ackend
`GPTQModel.load(..., backend=BACKEND.GPTQ_TTNN)` could never succeed. Device
resolution called `expand_selector_device_family(DEVICE.XLA)`, which asks PJRT
for `addressable_device_count()`. That initializes the Tenstorrent PJRT plugin,
which claims every chip; `TTNNLinear.post_init()` then fails to open its own mesh
with
TT_FATAL ... metal_context.cpp:74: context_id.get() >= 0
`auto_select_device(None, backend)` had the same problem through
`is_xla_available()`, so an unspecified device also poisoned the process.
The native backend reads no `xla:N` ordinal: it opens a `ttnn.MeshDevice` itself
and sizes it from `ttnn_device_count`. Keep the abstract `DEVICE.XLA` family
unexpanded for `GPTQ_TTNN` in both places, and leave every other backend on the
existing PJRT path.
Verified on tt-quietbox that device resolution now performs zero PJRT probes
(instrumented `addressable_device_count`/`device_count`; 0 calls) and that
`/dev/tenstorrent` stays closed until TT-Metal opens the mesh. Model load then
progresses into TT-Metal bring-up instead of failing on chip ownership.
Both new tests fail on the unpatched tree and pass with the change.
A p300c throttles GDDR at 90 C and shuts down at 110 C, and the parts shed heat at only ~2 C/min. A load/unload loop therefore ratchets temperature upward across cycles: on this host that ended in a hard thermal shutdown, after which a warm reboot recovered 3 of 4 cards and only a cold start recovered all four. Measured on tt-quietbox before choosing any default: idle baseline 58-64 C GDDR rise from one model load +20 to +34 C GDDR cooling rate at idle ~2 C/min Those numbers rule out a fixed sleep as the mechanism. Five seconds of idle removes about 0.2 C, so the cooldown is kept only as a teardown settle delay, and heat is handled by a temperature gate instead. The soft limit defaults to 80 C rather than just under the throttle point, because a load starting at 80 C can reach the shutdown limit on its own. tt_thermal reads peak GDDR over PCI telemetry (pyluwen, noc_safe) in ~2 ms without opening a TT-Metal device, so it is safe precisely at the points the runtime calls it -- while no mesh is open. An unreadable temperature, a missing driver, or a missing pyluwen disables the guard instead of failing the load, and every wait is bounded by a budget so a card with a broken fan logs loudly rather than hanging a job. Wiring: ttnn_runtime.open_mesh/close_mesh native TTNN path loader.from_quantized Torch/XLA path, which opens no TTNN mesh BaseQModel.release_device explicit close for load/unload loops The cooldown is a rate limit, not a per-hook sleep, so a load passing both gates pays one idle window rather than two. Defaults: cooldown 5 s, soft limit 80 C, wait budget 900 s (cooling 98 C to 80 C legitimately takes ~9 min at the measured rate).
Addresses the open CodeQL findings on the TTNN/XLALinear files: unused setup_logger globals, an empty except during fabric reset on a failed open, and a pass-through lambda in the XLA runtime stub.
… cap Two defects on this path, both measured on a 4x p300c host. The PJRT ownership guard never fired. ``_reject_pjrt_owner`` tested ``torch_xla._gptqmodel_device_claimed``, an attribute nothing in the tree ever set, so it was dead code and a genuine PJRT claim fell through to a bare TT-Metal assert. ``addressable_device_count()`` is the call that initializes PJRT and opens every chip, so record the claim there and route all six callers through one ``xla_device_count`` helper. Importing ``torch_xla`` remains inert, which is why a ``sys.modules`` check alone could never distinguish the cases. Closing a device did not make the card idle. Measured after ``close_device``: AICLK stayed at 1350 MHz and ~50 W per board for more than 50 s, and GDDR kept rising the whole time, because the firmware only falls back to its 800 MHz long-idle clock when it is told to. That means the existing cooldown slept while the cards were still running, so the claimed idle window was not idle. Send ``AICLK_GO_LONG_IDLE`` on close before pacing the next open. Board power is the real throughput ceiling, not temperature: p300c throttles by inserting NOP cycles at its per-board TDP limit (125 W here), under which sustained load still drove GDDR to 102 C and collapsed AICLK to 800 MHz. The newer ``TT_METAL_TDP_LIMIT_WATTS`` variable is absent from the installed 1.5.0 plugin build (0 matches in its libraries), so expose the firmware message directly: ``set_tdp_limit`` sends ``SET_TDP_LIMIT`` (0x22, in firmware since 19.8.0; this host runs 19.17.1) and ``tdp_limit_watts`` reads the effective limit back. Verified live: 125 -> 110 -> 100 -> 90 W.
The earlier text said closing the mesh starts the thermal idle window. That is measurably false: AICLK stayed at 1350 MHz and ~50 W per board for over 50 s after close_device. Document park_idle_clock as the step that actually returns the cards to 800 MHz / ~40 W, and add the measured TDP sweep showing a board power cap is not a GDDR mitigation (70 W peaked higher than 125 W).
A real load with `backend=GPTQ_TTNN, device=DEVICE.XLA` died inside `post_init` with a TT-Metal ownership fatal that read a garbage context id (`context_id 82459424 is out of range (max 32)`), because the model's layer-wise placement had already handed the chips to PJRT. `_resolve_default_layerwise_device` correctly leaves the XLA family unexpanded for the native backend, but the placement step then treated that family as a PJRT family: `xla_device_count()` imports torch_xla and calls `addressable_device_count()`, which initializes the plugin and claims all four chips in a FABRIC_1D mesh. The checkpoint was dispatched onto `xla:0..3` through a second PJRT mesh, and the native `ttnn.open_device` in `post_init` then collided with it. Two TT-Metal runtimes shared one UMD cluster, the loser read a released `Device`, and `extract_context_id()` returned pointer-shaped garbage. It is a stale-device ownership collision, not a 32-slot overflow. Bisected to a single call boundary: import, config, model construction and `make_quant` all leave `open_device` working; the layer-wise map is the first step that breaks it (torch_xla appears and the mesh is claimed at that exact point). The native TTNN kernel uploads a layer's packed weights on demand in forward, so its parameters belong on the host. Keep the whole model on CPU for that backend instead of building an `xla:N` map, and stop both `_layerwise_device_count` and `_layerwise_device_strings` from initializing PJRT when the native backend is selected -- counting over PCIe describes the same chips without claiming one. Verified on the host: OPT-125M GPTQ now loads in 7.7 s with `torch_xla` never imported, 72 TTNNLinear modules placed.
…s PCIe once The native TTNN forward took a CPU tensor and returned one, because every op between two quantized layers (attention matmuls, softmax, norms, residuals) is ordinary PyTorch on the host. That cost two PCIe crossings per layer -- about 144 per token for OPT-125M -- and it, not Tensix throughput, was what a 0.3 s forward was actually paying for. `gptqmodel/utils/tt_resident.py` adds the missing piece: an activation that lives on the device across several layers. `TTDeviceTensor` is an opaque handle to a ttnn tensor plus the mesh that owns it, `run_resident` executes a chain of resident-aware layers, and `apply_activation`/`add_residual` keep device-side glue resident instead of silently falling back to the host. `TTNNLinear.forward` accepts the handle and returns one, so a chain uploads once and reads back once. Measured on tt-quietbox, four consecutive 768x768 GPTQ layers at batch 8: per-layer forward 45.4 ms 4 uploads 4 readbacks resident chain 5.3 ms 1 upload 1 readback 8.6x, byte-identical output (allclose, normalised L1 0.0). The forward path is also refactored so the host and resident variants share `_compute_on_device`, and the transient dequantized weight tile is released per layer in one place. Scope is stated in the module and the docs rather than implied: this removes the crossings inside a chain, not the ones around host-side ops. `resident_boundaries` reports how many crossings a layer sequence still costs, so the remaining gap is measurable. A true single-upload decoder still needs attention, softmax and the norms on device, which is a model runner rather than a linear replacement. Also documents the three gotchas that produced real failures here: DEVICE.XLA names a family rather than a runtime (decide with `backend`), placement is not residency (native parameters belong on the host), and context ownership is one runtime per chip with no PJRT teardown, so the first query claims the cards.
…peedup claim Writing the architecture page first changed the design conclusion, so it is committed before any further kernel work. hw/tenstorrent.md now records how a p300c actually executes: the five RISC-V cores per Tensix tile (BRISC/NCRISC move data, TRISC0/1/2 unpack/math/pack), L1 as explicitly managed SRAM rather than a cache, the 32x32 tile decomposed into four 16x16 faces because the matrix engine is 16x16-native, its 8x16x16 per cycle and how small M wastes it (1x16 runs at 1/8), the fidelity cost ladder, 8x ~4 GB DRAM banks with lockstep allocation and DRAM_ALIGNMENT, and the NoC upgrade (1.35 GHz, 512-bit flits, 64 B read alignment, strided/L-shaped multicast). Facts are split into documented (vendor tech_reports, METALIUM_GUIDE, tt-isa-documentation) versus measured on this host. Measured here: the p300c exposes an 11x10 = 110 core grid, so kernel sizing must read the grid at runtime rather than assume 130 or 140. The correction: with both paths warmed, the resident activation chain is 1.13x (5.93 ms -> 5.26 ms), not the 8.6x previously claimed. The old figure timed a first call per module, which also uploads that layer's packed weights, so it charged one-time load cost to the host path. Both the docs and the module docstring now say so explicitly. The phase breakdown explains why residency is not the main lever: dequant (nibble planes -> BF16) 1.27 ms 85% ttnn.linear 0.06 ms 4% upload + readback 0.16 ms 11% The dequant is ~20x the GEMM it feeds, and a PCIe crossing is only ~0.12 ms at decode sizes. So the optimisation target is re-expanding packed weights on every forward, not transfer volume -- which is why building a device-side decoder for attention and norms is not the next win, and is not started here.
A GPTQ kernel can easily spend its time in a dtype the matrix engine cannot touch, so the support matrix is now measured rather than assumed. Probed on the card with ttnn.linear on a 256x256 tile tensor plus elementwise multiply: bfloat16 matmul yes (0.085 ms) elementwise yes bfloat8_b matmul yes (0.111 ms) elementwise yes bfloat4_b matmul yes (0.095 ms) elementwise yes float32 matmul yes (0.086 ms) elementwise yes int32 matmul NO elementwise yes uint32 matmul NO elementwise yes uint16 matmul NO elementwise yes uint8 matmul NO elementwise NO The FPU multiplies Float16/Float16_b, or float32 when fp32_dest_acc_en is set (which halves destination-tile capacity). bfloat8_b/bfloat4_b are storage formats unpacked to BF16 by TRISC0, not native multiply formats -- ttnn.linear accepting them means the conversion happens for you, not that the multiply is free. Integer dtypes have no matrix engine path at all; they allocate as tiles and do elementwise work on the SFPU. That is the mechanism behind the measured dequant cost. The packed GPTQ words are uint32, and nibble extraction (logical_right_shift + bitwise_and, both confirmed working) is inherently SFPU work: many integer ops on the unit that is not the fast path, feeding a BF16 GEMM that they dwarf. Expanding once per load rather than once per forward removes ~85% of a layer. Rule recorded for TT kernels here: keep hot compute in bfloat16, use block floats only to cut memory traffic, and use integer tiles only for bit manipulation. Also renumbers the hardware sections, since the dtype matrix is inserted as section 3, and fixes the two cross-references that pointed at the old numbers.
Caching expanded BF16 weights is an 8x memory regression (4-bit to 16-bit) and defeats the point of a quantized checkpoint -- ~14 GB for a 7B model. Removing that recommendation and replacing it with a design derived from the hardware. Measured on real OPT-125M q_proj weights (768x768, batch 8) to see whether a block-float storage format could replace per-forward dequant, since the unpack stage expands storage formats in the data path: bfloat16 (dequant then GEMM) 0.101 ms reference bfloat8_b (hardware unpack) 0.071 ms 1.0% norm L1, cosine 0.99995 bfloat4_b (hardware unpack) 0.072 ms 9.8% norm L1, cosine 0.99519 Both beat BF16 on time, which confirms the unpack stage is doing the expansion. Neither is suitable: bfloat4_b is too coarse (a re-quantization on top of an already 4-bit weight, and GPTQ's uniform levels plus zero point do not map onto one shared exponent per 16 logarithmic values), and bfloat8_b is accurate but costs 2x the memory of int4. The design recorded instead keeps the checkpoint packed at 0.5 B/element and expands per tile inside the kernel: BRISC reads the packed word tile and group metadata into L1, TRISC0 extracts nibbles and dequantizes straight into SrcA, TRISC1 issues the 16x16 FPU multiplies, TRISC2 packs, NCRISC writes out. That matches the engine's face granularity so the intermediate never becomes a 768x768 allocation, keeps group_size=128 (4 K-tiles) resident, and reduces g_idx to a scalar lookup per K tile instead of an expanded index tensor. Noted that L1 (1464 KiB) cannot hold a 768x768 BF16 layer (1.18 MB), so weights must stream per tile rather than assume layer residency. Status is stated plainly: design plus measured justification, not implemented. It needs a custom TT-Metalium op, which is a larger build than the TTNN-level work here; the TTNN dequant path remains the interim correct-but-slow route.
…or bf4" means Adds TTNNBlockFloat8Linear behind BACKEND.GPTQ_TT_BF8: the GPTQ weights are dequantized once through the shared CPU oracle and stored as TT block-float bfloat8_b, so the unpack stage expands them in the data path and the hot path is a single ttnn.linear. Measured on real q_proj weights: 0.071 ms vs 0.101 ms for dequant-then-BF16, with 1.0% normalized error and ~2x the memory of int4. Opt-in and labelled as a storage re-encode, not as the optimal path. Deliberately does NOT offer bfloat4_b for GPTQ checkpoints. Re-encoding an already 4-bit weight onto a symmetric block-float grid measured 9.8% normalized error: the zero point cannot be represented and uniform levels do not map onto one shared exponent per 16 logarithmic values. That is requantisation, not optimisation, so the backend was removed rather than shipped behind a flag. Distinguishes it from the thing that *would* be an optimisation: GPTQ's solve is grid-agnostic (it needs a quantiser and its error, then minimises Hessian- weighted error column by column), so running it with a block-float grid produces a checkpoint whose weights are natively bfloat4_b and needs no dequant at all. That is a quantization-time feature producing a new checkpoint format, and it is recorded as a separate target rather than conflated with this storage mode. Feasibility for the fused int4 kernel is now established: the installed build exposes ttnn.generic_op with ProgramDescriptor/CBDescriptor/KernelDescriptor, so a custom TT-Metalium kernel can be dispatched from Python without rebuilding tt-metal. Implementation is still outstanding; the design and its measured justification stay in hw/tenstorrent.md section 9.
Path 2 of the two ways to remove per-forward dequant: quantize *onto* the Tenstorrent block-float grid at quantization time, so the resulting checkpoint is natively bfloat8_b/bfloat4_b and the unpack stage expands it in the data path with no dequant op at inference. This is the legitimate reading of "GPTQ for bf4". Converting an existing int4 checkpoint is requantization and measured ~9.8% error; running the GPTQ solve against a block-float quantizer instead produces the format by construction. Implements the grid as documented in tech_reports/data_formats: blocks of 16 share one exponent taken from the block maximum, each value keeps a sign plus a fixed mantissa width (8-bit -> 6 stored mantissa bits, 4-bit -> 2), rounding to nearest-even, with the block clamped to the representable range for its exponent. Also provides the uniform int4 reference and the normalized-L1 error metric used elsewhere. Tests cover the shared-exponent block shape, 8-bit beating 4-bit on the same data, idempotence of re-quantizing an already-gridded tensor, the mantissa widths, and the case block-float should win: a per-group int4 scale collapses when one outlier shares the group, while block-float re-scales every 16 values. Not wired into the quantizer loop yet, and no end-to-end checkpoint comparison run: the OPT-125M checkpoints were evicted from the HF cache mid-session, so the real-weight grid-vs-int4 numbers still need to be taken.
…actly
First milestone of the fused int4 design: the dequant stage now runs in a custom
kernel dispatched through ttnn.generic_op, with no rebuild of tt-metal. Nibble
extraction and the group scale/zero application happen in one pass on the core,
instead of the TTNN chain (eight nibble planes, stack, permute, two embedding
gathers, subtract, multiply) that cost ~1.27 ms per layer against a 0.06 ms GEMM.
Correctness: 8192 codes dequantized bit-exactly against an independent torch
reference -- torch.equal true, max abs error 0.0 -- including the BF16
truncation the TTNN path produces.
Throughput on one core, DRAM round trip:
8,192 codes 1.28 ms 6.4 Mcodes/s
32,768 codes 4.74 ms 6.9 Mcodes/s
131,072 codes 18.1 ms 7.2 Mcodes/s
At 7.2 Mcodes/s a 768x768 layer extrapolates to ~0.082 ms on a single core
versus 1.27 ms for the TTNN chain, ~15x before using the 11x10 grid. Stated
honestly in the docs: that is an extrapolation from a smaller peak-rate sample,
not a full-layer run, and a full layer's 1.18 MB of output does not fit in the
1464 KiB L1 in one page, so tiling is required.
Records the four undocumented dispatch requirements found the hard way: at least
two io tensors, include "api/dataflow/dataflow_api.h" (the flat name does not
resolve), use InterleavedAddrGen<true> (the older helper is absent from the
shipped headers), and that the wheel's JIT include root points at the vendor's
build container, so a new kernel cannot compile until that path resolves -- a
symlink to site-packages/pjrt_plugin_tt/tt-metal unblocks it.
Outstanding for the fused design: consume the tile in SrcA instead of writing it
back to DRAM, and tile the layer across cores and pages.
…d out A 2D-grid, page-tiled variant of the dequant kernel deadlocked on device: spun at 100% CPU with telemetry unreadable, tt-smi then failed to detect devices, and recovery needed tt-smi -r (all four boards returned, zero thermal trips). The variant is not committed. Two findings survive it. A single 1.18 MB page is wrong regardless: addressing a large offset inside one page returned numerically incorrect output, because DRAM bank rotation is per page, so a layer must be stored one page per chunk. And the single-core kernel remains the only measured-correct configuration, so its 0.082 ms/layer number is still an extrapolation rather than a full-layer result. Points the next attempt at circular-buffer synchronisation across the page loop with a 2-core/2-page bring-up first.
The page said a full 768x768 layer dequantized in ~0.082 ms. That was 0.0819 seconds -- a ms/s slip -- and the full-layer run now measures 80.98 ms on one core, bit-exact. The conclusion inverts: the custom kernel is about 64x SLOWER than the TTNN op chain (1.27 ms), not 15x faster. Recording it plainly because the claim was wrong in the direction that flatters the work. What the kernel actually has is bit-exact arithmetic and no intermediate tensors; what it lacks is multi-core spread, and it is latency-bound on the per-page DRAM round trip. Also records the multi-core status honestly: per-core page-range args are verified for 2 cores but fail at 4x4 with "Number of runtime args cannot be modified", so the only verified configuration is a 1x1 grid looping over pages.
…umes it The dense BF16 tile no longer has to reach DRAM. The BRISC reads packed words and dequantizes straight into an L1 circular buffer, the TRISC compute stage consumes that buffer via copy_tile/pack_tile, and only the finished tile is written out. Verified bit-exact on device (torch.equal true on a 32x32 tile), through the repo code path in a hardware-gated test. This is the pipeline the fused kernel is built on; what remains is replacing the copy with the FPU matmul. Two hard-won requirements, both recorded in hw/tenstorrent.md: - Tile memory order. A 32x32 tile is four row-major 16x16 faces, so codes must be permuted into face0..face3 order before packing. Linear packing measured maxerr 0.2588 with every value mispositioned; after the permutation, exact. tile_order_indices()/permute_to_tile_order() encode the mapping. - Compute kernels need format init. A TRISC kernel silently produced NaN without init_sfpu(in_cb, out_cb), which lives in api/compute/eltwise_unary/eltwise_unary.h. Also confirms ComputeConfigDescriptor dispatches from generic_op, so reader/compute/writer triples can be launched from Python without rebuilding tt-metal. 41 CPU tests pass, 5 hardware-gated skipped in CI.
…ltiplies The copy in the fused path is now a real matrix multiply. One 32x32 tile runs as a single program: BRISC reads packed words from DRAM and dequantizes into an L1 circular buffer, the TRISC compute stage calls matmul_init/matmul_tiles against the activation tile and packs the product, and only the 32x32 result is written out. The packed checkpoint never becomes a DRAM tensor. Verified against a torch reference on device: norm_l1 0.0052, maxerr 0.0185 (BF16 accumulation). Operand order is asserted, not assumed -- matmul maps in0 to SrcB and in1 to SrcA, so the weight buffer goes first to compute W x ACT, and the test requires the transposed orientation to stay an order of magnitude worse. Two non-obvious API requirements recorded: matmul_tiles(in0, in1) computes in1 x in0, and compute_kernel_hw_startup(in0, in1, out) must precede matmul_init. Explicitly not claimed: speed. This is one tile on one core where dispatch dominates, and the earlier 80.98 ms figure measured the dequant-only path with its DRAM write. Widening to a full layer over the grid with K accumulated across tiles is what makes a comparison meaningful. Correctness is currently per-tile BF16 accumulation, not the HiFi4 + fp32 accumulation the TTNN path uses, so matching that accuracy floor belongs to the widening work. 41 CPU tests pass; fused matmul and fused dequant paths both verified on device behind the hardware gate.
…st timing The kernel now accumulates the whole reduction: tile_regs_acquire() zeroes the destination and each matmul_tiles accumulates into it, so one output tile comes from all K tiles. Verified against torch at K=256 (norm_l1 0.0046) and K=768 (0.0047), with fp32_dest_acc_en=True. Measured, not extrapolated: ~3.4 ms for one output tile at K=768. A trivial kernel dispatch on this box costs 0.019 ms, so that is kernel time, not launch overhead. TTNN runs a whole 768x768 layer in ~1.33 ms. The cause is the arithmetic unit. The nibble expansion runs on BRISC, an RV32 core with no FPU, so every code->float conversion is software floating point -- 24,576 per output tile at K=768. That is the opposite of the design intent, which puts the expansion in the compute path where the SFPU does float work. The current placement is simply what was easy to prove. So the fused GEMM is functionally complete for one tile and not yet worth running. Recorded plainly: it needs the expansion moved to the SFPU and the 576 output tiles spread over the grid. Also records that reading all K tiles in one noc_async_read per stream returns inf -- a transfer spanning many pages is invalid, pages must be read individually.
…okup table scale * (code - zero) has only 16 possible results, so the expansion needs no arithmetic at all. The kernel now indexes a 32-byte table built once on the host, which removes every software-float multiply from BRISC (an RV32 core with no FPU) and is simultaneously more accurate, because the table holds correctly rounded BF16 rather than truncated values. Measured at K=768 for one output tile: soft-float on BRISC 3.395 ms norm_l1 0.00478 16-entry LUT 0.259 ms norm_l1 0.00145 13x faster and more accurate. Still not a win over TTNN, and the arithmetic is unambiguous: a 768x768 layer is 576 output tiles, so perfect spread over the 11x10 grid lands near 1.36 ms against TTNN's ~1.33 ms for the whole layer. Parity, not victory. The remaining cost is the per-K DRAM barrier -- the reader does a synchronous read plus barrier for each of the 24 K tiles per output tile. Pipelining that with double-buffered CBs is the next lever, ahead of any grid work. 42 CPU tests pass; the LUT path, the soft-float path and the K-accumulation all verified on device behind the hardware gate.
…minor cost All activation and word reads are now issued back to back and covered by a single barrier (per-page reads, since one transfer spanning pages is invalid). Single output tile at K=768: 0.259 ms -> 0.2405 ms, about 7%. So the per-K barrier was real but minor; the time is spread across the LUT expansion's stores, the matmuls and the transfers, not concentrated where one tweak removes it. That leaves the fused approach at parity with TTNN rather than ahead, and the arithmetic is the reason: 576 output tiles per 768x768 layer, so perfect spread over the 11x10 grid lands near 1.36 ms against TTNN's ~1.33 ms. Records the structural limit: with one M tile every weight tile is dequantized once for 32 rows, and TTNN pays the same order of cost, so the fused path cannot win at decode shapes by optimising the same expansion. It wins by amortising over more rows (M=128 gives 4x) or by making the expansion genuinely cheaper per element. Measuring at larger M is therefore more informative than more tuning at M=32. Also records the deadlock this change caused and fixed: the shared compute kernel was switched to staged buffers while one reader still pushed one tile at a time, which wedged the device (recovered with tt-smi -r). Compute stage and every feeding reader must agree on staged vs streamed. 42 CPU tests pass; both fused GEMM paths verified on device.
…rmed The structural limit identified last turn was that one M tile gives every weight tile only 32 rows of use. Testing that directly by reusing one dequantization across several M tiles: latency is essentially flat in M, because the same dequantized weight tiles serve every M tile. M=32 0.2405 ms 0.2405 ms per 32 rows 1.0x M=64 0.2417 ms 0.1208 ms per 32 rows 2.0x M=128 0.2443 ms 0.0611 ms per 32 rows 3.9x M=256 0.2535 ms 0.0317 ms per 32 rows 7.6x norm_l1 0.0014 at every size, verified on device and behind the hardware gate for nm=2 and nm=4. So the fused path is at parity for decode (M=32) and substantially ahead for prefill/batched shapes, which is where a quantized-inference engine actually spends its FLOPs. A full 768x768 layer at M=256 is 24 invocations of ~0.2535 ms on one core (~6.1 ms) against TTNN's ~1.33 ms -- 4.6x slower on one core, but five cores match it and the 11x10 grid would put it roughly an order of magnitude ahead before any further tuning. Grid spread is now the blocker rather than an optimisation: the kernel still runs on a single core because per-core runtime arguments do not work past two cores. 42 CPU tests pass; the M-amortised path verified at nm=2 and nm=4 on device.
|
Correctness follow-up at [P1] The solver still uses the unchanged full inverse; the new reference test duplicates that error. Production update and the new reference both compute one full inverse and reuse it after columns have been frozen. GPTQ needs the remaining-variable inverse, or the equivalent upper Cholesky factor of the inverse; the original implementation explicitly constructs that upper factor. The counterexample uses 1.2 as the initial weight. The new test's already-on-grid 1.25 example has zero error and does not exercise the disputed update. Reproduced again with the same 0.25-step ttbf4 grid in both independent references: w = torch.tensor([[1.2, 1.2, 1.2] + [0.] * 13])
h = torch.eye(16)
h[:3, :3] = torch.tensor([
[1., .8, .7],
[.8, 1., .9],
[.7, .9, 1.],
])
# bits=4, damp=.01Actual first three outputs: Use an independently constructed upper-Cholesky or remaining-inverse oracle in the test, and correct the production update. The test passing currently establishes agreement between two copies of the same algorithm. [P2] Public export drops generation settings. The new early return skips the shared generation-config serialization. Reproduction: load a block-float checkpoint, set [P2] Public export silently ignores shard-size and safetensors-metadata arguments. The same writer call forwards neither [P2] Re-saving erases checkpoint provenance. The writer replaces Confirmed fixed on this head:
Design recommendation: keep packed tensor extraction specific to this format, but reuse common publication logic for shard limits, safetensors metadata, generation settings, and provenance. The early return currently fixes tensor export while skipping those contracts. Validation: broader suite 113 passed, 15 skipped, 4 failed; the failures require the unavailable Tenstorrent PJRT/XLA runtime. The subagent's overlapping native/resident selection had 13 passed, 3 skipped, plus direct probes. No TT hardware numerics or GIL=0 qualification is claimed. No repository files were changed. |
…xport contract **The solver was wrong, and my previous reference duplicated it.** GPTQ updates a column with the remaining-variable inverse, which is the upper Cholesky factor of `H^-1` (`H^-1 = U^T U`), not `H^-1` itself. Reusing `H^-1` makes every correction too small because row `i` of the inverse is not the conditional covariance left after columns `0..i` are frozen. On the review's counterexample the fix moves column 2 from `1.25` to `1.0` and lowers the damped objective from 0.0195 to 0.0170; on a 128x256 layer the output MSE improves 8.9 % at 4 bits. This is not `triu(cholesky(H))` -- that is the lower factor of `H` and its `triu` keeps only the diagonal, which is why the earlier note dismissed it. The factor has to be taken of the inverse, and it is upper. The previous test compared the solver against a second copy of the same mistake, so it now uses an independent upper-Cholesky oracle plus the counterexample that separates the two updates. **Public export now honours the save contract.** The early return in `save_quantized` fixed tensor export but skipped the rest of publication: - `generation_config.json` is written, so eos/max_new_tokens survive a reload. - `max_shard_size` is parsed by the shared parser and passed to the writer. - `safetensors_metadata` reaches the shard headers; `format` stays authoritative. - `quantization_config.meta` is inherited and merged, so a re-export keeps the source model and tokenizer provenance the evaluation tooling reads. `_parse_max_shard_size` and `_normalize_metadata` moved to module level so both paths use one implementation instead of a nested copy. Verified on the shipped Llama-3.2-1B-Instruct checkpoint: with the same shard limit the re-export is byte-identical (all three shards and the index), the header metadata is exact when not overridden, provenance is preserved, and `generation_config.json` is present. 92 passed, 14 skipped; ruff clean.
|
Fixed in [P1] Remaining-variable inverse — fixed. GPTQ updates a column with the upper Cholesky factor of Your counterexample, reproduced here:
The earlier note in the code that dismissed this ("taking The test now uses an independently constructed upper-Cholesky oracle, adds your Measured effect on a 128x256 layer with a real [P2] Generation settings — fixed. The early return now calls [P2] Shard size and safetensors metadata — fixed. [P2] Provenance — fixed. The writer now inherits Re-verified on the real artifact: with One consequence worth flagging: the published 92 passed, 14 skipped; ruff clean. |
|
Focused review: non-Tenstorrent GPTQ/Hessian regression check against PR base Conclusion: no numerical regression found in the standard GPTQ/Hessian paths tested, but the PR still has non-Tenstorrent compatibility regressions in shared device helpers. I would not give a blanket regression sign-off. The numerical paths have not merged at this head: [P2] CPU GPTAQ/FOEM auto staging can select an unavailable XLA device. [P2] Portable QQQ loses pre-Ampere NVIDIA support. [P2] Ordinary GPTQ synchronization now probes and initializes unrelated XLA. Numerical evidence:
A fresh subagent independently reviewed the shared lifecycle/device changes. No ROCm hardware, physical pre-Ampere GPU, mixed TT/CUDA host, or GIL=0 qualification is claimed. No repository code was modified. |
…mpere QQQ
Three regressions against the PR base in shared device code. None of them touch
the block-float numerics; they affect ordinary CPU/CUDA jobs.
**`auto_select_torch_device_unprobed` selected `xla:0` from package presence.**
`HAS_XLA` only records that `torch_xla` is installed, so a host with no
accelerator and an XLA runtime reporting zero devices initialized `DEVICE_0/1`
as `xla:0/xla:1` where base used `cpu`. Asking whether XLA is usable calls
`addressable_device_count()`, which initializes PJRT and claims every
Tenstorrent chip for the process. The unprobed selector now returns CPU when
there is no probe-free accelerator; callers that want XLA resolve it explicitly
through `is_xla_available()` / `xla_device_count()`, which are allowed to pay
that cost.
**`torch_sync()` probed XLA on every barrier.** A `device=None` sync called
`is_xla_available()` unconditionally, so ordinary GPTQ -- reaching it through
subset completion, layer finalization and forward replication -- imported XLA
and requested addressable devices. It now synchronizes XLA only when the
runtime was already initialized, detected by the claim flag `xla_device_count()`
sets after the probe answers (`xla_runtime_claimed()`). A CUDA/ROCm/CPU job no
longer discovers or claims another runtime.
**Portable QQQ rejected pre-Ampere NVIDIA.** `QQQTorchLinear` inherits from the
native `QQQLinear`, whose `validate_device` enforces the Marlin compute
capability floor and a CUDA-only requirement. The portable kernel computes with
a plain FP32 matmul, so it needs neither; it now skips that check and applies
only the generic device-family validation, which is what the fallback had before
the family checks landed. The native kernel keeps its SM80 restriction.
Tests cover all three: unprobed selection returns CPU with XLA "installed", an
unclaimed barrier never touches XLA while a claimed one does, and the portable
kernel validates without consulting compute capability while the native kernel
still raises on SM75.
153 passed, 36 skipped. The 2 failures in `test_calibration_data_device.py` are
pre-existing on this host: the installed `tt_torch` plugin patches
`torch.device("cuda:N")` and fails identically at the PR base.
`save_blockfloat_model` cast every non-quantized tensor to float16. On Llama-3.2-1B that saved 0.13 MiB and rounded `layers.0.input_layernorm.weight` by one ulp (1.5e-08), which was enough to break the "reload is bit-exact" invariant: the re-quantized checkpoint failed its own reload check with a 1.67e-05 logits drift, entirely from that one norm. Dense tensors now keep the model's own dtype, and `torch_dtype` in the saved config names that dtype rather than claiming float16, so a plain `from_pretrained` does not round them on the way back in. Cost on the 1B model: 996.3 -> 996.4 MiB.
|
Shared-helper regressions fixed in [P2] Unprobed staging could select [P2] [P2] Portable QQQ lost pre-Ampere support — fixed. Tests added for each: unprobed selection returns CPU when XLA is merely installed; an unclaimed Suite: 153 passed, 36 skipped. The 2 failures in |
…uper() hop CodeQL flagged `super(QQQLinear, cls)` in `QQQTorchLinear.validate_device` as "first argument to super() is not the enclosing class". Its suggested fix -- `super(QQQTorchLinear, cls)` -- would resolve to the native kernel's override and reintroduce the regression that method exists to avoid: a pre-Ampere NVIDIA card being rejected for a kernel that computes with a plain FP32 matmul. The difference is now a class attribute. `QQQLinear.MARLIN_DEVICE_RESTRICTIONS` is True and gates the SM80 floor and the ROCm rejection; `QQQTorchLinear` clears it and inherits one implementation, so `super()` sits in its own class and the linter is satisfied without changing behaviour. Verified: portable validates `cuda:0` without consulting compute capability, native still raises on SM75, and the ROCm rejection still applies only to the native kernel.
…ed with upstream Upstream `tt::DataFormat` has two block-float families, told apart by the shared exponent width: `Bfp4`/`Bfp8`/`Bfp2` use 5 bits (ExpPrecision::A), `Bfp4_b`/`Bfp8_b`/`Bfp2_b` use 8 (ExpPrecision::B). Only the B family is exposed to Python, as `ttnn.bfloat4_b` / `ttnn.bfloat8_b`; `bfloat4` and `bfloat8` do not exist, and there is no `_a` or `_c` variant of either. Our quantizer implements the 8-bit exponent, so the previous unprefixed `bf4`/`bf8` names denoted the *other* format in upstream's own vocabulary. Keep the suffix: canonical `bf4_b`/`bf8_b`, full vendor spelling only at the `getattr(ttnn, ...)` call site. - rename across the quantizer, layers, backend, config, script, docs, tests - record the enum values, ExpPrecision mapping and the absence of `_a`/`_c` in `hw/dtypes.md` §8.5, and the rationale in §1 - test: canonical name is the vendor spelling with only `bfloat` shortened, and the un-suffixed / `_a` / `_c` / `bfloat2_b` names are absent from ttnn Checkpoints store numeric `bits` per layer, not these strings, so existing artifacts still load unchanged.
Conflict in `TorchLinear.optimize`: main added the `compile=False` early return, this branch added the XLA skip. Keep both guards — they are independent reasons not to enter `torch.compile`, and either alone leaves the other case broken.
….16 MiB The docstrings claimed 279 MiB, which does not match the artifact. Measured from the shard headers: 250.50 MiB codes + 15.66 MiB exponents = 266.16 MiB, against 501.00 MiB of dense float16.
…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.
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.
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.
…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.
…3806) * feat(tenstorrent): run bf8/bf4 checkpoints on ROCm with HIP kernels 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. * feat(tenstorrent): define the bfloat2_b grid 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. * docs(tenstorrent): record the large-M prefill plateau 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. * refactor(tenstorrent): align the HIP emulation to the merged bf*_b naming #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. * fix(tenstorrent): stage partial K spans and initialise the base candidate 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. * fix(tenstorrent): flatten activations and guard the HIP dispatch 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. * docs(tenstorrent): refresh the prefill numbers after the staging fix 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. * fix(tenstorrent): keep int32 indices and empty batches working 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).
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.
…oats (#3808) * feat(ext): add CPU kernels for Tenstorrent bf8_b/bf4_b block floats * feat(ext): add bf2_b (Bfp2_b) block-float support to ttbfp * docs: describe ttbfp as CPU kernels rather than an emulator 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. * docs: align ttbfp names with bf8_b/bf4_b/bf2_b 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. * fix(ext): address native-kernel review of ttbfp CPU kernels - 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. * docs(ext): document the flat-layout cols stride restriction * fix(ext): honor ftz=False under ambient FTZ/DAZ 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. * style(ext): reindent the ftz-guard parallel blocks * fix(ext): keep bf4/bf2 packed and zero empty reductions - 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. * docs(ext): correct the bf4_b M=64 speedup to 1.9x
* feat(tenstorrent): emulate bf8/bf4 block-float on CUDA 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. * fix(tenstorrent): make the CUDA scratch per-call and stream-safe 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. * fix(tenstorrent): mask odd-N fallback stores and keep empty forwards 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.
Adds three Tenstorrent execution paths to GPT-QModel and publishes a real
checkpoint for the third:
BACKEND.GPTQ_TT_XLA/XLALinear— packed GPTQ through Torch/XLA and thePJRT TT plugin.
BACKEND.GPTQ_TTNN/TTNNLinear— the same GPTQ contract expressed innative TTNN ops on a
1xNmesh, with no StableHLO or PJRT in the path.METHOD.TT_BLOCKFLOAT— GPTQ solved onto the hardware's own block-floatgrid (
bf4_b/bf8_b), so a checkpoint needs no dequant at inference. Thisis the part with a published artifact and end-to-end quality numbers.
Validated on
tt-quietbox: 4× Blackhole p300c (4-chip mesh), Ubuntu 26.04.1,kernel 7.0.0-43-generic, TT-KMD 2.12.0, firmware 19.17.1, Python 3.12.16,
ttnnfrompjrt-plugin-tt 1.5.0.dev20260831000501.Scope limits, stated up front. No model-level token parity is claimed for the
XLA or TTNN paths — only per-layer numerics against an independent FP32 Torch
oracle.
TTNNLineartherefore stays out ofAUTO. The block-float path isvalidated end to end, and its numbers are below.
1. Why this exists
The XLA path works but pays for StableHLO/PJRT and cannot use exact 32-bit
integer shifts, so it uploads uint8 byte planes. Nothing let a user talk to
TT-Metal directly, nothing exploited the four cards as one fabric domain, and
nothing targeted the block-float storage formats the hardware unpacks for free.
BACKEND.GPTQ_TT_XLABACKEND.GPTQ_TTNNaddedgptqmodel/utils/backend.pyttnn_runtime.open_meshsingle-owner lifecyclegptqmodel/utils/ttnn_runtime.pyqlinear/ttnn.pyxla:N, no collectiveout_featuressharded over1xN+FABRIC_1Dall_gatherqlinear/ttnn.pybf4_b/bf8_b, stored as codesutils/tt_blockfloat_quant.py2. The two inference backends
flowchart LR A["Python + Transformers"] --> B["GPTQModel.load"] B --> C{"selected backend"} C -->|"gptq_tt_xla"| D["XLALinear"] D --> E["Torch/XLA StableHLO"] E --> F["PJRT TT plugin"] F --> G["TT-MLIR lowering"] G --> H["bundled TTNN / TT-Metal"] C -->|"gptq_ttnn"| I["TTNNLinear"] I --> J["ttnn_runtime.open_mesh"] J --> K["ttnn.MeshDevice 1xN"] K --> L["nibble extract + dequant on Tensix"] L --> M["ttnn.linear HiFi4 fp32 acc"] M --> N["all_gather dim 1"] H --> O["4x p300c"] N --> O classDef fail fill:#fee2e2,stroke:#b91c1c,color:#7f1d1d; P["PJRT already owns the chips"]:::fail --> Q["TTNNUnavailable with cause"]:::failWeight lifecycle (both paths): only packed tensors persist. The dequantized
BF16 tile is created per forward and freed before the call returns; no dense,
dequantized, or expanded weight cache survives an operation, which is the
repository-wide invariant.
What the native path buys. TT-Metal accepts
uint32forlogical_right_shift/bitwise_andand rejectsuint8/uint16for those ops,so the packed words upload unchanged instead of being expanded into byte planes
on the host. Measured on this box, the on-device dequant is ~85 % of a layer's
forward and the GEMM is ~4 % — the optimisation target is the expansion, not the
transfer, which is why the block-float work exists.
3. Native block-float:
bf4_b/bf8_bttnnspells thesebfloat4_b/bfloat8_b; the repository calls thembf4_band
bf8_band uses that spelling everywhere except thegetattr(ttnn, ...)callsite. The
_bis kept because it is load-bearing, not decoration: upstreamtt::DataFormatdistinguishesBfp4/Bfp8(5-bit shared exponent,ExpPrecision::A) fromBfp4_b/Bfp8_b(8-bit,ExpPrecision::B), and only theB family is exposed to Python. There is no
_aor_cvariant of either. Theycarry no vendor prefix on the assumption that no other provider claims
bf4_b/bf8_b. They are not industry formats: OCP microscaling uses oneE8M0scale per 32 values and NVIDIA NVFP4 one
FP8scale per 16, and neither isbit-compatible with a plain power-of-two exponent shared by 16 values.
Every dtype in this PR — including
bf4_b/bf8_b— is defined at the bit level, forboth weights and arithmetic, in the new
hw/dtypes.md.The grid was measured on silicon, not assumed. Encoding values and reading
them back:
bf4_b0.5, 0.625, 0.75, 0.875)2^exp / 4bf8_b2^exp / 64Codes span
[-(2·levels−1), +(2·levels−1)]— 15 levels forbf4_b, 255 forbf8_b. It is a storage format: the unpack stage expands it to BF16 in thedata path, so there is no dequant op in the graph, but there is also no BFP
arithmetic unit.
GPTQ runs on that grid directly. The solve is grid-agnostic: it needs a
quantizer
Qand its error, then minimises Hessian-weighted error column bycolumn.
utils/tt_blockfloat_quant.pysuppliesQfor the Tenstorrent grid, sothe resulting weights are native — not int4 cast onto a block-float grid
(measured 9.8 % error) and not a dequant cache.
The error-feedback update uses the remaining-variable inverse, i.e. the upper
Cholesky factor of
H⁻¹(H⁻¹ = UᵀU), which is what GPTQ specifies. ReusingH⁻¹directly makes every correction too small; on a synthetic 128×256 layerwith a real
XᵀXthe fixed update improves output MSE by 8.9 % at 4 bits.Checkpoint format
An ordinary Hugging Face directory — shards plus
model.safetensors.index.json,no bespoke payload file, no sidecar manifest:
<prefix>.codesuint8<prefix>.exponentsint8exponent per block of 16 values<prefix>.code_shape[out_features, in_features]value = (code - (2*levels - 1)) / levels * 2**exponent, which is exactarithmetic: loading does not re-quantize anything. The tied
lm_headis notstored — the shipped
modeling_tt_blockfloat.pygives it a view over theembedding's codes, and
config.json'sauto_mappoints at it so plaintransformerscan load the directory.Published artifact
https://huggingface.co/Qubitium/llama3.2-1b-instruct-tenstorrent-bf8-bf4-w4a16
(public, 13 files, 1012.9 MiB, revision
a827d9a). The repo is namedbf8-bf4because
bf8_bis the majority width — 81 of 113 modules, including theembedding; the old
...-bf4-...name understated it and now redirects here.unsloth/Llama-3.2-1B-Instructbf8_b, 32 ×bf4_b, embeddingbf8_b)q/k/v/o/down_proj= 8-bit,gate/up_proj= 4-bit, embedding = 8-bitneuralmagic/calibrationllm.parquet, 256 records, 87,380 tokens, 32×256 Hessian0.0Held-out perplexity (rows 256–319 of the same parquet, disjoint from
calibration, 6 × 512 tokens):
GSM8K accuracy was not re-run on the current revision. The previous revision
scored 54/200 on GSM8K-Platinum against 49/200 dense, a 5-question gap at n=200
(se ≈ 3.1) that is inside the noise floor and therefore says nothing either way.
4. Shared integration
The block-float format is inference-only and pre-quantized, so it plugs into the
existing lifecycle rather than building a new one:
METHOD.TT_BLOCKFLOATis inQUANTIZE_BLACK_LIST;QuantizationRunPlan.buildrefuses it, and
quantize()points atscripts/tt_quantize_blockfloat.py.GPTQModel.loadrunsrequire_trust_remote_codeandcheck_versionsbeforetaking the block-float route, and rejects a non-CPU
device/device_map.save_quantized()exports the packed state verbatim (the generic writer wouldrebuild a dense model it cannot represent) while honouring the rest of the save
contract: shard limit, safetensors header metadata,
generation_config.json,and the checkpoint's own provenance.
installs, so a swapped
code_shapeis rejected at load instead of failing onfirst forward.
5. Failure behaviour
Tenstorrent failures are raised as Python exceptions with a cause; nothing in the
TT code calls
sys.exit,os._exit, or aborts natively. Exercised paths:FileNotFoundErrornaming the fileValueErrornaming the fileValueErrorlisting themtt-blockfloatValueError.codeswithout a valid.code_shapeValueErrorValueErrorwith both expected sizescode_shapedisagreeing with the moduleValueErrorTTNNUnavailablewith cause6. Tests
tests/test_tenstorrent_support.py(3,479 lines) plustests/test_calibration_windows.py. Hardware-dependent cases are gated behindGPTQMODEL_TEST_TT_XLA/GPTQMODEL_TEST_TTNN.ruff checkclean; CodeQL and Analyze green.Coverage includes: the measured grid for both widths, GPTQ-on-grid against an
independent upper-Cholesky oracle, native-vs-int4 distinction, checkpoint
round-trips (byte-identical re-export), corrupt-checkpoint rejection, the save
contract, mesh readback composition, cache-key handling for inference tensors,
and device selection.
7. Corrections made during review
Recorded because the earlier claims in this PR were wrong and were retracted:
H⁻¹directly; GPTQ needs the remaining-variable inverse (upper Cholesky ofH⁻¹). Fixed, with a test that separates the two.nn.Linear. Fixed; re-export is now byte-identical.--embed-bitsquantizes the embedding"8. Not in scope
TTNNLinearinAUTO— it needs an explicit backend.hw/tenstorrent.md§9; the block-float path exists because it needs no customTT-Metalium op.
9. Where the details live
hw/dtypes.md— the single dtype reference: bit layouts, weights vsarithmetic, MX/NV/block-float definitions, emulation caveats.
docs/tenstorrent.md— user-facing behaviour, configuration, thermal guards.hw/tenstorrent.md— measured hardware findings: dtypes, grid, tile shapes,the dequant cost breakdown, mesh and fabric behaviour, power/thermal data.