Skip to content

Port basalt's prompt-path GEMMs and 16-bit conversions to Metal: one fixed fp32 fma chain per product output - #99

Closed
woodsonl wants to merge 51 commits into
lithos-ai:mainfrom
woodsonl:woodsonl/basalt-prompt-gemm-upstream
Closed

woodsonl wants to merge 51 commits into
lithos-ai:mainfrom
woodsonl:woodsonl/basalt-prompt-gemm-upstream

Conversation

@woodsonl

Copy link
Copy Markdown

The net change of woodsonl#32 (fork merge commit 6fac383), as one commit on #91 (woodsonl/basalt-prompt-dequant-upstream). Stacked: merge after #91.

basalt's prompt-path products and the conversions that feed them (src/prefill/gemm.cu and src/prefill/kernels.cu at b4c63b5) on Metal: Gemm::bf16 and Gemm::native (the FP16 image from #91's dequantizers, then Gemm::f16) as the op kind basalt_prompt_gemm, every output one fixed fp32 fma chain from +0 in increasing k (cuBLAS fixes no order; the port's is deterministic and independent of the chunk's rows, the tile and the slice); to_f16 and to_bf16 as basalt_prompt_convert, bit for bit; and the prompt family's plumbing every later prompt PR builds on (PROMPT_ROWS / prompt_rows, monolith/ops/basalt_prompt.py, monolith/compiler/emit_basalt_prompt.py, the test harness), with the kernel, program and contract tiers. The fork PR's description has the exactness argument, the test map and the timing.

Four files conflicted (docs/design/flash-next.md, monolith/kernels.py, tests/kernels/basalt_emu.py, third_party/NOTICE), each resolved to this PR's own lines: the fork's main also carries the hyper-connection write and the n-gram block, whose copies are #93 and #98. Ten of the fifteen files are byte-equal to the fork's merge; the other five differ only where this base lacks those two.

Verification of this branch at edb309f (M3 Max, 40 cores, macOS 27.0.1), with BASALT_SRC set to a basalt checkout at b4c63b5:

  • tests/kernels/test_basalt_prompt_gemm.py, tests/kernels/test_basalt_prompt_program.py, tests/contract/test_basalt_prompt_ops.py, test_basalt_prompt_dequant.py, test_basalt_platform.py and test_basalt_nan.py: 307 passed, 0 skipped, plain and under MTL_SHADER_VALIDATION=1 (with -s), 0 Invalid Metal usage lines.
  • Contract tier: 1342 passed, 17 skipped (optional extras), 2 failed: test_streaming_moe_oracle's two cases, this base's own Qwen3MoeRotaryEmbedding device= error (fixed by Build the streamed MoE oracle's rotary table without device= #67).
  • python tools/ci/hygiene.py: ok.

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.
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.
basalt_emu.py gains q2_0_dots (row_dot_multi's order: lane k % 32 takes
call k, fma(fl(d2 * d8), f(sumi), s) from +0, then the 32-lane
butterfly) and swiglu_q8_1 (t, the IEEE quotient and product with
subnormals, the IEEE quantizer), per experts.md.

test_basalt_experts.py ports iq_multi_parity's check_grouped (9 groups
of {1, 3, 4, 5, 0, 8, 2, 11, 1}, 8 tokens, spare grid rows and cap
entries, NaN rows) and native_grouped_parity at 512 x 256 and, as its
--gu2 run, 2560 x 640 (plans from entry 0 and 7, grid_groups 0..4 and
cap + 3, stale scratch). Each comparison basalt makes between two of its
own kernel variants becomes the grouped call against the same kernels
one entry a call, every float compared; the two gate/up kernels and the
two down trees are also compared with each other, and every stage of
every call is checked bit for bit against the emulation, with the
exponential taken from the GPU's expf_neg.
test_ieee_mul_keeps_subnormals checks ieee_mul against numpy's IEEE
float32 product on 65,610 pairs, 13,643 of them subnormal: the 2^-126
boundary, grid ties, products below half the smallest subnormal, signed
zeros and subnormal operands. test_swiglu_q8_1_edges runs the SwiGLU +
q8_1 dispatch alone on very negative gates with small up values (211
subnormal products), overflowing exponentials, large and zero gates and
the GEMV's 2^-48 grid, bit for bit against the emulation, and checks it
leaves the q8_1 blocks outside the call's entries untouched.
test_stages_against_float64 holds each stage of check_grouped's call
(gate and up on the tokens' q8_1 rows, down on the GPU's q8_1 of the
SwiGLU product) to iq_multi_parity's check_mmvq bound, rel < 1e-2, over
the GPU dequantizer's weights and the dequantized q8_1 rows (measured
6.7e-8). test_whole_expert_against_float64 is the contract's reference
for native_expert_grouped: the whole expert on fp32 activations, built
as native_expert_parity.cpp builds it, with its criterion eg < 3e-2
(measured 1.26e-2). Both cross-check the dequantizer against gguf-py's
dequantize_row_q2_0.
flash-next.md's invariant 5 lists experts.md with matvec.md and
dequant.md. experts.md states that 13.0 has the SwiGLU kernel's SASS
lines as quoted, that native_down_multi_kernel<42, true> and <42, false>
have identical template multisets in each version, and which tests check
the page.
basalt's native_grouped_parity --gu2 run checks native_gu2_kernel against
v1, whose gate/up takes native_gu_multi_kernel. The 2560 x 640 port now
takes its per-entry comparand on the one-row kernel too, so all 84 calls
(both plan bases, every grid_groups, stale scratch) cross the kernel
switch. test_stages_against_float64 also holds each entry, not only the
call, to rel < 1e-2 (worst entry 7.45e-8).
ieee_mul stands in for basalt's __fmul_rn (mul.rn.f32, SASS FMUL) in
the SwiGLU product. A zero operand returned its signed zero before any
check for exponent 255, so NaN * 0, inf * 0 and their mirrors came out
as +-0 where CUDA gives NaN, and inf times a subnormal went through the
integer rebuild. A NaN or inf fp16 scale in an expert's gate or up rows
reaches it: basalt's down output is NaN, the port's was zeros. An
operand with exponent 255 against a zero or a subnormal (the only case
the hardware product cannot serve, since it flushes the subnormal) now
returns CUDA's canonical NaN 0x7fffffff for a NaN or a zero operand and
the signed infinity otherwise.

test_ieee_mul_keeps_subnormals plants 0 * inf, NaN * 0, inf and NaN
against subnormals, and its grid ties are now ties: the factor 2^-75
makes the products (k + 0.5) 2^-149 (the old 2^-74 gave odd multiples
of 2^-149, all exact); the test counts 68 ties. test_swiglu_q8_1_edges
plants five NaN products in one block and a whole block of inf * 0
inside the dispatched entries and compares their q8_1 bytes with the
emulation, a NaN half as NaN (test_basalt_q8_1's convention). Both tests
fail on the previous ieee_mul and pass on this one.
test_whole_expert_against_float64 took its float64 weights from
basalt_dequant_f32, which reads each block scale through basalt_fp.metal's
h2f, the helper the kernel under test reads its scales through. The
contract's reference for native_expert_grouped dequantizes Q2_0 by the
host codec, as basalt builds G, U and D with ggml's to_float
(native_expert_parity.cpp:56-61). G, U and D now come from
tests/contract/gguf_reference.py's port of dequantize_row_q2_0, the
decode tools/gguf_writer.py's dequantize_q2_0 mirrors, and the 64-row
cross-check, which would now compare the codec with itself, is gone.
The host and GPU matrices are bitwise equal for this blob, so eg is
1.26e-2 as before.

per_entry kept only row ent_dst[e] of each single-entry call, so a
stray store by the comparand to another row went unseen; basalt diffs
the whole buffer (native_grouped_parity.cpp:226-234). Each call must now
leave every other row as the 0xFF pattern.

The basalt citations now point at the cited lines at b4c63b5:
random_rows (iq_multi_parity.cpp:72-90, native_grouped_parity.cpp:73-98),
the slot (:118), plan_sizes (:164-188), check() (:219-248), the
pre-fills (:309-310), dequant_q8_1 (:99-109), and check_grouped's
plan (:254-264, :321).

test_basalt_experts.py under MTL_SHADER_VALIDATION=1: 9 passed,
0 failed, 0 skipped, no validation reports.
experts.md said no instruction of these kernels carries .FTZ. The SASS
dumps hold 32 .FTZ-flagged instructions each, all inside the four copies
of div.rn.f32's slow-path subroutine __cuda_sm3x_div_rn_noftz_f32_slowpath
(compares against infinity, the NaN-propagating add, and a negation and a
compare on operands scaled into [1, 2)); the PTX has no .ftz. The page now
says so; the quotient is div.rn.f32's, IEEE's, so the Metal mapping is
unchanged. The down table's 13.0 call-t cell gains the FMUL R14, R14, R17
that forms d2 * d8 ahead of the FFMA (down16.nvcc130.sass:313). The
SwiGLU notes and the test summary now cover ieee_mul's non-finite cases.

NOTICE: basalt_fp.metal's own entry now names iq_kernels.cu for
Split<42>'s Q2_0 decode, the IEEE-built warp_sum and expf_neg, instead of
basalt_experts.metal's entry carrying that provenance; basalt_emu.py's
entry covers q2_0_dots and swiglu_q8_1, the routed experts' arithmetic.
The compare among the slow path's .FTZ instructions (FSETP.NEU.FTZ on
the FFMA.RP and FFMA.RM roundings) acts on the quotient of the two
rebiased operands, which lies in (0.5, 2), not [1, 2). experts.md now
says the negation and the compare act on values the subroutine has
scaled away from the subnormal range, which holds for both.
basalt_expert_gu and basalt_expert_down read each group's blob through
basalt's grp_ptr: buffer(1) is now a table of 64-bit GPU addresses (a
struct holding a device pointer, one a group, each 2-byte aligned and
inside a resident buffer), where it was byte offsets into one blobs
buffer at buffer(0). The expert cache is 33,973,862,400 bytes, above
maxBufferLength (30,150,672,384), so its slots span at least two
buffers, which one-buffer offsets cannot reach. The arithmetic is
unchanged.

Dispatch.use(buffer) makes a buffer a kernel reaches only through a GPU
address resident for that dispatch (useResource, read) in Queue.run and
Queue.profile. The test harness builds the table from the blob buffers'
GPU addresses and declares them; a new test moves a call's blobs into
two separate buffers and gets the same bits.
docs/research/basalt-nvcc/bf16.md reads bf16_gemv_fp32_mmvf, its multi-row kernel and the _cols launcher
from NVCC 13.0, 13.2 and 13.3's sm_120 PTX and SASS (basalt's flags for native_bf16.cu, --use_fast_math
included): two ordered FFMA.FTZ per bf16 pair, the FADD.FTZ XOR butterflies, the zeroed 32-slot block
stage, and per token the one-row sequence in the multi kernel. It is the authority the Metal port of
these kernels follows, so invariant 5 of flash-next.md now lists it with the other basalt-nvcc pages.
kernels/common/basalt_mmvf.metal is one source for bf16_gemv_fp32_mmvf (NT 1) and its multi-row kernel
(NT 4 or 8), in the sequence bf16.md reads from nvcc: per bf16 pair two ordered fma_ftz from +0, the
warp_sum_ftz butterfly, and above 32 threads the zeroed 32-slot block stage. monolith/kernels.py gets the
source, macro, params and _cols chunk builders, reproducing basalt's mmvf_block_size, its one-row routing
(n_tok 1 with ldy >= n_out) and its checks. tests/kernels gets the single-kernel runners (one call, and
_cols as offset-bound dispatches in one command buffer) and a numpy emulation of the sequence.

Work in progress: the parity tests follow in the next commit.
tests/kernels/test_basalt_mmvf.py carries route_window_parity's projection half (2560 to 256 and 1, plus
the contract's 2560 to 128 and 512, T = 2, 3, 4, 6, memcmp) and ple_parity's native PLE value check as a
standalone float64 test for the one-row and multi kernels (le(rel, 2e-6), no non-finite, separation above
1e-5 from BF16-rounded activations). New: bitwise column invariance (multi at T = 1..8, _cols at 9 and 17,
one row with ldy < n_out, strided rows with untouched gaps) at block sizes 32, 96 and 256; the kernel bit
for bit against the numpy emulation of bf16.md at five block sizes; each .FTZ site planted to give +0.
NOTICE, the emulation's header and the builders' section name native_bf16.cu and ggml's mmvf.cu.
The per-function table's FFMA.FTZ column counts the unrolled loop bodies; the sentence under it now says
which copies make up the one-row and the four-token totals, read from the 13.2 SASS.
PTX defines fma.rn.ftz.f32 (and mul.rn.ftz.f32) as the exact result rounded to
single precision, then a subnormal result flushed, so an exact value in
[2^-126 - 2^-150, 2^-126) gives the smallest normal 2^-126. This GPU's fma and
multiply flush on the exact value, before rounding, and return the zero of its
sign there; the explicit ftz() wrappers never saw the rounded 2^-126. Review
of #13 found it at the MMVF kernel's FMAs (R1: exact 2^-126 - 2^-151 gave +0,
the emulation 0x00800000); a sweep of 2^20 fmas and 2^19 products around
+-2^-126 found 40529 and 26053 such results.

fma_ftz now checks a zero from nonzero flushed factors against the exact
value, in integer units of 2^-150, and returns +-2^-126 when it rounds there;
mul_ftz is fma_ftz(a, b, -0). Both now match the emulation on that sweep. The
fix reaches every port kernel that includes basalt_fp.metal (mmvq, the q8_1
quantizers, the routed experts, mmvf). add_ftz is exact below 2^-126 and no
float's reciprocal lies in the interval, so the other helpers are unchanged.
The emulation already rounds to the float32 grid with its subnormals and
flushes after, as PTX defines fma.rn.ftz.f32 and mul.rn.ftz.f32; its
docstrings now say so, the tie 2^-126 - 2^-150 to 2^-126 included.

- test_basalt_platform: test_subnormals_in_safe_mode records that this GPU's
  multiply and fma return +0 for an exact 2^-126 - 2^-151; the helper test
  plants products and fmas within 40 * 2^-152 of +-2^-126 (c zero, normal, or
  of either sign) and named cases: the tie, its neighbours, a 2^-252 product
  beside +-2^-126 and an exact cancellation, with their expected bits.
- test_flush_to_zero: R1 at a pair's first FMA, the second FMA from a normal
  accumulator and its negative, and the tie, on the one-row and the multi
  kernel, all 0x00800000 (0x80800000). The IEEE guard is now the emulation
  without flushes (emu.mmvf(flush=False)) instead of a float64 product: the
  pairs (0, 1) and (1, 3) are zero in IEEE float32 too, so they are dropped,
  and the docstring names the pair that covers each .FTZ site.

With the original one-line fma_ftz and mul_ftz, both
test_ftz_helpers_match_the_emulation and test_flush_to_zero fail.
bf16.md said the explicit flushes make the MMVF kernel independent of the
GPU's subnormal handling, and matvec.md that the hardware does what SASS does
at the .FTZ multiplies and fmas. Neither held: this GPU's multiply and fma
flush on the exact value, so a result that rounds up to 2^-126 came back as
zero. State PTX's rule (round to single precision, then flush a subnormal
result), the measured hardware behaviour, and what fma_ftz and mul_ftz now do
about it, in bf16.md, matvec.md's Notation and invariant 5 of flash-next.md.
bf16.md also records that the rule rests on the PTX ISA's wording, not on a
run on Blackwell.
The net change of #14 (its nine commits and its
merge of the fork's main, which already carried the BF16 GEMVs this
branch stacks on), as one commit: basalt's dense_tc and dense_tc_pair
for Q2_0, Q3_K, Q4_K, Q5_K, Q6_K and IQ4_XS in each summation order its
variant rule can pick, with the rule evaluated at basalt's 170
multiprocessors; the nvcc research page; the builders; the ported
dense_tc_parity tests, a float64 reference per type and a bit-for-bit
numpy emulation; and iq4_table_lookup and vsub4 moved into
basalt_fp.metal for native_mmvq and dense_tc to share.
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 #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).
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