Skip to content
Closed
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
40 changes: 40 additions & 0 deletions docs/kernel-contract.md
Original file line number Diff line number Diff line change
Expand Up @@ -735,6 +735,14 @@ once in the vendor's order with nothing fused. Each output must be the host's re
TP=2 rank's half; gate 4 runs whole logits with whole ranges and power-of-two weights, where every step is exact
(`ernie5_5-head`; two controls: each term's multiply and add fused into an fma, and the last term's square dropped).

CUDA also checks ERNIE 5.5's DSA indexer keys (`ernie5_5/index.cu`, `tf_ernie55_index_key`): k's LayerNorm with k_norm's
weight and bias (eps 1e-6; the mean, then the squares about it, in fp32), then vLLM's NeoX RoPE on the first 64 dims
(pairs i and i + 32 turned at the fp32 angle inv[i] times the position, inv from the config's `rope_theta`, sincosf),
rounded to bf16 once. Each key must be within the float64 bound of the host's (`ernie5_5/key.zig`), from prompt chunks
and a decode row at the first position to decode rows past sincosf's fast range and at the 1M context's end; gate 4 runs
rows of 254 to 260 in steps of 2, where fp32 sums are exact and fp16 and bf16 sums lose the steps (`ernie5_5-index`;
three controls: GPT-J's pairs (2i, 2i + 1), the LayerNorm without its bias, and the next position's angle).

CUDA also checks ERNIE 5.5's DSA key lists (`ernie5_5/index.cu`, `tf_ernie55_window_merge`): each row's indexer
picks (`topk_rows`' out, `picked` of them held to [0, k] and ending at the first -1), then its sliding window's
min(seq, 128) positions up to seq - 1, then -1, as vLLM-ERNIE's `merge_swa_topk` lays them out for the sparse MLA,
Expand All @@ -754,6 +762,38 @@ by 8 and below 1e-6, where the mix RMS's eps outweighs sqrt(mean); gate 4 runs p
fp32 sum is exact (`ernie5_5-mhc`; two controls: the plain mix RMS 1 / sqrt(mean + eps), and comb's softmax over a
column).

CUDA also checks ERNIE 5.5's mHC post side (`ernie5_5/mhc.cu`, `tf_ernie55_mhc_post`): a layer's bf16 output x into
its row's 4 streams, stream o = post[o] x + sum_i comb[i][o] res[i] as vLLM's `mhc_post` forms it, from the product,
then the input streams in order in fma, rounded to bf16 once. Each stream must be within the float64 bound of the host's
(`ernie5_5/mhc.zig`); gate 4 runs streams 0 to 2 equal to x under comb -130, 131 and -130 against post 129, and stream
3's +-1 under 1/2: integer terms that fp32 holds in any order, cancelling to +-1/2, whose fp16 and bf16 roundings do not
(`ernie5_5-mhc`; two controls: comb read transposed, and the layer output added without post).

CUDA also checks ERNIE 5.5's hc_head (`ernie5_5/mhc.cu`, `tf_ernie55_hc_head`): the last layer's 4 streams into one
bf16 row as vLLM's `hc_head` forms it, its 4 mixes and the squares summed as the pre side sums them, the plain RMS
1 / sqrt(mean + eps), pre = sigmoid(m r scale + base) + hc_eps, then sum_s pre_s x_s rounded to bf16 once. Each
output must be within the float64 bound of the host's (`ernie5_5/mhc.zig`), from the pre side's rows; gate 4 runs pre
at 1/2 on one stream (`ernie5_5-mhc`; two controls: ERNIE's pre-side mix RMS 1 / (sqrt(mean) + eps), and the mixes
without hc_head's scale).

CUDA also checks ERNIE 5.5's first-layer mHC pre (`ernie5_5/mhc.cu`, `tf_ernie55_mhc_pre_broadcast`): vLLM-ERNIE's
broadcast, the embedding row e as each of the 4 streams, its 24 mixes with fn's 4 column blocks summed at load (a
thread's 16 terms in one fma chain, then the warps' butterflies), the mix RMS over e's own 4096 squares, then the pre
side's pre, post, comb and normed collapse, and e written into the 4 streams. Each output is held to its float64 bound
alone (`ernie5_5/mhc.zig`, whose host test holds it to the pre side of e's 4 copies), from the pre side's rows; gate 4
runs pre at 1/2 on half-integer rows, where every fp32 sum is exact (`ernie5_5-mhc`; two controls: the mix RMS's mean
over pre's 4 x 4096 values, and e written into stream 0 alone).

CUDA also checks ERNIE 5.5's HCA compressor (`ernie5_5/hca.cu`, `tf_ernie55_hca_compress`): a compressed row from its
128 tokens' fp32 kv and score, as vLLM's C128 compressor forms it: each channel's softmax over the tokens of score + ape
(indexed by the token's offset in the block) pooling kv (the max, then e^(s - M) summed and kv e in fma, the tokens in
order, one division), the row's RMSNorm 1 / sqrt(mean + eps) times its weight, and GPT-J's pairs on the last 64 dims
turned at the block's first position (YaRN's frequencies at compress_rope_theta), rounded to bf16 once. Each row must be
within the float64 bound of the host's (`ernie5_5/hca.zig`), from rows near the start, the first block, a prompt chunk
and the 1M context's last blocks; gate 4 sets every exponent to 0 (score = 4 - ape), so each pool's sums are exact, with
odd kv whose second half cancels the first (`ernie5_5-hca`; two controls: the pool without ape, and the rope at the
block's last position).

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
a and b; 8 for the head), and its RMS norm over 2048-wide rows; each registration's runs take 1 to 8 threads in turn,
Expand Down
7 changes: 7 additions & 0 deletions zig/build/cuda.zig
Original file line number Diff line number Diff line change
Expand Up @@ -142,13 +142,19 @@ pub fn targets(b: *std.Build, target: std.Build.ResolvedTarget, optimize: std.bu
runner.addImport("ernie5_5_mhc_cuda", b.createModule(.{ .root_source_file = b.path("zig/src/families/ernie5_5/cuda_mhc.zig"), .target = target, .optimize = optimize, .imports = &.{.{ .name = "cuda", .module = cuda }} }));
runner.addImport("hy4_mla_paged_cuda", b.createModule(.{ .root_source_file = b.path("zig/src/families/hy4_flash/mla_paged_cuda.zig"), .target = target, .optimize = optimize, .imports = &.{.{ .name = "cuda", .module = cuda }} }));
runner.addImport("hy4_index_paged", b.createModule(.{ .root_source_file = b.path("zig/src/families/hy4_flash/index_paged_cuda.zig"), .target = target, .optimize = optimize, .imports = &.{.{ .name = "cuda", .module = cuda }} }));
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 }} }));
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
const dots = native.engines.import_table.get("dots_mocr_cuda").?;
for ([_]struct { []const u8, *std.Build.Module }{ .{ "dots_mocr_cuda", dots }, .{ "cuda_dense", dots.import_table.get("cuda_dense").? } }) |m| runner.addImport(m[0], m[1]);
runner.addImport("moss_image_cuda", b.createModule(.{ .root_source_file = b.path("zig/src/families/moss_image/cuda_kernels.zig"), .target = target, .optimize = optimize, .link_libc = true, .imports = &.{.{ .name = "cuda", .module = cuda }} }));
runner.addImport("prompt_pages", b.createModule(.{ .root_source_file = b.path("zig/src/native/cuda_prompt_pages.zig"), .target = target, .optimize = optimize, .link_libc = true, .imports = &.{ .{ .name = "engine_api", .module = mods.api }, .{ .name = "core", .module = mods.core } } })); // TF_KV_SHARE's store, for the pages checks
// ERNIE 5.5 contract metadata and references over the runner's imports, without a GPU.
const ernie_contract = b.createModule(.{ .root_source_file = b.path("zig/tests/cuda/contract_ernie5_5_test.zig"), .target = target, .optimize = optimize, .link_libc = true });
var runner_imports = runner.import_table.iterator();
while (runner_imports.next()) |e| ernie_contract.addImport(e.key_ptr.*, e.value_ptr.*);
b.step("test-ernie5_5-contract-host", "ERNIE 5.5 contract host tests without a GPU").dependOn(&b.addRunArtifact(b.addTest(.{ .root_module = ernie_contract })).step);
const runner_exe = b.addExecutable(.{ .name = "tf-cuda-test", .root_module = runner });
@import("qwen_prompt_stages2.zig").consumers(b, runner);
b.installArtifact(runner_exe);
Expand Down Expand Up @@ -348,6 +354,7 @@ pub fn hostTests(b: *std.Build, draft_ids: *std.Build.Module, build_options: *st
const shard_tests = b.createModule(.{ .root_source_file = b.path("zig/src/living_shards_test.zig"), .target = host, .optimize = .debug, .link_libc = true });
shard_tests.addImport("living", mods.living);
b.step("test-living-shards-host", "Quantized save and reopen through actual shard writer").dependOn(&b.addRunArtifact(b.addTest(.{ .root_module = shard_tests })).step);
if (b.top_level_steps.get("test-ernie5_5-contract-host")) |t| step.dependOn(&t.step);
@import("cuda_contract_host.zig").steps(b, host, cuda, mods, step);
@import("cuda_int4_host.zig").steps(b, host, cuda, mods.core);
const bolt = b.step("test-bolt-host", "Nemotron Bolt and shared lane host contracts");
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 @@ -177,6 +177,7 @@ pub const kernels = [_]Kernel{
.{ .name = "hy4_mla_paged", .src = "hy4_flash/mla_paged", .flags = glue },
.{ .name = "hy4_mla_attn_paged", .src = "hy4_flash/mla_attn_paged", .flags = glue },
.{ .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 = "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
96 changes: 96 additions & 0 deletions zig/kernels/cuda/ernie5_5/hca.cu
Original file line number Diff line number Diff line change
@@ -0,0 +1,96 @@
// ERNIE 5.5's HCA compressor: a block's 128 tokens pooled per channel, the RMSNorm, GPT-J's rope at the block's start.

#include <cuda_bf16.h>

namespace ernie55h {

constexpr int H = 512, R = 128, NOPE = 448, T = 256;
constexpr unsigned all = 0xffffffffu;

enum Fault { none, no_ape, last_position };

// sincosf out of line: one copy of its large-angle path.
static __device__ __noinline__ void turn(float a, float* s, float* c) { sincosf(a, s, c); }

// Row blockIdx.x (tokens 128 row + i, ts floats apart: kv [512] then score [512]), thread t's channels 2t and 2t + 1.
template <Fault F>
__device__ __forceinline__ void compress(const float* __restrict__ st, long long ts, const float* __restrict__ ape,
const __nv_bfloat16* __restrict__ w, const float* __restrict__ freq,
const int* __restrict__ pos, __nv_bfloat16* __restrict__ out, long long os,
float eps) {
__shared__ float sq[T / 32];
const long long row = blockIdx.x;
const int t = threadIdx.x, lane = t & 31, warp = t >> 5;
const float* base = st + row * R * ts + 2 * t;
// s_i = score_i + ape_i (the control: score alone), its max, then e^(s_i - M) summed, kv_i e_i in fma, i in order
float m0 = -INFINITY, m1 = -INFINITY;
for (int i = 0; i < R; ++i) {
const float2 sc = *reinterpret_cast<const float2*>(base + i * ts + H);
const float2 ap = *reinterpret_cast<const float2*>(ape + i * H + 2 * t);
m0 = fmaxf(m0, F == no_ape ? sc.x : __fadd_rn(sc.x, ap.x));
m1 = fmaxf(m1, F == no_ape ? sc.y : __fadd_rn(sc.y, ap.y));
}
float s0 = 0.0f, s1 = 0.0f, p0 = 0.0f, p1 = 0.0f;
for (int i = 0; i < R; ++i) {
const float2 kv = *reinterpret_cast<const float2*>(base + i * ts);
const float2 sc = *reinterpret_cast<const float2*>(base + i * ts + H);
const float2 ap = *reinterpret_cast<const float2*>(ape + i * H + 2 * t);
const float e0 = expf(__fsub_rn(F == no_ape ? sc.x : __fadd_rn(sc.x, ap.x), m0));
const float e1 = expf(__fsub_rn(F == no_ape ? sc.y : __fadd_rn(sc.y, ap.y), m1));
s0 = __fadd_rn(s0, e0);
s1 = __fadd_rn(s1, e1);
p0 = __fmaf_rn(kv.x, e0, p0);
p1 = __fmaf_rn(kv.y, e1, p1);
}
float x0 = __fdiv_rn(p0, s0), x1 = __fdiv_rn(p1, s1);
// RMSNorm 1 / sqrt(mean + eps): the thread's two squares, the warp's butterfly, the 8 warps in order
float ss = __fmaf_rn(x1, x1, __fmul_rn(x0, x0));
for (int o = 16; o > 0; o >>= 1) ss = __fadd_rn(ss, __shfl_xor_sync(all, ss, o));
if (lane == 0) sq[warp] = ss;
__syncthreads();
float tot = sq[0];
for (int i = 1; i < T / 32; ++i) tot = __fadd_rn(tot, sq[i]);
const float r = __fdiv_rn(1.0f, __fsqrt_rn(__fadd_rn(__fmul_rn(tot, 1.0f / H), eps)));
const __nv_bfloat162 wv = *reinterpret_cast<const __nv_bfloat162*>(w + 2 * t);
x0 = __fmul_rn(__fmul_rn(x0, r), __bfloat162float(wv.x));
x1 = __fmul_rn(__fmul_rn(x1, r), __bfloat162float(wv.y));
// pair l = t - 224 on dims 448 + 2l, 449 + 2l, at the block's first position (the control: its last)
if (2 * t >= NOPE) {
const long long at = static_cast<long long>(pos[0]) + row * R + (F == last_position ? R - 1 : 0);
float sn, cs;
turn(__fmul_rn(freq[t - NOPE / 2], static_cast<float>(at)), &sn, &cs);
const float y0 = __fsub_rn(__fmul_rn(x0, cs), __fmul_rn(x1, sn));
const float y1 = __fadd_rn(__fmul_rn(x1, cs), __fmul_rn(x0, sn));
x0 = y0;
x1 = y1;
}
*reinterpret_cast<__nv_bfloat162*>(out + row * os + 2 * t) = __floats2bfloat162_rn(x0, x1);
}

} // namespace ernie55h

// 128-token blocks (kv then score, fp32, ts apart), ape, w, freq [32], row r at pos[0] + 128 r: bf16 rows os apart.
extern "C" __global__ void __launch_bounds__(256)
tf_ernie55_hca_compress(const float* __restrict__ st, long long ts, const float* __restrict__ ape,
const __nv_bfloat16* __restrict__ w, const float* __restrict__ freq,
const int* __restrict__ pos, __nv_bfloat16* __restrict__ out, long long os, float eps) {
ernie55h::compress<ernie55h::none>(st, ts, ape, w, freq, pos, out, os, eps);
}

// The contract's planted control: the pool's softmax over score alone, without ape.
extern "C" __global__ void __launch_bounds__(256)
tf_ctl_ernie55_hca_compress_no_ape(const float* __restrict__ st, long long ts, const float* __restrict__ ape,
const __nv_bfloat16* __restrict__ w, const float* __restrict__ freq,
const int* __restrict__ pos, __nv_bfloat16* __restrict__ out, long long os,
float eps) {
ernie55h::compress<ernie55h::no_ape>(st, ts, ape, w, freq, pos, out, os, eps);
}

// The contract's planted control: the rope at the block's last position, 128 r + 127, in place of its first.
extern "C" __global__ void __launch_bounds__(256)
tf_ctl_ernie55_hca_compress_last_position(const float* __restrict__ st, long long ts, const float* __restrict__ ape,
const __nv_bfloat16* __restrict__ w, const float* __restrict__ freq,
const int* __restrict__ pos, __nv_bfloat16* __restrict__ out,
long long os, float eps) {
ernie55h::compress<ernie55h::last_position>(st, ts, ape, w, freq, pos, out, os, eps);
}
Loading
Loading