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 @@ -10,6 +10,8 @@ Each release's page on GitHub has its notes and measurements. See [the 1.0.0 rel

- Nemotron on CUDA: a new prompt is filled a chunk at a time between other streams' decode rounds, so a long prompt no longer stalls replies already streaming; tokens unchanged.

- Qwen3.8 on CUDA: `TF_QWEN_PDL=1` (opt-in) uses programmatic dependent launch on the ModelOpt NVFP4 lanes and the qwen35 glue kernels; about 1.5% faster decode and prompt on a GB10, tokens unchanged.

- Lanes: drafted lone streams in families that opt in to copy pricing are priced as in 1.3.3 again; up to 2.5% faster at 4 code streams on M3 and M5 Ultra with the DFlash2 drafter, level elsewhere, tokens unchanged.
- Lane host: score requests and server shutdown wait on their own conditions, so neither can hang when a timed waiter on a shared condition times out with a wake pending.

Expand Down
2 changes: 1 addition & 1 deletion tools/pdl_early_loads.py
Original file line number Diff line number Diff line change
Expand Up @@ -17,7 +17,7 @@
WEIGHT_FIRST = re.compile(r"qmmf_kernel|^glm_mm\d+_(\d+|rows)$")
ADDR = re.compile(r"/\*([0-9a-f]{4,})\*/")
BRANCH = re.compile(r"\b(BRA|BRX|BRXU|JMP|JMX|JMXU|CALL)\b(\S*)\s+(.*?);")
PLAIN = re.compile(r"qmmf_prompt_k32_kernel|^tf_qmmf_shared|^tf_qmmf_native_fp4_check$") # launched plain only
PLAIN = re.compile(r"qmmf_prompt_k32_kernel|^tf_qmmf_shared|^tf_qmmf_native_fp4_check$|^tf_q35_(embed8?|splice|sums|conv_commit|gdn_chain|attn_merge|attn_partial|attn_rows|attn_rows_join|attn_partial_whole|attn_rows_whole)$") # launched plain only


def scan(text):
Expand Down
4 changes: 2 additions & 2 deletions zig/build/cuda.zig
Original file line number Diff line number Diff line change
Expand Up @@ -78,8 +78,8 @@ pub fn targets(b: *std.Build, target: std.Build.ResolvedTarget, optimize: std.bu
// check-pdl-loads: no global read above a dependent launch's wait (tools/pdl_early_loads.py)
if (nvcc) |tool| {
const check = b.addSystemCommand(&.{ "python3", "tools/pdl_early_loads.py", b.pathJoin(&.{ std.fs.path.dirname(tool) orelse ".", "cuobjdump" }) });
for (kernels, images) |k, image| if (image) |file| if (std.mem.startsWith(u8, k.name, "glm_") or std.mem.eql(u8, k.name, "qmmf")) check.addFileArg(file);
b.step("check-pdl-loads", "No global read before a dependent launch's wait in the GLM images and qmmf (needs -Dnvcc)").dependOn(&check.step);
for (kernels, images) |k, image| if (image) |file| if (std.mem.startsWith(u8, k.name, "glm_") or std.mem.eql(u8, k.name, "qmmf") or std.mem.eql(u8, k.name, "qwen35")) check.addFileArg(file);
b.step("check-pdl-loads", "No global read before a dependent launch's wait in the GLM images, qwen35 glue and qmmf (needs -Dnvcc)").dependOn(&check.step);
}
// MiniMax H3's kernel image: its library and the contract's runner take it
const h3_image = if (nvcc) |tool| fatbin(b, tool, version orelse blk: {
Expand Down
8 changes: 4 additions & 4 deletions zig/dense_serving_test.zig
Original file line number Diff line number Diff line change
Expand Up @@ -18,8 +18,8 @@ test "dense serving: owned CUDA images retain their reviewed lane and decode byt
try std.testing.expectEqualStrings("8780fd710be3ce2f04e53fa1e69eb062809d3bec6391d9bd49983d0588e374d0", &hash(group));
// #2825 hoists copy addresses before the K loop; copy order and math match prefill_kernel.
try std.testing.expectEqualStrings("e3724114b87cae6f6f761b2f86357f05b1693d84a0233e4d58ce46349fa853f6", &hash(@embedFile("kernels/cuda/qmm_prefill.cu")));
// the join variant's bytes: tf_q35_attn_rows_join for streams on shared pages; main's kernels' SASS unchanged
try std.testing.expectEqualStrings("77ac41e5764a79cca2313ecd09664479b8b4736747c79188e1ad5cae29fd03e4", &hash(@embedFile("kernels/cuda/qwen35.cu")));
// join variant's tf_q35_attn_rows_join for shared pages keeps SASS; #4706 adds TF_QWEN_PDL prologues (default off)
try std.testing.expectEqualStrings("12cb39dc09ba9e00fec8837739091cc2f305092043b0c92e23e0300c987c9ad3", &hash(@embedFile("kernels/cuda/qwen35.cu")));
// #1879's bytes: a comment names cuda_scratch.zig, where max_chunks moved; the code is unchanged
try std.testing.expectEqualStrings("f9e4a040cf219aac8db211df25d264dba390fce4a7e8da45557652c6ff0f28ba", &hash(@embedFile("kernels/cuda/qwen35.cuh")));
// 67711a6aa7's bytes: the opt-in DSpine draft kernels (#2633); default serving unchanged
Expand Down Expand Up @@ -51,6 +51,6 @@ test "dense serving: owned launches and projections retain their reviewed argume
try out.append(std.testing.allocator, c);
};
}
// The launch sequence includes main's moved delta scan and MTP's retained-row tap argument.
try std.testing.expectEqualStrings("2099ef3b0a28d63d079b65d191a9c3be7e7c0ff93fb9b53ec9d6a6e61565220d", &hash(out.items));
// main's moved delta scan and MTP's retained-row tap argument stay; #4706 adds TF_QWEN_PDL glue (default off)
try std.testing.expectEqualStrings("2822d47ae041b6d7051e39209bd389cb5e4f01520efee64838c1c0e0e5428b75", &hash(out.items));
}
9 changes: 9 additions & 0 deletions zig/kernels/cuda/qwen35.cu
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
// Qwen3.5's hybrids (2B, 27B) on CUDA: the Metal kernels' arithmetic and rounding; a segment is one stream's window.

#include "qwen35.cuh"
#include "qwen_pdl.cuh"
#include "qwen35_attn_tc.cuh"

using namespace tf_q35;
Expand Down Expand Up @@ -170,13 +171,15 @@ __device__ __forceinline__ void norm_rows(__nv_bfloat16* __restrict__ H, const _
extern "C" __global__ void __launch_bounds__(256) tf_q35_norm(__nv_bfloat16* __restrict__ H, const __nv_bfloat16* __restrict__ R,
const __nv_bfloat16* __restrict__ W, __nv_bfloat16* __restrict__ X, float eps, int D,
const int* __restrict__ P, float* __restrict__ XS) {
qwen_pdl::enter();
norm_rows<false>(H, R, W, X, eps, D, P, XS);
}

// tf_q35_norm over HF's raw weights: x = bf16((1 + w) * (h * inv)) with 1 + w in FP32 (a BF16 checkpoint's norms).
extern "C" __global__ void __launch_bounds__(256) tf_q35_norm_shift(__nv_bfloat16* __restrict__ H, const __nv_bfloat16* __restrict__ R,
const __nv_bfloat16* __restrict__ W, __nv_bfloat16* __restrict__ X, float eps,
int D, const int* __restrict__ P, float* __restrict__ XS) {
qwen_pdl::enter();
norm_rows<true>(H, R, W, X, eps, D, P, XS);
}

Expand All @@ -197,6 +200,7 @@ extern "C" __global__ void __launch_bounds__(32) tf_q35_gdn_pre(Geo geo, const _
__nv_bfloat16* __restrict__ Q, __nv_bfloat16* __restrict__ K,
__nv_bfloat16* __restrict__ V, float* __restrict__ G, __nv_bfloat16* __restrict__ BETA,
const int* __restrict__ P) {
qwen_pdl::enter();
const int lane = threadIdx.x;
const int head = blockIdx.y;
const int w = blockIdx.z;
Expand Down Expand Up @@ -385,6 +389,7 @@ extern "C" __global__ void __launch_bounds__(128) tf_q35_gdn_chain(Geo geo, cons
extern "C" __global__ void __launch_bounds__(32) tf_q35_gdn_post(Geo geo, const __nv_bfloat16* __restrict__ Y, const __nv_bfloat16* __restrict__ Z,
const __nv_bfloat16* __restrict__ NW, float eps, __nv_bfloat16* __restrict__ OUT,
const int* __restrict__ P, float* __restrict__ XS) {
qwen_pdl::enter();
__shared__ __align__(16) __nv_bfloat16 done[DK]; // the head's outputs, for XS's group sums (XS may be null)
const int lane = threadIdx.x, hv = blockIdx.y;
if (past_rows(P, blockIdx.z)) return;
Expand Down Expand Up @@ -443,13 +448,15 @@ __device__ __forceinline__ void head_rows(const __nv_bfloat16* __restrict__ X, c
extern "C" __global__ void __launch_bounds__(64) tf_q35_head_norm(const __nv_bfloat16* __restrict__ X, const __nv_bfloat16* __restrict__ W,
__nv_bfloat16* __restrict__ OUT, int heads, int stride, int hstride, float eps,
const int* __restrict__ P) {
qwen_pdl::enter();
head_rows<false>(X, W, OUT, heads, stride, hstride, eps, P);
}

// tf_q35_head_norm over HF's raw q and k norm weights, 1 + w in FP32.
extern "C" __global__ void __launch_bounds__(64) tf_q35_head_norm_shift(const __nv_bfloat16* __restrict__ X, const __nv_bfloat16* __restrict__ W,
__nv_bfloat16* __restrict__ OUT, int heads, int stride, int hstride,
float eps, const int* __restrict__ P) {
qwen_pdl::enter();
head_rows<true>(X, W, OUT, heads, stride, hstride, eps, P);
}

Expand All @@ -468,6 +475,7 @@ extern "C" __global__ void __launch_bounds__(256) tf_q35_rope(Geo geo, __nv_bflo
const __nv_bfloat16* __restrict__ Vr, const Seg* __restrict__ segs,
const int* __restrict__ rowseg, const Ancestor* __restrict__ rowanc, int layer,
const int* __restrict__ P, const int* __restrict__ M, const float* __restrict__ Y) {
qwen_pdl::enter();
rope_rows(geo, Qn, Kn, Vr, segs, rowseg, rowanc, P, M, Y, StoreBf16{layer, geo.kvh});
}

Expand Down Expand Up @@ -515,6 +523,7 @@ __device__ __forceinline__ void block_sums(__nv_bfloat16* done, size_t total, fl
// out = bf16(y * bf16(sigmoid(gate))), the gate the second half of each query head's q_proj rows; rows qh * HD wide.
extern "C" __global__ void tf_q35_attn_gate(Geo geo, const __nv_bfloat16* __restrict__ Y, const __nv_bfloat16* __restrict__ QRAW,
__nv_bfloat16* __restrict__ OUT, int rows, const int* __restrict__ P, float* __restrict__ XS) {
qwen_pdl::enter();
__shared__ __align__(16) __nv_bfloat16 done[256];
const size_t W = (size_t)geo.qh * HD;
if (P != nullptr) rows = P[2];
Expand Down
30 changes: 30 additions & 0 deletions zig/kernels/cuda/qwen_pdl.cuh
Original file line number Diff line number Diff line change
@@ -0,0 +1,30 @@
// Qwen3.8 glue kernels as dependent launches (sm_90 on).
#pragma once

#ifdef __CUDACC__ // the host emulator compiles Qwen kernels without CUDA headers
#include "common/qmm_frag.cuh"
#endif

namespace qwen_pdl {

// The next grid may launch once every CTA of this one has run this (or ended).
__device__ __forceinline__ void trigger() {
#ifdef __CUDACC__
qmm_frag::grid_launch();
#endif
}

// Returns once the grid before has completed and its writes are visible; read those coherently (no const __restrict__).
__device__ __forceinline__ void wait() {
#ifdef __CUDACC__
qmm_frag::grid_wait();
#endif
}

// Every Qwen glue kernel's first statement: a dependent launch then reads and writes exactly as a plain one.
__device__ __forceinline__ void enter() {
trigger();
wait();
}

} // namespace qwen_pdl
2 changes: 2 additions & 0 deletions zig/src/core/profile.zig
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,7 @@ pub const Switch = enum {
TF_QWEN_KV_SHARE,
TF_QWEN_KV_HOST,
TF_QWEN_REQUEST_STARTS,
TF_QWEN_PDL,
TF_GLM_REQUEST_STARTS,
TF_KV_SHARE,
TF_FLASHNEXT_KV_PAGES,
Expand Down Expand Up @@ -148,6 +149,7 @@ pub const entries = [_]Entry{
.{ .id = .TF_CUDA_POOL_AFTER_WARMUP, .families = &.{"qwen3_5"}, .class = .experimental, .syntax = .one, .report_values = &.{"1"}, .effect = "Size an idle device KV pool after Qwen DFlash2 warm-up", .evidence = "Default off; host sizing checks; device capacity and token checks required" },
.{ .id = .TF_CACHE_EVICT, .families = cuda_cache, .backend = "multiple", .scopes = &.{ .{ .backend = "cuda", .families = cuda_cache }, .{ .backend = "metal", .families = &.{ "nemotron_h", "qwen3_5", "qwen3_5_moe", "qwen4_exp", "glm5_next", "glm_moe_dsa", "minimax_m3_vl", "gemma4", "gemma4_unified", "spark2_5", "llama", "lfm2_moe", "lfm3", "lfm3_vl", "step5_vl", "kimi_k3", "kimi_k31" } }, .{ .backend = "xpu", .families = &.{ "nemotron_h", "lfm3", "qwen3_5", "gemma4" } } }, .class = .experimental, .syntax = .present, .report_values = &.{"decayed_resume"}, .effect = "Opt into bounded resume credit for RAM snapshot eviction", .evidence = "#3241; synthetic host rows gate; default main unchanged" },
.{ .id = .TF_QWEN_REQUEST_STARTS, .families = qwen, .class = .arithmetic, .syntax = .one, .effect = "Opt into CUDA message-start prompt cuts", .evidence = "#1334; default-off; GB10 six-turn: resumed equals fresh, one reply differs from unset" },
.{ .id = .TF_QWEN_PDL, .families = qwen, .backend = "cuda", .class = .identical, .syntax = .one, .effect = "Opt into programmatic dependent launches on Qwen3.8's qmmf lanes and glue", .evidence = "REV26; default-off; SASS gate and byte-identical contract cells" },
.{ .id = .TF_GLM_REQUEST_STARTS, .families = &.{"glm5_next"}, .class = .arithmetic, .syntax = .one, .effect = "Opt into CUDA message-start prompt cuts", .evidence = "#2396; default-off; GB10 TP=2 receipts in #2404" },
.{ .id = .TF_QWEN_KV_PAGES, .families = qwen, .class = .identical, .effect = "KV pool page size; memory and workload tradeoffs", .evidence = "#1357" },
.{ .id = .TF_QWEN_KV_PAGES_ALL, .families = qwen, .class = .debug, .syntax = .one, .effect = "Put the engine's own stream on pages too", .evidence = "#1357" },
Expand Down
2 changes: 2 additions & 0 deletions zig/src/families/qwen3_5/cuda.zig
Original file line number Diff line number Diff line change
Expand Up @@ -30,6 +30,8 @@ test {
_ = @import("cuda_forward.zig");
_ = engine;
_ = @import("cuda_modelopt.zig");
_ = @import("cuda_pdl.zig");
_ = @import("cuda_pdl_contract_test.zig");
_ = prompt_int8;
_ = native;
_ = native_moe;
Expand Down
24 changes: 12 additions & 12 deletions zig/src/families/qwen3_5/cuda_engine.zig
Original file line number Diff line number Diff line change
Expand Up @@ -34,10 +34,8 @@ pub const most_verify = Round.most_verify;
pub const argmaxSlices = scratch_memory.argmaxSlices;
pub const most_window = Round.most_window; // Maximum rows a stream's log holds
pub const aligned = scratch_memory.aligned; // Device allocations are 256-byte aligned

/// qwen35.cuh's Geo.
pub const Geo = extern struct { hid: c_int, nk: c_int, nv: c_int, qh: c_int, kvh: c_int, nl: c_int };

const layers = @import("cuda_layers.zig");
pub const Proj = layers.Proj;
pub const Delta = layers.Delta;
Expand All @@ -49,10 +47,8 @@ pub const Keeps = layers.Keeps;
const Kv8 = layers.Kv8;
/// A window: for a tree `parents` names each row's parent (-1: first row); `undo` keeps a one-row rollback copy.
pub const Part = struct { cache: *Cache, rows: usize, parents: ?[]const i32 = null, images: ?*const Images = null, undo: bool = true };

/// An image prompt's rows for its prompt chunks: the staged tables' rows.
pub const Images = Round.Images;

/// What a forward keeps: a prompt chunk its last row's logits or (`rows`) every final-norm row; a window its draws.
pub const Keep = union(enum) {
last,
Expand All @@ -61,16 +57,13 @@ pub const Keep = union(enum) {
hidden,
rows,
none, // a prompt chunk nothing reads: its last layer stops at the state writes

/// Whether the forward is a verify window (recorded, one-row bits); `last`, `rows` and `none` are prompt chunks.
pub fn verifies(k: Keep) bool {
return k != .last and k != .rows and k != .none;
}
};

/// A kept row's draw on the device: sample.cu's keyed rule at `position`, or greedy without one.
pub const Draw = struct { rule: ?cuda.sample.Rule, position: u64 };

pub const Engine = struct {
rec_scratch: recurrent.Pool,
startup: profile.Times = .{},
Expand Down Expand Up @@ -174,7 +167,6 @@ pub const Engine = struct {
hop: ?stage_fwd.Hop = null,
boundary: ?cuda.HostBuffer = null,
held: ?*stage_fwd.Held = null, // rank 0 with rounds in flight: the round's state its head reads later

pub const ids_at = Round.ids_at;
pub const segs_at = Round.segs_at;
pub const rowseg_at = Round.rowseg_at;
Expand All @@ -187,11 +179,9 @@ pub const Engine = struct {
pub const src_at = Round.src_at;
pub const mpos_at = Round.mpos_at;
const tables_len = Round.bytes;

pub fn init(gpa: std.mem.Allocator, io: std.Io, ctx: *const cuda.Context, dir: []const u8, kv8: bool, fit: ?hosted.Fit, prompt_rows_limit: usize) !*Engine {
return initStage(gpa, io, ctx, dir, kv8, fit, prompt_rows_limit, null);
}

/// One engine, or with `span` a pipeline stage holding only its layers' weights and state (RFC #2005).
pub fn initStage(gpa: std.mem.Allocator, io: std.Io, ctx: *const cuda.Context, dir: []const u8, kv8: bool, fit: ?hosted.Fit, prompt_rows_limit: usize, span: ?stage_fwd.Span) !*Engine {
if (!cuda.kernels.available) return error.BuiltWithoutKernels;
Expand Down Expand Up @@ -277,6 +267,7 @@ pub const Engine = struct {
e.prompt_attn = try @import("cuda_prompt.zig").resolve(e.mods[16], e.mods[17]);
try e.int8.resolve(e.mods[18]);
e.fp8 = .{ .rope = try e.mods[9].function("tf_q35_rope8"), .attn_partial = try e.mods[9].function("tf_q35_attn_partial8"), .attn_rows = try e.mods[9].function("tf_q35_attn_rows8"), .attn_rows_join = try e.mods[9].function("tf_q35_attn_rows8_join"), .attn_partial8_whole = try e.mods[9].function("tf_q35_attn_partial8_whole"), .attn_rows8_whole = try e.mods[9].function("tf_q35_attn_rows8_whole"), .compact = try e.mods[9].function("tf_q35k_compact8") };
try @import("cuda_pdl.zig").bind(ctx);
e.mo = if (g.kinds.modelopt) try modelopt.Kernels.load(d, @intCast(10 * major + minor), sms, g.moe()) else null;
errdefer if (e.mo) |*m| m.unload();
e.layers = try gpa.alloc(Layer, g.layers);
Expand All @@ -295,7 +286,6 @@ pub const Engine = struct {
try @import("cuda_engine_tail.zig").finish(e, io, started);
return e;
}

pub fn finishWarm(e: *Engine, io: std.Io, started: i96) !void {
const warm_start = profile.now(io);
e.startup = .{ .load = warm_start - started };
Expand Down Expand Up @@ -403,6 +393,16 @@ pub const Engine = struct {
try cuda.launch.launch(f, cfg, e.stream, &a);
}

/// A glue kernel with a qwen_pdl::enter() prologue: dependent under TF_QWEN_PDL, plain by default.
pub fn runPdl(e: *Engine, f: cuda.Function, grid: [3]usize, block: [3]usize, args: anytype) !void {
if (@import("cuda_launch_trace.zig").active) |t| return t.note(.{ .launch = if (f.handle) |h| @intFromPtr(h) else 0 });
var a: cuda.Args = .{};
inline for (args) |v| a.add(v);
const base: cuda.Config = .{ .grid = .{ .x = @intCast(grid[0]), .y = @intCast(grid[1]), .z = @intCast(grid[2]) }, .block = .{ .x = @intCast(block[0]), .y = @intCast(block[1]), .z = @intCast(block[2]) } };
const cfg = @import("cuda_pdl.zig").config(base, @import("cuda_pdl.zig").on());
try cuda.launch.launch(f, cfg, e.stream, &a);
}

pub fn promptAttention(e: *Engine, layer: usize, from: usize, end: usize) !void {
if (@import("cuda_launch_trace.zig").active) |t| return t.note(.attn);
return @import("cuda_prompt.zig").runFrom(e, layer, from, end);
Expand Down Expand Up @@ -438,7 +438,7 @@ pub const Engine = struct {

pub fn norm(e: *Engine, residual: bool, w: u64, rows: usize) !void {
if (@import("cuda_launch_trace.zig").active) |t| return t.note(.norm);
try e.run(if (e.g.bf16) e.fns.norm_shift else e.fns.norm, .{ rows, 1, 1 }, .{ 256, 1, 1 }, .{ e.h, if (residual) e.r else @as(u64, 0), w, e.x, e.g.eps, @as(c_int, @intCast(e.g.hidden)), e.tables.ptr + params_at, e.xs });
try e.runPdl(if (e.g.bf16) e.fns.norm_shift else e.fns.norm, .{ rows, 1, 1 }, .{ 256, 1, 1 }, .{ e.h, if (residual) e.r else @as(u64, 0), w, e.x, e.g.eps, @as(c_int, @intCast(e.g.hidden)), e.tables.ptr + params_at, e.xs });
}

/// Refuse the whole frame before settling any prior window or launching work.
Expand Down
Loading
Loading