Pidoku

Low-Precision Kernels: Block-Scaled FP8/FP4 and Mixed-Input GEMMs

Module 25 Lesson 25.g 1h 25m Difficulty 5/5

Prerequisites 13.e, 13.f, 13.g, 25.a, 25.e


Before you start: words you need#

WordPlain meaning
Scale factorA number stored next to a block of low-precision values; the real value is the stored value × its scale.
Per-tensor / per-channel / block scalingOne scale for the whole tensor, one per row or column, or one per small block (16, 32 or 128 × 128 values).
Block-scaled MMAA tensor-core instruction that takes the low-precision operands and their scale factors and applies the scales itself (Blackwell).
Mixed-input GEMMA GEMM whose two operands have different types, e.g. 4-bit weights × 16-bit activations (W4A16). The weights must be converted before or inside the MMA.
DequantiseTurn a low-precision value back into a higher-precision one by applying its scale (and zero point).
Zero pointAn offset subtracted from an unsigned integer weight so it can represent negative values (GPTQ/AWQ store 4-bit weights as 0–15 with offset 8).
PrepackingRearranging weights once at load time into the exact order the kernel’s registers and tensor cores need.
PromotionPeriodically moving a partial sum from the tensor core’s accumulator into a higher-precision FP32 register sum, to limit accumulated rounding error.

1. What is it?#

Quantisation (13.b–13.h) decides which format a model uses. This lesson is about the kernels that make those formats fast. There are two families:

  1. Same-type, low-precision GEMMs: FP8 × FP8, FP4 × FP4 (and FP8 × FP4), where both operands are low precision and the tensor core multiplies them natively. The engineering is in scale factors: where they live, when they are applied, and in what layout.
  2. Mixed-input GEMMs: INT4 or FP4 weights × BF16 or FP8 activations. The tensor core has no instruction for the mixed pair, so the kernel must convert the weights on the fly, between shared memory and the MMA, without slowing the pipeline. Marlin (Ampere and later) and Machete (Hopper) are the reference designs.

Facts checked on 13 November 2026 (PTX ISA 9.5, CUTLASS 4.8.1, vLLM v0.32.0, DeepGEMM main).


2. Why does it matter?#

  • Decode is memory-bound, so bytes per weight set the speed (2.e). Four-bit weights read 4× less than BF16 — but only if the kernel can convert them as fast as HBM delivers them. 13.f’s table shows the gap: naive dequantise-then-GEMM gives 1.3–1.5×; Marlin-class kernels 3.0–3.7× at batch 1.
  • Prefill is compute-bound, so tensor-core rate sets the speed. On B200, dense FP4 is 4× and FP8 2× the BF16 rate, if the kernel keeps scale handling off the critical path.
  • Accuracy lives in the scales. Block scaling (one scale per 16–128 values) is what makes FP8 and FP4 accurate enough for large models (13.g). Each extra scale is extra data the kernel must load, lay out and apply.

3. Simple analogy#

Prices in a shop written in “hundreds” on one shelf and “units” on another. Block scaling puts a little label on each shelf ("× 100") and the cashier (the tensor core) multiplies by the label as they add up the basket. Blackwell’s cashier reads the shelf labels directly; Hopper’s cashier needs a helper to multiply by the label after every few items.

A mixed-input GEMM is a cashier who only accepts euros, given a basket priced in a foreign currency. Someone must convert every price before the cashier sees it. Done item by item at the till, it is slow; done with a pre-printed conversion sheet arranged in the order the cashier scans (prepacking) and a fast trick for each conversion, it costs almost nothing.


4. Tiny example: turning INT4 into FP16 with no conversion instruction#

Converting an integer to a float normally needs a conversion instruction (I2F), which is slow relative to the data rate. Marlin-style kernels use a bit trick instead: FP16 1024.0 is 0x6400, and its 10 mantissa bits count in steps of exactly 1. OR-ing a 4-bit value q into the low mantissa bits gives the FP16 number 1024 + q. One logic instruction (LOP3, which does AND and OR together) does it for two values at once in a 32-bit register.

Go
// int4trick.go — the bit trick Marlin-style kernels use to turn packed 4-bit weights into
// FP16 without any integer-to-float conversion instructions, checked for every value.
package main

import (
	"fmt"
	"math"
)

// half decodes an IEEE FP16 bit pattern (normal numbers only, enough here).
func half(h uint16) float64 {
	sign := 1.0
	if h&0x8000 != 0 {
		sign = -1
	}
	exp := int(h>>10) & 0x1f
	frac := float64(h & 0x3ff)
	return sign * (1 + frac/1024) * math.Pow(2, float64(exp-15))
}

func main() {
	// Eight signed INT4 weights (stored with an offset of 8, as GPTQ/AWQ do), packed in one 32-bit word.
	w := []int{-8, -3, 0, 7, 5, -1, 2, -6}
	var packed uint32
	for i, v := range w {
		packed |= uint32(v+8) << (4 * i)
	}
	fmt.Printf("packed register: 0x%08x\n", packed)

	// The trick: OR a nibble into the low mantissa bits of FP16 1024.0 (0x6400) and the half
	// *is* 1024 + q. Two halves per 32-bit register, so one AND+OR (a single LOP3) makes two values.
	const magic = 0x64006400
	var out []float64
	for _, shift := range []uint{0, 8} { // two shifts reach all 8 nibbles
		x := packed >> shift
		lo := (x & 0x000f000f) | magic // nibbles k and k+4 -> 1024 + q in each half
		hi := (x & 0x00f000f0) | magic // nibbles k+1 and k+5 -> 1024 + 16q in each half
		for _, r := range []uint32{lo, hi} {
			for _, part := range []uint16{uint16(r), uint16(r >> 16)} {
				v := half(part)
				if r == hi {
					v = v/16 - 64 // one FMA: (1024 + 16q)/16 - 64 = q
				} else {
					v -= 1024
				}
				out = append(out, v-8) // remove the zero-point offset
			}
		}
	}
	// Values come out interleaved (0,4,1,5,2,6,3,7); Marlin pre-permutes weights at load time
	// so that this order is exactly what the tensor-core fragment needs.
	fmt.Println("decoded (register order):", out)

	// Exhaustive check of the low and high paths for every 4-bit value.
	ok := true
	for q := uint32(0); q < 16; q++ {
		if half(uint16(q|0x6400))-1024 != float64(q) || half(uint16(q<<4|0x6400))/16-64 != float64(q) {
			ok = false
		}
	}
	fmt.Println("all 16 nibble values decode exactly:", ok)
}
packed register: 0x2a7df850
decoded (register order): [-8 5 -3 -1 0 2 7 -6]
all 16 nibble values decode exactly: true

Per 8 weights: two shifts, four LOP3s and four FP16x2 subtract-or-FMA instructions, then the group scale is applied with one more FP16x2 multiply. The weights come out in an interleaved order, which is why Marlin and Machete prepack the weight matrix at load time: the permutation is paid once, and at run time every 32-bit load produces exactly the values the next mma needs.


5. Technical explanation#

Where scales are applied#

SchemeScale granularityAppliedTypical kernel
Per-tensor FP8one per tensor (A and B)epilogue: one multiply of the accumulatorcuBLASLt FP8, CUTLASS
Per-token × per-channel FP8 / INT8one per row of A, one per column of Bepilogue: an outer product of two scale vectors (EVT, 25.c)vLLM scaled_mm
Blockwise FP8 (DeepSeek-V3 style)A: 1 × 128 per token; B: 128 × 128inside the mainloop, once per K-block of 128DeepGEMM, CUTLASS blockwise
MXFP8 / MXFP6 / MXFP41 × 32 along K, E8M0 (power of two)by the tensor core on Blackwelltcgen05.mma ... block_scale
NVFP41 × 16 along K, E4M3, plus a per-tensor FP32by the tensor core (block scales) + epilogue (tensor scale)CUTLASS, FlashInfer, TRT-LLM

The rule: a scale that is constant along K can wait for the epilogue. A scale that changes along K must be applied before partial sums from different blocks are added — either by the kernel in registers (Hopper) or by the tensor core (Blackwell).

Blockwise FP8 on Hopper: scaling and promotion in the mainloop#

Hopper’s wgmma has no scale inputs. A blockwise FP8 kernel therefore runs, for each K-block of 128:

acc_tc = 0                                  # tensor-core accumulator, registers
wgmma(A_fp8[:, kblk], B_fp8[kblk, :]) -> acc_tc     (4 x k32 instructions)
acc_fp32 += acc_tc * (scale_A[row, kblk] * scale_B[kblk, col])   # CUDA-core FMAs

That multiply-add also performs promotion: the DeepSeek-V3 report found that FP8 accumulation inside H800 tensor cores keeps only about 14 bits, and moving partial sums into FP32 registers every 128 elements (4 wgmmas) restores accuracy (13.e). The cost is extra registers and CUDA-core work that must overlap with the next wgmma — DeepGEMM’s main engineering problem on Hopper, solved with warp specialisation and ping-pong (25.b).

Block scaling on Blackwell: scales go to the tensor core#

tcgen05.mma.cta_group::1.kind::mxf4nvf4.block_scale.scale_vec::4X
        [d_tmem], a_desc, b_desc, idesc, [sfa_tmem], [sfb_tmem], enable_input_d
  • The scale factors for A and B live in TMEM, copied there from shared memory with tcgen05.cp.
  • .kind::mxf8f6f4 covers MXFP8/6/4 (E8M0 scales per 32); .kind::mxf4nvf4 covers MXFP4 and NVFP4 (scale_vec::4X = one UE4M3 scale per 16 values); the multiply by the scale happens inside the MMA at full rate.
  • Scale-factor layout is part of the format. cuBLASLt, CUTLASS and FlashInfer expect scales in a specific swizzled layout (tiles of 128 rows × 4 scale columns, interleaved) so that TMA can load them in one box per K-block. The quantisation kernel that produces FP4 activations must write that layout directly; a “plain” row-major scale tensor costs an extra reshuffle kernel.
  • DeepGEMM’s SM100 path takes scales in packed UE8M0 (four per 32-bit int) and requires TMA-aligned, transposed scale layouts; its SM90 path takes FP32 scales.

Fused quantisation of activations#

For W4A4 or W8A8 inference, the activations must be quantised on the fly every layer. The fast designs fuse it into the previous kernel’s epilogue (RMSNorm + quantise, SiLU-and-mul + quantise, the GEMM epilogue of the previous layer): compute the block’s absolute maximum, derive the scale, write FP4/FP8 values and scale factors in the swizzled layout. vLLM’s activation_nvfp4_quant_fusion_kernels.cu and FlashInfer’s fused norm-quant kernels are examples. An unfused quantise kernel reads and writes the activation once more, which at decode batch sizes can cost as much as the GEMM.

Mixed-input GEMMs: Marlin and Machete#

Marlin (IST Austria, 2024; in vLLM for GPTQ/AWQ INT4 and also FP8 and FP4 weights) targets W4A16 at small batch:

  • Weights prepacked so each thread’s 128-bit load yields exactly the INT4 values for its mma.sync fragments; scales grouped (typically 128 along K) and also prepacked.
  • Dequantisation with the bit trick above, in registers, interleaved with mma.sync so the tensor core and the ALU overlap.
  • cp.async multi-stage pipelines and a striped partition of the weight matrix across SMs so that even a batch-1 GEMV uses every SM, with a global reduction at the end.
  • Result (paper): close to the ideal 4× over FP16 at batch 1–32 on A10/A100-class GPUs.

Machete (vLLM, Hopper) is “a spiritual successor to Marlin” built on CUTLASS 3:

  • Uses wgmma with the A operand from registers: the converted weights go straight from the conversion code into the MMA; activations are the B operand from shared memory. (Machete computes W × A, i.e. it is swapped: weights on the MMA’s M side.)
  • Prepacks weights to match wgmma’s register fragment layout, so shared-memory loads are wide.
  • Generated per type pair and schedule by generate.py, with a heuristic per problem shape.

On Blackwell, CUTLASS has mixed-input schedules (KernelTmaWarpSpecialized1SmMixedInputSm100), where a dedicated transform warpgroup converts weights from shared memory into the A operand in TMEM (or back into shared memory) so the single-thread MMA issuer never waits. Mixed FP8 × FP4 (DeepGEMM’s fp8xfp4 mode, used for DeepSeek’s FP4 expert weights) is natively supported by kind::mxf8f6f4 and needs no software conversion.


6. Under the hood: a W4A16 decode step, by the numbers#

Llama-class 70B layer (about 0.86 billion weights), decode at batch 8, H100 SXM:

weights per layer (BF16)           ≈ 1.72 GB → at 3.35 TB/s ≈ 0.51 ms
weights per layer (INT4, group 128) ≈ 0.43 GB + 3 % scales ≈ 0.44 GB → ≈ 0.13 ms at full rate
weights to convert per second      ≈ 0.86 G / 0.13 ms ≈ 6.6 × 10^12
conversion work per weight         ≈ 1.5 simple ALU instructions (LOP3, FP16x2 sub/FMA, scale)
                                   ≈ 10^13 ALU ops/s, a modest share of the SM's non-tensor ALU rate

The ALU budget is comfortable if the conversion is register-to-register and overlapped with loads. It breaks when (a) weights are unpacked through shared memory a second time, (b) scales are reloaded per value instead of per group, or (c) the kernel’s tile shape leaves SMs idle at small M (Marlin’s striped partitioning solves that). At large batch the GEMM becomes compute-bound and W4A16 loses its advantage: the tensor core still runs at BF16 rate, plus conversion overhead. That is why FP8 and FP4 activation formats (W8A8, W4A4) take over in prefill-heavy and high-batch serving (13.b).


7. Performance implications#

  • Batch decides the winner. W4A16 (Marlin/Machete) wins at small batch (memory-bound); FP8 W8A8 and NVFP4 W4A4 win at large batch and in prefill (compute-bound).
  • Blackwell changes the balance: hardware block scaling makes NVFP4 W4A4 nearly free in accuracy handling, so FP4 is fastest in both regimes on B200/B300 if accuracy is acceptable (13.g).
  • Group size costs bandwidth. Scales add bytes: one FP16 scale per 128 INT4 weights is +3 %; NVFP4 (one FP8 per 16 plus a tensor scale) is +12.5 %. Smaller groups are more accurate and slower.
  • Look for the conversion bottleneck in the profiler: ALU pipe saturated, tensor pipe idle, DRAM well below peak.

8. Production implications#

  • Check the kernel, not just the format. vLLM’s log names the linear method (for example MarlinLinearMethod, CUTLASS FP8, FlashInfer FP4). A format that runs on a generic fallback gives little speedup (13.f).
  • Weight repacking costs start-up time and memory. Marlin and Machete repack at load; budget for it in cold start (20.g, 20.h).
  • Scale layouts are an interface. When you produce quantised checkpoints or quantise activations yourself, match the scale layout the GEMM expects (DeepGEMM: TMA-aligned, transposed, UE8M0 packed on SM100), or pay for a transform kernel every step.
  • Architecture-specific paths. Blockwise FP8 has SM90, SM100 and SM120 implementations in vLLM (scaled_mm_blockwise_sm{90,100,120}_fp8.cu); results differ slightly between them. Accuracy evaluation must run on the target GPU (28.d).

9. Common mistakes#

  1. Dequantising weights to BF16 in a separate kernel, then calling cuBLAS: it reads 4-bit, writes 16-bit, reads 16-bit again.
  2. Applying K-varying scales in the epilogue. Blockwise scales change along K; applying them once at the end is mathematically wrong.
  3. Skipping promotion on Hopper FP8 with long K; error grows with K.
  4. Unfused activation quantisation, which costs a full extra pass over activations.
  5. Mismatched scale-factor layout (row-major instead of the swizzled 128 × 4 tiles), causing either wrong results or a hidden transform kernel.
  6. Assuming W4A16 helps prefill. It mostly helps decode.
  7. Using MXFP4 tolerances for NVFP4 or the reverse: different block sizes and scale formats give different error profiles (13.g).

10. Hands-on exercise#

  1. Extend the Go program to apply a group scale and a zero point stored as FP16 and compare the result with float64 dequantisation for 128 random weights. What is the maximum error?
  2. In vLLM, serve the same model as AWQ (Marlin) and FP8 on one H100. Measure decode tokens per second at batch 1, 8, 64 and 256, and prefill throughput. Where do the curves cross?
  3. Read csrc/quantization/machete/machete_prepack_kernel.cuh in vLLM and explain what permutation the prepack applies.
  4. On a B200, compare a CUTLASS NVFP4 GEMM with a BF16 GEMM at M = 16 and M = 8192, N = K = 8192. Explain the two ratios.

11. Interview questions#

  1. Why can per-channel scales be applied in the epilogue but blockwise scales cannot?
  2. What is FP8 accumulation promotion and why did DeepSeek need it on Hopper?
  3. How does Blackwell’s block-scaled MMA change FP8/FP4 kernel design?
  4. Explain the 0x6400 trick for INT4 → FP16 conversion. Why do Marlin-style kernels prepack weights?
  5. Why does Machete put the converted weights in the A operand of wgmma?
  6. W4A16 versus W4A4 for a decode-heavy chat service and for a prefill-heavy RAG service: which and why?
  7. A new FP4 checkpoint is only 1.2× faster than FP8 on B200. What do you check?

12. Further reading#

Checked on 13 November 2026.

↑↓ navigate↵ openesc close

100% drag to pan · scroll or pinch to zoom · double-click to zoom in