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
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

- Inkling 2 Mini on CUDA: the loop gate runs as a down half and an up half, so one-stream decode is about 28% faster on GB10 with identical tokens (#4697). Thanks @jschmied.

- Tools: `tools/bench_prose.py` measures decode on distinct natural prose, cache-format loss and long-context recall against any server, and counts a result only with matching token evidence (#4797). Thanks @GrgaPalcic.

- GLM Metal: one-Mac GLM-5.3-Flash prefills short remaining work first by default, cutting a short reply beside a long prompt from 6.11 s to 3.56 s (41.7%) with long-prompt TTFT within 1.2% (#3903, refs #3152). Thanks to @gilby.
Expand Down
85 changes: 84 additions & 1 deletion zig/kernels/cuda/inkling2/loop_math.cu
Original file line number Diff line number Diff line change
Expand Up @@ -165,7 +165,7 @@ __device__ void messages(const uint16_t* __restrict__ bank0, const uint16_t* __r
}
}

// One gate a block. A shared BF16 zeta is the sole bottleneck output; forget/gain stay FP32 through tanh (A7(a)).
// One gate a block: the frozen baseline the down/up halves are gated bit-equal against in the contract (not served).
__device__ void gate(const float* __restrict__ h, const float* __restrict__ m,
const uint16_t* __restrict__ down, const uint16_t* __restrict__ forget,
const uint16_t* __restrict__ gain, float* __restrict__ out,
Expand Down Expand Up @@ -225,6 +225,76 @@ __device__ void gate(const float* __restrict__ h, const float* __restrict__ m,
}
}

// A gate's down half, a block a row and rank pair: the one-block kernel's 256-thread chains and tree, so zeta is equal.
__device__ void gateDown(const float* __restrict__ h, const float* __restrict__ m, const uint16_t* __restrict__ down,
uint16_t* __restrict__ zeta, int c, float eps) {
__shared__ float sh[2 * 32];
__shared__ float inv_h, inv_m;
const size_t row = blockIdx.x;
const int r = 2 * static_cast<int>(blockIdx.y);
const float* hr = h + row * c;
const float* mr = m + row * c;
float ss[2] = {0.0f, 0.0f};
for (int i = threadIdx.x; i < c; i += blockDim.x) {
ss[0] = __fmaf_rn(hr[i], hr[i], ss[0]);
ss[1] = __fmaf_rn(mr[i], mr[i], ss[1]);
}
blockSums<2>(ss, sh);
if (threadIdx.x == 0) {
inv_h = rsqrtf(__fadd_rn(__fdiv_rn(ss[0], static_cast<float>(c)), eps));
inv_m = rsqrtf(__fadd_rn(__fdiv_rn(ss[1], static_cast<float>(c)), eps));
}
__syncthreads();
float acc[2] = {0.0f, 0.0f};
const uint16_t* d0 = down + static_cast<size_t>(r) * (2 * c);
const uint16_t* d1 = d0 + 2 * c;
for (int i = threadIdx.x; i < 2 * c; i += blockDim.x) {
const bool message = i >= c;
const float x = message ? mr[i - c] : hr[i];
const float n = bfr(__fmul_rn(x, message ? inv_m : inv_h));
acc[0] = __fmaf_rn(bf(d0[i]), n, acc[0]);
acc[1] = __fmaf_rn(bf(d1[i]), n, acc[1]);
}
blockSums<2>(acc, sh);
if (threadIdx.x == 0) {
zeta[row * kRank + r] = tobf(acc[0]);
zeta[row * kRank + r + 1] = tobf(acc[1]);
}
}

// A gate's up half: a thread an output column, forget/gain FP32 through tanh (A7(a)), the same ascending rank chains.
__device__ void gateUp(const float* h, const float* __restrict__ m, const uint16_t* __restrict__ zeta,
const uint16_t* __restrict__ forget, const uint16_t* __restrict__ gain, float* out, int c) {
__shared__ float z[kRank];
const size_t row = blockIdx.x;
if (threadIdx.x < kRank) z[threadIdx.x] = bf(zeta[row * kRank + threadIdx.x]);
__syncthreads();
const int i = static_cast<int>(blockIdx.y) * blockDim.x + threadIdx.x;
if (i >= c) return;
const uint4* f = reinterpret_cast<const uint4*>(forget + static_cast<size_t>(i) * kRank);
const uint4* g = reinterpret_cast<const uint4*>(gain + static_cast<size_t>(i) * kRank);
float sf = 0.0f, sg = 0.0f;
#pragma unroll
for (int q = 0; q < kRank / 8; ++q) {
const uint4 fq = __ldg(f + q), gq = __ldg(g + q);
const uint32_t fw[4] = {fq.x, fq.y, fq.z, fq.w}, gw[4] = {gq.x, gq.y, gq.z, gq.w};
#pragma unroll
for (int t = 0; t < 8; ++t) {
const float zr = z[8 * q + t];
const uint16_t fb = static_cast<uint16_t>(fw[t >> 1] >> (16 * (t & 1)));
const uint16_t gb = static_cast<uint16_t>(gw[t >> 1] >> (16 * (t & 1)));
sf = __fmaf_rn(bf(fb), zr, sf);
sg = __fmaf_rn(bf(gb), zr, sg);
}
}
const float fg = tanhf(sf), gg = tanhf(sg);
// The reference's four FP32 rounding steps, kept explicit so contraction cannot erase any of them.
const float keep = __fsub_rn(1.0f, fg);
const float old = __fmul_rn(keep, h[row * c + i]);
const float added = __fmul_rn(gg, m[row * c + i]);
out[row * c + i] = __fadd_rn(old, added);
}

} // namespace ink2l

extern "C" __global__ void __launch_bounds__(256)
Expand All @@ -242,6 +312,19 @@ extern "C" __global__ void __launch_bounds__(256)
ink2l::gate(h, m, down, forget, gain, out, c, eps);
}

// Gate down: grid (rows, 32 rank pairs). Gate up: grid (rows, c / 64); it may write `out` in place of h.
extern "C" __global__ void __launch_bounds__(256)
tf_ink2_loop_gate_down(const float* __restrict__ h, const float* __restrict__ m, const uint16_t* __restrict__ down,
uint16_t* __restrict__ zeta, int c, float eps) {
ink2l::gateDown(h, m, down, zeta, c, eps);
}

extern "C" __global__ void __launch_bounds__(64)
tf_ink2_loop_gate_up(const float* h, const float* __restrict__ m, const uint16_t* __restrict__ zeta,
const uint16_t* __restrict__ forget, const uint16_t* __restrict__ gain, float* out, int c) {
ink2l::gateUp(h, m, zeta, forget, gain, out, c);
}

// Mini QKV launch uses three independently normalized inputs; other kernels and cache/partial layouts are unchanged.
extern "C" __global__ void __launch_bounds__(256)
tf_ink2_loop_project_qkv(const uint16_t* __restrict__ uq, const uint16_t* __restrict__ uk,
Expand Down
2 changes: 2 additions & 0 deletions zig/src/core/contract/inkling2_experts_records.zig
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,8 @@ pub const cuda = [_]registry.CudaRecord{
.{ .launch = .{ .name = "inkling2_loop_math tf_ink2_loop_ar", .symbol = "tf_ink2_loop_ar", .image = "inkling2_loop_math", .threads = 512, .min_sm = 80 }, .usage = .{ .{ .regs = 32, .static = 656, .bound = 512 }, .{ .regs = 40, .static = 656, .bound = 512 }, .{ .regs = 40, .static = 656, .bound = 512 }, .{ .regs = 40, .static = 656, .bound = 512 }, .{ .regs = 40, .static = 656, .bound = 512 } }, .later_pending = true },
.{ .launch = .{ .name = "inkling2_loop_math tf_ink2_loop_messages", .symbol = "tf_ink2_loop_messages", .image = "inkling2_loop_math", .threads = 256, .min_sm = 80 }, .usage = .{ .{ .regs = 26, .static = 272, .bound = 256 }, .{ .regs = 28, .static = 272, .bound = 256 }, .{ .regs = 28, .static = 272, .bound = 256 }, .{ .regs = 32, .static = 272, .bound = 256 }, .{ .regs = 36, .static = 272, .bound = 256 } }, .later_pending = true },
.{ .launch = .{ .name = "inkling2_loop_math tf_ink2_loop_gate", .symbol = "tf_ink2_loop_gate", .image = "inkling2_loop_math", .threads = 256, .min_sm = 80 }, .usage = .{ .{ .regs = 32, .static = 392, .bound = 256 }, .{ .regs = 40, .static = 392, .bound = 256 }, .{ .regs = 40, .static = 392, .bound = 256 }, .{ .regs = 36, .static = 392, .bound = 256 }, .{ .regs = 36, .static = 392, .bound = 256 } }, .later_pending = true },
.{ .launch = .{ .name = "inkling2_loop_math tf_ink2_loop_gate_down", .symbol = "tf_ink2_loop_gate_down", .image = "inkling2_loop_math", .threads = 256, .min_sm = 80 }, .usage = .{ .{ .regs = 22, .static = 264, .bound = 256 }, .{ .regs = 24, .static = 264, .bound = 256 }, .{ .regs = 24, .static = 264, .bound = 256 }, .{ .regs = 32, .static = 264, .bound = 256 }, .{ .regs = 31, .static = 264, .bound = 256 } }, .later_pending = true },
.{ .launch = .{ .name = "inkling2_loop_math tf_ink2_loop_gate_up", .symbol = "tf_ink2_loop_gate_up", .image = "inkling2_loop_math", .threads = 64, .min_sm = 80 }, .usage = .{ .{ .regs = 38, .static = 256, .bound = 64 }, .{ .regs = 70, .static = 256, .bound = 64 }, .{ .regs = 46, .static = 256, .bound = 64 }, .{ .regs = 46, .static = 256, .bound = 64 }, .{ .regs = 46, .static = 256, .bound = 64 } }, .later_pending = true },
.{ .launch = .{ .name = "inkling2_loop_math tf_ink2_loop_project_qkv", .symbol = "tf_ink2_loop_project_qkv", .image = "inkling2_loop_math", .threads = 256, .min_sm = 80 }, .usage = .{ .{ .regs = 30, .static = 2048, .bound = 256 }, .{ .regs = 35, .static = 2048, .bound = 256 }, .{ .regs = 35, .static = 2048, .bound = 256 }, .{ .regs = 42, .static = 2048, .bound = 256 }, .{ .regs = 42, .static = 2048, .bound = 256 } }, .later_pending = true },
.{ .launch = .{ .name = "inkling2_loop_math tf_ink2_loop_round_bf16", .symbol = "tf_ink2_loop_round_bf16", .image = "inkling2_loop_math", .threads = 256, .min_sm = 80 }, .usage = .{ .{ .regs = 10, .static = 0, .bound = 256 }, .{ .regs = 10, .static = 0, .bound = 256 }, .{ .regs = 10, .static = 0, .bound = 256 }, .{ .regs = 10, .static = 0, .bound = 256 }, .{ .regs = 10, .static = 0, .bound = 256 } }, .later_pending = true },
};
Expand Down
6 changes: 4 additions & 2 deletions zig/src/families/inkling2/loop_engine.zig
Original file line number Diff line number Diff line change
Expand Up @@ -66,6 +66,7 @@ const Scratch = struct {
bank0: u64,
bank1: u64,
raw: u64, // three FP32 AR/gate rows per token
zeta: u64, // a gate's 64 BF16 bottleneck values per token, between its down and up halves
messages: u64, // four FP32 message rows per token
normalized: u64, // three BF16 rows per token
t: u64,
Expand Down Expand Up @@ -245,6 +246,7 @@ pub const Model = struct {
.bank0 = try m.alloc(rows * h * 2),
.bank1 = try m.alloc(rows * h * 2),
.raw = try m.alloc(3 * rows * h * 4),
.zeta = try m.alloc(rows * loop_math.rank * 2),
.messages = try m.alloc(4 * rows * h * 4),
.normalized = try m.alloc(3 * rows * h * 2),
.t = try m.alloc(rows * h * 4),
Expand Down Expand Up @@ -389,7 +391,7 @@ pub const Model = struct {
}
for (0..3) |role| {
const ctl = lw.controllers[role];
try loop_math.gate(&k.loop, s, m.s.raw + role * raw_stride, m.s.messages + role * raw_stride, ctl.down, ctl.forget, ctl.gain, m.s.raw + role * raw_stride, rows, h, c.eps);
try loop_math.gate(&k.loop, s, m.s.raw + role * raw_stride, m.s.messages + role * raw_stride, ctl.down, ctl.forget, ctl.gain, m.s.zeta, m.s.raw + role * raw_stride, rows, h, c.eps);
const norms = [3]u64{ lw.attn.norms[role], lw.attn.norms[role], lw.attn.norms[role] };
try ops.mix(&k.glue, s, m.mixArgs(&.{}, m.s.raw + role * raw_stride, 0, norms, m.s.normalized + role * norm_stride, 1, false, rows));
}
Expand Down Expand Up @@ -474,7 +476,7 @@ pub const Model = struct {
if (messages) {
try loop_math.ar(&k.loop, s, m.arBlocks(mlp_blocks, m.s.t, mlp_query, m.s.raw, 1, false, rows));
const ctl = lw.controllers[3];
try loop_math.gate(&k.loop, s, m.s.raw, m.s.messages + 3 * raw_stride, ctl.down, ctl.forget, ctl.gain, m.s.raw, rows, h, c.eps);
try loop_math.gate(&k.loop, s, m.s.raw, m.s.messages + 3 * raw_stride, ctl.down, ctl.forget, ctl.gain, m.s.zeta, m.s.raw, rows, h, c.eps);
try ops.mix(&k.glue, s, m.mixArgs(&.{}, m.s.raw, 0, .{ lw.mlp_norm, lw.mlp_norm, lw.mlp_norm }, m.s.normalized, 1, false, rows));
} else {
try ops.mix(&k.glue, s, m.mixArgs(mlp_blocks, m.s.t, mlp_query, .{ lw.mlp_norm, lw.mlp_norm, lw.mlp_norm }, m.s.normalized, 1, false, rows));
Expand Down
32 changes: 25 additions & 7 deletions zig/src/families/inkling2/loop_math_cuda.zig
Original file line number Diff line number Diff line change
Expand Up @@ -24,7 +24,8 @@ pub const Kernels = struct {
mod: cuda.Module,
ar_fn: cuda.Function,
messages_fn: cuda.Function,
gate_fn: cuda.Function,
gate_down_fn: cuda.Function,
gate_up_fn: cuda.Function,
project_qkv_fn: cuda.Function,
round_bf16_fn: cuda.Function,

Expand All @@ -36,7 +37,8 @@ pub const Kernels = struct {
.mod = mod,
.ar_fn = try mod.function("tf_ink2_loop_ar"),
.messages_fn = try mod.function("tf_ink2_loop_messages"),
.gate_fn = try mod.function("tf_ink2_loop_gate"),
.gate_down_fn = try mod.function("tf_ink2_loop_gate_down"),
.gate_up_fn = try mod.function("tf_ink2_loop_gate_up"),
.project_qkv_fn = try mod.function("tf_ink2_loop_project_qkv"),
.round_bf16_fn = try mod.function("tf_ink2_loop_round_bf16"),
};
Expand Down Expand Up @@ -87,7 +89,7 @@ pub fn messages(
try go(k.messages_fn, s, .{ .x = @intCast(rows), .y = 4 }, 256, &a);
}

/// Controller: BF16 D[64][2c]/F/G[c][64] and down I/O; FP32 F/G dots/tanh/four-step output; pre-offset msg, no scratch.
/// Controller: BF16 D/F/G, FP32 F/G dots/tanh/four-step output; zeta [rows][64] BF16 scratch; out may alias state.
pub fn gate(
k: *const Kernels,
s: cuda.Stream,
Expand All @@ -96,17 +98,33 @@ pub fn gate(
down_bf16: u64,
forget_bf16: u64,
gain_bf16: u64,
zeta_bf16: u64,
out_f32: u64,
rows: usize,
c: usize,
eps: f32,
) !void {
if (rows == 0 or c == 0) return error.Inkling2LoopGateShape;
try gateDown(k, s, state_f32, message_f32, down_bf16, zeta_bf16, rows, rank / 2, c, eps);
try gateUp(k, s, state_f32, message_f32, zeta_bf16, forget_bf16, gain_bf16, out_f32, rows, c);
}

/// The down half alone: `pairs` rank pairs from the first (all 32 in `gate`; fewer only for a contract control).
pub fn gateDown(k: *const Kernels, s: cuda.Stream, state_f32: u64, message_f32: u64, down_bf16: u64, zeta_bf16: u64, rows: usize, pairs: usize, c: usize, eps: f32) !void {
if (rows == 0 or c == 0 or pairs == 0 or pairs > rank / 2) return error.Inkling2LoopGateShape;
var a: cuda.Args = .{};
for ([_]u64{ state_f32, message_f32, down_bf16, forget_bf16, gain_bf16, out_f32 }) |v| a.add(v);
for ([_]i32{ int(rows), int(c) }) |v| a.add(v);
for ([_]u64{ state_f32, message_f32, down_bf16, zeta_bf16 }) |v| a.add(v);
a.add(int(c));
a.add(eps);
try go(k.gate_fn, s, .{ .x = @intCast(rows) }, 256, &a);
try go(k.gate_down_fn, s, .{ .x = @intCast(rows), .y = @intCast(pairs) }, 256, &a);
}

/// The up half: forget/gain from zeta and the four-step output, 64 columns a block.
pub fn gateUp(k: *const Kernels, s: cuda.Stream, state_f32: u64, message_f32: u64, zeta_bf16: u64, forget_bf16: u64, gain_bf16: u64, out_f32: u64, rows: usize, c: usize) !void {
if (rows == 0 or c == 0) return error.Inkling2LoopGateShape;
var a: cuda.Args = .{};
for ([_]u64{ state_f32, message_f32, zeta_bf16, forget_bf16, gain_bf16, out_f32 }) |v| a.add(v);
a.add(int(c));
try go(k.gate_up_fn, s, .{ .x = @intCast(rows), .y = @intCast((c + 63) / 64) }, 64, &a);
}

/// Mini QKV: normalized BF16 uq/uk/uv, query-side u_q; per-visit K/V conv/cache, then wo/post-conv; no history.
Expand Down
43 changes: 38 additions & 5 deletions zig/tests/cuda/contract_inkling2_loop_math.zig
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
//! Mini loop math under the contract, with independent host arithmetic and planted single-fault controls.
const std = @import("std");
const cuda = @import("cuda");
const core = @import("core");
const ink = @import("inkling2");
const rig_ = @import("contract_rig.zig");
Expand Down Expand Up @@ -54,6 +55,10 @@ pub fn Checked(comptime T: type) type {
try self.inner.simulate(acc, order, out);
}

pub fn replaced(self: *Self) ![]const u8 {
return self.inner.replaced();
}

pub fn check(self: *Self, _: g.Gate) !?[]const u8 {
const a = self.rig.gpu.gpa;
const got = try a.dupe(u8, try self.rig.outputBytes());
Expand Down Expand Up @@ -317,29 +322,40 @@ const gate_shapes = [_]c.Shape{
.{ .rows = 2048, .n = 128, .k = 256 },
};

/// Host reference preserves BF16 n/zeta and all four FP32 output steps; control substitutes F for Gain.
/// The served gate, or a control: forget weights again for gain (up half), or zeta from half the rank pairs (down).
pub const GateFault = enum { none, wrong_gain, half_ranks };

/// Host reference preserves BF16 n/zeta and all four FP32 output steps through both halves' launches.
pub const Gate = struct {
kern: *const lm.Kernels,
wrong_gain: bool = false,
fault: GateFault = .none,
shape: c.Shape = undefined,
h: []f32 = &.{},
m: []f32 = &.{},
d: []u16 = &.{},
f: []u16 = &.{},
gain: []u16 = &.{},
dev: [5]u64 = @splat(0),
zeta: u64 = 0,
out: u64 = 0,
base: u64 = 0,

pub fn spec(self: *const Gate) c.Spec {
return .{ .name = if (self.wrong_gain) "control: inkling2 loop rank-64 gate with forget weights again instead of gain" else "inkling2 loop tf_ink2_loop_gate (BF16 down input/result, FP32 F/G tanh and four output steps)", .accum = .f32, .depth = depth, .out = .f32, .served = if (self.wrong_gain) gate_shapes[0..2] else &gate_shapes };
const name = switch (self.fault) {
.none => "inkling2 loop tf_ink2_loop_gate_down + _up (BF16 down input/zeta, FP32 F/G tanh and four output steps)",
.wrong_gain => "control: inkling2 loop rank-64 gate up half with forget weights again instead of gain",
.half_ranks => "control: inkling2 loop rank-64 gate down half launched for 16 of its 32 rank pairs",
};
const served = if (self.fault != .none) gate_shapes[0..2] else &gate_shapes;
return .{ .name = name, .accum = .f32, .depth = depth, .out = .f32, .served = served, .replaces = "tf_ink2_loop_gate" };
}

fn depth(s: c.Shape) usize {
return (s.k + 255) / 256 + 10 + lm.rank;
}

pub fn control(self: *const Gate) ?g.Gate {
return if (self.wrong_gain) .shapes else null;
return if (self.fault != .none) .shapes else null;
}

pub fn free(self: *Gate, a: std.mem.Allocator) void {
Expand Down Expand Up @@ -377,12 +393,29 @@ pub const Gate = struct {
ref.plant(f32, self.m, shape.rows, cols, ref.asF32);
}
self.dev = .{ try ref.input(rig, self.h), try ref.input(rig, self.m), try ref.input(rig, self.d), try ref.input(rig, self.f), try ref.input(rig, self.gain) };
self.zeta = try rig.scratch(shape.rows * lm.rank * 2);
self.base = try rig.scratch(shape.rows * cols * 4);
self.out = try rig.output(shape.rows * cols * 4);
return true;
}

pub fn run(self: *Gate, rig: *rig_.Rig) !void {
try lm.gate(self.kern, rig.s, self.dev[0], self.dev[1], self.dev[2], self.dev[3], if (self.wrong_gain) self.dev[3] else self.dev[4], self.out, self.shape.rows, self.shape.n, eps);
const d = self.dev;
const rows = self.shape.rows;
const pairs: usize = if (self.fault == .half_ranks) lm.rank / 4 else lm.rank / 2;
try lm.gateDown(self.kern, rig.s, d[0], d[1], d[2], self.zeta, rows, pairs, self.shape.n, eps);
try lm.gateUp(self.kern, rig.s, d[0], d[1], self.zeta, d[3], if (self.fault == .wrong_gain) d[3] else d[4], self.out, rows, self.shape.n);
}

/// The one-block tf_ink2_loop_gate the served halves replace, on the same inputs: gate 3 wants its bytes.
pub fn replaced(self: *Gate, rig: *rig_.Rig) ![]const u8 {
const f = try self.kern.mod.function("tf_ink2_loop_gate");
var a: cuda.Args = .{};
for ([_]u64{ self.dev[0], self.dev[1], self.dev[2], self.dev[3], self.dev[4], self.base }) |v| a.add(v);
for ([_]i32{ @intCast(self.shape.rows), @intCast(self.shape.n) }) |v| a.add(v);
a.add(@as(f32, eps));
try cuda.launch.launch(f, .{ .grid = .{ .x = @intCast(self.shape.rows) }, .block = .{ .x = 256 } }, rig.s, &a);
return rig.bytes(self.base, self.shape.rows * self.shape.n * 4);
}

pub fn count(self: *const Gate) usize {
Expand Down
Loading
Loading