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

- Core and CUDA: exact row top-k, sparse-index scores and block summaries for sparse indexers, with kernel contracts on every release SM; no family uses them yet, so served output is unchanged (#5051). Thanks to @jschmied.

- Hy4-flash (groundwork, not yet served): fused iHC and HC CUDA kernels with serial-exact arithmetic, contract gates covering every output, 13 planted controls and launch limits on the five release SMs (#5100). Thanks to @GrgaPalcic.

- Ling-3.0-tiny on ARM CPUs: independent attention heads run in the persistent worker pool, each with its serial arithmetic and reduction order, so tokens and logits are unchanged; decode is about 10% faster at 1 and 4 threads (#5071). Thanks to @ThinkOffApp.
Expand Down
2 changes: 2 additions & 0 deletions zig/build/checkpoint_io_host.zig
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,8 @@ pub fn steps(b: *std.Build, target: std.Build.ResolvedTarget) void {
.dependOn(&b.addRunArtifact(b.addTest(.{ .root_module = core, .filters = &.{"part:"} })).step);
if (mode == .debug) b.step("test-fp8-block-host", "The shared block-FP8 reader and exact scale widening (core/quant/fp8.zig)")
.dependOn(&b.addRunArtifact(b.addTest(.{ .root_module = core, .filters = &.{"fp8 block:"} })).step);
if (mode == .debug) b.step("test-sparse-index-host", "The shared sparse-attention indexer reference and NVFP4 row storage (core/sparse_index.zig, core/nvfp4_store.zig)")
.dependOn(&b.addRunArtifact(b.addTest(.{ .root_module = core, .filters = &.{ "sparse index:", "nvfp4 store:", "sparse topology:" } })).step);
if (mode == .debug) b.step("test-gptq-reader-host", "The shared GPTQ reader on a synthetic checkpoint, against binary64 (core/quant/gptq.zig)")
.dependOn(&b.addRunArtifact(b.addTest(.{ .root_module = core, .filters = &.{"gptq:"} })).step);
const qwen = b.createModule(.{ .root_source_file = b.path("zig/src/families/qwen3_5/loader.zig"), .target = target, .optimize = mode, .link_libc = true, .imports = &.{.{ .name = "core", .module = core }} });
Expand Down
3 changes: 3 additions & 0 deletions zig/build/cuda_contract_host.zig
Original file line number Diff line number Diff line change
Expand Up @@ -20,6 +20,9 @@ pub fn steps(b: *std.Build, host: std.Build.ResolvedTarget, cuda: *std.Build.Mod
.imports = &.{ .{ .name = "cuda", .module = cuda }, .{ .name = "core", .module = mods.core } },
}) }));
step.dependOn(&writeback_contract.step);
const set_pair = b.addRunArtifact(b.addTest(.{ .root_module = b.createModule(.{ .root_source_file = b.path("zig/tests/cuda/contract_set_pair.zig"), .target = host, .optimize = .debug }) }));
b.step("test-contract-set-pair-host", "Contract sets set up in pairs: a failing second set releases the first").dependOn(&set_pair.step);
step.dependOn(&set_pair.step);
@import("cuda_row_contracts.zig").host(b, host, cuda, mods.core, step);
@import("cuda_window_host.zig").steps(b, host, step);
const utility_contract = b.addRunArtifact(b.addTest(.{ .root_module = b.createModule(.{
Expand Down
2 changes: 2 additions & 0 deletions zig/build/cuda_kernels.zig
Original file line number Diff line number Diff line change
Expand Up @@ -139,6 +139,8 @@ pub const kernels = [_]Kernel{
.{ .name = "qmmf", .flags = &.{"-O3"}, .native_fp = true }, // nvfp4/qmmf.cu (FP8G, FP4), tensorfold_nvfp4_v3
.{ .name = "prompt16", .flags = &.{"-O3"}, .native_fp = true }, // nvfp4/prompt.cu FP4/FP8 tile 4, nvfp4_prompt_v1
.{ .name = "tree_attention", .flags = &.{"-O3"} }, // ours: committed keys and paths (cuda/tree_attention.zig)
.{ .name = "topk_rows", .flags = &.{ "-O3", "--ftz=false" } }, // ours: every family's exact row top-k (cuda/topk_rows.zig)
.{ .name = "sparse_index", .flags = &.{ "-O3", "--ftz=false" } }, // ours: every family's indexer scores and block summaries
.{ .name = "block_attention", .flags = &.{"-O3"} }, // ours: a drafter's block over its context (cuda/block_attention.zig)
.{ .name = "window_attention", .flags = &.{"-O3"} }, // ours: sliding-window attention (cuda/window_attention.zig)
.{ .name = "window_rows", .flags = &.{"-O3"} }, // ours: window attention at head dims 256 and 512 (cuda/window_attention.zig)
Expand Down
130 changes: 130 additions & 0 deletions zig/kernels/cuda/common/topk_rows.cuh
Original file line number Diff line number Diff line change
@@ -0,0 +1,130 @@
// An exact row top-k for every family: an 8-bit radix select of fp32 scores, ties to the lower index, picks in order.
#pragma once

#include <stdint.h>

namespace tf_topk {

// A score's bits as a uint32 whose unsigned order is the scores' (-0 counted as +0, any NaN one key above +inf).
__device__ __forceinline__ uint32_t order_key(float s) {
if (s != s) return 0xffffffffu; // every NaN alike: its sign and payload are not stated by PTX arithmetic
const int32_t b = __float_as_int(s + 0.0f);
return (uint32_t)(b ^ ((b >> 31) | (int32_t)0x80000000));
}

// W warps' exclusive prefix of v in thread order and its total, via slot of `wsum`; its barrier orders slot reuse.
template <int W>
__device__ __forceinline__ int block_scan(int v, int (*wsum)[W], int slot, int* total) {
const int lane = threadIdx.x & 31, warp = threadIdx.x >> 5;
int inc = v;
for (int o = 1; o < 32; o <<= 1) {
const int u = __shfl_up_sync(0xffffffffu, inc, o);
if (lane >= o) inc += u;
}
if (lane == 31) wsum[slot][warp] = inc;
__syncthreads();
int before = inc - v;
for (int w = 0; w < warp; ++w) before += wsum[slot][w];
int all = 0;
for (int w = 0; w < W; ++w) all += wsum[slot][w];
*total = all;
return before;
}

// The k best of row[0, limit) by an 8-bit radix select, ties to the lower index, written to out in index order.
template <int T, typename O>
__device__ __forceinline__ void select_row(const float* row, int64_t limit, int k, O* out) {
__shared__ int hist[256];
__shared__ uint32_t sh_prefix;
__shared__ int sh_need, wsum[2][T / 32];
const int t = threadIdx.x, lane = t & 31, warp = t >> 5;
const unsigned below = (1u << lane) - 1;
const bool vec = (reinterpret_cast<uintptr_t>(row) & 15) == 0;
// The order keys of pools c + 8 t .. + 7 (0 past limit; callers test the index).
auto keys = [&](int64_t c, uint32_t u[8]) {
const int64_t i0 = c + 8 * t;
if (vec && i0 + 8 <= limit) {
const float4 a = *reinterpret_cast<const float4*>(row + i0), b = *reinterpret_cast<const float4*>(row + i0 + 4);
const float v[8] = {a.x, a.y, a.z, a.w, b.x, b.y, b.z, b.w};
for (int j = 0; j < 8; ++j) u[j] = order_key(v[j]);
} else {
for (int j = 0; j < 8; ++j) u[j] = i0 + j < limit ? order_key(row[i0 + j]) : 0u;
}
};
// T only sets the pools a pass reads (8 a thread): digit counts and index-order scans give every T the same picks
uint32_t prefix = 0, fixed = 0;
int need = k;
for (int shift = 24; shift >= 0; shift -= 8) {
for (int b = t; b < 256; b += blockDim.x) hist[b] = 0;
__syncthreads();
for (int64_t c = 0; c < limit; c += 8 * T) {
uint32_t u[8];
keys(c, u);
for (int j = 0; j < 8; ++j) {
const int b = c + 8 * t + j < limit && (u[j] & fixed) == prefix ? (int)((u[j] >> shift) & 0xFF) : 256;
if (__any_sync(0xffffffffu, b < 256)) {
const unsigned same = __match_any_sync(0xffffffffu, b);
if (b < 256 && (same & below) == 0) atomicAdd(&hist[b], __popc(same));
}
}
}
__syncthreads();
if (warp == 0) {
// Lane l holds bins 255 - 8 l .. 248 - 8 l; the digit is in the first lane whose count reaches need, else 0.
int h[8], own = 0;
for (int j = 0; j < 8; ++j) own += h[j] = hist[255 - 8 * lane - j];
int upto = own;
for (int o = 1; o < 32; o <<= 1) {
const int v = __shfl_up_sync(0xffffffffu, upto, o);
if (lane >= o) upto += v;
}
const unsigned hit = __ballot_sync(0xffffffffu, upto >= need);
if (lane == (hit ? __ffs(hit) - 1 : 31)) {
int above = upto - own, digit = 0;
for (int j = 0; j < 8; ++j) {
if (above + h[j] >= need) {
digit = 255 - 8 * lane - j;
break;
}
above += h[j];
}
sh_need = need - above;
sh_prefix = prefix | ((uint32_t)digit << shift);
}
}
__syncthreads();
need = sh_need;
prefix = sh_prefix;
fixed |= 0xFFu << shift;
__syncthreads();
}
int run_take = 0, run_eq = 0;
for (int64_t c = 0; c < limit; c += 8 * T) {
uint32_t u[8];
keys(c, u);
bool eq[8], gt[8];
int eqs = 0;
for (int j = 0; j < 8; ++j) {
const bool in = c + 8 * t + j < limit;
eq[j] = in && u[j] == prefix;
gt[j] = in && u[j] > prefix;
eqs += eq[j];
}
int all_eq, all_take;
int seen = run_eq + block_scan<T / 32>(eqs, wsum, 0, &all_eq);
bool take[8];
int takes = 0;
for (int j = 0; j < 8; ++j) {
take[j] = gt[j] || (eq[j] && seen < need);
seen += eq[j];
takes += take[j];
}
int at = run_take + block_scan<T / 32>(takes, wsum, 1, &all_take);
for (int j = 0; j < 8; ++j)
if (take[j]) out[at++] = (O)(c + 8 * t + j);
run_eq += all_eq;
run_take += all_take;
}
}

} // namespace tf_topk
104 changes: 104 additions & 0 deletions zig/kernels/cuda/sparse_index.cu
Original file line number Diff line number Diff line change
@@ -0,0 +1,104 @@
// Every family's indexer on the GPU (core/sparse_index.zig): the scores and the block summaries a first stage scores.
#include <cuda_bf16.h>
#include <stdint.h>

namespace tf_iscore {

constexpr int D = 128, KEYS = 64; // key width; keys a block (a thread each)

// A thread a key of row r: per head an fma chain over d, phi, times w; heads in order (sum, or max keeping NaN).
__device__ __forceinline__ void scores(const __nv_bfloat16* q, const __nv_bfloat16* k, int64_t ks, const float* w,
const int* counts, float* out, int64_t ld, int n, int H, int hk, float scale,
int relu, int max) {
extern __shared__ __align__(16) unsigned char smem[];
__nv_bfloat16* qs = reinterpret_cast<__nv_bfloat16*>(smem);
float* ws = reinterpret_cast<float*>(qs + H * D);
const int64_t r = blockIdx.y;
for (int i = threadIdx.x; i < H * D / 8; i += KEYS)
reinterpret_cast<uint4*>(qs)[i] = reinterpret_cast<const uint4*>(q + r * H * D)[i];
for (int i = threadIdx.x; i < H; i += KEYS) ws[i] = w ? w[r * H + i] : 1.0f;
__syncthreads();
const int64_t key = (int64_t)blockIdx.x * KEYS + threadIdx.x;
if (key >= ld) return;
const int64_t c = counts ? (int64_t)counts[r] : n, limit = c < 0 ? 0 : (c > n ? n : c);
if (key >= limit) { // past the row's count (clamped to [0, n]), up to ld: no stale score is left
out[r * ld + key] = -INFINITY;
return;
}
const int group = H / hk;
float acc = 0.0f;
for (int h = 0; h < H; ++h) {
const uint4* kp = reinterpret_cast<const uint4*>(k + key * ks + (int64_t)(h / group) * D);
const uint4* qp = reinterpret_cast<const uint4*>(qs + h * D);
float dot = 0.0f;
for (int c = 0; c < D / 8; ++c) {
const uint4 kv = kp[c], qv = qp[c];
const __nv_bfloat162* kb = reinterpret_cast<const __nv_bfloat162*>(&kv);
const __nv_bfloat162* qb = reinterpret_cast<const __nv_bfloat162*>(&qv);
for (int j = 0; j < 4; ++j) {
const float2 a = __bfloat1622float2(qb[j]), b = __bfloat1622float2(kb[j]);
dot = __fmaf_rn(a.x, b.x, dot);
dot = __fmaf_rn(a.y, b.y, dot);
}
}
if (relu && dot < 0.0f) dot = 0.0f; // NaN stays NaN
const float t = w ? __fmul_rn(ws[h], dot) : dot;
if (h == 0) acc = t;
else if (max) acc = (t > acc || t != t) ? t : acc;
else acc = __fadd_rn(acc, t);
}
out[r * ld + key] = __fmul_rn(acc, scale);
}

// Keys [lo, hi) (hi > lo) summarised, a thread a dim: mean (fp32 in key order), max (NaN kept), first or last.
__device__ __forceinline__ float summary(const __nv_bfloat16* k, int64_t ks, int64_t lo, int64_t hi, int mode,
int unit) {
__shared__ float part[D / 32];
const int d = threadIdx.x, lane = d & 31, warp = d >> 5;
float acc = 0.0f;
for (int64_t i = lo; i < hi; ++i) {
float x = __bfloat162float(k[i * ks + d]);
if (unit) { // the key times 1 / sqrt(its mean square), 0 when that is 0
float sq = __fmul_rn(x, x);
for (int o = 16; o > 0; o >>= 1) sq = __fadd_rn(sq, __shfl_xor_sync(0xffffffffu, sq, o));
__syncthreads();
if (lane == 0) part[warp] = sq;
__syncthreads();
const float ss = __fadd_rn(__fadd_rn(part[0], part[1]), __fadd_rn(part[2], part[3]));
const float ms = __fdiv_rn(ss, (float)D);
x = ms > 0.0f ? __fmul_rn(x, __fdiv_rn(1.0f, __fsqrt_rn(ms))) : (ms == 0.0f ? 0.0f : __fmul_rn(x, ms));
}
if (i == lo) acc = x;
else if (mode == 0) acc = __fadd_rn(acc, x);
else if (mode == 1) acc = (x > acc || x != x) ? x : acc;
else if (mode == 3) acc = x;
}
if (mode == 0) acc = __fdiv_rn(acc, (float)(hi - lo));
return acc;
}

} // namespace tf_iscore

// grid (ceil(ld / 64), rows), 64 threads, H * D * 2 + H * 4 bytes of dynamic shared memory.
extern "C" __global__ void __launch_bounds__(64)
tf_index_scores(const __nv_bfloat16* q, const __nv_bfloat16* k, int64_t ks, const float* w, const int* counts,
float* out, int64_t ld, int n, int H, int hk, float scale, int relu, int max) {
tf_iscore::scores(q, k, ks, w, counts, out, ld, n, H, hk, scale, relu, max);
}

// A block a summary, 128 threads (a dim each); grid: ceil(n / B) summaries.
extern "C" __global__ void __launch_bounds__(128)
tf_index_blocks(const __nv_bfloat16* k, int64_t ks, __nv_bfloat16* out, int64_t os, int64_t n, int B, int mode,
int unit) {
const int64_t lo = (int64_t)blockIdx.x * B, hi = lo + B < n ? lo + B : n;
out[(int64_t)blockIdx.x * os + threadIdx.x] = __float2bfloat16_rn(tf_iscore::summary(k, ks, lo, hi, mode, unit));
}

// Row r's open block, keys [end - end % B, end) of end = ends[r] = t + 1 clamped to [0, n]; 0 if none. A row a block.
extern "C" __global__ void __launch_bounds__(128)
tf_index_open_blocks(const __nv_bfloat16* k, int64_t ks, __nv_bfloat16* out, int64_t os, const int* ends, int64_t n,
int B, int mode, int unit) {
const int64_t e = ends[blockIdx.x], end = e < 0 ? 0 : (e > n ? n : e), lo = end - end % B;
const float v = lo < end ? tf_iscore::summary(k, ks, lo, end, mode, unit) : 0.0f;
out[(int64_t)blockIdx.x * os + threadIdx.x] = __float2bfloat16_rn(v);
}
27 changes: 27 additions & 0 deletions zig/kernels/cuda/topk_rows.cu
Original file line number Diff line number Diff line change
@@ -0,0 +1,27 @@
// Every family's exact row top-k (common/topk_rows.cuh): row r's k best of its first counts[r] scores, in index order.
#include "common/topk_rows.cuh"

// out[r] gets min(k, n) indices ascending, -1 after them; picked[r] their count; n = counts[r] in [0, ld], else ld.
template <int T>
__device__ __forceinline__ void topk_rows(const float* scores, int64_t ld, const int* counts, int k, int* out,
int* picked) {
const int64_t r = blockIdx.x;
const int64_t c = counts ? (int64_t)counts[r] : ld, n = c < 0 ? 0 : (c > ld ? ld : c); // a count clamps to [0, ld]
const int take = n < k ? (int)n : k;
int* o = out + r * k;
for (int64_t i = take + threadIdx.x; i < k; i += T) o[i] = -1;
if (threadIdx.x == 0) picked[r] = take;
if (take > 0) tf_topk::select_row<T>(scores + r * ld, n, take, o);
}

// A row per 4-warp block: many rows (a prompt chunk's).
extern "C" __global__ void __launch_bounds__(128)
tf_topk_rows(const float* scores, int64_t ld, const int* counts, int k, int* out, int* picked) {
topk_rows<128>(scores, ld, counts, k, out, picked);
}

// A row per 1,024-thread block: a few rows over many scores (a decode step's); the same bytes.
extern "C" __global__ void __launch_bounds__(1024)
tf_topk_rows_wide(const float* scores, int64_t ld, const int* counts, int k, int* out, int* picked) {
topk_rows<1024>(scores, ld, counts, k, out, picked);
}
2 changes: 1 addition & 1 deletion zig/src/core/contract/registry_cuda_sets.zig
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,7 @@ const CudaSet = registry.CudaSet;

/// The later releases' sets, rising by release; a tree's images are checked against the newest at or below their own.
pub const cuda_sets = [_]CudaSet{
.{ .release = .{ .major = 13, .minor = 2 }, .usage = &(@import("registry_shared_attention.zig").nvcc132(Override) ++ @import("zonos3_cuda_records.zig").cuda_132 ++ [_]Override{
.{ .release = .{ .major = 13, .minor = 2 }, .usage = &(@import("registry_shared_attention.zig").nvcc132(Override) ++ @import("zonos3_cuda_records.zig").cuda_132 ++ @import("sparse_index_records.zig").nvcc132 ++ [_]Override{
.{ .name = "window_pages tf_wrows_merge_512_pg", .usage = .{ .{ .regs = 56, .static = 128, .bound = 256 }, .{ .regs = 56, .static = 128, .bound = 256 }, .{ .regs = 56, .static = 128, .bound = 256 }, .{ .regs = 60, .static = 128, .bound = 256 }, .{ .regs = 60, .static = 128, .bound = 256 } } },
.{ .name = "moe tf_moe_topk_sigmoid_score_warp", .usage = .{ .{ .regs = 219, .static = 0, .bound = 256 }, .{ .regs = 219, .static = 0, .bound = 256 }, .{ .regs = 219, .static = 0, .bound = 256 }, .{ .regs = 203, .static = 0, .bound = 256 }, .{ .regs = 203, .static = 0, .bound = 256 } } },
.{ .name = "norms tf_rms_rows", .usage = .{ .{ .regs = 32, .static = 132, .bound = 1024 }, .{ .regs = 46, .static = 132, .bound = 1024 }, .{ .regs = 46, .static = 132, .bound = 1024 }, .{ .regs = 43, .static = 132, .bound = 1024 }, .{ .regs = 43, .static = 132, .bound = 1024 } } },
Expand Down
1 change: 1 addition & 0 deletions zig/src/core/contract/registry_joins.zig
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@ pub const cuda_after = @import("registry_media.zig").cuda ++
@import("nemotron_prompt_records.zig").cuda ++
@import("glm_cuda_records.zig").cuda ++
@import("registry_shared_attention.zig").records(registry.CudaRecord) ++
@import("sparse_index_records.zig").cuda ++
@import("gemma_cuda_records.zig").cuda ++
@import("spark_cuda_records.zig").cuda ++
@import("row_cuda_records.zig").cuda ++
Expand Down
34 changes: 34 additions & 0 deletions zig/src/core/contract/sparse_index_records.zig
Original file line number Diff line number Diff line change
@@ -0,0 +1,34 @@
//! topk_rows.cu's and sparse_index.cu's launches: every family's row top-k, indexer scores and block summaries.
const std = @import("std");
const registry = @import("registry.zig");
const R = registry.CudaRecord;
const U = @import("limits.zig").Usage;

const narrow_name = "topk rows tf_topk_rows";
const scores_name = "sparse index tf_index_scores (64 heads)";
const wide_name = "topk rows tf_topk_rows_wide";

fn with(regs: [5]u32, static: u32, bound: u32) [5]U {
var out: [5]U = undefined;
for (&out, regs) |*u, r| u.* = .{ .regs = r, .static = static, .bound = bound };
return out;
}

/// nvcc 13.0, sm_80 / 86 / 89 / 120 / 121 (--ftz=false); the scores' shared memory is 64 heads' at most.
pub const cuda = [_]R{
.{ .launch = .{ .name = scores_name, .symbol = "tf_index_scores", .image = "sparse_index", .threads = 64, .dynamic = 64 * 128 * 2 + 64 * 4 }, .usage = with(.{ 40, 64, 48, 46, 46 }, 0, 64) },
.{ .launch = .{ .name = "sparse index tf_index_blocks", .symbol = "tf_index_blocks", .image = "sparse_index", .threads = 128 }, .usage = with(.{ 30, 34, 34, 26, 26 }, 16, 128) },
.{ .launch = .{ .name = "sparse index tf_index_open_blocks", .symbol = "tf_index_open_blocks", .image = "sparse_index", .threads = 128 }, .usage = with(.{ 25, 37, 37, 32, 32 }, 16, 128) },
.{ .launch = .{ .name = narrow_name, .symbol = "tf_topk_rows", .image = "topk_rows", .threads = 128 }, .usage = with(.{ 56, 54, 54, 40, 40 }, 1064, 128) },
.{ .launch = .{ .name = wide_name, .symbol = "tf_topk_rows_wide", .image = "topk_rows", .threads = 1024 }, .usage = with(.{ 32, 56, 56, 60, 64 }, 1288, 1024) },
};

/// nvcc 13.2 where it differs.
pub const nvcc132 = [_]registry.Override{
.{ .name = scores_name, .usage = with(.{ 40, 64, 48, 56, 56 }, 0, 64) },
.{ .name = wide_name, .usage = with(.{ 32, 57, 57, 64, 64 }, 1288, 1024) },
};

test "sparse index records: the launches fit every SM by their measured records" {
for (cuda) |r| try std.testing.expectEqual(@as(usize, 0), try registry.checkCuda(std.testing.allocator, &.{r}, true));
}
Loading
Loading