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
13 changes: 13 additions & 0 deletions docs/environment.md
Original file line number Diff line number Diff line change
Expand Up @@ -27,6 +27,19 @@ Diagnostics quote and escape the supplied text so it cannot create another termi
| `TF_Q27_COPY_ROWS` | Whole u32 count; zero disables copied rows; default 48 |
| `TF_Q27_DRAFT_SLOTS` | Whole u32 count, clamped to 1 through the lane stream limit; default 8. DFlash2 can draft for at most the smaller of this count and the admitted streams, and none without a drafter. |
| `TF_MTP_DRAFTS` | Whole u32 count, clamped to 1 through the drafter's window less one; existing depth when unset |
| `TF_TIMING` | Exactly `0` or `1`; default off (each call's wall time on stderr while set) |
| `TF_NO_TREES` | Exactly `0` or `1`; default off. `1` keeps the CUDA drafter's chains only, and retains precedence over `TF_DRAFT_NODES` |
| `TF_MTP_TREES` | Exactly `0` or `1`; default off (1 turns the MTP drafter's trees on) |
| `TF_MTP_BATCH` | Exactly `0` or `1`; default on. `0` keeps one stream at a time |
| `TF_QWEN_KEEP_LATE` | Exactly `0` or `1`; default off |
| `TF_QWEN_KV_PAGE_TEST` | Whole page size from 1 to 2147483647; unset off. Each cache's own buffer reads through a table of n-position pages in reverse order (checks) |
| `TF_QWEN_POOL_LOG` | Exactly `0` or `1`; default off (the pool's census after a prompt pass) |
| `TF_COST_KEY_TRACE` | Exactly `0` or `1`; default off (each cost key's parts on stderr) |
| `TF_Q27_POCKET_OFF` | `all`, or a list of `layer:neuron` pairs; default off (pocket diagnostics) |
| `TF_Q27_TAIL` | Exactly `off`; default off — each nudged sequence's tail rows are the backward's rows |
| `TF_Q27_GEMM` | Exactly `narrow`; default the 128x128 tiles |
| `TENSORFOLD_MEMORY_RESERVE_GIB` | A finite GiB amount; the HIP admission's floor (0.5, or 2 on shared memory) and the memory's size still bound it |
| `TENSORFOLD_HIP_MEMORY_LIMIT_GB` | A positive finite GiB amount whose byte count fits a 64-bit size |
| `TF_DSPINE_WINDOW` | Qwen3.8-27B on CUDA with a DSpine `--drafter`: whole row count 16 through 8192 that narrows the drafter's sliding window; it must be at least the block (16) and at most the checkpoint's own `sliding_window`, else the drafter is refused when it opens; unset or blank keeps the checkpoint's (8192 for tencent/Qwen3.8-27B-DSpine-b16) |
| `TF_DRAFT_NODES` | Whole native-size nonnegative count, capped by the drafter's window; zero disables trees |
| `TF_QMMF_HALF_BELOW` | Whole native-size nonnegative block count; zero disables half tiles; default 96 |
Expand Down
5 changes: 1 addition & 4 deletions zig/src/families/qwen3_5/backend/hip/engine/native.zig
Original file line number Diff line number Diff line change
Expand Up @@ -171,10 +171,7 @@ fn prepare(
a,
problem,
"{s}",
.{try hip.admission.badSetting(a, if (err == error.BadReserve) error.BadReserve else error.BadLimit, .{
.reserve = @import("sys").getenv("TENSORFOLD_MEMORY_RESERVE_GIB"),
.limit = @import("sys").getenv("TENSORFOLD_HIP_MEMORY_LIMIT_GB"),
})},
.{try hip.admission.badSetting(a, if (err == error.BadReserve) error.BadReserve else error.BadLimit, hip.admission.envTexts())},
),
error.HostMemoryUnavailable => steps.refuseAll(
a,
Expand Down
23 changes: 18 additions & 5 deletions zig/src/families/qwen3_5/cuda_cache.zig
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@ const std = @import("std");
const cuda = @import("cuda");
const geometry = @import("cuda_geometry.zig");
const engine = @import("cuda_engine.zig");
const platform = @import("sys");

const Engine = engine.Engine;
const DeviceBuffer = cuda.DeviceBuffer;
Expand All @@ -21,7 +22,7 @@ pub fn keepLate() bool {
var on: ?bool = null;
};
if (S.on) |v| return v;
const v = if (std.c.getenv("TF_QWEN_KEEP_LATE")) |x| std.mem.eql(u8, std.mem.span(x), "1") else false;
const v = platform.environment.read(bool, "TF_QWEN_KEEP_LATE", false) catch false;
S.on = v;
return v;
}
Expand Down Expand Up @@ -71,16 +72,20 @@ pub const Paged = struct {

/// TF_QWEN_KV_PAGE_TEST=n: each cache's own buffer read through a table of n-position pages in reverse order (checks).
pub fn pageTest() !usize {
const v = std.c.getenv("TF_QWEN_KV_PAGE_TEST") orelse return 0;
return parsePageTest(std.mem.span(v));
const n = try platform.environment.read(u64, "TF_QWEN_KV_PAGE_TEST", 0);
return if (n == 0) 0 else parsePageTestValue(n);
}

pub fn parsePageTest(v: []const u8) !usize {
const n = std.fmt.parseInt(usize, v, 10) catch return error.BadQwenPageTest;
pub fn parsePageTestValue(n: usize) !usize {
if (!validPageTokens(n)) return error.BadQwenPageTest;
return n;
}

pub fn parsePageTest(v: []const u8) !usize {
const n = std.fmt.parseInt(usize, v, 10) catch return error.BadQwenPageTest;
return parsePageTestValue(n);
}

pub fn validPageTokens(n: usize) bool {
return n > 0 and n <= std.math.maxInt(c_int);
}
Expand Down Expand Up @@ -413,6 +418,14 @@ fn freePaged(gpa: std.mem.Allocator, p: *Paged) void {
if (p.own_ids) gpa.free(p.ids);
}

test "TF_QWEN_KEEP_LATE and TF_QWEN_KV_PAGE_TEST: the platform parses unset, valid and malformed text" {
try std.testing.expectEqual(@as(?u64, null), try platform.environment.parse("TF_QWEN_KEEP_LATE", null));
try std.testing.expectEqual(@as(?u64, 1), try platform.environment.parse("TF_QWEN_KEEP_LATE", "1"));
try std.testing.expectError(error.InvalidEnvironment, platform.environment.parse("TF_QWEN_KEEP_LATE", "on"));
try std.testing.expectEqual(@as(?u64, 512), try platform.environment.parse("TF_QWEN_KV_PAGE_TEST", "512"));
try std.testing.expectError(error.InvalidEnvironment, platform.environment.parse("TF_QWEN_KV_PAGE_TEST", "0"));
}

test "KV page dimensions: diagnostic rows fit the signed kernel argument" {
try std.testing.expectEqual(@as(usize, 48), try parsePageTest("48"));
try std.testing.expectError(error.BadQwenPageTest, parsePageTest("0"));
Expand Down
9 changes: 8 additions & 1 deletion zig/src/families/qwen3_5/cuda_cost_adapter.zig
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@ const E = @import("cuda_engine.zig");
const warm = @import("cuda_warm.zig");
const profile = @import("cuda_startup_profile.zig");
const costs = @import("cuda_window_costs.zig");
const platform = @import("sys");
pub const file_identity = @import("cuda_cost_identity.zig");
pub const Kind = enum { dflash, mtp };

Expand Down Expand Up @@ -38,7 +39,7 @@ pub fn identity(l: anytype, d: anytype, reserved: ?*E.Cache) !costs.Keys {
const checkpoint = std.fmt.bytesToHex(stamp, .lower);
const target_hex = std.fmt.bytesToHex(target, .lower);
const parts = [_][]const u8{ "qwen35-cuda/wall-chain-greedy-v2", gpu, release, geometry, policy, taps, @tagName(l.cost_kind), draft, facts, &checkpoint, &target_hex };
const trace = if (@import("sys").getenv("TF_COST_KEY_TRACE")) |v| std.mem.eql(u8, v, "1") else false;
const trace = try platform.environment.read(bool, "TF_COST_KEY_TRACE", false);
if (trace) {
const names = [_][]const u8{ "profile", "gpu", "driver", "geometry", "policy", "target-taps", "draft-kind", "draft-config", "draft-facts", "draft-checkpoint", "target-checkpoint" };
for (names, parts) |name_, bytes| tracePart(name_, bytes);
Expand Down Expand Up @@ -150,3 +151,9 @@ fn tracePart(name: []const u8, bytes: []const u8) void {
const hex = std.fmt.bytesToHex(digest, .lower);
std.log.info("window cost key part {s} {s}", .{ name, hex[0..12] });
}

test "TF_COST_KEY_TRACE: the platform parses unset, valid and malformed text" {
try std.testing.expectEqual(@as(?u64, null), try platform.environment.parse("TF_COST_KEY_TRACE", null));
try std.testing.expectEqual(@as(?u64, 1), try platform.environment.parse("TF_COST_KEY_TRACE", "1"));
try std.testing.expectError(error.InvalidEnvironment, platform.environment.parse("TF_COST_KEY_TRACE", "on"));
}
12 changes: 9 additions & 3 deletions zig/src/families/qwen3_5/cuda_draft.zig
Original file line number Diff line number Diff line change
Expand Up @@ -172,7 +172,7 @@ pub const Draft = struct {

/// The target's measured window cost, published after the complete reset-cache width sweep.
pub fn setCost(d: *Draft, rows: u32, ms: f64) void {
if (platform.c.getenv("TF_TIMING") != null) std.debug.print("[timing] window {d} rows {d:.2} ms (a hold level {d:.2})\n", .{ rows, ms, d.step_ms });
if (platform.environment.read(bool, "TF_TIMING", false) catch false) std.debug.print("[timing] window {d} rows {d:.2} ms (a hold level {d:.2})\n", .{ rows, ms, d.step_ms });
if (d.n_costs < d.costs.len) {
d.costs[d.n_costs] = .{ .width = rows, .ms = ms };
d.n_costs += 1;
Expand Down Expand Up @@ -440,7 +440,7 @@ pub const Draft = struct {
fn factsFn(p: *anyopaque) dr.Facts {
const d = cast(p);
// TF_NO_TREES=1: chains only (for comparing)
return .{ .fixed_block = d.c.kind == .dflash2, .depth = @intCast(d.c.block - 1), .step_ms = d.step_ms, .prior = &draft_prior.prior, .plain_guard = true, .batched = true, .stream_bytes = d.c.ringBytes() + d.target_taps + d.scratch_one, .trees = platform.c.getenv("TF_NO_TREES") == null, .window_costs = d.costs[0..d.n_costs], .lane_costs = d.costs[0..d.n_costs], .copy_match = factsCopyMatch(d), .tree_nodes = @intCast(if (d.c.block == 16) d.tree_nodes else 0) };
return .{ .fixed_block = d.c.kind == .dflash2, .depth = @intCast(d.c.block - 1), .step_ms = d.step_ms, .prior = &draft_prior.prior, .plain_guard = true, .batched = true, .stream_bytes = d.c.ringBytes() + d.target_taps + d.scratch_one, .trees = !(platform.environment.read(bool, "TF_NO_TREES", false) catch false), .window_costs = d.costs[0..d.n_costs], .lane_costs = d.costs[0..d.n_costs], .copy_match = factsCopyMatch(d), .tree_nodes = @intCast(if (d.c.block == 16) d.tree_nodes else 0) };
}

fn openFn(p: *anyopaque, s: *Stream) anyerror!void {
Expand Down Expand Up @@ -549,7 +549,7 @@ pub fn factsCopyMatch(d: anytype) i64 {

/// TF_TIMING=1: each call's wall time on stderr.
pub fn timing(what: []const u8, io: std.Io, t0: std.Io.Timestamp) void {
if (platform.c.getenv("TF_TIMING") == null) return;
if (!(platform.environment.read(bool, "TF_TIMING", false) catch false)) return;
const now = std.Io.Clock.awake.now(io);
const ns: f64 = @floatFromInt(t0.durationTo(now).toNanoseconds());
const at: f64 = @floatFromInt(@mod(now.toNanoseconds(), 1_000_000_000_000));
Expand Down Expand Up @@ -591,3 +591,9 @@ test "a drafter config with a zero divisor is refused, and any admitted rank's s
const c = try Config.parse(gpa, wide, target);
try std.testing.expect(Draft.stagedLen(c.rank) >= Draft.hp_at + (c.block - 1) * c.rank * 2);
}

test "TF_TIMING: the platform parses unset, valid and malformed text" {
try std.testing.expectEqual(@as(?u64, null), try platform.environment.parse("TF_TIMING", null));
try std.testing.expectEqual(@as(?u64, 1), try platform.environment.parse("TF_TIMING", "1"));
try std.testing.expectError(error.InvalidEnvironment, platform.environment.parse("TF_TIMING", "on"));
}
8 changes: 7 additions & 1 deletion zig/src/families/qwen3_5/cuda_draft_tree.zig
Original file line number Diff line number Diff line change
Expand Up @@ -11,10 +11,16 @@ pub const lanesOf = walker.lanesOf;

/// A grown tree's nodes at most: walker.nodes under the engine's window, 0 under TF_NO_TREES.
pub fn nodes() !usize {
return walker.nodes(engine.most_window, platform.c.getenv("TF_NO_TREES") != null);
return walker.nodes(engine.most_window, try platform.environment.read(bool, "TF_NO_TREES", false));
}

/// walker.grow under the engine's window.
pub fn grow(c: Candidates, pending: u32, rows: usize, most: usize, tokens: []u32, parents: []i32, own: []f64) usize {
return walker.grow(engine.most_window, c, pending, rows, most, tokens, parents, own);
}

test "TF_NO_TREES: the platform parses unset, valid and malformed text" {
try @import("std").testing.expectEqual(@as(?u64, null), try platform.environment.parse("TF_NO_TREES", null));
try @import("std").testing.expectEqual(@as(?u64, 1), try platform.environment.parse("TF_NO_TREES", "1"));
try @import("std").testing.expectError(error.InvalidEnvironment, platform.environment.parse("TF_NO_TREES", "on"));
}
14 changes: 10 additions & 4 deletions zig/src/families/qwen3_5/cuda_mtp.zig
Original file line number Diff line number Diff line change
Expand Up @@ -118,10 +118,10 @@ pub const Mtp = struct {
if (!e.g.moe()) return error.NotRouted;
const d = try gpa.create(Mtp);
errdefer gpa.destroy(d);
d.* = .{ .gpa = gpa, .io = io, .e = e, .w = undefined, .mod = undefined, .dmod = undefined, .fns = undefined, .ring_fns = undefined, .scratch = undefined, .capacity = capacity, .depth = default_depth, .trees = platform.c.getenv("TF_MTP_TREES") != null, .tap = .{@intCast(e.g.layers - 1)}, .taps_in = 0, .hin = 0, .hn = 0, .emb = 0, .en = 0, .h = 0, .r = 0, .x = 0, .qraw = 0, .q = 0, .kraw = 0, .kb = 0, .vb = 0, .att = 0, .xs = 0, .logits = 0, .words = 0, .picks = 0, .lane_state = 0, .lane_k = 0, .lane_v = 0, .anc = 0, .ids = 0, .tok = 0, .staged = undefined, .tab = 0 };
d.* = .{ .gpa = gpa, .io = io, .e = e, .w = undefined, .mod = undefined, .dmod = undefined, .fns = undefined, .ring_fns = undefined, .scratch = undefined, .capacity = capacity, .depth = default_depth, .trees = try platform.environment.read(bool, "TF_MTP_TREES", false), .tap = .{@intCast(e.g.layers - 1)}, .taps_in = 0, .hin = 0, .hn = 0, .emb = 0, .en = 0, .h = 0, .r = 0, .x = 0, .qraw = 0, .q = 0, .kraw = 0, .kb = 0, .vb = 0, .att = 0, .xs = 0, .logits = 0, .words = 0, .picks = 0, .lane_state = 0, .lane_k = 0, .lane_v = 0, .anc = 0, .ids = 0, .tok = 0, .staged = undefined, .tab = 0 };
d.depth = try platform.environment.read(u32, "TF_MTP_DRAFTS", default_depth);
d.depth = @min(@max(d.depth, 1), most_window - 1);
if (platform.c.getenv("TF_MTP_BATCH")) |v| d.batch = !std.mem.eql(u8, std.mem.span(v), "0");
d.batch = try platform.environment.read(bool, "TF_MTP_BATCH", true);
d.mod = try cuda.Module.load(e.d, cuda.kernels.qwen36_mtp);
errdefer d.mod.unload();
d.dmod = try cuda.Module.load(e.d, cuda.kernels.qwen35_draft);
Expand Down Expand Up @@ -160,7 +160,7 @@ pub const Mtp = struct {
}

pub fn setCost(d: *Mtp, rows: u32, ms: f64) void {
if (platform.c.getenv("TF_TIMING") != null) std.debug.print("[timing] window {d} rows {d:.2} ms (a draft level {d:.2})\n", .{ rows, ms, d.step_ms });
if (platform.environment.read(bool, "TF_TIMING", false) catch false) std.debug.print("[timing] window {d} rows {d:.2} ms (a draft level {d:.2})\n", .{ rows, ms, d.step_ms });
if (d.n_costs < d.costs.len) {
d.costs[d.n_costs] = .{ .width = rows, .ms = ms };
d.n_costs += 1;
Expand Down Expand Up @@ -474,7 +474,7 @@ pub const Mtp = struct {
};
}
ctx.held_n = n;
if (platform.c.getenv("TF_TIMING") != null) std.debug.print("[timing] lanes {d} levels {d}\n", .{ n, l.levels() });
if (platform.environment.read(bool, "TF_TIMING", false) catch false) std.debug.print("[timing] lanes {d} levels {d}\n", .{ n, l.levels() });
}

// the Drafter contract
Expand Down Expand Up @@ -562,3 +562,9 @@ pub const Mtp = struct {

/// Acceptance by depth until a stream has its own (the frozen engine's chains kept about three of four).
const prior = [_]f64{ 0.7, 0.55, 0.45, 0.4, 0.35, 0.3, 0.3 };

test "TF_MTP_TREES: the platform parses unset, valid and malformed text" {
try std.testing.expectEqual(@as(?u64, null), try platform.environment.parse("TF_MTP_TREES", null));
try std.testing.expectEqual(@as(?u64, 1), try platform.environment.parse("TF_MTP_TREES", "1"));
try std.testing.expectError(error.InvalidEnvironment, platform.environment.parse("TF_MTP_TREES", "on"));
}
10 changes: 8 additions & 2 deletions zig/src/families/qwen3_5/cuda_pages.zig
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@ const cuda = @import("cuda");
const kv = @import("core").kv_pool;
const engine = @import("cuda_engine.zig");
const caches = @import("cuda_cache.zig");
const platform = @import("sys");

const Engine = engine.Engine;
const Cache = caches.Cache;
Expand Down Expand Up @@ -193,8 +194,7 @@ pub const Pages = struct {

/// TF_QWEN_POOL_LOG=1: the pool's census after a prompt pass (the agent replay's memory readings).
pub fn log(p: *const Pages, prompt: usize, cached: usize) void {
const v = std.c.getenv("TF_QWEN_POOL_LOG") orelse return;
if (!std.mem.eql(u8, std.mem.span(v), "1")) return;
if (!(platform.environment.read(bool, "TF_QWEN_POOL_LOG", false) catch false)) return;
const n = p.pool.census();
std.log.info("qwen3_5 pool after a prompt of {d} (resumed at {d}): {d} pages leased, {d} held by the prompt cache, {d} free of {d}", .{ prompt, cached, n.leased, n.kept, n.free, n.total });
}
Expand Down Expand Up @@ -277,3 +277,9 @@ test "Qwen pages default: TF_QWEN_KV_PAGES_ALL unset keeps the engine's stream a
try std.testing.expect(pagedOnlyOf("1"));
for ([_][]const u8{ "0", "", "true", "01", " 1 " }) |v| try std.testing.expect(!pagedOnlyOf(v));
}

test "TF_QWEN_POOL_LOG: the platform parses unset, valid and malformed text" {
try std.testing.expectEqual(@as(?u64, null), try platform.environment.parse("TF_QWEN_POOL_LOG", null));
try std.testing.expectEqual(@as(?u64, 1), try platform.environment.parse("TF_QWEN_POOL_LOG", "1"));
try std.testing.expectError(error.InvalidEnvironment, platform.environment.parse("TF_QWEN_POOL_LOG", "on"));
}
14 changes: 11 additions & 3 deletions zig/src/families/qwen3_5/cuda_pocket.zig
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@
const std = @import("std");
const cuda = @import("cuda");
const to = @import("cuda_train_ops.zig");
const platform = @import("sys");

/// A layer's neurons on the device: fp32 [cap, hidden] gate rows, up rows and outputs; the first `used` live.
pub const Rows = struct { gate: cuda.DeviceBuffer, up: cuda.DeviceBuffer, down: cuda.DeviceBuffer, cap: usize, used: usize = 0 };
Expand Down Expand Up @@ -117,10 +118,10 @@ pub const Pockets = struct {
var learned: usize = 0;
var off: std.ArrayList([2]usize) = .empty;
defer off.deinit(p.gpa);
if (@import("sys").c.getenv("TF_Q27_POCKET_OFF")) |list| {
const all = std.mem.eql(u8, std.mem.span(list), "all");
if (try platform.environment.path("TF_Q27_POCKET_OFF", platform.environment.Process.get(.{}, "TF_Q27_POCKET_OFF"))) |list| {
const all = std.mem.eql(u8, list, "all");
if (all) for (host, 0..) |slot, l| if (slot) |h| for (0..h.n) |j| try off.append(p.gpa, .{ l, j });
var it = std.mem.tokenizeAny(u8, if (all) "" else std.mem.span(list), ", ");
var it = std.mem.tokenizeAny(u8, if (all) "" else list, ", ");
while (it.next()) |pair| {
const c = std.mem.indexOfScalar(u8, pair, ':') orelse return error.UnexpectedTensor;
try off.append(p.gpa, .{ try std.fmt.parseInt(usize, pair[0..c], 10), try std.fmt.parseInt(usize, pair[c + 1 ..], 10) });
Expand Down Expand Up @@ -209,3 +210,10 @@ fn staged(d: *const cuda.Driver, values: []const f32) !cuda.DeviceBuffer {
try d.check(d.api.cuMemcpyHtoD_v2(out.ptr, host.bytes.ptr, bytes.len), "pocket staged upload");
return out;
}

test "TF_Q27_POCKET_OFF: the platform parses unset, valid and malformed text" {
try std.testing.expectEqual(@as(?u64, null), try platform.environment.parse("TF_Q27_POCKET_OFF", null));
try std.testing.expectEqual(@as(u64, 0), (try platform.environment.parse("TF_Q27_POCKET_OFF", "all")).?);
try std.testing.expectEqual(@as(u64, 0), (try platform.environment.parse("TF_Q27_POCKET_OFF", "1:2")).?);
try std.testing.expectError(error.InvalidEnvironment, platform.environment.parse("TF_Q27_POCKET_OFF", "no\ncontrol"));
}
3 changes: 2 additions & 1 deletion zig/src/families/qwen3_5/cuda_round_timing.zig
Original file line number Diff line number Diff line change
@@ -1,14 +1,15 @@
//! Enabled-only numeric frame receipts join actual CUDA forward buckets to the shared core's accepted paths.
const std = @import("std");
const be = @import("lanes").backend;
const platform = @import("sys");
pub const Shape = @import("cuda_shapes.zig").Shape;
pub const Trace = struct {
const Frame = struct { first: usize, windows: usize, offered: usize, bucket: usize, ms: f64 };
frames: [@import("cuda_round.zig").max_segs]Frame = undefined,
len: usize = 0,

pub fn enabled() bool {
return std.c.getenv("TF_TIMING") != null;
return platform.environment.read(bool, "TF_TIMING", false) catch false;
}

pub fn create(a: std.mem.Allocator, on: bool) !?*Trace {
Expand Down
Loading
Loading