Skip to content
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
19 commits
Select commit Hold shift + click to select a range
de23d07
glm cuda: retain completed shared-cache prefixes on prefill cancellation
MaverickKB Nov 23, 2026
a11d016
changelog: #4694 under Unreleased
ashhart Nov 24, 2026
e5c9471
h3: products walk 64 row tiles under each weight tile (swizzle 6)
plotarmordev Nov 18, 2026
cdcb4ed
h3: test the 64-tile product bands against MLX's band of 4 past a ban…
plotarmordev Nov 18, 2026
d67be50
h3 image: the products on H3's own 32x64-warp kernel
plotarmordev Nov 18, 2026
44fdd63
h3 image: decode tiles 64 a pass
plotarmordev Nov 22, 2026
046e834
h3: name the block's product kernel, h3_gemm_32x64
plotarmordev Nov 22, 2026
9159ca9
h3: keep h3_gemm out of the shared kernel source; the contract compil…
plotarmordev Nov 22, 2026
2e97b3a
h3: the contract gates both products, bit-equal to MLX's gemm_nax at …
plotarmordev Nov 22, 2026
24551cb
h3 contract: upload the product input as is when the launch needs no …
plotarmordev Nov 22, 2026
1f491e0
h3: one-line comments on the products, and no unused most_batch re-ex…
plotarmordev Nov 22, 2026
34a5fa7
h3 contract: a planted control for each product, its K steps reversed…
plotarmordev Nov 22, 2026
d8ce641
h3 image: export the decoder's most_batch, which the image server's d…
plotarmordev Nov 23, 2026
63fe47e
h3 recipe: the decoder runs up to 64 tiles a command buffer
plotarmordev Nov 23, 2026
82fb7cc
changelog: #4641 under Unreleased
ashhart Nov 24, 2026
c5be4cb
refactor(hip): the d = 256 long-span score's pieces from plan.hip int…
AbrahamCete Nov 22, 2026
6ae1e68
feat(hip): score a multi-row launch's slots from one read of their ke…
AbrahamCete Nov 22, 2026
2eeb375
perf(hip): multi-row planned walks take the shared-row score step
AbrahamCete Nov 22, 2026
a6ad3dc
changelog: #4673 under Unreleased
ashhart Nov 24, 2026
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
6 changes: 6 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,12 @@ Each release's page on GitHub has its notes and measurements. See [the 1.0.0 rel

## Unreleased

- HIP decode: multi-row rounds score each slot's rows from one read of their keys (#N).

- H3 on Metal: transformer products run on the `h3_gemm_32x64` kernel in 64-row bands and the decoder decodes 64 tiles a pass, with sums unchanged (#N).

- GLM on CUDA: a prefill cancelled between chunks keeps its completed shared-cache prefix (#N).

- Qwen 3.5 on Metal: `TF_QWEN35_CHUNK` sets the prefill chunk size for measurement; the default stays 128 rows (#N).

- CUDA: Ripple-65B-Preview (ricursive) serves on the native engine from the publisher's NVFP4 release as published, with prompt chunks and decode, lane rounds as CUDA graphs, greedy and sampled draws, kept states and the prompt cache; the bf16 release is refused by name, and structured output and forced tool calls are refused until masked sampling lands (#2302, fixes #2300). Thanks to @jrb-ai.
Expand Down
13 changes: 13 additions & 0 deletions docs/kernel-contract.md
Original file line number Diff line number Diff line change
Expand Up @@ -208,6 +208,19 @@ enabled on RDNA3.5 for single-round `K <= 1024` plans), whose rows past an item'
`item_rows = 0` byte for byte when the largest item holds 3 or 4 rows. Its controls run over items one row short and go
red at gate 3.

HIP's shared-row decode score (`plan_rows.hip`: q fp32, d = 256, spans of 16,384 keys or more, launches of more than
one row) replaces `tf_plan_score256_*` byte for byte with two launches on its grid, a block a plan row. First
`tf_plan_lone_score256_*` scores the rows of one-row slots as `tf_plan_score256_*` does, at its occupancy, and its other
blocks leave. Then `tf_plan_rows_score256_*`, counted from each multi-row slot's `first`, has the block of every second
row score that row and the next of the same slot from one read of the keys; the other blocks leave, so a chunk never
crosses a slot. Its registrations run both head groups (16 over 2, 24 over 4) and both cache kinds as one operator, on
launches of 1 to 64 rows: slots of 3, 1, 4 and 2 rows one position apart (at the span's end, mid-span, across a block's
first key, at the span's start), and 5 and 7 slots of one row each, over spans of 16,384 to 262,144 keys with NaN and
infinite keys that some rows of a chunk see and others do not. Its controls go red at gate 3: one leads the chunks over
the whole launch (every slot's `first` 0 and its count every row), so a chunk crosses a slot, and one launches the
chunks alone, so no launch scores the rows of one-row slots. A row scored by both launches gets the same bits from
each, so no control can show it; each kernel's own exit test keeps the two sets apart.

The HIP relu^2 replacement retains every non-finite plant and checks both unfused bytes and every
independent float64 output class. No inherited infinity discrepancy is accepted.
The paired launch retains every table plant and checks both members' separate-launch bytes and every
Expand Down
2 changes: 1 addition & 1 deletion docs/recipes/minimax-h3-image-metal.md
Original file line number Diff line number Diff line change
Expand Up @@ -210,7 +210,7 @@ tensor units.
3. Each tile runs `post_quant_conv`, then its cells become tokens through `x_embedder`, with the 4 registers and one
zero token appended.
4. The 2D rotary table is built, and the 24 blocks run, then `norm_out` and `proj_out`.
5. Each token's 768 values are unpatchified to its 16 x 16 pixels. Up to 16 tiles run in one command buffer.
5. Each token's 768 values are unpatchified to its 16 x 16 pixels. Up to 64 tiles run in one command buffer.
6. Tiles are blended in float32: the top band against the tile above, then the left band against the tile to the left,
both as decoded.
7. The result is mapped to [0, 1] with ImageNet's statistics, clamped and truncated to bytes.
Expand Down
9 changes: 5 additions & 4 deletions docs/recipes/minimax-h3-metal.md
Original file line number Diff line number Diff line change
Expand Up @@ -21,8 +21,9 @@ forward stage by stage.

## Arithmetic

- Block projections: the prefill kernels' `tfp::gemm_nax` (MLX 0.32.3's NAX GEMM), bf16 x w^T as the checkpoint
stores w, fp32 sums, bf16 out. The SwiGLU's first projection is one product over its stored [value; gate] rows.
- Block projections: H3's own `h3_gemm_32x64` (64 x 128 a threadgroup, 32 x 64 a warp), bf16 x w^T as the checkpoint
stores w, fp32 sums in MLX 0.32.3's NAX GEMM order, bf16 out: bit-equal to `tfp::gemm_nax`. Threadgroups walk 64
row tiles under each weight tile. The SwiGLU's first projection is one product over its stored [value; gate] rows.
- Norms, rotary, the gated adds and the SwiGLU round to bf16 where the reference's bf16 MLX arithmetic rounds.
- Attention is FastH3's video sparse attention over 64-row tiles: a text, keyframe or audio tile attends every
tile; a video tile attends the prefix tiles and its top 20% of video tiles by pooled score; the pooled branch is
Expand All @@ -32,8 +33,8 @@ forward stage by stage.

## Kernel contract

Thirteen kernels are registered (`zig/tests/contract/metal_h3*.zig`), each against its formula in float64, and their
launches in `registry.zig`. The two GEMM entry points are the prefill source's own and are registered as launches.
The kernels are registered (`zig/tests/contract/metal_h3*.zig`), each against its formula in float64, and their
launches in `registry.zig`. The two products also match MLX's gemm_nax byte for byte at the served shapes.
Kernels whose outputs pass through intermediate bf16 roundings declare them as `mids`; their test inputs are of one
sign where a sum could cancel, so no rounding hides behind a small result.

Expand Down
7 changes: 6 additions & 1 deletion zig/build/h3_host.zig
Original file line number Diff line number Diff line change
Expand Up @@ -18,7 +18,8 @@ pub fn tests(b: *std.Build, target: std.Build.ResolvedTarget, test_step: *std.Bu
@import("h3_image_encoder.zig").compileHost(b, target, metal);
const sources = b.createModule(.{ .root_source_file = b.path("zig/kernels/metal/sources.zig") });
const kernels = b.createModule(.{ .root_source_file = b.path("zig/kernels/metal/h3/kernels.zig") });
const model = b.createModule(.{ .root_source_file = b.path("zig/src/families/h3/h3.zig"), .target = target, .optimize = .Debug, .link_libc = true, .imports = &.{ .{ .name = "metal", .module = metal }, .{ .name = "core", .module = core }, .{ .name = "kernel_sources", .module = sources }, .{ .name = "h3_kernels", .module = kernels } } });
const imports: []const std.Build.Module.Import = &.{ .{ .name = "metal", .module = metal }, .{ .name = "core", .module = core }, .{ .name = "kernel_sources", .module = sources }, .{ .name = "h3_kernels", .module = kernels } };
const model = b.createModule(.{ .root_source_file = b.path("zig/src/families/h3/h3.zig"), .target = target, .optimize = .Debug, .link_libc = true, .imports = imports });
const tool = b.addExecutable(.{ .name = "tf-h3-host-compile", .root_module = b.createModule(.{ .root_source_file = b.path("zig/tests/h3_dit.zig"), .target = target, .optimize = .Debug, .link_libc = true, .imports = &.{ .{ .name = "h3", .module = model }, .{ .name = "metal", .module = metal } } }) });
const picture_tool = b.addExecutable(.{ .name = "tf-h3-image-host-compile", .root_module = b.createModule(.{ .root_source_file = b.path("zig/tests/h3_image.zig"), .target = target, .optimize = .Debug, .link_libc = true, .imports = &.{ .{ .name = "h3", .module = model }, .{ .name = "metal", .module = metal }, .{ .name = "core", .module = core } } }) });
const compile = b.step("compile-h3-host", "Compile the actual H3 tools without compiling or executing shaders");
Expand All @@ -28,6 +29,10 @@ pub fn tests(b: *std.Build, target: std.Build.ResolvedTarget, test_step: *std.Bu
const rounding = b.addRunArtifact(b.addTest(.{ .root_module = modulation, .filters = &.{"modulation bf16:"} }));
b.step("test-h3-modulation-bf16", "H3's host bf16 rounding against the copy it replaced, no GPU").dependOn(&rounding.step);
test_step.dependOn(&rounding.step);
const block = b.createModule(.{ .root_source_file = b.path("zig/src/families/h3/block.zig"), .target = target, .optimize = .Debug, .link_libc = true, .imports = imports });
const bands = b.addRunArtifact(b.addTest(.{ .root_module = block, .filters = &.{"h3 gemm:"} }));
b.step("test-h3-gemm", "H3's transformer products in 64-tile bands against MLX's band of 4, on the GPU").dependOn(&bands.step);
test_step.dependOn(&bands.step);
const ahead = b.createModule(.{ .root_source_file = b.path("zig/src/families/h3/read_ahead.zig"), .target = target, .optimize = .Debug, .link_libc = true, .imports = &.{.{ .name = "core", .module = core }} });
const read_test = b.addTest(.{ .root_module = ahead });
const read_step = b.step("test-h3-read-ahead", "H3 whole-shard reads, truncated or missing files, and prefetch disabled");
Expand Down
1 change: 1 addition & 0 deletions zig/build/hip.zig
Original file line number Diff line number Diff line change
Expand Up @@ -501,6 +501,7 @@ const groups = [_]Source{
.{ .path = "qwen_vision.hip", .strict = true },
.{ .path = "draft/draft.hip" },
.{ .path = "exl3/exl3.hip" },
.{ .path = "decode/plan_rows.hip" },
};
/// What the group sources include, so an edit to one rebuilds them.
const headers = [_][]const u8{
Expand Down
104 changes: 104 additions & 0 deletions zig/glm_image_cache_host.zig
Original file line number Diff line number Diff line change
Expand Up @@ -394,3 +394,107 @@ test "GLM image cache: suffix encoding wire and actual splice dispatch preserve
try peer.take(0, none);
try t.expectEqual(@as(usize, 0), peer.rowCount());
}

/// Echo rank zero's reduction locally. The chunk control and the cache go through their serving paths.
const CancelWire = struct {
fn broadcast(_: u64, _: u64, _: usize, _: cuda.nccl.DataType, _: c_int, _: cuda.nccl.Comm, _: cuda.abi.Stream) callconv(.c) c_int {
return 0;
}
fn reduce(_: u64, _: u64, _: usize, _: cuda.nccl.DataType, _: cuda.nccl.RedOp, _: cuda.nccl.Comm, _: cuda.abi.Stream) callconv(.c) c_int {
return 0;
}
fn download(dst: ?*anyopaque, src: u64, n: usize) callconv(.c) c_int {
@memcpy(@as([*]u8, @ptrCast(dst.?))[0..n], @as([*]const u8, @ptrFromInt(src))[0..n]);
return 0;
}
fn device(d: *cuda.abi.Device) callconv(.c) c_int {
d.* = 0;
return 0;
}
fn attribute(out: *c_int, _: cuda.abi.DeviceAttribute, _: cuda.abi.Device) callconv(.c) c_int {
out.* = 0;
return 0;
}
};

fn checkInterruptedPrefix(planned: []const u32) !void {
var c: Cache = .{};
try c.init();
defer c.deinit();
var d = Device.driver();
d.api.cuDeviceGetAttribute = CancelWire.attribute;
d.api.cuCtxGetDevice = CancelWire.device;
d.api.cuMemcpyDtoH_v2 = CancelWire.download;
cuda.download_stage.forget();
defer cuda.download_stage.forget();
defer {
cuda.copy_source.synchronizeStream(&d, null) catch {};
cuda.copy_source.dropSpares(&d, cuda.copy_source.current());
}
var lib: cuda.nccl.Library = .{ .lib = undefined, .api = undefined };
lib.api.ncclBroadcast = CancelWire.broadcast;
lib.api.ncclAllReduce = CancelWire.reduce;
var word: f64 = 0;
var wire_buffer: [10000]u8 = undefined;
var wire_ids: [2049]u32 = undefined;
c.e.d = &d;
c.e.stream = .{ .d = &d, .handle = null };
c.e.lib = &lib;
c.e.comm = null;
c.e.dropped = .empty;
c.e.announce = 0;
c.e.share.rank = 0;
c.e.share.world = 2;
c.e.settings = .{};
c.e.m.glue.put_words = .{ .d = &d, .handle = null };
c.e.heat_gate.bands = null;
c.e.prompt_profs = @splat(null);
c.e.profiling_prompt = null;
c.e.prompt_logprobs = null;
c.e.drafter = null;
c.e.l2pf = null;
c.e.images = null;
c.e.pair = null;
c.e.shared_buf = .{ .d = &d, .ptr = @intFromPtr(&word), .len = @sizeOf(f64), .borrowed = true };
var seq: @TypeOf(c.e.cur.*) = .{ .st = undefined };
c.e.seqs = .empty;
try c.e.seqs.append(a, &seq);
defer c.e.seqs.deinit(a);
var link: glm.follow.Link = .{
.d = &d,
.lib = &lib,
.comm = null,
.stream = c.e.stream,
.ids = &wire_ids,
.gpa = a,
.wait = true,
.buf = .{ .d = &d, .ptr = @intFromPtr(&wire_buffer), .len = wire_buffer.len, .borrowed = true },
};
var back: glm.lanes.Lanes = .{ .x = .{ .e = &c.e, .link = &link } };
defer back.deinit();
const ids: [N]u32 = @splat(17);
var s = try lanes.Stream.init(a, .{ .id = "cancelled", .prompt = &ids, .max_new = 8 });
defer s.deinit(a);
const lane = try back.claim(&s);
lane.fill = 2048;
lane.marks = try a.dupe(u32, planned);
c.model.words = .{ 31, 47 };
try t.expect(s.reuse.hook == null);
try t.expectEqual(@as(u32, 0), try c.begin(&s));
const b = back.backend();
try b.vtable.cancel_prefill.?(b.ptr, &s);
try t.expectEqual(@as(usize, 1), c.model.live);
c.model.words = .{ 0, 0 };
var retry = try lanes.Stream.init(a, .{ .id = "retry", .prompt = &ids, .max_new = 8 });
defer retry.deinit(a);
try t.expectEqual(@as(u32, 2048), try c.begin(&retry));
try t.expectEqual([2]u64{ 31, 47 }, c.model.words);
}

test "GLM shared cache: cancellation before a scheduled mark preserves the completed prefix for retry" {
try checkInterruptedPrefix(&.{6144});
}

test "GLM shared cache: cancellation without scheduled marks preserves the completed prefix for retry" {
try checkInterruptedPrefix(&.{});
}
115 changes: 1 addition & 114 deletions zig/kernels/hip/decode/plan.hip
Original file line number Diff line number Diff line change
Expand Up @@ -11,22 +11,6 @@ __device__ __forceinline__ float wave_sum(float x) {
return __shfl(x, 0, 32);
}

// x from lane ^ M of its 16-lane row (M < 16): a DPP row_xmask move, all lanes active.
template <int M>
__device__ __forceinline__ float row_xor(float x) {
return __builtin_bit_cast(float, __builtin_amdgcn_mov_dpp(__builtin_bit_cast(int, x), 0x160 + M, 0xf, 0xf, false));
}

// wave_sum's folds, own value then partner's at xor 16, 8, 4, 2, 1, without LDS: every lane ends with the sum.
__device__ __forceinline__ float wave_sum_dpp(float x) {
const int w = __builtin_bit_cast(int, x);
x += __builtin_bit_cast(float, __builtin_amdgcn_permlanex16(w, w, 0x76543210u, 0xfedcba98u, false, false));
x += row_xor<8>(x);
x += row_xor<4>(x);
x += row_xor<2>(x);
return x + row_xor<1>(x);
}

// Row r's keys (already rotated, fp32) and values (the activation kind) into its slot's pages at its position.
__device__ void plan_kv_write_body(const float* keys, const void* values, int kind, int rows, int kv_heads, int d,
PlanArgs plan, int layer) {
Expand Down Expand Up @@ -56,42 +40,8 @@ __device__ void plan_kv_write_act_body(const void* keys, const void* values, int
cache[to] = static_cast<const uint16_t*>(values)[i];
}

// Query heads a block takes together: they share a KV head, so its keys and values are read once for all of them.
constexpr int kMaxGroup = 16;

// Keys a wave scores on long spans and on short ones: their loads go out together, each head's query read once.
constexpr int kScoreKeys = 4;
// Keys a wave scores on short spans (kScoreKeys on long ones, plan.hpp).
constexpr int kScoreKeysShort = 2;
// Steps of its waves' keys a long-span block walks at d = 256 (launches/plan.zig's score_steps).
constexpr int kScoreSteps = 8;
// load() of a 16-bit cache element as a global load: a flat load also counts on lgkmcnt, which LDS reads wait on.
__device__ __forceinline__ float cache_load(const void* p, int kind, long long i) {
const uint16_t bits = ((const __attribute__((address_space(1))) uint16_t*)p)[i];
return kind == 1 ? __half2float(__ushort_as_half(bits)) : bf16_to_float(bits);
}

// A wave's KEYS keys from key0 at d = 256 into k, lane l taking elements l + 32 i; keys past `visible` are not loaded.
template <int KEYS>
__device__ __forceinline__ void score_fetch(float (&k)[KEYS][8], const void* keys, int kind, const unsigned* pages,
unsigned pool, int kv, int key0, int visible, int lane) {
#pragma unroll
for (int j = 0; j < KEYS; ++j) {
if (key0 + j >= visible) break;
const long long base = page_at(pages, pool, kv, key0 + j, 256);
#pragma unroll
for (int i = 0; i < 8; ++i) k[j][i] = cache_load(keys, kind, base + lane + i * 32);
}
}

// Lane 0's KEYS scores of a head from `at`: one 16-byte store when `whole` (aligned rows, span a multiple of KEYS).
template <int KEYS>
__device__ __forceinline__ void score_store(float* at, const float (&sc)[KEYS], bool whole, int key0, int span) {
if (whole && KEYS == 4) {
*reinterpret_cast<float4*>(at) = make_float4(sc[0], sc[1 % KEYS], sc[2 % KEYS], sc[3 % KEYS]);
} else {
for (int j = 0; j < KEYS; ++j) if (key0 + j < span) at[j] = sc[j];
}
}

// score_keys over a plan's rows: a warp scores KEYS keys for each of the block's heads; q fp32 or of kind QKIND.
template <int KEYS, int KIND, int QKIND = 0>
Expand Down Expand Up @@ -155,69 +105,6 @@ __device__ void plan_score_body(const void* __restrict__ q, float* __restrict__
}
}

// plan_score_body on long spans at d = 256 (tf_plan_score256_*): no element tests, kScoreSteps steps a block.
template <int KIND, int QKIND>
__device__ void plan_score256_body(const void* __restrict__ q, float* __restrict__ scores, int span, int heads,
int kv_heads, int d, float scale, PlanArgs plan, int layer) {
constexpr int KEYS = kScoreKeys, STEPS = kScoreSteps;
extern __shared__ float qs[]; // the block's query heads, group * d
const int batch = blockIdx.z, group = heads / gridDim.y, head0 = blockIdx.y * group;
const long long q0 = (static_cast<long long>(batch) * heads + head0) * d;
for (int i = threadIdx.x; i < group * d; i += blockDim.x) qs[i] = load(q, QKIND, q0 + i); // kind 0: q fp32
__syncthreads();
const int visible = min(plan.pos[batch] + 1, span);
const int lane = threadIdx.x & 31;
const unsigned long long* desc = plan_desc(plan, plan.slot[batch]);
float* __restrict__ rows = scores + (static_cast<long long>(batch) * heads + head0) * span;
const void* keys = reinterpret_cast<const void*>(desc[plan_first(layer)]);
const unsigned* pages = plan_pages(plan, desc);
const unsigned pool = plan.pool;
const int kv = head0 / (heads / kv_heads);
const int stride = (blockDim.x >> 5) * KEYS; // keys a step of the block
const int first = blockIdx.x * STEPS * stride + (threadIdx.x >> 5) * KEYS;
const bool whole = (span % KEYS) == 0 && (reinterpret_cast<unsigned long long>(rows) & 15) == 0;
float kreg[KEYS][8] = {};
score_fetch<KEYS>(kreg, keys, KIND, pages, pool, kv, first, visible, lane);
#pragma unroll 1
for (int step = 0; step < STEPS; ++step) {
const int key0 = first + step * stride;
if (key0 >= span) break; // the same for the whole wave
float next[KEYS][8] = {};
score_fetch<KEYS>(next, keys, KIND, pages, pool, kv, step + 1 < STEPS ? key0 + stride : span, visible, lane);
if (key0 >= visible) { // the wave's keys are all past the row's: -INFINITY wherever the span has them
float none[KEYS];
for (int j = 0; j < KEYS; ++j) none[j] = -INFINITY;
for (int g = 0; lane == 0 && g < group; ++g) {
score_store<KEYS>(rows + key0 + static_cast<long long>(g) * span, none, whole, key0, span);
}
} else {
#pragma unroll
for (int g = 0; g < kMaxGroup; ++g) {
if (g < group) { // the same for the whole block, so every lane reaches the folds
float qv[8];
#pragma unroll
for (int i = 0; i < 8; ++i) qv[i] = qs[g * 256 + lane + i * 32];
float dot[KEYS];
#pragma unroll
for (int j = 0; j < KEYS; ++j) {
float partial = 0.f;
#pragma unroll
for (int i = 0; i < 8; ++i) partial += qv[i] * kreg[j][i];
dot[j] = wave_sum_dpp(partial);
}
if (lane == 0) {
float sc[KEYS];
#pragma unroll
for (int j = 0; j < KEYS; ++j) sc[j] = key0 + j < visible ? dot[j] * scale : -INFINITY;
score_store<KEYS>(rows + key0 + static_cast<long long>(g) * span, sc, whole, key0, span);
}
}
}
}
__builtin_memcpy(kreg, next, sizeof(kreg));
}
}

// apply_values over a plan's rows: a 128-key tile of the block's heads, weights worked once a block, in its order.
template <int KIND>
__device__ void plan_apply_body(const float* __restrict__ scores, const float* __restrict__ stats,
Expand Down
Loading
Loading