Skip to content
Open
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
8 changes: 5 additions & 3 deletions docs/api.md
Original file line number Diff line number Diff line change
Expand Up @@ -176,7 +176,7 @@ Unsupported image input, audio, video and non-text output requests receive HTTP

Each native GET /v1/models entry, including every configured alias, includes a capabilities object.
It reports the loaded engine's boolean Info flags: text_generation, context_fitted, call_gates, loop_guard,
thinking_budget, reasoning, reasoning_optional, answer_limit, structures, logprobs, penalties, prompt_logprobs,
thinking_budget, reasoning, reasoning_optional, answer_limit, structures, logprobs, penalties, logit_bias, prompt_logprobs,
prompt_cache, cache_salt ([salts](#prompt-cache-salts)), warm_turns, plain_only, decides, pictures, greedy_only,
slide_conversations, folded_memory and pocket_usage. folded_memory is true when `--slide` has attached the engine's folded
memory weights (living weights), and false when learning is off. The vision, speech, embeddings, readouts and rerank fields
Expand Down Expand Up @@ -601,6 +601,7 @@ delete runs gets 503, an id that is not a number 400, and an id the graph does n
| `max_tokens`, `max_completion_tokens` | Explicit reply limit; rejected if prompt plus reply exceeds the window | Both |
| `temperature`, `top_p`, `top_k`, `min_p` | Sampling overrides; zero temperature is greedy | Both |
| `presence_penalty`, `frequency_penalty` | OpenAI's, from -2 to 2: before each draw, greedy or sampled, a token the reply already holds loses `presence_penalty` from its logit and `frequency_penalty` once for each time it holds it; the prompt's tokens do not count. Drafted replies equal undrafted ones with them. Applied by Qwen3.8-27B and Qwen3.5-MoE on CUDA, and Qwen3.8-27B and Qwen3.8-Flash-Next on Metal; other engines refuse nonzero values with 400; zero, null and omitted values keep working | Native |
| `logit_bias` | OpenAI's: an object of decimal token IDs (within the tokenizer's vocabulary) to numbers from -100 to 100, at most 300 entries. Before each draw, greedy or sampled, a listed token's logit gains its number; exactly -100 bans the token, so it is never emitted (a forced thinking close or EOS conflicting with a ban fails the reply). Drafted replies equal undrafted ones with it. Applied by Qwen3.8-27B and Qwen3.5-MoE on CUDA (a kernel set built with `tf_bias_rows`), Qwen3.5-2B on Metal and Nemotron Parse on HIP; other engines refuse a non-empty object, even one of zeros, with 400; `{}`, null and omitted keep working | Native |
| `seed` | Explicit sampling key; native fallback uses configured defaults, then a fresh key (see below) | Both |
| `stream` | Server-sent events; the last event carries usage | Both |
| `stream_options.include_usage` | Usage in its own final event with `"choices": []`, not on the finish event | Both |
Expand Down Expand Up @@ -675,7 +676,8 @@ one token, the best, at probability 1. The server computes them from each token'
own cut, so they cost no engine work beyond asking for all 20 alternatives; `top_logprobs` still shows the count
asked for, and the reply's tokens and every other field are the same with the option on or off. A sampled request
needs `top_k` from 1 to 20, so the kept set always fits inside the 20 alternatives a row carries; other `top_k`
values (including none), a grammar, or a nonzero `presence_penalty` or `frequency_penalty` return HTTP 400.
values (including none), a grammar, non-empty `logit_bias`, or a nonzero `presence_penalty` or `frequency_penalty`
return HTTP 400.
The kept set is computed from the rows' 32-bit values, so a token whose cumulative `top_p` sum or `min_p` floor falls
within about 1e-6 of its cut can be listed on the other side of it, and a GPU sampler may skip a kept token more than
24 below the best in logit over temperature, whose listed probability is under 4e-11.
Expand Down Expand Up @@ -1930,7 +1932,7 @@ key may always ask. Only these two routes carry the binding: `/v1/responses`, `/
| `prompt_sha256` | The prompt's token ids after the template, hashed as `tensorfold.token_sha256` hashes the reply's |
| `token_sha256` | The reply's token ids, equal to `tensorfold.token_sha256` |
| `finish_reason` | The reply's |
| `request` | The resolved request the engine read: `max_tokens` after the window's clamp; `sampling` (null when greedy, else the `seed` actually used, `temperature`, `top_k`, `top_p` and `min_p`); `presence_penalty`, `frequency_penalty`; `eos` and `stop`; `drafts`; `think_budget`, `think_close`, `think_end`, `answer_max`; `loop_guard`, `loop_stop`; `call` (a required tool call's gate); `structure` (the grammar's `kind`, `text_sha256`, `after`, `budget`); `logprobs`, `prompt_logprobs`, `decide` and `untaught` |
| `request` | The resolved request the engine read: `max_tokens` after the window's clamp; `sampling` (null when greedy, else the `seed` actually used, `temperature`, `top_k`, `top_p` and `min_p`); `presence_penalty`, `frequency_penalty`; `eos` and `stop`; `logit_bias` (nonempty requests only: each entry's `token`, `value` and `ban`); `drafts`; `think_budget`, `think_close`, `think_end`, `answer_max`; `loop_guard`, `loop_stop`; `call` (a required tool call's gate); `structure` (the grammar's `kind`, `text_sha256`, `after`, `budget`); `logprobs`, `prompt_logprobs`, `decide` and `untaught` |
| `request_sha256` | SHA-256 over `request`, walked in order as below |

Every field is length-prefixed: its byte length as a little-endian u64, then its bytes. `request_sha256` hashes the field
Expand Down
4 changes: 4 additions & 0 deletions zig/build/cuda.zig
Original file line number Diff line number Diff line change
Expand Up @@ -383,6 +383,10 @@ pub fn hostTests(b: *std.Build, draft_ids: *std.Build.Module, build_options: *st
const drama3 = @import("drama3_host.zig").hostTests(b, step, cuda, mods.core);
const native_modules = engines(b, host, .debug, cuda, mods.core, mods.lanes, mods.nemotron, mods.heat, mods.qwen35, mods.qwen_vision);
@import("zonos3.zig").hostTests(b, step, cuda, mods.core, mods.lanes, native_modules.api);
const bias_host = b.step("test-logit-bias-host", "Sparse biases, hard bans, path rows and wrapper propagation without devices");
bias_host.dependOn(&b.addRunArtifact(b.addTest(.{ .root_module = native_modules.api, .filters = &.{"bias admission:"} })).step);
bias_host.dependOn(&b.addRunArtifact(b.addTest(.{ .root_module = mods.lanes, .filters = &.{ "bias", "recorded backend preserves", "committed first crosses" } })).step);
bias_host.dependOn(&b.addRunArtifact(b.addTest(.{ .root_module = mods.qwen35, .filters = &.{ "bias rows", "bias defaults:" } })).step);
b.step("test-qwen-grants-host", "Qwen MTP head-cost and copy grants without a GPU").dependOn(&b.addRunArtifact(b.addTest(.{ .root_module = mods.qwen35, .filters = &.{"shared head costs:"} })).step);
b.step("test-nemotron-grants-host", "Nemotron shared head-cost and copy grants without a GPU").dependOn(&b.addRunArtifact(b.addTest(.{ .root_module = mods.nemotron, .filters = &.{"Nemotron shared prices:"} })).step);
b.step("test-nemotron-cuda-steps-host", "Nemotron CUDA's stepped prompt pass on the lanes, stopped before GPU work").dependOn(&b.addRunArtifact(b.addTest(.{ .root_module = mods.nemotron, .filters = &.{"nemotron cuda steps:"} })).step);
Expand Down
1 change: 1 addition & 0 deletions zig/build/cuda_server_host.zig
Original file line number Diff line number Diff line change
Expand Up @@ -119,6 +119,7 @@ pub fn steps(b: *std.Build, host: std.Build.ResolvedTarget, cuda: *std.Build.Mod
prefill.has_side_effects = true; // reads TF_TOKENIZER_DIRS on every run
prefill.setCwd(b.path("."));
b.step("test-prefill-host", "Continued final assistant messages on Messages and chat routes and real templates, no devices").dependOn(&prefill.step);
b.step("test-server-logit-bias-host", "Real HTTP token bias forwarding, refusal and sparse parsing").dependOn(&b.addRunArtifact(b.addTest(.{ .root_module = server_tests, .filters = &.{"logit_bias:"} })).step);
b.step("test-cors-template-host", "Exact CORS and special-preserving template route regressions").dependOn(&b.addRunArtifact(b.addTest(.{ .root_module = server_tests, .filters = &.{ "CORS", "apply-template:" } })).step);
const salts = b.step("test-cache-salt-host", "Salted state, disk, Recall and per-key route isolation");
salts.dependOn(&b.addRunArtifact(b.addTest(.{ .root_module = server_tests, .filters = &.{ "salts:", "salts per key:", "two salts never", "a salted text prompt", "the routes:", "cache salt isolation:" } })).step);
Expand Down
1 change: 1 addition & 0 deletions zig/build/hip.zig
Original file line number Diff line number Diff line change
Expand Up @@ -167,6 +167,7 @@ pub fn steps(b: *std.Build, target: std.Build.ResolvedTarget, optimize: std.buil
native_ocr.dependOn(&b.addRunArtifact(b.addTest(.{ .root_module = host.native, .filters = &.{"GLM-OCR native flags:"} })).step);
native_ocr.dependOn(&b.addRunArtifact(b.addTest(.{ .root_module = host.native.import_table.get("glm_ocr").?, .filters = &.{"GLM-OCR native admission:"} })).step);
b.step("test-hip-family-offers-host", "HIP optional native family metadata without device execution").dependOn(&b.addRunArtifact(b.addTest(.{ .root_module = host.native, .filters = &.{"HIP optional family offers:"} })).step);
b.step("test-hip-logit-bias-host", "Host bias and ban draws without a HIP device").dependOn(&b.addRunArtifact(b.addTest(.{ .root_module = host.serve, .filters = &.{"logit_bias"} })).step);
b.step("test-hip-native-options-host", "Shared HIP native open settings without device execution").dependOn(&b.addRunArtifact(b.addTest(.{ .root_module = host.serve, .filters = &.{"HIP native options:"} })).step);
@import("hip_followers.zig").steps(b, &.{ host.serve, host.flashnext, host.nemotron });
@import("dots_mocr.zig").hipTests(b, host.hip, test_step);
Expand Down
10 changes: 10 additions & 0 deletions zig/kernels/cuda/sample_penalties.cuh
Original file line number Diff line number Diff line change
Expand Up @@ -8,3 +8,13 @@ extern "C" __global__ void __launch_bounds__(256) tf_penalize_rows(__nv_bfloat16
__nv_bfloat16* x = L + static_cast<size_t>(ROW[i]) * V + TOK[i];
*x = __float2bfloat16(__bfloat162float(*x) - SUB[i]);
}

// Bias entries use the same subtraction, with +inf as an unconditional hard ban (including nonfinite input).
extern "C" __global__ void __launch_bounds__(256) tf_bias_rows(__nv_bfloat16* L, unsigned V, const unsigned* ROW,
const unsigned* TOK, const float* SUB, unsigned n) {
const unsigned i = blockIdx.x * blockDim.x + threadIdx.x;
if (i >= n) return;
__nv_bfloat16* x = L + static_cast<size_t>(ROW[i]) * V + TOK[i];
*x = __float2bfloat16(SUB[i] == __int_as_float(0x7f800000) ? -__int_as_float(0x7f800000)
: __bfloat162float(*x) - SUB[i]);
}
5 changes: 5 additions & 0 deletions zig/src/core/contract/logit_bias_records.zig
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
//! The new sparse bias launch needs measured resource receipts before landing.
const registry = @import("registry.zig");
pub const records = [_]registry.CudaRecord{
.{ .launch = .{ .name = "sample tf_bias_rows", .symbol = "tf_bias_rows", .image = "sample", .threads = 256 }, .usage = registry.none },
};
2 changes: 1 addition & 1 deletion zig/src/core/contract/registry_joins.zig
Original file line number Diff line number Diff line change
Expand Up @@ -63,7 +63,7 @@ pub const nvcc_133_after = @import("flashnext_tile_records.zig").cuda_133 ++
@import("experts_bf16_records.zig").cuda_133 ++
@import("int4_records.zig").cuda_133;
pub const cuda_sets_after = [_]registry.CudaSet{.{ .release = .{ .major = 13, .minor = 4 }, .usage = &@import("mhc_cuda_records.zig").cuda_134 }};
pub const cuda_pending = @import("mhc_cuda_records.zig").cuda ++ @import("qwen_whole_records.zig").records ++
pub const cuda_pending = @import("mhc_cuda_records.zig").cuda ++ @import("logit_bias_records.zig").records ++ @import("qwen_whole_records.zig").records ++
@import("qwen_prompt_split_records.zig").records ++
@import("flashnext_tile_records.zig").pending ++
@import("int4_records.zig").records ++
Expand Down
4 changes: 4 additions & 0 deletions zig/src/core/engine_api.zig
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,7 @@ pub const Id = u64;
pub const Sampling = lanes.Sampling;
/// presence_penalty and frequency_penalty, applied where ``Info.penalties``.
pub const Penalties = lanes.Penalties;
pub const LogitBias = lanes.logit_bias.Entry;
pub const EmbeddingInfo = lanes.embedding.Info;
pub const EmbeddingBatch = lanes.embedding.Batch;
pub const embedding_vector = @import("embedding_vector.zig");
Expand Down Expand Up @@ -154,6 +155,7 @@ pub const Info = struct {
logprobs: bool = false,
/// Requests' presence_penalty and frequency_penalty change the draws (false: nonzero is refused).
penalties: bool = false,
logit_bias: bool = false, // sparse request token biases, including hard bans at -100
/// Requests may ask for ``prompt_logprobs`` (a prompt pass from 0 that reads every row).
prompt_logprobs: bool = false,
/// Prompt rows a prefill chunk at most, for the server's chunk starts (0: the engine cuts prompts itself).
Expand Down Expand Up @@ -426,6 +428,8 @@ pub const Engine = struct {
pub fn submit(e: Engine, id: Id, request: *const Request, sink: Sink) SubmitError!void {
try @import("cache_modes.zig").validate(request.decode_spans);
const info_ = e.info();
if (request.logit_bias.len > 0 and (!info_.logit_bias or request.promptOnly())) return error.InvalidRequest;
lanes.logit_bias.check(request.logit_bias) catch return error.InvalidRequest;
if (request.embedding != null and request.readout != null) return error.InvalidRequest;
if (request.readout != null) {
lanes.readout.admit(info_, request) catch return error.InvalidRequest;
Expand Down
1 change: 1 addition & 0 deletions zig/src/core/engine_api_test.zig
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
//! Host behavior checks for the shared engine API.
test {
_ = @import("engine_bias_test.zig");
_ = @import("lane_embedding_test.zig");
_ = @import("lane_readout_test.zig");
_ = @import("speech_guard.zig");
Expand Down
58 changes: 58 additions & 0 deletions zig/src/core/engine_bias_test.zig
Original file line number Diff line number Diff line change
@@ -0,0 +1,58 @@
//! Native submission refuses malformed biases and prompt-only work before calling a backend.
const std = @import("std");
const api = @import("engine_api.zig");

const Spy = struct {
offered: bool = true,
submissions: usize = 0,
fn engine(s: *Spy) api.Engine {
return .{ .ctx = s, .vtable = &.{ .info = info, .submit = submit, .cancel = cancel, .status = status, .memory = memory } };
}
fn info(ctx: *anyopaque) api.Info {
const s: *Spy = @ptrCast(@alignCast(ctx));
return .{ .context_window = 8, .logit_bias = s.offered };
}
fn submit(ctx: *anyopaque, _: api.Id, _: *const api.Request, _: api.Sink) api.SubmitError!void {
const s: *Spy = @ptrCast(@alignCast(ctx));
s.submissions += 1;
}
fn cancel(_: *anyopaque, _: api.Id) void {}
fn status(_: *anyopaque, out: *api.Status, _: []u32) void {
out.* = .{};
}
fn memory(_: *anyopaque, _: bool) ?api.Memory {
return null;
}
fn event(_: *anyopaque, _: api.Id, _: *const api.Event) void {}
};

test "bias admission: malformed native entries and prompt-only requests never reach the backend" {
var spy: Spy = .{};
const engine = spy.engine();
const sink: api.Sink = .{ .ctx = &spy, .event = Spy.event };
var request: api.Request = .{ .prompt = &.{1}, .max_tokens = 1 };
for ([_][]const api.LogitBias{
&.{ .{ .token = 1, .value = 0 }, .{ .token = 1, .value = 2 } },
&.{ .{ .token = 2, .value = 0 }, .{ .token = 1, .value = 2 } },
&.{.{ .token = 1, .value = std.math.nan(f32) }},
&.{.{ .token = 1, .value = 101 }},
}) |entries| {
request.logit_bias = entries;
try std.testing.expectError(error.InvalidRequest, engine.submit(1, &request, sink));
}
request.logit_bias = &.{.{ .token = 1, .value = 2 }};
spy.offered = false;
try std.testing.expectError(error.InvalidRequest, engine.submit(1, &request, sink));
spy.offered = true;
var vector: [1]f32 = undefined;
request.embedding = .{ .ends = &.{1}, .dimensions = 1, .output = &vector };
try std.testing.expectError(error.InvalidRequest, engine.submit(1, &request, sink));
try std.testing.expectEqual(@as(usize, 0), spy.submissions);
request.embedding = null;
try engine.submit(1, &request, sink);
try std.testing.expectEqual(@as(usize, 1), spy.submissions);
spy.offered = false;
request.logit_bias = &.{};
try engine.submit(2, &request, sink);
try std.testing.expectEqual(@as(usize, 2), spy.submissions);
}
1 change: 1 addition & 0 deletions zig/src/core/engine_capabilities.zig
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,7 @@ pub const Capability = enum {
structures,
logprobs,
penalties,
logit_bias,
prompt_logprobs,
prompt_cache,
cache_salt,
Expand Down
1 change: 1 addition & 0 deletions zig/src/core/engine_request.zig
Original file line number Diff line number Diff line change
Expand Up @@ -24,6 +24,7 @@ pub const Request = struct {
max_tokens: u32,
sampling: ?Sampling = null,
penalties: Penalties = .{},
logit_bias: []const lanes.logit_bias.Entry = &.{},
/// Tokens that end the reply as ``stop`` (the token is delivered); empty when the request ignores EOS.
eos: []const u32 = &.{},
stop: ?Stop = null,
Expand Down
20 changes: 19 additions & 1 deletion zig/src/core/lane_host_lone.zig
Original file line number Diff line number Diff line change
Expand Up @@ -16,7 +16,25 @@ fn takes(h: *LaneHost, job: *Job) bool {
const r = job.request;
const lone = h.lone orelse return false;
const think = lone.min_budget > 0 and (r.think_budget == 0 or r.think_budget > lone.min_budget);
return !((r.sampling != null and !lone.sampled) or (!r.drafts and !lone.plain) or ((r.think_budget > 0 or r.loop_guard) and !think) or r.call != null or (r.structure != null and !lone.structures) or r.penalties.active() or (r.images.len > 0 and !lone.images) or r.audios.len > 0 or (r.logprobs != null and !lone.logprobs) or r.prompt_logprobs != null);
return !((r.sampling != null and !lone.sampled) or (!r.drafts and !lone.plain) or ((r.think_budget > 0 or r.loop_guard) and !think) or r.call != null or (r.structure != null and !lone.structures) or r.penalties.active() or r.logit_bias.len > 0 or (r.images.len > 0 and !lone.images) or r.audios.len > 0 or (r.logprobs != null and !lone.logprobs) or r.prompt_logprobs != null);
}

test "logit_bias: a request cannot enter a lone driver that has no bias contract" {
const std = @import("std");
const api = @import("engine_api.zig");
const Driver = struct {
fn run(_: *anyopaque, _: *@import("lanes").Stream, _: api.LoneHooks) anyerror!bool {
return error.UnexpectedLoneRun;
}
};
var h: LaneHost = undefined;
h.lone = .{ .ctx = &h, .run = Driver.run };
var request: api.Request = .{ .prompt = &.{1}, .max_tokens = 1 };
var job: Job = undefined;
job.request = &request;
try std.testing.expect(takes(&h, &job));
request.logit_bias = &.{.{ .token = 1, .value = 0 }};
try std.testing.expect(!takes(&h, &job));
}

/// After a round: the lane core's last live stream goes back to the driver when nothing else waits or is due.
Expand Down
1 change: 1 addition & 0 deletions zig/src/core/lane_stream.zig
Original file line number Diff line number Diff line change
Expand Up @@ -91,6 +91,7 @@ pub fn open(h: *LaneHost, job: *Job) bool {
.eos = r.eos,
.sampling = r.sampling,
.penalties = r.penalties,
.logit_bias = r.logit_bias,
.drafts = r.drafts,
.proposer = job.custom orelse job.proposer.proposer(),
.recall = recall,
Expand Down
1 change: 1 addition & 0 deletions zig/src/core/lanes/backend.zig
Original file line number Diff line number Diff line change
Expand Up @@ -91,6 +91,7 @@ pub const Backend = struct {
keep_full_lone: bool = false,
/// Every draw (first, queue and verify rows) takes `Stream.penalties` from the reply's tokens; wrappers copy it.
penalties: bool = false,
logit_bias: bool = false, // every target draw honours Stream.logit_bias
/// Prompt fill gives the same tokens at any chunk cut, so --decode-share may cap its chunk rows; wrappers copy it.
chunk_invariant: bool = false,
/// Whether image requests may run a background warm prefill; wrappers preserve the target policy.
Expand Down
Loading