diff --git a/jang-tools/jang_tools/dsv41/DECODE_DSPARK_METHODS.md b/jang-tools/jang_tools/dsv41/DECODE_DSPARK_METHODS.md new file mode 100644 index 00000000..2c7a3ce7 --- /dev/null +++ b/jang-tools/jang_tools/dsv41/DECODE_DSPARK_METHODS.md @@ -0,0 +1,151 @@ +# DeepSeek-V4.1-Flash — decode & DSpark exact methods + +Canonical, cross-machine blueprint for the validated V4.1 decode/speculative methods. Reference +implementation: this directory (`jang_tools/dsv41/`, jangq). Mirror these verbatim into (a) the vMLX +engine's V4.1 SingleBatchGenerator spec-decode path and (b) vmlx-swift +(`Libraries/MLXLMCommon/SpecDec`). All numbers measured on an M5 Ultra (256 GB) against the +`DeepSeek-V4.1-Flash-1017-JANG-Q2Q3-IMATRIX` bundle. + +## M1 — DSpark speculative decode loop (`dspark.py::DSparkRunner.generate`) + +Output is **greedy by construction**: `emit` is composed only of backbone verify-forward argmaxes, +so the draft changes the *acceptance rate* (the speedup), not the decision rule. It is identical to +single-token AR **except at near-ties**: a W+1-row verify forward (and a chunked prefill) computes +bf16 hidden states that differ in the last bits from a 1-row decode, which can flip a top-2 whose +margin is below ~0.05. Measured (256 tokens, fp32 logits): structured identical; code / code2 / +prose first diverge at AR margins 0.0056 / 0.0045 / 0.040. With bf16 logits the top-2 tied exactly +every ~50-100 tokens, so the head now produces fp32 logits as the reference does. + +State: `c` = frontier (last position whose hidden is committed to the draft windows); `pending` = +backbone logits predicting position `c+1`. Per step: + +1. `p0 = argmax(pending)` — backbone truth for `c+1` (free). +2. `draft_ids, conf = draft(p0, c)` → `[p0@c+1, d1@c+2, …, dW@c+1+W]`. + **CRITICAL off-by-one:** seed the draft with the backbone's already-predicted `p0` (position + `c+1`) and draft `c+2` onward, with `main_hidden` taken at position `c`. Seeding the committed + token at `c` (drafting `c+1`) gives ~35 % accept + divergence. +3. `feed = [p0, d1..dW]` (W+1 tokens at `c+1..c+1+W`); `ck = checkpoint()` (O(1) ref snapshot). +4. `vlog, vmh = forward(feed, all_logits=True, return_hidden=True)` — **one** backbone forward. + `vlog` has W+1 rows; `vlog[j]` predicts position `c+2+j`, so `truth[j] = argmax(vlog[j])`, and the + bonus `truth[W]` exists. +5. Accept: `k` = longest prefix where `draft_ids[1+j] == truth[j]` (`j = 0..W-1`). +6. **NO-REFEED FAST PATH — `k == W` (~2× on high-accept content):** the verify forward already wrote + exactly-correct *causal* KV for every accepted position (no rejected tail to undo), so **do not + restore+refeed**. Keep the verify cache: `seed_windows(vmh, c+1..c+1+W)`; `c += W+1`; + `pending = vlog[W]`; `emit = [p0,d1..dW]`. `truth[W]` becomes the next step's `p0`. → **1 forward/step.** +7. **PARTIAL ACCEPT — `0 < k < W` (in-place commit, 1 forward/step):** the verify forward ran with + `capture_verify=True`, so every layer holds references to its per-token cache inputs (post-RoPE + window KV; the compressor's `(kv, score)` projections, or the normed latent at ratio 1). + `emit = [p0, d1..dk]`; `DSV41.commit_prefix(sess, ck, k+1)` restores the checkpoint and replays only + those k+1 tokens' cache updates (window append; compressor pooling → pending tail + completed + groups → compressed / index pool rows with the same RoPE positions; history + position); + `seed_windows(vmh[:k+1], …)`; `c += k+1`; `pending = vlog[k]`, so `truth[k]` is the next p0. + **`k == 0`** keeps the old path: `emit = [p0, truth[0]]`, `restore(ck)`, `forward(emit)` (2 forwards, + but cheaper per token than a 1-token step). The refeed path for partial accepts (and its A/B switch) is + removed: it ran a second forward over the kept tokens every step. Measured (256 tokens, chat prompts): code 44.9 → 57.5 tok/s, code2 + 41.3 → 48.7, Rust 50.9 → 59.1, prose unchanged. `tests/test_commit_prefix.py` proves the replay exact + (`commit_prefix(W+1)` == the capture forward's own state, bit for bit). + +Why it works: a 6-row verify forward ≈ 62 ms ≈ 2× a 1-row decode (32 ms) — the backbone forward +scales with rows — so eliminating the second (commit) forward ≈ 2× per step, on full and partial accepts alike. + +**Measured (n=80, adaptive, WITH fast path):** code **1.88× / 55.7 t/s**, structured **2.00× / 57.1**, +low_accept **1.93× / 50.1**, prose 1.04× / 31.5. MIN 1.04× (never-below-AR PASS). Output +identical to greedy on code (59/59) and structured (29/29) over those short runs (see the near-tie note in M1). = parity with antirez `ds4.c` +56.8 t/s serial. + +## M2 — Adaptive never-below-AR (`DSparkRunner(adaptive=True)`) + +- `accept_ema = 0.7*ema + 0.3*(k/W)` each step; draft width `W = clamp(round(self.width * ema), 1, + self.width)` — depth is **acceptance-governed**, shrinking as acceptance falls AND growing back as + it recovers, always within the draft head's physical size `bs` (a capacity bound, not a policy depth). +- **Wall-clock governor (replaces the zero-accept streak trigger, 2026-10-25 audit).** Acceptance + alone cannot keep speculation at or above AR speed: a step that accepts 1 of 5 drafts resets any + zero-accept streak yet still pays draft + verify + commit forwards. `_Governor` keeps an EMA of + seconds per emitted token for speculative steps and for AR steps (step start to next step start, + every sync included) and speculates only while that is cheaper than AR. AR mode issues a + speculative probe every `probe_every = 16` AR tokens (a probe replaces the stale estimate, so one + good probe switches back); spec mode re-measures AR every `ar_probe_every = 64` steps (AR cost + grows with context). Neither mode is terminal. Synthetic-timing test: + `jang-tools/tests/dsv41_dspark_governor_test.py` (low acceptance stays within a few % of AR, + high acceptance beats it, acceptance returning mid-stream recovers within one probe period). +- **Verified (`tests/verify_dspark_adaptive.py`):** output matches plain greedy (up to near-ties, M1) + AR, and on a low-accept→easy prompt drafting re-engages (accepted > 0), proving recovery. +- Swift parity: the vmlx-swift port should mirror this recoverable mode (no permanent latch). + +## M3 — Where single-stream AR decode time goes (it was not at the floor) + +- 10.6 GB read/token; stock decode 29–31 t/s = **~330 GB/s of ~800 peak**. The earlier reading + ("MLX qmv is ~50 % bandwidth-efficient, so AR is at the floor and MTP is the only lever") was wrong: + the gap was dispatch count and host/GPU serialization, not the GEMVs. M5 below moves AR decode + 29.0 → 39.2 tok/s (2k context) and 26.0 → 34.3 (100k), token-identical. +- Still true: `mx.compile` does not merge independent GEMVs; `gather_qmm` is slower than qmv at + M=1; `lane_qmm` (TensorFold) is 11 % slower at M=1; the MLA decode-attention kernel alone (M4) is a + wash. Each is one dispatch out of ~150 per layer; only removing most of them pays. +- MTP (M1) still multiplies whatever AR is: a wide verify costs about one forward. +- Prefill: the 865 pp/s figure was measured on repetitive text, where the Engram rows stay + page-cache warm. On unique text cold prefill is bound by Engram row reads; see + `RUNTIME_SERVING.md`. + +## M4 — Removed: standalone decode attention kernel, MoE expert dedup + +Both were measured and deleted so nothing dead stays in the runtime: +- `metal_decode_attn.py` (port of the engine's `glm5_mla_decode_attn`: 64 heads x rank-512 latent, rows + read in place by index, fp32 accumulation, sink in the combine pass). Equivalent (cos 0.999999) but a + wall-clock wash (31.08 vs 31.42 tok/s): attention is one of ~150 dispatches per layer, and replacing + one dispatch with another does not move a dispatch-bound step. M5 fused the rest instead. +- MoE expert dedup across verify rows (ds4 `moe_dedup_plan`): bit-identical, but slower than M5's fused + MoE at 2/4/8 rows (0.351/0.509/0.794 vs 0.330/0.433/0.668 ms per layer). The fused MoE is already bound + by the distinct experts' bytes (repeated tiles hit the GPU caches); the plan's pair loop only costs + parallelism. + +## M5 — Fused decode / verify kernels (`metal_decode.py`, default ON) + +Four bit-exact changes for forwards of at most 8 rows (decode, DSpark verify); prefill is untouched. +Each kernel copies MLX's accumulation order (quantized GEMV walk, f32 GEMV tiling, row reduction, +RMSNorm), so greedy decode is bit-equal with each flag off or on. + +| change | flag (`=0` disables) | per layer (synthetic, real dims) | +|---|---|---| +| per-layer `mx.async_eval` (<= 16 rows): the GPU runs early layers while later ones are encoded | `VMLX_DSV41_LAYER_ASYNC` | ~-0.14 ms | +| router logits from the bf16 gate weight (MLX f32 GEMV order, no per-call f32 copy); only where MLX uses the same tiling (K < 16 E) | `VMLX_DSV41_ROUTER_GEMV` | 1 row 86 → 68 µs | +| 6 routed + shared expert in 2 dispatches (mlx-serve `MOE_GU`/`MOE_DN`) instead of ~25 | `VMLX_DSV41_FUSED_MOE` | 1 row 0.279 → 0.226 ms | +| hyper-connection collapse + mixes + Sinkhorn split + expand in 3 dispatches per sublayer instead of ~14; self-checks once against the stock path | `VMLX_DSV41_FUSED_HC` | 1 row 0.183 → 0.137 ms | + +Real model (M5 Ultra, AR greedy, all four on vs off): 2k context 29.0–29.3 → 39.1–39.2 tok/s, 256 greedy +tokens identical; 100k context 26.0–26.3 → 34.3 tok/s, 64 tokens identical. Verify rows (2–8) now each +compute what a 1-row decode of that token computes, so verify is closer to sequential decode than the +stock batched path (tiny model: max logit gap 1.61 → 0.35); it is still not bit-identical to it. + +Note: MLX runs f32 matmuls as TF32 on M5 by default (`MLX_ENABLE_TF32=1`); the hyper-connection einsum +carries ~4e-4 relative error from it. The fused HC kernel reproduces that rounding to stay bit-equal. + +Tests: `tests/dsv41_decode_fusion_test.py` (op-level bit-equality, greedy identity on random-weight +models from `dsv41/tests/synth.py`); benchmark harness `dsv41/tests/bench_decode.py`. + +## Engine (vmlx-py) wiring status — DONE (vmlx `bf1ce697`) + +V4.1 DSpark speculative decode is wired into the engine serving path and verified live: +- **Draft load** (`loaders/load_jangtq_dsv41.py`): `_maybe_load_dsv41_dspark` calls + `jang_tools.dsv41.dspark.load_dspark(runtime.args, runtime.model.embed, runtime.model.head)` and + attaches `model._dspark`. Default ON for bundles that ship `dspark/`; `VMLX_DSV41_DSPARK=0` disables. +- **Generator** (`utils/dsv41_dspark_generator.py::DSV41DSparkGenerator`): subclasses + `SingleBatchGenerator`; overrides `_start_request`/`_yield_current_and_schedule_next` to drive + `DSparkRunner.stream()` on `model.runtime` (its own runtime `Session` + checkpoint/restore + the + no-refeed fast path), yielding one committed token per scheduler step and reusing the inherited + finish-reason/Response/stop machinery. Greedy text only: requests with images still to prefill, a + non-greedy sampler, logits processors or logprobs take the inherited AR path. A VL prefix-cache hit + that covers every image leaves a text-only tail, which DSpark serves. +- **Selection** (`scheduler.py::_create_batch_generator`): a branch before the SBG fallback returns + `DSV41DSparkGenerator` iff `model._dspark` is attached — so the default AR path is never affected. +- **Verified live** (`vmlx serve`, warmed, thinking-off code request): coherent output, `finish=stop`, + **decode-only ~65.9 tok/s vs AR ~31** (2x+); generator selection confirmed in logs; output + greedy by construction (identical except at near-ties, M1). +- Note: the engine's older `vmlx_engine/dspark/` (drafter/generate/session) is Qwen3/MiniCPM DSpark, + unrelated to V4.1. Future: the engine's `DeepseekV41Cache` exposes `trim`, so a later version can do + M1-step-7 no-refeed for *partial* accept too (the standalone runtime skips it). + +### vmlx-swift mirror (Libraries/MLXLMCommon/SpecDec) +Same shape: load the bundle `dspark/` draft, keep a draft-windows + backbone `Session` per sequence, +and in the decode step run M1 (draft → verify forward → accept → fast-path|commit) + M2 (adaptive +width + AR latch, **plus** the re-entry hysteresis the Python reference lacks). diff --git a/jang-tools/jang_tools/dsv41/RUNTIME_SERVING.md b/jang-tools/jang_tools/dsv41/RUNTIME_SERVING.md new file mode 100644 index 00000000..57f191cf --- /dev/null +++ b/jang-tools/jang_tools/dsv41/RUNTIME_SERVING.md @@ -0,0 +1,263 @@ +# DeepSeek-V4.1-Flash — runtime and serving contract (vmlx-py) + +Companion to `DECODE_DSPARK_METHODS.md` (decode and DSpark methods). This page covers the +pieces between the runtime and the vMLX engine: residency, prefill and Engram I/O, prefix +caching, multimodal, and how to measure all of it. Measured numbers come from an M5 Ultra +(256 GB) serving the `DeepSeek-V4.1-Flash-1017-JANG-Q2Q3-IMATRIX` bundle. + +## Speed ledger: why it was slow, and what each piece does + +Every row was measured on the real model (M5 Ultra 256 GB) and is exact or bounded as noted. Read this first +before touching a hot path: each fix removes one specific cause, and reverting any one of them brings that +cause back. Details are in the linked sections. + +**Prefill** (unique-text cold prompts; the first version ran 68 pp/s at 1k tokens): + +| was slow because | fix (where) | measured | +|---|---|---| +| Engram rows (24 random 256-byte reads per position per Engram layer, ~98 GB tables) were gathered by one thread: one page fault in flight | 16 concurrent memmap gathers with `MADV_RANDOM` (`engram.DiskEngramTable._gather`); `np.take` releases the GIL so graph building continues | 8–11k → 110–146k cold rows/s; 1k prefill 68 → 598 pp/s | +| every Engram read waited before any compute | layer 1's rows first, layer 14's rows resolved lazily after `mx.async_eval` of layers 0–13 (`DSV41._engram_rows(lazy=True)`) | reads overlap compute (bit-identical) | +| the next chunk's reads started only when it ran | `engram_lookahead`: the next chunk's hashes and reads start while this one computes (engine passes it) | 4k 459 → 756 pp/s with the above | +| (rule) each forward streams the routed experts once, ~0.14 s at prefill widths | one forward per chunk; never split a chunk to hide I/O | — | +| the engine capped MLX's allocator cache at 4 GB, so every 2048-token chunk freed and re-created its Metal buffers | 16 GB per-family floor (vMLX `mlx_memory.model_cache_limit_floor_bytes`) | 21k 475 → 769 pp/s | +| with the 8.3 GB draft resident, 2048-token chunks crossed Metal's recommended working set and the GPU slowed ~30% | 1024-token chunks while the draft is resident (`DSV41DSparkGenerator`) | 545 → 708 pp/s | +| `wo_a` (block-diagonal over 8 groups) ran token-major: one 1-row product per token per group, a third of each layer | group-major for prefill, one matmul per group (`Attention.__call__`) | 18.6 → 2.1 ms per layer; 708 → 909 pp/s | +| a pool shared by several layers was dequantized once per consumer | `Shared.view` memoizes the dequantized pool for one forward | one dequant per pool per forward | +| index scores materialized `[C, heads, T]` and reduced it | fused `sum_h w * relu(q . k)` kernel (vMLX `dsa_pool_index_scores`) | 100k keys: 164 → 97 ms per index layer | +| MLX's GPU `argpartition` sorts the whole row | block top-k for prefill rows >= 65536 keys (`topk_indices`), exact values | 2.4x at 100k, 16x at 1M | +| the fused scorer ran on simdgroup fp32 (~27 TFLOPS ceiling) | same kernel on the M5 matrix units with bf16 operands (vMLX `dsa_index_scores_mpp`) | 4.3x; 100k avg 831 → 884 pp/s | +| layers 21–39 computed every prompt row, though only the last rows reach the prompt end through their 128-token windows | prompt-suffix pruning, `1 + (40 - i) * 127` trailing rows per layer (`Model.prune_rows`), exact at the prompt end | 32k 938 → 1641, 100k 875 → 1584 pp/s | + +**Decode** (AR started at 29–31 tok/s; DSpark at 26.8 in the first live build): + +| was slow because | fix (where) | measured | +|---|---|---| +| bf16 logits tied every 50–100 tokens, so batched verify and 1-row decode broke ties differently and DSpark drifted | fp32 LM-head input, as the reference (`Model.__call__`) | correctness (enables the rows below) | +| each DSpark step ran a verify forward and then a second forward to commit the accepted tokens | full accepts keep the verify's state; partial accepts replay only the kept tokens' cache updates (`DSV41.commit_prefix`) | code 44.9 → 57.5 tok/s | +| speculation could run slower than AR on low-acceptance text | wall-clock governor: speculate only while faster than a measured AR step, re-measured as context grows (`dspark._Governor`) | never below AR | +| decode/verify attention dequantized the whole 4-bit pool every step (~0.5–1 GB per layer per token at 1M) | gather only the selected rows from the 4-bit pool (`append_compressed_rows(gather=True)`) | bit-identical; flat in context | +| a decode step was ~150 dispatches per layer, built for all 40 layers before the GPU started | per-layer `mx.async_eval`, bf16 router GEMV, 2-dispatch MoE, fused hyper-connection stage (`metal_decode.py`, M5 in DECODE_DSPARK_METHODS) | AR 29.0 → 39.2 tok/s (2k), 26.0 → 34.3 (100k); DSpark code 65.7 → 90.2 | + +**Memory**: compressed-KV and index pools are stored 4-bit (`QuantGrowBuffer`, the reference's FP4 footprint) and +the window keeps 128 rows: 905 MiB resident at 1M tokens (vs ~3.3 KB/token before). + +Measured and removed (no gain): standalone decode attention kernel, MoE expert dedup across verify rows +(DECODE_DSPARK_METHODS M4), 64-lane `os.pread` Engram reads, a scalar fused prefill sparse-attention kernel +(14.4 vs 13.7 ms for the gather path at 2048 queries), bf16 gather in prefill attention (no gain at 256k). + +## Components + +| piece | file | +|---|---| +| runtime (backbone, caches, Engram, VL splice) | `jang_tools/dsv41/model.py` (`DSV41`, `Session`) | +| Engram hashing + on-disk tables | `jang_tools/dsv41/engram.py` (`NgramHasher`, `DiskEngramTable`) | +| DSpark 3-stage MTP draft + adaptive loop | `jang_tools/dsv41/dspark.py` (`DSparkRunner`) | +| vision tower | `jang_tools/dsv41/vision.py` | +| engine model wrapper + per-layer cache | `jang_tools/dsv4_1/mlx_model.py` (`Model`, `DeepseekV41Cache`, `_SeqState`) | +| engine loader / generator / scheduler | vMLX `vmlx_engine/loaders/load_jangtq_dsv41.py`, `utils/dsv41_dspark_generator.py`, `utils/single_batch_generator.py`, `scheduler.py` | + +## Residency + +- Backbone weights (main bundle dir, ~197 GB) are loaded into owned, wired memory. No mmap + compute paths, no streaming, no dequantized copies. +- The two Engram tables (`engram/`, ~98 GB each, layers 1 and 14) are the only weights left + on SSD. They are read in place from their safetensors shards; the OS page cache keeps hot + rows (not wired, not counted as owned memory). +- Expected footprint after load: ~197 GB phys_footprint. If a bundle's `engram/` is missing, + loading fails (`open_engram_tables` raises) instead of running without Engram. + +## Prefill and Engram I/O + +Each position reads `(max_ngram_size - 1) * n_heads = 24` random 256-byte rows (plus 8 scale +bytes) per Engram layer. On unique text those rows are cold, so prefill is bound by how many +random SSD reads are in flight, not by compute. + +Measured (unique text, 2048-token engine chunks, standalone runtime): + +| tokens | before (1-thread memmap gather) | cold now | warm pages | +|---|---|---|---| +| 1024 | 68 pp/s | 598 | 741 | +| 2048 | — | 713 | 801 | +| 4096 | 459 | 756 | 794 | +| 8192 | 382 | 768 | 784 | +| 16384 | — | 746 | 762 | + +Design, and the rules it encodes: + +1. **Concurrent reads.** `DiskEngramTable._gather` gathers from the memmap on 16 threads + (`np.take` releases the GIL), with `MADV_RANDOM` on the mapping: ~110–146k cold rows/s, + against 8–11k for a single-thread gather. More than ~16 gather threads collapse on VM-map + contention. 64-lane `os.pread` reached ~130k rows/s but held the GIL per row and slowed graph + building, so it was removed. +2. **One forward per chunk.** Every forward streams the routed experts' weights, about 0.14 s + of fixed cost at prefill batch sizes, so splitting a chunk into sub-chunks to hide reads + costs more than it saves. Don't add forwards to overlap I/O. +3. **Per-layer lazy rows.** `_engram_rows(lazy=True)`: layer 1's rows are read up front; + later Engram layers get a callable that `Model.__call__` resolves when it reaches that + layer, after `mx.async_eval` of the layers before it, so those reads overlap GPU work. + Layer reads are chained first-layer-first so the first gets every I/O lane. +4. **Next-chunk lookahead.** `forward(ids, sess, engram_lookahead=next_ids)` starts the next + chunk's hashes and reads while this chunk computes. The record on the session is used + only if the next forward's start position and token ids match exactly; otherwise it is + discarded. The engine's chunked prefill loops pass the next chunk (`_model_call(..., + lookahead=...)`, gated on `model_type == "deepseek_v41"`). Any other caller that prefills + in chunks should pass the lookahead too; an unchunked prefill gets only (3). +5. Output is bit-identical with and without (3) and (4). Chunk boundaries themselves change + bf16 numerics slightly (cosine ~0.999 between single-pass and chunked logits), the same as + the engine's existing chunked prefill. + +The 1k case stays near 600 pp/s cold because layer 1's reads (~0.2 s) come before any compute +and the first chunk has nothing to overlap with. + +### Long-context indexer + +Each of the 8 index layers scores every compressed row for every query (32 heads x 128), so the +indexer is the cost that grows with context. Two changes, both exact up to ties: +- **Fused scores:** prefill (more than 8 rows) uses vMLX's `dsa_pool_index_scores` Metal kernel, + `sum_h w * relu(q . k)` in fp32 in one pass, instead of materializing `[C, heads, T]` and reducing + it (100k keys: 164 -> 97 ms per index layer per 2048-token chunk). Query chunks keep the `[C, T]` + fp32 block near 1 GB. Optional import; `VMLX_DSV41_FUSED_INDEX=0` or no vMLX keeps the bf16 path. + Numerics vs bf16: prefill logits mean cos 0.9962, top-1 agreement 100%. +- **Block top-k (prefill only):** MLX's GPU `argpartition` sorts the whole row. For prefill rows + (more than 8 queries) of 65536+ keys, `topk_indices` picks the 512 blocks of 64 with the largest + maxima (they hold the top-512 values) and partitions only those entries. Identical selected values; + 2.4x faster at 2048 x 100k, 16x at 256 x 1M. Decode keeps the direct partition: for one row it is + cheaper (170k context: 25.1 vs 23.9 tok/s), and decode index scores take the bf16 path where exact + ties are common, so a different pick among tied values would change decode output. +- **Matrix units:** the simdgroup fp32 kernel tops out near 27 TFLOPS (fp16 fragments are no faster: + simdgroup MMA has one rate for half and float). vMLX's `dsa_index_scores_mpp` runs the same fused + function on the M5 matrix units (Metal 4 tensor ops) with bf16 operands at ~115-120 TFLOPS: 4.3x the + fp32 kernel at 2048 x 100k keys. The indexer passes its bf16 tensors (`bf16_operands=True`; falls back + to the fp32 kernel on older vMLX / non-M5 / `VMLX_DSV41_INDEX_BF16=0`). Cold prefill to 100k: average + 831 -> 884 pp/s, 40-50k 913 -> 963, 88-100k 818 -> 910. Numerics vs the fp32 kernel: mean cos 0.9964, + top-1 100%, greedy continuation identical. The per-layer attention input (window + whole pool, concatenated and cast to fp32) also grows +with context and pushes peak active memory to ~214 GiB at 1M, past the resident cliff below; gathering +in bf16 instead is output-identical but measured no faster at 256k. + +### Prompt-suffix pruning + +Layers 21–39 own no cache but their 128-token window: the compressed pool, index keys and candidates +they read all come from layer 20 (the last KV source; the Engram layers are 1 and 14). For a prefill that +ends at `prompt_end`, layer i only needs the trailing `1 + (40 - i) * 127` rows (layer 39: 128, +layer 21: 2414): each window reaches 127 rows back, so a layer's first 127 kept rows see a partial +window and the layer above starts 127 rows later. The logits at `prompt_end - 1` and every layer's +window at `prompt_end` are those of a full prefill (`Model.prune_rows`, ported from ds4 #1272). + +- `DSV41.forward(..., prompt_end=)`; the engine's `SingleBatchGenerator._prefill` passes the end of each + prefill call (the N-1 prompt boundary), `DSparkRunner.prefill` the end of the prompt body. Decode, + DSpark verify (`capture_verify`), `all_logits` and multi-segment forwards never prune. +- A layer that drops rows restarts its window at the kept suffix; a forward entirely before a layer's + kept range still runs its last row there. DSpark `return_hidden` rows are exact for the last 128 + positions (all the draft reads), zero before. +- Prefix-cache snapshots are only valid at `prompt_end`. Every engine snapshot is taken there. +- `VMLX_DSV41_SUFFIX_PRUNE=0` disables. CPU test: `tests/test_suffix_prune.py` (tiny random model, + three pruned layers, chunk sizes 17–256). + +Measured (real model, cold unique text, 2048-token chunks, no draft): 8k 1019 → 1452 pp/s, 32k 938 → +1641, 100k 875 → 1584. Exactness at 8k / 32k: last-token logits cos 0.99996 / 0.99994, same top-5, +24 of 24 greedy tokens identical; window caches bit-identical through layer 27, bf16-level differences +above. + +### Grouped output projection + +`wo_a` is block-diagonal over 8 groups. For prefill (more than `GATHER_MAX_QUERIES` rows) it runs +group-major, one matrix multiply per group; token-major ran one 1-row product per token per group +and took a third of each layer (2048-token chunk: 18.6 → 2.1 ms per layer; cold prefill with the draft +resident 708 → 909 pp/s standalone). Decode and DSpark verify keep the per-row products so each verify +row is computed like a 1-row decode. Numerics: prefill logits vs token-major mean cos 0.9954, top-1 +98.4%, which is inside the model's own bf16 sensitivity (moving chunk boundaries 1024 → 512: mean cos +0.9943, min 0.73). Measured per-layer costs at a 2048-token chunk (layer 21): MoE 21.5 ms, attention core +12.8 ms, `wo_a` 2.1 ms (was 18.6), `wq_b` 2.9 ms, hyper-connection mixes 2.6 ms, `wq_a` 1.7 ms. + +### Serving memory settings that prefill depends on + +The standalone numbers above only hold in `vmlx serve` with two settings, both now defaults: + +1. **Allocator-cache floor.** The engine bounds MLX's allocator cache at 5% of resident, capped + at 4 GB. A 2048-token DSV4.1 chunk needs more scratch than that, so Metal buffers were freed + and re-created inside every chunk. AR serving, 21k-token cold prompt: 4 GB 475 pp/s, 16 GB + 769, MLX default 772. `vmlx_engine/mlx_memory.py` adds a per-family floor (`deepseek_v41` + 16 GB) that raises the computed default only; `VMLX_MLX_CACHE_LIMIT_MB` still overrides + exactly. The cache is cleared after every chunk, so idle residency is unchanged. +2. **Prefill chunk with the DSpark draft resident.** Metal's recommended working set on a + 256 GB machine is 239.1 GB (222.7 GiB, `iogpu.wired_limit_mb=0`). The backbone is 197 GiB + resident, and with the 8.3 GB draft 205.4 GiB. During prefill, active memory peaks at + ~209 GiB; with 2048-token chunks, active plus allocator cache crosses the working-set limit + and the GPU slows ~30%. The slowdown is GPU-side, not I/O: warm pages are equally slow, and + an 8.7 GB dummy MLX allocation without the draft reproduces it (760 → 548–620 pp/s). + Draft resident, 12k-token cold prompt: chunk 2048 545 pp/s, 1536 643, 1024 708, 768 684; + allocator cap 8–24 GB makes no difference at 1024. `DSV41DSparkGenerator` therefore caps + the prefill step at 1024 (`VMLX_DSV41_DSPARK_PREFILL_STEP` overrides). Without the draft, + 2048 stays best. The cliff tracks resident memory, not the allocator cap: with no draft and + 2048-token chunks, +0/2/4/6/8 GB of extra resident memory gives 764/772/773/753/588 pp/s, and with + +8 GB the cap (6–16 GB) changes nothing. Raising `iogpu.wired_limit_mb` is untested. + +## Prefix cache (engine) + +- RAM paged prefix cache plus block-disk L2 (`--use-paged-cache --enable-block-disk-cache`). + Entries are keyed on N-1 prompt tokens: the snapshot is taken at the prompt boundary, + before the last prompt token, which is re-fed on a hit. +- The block-disk directory is namespaced by a fingerprint of the serving configuration and engine + code, so entries written by a different engine build are not reused (a new namespace directory + appears instead). Benchmarks of SSD reuse must restart the same build. +- Per-tool-call persistence: the terminal snapshot is written when a request finishes; + the next request waits for it (`Terminal persistence settled ... persist_ms`, + `Admission waited ... wait_ms` in the server log). Measured: `persist_ms` 7–121 ms, admission + wait 14–116 ms. +- Stored-size target: ~0.9 GB for a 1M-token entry, the same as the resident 4-bit + compressed-KV pools (the resident pools measured 905 MB at 1M). Entries must store the 4-bit + pools as they are, without round-tripping through bf16. + +## Multimodal + +- VL requests run through the DSpark generator subclass of `SingleBatchGenerator`. The + scheduler must detect the generator with `isinstance`, not a class-name comparison, or + images are silently dropped. +- Image spans must be in a single start_pos-0 prefill forward. Image tokens take no part in + n-grams (`engram_mask = ~image_mask`), and image prefills don't use the lookahead path. + +## Measuring + +`tests/serve_acceptance.py` drives a real `vmlx serve` process (one model load per run). It +reports cold prefill, decode tok/s by content type, TTFT, RAM/SSD prefix reuse, per-tool-call +reuse, multiturn recall, multimodal answers, reasoning-parser leaks, and the server process +phys_footprint. Run with `VMLX_DSV41_DSPARK=0` for the AR baseline. Load only one copy of the +model at a time: a second ~200 GB load on a 256 GB machine will be killed. + +Serving results (2026-10-26: prompt-suffix pruning + fused decode kernels (DECODE_DSPARK_METHODS M5) on top of +the fp32 head, in-place partial-accept commit, group-major `wo_a` and matrix-unit index scores; DSpark +default on; unique-text cold prompts; M5 Ultra 256 GB; previous round in parentheses): + +| metric | DSpark (default) | AR (`VMLX_DSV41_DSPARK=0`) | +|---|---|---| +| cold prefill 1.6k / 6.5k / 26.5k tokens (1024-token chunks, draft resident) | 845 / 1331 / 1554 pp/s (822 / 955 / 940) | 21k: 769 pp/s (before) | +| decode code / code2 / structured / prose | 90.2 / 62.3 / 111.9 / 38.7 tok/s (60.8–66.0 / 46.1–51.1 / 82.4–86.7 / 29.5–31.0) | AR greedy 39.1–39.2 at 2k, 34.3 at 100k (29.0 / 26.0 before M5) | +| decode after a 170k-token context (AR) | 25.0 tok/s; tokens identical with/without the block top-k | | +| TTFT, short prompt | 0.21–0.46 s | 0.19–0.59 s | +| RAM prefix hit, 3.4k tokens | 3.38 s → 0.36 s | 6.45 s → 0.33 s | +| SSD hit after restart, 3.4k tokens | 3394 cached, 0.34 s (same as a RAM hit) | | +| tool turn 2 | 280/354 cached, 0.75 s | 280/354, 0.87 s | +| per-tool-call persist / next-request wait | 2–118 ms / ≤ 102 ms (22 writes) | | +| multimodal | Red / Apple / Red | same | +| multimodal reuse (925-token image turn, text follow-up) | 924/941 cached, 1.20 s → 0.22 s; other image misses ("Blue") | | +| KV measured at 256k / 512k / **1M** tokens (resident; stored format v2) | 230.0 / 455.0 / **905.0 MiB** (920 / 910 / 905 B/token); stored 231.0 / 457.0 / **909.0 MiB** — 1M = 949 MB | | +| long-context cold prefill (2048 chunks, no draft) | with suffix pruning 8k / 32k / 100k: 1452 / 1641 / 1584 pp/s (875 at 100k without); matrix-unit index scores alone 100k: 884 pp/s avg (40–50k 963, 88–100k 910); before the matrix-unit kernel 1M: 332 avg (windows 0–128k 792, 128–256k 618, 256–384k 431, 384–512k 366, 512–640k 306, 640–768k 270, 768–896k 234, 896k–1M 203) | | +| phys_footprint after load / end / peak | 206.8 / 206.9 / 213.2 GB | 198.1 / 205.8 GB | + +Decode cost by verify width before M5 (2k context, warm): 1 row 33 ms, 2 rows 44, 4 rows 51, 6 rows 60, +8 rows 67. The 1→2 step is MLX switching from its 1-row qmv kernel; beyond that each row adds ~4 ms of +extra routed experts. vMLX's row-exact multi-row QMV (`vmlx_engine/metal/row_exact_qmv.py`, bit-equal +to 1-row decode, weight fetched once) would flatten the dense part and make verify rows identical to +decode, but it is disabled on the installed MLX ("qmv traversal changed") and needs its kernel +template regenerated for that MLX. + +## Known open items + +- Prose decode ≈ AR (acceptance ~0.36; the governor keeps it at AR, not above). +- Regenerate `row_exact_qmv` for the installed MLX and use it for DSpark verify rows (speed + + exact greedy identity). +- `tests/test_chunking.py` assumes 32-dim index heads, which don't fit the 64-wide groups of the + 4-bit pools; it needs real-geometry heads. +- Logits top-2 are often exactly tied (bf16 head output), so chunk boundaries flip first + tokens; compare head precision with the reference. +- `iogpu.wired_limit_mb` raise not tested. diff --git a/jang-tools/jang_tools/dsv41/__init__.py b/jang-tools/jang_tools/dsv41/__init__.py new file mode 100644 index 00000000..c16330cb --- /dev/null +++ b/jang-tools/jang_tools/dsv41/__init__.py @@ -0,0 +1 @@ +"""DeepSeek-V4.1-Flash (1017) JANG affine conversion + MLX runtime.""" diff --git a/jang-tools/jang_tools/dsv41/calib_audit.py b/jang-tools/jang_tools/dsv41/calib_audit.py new file mode 100644 index 00000000..44ff096d --- /dev/null +++ b/jang-tools/jang_tools/dsv41/calib_audit.py @@ -0,0 +1,154 @@ +"""Audit normalized DSV4.1 calibration rows against the release encoder/parser and tokenizer. + +Checks, per row (failures are listed; exit 1 if any): + effort thinking-mode render starts with exactly one + "<|System|>Reasoning Effort: {75|100} (range 1-100, ...)" matching the row effort; + a chat-mode render of the same messages carries no effort prefix + prefix generation prefixes end with "<|Assistant|>" + tools every tool message links to a call id issued by the preceding assistant turn; + tool results render as inside <|User|> + roundtrip every assistant turn of agentic rows, rendered as a completion, parses back with + parse_message_from_completion_text to the same reasoning, content, tool names and + JSON-equal arguments + tokens template special tokens are single tokenizer ids, and every render survives + tokenizer encode -> decode unchanged + + python -m jang_tools.dsv41.calib_audit --bundle --rows calib/dsv41-1017/corpus_v41.jsonl +""" + +from __future__ import annotations + +import argparse +import collections +import copy +import json +import re +import sys +from pathlib import Path + +from jang_tools.dsv41.generate import load_encoding + +EFFORT = {"high": 75, "max": 100, "low": 50} +# vocab special tokens used by the 1017 template. DSML tags are "<" + "|DSML|" + " calls>" etc. and +# is plain text, both by design of the release template. +SPECIALS = ["<|begin▁of▁sentence|>", "<|end▁of▁sentence|>", "<|User|>", "<|Assistant|>", "<|System|>", + "", "", "|DSML|"] + + +def completion_text(enc, m: dict) -> str: + """What the model would emit for this assistant turn after '' (thinking mode).""" + msgs = [{"role": "user", "content": "x"}, copy.deepcopy(m)] + if msgs[1].get("tool_calls"): + msgs[0] = {"role": "system", "content": "", "tools": [{"type": "function", "function": { + "name": tc["function"]["name"], "description": "", "parameters": {"type": "object", "properties": {}}}} + for tc in m["tool_calls"]]} + msgs.insert(1, {"role": "user", "content": "x"}) + full = enc.encode_messages(msgs, thinking_mode="thinking", drop_thinking=False) + head = enc.encode_messages(msgs[:-1], thinking_mode="thinking", drop_thinking=False) + assert full.startswith(head), "assistant render does not extend the generation prefix" + return full[len(head):] + + +def same_args(a: str, b) -> bool: + try: + return json.loads(a) == (json.loads(b) if isinstance(b, str) else b) + except (ValueError, TypeError): # not JSON on either side + return False + + +def audit_row(enc, tok, row) -> list[str]: + errs = [] + eff = row["effort"] + msgs = copy.deepcopy(row["messages"]) + if row["kind"] == "agentic": + for m in msgs: + if m["role"] == "assistant": + m.setdefault("reasoning_content", "") + text = enc.encode_messages(msgs, thinking_mode="thinking", reasoning_effort=eff) + want = (f"<|begin▁of▁sentence|><|System|>Reasoning Effort: {EFFORT[eff]} (range 1-100, the higher the value, " + "the more thorough the reasoning)\n\n") + if not text.startswith(want): + errs.append(f"effort: prefix mismatch: {text[:120]!r}") + if text.count("Reasoning Effort:") != 1: + errs.append(f"effort: {text.count('Reasoning Effort:')} effort prefixes") + chat = enc.encode_messages(msgs, thinking_mode="chat") + if "Reasoning Effort:" in chat: + errs.append("effort: present in chat mode") + + # generation prefixes: final turn for single/chat, every assistant turn for agentic + cut_points = [i for i, m in enumerate(msgs) if m["role"] == "assistant"] if row["kind"] == "agentic" else [len(msgs)] + for i in cut_points: + p = enc.encode_messages(msgs[:i], thinking_mode="thinking", reasoning_effort=eff) + if not p.endswith("<|Assistant|>"): + errs.append(f"prefix: turn {i} ends {p[-40:]!r}") + + issued, linked = set(), True + for m in msgs: + if m["role"] == "assistant": + issued = {tc["id"] for tc in m.get("tool_calls", [])} + elif m["role"] == "tool" and m.get("tool_call_id") not in issued: + linked = False + if not linked: + errs.append("tools: tool result not linked to a preceding call") + if any(m["role"] == "tool" for m in msgs) and "" not in text: + errs.append("tools: tool results not rendered as ") + + if row["kind"] == "agentic": + for j, m in enumerate(m for m in msgs if m["role"] == "assistant"): + comp = completion_text(enc, m) + try: + parsed = enc.parse_message_from_completion_text(comp, thinking_mode="thinking") + except (ValueError, AssertionError, IndexError, KeyError) as e: + errs.append(f"roundtrip: turn {j} parse error {type(e).__name__}: {str(e)[:80]}") + continue + if (parsed.get("reasoning_content") or "").strip() != (m.get("reasoning_content") or "").strip(): + errs.append(f"roundtrip: turn {j} reasoning differs") + if (parsed.get("content") or "").strip() != (m.get("content") or "").strip(): + errs.append(f"roundtrip: turn {j} content differs") + want_calls = m.get("tool_calls", []) + got_calls = parsed.get("tool_calls", []) + if len(want_calls) != len(got_calls): + errs.append(f"roundtrip: turn {j} {len(got_calls)} calls parsed, {len(want_calls)} expected") + for w, g in zip(want_calls, got_calls): + gf = g.get("function", g) + if gf.get("name") != w["function"]["name"] or not same_args(w["function"]["arguments"], gf.get("arguments")): + errs.append(f"roundtrip: turn {j} call {w['function']['name']} differs") + + for t in (text,): + ids = tok.encode(t, add_special_tokens=False).ids + if tok.decode(ids, skip_special_tokens=False) != t: + errs.append("tokens: encode/decode round-trip changed the text") + if "<|DSML| invoke" in t and t.count("<|DSML| invoke") > ids.count(tok.token_to_id("|DSML|")): + errs.append("tokens: DSML tag not tokenized through the |DSML| special token") + return errs + + +def main(): + ap = argparse.ArgumentParser() + ap.add_argument("--bundle", required=True) + ap.add_argument("--rows", required=True) + a = ap.parse_args() + from tokenizers import Tokenizer + + bundle = Path(a.bundle).expanduser() + enc = load_encoding(bundle) + tok = Tokenizer.from_file(str(bundle / "tokenizer.json")) + bad_tok = [s for s in SPECIALS if len(tok.encode(s, add_special_tokens=False).ids) != 1] + print("special tokens as single ids:", "OK" if not bad_tok else f"NOT single: {bad_tok}") + rows = [json.loads(l) for l in open(a.rows)] + fails = collections.Counter() + nbad = 0 + for r in rows: + errs = audit_row(enc, tok, r) + if errs: + nbad += 1 + for e in errs: + fails[(r["domain"], re.sub(r"turn \d+", "turn N", e)[:110])] += 1 + print(f"rows audited {len(rows)}, rows with issues {nbad}") + for (d, e), v in fails.most_common(30): + print(f" x{v:4d} [{d}] {e}") + sys.exit(1 if nbad or bad_tok else 0) + + +if __name__ == "__main__": + main() diff --git a/jang-tools/jang_tools/dsv41/calib_corpus.py b/jang-tools/jang_tools/dsv41/calib_corpus.py new file mode 100644 index 00000000..925f3539 --- /dev/null +++ b/jang-tools/jang_tools/dsv41/calib_corpus.py @@ -0,0 +1,163 @@ +"""Normalize a JANG calibration corpus into DeepSeek-V4.1-1017 native conversations. + +Input rows (e.g. calib/glm53-flash-nvfp4-2026-10-11/corpus_v2_noreason.jsonl): + {messages, tools, prompt_only, effort: high|max, domain} +with assistant turns in either structured form (tool_calls field) or inline +GLM/Qwen form (`...` and `{"name","arguments"}`). + +Output rows are V4.1 encoder messages: + - assistant: content / reasoning_content / tool_calls (OpenAI format, JSON-string + arguments, ids call_); inline think/tool_call text is parsed out + - tool: role "tool" with tool_call_id matched to the preceding calls in order + - tools: attached to messages[0] (a system message is inserted when needed) +plus a generation plan: + kind = "single" -> generate reasoning + answer for the final turn (any recorded + final assistant reply is dropped) + kind = "agentic" -> keep recorded actions; regenerate reasoning turn by turn + (tools present => the encoder keeps every turn's thinking) + kind = "chat" -> multi-turn chat: keep prior turns, generate the last reply + +Every row is rendered through the release encoding/encoding.py at its effort in +thinking mode to validate it; failures are reported and skipped. + + python -m jang_tools.dsv41.calib_corpus --bundle --corpus --out +""" + +from __future__ import annotations + +import argparse +import collections +import copy +import json +import re +from pathlib import Path + +THINK_RE = re.compile(r"(.*?)", re.S) +CALL_RE = re.compile(r"\s*(\{.*?\})\s*", re.S) + + +def _args_str(args) -> str: + return args if isinstance(args, str) else json.dumps(args, ensure_ascii=False) + + +def parse_assistant(msg: dict, next_id) -> dict: + out = {"role": "assistant"} + content = msg.get("content") or "" + reasoning = msg.get("reasoning_content") or "" + thinks = THINK_RE.findall(content) + if thinks: + reasoning = "\n\n".join(t.strip() for t in [reasoning, *thinks] if t.strip()) + content = THINK_RE.sub("", content) + calls = [] + for tc in msg.get("tool_calls") or []: + fn = tc.get("function", tc) + calls.append({"id": next_id(), "type": "function", + "function": {"name": fn["name"], "arguments": _args_str(fn.get("arguments", {}))}}) + for raw in CALL_RE.findall(content): + obj = json.loads(raw) + calls.append({"id": next_id(), "type": "function", + "function": {"name": obj["name"], "arguments": _args_str(obj.get("arguments", {}))}}) + content = CALL_RE.sub("", content).strip() + out["content"] = content + if reasoning: + out["reasoning_content"] = reasoning.strip() + if calls: + out["tool_calls"] = calls + return out + + +def normalize(row: dict) -> dict: + counter = iter(range(10**6)) + next_id = lambda: f"call_{next(counter)}" # noqa: E731 + msgs: list[dict] = [] + pending: list[str] = [] + for m in row["messages"]: + role = m["role"] + if role == "assistant": + a = parse_assistant(m, next_id) + pending = [tc["id"] for tc in a.get("tool_calls", [])] + msgs.append(a) + elif role == "tool": + tid = pending.pop(0) if pending else f"call_orphan_{len(msgs)}" + msgs.append({"role": "tool", "tool_call_id": tid, "content": m.get("content") or ""}) + elif role in ("system", "user"): + msgs.append({"role": role, "content": m.get("content") or ""}) + else: + raise ValueError(f"unknown role {role}") + tools = row.get("tools") or None + if tools: + if msgs[0]["role"] != "system": + msgs.insert(0, {"role": "system", "content": ""}) + msgs[0]["tools"] = tools + agentic = bool(tools) and any(m.get("tool_calls") for m in msgs) + if agentic: + kind = "agentic" + else: + # generate the final reply ourselves: drop a trailing recorded assistant turn + while msgs and msgs[-1]["role"] == "assistant": + msgs.pop() + n_user = sum(m["role"] == "user" for m in msgs) + kind = "chat" if n_user > 1 else "single" + for m in msgs: + if m["role"] == "assistant" and not agentic: + m.pop("reasoning_content", None) # earlier chat turns: encoder drops their thinking anyway + return {"messages": msgs, "effort": row["effort"], "domain": row["domain"], "kind": kind} + + +def load_encoding(bundle: Path): + from jang_tools.dsv41.generate import load_encoding as _le + + return _le(bundle) + + +def render_prefix(enc, msgs, effort): + """Prompt text that ends with the assistant header + for the next turn.""" + return enc.encode_messages(msgs, thinking_mode="thinking", reasoning_effort=effort) + + +def main(): + ap = argparse.ArgumentParser() + ap.add_argument("--bundle", required=True, help="bundle dir (for encoding/ and tokenizer.json)") + ap.add_argument("--corpus", required=True) + ap.add_argument("--out", required=True) + a = ap.parse_args() + from tokenizers import Tokenizer + + bundle = Path(a.bundle).expanduser() + enc = load_encoding(bundle) + tok = Tokenizer.from_file(str(bundle / "tokenizer.json")) + rows = [json.loads(l) for l in open(a.corpus)] + out, fails = [], collections.Counter() + stats = collections.Counter() + for i, r in enumerate(rows): + try: + n = normalize(r) + msgs = copy.deepcopy(n["messages"]) + if n["kind"] == "agentic": + # full trajectory must render (thinking kept on every turn because tools are present) + for m in msgs: + if m["role"] == "assistant": + m.setdefault("reasoning_content", "") + text = enc.encode_messages(msgs, thinking_mode="thinking", reasoning_effort=n["effort"]) + else: + text = render_prefix(enc, msgs, n["effort"]) + n["n_tok_prompt"] = len(tok.encode(text, add_special_tokens=False).ids) + n["n_assistant_turns"] = sum(m["role"] == "assistant" for m in n["messages"]) + n["id"] = i + out.append(n) + stats[(n["kind"], n["effort"])] += 1 + except (ValueError, AssertionError, IndexError, KeyError, TypeError) as e: # a malformed source row is counted, not fatal + fails[f"{r['domain']}: {type(e).__name__}: {str(e)[:80]}"] += 1 + Path(a.out).parent.mkdir(parents=True, exist_ok=True) + with open(a.out, "w") as f: + for n in out: + f.write(json.dumps(n, ensure_ascii=False) + "\n") + print(f"normalized {len(out)}/{len(rows)}") + for k, v in sorted(stats.items()): + print(f" {k}: {v}") + for k, v in fails.most_common(): + print(f" FAIL x{v} {k}") + + +if __name__ == "__main__": + main() diff --git a/jang-tools/jang_tools/dsv41/calib_eval.py b/jang-tools/jang_tools/dsv41/calib_eval.py new file mode 100644 index 00000000..5b4cb84f --- /dev/null +++ b/jang-tools/jang_tools/dsv41/calib_eval.py @@ -0,0 +1,107 @@ +"""Teacher-forced held-out NLL / perplexity for a DSV4.1-1017 JANG bundle. + +Scores a fixed set of held-out conversations under one bundle and writes the +per-row and aggregate negative log-likelihood (mean over scored next-token +positions) plus perplexity. Run it once per bundle (RTN, then the imatrix +build) over the SAME rows and compare: lower NLL = the better-calibrated +weights. The default hold-out is the corpus rows whose domain was NOT used for +trace generation / stats (so the imatrix experts never saw them), rendered from +their recorded content. + + python -m jang_tools.dsv41.calib_eval --bundle \ + --rows calib/dsv41-1017/corpus_v41.jsonl --out eval/rtn.json +""" + +from __future__ import annotations + +import argparse +import copy +import json +import time +from pathlib import Path + +import mlx.core as mx + +# domains used for calibration (must match calib_generate.DEFAULT_DOMAINS) -> excluded from hold-out +from jang_tools.dsv41.calib_generate import DEFAULT_DOMAINS + + +def render_full(enc, row): + msgs = copy.deepcopy(row["messages"]) + for m in msgs: + if m["role"] == "assistant": + m.setdefault("reasoning_content", "") + return enc.encode_messages(msgs, thinking_mode="thinking", reasoning_effort=row["effort"]) + + +def main(): + ap = argparse.ArgumentParser() + ap.add_argument("--bundle", required=True) + ap.add_argument("--engram-dir") + ap.add_argument("--rows", required=True) + ap.add_argument("--out", required=True) + ap.add_argument("--max-tokens", type=int, default=2560) + ap.add_argument("--n", type=int, default=32, help="held-out rows to score") + ap.add_argument("--held-out", action="store_true", default=True, + help="score only domains NOT in DEFAULT_DOMAINS (genuine hold-out)") + ap.add_argument("--domains", help="comma list to score instead of the default hold-out") + ap.add_argument("--seed", type=int, default=0) + a = ap.parse_args() + + from jang_tools.dsv41.model import DSV41 + from jang_tools.dsv41.generate import load_encoding + + bundle = Path(a.bundle).expanduser() + enc = load_encoding(bundle) + m = DSV41(bundle, a.engram_dir) + + rows = [json.loads(l) for l in open(a.rows)] + if a.domains: + want = set(a.domains.split(",")) + rows = [r for r in rows if r["domain"] in want] + else: + rows = [r for r in rows if r["domain"] not in DEFAULT_DOMAINS] + # deterministic pick, stable across bundles + import random + + random.Random(a.seed).shuffle(rows) + rows = rows[: a.n] + + t0 = time.time() + per_row = [] + tot_nll = 0.0 + tot_tok = 0 + for i, r in enumerate(rows): + text = render_full(enc, r) + ids = m.tokenizer.encode(text, add_special_tokens=False).ids[: a.max_tokens] + if len(ids) < 2: + continue + sess = m.new_session() + logits = m.forward(ids, sess, all_logits=True) # [T, vocab] + lp = logits[:-1].astype(mx.float32) # predict positions 1..T-1 + tgt = mx.array(ids[1:], mx.int32) + logz = mx.logsumexp(lp, axis=-1) + tok_lp = mx.take_along_axis(lp, tgt[:, None], axis=-1)[:, 0] - logz + nll = float(-mx.sum(tok_lp)) + n = len(ids) - 1 + mx.eval(logits) + del logits, lp, sess + mx.clear_cache() + tot_nll += nll + tot_tok += n + per_row.append({"domain": r["domain"], "effort": r["effort"], "n_tok": n, "nll_mean": nll / n}) + if (i + 1) % 8 == 0: + print(f" {i + 1}/{len(rows)} rows, {tot_tok} tok, nll/tok={tot_nll / tot_tok:.4f} ({time.time() - t0:.0f}s)", flush=True) + + mean_nll = tot_nll / max(tot_tok, 1) + out = {"bundle": str(bundle), "rows": len(per_row), "tokens": tot_tok, + "nll_per_tok": mean_nll, "ppl": float(mx.exp(mx.array(mean_nll))), + "per_row": per_row} + Path(a.out).parent.mkdir(parents=True, exist_ok=True) + Path(a.out).write_text(json.dumps(out, indent=2)) + print(f"{bundle.name}: nll/tok={mean_nll:.4f} ppl={out['ppl']:.3f} " + f"over {tot_tok} tok / {len(per_row)} rows in {time.time() - t0:.0f}s -> {a.out}") + + +if __name__ == "__main__": + main() diff --git a/jang-tools/jang_tools/dsv41/calib_generate.py b/jang-tools/jang_tools/dsv41/calib_generate.py new file mode 100644 index 00000000..60f6b2c0 --- /dev/null +++ b/jang-tools/jang_tools/dsv41/calib_generate.py @@ -0,0 +1,206 @@ +"""Locally generate DSV4.1-1017 reasoning traces for selected calibration rows. + +Runs the local JANG bundle (no network). By default only the non-security technical +domains are generated (coding, agentic/terminal tool use, reasoning, systems, +long-context, ml-inference); pass --domains to override. Each row is rendered +through the release encoder (thinking mode, its own effort) and completed with +batched decode. + + single generate reasoning + answer for the final turn + agentic regenerate each assistant turn's reasoning in place, keeping the + recorded tool calls and tool results (turn-by-turn agent logic) + +Output rows carry the generated text back in `messages` (reasoning_content filled, +assistant content replaced for single rows) plus `gen` provenance, ready for +calib_audit.py and the calibration stats pass. + + python -m jang_tools.dsv41.calib_generate --bundle \ + --rows calib/dsv41-1017/corpus_v41.jsonl --out calib/dsv41-1017/traced.jsonl +""" + +from __future__ import annotations + +import argparse +import copy +import json +import time +from pathlib import Path + +import mlx.core as mx +import numpy as np + +DEFAULT_DOMAINS = { + "reason_long", "reason_53flash", "terminal_agent", "toolcall_53flash", + "v3_coding", "v3_agentic", "v3_systems", "v3_longctx", "ml_inference", +} +EFFORT = {"low": 50, "high": 75, "max": 100} + + +def main(): + ap = argparse.ArgumentParser() + ap.add_argument("--bundle", required=True) + ap.add_argument("--engram-dir") + ap.add_argument("--rows", required=True) + ap.add_argument("--out", required=True) + ap.add_argument("--domains", help="comma list; default = technical non-security domains") + ap.add_argument("--batch", type=int, default=12) + ap.add_argument("--max-new", type=int, default=1536) + ap.add_argument("--max-prompt", type=int, default=7000) + ap.add_argument("--temperature", type=float, default=0.6) + ap.add_argument("--top-p", type=float, default=0.95) + ap.add_argument("--seed", type=int, default=0) + ap.add_argument("--limit", type=int) + a = ap.parse_args() + + from jang_tools.dsv41.model import DSV41 + from jang_tools.dsv41.generate import load_encoding + + bundle = Path(a.bundle).expanduser() + enc = load_encoding(bundle) + domains = set(a.domains.split(",")) if a.domains else DEFAULT_DOMAINS + mx.random.seed(a.seed) + + rows = [json.loads(l) for l in open(a.rows)] + rows = [r for r in rows if r["domain"] in domains and r.get("n_tok_prompt", 0) <= a.max_prompt] + if a.limit: + rows = rows[: a.limit] + for i, r in enumerate(rows): + r["_ord"] = i # stable key for checkpoint/resume (deterministic given same inputs) + + # Resume: completed rows are appended to .partial as they finish, so a kill + # only loses the rows still in flight. On restart we skip rows already in partial. + Path(a.out).parent.mkdir(parents=True, exist_ok=True) + partial = Path(str(a.out) + ".partial") + done_ords = set() + if partial.exists(): + for l in open(partial): + l = l.strip() + if not l: + continue + try: + done_ords.add(json.loads(l)["_ord"]) + except (ValueError, KeyError): # a torn last line from an interrupted run is skipped + continue + todo = [r for r in rows if r["_ord"] not in done_ords] + if done_ords: + print(f"resume: {len(done_ords)} rows already in {partial.name}; {len(todo)} remaining", flush=True) + + m = DSV41(bundle, a.engram_dir) + eos = {m.tokenizer.token_to_id("<|end▁of▁sentence|>"), m.eos_id} + think_end = m.tokenizer.token_to_id("") + + # one generation job per assistant turn we must produce + Job = lambda **k: dict(k) # noqa: E731 + jobs = [] + remaining = {} # id(row) -> number of its jobs not yet applied + for r in todo: + if r["kind"] == "agentic": + turns = [i for i, msg in enumerate(r["messages"]) if msg["role"] == "assistant"] + rjobs = [Job(row=r, upto=ti, want="reason") for ti in turns] # keep recorded calls/content, regen reasoning + else: + rjobs = [Job(row=r, upto=len(r["messages"]), want="full")] + jobs.extend(rjobs) + remaining[id(r)] = len(rjobs) + + print(f"{len(todo)} rows -> {len(jobs)} generation turns; batch {a.batch}", flush=True) + done = 0 + t0 = time.time() + results = {id(r): copy.deepcopy(r) for r in todo} + for r in todo: + results[id(r)]["gen"] = {"domain": r["domain"], "effort": r["effort"], "kind": r["kind"], "turns": []} + pf = open(partial, "a") # append; resume preserves earlier rows + for b in range(0, len(jobs), a.batch): + chunk = jobs[b : b + a.batch] + sess, texts, active = [], [], [] + for job in chunk: + msgs = copy.deepcopy(job["row"]["messages"][: job["upto"]]) + prompt = enc.encode_messages(msgs, thinking_mode="thinking", reasoning_effort=job["row"]["effort"]) + ids = m.tokenizer.encode(prompt, add_special_tokens=False).ids + s = m.new_session() + lg = m.forward(ids, s) + sess.append(s) + texts.append([]) + active.append(True) + job["_ids"] = ids + job["_first"] = lg + # seed first sampled token for each + toks = [_sample(job["_first"], a.temperature, a.top_p) for job in chunk] + for i, (job, tk) in enumerate(zip(chunk, toks)): + texts[i].append(tk) + if tk in eos: + active[i] = False + for _ in range(a.max_new - 1): + idx = [i for i, on in enumerate(active) if on] + if not idx: + break + lg = m.decode_batch([sess[i] for i in idx], [toks[i] for i in idx]) + for j, i in enumerate(idx): + tk = _sample(lg[j], a.temperature, a.top_p) + toks[i] = tk + texts[i].append(tk) + if tk in eos: + active[i] = False + for job, out in zip(chunk, texts): + _apply(enc, m, job, out, eos, results[id(job["row"])]) + remaining[id(job["row"])] -= 1 + if remaining[id(job["row"])] == 0: # this row's turns are all generated -> checkpoint it + pf.write(json.dumps(results[id(job["row"])], ensure_ascii=False) + "\n") + pf.flush() + done += len(chunk) + print(f" {done}/{len(jobs)} turns ({time.time() - t0:.0f}s)", flush=True) + pf.close() + + # Assemble the final file from the partial, in stable row order. + by_ord = {} + for l in open(partial): + l = l.strip() + if l: + r = json.loads(l) + by_ord[r["_ord"]] = r + out_rows = [by_ord[r["_ord"]] for r in rows if r["_ord"] in by_ord] + with open(a.out, "w") as f: + for r in out_rows: + f.write(json.dumps(r, ensure_ascii=False) + "\n") + empty = sum(not any(t["reason_chars"] for t in r["gen"]["turns"]) for r in out_rows) + print(f"wrote {len(out_rows)} rows to {a.out} in {time.time() - t0:.0f}s; {empty} rows had no reasoning") + + +def _sample(logits, temperature, top_p): + if temperature <= 0: + return int(mx.argmax(logits)) + p = mx.softmax(logits / temperature, axis=-1) + if top_p < 1.0: + order = mx.argsort(-p) + sp = p[order] + keep = mx.cumsum(sp) - sp < top_p + sp = mx.where(keep, sp, 0) + return int(order[mx.random.categorical(mx.log(sp))]) + return int(mx.random.categorical(mx.log(p))) + + +def _apply(enc, m, job, out_ids, eos, result): + """Write the generated turn back into `result` (the row's output copy).""" + text = m.tokenizer.decode([t for t in out_ids if t not in eos], skip_special_tokens=False) + try: + parsed = enc.parse_message_from_completion_text( + text + "<|end▁of▁sentence|>", thinking_mode="thinking") + except (ValueError, AssertionError, IndexError, KeyError): # unparseable turn: split at instead + head, _, tail = text.partition("") + parsed = {"reasoning_content": head, "content": tail} + reason = (parsed.get("reasoning_content") or "").strip() + content = (parsed.get("content") or "").strip() + msg = result["messages"][job["upto"]] if job["want"] == "reason" else None + if job["want"] == "reason": + # agentic: keep recorded content + tool_calls, insert the model's reasoning + if reason: + msg["reasoning_content"] = reason + else: + # single: the model writes the whole final turn + result["messages"].append({"role": "assistant", "content": content, "reasoning_content": reason}) + result["gen"]["turns"].append({"upto": job["upto"], "want": job["want"], + "reason_chars": len(reason), "content_chars": len(content), + "n_gen": len(out_ids), "eos": out_ids[-1] in eos}) + + +if __name__ == "__main__": + main() diff --git a/jang-tools/jang_tools/dsv41/calib_metrics.py b/jang-tools/jang_tools/dsv41/calib_metrics.py new file mode 100644 index 00000000..556227f2 --- /dev/null +++ b/jang-tools/jang_tools/dsv41/calib_metrics.py @@ -0,0 +1,82 @@ +"""Quant-quality metrics for a DSV4.1 JANG bundle: teacher-forced over held-out rows, per next-token +position capture NLL, top-1 agreement (argmax == true token), top-1 probability, and entropy. +Report mean/median/p95/p99 percentiles. Self-contained (no full-precision reference needed; true +KL-vs-FP requires the 286GB source on a larger host — flagged in handoff).""" +import argparse, json, sys, time +from pathlib import Path +import mlx.core as mx +sys.path.insert(0, str(Path.home() / "jang/jang-tools")) +from jang_tools.dsv41.model import DSV41 +from jang_tools.dsv41.generate import load_encoding +from jang_tools.dsv41.calib_generate import DEFAULT_DOMAINS +import copy + + +def render_full(enc, row): + msgs = copy.deepcopy(row["messages"]) + for m in msgs: + if m["role"] == "assistant": + m.setdefault("reasoning_content", "") + return enc.encode_messages(msgs, thinking_mode="thinking", reasoning_effort=row["effort"]) + + +def pct(a, p): + return float(mx.sort(a)[int(max(0, min(len(a) - 1, round(p / 100 * (len(a) - 1)))))]) + + +def main(): + ap = argparse.ArgumentParser() + ap.add_argument("--bundle", required=True); ap.add_argument("--engram-dir") + ap.add_argument("--rows", required=True); ap.add_argument("--out", required=True) + ap.add_argument("--max-tokens", type=int, default=2560); ap.add_argument("--n", type=int, default=24) + ap.add_argument("--seed", type=int, default=0) + a = ap.parse_args() + enc = load_encoding(Path(a.bundle).expanduser()) + m = DSV41(Path(a.bundle).expanduser(), a.engram_dir) + rows = [json.loads(l) for l in open(a.rows)] + rows = [r for r in rows if r["domain"] not in DEFAULT_DOMAINS] + import random; random.Random(a.seed).shuffle(rows); rows = rows[: a.n] + + all_nll, all_top1, all_p1, all_ent = [], [], [], [] + t0 = time.time(); tot = 0 + for i, r in enumerate(rows): + ids = m.tokenizer.encode(render_full(enc, r), add_special_tokens=False).ids[: a.max_tokens] + if len(ids) < 2: + continue + sess = m.new_session() + logits = m.forward(ids, sess, all_logits=True) + lp = logits[:-1].astype(mx.float32) + tgt = mx.array(ids[1:], mx.int32) + logz = mx.logsumexp(lp, axis=-1) + logp = lp - logz[:, None] # log-softmax [T-1, V] + tok_lp = mx.take_along_axis(logp, tgt[:, None], axis=-1)[:, 0] + nll = -tok_lp # per-token NLL + am = mx.argmax(lp, axis=-1) # quant's top-1 token + top1 = (am == tgt).astype(mx.float32) # agreement with teacher-forced true token + p = mx.exp(logp) + p1 = mx.max(p, axis=-1) # top-1 probability + ent = -mx.sum(p * logp, axis=-1) # predictive entropy (nats) + mx.eval(nll, top1, p1, ent) + all_nll += nll.tolist(); all_top1 += top1.tolist(); all_p1 += p1.tolist(); all_ent += ent.tolist() + tot += len(ids) - 1 + del logits, lp, logp, p, sess; mx.clear_cache() + if (i + 1) % 6 == 0: + print(f" {i+1}/{len(rows)} rows {tot} tok top1={sum(all_top1)/len(all_top1):.3f} ({time.time()-t0:.0f}s)", flush=True) + + nll = mx.array(all_nll); p1 = mx.array(all_p1); ent = mx.array(all_ent) + res = { + "bundle": Path(a.bundle).name, "tokens": tot, "rows": len(rows), + "top1_accuracy": sum(all_top1) / len(all_top1), + "nll": {"mean": float(mx.mean(nll)), "median": pct(nll, 50), "p95": pct(nll, 95), "p99": pct(nll, 99)}, + "ppl_from_mean_nll": float(mx.exp(mx.mean(nll))), + "top1_prob": {"mean": float(mx.mean(p1)), "median": pct(p1, 50), "p5": pct(p1, 5), "p1": pct(p1, 1)}, + "entropy_nats": {"mean": float(mx.mean(ent)), "median": pct(ent, 50), "p95": pct(ent, 95), "p99": pct(ent, 99)}, + "note": "Self-referential quant metrics (teacher-forced). top1_accuracy = argmax==true-token. " + "True KL vs full-precision reference requires the 286GB source on a >256GB host.", + } + Path(a.out).write_text(json.dumps(res, indent=2)) + print(json.dumps(res, indent=2), flush=True) + + +if __name__ == "__main__": + main() diff --git a/jang-tools/jang_tools/dsv41/calib_requant.py b/jang-tools/jang_tools/dsv41/calib_requant.py new file mode 100644 index 00000000..468e5215 --- /dev/null +++ b/jang-tools/jang_tools/dsv41/calib_requant.py @@ -0,0 +1,222 @@ +"""Activation-weighted (imatrix) requantization of DSV4.1-1017 routed experts. + +For each routed expert projection, the per-input-channel importance imp_c = mean +x_c^2 (from calib_stats) weights an AWQ-style per-group clip search: each group of +64 input channels is clipped to [center +/- alpha*halfrange] for the alpha that +minimises the importance-weighted dequant error, then the clipped weights are +affine-quantized with MLX's own packer (so the bundle format is unchanged). This +is the sound, hardware-fitting subset of "awq/gptq/imatrix" for this model: + + - imatrix clip search is applied to gate/up/down of every routed expert; + - plain AWQ scale-folding does NOT apply cleanly here (gate/up share ffn_norm + with the router, so a folded per-channel scale would change routing; down's + input passes the SwiGLU +/-10 clamp, which breaks the fold) -- so we clip + rather than fold; + - GPTQ error-feedback needs per-expert input covariance (XX^T, ~40 GB/layer + for all experts at once) and a separate capture; left as a follow-up. + +Experts with too few calibration tokens fall back to plain affine (uniform imp). +Non-routed tensors, Engram and metadata are copied from the RTN bundle unchanged. + + python -m jang_tools.dsv41.calib_requant --src --rtn \ + --stats calib/dsv41-1017/stats.npz --dst +""" + +from __future__ import annotations + +import argparse +import json +import shutil +import time +from pathlib import Path + +import mlx.core as mx +import numpy as np + +from jang_tools.dsv41.convert_dsv41_jang import GROUP_SIZE, PROJ, default_plan +from jang_tools.dsv41.st_io import Shards, dequant_fp4 + +ALPHAS = mx.array(np.linspace(1.0, 0.5, 11, dtype=np.float32)) # 1.0 = no clip +PLAIN_ALPHAS = mx.array([1.0], dtype=np.float32) # --plain: alpha=1 only == plain affine (RTN) + + +def imatrix_affine(w: mx.array, imp: mx.array, bits: int, alphas: mx.array = ALPHAS): + """Clip each group to the importance-optimal range, then MLX-affine quantize. + + w [out, in]; imp [in] (>=0, per input channel). For every clip strength alpha the + TRUE packed+dequantized error (so the search sees MLX's rounding and the bf16 cast + exactly) is scored per group with the importance weights; the best alpha per group + is kept. alpha=1.0 is plain affine, so the result never loses to it. Returns + (packed, scales, biases) in MLX's affine layout plus the chosen clipped weights.""" + out, din = w.shape + ng = din // GROUP_SIZE + wf = w.astype(mx.float32) + wg = wf.reshape(out, ng, GROUP_SIZE) + impg = imp.reshape(1, ng, GROUP_SIZE) + 1e-12 + gmin = mx.min(wg, axis=0, keepdims=True) # [1,ng,1->G broadcast] + gmax = mx.max(wg, axis=0, keepdims=True) + center = (gmin + gmax) / 2 + half = (gmax - gmin) / 2 + best_err = best_pk = best_sc = best_bi = None + for ai in range(ALPHAS.shape[0]): + a = ALPHAS[ai] + lo = center - a * half + hi = center + a * half + wc = mx.clip(wg, lo, hi).reshape(out, din).astype(mx.bfloat16) + pk, sc, bi = mx.quantize(wc, group_size=GROUP_SIZE, bits=bits) + deq = mx.dequantize(pk, sc, bi, group_size=GROUP_SIZE, bits=bits).astype(mx.float32).reshape(out, ng, GROUP_SIZE) + err = mx.sum(impg * (wg - deq) ** 2, axis=(0, 2), keepdims=True) # [1,ng,1] per group + if best_err is None: + best_err, best_pk, best_sc, best_bi = err, pk, sc, bi + else: + take = err < best_err # [1,ng,1] + best_err = mx.where(take, err, best_err) + tk = take[0, :, 0] # [ng]; pk is [out, ng*wpg], sc/bi are [out, ng] + wpg = pk.shape[1] // ng + best_pk = mx.where(tk[None, :, None], pk.reshape(out, ng, wpg), best_pk.reshape(out, ng, wpg)).reshape(pk.shape) + best_sc = mx.where(tk[None, :], sc, best_sc) + best_bi = mx.where(tk[None, :], bi, best_bi) + return best_pk, best_sc.astype(mx.bfloat16), best_bi.astype(mx.bfloat16), None + + +def main(): + ap = argparse.ArgumentParser() + ap.add_argument("--src", required=True, help="original FP4/FP8 source") + ap.add_argument("--rtn", required=True, help="RTN JANG bundle to copy non-routed tensors from") + ap.add_argument("--stats", required=True) + ap.add_argument("--dst", required=True) + ap.add_argument("--plan", help="JSON {proj:{layer:bits}}; default = RTN plan") + ap.add_argument("--min-tokens", type=int, default=64, help="below this, an expert uses uniform importance") + ap.add_argument("--plain", action="store_true", + help="plain affine (RTN): restrict the clip search to alpha=1 (a no-op clip), i.e. no imatrix. " + "Bit-identical to convert_dsv41_jang's routed quantization; stats are ignored.") + ap.add_argument("--supersede", action="store_true", + help="disk-safe in-place: hardlink non-routed shards from --rtn, and delete each RTN routed " + "shard right after its imatrix replacement is written (consumes the RTN bundle; eval it first)") + a = ap.parse_args() + + src = Path(a.src).expanduser() + rtn = Path(a.rtn).expanduser() + dst = Path(a.dst).expanduser() + dst.mkdir(parents=True, exist_ok=True) + st = np.load(a.stats, allow_pickle=True) + meta = json.loads(str(st["meta"])) + # Engram shards (47/48) were moved into the RTN bundle at RTN-build time, so they are + # absent from the source tree; the requant only reads routed experts (main FP4 shards), + # so allow_missing skips the Engram shards instead of failing on them. + shards = Shards(src, allow_missing=True) + text = json.loads((src / "config.json").read_text())["text_config"] + n_layers, n_experts = text["num_hidden_layers"], text["n_routed_experts"] + from jang_tools.dsv41.convert_dsv41_jang import load_plan + + plan = load_plan(a.plan, n_layers) + # importance per (layer, expert, channel): mean x^2, with per-channel floor + gu_imp = st["gu_sq"] / np.maximum(st["gu_cnt"][..., None], 1.0) # [L,E,D] + dn_imp = st["dn_sq"] / np.maximum(st["gu_cnt"][..., None], 1.0) # [L,E,F] (down shares the routed count) + cnt = st["gu_cnt"] + + index = json.loads((rtn / "model.safetensors.index.json").read_text())["weight_map"] + # copy every non-routed shard file from the RTN bundle verbatim (hardlink under --supersede: 0 extra bytes) + routed_prefixes = tuple(f"layers.{l}.ffn.experts." for l in range(n_layers)) + keep_files = sorted({f for t, f in index.items() if not t.startswith(routed_prefixes)}) + # layer -> the RTN routed shard file holding that layer's experts (for --supersede deletion) + rtn_routed_file = {} + for t, f in index.items(): + if t.startswith(routed_prefixes): + rtn_routed_file[int(t.split(".")[1])] = f + dst_is_separate = dst.resolve() != rtn.resolve() + new_map = {} + for f in keep_files: + if not (dst / f).exists(): + if a.supersede: + _link_or_copy(str(rtn / f), str(dst / f)) + else: + shutil.copy2(rtn / f, dst / f) + for t, ff in index.items(): + if ff == f: + new_map[t] = f + for fn in ("config.json", "jang_config.json", "tokenizer.json", "tokenizer_config.json", "LICENSE"): + if (rtn / fn).exists(): + shutil.copy2(rtn / fn, dst / fn) + for sub in ("encoding", "engram"): + if (rtn / sub).exists() and not (dst / sub).exists(): + if (rtn / sub).is_symlink(): + (dst / sub).symlink_to((rtn / sub).resolve()) + else: + shutil.copytree(rtn / sub, dst / sub, copy_function=_link_or_copy) + + t0 = time.time() + shard_i = max([int(f.split("-")[1]) for f in keep_files], default=0) + report = {} + for layer in range(n_layers): + out = {} + for sp, proj in PROJ.items(): + bits = plan[proj][layer] + imp_all = (dn_imp if proj == "down_proj" else gu_imp)[layer] # [E, d] + names = [f"layers.{layer}.ffn.experts.{e}.{sp}.weight" for e in range(n_experts)] + pks, scs, bis = [], [], [] + err_num = err_den = 0.0 + for e in range(n_experts): + w = shards.dequant(names[e], mx.bfloat16) # [out,in] + if cnt[layer, e] >= a.min_tokens: + imp = mx.array(imp_all[e]) + else: + imp = mx.ones((w.shape[1],), mx.float32) + pk, sc, bi, wc = imatrix_affine(w, imp, bits, PLAIN_ALPHAS if a.plain else ALPHAS) + pks.append(pk); scs.append(sc); bis.append(bi) + if e < 8: # cheap fidelity probe + deq = mx.dequantize(pk, sc, bi, group_size=GROUP_SIZE, bits=bits) + err_num += float(mx.sum((deq.astype(mx.float32) - w.astype(mx.float32)) ** 2)) + err_den += float(mx.sum(w.astype(mx.float32) ** 2)) + mx.eval(pk, sc, bi) + base = f"layers.{layer}.ffn.experts.{proj}" + out[f"{base}.weight"] = mx.stack(pks) + out[f"{base}.scales"] = mx.stack(scs) + out[f"{base}.biases"] = mx.stack(bis) + report[f"{layer}.{proj}"] = {"bits": bits, "rel_l2_first8": (err_num / max(err_den, 1e-30)) ** 0.5} + shard_i += 1 + fn = f"model-routed-{layer:05d}.safetensors" + mx.save_safetensors(str(dst / fn), out, metadata={"format": "mlx"}) + for k in out: + new_map[k] = fn + freed = "" + if a.supersede and dst_is_separate: + # the FP4 source (shards) is the requant input, so dropping the RTN copy of this + # layer's experts is safe and keeps peak disk at ~one extra routed shard. + old = rtn / rtn_routed_file[layer] + if old.exists(): + gb = old.stat().st_size / 1e9 + old.unlink() + freed = f" (freed RTN {old.name}, {gb:.1f} GB)" + print(f"[{time.time()-t0:6.0f}s] layer {layer:2d}: {report[f'{layer}.down_proj']}{freed}", flush=True) + del out + mx.clear_cache() + + total = sum((dst / f).stat().st_size for f in set(new_map.values())) + (dst / "model.safetensors.index.json").write_text( + json.dumps({"metadata": {"total_size": total}, "weight_map": dict(sorted(new_map.items()))}, indent=2)) + jc = json.loads((dst / "jang_config.json").read_text()) + if a.plain: + jc.pop("imatrix_rel_l2_first8", None) + jc["calibration"] = {"method": "plain affine (RTN); imatrix evaluated and not adopted (no held-out gain)"} + else: + jc["profile"] = jc.get("profile", "") + "_IMATRIX" + jc["calibration"] = {"method": "imatrix clip-search (activation x^2 weighted)", "alphas": [1.0, 0.5, 11], + "stats_tokens": meta["tokens"], "stats_rows": meta["rows"], + "min_tokens_for_imatrix": a.min_tokens} + jc["imatrix_rel_l2_first8"] = report + (dst / "jang_config.json").write_text(json.dumps(jc, indent=2)) + print(f"done in {time.time()-t0:.0f}s -> {dst} ({total/1e9:.1f} GB routed+copied)") + + +def _link_or_copy(s, d): + try: + import os + + os.link(s, d) + except OSError: + shutil.copy2(s, d) + + +if __name__ == "__main__": + main() diff --git a/jang-tools/jang_tools/dsv41/calib_stats.py b/jang-tools/jang_tools/dsv41/calib_stats.py new file mode 100644 index 00000000..5cacc519 --- /dev/null +++ b/jang-tools/jang_tools/dsv41/calib_stats.py @@ -0,0 +1,112 @@ +"""Collect per-expert activation statistics for DSV4.1-1017 expert requantization. + +Runs the local bundle forward (prefill only) over the traced calibration +conversations and, at every routed MoE layer, accumulates for each expert e: + gate/up input (dim 5120): sum x, sum x^2, sum |x|, token count + down input (dim 2304): sum h, sum h^2, sum |h|, token count +(the down input is the post-SwiGLU, post-routing-weight intermediate actually +fed to down_proj). These give both AWQ per-channel scales (mean |x|) and the +imatrix diagonal importance (mean x^2) per expert, which the requantizer uses. + +Streaming: stats live in ~0.9 GB of fp32 accumulators; activations are freed per +row. Output: one .npz of {layer}.{proj}.{sq,abs,cnt} plus meta. + + python -m jang_tools.dsv41.calib_stats --bundle \ + --rows calib/dsv41-1017/traced_technical.jsonl --out calib/dsv41-1017/stats.npz +""" + +from __future__ import annotations + +import argparse +import json +import time +from pathlib import Path + +import mlx.core as mx +import numpy as np + + +class Accumulators: + def __init__(self, n_layers, n_experts, d_in, d_inter): + z = lambda d: mx.zeros((n_layers, n_experts, d), mx.float32) # noqa: E731 + self.gu_sq, self.gu_abs = z(d_in), z(d_in) + self.dn_sq, self.dn_abs = z(d_inter), z(d_inter) + self.gu_cnt = mx.zeros((n_layers, n_experts), mx.float32) + + def capture(self, layer, e_idx, gu_in, dn_in): + gu = gu_in.astype(mx.float32) + dn = dn_in.astype(mx.float32) + self.gu_sq[layer] = self.gu_sq[layer].at[e_idx].add(gu * gu) + self.gu_abs[layer] = self.gu_abs[layer].at[e_idx].add(mx.abs(gu)) + self.dn_sq[layer] = self.dn_sq[layer].at[e_idx].add(dn * dn) + self.dn_abs[layer] = self.dn_abs[layer].at[e_idx].add(mx.abs(dn)) + self.gu_cnt[layer] = self.gu_cnt[layer].at[e_idx].add(mx.ones(e_idx.shape, mx.float32)) + + def save(self, path, meta): + mx.eval(self.gu_sq, self.gu_abs, self.dn_sq, self.dn_abs, self.gu_cnt) + np.savez(path, gu_sq=np.array(self.gu_sq), gu_abs=np.array(self.gu_abs), + dn_sq=np.array(self.dn_sq), dn_abs=np.array(self.dn_abs), + gu_cnt=np.array(self.gu_cnt), meta=json.dumps(meta)) + + +def render_full(enc, row): + """The whole conversation as one prefill string (thinking kept on every assistant turn).""" + import copy + + msgs = copy.deepcopy(row["messages"]) + for m in msgs: + if m["role"] == "assistant": + m.setdefault("reasoning_content", "") + return enc.encode_messages(msgs, thinking_mode="thinking", reasoning_effort=row["effort"]) + + +def main(): + ap = argparse.ArgumentParser() + ap.add_argument("--bundle", required=True) + ap.add_argument("--engram-dir") + ap.add_argument("--rows", required=True) + ap.add_argument("--out", required=True) + ap.add_argument("--max-tokens", type=int, default=2560) + ap.add_argument("--limit", type=int) + a = ap.parse_args() + + from jang_tools.dsv41.model import DSV41 + from jang_tools.dsv41.generate import load_encoding + + bundle = Path(a.bundle).expanduser() + enc = load_encoding(bundle) + m = DSV41(bundle, a.engram_dir) + acc = Accumulators(m.args.num_hidden_layers, m.args.n_routed_experts, m.args.hidden_size, m.args.moe_intermediate_size) + for layer in m.model.layers: + layer.capture = acc.capture + + rows = [json.loads(l) for l in open(a.rows)] + if a.limit: + rows = rows[: a.limit] + t0 = time.time() + tot_tok = 0 + for i, r in enumerate(rows): + text = render_full(enc, r) + ids = m.tokenizer.encode(text, add_special_tokens=False).ids[: a.max_tokens] + if len(ids) < 2: + continue + sess = m.new_session() + m.forward(ids, sess) # prefill; capture fires inside every MoE layer + # Force ALL accumulators to materialize now. Evaluating only gu_cnt leaves the + # other four scatter-add graphs lazy, pinning every row's activations and OOMing. + mx.eval(acc.gu_sq, acc.gu_abs, acc.dn_sq, acc.dn_abs, acc.gu_cnt) + del sess + mx.clear_cache() + tot_tok += len(ids) + if (i + 1) % 20 == 0: + print(f" {i + 1}/{len(rows)} rows, {tot_tok} tok ({time.time() - t0:.0f}s)", flush=True) + meta = {"rows": len(rows), "tokens": tot_tok, "n_layers": m.args.num_hidden_layers, + "n_experts": m.args.n_routed_experts, "d_in": m.args.hidden_size, + "d_inter": m.args.moe_intermediate_size, "source_bundle": str(bundle)} + Path(a.out).parent.mkdir(parents=True, exist_ok=True) + acc.save(a.out, meta) + print(f"saved {a.out}: {meta['tokens']} tokens over {meta['rows']} rows in {time.time() - t0:.0f}s") + + +if __name__ == "__main__": + main() diff --git a/jang-tools/jang_tools/dsv41/convert_dspark_jang.py b/jang-tools/jang_tools/dsv41/convert_dspark_jang.py new file mode 100644 index 00000000..81d6d8f9 --- /dev/null +++ b/jang-tools/jang_tools/dsv41/convert_dspark_jang.py @@ -0,0 +1,168 @@ +"""DeepSeek-V4.1-Flash DSpark MTP draft -> a self-contained ``dspark/`` subdir in a JANG bundle. + +The main JANG bundle (`convert_dsv41_jang.py`) DROPS the `mtp.*` draft on purpose (it is a +speculative head, not needed for plain autoregressive serving). This tool carries the draft into +the bundle as its own component subdir — the same convention the engram tables use (`engram/`): + + /dspark/dspark.safetensors the 3-stage DSpark draft (routed experts 4-bit, rest bf16/f32) + /dspark/README.md + +and patches `/config.json` `runtime` so the bundle advertises `bundle_has_mtp: True`. + +Layout (matches what `dspark.load_dspark` assigns): + - routed experts: per (stage, proj) the 128 per-expert weights are dequantized, re-quantized to + 4-bit affine (group 64) and STACKED into the SwitchProj layout + mtp.{s}.ffn.experts.{gate,up,down}_proj.{weight,scales,biases} + (w1->gate_proj, w3->up_proj, w2->down_proj), so load is a direct assign, not a per-expert quant. + - everything else under `mtp.*` is copied at its load precision: F8_E4M3 weights -> bf16, + stored BF16/F32 tensors pass through. `.scale` siblings are consumed by the dequant. + +This is tiny next to the backbone (~5-8 GB), so it writes in place with no full-bundle rebuild. + +Usage: + python -m jang_tools.dsv41.convert_dspark_jang \ + --src ~/models/DeepSeek-V4.1-Flash-1017 \ + --dst ~/models/DeepSeek-V4.1-Flash-1017-JANG-Q2Q3-IMATRIX +""" + +from __future__ import annotations + +import argparse +import json +import re +import time +from pathlib import Path + +import mlx.core as mx + +from jang_tools.dsv41.st_io import Shards + +GROUP_SIZE = 64 +# source per-expert projection name -> prestacked SwitchProj name (same map the backbone uses) +PROJ = {"w1": "gate_proj", "w3": "up_proj", "w2": "down_proj"} +EXPERT_EVAL_CHUNK = 32 # eval cadence while quantizing experts, bounds transient memory + + +def _stage_ids(keys) -> list[int]: + return sorted({int(m.group(1)) for m in (re.match(r"mtp\.(\d+)\.", k) for k in keys) if m}) + + +def _quant_stack_experts(sh: Shards, stage: int, mat: str, n_experts: int, bits: int): + """Dequant the 128 per-expert bf16 weights for one projection and re-quantize to `bits`, + stacked into the SwitchProj layout (weight/scales/biases each stacked on axis 0).""" + qs, ss, bs = [], [], [] + for e in range(n_experts): + w = sh.dequant(f"mtp.{stage}.ffn.experts.{e}.{mat}.weight", mx.bfloat16) + qw, s, b = mx.quantize(w, group_size=GROUP_SIZE, bits=bits) + qs.append(qw) + ss.append(s) + bs.append(b) + if e % EXPERT_EVAL_CHUNK == EXPERT_EVAL_CHUNK - 1: + mx.eval(qs[-1], ss[-1], bs[-1]) + weight, scales, biases = mx.stack(qs), mx.stack(ss), mx.stack(bs) + mx.eval(weight, scales, biases) + return weight, scales, biases + + +def build_dspark_subdir(src: Path, dst: Path, bits: int = 4) -> dict: + src, dst = Path(src).expanduser(), Path(dst).expanduser() + if not (dst / "config.json").exists(): + raise FileNotFoundError(f"destination is not a JANG bundle: {dst}/config.json missing") + out_dir = dst / "dspark" + out_dir.mkdir(exist_ok=True) + + sh = Shards(src, allow_missing=True) + mtp = [n for n in sh.keys() if n.startswith("mtp.")] + if not mtp: + raise ValueError(f"no mtp.* tensors in source {src}") + stages = _stage_ids(mtp) + scfg = json.loads((src / "config.json").read_text())["text_config"] + n_experts = int(scfg["dspark_n_routed_experts"]) + + tensors: dict[str, mx.array] = {} + t0 = time.time() + + # 1) routed experts -> prestacked 4-bit + expert_err = {} + for s in stages: + for mat, proj in PROJ.items(): + weight, scales, biases = _quant_stack_experts(sh, s, mat, n_experts, bits) + base = f"mtp.{s}.ffn.experts.{proj}" + tensors[f"{base}.weight"] = weight + tensors[f"{base}.scales"] = scales + tensors[f"{base}.biases"] = biases + # cheap fidelity probe on expert 0 + w0 = sh.dequant(f"mtp.{s}.ffn.experts.0.{mat}.weight", mx.float32) + dq = mx.dequantize(weight[0], scales[0], biases[0], group_size=GROUP_SIZE, bits=bits).astype(mx.float32) + d = dq - w0 + expert_err[base] = float(mx.sqrt(mx.sum(d * d)) / mx.maximum(mx.sqrt(mx.sum(w0 * w0)), 1e-30)) + print(f"[{time.time()-t0:6.0f}s] experts {base}: {tuple(weight.shape)} rel_l2={expert_err[base]:.4f}", flush=True) + del weight, scales, biases, w0, dq + mx.clear_cache() + + # 2) everything else under mtp.* copied at load precision + n_copied = 0 + for name in sorted(mtp): + if ".ffn.experts." in name: + continue # handled above + if name.endswith(".scale"): + continue # consumed by dequant of its .weight + m = sh.meta[name] + if name.endswith(".weight") and m.dtype in ("F8_E4M3", "I8"): + tensors[name] = sh.dequant(name, mx.bfloat16) + else: + tensors[name] = sh.to_mx(name) # BF16 / F32 / small tensors pass through + n_copied += 1 + if n_copied % 16 == 0: + mx.eval(list(tensors.values())[-16:]) + mx.eval(list(tensors.values())[-16:]) + print(f"[{time.time()-t0:6.0f}s] copied {n_copied} non-expert mtp tensors", flush=True) + + out_file = out_dir / "dspark.safetensors" + tmp = out_dir / "dspark.tmp.safetensors" # mx.save_safetensors requires a .safetensors name + mx.save_safetensors(str(tmp), tensors, metadata={"format": "mlx"}) + tmp.rename(out_file) + size_gb = out_file.stat().st_size / 1e9 + + (out_dir / "README.md").write_text( + "DeepSeek-V4.1-Flash DSpark MTP draft (3 stages), carried as a self-contained bundle " + "component (like `engram/`). Routed experts are 4-bit affine (group 64), stacked in the " + "SwitchProj layout; attention/norms/shared/markov are bf16, small heads f32. Loaded by " + "`jang_tools.dsv41.dspark.load_dspark()` when the bundle advertises " + "`runtime.bundle_has_mtp`.\n" + ) + + # patch bundle config.json runtime to advertise the draft + cfg_path = dst / "config.json" + cfg = json.loads(cfg_path.read_text()) + rt = cfg.setdefault("runtime", {}) + rt["bundle_has_mtp"] = True + rt["mtp_mode"] = "dspark_subdir" + rt["dspark_dir"] = "dspark" + cfg.setdefault("text_config", {})["num_nextn_predict_layers"] = len(stages) + cfg_path.write_text(json.dumps(cfg, indent=2)) + + summary = { + "stages": stages, + "n_experts": n_experts, + "bits": bits, + "tensors": len(tensors), + "size_gb": round(size_gb, 2), + "expert_rel_l2": expert_err, + } + (out_dir / "dspark_convert.json").write_text(json.dumps(summary, indent=2)) + print(f"[{time.time()-t0:6.0f}s] wrote {out_file} ({size_gb:.2f} GB), patched config runtime", flush=True) + return summary + + +def main(): + ap = argparse.ArgumentParser() + ap.add_argument("--src", required=True, help="source DeepSeek-V4.1-Flash model dir (has mtp.*)") + ap.add_argument("--dst", required=True, help="JANG bundle dir to add dspark/ into") + ap.add_argument("--bits", type=int, default=4) + a = ap.parse_args() + build_dspark_subdir(Path(a.src), Path(a.dst), a.bits) + + +if __name__ == "__main__": + main() diff --git a/jang-tools/jang_tools/dsv41/convert_dsv41_jang.py b/jang-tools/jang_tools/dsv41/convert_dsv41_jang.py new file mode 100644 index 00000000..690a05a6 --- /dev/null +++ b/jang-tools/jang_tools/dsv41/convert_dsv41_jang.py @@ -0,0 +1,334 @@ +"""DeepSeek-V4.1-Flash(-1017) -> JANG mixed affine bundle (MLX mx.quantize, group 64). + +Default plan (~211 GB resident, fits a 256 GB Mac with KV/runtime headroom): + + routed experts (543.6B params) gate/up q3 on layers 0-7, q2 on 8-39; down q3 everywhere + attention / shared expert / + indexer wq_b / engram wkv / + embed / head 8-bit affine + router, mHC, sinks, norms, + compressor, indexer wk/weights source precision (F32 / BF16) passthrough + engram n-gram tables (~203 GB) NOT copied: stay FP8 on disk, read by row at runtime + DSpark MTP (mtp.*) dropped (autoregressive runtime only) + +Routed experts are written pre-stacked as + layers.N.ffn.experts.{gate,up,down}_proj.{weight,scales,biases} [384, out, in*bits/32] +Everything else keeps its source name. + +Output layout: one shard per routed layer plus shards for the non-routed tensors, so a +killed run resumes by skipping shards whose names are already recorded in +`.convert_progress.json`. + +Usage: + python -m jang_tools.dsv41.convert_dsv41_jang \ + --src ~/models/DeepSeek-V4.1-Flash-1017 \ + --dst ~/models/DeepSeek-V4.1-Flash-1017-JANG +""" + +from __future__ import annotations + +import argparse +import json +import re +import shutil +import time +from concurrent.futures import ThreadPoolExecutor +from pathlib import Path + +import mlx.core as mx +import numpy as np + +from jang_tools.dsv41.st_io import Shards, dequant_fp4 + +GROUP_SIZE = 64 +PROJ = {"w1": "gate_proj", "w3": "up_proj", "w2": "down_proj"} +EXPERT_CHUNK = 64 # experts dequantized + quantized at once (~2.4 GB bf16 per chunk) + + +def default_plan(n_layers: int) -> dict[str, dict[int, int]]: + hi_layers = set(range(8)) + return { + "gate_proj": {l: 3 if l in hi_layers else 2 for l in range(n_layers)}, + "up_proj": {l: 3 if l in hi_layers else 2 for l in range(n_layers)}, + "down_proj": {l: 3 for l in range(n_layers)}, + } + + +def load_plan(path: str | None, n_layers: int) -> dict[str, dict[int, int]]: + plan = default_plan(n_layers) + if path: + user = json.loads(Path(path).read_text()) + for proj, layers in user.items(): + for l, b in layers.items(): + plan[proj][int(l)] = int(b) + return plan + + +# --------------------------------------------------------------------------- classify + +PASSTHROUGH_RE = re.compile( + r"(norm|attn_sink|hc_attn|hc_ffn|\.gate\.(weight|bias|bias_vl)$|compressor\.(wkv|wgate)" + r"|indexer\.(wk|weights_proj)\.weight$|engram\.(q_weight|k_weight)$" + r"|^image_(start|end|newline)$|^vision\.|^aligner\.)" +) + + +def classify(name: str, shards: Shards) -> str | None: + """'skip' | 'routed' | 'q8' | 'pass' | None (scale sibling, consumed with its weight).""" + if name.startswith("mtp.") or ".engram.embed." in name: + return "skip" + if name.endswith(".scale"): + return None + if re.search(r"\.ffn\.experts\.\d+\.w[123]\.weight$", name): + return "routed" + if PASSTHROUGH_RE.search(name): + return "pass" + if name.endswith(".weight") and len(shards.meta[name].shape) == 2: + return "q8" + return "pass" + + +# --------------------------------------------------------------------------- writer + +class BundleWriter: + def __init__(self, dst: Path): + self.dst = dst + self.progress_path = dst / ".convert_progress.json" + self.progress = json.loads(self.progress_path.read_text()) if self.progress_path.exists() else {"shards": {}} + + def done(self, key: str) -> bool: + info = self.progress["shards"].get(key) + return info is not None and (self.dst / info["file"]).exists() + + def write(self, key: str, tensors: dict[str, mx.array]): + fname = f"part-{key}.safetensors" + tmp = self.dst / (fname + ".tmp.safetensors") + mx.save_safetensors(str(tmp), tensors, metadata={"format": "mlx"}) + tmp.rename(self.dst / fname) + self.progress["shards"][key] = { + "file": fname, + "tensors": sorted(tensors), + "bytes": (self.dst / fname).stat().st_size, + } + self.progress_path.write_text(json.dumps(self.progress, indent=1)) + + def finalize(self) -> dict[str, str]: + """Rename parts to model-XXXXX-of-NNNNN in key order and write the index.""" + keys = sorted(self.progress["shards"], key=_shard_sort_key) + n = len(keys) + weight_map, total = {}, 0 + for i, key in enumerate(keys, 1): + info = self.progress["shards"][key] + final = f"model-{i:05d}-of-{n:05d}.safetensors" + src = self.dst / info["file"] + if src.exists() and info["file"] != final: + src.rename(self.dst / final) + info["file"] = final + total += info["bytes"] + for t in info["tensors"]: + weight_map[t] = final + self.progress_path.write_text(json.dumps(self.progress, indent=1)) + (self.dst / "model.safetensors.index.json").write_text( + json.dumps({"metadata": {"total_size": total}, "weight_map": dict(sorted(weight_map.items()))}, indent=2) + ) + return weight_map + + +def _shard_sort_key(key: str): + kind, _, num = key.partition("-") + return (0 if kind == "base" else 1, int(num) if num.isdigit() else 0) + + +# --------------------------------------------------------------------------- conversion + +def quantize(w: mx.array, bits: int) -> dict[str, mx.array]: + qw, s, b = mx.quantize(w, group_size=GROUP_SIZE, bits=bits) + return {"weight": qw, "scales": s, "biases": b} + + +def convert_routed_layer(shards: Shards, layer: int, plan, pool: ThreadPoolExecutor, n_experts: int): + out: dict[str, mx.array] = {} + stats = {} + for src_proj, proj in PROJ.items(): + bits = plan[proj][layer] + names = [f"layers.{layer}.ffn.experts.{e}.{src_proj}.weight" for e in range(n_experts)] + raw_w = list(pool.map(shards.raw, names)) + raw_s = list(pool.map(shards.raw, [n[: -len(".weight")] + ".scale" for n in names])) + parts = {"weight": [], "scales": [], "biases": []} + err_num = err_den = 0.0 + for c in range(0, n_experts, EXPERT_CHUNK): + w = dequant_fp4(mx.array(np.stack(raw_w[c : c + EXPERT_CHUNK])), mx.array(np.stack(raw_s[c : c + EXPERT_CHUNK]))) + q = quantize(w, bits) + if c == 0: # cheap fidelity probe on the first chunk + deq = mx.dequantize(q["weight"], q["scales"], q["biases"], group_size=GROUP_SIZE, bits=bits) + d = (deq.astype(mx.float32) - w.astype(mx.float32)) + err_num = float(mx.sqrt(mx.sum(d * d))) + err_den = float(mx.sqrt(mx.sum(w.astype(mx.float32) ** 2))) + mx.eval(q) + for k in parts: + parts[k].append(q[k]) + del w, q + base = f"layers.{layer}.ffn.experts.{proj}" + for k, v in parts.items(): + out[f"{base}.{k}"] = mx.concatenate(v, axis=0) + mx.eval(out) + stats[proj] = {"bits": bits, "rel_l2_first_chunk": err_num / max(err_den, 1e-30)} + del raw_w, raw_s, parts + return out, stats + + +def convert_base(shards: Shards, names: list[str]): + out: dict[str, mx.array] = {} + kinds = {"q8": 0, "pass": 0} + for name in names: + kind = classify(name, shards) + if kind == "q8": + w = shards.dequant(name, mx.bfloat16) + base = name[: -len(".weight")] + for k, v in quantize(w, 8).items(): + out[f"{base}.{k}"] = v + else: + m = shards.meta[name] + if m.dtype in ("F8_E4M3", "I8"): + raise ValueError(f"refusing to pass through quantized source tensor {name}") + out[name] = shards.to_mx(name) + kinds[kind] += 1 + mx.eval(list(out.values())[-3:]) + return out, kinds + + +def write_metadata(src: Path, dst: Path, plan, n_layers: int, stats: dict, excluded: dict): + cfg = json.loads((src / "config.json").read_text()) + cfg.pop("quantization_config", None) + text = cfg["text_config"] + quant = {"group_size": GROUP_SIZE, "bits": 8, "mode": "affine"} + for proj, layers in plan.items(): + for l in range(n_layers): + quant[f"layers.{l}.ffn.experts.{proj}"] = {"group_size": GROUP_SIZE, "bits": layers[l], "mode": "affine"} + cfg["quantization"] = quant + text["num_nextn_predict_layers"] = 0 + cfg["runtime"] = { + "bundle_has_mtp": False, + "mtp_mode": "dropped", + "engram_tables": "disk", + "engram_dir": "engram", + } + (dst / "config.json").write_text(json.dumps(cfg, indent=2)) + + routed_bits = sum( + plan[p][l] for p in plan for l in range(n_layers) + ) / (3 * n_layers) + (dst / "jang_config.json").write_text(json.dumps({ + "weight_format": "affine", + "profile": "JANG_DSV41_Q2Q3_D3_L0-7G3U3_A8", + "source_model": "deepseek-ai/DeepSeek-V4.1-Flash-1017", + "source_revision": "1bae0e1088993b9b82de08f59de5be5a34e42170", + "has_vision": True, + "critical_f32_preserved": True, + "affine_group_size": GROUP_SIZE, + "affine_bits": { + "routed_expert_mean": round(routed_bits, 4), + "attention": 8, + "shared_expert": 8, + "indexer_wq_b": 8, + "engram_wkv": 8, + "embed_tokens": 8, + "lm_head": 8, + "norms_router_hc_compressor": "source", + }, + "routed_expert_bit_plan": {p: {str(l): b for l, b in v.items()} for p, v in plan.items()}, + "routed_layout": "prestacked layers.N.ffn.experts.{gate,up,down}_proj", + "engram": { + "storage": "fp8_e4m3 rows + e8m0 scales per 32 cols, unmodified source shards", + "location": "engram/ (see engram/README.md)", + "resident": False, + }, + "excluded": excluded, + "quant_error_probe": stats, + }, indent=2)) + + for fn in ("tokenizer.json", "tokenizer_config.json", "LICENSE"): + if (src / fn).exists(): + shutil.copy2(src / fn, dst / fn) + if (src / "encoding").exists(): + shutil.copytree(src / "encoding", dst / "encoding", dirs_exist_ok=True) + (dst / "engram").mkdir(exist_ok=True) + readme = dst / "engram" / "README.md" + if not readme.exists(): + readme.write_text( + "Engram n-gram tables (FP8, ~203 GB) are read from disk row by row, never loaded into RAM.\n\n" + "Place the two unmodified source shards that hold `layers.{1,14}.engram.embed.{weight,scale}`\n" + "here (model-00047-of-00048.safetensors, model-00048-of-00048.safetensors), or pass\n" + "`--engram-dir ` to the runtime. They can be moved, not copied, from the source download.\n" + ) + + +def convert(src: Path, dst: Path, plan_path: str | None, only_layers: list[int] | None = None): + dst.mkdir(parents=True, exist_ok=True) + shards = Shards(src, allow_missing=True) + if shards.missing: + print(f"[convert] shards not present yet: {shards.missing} (routed layers proceed; rerun to finish)") + text = json.loads((src / "config.json").read_text())["text_config"] + n_layers, n_experts = text["num_hidden_layers"], text["n_routed_experts"] + plan = load_plan(plan_path, n_layers) + writer = BundleWriter(dst) + stats = writer.progress.setdefault("stats", {}) + t0 = time.time() + + with ThreadPoolExecutor(16) as pool: + for layer in only_layers if only_layers is not None else range(n_layers): + key = f"routed-{layer}" + if writer.done(key): + continue + out, st = convert_routed_layer(shards, layer, plan, pool, n_experts) + writer.progress.setdefault("stats", {})[str(layer)] = st + writer.write(key, out) + gb = writer.progress["shards"][key]["bytes"] / 1e9 + print(f"[{time.time() - t0:7.0f}s] layer {layer:2d}: {gb:.2f} GB {st}", flush=True) + del out + mx.clear_cache() + + base_names = sorted(n for n in shards.keys() if classify(n, shards) in ("q8", "pass")) + excluded = { + "mtp": sum(n.startswith("mtp.") for n in shards.keys()), + "engram_embed": sum(".engram.embed." in n for n in shards.keys()), + } + # non-routed tensors, split in a few deterministic groups so each shard stays a few GB + groups: dict[str, list[str]] = {} + for n in base_names: + m = re.match(r"layers\.(\d+)\.", n) + key = f"base-{int(m.group(1)) // 10 + 1}" if m else "base-0" + groups.setdefault(key, []).append(n) + for key, names in sorted(groups.items()): + if writer.done(key) or only_layers is not None: + continue + if any(shards.meta.get(n) is None for n in names) or shards.missing: + print(f"[convert] {key}: waiting for missing source shards") + continue + out, kinds = convert_base(shards, names) + writer.write(key, out) + print(f"[{time.time() - t0:7.0f}s] {key}: {len(names)} tensors {kinds}", flush=True) + del out + mx.clear_cache() + + if only_layers is not None or shards.missing: + return + writer.finalize() + write_metadata(src, dst, plan, n_layers, writer.progress.get("stats", {}), excluded) + total = sum(v["bytes"] for v in writer.progress["shards"].values()) + print(f"done in {time.time() - t0:.0f}s, {total / 1e9:.2f} GB ({total / 2**30:.2f} GiB)") + + +def main(): + ap = argparse.ArgumentParser() + ap.add_argument("--src", required=True) + ap.add_argument("--dst", required=True) + ap.add_argument("--plan", help="JSON {proj: {layer: bits}} overriding the default plan") + ap.add_argument("--layers", help="comma list: convert only these routed layers (no finalize)") + a = ap.parse_args() + only = [int(x) for x in a.layers.split(",")] if a.layers else None + convert(Path(a.src).expanduser(), Path(a.dst).expanduser(), a.plan, only) + + +if __name__ == "__main__": + main() diff --git a/jang-tools/jang_tools/dsv41/dspark.py b/jang-tools/jang_tools/dsv41/dspark.py new file mode 100644 index 00000000..9cf1956b --- /dev/null +++ b/jang-tools/jang_tools/dsv41/dspark.py @@ -0,0 +1,783 @@ +"""DeepSeek-V4.1 dSpark (MTP) draft head in MLX + the speculative accept/reject loop. + +Faithful port of the release DSparkBlock / forward_embed / forward_head / forward_spec +(inference/model.py). dSpark is three MTP stages appended after the 40-layer backbone. Each stage +mirrors a backbone Block (latent attention over a 128-token window + a 128-expert top-3 MoE + hyper- +connections) but: + - its attention window is seeded from the backbone's hidden state, not from its own tokens; + - stage 0 carries main_proj/main_norm that project the concatenated mean-over-hc hidden of the + backbone target layers (37,38,39) down to one hidden; + - the last stage carries a final norm, a Markov bias head (embed+head over a rank-256 space) and a + confidence head. +The stages share the backbone's token embedding and output head. + +forward_spec drafts a block of `dspark_block_size` (5) tokens from the last committed token plus the +backbone's target-layer hidden; the Markov head sharpens each step autoregressively and the +confidence head scores the block. The release ships only this forward -- the accept/reject loop that +turns drafts into a speedup is built here (`DSparkRunner`). + +The draft is loaded at bf16 from the SOURCE model shards (the JANG bundle drops mtp.*), with the +routed experts quantized to 4-bit in memory so the whole draft is ~8 GB on top of the backbone. +Verification is greedy-exact (a draft is kept only if it equals the backbone's argmax), so draft +precision only moves the acceptance rate (the speedup). The committed tokens are the backbone's own +greedy tokens; the one caveat is floating point: the backbone scores a multi-token verify block in a +differently shaped forward than a one-token decode step, so a near-tie argmax can in principle flip +relative to plain AR decode. +""" + +from __future__ import annotations + +import time +from pathlib import Path + +import mlx.core as mx +import mlx.nn as nn +import numpy as np + +from jang_tools.dsv41.model import ( + GROUP_SIZE, + DenseLinear, + RMSNorm, + Rope, + SwitchProj, + _hc_post, + _hc_pre, + _hc_split, + _hc_split_metal, + sparse_attention, + yarn_inv_freq, +) +from jang_tools.dsv41.st_io import Shards + + +# --------------------------------------------------------------------------- hyper-connections +def _hc_mixes(x, fn, scale, base, hc, iters, hc_eps, eps): + """pre/post/comb mixing weights for one hc sub-block (release Block.hc_mixes).""" + B, S = x.shape[:2] + xf = x.reshape(B, S, -1).astype(mx.float32) + rs = mx.rsqrt(mx.mean(xf * xf, -1, keepdims=True) + eps) + m = (xf @ fn.T) * rs + if hc == 4: + return _hc_split_metal(m, scale, base, iters, hc_eps) + return _hc_split(hc, iters, hc_eps)(m, scale, base) + + +# --------------------------------------------------------------------------- draft attention +class BoundedWindow: + """The last ``cap`` rows of an append-only [1, T, D] sequence, oldest first. + + Functional updates (a new array per append, never an in-place slot write), so a (buf, n) ref + snapshot stays valid across later appends -- the same rollback contract as QuantGrowBuffer. Each append + copies at most ``cap`` rows (128 x head_dim bf16 = 128 KB), independent of context length.""" + + def __init__(self, cap: int): + self.cap = int(cap) + self.buf = None + self.n = 0 # rows held (<= cap) + + def append(self, x: mx.array): + if x.shape[1] == 0: + return + if x.shape[1] > self.cap: + x = x[:, -self.cap:] + buf = x if self.buf is None else mx.concatenate([self.buf, x], axis=1) + if buf.shape[1] > self.cap: + buf = buf[:, -self.cap:] + self.buf, self.n = buf, int(buf.shape[1]) + + def view(self, n=None): + return self.buf + + def snapshot(self): + return (self.buf, self.n) + + def load(self, s): + self.buf, self.n = s + + +class DSparkAttention(nn.Module): + """Latent attention whose KV window is main-hidden-derived; bf16 (draft precision).""" + + def __init__(self, args): + super().__init__() + d, H = args.hidden_size, args.num_attention_heads + self.n_heads, self.head_dim, self.rd = H, args.head_dim, args.qk_rope_head_dim + self.n_groups, self.o_lora_rank = args.o_groups, args.o_lora_rank + self.win = args.sliding_window + self.scale = self.head_dim ** -0.5 + self.attn_sink = mx.zeros((H,), mx.float32) + self.wq_a = DenseLinear(d, args.q_lora_rank) + self.q_norm = RMSNorm(args.q_lora_rank, args.rms_norm_eps) + self.wq_b = DenseLinear(args.q_lora_rank, H * self.head_dim) + self.wkv = DenseLinear(d, self.head_dim) + self.kv_norm = RMSNorm(self.head_dim, args.rms_norm_eps) + self.wo_a = mx.zeros((self.n_groups, self.o_lora_rank, H * self.head_dim // self.n_groups), mx.bfloat16) + self.wo_b = DenseLinear(self.n_groups * self.o_lora_rank, d) + inv = yarn_inv_freq(self.rd, args.rope_theta, 0, 1, 0, 0) # dspark attn is never compressed -> plain rope + self._rope = Rope(self.rd, inv) + # main-hidden-derived KV for the last `win` committed positions (rope'd), oldest first. Bounded: + # attend only ever reads the last `win` rows, so keeping every position (the old GrowBuffer) cost + # ~3 KB/token (~3 GB at 1M ctx) for nothing. + self.window = BoundedWindow(self.win) + + def seed(self, main_x, positions): + """Append the committed positions' main-derived KV to the window (release prefill/decode seed). + Only the last `win` positions can ever be attended, so older rows are dropped before projecting.""" + if main_x.shape[1] > self.win: + main_x = main_x[:, -self.win:] + positions = positions[-self.win:] + kv = self._rope(self.kv_norm(self.wkv(main_x)), positions) # [1, S, head_dim] + self.window.append(kv.astype(mx.bfloat16)) + + def attend(self, x, positions): + """Draft block attention: queries x [1, bs, d] attend to (last-`win` window ++ own KV).""" + B, bs, _ = x.shape + qr = self.q_norm(self.wq_a(x)) + q = self._rope(self.wq_b(qr).reshape(B, bs, self.n_heads, self.head_dim), positions) + kv = self._rope(self.kv_norm(self.wkv(x)), positions) # [1, bs, head_dim] + win = self.window.view() + full = mx.concatenate([win, kv], axis=1) if win is not None else kv # [1, L, head_dim] + L = full.shape[1] + idxs = mx.broadcast_to(mx.arange(L, dtype=mx.int32)[None, None], (1, bs, L)) # every query sees all + o = sparse_attention(q, full, self.attn_sink, idxs, self.scale) # [1, bs, H, head_dim] + o = self._rope(o, positions, inverse=True).astype(mx.bfloat16) + o = o.reshape(bs, self.n_groups, -1) # [bs, groups, (H/groups)*head_dim] + o = mx.einsum("sgd,grd->sgr", o, self.wo_a) # [bs, groups, o_lora_rank] + return self.wo_b(o.reshape(1, bs, -1)) # [1, bs, d] + + +# --------------------------------------------------------------------------- draft MoE +class DSparkMoE(nn.Module): + """128-expert top-3 MoE, routed experts 4-bit (gather_qmm), shared expert + gate bf16/f32.""" + + def __init__(self, args, n_experts, inter, bits=4): + super().__init__() + d = args.hidden_size + self.topk = args.raw["dspark_num_experts_per_tok"] + self.route_scale = args.routed_scaling_factor + self.norm_topk = args.norm_topk_prob + self.lim = args.swiglu_limit + self.gate_w = mx.zeros((n_experts, d), mx.bfloat16) + self.gate_bias = mx.zeros((n_experts,), mx.float32) + self.gate_proj = SwitchProj(n_experts, d, inter, bits) + self.up_proj = SwitchProj(n_experts, d, inter, bits) + self.down_proj = SwitchProj(n_experts, inter, d, bits) + self.sw1 = DenseLinear(d, inter) + self.sw3 = DenseLinear(d, inter) + self.sw2 = DenseLinear(inter, d) + + def __call__(self, x): + B, S, D = x.shape + xf = x.reshape(-1, D) + scores = mx.sqrt(nn.softplus(xf.astype(mx.float32) @ self.gate_w.astype(mx.float32).T)) + idx = mx.argpartition(-(scores + self.gate_bias), kth=self.topk - 1, axis=-1)[:, : self.topk] + w = mx.take_along_axis(scores, idx, axis=-1) + if self.norm_topk and self.topk > 1: + w = w / (mx.sum(w, -1, keepdims=True) + 1e-20) + w = w * self.route_scale + n = xf.shape[0] + xe = xf[:, None, None, :] # [N,1,1,D]; small N (<=bs) so no sort (release threshold 64) + gate = self.gate_proj(xe, idx, False).astype(mx.float32) + up = self.up_proj(xe, idx, False).astype(mx.float32) + lim = self.lim + if lim > 0: + up = mx.clip(up, -lim, lim) + gate = mx.minimum(gate, lim) + h = nn.silu(gate) * up + h = h * w[:, :, None, None] + y = self.down_proj(h.astype(mx.bfloat16), idx, False).astype(mx.float32) + y = mx.sum(y.reshape(n, self.topk, D), axis=1) + sg = self.sw1(xf).astype(mx.float32) + su = self.sw3(xf).astype(mx.float32) + if lim > 0: + su = mx.clip(su, -lim, lim) + sg = mx.minimum(sg, lim) + y = y + self.sw2((nn.silu(sg) * su).astype(mx.bfloat16)).astype(mx.float32) + return y.astype(x.dtype).reshape(B, S, D) + + +# --------------------------------------------------------------------------- one dSpark stage +class DSparkStage(nn.Module): + def __init__(self, args, n_experts, inter, is_first, is_last, n_targets, markov_rank): + super().__init__() + d, hc = args.hidden_size, args.hc_mult + self.attn = DSparkAttention(args) + self.moe = DSparkMoE(args, n_experts, inter) + self.attn_norm = RMSNorm(d, args.rms_norm_eps) + self.ffn_norm = RMSNorm(d, args.rms_norm_eps) + mix = (2 + hc) * hc + for p in ("attn", "ffn"): + setattr(self, f"hc_{p}_fn", mx.zeros((mix, hc * d), mx.float32)) + setattr(self, f"hc_{p}_base", mx.zeros((mix,), mx.float32)) + setattr(self, f"hc_{p}_scale", mx.zeros((3,), mx.float32)) + self.hc, self.iters, self.hc_eps, self.eps = hc, args.hc_sinkhorn_iters, args.hc_eps, args.rms_norm_eps + if is_first: + self.main_proj = DenseLinear(d * n_targets, d) + self.main_norm = RMSNorm(d, args.rms_norm_eps) + if is_last: + self.norm = RMSNorm(d, args.rms_norm_eps) + self.markov_embed = mx.zeros((args.vocab_size, markov_rank), mx.bfloat16) + self.markov_head = mx.zeros((args.vocab_size, markov_rank), mx.bfloat16) + self.conf_proj = mx.zeros((1, d + markov_rank), mx.float32) + + def _mixes(self, x, which): + return _hc_mixes(x, getattr(self, f"hc_{which}_fn"), getattr(self, f"hc_{which}_scale"), + getattr(self, f"hc_{which}_base"), self.hc, self.iters, self.hc_eps, self.eps) + + def forward(self, x, pre_mix, positions): + """x [1,bs,hc,d]; pre_mix [1,bs,hc]. Window must already hold committed KV. (release Block.forward).""" + residual = x + a_pre, a_post, a_comb = self._mixes(x, "attn") + h = self.attn.attend(self.attn_norm(_hc_pre(x, pre_mix)), positions) + x = _hc_post(h, residual, a_post, a_comb) + residual = x + f_pre, f_post, f_comb = self._mixes(x, "ffn") + h = self.moe(self.ffn_norm(_hc_pre(x, a_pre))) + x = _hc_post(h, residual, f_post, f_comb) + return x, f_pre + + +# --------------------------------------------------------------------------- dSpark head +def markov_chain(logits, markov_embed, head_t, seed_tok): + """Greedy Markov-biased decode of a drafted block, kept on the device (no per-step host sync). + logits [bs, vocab] f32; markov_embed [vocab, rank]; head_t [rank, vocab] f32 (the markov head, + cast + transposed once). Returns (drafted ids [bs] int32, markov embeddings [bs, rank] f32), where + step i uses the embedding of the previous token (seed_tok for i = 0).""" + tok = mx.array([int(seed_tok)], dtype=mx.int32) + toks, membeds = [], [] + for i in range(logits.shape[0]): + me = mx.take(markov_embed, tok, axis=0)[0].astype(mx.float32) # [rank] + tok = mx.argmax(logits[i] + me @ head_t, keepdims=True).astype(mx.int32) # [1] + toks.append(tok) + membeds.append(me) + return mx.concatenate(toks), mx.stack(membeds, axis=0) + + +class DSpark(nn.Module): + """The 3-stage dSpark draft head. embed/head are the backbone's (shared).""" + + def __init__(self, args, embed, head): + super().__init__() + self.args = args + self.embed, self.head = embed, head # backbone QuantizedEmbedding / QuantizedLinear + self.hc = args.hc_mult + self.bs = args.raw["dspark_block_size"] + self.noise = args.raw["dspark_noise_token_id"] + self.targets = tuple(args.raw["dspark_target_layer_ids"]) + self.n_stages = int(args.raw.get("n_mtp_layers", 3)) + self.markov_rank = args.raw["dspark_markov_rank"] + n_experts = args.raw["dspark_n_routed_experts"] + inter = args.raw.get("dspark_moe_inter_dim", args.moe_intermediate_size) + self.stages = [ + DSparkStage(args, n_experts, inter, i == 0, i == self.n_stages - 1, len(self.targets), self.markov_rank) + for i in range(self.n_stages) + ] + + # --- window management (external, keeps forward_spec a pure draft) --- + def seed_windows(self, main_hidden, positions): + """Add committed positions' KV to every stage window. main_hidden [1,S,d*n_targets].""" + positions = list(positions) + win = self.stages[0].attn.win + if main_hidden.shape[1] > win: # only the last `win` positions are ever attended + main_hidden = main_hidden[:, -win:] + positions = positions[-win:] + main_x = self.stages[0].main_norm(self.stages[0].main_proj(main_hidden)) # [1,S,d] + self.seed_from_main_x(main_x, positions) + + def seed_from_main_x(self, main_x, positions): + """Seed every stage window from already-projected main hidden rows main_x [1,S,d] (bf16) at + ``positions`` (consecutive). Also keeps the last ``win`` rows (``main_tail``) so a prompt- + boundary snapshot can carry them and a prefix hit resumes with full draft windows.""" + positions = [int(p) for p in positions] + pos = mx.array(np.asarray(positions, np.int64)) + for st in self.stages: + st.attn.seed(main_x, pos) + tail = getattr(self, "_main_tail", None) + if tail is None or not positions or tail[1] != positions[0]: + tail = (BoundedWindow(self.stages[0].attn.win), positions[0] if positions else 0) + object.__setattr__(self, "_main_tail", tail) + tail[0].append(main_x.astype(mx.bfloat16)) + object.__setattr__(self, "_main_tail", (tail[0], positions[-1] + 1 if positions else tail[1])) + # Submit without a host sync: the windows are next read by draft(), which evaluates them; a + # blocking eval here cost one GPU round-trip per committed step (AR mode most of all). + mx.async_eval([st.attn.window.buf for st in self.stages] + [self._main_tail[0].buf]) + + def main_tail(self): + """(main_x [1,<=win,d] bf16, first_position) of the last committed positions, or None.""" + tail = getattr(self, "_main_tail", None) + if tail is None or tail[0].buf is None: + return None + return tail[0].buf, int(tail[1]) - int(tail[0].n) + + def reset_windows(self): + for st in self.stages: + st.attn.window = BoundedWindow(st.attn.win) + object.__setattr__(self, "_main_tail", None) + + def window_checkpoint(self): + return [(st.attn.window.buf, st.attn.window.n) for st in self.stages] + + def window_restore(self, ck): + for st, (buf, n) in zip(self.stages, ck): + st.attn.window.buf, st.attn.window.n = buf, n + + # --- draft one block (release forward_embed -> stages -> forward_head), greedy --- + def draft(self, seed_tok, start_pos): + """Draft from `seed_tok` (the backbone's token for position start_pos+1). Windows must hold + committed KV for [0..start_pos]. Returns (output_ids[bs+1], confidence[bs]) where + output_ids = [seed_tok(@start_pos+1), draft(@start_pos+2), ..., draft(@start_pos+bs+1)].""" + bs = self.bs + ids = np.full(bs, self.noise, np.int32) + ids[0] = seed_tok + x = self.embed(mx.array(ids)[None]) # [1,bs,d] + x = mx.repeat(x[:, :, None, :], self.hc, axis=2) # [1,bs,hc,d] + pre_mix = mx.zeros((1, bs, self.hc), mx.float32) + pre_mix[..., 0] = 1.0 + positions = mx.arange(start_pos + 1, start_pos + 1 + bs) + for st in self.stages: + x, pre_mix = st.forward(x, pre_mix, positions) + last = self.stages[-1] + xc = _hc_pre(x, pre_mix) # [1,bs,d] (pre-norm; confidence reads this) + logits = self.head(last.norm(xc)).astype(mx.float32)[0] # [bs, vocab] + # Markov head, autoregressive over the block. The f32 head is cast ONCE (it was re-cast from + # bf16 -- vocab x rank, ~130 MB -- on every one of the bs steps), and the chain stays on the + # device: each step's argmax indexes the next embedding without a host round-trip, so the + # whole block costs one sync instead of bs. + drafted, me = markov_chain(logits, last.markov_embed, self._markov_head_t(), seed_tok) + conf = (mx.concatenate([xc[0], me], axis=-1) @ last.conf_proj.T)[:, 0] # [bs] + mx.eval(drafted, conf) + return [int(seed_tok)] + [int(t) for t in drafted.tolist()], conf + + def _markov_head_t(self): + last = self.stages[-1] + cached = getattr(self, "_markov_head_t_cache", None) + if cached is None or cached[0] is not last.markov_head: + t = last.markov_head.astype(mx.float32).T + mx.eval(t) + cached = (last.markov_head, t) + # plain attribute, not a Module child (keeps it out of parameters()) + object.__setattr__(self, "_markov_head_t_cache", cached) + return cached[1] + + +# --------------------------------------------------------------------------- loading +def _to_bf16(sh: Shards, name): + return sh.dequant(name, mx.bfloat16) + + +def _quant_experts(sh: Shards, stage, mat, n_experts, bits=4): + """Stack the per-expert bf16 weights for one projection and quantize to `bits` (SwitchProj layout).""" + qs, ss, bsL = [], [], [] + for e in range(n_experts): + w = sh.dequant(f"mtp.{stage}.ffn.experts.{e}.{mat}.weight", mx.bfloat16) + qw, s, b = mx.quantize(w, group_size=GROUP_SIZE, bits=bits) + qs.append(qw); ss.append(s); bsL.append(b) + if e % 32 == 31: + mx.eval(qs[-1], ss[-1], bsL[-1]) + return mx.stack(qs), mx.stack(ss), mx.stack(bsL) + + +class _DictShards: + """Shards-compatible view over an in-memory ``{name: mx.array}`` dict (the prestacked + ``dspark/`` subdir). Only the accessors ``load_dspark`` uses are implemented.""" + + def __init__(self, d: dict): + self.d = d + + def __contains__(self, name) -> bool: + return name in self.d + + def to_mx(self, name): + return self.d[name] + + def dequant(self, name, dtype=mx.bfloat16): + return self.d[name].astype(dtype) + + +def _resolve_dspark_file(path: Path): + """Return the prestacked draft safetensors inside a bundle, or None (use source shards).""" + for cand in (path / "dspark" / "dspark.safetensors", path / "dspark.safetensors"): + if cand.exists(): + return cand + return None + + +def load_dspark(source_dir, args, embed, head): + """Load the dSpark draft head. Prefers a bundle's self-contained ``dspark/`` subdir + (routed experts already stacked + 4-bit); otherwise reads the raw ``mtp.*`` from the + source model shards and quantizes experts on the fly. Both paths are byte-identical.""" + path = Path(source_dir).expanduser() + ds_file = _resolve_dspark_file(path) + if ds_file is not None: + sh = _DictShards(mx.load(str(ds_file))) + else: + sh = Shards(path, allow_missing=True) + ds = DSpark(args, embed, head) + n_experts = args.raw["dspark_n_routed_experts"] + for i, st in enumerate(ds.stages): + p = f"mtp.{i}" + a = st.attn + a.wq_a.weight = _to_bf16(sh, f"{p}.attn.wq_a.weight") + a.wq_b.weight = _to_bf16(sh, f"{p}.attn.wq_b.weight") + a.wkv.weight = _to_bf16(sh, f"{p}.attn.wkv.weight") + a.wo_b.weight = _to_bf16(sh, f"{p}.attn.wo_b.weight") + woa = _to_bf16(sh, f"{p}.attn.wo_a.weight") # [groups*o_lora_rank, (H/groups)*head_dim] + a.wo_a = woa.reshape(a.n_groups, a.o_lora_rank, -1) + a.q_norm.weight = _to_bf16(sh, f"{p}.attn.q_norm.weight") + a.kv_norm.weight = _to_bf16(sh, f"{p}.attn.kv_norm.weight") + a.attn_sink = sh.to_mx(f"{p}.attn.attn_sink").astype(mx.float32) + st.attn_norm.weight = _to_bf16(sh, f"{p}.attn_norm.weight") + st.ffn_norm.weight = _to_bf16(sh, f"{p}.ffn_norm.weight") + for which in ("attn", "ffn"): + setattr(st, f"hc_{which}_fn", sh.to_mx(f"{p}.hc_{which}_fn").astype(mx.float32)) + setattr(st, f"hc_{which}_base", sh.to_mx(f"{p}.hc_{which}_base").astype(mx.float32)) + setattr(st, f"hc_{which}_scale", sh.to_mx(f"{p}.hc_{which}_scale").astype(mx.float32)) + m = st.moe + m.gate_w = _to_bf16(sh, f"{p}.ffn.gate.weight") + m.gate_bias = sh.to_mx(f"{p}.ffn.gate.bias").astype(mx.float32) + m.sw1.weight = _to_bf16(sh, f"{p}.ffn.shared_experts.w1.weight") + m.sw3.weight = _to_bf16(sh, f"{p}.ffn.shared_experts.w3.weight") + m.sw2.weight = _to_bf16(sh, f"{p}.ffn.shared_experts.w2.weight") + for proj, mat in (("gate_proj", "w1"), ("up_proj", "w3"), ("down_proj", "w2")): + pre = f"{p}.ffn.experts.{proj}.weight" + if pre in sh: # bundle dspark/ subdir: experts already stacked + quantized + qw = sh.to_mx(pre) + s = sh.to_mx(f"{p}.ffn.experts.{proj}.scales") + b = sh.to_mx(f"{p}.ffn.experts.{proj}.biases") + else: # source shards: stack + quantize per-expert on the fly + qw, s, b = _quant_experts(sh, i, mat, n_experts) + sp = getattr(m, proj) + sp.weight, sp.scales, sp.biases = qw, s, b + if i == 0: + st.main_proj.weight = _to_bf16(sh, f"{p}.main_proj.weight") + st.main_norm.weight = _to_bf16(sh, f"{p}.main_norm.weight") + if i == ds.n_stages - 1: + st.norm.weight = _to_bf16(sh, f"{p}.norm.weight") + st.markov_embed = _to_bf16(sh, f"{p}.markov_head.embed.weight") + st.markov_head = _to_bf16(sh, f"{p}.markov_head.head.weight") + st.conf_proj = sh.to_mx(f"{p}.confidence_head.proj.weight").astype(mx.float32) + mx.eval(st.parameters()) + return ds + + +# --------------------------------------------------------------------------- accept/reject loop +def _accepts_kw(m, name: str) -> bool: + """True if the backbone's forward takes keyword ``name`` (DSV41 does; test fakes may not).""" + import inspect + + try: + params = inspect.signature(m.forward).parameters + except (TypeError, ValueError): + return False + return name in params or any(p.kind is p.VAR_KEYWORD for p in params.values()) + + +def _accepts_lookahead(m) -> bool: + return _accepts_kw(m, "engram_lookahead") + + +def _session_arrays(sess): + """Every live cache array of a runtime Session / engine _SeqState (for a per-chunk eval).""" + out = [] + for c in getattr(sess, "caches", ()) or (): + for a in (getattr(c, "window", None), getattr(c, "pend_kv", None), getattr(c, "pend_score", None)): + if a is not None: + out.append(a) + for q in (getattr(c, "compress_kv", None), getattr(c, "index_k", None)): + if q is None: + continue + for a in (getattr(q, "wq", None), getattr(q, "scales", None), getattr(q, "biases", None), + getattr(q, "buf", None)): + if a is not None: + out.append(a) + return out + +class _Governor: + """Wall-clock AR/speculation governor for DSparkRunner (adaptive mode). + + Tracks an EMA of seconds per EMITTED token for speculative steps and for AR steps, each measured + from step start to the next step start (i.e. including every sync, draft, verify and commit + forward, and the consumer's time between yields, which is the same per token for both modes). + + - speculate while spec s/token < AR s/token; otherwise take AR steps; + - in AR mode, one speculative PROBE every ``probe_every`` AR tokens re-measures speculation + (a probe after an AR stretch replaces the stale spec estimate instead of being averaged into + it, so one good probe is enough to switch back); + - in spec mode, one AR step every ``ar_probe_every`` spec steps re-measures AR (AR cost grows + with context length); + - an unmeasured AR cost is measured after the first two spec steps. + There is no terminal state: both estimates keep being refreshed, so neither mode can latch.""" + + def __init__(self, probe_every=16, ar_probe_every=64, alpha=0.3, warmup_spec=2): + self.probe_every, self.ar_probe_every = int(probe_every), int(ar_probe_every) + self.alpha, self.warmup_spec = float(alpha), int(warmup_spec) + self.spec = None # EMA seconds / emitted token, speculative steps + self.ar = None # EMA seconds / emitted token, AR steps + self.ar_mode = False # currently preferring AR + self.since_probe = 0 # AR tokens since the last speculative probe (AR mode) + self.since_ar = 0 # spec steps since the last AR measurement (spec mode) + self.spec_stale = False # next spec measurement replaces the estimate + self.n_spec = 0 + + def _ema(self, old, x, replace=False): + return x if (old is None or replace) else (1 - self.alpha) * old + self.alpha * x + + def record(self, mode, seconds, emitted): + per = float(seconds) / max(1, int(emitted)) + if mode == "spec": + self.spec = self._ema(self.spec, per, self.spec_stale) + self.spec_stale = False + self.n_spec += 1 + self.since_ar += 1 + else: + self.ar = self._ema(self.ar, per) + self.since_ar = 0 + if self.ar_mode: + self.since_probe += 1 + if self.spec is not None and self.ar is not None: + slower = self.spec >= self.ar + if slower and not self.ar_mode: + self.ar_mode, self.since_probe = True, 0 + elif not slower and self.ar_mode: + self.ar_mode = False + + def choose(self) -> str: + if self.ar_mode: + if self.since_probe >= self.probe_every: + self.since_probe = 0 + self.spec_stale = True + return "spec" # probe + return "ar" + if self.ar is None and self.n_spec >= self.warmup_spec: + return "ar" # first AR measurement + if self.ar is not None and self.since_ar >= self.ar_probe_every: + return "ar" # refresh the AR estimate + return "spec" + + +class DSparkRunner: + """Speculative greedy decode: output is the backbone's greedy tokens, accepting a block of + dSpark drafts per backbone verify step. Rollback is checkpoint/restore of the (ref-based) caches + plus a re-feed of exactly the accepted tokens -- correct regardless of the backbone cache's + internal compression.""" + + def __init__(self, dsv41, dspark, width=None, conf_gate=None, + adaptive=False, probe_every=16, ar_probe_every=64, + ema_alpha=0.3, clock=time.perf_counter): + self.m = dsv41 + self.ds = dspark + self.width = width or dspark.bs + self.conf_gate = conf_gate # if set, truncate the proposed block where confidence drops below it + # Adaptive mode = a WALL-CLOCK governor plus acceptance-tracked width; never a fixed depth and + # never a permanent latch (see _Governor). Width W = clamp(round(bs * accept_ema), 1, bs) + # shrinks AND grows with acceptance inside the draft head's physical size ``bs``. Whether a + # step speculates at all is decided by measured seconds per emitted token: speculation runs + # only while it is faster than the measured AR step; otherwise AR steps, with a speculative + # probe every ``probe_every`` AR tokens and an AR re-measure every ``ar_probe_every`` spec + # steps (AR cost grows with context, so it is never measured once and trusted forever). + self.adaptive = adaptive + self.probe_every = max(1, int(probe_every)) + self.ar_probe_every = max(1, int(ar_probe_every)) + self.ema_alpha = float(ema_alpha) + self.clock = clock + # Partial accepts commit the verify's kept prefix in place (DSV41.commit_prefix): no restore and + # no second forward over the kept tokens (each extra forward streams the routed experts again, + # ~0.14 s at prefill widths and a full decode step at verify widths). A backbone without + # commit_prefix (test doubles) takes the restore + re-forward commit. + self._capture_kw = {"capture_verify": True} if hasattr(dsv41, "commit_prefix") else {} + + def _greedy(self, logits): + return int(mx.argmax(logits)) + + def stream(self, prompt_ids, max_new, eos_ids=(), stats=None, session=None, start_offset=0): + """Greedy speculative decode as a GENERATOR: yields committed backbone-greedy tokens one at a + time (so a server can stream and check stops between/within accepted blocks). The yielded + sequence is identical to ``generate()['tokens']``. Owns its own runtime ``Session`` + + checkpoint/restore. If ``stats`` (dict) is passed it is filled with steps/drafted/accepted/ + emitted. ``session`` lets the engine spec-decode generator drive its OWN cache (the engine + DeepseekV41Cache list, duck-typing the runtime Session) so DSpark output populates the prefix + cache; with a restored prefix, ``start_offset`` skips the cached prompt and prefills only the + tail. (See DECODE_DSPARK_METHODS.md M1.)""" + sess, pending, c = self.prefill(prompt_ids, session=session, start_offset=start_offset) + yield from self.decode_stream(sess, pending, c, max_new, eos_ids=eos_ids, stats=stats) + + # Prefill chunk size (tokens per backbone forward). Matches the engine's default prefill_step_size; + # the engine passes its configured value explicitly. + PREFILL_CHUNK = 2048 + + def prefill(self, prompt_ids, session=None, start_offset=0, on_boundary=None, chunk_size=None, + clear_cache=True): + """Forward ``prompt_ids`` into ``session`` (a runtime Session or the engine's _SeqState duck + type) and seed the draft windows, returning (session, pending_logits, c), c = last prompt pos. + + ``prompt_ids`` is forwarded AS GIVEN from the session's current absolute position ``sess.pos``: + on a prefix HIT the scheduler already restored the cache and passes only the UNCACHED TAIL. + ``start_offset`` is accepted for back-compat but ignored -- the session position is authoritative. + + Shape of the prefill (same as the engine's AR SingleBatchGenerator, so AR and DSpark produce the + same cache and a prefix hit continues either): + 1. prompt[:-1] in ``chunk_size`` forwards, each materialized (+ ``mx.clear_cache``) so peak + memory is one chunk's activations, not the whole prompt's lazy graph; + 2. ``on_boundary(sess)`` at exactly the N-1 prompt boundary -- the state the prefix cache keys + on (the scheduler stores it under prompt[:-1] and re-feeds the last token on a hit). The + old code snapshotted AFTER the last token, so every hit restored N tokens under an N-1 + key and re-fed the last prompt token at position N; + 3. the last prompt token in its own forward -> the pending logits for c+1. + Draft windows are seeded only from the last ``win`` positions (all attend can read).""" + m, ds = self.m, self.ds + sess = session if session is not None else m.new_session() + ds.reset_windows() + start = int(getattr(sess, "pos", 0) or 0) # absolute position of the (possibly restored) cache + # Prefix hit: a DSpark-produced boundary snapshot carries the projected main hidden of its last + # `win` positions; reseed the draft windows from it so drafting after a hit sees a full window + # instead of only the uncached tail. Used only when it ends exactly at the restored position. + dtail = getattr(sess, "dspark_tail", None) + if dtail is not None and start > 0: + tail_x, tail_p0 = dtail + if tail_x is not None and int(tail_p0) + int(tail_x.shape[1]) == start: + ds.seed_from_main_x(tail_x, range(int(tail_p0), start)) + ids = [int(t) for t in prompt_ids] + if not ids: + raise ValueError("DSparkRunner.prefill needs at least one prompt token") + end = start + len(ids) + win = int(ds.stages[0].attn.win) + seed_from = max(start, end - win) # first absolute position whose hidden seeds the windows + step = max(1, int(chunk_size or self.PREFILL_CHUNK)) + body = ids[:-1] + p = start + for i in range(0, len(body), step): + piece = body[i:i + step] + # The next forward's tokens (the next chunk, or the final prompt token): its Engram rows + # are read from SSD while this chunk computes (DSV41.forward engram_lookahead). + nxt = body[i + step:i + 2 * step] or ids[-1:] + kw = {"engram_lookahead": nxt} if _accepts_lookahead(m) else {} + if _accepts_kw(m, "prompt_end"): + kw["prompt_end"] = end - 1 # the body ends at the N-1 boundary (suffix pruning) + if p + len(piece) > seed_from: + logits, mh = m.forward(piece, sess, all_logits=False, return_hidden=True, **kw) + lo = max(0, seed_from - p) + ds.seed_windows(mh[None, lo:], range(p + lo, p + len(piece))) + mx.eval(logits, _session_arrays(sess), [st.attn.window.buf for st in ds.stages]) + else: + logits = m.forward(piece, sess, all_logits=False, **kw) + mx.eval(logits, _session_arrays(sess)) + p += len(piece) + if clear_cache and hasattr(mx, "clear_cache"): + mx.clear_cache() + if on_boundary is not None: + on_boundary(sess) # exact N-1 prompt boundary (pos == end - 1) + logits, mh = m.forward(ids[-1:], sess, all_logits=False, return_hidden=True) + ds.seed_windows(mh[None], range(end - 1, end)) + return sess, logits, end - 1 + + def decode_stream(self, sess, pending, c, max_new, eos_ids=(), stats=None): + """Greedy speculative decode generator from a prefilled (sess, pending, c). Yields committed + backbone-greedy tokens one at a time (the same tokens as plain greedy decode, up to the usual + floating-point caveat that a multi-token verify forward and a one-token decode forward are + not bitwise identical, so a near-tie argmax can in principle differ); no-refeed fast path. + In adaptive mode a wall-clock governor picks AR or speculative steps (see _Governor).""" + m, ds = self.m, self.ds + n_emitted = n_steps = n_drafted = n_accepted = n_spec = n_ar = 0 + eos_ids = set(int(e) for e in eos_ids) + accept_ema = 1.0 + gov = _Governor(self.probe_every, self.ar_probe_every, self.ema_alpha) if self.adaptive else None + last = None # (mode, emitted, t_start) of the previous step, closed at the next step start + + def _rec(): + if stats is not None: + stats.update(steps=n_steps, drafted=n_drafted, accepted=n_accepted, emitted=n_emitted, + spec_steps=n_spec, ar_steps=n_ar) + if gov is not None: + stats.update(spec_s_per_tok=gov.spec, ar_s_per_tok=gov.ar) + + while n_emitted < max_new: + n_steps += 1 + p0 = self._greedy(pending) # backbone truth for c+1 (syncs the previous step) + now = self.clock() + if gov is not None and last is not None: # previous step's work is complete only now + gov.record(last[0], now - last[2], last[1]) + mode = gov.choose() if gov is not None else "spec" + if mode == "ar": + # One backbone forward (bare greedy). return_hidden + an async seed keep the draft + # windows current so a later speculative step resumes from correct state. + n_ar += 1 + plog, pmh = m.forward([p0], sess, all_logits=False, return_hidden=True) + ds.seed_windows(pmh[None], range(c + 1, c + 2)) + c += 1 + pending = plog + last = ("ar", 1, now) + yield p0; n_emitted += 1 + if (eos_ids and p0 in eos_ids) or n_emitted >= max_new: + _rec(); return + continue + n_spec += 1 + draft_ids, conf = self.ds.draft(p0, c) # output_ids[0]=p0; [1..bs] draft c+2..c+bs+1 + W = self.width # number of draft tokens to verify (1..bs) + if self.adaptive: # depth tracks acceptance (shrinks AND grows) + W = max(1, min(self.width, round(self.width * accept_ema))) + if self.conf_gate is not None: + cg = (conf >= self.conf_gate).tolist() + W = 1 + while W < self.width and cg[W - 1]: + W += 1 + feed = [p0] + draft_ids[1 : 1 + W] # [p0,d1..dW] at positions c+1..c+1+W + n_drafted += W + ck = sess.checkpoint() + vlog, vmh = m.forward(feed, sess, all_logits=True, return_hidden=True, # vlog[j] predicts c+2+j + **self._capture_kw) + truth = [int(x) for x in mx.argmax(vlog, axis=-1).tolist()] # truth for c+2 .. c+2+W + k = 0 + for j in range(W): # draft d_{j+1}=draft_ids[1+j] @ c+2+j vs truth[j] + if draft_ids[1 + j] == truth[j]: + k += 1 + else: + break + n_accepted += k + accept_ema = 0.7 * accept_ema + 0.3 * (k / max(1, W)) # update rolling acceptance + if k == W: + # whole block accepted: the verify forward already wrote exactly-correct causal KV for + # every position (no rejected tail to undo), so skip the restore+refeed commit forward + # -> 1 backbone forward this step. truth[W] (the free bonus) becomes the next p0. + emit = [p0] + draft_ids[1 : 1 + W] # W+1 accepted tokens; bonus deferred to next p0 + ds.seed_windows(vmh[None], range(c + 1, c + 1 + len(emit))) + c += len(emit) + pending = vlog[W] # predicts c+1 (== truth[W], next step's p0) + elif k > 0 and self._capture_kw: + # partial accept: keep the verify's first k+1 tokens (p0, d1..dk) and drop the rejected + # tail without a second forward (DSV41.commit_prefix replays only the kept tokens' + # window/compressor inputs onto the checkpoint). truth[k] becomes the next p0. + emit = [p0] + draft_ids[1 : 1 + k] + m.commit_prefix(sess, ck, len(emit)) + ds.seed_windows(vmh[None, : len(emit)], range(c + 1, c + 1 + len(emit))) + c += len(emit) + pending = vlog[k] # predicts c+1 (== truth[k]) + else: + emit = [p0] + draft_ids[1 : 1 + k] + [truth[k]] # all backbone-greedy truth, c+1..c+k+2 + sess.restore(ck) # undo the W+1-token verify (rejected tail present) + flog, fmh = m.forward(emit, sess, all_logits=True, return_hidden=True) # commit exactly emit + ds.seed_windows(fmh[None], range(c + 1, c + 1 + len(emit))) + c += len(emit) + pending = flog[-1] # predicts c+1 again + last = ("spec", len(emit), now) + for t in emit: + yield t; n_emitted += 1 + if (eos_ids and t in eos_ids) or n_emitted >= max_new: + _rec(); return + _rec() + + def generate(self, prompt_ids, max_new, eos_ids=(), verbose=False): + """Batch convenience wrapper over stream(): collect all tokens + report acceptance/speedup.""" + stats = {} + t0 = time.time() + out = list(self.stream(prompt_ids, max_new, eos_ids, stats)) + dt = time.time() - t0 + return { + "tokens": out, + "steps": stats.get("steps", 0), + "drafted": stats.get("drafted", 0), + "accepted": stats.get("accepted", 0), + "accept_rate": stats.get("accepted", 0) / max(1, stats.get("drafted", 0)), + "mean_emit": len(out) / max(1, stats.get("steps", 1)), + "seconds": dt, + "tok_per_s": len(out) / dt if dt else 0.0, + } diff --git a/jang-tools/jang_tools/dsv41/engram.py b/jang-tools/jang_tools/dsv41/engram.py new file mode 100644 index 00000000..64df2af0 --- /dev/null +++ b/jang-tools/jang_tools/dsv41/engram.py @@ -0,0 +1,263 @@ +"""Engram for DSV4.1: n-gram hashing (CPU) + disk-resident FP8 tables. + +Port of the release's inference/engram.py. The two tables are ~98 GB each +(384M rows x 256 FP8 bytes + 8 E8M0 scale bytes per row). Each position needs +only (max_ngram_size - 1) * n_heads = 24 rows per Engram layer, so the tables +stay in their original safetensors shards and are read in place by 16 concurrent +memmap gathers: the OS page cache holds whatever is hot, and none of it is wired +GPU memory. +""" + +from __future__ import annotations + +import hashlib +import mmap +from concurrent.futures import ThreadPoolExecutor +from dataclasses import dataclass +from pathlib import Path + +import mlx.core as mx +import numpy as np + +from jang_tools.dsv41.st_io import Shards, e8m0_to_float + + +def _is_prime(n: int) -> bool: + if n < 2: + return False + if n % 2 == 0: + return n == 2 + i = 3 + while i * i <= n: + if n % i == 0: + return False + i += 2 + return True + + +def _next_prime(start: int, seen: set[int]) -> int: + c = start + 1 + while not _is_prime(c) or c in seen: + c += 1 + return c + + +@dataclass(frozen=True) +class EngramLayout: + max_ngram_size: int + layer_ids: tuple[int, ...] + num_embeddings: tuple[int, ...] + primes: np.ndarray # [n_layers, max_ngram_size - 1, n_heads] int64 + n_heads: int + head_dim: int + + @classmethod + def from_config(cls, cfg: dict) -> "EngramLayout": + layer_ids = tuple(cfg["engram_layer_ids"]) + n, heads = cfg["engram_max_ngram_size"], cfg["engram_n_heads"] + seen: set[int] = set() + primes = [] + for _ in layer_ids: + per_ngram = [] + for _ in range(n - 1): + cur, sizes = cfg["engram_vocab_size"] - 1, [] + for _ in range(heads): + cur = _next_prime(cur, seen) + seen.add(cur) + sizes.append(cur) + per_ngram.append(sizes) + primes.append(per_ngram) + layout = cls(n, layer_ids, tuple(cfg["engram_num_embeddings"]), np.array(primes, np.int64), heads, cfg["engram_head_dim"]) + # bucket ranges tile each table exactly + assert tuple(int(p.sum()) for p in layout.primes) == layout.num_embeddings, "engram prime layout mismatch" + return layout + + +def build_compressed_token_map(tokenizer_json: Path, cache_dir: Path | None = None) -> tuple[np.ndarray, int]: + """Same normalization as the release: NFKC/NFD/strip accents/lowercase/collapse whitespace.""" + digest = hashlib.sha256(tokenizer_json.read_bytes()).hexdigest()[:16] + cache = (cache_dir or Path.home() / ".cache" / "jang_dsv41") / f"engram_token_map_{digest}.npy" + if cache.exists(): + lookup = np.load(cache) + return lookup, int(lookup.max()) + 1 + + from tokenizers import Regex, Tokenizer, normalizers + + sentinel = "" + normalizer = normalizers.Sequence([ + normalizers.NFKC(), + normalizers.NFD(), + normalizers.StripAccents(), + normalizers.Lowercase(), + normalizers.Replace(Regex(r"[ \t\r\n]+"), " "), + normalizers.Replace(Regex(r"^ $"), sentinel), + normalizers.Strip(), + normalizers.Replace(sentinel, " "), + ]) + tok = Tokenizer.from_file(str(tokenizer_json)) + n = tok.get_vocab_size(with_added_tokens=True) + key_to_new: dict[str, int] = {} + lookup = np.zeros(n, np.int64) + for tid in range(n): + text = tok.decode([tid], skip_special_tokens=False) + if "�" in text: + key = tok.id_to_token(tid) + else: + norm = normalizer.normalize_str(text) + key = norm if norm else text + lookup[tid] = key_to_new.setdefault(key, len(key_to_new)) + cache.parent.mkdir(parents=True, exist_ok=True) + np.save(cache, lookup) + return lookup, len(key_to_new) + + +def hash_multipliers(layer_ids, max_ngram_size: int, vocab: int) -> np.ndarray: + bound = max(1, (np.iinfo(np.int64).max // vocab) // 2) + rows = [] + for lid in layer_ids: + g = np.random.default_rng(10007 * lid) + rows.append(g.integers(low=0, high=bound, size=(max_ngram_size,), dtype=np.int64) * 2 + 1) + return np.stack(rows) + + +class NgramHasher: + """Per-sequence n-gram hash ids. Batch size 1; holds the compressed history across calls.""" + + DEAD = -1 + + def __init__(self, cfg: dict, layout: EngramLayout, tokenizer_json: Path): + self.layout = layout + self.token_map, vocab = build_compressed_token_map(tokenizer_json) + assert vocab == cfg["engram_compressed_vocab_size"], (vocab, cfg["engram_compressed_vocab_size"]) + self.pad_id = int(self.token_map[cfg["engram_pad_token_id"]]) + flat = layout.primes.reshape(len(layout.layer_ids), -1) + self.offsets = np.concatenate([np.zeros((flat.shape[0], 1), np.int64), np.cumsum(flat, 1)[:, :-1]], 1) + self.multipliers = hash_multipliers(layout.layer_ids, layout.max_ngram_size, vocab) + self.history = np.zeros(0, np.int64) + + def reset(self): + self.history = np.zeros(0, np.int64) + + def __call__(self, input_ids: np.ndarray, start_pos: int) -> np.ndarray: + """input_ids [L] -> hash ids [L, n_engram_layers, (max_ngram-1)*n_heads] (int64).""" + out, self.history = self.hash(input_ids, start_pos, self.history) + return out + + def hash(self, input_ids: np.ndarray, start_pos: int, history: np.ndarray, keep: np.ndarray | None = None): + """Stateless form: returns (hash ids, updated compressed-token history) for one sequence. + keep [L] bool (True = real text): image tokens (keep=False) become DEAD so they take part in + no n-gram and block n-grams that would span them (matches the release engram_mask).""" + comp = self.token_map[input_ids] + if keep is not None: + comp = np.where(keep, comp, self.DEAD) + history = np.concatenate([history[:start_pos], comp]) + L, n = len(input_ids), self.layout.max_ngram_size + pos = np.arange(start_pos, start_pos + L) + toks, blocked = [], np.zeros(L, bool) + for shift in range(n): + src = history[np.clip(pos - shift, 0, None)] + blocked = blocked | (pos < shift) | (src == self.DEAD) + toks.append(np.where(blocked, self.pad_id, src)) + toks = np.stack(toks, -1) # [L, n] + prod = toks[:, None, :] * self.multipliers[None] # [L, layers, n] + rolling, out = prod[..., 0], [] + for i in range(1, n): + rolling = np.bitwise_xor(rolling, prod[..., i]) + out.append(rolling[..., None] % self.layout.primes[None, :, i - 1, :]) + return np.concatenate(out, -1) + self.offsets[None], history + + +# Cold rows are random 256-byte reads spread over ~98 GB per table, so throughput is set by how +# many reads are in flight. Measured on cold rows: a single-thread memmap gather (one page fault +# at a time) reads ~8-11k rows/s; 16 threads each gathering a slice of the memmap read ~110k +# rows/s (more lanes contend on the VM map and slow down). np.take releases the GIL, so the main +# thread keeps building the MLX graph while the lanes fault rows in; 64-lane os.pread reached +# ~130k rows/s but held the GIL per row and slowed graph building during a pipelined prefill. +# This 16x concurrency is what took cold 1k-token prefill from 68 to ~600 pp/s. +_TAKE_LANES = 16 +_TAKE_POOL = ThreadPoolExecutor(_TAKE_LANES, thread_name_prefix="engram-take") +# Prefetch orchestration runs on its own pool so a waiting prefetch never holds an I/O lane. +_PREFETCH_POOL = ThreadPoolExecutor(4, thread_name_prefix="engram-prefetch") + + +class DiskEngramTable: + """One layer's FP8 table, read from its safetensors shard in place. + + Rows are read concurrently for every batch size, decode's few rows and prefill's tens of + thousands alike: the SSD serves random small reads in parallel, while a single gather through + the memory map takes its page faults one at a time. The OS page cache keeps hot n-grams; + nothing is wired. + """ + + def __init__(self, shards: Shards, layer_id: int): + w = shards.meta[f"layers.{layer_id}.engram.embed.weight"] + s = shards.meta[f"layers.{layer_id}.engram.embed.scale"] + assert w.dtype == "F8_E4M3" and s.dtype == "F8_E8M0", (w.dtype, s.dtype) + assert w.path == s.path + self.rows = np.memmap(w.path, np.uint8, "r", offset=w.offset, shape=w.shape) + self.scales = np.memmap(s.path, np.uint8, "r", offset=s.offset, shape=s.shape) + # Random rows: read-ahead around each fault only wastes SSD bandwidth (~1.5x more cold + # rows/s with MADV_RANDOM). + for mm in (self.rows, self.scales): + try: + mm._mmap.madvise(mmap.MADV_RANDOM) + except (AttributeError, OSError, ValueError): + pass + self.dim = w.shape[1] + self.sdim = s.shape[1] + self.block = w.shape[1] // s.shape[1] + + def _gather(self, uniq: np.ndarray): + """Rows and scales for sorted unique row ids: _TAKE_LANES slices gathered from the memmap + concurrently into preallocated buffers (one page fault in flight per lane).""" + n = len(uniq) + rows = np.empty((n, self.dim), np.uint8) + scales = np.empty((n, self.sdim), np.uint8) + step = max(1, -(-n // _TAKE_LANES)) + + def take(lo): + u = uniq[lo : lo + step] + np.take(self.rows, u, axis=0, out=rows[lo : lo + step]) + np.take(self.scales, u, axis=0, out=scales[lo : lo + step]) + + list(_TAKE_POOL.map(take, range(0, n, step))) + return rows, scales + + def read(self, ids: np.ndarray): + """Host-side half of lookup (thread-safe, no MLX calls): (inverse map, rows, scales).""" + uniq, inv = np.unique(ids.reshape(-1), return_inverse=True) + rr, ss = self._gather(uniq) + return inv, rr, ss + + def prefetch(self, ids: np.ndarray, after=None): + """Start reading ids' rows in the background (once the future `after`, if given, is done); + pass the returned future's result to `finish`.""" + def run(): + if after is not None: + after.result() + return self.read(ids) + return _PREFETCH_POOL.submit(run) + + def lookup(self, ids: np.ndarray) -> mx.array: + """ids [...] -> bf16 rows [..., dim]. Duplicate ids are read once.""" + return self.finish(ids.shape, self.read(ids)) + + def finish(self, shape, got) -> mx.array: + """Dequantize what `read` returned into bf16 rows of `shape + (dim,)`.""" + inv, rr, ss = got + r = mx.array(rr) + s = mx.array(ss) + n = rr.shape[0] + vals = mx.from_fp8(r, dtype=mx.float32).reshape(n, -1, self.block) * e8m0_to_float(s)[..., None] + vals = vals.reshape(n, self.dim).astype(mx.bfloat16) + return vals[mx.array(inv.astype(np.int32))].reshape(*shape, self.dim) + + +def open_engram_tables(engram_dir: Path, layer_ids) -> dict[int, DiskEngramTable]: + engram_dir = Path(engram_dir) + index = "engram.safetensors.index.json" if (engram_dir / "engram.safetensors.index.json").exists() else "none" + shards = Shards(engram_dir, index_name=index) + missing = [l for l in layer_ids if f"layers.{l}.engram.embed.weight" not in shards] + if missing: + raise FileNotFoundError(f"engram tables for layers {missing} not found under {engram_dir}") + return {l: DiskEngramTable(shards, l) for l in layer_ids} diff --git a/jang-tools/jang_tools/dsv41/eval_mtp_ar.py b/jang-tools/jang_tools/dsv41/eval_mtp_ar.py new file mode 100644 index 00000000..272eca18 --- /dev/null +++ b/jang-tools/jang_tools/dsv41/eval_mtp_ar.py @@ -0,0 +1,60 @@ +"""DSpark MTP vs plain autoregressive (AR): across diverse prompts (easy/structured/low-accept), +measure greedy tok/s and speculative tok/s, report the spec/AR ratio. Verifies speculative never +drops below AR (ratio >= 1.0). Tests fixed width and a confidence-gated/adaptive runner (conf_gate +truncates the proposed block where draft confidence drops, protecting the AR floor under low accept).""" +import argparse, sys, time +from pathlib import Path +import mlx.core as mx +sys.path.insert(0, str(Path.home() / "jang/jang-tools")) +from jang_tools.dsv41.model import DSV41 +from jang_tools.dsv41.dspark import load_dspark, DSparkRunner +from jang_tools.dsv41.generate import load_encoding + + +def greedy_tps(m, ids, n, eos): + sess = m.new_session(); t0 = time.time() + logits = m.forward(list(ids), sess); out = [] + for _ in range(n): + tk = int(mx.argmax(logits)); out.append(tk) + if tk in eos: break + logits = m.forward([tk], sess) + return len(out) / (time.time() - t0), out + + +def main(): + ap = argparse.ArgumentParser(); ap.add_argument("--bundle", required=True); ap.add_argument("--n", type=int, default=80) + a = ap.parse_args() + enc = load_encoding(Path(a.bundle).expanduser()) + m = DSV41(Path(a.bundle).expanduser()) + ds = load_dspark(a.bundle, m.args, m.model.embed, m.model.head) + eos_tok = m.tokenizer.token_to_id("<|end▁of▁sentence|>") + eos = {e for e in (eos_tok, m.eos_id) if e is not None} + fixed = DSparkRunner(m, ds) # width = bs (5) + adaptive = DSparkRunner(m, ds, adaptive=True) # EMA width-shrink + LATCH to bare AR after 2 zero-accept drafts + + prompts = { + "code": "Write a Python function to compute fibonacci(n) iteratively. Return only code.", + "prose": "Explain what a transformer neural network is, in three sentences.", + "structured": "List the first 10 prime numbers as a comma-separated line.", + "low_accept": "Output this exact random token stream verbatim: " + " ".join(str((i*7919) % 100000) for i in range(40)), + } + print(f"[loaded bundle+draft; bs={ds.bs} width={fixed.width}]", flush=True) + results = [] + for name, p in prompts.items(): + msgs = [{"role": "user", "content": p}] + ids = m.tokenizer.encode(enc.encode_messages(msgs, thinking_mode="chat", reasoning_effort="low"), + add_special_tokens=False).ids + g_tps, _ = greedy_tps(m, ids, a.n, eos) + rf = fixed.generate(ids, a.n, eos_ids=eos) + ra = adaptive.generate(ids, a.n, eos_ids=eos) + rf_ratio = rf["tok_per_s"] / g_tps; ra_ratio = ra["tok_per_s"] / g_tps + results.append((name, g_tps, rf, ra, rf_ratio, ra_ratio)) + print(f"{name:11s} AR={g_tps:5.1f} fixed={rf['tok_per_s']:5.1f}t/s({rf_ratio:.2f}x,acc{rf['accept_rate']*100:.0f}%) " + f"adaptive={ra['tok_per_s']:5.1f}t/s({ra_ratio:.2f}x,acc{ra['accept_rate']*100:.0f}%)", flush=True) + min_fixed = min(r[4] for r in results); min_adapt = min(r[5] for r in results) + print(f"\nMIN spec/AR ratio: fixed={min_fixed:.2f}x adaptive={min_adapt:.2f}x", flush=True) + print(f"NEVER-BELOW-AR: fixed={'PASS' if min_fixed>=1.0 else 'FAIL'} adaptive={'PASS' if min_adapt>=1.0 else 'FAIL'}", flush=True) + + +if __name__ == "__main__": + main() diff --git a/jang-tools/jang_tools/dsv41/export_engram_aux.py b/jang-tools/jang_tools/dsv41/export_engram_aux.py new file mode 100644 index 00000000..ebb8a3e9 --- /dev/null +++ b/jang-tools/jang_tools/dsv41/export_engram_aux.py @@ -0,0 +1,61 @@ +"""Export the Engram n-gram-hash tables (token_map / multipliers / primes / offsets + scalars) that +the vmlx-SWIFT port needs, so Swift does not reimplement HF-tokenizer normalization. Reuses the proven +jang_tools.dsv41.engram setup (EngramLayout + NgramHasher) and dumps one little safetensors sidecar. + + python export_engram_aux.py + +Swift parses safetensors itself (JSON header + raw bytes); dtypes chosen for easy Swift load: + token_map I32 [vocab] (compressed token id per vocab id; < compressed_vocab) + multipliers I64 [n_layers, max_ngram] + primes I64 [n_layers, max_ngram-1, n_heads] + offsets I64 [n_layers, cols] (cols = (max_ngram-1)*n_heads) + pad_id I64 [1] +Scalars (n_heads, head_dim, max_ngram, layer_ids, compressed_vocab) go in the safetensors __metadata__. +""" +import json, struct, sys +from pathlib import Path +import numpy as np + +bundle = Path(sys.argv[1]).expanduser() +out = Path(sys.argv[2]).expanduser() + +with open(bundle / "config.json") as f: + cfg = json.load(f)["text_config"] +from jang_tools.dsv41.engram import EngramLayout, NgramHasher + +layout = EngramLayout.from_config(cfg) +hasher = NgramHasher(cfg, layout, bundle / "tokenizer.json") + +tensors = { + "token_map": hasher.token_map.astype(np.int32), + "multipliers": hasher.multipliers.astype(np.int64), + "primes": layout.primes.astype(np.int64), + "offsets": hasher.offsets.astype(np.int64), + "pad_id": np.array([hasher.pad_id], np.int64), +} +meta = { + "n_heads": str(layout.n_heads), + "head_dim": str(layout.head_dim), + "max_ngram_size": str(layout.max_ngram_size), + "layer_ids": ",".join(str(x) for x in layout.layer_ids), + "compressed_vocab_size": str(int(hasher.token_map.max()) + 1), + "vocab_size": str(len(hasher.token_map)), +} + +DT = {np.dtype(np.int32): "I32", np.dtype(np.int64): "I64"} +header, blob, off = {}, bytearray(), 0 +for name, arr in tensors.items(): + arr = np.ascontiguousarray(arr) + b = arr.tobytes() + header[name] = {"dtype": DT[arr.dtype], "shape": list(arr.shape), "data_offsets": [off, off + len(b)]} + blob += b + off += len(b) +header["__metadata__"] = meta +hj = json.dumps(header).encode() +pad = (-len(hj)) % 8 +hj += b" " * pad +out.write_bytes(struct.pack("/engram unless --engram-dir points elsewhere +(e.g. the original download directory). +""" + +from __future__ import annotations + +import argparse +import importlib.util +import sys +import time +from pathlib import Path + +import mlx.core as mx +import numpy as np + +from jang_tools.dsv41.model import DSV41 + + +def load_encoding(bundle: Path): + path = bundle / "encoding" / "encoding.py" + spec = importlib.util.spec_from_file_location("dsv41_encoding", path) + mod = importlib.util.module_from_spec(spec) + spec.loader.exec_module(mod) + return mod + + +def sample(logits: mx.array, temperature: float, top_p: float) -> int: + if temperature <= 0: + return int(mx.argmax(logits)) + probs = mx.softmax(logits / temperature, axis=-1) + if top_p < 1.0: + order = mx.argsort(-probs) + sp = probs[order] + keep = mx.cumsum(sp) - sp < top_p + sp = mx.where(keep, sp, 0) + return int(order[mx.random.categorical(mx.log(sp))]) + return int(mx.random.categorical(mx.log(probs))) + + +def generate(m: DSV41, prompt_ids: list[int], max_tokens: int, temperature: float, top_p: float, + stop_ids: set[int], stream=True): + t0 = time.perf_counter() + logits = m.forward(prompt_ids) + mx.eval(logits) + t_prefill = time.perf_counter() - t0 + out: list[int] = [] + printed = "" + t1 = time.perf_counter() + for _ in range(max_tokens): + tok = sample(logits, temperature, top_p) + if tok in stop_ids: + out.append(tok) + break + out.append(tok) + if stream: + text = m.tokenizer.decode(out, skip_special_tokens=False) + if not text.endswith("�"): + sys.stdout.write(text[len(printed):]) + sys.stdout.flush() + printed = text + logits = m.forward([tok]) + t_decode = time.perf_counter() - t1 + if stream: + print() + stats = { + "prompt_tokens": len(prompt_ids), + "prefill_s": round(t_prefill, 3), + "prefill_tok_s": round(len(prompt_ids) / t_prefill, 1), + "gen_tokens": len(out), + "decode_tok_s": round(len(out) / max(t_decode, 1e-9), 2), + "peak_mem_gb": round(mx.get_peak_memory() / 1e9, 2), + } + return out, stats + + +def main(): + ap = argparse.ArgumentParser() + ap.add_argument("--bundle", required=True) + ap.add_argument("--engram-dir") + ap.add_argument("--prompt") + ap.add_argument("--system") + ap.add_argument("--chat", action="store_true") + ap.add_argument("--mode", choices=["thinking", "chat"], default="thinking") + ap.add_argument("--effort", default="high", help="low | high | max | 1-100 (thinking mode)") + ap.add_argument("--max-tokens", type=int, default=2048) + ap.add_argument("--temperature", type=float, default=1.0) + ap.add_argument("--top-p", type=float, default=0.95) + ap.add_argument("--seed", type=int, default=0) + a = ap.parse_args() + + bundle = Path(a.bundle).expanduser() + enc = load_encoding(bundle) + effort = int(a.effort) if a.effort.isdigit() else a.effort + mx.random.seed(a.seed) + + t = time.perf_counter() + m = DSV41(bundle, a.engram_dir) + print(f"[loaded in {time.perf_counter() - t:.1f}s, active memory {mx.get_active_memory() / 1e9:.1f} GB]", + file=sys.stderr) + eos = m.tokenizer.token_to_id("<|end▁of▁sentence|>") + stop = {eos, m.eos_id} + + messages = [] + if a.system: + messages.append({"role": "system", "content": a.system}) + + def turn(user_text: str): + messages.append({"role": "user", "content": user_text}) + prompt = enc.encode_messages(messages, thinking_mode=a.mode, reasoning_effort=effort) + ids = m.tokenizer.encode(prompt, add_special_tokens=False).ids + m.reset() # the release runtime prefills from position 0; re-prefill the whole conversation + out, stats = generate(m, ids, a.max_tokens, a.temperature, a.top_p, stop) + completion = m.tokenizer.decode(out, skip_special_tokens=False) + try: + msg = enc.parse_message_from_completion_text(completion, thinking_mode=a.mode) + except (ValueError, AssertionError, IndexError, KeyError): # not a parseable assistant turn: keep the raw text + msg = {"role": "assistant", "content": completion} + messages.append(msg) + print(f"[{stats}]", file=sys.stderr) + + if a.prompt: + turn(a.prompt) + if a.chat: + while True: + try: + user = input("\n>>> ") + except EOFError: + break + if user.strip() in ("/exit", "/quit"): + break + if user.strip(): + turn(user) + + +if __name__ == "__main__": + main() diff --git a/jang-tools/jang_tools/dsv41/kl_eval.py b/jang-tools/jang_tools/dsv41/kl_eval.py new file mode 100644 index 00000000..752be05a --- /dev/null +++ b/jang-tools/jang_tools/dsv41/kl_eval.py @@ -0,0 +1,109 @@ +"""KL / top-1 quant-quality harness for DSV4.1 JANG bundles. + +Two passes, so two models never need to co-reside (each ~211 GB; a full-precision reference +needs a >256 GB host). On this 256 GB Studio the full-precision source (286 GB fp8) and a +complete RTN reference do not fit, so the reference pass is run elsewhere; this harness makes +KL "ready" — the quant-side dump runs here, and `--mode kl` diffs two dumps offline. + + # pass 1 (reference, on a host where it fits): + python -m jang_tools.dsv41.kl_eval --mode dump --bundle --rows calib/... --out ref.npz + # pass 2 (this quant, here): + python -m jang_tools.dsv41.kl_eval --mode dump --bundle --rows calib/... --out imatrix.npz + # KL (anywhere): + python -m jang_tools.dsv41.kl_eval --mode kl --ref ref.npz --cand imatrix.npz + +`dump` saves, per scored next-token position, the full log-probs (fp16) + the true token, over the +SAME deterministic held-out rows (seed-stable), so the two dumps align position-for-position. +`kl` computes per-position KL(ref||cand), top-1 agreement (ref argmax == cand argmax), and reports +mean/median/p95/p99. +""" +import argparse, json, sys, time +from pathlib import Path +import numpy as np +import mlx.core as mx +sys.path.insert(0, str(Path.home() / "jang/jang-tools")) + + +def _rows(rows_path, n, seed): + from jang_tools.dsv41.calib_generate import DEFAULT_DOMAINS + import random + rows = [json.loads(l) for l in open(rows_path)] + rows = [r for r in rows if r["domain"] not in DEFAULT_DOMAINS] + random.Random(seed).shuffle(rows) + return rows[:n] + + +def dump(a): + import copy + from jang_tools.dsv41.model import DSV41 + from jang_tools.dsv41.generate import load_encoding + enc = load_encoding(Path(a.bundle).expanduser()) + m = DSV41(Path(a.bundle).expanduser(), a.engram_dir) + rows = _rows(a.rows, a.n, a.seed) + logps, trues, row_lens = [], [], [] + t0 = time.time() + for i, r in enumerate(rows): + msgs = copy.deepcopy(r["messages"]) + for mm in msgs: + if mm["role"] == "assistant": + mm.setdefault("reasoning_content", "") + ids = m.tokenizer.encode(enc.encode_messages(msgs, thinking_mode="thinking", reasoning_effort=r["effort"]), + add_special_tokens=False).ids[: a.max_tokens] + if len(ids) < 2: + continue + sess = m.new_session() + logits = m.forward(ids, sess, all_logits=True) + lp = logits[:-1].astype(mx.float32) + lp = lp - mx.logsumexp(lp, axis=-1, keepdims=True) # log-softmax [T-1, V] + mx.eval(lp) + logps.append(np.asarray(lp.astype(mx.float16))) # fp16 to bound disk + trues.append(np.asarray(ids[1:], dtype=np.int32)) + row_lens.append(len(ids) - 1) + del logits, lp, sess; mx.clear_cache() + if (i + 1) % 4 == 0: + print(f" dumped {i+1}/{len(rows)} rows ({time.time()-t0:.0f}s)", flush=True) + LP = np.concatenate(logps, axis=0) # [P, V] fp16 + TR = np.concatenate(trues, axis=0) # [P] + np.savez(a.out, logprobs=LP, true=TR, lens=np.asarray(row_lens), bundle=Path(a.bundle).name) + print(f"wrote {a.out}: {LP.shape[0]} positions x {LP.shape[1]} vocab (fp16), bundle={Path(a.bundle).name}", flush=True) + + +def _pct(x, p): + return float(np.percentile(x, p)) + + +def kl(a): + ref = np.load(a.ref); cand = np.load(a.cand) + rlp = ref["logprobs"].astype(np.float32); clp = cand["logprobs"].astype(np.float32) + assert rlp.shape == clp.shape, f"shape mismatch {rlp.shape} vs {clp.shape} (dumps must use same rows/seed)" + rp = np.exp(rlp) + kl_pos = np.sum(rp * (rlp - clp), axis=-1) # KL(ref||cand) per position [P] + r_arg = rlp.argmax(-1); c_arg = clp.argmax(-1) + top1_agree = float((r_arg == c_arg).mean()) + true = ref["true"] + ref_top1_acc = float((r_arg == true).mean()); cand_top1_acc = float((c_arg == true).mean()) + out = { + "ref": str(ref["bundle"]), "cand": str(cand["bundle"]), "positions": int(kl_pos.shape[0]), + "kl_ref_cand": {"mean": float(kl_pos.mean()), "median": _pct(kl_pos, 50), + "p95": _pct(kl_pos, 95), "p99": _pct(kl_pos, 99)}, + "top1_agreement_ref_vs_cand": top1_agree, + "ref_top1_acc_vs_true": ref_top1_acc, "cand_top1_acc_vs_true": cand_top1_acc, + } + print(json.dumps(out, indent=2)) + if a.out: + Path(a.out).write_text(json.dumps(out, indent=2)) + + +def main(): + ap = argparse.ArgumentParser() + ap.add_argument("--mode", choices=["dump", "kl"], required=True) + ap.add_argument("--bundle"); ap.add_argument("--engram-dir"); ap.add_argument("--rows") + ap.add_argument("--ref"); ap.add_argument("--cand") + ap.add_argument("--out"); ap.add_argument("--n", type=int, default=16) + ap.add_argument("--max-tokens", type=int, default=1536); ap.add_argument("--seed", type=int, default=0) + a = ap.parse_args() + (dump if a.mode == "dump" else kl)(a) + + +if __name__ == "__main__": + main() diff --git a/jang-tools/jang_tools/dsv41/metal_decode.py b/jang-tools/jang_tools/dsv41/metal_decode.py new file mode 100644 index 00000000..bf37b64b --- /dev/null +++ b/jang-tools/jang_tools/dsv41/metal_decode.py @@ -0,0 +1,785 @@ +# SPDX-License-Identifier: MIT +# The GEMV / quantized-GEMV instruction patterns below are transcribed from MLX v0.32 (gemv.h, +# quantized.h: load_vector, qdot, qmv_fast_impl, qmv_impl) so each product keeps MLX's +# accumulation order. Copyright (c) 2023-2026 Apple Inc., MIT licensed. +"""Fused Metal kernels for DSV4.1 single-stream decode and DSpark verify (<= MAX_ROWS rows). + +Why decode was slow: a 1-row step is not limited by the 10.6 GB of weights it reads (~330 GB/s of +~800) but by dispatch count. Stock MLX ops ran ~150 dispatches per layer -- the router's f32 recast of +the 384 x 5120 gate every call, separate gate/up/down gather_qmm plus three shared-expert linears +(~25), and ~14 small ops per hyper-connection sublayer -- each too short to fill the GPU, with the host +encoding all 40 layers before the GPU started. These kernels collapse the per-layer work: + + router_logits bf16 gate weight read in place with MLX's f32 GEMV order (no per-call f32 copy) + moe_decode 6 routed + shared expert in 2 dispatches (gate+up+SwiGLU, then down+sum) + hc_stage_decode hyper-connection collapse + mixes + RMSNorm + Sinkhorn split in 2 dispatches + hc_post_decode the expand back into the 4 hc streams in 1 dispatch + +Together with per-layer mx.async_eval (model.LAYER_ASYNC) they take AR decode from 29.0 to 39.2 tok/s +at 2k context (26.0 -> 34.3 at 100k), greedy tokens unchanged: every kernel reproduces MLX's +accumulation order (and its TF32 rounding of f32 matmuls), so outputs are bit-equal to the stock ops. + +Each entry point returns None when its inputs are not eligible; the caller then takes the stock path. +""" + +from __future__ import annotations + +from functools import lru_cache + +import mlx.core as mx + +MAX_ROWS = 8 + + +def _gpu() -> bool: + return mx.default_device() == mx.gpu and mx.metal.is_available() + + +# ----------------------------------------------------------------------------- router GEMV +# MLX's f32 GEMV (BM4/BN1/SM1/SN32/TM4/TN4: 4 rows per simdgroup, each lane 4 consecutive k per +# 128-wide block, simd_shuffle_down reduction) reading the bf16 weight directly, so the per-call +# f32 copy of the 384 x 5120 gate weight (~7.9 MB written + read per layer) is never made. Grid y = +# input row: every row is reduced exactly like a 1-row decode. At 1 row the logits are bit-identical +# to `x.astype(f32) @ w.astype(f32).T`; at 2-8 rows stock MLX switches to a GEMM, and these logits +# then equal the 1-row decode of each row instead (<= ~2e-6 absolute difference from the GEMM). + +_ROUTER_SRC = r""" + uint lane = thread_index_in_simdgroup; + uint row = threadgroup_position_in_grid.x * 16u + simdgroup_index_in_threadgroup * 4u; + uint r_in = threadgroup_position_in_grid.y; + const device T* xr = x + (size_t)r_in * K; + float accum[4] = {0}; + for (uint base = 0u; base < (uint)K; base += 128u) { + uint k = base + lane * 4u; + float v[4]; + #pragma clang loop unroll(full) + for (uint j = 0u; j < 4u; ++j) v[j] = float(xr[k + j]); + #pragma clang loop unroll(full) + for (uint r = 0u; r < 4u; ++r) { + #pragma clang loop unroll(full) + for (uint j = 0u; j < 4u; ++j) + accum[r] += float(weight[(size_t)(row + r) * K + k + j]) * v[j]; + } + } + #pragma clang loop unroll(full) + for (uint r = 0u; r < 4u; ++r) { + #pragma clang loop unroll(full) + for (ushort offset = 16u; offset >= 1u; offset >>= 1u) + accum[r] += simd_shuffle_down(accum[r], offset); + if (lane == 0u) out[(size_t)r_in * N + row + r] = accum[r]; + } +""" + + +@lru_cache(maxsize=1) +def _router_kernel(): + return mx.fast.metal_kernel(name="dsv41_router_gemv_bf16w_f32", input_names=["x", "weight"], + output_names=["out"], source=_ROUTER_SRC) + + +def router_logits(x: mx.array, weight: mx.array): + """f32 logits [R, E] = x [R, K] (bf16) . weight [E, K] (bf16)^T with f32 products, or None.""" + if x.ndim != 2 or weight.ndim != 2 or not _gpu(): + return None + R, K = x.shape + E = weight.shape[0] + # MLX takes this GEMV tiling only while K < 16 * E (a split-K variant otherwise) and E < 4096 + # (bm = 8 above); measured bit-equal for E 128..512 in that range (tests/dsv41_decode_fusion_test.py). + if (R > MAX_ROWS or K != weight.shape[1] or K % 128 or E % 16 or K >= 16 * E or E > 2048 + or x.dtype != mx.bfloat16 or weight.dtype != mx.bfloat16): + return None + return _router_kernel()(inputs=[x, weight], template=[("T", x.dtype), ("K", K), ("N", E)], + grid=(E // 16 * 128, R, 1), threadgroup=(128, 1, 1), + output_shapes=[(R, E)], output_dtypes=[mx.float32])[0] + + +# ----------------------------------------------------------------------------- fused MoE decode +# Two dispatches replace the ~25 of Block.moe (two gather_qmm + SwiGLU elementwise + gather_qmm + +# reshape-sum + three shared-expert qlinear + their elementwise), mlx-serve MOE_GU / MOE_DN style: +# moe_gu: grid (F/8 tiles, TOPK+1 slots, R rows). Slot s < TOPK is routed expert idx[r, s] +# (2/3-bit), slot TOPK is the shared expert (w1/w3, 8-bit). Each simdgroup computes 4 gate and +# 4 up rows from one read of x, rounds each to bf16 as gather_qmm / qlinear do, and applies the +# clamped SwiGLU (and the route weight for routed slots) in f32 -> h [R, TOPK+1, F] bf16. +# moe_dn: grid (D/4 tiles, R rows), TOPK+1 simdgroups (one per slot) each project 4 output rows of +# its slot (down_proj / w2), round to bf16, then sum in f32 in slot order (MLX's sequential +# axis reduction) plus the shared expert -> y [R, D] bf16. +# Every projection runs MLX's qmv_fast or qmv lane walk and reduction (whichever MLX picks for that K +# and bit width, see _fast) for its (row, slot), as a 1-row gather_qmm / quantized_matmul does. So decode is +# bit-identical to the stock path, and each verify row is computed exactly as its 1-row decode. + +_QHEADER = r""" +#include +#include +using namespace metal; + +template constexpr int dsv_pack_factor() { return (bits == 3 || bits == 5) ? 8 : (bits == 6 ? 4 : 32 / bits); } +template constexpr int dsv_bytes_per_pack() { return ((bits & (bits - 1)) == 0) ? 4 : (bits == 5 ? 5 : 3); } + +template +inline float dsv_load_vector(const device T* x, thread float* x_thread) { + float sum = 0; + if (bits == 2) { + for (int i = 0; i < vpt; i += 4) { + sum += float(x[i]) + float(x[i + 1]) + float(x[i + 2]) + float(x[i + 3]); + x_thread[i] = x[i]; + x_thread[i + 1] = x[i + 1] / 4.0f; + x_thread[i + 2] = x[i + 2] / 16.0f; + x_thread[i + 3] = x[i + 3] / 64.0f; + } + } else if (bits == 3) { + for (int i = 0; i < vpt; i += 8) { + sum += float(x[i]) + float(x[i + 1]) + float(x[i + 2]) + float(x[i + 3]) + float(x[i + 4]) + + float(x[i + 5]) + float(x[i + 6]) + float(x[i + 7]); + x_thread[i] = x[i]; + x_thread[i + 1] = x[i + 1] / 8.0f; + x_thread[i + 2] = x[i + 2] / 64.0f; + x_thread[i + 3] = x[i + 3] / 2.0f; + x_thread[i + 4] = x[i + 4] / 16.0f; + x_thread[i + 5] = x[i + 5] / 128.0f; + x_thread[i + 6] = x[i + 6] / 4.0f; + x_thread[i + 7] = x[i + 7] / 32.0f; + } + } else if (bits == 4) { + for (int i = 0; i < vpt; i += 4) { + sum += float(x[i]) + float(x[i + 1]) + float(x[i + 2]) + float(x[i + 3]); + x_thread[i] = x[i]; + x_thread[i + 1] = x[i + 1] / 16.0f; + x_thread[i + 2] = x[i + 2] / 256.0f; + x_thread[i + 3] = x[i + 3] / 4096.0f; + } + } else if (bits == 8) { + for (int i = 0; i < vpt; i++) { + sum += x[i]; + x_thread[i] = x[i]; + } + } + return sum; +} + +template +inline float dsv_load_vector_safe(const device T* x, thread float* x_thread, int N) { + float sum = 0; + if (bits == 2) { + for (int i = 0; i < N; i += 4) { + sum += float(x[i]) + float(x[i + 1]) + float(x[i + 2]) + float(x[i + 3]); + x_thread[i] = x[i]; + x_thread[i + 1] = x[i + 1] / 4.0f; + x_thread[i + 2] = x[i + 2] / 16.0f; + x_thread[i + 3] = x[i + 3] / 64.0f; + } + } else if (bits == 3) { + for (int i = 0; i < N; i += 8) { + sum += float(x[i]) + float(x[i + 1]) + float(x[i + 2]) + float(x[i + 3]) + float(x[i + 4]) + + float(x[i + 5]) + float(x[i + 6]) + float(x[i + 7]); + x_thread[i] = x[i]; + x_thread[i + 1] = x[i + 1] / 8.0f; + x_thread[i + 2] = x[i + 2] / 64.0f; + x_thread[i + 3] = x[i + 3] / 2.0f; + x_thread[i + 4] = x[i + 4] / 16.0f; + x_thread[i + 5] = x[i + 5] / 128.0f; + x_thread[i + 6] = x[i + 6] / 4.0f; + x_thread[i + 7] = x[i + 7] / 32.0f; + } + } else if (bits == 4) { + for (int i = 0; i < N; i += 4) { + sum += float(x[i]) + float(x[i + 1]) + float(x[i + 2]) + float(x[i + 3]); + x_thread[i] = x[i]; + x_thread[i + 1] = x[i + 1] / 16.0f; + x_thread[i + 2] = x[i + 2] / 256.0f; + x_thread[i + 3] = x[i + 3] / 4096.0f; + } + } else if (bits == 8) { + for (int i = 0; i < N; i++) { + sum += x[i]; + x_thread[i] = x[i]; + } + } + for (int i = N; i < vpt; i++) x_thread[i] = 0; + return sum; +} + +template +inline float dsv_qdot(const device uint8_t* w, const thread float* x_thread, float scale, float bias, float sum) { + float accum = 0; + if (bits == 2) { + for (int i = 0; i < (vpt / 4); i++) { + accum += (x_thread[4 * i] * (w[i] & 0x03) + x_thread[4 * i + 1] * (w[i] & 0x0c) + + x_thread[4 * i + 2] * (w[i] & 0x30) + x_thread[4 * i + 3] * (w[i] & 0xc0)); + } + } else if (bits == 3) { + for (int i = 0; i < (vpt / 8); i++) { + x_thread += 8 * i; + w += 3 * i; + accum += (w[0] & 0x07) * x_thread[0]; + accum += (w[0] & 0x38) * x_thread[1]; + accum += (w[0] & 0xc0) * x_thread[2]; + accum += (w[1] & 0x01) * (x_thread[2] * 256.0f); + accum += (w[1] & 0x0e) * x_thread[3]; + accum += (w[1] & 0x70) * x_thread[4]; + accum += (w[1] & 0x80) * x_thread[5]; + accum += (w[2] & 0x03) * (x_thread[5] * 256.0f); + accum += (w[2] & 0x1c) * x_thread[6]; + accum += (w[2] & 0xe0) * x_thread[7]; + } + } else if (bits == 4) { + const device uint16_t* ws = (const device uint16_t*)w; + for (int i = 0; i < (vpt / 4); i++) { + accum += (x_thread[4 * i] * (ws[i] & 0x000f) + x_thread[4 * i + 1] * (ws[i] & 0x00f0) + + x_thread[4 * i + 2] * (ws[i] & 0x0f00) + x_thread[4 * i + 3] * (ws[i] & 0xf000)); + } + } else if (bits == 8) { + for (int i = 0; i < vpt; i++) accum += x_thread[i] * w[i]; + } + return scale * accum + sum * bias; +} + +template +inline float dsv_qdot_safe(const device uint8_t* w, const thread float* x_thread, float scale, float bias, + float sum, int N) { + float accum = 0; + if (bits == 2) { + for (int i = 0; i < (N / 4); i++) { + accum += (x_thread[4 * i] * (w[i] & 0x03) + x_thread[4 * i + 1] * (w[i] & 0x0c) + + x_thread[4 * i + 2] * (w[i] & 0x30) + x_thread[4 * i + 3] * (w[i] & 0xc0)); + } + } else if (bits == 3) { + for (int i = 0; i < (N / 8); i++) { + x_thread += 8 * i; + w += 3 * i; + accum += (w[0] & 0x07) * x_thread[0]; + accum += (w[0] & 0x38) * x_thread[1]; + accum += (w[0] & 0xc0) * x_thread[2]; + accum += (w[1] & 0x01) * (x_thread[2] * 256.0f); + accum += (w[1] & 0x0e) * x_thread[3]; + accum += (w[1] & 0x70) * x_thread[4]; + accum += (w[1] & 0x80) * x_thread[5]; + accum += (w[2] & 0x03) * (x_thread[5] * 256.0f); + accum += (w[2] & 0x1c) * x_thread[6]; + accum += (w[2] & 0xe0) * x_thread[7]; + } + } else if (bits == 4) { + const device uint16_t* ws = (const device uint16_t*)w; + for (int i = 0; i < (N / 4); i++) { + accum += (x_thread[4 * i] * (ws[i] & 0x000f) + x_thread[4 * i + 1] * (ws[i] & 0x00f0) + + x_thread[4 * i + 2] * (ws[i] & 0x0f00) + x_thread[4 * i + 3] * (ws[i] & 0xf000)); + } + } else if (bits == 8) { + for (int i = 0; i < N; i++) accum += x_thread[i] * w[i]; + } + return scale * accum + sum * bias; +} + +// NP projections (sharing x) x 4 output rows, MLX qmv_fast_impl (FAST, K % 512 == 0) or qmv_impl +// lane walk. w*/s*/b* point at the simdgroup's first output row. acc[p * 4 + row] (not yet reduced). +template +inline void dsv_qmv4(const device uint8_t* const* w, const device T* const* sc, const device T* const* bi, + const device T* x, int K, uint lane, thread float* acc) { + constexpr int packs = FAST ? (bits <= 2 ? 1 : 2) : 1; + constexpr int pf = dsv_pack_factor(); + constexpr int bpp = dsv_bytes_per_pack(); + constexpr int vpt = pf * packs; + constexpr int block = vpt * 32; + constexpr int scale_step = GS / vpt; + const int in_w = K * bpp / pf; + const int in_g = K / GS; + const device uint8_t* ws[NP]; + const device T* ss[NP]; + const device T* bs[NP]; + for (int p = 0; p < NP; p++) { + ws[p] = w[p] + lane * packs * bpp; + ss[p] = sc[p] + lane / scale_step; + bs[p] = bi[p] + lane / scale_step; + } + x += lane * vpt; + thread float x_thread[vpt]; + int k = 0; + const int full_end = FAST ? K : K - block; + for (; k < full_end; k += block) { + float sum = dsv_load_vector(x, x_thread); + for (int p = 0; p < NP; p++) { + for (int row = 0; row < 4; row++) { + float s = ss[p][row * in_g]; + float b = bs[p][row * in_g]; + acc[p * 4 + row] += dsv_qdot(ws[p] + row * in_w, x_thread, s, b, sum); + } + ws[p] += block * bpp / pf; + ss[p] += block / GS; + bs[p] += block / GS; + } + x += block; + } + if (!FAST) { + const int remaining = clamp(int(K - k - int(lane) * vpt), 0, vpt); + if (remaining > 0) { + float sum = dsv_load_vector_safe(x, x_thread, remaining); + for (int p = 0; p < NP; p++) { + for (int row = 0; row < 4; row++) { + float s = ss[p][row * in_g]; + float b = bs[p][row * in_g]; + acc[p * 4 + row] += dsv_qdot_safe(ws[p] + row * in_w, x_thread, s, b, sum, remaining); + } + } + } + } +} + +inline float dsv_minimum(float x, float y) { return metal::isnan(x) ? x : (x < y ? x : y); } +inline float dsv_maximum(float x, float y) { return metal::isnan(x) ? x : (x > y ? x : y); } +inline float dsv_silu(float x) { // nn.silu = x * sigmoid(x), MLX Sigmoid + float y = 1 / (1 + metal::precise::exp(metal::abs(x))); + return x * ((x < 0) ? y : 1 - y); +} +""" + +_MOE_GU_SRC = r""" + const uint lane = thread_index_in_simdgroup; + const uint sg = simdgroup_index_in_threadgroup; + const uint slot = threadgroup_position_in_grid.y; + const uint r = threadgroup_position_in_grid.z; + const uint out_row = threadgroup_position_in_grid.x * (4u * NSG) + sg * 4u; + const device T* xr = x + (size_t)r * D; + float acc[8] = {0, 0, 0, 0, 0, 0, 0, 0}; + float rw = 1.0f; + if (slot < (uint)TOPK) { + const size_t row0 = (size_t)idx[r * TOPK + slot] * F + out_row; + const int in_w = D * dsv_bytes_per_pack
() / dsv_pack_factor
(); + const device uint8_t* w[2] = {(const device uint8_t*)gw + row0 * in_w, (const device uint8_t*)uw + row0 * in_w}; + const device T* s[2] = {gs + row0 * (D / GS), us + row0 * (D / GS)}; + const device T* b[2] = {gb + row0 * (D / GS), ub + row0 * (D / GS)}; + dsv_qmv4(w, s, b, xr, D, lane, acc); + rw = route_w[r * TOPK + slot]; + } else { + const size_t row0 = out_row; + const int in_w = D * dsv_bytes_per_pack() / dsv_pack_factor(); + const device uint8_t* w[2] = {(const device uint8_t*)w1 + row0 * in_w, (const device uint8_t*)w3 + row0 * in_w}; + const device T* s[2] = {s1 + row0 * (D / GS), s3 + row0 * (D / GS)}; + const device T* b[2] = {b1 + row0 * (D / GS), b3 + row0 * (D / GS)}; + dsv_qmv4(w, s, b, xr, D, lane, acc); + } + for (int row = 0; row < 4; row++) { + float g = simd_sum(acc[row]); + float u = simd_sum(acc[4 + row]); + if (lane == 0) { + g = float(static_cast(g)); + u = float(static_cast(u)); + if (HAS_LIM) { + u = dsv_minimum(dsv_maximum(u, -LIM), LIM); + g = dsv_minimum(g, LIM); + } + float h = dsv_silu(g) * u; + if (slot < (uint)TOPK) h = h * rw; + out[((size_t)r * (TOPK + 1) + slot) * F + out_row + row] = static_cast(h); + } + } +""" + +_MOE_DN_SRC = r""" + const uint lane = thread_index_in_simdgroup; + const uint slot = simdgroup_index_in_threadgroup; + const uint r = threadgroup_position_in_grid.y; + const uint out_row = threadgroup_position_in_grid.x * (4u * RG); + const device T* hr = h + ((size_t)r * (TOPK + 1) + slot) * F; + float acc[4 * RG]; + for (int i = 0; i < 4 * RG; i++) acc[i] = 0; + if (slot < (uint)TOPK) { + const size_t row0 = (size_t)idx[r * TOPK + slot] * D + out_row; + const int in_w = F * dsv_bytes_per_pack() / dsv_pack_factor(); + const device uint8_t* w[RG]; + const device T* s[RG]; + const device T* b[RG]; + for (int p = 0; p < RG; p++) { + w[p] = (const device uint8_t*)dw + (row0 + 4 * p) * in_w; + s[p] = ds + (row0 + 4 * p) * (F / GS); + b[p] = db + (row0 + 4 * p) * (F / GS); + } + dsv_qmv4(w, s, b, hr, F, lane, acc); + } else { + const size_t row0 = out_row; + const int in_w = F * dsv_bytes_per_pack() / dsv_pack_factor(); + const device uint8_t* w[RG]; + const device T* s[RG]; + const device T* b[RG]; + for (int p = 0; p < RG; p++) { + w[p] = (const device uint8_t*)w2 + (row0 + 4 * p) * in_w; + s[p] = s2 + (row0 + 4 * p) * (F / GS); + b[p] = b2 + (row0 + 4 * p) * (F / GS); + } + dsv_qmv4(w, s, b, hr, F, lane, acc); + } + threadgroup float part[(TOPK + 1) * 4 * RG]; + for (int i = 0; i < 4 * RG; i++) { + float v = simd_sum(acc[i]); + if (lane == 0) part[slot * 4 * RG + i] = float(static_cast(v)); + } + threadgroup_barrier(mem_flags::mem_threadgroup); + if (slot == 0 && lane < 4 * RG) { + float y = 0.0f; + for (int s = 0; s < TOPK; s++) y = part[s * 4 * RG + lane] + y; + y = y + part[TOPK * 4 * RG + lane]; + out[(size_t)r * D + out_row + lane] = static_cast(y); + } +""" + + +# (simdgroups per threadgroup in moe_gu, 4-row groups per simdgroup in moe_dn): occupancy only, the +# per-row arithmetic does not depend on it. +MOE_TILE = (2, 1) + + +def _fast(bits: int, K: int) -> bool: + """MLX runs qmv_fast when K is a multiple of its block (32 lanes x values per thread: 512 for + 2/3/4-bit, 256 for 8-bit), else qmv. Measured on f32 outputs against quantized_matmul / gather_qmm + (tests/dsv41_decode_fusion_test.py).""" + return K % (256 if bits == 8 else 512) == 0 + + +@lru_cache(maxsize=None) +def _moe_kernels(lim: float): + has = lim > 0 + src = _MOE_GU_SRC.replace("HAS_LIM", "true" if has else "false").replace("LIM", f"{lim if has else 0.0:.9e}f") + gu = mx.fast.metal_kernel( + name=f"dsv41_moe_gu_{'lim' if has else 'nolim'}", header=_QHEADER, source=src, + input_names=["x", "idx", "route_w", "gw", "gs", "gb", "uw", "us", "ub", "w1", "s1", "b1", "w3", "s3", "b3"], + output_names=["out"]) + dn = mx.fast.metal_kernel( + name="dsv41_moe_dn", header=_QHEADER, source=_MOE_DN_SRC, + input_names=["h", "idx", "dw", "ds", "db", "w2", "s2", "b2"], output_names=["out"]) + return gu, dn + + +def _moe_eligible(x, idx, experts, shared, group_size) -> bool: + if x.ndim != 2 or idx.ndim != 2 or not _gpu(): + return False + R, D = x.shape + g, u, d = experts.gate_proj, experts.up_proj, experts.down_proj + F = g.weight.shape[1] + sw = (shared.w1, shared.w3, shared.w2) + return not (R > MAX_ROWS or x.dtype != mx.bfloat16 or g.bits != u.bits or g.bits not in (2, 3, 4, 8) + or d.bits not in (2, 3, 4, 8) or any(m.bits != shared.w1.bits or m.group_size != group_size for m in sw) + or shared.w1.bits not in (2, 3, 4, 8) or F % 8 or D % 8 or F % group_size or D % group_size + or g.scales.dtype != mx.bfloat16 or shared.w1.scales.dtype != mx.bfloat16 + or d.weight.shape[1] != D or shared.w1.weight.shape[0] != F or shared.w2.weight.shape[0] != D) + + +def moe_decode(x, idx, w, experts, shared, swiglu_limit: float, group_size: int = 64): + """Routed + shared expert MoE for R <= MAX_ROWS rows in two dispatches, or None if not eligible. + + x [R, D] bf16; idx [R, TOPK] expert ids (argpartition order = summation order); w [R, TOPK] f32 + route weights (already normalized and scaled). experts: SwitchMLP (gate_proj/up_proj/down_proj + SwitchProj); shared: SharedExpert (w1/w2/w3 QuantizedLinear). Returns y [R, D] bf16.""" + if not _moe_eligible(x, idx, experts, shared, group_size): + return None + R, D = x.shape + topk = idx.shape[1] + g, u, d = experts.gate_proj, experts.up_proj, experts.down_proj + F = g.weight.shape[1] + lim = float(swiglu_limit) + nsg, rg = MOE_TILE + if F % (4 * nsg) or D % (4 * rg): + return None + gu, dn = _moe_kernels(lim) + idx = idx.astype(mx.uint32) + w = w.astype(mx.float32) + tmpl = [("T", mx.bfloat16), ("D", D), ("F", F), ("TOPK", topk), ("GS", group_size), + ("BS", shared.w1.bits)] + h = gu(inputs=[x, idx, w, g.weight, g.scales, g.biases, u.weight, u.scales, u.biases, + shared.w1.weight, shared.w1.scales, shared.w1.biases, + shared.w3.weight, shared.w3.scales, shared.w3.biases], + template=tmpl + [("BR", g.bits), ("FAST_D", _fast(g.bits, D)), ("FAST_DS", _fast(shared.w1.bits, D)), + ("NSG", nsg)], + grid=(F // (4 * nsg) * 32 * nsg, topk + 1, R), threadgroup=(32 * nsg, 1, 1), + output_shapes=[(R, topk + 1, F)], output_dtypes=[mx.bfloat16])[0] + y = dn(inputs=[h, idx, d.weight, d.scales, d.biases, shared.w2.weight, shared.w2.scales, shared.w2.biases], + template=tmpl + [("BD", d.bits), ("FAST_F", _fast(d.bits, F)), ("FAST_FS", _fast(shared.w1.bits, F)), + ("RG", rg)], + grid=(D // (4 * rg) * 32 * (topk + 1), R, 1), threadgroup=(32 * (topk + 1), 1, 1), + output_shapes=[(R, D)], output_dtypes=[mx.bfloat16])[0] + return y + + +# ----------------------------------------------------------------------------- fused hyper-connections +# Per sublayer the stock decode runs hc_mixes (astype, square, mean = 2-pass all-reduce, rsqrt, f32 +# GEMV 24 x 20480, multiply, Sinkhorn kernel), hc_pre (compiled multiply + axis reduction + cast), +# RMSNorm and hc_post (compiled multiply, einsum GEMM, add, cast): ~14 dispatches. Here (mlx-serve +# HC_STAGE / HC_SPLIT, oMLX K1/K2) three: +# hc_stage: tg 0 collapses the stream with the previous pre and RMS-norms it (MLX rms_single_row / +# rms_looped order); tg 1 sums x^2 in MLX's row_reduce_looped order; tgs 2-7 run MLX's gemv +# (BM1 BN8 SM1 SN32 TM4 TN4, its choice for 24 x 20480) for the 24 mixes. +# hc_split: mean, rsqrt, mixes * rs and the release Sinkhorn (the code of _hc_split_metal) +# -> pre / post / comb. +# hc_post: post * h + comb^T . residual -> next stream (bf16). MLX's f32 GEMM for the einsum runs on +# the M5 matrix units in TF32 (MLX_ENABLE_TF32=1, the default): comb truncated to TF32, the +# four products summed pairwise; reproduced exactly here. +# Each row (decode or verify) is computed as its own 1-row decode. Bit-identity with the stock ops is +# checked once at first use (hc_selfcheck); any mismatch (another MLX, TF32 off) disables the path. + +_HC_STAGE_SRC = r""" + const uint tg = threadgroup_position_in_grid.x; + const uint r = threadgroup_position_in_grid.y; + const uint lid = thread_position_in_threadgroup.x; + const uint lane = thread_index_in_simdgroup; + const uint sg = simdgroup_index_in_threadgroup; + const device T* xr = x + (size_t)r * (HC * D); + threadgroup float tmem[1024]; + if (tg == 0) { + // hc_pre: s = sum_j pre_j * x_j in f32 (sequential axis reduction), cast to T; then RMSNorm. + float p[HC]; + for (int j = 0; j < HC; j++) p[j] = pre[r * HC + j]; + float acc = 0; + if (NORM_LOOPED) { + for (uint b = 0; b < (uint)D; b += 1024u * 4u) { + if (b + lid * 4u + 4u <= (uint)D) { + for (int i = 0; i < 4; i++) { + uint d = b + lid * 4u + i; + float s = 0.0f; + for (int j = 0; j < HC; j++) { float t = p[j] * float(xr[j * D + d]); s = t + s; } + float xi = float(static_cast(s)); + acc += xi * xi; + } + } else { + for (int i = 0; i < 4; i++) { + uint d = b + lid * 4u + i; + if (d < (uint)D) { + float s = 0.0f; + for (int j = 0; j < HC; j++) { float t = p[j] * float(xr[j * D + d]); s = t + s; } + float xi = float(static_cast(s)); + acc += xi * xi; + } + } + } + } + } else { + float tx[4]; + for (int i = 0; i < 4; i++) { + uint d = lid * 4u + i; + float s = 0.0f; + if (d < (uint)D) { + for (int j = 0; j < HC; j++) { float t = p[j] * float(xr[j * D + d]); s = t + s; } + } + tx[i] = (d < (uint)D) ? float(static_cast(s)) : 0.0f; + acc += tx[i] * tx[i]; + } + } + acc = simd_sum(acc); + if (sg == 0) tmem[lane] = 0; + threadgroup_barrier(mem_flags::mem_threadgroup); + if (lane == 0) tmem[sg] = acc; + threadgroup_barrier(mem_flags::mem_threadgroup); + if (sg == 0) { + acc = simd_sum(tmem[lane]); + if (lane == 0) tmem[32] = metal::precise::rsqrt(acc / (float)D + NORM_EPS); + } + threadgroup_barrier(mem_flags::mem_threadgroup); + const float inv = tmem[32]; + for (uint d = lid; d < (uint)D; d += 1024u) { + float s = 0.0f; + for (int j = 0; j < HC; j++) { float t = p[j] * float(xr[j * D + d]); s = t + s; } + T xv = static_cast(s); + xin[(size_t)r * D + d] = nw[d] * static_cast(xv * inv); + } + } else if (tg == 1) { + // sum(x^2) over the HC * D values: MLX row_reduce_looped, one threadgroup of RED_TGS threads. + float total = 0.0f; + if (lid < (uint)RED_TGS) { + const int n = HC * D; + const int blocks = n / (RED_TGS * 4); + const int extra = n - blocks * (RED_TGS * 4); + long off = lid * 4; + for (int b = 0; b < blocks; b++) { + for (int i = 0; i < 4; i++) { float v = float(xr[off + i]); total = (v * v) + total; } + off += RED_TGS * 4; + } + const int index = lid * 4; + if (index + 4 <= extra) { + for (int i = 0; i < 4; i++) { float v = float(xr[off + i]); total = (v * v) + total; } + } else { + for (int i = 0; index + i < extra; i++) { float v = float(xr[off + i]); total = (v * v) + total; } + } + } + total = simd_sum(total); + if (lane == 0) tmem[sg] = total; + threadgroup_barrier(mem_flags::mem_threadgroup); + const uint nsg = (RED_TGS + 31) / 32; + total = lid < nsg ? tmem[lid] : 0.0f; + total = simd_sum(total); + if (lid == 0) part[r] = total; + } else { + // MLX gemv BM1 BN8 SM1 SN32 TM4 TN4: one MLX threadgroup (8 simdgroups) per real one, so the + // 6 output tiles stream fn on 6 cores as MLX does; simdgroups 8.. idle. + const uint v = sg / 8u, sgN = sg % 8u; + const int out_row = (v == 0) ? (int)(tg - 2) * 4 : MIX; + float res[4] = {0, 0, 0, 0}; + if (out_row < MIX) { + int bn = (int)(32u * sgN + lane) * 4; + const device float* mat = fn + (size_t)out_row * (HC * D); + const int n_iter = (HC * D) / 1024; + for (int i = 0; i < n_iter; ++i) { + float vc[4]; + for (int tn = 0; tn < 4; tn++) vc[tn] = float(xr[bn + tn]); + int mo = 0; + for (int tm = 0; tm < 4; tm++) { + float inter[4]; + for (int tn = 0; tn < 4; tn++) inter[tn] = mat[mo + bn + tn]; + for (int tn = 0; tn < 4; tn++) res[tm] += inter[tn] * vc[tn]; + mo += HC * D; + } + bn += 1024; + } + const int leftover = (HC * D) - n_iter * 1024; + if (leftover > 0) { + float vc[4]; + for (int tn = 0; tn < 4; tn++) vc[tn] = (bn + tn < HC * D) ? float(xr[bn + tn]) : 0.0f; + for (int tm = 0; tm < 4; tm++) { + float inter[4]; + for (int tn = 0; tn < 4; tn++) inter[tn] = (bn + tn < HC * D) ? mat[tm * (HC * D) + bn + tn] : 0.0f; + for (int tn = 0; tn < 4; tn++) res[tm] += inter[tn] * vc[tn]; + } + } + for (int tm = 0; tm < 4; tm++) + for (ushort sn = 16; sn >= 1; sn >>= 1) res[tm] += simd_shuffle_down(res[tm], sn); + } + // tgp reduction across the 8 K-split simdgroups (tgp_results = base + sgN * (blockM + TM)) + threadgroup float* tr = tmem + v * 64u + sgN * 8u; + if (lane == 0) for (int tm = 0; tm < 4; tm++) tr[tm] = res[tm]; + threadgroup_barrier(mem_flags::mem_threadgroup); + if (lane == 0 && sgN == 0 && out_row < MIX) { + for (int sgn = 1; sgn < 8; sgn++) + for (int tm = 0; tm < 4; tm++) res[tm] += tmem[v * 64u + sgn * 8u + tm]; + for (int tm = 0; tm < 4; tm++) dots[(size_t)r * MIX + out_row + tm] = res[tm]; + } + } +""" + +_HC_SPLIT2_SRC = r""" + const uint lane = thread_index_in_simdgroup; + const uint r = threadgroup_position_in_grid.y; + const float total = part[r]; + if (lane != 0) return; + const float mean = total * INV_N; + const float rs = metal::precise::rsqrt(mean + RMS_EPS); + float m[24]; + for (int j = 0; j < 24; j++) m[j] = dots[(size_t)r * 24 + j] * rs; + const uint t = r; + float s0 = scale[0], s1 = scale[1], s2 = scale[2]; + for (int j = 0; j < 4; j++) { + pre[t * 4 + j] = 1.0f / (1.0f + metal::precise::exp(-(m[j] * s0 + base[j]))) + EPS; + post[t * 4 + j] = 2.0f / (1.0f + metal::precise::exp(-(m[4 + j] * s1 + base[4 + j]))); + } + float c[16]; + for (int i = 0; i < 16; i++) c[i] = m[8 + i] * s2 + base[8 + i]; + for (int rr = 0; rr < 4; rr++) { + float mx_ = c[rr * 4]; + for (int k = 1; k < 4; k++) mx_ = metal::max(mx_, c[rr * 4 + k]); + float sum = 0.0f; + for (int k = 0; k < 4; k++) { c[rr * 4 + k] = metal::precise::exp(c[rr * 4 + k] - mx_); sum += c[rr * 4 + k]; } + for (int k = 0; k < 4; k++) c[rr * 4 + k] = c[rr * 4 + k] / sum + EPS; + } + for (int k = 0; k < 4; k++) { + float cs = c[k] + c[4 + k] + c[8 + k] + c[12 + k]; + for (int rr = 0; rr < 4; rr++) c[rr * 4 + k] = c[rr * 4 + k] / (cs + EPS); + } + for (int it = 0; it < ITERS - 1; it++) { + for (int rr = 0; rr < 4; rr++) { + float rsum = c[rr * 4] + c[rr * 4 + 1] + c[rr * 4 + 2] + c[rr * 4 + 3]; + for (int k = 0; k < 4; k++) c[rr * 4 + k] = c[rr * 4 + k] / (rsum + EPS); + } + for (int k = 0; k < 4; k++) { + float cs = c[k] + c[4 + k] + c[8 + k] + c[12 + k]; + for (int rr = 0; rr < 4; rr++) c[rr * 4 + k] = c[rr * 4 + k] / (cs + EPS); + } + } + for (int i = 0; i < 16; i++) comb[t * 16 + i] = c[i]; +""" + +_HC_POST_SRC = r""" + const uint d = thread_position_in_grid.x; + const uint r = thread_position_in_grid.y; + if (d >= (uint)D) return; + float hv = float(h[(size_t)r * D + d]); + float rv[4]; + for (int j = 0; j < 4; j++) rv[j] = float(res[((size_t)r * 4 + j) * D + d]); + for (int k = 0; k < 4; k++) { + float c[4]; + for (int j = 0; j < 4; j++) c[j] = TF32 ? as_type(as_type(comb[r * 16 + j * 4 + k]) & 0xFFFFE000u) + : comb[r * 16 + j * 4 + k]; + float p0 = c[0] * rv[0], p1 = c[1] * rv[1], p2 = c[2] * rv[2], p3 = c[3] * rv[3]; + float e = (p0 + p1) + (p2 + p3); + float t = post[r * 4 + k] * hv; + out[((size_t)r * 4 + k) * D + d] = static_cast(t + e); + } +""" + + +def _red_tgs(n: int) -> int: + """MLX threadgroup_size_from_row_size: the row_reduce_looped width for a 1-row sum of n values.""" + if n <= 512: + return 32 + if n <= 1024: + return 128 + return min(1024, ((n + 3) // 4 + 31) // 32 * 32) + + +@lru_cache(maxsize=None) +def _hc_kernels(norm_eps: float, rms_eps: float, hc_eps: float, iters: int, n: int): + lit = lambda v: f"{float(v):.9e}f" # noqa: E731 + stage_src = _HC_STAGE_SRC.replace("NORM_EPS", lit(norm_eps)).replace("RED_TGS", str(_red_tgs(n))) + stage = mx.fast.metal_kernel(name=f"dsv41_hc_stage_{n}", input_names=["x", "pre", "fn", "nw"], + output_names=["xin", "part", "dots"], source=stage_src) + split_src = (_HC_SPLIT2_SRC.replace("INV_N", lit(1.0 / n)).replace("RMS_EPS", lit(rms_eps)) + .replace("ITERS", str(int(iters))).replace("EPS", lit(hc_eps))) + split = mx.fast.metal_kernel(name=f"dsv41_hc_split2_{iters}", input_names=["part", "dots", "scale", "base"], + output_names=["pre", "post", "comb"], source=split_src) + post = mx.fast.metal_kernel(name="dsv41_hc_post", input_names=["h", "res", "post", "comb"], + output_names=["out"], source=_HC_POST_SRC) + return stage, split, post + + +@lru_cache(maxsize=1) +def _gemm_rounds_to_tf32() -> bool: + """Whether this device's f32 GEMMs truncate operands to TF32. M5 matrix units do (MLX default); + other GPUs accumulate in another order, and the hc expand kernel then cannot be bit-equal (the + runtime self-check keeps the stock ops there). Probed with the expand einsum's own shape.""" + comb = mx.full((1, 1, 4, 4), 1.0 + 2.0 ** -12, mx.float32) # not representable in TF32 + res = mx.ones((1, 1, 4, 256), mx.float32) + y = mx.einsum("bsjk,bsjd->bskd", comb, res) + return bool((y[0, 0, 0, 0] == 4.0).item()) + + +def _tf32() -> bool: + import os + if os.environ.get("MLX_ENABLE_TF32", "1").strip() in {"0", "false", "False"}: + return False + return _gpu() and _gemm_rounds_to_tf32() + + +def hc_stage_decode(x, pre, fn, scale, base, norm_w, norm_eps, rms_eps, hc_eps, iters): + """x [R, 4, D] bf16 stream; pre [R, 4] f32 (the previous sublayer's pre). Returns (xin [R, D] bf16 = + RMSNorm(hc_pre(x, pre)), pre', post', comb' of hc_mixes(x)), or None if not eligible.""" + if x.ndim != 3 or x.shape[1] != 4 or x.dtype != mx.bfloat16 or not _gpu(): + return None + R, hc, D = x.shape + n = hc * D + if (R > MAX_ROWS or fn.shape != (24, n) or fn.dtype != mx.float32 or norm_w.dtype != mx.bfloat16 + or norm_w.shape != (D,) or n % 4 or n < 16 * 24 or D > 1024 * 4 * 64): + return None + stage, split, _ = _hc_kernels(float(norm_eps), float(rms_eps), float(hc_eps), int(iters), n) + xin, part, dots = stage(inputs=[x, pre.astype(mx.float32), fn, norm_w], template=[("T", mx.bfloat16), ("D", D), + ("HC", hc), ("MIX", 24), ("NORM_LOOPED", D > 4096)], + grid=(1024 * (2 + 24 // 4), R, 1), threadgroup=(1024, 1, 1), + output_shapes=[(R, D), (R, 1), (R, 24)], + output_dtypes=[mx.bfloat16, mx.float32, mx.float32], init_value=0) + p, po, cb = split(inputs=[part, dots, scale.astype(mx.float32), base.astype(mx.float32)], + grid=(32, R, 1), threadgroup=(32, 1, 1), + output_shapes=[(R, 4), (R, 4), (R, 16)], output_dtypes=[mx.float32] * 3) + return xin, p, po, cb.reshape(R, 4, 4) + + +def hc_post_decode(h, residual, post, comb): + """h [R, D] bf16, residual [R, 4, D] bf16, post [R, 4], comb [R, 4, 4] -> [R, 4, D] bf16, or None.""" + if h.ndim != 2 or residual.ndim != 3 or residual.shape[1] != 4 or not _gpu() or h.dtype != mx.bfloat16: + return None + R, D = h.shape + _, _, post_k = _hc_kernels(0.0, 0.0, 0.0, 1, 4 * D) + return post_k(inputs=[h, residual, post.astype(mx.float32), comb.reshape(R, 16).astype(mx.float32)], + template=[("T", mx.bfloat16), ("D", D), ("TF32", _tf32())], + grid=(D, R, 1), threadgroup=(256, 1, 1), output_shapes=[(R, 4, D)], output_dtypes=[mx.bfloat16])[0] diff --git a/jang-tools/jang_tools/dsv41/model.py b/jang-tools/jang_tools/dsv41/model.py new file mode 100644 index 00000000..4c5e02fb --- /dev/null +++ b/jang-tools/jang_tools/dsv41/model.py @@ -0,0 +1,1403 @@ +"""DeepSeek-V4.1-Flash text model in MLX, for JANG affine bundles. + +A batch-1 port of the release's inference/model.py (autoregressive path only): +hyper-connections (hc_mult=4, Sinkhorn mixing), latent attention over a +128-token sliding window plus compressed KV picked by the two-level indexer, +cross-layer KV / index / candidate sharing, Engram n-gram lookups at layers 1 +and 14, sqrtsoftplus-routed MoE with one shared expert. + +Not ported: the vision tower (bundle tensors are present but unused here), +DSpark speculative heads (not in the bundle), and the release's FP8/FP4 +activation round-trips (activations stay bf16/fp32 here). Prefill must be a +single call starting at position 0, then one token per call -- the same +contract as the release's generate.py. +""" + +from __future__ import annotations + +import json +import math +import os +from dataclasses import dataclass, field +from pathlib import Path + +import mlx.core as mx +import mlx.nn as nn +import numpy as np + +from jang_tools.dsv41.engram import EngramLayout, NgramHasher, open_engram_tables + +# Forwards of at least ENGRAM_LAZY_MIN tokens read the later Engram layers' rows while the GPU +# runs the layers before them (DSV41._engram_rows(lazy=True)); shorter ones read inline. +ENGRAM_LAZY_MIN = 64 + +GROUP_SIZE = 64 + + +def _env_on(name: str, default: str = "1") -> bool: + return os.environ.get(name, default).strip().lower() not in {"0", "false", "off", "no"} + + +# Decode / DSpark verify forwards of at most this many tokens submit each layer to the GPU as soon as it +# is built (mx.async_eval per layer) instead of building all 40 layers and then waiting, so the GPU runs +# the early layers while Python builds the later ones (ds4 #1261, oMLX language.py). Bit-identical: +# only the scheduling changes. VMLX_DSV41_LAYER_ASYNC=0 restores the single end-of-graph eval. +LAYER_ASYNC = _env_on("VMLX_DSV41_LAYER_ASYNC") +LAYER_ASYNC_MAX_ROWS = 16 +# Router logits for <= 8 rows from the bf16 gate weight with MLX's f32 GEMV order (metal_decode.py): +# no per-call f32 copy of the 384 x 5120 weight. 1 row: bit-identical; 2-8 rows: each row exactly its +# 1-row decode logits. VMLX_DSV41_ROUTER_GEMV=0 restores the f32-cast matmul. +ROUTER_GEMV = _env_on("VMLX_DSV41_ROUTER_GEMV") +# Routed + shared experts for <= 8 rows in two Metal dispatches (metal_decode.moe_decode, mlx-serve +# MOE_GU/MOE_DN) instead of ~25. 1 row: bit-identical; 2-8 rows: each row exactly its 1-row decode. +# VMLX_DSV41_FUSED_MOE=0 restores gather_qmm + qlinear. +FUSED_MOE = _env_on("VMLX_DSV41_FUSED_MOE") +# Hyper-connection stage for <= 8 rows in three Metal dispatches per sublayer (metal_decode.hc_*: +# mixes + collapse + RMSNorm, Sinkhorn split, expand) instead of ~14, each MLX op's order reproduced. +# Bit-identical (checked once per process against the stock ops; a mismatch keeps the stock path). +# VMLX_DSV41_FUSED_HC=0 restores the stock ops. +FUSED_HC = _env_on("VMLX_DSV41_FUSED_HC") + + +@dataclass +class Args: + vocab_size: int + hidden_size: int + moe_intermediate_size: int + num_hidden_layers: int + num_attention_heads: int + head_dim: int + qk_rope_head_dim: int + q_lora_rank: int + o_lora_rank: int + o_groups: int + swiglu_limit: float + rms_norm_eps: float + rope_theta: float + rope_scaling: dict + n_routed_experts: int + num_experts_per_tok: int + routed_scaling_factor: float + norm_topk_prob: bool + sliding_window: int + compress_ratios: list + compress_rope_theta: float + kv_source_layer_ids: list + index_source_layer_ids: list + index_n_heads: int + index_head_dim: int + index_topk: int + candidate_source_layer_id: int + candidate_topk_blocks: int + candidate_block_size: int + hc_mult: int + hc_sinkhorn_iters: int + hc_eps: float + engram_layer_ids: list + raw: dict = field(default_factory=dict) + + @classmethod + def from_config(cls, text_cfg: dict) -> "Args": + names = cls.__dataclass_fields__.keys() - {"raw"} + return cls(**{k: text_cfg[k] for k in names}, raw=text_cfg) + + +# ----------------------------------------------------------------------------- rope + +def yarn_inv_freq(dim, base, original_seq_len, factor, beta_fast, beta_slow) -> np.ndarray: + freqs = 1.0 / (base ** (np.arange(0, dim, 2, dtype=np.float32) / dim)) + if original_seq_len > 0: + def corr(rot): + return dim * math.log(original_seq_len / (rot * 2 * math.pi)) / (2 * math.log(base)) + + low = max(math.floor(corr(beta_fast)), 0) + high = min(math.ceil(corr(beta_slow)), dim - 1) + ramp = np.clip((np.arange(dim // 2, dtype=np.float32) - low) / max(high - low, 1e-3), 0, 1) + smooth = 1 - ramp + freqs = freqs / factor * (1 - smooth) + freqs * smooth + return freqs.astype(np.float32) + + +class Rope: + """Interleaved-pair rotary embedding on the last `dim` features, at arbitrary positions.""" + + def __init__(self, dim, inv_freq: np.ndarray): + self.dim = dim + self.inv_freq = mx.array(inv_freq) + + def __call__(self, x: mx.array, positions: mx.array, inverse: bool = False) -> mx.array: + """x [..., L, (heads,) D] where the L axis matches `positions`; rotates x[..., -dim:].""" + return _rope_fn(self.dim, x.ndim, inverse)(x, positions, self.inv_freq) + + +_ROPE = {} + + +def _rope_fn(dim: int, ndim: int, inverse: bool): + key = (dim, ndim, inverse) + if key not in _ROPE: + def rope(x, positions, inv_freq): + ang = positions.astype(mx.float32)[:, None] * inv_freq[None] # [L, dim/2] + cos, sin = mx.cos(ang), mx.sin(ang) + if inverse: + sin = -sin + if ndim == 4: # [B, L, H, D] + cos, sin = cos[:, None, :], sin[:, None, :] + head, tail = x[..., :-dim], x[..., -dim:] + t = tail.astype(mx.float32).reshape(*tail.shape[:-1], dim // 2, 2) + a, b = t[..., 0], t[..., 1] + rot = mx.stack([a * cos - b * sin, a * sin + b * cos], axis=-1).reshape(tail.shape) + return mx.concatenate([head, rot.astype(x.dtype)], axis=-1) + + _ROPE[key] = mx.compile(rope) + return _ROPE[key] + + +# ----------------------------------------------------------------------------- layers + +class RMSNorm(nn.Module): + def __init__(self, dim, eps): + super().__init__() + self.weight = mx.ones((dim,)) + self.eps = eps + + def __call__(self, x): + # fp32 statistics, weight applied before the cast back -- same order as the release + return mx.fast.rms_norm(x, self.weight, self.eps) + + +def qlinear(in_dim, out_dim, bits): + return nn.QuantizedLinear(in_dim, out_dim, bias=False, group_size=GROUP_SIZE, bits=bits) + + +class DenseLinear(nn.Module): + """Source-precision weight kept as stored (bf16 / f32).""" + + def __init__(self, in_dim, out_dim, dtype=mx.bfloat16): + super().__init__() + self.weight = mx.zeros((out_dim, in_dim), dtype=dtype) + + def __call__(self, x, compute=None): + w = self.weight if compute is None else self.weight.astype(compute) + return (x if compute is None else x.astype(compute)) @ w.T + + +class QuantGrowBuffer: + """Append-only [1, T, D] buffer whose rows are stored 4-bit (affine, group_size GROUP_SIZE) so the + DSA compressed/index pools match the release's FP4 cache footprint (~4x smaller than bf16; a 1M-ctx + cache is ~890 MB, not ~3.2 GB). append() quantizes the incoming bf16 rows; view() dequantizes the + first n back to bf16 for the attention/indexer read path (the release dequantizes on read too). The + transient dequantized view is freed each step; only the 4-bit store is resident.""" + + STEP = 2048 + BITS = 4 + + def __init__(self): + self.wq = None # [1, T, D*BITS/32] uint32 packed + self.scales = None # [1, T, D/GROUP_SIZE] + self.biases = None + self.n = 0 + self.D = None + + def append(self, x: mx.array): + k = x.shape[1] + if k == 0: + return + self.D = x.shape[2] + wq, s, b = mx.quantize(x[0].astype(mx.bfloat16), group_size=GROUP_SIZE, bits=self.BITS) + wq, s, b = wq[None], s[None], b[None] + if self.wq is None or self.n + k > self.wq.shape[1]: + cap = ((self.n + k + self.STEP - 1) // self.STEP) * self.STEP + nwq = mx.zeros((1, cap, wq.shape[2]), dtype=mx.uint32) + ns = mx.zeros((1, cap, s.shape[2]), dtype=s.dtype) + nb = mx.zeros((1, cap, b.shape[2]), dtype=b.dtype) + if self.wq is not None: + nwq[:, : self.n] = self.wq[:, : self.n] + ns[:, : self.n] = self.scales[:, : self.n] + nb[:, : self.n] = self.biases[:, : self.n] + self.wq, self.scales, self.biases = nwq, ns, nb + self.wq[:, self.n : self.n + k] = wq + self.scales[:, self.n : self.n + k] = s + self.biases[:, self.n : self.n + k] = b + self.n += k + + def view(self, n=None): + n = self.n if n is None else n + if self.wq is None or n == 0: + return None + deq = mx.dequantize(self.wq[0, :n], self.scales[0, :n], self.biases[0, :n], + group_size=GROUP_SIZE, bits=self.BITS) + return deq[None] + + def gather(self, idx: mx.array) -> mx.array: + """Dequantize only the rows ``idx`` ([M] int32, each in [0, n)) -> [M, D] bf16. Bit-identical + to ``view()[0][idx]`` (dequantization is per row/group), without materializing the pool.""" + wq = mx.take(self.wq[0], idx, axis=0) + sc = mx.take(self.scales[0], idx, axis=0) + bi = mx.take(self.biases[0], idx, axis=0) + return mx.dequantize(wq, sc, bi, group_size=GROUP_SIZE, bits=self.BITS) + + def snapshot(self): + return (self.wq, self.scales, self.biases, self.n, self.D) + + def load(self, s): + self.wq, self.scales, self.biases, self.n, self.D = s + + def load_dense(self, x): + """Replace the buffer with the 4-bit quantization of a dense [1,T,D] bf16 array (used to + restore from a bf16 prefix-cache state without changing the stored serialization format).""" + self.wq = self.scales = self.biases = None + self.n = 0 + self.D = None + if x is not None and x.shape[1] > 0: + self.append(x) + + +class LayerCache: + def __init__(self): + self.window = None # [1, <=win, D] raw post-RoPE KV, oldest first + self.compress_kv = QuantGrowBuffer() # 4-bit resident (FP4-parity footprint) + self.index_k = QuantGrowBuffer() # 4-bit resident + self.pend_kv = None # compressor: tokens of the not yet complete group (ratio > 1), fp32 + self.pend_score = None + + +class Shared: + """What attention layers hand down the stack (release: SharedAttentionRuntime).""" + + def __init__(self): + self.compress_kv = None + self.index_k = None + self.topk_idxs = None + self.candidates = None + self._views = {} + self.capture = False # stash per-token projections for DSV41.commit_prefix (DSpark verify) + + def view(self, buf, n): + """``buf.view(n)`` memoized for this forward: a pool shared by several consumer layers (layer + 20's index pool feeds 5 indexers; each compressed pool up to 6 attention layers) is + dequantized once per forward instead of once per consumer. Lives only as long as this + Shared (one forward), so nothing extra stays resident between steps.""" + key = (id(buf), int(n), int(getattr(buf, "n", 0))) + hit = self._views.get(key) + if hit is None or hit[0] is not buf: + hit = (buf, buf.view(n)) + self._views[key] = hit + return hit[1] + + +# Queries per segment up to which attention gathers only its selected compressed rows from the 4-bit +# pool instead of dequantizing the whole pool (decode = 1, DSpark verify <= bs + 1). +GATHER_MAX_QUERIES = 8 +# Prompt-suffix pruning (Model.__call__ prompt_end): the layers after the last KV-source layer own no +# cache but their 128-token windows, so each one only needs the prompt rows the last prompt token can +# still reach through the windows above it. VMLX_DSV41_SUFFIX_PRUNE=0 runs every row through every layer. +SUFFIX_PRUNE = os.environ.get("VMLX_DSV41_SUFFIX_PRUNE", "1").strip().lower() not in {"0", "false", "off", "no"} + + +def sparse_attention(q, kv, sink, idxs, scale, chunk=256): + """q [1,S,H,D], kv [1,N,D] (keys == values), sink [H], idxs [1,S,K] int32 (-1 = none).""" + q, kv, idxs = q[0], kv[0].astype(mx.float32), idxs[0] + S, H, D = q.shape + outs = [] + for c in range(0, S, chunk): + outs.append(_attn_chunk(q[c : c + chunk], kv, sink, idxs[c : c + chunk], scale)) + return mx.concatenate(outs, axis=0)[None] if len(outs) > 1 else outs[0][None] + + +@mx.compile +def _attn_core(q, kv, sink, ix, scale): + valid = ix >= 0 + g = mx.take(kv, mx.where(valid, ix, 0), axis=0) # [C,K,D] + s = (q.astype(mx.float32) @ g.transpose(0, 2, 1)) * scale # [C,H,K] + s = mx.where(valid[:, None, :], s, -mx.inf) + m = mx.maximum(mx.max(s, axis=-1, keepdims=True), sink[None, :, None]) + p = mx.exp(s - m) + denom = mx.sum(p, axis=-1, keepdims=True) + mx.exp(sink[None, :, None] - m) + return (p @ g) / denom + + +def _attn_chunk(q, kv, sink, ix, scale): + return _attn_core(q, kv, sink, ix, mx.array(scale, mx.float32)) + + +# Prefill rows at least this long take the block top-k (topk_indices): MLX's GPU argpartition is a full +# sort of the row, which at long context dominates the indexer (2048 x 100k keys: 32.7 -> 13.5 ms, +# 256 x 1M: 51.9 -> 3.2 ms for the selection). Decode (<= GATHER_MAX_QUERIES rows) keeps the direct +# partition: faster there (170k context: 25.1 vs 23.9 tok/s) and its bf16 index scores tie often. +TOPK_BLOCK_MIN = 65536 +TOPK_BLOCK = 64 +# Fused index scores take the bf16 q / index keys / weights as is (the reference scores in bf16) on the +# M5 matrix units when vMLX supports it; VMLX_DSV41_INDEX_BF16=0 keeps fp32 operands. +FUSED_INDEX_BF16 = os.environ.get("VMLX_DSV41_INDEX_BF16", "1").strip().lower() not in {"0", "false", "off", "no"} + + +def topk_indices(scores, k): + """Indices of the k largest along the last axis (unordered). + + Long rows: the k largest values lie in the k blocks (of TOPK_BLOCK) with the largest maxima, so + select those blocks first and run the exact selection over their k*TOPK_BLOCK entries. Same + values selected; only the choice among exactly tied values can differ. Indices past the row end + (block padding) are -inf entries; callers mask indices past the visible length.""" + T = scores.shape[-1] + if k >= T: + return mx.broadcast_to(mx.arange(T, dtype=mx.int32), scores.shape) + if scores.ndim == 2 and scores.shape[0] > GATHER_MAX_QUERIES and T >= TOPK_BLOCK_MIN and T // TOPK_BLOCK > k: + C, b = scores.shape[0], TOPK_BLOCK + pad = -T % b + s = mx.concatenate([scores, mx.full((C, pad), -mx.inf, dtype=scores.dtype)], axis=-1) if pad else scores + nb = s.shape[1] // b + top_b = mx.argpartition(-mx.max(s.reshape(C, nb, b), axis=-1), kth=k - 1, axis=-1)[:, :k] + cand = (top_b[:, :, None] * b + mx.arange(b)[None, None]).reshape(C, -1) + sel = mx.argpartition(-mx.take_along_axis(s, cand, axis=-1), kth=k - 1, axis=-1)[:, :k] + return mx.take_along_axis(cand, sel, axis=-1).astype(mx.int32) + return mx.argpartition(-scores, kth=k - 1, axis=-1)[..., :k].astype(mx.int32) + + +def select_candidate_blocks(logits, compress_lens, topk_blocks, block_size): + """Level one of the two-level top-k. logits [C,T] with unreachable at -inf; lens [C,1].""" + C, T = logits.shape + pad = -T % block_size + sc = mx.concatenate([logits, mx.full((C, pad), -mx.inf)], axis=-1) if pad else logits + sc = mx.max(sc.reshape(C, -1, block_size), axis=-1) + nb = sc.shape[-1] + last = (compress_lens - 1) // block_size + sc = mx.where(mx.arange(nb)[None] == last, mx.inf, sc) + if topk_blocks >= nb: + keep = sc > -mx.inf + else: + top = mx.argpartition(-sc, kth=topk_blocks - 1, axis=-1)[:, :topk_blocks] + vals = mx.take_along_axis(sc, top, axis=-1) + keep = mx.put_along_axis(mx.zeros((C, nb), dtype=mx.bool_), top, vals > -mx.inf, axis=-1) + return mx.repeat(keep, block_size, axis=-1)[:, :T] + + +class Compressor(nn.Module): + def __init__(self, args: Args, ratio: int): + super().__init__() + self.ratio = ratio + self.norm = RMSNorm(args.head_dim, args.rms_norm_eps) + self.wkv = DenseLinear(args.hidden_size, args.head_dim) + if ratio > 1: + self.wgate = DenseLinear(args.hidden_size, args.head_dim) + + def __call__(self, x, start_pos, cache: LayerCache, capture: bool = False): + """Latents for the groups completed by this chunk, and the index of the first one. + + Group g pools tokens g*r .. g*r+r-1; a trailing partial group waits in the cache, so any + chunking (single prefill, continuation, one token per step) yields the same groups.""" + r = self.ratio + if r == 1: # one token per group: a plain projection, no pooling + latent = self.norm(self.wkv(x)) + if capture: + cache.verify_proj = latent + return latent, start_pos + kv, score = self.wkv(x, mx.float32), self.wgate(x, mx.float32) + if capture: + cache.verify_proj = (kv, score) + return self._pool(kv, score, start_pos, cache, x.dtype) + + def commit(self, proj, keep: int, start_pos: int, cache: LayerCache): + """Replay only the first ``keep`` tokens of a captured forward onto the restored cache: + the same groups / pending tail a forward of exactly those tokens would leave.""" + if self.ratio == 1: + return proj[:, :keep], start_pos + kv, score = proj + return self._pool(kv[:, :keep], score[:, :keep], start_pos, cache, mx.bfloat16) + + def _pool(self, kv, score, start_pos, cache: LayerCache, dtype): + r = self.ratio + n_pend = 0 + if cache.pend_kv is not None: + n_pend = cache.pend_kv.shape[1] + kv = mx.concatenate([cache.pend_kv, kv], axis=1) + score = mx.concatenate([cache.pend_score, score], axis=1) + total = kv.shape[1] + full = total - total % r + g0 = (start_pos - n_pend) // r + cache.pend_kv = kv[:, full:] if full < total else None + cache.pend_score = score[:, full:] if full < total else None + if full == 0: + return None, g0 + B = kv.shape[0] + kv = kv[:, :full].reshape(B, -1, r, kv.shape[-1]) + score = score[:, :full].reshape(B, -1, r, score.shape[-1]) + out = mx.sum(kv * mx.softmax(score, axis=2), axis=2) + return self.norm(out.astype(dtype)), g0 + + +def _fused_index_scores(): + """vMLX's fused DSA index-score Metal kernel (`dsa_pool_index_scores`), or None when vMLX is not + importable or VMLX_DSV41_FUSED_INDEX=0. The kernel returns None for shapes it does not admit, and + the caller then takes the stock path.""" + if os.environ.get("VMLX_DSV41_FUSED_INDEX", "1").strip().lower() in {"0", "false", "off", "no"}: + return None + try: + from vmlx_engine.metal.dsa_index_scores import dsa_pool_index_scores + except ImportError: # vMLX not installed: the stock bf16 indexer path + return None + return dsa_pool_index_scores + + +class Indexer(nn.Module): + def __init__(self, args: Args, layer_id: int, qbits: dict): + super().__init__() + self.owns_k = layer_id in args.kv_source_layer_ids + self.ratio = args.compress_ratios[layer_id] + self.is_candidate_source = layer_id == args.candidate_source_layer_id + self.uses_candidates = 0 <= args.candidate_source_layer_id < layer_id + self.n_heads, self.head_dim = args.index_n_heads, args.index_head_dim + self.topk = args.index_topk + self.cand_blocks, self.cand_size = args.candidate_topk_blocks, args.candidate_block_size + pfx = f"layers.{layer_id}.attn.indexer" + self.wq_b = qlinear(args.q_lora_rank, self.n_heads * self.head_dim, qbits[f"{pfx}.wq_b"]) + self.weights_proj = DenseLinear(args.hidden_size, self.n_heads) + if self.owns_k: + self.wk = DenseLinear(args.head_dim, self.head_dim) + self.k_norm = RMSNorm(self.head_dim, args.rms_norm_eps) + + def __call__(self, x, qr, latent, g0, start_pos, rope: Rope, cache: LayerCache, shared: Shared): + B, S, _ = x.shape + r, end = self.ratio, start_pos + S + if self.owns_k and latent is not None: + k = self.k_norm(self.wk(latent)) + cache.index_k.append(rope(k, (g0 + mx.arange(latent.shape[1])) * r)) + if self.owns_k: + shared.index_k = cache.index_k + T = end // r + q = self.wq_b(qr).reshape(B, S, self.n_heads, self.head_dim) + # the release scores in bf16 end to end; near-tied positions follow that rounding + q = rope(q, mx.arange(start_pos, end))[0].astype(mx.bfloat16) # [S,h,d] + index_k = shared.view(shared.index_k, T)[0].astype(mx.bfloat16) # [T,d] + w = (self.weights_proj(x) * (self.head_dim ** -0.5 * self.n_heads ** -0.5))[0] # [S,h] bf16 + k = min(self.topk, T) + fused = _fused_index_scores() if S > GATHER_MAX_QUERIES and T >= 32 else None + if fused is not None: + # Prefill: one fused kernel per query chunk computes sum_h w * relu(q . k) in fp32 without + # materializing [C, h, T] (100k keys: 164 -> 97 ms per index layer per 2048-token chunk). + # The chunk keeps the [C, T] fp32 scores near 1 GB at any context length. + chunk = max(16, min(S, (1 << 28) // T)) + qf, kf, wf = q.astype(mx.float32), index_k.astype(mx.float32)[None], w.astype(mx.float32) + else: + chunk = max(16, min(512, (1 << 26) // max(1, self.n_heads * T))) + out_idx, out_cand = [], [] + for c in range(0, S, chunk): + qi = q[c : c + chunk] + sc = None + if fused is not None: + sc = None + if FUSED_INDEX_BF16: + try: # vMLX >= 391ea34f: bf16 operands on the M5 matrix units (~4x the fp32 kernel) + sc = fused(q[None, c : c + chunk], index_k[None], w[None, c : c + chunk], 1.0, + bf16_operands=True) + except TypeError: # older vMLX: fp32 operands only + sc = None + if sc is None: + sc = fused(qf[None, c : c + chunk], kf, wf[None, c : c + chunk], 1.0) + sc = None if sc is None else sc[0] + if sc is None: + sc = mx.maximum(qi @ index_k.T, 0) # [C,h,T] + sc = mx.sum((sc * w[c : c + chunk, :, None]).astype(mx.float32), axis=1).astype(mx.bfloat16) + sc = sc.astype(mx.float32) # [C,T] + # compressed positions a query can see: a group is visible once the query passed its last token + lens = ((start_pos + mx.arange(c, c + qi.shape[0]) + 1) // r)[:, None] + sc = mx.where(mx.arange(T)[None] >= lens, -mx.inf, sc) + if self.is_candidate_source: + out_cand.append(select_candidate_blocks(sc, lens, self.cand_blocks, self.cand_size)) + elif self.uses_candidates: + sc = mx.where(shared.candidates[c : c + chunk], sc, -mx.inf) + idx = topk_indices(sc, k) + out_idx.append(mx.where(idx < lens, idx, -1).astype(mx.int32)) + if self.is_candidate_source: + shared.candidates = mx.concatenate(out_cand, axis=0) + return mx.concatenate(out_idx, axis=0)[None] + + +def append_compressed_rows(raw, widx, cidx, pool, T, shared, gather=False): + """Append the compressed-pool rows the queries attend to after the window rows. + + raw [1,L,D] window KV, widx [1,S,W] window indices into raw, cidx [1,S,K] top-k compressed indices + in [0,T) (-1 = none). Returns (kv, idxs) for sparse_attention. + + gather=False: the whole pool (dequantized once per forward via shared.view) is appended and cidx + is offset into it. gather=True (decode / DSpark verify): only the S*K selected rows are dequantized + from the 4-bit pool, each query's K slots get their own rows in the same order -- bit-identical + attention, without the full [T,D] dequant + concat + fp32 cast (~0.5-1 GB per layer per token at 1M + context).""" + if gather and isinstance(pool, QuantGrowBuffer): + S, K = cidx.shape[1], cidx.shape[2] + valid = cidx >= 0 + rows = pool.gather(mx.where(valid, cidx, 0).reshape(-1).astype(mx.int32)) # [S*K, D] + slot = mx.arange(S * K, dtype=mx.int32).reshape(1, S, K) + raw.shape[1] + cidx = mx.where(valid, slot, -1) + kv = mx.concatenate([raw, rows[None].astype(raw.dtype)], axis=1) + else: + comp = shared.view(pool, T) if shared is not None else pool.view(T) + cidx = mx.where(cidx >= 0, cidx + raw.shape[1], -1) + kv = mx.concatenate([raw, comp], axis=1) + return kv, mx.concatenate([widx, cidx], axis=-1) + + +class Seg: + """One sequence's slice of the token axis in a forward call.""" + + __slots__ = ("lo", "n", "start", "caches", "shared") + + def __init__(self, lo, n, start, caches): + self.lo, self.n, self.start, self.caches = lo, n, start, caches + self.shared = Shared() + + +class Attention(nn.Module): + def __init__(self, args: Args, layer_id: int, qbits: dict): + super().__init__() + pfx = f"layers.{layer_id}.attn" + d, H = args.hidden_size, args.num_attention_heads + self.layer_id = layer_id + self.n_heads, self.head_dim, self.rd = H, args.head_dim, args.qk_rope_head_dim + self.n_groups, self.o_lora_rank = args.o_groups, args.o_lora_rank + self.window = args.sliding_window + self.ratio = args.compress_ratios[layer_id] + self.scale = self.head_dim ** -0.5 + self.attn_sink = mx.zeros((H,), mx.float32) + self.wq_a = qlinear(d, args.q_lora_rank, qbits[f"{pfx}.wq_a"]) + self.q_norm = RMSNorm(args.q_lora_rank, args.rms_norm_eps) + self.wq_b = qlinear(args.q_lora_rank, H * self.head_dim, qbits[f"{pfx}.wq_b"]) + self.wkv = qlinear(d, self.head_dim, qbits[f"{pfx}.wkv"]) + self.kv_norm = RMSNorm(self.head_dim, args.rms_norm_eps) + self.wo_a = qlinear(H * self.head_dim // self.n_groups, self.n_groups * self.o_lora_rank, qbits[f"{pfx}.wo_a"]) + self.wo_b = qlinear(self.n_groups * self.o_lora_rank, d, qbits[f"{pfx}.wo_b"]) + self.is_kv_source = layer_id in args.kv_source_layer_ids + self.is_index_source = layer_id in args.index_source_layer_ids + if self.is_kv_source: + self.compressor = Compressor(args, self.ratio) + if self.is_index_source: + self.indexer = Indexer(args, layer_id, qbits) + rs = args.rope_scaling + if self.ratio: + inv = yarn_inv_freq(self.rd, args.compress_rope_theta, rs["original_max_position_embeddings"], + rs["factor"], rs["beta_fast"], rs["beta_slow"]) + else: + inv = yarn_inv_freq(self.rd, args.rope_theta, 0, 1, 0, 0) + self._rope = Rope(self.rd, inv) + + def __call__(self, x, segs): + """x [1,N,D] holds the tokens of every segment back to back; projections run batched, + window / compression / indexing / attention run per segment against its own cache.""" + B, N, _ = x.shape + pos = mx.concatenate([mx.arange(s.start, s.start + s.n) for s in segs]) if len(segs) > 1 \ + else mx.arange(segs[0].start, segs[0].start + segs[0].n) + qr = self.q_norm(self.wq_a(x)) + q = self._rope(self.wq_b(qr).reshape(B, N, self.n_heads, self.head_dim), pos) + kv = self._rope(self.kv_norm(self.wkv(x)), pos) + outs = [] + for s in segs: + sl = slice(s.lo, s.lo + s.n) + outs.append(self._core(x[:, sl], qr[:, sl], q[:, sl], kv[:, sl], s.start, s.caches[self.layer_id], s.shared)) + o = outs[0] if len(outs) == 1 else mx.concatenate(outs, axis=1) + o = self._rope(o, pos, inverse=True).astype(mx.bfloat16) + # wo_a is block-diagonal over groups: one batched quantized matmul per group + wa = self.wo_a + w = wa.weight.reshape(self.n_groups, self.o_lora_rank, -1) + sc = wa.scales.reshape(self.n_groups, self.o_lora_rank, -1) + bi = wa.biases.reshape(self.n_groups, self.o_lora_rank, -1) + if B * N > GATHER_MAX_QUERIES: + # Prefill: group-major [G, tokens, K] so each group is one matrix multiply. The + # token-major layout below runs one 1-row product per token per group (2048-token + # chunk: 18.6 ms -> 2.1 ms per layer). + og = o.reshape(B * N, self.n_groups, -1).transpose(1, 0, 2) + og = mx.quantized_matmul(og, w, sc, bi, transpose=True, group_size=wa.group_size, bits=wa.bits) + return self.wo_b(og.transpose(1, 0, 2).reshape(B, N, -1)) + # Decode / DSpark verify: per-row products, each row computed exactly as a 1-row decode. + o = o.reshape(B * N, self.n_groups, 1, -1) + o = mx.quantized_matmul(o, w, sc, bi, transpose=True, group_size=wa.group_size, bits=wa.bits) + return self.wo_b(o.reshape(B, N, -1)) + + def _core(self, x, qr, q, kv, start, cache: LayerCache, shared: Shared): + S = x.shape[1] + win = self.window + prev = cache.window + raw = kv if prev is None else mx.concatenate([prev, kv], axis=1) + base = start - (0 if prev is None else prev.shape[1]) # absolute position of raw[0] + K = min(win, start + S) + wpos = (start + mx.arange(S))[:, None] - (K - 1) + mx.arange(K)[None] # each query's window + widx = mx.where(wpos < 0, -1, wpos - base)[None].astype(mx.int32) + cache.window = raw[:, -win:] + if shared.capture: + cache.verify_kv = (start, kv) + + if self.ratio: + T, cidx = self._compressed(x, qr, start, cache, shared) + if T: + raw, widx = append_compressed_rows(raw, widx, cidx, shared.compress_kv, T, shared, + gather=S <= GATHER_MAX_QUERIES) + return sparse_attention(q, raw, self.attn_sink, widx, self.scale) + + def _compressed(self, x, qr, start_pos, cache: LayerCache, shared: Shared): + B, S, _ = x.shape + r = self.ratio + T = (start_pos + S) // r + latent, g0 = None, 0 + if self.is_kv_source: + latent, g0 = self.compressor(x, start_pos, cache, capture=shared.capture) + shared.compress_kv = cache.compress_kv + if self.is_index_source: + if T == 0: + idxs = mx.zeros((B, S, 0), mx.int32) + else: + idxs = self.indexer(x, qr, latent, g0, start_pos, self._rope, cache, shared) + shared.topk_idxs = idxs + else: + idxs = shared.topk_idxs + if latent is not None: + # a latent stands for the first token of its group + cache.compress_kv.append(self._rope(latent, (g0 + mx.arange(latent.shape[1])) * r)) + # T compressed rows are visible to this segment (read from shared.compress_kv by the caller) + return T, idxs + + +class SwitchProj(nn.Module): + def __init__(self, n_experts, in_dim, out_dim, bits): + super().__init__() + self.bits = bits + self.weight = mx.zeros((n_experts, out_dim, in_dim * bits // 32), mx.uint32) + self.scales = mx.zeros((n_experts, out_dim, in_dim // GROUP_SIZE), mx.bfloat16) + self.biases = mx.zeros((n_experts, out_dim, in_dim // GROUP_SIZE), mx.bfloat16) + + def __call__(self, x, idx, sorted_indices): + return mx.gather_qmm(x, self.weight, self.scales, self.biases, rhs_indices=idx, transpose=True, + group_size=GROUP_SIZE, bits=self.bits, sorted_indices=sorted_indices) + + +class SwitchMLP(nn.Module): + def __init__(self, args: Args, layer_id: int, qbits: dict): + super().__init__() + d, f, E = args.hidden_size, args.moe_intermediate_size, args.n_routed_experts + pfx = f"layers.{layer_id}.ffn.experts" + self.gate_proj = SwitchProj(E, d, f, qbits[f"{pfx}.gate_proj"]) + self.up_proj = SwitchProj(E, d, f, qbits[f"{pfx}.up_proj"]) + self.down_proj = SwitchProj(E, f, d, qbits[f"{pfx}.down_proj"]) + + +class SharedExpert(nn.Module): + def __init__(self, args: Args, layer_id: int, qbits: dict): + super().__init__() + d, f = args.hidden_size, args.moe_intermediate_size + pfx = f"layers.{layer_id}.ffn.shared_experts" + self.w1 = qlinear(d, f, qbits[f"{pfx}.w1"]) + self.w2 = qlinear(f, d, qbits[f"{pfx}.w2"]) + self.w3 = qlinear(d, f, qbits[f"{pfx}.w3"]) + + +class Gate(nn.Module): + def __init__(self, args: Args): + super().__init__() + E = args.n_routed_experts + self.weight = mx.zeros((E, args.hidden_size), mx.bfloat16) + self.bias = mx.zeros((E,), mx.float32) + self.bias_vl = mx.zeros((E,), mx.float32) + + +class FFN(nn.Module): + def __init__(self, args: Args, layer_id: int, qbits: dict): + super().__init__() + self.gate = Gate(args) + self.experts = SwitchMLP(args, layer_id, qbits) + self.shared_experts = SharedExpert(args, layer_id, qbits) + + +class Engram(nn.Module): + def __init__(self, args: Args, layer_id: int, layout: EngramLayout, qbits: dict): + super().__init__() + self.hash_index = layout.layer_ids.index(layer_id) + self.dim, self.hc = args.hidden_size, args.hc_mult + n_cols = (layout.max_ngram_size - 1) * layout.n_heads + self.wkv = qlinear(n_cols * layout.head_dim, args.hidden_size * (args.hc_mult + 1), qbits[f"layers.{layer_id}.engram.wkv"]) + self.q_weight = mx.ones((args.hc_mult, args.hidden_size)) + self.k_weight = mx.ones((args.hc_mult, args.hidden_size)) + self.eps = args.rms_norm_eps + + def __call__(self, h, rows, text_mask=None): + """h [1,S,hc,D]; rows [1,S,n_cols,head_dim] bf16 fetched from disk. + text_mask [1,S] (1.0 text, 0.0 image) zeros the engram contribution on image tokens.""" + kv = self.wkv(rows.reshape(*rows.shape[:2], -1)) + key = kv[..., : self.hc * self.dim].astype(mx.float32).reshape(*kv.shape[:2], self.hc, self.dim) + value = kv[..., self.hc * self.dim :].astype(mx.float32) + weight = self.q_weight.astype(mx.float32) * self.k_weight.astype(mx.float32) + hf = h.astype(mx.float32) + rstd = mx.rsqrt(mx.mean(hf * hf, -1) + self.eps) * mx.rsqrt(mx.mean(key * key, -1) + self.eps) + dot = mx.sum(hf * weight * key, -1) * rstd * self.dim ** -0.5 + gate = mx.sigmoid(mx.sign(dot) * mx.sqrt(mx.maximum(mx.abs(dot), 1e-6))) + if text_mask is not None: + gate = gate * text_mask[..., None] # image tokens contribute no n-gram + return (hf + gate[..., None] * value[:, :, None, :]).astype(h.dtype) + + +@mx.compile +def _hc_pre(x, pre): + return mx.sum(pre[..., None] * x.astype(mx.float32), axis=2).astype(x.dtype) + + +@mx.compile +def _hc_post(x, residual, post, comb): + y = post[..., None] * x[:, :, None, :].astype(mx.float32) + y = y + mx.einsum("bsjk,bsjd->bskd", comb, residual.astype(mx.float32)) + return y.astype(x.dtype) + + +_HC_KERNELS = {} + +_HC_SRC = """ + uint t = thread_position_in_grid.x; + if (t >= N) return; + const device float* m = mixes + t * 24; + float s0 = scale[0], s1 = scale[1], s2 = scale[2]; + for (int j = 0; j < 4; j++) { + pre[t * 4 + j] = 1.0f / (1.0f + metal::precise::exp(-(m[j] * s0 + base[j]))) + EPS; + post[t * 4 + j] = 2.0f / (1.0f + metal::precise::exp(-(m[4 + j] * s1 + base[4 + j]))); + } + float c[16]; + for (int i = 0; i < 16; i++) c[i] = m[8 + i] * s2 + base[8 + i]; + for (int r = 0; r < 4; r++) { + float mx_ = c[r * 4]; + for (int k = 1; k < 4; k++) mx_ = metal::max(mx_, c[r * 4 + k]); + float sum = 0.0f; + for (int k = 0; k < 4; k++) { c[r * 4 + k] = metal::precise::exp(c[r * 4 + k] - mx_); sum += c[r * 4 + k]; } + for (int k = 0; k < 4; k++) c[r * 4 + k] = c[r * 4 + k] / sum + EPS; + } + for (int k = 0; k < 4; k++) { + float cs = c[k] + c[4 + k] + c[8 + k] + c[12 + k]; + for (int r = 0; r < 4; r++) c[r * 4 + k] = c[r * 4 + k] / (cs + EPS); + } + for (int it = 0; it < ITERS - 1; it++) { + for (int r = 0; r < 4; r++) { + float rs = c[r * 4] + c[r * 4 + 1] + c[r * 4 + 2] + c[r * 4 + 3]; + for (int k = 0; k < 4; k++) c[r * 4 + k] = c[r * 4 + k] / (rs + EPS); + } + for (int k = 0; k < 4; k++) { + float cs = c[k] + c[4 + k] + c[8 + k] + c[12 + k]; + for (int r = 0; r < 4; r++) c[r * 4 + k] = c[r * 4 + k] / (cs + EPS); + } + } + for (int i = 0; i < 16; i++) comb[t * 16 + i] = c[i]; +""" + + +def _hc_split_metal(m, scale, base, iters: int, eps: float): + """pre/post/comb + Sinkhorn for hc=4 in one thread per token (release kernel order).""" + key = (iters, eps) + if key not in _HC_KERNELS: + src = _HC_SRC.replace("ITERS", str(int(iters))).replace("EPS", f"{float(eps):.9e}f") + _HC_KERNELS[key] = mx.fast.metal_kernel( + name=f"dsv41_hc_split_{iters}", input_names=["mixes", "scale", "base", "N_arr"], + output_names=["pre", "post", "comb"], source=src.replace("N)", "N_arr[0])")) + lead = m.shape[:-1] + flat = m.reshape(-1, m.shape[-1]).astype(mx.float32) + n = flat.shape[0] + pre, post, comb = _HC_KERNELS[key]( + inputs=[flat, scale.astype(mx.float32), base.astype(mx.float32), mx.array([n], mx.uint32)], + output_shapes=[(n, 4), (n, 4), (n, 16)], output_dtypes=[mx.float32] * 3, + grid=(n, 1, 1), threadgroup=(min(n, 256), 1, 1)) + return pre.reshape(*lead, 4), post.reshape(*lead, 4), comb.reshape(*lead, 4, 4) + + +_HC_SPLIT = {} + + +def _hc_split(hc: int, iters: int, eps: float): + """Compiled pre/post/comb split + Sinkhorn (thousands of tiny ops per token otherwise).""" + key = (hc, iters, eps) + if key not in _HC_SPLIT: + def split(m, scale, base): + pre = mx.sigmoid(m[..., :hc] * scale[0] + base[:hc]) + eps + post = 2 * mx.sigmoid(m[..., hc : 2 * hc] * scale[1] + base[hc : 2 * hc]) + comb = (m[..., 2 * hc :] * scale[2] + base[2 * hc :]).reshape(*m.shape[:-1], hc, hc) + comb = mx.softmax(comb, axis=-1) + eps + comb = comb / (mx.sum(comb, axis=-2, keepdims=True) + eps) + for _ in range(iters - 1): + comb = comb / (mx.sum(comb, axis=-1, keepdims=True) + eps) + comb = comb / (mx.sum(comb, axis=-2, keepdims=True) + eps) + return pre, post, comb + + _HC_SPLIT[key] = mx.compile(split) + return _HC_SPLIT[key] + + +_HC_FUSED_OK: dict = {} + + +def _hc_fused_ok(blk) -> bool: + """Once per (D, eps) per process: the fused hc stage / expand reproduce the stock ops bit for bit + on a random stream with this block's weights (guards against another MLX build). Only where f32 + GEMMs round to TF32 (M5 matrix units, MLX default): elsewhere the expand's 4-term sum follows another + order, a random-stream check can pass by chance and real decode then diverges, so stock ops.""" + from jang_tools.dsv41.metal_decode import _tf32 + D = blk.hc_attn_fn.shape[1] // blk.hc + tf32 = _tf32() + key = (D, blk.eps, blk.attn_norm.eps, blk.hc_eps, blk.iters, tf32) + ok = _HC_FUSED_OK.get(key) + if ok is None and not tf32: + ok = _HC_FUSED_OK[key] = False + if ok is None: + ok = False + try: + from jang_tools.dsv41.metal_decode import hc_post_decode, hc_stage_decode + k = mx.random.key(7) + x = (mx.random.normal((1, 2, blk.hc, D), key=k) * 3).astype(mx.bfloat16) + pre = mx.softmax(mx.random.normal((1, 2, blk.hc), key=mx.random.key(8)), axis=-1) + h = (mx.random.normal((1, 2, D), key=mx.random.key(9)) * 2).astype(mx.bfloat16) + st = hc_stage_decode(x[0], pre[0], blk.hc_attn_fn, blk.hc_attn_scale, blk.hc_attn_base, + blk.attn_norm.weight, blk.attn_norm.eps, blk.eps, blk.hc_eps, blk.iters) + if st is not None: + ok = True + for i in range(2): # stock, one row at a time + xi = x[:, i:i + 1] + ref = (blk.attn_norm(_hc_pre(xi, pre[:, i:i + 1])), + *blk.hc_mixes(xi, blk.hc_attn_fn, blk.hc_attn_scale, blk.hc_attn_base)) + for a, b in zip(st, ref): + ok = ok and mx.array_equal(a[i], b.reshape(b.shape[2:])).item() + post = hc_post_decode(h[0, i:i + 1], x[0, i:i + 1], st[2][i:i + 1], st[3][i:i + 1]) + ok = ok and post is not None and mx.array_equal( + post, _hc_post(h[:, i:i + 1], xi, st[2][None, i:i + 1], st[3][None, i:i + 1])[0]).item() + except (RuntimeError, ValueError, TypeError): # kernel build / launch failed: stock path + ok = False + _HC_FUSED_OK[key] = ok + return ok + + +class Block(nn.Module): + def __init__(self, args: Args, layer_id: int, layout: EngramLayout, qbits: dict): + super().__init__() + self.layer_id = layer_id + self.attn = Attention(args, layer_id, qbits) + self.ffn = FFN(args, layer_id, qbits) + if layer_id in layout.layer_ids: + self.engram = Engram(args, layer_id, layout, qbits) + self.attn_norm = RMSNorm(args.hidden_size, args.rms_norm_eps) + self.ffn_norm = RMSNorm(args.hidden_size, args.rms_norm_eps) + hc = args.hc_mult + mix = (2 + hc) * hc + for p in ("attn", "ffn"): + setattr(self, f"hc_{p}_fn", mx.zeros((mix, hc * args.hidden_size), mx.float32)) + setattr(self, f"hc_{p}_base", mx.zeros((mix,), mx.float32)) + setattr(self, f"hc_{p}_scale", mx.zeros((3,), mx.float32)) + self.hc, self.iters, self.hc_eps, self.eps = hc, args.hc_sinkhorn_iters, args.hc_eps, args.rms_norm_eps + self.topk, self.route_scale = args.num_experts_per_tok, args.routed_scaling_factor + self.norm_topk = args.norm_topk_prob + self.swiglu_limit = args.swiglu_limit + self.capture = None # set to fn(layer_id, e_idx[Nk], gate_up_in[Nk,D], down_in[Nk,F]) to collect stats + + # hyper-connections ------------------------------------------------------- + def hc_mixes(self, x, fn, scale, base): + B, S = x.shape[:2] + xf = x.reshape(B, S, -1).astype(mx.float32) + rs = mx.rsqrt(mx.mean(xf * xf, -1, keepdims=True) + self.eps) + m = (xf @ fn.T) * rs # [B,S,mix] + if self.hc == 4: + return _hc_split_metal(m, scale, base, self.iters, self.hc_eps) + return _hc_split(self.hc, self.iters, self.hc_eps)(m, scale, base) + + @staticmethod + def hc_pre(x, pre): + return _hc_pre(x, pre) + + @staticmethod + def hc_post(x, residual, post, comb): + return _hc_post(x, residual, post, comb) + + # moe ---------------------------------------------------------------------- + def moe(self, x, image_mask=None): + B, S, D = x.shape + xf = x.reshape(-1, D) + g = self.ffn.gate + logits = None + if ROUTER_GEMV and xf.shape[0] <= GATHER_MAX_QUERIES: + from jang_tools.dsv41.metal_decode import router_logits + logits = router_logits(xf, g.weight) + if logits is None: + logits = xf.astype(mx.float32) @ g.weight.astype(mx.float32).T + scores = mx.sqrt(nn.softplus(logits)) + # VL routing: image tokens use the separately-trained bias_vl (release Gate.forward) + bias = g.bias if image_mask is None else mx.where(image_mask.reshape(-1, 1), g.bias_vl, g.bias) + idx = mx.argpartition(-(scores + bias), kth=self.topk - 1, axis=-1)[:, : self.topk] + w = mx.take_along_axis(scores, idx, axis=-1) + if self.norm_topk and self.topk > 1: + w = w / (mx.sum(w, -1, keepdims=True) + 1e-20) + w = w * self.route_scale + + sw = self.ffn.experts + n = xf.shape[0] + if FUSED_MOE and n <= GATHER_MAX_QUERIES and self.capture is None: + from jang_tools.dsv41.metal_decode import moe_decode + y = moe_decode(xf, idx, w, sw, self.ffn.shared_experts, self.swiglu_limit) + if y is not None: + return y.reshape(B, S, D) + do_sort = n * self.topk >= 64 + xe = xf[:, None, None, :] # [N,1,1,D] + if do_sort: + flat = idx.reshape(-1) + order = mx.argsort(flat) + inv = mx.argsort(order) + xe = xe.reshape(n, D)[order // self.topk][:, None, :] # [N*k,1,D] + e_idx = flat[order] + else: + e_idx = idx + gate = sw.gate_proj(xe, e_idx, do_sort).astype(mx.float32) + up = sw.up_proj(xe, e_idx, do_sort).astype(mx.float32) + lim = self.swiglu_limit + if lim > 0: + up = mx.clip(up, -lim, lim) + gate = mx.minimum(gate, lim) + h = nn.silu(gate) * up + if do_sort: + h = h * w.reshape(-1)[order][:, None, None] + else: + h = h * w[:, :, None, None] + if self.capture is not None and do_sort: # calibration: per-expert projection inputs + self.capture(self.layer_id, e_idx, xe.reshape(-1, D), h.reshape(-1, h.shape[-1])) + y = sw.down_proj(h.astype(mx.bfloat16), e_idx, do_sort).astype(mx.float32) + if do_sort: + y = y[inv].reshape(n, self.topk, D) + else: + y = y.reshape(n, self.topk, D) + y = mx.sum(y, axis=1) + + se = self.ffn.shared_experts + sg = se.w1(xf).astype(mx.float32) + su = se.w3(xf).astype(mx.float32) + if lim > 0: + su = mx.clip(su, -lim, lim) + sg = mx.minimum(sg, lim) + y = y + se.w2((nn.silu(sg) * su).astype(mx.bfloat16)).astype(mx.float32) + return y.astype(x.dtype).reshape(B, S, D) + + def _stage(self, xs, pre, p): + """Fused hc_mixes + hc_pre + RMSNorm for sublayer p ("attn" / "ffn"), xs [S, 4, D].""" + from jang_tools.dsv41.metal_decode import hc_stage_decode + norm = getattr(self, f"{p}_norm") + return hc_stage_decode(xs, pre, getattr(self, f"hc_{p}_fn"), getattr(self, f"hc_{p}_scale"), + getattr(self, f"hc_{p}_base"), norm.weight, norm.eps, self.eps, self.hc_eps, self.iters) + + @staticmethod + def _post(h, xs, post, comb): + from jang_tools.dsv41.metal_decode import hc_post_decode + out = hc_post_decode(h, xs, post, comb) + return out if out is not None else _hc_post(h[None], xs[None], post[None], comb[None])[0] + + def _call_fused_hc(self, x, segs, pre_mix, image_mask): + S = x.shape[1] + xs = x[0] + st = self._stage(xs, pre_mix.reshape(S, self.hc), "attn") + if st is None: + return None + xin, a_pre, a_post, a_comb = st + xs = self._post(self.attn(xin[None], segs)[0], xs, a_post, a_comb) + st = self._stage(xs, a_pre, "ffn") + xin, f_pre, f_post, f_comb = st + xs = self._post(self.moe(xin[None], image_mask)[0], xs, f_post, f_comb) + return xs[None], f_pre[None] + + def __call__(self, x, segs, pre_mix, image_mask=None): + if (FUSED_HC and x.shape[0] == 1 and x.shape[1] <= GATHER_MAX_QUERIES and self.hc == 4 + and _hc_fused_ok(self)): + out = self._call_fused_hc(x, segs, pre_mix, image_mask) + if out is not None: + return out + residual = x + a_pre, a_post, a_comb = self.hc_mixes(x, self.hc_attn_fn, self.hc_attn_scale, self.hc_attn_base) + h = self.attn(self.attn_norm(self.hc_pre(x, pre_mix)), segs) + x = self.hc_post(h, residual, a_post, a_comb) + residual = x + f_pre, f_post, f_comb = self.hc_mixes(x, self.hc_ffn_fn, self.hc_ffn_scale, self.hc_ffn_base) + h = self.moe(self.ffn_norm(self.hc_pre(x, a_pre)), image_mask) + x = self.hc_post(h, residual, f_post, f_comb) + return x, f_pre + + +class Model(nn.Module): + def __init__(self, args: Args, qbits: dict, layout: EngramLayout, vision_args=None): + super().__init__() + self.args = args + self.embed = nn.QuantizedEmbedding(args.vocab_size, args.hidden_size, group_size=GROUP_SIZE, bits=qbits["embed"]) + self.layers = [Block(args, i, layout, qbits) for i in range(args.num_hidden_layers)] + self.norm = RMSNorm(args.hidden_size, args.rms_norm_eps) + self.head = qlinear(args.hidden_size, args.vocab_size, qbits["head"]) + self.layout = layout + self.vision_args = vision_args + # dSpark/MTP reads the mean-over-hc hidden at the INPUT of these layers (release Transformer.forward) + self.target_layer_ids = tuple(args.raw.get("dspark_target_layer_ids", ())) + # First layer prompt-suffix pruning may shorten: past the last KV-source (its compressor and index + # keys need every row) and past every Engram layer. Layers from here on keep only a window cache. + self.prune_from = max([*args.kv_source_layer_ids, *layout.layer_ids, args.candidate_source_layer_id]) + 1 + if vision_args is not None: + from jang_tools.dsv41.vision import ViT, Aligner, IMAGE, IMAGE_START, IMAGE_END, IMAGE_NEW_LINE + self.vision = ViT(vision_args) + self.aligner = Aligner(vision_args) + self.image_start = mx.zeros((args.hidden_size,), mx.bfloat16) + self.image_end = mx.zeros((args.hidden_size,), mx.bfloat16) + self.image_newline = mx.zeros((args.hidden_size,), mx.bfloat16) + self._img_types = (IMAGE, IMAGE_START, IMAGE_END, IMAGE_NEW_LINE) + + def encode_image(self, patches, n_vit_h, n_vit_w): + return self.aligner(self.vision(patches, n_vit_h, n_vit_w), n_vit_h, n_vit_w) + + def merge_image_embeddings(self, h, images): + """Overwrite each image's token span in h[0] with ViT/aligner features + learned delimiters.""" + IMAGE, IMAGE_START, IMAGE_END, IMAGE_NEW_LINE = self._img_types + for img in images: + types = np.asarray(img.types) + s = img.start + feats = self.encode_image(img.patches, img.n_vit_h, img.n_vit_w).astype(h.dtype) # [n_image_slots, D] + fi = 0 + rows = [] + for t in types: + if t == IMAGE: + rows.append(feats[fi]); fi += 1 + elif t == IMAGE_START: + rows.append(self.image_start.astype(h.dtype)) + elif t == IMAGE_END: + rows.append(self.image_end.astype(h.dtype)) + else: # IMAGE_NEW_LINE + rows.append(self.image_newline.astype(h.dtype)) + span = mx.stack(rows, axis=0) # [len(types), D] + h[0, s : s + len(types)] = span + return h + + def prune_rows(self, layer_id: int, seg_start: int, n: int, prompt_end: int) -> int: + """Trailing rows of an n-row forward starting at seg_start that layer ``layer_id`` must run so the + logits at ``prompt_end - 1`` and every layer's window cache at ``prompt_end`` are exact. + + A pruned layer's 128-token window reaches 127 rows back, so its first 127 kept rows see a partial + window and only its last keep - 127 outputs are exact; the layer above must not read further + back than that. The last layer needs its window (128 rows), hence keep = 1 + (L - i) * 127 for L + layers (layer 39: 128, layer 21: 2414). At least one row always runs, so a forward that lies + entirely before the kept range still leaves a window row at the right position.""" + win = self.args.sliding_window + keep = 1 + (len(self.layers) - layer_id) * (win - 1) + lo = max(seg_start, prompt_end - keep) + return max(1, min(n, seg_start + n - lo)) + + def __call__(self, tokens: mx.array, segs: list, engram_rows: dict, all_logits: bool = False, + images=None, image_mask: mx.array | None = None, return_hidden: bool = False, + prompt_end: int | None = None): + """tokens [1,N]: the segments' tokens back to back. engram_rows: {layer_id: [1,N,cols,head_dim]}. + images: list of ImageInput to splice into the prefill (start_pos 0). image_mask [1,N] bool, + True inside image spans. Returns fp32 logits at each segment's last token (or every token). + With return_hidden, also returns main_hidden [1,N,dim*len(target_layer_ids)] (bf16): the + mean-over-hc hidden at the INPUT of each dSpark target layer, concatenated -- the MTP head's + input (release Transformer.forward collects h.mean(dim=2) at target_layer_ids). + prompt_end: absolute position where the prompt ends (this forward ends at or before it). The + layers from prune_from run only the trailing rows the last prompt token still depends on + (prune_rows); the returned logits are exact only when this forward ends at prompt_end, and + main_hidden only for the last 128 rows before prompt_end (rows before are zero).""" + h = self.embed(tokens) + if images: + h = self.merge_image_embeddings(h, images) + hc = self.args.hc_mult + h = mx.repeat(h[:, :, None, :], hc, axis=2) + pre_mix = mx.zeros((*tokens.shape, hc), mx.float32) + pre_mix[..., 0] = 1.0 + text_mask = None if image_mask is None else (~image_mask).astype(mx.float32) + main_hiddens = [] + N = tokens.shape[1] + prune = (SUFFIX_PRUNE and prompt_end is not None and len(segs) == 1 and not all_logits and N > 1 + and prompt_end >= segs[0].start + N) + seg0, cur = segs[0], N + per_layer_async = LAYER_ASYNC and tokens.shape[-1] <= LAYER_ASYNC_MAX_ROWS + for i, layer in enumerate(self.layers): + if prune and i >= self.prune_from: + n = min(cur, self.prune_rows(i, seg0.start, N, prompt_end)) + if n < N: + # Rows before the kept suffix never reach this layer: its window restarts at the + # suffix (the stale rows would sit at the wrong positions; only rows whose outputs + # nothing reads see the shortened window). + seg0.caches[i].window = None + if n < cur: + h, pre_mix = h[:, -n:], pre_mix[:, -n:] + if image_mask is not None: + image_mask = image_mask[:, -n:] + sh = seg0.shared + if sh.topk_idxs is not None: + sh.topk_idxs = sh.topk_idxs[:, -n:] + if sh.candidates is not None: + sh.candidates = sh.candidates[-n:] + seg = Seg(0, n, seg0.start + N - n, seg0.caches) + seg.shared = sh + segs, cur = [seg], n + if i in engram_rows: + rows = engram_rows[i] + if callable(rows): # still being read: start the layers so far on the GPU meanwhile + mx.async_eval(h, pre_mix) + rows = rows() + h = layer.engram(h, rows, text_mask) + if return_hidden and i in self.target_layer_ids: + mh = mx.mean(h, axis=2) # [1,cur,dim] at this layer's input + if cur < N: # pruned: rows before the suffix are not computed (zeros, never read) + mh = mx.pad(mh, [(0, 0), (N - cur, 0), (0, 0)]) + main_hiddens.append(mh) + h, pre_mix = layer(h, segs, pre_mix, image_mask) + if per_layer_async: + mx.async_eval(h, pre_mix) + if not all_logits: + last = mx.array([sg.lo + sg.n - 1 for sg in segs]) + h, pre_mix = h[:, last], pre_mix[:, last] + h = Block.hc_pre(h, pre_mix) + # fp32 head input -> fp32 logits, as the reference (F.linear(x.float(), weight)). In bf16 the + # top-2 logits tie exactly every ~50-100 tokens, and a batched verify forward breaks those + # ties differently from single-token decode, so DSpark drifted from greedy AR. + logits = self.head(self.norm(h).astype(mx.float32))[0] + if return_hidden: + main_hidden = mx.concatenate(main_hiddens, axis=-1) if main_hiddens else None + return logits, main_hidden + return logits + + +# ----------------------------------------------------------------------------- loading + +def _infer_bits(bundle: Path) -> dict[str, int]: + from jang_tools.dsv41.st_io import read_header + + index = json.loads((bundle / "model.safetensors.index.json").read_text())["weight_map"] + shapes = {} + for fn in sorted(set(index.values())): + header, _ = read_header(bundle / fn) + for k, v in header.items(): + if k != "__metadata__": + shapes[k] = v["shape"] + bits = {} + for k, shp in shapes.items(): + if k.endswith(".scales"): + base = k[: -len(".scales")] + wshape = shapes[base + ".weight"] + bits[base] = wshape[-1] * 32 // (shp[-1] * GROUP_SIZE) + return bits + + +class DSV41: + """Loaded bundle + tokenizer + Engram hasher/tables, with a batch-1 session.""" + + def __init__(self, bundle: str | Path, engram_dir: str | Path | None = None, wired: bool = True): + from tokenizers import Tokenizer + + bundle = Path(bundle).expanduser() + cfg = json.loads((bundle / "config.json").read_text()) + text = cfg["text_config"] + self.args = Args.from_config(text) + self.eos_id = cfg.get("eos_token_id", 1) + layout = EngramLayout.from_config(text) + qbits = _infer_bits(bundle) + # vision tower (VL): weights live in the bundle as BF16 passthrough; enabled when present + self.vision_args = None + if "vision_config" in cfg and cfg["vision_config"].get("num_hidden_layers", 0) > 0: + from jang_tools.dsv41.vision import VisionArgs + self.vision_args = VisionArgs.from_config(cfg) + self.model = Model(self.args, qbits, layout, self.vision_args) + + index = json.loads((bundle / "model.safetensors.index.json").read_text())["weight_map"] + skip = () if self.vision_args is not None else ("vision.", "aligner.", "image_") + if wired: + info = mx.device_info() + mx.set_wired_limit(int(info["max_recommended_working_set_size"])) + from mlx.utils import tree_flatten + + shapes = {k: v.shape for k, v in tree_flatten(self.model.parameters())} + for fn in sorted(set(index.values())): + w = mx.load(str(bundle / fn)) + w = [(k, v) for k, v in w.items() if not k.startswith(skip)] + bad = [(k, v.shape, shapes.get(k)) for k, v in w if k in shapes and tuple(v.shape) != tuple(shapes[k])] + if bad: + raise RuntimeError(f"shape mismatch in {fn}: {bad[:3]}") + self.model.load_weights(w, strict=False) + mx.eval(self.model.parameters()) + self._check_loaded(index, skip) + + self.tokenizer = Tokenizer.from_file(str(bundle / "tokenizer.json")) + self.hasher = NgramHasher(text, layout, bundle / "tokenizer.json") + edir = Path(engram_dir).expanduser() if engram_dir else bundle / "engram" + self.tables = open_engram_tables(edir, layout.layer_ids) + self.layout = layout + self.reset() + + def _check_loaded(self, index, skip): + from mlx.utils import tree_flatten + + params = dict(tree_flatten(self.model.parameters())) + expected = {k for k in index if not k.startswith(skip)} + missing = expected - params.keys() + unset = params.keys() - expected + if missing or unset: + raise RuntimeError(f"weight mismatch: {len(missing)} unused bundle tensors, {len(unset)} unloaded params " + f"(e.g. {sorted(missing)[:3]} / {sorted(unset)[:3]})") + + def reset(self): + self.session = self.new_session() + + # sessions --------------------------------------------------------------- + def new_session(self) -> "Session": + return Session(self.args.num_hidden_layers) + + @property + def pos(self) -> int: + return self.session.pos + + @property + def caches(self): + return self.session.caches + + def _engram_rows(self, ids: np.ndarray, start_pos: int, sess: "Session | None" = None, + keep: np.ndarray | None = None, lazy: bool = False) -> dict: + """{layer_id: rows [1,S,cols,head_dim]}. With lazy, the reads run in the background (layer + by layer, first layer first) and only the first is waited for here; later layers get a + callable the forward resolves when it reaches them, after queueing the earlier layers on + the GPU, so their cold SSD reads overlap compute (one forward, no extra weight passes). + Rows already requested by a matching `engram_lookahead` are used instead of reading.""" + sess = sess or self.session + ahead = getattr(sess, "engram_ahead", None) + sess.engram_ahead = None + if ahead is not None and keep is None and ahead[0] == start_pos and np.array_equal(ahead[1], ids): + _, _, pending, sess.history = ahead + else: + hashes, sess.history = self.hasher.hash(ids, start_pos, sess.history, keep) # [S, n_layers, cols] + if not lazy: + return {lid: self.tables[lid].lookup(hashes[:, j])[None] for j, lid in enumerate(self.layout.layer_ids)} + pending = self._read_ahead(hashes) + rows = {} + for k, (lid, (t, f, shape)) in enumerate(zip(self.layout.layer_ids, pending)): + if k == 0: + rows[lid] = t.finish(shape, f.result())[None] + else: + rows[lid] = lambda t=t, f=f, shape=shape: t.finish(shape, f.result())[None] + return rows + + def _read_ahead(self, hashes: np.ndarray) -> list: + """Start background reads of every Engram layer's rows for hashes [S, n_layers, cols], one + layer after another so the first layer's rows (needed first) get every I/O lane.""" + out, prev = [], None + for j, lid in enumerate(self.layout.layer_ids): + t = self.tables[lid] + f = t.prefetch(hashes[:, j], after=prev) + out.append((t, f, hashes[:, j].shape)) + prev = f + return out + + def _start_lookahead(self, sess, ids: list[int]): + """Request the rows for `ids`, the tokens the next forward on `sess` will append, while + this forward runs on the GPU. The hashes need only token ids and the n-gram history; + the history they produce is applied when that forward consumes the record.""" + arr = np.asarray(ids, np.int64) + hashes, history = self.hasher.hash(arr, sess.pos, sess.history, None) + sess.engram_ahead = (sess.pos, arr, self._read_ahead(hashes), history) + + def forward(self, ids: list[int], sess: "Session | None" = None, all_logits: bool = False, + images=None, token_types=None, return_hidden: bool = False, + engram_lookahead: list[int] | None = None, capture_verify: bool = False, + prompt_end: int | None = None) -> mx.array: + """Append tokens to a session (prefill, continuation or one decode step). + images/token_types carry VL inputs (image spans must be in a single start_pos-0 prefill). + engram_lookahead: the next chunk of a chunked prefill; its Engram rows are read while this + forward computes (text tokens only). + capture_verify: keep references to this forward's per-token cache inputs so commit_prefix + can later keep only a prefix of these tokens (DSpark partial accept, no second forward). + prompt_end: absolute position where the prompt being prefilled ends (Model.__call__): the late + layers then skip prompt rows the end of the prompt no longer depends on. Pass it only for + prefill chunks whose logits are discarded or that end exactly at prompt_end. + Returns fp32 logits [vocab] at the last token ([len(ids), vocab] with all_logits). + With return_hidden also returns main_hidden [len(ids), dim*n_targets] for the dSpark head.""" + sess = sess or self.session + arr = np.asarray(ids, np.int64) + image_mask = None + if token_types is not None: + tt = np.asarray(token_types) + image_mask = mx.array((tt >= 0)[None]) # [1,N] bool, True inside image spans + # image tokens take no part in an n-gram (release engram_mask = ~image_mask) + engram_mask = None if token_types is None else (np.asarray(token_types) < 0) + rows = self._engram_rows(arr, sess.pos, sess, engram_mask, lazy=len(arr) >= ENGRAM_LAZY_MIN) + seg = Seg(0, len(ids), sess.pos, sess.caches) + seg.shared.capture = capture_verify + out = self.model(mx.array(arr[None].astype(np.int32)), [seg], rows, all_logits=all_logits, + images=images, image_mask=image_mask, return_hidden=return_hidden, + prompt_end=None if capture_verify else prompt_end) + sess.pos += len(ids) + if engram_lookahead: + self._start_lookahead(sess, engram_lookahead) + if return_hidden: + logits, main_hidden = out + mh = None if main_hidden is None else main_hidden[0] # [N, dim*n_targets] + return (logits if all_logits else logits[0]), mh + return out if all_logits else out[0] + + def commit_prefix(self, sess, ck, keep: int): + """Keep only the first ``keep`` tokens of the capture_verify forward that followed checkpoint + ``ck`` -- the cache state a forward of exactly those tokens would have left, with no second + forward. Per layer: restore, then re-append the kept tokens' window rows and replay the + compressor on their captured projections (same groups, pending tail, pool/index rows and + RoPE positions as in Attention._compressed). History and position are truncated.""" + history = sess.history # includes the verify's tokens (absolute positions) + sess.restore(ck) + start = sess.pos + for layer, cache in zip(self.model.layers, sess.caches): + attn = layer.attn + cap = getattr(cache, "verify_kv", None) + if cap is None: + raise RuntimeError("commit_prefix needs a capture_verify forward after the checkpoint") + v_start, kv = cap + assert v_start == start, (v_start, start) + prev = cache.window + raw = kv[:, :keep] if prev is None else mx.concatenate([prev, kv[:, :keep]], axis=1) + cache.window = raw[:, -attn.window:] + if attn.ratio and attn.is_kv_source: + r = attn.ratio + latent, g0 = attn.compressor.commit(cache.verify_proj, keep, start, cache) + if latent is not None: + pos = (g0 + mx.arange(latent.shape[1])) * r + if attn.is_index_source and attn.indexer.owns_k: + ix = attn.indexer + cache.index_k.append(attn._rope(ix.k_norm(ix.wk(latent)), pos)) + cache.compress_kv.append(attn._rope(latent, pos)) + cache.verify_kv = None + cache.verify_proj = None + sess.history = history[: start + keep] + sess.pos = start + keep + + def decode_batch(self, sessions: list["Session"], tokens: list[int]) -> mx.array: + """One token for each of several sessions in a single forward. Returns logits [B, vocab].""" + rows_parts = [self._engram_rows(np.asarray([t], np.int64), s.pos, s) for s, t in zip(sessions, tokens)] + rows = {lid: mx.concatenate([r[lid] for r in rows_parts], axis=1) for lid in self.layout.layer_ids} + segs = [Seg(i, 1, s.pos, s.caches) for i, s in enumerate(sessions)] + logits = self.model(mx.array([tokens], mx.int32), segs, rows) + for s in sessions: + s.pos += 1 + return logits + + +class Session: + """Per-sequence state: layer caches, Engram compressed-token history, position.""" + + def __init__(self, n_layers: int): + self.caches = [LayerCache() for _ in range(n_layers)] + self.history = np.zeros(0, np.int64) + self.pos = 0 + + def checkpoint(self): + """O(1) snapshot (refs only) for speculative verification. QuantGrowBuffer.append either + grows a fresh buffer or writes past `.n` in place, so saving each buffer's snapshot() and the + window/pend refs is enough: bytes below `.n` are never mutated and view only reads [:n].""" + caches = [] + for c in self.caches: + caches.append(( + c.window, + c.compress_kv.snapshot(), + c.index_k.snapshot(), + c.pend_kv, c.pend_score, + )) + return (caches, self.history, self.pos) + + def restore(self, ck): + caches, history, pos = ck + for c, s in zip(self.caches, caches): + c.window = s[0] + c.compress_kv.load(s[1]) + c.index_k.load(s[2]) + c.pend_kv, c.pend_score = s[3], s[4] + self.history = history + self.pos = pos diff --git a/jang-tools/jang_tools/dsv41/prefill_probe.py b/jang-tools/jang_tools/dsv41/prefill_probe.py new file mode 100644 index 00000000..8c2bb5a1 --- /dev/null +++ b/jang-tools/jang_tools/dsv41/prefill_probe.py @@ -0,0 +1,27 @@ +"""Raw standalone prefill pp/s for the DSV4.1 runtime (no engine/scheduler overhead). +Times m.forward(prompt) for several sizes, warm (2nd run), to find the runtime prefill ceiling.""" +import sys, time +from pathlib import Path +import mlx.core as mx +sys.path.insert(0, str(Path.home() / "jang/jang-tools")) +from jang_tools.dsv41.model import DSV41 + +m = DSV41(str(Path.home() / "models/DeepSeek-V4.1-Flash-1017-JANG-Q2Q3-IMATRIX")) +vocab = m.args.vocab_size +import random +for n in (512, 1024, 2048, 4096): + ids = [random.randint(1000, min(vocab - 1, 100000)) for _ in range(n)] + # natural-ish: repeat a small coherent token window so engram rows are cache-coherent + base = m.tokenizer.encode("The quick brown fox jumps over the lazy dog. ", add_special_tokens=False).ids + ids = (base * (n // len(base) + 1))[:n] + best = None + for trial in range(2): + sess = m.new_session() + t0 = time.time() + logits = m.forward(ids, sess) + mx.eval(logits) + dt = time.time() - t0 + pps = n / dt + best = pps if best is None else max(best, pps) + del sess, logits; mx.clear_cache() + print(f"n={n:5d} prefill {best:7.1f} pp/s ({n/best*1000:.0f} ms)", flush=True) diff --git a/jang-tools/jang_tools/dsv41/st_io.py b/jang-tools/jang_tools/dsv41/st_io.py new file mode 100644 index 00000000..77a971f6 --- /dev/null +++ b/jang-tools/jang_tools/dsv41/st_io.py @@ -0,0 +1,157 @@ +"""Torch-free safetensors access and DSV4.1 source codecs. + +The DSV4.1 release stores: + - non-routed matmuls as F8_E4M3 with one F8_E8M0 scale per 32x32 block + - routed experts as I8 (two FP4 e2m1 nibbles per byte) with one F8_E8M0 + scale per 32 input columns (i.e. MXFP4) + - Engram tables as F8_E4M3 rows with one F8_E8M0 scale per 32 columns + - control tensors as BF16 / F32 + +Headers are parsed directly so tensors can be read with a single pread and +decoded on the GPU with MLX. Nothing here imports torch. +""" + +from __future__ import annotations + +import json +import os +import struct +from dataclasses import dataclass +from pathlib import Path + +import mlx.core as mx +import numpy as np + +_NP_STORAGE = { + "F8_E4M3": np.uint8, + "F8_E8M0": np.uint8, + "I8": np.uint8, + "U8": np.uint8, + "BF16": np.uint16, + "F16": np.float16, + "F32": np.float32, + "I32": np.int32, + "I64": np.int64, +} + +FP4_TABLE = mx.array( + [0.0, 0.5, 1.0, 1.5, 2.0, 3.0, 4.0, 6.0, 0.0, -0.5, -1.0, -1.5, -2.0, -3.0, -4.0, -6.0], + dtype=mx.float32, +) + + +@dataclass(frozen=True) +class TensorMeta: + path: Path + dtype: str + shape: tuple[int, ...] + offset: int # absolute byte offset in the file + nbytes: int + + +def read_header(path: Path) -> tuple[dict, int]: + with open(path, "rb") as f: + (n,) = struct.unpack(" location map for a directory of safetensors shards.""" + + def __init__(self, root: str | Path, index_name: str = "model.safetensors.index.json", allow_missing: bool = False): + self.root = Path(root) + index = self.root / index_name + if index.exists(): + files = sorted(set(json.loads(index.read_text())["weight_map"].values())) + else: + files = sorted(p.name for p in self.root.glob("*.safetensors")) + self.meta: dict[str, TensorMeta] = {} + self.missing: list[str] = [] + for fn in files: + path = self.root / fn + if allow_missing and not path.exists(): + self.missing.append(fn) + continue + header, base = read_header(path) + for name, info in header.items(): + if name == "__metadata__": + continue + start, end = info["data_offsets"] + self.meta[name] = TensorMeta(path, info["dtype"], tuple(info["shape"]), base + start, end - start) + + def __contains__(self, name: str) -> bool: + return name in self.meta + + def keys(self): + return self.meta.keys() + + def raw(self, name: str) -> np.ndarray: + m = self.meta[name] + buf = np.empty(m.nbytes, dtype=np.uint8) + with open(m.path, "rb", buffering=0) as f: + fd = f.fileno() + view = memoryview(buf) + done = 0 + while done < m.nbytes: + got = os.preadv(fd, [view[done:]], m.offset + done) + if got <= 0: + raise IOError(f"short read for {name}") + done += got + return buf.view(_NP_STORAGE[m.dtype]).reshape(m.shape) + + def to_mx(self, name: str) -> mx.array: + """Raw tensor as an MLX array; BF16 comes back as bfloat16, FP8 / I8 as uint8.""" + m = self.meta[name] + arr = mx.array(self.raw(name)) + if m.dtype == "BF16": + arr = arr.view(mx.bfloat16) + return arr + + def dequant(self, name: str, dtype=mx.bfloat16) -> mx.array: + """Dequantized weight. Dispatches on the stored dtype and the sibling `.scale`.""" + m = self.meta[name] + if m.dtype in ("BF16", "F16", "F32"): + return self.to_mx(name).astype(dtype) + scale_name = name[: -len(".weight")] + ".scale" if name.endswith(".weight") else name + ".scale" + w = self.to_mx(name) + s = self.to_mx(scale_name) + if m.dtype == "F8_E4M3": + return dequant_fp8_block(w, s, dtype) + if m.dtype == "I8": + return dequant_fp4(w, s, dtype) + raise ValueError(f"cannot dequantize {name} ({m.dtype})") + + +def e8m0_to_float(s: mx.array) -> mx.array: + """UE8M0 byte -> 2 ** (byte - 127), built exactly from the float32 exponent bits. + + Byte 0 (2**-127) is a float32 subnormal: mantissa bit 22. 0xFF is NaN in the spec and never + stored.""" + b = s.astype(mx.uint32) + bits = mx.where(b == 0, mx.array(0x00400000, mx.uint32), mx.left_shift(b, 23)) + return bits.view(mx.float32) + + +def dequant_fp8_block(w: mx.array, s: mx.array, dtype=mx.bfloat16) -> mx.array: + """F8_E4M3 [out, in] with E8M0 scales [ceil(out/bo), ceil(in/bi)]; block size inferred.""" + out_dim, in_dim = w.shape + bo = -(-out_dim // s.shape[0]) + bi = -(-in_dim // s.shape[1]) + scale = e8m0_to_float(s) + scale = mx.repeat(mx.repeat(scale, bo, axis=0)[:out_dim], bi, axis=1)[:, :in_dim] + return (mx.from_fp8(w, dtype=mx.float32) * scale).astype(dtype) + + +def dequant_fp4(w: mx.array, s: mx.array, dtype=mx.bfloat16) -> mx.array: + """Packed FP4 (low nibble = even column) [..., out, in/2] with E8M0 scales per 32 columns. + + FP4 values times a power of two are exact in bfloat16, so the bf16 result is lossless. + """ + lo = mx.bitwise_and(w, 0x0F) + hi = mx.right_shift(w, 4) + vals = mx.stack([FP4_TABLE[lo], FP4_TABLE[hi]], axis=-1).reshape(*w.shape[:-1], w.shape[-1] * 2) + in_dim = vals.shape[-1] + block = in_dim // s.shape[-1] + vals = vals.reshape(*vals.shape[:-1], s.shape[-1], block) * e8m0_to_float(s)[..., None] + return vals.reshape(*w.shape[:-1], in_dim).astype(dtype) diff --git a/jang-tools/jang_tools/dsv41/tests/__init__.py b/jang-tools/jang_tools/dsv41/tests/__init__.py new file mode 100644 index 00000000..e69de29b diff --git a/jang-tools/jang_tools/dsv41/tests/bench_decode.py b/jang-tools/jang_tools/dsv41/tests/bench_decode.py new file mode 100644 index 00000000..0378d922 --- /dev/null +++ b/jang-tools/jang_tools/dsv41/tests/bench_decode.py @@ -0,0 +1,156 @@ +"""Decode-path microbenchmarks at the bundle's per-layer dimensions (random weights, no bundle load). + + python -m jang_tools.dsv41.tests.bench_decode stack --layers 10 --experts 16 # full decode step + python -m jang_tools.dsv41.tests.bench_decode moe [--rows 1] # Block.moe per layer + python -m jang_tools.dsv41.tests.bench_decode router [--rows 1] + python -m jang_tools.dsv41.tests.bench_decode hc [--rows 1] + +Each A/B toggles one module flag in-process and interleaves the two sides in rounds, so both see the +same GPU clock / contention. Reports the median per round. +""" + +from __future__ import annotations + +import argparse +import statistics +import time + +import mlx.core as mx +import numpy as np + +from jang_tools.dsv41 import model as M +from jang_tools.dsv41.tests import synth as S + + +def _ab(run, flags: dict, rounds: int, reps: int): + """run() -> sync'ed work; flags {label: setter(bool)}. Interleaves off/on rounds and times every call. + Returns {label: ((p10, median) off, (p10, median) on)} in ms. Another process shares this GPU, so the + low percentile is the better estimate of the uncontended cost.""" + res = {} + for label, setter in flags.items(): + t = {False: [], True: []} + for r in range(rounds): + for on in ((False, True) if r % 2 == 0 else (True, False)): + setter(on) + run() # warm (kernel compile / cache) + for _ in range(reps): + t0 = time.perf_counter() + run() + t[on].append((time.perf_counter() - t0) * 1e3) + res[label] = tuple((float(np.percentile(t[k], 10)), statistics.median(t[k])) for k in (False, True)) + setter(True) + return res + + +def _fmt(off, on): + return (f"off p10 {off[0]:7.3f} med {off[1]:7.3f} | on p10 {on[0]:7.3f} med {on[1]:7.3f} ms " + f"| p10 {off[0] / on[0]:.3f}x med {off[1] / on[1]:.3f}x") + + +def bench_stack(a): + args = S.real_args(a.layers, a.experts) + model = S.build(args) + caches = S.new_caches(args) + rng = np.random.default_rng(0) + prompt = rng.integers(0, args.vocab_size, a.ctx).tolist() + mx.eval(S.forward(model, prompt, caches, 0)) + state = {"pos": a.ctx, "tok": 1} + + def step(): + lg = S.forward(model, [state["tok"]] * a.rows, caches, state["pos"], all_logits=a.rows > 1) + state["tok"] = int(mx.argmax(lg[-1])) + state["pos"] += a.rows + + def set_async(on): + M.LAYER_ASYNC = on + + flags = {k: FLAG_SETTERS[k] for k in a.flags.split(",") if k in FLAG_SETTERS} or {"layer_async": set_async} + out = _ab(step, flags, a.rounds, a.reps) + for k, (off, on) in out.items(): + print(f"stack L={a.layers} E={a.experts} ctx={a.ctx} rows={a.rows} {k:12s} {_fmt(off, on)}") + + +FLAG_SETTERS = {} + + +def _flag(name): + def set_(on): + setattr(M, name, on) + return set_ + + +def _all(on): + for name in ("LAYER_ASYNC", "ROUTER_GEMV", "FUSED_MOE", "FUSED_HC"): + setattr(M, name, on) + + +FLAG_SETTERS["all"] = _all +FLAG_SETTERS.update(router_gemv=_flag("ROUTER_GEMV"), fused_moe=_flag("FUSED_MOE"), fused_hc=_flag("FUSED_HC")) + + +def _chain(a, op): + """op(block, x [1,R,D] bf16) -> [1,R,D]; runs it over `--layers` distinct real-dimension blocks, + `--cycles` times, as one serial graph (each layer's input depends on the previous output), so the + weights stream from DRAM as in decode. Returns run() and the number of op calls per run.""" + args = S.real_args(a.layers, a.experts) + model = S.build(args, expert_bits=lambda i: (a.gate_bits, 3)) + x0 = (mx.random.normal((1, a.rows, args.hidden_size)) * 0.8).astype(mx.bfloat16) + mx.eval(x0) + n = a.layers * a.cycles + + def run(): + x = x0 + for c in range(a.cycles): + for blk in model.layers: + x = mx.fast.rms_norm(op(blk, x), None, 1e-6) + mx.eval(x) + + return run, n + + +def bench_moe(a): + run, n = _chain(a, lambda blk, x: blk.moe(x)) + flags = {k: FLAG_SETTERS[k] for k in (a.flags or "fused_moe").split(",") if k in FLAG_SETTERS} + out = _ab(run, flags, a.rounds, a.reps) + for k, (off, on) in out.items(): + print(f"moe/layer rows={a.rows} gate_bits={a.gate_bits} E={a.experts} {k:12s} " + f"{_fmt(tuple(v / n for v in off), tuple(v / n for v in on))}") + + +def bench_hc(a): + """The hyper-connection stage alone: the decode stack with attention and MoE replaced by x * 0.5.""" + M.Attention.__call__ = lambda self, x, segs: x * 0.5 + M.Block.moe = lambda self, x, image_mask=None: x * 0.5 + args = S.real_args(a.layers, a.experts) + model = S.build(args) + caches = S.new_caches(args) + state = {"pos": 0} + + def step(): + mx.eval(S.forward(model, [1] * a.rows, caches, state["pos"], all_logits=True)) + state["pos"] += a.rows + + out = _ab(step, {k: FLAG_SETTERS[k] for k in (a.flags or "fused_hc").split(",") if k in FLAG_SETTERS}, + a.rounds, a.reps) + for k, (off, on) in out.items(): + print(f"hc/layer rows={a.rows} {k:12s} {_fmt(tuple(v / a.layers for v in off), tuple(v / a.layers for v in on))}") + + +def main(): + ap = argparse.ArgumentParser() + ap.add_argument("what", choices=["stack", "moe", "hc"]) + ap.add_argument("--cycles", type=int, default=4) + ap.add_argument("--layers", type=int, default=10) + ap.add_argument("--experts", type=int, default=16) + ap.add_argument("--ctx", type=int, default=1024) + ap.add_argument("--rows", type=int, default=1) + ap.add_argument("--gate-bits", type=int, default=2) + ap.add_argument("--rounds", type=int, default=6) + ap.add_argument("--reps", type=int, default=10) + ap.add_argument("--flags", default="") + a = ap.parse_args() + {"stack": bench_stack, "moe": bench_moe, "hc": bench_hc}[a.what](a) + + +if __name__ == "__main__": + main() diff --git a/jang-tools/jang_tools/dsv41/tests/parity_reference.py b/jang-tools/jang_tools/dsv41/tests/parity_reference.py new file mode 100644 index 00000000..ee07a190 --- /dev/null +++ b/jang-tools/jang_tools/dsv41/tests/parity_reference.py @@ -0,0 +1,225 @@ +"""Parity: release inference/model.py (CPU torch, shimmed kernels) vs the MLX port. + +Builds a small random DSV4.1 that exercises every V4.1 mechanism (ratio 0/2/1 +layers, KV-source sharing, index sources without their own keys, candidate +blocks, Engram, sliding window), writes it as a JANG-layout bundle (8-bit affine +everywhere, Engram table as an FP8 + E8M0 safetensors file), then compares +prefill and teacher-forced decode logits step by step. + + python jang_tools/dsv41/tests/parity_reference.py --src ~/models/DeepSeek-V4.1-Flash-1017 +""" + +from __future__ import annotations + +import argparse +import json +import shutil +import sys +import tempfile +from pathlib import Path + +import numpy as np +import torch + +HERE = Path(__file__).resolve().parent + + +def build_config(): + from jang_tools.dsv41.engram import _next_prime + + eng = { + "engram_layer_ids": [1, 4], + "engram_max_ngram_size": 3, + "engram_vocab_size": 1000, + "engram_n_heads": 2, + "engram_head_dim": 32, + "engram_pad_token_id": 2, + "engram_compressed_vocab_size": 99092, + } + # table sizes = sum of the bucket primes, drawn the same way the release does + seen, sizes = set(), [] + for _ in eng["engram_layer_ids"]: + tot = 0 + for _ in range(eng["engram_max_ngram_size"] - 1): + cur = eng["engram_vocab_size"] - 1 + for _ in range(eng["engram_n_heads"]): + cur = _next_prime(cur, seen) + seen.add(cur) + tot += cur + sizes.append(tot) + eng["engram_num_embeddings"] = sizes + text = { + "vocab_size": 129280, "hidden_size": 256, "moe_intermediate_size": 128, "num_hidden_layers": 6, + "num_attention_heads": 4, "head_dim": 64, "qk_rope_head_dim": 16, "q_lora_rank": 64, + "o_lora_rank": 32, "o_groups": 2, "swiglu_limit": 10.0, "rms_norm_eps": 1e-20, "rope_theta": 10000, + "rope_scaling": {"rope_type": "yarn", "factor": 4, "beta_fast": 32, "beta_slow": 1, + "original_max_position_embeddings": 64}, + "n_routed_experts": 8, "num_experts_per_tok": 2, "routed_scaling_factor": 1.5, "norm_topk_prob": True, + "sliding_window": 16, "compress_ratios": [0, 2, 2, 1, 1, 1], "compress_rope_theta": 40000, + "kv_source_layer_ids": [1, 3], "index_source_layer_ids": [1, 3, 5], "index_n_heads": 16, + "index_head_dim": 32, "index_topk": 8, "candidate_source_layer_id": 3, "candidate_topk_blocks": 3, + "candidate_block_size": 4, "hc_mult": 4, "hc_sinkhorn_iters": 20, "hc_eps": 1e-6, **eng, + } + return text + + +def ref_args(ref, t): + rs = t["rope_scaling"] + return ref.ModelArgs( + max_batch_size=1, max_seq_len=256, temperature=0, dtype="bf16", expert_dtype=None, + vocab_size=t["vocab_size"], dim=t["hidden_size"], moe_inter_dim=t["moe_intermediate_size"], + n_layers=t["num_hidden_layers"], n_mtp_layers=0, n_heads=t["num_attention_heads"], + n_routed_experts=t["n_routed_experts"], n_activated_experts=t["num_experts_per_tok"], + route_scale=t["routed_scaling_factor"], swiglu_limit=t["swiglu_limit"], q_lora_rank=t["q_lora_rank"], + head_dim=t["head_dim"], rope_head_dim=t["qk_rope_head_dim"], norm_eps=t["rms_norm_eps"], + o_groups=t["o_groups"], o_lora_rank=t["o_lora_rank"], window_size=t["sliding_window"], + compress_ratios=tuple(t["compress_ratios"]), kv_source_layers=tuple(t["kv_source_layer_ids"]), + index_source_layers=tuple(t["index_source_layer_ids"]), compress_rope_theta=t["compress_rope_theta"], + original_seq_len=rs["original_max_position_embeddings"], rope_theta=t["rope_theta"], + rope_factor=rs["factor"], beta_fast=rs["beta_fast"], beta_slow=rs["beta_slow"], + index_n_heads=t["index_n_heads"], index_head_dim=t["index_head_dim"], index_topk=t["index_topk"], + candidate_source_layer=t["candidate_source_layer_id"], candidate_topk_blocks=t["candidate_topk_blocks"], + candidate_block_size=t["candidate_block_size"], hc_mult=t["hc_mult"], + engram_layer_ids=tuple(t["engram_layer_ids"]), engram_num_embeddings=tuple(t["engram_num_embeddings"]), + engram_max_ngram_size=t["engram_max_ngram_size"], engram_vocab_size=t["engram_vocab_size"], + engram_n_heads=t["engram_n_heads"], engram_head_dim=t["engram_head_dim"], + engram_pad_id=t["engram_pad_token_id"], engram_compressed_vocab_size=t["engram_compressed_vocab_size"], + vision_n_layers=0, dspark_block_size=0, + ) + + +def randomize(model, seed=0): + g = torch.Generator().manual_seed(seed) + with torch.no_grad(): + for name, p in model.named_parameters(): + if p.dtype in (torch.float8_e4m3fn,): + p.copy_((torch.randn(p.shape, generator=g) * 2).to(torch.float8_e4m3fn)) + elif p.dtype == torch.float8_e8m0fnu: + p.copy_((2.0 ** -torch.randint(1, 4, p.shape, generator=g).float()).to(torch.float8_e8m0fnu)) + elif "norm" in name or name.endswith(("q_weight", "k_weight")): + p.copy_(1 + 0.1 * torch.randn(p.shape, generator=g)) + elif "hc_" in name and name.endswith("scale"): + p.copy_(0.5 + 0.1 * torch.randn(p.shape, generator=g)) + elif "hc_" in name and name.endswith("base"): + p.copy_(0.3 * torch.randn(p.shape, generator=g)) + elif name.endswith(("attn_sink", ".bias")): + p.copy_(0.5 * torch.randn(p.shape, generator=g)) + else: + fan_in = p.shape[-1] if p.ndim > 1 else 1 + p.copy_(torch.randn(p.shape, generator=g) / fan_in ** 0.5) + + +def write_bundle(model, text, src: Path, out: Path): + import mlx.core as mx + from jang_tools.dsv41.convert_dsv41_jang import PASSTHROUGH_RE + + out.mkdir(parents=True, exist_ok=True) + (out / "engram").mkdir() + sd = {k: v.detach() for k, v in model.state_dict().items()} + tensors, engram = {}, {} + experts: dict = {} + + def to_mx(t): + if t.dtype == torch.bfloat16: + return mx.array(t.view(torch.uint16).numpy()).view(mx.bfloat16) + return mx.array(t.numpy()) + + def write_back(t, q): + # the reference then runs on exactly the weights the bundle holds + deq = mx.dequantize(*q, group_size=64, bits=8).astype(mx.float32) + with torch.no_grad(): + t.copy_(torch.from_numpy(np.array(deq)).reshape(t.shape).to(t.dtype)) + + for name, t in sd.items(): + if ".engram.embed." in name: + engram[name] = t.contiguous() + continue + parts = name.split(".") + if ".ffn.experts." in name: + experts.setdefault((int(parts[1]), parts[5]), {})[int(parts[4])] = t + continue + if not PASSTHROUGH_RE.search(name) and name.endswith(".weight") and t.ndim == 2: + qw, s, b = mx.quantize(to_mx(t.to(torch.bfloat16)), group_size=64, bits=8) + write_back(t, (qw, s, b)) + base = name[: -len(".weight")] + tensors.update({f"{base}.weight": qw, f"{base}.scales": s, f"{base}.biases": b}) + else: + tensors[name] = to_mx(t) + proj = {"w1": "gate_proj", "w2": "down_proj", "w3": "up_proj"} + for (layer, w), d in experts.items(): + stack = torch.stack([d[e] for e in sorted(d)]).to(torch.bfloat16) + qw, s, b = mx.quantize(to_mx(stack), group_size=64, bits=8) + for i, e in enumerate(sorted(d)): + write_back(d[e], (qw[i], s[i], b[i])) + base = f"layers.{layer}.ffn.experts.{proj[w]}" + tensors.update({f"{base}.weight": qw, f"{base}.scales": s, f"{base}.biases": b}) + for l in range(text["num_hidden_layers"]): + tensors.setdefault(f"layers.{l}.ffn.gate.bias_vl", mx.zeros((text["n_routed_experts"],))) + mx.save_safetensors(str(out / "model-00001-of-00001.safetensors"), tensors) + (out / "model.safetensors.index.json").write_text(json.dumps( + {"metadata": {}, "weight_map": {k: "model-00001-of-00001.safetensors" for k in tensors}})) + (out / "config.json").write_text(json.dumps({"eos_token_id": 1, "text_config": text})) + shutil.copy2(src / "tokenizer.json", out / "tokenizer.json") + from safetensors.torch import save_file + + save_file(engram, str(out / "engram" / "engram-00001-of-00001.safetensors")) + + +def main(): + ap = argparse.ArgumentParser() + ap.add_argument("--src", required=True, help="release dir (tokenizer + inference/)") + ap.add_argument("--prompt-len", type=int, default=70) + ap.add_argument("--decode", type=int, default=40) + ap.add_argument("--full-selection", action="store_true", + help="index_topk / candidate blocks cover every position: no near-tie flips, strict check") + a = ap.parse_args() + src = Path(a.src).expanduser() + + sys.path[:0] = [str(HERE / "ref_shim"), str(src / "inference")] + import model as ref # the release reference, with shimmed kernels + from transformers import AutoTokenizer + + torch.set_default_dtype(torch.bfloat16) + text = build_config() + if a.full_selection: + text.update(index_topk=512, candidate_topk_blocks=512) + tok = AutoTokenizer.from_pretrained(str(src)) + rmodel = ref.Transformer(ref_args(ref, text), tok) + torch.set_default_dtype(torch.float32) + randomize(rmodel) + + sample = (src / "encoding" / "README.md").read_text() + ids = tok.encode(sample, add_special_tokens=False)[: a.prompt_len + a.decode] + P = a.prompt_len + + from jang_tools.dsv41.model import DSV41 + + with tempfile.TemporaryDirectory() as td: + bundle = Path(td) / "bundle" + write_bundle(rmodel, text, src, bundle) + ref_logits = [] + with torch.inference_mode(): + x = torch.tensor([ids]) + ref_logits.append(rmodel.forward(x[:, :P], 0)[1][0].float().numpy()) + for i in range(P, len(ids) - 1): + ref_logits.append(rmodel.forward(x[:, i : i + 1], i)[1][0].float().numpy()) + m = DSV41(bundle, wired=False) + mine = [np.array(m.forward(ids[:P]))] + for i in range(P, len(ids) - 1): + mine.append(np.array(m.forward([ids[i]]))) + + worst_cos, agree = 1.0, 0 + for step, (r, o) in enumerate(zip(ref_logits, mine)): + cos = float(np.dot(r, o) / (np.linalg.norm(r) * np.linalg.norm(o))) + rel = float(np.linalg.norm(r - o) / np.linalg.norm(r)) + worst_cos = min(worst_cos, cos) + agree += int(r.argmax() == o.argmax()) + if step in (0, 1, len(mine) - 1) or cos < 0.995: + print(f"step {step:3d} pos {P + step - 1 if step else P - 1:4d} cos {cos:.5f} rel {rel:.4f} " + f"top1 {r.argmax()} vs {o.argmax()}") + print(f"steps {len(mine)} worst cos {worst_cos:.5f} top1 agree {agree}/{len(mine)}") + sys.exit(0 if worst_cos > (0.999 if a.full_selection else 0.8) else 1) + + +if __name__ == "__main__": + main() diff --git a/jang-tools/jang_tools/dsv41/tests/parity_vision.py b/jang-tools/jang_tools/dsv41/tests/parity_vision.py new file mode 100644 index 00000000..ef4adcb1 --- /dev/null +++ b/jang-tools/jang_tools/dsv41/tests/parity_vision.py @@ -0,0 +1,107 @@ +"""Numeric parity: MLX vision tower (ViT+Aligner) vs the release torch reference. + +Loads the real BF16 vision weights from a JANG bundle into both the release torch modules and the +MLX port, runs identical random patches through, and reports max/mean relative error on the ViT +output and the final aligner output. This validates the 2D RoPE, the attention, the SwiGLU MLP and +the 3x3 unfold merge independently of the main backbone forward. + + python -m jang_tools.dsv41.tests.parity_vision --bundle \ + --ref ~/models/DeepSeek-V4.1-Flash-1017/inference +""" + +from __future__ import annotations + +import argparse +import json +import sys +from pathlib import Path +from types import SimpleNamespace + +import mlx.core as mx +import numpy as np + + +def main(): + ap = argparse.ArgumentParser() + ap.add_argument("--bundle", required=True) + ap.add_argument("--ref", required=True, help="release inference/ dir with vision.py") + ap.add_argument("--nh", type=int, default=4) + ap.add_argument("--nw", type=int, default=6) + a = ap.parse_args() + + import torch + + bundle = Path(a.bundle).expanduser() + cfg = json.loads((bundle / "config.json").read_text()) + from jang_tools.dsv41.vision import ViT as MLViT, Aligner as MLAligner, VisionArgs + + va = VisionArgs.from_config(cfg) + + # locate + load the vision/aligner BF16 tensors from the bundle + index = json.loads((bundle / "model.safetensors.index.json").read_text())["weight_map"] + files = sorted({f for t, f in index.items() if t.startswith(("vision.", "aligner.", "image_"))}) + W = {} + for f in files: + W.update({k: v.astype(mx.float32) for k, v in mx.load(str(bundle / f)).items() + if k.startswith(("vision.", "aligner.", "image_"))}) # f32: clean parity (bf16 values exact) + print(f"loaded {len(W)} vision tensors from {files}") + + # --- MLX side --- + ml_vit, ml_al = MLViT(va), MLAligner(va) + ml_vit.load_weights([(k[len("vision."):], v) for k, v in W.items() if k.startswith("vision.")], strict=True) + ml_al.load_weights([(k[len("aligner."):], v) for k, v in W.items() if k.startswith("aligner.")], strict=True) + mx.eval(ml_vit.parameters(), ml_al.parameters()) + + # --- torch reference side --- + sys.path.insert(0, str(Path(a.ref).expanduser())) + import vision as refv # release inference/vision.py + + rargs = SimpleNamespace( + vision_dim=va.dim, vision_n_heads=va.n_heads, vision_inter_dim=va.inter_dim, + vision_patch_size=va.patch_size, vision_rope_theta=va.rope_theta, + vision_n_layers=va.n_layers, vision_downsample_ratio=va.downsample_ratio, dim=va.text_dim, + ) + ref_vit, ref_al = refv.ViT(rargs), refv.Aligner(rargs) + + def to_t(v): + return torch.from_numpy(np.array(v.astype(mx.float32))) # f32 + + sd_vit = {k[len("vision."):]: to_t(v) for k, v in W.items() if k.startswith("vision.")} + sd_al = {k[len("aligner."):]: to_t(v) for k, v in W.items() if k.startswith("aligner.")} + ref_vit.load_state_dict(sd_vit, strict=True) + ref_al.load_state_dict(sd_al, strict=True) + ref_vit.eval(); ref_al.eval() + + # identical random patches + nh, nw = a.nh, a.nw + p = va.patch_size + rng = np.random.default_rng(0) + patches = rng.standard_normal((nh * nw, 3, p, p)).astype(np.float32) * 0.5 + + with torch.inference_mode(): + r_vit = ref_vit(torch.from_numpy(patches), nh, nw) + r_al = ref_al(r_vit, nh, nw) + m_vit = ml_vit(mx.array(patches), nh, nw) + m_al = ml_al(m_vit, nh, nw) + mx.eval(m_vit, m_al) + + def rel(ref_t, ml_a, name): + r = ref_t.float().numpy() + m = np.array(ml_a.astype(mx.float32)) + assert r.shape == m.shape, f"{name} shape {r.shape} vs {m.shape}" + num = np.linalg.norm((r - m).ravel()) + den = np.linalg.norm(r.ravel()) + 1e-9 + mx_abs = np.abs(r - m).max() + print(f"{name:12s} shape={r.shape} rel-L2={num/den:.3e} max-abs={mx_abs:.3e}") + return num / den + + print(f"\ngrid n_vit={nh}x{nw} -> {nh*nw} patches; aligner -> {m_al.shape[0]} llm tokens") + e1 = rel(r_vit, m_vit, "ViT out") + e2 = rel(r_al, m_al, "Aligner out") + ok = e1 < 2e-2 and e2 < 2e-2 + print("\nPARITY", "PASS" if ok else "FAIL", "(bf16 tolerance 2e-2 rel-L2)") + sys.exit(0 if ok else 1) + + +if __name__ == "__main__": + main() diff --git a/jang-tools/jang_tools/dsv41/tests/ref_shim/kernel.py b/jang-tools/jang_tools/dsv41/tests/ref_shim/kernel.py new file mode 100644 index 00000000..f68a561e --- /dev/null +++ b/jang-tools/jang_tools/dsv41/tests/ref_shim/kernel.py @@ -0,0 +1,55 @@ +"""Plain-torch stand-ins for the release's TileLang kernels (CPU parity tests only). + +Activation quant round-trips are identity here, so the reference runs the same +bf16/fp32 numerics as the MLX port. sparse_attn and hc_split_sinkhorn follow the +kernel semantics exactly. +""" + +import torch + + +def act_quant(x, block_size=128, scale_fmt=None, scale_dtype=torch.float32, inplace=False): + if inplace: + return x + raise NotImplementedError("fp8 GEMM path is not used in bf16 parity mode") + + +def fp4_act_quant(x, block_size=32, inplace=False, scale_dtype=None): + if inplace: + return x + raise NotImplementedError + + +def fp8_gemm(*a, **k): + raise NotImplementedError + + +def fp4_gemm(*a, **k): + raise NotImplementedError + + +def sparse_attn(q, kv, attn_sink, topk_idxs, softmax_scale): + b, s, h, d = q.shape + valid = topk_idxs >= 0 + idx = topk_idxs.clamp_min(0).long() + g = torch.gather(kv.float().unsqueeze(1).expand(b, s, *kv.shape[1:]), 2, idx[..., None].expand(*idx.shape, d)) + scores = torch.einsum("bshd,bskd->bshk", q.float(), g) * softmax_scale + scores = scores.masked_fill(~valid[:, :, None, :], float("-inf")) + m = torch.maximum(scores.amax(-1, keepdim=True), attn_sink.float()[None, None, :, None]) + p = torch.exp(scores - m) + denom = p.sum(-1, keepdim=True) + torch.exp(attn_sink.float()[None, None, :, None] - m) + o = torch.einsum("bshk,bskd->bshd", p, g) / denom + return o.to(q.dtype) + + +def hc_split_sinkhorn(mixes, hc_scale, hc_base, hc_mult=4, sinkhorn_iters=20, eps=1e-6): + hc = hc_mult + pre = torch.sigmoid(mixes[..., :hc] * hc_scale[0] + hc_base[:hc]) + eps + post = 2 * torch.sigmoid(mixes[..., hc : 2 * hc] * hc_scale[1] + hc_base[hc : 2 * hc]) + comb = (mixes[..., 2 * hc :] * hc_scale[2] + hc_base[2 * hc :]).unflatten(-1, (hc, hc)) + comb = comb.softmax(-1) + eps + comb = comb / (comb.sum(-2, keepdim=True) + eps) + for _ in range(sinkhorn_iters - 1): + comb = comb / (comb.sum(-1, keepdim=True) + eps) + comb = comb / (comb.sum(-2, keepdim=True) + eps) + return pre, post, comb diff --git a/jang-tools/jang_tools/dsv41/tests/replay_reference.py b/jang-tools/jang_tools/dsv41/tests/replay_reference.py new file mode 100644 index 00000000..899706be --- /dev/null +++ b/jang-tools/jang_tools/dsv41/tests/replay_reference.py @@ -0,0 +1,130 @@ +"""Strict port check: replay the release reference's per-block inputs through the MLX blocks. + +End-to-end logits on a random MoE drift on routing near-ties (bf16 noise flips a +top-k expert and the error compounds), so parity_reference.py is a loose check. +Here every MLX attention / block / Engram call receives the reference's exact +input for that layer and step, over a single-shot prefill plus teacher-forced +decode, so cache, compressor-state, KV-sharing, indexer and hc logic are checked +without compounding. Selection covers all positions (no near-tie top-k flips). +Block outputs whose MoE router has a near-tie (top-k margin < 0.02) are reported +but not failed. + + PYTHONPATH=jang-tools python jang_tools/dsv41/tests/replay_reference.py --src ~/models/DeepSeek-V4.1-Flash-1017 +""" + +from __future__ import annotations + +import argparse +import sys +import tempfile +from pathlib import Path + +import numpy as np +import torch + +from jang_tools.dsv41.tests import parity_reference as P + + +def main(): + ap = argparse.ArgumentParser() + ap.add_argument("--src", required=True) + ap.add_argument("--prompt-len", type=int, default=70) + ap.add_argument("--decode", type=int, default=40) + ap.add_argument("--tol", type=float, default=0.02) + a = ap.parse_args() + src = Path(a.src).expanduser() + sys.path[:0] = [str(Path(P.__file__).parent / "ref_shim"), str(src / "inference")] + import model as ref + from transformers import AutoTokenizer + + import mlx.core as mx + from jang_tools.dsv41 import model as M + + torch.set_default_dtype(torch.bfloat16) + text = P.build_config() + text.update(index_topk=512, candidate_topk_blocks=512) + tok = AutoTokenizer.from_pretrained(str(src)) + rm = ref.Transformer(P.ref_args(ref, text), tok) + torch.set_default_dtype(torch.float32) + P.randomize(rm) + n = a.prompt_len + ids = tok.encode((src / "encoding" / "README.md").read_text(), add_special_tokens=False)[: n + a.decode] + + rec = {"blk": [], "attn": [], "eng": []} + + def wrap(cls, key, fn): + orig = cls.forward + + def f(self, *args, **kw): + out = orig(self, *args, **kw) + rec[key].append(fn(args, out)) + return out + + cls.forward = f + + cpy = lambda t: t.float().numpy().copy() # noqa: E731 + wrap(ref.Block, "blk", lambda ar, o: (cpy(ar[0]), cpy(ar[2]), cpy(o[0]), cpy(o[1]))) + wrap(ref.Attention, "attn", lambda ar, o: (cpy(ar[0]), cpy(o))) + wrap(ref.Engram, "eng", lambda ar, o: (cpy(ar[0]), cpy(o))) + + with tempfile.TemporaryDirectory() as td: + bundle = Path(td) / "bundle" + P.write_bundle(rm, text, src, bundle) + with torch.inference_mode(): + x = torch.tensor([ids]) + rm.forward(x[:, :n], 0) + for i in range(n, len(ids) - 1): + rm.forward(x[:, i : i + 1], i) + m = M.DSV41(bundle, wired=False) + + layers = m.model.layers + nl = len(layers) + steps = len(rec["blk"]) // nl + + def rel(o, r, base=None): + return float(np.linalg.norm(o - r) / np.linalg.norm(r if base is None else base)) + + # attention replay (own caches) + caches = [M.LayerCache() for _ in layers] + worst_attn = 0.0 + for t in range(steps): + sp = 0 if t == 0 else n - 1 + t + seg = M.Seg(0, n if t == 0 else 1, sp, caches) + for i, layer in enumerate(layers): + xin, out = rec["attn"][t * nl + i] + o = layer.attn(mx.array(xin).astype(mx.bfloat16), [seg]) + worst_attn = max(worst_attn, rel(np.array(o.astype(mx.float32)), out)) + + # block + engram replay (fresh caches) + sess = m.new_session() + caches = sess.caches + worst_blk, worst_eng, ties, k = 0.0, 0.0, 0, 0 + for t in range(steps): + sp = 0 if t == 0 else n - 1 + t + tk = ids[:n] if t == 0 else [ids[n - 1 + t]] + seg = M.Seg(0, len(tk), sp, caches) + rows = m._engram_rows(np.array(tk), sp, sess) + for i, layer in enumerate(layers): + if i in rows: + ein, eout = rec["eng"][k] + k += 1 + o = layer.engram(mx.array(ein).astype(mx.bfloat16), rows[i]) + worst_eng = max(worst_eng, rel(np.array(o.astype(mx.float32)), eout, eout - ein)) + xin, pm, out, opm = rec["blk"][t * nl + i] + h, _ = layer(mx.array(xin).astype(mx.bfloat16), [seg], mx.array(pm)) + e = rel(np.array(h.astype(mx.float32)), out) + if e > a.tol: + ties += 1 + print(f" block {i} step {t}: rel {e:.3f} (router near-tie suspected)") + else: + worst_blk = max(worst_blk, e) + + print(f"attention worst rel {worst_attn:.4f} | block worst rel {worst_blk:.4f} " + f"({ties} near-tie outliers) | engram worst rel-of-delta {worst_eng:.4f}") + ok = worst_attn < a.tol and worst_blk < a.tol and worst_eng < a.tol and ties <= 2 + print("PASS" if ok else "FAIL") + sys.exit(0 if ok else 1) + + +if __name__ == "__main__": + main() diff --git a/jang-tools/jang_tools/dsv41/tests/serve_acceptance.py b/jang-tools/jang_tools/dsv41/tests/serve_acceptance.py new file mode 100644 index 00000000..247dc500 --- /dev/null +++ b/jang-tools/jang_tools/dsv41/tests/serve_acceptance.py @@ -0,0 +1,209 @@ +"""DeepSeek-V4.1-Flash serving acceptance against a real `vmlx serve` process. + +One model load per run. Reports cold prefill, decode tok/s by content type, TTFT, RAM prefix +reuse, per-tool-call reuse, multiturn recall, multimodal answers, reasoning-parser leaks, and +the server's phys_footprint. + + python jang_tools/dsv41/tests/serve_acceptance.py --bundle --image \ + --disk-dir --out result.json [--ar] [--restart-probe] + +--ar sets VMLX_DSV41_DSPARK=0 (AR baseline). --restart-probe only re-sends the SSD probe +prompt (run it after a normal run, with the same --disk-dir, to prove SSD persistence). +""" +from __future__ import annotations + +import argparse +import base64 +import json +import os +import re +import signal +import subprocess +import time +import urllib.request + +ap = argparse.ArgumentParser() +ap.add_argument("--bundle", required=True) +ap.add_argument("--image", help="a solid-red PNG (required unless --no-vision)") +ap.add_argument("--no-vision", action="store_true", help="text-only bundle (e.g. DSV4-0731): skip the image checks") +ap.add_argument("--image2", help="a solid-blue PNG (multimodal prefix-reuse miss check)") +ap.add_argument("--disk-dir", required=True) +ap.add_argument("--out", required=True) +ap.add_argument("--port", type=int, default=8170) +ap.add_argument("--ar", action="store_true") +ap.add_argument("--restart-probe", action="store_true") +a = ap.parse_args() + +env = dict(os.environ) +env.pop("VMLX_DSV41_DSPARK", None) +if a.ar: + env["VMLX_DSV41_DSPARK"] = "0" +log_path = os.path.splitext(a.out)[0] + ".serve.log" +logf = open(log_path, "w") +proc = subprocess.Popen(["vmlx", "serve", a.bundle, "--port", str(a.port), "--host", "127.0.0.1", + "--use-paged-cache", "--enable-block-disk-cache", "--block-disk-cache-dir", + a.disk_dir, "--enable-auto-tool-choice"], stdout=logf, stderr=subprocess.STDOUT, env=env) +base = f"http://127.0.0.1:{a.port}" +def _data_url(path): + return "data:image/png;base64," + base64.b64encode(open(path, "rb").read()).decode() + + +IMG = None if a.no_vision else _data_url(a.image) +R: dict = {"mode": "ar" if a.ar else "dspark"} +MID = None + + +def post(body, timeout=1800): + req = urllib.request.Request(base + "/v1/chat/completions", data=json.dumps(body).encode(), + headers={"Content-Type": "application/json"}) + return urllib.request.urlopen(req, timeout=timeout) + + +def chat(messages, mx=64, think=False, tools=None, effort=None): + b = {"model": MID, "messages": messages, "max_tokens": mx, "temperature": 0, "stream": False, + "chat_template_kwargs": {"enable_thinking": think}} + if tools: + b["tools"] = tools + if effort: + b["reasoning_effort"] = effort + t0 = time.time() + r = json.loads(post(b).read()) + dt = time.time() - t0 + u = r.get("usage") or {} + m = r["choices"][0]["message"] + return {"content": m.get("content") or "", "reasoning": m.get("reasoning_content") or "", + "tool_calls": m.get("tool_calls"), "ptok": u.get("prompt_tokens"), + "cached": (u.get("prompt_tokens_details") or {}).get("cached_tokens", 0), "s": dt} + + +def stream_decode(messages, mx=256): + """Decode tok/s excluding prefill: first delta to last, tokens from usage.""" + b = {"model": MID, "messages": messages, "max_tokens": mx, "temperature": 0, "stream": True, + "stream_options": {"include_usage": True}, "chat_template_kwargs": {"enable_thinking": False}} + t0 = time.time() + first = last = None + usage = {} + with post(b) as resp: + for raw in resp: + line = raw.decode().strip() + if not line.startswith("data:") or line[5:].strip() == "[DONE]": + continue + ev = json.loads(line[5:]) + usage = ev.get("usage") or usage + for ch in ev.get("choices") or []: + d = ch.get("delta") or {} + if (d.get("content") or "") + (d.get("reasoning_content") or ""): + now = time.time() + first = first or now + last = now + n = usage.get("completion_tokens") or 0 + dec = (last - first) if first and last and last > first else None + return {"ctok": n, "ttft_s": round(first - t0, 3) if first else None, + "decode_tps": round((n - 1) / dec, 1) if dec and n > 1 else None} + + +def footprint(): + out = subprocess.run(["vmmap", "--summary", str(proc.pid)], capture_output=True, text=True).stdout + unit = {"K": 1 / 1048576, "M": 1 / 1024, "G": 1} + m = re.search(r"Physical footprint:\s+([\d.]+)([KMG])", out) + p = re.search(r"Physical footprint \(peak\):\s+([\d.]+)([KMG])", out) + return {"footprint_gb": float(m[1]) * unit[m[2]] if m else None, + "peak_gb": float(p[1]) * unit[p[2]] if p else None} + + +SSD_PROMPT = [{"role": "user", "content": "SSD persistence probe. " + " ".join( + f"Record {i}: sensor value {i * 37 % 101} at station {i % 13}." for i in range(260)) + " Summarize in one line."}] +try: + for _ in range(600): + time.sleep(2) + if proc.poll() is not None: + raise SystemExit(f"server exited rc={proc.returncode}; see {log_path}") + try: + urllib.request.urlopen(base + "/health", timeout=5) + break + except OSError: # not listening yet (URLError, connection refused, timeout) + continue + MID = json.loads(urllib.request.urlopen(base + "/v1/models", timeout=5).read())["data"][0]["id"] + chat([{"role": "user", "content": "hi"}], mx=4) + # vmmap on a ~200 GB process disturbs the next request: memory is sampled only after the timed checks. + if a.restart_probe: + r = chat(SSD_PROMPT, mx=8) + R["ssd_restart"] = {"ptok": r["ptok"], "cached": r["cached"], "s": round(r["s"], 2)} + R["footprint_after_load"] = footprint() + else: + tag = f"{R['mode']}-{int(time.time())}" # unique text: no prefix hit, cold Engram rows + for n in (1000, 4000, 16000): + body = " ".join(f"Item {tag}-{n}-{i}: the quick brown fox number {i} jumps over lazy dog {i * 7}." + for i in range(n // 18)) + r = chat([{"role": "user", "content": body + " Reply OK."}], mx=1) + R[f"cold_prefill_{n}"] = {"ptok": r["ptok"], "s": round(r["s"], 2), "pp_s": round(r["ptok"] / r["s"], 1)} + R["decode"] = {name: stream_decode([{"role": "user", "content": msg}]) for name, msg in [ + ("code", "Write a Python function that checks whether a string is a palindrome, with a docstring and two examples."), + ("code2", "Write a JavaScript function that deep-clones an object, with comments."), + ("structured", "List the 12 months of the year as a JSON array of objects with name and days."), + ("prose", "Write a short story about a lighthouse keeper who finds a message in a bottle.")]} + r1, r2 = chat(SSD_PROMPT, mx=8), chat(SSD_PROMPT, mx=8) + R["prefix_ram"] = [{"ptok": x["ptok"], "cached": x["cached"], "s": round(x["s"], 2)} for x in (r1, r2)] + tools = [{"type": "function", "function": {"name": "get_weather", "description": "Get weather", "parameters": { + "type": "object", "properties": {"city": {"type": "string"}}, "required": ["city"]}}}] + conv = [{"role": "system", "content": "You are a helpful assistant with tools."}, + {"role": "user", "content": "What is the weather in Paris right now? Use the tool."}] + t1 = chat(conv, mx=96, tools=tools) + R["tool_t1"] = {"tool_calls": t1["tool_calls"], "content": t1["content"][:160]} + if t1["tool_calls"]: + tc = t1["tool_calls"] + conv2 = conv + [{"role": "assistant", "content": t1["content"], "tool_calls": tc}, + {"role": "tool", "tool_call_id": tc[0].get("id", "call_0"), "content": '{"temp_c": 18, "sky": "cloudy"}'}] + t2 = chat(conv2, mx=64, tools=tools) + R["tool_t2"] = {"content": t2["content"][:160], "ptok": t2["ptok"], "cached": t2["cached"], "s": round(t2["s"], 2)} + mt = [{"role": "user", "content": "My name is Sam and my favorite color is teal. Acknowledge briefly."}] + x = chat(mt, mx=40) + mt += [{"role": "assistant", "content": x["content"]}, {"role": "user", "content": "What is my favorite color? One word."}] + y = chat(mt, mx=10) + mt += [{"role": "assistant", "content": y["content"]}, {"role": "user", "content": "And my name? One word."}] + z = chat(mt, mx=10) + R["multiturn"] = {"color": y["content"], "name": z["content"]} + if not a.no_vision: + sysm = {"role": "system", "content": "Answer in one word."} + u1 = {"role": "user", "content": [{"type": "text", "text": "What color is this image?"}, + {"type": "image_url", "image_url": {"url": IMG}}]} + m1 = chat([sysm, u1], mx=8) + conv_mm = [sysm, u1, {"role": "assistant", "content": m1["content"]}, + {"role": "user", "content": "Name a fruit of exactly that color."}] + m2 = chat(conv_mm, mx=8) + conv_mm += [{"role": "assistant", "content": m2["content"]}, {"role": "user", "content": "What color was the image again?"}] + m3 = chat(conv_mm, mx=8) + R["multimodal"] = {"answers": [m1["content"], m2["content"], m3["content"]], + "cached": [m1["cached"], m2["cached"], m3["cached"]]} + # Multimodal prefix reuse: a conversation long enough to be stored (> 256 tokens). The text + # follow-up should hit the cache entry from the image turn; a different image must miss. + long_sys = {"role": "system", "content": "You are a careful visual assistant. " + " ".join( + f"Guideline {i}: describe only what is visible, answer in one word when asked." for i in range(40))} + def img_turn(url): + return {"role": "user", "content": [{"type": "text", "text": "What color is this image? One word."}, + {"type": "image_url", "image_url": {"url": url}}]} + v1 = chat([long_sys, img_turn(IMG)], mx=8) + conv_v = [long_sys, img_turn(IMG), {"role": "assistant", "content": v1["content"]}, + {"role": "user", "content": "Name a fruit of exactly that color. One word."}] + v2 = chat(conv_v, mx=8) + R["multimodal_reuse"] = {"answers": [v1["content"], v2["content"]], "ptok": [v1["ptok"], v2["ptok"]], + "cached": [v1["cached"], v2["cached"]], "s": [round(v1["s"], 2), round(v2["s"], 2)]} + if a.image2: + v3 = chat([long_sys, img_turn(_data_url(a.image2))], mx=8) + R["multimodal_reuse"].update(other_image=v3["content"], other_image_cached=v3["cached"]) + rr = chat([{"role": "user", "content": "What is 17*23?"}], mx=300, think=True, effort="high") + R["reasoning"] = {"reasoning_len": len(rr["reasoning"]), "content": rr["content"][:80], + "leak": "" in rr["content"]} + R["footprint_end"] = footprint() +finally: + proc.send_signal(signal.SIGINT) + try: + proc.wait(timeout=30) + except subprocess.TimeoutExpired: + proc.kill() + logf.close() + keep = ("persist_ms", "wait_ms", "paged cache hit", "Stored paged", "DSpark", "Traceback", "Error") + R["log"] = [l.rstrip()[:240] for l in open(log_path) if any(k in l for k in keep)][-80:] + with open(a.out, "w") as f: + json.dump(R, f, indent=1) + print(json.dumps({k: v for k, v in R.items() if k != "log"}, indent=1)) diff --git a/jang-tools/jang_tools/dsv41/tests/synth.py b/jang-tools/jang_tools/dsv41/tests/synth.py new file mode 100644 index 00000000..a197f30f --- /dev/null +++ b/jang-tools/jang_tools/dsv41/tests/synth.py @@ -0,0 +1,148 @@ +"""Synthetic DSV4.1 models (random weights, no bundle) for decode-path tests and microbenchmarks. + +``tiny_args`` is small enough for fast exactness tests but keeps the bundle's quant layout (2/3-bit +group-64 experts, 8-bit dense) and the projection-length classes that pick MLX's qmv kernels +(hidden a multiple of 512 -> qmv_fast; intermediate not -> qmv). ``real_args`` keeps the bundle's +per-layer dimensions with fewer layers / experts, for per-layer timing. + + build(args, expert_bits=...) -> Model with random weights + greedy(model, prompt, steps) -> generated token ids (decode one token per forward) +""" + +from __future__ import annotations + +import mlx.core as mx +import mlx.nn as nn +import numpy as np +from mlx.utils import tree_flatten + +from jang_tools.dsv41 import model as M +from jang_tools.dsv41.engram import EngramLayout + + +def _base(**kw): + t = { + "vocab_size": 1024, "rms_norm_eps": 1e-6, "rope_theta": 10000, "swiglu_limit": 10.0, + "rope_scaling": {"rope_type": "yarn", "factor": 16, "beta_fast": 32, "beta_slow": 1, + "original_max_position_embeddings": 65536}, + "routed_scaling_factor": 1.5, "norm_topk_prob": True, "compress_rope_theta": 160000, + "hc_mult": 4, "hc_sinkhorn_iters": 20, "hc_eps": 1e-6, + "engram_layer_ids": [], "engram_max_ngram_size": 3, "engram_vocab_size": 1000, "engram_n_heads": 2, + "engram_head_dim": 32, "engram_pad_token_id": 2, "engram_compressed_vocab_size": 1000, + "engram_num_embeddings": [], + } + t.update(kw) + return t + + +def tiny_args(n_layers=6, n_experts=128, window=16): + ratios = ([0, 2, 2, 1, 1, 1] * 4)[:n_layers] + return M.Args.from_config(_base( + hidden_size=1024, moe_intermediate_size=768, num_hidden_layers=n_layers, num_attention_heads=4, + head_dim=128, qk_rope_head_dim=64, q_lora_rank=256, o_lora_rank=128, o_groups=2, + n_routed_experts=n_experts, num_experts_per_tok=6, sliding_window=window, compress_ratios=ratios, + kv_source_layer_ids=[1, 3], index_source_layer_ids=[1, 3, 5], index_n_heads=8, index_head_dim=64, + index_topk=8, candidate_source_layer_id=3, candidate_topk_blocks=3, candidate_block_size=4)) + + +def real_args(n_layers=10, n_experts=16): + """Bundle dimensions (hidden 5120, intermediate 2304, 64 heads x 512, ...) on fewer layers.""" + ratios = [0, 2, 2, 2, 2, 1, 1, 1, 1, 1, 1, 1][:n_layers] + return M.Args.from_config(_base( + hidden_size=5120, moe_intermediate_size=2304, num_hidden_layers=n_layers, num_attention_heads=64, + head_dim=512, qk_rope_head_dim=64, q_lora_rank=1280, o_lora_rank=1024, o_groups=8, + n_routed_experts=n_experts, num_experts_per_tok=6, sliding_window=128, compress_ratios=ratios, + kv_source_layer_ids=[1, 5], index_source_layer_ids=[1, 5, 7, 9], index_n_heads=64, index_head_dim=128, + index_topk=512, candidate_source_layer_id=5, candidate_topk_blocks=2048, candidate_block_size=8)) + + +def _qbits(args, expert_bits): + b = {"embed": 8, "head": 8} + for i in range(args.num_hidden_layers): + p = f"layers.{i}" + for n in ("wq_a", "wq_b", "wkv", "wo_a", "wo_b", "indexer.wq_b"): + b[f"{p}.attn.{n}"] = 8 + for n in ("w1", "w2", "w3"): + b[f"{p}.ffn.shared_experts.{n}"] = 8 + g, d = expert_bits(i) + b[f"{p}.ffn.experts.gate_proj"] = g + b[f"{p}.ffn.experts.up_proj"] = g + b[f"{p}.ffn.experts.down_proj"] = d + b[f"{p}.engram.wkv"] = 8 + return b + + +def bundle_bits(i): + """The Q2Q3 bundle: gate/up 2-bit (3-bit on a few layers), down 3-bit.""" + return (3 if i % 5 == 4 else 2), 3 + + +def _rand_quant(key, w_shape, bits, in_dim, dtype=mx.bfloat16, lo=None): + """Random affine-quantized weight: packed codes uniform, values in about +-1.7/sqrt(in_dim).""" + k1, k2 = mx.random.split(key) + # two 16-bit halves: randint draws through float32, so a single 32-bit draw has zero low bits + codes = (mx.random.randint(0, 1 << 16, w_shape, key=k1).astype(mx.uint32) << 16) | \ + mx.random.randint(0, 1 << 16, w_shape, key=k2).astype(mx.uint32) + lo = 1.7 / in_dim ** 0.5 if lo is None else lo + g_shape = (*w_shape[:-1], in_dim // M.GROUP_SIZE) + jitter = 1 + 0.2 * mx.random.uniform(shape=g_shape, key=k2) + scales = (2 * lo / ((1 << bits) - 1) * jitter).astype(dtype) + biases = (-lo * jitter).astype(dtype) + return codes, scales, biases + + +def build(args, expert_bits=bundle_bits, seed=0, dtype=mx.bfloat16) -> M.Model: + layout = EngramLayout.from_config(args.raw) + model = M.Model(args, _qbits(args, expert_bits), layout) + params = dict(tree_flatten(model.parameters())) + key = mx.random.key(seed) + new = [] + for i, (name, p) in enumerate(sorted(params.items())): + k = mx.random.fold_in(key, i) if hasattr(mx.random, "fold_in") else mx.random.key(seed * 100003 + i) + base = name.rsplit(".", 1)[0] + if name.endswith(".weight") and p.dtype == mx.uint32: + bits = 32 * p.shape[-1] // (params[base + ".scales"].shape[-1] * M.GROUP_SIZE) + in_dim = params[base + ".scales"].shape[-1] * M.GROUP_SIZE + w, s, b = _rand_quant(k, p.shape, bits, in_dim, lo=1.0 if name.startswith("embed") else None) + new += [(name, w), (base + ".scales", s), (base + ".biases", b)] + elif name.endswith((".scales", ".biases")): + continue + elif "norm" in name or name.endswith(("q_weight", "k_weight")): # BF16 in the bundle + new.append((name, (1 + 0.1 * mx.random.normal(p.shape, key=k)).astype(mx.bfloat16))) + elif name.endswith("_scale") and "hc_" in name: + new.append((name, (0.5 + 0.1 * mx.random.normal(p.shape, key=k)).astype(p.dtype))) + elif name.endswith("_base") and "hc_" in name: + new.append((name, (0.3 * mx.random.normal(p.shape, key=k)).astype(p.dtype))) + elif name.endswith(("attn_sink", ".bias", "bias_vl")): + new.append((name, (0.5 * mx.random.normal(p.shape, key=k)).astype(p.dtype))) + else: + fan = p.shape[-1] if p.ndim > 1 else 1 + new.append((name, (mx.random.normal(p.shape, key=k) / fan ** 0.5).astype(p.dtype))) + if len(new) % 64 == 0: + mx.eval([v for _, v in new[-64:]]) + model.load_weights(new, strict=False) + mx.eval(model.parameters()) + return model + + +def new_caches(args): + return [M.LayerCache() for _ in range(args.num_hidden_layers)] + + +def forward(model, ids, caches, pos, all_logits=False): + seg = M.Seg(0, len(ids), pos, caches) + return model(mx.array([ids], mx.int32), [seg], {}, all_logits=all_logits) + + +def greedy(model, prompt, steps, return_logits=False): + """Prefill ``prompt`` then decode ``steps`` tokens one forward each (argmax).""" + caches = new_caches(model.args) + logits = forward(model, list(prompt), caches, 0) + pos, out, lg = len(prompt), [], [] + for _ in range(steps): + lg.append(np.array(logits[0].astype(mx.float32))) + tok = int(mx.argmax(logits[0])) + out.append(tok) + logits = forward(model, [tok], caches, pos) + pos += 1 + return (out, lg) if return_logits else out diff --git a/jang-tools/jang_tools/dsv41/tests/test_chunking.py b/jang-tools/jang_tools/dsv41/tests/test_chunking.py new file mode 100644 index 00000000..96144d69 --- /dev/null +++ b/jang-tools/jang_tools/dsv41/tests/test_chunking.py @@ -0,0 +1,88 @@ +"""Chunked continuation == single-shot prefill, and batched decode == per-session decode. + +Uses the small random DSV4.1 from parity_reference (no reference forward needed). + + PYTHONPATH=jang-tools python jang_tools/dsv41/tests/test_chunking.py --src ~/models/DeepSeek-V4.1-Flash-1017 +""" + +from __future__ import annotations + +import argparse +import sys +import tempfile +from pathlib import Path + +import numpy as np +import torch + +from jang_tools.dsv41.tests import parity_reference as P + + +def cos(a, b): + a, b = a.reshape(-1), b.reshape(-1) + return float(np.dot(a, b) / (np.linalg.norm(a) * np.linalg.norm(b))) + + +def main(): + ap = argparse.ArgumentParser() + ap.add_argument("--src", required=True) + a = ap.parse_args() + src = Path(a.src).expanduser() + sys.path[:0] = [str(Path(P.__file__).parent / "ref_shim"), str(src / "inference")] + import model as ref + from transformers import AutoTokenizer + + from jang_tools.dsv41.model import DSV41 + + torch.set_default_dtype(torch.bfloat16) + text = P.build_config() + # no discrete choices left to flip on bf16 noise: full index selection, every expert routed + text.update(index_topk=512, candidate_topk_blocks=512, n_routed_experts=2, num_experts_per_tok=2) + tok = AutoTokenizer.from_pretrained(str(src)) + rm = ref.Transformer(P.ref_args(ref, text), tok) + torch.set_default_dtype(torch.float32) + P.randomize(rm) + ids = tok.encode((src / "encoding" / "README.md").read_text(), add_special_tokens=False)[:150] + ok = True + with tempfile.TemporaryDirectory() as td: + P.write_bundle(rm, text, src, Path(td) / "b") + m = DSV41(Path(td) / "b", wired=False) + + full = np.array(m.forward(ids, m.new_session(), all_logits=True)) + for plan in ([37, 1, 1, 50, 61], [1] * 20 + [130], [7, 9, 11, 13, 110], [128, 22]): + sess, outs = m.new_session(), [] + o = 0 + for c in plan: + outs.append(np.array(m.forward(ids[o:o + c], sess, all_logits=True))) + o += c + cc = np.concatenate(outs) + per = [cos(full[i], cc[i]) for i in range(len(ids))] + c_ = min(per) + if c_ < 0.999: + bad = [i for i, v in enumerate(per) if v < 0.999] + print(f" first bad token {bad[0]}, n bad {len(bad)}, boundaries {np.cumsum(plan)[:-1].tolist()[:8]}") + print(f"chunk plan {plan[:6]}{'...' if len(plan) > 6 else ''}: worst per-token logit cos {c_:.5f}") + ok &= c_ > 0.999 + + # batched decode: three sessions at different positions vs each alone + starts = [40, 77, 101] + solo, batch = [], [] + for st in starts: + s = m.new_session() + m.forward(ids[:st], s) + solo.append([np.array(m.forward([ids[st + k]], s)) for k in range(5)]) + sess = [m.new_session() for _ in starts] + for s, st in zip(sess, starts): + m.forward(ids[:st], s) + for k in range(5): + out = np.array(m.decode_batch(sess, [ids[st + k] for st in starts])) + batch.append(out) + c_ = min(cos(solo[b][k], batch[k][b]) for b in range(3) for k in range(5)) + print(f"batched decode vs solo: worst logit cos {c_:.5f}") + ok &= c_ > 0.999 + print("PASS" if ok else "FAIL") + sys.exit(0 if ok else 1) + + +if __name__ == "__main__": + main() diff --git a/jang-tools/jang_tools/dsv41/tests/test_commit_prefix.py b/jang-tools/jang_tools/dsv41/tests/test_commit_prefix.py new file mode 100644 index 00000000..385622e5 --- /dev/null +++ b/jang-tools/jang_tools/dsv41/tests/test_commit_prefix.py @@ -0,0 +1,126 @@ +"""DSV41.commit_prefix == feeding exactly the kept tokens. + +A capture_verify forward of W+1 tokens followed by commit_prefix(keep) must leave the cache a +forward of only those `keep` tokens would leave: same window rows, compressed / index pool rows, +compressor pending tail, Engram history and position. Two checks on a small random DSV4.1 from +parity_reference (ratio-2 and ratio-1 compressors, 16-token window, index owners), CPU: + 1. exact: commit_prefix(W+1) after a capture forward == that forward's own state, bit for bit; + 2. against a forward of only the kept tokens (a different batch shape, so bf16 numerics differ in + the last bits and the small model's top-8 indexer picks can flip): same row counts and + pending lengths, values within cos 0.995. Logit drift after a flipped pick is reported only. + + PYTHONPATH=jang-tools python jang_tools/dsv41/tests/test_commit_prefix.py --src ~/models/DeepSeek-V4.1-Flash-1017 +""" + +from __future__ import annotations + +import argparse +import sys +import tempfile +from pathlib import Path + +import mlx.core as mx +import numpy as np +import torch + +from jang_tools.dsv41.tests import parity_reference as P + + +def cos(a, b): + a, b = a.reshape(-1).astype(np.float64), b.reshape(-1).astype(np.float64) + return float(np.dot(a, b) / (np.linalg.norm(a) * np.linalg.norm(b))) + + +def arr(x): + return None if x is None else np.array(x.astype(mx.float32)) + + +def pool(buf): + v = buf.view() + return None if v is None else arr(v) + + +def close(a, b, tol=0.995): + if a is None or b is None: + return a is None and b is None + return a.shape == b.shape and (a.size == 0 or cos(a, b) > tol) + + +def main(): + ap = argparse.ArgumentParser() + ap.add_argument("--src", required=True) + a = ap.parse_args() + src = Path(a.src).expanduser() + sys.path[:0] = [str(Path(P.__file__).parent / "ref_shim"), str(src / "inference")] + import model as ref + from transformers import AutoTokenizer + + from jang_tools.dsv41.model import DSV41 + + mx.set_default_device(mx.cpu) + torch.set_default_dtype(torch.bfloat16) + text = P.build_config() + text.update(index_head_dim=64) # 4-bit pools quantize in groups of 64 + tok = AutoTokenizer.from_pretrained(str(src)) + rm = ref.Transformer(P.ref_args(ref, text), tok) + torch.set_default_dtype(torch.float32) + P.randomize(rm) + ids = tok.encode((src / "encoding" / "README.md").read_text(), add_special_tokens=False)[:160] + ok = True + with tempfile.TemporaryDirectory() as td: + P.write_bundle(rm, text, src, Path(td) / "b") + m = DSV41(Path(td) / "b", wired=False) + W1 = 6 # verify width W+1 + for start in (31, 32, 33, 47, 63): # pending tails of every length at the ratio-2 layers + for keep in range(1, W1 + 1): + s_ref = m.new_session() + m.forward(ids[:start], s_ref) + m.forward(ids[start:start + keep], s_ref) + s = m.new_session() + m.forward(ids[:start], s) + ck = s.checkpoint() + m.forward(ids[start:start + W1], s, all_logits=True, capture_verify=True) + m.commit_prefix(s, ck, keep) + why = [] + if not (s.pos == s_ref.pos and np.array_equal(s.history, s_ref.history)): + why.append("pos/history") + for li, (c, r) in enumerate(zip(s.caches, s_ref.caches)): + if not close(arr(c.window), arr(r.window)): + why.append(f"L{li} window") + if not (c.compress_kv.n == r.compress_kv.n and close(pool(c.compress_kv), pool(r.compress_kv))): + why.append(f"L{li} pool {c.compress_kv.n}/{r.compress_kv.n}") + if not (c.index_k.n == r.index_k.n and close(pool(c.index_k), pool(r.index_k))): + why.append(f"L{li} index {c.index_k.n}/{r.index_k.n}") + if not (close(arr(c.pend_kv), arr(r.pend_kv)) and close(arr(c.pend_score), arr(r.pend_score))): + why.append(f"L{li} pend") + good = not why + nxt = ids[start + keep:start + keep + 12] + la = np.array(m.forward(nxt, s, all_logits=True)) + lb = np.array(m.forward(nxt, s_ref, all_logits=True)) + c_ = min(cos(la[i], lb[i]) for i in range(len(nxt))) + good &= c_ > 0.999 + if why: + print(f"FAIL start={start} keep={keep}: state {why}") + elif c_ <= 0.999: + print(f"note start={start} keep={keep}: state matches; later logits cos {c_:.5f} (top-k pick flipped)") + ok &= not why + for start in (31, 32, 47): + s1, s2 = m.new_session(), m.new_session() + m.forward(ids[:start], s1); m.forward(ids[:start], s2) + m.forward(ids[start:start + W1], s1, all_logits=True) + ck = s2.checkpoint() + m.forward(ids[start:start + W1], s2, all_logits=True, capture_verify=True) + m.commit_prefix(s2, ck, W1) + for li, (c, r) in enumerate(zip(s1.caches, s2.caches)): + for name, x, y in (("window", arr(c.window), arr(r.window)), ("pool", pool(c.compress_kv), pool(r.compress_kv)), + ("index", pool(c.index_k), pool(r.index_k)), ("pend", arr(c.pend_kv), arr(r.pend_kv))): + same = (x is None and y is None) or (x is not None and y is not None and np.array_equal(x, y)) + if not same: + print(f"FAIL exact replay start={start} L{li} {name}") + ok &= same + print("commit_prefix == kept-token forward:", "PASS" if ok else "FAIL") + sys.exit(0 if ok else 1) + + +if __name__ == "__main__": + main() diff --git a/jang-tools/jang_tools/dsv41/tests/test_engram_io.py b/jang-tools/jang_tools/dsv41/tests/test_engram_io.py new file mode 100644 index 00000000..81495662 --- /dev/null +++ b/jang-tools/jang_tools/dsv41/tests/test_engram_io.py @@ -0,0 +1,55 @@ +"""Concurrent (16-lane) Engram gathers == a plain memory-mapped gather, and pipelined lookup == lookup. + +CPU only, on a small synthetic FP8 table written as a safetensors shard. + + PYTHONPATH=jang-tools python jang_tools/dsv41/tests/test_engram_io.py +""" + +from __future__ import annotations + +import json +import struct +import tempfile +from pathlib import Path + +import mlx.core as mx +import numpy as np + +from jang_tools.dsv41 import engram as E +from jang_tools.dsv41.st_io import Shards + + +def _write_table(path: Path, n_rows: int, dim: int, sdim: int, rng) -> tuple[np.ndarray, np.ndarray]: + w = rng.integers(0, 0x7F, (n_rows, dim), dtype=np.uint8) # finite positive E4M3 codes + s = rng.integers(120, 134, (n_rows, sdim), dtype=np.uint8) # E8M0 exponents near 1.0 + header = { + "layers.1.engram.embed.weight": {"dtype": "F8_E4M3", "shape": [n_rows, dim], "data_offsets": [0, w.nbytes]}, + "layers.1.engram.embed.scale": {"dtype": "F8_E8M0", "shape": [n_rows, sdim], + "data_offsets": [w.nbytes, w.nbytes + s.nbytes]}, + } + hb = json.dumps(header).encode() + hb += b" " * (-len(hb) % 8) + path.write_bytes(struct.pack(" layer 5: 46, 6: 31, 7: 16 rows + for n, step in ((40, 64), (47, 64), (100, 64), (161, 64), (161, 32), (161, 17), (250, 256)): + ids = ids_all[:n] + s0, s1 = prefill(m, ids, step, False), prefill(m, ids, step, True) + why = [] + for li, (c, r) in enumerate(zip(s0.caches, s1.caches)): + w0, w1 = arr(c.window), arr(r.window) + if li < pf: + same = all((x is None and y is None) or (x is not None and y is not None and np.array_equal(x, y)) + for x, y in ((w0, w1), (pool(c.compress_kv), pool(r.compress_kv)), + (pool(c.index_k), pool(r.index_k)), (arr(c.pend_kv), arr(r.pend_kv)))) + if not same: + why.append(f"L{li} state differs") + elif w0.shape != w1.shape or cos(w0, w1) < 0.9999: + why.append(f"L{li} window {w0.shape}/{w1.shape} cos {cos(w0, w1) if w0.shape == w1.shape else 0:.6f}") + tail = ids_all[n - 1:n + 8] # the last prompt token, then continuation tokens + worst, flips = 1.0, 0 + for t in tail: + l0 = np.array(m.forward([t], s0)); l1 = np.array(m.forward([t], s1)) + worst = min(worst, cos(l0, l1)); flips += int(l0.argmax() != l1.argmax()) + if worst < 0.999 or flips: + why.append(f"logits cos {worst:.5f}, argmax flips {flips}") + print(f"n={n} step={step}: {'ok' if not why else 'FAIL ' + '; '.join(why)} (logits cos {worst:.6f})") + ok &= not why + print("suffix pruning == full prefill:", "PASS" if ok else "FAIL") + sys.exit(0 if ok else 1) + + +if __name__ == "__main__": + main() diff --git a/jang-tools/jang_tools/dsv41/tests/verify_dspark_adaptive.py b/jang-tools/jang_tools/dsv41/tests/verify_dspark_adaptive.py new file mode 100644 index 00000000..d3259449 --- /dev/null +++ b/jang-tools/jang_tools/dsv41/tests/verify_dspark_adaptive.py @@ -0,0 +1,62 @@ +"""Verify the RECOVERABLE adaptive DSpark change: + 1) adaptive DSpark output is TOKEN-IDENTICAL to plain greedy AR (correctness), + 2) it does NOT permanently latch -- after a hard (low-accept) stretch it RECOVERS drafting on an + easy continuation (prove depth is acceptance-governed, not hard-enforced). +""" +import sys, time +from pathlib import Path +import mlx.core as mx +from jang_tools.dsv41.model import DSV41 +from jang_tools.dsv41.dspark import load_dspark, DSparkRunner + +BUNDLE = Path(sys.argv[1]).expanduser() +N = int(sys.argv[2]) if len(sys.argv) > 2 else 60 +m = DSV41(BUNDLE) +ds = load_dspark(BUNDLE, m.args, m.model.embed, m.model.head) +eos_tok = m.tokenizer.token_to_id("<|end▁of▁sentence|>") +eos = {e for e in (eos_tok, m.eos_id) if e is not None} + +enc = None +try: + from jang_tools.dsv41.generate import load_encoding + enc = load_encoding(BUNDLE) +except (ImportError, OSError) as e: # no bundle encoder: token ids only + print(f"encoding unavailable ({type(e).__name__}: {e}); using raw ids") + +def ids_for(prompt): + if enc is not None: + return m.tokenizer.encode(enc.encode_messages([{"role": "user", "content": prompt}], + thinking_mode="chat", reasoning_effort="low"), + add_special_tokens=False).ids + return m.tokenizer.encode(prompt, add_special_tokens=False).ids + +def greedy_ar(ids, n): + out, sess = [], m.new_session() + logits, _ = m.forward(list(ids), sess, all_logits=False, return_hidden=True) + for _ in range(n): + t = int(mx.argmax(logits)); out.append(t) + if eos and t in eos: break + logits = m.forward([t], sess, all_logits=False) + return out + +# low-accept prefix (random numbers) then an easy continuation in ONE prompt -> exercises enter-AR +# then recover. +prompt = ("Repeat this line then explain fibonacci simply: " + + " ".join(str((i * 7919) % 100000) for i in range(24))) +ids = ids_for(prompt) + +ar = greedy_ar(ids, N) +stats = {} +runner = DSparkRunner(m, ds, adaptive=True) +spec = list(runner.stream(ids, N, eos_ids=eos, stats=stats)) + +ident = ar == spec +print(f"[bundle loaded] bs={ds.bs} width={runner.width} probe_every={runner.probe_every}") +print(f"AR tokens ({len(ar)}): {ar[:24]}") +print(f"SPEC tokens({len(spec)}): {spec[:24]}") +print(f"TOKEN-IDENTICAL: {'PASS' if ident else 'FAIL'}") +if not ident: + for i,(a,b) in enumerate(zip(ar,spec)): + if a!=b: print(f" first diff @ {i}: AR={a} SPEC={b}"); break +print(f"stats: {stats} (accepted>0 proves drafting engaged; not a permanent AR latch)") +print(f"RECOVERY: {'PASS' if stats.get('accepted',0) > 0 else 'CHECK'} (accepted={stats.get('accepted',0)} of drafted={stats.get('drafted',0)})") diff --git a/jang-tools/jang_tools/dsv41/verify_source.py b/jang-tools/jang_tools/dsv41/verify_source.py new file mode 100644 index 00000000..57d58557 --- /dev/null +++ b/jang-tools/jang_tools/dsv41/verify_source.py @@ -0,0 +1,54 @@ +"""SHA-256 every downloaded file against the Hub's LFS oids for a pinned revision. + + python -m jang_tools.dsv41.verify_source --dir ~/models/DeepSeek-V4.1-Flash-1017 \ + --repo deepseek-ai/DeepSeek-V4.1-Flash-1017 --revision 1bae0e1088993b9b82de08f59de5be5a34e42170 +""" + +from __future__ import annotations + +import argparse +import hashlib +import json +import sys +import urllib.request +from concurrent.futures import ProcessPoolExecutor +from pathlib import Path + + +def sha256(path: Path) -> str: + h = hashlib.sha256() + with open(path, "rb") as f: + while chunk := f.read(64 << 20): + h.update(chunk) + return h.hexdigest() + + +def main(): + ap = argparse.ArgumentParser() + ap.add_argument("--dir", required=True) + ap.add_argument("--repo", required=True) + ap.add_argument("--revision", required=True) + ap.add_argument("--workers", type=int, default=8) + a = ap.parse_args() + root = Path(a.dir).expanduser() + url = f"https://huggingface.co/api/models/{a.repo}/revision/{a.revision}?blobs=true" + with urllib.request.urlopen(url) as resp: + info = json.load(resp) + expected = {s["rfilename"]: s["lfs"]["sha256"] for s in info["siblings"] if s.get("lfs")} + files = sorted(expected) + missing = [f for f in files if not (root / f).exists()] + with ProcessPoolExecutor(a.workers) as ex: + got = dict(zip([f for f in files if f not in missing], + ex.map(sha256, [root / f for f in files if f not in missing]))) + bad = [f for f, h in got.items() if h != expected[f]] + report = {"repo": a.repo, "revision": a.revision, "checked": len(got), "missing": missing, "mismatch": bad, + "sha256": got} + (root / "sha256-verification.json").write_text(json.dumps(report, indent=1)) + print(f"checked {len(got)} LFS files: {len(bad)} mismatched, {len(missing)} missing") + for f in bad + missing: + print(" BAD/MISSING", f) + sys.exit(1 if bad or missing else 0) + + +if __name__ == "__main__": + main() diff --git a/jang-tools/jang_tools/dsv41/vision.py b/jang-tools/jang_tools/dsv41/vision.py new file mode 100644 index 00000000..a4acacec --- /dev/null +++ b/jang-tools/jang_tools/dsv41/vision.py @@ -0,0 +1,334 @@ +"""MLX port of the DeepSeek-V4.1 vision tower (ViT + Aligner) and image preprocessing. + +A faithful port of release `inference/vision.py` + `inference/image_processor.py`. The ViT runs +full bidirectional attention over one image's patch grid with 2D RoPE; the Aligner does a 3x3 +spatial merge (9x token reduction) and projects to the text hidden size. Weights are BF16 +passthrough in the JANG bundle (names `vision.*`, `aligner.*`, `image_{start,end,newline}`), so the +modules here mirror those names and load via nn.Module.load_weights. + +Preprocessing is pure PIL/NumPy. `prepare_vl_inputs` expands each image placeholder id in a token +list into its image span and returns the parallel token-type array the backbone uses to build the +image mask (VL routing bias) and to splice aligner rows into the embedding stream. +""" + +from __future__ import annotations + +import base64 +import io +import math +from dataclasses import dataclass +from functools import lru_cache +from urllib.request import urlopen + +import mlx.core as mx +import mlx.nn as nn +import numpy as np + +# token types (parallel to input_ids over an image span); TEXT elsewhere +TEXT = -1 +IMAGE_START, IMAGE, IMAGE_NEW_LINE, IMAGE_END = range(4) + + +@dataclass +class VisionArgs: + n_layers: int + dim: int + n_heads: int + inter_dim: int + patch_size: int + rope_theta: float + downsample_ratio: int + max_n_token: int + min_pixels: int + max_wh_ratio: float | None + image_token_id: int + text_dim: int + eps: float = 1e-6 + + @property + def rope_dim(self) -> int: + return self.dim // self.n_heads // 2 + + @classmethod + def from_config(cls, cfg: dict) -> "VisionArgs": + v = cfg["vision_config"] + return cls( + n_layers=v["num_hidden_layers"], dim=v["hidden_size"], n_heads=v["num_attention_heads"], + inter_dim=v["intermediate_size"], patch_size=v["patch_size"], + rope_theta=v.get("rope_theta", 10000.0), downsample_ratio=v["downsample_ratio"], + max_n_token=v.get("max_image_tokens", 1024), min_pixels=v.get("min_pixels", 544 * 544), + max_wh_ratio=v.get("max_wh_ratio"), image_token_id=cfg["image_token_id"], + text_dim=cfg["text_config"]["hidden_size"], + ) + + +# --------------------------------------------------------------------------- ViT + +@lru_cache(8) +def _vision_cos_sin(n_h: int, n_w: int, dim: int, theta: float): + """2D RoPE tables, matching release get_vision_cos_sin. Returns cos,sin [n_h*n_w, 1, dim].""" + inv = 1.0 / (theta ** (np.arange(0, dim, 2, dtype=np.float32) / dim)) # [dim/2] + hpos = np.broadcast_to(np.arange(n_h)[:, None], (n_h, n_w)) + wpos = np.broadcast_to(np.arange(n_w)[None, :], (n_h, n_w)) + pos = np.stack([hpos, wpos], axis=-1).reshape(-1, 2, 1).astype(np.float32) # [n,2,1] + freqs = (pos * inv).reshape(n_h * n_w, -1) # [n, dim] + cos = mx.array(np.cos(freqs))[:, None, :] + sin = mx.array(np.sin(freqs))[:, None, :] + return cos, sin + + +def _apply_rotary(x: mx.array, cos: mx.array, sin: mx.array) -> mx.array: + """x [n, heads, head_dim]; cos/sin [n,1,head_dim/2]. fp32 rotate, cast back.""" + dt = x.dtype + xf = x.astype(mx.float32) + x1, x2 = mx.split(xf, 2, axis=-1) + return mx.concatenate([x1 * cos - x2 * sin, x2 * cos + x1 * sin], axis=-1).astype(dt) + + +class _RMSNorm(nn.Module): + def __init__(self, dim: int, eps: float = 1e-6): + super().__init__() + self.weight = mx.ones((dim,)) + self.eps = eps + + def __call__(self, x: mx.array) -> mx.array: + dt = x.dtype + xf = x.astype(mx.float32) + xf = xf * mx.rsqrt(mx.mean(xf * xf, axis=-1, keepdims=True) + self.eps) + return (self.weight * xf).astype(dt) + + +class PatchEmbed(nn.Module): + def __init__(self, a: VisionArgs): + super().__init__() + self.proj = nn.Linear(3 * a.patch_size**2, a.dim) + + def __call__(self, x: mx.array) -> mx.array: + return self.proj(x.reshape(x.shape[0], -1)) + + +class VisionAttention(nn.Module): + def __init__(self, a: VisionArgs): + super().__init__() + self.n_heads = a.n_heads + self.head_dim = a.dim // a.n_heads + self.scale = self.head_dim**-0.5 + self.wqkv = nn.Linear(a.dim, 3 * a.dim) + self.wo = nn.Linear(a.dim, a.dim) + + def __call__(self, x: mx.array, cos: mx.array, sin: mx.array) -> mx.array: + n = x.shape[0] + qkv = self.wqkv(x) + q, k, v = mx.split(qkv, 3, axis=-1) + q = _apply_rotary(q.reshape(n, self.n_heads, self.head_dim), cos, sin) + k = _apply_rotary(k.reshape(n, self.n_heads, self.head_dim), cos, sin) + v = v.reshape(n, self.n_heads, self.head_dim) + # [1, heads, n, hd] for SDPA (full bidirectional, no mask) + q = q.transpose(1, 0, 2)[None] + k = k.transpose(1, 0, 2)[None] + v = v.transpose(1, 0, 2)[None] + o = mx.fast.scaled_dot_product_attention(q, k, v, scale=self.scale) + o = o[0].transpose(1, 0, 2).reshape(n, -1) + return self.wo(o) + + +class VisionMLP(nn.Module): + def __init__(self, a: VisionArgs): + super().__init__() + self.w1 = nn.Linear(a.dim, 2 * a.inter_dim, bias=False) + self.w2 = nn.Linear(a.inter_dim, a.dim, bias=False) + + def __call__(self, x: mx.array) -> mx.array: + gate, up = mx.split(self.w1(x), 2, axis=-1) + return self.w2(nn.silu(gate) * up) + + +class VisionBlock(nn.Module): + def __init__(self, a: VisionArgs): + super().__init__() + self.norm1 = _RMSNorm(a.dim, a.eps) + self.attn = VisionAttention(a) + self.norm2 = _RMSNorm(a.dim, a.eps) + self.mlp = VisionMLP(a) + + def __call__(self, x: mx.array, cos: mx.array, sin: mx.array) -> mx.array: + x = x + self.attn(self.norm1(x), cos, sin) + return x + self.mlp(self.norm2(x)) + + +class ViT(nn.Module): + def __init__(self, a: VisionArgs): + super().__init__() + self.rope_dim = a.rope_dim + self.rope_theta = a.rope_theta + self.patch_embed = PatchEmbed(a) + self.blocks = [VisionBlock(a) for _ in range(a.n_layers)] + self.norm = _RMSNorm(a.dim, a.eps) + + def __call__(self, patches: mx.array, n_h: int, n_w: int) -> mx.array: + x = self.patch_embed(patches) + cos, sin = _vision_cos_sin(n_h, n_w, self.rope_dim, self.rope_theta) + for block in self.blocks: + x = block(x, cos, sin) + return self.norm(x) + + +def _gelu_erf(x: mx.array) -> mx.array: + return 0.5 * x * (1.0 + mx.erf(x / math.sqrt(2.0))) + + +class Aligner(nn.Module): + """3x3 spatial merge (release uses F.unfold) + two-layer projector to the text hidden size.""" + + def __init__(self, a: VisionArgs): + super().__init__() + self.r = a.downsample_ratio + self.w1 = nn.Linear(a.dim * self.r**2, a.text_dim) + self.w2 = nn.Linear(a.text_dim, a.text_dim) + + def __call__(self, x: mx.array, n_h: int, n_w: int) -> mx.array: + r = self.r + C = x.shape[-1] + x = x.reshape(n_h, n_w, C) + ph, pw = (-n_h) % r, (-n_w) % r # pad to a multiple of r (bottom/right), matching F.pad + if ph or pw: + x = mx.pad(x, [(0, ph), (0, pw), (0, 0)]) + H, W = n_h + ph, n_w + pw + # F.unfold(kernel=r, stride=r) on [C,H,W] then transpose -> rows=blocks (row-major), + # cols = (c, kh, kw) flattened. Replicate with reshape/transpose. + x = x.reshape(H // r, r, W // r, r, C) # [bh, kh, bw, kw, C] + x = x.transpose(0, 2, 4, 1, 3) # [bh, bw, C, kh, kw] + x = x.reshape((H // r) * (W // r), C * r * r) # [n_llm, C*r*r] with col = c*r*r + kh*r + kw + return self.w2(_gelu_erf(self.w1(x))) + + +# --------------------------------------------------------------------------- preprocessing + +@dataclass +class ImageInput: + start: int + patches: mx.array + n_vit_h: int + n_vit_w: int + types: list[int] + + +def num_image_tokens(n_llm_h: int, n_llm_w: int) -> int: + return n_llm_h * (n_llm_w + 1) + 2 + + +def llm_grid(best_h: int, best_w: int, patch: int, r: int): + return math.ceil((best_h // patch) / r), math.ceil((best_w // patch) / r) + + +def solve_resize_ratio(height, width, patch, r, max_n_token): + ratio = height / width + max_w = math.sqrt((max_n_token - 2) / ratio + 0.25) - 0.5 + max_h = max_w * ratio + cell = patch * r + if max_w < 1.0: + return (max_n_token - 2) // 2 * cell, cell + if max_h < 1.0: + return cell, (max_n_token - 3) * cell + beta = min(math.floor(max_w) * cell / width, math.floor(max_h) * cell / height) + return math.floor(height * beta / patch) * patch, math.floor(width * beta / patch) * patch + + +def safe_resize(height, width, best_h, best_w, patch, r, max_n_token): + n_llm_h, n_llm_w = llm_grid(best_h, best_w, patch, r) + if num_image_tokens(n_llm_h, n_llm_w) > max_n_token: + best_h, best_w = solve_resize_ratio(height, width, patch, r, max_n_token) + n_llm_h, n_llm_w = llm_grid(best_h, best_w, patch, r) + assert num_image_tokens(n_llm_h, n_llm_w) <= max_n_token + return n_llm_h, n_llm_w, best_h, best_w + + +def load_image_bytes(record) -> bytes: + if isinstance(record, str): # the chat encoder hands back bare url/path strings + record = {"url": record} + data = record.get("data") + if isinstance(data, bytes): + return data + if isinstance(data, str): + return base64.b64decode(data) + source = record.get("source") + if isinstance(source, dict): + if source.get("data") is not None: + return base64.b64decode(source["data"]) + if source.get("url"): + return load_image_bytes({"url": source["url"]}) + url = record.get("url") + if isinstance(url, str) and url: + if url.startswith("data:"): + header, _, payload = url.partition(",") + if ";base64" not in header: + raise ValueError(f"Unsupported data URL encoding: {header}") + return base64.b64decode(payload) + if url.startswith(("http://", "https://")): + with urlopen(url, timeout=30) as response: + return response.read() + with open(url, "rb") as file: + return file.read() + raise ValueError(f"Cannot load image from record: {list(record.keys())}") + + +def plan_image_grid(width: int, height: int, a: VisionArgs): + p = a.patch_size + if a.max_wh_ratio is not None and width > height * a.max_wh_ratio: + width = height * a.max_wh_ratio + if 0 < width * height < a.min_pixels: + ratio = (a.min_pixels / (width * height)) ** 0.5 + width = int(width * ratio) + height = int(height * ratio) + best_w = math.ceil(width / p) * p + best_h = math.ceil(height / p) * p + return safe_resize(height, width, best_h, best_w, p, a.downsample_ratio, a.max_n_token) + + +def load_image(record, a: VisionArgs): + """Load+transform one image record into ViT patches [n_vit_h*n_vit_w, 3, p, p] (bf16).""" + from PIL import Image, ImageOps + + p = a.patch_size + with Image.open(io.BytesIO(load_image_bytes(record))) as source: + image = source.convert("RGB") + n_llm_h, n_llm_w, best_h, best_w = plan_image_grid(image.width, image.height, a) + n_vit_h, n_vit_w = best_h // p, best_w // p + if a.max_wh_ratio is not None and image.width >= a.max_wh_ratio * image.height: + image = image.resize((best_w, best_h)) + else: + image = ImageOps.pad(image, (best_w, best_h), color=(127, 127, 127)) + x = np.asarray(image, dtype=np.float32).transpose(2, 0, 1) / 255.0 # [3,H,W] + x = (x - 0.5) / 0.5 + x = x.reshape(3, n_vit_h, p, n_vit_w, p).transpose(1, 3, 0, 2, 4).reshape(n_vit_h * n_vit_w, 3, p, p) + return mx.array(x.astype(np.float32)).astype(mx.bfloat16), n_vit_h, n_vit_w, n_llm_h, n_llm_w + + +def image_token_types(n_llm_h: int, n_llm_w: int) -> list[int]: + types = [IMAGE_START] + types += ([IMAGE] * n_llm_w + [IMAGE_NEW_LINE]) * n_llm_h + types.append(IMAGE_END) + return types + + +def prepare_vl_inputs(prompt_tokens: list[int], images: list, a: VisionArgs): + """Expand each image_token_id in a token list into its image span. + + Returns (tokens, token_types, image_inputs|None). Image-span positions carry a.image_token_id in + `tokens`; `token_types` is TEXT(-1) for text and the 0..3 enum inside spans.""" + num_ph = sum(t == a.image_token_id for t in prompt_tokens) + if num_ph != len(images): + raise ValueError(f"Found {num_ph} image tokens but got {len(images)} images") + tokens, token_types, image_inputs = [], [], [] + it = iter(images) + for tok in prompt_tokens: + if tok != a.image_token_id: + tokens.append(tok) + token_types.append(TEXT) + continue + patches, n_vit_h, n_vit_w, n_llm_h, n_llm_w = load_image(next(it), a) + types = image_token_types(n_llm_h, n_llm_w) + image_inputs.append(ImageInput(len(tokens), patches, n_vit_h, n_vit_w, types)) + tokens += [a.image_token_id] * len(types) + token_types += types + return tokens, token_types, image_inputs or None diff --git a/jang-tools/jang_tools/dsv4_1/__init__.py b/jang-tools/jang_tools/dsv4_1/__init__.py new file mode 100644 index 00000000..ad1a477e --- /dev/null +++ b/jang-tools/jang_tools/dsv4_1/__init__.py @@ -0,0 +1,6 @@ +"""DeepSeek-V4.1-Flash engine model (model_type ``deepseek_v41``). Importing registers it with mlx_lm.""" + +from jang_tools.dsv4_1 import mlx_register # noqa: F401 (side effect: register with mlx_lm) +from jang_tools.dsv4_1.mlx_model import Model, ModelArgs, load_deepseek_v41 + +__all__ = ["Model", "ModelArgs", "load_deepseek_v41", "mlx_register"] diff --git a/jang-tools/jang_tools/dsv4_1/mlx_model.py b/jang-tools/jang_tools/dsv4_1/mlx_model.py new file mode 100644 index 00000000..3a32eb2e --- /dev/null +++ b/jang-tools/jang_tools/dsv4_1/mlx_model.py @@ -0,0 +1,448 @@ +"""DeepSeek-V4.1-Flash (``model_type: deepseek_v41``) as a vMLX engine model. + +V4.1 is the V4 family plus Engram n-gram tap layers, a vision tower, dSpark MTP heads, and cross-layer +KV/index/candidate sharing in the latent-attention stack. Rather than re-port that validated compute +into the engine's per-layer-cache idiom, this module WRAPS the proven batch-1 runtime in +``jang_tools.dsv41`` (``DSV41`` / ``Model`` / ``Session``) behind the small contract the engine drives: + + Model(args) # lightweight; real weights attached by the loader + model.layers # list, one per decoder layer (engine cache bookkeeping) + model.make_cache() -> [cache] # one DeepseekV41Cache per layer, sharing one Session + model(input_ids, cache, mask) # append the new tokens, return last-row logits (1,1,V) + +The whole sequence state (per-layer KV windows + compressed/index buffers, the Engram compressed-token +history, the position) lives in one ``jang_tools.dsv41.Session``; the per-layer ``DeepseekV41Cache`` +objects are thin views onto it so the engine can treat the model like any other (len(cache) == layers, +each reports the shared ``offset``). Weights, tokenizer and the disk-resident Engram tables are loaded by +``load_deepseek_v41`` through the validated ``DSV41`` path (q2/q3 per-tensor affine), so the engine's +generic variable-bit hydration is bypassed for this family. +""" + +from __future__ import annotations + +import json +from dataclasses import dataclass + +import mlx.core as mx +import mlx.nn as nn +import numpy as np + +try: + from mlx_lm.models.base import BaseModelArgs +except ImportError: # pragma: no cover - mlx_lm always present in the engine env + @dataclass + class BaseModelArgs: # minimal shim + @classmethod + def from_dict(cls, params): + import inspect + fields = set(inspect.signature(cls).parameters) + return cls(**{k: v for k, v in params.items() if k in fields}) + + +@dataclass +class ModelArgs(BaseModelArgs): + """Only what the engine/registry reads off the class; the full architecture config is parsed by + ``jang_tools.dsv41.Args`` from ``config.json['text_config']`` inside ``DSV41``.""" + + model_type: str = "deepseek_v41" + hidden_size: int = 5120 + num_hidden_layers: int = 40 + vocab_size: int = 129280 + num_attention_heads: int = 64 + num_key_value_heads: int = 1 + head_dim: int = 512 + tie_word_embeddings: bool = False + + @classmethod + def from_dict(cls, params): + # config.json keeps the real fields under text_config; surface the few we expose. + tc = params.get("text_config", params) if isinstance(params, dict) else params + merged = {**(tc if isinstance(tc, dict) else {}), **({"model_type": params.get("model_type")} if isinstance(params, dict) else {})} + return super().from_dict(merged) + + +class _SeqState: + """One decoding sequence's shared state, Session-compatible (jang_tools.dsv41.Session duck type): + the per-layer cache list, the Engram compressed-token history, and the position. The per-layer + DeepseekV41Cache objects ARE the entries of ``caches`` (they duck-type LayerCache), so + ``DSV41.forward(ids, seq)`` drives them directly.""" + + def __init__(self): + self.caches: list = [] + self.history = np.zeros(0, np.int64) + self.pos = 0 + # (main_x [1, <=win, d] bf16, first_position): the dSpark draft-window seed of the last + # committed positions, recorded on DSpark prompt-boundary snapshots so a prefix hit can + # resume drafting with a full window (jang_tools.dsv41.dspark.DSparkRunner.prefill). + self.dspark_tail = None + + def checkpoint(self): + """O(1) ref snapshot for DSpark speculative verification (mirrors runtime Session.checkpoint, + but over DeepseekV41Cache fields). QuantGrowBuffer.append writes past .n in place / regrows, so + snapshotting (window, compress_kv.snapshot(), index_k.snapshot(), pend) + history + pos and + restoring them is a safe rollback.""" + snaps = [] + for c in self.caches: + snaps.append((c.window, c.compress_kv.snapshot(), c.index_k.snapshot(), c.pend_kv, c.pend_score)) + return (snaps, self.history, self.pos) + + def restore(self, ck): + snaps, history, pos = ck + for c, s in zip(self.caches, snaps): + c.window = s[0] + c.compress_kv.load(s[1]) + c.index_k.load(s[2]) + c.pend_kv, c.pend_score = s[3], s[4] + self.history = history + self.pos = pos + + +def _relink(cache: list) -> "_SeqState": + """Unify a per-layer DeepseekV41Cache list onto one _SeqState. make_cache() already shares one; + the engine's per-layer reconstruct builds each cache with its OWN _SeqState (pos on every layer, + Engram history only on the idx==0 layer), so pull those onto a single canonical seq and point all + layers at it. Idempotent.""" + canon = cache[0]._seq + for c in cache: + s = c._seq + if s is not canon: + if s.pos: + canon.pos = s.pos + if s.history.size: + canon.history = s.history + if getattr(s, "dspark_tail", None) is not None: + canon.dspark_tail = s.dspark_tail + c._seq = canon + canon.caches = list(cache) + return canon + + +class DeepseekV41Cache: + """One decoder layer's KV cache for the engine. Duck-types jang_tools.dsv41.LayerCache (the runtime + reads/writes .window / .compress_kv / .index_k / .pend_kv / .pend_score on it) and adds the engine + cache contract (offset / state / meta_state / from_state / is_trimmable / compress_ratio). + + The sliding window is the raw last-``win`` KV; compress_kv / index_k are append-only GrowBuffers of + the compressed-global pool (one row per ``ratio`` tokens); pend_* is the compressor's partial group. + Sequence-level position + Engram history live on the shared _SeqState and are serialized on layer 0 + so a restored prefix resumes exactly (offset, n-gram continuation).""" + + def __init__(self, seq: "_SeqState | None" = None, idx: int = 0, ratio: int = 0, + sliding_window=None, compress_ratio=None): + from jang_tools.dsv41.model import QuantGrowBuffer + + # sliding_window/compress_ratio accepted so the engine's DSV4 reconstruct ctor + # (`cache_cls(sliding_window=.., compress_ratio=..)`) can build us unchanged. + self._seq = seq if seq is not None else _SeqState() + self._idx = int(idx) + self._ratio = int(ratio or compress_ratio or 0) + # LayerCache fields (names match jang_tools.dsv41.model.LayerCache exactly). compress_kv / + # index_k are 4-bit RESIDENT (FP4-parity) so the live 1M-ctx cache is ~890 MB, not ~3.2 GB + # bf16 (the release stores these FP4 too). state() serializes the 4-bit pools as stored (format + # v2 below), so stored prefix/SSD entries are the same size and bit-exact. See + # jang_tools.dsv41.model.QuantGrowBuffer. + self.window = None + self.compress_kv = QuantGrowBuffer() + self.index_k = QuantGrowBuffer() + self.pend_kv = None + self.pend_score = None + self._meta = None # pending meta_state (restore) + self._pending_state = None # pending state tuple (restore); finalize when both present + + @property + def offset(self) -> int: + return int(self._seq.pos) + + @property + def nbytes(self) -> int: + """Resident bytes of this layer's KV (window + compressed pools + pend). The memory-aware + prefix cache sizes/evicts entries by this.""" + total = 0 + for a in (self.window, self.pend_kv, self.pend_score): + if a is not None: + total += a.nbytes + for q in (self.compress_kv, self.index_k): # 4-bit resident bytes (wq + scales + biases) + for a in (q.wq, q.scales, q.biases): + if a is not None and a.shape[1]: + total += int(int(a.size) * a.dtype.size * q.n / a.shape[1]) + return int(total) + + # --- serialization (prefix cache in RAM; disk cache on SSD) --- + # + # Format v2 (``meta_state["fmt"] == 2``): the 4-bit compressed/index pools are emitted AS STORED + # (packed wq uint32 + scales + biases, first n rows only), never dequantized. The old format emitted + # the dequantized bf16 view (~3.6x larger: ~3.3 GB per 1M-token entry, ~6.4 GB on SSD after the + # numpy float32 widening) and re-quantized on restore (not bit-exact). bf16/f16 arrays travel as + # their exact uint16 bit pattern (the numpy-based block store widens bf16 to float32 otherwise); + # meta "dtypes" records the original dtype so restore views them back bit-exactly. + # + # Size: per token ~0.9 KB at 1M context (compressed pools of the 4 KV-source layers, ratio 2/2/2/1, + # 512-dim rows at 4 bit = 256 B + 8 groups x 2 x 2 B scales/biases; plus 128-dim index rows), i.e. + # a stored 1M-token entry is ~0.9 GB, like the resident cache. Fixed per entry: the 40 sliding + # windows (128 x 512 bf16 each, ~5.2 MB) + the Engram history (int32, 4 B/token on layer 0). + # + # Pre-v2 entries are REJECTED (restore raises), never migrated: they were bf16 round-trips and were + # stored N tokens under an N-1 key (the prompt-boundary off-by-one), so they cannot be trusted. + FORMAT = 2 + + @staticmethod + def _to_bits(a): + """(array, dtype-name) with bf16/f16 carried as their exact uint16 bit pattern.""" + name = str(a.dtype).split(".")[-1] + if a.dtype in (mx.bfloat16, mx.float16): + return a.view(mx.uint16), name + return a, name + + @staticmethod + def _from_bits(a, name): + if name in ("bfloat16", "float16"): + want = getattr(mx, name) + if a.dtype == mx.uint16: + return a.view(want) + return a.astype(want) # a store that widened it (value-exact for bf16/f16 sources) + want = getattr(mx, name, None) + if want is not None and a.dtype != want: + return a.astype(want) + return a + + def _named_arrays(self): + """[(name, array)] of this layer's live state, 4-bit pools sliced to their n rows.""" + out = [] + if self.window is not None: + out.append(("window", self.window)) + for tag, q in (("ck", self.compress_kv), ("ik", self.index_k)): + if q.wq is not None and q.n > 0: + out.append((f"{tag}_wq", q.wq[:, : q.n])) + out.append((f"{tag}_s", q.scales[:, : q.n])) + out.append((f"{tag}_b", q.biases[:, : q.n])) + if self.pend_kv is not None: + out.append(("pend_kv", self.pend_kv)) + if self.pend_score is not None: + out.append(("pend_score", self.pend_score)) + if self._idx == 0 and self._seq.history.size: + out.append(("hist", mx.array(self._seq.history.astype(np.int32)))) + if self._idx == 0 and getattr(self._seq, "dspark_tail", None) is not None: + out.append(("dsp_x", self._seq.dspark_tail[0])) + return out + + @property + def state(self): + """Tuple of this layer's live arrays (format v2, see above), in the order declared by + meta_state["order"]. Layer 0 also carries the Engram history.""" + return tuple(self._to_bits(a)[0] for _, a in self._named_arrays()) + + @state.setter + def state(self, value): + # Order-independent restore: the engine may set state before or after meta_state, so stash + # and finalize once both are present (the array layout is declared in meta.order). + self._pending_state = tuple(value) + self._try_finalize() + + @property + def meta_state(self): + named = self._named_arrays() + return json.dumps({ + "fmt": self.FORMAT, + "order": [n for n, _ in named], + "dtypes": {n: str(a.dtype).split(".")[-1] for n, a in named}, + "idx": int(self._idx), "ratio": int(self._ratio), + "ck_n": int(self.compress_kv.n), "ik_n": int(self.index_k.n), + "ck_D": self.compress_kv.D, "ik_D": self.index_k.D, + "pos": int(self._seq.pos), + "dsp_p0": (int(self._seq.dspark_tail[1]) + if self._idx == 0 and getattr(self._seq, "dspark_tail", None) is not None else None), + }) + + @meta_state.setter + def meta_state(self, value): + if isinstance(value, (tuple, list)) and len(value) == 1: + value = value[0] + self._meta = json.loads(value) if isinstance(value, str) else dict(value) + self._try_finalize() + + def _try_finalize(self): + """Apply a restored (state, meta_state) pair once both have arrived.""" + meta, value = self._meta, self._pending_state + if meta is None or value is None: + return + self._pending_state = None + self._meta = None + if int(meta.get("fmt", 0) or 0) != self.FORMAT: + raise ValueError( + f"stale DeepseekV41Cache entry (format {meta.get('fmt', 1)}, need {self.FORMAT}): " + "pre-v2 entries were bf16 round-trips stored at the wrong prompt boundary; rejecting") + order = list(meta["order"]) + if len(order) != len(value): + raise ValueError(f"DeepseekV41Cache state has {len(value)} arrays, meta declares {len(order)}") + dtypes = meta.get("dtypes") or {} + arrs = {n: self._from_bits(a, dtypes.get(n, "")) for n, a in zip(order, value)} + self._idx = int(meta.get("idx", self._idx)) + if meta.get("ratio") is not None: + self._ratio = int(meta["ratio"]) + self.window = arrs.get("window") + for tag, q in (("ck", self.compress_kv), ("ik", self.index_k)): + n = int(meta.get(f"{tag}_n", 0) or 0) + if f"{tag}_wq" in arrs: + wq, sc, bi = arrs[f"{tag}_wq"], arrs[f"{tag}_s"], arrs[f"{tag}_b"] + if not (wq.shape[1] == sc.shape[1] == bi.shape[1] == n): + raise ValueError(f"DeepseekV41Cache {tag} pool rows {wq.shape[1]} != meta n {n}") + q.wq, q.scales, q.biases, q.n = wq, sc, bi, n + q.D = meta.get(f"{tag}_D") or int(wq.shape[2]) * 32 // q.BITS + else: + if n: + raise ValueError(f"DeepseekV41Cache {tag} pool missing ({n} rows declared)") + q.wq = q.scales = q.biases = None + q.n, q.D = 0, None + self.pend_kv = arrs.get("pend_kv") + self.pend_score = arrs.get("pend_score") + self._seq.pos = int(meta.get("pos", 0)) + if self._idx == 0: + hist = arrs.get("hist") + self._seq.history = (np.asarray(hist).astype(np.int64) if hist is not None + else np.zeros(0, np.int64)) + dsp = arrs.get("dsp_x") + self._seq.dspark_tail = (dsp, int(meta["dsp_p0"])) if dsp is not None else None + + @classmethod + def from_state(cls, state, meta_state): + """mlx_lm-style constructor (disk prompt cache restore).""" + c = cls() + c.meta_state = meta_state + c.state = state + return c + + @property + def compress_ratio(self): + """The layer's compression ratio, None for a sliding-window-only (ratio 0) layer -- the + engine's DSV4 record validator requires a ratio in [1, 4096] when one is given. The restore + does not depend on it (meta_state carries "ratio").""" + return int(self._ratio) if self._ratio else None + + @property + def sliding_window(self): + return None if self.window is None else int(self.window.shape[1]) + + def is_trimmable(self) -> bool: + # Not exactly trimmable: the sliding window keeps only the last `win` rows (older rows cannot be + # rebuilt), dropping compressed rows needs the ratio-aligned group boundary, and the compressor's + # partial group (pend_*) is path state. Rollback is checkpoint()/restore() on the _SeqState. + return False + + def trim(self, n: int) -> int: + """No-op (returns 0 trimmed): see is_trimmable. The previous lossy trim (window slice, pool + rows max(1, n // r), cleared pend) produced a state no forward could have produced.""" + return 0 + + +def clone_cache_list(cache: list) -> list: + """Deep copy of an engine DeepseekV41Cache list (a prompt-boundary snapshot), bit-exact and compact: + the 4-bit pools are copied as stored (first n rows of wq/scales/biases), never dequantized, and all + layers share ONE new _SeqState (pos + one copy of the Engram history, not one per layer).""" + def cp(a): + return None if a is None else mx.array(a) # mx.array(a) copies + + src_seq = cache[0]._seq + seq = _SeqState() + seq.pos = int(src_seq.pos) + seq.history = src_seq.history.copy() + tail = getattr(src_seq, "dspark_tail", None) + # only a tail that ends exactly at this boundary is meaningful (a restored one goes stale) + if tail is not None and tail[0] is not None and int(tail[1]) + int(tail[0].shape[1]) == seq.pos: + seq.dspark_tail = (mx.array(tail[0]), int(tail[1])) + out = [] + for c in cache: + cl = DeepseekV41Cache(seq, c._idx, c._ratio) + cl.window = cp(c.window) + for src, dst in ((c.compress_kv, cl.compress_kv), (c.index_k, cl.index_k)): + if src.wq is not None and src.n > 0: + dst.wq = cp(src.wq[:, : src.n]) + dst.scales = cp(src.scales[:, : src.n]) + dst.biases = cp(src.biases[:, : src.n]) + dst.n, dst.D = int(src.n), src.D + cl.pend_kv = cp(c.pend_kv) + cl.pend_score = cp(c.pend_score) + out.append(cl) + seq.caches = list(out) + arrays = [a for c in out for _, a in c._named_arrays()] + if arrays: + mx.eval(arrays) + return out + + +class Model(nn.Module): + """Engine-facing wrapper. Real compute + weights come from an attached ``DSV41`` runtime.""" + + def __init__(self, args: ModelArgs): + super().__init__() + self.args = args + self.model_type = args.model_type + self._rt = None # DSV41, attached by load_deepseek_v41 + + def attach(self, rt) -> "Model": + self._rt = rt + return self + + @property + def runtime(self): + if self._rt is None: + raise RuntimeError("DeepseekV41 Model has no runtime attached (use load_deepseek_v41)") + return self._rt + + @property + def layers(self): + return self.runtime.model.layers + + def make_cache(self): + rt = self.runtime + ratios = getattr(rt.args, "compress_ratios", None) or [0] * rt.args.num_hidden_layers + seq = _SeqState() + seq.caches = [DeepseekV41Cache(seq, i, ratios[i] if i < len(ratios) else 0) + for i in range(rt.args.num_hidden_layers)] + return seq.caches + + def __call__(self, input_ids: mx.array, cache=None, mask=None, all_logits: bool = False, + images=None, token_types=None, **kwargs): + """Append ``input_ids`` (the new chunk) to the sequence; return last-row logits (1,1,V) + (or every row with ``all_logits``). The engine's per-layer cache list is _SeqState.caches, + which duck-types the runtime's Session, so DSV41.forward drives it directly. VL inputs + (``images`` = jang_tools.dsv41.vision.ImageInput list, ``token_types``) splice vision features + into the start_pos-0 prefill chunk; the runtime handles bias_vl routing + engram masking. + ``engram_lookahead`` (list of token ids) is the next prefill chunk: its Engram rows are read + from SSD while this chunk computes. ``prompt_end`` (absolute position where the prompt ends) lets + the late layers skip prompt rows the prompt's last token no longer reads (DSV41.forward).""" + rt = self.runtime + ids = [int(t) for t in mx.array(input_ids).reshape(-1).tolist()] + if cache and all(isinstance(c, DeepseekV41Cache) for c in cache): + seq = _relink(cache) # unify per-layer caches onto one Session (handles reconstructed lists) + elif cache: + # A cache list that is not (entirely) DeepseekV41Cache -- e.g. a generic disk-cache restore + # that rebuilt unknown classes as empty KVCache. Falling back to the runtime's shared + # session would silently continue a stale sequence; refuse instead. + raise TypeError("DeepseekV41 Model needs a DeepseekV41Cache list (got " + + ", ".join(sorted({type(c).__name__ for c in cache})) + ")") + else: + seq = rt.session # no engine cache: the runtime's default session (standalone use) + extra = {"prompt_end": kwargs["prompt_end"]} if kwargs.get("prompt_end") is not None else {} + logits = rt.forward(ids, seq, all_logits=all_logits, images=images, token_types=token_types, + engram_lookahead=kwargs.get("engram_lookahead"), **extra) + if all_logits: + return logits[None] # (1, len, V) + return logits[None, None, :] # (1, 1, V) + + def sanitize(self, weights): # weights load through the DSV41 path, not the generic loader + return weights + + +def load_deepseek_v41(model_path, *, engram_dir=None, skip_params_eval: bool = True, wired: bool = True): + """Load a DeepSeek-V4.1-Flash JANG bundle through the validated runtime and wrap it for the engine. + + Returns ``(model, tokenizer)``. The tokenizer is the bundle's ``tokenizers.Tokenizer``; the caller + (engine loader) wraps it as needed.""" + from jang_tools.dsv41.model import DSV41 + + rt = DSV41(model_path, engram_dir=engram_dir, wired=wired) + model = Model(ModelArgs(model_type="deepseek_v41", num_hidden_layers=rt.args.num_hidden_layers, + hidden_size=rt.args.hidden_size, vocab_size=rt.args.vocab_size, + num_attention_heads=rt.args.num_attention_heads, head_dim=rt.args.head_dim)) + model.attach(rt) + return model, rt.tokenizer diff --git a/jang-tools/jang_tools/dsv4_1/mlx_register.py b/jang-tools/jang_tools/dsv4_1/mlx_register.py new file mode 100644 index 00000000..31cf6d79 --- /dev/null +++ b/jang-tools/jang_tools/dsv4_1/mlx_register.py @@ -0,0 +1,31 @@ +"""Register the DeepSeek-V4.1 model class with mlx_lm so ``model_type: deepseek_v41`` resolves. + +Mirror of ``jang_tools.dsv4.mlx_register``: pre-populate ``sys.modules`` so +``mlx_lm.utils.load_model`` finds ``.Model`` / ``.ModelArgs`` for the new type, and add the mapping +entry when mlx_lm exposes one. Loading the actual weights goes through ``mlx_model.load_deepseek_v41``; +this shim only makes the class discoverable. +""" + +from __future__ import annotations + +import sys + +from jang_tools.dsv4_1 import mlx_model + +_MODEL_TYPE = "deepseek_v41" + + +def register() -> None: + sys.modules.setdefault(f"mlx_lm.models.{_MODEL_TYPE}", mlx_model) + sys.modules[f"mlx_lm.models.{_MODEL_TYPE}"] = mlx_model + try: # optional: some mlx_lm builds keep an explicit mapping dict + import mlx_lm.models as mlx_lm_models + + mapping = getattr(mlx_lm_models, "_MODEL_MAPPING", None) + if isinstance(mapping, dict): + mapping[_MODEL_TYPE] = mlx_model + except ImportError: # no mlx_lm: nothing to register with + return + + +register() diff --git a/jang-tools/tests/dsv41_attention_gather_test.py b/jang-tools/tests/dsv41_attention_gather_test.py new file mode 100644 index 00000000..4dc605d4 --- /dev/null +++ b/jang-tools/tests/dsv41_attention_gather_test.py @@ -0,0 +1,48 @@ +"""Decode-path compressed-row gather is bit-identical to the full-pool path (CPU only).""" + +from __future__ import annotations + +import mlx.core as mx +import numpy as np +import pytest + +from jang_tools.dsv41.model import QuantGrowBuffer, Shared, append_compressed_rows, sparse_attention + + +@pytest.fixture(autouse=True) +def _cpu_only(): + prev = mx.default_device() + mx.set_default_device(mx.cpu) + yield + mx.set_default_device(prev) + + +@pytest.mark.parametrize("S", [1, 3, 6]) +def test_gather_equals_full_pool(S): + rng = np.random.default_rng(S) + D, H, T, W, K = 128, 4, 300, 16, 24 + pool = QuantGrowBuffer() + pool.append(mx.array(rng.standard_normal((1, T, D)).astype(np.float32)).astype(mx.bfloat16)) + raw = mx.array(rng.standard_normal((1, W, D)).astype(np.float32)).astype(mx.bfloat16) + widx = mx.array(np.tile(np.arange(W, dtype=np.int32), (1, S, 1))) + ci = rng.integers(0, T, (1, S, K)).astype(np.int32) + ci[0, :, -3:] = -1 # unused slots + cidx = mx.array(ci) + q = mx.array(rng.standard_normal((1, S, H, D)).astype(np.float32)).astype(mx.bfloat16) + sink = mx.array(rng.standard_normal((H,)).astype(np.float32)) + kv_full, ix_full = append_compressed_rows(raw, widx, cidx, pool, T, Shared(), gather=False) + kv_g, ix_g = append_compressed_rows(raw, widx, cidx, pool, T, Shared(), gather=True) + assert kv_g.shape[1] == W + S * K < kv_full.shape[1] + a = sparse_attention(q, kv_full, sink, ix_full, D ** -0.5) + b = sparse_attention(q, kv_g, sink, ix_g, D ** -0.5) + assert np.array_equal(np.array(a), np.array(b)) + + +def test_shared_view_memoizes_per_forward_and_tracks_appends(): + pool = QuantGrowBuffer() + pool.append(mx.ones((1, 10, 64), mx.bfloat16)) + sh = Shared() + v1 = sh.view(pool, 10) + assert sh.view(pool, 10) is v1 + pool.append(mx.ones((1, 2, 64), mx.bfloat16)) + assert sh.view(pool, 12) is not v1 and sh.view(pool, 12).shape[1] == 12 diff --git a/jang-tools/tests/dsv41_cache_state_test.py b/jang-tools/tests/dsv41_cache_state_test.py new file mode 100644 index 00000000..5b6fb96c --- /dev/null +++ b/jang-tools/tests/dsv41_cache_state_test.py @@ -0,0 +1,181 @@ +"""DeepseekV41Cache serialization (format v2) and prompt-snapshot clone. CPU only, no bundle. + +Contracts: +- state/meta_state carry the 4-bit pools as stored (wq/scales/biases), so a restore is bit-exact and + an entry is ~4-bit size (~0.9 KB/token at the real geometry -> ~0.9 GB per 1M-token entry); +- bf16 arrays travel as uint16 bit patterns, so a numpy round-trip (the block store) is bit-exact; +- pre-v2 entries are rejected, never re-quantized; +- clone_cache_list is bit-exact, compact (n rows, not the grow capacity), shares one _SeqState and + is independent of later appends to the source. +""" + +from __future__ import annotations + +import json + +import mlx.core as mx +import numpy as np +import pytest + + +from jang_tools.dsv4_1.mlx_model import DeepseekV41Cache, _SeqState, clone_cache_list # noqa: E402 + + + +@pytest.fixture(autouse=True) +def _cpu_only(): + """CPU only (another process owns the GPU); restore the previous default afterwards.""" + prev = mx.default_device() + mx.set_default_device(mx.cpu) + yield + mx.set_default_device(prev) + +def _bits(a): + a = mx.array(a) + if a.dtype in (mx.bfloat16, mx.float16): + a = a.view(mx.uint16) + return np.array(a) + + +def _make(n_tokens=600, ratios=(0, 2, 1), seed=0): + rng = np.random.default_rng(seed) + seq = _SeqState() + caches = [DeepseekV41Cache(seq, i, r) for i, r in enumerate(ratios)] + seq.caches = caches + for c in caches: + c.window = mx.array(rng.standard_normal((1, 128, 512)).astype(np.float32)).astype(mx.bfloat16) + if c._ratio: + rows = n_tokens // c._ratio + c.compress_kv.append(mx.array(rng.standard_normal((1, rows, 512)).astype(np.float32)).astype(mx.bfloat16)) + c.index_k.append(mx.array(rng.standard_normal((1, rows, 128)).astype(np.float32)).astype(mx.bfloat16)) + if c._ratio == 2 and n_tokens % 2: + c.pend_kv = mx.array(rng.standard_normal((1, 1, 512)).astype(np.float32)) + c.pend_score = mx.array(rng.standard_normal((1, 1, 512)).astype(np.float32)) + seq.pos = n_tokens + seq.history = rng.integers(0, 50000, n_tokens).astype(np.int64) + mx.eval([c.state for c in caches]) + return caches + + +def _assert_same(a, b): + assert a._idx == b._idx and a._ratio == b._ratio + assert int(a.offset) == int(b.offset) + assert np.array_equal(_bits(a.window), _bits(b.window)) + for qa, qb in ((a.compress_kv, b.compress_kv), (a.index_k, b.index_k)): + assert qa.n == qb.n + if qa.n: + for x, y in ((qa.wq, qb.wq), (qa.scales, qb.scales), (qa.biases, qb.biases)): + assert np.array_equal(_bits(x[:, : qa.n]), _bits(y[:, : qb.n])) + assert np.array_equal(_bits(qa.view()), _bits(qb.view())) + for x, y in ((a.pend_kv, b.pend_kv), (a.pend_score, b.pend_score)): + assert (x is None) == (y is None) + if x is not None: + assert np.array_equal(np.array(x), np.array(y)) + + +@pytest.mark.parametrize("n_tokens", [601, 1024]) +@pytest.mark.parametrize("via_numpy", [False, True]) +def test_state_round_trip_is_bit_exact(n_tokens, via_numpy): + src = _make(n_tokens) + restored = [] + for c in src: + state, meta = c.state, c.meta_state + assert all(a.dtype not in (mx.bfloat16, mx.float16) for a in state) # bits only + if via_numpy: # what the block store / SSD path does (np.array, later mx.array) + state = tuple(mx.array(np.array(a)) for a in state) + meta = json.loads(json.dumps(meta)) + restored.append(DeepseekV41Cache.from_state(state, meta)) + for a, b in zip(src, restored): + _assert_same(a, b) + assert np.array_equal(restored[0]._seq.history, src[0]._seq.history) + + +def test_setter_order_independent_and_ratio_restored(): + src = _make(512)[2] + c = DeepseekV41Cache(sliding_window=128, compress_ratio=None) # engine reconstruct ctor + c.state = src.state + c.meta_state = src.meta_state + _assert_same(src, c) + assert c.compress_ratio == 1 + assert DeepseekV41Cache(ratio=0).compress_ratio is None + + +def test_pre_v2_entry_is_rejected_not_requantized(): + src = _make(512)[1] + old_meta = json.dumps({"order": ["window", "ck", "ik"], "idx": 1, "ck_n": 256, "ik_n": 256, "pos": 512}) + old_state = (src.window, src.compress_kv.view(), src.index_k.view()) + c = DeepseekV41Cache() + c.state = old_state + with pytest.raises(ValueError, match="stale DeepseekV41Cache"): + c.meta_state = old_meta + with pytest.raises(ValueError): + DeepseekV41Cache.from_state(old_state, old_meta) + + +def test_clone_is_exact_compact_shared_and_independent(): + src = _make(700) + cl = clone_cache_list(src) + assert len({id(c._seq) for c in cl}) == 1 and cl[0]._seq.caches == cl + assert cl[0]._seq is not src[0]._seq + for a, b in zip(src, cl): + _assert_same(a, b) + for q in (b.compress_kv, b.index_k): + if q.n: + assert q.wq.shape[1] == q.n # compact: no grow-capacity rows + before = [np.array(c.compress_kv.wq[:, : c.compress_kv.n]) for c in cl if c.compress_kv.n] + # keep decoding on the source: appends, window replacement, pos/history growth + for c in src: + if c._ratio: + c.compress_kv.append(mx.ones((1, 300, 512), mx.bfloat16)) + c.window = mx.zeros((1, 128, 512), mx.bfloat16) + src[0]._seq.pos += 600 + src[0]._seq.history = np.concatenate([src[0]._seq.history, np.zeros(600, np.int64)]) + after = [np.array(c.compress_kv.wq[:, : c.compress_kv.n]) for c in cl if c.compress_kv.n] + assert all(np.array_equal(x, y) for x, y in zip(before, after)) + assert int(cl[0].offset) == 700 and cl[0]._seq.history.size == 700 + assert not np.array_equal(_bits(cl[0].window), np.zeros((1, 128, 512), np.uint16)) + + +def _state_bytes(c): + return sum(int(a.nbytes) for a in c.state) + + +def test_serialized_entry_is_four_bit_size_per_token(): + """Real geometry: pool rows of 512 (kv) + 128 (index) dims at 4 bit, group 64, bf16 scale+bias. + Per pool row: kv 256 + 32 B, index 64 + 8 B. The model's KV-source layers are 2, 8, 14 (ratio 2) + and 20 (ratio 1): 5 ratio-2 layer equivalents -> 5 * 360 / 2 = 900 B/token.""" + n = 4096 + one = _make(n, ratios=(2,))[0] + win = 128 * 512 * 2 + hist = n * 4 + pool_bytes = _state_bytes(one) - win - hist + rows = n // 2 + assert pool_bytes == rows * (256 + 32) + rows * (64 + 8) + per_token_model = pool_bytes / n * 5 # 3 ratio-2 layers + 1 ratio-1 layer (= 2 ratio-2 layers) + assert per_token_model == pytest.approx(900.0) + one_m_entry_gb = per_token_model * (1 << 20) / 1e9 + assert one_m_entry_gb < 1.0 # ~0.94 GB incl. nothing else; + ~5.2 MB windows + 4 MB history + # the old format serialized the dequantized bf16 view: 3.6x the bytes + old = rows * 512 * 2 + rows * 128 * 2 + assert old / pool_bytes == pytest.approx(3.56, rel=0.01) + + +def test_trim_is_refused(): + c = _make(512)[1] + before = _state_bytes(c) + assert c.is_trimmable() is False + assert c.trim(10) == 0 + assert _state_bytes(c) == before and int(c.offset) == 512 + + +def test_dspark_tail_round_trips_and_clone_keeps_it_only_at_the_boundary(): + src = _make(700) + tail_x = mx.array(np.random.default_rng(5).standard_normal((1, 128, 64)).astype(np.float32)).astype(mx.bfloat16) + src[0]._seq.dspark_tail = (tail_x, 700 - 128) + rest = [DeepseekV41Cache.from_state(c.state, c.meta_state) for c in src] + got = rest[0]._seq.dspark_tail + assert got is not None and got[1] == 572 and np.array_equal(_bits(got[0]), _bits(tail_x)) + assert rest[1]._seq.dspark_tail is None # layer 0 only + assert clone_cache_list(src)[0]._seq.dspark_tail is not None + src[0]._seq.pos = 701 # tail no longer ends at the boundary -> stale, dropped by the clone + assert clone_cache_list(src)[0]._seq.dspark_tail is None diff --git a/jang-tools/tests/dsv41_decode_fusion_test.py b/jang-tools/tests/dsv41_decode_fusion_test.py new file mode 100644 index 00000000..0084ac77 --- /dev/null +++ b/jang-tools/tests/dsv41_decode_fusion_test.py @@ -0,0 +1,262 @@ +"""DSV4.1 decode-path speedups == the stock path (small synthetic model, small GPU kernels; no bundle). + +Each technique is A/B-gated by a module flag (env var at import); every test runs the same forward +with the flag off and on and compares logits / outputs. +""" + +from __future__ import annotations + +import mlx.core as mx +import numpy as np +import pytest + +import jang_tools.dsv41.model as M +from jang_tools.dsv41.tests import synth as S + +pytestmark = pytest.mark.skipif(not mx.metal.is_available(), reason="Metal kernels") + +PROMPT = list(range(5, 45)) + + +@pytest.fixture(scope="module") +def tiny(): + return S.build(S.tiny_args()) + + +def _bits(a): + a = mx.array(a) + if a.dtype in (mx.bfloat16, mx.float16): + a = a.view(mx.uint16) + return np.array(a) + + +def _run_greedy(model, steps=12): + out, lg = S.greedy(model, PROMPT, steps, return_logits=True) + return out, np.stack(lg) + + +def _run_verify(model, rows=5): + """Prefill, then one multi-row verify-shaped forward (all logits).""" + caches = S.new_caches(model.args) + mx.eval(S.forward(model, PROMPT, caches, 0)) + lg = S.forward(model, [7, 300, 11, 900, 3, 77, 512, 64][:rows], caches, len(PROMPT), all_logits=True) + return np.array(lg.astype(mx.float32)) + + +_KERNEL = {"ROUTER_GEMV": ("router_logits",), "FUSED_MOE": ("moe_decode",), "FUSED_HC": ("hc_stage_decode",)} + + +def _run_sequential(model, rows=5): + """The verify tokens decoded one forward each (what a verify row should reproduce).""" + caches = S.new_caches(model.args) + mx.eval(S.forward(model, PROMPT, caches, 0)) + out = [np.array(S.forward(model, [t], caches, len(PROMPT) + i).astype(mx.float32))[0] + for i, t in enumerate([7, 300, 11, 900, 3, 77, 512, 64][:rows])] + return np.stack(out) + + +def _ab(monkeypatch, model, attr, run): + """run(model) with M. off, then on; with a kernel behind the flag, assert it actually ran.""" + from jang_tools.dsv41 import metal_decode as MD + calls = [] + names = _KERNEL.get(attr, ()) + for name in names: + def counted(*a, _orig=getattr(MD, name), **k): + out = _orig(*a, **k) + calls.append(out is not None) + return out + + monkeypatch.setattr(MD, name, counted) + monkeypatch.setattr(M, attr, False) + a = run(model) + assert not calls + monkeypatch.setattr(M, attr, True) + b = run(model) + if names: + assert calls and any(calls), f"{names} not taken" + return a, b + + +def test_layer_async_is_bit_exact(tiny, monkeypatch): + (ta, la), (tb, lb) = _ab(monkeypatch, tiny, "LAYER_ASYNC", _run_greedy) + assert ta == tb and len(set(ta)) > 3 + assert np.array_equal(la.view(np.uint32), lb.view(np.uint32)) + va, vb = _ab(monkeypatch, tiny, "LAYER_ASYNC", _run_verify) + assert np.array_equal(va.view(np.uint32), vb.view(np.uint32)) + + +@pytest.mark.parametrize("E,K", [(384, 5120), (128, 1024), (512, 5120)]) +def test_router_gemv_bit_exact_at_one_row(E, K): + from jang_tools.dsv41.metal_decode import router_logits + w = (mx.random.normal((E, K), key=mx.random.key(1)) / 70).astype(mx.bfloat16) + for t in range(24): + x = (mx.random.normal((1, K), key=mx.random.key(t)) * (1 + t % 5)).astype(mx.bfloat16) + assert np.array_equal(_bits(router_logits(x, w)), _bits(x.astype(mx.float32) @ w.astype(mx.float32).T)) + + +def test_router_gemv_rows_equal_their_one_row_decode(): + from jang_tools.dsv41.metal_decode import router_logits + w = (mx.random.normal((384, 5120), key=mx.random.key(1)) / 70).astype(mx.bfloat16) + for R in (1, 2, 5, 8): + x = mx.random.normal((R, 5120), key=mx.random.key(R)).astype(mx.bfloat16) + out = router_logits(x, w) + per_row = mx.concatenate([x[i:i + 1].astype(mx.float32) @ w.astype(mx.float32).T for i in range(R)]) + assert np.array_equal(_bits(out), _bits(per_row)) # row r == its own 1-row decode + stock = x.astype(mx.float32) @ w.astype(mx.float32).T + assert float(mx.abs(out - stock).max()) < 1e-5 + assert router_logits(mx.zeros((9, 5120), mx.bfloat16), w) is None + # outside MLX's matching GEMV tiling (split-K when K >= 16 E): stock path + assert router_logits(mx.zeros((1, 5120), mx.bfloat16), w[:256]) is None + + +def test_router_gemv_decode_is_bit_exact(tiny, monkeypatch): + (ta, la), (tb, lb) = _ab(monkeypatch, tiny, "ROUTER_GEMV", _run_greedy) + assert ta == tb + assert np.array_equal(la.view(np.uint32), lb.view(np.uint32)) + va, vb = _ab(monkeypatch, tiny, "ROUTER_GEMV", _run_verify) + assert np.abs(va - vb).max() < 0.05 * np.abs(va).max() + + +# ----------------------------------------------------------------------------- fused MoE + +_QMV_SRC = r""" + const uint lane = thread_index_in_simdgroup; + const uint out_row = threadgroup_position_in_grid.x * 8u + simdgroup_index_in_threadgroup * 4u; + const int in_w = K * dsv_bytes_per_pack() / dsv_pack_factor(); + const device uint8_t* w[1] = {(const device uint8_t*)wq + out_row * in_w}; + const device T* s[1] = {sc + out_row * (K / 64)}; + const device T* b[1] = {bi + out_row * (K / 64)}; + float acc[4] = {0, 0, 0, 0}; + dsv_qmv4(w, s, b, x, K, lane, acc); + for (int r = 0; r < 4; r++) { float v = simd_sum(acc[r]); if (lane == 0) y[out_row + r] = static_cast(v); } +""" + + +@pytest.mark.parametrize("bits", [2, 3, 8]) +@pytest.mark.parametrize("K", [768, 1024, 2304, 5120]) +def test_qmv_walk_matches_mlx_in_f32(bits, K): + """The kernels' projection walk (qmv_fast / qmv chosen by metal_decode._fast) reproduces MLX's + 1-row quantized_matmul and gather_qmm bit for bit -- checked on f32 outputs, where any change + of accumulation order shows (bf16 outputs would hide most of it).""" + from jang_tools.dsv41 import metal_decode as MD + from jang_tools.dsv41.tests.synth import _rand_quant + k = mx.fast.metal_kernel(name="dsv41_test_qmv", header=MD._QHEADER, source=_QMV_SRC, + input_names=["x", "wq", "sc", "bi"], output_names=["y"]) + N = 512 + w, s, b = _rand_quant(mx.random.key(K + bits), (N, K * bits // 32), bits, K) + s, b = s.astype(mx.float32), b.astype(mx.float32) + for t in range(3): + x = (mx.random.normal((1, K), key=mx.random.key(t)) * 3).astype(mx.bfloat16).astype(mx.float32) + out = k(inputs=[x[0], w, s, b], template=[("T", mx.float32), ("K", K), ("BITS", bits), ("FAST", MD._fast(bits, K))], + grid=(N // 8 * 64, 1, 1), threadgroup=(64, 1, 1), output_shapes=[(N,)], output_dtypes=[mx.float32])[0] + ref = mx.quantized_matmul(x, w, s, b, transpose=True, group_size=64, bits=bits)[0] + gref = mx.gather_qmm(x[None], w[None], s[None], b[None], rhs_indices=mx.array([[0]], mx.uint32), + transpose=True, group_size=64, bits=bits).reshape(-1) + assert np.array_equal(np.array(out), np.array(ref)) + assert np.array_equal(np.array(out), np.array(gref)) + + +def _route(blk, xf): + import mlx.nn as nn + g = blk.ffn.gate + scores = mx.sqrt(nn.softplus(xf.astype(mx.float32) @ g.weight.astype(mx.float32).T)) + idx = mx.argpartition(-(scores + g.bias), kth=blk.topk - 1, axis=-1)[:, :blk.topk] + w = mx.take_along_axis(scores, idx, axis=-1) + return idx, w / (mx.sum(w, -1, keepdims=True) + 1e-20) * blk.route_scale + + +@pytest.mark.parametrize("dims,gate_bits", [("tiny", 2), ("tiny", 3), ("real", 2), ("real", 3)]) +def test_moe_decode_matches_stock(dims, gate_bits, monkeypatch): + from jang_tools.dsv41.metal_decode import moe_decode + args = S.tiny_args(1) if dims == "tiny" else S.real_args(1, 16) + blk = S.build(args, expert_bits=lambda i: (gate_bits, 3)).layers[0] + D = args.hidden_size + for t in range(6): # 1 row: bit-identical to Block.moe (stock), scales up into the SwiGLU clamp + x = (mx.random.normal((1, 1, D), key=mx.random.key(100 + t)) * (0.5 + t)).astype(mx.bfloat16) + monkeypatch.setattr(M, "FUSED_MOE", False) + ref = blk.moe(x) + monkeypatch.setattr(M, "FUSED_MOE", True) + assert np.array_equal(_bits(blk.moe(x)), _bits(ref)) + for R in (2, 5, 8): # R rows: each row == its own 1-row computation, and close to the stock batch + x = (mx.random.normal((R, D), key=mx.random.key(R)) * 2).astype(mx.bfloat16) + rr = [_route(blk, x[i:i + 1]) for i in range(R)] + idx, w = mx.concatenate([a for a, _ in rr]), mx.concatenate([b for _, b in rr]) + out = moe_decode(x, idx, w, blk.ffn.experts, blk.ffn.shared_experts, blk.swiglu_limit) + per = mx.concatenate([moe_decode(x[i:i + 1], idx[i:i + 1], w[i:i + 1], blk.ffn.experts, + blk.ffn.shared_experts, blk.swiglu_limit) for i in range(R)]) + assert np.array_equal(_bits(out), _bits(per)) + monkeypatch.setattr(M, "FUSED_MOE", False) + stock = blk.moe(x[None])[0].astype(mx.float32) + monkeypatch.setattr(M, "FUSED_MOE", True) + assert float(mx.abs(blk.moe(x[None])[0].astype(mx.float32) - stock).max()) <= 0.01 * float(mx.abs(stock).max()) + + +def test_fused_moe_decode_is_bit_exact(tiny, monkeypatch): + (ta, la), (tb, lb) = _ab(monkeypatch, tiny, "FUSED_MOE", _run_greedy) + assert ta == tb + assert np.array_equal(la.view(np.uint32), lb.view(np.uint32)) + va, vb = _ab(monkeypatch, tiny, "FUSED_MOE", _run_verify) + assert np.abs(va - vb).max() < 0.05 * np.abs(va).max() + + +# ----------------------------------------------------------------------------- fused hyper-connections + +@pytest.mark.parametrize("dims", ["tiny", "real"]) +def test_hc_stage_and_post_match_stock(dims): + from jang_tools.dsv41 import metal_decode as MD + args = S.tiny_args(1) if dims == "tiny" else S.real_args(1, 16) + blk = S.build(args).layers[0] + D = args.hidden_size + for t in range(6): + for R in (1, 3): + x = (mx.random.normal((1, R, 4, D), key=mx.random.key(t)) * (0.3 + 2 * t)).astype(mx.bfloat16) + pre = mx.softmax(mx.random.normal((1, R, 4), key=mx.random.key(50 + t)), -1) + h = (mx.random.normal((1, R, D), key=mx.random.key(70 + t)) * 2).astype(mx.bfloat16) + out = MD.hc_stage_decode(x[0], pre[0], blk.hc_ffn_fn, blk.hc_ffn_scale, blk.hc_ffn_base, + blk.ffn_norm.weight, blk.ffn_norm.eps, blk.eps, blk.hc_eps, blk.iters) + for i in range(R): # each row == the stock ops on that row alone (= stock decode) + xi = x[:, i:i + 1] + ref = (blk.ffn_norm(M._hc_pre(xi, pre[:, i:i + 1])), + *blk.hc_mixes(xi, blk.hc_ffn_fn, blk.hc_ffn_scale, blk.hc_ffn_base)) + for a, b in zip(out, ref): + assert np.array_equal(_bits(a[i]), _bits(b.reshape(b.shape[2:]))) + if MD._tf32(): # the expand reproduces the M5 matrix units' TF32 GEMM; elsewhere the + # runtime self-check keeps the stock ops (test_fused_hc_decode_is_bit_exact) + post = MD.hc_post_decode(h[0], x[0], out[2], out[3]) + assert np.array_equal(_bits(post), _bits(M._hc_post(h, x, out[2][None], out[3][None])[0])) + + +def test_fused_hc_decode_is_bit_exact(tiny, monkeypatch): + from jang_tools.dsv41 import metal_decode as MD + M._HC_FUSED_OK.clear() + if not MD._tf32(): + # This device's f32 GEMMs are not TF32 (or MLX_ENABLE_TF32=0): the fused hc path must stay off, + # so decode with the flag on is the stock decode. + monkeypatch.setattr(M, "FUSED_HC", False) + ta, la = _run_greedy(tiny) + monkeypatch.setattr(M, "FUSED_HC", True) + tb, lb = _run_greedy(tiny) + assert ta == tb and np.array_equal(la.view(np.uint32), lb.view(np.uint32)) + assert M._HC_FUSED_OK and not any(M._HC_FUSED_OK.values()) + return + (ta, la), (tb, lb) = _ab(monkeypatch, tiny, "FUSED_HC", _run_greedy) + assert ta == tb + assert np.array_equal(la.view(np.uint32), lb.view(np.uint32)) + assert all(M._HC_FUSED_OK.values()) and M._HC_FUSED_OK + # Verify rows: stock runs the mixes / einsum as TF32 GEMMs over the rows, the fused stage computes + # each row as its 1-row decode, so the fused verify is closer to sequential decode. + va, vb = _ab(monkeypatch, tiny, "FUSED_HC", _run_verify) + monkeypatch.setattr(M, "FUSED_HC", False) + seq = _run_sequential(tiny) + assert np.abs(vb - seq).max() <= np.abs(va - seq).max() + + +def test_all_fusions_together_decode_bit_exact(tiny, monkeypatch): + flags = ("ROUTER_GEMV", "FUSED_MOE", "FUSED_HC", "LAYER_ASYNC") + for f in flags: + monkeypatch.setattr(M, f, False) + a, la = _run_greedy(tiny, 16) + for f in flags: + monkeypatch.setattr(M, f, True) + b, lb = _run_greedy(tiny, 16) + assert a == b and np.array_equal(la.view(np.uint32), lb.view(np.uint32)) diff --git a/jang-tools/tests/dsv41_dspark_governor_test.py b/jang-tools/tests/dsv41_dspark_governor_test.py new file mode 100644 index 00000000..c782123b --- /dev/null +++ b/jang-tools/tests/dsv41_dspark_governor_test.py @@ -0,0 +1,234 @@ +"""DSparkRunner adaptive governor under a synthetic timing model (CPU only, fake backbone/draft). + +The fake backbone's greedy next token is a deterministic function of (token, position); a forward of +L tokens advances a fake clock by base + per_token * L, a draft by draft_cost. The draft's accuracy +is scripted per phase. Contracts: +- output == plain greedy, always; +- when speculation is slower than AR (low acceptance) the runner spends ~all tokens in AR steps and + its total time is within a few percent of pure AR; +- when speculation is faster it is used and beats AR; +- no permanent latch: speculative probes keep happening in AR mode, and acceptance recovering mid- + stream returns to speculation. +""" + +from __future__ import annotations + +from types import SimpleNamespace + +import mlx.core as mx +import pytest + + +from jang_tools.dsv41.dspark import BoundedWindow, DSparkRunner, _Governor # noqa: E402 + + +@pytest.fixture(autouse=True) +def _cpu_only(): + """CPU only (another process owns the GPU); restore the previous default afterwards.""" + prev = mx.default_device() + mx.set_default_device(mx.cpu) + yield + mx.set_default_device(prev) + +V = 101 + + +def nxt(tok, pos): + return (tok * 13 + pos * 5 + 7) % V + + +class Clock: + def __init__(self): + self.t = 0.0 + + def __call__(self): + return self.t + + +class Sess: + def __init__(self): + self.pos = 0 + self.caches = [] + + def checkpoint(self): + return self.pos + + def restore(self, ck): + self.pos = ck + + +class FakeBackbone: + def __init__(self, clock, base=0.020, per_token=0.001): + self.clock, self.base, self.per_token = clock, base, per_token + + def new_session(self): + return Sess() + + def forward(self, ids, sess, all_logits=False, return_hidden=False): + self.clock.t += self.base + self.per_token * len(ids) + rows = [nxt(int(t), sess.pos + i) for i, t in enumerate(ids)] + sess.pos += len(ids) + logits = mx.stack([mx.eye(V)[r] for r in rows]) + out = logits if all_logits else logits[-1] + return (out, mx.zeros((len(ids), 2))) if return_hidden else out + + +class FakeDraft: + """accuracy(position) -> fraction of the block's leading tokens drafted correctly there.""" + + def __init__(self, clock, accuracy, bs=5, cost=0.006): + self.clock, self.accuracy, self.bs, self.cost = clock, accuracy, bs, cost + self.stages = [SimpleNamespace(attn=SimpleNamespace(win=8, window=BoundedWindow(8)))] + self.calls = 0 + + def reset_windows(self): + pass + + def seed_windows(self, main_hidden, positions): + pass + + def draft(self, seed_tok, start_pos): + self.clock.t += self.cost + good = int(round(self.accuracy(start_pos) * self.bs)) + self.calls += 1 + out, t, p = [int(seed_tok)], int(seed_tok), start_pos + 1 + for i in range(self.bs): + n = nxt(t, p) if i < good else (nxt(t, p) + 1) % V + out.append(n) + t, p = n, p + 1 + return out, mx.ones((self.bs,)) + + +def greedy(prompt, n): + pos, t, out = len(prompt), nxt(prompt[-1], len(prompt) - 1), [] + for _ in range(n): + out.append(t) + t = nxt(t, pos) + pos += 1 + return out + + +def run(accuracy, n=400, draft_cost=0.006, **kw): + clock = Clock() + m = FakeBackbone(clock) + ds = FakeDraft(clock, accuracy, cost=draft_cost) + r = DSparkRunner(m, ds, adaptive=True, clock=clock, **kw) + prompt = [3, 1, 4, 1, 5] + sess, pending, c = r.prefill(prompt) + t0 = clock.t + stats = {} + out = list(r.decode_stream(sess, pending, c, n, stats=stats)) + assert out == greedy(prompt, n) + ar_time = n * (m.base + m.per_token) + return (clock.t - t0) / ar_time, stats, ds + + +def test_low_acceptance_stays_at_ar_speed(): + ratio, stats, ds = run(lambda i: 0.0) + assert ratio < 1.06, ratio + assert stats["ar_steps"] > 0.85 * stats["emitted"] + assert stats["spec_steps"] >= 400 // 17 - 2 # probes keep happening: no permanent latch + + +def test_partial_acceptance_that_loses_to_ar_falls_back(): + # one accepted token per block: k>=1 every step (the old zero-streak latch never fired), but with + # a slow draft the rejecting step (draft + verify + commit forward) costs more per token than AR + ratio, stats, _ = run(lambda pos: 0.2, n=400, draft_cost=0.04) + assert ratio < 1.08, ratio + assert stats["ar_steps"] > 0.8 * stats["emitted"] + + +def test_high_acceptance_speculates_and_beats_ar(): + ratio, stats, _ = run(lambda i: 1.0) + assert ratio < 0.45, ratio + assert stats["spec_steps"] > 3 * stats["ar_steps"] + assert stats["ar_steps"] >= 1 # AR keeps being re-measured + + +def test_recovers_when_acceptance_returns(): + # hopeless until position 200, perfect afterwards: back to speculation within one probe period + ratio, stats, ds = run(lambda pos: 0.0 if pos < 200 else 1.0, n=600) + assert ratio < 0.7, ratio + assert stats["spec_steps"] > 60 + + +def test_governor_has_no_terminal_state(): + g = _Governor(probe_every=4, ar_probe_every=8) + seq = [] + for step in range(200): + mode = g.choose() + seq.append(mode) + g.record(mode, 0.05 if mode == "spec" else 0.02, 1) # spec always slower + assert "spec" in seq[-20:] # still probing at the end + g2 = _Governor(probe_every=4, ar_probe_every=8) + seq2 = [] + for step in range(200): + mode = g2.choose() + seq2.append(mode) + g2.record(mode, 0.01 if mode == "spec" else 0.02, 1) # spec always faster + assert "ar" in seq2[-20:] # AR still re-measured at the end + assert seq2[-20:].count("spec") > 15 + + +def test_markov_chain_matches_reference_loop(): + import numpy as np + + from jang_tools.dsv41.dspark import markov_chain + + rng = np.random.default_rng(3) + vocab, rank, bs = 97, 16, 5 + emb = mx.array(rng.standard_normal((vocab, rank)).astype(np.float32)).astype(mx.bfloat16) + head = mx.array(rng.standard_normal((vocab, rank)).astype(np.float32)).astype(mx.bfloat16) + logits = mx.array(rng.standard_normal((bs, vocab)).astype(np.float32)) + # reference: the pre-hoist loop (head re-cast every step, host argmax) + out, mes = [11], [] + for i in range(bs): + me = emb[out[i]].astype(mx.float32) + out.append(int(mx.argmax(logits[i] + me @ head.astype(mx.float32).T))) + mes.append(me) + got, me = markov_chain(logits, emb, head.astype(mx.float32).T, 11) + assert [11] + got.tolist() == out + assert np.array_equal(np.array(me), np.array(mx.stack(mes))) + + +class SeedRecordingDraft(FakeDraft): + def __init__(self, clock): + super().__init__(clock, lambda pos: 1.0) + self.reseeded = [] + + def seed_from_main_x(self, main_x, positions): + self.reseeded.append(list(positions)) + + +@pytest.mark.parametrize("tail_end_offset,expect", [(0, True), (-1, False)]) +def test_prefix_hit_reseeds_draft_window_from_snapshot_tail(tail_end_offset, expect): + clock = Clock() + m = FakeBackbone(clock) + ds = SeedRecordingDraft(clock) + r = DSparkRunner(m, ds, adaptive=True, clock=clock) + sess = Sess() + sess.pos = 50 # restored prefix + sess.dspark_tail = (mx.zeros((1, 8, 4)), 42 + tail_end_offset) + r.prefill([7, 8, 9], session=sess) + assert (ds.reseeded == [list(range(42, 50))]) is expect + + +class LookaheadBackbone(FakeBackbone): + def __init__(self, clock): + super().__init__(clock) + self.calls = [] + + def forward(self, ids, sess, all_logits=False, return_hidden=False, engram_lookahead=None): + self.calls.append((list(ids), engram_lookahead)) + return super().forward(ids, sess, all_logits=all_logits, return_hidden=return_hidden) + + +def test_chunked_prefill_passes_next_chunk_as_engram_lookahead(): + clock = Clock() + m = LookaheadBackbone(clock) + r = DSparkRunner(m, FakeDraft(clock, lambda pos: 1.0), adaptive=True, clock=clock) + prompt = list(range(1, 12)) # body = 10 tokens in chunks of 4, then the last token + r.prefill(prompt, chunk_size=4) + fed = [c[0] for c in m.calls] + assert fed == [prompt[0:4], prompt[4:8], prompt[8:10], prompt[10:11]] + assert [c[1] for c in m.calls] == [fed[1], fed[2], fed[3], None] diff --git a/jang-tools/tests/dsv41_topk_test.py b/jang-tools/tests/dsv41_topk_test.py new file mode 100644 index 00000000..2b2682ad --- /dev/null +++ b/jang-tools/tests/dsv41_topk_test.py @@ -0,0 +1,34 @@ +"""Block top-k (long index rows) selects exactly the values the direct argpartition selects.""" +import mlx.core as mx +import pytest + +import jang_tools.dsv41.model as M + + +@pytest.mark.parametrize("rows,length", [(7, 70000), (3, 140001), (2, 65536)]) +def test_block_topk_matches_direct(rows, length): + with mx.stream(mx.cpu): + sc = mx.random.normal((max(rows, 9), length), key=mx.random.key(length))[:max(rows, 9)] + rows = sc.shape[0] + sc = mx.where(mx.arange(length)[None] >= (length - 5 + mx.arange(rows))[:, None], -mx.inf, sc) + block = M.topk_indices(sc, 512) + direct = mx.argpartition(-sc, kth=511, axis=-1)[:, :512] + vb = mx.sort(mx.take_along_axis(sc, block, axis=-1), axis=-1) + vd = mx.sort(mx.take_along_axis(sc, direct, axis=-1), axis=-1) + assert block.dtype == mx.int32 and block.shape == (rows, 512) + assert mx.array_equal(vb, vd).item() + + +def test_short_rows_keep_direct_path(): + with mx.stream(mx.cpu): + sc = mx.random.normal((4, 1000), key=mx.random.key(1)) + assert M.topk_indices(sc, 1000).shape == (4, 1000) + assert M.topk_indices(sc, 16).shape == (4, 16) + + +def test_decode_rows_keep_direct_path(): + """<= GATHER_MAX_QUERIES rows (decode / verify) never take the block path: identical indices.""" + with mx.stream(mx.cpu): + sc = mx.random.normal((3, 70000), key=mx.random.key(3)) + direct = mx.argpartition(-sc, kth=511, axis=-1)[:, :512].astype(mx.int32) + assert mx.array_equal(M.topk_indices(sc, 512), direct).item()