diff --git a/CHANGELOG.md b/CHANGELOG.md index 80100bcb809..b282024a130 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -4,6 +4,8 @@ Each release's page on GitHub has its notes and measurements. See [the 1.0.0 rel ## Unreleased +- On M5 Macs, opt-in: `TF_ATTENTION_PV_FP32=1` keeps attention's P x V at full fp32 for Nemotron's prompt attention, closer to float64 (output cells off the nearest bf16 value fall from about 1.1M to 1.8K of 8.6M), at a large prompt-speed cost (30% to 87% slower at 2K to 32K). Unset, nothing changes (part of #1772). + - The benchmark clients refuse a nonpositive `--tokens`, `--reps` or `--levels` entry, or a malformed `--levels` list, with a clear error and exit status 2 before any request, instead of failing mid-run or writing zero-stream cells (#1869, fixes #1867). Thanks to @garvrao80. - Qwen3.8-Flash-Next on Macs, opt-in: `TENSORFOLD_PREFILL_POLICY=fcfs` serves long prompts that arrive together oldest first, in chunks of `TENSORFOLD_PREFILL_TOKENS` rows (default 2,048) between decode rounds, with the same tokens. With eight 14K-token prompts at once on an M3 Ultra, the last user's first token comes after 93.6 s instead of 326.9 s; unset, nothing changes (#1843). Thanks to @ivanfioravanti. diff --git a/docs/kernel-contract.md b/docs/kernel-contract.md index b9ae0661d49..926c065f4d1 100644 --- a/docs/kernel-contract.md +++ b/docs/kernel-contract.md @@ -318,3 +318,13 @@ The sum fixtures use integers with exact FP32 partials below 2^24, including poo FP16 and BF16 simulations must fail in each of the three accumulator orders. Pooling declares its nine-term reduction separately from the physical grid width, so the small stress grid remains a valid launch. NaN and both infinity signs have explicit class controls. These registrations still require the device gates. + +## Shared M5 attention products + +The shared `attention_nax` defaults to the relaxed tensor P x V: float P is truncated to ten fraction bits. +`TF_ATTENTION_PV_FP32=1` opts into full float P with FP32 FMA accumulation on M5; unset preserves the old arithmetic. +The cut registration's independent formula includes the operand cut, while the full registration uses the full P. +A third registration executes the real cut kernel against the full FP32 bound and must fail the shapes gate. +The product fixture writes float output so BF16 rounding cannot conceal that control. +Both modes still require exceptional-class, repeat, guard, shape, accumulator and separate launch checks. +See [the mode's scope and device checks](recipes/m5-attention-precision.md); other families' rounding is unchanged. diff --git a/docs/recipes/m5-attention-precision.md b/docs/recipes/m5-attention-precision.md new file mode 100644 index 00000000000..cadbe79b625 --- /dev/null +++ b/docs/recipes/m5-attention-precision.md @@ -0,0 +1,53 @@ +# Shared M5 attention precision + +`TF_ATTENTION_PV_FP32=1` selects explicit float FMA products for the shared `attention_nax` P x V on M5. +Unset or `0` keeps the existing tensor product, which truncates a float probability to ten fraction bits. +Other values are refused when a library using this attention source is opened. +Set the variable before starting the process and keep it fixed for that process. +The default has not changed. This is an experimental arithmetic mode, not a family qualification. + +The full mode retains Q x K, softmax, masks, the normalizer and the final BF16 output. +It preserves every normal FP32 probability bit in its products, with FP32 FMA accumulation. +It does not promise exact real sums or bit equality with the cut mode. +The extra scalar products and lane shuffles can cost throughput; measure the selected checkpoint and prompt size. +Older GPUs keep the previous simdgroup-matrix source even when the switch is set. +Nemotron disk prompt states include the mode in their identity and cannot cross it. + +The shared helper serves Nemotron prompt attention, including its paged twin, and Qwen Image/MOSS Image attention. +It does not change the 27B text path's explicit half probabilities, general float GEMM or another family's attention. +The 27B's Qwen-VL tower also uses a separate float GEMM. +A teacher-forced 27B comparison is an unaffected control, not proof of a quality change in that model. +Image denoisers have velocity outputs rather than top tokens; their teacher-forced velocities need their own case. + +## Checks + +```sh +zig build test-kernel-contract tf-kernel-contract -Dcpu=apple_m1 +./zig-out/bin/tf-kernel-contract --only 'attention PV' +``` + +The contract registers cut operands against a cut-operand binary64 formula and full operands against full binary64. +Both require FP32 sums, guarded buffers, repeats, exceptional classes and matrix tile edges. +The served Nemotron prompt range keeps the measured one-sided operand-cut terms when unset. +Full mode removes that operand cut and counts 32 FMA steps per key tile; its control still compiles the cut product. +The masked-key nonfinite finding remains a separate case in both modes. +Its planted control runs the actual cut helper against the full-operand bound and must fail the shapes gate. +The bound is the FP32 chain length and term magnitude, not a percentage fitted to the observed result. +Separate launch records name both probes and all four production full-mode alignments. +M1/M2 compilation records and an M5 device receipt are distinct evidence; unsupported hardware is not a pass. + +The template probe injects exact dyadic probabilities into the real attention source, including a float-output copy. +It checks causal/full visibility, query/key tails, key-tile seams, five repeats, input bytes and guards: + +```sh +swiftc -O tools/zig/attention_pv.swift -o attention-pv +TF_ATTENTION_PV_FP32=0 ./attention-pv . check red +TF_ATTENTION_PV_FP32=1 ./attention-pv . check +TF_ATTENTION_PV_FP32=0 ./attention-pv . bench 2048 +TF_ATTENTION_PV_FP32=1 ./attention-pv . bench 2048 +``` + +Run device work only on an isolated GPU under the machine's existing queue and lock. +A compile failure cannot stand in for the cut mode's numerical red witness. +Teacher-force identical histories and report every top-token difference and both margins; do not judge diverging replies. +No default should change before the affected family has its own accepted correctness and fidelity receipts. diff --git a/tools/zig/attention_pv.swift b/tools/zig/attention_pv.swift new file mode 100644 index 00000000000..2fbc22934f1 --- /dev/null +++ b/tools/zig/attention_pv.swift @@ -0,0 +1,200 @@ +import Foundation +import Metal +import CryptoKit + +func replaceOnce(_ source: String, _ old: String, _ new: String) -> String { + precondition(source.components(separatedBy: old).count == 2, "SourceAnchor: \(old)") + return source.replacingOccurrences(of: old, with: new) +} +func expand(_ path: URL) throws -> String { + let text = try String(contentsOf: path, encoding: .utf8) + return try text.components(separatedBy: "\n").map { line in + if line.hasPrefix("#include \"") { + let name = line.components(separatedBy: "\"")[1] + return try expand(path.deletingLastPathComponent().appendingPathComponent(name)) + } + return line + }.joined(separator: "\n") +} +func json(_ value: [String: Any]) throws { + let data = try JSONSerialization.data(withJSONObject: value, options: [.sortedKeys, .prettyPrinted]) + FileHandle.standardOutput.write(data) + FileHandle.standardOutput.write(Data([10])) +} +func bf16(_ value: Double) -> UInt16 { + let word = Float(value).bitPattern + return UInt16(truncatingIfNeeded: (word &+ 0x7fff &+ ((word >> 16) & 1)) >> 16) +} +func checked(_ command: MTLCommandBuffer) { + command.commit() + command.waitUntilCompleted() + precondition(command.status == .completed, "CommandFailed: \(String(describing: command.error))") +} +let args = CommandLine.arguments +precondition(args.count >= 3, "attention_pv SOURCE_ROOT check|bench [rows] [red]") +let root = URL(fileURLWithPath: args[1]) +let mode = args[2] +let expectRed = args.last == "red" +let selection = ProcessInfo.processInfo.environment["TF_ATTENTION_PV_FP32"] ?? "0" +precondition(["0", "1"].contains(selection), "TF_ATTENTION_PV_FP32 must be 0 or 1") +let attention = (selection == "1" ? "#define TF_ATTN_PV_FP32 1\n" : "") + + (try expand(root.appendingPathComponent("zig/kernels/metal/prefill/attention_nax.metal"))) +guard let device = MTLCreateSystemDefaultDevice(), device.supportsFamily(.apple10) else { + fatalError("RequiresM5TensorUnits") +} +let queue = device.makeCommandQueue()! +let options = MTLCompileOptions() +options.languageVersion = .version4_1 +options.mathMode = .safe +options.mathFloatingPointFunctions = .fast +func library(_ source: String) throws -> MTLLibrary { try device.makeLibrary(source: source, options: options) } +func pipeline(_ library: MTLLibrary, _ name: String) throws -> MTLComputePipelineState { + try device.makeComputePipelineState(function: library.makeFunction(name: name)!) +} +func buffer(_ values: [T]) -> MTLBuffer { + values.withUnsafeBytes { device.makeBuffer(bytes: $0.baseAddress!, length: $0.count, options: .storageModeShared)! } +} +func parameters(_ rows: Int, _ keys: Int) -> [Int32] { + let prefix = [1, 1, rows, keys, 1, (rows + 63) / 64, (keys + 31) / 32, + rows / 64, keys / 32, rows % 64, keys % 32, keys - rows] + return (prefix + [rows*128, rows*128, 128, keys*128, keys*128, 128, + keys*128, keys*128, 128, rows*128, rows*128, 128]).map(Int32.init) +} +func dispatch(_ pipe: MTLComputePipelineState, _ buffers: [MTLBuffer], _ groups: Int, _ command: MTLCommandBuffer) { + let enc = command.makeComputeCommandEncoder()! + enc.setComputePipelineState(pipe) + for (i, b) in buffers.enumerated() { enc.setBuffer(b, offset: 0, index: i) } + enc.dispatchThreadgroups(MTLSize(width: groups, height: 1, depth: 1), + threadsPerThreadgroup: MTLSize(width: 128, height: 1, depth: 1)) + enc.endEncoding() +} +let sentinel: UInt32 = 0x13579bdf +if mode == "check" { + let body = attention.components(separatedBy: "// ---- entry points:")[0] + var instrumented = replaceOnce(body, "device T* O, const device int* P", "device float* O, const device int* P") + instrumented = replaceOnce(instrumented, "s[f][e] = fast::exp2(s[f][e] - top_new[e >> 2]);", + "s[f][e] = s[f][e] == kMasked ? 0.0f : (kb*BK + 16*f + home.x + TF_COL(e) == int(F[3]) ? F[1] : (kb*BK + 16*f + home.x + TF_COL(e) == int(F[3])+1 ? F[2] : 0.0f));") + let signature = """ + kernel void NAME(const device bfloat* Q [[buffer(0)]], const device bfloat* K [[buffer(1)]], + const device bfloat* V [[buffer(2)]], const device int* P [[buffer(3)]], const device float* F [[buffer(4)]], + device float* O [[buffer(5)]], uint3 tg [[threadgroup_position_in_grid]], + uint sg [[simdgroup_index_in_threadgroup]], uint lane [[thread_index_in_simdgroup]]) { + tfp::FUNCTION(Q, K, V, O, P, F, tg, sg, lane); + } + """ + var shader = replaceOnce(instrumented, "device float* O, const device int* P", "device T* O, const device int* P") + let raw = replaceOnce(instrumented, "inline void attention_nax(", "inline void attention_raw(") + .replacingOccurrences(of: "acc[i][e] = acc[i][e] * inv[e >> 2];", with: "acc[i][e] = acc[i][e];") + let rawBody = raw.components(separatedBy: "// One 64-query block")[1] + shader += "\nnamespace tfp {\n// One 64-query block" + rawBody + for aq in [false, true] { for ak in [false, true] { for causal in [false, true] { for raw in [false, true] { + let name = "pv_\(aq ? 1 : 0)\(ak ? 1 : 0)\(causal ? 1 : 0)\(raw ? 1 : 0)" + let sig = raw ? signature : signature.replacingOccurrences(of: "device float* O", with: "device bfloat* O") + shader += sig.replacingOccurrences(of: "NAME", with: name) + .replacingOccurrences(of: "FUNCTION", with: raw ? "attention_raw" : "attention_nax") + .replacingOccurrences(of: "AQ", with: String(aq)).replacingOccurrences(of: "AK", with: String(ak)) + .replacingOccurrences(of: "CAUSAL", with: String(causal)) + } } } } + let lib = try library(shader) + let scalarText = try expand(root.appendingPathComponent("zig/kernels/metal/core/shared_attention.metal")) + let scalar = replaceOnce(scalarText, "weight[t] = precise::exp(score[t] - next);", + "weight[t] = first+t == 0 ? 1.0f : (first+t == 1 ? 0.999267578125f : 0.0f);") + let scalarLib = try library("#define TF_D 128\n#define TF_QH 1\n#define TF_KVH 1\n#define TF_RD 0\n#define TF_OUT float\n" + scalar) + let scalarPipe = try pipeline(scalarLib, "tf_shared_lane_attention") + var records = [[String: Any]](), mismatches = 0, comparisons = 0, repeats = 0, guards = 0, unchanged = 0 + let cases: [(String, Float, Float, Float)] = [ + ("catch", 1, 0.999267578125, 1), + ("third-part", 1, Float(bitPattern: 0x3f7f1234), 1), + ("small-residual", Float(bitPattern: 0x03800001), Float(bitPattern: 0x03800000), Float(pow(2.0, 120))), + ("exact-cancel", 1, 1, 1)] + for (label, a, b, v) in cases { + for (rows, keys, first) in [(1,2,0), (17,33,31), (64,64,0), (65,65,31)] { + let aq = rows % 64 == 0, ak = keys % 32 == 0 + for causal in [false, true] { for raw in [false, true] { + let name = "pv_\(aq ? 1 : 0)\(ak ? 1 : 0)\(causal ? 1 : 0)\(raw ? 1 : 0)" + let pipe = try pipeline(lib, name) + let q = buffer([UInt16](repeating: 0, count: rows*128)) + let k = buffer([UInt16](repeating: 0, count: keys*128)) + var values = [UInt16](repeating: 0, count: keys*128) + for c in 0..<128 { values[first*128+c] = bf16(Double(v)); values[(first+1)*128+c] = bf16(-Double(v)) } + let vb = buffer(values), pb = buffer(parameters(rows, keys)), fb = buffer([Float(0),a,b,Float(first)]) + let out = buffer([UInt32](repeating: sentinel, count: rows*128+16)) + let inputs = [q,k,vb,pb,fb] + let saved = inputs.map { Data(bytes: $0.contents(), count: $0.length) } + var firstWords: [UInt32]? = nil, bad = 0 + for _ in 0..<5 { + let command = queue.makeCommandBuffer()! + dispatch(pipe, inputs+[out], (rows+63)/64, command) + checked(command) + let bits = out.contents().bindMemory(to: UInt32.self, capacity: rows*128+16) + let bf = out.contents().bindMemory(to: UInt16.self, capacity: (rows*128+16)*2) + for row in 0.. 0 ? 0 : 1) : (mismatches == 0 ? 0 : 1)) +} else { + precondition(mode == "bench" && args.count >= 4) + let rows = Int(args[3])! + precondition([2048,8192,32768].contains(rows)) + let lib = try library(attention) + let name = "custom_kernel_tf_attention_nax_bf16_t_t_t_bfloat16_t_bfloat16_t_bfloat16_t_int32_t_float_bfloat16_t" + let pipe = try pipeline(lib,name) + let q = buffer((0.. using namespace metal; typedef bfloat bfloat16_t; @@ -26,6 +26,29 @@ inline void row_fold(thread const frag& f, thread float (&r)[2]) { } } +// The P x V product: the default tensor op cuts P to ten fraction bits; the opt-in uses float FMAs. +template +inline void attention_pv(thread frag& lo, thread frag& hi, thread const frag& p, + thread const frag& v0, thread const frag& v1, ushort lane) { +#if defined(TF_ATTN_PV_FP32) && !defined(TF_SIMD_FRAGS) + TF_UNROLL + for (ushort k = 0; k < 16; k++) { + const ushort pl = (lane & 22) | ((k >> 2) & 1) | ((k >> 3) << 3); + const ushort vl = ((k & 3) << 1) | ((k & 4) << 2) | (lane & 9); + const float p0 = simd_shuffle(p[k & 3], pl), p1 = simd_shuffle(p[4 + (k & 3)], pl); + TF_UNROLL + for (ushort c = 0; c < 4; c++) { + const float a = simd_shuffle(float(v0[4 * (k >> 3) + c]), vl); + const float b = simd_shuffle(float(v1[4 * (k >> 3) + c]), vl); + lo[c] = fma(p0, a, lo[c]); hi[c] = fma(p0, b, hi[c]); + lo[4 + c] = fma(p1, a, lo[4 + c]); hi[4 + c] = fma(p1, b, hi[4 + c]); + } + } +#else + mma_16x32(lo, hi, p, v0, v1); +#endif +} + // One 64-query block of one head, online softmax over 32-key blocks; P holds the ATTN_PARAMS fields, F[0] the scale. template inline void attention_nax(const device T* Q, const device T* K, const device T* V, device T* O, const device int* P, @@ -147,7 +170,7 @@ inline void attention_nax(const device T* Q, const device T* K, const device T* frag_get(v0, V, vs, 16 * k, 16 * d, home); frag_get(v1, V, vs, 16 * k, 16 * d + 16, home); } - mma_16x32(acc[d], acc[d + 1], s[k], v0, v1); + attention_pv(acc[d], acc[d + 1], s[k], v0, v1, ushort(lane)); } } K += BK * ks; diff --git a/zig/src/core/attention_precision.zig b/zig/src/core/attention_precision.zig new file mode 100644 index 00000000000..6746e00ac62 --- /dev/null +++ b/zig/src/core/attention_precision.zig @@ -0,0 +1,63 @@ +//! Source selection for the shared M5 attention product; other kernels retain their own rounding policy. +const std = @import("std"); + +pub const env = "TF_ATTENTION_PV_FP32"; +pub const define = "#define TF_ATTN_PV_FP32 1\n"; + +/// Only an explicit 1 enables the mode; an unset or zero value keeps the existing product. +pub fn parse(value: ?[]const u8) !bool { + const text = value orelse return false; + if (std.mem.eql(u8, text, "0")) return false; + if (std.mem.eql(u8, text, "1")) return true; + return error.AttentionPrecisionValue; +} + +/// Read while building the engine's libraries, before serving begins. +pub fn requested() !bool { + return parse(if (@import("sys").c.getenv(env)) |v| std.mem.span(v) else null); +} + +/// Expand fragments with an explicit mode, so contracts never inherit a caller's environment. +pub fn source(a: std.mem.Allocator, units: bool, text: []const u8, header: []const u8, full: bool) ![]u8 { + const body = try std.mem.replaceOwned(u8, a, text, "#include \"../nax.h\"", header); + defer a.free(body); + const head = if (!units) "#define TF_SIMD_FRAGS 1\n" else if (full) define else ""; + return std.mem.concat(a, u8, &.{ head, body }); +} + +/// Keep the default identity and separate opt-in states even when a short calibration probe misses the difference. +pub fn hashMode(h: *std.hash.Wyhash, full: bool) void { + if (full) h.update("attention-pv-fp32-v1"); +} + +test "attention precision: unset and zero preserve the default; only one opts in" { + try std.testing.expect(!try parse(null)); + try std.testing.expect(!try parse("0")); + try std.testing.expect(try parse("1")); + for ([_][]const u8{ "", "true", "01", "-1", "2" }) |v| try std.testing.expectError(error.AttentionPrecisionValue, parse(v)); +} + +test "attention precision: source modes and the older-chip source are explicit" { + const a = std.testing.allocator; + const text = "#include \"../nax.h\"\nBODY"; + const off = try source(a, true, text, "HEADER", false); + defer a.free(off); + const on = try source(a, true, text, "HEADER", true); + defer a.free(on); + const old = try source(a, false, text, "HEADER", true); + defer a.free(old); + try std.testing.expectEqualStrings("HEADER\nBODY", off); + try std.testing.expectEqualStrings(define ++ "HEADER\nBODY", on); + try std.testing.expectEqualStrings("#define TF_SIMD_FRAGS 1\nHEADER\nBODY", old); +} + +test "attention precision: kept-state identity separates the mode without moving the default" { + var base = std.hash.Wyhash.init(17); + base.update("checkpoint"); + var off = base; + hashMode(&off, false); + var on = base; + hashMode(&on, true); + try std.testing.expectEqual(base.final(), off.final()); + try std.testing.expect(on.final() != off.final()); +} diff --git a/zig/src/core/contract.zig b/zig/src/core/contract.zig index 6828c844cc6..867ba1525f0 100644 --- a/zig/src/core/contract.zig +++ b/zig/src/core/contract.zig @@ -3,6 +3,7 @@ pub const delta_slots_ref = @import("contract/delta_slots_ref.zig"); pub const delta_slots_records = @import("contract/delta_slots_records.zig"); pub const spec = @import("contract/contract.zig"); pub const gates = @import("contract/gates.zig"); +pub const attention_pv = @import("contract/attention_pv.zig"); pub const rows = @import("contract/rows.zig"); pub const affine = @import("contract/affine.zig"); pub const dense = @import("contract/dense.zig"); @@ -29,6 +30,7 @@ test { _ = spec; _ = gates; _ = rows; + _ = attention_pv; _ = affine; _ = dense; _ = limits; diff --git a/zig/src/core/contract/attention_pv.zig b/zig/src/core/contract/attention_pv.zig new file mode 100644 index 00000000000..43cd25e11b3 --- /dev/null +++ b/zig/src/core/contract/attention_pv.zig @@ -0,0 +1,151 @@ +//! Independent scalar products for the shared attention P x V, including the legacy operand cut. +const std = @import("std"); +const c = @import("contract.zig"); +const rows = @import("rows.zig"); + +pub const Mode = enum { cut, fp32, cut_control }; +pub const shapes = [_]c.Shape{ .{ .rows = 4, .n = 32, .k = 32 }, .{ .rows = 17, .n = 33, .k = 65 }, .{ .rows = 4, .n = 32, .k = 4096 } }; +pub fn name(m: Mode) []const u8 { + return switch (m) { + .cut => "metal attention PV cut", + .fp32 => "metal attention PV fp32", + .cut_control => "control: metal attention PV cut against fp32", + }; +} +fn depth(s: c.Shape) usize { + return s.k; +} +pub fn spec(m: Mode) c.Spec { + return .{ .name = name(m), .accum = .f32, .depth = depth, .out = .f32, .tiles = .{ .{ .size = 16 }, .{ .size = 32 }, .{ .size = 16 } }, .served = &shapes }; +} + +/// The observed M5 relaxed operand conversion, independent of the device helper. +pub fn cut(p: f32) f32 { + return @bitCast(@as(u32, @bitCast(p)) & 0xffffe000); +} + +pub const Fixture = struct { + a: std.mem.Allocator, + shape: c.Shape, + p: []f32, + v: []u16, + + pub fn init(a: std.mem.Allocator, s: c.Shape) !Fixture { + const p = try a.alloc(f32, s.rows * s.k); + errdefer a.free(p); + return .{ .a = a, .shape = s, .p = p, .v = try a.alloc(u16, s.k * s.n) }; + } + pub fn deinit(f: Fixture) void { + f.a.free(f.p); + f.a.free(f.v); + } + + pub fn fill(f: Fixture, mode: rows.Fill, seed: u64) !void { + const s = f.shape; + var rng = std.Random.DefaultPrng.init(seed); + const random = rng.random(); + for (f.p) |*p| p.* = random.float(f32); + for (f.v) |*v| v.* = c.toBf16(random.float(f32) * 2 - 1); + if (mode == .stress) { + const d = try rows.Rows.init(f.a, .dot, .{ .rows = s.rows, .n = 1, .k = s.k }); + defer d.deinit(); + d.fill(.stress, seed); + for (f.p, d.x) |*p, x| p.* = c.fromBf16(x); + for (0..s.k) |k| @memset(f.v[k * s.n ..][0..s.n], d.w[k]); + } else if (mode == .nonfinite) { + const values = [_]f32{ std.math.nan(f32), std.math.inf(f32), -std.math.inf(f32) }; + for (values, 0..) |v, r| if (r < s.rows) { + f.p[r * s.k] = v; + }; + if (s.rows > 3) { + f.p[3 * s.k] = 0; + f.v[0] = c.toBf16(std.math.inf(f32)); + } + } else if (s.k >= 2) { + // Cancellation exposes a cut probability even when a long random row would hide it. + @memset(f.p[0..s.k], 0); + f.p[0] = 1; + f.p[1] = 0.999267578125; + for (0..s.n) |j| { + f.v[j] = c.toBf16(1); + f.v[s.n + j] = c.toBf16(-1); + } + } + } + fn terms(f: Fixture, m: Mode, r: usize, j: usize, out: []f64) void { + for (out, 0..) |*t, k| { + const p = f.p[r * f.shape.k + k]; + t.* = @as(f64, if (m == .cut) cut(p) else p) * c.fromBf16(f.v[k * f.shape.n + j]); + } + } + pub fn reference(f: Fixture, m: Mode, want: []f64, mag: []f64) !void { + const t = try f.a.alloc(f64, f.shape.k); + defer f.a.free(t); + for (0..f.shape.rows) |r| for (0..f.shape.n) |j| { + f.terms(m, r, j, t); + var sum: f64 = 0; + var magnitude: f64 = 0; + for (t) |v| { + sum += v; + magnitude += @abs(v); + } + want[r * f.shape.n + j] = sum; + mag[r * f.shape.n + j] = magnitude; + }; + } + pub fn simulate(f: Fixture, m: Mode, acc: c.Accum, order: rows.Order, out: []f64) !void { + const t = try f.a.alloc(f64, f.shape.k); + defer f.a.free(t); + for (0..f.shape.rows) |r| for (0..f.shape.n) |j| { + f.terms(m, r, j, t); + out[r * f.shape.n + j] = rows.sumIn(acc, order, t); + }; + } +}; + +test "attention PV: the cut mode fails the full probability's derived bound" { + const f = try Fixture.init(std.testing.allocator, shapes[0]); + defer f.deinit(); + try f.fill(.random, 1772); + var want: [128]f64 = undefined; + var mag: [128]f64 = undefined; + var legacy: [128]f64 = undefined; + try f.reference(.fp32, &want, &mag); + try f.simulate(.cut, .f32, .sequential, &legacy); + try std.testing.expectEqual(@as(f64, 3.0 / 4096.0), want[0]); + try std.testing.expectEqual(@as(f64, 1.0 / 1024.0), legacy[0]); + try std.testing.expect(@abs(legacy[0] - want[0]) > c.bound(spec(.fp32), shapes[0], want[0], mag[0])); +} + +test "attention PV: stress requires fp32 sums in all three independent orders" { + const f = try Fixture.init(std.testing.allocator, shapes[2]); + defer f.deinit(); + try f.fill(.stress, 1772); + var want: [128]f64 = undefined; + var mag: [128]f64 = undefined; + var got: [128]f64 = undefined; + try f.reference(.fp32, &want, &mag); + for (std.enums.values(rows.Order)) |order| { + try f.simulate(.fp32, .f32, order, &got); + try std.testing.expectEqualSlices(f64, &want, &got); + for ([_]c.Accum{ .f16, .bf16 }) |acc| { + try f.simulate(.fp32, acc, order, &got); + var most: f64 = 0; + for (got, want) |g, v| most = @max(most, if (std.math.isFinite(g)) @abs(g - v) / c.boundExact(spec(.fp32), v) else std.math.inf(f64)); + try std.testing.expect(most >= 100); + } + } +} + +test "attention PV: every M5 FMA supplier maps to the requested matrix coordinate" { + for (0..32) |lane| for (0..16) |k| { + const row = ((lane & 16) >> 2) | ((lane >> 1) & 3); + const col = (lane & 8) + ((lane & 1) << 2); + const pl = (lane & 22) | ((k >> 2) & 1) | ((k >> 3) << 3); + const vl = ((k & 3) << 1) | ((k & 4) << 2) | (lane & 9); + try std.testing.expectEqual(row, ((pl & 16) >> 2) | ((pl >> 1) & 3)); + try std.testing.expectEqual(k, (pl & 8) + ((pl & 1) << 2) + (k & 3)); + try std.testing.expectEqual(k, ((vl & 16) >> 2) | ((vl >> 1) & 3) | ((k >> 3) * 8)); + try std.testing.expectEqual(col, (vl & 8) + ((vl & 1) << 2)); + }; +} diff --git a/zig/src/core/contract/attention_pv_records.zig b/zig/src/core/contract/attention_pv_records.zig new file mode 100644 index 00000000000..f111d8f90d7 --- /dev/null +++ b/zig/src/core/contract/attention_pv_records.zig @@ -0,0 +1,24 @@ +//! Explicit precision-mode launch records for the shared attention product; older chips retain their existing path. +const std = @import("std"); +const M = @import("limits.zig").MetalLaunch; +const prefix = "attention pv "; +pub const records = probes ++ prompts; +const probes = [_]M{ + .{ .name = prefix ++ "cut tf_attention_pv_contract", .threads = 32, .tg_memory = 0, .reserved = 32, .offline = false }, + .{ .name = prefix ++ "fp32 tf_attention_pv_contract", .threads = 32, .tg_memory = 0, .reserved = 32, .offline = false }, +}; +const prompts = blk: { + var out: [4]M = undefined; + for (&out, [_][]const u8{ "n_n", "n_t", "t_n", "t_t" }) |*r, tag| r.* = .{ + .name = prefix ++ "fp32 custom_kernel_tf_attention_nax_bf16_" ++ tag ++ "_t_bfloat16_t_bfloat16_t_bfloat16_t_int32_t_float_bfloat16_t", + .threads = 128, + .tg_memory = 0, + .reserved = 128, + .offline = false, + }; + break :blk out; +}; +test "attention PV: both arithmetic modes and all four full-mode production alignments have launch records" { + try std.testing.expectEqual(@as(usize, 6), records.len); + try std.testing.expectEqual(@as(usize, 0), try @import("registry.zig").checkMetal(std.testing.allocator, &records, true)); +} diff --git a/zig/src/core/contract/registry.zig b/zig/src/core/contract/registry.zig index 8e8e10c965a..e6bb1f89ed4 100644 --- a/zig/src/core/contract/registry.zig +++ b/zig/src/core/contract/registry.zig @@ -569,7 +569,7 @@ test { _ = @import("nemotron_ssd_records.zig"); } /// The Metal collector keeps measured slots and the restored vision declarations. -pub const all_metal = metal ++ @import("delta_slots_records.zig").records ++ @import("flashnext_pending.zig").records ++ @import("simd_pairs_records.zig").records ++ @import("metal_pair_records.zig").records ++ @import("glm_rows_records.zig").records ++ @import("weight_only_records.zig").metal ++ @import("hc_activation_records.zig").metal ++ @import("qwen4_records.zig").metal ++ @import("lfm2_records.zig").records ++ @import("nemotron_experts_records.zig").records ++ @import("nemotron_pages_records.zig").records ++ @import("nemotron_attention_records.zig").records ++ +pub const all_metal = @import("attention_pv_records.zig").records ++ metal ++ @import("delta_slots_records.zig").records ++ @import("flashnext_pending.zig").records ++ @import("simd_pairs_records.zig").records ++ @import("metal_pair_records.zig").records ++ @import("glm_rows_records.zig").records ++ @import("weight_only_records.zig").metal ++ @import("hc_activation_records.zig").metal ++ @import("qwen4_records.zig").metal ++ @import("lfm2_records.zig").records ++ @import("nemotron_experts_records.zig").records ++ @import("nemotron_pages_records.zig").records ++ @import("nemotron_attention_records.zig").records ++ @import("nemotron_ssd_records.zig").records ++ @import("flashnext_attention_records.zig").records ++ @import("spark25_records.zig").records ++ @import("gemma_attention_records.zig").records ++ @import("moss_image_records.zig").records ++ @import("dsv41_metal_records.zig").records ++ @import("minimax_records.zig").records; const learning = @import("registry_learning.zig"); pub const gradient_pending = learning.gradient_pending; diff --git a/zig/src/core/frags.zig b/zig/src/core/frags.zig index 0dfe9e36a33..14bb7af2b86 100644 --- a/zig/src/core/frags.zig +++ b/zig/src/core/frags.zig @@ -2,13 +2,17 @@ const std = @import("std"); const mtl = @import("metal"); const ks = @import("kernel_sources"); +pub const precision = @import("attention_precision.zig"); /// A prompt-kernel source with nax.h inlined; a GPU without tensor units takes nax.h's simdgroup-matrix layout. pub fn source(device: mtl.Device, a: std.mem.Allocator, text: []const u8) ![]u8 { - const src = try std.mem.replaceOwned(u8, a, text, "#include \"../nax.h\"", ks.nax); - if (device.tensorUnits()) return src; - defer a.free(src); - return std.mem.concat(a, u8, &.{ "#define TF_SIMD_FRAGS 1\n", src }); + const full = if (std.mem.indexOf(u8, text, "TF_ATTN_PV_FP32") != null) try precision.requested() else false; + return sourceMode(device, a, text, full); +} + +/// Contract libraries name their precision independently of the process environment. +pub fn sourceMode(device: mtl.Device, a: std.mem.Allocator, text: []const u8, full: bool) ![]u8 { + return precision.source(a, device.tensorUnits(), text, ks.nax, full); } /// The op both ways the prompt kernels use it (a transposed right operand, a plain one) through nax.h's fragments. diff --git a/zig/src/native/metal_identity.zig b/zig/src/native/metal_identity.zig index 40cad0aa3c1..c7af3033b74 100644 --- a/zig/src/native/metal_identity.zig +++ b/zig/src/native/metal_identity.zig @@ -18,6 +18,8 @@ pub fn learned(a: Allocator, io: std.Io, dir: []const u8, b: *nemotron.backend.M const probe = try nemotron.learned_prompts.probe(b); const ns = std.Io.Clock.awake.now(io).toNanoseconds() - t0; for ([_]u64{ b.o.chunk, @intFromBool(b.head != null), nemotron.kernels.sourceHash(), probe }) |x| h.update(std.mem.asBytes(&x)); + const precision = @import("tensorfold").frags.precision; + precision.hashMode(&h, b.m.device.tensorUnits() and try precision.requested()); var os: [64]u8 = undefined; h.update(api.prompt_imprint.osBuild(&os)); h.update(std.mem.span(b.m.device.name())); diff --git a/zig/tests/contract/metal_attention_pv.zig b/zig/tests/contract/metal_attention_pv.zig new file mode 100644 index 00000000000..a936f7f24a3 --- /dev/null +++ b/zig/tests/contract/metal_attention_pv.zig @@ -0,0 +1,121 @@ +//! The served attention product in both arithmetic modes, with the real cut path as a full-float control. +const std = @import("std"); +const mtl = @import("metal"); +const tf = @import("tensorfold"); +const contract = @import("contract"); +const sources = @import("kernel_sources"); +const rig_ = @import("rig.zig"); +const ref = contract.attention_pv; +const c = contract.spec; +const g = contract.gates; + +pub const function = "tf_attention_pv_contract"; +const wrapper = + \\[[max_total_threads_per_threadgroup(32)]] + \\kernel void tf_attention_pv_contract(const device float* P [[buffer(0)]], const device bfloat* V [[buffer(1)]], + \\ device float* O [[buffer(2)]], constant int* dims [[buffer(3)]], + \\ uint3 tg [[threadgroup_position_in_grid]], ushort lane [[thread_index_in_simdgroup]]) { + \\ using namespace tfp; + \\ const short2 home = frag_home(lane); + \\ const int row = int(tg.y) * 16, col = int(tg.x) * 32; + \\ frag lo = frag(0), hi = frag(0); + \\ for (int k = 0; k < dims[2]; k += 16) { + \\ frag p; frag v0, v1; + \\ frag_get_in(p, P, dims[2], row, k, home, dims[0], dims[2]); + \\ frag_get_in(v0, V, dims[1], k, col, home, dims[2], dims[1]); + \\ frag_get_in(v1, V, dims[1], k, col + 16, home, dims[2], dims[1]); + \\ attention_pv(lo, hi, p, v0, v1, lane); + \\ } + \\ frag_put_in(lo, O, dims[1], row, col, home, dims[0], dims[1]); + \\ frag_put_in(hi, O, dims[1], row, col + 16, home, dims[0], dims[1]); + \\} +; + +pub fn text(a: std.mem.Allocator, device: mtl.Device, full: bool) ![]u8 { + const attention = for (sources.prefill) |f| { + if (std.mem.eql(u8, f.name, "attention_nax")) break f.text; + } else return error.AttentionSource; + const joined = try std.mem.concat(a, u8, &.{ attention, "\n", wrapper }); + defer a.free(joined); + return tf.frags.sourceMode(device, a, joined, full); +} + +pub const Probe = struct { + a: std.mem.Allocator, + rig: rig_.Rig, + mode: ref.Mode, + pipe: mtl.Pipeline, + fixture: ?ref.Fixture = null, + p: rig_.Ref = undefined, + v: rig_.Ref = undefined, + out: rig_.Ref = undefined, + + pub fn init(a: std.mem.Allocator, device: mtl.Device, queue: mtl.Queue, mode: ref.Mode) !Probe { + if (!device.tensorUnits()) return error.TensorUnitsRequired; + const source = try text(a, device, mode == .fp32); + defer a.free(source); + return .{ .a = a, .rig = .{ .a = a, .device = device, .queue = queue }, .mode = mode, .pipe = try rig_.pipeline(device, source, function) }; + } + pub fn deinit(p: *Probe) void { + if (p.fixture) |f| f.deinit(); + p.rig.deinit(); + p.pipe.deinit(); + } + pub fn kernel(p: *Probe) g.Kernel { + return .{ .spec = ref.spec(p.mode), .ctx = p, .vt = &vt, .control = if (p.mode == .cut_control) .shapes else null }; + } + const vt = g.hooks(Probe); + + pub fn prepare(p: *Probe, s: c.Shape, fill: g.Fill, seed: u64) !bool { + if (p.fixture) |f| f.deinit(); + p.fixture = null; + p.rig.reset(); + const f = try ref.Fixture.init(p.a, s); + p.fixture = f; + try f.fill(fill, seed); + p.p = try p.rig.input(std.mem.sliceAsBytes(f.p)); + p.v = try p.rig.input(std.mem.sliceAsBytes(f.v)); + p.out = try p.rig.output(s.rows * s.n * 4); + return true; + } + pub fn run(p: *Probe) !void { + const s = p.fixture.?.shape; + const pass = p.rig.begin(); + const e = pass.e; + e.setPipeline(p.pipe); + e.setBuffer(p.p.buf, p.p.off, 0); + e.setBuffer(p.v.buf, p.v.off, 1); + e.setBuffer(p.out.buf, p.out.off, 2); + e.setValue([3]i32{ @intCast(s.rows), @intCast(s.n), @intCast(s.k) }, 3); + e.dispatchGroups(mtl.Size.of((s.n + 31) / 32, (s.rows + 15) / 16, 1), mtl.Size.of(32, 1, 1)); + try p.rig.finish(pass); + } + pub fn count(p: *Probe) usize { + const s = p.fixture.?.shape; + return s.rows * s.n; + } + pub fn reference(p: *Probe, want: []f64, mag: []f64) !void { + return p.fixture.?.reference(p.mode, want, mag); + } + pub fn simulate(p: *Probe, acc: c.Accum, order: g.Order, out: []f64) !void { + return p.fixture.?.simulate(p.mode, acc, order, out); + } +}; + +pub const Suite = struct { + probes: [3]?Probe = @splat(null), + pub fn deinit(s: *Suite) void { + for (&s.probes) |*p| if (p.*) |*probe| probe.deinit(); + } + pub fn collect(s: *Suite, a: std.mem.Allocator, device: mtl.Device, queue: mtl.Queue, kernels: *std.ArrayList(g.Kernel), only: ?[]const u8) !void { + for (std.enums.values(ref.Mode), 0..) |mode, i| { + if (only) |needle| if (std.mem.indexOf(u8, ref.name(mode), needle) == null) continue; + if (!device.tensorUnits()) { + std.debug.print("UNSUPPORTED {s}: this precision mode is specific to M5; older-chip arithmetic unchanged\n", .{ref.name(mode)}); + continue; + } + s.probes[i] = try Probe.init(a, device, queue, mode); + try kernels.append(a, s.probes[i].?.kernel()); + } + } +}; diff --git a/zig/tests/contract/metal_limits.zig b/zig/tests/contract/metal_limits.zig index 3c6d87d556d..f61445eecc4 100644 --- a/zig/tests/contract/metal_limits.zig +++ b/zig/tests/contract/metal_limits.zig @@ -31,6 +31,19 @@ fn launchOf(a: std.mem.Allocator, device: mtl.Device, d: limits.MetalLaunch) !La return std.mem.indexOf(u8, s, p) != null; } }.f; + if (std.mem.startsWith(u8, d.name, "attention pv ")) { + const full = std.mem.indexOf(u8, d.name, " fp32 ") != null; + const probe = @import("metal_attention_pv.zig"); + if (std.mem.eql(u8, fun, probe.function)) { + const body = try probe.text(a, device, full); + return .{ .decl = d, .function = fun, .here = body, .pre_m5 = body }; + } + const raw = for (sources.prefill) |f| { + if (std.mem.eql(u8, f.name, "attention_nax")) break f.text; + } else return error.UnknownLaunch; + const body = try tf.frags.sourceMode(device, a, raw, full); + return .{ .decl = d, .function = fun, .here = body, .pre_m5 = try preM5(a, "", raw) }; + } if (std.mem.startsWith(u8, d.name, "qwen4-native ")) { const body = try @import("qwen4").family.limits_sources.source(a, d.name); return .{ .decl = d, .function = fun, .here = body, .pre_m5 = body }; @@ -137,7 +150,7 @@ fn launchOf(a: std.mem.Allocator, device: mtl.Device, d: limits.MetalLaunch) !La } else return error.UnknownLaunch; const pre = if (frags) try preM5(a, head, text) else try std.mem.concat(a, u8, &.{ head, text }); const here = if (frags and device.tensorUnits()) blk: { - const body = try std.mem.replaceOwned(u8, a, text, "#include \"../nax.h\"", sources.nax); + const body = try tf.frags.source(device, a, text); break :blk try std.mem.concat(a, u8, &.{ head, body }); } else pre; return .{ .decl = d, .function = fun, .here = here, .pre_m5 = pre }; @@ -165,7 +178,7 @@ fn attentionLaunch(a: std.mem.Allocator, device: mtl.Device, d: limits.MetalLaun if (std.mem.eql(u8, f.name, file)) break f.text; } else return error.UnknownLaunch; const pre = try preM5(a, "", text); - return .{ .decl = d, .function = fun, .here = if (tensor) try std.mem.replaceOwned(u8, a, text, "#include \"../nax.h\"", sources.nax) else pre, .pre_m5 = pre }; + return .{ .decl = d, .function = fun, .here = if (tensor) try tf.frags.source(device, a, text) else pre, .pre_m5 = pre }; } return .{ .decl = d, .function = fun, .here = sources.nemotron_glue, .pre_m5 = sources.nemotron_glue }; } @@ -185,13 +198,17 @@ fn pagedLaunch(a: std.mem.Allocator, device: mtl.Device, d: limits.MetalLaunch, } if (std.mem.indexOf(u8, d.name, " prompt ") != null) { const pre = try preM5(a, "", paged.prefill); - return .{ .decl = d, .function = fun, .here = if (tensor) try std.mem.replaceOwned(u8, a, paged.prefill, "#include \"../nax.h\"", sources.nax) else pre, .pre_m5 = pre }; + return .{ .decl = d, .function = fun, .here = if (tensor) try tf.frags.source(device, a, paged.prefill) else pre, .pre_m5 = pre }; } return .{ .decl = d, .function = fun, .here = paged.glue, .pre_m5 = paged.glue }; } /// One launch on this GPU: the pipeline's own thread limit and threadgroup bytes against its declaration. pub fn onThisGpu(a: std.mem.Allocator, device: mtl.Device, l: Launch, control: bool) !usize { + if (std.mem.indexOf(u8, l.here, "TF_ATTN_PV_FP32") != null) { + const full = std.mem.indexOf(u8, l.here, tf.frags.precision.define) != null; + std.debug.print("PRECISION limits {s}: shared P x V library {s}\n", .{ l.decl.name, if (full) "fp32" else "legacy" }); + } const p = rig_.pipeline(device, l.here, l.function) catch |err| { std.debug.print("{s} {s}: no pipeline on this GPU ({t})\n", .{ if (control) "RED " else "FAIL", l.decl.name, err }); return 1; diff --git a/zig/tests/contract/metal_main.zig b/zig/tests/contract/metal_main.zig index ad0158f04e6..441195c6f03 100644 --- a/zig/tests/contract/metal_main.zig +++ b/zig/tests/contract/metal_main.zig @@ -406,6 +406,9 @@ pub fn main(init: std.process.Init) !u8 { var nemotron_ssd: @import("metal_nemotron_ssd_gemm.zig").Suite = .{ .a = a, .device = device, .queue = queue, .kernels = &kernels }; defer nemotron_ssd.deinit(); try nemotron_ssd.collect(o.only); + var attention_pv: @import("metal_attention_pv.zig").Suite = .{}; + defer attention_pv.deinit(); + try attention_pv.collect(a, device, queue, &kernels, o.only); const weight_only = @import("metal_weight_only.zig"); const weight_source = try weight_only.text(a); defer a.free(weight_source); diff --git a/zig/tests/contract/metal_nemotron_attention.zig b/zig/tests/contract/metal_nemotron_attention.zig index b0d366c2167..41f6c8af08e 100644 --- a/zig/tests/contract/metal_nemotron_attention.zig +++ b/zig/tests/contract/metal_nemotron_attention.zig @@ -8,7 +8,6 @@ const rig_ = @import("rig.zig"); const c = contract.spec; const g = contract.gates; const ref = tf.attention_ref; - pub const D = 128; pub const kvh = 2; pub const heads = 32; @@ -16,7 +15,6 @@ pub const G = heads / kvh; const maxd = 64; // tf_tree_tail's MAXD const chunk = 512; // the partials' and the tail's keys a chunk pub const scale: f32 = 1.0 / @sqrt(@as(f32, D)); - /// decode: attn_partial_N then attn_merge; tree: a partial, tf_tree_tail and tf_tree_merge; prompt: tf_attention_nax. pub const Which = enum { decode, tree, prompt, write, put, compact }; @@ -104,11 +102,12 @@ fn stressValue(j: usize, n: usize) f32 { } /// A library's text as the engine builds it on this GPU, then the control's edit when asked. -fn built(a: std.mem.Allocator, device: mtl.Device, w: Which, text: []const u8, control: bool) ![]u8 { +fn built(a: std.mem.Allocator, device: mtl.Device, w: Which, text: []const u8, control: bool, full: ?bool) ![]u8 { const src = switch (w) { .decode => if (device.tensorUnits() or std.mem.indexOf(u8, text, "partial_direct") == null) try a.dupe(u8, text) else try tf.nemotron.simd_attention.forGeneration(a, device.generation(), text), .tree, .compact => if (device.tensorUnits()) try a.dupe(u8, text) else try std.mem.concat(a, u8, &.{ "#define TF_SIMD_LAYOUT 1\n", text }), - .prompt, .put => try tf.frags.source(device, a, text), + .prompt => if (full) |on| try tf.frags.sourceMode(device, a, text, on) else try tf.frags.source(device, a, text), + .put => try tf.frags.source(device, a, text), .write => try a.dupe(u8, text), }; if (!control) return src; @@ -128,8 +127,8 @@ fn prefillText(file: []const u8) ![]const u8 { return error.UnknownSource; } -fn compile(a: std.mem.Allocator, device: mtl.Device, w: Which, text: []const u8, control: bool, fun: []const u8) !mtl.Pipeline { - const t = try built(a, device, w, text, control); +fn compile(a: std.mem.Allocator, device: mtl.Device, w: Which, text: []const u8, control: bool, fun: []const u8, full: ?bool) !mtl.Pipeline { + const t = try built(a, device, w, text, control, full); defer a.free(t); return rig_.pipeline(device, t, fun); } @@ -140,6 +139,7 @@ pub const Probe = struct { which: Which, tiles: usize, control: bool, + prompt_full: ?bool = null, // an explicit contract mode; null uses the serving process mode pipes: [3]?mtl.Pipeline = .{ null, null, null }, // decode: partial, merge; tree: tail, merge; glue: the kernel partials: [16]?mtl.Pipeline = @splat(null), // the tree's prefix partial at 1 to 16 tiles prompts: [4]?mtl.Pipeline = @splat(null), // tf_attention_nax by (whole query blocks, whole key blocks) @@ -168,18 +168,18 @@ pub const Probe = struct { .decode => { var buf: [32]u8 = undefined; const k = try nemotronKernel(try std.fmt.bufPrint(&buf, "attn_partial_{d}", .{tiles})); - p.pipes[0] = try compile(a, device, .decode, k.source, control, k.function); + p.pipes[0] = try compile(a, device, .decode, k.source, control, k.function, null); const m = try nemotronKernel("attn_merge"); - p.pipes[1] = try compile(a, device, .decode, m.source, false, m.function); + p.pipes[1] = try compile(a, device, .decode, m.source, false, m.function, null); }, .tree => { - p.pipes[0] = try compile(a, device, .tree, sources.nemotron_tree, control, "tf_tree_tail"); - p.pipes[1] = try compile(a, device, .tree, sources.nemotron_tree, false, "tf_tree_merge"); + p.pipes[0] = try compile(a, device, .tree, sources.nemotron_tree, control, "tf_tree_tail", null); + p.pipes[1] = try compile(a, device, .tree, sources.nemotron_tree, false, "tf_tree_merge", null); }, .prompt => {}, - .write => p.pipes[0] = try compile(a, device, .write, sources.nemotron_glue, control, "tf_kv_write"), - .compact => p.pipes[0] = try compile(a, device, .compact, sources.nemotron_tree, control, "tf_kv_compact"), - .put => p.pipes[0] = try compile(a, device, .put, try prefillText("glue"), control, "custom_kernel_tf_kv_put_bfloat16_t_bfloat16_t_int32_t_bfloat16_t"), + .write => p.pipes[0] = try compile(a, device, .write, sources.nemotron_glue, control, "tf_kv_write", null), + .compact => p.pipes[0] = try compile(a, device, .compact, sources.nemotron_tree, control, "tf_kv_compact", null), + .put => p.pipes[0] = try compile(a, device, .put, try prefillText("glue"), control, "custom_kernel_tf_kv_put_bfloat16_t_bfloat16_t_int32_t_bfloat16_t", null), } return p; } @@ -346,7 +346,7 @@ pub const Probe = struct { if (p.pt() > 0 and p.partials[tiles - 1] == null) { var buf: [32]u8 = undefined; const k = try nemotronKernel(try std.fmt.bufPrint(&buf, "attn_partial_{d}", .{tiles})); - p.partials[tiles - 1] = try compile(p.a, p.rig.device, .decode, k.source, false, k.function); + p.partials[tiles - 1] = try compile(p.a, p.rig.device, .decode, k.source, false, k.function, null); } }, .prompt => { @@ -355,7 +355,7 @@ pub const Probe = struct { var buf: [160]u8 = undefined; const tag = [2]u8{ if (v >= 2) 't' else 'n', if (v % 2 == 1) 't' else 'n' }; const s = try std.fmt.bufPrint(&buf, "custom_kernel_tf_attention_nax_bf16_{c}_{c}_t_bfloat16_t_bfloat16_t_bfloat16_t_int32_t_float_bfloat16_t", .{ tag[0], tag[1] }); - p.prompts[v] = try compile(p.a, p.rig.device, .prompt, try prefillText("attention_nax"), p.control, s); + p.prompts[v] = try compile(p.a, p.rig.device, .prompt, try prefillText("attention_nax"), p.control, s, p.prompt_full); } }, else => unreachable, diff --git a/zig/tests/contract/metal_nemotron_prompt_range.zig b/zig/tests/contract/metal_nemotron_prompt_range.zig index 1bcc6ca692d..2ea5a3ac336 100644 --- a/zig/tests/contract/metal_nemotron_prompt_range.zig +++ b/zig/tests/contract/metal_nemotron_prompt_range.zig @@ -1,6 +1,7 @@ //! Nemotron's tf_attention_nax on the M5: attention_range at its arithmetic, fp32 P cut as the tensor units take it. const std = @import("std"); const mtl = @import("metal"); +const tf = @import("tensorfold"); const contract = @import("contract"); const old = @import("metal_nemotron_attention.zig"); const c = contract.spec; @@ -11,7 +12,13 @@ const D = old.D; /// P with the tensor units' cut; P spread over [0, 1]; that case without the cut; a non-finite value at a masked key. const Case = enum { cut, spread, cutless, masked }; -fn name(k: Case) []const u8 { +fn name(k: Case, full: bool) []const u8 { + if (full) return switch (k) { + .cut => "metal nemotron attention prompt nax, full fp32 P", + .spread => "metal nemotron attention prompt nax, full fp32 P spread over [0, 1]", + .cutless => "control: metal nemotron attention prompt nax, full fp32 P range with tensor-cut product", + .masked => "metal nemotron attention prompt nax, full fp32 P with a non-finite value at a masked key", + }; return switch (k) { .cut => "metal nemotron attention prompt nax", .spread => "metal nemotron attention prompt nax, P spread over [0, 1]", @@ -21,14 +28,16 @@ fn name(k: Case) []const u8 { } /// tf_attention_nax: 8 mma steps a score, fp32 SCALE * log2e, fast exp2; a 32-key block: 2 P x V steps, rescale, folds. -fn form(n: usize, cut: f64) ar.Form { +fn form(n: usize, cut: f64, full: bool) ar.Form { const blocks: f64 = @floatFromInt(n / 32 + 2); - return .{ .score = 9 * ar.mma_step, .fast_exp = true, .chunk_exp = false, .p_rel = 0, .p_cut = cut, .num = (2 * ar.mma_step + 1) * blocks + ar.mma_step + 2, .den = 3 * blocks + 6, .score_round = 4, .div = 2 }; + const product: f64 = if (full) 32 else 2 * ar.mma_step; + return .{ .score = 9 * ar.mma_step, .fast_exp = true, .chunk_exp = false, .p_rel = 0, .p_cut = cut, .num = (product + 1) * blocks + ar.mma_step + 2, .den = 3 * blocks + 6, .score_round = 4, .div = 2 }; } const Probe = struct { inner: old.Probe, case: Case, + full: bool, rig: *@import("rig.zig").Rig, point: []f64 = &.{}, half: []f64 = &.{}, @@ -101,7 +110,7 @@ const Probe = struct { const vf = buf[most * D .. 2 * most * D]; const w = buf[2 * most * D ..][0..most]; const tau = buf[2 * most * D + most ..][0..most]; - const cut: f64 = if (p.case == .cutless) 0 else ar.operand_cut; + const cut: f64 = if (p.full or p.case == .cutless) 0 else ar.operand_cut; var q: [D]f64 = undefined; for (0..old.kvh) |hk| { for (0..most * D) |i| { @@ -110,7 +119,7 @@ const Probe = struct { } for (0..in.rows) |qi| for (hk * old.G..(hk + 1) * old.G) |h| { const n = in.len + qi + 1; - const f = form(n, cut); + const f = form(n, cut, p.full); in.query(qi, h, &q); const o = in.outAt(qi, h); ar.head(&q, kf, vf, n, D, old.scale, f, w, tau, want[o..][0..D], p.half[o..][0..D]); @@ -149,15 +158,17 @@ pub const Suite = struct { /// Only on the tensor units, where the cut was measured; before the M5, attention_ref's bound stays. pub fn collect(s: *Suite, only: ?[]const u8) !void { if (!s.device.tensorUnits()) return; + const full = try tf.frags.precision.requested(); for (std.enums.values(Case)) |k| { - if (only) |o| if (std.mem.indexOf(u8, name(k), o) == null) continue; + if (only) |o| if (std.mem.indexOf(u8, name(k, full), o) == null) continue; const p = try s.a.create(Probe); errdefer s.a.destroy(p); - p.* = .{ .inner = try old.Probe.init(s.a, s.device, s.queue, .prompt, 1, false), .case = k, .rig = undefined }; + p.* = .{ .inner = try old.Probe.init(s.a, s.device, s.queue, .prompt, 1, false), .case = k, .full = full, .rig = undefined }; + p.inner.prompt_full = full and k != .cutless; p.rig = &p.inner.rig; try s.probes.append(s.a, p); var spec = old.spec(.prompt, 1, false); - spec.name = name(k); + spec.name = name(k, full); if (k == .masked) { spec.served = spec.served[0..1]; spec.known = .{ .gate = .nonfinite, .finding = "a non-finite value at a key masked for a row of its tile reaches that row as NaN (P = 0 times Inf inside the P x V mma)" };