Skip to content
Merged
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
4 changes: 4 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -4,8 +4,12 @@ Each release's page on GitHub has its notes and measurements. See [the 1.0.0 rel

## Unreleased

- DeepSeek-V4.1 on Metal: a decode round over several streams runs each per-stream stage (window key, compressed rows and index keys, ratio-2 pooling, decode attention, index scores, candidate blocks and the top 512) as one dispatch over a table of the streams' state, with one barrier between stages instead of one a stream, and the same bits (#2954, refs #2984). Thanks to @gilby.

- Qwen3.8-27B on Metal with `TF_QWEN27_METAL_KV_PAGES=1`: Macs with tensor units (M5) take the flag instead of refusing it, and a paged prompt pass finds a chunk's two pages once and picks the right one at each step, instead of looking up the page at every step; with the flag unset nothing changes (#3180, refs #1293). Thanks to @CodingEmil.



- Tests: the last real-clock multi-rank bring-up tests run on the lockstep clock, so a busy CI runner cannot change their outcome (#4193).

- CUDA contract: nvcc 13.3 resource records for 121 launches, clearing 408 stale lines on five-SM fatbins (#3953). Thanks to @Bizuayeu.
Expand Down
13 changes: 12 additions & 1 deletion docs/kernel-contract.md
Original file line number Diff line number Diff line change
Expand Up @@ -488,7 +488,18 @@ relu by `fmaxf`, and the down launched one neuron short).
Metal also checks DeepSeek V4.1's CSA2 attention (`csa2_attn.metal`): decode rows (ring or linear windows) and prompt rows
(16-key tiles at absolute positions), fp32 and bf16 out, against float64's softmax over the window, the selected rows and
the sink with the inverse RoPE, and a row's bytes equal across chunk splits and between the two launches (four controls,
each one planted fault, and one on the row bytes).
each one planted fault, and one on the row bytes). Its slot kernels (`*_segs`: the window key, the ratio-2 pool with
the inputs it keeps, the FP4 round trip, the key packing and the decode attention) run the rows of several slots in one
launch over a table of the slots' state, each bit-equal to its per-slot kernel launched a slot at a time at 1 to 4 slots
and 1 to 17 rows, NaN and infinities included; each but the prefetch attention has a control that reads or writes the
first slot's state for every row. The indexer's decode scores (`tf_dsv41_ix_scores_dec_segs`) and candidate blocks
(`tf_cand_segs`) do the same over each slot's keys, position and key count, bit-equal to the per-slot launches at
ratios 1 and 2, with and without a candidate mask, and a slot with no keys left alone; the top-512 runs unchanged over
score rows of one stride. Their controls score the first slot's keys and count the first slot's keys for every row.
The slot table entry `TfDsv41Seg` lives in one header (`segs.h`) the five sources start with; a kernel reads back its
size and field offsets against segs.zig's `Seg`. After the gates, every per-slot kernel these slot kernels share a body
with is checked byte-equal to the base's body, kept only in the tests (`dsv41_base`), on the same random and non-finite
inputs at one stream.

CUDA also checks the grouped EXL3 experts' `tf_exl3_plan_finish`: its bf16 and fp32 SwiGLU and its fp32 and bf16 down
epilogues bit-equal to main's kernel (kept in `contract_controls.cu`), and its SwiGLU-OAI (`act_mode` 2,
Expand Down
11 changes: 11 additions & 0 deletions zig/build/dsv41_metal.zig
Original file line number Diff line number Diff line change
Expand Up @@ -137,6 +137,17 @@ pub fn steps(b: *std.Build, metal: *std.Build.Module, sources: *std.Build.Module
const vreal_run = b.addRunArtifact(b.addTest(.{ .root_module = vreal }));
vreal_run.has_side_effects = true;
b.step("test-dsv41-metal-vision-real", "DeepSeek-V4.1 Metal: the release's vision tower (TF_DSV41_REAL_VISION) against float64").dependOn(&vreal_run.step);
// the tiny forward's round at 1, 2 and 4 slots on synthetic weights: dispatches, barriers and time
const slots = b.createModule(.{
.root_source_file = b.path("zig/tests/dsv41_metal/slots_time.zig"),
.target = b.graph.host,
.optimize = .ReleaseFast,
.link_libc = true,
.imports = &.{ .{ .name = "dsv41_metal", .module = quick.pkg }, .{ .name = "metal", .module = metal }, .{ .name = "dsv41", .module = quick.host } },
});
const slots_run = b.addRunArtifact(b.addTest(.{ .root_module = slots }));
slots_run.has_side_effects = true;
b.step("time-dsv41-metal-slots", "DeepSeek-V4.1 Metal: the tiny forward's round at 1, 2 and 4 slots (dispatches, time)").dependOn(&slots_run.step);
const ptime = b.createModule(.{
.root_source_file = b.path("zig/tests/dsv41_metal/prompt_time.zig"),
.target = b.graph.host,
Expand Down
66 changes: 49 additions & 17 deletions zig/kernels/metal/deepseek_v41/cand.metal
Original file line number Diff line number Diff line change
Expand Up @@ -43,26 +43,21 @@ inline uint2 tf_cand_pick(threadgroup atomic_uint* bins, uint k, threadgroup uin
return r;
}

// scores [rows][keys], visible [rows], keyed [rows][blocks] scratch, mask [rows][blocks] bytes.
[[max_total_threads_per_threadgroup(TF_TG)]] kernel void tf_cand(
constant TfCandArgs& args [[buffer(0)]],
device const uint* scores [[buffer(1)]],
device const int* visible [[buffer(2)]],
device uint* keyed [[buffer(3)]],
device uchar* mask [[buffer(4)]],
uint row [[threadgroup_position_in_grid]],
uint tid [[thread_index_in_threadgroup]],
uint lane [[thread_index_in_simdgroup]],
uint simd [[simdgroup_index_in_threadgroup]]) {
threadgroup atomic_uint bins[TF_BINS];
threadgroup uint sc[34], part[64];
// A candidate threadgroup's shared memory: the radix bins and the scan's partial sums.
struct TfCandShared {
atomic_uint bins[TF_BINS];
uint sc[34], part[64];
};

// One row: its scores s (keys of them), visible count, keyed scratch kd and mask out.
inline void tf_cand_row(TfCandArgs args, device const uint* s, int vis, device uint* kd, device uchar* out, uint tid,
uint lane, uint simd, threadgroup TfCandShared& sh) {
threadgroup auto& bins = sh.bins;
threadgroup auto& sc = sh.sc;
threadgroup auto& part = sh.part;
const uint n = min((args.keys + 7u) / 8u, args.blocks);
const uint k = min(args.topk, 2048u);
const int vis = visible[row];
const uint last = vis >= 1 ? uint(vis - 1) / 8u : 0xffffffffu;
device const uint* s = scores + ulong(row) * args.keys;
device uint* kd = keyed + ulong(row) * args.blocks;
device uchar* out = mask + ulong(row) * args.blocks;
#if TF_CTL == 4
if (tid == 0u && args.keys > 0u) ((device uint*)s)[0] ^= 1u;
#endif
Expand Down Expand Up @@ -127,3 +122,40 @@ inline uint2 tf_cand_pick(threadgroup atomic_uint* bins, uint k, threadgroup uin
if (j < args.blocks) out[j] = pick ? 1 : 0;
}
}

// scores [rows][keys], visible [rows], keyed [rows][blocks] scratch, mask [rows][blocks] bytes.
[[max_total_threads_per_threadgroup(TF_TG)]] kernel void tf_cand(
constant TfCandArgs& args [[buffer(0)]],
device const uint* scores [[buffer(1)]],
device const int* visible [[buffer(2)]],
device uint* keyed [[buffer(3)]],
device uchar* mask [[buffer(4)]],
uint row [[threadgroup_position_in_grid]],
uint tid [[thread_index_in_threadgroup]],
uint lane [[thread_index_in_simdgroup]],
uint simd [[simdgroup_index_in_threadgroup]]) {
threadgroup TfCandShared sh;
tf_cand_row(args, scores + ulong(row) * args.keys, visible[row], keyed + ulong(row) * args.blocks,
mask + ulong(row) * args.blocks, tid, lane, simd, sh);
}

// tf_cand over several slots' rows, scores a fixed `stride` a row: row r over its slot's keys (none: left as it was).
[[max_total_threads_per_threadgroup(TF_TG)]] kernel void tf_cand_segs(
constant TfCandArgs& args [[buffer(0)]],
device const uint* scores [[buffer(1)]],
device const int* visible [[buffer(2)]],
device uint* keyed [[buffer(3)]],
device uchar* mask [[buffer(4)]],
const device TfDsv41Seg* SG [[buffer(5)]],
const device int* RS [[buffer(6)]],
uint row [[threadgroup_position_in_grid]],
uint tid [[thread_index_in_threadgroup]],
uint lane [[thread_index_in_simdgroup]],
uint simd [[simdgroup_index_in_threadgroup]]) {
threadgroup TfCandShared sh;
const uint keys = SG[TF_CTL == 6 ? 0 : RS[row]].nkeys; // control 6: every row over the first slot's key count
if (keys == 0u) return;
const TfCandArgs one = {keys, args.blocks, args.topk};
tf_cand_row(one, scores + ulong(row) * args.keys, visible[row], keyed + ulong(row) * args.blocks,
mask + ulong(row) * args.blocks, tid, lane, simd, sh);
}
77 changes: 67 additions & 10 deletions zig/kernels/metal/deepseek_v41/compress.metal
Original file line number Diff line number Diff line change
Expand Up @@ -49,10 +49,8 @@ struct TfCPoolArgs {
};

// Compressor ratio 2 (model.py:429-487): a column a thread, rows in order; odd positions pool the two slots.
[[kernel, max_total_threads_per_threadgroup(32)]] void tf_dsv41_c_pool2(
const device float* KV [[buffer(0)]], const device float* SC [[buffer(1)]], device float* ST [[buffer(2)]],
const device int* P [[buffer(3)]], device bfloat* Y [[buffer(4)]], constant TfCPoolArgs& a [[buffer(5)]],
uint d [[thread_position_in_grid]]) {
inline void tf_c_pool2_col(const device float* KV, const device float* SC, device float* ST, const device int* P,
device bfloat* Y, TfCPoolArgs a, uint d) {
if (d >= a.dim) return;
// the carry ST (kv[2][dim], score[2][dim]) keeps each slot's last value: any launch split gives the same bits
float kv[2] = {ST[d], ST[a.dim + d]}, sc[2] = {ST[2 * a.dim + d], ST[3 * a.dim + d]};
Expand All @@ -75,14 +73,20 @@ struct TfCPoolArgs {
ST[d] = kv[0], ST[a.dim + d] = kv[1], ST[2 * a.dim + d] = sc[0], ST[3 * a.dim + d] = sc[1];
}

[[kernel, max_total_threads_per_threadgroup(32)]] void tf_dsv41_c_pool2(
const device float* KV [[buffer(0)]], const device float* SC [[buffer(1)]], device float* ST [[buffer(2)]],
const device int* P [[buffer(3)]], device bfloat* Y [[buffer(4)]], constant TfCPoolArgs& a [[buffer(5)]],
uint d [[thread_position_in_grid]]) {
tf_c_pool2_col(KV, SC, ST, P, Y, a, d);
}

struct TfCRtArgs {
uint blocks, in_stride, out_row;
};

// The compressed KV's fp4_act_quant round trip (kernel.py:184), 16-value blocks, E4M3 scales, to row D[r] (< 0 skips).
[[kernel, max_total_threads_per_threadgroup(32)]] void tf_dsv41_c_fp4rt(
const device bfloat* X [[buffer(0)]], device bfloat* Y [[buffer(1)]], const device int* D [[buffer(2)]],
constant TfCRtArgs& a [[buffer(3)]], uint2 g [[thread_position_in_grid]]) {
inline void tf_c_fp4rt_block(const device bfloat* X, device bfloat* Y, const device int* D, constant TfCRtArgs& a,
uint2 g) {
if (g.x >= a.blocks) return;
const int at = D[g.y];
if (at < 0) return;
Expand All @@ -105,14 +109,19 @@ struct TfCRtArgs {
if (TF_CTL == 4 && g.x == 0) Y[ulong(at) * a.out_row + a.out_row + 15u] = bfloat(1.0f);
}

[[kernel, max_total_threads_per_threadgroup(32)]] void tf_dsv41_c_fp4rt(
const device bfloat* X [[buffer(0)]], device bfloat* Y [[buffer(1)]], const device int* D [[buffer(2)]],
constant TfCRtArgs& a [[buffer(3)]], uint2 g [[thread_position_in_grid]]) {
tf_c_fp4rt_block(X, Y, D, a, g);
}

struct TfCPackArgs {
uint blocks, in_stride, code_row, scale_row, scale_off, use_dest;
};

// Index keys and queries, fp4_act_quant: 32-value blocks, E8M0 scales, E2M1 nibbles, to row D[r] (< 0 skips).
[[kernel, max_total_threads_per_threadgroup(32)]] void tf_dsv41_c_fp4pack(
const device bfloat* X [[buffer(0)]], device uchar* C [[buffer(1)]], device uchar* S [[buffer(2)]],
const device int* D [[buffer(3)]], constant TfCPackArgs& a [[buffer(4)]], uint2 g [[thread_position_in_grid]]) {
inline void tf_c_fp4pack_block(const device bfloat* X, device uchar* C, device uchar* S, const device int* D,
constant TfCPackArgs& a, uint2 g) {
if (g.x >= a.blocks) return;
const int at = a.use_dest != 0u ? D[g.y] : int(g.y);
if (at < 0) return;
Expand All @@ -136,3 +145,51 @@ struct TfCPackArgs {
S[ulong(at) * a.scale_row + a.scale_off + g.x] = bad ? uchar(255) : uchar(e + 127);
if (TF_CTL == 4 && g.x == 0) S[ulong(at) * a.scale_row + a.scale_row] = uchar(1);
}

[[kernel, max_total_threads_per_threadgroup(32)]] void tf_dsv41_c_fp4pack(
const device bfloat* X [[buffer(0)]], device uchar* C [[buffer(1)]], device uchar* S [[buffer(2)]],
const device int* D [[buffer(3)]], constant TfCPackArgs& a [[buffer(4)]], uint2 g [[thread_position_in_grid]]) {
tf_c_fp4pack_block(X, C, S, D, a, g);
}

// Control 6 of the slot kernels: every row takes the first slot's state.
inline uint tf_c_slot(const device int* RS, uint r) { return TF_CTL == 6 ? 0u : uint(RS[r]); }

struct TfCPoolSegArgs {
uint keep, dim; // rows a slot's kept inputs hold (its score half starts keep rows on), columns
};

// tf_dsv41_c_pool2 over several slots, slot g.y over its rows and carry; its kv and score rows kept in its inputs.
[[kernel, max_total_threads_per_threadgroup(32)]] void tf_dsv41_c_pool2_segs(
const device float* KV [[buffer(0)]], const device float* SC [[buffer(1)]], const device int* P [[buffer(3)]],
device bfloat* Y [[buffer(4)]], constant TfCPoolSegArgs& a [[buffer(5)]], const device TfDsv41Seg* SG [[buffer(6)]],
uint2 g [[thread_position_in_grid]]) {
if (g.x >= a.dim) return;
const TfDsv41Seg s = SG[g.y];
const ulong b = s.base;
const TfCPoolArgs one = {s.rows, a.dim};
tf_c_pool2_col(KV + b * a.dim, SC + b * a.dim, SG[TF_CTL == 6 ? 0u : g.y].carry, P + b, Y + b * a.dim, one, g.x);
if (s.inputs == nullptr) return;
device uint* in = (device uint*)s.inputs;
const device uint* kv = (const device uint*)KV + b * a.dim;
const device uint* sc = (const device uint*)SC + b * a.dim;
for (uint r = 0; r < s.rows; ++r) {
in[ulong(r) * a.dim + g.x] = kv[ulong(r) * a.dim + g.x];
in[ulong(a.keep + r) * a.dim + g.x] = sc[ulong(r) * a.dim + g.x];
}
}

// tf_dsv41_c_fp4rt over several slots: row r into its slot's compressed rows (RS: row -> slot).
[[kernel, max_total_threads_per_threadgroup(32)]] void tf_dsv41_c_fp4rt_segs(
const device bfloat* X [[buffer(0)]], const device int* D [[buffer(2)]], constant TfCRtArgs& a [[buffer(3)]],
const device TfDsv41Seg* SG [[buffer(4)]], const device int* RS [[buffer(5)]], uint2 g [[thread_position_in_grid]]) {
tf_c_fp4rt_block(X, (device bfloat*)SG[tf_c_slot(RS, g.y)].pool, D, a, g);
}

// tf_dsv41_c_fp4pack over several slots: row r into its slot's index keys, codes and scales (RS: row -> slot).
[[kernel, max_total_threads_per_threadgroup(32)]] void tf_dsv41_c_fp4pack_segs(
const device bfloat* X [[buffer(0)]], const device int* D [[buffer(3)]], constant TfCPackArgs& a [[buffer(4)]],
const device TfDsv41Seg* SG [[buffer(5)]], const device int* RS [[buffer(6)]], uint2 g [[thread_position_in_grid]]) {
device uchar* k = SG[tf_c_slot(RS, g.y)].keys;
tf_c_fp4pack_block(X, k, k, D, a, g);
}
46 changes: 39 additions & 7 deletions zig/kernels/metal/deepseek_v41/csa2_attn.metal
Original file line number Diff line number Diff line change
Expand Up @@ -286,15 +286,23 @@ inline void tf_attn_store(thread TfAccN<HS>& s, uint hh, float sink, const devic

// Decode: a threadgroup is one row, HS heads and a simdgroup for each of the five chunks; simdgroup 0 joins them.

// A decode threadgroup's shared memory: the chunks' states, their counts and the staged indices.
struct TfAttnDecShared {
float tacc[TF_ATTN_NCH][TF_ATTN_HS][TF_ATTN_D];
float tml[TF_ATTN_NCH][TF_ATTN_HS][2];
uint tn[TF_ATTN_NCH];
int tidx[TF_ATTN_SEL];
};

// A selected run's simdgroup first copies its 128 indices to threadgroup memory, so no key load waits on an index load.
template <typename T, bool PF>
[[kernel, max_total_threads_per_threadgroup(32 * TF_ATTN_NCH)]] void tf_dsv41_attn_dec(
TF_ATTN_ARGS, uint2 tg [[threadgroup_position_in_grid]], uint sg [[simdgroup_index_in_threadgroup]],
uint lane [[thread_index_in_simdgroup]]) {
threadgroup float tacc[TF_ATTN_NCH][TF_ATTN_HS][TF_ATTN_D];
threadgroup float tml[TF_ATTN_NCH][TF_ATTN_HS][2];
threadgroup uint tn[TF_ATTN_NCH];
threadgroup int tidx[TF_ATTN_SEL];
inline void tf_attn_dec_row(const device uint4* Q, const device uint4* W, const device uint4* C, const device int* I,
const device TfAttnMeta* M, const device float* SK, const device float* CS, device T* O,
constant TfAttnArgs& a, uint2 tg, uint sg, uint lane, threadgroup TfAttnDecShared& sh) {
threadgroup auto& tacc = sh.tacc;
threadgroup auto& tml = sh.tml;
threadgroup auto& tn = sh.tn;
threadgroup auto& tidx = sh.tidx;
const uint r = tg.x, h0 = tg.y * TF_ATTN_HS;
if (r >= a.rows || h0 >= a.heads) return;
if (sg != 0)
Expand Down Expand Up @@ -330,6 +338,28 @@ template <typename T, bool PF>
if (TF_CTL == 4 && r == 0 && h0 == 0 && lane == 0) O[ulong(a.rows) * a.heads * TF_ATTN_D] = T(1.0f);
}

template <typename T, bool PF>
[[kernel, max_total_threads_per_threadgroup(32 * TF_ATTN_NCH)]] void tf_dsv41_attn_dec(
TF_ATTN_ARGS, uint2 tg [[threadgroup_position_in_grid]], uint sg [[simdgroup_index_in_threadgroup]],
uint lane [[thread_index_in_simdgroup]]) {
threadgroup TfAttnDecShared sh;
tf_attn_dec_row<T, PF>(Q, W, C, I, M, SK, CS, O, a, tg, sg, lane, sh);
}

// Decode rows of several slots in one launch, each over its slot's window and compressed rows; control 6: slot 0's.
template <typename T, bool PF>
[[kernel, max_total_threads_per_threadgroup(32 * TF_ATTN_NCH)]] void tf_dsv41_attn_dec_segs(
const device uint4* Q [[buffer(0)]], const device int* I [[buffer(3)]], const device TfAttnMeta* M [[buffer(4)]],
const device float* SK [[buffer(5)]], const device float* CS [[buffer(6)]], device T* O [[buffer(7)]],
constant TfAttnArgs& a [[buffer(8)]], const device TfDsv41Seg* SG [[buffer(9)]],
const device int* RS [[buffer(10)]], uint2 tg [[threadgroup_position_in_grid]],
uint sg [[simdgroup_index_in_threadgroup]], uint lane [[thread_index_in_simdgroup]]) {
threadgroup TfAttnDecShared sh;
const TfDsv41Seg s = SG[(TF_CTL == 6 || tg.x >= a.rows) ? 0 : RS[tg.x]];
tf_attn_dec_row<T, PF>(Q, (const device uint4*)s.window, (const device uint4*)s.comp, I, M, SK, CS, O, a, tg, sg, lane,
sh);
}

// Prompt: a threadgroup is RR consecutive rows by HG pairs of heads; a simdgroup is one row and PH heads.

// A simdgroup's heads share each key's loads; keys come from device memory, a run's indices four at a time.
Expand Down Expand Up @@ -430,3 +460,5 @@ template [[host_name("tf_dsv41_attn_dec_pf_bf16")]] [[kernel]] decltype(tf_dsv41
template [[host_name("tf_dsv41_attn_dec_pf_f32")]] [[kernel]] decltype(tf_dsv41_attn_dec<float, true>) tf_dsv41_attn_dec<float, true>;
template [[host_name("tf_dsv41_attn_pre_bf16")]] [[kernel]] decltype(tf_dsv41_attn_pre<bfloat>) tf_dsv41_attn_pre<bfloat>;
template [[host_name("tf_dsv41_attn_pre_f32")]] [[kernel]] decltype(tf_dsv41_attn_pre<float>) tf_dsv41_attn_pre<float>;
template [[host_name("tf_dsv41_attn_dec_segs_bf16")]] [[kernel]] decltype(tf_dsv41_attn_dec_segs<bfloat, false>) tf_dsv41_attn_dec_segs<bfloat, false>;
template [[host_name("tf_dsv41_attn_dec_segs_pf_bf16")]] [[kernel]] decltype(tf_dsv41_attn_dec_segs<bfloat, true>) tf_dsv41_attn_dec_segs<bfloat, true>;
Loading
Loading