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

## Unreleased

- GLM on Metal: vectorized prompt, KDA and indexer kernels on Macs without tensor units cut cold prompt time 5.17% to 5.68% (2K to 64K tokens) with 0/64 token differences (#3921, refs #3152). Thanks to @gilby.

- MiniMax-H3-Image on Metal: `tf-h3-image` runs its transformer (MiniMax H3's, without the audio layers, on M5 tensor units) from a picture case through its six distilled steps, each with its own output head, beside the engine; the VAE's rules (config, tiles and blend, latent statistics, pixels) run on the host, and core/picture gains Pillow's Lanczos-3 resampling. Clip cases run as before (#2775).

- Kernel contract: the GLM record for `df_sumn` under nvcc 13.3 (40 registers) is the one checked; a stale generic 33-register entry no longer overrides it (#4291). Thanks to @Bizuayeu.
Expand Down
8 changes: 8 additions & 0 deletions zig/build/glm_rows_contract.zig
Original file line number Diff line number Diff line change
Expand Up @@ -14,5 +14,13 @@ pub fn host(b: *std.Build, sources: *std.Build.Module) *std.Build.Step {
run.has_side_effects = true;
const step = b.step("test-glm-window-contract-host", "Register and validate actual GLM replacement operators without a GPU");
step.dependOn(&run.step);
const ownership_metal = b.createModule(.{ .root_source_file = b.path("zig/glm_kernel_ownership_metal.zig"), .target = b.graph.host });
const loader = b.createModule(.{ .root_source_file = b.path("zig/glm_rows_contract_family.zig"), .target = b.graph.host, .imports = &.{ .{ .name = "metal", .module = ownership_metal }, .{ .name = "kernel_sources", .module = sources } } });
const ownership_root = b.createModule(.{ .root_source_file = b.path("zig/glm_kernel_ownership_host.zig"), .target = b.graph.host, .optimize = .debug, .link_libc = true, .imports = &.{ .{ .name = "metal", .module = ownership_metal }, .{ .name = "glm_kernels", .module = loader } } });
const ownership_run = b.addRunArtifact(b.addTest(.{ .root_module = ownership_root, .filters = &.{"GLM kernel ownership:"} }));
ownership_run.has_side_effects = true;
const ownership_step = b.step("test-glm-kernel-ownership-host", "Actual GLM loader pipelines are all released once on both capability paths");
ownership_step.dependOn(&ownership_run.step);
step.dependOn(ownership_step);
return step;
}
2 changes: 1 addition & 1 deletion zig/gemma4_shared_affine_test.zig
Original file line number Diff line number Diff line change
Expand Up @@ -104,7 +104,7 @@ test "landed Metal source bytes are pinned without shader compilation" {
var hash: [32]u8 = undefined;
std.crypto.hash.sha2.Sha256.hash(ks.core_affine_mm, &hash, .{});
// Hy4-flash's mapped experts and rounded SiLU, both behind defines that are off for every other caller
try std.testing.expectEqualStrings("2cf4deb55455fda30efb4fce3043ef5d90052d71f48ce7660960e8b588478aca", &std.fmt.bytesToHex(hash, .lower));
try std.testing.expectEqualStrings("9a01998f26f80c9faa511dce14d1f545264c9ab343d189d8f0f005d83cc632b7", &std.fmt.bytesToHex(hash, .lower));
}
{
var hash: [32]u8 = undefined;
Expand Down
19 changes: 19 additions & 0 deletions zig/glm_kernel_ownership_host.zig
Original file line number Diff line number Diff line change
@@ -0,0 +1,19 @@
//! Exercise the actual GLM loader and destructor on both Metal capability paths.
const std = @import("std");
const metal = @import("metal");
const kernels = @import("glm_kernels").glm.kernels;
fn check(tensor: bool) !void {
metal.reset();
const a = std.testing.allocator;
const k = try kernels.load(a, .{ .tensor = tensor });
defer a.destroy(k);
k.deinit();
try std.testing.expectEqual(metal.created.load(.monotonic), metal.released.load(.monotonic));
try std.testing.expect(metal.created.load(.monotonic) > 0);
}
test "GLM kernel ownership: pre-M5 releases every compiled pipeline exactly once" {
try check(false);
}
test "GLM kernel ownership: M5 releases every compiled pipeline exactly once" {
try check(true);
}
56 changes: 56 additions & 0 deletions zig/glm_kernel_ownership_metal.zig
Original file line number Diff line number Diff line change
@@ -0,0 +1,56 @@
//! Count loader pipeline ownership without a device, shader compiler or driver.
const std = @import("std");
pub var created = std.atomic.Value(usize).init(0);
pub var released = std.atomic.Value(usize).init(0);
var ended: [4096]std.atomic.Value(bool) = @splat(std.atomic.Value(bool).init(false));
pub fn reset() void {
created.store(0, .monotonic);
released.store(0, .monotonic);
for (&ended) |*v| v.store(false, .monotonic);
}
pub const Device = struct {
tensor: bool,
pub fn tensorUnits(d: Device) bool {
return d.tensor;
}
pub fn name(_: Device) [*:0]const u8 {
return "ownership fixture";
}
};
pub const CompileOptions = struct {
pub fn mlx() CompileOptions {
return .{};
}
};
pub const Library = struct {
pub fn fromSource(_: Device, _: []const u8, _: CompileOptions) !Library {
return .{};
}
pub fn deinit(_: Library) void {}
};
pub const Pipeline = struct {
id: usize,
pub fn init(_: Device, _: Library, _: [:0]const u8, _: bool) !Pipeline {
const id = created.fetchAdd(1, .monotonic);
std.debug.assert(id < ended.len);
return .{ .id = id };
}
pub fn deinit(p: Pipeline) void {
std.debug.assert(!ended[p.id].swap(true, .monotonic));
_ = released.fetchAdd(1, .monotonic);
}
};
pub const Buffer = struct {
pub fn deinit(_: Buffer) void {}
};
pub const ComputeEncoder = struct {};
pub const Queue = struct {};
pub const Size = @import("gemma4_recording_metal.zig").Size;
pub const objc = struct {
pub const Pool = struct {
pub fn push() Pool {
return .{};
}
pub fn pop(_: Pool) void {}
};
};
1 change: 1 addition & 0 deletions zig/glm_rows_contract_family.zig
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
//! Shared GLM owners for recording-only contract tests.
pub const glm = struct {
pub const kernels = @import("src/families/glm/kernels.zig");
pub const wide = @import("src/families/glm/wide.zig");
pub const affine = @import("src/families/glm/affine.zig");
};
147 changes: 67 additions & 80 deletions zig/kernels/metal/core/affine_mm.metal
Original file line number Diff line number Diff line change
Expand Up @@ -152,6 +152,47 @@ inline void am_codes(thread const Codes& c, threadgroup bfloat* out) {
#endif
}

#if defined(TF_GLM_M3_FAST) && defined(TF_SIMD_FRAGS)
// GLM pre-M5: codes in [K=64][N=64] layout so frag_get reads transposed weights with zero bank conflict.
inline void am_codes_kn(thread const Codes& c, threadgroup bfloat* tile, int w_n, int w_kh) {
#if TF_BITS == 2
TF_UNROLL
for (short i = 0; i < 2; i++) {
const uint w = c.v[i];
TF_UNROLL
for (short j = 0; j < 16; j++) tile[(w_kh * 32 + i * 16 + j) * PAD + w_n] = bfloat(float((w >> (2 * j)) & 3u));
}
#elif TF_BITS % 4 != 0
TF_UNROLL
for (short j = 0; j < 32; j++) {
const short at = TF_BITS * j, word = at / 32, shift = at % 32;
uint v = c.v[word] >> shift;
if (shift + TF_BITS > 32) v |= c.v[word + 1] << (32 - shift);
tile[(w_kh * 32 + j) * PAD + w_n] = bfloat(float(v & ((1u << TF_BITS) - 1u)));
}
#elif TF_BITS == 4
TF_UNROLL
for (short i = 0; i < 4; i++) {
const uint w = c.v[0][i];
TF_UNROLL
for (short j = 0; j < 8; j++) {
tile[(w_kh * 32 + i * 8 + j) * PAD + w_n] = as_type<bfloat>(ushort(0x4300u | ((w >> (4 * j)) & 0xfu)));
}
}
#else
TF_UNROLL
for (short i = 0; i < 8; i++) {
const uchar4 f = as_type<uchar4>(c.v[i / 4][i % 4]);
const int b = w_kh * 32 + i * 4;
tile[b * PAD + w_n] = bfloat(float(f.x));
tile[(b + 1) * PAD + w_n] = bfloat(float(f.y));
tile[(b + 2) * PAD + w_n] = bfloat(float(f.z));
tile[(b + 3) * PAD + w_n] = bfloat(float(f.w));
}
#endif
}
#endif

// A block of the code tile as the transposed right operand: 8-byte loads on M5 (PAD rows, 16-column blocks).
#ifndef TF_SIMD_FRAGS
#define am_tile_frag frag_get_tg
Expand Down Expand Up @@ -188,8 +229,13 @@ inline void am_step(thread frag<float> (&acc)[TM][2], thread const AmRows<TM>& r
TF_UNROLL
for (short q = 0; q < 4; q++) { // the step's four 16-deep slices, every row fragment's chain interleaved
frag<bfloat> b0, b1, a[TL];
#if defined(TF_GLM_M3_FAST) && defined(TF_SIMD_FRAGS)
frag_get(b0, tile, PAD, 16 * q, tn, home);
frag_get(b1, tile, PAD, 16 * q, tn + 16, home);
#else
am_tile_frag(b0, tile, PAD, tn, 16 * q, home);
am_tile_frag(b1, tile, PAD, tn + 16, 16 * q, home);
#endif
TF_UNROLL
for (short m = 0; m < TL; m++) {
a[m] = am_frag(rows.x[m][0], rows.x[m][1], k + 16 * q, home);
Expand Down Expand Up @@ -231,8 +277,13 @@ inline void am_step128(thread frag<float> (&acc)[TM][2], thread frag<float> (&pa
TF_UNROLL
for (short q = 0; q < 4; q++) {
frag<bfloat> b0, b1, a[TL];
#if defined(TF_GLM_M3_FAST) && defined(TF_SIMD_FRAGS)
frag_get(b0, tile, PAD, 16 * q, tn, home);
frag_get(b1, tile, PAD, 16 * q, tn + 16, home);
#else
frag_get_t(b0, tile, PAD, tn, 16 * q, home);
frag_get_t(b1, tile, PAD, tn + 16, 16 * q, home);
#endif
TF_UNROLL
for (short m = 0; m < TL; m++) {
a[m] = am_frag(rows.x[m][0], rows.x[m][1], k + 16 * q, home);
Expand Down Expand Up @@ -268,7 +319,11 @@ template <int TM>
inline void am_k_loop(thread frag<float> (&acc)[TM][2], thread const AmRows<TM>& rows, int K, int live,
const device uchar* wq, const device bfloat* scales, const device bfloat* biases,
threadgroup bfloat* tile, threadgroup float* sb, int tn, uint t, short2 home) {
#if defined(TF_GLM_M3_FAST) && defined(TF_SIMD_FRAGS)
const int w_n = int(t / 2), w_kh = int(t % 2);
#else
threadgroup bfloat* mine = tile + (t / 2) * PAD + 32 * (t % 2);
#endif
const int g_mine = TF_GROUP == 32 ? int(t % 2) : 0; // at g32 each thread of a pair takes one group's scale and bias
#if TF_GROUP == 128
frag<float> part[TM][2]; // a group's sums across its two steps
Expand All @@ -280,7 +335,11 @@ inline void am_k_loop(thread frag<float> (&acc)[TM][2], thread const AmRows<TM>&
}
for (int k = 0; k < K; k += 64) {
threadgroup_barrier(mem_flags::mem_threadgroup);
#if defined(TF_GLM_M3_FAST) && defined(TF_SIMD_FRAGS)
am_codes_kn(am_load(wq), tile, w_n, w_kh);
#else
am_codes(am_load(wq), mine);
#endif
if (TF_GROUP == 32 || t % 2 == 0) {
const float s = float(scales[g_mine]);
sb[g_mine * 128 + t / 2] = s;
Expand Down Expand Up @@ -417,9 +476,14 @@ inline void am_block(const device bfloat* x, int ldx, const device float* xs, in
uint3 tg [[threadgroup_position_in_grid]]) {
threadgroup bfloat tile[64 * PAD];
threadgroup float sb[NG * 128];
const int row = int(tg.y) * 64, col = int(tg.x) * 64, b = int(tg.z);
am_block<64>(X + long(b) * st.x_batch, st.x_row, XS + long(b) * st.sums_batch * (a.k / TF_GROUP),
st.sums_row * (a.k / TF_GROUP), row, min(64, a.rows - row), a.k, st.y_row, col,
#if defined(TF_GLM_M3_FAST) && defined(TF_SIMD_FRAGS)
constexpr int BM = 32;
#else
constexpr int BM = 64;
#endif
const int row = int(tg.y) * BM, col = int(tg.x) * 64, b = int(tg.z);
am_block<BM>(X + long(b) * st.x_batch, st.x_row, XS + long(b) * st.sums_batch * (a.k / TF_GROUP),
st.sums_row * (a.k / TF_GROUP), row, min(BM, a.rows - row), a.k, st.y_row, col,
long(b) * st.w_batch + col, W, S, B, Y + long(b) * st.y_batch, tile, sb, sg, lane);
}

Expand Down Expand Up @@ -468,80 +532,3 @@ TF_GATHER(64)
}
TF_GATHER_SCATTER(32)
TF_GATHER_SCATTER(64)

#ifdef TF_GLU_PLAIN
// mlx-lm's compiled SwiGLU on bf16 rows (LFM2): silu(g) * u, rounded to bf16 at each step; `limit` unused.
inline bfloat am_swiglu(float g, float u, float limit) {
const float gt = float(bfloat(g));
const bfloat s = static_cast<bfloat>(1.0f / (1.0f + metal::precise::exp(-gt)));
const bfloat silu = static_cast<bfloat>(gt * float(s));
return static_cast<bfloat>(float(silu) * float(bfloat(u)));
}
#else
// The glue's SwiGLU in bf16 (glm_act2): MLX's bf16 exp and abs, nn.silu's x*sigmoid(x), gate and up clipped at `limit`.
inline bfloat am_sigmoid(bfloat x) {
const bfloat e = bfloat(__metal_exp(float(bfloat(__metal_fabs(float(x), __METAL_MAYBE_FAST_MATH__))), __METAL_MAYBE_FAST_MATH__));
const bfloat y = bfloat(1) / (bfloat(1) + e);
return (x < 0) ? y : (bfloat(1) - y);
}

inline bfloat am_swiglu(float g, float u, float limit) {
const float lim = float(bfloat(limit));
const bfloat gt = bfloat(metal::min(float(bfloat(g)), lim));
const bfloat up = bfloat(metal::min(metal::max(float(bfloat(u)), -lim), lim));
#ifdef TF_GLU_ROUND_SILU
const bfloat sl = bfloat(precise::divide(float(gt), 1.0f + precise::exp(-float(gt))));
#else
const bfloat sl = gt * am_sigmoid(gt);
#endif
return sl * up;
}
#endif

// A simdgroup's gate (j 0) and up (j 1) fragments as SwiGLU outputs into y (ld N), rows below live only.
template <int TM>
inline void am_store_glu(thread const frag<float> (&acc)[TM][2], device bfloat* y, int N, int live, short2 home,
float limit) {
TF_UNROLL
for (short i = 0; i < TM; i++) {
TF_UNROLL
for (short e = 0; e < 8; e++) {
const int r = 16 * i + home.y + (e >> 2) * 8;
if (r < live) y[long(r) * N + home.x + TF_COL(e)] = am_swiglu(acc[i][0][e], acc[i][1][e], limit);
}
}
}

// The routed experts' gate and up over ORDER's token rows (pair / topk), SwiGLU'd to act [rows, n]: 32 columns a tile.
#define TF_GATHER_GLU(BM) \
[[kernel]] void tf_affine_gather_glu_##BM( \
const device bfloat* X [[buffer(0)]], const device uint32_t* WG [[buffer(1)]], \
const device bfloat* SG [[buffer(2)]], const device bfloat* BG [[buffer(3)]], \
const device float* XS [[buffer(4)]], constant MmArgs& a [[buffer(5)]], device bfloat* Y [[buffer(6)]], \
const device int32_t* OFFS [[buffer(7)]], const device int32_t* ORDER [[buffer(8)]], \
const device uint32_t* WU [[buffer(9)]], const device bfloat* SU [[buffer(10)]], \
const device bfloat* BU [[buffer(11)]], constant float2& glu [[buffer(12)]], TF_AM_MAP_ARG \
uint sg [[simdgroup_index_in_threadgroup]], uint lane [[thread_index_in_simdgroup]], \
uint3 tg [[threadgroup_position_in_grid]]) { \
constexpr int SM = BM / 2; \
constexpr int TM = SM / 16; \
threadgroup bfloat tile[64 * PAD]; \
threadgroup float sb[NG * 128]; \
int expert, row, rows; \
if (!am_tile<BM>(OFFS, a.experts, a.rows, int(tg.y), lane, expert, row, rows)) return; \
const int c0 = int(tg.x) * 32, t = int(sg) * 32 + int(lane), tr = t / 2; \
const bool up = ((tr >> 4) & 1) != 0; \
const long wrow = long(TF_AM_EXPERT(expert)) * a.n + c0 + (tr >> 5) * 16 + (tr & 15); \
const int tm = SM * int(sg / 2), tn = 32 * int(sg % 2), live = clamp(rows - tm, 0, SM); \
const short2 home = frag_home(ushort(lane)); \
const AmRows<TM> starts = am_rows<TM>(X, a.k, XS, a.k / TF_GROUP, row, rows, tm, home, ORDER, int(glu.x)); \
frag<float> acc[TM][2]; \
am_k_loop<TM>(acc, starts, a.k, live, \
(const device uchar*)(up ? WU : WG) + wrow * (a.k * TF_BITS / 8) + HALF_BYTES * (t % 2), \
(up ? SU : SG) + wrow * (a.k / TF_GROUP), (up ? BU : BG) + wrow * (a.k / TF_GROUP), tile, sb, tn, \
uint(t), home); \
am_store_glu<TM>(acc, Y + long(row + tm) * a.n + c0 + tn / 2, a.n, live, home, glu.y); \
}
// Tile rows by 16: gate, up, gate, up for columns c0.., c0 + 16..
TF_GATHER_GLU(32)
TF_GATHER_GLU(64)
Loading
Loading