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
1 change: 1 addition & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@ Each release's page on GitHub has its notes and measurements. See [the 1.0.0 rel

## Unreleased

- Hy4-flash (`hy_v4_flash`) on Metal: `tensorfold-native serve` takes Tencent's 4- and 8-bit MLX checkpoints with DFly2 drafts, contexts to 256K tokens (128K by default; the compressed indexer recalls 2,048 keys a sparse layer past 2,048 tokens), and a following prompt that starts with the last one's tokens prefills only the rest; Hy4's chat template needs `str.format()` from #3816 (Refs #3797).
- CLI: `tensorfold log` reads the request journal read-only while a server runs: `list` with tokens, time to first token and decode rate, `show ID` with the reply decoded, `follow` across rotations and `--json`; journal `finish` records carry the queue wait, time to first token, decode rate and token counts (#4160, part of #3666).

- Engine: under SRPT scheduling, a prompt that finishes on its last fill step no longer writes its lent time to freed scheduler memory (#4159, fixes #3709).
Expand Down
1 change: 1 addition & 0 deletions build.zig
Original file line number Diff line number Diff line change
Expand Up @@ -187,6 +187,7 @@ pub fn build(b: *std.Build) void {
else => {},
}
@import("zig/build/gemma4_backward.zig").tests(b, test_step);
@import("zig/build/hy4_flash.zig").tests(b, test_step);
const gemma4_host_sources = b.createModule(.{ .root_source_file = b.path("zig/kernels/metal/sources.zig"), .target = b.graph.host });
gemma4_host_sources.addAnonymousImport("nemotron_packed_metallib", .{ .root_source_file = b.addWriteFiles().add("gemma4-host-empty.metallib", "") });
const gemma4_contract_host = @import("zig/build/gemma4_host.zig").tests(b, gemma4_host_sources);
Expand Down
7 changes: 7 additions & 0 deletions zig/build/cuda_kernels.zig
Original file line number Diff line number Diff line change
Expand Up @@ -148,6 +148,13 @@ pub const kernels = [_]Kernel{
.{ .name = "glm_glue", .flags = &.{"-O3"} }, // ours: the Python family's Triton glue by hand, its PTX op for op
.{ .name = "glm_ops", .flags = &.{"-O3"} }, // ours: GLM's integer work the Python family did in torch (the DSA token lists)
.{ .name = "glm_index", .flags = &.{"-O3"} }, // a prompt chunk's DSA scores and top-512 pools
.{ .name = "hy4_indexpool", .src = "hy4_flash/indexpool", .flags = &.{ "-O3", "--fmad=false" } },
.{ .name = "affine_experts", .flags = &.{ "-O3", "--fmad=false" } },
.{ .name = "hy4_index_recall", .src = "hy4_flash/index_recall", .flags = &.{ "-O3", "--fmad=false" } },
.{ .name = "hy4_attention_sink", .src = "hy4_flash/attention_sink", .flags = &.{ "-O3", "--fmad=false" } },
.{ .name = "hy4_mla_project", .src = "hy4_flash/mla_project", .flags = &.{ "-O3", "--fmad=false" } },
.{ .name = "hy4_mla_attention", .src = "hy4_flash/mla_attention", .flags = &.{ "-O3", "--fmad=false" } },
.{ .name = "hy4_ihc", .src = "hy4_flash/ihc", .flags = &.{ "-O3", "--fmad=false" } },
.{ .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
23 changes: 23 additions & 0 deletions zig/build/hy4_flash.zig
Original file line number Diff line number Diff line change
@@ -0,0 +1,23 @@
//! Host checks for native Hy4-flash tensor layouts, retained keys and draft inputs.
const std = @import("std");

pub fn tests(b: *std.Build, test_step: *std.Build.Step) void {
const core = b.createModule(.{
.root_source_file = b.path("zig/src/core/root.zig"),
.target = b.graph.host,
.link_libc = true,
});
const hash = b.createModule(.{ .root_source_file = b.path("zig/src/families/deepseek_v41/engram_hash.zig") });
const module = b.createModule(.{
.root_source_file = b.path("zig/src/families/hy4_flash/host_tests.zig"),
.target = b.graph.host,
.link_libc = true,
.imports = &.{
.{ .name = "core", .module = core },
.{ .name = "engram_hash_core", .module = hash },
},
});
const run = b.addRunArtifact(b.addTest(.{ .root_module = module }));
test_step.dependOn(&run.step);
b.step("test-hy4-flash-host", "Hy4-flash checkpoint layout, slot selection, Engram gathers and DFly2 inputs").dependOn(&run.step);
}
1 change: 1 addition & 0 deletions zig/build/metal_targets.zig
Original file line number Diff line number Diff line change
Expand Up @@ -554,6 +554,7 @@ pub fn metalEngineModules(b: *std.Build, target: std.Build.ResolvedTarget, optim
.link_libc = true,
.imports = &.{ .{ .name = "metal", .module = metal }, .{ .name = "kernel_sources", .module = sources }, .{ .name = "nemotron_draft_ids", .module = draft_ids }, .{ .name = "lanes", .module = lanes }, .{ .name = "fabric", .module = fabric }, .{ .name = "living", .module = living } },
});
engine.addImport("engram_hash_core", b.createModule(.{ .root_source_file = b.path("zig/src/families/deepseek_v41/engram_hash.zig"), .target = target, .optimize = optimize }));
return .{ .metal = metal, .lanes = lanes, .fabric = fabric, .sources = sources, .engine = engine, .living = living, .qwen27 = qwen27_build.engineModules(b, target, metal, sources, engine) };
}

Expand Down
8 changes: 4 additions & 4 deletions zig/gemma4_shared_affine_test.zig
Original file line number Diff line number Diff line change
Expand Up @@ -103,14 +103,14 @@ test "landed Metal source bytes are pinned without shader compilation" {
{
var hash: [32]u8 = undefined;
std.crypto.hash.sha2.Sha256.hash(ks.core_affine_mm, &hash, .{});
// dda89ef49's bytes: 47afc1620..dda89ef49 reworded comments only, after cf10a6b7d's pinned edit
try std.testing.expectEqualStrings("c959eb1f5ac8a57049c09b3aad5d20f26b64f2e47d8b082c47ebbfae90d97a8b", &std.fmt.bytesToHex(hash, .lower));
// Hy4-flash's mapped experts and rounded SiLU, both behind defines that are off for every other caller
try std.testing.expectEqualStrings("2cf4deb55455fda30efb4fce3043ef5d90052d71f48ce7660960e8b588478aca", &std.fmt.bytesToHex(hash, .lower));
}
{
var hash: [32]u8 = undefined;
std.crypto.hash.sha2.Sha256.hash(ks.core_lane_projection, &hash, .{});
// Packed affine lanes with producer sums and independent prompt row blocks.
try std.testing.expectEqualStrings("7befe2028dae5036541f311f230a02d5652e634450ef16dc66dce6e15e935277", &std.fmt.bytesToHex(hash, .lower));
// Packed affine lanes with producer sums, prompt row blocks, inline sums and the 8-bit reg layout.
try std.testing.expectEqualStrings("d921d9a938d3c4f1fe5a1c89ddfd135d96845055bee1721080ba82fef7a9f8e3", &std.fmt.bytesToHex(hash, .lower));
}
}
test "released lane parameters and conservative scratch size" {
Expand Down
82 changes: 82 additions & 0 deletions zig/kernels/cuda/affine_experts.cu
Original file line number Diff line number Diff line change
@@ -0,0 +1,82 @@
// CUDA grouped FFN rows over the checkpoint's 4- or 8-bit MLX affine experts (group size 64).
#include <cuda_bf16.h>
#include <stdint.h>
#include "common/reduce.cuh"

struct AffineExpertShape {
uint32_t width, inner, first, experts, pairs, rows;
float swiglu_limit;
};

template<int Bits>
__device__ float dot(const __nv_bfloat16 *input, const uint32_t *words, const __nv_bfloat16 *scale,
const __nv_bfloat16 *bias, uint32_t width, uint32_t lane) {
constexpr uint32_t mask = (1 << Bits) - 1;
float acc = 0.0f;
for (uint32_t group = 0; group < width / 64; ++group) {
const float s = __bfloat162float(scale[group]), b = __bfloat162float(bias[group]);
for (uint32_t i = lane; i < 64; i += 32) {
const uint32_t index = group * 64 + i;
const uint32_t bit = index * Bits;
const float code = float((words[bit / 32] >> (bit % 32)) & mask);
const float w = __bfloat162float(__float2bfloat16_rn(__fmaf_rn(code, s, b)));
acc = __fmaf_rn(__bfloat162float(input[index]), w, acc);
}
}
return tf_common::warp_sum(acc);
}

template<int Bits, bool Up>
__device__ void expert_rows(const __nv_bfloat16 *x, const int32_t *ids, const int32_t *source,
const uint32_t *words, const __nv_bfloat16 *scale, const __nv_bfloat16 *bias,
void *output, AffineExpertShape a) {
const uint32_t pair = blockIdx.y, lane = threadIdx.x % 32;
const uint32_t n = 4 * blockIdx.x + threadIdx.x / 32;
const uint32_t width = Up ? a.width : a.inner, size = Up ? a.inner : a.width;
if (n >= size) return;
const uint64_t out = uint64_t(pair) * size + n;
const int32_t id = ids[pair];
const int32_t row = Up ? source[pair] : pair;
if (id < 0 || uint32_t(id) < a.first || uint32_t(id) - a.first >= a.experts ||
row < 0 || (Up && uint32_t(row) >= a.rows)) {
if (lane == 0) {
if constexpr (Up) reinterpret_cast<__nv_bfloat16 *>(output)[out] = __float2bfloat16_rn(0.0f);
else reinterpret_cast<float *>(output)[out] = 0.0f;
}
return;
}

const __nv_bfloat16 *input = x + uint64_t(row) * width;
const uint64_t expert_row = uint64_t(uint32_t(id) - a.first) * (Up ? 2 * size : size) + n;
const uint32_t packed_width = width * Bits / 32, groups = width / 64;
const uint64_t wc = expert_row * packed_width, gc = expert_row * groups;
const float first = dot<Bits>(input, words + wc, scale + gc, bias + gc, width, lane);
if constexpr (Up) {
const uint64_t wu = wc + uint64_t(size) * packed_width, gu = gc + uint64_t(size) * groups;
const float second = dot<Bits>(input, words + wu, scale + gu, bias + gu, width, lane);
if (lane == 0) {
float gate = __bfloat162float(__float2bfloat16_rn(first));
float up = __bfloat162float(__float2bfloat16_rn(second));
if (a.swiglu_limit > 0) {
gate = fminf(gate, a.swiglu_limit);
up = fminf(a.swiglu_limit, fmaxf(-a.swiglu_limit, up));
}
const float activated = __bfloat162float(__float2bfloat16_rn(gate / (1.0f + expf(-gate))));
reinterpret_cast<__nv_bfloat16 *>(output)[out] = __float2bfloat16_rn(activated * up);
}
} else if (lane == 0) {
reinterpret_cast<float *>(output)[out] = first;
}
}

#define TF_AFFINE_EXPERTS(bits, suffix, up) \
extern "C" __global__ void __launch_bounds__(128) tf_affine_experts_##suffix##_##bits( \
const __nv_bfloat16 *x, const int32_t *ids, const int32_t *rows, const uint32_t *words, \
const __nv_bfloat16 *scale, const __nv_bfloat16 *bias, void *out, AffineExpertShape shape) { \
expert_rows<bits, up>(x, ids, rows, words, scale, bias, out, shape); \
}

TF_AFFINE_EXPERTS(4, up, true)
TF_AFFINE_EXPERTS(4, down, false)
TF_AFFINE_EXPERTS(8, up, true)
TF_AFFINE_EXPERTS(8, down, false)
21 changes: 21 additions & 0 deletions zig/kernels/cuda/hy4_flash/attention_sink.cu
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
// Finish a head's online softmax with its learned, zero-value sink.
extern "C" __global__ void tf_hy4_finish_attention(
const float *maxima,
const float *mass,
const float *numerator,
const float *sinks,
float *output,
unsigned int rows,
unsigned int heads,
unsigned int width) {
const unsigned int row_head = blockIdx.x;
const unsigned int column = blockIdx.y * blockDim.x + threadIdx.x;
if (column >= width || row_head >= static_cast<unsigned long long>(rows) * heads) return;

const float sink = sinks[row_head % heads];
const float top = fmaxf(maxima[row_head], sink);
const float prior = expf(maxima[row_head] - top);
const float denominator = mass[row_head] * prior + expf(sink - top);
const unsigned long long offset = static_cast<unsigned long long>(row_head) * width + column;
output[offset] = numerator[offset] * prior / denominator;
}
59 changes: 59 additions & 0 deletions zig/kernels/cuda/hy4_flash/ihc.cu
Original file line number Diff line number Diff line change
@@ -0,0 +1,59 @@
// Hy4-flash reads independent stream gates in FP32 and stores BF16 hidden rows.
#include <cuda_bf16.h>
#include <stdint.h>
#include "../common/reduce.cuh"

struct Hy4IhcShape {
uint32_t rows, width, gates;
float eps, gate_eps, post_magnitude;
};

extern "C" __global__ void __launch_bounds__(256) tf_hy4_ihc_collapse(
const __nv_bfloat16 *hidden, const float *project, const float *bias, const float *scale,
__nv_bfloat16 *collapsed, float *post, Hy4IhcShape a) {
__shared__ float partial[9][8], pre[4];
const uint32_t t = threadIdx.x, wide = 4 * a.width, row = blockIdx.x;
const uint32_t lane = t % 32, warp = t / 32;
const __nv_bfloat16 *x = hidden + uint64_t(row) * wide;
float sq = 0.0f, logits[8] = {};
for (uint32_t i = t; i < wide; i += 256) {
const float v = __bfloat162float(x[i]);
sq = __fmaf_rn(v, v, sq);
for (uint32_t j = 0; j < a.gates; ++j) logits[j] = __fmaf_rn(v, project[j * wide + i], logits[j]);
}
sq = tf_common::warp_sum(sq);
if (lane == 0) partial[8][warp] = sq;
for (uint32_t j = 0; j < a.gates; ++j) {
const float score = tf_common::warp_sum(logits[j]);
if (lane == 0) partial[j][warp] = score;
}
__syncthreads();
if (t < a.gates) {
float sum = 0.0f, dot = 0.0f;
for (uint32_t i = 0; i < 8; ++i) {
sum += partial[8][i];
dot += partial[t][i];
}
const float mix = dot * rsqrtf(sum / float(wide) + a.eps);
const float gate = 1.0f / (1.0f + expf(-(mix * scale[t / 4] + bias[t])));
if (t < 4) pre[t] = gate + a.gate_eps;
else post[uint64_t(row) * 4 + t - 4] = a.post_magnitude * gate + a.gate_eps;
}
__syncthreads();
for (uint32_t i = t; i < a.width; i += 256) {
float v = 0.0f;
for (uint32_t j = 0; j < 4; ++j) v += pre[j] * __bfloat162float(x[j * a.width + i]);
collapsed[uint64_t(row) * a.width + i] = __float2bfloat16_rn(v);
}
}

extern "C" __global__ void __launch_bounds__(256) tf_hy4_ihc_add(
const __nv_bfloat16 *residual, const __nv_bfloat16 *branch, const float *post,
__nv_bfloat16 *output, Hy4IhcShape a) {
const uint32_t i = blockIdx.x * blockDim.x + threadIdx.x, row = blockIdx.y;
if (i >= 4 * a.width) return;
const uint64_t full = uint64_t(row) * 4 * a.width + i;
const uint64_t local = uint64_t(row) * a.width + i % a.width;
output[full] = __float2bfloat16_rn(__bfloat162float(residual[full]) +
post[uint64_t(row) * 4 + i / a.width] * __bfloat162float(branch[local]));
}
58 changes: 58 additions & 0 deletions zig/kernels/cuda/hy4_flash/index_recall.cu
Original file line number Diff line number Diff line change
@@ -0,0 +1,58 @@
// Score only earlier completed groups. When they all fit, selection reads no scores.
#include <cuda_bf16.h>
#include <stdint.h>
#include "../common/reduce.cuh"
#include "../glm_index_pools.cuh"

struct Hy4RecallShape { uint32_t rows, score_groups, group_budget; };
struct Hy4RecallRow { uint32_t group_base, token; };

extern "C" __global__ void __launch_bounds__(128) tf_hy4_group_scores(
const __nv_bfloat16 *query, const __nv_bfloat16 *keys, const __nv_bfloat16 *head_weights,
const Hy4RecallRow *rows, float *scores, Hy4RecallShape a, float head_scale) {
const uint32_t r = blockIdx.y, lane = threadIdx.x % 32;
const uint32_t group = blockIdx.x * 4 + threadIdx.x / 32;
const Hy4RecallRow row = rows[r];
const uint32_t closed = row.token / 4;
if (closed < a.group_budget || closed > a.score_groups || group >= closed) return;
const __nv_bfloat16 *key = keys + (uint64_t(row.group_base) + group) * 128;
float cached[4];
for (uint32_t d = 0; d < 4; ++d) cached[d] = __bfloat162float(key[lane + d * 32]);
float score = 0.0f;
for (uint32_t head = 0; head < 16; ++head) {
const __nv_bfloat16 *q = query + (uint64_t(r) * 16 + head) * 128;
float dot = 0.0f;
for (uint32_t d = 0; d < 4; ++d) dot = __fmaf_rn(__bfloat162float(q[lane + d * 32]), cached[d], dot);
dot = tf_common::warp_sum(dot);
const float weight = __bfloat162float(head_weights[uint64_t(r) * 16 + head]) * head_scale;
score = __fmaf_rn(weight, fmaxf(dot, 0.0f), score);
}
if (lane == 0) scores[uint64_t(r) * a.score_groups + group] = score;
}

extern "C" __global__ void __launch_bounds__(256) tf_hy4_recall_groups(
const float *scores, const Hy4RecallRow *rows, int32_t *tokens, int32_t *counts, Hy4RecallShape a) {
__shared__ glm_index::Smem scratch;
__shared__ int64_t selected[511];
const uint32_t r = blockIdx.x, position = rows[r].token, closed = position / 4;
if (closed > a.score_groups) {
if (threadIdx.x == 0) counts[r] = 0;
return;
}
const uint32_t keep = min(closed, a.group_budget - 1);
if (closed > keep) {
int phase = 0;
const glm_index::Row candidates { scores + uint64_t(r) * a.score_groups, int(closed) };
glm_index::select(scratch, candidates, int(keep), selected, phase);
} else {
for (uint32_t i = threadIdx.x; i < keep; i += 256) selected[i] = i;
}
__syncthreads();
int32_t *out = tokens + uint64_t(r) * a.group_budget * 4;
const uint32_t count = keep * 4 + position % 4 + 1;
for (uint32_t i = threadIdx.x; i < count; i += 256) {
const uint32_t id = i / 4 < keep ? uint32_t(selected[i / 4]) : closed;
out[i] = int32_t(id * 4 + i % 4);
}
if (threadIdx.x == 0) counts[r] = int32_t(count);
}
32 changes: 32 additions & 0 deletions zig/kernels/cuda/hy4_flash/indexpool.cu
Original file line number Diff line number Diff line change
@@ -0,0 +1,32 @@
// Hy4-flash's four-slot sparse index pooling before key normalization and RoPE.
extern "C" __global__ void tf_hy4_pool_groups(
const float *values,
const float *gates,
const float *position_bias,
float *output,
unsigned int groups,
unsigned int width) {
const unsigned int group = blockIdx.x;
const unsigned int column = blockIdx.y * blockDim.x + threadIdx.x;
if (column >= width || group >= groups) return;

const unsigned long long base = static_cast<unsigned long long>(group) * 4 * width + column;
float logits[4];
#pragma unroll
for (unsigned int slot = 0; slot < 4; ++slot) {
const unsigned int offset = slot * width;
logits[slot] = gates[base + offset] + position_bias[offset + column];
}
const float maximum = fmaxf(fmaxf(logits[0], logits[1]), fmaxf(logits[2], logits[3]));
float weights[4];
#pragma unroll
for (unsigned int slot = 0; slot < 4; ++slot) weights[slot] = expf(logits[slot] - maximum);
const float normalizer = ((weights[0] + weights[1]) + weights[2]) + weights[3];
float projected[4];
#pragma unroll
for (unsigned int slot = 0; slot < 4; ++slot) {
projected[slot] = values[base + slot * width] * (weights[slot] / normalizer);
}
output[static_cast<unsigned long long>(group) * width + column] =
((projected[0] + projected[1]) + projected[2]) + projected[3];
}
37 changes: 37 additions & 0 deletions zig/kernels/cuda/hy4_flash/mla_attention.cu
Original file line number Diff line number Diff line change
@@ -0,0 +1,37 @@
// Score absorbed queries against retained BF16 cache rows. The retained slots already include any causal limit.
#include <cuda_bf16.h>
#include <stdint.h>
#include "../common/mla.cuh"

extern "C" __global__ void __launch_bounds__(256) tf_hy4_attend_chunks(
const __nv_bfloat16 *qa, const __nv_bfloat16 *cache, const int *slots, const int *counts,
float *numerator, float *maxima, float *mass, int64_t rows, int64_t heads, int64_t key_stride,
float scale) {
glm_attn::chunks_wide<16, false, 64>(
qa, cache, nullptr, slots, counts, numerator, maxima, mass, rows, heads, key_stride, scale,
1, nullptr, 0);
}

// Merge tiled maxima and mass, counting each head's learned zero-value sink exactly once.
extern "C" __global__ void __launch_bounds__(128) tf_hy4_attend_merge(
const float *numerator, const float *maxima, const float *mass, const float *sinks,
__nv_bfloat16 *output, int64_t rows, int64_t heads, int32_t chunks) {
constexpr int latent = glm_attn::LW;
const int64_t head = blockIdx.y;
const int64_t row_head = blockIdx.x * heads + head;
const int64_t plane = rows * heads;
const int column = threadIdx.x * 4;
float top = sinks[head];
for (int i = 0; i < chunks; ++i) top = fmaxf(top, maxima[i * plane + row_head]);
float denom = expf(sinks[head] - top);
float acc[4] = {};
for (int i = 0; i < chunks; ++i) {
const int64_t base = i * plane + row_head;
const float p = expf(maxima[base] - top);
denom = __fmaf_rn(mass[base], p, denom);
#pragma unroll
for (int j = 0; j < 4; ++j) acc[j] = __fmaf_rn(numerator[base * latent + column + j], p, acc[j]);
}
#pragma unroll
for (int j = 0; j < 4; ++j) output[row_head * latent + column + j] = __float2bfloat16_rn(acc[j] / denom);
}
Loading
Loading