Skip to content

Port basalt's sampler to Metal (OI-005, family 5) - #102

Closed
woodsonl wants to merge 78 commits into
lithos-ai:mainfrom
woodsonl:woodsonl/basalt-sampler-upstream
Closed

woodsonl wants to merge 78 commits into
lithos-ai:mainfrom
woodsonl:woodsonl/basalt-sampler-upstream

Conversation

@woodsonl

Copy link
Copy Markdown

The net change of woodsonl#25 (fork merge commit cc8aa8e), as one commit on #101 (woodsonl/libdevice-library-math-upstream). Stacked: merge after #101, which follows #100, #99, #98 and #82.

The change applies to #101's branch without a conflict, and its added and removed lines equal the fork merge's. Every file it touches equals the fork's after the merge, except docs/design/flash-next.md, which differs in one line outside this change, this stack's metal_core.mm:99 citation.

Verification of this change on #101's branch (M3 Max, 40 cores, macOS 27.0.1), with BASALT_SRC set to a basalt checkout at b4c63b5, BASALT_PLE_FIXTURE at the two fetched byte ranges, and the native module built in the worktree:

  • Every tests/kernels/test_basalt_*.py file (25), plain and under MTL_SHADER_VALIDATION=1: 1,339 passed, 0 skipped, 0 validation reports.
  • tests/contract: 1,573 passed, 2 failed, 17 skipped (16 for the serve extra's httpx and fastapi, 1 for mlx). The two failures are tests/contract/test_streaming_moe_oracle.py's test_streamed_experts_equal_materialized_hf[True] and [False], which fail the same way on Transcribe libdevice's math functions in the port contract #101's head without this change; Build the streamed MoE oracle's rotary table without device= #67 fixes them.
  • tests/runtime: 96 passed. tools/ci/hygiene.py: ok.
  • These ran on the change through fork commit 3842a99; 39c38a8, the last commit, changes docs/research/basalt-nvcc/prefill_kernels.md alone, which no test reads.

What and why

This pull request ports basalt's sampler (src/kernels/cuda/sampler.cu at b4c63b5) to Metal 4 as an exact port: the
same arithmetic in nvcc's rounding sequence, the same reduction orders and tie rules, and every pick bit for bit where
basalt's tests compare bits. It covers OI-005's fifth family: the greedy pick (the lowest index on ties), Philox
sampling on (seed, absolute position), the cluster top-k and greedy argmax, and their tests, sampler_parity whole
and decode_cluster_parity's argmax half.

Kernels (kernels/common/basalt_sampler.metal)

  • bs_greedy_partial and bs_greedy_merge: the cluster argmax (sampler_greedy_cluster_kernel) as a partials
    dispatch of 8 threadgroups per row and a merge, since Metal has no thread-block clusters. The pick is the row's
    lowest id of its largest non-NaN value above -inf, else 0, whatever the partition.
  • bs_greedy_one_block: the greedy kernel with the logit bias and the penalty window (mode 1).
  • bs_greedy_top_prob: the drafter's greedy tail, the pick's softmax probability in basalt's 1,024-thread order.
  • bs_split_part and bs_split_merge: the sampled path (top_k, the penalties, top_p, min_p, temperature, one
    Philox draw at the row's counter ctr_base + position + t), with the probe's probability (sample_tokens_probe).
  • bs_sample_one_block: the sampled path the build takes past 64 rows or 64 blocks of 4,096 logits.
  • bs_coupled_stage, bs_coupled_penalize, bs_coupled_part and bs_coupled_merge: coupled draft sampling.

Every compare that orders or selects possibly subnormal floats runs on order-preserving integer keys of the bits,
because this GPU's <, > and == read a subnormal as zero (a new platform test pins this). Every binary32
operation that can meet a subnormal is IEEE's, emulated where this GPU flushes.

Shared helpers

  • kernels/common/basalt_ieee.metal: ieee_add, ieee_mul and their scaling helpers, moved from
    basalt_q8_1.metal unchanged. Every builder that concatenates basalt_q8_1.metal now includes it first.
  • kernels/common/basalt_f64.metal: IEEE binary64 in software (add, multiply, fma, fma rounded to odd, divide,
    conversions and ordered compares, with subnormals), for the sampled tail's double-precision steps.
  • kernels/common/basalt_libdevice.metal: exact transcriptions of NVIDIA libdevice's __nv_exp and __nv_logf
    as nvcc 13.0 inlines them into sampler.cu, so exp(double) and logf give CUDA's bits. Credited in
    third_party/NOTICE under "NVIDIA libdevice (CUDA Toolkit 13.0, NVIDIA Corporation)".

The op kind

basalt_sample (monolith/ops/basalt_sample.py, handler _basalt_sample in monolith/compiler/emit.py): inputs
(logits [T, V] F32, ctr_base [2] U32, nq [1] U32[, bias [V] F32][, history [T, H] I32]), outputs (token [T] I32, qprob [T] F32). Per-step values (rows, seed, position, the probe's queries) come from StepState and per-request
values from the op's params record, whose mode word gates the dispatches as basalt's verify window picks its
tokens (verify.cpp:2496-2498, :2659): 0 the cluster pair alone, for a request the window does not sample again
(greedy, or a temperature not above 0, NaN included, with no penalty window and no bias); 1 the one-block greedy kernel
after it (greedy, or a temperature at or below 0, with a window or a bias); 2 the sampled path after it (a sampled
request, or a NaN temperature with a window or a bias, which samples at inv_t 0). Attr greedy_only builds a program
for mode 0 alone (below).

Tests

  • tests/kernels/test_basalt_sampler.py: sampler_parity ported whole, every fixture and gate, on both sampled
    paths and both greedy kernels, plus the port's additions (TP.1 for the top-prob kernel, PL.1, PW.1 a penalty
    window wider than the history rows, W.1 window invariance on every path, the one-block geometry, the launch guards,
    the NaN store).
  • tests/kernels/test_basalt_coupled.py: coupled_parity's 420 cases (C.1-C.6), A8, the launch guards and the NaN
    store.
  • tests/kernels/test_basalt_decode_cluster.py: decode_cluster_parity's argmax half, every denormal case of more
    than one logit holding a row a flushing compare would miss. The other half checks qsa_block_topk_cluster, the
    sparse-attention indexer's block selection, and carries over with that kernel's port.
  • tests/kernels/test_basalt_sampler_program.py: the op through emitted programs replayed by Engine (M18.1, DC.1
    with A6, DCP.2, MG.1, the greedy-only build).
  • tests/kernels/test_basalt_sampler_helpers.py: the binary64, IEEE binary32, libdevice, Philox and key helpers
    bit for bit against host references.
  • tests/basalt_sampler_ref.py (host references, numpy only), tests/contract/test_basalt_sampler_refs.py and
    tests/contract/test_basalt_sampler_ops.py (registration, coverage, the emitted programs, the packer's refusals).

Docs

docs/research/basalt-nvcc/sampler.md records nvcc's sm_120 PTX and SASS for every sampler site. The port contract
(docs/design/flash-next.md) lists the sampler's library logf and binary64 exp among the library calls that are
not correctly rounded (invariant 5 transcribes libdevice's functions, these two included), states the compare-on-keys
rule, quotes both gates of decode_cluster_parity, and adds the top-prob kernel to the table of kernels without a
basalt reference test. docs/research/basalt-nvcc/nan.md lists the sampler's stores.

The merge of main

The branch merges origin/main five times, at 9b255e0 (acf1c53), 50a6152 (2acc918), 6fac383 (81c9be9), 15d65e4
(df6768a) and 143c09a (8011a3c). These changes follow from main's newer work:

  • Main's IEEE helpers (ieee_div127, ieee_rcp, ieee_fma, ieee_div, warp_sum_ieee) stay in
    basalt_q8_1.metal; basalt_s2_experts_source() and the drafter tests' two hand-built control sources now include
    basalt_ieee.metal ahead of it.
  • The sampler's division is renamed ieee_div_any: main's ieee_div has the same signature and covers divisors of
    at least 1 only, so a source concatenating both files would not compile.
  • Main's invariant 5 requires sm_120's canonical NaN at every store a NaN can reach. Two sampler stores take a NaN
    from this GPU's arithmetic and now store through cuda_nan: bs_greedy_top_prob's probability and
    bs_coupled_penalize's in-place logit. Each has the negative-control check of test_basalt_nan.py. The probe's
    qprob and the coupled out_prob already carry 0x7fffffff (the software binary64's conversion).
  • Main's Apple9 (M3, M4): the matrix tile and measured M3 Ultra / M4 Pro profiles #35 has invariant 5 transcribe libdevice's exp, logf, expf, powf, cosf, sinf and log1pf. Its
    sentence replaces this branch's sampler-only one in that paragraph, which keeps the pointer to sampler.md
    sections 2.5-2.6 and the note that the sampler's binary64 is software IEEE binary64; sampler.md section 4.3 no
    longer asks the contract to name the two functions.
  • 3842a99 points 24 line citations in main's pages at their lines, since this branch adds lines to flash-next.md
    and moves ieee_add and ieee_mul to basalt_ieee.metal: prefill_kernels.md's eight flash-next.md cites
    (three of them pointed one or ten lines early on main already), and the sixteen basalt_q8_1.metal cites of
    hc_fused.md and prefill_kernels.md; basalt_s2_experts.metal's header names basalt_ieee.metal as
    ieee_mul's home.

Decisions

  • D1: the branch builds on origin/main (the shader-validation gate, the IEEE helpers, invariant 5).
  • D2: IEEE subnormals emulated at every binary32 site that can meet one; division through binary64 (double rounding
    is harmless for a quotient, 53 >= 2 x 24 + 2), the penalty's fma through f64_fma_odd (rounded to odd, then to
    nearest).
  • D3: the IEEE helpers in basalt_ieee.metal, binary64 and libdevice in files of their own; the key helpers stay in
    basalt_sampler.metal until a second user appears.
  • D4: the one-block kernels keep their penalty bitmap in device memory, one region per row; every other kernel uses
    static threadgroup arrays at basalt's sizes, the coupled seen at 8,192 words.
  • D5: the draw counter is ctr_base (the request's base, two words) plus StepState position plus the row.
  • D6: penalties need a history input; the packer refuses a penalty window without one.
  • D7: one op kind, basalt_sample; the drafter's top-prob and coupled kernels are tested at kernel level and get op
    kinds with the drafter, their only engine caller.
  • D8: the sampled references use nv_exp and nv_logf; mirror_prob keeps math.exp.
  • D9: libdevice's __nv_exp and __nv_logf transcribed exactly (credited to NVIDIA in NOTICE).
  • D10: the top-prob kernel's __expf is fast::exp2 of the IEEE product with log2(e), the sums around it IEEE adds.
  • D11: every dispatch emitted and gated on mode, with a greedy-only build because the gated dispatches cost more
    than the run-to-run spread (below).
  • D12: min_p above 1 accepted, as basalt accepts it (the tail keeps nothing and picks the list's head).
  • D13: bs_row_top_prob and bs_map_ids are not built (no caller).
  • D14: threadgroup out-of-bounds stores measured under shader validation (below).
  • D15: the mode follows basalt's verify window, which samples again only a sampled request, a penalty window or a
    logit bias; so a NaN temperature keeps the greedy pick without either and samples with one (verify.cpp:2496-2498,
    :2659; generate.cpp:8195-8196 binds the history only for penalty_last_n > 0).

Measurements (Apple M3 Max, 40 GPU cores, macOS 27.0.1)

  • D14, shader validation and threadgroup memory [M]. A plain store past the end of a kernel's whole threadgroup
    allocation is reported; a store from one static threadgroup array into the next is not, and lands there; a
    threadgroup atomic_fetch_or is never checked. So every threadgroup index and every within-scratch row offset in
    these kernels is bounded at its site, and the coupled seen and the list arrays rest on the fixtures' results.
  • Compile [M]. The family's library 0.22 s and the bs_split_merge pipeline 0.14 s, first build; every sampler
    pipeline allows 1,024 threads per threadgroup.
  • Bench (tools/bench/basalt_sampler.py, the GPU alone, two runs) [M]. Minimum GPU time per call:
    • B.1, the split path at 248,320 logits: 337-338 us (T 1, top_k 20), 453-530 us (T 1, 64), 227-254 us (T 4, 20),
      556-616 us (T 4, 64), 296-325 us (T 8, 20), 883-888 us (T 8, 64); with the probe 331-338, 354-463, 228-265,
      554-623, 295-298 and 832-847 us.
    • B.2, the coupled draft at 106,299 logits: 120-121 us.
    • Mode 0: the three gated dispatches add 5.6-5.7 us a step at T = 1 and 7.9-10.2 us at T = 8 (minimum of 40
      alternating pairs of 20-step command buffers; the ranges of the two sides do not overlap), so greedy_only
      programs emit the cluster pair alone.
  • Residual. basalt's __expf in the top-prob kernel is MUFU.EX2, which NVIDIA does not specify; the port uses
    fast::exp2 of the same product (invariant 5). The probability can differ from CUDA's in its last bits; its pick
    cannot. TP.1 bounds the probability at q5k_head_parity's 1e-5 relative error.

Review fixes

CodeRabbit's findings on this pull request: three fixed and answered on the PR (below); a fourth, E731 on two lambdas
in test_basalt_platform.py, was withdrawn as main's lines outside this change.

  • 26d6d74, the bias read. A program built without a bias input binds a 16-byte placeholder at slot 3, yet a
    request's record could still set the BIAS flag, and the one-block greedy kernel, the split part and the one-block
    sampled kernel would then read bias[v] across the whole vocabulary, past the placeholder. The handler now compiles
    the family with BS_BIAS_BOUND 1 when it binds the (V,) bias and 0 otherwise, and the kernels add the bias only
    where it is 1. The contract test checks the macro on programs with and without the input; a program-tier test
    writes the flag into a program without the input, in modes 1 and 2 on both sampled paths, and gets the flag-clear
    picks with no validation report.
  • d5e5eca, the host fma. The package supports Python 3.10, where math.fma does not exist (it came in 3.13), and the
    contract tier runs the sampled references, whose nv_exp calls fma64. fma_exact computes IEEE's fma on Python
    floats exactly (a * b + c as a Fraction, rounded once, subnormals included), with IEEE's NaN, infinity and
    signed-zero cases; fma64 uses math.fma where it exists and fma_exact elsewhere. On 367,304 operand triples it
    equals math.fma bit for bit, apart from the sign of an overflow's infinity, which math.fma does not give.
  • 39c38a8, the sampler helpers' home. prefill_kernels.md placed ieee_div_any, the float keys and three soft
    binary64 helpers on this branch and listed them among the helpers main lacks; it now cites their lines on main.

Two review lenses (exactness against sampler.cu; tests and bounds, D14 included) added:

  • 0fc78e3, the mode rule for a NaN temperature (D15); the contract's mode table pins the new rows.
  • e198948 and 67e845a, PW.1: a penalty window of 64 over history rows of 4 slots, on G-1B, both sampled paths and
    MG.1's programs. Without the window clamp the cases fail with shader validation's "Invalid load".
  • ec45e7b, the launch guards: each early return that keeps a dispatch inside its geometry or a record inside its
    sizes now has a case that dispatches past it (nine guards in six kernels, and basalt_coupled_node's refusal).
  • 86e5dd1, DCP.1's two nv = 1,000 denormal cases redrawn, so every denormal case fails a compare that flushes.
  • 3b4153f, why decode_cluster_parity's QSA half is not ported here, and its argmax gate quoted in the contract.
  • ce19a28 and 97460d2, the libdevice transcriptions stated by source in NOTICE and the headers.

Verification

At 3842a99 (October 24, 2026), from the repository root with the dev venv and the native module rebuilt (logs
sampler-verify-20261024-175212-59726.log and sampler-ple-verify-20261024-185143-81665.log):

  • Every tests/kernels/test_basalt_*.py file, this PR's five and every basalt port file on main (25), plain and under
    MTL_SHADER_VALIDATION=1: 1,321 passed, 18 skipped, 0 validation reports. The 18 skips are the n-gram block's
    real-weight cases, which need BASALT_PLE_FIXTURE; none is in this PR's files. With the fixture set, the n-gram
    block's two kernel files run whole: 82 passed, 0 skipped, plain and validated, 0 reports.
  • tests/contract with BASALT_SRC set: 1,575 passed, 21 skipped: 17 optional extras this venv lacks (httpx,
    fastapi, mlx) and 4 the same fixture's, which pass with it set (the n-gram contract files: 85 passed).
  • tests/runtime: 96 passed. tools/ci/hygiene.py and compileall: ok.

39c38a8 changes prefill_kernels.md alone, which no test reads; tools/ci/hygiene.py passes on it.

basalt's .basalt packs ship their weights as GGUF blocks, so porting a
pack starts with formats that read them. monolith/formats/gguf.py
registers Q2_0, Q4_0, Q5_0, Q8_0, Q3_K, Q4_K, Q5_K, Q6_K, IQ4_NL and
IQ4_XS: each block is ggml-common.h's struct as a numpy structured
dtype, unpack takes a tensor's GGUF rows, and dequantize is the oracle,
written from ggml-quants.c's dequantize_row_* at llama.cpp 3cf03257.
GGML_TYPES maps the GGUF type ids. 42 is GGML_TYPE_Q2_0 (64 values per
block: an fp16 scale and 2-bit codes, value (code - 1) * d), the type of
every routed expert in the official Q2_0 pack. BF16 rows go to the
existing bf16 plugin. F32 and F16 decode by a dtype view, without a
plugin: in a pack they are norms and conv taps, and "f32" already names
the non-plugin checkpoint dtype.

Every product in these decoders is exact in float32. The only rounding
step is the subtraction in Q4_K and Q5_K, which an FMA rounds the same
way, so the oracle does not depend on evaluation order or contraction.

The tests compare the oracle byte for byte with llama.cpp's own numpy
dequantizers (gguf-py quants.py at the same commit, vendored unchanged
in tests/contract/gguf_reference.py) and with a scalar port of
dequantize_row_q2_0, which gguf-py lacks. They use random blocks with
finite scales plus edge scales (+-0, subnormals, the largest normal).
With BASALT_SRC set, they also compile basalt's two CPU references and
compare against them. pack, unpack_pack and msl_decode come with the
Metal decode kernels.
monolith/formats/basalt_reader.py reads the container basalt defines
in include/basalt/core/model_format.hpp and writes with
tools/model_file.py. It parses the 64 KiB header and its section table
(sections at 2 MiB multiples, each with a SHA-256) and gives section
access by name. It returns meta's GGUF tensors with absolute offsets,
checked against their type and shape. It also parses dense.index v3,
experts.layout v5 and mtp/dense.index. BasaltFile maps a path, or
takes any buffer that has a length and slices to bytes, such as an
HTTP range reader.

The parsers refuse what basalt's own readers refuse, because a
misparsed row is a wrong byte offset that still decodes to a plausible
weight:
- a header, version or section outside the file (model_file.cpp);
- a dense row that is not 19 fields (weights.cpp);
- a layout newer than v5, or layers that do not tile the experts
  section (expert_layout.cpp);
- an MTP line that is not 6 fields (mtp.cpp).

ExpertsLayout.matrices splits an expert blob into its gate, up and down
GGUF rows the way basalt's native_fmt does, from the n_embd and n_ff
the caller passes; the module names no model.
Synthetic blocks prove the decode rules; real bytes prove that the
reader finds the right rows. The pack (jesdga/Qwen3.8-Flash-Next-Basalt,
Qwen3.8-FN-GSQ-RCO-Q2_0.basalt at 2a6a758) is 64.9 GiB and is never
downloaded. tests/contract/fixtures/make_basalt_fixture.py range-reads
it through BasaltFile over HTTP and refuses any reply that is not a
206 of the exact length. It writes a 49 KB fixture:
- the header and section table;
- experts.layout, mtp/dense.index, and dense.index gzipped;
- up to 1 KiB of the first and last rows of the first meta tensor of
  each ggml type;
- the first and last gate, up and down rows of expert 0 in layer 0 and
  expert 511 in layer 47, located through experts.layout.

test_basalt_pack.py checks the fixture three ways:
- the three index sections hash to the table's SHA-256;
- the dense pool, the 48 Q2_0 expert layers and the drafter index are
  consistent, and every fixture row lies where meta or the layout puts
  it;
- the rows of all 13 types the pack uses decode byte for byte like the
  reference, with finite, plausible values.
With BASALT_SRC set, the rows are also compared with basalt's compiled
CPU references. The weights are Qwen's (Qwen Community License 1.0);
third_party/NOTICE records the provenance.
The port needs one registered format for each ggml type the Q2_0 pack
uses. F32 (292 tensors in the pack) and F16 (one) were decoded by a
dtype view outside the registry. They are now one-value block formats,
f32 and f16, so ggml_dequantize sends every type through FORMATS.

Registering "f32" changes no checkpoint path. pack_plan.bind_formats
rewrites a checkpoint's "f32" to "bf16" before it resolves a format,
and dequant.py and pack_plan.py skip "f32" groups by name.

The synthetic F16 values now get the fp16 edge cases and stay finite,
as the block scales do: random halves include NaNs, and a hardware
conversion may quiet their bits. gguf.py also carries the ggml
authors' MIT notice, since it copies the kvalues_iq4nl table.
basalt_reader.py takes its layout constants and header structs from
basalt's tools/model_file.py, so it now carries basalt's MIT notice and
an adapted-from line, and third_party/BASALT-LICENSE holds the licence.

The fixture holds a few hundred rows of the pack's weights. The pack's
meta section names the Qwen Community License 1.0, whose first
condition asks every copy to keep its notice, so
third_party/QWEN-COMMUNITY-LICENSE holds it: basalt's copy, identical
to the text in meta. NOTICE also records gguf-py's own copyright line.

The reader's docstring now lists every check where it is stricter than
basalt. abbe033's message said basalt refuses a dense.index or
mtp/dense.index row with extra fields. basalt's sscanf and istream
parsers accept those rows; only this reader refuses them.
Review of #6 found that the reader accepted index entries basalt's own
loaders refuse, so a bad entry would be sliced silently from the
padding and index text that follow its section:
- mtp/dense.index entries are now bounded by mtp/dense, as
  MtpDrafter::load bounds them (mtp.cpp:258; hc8_only() is always on).
- Every dense.index row basalt loads (any but an in_gguf one) now gets
  WeightTable::load's checks (weights.cpp:284-386): it names file 0,
  the only file a .basalt pack has; its codes, scales and offset planes
  add up to its sizes, with fp16 scales widened to f32; a promoted
  BF16 or F16 row is 4 bytes per value in and 2 out; and its source
  bytes lie inside dense.
- experts.layout must fill the experts section, or all of it but one
  blob of padding. basalt's default arena source accepts both; its
  --mmap-experts source accepts only the exact total
  (expert_source.cpp:413-416, 1863-1866). This also refuses a layout
  that is missing its last layers.
- The parse functions take their section's size, and BasaltFile passes
  it, so test_basalt_pack.py runs every bound against the real pack's
  section sizes.

Python keeps a negative number negative, but basalt parses offsets and
sizes as unsigned. So the reader refuses a negative offset or size,
which an end-only check would let read backwards into the previous
section. ExpertsLayout refuses an out-of-range or negative layer
instead of wrapping to the last one. A meta tensor without bytes, or
with any other missing field, raises ValueError instead of KeyError.

The refusal test's offset case passed on the size check: it inherited
bytes: 135 from the case before it, so deleting the gguf bound left
every test green. Each refusal case now starts from a fresh, valid
input with exactly one defect and must match its own check's message.
New cases cover the guards that survived deletion and the docstring's
stricter-than-basalt bullets. A pass that disabled each of the 49
guards in turn left none undetected.
7e8b36a's docstring says the reader refuses a negative offset or size.
The code refused only some of them: a dense row's src_off and
src_bytes, and meta's and mtp's offsets and sizes. A dense row could
still carry a negative dst_off, dst_bytes or plane size. For example,
codes_bytes -8 with fp16 scales 8 and offsets 20 still adds up to its
16/20 bytes, so it passed every check. basalt parses those fields
with %llu (weights.cpp:172), so its plane sum wraps to the same
total. It then streams a 2^64 - 8 byte codes plane until its bounds
check refuses the row (weights.cpp:309-363, 383).

- dense.index: a row with a negative offset, size or shape is refused
  as it is parsed. That covers src_off, src_bytes, dst_off, dst_bytes,
  ne0, ne1 and the three plane sizes. basalt's converter writes none
  (tools/convert/model_sections.py:252-269).
- mtp/dense.index: negative rows or cols are refused too. -1 x -64 of
  q8_0 is 68 bytes, so the size check alone let it through.
- meta: every number must be a non-negative JSON integer. basalt's
  Json::u64() returns the magnitude of a negative integer, and 0 for
  a float, bool or string (model_file.cpp:172-197,
  model_file.hpp:76). int() read an offset of 3976.0 as 3976, where
  basalt reads 0. A shape of [-64, -2] matched its 136 bytes. All
  1080 tensors in the official pack's meta are non-negative integers.

Negatives are now refused at parse, so each section bound checks only
its upper end. The tests pin each new guard with an input whose sizes
still add up. A pass that disabled each of the 57 guards and guarded
fields in turn left none undetected.
Under MTL_SHADER_VALIDATION=1 an out-of-bounds store is dropped and
logged on the command buffer's `logs`, while its status stays completed
and its error nil. RunResult.error therefore stayed empty, pytest's
capture discarded the stderr text of passing tests, and the CI lane,
which counts JUnit failures, passed a deliberate out-of-bounds store.

Every completion point now reads the logs after waitUntilCompleted
and appends each report to the error, as "shader validation: <report>":
Queue.run (RunResult.error), Queue.profile (raises), and the host
pump's observe (RunnerStats.error, which stops the pump; Engine.run
raises it). The host stack of the buffer's allocation is cut from each
report, since it is the same nanobind frames for every buffer.

Measured on the M3 Max, 2,000 command buffers each: the logs are
complete when waitUntilCompleted returns, through a plain encoder and
through ICB replay, with or without MTL_SHADER_VALIDATION_REPORT_TO_STDERR
(without it the text goes only to the unified log). Reading the logs
of a command buffer without validation costs a median 83 ns.

tests/runtime/test_shader_validation.py runs the cases in
shader_validation_cases.py (one kernel through each of the three
paths, in and out of bounds) in a pytest subprocess with the variables
set before Metal starts. Captured, with -s, and with the report only
in the unified log, the out-of-bounds cases fail and the in-bounds ones
pass. The lane's own environment, command line and judge() fail the
tier. Against origin/main's runtime, all six cases pass and all four
gate tests fail.
7ee5859 put the reports in RunResult.error, so a test that dropped
the RunResult passed an out-of-bounds store under validation, and the
gate's own queue case could not tell the runtime failing it from the
test checking it. Queue.run now raises the reports, after its
autorelease pool, as Queue.profile and Engine.run already do.
RunResult.error keeps its meaning: the command buffer's own error.
Without validation the logs are empty and nothing changes.

The queue case now drops its RunResult. A module fixture stores out of
bounds at teardown, after every test body: under validation that is a
teardown error, which the lane's judge counts. Captured, with -s, and
with the report only in the unified log, the cases give "3 failed,
4 passed, 1 error", and the lane's judge fails the tier with
"3 failed, 1 errors".
CLAUDE.md sends kernel and emitter changes to "CONTRIBUTING.md test
tiers" for the validation command, and that section did not have it.
It now gives the command and what a report does: the runtime raises it
where the command buffer completes, so the test that ran the kernel
fails whatever it checks and in any capture mode, and a report in a
fixture fails the run. MTL_SHADER_VALIDATION=1 alone is enough;
REPORT_TO_STDERR adds the full text. It also states the limits: MLX's
command buffers are not checked, and on an M3 Max under macOS 27
validation reported out-of-bounds stores but not loads (probes of
const and writable device pointers, 64 B to 4 MiB past the end).
docs/ci.md says the lane's --shader-validation fails a test on a report.
The runtime raises each shader-validation report, but an exception
is only a failure if it reaches pytest. tools/profile_writer.py
catches Exception around its GPU runs and logs "skipped", and an
exception on another thread is only a pytest warning, so a test
could pass with a report printed, in plain pytest and in the lane.

failure() now counts every report in a process-wide atomic, exposed
as _native.validation_reports(); the pump reads every command
buffer's logs, not only until the first failure. tests/conftest.py
wraps each test's setup, call and teardown and fails the phase when
the count grew and the phase did not already fail. Without the
Metal module the count stays 0.

The cases file gains a caught report and one raised on a thread:
under validation both now fail (5 failed, 6 passed, 1 error; without
the conftest they pass: 3 failed, 8 passed, 1 error).
measure() catches Exception around each GEMV geometry, the tile block
and each attention variant, to skip what a kernel refuses. A shader-
validation report is not a refusal, but it was logged as "skipped" or
"tile: not available" and the measurement went on, so a profile could
be written from a kernel that accesses memory out of bounds. The
three handlers now re-raise an error whose text holds "shader
validation:" (a substring: failure() puts the command buffer's own
error first).

Checked under MTL_SHADER_VALIDATION=1 by making each bench call first
store out of bounds through Queue.run: measure() now raises from the
GEMV, tile and attention paths. The tile path runs on this M3 Max; the
old handler logged "tile: not available on this device (shader
validation: Invalid store ...)" and returned.
CONTRIBUTING.md said validation on an M3 Max under macOS 27 reported
out-of-bounds stores but not loads. The probe behind that imported a
runtime without the gate. With this branch's runtime, 8 of 8 out-of-
bounds loads raise (device, constant and threadgroup memory, 64 B to
4 MiB past the end) and 3 in-bounds controls stay clean, so the text
now says validation reports loads and stores in all three spaces.

The command now runs every GPU tier (kernels, runtime, spec, layers,
models), as the lane's --shader-validation does: lithos-ai#92's out-of-bounds
stores were found at the model tier. The text names tests/conftest.py
as the backstop for a report nothing raised, and says that outside
pytest only the raise applies. docs/ci.md now limits its claim to
command buffers the runtime commits and names MLX's as unchecked.
A harness that catches the runtime's error and calls pytest.skip()
or pytest.xfail() raised an outcome exception through the conftest's
wrapper, past the count check, and the next phase's snapshot took the
report in: the test was skipped and the report lost. The wrapper now
catches those two exceptions and fails the phase when the count grew
(it re-raises them when it did not).

The cases file gains a `skipped` path that turns the Queue.run error
into a skip. Under validation: 6 failed, 7 passed, 1 error; with
--noconftest the case is skipped (3 failed, 9 passed, 1 skipped,
1 error). Found by a Codex review of the fix.
A test marked xfail that fails on a raised validation report is reported
xfailed: the conftest backstop only sees reports that nothing raised,
and pytest's xfail marker turns the raised error into an expected
failure. No test is marked xfail, but the test-tiers text said the test
that ran the kernel fails whatever it checks, so it now names the
exception.
Adds docs/design/flash-next.md, the contract every pull request of the
Metal 4 port of basalt's Qwen3.8-Flash-Next engine is checked against,
and its entry in docs/README.md.

- Numerics: the precision of every quantity on the decode path, the
  exactness invariants (window invariance, per-projection kernel choice,
  state commit, per-step values as data, basalt's rounding sequence),
  and how this path departs from the repository-wide contract.
- Acceptance setup: the pinned Q2_0 pack (size, sha256), the wikitext-2
  perplexity gate as basalt-bench runs it, the greedy identity check
  between --spec 0 and --spec 7, and every basalt parity test the port
  carries over, with its criterion quoted from basalt, plus the tests the
  port adds where basalt has no reference test.
- Memory budget on a 48 GiB M3 Max: every allocation class derived from
  the pack and basalt's allocation code, the expert cache and RAM tier,
  and the constraints the Metal port must meet.
…mmvq

The Metal port of basalt's matrix-vector path follows the rounding
sequence nvcc actually emits, not the one the CUDA source suggests.
This page reads it from the sm_120 PTX and SASS of NVCC 13.0, 13.2
and 13.3 (Compiler Explorer, basalt's own per-file flags) for the
native and IEEE q8_1 quantizers, the SwiGLU quantizer and the ten
one-column native_mmvq kernels: every multiply-add that fuses and
with which operands, the .FTZ sites, the division sequences and the
conversions, and the Metal form the port writes at each site.

It settles the scoping report's open sites: Q4_K and Q5_K return
fma(dm.x, sumf_d, -fl(dm.y * sumf_m)) (fused by ptxas, not in PTX);
Q4_0 and Q5_0 take fma(sumi, d8, fl(-k * s8)) before
fma(d, inner, tmp). The native quantizer's amax / 127 compiles to a
multiply by fl(1/127) and xi / d to MUFU.RCP then FMUL.FTZ. The
dataflow of every kernel is the same in the three versions, apart
from where 13.3 applies the quantizers' upper clamp, which gives the
same codes.

Multi-column kernels and the dequantizers follow in later commits.
The exact port of basalt's matrix-vector kernels writes nvcc's compiled
rounding sequence explicitly. kernels/common/basalt_fp.metal holds the
helpers every port kernel shares: flush-to-zero by integer bit tests,
the .FTZ forms of add, multiply, fma, max and abs, the correctly
rounded reciprocal that stands where SASS has MUFU.RCP, basalt's warp
sum and max butterflies on simd_shuffle_xor, and exact integer forms of
__dp4a, __byte_perm, __vsubss4 and the two-16-bit-load word read. The
file starts with #pragma STDC FP_CONTRACT OFF.

tests/kernels/test_basalt_platform.py measures what the port rests on,
in MTLMathModeSafe on this M3 Max: add, multiply, fma and division
round to nearest even (2^20 random inputs plus planted ties); they and
fmax flush subnormal inputs and results to signed zero while fabs keeps
the bits; the pragma stops contraction in a runtime-compiled source
(and safe mode fuses a * b + c without it), told apart the way basalt's
elementwise_parity does; fp16 conversions are exact and round to
nearest even. tests/kernels/basalt_emu.py is the numpy emulation the
bit-for-bit tests compare against, with an fma rounded once through a
round-to-odd float64 sum.

Invariant 5 of the contract now names nvcc's sm_120 PTX and SASS,
recorded in docs/research/basalt-nvcc/, as the authority for fusion,
operand order, flush-to-zero and approximate instructions; maps an
approximate reciprocal or division to a correctly rounded reciprocal
and the same multiply; applies flush-to-zero explicitly; and records the
measured rounding and subnormal behaviour in place of the [H].
kernels/common/basalt_q8_1.metal carries basalt's three q8_1 producers
in the rounding sequence nvcc compiles for them (matvec.md sections
1-3): native_quantize_q8_1 with flush-to-zero abs, max and add, the
scale as a multiply by fl(1/127) and the codes through a correctly
rounded reciprocal where SASS has MUFU.RCP; the shared expert's SwiGLU
quantizer on top of it; and the IEEE quantize_q8_1. This GPU flushes
subnormals, so the IEEE kernel rebuilds amax from bit patterns, adds
and divides on operands scaled by 2^64, and rounds a subnormal scale
by integer division. The native sequence is one device function, for
the fused epilogues other PRs must reproduce byte for byte.

tests/kernels/test_basalt_q8_1.py ports iq_multi_parity's
check_q8_1_finite with basalt's exact-or-near criterion and its three
clamped blocks, compares both quantizers bit for bit with the numpy
emulation on normal data and planted edge blocks (subnormals, a
flushed scale, overflow, NaN), checks the SwiGLU quantizer bit for bit
given the GPU's exponential, and counts how often the quotient through
the correctly rounded reciprocal differs from the correctly rounded
quotient: 25.3% of quotients in their last bit, 3 codes in 2,097,152.
monolith/kernels.py gains the source and params builders.
Checkpoint of run 7's step 3 work so a session end does not lose it: one mmvq source for the ten in-pack types with macros for the type, column count, rows per block and SIMD-group count, its source/params builders, the numpy emulation of the dot products and the first tests. Not yet compiled or run; later commits fix and replace it.
kernels/common/basalt_mmvq.metal is basalt's one-column native_*_mmvq kernels and its native_mmvq_multi_kernel in
one source: the format traits' load/apply split (decode a weight block once, run the format's dot per column),
SIMD-group order for the cross-warp sum and basalt's XOR butterfly, for Q2_0, Q3_K, Q4_K, Q5_K, Q6_K, IQ4_XS,
IQ4_NL, Q4_0, Q5_0 and Q8_0 on GGUF blocks as the file stores them and q8_1 activations as basalt lays them out.
The float steps are the ones nvcc 13.x compiles (docs/research/basalt-nvcc/matvec.md): fma() exactly where SASS has
FFMA.FTZ, with its operands, the rest flush-to-zero adds and multiplies, contraction off. The builders in
monolith/kernels.py give basalt's launches: one column (4 rows per threadgroup for small K), the exact multi-column
layout (1 row, 2 for small K) and the upstream layout the negative control runs; one column is always the
one-column launch, as in basalt.

tests/kernels/test_basalt_mmvq.py ports mmvq_multi_parity (T columns against T one-column calls bitwise, its
upstream-layout negative control, the Q8_0 one-column section against a float64 dot) with basalt's criteria
quoted, adds float64 references under its 1e-4 rule for Q4_0, Q5_0, Q4_K, Q5_K and Q6_K, column invariance for
T = 1..8 in both layouts of every type, and a bit-for-bit comparison with the numpy emulation of nvcc's arithmetic
(tests/kernels/basalt_emu.py). Results on the M3 Max: 47 passed, 0 failed, 0 skipped; under shader validation
57 passed (with the q8_1 and platform tests) and 0 validation reports. NOTICE entries under ggml and basalt.
Section 6 of docs/research/basalt-nvcc/matvec.md: native_mmvq_multi_kernel compiled by NVCC 13.0 and 13.3 with
basalt's flags at two and eight columns, regular and small-K, and in the upstream layout, for the ten types. Per
(column, row) it is the one-column kernel's sequence: the same dot templates, the raw SASS lines at every site
quoted for both versions, the operands traced to their fp16 halves, every add, multiply and FMA .FTZ, and the
cross-warp sum and butterfly counts NCOLS * ROWS * (NW - 1 + 5) adds and NCOLS * ROWS * 5 shuffles. The one
difference, in Q4_0 and Q5_0, is where the negation of fl(k * s8) sits (the front end leaves mul, mul, sub and
ptxas fuses the d8 product), which gives the same bits. The Metal port's shared apply_acc stands for both kernels.
… IQ4_NL, IQ4_XS

iq_parity checks basalt's dequantizers against gguf-py and native_mmvq against a float64 product, 1 to 8 columns.
For this pack's four types it checks, kernels/common/basalt_dequant.metal ports dq_iq4_nl, dq_q3_k, dq_iq4_xs and
dq_q2_0 under dequant_flat_kernel<float> (the Q3_K token embedding's gather shares them). NVCC 13.0 and 13.3 compile
each value to one or two IEEE FMULs with nothing fused or flushed, and no product of an fp16 scale and a small
integer is subnormal, so the Metal multiplies are CUDA's (docs/research/basalt-nvcc/dequant.md).

tests/kernels/test_basalt_iq_parity.py rebuilds tools/iq_fixture.py's fixtures byte for byte (checked against the
files basalt's generator writes; gguf_reference's values equal its reference bit for bit) and applies
iq_parity.cpp:112's criterion: dequant rel 0 for all four, mmvq rel 4.7e-3 to 5.4e-3 against 2e-2, every column
of 2..8-column calls bitwise equal to its one-column call. The byte reader w_u8 moves to basalt_fp.metal so both
kernels share it. Under shader validation the basalt GPU tests give 61 passed and 0 reports.
…at dequant.md

The test body now carries basalt's near rule (iq_multi_parity.cpp:465-466) and its clamp count (:480) where they are asserted, as the mmvq and iq_parity tests do; invariant 5 lists docs/research/basalt-nvcc/dequant.md beside matvec.md. Contract tier with the q8_1 tests: 1159 passed, 49 skipped; hygiene ok.
Review of PR 10 found that this GPU's fmax does not flush subnormals,
contrary to what the test docstring, invariant 5, matvec.md and
basalt_q8_1.metal said. Its comparison treats a subnormal as zero, but
the chosen operand comes back unflushed, and on a tie that is the second
operand. fmin does the same. The one fmax assertion (fmax(s, 0) == +0)
passed only because the zero was the second operand.

test_subnormals_in_safe_mode (renamed from test_subnormals_flush_in_
safe_mode) now asserts each claim on cases that tell it apart:
- input flushes where the exact result is normal: s + m, -s * 2^100,
  s / m and fma(m, 1, s);
- result flushes of normal inputs, both signs: 1.5m - m, -1.5m + m,
  +-m * 0.5, fma(+-m, 0.5, 0) and m / 2;
- fmax and fmin returning the chosen operand unflushed: fmax(s, 0) = +0,
  fmax(0, s) = s, fmax(s2, s) = s, fmax(s, -1) = s, fmax(+0, -0) = -0,
  fmin(s, 0) = +0, fmin(0, s) = s and fmin(-s, 2^100) = -s.

test_ftz_helpers_match_the_emulation compared only add_ftz: mul_ftz and
fma_ftz were weighted by zero, and max_ftz and rcp_ftz were never called.
Each helper now gets its own output column (add, mul, fma, max, rcp and
abs) and is compared bit for bit with basalt_emu. The test plants
subnormal inputs and pairs of them, sums and fma results in the
subnormal range, exact subnormal products beside a normal addend, and
reciprocals that underflow.

Mutants of basalt_fp.metal that the old test let through are now
caught:
- mul_ftz and fma_ftz times 1.5;
- fma_ftz unfused;
- max_ftz as plain fmax;
- abs_ftz as plain fabs;
- rcp_ftz through fast::divide.
Dropping the flush from add_ftz or rcp_ftz stays invisible, because the
hardware already flushes there.

The max_ftz comparison leaves out +0 against -0. The GPU returns the
second operand there and numpy returns +0, and CUDA's FMNMX was not
checked. The port takes max_ftz of absolute values only, so neither
case reaches it. basalt_fp.metal says so.

basalt_emu gains max_ftz, which q8_1_native's butterfly now uses.

test_half_conversions also asserts the 2,048 non-finite fp16 patterns:
infinities convert exactly and NaN stays NaN. Its payload is not kept.

Corrected wording in invariant 5 (flash-next.md), matvec.md Notation and
section 3, and basalt_q8_1.metal. matvec.md also no longer says that the
hardware already matches SASS at every .FTZ site. That is false for the
.FTZ absolute value and maximum, where the helpers do the flushing. No
kernel arithmetic changes: the only float fmax in the port is inside
max_ftz, and the IEEE quantizer's amax is an integer max of bit
patterns.
The port of mmvq_multi_parity's Q8_0 one-column section dropped basalt's
output pre-fills. Basalt fills the one-column output with 0xff and the
two-column output with 0xfe (mmvq_multi_parity.cpp:426-427), so a row
that neither call writes cannot pass `diff == 0` (:461). In the port,
both outputs came from fresh allocations with identical bytes.

basalt_gpu.run gains a fill byte for the buffers it allocates from a
byte count, and mmvq passes it through. Fills used:
- test_q8_0_one_column: basalt's 0xff and 0xfe.
- test_mmvq_multi_parity, its negative control and test_column_invariance:
  multi side 0xff, single side 0xfe. These are a strengthening; basalt's
  main sweep does not pre-fill. 0xff on the multi side is NaN, so a row
  the control's layout leaves unwritten fails the non-finite check
  instead of counting as the control's power.

Checked with a mutant whose store guard skips the last row: all four
tests now catch it. Before, test_column_invariance passed it, because
both sides read the same fresh bytes.

test_column_invariance used n_out 70, which is even. The 2-row layouts
(the multi-column small-K launch) therefore never had a partial last
threadgroup, despite the comment "a row tail for every ROWS". n_out 71
leaves a tail for both 2 and 4 rows.

The four basalt test files: 61 passed, 0 failed, 0 skipped.
Review of PR 10 found four test files carrying basalt or ggml code with
no licence header, provenance line or NOTICE entry, which CLAUDE.md and
CONTRIBUTING.md:54-56 require. tools/ci/hygiene.py does not check
provenance, so it passed anyway. Each file now gets the SPDX and
copyright lines used on test_basalt_iq_parity.py, a provenance line
"adapted from <repo> <path> @ <commit>", and a NOTICE entry:

- test_basalt_mmvq.py ports mmvq_multi_parity.cpp: its cases with scale
  offsets, sane_half, widths, seeds and Q8_0 geometries, compare_q80's
  float64 reference, its output pre-fills and its pass criteria.
- test_basalt_q8_1.py ports iq_multi_parity.cpp's check_q8_1_finite:
  the planted blocks, the host transcription and the pass criterion.
- test_basalt_platform.py quotes and enforces elementwise_parity.cpp's
  contraction criterion. The same rule covers test_basalt_iq_parity.py's
  pass criterion.
- basalt_emu.py has two sources. From basalt: the iteration traits and
  the quantizers' and kernels' arithmetic. From ggml, through basalt:
  kvalues_iq4nl, get_scale_min_k4 and the q8_1 rule. It is listed under
  both sections of NOTICE.

Comments and NOTICE only; hygiene passes.
The correction in f6dd07d left one line of the paragraph past the file's 120-column wrap. Whitespace only.
Add docs/research/basalt-nvcc/experts.md, the authority the Metal port of
native_expert_grouped follows for the Q2_0 / Q2_0 experts (flash-next.md,
invariant 5). It reads every rounding site of the gate/up kernels
(native_gu2_kernel, native_gu_multi_kernel), the SwiGLU product with its
IEEE q8_1 (swiglu_q8_1_entries_pdl_kernel) and the down kernel
(native_down_multi_kernel, 16-lane and generic paths) from the sm_120 PTX
and SASS of NVCC 13.0 and 13.3, compiled on Compiler Explorer with
iq_kernels.cu's own flags (nvcc's IEEE defaults).

The kernels carry no .FTZ. The page shows that no subnormal can reach the
matrix-vector parts or the SwiGLU quotient (every value is a multiple of
2^-48, the quotient is at least 2.6e-37), so Metal's plain operations give
the IEEE result there, and that the SwiGLU product can be subnormal, which
the port emulates.
kernels/common/basalt_experts.metal holds native_expert_grouped's three
dispatches for Q2_0 gate/up and Q2_0 down, in the rounding sequence
nvcc compiles for iq_kernels.cu (docs/research/basalt-nvcc/experts.md):

- basalt_expert_gu: native_gu2_kernel (two rows a SIMD-group, n_embd
  2560) or native_gu_multi_kernel (one row a SIMD-group), macro GU2;
- basalt_expert_swiglu_q8_1: the SwiGLU product with the IEEE q8_1
  store over the call's own entries;
- basalt_expert_down: row_dot_20_sub16 on q8_1 rows staged in
  threadgroup memory at n_ff 640, else row_dot_multi, macro SUB16.

The plan is basalt's, read on the device; grp_ptr becomes byte offsets
into one buffer of blobs. fma() stands exactly at SASS's FFMA sites;
the SwiGLU product, which can be subnormal, goes through a new ieee_mul
(exact integer product of the significands), next to ieee_add.

The Q2_0 decode, the q8_1 word readers, a plain warp_sum and the
IEEE-build __expf move into basalt_fp.metal so native_mmvq and the
experts share one copy; basalt_mmvq.metal now calls them. Builders in
monolith/kernels.py follow basalt's launcher (gu2_usable, d_rows, gy).
The first test builds every variant and checks a call writes finite
rows and leaves the others untouched. NOTICE entries under ggml and
basalt.
A step of the program can pause for CPU work between two of its GPU
passes (HostPoint): the pass ending at a point's publish boundary
signals an MTLSharedEvent, the host waits for it and runs the point's
task, and only then commits the command buffer that starts at the
point's wait boundary, so no command buffer ever waits on the host and a
slow task cannot trip the GPU watchdog (probes/p16_host_handoff: a 5 s
park is killed, 4.5 s survives). Host buffers come from the session by
name and stay resident; ops declare buffers they reach through GPU
addresses; Program.check_host_points rejects any op that races a task.

This is #15, squashed, on top of the upstream copies
of the shader-validation gate (lithos-ai#73) and the
routed-expert grp_ptr table (lithos-ai#77). It also records
host points in docs/design/design.md and constraint 5 of
docs/design/flash-next.md, and adds tools/bench/host_handoff.py, which
measures the runtime's handoff: a median of 136 to 137 us of GPU idle
time per handoff on a 40-core M3 Max.
A read-only Codex review (GPT-6.1-Sol, maximum reasoning) of the merged
host-step runtime reported ten findings; each holds against the code.

- The pump records a command buffer before it commits it: if recording
  threw after the commit, the failure cleanup could miss GPU work in
  flight. encode_segment no longer commits; commit time is now counted in
  RunnerStats.commit_ms, which host steps left at zero.
- Runner.run sets the ring tail under the token mutex, so a drain() on
  another thread cannot interleave with it and deliver a token twice.
- max_tokens counts the tokens taken from the ring during the run; a
  task that called runner.drain() used to keep the count below it.
- set_host_points builds the new schedule beside the old one and swaps
  it in, so an allocation failure leaves the runner as it was.
- Engine.run holds an engine lock across the native run and the
  collection of its tokens and failing task, so a second thread cannot
  clear the first run's tokens in between; a call from another thread or
  from one of the engine's own tasks fails at once.
- Engine.profile also refuses tasks installed directly on the runner.
- A zero-step run reports an earlier host failure (StepState error 4).
- check_host_points refuses a task write that reaches a weights or
  params buffer through another name.
- A CallableTask's exception slot is its own: the comment states that a
  task serves one runner, which Engine guarantees by wrapping each
  callable in a task of its own.

Each fix with a test fails without it on main: the five new tests and the
updated concurrency tests.
A second Codex review of the cross-check fixes found that a
KeyboardInterrupt landing between the lock acquire and the try in
Engine.run left the lock held, so every later run failed with "already
running on another thread". run() now claims the engine inside its try
(_claim, under a guard lock), and the finally releases only its own
claim with attribute reads and a store, between which no interrupt can
land. The new test interrupts run() right after the claim and fails
with the claim moved back outside the try.
A second Codex review found the lock the previous commit introduced
still strandable: on Python 3.14 and later a `with` arms its release
only after __enter__ returns, so a KeyboardInterrupt at that point left
the guard held and every later run blocked, which is worse than the
refusal it replaced.

The claim is now one dict.setdefault, which tests and takes it in a
single call, and run() makes that call inside its try. An interrupt
lands only after a call returns, at a RESUME or at a backward jump, so
a claim the call took is always released by run()'s finally, whose
release is subscripts and an identity test with no call of its own
(checked by disassembly on 3.13, 3.14 and 3.15).

Two tests: one injects a KeyboardInterrupt at every point of run() and
its claim where CPython can raise a pending signal and requires a later
run to still complete; the other requires the claim to hold no context
manager and the release to run no call. The first fails on the
acquire-before-try version, the second on both earlier versions.
The opcode-injection sweep this replaces never injected anything: its
trace function set f_trace_opcodes without activating the frame's
tracing, so all nine of its injection points raised nothing and the
test passed on a design that strands the claim. Its injection points
were also the wrong ones: an exception raised at the instruction after
a call is looked up at that instruction's offset, which for the last
call of the try lies outside the protected interval, where the real
post-call check still sits at the call.

The test now asks the interpreter for the interrupt: it raises SIGINT
inside the claim and inside the run, and the interpreter turns the flag
into a KeyboardInterrupt at its own next check, which is where a Ctrl-C
would arrive. The test requires the interrupt to propagate and a later
run to complete, and it fails when the claim moves back outside the
try. The disassembly test keeps the other half: it rejects a claim held
under a context manager and a release that calls anything.
A detached run inherits SIGINT as SIG_IGN, and Python keeps an ignored
signal ignored, so raise_signal did nothing and the test failed every
run of the verification tiers while passing from a terminal. The test
now installs the default handler for its own duration and restores the
one it found, so it exercises the same path whatever launched pytest.
CodeRabbit found the claim's release still interruptible on Python
3.10, which the package supports and CI tests: 3.10 checks the eval
breaker between ordinary opcodes, so a signal can land between the
identity test and the delete. No pure-Python claim closes that, because
the release itself is more than one instruction there.

The claim is therefore gone. The runner already guards a run with an
atomic hold a second thread cannot enter, so the pump now swaps the
ring's tokens into its own RunnerStats before it returns, under that
hold, and Engine.run reports those instead of draining afterwards. It
also reads the task list before the run, so a reconfiguration cannot
shift the index of the failing task under it. Both windows the claim
was added for are closed by the runner's own hold, and no Python state
is left for an interrupt to strand.

Engine.run from another thread, and from one of the engine's own host
tasks, now meets the runner's refusal rather than an engine-level one;
the concurrency tests assert that, and that the held run still reports
every token the refused caller could not take. A new test reads the
tokens from the pump's stats and requires a later drain to find none.
A read-only Codex review of the previous commit found both of its new
edges.

The pump took the ring's tokens into its stats, which left drain()
empty for the five benchmarks that still collect tokens that way
(tools/bench/dspark_profile.py, dspark_round_latency.py,
dspark_compare_packs.py, profile_spec_round.py). It copies them now:
the stats carry the run's own tokens, read under the runner's hold, and
drain() keeps handing the same tokens to a caller that takes them that
way. The next run clears the list as it always did.

Engine.run read the task list before the native call to keep a
reconfiguration from shifting the failing task's index, but a
reconfiguration between that read and the hold left the engine
reporting the wrong task's exception. The stats now carry the failing
task itself, so no index is resolved against a list that may have
moved.
A review raised that a caller keeping raw RunnerStats after dropping
the runner can have the task's exception collected out from under the
retained task. Engine.run reads it inside the call that returns the
stats; the field now says so.
A task carries one exception slot, so the cross-check's ninth finding
asked that a task serve one runner. That was a comment, and nothing
enforced it: set_host_points took any shared task, so two runners could
install one CallableTask and overwrite each other's cause before either
caller read it.

A task now records the runner holding it. set_host_points claims every
task of the new schedule before it swaps that schedule in, gives back
what it claimed if a later point refuses, and releases the tasks the
replaced schedule no longer uses. A released runner and one that dies
hand their tasks back, so the same task serves the next runner.

Two tests: a second runner is refused while the first holds the task
and takes it once that runner is gone, and a refused call leaves the
runner with no points installed and the tasks it had claimed free.
A schedule may hold one task at several points, so replacing it ran the
release once per point. The clears stored null unconditionally, so a
runner that claimed the task between two of them lost it again.

Every release is a compare-and-clear against the releasing runner now,
in the schedule swap, in release_host_tasks and in the runner's
destructor. The test installs one task at two points, replaces the
schedule, lets a second runner claim it, and requires the first runner
to be refused.
basalt's Q5_K output head (q5k_head.cu, head_proxy.cuh) as Metal kernels in
kernels/common/basalt_q5k_head.metal, each output bit for bit the arithmetic
nvcc compiles for sm_120: the head (1 to 8 columns), its unmapped-row mask,
the top-1 with its cross-threadgroup merge as a second dispatch, and the
2-bit proxy's pack, score and final pass. The Q5_K decode and dot move into
basalt_fp.metal, shared with native_mmvq. Offsets are 64-bit where basalt's
are size_t or int64_t, and the builders refuse what basalt's API refuses.
Research notes: docs/research/basalt-nvcc/q5k_head.md.

The net change of #17 (merge 0844a96).
basalt's routed Q2_0 experts of the drafter (src/core/mtp.cpp:931-935) as
Metal kernels in kernels/common/basalt_s2_experts.metal: moe_group_resident's
plan, quantize_q8_0_scaled and moe_grouped_s2 (gate/up, SwiGLU, the
intermediate's quantizer, down). Both CUDA files build with nvcc's IEEE
defaults; this GPU flushes subnormals, so every rounding site a subnormal can
reach goes through IEEE helpers in basalt_q8_1.metal, and a stored NaN is
sm_120's canonical 0x7fffffff. Indices are 64-bit where basalt's are size_t or
long long, and the builders refuse launches basalt cannot make. Research
notes: docs/research/basalt-nvcc/s2_experts.md.

The net change of #18 (merge d151b0a).
On sm_120 every FADD, FMUL, FFMA, MUFU and division sequence that makes or
passes a NaN stores the canonical 0x7fffffff, and __float2half stores 0x7fff;
this GPU's arithmetic gives 0x7fc00000 and its half() 0x7e00. cuda_nan and
cuda_nan_f16 in basalt_fp.metal rewrite a stored NaN to sm_120's bits and keep
every other value's, and every port kernel applies them at the stores a NaN
can reach (native_mmvq and the q8_1 quantizers, the dequantizers, the routed
experts, the BF16 GEMVs, dense_tc, the Q5_K head, the drafter experts).
docs/research/basalt-nvcc/nan.md records each store with its evidence;
test_basalt_nan.py checks each against a control without the rewrite;
invariant 5 of the port contract states the rule.

The net change of #20 (merge 0d7d491).
BasaltSource (monolith/packs/basalt.py) serves a .basalt file's tensors by IR
name (gguf/<name>, dense/<name>, mtp/<name>, whole sections), each an absolute
byte range with its ggml type and shape, and refuses what basalt does not
load as stored: dense rows it converts or serves from gguf, a slot its source
bytes do not fill, the hyper-connection matrices its kernels read only
through their 8-bit copies, types the format plugins lack, sizes a type and
shape do not give. emit_program takes a source wherever it takes a pack: the
basalt_windows planner maps only the pages the bound tensors touch, in
page-aligned windows inside the file of at most WINDOW_BYTES each, named by a
digest of (path, offset, size), and refuses a binding off a 16-byte boundary.
PackFile programs are byte for byte unchanged. A file-backed buffer that runs
past the end of its file is refused when it is mapped (an fstat guard in
metal_core.mm) rather than faulting on first touch, and the reader's size
check multiplies exactly. A copy test mode gives each tensor an exact buffer
read from the same file.

The net change of #22 (merge e2e0bd5).
monolith/ops/basalt.py registers one op kind per basalt host launcher
(basalt_q8_1 with its native, swiglu and ieee quantizers, basalt_mmvq,
basalt_dense_tc, basalt_dense_tc_pair, basalt_mmvf), so a compiled program
can emit the merged Metal kernels over a .basalt file's weight windows; its
docstring is the contract. monolith/compiler/emit_basalt.py holds their
handlers, merged into emit.HANDLERS: each emits one dispatch whose macros,
grid, threadgroup and params come only from monolith/kernels.py's builders
(basalt_q8_1_grid and basalt_mmvf_grid are new), and checks at emit time
basalt's launcher checks, pointer alignment at every binding, what basalt's
call sites satisfy (contiguous output columns, the IEEE q8_1 rows read only
by the routed experts and never through a view, a weight as shipped rows
whose pack aux entry holds exactly its rows), and refuses a dynamic-T
program. dense_tc keeps the summation order basalt's variant rule picks on
its 170 multiprocessors. Engine now refuses a pipeline whose SIMD-groups are
not 32 lanes and an op whose threadgroup exceeds its pipeline's
max_threads_per_threadgroup, which would not run as encoded.

Tests: tests/contract/test_basalt_ops.py (dispatches against the builders
at T = 1 .. 8, dense_tc's order, each refusal with one defect),
tests/kernels/test_basalt_ops_program.py (static programs at T = 1 .. 8 on
the GPU, bitwise equal to the single-kernel harness and window invariant)
and tests/runtime/test_engine_limits.py.

The net change of #23 (merge e7eb8b4). Its one conflict
was engine.py's imports: the fork's carry field, Callable and Union for the
host-step runtime, which this base lacks; this commit adds only #23's
import math.
The first piece of the expert tiers (OI-007): basalt's act_quant_q8_1 and
q2_0_gguf_rows_multi, the arithmetic basalt runs on the CPU when the GPU
expert cache misses, transcribed from AVX-512 to ARM NEON operation for
operation in runtime/src/basalt_cpu.cpp, with basalt's ActQ, geometry
constants and signatures in basalt_cpu.h. Where a literal transcription
would give other bits, the port writes x86's: the float-to-int conversion
returns the integer indefinite (-127 after the clamp) for a NaN, an
infinity or an overflow where FCVTZS saturates; the horizontal sum and max
trees are written out by hand in GCC's AVX-512 header order, MAXPS's
operand order visible at every node; the file builds with
-ffp-contract=off (runtime/CMakeLists.txt); and a row whose result is a
NaN is recomputed lane by lane under x86's NaN rules. native.mm binds both
kernels and checks dtype, rank, shape, contiguity and every bound (by
division, which cannot wrap) before it releases the interpreter lock.

Tests: tests/kernels/test_basalt_cpu_q2.py against the numpy AVX-512
reference tests/kernels/basalt_cpu_emu.py, x86 golden values and a float64
check through llama.cpp's dequantizer. docs/research/basalt-cpu-q2.md holds
the research the transcription cites; the port contract
(docs/design/flash-next.md) states the quantizer's rule and the CPU tier's
bar; third_party/NOTICE gains three entries.

The net change of #21 (merge 9b255e0). Its one conflict
was runtime/src/native.mm: the fork's includes and the declarations before
NB_MODULE carry the host-step runtime (the Foundation import, <algorithm>,
<memory>, <tuple>, CallableTask and the host-task type slots), which this
base lacks, so this commit adds only #21's lines there.
docs/design/flash-next.md merged clean and likewise gets only its two
changed rows. The other seven files equal the fork's.
…6 output

The net change of #24 (fork merge commit 50a6152), as
one commit on the copy of #21. The fork's native.mm
also carries the host-step runtime, which this base lacks, so this commit
keeps the base's lines there and adds exactly the PR's changed lines.
The net change of #28 (fork merge commit fa10916), as
one commit on the copy of #24. Five of its six files
are byte-equal to the fork's merge; docs/design/flash-next.md carries
the PR's changed lines and differs from the fork only where this base
lacks the fork's later lines.
…, bit for bit

The net change of #29 (fork merge commit 9c83a1a), as one commit on
woodsonl/basalt-hc-copies-upstream.
The net change of #30 (fork merge commit 5f67939), as
one commit on the copy of #28. Eleven of its fourteen
files are byte-equal to the fork's merge. monolith/kernels.py and
third_party/NOTICE carry exactly the PR's added and removed lines, and
docs/design/flash-next.md its changed lines rewrapped; the three differ
from the fork only where this base lacks the fork's later lines (the
prompt path's group dequantizers, #29).
The net change of #31 (fork merge commit 8a7e39f): the
grouped RMSNorm and the n-gram block's gate, broadcast, convolution and
history kernels, the basalt_ple_block and basalt_ple_commit op kinds with
their emitter handlers, and ple_parity's block, key and value checks.
The net change of #32 (fork merge commit 6fac383): Gemm::bf16 and
Gemm::native as basalt_prompt_gemm, one fixed fp32 fma chain per output, and to_f16
and to_bf16 as basalt_prompt_convert, with the prompt family's plumbing (PROMPT_ROWS,
prompt_rows, the op and handler modules, the test harness) and its tests. Applied on
lithos-ai#91's branch; flash-next.md, monolith/kernels.py, tests/kernels/basalt_emu.py and
third_party/NOTICE keep only this PR's own lines where the fork also carries the
hyper-connection write and the n-gram block (lithos-ai#93, lithos-ai#98).
#26's net change is against the fork's main at 6fac383, which
holds #28 to #32. Their copies split at lithos-ai#90:
lithos-ai#91 and lithos-ai#99 on one branch, lithos-ai#93 and lithos-ai#98 on the other. This branch starts from
lithos-ai#99's (woodsonl/basalt-prompt-gemm-upstream) and merges lithos-ai#98's
(woodsonl/basalt-ngram-upstream), so it holds all five.

Five files conflict, each where both sides add to the same lines: the citation
comment in basalt_fp.metal, the NOTICE entries, the authority list in
flash-next.md, and adjacent additions in kernels.py and basalt_emu.py. Each
takes the fork's merged text at 6fac383. flash-next.md keeps this stack's two
lines that differ from the fork: the metal_core.mm:99 citation, and no
invariant 5 of the host-step runtime (lithos-ai#80).

The merged tree differs from the fork's 6fac383 in the same 47 files, by the
same lines, as lithos-ai#89's tree differs from the fork's 50a6152.
#26 emits the Q5_K head's gathered rows, map and 2-bit copy
as buffers of role "host", which the session allocates and passes to Engine,
and its program test checks that Engine refuses a program without them. That
role and its refusal come from the host-step runtime (#15,
here lithos-ai#80), which lithos-ai#99's and lithos-ai#98's branches lack. lithos-ai#82's branch
(woodsonl/host-step-crosscheck-fixes-upstream) holds lithos-ai#80, its review fixes and
the shader-validation gate (lithos-ai#73) under it.

Two files conflict, monolith/runtime/engine.py and runtime/src/native.mm,
where the host-step runtime and the basalt ports change neighbouring lines.
Both take the fork's merged text at 6fac383. The auto-merged
runtime/src/metal_core.mm keeps this repository's include layout, and
docs/design/flash-next.md keeps this stack's metal_core.mm:99 citation.

The merged tree now differs from the fork's 6fac383 in 21 files, none of which
#26 touches: the 40-core M3 Max backend and its tests (lithos-ai#66,
lithos-ai#69), the gqa test's hits buffer (lithos-ai#75), the MoE golden script (lithos-ai#67), the models
doc (lithos-ai#68), the metal_core.mm include layout, and that citation.
monolith/ops/basalt.py registers one op kind per basalt host launcher of the
Q5_K head: basalt_q5k_head (q5k_head_mmvq, then q5k_head_mask_unmapped on
each column when a map is given), basalt_q5k_top1 (the partials, then the
merge) and basalt_q5k_proxy_top1 (the 2-bit score, then the final). Its
docstring is their contract. monolith/compiler/emit_basalt.py emits them in
basalt's launch order, with macros, grids, threadgroups, params and scratch
sizes from monolith/kernels.py's builders only. basalt_q5k_mask_grid and
basalt_q5k_top1_part_bytes are new. Each follow-up dispatch declares what the
dispatch before it wrote, so the barrier pass orders it. The handlers make
basalt's launcher checks at emit time, plus the port's alignment rule.

Graph.input(..., host=True) declares an input whose buffer the session
allocates and passes to every program that binds it: the drafter's gathered
head rows, their map and the 2-bit copy, one allocation for every tier and
width. emit_program gives it role "host" at exactly the value's bytes, which
Engine requires the session to supply. It refuses a host input named after a
StepState field or one of the program's own buffers, since one name cannot
hold both. The accept and confidence logs are assigned rather than set by
default, so that check sees them.

Tests: tests/contract/test_basalt_q5k_ops.py (dispatches against the builders
at T = 1 .. 8, barriers, scratch sizes, and 62 refusals with one defect
each). tests/kernels/test_basalt_q5k_ops_program.py runs static programs on
the GPU over a .basalt file and over the session's host buffers, bit for bit
equal to the single-kernel harness.

The net change of #26 (merge 15d65e4). It applies without
a conflict on this base, which merges lithos-ai#99's, lithos-ai#98's and lithos-ai#82's branches. All
eight files are byte-equal to the fork's merge.
The net change of #35 (fork merge commit 143c09a): the
port contract's invariant 5 transcribes libdevice's exp, logf, expf,
powf, cosf, sinf and log1pf from the PTX nvcc inlines, each approximate
step in them mapped as the invariant maps it, in place of the library
expf's metal::precise::exp; prefill_kernels.md and ple.md record the
choice.
The net change of #25 (fork merge commit cc8aa8e) as one
commit on lithos-ai#101's branch (woodsonl/libdevice-library-math-upstream, the copy
of #35). It applies without a conflict; every file it
touches equals the fork's after the merge, apart from flash-next.md's
metal_core.mm:99 citation, which this stack carries outside the change.

basalt's sampler (src/kernels/cuda/sampler.cu at b4c63b5) as an exact Metal
port: the cluster and one-block greedy picks, the drafter's greedy
top-prob tail, the split and one-block sampled paths with Philox draws on
(seed, absolute position) and the probe, and coupled draft sampling; the
basalt_sample op kind with its mode word and greedy_only build; IEEE
binary32 helpers moved to basalt_ieee.metal, software binary64 and
libdevice's __nv_exp and __nv_logf transcribed; sampler_parity whole,
coupled_parity, decode_cluster_parity's argmax half and the port's own
checks; the bench script, sampler.md and the contract and NOTICE entries.
@woodsonl woodsonl closed this Oct 25, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant