Skip to content
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
12 changes: 12 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,16 @@ Each release's page on GitHub has its notes and measurements. See [the 1.0.0 rel

## Unreleased

- CUDA: `TF_DSPINE_WINDOW=N` (16 to 8,192, opt-in) narrows a Qwen3.8-27B DSpine drafter's sliding window to N rows without editing the checkpoint; a value outside the block size and the checkpoint's own window is refused when the drafter opens, and unset keeps the checkpoint's window. Drafts are verified, so replies are unchanged (#2705, after #2633). Thanks to @jschmied.

- Metal: Spark2.5's and Llama's bf16 decode matvec kernels come from one source, with the same compiled code; Qwen3.8-27B saved prompt states on Metal are recomputed once after upgrading (#2792, part of #2251). Thanks to @jschmied.

- Metal: the image towers' and Spark2.5's and Llama's prompt GEMMs share one `gemm_nax` kernel macro, with the same preprocessed source; Qwen3.8-27B saved prompt states on Metal are recomputed once after upgrading (#2787, part of #2251). Thanks to @jschmied.

- GLM-5.3-Flash on Metal: the TP2 sparse-attention and KDA-rows kernels are the full kernels' templates at 32 heads, with the same compiled code; saved GLM prompt states on Metal are recomputed once after upgrading (#2786, part of #2251). Thanks to @jschmied.

- Metal: Qwen 3.5, LFM2-MoE, MiniMax-M3 (with its DFlash2 and DSpark drafters), Step-5 and Spark-X read MLX affine modules through one core reader, `core/quant/mlx_affine.zig`, and LFM3 takes its modules' stored shapes from it while keeping its own checks; loads are unchanged, and a module the reader refuses now reports `UnexpectedAffineTensor` and is named in the log (#2583, part of #2460). Thanks to @jschmied.

## 1.2.7

- GLM-5.3-Flash on CUDA: with `TF_GLM_LAYERS=N`, serve's start-up memory check counts the weights by tensor from the shard headers, only those the load reads (the first N layers, the MTP layer when drafts are on, the embedding, norm and head), where it counted every checkpoint file. A 20-layer thin load of the 163.6 GiB checkpoint now counts 66.6 GiB without drafts. Unset, the count is the files' as before (#2788, fixes #2745). Thanks to @wojo.
Expand Down Expand Up @@ -289,6 +299,8 @@ Each release's page on GitHub has its notes and measurements. See [the 1.0.0 rel
- Lean checks: each new `getenv` that reads a setting outside `platform/environment.zig` is a finding, whether it
names a `TF_*` or `TENSORFOLD_*` setting or takes a name that is not a literal, such as a new wrapper's; the reads
already on main, test files and `test` blocks are not counted (#2521). Thanks to @Bizuayeu.
- HIP on gfx12 under `--policy matrix=on`: Qwen3 dense checkpoints load each layer's gate and up weights interleaved as one weight, and one WMMA product writes silu(gate) x up in its epilogue instead of two products and `tf_silu_mul`, with the same output bytes: Qwen3-Reranker-8B ranks 16 documents in 0.657 to 0.661 s instead of 0.687 to 0.697 s and Qwen3-Embedding-8B embeds 100 short inputs in 0.901 to 0.911 s instead of 0.940 to 0.948 s on a Radeon AI PRO R9700. The kernel contract checks both fused blocks byte for byte against the unfused launches (part of #2245). Thanks to @laudney.
- Nemotron on Macs: the masked prompt shader calls the shared `tf_paged_row` page helper again, so its prompt sources compile; #2322 had used the name #2283 retired the same day (#2548).

- GLM-5.3-Flash on CUDA: with `TF_KV_SHARE=n`, the startup plan sets a slot aside in the prompt cache for each kept
state, so the cache keeps as many states as its slots hold, up to n, and the rest of it goes to the KV pool's pages;
Expand Down
1 change: 1 addition & 0 deletions docs/environment.md
Original file line number Diff line number Diff line change
Expand Up @@ -23,6 +23,7 @@ Diagnostics quote and escape the supplied text so it cannot create another termi
| `TF_Q27_COPY_ROWS` | Whole u32 count; zero disables copied rows; default 48 |
| `TF_Q27_DRAFT_SLOTS` | Whole u32 count, clamped to 1 through the lane stream limit; default 8. DFlash2 can draft for at most the smaller of this count and the admitted streams, and none without a drafter. |
| `TF_MTP_DRAFTS` | Whole u32 count, clamped to 1 through the drafter's window less one; existing depth when unset |
| `TF_DSPINE_WINDOW` | Qwen3.8-27B on CUDA with a DSpine `--drafter`: whole row count 16 through 8192 that narrows the drafter's sliding window; it must be at least the block (16) and at most the checkpoint's own `sliding_window`, else the drafter is refused when it opens; unset or blank keeps the checkpoint's (8192 for tencent/Qwen3.8-27B-DSpine-b16) |
| `TF_DRAFT_NODES` | Whole native-size nonnegative count, capped by the drafter's window; zero disables trees |
| `TF_QMMF_HALF_BELOW` | Whole native-size nonnegative block count; zero disables half tiles; default 96 |
| `TENSORFOLD_PROMPT_CACHE_KEEP_OTHERS` | Exactly `0` or `1`, checked when the CUDA backend starts; default off ([profiles](profiles.md)) |
Expand Down
33 changes: 27 additions & 6 deletions tools/zig/gen_glm_kernels.py
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@

import argparse
import hashlib
import json
import sys
from dataclasses import dataclass, field
from pathlib import Path
Expand Down Expand Up @@ -67,6 +68,7 @@ class Spec:
template: list = field(default_factory=list)
extra: list = field(default_factory=list) # more template instantiations of the same function
threads: int = 0
shares: str = "" # the key whose file holds this template, under that key's function name


def _digest(text: str) -> str:
Expand All @@ -88,9 +90,9 @@ def specs() -> list[Spec]:
out: list[Spec] = []

def plain(key: str, base: str, body: str, header: str, inputs: list[Arg], outputs: list[Arg], template: list,
extra: list | None = None, threads: int = 0) -> None:
extra: list | None = None, threads: int = 0, shares: str = "") -> None:
out.append(Spec(key, f"{base}_{_digest(header + body)}", body, inputs, outputs,
header, template, extra or [], threads=threads))
header, template, extra or [], threads=threads, shares=shares))

qmv_in = [Arg("X", bf, big, 2), Arg("W", u32, big, 2), Arg("S", bf, big, 2), Arg("B", bf, big, 2)]
for k, n in PROJECTIONS:
Expand Down Expand Up @@ -123,7 +125,8 @@ def plain(key: str, base: str, body: str, header: str, inputs: list[Arg], output
Arg("GBB", bf, big, 2), Arg("A", f32, big), Arg("DTB", f32, big), Arg("ST", f32, big, 4),
Arg("ONW", f32, big), Arg("LB", f32, one), Arg("EPS", f32, one)],
[Arg("Y", bf, big, 2), Arg("ST_OUT", f32, big, 4), Arg("CS_OUT", bf, big, 2)],
[("H", heads), ("D", KDA_DIM), ("TAPS", TAPS), ("TY", KD.TY), ("FB", 4), ("GB", 4)], threads=1024)
[("H", heads), ("D", KDA_DIM), ("TAPS", TAPS), ("TY", KD.TY), ("FB", 4), ("GB", 4)], threads=1024,
shares="kda_rows")

def router(rr: int) -> list:
return [("K", HIDDEN), ("NE", EXPERTS), ("RR", rr), ("C", 8 if rr <= 4 else 4), ("NT", M.ROUTER_TG)]
Expand Down Expand Up @@ -176,7 +179,7 @@ def router(rr: int) -> list:
[Arg("queries", bf, big, 3), Arg("keys", bf, big, 2), Arg("indices", i32, big, 2),
Arg("scale", f32, one), Arg("meta", i32, one)],
[Arg("out", bf, big, 3)], "", [("QK_DIM", RANK), ("TOPK", TOPK_KEYS), ("HEADS", heads)],
threads=1024))
threads=1024, shares="sparse_attention"))
return out


Expand All @@ -194,14 +197,27 @@ def rendered(spec: Spec) -> tuple[str, str]:
+ BF16_MATH + strip_comments(text))


def shared(spec: Spec, fname: str, text: str, owner: str) -> tuple[str, str]:
"""(file text with the template alone, named `owner` as its key's kernel is, the key's instantiation of it)."""

head, sep, tail = text.rpartition('\ntemplate [[host_name("')
assert sep and not spec.extra and tail.count("\n") == 1, spec.key
args = owner + "<" + ", ".join(_template_value(v) for _, v in spec.template) + ">"
return head.replace(fname, owner), f'\ntemplate [[host_name("{fname}")]] [[kernel]] decltype({args}) {args};\n'


def names_zig(entries: list[tuple[Spec, str]]) -> str:
owners = {s.key: f for s, f in entries}
lines = ["//! Generated by tools/zig/gen_glm_kernels.py: each kernel's function names and source; do not edit.",
"", "pub const Kernel = struct { key: []const u8, functions: []const [:0]const u8, source: []const u8 };",
"", "pub const all = [_]Kernel{"]
for spec, fname in entries:
names = [fname] + [function_name(spec.name, spec.inputs, spec.outputs, t) for t in spec.extra]
listed = ", ".join(f'"{n}"' for n in names)
lines.append(f' .{{ .key = "{spec.key}", .functions = &.{{ {listed} }}, .source = @embedFile("{spec.key}.metal") }},')
source = f'@embedFile("{spec.shares or spec.key}.metal")'
if spec.shares:
source += " ++ " + json.dumps(shared(spec, fname, rendered(spec)[1], owners[spec.shares])[1])
lines.append(f' .{{ .key = "{spec.key}", .functions = &.{{ {listed} }}, .source = {source} }},')
lines += ["};", ""]
return "\n".join(lines)

Expand All @@ -212,7 +228,12 @@ def main() -> int:
args = ap.parse_args()
py_kernels._stand_in() # the sources only: never import MLX here
entries = [(s, *rendered(s)) for s in specs()]
files = {OUT / f"{s.key}.metal": text for s, _, text in entries}
files = {OUT / f"{s.key}.metal": text for s, _, text in entries if not s.shares}
owners = {s.key: f for s, f, _ in entries}
for s, fname, text in entries:
if s.shares:
alone = shared(s, fname, text, owners[s.shares])[0]
assert files.setdefault(OUT / f"{s.shares}.metal", alone) == alone, f"{s.key}: not {s.shares}'s template"
files[NAMES] = names_zig([(s, f) for s, f, _ in entries])
stale = 0
for path, text in files.items():
Expand Down
46 changes: 46 additions & 0 deletions zig/kernels/metal/core/bf16_matvec.metal
Original file line number Diff line number Diff line change
@@ -0,0 +1,46 @@
// Decode glue's bf16 linear: Y = bf16(X W^T) with fp32 sums, kernels P_matvec_ROWS for 1 to 32 rows of X.
#include <metal_stdlib>
using namespace metal;

struct tf_bf16_mv_args { uint rows, n, k, ldy; };

// Y[r, j] = bf16(sum_i X[r, i] * W[j, i]) over bf16 W [n, k] in fp32 (torch's bf16 linear): a simdgroup a row j.
template <uint ROWS>
inline void tf_bf16_matvec_t(const device bfloat* X, const device bfloat* W, constant tf_bf16_mv_args& a,
device bfloat* Y, uint3 tg, uint sg, uint lane) {
constexpr uint SG = 8;
const uint j = tg.x * SG + sg;
if (j >= a.n) return;
const device bfloat* w = W + (size_t)j * a.k;
float acc[ROWS];
_Pragma("clang loop unroll(full)")
for (uint r = 0; r < ROWS; ++r) acc[r] = 0.0f;
for (uint i = 8 * lane; i < a.k; i += 256) {
const float4 w0 = float4(*(const device bfloat4*)(w + i)), w1 = float4(*(const device bfloat4*)(w + i + 4));
_Pragma("clang loop unroll(full)")
for (uint r = 0; r < ROWS; ++r) {
const device bfloat* x = X + (size_t)r * a.k + i;
acc[r] += dot(w0, float4(*(const device bfloat4*)x)) + dot(w1, float4(*(const device bfloat4*)(x + 4)));
}
}
_Pragma("clang loop unroll(full)")
for (uint r = 0; r < ROWS; ++r) {
const float s = simd_sum(acc[r]);
if (lane == 0 && r < a.rows) Y[(size_t)r * a.ldy + j] = bfloat(s);
}
}

#define TF_BF16_MATVEC(NAME, ROWS) \
[[kernel]] void NAME(const device bfloat* X [[buffer(0)]], const device bfloat* W [[buffer(1)]], \
constant tf_bf16_mv_args& a [[buffer(2)]], device bfloat* Y [[buffer(3)]], \
uint3 tg [[threadgroup_position_in_grid]], uint sg [[simdgroup_index_in_threadgroup]], \
uint lane [[thread_index_in_simdgroup]]) { \
tf_bf16_matvec_t<ROWS>(X, W, a, Y, tg, sg, lane); \
}
#define TF_BF16_MATVECS(P) \
TF_BF16_MATVEC(P##_matvec_1, 1) \
TF_BF16_MATVEC(P##_matvec_2, 2) \
TF_BF16_MATVEC(P##_matvec_4, 4) \
TF_BF16_MATVEC(P##_matvec_8, 8) \
TF_BF16_MATVEC(P##_matvec_16, 16) \
TF_BF16_MATVEC(P##_matvec_32, 32)
32 changes: 12 additions & 20 deletions zig/kernels/metal/core/qwen_vision.metal
Original file line number Diff line number Diff line change
@@ -1,28 +1,20 @@
// Qwen-VL image towers (the Qwen3.5 tower, any width): bf16 weights, fp32 sums and residual; gemm_nax.metal first.

// ---- the projections and attention products: tfp::gemm_nax (bm64 bn128 bk256 wm2 wn4) by operand layout ----
#define QWV_GEMM(NAME, T, TB, AM, AN) \
[[max_total_threads_per_threadgroup(256)]] [[kernel]] void NAME( \
const device T* A [[buffer(0)]], const device T* B [[buffer(1)]], const device int32_t* P [[buffer(2)]], \
device T* D [[buffer(3)]], uint sg [[simdgroup_index_in_threadgroup]], \
uint lane [[thread_index_in_simdgroup]], uint3 tg [[threadgroup_position_in_grid]]) { \
tfp::gemm_nax<T, false, TB, AM, AN, false, 64, 128, 256, 2, 4>(A, B, D, P, tg, sg, lane); \
}
// x [M, K] w^T: every linear layer (bf16 in and out, fp32 sums)
QWV_GEMM(qwv_gemm_bf16_nt_00, bfloat16_t, true, false, false)
QWV_GEMM(qwv_gemm_bf16_nt_01, bfloat16_t, true, false, true)
QWV_GEMM(qwv_gemm_bf16_nt_10, bfloat16_t, true, true, false)
QWV_GEMM(qwv_gemm_bf16_nt_11, bfloat16_t, true, true, true)
TF_GEMM_NAX_KERNEL(qwv_gemm_bf16_nt_00, bfloat16_t, false, true, false, false)
TF_GEMM_NAX_KERNEL(qwv_gemm_bf16_nt_01, bfloat16_t, false, true, false, true)
TF_GEMM_NAX_KERNEL(qwv_gemm_bf16_nt_10, bfloat16_t, false, true, true, false)
TF_GEMM_NAX_KERNEL(qwv_gemm_bf16_nt_11, bfloat16_t, false, true, true, true)
// q k^T per head in fp32
QWV_GEMM(qwv_gemm_f32_nt_00, float, true, false, false)
QWV_GEMM(qwv_gemm_f32_nt_01, float, true, false, true)
QWV_GEMM(qwv_gemm_f32_nt_10, float, true, true, false)
QWV_GEMM(qwv_gemm_f32_nt_11, float, true, true, true)
TF_GEMM_NAX_KERNEL(qwv_gemm_f32_nt_00, float, false, true, false, false)
TF_GEMM_NAX_KERNEL(qwv_gemm_f32_nt_01, float, false, true, false, true)
TF_GEMM_NAX_KERNEL(qwv_gemm_f32_nt_10, float, false, true, true, false)
TF_GEMM_NAX_KERNEL(qwv_gemm_f32_nt_11, float, false, true, true, true)
// p v per head in fp32
QWV_GEMM(qwv_gemm_f32_nn_00, float, false, false, false)
QWV_GEMM(qwv_gemm_f32_nn_01, float, false, false, true)
QWV_GEMM(qwv_gemm_f32_nn_10, float, false, true, false)
QWV_GEMM(qwv_gemm_f32_nn_11, float, false, true, true)
TF_GEMM_NAX_KERNEL(qwv_gemm_f32_nn_00, float, false, false, false, false)
TF_GEMM_NAX_KERNEL(qwv_gemm_f32_nn_01, float, false, false, false, true)
TF_GEMM_NAX_KERNEL(qwv_gemm_f32_nn_10, float, false, false, true, false)
TF_GEMM_NAX_KERNEL(qwv_gemm_f32_nn_11, float, false, false, true, true)

inline float qwv_bf(float x) { return float(bfloat(x)); }

Expand Down
31 changes: 12 additions & 19 deletions zig/kernels/metal/gemma4/vision.metal
Original file line number Diff line number Diff line change
@@ -1,24 +1,17 @@
// Gemma 4's image tower at torch's per-op bf16 rounding (transformers' modeling_gemma4.py); after gemm_nax.metal.

#define G4V_GEMM(NAME, T, TA, TB, AM, AN) \
[[max_total_threads_per_threadgroup(256)]] [[kernel]] void NAME( \
const device T* A [[buffer(0)]], const device T* B [[buffer(1)]], const device int32_t* P [[buffer(2)]], \
device T* D [[buffer(3)]], uint sg [[simdgroup_index_in_threadgroup]], \
uint lane [[thread_index_in_simdgroup]], uint3 tg [[threadgroup_position_in_grid]]) { \
tfp::gemm_nax<T, TA, TB, AM, AN, false, 64, 128, 256, 2, 4>(A, B, D, P, tg, sg, lane); \
}
G4V_GEMM(g4v_gemm_bf16_nt_00, bfloat16_t, false, true, false, false)
G4V_GEMM(g4v_gemm_bf16_nt_01, bfloat16_t, false, true, false, true)
G4V_GEMM(g4v_gemm_bf16_nt_10, bfloat16_t, false, true, true, false)
G4V_GEMM(g4v_gemm_bf16_nt_11, bfloat16_t, false, true, true, true)
G4V_GEMM(g4v_gemm_f32_nt_00, float, false, true, false, false)
G4V_GEMM(g4v_gemm_f32_nt_01, float, false, true, false, true)
G4V_GEMM(g4v_gemm_f32_nt_10, float, false, true, true, false)
G4V_GEMM(g4v_gemm_f32_nt_11, float, false, true, true, true)
G4V_GEMM(g4v_gemm_f32_nn_00, float, false, false, false, false)
G4V_GEMM(g4v_gemm_f32_nn_01, float, false, false, false, true)
G4V_GEMM(g4v_gemm_f32_nn_10, float, false, false, true, false)
G4V_GEMM(g4v_gemm_f32_nn_11, float, false, false, true, true)
TF_GEMM_NAX_KERNEL(g4v_gemm_bf16_nt_00, bfloat16_t, false, true, false, false)
TF_GEMM_NAX_KERNEL(g4v_gemm_bf16_nt_01, bfloat16_t, false, true, false, true)
TF_GEMM_NAX_KERNEL(g4v_gemm_bf16_nt_10, bfloat16_t, false, true, true, false)
TF_GEMM_NAX_KERNEL(g4v_gemm_bf16_nt_11, bfloat16_t, false, true, true, true)
TF_GEMM_NAX_KERNEL(g4v_gemm_f32_nt_00, float, false, true, false, false)
TF_GEMM_NAX_KERNEL(g4v_gemm_f32_nt_01, float, false, true, false, true)
TF_GEMM_NAX_KERNEL(g4v_gemm_f32_nt_10, float, false, true, true, false)
TF_GEMM_NAX_KERNEL(g4v_gemm_f32_nt_11, float, false, true, true, true)
TF_GEMM_NAX_KERNEL(g4v_gemm_f32_nn_00, float, false, false, false, false)
TF_GEMM_NAX_KERNEL(g4v_gemm_f32_nn_01, float, false, false, false, true)
TF_GEMM_NAX_KERNEL(g4v_gemm_f32_nn_10, float, false, false, true, false)
TF_GEMM_NAX_KERNEL(g4v_gemm_f32_nn_11, float, false, false, true, true)

constant constexpr uint G4V_W = 1152, G4V_HEADS = 16, G4V_DH = 72, G4V_HALF = 36, G4V_QKV = 3 * G4V_W;

Expand Down
2 changes: 0 additions & 2 deletions zig/kernels/metal/glm/kda_rows.metal
Original file line number Diff line number Diff line change
Expand Up @@ -298,5 +298,3 @@ template <int H, int D, int TAPS, int TY, int FB, int GB>
}

}

template [[host_name("custom_kernel_tf_glm5_kda_rows_918a341e71__64_128_4_32_4_4_bfloat16_t_bfloat16_t_float_uint32_t_bfloat16_t_bfloat16_t_uint32_t_bfloat16_t_bfloat16_t_float_float_float_float_floatc_floatc_bfloat16_t_float_bfloat16_t")]] [[kernel]] decltype(custom_kernel_tf_glm5_kda_rows_918a341e71__64_128_4_32_4_4_bfloat16_t_bfloat16_t_float_uint32_t_bfloat16_t_bfloat16_t_uint32_t_bfloat16_t_bfloat16_t_float_float_float_float_floatc_floatc_bfloat16_t_float_bfloat16_t<64, 128, 4, 32, 4, 4>) custom_kernel_tf_glm5_kda_rows_918a341e71__64_128_4_32_4_4_bfloat16_t_bfloat16_t_float_uint32_t_bfloat16_t_bfloat16_t_uint32_t_bfloat16_t_bfloat16_t_float_float_float_float_floatc_floatc_bfloat16_t_float_bfloat16_t<64, 128, 4, 32, 4, 4>;
Loading
Loading