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

- On a CUDA card too small for an EXL3 checkpoint's embedding beside its window, the Qwen3.5 engine maps the embedding rows from host memory instead of refusing to start; wherever they fit on the card, they stay there as before (#1678). Thanks to @diwakergupta.

- An Intel XPU server built without DPAS (`-Dxpu-dpas=false`, Gen12LP) serves Nemotron-H and leaves out the Qwen3.8-27B runner and Gemma 4 E4B, refusing them by name, and Gen12LP's Nemotron prompt projection takes 8 x 4 tiles (#1692). Thanks to @jschmied.

- MOSS-Image computes its sampling schedule natively from `scheduler_config.json`, bit for bit what its `MOSSImageScheduler` sets: the shifted float32 grid snapped to the training levels, repeats dropped, sigmas ending at 0 (#1670, part of #1529). Thanks to @BobClawblaw.
Expand Down
4 changes: 4 additions & 0 deletions zig/qwen35_formats_host.zig
Original file line number Diff line number Diff line change
Expand Up @@ -262,3 +262,7 @@ test "format coexistence: EXL3 BF16 prompt: 4096 rows reach both GDN scalar proj
test "format coexistence: EXL3 BF16 prompt: existing rows and partial final slices keep every argument and row" {
for ([_]usize{ 0, 1, 16, 17, 127, 128, 129, 2049, 4095 }) |rows| try bf16Prompt(rows);
}

test {
_ = @import("src/families/qwen3_5/cuda_host_embed.zig"); // where an EXL3 checkpoint's embedding rows live
}
2 changes: 1 addition & 1 deletion zig/src/cli/qwen35_learn.zig
Original file line number Diff line number Diff line change
Expand Up @@ -68,7 +68,7 @@ pub fn main(init: std.process.Init) !u8 {
defer driver.close();
var ctx = try cuda.Context.init(&driver, 0);
defer ctx.deinit();
const e = try qwen.Engine.init(a, io, &ctx, args[1], false);
const e = try qwen.Engine.init(a, io, &ctx, args[1], false, null);
defer e.deinit();
if (e.pockets.any() or e.g.pocket != 0) return error.FreshUntaughtCheckpointRequired;
const t = try Trainer.init(a, io, e);
Expand Down
8 changes: 8 additions & 0 deletions zig/src/families/qwen3_5/cuda_draft.zig
Original file line number Diff line number Diff line change
Expand Up @@ -183,6 +183,14 @@ pub const Draft = struct {
d.gpa.destroy(d);
}

/// One stream's bytes, before the drafter loads: its ring, the target's taps of `hidden` and a frame's scratch.
pub fn streamBytesFor(c: Config, hidden: usize) !usize {
var d: Draft = undefined;
d.c = c;
d.frame_streams = 1;
return c.ringBytes() + engine.tap_rows * c.n_taps * hidden * 2 + try d.layout(false);
}

fn scratchBytes(d: *Draft) !usize {
d.at = 0;
return d.layout(false);
Expand Down
12 changes: 6 additions & 6 deletions zig/src/families/qwen3_5/cuda_engine.zig
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,7 @@ const pocket = @import("cuda_pocket.zig");
const profile = @import("cuda_startup_profile.zig");
const modelopt = @import("cuda_modelopt.zig");
const x3w = @import("cuda_exl3_weights.zig");
const hosted = @import("cuda_host_embed.zig");
pub const recurrent = @import("cuda_recurrent.zig");

pub const Geometry = geometry.Geometry;
Expand Down Expand Up @@ -107,6 +108,7 @@ pub const Engine = struct {
embed_s: u64,
embed_b: u64,
embed_bits: u8, // the embedding's rows' width: 4 or 8 (16: bf16 rows, an EXL3 checkpoint's)
host_embed: ?cuda.HostBuffer = null, // an EXL3 checkpoint's rows in mapped host memory: the card had no room
kit: ?*x3w.Kit = null, // an EXL3 checkpoint's kernels (g.exl3)
head: Proj,
final_norm: u64,
Expand Down Expand Up @@ -171,7 +173,7 @@ pub const Engine = struct {
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) !*Engine {
pub fn init(gpa: std.mem.Allocator, io: std.Io, ctx: *const cuda.Context, dir: []const u8, kv8: bool, fit: ?hosted.Fit) !*Engine {
if (!cuda.kernels.available) return error.BuiltWithoutKernels;
const started = profile.now(io);
const g = try Geometry.read(gpa, io, dir);
Expand Down Expand Up @@ -208,10 +210,8 @@ pub const Engine = struct {
errdefer e.stream.deinit();
var ck = try core.Checkpoint.openModel(gpa, io, dir);
defer core.checkpoint.cache.close(&ck);
// an EXL3 checkpoint's weights are sized by a dry run of its loader (trellis widths come from the tensors)
const wbytes = if (g.exl3) try x3w.measure(e, &ck) else weights.total(g);
e.arena = try DeviceBuffer.alloc(d, wbytes + try e.scratch(.measure));
errdefer e.arena.free();
e.arena = try hosted.arena(e, io, ctx, &ck, fit);
errdefer hosted.release(e);
try e.arena.fill8(0, null); // touched once now: the driver commits memory on first touch, slowly
const kk = cuda.kernels;
const images = [_][]const u8{ kk.qmm_group, kk.qmm_prefill, kk.lane_gemv, kk.affine4_pack, kk.qwen35, kk.sample, kk.qwen35_keep, kk.affine8, kk.affine_prefill, kk.qwen35_kv8, kk.experts, kk.experts_prefill, kk.experts_pack, kk.moe, kk.experts3, kk.experts3_prefill, kk.prefill_attention, kk.gdn_prefill, kk.w4a8_prefill };
Expand Down Expand Up @@ -298,7 +298,7 @@ pub const Engine = struct {
e.host_logits.free();
e.staged.free();
e.tables.free();
e.arena.free();
hosted.release(e);
e.gpa.free(e.layers);
e.gpa.free(e.dir);
e.affine.deinit();
Expand Down
13 changes: 10 additions & 3 deletions zig/src/families/qwen3_5/cuda_exl3_weights.zig
Original file line number Diff line number Diff line change
Expand Up @@ -233,12 +233,12 @@ fn all(s: *Sink, ck: *core.Checkpoint) !void {
const g = e.g;
const kit = e.kit;
const m = "model.language_model.";
// embeddings stay bf16 rows (embedRows); the head is an EXL3 projection
const embed = try plain(s, ck, "{s}embed_tokens.weight", .{m}, .bf16, &.{ g.vocab, g.hidden });
// embeddings stay bf16 rows (embedRows), mapped from host memory when the card has no room; the head is EXL3
const embed: u64 = if (e.host_embed != null) 0 else try plain(s, ck, "{s}embed_tokens.weight", .{m}, .bf16, &.{ g.vocab, g.hidden });
const head = try dense(s, kit, ck, "", "lm_head", g.vocab, g.hidden);
const final = try norm1(s, ck, "{s}norm.weight", .{m}, g.hidden);
if (!s.measure) {
e.embed_w = embed;
e.embed_w = if (e.host_embed) |h| try mappedEmbed(e, ck, h) else embed;
e.embed_s = 0;
e.embed_b = 0;
e.embed_bits = 16;
Expand Down Expand Up @@ -299,6 +299,13 @@ pub fn reserveGroups(k: *Kit, st: cuda.Stream, l: engine.Layer) !void {
}
}

/// The embedding rows copied into the engine's mapped host memory.
fn mappedEmbed(e: *Engine, ck: *core.Checkpoint, host: cuda.HostBuffer) !u64 {
var buf: [200]u8 = undefined;
const t = try ck.expect(try name(&buf, "model.language_model.embed_tokens.weight", .{}), .bf16, &.{ e.g.vocab, e.g.hidden });
return @import("cuda_host_embed.zig").rows(host, t.bytes);
}

/// The arena bytes the weights take (the scratch is added by the caller).
pub fn measure(e: *Engine, ck: *core.Checkpoint) !usize {
var s: Sink = .{ .e = e, .measure = true };
Expand Down
71 changes: 71 additions & 0 deletions zig/src/families/qwen3_5/cuda_host_embed.zig
Original file line number Diff line number Diff line change
@@ -0,0 +1,71 @@
//! An EXL3 checkpoint's bf16 embedding rows in mapped host memory, only when the card has no room for them.
const std = @import("std");
const cuda = @import("cuda");

/// What a load has to leave room for: the server's room before it, one stream's window, and the drafter's directory.
pub const Fit = struct { room: u64, context: usize, drafter: ?[]const u8 };

/// The load's other bytes (kernels, kit, startup costs): ~112 MiB on a 3090 Ti; less refuses as main does, more maps.
const others: u64 = 96 << 20;

/// Whether the rows go to host memory: a discrete card whose room holds the device bytes and one stream only so.
pub fn mapped(unified: bool, room: u64, device: u64, stream: u64, beside: u64) bool {
return !unified and room < device +| stream +| beside;
}

/// The engine's arena of weights and scratch rows, with any host memory for the embedding rows made first.
pub fn arena(e: anytype, io: std.Io, ctx: *const cuda.Context, ck: anytype, fit: ?Fit) !cuda.DeviceBuffer {
e.host_embed = null;
errdefer if (e.host_embed) |*h| h.free();
const bytes = try measure(e, io, ctx, ck, fit);
return cuda.DeviceBuffer.alloc(e.d, bytes + try e.scratch(.measure));
}

/// The arena and the host memory `arena` made.
pub fn release(e: anytype) void {
e.arena.free();
if (e.host_embed) |*h| h.free();
}

/// The weights' bytes on the card (EXL3: a dry run of its loader, as trellis widths come from the tensors).
fn measure(e: anytype, io: std.Io, ctx: *const cuda.Context, ck: anytype, fit: ?Fit) !usize {
if (!e.g.exl3) return @import("cuda_weights.zig").total(e.g);
const x3w = @import("cuda_exl3_weights.zig");
const bytes = try x3w.measure(e, ck);
const f = fit orelse return bytes;
const unified = (try ctx.attribute(.integrated)) != 0;
const stream = e.streamBytes(f.context);
const beside = if (f.drafter) |dir| try drafter(e, io, dir) else 0;
if (!mapped(unified, f.room, bytes + try e.scratch(.measure) + others, stream, beside)) return bytes;
e.host_embed = try cuda.HostBuffer.allocMapped(e.d, e.g.vocab * e.g.hidden * 2);
std.log.info("qwen3_5: embedding rows read from host memory: no room beside a {d}-token stream", .{f.context});
return x3w.measure(e, ck);
}

/// A DFlash2 drafter's device bytes: its weights (bf16 linears made 4-bit, 5/16) and one stream's ring, taps and frame.
fn drafter(e: anytype, io: std.Io, dir: []const u8) !u64 {
const draft = @import("cuda_draft.zig");
const c = draft.Config.read(e.gpa, io, dir, e.g) catch return 0; // not a DFlash2 drafter: its open says why
var d = try std.Io.Dir.cwd().openDir(io, dir, .{ .iterate = true });
defer d.close(io);
var total: u64 = 0;
var it = d.iterate();
while (try it.next(io)) |f| {
if (std.mem.endsWith(u8, f.name, ".safetensors")) total += (try d.statFile(io, f.name, .{})).size;
}
return total / 16 * 5 + try draft.Draft.streamBytesFor(c, e.g.hidden);
}

/// The rows copied to the pinned host memory the device reads in place.
pub fn rows(host: cuda.HostBuffer, bytes: []const u8) !u64 {
if (bytes.len != host.bytes.len) return error.EmbeddingShape;
@memcpy(host.bytes, bytes);
return host.device();
}

test "the rows stay on the card unless a discrete card's room is short of the device bytes and one stream" {
try std.testing.expect(!mapped(false, 20, 10, 5, 5));
try std.testing.expect(mapped(false, 19, 10, 5, 5));
try std.testing.expect(!mapped(true, 19, 10, 5, 5)); // unified memory: host memory is the same memory
try std.testing.expect(mapped(false, 0, std.math.maxInt(u64), 1, 1));
}
14 changes: 12 additions & 2 deletions zig/src/families/qwen3_5/cuda_native.zig
Original file line number Diff line number Diff line change
Expand Up @@ -49,7 +49,10 @@ pub const kept_disk = @import("cuda_disk.zig");
/// explain() words open refusals too (--vision on a checkpoint without a tower it reads).
pub const explains_open = true;

pub const Options = struct { context: usize, drafts: bool, segments: usize = 1, slide: bool = false, vision: ?vision.Limits = null, kv8: bool = false, prompt_int8: bool = false, precision: ?enum { full } = null, rope_yarn: ?f64 = null };
/// The server's reading of the room left now; null if unreadable.
pub const Room = struct { ctx: *anyopaque, read: *const fn (*anyopaque) ?u64 };
/// `room` and `drafter` size an EXL3 checkpoint's load: its embedding rows go to host memory when the card is short.
pub const Options = struct { context: usize, drafts: bool, segments: usize = 1, slide: bool = false, vision: ?vision.Limits = null, kv8: bool = false, prompt_int8: bool = false, precision: ?enum { full } = null, rope_yarn: ?f64 = null, room: ?Room = null, drafter: ?[]const u8 = null };

/// The window --context may ask for: the config's, or the YaRN window its block or --rope-yarn makes (cuda_rope.zig).
pub fn contextCeiling(a: std.mem.Allocator, io: std.Io, dir: []const u8, flag: ?f64) !i64 {
Expand Down Expand Up @@ -133,7 +136,7 @@ pub fn open(gpa: std.mem.Allocator, io: std.Io, ctx: *const cuda.Context, dir: [
const share_snaps = try prefix_mod.sharing();
// a kept state sits on a cold pass's chunk cut, so later chunks keep a cold pass's bits: pages divide the chunk
if (share_snaps > 0 and (page_tokens == 0 or E.max_rows % page_tokens != 0)) return error.QwenShareNeedsPages;
const e = try E.Engine.init(gpa, io, ctx, dir, o.kv8);
const e = try E.Engine.init(gpa, io, ctx, dir, o.kv8, fitOf(o));
errdefer e.deinit();
if (o.rope_yarn) |f| { // --rope-yarn over the downloaded config: its table, and the window it allows
var arena = std.heap.ArenaAllocator.init(gpa);
Expand Down Expand Up @@ -173,6 +176,13 @@ pub fn open(gpa: std.mem.Allocator, io: std.Io, ctx: *const cuda.Context, dir: [
};
}

/// What an EXL3 load must leave room for: one stream at the asked window, and the drafter that loads beside it.
fn fitOf(o: Options) ?@import("cuda_host_embed.zig").Fit {
const r = o.room orelse return null;
const room = r.read(r.ctx) orelse return null;
return .{ .room = room, .context = o.context, .drafter = if (o.drafts) o.drafter else null };
}

pub fn learnModel(p: *anyopaque, dir: []const u8) slide.Model {
const l: *Lanes = @ptrCast(@alignCast(p));
return .{ .e = l.e, .dir = dir, .lay = slide.layout(l.e.g.hidden, l.e.g.layers, l.e.g.intermediate, 0) catch unreachable };
Expand Down
6 changes: 3 additions & 3 deletions zig/tests/qwen35_cuda_main.zig
Original file line number Diff line number Diff line change
Expand Up @@ -59,7 +59,7 @@ pub fn main(init: std.process.Init) !u8 {
defer driver.close();
var ctx = try cuda.Context.init(&driver, 0);
defer ctx.deinit();
const e = try E.Engine.init(init.gpa, init.io, &ctx, args[1], args.len == 6);
const e = try E.Engine.init(init.gpa, init.io, &ctx, args[1], args.len == 6, null);
defer e.deinit();
if (std.mem.eql(u8, args[2], "mtp")) return mtpCheck(init.gpa, init.io, e, args[1], ids.items);
// TF_Q35_PREFILL=N starts the stream after N cycled ids; TF_Q35_BESIDE=N steps an N-token stream beside it
Expand Down Expand Up @@ -393,10 +393,10 @@ fn kl(init: std.process.Init, a: std.mem.Allocator, model: []const u8, ids_path:
defer driver.close();
var ctx = try cuda.Context.init(&driver, 0);
defer ctx.deinit();
const eb = try E.Engine.init(init.gpa, io, &ctx, model, int8);
const eb = try E.Engine.init(init.gpa, io, &ctx, model, int8, null);
defer eb.deinit();
// int8: one engine (two would not fit), fp8 caches, the second cache's prompt chunks through int8 activations
const e8 = if (int8) eb else try E.Engine.init(init.gpa, io, &ctx, model, !control);
const e8 = if (int8) eb else try E.Engine.init(init.gpa, io, &ctx, model, !control, null);
defer if (!int8) e8.deinit();
var cb = try E.Cache.init(init.gpa, eb, skip + rows + 64);
defer cb.deinit(init.gpa);
Expand Down
Loading