diff --git a/docs/environment.md b/docs/environment.md index bf11b83c5f3..b905c2fea03 100644 --- a/docs/environment.md +++ b/docs/environment.md @@ -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 | diff --git a/zig/src/families/qwen3_5/backend/hip/engine/native.zig b/zig/src/families/qwen3_5/backend/hip/engine/native.zig index 9b3467cfd59..d9d1d32f8fc 100644 --- a/zig/src/families/qwen3_5/backend/hip/engine/native.zig +++ b/zig/src/families/qwen3_5/backend/hip/engine/native.zig @@ -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, diff --git a/zig/src/families/qwen3_5/cuda_cache.zig b/zig/src/families/qwen3_5/cuda_cache.zig index 7c3c98e1762..1675ac8aa5e 100644 --- a/zig/src/families/qwen3_5/cuda_cache.zig +++ b/zig/src/families/qwen3_5/cuda_cache.zig @@ -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; @@ -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; } @@ -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); } @@ -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")); diff --git a/zig/src/families/qwen3_5/cuda_cost_adapter.zig b/zig/src/families/qwen3_5/cuda_cost_adapter.zig index e2f1796d4a7..11b766fb1a6 100644 --- a/zig/src/families/qwen3_5/cuda_cost_adapter.zig +++ b/zig/src/families/qwen3_5/cuda_cost_adapter.zig @@ -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 }; @@ -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); @@ -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")); +} diff --git a/zig/src/families/qwen3_5/cuda_draft.zig b/zig/src/families/qwen3_5/cuda_draft.zig index 5c9d057ab8d..b7f77b8a4f4 100644 --- a/zig/src/families/qwen3_5/cuda_draft.zig +++ b/zig/src/families/qwen3_5/cuda_draft.zig @@ -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; @@ -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 { @@ -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)); @@ -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")); +} diff --git a/zig/src/families/qwen3_5/cuda_draft_tree.zig b/zig/src/families/qwen3_5/cuda_draft_tree.zig index 0475cca0ae5..e5897d2c221 100644 --- a/zig/src/families/qwen3_5/cuda_draft_tree.zig +++ b/zig/src/families/qwen3_5/cuda_draft_tree.zig @@ -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")); +} diff --git a/zig/src/families/qwen3_5/cuda_mtp.zig b/zig/src/families/qwen3_5/cuda_mtp.zig index 7be3a015faa..6aa5907b493 100644 --- a/zig/src/families/qwen3_5/cuda_mtp.zig +++ b/zig/src/families/qwen3_5/cuda_mtp.zig @@ -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); @@ -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; @@ -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 @@ -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")); +} diff --git a/zig/src/families/qwen3_5/cuda_pages.zig b/zig/src/families/qwen3_5/cuda_pages.zig index cc50afddd88..100ccd0557c 100644 --- a/zig/src/families/qwen3_5/cuda_pages.zig +++ b/zig/src/families/qwen3_5/cuda_pages.zig @@ -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; @@ -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 }); } @@ -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")); +} diff --git a/zig/src/families/qwen3_5/cuda_pocket.zig b/zig/src/families/qwen3_5/cuda_pocket.zig index e52074f4f71..5fc87cc2515 100644 --- a/zig/src/families/qwen3_5/cuda_pocket.zig +++ b/zig/src/families/qwen3_5/cuda_pocket.zig @@ -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 }; @@ -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) }); @@ -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")); +} diff --git a/zig/src/families/qwen3_5/cuda_round_timing.zig b/zig/src/families/qwen3_5/cuda_round_timing.zig index 05fe0226236..8354515bdc9 100644 --- a/zig/src/families/qwen3_5/cuda_round_timing.zig +++ b/zig/src/families/qwen3_5/cuda_round_timing.zig @@ -1,6 +1,7 @@ //! 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 }; @@ -8,7 +9,7 @@ pub const Trace = struct { 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 { diff --git a/zig/src/families/qwen3_5/cuda_train.zig b/zig/src/families/qwen3_5/cuda_train.zig index 8844e195865..66efea9e84c 100644 --- a/zig/src/families/qwen3_5/cuda_train.zig +++ b/zig/src/families/qwen3_5/cuda_train.zig @@ -1,5 +1,6 @@ //! The 27B's Living Weights trainer: packed passes through Forward.chunks and the loss back to the lowest nudged layer. const std = @import("std"); +const platform = @import("sys"); const cuda = @import("cuda"); const core = @import("core"); const living = @import("living"); @@ -247,7 +248,7 @@ pub const Trainer = struct { /// The rows the backward still needs, each nudged sequence's from its first nudged row on (null: every row). fn tailRows(t: *Trainer, rows: usize) ?to.Tail { if (!t.k.wide) return null; - if (@import("sys").c.getenv("TF_Q27_TAIL")) |v| if (std.mem.eql(u8, std.mem.span(v), "off")) return null; + if ((platform.environment.read(u64, "TF_Q27_TAIL", 1) catch 1) == 0) return null; const list = t.tails.slice(i32, pack_rows); const mask = t.tails.host.bytes[pack_rows * 4 ..][0..pack_rows]; @memset(mask[0..rows], 0); @@ -564,3 +565,9 @@ test "Save recovery: dense constructor pending work drains or exits before any o if (!cuda.kernels.available) return error.SkipZigTest; try @import("cuda_train_init_test.zig").pendingFailure(Trainer.initWithWeights); } + +test "TF_Q27_TAIL: the platform parses unset, valid and malformed text" { + try std.testing.expectEqual(@as(?u64, null), try platform.environment.parse("TF_Q27_TAIL", null)); + try std.testing.expectEqual(@as(?u64, 0), try platform.environment.parse("TF_Q27_TAIL", "off")); + try std.testing.expectError(error.InvalidEnvironment, platform.environment.parse("TF_Q27_TAIL", "on")); +} diff --git a/zig/src/families/qwen3_5/cuda_train_ops.zig b/zig/src/families/qwen3_5/cuda_train_ops.zig index 1dc9d43ec9b..f56479d35d9 100644 --- a/zig/src/families/qwen3_5/cuda_train_ops.zig +++ b/zig/src/families/qwen3_5/cuda_train_ops.zig @@ -1,6 +1,7 @@ //! The 27B's input gradients for Living Weights as calls on one stream. const std = @import("std"); const cuda = @import("cuda"); +const platform = @import("sys"); /// A 4-bit matrix [n, k] in MLX's layout: words [n, k / 8], bf16 scales and biases [n, k / group]. pub const Q4 = struct { w: u64, s: u64, b: u64, n: usize, k: usize, group: usize = 64 }; @@ -51,7 +52,7 @@ pub const Kernels = struct { pub fn load(d: *const cuda.Driver) !Kernels { if (!cuda.kernels.available) return error.BuiltWithoutKernels; - const narrow = if (@import("sys").c.getenv("TF_Q27_GEMM")) |v| std.mem.eql(u8, std.mem.span(v), "narrow") else false; + const narrow = (try platform.environment.read(?u64, "TF_Q27_GEMM", null)) != null; var k: Kernels = .{ .own = try cuda.Module.load(d, cuda.kernels.qwen27_train), .attn = undefined, .train = undefined, .fo = undefined, .fa = undefined, .ft = undefined, .wide = !narrow }; errdefer k.own.unload(); k.attn = try cuda.Module.load(d, cuda.kernels.attn_train); @@ -418,3 +419,11 @@ test "splits stay within the K rows and fill small products" { try std.testing.expect(splitsFor(16, 5120, 248320) > 1); try std.testing.expectEqual(@as(usize, 1), splitsFor(16, 5120, 512)); } + +test "TF_Q27_GEMM: the platform parses unset, valid and malformed text" { + try std.testing.expectEqual(@as(?u64, null), try platform.environment.parse("TF_Q27_GEMM", null)); + try std.testing.expectEqual(@as(?u64, 0), try platform.environment.parse("TF_Q27_GEMM", "narrow")); + try std.testing.expectEqual(@as(?u64, null), try platform.environment.value(?u64, "TF_Q27_GEMM", null, null)); + try std.testing.expect((try platform.environment.value(?u64, "TF_Q27_GEMM", "narrow", null)) != null); + try std.testing.expectError(error.InvalidEnvironment, platform.environment.parse("TF_Q27_GEMM", "wide")); +} diff --git a/zig/src/hip/admission.zig b/zig/src/hip/admission.zig index e3a0946d4bb..dd612d46e85 100644 --- a/zig/src/hip/admission.zig +++ b/zig/src/hip/admission.zig @@ -55,10 +55,7 @@ pub fn budget(gpa: Allocator, io: std.Io, ctx: Context) !Pool { const integrated = (try ctx.attribute(.integrated)) != 0; const card = try ctx.memInfo(); const own: MemInfo = .{ .total = card.total, .available = card.free }; - const env: Env = .{ - .reserve = getenv("TENSORFOLD_MEMORY_RESERVE_GIB"), - .limit = getenv("TENSORFOLD_HIP_MEMORY_LIMIT_GB"), - }; + const env = envTexts(); if (windows) { // WDDM reports the whole budget through the driver: no host text, no dedicated-VRAM file. const p = try plan(false, own, null, null, env); @@ -79,6 +76,12 @@ pub const Source = enum { card, carve_out, host }; /// The reserve and cap variables' text, unset as null. pub const Env = struct { reserve: ?[]const u8 = null, limit: ?[]const u8 = null }; +/// The two settings' texts, registered in platform/environment.zig; `plan` refuses them against the runtime bounds. +pub fn envTexts() Env { + const e = @import("sys").environment; + return .{ .reserve = e.rawText("TENSORFOLD_MEMORY_RESERVE_GIB"), .limit = e.rawText("TENSORFOLD_HIP_MEMORY_LIMIT_GB") }; +} + pub const Plan = struct { pool: Pool, source: Source }; pub const PlanError = error{ HostMemoryUnavailable, BadReserve, BadLimit }; @@ -173,10 +176,6 @@ fn announce(p: Plan) void { std.log.info("HIP memory budget from {s}: {d:.1} of {d:.1} GiB free, {d:.1} GiB reserve", .{ what, f, t, r }); } -fn getenv(name: [:0]const u8) ?[]const u8 { - return std.mem.span(std.c.getenv(name) orelse return null); -} - /// A /proc file's text, streamed: procfs reports size 0, and a positional read (readFileAlloc) stops there. pub fn procText(a: Allocator, io: std.Io, path: []const u8) ?[]u8 { var file = std.Io.Dir.cwd().openFile(io, path, .{}) catch return null; @@ -253,3 +252,12 @@ test "a carve-out needs the card's total to be the dedicated VRAM: not past it, const shared = plan(true, .{ .total = 60 * g, .available = 59 * g }, big, g / 2, .{ .reserve = "1" }); try std.testing.expectError(error.BadReserve, shared); // shared memory keeps its floor of 2 } + +test "HIP memory settings: the platform parses unset, valid and malformed text" { + const e = @import("sys").environment; + for ([_][:0]const u8{ "TENSORFOLD_MEMORY_RESERVE_GIB", "TENSORFOLD_HIP_MEMORY_LIMIT_GB" }) |name| { + try std.testing.expectEqual(@as(f64, 7), try e.value(f64, name, null, 7)); + try std.testing.expectEqual(@as(f64, 2.5), try e.value(f64, name, "2.5", 7)); + try std.testing.expectError(error.InvalidEnvironment, e.check(name, "none")); + } +} diff --git a/zig/src/platform/environment.zig b/zig/src/platform/environment.zig index e997400ad92..aadc2fbd99b 100644 --- a/zig/src/platform/environment.zig +++ b/zig/src/platform/environment.zig @@ -54,6 +54,20 @@ pub const rules = [_]Rule{ .{ .name = "TF_DSPINE_WINDOW", .scope = .cuda, .kind = .size, .min = 16, .max = 8192, .forms = "a whole row count from 16 to 8192, at most the DSpine drafter's own sliding_window" }, .{ .name = "TF_DRAFT_NODES", .scope = .cuda, .kind = .size, .forms = "a whole nonnegative native-size node count (capped by the drafter's window)" }, .{ .name = "TF_QMMF_HALF_BELOW", .scope = .cuda, .kind = .size, .forms = "a whole nonnegative native-size block count (0 disables half tiles)" }, + // Qwen 3.5 CUDA and HIP settings, read through this table: + .{ .name = "TENSORFOLD_MEMORY_RESERVE_GIB", .scope = .cuda, .kind = .real, .forms = "a finite GiB amount (the HIP admission's floor and the memory's size still bound it)" }, + .{ .name = "TENSORFOLD_HIP_MEMORY_LIMIT_GB", .scope = .cuda, .kind = .real, .forms = "a finite GiB amount (the HIP admission still fits its byte count in a 64-bit size)" }, + .{ .name = "TF_QWEN_KEEP_LATE", .scope = .cuda, .kind = .flag, .forms = "0 or 1 (default 0)" }, + .{ .name = "TF_QWEN_KV_PAGE_TEST", .scope = .cuda, .kind = .size, .min = 1, .max = 2147483647, .forms = "a whole page size from 1 to 2147483647 (unset: off)" }, + .{ .name = "TF_COST_KEY_TRACE", .scope = .cuda, .kind = .flag, .forms = "0 or 1 (default 0)" }, + .{ .name = "TF_TIMING", .scope = .cuda, .kind = .flag, .forms = "0 or 1 (default 0)" }, + .{ .name = "TF_NO_TREES", .scope = .cuda, .kind = .flag, .forms = "0 or 1 (default 0; 1 keeps the CUDA drafter's chains only)" }, + .{ .name = "TF_MTP_TREES", .scope = .cuda, .kind = .flag, .forms = "0 or 1 (default 0)" }, + .{ .name = "TF_MTP_BATCH", .scope = .cuda, .kind = .flag, .forms = "0 or 1 (default 1; 0 keeps one stream at a time)" }, + .{ .name = "TF_QWEN_POOL_LOG", .scope = .cuda, .kind = .flag, .forms = "0 or 1 (default 0)" }, + .{ .name = "TF_Q27_POCKET_OFF", .scope = .cuda, .kind = .path, .forms = "all, or a list of layer:neuron pairs without control characters (default off)" }, + .{ .name = "TF_Q27_TAIL", .scope = .cuda, .kind = .word, .words = &.{"off"}, .forms = "off (default: each nudged sequence's tail rows)" }, + .{ .name = "TF_Q27_GEMM", .scope = .cuda, .kind = .word, .words = &.{"narrow"}, .forms = "narrow (default: 128x128 tiles)" }, .{ .name = "TENSORFOLD_PROMPT_CACHE_KEEP_OTHERS", .scope = .cuda, .kind = .flag, .forms = "0 or 1" }, .{ .name = "TF_PROMPT_INTERMEDIATE", .scope = .cuda, .kind = .flag, .forms = "0 or 1 (default 0)" }, .{ .name = "TENSORFOLD_LFM2_KV_PAGES", .scope = .cuda, .kind = .flag, .forms = "0 or 1 (unset leases pool pages)" }, @@ -308,6 +322,11 @@ pub fn describe(a: std.mem.Allocator, name: []const u8, raw: []const u8) ![]cons return std.fmt.allocPrint(a, "{s}=\"{f}\": expected {s}", .{ name, std.zig.fmtString(raw), rule(name).forms }); } +/// A registered setting's raw text, for readers that parse it against runtime bounds the table cannot name. +pub fn rawText(name: [:0]const u8) ?[]const u8 { + return sys.getenv(name); +} + /// A direct family/tool entry point gets the same refusal even when it has no server problem buffer. fn checked(name: [:0]const u8, raw: ?[]const u8) Error!?u64 { return parse(name, raw) catch { diff --git a/zig/src/platform/environment_test.zig b/zig/src/platform/environment_test.zig index 32c4130724e..387b7e95376 100644 --- a/zig/src/platform/environment_test.zig +++ b/zig/src/platform/environment_test.zig @@ -67,6 +67,28 @@ const valid = [_]Case{ .{ .name = "TENSORFOLD_UNIFIED_HOST_COUNTS", .raw = "0", .n = 0 }, .{ .name = "TENSORFOLD_UNIFIED_HOST_COUNTS", .raw = "1", .n = 1 }, .{ .name = "TF_MTP_DRAFTS", .raw = "0", .n = 0 }, + .{ .name = "TF_QWEN_KEEP_LATE", .raw = "0", .n = 0 }, + .{ .name = "TF_QWEN_KEEP_LATE", .raw = "1", .n = 1 }, + .{ .name = "TF_QWEN_KV_PAGE_TEST", .raw = "1", .n = 1 }, + .{ .name = "TF_QWEN_KV_PAGE_TEST", .raw = "2147483647", .n = 2147483647 }, + .{ .name = "TF_COST_KEY_TRACE", .raw = "0", .n = 0 }, + .{ .name = "TF_COST_KEY_TRACE", .raw = "1", .n = 1 }, + .{ .name = "TF_TIMING", .raw = "0", .n = 0 }, + .{ .name = "TF_TIMING", .raw = "1", .n = 1 }, + .{ .name = "TF_NO_TREES", .raw = "0", .n = 0 }, + .{ .name = "TF_NO_TREES", .raw = "1", .n = 1 }, + .{ .name = "TF_MTP_TREES", .raw = "0", .n = 0 }, + .{ .name = "TF_MTP_TREES", .raw = "1", .n = 1 }, + .{ .name = "TF_MTP_BATCH", .raw = "0", .n = 0 }, + .{ .name = "TF_MTP_BATCH", .raw = "1", .n = 1 }, + .{ .name = "TF_QWEN_POOL_LOG", .raw = "0", .n = 0 }, + .{ .name = "TF_QWEN_POOL_LOG", .raw = "1", .n = 1 }, + .{ .name = "TF_Q27_GEMM", .raw = "narrow", .n = 0 }, + .{ .name = "TF_Q27_TAIL", .raw = "off", .n = 0 }, + .{ .name = "TF_Q27_POCKET_OFF", .raw = "all", .n = 0 }, + .{ .name = "TENSORFOLD_MEMORY_RESERVE_GIB", .raw = "1", .n = 4607182418800017408 }, + .{ .name = "TENSORFOLD_HIP_MEMORY_LIMIT_GB", .raw = "2", .n = 4611686018427387904 }, + .{ .name = "TF_MTP_DRAFTS", .raw = "4294967295", .n = std.math.maxInt(u32) }, .{ .name = "TF_DSPINE_WINDOW", .raw = "16", .n = 16 }, .{ .name = "TF_DSPINE_WINDOW", .raw = "4096", .n = 4096 }, @@ -172,7 +194,14 @@ test "environment: range, enum, whitespace and native prompt geometry refusals a .{ "XPU_A8_BITS", "16" }, .{ "TF_SLIDE_POCKET_KEY", "AUTO" }, .{ "TF_DRAMA_PREFILL_ROWS", "4096x" }, .{ "TF_DRAMA_REFERENCE_CACHE", "4294967296" }, .{ "TF_DSPINE_WINDOW", "0" }, .{ "TF_DSPINE_WINDOW", "15" }, - .{ "TF_DSPINE_WINDOW", "8193" }, + .{ "TF_DSPINE_WINDOW", "8193" }, .{ "TF_QWEN_KV_PAGE_TEST", "2147483648" }, + .{ "TF_QWEN_KV_PAGE_TEST", "0" }, .{ "TF_Q27_GEMM", "wide" }, + .{ "TF_Q27_GEMM", "NARROW" }, .{ "TF_Q27_TAIL", "on" }, + .{ "TF_Q27_TAIL", "OFF" }, .{ "TF_Q27_POCKET_OFF", "no\ncontrol" }, + .{ "TF_QWEN_KEEP_LATE", "2" }, .{ "TF_TIMING", "2" }, + .{ "TF_NO_TREES", "true" }, .{ "TF_MTP_TREES", "yes" }, + .{ "TF_MTP_BATCH", "off" }, .{ "TF_QWEN_POOL_LOG", "true" }, + .{ "TF_COST_KEY_TRACE", "on" }, }) |c| try t.expectError(error.InvalidEnvironment, e.parse(c[0], c[1])); try t.expectEqual(@as(?u64, null), try e.parse("TF_CUDA_DEVICE", " ")); try t.expectEqual(@as(?u64, 0), try e.parse("TF_Q27_COPY_ROWS", "+0"));