Repository navigation
Conversation
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.
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 #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.
This was referenced Oct 24, 2026
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
The net change of woodsonl#26 (fork merge commit 15d65e4), as one commit on #99 (
woodsonl/basalt-prompt-gemm-upstream) merged with #98 (woodsonl/basalt-ngram-upstream) and #82 (woodsonl/host-step-crosscheck-fixes-upstream). Stacked: merge after #99, #98 and #82 (#82 carries #80 and #73).No single copy branch holds what the fork's main held under woodsonl#26 (6fac383). The copies of woodsonl#28 to woodsonl#32 split at #90, with #91 and #99 on one branch and #93 and #98 on the other. This PR's host inputs also take role
"host": the session allocates their buffers, andEnginerefuses a program without them. That handling comes from the host-step runtime (woodsonl#15, here #80), and this PR's program test checks the refusal. The runtime's review fixes (woodsonl#19) are #82, which also holds #80 and #73's gate. So the branch starts from #99's and merges two branches before the PR's commit:docs/design/flash-next.md,kernels/common/basalt_fp.metal,monolith/kernels.py,tests/kernels/basalt_emu.py,third_party/NOTICE), each where both sides add to the same lines. Each takes the fork's merged text, except thatflash-next.mdkeeps this stack'smetal_core.mm:99citation.monolith/runtime/engine.py,runtime/src/native.mm), each resolved to the fork's merged text.The merged tree differs from the fork's 6fac383 in 21 files, none of them this PR's. They are the files of copies outside this stack (#66, #67, #68, #69, #75),
runtime/src/metal_core.mm's include layout and that citation. The net change then applies without a conflict, and all eight files are byte-equal to the fork's merge.Verification of this branch at f3476e3 (M3 Max, 40 cores, macOS 27.0.1), with
BASALT_SRCset to a basalt checkout at b4c63b5 andBASALT_PLE_FIXTUREat the two fetched byte ranges, the native module built in the worktree (is_available()True):tests/contract/test_basalt_q5k_ops.py: 83 passed.tests/kernels/test_basalt_q5k_ops_program.pyunderMTL_SHADER_VALIDATION=1 MTL_SHADER_VALIDATION_REPORT_TO_STDERR=1with-s: 20 passed, 0Invalid Metal usagelines.tests/kernels/test_basalt_*.pyandtests/runtime, run the same way: 865 passed, 0 skipped, 0Invalid Metal usagelines. Fail a GPU test on a shader-validation report #73's gate is in this base, so a report would also have failed its test.test_streaming_moe_oracle's two cases, withTypeError: Qwen3MoeRotaryEmbedding.__init__() got an unexpected keyword argument 'device'. They fail the same way on the base without the change (1208d58), and Build the streamed MoE oracle's rotary table without device= #67 fixes them.python tools/ci/hygiene.py: ok.OI-013 PR 3: basalt's Q5_K head as ops. Built as
.context/basalt-port/oi013-scope-repo.md§6 "PR 3" specifies it, using the mechanics of §4.1-4.5 and §5.1-5.2, plus the PR 3 item ofoi013-scope-basalt.md§6. It follows the patterns of PR woodsonl#23.What
Three op kinds, one per basalt host launcher. They are registered in
monolith/ops/basalt.py(so the coverage guard sees them), with their contract in its docstring. Handlers inmonolith/compiler/emit_basalt.pyemit them in basalt's launch order:basalt_q5k_headq5k_head_mmvq(+q5k_head_mask_unmappedper column with a map,mtp.cpp:1024-1025)basalt_q5k_top1q5k_head_top1: the partials, then the mergebasalt_q5k_proxy_top1(attrsn_rows,n_cap)q5k_proxy_top1: the score, then the finalBuilders only. Macros, grids, threadgroups, params and scratch sizes come from
monolith/kernels.py's builders. This PR adds two builders:basalt_q5k_mask_grid(q5k_head.cu:406-408) andbasalt_q5k_top1_part_bytes(12 bytes per threadgroup). Nothing is derived from the profile's crew or core count.The top-1's grid. It is computed once, with basalt's constants (170 multiprocessors x 2, capped at 4096). It is the first dispatch's grid and the merge's
n_blocks, so the probability sums in basalt's order.No map. Without a map, a 4-byte dummy buffer fills the map slot (
has_map0), as the harness does (tests/kernels/basalt_gpu.py:304-308).Checks, at emit time:
1 <= n_rows <= n_cap(the builder's check)q5_kweight, or a hostu8input of rank 2 and whole Q5_K blocks, holding the rows read; a pack entry must be exactly those rowsq5k_proxy_bytes(n_cap)bytesemit_program, for every program: no host input named after a StepState field (an input of a field's name binds that field), and none named after one of the program's own buffers (StepState, the token ring, a weights window), since one name cannot hold both buffers; and, once every handler has run, none whose name a buffer the handlers created took (a params record, a scratch arena, the accept log, the confidence log)Provenance lines and
third_party/NOTICEentries cite the transcribed launcher checks (q5k_head.cu:372-374,:406-408,:411-412,:516-518) and the per-column mask (mtp.cpp:1024-1025).Barriers. Each follow-up dispatch (each mask, the merge, the final) reads what the dispatch before it wrote. Those dispatches declare the writes in
writes=, soplace_barriersgives the follow-upbarrier_before. No new mechanism.Host inputs.
Graph.input(..., host=True)declares an input whose buffer the session allocates and passes to every program that binds it. The emitter gives it role"host", whichEnginealready requires the session to supply (PR Let a step pause for host work between GPU passes woodsonl/mlxstream#15), and sizes it at exactly the value's bytes: a session buffer needs at least those bytes, with no 16-byte floor, so basalt's exact allocations (map.size() * 4,mtp.cpp:656) are taken. The program's own buffers keep the floor. The gathered head rows, their map and the 2-bit copy are host inputs. One allocation serves every draft-head program: one per tier and width, as basalt'sround_exec_[tier][T].The pack is not an op.
q5k_proxy_packruns at load and at every flush, outside basalt's graphs (mtp.cpp:680,:1439-1452). Lane G's session code issues it as a direct dispatch. This PR proves the copy that dispatch makes: the GPU test packs with the harness's own direct dispatch, at load and again at a flush (row0 > 0), and scores the copy after each.Why
OI-013 runs the merged basalt kernels as compiled static programs, one per window width, as basalt captures one graph per width. The Q5_K head is the first family with several dispatches per launcher. One handler per launcher keeps their shared invariants (the merge's partial count, the scratch layout, the barriers) out of every model's lowering (§4.1). The port contract (
docs/design/flash-next.md) requires each kernel bitwise equal to basalt's reference. The GPU tests compare each program's output with the merged single-kernel harness on the same bytes.Tests
tests/contract/test_basalt_q5k_ops.py(83 tests, no GPU):barriers="minimal", afterplace_barriersand the backend's finalize: each mask, merge and final carriesbarrier_before, and the first dispatches do not.n_blocksequals the first dispatch's grid (340, 125 and 1 at 4000, 1000 and 8 rows), with and without a map.tests/kernels/test_basalt_q5k_ops_program.py(20 tests, GPU, under shader validation). Synthetic Q5_K rows at n_in 2560, rescaled asq5k_head_parity.cppdoes, with planted rows. Static programs over a.basaltfile, bound both through its windows and as exact per-tensor copies:q5k_proxy_bytes(1)): the proxy top-1, the top-1 with the map and the masked head at T = 2.Every output is bitwise equal to the harness (
basalt_gpu.py:311-368,:386-448). The draft programs run at load and again after a flush. The flush gathers four tokens into context rows, packs the copy atrow0= 3000 on top of the load's pack, and updates the map. Each program scores equal to the harness after each, and the flush moves its pick to the planted token. Every program run twice gives identical bits.Negative controls (mutation run)
Every emit-time check, and each sub-condition of a compound check, has a negative control: with it removed, its own test fails. The set at c67c928 is 63 mutations, one per check or sub-condition, each run in its own scratch tree. Result: 0 not as expected, and the unmutated baseline of the 78 tests the mutants name passes. Four mutants are GPU mutants:
The earlier set (47 mutations at 7c10704, all caught) removed each compound condition whole, so it never removed a sub-condition alone. Review fix 1 below lists what that missed. That set's earlier run reported 9 misses because four runs shared one scratch tree; rerun one at a time, all 9 failed their tests. The GPU fixture's top-1 read was also fixed to read each workspace whole (27e02f5).
The program-buffer guard (b6b930e, review fix 6) has its own controls, each a tree of its own running the q5k contract file: with the guard removed (721f5f1's
emit.py), its three twins fail with DID NOT RAISE and the other 76 tests pass; with only the name term removed (v.name in (program.step_state, program.ring)), thestep_stateandringtwins fail, because StepState's and the ring's specs are set after the input loop; with only theprogram.buffersterm removed, the window twin fails. The unmutated tree passes all 79.Review fixes
Two reviews of 2794a74 raised one blocking finding and five minor ones. Two of the minor ones are the same hole, one found by each review. All are fixed. Against 4162681 (2794a74 merged with main; the merge changed nothing under monolith/, the Metal kernels or the GPU harness), the new tests fail: the contract file 4 failed, 72 passed; the GPU file under shader validation 1 failed, 19 passed.
n_capan int, and five sub-conditions ofq5k_head_supported: n_in > 0, 64 blocks, a column, 8 columns, staging. The one twin of 16 columns could not separate them. Its 16 x 80 x 96 = 122,880 staging bytes also break the 96 KiB rule, so with the column cap removed it was still refused, with the same message.n_capmissingq5k_head_supportedas four twins: 9 columns (69,120 staging bytes, so only the cap refuses them), 0 columns, 65 blocks, and 3 columns of 64 blocks (staging only)shape[1] < 1term is deleted. Each op refuses rows of no blocks with its own check:_Ctx.bufbinds an input named after a StepState field (tokens=pending_tokens) to that field.emit_programgave role"host"only to the other inputs.draft_tokenstherefore bound the 176-byte StepState at byte 64. Engine never required the session's buffer, and the head read its 112,640 bytes of rows from there.emit_programnow refuses a host input whose field name is a StepState field, once for every op: "the host input 'draft_tokens' is named after StepState's 'draft_tokens'; a host input binds the session's buffer of its name".Graph.input's docstring states the rule.draft_tokens, andtokensforpending_tokens) fail at 2794a74 (DID NOT RAISE). A guard without thetokensalias fails the second.map.size() * 4,mtp.cpp:656).test_host_inputs_are_sized_exactlyfails at 2794a74: dvocab 16, not 4.test_one_row_on_exact_session_buffersputs one draft row on session buffers of exactly 1,760, 4 andq5k_proxy_bytes(1)bytes. The proxy top-1, the top-1 with the map and the masked head at T = 2 are bit for bit the harness's. At 2794a74 Engine refuses the buffers: "host buffer dvocab: 4 bytes, program needs 16". A mask that reads one id past the rows is a shader-validation report in this test.test_verify_head_window_invariancechecks both the file's windows and exact copies: column j of each width's logits (T = 1..8) is bit for bit the 1-wide program's on column j alone, as PR Emit basalt's single-dispatch GEMVs and q8_1 quantizers as ops (OI-013 PR 2) woodsonl/mlxstream#23'stest_window_invariancechecks. A kernel mutant that moves column 0 with the width also moves the harness at that width. It still passestest_verify_head_is_the_harnessandtest_file_programs_run_twice_alike, and fails the new test at (T 2, j 0).emit_basalt.py's provenance line and its NOTICE entry listsrc/core/mtp.cpp:1024-1025, the per-column mask loop.verify.cpp:1935-1936, theq5k_head_mmvqcall) instead of the private label H3.q5k_head_parity.cpp:291-292addsalpha * dq).mtp.cpp:676-678), not only its size (:676).A recheck of 721f5f1 found fix 2 incomplete: a host input named after one of the program's own buffers, rather than a StepState field, still bound that buffer. b6b930e closes it:
Graph.input(..., host=True)namedstep_stateorringpassed the input loop, andemit_programthen replaced its host spec with the program's own (emit.py:1501-1502at 721f5f1).program.buffers, which holds the windows by then.Graph.input's docstring states the rule.step_state, namedring, and named after the window that the verify head's rows bind, beside the verify head. All three fail at 721f5f1 (DID NOT RAISE); Negative controls covers each term of the guard.accept_logandconf_log, which a speculative program's handlers added withsetdefault(emit.py:1348,:1359at be06f95; the host spec stayed, so the ops wrote their full logs into the session's buffer), and the generated params and workspace records (params.…,ws.…). Fix 7 closes those. A value that is not a host input but is named after a window,step_stateorringstill collides; that is not closed here.CodeRabbit's review of be06f95 (comment 4367884007) reached those siblings from a graph. c7cc401 closes them for host inputs:
ctx.paramsandctx.scratchreplaced the host spec, so the op bound the program's own buffer as its rows. An emit-only probe at be06f95: host rows namedparams.S2.basalt_q5k_head.0bound the head's 16-byte params record, andws.T2.basalt_q5k_top1.part.1the top-1's 96-byte partials arena, both in place of 112,640 bytes. The accept scan and the verify select adopted a host input namedaccept_logorconf_logthroughsetdefaultand bound it at slot 4, the log they write.emit_programrecords each host input's spec. After every handler and the tail have run, it refuses the program if the buffer of that name holds any other spec, and the message names the input and what took its name: "the program's params record took the name of the host input 'params.S2.basalt_q5k_head.0'; a host input binds the session's buffer of its name" (or a scratch arena, the accept or confidence log, StepState, the token ring). The two log handlers assign their spec instead of usingsetdefault, so a log replaces the host spec and the check sees it. One check after the handlers covers every handler, a chip backend's included. Fix 6's guard stays: a window exists before the loop, so a host input of its name overwrites the window's spec, and only that guard sees it.Graph.input's docstring lists the buffers.setdefaultrestored in one log handler, only that log's twin fails. With fix 6's program-buffer block removed, the window twin fails (DID NOT RAISE), and thestep_stateandringtwins fail because the end check refuses them with its own message instead. The unmutated tree passes all 83.The branch merges origin/main twice:
50a6152 (4162681: PR Port basalt's Q2_0 CPU expert kernels to ARM NEON woodsonl/mlxstream#21's CPU Q2_0 kernels and PR Port basalt's CPU SwiGLU and glibc expf, held against its recorded x86 output woodsonl/mlxstream#24's CPU expf).
git merge-tree --write-tree 2794a74 50a6152reproduces the merge's tree exactly, so that merge needed no resolution.6fac383 (be06f95: PRs Build basalt's int8 hyper-connection copies on the host (OI-005 family 1, PR 1) woodsonl/mlxstream#28 to Port basalt's prompt-path GEMMs and 16-bit conversions to Metal: one fixed fp32 fma chain per product output woodsonl/mlxstream#32, which add the int8 hyper-connection copies and
basalt_gr_post, the group dequantizers, the n-gram block's decode path, and the prompt-path GEMMs and 16-bit conversions).emit.pyandkernels.pymerged cleanly. Three files conflicted where both sides added code next to each other, and the resolution keeps both sides whole:monolith/compiler/emit_basalt.py: main's handlers (_gr_post,_ple_block,_ple_commit) where main has them, then this PR's Q5_K section unchanged, including_q5k_rowsand its row-count check. One handler table holds both sides' kinds. The module docstring names both multi-dispatch cases. The provenance comment cites both sides' sources, including this PR'sq5k_head.cu:372-374,:406-408,:411-412,:516-518andmtp.cpp:1024-1025.monolith/ops/basalt.py: both registrations. The docstring's summary names the GEMVs, quantizers, Q5_K head and hyper-connection write; main's alignment paragraph comes first, then this PR's Q5_K paragraphs.third_party/NOTICE: this PR'skernels.pyQ5_K entry, then main's n-gram entry, and oneemit_basalt.pyentry citing both sides' sources and checks. It has 78 entries (the base's 58, this PR's 1, main's 19), none twice.In the three files, every line either parent added since 50a6152 is in the merge, except the lines the resolution rewrapped: the two docstrings' summaries, the provenance comment, the table's last line and the
emit_basalt.pyNOTICE entry, whose text the merged versions carry.Verification
The full chain ran at c7cc401: review fix 7 on be06f95.
MTL_SHADER_VALIDATION=1 MTL_SHADER_VALIDATION_REPORT_TO_STDERR=1, and_native.validation_reports()= 0 in every tier.emit.py,core/ir.pyand the q5k contract file).is_available()is True. No tier had a failure or an error.BASALT_PLE_FIXTUREnamed the n-gram block's two real-weight ranges, the files PR Port basalt's n-gram block decode path to Metal (OI-005, family 4, PR 1 of 2) woodsonl/mlxstream#31 fetched (20,684,800 and 13,312,000 bytes), so main's n-gram tests ran too. Without it, the contract tier gives 1527 passed and 21 skipped, and the basalt tier 751 passed and 18 skipped; the extra skips are all those tests.python tools/ci/hygiene.pytests/contract(withBASALT_SRC,BASALT_PLE_FIXTURE)tests/contract/test_basalt_q5k_ops.py(in that tier)tests/runtimetests/kernels/test_basalt_*.py(withBASALT_PLE_FIXTURE)tests/kernels/test_basalt_q5k_ops_program.py(in that tier)tests/kernels+tests/spectests/layers+tests/modelsThe contract tier's 1531 are be06f95's 1527 and fix 7's four twins. The basalt tier's 769 are 721f5f1's 443 and the 326 that main's PRs woodsonl#28 to woodsonl#32 added.
Not verified
emit_programnow refuses that input._Ctx.buf,emit.py:201-205); a host input whose name a buffer the handlers create takes is refused at emit time (review fix 7). OnlyGraph.inputsetsis_host, and the handler refuses a copy that is not a host input..basaltfile's head: the tests use synthetic Q5_K rows at n_in 2560.tests/layersandtests/models: 19 skipped as listed.