Skip to content
Closed
Show file tree
Hide file tree
Changes from 1 commit
Commits
Show all changes
34 commits
Select commit Hold shift + click to select a range
f9fc1a7
glm: group-limited top-k routing (Ling's 8 groups, keep 4) and a per-…
jschmied Oct 15, 2026
a655957
ling: Ling-3.1-flash's config loader and weight map, its routing and …
jschmied Oct 15, 2026
d46e372
ling: weights in the checkpoint's own format (bf16, FP8 blocks, Model…
jschmied Oct 15, 2026
faf7af1
docs: Ling-3.1-flash recipe: what exists, what is missing, testing wi…
jschmied Oct 15, 2026
7d184cb
glm: MLA kernels take Ling-3.1's shape: 64 roped key columns, 128-wid…
jschmied Oct 15, 2026
ef8f12f
glm: KDA serves Ling-3.1 as is (real layer 0 vs fla and float64); an …
jschmied Oct 15, 2026
6f583ba
ling: the TP=1 layer graph in any loaded format: KDA and MLA mixers, …
jschmied Oct 15, 2026
bfb44dd
ling: SwiGLU clamp in Ling's order, min(silu(g), L) * clip(u, -L, L)
jschmied Oct 15, 2026
2a5e1b6
tests: zig fmt ling_mla_real.zig
jschmied Oct 15, 2026
a3f14d3
ling: served through the lane core at TP=1: engine, lane backend, ser…
jschmied Oct 15, 2026
577436b
ling: the MTP layer (model.layers.72) drafts: enorm | hnorm through e…
jschmied Oct 15, 2026
7bd7a40
tests: ling-pack times one MoE layer's expert load (read, pack, cold)…
jschmied Oct 15, 2026
bbe360f
ling: routed experts staged in batches through pinned memory and pack…
jschmied Oct 15, 2026
412f66f
tests: ling-layer-speed times one real layer whole and op by op per p…
jschmied Oct 15, 2026
99652ba
ling: row copies 16 bytes a thread on aligned rows (prompt KDA and ML…
jschmied Oct 15, 2026
b3faea6
ling: a single decode row's projections write their columns in place,…
jschmied Oct 15, 2026
5b00637
ling: FP8 prompt chunks under 16 routed pairs an expert run the decod…
jschmied Oct 15, 2026
e78d23b
glm: group-limited select without divisions where groups are whole la…
jschmied Oct 15, 2026
0ffce4f
tests: ling-layer-speed takes a rows list, times prompt ops from an i…
jschmied Oct 15, 2026
bd7c23e
tests: ling-layer-speed starts each rep after a random spin (tf_probe…
jschmied Oct 15, 2026
32055e9
glm: swiglu keeps GLM's limit as given; only Ling's swigluWith maps 0…
jschmied Oct 15, 2026
991383f
glm: swigluWith's doc comment within 120 columns
jschmied Oct 15, 2026
03171bf
glm: drop the opt-in 16-row chunked KDA prompt path; GLM's cuda_kda.z…
jschmied Oct 15, 2026
66579cb
ling: config refuses every geometry the kernels don't take, at load, …
jschmied Oct 16, 2026
92afed6
ling: routing groups of one and a single pick refused at load; one gr…
jschmied Oct 16, 2026
674163f
ling: Store.alloc owns a buffer only once it is in both lists; a fake…
jschmied Oct 16, 2026
0ba510a
ling: a new stream's slot is chosen before its map entry exists (lane…
jschmied Oct 16, 2026
82b3817
ling: rows past a sequence's capacity are refused before any layer ru…
jschmied Oct 16, 2026
0ba2adf
ling: Engine.init frees its sequences when binding slot 0 or the last…
jschmied Oct 16, 2026
5649c63
ling: every tensor of the full checkpoint checked against the loader'…
jschmied Oct 16, 2026
e4c9bcc
oracle: the Ling oracles check their HF source against inclusionAI/Li…
jschmied Oct 16, 2026
5e931c3
ling: a segment the scratch cannot hold is refused before any layer r…
jschmied Oct 16, 2026
1395e26
ling: staging and loaded weights freed only after the stream drains; …
jschmied Oct 16, 2026
e99e650
docs/recipes/ling-3.1: file names for hashes the rebase changed, curr…
jschmied Oct 16, 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
Prev Previous commit
Next Next commit
tests: ling-pack times one MoE layer's expert load (read, pack, cold)…
… and checks its bytes against the host packers; ling-layer-real can dump its rows
  • Loading branch information
jschmied committed Oct 16, 2026
commit 7bd7a40a3f4aefe2243008d27cbbbc0eed0e59fc
10 changes: 8 additions & 2 deletions zig/tests/cuda/ling_layer_real.zig
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
//! `ling-layer-real DIR FIXTURE`: one real Ling-3.1 layer through the graph vs HF's captured output; exactness on it.
//! `ling-layer-real DIR FIXTURE [DUMP]`: one real Ling-3.1 layer through the graph vs HF's output; exactness on it.
const std = @import("std");
const cuda = @import("cuda");
const check = @import("check.zig");
Expand Down Expand Up @@ -56,7 +56,7 @@ fn dist(got: []const u16, want: []const f32, rows: usize, D: usize, skip: []cons
}

/// `ling-layer-real DIR FIXTURE` (oracle/ling_layer.py's file for layer L of the checkpoint at DIR).
pub fn run(gpu: check.Gpu, dir: []const u8, path: []const u8) !void {
pub fn run(gpu: check.Gpu, dir: []const u8, path: []const u8, dump: ?[]const u8) !void {
var arena = std.heap.ArenaAllocator.init(gpu.gpa);
defer arena.deinit();
const a = arena.allocator();
Expand Down Expand Up @@ -138,6 +138,12 @@ pub fn run(gpu: check.Gpu, dir: []const u8, path: []const u8) !void {
const dd = dist(dec, want[P * D ..], N, D, skip[P..]);
const dp = dist(dec, @as([]const f32, try widen(a, got[P * D .. (P + N) * D])), N, D, skip[P..]);
std.debug.print("RESULT decode rows {d}-{d}: rel L2 {e:.3} vs HF, {e:.3} vs the prompt's rows\n", .{ P, P + N - 1, dd[0], dp[0] });
if (dump) |d| { // the prompt's and the decode rows' bytes, for comparing two builds
const all = try a.alloc(u16, got.len + dec.len);
@memcpy(all[0..got.len], got);
@memcpy(all[got.len..], dec);
try std.Io.Dir.cwd().writeFile(gpu.io, .{ .sub_path = d, .data = std.mem.sliceAsBytes(all) });
}
try check.expect(dv[1] <= 1e-2 and dd[1] <= 1e-2, "layer {d} within rel L2 1e-2 of HF (rows whose picks agree)", .{L});
check.pass("ling-layer-real layer {d}: rel L2 {e:.3} of HF ({d} flipped rows apart); cut == uncut, window == decode rows; peak {d} MiB on the device", .{ L, dv[1], nf, cuda.usage(false).peak >> 20 });
}
Expand Down
160 changes: 160 additions & 0 deletions zig/tests/cuda/ling_pack.zig
Original file line number Diff line number Diff line change
@@ -0,0 +1,160 @@
//! `ling-pack DIR LAYER [EXPERTS]`: a MoE layer's experts loaded and timed, bytes vs the host packers the loader used.
const std = @import("std");
const cuda = @import("cuda");
const core = @import("core");
const ling = @import("ling_cuda");
const check = @import("check.zig");
const lw = @import("ling_weights_tests.zig");

const W = ling.weights;
const X8 = cuda.experts.Fp8Experts;
const X4 = cuda.experts.Nvfp4Experts;

/// Host memory from /proc/self/status: the peak resident set since the last reset, and anonymous memory now (KiB).
const Host = struct {
hwm: usize = 0,
anon: usize = 0,

fn read(io: std.Io) Host {
var buf: [8192]u8 = undefined;
const text = std.Io.Dir.cwd().readFile(io, "/proc/self/status", &buf) catch return .{};
var h: Host = .{};
var lines = std.mem.tokenizeScalar(u8, text, '\n');
while (lines.next()) |line| {
inline for (.{ .{ "VmHWM:", "hwm" }, .{ "RssAnon:", "anon" } }) |kv| if (std.mem.startsWith(u8, line, kv[0])) {
var it = std.mem.tokenizeAny(u8, line[kv[0].len..], " \tkB");
@field(h, kv[1]) = std.fmt.parseInt(usize, it.next() orelse "0", 10) catch 0;
};
}
return h;
}

/// Resets VmHWM to the current resident set (proc(5) clear_refs 5).
fn reset(io: std.Io) void {
std.Io.Dir.cwd().writeFile(io, .{ .sub_path = "/proc/self/clear_refs", .data = "5" }) catch {};
}
};

fn secs(io: std.Io, t0: i96) f64 {
return @as(f64, @floatFromInt(check.now(io) - t0)) / 1e9;
}

/// Every byte of layer i's routed experts 0..count read once from the mapping (the read alone, no device work).
fn touch(ck: *core.Checkpoint, i: u32, count: usize) !usize {
var sum: u64 = 0;
var bytes: usize = 0;
var b: [64]u8 = undefined;
const prefix = try std.fmt.bufPrint(&b, "model.layers.{d}.mlp.experts.", .{i});
for (ck.files.items) |*f| for (f.names.keys()) |k| {
if (!std.mem.startsWith(u8, k, prefix)) continue;
const rest = k[prefix.len..];
const e = std.fmt.parseInt(usize, rest[0 .. std.mem.indexOfScalar(u8, rest, '.') orelse continue], 10) catch continue;
if (e >= count) continue;
const t = f.get(k).?;
for (std.mem.bytesAsSlice(u64, @as([]align(1) const u8, t.bytes[0 .. t.bytes.len / 8 * 8]))) |w| sum +%= w;
bytes += t.bytes.len;
};
std.mem.doNotOptimizeAway(sum);
return bytes;
}

/// One expert's packed device words against the host packers' bytes from the same file tensors.
fn compare(gpu: check.Gpu, ck: *core.Checkpoint, i: u32, l: cuda.experts.Layer, a: std.mem.Allocator) !void {
const ni = l.width;
const d = l.dims;
const nvfp4 = l.format == .nvfp4;
const up_n = if (nvfp4) X4.bytes(1, ni, d, 2) / 4 else 2 * ni * d / 4;
const down_n = if (nvfp4) X4.bytes(1, d, ni, 1) / 4 else d * ni / 4;
const inv_n = (ni / 128) * (d / 128);
const hu = try a.alloc(u32, up_n);
const hd = try a.alloc(u32, down_n);
const gu = try a.alloc(u32, up_n);
const gd = try a.alloc(u32, down_n);
const scale_up = try a.alloc(u8, l.experts * (if (nvfp4) 2 * 4 else 2 * inv_n * 4));
const scale_down = try a.alloc(u8, l.experts * (if (nvfp4) 4 else inv_n * 4));
try (cuda.DeviceBuffer{ .d = gpu.d, .ptr = l.up_scale, .len = scale_up.len }).download(0, scale_up);
try (cuda.DeviceBuffer{ .d = gpu.d, .ptr = l.down_scale, .len = scale_down.len }).download(0, scale_down);
var b: [3][192]u8 = undefined;
for (0..l.experts) |e| {
var m: [3][]const u8 = undefined;
for ([_][]const u8{ "gate_proj", "up_proj", "down_proj" }, 0..) |p, j| m[j] = try std.fmt.bufPrint(&b[j], "model.layers.{d}.mlp.experts.{d}.{s}", .{ i, e, p });
if (nvfp4) {
var x: [3]core.nvfp4.Linear = undefined;
for (&x, m) |*y, name| y.* = try core.nvfp4.Linear.read(ck, name);
X4.packGateUp(hu, .{ x[0].codes, x[0].scales }, .{ x[1].codes, x[1].scales }, ni, d);
X4.packOne(hd, x[2].codes, x[2].scales, d, ni);
const globals = [3]f32{ x[0].global, x[1].global, x[2].global };
try check.sameBytes("nvfp4 gate and up globals", scale_up[8 * e ..][0..8], std.mem.sliceAsBytes(globals[0..2]));
try check.sameBytes("nvfp4 down global", scale_down[4 * e ..][0..4], std.mem.sliceAsBytes(globals[2..3]));
} else {
var t: [3]core.checkpoint.Tensor = undefined;
var s: [3]core.checkpoint.Tensor = undefined;
for (&t, &s, m) |*w, *sc, name| {
var nb: [200]u8 = undefined;
w.* = try ck.get(try std.fmt.bufPrint(&nb, "{s}.weight", .{name}));
sc.* = try ck.get(try std.fmt.bufPrint(&nb, "{s}.weight_scale_inv", .{name}));
}
try X8.packGateUp(a, hu, t[0].bytes, t[1].bytes, ni, d);
X8.packOne(hd, t[2].bytes, d, ni);
try check.sameBytes("fp8 gate scale_inv", scale_up[(2 * e) * inv_n * 4 ..][0 .. inv_n * 4], s[0].bytes);
try check.sameBytes("fp8 up scale_inv", scale_up[(2 * e + 1) * inv_n * 4 ..][0 .. inv_n * 4], s[1].bytes);
try check.sameBytes("fp8 down scale_inv", scale_down[e * inv_n * 4 ..][0 .. inv_n * 4], s[2].bytes);
}
try (cuda.DeviceBuffer{ .d = gpu.d, .ptr = l.up, .len = l.experts * up_n * 4 }).download(e * up_n * 4, std.mem.sliceAsBytes(gu));
try (cuda.DeviceBuffer{ .d = gpu.d, .ptr = l.down, .len = l.experts * down_n * 4 }).download(e * down_n * 4, std.mem.sliceAsBytes(gd));
var nb: [64]u8 = undefined;
try check.sameBytes(try std.fmt.bufPrint(&nb, "expert {d} gate-up words", .{e}), std.mem.sliceAsBytes(gu), std.mem.sliceAsBytes(hu));
try check.sameBytes(try std.fmt.bufPrint(&nb, "expert {d} down words", .{e}), std.mem.sliceAsBytes(gd), std.mem.sliceAsBytes(hd));
}
}

pub fn run(gpu: check.Gpu, rest: []const [:0]const u8) !void {
if (rest.len < 2) return error.MissingArgument;
const dir = rest[0];
const i = try std.fmt.parseInt(u32, rest[1], 10);
var arena = std.heap.ArenaAllocator.init(gpu.gpa);
defer arena.deinit();
const io = gpu.io;
var s = try cuda.Stream.init(gpu.d, false);
defer s.deinit();
var kit: lw.Kit = undefined;
try kit.init(gpu);
defer kit.deinit();
var why: ling.config.Why = .{};
var o = W.open(gpu.gpa, io, dir, &why) catch |e| {
std.debug.print("{s}: {s}\n", .{ dir, why.text() });
return e;
};
defer o.ck.close();
if (!o.c.isMoe(i)) return error.NotMoeLayer;
const count = if (rest.len > 2) try std.fmt.parseInt(usize, rest[2], 10) else o.c.experts;
const opts: W.Options = .{ .globals = false, .experts = count };
// the read alone from a cold cache, then a load on hot pages (pack and upload), then a cold load (both)
o.ck.release();
var t0 = check.now(io);
const bytes = try touch(&o.ck, i, count);
const read_s = secs(io, t0);
var hot_s: f64 = 0;
var cold_s: f64 = 0;
var peak: [2]usize = .{ 0, 0 };
var host: [2]Host = undefined;
for (0..2) |pass| {
if (pass == 1) o.ck.release();
Host.reset(io);
const base = cuda.usage(true).device;
t0 = check.now(io);
var w = try W.load(gpu.gpa, gpu.d, s, &kit.pack, &o.ck, o.c, &.{i}, opts);
defer w.deinit();
if (pass == 0) hot_s = secs(io, t0) else cold_s = secs(io, t0);
peak[pass] = cuda.usage(false).peak - base;
host[pass] = Host.read(io);
if (pass == 1) {
const l = w.layer(i).?.ffn.moe.routed.grouped;
try compare(gpu, &o.ck, i, l, arena.allocator());
std.debug.print("RESULT layer {d}: {d} experts {t}, {d:.2} GiB of expert tensors\n", .{ i, count, l.format, @as(f64, @floatFromInt(bytes)) / (1 << 30) });
}
}
std.debug.print("RESULT read alone {d:.2} s ({d:.0} MiB/s); load on hot pages {d:.2} s; cold load {d:.2} s\n", .{ read_s, @as(f64, @floatFromInt(bytes >> 20)) / read_s, hot_s, cold_s });
std.debug.print("RESULT device peak above the start {d} MiB (hot), {d} MiB (cold); host VmHWM {d} MiB (hot), {d} MiB (cold), RssAnon {d} MiB\n", .{ peak[0] >> 20, peak[1] >> 20, host[0].hwm >> 10, host[1].hwm >> 10, host[1].anon >> 10 });
check.pass("ling-pack layer {d}: every expert's packed words and scales equal the host packers' bytes", .{i});
}
6 changes: 4 additions & 2 deletions zig/tests/cuda/main.zig
Original file line number Diff line number Diff line change
Expand Up @@ -113,12 +113,13 @@ const usage =
\\ ling-synth <dir> [--format bf16|fp8|nvfp4] [--layers N] a tiny Ling-3.1 checkpoint with the real names and config schema
\\ ling-weights <dir> every layer of a Ling checkpoint loaded: projections vs float64, small tensors byte for byte
\\ ling-forward-synth <dir> <ref> [picks] a ling-synth checkpoint's forward vs oracle/ling_forward.py; cuts, windows, batches
\\ ling-layer-real <dir> <fixture> one real Ling-3.1 layer vs HF's captured output (oracle/ling_layer.py); exactness
\\ ling-layer-real <dir> <fixture> [dump] one real Ling-3.1 layer vs HF's captured output (oracle/ling_layer.py); exactness
\\ ling-clamp <dir> Ling's SwiGLU order min(silu(g), L): glue and the dir's grouped experts vs float64
\\ ling-clamp-old <dir> <fatbins> the grouped expert instances vs an older build's fatbins, byte for byte
\\ ling-lanes <dir> <out> [ref] [--layers a,b] [--mtp] Ling's lane backend: chunked, drafted, resumed, concurrent == plain
\\ ling-mtp-real <dir> <fixture> the real MTP layer vs HF's (oracle/ling_mtp.py); cut, window == decode rows
\\ ling-weights-real <dir> <refdir> real Ling-3.1 layers 0, 4, 7 (4 experts) vs float64 and torch (oracle/ling_weights.py)
\\ ling-pack <dir> <layer> [experts] one MoE layer's experts: read, pack and cold load timed; bytes vs the host packers
\\
;

Expand Down Expand Up @@ -227,12 +228,13 @@ fn run(gpu: check.Gpu, cmd: []const u8, rest: []const [:0]const u8) !void {
if (std.mem.eql(u8, cmd, "ling-synth")) return ling_synth.run(gpu, rest);
if (std.mem.eql(u8, cmd, "ling-weights")) return ling_weights.run(gpu, try arg(rest, 0));
if (std.mem.eql(u8, cmd, "ling-forward-synth")) return @import("ling_forward_synth.zig").run(gpu, try arg(rest, 0), try arg(rest, 1), if (rest.len > 2) rest[2] else null);
if (std.mem.eql(u8, cmd, "ling-layer-real")) return @import("ling_layer_real.zig").run(gpu, try arg(rest, 0), try arg(rest, 1));
if (std.mem.eql(u8, cmd, "ling-layer-real")) return @import("ling_layer_real.zig").run(gpu, try arg(rest, 0), try arg(rest, 1), if (rest.len > 2) rest[2] else null);
if (std.mem.eql(u8, cmd, "ling-clamp")) return @import("ling_clamp.zig").run(gpu, try arg(rest, 0));
if (std.mem.eql(u8, cmd, "ling-clamp-old")) return @import("ling_clamp.zig").old(gpu, try arg(rest, 0), try arg(rest, 1));
if (std.mem.eql(u8, cmd, "ling-mtp-real")) return @import("ling_mtp_real.zig").run(gpu, try arg(rest, 0), try arg(rest, 1));
if (std.mem.eql(u8, cmd, "ling-lanes")) return @import("ling_lanes.zig").run(gpu, rest);
if (std.mem.eql(u8, cmd, "ling-weights-real")) return ling_real.run(gpu, try arg(rest, 0), try arg(rest, 1));
if (std.mem.eql(u8, cmd, "ling-pack")) return @import("ling_pack.zig").run(gpu, rest);
if (std.mem.eql(u8, cmd, "glm-lanes-concurrent")) return glm_lanes_tests.concurrentCheck(gpu, try arg(rest, 0), try arg(rest, 1), try std.fmt.parseInt(c_int, try arg(rest, 2), 10), try std.fmt.parseInt(c_int, try arg(rest, 3), 10), try arg(rest, 4));
std.debug.print("{s}", .{usage});
return error.UnknownCommand;
Expand Down