Skip to content
Closed
Show file tree
Hide file tree
Changes from 1 commit
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
Prev Previous commit
Next Next commit
music3: share the backend-independent parts before a Metal backend
The AR's sampling, result, trace and progress types, the song's timings,
the weight bytes a frame reads and the clock move to common.zig. The
weight loaders take any store with alloc / upload / stage / unstage, and
the CUDA store moves to store.zig, so weights.zig no longer touches the
CUDA runtime. generate.zig names its backend from the family module and
asks the engine for its weight bytes; parity.zig takes either engine.

No change to what the CUDA engine computes: the same kernels run on the
same buffers in the same order.
  • Loading branch information
drowzeys committed Oct 17, 2026
commit 27b283c42efdd852409b68b49a9049bd82fce62a
2 changes: 1 addition & 1 deletion zig/build/cuda.zig
Original file line number Diff line number Diff line change
Expand Up @@ -160,7 +160,7 @@ pub fn targets(b: *std.Build, target: std.Build.ResolvedTarget, optimize: std.bu
const controls = if (nvcc) |tool| fatbin(b, tool, version.?, .{ .name = "contract_controls", .flags = &.{"-O3"} }, sms) else null;
@import("kernel_contract.zig").cuda(b, runner_exe, controls);
nativeServer(b, target, optimize, cuda, mods.core, mods.lanes, mods.nemotron, mods.heat, mods.tokenizer, build_options, true).root_module.strip = strip;
const m3_tool = b.createModule(.{ .root_source_file = b.path("zig/src/families/music3/generate.zig"), .target = target, .optimize = optimize, .link_libc = true, .strip = strip, .imports = &.{ .{ .name = "cuda", .module = cuda }, .{ .name = "core", .module = mods.core }, .{ .name = "music3", .module = music3Module(b, target, optimize, cuda, mods.core) } } });
const m3_tool = b.createModule(.{ .root_source_file = b.path("zig/src/families/music3/generate.zig"), .target = target, .optimize = optimize, .link_libc = true, .strip = strip, .imports = &.{ .{ .name = "core", .module = mods.core }, .{ .name = "music3", .module = music3Module(b, target, optimize, cuda, mods.core) } } });
const m3_exe = b.addExecutable(.{ .name = "music3-generate", .root_module = m3_tool });
b.step("music3-generate", "MiniMax Music 3 lyrics and a caption to a song on one CUDA GPU").dependOn(&b.addInstallArtifact(m3_exe, .{}).step);
}
Expand Down
39 changes: 7 additions & 32 deletions zig/src/families/music3/ar.zig
Original file line number Diff line number Diff line change
Expand Up @@ -4,32 +4,15 @@ const cuda = @import("cuda");
const cfg = @import("config.zig");
const wts = @import("weights.zig");
const kern = @import("kernels.zig");
const common = @import("common.zig");

const H = cfg.hidden;
const Buf = cuda.DeviceBuffer;
const decode_splits = 16;

pub const Sampling = struct {
ar_cfg: f32 = 1.5,
top_k: i32 = 50,
seed: u64 = 0, // the AR stage's own seed (config.deriveSeed(song seed, "ar"))
};

/// Per-frame logits for parity (teacher forcing): code 0 [2, 16385] and the depth heads [7, 2, 1024], fp32.
pub const Trace = struct {
c0: std.ArrayList(f32) = .empty,
depth: std.ArrayList(f32) = .empty,
};

pub const Result = struct {
states: []u16, // bf16 [frames, 8 * 4096] of the kept frames (frame 0 dropped, as the reference)
frames: usize,
stopped: bool,
prompt_tokens: usize,
prefill_ms: f64,
ar_ms: f64,
frames_per_s: f64,
};
pub const Sampling = common.Sampling;
pub const Trace = common.Trace;
pub const Result = common.Result;

pub const Ar = struct {
gpa: std.mem.Allocator,
Expand Down Expand Up @@ -323,10 +306,7 @@ pub const Ar = struct {
try a.graph.?.launchOn(a.s);
}

pub const Progress = struct {
ctx: *anyopaque,
f: *const fn (ctx: *anyopaque, stage: []const u8, done: usize, total: usize) void,
};
pub const Progress = common.Progress;

/// Prompt, then frames to the stop code or `limit` kept; `forced_codes` replaces every draw, `trace` keeps logits.
pub fn run(a: *Ar, io: std.Io, ids: []const u32, unc: []const u32, smp: Sampling, limit: usize, graphs: bool, sync_every: usize, forced_codes: ?[]const [8]i32, trace: ?*Trace, progress: ?Progress) !Result {
Expand Down Expand Up @@ -376,10 +356,5 @@ pub const Ar = struct {
}
};

pub fn nowNs(io: std.Io) i128 {
return @intCast(std.Io.Clock.awake.now(io).toNanoseconds());
}

pub fn ms(a: i128, b: i128) f64 {
return @as(f64, @floatFromInt(b - a)) / 1e6;
}
pub const nowNs = common.nowNs;
pub const ms = common.ms;
73 changes: 73 additions & 0 deletions zig/src/families/music3/common.zig
Original file line number Diff line number Diff line change
@@ -0,0 +1,73 @@
//! What every backend shares: the AR's sampling knobs, its result and trace, a song's timings, the clock.
const std = @import("std");
const cfg = @import("config.zig");
const wts = @import("weights.zig");

pub const Sampling = struct {
ar_cfg: f32 = 1.5,
top_k: i32 = 50,
seed: u64 = 0, // the AR stage's own seed (config.deriveSeed(song seed, "ar"))
};

/// Per-frame logits for parity (teacher forcing): code 0 [2, 16385] and the depth heads [7, 2, 1024], fp32.
pub const Trace = struct {
c0: std.ArrayList(f32) = .empty,
depth: std.ArrayList(f32) = .empty,
};

pub const Result = struct {
states: []u16, // bf16 [frames, 8 * 4096] of the kept frames (frame 0 dropped, as the reference)
frames: usize,
stopped: bool,
prompt_tokens: usize,
prefill_ms: f64,
ar_ms: f64,
frames_per_s: f64,
};

pub const Progress = struct {
ctx: *anyopaque,
f: *const fn (ctx: *anyopaque, stage: []const u8, done: usize, total: usize) void,
};

pub const Song = struct {
audio: []f32, // [2, samples]
samples: usize,
frames: usize,
stopped: bool,
prompt_tokens: usize,
prefill_ms: f64,
ar_ms: f64,
frames_per_s: f64,
dit_ms: f64,
dav_ms: f64,
total_ms: f64,
latent_frames: usize,
peak_device_gb: f64,
};

/// Weight bytes a frame reads: body and lm_head once, the depth decoder 7 times, each head once.
pub fn frameBytes(a: *const wts.Ar) f64 {
const per: f64 = if (a.format == .int8) 1 else 2;
var n: f64 = 0;
const add = struct {
fn m(x: wts.Mat) f64 {
return @floatFromInt(x.n * x.k);
}
}.m;
for (a.body) |L| n += add(L.qkv) + add(L.o) + add(L.gate_up) + add(L.down);
n += add(a.lm_head);
var dn: f64 = add(a.projection);
for (a.depth) |L| dn += add(L.qkv) + add(L.o) + add(L.gate_up) + add(L.down);
n += @as(f64, cfg.codebooks - 1) * dn;
for (a.heads) |h| n += add(h);
return n * per;
}

pub fn nowNs(io: std.Io) i128 {
return @intCast(std.Io.Clock.awake.now(io).toNanoseconds());
}

pub fn ms(a: i128, b: i128) f64 {
return @as(f64, @floatFromInt(b - a)) / 1e6;
}
43 changes: 11 additions & 32 deletions zig/src/families/music3/engine.zig
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,8 @@ const prompt = @import("prompt.zig");
const ar_ = @import("ar.zig");
const dit_ = @import("dit.zig");
const dav_ = @import("dav.zig");
const common = @import("common.zig");
const Store = @import("store.zig").Store;

pub const Options = struct {
format: wts.Format = .int8,
Expand All @@ -23,23 +25,9 @@ pub const Options = struct {
log: bool = true,
};

pub const Song = struct {
audio: []f32, // [2, samples]
samples: usize,
frames: usize,
stopped: bool,
prompt_tokens: usize,
prefill_ms: f64,
ar_ms: f64,
frames_per_s: f64,
dit_ms: f64,
dav_ms: f64,
total_ms: f64,
latent_frames: usize,
peak_device_gb: f64,
};
pub const Song = common.Song;

pub const Progress = ar_.Ar.Progress;
pub const Progress = common.Progress;

pub const Engine = struct {
gpa: std.mem.Allocator,
Expand All @@ -48,7 +36,7 @@ pub const Engine = struct {
ctx: cuda.Context,
stream: cuda.Stream,
k: *kern.Kernels,
store: wts.Store,
store: Store,
arw: ?wts.Ar = null,
ditw: ?wts.Dit = null,
davw: ?wts.Dav = null,
Expand Down Expand Up @@ -117,21 +105,12 @@ pub const Engine = struct {

/// Weight bytes a frame reads: body and lm_head once, the depth decoder 7 times, each head once.
pub fn frameBytes(e: *const Engine) f64 {
const a = &e.arw.?;
const per: f64 = if (a.format == .int8) 1 else 2;
var n: f64 = 0;
const add = struct {
fn m(x: wts.Mat) f64 {
return @floatFromInt(x.n * x.k);
}
}.m;
for (a.body) |L| n += add(L.qkv) + add(L.o) + add(L.gate_up) + add(L.down);
n += add(a.lm_head);
var dn: f64 = add(a.projection);
for (a.depth) |L| dn += add(L.qkv) + add(L.o) + add(L.gate_up) + add(L.down);
n += 7 * dn;
for (a.heads) |h| n += add(h);
return n * per;
return common.frameBytes(&e.arw.?);
}

/// Weight bytes on the device.
pub fn deviceBytes(e: *const Engine) usize {
return e.store.bytes;
}

pub fn generate(e: *Engine, io: std.Io, caption: []const u8, lyrics: []const u8, s: cfg.Settings, progress: ?Progress) !Song {
Expand Down
17 changes: 8 additions & 9 deletions zig/src/families/music3/generate.zig
Original file line number Diff line number Diff line change
@@ -1,6 +1,5 @@
//! music3-generate: MiniMax Music 3 to a song on one CUDA GPU, a --serve mode, parity dumps (MiniMax-Music3 License).
//! music3-generate: MiniMax Music 3 songs on CUDA or Metal, --serve, parity dumps (MiniMax-Music3 License).
const std = @import("std");
const cuda = @import("cuda");
const core = @import("core");
const m3 = @import("music3");

Expand Down Expand Up @@ -126,7 +125,7 @@ const PrintProgress = struct {
last: i128 = 0,
fn f(ctx: *anyopaque, stage: []const u8, done: usize, total: usize) void {
const p: *PrintProgress = @ptrCast(@alignCast(ctx));
const now = m3.ar.nowNs(p.io);
const now = m3.common.nowNs(p.io);
if (done != total and now - p.last < 2_000_000_000) return;
p.last = now;
std.debug.print("[music3] {s} {d}/{d}\n", .{ stage, done, total });
Expand All @@ -142,7 +141,7 @@ fn writeWav(gpa: std.mem.Allocator, io: std.Io, path: []const u8, audio: []const
fn statsJson(gpa: std.mem.Allocator, e: *m3.Engine, song: m3.Song, s: cfg.Settings, extra: ?[]const u8) ![]u8 {
const aus = audioS(song);
const gbs = e.frameBytes() * song.frames_per_s / 1e9;
return std.fmt.allocPrint(gpa, "{{\"engine\":\"tensorfold-music3-cuda\",\"weights\":\"{s}\",\"prompt_tokens\":{d},\"frames\":{d},\"stopped\":{},\"prefill_s\":{d:.3},\"ar_s\":{d:.3},\"frames_per_s\":{d:.2},\"ar_weight_gb_per_frame\":{d:.2},\"ar_achieved_gb_s\":{d:.1},\"dit_s\":{d:.3},\"dav_s\":{d:.3},\"total_s\":{d:.3},\"audio_s\":{d:.3},\"rtf\":{d:.3},\"latent_frames\":{d},\"steps\":{d},\"seed\":{d},\"load_s\":{d:.2},\"peak_memory_gb\":{d:.2}{s}}}", .{ @tagName(e.o.format), song.prompt_tokens, song.frames, song.stopped, song.prefill_ms / 1000, song.ar_ms / 1000, song.frames_per_s, e.frameBytes() / 1e9, gbs, song.dit_ms / 1000, song.dav_ms / 1000, song.total_ms / 1000, aus, song.total_ms / 1000 / @max(aus, 1e-9), song.latent_frames, s.steps, s.seed, e.load_ms / 1000, song.peak_device_gb, extra orelse "" });
return std.fmt.allocPrint(gpa, "{{\"engine\":\"tensorfold-music3-" ++ m3.backend ++ "\",\"weights\":\"{s}\",\"prompt_tokens\":{d},\"frames\":{d},\"stopped\":{},\"prefill_s\":{d:.3},\"ar_s\":{d:.3},\"frames_per_s\":{d:.2},\"ar_weight_gb_per_frame\":{d:.2},\"ar_achieved_gb_s\":{d:.1},\"dit_s\":{d:.3},\"dav_s\":{d:.3},\"total_s\":{d:.3},\"audio_s\":{d:.3},\"rtf\":{d:.3},\"latent_frames\":{d},\"steps\":{d},\"seed\":{d},\"load_s\":{d:.2},\"peak_memory_gb\":{d:.2}{s}}}", .{ @tagName(e.o.format), song.prompt_tokens, song.frames, song.stopped, song.prefill_ms / 1000, song.ar_ms / 1000, song.frames_per_s, e.frameBytes() / 1e9, gbs, song.dit_ms / 1000, song.dav_ms / 1000, song.total_ms / 1000, aus, song.total_ms / 1000 / @max(aus, 1e-9), song.latent_frames, s.steps, s.seed, e.load_ms / 1000, song.peak_device_gb, extra orelse "" });
}

fn idsOnly(gpa: std.mem.Allocator, io: std.Io, a: Args) !u8 {
Expand Down Expand Up @@ -182,7 +181,7 @@ const ServeProgress = struct {
const p: *ServeProgress = @ptrCast(@alignCast(ctx));
if (!p.on) return;
const si: usize = if (std.mem.eql(u8, stage, "ar")) 0 else if (std.mem.eql(u8, stage, "dit")) 1 else 2;
const now = m3.ar.nowNs(p.io);
const now = m3.common.nowNs(p.io);
if (done != total and now - p.last[si] < 1_000_000_000) return;
p.last[si] = now;
std.debug.print("{{\"id\":{s},\"progress\":{{\"stage\":\"{s}\",\"done\":{d},\"total\":{d}}}}}\n", .{ p.id, stage, done, total });
Expand All @@ -191,18 +190,18 @@ const ServeProgress = struct {

fn serve(gpa: std.mem.Allocator, io: std.Io, a: Args, opts: m3.Options) !u8 {
std.debug.print("{s}\n", .{built_with});
const t0 = m3.ar.nowNs(io);
const t0 = m3.common.nowNs(io);
const e = m3.Engine.create(gpa, io, a.model, opts) catch |er| {
var buf: [256]u8 = undefined;
answer(std.fmt.bufPrint(&buf, "{{\"ok\":false,\"error\":\"load failed: {s}\"}}", .{@errorName(er)}) catch "{\"ok\":false,\"error\":\"load failed\"}");
return 1;
};
defer e.destroy();
const load_s = m3.ar.ms(t0, m3.ar.nowNs(io)) / 1000;
std.debug.print("[music3] serving {s}: loaded in {d:.1}s; weights on the device: {d:.1} GB ({s})\n", .{ a.model, load_s, @as(f64, @floatFromInt(e.store.bytes)) / 1e9, @tagName(opts.format) });
const load_s = m3.common.ms(t0, m3.common.nowNs(io)) / 1000;
std.debug.print("[music3] serving {s}: loaded in {d:.1}s; weights on the device: {d:.1} GB ({s})\n", .{ a.model, load_s, @as(f64, @floatFromInt(e.deviceBytes())) / 1e9, @tagName(opts.format) });
{
var buf: [256]u8 = undefined;
answer(try std.fmt.bufPrint(&buf, "{{\"ready\":true,\"engine\":\"tensorfold-music3-cuda\",\"load_s\":{d:.2},\"sample_rate\":44100,\"channels\":2,\"license_display\":\"MiniMax-Music3\",\"weights\":\"{s}\"}}", .{ load_s, @tagName(opts.format) }));
answer(try std.fmt.bufPrint(&buf, "{{\"ready\":true,\"engine\":\"tensorfold-music3-" ++ m3.backend ++ "\",\"load_s\":{d:.2},\"sample_rate\":44100,\"channels\":2,\"license_display\":\"MiniMax-Music3\",\"weights\":\"{s}\"}}", .{ load_s, @tagName(opts.format) }));
}
const in = fdopen(0, "r") orelse return error.Stdin;
var line: ?[*]u8 = null;
Expand Down
2 changes: 2 additions & 0 deletions zig/src/families/music3/music3.zig
Original file line number Diff line number Diff line change
@@ -1,5 +1,7 @@
//! MiniMax Music 3 (MiniMax-Music3) on one CUDA GPU: the AR LM and depth decoder, the DiT and the DAV.
pub const backend = "cuda";
pub const config = @import("config.zig");
pub const common = @import("common.zig");
pub const prompt = @import("prompt.zig");
pub const weights = @import("weights.zig");
pub const kernels = @import("kernels.zig");
Expand Down
19 changes: 10 additions & 9 deletions zig/src/families/music3/parity.zig
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
//! Parity dumps vs a ComfyUI reference run (REF) as .npy in OUT for tools/music3/parity.py.
const std = @import("std");
const m3 = @import("music3.zig");
const common = @import("common.zig");
const npy = @import("npy.zig");
const cfg = @import("config.zig");

Expand Down Expand Up @@ -40,7 +40,8 @@ fn transpose(gpa: std.mem.Allocator, src: []const f32, C: usize, L: usize) ![]f3
return out;
}

pub fn run(gpa: std.mem.Allocator, io: std.Io, e: *m3.Engine, o: Opts) !u8 {
/// `e`: either backend's engine (ids, ar.run, dit().denoise, dav().decode).
pub fn run(gpa: std.mem.Allocator, io: std.Io, e: anytype, o: Opts) !u8 {
var arena = std.heap.ArenaAllocator.init(gpa);
defer arena.deinit();
const a = arena.allocator();
Expand All @@ -58,13 +59,13 @@ pub fn run(gpa: std.mem.Allocator, io: std.Io, e: *m3.Engine, o: Opts) !u8 {
const codes: []const [8]i32 = @as([*]const [8]i32, @ptrCast(flat.ptr))[0..nf];
var frames = if (o.frames > 0) o.frames else nf - 1;
frames = @min(frames, nf - 1);
var tr: m3.ar.Trace = .{};
var tr: common.Trace = .{};
defer tr.c0.deinit(gpa);
defer tr.depth.deinit(gpa);
const t0 = m3.ar.nowNs(io);
const t0 = common.nowNs(io);
const r = try e.ar.?.run(io, pr.cond, pr.unc, .{}, frames, false, 1, codes[0 .. frames + 1], &tr, null);
defer gpa.free(r.states);
const secs = m3.ar.ms(t0, m3.ar.nowNs(io)) / 1000;
const secs = common.ms(t0, common.nowNs(io)) / 1000;
const nlog = tr.c0.items.len / (2 * (cfg.c0_codes + 1));
try npy.write(gpa, io, try path(a, o.out, "c0_logits.npy"), f32, tr.c0.items, &.{ nlog, 2, cfg.c0_codes + 1 });
try npy.write(gpa, io, try path(a, o.out, "depth_logits.npy"), f32, tr.depth.items, &.{ nlog, 7, 2, cfg.codebook_size });
Expand All @@ -87,10 +88,10 @@ pub fn run(gpa: std.mem.Allocator, io: std.Io, e: *m3.Engine, o: Opts) !u8 {
if (L != cfg.framesToLatents(frames)) return error.NoiseLength;
const noise = try transpose(a, try nz.toF32(a), 128, L);
var d = e.dit();
const t0 = m3.ar.nowNs(io);
const t0 = common.nowNs(io);
const lat = try d.denoise(states, frames, o.steps, o.dit_cfg, 0, noise, null, null);
defer gpa.free(lat);
const secs = m3.ar.ms(t0, m3.ar.nowNs(io)) / 1000;
const secs = common.ms(t0, common.nowNs(io)) / 1000;
const back = try transpose(a, lat, L, 128); // [L, 128] -> [128, L]
try npy.write(gpa, io, try path(a, o.out, "latent.npy"), f32, back, &.{ 1, 128, L });
std.debug.print("[music3] parity dit: {d} latent rows, {d:.1}s\n", .{ L, secs });
Expand Down Expand Up @@ -128,10 +129,10 @@ pub fn run(gpa: std.mem.Allocator, io: std.Io, e: *m3.Engine, o: Opts) !u8 {
defer lat.deinit(gpa);
const L = lat.shape[lat.rank - 1];
const x = try transpose(a, try lat.toF32(a), 128, L);
const t0 = m3.ar.nowNs(io);
const t0 = common.nowNs(io);
const audio = try v.decode(x, L);
defer gpa.free(audio);
const secs = m3.ar.ms(t0, m3.ar.nowNs(io)) / 1000;
const secs = common.ms(t0, common.nowNs(io)) / 1000;
try npy.write(gpa, io, try path(a, o.out, "audio.npy"), f32, audio, &.{ 2, L * 512 });
std.debug.print("[music3] parity dav: {d} latent rows, {d:.2}s\n", .{ L, secs });
} else |_| {}
Expand Down
46 changes: 46 additions & 0 deletions zig/src/families/music3/store.zig
Original file line number Diff line number Diff line change
@@ -0,0 +1,46 @@
//! The CUDA weight store weights.zig's loaders fill: device buffers for the engine's life, one staging buffer.
const std = @import("std");
const cuda = @import("cuda");

pub const Store = struct {
gpa: std.mem.Allocator,
bufs: std.ArrayList(cuda.DeviceBuffer) = .empty,
bytes: usize = 0,
d: *const cuda.Driver,
staging: ?cuda.DeviceBuffer = null,

const staging_bytes: usize = 24576 * 4096 * 2;

pub fn alloc(s: *Store, bytes: usize) !u64 {
const b = try cuda.DeviceBuffer.alloc(s.d, @max(bytes, 256));
try s.bufs.append(s.gpa, b);
s.bytes += bytes;
return b.ptr;
}

pub fn upload(s: *Store, bytes: []const u8) !u64 {
const p = try s.alloc(bytes.len);
var b = s.bufs.items[s.bufs.items.len - 1];
try b.upload(0, bytes);
return p;
}

/// `bytes` in the staging buffer (made on first use), for the quantizer to read.
pub fn stage(s: *Store, bytes: []const u8) !u64 {
if (bytes.len > staging_bytes) return error.StagingTooSmall;
if (s.staging == null) s.staging = try cuda.DeviceBuffer.alloc(s.d, staging_bytes);
try s.staging.?.upload(0, bytes);
return s.staging.?.ptr;
}

pub fn unstage(s: *Store) void {
if (s.staging) |*b| b.free();
s.staging = null;
}

pub fn deinit(s: *Store) void {
s.unstage();
for (s.bufs.items) |*b| b.free();
s.bufs.deinit(s.gpa);
}
};
Loading