diff --git a/CHANGELOG.md b/CHANGELOG.md index 4e92070b6b1..61110476997 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -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. diff --git a/tools/pdl_early_loads.py b/tools/pdl_early_loads.py index 40ac296db15..64a982a891b 100644 --- a/tools/pdl_early_loads.py +++ b/tools/pdl_early_loads.py @@ -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): diff --git a/zig/build/cuda.zig b/zig/build/cuda.zig index 248c3949c66..20e8671defd 100644 --- a/zig/build/cuda.zig +++ b/zig/build/cuda.zig @@ -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: { diff --git a/zig/dense_serving_test.zig b/zig/dense_serving_test.zig index a99df4ad4e0..57f1499bc9f 100644 --- a/zig/dense_serving_test.zig +++ b/zig/dense_serving_test.zig @@ -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 @@ -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)); } diff --git a/zig/kernels/cuda/qwen35.cu b/zig/kernels/cuda/qwen35.cu index 3412166b1a2..fa65456fcea 100644 --- a/zig/kernels/cuda/qwen35.cu +++ b/zig/kernels/cuda/qwen35.cu @@ -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; @@ -170,6 +171,7 @@ __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(H, R, W, X, eps, D, P, XS); } @@ -177,6 +179,7 @@ extern "C" __global__ void __launch_bounds__(256) tf_q35_norm(__nv_bfloat16* __r 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(H, R, W, X, eps, D, P, XS); } @@ -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; @@ -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; @@ -443,6 +448,7 @@ __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(X, W, OUT, heads, stride, hstride, eps, P); } @@ -450,6 +456,7 @@ extern "C" __global__ void __launch_bounds__(64) tf_q35_head_norm(const __nv_bfl 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(X, W, OUT, heads, stride, hstride, eps, P); } @@ -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}); } @@ -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]; diff --git a/zig/kernels/cuda/qwen_pdl.cuh b/zig/kernels/cuda/qwen_pdl.cuh new file mode 100644 index 00000000000..fbcc4ba48e8 --- /dev/null +++ b/zig/kernels/cuda/qwen_pdl.cuh @@ -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 diff --git a/zig/src/core/profile.zig b/zig/src/core/profile.zig index 42b39f6ad48..39ea907baf5 100644 --- a/zig/src/core/profile.zig +++ b/zig/src/core/profile.zig @@ -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, @@ -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" }, diff --git a/zig/src/families/qwen3_5/cuda.zig b/zig/src/families/qwen3_5/cuda.zig index 556bfe9a2cb..4d3375563b5 100644 --- a/zig/src/families/qwen3_5/cuda.zig +++ b/zig/src/families/qwen3_5/cuda.zig @@ -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; diff --git a/zig/src/families/qwen3_5/cuda_engine.zig b/zig/src/families/qwen3_5/cuda_engine.zig index 5421083adca..7ff380f43b6 100644 --- a/zig/src/families/qwen3_5/cuda_engine.zig +++ b/zig/src/families/qwen3_5/cuda_engine.zig @@ -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; @@ -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, @@ -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 = .{}, @@ -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; @@ -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; @@ -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); @@ -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 }; @@ -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); @@ -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. diff --git a/zig/src/families/qwen3_5/cuda_forward.zig b/zig/src/families/qwen3_5/cuda_forward.zig index 834e494f4b4..56ab6e16352 100644 --- a/zig/src/families/qwen3_5/cuda_forward.zig +++ b/zig/src/families/qwen3_5/cuda_forward.zig @@ -96,11 +96,11 @@ pub fn body(e: *E.Engine, shape: anytype) !void { const layer: c_int = @intCast(di); try e.projManyPrompt(&.{ m.qkv, m.z, m.a, m.b }, e.x, &.{ e.qkv, e.z, e.a, e.b }, total, prompt); if (e.learning) |k| try k.delta(i, e.qkv, e.z, e.b, e.a, total); - try e.run(e.fns.gdn_pre, .{ 1, 2 * g.k_heads + g.v_heads, total }, .{ 32, 1, 1 }, .{ geo, e.qkv, t_segs, t_rows, t_par, layer, m.conv, e.a, e.b, m.a_log, m.dt_bias, e.q, e.k, e.v, e.g_, e.beta, t_params }); + try e.runPdl(e.fns.gdn_pre, .{ 1, 2 * g.k_heads + g.v_heads, total }, .{ 32, 1, 1 }, .{ geo, e.qkv, t_segs, t_rows, t_par, layer, m.conv, e.a, e.b, m.a_log, m.dt_bias, e.q, e.k, e.v, e.g_, e.beta, t_params }); // one recorded window of 2+ rows: gdn_pre logged its tails, conv_commit would only return if (!(record and nseg == 1 and total > 1)) try e.run(e.fns.conv_commit, .{ (g.convWidth() + 255) / 256, nseg, 1 }, .{ 256, 1, 1 }, .{ geo, e.qkv, t_segs, t_par, layer, t_params }); if (prompt and nseg == 1) try @import("cuda_prompt.zig").delta(e, di, total) else try e.deltaScan(record, shape.slots, nseg, layer); - try e.run(e.fns.gdn_post, .{ 1, g.v_heads, total }, .{ 32, 1, 1 }, .{ geo, e.y, e.z, m.norm, g.eps, e.mix, t_params, sums }); + try e.runPdl(e.fns.gdn_post, .{ 1, g.v_heads, total }, .{ 32, 1, 1 }, .{ geo, e.y, e.z, m.norm, g.eps, e.mix, t_params, sums }); try e.projAgain(m.out, e.mix, e.r, total, prompt); di += 1; }, @@ -112,9 +112,9 @@ pub fn body(e: *E.Engine, shape: anytype) !void { } else try e.projManyPrompt(&.{ m.q, m.k, m.v }, e.x, &.{ e.qraw, e.kraw, e.vraw }, total, prompt); if (e.learning) |k| try k.attention(i, e.qraw, e.kraw, e.vraw, total); const head_norm = if (g.bf16) e.fns.head_norm_shift else e.fns.head_norm; - try e.run(head_norm, .{ total * g.q_heads, 1, 1 }, .{ 64, 1, 1 }, .{ e.qraw, m.q_norm, e.qn, @as(c_int, @intCast(g.q_heads)), @as(c_int, @intCast(2 * aw)), @as(c_int, 2 * head_dim), g.eps, t_params }); - try e.run(head_norm, .{ total * g.kv_heads, 1, 1 }, .{ 64, 1, 1 }, .{ e.kraw, m.k_norm, e.kn, @as(c_int, @intCast(g.kv_heads)), @as(c_int, @intCast(g.kv_heads * head_dim)), @as(c_int, head_dim), g.eps, t_params }); - try launch(e, if (e.kv8) e.fp8.rope else e.fns.rope, sig.rope, .{ total, g.q_heads + g.kv_heads, 1 }, .{ head_dim, 1, 1 }, .{ geo, e.qn, e.kn, e.vraw, t_segs, t_rows, t_anc, @as(c_int, ai), t_params, mpos, e.rope_table }); + try e.runPdl(head_norm, .{ total * g.q_heads, 1, 1 }, .{ 64, 1, 1 }, .{ e.qraw, m.q_norm, e.qn, @as(c_int, @intCast(g.q_heads)), @as(c_int, @intCast(2 * aw)), @as(c_int, 2 * head_dim), g.eps, t_params }); + try e.runPdl(head_norm, .{ total * g.kv_heads, 1, 1 }, .{ 64, 1, 1 }, .{ e.kraw, m.k_norm, e.kn, @as(c_int, @intCast(g.kv_heads)), @as(c_int, @intCast(g.kv_heads * head_dim)), @as(c_int, head_dim), g.eps, t_params }); + try launchPdl(e, if (e.kv8) e.fp8.rope else e.fns.rope, sig.rope, .{ total, g.q_heads + g.kv_heads, 1 }, .{ head_dim, 1, 1 }, .{ geo, e.qn, e.kn, e.vraw, t_segs, t_rows, t_anc, @as(c_int, ai), t_params, mpos, e.rope_table }); if (unread and last_layer) return; // the keys, values and their rotary rows are all this chunk keeps if (prompt and nseg == 1 and (g.q_heads / g.kv_heads) % 2 == 0) { // a prompt chunk's rows over its own cache: tensor-core tiles in place of the decode partials @@ -140,7 +140,7 @@ pub fn body(e: *E.Engine, shape: anytype) !void { const mix0 = e.mix + t0 * aw * 2; const gate_args = .{ geo, y0, e.qraw + t0 * 2 * aw * 2, mix0, @as(c_int, @intCast(rows)), gp, sums }; const gate_grid = .{ (rows * aw + 255) / 256, 1, 1 }; - try launch(e, e.fns.attn_gate, sig.attn_gate, gate_grid, .{ 256, 1, 1 }, gate_args); + try launchPdl(e, e.fns.attn_gate, sig.attn_gate, gate_grid, .{ 256, 1, 1 }, gate_args); if (e.learning) |k| try k.gated(i, e.mix, total); try e.projAgain(m.o, mix0, e.r + t0 * g.hidden * 2, rows, prompt); ai += 1; @@ -188,6 +188,12 @@ fn launch(e: *E.Engine, f: cuda.Function, comptime s: sig.Sig, grid: [3]usize, b return e.run(f, grid, block, args); } +/// A glue launch with a qwen_pdl::enter() prologue, dependent under TF_QWEN_PDL. +fn launchPdl(e: *E.Engine, f: cuda.Function, comptime s: sig.Sig, grid: [3]usize, block: [3]usize, args: anytype) !void { + sig.check(s, @TypeOf(args)); + return e.runPdl(f, grid, block, args); +} + /// A bf16 decode attention launch with its two tile buffers of dynamic shared memory. fn shared(e: *E.Engine, f: cuda.Function, comptime s: sig.Sig, grid: [3]usize, threads: u32, args: anytype) !void { sig.check(s, @TypeOf(args)); diff --git a/zig/src/families/qwen3_5/cuda_modelopt.zig b/zig/src/families/qwen3_5/cuda_modelopt.zig index 0c515c13160..da853b39ed4 100644 --- a/zig/src/families/qwen3_5/cuda_modelopt.zig +++ b/zig/src/families/qwen3_5/cuda_modelopt.zig @@ -249,6 +249,7 @@ pub const Kernels = struct { pub fn load(d: *const cuda.Driver, capability: u32, sms: usize, moe: bool) !Kernels { if (modeloptRefusal(capability) != null) return error.ModeloptNeedsSm80; var lane = try cuda.qmmf.Lane.load(d, capability / 10); + lane.pdl = @import("cuda_pdl.zig").on(); // 1A: the qmmf image already prefetches weights before its wait errdefer lane.unload(); var prompt = try cuda.nvfp4.Prompt.load(d); errdefer prompt.unload(); diff --git a/zig/src/families/qwen3_5/cuda_pdl.zig b/zig/src/families/qwen3_5/cuda_pdl.zig new file mode 100644 index 00000000000..ebedfcbace3 --- /dev/null +++ b/zig/src/families/qwen3_5/cuda_pdl.zig @@ -0,0 +1,64 @@ +//! Qwen3.8's launches as dependent launches (TF_QWEN_PDL, default off): the glue kernels open with qwen_pdl::enter(). +const std = @import("std"); +const cuda = @import("cuda"); + +var state: std.atomic.Value(u8) = .init(0); // 0 unread, 1 off, 2 on +var supported: std.atomic.Value(bool) = .init(true); + +fn bindMajor(major: c_int) void { + supported.store(major >= 9, .release); +} + +/// Bind the process-wide launch policy to a context before loading any Qwen modules. +pub fn bind(ctx: *const cuda.Context) !void { + bindMajor(try ctx.attribute(.compute_capability_major)); +} + +/// TF_QWEN_PDL, read once: exact 0 launches Qwen's kernels plain (the environment refuses malformed values at startup). +pub fn on() bool { + const v = state.load(.monotonic); + if (v != 0) return v == 2 and supported.load(.acquire); + const want = @import("sys").environment.value(bool, "TF_QWEN_PDL", @import("profile").lookup("TF_QWEN_PDL"), false) catch false; + state.store(if (want) 2 else 1, .monotonic); + return want and supported.load(.acquire); +} + +/// `cfg` as a Qwen launch makes it: dependent when `pdl`. +pub fn config(cfg: cuda.launch.Config, pdl: bool) cuda.launch.Config { + var c = cfg; + c.pdl = pdl; + return c; +} + +/// Test drivers: a cuLaunchKernelEx handing each launch, its attributes dropped, to a recording cuLaunchKernel. +pub fn forwardEx(comptime plain: @FieldType(cuda.abi.Api, "cuLaunchKernel")) @FieldType(cuda.abi.Api, "cuLaunchKernelEx") { + const P = ?[*]?*anyopaque; + return &struct { + fn ex(c: *const cuda.abi.LaunchConfig, f: cuda.abi.Function, p: P, e: P) callconv(.c) cuda.abi.Result { + return plain(f, c.grid_x, c.grid_y, c.grid_z, c.block_x, c.block_y, c.block_z, c.shared_bytes, c.stream, p, e); + } + }.ex; +} + +test "a Qwen launch keeps its config and sets only pdl" { + const base: cuda.launch.Config = .{ .grid = .{ .x = 7, .y = 2 }, .block = .{ .x = 128 }, .shared = 4096 }; + const c = config(base, true); + try std.testing.expect(c.pdl and c.grid.x == 7 and c.grid.y == 2 and c.block.x == 128 and c.shared == 4096); + try std.testing.expect(!config(c, false).pdl); +} + +test "Qwen PDL policy: default off, pre-sm90 devices disable it, sm90 retains an explicit on" { + state.store(2, .monotonic); + supported.store(true, .release); + defer { + state.store(0, .monotonic); + supported.store(true, .release); + } + bindMajor(8); + try std.testing.expect(!on()); + supported.store(true, .release); + bindMajor(9); + try std.testing.expect(on()); + state.store(1, .monotonic); + try std.testing.expect(!on()); +} diff --git a/zig/src/families/qwen3_5/cuda_pdl_contract_test.zig b/zig/src/families/qwen3_5/cuda_pdl_contract_test.zig new file mode 100644 index 00000000000..f0dcc05b818 --- /dev/null +++ b/zig/src/families/qwen3_5/cuda_pdl_contract_test.zig @@ -0,0 +1,14 @@ +//! REV26: TF_QWEN_PDL changes only the launch attribute; the SASS rule covers the glue kernels' waits. +const std = @import("std"); +const pdl = @import("cuda_pdl.zig"); + +test "TF_QWEN_PDL changes only the dependent-launch attribute" { + const base: @import("cuda").Config = .{ .grid = .{ .x = 160, .y = 1, .z = 2 }, .block = .{ .x = 128 }, .shared = 8192 }; + const plain = pdl.config(base, false); + const dependent = pdl.config(base, true); + try std.testing.expect(!plain.pdl and dependent.pdl); + try std.testing.expectEqual(plain.grid.x, dependent.grid.x); + try std.testing.expectEqual(plain.grid.z, dependent.grid.z); + try std.testing.expectEqual(plain.block.x, dependent.block.x); + try std.testing.expectEqual(plain.shared, dependent.shared); +} diff --git a/zig/src/platform/environment.zig b/zig/src/platform/environment.zig index 59624049bd6..a10319debdf 100644 --- a/zig/src/platform/environment.zig +++ b/zig/src/platform/environment.zig @@ -162,6 +162,7 @@ pub const rules = [_]Rule{ .{ .name = "TF_GLM_PROF", .scope = .glm, .kind = .flag, .forms = "0 or 1" }, .{ .name = "TF_GLM_LINK_WAIT", .scope = .glm, .kind = .flag, .forms = "0 or 1" }, .{ .name = "TF_GLM_PDL", .scope = .glm, .kind = .flag, .forms = "0 or 1" }, + .{ .name = "TF_QWEN_PDL", .scope = .common, .kind = .flag, .forms = "0 or 1" }, .{ .name = "TF_GLM_PROMPT_STEPS", .scope = .glm, .kind = .flag, .forms = "0 or 1" }, .{ .name = "TF_GLM_SHARED", .scope = .glm, .kind = .flag, .forms = "0 or 1" }, .{ .name = "TF_GLM_DSEL", .scope = .glm, .kind = .flag, .forms = "0 or 1" }, diff --git a/zig/src/platform/environment_test.zig b/zig/src/platform/environment_test.zig index 6682d40ab70..5a182df0c21 100644 --- a/zig/src/platform/environment_test.zig +++ b/zig/src/platform/environment_test.zig @@ -76,6 +76,8 @@ const valid = [_]Case{ .{ .name = "TF_MTP_DRAFTS", .raw = "0", .n = 0 }, .{ .name = "TF_QWEN_KEEP_LATE", .raw = "0", .n = 0 }, .{ .name = "TF_QWEN_KEEP_LATE", .raw = "1", .n = 1 }, + .{ .name = "TF_QWEN_PDL", .raw = "0", .n = 0 }, + .{ .name = "TF_QWEN_PDL", .raw = "1", .n = 1 }, .{ .name = "TF_QWEN_KV_PAGE_TEST", .raw = "1", .n = 1 }, .{ .name = "TF_QWEN_KV_PAGE_TEST", .raw = "2147483647", .n = 2147483647 }, .{ .name = "TF_COST_KEY_TRACE", .raw = "0", .n = 0 }, diff --git a/zig/tests/cuda/contract_q35_launch_args_host.zig b/zig/tests/cuda/contract_q35_launch_args_host.zig index ebd9408b5c2..7976cb3af94 100644 --- a/zig/tests/cuda/contract_q35_launch_args_host.zig +++ b/zig/tests/cuda/contract_q35_launch_args_host.zig @@ -198,7 +198,7 @@ fn sitesIn(a: std.mem.Allocator, path: []const u8, text: [:0]const u8, out: *std while (i < list.len) : (i += 1) { if (list[i].tag != .identifier) continue; const name = text[list[i].loc.start..list[i].loc.end]; - if (!std.mem.eql(u8, name, "run") and !std.mem.eql(u8, name, "shared") and !std.mem.eql(u8, name, "launch")) continue; + if (!std.mem.eql(u8, name, "run") and !std.mem.eql(u8, name, "runPdl") and !std.mem.eql(u8, name, "shared") and !std.mem.eql(u8, name, "launch") and !std.mem.eql(u8, name, "launchPdl")) continue; if (i + 1 >= list.len or list[i + 1].tag != .l_paren) continue; var spans: std.ArrayList(Span) = .empty; var depth: usize = 0;