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

- CUDA kernels: ERNIE 5.5's router (`tf_ernie55_route`, in a new `ernie5_5_moe` image): a row's 512 experts scored from its two routers' logits as sigmoid(l0) + sigmoid(l1), the top 10 of score + bias by core's row select (ties to the lower id), and the picks' weights as their scores over their sum (at least 1e-20) times each expert's scale, the picks and weights core's combine takes; under the kernel contract against float64; nothing launches it yet, so served output is unchanged (#5368, part of #4926). Thanks to @Bizuayeu.

## 1.3.8

- Inkling 2 Mini EXL3 on Metal: `--parallel` lanes are capped to what the stream-state pool holds for short requests, so a 16 GB Mac at `--parallel 8` runs 5 lanes instead of failing extra streams with InklingStateFull; larger Macs keep every lane. Thanks @grantoverton.
Expand Down
7 changes: 7 additions & 0 deletions docs/kernel-contract.md
Original file line number Diff line number Diff line change
Expand Up @@ -1043,6 +1043,13 @@ between torch's form at both ends of the fp32 sigmoid's error (core's `headGateR
8,192 values, 64 of DSA's 16,384, 4 of a TP=2 rank's 4,096, and widths around a block's 2,048; with no sums, gate 4
does not apply (`ernie5_5-out-gate`; two controls: the sigmoid left in fp32 for the product, as core's `tf_gate_rows`
has it, which only the ends catch, and the sigmoid of -g).
CUDA also checks ERNIE 5.5's router (`ernie5_5/moe.cu`, `tf_ernie55_route`): a row's 512 experts scored from its two
routers' fp32 logits as sigmoid(l0) + sigmoid(l1), the top 10 of score + bias by core's row select (ties to the lower
id, a NaN never picked, the picks in ascending ids), and each pick's score over the picks' sum, at least 1e-20, times
its expert's scale, as vLLM-ERNIE's routing forms them. The picks must rank as the host's (`ernie5_5/route.zig`), with
only near-ties swapped and exact ties to the lower id, and the weights must be within 2^-20 of its float64 ones, at
a decode row, a verify window and a prompt chunk (`ernie5_5-moe`; two controls: one sigmoid of the two logits
summed, and weights from score + bias).

CPU: Qwen3.5-2B's affine projection (4 bits, groups of 64, `cpu_kernels.zig`) at the widths the 2B calls it, one row
to a 128-row prompt chunk, registered once for each chain count of its projection classes (16; 32 for the delta rule's
Expand Down
1 change: 1 addition & 0 deletions zig/build/cuda.zig
Original file line number Diff line number Diff line change
Expand Up @@ -145,6 +145,7 @@ pub fn targets(b: *std.Build, target: std.Build.ResolvedTarget, optimize: std.bu
runner.addImport("ernie5_5_hca_cuda", b.createModule(.{ .root_source_file = b.path("zig/src/families/ernie5_5/cuda_hca.zig"), .target = target, .optimize = optimize, .imports = &.{.{ .name = "cuda", .module = cuda }} }));
const ernie_st = b.createModule(.{ .root_source_file = b.path("zig/tests/cuda/ernie5_5_synth_st.zig"), .target = target, .optimize = optimize, .imports = &.{.{ .name = "core", .module = mods.core }} });
runner.addImport("ernie5_5_synth", b.createModule(.{ .root_source_file = b.path("zig/src/families/ernie5_5/synth.zig"), .target = target, .optimize = optimize, .link_libc = true, .imports = &.{.{ .name = "safetensors", .module = ernie_st }} }));
runner.addImport("ernie5_5_moe_cuda", b.createModule(.{ .root_source_file = b.path("zig/src/families/ernie5_5/cuda_moe.zig"), .target = target, .optimize = optimize, .imports = &.{.{ .name = "cuda", .module = cuda }} }));
runner.addImport("gemma4_cuda", @import("gemma4_cuda.zig").module(b, target, optimize, cuda, mods.core, mods.lanes));
runner.addImport("spark25", @import("spark25.zig").module(b, target, optimize, cuda, mods.core, mods.lanes));
// the served family and its engine, for the dots runner
Expand Down
1 change: 1 addition & 0 deletions zig/build/cuda_kernels.zig
Original file line number Diff line number Diff line change
Expand Up @@ -179,6 +179,7 @@ pub const kernels = [_]Kernel{
.{ .name = "hy4_mla_c2", .src = "hy4_flash/mla_c2", .flags = glue },
.{ .name = "ernie5_5_hca", .src = "ernie5_5/hca", .flags = &.{"-O3"} }, // ours: ERNIE 5.5's HCA compressor
.{ .name = "ernie5_5_hca_attn", .src = "ernie5_5/hca_attn", .flags = &.{"-O3"} }, // ours: ERNIE 5.5's HCA attention
.{ .name = "ernie5_5_moe", .src = "ernie5_5/moe", .flags = &.{"-O3"} }, // ours: ERNIE 5.5's router
.{ .name = "minimax_m3", .flags = glue }, // ours: MiniMax-M3.1-Flash's glue (norms, RoPE prep, routing, DSpark, tower RoPE)
.{ .name = "minimax_m3_attn", .flags = glue }, // ours: MiniMax-M3.1-Flash's indexer and block-sparse attention
.{ .name = "idol", .flags = glue }, // ours: Idol's denoiser glue and its fp16 head-64 attention
Expand Down
68 changes: 68 additions & 0 deletions zig/kernels/cuda/ernie5_5/moe.cu
Original file line number Diff line number Diff line change
@@ -0,0 +1,68 @@
// ERNIE 5.5's router: two routers' logits as two sigmoid scores summed, the top k of score + bias, weights scaled.

#include <math.h>

#include "common/glue_math.cuh"
#include "common/topk_rows.cuh"

namespace ernie55r {

constexpr int E = 512, T = 64, K = 32;

enum Fault { none, one_sigmoid, biased_weights };

// Row blockIdx.x: logits [2 E] ls apart (the first router's row, then the second's); picks and weights k a row.
template <Fault F>
__device__ __forceinline__ void route(const float* __restrict__ logits, long long ls, const float* __restrict__ bias,
const float* __restrict__ scale, int* __restrict__ ids, float* __restrict__ wts,
int k) {
__shared__ __align__(16) float sel[E];
__shared__ float score[E];
__shared__ int pick[K];
const long long row = blockIdx.x;
const float* l = logits + row * ls;
for (int e = threadIdx.x; e < E; e += T) {
// sigmoid(l0) + sigmoid(l1) (the control: one sigmoid of l0 + l1), then + bias; a NaN ranks as -inf
const float s = F == one_sigmoid ? tf_glue::tf_sigmoid(__fadd_rn(l[e], l[E + e]))
: __fadd_rn(tf_glue::tf_sigmoid(l[e]), tf_glue::tf_sigmoid(l[E + e]));
const float v = __fadd_rn(s, bias[e]);
score[e] = s;
sel[e] = v == v ? v : -INFINITY;
}
__syncthreads();
tf_topk::select_row<T>(sel, E, k, pick); // the k best, ties to the lower id, in ascending ids
__syncthreads();
if (threadIdx.x != 0) return;
// the picks' scores (the control: score + bias) summed in id order, over max(sum, 1e-20), times the expert's scale
float total = 0.0f;
for (int j = 0; j < k; ++j) total = __fadd_rn(total, F == biased_weights ? sel[pick[j]] : score[pick[j]]);
const float d = fmaxf(total, 1e-20f);
for (int j = 0; j < k; ++j) {
const int e = pick[j];
ids[row * k + j] = e;
wts[row * k + j] = __fmul_rn(__fdiv_rn(F == biased_weights ? sel[e] : score[e], d), scale[e]);
}
}

} // namespace ernie55r

extern "C" __global__ void __launch_bounds__(64)
tf_ernie55_route(const float* __restrict__ logits, long long ls, const float* __restrict__ bias,
const float* __restrict__ scale, int* __restrict__ ids, float* __restrict__ wts, int k) {
ernie55r::route<ernie55r::none>(logits, ls, bias, scale, ids, wts, k);
}

// The contract's planted controls: one sigmoid of the two logits summed, and weights from score + bias.
extern "C" __global__ void __launch_bounds__(64)
tf_ctl_ernie55_route_one_sigmoid(const float* __restrict__ logits, long long ls, const float* __restrict__ bias,
const float* __restrict__ scale, int* __restrict__ ids, float* __restrict__ wts,
int k) {
ernie55r::route<ernie55r::one_sigmoid>(logits, ls, bias, scale, ids, wts, k);
}

extern "C" __global__ void __launch_bounds__(64)
tf_ctl_ernie55_route_biased_weights(const float* __restrict__ logits, long long ls,
const float* __restrict__ bias, const float* __restrict__ scale,
int* __restrict__ ids, float* __restrict__ wts, int k) {
ernie55r::route<ernie55r::biased_weights>(logits, ls, bias, scale, ids, wts, k);
}
3 changes: 2 additions & 1 deletion zig/src/core/contract/ernie5_5_records.zig
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
//! ERNIE 5.5 CUDA launch records: MultiMax, DSA keys/lists and mHC and HCA.
//! ERNIE 5.5 CUDA launch records: MultiMax, DSA keys/lists, mHC, HCA and the router.
const registry = @import("registry.zig");

/// nvcc 13.0's usage (nvcc -cubin per SM at the image's flags), the compiler of the release fatbins.
Expand All @@ -18,6 +18,7 @@ pub const cuda = [_]registry.CudaRecord{
.{ .launch = .{ .name = "ernie5_5 index tf_ernie55_window_merge", .symbol = "tf_ernie55_window_merge", .image = "ernie5_5_index", .threads = 256 }, .usage = .{ .{ .regs = 24, .static = 4, .bound = 256 }, .{ .regs = 24, .static = 4, .bound = 256 }, .{ .regs = 24, .static = 4, .bound = 256 }, .{ .regs = 40, .static = 4, .bound = 256 }, .{ .regs = 40, .static = 4, .bound = 256 } } },
.{ .launch = .{ .name = "ernie5_5 mhc tf_ernie55_mhc_pre", .symbol = "tf_ernie55_mhc_pre", .image = "ernie5_5_mhc", .threads = 256 }, .usage = .{ .{ .regs = 40, .static = 948, .bound = 256 }, .{ .regs = 40, .static = 948, .bound = 256 }, .{ .regs = 40, .static = 948, .bound = 256 }, .{ .regs = 40, .static = 948, .bound = 256 }, .{ .regs = 40, .static = 948, .bound = 256 } } },
.{ .launch = .{ .name = "ernie5_5 mhc tf_ernie55_mhc_pre_broadcast", .symbol = "tf_ernie55_mhc_pre_broadcast", .image = "ernie5_5_mhc", .threads = 256 }, .usage = .{ .{ .regs = 32, .static = 948, .bound = 256 }, .{ .regs = 40, .static = 948, .bound = 256 }, .{ .regs = 40, .static = 948, .bound = 256 }, .{ .regs = 40, .static = 948, .bound = 256 }, .{ .regs = 40, .static = 948, .bound = 256 } } },
.{ .launch = .{ .name = "ernie5_5 moe tf_ernie55_route", .symbol = "tf_ernie55_route", .image = "ernie5_5_moe", .threads = 64 }, .usage = .{ .{ .regs = 40, .static = 5272, .bound = 64 }, .{ .regs = 45, .static = 5272, .bound = 64 }, .{ .regs = 45, .static = 5272, .bound = 64 }, .{ .regs = 50, .static = 5272, .bound = 64 }, .{ .regs = 50, .static = 5272, .bound = 64 } } },
};

test "ERNIE 5.5 CUDA: every launch is in the live registry and fits every SM" {
Expand Down
1 change: 1 addition & 0 deletions zig/src/cuda/kernels.zig
Original file line number Diff line number Diff line change
Expand Up @@ -130,6 +130,7 @@ pub const ernie5_5_index: []const u8 = if (available) &Blob("fatbin_ernie5_5_ind
pub const ernie5_5_mhc: []const u8 = if (available) &Blob("fatbin_ernie5_5_mhc").bytes else &.{};
pub const ernie5_5_hca: []const u8 = if (available) &Blob("fatbin_ernie5_5_hca").bytes else &.{};
pub const ernie5_5_hca_attn: []const u8 = if (available) &Blob("fatbin_ernie5_5_hca_attn").bytes else &.{};
pub const ernie5_5_moe: []const u8 = if (available) &Blob("fatbin_ernie5_5_moe").bytes else &.{};
pub const inkling2_rows: []const u8 = if (available) &Blob("fatbin_inkling2_rows").bytes else &.{};
pub const inkling2_dspark: []const u8 = if (available) &Blob("fatbin_inkling2_dspark").bytes else &.{};
pub const inkling2_dflash2: []const u8 = if (available) &Blob("fatbin_inkling2_dflash2").bytes else &.{};
Expand Down
37 changes: 37 additions & 0 deletions zig/src/families/ernie5_5/cuda_moe.zig
Original file line number Diff line number Diff line change
@@ -0,0 +1,37 @@
//! ERNIE 5.5's MoE kernels (ernie5_5/moe.cu): the router's picks and weights, as core's combine takes them.
const cuda = @import("cuda");
pub const route = @import("route.zig");

pub const threads = 64;

pub const Moe = struct {
mod: cuda.Module,
route_fn: cuda.Function,

pub fn load(d: *const cuda.Driver) !Moe {
var mod = try cuda.Module.load(d, cuda.kernels.ernie5_5_moe);
errdefer mod.unload();
return .{ .mod = mod, .route_fn = try mod.function("tf_ernie55_route") };
}

pub fn unload(x: *Moe) void {
x.mod.unload();
}

/// fp32 logits [rows][2 x 512] (ls apart), f32 bias and scale [512] into int32 ids and fp32 weights [rows][k].
pub fn picks(x: *const Moe, s: cuda.Stream, logits: u64, bias: u64, scale: u64, ids: u64, wts: u64, sh: route.Shape) !void {
try launch(x.route_fn, s, logits, bias, scale, ids, wts, sh);
}
};

/// `f`, tf_ernie55_route or an entry of the image with its arguments, one row a block.
pub fn launch(f: cuda.Function, s: cuda.Stream, logits: u64, bias: u64, scale: u64, ids: u64, wts: u64, sh: route.Shape) !void {
try route.check(sh);
if (sh.rows == 0) return;
var a: cuda.Args = .{};
a.add(logits);
a.add(@as(i64, @intCast(sh.ls)));
inline for (.{ bias, scale, ids, wts }) |v| a.add(v);
a.add(@as(c_int, @intCast(sh.k)));
try cuda.launch.launch(f, .{ .grid = .{ .x = @intCast(sh.rows) }, .block = .{ .x = threads } }, s, &a);
}
1 change: 1 addition & 0 deletions zig/src/families/ernie5_5/host_test.zig
Original file line number Diff line number Diff line change
Expand Up @@ -15,4 +15,5 @@ test {
_ = @import("hca_test.zig");
_ = @import("synth.zig");
_ = @import("synth_test.zig");
_ = @import("route_test.zig");
}
55 changes: 55 additions & 0 deletions zig/src/families/ernie5_5/route.zig
Original file line number Diff line number Diff line change
@@ -0,0 +1,55 @@
//! ERNIE 5.5's router (vLLM-ERNIE's ernie5_5_routing): two sigmoid scores, the top k of score + bias, weights scaled.
const std = @import("std");

/// The released router: 512 experts, each scored from two logits (gate.weight's row, then weight_1's), top 10.
pub const experts = 512;
pub const topk = 10;
/// The most picks a row may ask for (the kernel's shared slots).
pub const most_topk = 32;

/// rows of 2 x experts fp32 logits, ls apart; picks (int32) and weights (fp32) k a row.
pub const Shape = struct { rows: usize, k: usize = topk, ls: usize = 2 * experts };

/// k picks from 1 to most_topk, logit rows at least both routers wide, and rows that fit the grid.
pub fn check(sh: Shape) error{RouteShape}!void {
if (sh.k == 0 or sh.k > most_topk or sh.ls < 2 * experts) return error.RouteShape;
if (sh.rows > std.math.maxInt(i32)) return error.RouteShape;
}

pub fn sigmoid(v: f64) f64 {
return 1 / (1 + @exp(-v));
}

/// Expert e's score: sigmoid of the first router's logit plus sigmoid of the second's.
pub fn score(l: []const f32, e: usize) f64 {
return sigmoid(l[e]) + sigmoid(l[experts + e]);
}

/// What expert e is ranked by: its score plus its correction bias, a NaN as -inf (never picked ahead of a number).
pub fn rank(l: []const f32, bias: []const f32, e: usize) f64 {
const v = score(l, e) + bias[e];
return if (std.math.isNan(v)) -std.math.inf(f64) else v;
}

/// A row in float64: the k best ranks (ties to the lower id) in ascending ids, weights score / max(sum, 1e-20) * scale.
pub fn route(l: []const f32, bias: []const f32, scale: []const f32, ids: []u32, w: []f64) void {
var taken: [experts]bool = @splat(false);
for (ids) |*id| {
var best: usize = experts;
for (0..experts) |e| {
if (taken[e]) continue;
if (best == experts or rank(l, bias, e) > rank(l, bias, best)) best = e;
}
taken[best] = true;
id.* = @intCast(best);
}
std.mem.sort(u32, ids, {}, std.sort.asc(u32));
weights(l, scale, ids, w);
}

/// The picks' weights: each score over the picks' summed scores (at least 1e-20), times the expert's scale.
pub fn weights(l: []const f32, scale: []const f32, ids: []const u32, w: []f64) void {
var total: f64 = 0;
for (ids) |id| total += score(l, id);
for (w, ids) |*x, id| x.* = score(l, id) / @max(total, 1e-20) * scale[id];
}
84 changes: 84 additions & 0 deletions zig/src/families/ernie5_5/route_test.zig
Original file line number Diff line number Diff line change
@@ -0,0 +1,84 @@
const std = @import("std");
const r = @import("route.zig");

const e = r.experts;

/// vLLM-ERNIE's _ernie5_5_routing_torch: experts by score + bias (then id), the first k, weighed without the bias.
fn vendor(l: []const f32, bias: []const f32, scale: []const f32, ids: []u32, w: []f64) void {
var order: [e]u32 = undefined;
for (&order, 0..) |*o, i| o.* = @intCast(i);
const Ctx = struct { l: []const f32, bias: []const f32 };
std.mem.sort(u32, &order, Ctx{ .l = l, .bias = bias }, struct {
fn before(c: Ctx, a: u32, b: u32) bool {
const x = r.rank(c.l, c.bias, a);
const y = r.rank(c.l, c.bias, b);
return x > y or (x == y and a < b);
}
}.before);
@memcpy(ids, order[0..ids.len]);
std.mem.sort(u32, ids, {}, std.sort.asc(u32));
var sum: f64 = 0;
for (ids) |id| sum += r.sigmoid(l[id]) + r.sigmoid(l[e + id]);
for (w, ids) |*x, id| x.* = (r.sigmoid(l[id]) + r.sigmoid(l[e + id])) / @max(sum, 1e-20) * scale[id];
}

fn fill(seed: u64, l: *[2 * e]f32, bias: *[e]f32, scale: *[e]f32) void {
var prng = std.Random.DefaultPrng.init(seed);
const rng = prng.random();
for (l) |*x| x.* = rng.floatNorm(f32) * 2;
for (bias, 0..) |*b, i| b.* = if (i % 3 == 0) 0.3 * rng.float(f32) else 0;
for (scale) |*s| s.* = 0.5 + rng.float(f32) * 2;
}

test "the router is vLLM-ERNIE's: two sigmoids summed, picked by score + bias, weighed without it, scaled per expert" {
var l: [2 * e]f32 = undefined;
var bias: [e]f32 = undefined;
var scale: [e]f32 = undefined;
for (0..4) |seed| {
fill(seed, &l, &bias, &scale);
var ids: [r.topk]u32 = undefined;
var w: [r.topk]f64 = undefined;
var vi: [r.topk]u32 = undefined;
var vw: [r.topk]f64 = undefined;
r.route(&l, &bias, &scale, &ids, &w);
vendor(&l, &bias, &scale, &vi, &vw);
try std.testing.expectEqualSlices(u32, &vi, &ids);
for (vw, w) |v, g| try std.testing.expectApproxEqRel(v, g, 1e-14);
}
// the bias picks an expert its score alone would not, and its weight leaves the bias out
@memset(&l, -4);
for (0..r.topk) |i| l[i] = 3;
@memset(&bias, 0);
bias[100] = 5;
@memset(&scale, 1);
var ids: [r.topk]u32 = undefined;
var w: [r.topk]f64 = undefined;
r.route(&l, &bias, &scale, &ids, &w);
try std.testing.expectEqual(@as(u32, 100), ids[r.topk - 1]);
try std.testing.expect(w[r.topk - 1] < 0.01);
}

test "ties go to the lower id, a NaN is never picked ahead of a number, and tiny scores divide by 1e-20" {
var l: [2 * e]f32 = @splat(-30);
var bias: [e]f32 = @splat(0);
const scale: [e]f32 = @splat(2);
for (1..r.topk) |i| l[i] = 4;
l[20] = 1;
l[22] = 1; // 20 and 22 tie for the last pick
l[0] = std.math.nan(f32);
bias[0] = 9;
var ids: [r.topk]u32 = undefined;
var w: [r.topk]f64 = undefined;
r.route(&l, &bias, &scale, &ids, &w);
try std.testing.expectEqualSlices(u32, &.{ 1, 2, 3, 4, 5, 6, 7, 8, 9, 20 }, &ids);
@memset(&l, -100);
r.route(&l, &bias, &scale, &ids, &w);
try std.testing.expectApproxEqRel(2 * r.sigmoid(-100) / 1e-20 * 2, w[0], 1e-12);
}

test "check refuses no picks, more than the kernel holds, and logit rows narrower than both routers" {
try r.check(.{ .rows = 300 });
try std.testing.expectError(error.RouteShape, r.check(.{ .rows = 1, .k = 0 }));
try std.testing.expectError(error.RouteShape, r.check(.{ .rows = 1, .k = r.most_topk + 1 }));
try std.testing.expectError(error.RouteShape, r.check(.{ .rows = 1, .ls = 2 * e - 1 }));
}
Loading
Loading