Skip to content

Commit 76ad10f

Browse files
tournierjcashhart
authored andcommitted
nvfp4: Flash Next reads the NVFP4 (ModelOpt FP4) checkpoint as it ships (#67)
PR #67's first twenty commits, rebased onto next-0.3.6.2 as one (their branch merged main twice; the moved MoE module is the only adaptation). Its commits: - nvfp4: the format's decoder, its row-invariant matmul, and the MoE tables - nvfp4: the engine's route for the checkpoint — BF16 non-experts, FP4 experts, the stacked tables checked on real d - nvfp4: the family admits modelopt checkpoints on CUDA (require_readable's refusals route) - nvfp4: the recipe's NVFP4 section — the format, the route, what the real checkpoint checks - nvfp4: the MTP layer's BF16 stacked experts ride the FP4 tables (the checkpoint excludes them from FP4) - nvfp4: the BF16 embedding as a plain B16 (the row lookup, not a matmul face) - nvfp4: the draft head from the bf16 lm_head requantized 4-bit (drafts change speed, never bits) - nvfp4: the whole expert stack decodes in one pass (e2m1_bits and row_scales stacked, load time at the 512-expert sca - nvfp4: the draft head quantized from the full bf16 lm_head, rows in token-id order (the sampler maps the subset as o - nvfp4: a tiny modelopt checkpoint builder and the loader's tests (the format, the header, the route's faces) - nvfp4: e4m3_bits exact on all 256 fp8 codes (the field form for normals, the value table for subnormals, the NaN cod - nvfp4: the family's check reads modelopt (NVFP4 group 16 refused otherwise), the Swift checkpoint listed in MODELS - nvfp4: the FP4 tables in the kernel's tile order (the K block contiguous, N tiles outer) and the decode gathering in - nvfp4: the MoE buffers at the engine's flat index (row * slots + slot, the qmm kernels' dest), count read as the pro - nvfp4: the b16 matmul reading whole BK blocks a slice (the split by the weight's shape, never the row count) and the - nvfp4: the loader's BF16 faces and the expert stack calling the helpers by their names (b16_from_rows, stack(proj)) - nvfp4: the tiny checkpoint shipping the n-gram constants the loader checks (I64 like the real one, and a table of th - nvfp4: the docs say what the engine reads (README's refusals and the Spark list, the runbook's) and what the real we - nvfp4: the CPU checks pin the NVFP4 route (the family's check on a ModelOpt config and its block size of 16, the Swi - nvfp4: the tiny fixture mirrors the published naming and the engine's widths
1 parent f925559 commit 76ad10f

11 files changed

Lines changed: 1692 additions & 30 deletions

File tree

‎src/tensorfold/families/qwen4_exp/__init__.py‎

Lines changed: 19 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -9,8 +9,9 @@
99
TITLE = "Qwen3.8 Flash Next"
1010
LANES = True
1111
# 4-bit weights in groups of 32 (what the fused kernels read), with the checkpoint's MTP head kept
12-
MODELS = ("Vontra/Qwen3.8-Flash-Next-MLX-4bit-MTP", "turboderp/Qwen3.8-Flash-Next-exl3")
13-
QUANT_METHODS = {"cuda": ("mlx", "exl3")} # the CUDA engine reads MLX affine 4-bit and EXL3 packs
12+
MODELS = ("Vontra/Qwen3.8-Flash-Next-MLX-4bit-MTP", "turboderp/Qwen3.8-Flash-Next-exl3",
13+
"ukisai/Swift-1.5-Qwen3.8-Flash-Next-NVFP4")
14+
QUANT_METHODS = {"cuda": ("mlx", "exl3", "modelopt")} # MLX affine 4-bit, EXL3 packs and NVFP4 (ModelOpt)
1415
EXL3_VARIANT = "any" # every EXL3 codebook and width (tensorfold.families.EXL3_VARIANT_ANY)
1516
KERNEL_PACKAGE = "tensorfold.kernels.qwen.flash_next.v1"
1617
KERNEL_VERSION = "v1"
@@ -30,14 +31,27 @@ def has_mtp(model_dir: Path) -> bool:
3031

3132

3233
def check(model_dir: Path) -> None:
33-
from tensorfold.families import EXL3_QUANT, quant_method, quantization, read_config
34+
from tensorfold.families import (EXL3_QUANT, OWN_MODEL_HELP, describe_quantization, quant_method,
35+
quantization, read_config)
3436

3537
config = read_config(model_dir)
3638
if quant_method(config) == EXL3_QUANT:
3739
# an EXL3 pack (the CUDA engine, any codebook and per-tensor width): only the MTP head to report
3840
if (Path(model_dir) / "model.safetensors.index.json").is_file() and not has_mtp(model_dir):
3941
print("[tensorfold] this EXL3 checkpoint has no MTP head: decoding without MTP drafts", flush=True)
4042
return
43+
if quant_method(config) == "modelopt":
44+
# the CUDA engine's NVFP4 route (the Swift checkpoint): the FP4 block size the kernels read
45+
found = config.get("quantization") or config.get("quantization_config") or {}
46+
groups = found.get("config_groups") or {}
47+
group = int(((groups.get("group_0") or {}).get("weights") or {}).get("group_size", 16))
48+
if str(found.get("quant_algo") or "NVFP4").upper() != "NVFP4" or group != 16:
49+
raise ValueError(f"TensorFold's Flash Next kernels read NVFP4 (ModelOpt FP4) weights in blocks of 16 "
50+
f"({MODELS[-1]}); this checkpoint has " + describe_quantization(config) + f". "
51+
f"{OWN_MODEL_HELP}")
52+
if (Path(model_dir) / "model.safetensors.index.json").is_file() and not has_mtp(model_dir):
53+
print("[tensorfold] this NVFP4 checkpoint has no MTP head: decoding without MTP drafts", flush=True)
54+
return
4155
bits, group = quantization(config)
4256
if (bits, group) != (4, 32):
4357
raise ValueError(f"TensorFold's Flash Next kernels read 4-bit weights in groups of 32; this checkpoint has "
@@ -113,7 +127,8 @@ def kernel_version(model: Any) -> str:
113127
return f"{source}|prompt_attention={','.join(modes)}" + (f"|{prefill}" if prefill else "")
114128

115129

116-
# the CUDA engine's kernels read MLX affine weights of this (bits, group size)
130+
# the CUDA engine's kernels read MLX affine weights of this (bits, group size), or an NVFP4 (modelopt)
131+
# checkpoint: the routed experts in FP4 (the format's own kernels), every other linear BF16
117132
CUDA_QUANTIZATION = (4, 32)
118133
# the KV cache dtypes the CUDA engine can allocate (``--kv-dtype``)
119134
CUDA_KV_DTYPES = ("bf16", "int8", "int4")
Lines changed: 170 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,170 @@
1+
"""The NVFP4 checkpoint's bf16 linears on a row-invariant Triton matmul, and a 4-bit copy for draft-only weights."""
2+
3+
from __future__ import annotations
4+
5+
from dataclasses import dataclass
6+
7+
import torch
8+
9+
HAS_TRITON = True
10+
try:
11+
import triton
12+
import triton.language as tl
13+
except ModuleNotFoundError:
14+
HAS_TRITON = False
15+
16+
BN = 64
17+
BK = 64 # the K block a program reads a step (the split keeps slices whole blocks)
18+
GS = 32 # the MLX group size this module's quantize4 emits
19+
20+
21+
@dataclass
22+
class B16:
23+
"""A BF16 matrix [n, k] as the checkpoint stores it."""
24+
25+
weight: torch.Tensor # [n, k] bf16, contiguous
26+
n: int
27+
k: int
28+
29+
def nbytes(self) -> int:
30+
return self.weight.numel() * self.weight.element_size()
31+
32+
33+
def make_b16(weight: torch.Tensor) -> B16:
34+
w = weight.to(torch.bfloat16).contiguous()
35+
return B16(w, int(w.shape[0]), int(w.shape[1]))
36+
37+
38+
def split_k(n: int, k: int, target: int = 160, bk: int = BK) -> int:
39+
"""K slices by the weight's shape alone: a power of two with whole BK blocks a slice."""
40+
41+
tiles = -(-n // BN)
42+
blocks = k // bk
43+
sk = 1
44+
while sk < 32 and tiles * sk < target and blocks % (sk * 2) == 0 and blocks // (sk * 2) >= 1:
45+
sk *= 2
46+
return sk
47+
48+
49+
if HAS_TRITON:
50+
@triton.jit
51+
def _b16mm(X, W, OUT, PART, M, x_stride,
52+
N: tl.constexpr, K: tl.constexpr, SK: tl.constexpr, BM: tl.constexpr,
53+
BLOCK_N: tl.constexpr, BK: tl.constexpr, F32: tl.constexpr):
54+
"""x [M, K] @ W.T -> [M, N]: K in BK steps in order, a tensor-core dot each, fp32 accumulators."""
55+
56+
pid_n = tl.program_id(1)
57+
pid_s = tl.program_id(2)
58+
rm = tl.program_id(0) * BM + tl.arange(0, BM)
59+
rn = pid_n * BLOCK_N + tl.arange(0, BLOCK_N)
60+
rk = tl.arange(0, BK)
61+
m_ok = rm < M
62+
n_ok = rn < N
63+
KS: tl.constexpr = K // SK
64+
NB: tl.constexpr = KS // BK # whole BK blocks a slice (split_k picks SK for that)
65+
acc = tl.zeros((BM, BLOCK_N), dtype=tl.float32)
66+
for i in range(NB):
67+
k0 = (pid_s * NB + i) * BK
68+
x = tl.load(X + rm[:, None] * x_stride + (k0 + rk)[None, :], mask=m_ok[:, None], other=0.0)
69+
w = tl.load(W + rn[:, None] * K + (k0 + rk)[None, :], mask=n_ok[:, None], other=0.0)
70+
acc = tl.dot(x, tl.trans(w), acc)
71+
out_mask = m_ok[:, None] & n_ok[None, :]
72+
if SK == 1:
73+
tl.store(OUT + rm[:, None] * N + rn[None, :], acc if F32 else acc.to(tl.bfloat16), mask=out_mask)
74+
else:
75+
tl.store(PART + (pid_s * M + rm[:, None]) * N + rn[None, :], acc, mask=out_mask)
76+
77+
@triton.jit
78+
def _reduce(PART, OUT, total, SK: tl.constexpr, BLOCK: tl.constexpr):
79+
offs = tl.program_id(0) * BLOCK + tl.arange(0, BLOCK)
80+
ok = offs < total
81+
acc = tl.load(PART + offs, mask=ok, other=0.0)
82+
for s in tl.static_range(1, SK):
83+
acc = acc + tl.load(PART + s * total + offs, mask=ok, other=0.0)
84+
tl.store(OUT + offs, acc.to(tl.bfloat16), mask=ok)
85+
86+
87+
def matmul(x: torch.Tensor, b: B16, *, out: torch.Tensor | None = None, f32: bool = False,
88+
sk: int | None = None, num_warps: int = 4, num_stages: int = 3,
89+
block_n: int = BN, bk: int = BK) -> torch.Tensor:
90+
"""x [M, K] bf16 @ b.T -> [M, N] bf16 (or fp32 sums), K slices summed in slice order."""
91+
92+
if not HAS_TRITON:
93+
raise RuntimeError("the BF16 matmul needs Triton (the CUDA engine's environment)")
94+
m, k = x.shape
95+
if k != b.k or x.stride(1) != 1:
96+
raise ValueError(f"b16 matmul: x {tuple(x.shape)} does not match K={b.k}")
97+
if k % bk:
98+
raise ValueError(f"b16 matmul: K {k} is not a multiple of the K block {bk}")
99+
sk = int(sk) if sk else split_k(b.n, b.k, bk=bk)
100+
if out is None:
101+
out = torch.empty((m, b.n), dtype=torch.float32 if f32 else torch.bfloat16, device=x.device)
102+
elif out.shape != (m, b.n) or not out.is_contiguous() or (out.dtype == torch.float32) != f32:
103+
raise ValueError(f"b16 matmul: out {tuple(out.shape)} {out.dtype} must be a contiguous ({m}, {b.n}), "
104+
f"dtype matching f32={f32}")
105+
part = torch.empty((sk, m, b.n), dtype=torch.float32, device=x.device) if sk > 1 else out
106+
bm = 128 if m > 128 else 16
107+
grid = (triton.cdiv(m, bm), -(-b.n // block_n), sk)
108+
_b16mm[grid](x, b.weight, out, part, m, x.stride(0), N=b.n, K=k, SK=sk, BM=bm,
109+
BLOCK_N=block_n, BK=bk, F32=f32, num_warps=num_warps, num_stages=num_stages)
110+
if sk > 1:
111+
if f32:
112+
out.copy_(part[0])
113+
for s in range(1, sk):
114+
out += part[s]
115+
else:
116+
total = m * b.n
117+
_reduce[(triton.cdiv(total, 1024),)](part, out, total, SK=sk, BLOCK=1024, num_warps=4)
118+
return out
119+
120+
121+
def quantize4(w: torch.Tensor, chunk: int = 8192, out: str = "q4"):
122+
"""bf16 (N, K) -> MLX affine 4-bit in groups of 32, for weights that only draft (the MTP head's lm_head copy)."""
123+
124+
from . import qmm
125+
126+
n, k = w.shape
127+
words, scales, biases = [], [], []
128+
for lo in range(0, n, chunk):
129+
part = w[lo:lo + chunk].float()
130+
g = part.reshape(-1, k // GS, GS)
131+
mn = g.min(dim=-1, keepdim=True).values
132+
mx = g.max(dim=-1, keepdim=True).values
133+
s = ((mx - mn) / 15.0).clamp(min=1e-8)
134+
q = ((g - mn) / s).round().clamp(0, 15).to(torch.uint8).reshape(-1, k)
135+
packed = (q[:, 1::2] << 4 | q[:, 0::2]).view(torch.uint32) # (rows, K/8)
136+
words.append(packed)
137+
scales.append(s.reshape(-1, k // GS).to(torch.bfloat16))
138+
biases.append(mn.reshape(-1, k // GS).to(torch.bfloat16))
139+
return qmm.make_q4(torch.cat(words), torch.cat(scales), torch.cat(biases))
140+
141+
142+
def b16_from_rows(rows: torch.Tensor) -> "_Routed":
143+
"""A [n, k] bf16 matrix with the ``qmm.matmul`` face (a ``kernel`` tag)."""
144+
145+
b = make_b16(rows)
146+
return _Routed(b)
147+
148+
149+
class _Routed:
150+
"""A bf16 matrix tagged ``kernel == 'b16'`` so ``forward._mm`` routes it here; ``stack`` joins rows."""
151+
152+
kernel = "b16"
153+
154+
def __init__(self, b: B16) -> None:
155+
self.b = b
156+
self.n, self.k = b.n, b.k
157+
158+
@property
159+
def weight(self) -> torch.Tensor:
160+
return self.b.weight
161+
162+
def nbytes(self) -> int:
163+
return self.b.nbytes()
164+
165+
166+
def stack_b16(parts: list) -> _Routed:
167+
"""Rows of several _Routed of the same K stacked in order (the hyper-connection's down + inject)."""
168+
169+
rows = [p.b.weight if isinstance(p, _Routed) else p.weight for p in parts]
170+
return b16_from_rows(torch.cat(rows, dim=0))

‎src/tensorfold/families/qwen4_exp/cuda/forward.py‎

Lines changed: 27 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -14,8 +14,8 @@
1414

1515
from . import attention as attn_mod
1616
from . import gdn as gdn_mod
17-
from . import gdn_io, glue, qmm
18-
from .state import ATT_ROWS, CAND, Buffers, State
17+
from . import bf16, gdn_io, glue, nvfp4_moe, qmm
18+
from .state import ATT_ROWS, CAND, Buffers, State, _MoECfg
1919
from .weights import HC, LayerW, Weights
2020

2121

@@ -29,14 +29,16 @@ def _gather(w: Weights, b: Buffers, part: torch.Tensor, flat: torch.Tensor, R: i
2929

3030

3131
def _mm(x: torch.Tensor, q: qmm.Q4, xs: torch.Tensor, out: torch.Tensor, b: Buffers, **kw) -> torch.Tensor:
32+
if getattr(q, "kernel", "qmm") == "b16": # an NVFP4 checkpoint's BF16 linear (non-experts)
33+
return bf16.matmul(x, q, out=out)
3234
if not isinstance(q, qmm.Q4): # an EXL3 pack's matrix (``exl3_mm``): prompts on its prompt path
3335
return q.prefill(x, out) if b.prefill else q(x, out)
3436
mm = qmm.prefill_matmul if b.prefill else qmm.matmul
3537
return mm(x, q, xs, out=out, part=b.part, **kw)
3638

3739

3840
def _embed(w: Weights, ids: torch.Tensor, copies: int, out: torch.Tensor) -> torch.Tensor:
39-
if len(w.embed) == 1: # an EXL3 checkpoint's unquantized embedding
41+
if len(w.embed) == 1: # an unquantized embedding: an EXL3 pack's, or an NVFP4 checkpoint's BF16 table
4042
from .exl3_mm import embed
4143

4244
return embed(ids, w.embed[0], w.cfg.hidden, copies, out)
@@ -57,12 +59,26 @@ def hc_block(hc: HC, b: Buffers, R: int, eps: float, streams: int, low: int, mod
5759
def _readout(hc: HC, b: Buffers, h: torch.Tensor, R: int, eps: float, streams: int, low: int, inject) -> None:
5860
"""normed streams -> down -> SiLU / inject -> up -> mix: b.mixed [R, D] and its group sums."""
5961

60-
if R <= FUSED_ROWS and not b.prefill and isinstance(hc.down, qmm.Q4):
62+
if getattr(hc.down, "kernel", "qmm") == "b16": # an NVFP4 checkpoint: the same steps, bf16 kernels
63+
_readout_b16(hc, b, h, R, eps, streams, low, inject)
64+
elif R <= FUSED_ROWS and not b.prefill and isinstance(hc.down, qmm.Q4):
6165
_readout_fused(hc, b, h, R, eps, streams, low, inject)
6266
else:
6367
_readout_plain(hc, b, h, R, eps, streams, low, inject)
6468

6569

70+
def _readout_b16(hc: HC, b: Buffers, h: torch.Tensor, R: int, eps: float, streams: int, low: int, inject) -> None:
71+
"""The read-out through the BF16 kernels: norm, bf16 down, the activation and inject gates (with the
72+
slice sums fused), bf16 up, the mix — the plain path's steps, the same bits per row."""
73+
74+
glue.hc_normed(h[:R], b.pss[:R], hc.scale, b.normed[:R], b.xs_normed[:R], streams, eps)
75+
got = bf16.matmul(b.normed[:R], hc.down.b, out=torch.empty((R, hc.down.n), dtype=torch.float32,
76+
device=h.device), f32=True)
77+
glue.hc_act(got, b.act[:R], b.xs_act[:R], inject, streams, low)
78+
_mm(b.act[:R], hc.up, b.xs_act[:R], b.up[:R], b)
79+
glue.hc_mix(b.up[:R], b.normed[:R], b.mixed[:R], b.xs_mixed[:R], streams)
80+
81+
6682
def _readout_fused(hc: HC, b: Buffers, h: torch.Tensor, R: int, eps: float, streams: int, low: int, inject) -> None:
6783
"""The norm inside the down projection, the mix inside the up projection."""
6884

@@ -135,7 +151,7 @@ def _prefill_chain(g, st: State, li: int, b: Buffers, a0: int, a1: int, c) -> No
135151
def _out_proj(w: Weights, b: Buffers, x: torch.Tensor, q: qmm.Q4, xs: torch.Tensor, R: int):
136152
"""A block's output projection: (1, bf16 branch) on one GPU; (3, gathered fp32 partials) across ranks."""
137153

138-
if not isinstance(q, qmm.Q4): # an EXL3 pack (one GPU): the bf16 branch
154+
if not isinstance(q, qmm.Q4): # an NVFP4 checkpoint's BF16 face, or an EXL3 pack (one GPU): the bf16 branch
139155
return 1, _mm(x, q, xs, b.branch[:R], b)
140156
if w.comm is None:
141157
got = _mm(x, q, xs, b.branch[:R], b, reduce=False)
@@ -235,9 +251,13 @@ def moe_block(layer: LayerW, w: Weights, b: Buffers, R: int) -> tuple:
235251
"""Routed experts + the shared expert. Returns the pending write-back: (2, slots y, weights) on one GPU, (3, gathered fp32 partials, None) across ranks."""
236252

237253
m = layer.moe
238-
if w.x3 is not None: # an EXL3 pack: each expert at its own width, one GPU
254+
if getattr(m.experts, "kernel", "qmm") == "nvfp4": # an NVFP4 checkpoint: the FP4 experts
255+
buf = b.moe
256+
nvfp4_moe.moe(b.mixed[:R], b.xs_mixed[:R], m.router, m.experts, buf, _MoECfg(w.cfg))
257+
elif w.x3 is not None: # an EXL3 pack: each expert at its own width, one GPU
239258
return _exl3_moe(m, w, b, R)
240-
buf = moe_mod.moe(b.mixed[:R], m.router, m.experts, b.moe, w.cfg.top_k, w.cfg.experts)
259+
else:
260+
buf = moe_mod.moe(b.mixed[:R], m.router, m.experts, b.moe, w.cfg.top_k, w.cfg.experts)
241261
if w.comm is None:
242262
return 2, buf.y[:R], buf.wts[:R]
243263
glue.moe_partial(buf.y[:R], buf.wts[:R], b.part_moe, R)

0 commit comments

Comments
 (0)