Skip to content
Closed
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: 4 additions & 4 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,10 @@ Each release's page on GitHub has its notes and measurements. See [the 1.0.0 rel

## Unreleased

- Server: opt-in --tool-think-close bounds thinking for required or named tool calls so the call has room in max_tokens; the flag defaults off and keeps smaller thinking budgets (#4157). Thanks to @jayleaton.

- CUDA: Drama 3 loads compact NVFP4 checkpoints as stored, stages held experts in slot order, and masks routing to their original ids (#4144). Thanks to @plotarmordev.

- Docs: the README's build section says that a Linux `zig build native` compiles for the build machine's CPU, and that `-Dcpu=baseline` or `-Dcpu=x86_64_v3` builds a binary for another machine, with thanks to @Nipale-ai (#3179; #3301).

- Spark 2.5 on CUDA: gate and up load as one stacked weight and decode in one launch on every CUDA chip instead of two launches, with the bits unchanged; only 4-bit checkpoints take this path (#3130).
Expand All @@ -16,10 +20,6 @@ Each release's page on GitHub has its notes and measurements. See [the 1.0.0 rel

- CI: the Zig format and TensorFold Web workflows cancel a pull request's older run when it gets a newer push, so superseded runs no longer queue; main pushes all run (#3850).





- Server: chat and legacy completions requests take `deadline_s` (seconds, more than 0 and at most 1,000,000; any other value is refused before the engine): at that time the server cancels the engine itself and the reply ends with `finish_reason: "deadline"`, keeping every token the engine gave and its usage; a reply the engine ended first, or a cancel that came first, keeps its own ending, and without the field nothing changes (#3438). Thanks to @jayleaton.

- Tests: the CUDA kernel contract's NVFP4_NZ5 stress fill holds +5s among its 4s and 6s, its float64 reference reads code 0b1000 as 5, and a second planted control goes red at the sums gate, so that gate covers the +5 code; no kernel changes (#3543, refs #2894). Thanks to @Bizuayeu.
Expand Down
4 changes: 4 additions & 0 deletions docs/api.md
Original file line number Diff line number Diff line change
Expand Up @@ -807,6 +807,10 @@ Qwen XML and JSON call templates keep their envelopes. Gemma 4 uses
uses the canonical `<tool_call>{"name":"NAME","arguments":{...}}</tool_call>` form. The native grammar limits
whitespace between calls; `parallel_tool_calls: false` allows exactly one. With thinking enabled, the constraint
starts after the think-end token. A reply cut short by `max_tokens` can remain incomplete and ends as `length`.
With `--tool-think-close` (off by default), a required or named call on an engine that takes `thinking_budget` gets a
think budget of `max_tokens - max(256, max_tokens / 4)`, or the request's own `thinking_budget` when that is smaller,
so the think block closes with room left for the call instead of ending as `length`. It changes the reply of any such
call whose thinking would have run past that point. `"auto"`, `"none"` and requests without tools are unchanged.
Drafting stays enabled and uses the same grammar masks as plain decoding.

This requires the loaded backend's structured-output capability and `libtfgrammar`. Nemotron, Qwen3.5-2B,
Expand Down
1 change: 1 addition & 0 deletions docs/run-guide.md
Original file line number Diff line number Diff line change
Expand Up @@ -123,6 +123,7 @@ The binary's `capabilities --json` response lists its supported flags and platfo
| `--thinking-budget N` | Limit reasoning tokens where the engine supports closing the reasoning block. |
| `--thinking-reserve N` | With thinking on, let reasoning use up to N tokens beyond a request's `max_tokens`, which then limits the answer (lane engines). |
| `--loop-guard` | Close reasoning that repeats itself verbatim (a short cycle, or a long passage) where the engine supports it. |
| `--tool-think-close` | With thinking on, a required or named tool call closes its think block at `max_tokens - max(256, max_tokens / 4)` (or a smaller request `thinking_budget`), so the call fits instead of ending as `length`. Off by default ([API](api.md)). |
| `--loop-guard-stop` | As `--loop-guard`, but end the reply where the guard fires: the reasoning so far, no answer or tool calls, `finish_reason` `content_filter` and a `reasoning_loop` error ([API](api.md)). |
| `--no-drafts` | Produce the plain reference through the same engine. |
| `--drafter DRAFTER` | An external drafter, as a directory or a repo id in the Hugging Face cache, for models that take one (Gemma 4 31B's recipe names its drafter); `none` serves without one. Without the flag, Qwen3.8-27B pairs DFlash2 when the cache holds it (never downloaded, not on HIP): one line names it, and serve runs without it if it does not open. |
Expand Down
52 changes: 52 additions & 0 deletions tools/zig/drama3_compact_gb10.sh
Original file line number Diff line number Diff line change
@@ -0,0 +1,52 @@
#!/bin/sh
# Drama 3 compact NVFP4 on one GB10, the checks host tests cannot make; RECEIPT.txt and every log go to RECEIPT_DIR.
set -eu
[ "$#" -eq 6 ] || { echo 'usage: drama3_compact_gb10.sh PRE_FEATURE_COMMIT FP8_MODEL COMPACT_MODEL CODEC NVCC RECEIPT_DIR' >&2; exit 2; }
base=$1 fp8=$2 compact=$3 codec=$4 nvcc=$5 out=$6
root=$(CDPATH= cd -- "$(dirname -- "$0")/../.." && pwd)
# the FP8 comparison needs a tree without the feature: once merged, merge-base with main is HEAD itself
if git -C "$root" grep -q d3_router_compact "$base" -- zig/kernels/cuda; then echo "$base already has d3_router_compact" >&2; exit 2; fi
mkdir -p "$out"
out=$(CDPATH= cd -- "$out" && pwd)
main_tree=$(mktemp -d "${TMPDIR:-/tmp}/drama3-main.XXXXXX")
trap 'git -C "$root" worktree remove --force "$main_tree"' EXIT
git -C "$root" worktree add --detach "$main_tree" "$base" >/dev/null
for tree in "$root" "$main_tree"; do
(cd "$tree" && zig build drama3-generate -Dsm=121 -Dnvcc="$nvcc" -Doptimize=ReleaseFast)
done
(cd "$root" && zig build install fatbins kernel-contract-fatbins -Dsm=80,86,89,120,121 -Dnvcc="$nvcc" -Doptimize=ReleaseFast)
text='The quick brown fox jumps over the lazy dog.'
run() { # TREE MODEL NAME [ARGS...]: greedy codes into NAME.codes, stderr into NAME.log
bin=$1/zig-out/bin/drama3-generate model=$2 name=$3
shift 3
"$bin" --model "$model" --text "$text" --greedy --max-frames 200 --out "$out/$name.codes" "$@" 2>"$out/$name.log"
tail -n 1 "$out/$name.log" | grep -q '^RESULT drama3 OK'
}
run "$main_tree" "$fp8" fp8-main
run "$root" "$fp8" fp8-head
cmp "$out/fp8-main.codes" "$out/fp8-head.codes"
run "$root" "$compact" compact --codec "$codec" --replay 1
# a pruned checkpoint compacts only the layers that dropped experts: NVFP4 in all 40 and at least one compact router
grep -q 'routed experts NVFP4 in 40 of 40 layers; compact routers in [1-9][0-9]* of 40 layers' "$out/compact.log"
# batched prefill is gated within its own capacity: cross-capacity frames may differ near a tie (docs/drama3-prefill.md)
run "$root" "$compact" compact-batched --codec "$codec" --max-rows 64 --replay 1
cmp -s "$out/compact.codes" "$out/compact-batched.codes" && capacity=equal || capacity=differ
# gates 1-4 and the unmasked control; the word matches no limits record, so the pending one waits for the audit below
"$root/zig-out/bin/tf-cuda-test" kernel-contract 'compact router' >"$out/contract.log" 2>&1
status=0
"$root/zig-out/bin/tf-cuda-test" kernel-contract-limits "$root/zig-out/fatbin" >"$out/limits.log" 2>&1 || status=$?
"$root/tools/zig/drama3_limits_gate.sh" "$status" "$out/limits.log"
{
echo "head $(git -C "$root" rev-parse HEAD) pre-feature $base"
nvidia-smi --query-gpu=name,driver_version --format=csv,noheader
"$nvcc" --version | tail -n 1
for f in "$fp8" "$compact" "$codec"; do echo "input $f: $(find "$f" -name '*.safetensors' -o -name '*.pth' | sort | xargs cat | sha256sum | cut -d' ' -f1)"; done
echo "PASS fp8 greedy codes byte-identical to $base: $(sha256sum "$out/fp8-head.codes" | cut -d' ' -f1)"
echo "PASS compact $(grep -o 'routed experts held.*' "$out/compact.log")"
echo "PASS compact decode and replay: $(tail -n 1 "$out/compact.log")"
echo "PASS compact batched prefill (64 rows) decode and replay: $(tail -n 1 "$out/compact-batched.log")"
echo "INFO compact codes at 1 and 64 prompt rows $capacity"
grep '^(filtered) SUMMARY' "$out/contract.log"
grep '^RECORD drama3 d3_router_compact:' "$out/limits.log"
} >"$out/RECEIPT.txt"
cat "$out/RECEIPT.txt"
7 changes: 7 additions & 0 deletions tools/zig/drama3_limits_gate.sh
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
#!/bin/sh
# drama3_limits_gate.sh STATUS LOG: fails unless d3_router_compact was audited on all five SMs; stale records pass.
status=$1 log=$2
grep -Eq '^(FAIL|MISSED) limits' "$log" && exit 1
[ "$(grep -c '^PASS limits sm_[0-9]* drama3 d3_router_compact: ' "$log")" -eq 5 ] || exit 1
[ "$status" -eq 0 ] && exit 0
grep -qx "FAIL kernel-contract-limits: $(grep -c '^PASS limits .*(record stale)$' "$log") problems" "$log"
73 changes: 73 additions & 0 deletions tools/zig/drama3_limits_gate_test.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,73 @@
"""drama3_limits_gate.sh: stale records pass; a failed launch, missing image or unaudited router fails."""
import re
import subprocess
import tempfile
import unittest
from pathlib import Path

ROOT = Path(__file__).resolve().parents[2]
GATE = ROOT / "tools/zig/drama3_limits_gate.sh"
# a GB10 audit of the real registry (nvcc 13.0): 877 stale records, no failed launch or missed control
REAL = (ROOT / "docs/receipts/glm-fp4local-80517fc3/head-797dd2e1/single/limits.log").read_text().splitlines()
SMS = (80, 86, 89, 120, 121)
STALE = "PASS limits sm_{sm} {name}: 30 registers, 0 static shared bytes, bound 128 (record stale)"
ROUTER = "drama3 d3_router_compact"


def pending_tile_launches() -> list[str]:
"""The K32 tile launches the registry holds unmeasured, stale under every nvcc."""
source = (ROOT / "zig/src/core/contract/nvfp4_tile_pending.zig").read_text()
return re.findall(r'\.name = "([^"]+)"', source)


def audit(*names: str, extra: tuple[str, ...] = ()) -> list[str]:
"""The real log plus each name's stale record on every SM, its problem count raised to match."""
log = [line for line in REAL if not line.startswith("FAIL kernel-contract-limits")]
log += [STALE.format(sm=sm, name=name) for name in names for sm in SMS] + list(extra)
stale = sum(line.startswith("PASS limits") and line.endswith("(record stale)") for line in log)
return log + [f"FAIL kernel-contract-limits: {stale} problems"]


def gate(status: int, lines: list[str]) -> int:
with tempfile.NamedTemporaryFile("w", suffix=".log") as log:
log.write("\n".join(lines) + "\n")
log.flush()
return subprocess.run(["sh", str(GATE), str(status), log.name]).returncode


class LimitsGateTests(unittest.TestCase):
def test_clean_audit_passes(self):
lines = [STALE.format(sm=sm, name=ROUTER).replace("stale", "current") for sm in SMS]
self.assertEqual(gate(0, lines + ["PASS kernel-contract-limits: every registered launch fits"]), 0)

def test_real_registry_with_pending_records_passes(self):
tiles = pending_tile_launches()
self.assertEqual(len(tiles), 2)
self.assertEqual(gate(1, audit(ROUTER, *tiles)), 0)

def test_router_not_audited_fails(self):
self.assertNotEqual(gate(1, audit(*pending_tile_launches())), 0)

def test_failed_launch_fails(self):
failed = "FAIL limits sm_121 nvfp4_experts_tile tf_nvfp4_tile_swiglu: 300 registers, 0 static shared bytes, bound 128 (record stale): too many registers"
self.assertNotEqual(gate(1, audit(ROUTER, extra=(failed,))), 0)

def test_missing_image_fails(self):
missing = "FAIL limits drama3 d3_rmsnorm: zig-out/fatbin/drama3.fatbin holds no sm_89 image (build with -Dsm=80,86,89,120,121)"
self.assertNotEqual(gate(1, audit(ROUTER, extra=(missing,))), 0)

def test_missed_control_fails(self):
missed = "MISSED limits sm_121 control: past its bounds: 10 registers, 0 static shared bytes, bound 256 (record current)"
self.assertNotEqual(gate(1, audit(ROUTER, extra=(missed,))), 0)

def test_problem_count_beyond_stale_records_fails(self):
lines = audit(ROUTER)
lines[-1] = lines[-1].replace(" problems", "1 problems")
self.assertNotEqual(gate(1, lines), 0)

def test_error_without_summary_fails(self):
self.assertNotEqual(gate(1, audit(ROUTER)[:-1]), 0)


if __name__ == "__main__":
unittest.main()
55 changes: 55 additions & 0 deletions zig/kernels/cuda/drama3_moe.cuh
Original file line number Diff line number Diff line change
Expand Up @@ -56,6 +56,61 @@ extern "C" __global__ void d3_router(const bf16* __restrict__ sp, int ss, int r_
}
}

// d3_router over held ids only (slots[e] >= 0), picks as slots; a poisoned sum gives NaN weights, never a dropped id.
extern "C" __global__ void d3_router_compact(const bf16* __restrict__ sp, int ss, int r_off, int* __restrict__ picks,
float* __restrict__ weights, const int* __restrict__ slots) {
const int t = blockIdx.x, e = threadIdx.x; // 256 threads
const bool kept = slots[e] >= 0;
const float lg = kept ? b2f(sp[(size_t)t * ss + r_off + e]) : -INFINITY;
const float m = block_max(lg);
const float p = expf(lg - m);
const float sum = block_sum(p);
const bool poisoned = !isfinite(sum) || sum <= 0.f;
__shared__ float best_v[8];
__shared__ int best_i[8];
__shared__ float wv[32];
__shared__ int wi[32];
float mine = kept ? (poisoned ? 0.f : p / sum) : -1.f;
for (int k = 0; k < 8; ++k) {
float v = mine;
int idx = e;
#pragma unroll
for (int o = 16; o > 0; o >>= 1) {
const float ov = __shfl_xor_sync(FULL, v, o);
const int oi = __shfl_xor_sync(FULL, idx, o);
if (ov > v || (ov == v && oi < idx)) {
v = ov;
idx = oi;
}
}
if ((e & 31) == 0) {
wv[e >> 5] = v;
wi[e >> 5] = idx;
}
__syncthreads();
if (e == 0) {
float bv = wv[0];
int bi = wi[0];
for (int j = 1; j < 8; ++j)
if (wv[j] > bv || (wv[j] == bv && wi[j] < bi)) {
bv = wv[j];
bi = wi[j];
}
best_v[k] = bv;
best_i[k] = bi;
}
__syncthreads();
if (e == best_i[k]) mine = -1.f;
__syncthreads();
}
if (e < 8) {
float s = 0.f;
for (int j = 0; j < 8; ++j) s += best_v[j];
picks[t * 8 + e] = slots[best_i[e]];
weights[t * 8 + e] = poisoned ? NAN : best_v[e] / s;
}
}

// y [T, N] = bf16(bf16(silu(g)) * u) with g, u at offsets of rows `stride` apart.
extern "C" __global__ void d3_swiglu(const bf16* __restrict__ x, int stride, int g_off, int u_off, int N,
bf16* __restrict__ y) {
Expand Down
3 changes: 2 additions & 1 deletion zig/src/core/contract/registry_joins.zig
Original file line number Diff line number Diff line change
Expand Up @@ -53,7 +53,8 @@ pub const cuda_pending = @import("qwen_whole_records.zig").records ++
@import("cuda_lane_pending.zig").records ++
@import("weight_only_records.zig").cuda ++
@import("hc_activation_records.zig").cuda ++
@import("qwen4_records.zig").cuda;
@import("qwen4_records.zig").cuda ++
@import("registry_media.zig").cuda_pending;
pub const metal_before = @import("fsr_records.zig").metal ++
@import("scale_index_records.zig").metal ++
@import("lfm3_records.zig").metal;
Expand Down
4 changes: 4 additions & 0 deletions zig/src/core/contract/registry_media.zig
Original file line number Diff line number Diff line change
Expand Up @@ -62,3 +62,7 @@ pub const cuda = [_]CudaRecord{
.{ .launch = .{ .name = "fp8_experts prompt down f32", .symbol = "_ZN14tf_fp8_experts24fp8_expert_prompt_kernelILi1ELi0ELi4ELi4EEEvPK13__nv_bfloat16iiPK5uint4PKfiiPKiSA_SA_Pvifi", .image = "fp8_experts", .threads = 128 }, .usage = .{ .{ .regs = 197, .static = 32768, .bound = 128 }, .{ .regs = 197, .static = 32768, .bound = 128 }, .{ .regs = 197, .static = 32768, .bound = 128 }, .{ .regs = 221, .static = 32768, .bound = 128 }, .{ .regs = 221, .static = 32768, .bound = 128 } } },
.{ .launch = .{ .name = "fp8_experts prompt down bf16", .symbol = "_ZN14tf_fp8_experts24fp8_expert_prompt_kernelILi1ELi3ELi4ELi4EEEvPK13__nv_bfloat16iiPK5uint4PKfiiPKiSA_SA_Pvifi", .image = "fp8_experts", .threads = 128 }, .usage = .{ .{ .regs = 197, .static = 32768, .bound = 128 }, .{ .regs = 197, .static = 32768, .bound = 128 }, .{ .regs = 197, .static = 32768, .bound = 128 }, .{ .regs = 221, .static = 32768, .bound = 128 }, .{ .regs = 221, .static = 32768, .bound = 128 } } },
};
/// Drama 3's compact-checkpoint router, unmeasured: the GB10 check runs its contract and prints its RECORD.
pub const cuda_pending = [_]CudaRecord{
.{ .launch = .{ .name = "drama3 d3_router_compact", .symbol = "d3_router_compact", .image = "drama3", .threads = 256 }, .usage = @import("registry.zig").none },
};
1 change: 1 addition & 0 deletions zig/src/families/drama3/cuda/engine.zig
Original file line number Diff line number Diff line change
Expand Up @@ -142,6 +142,7 @@ pub const Engine = struct {
e.w.deinit();
gpa.destroy(e.w);
}
if (e.w.nvfp4_layers > 0) try e.k.loadNvfp4();
errdefer e.freeState();
try e.allocState();
errdefer {
Expand Down
22 changes: 15 additions & 7 deletions zig/src/families/drama3/cuda/forward.zig
Original file line number Diff line number Diff line change
Expand Up @@ -82,24 +82,32 @@ pub fn backboneLayer(e: *Engine, ln: Lane, li: usize, t: usize, start: usize) !v
try moe(e, s, L, t);
}

/// The MoE block: router, gated shared expert and the routed FP8 experts, added to the residual stream.
/// The MoE block: router (held experts only when compact), gated shared expert and routed FP8 or NVFP4 experts.
fn moe(e: *Engine, s: cuda.Stream, L: *const wts.Layer, t: usize) !void {
const k = &e.k;
const mp = cfg.moe_proj;
try k.linear(s, L.moe_in, e.xn, H, H, mp, e.sp, mp, t);
try k.router(s, e.sp, mp, 2 * cfg.shared_width, e.picks, e.rw, t);
if (L.slots != 0) {
try k.routerCompact(s, e.sp, mp, 2 * cfg.shared_width, e.picks, e.rw, L.slots, t);
} else {
try k.router(s, e.sp, mp, 2 * cfg.shared_width, e.picks, e.rw, t);
}
try k.swiglu(s, e.sp, mp, 0, cfg.shared_width, cfg.shared_width, e.sact, t);
try k.linear(s, L.shared_down, e.sact, cfg.shared_width, cfg.shared_width, H, e.shout, H, t);
const pairs = t * cfg.top_k;
const prompt = t > 2;
const tile: usize = if (prompt) cuda.experts.promptTile(.fp8g) else 16;
try k.plan.route(s, e.picks, pairs, cfg.experts, tile, e.plan);
const items = cuda.grouped.maxItems(pairs, cfg.experts, tile);
// activations to FP8 per row and 128 inputs before each expert projection, as the reference serves them
try k.actQuant(s, e.xn, H, e.xq, H, e.xsc, t, H);
try k.experts(s, true, prompt, e.xq, H, cfg.top_k, e.xsc, L.experts, e.plan, e.gu, items);
try k.actQuant(s, e.gu, cfg.expert_width, e.gq, cfg.expert_width, e.gsc, pairs, cfg.expert_width);
try k.experts(s, false, prompt, e.gq, cfg.expert_width, 0, e.gsc, L.experts, e.plan, e.down, items);
if (L.experts.format == .nvfp4) {
try k.nvfp4Experts(s, prompt, e.xn, cfg.top_k, L.experts, e.plan, e.gu, e.down, items);
} else {
// activations to FP8 per row and 128 inputs before each expert projection, as the reference serves them
try k.actQuant(s, e.xn, H, e.xq, H, e.xsc, t, H);
try k.experts(s, true, prompt, e.xq, H, cfg.top_k, e.xsc, L.experts, e.plan, e.gu, items);
try k.actQuant(s, e.gu, cfg.expert_width, e.gq, cfg.expert_width, e.gsc, pairs, cfg.expert_width);
try k.experts(s, false, prompt, e.gq, cfg.expert_width, 0, e.gsc, L.experts, e.plan, e.down, items);
}
try k.moeCombine(s, e.x, e.down, e.rw, e.shout, e.sp, mp, 2 * cfg.shared_width + cfg.experts, H, t);
}

Expand Down
Loading
Loading