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

- Drama voices: `--manage-voices` (off by default) lets admin keys add a voice with `POST /v1/voices` (a WAV with its transcript, or an attested voice file, checked and encoded by the loaded model's own codec) and delete one with `DELETE /v1/voices/NAME`, and `--request-voices` lets a request carry an inline voice object; a running request keeps the voice it copied when it arrived (#3140).

- Idol on Metal: Idol's released denoiser runs as a native Metal family, `idol`, with fp16 block projections and attention inputs summed in fp32 and fp32 norms, softmax and RePo as the SDK splits them; `tf-idol` checks it step by step against idol-sdk's float32 run, and its 27 kernels are in the kernel contract with 19 planted controls. The image encoders and decoders are separate changes (#1766, for #1757). Thanks to @jayleaton.

- Code: a GPTQ reader in `core/quant` reads AutoGPTQ v1 4-bit symmetric group-128 weights as stored (`qweight`, fp16 `scales`, a `qzeros` zero point of 8) into an fp64 reference, and refuses every other GPTQ field, rule or tensor by name; host only, with no caller yet (#3611, refs #3368).
Expand Down
3 changes: 2 additions & 1 deletion docs/api.md
Original file line number Diff line number Diff line change
Expand Up @@ -49,7 +49,8 @@ different scopes, or scopes a key the flags or environment already give, is refu
| `read` | GET `/metrics`, `/v1/metrics`, `/v1/load`, `/memory`, `/v1/memory`, `/stats`, `/dashboard`, `/v1/benchmark/manifest`, `/v1/models`, `/models`, `/v1/voices` |

A scoped key reaches nothing else: not the stored Responses (GET or DELETE `/v1/responses/ID`), Recall, Sliding Weights,
`/v1/imprint`, another method, or a suffix alias such as `/alt/completions` that the server answers for a full key. The route
`/v1/imprint`, adding or deleting voices (`--manage-voices`), another method, or a suffix alias such as `/alt/completions`
that the server answers for a full key. The route
is matched exactly after the query and trailing slashes are cut. A refused route answers 403 with the code
`insufficient_scope` (Messages routes: an Anthropic `permission_error`) and closes the connection before the body is read
or a parked model reloads. The public routes stay public.
Expand Down
17 changes: 15 additions & 2 deletions docs/drama-http-voices.md
Original file line number Diff line number Diff line change
@@ -1,8 +1,8 @@
# Attested HTTP voices

`tensorfold-native serve MODEL --voices DIR --default-voice NAME` loads the catalog at startup. Without these flags the built-in voice and speech request lowering are unchanged. `--default-voice` defaults to `default`; a configured name must exist. A missing, malformed or unattested catalog file refuses startup rather than silently substituting a voice. Restart to reload files.
`tensorfold-native serve MODEL --voices DIR --default-voice NAME` loads the catalog at startup. Without these flags the built-in voice and speech request lowering are unchanged. `--default-voice` defaults to `default`; a configured name must exist. A missing, malformed or unattested catalog file refuses startup rather than silently substituting a voice. Without `--manage-voices`, restart to reload files.

`POST /v1/audio/speech` selects a catalog entry with `voice` (or the existing `speaker` alias). An absent, empty or case-insensitive `default` selects the configured default. Other names match exactly. Request-supplied reference arrays and paths remain unsupported. `GET /v1/voices` returns `{"voices": ["default", ...], "details": [{"id": NAME, "description": TEXT}, ...]}` with catalog names sorted, without transcripts, codes or attestation notes; `description` is the file's optional one-line description (at most 200 bytes), else empty. Non-speech models return the existing unknown-route response.
`POST /v1/audio/speech` selects a catalog entry with `voice` (or the existing `speaker` alias). An absent, empty or case-insensitive `default` selects the configured default. Other names match exactly. Reference arrays, `ref_audio`, `ref_text` and paths in a request remain unsupported; an inline voice object needs `--request-voices` (below). `GET /v1/voices` returns `{"voices": ["default", ...], "details": [{"id": NAME, "description": TEXT}, ...]}` with catalog names sorted, without transcripts, codes or attestation notes; `description` is the file's optional one-line description (at most 200 bytes), else empty. Non-speech models return the existing unknown-route response.

Each regular `NAME.json` file contains:

Expand All @@ -25,6 +25,19 @@ Reference `text` is the exact transcript. Codes are frame-major signed integers,

The loader enforces the family's reference count, transcript length, frame count and codebook ranges before serving. It also rejects empty references, structural prompt tokens, malformed speaker tags, oversized files and oversized catalogs. The assembled prompt must still fit the engine's advertised prompt budget. Reference rows go through the same family `prompt.build` used by the generation CLI; only the tokenizer interface is adapted.

## Voices added while serving

`--manage-voices` (off by default) adds two routes for keys with the `admin` scope, or any key in a key file without scopes; `inference` and `read` keys get 403. Without an API key every client is an admin, so serve with `--api-key-file` before turning it on. Without the flag both routes answer as before, with the unknown-route 404.

- `POST /v1/voices` adds or replaces `name`. The body is `{"name": NAME, ...}` plus either a voice file's own fields (`format`, `source`, `references`, optional `description`), or `{"audio": BASE64, "text": TRANSCRIPT, "source": {...}}` with optional `description`. `audio` is a WAV file (PCM 8, 16, 24 or 32-bit, or float32, any channel count, at most 30 seconds, and a rate from 1 to 192,000 Hz whose reduced ratio `rate / gcd(rate, 44100)` is at most 640; this includes 8/16/24/32/44.1/48/64/88.2/96/176.4/192 kHz) in standard base64, resampled and encoded by the loaded model's own codec, on the speech engine's thread when a lane is free. The attestation and transcript are checked before any audio is encoded. The reply is `{"id": NAME, "description": TEXT, "added": true}` with 201, or `"added": false` with 200 for a replaced voice.
- `DELETE /v1/voices/NAME` deletes a voice; the configured `--default-voice` cannot be deleted (409), and an unknown name is a 404.

With `--voices DIR`, an added voice is written to `DIR/NAME.json` (through a temporary file renamed into place, before the catalog changes) and a deleted one's file is removed, so a restart loads the same catalog. Without a directory, changes last until the server stops. A request reads its voice once, when it arrives: a voice deleted or replaced while it runs does not change its audio. The reference prompt cache keys on the reference rows themselves, so a replaced voice never reuses the old voice's saved rows.

## Inline voices

`--request-voices` (off by default) lets `voice` in `POST /v1/audio/speech` be a voice file's object instead of a name: `"voice": {"format": "drama3-http-voice/1", "source": {...}, "references": [...]}`, checked as the catalog checks a file, attestation included. It builds the same prompt as a catalog voice with the same references, and takes no `speaker` field. Without the flag, an object `voice` gets the same refusal as before.

## Speech limits and discovery

`GET /v1/models` includes a `speech` object only for a loaded speech engine. `max_assembled_prompt_rows` counts all backbone prompt rows, including wrappers, reference transcripts and acoustic reference codes. `max_generated_acoustic_frames` is the output budget, not a text-token limit. `sample_rate_hz` and `samples_per_acoustic_frame` describe the output geometry. `max_input_code_points` is the separate HTTP input-text policy; it is not a tokenizer or assembled-row budget.
Expand Down
2 changes: 1 addition & 1 deletion zig/build/drama3_host.zig
Original file line number Diff line number Diff line change
Expand Up @@ -26,7 +26,7 @@ pub fn native(b: *std.Build, step: *std.Build.Step, family: *std.Build.Module, c
if (family.import_table.get("metal")) |runtime| mod.addImport("metal", runtime);
if (cuda) |c| mod.addImport("cuda", c);
step.dependOn(&b.addObject(.{ .name = name, .root_module = mod }).step);
const tests = b.addTest(.{ .root_module = mod, .filters = &.{ "native silence guard:", "drama reference cache:" } });
const tests = b.addTest(.{ .root_module = mod, .filters = &.{ "native silence guard:", "drama reference cache:", "drama voice encode:" } });
step.dependOn(&b.addRunArtifact(tests).step);
}

Expand Down
6 changes: 3 additions & 3 deletions zig/src/core/engine_api.zig
Original file line number Diff line number Diff line change
Expand Up @@ -125,6 +125,7 @@ pub const SpeechRequest = @import("speech_api.zig").SpeechRequest;
pub const SpeechResult = @import("speech_api.zig").SpeechResult;
pub const SpeechInfo = @import("speech_api.zig").SpeechInfo;
pub const SpeechSubmitError = error{ Closed, Busy, InvalidRequest, Unsupported };
pub const EncodeVoiceError = error{ BadWav, Closed, Failed, OutOfMemory };
pub const ImageRequest = @import("image_api.zig").ImageRequest;
pub const ImageResult = @import("image_api.zig").ImageResult;
pub const ImageInfo = @import("image_api.zig").ImageInfo;
Expand Down Expand Up @@ -444,6 +445,8 @@ pub const Engine = struct {
load: ?*const fn (ctx: *anyopaque, producer: ?load_ledger.Producer) void = null,
/// Asked once per whole request: the returned message is the refusal, up to `refusal_bytes`; null: accepted.
refusal: ?*const fn (ctx: *anyopaque, request: *const Request, out: []u8) ?[]const u8 = null,
/// A reference WAV file's codec rows in `gpa`, on the speech engine's own thread; null: it encodes no voices.
encode_voice: ?*const fn (ctx: *anyopaque, gpa: Allocator, wav: []const u8) EncodeVoiceError![][10]i32 = null,
};

pub fn info(e: Engine) Info {
Expand Down Expand Up @@ -561,7 +564,6 @@ pub const LaneHost = @import("lane_host.zig").LaneHost;
pub const prefill_env = @import("lane_host_env.zig");
/// An opt-in family round planner for the lane host, in place of its `prefill_step` chunks (lane_rounds.zig).
pub const Rounds = @import("lane_host.zig").Rounds;

/// Exact prompt reuse between requests, for any family (prompt_cache.zig).
pub const prompt_cache = @import("prompt_cache.zig");
/// The same for a paged cache over the backend's own KV pages (prompt_radix.zig).
Expand All @@ -572,15 +574,13 @@ pub const cache_modes = @import("cache_modes.zig");
/// Learned prompt-cache states on disk (prompt_imprint.zig), and when a shared cut goes there (prompt_learn.zig).
pub const prompt_imprint = @import("prompt_imprint.zig");
pub const prompt_learn = @import("prompt_learn.zig");

/// A question about a conversation's kept states, in RAM and on disk (rows_ask.zig).
pub const ImprintAsk = @import("rows_ask.zig").Ask;
pub const ImprintOp = @import("rows_ask.zig").Op;
pub const ImprintDisk = @import("rows_ask.zig").Disk;

/// Recall's record of the ids earlier requests read and wrote, for drafts (not the prompt cache's learned states).
pub const recall_store = lanes.recall_store;

/// The idle keepalive's ticker and target contract.
pub const keepalive = @import("keepalive.zig");

Expand Down
8 changes: 8 additions & 0 deletions zig/src/families/drama3/model.zig
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@ pub const max_reference_samples = 30 * 44100;
pub fn reference(samples: []const f32, rate: u32) !void {
if (rate == 0 or rate > 192000 or samples.len == 0 or samples.len > @as(usize, rate) * 30)
return error.BadReference;
if (rate / std.math.gcd(rate, @as(u32, 44100)) > 640) return error.BadReference;
for (samples) |s| if (!std.math.isFinite(s)) return error.BadReference;
}

Expand Down Expand Up @@ -53,3 +54,10 @@ test "typed reference rows are bounded and agree with their semantic code" {
try std.testing.expectError(error.BadCode, validate(&rows, ids, 16, 8));
try std.testing.expectError(error.BadPromptSize, validate(&rows, ids, 2, 1));
}

test "voice reference: reduced resample width accepts standard rates and refuses pathological rates" {
for ([_]u32{ 8000, 11025, 16000, 22050, 24000, 32000, 44100, 48000, 64000, 88200, 96000, 176400, 192000 }) |rate|
try reference(&.{0}, rate);
for ([_]u32{ 44101, 44113, 191999 }) |rate|
try std.testing.expectError(error.BadReference, reference(&.{0}, rate));
}
20 changes: 19 additions & 1 deletion zig/src/families/drama3/wav.zig
Original file line number Diff line number Diff line change
Expand Up @@ -34,7 +34,7 @@ pub fn parse(gpa: std.mem.Allocator, bytes: []const u8) !Audio {
} else if (std.mem.eql(u8, id, "data")) {
data = body;
}
at += 8 + len + (len & 1);
at += 8 + @as(usize, len) + (len & 1);
}
const d = data orelse return error.BadWav;
if (channels == 0 or rate == 0) return error.BadWav;
Expand Down Expand Up @@ -163,3 +163,21 @@ test "resampling keeps torchaudio's output length and a constant signal's level"
try std.testing.expectEqual(@as(usize, 4410), y.len);
for (y[200 .. y.len - 200]) |v| try std.testing.expectApproxEqAbs(@as(f32, 0.25), v, 2e-3);
}

test "voice WAV: a huge trailing chunk cannot overflow the RIFF advance" {
var bytes: [44]u8 = undefined;
header(&bytes, 44100, 0);
@memcpy(bytes[36..40], "JUNK");
std.mem.writeInt(u32, bytes[40..44], 0xFFFFFFF8, .little);
try std.testing.expectError(error.BadWav, parse(std.testing.allocator, &bytes));
}

test "voice WAV: a truncated maximal data chunk is bounded by the available bytes" {
var bytes: [46]u8 = @splat(0);
header(bytes[0..44], 44100, 1);
std.mem.writeInt(u32, bytes[40..44], 0xFFFFFFFF, .little);
const audio = try parse(std.testing.allocator, &bytes);
defer audio.deinit(std.testing.allocator);
try std.testing.expectEqual(@as(usize, 1), audio.samples.len);
try std.testing.expectEqual(@as(f32, 0), audio.samples[0]);
}
14 changes: 6 additions & 8 deletions zig/src/native/drama_host.zig
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,7 @@ const Limit = if (is_cuda) @import("drama_limit.zig").Limit else struct {
fn deinit(_: *@This()) void {}
};
const Warm = if (is_cuda) struct {} else d3.residency.Warm;
const Voice = @import("drama_host_voice.zig").For(Host);
const Session = struct {
e: *d3.Engine,
t: *d3.tts.Tts,
Expand Down Expand Up @@ -66,6 +67,7 @@ const Host = struct {
closing: bool = false,
failed: completion.State = .{},
refs: Refs = .{},
voices: @import("drama_host_voice.zig").Queue = .{},
const vtable: api.Engine.VTable = .{
.info = info,
.submit = submitText,
Expand All @@ -75,6 +77,7 @@ const Host = struct {
.memory = memory,
.keepalive = if (is_cuda) null else keepalive,
.drain = drain,
.encode_voice = Voice.encode,
};
fn self(p: *anyopaque) *Host {
return @ptrCast(@alignCast(p));
Expand Down Expand Up @@ -163,6 +166,7 @@ const Host = struct {
if (is_cuda) h.sessions[0].e.ctx.makeCurrent() catch {
h.lock();
h.closing = true;
Voice.refuse(h);
h.unlock();
while (true) {
h.lock();
Expand All @@ -174,6 +178,7 @@ const Host = struct {
};
while (true) {
h.lock();
if (Voice.step(h)) continue;
const work = h.queue.next() orelse {
if (h.closing or h.failed.closed) {
h.unlock();
Expand Down Expand Up @@ -356,14 +361,7 @@ pub fn open(gpa: std.mem.Allocator, io: std.Io, dir: []const u8, _: []const u8,
try o.silence.validate();
const h = try gpa.create(Host);
errdefer gpa.destroy(h);
h.* = .{
.gpa = gpa,
.io = io,
.limit = undefined,
.queue = try rounds.Queue.init(o.lanes),
.info_ = .{},
.silence = o.silence,
};
h.* = .{ .gpa = gpa, .io = io, .limit = undefined, .queue = try rounds.Queue.init(o.lanes), .info_ = .{}, .silence = o.silence };
if (is_cuda) h.refs = .{ .gpa = gpa, .capacity = o.reference_entries };
try h.limit.init(gpa, io, o.device);
errdefer h.limit.deinit();
Expand Down
87 changes: 87 additions & 0 deletions zig/src/native/drama_host_voice.zig
Original file line number Diff line number Diff line change
@@ -0,0 +1,87 @@
//! A reference WAV file's codes for POST /v1/voices, encoded on the speech host's own thread by an idle lane's codec.
const std = @import("std");
const api = @import("engine_api");

/// One waiting encode; the asking thread sleeps on `done` under the host's mutex.
const Ask = struct {
gpa: std.mem.Allocator,
wav: []const u8,
codes: [][10]i32 = &.{},
err: ?api.EncodeVoiceError = null,
done: bool = false,
cond: std.Io.Condition = .init,
};

/// Asks waiting for the host thread: one at a time, in arrival order.
pub const Queue = struct { turn: std.Io.Mutex = .init, ask: ?*Ask = null };

/// Errors of the file itself: the request's to fix, so the engine stays open.
fn input(err: anyerror) bool {
for ([_]anyerror{ error.NotWav, error.BadWav, error.UnsupportedWav, error.BadReference, error.EmptyAudio }) |e| if (err == e) return true;
return false;
}

pub fn For(comptime Host: type) type {
return struct {
/// The engine's encode_voice: hands the file to the host thread and waits for its codes.
pub fn encode(p: *anyopaque, gpa: std.mem.Allocator, wav: []const u8) api.EncodeVoiceError![][10]i32 {
const h: *Host = @ptrCast(@alignCast(p));
h.voices.turn.lockUncancelable(h.io);
defer h.voices.turn.unlock(h.io);
var ask: Ask = .{ .gpa = gpa, .wav = wav };
h.mutex.lockUncancelable(h.io);
defer h.mutex.unlock(h.io);
if (h.closing or h.failed.closed) return error.Closed;
h.voices.ask = &ask;
h.wake.signal(h.io);
while (!ask.done) ask.cond.waitUncancelable(h.io, &h.mutex);
return ask.err orelse ask.codes;
}

/// On the host thread with its mutex held: runs a waiting encode on an idle lane; true: done, mutex released.
pub fn step(h: *Host) bool {
const ask = h.voices.ask orelse return false;
if (h.closing or h.failed.closed) {
refuse(h);
h.mutex.unlock(h.io);
return true;
}
const lane = for (h.jobs[0..h.queue.lanes], 0..) |job, i| {
if (job == null) break i;
} else return false; // every lane busy: the ask waits for one to finish
h.voices.ask = null;
h.mutex.unlock(h.io);
const t = h.sessions[lane].t;
const outcome: ?api.EncodeVoiceError = if (t.encodeWav(ask.wav)) |codes| copy: {
defer t.c.gpa.free(codes);
ask.codes = ask.gpa.dupe([10]i32, codes) catch break :copy error.OutOfMemory;
break :copy null;
} else |err| if (err == error.OutOfMemory) error.OutOfMemory else if (input(err)) error.BadWav else fail: {
std.log.warn("drama3: reference encode failed, closing the speech engine: {s}", .{@errorName(err)});
break :fail error.Failed;
};
h.mutex.lockUncancelable(h.io);
if (outcome) |e| if (e == error.Failed) {
h.failed.closed = true; // a device error: as in advance, the engine stops serving
};
ask.err = outcome;
ask.done = true;
ask.cond.signal(h.io);
h.mutex.unlock(h.io);
return true;
}

/// With the host's mutex held and the engine closing: a waiting encode gets Closed.
pub fn refuse(h: *Host) void {
const ask = h.voices.ask orelse return;
h.voices.ask = null;
ask.err = error.Closed;
ask.done = true;
ask.cond.signal(h.io);
}
};
}

test {
_ = @import("drama_host_voice_test.zig");
}
Loading
Loading