diff --git a/CHANGELOG.md b/CHANGELOG.md index abab5307d36..17585e571be 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -27,6 +27,9 @@ Each release's page on GitHub has its notes and measurements. See [the 1.0.0 rel - Flash Next on HIP routes from the checkpoint's stored BF16 router rows, widened in the router kernel with the FP32 lane order kept, which saves 2.5 MiB of memory a layer with the same tokens (#1614). Thanks to @gilby. - The Metal vision towers' shard reader and the cluster planner's checkpoint reader check a safetensors header's length with core's `headerSize` before reading it, so a malformed or oversized header is refused before any large allocation (#1872). +- Qwen3.8-27B on Metal: `--slide` binds the shared Living Weights learner to the native forward and Metal backward, reserves trainer memory beside streams and invalidates in-place prompt reuse when weights move. Real-checkpoint lesson qualification is pending. + +- Qwen3.8-27B on Metal reads Living Weights neurons saved into a folder on CUDA and applies them in prompt chunks, verify windows and decode. Requests marked untaught skip the neurons, and a folder with no learned neurons keeps its original GPU work (#1568). - `serve --prompt-cache-disk DIR` is a shorter spelling of `--learn-conversations --learn-dir DIR`, with the same limits, spill and start-up line; giving it together with either legacy flag is refused (#1908). Thanks to @garvrao80. diff --git a/docs/living-weights.md b/docs/living-weights.md index 479ba6aa9f4..47f8742d8ea 100644 --- a/docs/living-weights.md +++ b/docs/living-weights.md @@ -27,11 +27,16 @@ The acceptance checks still decide what is kept on every run. for Nemotron, 10.6 GiB for Qwen3.8 Flash Next); on a Mac the trainer works on the model's own weights. - The Nemotron 3.5 Lightning MLX 4-bit checkpoint, or, on a GB10 only, the Qwen3.8 Flash Next MLX 4-bit group-32 checkpoint with its MTP head. Macs refuse `--slide` for Flash Next. +- Qwen3.8-27B MLX affine 4-bit group-64 folders can load saved CUDA neurons on Metal. The Metal trainer and + `--slide` use the same lesson gate as CUDA; real-checkpoint lesson, retention and served A/B qualification is pending. + See the [Metal learner checks](recipes/qwen27-living-weights-metal.md). - A TensorFold build with the pocket learner described here (the release after 1.0.6). A folder taught by 1.0.3 to 1.0.6 still serves and answers from what it learned, but `--slide` refuses it: those releases saved lessons into the shared experts the pocket widens. Teach a fresh copy instead. -A Nemotron folder that learned on either backend serves on the other. +A Nemotron folder that learned on either backend serves on the other. Qwen3.8-27B uses the same saved neuron +format on CUDA and Metal. A Metal server reserves its trainer memory before fitting its serving streams; an +untaught 27B server opened without `--slide` allocates no trainer. ## Quick start diff --git a/docs/recipes/qwen27-living-weights-metal.md b/docs/recipes/qwen27-living-weights-metal.md new file mode 100644 index 00000000000..b5befe5f671 --- /dev/null +++ b/docs/recipes/qwen27-living-weights-metal.md @@ -0,0 +1,178 @@ +# Qwen3.8-27B Living Weights on Metal + +The Metal engine uses the existing Qwen dense family description, pocket fitter, lesson acceptance checks, save +transaction and affine4 shard writer. It accepts the same 64-neuron SwiGLU pocket as CUDA. The original MLP codes, +scales and biases remain unchanged. Empty layers launch no pocket kernel, and untaught streams skip every pocket. + +The trainer is implemented with host checks and synthetic device fixtures. Fresh device execution, real-checkpoint +retention, restart, concurrent, resumed and drafted/plain checks are required before calling it qualified for learning. + +## Forward and backward + +The trainer runs the serving runner with fresh per-sequence states, one row at a time, as the dense CUDA trainer does. +It captures the native residuals, projections, prepared attention and DeltaNet rows, answer logits and recurrent checkpoints. +A pack holds at most 1,024 rows across eight sequences, with at most 512 input rows per sequence. Long conversation +keys use a separate, freshly admitted native cache. Target passes without a nudge still retain the residuals that the +shared pocket checks read. + +The Metal backward differentiates its own forward. Its DeltaNet rounds the convolution before SiLU, rounds the +sigmoid and activation, uses RMS-normalized Q/K with BF16 scales, rounds softplus and applies an output SiLU gate. +These gate and normalization derivatives follow this backend's forward. BF16 nodes use straight-through +input gradients. Reductions and transposed affine products accumulate in FP32; no FP32 operand is fed to an M5 MMA. +Attention differentiates its gate from the probability product, rather than reconstructing context from a rounded +gated BF16 row. The independent reference uses binary64, including central differences of the stated smooth nodes. +This does not claim a derivative of the discontinuous quantizer. + +The server reserves the trainer's future buffers before fitting streams, prompt frames, cache and the optional +Neural Engine share. An idle learner replaces that reservation with its actual allocations. A weight change clears +the prompt store and the native standing/rewind metadata, pending round and draft trees. Learning uses the lane host's +exclusive phase; it does not introduce a second serving scheduler. + +## Checks + +Build-only and host checks, without a GPU: + +```sh +zig build tf-qwen27-learning check-qwen27-speed-host test-qwen27-learning-host \ + test-qwen27-slide-flags-host test-qwen27-pocket-host test-qwen27-living-host \ + tf-qwen27-pocket tf-qwen27-untaught test-kernel-contract -Dcpu=apple_m1 +python3 tools/zig/metal_learning_sources.py --check +``` + +Run GPU checks only when the project's GPU queue permits them. The standalone test creates a small synthetic folder: + +```sh +zig-out/bin/tf-qwen27-learning zig-out/qwen27-learning-fixture +swiftc tools/zig/qwen27_learning_numeric.swift -o zig-out/bin/qwen27-learning-numeric +zig-out/bin/qwen27-learning-numeric . +zig-out/bin/qwen27-learning-numeric . --sigmoid-control +``` + +The final command must fail the gated-RMS gradient check. It substitutes the CUDA sigmoid derivative in the test's +source copy. The normal checks retain five identical runs, input/guard checks, FP64 references and their measured +errors. The native fixture checks serving/trainer logits, solo/packed loss, repeated gradients, no-nudge residuals, +open-pocket scaling and untaught streams. + +The native fixture is also reached through the Metal contract runner's `qwen27 learning` selection. Every learner +launch has a source-derived thread ceiling and a registered limits source. Bounded fixtures are not the complete +contract receipt; run the full Metal contract, its controls and the supported-chip limits before qualification. + +Real-model cells must use fresh writable copies, the unchanged CUDA lesson gate, original-folder hashes, +held-out wordings and unrelated prompts. Check taught-folder restart with and without `--slide`, drafted/plain, +concurrent/solo, resumed/fresh and untaught output equality. Record trainer time and peak memory separately from +ordinary serving speed. The transposed-gradient implementation keeps full FP32 arithmetic; whole-checkpoint +training latency is not established by the synthetic fixture. + +## Lesson work and timing + +Each learner row uses the same native stages and barriers, in one command buffer instead of one per four layers. +Its single-row round metadata lives on the stack. Serving retains its existing submission interval. Rows still run +in order and wait before the next row uploads shared metadata. This preserves the decode arithmetic; it does not +replace it with prompt matrix products. Prefix reuse is still disabled for this trainer. + +Only rows predicting an answer run the vocabulary projection, loss and head gradient. The other rows have zero loss +weight and their head input gradient is explicitly zero. Earlier layers still differentiate through every prompt row, +including attention and recurrent dependencies. Four independent affine-gradient rows share each weight decode, with +each row's original FP32 FMA sequence in increasing output-column order. The optimizer and lesson gate are unchanged. + +Set `TF_Q27_LEARN_DIAG=1` before starting the server to log every trainer pass: mode, sequences, full and answer rows, +wall time, forward planning/upload remainder, encoding, commit/wait and GPU spans, backward/loss encoding, commit/wait +and GPU spans, submission/wait counts, resets, and affine weight-decode/FMA counts. During output fitting a target pass is a packed Adam batch; +the server's outer "steps" counter does not count those batches. GPU spans are contained within completion waits; +they must not be added to wall time. Planning/upload is the forward wall remainder after encoding and completion. +The existing `slide pocket: round ...` line still reports read, fit, values, judge and check totals with rows/passes. + +Before measuring the full lesson, build and run the scalar replacement check on the GPU under its queue lock: + +```sh +swiftc tools/zig/qwen27_learning_affine.swift -o zig-out/bin/qwen27-learning-affine +zig-out/bin/qwen27-learning-affine . +zig-out/bin/qwen27-learning-affine . --reorder-control +``` + +The last command must fail. It reverses each output-column accumulation in the production source copy. The normal +check compares every output byte to the frozen scalar kernel, including partial row tiles, zero/nonfinite gradients, add/replace, +five repeats, unchanged inputs and guard bytes. These device checks and full-model timing remain required. + +## Full-checkpoint receipt runner + +`tools/zig/qwen27_living_ab.py` runs one owned server at a time on disposable, non-linked checkpoint copies. +Reserve the GPU exclusively for the entire invocation. It binds only loopback, uses a private temporary API key, +retains every request, response, token array, timing, refusal and process exit, and verifies the original files again. +A protocol fake checks the runner on the host; that fake executes no model arithmetic. + +Build the base binary from the pinned main and the candidate from this branch with identical settings. +Build the three device checkers above from the candidate. Supply a public prompt panel with at least four prompts, +including prose, code and a long prompt spanning multiple prompt chunks. The JSON panel is an array of strings +and must include a 2049-to-8192-token prompt after tokenization. +The default panel includes a long calibration prompt; all rendered cases must fit 8192 tokens. +Use the same context, parallelism, cache setting and qualified drafter in both arms. The runner requires nonzero +proposed and accepted drafts for each panel and each temperature; a draft flag alone cannot pass. + +```sh +python3 tools/zig/qwen27_living_ab.py \ + --base-binary BASE_BINARY --candidate-binary CANDIDATE_BINARY \ + --backend metal --checkpoint ORIGINAL_CHECKPOINT --checkpoint-revision CHECKPOINT_REVISION \ + --hardware 'GPU and RAM class' --runtime 'OS and runtime versions' \ + --pocket-binary zig-out/bin/tf-qwen27-pocket \ + --learning-binary zig-out/bin/tf-qwen27-learning \ + --untaught-binary zig-out/bin/tf-qwen27-untaught \ + --panel PUBLIC_PANEL.json --tokens 256 --reps 3 --output NEW_RECEIPT_DIRECTORY +``` + +Pass additional shared server arguments as a JSON argv array through `--server-args`; include the context, +parallelism, disabled prompt cache and qualified drafter settings. The default context is 8192 with four slots and +no prompt retention. Choose an adequate admitted context for the supplied panel. No host limits are raised. +The runner alternates main and candidate with `--slide` off, then checks an empty `--slide` folder, teaches a fixed +access-word fact, checks two held-out questions greedy and sampled, and requires unchanged unrelated token arrays. +It checks drafted/plain and concurrent/solo equality before and after teaching, after restart and after deletion. +It deletes through the existing endpoint, rolls the copy back through the existing CLI, and requires original subject +and unrelated token arrays again. All-vocabulary BF16 logit hashes compare up to 512 teacher-forced rows per case. +Full-prompt state and final logit hashes compare 128-row and native-capacity chunks. Both use untaught streams and +load models sequentially. The small device fixtures run only after the servers have closed. + +The default speed bound is zero slowdown in every cell's median HTTP wall time over three alternating repetitions. +Raw runtime counters are retained separately. Predeclare any measurement-noise allowance with `--max-slowdown-pct` +before running; a relaxed allowance must not be presented as the exact-speed gate. Run the full panel separately on +M3 Ultra and M5 Ultra. Record peak physical/device memory and full lesson time from the retained logs separately. +These receipts do not establish unmeasured prompt lengths, resumed state, cancellation or peer configurations. + +For portability, first run the same command on CUDA, omitting the three Metal device binaries and using CUDA binaries +and hardware/runtime labels. A producer invocation without `--from-other` deliberately exits incomplete after keeping +`portable-model/`; it cannot claim the two-way gate. Transfer that serving copy to the Metal test machine and pass +`--from-other CUDA_PORTABLE_MODEL`. Then run CUDA with `--from-other METAL_PORTABLE_MODEL`. Preserve both receipts. +Imported folders are served without learning or rollback; their historical backup metadata is not a portable undo log. +A complete receipt requires the other backend's folder, held-out recall, actual drafting and all equality checks. +A refusal, missing counters, failed checker or incomplete portability cell cannot become a passing summary. + +No real-checkpoint retention, speed or whole-model numerical qualification is implied by these commands. +The shared lesson acceptance checks and directional error limit remain unchanged. + +## Local backward checks + +`zig build test-qwen27-linear-host test-qwen27-learning-reference-host` runs without a device. +The loader check passes 2-, 3-, 4-, 5-, 6- and 8-bit projections through the actual linear builder, +including a rank slice, and compares every copied byte with the original views. + +`zig build tf-qwen27-learning-local` builds a bounded, checkpoint-free Metal panel. +Run `zig-out/bin/tf-qwen27-learning-local` under the machine's GPU lock. +The same panel is called by `tf-kernel-contract --only "qwen27 learning local" --no-limits`. +Its four source mutations contribute to the contract's control tally and a missed control fails the run. +Compile, launch, ownership or repeat errors fail the run; they never count as a caught numerical fault. + +Independent binary64 references cover pocket input adjoints with saved/open neuron scaling, raw affine4 input +adjoints with add mode and a ragged four-row batch, weighted partial-RoPE Q/K RMS adjoints, and all split outputs +of a five-row GDN recurrence across its four-row checkpoint. Every checked output repeats byte for byte five times, +all guards survive and inputs stay unchanged. The affine fixture's dyadic expression is exact; the other three +retain the existing local numerical panel's 2e-6 absolute allowance. These local fixture limits do not replace or +relax the whole-model directional rule or any declared compiler/resource limit. + +The host also checks independent smooth central slopes for the pocket, weighted RMS/RoPE and recurrence references. +Stored BF16 inputs are base nodes, not a differentiable quantizer. The recurrence's saved checkpoint offsets are +frozen at the base point for its local straight-through check. These are local mathematical checks, not proof of +real-checkpoint gradients through every served rounding point. The panel supplements the contract; it does not +claim all shapes, exceptional classes, accumulator witnesses or all 22 backward kernels are qualified. + +Before advertising learning, retain the complete whole-model directional panel, full contract and resource receipts, +pre-M5/M5 slide-off token and speed comparisons, the mixed-width release checkpoints, keep-rate and exact removal, +and the CUDA/Metal saved-folder round trip. Every refusal and every failed device cell remains in the receipts. diff --git a/tools/zig/metal_learning_sources.py b/tools/zig/metal_learning_sources.py new file mode 100644 index 00000000000..b889c07f34c --- /dev/null +++ b/tools/zig/metal_learning_sources.py @@ -0,0 +1,262 @@ +"""Emit Metal wrappers around the owned CUDA learner algebra; no model or compiler is invoked.""" +import argparse +import hashlib +import json +import re +from pathlib import Path + +ROOT = Path(__file__).resolve().parents[2] +VALUES = dict(DK=128, DV=128, TAPS=4, CK=4, SPLIT=4, ROWS=32, ATTN_KEYS=2048, WARPS=8) + + +def close_brace(text, start): + depth = 1 + at = start + 1 + while depth: + if text[at] == '{': + depth += 1 + elif text[at] == '}': + depth -= 1 + at += 1 + return at + + +def convert(text): + text = text.replace('__device__ __forceinline__', 'inline').replace('__restrict__', '') + text = text.replace('__bfloat162float', 'float').replace('__float2bfloat16_rn', 'bfloat').replace('__float2bfloat16', 'bfloat') + text = text.replace('__syncthreads()', 'threadgroup_barrier(mem_flags::mem_threadgroup)') + for before, after in [('expf', 'precise::exp'), ('sqrtf', 'precise::sqrt'), ('log1pf', 'tf_log1p'), + ('cosf', 'precise::cos'), ('sinf', 'precise::sin'), ('fmaxf', 'max'), ('make_float4', 'float4')]: + text = re.sub(r'\b'+before+r'\b', after, text) + text = re.sub(r'\bconst\s+(float4|float|bf16|unsigned|int)\s*\*', r'const device \1*', text) + text = re.sub(r'(? 0; mask >>= 1) v += simd_shuffle_xor(v, mask); + return v; + } + inline float warp_max(float v) { + for (ushort mask = 16; mask > 0; mask >>= 1) v = max(v, simd_shuffle_xor(v, mask)); + return v; + } + inline float block_sum_tree(float v, threadgroup float* scratch, int warps) { + const uint lane = threadIdx.x & 31, warp = threadIdx.x >> 5; + v = warp_sum(v); + if (lane == 0) scratch[warp] = v; + threadgroup_barrier(mem_flags::mem_threadgroup); + float total = warp == 0 && lane < uint(warps) ? scratch[lane] : 0.0f; + if (warp == 0) total = warp_sum(total); + if (threadIdx.x == 0) scratch[0] = total; + threadgroup_barrier(mem_flags::mem_threadgroup); + const float result = scratch[0]; + threadgroup_barrier(mem_flags::mem_threadgroup); + return result; + } + inline float block_max_tree(float v, threadgroup float* scratch, int warps) { + const uint lane = threadIdx.x & 31, warp = threadIdx.x >> 5; + v = warp_max(v); + if (lane == 0) scratch[warp] = v; + threadgroup_barrier(mem_flags::mem_threadgroup); + float total = warp == 0 && lane < uint(warps) ? scratch[lane] : -INFINITY; + if (warp == 0) total = warp_max(total); + if (threadIdx.x == 0) scratch[0] = total; + threadgroup_barrier(mem_flags::mem_threadgroup); + const float result = scratch[0]; + threadgroup_barrier(mem_flags::mem_threadgroup); + return result; + } +''' + + +def scratch(body): + count = 0 + def allocation(match): + nonlocal count + declarations = [] + for term in match[1].split(','): + term = term.strip() + name = re.match(r'\w+', term)[0] + dims = re.findall(r'\[([^]]+)\]', term) + size = 1 + for dim in dims: + size *= int(dim) if dim.isdecimal() else VALUES[dim] + offset = count + count += size + if not dims: + declarations.append(f'threadgroup float& {name} = shared[{offset}];') + elif len(dims) == 1: + declarations.append(f'threadgroup float* {name} = shared + {offset};') + else: + tail = ''.join('['+d+']' for d in dims[1:]) + declarations.append(f'threadgroup float (*{name}){tail} = reinterpret_cast(shared + {offset});') + return '\n '.join(declarations) + return re.sub(r'__shared__\s+float\s+([^;]+);', allocation, body), max(count, 1) + + +def native_policy(text, stem): + """STE through BF16 nodes; native deltanet.metal is the forward, never this recomputation.""" + if stem == 'attn_train': + before = 'dpq[at] = g * f32(gated[(size_t)r * qw + c]) * (1.0f - sg);' + assert before in text + # The rounded gated row cannot recover its pre-gate context. A separate native-probability product fills this. + return text.replace(before, 'dpq[at] = 0.0f;') + if stem != 'gdn_train': + return text + changes = [ + ('const float s = sigmoidf_(v);\n return s * (1.0f + v * (1.0f - s));', + 'v = bf(v);\n const float s = sigmoidf_(v);\n return bf(s) + v * s * (1.0f - s);'), + ('const float aq = conv_acc(P, hist, cw, r, cq, s), ak = conv_acc(P, hist, cw, r, ck, s);', + 'const float aq = bf(conv_acc(P, hist, cw, r, cq, s)), ak = bf(conv_acc(P, hist, cw, r, ck, s));'), + ('bf(aq / (1.0f + expf(-aq)))', 'bf(aq * bf(sigmoidf_(aq)))'), + ('bf(ak / (1.0f + expf(-ak)))', 'bf(ak * bf(sigmoidf_(ak)))'), + ('float inv = 1.0f / sqrtf(ss + 1e-6f);\n if (warp == 0) inv = inv * (1.0f / sqrtf((float)DK));', + 'const float inv = 1.0f / sqrtf(ss / float(DK) + 1e-6f);\n const float scale = warp == 0 ? bf(1.0f / float(DK)) : bf(1.0f / sqrtf(float(DK)));'), + ('out[i] = v4[i] * inv;', 'out[i] = bf(scale * bf(v4[i] * inv));'), + ('const float av = conv_acc(P, hist, cw, r, c, s);', 'const float av = bf(conv_acc(P, hist, cw, r, c, s));'), + ('b16(av / (1.0f + expf(-av)))', 'b16(av * bf(sigmoidf_(av)))'), + ('softplusf_(a + dt_bias[hv])', 'bf(max(bf(a + dt_bias[hv]), 0.0f) + log1pf(expf(-abs(bf(a + dt_bias[hv])))))'), + ('const float yn = bf(bf(yv * ri) * w);', 'const float yn = bf(yv * ri * w);'), + ('const float sg = sigmoidf_(f32(P[zc])), d = dout[row + t];\n dproj[zc] = d * yn * sg * (1.0f - sg);\n const float dn = d * sg * w;', + 'const float z = f32(P[zc]), sg = sigmoidf_(z), d = dout[row + t];\n dproj[zc] = d * yn * sg * (1.0f + z * (1.0f - sg));\n const float dn = d * z * sg * w;'), + ('const float* saved = ckpt + (size_t)h * nch * size + rb * DK;', 'const float* saved = ckpt + (size_t)h * size + rb * DK;'), + ('load_state(st, saved + c * size, warp, lane);', 'load_state(st, saved + (size_t)c * s.nv * size, warp, lane);'), + ('const float inv = 1.0f / sqrtf(ss + 1e-6f), sc = which == 0 ? 1.0f / sqrtf((float)DK) : 1.0f;', + 'const float inv = 1.0f / sqrtf(ss / float(DK) + 1e-6f), sc = which == 0 ? bf(1.0f / float(DK)) : bf(1.0f / sqrtf(float(DK)));'), + ('sc * inv * (d - inv * inv * x * dot);', 'sc * inv * (d - inv * inv * x * dot / float(DK));'), + ('x = f32(P[at + s.nv + h]) + dt_bias[h];', 'x = bf(f32(P[at + s.nv + h]) + dt_bias[h]);'), + ('sx = x > 20.0f ? 1.0f : sigmoidf_(x);', 'sx = sigmoidf_(x);'), + ] + for before, after in changes: + assert before in text, (stem, before) + text = text.replace(before, after) + return text + + +def owned_source(stem): + folder = ROOT/'zig/kernels/cuda' + path = folder/f'{stem}.cu' + original = path.read_text() + text = original + dependencies = {} + if stem == 'attn_train': + header = folder/'attn_back.cuh' + shared = header.read_text() + dependencies[str(header.relative_to(ROOT))] = hashlib.sha256(shared.encode()).hexdigest() + text = text.replace('#include "attn_back.cuh"', shared) + text = re.sub(r'^#define TF_ATTN_BACK.*$', '', text, flags=re.M) + text = re.sub(r'TF_ATTN_BACK\((\w+)\)', r'tf_attn_\1', text) + header = folder/'common/act.cuh' + helpers = header.read_text() + dependencies[str(header.relative_to(ROOT))] = hashlib.sha256(helpers.encode()).hexdigest() + for name in ('sigmoidf_', 'softplusf_', 'silu_grad'): + token = f'using tf_common::{name};' + if token in text: + found = re.search(r'__device__ __forceinline__ float '+name+r'\([^)]*\)\s*\{', helpers) + assert found, name + definition = helpers[found.start():close_brace(helpers, found.end()-1)] + text = text.replace(token, definition) + return original, text, dependencies + + +def emit(stem): + path = ROOT/'zig/kernels/cuda'/f'{stem}.cu' + original, owned, dependencies = owned_source(stem) + native = re.sub(r'\bhalf\b', 'rope_half', native_policy(owned, stem)) + bounds = {name: int(bound) for bound, name in re.findall(r'__launch_bounds__\(\s*(\d+)[^)]*\)\s*(\w+)', native)} + text = re.sub(r'//[^\n]*', '', native.replace('namespace {', '').replace('} // namespace', '')) + text = re.sub(r'^#include.*$', '', text, flags=re.M) + text = re.sub(r'^#pragma once.*$', '', text, flags=re.M) + text = re.sub(r'typedef __nv_bfloat16 bf16;', '', text) + text = re.sub(r'using tf_common::\w+;', '', text) + text = re.sub(r'__launch_bounds__\([^)]*\)', '', text) + shapes = [] + for match in list(re.finditer(r'struct (?:GdnShape|Heads)\s*\{[^}]*};', text)): + shapes.append(match[0]) + for shape in shapes: + text = text.replace(shape, '') + constants = re.findall(r'constexpr int [^;]+;', text) + for constant in constants: + text = text.replace(constant, '') + defines = re.findall(r'^#define .+$', text, flags=re.M) + for define in defines: + text = text.replace(define, '') + pattern = r'extern\s+"C"\s+__global__\s+void\s+(\w+)\s*\((.*?)\)\s*\{' + matches = list(re.finditer(pattern, text, re.S)) + assert matches + helpers = text[:matches[0].start()].strip() + methods, wrappers, metadata = [], [], [] + for match in matches: + name, signature = match[1], match[2] + used = {'gdn_train': {'tf_gdn_norm_back', 'tf_gdn_scan_back', 'tf_gdn_qk_back', 'tf_gdn_gates_back', 'tf_gdn_conv_back'}, + 'attn_train': {'tf_attn_q', 'tf_attn_gate_back', 'tf_attn_prep_back'}} + if name not in used[stem]: + continue + body = text[match.end():close_brace(text, match.end()-1)-1] + body, floats = scratch(body) + params = [] + pointer_args, scalar_args, calls = [], [], [] + for item in signature.split(','): + item = item.replace('__restrict__', '').strip() + arg = re.search(r'(\w+)$', item)[1] + ty = item[:item.rfind(arg)].strip() + params.append((ty,arg)) + if '*' in ty: + slot = len(pointer_args) + pointer_args.append(f'{convert(ty)} {arg} [[buffer({slot})]]') + calls.append(arg) + else: + scalar_args.append((ty,arg)) + calls.append('a.'+arg) + argument_struct = f'{name}_args' + fields = '\n'.join(f' {convert(ty)} {arg};' for ty,arg in scalar_args) + wrappers.append(f'struct {argument_struct} {{\n{fields}\n}};') + attributes = pointer_args+[f'constant {argument_struct}& a [[buffer({len(pointer_args)})]]', + 'uint3 threadIdx [[thread_position_in_threadgroup]]', + 'uint3 blockIdx [[threadgroup_position_in_grid]]', 'uint3 blockDim [[threads_per_threadgroup]]'] + wrappers.append(f'[[max_total_threads_per_threadgroup({bounds.get(name,256)})]]\nkernel void {name}(\n '+',\n '.join(attributes)+f') {{\n threadgroup float memory[{floats}];\n Context c = {{threadIdx, blockIdx, blockDim, memory}};\n c.{name}('+', '.join(calls)+');\n}') + methods.append(' void '+name+'('+convert(signature)+') {\n'+convert(body)+'\n }') + metadata.append(dict(name=name,pointers=[dict(type=t,name=n) for t,n in params if '*' in t], + scalars=[dict(type=t,name=n) for t,n in scalar_args],threadgroup_bytes=floats*4,max_threads=bounds.get(name,256))) + out = '// Owned learner algebra with generated Metal bindings; regenerate with tools/zig/metal_learning_sources.py.\n' + out += '#include \nusing namespace metal;\ntypedef bfloat bf16;\n' + out += '\n'.join(shapes)+'\n'+'\n'.join('constant '+v for v in constants)+'\n'+'\n'.join(defines)+'\n' + out += 'namespace tf_metal_learn {\nstruct Context {\n uint3 threadIdx, blockIdx, blockDim;\n threadgroup float* shared;\n' + out += ' inline float tf_log1p(float x) { return metal::log(1.0f + x); }\n'+REDUCE+convert(helpers)+'\n'+'\n'.join(methods)+'\n};\n}\n' + tail = 'using tf_metal_learn::Context;\n'+'\n'.join(wrappers)+'\n' + out = re.sub(r'\n\s*\n\s*\n', '\n\n', out) + out = '\n'.join(line.rstrip() for line in out.splitlines()) + '\n' + return out, tail, dict(source=str(path.relative_to(ROOT)),sha256=hashlib.sha256(original.encode()).hexdigest(),dependencies=dependencies,kernels=metadata) + + +def main(): + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument('--check', action='store_true', help='Refuse stale generated files without changing them') + args = parser.parse_args() + manifests = {} + files = {} + for source in ['gdn_train','attn_train']: + text, tail, meta = emit(source) + destination = ROOT/'zig/kernels/metal/qwen27'/f'{source}.metal' + files[destination] = f'#include "{source}_impl.h"\n#include "{source}_entries.h"\n' + files[destination.with_name(source+'_entries.h')] = tail + files[destination.with_name(source+'_impl.h')] = text + manifests[source] = meta + files[ROOT/'zig/kernels/metal/qwen27/learning-bindings.json'] = json.dumps(manifests,indent=2)+'\n' + for path, content in files.items(): + if args.check: + if path.read_text() != content: + parser.exit(1, 'stale generated source: '+str(path.relative_to(ROOT))+'\n') + else: + path.write_text(content) + print(path.relative_to(ROOT), 'checked' if args.check else 'generated') + + +if __name__ == '__main__': + main() diff --git a/tools/zig/qwen27_learning_affine.swift b/tools/zig/qwen27_learning_affine.swift new file mode 100644 index 00000000000..3db15d52b2f --- /dev/null +++ b/tools/zig/qwen27_learning_affine.swift @@ -0,0 +1,100 @@ +import Foundation +import Metal + +let root = URL(fileURLWithPath: CommandLine.arguments[1]) +let device = MTLCreateSystemDefaultDevice()! +let queue = device.makeCommandQueue()! +let options = MTLCompileOptions() +options.languageVersion = .version4_1 +options.mathMode = .safe +options.mathFloatingPointFunctions = .fast +var source = try String(contentsOf: root.appendingPathComponent("zig/kernels/metal/core/learn_linear.metal"), encoding: .utf8) +if CommandLine.arguments.contains("--reorder-control") { + source = source.replacingOccurrences(of: "for (uint out = 0; out < n; out++) {", with: "for (uint step = 0; step < n; step++) { const uint out = n - 1 - step;") +} +let reference = #""" +#include +using namespace metal; +struct learn_shape { uint4 u; float4 f; }; + +// A raw affine4 matrix's input gradient in full fp32, in output-column order; no relaxed float MMA operand. +[[max_total_threads_per_threadgroup(256)]] +kernel void tf_learn_q4_scalar(const device float* grad [[buffer(0)]], const device uint* words [[buffer(1)]], + const device bfloat* scales [[buffer(2)]], const device bfloat* biases [[buffer(3)]], + device float* dx [[buffer(4)]], constant learn_shape& p [[buffer(5)]], + uint i [[thread_position_in_grid]]) { + const uint rows = p.u.x, n = p.u.y, k = p.u.z; + if (i >= rows * k) return; + const uint row = i / k, column = i % k; + float sum = 0.0f; + for (uint out = 0; out < n; out++) { + const size_t at = size_t(out) * k + column; + const uint q = (words[at / 8] >> (4 * (column & 7))) & 15; + const size_t group = size_t(out) * (k / 64) + column / 64; + const float weight = float(scales[group]) * float(q) + float(biases[group]); + sum = fma(grad[size_t(row) * n + out], weight, sum); + } + dx[i] = p.u.w != 0 ? dx[i] + sum : sum; +} + +"""# +let fast = try device.makeLibrary(source: source, options: options) +let scalar = try device.makeLibrary(source: reference, options: options) +let pipelines = try [fast.makeFunction(name: "tf_learn_q4_back")!, scalar.makeFunction(name: "tf_learn_q4_scalar")!].map { + try device.makeComputePipelineState(function: $0) +} +func bytes(_ a: [T]) -> Data { a.withUnsafeBytes { Data($0) } } +func buffer(_ d: Data) -> MTLBuffer { + var guarded = d + guarded.append(Data(repeating: 0xa5, count: 64)) + return guarded.withUnsafeBytes { device.makeBuffer(bytes: $0.baseAddress!, length: guarded.count, options: .storageModeShared)! } +} +func snapshot(_ b: MTLBuffer) -> Data { Data(bytes: b.contents(), count: b.length) } +func bf(_ x: Float) -> UInt16 { + let u = x.bitPattern + return UInt16(truncatingIfNeeded: (u &+ 0x7fff &+ ((u >> 16) & 1)) >> 16) +} +var cases = 0 +var shapes = [1, 3, 4, 7, 8, 17].flatMap { rows in [17, 257, 521].flatMap { n in [64, 128].map { k in (rows, n, k, false) } } } +shapes += [(1024, 17, 64, false), (7, 248320, 64, false), (7, 17, 17408, false), (7, 257, 128, true)] +for (rows, n, k, plant) in shapes { for add in [0, 1] { + var gradient: [Float] = (0..(_ x:[T]) -> Data { x.withUnsafeBytes { Data($0) } } +func buffer(_ d:Data) -> MTLBuffer { + var all = d; all.append(Data(repeating:0xa5,count:64)) + return all.withUnsafeBytes { device.makeBuffer(bytes:$0.baseAddress!,length:all.count,options:.storageModeShared)! } +} +func fbuf(_ x:[Float]) -> MTLBuffer { buffer(data(x)) } +func zeros(_ n:Int) -> MTLBuffer { fbuf([Float](repeating:0,count:n)) } +func bf(_ f:Float) -> UInt16 { + let u=f.bitPattern + return UInt16(truncatingIfNeeded:(u &+ 0x7fff &+ ((u>>16)&1))>>16) +} +func fv(_ b:UInt16) -> Float { Float(bitPattern:UInt32(b)<<16) } +func bbuf(_ x:[Float]) -> MTLBuffer { buffer(data(x.map(bf))) } +func floats(_ b:MTLBuffer,_ n:Int) -> [Float] { Array(UnsafeBufferPointer(start:b.contents().assumingMemoryBound(to:Float.self),count:n)) } +func shape(_ u:[UInt32],_ f:[Float]=[0,0,0,0]) -> Data { data(u)+data(f) } +func run(_ name:String,_ b:[MTLBuffer],_ p:Data,_ groups:MTLSize,_ threads:Int=256) throws { + let cb=queue.makeCommandBuffer()!, e=cb.makeComputeCommandEncoder()!, pipeline=pipes[name]! + precondition(threads<=pipeline.maxTotalThreadsPerThreadgroup) + e.setComputePipelineState(pipeline) + for (i,x) in b.enumerated() { e.setBuffer(x,offset:0,index:i) } + p.withUnsafeBytes { e.setBytes($0.baseAddress!,length:p.count,index:b.count) } + e.dispatchThreadgroups(groups,threadsPerThreadgroup:MTLSize(width:threads,height:1,depth:1)) + e.endEncoding();cb.commit();cb.waitUntilCompleted() + if let err=cb.error { throw err } +} +func linear(_ name:String,_ b:[MTLBuffer],_ p:Data,_ n:Int) throws { try run(name,b,p,MTLSize(width:(n+255)/256,height:1,depth:1)) } +var results=[[String:Any]]() +func check(_ name:String,_ out:MTLBuffer,_ expected:[Double],_ tolerance:Double,_ inputs:[MTLBuffer],_ invoke:() throws -> Void) throws { + let before=inputs.map { Data(bytes:$0.contents(),count:$0.length) } + var first:Data?=nil, worst=0.0 + for _ in 0..<5 { + try invoke() + let values=floats(out,expected.count) + for (x,y) in zip(values,expected) { + if !x.isFinite || abs(Double(x)-y)>tolerance { fatalError("\(name): \(x) expected \(y), bound \(tolerance)") } + worst=max(worst,abs(Double(x)-y)) + } + let bytes=Data(bytes:out.contents(),count:out.length) + if let first { precondition(bytes==first,"repeat differs: \(name)") } else { first=bytes } + precondition(bytes.suffix(64)==Data(repeating:0xa5,count:64),"guard changed") + for (input,original) in zip(inputs,before) { precondition(Data(bytes:input.contents(),count:input.length)==original,"input changed") } + } + results.append(["name":name,"outputs":expected.count,"repeats":5,"worst_abs":worst,"bound":tolerance,"guards":true,"inputs_unchanged":true]) +} +// Full-fp32 affine input gradient. Every product and sum here is a dyadic exact float32 value. +do { + let R=3,N=17,K=64 + let grad=(0..>UInt32(4*(k%8)))&15 + expected[r*K+k] += Double(grad[r*N+n])*(Double(scales[n])*Double(code)+Double(biases[n])) + } } } + let inputs=[fbuf(grad),buffer(data(words)),bbuf(scales),bbuf(biases)], out=zeros(R*K) + try check("affine4 input gradient exact",out,expected,0,inputs) { + try linear("tf_learn_q4_back",inputs+[out],shape([UInt32(R),UInt32(N),UInt32(K),0]),((R+3)/4)*K) + } +} +// RMS input derivative against the independent binary64 expression, including a partial vector tail. +do { + let R=3,D=65,eps=Float(1e-6) + let x=(0..Double { gate/(1+exp(-gate))*up*g } + for r in 0..Double { delta*normalized*zz/(1+exp(-zz)) } + let fd=(objective(z+step)-objective(z-step))/(2*step) + worstFD=max(worstFD,abs(fd-expectedP[r*proj+conv+h*D+d])) + } + for d in 0..=from ? Double(scale) : 1.0 + let cg=sc*error*up*sigmoid*(1+gate*(1-sigmoid)),cu=sc*error*gate*sigmoid + for d in 0.. counts["drafted"]: + raise ValueError("accepted draft count exceeds proposals") + for key in total: + total[key] += counts[key] + if total["rounds"] == 0 or total["drafted"] == 0 or total["accepted"] == 0: + raise ValueError("drafted cell did not propose and accept drafts") + return total + + +def panel(server, args, tag): + plain = [] + for t in (0, 0.7): + rows = [ask(server, p, f"{tag}-solo-{t}-{i}", args, temperature=t) for i, p in enumerate(args.panel)] + drafted = [ask(server, p, f"{tag}-draft-{t}-{i}", args, True, t) for i, p in enumerate(args.panel)] + equal(rows, drafted, "drafted/plain") + write(server.root / f"{tag}-draft-counts-{t}.json", draft_activity(drafted)) + with ThreadPoolExecutor(max_workers=4) as pool: + concurrent = list(pool.map(lambda pair: ask(server, pair[1], f"{tag}-concurrent-{t}-{pair[0]}", args, + temperature=t), enumerate(args.panel))) + equal(rows, concurrent, "concurrent/solo") + plain.extend(rows) + write(server.root / (tag + ".json"), plain) + return plain + + +def session(args, binary, root, model, slide=False, graph=None): + root.mkdir() + return Server(args, binary, root, model, False, True, slide, graph) + + +def subject(server, args, tag): + return [ask(server, p, f"{tag}-{t}-{i}", args, temperature=t) + for t in (0, 0.7) for i, p in enumerate(HELD)] + + +def recall(server, args, tag): + rows = subject(server, args, tag) + if any(x["text"].strip().casefold().strip(".\"' ") != FACT["value"] for x in rows): + raise ValueError("a held-out question did not return only the access word") + return rows + + +def lesson(server, args): + raw = server.request("/v1/slide/learn", {"text": FACT["text"], "questions": [FACT["question"]]}) + (server.root / "lesson.sse").write_text(raw) + events = [json.loads(line[5:].strip()) for line in raw.splitlines() + if line.startswith("data:") and line[5:].strip() != "[DONE]"] + if any(line.strip() in ("event: failed", "event: error") for line in raw.splitlines()): + raise ValueError("lesson emitted a failure; its full SSE is retained") + graph = server.json("/v1/slide/graph") + write(server.root / "graph.json", graph) + kept = [f for f in graph.get("facts", []) if f.get("state") == "learned"] + if not raw.rstrip().endswith("data: [DONE]") or not kept or not any(e.get("saved") is True for e in events): + raise ValueError("lesson refused or did not finish saving; retained SSE and graph are authoritative") + if not any(e.get("recalled") is True for e in events): + raise ValueError("lesson has no successful recalled event") + return kept + + +def run_tool(binary, argv, root, marker): + with (root / "stdout.log").open("wb") as out: + result = subprocess.run([str(binary), *map(str, argv)], stdout=out, stderr=subprocess.STDOUT) + if result.returncode or marker not in (root / "stdout.log").read_text(errors="replace"): + raise ValueError("device checker failed or omitted its success marker: " + marker) + + +def run(args): + args.output.mkdir(parents=True) + sources = {str(args.checkpoint): manifest(args.checkpoint)} + if args.from_other: + sources[str(args.from_other)] = manifest(args.from_other) + write(args.output / "identity.json", {"backend": args.backend, "checkpoint_revision": args.checkpoint_revision, + "base_binary_sha256": digest(args.base_binary), "candidate_binary_sha256": digest(args.candidate_binary), + "runner_sha256": digest(Path(__file__)), "hardware": getattr(args, "hardware", "synthetic"), + "runtime": getattr(args, "runtime", "synthetic"), + "device_binary_sha256": {name: digest(value) for name, value in (("pocket", args.pocket_binary), ("learning", args.learning_binary), ("untaught", args.untaught_binary)) if value}, "source_manifests": sources, "panel": args.panel, + "server_args": args.server_args, "max_slowdown_pct": args.max_slowdown_pct, "repetitions": args.reps}) + result = {"complete": False, "checks": {}, "device_fixtures": "unchecked", "portable_input": "unchecked"} + try: + original = args.output / "untaught-model" + model = args.output / "learning-model" + copy_checkpoint(args.checkpoint, original, sources[str(args.checkpoint)]) + copy_checkpoint(args.checkpoint, model, sources[str(args.checkpoint)]) + measurements = {"base": [], "candidate": []} + reference = None + cases = None + for rep in range(args.reps): + order = ("base", "candidate") if rep % 2 == 0 else ("candidate", "base") + for arm in order: + binary = args.base_binary if arm == "base" else args.candidate_binary + with session(args, binary, args.output / f"{arm}-{rep}", original) as server: + ask(server, args.panel[0], "warmup", args) + rows = panel(server, args, "untaught") + if reference is None: + reference = rows + cases = [server.json("/tokenize", {"messages": [{"role": "user", "content": p}], + "chat_template_kwargs": {"enable_thinking": False}})["tokens"] + for p in [FACT["question"], *HELD, *args.panel]] + if not any(len(ids) > 2048 for ids in cases) or any(len(ids) > 8192 for ids in cases): + raise ValueError("panel must include a 2049-to-8192-token prompt; all cases must fit 8192 tokens") + equal(reference, rows, "untaught candidate/main/repeat") + measurements[arm].append([r["seconds"] for r in rows]) + write(args.output / "token-cases.json", cases) + slowdowns = [] + for i in range(len(reference)): + before = statistics.median(row[i] for row in measurements["base"]) + after = statistics.median(row[i] for row in measurements["candidate"]) + slowdowns.append(100 * (after / before - 1)) + result["timings"] = {"raw_seconds": measurements, "median_slowdown_pct_by_cell": slowdowns, + "limit_pct": args.max_slowdown_pct} + result["checks"]["untaught_tokens"] = True + result["checks"]["untaught_speed"] = all(v <= args.max_slowdown_pct for v in slowdowns) + graph = args.output / "lesson-graph.json" + with session(args, args.candidate_binary, args.output / "teach", model, True, graph) as server: + before = panel(server, args, "before") + before_held = subject(server, args, "before-held") + equal(reference, before, "slide on without lessons") + kept = lesson(server, args) + held = recall(server, args, "held") + after = panel(server, args, "after") + equal(before, after, "unrelated facts after lesson") + portable = args.output / "portable-model" + copy_checkpoint(model, portable, manifest(model)) + write(args.output / "portable-manifest.json", manifest(portable)) + with session(args, args.candidate_binary, args.output / "restart-off", model) as server: + equal(after, panel(server, args, "restart"), "taught off restart unrelated") + equal(held, recall(server, args, "restart-held"), "taught off restart held") + with session(args, args.candidate_binary, args.output / "restart-on", model, True, graph) as server: + equal(held, recall(server, args, "restart-held"), "taught on restart held") + for fact in kept: + raw = server.request("/v1/slide/fact/" + str(fact["id"]), {}, method="DELETE") + (server.root / f"delete-{fact['id']}.sse").write_text(raw) + remaining = server.json("/v1/slide/graph") + write(server.root / "after-delete.json", remaining) + if any(f.get("state") == "learned" for f in remaining.get("facts", [])): + raise ValueError("delete refused or retained a learned fact") + equal(reference, panel(server, args, "deleted"), "delete original equality") + deleted_held = subject(server, args, "deleted-held") + equal(before_held, deleted_held, "delete subject original equality") + rollback = args.output / "rollback" + rollback.mkdir() + with (rollback / "stdout.log").open("wb") as out: + subprocess.run([str(args.candidate_binary), "slide", "rollback", str(model)], check=True, + stdout=out, stderr=subprocess.STDOUT) + with session(args, args.candidate_binary, args.output / "rolled-back", model) as server: + equal(reference, panel(server, args, "rolled-back"), "rollback original equality") + rolled_held = subject(server, args, "rolled-held") + equal(before_held, rolled_held, "rollback subject original equality") + result["checks"].update(lesson=True, restart=True, delete=True, rollback=True, + drafts_and_concurrent=True, slide_on_untaught=True) + if args.backend == "metal": + for name, binary, argv, marker in [ + ("pocket", args.pocket_binary, [args.output / "pocket-data"], "Q27_POCKET compared="), + ("learning", args.learning_binary, [args.output / "learning-data"], "untaught_equal=true"), + ("untaught", args.untaught_binary, [original, portable, args.output / "token-cases.json"], "logits_equal=true")]: + dest = args.output / (name + "-device") + dest.mkdir() + run_tool(binary, argv, dest, marker) + result["device_fixtures"] = "pass" + if args.from_other: + imported = args.output / "imported-model" + copy_checkpoint(args.from_other, imported, sources[str(args.from_other)]) + with session(args, args.candidate_binary, args.output / "imported", imported) as server: + recall(server, args, "portable-held") + equal(reference, panel(server, args, "portable"), "portable unrelated original equality") + result["portable_input"] = "pass" + if args.backend == "metal": + dest = args.output / "imported-untaught-device" + dest.mkdir() + run_tool(args.untaught_binary, [original, imported, args.output / "token-cases.json"], dest, "logits_equal=true") + result["complete"] = all(result["checks"].values()) and result["portable_input"] == "pass" + if args.backend == "metal": + result["complete"] = result["complete"] and result["device_fixtures"] == "pass" + except Exception as exc: + result["error"] = str(exc) + raise + finally: + unchanged = {root: manifest(Path(root)) == expected for root, expected in sources.items()} + result["originals_unchanged"] = unchanged + result["complete"] = result["complete"] and all(unchanged.values()) + write(args.output / "summary.json", result) + if not all(unchanged.values()): + raise ValueError("an original checkpoint changed") + return result + + +def main(): + p = argparse.ArgumentParser(description=__doc__) + for name in ("base-binary", "candidate-binary", "checkpoint", "output"): + p.add_argument("--" + name, type=Path, required=True) + p.add_argument("--backend", choices=("metal", "cuda"), required=True) + p.add_argument("--checkpoint-revision", required=True) + p.add_argument("--hardware", required=True, help="Public GPU and RAM class, without host names") + p.add_argument("--runtime", required=True, help="OS, driver and runtime library versions") + p.add_argument("--from-other", type=Path, help="A portable-model produced by this runner on the other backend") + for name in ("pocket-binary", "learning-binary", "untaught-binary"): + p.add_argument("--" + name, type=Path) + p.add_argument("--panel", type=Path) + p.add_argument("--tokens", type=int, default=64) + p.add_argument("--reps", type=int, default=3) + p.add_argument("--max-slowdown-pct", type=float, default=0) + p.add_argument("--port", type=int, default=8080) + p.add_argument("--startup-timeout", type=float, default=900) + p.add_argument("--request-timeout", type=float, default=86400) + p.add_argument("--server-args", default='["--context","8192","--parallel","4","--prompt-cache-gib","0"]') + args = p.parse_args() + args.server_args = json.loads(args.server_args) + args.panel = json.loads(args.panel.read_text()) if args.panel else PANEL + if not isinstance(args.panel, list) or len(args.panel) < 4 or not all(isinstance(v, str) and v for v in args.panel): + p.error("panel must contain at least four nonempty public prompts") + if not isinstance(args.server_args, list) or not all(isinstance(v, str) for v in args.server_args): + p.error("server-args must be a JSON argv array") + reserved = {"--host", "--port", "--api-key", "--api-key-file", "--backend", "--slide", "--slide-graph"} + if any(v.split("=", 1)[0] in reserved for v in args.server_args): + p.error("server-args cannot override process ownership or slide settings") + if args.tokens < 2 or args.reps < 3 or not math.isfinite(args.max_slowdown_pct) or args.max_slowdown_pct < 0: + p.error("tokens >= 2, reps >= 3 and a finite nonnegative slowdown limit are required") + for name in ("base_binary", "candidate_binary", "checkpoint", "output", "from_other", "pocket_binary", "learning_binary", "untaught_binary"): + value = getattr(args, name) + if value is not None: + setattr(args, name, value.resolve()) + if args.output.exists() or any(root and (args.output == root or root in args.output.parents) + for root in (args.checkpoint, args.from_other)): + p.error("output must be new and outside every source checkpoint") + if args.backend == "metal" and not all((args.pocket_binary, args.learning_binary, args.untaught_binary)): + p.error("Metal needs the three built device checkers") + summary = run(args) + if not summary["complete"]: + p.exit(1, "incomplete or failed gate; inspect summary.json (the portable folder is retained)\n") + + +if __name__ == "__main__": + main() diff --git a/tools/zig/qwen27_living_fake.py b/tools/zig/qwen27_living_fake.py new file mode 100755 index 00000000000..ead09cb4961 --- /dev/null +++ b/tools/zig/qwen27_living_fake.py @@ -0,0 +1,89 @@ +#!/usr/bin/env python3 +"""Protocol-only owned-process fixture for the lesson runner; it implements no model or GPU arithmetic.""" +import hashlib +from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer +import json +from pathlib import Path +import sys + + +def main(): + args = sys.argv[1:] + if args and args[0] != "serve" and args[0] != "slide": + print("Q27_POCKET compared=1 untaught_equal=true logits_equal=true") + return + if args[:2] == ["slide", "rollback"]: + model = Path(args[2]) + (model / "state.json").write_text('{"learned":false}') + return + model = Path(args[1]) + port = int(args[args.index("--port") + 1]) + graph = Path(args[args.index("--slide-graph") + 1]) + fault = args[args.index("--fake-fault") + 1] if "--fake-fault" in args else "none" + + def state(): + return json.loads((model / "state.json").read_text()).get("learned", False) + + class Handler(BaseHTTPRequestHandler): + def log_message(self, *_): + pass + + def send(self, body, kind="application/json"): + data = body.encode() if isinstance(body, str) else json.dumps(body).encode() + self.send_response(200) + self.send_header("Content-Type", kind) + self.send_header("Content-Length", str(len(data))) + self.end_headers() + self.wfile.write(data) + + def body(self): + return json.loads(self.rfile.read(int(self.headers.get("Content-Length", 0))) or b"{}") + + def do_GET(self): + if self.path == "/health": + self.send({"ok": True}) + elif self.path == "/v1/slide/graph": + self.send({"facts": [{"id": 1, "state": "learned" if state() else "deleted"}] if state() or graph.exists() else []}) + else: + self.send_error(404) + + def do_POST(self): + body = self.body() + if self.path == "/tokenize": + self.send({"tokens": [3] * 4096 if "calibration words" in body["messages"][0]["content"] else [3, 5, 7]}) + elif self.path == "/v1/slide/learn": + if fault == "refused": + self.send('event: learned\ndata: {"recalled":false}\n\ndata: [DONE]\n\n', "text/event-stream") + return + (model / "state.json").write_text('{"learned":true}') + graph.write_text('{"facts":[{"id":1,"state":"learned"}]}') + self.send('event: learned\ndata: {"recalled":true}\n\nevent: saved\ndata: {"saved":true}\n\ndata: [DONE]\n\n', "text/event-stream") + elif self.path == "/v1/chat/completions": + prompt = body["messages"][0]["content"] + subject = "Veyra" in prompt + text = "taluno" if subject and state() else "unknown" if subject else "stable" + ids = list(text.encode()) + [int(body["temperature"] * 10)] + if fault == "draft" and body.get("draft"): + ids.append(91) + if fault == "disturb" and state() and not subject: + ids.append(92) + if fault == "import-disturb" and not subject and json.loads((model / "state.json").read_text()).get("imported"): + ids.append(93) + sha = hashlib.sha256(",".join(map(str, ids)).encode()).hexdigest() + self.send({"choices": [{"message": {"content": text}}], "tensorfold": {"token_ids": ids, "token_sha256": sha}, + "speculative": {"rounds": 3, "drafted": 0 if fault == "no-drafts" else 4, + "accepted": 0 if fault == "no-drafts" else 2}}) + else: + self.send_error(404) + + def do_DELETE(self): + self.body() + if fault != "delete": + (model / "state.json").write_text('{"learned":false}') + self.send('event: saved\ndata: {"saved":true}\n\ndata: [DONE]\n\n', "text/event-stream") + + ThreadingHTTPServer(("127.0.0.1", port), Handler).serve_forever() + + +if __name__ == "__main__": + main() diff --git a/tools/zig/qwen27_living_support.py b/tools/zig/qwen27_living_support.py new file mode 100644 index 00000000000..71f785406c0 --- /dev/null +++ b/tools/zig/qwen27_living_support.py @@ -0,0 +1,152 @@ +"""One owned native process at a time, with isolated checkpoint copies and retained HTTP receipts.""" +import hashlib +import http.client +import json +import os +from pathlib import Path +import secrets +import shutil +import socket +import subprocess +import sys +import time +import urllib.error +import urllib.request + + +def write(path, value): + path.write_text(json.dumps(value, indent=2, ensure_ascii=False) + "\n") + + +def digest(path): + h = hashlib.sha256() + with path.open("rb") as stream: + for block in iter(lambda: stream.read(8 * 1024 * 1024), b""): + h.update(block) + return h.hexdigest() + + +def manifest(root): + if not root.is_dir() or root.is_symlink(): + raise ValueError("checkpoint must be a real directory") + result = {} + for path in sorted(root.rglob("*")): + if path.is_symlink(): + raise ValueError("checkpoint must not contain symbolic links") + if path.is_file(): + result[str(path.relative_to(root))] = {"sha256": digest(path), "bytes": path.stat().st_size} + if not result: + raise ValueError("checkpoint is empty") + return result + + +def verify_copy(source, target, expected): + if any(p.is_symlink() for p in target.rglob("*")): + raise ValueError("checkpoint copy contains a symbolic link") + paths = [p for p in target.rglob("*") if p.is_file()] + if {str(p.relative_to(target)) for p in paths} != expected.keys(): + raise ValueError("checkpoint copy has a different file set") + for path in paths: + relative = str(path.relative_to(target)) + if path.is_symlink() or os.path.samestat((source / relative).stat(), path.stat()): + raise ValueError("checkpoint copy shares a source inode") + if path.stat().st_size != expected[relative]["bytes"]: + raise ValueError("checkpoint copy has a different file size") + + +def copy_checkpoint(source, target, expected): + target.mkdir() + command = (["cp", "-cR"] if sys.platform == "darwin" else ["cp", "-a", "--reflink=auto"]) + command += [str(source) + "/.", str(target)] + result = subprocess.run(command, stdout=subprocess.PIPE, stderr=subprocess.PIPE) + if result.returncode: + shutil.copytree(source, target, dirs_exist_ok=True) + verify_copy(source, target, expected) + + +class NoRedirect(urllib.request.HTTPRedirectHandler): + def redirect_request(self, req, fp, code, msg, headers, newurl): + raise ValueError("local experiment server redirected a request") + + +class Server: + def __init__(self, args, binary, root, model, thinking, seeded, slide, graph=None): + self.args, self.root = args, root + self.base = "http://127.0.0.1:" + str(args.port) + self.key = secrets.token_hex(24) + self.keyfile = root / "key" + with os.fdopen(os.open(self.keyfile, os.O_WRONLY | os.O_CREAT | os.O_EXCL, 0o600), "w") as stream: + stream.write(self.key + "\n") + self.command = [str(binary), "serve", str(model), "--host", "127.0.0.1", "--port", str(args.port), + "--api-key-file", str(self.keyfile), "--backend", args.backend, + "--slide-graph", str(graph or root / "graph.json"), *args.server_args] + if slide: + self.command.append("--slide") + if seeded: + self.command.append("--prompt-seed") + if not thinking: + self.command.append("--no-thinking") + self.opener = urllib.request.build_opener(urllib.request.ProxyHandler({}), NoRedirect()) + self.process, self.log = None, None + + def __enter__(self): + try: + with socket.socket() as reservation: + reservation.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1) + reservation.bind(("127.0.0.1", self.args.port)) + write(self.root / "command.json", self.command) + self.log = (self.root / "server.log").open("wb") + env = {k: v for k, v in os.environ.items() if not k.startswith("TF_SLIDE_")} + env["TENSORFOLD_LOG_TIME"] = "1" + self.process = subprocess.Popen(self.command, env=env, stdout=self.log, stderr=subprocess.STDOUT) + write(self.root / "process.json", {"pid": self.process.pid}) + deadline = time.monotonic() + self.args.startup_timeout + while True: + if self.process.poll() is not None: + raise RuntimeError("owned server exited during startup") + try: + self.request("/health", timeout=min(2, self.args.startup_timeout)) + break + except (OSError, urllib.error.URLError): + if time.monotonic() >= deadline: + raise TimeoutError("owned server did not become ready") + time.sleep(0.05) + return self + except BaseException: + self.close() + raise + + def request(self, route, body=None, timeout=None, method=None): + raw = None if body is None else json.dumps(body, ensure_ascii=False).encode() + req = urllib.request.Request(self.base + route, raw, method=method, headers={"Authorization": "Bearer " + self.key, + "Content-Type": "application/json"}) + try: + with self.opener.open(req, timeout=timeout or self.args.request_timeout) as response: + return response.read().decode() + except urllib.error.HTTPError as error: + (self.root / "http-error.txt").write_bytes(error.read()) + raise + except http.client.IncompleteRead as error: + (self.root / "http-incomplete.txt").write_bytes(error.partial) + raise + + def json(self, route, body=None): + return json.loads(self.request(route, body)) + + def close(self): + if self.process is not None: + if self.process.poll() is None: + self.process.terminate() + try: + self.process.wait(timeout=30) + except subprocess.TimeoutExpired: + self.process.kill() + self.process.wait(timeout=30) + write(self.root / "process.json", {"pid": self.process.pid, "exit": self.process.returncode}) + if self.log is not None: + self.log.close() + if self.keyfile.exists(): + self.keyfile.unlink() + + def __exit__(self, *_): + self.close() diff --git a/tools/zig/test_qwen27_living_ab.py b/tools/zig/test_qwen27_living_ab.py new file mode 100644 index 00000000000..ac240f2a6f1 --- /dev/null +++ b/tools/zig/test_qwen27_living_ab.py @@ -0,0 +1,65 @@ +"""Exercise the full runner on a protocol fake and keep every planted refusal visible.""" +import argparse +import hashlib +import json +from pathlib import Path +import socket +import tempfile +import unittest + +import qwen27_living_ab as runner + + +class RunnerTest(unittest.TestCase): + def test_hash_uses_the_server_decimal_comma_protocol(self): + ids = [1, 23, 456, 2**32 - 1] + sha = hashlib.sha256(",".join(map(str, ids)).encode()).hexdigest() + self.assertEqual(sha, runner.tokens({"tensorfold": {"token_ids": ids, "token_sha256": sha}})["sha256"]) + with self.assertRaises(ValueError): + runner.tokens({"tensorfold": {"token_ids": ids, "token_sha256": "incorrect"}}) + with self.assertRaises(ValueError): + runner.tokens({"tensorfold": {"token_ids": []}}) + + def args(self, root, fault="none"): + source, incoming = root / "source", root / "incoming" + source.mkdir() + incoming.mkdir() + (source / "state.json").write_text('{"learned":false}') + (incoming / "state.json").write_text('{"learned":true,"imported":true}') + fake = Path(__file__).with_name("qwen27_living_fake.py").resolve() + with socket.socket() as port: + port.bind(("127.0.0.1", 0)) + selected = port.getsockname()[1] + return argparse.Namespace(output=root / "out", checkpoint=source, from_other=incoming, backend="metal", + checkpoint_revision="synthetic", base_binary=fake, candidate_binary=fake, pocket_binary=fake, + learning_binary=fake, untaught_binary=fake, port=selected, startup_timeout=10, request_timeout=10, + server_args=["--fake-fault", fault], panel=list(runner.PANEL), reps=3, tokens=16, + max_slowdown_pct=1e9) + + def test_full_matrix_and_restart_delete_rollback_portability(self): + with tempfile.TemporaryDirectory() as folder: + args = self.args(Path(folder)) + result = runner.run(args) + self.assertTrue(result["complete"]) + self.assertEqual("pass", result["device_fixtures"]) + self.assertEqual("pass", result["portable_input"]) + self.assertTrue(all(result["originals_unchanged"].values())) + self.assertTrue((args.output / "portable-manifest.json").is_file()) + self.assertFalse(list(args.output.rglob("key"))) + for path in args.output.rglob("process.json"): + self.assertIn("exit", json.loads(path.read_text())) + + def test_bad_drafts_refusal_disturbance_and_delete_never_report_complete(self): + for fault in ("draft", "no-drafts", "refused", "disturb", "delete", "import-disturb"): + with self.subTest(fault=fault), tempfile.TemporaryDirectory() as folder: + args = self.args(Path(folder), fault) + with self.assertRaises(ValueError): + runner.run(args) + summary = json.loads((args.output / "summary.json").read_text()) + self.assertFalse(summary["complete"]) + self.assertTrue(all(summary["originals_unchanged"].values())) + self.assertFalse(list(args.output.rglob("key"))) + + +if __name__ == "__main__": + unittest.main() diff --git a/zig/build/cuda.zig b/zig/build/cuda.zig index aee1b1121fd..c1bb7e09ee8 100644 --- a/zig/build/cuda.zig +++ b/zig/build/cuda.zig @@ -253,6 +253,7 @@ pub fn hostTests(b: *std.Build, draft_ids: *std.Build.Module, build_options: *st b.step("test-living-host", "Family-neutral learner, saved form and commit gate on host").dependOn(&b.addRunArtifact(b.addTest(.{ .root_module = mods.living })).step); const shard_tests = b.createModule(.{ .root_source_file = b.path("zig/src/living_shards_test.zig"), .target = host, .optimize = .debug, .link_libc = true }); shard_tests.addImport("living", mods.living); + shard_tests.addImport("core", shard_tests); b.step("test-living-shards-host", "Quantized save and reopen through actual shard writer").dependOn(&b.addRunArtifact(b.addTest(.{ .root_module = shard_tests })).step); const writeback_contract = b.addRunArtifact(b.addTest(.{ .root_module = b.createModule(.{ .root_source_file = b.path("zig/tests/cuda/contract_flashnext_writeback.zig"), @@ -502,6 +503,7 @@ pub fn hostTests(b: *std.Build, draft_ids: *std.Build.Module, build_options: *st // Living Weights: the family-neutral learner, then the pocket in each family's shards over the core's shard files const living_run = b.addRunArtifact(b.addTest(.{ .root_module = mods.living })); const shards = b.createModule(.{ .root_source_file = b.path("zig/src/living_shards_test.zig"), .target = host, .optimize = .debug, .link_libc = true, .imports = &.{.{ .name = "living", .module = mods.living }} }); + shards.addImport("core", shards); const shards_run = b.addRunArtifact(b.addTest(.{ .root_module = shards })); step.dependOn(&living_run.step); step.dependOn(&shards_run.step); diff --git a/zig/build/qwen27.zig b/zig/build/qwen27.zig index 841e4c38ff5..b096e67cae3 100644 --- a/zig/build/qwen27.zig +++ b/zig/build/qwen27.zig @@ -16,15 +16,24 @@ pub const Shared = struct { }; /// The 27B's Metal sources, embedded by name (zig/kernels/metal/qwen27). -const parts = [_][]const u8{ "xsum", "norm_xs", "norm_input", "mlp_xs", "mlp_ane", "glue", "copy", "attention_mpp", "attention_io", "attention_prompt", "attention_prompt_sg", "prompt_glue", "prompt_state" }; +const parts = [_][]const u8{ "xsum", "norm_xs", "norm_input", "mlp_xs", "mlp_ane", "glue", "copy", "attention_mpp", "attention_io", "attention_prompt", "attention_prompt_sg", "prompt_glue", "prompt_state", "pocket", "learn_rows", "learn_linear", "gdn_train", "attn_train" }; /// The shared modules, imported into `engine` (whose `core` is itself) for the server and the release binary. pub fn engineModules(b: *std.Build, target: std.Build.ResolvedTarget, metal: *std.Build.Module, sources: *std.Build.Module, engine: *std.Build.Module) Shared { const files = b.addWriteFiles(); var index: []const u8 = ""; for (parts) |part| { - _ = files.addCopyFile(b.path(b.fmt("zig/kernels/metal/qwen27/{s}.metal", .{part})), b.fmt("{s}.metal", .{part})); - index = b.fmt("{s}pub const {s} = @embedFile(\"{s}.metal\");\n", .{ index, part, part }); + if (std.mem.eql(u8, part, "gdn_train") or std.mem.eql(u8, part, "attn_train")) { + for ([_][]const u8{ "impl", "entries" }) |suffix| { + const name = b.fmt("{s}_{s}.h", .{ part, suffix }); + _ = files.addCopyFile(b.path(b.fmt("zig/kernels/metal/qwen27/{s}", .{name})), name); + } + index = b.fmt("{s}pub const {s} = @embedFile(\"{s}_impl.h\") ++ \"\\n\" ++ @embedFile(\"{s}_entries.h\");\n", .{ index, part, part, part }); + } else { + const folder = if (std.mem.startsWith(u8, part, "learn_")) "core" else "qwen27"; + _ = files.addCopyFile(b.path(b.fmt("zig/kernels/metal/{s}/{s}.metal", .{ folder, part })), b.fmt("{s}.metal", .{part})); + index = b.fmt("{s}pub const {s} = @embedFile(\"{s}.metal\");\n", .{ index, part, part }); + } } _ = files.addCopyFile(b.path("zig/kernels/metal/core/deltanet.metal"), "gdn.metal"); _ = files.addCopyFile(b.path("zig/kernels/metal/core/deltanet_slots.metal"), "gdn_slots.metal"); @@ -41,6 +50,7 @@ pub fn engineModules(b: *std.Build, target: std.Build.ResolvedTarget, metal: *st .tree_commit = b.createModule(.{ .root_source_file = b.path("zig/src/core/tree_commit_gpu.zig"), .target = target, .optimize = .ReleaseSafe, .link_libc = true, .imports = &.{ .{ .name = "metal", .module = metal }, .{ .name = "tree_round", .module = tree_round }, .{ .name = "tree_commit_sources", .module = b.createModule(.{ .root_source_file = b.path("zig/tree_commit_sources.zig") }) } } }), .draft_ops = b.createModule(.{ .root_source_file = b.path("zig/src/core/draft_ops.zig"), .target = target, .optimize = .ReleaseSafe, .link_libc = true, .imports = &.{ .{ .name = "metal", .module = metal }, .{ .name = "draft_ops_sources", .module = b.createModule(.{ .root_source_file = b.path("zig/draft_ops_sources.zig") }) } } }), }; + if (!engine.import_table.contains("living")) engine.addImport("living", b.createModule(.{ .root_source_file = b.path("zig/src/living/living.zig"), .target = target, .optimize = .ReleaseSafe, .link_libc = true })); engine.addImport("core", engine); engine.addImport("core_delta", s.delta); engine.addImport("qwen_runtime_sources", s.runtime_sources); @@ -101,6 +111,7 @@ pub fn targets(b: *std.Build, target: std.Build.ResolvedTarget, optimize: std.bu const qwen_core = b.createModule(.{ .root_source_file = b.path("zig/qwen27_core.zig"), .target = target, .optimize = .ReleaseSafe, .link_libc = true, .imports = &.{ .{ .name = "metal", .module = metal }, .{ .name = "tokenizer", .module = b.createModule(.{ .root_source_file = b.path("zig/src/core/tokenizer/tokenizer.zig"), .target = target, .optimize = .ReleaseSafe, .link_libc = true }) } } }); const qwen27 = b.createModule(.{ .root_source_file = b.path("zig/src/families/qwen27/qwen27.zig"), .target = target, .optimize = .ReleaseSafe, .link_libc = true, .imports = &.{ .{ .name = "core", .module = qwen_core }, .{ .name = "metal", .module = metal } } }); + qwen27.addImport("living", engine.import_table.get("living").?); for ([_]struct { []const u8, *std.Build.Module }{ .{ "core", qwen_core }, .{ "core_lane", core_lane }, .{ "core_row", core_row }, .{ "bf16_topk", s.bf16_topk }, .{ "bf16_topk_gpu", s.bf16_topk_gpu }, .{ "tree_round", s.tree_round }, .{ "tree_round_gpu", s.tree_round_gpu }, .{ "tree_commit_gpu", s.tree_commit }, .{ "draft_ops", s.draft_ops }, .{ "kernel_sources", sources } }) |m| qwen_core.addImport(m[0], m[1]); for ([_]struct { []const u8, *std.Build.Module }{ .{ "core_lane", core_lane }, .{ "qwen_runtime_sources", s.runtime_sources }, .{ "core_delta", s.delta }, .{ "qwen_gdn_source", s.gdn_source } }) |m| qwen27.addImport(m[0], m[1]); for ([_]*std.Build.Module{ s.bf16_topk, s.tree_round, s.draft_ops }) |m| test_step.dependOn(&b.addRunArtifact(b.addTest(.{ .root_module = m })).step); diff --git a/zig/build/qwen27_host.zig b/zig/build/qwen27_host.zig index 68f47303d60..c47f6d8f9c4 100644 --- a/zig/build/qwen27_host.zig +++ b/zig/build/qwen27_host.zig @@ -1,6 +1,7 @@ //! Host regressions use no shaders, model or GPU execution. const std = @import("std"); pub fn tests(b: *std.Build, test_step: *std.Build.Step) void { + @import("qwen27_living_host.zig").tests(b); const real_metal = b.createModule(.{ .root_source_file = b.path("zig/src/metal/metal.zig"), .target = b.graph.host }); const recording = b.createModule(.{ .root_source_file = b.path("zig/qwen27_quant_metal.zig"), .target = b.graph.host, .imports = &.{.{ .name = "real_metal", .module = real_metal }} }); const quant_sources = b.createModule(.{ .root_source_file = b.path("zig/kernels/metal/sources.zig") }); @@ -19,6 +20,12 @@ pub fn tests(b: *std.Build, test_step: *std.Build.Step) void { const allocated = b.createModule(.{ .root_source_file = b.path("zig/qwen27_allocation_host.zig"), .target = b.graph.host, .link_libc = true, .imports = &.{.{ .name = "lanes", .module = pricing_lanes }} }); const window_step = b.step("test-qwen27-window-host", "Device width, copied trees and counted zero-grant drafting without shaders"); for ([_]*std.Build.Module{ window, taps, allocated }) |m| window_step.dependOn(&b.addRunArtifact(b.addTest(.{ .root_module = m })).step); + const identity = b.createModule(.{ .root_source_file = b.path("zig/tests/qwen27/learning_identity.zig"), .target = b.graph.host }); + b.step("test-qwen27-learning-identity-host", "Poisoned skipped-head storage and strict produced-row identity without a GPU").dependOn(&b.addRunArtifact(b.addTest(.{ .root_module = identity })).step); + const living = b.createModule(.{ .root_source_file = b.path("zig/src/living/living.zig"), .target = b.graph.host, .link_libc = true }); + const pocket = b.createModule(.{ .root_source_file = b.path("zig/qwen27_pocket_host.zig"), .target = b.graph.host, .optimize = .debug, .link_libc = true, .imports = &.{.{ .name = "living", .module = living }} }); + pocket.addImport("core", pocket); + b.step("test-qwen27-pocket-host", "CUDA-taught shard reader, original Metal width and untaught row runs without shaders").dependOn(&b.addRunArtifact(b.addTest(.{ .root_module = pocket })).step); const rows = b.createModule(.{ .root_source_file = b.path("zig/src/qwen27_rows_test.zig"), .target = b.graph.host }); b.step("test-qwen27-prompt-rows-host", "Device-aware prompt rows beside owned decoding streams without a GPU").dependOn(&b.addRunArtifact(b.addTest(.{ .root_module = rows, .filters = &.{"qwen27 rows:"} })).step); const ane_policy = b.createModule(.{ .root_source_file = b.path("zig/src/families/qwen27/ane_policy.zig"), .target = b.graph.host }); @@ -71,6 +78,12 @@ pub fn tests(b: *std.Build, test_step: *std.Build.Step) void { } pub fn compileHost(b: *std.Build, metal: *std.Build.Module, engine: *std.Build.Module, lanes: *std.Build.Module) void { + pocketProbe(b, metal); + @import("qwen27_learning_checks.zig").steps(b, metal, engine); + const learner = b.addExecutable(.{ .name = "tf-qwen27-learning", .root_module = b.createModule(.{ .root_source_file = b.path("zig/tests/qwen27/learning.zig"), .target = b.graph.host, .optimize = .ReleaseSafe, .link_libc = true, .imports = &.{ .{ .name = "metal", .module = metal }, .{ .name = "tensorfold", .module = engine } } }) }); + b.step("tf-qwen27-learning", "Build native forward/trainer identity and gradient checks without running a GPU").dependOn(&b.addInstallArtifact(learner, .{}).step); + const untaught = b.addExecutable(.{ .name = "tf-qwen27-untaught", .root_module = b.createModule(.{ .root_source_file = b.path("zig/tests/qwen27/untaught.zig"), .target = b.graph.host, .optimize = .ReleaseSafe, .link_libc = true, .imports = &.{ .{ .name = "metal", .module = metal }, .{ .name = "tensorfold", .module = engine } } }) }); + b.step("tf-qwen27-untaught", "Build sequential full-model untaught logit comparison without running it").dependOn(&b.addInstallArtifact(untaught, .{}).step); const api = b.createModule(.{ .root_source_file = b.path("zig/src/core/engine_api.zig"), .target = b.graph.host, .link_libc = true, .imports = &.{.{ .name = "lanes", .module = lanes }} }); const host = b.createModule(.{ .root_source_file = b.path("zig/src/native/qwen27_served.zig"), .target = b.graph.host, .link_libc = true, .imports = &.{ .{ .name = "metal", .module = metal }, .{ .name = "tensorfold", .module = engine }, .{ .name = "engine_api", .module = api } } }); const boundary = b.addTest(.{ .root_module = b.createModule(.{ .root_source_file = b.path("zig/qwen27_bank_boundary_host.zig"), .target = b.graph.host, .optimize = .debug, .link_libc = true, .imports = &.{ .{ .name = "tensorfold", .module = engine }, .{ .name = "metal", .module = metal } } }), .filters = &.{"qwen27 bank boundary:"} }); @@ -81,6 +94,11 @@ pub fn compileHost(b: *std.Build, metal: *std.Build.Module, engine: *std.Build.M b.step("test-qwen27-grants-host", "Native shared draft policy counts granted and proposed nodes without a GPU").dependOn(&b.addRunArtifact(b.addTest(.{ .root_module = grants })).step); const tree_host = b.addTest(.{ .root_module = engine, .filters = &.{"qwen27 window:"} }); b.step("test-qwen27-draft-tree-host", "Real selector 31-node tree and verify parents without a GPU").dependOn(&b.addRunArtifact(tree_host).step); + const learner_host = b.addTest(.{ .root_module = engine, .filters = &.{"qwen27 learning:"} }); + b.step("test-qwen27-learning-host", "Learner argument ABI, explicit memory reserve and weight epoch without devices").dependOn(&b.addRunArtifact(learner_host).step); + const metal_flags = b.createModule(.{ .root_source_file = b.path("zig/src/native/metal.zig"), .target = b.graph.host, .link_libc = true, .imports = &.{ .{ .name = "metal", .module = metal }, .{ .name = "tensorfold", .module = engine }, .{ .name = "engine_api", .module = api } } }); + const slide_flags = b.addTest(.{ .root_module = metal_flags, .filters = &.{"--slide admits"} }); + b.step("test-qwen27-slide-flags-host", "The actual Metal startup --slide family admission without loading a model").dependOn(&b.addRunArtifact(slide_flags).step); const object = b.addObject(.{ .name = "qwen27-speed-compile", .root_module = b.createModule(.{ .root_source_file = b.path("zig/qwen27_speed_compile.zig"), .target = b.graph.host, @@ -101,3 +119,16 @@ fn tryNames(b: *std.Build, names: *std.ArrayList([]const u8), text: []const u8) rest = rest[end + 1 ..]; } } + +fn pocketProbe(b: *std.Build, metal: *std.Build.Module) void { + const target = b.graph.host; + const core = b.createModule(.{ .root_source_file = b.path("zig/qwen27_pocket_core.zig"), .target = target, .optimize = .ReleaseSafe, .link_libc = true }); + core.addImport("metal", metal); + const files = b.addWriteFiles(); + _ = files.addCopyFile(b.path("zig/kernels/metal/qwen27/pocket.metal"), "pocket.metal"); + const sources = b.createModule(.{ .root_source_file = files.add("pocket_sources.zig", "pub const pocket = @embedFile(\"pocket.metal\");\n") }); + const pocket = b.createModule(.{ .root_source_file = b.path("zig/src/families/qwen27/pocket.zig"), .target = target, .optimize = .ReleaseSafe, .link_libc = true, .imports = &.{ .{ .name = "metal", .module = metal }, .{ .name = "core", .module = core }, .{ .name = "qwen_runtime_sources", .module = sources } } }); + const living = b.createModule(.{ .root_source_file = b.path("zig/src/living/living.zig"), .target = target, .optimize = .ReleaseSafe, .link_libc = true }); + const exe = b.addExecutable(.{ .name = "tf-qwen27-pocket", .root_module = b.createModule(.{ .root_source_file = b.path("zig/tests/qwen27/pocket.zig"), .target = target, .optimize = .ReleaseSafe, .link_libc = true, .imports = &.{ .{ .name = "metal", .module = metal }, .{ .name = "core", .module = core }, .{ .name = "living", .module = living }, .{ .name = "pocket", .module = pocket } } }) }); + b.step("tf-qwen27-pocket", "Build CUDA-taught folder and Metal pocket float64 checks without running a GPU").dependOn(&b.addInstallArtifact(exe, .{}).step); +} diff --git a/zig/build/qwen27_learning_checks.zig b/zig/build/qwen27_learning_checks.zig new file mode 100644 index 00000000000..1669d0bfc2e --- /dev/null +++ b/zig/build/qwen27_learning_checks.zig @@ -0,0 +1,12 @@ +//! Local backward references and counted real-source faults use the same served shader strings. +const std = @import("std"); +pub fn module(b: *std.Build, target: std.Build.ResolvedTarget, optimize: ?std.builtin.OptimizeMode, metal: *std.Build.Module, sources: *std.Build.Module, existing: ?*std.Build.Module) *std.Build.Module { + return b.createModule(.{ .root_source_file = b.path("zig/qwen27_learning_checks.zig"), .target = target, .optimize = optimize, .link_libc = true, .imports = &.{ .{ .name = "metal", .module = metal }, .{ .name = "learning_sources", .module = sources }, .{ .name = "contract", .module = existing orelse @import("kernel_contract.zig").module(b, target, .debug) } } }); +} +pub fn steps(b: *std.Build, metal: *std.Build.Module, engine: *std.Build.Module) void { + const checks = module(b, b.graph.host, .Debug, metal, engine.import_table.get("qwen_runtime_sources").?, null); + const run = b.addRunArtifact(b.addTest(.{ .root_module = checks })); + b.step("test-qwen27-learning-reference-host", "Independent binary64 local adjoints and source fault witnesses, no devices").dependOn(&run.step); + const exe = b.addExecutable(.{ .name = "tf-qwen27-learning-local", .root_module = b.createModule(.{ .root_source_file = b.path("zig/qwen27_learning_main.zig"), .target = b.graph.host, .optimize = .ReleaseSafe, .link_libc = true, .imports = &.{ .{ .name = "metal", .module = metal }, .{ .name = "checks", .module = checks } } }) }); + b.step("tf-qwen27-learning-local", "Build the bounded four-kernel backward panel without running it").dependOn(&b.addInstallArtifact(exe, .{}).step); +} diff --git a/zig/build/qwen27_living_host.zig b/zig/build/qwen27_living_host.zig new file mode 100644 index 00000000000..caa64f26751 --- /dev/null +++ b/zig/build/qwen27_living_host.zig @@ -0,0 +1,19 @@ +//! Actual portable pocket loading, row dispatch and allocation ownership without a device. +const std = @import("std"); +pub fn tests(b: *std.Build) void { + const target = b.graph.host; + const real = b.createModule(.{ .root_source_file = b.path("zig/src/metal/metal.zig"), .target = target }); + const metal = b.createModule(.{ .root_source_file = b.path("zig/qwen27_pocket_recording.zig"), .target = target, .imports = &.{.{ .name = "real_metal", .module = real }} }); + const core = b.createModule(.{ .root_source_file = b.path("zig/qwen27_living_core.zig"), .target = target, .link_libc = true, .imports = &.{.{ .name = "metal", .module = metal }} }); + const living = b.createModule(.{ .root_source_file = b.path("zig/src/living/living.zig"), .target = target, .link_libc = true }); + const sources = b.createModule(.{ .root_source_file = b.addWriteFiles().add("recording-pocket-source.zig", "pub const pocket = \"recorded, not compiled\";"), .target = target }); + const pocket = b.createModule(.{ .root_source_file = b.path("zig/src/families/qwen27/pocket.zig"), .target = target, .imports = &.{ .{ .name = "metal", .module = metal }, .{ .name = "core", .module = core }, .{ .name = "qwen_runtime_sources", .module = sources } } }); + const storage = b.createModule(.{ .root_source_file = b.path("zig/src/families/qwen27/pocket_storage.zig"), .target = target, .link_libc = true, .imports = &.{ .{ .name = "core", .module = core }, .{ .name = "living", .module = living } } }); + const root = b.createModule(.{ .root_source_file = b.path("zig/qwen27_living_host.zig"), .target = target, .link_libc = true, .imports = &.{ .{ .name = "metal", .module = metal }, .{ .name = "core", .module = core }, .{ .name = "living", .module = living }, .{ .name = "pocket", .module = pocket }, .{ .name = "storage", .module = storage } } }); + const run = b.addRunArtifact(b.addTest(.{ .root_module = root })); + run.has_side_effects = true; + b.step("test-qwen27-living-host", "Portable dense pocket I/O, actual dispatch and untouched stream rows without shaders").dependOn(&run.step); + const linear_core = b.createModule(.{ .root_source_file = b.path("zig/qwen27_linear_core.zig"), .target = target, .link_libc = true, .imports = &.{.{ .name = "metal", .module = metal }} }); + const linear = b.createModule(.{ .root_source_file = b.path("zig/qwen27_linear_host.zig"), .target = target, .link_libc = true, .imports = &.{ .{ .name = "metal", .module = metal }, .{ .name = "core", .module = linear_core } } }); + b.step("test-qwen27-linear-host", "Actual mixed-width linear loader and original row views without a pocket or GPU").dependOn(&b.addRunArtifact(b.addTest(.{ .root_module = linear, .filters = &.{"qwen27 linear:"} })).step); +} diff --git a/zig/build/sys.zig b/zig/build/sys.zig index 2c1dd3ebc1b..3b603718e01 100644 --- a/zig/build/sys.zig +++ b/zig/build/sys.zig @@ -35,6 +35,10 @@ const Walk = struct { const path = root.src_path.sub_path; if ((std.mem.endsWith(u8, path, "native/metal.zig") or std.mem.endsWith(u8, path, "tests/contract/metal_main.zig")) and !m.import_table.contains("qwen4")) @import("qwen4.zig").metalNative(w.b, target, m); + if (std.mem.endsWith(u8, path, "tests/contract/metal_main.zig") and !m.import_table.contains("qwen27_learning")) { + m.addImport("qwen27_learning", w.b.createModule(.{ .root_source_file = w.b.path("zig/tests/qwen27/learning.zig"), .target = target, .optimize = m.optimize, .link_libc = true, .imports = &.{ .{ .name = "metal", .module = m.import_table.get("metal").? }, .{ .name = "tensorfold", .module = m.import_table.get("tensorfold").? } } })); + m.addImport("qwen27_learning_checks", @import("qwen27_learning_checks.zig").module(w.b, target, m.optimize, m.import_table.get("metal").?, m.import_table.get("tensorfold").?.import_table.get("qwen_runtime_sources").?, m.import_table.get("contract"))); + } const needs_memory = std.mem.indexOf(u8, path, "flashnext") != null or std.mem.indexOf(u8, path, "residency") != null or std.mem.endsWith(u8, path, "cli/tests.zig") or std.mem.endsWith(u8, path, "src/tensorfold.zig") or std.mem.endsWith(u8, path, "cli/cli.zig") or diff --git a/zig/kernels/metal/core/learn_linear.metal b/zig/kernels/metal/core/learn_linear.metal new file mode 100644 index 00000000000..d4b743483e4 --- /dev/null +++ b/zig/kernels/metal/core/learn_linear.metal @@ -0,0 +1,72 @@ +#include +using namespace metal; +struct learn_shape { uint4 u; float4 f; }; + +// A raw affine4 matrix's input gradient in full fp32, in output-column order; no relaxed float MMA operand. +[[max_total_threads_per_threadgroup(256)]] +kernel void tf_learn_q4_back(const device float* grad [[buffer(0)]], const device uint* words [[buffer(1)]], + const device bfloat* scales [[buffer(2)]], const device bfloat* biases [[buffer(3)]], + device float* dx [[buffer(4)]], constant learn_shape& p [[buffer(5)]], + uint i [[thread_position_in_grid]]) { + const uint rows = p.u.x, n = p.u.y, k = p.u.z; + const uint row = (i / k) * 4, column = i % k; + if (row >= rows) return; + float s0 = 0.0f, s1 = 0.0f, s2 = 0.0f, s3 = 0.0f; + for (uint out = 0; out < n; out++) { + const size_t at = size_t(out) * k + column; + const uint q = (words[at / 8] >> (4 * (column & 7))) & 15; + const size_t group = size_t(out) * (k / 64) + column / 64; + const float weight = float(scales[group]) * float(q) + float(biases[group]); + s0 = fma(grad[size_t(row) * n + out], weight, s0); + if (row + 1 < rows) s1 = fma(grad[size_t(row + 1) * n + out], weight, s1); + if (row + 2 < rows) s2 = fma(grad[size_t(row + 2) * n + out], weight, s2); + if (row + 3 < rows) s3 = fma(grad[size_t(row + 3) * n + out], weight, s3); + } + const size_t at = size_t(row) * k + column; + dx[at] = p.u.w != 0 ? dx[at] + s0 : s0; + if (row + 1 < rows) dx[at + k] = p.u.w != 0 ? dx[at + k] + s1 : s1; + if (row + 2 < rows) dx[at + 2 * k] = p.u.w != 0 ? dx[at + 2 * k] + s2 : s2; + if (row + 3 < rows) dx[at + 3 * k] = p.u.w != 0 ? dx[at + 3 * k] + s3 : s3; +} + +// The grouped-query key/value gradients sum query heads, then query rows, in a fixed order. +[[max_total_threads_per_threadgroup(256)]] +kernel void tf_learn_attn_kv_back(const device bfloat* qkv [[buffer(0)]], const device float* dout [[buffer(1)]], + const device float* probability [[buffer(2)]], const device float* score_grad [[buffer(3)]], + device float* dk [[buffer(4)]], device float* dv [[buffer(5)]], + constant learn_shape& p [[buffer(6)]], uint i [[thread_position_in_grid]]) { + const uint rows = p.u.x, heads = p.u.y, kv_heads = p.u.z, dim = p.u.w; + const uint kw = kv_heads * dim, qw = heads * dim, stride = qw + 2 * kw; + if (i >= rows * kw) return; + const uint key = i / kw, h = i % kw / dim, d = i % dim, per = heads / kv_heads; + float key_grad = 0.0f, value_grad = 0.0f; + for (uint head = h * per; head < (h + 1) * per; head++) { + for (uint query = key; query < rows; query++) { + const size_t prob = (size_t(head) * rows + query) * rows + key; + key_grad = fma(score_grad[prob], float(qkv[size_t(query) * stride + head * dim + d]), key_grad); + value_grad = fma(probability[prob], dout[size_t(query) * qw + head * dim + d], value_grad); + } + } + dk[i] = key_grad * p.f.x; + dv[i] = value_grad; +} + +// Differentiate the output gate from P times V, without dividing a rounded gated BF16 value by its sigmoid. +[[max_total_threads_per_threadgroup(256)]] +kernel void tf_learn_attn_gate_grad(const device float* dgated [[buffer(0)]], const device bfloat* pq [[buffer(1)]], + const device bfloat* qkv [[buffer(2)]], const device float* probability [[buffer(3)]], + device float* dpq [[buffer(4)]], constant learn_shape& p [[buffer(5)]], + uint i [[thread_position_in_grid]]) { + const uint rows = p.u.x, heads = p.u.y, kv_heads = p.u.z, dim = p.u.w; + const uint qw = heads * dim, kw = kv_heads * dim, stride = qw + 2 * kw; + if (i >= rows * qw) return; + const uint row = i / qw, h = i % qw / dim, d = i % dim, kh = h / (heads / kv_heads); + float context = 0.0f; + for (uint j = 0; j <= row; j++) { + const float prob = probability[(size_t(h) * rows + row) * rows + j]; + context = fma(prob, float(qkv[size_t(j) * stride + qw + kw + kh * dim + d]), context); + } + const size_t at = size_t(row) * (2 * qw) + h * (2 * dim) + dim + d; + const float sigmoid = 1.0f / (1.0f + precise::exp(-float(pq[at]))); + dpq[at] = dgated[i] * context * sigmoid * (1.0f - sigmoid); +} diff --git a/zig/kernels/metal/core/learn_rows.metal b/zig/kernels/metal/core/learn_rows.metal new file mode 100644 index 00000000000..1314c2e118b --- /dev/null +++ b/zig/kernels/metal/core/learn_rows.metal @@ -0,0 +1,177 @@ +#include +using namespace metal; +struct learn_shape { uint4 u; float4 f; }; + +inline float learn_sum(float v, threadgroup float* scratch, uint t) { + v = simd_sum(v); + if ((t & 31) == 0) scratch[t >> 5] = v; + threadgroup_barrier(mem_flags::mem_threadgroup); + float total = t < 8 ? scratch[t] : 0.0f; + if (t < 32) total = simd_sum(total); + if (t == 0) scratch[0] = total; + threadgroup_barrier(mem_flags::mem_threadgroup); + const float result = scratch[0]; + threadgroup_barrier(mem_flags::mem_threadgroup); + return result; +} + +[[max_total_threads_per_threadgroup(256)]] +kernel void tf_learn_copy(const device uchar* x [[buffer(0)]], device uchar* y [[buffer(1)]], + constant learn_shape& p [[buffer(2)]], uint i [[thread_position_in_grid]]) { + const uint first = i * 16; + if (first >= p.u.x) return; + if (p.u.y != 0 && first + 16 <= p.u.x) { + *(device uint4*)(y + first) = *(const device uint4*)(x + first); + } else { + for (uint j = 0; j < 16 && first + j < p.u.x; j++) y[first + j] = x[first + j]; + } +} + +[[max_total_threads_per_threadgroup(256)]] +kernel void tf_learn_zero(device float* x [[buffer(0)]], constant learn_shape& p [[buffer(1)]], + uint i [[thread_position_in_grid]]) { + if (i < p.u.x) x[i] = 0.0f; +} + +[[max_total_threads_per_threadgroup(256)]] +kernel void tf_learn_nudge(device bfloat* x [[buffer(0)]], const device float* delta [[buffer(1)]], + constant learn_shape& p [[buffer(2)]], uint i [[thread_position_in_grid]]) { + if (i < p.u.x) x[i] = bfloat(float(x[i]) + delta[i]); +} + +// Gradient of mean answer loss: the native BF16 logits in, BF16-rounded fp32 gradient and loss/probability out. +[[max_total_threads_per_threadgroup(256)]] +kernel void tf_learn_loss(const device bfloat* logits [[buffer(0)]], const device uint* target [[buffer(1)]], + const device float* weight [[buffer(2)]], device float* grad [[buffer(3)]], + device float2* stats [[buffer(4)]], constant learn_shape& p [[buffer(5)]], + uint row [[threadgroup_position_in_grid]], uint t [[thread_index_in_threadgroup]]) { + threadgroup float scratch[8]; + const uint width = p.u.y; + const size_t base = size_t(row) * width; + float top = -INFINITY; + for (uint c = t; c < width; c += 256) top = max(top, float(logits[base + c])); + top = simd_max(top); + if ((t & 31) == 0) scratch[t >> 5] = top; + threadgroup_barrier(mem_flags::mem_threadgroup); + float high = t < 8 ? scratch[t] : -INFINITY; + if (t < 32) high = simd_max(high); + if (t == 0) scratch[0] = high; + threadgroup_barrier(mem_flags::mem_threadgroup); + top = scratch[0]; + threadgroup_barrier(mem_flags::mem_threadgroup); + float total = 0.0f; + for (uint c = t; c < width; c += 256) total += precise::exp(float(logits[base + c]) - top); + total = learn_sum(total, scratch, t); + for (uint c = t; c < width; c += 256) { + const float probability = precise::exp(float(logits[base + c]) - top) / total; + grad[base + c] = float(bfloat((probability - float(c == target[row])) * weight[row])); + } + if (t == 0) { + const float wanted = float(logits[base + target[row]]); + stats[row] = float2(precise::log(total) + top - wanted, precise::exp(wanted - top) / total); + } +} + +// The input gradient of RMS normalization adds to the residual stream's existing gradient. +[[max_total_threads_per_threadgroup(256)]] +kernel void tf_learn_rms_back(const device bfloat* x [[buffer(0)]], const device bfloat* gain [[buffer(1)]], + const device float* dy [[buffer(2)]], device float* grad [[buffer(3)]], + constant learn_shape& p [[buffer(4)]], uint row [[threadgroup_position_in_grid]], + uint t [[thread_index_in_threadgroup]]) { + threadgroup float scratch[8]; + const uint width = p.u.y; + const size_t base = size_t(row) * width; + float square = 0.0f, dot = 0.0f; + for (uint c = t; c < width; c += 256) { + const float v = float(x[base + c]); + square = fma(v, v, square); + dot = fma(v, float(gain[c]) * dy[base + c], dot); + } + square = learn_sum(square, scratch, t); + dot = learn_sum(dot, scratch, t); + const float inv = 1.0f / precise::sqrt(square / float(width) + p.f.x); + for (uint c = t; c < width; c += 256) { + const float g = inv * float(gain[c]) * dy[base + c]; + const float correction = inv * inv * inv * float(x[base + c]) * dot / float(width); + grad[base + c] += g - correction; + } +} + +// The packed gate/up rows have the same member order as the serving MLP. +[[max_total_threads_per_threadgroup(256)]] +kernel void tf_learn_swiglu_back(const device bfloat* gu [[buffer(0)]], const device float* da [[buffer(1)]], + device float* dgu [[buffer(2)]], constant learn_shape& p [[buffer(3)]], + uint i [[thread_position_in_grid]]) { + const uint width = p.u.y; + if (i >= p.u.x * width) return; + const size_t at = size_t(i / width) * (2 * width) + i % width; + const float gate = float(gu[at]), up = float(gu[at + width]); + const float sigmoid = 1.0f / (1.0f + precise::exp(-gate)); + dgu[at] = da[i] * up * sigmoid * (1.0f + gate * (1.0f - sigmoid)); + dgu[at + width] = da[i] * gate * sigmoid; +} + +// The pocket's contribution to its normalized input gradient, with the open neurons' per-sequence scale. +[[max_total_threads_per_threadgroup(256)]] +kernel void tf_learn_pocket_back(const device bfloat* x [[buffer(0)]], const device float* weights [[buffer(1)]], + const device float* grad [[buffer(2)]], device float* dx [[buffer(3)]], + constant learn_shape& p [[buffer(4)]], uint row [[threadgroup_position_in_grid]], + uint t [[thread_index_in_threadgroup]], uint lane [[thread_index_in_simdgroup]], + uint sg [[simdgroup_index_in_threadgroup]]) { + threadgroup float cg[64], cu[64]; + const uint width = p.u.y, n = p.u.z, cap = p.u.w; + const device float* gate = weights; + const device float* up = gate + size_t(cap) * width; + const device float* down = up + size_t(cap) * width; + const size_t base = size_t(row) * width; + for (uint j = sg; j < n; j += 8) { + float g = 0.0f, u = 0.0f, e = 0.0f; + for (uint c = lane; c < width; c += 32) { + const float value = float(x[base + c]); + g = fma(value, gate[size_t(j) * width + c], g); + u = fma(value, up[size_t(j) * width + c], u); + e = fma(grad[base + c], down[size_t(j) * width + c], e); + } + g = simd_sum(g); u = simd_sum(u); e = simd_sum(e); + const float sigmoid = 1.0f / (1.0f + precise::exp(-g)); + const float scale = j >= p.u.x ? p.f.x : 1.0f; + if (lane == 0) { + cg[j] = scale * e * u * sigmoid * (1.0f + g * (1.0f - sigmoid)); + cu[j] = scale * e * g * sigmoid; + } + } + threadgroup_barrier(mem_flags::mem_threadgroup); + for (uint c = t; c < width; c += 256) { + float change = 0.0f; + for (uint j = 0; j < n; j++) { + change = fma(cg[j], gate[size_t(j) * width + c], change); + change = fma(cu[j], up[size_t(j) * width + c], change); + } + dx[base + c] += change; + } +} + +// Widen actual native BF16 prepared rows; the recurrence backward consumes these, not a second forward. +[[max_total_threads_per_threadgroup(256)]] +kernel void tf_learn_widen(const device bfloat* x [[buffer(0)]], device float* y [[buffer(1)]], + constant learn_shape& p [[buffer(2)]], uint i [[thread_position_in_grid]]) { + if (i < p.u.x) y[i] = float(x[i]); +} + + +// Q/K conv activations before native RMS, with the native two BF16 SiLU nodes. V is captured directly. +[[max_total_threads_per_threadgroup(256)]] +kernel void tf_learn_gdn_act(const device bfloat* projection [[buffer(0)]], const device bfloat* conv [[buffer(1)]], + device bfloat* act [[buffer(2)]], constant learn_shape& p [[buffer(3)]], + uint2 i [[thread_position_in_grid]]) { + const uint c = i.x, row = i.y; + if (c >= p.u.y || row >= p.u.x) return; + float sum = 0.0f; + for (int tap = 0; tap < 4; tap++) { + const int at = int(row) - 3 + tap; + if (at >= 0) sum += float(conv[c * 4 + tap]) * float(projection[size_t(at) * p.u.z + c]); + } + const float rounded = float(bfloat(sum)); + const float sigmoid = float(bfloat(1.0f / (1.0f + metal::exp(-rounded)))); + act[size_t(row) * p.u.w + c] = bfloat(rounded * sigmoid); +} diff --git a/zig/kernels/metal/qwen27/attn_train.metal b/zig/kernels/metal/qwen27/attn_train.metal new file mode 100644 index 00000000000..578f4fb91be --- /dev/null +++ b/zig/kernels/metal/qwen27/attn_train.metal @@ -0,0 +1,2 @@ +#include "attn_train_impl.h" +#include "attn_train_entries.h" diff --git a/zig/kernels/metal/qwen27/attn_train_entries.h b/zig/kernels/metal/qwen27/attn_train_entries.h new file mode 100644 index 00000000000..a5517a5907e --- /dev/null +++ b/zig/kernels/metal/qwen27/attn_train_entries.h @@ -0,0 +1,67 @@ +using tf_metal_learn::Context; +struct tf_attn_q_args { + Heads a; +}; +[[max_total_threads_per_threadgroup(256)]] +kernel void tf_attn_q( + const device bf16* qkv [[buffer(0)]], + const device float* dout [[buffer(1)]], + device float* probs [[buffer(2)]], + device float* dscores [[buffer(3)]], + device float* dq [[buffer(4)]], + const device bf16* pk [[buffer(5)]], + const device bf16* pv [[buffer(6)]], + constant tf_attn_q_args& a [[buffer(7)]], + uint3 threadIdx [[thread_position_in_threadgroup]], + uint3 blockIdx [[threadgroup_position_in_grid]], + uint3 blockDim [[threads_per_threadgroup]]) { + threadgroup float memory[4640]; + Context c = {threadIdx, blockIdx, blockDim, memory}; + c.tf_attn_q(qkv, dout, probs, dscores, dq, a.a, pk, pv); +} +struct tf_attn_gate_back_args { + int heads; + int dim; +}; +[[max_total_threads_per_threadgroup(256)]] +kernel void tf_attn_gate_back( + const device float* dgated [[buffer(0)]], + const device bf16* gated [[buffer(1)]], + const device bf16* pq [[buffer(2)]], + device float* dout [[buffer(3)]], + device float* dpq [[buffer(4)]], + constant tf_attn_gate_back_args& a [[buffer(5)]], + uint3 threadIdx [[thread_position_in_threadgroup]], + uint3 blockIdx [[threadgroup_position_in_grid]], + uint3 blockDim [[threads_per_threadgroup]]) { + threadgroup float memory[1]; + Context c = {threadIdx, blockIdx, blockDim, memory}; + c.tf_attn_gate_back(dgated, gated, pq, dout, dpq, a.heads, a.dim); +} +struct tf_attn_prep_back_args { + int pos0; + int heads; + int kv_heads; + int dim; + int rope_half; + float eps; +}; +[[max_total_threads_per_threadgroup(256)]] +kernel void tf_attn_prep_back( + const device bf16* pq [[buffer(0)]], + const device bf16* pk [[buffer(1)]], + const device float* qscale [[buffer(2)]], + const device float* kscale [[buffer(3)]], + const device float* inv [[buffer(4)]], + const device float* dq [[buffer(5)]], + const device float* dk [[buffer(6)]], + device float* dpq [[buffer(7)]], + device float* dpk [[buffer(8)]], + constant tf_attn_prep_back_args& a [[buffer(9)]], + uint3 threadIdx [[thread_position_in_threadgroup]], + uint3 blockIdx [[threadgroup_position_in_grid]], + uint3 blockDim [[threads_per_threadgroup]]) { + threadgroup float memory[288]; + Context c = {threadIdx, blockIdx, blockDim, memory}; + c.tf_attn_prep_back(pq, pk, qscale, kscale, inv, a.pos0, dq, dk, dpq, dpk, a.heads, a.kv_heads, a.dim, a.rope_half, a.eps); +} diff --git a/zig/kernels/metal/qwen27/attn_train_impl.h b/zig/kernels/metal/qwen27/attn_train_impl.h new file mode 100644 index 00000000000..d2d2a2232c3 --- /dev/null +++ b/zig/kernels/metal/qwen27/attn_train_impl.h @@ -0,0 +1,168 @@ +// Owned learner algebra with generated Metal bindings; regenerate with tools/zig/metal_learning_sources.py. +#include +using namespace metal; +typedef bfloat bf16; +struct Heads { + int rows, heads, kv_heads, dim, qkv; + float scale; + int prefix; +}; + +#define ATTN_KEYS 2048 +namespace tf_metal_learn { +struct Context { + uint3 threadIdx, blockIdx, blockDim; + threadgroup float* shared; + inline float tf_log1p(float x) { return metal::log(1.0f + x); } + inline float warp_sum(float v) { + for (ushort mask = 16; mask > 0; mask >>= 1) v += simd_shuffle_xor(v, mask); + return v; + } + inline float warp_max(float v) { + for (ushort mask = 16; mask > 0; mask >>= 1) v = max(v, simd_shuffle_xor(v, mask)); + return v; + } + inline float block_sum_tree(float v, threadgroup float* scratch, int warps) { + const uint lane = threadIdx.x & 31, warp = threadIdx.x >> 5; + v = warp_sum(v); + if (lane == 0) scratch[warp] = v; + threadgroup_barrier(mem_flags::mem_threadgroup); + float total = warp == 0 && lane < uint(warps) ? scratch[lane] : 0.0f; + if (warp == 0) total = warp_sum(total); + if (threadIdx.x == 0) scratch[0] = total; + threadgroup_barrier(mem_flags::mem_threadgroup); + const float result = scratch[0]; + threadgroup_barrier(mem_flags::mem_threadgroup); + return result; + } + inline float block_max_tree(float v, threadgroup float* scratch, int warps) { + const uint lane = threadIdx.x & 31, warp = threadIdx.x >> 5; + v = warp_max(v); + if (lane == 0) scratch[warp] = v; + threadgroup_barrier(mem_flags::mem_threadgroup); + float total = warp == 0 && lane < uint(warps) ? scratch[lane] : -INFINITY; + if (warp == 0) total = warp_max(total); + if (threadIdx.x == 0) scratch[0] = total; + threadgroup_barrier(mem_flags::mem_threadgroup); + const float result = scratch[0]; + threadgroup_barrier(mem_flags::mem_threadgroup); + return result; + } +inline float f32(bf16 v) { return float(v); } +inline bf16 b16(float v) { return bfloat(v); } + +inline float sigmoidf_(float x) { return 1.0f / (1.0f + precise::exp(-x)); } + +inline void rope_cs(int pos, const device float* inv, int i, thread float& c, thread float& s) { + const float ang = (float)pos * inv[i]; + c = precise::cos(ang), s = precise::sin(ang); +} + void tf_attn_q( + const device bf16* qkv, const device float* dout, device float* probs, device float* dscores, device float* dq, Heads a, const device bf16* pk, + const device bf16* pv) { + + threadgroup float* qi = shared + 0; + threadgroup float* gi = shared + 256; + threadgroup float* sc = shared + 512; + threadgroup float* dp = shared + 2560; + threadgroup float* scratch = shared + 4608; + const int t = threadIdx.x, lane = t & 31, w = t >> 5, h = blockIdx.x, i = blockIdx.y; + const int kv = h / (a.heads / a.kv_heads), qw = a.heads * a.dim, kw = a.kv_heads * a.dim; + const int keys = a.prefix + a.rows, at = a.prefix + i; + const device bf16* k = qkv + qw; + const device bf16* v = qkv + qw + kw; + for (int d = t; d < a.dim; d += 256) { + qi[d] = f32(qkv[(size_t)i * a.qkv + h * a.dim + d]); + gi[d] = dout[(size_t)i * qw + h * a.dim + d]; + } + threadgroup_barrier(mem_flags::mem_threadgroup); + for (int j = w; j <= at; j += 8) { + const device bf16* kr = (j < a.prefix ? pk + (size_t)j * kw : k + (size_t)(j - a.prefix) * a.qkv) + kv * a.dim; + const device bf16* vr = (j < a.prefix ? pv + (size_t)j * kw : v + (size_t)(j - a.prefix) * a.qkv) + kv * a.dim; + float s = 0, g = 0; + for (int d = lane; d < a.dim; d += 32) { + s += qi[d] * f32(kr[d]); + g += gi[d] * f32(vr[d]); + } + s = warp_sum(s); + g = warp_sum(g); + if (lane == 0) sc[j] = s * a.scale, dp[j] = g; + } + threadgroup_barrier(mem_flags::mem_threadgroup); + float top = -INFINITY; + for (int j = t; j <= at; j += 256) top = max(top, sc[j]); + top = block_max_tree(top, scratch, 8); + float total = 0; + for (int j = t; j <= at; j += 256) { + const float e = precise::exp(sc[j] - top); + sc[j] = e; + total += e; + } + total = block_sum_tree(total, scratch, 8); + float mix = 0; + for (int j = t; j <= at; j += 256) { + sc[j] /= total; + mix += sc[j] * dp[j]; + } + mix = block_sum_tree(mix, scratch, 8); + const size_t row = ((size_t)h * a.rows + i) * keys; + for (int j = t; j < keys; j += 256) { + const bool live = j <= at; + const float p = live ? sc[j] : 0.0f, g = live ? p * (dp[j] - mix) : 0.0f; + if (live) dp[j] = g; + probs[row + j] = p; + dscores[row + j] = g; + } + threadgroup_barrier(mem_flags::mem_threadgroup); + for (int d = t; d < a.dim; d += 256) { + float acc = 0; + for (int j = 0; j <= at; j++) { + const device bf16* kr = j < a.prefix ? pk + (size_t)j * kw : k + (size_t)(j - a.prefix) * a.qkv; + acc += dp[j] * f32(kr[kv * a.dim + d]); + } + dq[(size_t)i * qw + h * a.dim + d] = acc * a.scale; + } + + } + void tf_attn_gate_back( + const device float* dgated, const device bf16* gated, const device bf16* pq, device float* dout, device float* dpq, int heads, int dim) { + + const int c = blockIdx.x * 256 + threadIdx.x, r = blockIdx.y, qw = heads * dim; + if (c >= qw) return; + const int h = c / dim, d = c % dim; + const size_t at = (size_t)r * 2 * qw + h * 2 * dim + dim + d; + const float sg = sigmoidf_(f32(pq[at])), g = dgated[(size_t)r * qw + c]; + dout[(size_t)r * qw + c] = g * sg; + dpq[at] = 0.0f; + + } + void tf_attn_prep_back( + const device bf16* pq, const device bf16* pk, const device float* qscale, const device float* kscale, const device float* inv, int pos0, + const device float* dq, const device float* dk, device float* dpq, device float* dpk, int heads, int kv_heads, int dim, int rope_half, float eps) { + + threadgroup float* go = shared + 0; + threadgroup float* scratch = shared + 256; + const int hd = blockIdx.x, r = blockIdx.y, d = threadIdx.x; + const int qw = heads * dim, kw = kv_heads * dim; + const bool q = hd < heads; + const float x = q ? f32(pq[(size_t)r * 2 * qw + hd * 2 * dim + d]) : f32(pk[(size_t)r * kw + (hd - heads) * dim + d]); + go[d] = q ? dq[(size_t)r * qw + hd * dim + d] : dk[(size_t)r * kw + (hd - heads) * dim + d]; + threadgroup_barrier(mem_flags::mem_threadgroup); + float gn = go[d]; + if (d < 2 * rope_half) { + float c, s; + rope_cs(pos0 + r, inv, d % rope_half, c, s); + gn = d < rope_half ? go[d] * c + go[d + rope_half] * s : go[d] * c - go[d - rope_half] * s; + } + const float w = (q ? qscale : kscale)[d]; + const float sq = block_sum_tree(x * x, scratch, dim / 32), dot = block_sum_tree(w * gn * x, scratch, dim / 32); + const float rinv = 1.0f / precise::sqrt(sq / (float)dim + eps); + const float g = rinv * w * gn - rinv * rinv * rinv * x * dot / (float)dim; + if (q) + dpq[(size_t)r * 2 * qw + hd * 2 * dim + d] = g; + else + dpk[(size_t)r * kw + (hd - heads) * dim + d] = g; + + } +}; +} diff --git a/zig/kernels/metal/qwen27/gdn_train.metal b/zig/kernels/metal/qwen27/gdn_train.metal new file mode 100644 index 00000000000..792b7a0d39b --- /dev/null +++ b/zig/kernels/metal/qwen27/gdn_train.metal @@ -0,0 +1,2 @@ +#include "gdn_train_impl.h" +#include "gdn_train_entries.h" diff --git a/zig/kernels/metal/qwen27/gdn_train_entries.h b/zig/kernels/metal/qwen27/gdn_train_entries.h new file mode 100644 index 00000000000..0c8b02445ab --- /dev/null +++ b/zig/kernels/metal/qwen27/gdn_train_entries.h @@ -0,0 +1,103 @@ +using tf_metal_learn::Context; +struct tf_gdn_norm_back_args { + GdnShape s; + float eps; +}; +[[max_total_threads_per_threadgroup(128)]] +kernel void tf_gdn_norm_back( + const device bf16* y [[buffer(0)]], + const device bf16* P [[buffer(1)]], + const device bf16* norm_w [[buffer(2)]], + const device float* dout [[buffer(3)]], + device float* dy [[buffer(4)]], + device float* dproj [[buffer(5)]], + constant tf_gdn_norm_back_args& a [[buffer(6)]], + uint3 threadIdx [[thread_position_in_threadgroup]], + uint3 blockIdx [[threadgroup_position_in_grid]], + uint3 blockDim [[threads_per_threadgroup]]) { + threadgroup float memory[161]; + Context c = {threadIdx, blockIdx, blockDim, memory}; + c.tf_gdn_norm_back(y, P, norm_w, dout, dy, dproj, a.s, a.eps); +} +struct tf_gdn_scan_back_args { + GdnShape s; + int from; +}; +[[max_total_threads_per_threadgroup(256)]] +kernel void tf_gdn_scan_back( + const device bf16* act [[buffer(0)]], + const device float* q [[buffer(1)]], + const device float* k [[buffer(2)]], + const device float* g [[buffer(3)]], + const device float* beta [[buffer(4)]], + const device float* ckpt [[buffer(5)]], + const device float* dy [[buffer(6)]], + device float* work [[buffer(7)]], + device float* dqp [[buffer(8)]], + device float* dkp [[buffer(9)]], + device float* dact [[buffer(10)]], + device float* dg [[buffer(11)]], + device float* dbeta [[buffer(12)]], + constant tf_gdn_scan_back_args& a [[buffer(13)]], + uint3 threadIdx [[thread_position_in_threadgroup]], + uint3 blockIdx [[threadgroup_position_in_grid]], + uint3 blockDim [[threads_per_threadgroup]]) { + threadgroup float memory[2384]; + Context c = {threadIdx, blockIdx, blockDim, memory}; + c.tf_gdn_scan_back(act, q, k, g, beta, ckpt, dy, work, dqp, dkp, dact, dg, dbeta, a.s, a.from); +} +struct tf_gdn_qk_back_args { + GdnShape s; +}; +[[max_total_threads_per_threadgroup(128)]] +kernel void tf_gdn_qk_back( + const device bf16* act [[buffer(0)]], + const device float* dqp [[buffer(1)]], + const device float* dkp [[buffer(2)]], + device float* dact [[buffer(3)]], + constant tf_gdn_qk_back_args& a [[buffer(4)]], + uint3 threadIdx [[thread_position_in_threadgroup]], + uint3 blockIdx [[threadgroup_position_in_grid]], + uint3 blockDim [[threads_per_threadgroup]]) { + threadgroup float memory[32]; + Context c = {threadIdx, blockIdx, blockDim, memory}; + c.tf_gdn_qk_back(act, dqp, dkp, dact, a.s); +} +struct tf_gdn_gates_back_args { + GdnShape s; +}; +[[max_total_threads_per_threadgroup(256)]] +kernel void tf_gdn_gates_back( + const device bf16* P [[buffer(0)]], + const device float* a_log [[buffer(1)]], + const device float* dt_bias [[buffer(2)]], + const device float* g [[buffer(3)]], + const device float* dg [[buffer(4)]], + const device float* dbeta [[buffer(5)]], + device float* dproj [[buffer(6)]], + constant tf_gdn_gates_back_args& a [[buffer(7)]], + uint3 threadIdx [[thread_position_in_threadgroup]], + uint3 blockIdx [[threadgroup_position_in_grid]], + uint3 blockDim [[threads_per_threadgroup]]) { + threadgroup float memory[1]; + Context c = {threadIdx, blockIdx, blockDim, memory}; + c.tf_gdn_gates_back(P, a_log, dt_bias, g, dg, dbeta, dproj, a.s); +} +struct tf_gdn_conv_back_args { + GdnShape s; +}; +[[max_total_threads_per_threadgroup(256)]] +kernel void tf_gdn_conv_back( + const device bf16* P [[buffer(0)]], + const device bf16* hist [[buffer(1)]], + const device bf16* cw [[buffer(2)]], + const device float* dact [[buffer(3)]], + device float* dproj [[buffer(4)]], + constant tf_gdn_conv_back_args& a [[buffer(5)]], + uint3 threadIdx [[thread_position_in_threadgroup]], + uint3 blockIdx [[threadgroup_position_in_grid]], + uint3 blockDim [[threads_per_threadgroup]]) { + threadgroup float memory[1]; + Context c = {threadIdx, blockIdx, blockDim, memory}; + c.tf_gdn_conv_back(P, hist, cw, dact, dproj, a.s); +} diff --git a/zig/kernels/metal/qwen27/gdn_train_impl.h b/zig/kernels/metal/qwen27/gdn_train_impl.h new file mode 100644 index 00000000000..20b247b6c05 --- /dev/null +++ b/zig/kernels/metal/qwen27/gdn_train_impl.h @@ -0,0 +1,356 @@ +// Owned learner algebra with generated Metal bindings; regenerate with tools/zig/metal_learning_sources.py. +#include +using namespace metal; +typedef bfloat bf16; +struct GdnShape { + int rows, nk, nv, conv, proj; +}; +constant constexpr int DK = 128, DV = 128, TAPS = 4; +constant constexpr int CK = 4; +constant constexpr int SPLIT = 4; +constant constexpr int ROWS = DV / SPLIT; +constant constexpr int WARPS = ROWS / 4; + +namespace tf_metal_learn { +struct Context { + uint3 threadIdx, blockIdx, blockDim; + threadgroup float* shared; + inline float tf_log1p(float x) { return metal::log(1.0f + x); } + inline float warp_sum(float v) { + for (ushort mask = 16; mask > 0; mask >>= 1) v += simd_shuffle_xor(v, mask); + return v; + } + inline float warp_max(float v) { + for (ushort mask = 16; mask > 0; mask >>= 1) v = max(v, simd_shuffle_xor(v, mask)); + return v; + } + inline float block_sum_tree(float v, threadgroup float* scratch, int warps) { + const uint lane = threadIdx.x & 31, warp = threadIdx.x >> 5; + v = warp_sum(v); + if (lane == 0) scratch[warp] = v; + threadgroup_barrier(mem_flags::mem_threadgroup); + float total = warp == 0 && lane < uint(warps) ? scratch[lane] : 0.0f; + if (warp == 0) total = warp_sum(total); + if (threadIdx.x == 0) scratch[0] = total; + threadgroup_barrier(mem_flags::mem_threadgroup); + const float result = scratch[0]; + threadgroup_barrier(mem_flags::mem_threadgroup); + return result; + } + inline float block_max_tree(float v, threadgroup float* scratch, int warps) { + const uint lane = threadIdx.x & 31, warp = threadIdx.x >> 5; + v = warp_max(v); + if (lane == 0) scratch[warp] = v; + threadgroup_barrier(mem_flags::mem_threadgroup); + float total = warp == 0 && lane < uint(warps) ? scratch[lane] : -INFINITY; + if (warp == 0) total = warp_max(total); + if (threadIdx.x == 0) scratch[0] = total; + threadgroup_barrier(mem_flags::mem_threadgroup); + const float result = scratch[0]; + threadgroup_barrier(mem_flags::mem_threadgroup); + return result; + } +inline float f32(bf16 v) { return float(v); } +inline bf16 b16(float v) { return bfloat(v); } +inline float bf(float x) { return f32(b16(x)); } + +inline float sigmoidf_(float x) { return 1.0f / (1.0f + precise::exp(-x)); } +inline float softplusf_(float x) { return x > 20.0f ? x : tf_log1p(precise::exp(x)); } + +inline float silu_grad(float v) { + v = bf(v); + const float s = sigmoidf_(v); + return bf(s) + v * s * (1.0f - s); +} + +inline int chunks(int rows) { return (rows + CK - 1) / CK; } + +inline float conv_acc(const device bf16* P, const device bf16* hist, const device bf16* cw, int r, int c, thread const GdnShape& s) { + float acc = 0.0f; +#pragma unroll + for (int tap = 0; tap < TAPS; ++tap) { + const int at = r - (TAPS - 1) + tap; + const float x = at >= 0 ? f32(P[(size_t)at * s.proj + c]) + : (hist != nullptr ? f32(hist[(size_t)(at + TAPS - 1) * s.conv + c]) : 0.0f); + acc = acc + f32(cw[c * TAPS + tap]) * x; + } + return acc; +} + +inline void load_state(thread float (&s)[4][4], const device float* base, int warp, int lane) { +#pragma unroll + for (int j = 0; j < 4; ++j) { + const float4 v = base != nullptr ? *reinterpret_cast(base + (warp * 4 + j) * DK + lane * 4) + : float4(0.0f, 0.0f, 0.0f, 0.0f); + s[j][0] = v.x; s[j][1] = v.y; s[j][2] = v.z; s[j][3] = v.w; + } +} + +inline void store_state(thread const float (&s)[4][4], device float* base, int warp, int lane) { +#pragma unroll + for (int j = 0; j < 4; ++j) + *reinterpret_cast(base + (warp * 4 + j) * DK + lane * 4) = float4(s[j][0], s[j][1], s[j][2], s[j][3]); +} + +inline void update(thread float (&s)[4][4], thread const float (&kk)[4], const threadgroup float* vrow, int warp, float g, + float beta) { +#pragma unroll + for (int j = 0; j < 4; ++j) { + float kv = 0.0f; +#pragma unroll + for (int i = 0; i < 4; ++i) { + s[j][i] = s[j][i] * g; + kv = kv + s[j][i] * kk[i]; + } + kv = warp_sum(kv); + const float delta = (vrow[warp * 4 + j] - kv) * beta; +#pragma unroll + for (int i = 0; i < 4; ++i) s[j][i] = s[j][i] + kk[i] * delta; + } +} + void tf_gdn_norm_back(const device bf16* y, const device bf16* P, + const device bf16* norm_w, const device float* dout, + device float* dy, device float* dproj, GdnShape s, + float eps) { + + const int r = blockIdx.x, h = blockIdx.y, t = threadIdx.x, warp = t >> 5, lane = t & 31; + threadgroup float* ys = shared + 0; + threadgroup float* scratch = shared + 128; + threadgroup float& rinv = shared[160]; + const size_t row = ((size_t)r * s.nv + h) * DV; + ys[t] = f32(y[row + t]); + threadgroup_barrier(mem_flags::mem_threadgroup); + if (warp == 0) { + float ss = 0.0f; +#pragma unroll + for (int i = 0; i < 4; ++i) { const float v = ys[lane * 4 + i]; ss = ss + v * v; } + ss = warp_sum(ss); + if (lane == 0) rinv = 1.0f / precise::sqrt(ss / (float)DV + eps); + } + threadgroup_barrier(mem_flags::mem_threadgroup); + const float w = f32(norm_w[t]), yv = ys[t], ri = rinv; + const float yn = bf(yv * ri * w); + const size_t zc = (size_t)r * s.proj + s.conv + h * DV + t; + const float z = f32(P[zc]), sg = sigmoidf_(z), d = dout[row + t]; + dproj[zc] = d * yn * sg * (1.0f + z * (1.0f - sg)); + const float dn = d * z * sg * w; + const float dot = block_sum_tree(yv * dn, scratch, 4); + dy[row + t] = ri * dn - ri * ri * ri * yv * dot / (float)DV; + + } + void tf_gdn_scan_back(const device bf16* act, const device float* q, + const device float* k, const device float* g, + const device float* beta, const device float* ckpt, + const device float* dy, device float* work, + device float* dqp, device float* dkp, + device float* dact, device float* dg, + device float* dbeta, GdnShape s, int from) { + + threadgroup float* qs = shared + 0; + threadgroup float* ks = shared + 128; + threadgroup float* vs = shared + 256; + threadgroup float* dos = shared + 288; + threadgroup float (*red_q)[DK] = reinterpret_cast(shared + 320); + threadgroup float (*red_k)[DK] = reinterpret_cast(shared + 1344); + threadgroup float* red_g = shared + 2368; + threadgroup float* red_b = shared + 2376; + const int h = blockIdx.x / SPLIT, part = blockIdx.x % SPLIT, rb = part * ROWS, hk = h / (s.nv / s.nk); + const int t = threadIdx.x, warp = t >> 5, lane = t & 31; + const size_t size = (size_t)DV * DK, mine_size = (size_t)ROWS * DK; + const int v0 = 2 * s.nk * DK + h * DV + rb, nch = chunks(s.rows); + const device float* saved = ckpt + (size_t)h * size + rb * DK; + device float* mine = work + (size_t)blockIdx.x * CK * mine_size; + float ds[4][4]; +#pragma unroll + for (int j = 0; j < 4; ++j) +#pragma unroll + for (int i = 0; i < 4; ++i) ds[j][i] = 0.0f; + for (int c = nch - 1; c >= from / CK; --c) { + const int first = c * CK, last = min(first + CK, s.rows); + { + + float st[4][4]; + load_state(st, saved + (size_t)c * s.nv * size, warp, lane); + float in_kv = 0.0f, in_g = 0.0f, in_b = 0.0f; + auto fetch = [&](int r) { + if (t < DK) in_kv = k[((size_t)r * s.nk + hk) * DK + t]; + else if (t < DK + ROWS) in_kv = f32(act[(size_t)r * s.conv + v0 + t - DK]); + in_g = g[r * s.nv + h]; + in_b = beta[r * s.nv + h]; + }; + if (first + 1 < last) fetch(first); + for (int r = first; r < last; ++r) { + store_state(st, mine + (r - first) * mine_size, warp, lane); + if (r + 1 == last) break; + if (t < DK) ks[t] = in_kv; + else if (t < DK + ROWS) vs[t - DK] = in_kv; + const float gg = in_g, bb = in_b; + threadgroup_barrier(mem_flags::mem_threadgroup); + if (r + 2 < last) fetch(r + 1); + float kk[4]; +#pragma unroll + for (int i = 0; i < 4; ++i) kk[i] = ks[lane * 4 + i]; + update(st, kk, vs, warp, gg, bb); + threadgroup_barrier(mem_flags::mem_threadgroup); + } + } + + float in_qk, in_vd = 0.0f, in_g, in_b; + auto fetch = [&](int r) { + in_qk = t < DK ? q[((size_t)r * s.nk + hk) * DK + t] : k[((size_t)r * s.nk + hk) * DK + t - DK]; + if (t < ROWS) in_vd = f32(act[(size_t)r * s.conv + v0 + t]); + else if (t < 2 * ROWS) in_vd = dy[((size_t)r * s.nv + h) * DV + rb + t - ROWS]; + in_g = g[r * s.nv + h]; + in_b = beta[r * s.nv + h]; + }; + fetch(last - 1); + for (int r = last - 1; r >= first; --r) { + if (t < DK) qs[t] = in_qk; + else ks[t - DK] = in_qk; + if (t < ROWS) vs[t] = in_vd; + else if (t < 2 * ROWS) dos[t - ROWS] = in_vd; + const float gg = in_g, bb = in_b; + threadgroup_barrier(mem_flags::mem_threadgroup); + if (r > first) fetch(r - 1); + float kk[4], qq[4], pq[4], pk[4], pg = 0.0f, pb = 0.0f; +#pragma unroll + for (int i = 0; i < 4; ++i) { + kk[i] = ks[lane * 4 + i]; + qq[i] = qs[lane * 4 + i]; + pq[i] = 0.0f; + pk[i] = 0.0f; + } + const device float* prev = mine + (r - first) * mine_size; + float4 p4[4]; +#pragma unroll + for (int j = 0; j < 4; ++j) p4[j] = *reinterpret_cast(prev + (warp * 4 + j) * DK + lane * 4); +#pragma unroll + for (int j = 0; j < 4; ++j) { + const int row = warp * 4 + j; + const float sp[4] = {p4[j].x, p4[j].y, p4[j].z, p4[j].w}; + float sd[4], kv = 0.0f; +#pragma unroll + for (int i = 0; i < 4; ++i) { + sd[i] = sp[i] * gg; + kv = kv + sd[i] * kk[i]; + } + kv = warp_sum(kv); + const float err = vs[row] - kv, delta = err * bb, dj = dos[row]; + float dd = 0.0f; +#pragma unroll + for (int i = 0; i < 4; ++i) { + pq[i] += dj * (sd[i] + kk[i] * delta); + ds[j][i] += dj * qq[i]; + dd += ds[j][i] * kk[i]; + } + dd = warp_sum(dd); + const float dkv = -bb * dd; + if (lane == 0) { + dact[(size_t)r * s.conv + v0 + row] = bb * dd; + pb += dd * err; + } +#pragma unroll + for (int i = 0; i < 4; ++i) { + pk[i] += delta * ds[j][i] + dkv * sd[i]; + const float dsp = ds[j][i] + dkv * kk[i]; + pg += dsp * sp[i]; + ds[j][i] = gg * dsp; + } + } +#pragma unroll + for (int i = 0; i < 4; ++i) { + red_q[warp][lane * 4 + i] = pq[i]; + red_k[warp][lane * 4 + i] = pk[i]; + } + pg = warp_sum(pg); + if (lane == 0) { + red_g[warp] = pg; + red_b[warp] = pb; + } + threadgroup_barrier(mem_flags::mem_threadgroup); + const size_t out = ((size_t)r * s.nv + h) * SPLIT + part; + if (t < DK) { + float x = 0.0f; +#pragma unroll + for (int w = 0; w < WARPS; ++w) x += red_q[w][t]; + dqp[out * DK + t] = x; + if (t == 0) { + float e = 0.0f; +#pragma unroll + for (int w = 0; w < WARPS; ++w) e += red_g[w]; + dg[out] = e; + } + } else { + float x = 0.0f; +#pragma unroll + for (int w = 0; w < WARPS; ++w) x += red_k[w][t - DK]; + dkp[out * DK + t - DK] = x; + if (t == DK) { + float e = 0.0f; +#pragma unroll + for (int w = 0; w < WARPS; ++w) e += red_b[w]; + dbeta[out] = e; + } + } + } + } + + } + void tf_gdn_qk_back(const device bf16* act, const device float* dqp, + const device float* dkp, device float* dact, + GdnShape s) { + + threadgroup float* scratch = shared + 0; + const int r = blockIdx.x, hk = blockIdx.y, t = threadIdx.x, per = s.nv / s.nk; + for (int which = 0; which < 2; ++which) { + const device float* part = which == 0 ? dqp : dkp; + float d = 0.0f; + for (int h = hk * per; h < (hk + 1) * per; ++h) + for (int p = 0; p < SPLIT; ++p) d += part[(((size_t)r * s.nv + h) * SPLIT + p) * DK + t]; + const int c = which * s.nk * DK + hk * DK + t; + const float x = f32(act[(size_t)r * s.conv + c]); + const float ss = block_sum_tree(x * x, scratch, 4); + const float dot = block_sum_tree(x * d, scratch, 4); + const float inv = 1.0f / precise::sqrt(ss / float(DK) + 1e-6f), sc = which == 0 ? bf(1.0f / float(DK)) : bf(1.0f / precise::sqrt(float(DK))); + dact[(size_t)r * s.conv + c] = sc * inv * (d - inv * inv * x * dot / float(DK)); + } + + } + void tf_gdn_gates_back(const device bf16* P, const device float* a_log, + const device float* dt_bias, const device float* g, + const device float* dg, const device float* dbeta, + device float* dproj, GdnShape s) { + + const int h = threadIdx.x, r = blockIdx.x; + if (h >= s.nv || r >= s.rows) return; + const size_t at = (size_t)r * s.proj + s.conv + s.nv * DV; + const float b = f32(P[at + h]), x = bf(f32(P[at + s.nv + h]) + dt_bias[h]); + const float sb = sigmoidf_(b), sx = sigmoidf_(x); + float db = 0.0f, dgs = 0.0f; + for (int p = 0; p < SPLIT; ++p) { + db += dbeta[(r * s.nv + h) * SPLIT + p]; + dgs += dg[(r * s.nv + h) * SPLIT + p]; + } + dproj[at + h] = db * sb * (1.0f - sb); + dproj[at + s.nv + h] = -dgs * g[r * s.nv + h] * precise::exp(a_log[h]) * sx; + + } + void tf_gdn_conv_back(const device bf16* P, const device bf16* hist, + const device bf16* cw, const device float* dact, + device float* dproj, GdnShape s) { + + const int c = blockIdx.x * 256 + threadIdx.x, r = blockIdx.y; + if (c >= s.conv || r >= s.rows) return; + float acc = 0.0f; +#pragma unroll + for (int tap = 0; tap < TAPS; ++tap) { + const int at = r + TAPS - 1 - tap; + if (at >= s.rows) continue; + const float pre = conv_acc(P, hist, cw, at, c, s); + acc += f32(cw[c * TAPS + tap]) * dact[(size_t)at * s.conv + c] * silu_grad(pre); + } + dproj[(size_t)r * s.proj + c] = acc; + + } +}; +} diff --git a/zig/kernels/metal/qwen27/learning-bindings.json b/zig/kernels/metal/qwen27/learning-bindings.json new file mode 100644 index 00000000000..9c7106fca80 --- /dev/null +++ b/zig/kernels/metal/qwen27/learning-bindings.json @@ -0,0 +1,381 @@ +{ + "gdn_train": { + "source": "zig/kernels/cuda/gdn_train.cu", + "sha256": "7778b3e03065cdf26285af0990b5a0dffcfb51bc3ffc1bd2547c044c4c806ca8", + "dependencies": { + "zig/kernels/cuda/common/act.cuh": "46ac1df9631e99f1987b2b522022b1e37e1294ed0808ac095b992bfeb913b59f" + }, + "kernels": [ + { + "name": "tf_gdn_norm_back", + "pointers": [ + { + "type": "const bf16*", + "name": "y" + }, + { + "type": "const bf16*", + "name": "P" + }, + { + "type": "const bf16*", + "name": "norm_w" + }, + { + "type": "const float*", + "name": "dout" + }, + { + "type": "float*", + "name": "dy" + }, + { + "type": "float*", + "name": "dproj" + } + ], + "scalars": [ + { + "type": "GdnShape", + "name": "s" + }, + { + "type": "float", + "name": "eps" + } + ], + "threadgroup_bytes": 644, + "max_threads": 128 + }, + { + "name": "tf_gdn_scan_back", + "pointers": [ + { + "type": "const bf16*", + "name": "act" + }, + { + "type": "const float*", + "name": "q" + }, + { + "type": "const float*", + "name": "k" + }, + { + "type": "const float*", + "name": "g" + }, + { + "type": "const float*", + "name": "beta" + }, + { + "type": "const float*", + "name": "ckpt" + }, + { + "type": "const float*", + "name": "dy" + }, + { + "type": "float*", + "name": "work" + }, + { + "type": "float*", + "name": "dqp" + }, + { + "type": "float*", + "name": "dkp" + }, + { + "type": "float*", + "name": "dact" + }, + { + "type": "float*", + "name": "dg" + }, + { + "type": "float*", + "name": "dbeta" + } + ], + "scalars": [ + { + "type": "GdnShape", + "name": "s" + }, + { + "type": "int", + "name": "from" + } + ], + "threadgroup_bytes": 9536, + "max_threads": 256 + }, + { + "name": "tf_gdn_qk_back", + "pointers": [ + { + "type": "const bf16*", + "name": "act" + }, + { + "type": "const float*", + "name": "dqp" + }, + { + "type": "const float*", + "name": "dkp" + }, + { + "type": "float*", + "name": "dact" + } + ], + "scalars": [ + { + "type": "GdnShape", + "name": "s" + } + ], + "threadgroup_bytes": 128, + "max_threads": 128 + }, + { + "name": "tf_gdn_gates_back", + "pointers": [ + { + "type": "const bf16*", + "name": "P" + }, + { + "type": "const float*", + "name": "a_log" + }, + { + "type": "const float*", + "name": "dt_bias" + }, + { + "type": "const float*", + "name": "g" + }, + { + "type": "const float*", + "name": "dg" + }, + { + "type": "const float*", + "name": "dbeta" + }, + { + "type": "float*", + "name": "dproj" + } + ], + "scalars": [ + { + "type": "GdnShape", + "name": "s" + } + ], + "threadgroup_bytes": 4, + "max_threads": 256 + }, + { + "name": "tf_gdn_conv_back", + "pointers": [ + { + "type": "const bf16*", + "name": "P" + }, + { + "type": "const bf16*", + "name": "hist" + }, + { + "type": "const bf16*", + "name": "cw" + }, + { + "type": "const float*", + "name": "dact" + }, + { + "type": "float*", + "name": "dproj" + } + ], + "scalars": [ + { + "type": "GdnShape", + "name": "s" + } + ], + "threadgroup_bytes": 4, + "max_threads": 256 + } + ] + }, + "attn_train": { + "source": "zig/kernels/cuda/attn_train.cu", + "sha256": "8e26df47c2c573c846f270ed61f452b621486f4c131fde1162aa9eb1a56d4042", + "dependencies": { + "zig/kernels/cuda/attn_back.cuh": "f9f7f3666999cbf25e086ca04e4e2380e3c76ad371297c1936eed8f957395fe8", + "zig/kernels/cuda/common/act.cuh": "46ac1df9631e99f1987b2b522022b1e37e1294ed0808ac095b992bfeb913b59f" + }, + "kernels": [ + { + "name": "tf_attn_q", + "pointers": [ + { + "type": "const bf16*", + "name": "qkv" + }, + { + "type": "const float*", + "name": "dout" + }, + { + "type": "float*", + "name": "probs" + }, + { + "type": "float*", + "name": "dscores" + }, + { + "type": "float*", + "name": "dq" + }, + { + "type": "const bf16*", + "name": "pk" + }, + { + "type": "const bf16*", + "name": "pv" + } + ], + "scalars": [ + { + "type": "Heads", + "name": "a" + } + ], + "threadgroup_bytes": 18560, + "max_threads": 256 + }, + { + "name": "tf_attn_gate_back", + "pointers": [ + { + "type": "const float*", + "name": "dgated" + }, + { + "type": "const bf16*", + "name": "gated" + }, + { + "type": "const bf16*", + "name": "pq" + }, + { + "type": "float*", + "name": "dout" + }, + { + "type": "float*", + "name": "dpq" + } + ], + "scalars": [ + { + "type": "int", + "name": "heads" + }, + { + "type": "int", + "name": "dim" + } + ], + "threadgroup_bytes": 4, + "max_threads": 256 + }, + { + "name": "tf_attn_prep_back", + "pointers": [ + { + "type": "const bf16*", + "name": "pq" + }, + { + "type": "const bf16*", + "name": "pk" + }, + { + "type": "const float*", + "name": "qscale" + }, + { + "type": "const float*", + "name": "kscale" + }, + { + "type": "const float*", + "name": "inv" + }, + { + "type": "const float*", + "name": "dq" + }, + { + "type": "const float*", + "name": "dk" + }, + { + "type": "float*", + "name": "dpq" + }, + { + "type": "float*", + "name": "dpk" + } + ], + "scalars": [ + { + "type": "int", + "name": "pos0" + }, + { + "type": "int", + "name": "heads" + }, + { + "type": "int", + "name": "kv_heads" + }, + { + "type": "int", + "name": "dim" + }, + { + "type": "int", + "name": "rope_half" + }, + { + "type": "float", + "name": "eps" + } + ], + "threadgroup_bytes": 1152, + "max_threads": 256 + } + ] + } +} diff --git a/zig/kernels/metal/qwen27/pocket.metal b/zig/kernels/metal/qwen27/pocket.metal new file mode 100644 index 00000000000..bd9691e7d0e --- /dev/null +++ b/zig/kernels/metal/qwen27/pocket.metal @@ -0,0 +1,67 @@ +#include +using namespace metal; + +// One row's saved SwiGLU neurons, followed by their output in neuron order and one BF16 add. +[[max_total_threads_per_threadgroup(256)]] +kernel void tf_q27_pocket_rows(const device bfloat* x [[buffer(0)]], const device float* weights [[buffer(1)]], + device bfloat* out [[buffer(2)]], constant uint4& p [[buffer(3)]], + uint row [[threadgroup_position_in_grid]], uint t [[thread_index_in_threadgroup]], + uint lane [[thread_index_in_simdgroup]], uint sg [[simdgroup_index_in_threadgroup]]) { + threadgroup float activation[64]; + const uint d = p.x, n = p.y, cap = p.z; + const device float* gate = weights; + const device float* up = weights + size_t(cap) * d; + const device float* down = up + size_t(cap) * d; + for (uint j = sg; j < n; j += 8) { + float g = 0.0f, u = 0.0f; + for (uint k = lane; k < d; k += 32) { + const float value = float(x[size_t(row) * d + k]); + g = fma(value, gate[size_t(j) * d + k], g); + u = fma(value, up[size_t(j) * d + k], u); + } + g = simd_sum(g); + u = simd_sum(u); + if (lane == 0) activation[j] = (g / (1.0f + precise::exp(-g))) * u; + } + threadgroup_barrier(mem_flags::mem_threadgroup); + for (uint k = t; k < d; k += 256) { + float change = 0.0f; + for (uint j = 0; j < n; j++) change = fma(activation[j], down[size_t(j) * d + k], change); + const size_t at = size_t(row) * d + k; + out[at] = bfloat(float(out[at]) + change); + } +} + +// Training scales only the open fact; the ordinary serving entry and its bindings stay unchanged. +[[max_total_threads_per_threadgroup(256)]] +kernel void tf_q27_pocket_scaled(const device bfloat* x [[buffer(0)]], const device float* weights [[buffer(1)]], + device bfloat* out [[buffer(2)]], constant uint4& p [[buffer(3)]], constant float& scale [[buffer(4)]], + uint row [[threadgroup_position_in_grid]], uint t [[thread_index_in_threadgroup]], + uint lane [[thread_index_in_simdgroup]], uint sg [[simdgroup_index_in_threadgroup]]) { + threadgroup float activation[64]; + const uint d = p.x, n = p.y, cap = p.z; + const device float* gate = weights; + const device float* up = weights + size_t(cap) * d; + const device float* down = up + size_t(cap) * d; + for (uint j = sg; j < n; j += 8) { + float g = 0.0f, u = 0.0f; + for (uint k = lane; k < d; k += 32) { + const float value = float(x[size_t(row) * d + k]); + g = fma(value, gate[size_t(j) * d + k], g); + u = fma(value, up[size_t(j) * d + k], u); + } + g = simd_sum(g); + u = simd_sum(u); + if (lane == 0) { + const float value = (g / (1.0f + precise::exp(-g))) * u; + activation[j] = j >= p.w && scale != 1.0f ? value * scale : value; + } + } + threadgroup_barrier(mem_flags::mem_threadgroup); + for (uint k = t; k < d; k += 256) { + float change = 0.0f; + for (uint j = 0; j < n; j++) change = fma(activation[j], down[size_t(j) * d + k], change); + const size_t at = size_t(row) * d + k; + out[at] = bfloat(float(out[at]) + change); + } +} diff --git a/zig/qwen27_core.zig b/zig/qwen27_core.zig index ebd50da1498..7c406dfd381 100644 --- a/zig/qwen27_core.zig +++ b/zig/qwen27_core.zig @@ -33,3 +33,9 @@ pub const bf16_topk_gpu = @import("bf16_topk_gpu"); pub const tree_commit_gpu = @import("tree_commit_gpu"); pub const tree_slots = @import("src/core/tree_slots.zig"); + +pub const dense_pocket = @import("src/core/dense_pocket.zig"); + +pub const affine4_host = @import("src/core/affine4_host.zig"); + +pub const shard_edit = @import("src/core/shard_edit.zig"); diff --git a/zig/qwen27_learning_checks.zig b/zig/qwen27_learning_checks.zig new file mode 100644 index 00000000000..654046dcc7e --- /dev/null +++ b/zig/qwen27_learning_checks.zig @@ -0,0 +1,100 @@ +//! Supplemental local FP64 learning checks, with real source faults counted in the contract's control tally. +const std = @import("std"); +const mtl = @import("metal"); +const contract = @import("contract"); +const source = @import("learning_sources"); +const ref = @import("tests/qwen27/learning_reference.zig"); +pub const Tally = contract.gates.Tally; +const Case = struct { symbol: []const u8, text: []const u8, from: []const u8, to: []const u8 }; +fn case(which: ref.Which) Case { + return switch (which) { + .pocket => .{ .symbol = "tf_learn_pocket_back", .text = source.learn_rows, .from = "const float scale = j >= p.u.x ? p.f.x : 1.0f;", .to = "const float scale = 1.0f;" }, + .affine => .{ .symbol = "tf_learn_q4_back", .text = source.learn_linear, .from = "4 * (column & 7)", .to = "4 * ((column + 1) & 7)" }, + .prep => .{ .symbol = "tf_attn_prep_back", .text = source.attn_train, .from = "go[d] * c + go[d + rope_half] * s", .to = "go[d] * c - go[d + rope_half] * s" }, + .scan => .{ .symbol = "tf_gdn_scan_back", .text = source.gdn_train, .from = "const float dkv = -bb * dd;", .to = "const float dkv = bb * dd;" }, + }; +} +fn edit(a: std.mem.Allocator, c: Case) ![]u8 { + if (std.mem.count(u8, c.text, c.from) != 1) return error.LearningControlEditMissing; + return std.mem.replaceOwned(u8, a, c.text, c.from, c.to); +} +fn execute(comptime rig_: type, a: std.mem.Allocator, device: mtl.Device, queue: mtl.Queue, which: ref.Which, control: bool) !bool { + var arena = std.heap.ArenaAllocator.init(a); + defer arena.deinit(); + const mem = arena.allocator(); + const c = case(which); + const text = if (control) try edit(mem, c) else c.text; + const pipeline = try rig_.pipeline(device, text, c.symbol); + defer pipeline.deinit(); + const f = try ref.make(mem, which); + if (pipeline.simdWidth() != 32 or pipeline.maxThreads() < f.threads) return error.LearningLocalLaunchLimit; + var rig: rig_.Rig = .{ .a = mem, .device = device, .queue = queue }; + defer rig.deinit(); + const buffers = try mem.alloc(rig_.Ref, f.buffers.len); + for (buffers, f.buffers) |*slot, b| { + slot.* = if (b.input) try rig.input(b.bytes) else if (b.want != null) try rig.output(b.bytes.len) else try rig.scratch(b.bytes.len); + } + const inputs = try mem.dupe(u8, try rig.inputBytes()); + var first: ?[]u8 = null; + var matches = true; + var worst: f64 = 0; + for (0..5) |_| { + for (buffers, f.buffers) |slot, b| if (!b.input) @memcpy(rig.bytes(slot, b.bytes.len), b.bytes); + const pass = rig.begin(); + pass.e.setPipeline(pipeline); + for (buffers, 0..) |slot, i| pass.e.setBuffer(slot.buf, slot.off, i); + pass.e.setBytes(f.params, buffers.len); + pass.e.dispatchGroups(mtl.Size.of(f.groups[0], f.groups[1], f.groups[2]), mtl.Size.of(f.threads, 1, 1)); + try rig.finish(pass); + for (buffers, f.buffers) |slot, b| if (b.want) |want| { + const got = std.mem.bytesAsSlice(f32, @as([]align(4) const u8, @alignCast(rig.bytes(slot, b.bytes.len)))); + for (got, want) |x, y| { + const distance = @abs(x - y); + worst = @max(worst, distance); + if (!std.math.isFinite(x) or distance > f.bound) matches = false; + } + }; + const out = try rig.outputBytes(); + if (first) |bytes| { + if (!std.mem.eql(u8, bytes, out)) return error.LearningLocalRepeat; + } else first = try mem.dupe(u8, out); + if (!try rig.intact() or rig.overlap() or !std.mem.eql(u8, inputs, try rig.inputBytes())) return error.LearningLocalOwnership; + } + std.debug.print("Q27_LOCAL {s} control={} match={} worst_abs={e:.9} bound={e:.9} repeats=5 guards=true inputs_unchanged=true\n", .{ c.symbol, control, matches, worst, f.bound }); + return matches; +} + +/// This supplements gates 1-5; passing four local finite fixtures is not a whole-model gradient qualification. +pub fn run(comptime rig_: type, a: std.mem.Allocator, device: mtl.Device, queue: mtl.Queue, only: ?[]const u8, tally: *Tally) !void { + for (std.enums.values(ref.Which)) |which| { + const name = try std.fmt.allocPrint(a, "qwen27 learning local {s}", .{case(which).symbol}); + defer a.free(name); + if (only) |filter| if (std.mem.indexOf(u8, name, filter) == null) continue; + if (!try execute(rig_, a, device, queue, which, false)) { + tally.failed += 1; + std.debug.print("FAIL local shapes {s}\n", .{name}); + } + tally.controls += 1; + // Compile and launch errors are errors, never evidence that a numerical control was caught. + if (!try execute(rig_, a, device, queue, which, true)) { + tally.caught += 1; + std.debug.print("CONTROL {s}: red at local shapes, as planted\n", .{name}); + } else { + tally.missed += 1; + std.debug.print("CONTROL MISSED {s}\n", .{name}); + } + } +} + +test "Qwen27 local adjoints: every real source control has exactly one witness" { + for (std.enums.values(ref.Which)) |which| { + const c = case(which); + const changed = try edit(std.testing.allocator, c); + defer std.testing.allocator.free(changed); + try std.testing.expect(!std.mem.eql(u8, c.text, changed)); + try std.testing.expectEqual(@as(usize, 0), std.mem.count(u8, changed, c.from)); + } +} +test { + _ = ref; +} diff --git a/zig/qwen27_learning_main.zig b/zig/qwen27_learning_main.zig new file mode 100644 index 00000000000..7b887ad413e --- /dev/null +++ b/zig/qwen27_learning_main.zig @@ -0,0 +1,16 @@ +//! Run only the bounded local backward panel without opening a checkpoint or trainer. +const std = @import("std"); +const mtl = @import("metal"); +const checks = @import("checks"); +pub fn main(init: std.process.Init) !u8 { + const pool = mtl.objc.Pool.push(); + defer pool.pop(); + const device = try mtl.Device.init(); + defer device.deinit(); + const queue = try device.queue(); + defer queue.deinit(); + var tally: checks.Tally = .{}; + try checks.run(@import("tests/contract/rig.zig"), init.gpa, device, queue, null, &tally); + std.debug.print("Q27_LOCAL_SUMMARY controls={d} red={d} missed={d} failures={d}\n", .{ tally.controls, tally.caught, tally.missed, tally.failed }); + return if (tally.problems() == 0) 0 else 1; +} diff --git a/zig/qwen27_linear_core.zig b/zig/qwen27_linear_core.zig new file mode 100644 index 00000000000..2c15499ff36 --- /dev/null +++ b/zig/qwen27_linear_core.zig @@ -0,0 +1,5 @@ +//! Actual loader dependencies at a recording Metal boundary. +pub const checkpoint_metal = @import("src/core/checkpoint_metal.zig"); +pub const dense_pocket = @import("src/core/dense_pocket.zig"); +pub const row_projection = @import("src/core/row_projection.zig"); +pub const lane_projection = @import("src/core/lane_projection.zig"); diff --git a/zig/qwen27_linear_host.zig b/zig/qwen27_linear_host.zig new file mode 100644 index 00000000000..c5c0b20c4da --- /dev/null +++ b/zig/qwen27_linear_host.zig @@ -0,0 +1,4 @@ +//! Load through the production Builder using host-backed Metal buffers. +test { + _ = @import("src/families/qwen27/gpu_weights.zig"); +} diff --git a/zig/qwen27_living_core.zig b/zig/qwen27_living_core.zig new file mode 100644 index 00000000000..8df9da49edf --- /dev/null +++ b/zig/qwen27_living_core.zig @@ -0,0 +1,8 @@ +//! Shared host I/O for the actual Metal pocket reader and writer. +pub const Checkpoint = @import("src/core/checkpoint.zig").Checkpoint; +pub const checkpoint_host = @import("src/core/checkpoint.zig"); +pub const shard_edit = @import("src/core/shard_edit.zig"); +pub const safetensors = @import("src/core/safetensors.zig"); +pub const affine4_host = @import("src/core/affine4_host.zig"); +pub const dense_pocket = @import("src/core/dense_pocket.zig"); +pub const checkpoint_metal = @import("src/core/checkpoint_metal.zig"); diff --git a/zig/qwen27_living_host.zig b/zig/qwen27_living_host.zig new file mode 100644 index 00000000000..37620834471 --- /dev/null +++ b/zig/qwen27_living_host.zig @@ -0,0 +1,177 @@ +//! Tiny dense checkpoints exercise the actual Metal loader, writer and row bindings without shader execution. +const std = @import("std"); +const metal = @import("metal"); +const core = @import("core"); +const living = @import("living"); +const pocket = @import("pocket"); +const storage = @import("storage"); +const Selection = @FieldType(pocket.Pockets, "selected"); +const d = 64; +const width = 128; +const layers = 4; +const cap = 64; +const n = cap * d; +const Shards = living.shards.Io(core); + +fn family(scoped: bool, wrapped: bool) living.Family { + var f = living.families.qwen3_5; + if (!scoped) f.names.layers = "model.layers."; + if (!wrapped) f.keys.scope = null; + return f; +} + +fn fixture(a: std.mem.Allocator, io: std.Io, dir: []const u8, scoped: bool, wrapped: bool) !void { + var tensors: std.ArrayList(core.shard_edit.New) = .empty; + for (0..layers) |l| for ([_][]const u8{ "gate_proj", "up_proj", "down_proj" }, 0..) |proj, p| { + const rows: usize = if (p == 2) d else width; + const cols: usize = if (p == 2) width else d; + for ([_][]const u8{ "weight", "scales", "biases" }, 0..) |leaf, kind| { + const k = if (kind == 0) cols / 8 else cols / 64; + const bytes = try a.alloc(u8, rows * k * (if (kind == 0) @as(usize, 4) else 2)); + if (kind == 0) { + for (0..rows * k) |i| std.mem.writeInt(u32, bytes[i * 4 ..][0..4], @as(u32, @intCast(i)) + 0x12345670, .little); + } else for (0..rows * k) |i| std.mem.writeInt(u16, bytes[i * 2 ..][0..2], if (kind == 1) 0x3d80 else 0xbf00, .little); + try tensors.append(a, .{ .name = try std.fmt.allocPrint(a, "{s}model.layers.{d}.mlp.{s}.{s}", .{ if (scoped) "language_model." else "", l, proj, leaf }), .dtype = if (kind == 0) .u32 else .bf16, .shape = try a.dupe(usize, &.{ rows, k }), .bytes = bytes }); + } + }; + try core.shard_edit.create(a, try std.fs.path.join(a, &.{ dir, "model.safetensors" }), &.{.{ "format", "mlx" }}, tensors.items); + const conf = + \\"model_type":"qwen3_5","hidden_size":64,"intermediate_size":128,"num_hidden_layers":4, + \\"num_attention_heads":4,"num_key_value_heads":2,"head_dim":16,"vocab_size":97, + \\"linear_num_key_heads":2,"linear_num_value_heads":4,"linear_key_head_dim":16,"linear_value_head_dim":16, + \\"linear_conv_kernel_dim":4,"eos_token_id":2 + ; + const text = try std.fmt.allocPrint(a, "{{\"quantization\":{{\"bits\":4,\"group_size\":64}},{s}{s}{s}}}", .{ if (wrapped) "\"text_config\":{" else "", conf, if (wrapped) "}" else "" }); + try std.Io.Dir.cwd().writeFile(io, .{ .sub_path = try std.fs.path.join(a, &.{ dir, "config.json" }), .data = text }); +} + +fn layout() living.Layout { + var all: living.Layers = .empty; + for (0..layers) |l| all.set(l); + return .fromExperts(d, width, layers, all); +} + +fn vectors(a: std.mem.Allocator) ![3][]f32 { + var out: [3][]f32 = undefined; + for (&out) |*v| { + v.* = try a.alloc(f32, n); + @memset(v.*, 0); + } + out[0][0] = 16; + out[1][0] = 0.0625; + out[2][0] = 0.125; + out[2][1] = -0.125; + return out; +} + +fn covered(r: *const metal.Record) [9]bool { + var seen: [9]bool = @splat(false); + for (r.calls[0..r.count]) |c| { + const first = (c.output - 32) / (d * 2); + for (first..first + c.rows) |row| seen[row] = true; + } + return seen; +} + +test "qwen27 living: an empty folder and a failed first pipeline allocate no retained pocket work" { + const a = std.testing.allocator; + var r: metal.Record = .{ .a = a }; + var p = try pocket.Pockets.init(a, r.device(), d, layers); + defer p.deinit(); + const zero: [n]f32 = @splat(0); + try p.set(0, &zero, &zero, &zero, 0); + for ([_]usize{ 1, 16, 128, 2048 }) |rows| try p.add(r.encoder(), 0, undefined, undefined, rows); + try std.testing.expectEqual(@as(usize, 0), r.allocated); + try std.testing.expectEqual(@as(usize, 0), r.libraries); + try std.testing.expectEqual(@as(usize, 0), r.count); + r.fail_pipeline = true; + try std.testing.expectError(error.PlantedPipelineFailure, p.set(0, &zero, &zero, &zero, 1)); + try std.testing.expect(p.layers[0] == null and p.kernel == null); + try std.testing.expectEqual(@as(usize, 0), r.live); +} + +test "qwen27 living: actual mixed verify, prompt chunks and single rows bind only taught rows" { + const a = std.testing.allocator; + var r: metal.Record = .{ .a = a }; + var p = try pocket.Pockets.init(a, r.device(), d, layers); + defer p.deinit(); + const zero: [n]f32 = @splat(0); + try p.set(0, &zero, &zero, &zero, 1); + const x = try r.device().buffer(2048 * d * 2 + 32, 0); + defer x.deinit(); + const y = try r.device().buffer(2048 * d * 2 + 32, 0); + defer y.deinit(); + const Span = struct { parents: []const i32 }; + const spans = [_]Span{ .{ .parents = &.{ -1, 0, 1 } }, .{ .parents = &.{ -1, 0, 1, 2 } }, .{ .parents = &.{ -1, 0 } } }; + p.selected = try Selection.windows(&.{ 0, 1, 2 }, &.{ 0, 3, 7 }, &spans, &.{ false, true, false }); + try p.add(r.encoder(), 0, .{ .buffer = x, .offset = 16 }, .{ .buffer = y, .offset = 32 }, 9); + try std.testing.expectEqual(@as(usize, 2), r.count); + try std.testing.expectEqual([9]bool{ true, true, true, false, false, false, false, true, true }, covered(&r)); + try std.testing.expectEqual(@as(usize, 16 + 7 * d * 2), r.calls[1].input); + try std.testing.expectEqual([4]u32{ d, 1, cap, 0 }, r.calls[0].shape); + const verify = covered(&r); + r.count = 0; + p.selected = .{}; + for (verify, 0..) |taught, i| if (taught) try p.add(r.encoder(), 0, .{ .buffer = x, .offset = 16 + i * d * 2 }, .{ .buffer = y, .offset = 32 + i * d * 2 }, 1); + try std.testing.expectEqual(verify, covered(&r)); + r.count = 0; + p.selected = .{ .all = false }; + try p.add(r.encoder(), 0, .{ .buffer = x }, .{ .buffer = y }, 128); + try std.testing.expectEqual(@as(usize, 0), r.count); + p.selected = .{}; + try p.add(r.encoder(), 0, .{ .buffer = x }, .{ .buffer = y }, 2048); + try std.testing.expectEqual(@as(usize, 2048), r.calls[0].rows); + try std.testing.expectError(error.BadPocketRows, p.selected.add(std.math.maxInt(usize), 2)); +} + +test "qwen27 living: CUDA and Metal saves reopen through the actual Metal loader and common CUDA reader" { + const a = std.testing.allocator; + const io = std.testing.io; + inline for (.{ true, false }) |scoped| inline for (.{ true, false }) |wrapped| { + var arena: std.heap.ArenaAllocator = .init(a); + defer arena.deinit(); + const ar = arena.allocator(); + var temp = std.testing.tmpDir(.{}); + defer temp.cleanup(); + const dir = try temp.dir.realPathFileAlloc(io, ".", ar); + try fixture(ar, io, dir, scoped, wrapped); + const f = comptime family(scoped, wrapped); + var ck = try core.Checkpoint.openModel(a, io, dir); + const prefix = try std.fmt.allocPrint(ar, "{s}0.mlp.down_proj.", .{f.names.layers}); + const old = try ck.get(try std.fmt.allocPrint(ar, "{s}weight", .{prefix})); + const base_bytes = try ar.dupe(u8, old.bytes); + ck.close(); + const v = try vectors(ar); + _ = try Shards.write(a, io, dir, f, layout(), &.{0}, cap, &.{ v[0], v[1] }, v[2]); + const config_text = try temp.dir.readFileAlloc(io, "config.json", ar, .limited(1 << 20)); + const c = try pocket.config.parse(a, config_text, null); + try std.testing.expectEqual(@as(usize, width), c.intermediate); + var r: metal.Record = .{ .a = a }; + { + var p = try pocket.Pockets.init(a, r.device(), d, layers); + defer p.deinit(); + try p.load(io, dir, c); + const actual = try vectors(ar); + try std.testing.expectEqual(@as(usize, 1), try p.read(0, actual[0], actual[1], actual[2])); + for (v, actual) |expected, got| try std.testing.expectEqualSlices(f32, expected, got); + try std.testing.expect(p.layers[1] == null and p.layers[2] == null and p.layers[3] == null); + v[2][0] = 0.25; + try core.shard_edit.save_guard.begin(io, dir); + _ = try storage.save(a, io, dir, layout(), &.{0}, cap, v[0], v[1], v[2]); + try std.testing.expectError(error.CheckpointSaveUncertain, core.Checkpoint.openModel(a, io, dir)); + try core.shard_edit.save_guard.finish(io, dir); + var saved = try core.Checkpoint.openModel(a, io, dir); + defer saved.close(); + const down = try saved.get(try std.fmt.allocPrint(ar, "{s}weight", .{prefix})); + for (0..d) |row| try std.testing.expectEqualSlices(u8, base_bytes[row * width / 2 ..][0 .. width / 2], down.bytes[row * (width + cap) / 2 ..][0 .. width / 2]); + const base_view = try ar.alloc(u8, base_bytes.len); + try core.dense_pocket.copyBase(down.bytes, d, (width + cap) / 2, width / 2, base_view); + try std.testing.expectEqualSlices(u8, base_bytes, base_view); + const read = try ar.alloc(f32, n); + const base = try std.fmt.allocPrint(ar, "{s}0.", .{f.names.layers}); + try core.dense_pocket.read(&saved, base, "mlp.down_proj", d, width, read); + try std.testing.expectEqualSlices(f32, v[2], read); + } + try std.testing.expectEqual(@as(usize, 0), r.live); + }; +} diff --git a/zig/qwen27_pocket_core.zig b/zig/qwen27_pocket_core.zig new file mode 100644 index 00000000000..d78b1bd878d --- /dev/null +++ b/zig/qwen27_pocket_core.zig @@ -0,0 +1,7 @@ +//! Shared checkpoint and pocket contracts for the model-free device probe. +pub const Checkpoint = @import("src/core/checkpoint.zig").Checkpoint; +pub const shard_edit = @import("src/core/shard_edit.zig"); +pub const safetensors = @import("src/core/safetensors.zig"); +pub const affine4_host = @import("src/core/affine4_host.zig"); +pub const dense_pocket = @import("src/core/dense_pocket.zig"); +pub const checkpoint_metal = @import("src/core/checkpoint_metal.zig"); diff --git a/zig/qwen27_pocket_host.zig b/zig/qwen27_pocket_host.zig new file mode 100644 index 00000000000..dd706ecca8b --- /dev/null +++ b/zig/qwen27_pocket_host.zig @@ -0,0 +1,9 @@ +//! Shared CUDA-writer/Metal-reader pocket fixtures without any device or shader imports. +pub const dense_pocket = @import("src/core/dense_pocket.zig"); + +test { + _ = @import("src/families/qwen27/config.zig"); + _ = @import("src/families/qwen27/pocket_rows.zig"); + _ = @import("src/families/qwen3_5/pocket_shards_test.zig"); + _ = dense_pocket; +} diff --git a/zig/qwen27_pocket_recording.zig b/zig/qwen27_pocket_recording.zig new file mode 100644 index 00000000000..7d156f66dd3 --- /dev/null +++ b/zig/qwen27_pocket_recording.zig @@ -0,0 +1,102 @@ +//! Record actual pocket bindings and ownership on host buffers; no shader arithmetic is executed. +const std = @import("std"); +const real = @import("real_metal"); +pub const ResourceOptions = real.ResourceOptions; +pub const Size = real.Size; +pub const MappedFile = real.MappedFile; +pub const Queue = real.Queue; +pub const objc = real.objc; +pub const Bound = struct { buffer: Buffer, offset: usize }; +pub const Call = struct { input: usize, output: usize, weights: usize, rows: usize, shape: [4]u32 }; +pub const Record = struct { + a: std.mem.Allocator, + allocated: usize = 0, + live: usize = 0, + libraries: usize = 0, + pipelines: usize = 0, + fail_pipeline: bool = false, + bound: [3]Bound = undefined, + shape: [4]u32 = undefined, + calls: [256]Call = undefined, + count: usize = 0, + pub fn device(r: *Record) Device { + return .{ .r = r }; + } + pub fn encoder(r: *Record) ComputeEncoder { + return .{ .r = r }; + } +}; +pub const Buffer = struct { + r: *Record, + data: []align(256) u8, + pub fn contents(b: Buffer) [*]u8 { + return b.data.ptr; + } + pub fn length(b: Buffer) usize { + return b.data.len; + } + pub fn slice(b: Buffer, comptime T: type, n: usize) []T { + return @as([*]T, @ptrCast(@alignCast(b.contents())))[0..n]; + } + pub fn deinit(b: Buffer) void { + b.r.a.free(b.data); + b.r.live -= 1; + } +}; +pub const Device = struct { + r: *Record, + pub fn tensorUnits(_: Device) bool { + return false; + } + pub fn buffer(d: Device, bytes: usize, _: usize) !Buffer { + const data = try d.r.a.alignedAlloc(u8, .fromByteUnits(256), bytes); + @memset(data, 0); + d.r.allocated += 1; + d.r.live += 1; + return .{ .r = d.r, .data = data }; + } +}; +pub const CompileOptions = struct { + pub fn mlx() @This() { + return .{}; + } +}; +pub const Library = struct { + pub fn fromSource(d: Device, _: []const u8, _: CompileOptions) !Library { + d.r.libraries += 1; + return .{}; + } + pub fn deinit(_: Library) void {} +}; +pub const Pipeline = struct { + pub fn init(d: Device, _: Library, name: []const u8, _: bool) !Pipeline { + if (d.r.fail_pipeline) return error.PlantedPipelineFailure; + if (!std.mem.eql(u8, name, "tf_q27_pocket_rows")) return error.WrongPocketSymbol; + d.r.pipelines += 1; + return .{}; + } + pub fn maxThreads(_: Pipeline) usize { + return 256; + } + pub fn deinit(_: Pipeline) void {} +}; +pub const ComputeEncoder = struct { + r: *Record, + pub fn setPipeline(_: ComputeEncoder, _: Pipeline) void {} + pub fn setBuffer(e: ComputeEncoder, b: Buffer, offset: usize, at: usize) void { + e.r.bound[at] = .{ .buffer = b, .offset = offset }; + } + pub fn setValue(e: ComputeEncoder, value: anytype, at: usize) void { + std.debug.assert(at == 3); + e.r.shape = @bitCast(value); + } + pub fn dispatchGroups(e: ComputeEncoder, grid: Size, group: Size) void { + std.debug.assert(group.width == 256 and e.r.count < e.r.calls.len); + e.r.calls[e.r.count] = .{ .input = e.r.bound[0].offset, .output = e.r.bound[2].offset, .weights = @intFromPtr(e.r.bound[1].buffer.contents()), .rows = grid.width, .shape = e.r.shape }; + e.r.count += 1; + } + pub fn barrier(_: ComputeEncoder) void {} +}; +pub const ResidencySet = struct { + pub const Follow = struct { ctx: *anyopaque, join: *const fn (*anyopaque, Buffer) void, leave: *const fn (*anyopaque, Buffer) void }; +}; diff --git a/zig/src/core/contract/qwen27_learning_records.zig b/zig/src/core/contract/qwen27_learning_records.zig new file mode 100644 index 00000000000..410f1d5c309 --- /dev/null +++ b/zig/src/core/contract/qwen27_learning_records.zig @@ -0,0 +1,26 @@ +//! Learner groups have source-declared thread ceilings; old-chip compile receipts remain separate. +const M = @import("limits.zig").MetalLaunch; +pub const metal = [_]M{ + .{ .name = "qwen27 learning learn_linear tf_learn_attn_gate_grad", .threads = 256, .reserved = 256, .tg_memory = 0 }, + .{ .name = "qwen27 learning gdn_train tf_gdn_norm_back", .threads = 128, .reserved = 128, .tg_memory = 644 }, + .{ .name = "qwen27 learning gdn_train tf_gdn_scan_back", .threads = 256, .reserved = 256, .tg_memory = 9536 }, + .{ .name = "qwen27 learning gdn_train tf_gdn_qk_back", .threads = 128, .reserved = 128, .tg_memory = 128 }, + .{ .name = "qwen27 learning gdn_train tf_gdn_gates_back", .threads = 256, .reserved = 256, .tg_memory = 4 }, + .{ .name = "qwen27 learning gdn_train tf_gdn_conv_back", .threads = 256, .reserved = 256, .tg_memory = 4 }, + .{ .name = "qwen27 learning attn_train tf_attn_q", .threads = 256, .reserved = 256, .tg_memory = 18560 }, + .{ .name = "qwen27 learning attn_train tf_attn_gate_back", .threads = 256, .reserved = 256, .tg_memory = 4 }, + .{ .name = "qwen27 learning attn_train tf_attn_prep_back", .threads = 256, .reserved = 256, .tg_memory = 1152 }, + .{ .name = "qwen27 learning learn_rows tf_learn_copy", .threads = 256, .reserved = 256, .tg_memory = 0 }, + .{ .name = "qwen27 learning learn_rows tf_learn_zero", .threads = 256, .reserved = 256, .tg_memory = 0 }, + .{ .name = "qwen27 learning learn_rows tf_learn_nudge", .threads = 256, .reserved = 256, .tg_memory = 0 }, + .{ .name = "qwen27 learning learn_rows tf_learn_widen", .threads = 256, .reserved = 256, .tg_memory = 0 }, + .{ .name = "qwen27 learning learn_rows tf_learn_gdn_act", .threads = 256, .reserved = 256, .tg_memory = 0 }, + .{ .name = "qwen27 learning learn_rows tf_learn_loss", .threads = 256, .reserved = 256, .tg_memory = 32 }, + .{ .name = "qwen27 learning learn_rows tf_learn_rms_back", .threads = 256, .reserved = 256, .tg_memory = 32 }, + .{ .name = "qwen27 learning learn_rows tf_learn_swiglu_back", .threads = 256, .reserved = 256, .tg_memory = 0 }, + .{ .name = "qwen27 learning learn_rows tf_learn_pocket_back", .threads = 256, .reserved = 256, .tg_memory = 512 }, + .{ .name = "qwen27 learning learn_linear tf_learn_q4_back", .threads = 256, .reserved = 256, .tg_memory = 0 }, + .{ .name = "qwen27 learning learn_linear tf_learn_attn_kv_back", .threads = 256, .reserved = 256, .tg_memory = 0 }, + .{ .name = "qwen27 learning pocket tf_q27_pocket_rows", .threads = 256, .reserved = 256, .tg_memory = 256 }, + .{ .name = "qwen27 learning pocket tf_q27_pocket_scaled", .threads = 256, .reserved = 256, .tg_memory = 256 }, +}; diff --git a/zig/src/core/contract/registry.zig b/zig/src/core/contract/registry.zig index dbd2cbb833a..3a45458b720 100644 --- a/zig/src/core/contract/registry.zig +++ b/zig/src/core/contract/registry.zig @@ -379,7 +379,7 @@ pub fn checkCuda(a: std.mem.Allocator, list: []const CudaRecord, quiet: bool) !u return n; } /// Metal pipelines as the engine launches them; tg_memory is the most any chip reflects, m1 and m2 the compiled limits. -pub const metal = @import("fsr_records.zig").metal ++ [_]M{ +pub const metal = @import("qwen27_learning_records.zig").metal ++ @import("fsr_records.zig").metal ++ [_]M{ .{ .name = "softmax tf_softmax_bf16", .threads = 1024, .tg_memory = 256, .m1 = 1024, .m2 = 1024 }, .{ .name = "rms tf_rms_norm_bf16", .threads = 1024, .tg_memory = 144, .m1 = 1024, .m2 = 1024 }, .{ .name = "top-k tf_bf16_topk", .threads = 256, .tg_memory = 4096, .m1 = 768, .m2 = 768 }, diff --git a/zig/src/core/dense_pocket.zig b/zig/src/core/dense_pocket.zig new file mode 100644 index 00000000000..a323acc2b87 --- /dev/null +++ b/zig/src/core/dense_pocket.zig @@ -0,0 +1,53 @@ +//! Shared dense MLP widening: preserve base codes and read the saved pocket. Credit @ZackSample #911. +const std = @import("std"); +const affine = @import("affine4_host.zig"); + +/// Preserve each base row's byte prefix, including separate affine groups in the down projection. +pub fn base(a: std.mem.Allocator, bytes: []const u8, rows: usize, stride: usize, kept: usize) ![]u8 { + if (stride == 0 or kept > stride or rows == 0 or bytes.len % stride != 0 or bytes.len / stride < rows) + return error.UnexpectedTensor; + const out = try a.alloc(u8, rows * kept); + try copyBase(bytes, rows, stride, kept, out); + return out; +} + +/// Copy complete base groups into distinct storage, leaving each widened row's pocket tail out. +pub fn copyBase(bytes: []const u8, rows: usize, stride: usize, kept: usize, out: []u8) !void { + if (stride == 0 or kept > stride or rows == 0 or bytes.len % stride != 0 or bytes.len / stride < rows) + return error.UnexpectedTensor; + if (out.len != rows * kept) return error.UnexpectedTensor; + for (0..rows) |row| @memcpy(out[row * kept ..][0..kept], bytes[row * stride ..][0..kept]); +} +fn value(ts: anytype, width: usize, row: usize, col: usize) f32 { + const w = std.mem.readInt(u32, ts[0].bytes[(row * width + col) / 8 * 4 ..][0..4], .little); + const i = (row * width + col) / 64; + const scale = affine.f32of(std.mem.readInt(u16, ts[1].bytes[i * 2 ..][0..2], .little)); + const bias = affine.f32of(std.mem.readInt(u16, ts[2].bytes[i * 2 ..][0..2], .little)); + return scale * @as(f32, @floatFromInt((w >> @intCast(4 * (col % 8))) & 15)) + bias; +} +pub fn read(ck: anytype, prefix: []const u8, name: []const u8, n: usize, k: usize, extra: []f32) !void { + var buf: [192]u8 = undefined; + var ts: [3]@TypeOf(try ck.get("")) = undefined; + for ([_][]const u8{ "weight", "scales", "biases" }, &ts) |suffix, *t| + t.* = try ck.get(try std.fmt.bufPrint(&buf, "{s}{s}.{s}", .{ prefix, name, suffix })); + const na = ts[0].dim(0); + const ka = ts[0].dim(1) * 8; + if (!ts[0].is(.u32, &.{ na, ka / 8 }) or !ts[1].is(.bf16, &.{ na, ka / 64 }) or + !ts[2].is(.bf16, &.{ na, ka / 64 }) or n > na or k > ka or ka % 64 != 0) return error.UnexpectedTensor; + if (na > n and ka == k and extra.len == (na - n) * k) { + for (n..na) |row| for (0..k) |col| { + extra[(row - n) * k + col] = value(ts, ka, row, col); + }; + } else if (na == n and ka > k and extra.len == (ka - k) * n) { + for (0..n) |row| for (k..ka) |col| { + extra[(col - k) * n + row] = value(ts, ka, row, col); + }; + } else return error.UnexpectedTensor; +} + +test "widened down projection keeps every base group byte for byte across row strides" { + const bytes = [_]u8{ 1, 2, 3, 4, 90, 91, 5, 6, 7, 8, 92, 93 }; + const out = try base(std.testing.allocator, &bytes, 2, 6, 4); + defer std.testing.allocator.free(out); + try std.testing.expectEqualSlices(u8, &.{ 1, 2, 3, 4, 5, 6, 7, 8 }, out); +} diff --git a/zig/src/core/root.zig b/zig/src/core/root.zig index 547b881f171..f8eea9e956e 100644 --- a/zig/src/core/root.zig +++ b/zig/src/core/root.zig @@ -141,3 +141,5 @@ pub const hc_pointwise = @import("hc_pointwise.zig"); pub const hc_pointwise_cuda_adapter = @import("hc_pointwise_cuda_impl.zig").Adapter; pub const hc_pointwise_metal_adapter = @import("hc_pointwise_metal_impl.zig").Adapter; pub const hc_pointwise_contract = @import("contract/hc_pointwise.zig"); + +pub const dense_pocket = @import("dense_pocket.zig"); diff --git a/zig/src/families/qwen27/config.zig b/zig/src/families/qwen27/config.zig index 27fd56091bc..53e07c7c847 100644 --- a/zig/src/families/qwen27/config.zig +++ b/zig/src/families/qwen27/config.zig @@ -8,6 +8,7 @@ pub const max_eos = 8; pub const Config = struct { hidden: usize, intermediate: usize, + pocket: usize = 0, layers: usize, vocab: usize, heads: usize, @@ -305,6 +306,11 @@ pub fn parse(gpa: std.mem.Allocator, json: []const u8, generation: ?[]const u8) .rope_dims = @intFromFloat(@as(f64, @floatFromInt(head_dim)) * factor), .rope_theta = if (rope) |r| try optional(r, "rope_theta", try optional(t, "rope_theta", 10000000)) else try optional(t, "rope_theta", 10000000), }; + if (t.get("tensorfold_learned_neurons")) |v| { + c.pocket = try integer(v, true); + if (c.pocket != 0 and (c.pocket != 64 or c.pocket >= c.intermediate)) return error.BadPocketShape; + c.intermediate -= c.pocket; + } if (t.get("max_position_embeddings")) |v| c.max_position = try integer(v, false); if (rope) |r| if (r.get("mrope_interleaved")) |v| { if (v != .bool or !v.bool) return error.UnsupportedMrope; diff --git a/zig/src/families/qwen27/config_test.zig b/zig/src/families/qwen27/config_test.zig index ab3307a5d8e..ea5907b750d 100644 --- a/zig/src/families/qwen27/config_test.zig +++ b/zig/src/families/qwen27/config_test.zig @@ -299,3 +299,16 @@ test "the fused zba row keeps the tiled projection and each rank's a and b" { try std.testing.expectEqual(@as(usize, 6192), u.zbaA()); try std.testing.expectEqual(@as(usize, 6240), u.zbaDim()); } + +test "a CUDA-taught dense folder keeps the original Metal MLP width" { + const a = std.testing.allocator; + var parsed = try std.json.parseFromSlice(std.json.Value, a, fixture, .{}); + defer parsed.deinit(); + const arena = parsed.arena.allocator(); + try parsed.value.object.put(arena, "intermediate_size", .{ .integer = 192 }); + try parsed.value.object.put(arena, "tensorfold_learned_neurons", .{ .integer = 64 }); + const json = try std.json.Stringify.valueAlloc(a, parsed.value, .{}); + defer a.free(json); + const c = try parse(a, json, null); + try std.testing.expectEqual(@as(usize, 128), c.intermediate); +} diff --git a/zig/src/families/qwen27/decode_round.zig b/zig/src/families/qwen27/decode_round.zig index d558bdee802..9a0d5b73849 100644 --- a/zig/src/families/qwen27/decode_round.zig +++ b/zig/src/families/qwen27/decode_round.zig @@ -6,7 +6,7 @@ const Frame = @import("gpu_frame.zig").Frame; const forward = @import("forward.zig"); const Ref = @import("projection.zig").Ref; /// Layers a verify encodes before committing them, so the GPU starts while the CPU encodes the rest. -const commit_every = 4; +const schedule = @import("train_schedule.zig"); const wts = @import("gpu_weights.zig"); const attn = @import("attention.zig"); const abi = @import("gdn_contract.zig"); @@ -41,12 +41,16 @@ pub const Runner = struct { owned: std.ArrayList(mtl.Buffer), taps: Taps, slots: u32, + untaught: [attn.planning.max_streams]bool = @splat(false), ready: u32, // slots [0, ready) have their K/V rows; a later slot takes its own when first used (ensure) capacity: u32, active: ?[32]u8 = null, failed: bool = false, capture_taps: bool = false, tail: ?forward.Tail = null, + learning_rows: bool = false, // the trainer uses the same row kernels with fewer submissions + learning_io: ?std.Io = null, + learning_stats: @import("train_submit.zig").Stats = .{}, accepted_chain: bool = false, last_gpu_seconds: f64 = 0, gpu_seconds: f64 = 0, // with a trace attached: every pass's GPU-busy seconds, its spans' and share's buffers too @@ -261,8 +265,14 @@ pub const Runner = struct { defer pool.pop(); const spanned = if (r.trace) |t| t.spanned else 0; // a profiled pass's spans commit buffers of their own const handed = if (r.model.ane) |share| share.gpu_seconds else 0; + if (r.model.pockets) |*pockets| { + pockets.selected = try @import("pocket_rows.zig").Selection.windows(round.slots, round.firsts, round.windows, &r.untaught); + } var stages = forward.Stages{ .model = r.model, .rows = @intCast(round.ids.len), .hooks = .{ .ptr = r, .gdn = gdnForward, .attention = attentionForward, .tap = if (r.capture_taps) tap else null }, .head = head, .tail = r.tail, .images = placed.images, .reduce = r.reduce, .picks = r.picks }; - r.last_gpu_seconds = @import("core").segments.runCommitting(r.model.device, &.{r.model.queue}, r.model.config.layers, .concurrent, &stages, commit_every) catch |err| { + r.last_gpu_seconds = (if (schedule.commitEvery(r.learning_rows) == 0) + @import("train_submit.zig").run(r.model.queue, RowProgram{ .stages = &stages, .layers = r.model.config.layers }, &r.learning_stats, r.learning_io) + else + @import("core").segments.runCommitting(r.model.device, &.{r.model.queue}, r.model.config.layers, .concurrent, &stages, 4)) catch |err| { r.failed = true; return err; }; @@ -453,7 +463,7 @@ pub const Runner = struct { fn gdnForward(ptr: *anyopaque, e: mtl.ComputeEncoder, block: usize, weights: wts.Gdn, frame: *Frame, rows: u32) !void { const r: *Runner = @ptrCast(@alignCast(ptr)); - var hook = GdnHook{ .pool = &r.gdn, .quant = &r.model.kernels, .glue = r.model.glue, .plan = r.current_gdn orelse return error.RoundNotReady, .linear_index = r.linear_index, .accepted_chain = r.accepted_chain }; + var hook = GdnHook{ .pool = &r.gdn, .quant = &r.model.kernels, .glue = r.model.glue, .plan = r.current_gdn orelse return error.RoundNotReady, .linear_index = r.linear_index, .accepted_chain = r.accepted_chain, .learning = r.model.learning }; try GdnHook.forward(&hook, e, block, weights, frame, rows); } @@ -471,7 +481,9 @@ pub const Runner = struct { try r.model.glue.unstack(e, f.get(.mixed), f.get(.key), .{ .rows = rows, .width = kv, .stride = 2 * kv, .offset = 0 }); try r.model.glue.unstack(e, f.get(.mixed), f.get(.value), .{ .rows = rows, .width = kv, .stride = 2 * kv, .offset = kv }); e.barrier(); + try r.model.capture(e, .attention, block, &.{ f.get(.q_gate), f.get(.key), f.get(.value) }, rows); try r.attention.preprocess(e, .{ .qg = f.get(.q_gate), .key = f.get(.key), .q_gain = wts.ref(weights.q_norm), .k_gain = wts.ref(weights.k_norm), .norm_q = f.get(.norm_query), .norm_k = f.get(.norm_key), .query = f.get(.query), .rotated_key = f.get(.rotated_key), .positions = f.get(.positions), .rows = rows, .eps = r.model.config.eps, .theta = r.model.config.rope_theta, .h_end = r.current_placed.h_end, .w_end = r.current_placed.w_end, .plane = f.capacity, .geometry = r.geometry }); + try r.model.capture(e, .prepared_attention, block, &.{ f.get(.query), f.get(.rotated_key), f.get(.value) }, rows); try r.attention.encode(e, &r.scratch, &r.bindings[layer], plan, f.get(.query), f.get(.rotated_key), f.get(.value), f.get(.mixer_out), caches, f.get(.q_gate), r.model.kernels.prompt, r.reduce != null); } @@ -514,3 +526,18 @@ fn fingerprint(round: *const Round) [32]u8 { hash.final(&out); return out; } + +const RowProgram = struct { + stages: *forward.Stages, + layers: usize, + pub fn encode(p: @This(), e: mtl.ComputeEncoder) !void { + var lane: @import("core").segments.Lane = .{ .k = 0, .cb = undefined, .enc = e, .fence = undefined }; + try p.stages.begin(&lane); + for (0..p.layers) |l| { + try p.stages.pre(&lane, l); + try p.stages.mixer(&lane, l); + try p.stages.post(&lane, l); + } + try p.stages.finish(&lane); + } +}; diff --git a/zig/src/families/qwen27/forward.zig b/zig/src/families/qwen27/forward.zig index 2a415ccafff..c209a330e96 100644 --- a/zig/src/families/qwen27/forward.zig +++ b/zig/src/families/qwen27/forward.zig @@ -104,6 +104,7 @@ pub const Stages = struct { std.mem.swap(Ref, &s.hidden, &s.residual); if (s.hooks.tap) |tap| try tap(s.hooks.ptr, e, index - 1, s.hidden, s.rows); } + try m.capture(e, .input, index, &.{ s.hidden, f.get(.input) }, s.rows); } pub fn mixer(s: *Stages, lane: *@import("core").segments.Lane, index: usize) !void { const m = s.model; @@ -112,6 +113,7 @@ pub const Stages = struct { .attention => |a| try s.hooks.attention(s.hooks.ptr, lane.enc, index, a, &m.frame, s.rows), } lane.enc.barrier(); + try m.capture(lane.enc, .gated, index, &.{m.frame.get(.mixer_out)}, s.rows); } pub fn post(s: *Stages, lane: *@import("core").segments.Lane, index: usize) !void { const m = s.model; @@ -148,6 +150,7 @@ pub const Stages = struct { try m.kernels.norm(e, s.hidden, f.get(.output), wts.ref(layer.post_norm), f.get(.eps), f.get(.dims), s.residual, f.get(.input), f.get(.sums), h, s.rows); e.barrier(); std.mem.swap(Ref, &s.hidden, &s.residual); + try m.capture(e, .post, index, &.{ s.hidden, f.get(.input) }, s.rows); var up = f.get(.mixed); up.offset += @as(usize, m.config.intermediate) * 2; const width: u32 = @intCast(m.config.intermediate); @@ -174,11 +177,13 @@ pub const Stages = struct { try m.kernels.addAne(lane.enc, .{ .buffer = share.partial }, .{ .buffer = share.outputs[slice].buffer }, f.get(.output), h, width, share.columns, @min(ane_mlp.width, s.rows - base), base); } lane.enc.barrier(); + try m.addPocket(lane.enc, index, f.get(.input), f.get(.output), s.rows); s.pending = f.get(.output); return; } else { try m.kernels.quant(e, layer.gu, f.get(.input), sums(f, .sums, s.rows), f.get(.dims), f.get(.mixed), s.rows); e.barrier(); + try m.capture(e, .mlp, index, &.{f.get(.mixed)}, s.rows); try m.kernels.mlp(e, f.get(.mixed), up, f.get(.dims), f.get(.activated), f.get(.act_sums), width, s.rows); } lane.enc.barrier(); @@ -205,6 +210,7 @@ pub const Stages = struct { if (s.reduce.?.broken()) return error.PairFailed; e.barrier(); } + try m.addPocket(lane.enc, index, f.get(.input), f.get(.output), s.rows); s.pending = f.get(.output); } pub fn finish(s: *Stages, lane: *@import("core").segments.Lane) !void { @@ -215,6 +221,7 @@ pub const Stages = struct { try m.kernels.norm(e, s.hidden, s.pending, wts.ref(m.weights.norm), f.get(.eps), f.get(.dims), s.residual, f.get(.input), f.get(.sums), @intCast(m.config.hidden), s.rows); e.barrier(); std.mem.swap(Ref, &s.hidden, &s.residual); + try m.capture(e, .final, m.config.layers, &.{ s.hidden, f.get(.input) }, s.rows); if (s.hooks.tap) |tap| try tap(s.hooks.ptr, e, m.config.layers - 1, s.hidden, s.rows); if (s.head == .all and s.rows > @import("gpu_frame.zig").logit_rows) return error.BadFrameRows; if (s.head != .none) { @@ -227,6 +234,7 @@ pub const Stages = struct { try m.kernels.quant(e, m.weights.head, input, head_sums, f.get(.dims), f.get(.logits), if (s.head == .last) 1 else s.rows); } e.barrier(); + if (s.head != .none) try m.capture(e, .logits, m.config.layers, &.{f.get(.logits)}, if (s.head == .last) 1 else s.rows); if (s.reduce) |r| { if (s.head != .none) { const picks = s.picks orelse return error.HeadSeamMissing; diff --git a/zig/src/families/qwen27/gdn_hook.zig b/zig/src/families/qwen27/gdn_hook.zig index 944fd7aa307..d52a091f448 100644 --- a/zig/src/families/qwen27/gdn_hook.zig +++ b/zig/src/families/qwen27/gdn_hook.zig @@ -15,6 +15,7 @@ pub const Hook = struct { plan: *const Plan, linear_index: []const u32, accepted_chain: bool = false, + learning: ?@import("train_hooks.zig").Hooks = null, pub fn forward(ptr: *anyopaque, e: metal.ComputeEncoder, block: usize, weight: Weights.Gdn, frame: *Frame, rows: u32) !void { const hook: *Hook = @ptrCast(@alignCast(ptr)); @@ -24,7 +25,12 @@ pub const Hook = struct { try hook.quant.quant(e, weight.qkv, frame.get(.input), sums, frame.get(.dims), try hook.pool.projected(layer), rows); try hook.quant.quant(e, weight.zba, frame.get(.input), sums, frame.get(.dims), frame.get(.mixed), rows); e.barrier(); + if (hook.learning) |keep| try keep.capture(e, .gdn, block, &.{ try hook.pool.projected(layer), frame.get(.mixed) }, rows); if (hook.accepted_chain) try hook.pool.forwardChain(layer, devicePlan(hook.plan.*, frame), try refs(weight, frame), e, hook.quant.prompt) else try hook.pool.forward(layer, devicePlan(hook.plan.*, frame), try refs(weight, frame), e); + if (hook.learning) |keep| { + const saved = try hook.pool.trainingRows(layer); + try keep.capture(e, .gdn_state, block, &saved, rows); + } } pub fn commit(hook: *Hook, e: metal.ComputeEncoder, block: usize, frame: *Frame) !void { diff --git a/zig/src/families/qwen27/gdn_pool_gpu.zig b/zig/src/families/qwen27/gdn_pool_gpu.zig index ced5aea0e31..a715751739b 100644 --- a/zig/src/families/qwen27/gdn_pool_gpu.zig +++ b/zig/src/families/qwen27/gdn_pool_gpu.zig @@ -149,6 +149,16 @@ pub const Pool = struct { return .{ .buffer = span.buffer, .offset = span.offset }; } + /// Prepared native rows, captured after the scan before this scratch is reused by the next layer. + pub fn trainingRows(pool: *const Pool, layer: usize) ![6]Ref { + var refs: [6]Ref = undefined; + inline for (.{ Field.query, Field.key, Field.value, Field.decay, Field.mixing, Field.recurrent }, 0..) |field, i| { + const span = if (field == .recurrent) gdn.Span{ .buffer = pool.get(field), .bytes = pool.get(field).length() } else try pool.layerSpan(field, layer); + refs[i] = .{ .buffer = span.buffer, .offset = span.offset }; + } + return refs; + } + pub fn forward(pool: *Pool, layer: usize, plan: DevicePlan, refs: Refs, e: metal.ComputeEncoder) !void { try @import("gdn_pool.zig").validatePlan(pool.budget.shape, pool.budget.slots, pool.budget.rows, plan.host); const prepared = try pool.round(layer, plan, refs, false); diff --git a/zig/src/families/qwen27/gpu_weights.zig b/zig/src/families/qwen27/gpu_weights.zig index 6ce0b1ee3f3..bf254af815d 100644 --- a/zig/src/families/qwen27/gpu_weights.zig +++ b/zig/src/families/qwen27/gpu_weights.zig @@ -110,13 +110,40 @@ const Builder = struct { }; try b.stage.reserve(b.checkpoint, names); defer b.stage.reset(); + var cuts: std.ArrayList(mtl.Buffer) = .empty; + defer { + for (cuts.items) |buffer| buffer.deinit(); + cuts.deinit(b.allocator); + } var triples: [3]projection.Triple = undefined; for (parts, triples[0..parts.len], 0..) |p, *t, i| { - t.* = try viewed(p, k, .{ - try b.stage.read(b.checkpoint, names[i * 3]), - try b.stage.read(b.checkpoint, names[i * 3 + 1]), - try b.stage.read(b.checkpoint, names[i * 3 + 2]), - }); + if (k * p.w.bits % 32 != 0 or k % p.w.group != 0) return error.BadNativeTensor; + var tensors: [3]Tensor = undefined; + for (&tensors, 0..) |*item, j| { + const dtype: cp.DType = if (j == 0) .u32 else .bf16; + const nk = k + p.extra_cols; + const columns = if (j == 0) nk * p.w.bits / 32 else nk / p.w.group; + const base_columns = if (j == 0) k * p.w.bits / 32 else k / p.w.group; + item.* = try checked(try b.stage.read(b.checkpoint, names[i * 3 + j]), dtype, &.{ p.n + p.extra_rows, columns }); + if ((p.extra_rows != 0 or p.extra_cols != 0) and (p.w.bits != 4 or p.w.group != 64)) return error.BadPocketFormat; + const stride = columns * dtype.size(); + const kept = base_columns * dtype.size(); + if (p.extra_cols != 0) { + const buffer = try b.device.buffer(p.n * kept, mtl.ResourceOptions.shared | mtl.ResourceOptions.untracked); + cuts.append(b.allocator, buffer) catch |err| { + buffer.deinit(); + return err; + }; + const bytes = item.host(u8); + try @import("core").dense_pocket.copyBase(bytes, p.n, stride, kept, buffer.slice(u8, p.n * kept)); + item.buffer = buffer; + item.offset = 0; + } + item.bytes = p.n * kept; + item.shape[0] = p.n; + item.shape[1] = base_columns; + } + t.* = try viewed(p, k, tensors); } return b.stack(triples[0..parts.len]); } @@ -243,10 +270,10 @@ const Builder = struct { } }, }; const gu = try b.linear(&.{ - .{ .module = try Name.full(a, prefix, "mlp.gate_proj"), .n = g.intermediate, .w = w[@backingInt(M.gate)], .span = s.intermediateRows() }, - .{ .module = try Name.full(a, prefix, "mlp.up_proj"), .n = g.intermediate, .w = w[@backingInt(M.up)], .span = s.intermediateRows() }, + .{ .module = try Name.full(a, prefix, "mlp.gate_proj"), .n = g.intermediate, .extra_rows = g.pocket, .w = w[@backingInt(M.gate)], .span = s.intermediateRows() }, + .{ .module = try Name.full(a, prefix, "mlp.up_proj"), .n = g.intermediate, .extra_rows = g.pocket, .w = w[@backingInt(M.up)], .span = s.intermediateRows() }, }, g.hidden); - const down = try b.linear(&.{.{ .module = try Name.full(a, prefix, "mlp.down_proj"), .n = g.hidden, .w = w[@backingInt(M.down)], .span = s.outputRows() }}, g.intermediate); + const down = try b.linear(&.{.{ .module = try Name.full(a, prefix, "mlp.down_proj"), .n = g.hidden, .extra_cols = g.pocket, .w = w[@backingInt(M.down)], .span = s.outputRows() }}, g.intermediate); return .{ .norm = try b.tensor(try Name.full(a, prefix, "input_layernorm.weight"), .bf16, &.{c.hidden}), .post_norm = try b.tensor(try Name.full(a, prefix, "post_attention_layernorm.weight"), .bf16, &.{c.hidden}), .gu = gu, .down = down, .mixer = mixer }; } }; @@ -259,6 +286,8 @@ const Part = struct { w: Width, /// The rows this rank takes: the whole tensor unless the rank splits this matrix. span: cfg.Span = .{}, + extra_rows: usize = 0, + extra_cols: usize = 0, }; /// Rows `[span.from, end)` of `t`: rows are contiguous, so the same buffer at a later offset and a shorter shape. @@ -368,3 +397,59 @@ test "A_log loads in bf16 or in f32, as mlx-vlm conversions store it, and refuse t.bytes = 32 * 4; try std.testing.expectError(error.BadNativeTensor, decayLog(t, &.{48})); } + +test "qwen27 linear: mixed widths keep main word counts views and copies without a pocket" { + if (comptime !@hasDecl(mtl, "Record")) return error.SkipZigTest; + const a = std.testing.allocator; + for ([_]u8{ 2, 3, 4, 5, 6, 8 }) |bits| { + var record: mtl.Record = .{ .a = a }; + const device = record.device(); + { + var ck = cp.Checkpoint.init(a); + defer ck.deinit(); + const n = 16; + const k: usize = 5120; + const words = k * bits / 32; + for ([_][]const u8{ "x.weight", "x.scales", "x.biases" }, 0..) |name, i| { + const columns: usize = if (i == 0) words else k / 64; + const dtype: cp.DType = if (i == 0) .u32 else .bf16; + const bytes = n * columns * dtype.size(); + const buffer = try device.buffer(bytes, 0); + try ck.own(buffer, bytes); + for (buffer.contents()[0..bytes], 0..) |*v, at| v.* = @truncate((at * 17 + i * 31) % 251); + var tensor: Tensor = .{ .buffer = buffer, .offset = 0, .bytes = bytes, .dtype = dtype, .rank = 2 }; + tensor.shape[0] = n; + tensor.shape[1] = columns; + try ck.set(name, tensor); + } + var owned: std.ArrayList(mtl.Buffer) = .empty; + defer { + for (owned.items) |buffer| buffer.deinit(); + owned.deinit(a); + } + var runs: std.ArrayList([]projection.Run) = .empty; + defer { + for (runs.items) |r| a.free(r); + runs.deinit(a); + } + var stage = cp.Stage{ .device = device }; + defer stage.deinit(); + const builder: Builder = .{ .allocator = a, .device = device, .checkpoint = &ck, .prefix = "", .owned = &owned, .stage = &stage, .runs = &runs, .widths = undefined }; + const part: Part = .{ .module = "x", .n = n, .w = .{ .bits = bits, .group = 64 }, .span = .{ .from = 8, .len = 8 } }; + const original = [_]Tensor{ try ck.get("x.weight"), try ck.get("x.scales"), try ck.get("x.biases") }; + const view = try Builder.viewed(part, k, original); + try std.testing.expectEqual(@as(usize, words), view.weight.shape[1]); + try std.testing.expectEqual(@as(usize, 8 * words * 4), view.weight.offset); + const loaded = try builder.linear(&.{part}, k); + try std.testing.expectEqual(bits, loaded.bits); + try std.testing.expectEqual(@as(u32, k), loaded.k); + try std.testing.expectEqual(@as(u32, 8), loaded.n); + const raw = loaded.raw.?; + try std.testing.expectEqualSlices(u8, view.weight.host(u8), raw.w.contents()[raw.w_off..][0..view.weight.bytes]); + try std.testing.expectEqualSlices(u8, view.scales.host(u8), raw.scales.contents()[raw.s_off..][0..view.scales.bytes]); + try std.testing.expectEqualSlices(u8, view.biases.host(u8), raw.biases.contents()[raw.b_off..][0..view.biases.bytes]); + try std.testing.expectEqual(@as(usize, 0), stage.used); + } + try std.testing.expectEqual(@as(usize, 0), record.live); + } +} diff --git a/zig/src/families/qwen27/model.zig b/zig/src/families/qwen27/model.zig index 86f4b260099..de3b7074f49 100644 --- a/zig/src/families/qwen27/model.zig +++ b/zig/src/families/qwen27/model.zig @@ -27,6 +27,9 @@ pub const Model = struct { kernels: quant.Kernels, glue: glue.Kernels, frame: Frame, + pockets: ?@import("pocket.zig").Pockets = null, + learning: ?@import("train_hooks.zig").Hooks = null, + learn_reserved: u64 = 0, /// The Neural Engine's share of prompt-chunk MLPs, when it loaded. ane: ?*ane_mlp.Share = null, /// A deferred share still needs the checkpoint mappings, until loadShare decides and closes them. @@ -110,8 +113,16 @@ pub const Model = struct { defer core.checkpoint_host.freeShardFiles(a, files); // projections stay in the files until load repacks them: the weights live once, in their lane layouts for (files) |file| try m.checkpoint.addFileSplit(m.device, file, "", "language_model.", wts.repacked); + m.pockets = null; + m.learning = null; + m.learn_reserved = 0; + errdefer if (m.pockets) |*pockets| pockets.deinit(); m.weights = try wts.load(a, m.device, &m.checkpoint, &m.shard, &ws); errdefer m.weights.deinit(); + if (c.pocket > 0) { + m.pockets = try @import("pocket.zig").Pockets.init(a, m.device, c.hidden, c.layers); + try m.pockets.?.load(io, dir, c); + } m.kernels = .{ .allocator = a, .device = m.device, .raw_tiles = !m.device.tensorUnits(), .long_prompt = quant.longPrompt(std.mem.span(m.device.name()), m.device.tensorUnits()) }; errdefer m.kernels.deinit(); m.glue = try glue.Kernels.init(m.device); @@ -169,9 +180,19 @@ pub const Model = struct { return if (m.ane) |share| share.cacheBytes(m.config) else 0; } + pub fn capture(m: *Model, e: mtl.ComputeEncoder, point: @import("train_hooks.zig").Point, layer: usize, refs: []const @import("projection.zig").Ref, rows: u32) !void { + if (m.learning) |hooks| try hooks.capture(e, point, layer, refs, rows); + } + + pub fn addPocket(m: *Model, e: mtl.ComputeEncoder, layer: usize, input: @import("projection.zig").Ref, output: @import("projection.zig").Ref, rows: usize) !void { + if (m.learning) |hooks| return hooks.add(hooks.ctx, e, layer, input, output, @intCast(rows)); + if (m.pockets) |*pockets| try pockets.add(e, layer, input, output, rows); + } + pub fn deinit(m: *Model) void { if (m.ane) |share| share.deinit(); m.frame.deinit(); + if (m.pockets) |*pockets| pockets.deinit(); m.glue.deinit(); m.kernels.deinit(); m.weights.deinit(); diff --git a/zig/src/families/qwen27/pocket.zig b/zig/src/families/qwen27/pocket.zig new file mode 100644 index 00000000000..048fac26690 --- /dev/null +++ b/zig/src/families/qwen27/pocket.zig @@ -0,0 +1,138 @@ +//! Saved affine pocket rows beside the original dense MLP; empty layers allocate and launch no GPU work. +const std = @import("std"); +const mtl = @import("metal"); +const core = @import("core"); +pub const config = @import("config.zig"); +const Config = config.Config; +const Ref = @import("projection.zig").Ref; +const Selection = @import("pocket_rows.zig").Selection; +const max_neurons = 64; + +pub const Rows = struct { weights: mtl.Buffer, cap: usize, used: usize }; +pub const Pockets = struct { + allocator: std.mem.Allocator, + device: mtl.Device, + hidden: usize, + layers: []?Rows, + kernel: ?mtl.Pipeline = null, + selected: Selection = .{}, + residency: ?mtl.ResidencySet.Follow = null, + + pub fn init(a: std.mem.Allocator, device: mtl.Device, hidden: usize, layers: usize) !Pockets { + const list = try a.alloc(?Rows, layers); + @memset(list, null); + return .{ .allocator = a, .device = device, .hidden = hidden, .layers = list }; + } + + pub fn deinit(p: *Pockets) void { + p.setResident(null); + for (p.layers) |slot| if (slot) |rows| rows.weights.deinit(); + if (p.kernel) |kernel| kernel.deinit(); + p.allocator.free(p.layers); + p.* = undefined; + } + + /// The caller drains prior GPU work before replacing a layer's shared rows. + pub fn set(p: *Pockets, layer: usize, gate: []const f32, up: []const f32, down: []const f32, used: usize) !void { + if (layer >= p.layers.len or p.hidden == 0 or gate.len % p.hidden != 0) return error.BadPocketShape; + const n = gate.len / p.hidden; + if (n == 0 or n > max_neurons or used > n or up.len != gate.len or down.len != gate.len) return error.BadPocketShape; + if (used == 0 and p.layers[layer] == null) return; + const buffer = try p.device.buffer(3 * gate.len * 4, mtl.ResourceOptions.shared | mtl.ResourceOptions.untracked); + errdefer buffer.deinit(); + const values = buffer.slice(f32, 3 * gate.len); + @memcpy(values[0..gate.len], gate); + @memcpy(values[gate.len..][0..up.len], up); + @memcpy(values[2 * gate.len ..], down); + if (p.kernel == null and used > 0) { + const lib = try mtl.Library.fromSource(p.device, @import("qwen_runtime_sources").pocket, mtl.CompileOptions.mlx()); + defer lib.deinit(); + p.kernel = try mtl.Pipeline.init(p.device, lib, "tf_q27_pocket_rows", false); + } + if (p.residency) |hook| hook.join(hook.ctx, buffer); + if (p.layers[layer]) |old| { + if (p.residency) |hook| hook.leave(hook.ctx, old.weights); + old.weights.deinit(); + } + p.layers[layer] = .{ .weights = buffer, .cap = n, .used = used }; + } + + pub fn read(p: *const Pockets, layer: usize, gate: []f32, up: []f32, down: []f32) !usize { + if (layer >= p.layers.len) return error.BadPocketShape; + const slot = p.layers[layer] orelse { + @memset(gate, 0); + @memset(up, 0); + @memset(down, 0); + return 0; + }; + if (gate.len != slot.cap * p.hidden or up.len != gate.len or down.len != gate.len) return error.BadPocketShape; + const values = slot.weights.slice(f32, 3 * gate.len); + @memcpy(gate, values[0..gate.len]); + @memcpy(up, values[gate.len..][0..up.len]); + @memcpy(down, values[2 * gate.len ..]); + return slot.used; + } + + pub fn any(p: *const Pockets) bool { + for (p.layers) |slot| if (slot) |rows| if (rows.used != 0) return true; + return false; + } + + pub fn add(p: *const Pockets, e: mtl.ComputeEncoder, layer: usize, input: Ref, output: Ref, rows: usize) !void { + const slot = p.layers[layer] orelse return; + if (slot.used == 0) return; + if (p.selected.all) return p.run(e, slot, input, output, .{ .first = 0, .count = rows }); + for (p.selected.ranges[0..p.selected.count]) |range| { + if (range.first > rows or range.count > rows - range.first) return error.BadPocketRows; + try p.run(e, slot, input, output, range); + } + } + + fn run(p: *const Pockets, e: mtl.ComputeEncoder, slot: Rows, input: Ref, output: Ref, range: Selection.Range) !void { + if (range.count == 0) return; + const kernel = p.kernel orelse return error.MissingPocketKernel; + if (kernel.maxThreads() < 256) return error.UnsupportedPocketGroup; + const offset = range.first * p.hidden * 2; + e.setPipeline(kernel); + e.setBuffer(input.buffer, input.offset + offset, 0); + e.setBuffer(slot.weights, 0, 1); + e.setBuffer(output.buffer, output.offset + offset, 2); + e.setValue(@Vector(4, u32){ @intCast(p.hidden), @intCast(slot.used), @intCast(slot.cap), 0 }, 3); + e.dispatchGroups(.{ .width = range.count }, .{ .width = 256 }); + e.barrier(); + } + + pub fn load(p: *Pockets, io: std.Io, dir: []const u8, c: Config) !void { + if (c.pocket == 0) return; + var ck = try core.Checkpoint.openModel(p.allocator, io, dir); + defer ck.close(); + const scoped = ck.has("language_model.model.layers.0.mlp.gate_proj.weight"); + if (scoped == ck.has("model.layers.0.mlp.gate_proj.weight")) return error.BadPocketNamespace; + const prefix: []const u8 = if (scoped) "language_model." else ""; + const n = c.pocket * c.hidden; + const host = try p.allocator.alloc(f32, 3 * n); + defer p.allocator.free(host); + for (0..c.layers) |layer| { + var buf: [128]u8 = undefined; + const base = try std.fmt.bufPrint(&buf, "{s}model.layers.{d}.", .{ prefix, layer }); + try core.dense_pocket.read(&ck, base, "mlp.gate_proj", c.intermediate, c.hidden, host[0..n]); + try core.dense_pocket.read(&ck, base, "mlp.up_proj", c.intermediate, c.hidden, host[n..][0..n]); + try core.dense_pocket.read(&ck, base, "mlp.down_proj", c.hidden, c.intermediate, host[2 * n ..][0..n]); + var used: usize = 0; + for (0..c.pocket) |j| if (std.mem.indexOfNone(f32, host[n + j * c.hidden ..][0..c.hidden], &.{0}) != null) { + used = j + 1; + }; + try p.set(layer, host[0..n], host[n..][0..n], host[2 * n ..][0..n], used); + } + } + + pub fn appendBuffers(p: *const Pockets, a: std.mem.Allocator, list: *std.ArrayList(mtl.Buffer)) !void { + for (p.layers) |slot| if (slot) |rows| try list.append(a, rows.weights); + } + + pub fn setResident(p: *Pockets, follow: ?mtl.ResidencySet.Follow) void { + if (p.residency) |old| for (p.layers) |slot| if (slot) |rows| old.leave(old.ctx, rows.weights); + p.residency = follow; + if (follow) |hook| for (p.layers) |slot| if (slot) |rows| hook.join(hook.ctx, rows.weights); + } +}; diff --git a/zig/src/families/qwen27/pocket_rows.zig b/zig/src/families/qwen27/pocket_rows.zig new file mode 100644 index 00000000000..39bcce112b0 --- /dev/null +++ b/zig/src/families/qwen27/pocket_rows.zig @@ -0,0 +1,50 @@ +//! Taught row runs for a shared pass; untaught streams have no pocket dispatch. +const std = @import("std"); + +pub const Selection = struct { + pub const Range = struct { first: usize, count: usize }; + ranges: [128]Range = undefined, + count: usize = 0, + all: bool = true, + + pub fn windows(slots: []const u32, firsts: []const u32, spans: anytype, untaught: []const bool) !Selection { + if (slots.len != firsts.len or slots.len != spans.len) return error.BadPocketRows; + var selected: Selection = .{ .all = false }; + for (slots, firsts, spans) |slot, first, span| { + if (slot >= untaught.len) return error.BadPocketRows; + if (!untaught[slot]) try selected.add(first, span.parents.len); + } + return selected; + } + + pub fn add(s: *Selection, first: usize, count: usize) !void { + if (count == 0) return; + _ = std.math.add(usize, first, count) catch return error.BadPocketRows; + if (s.count > 0) { + const last = &s.ranges[s.count - 1]; + if (last.first + last.count == first) { + last.count += count; + return; + } + if (last.first + last.count > first) return error.BadPocketRows; + } + if (s.count == s.ranges.len) return error.BadPocketRows; + s.ranges[s.count] = .{ .first = first, .count = count }; + s.count += 1; + } +}; + +test "mixed taught and untaught windows dispatch only taught runs, including a 2048-row prompt" { + var s: Selection = .{ .all = false }; + try s.add(0, 3); + try s.add(5, 2); + try s.add(7, 4); + try std.testing.expectEqual(@as(usize, 2), s.count); + try std.testing.expectEqual(Selection.Range{ .first = 0, .count = 3 }, s.ranges[0]); + try std.testing.expectEqual(Selection.Range{ .first = 5, .count = 6 }, s.ranges[1]); + s = .{ .all = false }; + try std.testing.expectEqual(@as(usize, 0), s.count); + try s.add(0, 2048); + try std.testing.expectEqual(@as(usize, 2048), s.ranges[0].count); + try std.testing.expectError(error.BadPocketRows, s.add(2047, 1)); +} diff --git a/zig/src/families/qwen27/pocket_storage.zig b/zig/src/families/qwen27/pocket_storage.zig new file mode 100644 index 00000000000..a3b19679e0a --- /dev/null +++ b/zig/src/families/qwen27/pocket_storage.zig @@ -0,0 +1,44 @@ +//! Portable dense pocket saves preserve the checkpoint's tensor namespace and config scope. +const std = @import("std"); +const living = @import("living"); +const core = @import("core"); + +pub fn save(a: std.mem.Allocator, io: std.Io, dir: []const u8, lay: living.Layout, layers: []const usize, neurons: usize, gate: []f32, up: []f32, down: []f32) !usize { + // The native loader accepts both public namespaces. Keep the folder's names and config key scope as stored. + const scoped = try namespace(a, io, dir); + const path = try std.fs.path.join(a, &.{ dir, "config.json" }); + defer a.free(path); + const text = try std.Io.Dir.cwd().readFileAlloc(io, path, a, .limited(16 << 20)); + defer a.free(text); + var doc = try std.json.parseFromSlice(std.json.Value, a, text, .{}); + defer doc.deinit(); + if (doc.value != .object) return error.BadConfig; + const wrapped = doc.value.object.contains("text_config"); + inline for (.{ false, true }) |scope| inline for (.{ false, true }) |wrap| { + if (scoped == scope and wrapped == wrap) return living.shards.Io(core).writePending(a, io, dir, storedFamily(scope, wrap), lay, layers, neurons, &.{ gate, up }, down); + }; + unreachable; +} + +// A save owns the pending transaction; inspect headers only, without reopening it as a serving checkpoint. +fn namespace(a: std.mem.Allocator, io: std.Io, dir: []const u8) !bool { + const paths = try core.checkpoint_host.shardFiles(a, io, dir); + defer core.checkpoint_host.freeShardFiles(a, paths); + var scoped = false; + var plain = false; + for (paths) |path| { + var f = try core.safetensors.File.open(a, io, path); + defer f.close(io); + scoped = scoped or f.get("language_model.model.layers.0.mlp.gate_proj.weight") != null; + plain = plain or f.get("model.layers.0.mlp.gate_proj.weight") != null; + } + if (scoped == plain) return error.BadPocketNamespace; + return scoped; +} + +fn storedFamily(comptime scoped: bool, comptime wrapped: bool) living.family.Family { + var f = living.families.qwen3_5; + if (!scoped) f.names.layers = "model.layers."; + if (!wrapped) f.keys.scope = null; + return f; +} diff --git a/zig/src/families/qwen27/qwen27.zig b/zig/src/families/qwen27/qwen27.zig index 94752124645..b1487ca276a 100644 --- a/zig/src/families/qwen27/qwen27.zig +++ b/zig/src/families/qwen27/qwen27.zig @@ -1,6 +1,11 @@ //! Dense Qwen text configuration and checkpoint contracts. GPU forward pieces follow separately. +pub const learning_epoch = @import("train_epoch.zig"); +pub const train = @import("train.zig"); +pub const slide = @import("slide.zig"); +pub const train_memory = @import("train_memory.zig"); pub const dflash = @import("dflash/root.zig"); pub const config = @import("config.zig"); +pub const train_admission = @import("train_admission.zig"); pub const affine = @import("affine.zig"); pub const widths = @import("widths.zig"); pub const checkpoint = @import("checkpoint.zig"); @@ -45,6 +50,7 @@ pub const tap_ring = @import("tap_ring.zig"); /// The 27B's Metal sources by name (the kernel contract compiles them as the engine does). pub const runtime_sources = @import("qwen_runtime_sources"); test { + _ = @import("train_host.zig"); _ = dflash; _ = disk; _ = @import("core").gpu_profile; @@ -65,6 +71,7 @@ test { _ = prompt_state; _ = prompt_marks; _ = config; + _ = pocket_rows; _ = affine; _ = widths; _ = checkpoint; @@ -73,3 +80,6 @@ test { } pub const residency = @import("residency.zig"); + +pub const pocket = @import("pocket.zig"); +pub const pocket_rows = @import("pocket_rows.zig"); diff --git a/zig/src/families/qwen27/residency.zig b/zig/src/families/qwen27/residency.zig index bb14753233e..6c50d24cdcd 100644 --- a/zig/src/families/qwen27/residency.zig +++ b/zig/src/families/qwen27/residency.zig @@ -126,6 +126,7 @@ pub fn hold(h: anytype, io: std.Io) !void { defer list.deinit(h.gpa); for (h.model.checkpoint.shards.items) |s| try list.append(h.gpa, s.buffer); try list.appendSlice(h.gpa, h.model.weights.owned.items); + if (h.model.pockets) |*pockets| try pockets.appendBuffers(h.gpa, &list); try h.model.frame.appendBuffers(h.gpa, &list); if (h.model.ane) |share| { var buffers: ShareBuffers = undefined; @@ -149,6 +150,7 @@ pub fn hold(h: anytype, io: std.Io) !void { h.resident = try mtl.resident.Resident.hold(h.gpa, io, h.model.device, h.model.queue, list.items, "qwen27"); if (h.resident) |*r| { h.model.kernels.setResident(r.follow()); + if (h.model.pockets) |*pockets| pockets.setResident(r.follow()); h.runner.setResident(r.follow()); setBack(h.back, r.follow()); if (h.draft) |d| d.model.backend.setResident(r.follow()); @@ -158,6 +160,7 @@ pub fn hold(h: anytype, io: std.Io) !void { pub fn drop(h: anytype) void { h.model.kernels.setResident(null); + if (h.model.pockets) |*pockets| pockets.setResident(null); h.runner.setResident(null); setBack(h.back, null); if (h.draft) |d| d.model.backend.setResident(null); diff --git a/zig/src/families/qwen27/slide.zig b/zig/src/families/qwen27/slide.zig new file mode 100644 index 00000000000..e86fe761d03 --- /dev/null +++ b/zig/src/families/qwen27/slide.zig @@ -0,0 +1,65 @@ +//! The existing lesson gate and CUDA-compatible shard writer over the native Metal trainer. +const std = @import("std"); +const living = @import("living"); +const core = @import("core"); +const mtl = @import("metal"); +const train = @import("train.zig"); +const lessons = living.learner; +pub const family = living.families.qwen3_5; +pub const Example = lessons.Example; +pub const Lesson = lessons.Lesson; +pub const Report = lessons.Report; +pub const Step = lessons.Step; +pub const Model = struct { m: *@import("model.zig").Model, dir: []const u8, follow: ?mtl.ResidencySet.Follow = null }; +pub const linked = core.shard_edit.linked; + +pub fn layout(c: @import("config.zig").Config) living.Layout { + var every: living.Layers = .empty; + for (0..c.layers) |l| every.set(l); + return .fromExperts(c.hidden, c.intermediate, c.layers, every); +} +const Host = struct { + pub const Trainer = train.Trainer; + pub const max_rows = train.max_rows; + pub const Ctx = Model; + pub const family = living.families.qwen3_5; + pub fn layout(m: Ctx) living.Layout { + return @import("slide.zig").layout(m.m.config); + } + pub fn trainer(a: std.mem.Allocator, io: std.Io, m: Ctx) !*Trainer { + return Trainer.init(a, io, m.m, m.dir, m.follow); + } + pub fn drain(t: *Trainer) void { + t.drain(); + } + pub fn free(t: *Trainer, _: std.mem.Allocator) void { + t.deinit(); + } + pub fn seconds(io: std.Io) f64 { + return @as(f64, @floatFromInt(std.Io.Clock.awake.now(io).toNanoseconds())) / 1e9; + } + pub fn pocketSaveBegin(m: Ctx, _: std.mem.Allocator, io: std.Io) !void { + try @import("save_guard").begin(io, m.dir); + } + pub fn pocketSaveFinish(m: Ctx, _: std.mem.Allocator, io: std.Io) !void { + try @import("save_guard").finish(io, m.dir); + } + pub fn pocketSwiglu(m: Ctx, layer: usize, gate: []const f32, up: []const f32, down: []const f32, used: usize) !void { + if (m.m.pockets == null) { + m.m.pockets = try @import("pocket.zig").Pockets.init(m.m.allocator, m.m.device, m.m.config.hidden, m.m.config.layers); + m.m.pockets.?.setResident(m.follow); + } + try m.m.pockets.?.set(layer, gate, up, down, used); + } + pub fn pocketReadSwiglu(m: Ctx, layer: usize, gate: []f32, up: []f32, down: []f32) !usize { + if (m.m.pockets) |p| return p.read(layer, gate, up, down); + @memset(gate, 0); + @memset(up, 0); + @memset(down, 0); + return 0; + } + pub fn pocketSaveSwiglu(m: Ctx, a: std.mem.Allocator, io: std.Io, layers: []const usize, neurons: usize, gate: []f32, up: []f32, down: []f32) !usize { + return @import("pocket_storage.zig").save(a, io, m.dir, Host.layout(m), layers, neurons, gate, up, down); + } +}; +pub const Learner = lessons.Learner(Host); diff --git a/zig/src/families/qwen27/train.zig b/zig/src/families/qwen27/train.zig new file mode 100644 index 00000000000..53e582c2b1a --- /dev/null +++ b/zig/src/families/qwen27/train.zig @@ -0,0 +1,315 @@ +//! The shared Living Weights lesson gate over the 27B's actual Metal forward and native input-gradient backward. +const std = @import("std"); +const mtl = @import("metal"); +const living = @import("living"); +const Model = @import("model.zig").Model; +const Config = @import("config.zig").Config; +const Runner = @import("decode_round.zig").Runner; +pub const Row = @import("train_row.zig").Row; +const to = @import("train_ops.zig"); +const capture = @import("train_tape.zig"); +const load = @import("train_load.zig"); +const back = @import("train_back.zig"); +const more = @import("train_more.zig"); +const schedule = @import("train_schedule.zig"); +const submit = @import("train_submit.zig"); +const mode_api = living.train_mode; +pub const Turn = living.lesson_route.Turn; +pub const Mode = mode_api.Mode; +pub const Result = mode_api.Result; +pub const Seq = mode_api.Seq; +pub const Span = mode_api.Span; +pub const max_rows = 512; +pub const pack_rows = 1024; +pub const max_seqs = 8; +pub fn keepLow(layers: usize) usize { + return layers / 5; +} + +pub const Trainer = struct { + gpa: std.mem.Allocator, + io: ?std.Io = null, + m: *Model, + g: Config, + dir: []const u8, + k: to.Kernels = undefined, + k_ready: bool = false, + runner: Runner = undefined, + runner_ready: bool = false, + owned: std.ArrayList(mtl.Buffer) = .empty, + follow: ?mtl.ResidencySet.Follow = null, + w: []load.Layer = &.{}, + tape: []capture.Layer = &.{}, + head: to.Q4 = undefined, + sc: back.Scratch = undefined, + final_h: to.Ref = undefined, + logits: to.Ref = undefined, + dlogits: to.Ref = undefined, + grad: to.Ref = undefined, + dy: to.Ref = undefined, + delta: to.Ref = undefined, + push: to.Ref = undefined, + targets: to.Ref = undefined, + weights: to.Ref = undefined, + stats: to.Ref = undefined, + zero_history: to.Ref = undefined, + spans: [max_seqs]Span = undefined, + answers: [max_seqs]mode_api.Answer = undefined, + seqs: [max_seqs]Seq = undefined, + cp_first: [max_seqs]usize = @splat(0), + nseq: usize = 0, + rows: usize = 0, + pack: usize = pack_rows, + count: living.pocket_clock.Count = .{}, + prefixes: struct { + pub const most = 0; + } = .{}, + nudge: mode_api.Nudge = .{}, + from: [living.family.max_layers]u32 = @splat(std.math.maxInt(u32)), + keys_top: ?usize = null, + pocket_back: bool = true, + mode: Mode = .keys, + low: usize = 0, + hook_at: usize = 0, + local_row: usize = 0, + slot: u32 = 0, + reserved: u64 = 0, + + pub fn init(a: std.mem.Allocator, io: std.Io, m: *Model, dir: []const u8, follow: ?mtl.ResidencySet.Follow) !*Trainer { + if (m.widths_tag != 0 or m.config.dk != 128 or m.config.dv != 128 or m.config.conv_kernel != 4 or m.config.head_dim != 256) return error.UnsupportedLearningShape; + const t = try a.create(Trainer); + t.* = .{ .gpa = a, .io = if (std.c.getenv("TF_Q27_LEARN_DIAG") != null) io else null, .m = m, .g = m.config, .dir = dir, .follow = follow, .reserved = m.learn_reserved }; + m.learn_reserved = 0; // The allocation replaces the reservation, under the lane host's exclusive learn phase. + errdefer t.deinit(); + t.k = try to.Kernels.init(a, m.device); + t.k_ready = true; + t.runner = try Runner.init(a, m, max_seqs, max_rows + 1); + t.runner_ready = true; + t.runner.learning_rows = true; + t.runner.learning_io = t.io; + t.runner.setResident(follow); + try load.weights(t, io); + try capture.carve(t); + const g = t.g; + const R = pack_rows; + t.final_h = try t.alloc(R * g.hidden * 2); + t.logits = try t.alloc(R * g.vocab * 2); + t.dlogits = try t.alloc(R * g.vocab * 4); + t.grad = try t.alloc(R * g.hidden * 4); + t.dy = try t.alloc(R * g.hidden * 4); + const vectors = max_seqs * 3 * g.layers * g.hidden * 4; + t.delta = try t.alloc(vectors); + t.push = try t.alloc(vectors); + t.targets = try t.alloc(R * 4); + t.weights = try t.alloc(R * 4); + t.stats = try t.alloc(R * 8); + t.zero_history = try t.alloc(3 * g.gdnQkvDim() * 2); + t.sc = try back.Scratch.init(t); + var total: usize = 0; + for (t.owned.items) |b| total += b.length(); + std.log.info("slide: the Metal trainer owns {d:.2} GiB beside its runner", .{@as(f64, @floatFromInt(total)) / (1 << 30)}); + return t; + } + + pub fn deinit(t: *Trainer) void { + t.drain(); + if (t.runner_ready) t.runner.deinit(); + for (t.owned.items) |buffer| { + if (t.follow) |f| f.leave(f.ctx, buffer); + buffer.deinit(); + } + t.owned.deinit(t.gpa); + t.gpa.free(t.w); + t.gpa.free(t.tape); + if (t.k_ready) t.k.deinit(); + t.m.learn_reserved = t.reserved; + t.gpa.destroy(t); + } + pub fn drain(t: *Trainer) void { + // Each forward/backward submission below waits before returning, including every error path. + std.debug.assert(t.m.learning == null); + } + pub fn alloc(t: *Trainer, size: usize) !to.Ref { + try t.owned.ensureUnusedCapacity(t.gpa, 1); + const buffer = try t.m.device.buffer(@max(16, size), mtl.ResourceOptions.shared | mtl.ResourceOptions.untracked); + @memset(buffer.contents()[0..buffer.length()], 0); + t.owned.appendAssumeCapacity(buffer); + if (t.follow) |f| f.join(f.ctx, buffer); + return .{ .buffer = buffer }; + } + pub fn bytes(t: *Trainer, data: []const u8) !to.Ref { + const ref = try t.alloc(data.len); + @memcpy(ref.buffer.contents()[0..data.len], data); + return ref; + } + pub fn vec(t: *const Trainer, s: usize, i: usize, l: usize) usize { + return ((s * 3 + i) * t.g.layers + l) * t.g.hidden; + } + pub fn pushAt(t: *const Trainer, s: usize, i: usize, l: usize) []const f32 { + return slice(f32, to.plus(t.push, t.vec(s, i, l) * 4), t.g.hidden); + } + pub fn deltaAt(t: *const Trainer, s: usize, i: usize, l: usize) []f32 { + return slice(f32, to.plus(t.delta, t.vec(s, i, l) * 4), t.g.hidden); + } + pub fn normed(t: *const Trainer, l: usize, row: usize) []const u16 { + return slice(u16, to.plus(t.tape[l].y, row * t.g.hidden * 2), t.g.hidden); + } + pub fn readScale(t: *const Trainer, l: usize, out: []f32) !void { + if (out.len != t.g.hidden) return error.BadScale; + for (out, t.m.weights.layers[l].post_norm.host(u16)) |*v, b| v.* = @bitCast(@as(u32, b) << 16); + } + pub fn residual(t: *Trainer, l: usize, row: usize) []const u16 { + return more.residual(t, l, row); + } + pub fn packs(_: *const Trainer) bool { + return true; + } + pub fn prefixSlots(_: *Trainer, n: usize) !void { + if (n != 0) return error.TooManyPrefixes; + } + pub fn greedy(t: *Trainer, seqs: []const Seq, same: []bool) !void { + return more.greedy(t, seqs, same); + } + pub fn tapRows(t: *Trainer, ids: []const u32, context: usize, rows: []const u32, layers: []const usize, out: []u16) !void { + return more.tapRows(t, ids, context, rows, layers, out); + } + pub fn step(t: *Trainer, ids: []const u32, start: usize, mode: Mode, turn: living.lesson_route.Turn) !Result { + var out: [1]Result = undefined; + try t.pass(&.{.{ .ids = ids, .start = start, .decide = turn.decide, .nudge = t.nudge }}, mode, turn, &out); + return out[0]; + } + + pub fn pass(t: *Trainer, seqs: []const Seq, mode: Mode, _: living.lesson_route.Turn, out: []Result) !void { + const pool = mtl.objc.Pool.push(); + defer pool.pop(); + const began = submit.now(t.io); + t.runner.learning_stats = .{}; + var forward_seconds: f64 = 0; + var back_encode: f64 = 0; + var back_wait: f64 = 0; + var back_gpu: f64 = 0; + var affine_work: to.Work = .{}; + if (seqs.len == 0 or seqs.len > max_seqs or out.len < seqs.len) return error.BadPass; + switch (mode) { + .keys, .loss, .target => {}, + .prime => { + for (out[0..seqs.len]) |*r| r.* = .{ .loss = 0, .recalled = false }; + return; + }, + else => return error.RoutedUnsupported, + } + var rows: usize = 0; + var checkpoints: usize = 0; + var low = t.g.layers; + for (seqs, 0..) |sq, si| { + if (sq.ids.len < 2 or sq.start < 1 or sq.start >= sq.ids.len or sq.ids.len - 1 > max_rows) return error.BadExample; + if (sq.skip != 0 or !std.math.isFinite(sq.scale)) return error.BadPrefix; + const n = sq.ids.len - 1; + t.spans[si] = .{ .at = rows, .rows = n }; + t.cp_first[si] = checkpoints; + checkpoints += (n + 3) / 4; + rows += n; + for (sq.nudge.layers, sq.nudge.rows) |mask, row| { + if (mask == 0) continue; + if (row >= n or (t.g.layers < 64 and mask >> @intCast(t.g.layers) != 0)) return error.BadNudge; + if (mode == .target) low = @min(low, @ctz(mask)); + } + } + if (rows > t.pack) return error.PassTooLong; + if (low < keepLow(t.g.layers)) return error.NudgeBelowKept; + t.low = if (mode == .target and low == t.g.layers) keepLow(t.g.layers) else low; + t.mode = mode; + t.nseq = seqs.len; + t.rows = rows; + @memcpy(t.seqs[0..seqs.len], seqs); + t.count = .{ .passes = t.count.passes + 1, .rows = t.count.rows + rows }; + @memset(slice(u32, t.targets, rows), 0); + @memset(slice(f32, t.weights, rows), 0); + _ = mode_api.answers(seqs, t.spans[0..seqs.len], t.answers[0..seqs.len]); + for (seqs, t.answers[0..seqs.len], 0..) |sq, a, si| { + for (0..a.rows) |row| { + slice(u32, t.targets, rows)[a.first + row] = sq.ids[sq.start + row]; + slice(f32, t.weights, rows)[a.first + row] = 1 / @as(f32, @floatFromInt(a.rows)); + } + try t.runner.reset(@intCast(si)); + } + const previous = t.m.kernels.prompt; + t.m.kernels.prompt = false; + defer t.m.kernels.prompt = previous; + std.debug.assert(t.m.learning == null); + t.m.learning = .{ .ctx = t, .save = capture.save, .add = add }; + defer t.m.learning = null; + const forward_start = submit.now(t.io); + for (seqs, t.spans[0..seqs.len], 0..) |sq, sp, si| for (0..sp.rows) |row| { + t.hook_at = sp.at + row; + t.local_row = row; + t.slot = @intCast(si); + try t.forwardRow(&t.runner, @intCast(si), row, sq.ids[row..][0..1], schedule.head(mode, row, sq.start)); + }; + forward_seconds = submit.now(t.io) - forward_start; + // Remove the hook before backward and before any caller can observe completion. + t.m.learning = null; + if (mode != .keys) { + const back_start = submit.now(t.io); + const cb = t.m.queue.commandBuffer(); + const encoder = cb.compute(.serial); + var ended = false; + defer if (!ended) encoder.end(); + const o = to.Ops{ .kernels = &t.k, .e = encoder, .work = if (t.io != null) &affine_work else null }; + try schedule.loss(t, o); + if (mode == .target and low < t.g.layers) try back.run(t, o); + encoder.end(); + ended = true; + back_encode = submit.now(t.io) - back_start; + const wait_start = submit.now(t.io); + cb.commit(); + cb.wait(); + back_wait = submit.now(t.io) - wait_start; + back_gpu = if (t.io != null) cb.gpuSeconds() else 0; + if (@import("decode_round.zig").gpuFailed(cb, "learning backward")) return error.LearningGpuFailure; + } + if (t.io != null) { + const f = t.runner.learning_stats; + var answer_rows: usize = 0; + for (t.answers[0..seqs.len]) |a| answer_rows += a.rows; + std.log.info("slide qwen27: pass {d} {t}, {d} sequences, {d} rows, {d} answer rows: wall {d:.3} s; forward {d:.3} s (plan/upload {d:.3}, encode {d:.3}, commit/wait {d:.3}, GPU {d:.3}); backward/loss encode {d:.3}, commit/wait {d:.3}, GPU {d:.3}; row buffers/waits {d}/{d}, resets {d}, tail {d}; affine decodes {d}, FMAs {d}", .{ t.count.passes, mode, seqs.len, rows, answer_rows, submit.now(t.io) - began, forward_seconds, @max(0, forward_seconds - f.encode - f.wait), f.encode, f.wait, f.gpu, back_encode, back_wait, back_gpu, f.buffers, f.waits, seqs.len, @intFromBool(mode != .keys), affine_work.decodes, affine_work.fmas }); + } + for (out[0..seqs.len], t.answers[0..seqs.len]) |*r, a| { + r.* = .{ .loss = 0, .recalled = mode != .keys }; + if (mode != .keys) for (slice([2]f32, to.plus(t.stats, a.first * 8), a.rows)) |stat| { + if (!std.math.isFinite(stat[0]) or !std.math.isFinite(stat[1])) return error.NonFiniteLearningLoss; + r.loss += stat[0] / @as(f32, @floatFromInt(a.rows)); + r.recalled = r.recalled and stat[1] > 0.5; + }; + } + } + pub fn forwardRow(t: *Trainer, runner: *Runner, slot: u32, at: usize, ids: []const u32, logits: bool) !void { + if (ids.len != 1) return error.BadLearningRows; + var row: Row = .{}; + var round = try row.view(t.gpa, ids[0], slot, @intCast(at), runner.capacity, @intCast(t.g.conv_kernel), runner.slots, @intCast(t.g.vocab)); + try runner.advance(&round, if (logits) .all else .none); + } +}; +pub fn slice(comptime T: type, ref: to.Ref, n: usize) []T { + return @as([*]T, @ptrCast(@alignCast(ref.buffer.contents() + ref.offset)))[0..n]; +} +fn add(ctx: *anyopaque, e: mtl.ComputeEncoder, l: usize, x: to.Ref, out: to.Ref, rows: u32) !void { + const t: *Trainer = @ptrCast(@alignCast(ctx)); + const o = to.Ops{ .kernels = &t.k, .e = e }; + if (rows != 1) return error.BadLearningRows; + const sq = t.seqs[t.slot]; + if (t.m.pockets) |p| if (p.layers[l]) |pk| if (pk.used > 0) { + const pipeline = t.k.pipelines.get("tf_q27_pocket_scaled").?; + e.setPipeline(pipeline); + e.setBuffer(x.buffer, x.offset, 0); + e.setBuffer(pk.weights, 0, 1); + e.setBuffer(out.buffer, out.offset, 2); + e.setValue(@Vector(4, u32){ @intCast(t.g.hidden), @intCast(pk.used), @intCast(pk.cap), t.from[l] }, 3); + e.setValue(sq.scale, 4); + e.dispatchGroups(.{ .width = 1 }, .{ .width = 256 }); + e.barrier(); + }; + for (sq.nudge.layers, sq.nudge.rows, 0..) |mask, row, i| { + if (mask >> @intCast(l) & 1 != 0 and t.local_row == row) try o.nudge(out, to.plus(t.delta, t.vec(t.slot, i, l) * 4), t.g.hidden); + } +} diff --git a/zig/src/families/qwen27/train_admission.zig b/zig/src/families/qwen27/train_admission.zig new file mode 100644 index 00000000000..3b7001772bd --- /dev/null +++ b/zig/src/families/qwen27/train_admission.zig @@ -0,0 +1,7 @@ +//! Native server learning admits the dense 27B; the synthetic trainer fixture remains a separate entry point. +const Config = @import("config.zig").Config; +pub fn supported(c: Config) bool { + if (c.hidden != 5120 or c.intermediate != 17408 or c.layers != 64 or c.vocab != 248320 or c.heads != 24 or c.kv_heads != 4 or c.head_dim != 256 or c.k_heads != 16 or c.v_heads != 48 or c.dk != 128 or c.dv != 128 or c.conv_kernel != 4 or c.rope_dims != 64 or c.eps != 1e-6 or c.rope_theta != 10000000 or c.ranks != 1) return false; + for (c.kinds[0..c.layers], 0..) |kind, l| if (kind != (if (l % 4 == 3) @import("config.zig").Kind.attention else .linear)) return false; + return true; +} diff --git a/zig/src/families/qwen27/train_back.zig b/zig/src/families/qwen27/train_back.zig new file mode 100644 index 00000000000..48daf43982b --- /dev/null +++ b/zig/src/families/qwen27/train_back.zig @@ -0,0 +1,157 @@ +//! Loss input gradients through the native dense MLP, GDN and attention; BF16 nodes use straight-through gradients. +const std = @import("std"); +const mtl = @import("metal"); +const to = @import("train_ops.zig"); +const Ref = to.Ref; +const plus = to.plus; +const wts = @import("gpu_weights.zig"); +const train = @import("train.zig"); + +pub const Scratch = struct { + mlp: Ref, + gu: Ref, + mix: Ref, + dp: Ref, + dact: Ref, + gy: Ref, + work: Ref, + dqparts: Ref, + dkparts: Ref, + dg: Ref, + db: Ref, + dout: Ref, + dpq: Ref, + dpk: Ref, + dv: Ref, + dq: Ref, + dk: Ref, + probability: Ref, + dscores: Ref, + + pub fn init(t: anytype) !Scratch { + const g = t.g; + const R = train.pack_rows; + const M = train.max_rows; + const vi = g.gdnValueDim(); + const conv = g.gdnQkvDim(); + const qi = g.heads * g.head_dim; + const kv = g.kvDim(); + return .{ + .mlp = try t.alloc(R * g.intermediate * 4), + .gu = try t.alloc(R * 2 * g.intermediate * 4), + .mix = try t.alloc(R * @max(vi, qi) * 4), + .dp = try t.alloc(M * (conv + vi + 2 * g.v_heads) * 4), + .dact = try t.alloc(M * conv * 4), + .gy = try t.alloc(M * vi * 4), + .work = try t.alloc(g.v_heads * 4 * 4 * 32 * 128 * 4), + .dqparts = try t.alloc(M * g.v_heads * 4 * 128 * 4), + .dkparts = try t.alloc(M * g.v_heads * 4 * 128 * 4), + .dg = try t.alloc(M * g.v_heads * 4 * 4), + .db = try t.alloc(M * g.v_heads * 4 * 4), + .dout = try t.alloc(M * qi * 4), + .dpq = try t.alloc(M * 2 * qi * 4), + .dpk = try t.alloc(M * kv * 4), + .dv = try t.alloc(M * kv * 4), + .dq = try t.alloc(M * qi * 4), + .dk = try t.alloc(M * kv * 4), + .probability = try t.alloc(g.heads * M * M * 4), + .dscores = try t.alloc(g.heads * M * M * 4), + }; + } +}; + +pub fn run(t: *train.Trainer, o: to.Ops) !void { + const g = t.g; + const R = t.rows; + const D = g.hidden; + try @import("train_schedule.zig").headBack(t, o); + try o.zero(t.grad, R * D); + try o.rmsBack(t.final_h, wts.ref(t.m.weights.norm), t.dy, t.grad, R, D, g.eps); + var l = g.layers; + while (l > t.low) { + l -= 1; + for (t.seqs[0..t.nseq], t.spans[0..t.nseq], 0..) |sq, sp, si| { + for (sq.nudge.layers, sq.nudge.rows, 0..) |mask, row, i| { + if (mask >> @intCast(l) & 1 == 0) continue; + try o.copy(plus(t.grad, sp.row(row) * D * 4), plus(t.push, t.vec(si, i, l) * 4), D * 4); + } + } + if (l == t.low) return; + const kp = t.tape[l]; + const w = t.w[l]; + const layer = t.m.weights.layers[l]; + try o.q4Back(t.grad, w.mlp.down, t.sc.mlp, R, false); + try o.swigluBack(kp.gu, t.sc.mlp, t.sc.gu, R, g.intermediate); + try o.q4Back(t.sc.gu, w.mlp.gu, t.dy, R, false); + if (t.pocket_back) if (t.m.pockets) |p| if (p.layers[l]) |pk| if (pk.used > 0) { + for (t.spans[0..t.nseq], t.seqs[0..t.nseq]) |sp, sq| { + try o.go("tf_learn_pocket_back", &.{ plus(kp.y, sp.at * D * 2), .{ .buffer = pk.weights }, plus(t.grad, sp.at * D * 4), plus(t.dy, sp.at * D * 4) }, to.Shape{ + .u = .{ t.from[l], @intCast(D), @intCast(pk.used), @intCast(pk.cap) }, + .f = .{ sq.scale, 0, 0, 0 }, + }, .{ .width = sp.rows }, 256); + } + }; + try o.rmsBack(kp.h_mid, wts.ref(layer.post_norm), t.dy, t.grad, R, D, g.eps); + if (w.gdn) |gl| { + try o.q4Back(t.grad, gl.out, t.sc.mix, R, false); + for (t.spans[0..t.nseq], 0..) |sp, si| try gdn(t, o, l, si, sp); + } else { + try o.q4Back(t.grad, w.attn.?.out, t.sc.mix, R, false); + for (t.spans[0..t.nseq]) |sp| try attention(t, o, l, sp); + } + try o.rmsBack(kp.h_in, wts.ref(layer.norm), t.dy, t.grad, R, D, g.eps); + } +} + +fn gdn(t: *train.Trainer, o: to.Ops, l: usize, si: usize, sp: train.Span) !void { + const g = t.g; + const w = t.w[l].gdn.?; + const k = t.tape[l]; + const s = t.sc; + const vi = g.gdnValueDim(); + const conv = g.gdnQkvDim(); + const ki = g.k_heads * 128; + const proj = conv + vi + 2 * g.v_heads; + const rows = sp.rows; + const shape: to.GdnShape = .{ .rows = @intCast(rows), .nk = @intCast(g.k_heads), .nv = @intCast(g.v_heads), .conv = @intCast(conv), .proj = @intCast(proj) }; + const p = plus(k.proj, sp.at * proj * 2); + const act = plus(k.act, sp.at * conv * 2); + const q = plus(k.q, sp.at * ki * 4); + const key = plus(k.k, sp.at * ki * 4); + const decay = plus(k.decay, sp.at * g.v_heads * 4); + const beta = plus(k.beta, sp.at * g.v_heads * 4); + try o.zero(s.dp, rows * proj); + try o.go("tf_learn_gdn_act", &.{ p, w.conv, act }, to.Shape{ .u = .{ @intCast(rows), @intCast(2 * ki), @intCast(proj), @intCast(conv) } }, .{ .width = (2 * ki + 255) / 256, .height = rows }, 256); + try o.go("tf_gdn_norm_back", &.{ plus(k.recur, sp.at * vi * 2), p, w.norm, plus(s.mix, sp.at * vi * 4), s.gy, s.dp }, extern struct { s: to.GdnShape, eps: f32 }{ .s = shape, .eps = g.eps }, .{ .width = rows, .height = g.v_heads }, 128); + const checkpoints = plus(k.checkpoints, t.cp_first[si] * g.v_heads * 128 * 128 * 4); + try o.go("tf_gdn_scan_back", &.{ act, q, key, decay, beta, checkpoints, s.gy, s.work, s.dqparts, s.dkparts, s.dact, s.dg, s.db }, extern struct { s: to.GdnShape, from: i32 }{ .s = shape, .from = 0 }, .{ .width = g.v_heads * 4 }, 256); + try o.go("tf_gdn_qk_back", &.{ act, s.dqparts, s.dkparts, s.dact }, shape, .{ .width = rows, .height = g.k_heads }, 128); + try o.go("tf_gdn_gates_back", &.{ p, w.a_log, w.dt, decay, s.dg, s.db, s.dp }, shape, .{ .width = rows }, 256); + // Fresh sequences have no incoming conv history; the zero slab is deliberately valid device storage. + try o.go("tf_gdn_conv_back", &.{ p, t.zero_history, w.conv, s.dact, s.dp }, shape, .{ .width = (conv + 255) / 256, .height = rows }, 256); + try o.q4Back(s.dp, w.input, plus(t.dy, sp.at * g.hidden * 4), rows, false); +} + +fn attention(t: *train.Trainer, o: to.Ops, l: usize, sp: train.Span) !void { + const g = t.g; + const w = t.w[l].attn.?; + const k = t.tape[l]; + const s = t.sc; + const rows = sp.rows; + const qi = g.heads * g.head_dim; + const kv = g.kvDim(); + const pq = plus(k.pq, sp.at * 2 * qi * 2); + const pk = plus(k.pk, sp.at * kv * 2); + const qkv = plus(k.qkv, sp.at * (qi + 2 * kv) * 2); + try o.go("tf_attn_gate_back", &.{ plus(s.mix, sp.at * qi * 4), plus(k.gated, sp.at * qi * 2), pq, s.dout, s.dpq }, extern struct { heads: i32, dim: i32 }{ .heads = @intCast(g.heads), .dim = @intCast(g.head_dim) }, .{ .width = (qi + 255) / 256, .height = rows }, 256); + const heads: to.Heads = .{ .rows = @intCast(rows), .heads = @intCast(g.heads), .kv_heads = @intCast(g.kv_heads), .dim = @intCast(g.head_dim), .qkv = @intCast(qi + 2 * kv), .scale = 1 / @sqrt(@as(f32, @floatFromInt(g.head_dim))) }; + try o.go("tf_attn_q", &.{ qkv, s.dout, s.probability, s.dscores, s.dq, t.zero_history, t.zero_history }, heads, .{ .width = g.heads, .height = rows }, 256); + try o.linear("tf_learn_attn_kv_back", &.{ qkv, s.dout, s.probability, s.dscores, s.dk, s.dv }, .{ .u = .{ @intCast(rows), @intCast(g.heads), @intCast(g.kv_heads), @intCast(g.head_dim) }, .f = .{ heads.scale, 0, 0, 0 } }, rows * kv); + try o.linear("tf_learn_attn_gate_grad", &.{ plus(s.mix, sp.at * qi * 4), pq, qkv, s.probability, s.dpq }, .{ .u = .{ @intCast(rows), @intCast(g.heads), @intCast(g.kv_heads), @intCast(g.head_dim) } }, rows * qi); + const Params = extern struct { pos0: i32 = 0, heads: i32, kv_heads: i32, dim: i32, half: i32, eps: f32 }; + try o.go("tf_attn_prep_back", &.{ pq, pk, w.qs, w.ks, w.inv, s.dq, s.dk, s.dpq, s.dpk }, Params{ .heads = @intCast(g.heads), .kv_heads = @intCast(g.kv_heads), .dim = @intCast(g.head_dim), .half = @intCast(g.rope_dims / 2), .eps = g.eps }, .{ .width = g.heads + g.kv_heads, .height = rows }, g.head_dim); + const dest = plus(t.dy, sp.at * g.hidden * 4); + try o.q4Back(s.dpq, w.q, dest, rows, false); + try o.q4Back(s.dpk, w.k, dest, rows, true); + try o.q4Back(s.dv, w.v, dest, rows, true); +} diff --git a/zig/src/families/qwen27/train_epoch.zig b/zig/src/families/qwen27/train_epoch.zig new file mode 100644 index 00000000000..19c0f52dbae --- /dev/null +++ b/zig/src/families/qwen27/train_epoch.zig @@ -0,0 +1,13 @@ +//! The native routes around the prompt store belong to the same learned-weight epoch. +pub fn changed(back: anytype) void { + back.standing.deinit(back.gpa); + back.dropTree(); + back.dropRound(); +} + +/// Cache.clear stops and detaches borrowed disk rows; the server still owns and closes them exactly once. +pub fn takeDisk(host: anytype) @TypeOf(host.disk_rows) { + const rows = host.disk_rows; + host.disk_rows = null; + return rows; +} diff --git a/zig/src/families/qwen27/train_hooks.zig b/zig/src/families/qwen27/train_hooks.zig new file mode 100644 index 00000000000..ba680df9752 --- /dev/null +++ b/zig/src/families/qwen27/train_hooks.zig @@ -0,0 +1,14 @@ +//! Optional captures and additions in the serving forward; an ordinary model has no learning hooks. +const mtl = @import("metal"); +const Ref = @import("projection.zig").Ref; + +pub const Point = enum { input, gdn, gdn_state, attention, prepared_attention, gated, post, mlp, final, logits }; +pub const Hooks = struct { + ctx: *anyopaque, + save: *const fn (*anyopaque, mtl.ComputeEncoder, Point, usize, []const Ref, u32) anyerror!void, + add: *const fn (*anyopaque, mtl.ComputeEncoder, usize, Ref, Ref, u32) anyerror!void, + + pub fn capture(h: Hooks, e: mtl.ComputeEncoder, point: Point, layer: usize, refs: []const Ref, rows: u32) !void { + try h.save(h.ctx, e, point, layer, refs, rows); + } +}; diff --git a/zig/src/families/qwen27/train_host.zig b/zig/src/families/qwen27/train_host.zig new file mode 100644 index 00000000000..4038b0f8acb --- /dev/null +++ b/zig/src/families/qwen27/train_host.zig @@ -0,0 +1,225 @@ +//! Host-only learner ABI, reservation and native cache-epoch regressions. +const std = @import("std"); +const to = @import("train_ops.zig"); +const config = @import("config.zig"); + +test "qwen27 learning: Metal argument layouts match the generated wrappers" { + try std.testing.expectEqual(@as(usize, 32), @sizeOf(to.Shape)); + try std.testing.expectEqual(@as(usize, 16), @offsetOf(to.Shape, "f")); + try std.testing.expectEqual(@as(usize, 20), @sizeOf(to.GdnShape)); + try std.testing.expectEqual(@as(usize, 28), @sizeOf(to.Heads)); + try std.testing.expectEqual(@as(usize, 20), @offsetOf(to.Heads, "scale")); +} + +test "qwen27 learning: the reserve covers both native frame widths and every GDN checkpoint" { + var c: config.Config = .{ .hidden = 5120, .intermediate = 17408, .layers = 64, .vocab = 248320, .heads = 24, .kv_heads = 4, .head_dim = 256, .k_heads = 16, .v_heads = 48, .dk = 128, .dv = 128, .conv_kernel = 4, .eps = 1e-6, .rope_dims = 64, .rope_theta = 10000000 }; + for (0..64) |l| c.kinds[l] = if (l % 4 == 3) .attention else .linear; + const small = try @import("train_memory.zig").bytes(c, 128, true); + const wide = try @import("train_memory.zig").bytes(c, 2048, true); + try std.testing.expect(wide > small); + const checkpoints = (1024 / 4 + 8) * c.v_heads * c.dv * c.dk * 4; + try std.testing.expect(small > checkpoints * 39); + try std.testing.expect(wide < 128 << 30); +} + +test "qwen27 learning: moving weights invalidates standing, rewind metadata, draft trees and the pending round" { + const Fake = struct { + gpa: std.mem.Allocator, + standing: struct { + tokens: usize = 17, + rewind_at: u32 = 11, + pub fn deinit(s: *@This(), _: std.mem.Allocator) void { + s.* = .{ .tokens = 0, .rewind_at = 0 }; + } + } = .{}, + trees: usize = 3, + round: bool = true, + pub fn dropTree(f: *@This()) void { + f.trees = 0; + } + pub fn dropRound(f: *@This()) void { + f.round = false; + } + }; + var fake: Fake = .{ .gpa = std.testing.allocator }; + @import("train_epoch.zig").changed(&fake); + try std.testing.expectEqual(@as(usize, 0), fake.standing.tokens); + try std.testing.expectEqual(@as(u32, 0), fake.standing.rewind_at); + try std.testing.expectEqual(@as(usize, 0), fake.trees); + try std.testing.expect(!fake.round); +} + +test "qwen27 learning: detached disk rows retain their server owner until close" { + const Row = struct { stopped: bool = false }; + const Store = struct { + disk: ?*Row, + pub fn clear(s: *@This()) void { + if (s.disk) |r| r.stopped = true; + s.disk = null; + } + }; + var rows: Row = .{}; + var host: struct { disk_rows: ?*Row } = .{ .disk_rows = &rows }; + var store: Store = .{ .disk = &rows }; + store.clear(); + try std.testing.expect(rows.stopped and store.disk == null); + const owned = @import("train_epoch.zig").takeDisk(&host); + try std.testing.expect(owned.? == &rows); + try std.testing.expect(@import("train_epoch.zig").takeDisk(&host) == null); +} + +const schedule = @import("train_schedule.zig"); +const mode_api = @import("living").train_mode; + +test "qwen27 learning: only answer rows run the vocabulary forward and backward" { + const fake = struct { + g: struct { hidden: usize = 64, vocab: usize = 248320 } = .{}, + rows: usize = 12, + answers: [2]mode_api.Answer = .{ .{ .first = 3, .at = 0, .rows = 2 }, .{ .first = 10, .at = 2, .rows = 2 } }, + nseq: usize = 2, + dlogits: to.Ref = .{ .buffer = undefined, .offset = 0 }, + head: to.Q4 = undefined, + dy: to.Ref = .{ .buffer = undefined, .offset = 0 }, + }{}; + const Ops = struct { + rows: *usize, + zeros: *usize, + pub fn q4Back(o: @This(), _: to.Ref, _: to.Q4, _: to.Ref, rows: usize, add: bool) !void { + try std.testing.expect(!add); + o.rows.* += rows; + } + pub fn zero(o: @This(), _: to.Ref, count: usize) !void { + o.zeros.* += count; + } + }; + var rows: usize = 0; + var zeros: usize = 0; + try schedule.headBack(&fake, Ops{ .rows = &rows, .zeros = &zeros }); + try std.testing.expectEqual(@as(usize, 4), rows); + try std.testing.expectEqual(@as(usize, 12 * 64), zeros); + try std.testing.expect(!schedule.head(.target, 0, 4)); + try std.testing.expect(!schedule.head(.loss, 2, 4)); + try std.testing.expect(schedule.head(.target, 3, 4)); + try std.testing.expect(!schedule.head(.keys, 3, 4)); +} + +test "qwen27 learning: one submission per native learner row preserves the serving interval" { + try std.testing.expectEqual(@as(usize, 0), schedule.commitEvery(true)); + try std.testing.expectEqual(@as(usize, 4), schedule.commitEvery(false)); +} + +test "qwen27 learning: four independent gradient rows share one affine weight walk" { + try std.testing.expectEqual(@as(usize, 2 * 64), schedule.q4Threads(7, 64)); + try std.testing.expectEqual(@as(usize, 64), schedule.q4Threads(1, 64)); + try std.testing.expectEqual(@as(usize, 0), schedule.q4Threads(0, 64)); +} + +const submit = @import("train_submit.zig"); +test "qwen27 learning: a native row commits and waits once without a device allocation" { + const Fake = struct { + buffers: usize = 0, + encoders: usize = 0, + ended: usize = 0, + commits: usize = 0, + waits: usize = 0, + layers: usize = 0, + encode_fail: bool = false, + gpu_fail: bool = false, + const Encoder = struct { + fake: *ThisFake, + pub fn end(e: @This()) void { + e.fake.ended += 1; + } + }; + const ThisFake = @This(); + pub fn commandBuffer(f: *@This()) *@This() { + f.buffers += 1; + return f; + } + pub fn compute(f: *@This(), _: enum { concurrent }) Encoder { + f.encoders += 1; + return .{ .fake = f }; + } + pub fn commit(f: *@This()) void { + f.commits += 1; + } + pub fn wait(f: *@This()) void { + f.waits += 1; + } + pub fn failure(f: *@This()) ?[]const u8 { + return if (f.gpu_fail) "injected" else null; + } + pub fn gpuSeconds(_: *@This()) f64 { + return 0.25; + } + pub fn encode(f: *@This(), _: Encoder) !void { + for (0..64) |_| f.layers += 1; + if (f.encode_fail) return error.InjectedEncode; + } + }; + var f: Fake = .{}; + var stats: submit.Stats = .{}; + try std.testing.expectEqual(@as(f64, 0.25), try submit.run(&f, &f, &stats, null)); + try std.testing.expectEqual(@as(usize, 64), f.layers); + try std.testing.expectEqual(@as(usize, 1), f.buffers); + try std.testing.expectEqual(@as(usize, 1), f.ended); + try std.testing.expectEqual(@as(usize, 1), f.commits); + try std.testing.expectEqual(@as(usize, 1), f.waits); + try std.testing.expectEqual(@as(usize, 1), stats.buffers); + try std.testing.expectEqual(@as(usize, 1), stats.waits); + f = .{ .encode_fail = true }; + try std.testing.expectError(error.InjectedEncode, submit.run(&f, &f, &stats, null)); + try std.testing.expectEqual(@as(usize, 1), f.ended); + try std.testing.expectEqual(@as(usize, 0), f.commits); + try std.testing.expectEqual(@as(usize, 0), f.waits); + f = .{ .gpu_fail = true }; + try std.testing.expectError(error.LearningGpuFailure, submit.run(&f, &f, &stats, null)); + try std.testing.expectEqual(@as(usize, 1), f.ended); + try std.testing.expectEqual(@as(usize, 1), f.commits); + try std.testing.expectEqual(@as(usize, 1), f.waits); +} + +test "qwen27 learning: row metadata is identical without the nine Round allocations" { + const Round = @import("round_plan.zig").Round; + const Row = @import("train_row.zig").Row; + for ([_]u32{ 0, 1, 127, 511 }) |at| for ([_]u32{ 0, 7 }) |slot| { + var old = try Round.init(std.testing.allocator, &.{.{ .slot = slot, .start = at, .capacity = 513, .ids = &.{17} }}, 4, 8, 32); + defer old.deinit(); + var row: Row = .{}; + const view = try row.view(std.testing.failing_allocator, 17, slot, at, 513, 4, 8, 32); + try std.testing.expectEqualSlices(u32, old.ids, view.ids); + try std.testing.expectEqualSlices(i32, old.feed_positions, view.feed_positions); + try std.testing.expectEqualSlices(u64, old.draw_positions, view.draw_positions); + try std.testing.expectEqualSlices(u32, old.slots, view.slots); + try std.testing.expectEqualSlices(u32, old.firsts, view.firsts); + try std.testing.expectEqual(old.windows[0].start, view.windows[0].start); + try std.testing.expectEqual(old.windows[0].taps, view.windows[0].taps); + try std.testing.expectEqualSlices(i32, old.windows[0].parents, view.windows[0].parents); + try std.testing.expectEqualSlices(u32, old.windows[0].depths, view.windows[0].depths); + try std.testing.expectEqualSlices(u32, old.windows[0].conv, view.windows[0].conv); + }; + try std.testing.expectError(error.OutOfMemory, Round.init(std.testing.failing_allocator, &.{.{ .slot = 0, .start = 0, .capacity = 513, .ids = &.{17} }}, 4, 8, 32)); + var row: Row = .{}; + try std.testing.expectError(error.BadRoundPlan, row.view(std.testing.failing_allocator, 1, 8, 0, 513, 4, 8, 32)); + try std.testing.expectError(error.BadRoundPlan, row.view(std.testing.failing_allocator, 1, 0, 513, 513, 4, 8, 32)); + try std.testing.expectError(error.BadTokenId, row.view(std.testing.failing_allocator, 32, 0, 0, 513, 4, 8, 32)); +} + +test { + _ = @import("train_scalars.zig"); +} + +test "qwen27 learning: server admission keeps the 9B and pair shapes out of the unqualified learner" { + var c: config.Config = .{ .hidden = 5120, .intermediate = 17408, .layers = 64, .vocab = 248320, .heads = 24, .kv_heads = 4, .head_dim = 256, .k_heads = 16, .v_heads = 48, .dk = 128, .dv = 128, .conv_kernel = 4, .eps = 1e-6, .rope_dims = 64, .rope_theta = 10000000 }; + for (0..c.layers) |l| c.kinds[l] = if (l % 4 == 3) .attention else .linear; + const admits = @import("train_admission.zig").supported; + try std.testing.expect(admits(c)); + c.hidden = 4096; + try std.testing.expect(!admits(c)); + c.hidden = 5120; + c.ranks = 2; + try std.testing.expect(!admits(c)); + c.ranks = 1; + c.kinds[3] = .linear; + try std.testing.expect(!admits(c)); +} diff --git a/zig/src/families/qwen27/train_load.zig b/zig/src/families/qwen27/train_load.zig new file mode 100644 index 00000000000..82415f9b491 --- /dev/null +++ b/zig/src/families/qwen27/train_load.zig @@ -0,0 +1,139 @@ +//! Original affine4 words for the Metal input-gradient products; no serving pack or weight is changed. +const std = @import("std"); +const core = @import("core"); +const wts = @import("gpu_weights.zig"); +const to = @import("train_ops.zig"); +const keepLow = @import("train.zig").keepLow; +pub const Mlp = struct { gu: to.Q4 = undefined, down: to.Q4 = undefined }; +pub const Gdn = struct { input: to.Q4, out: to.Q4, conv: to.Ref, a_log: to.Ref, dt: to.Ref, norm: to.Ref }; +pub const Attn = struct { q: to.Q4, k: to.Q4, v: to.Q4, out: to.Q4, qs: to.Ref, ks: to.Ref, inv: to.Ref }; +pub const Layer = struct { mlp: Mlp = .{}, gdn: ?Gdn = null, attn: ?Attn = null }; +const Reader = struct { + t: *@import("train.zig").Trainer, + prefix: []const u8, + ck: *core.Checkpoint, + + fn get(r: Reader, buf: *[3][]const u8, name: []const u8) ![3]core.safetensors.Tensor { + var nb: [192]u8 = undefined; + var out: [3]core.safetensors.Tensor = undefined; + for ([_][]const u8{ "weight", "scales", "biases" }, 0..) |s, i| { + out[i] = try r.ck.get(try std.fmt.bufPrint(&nb, "{s}{s}.{s}", .{ r.prefix, name, s })); + buf[i] = out[i].bytes; + } + return out; + } + + /// rows [0, n) and columns [0, k) of `name` (stored [n_all, k_all]) as one Q4 on the device. + fn q4(r: Reader, name: []const u8, n: usize, k: usize) !to.Q4 { + var raw: [3][]const u8 = undefined; + const ts = try r.get(&raw, name); + const k_all = ts[1].dim(1) * 64; + if (ts[0].dim(0) < n or k_all < k or ts[0].dim(1) * 8 != k_all or + !ts[0].is(.u32, &.{ ts[0].dim(0), k_all / 8 }) or !ts[1].is(.bf16, &.{ ts[0].dim(0), k_all / 64 }) or + !ts[2].is(.bf16, &.{ ts[0].dim(0), k_all / 64 })) return error.UnexpectedTensor; + const per = [3]usize{ 4 * k / 8, 2 * k / 64, 2 * k / 64 }; + const per_all = [3]usize{ 4 * k_all / 8, 2 * k_all / 64, 2 * k_all / 64 }; + var ptrs: [3]to.Ref = undefined; + for (0..3) |j| { + if (k == k_all) { + ptrs[j] = try r.t.bytes(raw[j][0 .. n * per[j]]); + continue; + } + const cut = try r.t.gpa.alloc(u8, n * per[j]); + defer r.t.gpa.free(cut); + for (0..n) |row| @memcpy(cut[row * per[j] ..][0..per[j]], raw[j][row * per_all[j] ..][0..per[j]]); + ptrs[j] = try r.t.bytes(cut); + } + return .{ .words = ptrs[0], .scales = ptrs[1], .biases = ptrs[2], .n = n, .k = k }; + } + + /// Several projections over the same inputs stacked by rows: [n0 + n1 + ..., k]. + fn stack(r: Reader, names: []const []const u8, ns: []const usize, k: usize) !to.Q4 { + var total: usize = 0; + for (ns) |n| total += n; + var parts: [3][]u8 = undefined; + const per = [3]usize{ 4 * k / 8, 2 * k / 64, 2 * k / 64 }; + var made: usize = 0; + defer for (parts[0..made]) |p| r.t.gpa.free(p); + for (&parts, per) |*p, b| { + p.* = try r.t.gpa.alloc(u8, total * b); + made += 1; + } + var at: usize = 0; + for (names, ns) |name, n| { + var raw: [3][]const u8 = undefined; + const ts = try r.get(&raw, name); + if (ts[0].dim(0) < n or ts[0].dim(1) * 8 != k) return error.UnexpectedTensor; + for (0..3) |j| @memcpy(parts[j][at * per[j] ..][0 .. n * per[j]], raw[j][0 .. n * per[j]]); + at += n; + } + return .{ .words = try r.t.bytes(parts[0]), .scales = try r.t.bytes(parts[1]), .biases = try r.t.bytes(parts[2]), .n = total, .k = k }; + } +}; + +pub fn weights(t: anytype, io: std.Io) !void { + const g = t.g; + var ck = try core.Checkpoint.openModel(t.gpa, io, t.dir); + defer ck.close(); + const prefix: []const u8 = if (ck.has("language_model.model.layers.0.mlp.gate_proj.weight")) "language_model." else ""; + const r: Reader = .{ .t = t, .ck = &ck, .prefix = prefix }; + var nb: [192]u8 = undefined; + var names: [4][192]u8 = undefined; + const inv_host = try t.gpa.alloc(f32, g.rope_dims / 2); + defer t.gpa.free(inv_host); + for (inv_host, 0..) |*v, i| v.* = @floatCast(std.math.pow(f64, g.rope_theta, -@as(f64, @floatFromInt(i)) / @as(f64, @floatFromInt(g.rope_dims / 2)))); + const inv = try t.bytes(std.mem.sliceAsBytes(inv_host)); + t.w = try t.gpa.alloc(Layer, g.layers); + @memset(t.w, .{}); + for (keepLow(g.layers)..g.layers) |l| { + const lw = &t.w[l]; + const I = g.intermediate; + lw.mlp = .{ + .gu = try r.stack(&.{ + try std.fmt.bufPrint(&names[0], "model.layers.{d}.mlp.gate_proj", .{l}), + try std.fmt.bufPrint(&names[1], "model.layers.{d}.mlp.up_proj", .{l}), + }, &.{ I, I }, g.hidden), + .down = try r.q4(try std.fmt.bufPrint(&nb, "model.layers.{d}.mlp.down_proj", .{l}), g.hidden, I), + }; + switch (t.m.weights.layers[l].mixer) { + .linear => |d| { + const modules = [_][]const u8{ + try std.fmt.bufPrint(&names[0], "model.layers.{d}.linear_attn.in_proj_qkv", .{l}), + try std.fmt.bufPrint(&names[1], "model.layers.{d}.linear_attn.in_proj_z", .{l}), + try std.fmt.bufPrint(&names[2], "model.layers.{d}.linear_attn.in_proj_b", .{l}), + try std.fmt.bufPrint(&names[3], "model.layers.{d}.linear_attn.in_proj_a", .{l}), + }; + lw.gdn = .{ + .input = try r.stack(&modules, &.{ g.gdnQkvDim(), g.gdnValueDim(), g.v_heads, g.v_heads }, g.hidden), + .out = try r.q4(try std.fmt.bufPrint(&nb, "model.layers.{d}.linear_attn.out_proj", .{l}), g.hidden, g.gdnValueDim()), + .conv = wts.ref(d.conv), + .norm = wts.ref(d.norm), + .a_log = try widen(t, d.a_log), + .dt = try widen(t, d.dt), + }; + }, + .attention => |a| { + lw.attn = .{ + .q = try r.q4(try std.fmt.bufPrint(&nb, "model.layers.{d}.self_attn.q_proj", .{l}), g.qDim(), g.hidden), + .k = try r.q4(try std.fmt.bufPrint(&nb, "model.layers.{d}.self_attn.k_proj", .{l}), g.kvDim(), g.hidden), + .v = try r.q4(try std.fmt.bufPrint(&nb, "model.layers.{d}.self_attn.v_proj", .{l}), g.kvDim(), g.hidden), + .out = try r.q4(try std.fmt.bufPrint(&nb, "model.layers.{d}.self_attn.o_proj", .{l}), g.hidden, g.heads * g.head_dim), + .qs = try widen(t, a.q_norm), + .ks = try widen(t, a.k_norm), + .inv = inv, + }; + }, + } + } + t.head = try r.q4("lm_head", g.vocab, g.hidden); +} +fn widen(t: anytype, tensor: wts.Tensor) !to.Ref { + const dtype: @import("train_scalars.zig").Kind = switch (tensor.dtype) { + .bf16 => .bf16, + .f32 => .f32, + else => return error.UnsupportedLearningScalar, + }; + const floats = try @import("train_scalars.zig").values(t.gpa, dtype, tensor.host(u8)); + defer t.gpa.free(floats); + return t.bytes(std.mem.sliceAsBytes(floats)); +} diff --git a/zig/src/families/qwen27/train_memory.zig b/zig/src/families/qwen27/train_memory.zig new file mode 100644 index 00000000000..da88eba2722 --- /dev/null +++ b/zig/src/families/qwen27/train_memory.zig @@ -0,0 +1,42 @@ +//! Conservative up-front reserve for the learner, leaving serving slots unable to spend its future allocations. +const std = @import("std"); +const Config = @import("config.zig").Config; +const memory = @import("prompt_memory.zig"); + +pub fn bytes(g: Config, frame: u32, tensor_units: bool) !u64 { + const R: u64 = 1024; + const M: u64 = 512; + const D: u64 = g.hidden; + const I: u64 = g.intermediate; + const vi: u64 = g.gdnValueDim(); + const conv: u64 = g.gdnQkvDim(); + const qi: u64 = g.heads * g.head_dim; + const kv: u64 = g.kvDim(); + const ki: u64 = g.k_heads * g.dk; + const proj = conv + vi + 2 * g.v_heads; + var n: u64 = R * g.layers * D * 2; // Every layer's pocket input. + n += R * D * 10 + R * g.vocab * 6 + 8 * 3 * g.layers * D * 8 + R * 16; + n += R * (3 * I + @max(vi, qi)) * 4; + n += M * (proj + conv + vi) * 4; + n += g.v_heads * 4 * 4 * 32 * 128 * 4; + n += M * g.v_heads * 4 * (128 * 2 + 2) * 4; + n += M * (qi * 4 + kv * 4) * 4 + 2 * g.heads * M * M * 4; + n += 3 * conv * 2 + q4(g.vocab, D); + for (g.layers / 5..g.layers) |l| { + n += R * (2 * D + 2 * I) * 2 + 2 * q4(I, D) + q4(D, I); + if (g.kind(l) == .linear) { + n += R * (proj * 2 + conv * 2 + 2 * ki * 4 + 2 * g.v_heads * 4 + vi * 2); + n += (R / 4 + 8) * g.v_heads * g.dv * g.dk * 4; + n += q4(proj, D) + q4(D, vi); + } else { + n += R * (2 * qi + 2 * kv + qi + 2 * kv + qi) * 2; + n += q4(2 * qi, D) + 2 * q4(kv, D) + q4(D, qi); + } + } + n += try memory.runnerBytes(g, M + 1, 8, frame, tensor_units, 0); + // Scalar copies, Metal pipeline state and allocator rounding stay inside this explicit spare. + return std.math.add(u64, n, 512 << 20); +} +fn q4(n: u64, k: u64) u64 { + return n * k / 2 + n * k / 16; +} diff --git a/zig/src/families/qwen27/train_more.zig b/zig/src/families/qwen27/train_more.zig new file mode 100644 index 00000000000..21ac050f010 --- /dev/null +++ b/zig/src/families/qwen27/train_more.zig @@ -0,0 +1,81 @@ +//! Greedy lesson checks and conversation keys use the serving runner with fresh native states. +const std = @import("std"); +const train = @import("train.zig"); +const Runner = @import("decode_round.zig").Runner; +const to = @import("train_ops.zig"); +const mtl = @import("metal"); + +pub fn residual(t: *train.Trainer, l: usize, row: usize) []const u16 { + if (l == 0 or l > t.g.layers or (l < t.g.layers and (t.mode != .target or l < t.low))) + return train.slice(u16, t.zero_history, t.g.hidden); + const ref = if (l == t.g.layers) t.final_h else t.tape[l].h_in; + return train.slice(u16, to.plus(ref, row * t.g.hidden * 2), t.g.hidden); +} + +pub fn greedy(t: *train.Trainer, seqs: []const train.Seq, same: []bool) !void { + if (seqs.len > train.max_seqs or same.len < seqs.len or t.m.learning != null) return error.BadPass; + const prompt = t.m.kernels.prompt; + t.m.kernels.prompt = false; + defer t.m.kernels.prompt = prompt; + for (seqs, 0..) |sq, si| { + if (sq.start < 1 or sq.start >= sq.ids.len or sq.ids.len > train.max_rows + 1) return error.BadExample; + try t.runner.reset(@intCast(si)); + same[si] = true; + for (0..sq.ids.len - 1) |row| { + try t.forwardRow(&t.runner, @intCast(si), row, sq.ids[row..][0..1], row + 1 >= sq.start); + if (row + 1 < sq.start) continue; + const logits = train.slice(u16, t.m.frame.get(.logits), t.g.vocab); + var top: u32 = 0; + var best = -std.math.inf(f32); + for (logits, 0..) |bits, id| { + const v: f32 = @bitCast(@as(u32, bits) << 16); + if (!std.math.isFinite(v)) return error.NonFiniteLearningLogit; + if (v > best) { + best = v; + top = @intCast(id); + } + } + same[si] = same[si] and top == sq.ids[row + 1]; + } + } +} + +pub fn tapRows(t: *train.Trainer, ids: []const u32, context: usize, rows: []const u32, layers: []const usize, out: []u16) !void { + const D = t.g.hidden; + if (ids.len == 0 or ids.len >= t.g.max_position or context > ids.len or out.len != rows.len * layers.len * D or t.m.learning != null) return error.BadTap; + for (rows, 0..) |row, i| if (row >= ids.len or (i > 0 and row <= rows[i - 1])) return error.BadTap; + for (layers) |l| if (l >= t.g.layers) return error.BadTap; + // Long-context taps are admitted beside the actual trainer and serving allocations, before a second cache exists. + const need = try @import("prompt_memory.zig").runnerBytes(t.g, @intCast(ids.len + 1), 1, t.m.frame.capacity, t.m.device.tensorUnits(), 0); + const free = t.m.device.maxWorkingSet() -| t.m.device.allocated(); + if (need + (8 << 30) > free) return error.LearningMemory; + var runner = try Runner.init(t.gpa, t.m, 1, @intCast(ids.len + 1)); + defer runner.deinit(); + runner.learning_rows = true; + runner.learning_io = t.io; + runner.setResident(t.follow); + const old_mode = t.mode; + const old_at = t.hook_at; + const prompt = t.m.kernels.prompt; + t.mode = .keys; + t.hook_at = 0; + t.m.kernels.prompt = false; + defer { + t.mode = old_mode; + t.hook_at = old_at; + t.m.kernels.prompt = prompt; + t.m.learning = null; + } + t.m.learning = .{ .ctx = t, .save = @import("train_tape.zig").save, .add = plainPocket }; + var ri: usize = 0; + for (ids, 0..) |_, row| { + try t.forwardRow(&runner, 0, row, ids[row..][0..1], false); + if (ri == rows.len or row != rows[ri]) continue; + for (layers, 0..) |l, j| @memcpy(out[(ri * layers.len + j) * D ..][0..D], t.normed(l, 0)); + ri += 1; + } +} +fn plainPocket(ctx: *anyopaque, e: mtl.ComputeEncoder, l: usize, x: to.Ref, y: to.Ref, rows: u32) !void { + const t: *train.Trainer = @ptrCast(@alignCast(ctx)); + if (t.m.pockets) |*p| try p.add(e, l, x, y, rows); +} diff --git a/zig/src/families/qwen27/train_ops.zig b/zig/src/families/qwen27/train_ops.zig new file mode 100644 index 00000000000..ffacb934277 --- /dev/null +++ b/zig/src/families/qwen27/train_ops.zig @@ -0,0 +1,140 @@ +//! Metal learner primitives over the native engine's saved rows and original affine words. +const std = @import("std"); +const mtl = @import("metal"); +pub const Ref = @import("projection.zig").Ref; +const sources = @import("qwen_runtime_sources"); + +pub const Shape = extern struct { + u: [4]u32 align(16) = @splat(0), + f: [4]f32 align(16) = @splat(0), +}; +pub const GdnShape = extern struct { rows: i32, nk: i32, nv: i32, conv: i32, proj: i32 }; +pub const Heads = extern struct { rows: i32, heads: i32, kv_heads: i32, dim: i32, qkv: i32, scale: f32, prefix: i32 = 0 }; +pub const Q4 = struct { words: Ref, scales: Ref, biases: Ref, n: usize, k: usize }; + +const gdn_names = [_][]const u8{ + "tf_gdn_norm_back", "tf_gdn_scan_back", + "tf_gdn_qk_back", "tf_gdn_gates_back", + "tf_gdn_conv_back", +}; +const attn_names = [_][]const u8{ + "tf_attn_q", "tf_attn_gate_back", "tf_attn_prep_back", +}; +const row_names = [_][]const u8{ + "tf_learn_copy", "tf_learn_widen", "tf_learn_gdn_act", "tf_learn_zero", "tf_learn_nudge", "tf_learn_loss", + "tf_learn_rms_back", "tf_learn_swiglu_back", "tf_learn_pocket_back", +}; +const linear_names = [_][]const u8{ "tf_learn_q4_back", "tf_learn_attn_kv_back", "tf_learn_attn_gate_grad" }; + +pub const Kernels = struct { + allocator: std.mem.Allocator, + pipelines: std.StringHashMapUnmanaged(mtl.Pipeline) = .empty, + + pub fn init(a: std.mem.Allocator, device: mtl.Device) !Kernels { + var k: Kernels = .{ .allocator = a }; + errdefer k.deinit(); + const units = [_]struct { text: []const u8, names: []const []const u8 }{ + .{ .text = sources.gdn_train, .names = &gdn_names }, + .{ .text = sources.attn_train, .names = &attn_names }, + .{ .text = sources.learn_rows, .names = &row_names }, + .{ .text = sources.pocket, .names = &.{"tf_q27_pocket_scaled"} }, + .{ .text = sources.learn_linear, .names = &linear_names }, + }; + for (units) |unit| { + const library = try mtl.Library.fromSource(device, unit.text, mtl.CompileOptions.mlx()); + defer library.deinit(); + for (unit.names) |name| { + const pipeline = try mtl.Pipeline.init(device, library, name, false); + k.pipelines.put(a, name, pipeline) catch |err| { + pipeline.deinit(); + return err; + }; + } + } + return k; + } + + pub fn deinit(k: *Kernels) void { + var values = k.pipelines.valueIterator(); + while (values.next()) |p| p.deinit(); + k.pipelines.deinit(k.allocator); + k.* = undefined; + } +}; + +pub const Work = struct { decodes: usize = 0, fmas: usize = 0 }; + +pub const Ops = struct { + kernels: *const Kernels, + e: mtl.ComputeEncoder, + work: ?*Work = null, + + pub fn go(o: Ops, name: []const u8, buffers: []const Ref, params: anytype, groups: mtl.Size, threads: usize) !void { + const pipeline = o.kernels.pipelines.get(name) orelse return error.NoLearningKernel; + if (threads == 0 or threads > pipeline.maxThreads()) return error.UnsupportedLearningGroup; + o.e.setPipeline(pipeline); + for (buffers, 0..) |buffer, slot| o.e.setBuffer(buffer.buffer, buffer.offset, slot); + o.e.setValue(params, buffers.len); + o.e.dispatchGroups(groups, .{ .width = threads }); + o.e.barrier(); + } + + pub fn linear(o: Ops, name: []const u8, buffers: []const Ref, shape: Shape, count: usize) !void { + if (count == 0) return; + try o.go(name, buffers, shape, .{ .width = (count + 255) / 256 }, 256); + } + + pub fn copy(o: Ops, source: Ref, destination: Ref, bytes: usize) !void { + const aligned = source.offset % 16 == 0 and destination.offset % 16 == 0; + try o.linear("tf_learn_copy", &.{ source, destination }, .{ .u = .{ @intCast(bytes), @intFromBool(aligned), 0, 0 } }, (bytes + 15) / 16); + } + + pub fn widen(o: Ops, source: Ref, destination: Ref, count: usize) !void { + try o.linear("tf_learn_widen", &.{ source, destination }, .{ .u = .{ @intCast(count), 0, 0, 0 } }, count); + } + + pub fn zero(o: Ops, destination: Ref, count: usize) !void { + try o.linear("tf_learn_zero", &.{destination}, .{ .u = .{ @intCast(count), 0, 0, 0 } }, count); + } + + pub fn nudge(o: Ops, destination: Ref, delta: Ref, count: usize) !void { + try o.linear("tf_learn_nudge", &.{ destination, delta }, .{ .u = .{ @intCast(count), 0, 0, 0 } }, count); + } + + pub fn q4Back(o: Ops, gradient: Ref, w: Q4, destination: Ref, rows: usize, add: bool) !void { + if (o.work) |work| { + work.decodes += @import("train_schedule.zig").q4Threads(rows, w.k) * w.n; + work.fmas += rows * w.k * w.n; + } + try o.linear("tf_learn_q4_back", &.{ gradient, w.words, w.scales, w.biases, destination }, .{ + .u = .{ @intCast(rows), @intCast(w.n), @intCast(w.k), @intFromBool(add) }, + }, @import("train_schedule.zig").q4Threads(rows, w.k)); + } + + pub fn rmsBack(o: Ops, x: Ref, gain: Ref, dy: Ref, residual_gradient: Ref, rows: usize, width: usize, eps: f32) !void { + try o.go("tf_learn_rms_back", &.{ x, gain, dy, residual_gradient }, Shape{ + .u = .{ @intCast(rows), @intCast(width), 0, 0 }, + .f = .{ eps, 0, 0, 0 }, + }, .{ .width = rows }, 256); + } + + pub fn loss(o: Ops, logits: Ref, targets: Ref, weights: Ref, gradient: Ref, stats: Ref, rows: usize, vocab: usize) !void { + try o.go("tf_learn_loss", &.{ logits, targets, weights, gradient, stats }, Shape{ + .u = .{ @intCast(rows), @intCast(vocab), 0, 0 }, + }, .{ .width = rows }, 256); + } + + pub fn swigluBack(o: Ops, pair: Ref, gradient: Ref, output: Ref, rows: usize, width: usize) !void { + try o.linear("tf_learn_swiglu_back", &.{ pair, gradient, output }, .{ + .u = .{ @intCast(rows), @intCast(width), 0, 0 }, + }, rows * width); + } +}; + +pub fn at(buffer: mtl.Buffer, offset: usize) Ref { + return .{ .buffer = buffer, .offset = offset }; +} + +pub fn plus(ref: Ref, offset: usize) Ref { + return .{ .buffer = ref.buffer, .offset = ref.offset + offset }; +} diff --git a/zig/src/families/qwen27/train_row.zig b/zig/src/families/qwen27/train_row.zig new file mode 100644 index 00000000000..c99406ce2ad --- /dev/null +++ b/zig/src/families/qwen27/train_row.zig @@ -0,0 +1,30 @@ +//! A learner's single-row Round view has the same metadata as Round.init, with no owning heap allocations. +const std = @import("std"); +const Round = @import("round_plan.zig").Round; +const Window = @import("state.zig").Window; + +pub const Row = struct { + ids: [1]u32 = undefined, + feed: [1]i32 = undefined, + draw: [1]u64 = undefined, + slots: [1]u32 = undefined, + firsts: [1]u32 = .{0}, + parents: [1]i32 = .{-1}, + depths: [1]u32 = .{0}, + conv: [16]u32 = undefined, + windows: [1]Window = undefined, + + /// Borrowed until this Row dies; do not call Round.deinit on the view. + pub fn view(r: *Row, a: std.mem.Allocator, id: u32, slot: u32, at: u32, capacity: u32, taps: u32, slots: u32, vocab: u32) !Round { + if (slots == 0 or slots > 128 or vocab == 0 or slot >= slots or @as(u64, at) + 1 > capacity) return error.BadRoundPlan; + if (id >= vocab) return error.BadTokenId; + if (taps < 1 or taps > 16) return error.BadWindow; + r.ids = .{id}; + r.feed = .{std.math.cast(i32, at) orelse return error.PositionOverflow}; + r.draw = .{@as(u64, at) + 1}; + r.slots = .{slot}; + for (r.conv[0..taps], 0..) |*v, i| v.* = @intCast(i); + r.windows = .{.{ .gpa = a, .start = at, .parents = &r.parents, .depths = &r.depths, .conv = r.conv[0..taps], .taps = taps }}; + return .{ .allocator = a, .ids = &r.ids, .feed_positions = &r.feed, .draw_positions = &r.draw, .windows = &r.windows, .slots = &r.slots, .firsts = &r.firsts }; + } +}; diff --git a/zig/src/families/qwen27/train_scalars.zig b/zig/src/families/qwen27/train_scalars.zig new file mode 100644 index 00000000000..5e34c9c3a1f --- /dev/null +++ b/zig/src/families/qwen27/train_scalars.zig @@ -0,0 +1,27 @@ +//! Preserve F32 A_log values and widen BF16 scalars once for the Metal backward. +const std = @import("std"); +pub const Kind = enum { bf16, f32 }; + +pub fn values(a: std.mem.Allocator, kind: Kind, raw: []const u8) ![]f32 { + const stride: usize = if (kind == .bf16) 2 else 4; + if (raw.len % stride != 0) return error.BadLearningScalar; + const out = try a.alloc(f32, raw.len / stride); + for (out, 0..) |*v, i| { + const bits = if (kind == .bf16) @as(u32, std.mem.readInt(u16, raw[i * 2 ..][0..2], .little)) << 16 else std.mem.readInt(u32, raw[i * 4 ..][0..4], .little); + v.* = @bitCast(bits); + } + return out; +} + +test "qwen27 learning: F32 decay logs keep their low bits and BF16 gains widen exactly" { + const a = std.testing.allocator; + const f = [_]f32{ -0.1234567, 1.234567, 0, -3.1 }; + const full = try values(a, .f32, std.mem.sliceAsBytes(&f)); + defer a.free(full); + try std.testing.expectEqualSlices(u8, std.mem.sliceAsBytes(&f), std.mem.sliceAsBytes(full)); + const b = [_]u16{ 0xbf80, 0x0000, 0x3f81, 0x8000 }; + const wide = try values(a, .bf16, std.mem.sliceAsBytes(&b)); + defer a.free(wide); + for (b, wide) |bits, v| try std.testing.expectEqual(@as(u32, bits) << 16, @as(u32, @bitCast(v))); + try std.testing.expectError(error.BadLearningScalar, values(a, .f32, &.{ 0, 1 })); +} diff --git a/zig/src/families/qwen27/train_schedule.zig b/zig/src/families/qwen27/train_schedule.zig new file mode 100644 index 00000000000..3471c3b7850 --- /dev/null +++ b/zig/src/families/qwen27/train_schedule.zig @@ -0,0 +1,25 @@ +//! The native row program stays serial; only independent head rows and submissions are scheduled here. +const mode_api = @import("living").train_mode; +const to = @import("train_ops.zig"); + +pub fn commitEvery(learning_rows: bool) usize { + return if (learning_rows) 0 else 4; +} +pub fn head(mode: mode_api.Mode, row: usize, start: usize) bool { + return mode != .keys and row + 1 >= start; +} +pub fn q4Threads(rows: usize, width: usize) usize { + return ((rows + 3) / 4) * width; +} +pub fn loss(t: anytype, o: anytype) !void { + for (t.answers[0..t.nseq]) |a| { + try o.loss(to.plus(t.logits, a.first * t.g.vocab * 2), to.plus(t.targets, a.first * 4), to.plus(t.weights, a.first * 4), to.plus(t.dlogits, a.first * t.g.vocab * 4), to.plus(t.stats, a.first * 8), a.rows, t.g.vocab); + } +} +pub fn headBack(t: anytype, o: anytype) !void { + // Zero-loss rows have +0 input gradients; every answer retains its original fixed-order affine product. + try o.zero(t.dy, t.rows * t.g.hidden); + for (t.answers[0..t.nseq]) |a| { + try o.q4Back(to.plus(t.dlogits, a.first * t.g.vocab * 4), t.head, to.plus(t.dy, a.first * t.g.hidden * 4), a.rows, false); + } +} diff --git a/zig/src/families/qwen27/train_submit.zig b/zig/src/families/qwen27/train_submit.zig new file mode 100644 index 00000000000..7233faa63e4 --- /dev/null +++ b/zig/src/families/qwen27/train_submit.zig @@ -0,0 +1,34 @@ +//! One row's unchanged native stages in one command buffer, with host encoding and completion measured separately. +const std = @import("std"); + +pub const Stats = struct { + encode: f64 = 0, + wait: f64 = 0, + gpu: f64 = 0, + buffers: usize = 0, + waits: usize = 0, +}; +pub fn now(io: ?std.Io) f64 { + return if (io) |i| @as(f64, @floatFromInt(std.Io.Clock.awake.now(i).toNanoseconds())) / 1e9 else 0; +} +pub fn run(queue: anytype, program: anytype, stats: *Stats, io: ?std.Io) !f64 { + const start = now(io); + const cb = queue.commandBuffer(); + const e = cb.compute(.concurrent); + var ended = false; + defer if (!ended) e.end(); + try program.encode(e); + e.end(); + ended = true; + const encoded = now(io); + cb.commit(); + cb.wait(); + stats.encode += encoded - start; + stats.wait += now(io) - encoded; + stats.buffers += 1; + stats.waits += 1; + if (cb.failure() != null) return error.LearningGpuFailure; + const gpu = cb.gpuSeconds(); + stats.gpu += gpu; + return gpu; +} diff --git a/zig/src/families/qwen27/train_tape.zig b/zig/src/families/qwen27/train_tape.zig new file mode 100644 index 00000000000..254367a4ed4 --- /dev/null +++ b/zig/src/families/qwen27/train_tape.zig @@ -0,0 +1,125 @@ +//! Native forward values retained for the learner; all offsets are packed pass rows. +const std = @import("std"); +const mtl = @import("metal"); +const to = @import("train_ops.zig"); +const hooks = @import("train_hooks.zig"); +pub const Ref = @import("projection.zig").Ref; +pub const Layer = struct { + y: Ref = undefined, + h_in: Ref = undefined, + h_mid: Ref = undefined, + gu: Ref = undefined, + proj: Ref = undefined, + act: Ref = undefined, + q: Ref = undefined, + k: Ref = undefined, + decay: Ref = undefined, + beta: Ref = undefined, + recur: Ref = undefined, + checkpoints: Ref = undefined, + pq: Ref = undefined, + pk: Ref = undefined, + pv: Ref = undefined, + qkv: Ref = undefined, + gated: Ref = undefined, +}; + +pub fn save(ctx: *anyopaque, e: mtl.ComputeEncoder, point: hooks.Point, l: usize, refs: []const Ref, rows: u32) !void { + const t: *@import("train.zig").Trainer = @ptrCast(@alignCast(ctx)); + if (rows != 1) return error.BadLearningRows; + const g = t.g; + const D = g.hidden; + const o = to.Ops{ .kernels = &t.k, .e = e }; + const at = t.hook_at; + if (point == .final) { + if (t.mode != .keys) try copy(o, refs[0], t.final_h, at, D * 2); + return; + } + if (point == .logits) { + if (t.mode != .keys) try copy(o, refs[0], t.logits, at, g.vocab * 2); + return; + } + const kept = t.tape[l]; + // Every layer's postnorm is needed by the pocket fitter, even below the backwards limit. + if (point == .post) try copy(o, refs[1], kept.y, at, D * 2); + if (t.mode != .target or l < t.low) return; + const conv = g.gdnQkvDim(); + const vi = g.gdnValueDim(); + const ki = g.k_heads * g.dk; + const proj = conv + vi + 2 * g.v_heads; + switch (point) { + .input => { + try copy(o, refs[0], kept.h_in, at, D * 2); + if (g.kind(l) == .linear and t.local_row % 4 == 0) { + const state = try t.runner.gdn.committedSpan(t.runner.linear_index[l], t.slot, true); + try o.copy(.{ .buffer = state.buffer, .offset = state.offset }, to.plus(kept.checkpoints, (t.cp_first[t.slot] + t.local_row / 4) * state.bytes), state.bytes); + } + }, + .post => try copy(o, refs[0], kept.h_mid, at, D * 2), + .mlp => try copy(o, refs[0], kept.gu, at, 2 * g.intermediate * 2), + .gdn => { + const dest = to.plus(kept.proj, at * proj * 2); + try o.copy(refs[0], dest, conv * 2); + try o.copy(refs[1], to.plus(dest, conv * 2), (vi + 2 * g.v_heads) * 2); + }, + .gdn_state => { + try o.widen(refs[0], to.plus(kept.q, at * ki * 4), ki); + try o.widen(refs[1], to.plus(kept.k, at * ki * 4), ki); + try o.copy(refs[2], to.plus(kept.act, (at * conv + 2 * ki) * 2), vi * 2); + try copy(o, refs[3], kept.decay, at, g.v_heads * 4); + try o.widen(refs[4], to.plus(kept.beta, at * g.v_heads * 4), g.v_heads); + try copy(o, refs[5], kept.recur, at, vi * 2); + }, + .attention => { + try copy(o, refs[0], kept.pq, at, g.qDim() * 2); + try copy(o, refs[1], kept.pk, at, g.kvDim() * 2); + try copy(o, refs[2], kept.pv, at, g.kvDim() * 2); + }, + .prepared_attention => { + const qi = g.heads * g.head_dim; + const kv = g.kvDim(); + const dest = to.plus(kept.qkv, at * (qi + 2 * kv) * 2); + try o.copy(refs[0], dest, qi * 2); + try o.copy(refs[1], to.plus(dest, qi * 2), kv * 2); + try o.copy(refs[2], to.plus(dest, (qi + kv) * 2), kv * 2); + }, + .gated => if (g.kind(l) == .attention) { + try copy(o, refs[0], kept.gated, at, g.heads * g.head_dim * 2); + }, + .final, .logits => unreachable, + } +} +fn copy(o: to.Ops, src: Ref, dest: Ref, row: usize, width: usize) !void { + try o.copy(src, to.plus(dest, row * width), width); +} + +pub fn carve(t: anytype) !void { + const g = t.g; + const R = @import("train.zig").pack_rows; + t.tape = try t.gpa.alloc(Layer, g.layers); + @memset(t.tape, .{}); + for (t.tape, 0..) |*k, l| { + k.y = try t.alloc(R * g.hidden * 2); + if (l < @import("train.zig").keepLow(g.layers)) continue; + k.h_in = try t.alloc(R * g.hidden * 2); + k.h_mid = try t.alloc(R * g.hidden * 2); + k.gu = try t.alloc(R * 2 * g.intermediate * 2); + if (g.kind(l) == .linear) { + const conv = g.gdnQkvDim(); + k.proj = try t.alloc(R * (conv + g.gdnValueDim() + 2 * g.v_heads) * 2); + k.act = try t.alloc(R * conv * 2); + k.q = try t.alloc(R * g.k_heads * g.dk * 4); + k.k = try t.alloc(R * g.k_heads * g.dk * 4); + k.decay = try t.alloc(R * g.v_heads * 4); + k.beta = try t.alloc(R * g.v_heads * 4); + k.recur = try t.alloc(R * g.gdnValueDim() * 2); + k.checkpoints = try t.alloc((R / 4 + @import("train.zig").max_seqs) * g.v_heads * g.dv * g.dk * 4); + } else { + k.pq = try t.alloc(R * g.qDim() * 2); + k.pk = try t.alloc(R * g.kvDim() * 2); + k.pv = try t.alloc(R * g.kvDim() * 2); + k.qkv = try t.alloc(R * (g.heads * g.head_dim + 2 * g.kvDim()) * 2); + k.gated = try t.alloc(R * g.heads * g.head_dim * 2); + } + } +} diff --git a/zig/src/families/qwen3_5/cuda_wide.zig b/zig/src/families/qwen3_5/cuda_wide.zig index fb080281003..b7262a99534 100644 --- a/zig/src/families/qwen3_5/cuda_wide.zig +++ b/zig/src/families/qwen3_5/cuda_wide.zig @@ -1,45 +1,4 @@ -//! A widened dense MLP: preserve the base codes and read the exact saved pocket. Credit @ZackSample #911. -const std = @import("std"); -const affine = @import("living").affine; - -/// Preserve each base row's byte prefix, including separate affine groups in the down projection. -pub fn base(a: std.mem.Allocator, bytes: []const u8, rows: usize, stride: usize, kept: usize) ![]u8 { - if (stride == 0 or kept > stride or rows == 0 or bytes.len % stride != 0 or bytes.len / stride < rows) - return error.UnexpectedTensor; - const out = try a.alloc(u8, rows * kept); - for (0..rows) |row| @memcpy(out[row * kept ..][0..kept], bytes[row * stride ..][0..kept]); - return out; -} -fn value(ts: anytype, width: usize, row: usize, col: usize) f32 { - const w = std.mem.readInt(u32, ts[0].bytes[(row * width + col) / 8 * 4 ..][0..4], .little); - const i = (row * width + col) / 64; - const scale = affine.f32of(std.mem.readInt(u16, ts[1].bytes[i * 2 ..][0..2], .little)); - const bias = affine.f32of(std.mem.readInt(u16, ts[2].bytes[i * 2 ..][0..2], .little)); - return scale * @as(f32, @floatFromInt((w >> @intCast(4 * (col % 8))) & 15)) + bias; -} -pub fn read(ck: anytype, prefix: []const u8, name: []const u8, n: usize, k: usize, extra: []f32) !void { - var buf: [192]u8 = undefined; - var ts: [3]@TypeOf(try ck.get("")) = undefined; - for ([_][]const u8{ "weight", "scales", "biases" }, &ts) |suffix, *t| - t.* = try ck.get(try std.fmt.bufPrint(&buf, "{s}{s}.{s}", .{ prefix, name, suffix })); - const na = ts[0].dim(0); - const ka = ts[0].dim(1) * 8; - if (!ts[0].is(.u32, &.{ na, ka / 8 }) or !ts[1].is(.bf16, &.{ na, ka / 64 }) or - !ts[2].is(.bf16, &.{ na, ka / 64 }) or n > na or k > ka or ka % 64 != 0) return error.UnexpectedTensor; - if (na > n and ka == k and extra.len == (na - n) * k) { - for (n..na) |row| for (0..k) |col| { - extra[(row - n) * k + col] = value(ts, ka, row, col); - }; - } else if (na == n and ka > k and extra.len == (ka - k) * n) { - for (0..n) |row| for (k..ka) |col| { - extra[(col - k) * n + row] = value(ts, ka, row, col); - }; - } else return error.UnexpectedTensor; -} - -test "widened down projection keeps every base group byte for byte across row strides" { - const bytes = [_]u8{ 1, 2, 3, 4, 90, 91, 5, 6, 7, 8, 92, 93 }; - const out = try base(std.testing.allocator, &bytes, 2, 6, 4); - defer std.testing.allocator.free(out); - try std.testing.expectEqualSlices(u8, &.{ 1, 2, 3, 4, 5, 6, 7, 8 }, out); -} +//! Compatibility names for the shared widened dense MLP reader. Credit @ZackSample #911. +const shared = @import("core").dense_pocket; +pub const base = shared.base; +pub const read = shared.read; diff --git a/zig/src/living/families.zig b/zig/src/living/families.zig index a0df161d523..723bb32b0ef 100644 --- a/zig/src/living/families.zig +++ b/zig/src/living/families.zig @@ -60,6 +60,16 @@ pub const qwen3_5: Family = .{ .quant = .{ .bits = 4, .group = 64 }, .keys = .{ .scope = "text_config", .width = "intermediate_size" }, .experts = .every, + .widths = .{ + .embedding = "language_model.model.embed_tokens", + .head = "language_model.lm_head", + .mixer = "", + .aliases = &.{ "model.language_model.", "language_model.", "text_model.", "model." }, + .pattern = .{ .types = "layer_types", .linear = "linear_attention", .attention = "full_attention", .interval = "full_attention_interval", .default_interval = 4 }, + .common = &.{ "mlp.gate_proj", "mlp.up_proj", "mlp.down_proj" }, + .mamba = &.{ "linear_attn.in_proj_qkv", "linear_attn.in_proj_z", "linear_attn.in_proj_b", "linear_attn.in_proj_a", "linear_attn.out_proj" }, + .attention = &.{ "self_attn.q_proj", "self_attn.k_proj", "self_attn.v_proj", "self_attn.o_proj" }, + }, }; pub const all = [_]Family{ nemotron_h, nemotron_h_omni, qwen4_exp, qwen3_5 }; diff --git a/zig/src/living/family.zig b/zig/src/living/family.zig index 7b6f28edc48..9819ea25a06 100644 --- a/zig/src/living/family.zig +++ b/zig/src/living/family.zig @@ -53,12 +53,23 @@ pub const Keys = struct { /// Which layers have a shared expert: those a layer pattern marks MoE, or every layer. pub const Experts = enum { pattern, every }; +/// A dense family's mixer kinds are independent of the layers where its learnable MLP sits. +pub const WidthPattern = struct { + types: []const u8, + linear: []const u8, + attention: []const u8, + interval: []const u8, + default_interval: usize, +}; + /// Quantized matrices read by a native family, in its loader's admission order. pub const Widths = struct { embedding: []const u8, head: []const u8, mixer: []const u8, aliases: []const []const u8 = &.{}, + pattern: ?WidthPattern = null, + common: []const []const u8 = &.{}, residuals: []const []const u8 = &.{}, mamba: []const []const u8 = &.{}, attention: []const []const u8 = &.{}, diff --git a/zig/src/living/testdata/qwen27-mlx-config.json b/zig/src/living/testdata/qwen27-mlx-config.json new file mode 100644 index 00000000000..3fb03e916f4 --- /dev/null +++ b/zig/src/living/testdata/qwen27-mlx-config.json @@ -0,0 +1,170 @@ +{ + "architectures": [ + "Qwen3_5ForConditionalGeneration" + ], + "do_sample": true, + "eos_token_id": [ + 248046, + 248044 + ], + "generation_config": { + "bos_token_id": 248044, + "do_sample": true, + "eos_token_id": [ + 248046, + 248044 + ], + "pad_token_id": 248044, + "temperature": 1.0, + "top_k": 20, + "top_p": 0.95 + }, + "image_token_id": 248056, + "language_model_only": false, + "model_type": "qwen3_5", + "quantization": { + "group_size": 64, + "bits": 4, + "mode": "affine" + }, + "quantization_config": { + "group_size": 64, + "bits": 4, + "mode": "affine" + }, + "temperature": 1.0, + "text_config": { + "attention_bias": false, + "attention_dropout": 0.0, + "attn_output_gate": true, + "bos_token_id": 248044, + "dtype": "bfloat16", + "eos_token_id": 248044, + "full_attention_interval": 4, + "head_dim": 256, + "hidden_act": "silu", + "hidden_size": 5120, + "initializer_range": 0.02, + "intermediate_size": 17408, + "layer_types": [ + "linear_attention", + "linear_attention", + "linear_attention", + "full_attention", + "linear_attention", + "linear_attention", + "linear_attention", + "full_attention", + "linear_attention", + "linear_attention", + "linear_attention", + "full_attention", + "linear_attention", + "linear_attention", + "linear_attention", + "full_attention", + "linear_attention", + "linear_attention", + "linear_attention", + "full_attention", + "linear_attention", + "linear_attention", + "linear_attention", + "full_attention", + "linear_attention", + "linear_attention", + "linear_attention", + "full_attention", + "linear_attention", + "linear_attention", + "linear_attention", + "full_attention", + "linear_attention", + "linear_attention", + "linear_attention", + "full_attention", + "linear_attention", + "linear_attention", + "linear_attention", + "full_attention", + "linear_attention", + "linear_attention", + "linear_attention", + "full_attention", + "linear_attention", + "linear_attention", + "linear_attention", + "full_attention", + "linear_attention", + "linear_attention", + "linear_attention", + "full_attention", + "linear_attention", + "linear_attention", + "linear_attention", + "full_attention", + "linear_attention", + "linear_attention", + "linear_attention", + "full_attention", + "linear_attention", + "linear_attention", + "linear_attention", + "full_attention" + ], + "linear_conv_kernel_dim": 4, + "linear_key_head_dim": 128, + "linear_num_key_heads": 16, + "linear_num_value_heads": 48, + "linear_value_head_dim": 128, + "mamba_ssm_dtype": "float32", + "max_position_embeddings": 262144, + "model_type": "qwen3_5_text", + "mtp_num_hidden_layers": 1, + "mtp_use_dedicated_embeddings": false, + "num_attention_heads": 24, + "num_hidden_layers": 64, + "num_key_value_heads": 4, + "output_gate_type": "swish", + "pad_token_id": null, + "partial_rotary_factor": 0.25, + "rms_norm_eps": 1e-06, + "rope_parameters": { + "mrope_interleaved": true, + "mrope_section": [ + 11, + 11, + 10 + ], + "partial_rotary_factor": 0.25, + "rope_theta": 10000000, + "rope_type": "default" + }, + "tie_word_embeddings": false, + "use_cache": true, + "vocab_size": 248320 + }, + "tie_word_embeddings": false, + "top_k": 20, + "top_p": 0.95, + "transformers_version": "5.8.0.dev0", + "video_token_id": 248057, + "vision_config": { + "deepstack_visual_indexes": [], + "depth": 27, + "hidden_act": "gelu_pytorch_tanh", + "hidden_size": 1152, + "in_channels": 3, + "initializer_range": 0.02, + "intermediate_size": 4304, + "model_type": "qwen3_5", + "num_heads": 16, + "num_position_embeddings": 2304, + "out_hidden_size": 5120, + "patch_size": 16, + "spatial_merge_size": 2, + "temporal_patch_size": 2 + }, + "vision_end_token_id": 248054, + "vision_start_token_id": 248053 +} \ No newline at end of file diff --git a/zig/src/living/widths.zig b/zig/src/living/widths.zig index 2084b01f876..d64e4097649 100644 --- a/zig/src/living/widths.zig +++ b/zig/src/living/widths.zig @@ -15,24 +15,55 @@ pub fn other(a: std.mem.Allocator, f: Family, root: std.json.ObjectMap) !?Mismat const global = try width(q, .{ .bits = 0, .group = 64 }); if (global.bits == 0 or global.group == 0) return error.BadConfig; if (try matrix(a, f, q, global, names.embedding, false)) |m| return m; - const kinds = try families.kinds(a, f, o); - for (kinds, 0..) |kind, i| { + const layer_kinds = try kinds(a, f, o); + for (layer_kinds, 0..) |kind, i| { const members = switch (kind) { 'M' => names.mamba, '*' => names.attention, 'E' => names.expert, else => return error.BadConfig, }; - for (members) |member| { + for ([_][]const []const u8{ members, names.common }) |list| for (list) |member| { const path = try std.fmt.allocPrint(a, "{s}{d}.{s}{s}", .{ f.names.layers, i, names.mixer, member }); var residual = false; for (names.residuals) |r| residual = residual or std.mem.eql(u8, member, r); if (try matrix(a, f, q, global, path, residual)) |m| return m; - } + }; } return matrix(a, f, q, global, names.head, false); } +fn kinds(a: std.mem.Allocator, f: Family, o: std.json.ObjectMap) ![]const u8 { + const p = f.widths.?.pattern orelse return families.kinds(a, f, o); + const count = families.intField(o, f.keys.layers) orelse return error.BadConfig; + const out = try a.alloc(u8, count); + errdefer a.free(out); + if (o.get(p.types)) |v| { + if (v != .array or v.array.items.len != count) return error.BadConfig; + const interval: ?usize = if (o.get(p.interval) != null) families.intField(o, p.interval) orelse return error.ConflictingLayerPattern else null; + if (interval == 0) return error.ConflictingLayerPattern; + for (v.array.items, out, 0..) |v_, *kind, i| { + if (v_ != .string) return error.BadConfig; + kind.* = if (std.mem.eql(u8, v_.string, p.linear)) 'M' else if (std.mem.eql(u8, v_.string, p.attention)) '*' else return error.BadConfig; + if (interval) |n| if ((kind.* == '*') != ((i + 1) % n == 0)) return error.ConflictingLayerPattern; + } + } else { + const interval = if (o.get(p.interval) != null) families.intField(o, p.interval) orelse return error.BadConfig else p.default_interval; + if (interval == 0) return error.BadConfig; + for (out, 0..) |*kind, i| kind.* = if ((i + 1) % interval == 0) '*' else 'M'; + } + return out; +} + +fn canonical(f: Family, name: []const u8) []const u8 { + var path = name; + if (std.mem.endsWith(u8, path, ".weight")) path = path[0 .. path.len - ".weight".len]; + for (f.widths.?.aliases) |alias| if (std.mem.startsWith(u8, path, alias)) { + path = path[alias.len..]; + }; + return path; +} + fn quantBlock(o: std.json.ObjectMap) ?std.json.ObjectMap { for ([_][]const u8{ "quantization", "quantization_config" }) |key| { if (o.get(key)) |v| if (v == .object and v.object.count() > 0) return v.object; @@ -50,12 +81,7 @@ fn matrix(a: std.mem.Allocator, f: Family, q: std.json.ObjectMap, global: Quant, var got = global; var it = q.iterator(); while (it.next()) |entry| { - var path = entry.key_ptr.*; - for (f.widths.?.aliases) |alias| if (std.mem.startsWith(u8, path, alias)) { - path = path[alias.len..]; - break; - }; - if (!std.mem.eql(u8, path, name)) continue; + if (!std.mem.eql(u8, canonical(f, entry.key_ptr.*), canonical(f, name))) continue; const v = entry.value_ptr.*; got = switch (v) { .bool => if (v.bool) global else if (residual) f.quant else return error.BadConfig, @@ -92,3 +118,7 @@ test "Metal learner: effective widths use the descriptor, module defaults and se try q.put(a, changed.widths.?.head, .{ .object = .{} }); try std.testing.expectError(error.BadConfig, other(a, changed, root)); } + +test { + _ = @import("widths_qwen_test.zig"); +} diff --git a/zig/src/living/widths_qwen_test.zig b/zig/src/living/widths_qwen_test.zig new file mode 100644 index 00000000000..a12dc51e0c3 --- /dev/null +++ b/zig/src/living/widths_qwen_test.zig @@ -0,0 +1,103 @@ +//! The supplied dense checkpoint config and independent served matrix identities exercise learner width admission. +const std = @import("std"); +const t = std.testing; +const widths = @import("widths.zig"); +const family = @import("families.zig").qwen3_5; +// TensorFold/Qwen3.8-27B-MLX-4bit@70ae7fac63274ff2eac54152031433374cb80f2f (Hugging Face config.json). +const config = @embedFile("testdata/qwen27-mlx-config.json"); +fn root(a: std.mem.Allocator) !std.json.ObjectMap { + return (try std.json.parseFromSliceLeaky(std.json.Value, a, config, .{})).object; +} +test "Dense Qwen widths: supplied 27B MLX config admits before any model or device access" { + var arena: std.heap.ArenaAllocator = .init(t.allocator); + defer arena.deinit(); + try t.expect((try widths.other(arena.allocator(), family, try root(arena.allocator()))) == null); +} +const linear = [_][]const u8{ "linear_attn.in_proj_qkv", "linear_attn.in_proj_z", "linear_attn.in_proj_b", "linear_attn.in_proj_a", "linear_attn.out_proj" }; +const attention = [_][]const u8{ "self_attn.q_proj", "self_attn.k_proj", "self_attn.v_proj", "self_attn.o_proj" }; +const mlp = [_][]const u8{ "mlp.gate_proj", "mlp.up_proj", "mlp.down_proj" }; +fn override(a: std.mem.Allocator, doc: *std.json.ObjectMap, name: []const u8, bits: i64, group: i64) !void { + var v: std.json.ObjectMap = .{}; + try v.put(a, "bits", .{ .integer = bits }); + try v.put(a, "group_size", .{ .integer = group }); + try doc.getPtr("quantization").?.object.put(a, name, .{ .object = v }); +} +fn bad(key: []const u8, named: []const u8, bits: i64, group: i64) !void { + var arena: std.heap.ArenaAllocator = .init(t.allocator); + defer arena.deinit(); + const a = arena.allocator(); + var doc = try root(a); + try override(a, &doc, key, bits, group); + const mismatch = try widths.other(a, family, doc); + try t.expect(mismatch != null); + const m = mismatch.?; + try t.expectEqualStrings(named, m.name); + try t.expectEqual(bits, @as(i64, m.quant.bits)); + try t.expectEqual(group, @as(i64, @intCast(m.quant.group))); +} +test "Dense Qwen widths: every served matrix rejects a mixed width by its checkpoint name" { + try bad("language_model.model.embed_tokens", "language_model.model.embed_tokens", 8, 64); + try bad("language_model.lm_head", "language_model.lm_head", 4, 32); + var count: usize = 2; + for (0..64) |i| { + const mixer: []const []const u8 = if ((i + 1) % 4 == 0) &attention else &linear; + for ([_][]const []const u8{ mixer, &mlp }) |members| for (members) |member| { + var buf: [128]u8 = undefined; + const name = try std.fmt.bufPrint(&buf, "language_model.model.layers.{d}.{s}", .{ i, member }); + try bad(name, name, 8, 64); + count += 1; + }; + } + try t.expectEqual(@as(usize, 498), count); +} +test "Dense Qwen widths: native prefix aliases and weight suffixes cannot bypass admission" { + for ([_][]const u8{ "", "model.", "language_model.", "language_model.model.", "model.language_model.", "model.language_model.model.", "text_model.", "text_model.model." }) |prefix| { + for ([_][]const u8{ "", ".weight" }) |suffix| { + for ([_][2][]const u8{ .{ "layers.0.linear_attn.in_proj_b", "language_model.model.layers.0.linear_attn.in_proj_b" }, .{ "layers.3.self_attn.v_proj", "language_model.model.layers.3.self_attn.v_proj" }, .{ "embed_tokens", "language_model.model.embed_tokens" }, .{ "lm_head", "language_model.lm_head" } }) |pair| { + var buf: [160]u8 = undefined; + try bad(try std.fmt.bufPrint(&buf, "{s}{s}{s}", .{ prefix, pair[0], suffix }), pair[1], 6, 64); + } + } + } +} +test "Dense Qwen widths: MTP, vision and the other mixer kind are not served matrices" { + var arena: std.heap.ArenaAllocator = .init(t.allocator); + defer arena.deinit(); + const a = arena.allocator(); + var doc = try root(a); + for ([_][]const u8{ "language_model.mtp.layers.0.mlp.gate_proj", "vision_tower.blocks.0.attn.qkv", "language_model.model.layers.0.self_attn.q_proj", "language_model.model.layers.3.linear_attn.in_proj_a", "language_model.model.layers.64.mlp.gate_proj" }) |name| try override(a, &doc, name, 8, 64); + try t.expect((try widths.other(a, family, doc)) == null); +} +test "Dense Qwen widths: matching explicit declarations and native interval fallbacks keep served widths" { + var arena: std.heap.ArenaAllocator = .init(t.allocator); + defer arena.deinit(); + const a = arena.allocator(); + var doc = try root(a); + const text = &doc.getPtr("text_config").?.object; + try text.put(a, "full_attention_interval", .{ .integer = 4 }); + try override(a, &doc, "language_model.model.layers.0.self_attn.q_proj", 8, 64); + try t.expect((try widths.other(a, family, doc)) == null); + try t.expect(text.swapRemove("layer_types")); + try t.expect((try widths.other(a, family, doc)) == null); + try text.put(a, "full_attention_interval", .{ .integer = 1 }); + try t.expectEqualStrings("language_model.model.layers.0.self_attn.q_proj", (try widths.other(a, family, doc)).?.name); + try t.expect(text.swapRemove("full_attention_interval")); + try t.expect((try widths.other(a, family, doc)) == null); + try override(a, &doc, "language_model.model.layers.3.self_attn.o_proj", 4, 128); + try t.expectEqualStrings("language_model.model.layers.3.self_attn.o_proj", (try widths.other(a, family, doc)).?.name); +} + +test "Dense Qwen widths: explicit mixer kinds and a supplied interval must agree" { + var arena: std.heap.ArenaAllocator = .init(t.allocator); + defer arena.deinit(); + const a = arena.allocator(); + var doc = try root(a); + const text = &doc.getPtr("text_config").?.object; + try t.expect((try widths.other(a, family, doc)) == null); + for ([_]i64{ 1, 2, 3, 5, 0, -1 }) |n| { + try text.put(a, "full_attention_interval", .{ .integer = n }); + try t.expectError(error.ConflictingLayerPattern, widths.other(a, family, doc)); + } + try text.put(a, "full_attention_interval", .{ .string = "4" }); + try t.expectError(error.ConflictingLayerPattern, widths.other(a, family, doc)); +} diff --git a/zig/src/living_shards_test.zig b/zig/src/living_shards_test.zig index e3fb09668f1..07d3a5f1ffc 100644 --- a/zig/src/living_shards_test.zig +++ b/zig/src/living_shards_test.zig @@ -1,6 +1,7 @@ //! Living Weights' pocket in each family's own shards, rooted here so the tests reach the core's shard files by path. const std = @import("std"); const living = @import("living"); +pub const dense_pocket = @import("core/dense_pocket.zig"); const host4 = @import("core/affine4_host.zig"); test { diff --git a/zig/src/native/metal.zig b/zig/src/native/metal.zig index 235c7667234..eec389e9cde 100644 --- a/zig/src/native/metal.zig +++ b/zig/src/native/metal.zig @@ -318,7 +318,7 @@ fn refusal(a: Allocator, o: api.Open, dense: bool) !?[]const u8 { const t = o.model_type; if (o.kv8) return "--kv-cache fp8 keeps fp8 caches on CUDA; the Metal engines keep bf16: serve without it"; if (o.prompt_int8) return prompt_int8_refusal; - if (!learners.supports(t)) if (try o.slideRefusal(a, "Macs")) |why| return why; + if (!(dense and std.mem.eql(u8, t, "qwen3_5")) and !learners.supports(t)) if (try o.slideRefusal(a, "Macs")) |why| return why; const one_mac: ?[]const u8 = if (std.mem.eql(u8, t, "nemotron_h")) "Nemotron" else if (std.mem.eql(u8, t, "lfm2_moe")) "LFM2.5-24B-A2B" else if (isGemma4(t)) "Gemma 4" else if (std.mem.eql(u8, t, "step5_vl")) "Step-5" else if (std.mem.eql(u8, t, "spark2_5")) "Spark-X2.6" else if (std.mem.eql(u8, t, "minimax_m3_vl")) "MiniMax-M3.1-Flash" else if (!std.mem.eql(u8, t, "qwen3_5")) null else if (dense) "Qwen3.8-27B" else "Qwen3.5-2B"; if (o.speed_up != null) if (one_mac) |name| return try std.fmt.allocPrint(a, "--speed-up joins two Macs for Flash Next, GLM-5.3-Flash and GLM-5.3 only: serve {s} without it", .{name}); if (o.recall and std.mem.eql(u8, t, "qwen4_exp")) return recall_refusal; @@ -343,10 +343,11 @@ fn openQwen27(a: Allocator, gpa: Allocator, io: std.Io, o: api.Open, problem: *[ problem.* = "--drafter-bits takes 0 (bf16) or 4"; return null; } + if (o.slide and try @import("qwen27_slide.zig").refused(a, io, o.dir, problem)) return null; var why: []const u8 = ""; const drafter = if (o.drafts) o.drafter else null; const learn: ?@import("qwen27_disk.zig").Learn = if (o.learn_conversations) if (o.learn) |root| .{ .root = root, .dir = o.dir, .drafter = drafter, .cap = gibBytes(o.learn_gib), .floor = gibBytes(o.learn_min_free_gib), .daily = gibBytes(o.learn_daily_gib), .spill = o.spill, .slots = spill.slots(o) } else null else null; - const h = qwen27.open(gpa, io, o.dir, .{ .context = @intCast(context), .streams = o.lanes, .streams_fixed = o.lanes_fixed, .drafter = drafter, .drafter_name = o.drafter_name, .drafter_bits = o.drafter_bits, .cache_gib = o.prompt_cache_gib, .cache_over_cap = o.prompt_cache_over_cap, .decode_share = o.decode_share, .learn = learn, .vision = o.vision }, a, &why) catch |err| { + const h = qwen27.open(gpa, io, o.dir, .{ .context = @intCast(context), .streams = o.lanes, .streams_fixed = o.lanes_fixed, .drafter = drafter, .drafter_name = o.drafter_name, .drafter_bits = o.drafter_bits, .cache_gib = o.prompt_cache_gib, .cache_over_cap = o.prompt_cache_over_cap, .decode_share = o.decode_share, .slide = if (o.slide) o.dir else null, .learn = learn, .vision = o.vision }, a, &why) catch |err| { problem.* = if (why.len > 0) why else try std.fmt.allocPrint(a, "the native Qwen3.8-27B engine cannot load {s} ({s})", .{ o.dir, @errorName(err) }); return null; }; @@ -531,12 +532,14 @@ test "--recall is refused by Flash Next before any load, and not by the lane eng } } -test "--slide is refused by every family but Nemotron, which learns into its weights" { +test "--slide admits Nemotron and the dense 27B, refusing other Metal families" { var arena: std.heap.ArenaAllocator = .init(std.testing.allocator); defer arena.deinit(); const a = arena.allocator(); try std.testing.expect((try refusal(a, .{ .dir = "d", .model_type = "nemotron_h", .slide = true }, false)) == null); - for ([_][]const u8{ "glm_moe_dsa", "qwen4_exp", "glm5_next", "qwen3_5" }) |t| { + try std.testing.expect((try refusal(a, .{ .dir = "d", .model_type = "qwen3_5", .slide = true }, true)) == null); + try std.testing.expect((try refusal(a, .{ .dir = "d", .model_type = "qwen3_5", .slide = true }, false)) != null); + for ([_][]const u8{ "glm_moe_dsa", "qwen4_exp", "glm5_next" }) |t| { const why = (try refusal(a, .{ .dir = "d", .model_type = t, .slide = true }, true)) orelse return error.TestExpectedRefusal; try std.testing.expectEqualStrings(try std.fmt.allocPrint(a, "--slide: {s} checkpoints do not learn on Macs yet", .{t}), why); } @@ -553,7 +556,7 @@ test "prompt precision: Metal refuses int8 before any model or family-specific l test "slide admission: Metal entry points refuse before checkpoint or device access" { const check = @import("slide_open_test.zig").check; - for (families) |f| if (!std.mem.eql(u8, f.model_type, "nemotron_h")) try check(open, "Macs", &.{f.model_type}); + for (families) |f| if (!std.mem.eql(u8, f.model_type, "nemotron_h") and !std.mem.eql(u8, f.model_type, "qwen3_5")) try check(open, "Macs", &.{f.model_type}); try check(@import("qwen35.zig").open, "Macs", &.{"qwen3_5"}); try check(@import("gemma4.zig").open, "Macs", &.{"gemma4"}); try check(@import("lfm2_moe.zig").open, "Macs", &.{"lfm2_moe"}); diff --git a/zig/src/native/metal_slide.zig b/zig/src/native/metal_slide.zig index f462c90bd97..b7d88aeb653 100644 --- a/zig/src/native/metal_slide.zig +++ b/zig/src/native/metal_slide.zig @@ -63,6 +63,12 @@ pub fn slideWidths(a: Allocator, io: std.Io, dir: []const u8, f: living.Family) if (doc != .object) return null; const mismatch = living.widths.other(a, f, doc.object) catch |e| switch (e) { error.NoWidthDescription => return e, + error.ConflictingLayerPattern => { + const pattern = f.widths.?.pattern.?; + const scope = f.keys.scope orelse ""; + const dot: []const u8 = if (scope.len == 0) "" else "."; + return try std.fmt.allocPrint(a, "--slide: {s}{s}{s} conflicts with {s}{s}{s}", .{ scope, dot, pattern.types, scope, dot, pattern.interval }); + }, else => return null, }; const m = mismatch orelse return null; @@ -84,3 +90,19 @@ test "Metal learner: a family's declarations register it, without a model-name a try std.testing.expect(!R.supports("unknown")); try std.testing.expect(R.supports("future")); } + +test "Metal learner: conflicting dense mixer declarations are a named admission refusal" { + const t = std.testing; + var tmp = t.tmpDir(.{}); + defer tmp.cleanup(); + var arena: std.heap.ArenaAllocator = .init(t.allocator); + defer arena.deinit(); + const a = arena.allocator(); + const bytes = "{\"text_config\":{\"num_hidden_layers\":4,\"layer_types\":[\"linear_attention\",\"linear_attention\",\"linear_attention\",\"full_attention\"],\"full_attention_interval\":2},\"quantization\":{\"bits\":4,\"group_size\":64,\"mode\":\"affine\"}}"; + try tmp.dir.writeFile(t.io, .{ .sub_path = "config.json", .data = bytes }); + const dir = try tmp.dir.realPathFileAlloc(t.io, ".", a); + const why = try slideWidths(a, t.io, dir, living.families.qwen3_5); + try t.expect(why != null); + try t.expect(std.mem.indexOf(u8, why.?, "text_config.layer_types") != null); + try t.expect(std.mem.indexOf(u8, why.?, "text_config.full_attention_interval") != null); +} diff --git a/zig/src/native/qwen27_disk.zig b/zig/src/native/qwen27_disk.zig index 62d6c909700..3923609d543 100644 --- a/zig/src/native/qwen27_disk.zig +++ b/zig/src/native/qwen27_disk.zig @@ -133,6 +133,7 @@ pub fn attach(h: *Host, io: std.Io, a: Allocator, o: Learn) !void { const store = &(h.cache orelse return std.log.warn("Qwen3.8-27B: --learn-conversations needs the prompt cache, which --prompt-cache-gib 0 turned off", .{})); const id = try identity(h, io, a, o.dir, o.drafter); const r = try rows.attach(h.gpa, store, .{ .root = o.root, .identity = id.id, .cap = o.cap, .floor = o.floor, .daily = o.daily, .lookahead = store.rules.lookahead, .planned = store.rules.planned, .spill = o.spill, .slots = o.slots }); + h.disk_rows = r; r.prefill_rate = id.rate; std.log.info("Qwen3.8-27B: conversation states on disk in {s} ({d} states, {d} MiB of {d} MiB)", .{ r.dir, r.states.items.len, r.held() >> 20, o.cap >> 20 }); } diff --git a/zig/src/native/qwen27_lanes.zig b/zig/src/native/qwen27_lanes.zig index d55d4e68019..19ccba244d5 100644 --- a/zig/src/native/qwen27_lanes.zig +++ b/zig/src/native/qwen27_lanes.zig @@ -194,7 +194,9 @@ pub const Metal = struct { } pub fn slotFor(b: *const Metal, s: *const lanes.Stream) !u32 { - return b.slotOf(s) orelse error.UnknownStream; + const slot = b.slotOf(s) orelse return error.UnknownStream; + b.runner.untaught[slot] = s.untaught; + return slot; } fn push(b: *Metal, token: u32) u64 { diff --git a/zig/src/native/qwen27_served.zig b/zig/src/native/qwen27_served.zig index e8f8111df04..74de4aa7071 100644 --- a/zig/src/native/qwen27_served.zig +++ b/zig/src/native/qwen27_served.zig @@ -19,6 +19,7 @@ const images = @import("qwen27_images.zig"); const Allocator = std.mem.Allocator; pub const Options = struct { + slide: ?[]const u8 = null, // The writable checkpoint folder; null keeps the ordinary serving allocation. context: u32, streams: u32, // --parallel: slots at most, fewer when their caches do not fit streams_fixed: bool = false, // --parallel named a number: every slot fits, or the server refuses @@ -49,8 +50,10 @@ pub const Host = struct { cache: ?pc.Store = null, resident: ?Resident = null, warm: mtl.keepalive.Target, + disk_rows: ?*pc.rows.Rows = null, // Owned even after a learned-weight change detaches the cache from disk. disk_stage: ?mtl.Buffer = null, // copies out of private kept states for the disk (qwen27_disk.zig) vision: ?*images.Vision = null, // --vision's tower and image rows + slide: ?*@import("qwen27_slide.zig").Bridge = null, spares: q.snapshot.Spares = .{}, // dropped kept states' buffers, for the next saves pub fn engine(h: *Host) api.Engine { @@ -186,6 +189,10 @@ fn shareRoom(h: *const Host, why: *[]const u8) !u64 { /// Room left beside the weights and an 8 GiB margin. fn room(model: *const q.model.Model) usize { + return rawRoom(model) -| model.learn_reserved; +} + +fn rawRoom(model: *const q.model.Model) usize { const dev = model.device; return q.prompt_memory.room(dev.maxWorkingSet(), dev.allocated(), if (std.c.getenv("TF_QWEN27_WORKING_SET_BYTES")) |v| std.mem.span(v) else null) catch 0; } @@ -338,6 +345,16 @@ pub fn attach(parent: Allocator, io: std.Io, model: *q.model.Model, drafter: ?*q }; var draft_owned = owns_draft; errdefer if (draft_owned) draft_model.?.deinit(); + const reserve_before = model.learn_reserved; + if (o.slide != null) { + if (model.widths_tag != 0) return error.UnsupportedLearningFormat; + model.learn_reserved = try q.train_memory.bytes(model.config, q.gpu_frame.max_rows, model.device.tensorUnits()); + if (room(model) == 0) { + model.learn_reserved = reserve_before; + return error.LearningMemory; + } + } + errdefer model.learn_reserved = reserve_before; const memory = q.prompt_memory; const fit_prompt = memory.Fit{ .config = model.config, .context = capacity + window, .slots = @max(o.streams, 1), .shared = model.device.tensorUnits(), .ring = if (draft_model) |d| @as(usize, d.ring().window) * d.ring().stride else 0, .current_rows = model.frame.capacity, .left = room(model) }; const value = if (std.c.getenv("TF_PROMPT_ROWS")) |v| std.mem.span(v) else null; @@ -360,8 +377,11 @@ pub fn attach(parent: Allocator, io: std.Io, model: *q.model.Model, drafter: ?*q h.cache = null; h.resident = null; h.disk_stage = null; + h.disk_rows = null; h.vision = o.images; // closed with the host; a failed attach leaves it to the caller h.trace = null; + h.slide = null; + h.spares = .{}; h.runner = try q.decode_round.Runner.initReady(gpa, model, slots, capacity + window, 1); errdefer h.runner.deinit(); if (profileEvery()) |every| { @@ -410,9 +430,15 @@ pub fn attach(parent: Allocator, io: std.Io, model: *q.model.Model, drafter: ?*q try enableCache(h, o.cache_gib, o.cache_over_cap, a, why); errdefer if (h.cache) |*store| store.deinit(); if (o.learn) |l| try disk.attach(h, io, a, l); - errdefer if (h.cache) |*store| if (store.disk) |r| r.deinit(); + errdefer if (h.disk_rows) |r| r.deinit(); h.host.keepalive_target = .{ .ctx = &h.warm, .tick = mtl.keepalive.Target.tick }; if (h.trace) |*t| t.enabled = true; // serving rounds count from here: measure() timed whole, unsplit buffers + if (o.slide) |dir| { + h.slide = try @import("qwen27_slide.zig").Bridge.init(h, io, dir); + h.host.learner = h.slide.?.hook(); + h.host.info_.slide_conversations = h.slide.?.conversations(); + } + errdefer if (h.slide) |learner| learner.deinit(); try h.host.start(); std.log.info("Qwen3.8-27B: {d} streams of {d} tokens{s}{s}", .{ slots, capacity, if (h.draft != null) ", DFlash2 drafts for one of them" else "", if (o.images != null) ", images read" else "" }); return h; @@ -442,7 +468,7 @@ fn gibBytes(gib: f64) u64 { fn laterFootprint(h: *const Host) !u64 { const tower: u64 = if (h.back.vision) |v| v.firstUse() else 0; const share = try h.model.shareCacheBytes(); - return std.math.add(u64, try std.math.add(u64, laterBytes(h), tower), share); + return std.math.add(u64, try std.math.add(u64, try std.math.add(u64, laterBytes(h), tower), share), h.model.learn_reserved); } /// The prompt bank may capture marks without splitting; only request starts are guaranteed cold cuts. @@ -453,7 +479,7 @@ pub fn cacheRules(chunk: u32) pc.Rules { /// Prompt reuse in up to 16 GiB of what 70% of RAM leaves once every slot has its memory; CacheOverCap: `why` says why. fn enableCache(h: *Host, gib: ?f64, over: bool, a: Allocator, why: *[]const u8) !void { const later = try laterFootprint(h); - const plan = try cache_fit.budgetBeside(gib, over, room(h.model) -| later, later, a, why, ""); + const plan = try cache_fit.budgetBeside(gib, over, rawRoom(h.model) -| later, later, a, why, ""); if (plan.budget_bytes == 0) return; // a short prompt keeps its history's mark at a chunk end its pass cuts anyway (qwen27_slots.prefill): no extra call h.cache = pc.Store.init(h.gpa, .{ .ptr = h, .vtable = &.{ .bytes = Snaps.bytes, .save = Snaps.save, .restore = Snaps.restore, .drop = Snaps.drop, .charged = Snaps.charged, .spare = Snaps.spare, .trim = Snaps.trim, .reuses = Snaps.reuses, .rows = &disk.image } }, cacheRules(@intCast(h.back.chunk)), plan.budget_bytes); @@ -471,7 +497,8 @@ const holdResident = q.residency.hold; pub fn close(ptr: *anyopaque) void { const h = Host.of(ptr); h.host.stop(); - const rows = if (h.cache) |*store| store.disk else null; + if (h.slide) |learner| learner.deinit(); + const rows = q.learning_epoch.takeDisk(h); if (h.cache) |*store| store.deinit(); // its states leave the set as they go h.spares.deinit(); if (rows) |r| r.deinit(); // after the store: its entries leave the write queue as they go diff --git a/zig/src/native/qwen27_slide.zig b/zig/src/native/qwen27_slide.zig new file mode 100644 index 00000000000..f54e976023f --- /dev/null +++ b/zig/src/native/qwen27_slide.zig @@ -0,0 +1,74 @@ +//! The shared learner on the exclusive lane thread; changed weights also invalidate the native in-place resume. +const std = @import("std"); +const api = @import("engine_api"); +const q = @import("tensorfold").qwen27; +const Shared = @import("slide_adapter.zig").Adapter(q.slide); +const Host = @import("qwen27_served.zig").Host; + +pub const Bridge = struct { + host: *Host, + dir: []u8, + adapter: Shared, + + pub fn init(h: *Host, io: std.Io, dir: []const u8) !*Bridge { + const b = try h.gpa.create(Bridge); + errdefer h.gpa.destroy(b); + const copy = try h.gpa.dupe(u8, dir); + b.* = .{ .host = h, .dir = copy, .adapter = Shared.init(h.gpa, io, q.slide.Model{ .m = h.model, .dir = copy, .follow = h.runner.residency }) }; + return b; + } + pub fn deinit(b: *Bridge) void { + const a = b.host.gpa; + b.adapter.deinit(); + a.free(b.dir); + a.destroy(b); + } + pub fn conversations(b: *const Bridge) bool { + return b.adapter.learner.readsConversations(); + } + pub fn hook(b: *Bridge) api.Learner { + return .{ .ctx = b, .begin = begin, .step = step, .abort = abort }; + } + fn begin(ctx: *anyopaque, request: *const api.LearnRequest, sink: api.LearnSink) !void { + const b: *Bridge = @ptrCast(@alignCast(ctx)); + const h = b.adapter.hook(); + try h.begin(h.ctx, request, sink); + } + fn step(ctx: *anyopaque) api.Learner.Step { + const b: *Bridge = @ptrCast(@alignCast(ctx)); + const h = b.adapter.hook(); + const result = h.step(h.ctx); + if (result.changed) { + // The lane host clears its saved RAM/disk cache. Slot 0 has another route around that store. + q.learning_epoch.changed(b.host.back); + } + return result; + } + fn abort(ctx: *anyopaque) void { + const b: *Bridge = @ptrCast(@alignCast(ctx)); + const h = b.adapter.hook(); + h.abort(h.ctx); + } +}; + +/// Check links before mapping weights or creating a Metal device. +pub fn refused(a: std.mem.Allocator, io: std.Io, dir: []const u8, problem: *[]const u8) !bool { + const path = try std.fs.path.join(a, &.{ dir, "config.json" }); + defer a.free(path); + const text = try std.Io.Dir.cwd().readFileAlloc(io, path, a, .limited(16 << 20)); + defer a.free(text); + const config = try q.config.parse(a, text, null); + if (!q.train_admission.supported(config)) { + problem.* = "--slide on this Metal engine requires the dense Qwen3.8-27B geometry"; + return true; + } + if (try @import("metal_slide.zig").slideWidths(a, io, dir, q.slide.family)) |why| { + problem.* = why; + return true; + } + if (try @import("slide_adapter.zig").refusal(@import("tensorfold").shard_edit, a, io, dir, "`cp -cRL` (an APFS clone that follows links)")) |why| { + problem.* = why; + return true; + } + return false; +} diff --git a/zig/src/native/qwen27_slots.zig b/zig/src/native/qwen27_slots.zig index 1dedd55bcb5..33bd6bc752b 100644 --- a/zig/src/native/qwen27_slots.zig +++ b/zig/src/native/qwen27_slots.zig @@ -57,6 +57,7 @@ pub fn opening(b: *Metal, s: *lanes.Stream, slot: u32) !Fill { s.fill_at.store(@intCast(at), .monotonic); // what the restore kept: 0 when it failed const encoded = if (b.vision) |v| try images.encode(v, b.runner.model.queue, s, slot) else null; if (encoded != null) b.image_fill = s; // the vision rows are this pass's until it closes + b.runner.untaught[slot] = s.untaught; return .{ .slot = slot, .at = at, .from = at, .images = encoded, .checkpoint = resume_rules.cachePoint(slot == 0 and slotResume(b) and plain(s) and s.max_new > 0 and s.reuse.hook != null and b.checkpoint_hook != null, at, b.chunk, ids.len, s.history_len, s.reuse.marks, s.chunks, s.decode_spans), .rewind = rewindPoint(b, s, slot, at) }; } @@ -420,6 +421,8 @@ pub fn promote(b: *Metal) void { }; b.owners[0] = s; b.owners[k] = null; + b.runner.untaught[0] = s.untaught; + b.runner.untaught[k] = false; b.runner.rope[0] = b.runner.rope[k]; b.runner.rope[k] = .{}; clearContext(b, from) catch {}; diff --git a/zig/src/tensorfold.zig b/zig/src/tensorfold.zig index 8515d18557a..1be2f3963f8 100644 --- a/zig/src/tensorfold.zig +++ b/zig/src/tensorfold.zig @@ -145,3 +145,5 @@ pub const hc_pointwise_metal_adapter = @import("core/hc_pointwise_metal_impl.zig pub const hc_pointwise_contract = @import("core/contract/hc_pointwise.zig"); pub const attention_ref = @import("core/attention_ref.zig"); + +pub const dense_pocket = @import("core/dense_pocket.zig"); diff --git a/zig/tests/contract/metal_limits.zig b/zig/tests/contract/metal_limits.zig index 137c00e8d5c..c5859e6662b 100644 --- a/zig/tests/contract/metal_limits.zig +++ b/zig/tests/contract/metal_limits.zig @@ -48,6 +48,15 @@ fn launchOf(a: std.mem.Allocator, device: mtl.Device, d: limits.MetalLaunch) !La const body = try @import("qwen4").family.limits_sources.source(a, d.name); return .{ .decl = d, .function = fun, .here = body, .pre_m5 = body }; } + if (std.mem.startsWith(u8, d.name, "qwen27 learning ")) { + inline for (.{ "gdn_train", "attn_train", "learn_rows", "learn_linear", "pocket" }) |unit| { + if (std.mem.startsWith(u8, d.name, "qwen27 learning " ++ unit ++ " ")) { + const body = @field(tf.qwen27.runtime_sources, unit); + return .{ .decl = d, .function = fun, .here = body, .pre_m5 = body }; + } + } + return error.NoLearningSource; + } if (std.mem.startsWith(u8, d.name, "hc-pointwise ")) { const body = try @import("metal_hc_pointwise.zig").text(a); return .{ .decl = d, .function = fun, .here = body, .pre_m5 = body }; diff --git a/zig/tests/contract/metal_main.zig b/zig/tests/contract/metal_main.zig index 1aa25764a81..a5edbd41123 100644 --- a/zig/tests/contract/metal_main.zig +++ b/zig/tests/contract/metal_main.zig @@ -125,6 +125,10 @@ pub fn main(init: std.process.Init) !u8 { return 0; } if (o.gates) try @import("metal_delta_slots.zig").run(a, device, queue, o.only, o.seed); + if (o.gates and (o.only == null or std.mem.indexOf(u8, "qwen27 learning", o.only.?) != null)) { + const path = try std.fmt.allocPrint(a, "zig-out/qwen27-learning-contract-{d}", .{std.Io.Clock.awake.now(init.io).toNanoseconds()}); + try @import("qwen27_learning").run(a, init.io, path); + } try gemma.requireComplete(gemma.entries); var gemma_list: std.ArrayList(*gemma.Probe) = .empty; defer { @@ -463,6 +467,7 @@ pub fn main(init: std.process.Init) !u8 { var t: g.Tally = .{}; const t0 = std.Io.Clock.awake.now(init.io); if (o.gates) { + try @import("qwen27_learning_checks").run(@import("rig.zig"), a, device, queue, o.only, &t); try g.runAll(a, kernels.items, o.seed, &t); for (flash_list[0..flash_made]) |*probe| try probe.rowCountInvariant(); try dsv41_suites.gates(init.io, o.seed, &t); diff --git a/zig/tests/qwen27/learning.zig b/zig/tests/qwen27/learning.zig new file mode 100644 index 00000000000..af84bdda959 --- /dev/null +++ b/zig/tests/qwen27/learning.zig @@ -0,0 +1,136 @@ +//! Synthetic serving/trainer identity, packed-sequence and nudged-gradient smoke checks. No checkpoint downloads. +const std = @import("std"); +const tf = @import("tensorfold"); +const mtl = @import("metal"); +const q = tf.qwen27; +const identity = @import("learning_identity.zig"); +const graph = @import("synthetic_graph.zig"); + +fn write(a: std.mem.Allocator, io: std.Io, dir: []const u8, m: *q.model.Model) !void { + try std.Io.Dir.cwd().createDirPath(io, dir); + var folder = try std.Io.Dir.cwd().openDir(io, dir, .{}); + defer folder.close(io); + var tensors: std.ArrayList(tf.shard_edit.New) = .empty; + defer tensors.deinit(a); + var index: std.ArrayList(u8) = .empty; + defer index.deinit(a); + try index.appendSlice(a, "{\"weight_map\":{"); + var it = m.checkpoint.tensors.iterator(); + while (it.next()) |entry| { + const t = entry.value_ptr.*; + try tensors.append(a, .{ .name = entry.key_ptr.*, .dtype = t.dtype, .shape = try a.dupe(usize, t.shape[0..t.rank]), .bytes = t.buffer.contents()[t.offset..][0..t.bytes] }); + try index.print(a, "{s}\"{s}\":\"model.safetensors\"", .{ if (tensors.items.len == 1) "" else ",", entry.key_ptr.* }); + } + try index.appendSlice(a, "}}"); + try tf.shard_edit.create(a, try std.fs.path.join(a, &.{ dir, "model.safetensors" }), &.{.{ "format", "mlx" }}, tensors.items); + try folder.writeFile(io, .{ .sub_path = "model.safetensors.index.json", .data = index.items }); +} +pub fn main(init: std.process.Init) !void { + var arena = std.heap.ArenaAllocator.init(init.gpa); + defer arena.deinit(); + const a = arena.allocator(); + const args = try init.minimal.args.toSlice(a); + if (args.len != 2) return error.Usage; + try run(a, init.io, args[1]); +} + +/// Called by the Metal contract runner as well as the bounded standalone gate. +pub fn run(a: std.mem.Allocator, io: std.Io, dir: []const u8) !void { + const pool = mtl.objc.Pool.push(); + defer pool.pop(); + const m = try graph.create(a); + defer m.deinit(); + try write(a, io, dir, m); + const t = try q.train.Trainer.init(a, io, m, dir, null); + defer t.deinit(); + var runner = try q.decode_round.Runner.init(a, m, 1, 32); + defer runner.deinit(); + const ids = [_]u32{ 7, 13, 29, 31 }; + const seq: q.train.Seq = .{ .ids = &ids, .start = 2, .decide = 1 }; + const turn = q.train.Turn{ .decide = 1, .whole = true }; + var results: [2]q.train.Result = undefined; + var baseline: [3][96]u16 = undefined; + for (0..3) |row| { + try t.forwardRow(&runner, 0, row, ids[row..][0..1], true); + @memcpy(&baseline[row], q.train.slice(u16, m.frame.get(.logits), 96)); + } + try t.pass(&.{seq}, .loss, turn, &results); + for (seq.start - 1..3) |row| if (!std.mem.eql(u16, &baseline[row], q.train.slice(u16, @import("tensorfold").qwen27.projection.Ref{ .buffer = t.logits.buffer, .offset = row * 96 * 2 }, 96))) return error.TrainerForwardDiffers; + const solo = results[0].loss; + const other_ids = [_]u32{ 17, 19, 31, 37, 41 }; + const other: q.train.Seq = .{ .ids = &other_ids, .start = 3, .decide = 1 }; + try t.pass(&.{other}, .loss, turn, &results); + const other_solo = results[0].loss; + try t.pass(&.{ seq, other }, .loss, turn, &results); + if (results[0].loss != solo or results[1].loss != other_solo) return error.PackedLossDiffers; + const nudged: q.train.Seq = .{ .ids = &ids, .start = 2, .decide = 1, .nudge = .{ .layers = .{ 1, 2, 4 }, .rows = .{ 0, 1, 2 } } }; + try t.pass(&.{nudged}, .target, turn, &results); + var norm: f64 = 0; + for (0..3) |i| for (t.pushAt(0, i, i)) |value| { + if (!std.math.isFinite(value)) return error.NonFiniteLearningGradient; + norm += @as(f64, value) * value; + }; + if (norm == 0) return error.MissingLearningGradient; + const fingerprint = std.crypto.hash.sha2.Sha256.hash; + var solo_gradients: [3][32]u8 = undefined; + for (0..3) |i| fingerprint(std.mem.sliceAsBytes(t.pushAt(0, i, i)), &solo_gradients[i], .{}); + try t.pass(&.{ nudged, other }, .target, turn, &results); + for (0..3) |i| { + var packed_hash: [32]u8 = undefined; + fingerprint(std.mem.sliceAsBytes(t.pushAt(0, i, i)), &packed_hash, .{}); + if (!std.mem.eql(u8, &solo_gradients[i], &packed_hash)) return error.PackedGradientDiffers; + } + var first: [32]u8 = undefined; + fingerprint(std.mem.sliceAsBytes(t.pushAt(0, 0, 0)), &first, .{}); + for (0..4) |_| { + try t.pass(&.{nudged}, .target, turn, &results); + var next: [32]u8 = undefined; + fingerprint(std.mem.sliceAsBytes(t.pushAt(0, 0, 0)), &next, .{}); + if (!std.mem.eql(u8, &first, &next)) return error.LearningRepeatDiffers; + } + // A no-nudge target still keeps every residual read by the lesson's pocket validation. + try t.pass(&.{seq}, .target, turn, &results); + if (std.mem.allEqual(u16, t.residual(1, 0), 0)) return error.MissingLearningResidual; + var same: [1]bool = undefined; + try t.greedy(&.{seq}, &same); + // A scaled open pocket must disappear at scale zero, while an untaught stream must skip every saved neuron. + const neurons = 64; + const n = neurons * m.config.hidden; + const gate = try a.alloc(f32, n); + const up = try a.alloc(f32, n); + const down = try a.alloc(f32, n); + @memset(gate, 0); + @memset(up, 0); + @memset(down, 0); + gate[0] = 4; + up[0] = 1; + for (down[0..m.config.hidden], 0..) |*v, i| v.* = if (i % 2 == 0) 0.5 else -0.5; + try q.slide.Learner.Host.pocketSwiglu(.{ .m = m, .dir = dir }, 2, gate, up, down, 1); + t.from[2] = 0; + var scaled = seq; + scaled.scale = 0; + try t.pass(&.{scaled}, .loss, turn, &results); + if (results[0].loss != solo) return error.ScaledPocketNotZero; + try runner.reset(0); + runner.untaught[0] = true; + for (0..3) |row| { + try t.forwardRow(&runner, 0, row, ids[row..][0..1], true); + if (!std.mem.eql(u16, &baseline[row], q.train.slice(u16, m.frame.get(.logits), 96))) return error.UntaughtPocketDiffers; + } + // Poison skipped prompt-head storage so a stale value can never accidentally satisfy the identity gate. + @memset(q.train.slice(u16, t.logits, (seq.start - 1) * m.config.vocab), 0x7fc1); + // The pocket input backward and the scaled entry run through the production trainer, too. + try t.pass(&.{nudged}, .target, turn, &results); + for (t.pushAt(0, 0, 0)) |value| if (!std.math.isFinite(value)) return error.NonFinitePocketGradient; + // The serving entry and the trainer's scale-one entry must agree with live neurons, too. + runner.untaught[0] = false; + try runner.reset(0); + for (0..3) |row| { + try t.forwardRow(&runner, 0, row, ids[row..][0..1], true); + const kept = q.train.slice(u16, .{ .buffer = t.logits.buffer, .offset = row * 96 * 2 }, 96); + const hidden = q.train.slice(u16, .{ .buffer = t.final_h.buffer, .offset = row * m.config.hidden * 2 }, m.config.hidden); + // The native layer program finishes in frame.hidden after its two residual swaps per block. + try identity.check(row, seq.start, hidden, q.train.slice(u16, m.frame.get(.hidden), m.config.hidden), kept, q.train.slice(u16, m.frame.get(.logits), 96)); + } + std.debug.print("Q27_TRAIN native_logits_equal=true packed_loss_equal=true repeat=5 nonzero_gradient_norm={d:.9} target_residuals=true greedy_checked=true scaled_zero_equal=true untaught_equal=true pocket_backward=true taught_logits_equal=true prompt_hidden_equal=true\n", .{@sqrt(norm)}); +} diff --git a/zig/tests/qwen27/learning_identity.zig b/zig/tests/qwen27/learning_identity.zig new file mode 100644 index 00000000000..95f9fc02d53 --- /dev/null +++ b/zig/tests/qwen27/learning_identity.zig @@ -0,0 +1,19 @@ +//! A trainer stores every final hidden row and only answer logits; both ranges have independent identity checks. +const std = @import("std"); + +pub fn check(row: usize, start: usize, hidden: []const u16, served_hidden: []const u16, logits: []const u16, served_logits: []const u16) !void { + if (!std.mem.eql(u16, hidden, served_hidden)) return error.TaughtTrainerHiddenDiffers; + if (row + 1 >= start and !std.mem.eql(u16, logits, served_logits)) return error.TaughtTrainerForwardDiffers; +} + +test "qwen27 identity: poisoned skipped prompt logits are not outputs; every hidden and answer row is checked" { + const hidden = [_]u16{ 0x3f80, 0x4000 }; + const logits = [_]u16{ 0x4040, 0x4080 }; + const skipped = [_]u16{ 0x7fc1, 0x7fc1 }; + try check(0, 2, &hidden, &hidden, &skipped, &logits); + try check(1, 2, &hidden, &hidden, &logits, &logits); + try std.testing.expectError(error.TaughtTrainerHiddenDiffers, check(0, 2, &skipped, &hidden, &skipped, &logits)); + try std.testing.expectError(error.TaughtTrainerForwardDiffers, check(1, 2, &hidden, &hidden, &skipped, &logits)); + // A one-token prompt has no skipped head row. + try std.testing.expectError(error.TaughtTrainerForwardDiffers, check(0, 1, &hidden, &hidden, &skipped, &logits)); +} diff --git a/zig/tests/qwen27/learning_reference.zig b/zig/tests/qwen27/learning_reference.zig new file mode 100644 index 00000000000..f0a5ce75833 --- /dev/null +++ b/zig/tests/qwen27/learning_reference.zig @@ -0,0 +1,183 @@ +//! Independent binary64 local adjoints on saved BF16/F32 nodes; no trainer or shader helpers are called. +const std = @import("std"); +pub const Which = enum { pocket, affine, prep, scan }; +pub const Buffer = struct { bytes: []u8, want: ?[]f64 = null, input: bool = true }; +pub const Fixture = struct { buffers: []Buffer, params: []u8, groups: [3]usize, threads: usize = 256, bound: f64 }; +pub const Shape = extern struct { u: [4]u32 align(16), f: [4]f32 align(16) }; +pub const Prep = extern struct { pos: i32, heads: i32, kv: i32, dim: i32, half: i32, eps: f32 }; +pub const Scan = extern struct { rows: i32, nk: i32, nv: i32, conv: i32, proj: i32, from: i32 }; + +pub fn floats(a: std.mem.Allocator, n: usize, salt: usize, divisor: f32) ![]f32 { + const out = try a.alloc(f32, n); + for (out, 0..) |*v, i| v.* = @as(f32, @floatFromInt(@as(i32, @intCast((i * 13 + salt * 7) % 29)) - 14)) / divisor; + return out; +} +pub fn input(a: std.mem.Allocator, values: anytype) !Buffer { + return .{ .bytes = try a.dupe(u8, std.mem.sliceAsBytes(values)) }; +} +pub fn bfInput(a: std.mem.Allocator, values: []const f32) !Buffer { + const words = try a.alloc(u16, values.len); + for (words, values) |*to, x| { + const bits: u32 = @bitCast(x); + to.* = @truncate((bits +% 0x7fff +% ((bits >> 16) & 1)) >> 16); + } + return input(a, words); +} +pub fn output(a: std.mem.Allocator, n: usize, initial: f32) !Buffer { + const values = try a.alloc(f32, n); + @memset(values, initial); + const want = try a.alloc(f64, n); + @memset(want, initial); + return .{ .bytes = std.mem.sliceAsBytes(values), .want = want, .input = false }; +} +pub fn scratch(a: std.mem.Allocator, n: usize) !Buffer { + const out = try output(a, n, 0); + return .{ .bytes = out.bytes, .input = false }; +} +pub fn params(a: std.mem.Allocator, value: anytype) ![]u8 { + return a.dupe(u8, std.mem.asBytes(&value)); +} +pub fn scalar(b: Buffer, comptime T: type, i: usize) f64 { + const x = std.mem.bytesAsSlice(T, @as([]align(@alignOf(T)) const u8, @alignCast(b.bytes)))[i]; + if (T == u16) return @as(f32, @bitCast(@as(u32, x) << 16)); + return x; +} + +pub fn make(a: std.mem.Allocator, which: Which) !Fixture { + return switch (which) { + .pocket => pocket(a), + .affine => affine(a), + .prep => prep(a), + .scan => @import("learning_scan_reference.zig").make(a), + }; +} +fn pocket(a: std.mem.Allocator) !Fixture { + const rows = 3; + const d = 65; + const cap = 64; + const neurons = 3; + const b = try a.alloc(Buffer, 4); + b[0] = try bfInput(a, try floats(a, rows * d, 0, 16)); + const weights = try a.alloc(f32, 3 * cap * d); + @memset(weights, 0); + for (0..3) |part| for (0..neurons) |j| for (0..d) |c| { + weights[(part * cap + j) * d + c] = @as(f32, @floatFromInt(@as(i32, @intCast((part * 7 + j * 13 + c * 17) % 23)) - 11)) / 128; + }; + b[1] = try input(a, weights); + b[2] = try input(a, try floats(a, rows * d, 1, 32)); + b[3] = try output(a, rows * d, 0.125); + for (0..rows) |r| for (0..neurons) |j| { + var gate: f64 = 0; + var up: f64 = 0; + var error_dot: f64 = 0; + for (0..d) |c| { + const x = scalar(b[0], u16, r * d + c); + gate += x * weights[j * d + c]; + up += x * weights[(cap + j) * d + c]; + error_dot += scalar(b[2], f32, r * d + c) * weights[(2 * cap + j) * d + c]; + } + const sigmoid = 1 / (1 + @exp(-gate)); + const scale: f64 = if (j >= 1) 0.25 else 1; + const cg = scale * error_dot * up * sigmoid * (1 + gate * (1 - sigmoid)); + const cu = scale * error_dot * gate * sigmoid; + for (0..d) |c| b[3].want.?[r * d + c] += cg * weights[j * d + c] + cu * weights[(cap + j) * d + c]; + }; + return .{ .buffers = b, .params = try params(a, Shape{ .u = .{ 1, d, neurons, cap }, .f = .{ 0.25, 0, 0, 0 } }), .groups = .{ rows, 1, 1 }, .bound = 2e-6 }; +} +fn affine(a: std.mem.Allocator) !Fixture { + const rows = 5; + const n = 17; + const k = 128; + const b = try a.alloc(Buffer, 5); + b[0] = try input(a, try floats(a, rows * n, 2, 1024)); + const words = try a.alloc(u32, n * k / 8); + for (words, 0..) |*word, i| word.* = @as(u32, @intCast(i)) *% 1550719 +% 191; + b[1] = try input(a, words); + const scales = try a.alloc(f32, n * k / 64); + const biases = try a.alloc(f32, scales.len); + for (scales, biases, 0..) |*s, *z, i| { + s.* = @as(f32, @floatFromInt(i % 7 + 1)) / 64; + z.* = @as(f32, @floatFromInt(@as(i32, @intCast(i % 9)) - 4)) / 32; + } + b[2] = try bfInput(a, scales); + b[3] = try bfInput(a, biases); + b[4] = try output(a, rows * k, 0.125); + for (0..rows) |r| for (0..k) |c| for (0..n) |out| { + const code = (words[out * k / 8 + c / 8] >> @as(u5, @intCast(4 * (c % 8)))) & 15; + const group = out * (k / 64) + c / 64; + b[4].want.?[r * k + c] += scalar(b[0], f32, r * n + out) * (scalar(b[2], u16, group) * @as(f64, @floatFromInt(code)) + scalar(b[3], u16, group)); + }; + return .{ .buffers = b, .params = try params(a, Shape{ .u = .{ rows, n, k, 1 }, .f = @splat(0) }), .groups = .{ ((rows + 3) / 4 * k + 255) / 256, 1, 1 }, .bound = 0 }; +} +fn prep(a: std.mem.Allocator) !Fixture { + const rows = 3; + const heads: usize = 2; + const kv: usize = 1; + const dim = 256; + const half = 32; + const b = try a.alloc(Buffer, 9); + b[0] = try bfInput(a, try floats(a, rows * 2 * heads * dim, 3, 16)); + b[1] = try bfInput(a, try floats(a, rows * kv * dim, 4, 16)); + for (2..4) |i| { + const w = try a.alloc(f32, dim); + for (w, 0..) |*x, d| x.* = @as(f32, @floatFromInt((d + i) % 7 + 1)) / 8; + b[i] = try input(a, w); + } + const inv = try a.alloc(f32, half); + for (inv, 0..) |*v, i| v.* = @as(f32, @floatFromInt(i + 1)) / 1024; + b[4] = try input(a, inv); + b[5] = try input(a, try floats(a, rows * heads * dim, 5, 32)); + b[6] = try input(a, try floats(a, rows * kv * dim, 6, 32)); + b[7] = try output(a, rows * 2 * heads * dim, 0.125); + b[8] = try output(a, rows * kv * dim, 0.125); + for (0..rows) |r| for (0..heads + kv) |h| { + const query = h < heads; + const head = if (query) h else h - heads; + const raw = if (query) b[0] else b[1]; + const grad = if (query) b[5] else b[6]; + const weights = if (query) b[2] else b[3]; + const raw_at = if (query) r * 2 * heads * dim + head * 2 * dim else (r * kv + head) * dim; + const grad_at = (r * (if (query) heads else kv) + head) * dim; + var square: f64 = 0; + var dot: f64 = 0; + var weighted: [dim]f64 = undefined; + for (0..dim) |d| { + var upstream = scalar(grad, f32, grad_at + d); + if (d < 2 * half) { + const angle = @as(f64, @floatFromInt(17 + r)) * scalar(b[4], f32, d % half); + const other = if (d < half) d + half else d - half; + upstream = upstream * @cos(angle) + (if (d < half) @as(f64, 1) else -1) * scalar(grad, f32, grad_at + other) * @sin(angle); + } + const x = scalar(raw, u16, raw_at + d); + weighted[d] = scalar(weights, f32, d) * upstream; + square += x * x; + dot += x * weighted[d]; + } + const eps: f32 = 1e-6; + const inv_rms = 1 / @sqrt(square / dim + eps); + const out = if (query) b[7].want.? else b[8].want.?; + for (0..dim) |d| out[raw_at + d] = inv_rms * (weighted[d] - scalar(raw, u16, raw_at + d) * inv_rms * inv_rms * dot / dim); + }; + return .{ .buffers = b, .params = try params(a, Prep{ .pos = 17, .heads = heads, .kv = kv, .dim = dim, .half = half, .eps = 1e-6 }), .groups = .{ heads + kv, rows, 1 }, .bound = 2e-6 }; +} + +test "Qwen27 local adjoints: every fixture has finite reference outputs and a fixed narrow ABI" { + try std.testing.expectEqual(@as(usize, 32), @sizeOf(Shape)); + try std.testing.expectEqual(@as(usize, 24), @sizeOf(Prep)); + try std.testing.expectEqual(@as(usize, 24), @sizeOf(Scan)); + for (std.enums.values(Which)) |which| { + var arena = std.heap.ArenaAllocator.init(std.testing.allocator); + defer arena.deinit(); + const fixture = try make(arena.allocator(), which); + var nonzero: usize = 0; + for (fixture.buffers) |b| if (b.want) |want| for (want) |x| { + try std.testing.expect(std.math.isFinite(x)); + nonzero += @intFromBool(x != 0); + }; + try std.testing.expect(nonzero > 0); + } +} + +test { + _ = @import("learning_reference_fd.zig"); +} diff --git a/zig/tests/qwen27/learning_reference_fd.zig b/zig/tests/qwen27/learning_reference_fd.zig new file mode 100644 index 00000000000..f9d294627e9 --- /dev/null +++ b/zig/tests/qwen27/learning_reference_fd.zig @@ -0,0 +1,133 @@ +//! Independent smooth losses check selected coordinates of the local binary64 adjoints. +const std = @import("std"); +const ref = @import("learning_reference.zig"); +const t = std.testing; +fn value(f: ref.Fixture, slot: usize, i: usize, changed_slot: usize, at: usize, delta: f64) f64 { + const raw = if (slot == 0 or (f.buffers.len == 9 and slot == 1)) ref.scalar(f.buffers[slot], u16, i) else ref.scalar(f.buffers[slot], f32, i); + return raw + if (slot == changed_slot and i == at) delta else @as(f64, 0); +} +fn pocketLoss(f: ref.Fixture, at: usize, delta: f64) f64 { + var loss: f64 = 0; + for (0..3) |r| for (0..3) |j| { + var g: f64 = 0; + var u: f64 = 0; + var e: f64 = 0; + for (0..65) |d| { + const x = value(f, 0, r * 65 + d, 0, at, delta); + g += x * ref.scalar(f.buffers[1], f32, j * 65 + d); + u += x * ref.scalar(f.buffers[1], f32, (64 + j) * 65 + d); + e += ref.scalar(f.buffers[2], f32, r * 65 + d) * ref.scalar(f.buffers[1], f32, (128 + j) * 65 + d); + } + loss += e * u * g / (1 + @exp(-g)) * (if (j >= 1) @as(f64, 0.25) else 1); + }; + return loss; +} +fn prepLoss(f: ref.Fixture, slot: usize, at: usize, delta: f64) f64 { + var loss: f64 = 0; + for (0..3) |r| for (0..3) |h| { + const query = h < 2; + const head = if (query) h else h - 2; + const raw_slot: usize = if (query) 0 else 1; + const raw_at = if (query) r * 1024 + head * 512 else r * 256; + const grad_at = if (query) r * 512 + head * 256 else r * 256; + var norm: f64 = 0; + var y: [256]f64 = undefined; + for (0..256) |d| { + const x = value(f, raw_slot, raw_at + d, slot, at, delta); + norm += x * x; + } + const eps: f32 = 1e-6; + norm = @sqrt(norm / 256 + eps); + for (&y, 0..) |*out, d| out.* = value(f, raw_slot, raw_at + d, slot, at, delta) * ref.scalar(f.buffers[if (query) 2 else 3], f32, d) / norm; + for (0..256) |d| { + var out = y[d]; + if (d < 64) { + const angle = @as(f64, @floatFromInt(17 + r)) * ref.scalar(f.buffers[4], f32, d % 32); + out = y[d] * @cos(angle) + (if (d < 32) @as(f64, -1) else 1) * y[if (d < 32) d + 32 else d - 32] * @sin(angle); + } + loss += out * ref.scalar(f.buffers[if (query) 5 else 6], f32, grad_at + d); + } + }; + return loss; +} +fn scanLoss(a: std.mem.Allocator, f: ref.Fixture, slot: usize, at: usize, delta: f64) !f64 { + const size = 2 * 128 * 128; + const state = try a.alloc(f64, size); + defer a.free(state); + const base = try a.alloc(f64, size); + defer a.free(base); + for (state, base, 0..) |*s, *b, i| { + s.* = ref.scalar(f.buffers[5], f32, i); + b.* = s.*; + } + var loss: f64 = 0; + for (0..5) |r| { + if (r == 4) for (state, base, 0..) |*s, *b, i| { + // Freeze each saved checkpoint's offset at the base point; cuts have a local straight-through adjoint. + const checkpoint = ref.scalar(f.buffers[5], f32, size + i); + s.* += checkpoint - b.*; + b.* = checkpoint; + }; + for (0..2) |h| for (0..128) |v| { + const offset = (h * 128 + v) * 128; + const g = value(f, 3, r * 2 + h, slot, at, delta); + const mix = value(f, 4, r * 2 + h, slot, at, delta); + var prediction: f64 = 0; + var base_prediction: f64 = 0; + for (0..128) |d| { + prediction += state[offset + d] * g * value(f, 2, r * 128 + d, slot, at, delta); + base_prediction += base[offset + d] * ref.scalar(f.buffers[3], f32, r * 2 + h) * ref.scalar(f.buffers[2], f32, r * 128 + d); + } + const error_value = value(f, 0, r * 512 + 256 + h * 128 + v, slot, at, delta) - prediction; + const base_error = ref.scalar(f.buffers[0], u16, r * 512 + 256 + h * 128 + v) - base_prediction; + var y: f64 = 0; + for (0..128) |d| { + state[offset + d] = state[offset + d] * g + value(f, 2, r * 128 + d, slot, at, delta) * mix * error_value; + base[offset + d] = base[offset + d] * ref.scalar(f.buffers[3], f32, r * 2 + h) + ref.scalar(f.buffers[2], f32, r * 128 + d) * ref.scalar(f.buffers[4], f32, r * 2 + h) * base_error; + y += state[offset + d] * value(f, 1, r * 128 + d, slot, at, delta); + } + loss += y * ref.scalar(f.buffers[6], f32, (r * 2 + h) * 128 + v); + }; + } + return loss; +} +fn close(want: f64, got: f64) !void { + try t.expect(std.math.isFinite(got)); + try t.expect(@abs(want - got) <= 1e-8 + 1e-6 * @abs(want)); +} +test "Qwen27 local adjoints: pocket and weighted partial RoPE RMS match independent central slopes" { + var arena = std.heap.ArenaAllocator.init(t.allocator); + defer arena.deinit(); + const a = arena.allocator(); + const p = try ref.make(a, .pocket); + for ([_]usize{ 0, 32, 64, 65, 194 }) |at| for ([_]f64{ 0x1p-12, 0x1p-15, 0x1p-18 }) |step| + try close(p.buffers[3].want.?[at] - 0.125, (pocketLoss(p, at, step) - pocketLoss(p, at, -step)) / (2 * step)); + const f = try ref.make(a, .prep); + for ([_][2]usize{ .{ 0, 0 }, .{ 0, 32 }, .{ 0, 63 }, .{ 0, 64 }, .{ 0, 512 }, .{ 0, 2048 }, .{ 1, 0 }, .{ 1, 32 }, .{ 1, 255 }, .{ 1, 512 } }) |probe| for ([_]f64{ 0x1p-12, 0x1p-15, 0x1p-18 }) |step| + try close(f.buffers[if (probe[0] == 0) 7 else 8].want.?[probe[1]], (prepLoss(f, probe[0], probe[1], step) - prepLoss(f, probe[0], probe[1], -step)) / (2 * step)); +} +test "Qwen27 local adjoints: scan Q K V decay and mixing cross the four-row checkpoint in central slopes" { + var arena = std.heap.ArenaAllocator.init(t.allocator); + defer arena.deinit(); + const a = arena.allocator(); + const f = try ref.make(a, .scan); + for ([_]usize{ 0, 4 }) |row| for (0..5) |slot| { + const at = switch (slot) { + 0 => row * 512 + 256, + 1, 2 => row * 128, + else => row * 2, + }; + var analytic: f64 = 0; + if (slot == 0) { + analytic = f.buffers[10].want.?[at]; + } else { + for (0..4) |part| { + if (slot == 1 or slot == 2) { + for (0..2) |h| analytic += f.buffers[if (slot == 1) 8 else 9].want.?[((row * 2 + h) * 4 + part) * 128]; + } else analytic += f.buffers[if (slot == 3) 11 else 12].want.?[(row * 2) * 4 + part]; + } + } + const step = 0x1p-15; + try close(analytic, (try scanLoss(a, f, slot, at, step) - try scanLoss(a, f, slot, at, -step)) / (2 * step)); + }; +} diff --git a/zig/tests/qwen27/learning_scan_reference.zig b/zig/tests/qwen27/learning_scan_reference.zig new file mode 100644 index 00000000000..1cee597fa31 --- /dev/null +++ b/zig/tests/qwen27/learning_scan_reference.zig @@ -0,0 +1,84 @@ +//! Dense binary64 delta-rule reverse pass, independent of split warps and generated shader bodies. +const std = @import("std"); +const ref = @import("learning_reference.zig"); +pub fn make(a: std.mem.Allocator) !ref.Fixture { + const rows = 5; + const heads = 2; + const dim = 128; + const conv = 2 * dim + heads * dim; + const parts = 4; + const size = heads * dim * dim; + const b = try a.alloc(ref.Buffer, 13); + b[0] = try ref.bfInput(a, try ref.floats(a, rows * conv, 0, 32)); + b[1] = try ref.input(a, try ref.floats(a, rows * dim, 1, 256)); + b[2] = try ref.input(a, try ref.floats(a, rows * dim, 2, 128)); + const decay = try a.alloc(f32, rows * heads); + const beta = try a.alloc(f32, rows * heads); + for (decay, beta, 0..) |*g, *mix, i| { + g.* = @as(f32, @floatFromInt(i % 3 + 5)) / 8; + mix.* = @as(f32, @floatFromInt(i % 3 + 1)) / 8; + } + b[3] = try ref.input(a, decay); + b[4] = try ref.input(a, beta); + const checkpoints = try a.alloc(f32, 2 * size); + const state = try a.alloc(f64, size); + const states = try a.alloc(f64, rows * size); + const errors = try a.alloc(f64, rows * heads * dim); + for (state, 0..) |*v, i| v.* = @as(f64, @floatFromInt(@as(i32, @intCast(i % 19)) - 9)) / 1024; + for (0..rows) |r| { + if (r % 4 == 0) for (state, 0..) |*v, i| { + checkpoints[(r / 4) * size + i] = @floatCast(v.*); + // The independent tape consumes the same saved F32 checkpoint at each four-row boundary. + v.* = checkpoints[(r / 4) * size + i]; + }; + @memcpy(states[r * size ..][0..size], state); + for (0..heads) |h| for (0..dim) |v| { + const at = (h * dim + v) * dim; + var prediction: f64 = 0; + for (0..dim) |d| prediction += state[at + d] * decay[r * heads + h] * ref.scalar(b[2], f32, r * dim + d); + const error_value = ref.scalar(b[0], u16, r * conv + 2 * dim + h * dim + v) - prediction; + errors[(r * heads + h) * dim + v] = error_value; + for (0..dim) |d| state[at + d] = state[at + d] * decay[r * heads + h] + ref.scalar(b[2], f32, r * dim + d) * error_value * beta[r * heads + h]; + }; + } + b[5] = try ref.input(a, checkpoints); + b[6] = try ref.input(a, try ref.floats(a, rows * heads * dim, 3, 64)); + b[7] = try ref.scratch(a, heads * parts * 4 * 32 * dim); + b[8] = try ref.output(a, rows * heads * parts * dim, 0); + b[9] = try ref.output(a, rows * heads * parts * dim, 0); + b[10] = try ref.output(a, rows * conv, 0.125); + b[11] = try ref.output(a, rows * heads * parts, 0); + b[12] = try ref.output(a, rows * heads * parts, 0); + const ds = try a.alloc(f64, size); + @memset(ds, 0); + var r: usize = rows; + while (r > 0) { + r -= 1; + for (0..heads) |h| for (0..dim) |v| { + const at = (h * dim + v) * dim; + const group = (r * heads + h) * parts + v / 32; + const prior = states[r * size + at ..][0..dim]; + const g: f64 = decay[r * heads + h]; + const mix: f64 = beta[r * heads + h]; + const err = errors[(r * heads + h) * dim + v]; + const upstream = ref.scalar(b[6], f32, (r * heads + h) * dim + v); + var dd: f64 = 0; + for (0..dim) |d| { + const k = ref.scalar(b[2], f32, r * dim + d); + b[8].want.?[group * dim + d] += upstream * (g * prior[d] + k * mix * err); + ds[at + d] += upstream * ref.scalar(b[1], f32, r * dim + d); + dd += ds[at + d] * k; + } + b[10].want.?[r * conv + 2 * dim + h * dim + v] = mix * dd; + b[12].want.?[group] += dd * err; + for (0..dim) |d| { + const k = ref.scalar(b[2], f32, r * dim + d); + b[9].want.?[group * dim + d] += mix * err * ds[at + d] - mix * dd * g * prior[d]; + const before_decay = ds[at + d] - mix * dd * k; + b[11].want.?[group] += before_decay * prior[d]; + ds[at + d] = g * before_decay; + } + }; + } + return .{ .buffers = b, .params = try ref.params(a, ref.Scan{ .rows = rows, .nk = 1, .nv = heads, .conv = conv, .proj = conv + heads * dim + 2 * heads, .from = 0 }), .groups = .{ heads * parts, 1, 1 }, .bound = 2e-6 }; +} diff --git a/zig/tests/qwen27/pocket.zig b/zig/tests/qwen27/pocket.zig new file mode 100644 index 00000000000..3e2f37bfe23 --- /dev/null +++ b/zig/tests/qwen27/pocket.zig @@ -0,0 +1,158 @@ +//! Model-free CUDA-shard to Metal-pocket check against an independent float64 formula. +const std = @import("std"); +const mtl = @import("metal"); +const core = @import("core"); +const living = @import("living"); +const pk = @import("pocket"); +const cfg = pk.config; +const d = 64; +const own = 128; +const cap = 64; +const n = d * cap; +const bf = core.affine4_host; +const Shards = living.shards.Io(core); + +const Fixture = struct { + gate: []f32, + up: []f32, + down: []f32, + config: cfg.Config, +}; + +fn fixture(a: std.mem.Allocator, io: std.Io, dir: []const u8) !Fixture { + try std.Io.Dir.cwd().createDirPath(io, dir); + var arena = std.heap.ArenaAllocator.init(a); + defer arena.deinit(); + const tmp = arena.allocator(); + var tensors: std.ArrayList(core.shard_edit.New) = .empty; + var index: std.ArrayList(u8) = .empty; + try index.appendSlice(tmp, "{\"weight_map\":{"); + for (0..2) |layer| for ([_][]const u8{ "gate_proj", "up_proj", "down_proj" }, 0..) |proj, p| { + const rows: usize = if (p == 2) d else own; + const cols: usize = if (p == 2) own else d; + for ([_][]const u8{ "weight", "scales", "biases" }, 0..) |leaf, kind| { + const width = if (kind == 0) cols / 8 else cols / 64; + const bytes = try tmp.alloc(u8, rows * width * (if (kind == 0) @as(usize, 4) else 2)); + @memset(bytes, 0); + if (kind == 1) for (0..rows * width) |i| std.mem.writeInt(u16, bytes[i * 2 ..][0..2], bf.bf16of(1), .little); + const name = try std.fmt.allocPrint(tmp, "language_model.model.layers.{d}.mlp.{s}.{s}", .{ layer, proj, leaf }); + try tensors.append(tmp, .{ .name = name, .dtype = if (kind == 0) .u32 else .bf16, .shape = try tmp.dupe(usize, &.{ rows, width }), .bytes = bytes }); + try index.print(tmp, "{s}\"{s}\":\"model.safetensors\"", .{ if (tensors.items.len == 1) "" else ",", name }); + } + }; + try index.appendSlice(tmp, "}}"); + try core.shard_edit.create(a, try std.fs.path.join(tmp, &.{ dir, "model.safetensors" }), &.{.{ "format", "mlx" }}, tensors.items); + var folder = try std.Io.Dir.cwd().openDir(io, dir, .{}); + defer folder.close(io); + try folder.writeFile(io, .{ .sub_path = "model.safetensors.index.json", .data = index.items }); + try folder.writeFile(io, .{ .sub_path = "config.json", .data = + \\{"model_type":"qwen3_5","quantization":{"bits":4,"group_size":64},"text_config":{ + \\"hidden_size":64,"intermediate_size":128,"num_hidden_layers":2,"num_attention_heads":4, + \\"num_key_value_heads":2,"head_dim":16,"vocab_size":97,"linear_num_key_heads":2, + \\"linear_num_value_heads":4,"linear_key_head_dim":16,"linear_value_head_dim":16, + \\"linear_conv_kernel_dim":4,"eos_token_id":2}} + }); + const gate = try a.alloc(f32, n); + errdefer a.free(gate); + const up = try a.alloc(f32, n); + errdefer a.free(up); + const down = try a.alloc(f32, n); + errdefer a.free(down); + @memset(gate, 0); + @memset(up, 0); + @memset(down, 0); + gate[0] = 16; + up[0] = 0.0625; + down[0] = 0.125; + down[1] = -0.125; + var all: living.Layers = .empty; + all.set(0); + all.set(1); + const layout = living.Layout.fromExperts(d, own, 2, all); + _ = try Shards.write(a, io, dir, living.families.qwen3_5, layout, &.{0}, cap, &.{ gate, up }, down); + const text = try folder.readFileAlloc(io, "config.json", tmp, .limited(1 << 20)); + return .{ .gate = gate, .up = up, .down = down, .config = try cfg.parse(a, text, null) }; +} + +fn reference(f: Fixture, x: []const u16, out: u16, col: usize) u16 { + var g: f64 = 0; + var u: f64 = 0; + for (0..d) |k| { + g += @as(f64, bf.f32of(x[k])) * f.gate[k]; + u += @as(f64, bf.f32of(x[k])) * f.up[k]; + } + const activation = (g / (1 + @exp(-g))) * u; + return bf.bf16of(@floatCast(@as(f64, bf.f32of(out)) + activation * f.down[col])); +} + +pub fn main(init: std.process.Init) !void { + const a = init.arena.allocator(); + const io = init.io; + const args = try init.minimal.args.toSlice(a); + if (args.len < 2) return error.NeedFixtureDirectory; + const f = try fixture(a, io, args[1]); + if (f.config.intermediate != own or f.config.pocket != cap) return error.PocketWidthNotSplit; + if (args.len == 3 and std.mem.eql(u8, args[2], "--fixture-only")) { + std.debug.print("Q27_POCKET_FIXTURE saved_by_common_CUDA_writer=true original_width={d} pocket={d}\n", .{ f.config.intermediate, f.config.pocket }); + return; + } + const pool = mtl.objc.Pool.push(); + defer pool.pop(); + const device = try mtl.Device.init(); + defer device.deinit(); + const queue = try device.queue(); + defer queue.deinit(); + var pockets = try pk.Pockets.init(a, device, d, 2); + defer pockets.deinit(); + try pockets.load(io, args[1], f.config); + const read = try a.alloc(f32, 3 * n); + const used = try pockets.read(0, read[0..n], read[n..][0..n], read[2 * n ..]); + if (used != 1 or !std.mem.eql(f32, f.gate, read[0..n]) or !std.mem.eql(f32, f.up, read[n..][0..n]) or !std.mem.eql(f32, f.down, read[2 * n ..])) return error.CudaPocketReadDiffers; + if (pockets.layers[1] != null) return error.EmptyLayerAllocated; + var compared: usize = 0; + var untouched: usize = 0; + for ([_]usize{ 1, 3, 128, 2048 }) |rows| { + const count = rows * d; + const input = try device.buffer((count + 16) * 2, mtl.ResourceOptions.shared | mtl.ResourceOptions.untracked); + defer input.deinit(); + const output = try device.buffer((count + 16) * 2, mtl.ResourceOptions.shared | mtl.ResourceOptions.untracked); + defer output.deinit(); + const x = input.slice(u16, count + 16); + @memset(x, 0); + for (0..rows) |r| x[r * d] = bf.bf16of(([_]f32{ 0, 1, -1, 2 })[r % 4]); + @memset(x[count..], 0x5a3c); + const before = try a.dupe(u16, x); + const initial = try a.alloc(u16, count + 16); + @memset(initial, bf.bf16of(0.25)); + @memset(initial[count..], 0x5a3c); + const y = output.slice(u16, count + 16); + for ([_]bool{ false, true }) |untaught| { + pockets.selected = .{ .all = !untaught }; + var first: ?[]u16 = null; + for (0..5) |_| { + @memcpy(y, initial); + const cb = queue.commandBuffer(); + const enc = cb.compute(.serial); + try pockets.add(enc, 0, .{ .buffer = input }, .{ .buffer = output }, rows); + try pockets.add(enc, 1, .{ .buffer = input }, .{ .buffer = output }, rows); + enc.end(); + cb.commit(); + cb.wait(); + if (cb.failure() != null) return error.PocketGpuFailure; + for (0..rows) |r| for (0..d) |col| { + const expected = if (untaught) initial[r * d + col] else reference(f, x[r * d ..][0..d], initial[r * d + col], col); + if (y[r * d + col] != expected) { + std.debug.print("POCKET_DIFF rows={d} row={d} col={d} got={x} reference={x}\n", .{ rows, r, col, y[r * d + col], expected }); + return error.PocketFloat64Mismatch; + } + if (untaught) untouched += 1 else compared += 1; + }; + if (!std.mem.eql(u16, before, x) or !std.mem.eql(u16, initial[count..], y[count..])) return error.PocketInputOrGuardChanged; + if (first) |prior| { + if (!std.mem.eql(u16, prior, y)) return error.PocketRepeatChanged; + } else first = try a.dupe(u16, y); + } + } + } + std.debug.print("Q27_POCKET compared={d} untaught_equal={d} repeats=5 rows=1,3,128,2048 CUDA_shards_equal=true empty_layer_no_buffer=true\n", .{ compared, untouched }); +} diff --git a/zig/tests/qwen27/untaught.zig b/zig/tests/qwen27/untaught.zig new file mode 100644 index 00000000000..b4dbf74d468 --- /dev/null +++ b/zig/tests/qwen27/untaught.zig @@ -0,0 +1,65 @@ +//! Compare every teacher-forced logit byte on original weights and an untaught stream of a portable taught folder. +const std = @import("std"); +const tf = @import("tensorfold"); +const q = tf.qwen27; +const mtl = @import("metal"); +const Row = q.train.Row; +const Hash = std.crypto.hash.sha2.Sha256; + +fn noShare(_: u64) bool { + return false; +} + +fn hashes(a: std.mem.Allocator, io: std.Io, dir: []const u8, cases: []const []const u32) ![][32]u8 { + const pool = mtl.objc.Pool.push(); + defer pool.pop(); + const model = try q.model.Model.load(a, io, dir, 128, noShare); + defer model.deinit(); + var count: usize = 0; + var capacity: usize = 1; + for (cases) |ids| { + if (ids.len == 0 or ids.len > 8192) return error.BadUntaughtCase; + count += @min(ids.len, 512) + 2; + capacity = @max(capacity, ids.len + 1); + } + var runner = try q.decode_round.Runner.init(a, model, 1, @intCast(capacity)); + defer runner.deinit(); + const out = try a.alloc([32]u8, count); + errdefer a.free(out); + var index: usize = 0; + for (cases) |ids| { + try runner.reset(0); + runner.untaught[0] = true; + for (ids[0..@min(ids.len, 512)], 0..) |id, at| { + var row: Row = .{}; + const round = try row.view(a, id, 0, @intCast(at), runner.capacity, @intCast(model.config.conv_kernel), 1, @intCast(model.config.vocab)); + try runner.advance(&round, .all); + const ref = model.frame.get(.logits); + Hash.hash(ref.buffer.contents()[ref.offset..][0 .. model.config.vocab * 2], &out[index], .{}); + index += 1; + } + for ([_]usize{ 128, model.frame.capacity }) |chunk| { + try runner.reset(0); + runner.untaught[0] = true; + const session = q.session.Session{ .runner = &runner }; + try session.prefill(ids, chunk); + out[index] = try session.fingerprint(); + index += 1; + } + } + return out; +} + +pub fn main(init: std.process.Init) !void { + const a = init.arena.allocator(); + const args = try init.minimal.args.toSlice(a); + if (args.len != 4) return error.NeedOriginalTaughtAndTokenCases; + const bytes = try std.Io.Dir.cwd().readFileAlloc(init.io, args[3], a, .limited(8 << 20)); + var parsed = try std.json.parseFromSlice([]const []const u32, a, bytes, .{}); + defer parsed.deinit(); + if (parsed.value.len == 0) return error.BadUntaughtCase; + const base = try hashes(a, init.io, args[1], parsed.value); + const taught = try hashes(a, init.io, args[2], parsed.value); + if (!std.mem.eql(u8, std.mem.sliceAsBytes(base), std.mem.sliceAsBytes(taught))) return error.UntaughtModelLogitsDiffer; + std.debug.print("Q27_UNTAUGHT digests={d} logits_equal=true prompt_state_equal=true max_teacher_rows=512 models_sequential=true\n", .{base.len}); +}