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

## Unreleased

- GLM-5.3-Flash on CUDA takes `--mtp-confidence F` (off by default), as Nemotron does: each MTP draft carries its chance, read from the ranks' greedy pick with their softmax sums, and a chain stops where that chance falls under F. On GB10 at TP=3 with 0.5, decode went from 51.6 to 54.1 tok/s (+4.9%), greedy chat at one stream from 45.0 to 47.9 tok/s, and four distinct prompts at once from 70.6 to 75.0 tok/s, with the same tokens. At TP=2 four greedy code streams were 3.7% slower with it, so a code-heavy TP=2 server is better off without it. Under any `--mtp-confidence` floor, Nemotron's included, a sampled stream now drafts its rates' depth instead of the deepest window. Without the flag every path is unchanged, and `tf_glm_top1` compiles to the same code (#1585). Thanks to @Bizuayeu.

- LFM2.5-24B-A2B on Metal can hand an external drafter the rows of the layers it reads (its taps), copied on the GPU by a new kernel, `lfm2_tap`, that the kernel contract checks bit for bit with two planted controls (#1390, part of #1374). A drafting stream resumes a kept prompt state only when it also holds the drafter's context. Nothing uses the taps yet: without a drafter none are kept and every forward runs as before. Thanks to @BlivionIaG.

- Nemotron on CUDA: the MoE residual's norm, Mamba's group norm, the MTP input norms and the bf16 token rows run on the shared norm and embedding kernels instead of Nemotron's own copies, which are removed. The shared kernels keep Nemotron's summation order, so replies are the same tokens as before, and one fewer CUDA image loads (#1353, step 1 of #548). Thanks to @jschmied.
Expand Down
28 changes: 26 additions & 2 deletions zig/kernels/cuda/glm_glue_rows.cuh
Original file line number Diff line number Diff line change
Expand Up @@ -192,8 +192,8 @@ extern "C" __global__ void tf_glm_conv_shift(__nv_bfloat16* conv, const __nv_bfl
}

// decode.sample_rows' greedy pick, as the host scan: first max of n bf16 logits, NaN never wins; out fp32 bits, lo+id.
extern "C" __global__ void __launch_bounds__(1024) tf_glm_top1(const unsigned short* logits, int64_t n, unsigned lo,
unsigned* out) {
template <bool sums>
__device__ __forceinline__ void glm_top1(const unsigned short* logits, int64_t n, unsigned lo, unsigned* out) {
__shared__ float sv[1024];
__shared__ unsigned si[1024];
const int t = threadIdx.x;
Expand All @@ -217,6 +217,30 @@ extern "C" __global__ void __launch_bounds__(1024) tf_glm_top1(const unsigned sh
out[0] = __float_as_uint(sv[0]);
out[1] = lo + (si[0] == 0xffffffffu ? 0u : si[0]);
}
if constexpr (sums) {
// out[2]: the slice's sum of exp(logit - its max), fp32 bits, from which rank 0 reads the pick's chance
const float m = sv[0];
float s = 0.0f;
for (int64_t i = t; i < n; i += 1024)
s += __expf(__int_as_float(static_cast<int>(static_cast<unsigned>(logits[i]) << 16)) - m);
__syncthreads();
sv[t] = s;
__syncthreads();
for (int h = 512; h > 0; h >>= 1) {
if (t < h) sv[t] += sv[t + h];
__syncthreads();
}
if (t == 0) out[2] = __float_as_uint(sv[0]);
}
}
extern "C" __global__ void __launch_bounds__(1024) tf_glm_top1(const unsigned short* logits, int64_t n, unsigned lo,
unsigned* out) {
glm_top1<false>(logits, n, lo, out);
}
// The pick with its slice's softmax sum in out[2]: an MTP draft's chance (--mtp-confidence) across the ranks.
extern "C" __global__ void __launch_bounds__(1024) tf_glm_top1_sums(const unsigned short* logits, int64_t n,
unsigned lo, unsigned* out) {
glm_top1<true>(logits, n, lo, out);
}

// The leader's step for the other ranks, written to the link's buffer from launch arguments (cuda_follow's Link.send).
Expand Down
3 changes: 2 additions & 1 deletion zig/src/core/contract/glm_sampling_pending.zig
Original file line number Diff line number Diff line change
Expand Up @@ -2,12 +2,13 @@
const std = @import("std");
const R = @import("registry.zig").CudaRecord;

/// Shared sampling and GLM greedy launches used for prompt scoring and grammar-constrained draws.
/// Shared sampling and GLM greedy launches: prompt scoring, grammar-constrained draws and MTP drafts' chances.
pub const sampling = [_]R{
.{ .launch = .{ .name = "sample tf_draw", .symbol = "tf_draw", .image = "sample", .threads = 1024 }, .usage = .{ .{ .regs = 52, .static = 9752, .bound = 1024 }, .{ .regs = 64, .static = 9752, .bound = 1024 }, .{ .regs = 64, .static = 9752, .bound = 1024 }, .{ .regs = 64, .static = 9752, .bound = 1024 }, .{ .regs = 64, .static = 9752, .bound = 1024 } }, .later_pending = true },
.{ .launch = .{ .name = "sample tf_logprob_rows", .symbol = "tf_logprob_rows", .image = "sample", .threads = 1024 }, .usage = .{ .{ .regs = 27, .static = 520, .bound = 1024 }, .{ .regs = 28, .static = 520, .bound = 1024 }, .{ .regs = 28, .static = 520, .bound = 1024 }, .{ .regs = 40, .static = 520, .bound = 1024 }, .{ .regs = 40, .static = 520, .bound = 1024 } }, .later_pending = true },
.{ .launch = .{ .name = "sample tf_grammar_mask", .symbol = "tf_grammar_mask", .image = "sample", .threads = 256 }, .usage = .{ .{ .regs = 28, .static = 0, .bound = 256 }, .{ .regs = 26, .static = 0, .bound = 256 }, .{ .regs = 26, .static = 0, .bound = 256 }, .{ .regs = 16, .static = 0, .bound = 256 }, .{ .regs = 16, .static = 0, .bound = 256 } }, .later_pending = true },
.{ .launch = .{ .name = "glm_glue tf_glm_top1", .symbol = "tf_glm_top1", .image = "glm_glue", .threads = 1024 }, .usage = .{ .{ .regs = 29, .static = 8192, .bound = 1024 }, .{ .regs = 30, .static = 8192, .bound = 1024 }, .{ .regs = 30, .static = 8192, .bound = 1024 }, .{ .regs = 36, .static = 8192, .bound = 1024 }, .{ .regs = 36, .static = 8192, .bound = 1024 } }, .later_pending = true },
.{ .launch = .{ .name = "glm_glue tf_glm_top1_sums", .symbol = "tf_glm_top1_sums", .image = "glm_glue", .threads = 1024 }, .usage = .{ .{ .regs = 32, .static = 8192, .bound = 1024 }, .{ .regs = 31, .static = 8192, .bound = 1024 }, .{ .regs = 31, .static = 8192, .bound = 1024 }, .{ .regs = 39, .static = 8192, .bound = 1024 }, .{ .regs = 39, .static = 8192, .bound = 1024 } }, .later_pending = true },
};

test "GLM sampling has measured 13.0 resources on every target" {
Expand Down
26 changes: 23 additions & 3 deletions zig/src/core/lanes/depth.zig
Original file line number Diff line number Diff line change
Expand Up @@ -144,7 +144,7 @@ pub const Rule = struct {
pub fn depth(r: *Rule, who: Who) !i64 {
const most = @min(@as(i64, r.most_drafts), @max(1, who.draft_room - 1));
if (most <= 0) return 0;
if (r.confidence_floor != null) return most;
if (r.confidence_floor != null and !who.sampled) return most;
const p = try r.rates(who);
if (r.family_costs.empty()) {
const want: i64 = if (p[0] < 0.8) 1 else if (p[0] < 0.9) 2 else 3;
Expand Down Expand Up @@ -192,9 +192,9 @@ pub const Rule = struct {
return true;
}

/// Python `_head_depth`: the next round's head drafts for a stream (0 when forced, 1 with a copy ahead).
/// Python `_head_depth`: next head drafts (0 forced, 1 with a copy); a floor leaves a sampled stream its rates'.
pub fn headDepth(r: *Rule, who: *const Who, budget: ?i64, probe: Probe) !i64 {
const d: i64 = if (who.finished) 0 else if (budget) |b| b else if (r.node_probabilities)
const d: i64 = if (who.finished) 0 else if (budget) |b| b else if (r.node_probabilities and !(who.sampled and r.confidence_floor != null))
@min(@as(i64, r.most_drafts), @max(1, who.draft_room - 1))
else
try r.depth(who.*);
Expand Down Expand Up @@ -353,6 +353,26 @@ test "depth picks the most tokens a ms and probes deeper" {
try std.testing.expectEqual(@as(i64, 3), try rule.depth(who));
}

test "under a confidence floor a greedy stream drafts the most, and a sampled one keeps its rates' depth" {
const gpa = std.testing.allocator;
const empty: Table = .{};
const No = struct {
fn copy(_: *anyopaque, _: *const Who) bool {
return false;
}
};
var unused: u8 = 0;
const probe: Probe = .{ .ptr = &unused, .copy = No.copy };
var rule: Rule = .{ .gpa = gpa, .prior = &.{ 0.5, 0.5, 0.5 }, .most_drafts = 3, .family_costs = &empty, .shared_costs = &empty, .mtp_step_ms = 0.5, .plain_guard = false, .node_probabilities = true, .confidence_floor = 0.5, .batch_rows = 8 };
defer rule.deinit();
var states: [2]?State = .{ null, null };
defer for (&states) |*s| if (s.*) |*x| x.deinit(gpa);
const greedy: Who = .{ .state = &states[0], .draft_room = 100, .finished = false, .forced = false };
const sampled: Who = .{ .state = &states[1], .draft_room = 100, .finished = false, .forced = false, .sampled = true };
try std.testing.expectEqual(@as(i64, 3), try rule.headDepth(&greedy, null, probe));
try std.testing.expectEqual(@as(i64, 1), try rule.headDepth(&sampled, null, probe)); // a first rate under 0.8: one draft
}

test "a shared round's drafts come out the same whichever depths its overhead was measured at" {
const gpa = std.testing.allocator;
var shared: Table = .{};
Expand Down
1 change: 1 addition & 0 deletions zig/src/families/glm/cuda.zig
Original file line number Diff line number Diff line change
Expand Up @@ -77,6 +77,7 @@ test {
_ = lanes;
_ = native;
_ = @import("cuda_qpack.zig");
_ = @import("cuda_mtp_chance.zig");
_ = @import("cuda_tile.zig");
_ = @import("heat"); // upstream's heat bands, run where the GLM ranks use them
}
Expand Down
12 changes: 10 additions & 2 deletions zig/src/families/glm/cuda_engine.zig
Original file line number Diff line number Diff line change
Expand Up @@ -528,7 +528,7 @@ pub const Engine = struct {
}

/// decode.draft: the MTP head absorbs the kept rows (committed first) with `follow`, then chains `depth` drafts.
pub fn draft(e: *Engine, from_prompt: bool, follow: []const u32, depth: usize, out: []u32) !void {
pub fn draft(e: *Engine, from_prompt: bool, follow: []const u32, depth: usize, out: []u32, chances: ?[]f64) !void {
if (!e.mtp) return error.NoDraftHead;
if (depth > max_drafts) return error.TooDeep;
var one: [1]fw.Rank = undefined;
Expand All @@ -545,7 +545,14 @@ pub const Engine = struct {
try e.cur.st.setMtpLen(e.stream, e.cur.st.mtp_len + part.len);
}
for (0..depth) |j| {
try e.draw(e.bm.logits, 1, e.cur.st.pos + 1 + j, 0, out[j..][0..1]);
if (chances != null and !e.structured and e.cur.sampling == null) {
const p = try e.greedyChance(e.bm.logits);
out[j] = p.token;
chances.?[j] = p.chance;
} else {
try e.draw(e.bm.logits, 1, e.cur.st.pos + 1 + j, 0, out[j..][0..1]);
if (chances) |c| c[j] = 1; // a sampled or structured draft keeps chance 1: its window runs whole
}
if (j + 1 < depth) {
try f.mtp(@ptrCast(out[j..][0..1]), &.{e.bm.fnormed});
try e.cur.st.setMtpLen(e.stream, e.cur.st.mtp_len + 1);
Expand All @@ -569,6 +576,7 @@ pub const Engine = struct {
pub const redrawFirst = @import("cuda_structured.zig").redrawFirst;
/// decode.sample_rows' greedy pick: per-rank top-1 (tf_glm_top1), all-gathered, largest value then lowest id.
const greedy = @import("cuda_engine_pick.zig").greedy;
const greedyChance = @import("cuda_engine_pick.zig").greedyChance;

/// A failed RoCE gather's error, after a synchronize whose result read gathered rows (they hold nothing then).
pub fn checkGathers(e: *const Engine) !void {
Expand Down
20 changes: 12 additions & 8 deletions zig/src/families/glm/cuda_engine_pick.zig
Original file line number Diff line number Diff line change
@@ -1,16 +1,26 @@
//! The existing rank-gathered greedy pick, kept separate from engine lifetime and prompt diagnostics.
const cuda = @import("cuda");
const ranks = @import("cuda_ranks.zig");
const chance = @import("cuda_mtp_chance.zig");
const Engine = @import("cuda_engine.zig").Engine;
const pair_bytes = 16;
pub fn greedy(e: *Engine, logits: u64) !u32 {
return (try pick(e, logits, false)).token;
}

/// greedy with the pick's chance from every rank's softmax sum (tf_glm_top1_sums), for --mtp-confidence's drafts.
pub fn greedyChance(e: *Engine, logits: u64) !chance.Pick {
return pick(e, logits, true);
}

fn pick(e: *Engine, logits: u64, sums: bool) !chance.Pick {
const world = e.share.world;
var a: cuda.Args = .{};
a.add(logits);
a.add(@as(i64, @intCast(e.share.vocab.len())));
a.add(@as(u32, @intCast(e.share.vocab.lo)));
a.add(e.pairs.ptr + e.share.rank * pair_bytes);
try cuda.launch.launch(e.m.glue.top1, .{ .grid = .{ .x = 1 }, .block = .{ .x = 1024 } }, e.stream, &a);
try cuda.launch.launch(if (sums) e.m.glue.top1_sums else e.m.glue.top1, .{ .grid = .{ .x = 1 }, .block = .{ .x = 1024 } }, e.stream, &a);
const mine = e.pairs.ptr + e.share.rank * pair_bytes;
const stamp = @import("cuda_prof.zig").span(e.profiling_prompt, e.stream, .token_gather);
if (e.group) |g| try g.allGather(e.stream, mine, e.pairs.ptr, pair_bytes) else try e.lib.check(e.lib.api.ncclAllGather(mine, e.pairs.ptr, pair_bytes, .u8, e.comm, e.stream.handle), "ncclAllGather");
Expand All @@ -19,11 +29,5 @@ pub fn greedy(e: *Engine, logits: u64) !u32 {
try e.checkGathers();
var all: [ranks.max_world][4]u32 = undefined; // Engine.init refuses a larger world
try e.d.check(e.d.api.cuMemcpyDtoH_v2(&all, e.pairs.ptr, world * pair_bytes), "cuMemcpyDtoH");
var pick = all[0];
for (all[1..world]) |p| {
const v: f32 = @bitCast(p[0]);
const b: f32 = @bitCast(pick[0]);
if (v > b or (v == b and p[1] < pick[1])) pick = p;
}
return pick[1];
return chance.pick(all[0..world], sums);
}
12 changes: 7 additions & 5 deletions zig/src/families/glm/cuda_follow.zig
Original file line number Diff line number Diff line change
Expand Up @@ -19,7 +19,7 @@ pub const Header = extern struct {
kind: u32,
n: u32 = 0, // ids that follow
depth: u32 = 0, // draft: drafts to chain; chunk: where it starts; shared: its parts
flags: u32 = 0, // begin: sampled; draft: from the prompt; prefill, chunk: prompt_logprobs (1); chunk: indexer rows split (2); verify, shared: whole rows
flags: u32 = 0, // begin: sampled; draft: from the prompt (1), chances (2); prefill, chunk: prompt_logprobs (1); chunk: indexer rows split (2); verify, shared: whole rows
a: u64 = 0, // keep: rows; prefill, chunk: the kept state it resumes (0: none); redraw: the prompt's length
seed: u64 = 0, // begin: the sampling seed; prefill, chunk: the kept state's position
temperature: f64 = 0,
Expand Down Expand Up @@ -275,10 +275,11 @@ pub const Leader = struct {
return x.e.redrawFirst(len, bits);
}

pub fn draft(x: Leader, from_prompt: bool, follow_ids: []const u32, depth: usize, out: []u32) !void {
/// With `chances` every rank picks with its softmax sum, so rank 0 reads each draft's chance (--mtp-confidence).
pub fn draft(x: Leader, from_prompt: bool, follow_ids: []const u32, depth: usize, out: []u32, chances: ?[]f64) !void {
try x.flush();
try x.send(.{ .kind = @backingInt(Kind.draft), .depth = @intCast(depth), .flags = @intFromBool(from_prompt) }, follow_ids);
try x.e.draft(from_prompt, follow_ids, depth, out);
try x.send(.{ .kind = @backingInt(Kind.draft), .depth = @intCast(depth), .flags = @intFromBool(from_prompt) | @as(u32, @intFromBool(chances != null)) << 1 }, follow_ids);
try x.e.draft(from_prompt, follow_ids, depth, out, chances);
}

/// DFlash2's round on every rank (Engine.draftBlock): each stream's slot, kept rows and anchor.
Expand Down Expand Up @@ -318,6 +319,7 @@ fn structuredStep(h: Header) bool {
/// A rank other than 0 runs rank 0's steps until it ends; a cancelled prefill is error.Cancelled and the loop goes on.
pub fn follow(e: *Engine, link: *Link) !void {
var drafts: [engine.max_drafts]u32 = undefined;
var chances: [engine.max_drafts]f64 = undefined;
var sampled: [16]u32 = undefined;
cuda.tp_watch.sleep(e.io); // rank 0 starts with no stream: its first step wakes this rank
while (true) {
Expand Down Expand Up @@ -383,7 +385,7 @@ pub fn follow(e: *Engine, link: *Link) !void {
.draft => {
const ids = try e.gpa.dupe(u32, step.ids);
defer e.gpa.free(ids);
try e.draft(h.flags & 1 != 0, ids, h.depth, &drafts);
try e.draft(h.flags & 1 != 0, ids, h.depth, &drafts, if (h.flags & 2 != 0) &chances else null);
},
.block => {
const k = h.depth;
Expand Down
1 change: 1 addition & 0 deletions zig/src/families/glm/cuda_glue.zig
Original file line number Diff line number Diff line change
Expand Up @@ -24,6 +24,7 @@ pub const Kernels = struct {
combine: cuda.Function,
slice_sum: cuda.Function,
top1: cuda.Function,
top1_sums: cuda.Function,
put_words: cuda.Function,
embed_b16: cuda.Function,
conv_shift: cuda.Function,
Expand Down
15 changes: 9 additions & 6 deletions zig/src/families/glm/cuda_lanes.zig
Original file line number Diff line number Diff line change
Expand Up @@ -34,7 +34,7 @@ const Lane = struct {
slot: u32,
pending_rows: ?usize = null,
held: [max_held]u32 = undefined,
chances: [max_held]f64 = undefined, // DFlash2's: each held draft's chance from the selector
chances: [max_held]f64 = undefined, // each held draft's chance: DFlash2's selector's, or the MTP head's (--mtp-confidence)
held_n: usize = 0,
first: ?u64 = null,
fill: ?usize = null, // a prompt pass going a chunk at a time: where its next chunk starts
Expand All @@ -44,6 +44,7 @@ pub const Lanes = struct {
x: follow.Leader,
whole: bool = false, // prompt passes run whole (TF_GLM_PROMPT_STEPS=0): no other stream's round between chunks
alone: bool = false, // each window in its own forward (TF_GLM_SHARED=0)
mtp_confidence: ?f64 = null, // --mtp-confidence: the MTP head's chains stop where their chance falls under it
shared: u64 = 0, // forwards that held several streams' windows (checks read it)
lanes: std.AutoHashMapUnmanaged(*const lanes.Stream, Lane) = .empty,
drawn: [ring]u32 = undefined,
Expand Down Expand Up @@ -114,7 +115,8 @@ pub const Lanes = struct {
.drafts = if (block) max_held else engine.max_drafts,
.draft_streams = block, // one block pass drafts every stream of the round
.mtp_step_ms = if (block) 1.6 / @as(f64, max_held) else 0, // a block's 7 drafts in one pass (about 1.6 ms)
.draft_probabilities = block, // the selector's chances size each window against the costs below
.draft_probabilities = block or self.mtp_confidence != null, // chances size each window (DFlash2's by the costs)
.draft_confidence = if (block) null else self.mtp_confidence,
.window_costs = if (block) &gb10_window_costs else &.{},
.shared_costs = if (block) &gb10_shared_costs else &.{},
.hidden_rows = sharing,
Expand Down Expand Up @@ -473,12 +475,13 @@ pub const Lanes = struct {
if (r.position != self.x.e.pos() + 1) return error.PositionMismatch;
if (r.lanes != null) return error.TreesNotBuilt;
const depth = @min(r.depth, engine.max_drafts);
const chances: ?[]f64 = if (self.mtp_confidence != null) l.chances[0..depth] else null;
if (r.rows) |rows| {
for (rows, 0..) |row, i| if (row != i) return error.TreesNotBuilt;
try self.x.draft(false, r.follow[0..rows.len], depth, &l.held);
try self.x.draft(false, r.follow[0..rows.len], depth, &l.held, chances);
} else {
const first = self.value(r.first orelse return error.NoFirstToken);
try self.x.draft(true, &.{first}, depth, &l.held);
try self.x.draft(true, &.{first}, depth, &l.held, chances);
}
l.held_n = depth;
}
Expand Down Expand Up @@ -521,10 +524,10 @@ pub const Lanes = struct {
return std.fmt.parseFloat(f64, std.mem.span(v)) catch 0.7;
}

/// DFlash2's chance for each held draft (the MTP head gives none: the lane core's per-depth rates stand).
/// Each held draft's chance, DFlash2's or the MTP head's under --mtp-confidence (else the per-depth rates stand).
fn chancesFn(ptr: *anyopaque, s: *lanes.Stream, out: []f64) anyerror!bool {
const self = of(ptr);
if (self.x.e.drafter == null) return false;
if (self.x.e.drafter == null and self.mtp_confidence == null) return false;
const l = self.lanes.getPtr(s) orelse return false;
if (l.held_n == 0) return false;
const n = @min(out.len, l.held_n);
Expand Down
Loading
Loading