Skip to content
Merged
Show file tree
Hide file tree
Changes from 1 commit
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
Prev Previous commit
Next Next commit
gemma4 CUDA: per-layer inputs in Gemma's own image, gemma4_ple.cu, ga…
…ted by the contract (#1222)

tf_gemma4_ple_rows leaves act_rows. Its contract test checks a float64 reference within a derived bound and
the host steps' bits, plants two controls (no norm, no token scale), and kernel-contract takes words that
filter the kernels and their live limits.
  • Loading branch information
jschmied authored and ashhart committed Nov 5, 2026
commit b088e5213e016cf315841731caebcbb2dfd0dbbe
1 change: 1 addition & 0 deletions zig/build/cuda_kernels.zig
Original file line number Diff line number Diff line change
Expand Up @@ -113,6 +113,7 @@ pub const kernels = [_]Kernel{
.{ .name = "moss_image", .flags = glue }, // ours: MOSS-Image's modulated norm, q/k rotary, situ, gated add
.{ .name = "tree_round", .flags = &.{"-O3"} }, // ours: verified tree rounds for every family (cuda/tree_round.zig)
.{ .name = "act_rows", .flags = &.{"-O3"} }, // ours: SwiGLU, output gates, group sums (cuda/act_rows.zig)
.{ .name = "gemma4_ple", .flags = &.{"-O3"} }, // ours: Gemma 4 E-series per-layer inputs (gemma4/cuda_ple.zig)
.{ .name = "gdn_prep", .flags = &.{"-O3"} }, // ours: Gated DeltaNet conv, norms, g and beta (cuda/gdn_prep.zig)
.{ .name = "qk_rows", .flags = &.{"-O3"} }, // ours: QK norm, RoPE and the cache write (cuda/qk_rows.zig)
.{ .name = "qmmf", .flags = &.{"-O3"} }, // nvfp4/qmmf.cu's device code (FP8G, FP4), tensorfold_nvfp4_v3
Expand Down
30 changes: 0 additions & 30 deletions zig/kernels/cuda/act_rows.cu
Original file line number Diff line number Diff line change
Expand Up @@ -173,33 +173,3 @@ extern "C" __global__ void __launch_bounds__(tf_act_l2::NT) tf_swiglu_l2_rows(co
__nv_bfloat16* out, int n, float eps) {
tf_act_l2::swiglu_rows<tf_act_l2::GS | tf_act_l2::US | tf_act_l2::PROD>(g, g_ld, u, u_ld, sug, suu, out, n, eps);
}

// Gemma 4 E-series per-layer inputs in layer_input.zig's steps (scale, 256-wide rms, + table * token, * mix).
extern "C" __global__ void __launch_bounds__(64) tf_ple_rows(const __nv_bfloat16* __restrict__ p,
const __nv_bfloat16* __restrict__ t,
const __nv_bfloat16* __restrict__ w,
__nv_bfloat16* __restrict__ out, int parts, float scale,
float token, float mix, float eps) {
__shared__ float sums[2];
const long long base = ((long long)blockIdx.x * parts + blockIdx.y) * 256 + threadIdx.x * 4;
const int lane = threadIdx.x & 31;
float x[4];
float acc = 0.0f;
for (int i = 0; i < 4; i++) {
x[i] = __bfloat162float(__float2bfloat16_rn(__fmul_rn(__bfloat162float(p[base + i]), scale)));
acc = __fadd_rn(acc, __fmul_rn(x[i], x[i]));
}
for (int s = 1; s < 32; s <<= 1) acc = __fadd_rn(acc, __shfl_xor_sync(0xffffffffu, acc, s));
if (lane == 0) sums[threadIdx.x >> 5] = acc;
__syncthreads();
const float mean = __fadd_rn(__fdiv_rn(__fadd_rn(sums[0], sums[1]), 256.0f), eps);
const float inv = (float)(1.0 / sqrt((double)mean));
for (int i = 0; i < 4; i++) {
const int k = threadIdx.x * 4 + i;
const float n = __bfloat162float(__float2bfloat16_rn(__fmul_rn(x[i], inv)));
const float y = __bfloat162float(__float2bfloat16_rn(__fmul_rn(__bfloat162float(w[k]), n)));
const float tt = __bfloat162float(__float2bfloat16_rn(__fmul_rn(__bfloat162float(t[base + i]), token)));
const float sum = __bfloat162float(__float2bfloat16_rn(__fadd_rn(y, tt)));
out[base + i] = __float2bfloat16_rn(__fmul_rn(sum, mix));
}
}
9 changes: 9 additions & 0 deletions zig/kernels/cuda/contract_controls.cu
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@
#include <math.h>
#include <stdint.h>
#include "common/reduce.cuh"
#include "gemma4_ple.cuh"

__device__ __forceinline__ float tf_ctl_x(const __nv_bfloat16* x, int64_t i) { return __bfloat162float(x[i]); }

Expand Down Expand Up @@ -533,3 +534,11 @@ TF_CTL_EXL3_GROUPED(tf_ctl_exl3_grouped_old_2, 2, tf_exl3::PLAIN)
TF_CTL_EXL3_GROUPED(tf_ctl_exl3_grouped_skip, 2, tf_exl3::SKIP)
TF_CTL_EXL3_GROUPED(tf_ctl_exl3_grouped_stale, 2, tf_exl3::STALE)
#undef TF_CTL_EXL3_GROUPED

// Gate 3: gemma4_ple.cu's tf_gemma4_ple_rows with one step dropped (tf_ple::DROP_*); the shapes gate must go red.
extern "C" __global__ void __launch_bounds__(64) tf_ctl_ple_rows(const __nv_bfloat16* p, const __nv_bfloat16* t,
const __nv_bfloat16* w, __nv_bfloat16* out, int parts,
float scale, float token, float mix, float eps,
int drop) {
tf_ple::rows(p, t, w, out, parts, scale, token, mix, eps, drop);
}
13 changes: 13 additions & 0 deletions zig/kernels/cuda/gemma4_ple.cu
Original file line number Diff line number Diff line change
@@ -0,0 +1,13 @@
// Gemma 4's own image: the E-series per-layer inputs (cuda_ple.zig); the steps are gemma4_ple.cuh's.

#include <cuda_bf16.h>
#include "gemma4_ple.cuh"

// out [rows, parts 256] from projected rows p and table rows t (packed alike); 64 threads a (row, part).
extern "C" __global__ void __launch_bounds__(64) tf_gemma4_ple_rows(const __nv_bfloat16* __restrict__ p,
const __nv_bfloat16* __restrict__ t,
const __nv_bfloat16* __restrict__ w,
__nv_bfloat16* __restrict__ out, int parts,
float scale, float token, float mix, float eps) {
tf_ple::rows(p, t, w, out, parts, scale, token, mix, eps, 0);
}
39 changes: 39 additions & 0 deletions zig/kernels/cuda/gemma4_ple.cuh
Original file line number Diff line number Diff line change
@@ -0,0 +1,39 @@
// Gemma 4 E-series per-layer inputs in layer_input.zig's steps, shared by gemma4_ple.cu and the contract's controls.
#pragma once
#include <cuda_bf16.h>

namespace tf_ple {

// Controls only: drop a step the contract's shapes gate must catch.
constexpr int DROP_NORM = 1;
constexpr int DROP_TOKEN = 2;

__device__ __forceinline__ float rb(float v) { return __bfloat162float(__float2bfloat16_rn(v)); }

// A block of 64 a (row, part): MLX's one-row rms_norm sums (4-value chains, butterflies); p, t, out packed alike.
__device__ __forceinline__ void rows(const __nv_bfloat16* __restrict__ p, const __nv_bfloat16* __restrict__ t,
const __nv_bfloat16* __restrict__ w, __nv_bfloat16* __restrict__ out, int parts,
float scale, float token, float mix, float eps, int drop) {
__shared__ float sums[2];
const long long base = ((long long)blockIdx.x * parts + blockIdx.y) * 256 + threadIdx.x * 4;
const int lane = threadIdx.x & 31;
float x[4];
float acc = 0.0f;
for (int i = 0; i < 4; i++) {
x[i] = rb(__fmul_rn(__bfloat162float(p[base + i]), scale));
acc = __fadd_rn(acc, __fmul_rn(x[i], x[i]));
}
for (int s = 1; s < 32; s <<= 1) acc = __fadd_rn(acc, __shfl_xor_sync(0xffffffffu, acc, s));
if (lane == 0) sums[threadIdx.x >> 5] = acc;
__syncthreads();
const float mean = __fadd_rn(__fdiv_rn(__fadd_rn(sums[0], sums[1]), 256.0f), eps);
const float inv = (drop & DROP_NORM) ? 1.0f : (float)(1.0 / sqrt((double)mean));
for (int i = 0; i < 4; i++) {
const int k = threadIdx.x * 4 + i;
const float y = rb(__fmul_rn(__bfloat162float(w[k]), rb(__fmul_rn(x[i], inv))));
const float tt = rb(__fmul_rn(__bfloat162float(t[base + i]), (drop & DROP_TOKEN) ? 1.0f : token));
out[base + i] = __float2bfloat16_rn(__fmul_rn(rb(__fadd_rn(y, tt)), mix));
}
}

} // namespace tf_ple
4 changes: 2 additions & 2 deletions zig/src/core/contract/gemma_cuda_records.zig
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
//! Gemma 4's CUDA launch records: act_rows, embed_rows, qk_rows, the wide LayerNorm and picks to ids.
//! Gemma 4's CUDA launch records: act_rows, embed_rows, qk_rows, the wide LayerNorm, picks to ids, gemma4_ple.
const CudaRecord = @import("registry.zig").CudaRecord;

pub const cuda = [_]CudaRecord{
Expand All @@ -13,5 +13,5 @@ pub const cuda = [_]CudaRecord{
.{ .launch = .{ .name = "act_rows tf_swiglu_rows_round 128 threads", .symbol = "tf_swiglu_rows_round", .image = "act_rows", .threads = 128 }, .usage = .{ .{ .regs = 34, .static = 0, .bound = 256 }, .{ .regs = 34, .static = 0, .bound = 256 }, .{ .regs = 34, .static = 0, .bound = 256 }, .{ .regs = 34, .static = 0, .bound = 256 }, .{ .regs = 34, .static = 0, .bound = 256 } } },
.{ .launch = .{ .name = "act_rows tf_softcap_rows 256 threads", .symbol = "tf_softcap_rows", .image = "act_rows", .threads = 256 }, .usage = .{ .{ .regs = 24, .static = 0, .bound = 256 }, .{ .regs = 24, .static = 0, .bound = 256 }, .{ .regs = 24, .static = 0, .bound = 256 }, .{ .regs = 25, .static = 0, .bound = 256 }, .{ .regs = 25, .static = 0, .bound = 256 } } },
.{ .launch = .{ .name = "act_rows tf_softcap_rows 128 threads", .symbol = "tf_softcap_rows", .image = "act_rows", .threads = 128 }, .usage = .{ .{ .regs = 24, .static = 0, .bound = 256 }, .{ .regs = 24, .static = 0, .bound = 256 }, .{ .regs = 24, .static = 0, .bound = 256 }, .{ .regs = 25, .static = 0, .bound = 256 }, .{ .regs = 25, .static = 0, .bound = 256 } } },
.{ .launch = .{ .name = "act_rows tf_ple_rows", .symbol = "tf_ple_rows", .image = "act_rows", .threads = 64 }, .usage = .{ .{ .regs = 24, .static = 8, .bound = 64 }, .{ .regs = 26, .static = 8, .bound = 64 }, .{ .regs = 26, .static = 8, .bound = 64 }, .{ .regs = 26, .static = 8, .bound = 64 }, .{ .regs = 26, .static = 8, .bound = 64 } } },
.{ .launch = .{ .name = "gemma4_ple tf_gemma4_ple_rows", .symbol = "tf_gemma4_ple_rows", .image = "gemma4_ple", .threads = 64 }, .usage = .{ .{ .regs = 24, .static = 8, .bound = 64 }, .{ .regs = 26, .static = 8, .bound = 64 }, .{ .regs = 26, .static = 8, .bound = 64 }, .{ .regs = 26, .static = 8, .bound = 64 }, .{ .regs = 26, .static = 8, .bound = 64 } } },
};
17 changes: 1 addition & 16 deletions zig/src/cuda/act_rows.zig
Original file line number Diff line number Diff line change
Expand Up @@ -35,13 +35,12 @@ pub const ActRows = struct {
swiglu_l2_fn: Function,
head_gate_fn: Function,
gelu_erf_fn: Function,
ple_fn: Function,

pub fn load(d: *const Driver) !ActRows {
if (!kernels.available) return error.BuiltWithoutKernels;
var mod = try Module.load(d, kernels.act_rows);
errdefer mod.unload();
return .{ .mod = mod, .swiglu_fn = try mod.function("tf_swiglu_rows"), .gate_fn = try mod.function("tf_gate_rows"), .sums_fn = try mod.function("tf_group_sums_rows"), .dconv_fn = try mod.function("tf_dconv_rows"), .geglu_fn = try mod.function("tf_geglu_rows"), .swiglu_round_fn = try mod.function("tf_swiglu_rows_round"), .softcap_fn = try mod.function("tf_softcap_rows"), .gate_l2_fn = try mod.function("tf_gate_l2_rows"), .swiglu_l2_fn = try mod.function("tf_swiglu_l2_rows"), .head_gate_fn = try mod.function("tf_head_gate_rows"), .gelu_erf_fn = try mod.function("tf_gelu_erf_rows"), .ple_fn = try mod.function("tf_ple_rows") };
return .{ .mod = mod, .swiglu_fn = try mod.function("tf_swiglu_rows"), .gate_fn = try mod.function("tf_gate_rows"), .sums_fn = try mod.function("tf_group_sums_rows"), .dconv_fn = try mod.function("tf_dconv_rows"), .geglu_fn = try mod.function("tf_geglu_rows"), .swiglu_round_fn = try mod.function("tf_swiglu_rows_round"), .softcap_fn = try mod.function("tf_softcap_rows"), .gate_l2_fn = try mod.function("tf_gate_l2_rows"), .swiglu_l2_fn = try mod.function("tf_swiglu_l2_rows"), .head_gate_fn = try mod.function("tf_head_gate_rows"), .gelu_erf_fn = try mod.function("tf_gelu_erf_rows") };
}

/// out = bf16(bf16(gelu_erf(gate)) * up) as PyTorch's exact GELU then the product, rows as swiglu's; xs: sums.
Expand Down Expand Up @@ -99,20 +98,6 @@ pub const ActRows = struct {
try launch_.launch(f, .{ .grid = grid(rows, n, t), .block = .{ .x = t } }, s, &a);
}

/// Gemma 4 E-series per-layer inputs: out [rows, parts 256] from projected p and table rows t (packed alike).
pub fn ple(g: *const ActRows, s: Stream, p: u64, t: u64, w: u64, out: u64, rows: usize, parts: usize, c: Ple) !void {
if (parts == 0 or rows * parts * 256 > std.math.maxInt(i32) or !aligned(&.{ p, t, out }, &.{})) return error.RowShape;
if (rows == 0) return;
var a: launch_.Args = .{};
for ([_]u64{ p, t, w, out }) |v| a.add(v);
a.add(@as(i32, @intCast(parts)));
for ([_]f32{ c.scale, c.token, c.mix, c.eps }) |v| a.add(v);
try launch_.launch(g.ple_fn, .{ .grid = .{ .x = @intCast(rows), .y = @intCast(parts), .z = 1 }, .block = .{ .x = 64 } }, s, &a);
}

/// tf_ple_rows's scalars, each a bf16 value as MLX multiplies by it, and the norm's epsilon.
pub const Ple = struct { scale: f32, token: f32, mix: f32, eps: f32 };

/// out [rows, n] = bf16(cap * tanh(x / cap)) in MLX's bf16 steps (x / cap and tanh rounded); out may be x.
pub fn softcap(g: *const ActRows, s: Stream, x: u64, out: u64, rows: usize, n: usize, cap: f32) !void {
if (n % 8 != 0 or n > std.math.maxInt(i32) or !aligned(&.{ x, out }, &.{n})) return error.RowShape;
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 @@ -16,6 +16,7 @@ pub const built_sm: ?u32 = options.built_sm;

pub const qwen4_hc: []const u8 = if (available) &Blob("fatbin_qwen4_hc").bytes else &.{};
pub const qwen4_ple: []const u8 = if (available) &Blob("fatbin_qwen4_ple").bytes else &.{};
pub const gemma4_ple: []const u8 = if (available) &Blob("fatbin_gemma4_ple").bytes else &.{};
pub const qwen4_gdn: []const u8 = if (available) &Blob("fatbin_qwen4_gdn").bytes else &.{};
pub const qwen4_projection: []const u8 = if (available) &Blob("fatbin_qwen4_projection").bytes else &.{};
pub const gdn: []const u8 = if (available) &Blob("fatbin_gdn").bytes else &.{};
Expand Down
2 changes: 2 additions & 0 deletions zig/src/families/gemma4/cuda.zig
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@ pub const config = @import("cuda_config.zig");
pub const widths = @import("cuda_widths.zig");
pub const plan = @import("cuda_plan.zig");
pub const layer_input = @import("cuda_layer_input.zig");
pub const ple = @import("cuda_ple.zig");
pub const weights = @import("cuda_weights.zig");
pub const kernels = @import("cuda_kernels.zig");
pub const forward = @import("cuda_forward.zig");
Expand Down Expand Up @@ -41,6 +42,7 @@ test {
_ = @import("cuda_widths.zig");
_ = @import("cuda_plan.zig");
_ = @import("cuda_layer_input.zig");
_ = @import("cuda_ple.zig");
_ = @import("cuda_weights.zig");
_ = @import("cuda_kernels.zig");
_ = @import("cuda_forward.zig");
Expand Down
4 changes: 2 additions & 2 deletions zig/src/families/gemma4/cuda_forward.zig
Original file line number Diff line number Diff line change
Expand Up @@ -348,8 +348,8 @@ pub const Model = struct {
try m.project(k, s, p.project, x.h[0], x.xs, x.li.proj, rows, prompt);
try k.embed.affine(s, x.ids, p.table_w, p.table_s, p.table_b, x.li.table, rows, stacked, .{ .bits = p.table_bits, .group = cfg.group });
const li = @import("cuda_layer_input.zig");
const c: cuda.act_rows.ActRows.Ple = .{ .scale = li.scalar(1.0 / @sqrt(@as(f64, @floatFromInt(g.hidden)))), .token = li.scalar(@sqrt(@as(f64, @floatFromInt(g.layer_input)))), .mix = li.scalar(std.math.sqrt1_2), .eps = cfg.eps };
try k.act.ple(s, x.li.proj, x.li.table, p.norm, x.li.all, rows, g.layers, c);
const c: @import("cuda_ple.zig").Scalars = .{ .scale = li.scalar(1.0 / @sqrt(@as(f64, @floatFromInt(g.hidden)))), .token = li.scalar(@sqrt(@as(f64, @floatFromInt(g.layer_input)))), .mix = li.scalar(std.math.sqrt1_2), .eps = cfg.eps };
try k.ple.run(s, x.li.proj, x.li.table, p.norm, x.li.all, rows, g.layers, c);
}

/// Layer i's per-layer block on the residual in s.h[0]: gate, GeGLU with its inputs, projection, the scaled tail.
Expand Down
5 changes: 5 additions & 0 deletions zig/src/families/gemma4/cuda_kernels.zig
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,8 @@ pub const Kernels = struct {
qk: cuda.qk_rows.QkRows,
win: cuda.window_attention.WindowAttention,
act: cuda.act_rows.ActRows,
/// gemma4_ple.cu: the E-series per-layer inputs.
ple: @import("cuda_ple.zig").PleRows,

pub fn load(ctx: *const cuda.Context) !Kernels {
const d = ctx.d;
Expand Down Expand Up @@ -46,10 +48,13 @@ pub const Kernels = struct {
k.win = try cuda.window_attention.WindowAttention.load(d);
errdefer k.win.unload();
k.act = try cuda.act_rows.ActRows.load(d);
errdefer k.act.unload();
k.ple = try @import("cuda_ple.zig").PleRows.load(d);
return k;
}

pub fn deinit(k: *Kernels) void {
k.ple.unload();
k.act.unload();
k.win.unload();
k.qk.unload();
Expand Down
37 changes: 37 additions & 0 deletions zig/src/families/gemma4/cuda_ple.zig
Original file line number Diff line number Diff line change
@@ -0,0 +1,37 @@
//! gemma4_ple.cu: the E-series per-layer inputs from the projected rows and the token table's rows (#1222).
const std = @import("std");
const cuda = @import("cuda");

/// tf_gemma4_ple_rows's scalars, each a bf16 value as MLX multiplies by it, and the norm's epsilon.
pub const Scalars = struct { scale: f32, token: f32, mix: f32, eps: f32 };

/// The part each norm runs over: hidden_size_per_layer_input, 256 on every E-series checkpoint.
pub const width = 256;

pub const PleRows = struct {
mod: cuda.Module,
fn_: cuda.Function,

pub fn load(d: *const cuda.Driver) !PleRows {
if (!cuda.kernels.available) return error.BuiltWithoutKernels;
var mod = try cuda.Module.load(d, cuda.kernels.gemma4_ple);
errdefer mod.unload();
return .{ .mod = mod, .fn_ = try mod.function("tf_gemma4_ple_rows") };
}

pub fn unload(g: *PleRows) void {
g.mod.unload();
}

/// out [rows, parts 256] from projected rows p and table rows t (packed alike) and the norm's weight w [256].
pub fn run(g: *const PleRows, s: cuda.Stream, p: u64, t: u64, w: u64, out: u64, rows: usize, parts: usize, c: Scalars) !void {
if (parts == 0 or rows * parts * width > std.math.maxInt(i32)) return error.RowShape;
for ([_]u64{ p, t, out }) |v| if (v % 16 != 0) return error.RowShape;
if (rows == 0) return;
var a: cuda.Args = .{};
for ([_]u64{ p, t, w, out }) |v| a.add(v);
a.add(@as(i32, @intCast(parts)));
for ([_]f32{ c.scale, c.token, c.mix, c.eps }) |v| a.add(v);
try cuda.launch.launch(g.fn_, .{ .grid = .{ .x = @intCast(rows), .y = @intCast(parts), .z = 1 }, .block = .{ .x = 64 } }, s, &a);
}
};
2 changes: 1 addition & 1 deletion zig/tests/cuda/contract_compile.zig
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,6 @@ const check = @import("check.zig");
const contracts = @import("contract_tests.zig");
export fn tf_compile_contract_consumers(gpu: *const check.Gpu, dir: [*:0]const u8) c_int {
contracts.fatbins(gpu.*, std.mem.span(dir)) catch return 1;
const problems = contracts.live(gpu.*) catch return 1;
const problems = contracts.live(gpu.*, &.{}) catch return 1;
return if (problems == 0) 0 else 1;
}
Loading