Skip to content
Draft
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 @@ -77,6 +77,8 @@ Each release's page on GitHub has its notes and measurements. See [the 1.0.0 rel
- Metal kernels: Step-5's `s5_embed`, MiniMax-M3's `mm_embed` and Spark2.5's `sp_embed` take their affine-quantized embedding row from one macro; each shader's compiler-visible tokens are identical to before (#5203, refs #2251).


- Ripple-65B-Preview on CUDA serves structured output (`response_format`) and forced tool calls (`tool_choice` `"required"` or a named function): a grammar's rows are drawn on the GPU from a copy with the disallowed tokens at -inf, by the same draw and argmax kernels, and logprob rows read the unmasked logits; a request with no grammar runs the launches it ran before (#5363, fixes #5252). Thanks to @jrb-ai.

## 1.3.6

- Input checks: GLM on CUDA refuses token IDs outside its embedding on every path (ordinary, MTP, paired prompts, DFlash) and refuses startup when the tokenizer has more tokens than the model's vocabulary; ERNIE 5.5 refuses configs whose attention dimensions do not add up and bounds its expected-tensor reports; living memory replays only regular journal files and checks a saved prefix length before allocating; request records redact inline document payloads and file containers. Valid inputs produce the same output.
Expand Down
18 changes: 12 additions & 6 deletions docs/recipes/ripple-65b-cuda.md
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,7 @@ sm_80, 86, 89, 120 and 121 and their launches fit each, but only GB10 was run.
hf download ricursiveAI/Ripple-65B-Preview-NVFP4 --revision 99eea4477a001a41b86914e41feb4b2ed86105e5 \
--local-dir models/ripple-65b-nvfp4
zig build native -Dnvcc=/usr/local/cuda/bin/nvcc -Dsm=121
zig build grammar -Dxgrammar=PATH_TO_XGRAMMAR_v0.2.8 # structured output and forced tool calls
zig-out/native/bin/tensorfold-native serve models/ripple-65b-nvfp4 --name ripple --port 8888 --context 32768
```

Expand All @@ -28,7 +29,7 @@ layer is global and keeps every key, in 512-row pages.

Thinking follows the chat template, as on Metal: Ripple writes `<think>` itself when it thinks and answers bare
otherwise, and the server files a reply without the block as answer. Its think markers are spelled from several
tokens, so a thinking budget and logprobs are refused by name.
tokens, so a thinking budget is refused by name. Logprobs are served.

## What the family is

Expand Down Expand Up @@ -81,6 +82,14 @@ pick by at most 0.25 nats.
- Served replies are bit-identical alone, beside seven other streams and one at a time (greedy and sampled). A
conversation sent again, reusing 79 to 81 cached tokens, equals its first reply, and 60 repeats of a reply equal the
first. Seeded replies equal their repeats, and streamed text equals the reply sent whole.
- Structured output and forced tool calls draw under the grammar's mask on the GPU: a row's copy with its disallowed
tokens at -inf, through the draw and argmax kernels of a row with no grammar. The first token and a 4-row window
under masks equal the plain draw over the same rows with the other tokens at -inf, greedy and sampled; the model's
rows keep their bits and the logprob rows read them; streams with no grammar in a round beside a masked stream
equal each alone. Served: 11 request forms (`response_format` json_object and json_schema; `guided_json`,
`guided_regex`, `guided_choice` and `guided_grammar`; `structured_outputs` json, json_object, regex, choice and
grammar), greedy and sampled, give valid replies, and tool calls with `tool_choice` `"auto"`, `"required"`, a named
function and a streamed required call agree. The plain dumps and reply hashes above are unchanged.

## Measured (GB10, NVFP4 release, `--context 32768`, no other model busy)

Expand All @@ -106,11 +115,8 @@ budget.

## Not done

Structured output (`response_format`) and forced tool calls (`tool_choice` `"required"` or a named function) are not
supported on CUDA yet: the server refuses them, because the CUDA family has no masked sampling. Tool calls with
`tool_choice` `"auto"` work. No quality suite was run. Past 131,072 tokens, only the one near-cap prompt above was
run. Only GB10 was run. The publisher's DFlash2 drafter (`ricursiveAI/Ripple-65B-Preview-DFlash2`) is not served
on CUDA yet.
No quality suite was run. Past 131,072 tokens, only the one near-cap prompt above was run. Only GB10 was run. The
publisher's DFlash2 drafter (`ricursiveAI/Ripple-65B-Preview-DFlash2`) is not served on CUDA yet.

## Licence

Expand Down
15 changes: 14 additions & 1 deletion zig/kernels/cuda/contract_ricursive_controls.cuh
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
// Planted controls for Ripple's attention prep (ricursive_prep.cu): each keeps one fault its gate must catch.
// Planted controls for Ripple's attention prep (ricursive_prep.cu) and grammar mask (sample.cu), one fault each.

// Included by contract_controls_set.cu after contract_controls.cu, whose headers it reuses.

Expand All @@ -22,3 +22,16 @@ extern "C" __global__ void __launch_bounds__(tf_rcp::NT) tf_ctl_rc_prep_rows(
tf_rcp::prep_rows(XQ, XK, XV, inv, qw, kw, Q, KC, VC, rows, heads, kv_heads, pos, nullptr, ring, rope, eps, tab, page,
tok, stride, keep);
}

// Gate 3: sample.cu's tf_grammar_mask reading a word's bits from the top (token t at bit 31 - t % 32); shapes go red.
extern "C" __global__ void __launch_bounds__(256) tf_ctl_rc_grammar_mask(__nv_bfloat16* L, unsigned V, const unsigned* BITS, unsigned W) {
const unsigned row = blockIdx.x;
__nv_bfloat16* x = L + static_cast<size_t>(row) * V;
for (unsigned w = threadIdx.x; w < W; w += blockDim.x) {
const unsigned allowed = BITS[static_cast<size_t>(row) * W + w];
for (unsigned b = 0; b < 32u; b++) {
const unsigned t = w * 32u + b;
if (t < V && ((allowed >> (31u - b)) & 1u) == 0u) x[t] = __ushort_as_bfloat16(static_cast<unsigned short>(0xFF80u));
}
}
}
68 changes: 58 additions & 10 deletions zig/src/families/ricursive/cuda_backend.zig
Original file line number Diff line number Diff line change
Expand Up @@ -59,6 +59,8 @@ pub const Ripple = struct {
slot_bufs: cuda.DeviceBuffer, // a slot's last-row logits, then its rule, a slot each
sample: cuda.Module,
draws: cuda.sample.Draws,
mask_fn: cuda.Function, // sample.cu's tf_grammar_mask: structured output's disallowed tokens to -inf
masked: ?cuda.DeviceBuffer = null, // rows under their grammars, then the grammars' bits; the first such row opens it
lanes: std.AutoHashMapUnmanaged(*const Stream, Lane) = .empty,
free: []bool, // slot i is free
next: u64 = 0,
Expand Down Expand Up @@ -91,14 +93,16 @@ pub const Ripple = struct {
var sample = try cuda.Module.load(d, cuda.kernels.sample);
errdefer sample.unload();
const draws = try cuda.sample.Draws.resolve(sample);
return .{ .gpa = gpa, .d = d, .m = m, .tok = tok, .meta = meta, .words = words, .picks = picks, .slot_bufs = slot_bufs, .sample = sample, .draws = draws, .free = free };
const mask_fn = try sample.function("tf_grammar_mask");
return .{ .gpa = gpa, .d = d, .m = m, .tok = tok, .meta = meta, .words = words, .picks = picks, .slot_bufs = slot_bufs, .sample = sample, .draws = draws, .mask_fn = mask_fn, .free = free };
}

pub fn deinit(x: *Ripple) void {
var it = x.lanes.valueIterator();
while (it.next()) |l| l.rows.deinit(x.gpa);
x.lanes.deinit(x.gpa);
x.gpa.free(x.free);
if (x.masked) |*b| b.free();
x.sample.unload();
x.slot_bufs.free();
x.picks.free();
Expand All @@ -112,7 +116,7 @@ pub const Ripple = struct {
return .{ .ptr = x, .vtable = &vtable, .chunk_invariant = true }; // chunk cuts give the same bits
}

const vtable: be.Backend.VTable = .{ .prefill = prefill, .prefill_step = prefillStep, .cancel_prefill = cancelPrefill, .first = first, .queue = queue, .read = read, .verify = verify, .keep = keep, .draft = draft, .release = release, .first_row = firstRow, .prompt_rows = true, .reports_fill = true };
const vtable: be.Backend.VTable = .{ .prefill = prefill, .prefill_step = prefillStep, .cancel_prefill = cancelPrefill, .first = first, .first_masked = firstMasked, .queue = queue, .read = read, .verify = verify, .keep = keep, .draft = draft, .release = release, .first_row = firstRow, .prompt_rows = true, .reports_fill = true };

/// The round loop's facts: no draft head; host copies verified in windows up to 16 rows, streams sharing a round.
pub fn facts(x: *const Ripple) lanes.Model {
Expand All @@ -132,8 +136,8 @@ pub const Ripple = struct {
return x.tok.ptr + i * 4;
}

/// `rows` bf16 logits rows drawn into `out`, row r at `position0 + r` (argmax when greedy).
fn drawRows(x: *Ripple, l: *const Lane, logits: u64, rows: usize, position0: u64, out: u64, meta_at: usize) !void {
/// `rows` bf16 logits rows drawn into `out`, row r at `position0 + r` (argmax when greedy); public for GPU tests.
pub fn drawRows(x: *Ripple, l: *const Lane, logits: u64, rows: usize, position0: u64, out: u64, meta_at: usize) !void {
const v = x.m.c.vocab;
if (!l.sampled) return x.m.k.argmaxRows(x.m.s, logits, rows, v, v, out);
const meta = [4]i32{ @intCast(position0 - 1), 0, 0, 0 };
Expand All @@ -142,6 +146,31 @@ pub const Ripple = struct {
try x.draws.draw(x.m.s, logits, v, l.rule, mp, 0, out, rows, null, null);
}

/// A row's allowed-token words (lanes/grammar.zig: token t at bit t % 32 of word t / 32).
pub fn maskWords(vocab: usize) usize {
return (vocab + 31) / 32;
}

/// `rows` logits rows copied to row `row` of the grammar scratch, the tokens `masks` disallows at -inf there.
fn maskedRows(x: *Ripple, logits: u64, rows: usize, masks: []const u32, row: usize) !u64 {
const v = x.m.c.vocab;
const nw = maskWords(v);
if (masks.len != rows * nw or row + rows > round_rows) return error.InvalidGrammarMasks;
if (x.masked == null) x.masked = try cuda.DeviceBuffer.alloc(x.d, round_rows * (v * 2 + nw * 4));
const dst = x.masked.?.ptr + row * v * 2;
const bits = x.masked.?.ptr + round_rows * v * 2 + row * nw * 4;
// the rows at `logits` keep their bits: the logprob rows read them
try x.d.check(x.d.api.cuMemcpyDtoDAsync_v2(dst, logits, rows * v * 2, x.m.s.handle), "cuMemcpyDtoDAsync");
try x.upload(bits, std.mem.sliceAsBytes(masks));
var a: cuda.Args = .{};
a.add(dst);
a.add(@as(u32, @intCast(v)));
a.add(bits);
a.add(@as(u32, @intCast(nw)));
try cuda.launch.launch(x.mask_fn, .{ .grid = .{ .x = @intCast(rows) }, .block = .{ .x = 256 } }, x.m.s, &a);
return dst;
}

/// The stream's caches at `at` for the prompt cache, copied behind the chunk that ends there.
pub fn saveState(x: *Ripple, owner: ?*anyopaque, at: u32) !*snap.Saved {
const s: *const Stream = @ptrCast(@alignCast(owner orelse return error.NoOwner));
Expand Down Expand Up @@ -178,7 +207,6 @@ pub const Ripple = struct {
const p = s.prompt();
if (p.len == 0) return error.EmptyPrompt;
if (!fits(x.m.context, p.len, @as(usize, s.max_new))) return error.PastContext;
if (s.grammar != null) return error.StructuresUnsupported;
const got = try x.lanes.getOrPut(x.gpa, s);
if (!got.found_existing) {
const slot = x.freeSlot() orelse {
Expand Down Expand Up @@ -300,11 +328,21 @@ pub const Ripple = struct {

/// The prompt's last row drawn at `position`; with logprobs, its row kept for first_row.
fn first(ptr: *anyopaque, s: *Stream, position: u64) anyerror!u64 {
const x = self(ptr);
return self(ptr).firstAt(s, position, &.{});
}

/// The first token under a grammar: the draw reads the row with its disallowed tokens at -inf.
fn firstMasked(ptr: *anyopaque, s: *Stream, position: u64, mask: []const u32) anyerror!u64 {
if (mask.len == 0) return error.InvalidGrammarMasks;
return self(ptr).firstAt(s, position, mask);
}

fn firstAt(x: *Ripple, s: *Stream, position: u64, mask: []const u32) !u64 {
const l = try x.laneOf(s);
if (position != l.len or l.fill != null) return error.PositionMismatch;
const from = if (mask.len == 0) l.last else try x.maskedRows(l.last, 1, mask, 0);
const h = x.handle();
try x.drawRows(l, l.last, 1, position, x.tokAt(h % ring), 0);
try x.drawRows(l, from, 1, position, x.tokAt(h % ring), 0);
if (s.logprobs) |k| {
try x.draws.logprobRows(x.m.s, l.last, x.m.c.vocab, x.tokAt(h % ring), k, false, x.words.ptr, 1);
var w: [row_words]u32 = undefined;
Expand Down Expand Up @@ -360,7 +398,7 @@ pub const Ripple = struct {
for (windows, chains) |w, *c| {
if (w.held != 0) return error.NoHeldDrafts; // no draft head: every draft comes from the host
if (w.parents != null) return error.ChainsOnly;
if (w.masks.len != 0) return error.StructuresUnsupported;
if (w.masks.len != 0 and w.masks.len != w.rows() * maskWords(v)) return error.InvalidGrammarMasks;
const l = try x.laneOf(w.stream);
if (w.rows() > max_window) return error.WindowTooWide;
if (total + w.rows() > @min(round_rows, x.m.round_rows)) return error.RoundTooWide;
Expand All @@ -382,7 +420,9 @@ pub const Ripple = struct {
const l = x.lanes.getPtr(w.stream).?;
const n = l.rows.items.len;
const logits = x.m.b.rows + at * v * 2;
try x.drawRows(l, logits, n, w.positions[0], x.tokAt(ring + at), i);
// a grammar's rows are drawn from a copy; the logprob rows below read the model's
const from = if (w.masks.len == 0) logits else try x.maskedRows(logits, n, w.masks, at);
try x.drawRows(l, from, n, w.positions[0], x.tokAt(ring + at), i);
if (o.rows.len > 0) {
try x.draws.logprobRows(x.m.s, logits, v, x.tokAt(ring + at), w.stream.logprobs.?, false, x.words.ptr + at * row_words * 4, n);
scored = true;
Expand Down Expand Up @@ -451,7 +491,7 @@ test "ricursive cuda backend: windows of 16 rows, a stream a slot, rows a round"
var m: fwd.Model = undefined;
m.round_rows = round_rows;
m.arena.slots = 6;
const x: Ripple = .{ .gpa = std.testing.allocator, .d = undefined, .m = &m, .tok = undefined, .meta = undefined, .words = undefined, .picks = undefined, .slot_bufs = undefined, .sample = undefined, .draws = undefined, .free = &.{} };
const x: Ripple = .{ .gpa = std.testing.allocator, .d = undefined, .m = &m, .tok = undefined, .meta = undefined, .words = undefined, .picks = undefined, .slot_bufs = undefined, .sample = undefined, .draws = undefined, .mask_fn = undefined, .free = &.{} };
const f = x.facts();
try std.testing.expectEqual(@as(u32, 16), f.exact_width);
try std.testing.expectEqual(@as(u32, 6), f.max_streams);
Expand All @@ -461,6 +501,14 @@ test "ricursive cuda backend: windows of 16 rows, a stream a slot, rows a round"
std.testing.refAllDecls(Ripple);
}

test "ricursive cuda backend: a grammar row's words cover the vocabulary, a bit a token" {
try std.testing.expectEqual(@as(usize, 3136), Ripple.maskWords(100352)); // the release's logits, 32 tokens a word
try std.testing.expectEqual(@as(usize, 1), Ripple.maskWords(1));
try std.testing.expectEqual(@as(usize, 2), Ripple.maskWords(33));
// the grammar scratch holds a round's rows, then their bits: the bits start at a whole 16 bytes
try std.testing.expectEqual(@as(usize, 0), (round_rows * 100352 * 2) % 16);
}

test {
_ = snap;
}
5 changes: 2 additions & 3 deletions zig/src/families/ricursive/cuda_native.zig
Original file line number Diff line number Diff line change
Expand Up @@ -214,7 +214,6 @@ pub fn explain(_: ?*anyopaque, err: anyerror) ?[]const u8 {
error.ParallelPastMemory => "--parallel: the CUDA memory budget fits fewer Ripple streams than asked (each stream's caches are allocated at load): lower --parallel or --context, serve --parallel auto, or adjust TENSORFOLD_MEMORY_RESERVE_GIB / TENSORFOLD_CUDA_MEMORY_LIMIT_GB",
error.SegmentsUnsupported => "--segments: Ripple on CUDA runs its prompt chunks one after another: serve without --segments",
error.NoDraftHead => "Ripple on CUDA has no draft head: drafts come from the prompt's own text only",
error.StructuresUnsupported => "structured output is not built for Ripple on CUDA yet",
error.CapturedKernels => "Ripple runs on the engine's own kernels: unset TENSORFOLD_CUDA_KERNELS",
error.BuiltWithoutKernels => "this build carries no CUDA kernel images: build with -Dnvcc",
error.RicursiveCudaNeedsNvfp4 => "Ripple on CUDA serves the NVFP4 release (ModelOpt W4A16 MLPs, bf16 attention): the BF16 checkpoint's 130 GB do not fit GB10",
Expand All @@ -231,10 +230,10 @@ test "ricursive cuda native: a reply thinks or answers bare, with no thinking bu
}

test "ricursive cuda native: every refusal of its own is worded, the rest left to the server" {
for ([_]anyerror{ error.PastContext, error.NoFreeSlot, error.NoStreamFits, error.ParallelPastRound, error.ParallelPastMemory, error.SegmentsUnsupported, error.NoDraftHead, error.StructuresUnsupported, error.CapturedKernels, error.BuiltWithoutKernels, error.RicursiveCudaNeedsNvfp4, error.UnsupportedRicursiveCudaShape, error.Unimplemented }) |e| {
for ([_]anyerror{ error.PastContext, error.NoFreeSlot, error.NoStreamFits, error.ParallelPastRound, error.ParallelPastMemory, error.SegmentsUnsupported, error.NoDraftHead, error.CapturedKernels, error.BuiltWithoutKernels, error.RicursiveCudaNeedsNvfp4, error.UnsupportedRicursiveCudaShape, error.Unimplemented }) |e| {
try std.testing.expect(explain(null, e) != null);
}
for ([_]anyerror{ error.OutOfMemory, error.SamplingUnsupported, error.LogprobsUnsupported, error.WindowTooWide }) |e| {
for ([_]anyerror{ error.OutOfMemory, error.SamplingUnsupported, error.LogprobsUnsupported, error.StructuresUnsupported, error.InvalidGrammarMasks, error.WindowTooWide }) |e| {
try std.testing.expect(explain(null, e) == null);
}
}
Expand Down
7 changes: 6 additions & 1 deletion zig/tests/cuda/contract_ricursive.zig
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
//! Ripple's CUDA kernels under the contract, with controls (ricursive-contract): glue, attention prep, attention.
//! Ripple's CUDA kernels under the contract, with controls (ricursive-contract): glue, prep, attention, grammar mask.
const std = @import("std");
const cuda = @import("cuda");
const core = @import("core");
Expand All @@ -7,6 +7,7 @@ const check = @import("check.zig");
const glue = @import("contract_ricursive_glue.zig");
const prep = @import("contract_ricursive_prep.zig");
const attn = @import("contract_ricursive_attn.zig");
const mask = @import("contract_ricursive_mask.zig");

const g = core.contract.gates;

Expand All @@ -17,6 +18,7 @@ pub const Set = struct {
glue: glue.Set = .{},
prep: *prep.Set = undefined, // its own image, and contract_controls' tf_ctl_rc_prep
attn: *attn.Set = undefined, // window_attention's image (WindowAttention owns it), tree_attention's (GlobalDecode)
mask: mask.Set = .{}, // sample's image, and contract_controls' tf_ctl_rc_grammar_mask (prep's module)

/// The set, its kernels appended to `list`.
pub fn init(gpu: check.Gpu, s: cuda.Stream, a: std.mem.Allocator, list: *std.ArrayList(g.Kernel)) !*Set {
Expand All @@ -29,10 +31,13 @@ pub const Set = struct {
set.prep = try prep.Set.init(gpu, s, a, list);
errdefer set.prep.deinit();
set.attn = try attn.Set.init(gpu, s, a, list);
errdefer set.attn.deinit();
try set.mask.init(gpu, s, set.prep.ctl, a, list);
return set;
}

pub fn deinit(set: *Set) void {
set.mask.deinit();
set.attn.deinit();
set.prep.deinit();
set.glue.deinit();
Expand Down
Loading
Loading