Skip to content

Commit f925559

Browse files
committed
feat: impossible checkpoints keep the others, NVFP4 checkpoints on CUDA, expert-aligned prompt tiles
- Checkpoint copies and snapshot loads check again before every eviction, and a resumed prompt stops holding the stored prefix it copied; the memory tests pin host RAM, so they pass on any Mac (#74). - #70's 64 GB M5 Pro measurements go into the README and recipes, labelled as 0.3.5.1. - On M1-M4, Flash Next's prompt expert gathers take row tiles that never straddle experts (the scheduling idea of ml-explore/mlx#4567), same bits. - A reader for ModelOpt and compressed-tensors NVFP4, FP8 and MXFP8 weights, W4A16 and W8A16 lane matmuls with exact weights, and Qwen3.8-27B on ModelOpt NVFP4 checkpoints. Fixes #70.
1 parent af9639f commit f925559

25 files changed

Lines changed: 1624 additions & 83 deletions

‎src/tensorfold/cuda/capacity.py‎

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -11,8 +11,8 @@
1111
from typing import Callable
1212

1313
GIB = 1024**3
14-
SIZES = {"U8": 1, "I8": 1, "BOOL": 1, "BF16": 2, "F16": 2, "I16": 2, "U16": 2,
15-
"U32": 4, "I32": 4, "F32": 4, "I64": 8, "U64": 8, "F64": 8}
14+
SIZES = {"U8": 1, "I8": 1, "BOOL": 1, "F8_E4M3": 1, "F8_E5M2": 1, "F8_E8M0": 1, "BF16": 2, "F16": 2, "I16": 2,
15+
"U16": 2, "U32": 4, "I32": 4, "F32": 4, "I64": 8, "U64": 8, "F64": 8}
1616

1717

1818
@dataclass(frozen=True)

‎src/tensorfold/cuda/kernels/qmm.cpp‎

Lines changed: 23 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -5,6 +5,8 @@ void qmm_cuda(const at::Tensor&, const at::Tensor&, const at::Tensor&, const at:
55
at::Tensor&, const at::Tensor&, int, int, int, int, bool, bool);
66
void qmm_prefill_cuda(const at::Tensor&, const at::Tensor&, const at::Tensor&, const at::Tensor&, at::Tensor&, int,
77
int, bool, int);
8+
void qmm_prefill8w_cuda(const at::Tensor&, const at::Tensor&, const at::Tensor&, const at::Tensor&, at::Tensor&, int,
9+
int, bool, int);
810
void qmm_prefill8_cuda(const at::Tensor&, const at::Tensor&, const at::Tensor&, const at::Tensor&, const at::Tensor&,
911
const at::Tensor&, at::Tensor&, int, int, bool, int);
1012

@@ -88,8 +90,29 @@ void qmm_prefill8(const at::Tensor& x8, const at::Tensor& xs, const at::Tensor&
8890
static_cast<int>(tile));
8991
}
9092

93+
// Prefill in FP8 over e4m3 weight bytes (fragment order): x8 and a from ``quantize_rows``, a bf16 scale per (gs, column).
94+
void qmm_prefill8w(const at::Tensor& x8, const at::Tensor& a, const at::Tensor& w8, const at::Tensor& scales,
95+
at::Tensor& out, int64_t n, int64_t gs, bool f32, int64_t tile) {
96+
TORCH_CHECK(tile >= 0 && tile <= 2, "tile 0-2");
97+
TORCH_CHECK(gs == 32 || gs == 64, "groups of 32 or 64 inputs");
98+
TORCH_CHECK(x8.is_cuda() && x8.scalar_type() == at::kByte && x8.dim() == 2 && x8.is_contiguous() &&
99+
x8.size(0) >= 1, "x8: (M, K) e4m3 bytes, contiguous");
100+
const int64_t m = x8.size(0), k = x8.size(1);
101+
TORCH_CHECK(k % 64 == 0 && n % 128 == 0, "K a multiple of 64 and n of 128");
102+
TORCH_CHECK(a.is_cuda() && a.is_contiguous() && a.scalar_type() == at::kFloat && a.numel() == m, "a: (M,) fp32");
103+
TORCH_CHECK(w8.is_cuda() && w8.is_contiguous() && w8.scalar_type() == at::kByte && w8.numel() == n * k,
104+
"staged weight: n * K e4m3 bytes");
105+
TORCH_CHECK(scales.is_cuda() && scales.is_contiguous() && scales.scalar_type() == at::kBFloat16 &&
106+
scales.size(0) == k / gs && scales.size(1) == n, "scales: (K / gs, n) bf16");
107+
TORCH_CHECK(out.is_cuda() && out.is_contiguous() && out.size(0) == m && out.size(1) == n &&
108+
out.scalar_type() == (f32 ? at::kFloat : at::kBFloat16), "out: (M, n)");
109+
c10::cuda::CUDAGuard guard(x8.device());
110+
qmm_prefill8w_cuda(x8, a, w8, scales, out, static_cast<int>(n), static_cast<int>(gs), f32, static_cast<int>(tile));
111+
}
112+
91113
PYBIND11_MODULE(TORCH_EXTENSION_NAME, m) {
92114
m.def("qmm", &qmm);
93115
m.def("qmm_prefill", &qmm_prefill);
94116
m.def("qmm_prefill8", &qmm_prefill8);
117+
m.def("qmm_prefill8w", &qmm_prefill8w);
95118
}

‎src/tensorfold/cuda/kernels/qmm_prefill8.cu‎

Lines changed: 39 additions & 14 deletions
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,5 @@
1-
// FP8 prefill on exact e4m3 weights: acc = fma(P, s, acc) per group, bias MMAs, row scale; no row affects another.
1+
// FP8 prefill on exact e4m3 weights (4-bit words, or staged e4m3 bytes with W8): acc = fma(P, s, acc) per group,
2+
// bias MMAs for 4-bit words, row scale; no row affects another.
23

34
#include <ATen/ATen.h>
45
#include <algorithm>
@@ -44,7 +45,7 @@ __device__ __forceinline__ void weights8(uint32_t w, uint32_t& b0, uint32_t& b1)
4445
b1 = __byte_perm(e4m3_pair(w, 8), e4m3_pair(w, 12), 0x5410);
4546
}
4647

47-
template <int GS, int BM, int BN, int WM, int WN, int STAGES>
48+
template <int GS, int BM, int BN, int WM, int WN, int STAGES, bool W8 = false>
4849
struct Tile {
4950
static constexpr int THREADS = WM * WN * 32;
5051
static constexpr int MT = BM / WM / 16;
@@ -54,7 +55,7 @@ struct Tile {
5455
static constexpr int CHUNKS = ROW / 16;
5556
static constexpr int PER128 = 128 / ROW; // rows in 128 bytes of shared memory
5657
static constexpr int X = BM * ROW;
57-
static constexpr int W = BN * GS / 2;
58+
static constexpr int W = W8 ? BN * GS : BN * GS / 2; // e4m3 bytes, or 4-bit words
5859
static constexpr int S = BN * 2;
5960
static constexpr int STAGE = X + W + S;
6061
static constexpr int SMEM = STAGES * STAGE;
@@ -64,12 +65,12 @@ struct Tile {
6465
template <int CHUNKS, int PER128>
6566
__device__ __forceinline__ int swz8(int r, int c) { return c ^ ((r / PER128) % CHUNKS); }
6667

67-
template <int GS, int BM, int BN, int WM, int WN, int STAGES, bool F32>
68+
template <int GS, int BM, int BN, int WM, int WN, int STAGES, bool F32, bool W8>
6869
__global__ void __launch_bounds__(WM * WN * 32, 2) prefill8_kernel(
6970
const uint8_t* __restrict__ x, const __nv_bfloat16* __restrict__ xs, const float* __restrict__ scale,
7071
const uint32_t* __restrict__ w, const __nv_bfloat16* __restrict__ scales,
7172
const __nv_bfloat16* __restrict__ biases, void* __restrict__ out, int M, int N, int K, int npad, int group) {
72-
using T = Tile<GS, BM, BN, WM, WN, STAGES>;
73+
using T = Tile<GS, BM, BN, WM, WN, STAGES, W8>;
7374
extern __shared__ __align__(128) unsigned char buf[];
7475
const int tid = threadIdx.x, lane = tid & 31, warp = tid >> 5;
7576
const int wm = warp / WN, wn = warp % WN;
@@ -87,7 +88,7 @@ __global__ void __launch_bounds__(WM * WN * 32, 2) prefill8_kernel(
8788
x + static_cast<size_t>(min(m0 + r, M - 1)) * K + g * GS + ch * 16, m0 + r < M);
8889
}
8990
unsigned char* pw = p + T::X;
90-
constexpr int TILE_BYTES = 64 * GS / 2;
91+
constexpr int TILE_BYTES = W8 ? 64 * GS : 64 * GS / 2;
9192
#pragma unroll
9293
for (int c = tid; c < T::W / 16; c += T::THREADS) {
9394
const int t = c / (TILE_BYTES / 16), off = c % (TILE_BYTES / 16);
@@ -141,7 +142,13 @@ __global__ void __launch_bounds__(WM * WN * 32, 2) prefill8_kernel(
141142
#pragma unroll
142143
for (int ks = 0; ks < T::KS; ++ks) {
143144
uint32_t b0, b1;
144-
weights8(pw[wbase + j * 32 * T::KS + ks], b0, b1);
145+
if constexpr (W8) {
146+
const uint2 b = reinterpret_cast<const uint2*>(pw)[wbase + j * 32 * T::KS + ks];
147+
b0 = b.x;
148+
b1 = b.y;
149+
} else {
150+
weights8(pw[wbase + j * 32 * T::KS + ks], b0, b1);
151+
}
145152
#pragma unroll
146153
for (int i = 0; i < T::MT; ++i) {
147154
if (ks == 0) mma8z(cur[i], a[ks][i], b0, b1);
@@ -167,7 +174,7 @@ __global__ void __launch_bounds__(WM * WN * 32, 2) prefill8_kernel(
167174
}
168175
wait<0>();
169176
// bias term: acc += xs (bf16, (M, KG)) times biases (bf16, (KG, npad)) as k16 MMAs over the groups (zeros past KG)
170-
{
177+
if constexpr (!W8) {
171178
const int c = lane & 3, gr = lane >> 2;
172179
const unsigned short* xb = reinterpret_cast<const unsigned short*>(xs);
173180
const unsigned short* bb = reinterpret_cast<const unsigned short*>(biases);
@@ -226,12 +233,12 @@ __global__ void __launch_bounds__(WM * WN * 32, 2) prefill8_kernel(
226233
}
227234
}
228235

229-
template <int GS, int BM, int BN, int WM, int WN, int STAGES, bool F32>
236+
template <int GS, int BM, int BN, int WM, int WN, int STAGES, bool F32, bool W8 = false>
230237
void launch(const at::Tensor& x, const at::Tensor& xs, const at::Tensor& scale, const at::Tensor& w,
231238
const at::Tensor& scales, const at::Tensor& biases, at::Tensor& out, int N) {
232-
using T = Tile<GS, BM, BN, WM, WN, STAGES>;
239+
using T = Tile<GS, BM, BN, WM, WN, STAGES, W8>;
233240
const int M = x.size(0), K = x.size(1);
234-
auto kernel = prefill8_kernel<GS, BM, BN, WM, WN, STAGES, F32>;
241+
auto kernel = prefill8_kernel<GS, BM, BN, WM, WN, STAGES, F32, W8>;
235242
static bool configured = false;
236243
if (!configured) {
237244
cudaFuncSetAttribute(kernel, cudaFuncAttributeMaxDynamicSharedMemorySize, T::SMEM);
@@ -240,9 +247,10 @@ void launch(const at::Tensor& x, const at::Tensor& xs, const at::Tensor& scale,
240247
const int rows_t = (M + BM - 1) / BM;
241248
const int group = std::max(1, std::min(rows_t, static_cast<int>((12LL << 20) / (static_cast<long long>(BM) * K))));
242249
kernel<<<rows_t * ((N + BN - 1) / BN), T::THREADS, T::SMEM, at::cuda::getCurrentCUDAStream()>>>(
243-
reinterpret_cast<const uint8_t*>(x.data_ptr()), reinterpret_cast<const __nv_bfloat16*>(xs.data_ptr()),
244-
scale.data_ptr<float>(), reinterpret_cast<const uint32_t*>(w.data_ptr()),
245-
reinterpret_cast<const __nv_bfloat16*>(scales.data_ptr()), reinterpret_cast<const __nv_bfloat16*>(biases.data_ptr()),
250+
reinterpret_cast<const uint8_t*>(x.data_ptr()),
251+
W8 ? nullptr : reinterpret_cast<const __nv_bfloat16*>(xs.data_ptr()), scale.data_ptr<float>(),
252+
reinterpret_cast<const uint32_t*>(w.data_ptr()), reinterpret_cast<const __nv_bfloat16*>(scales.data_ptr()),
253+
W8 ? nullptr : reinterpret_cast<const __nv_bfloat16*>(biases.data_ptr()),
246254
out.data_ptr(), M, N, K, static_cast<int>(scales.size(1)), group);
247255
C10_CUDA_KERNEL_LAUNCH_CHECK();
248256
}
@@ -259,10 +267,27 @@ void dispatch(int tile, const at::Tensor& x, const at::Tensor& xs, const at::Ten
259267

260268
} // namespace
261269

270+
template <int GS, bool F32>
271+
void dispatch_w8(int tile, const at::Tensor& x, const at::Tensor& a, const at::Tensor& w, const at::Tensor& s,
272+
at::Tensor& out, int N) {
273+
switch (tile) {
274+
case 1: launch<GS, 64, 128, 1, 4, 4, F32, true>(x, x, a, w, s, s, out, N); break;
275+
case 2: launch<GS, 128, 128, 2, 4, 3, F32, true>(x, x, a, w, s, s, out, N); break;
276+
default: launch<GS, 128, 128, 2, 2, 3, F32, true>(x, x, a, w, s, s, out, N); break;
277+
}
278+
}
279+
262280
// ``tile`` (0: 128x128, four 64x64 warps; 1: 64x128; 2: 128x128, eight 64x32 warps) never changes a row's bits.
263281
void qmm_prefill8_cuda(const at::Tensor& x, const at::Tensor& xs, const at::Tensor& a, const at::Tensor& w,
264282
const at::Tensor& scales, const at::Tensor& biases, at::Tensor& out, int N, int gs, bool f32,
265283
int tile) {
266284
if (gs == 64) { if (f32) dispatch<64, true>(tile, x, xs, a, w, scales, biases, out, N); else dispatch<64, false>(tile, x, xs, a, w, scales, biases, out, N); }
267285
else { if (f32) dispatch<32, true>(tile, x, xs, a, w, scales, biases, out, N); else dispatch<32, false>(tile, x, xs, a, w, scales, biases, out, N); }
268286
}
287+
288+
// The same over e4m3 weight bytes in fragment order with a bf16 scale per (group of 32 or 64 inputs, column), no bias.
289+
void qmm_prefill8w_cuda(const at::Tensor& x, const at::Tensor& a, const at::Tensor& w, const at::Tensor& scales,
290+
at::Tensor& out, int N, int gs, bool f32, int tile) {
291+
if (gs == 32) { if (f32) dispatch_w8<32, true>(tile, x, a, w, scales, out, N); else dispatch_w8<32, false>(tile, x, a, w, scales, out, N); }
292+
else { if (f32) dispatch_w8<64, true>(tile, x, a, w, scales, out, N); else dispatch_w8<64, false>(tile, x, a, w, scales, out, N); }
293+
}
Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1 @@
1+
"""NVFP4 and FP8 checkpoints (ModelOpt, compressed-tensors) on CUDA: the reader, row-invariant kernels, prompt staging."""
Lines changed: 103 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,103 @@
1+
"""NVFP4 / FP8 / MXFP8 checkpoints (ModelOpt, compressed-tensors): each linear's scheme, and a numpy dequantizer."""
2+
3+
from __future__ import annotations
4+
5+
import json
6+
from pathlib import Path
7+
8+
import numpy as np
9+
10+
METHODS = ("modelopt", "compressed-tensors")
11+
E2M1 = np.array([0.0, 0.5, 1.0, 1.5, 2.0, 3.0, 4.0, 6.0, -0.0, -0.5, -1.0, -1.5, -2.0, -3.0, -4.0, -6.0],
12+
dtype=np.float32)
13+
SCHEMES = ("nvfp4", "fp8", "mxfp8", "bf16")
14+
15+
16+
def config_block(config: dict) -> dict | None:
17+
"""The quantization block of config.json (top level or text config) when it names ModelOpt or compressed-tensors."""
18+
19+
for source in (config, config.get("text_config") or {}):
20+
found = source.get("quantization_config")
21+
if isinstance(found, dict) and str(found.get("quant_method", "")).lower() in METHODS:
22+
return found
23+
return None
24+
25+
26+
def require_config(config: dict, *, where: str, tested: str, help: str) -> None:
27+
"""Refuse a ModelOpt / compressed-tensors checkpoint whose weights are not NVFP4, FP8 or MXFP8."""
28+
29+
block = config_block(config) or {}
30+
method = str(block.get("quant_method", "")).lower()
31+
formats = {str(block.get("format", "") or "")}
32+
groups = block.get("config_groups") or {}
33+
for group in groups.values():
34+
weights = group.get("weights") or {}
35+
formats.add(str(group.get("format", "") or ""))
36+
bits, kind = weights.get("num_bits"), str(weights.get("type", "float"))
37+
if kind != "float" or bits not in (4, 8):
38+
raise ValueError(f"this {method} checkpoint stores {bits}-bit {kind} weights; {where} reads NVFP4 and FP8 "
39+
f"weights of this format. Tested checkpoints: {tested}. {help}")
40+
bad = {f for f in formats if f and f not in ("nvfp4-pack-quantized", "float-quantized", "naive-quantized",
41+
"mixed-precision")}
42+
if bad:
43+
raise ValueError(f"this {method} checkpoint's weights are stored as {', '.join(sorted(bad))}; {where} reads "
44+
f"NVFP4 and FP8 weights. Tested checkpoints: {tested}. {help}")
45+
46+
47+
def is_quantized(model_dir: str | Path) -> bool:
48+
"""Whether config.json names ModelOpt or compressed-tensors quantization."""
49+
50+
config = Path(model_dir) / "config.json"
51+
return config.is_file() and config_block(json.loads(config.read_text())) is not None
52+
53+
54+
def scheme(tensors: dict[str, tuple[str, list[int]]]) -> str:
55+
"""One linear's scheme from its tensors' (dtype, shape) by suffix: nvfp4, fp8, mxfp8 or bf16."""
56+
57+
w = tensors.get("weight") or tensors.get("weight_packed")
58+
s = tensors.get("weight_scale")
59+
if w is None:
60+
raise ValueError("a linear without weight or weight_packed")
61+
if w[0] == "U8" and s is not None and s[0] == "F8_E4M3":
62+
return "nvfp4"
63+
if w[0] == "F8_E4M3" and s is not None and s[0] == "U8":
64+
return "mxfp8"
65+
if w[0] == "F8_E4M3":
66+
return "fp8"
67+
if w[0] in ("BF16", "F16", "F32"):
68+
return "bf16"
69+
raise ValueError(f"unknown weight storage {w[0]} with scale {s[0] if s else None}")
70+
71+
72+
def e4m3(bits: np.ndarray) -> np.ndarray:
73+
"""e4m3fn bytes as float32 (no infinities; 0x7f and 0xff are NaN)."""
74+
75+
b = bits.astype(np.int32)
76+
sign = np.where(b & 0x80, -1.0, 1.0).astype(np.float32)
77+
exp, man = (b >> 3) & 0xF, b & 0x7
78+
value = np.where(exp == 0, man / 8.0 * 2.0 ** -6, (1 + man / 8.0) * 2.0 ** (exp - 7.0)).astype(np.float32)
79+
return np.where((b & 0x7F) == 0x7F, np.float32(np.nan), sign * value)
80+
81+
82+
def e8m0(bits: np.ndarray) -> np.ndarray:
83+
"""e8m0 exponent bytes as float32 powers of two (255 is NaN)."""
84+
85+
b = bits.astype(np.int32)
86+
return np.where(b == 255, np.float32(np.nan), np.ldexp(np.float32(1.0), b - 127).astype(np.float32))
87+
88+
89+
def dequant(scheme_name: str, weight: np.ndarray, scale: np.ndarray | None = None, global_scale: float = 1.0,
90+
*, reciprocal_global: bool = False) -> np.ndarray:
91+
"""[N, K] float32 of one stored weight: e2m1 pairs with e4m3 per 16 x global, e4m3 x scale, or e4m3 x e8m0 per 32."""
92+
93+
if scheme_name == "nvfp4":
94+
n, half = weight.shape
95+
codes = np.empty((n, 2 * half), dtype=np.uint8)
96+
codes[:, 0::2], codes[:, 1::2] = weight & 0xF, weight >> 4
97+
g = 1.0 / global_scale if reciprocal_global else global_scale
98+
return E2M1[codes] * np.repeat(e4m3(scale), 16, axis=1) * np.float32(g)
99+
if scheme_name == "fp8":
100+
return e4m3(weight) * np.float32(np.asarray(scale, dtype=np.float32).reshape(-1)[0])
101+
if scheme_name == "mxfp8":
102+
return e4m3(weight) * np.repeat(e8m0(scale), 32, axis=1)
103+
return weight.astype(np.float32)

0 commit comments

Comments
 (0)