diff --git a/docs/README.md b/docs/README.md index bd4aeac3..8c90b94e 100644 --- a/docs/README.md +++ b/docs/README.md @@ -11,6 +11,7 @@ These documents describe the current architecture, implementation contracts, and | [Serving](design/serving.md) | Startup, request execution, protocol adapters, prefix caching, and streaming | | [Model adapters](design/models.md) | Checkpoint interpretation, supported model structures, and numerical conventions | | [Extension contracts](design/extensions.md) | Interfaces for models, formats, operations, drafters, and chip backends | +| [Flash-Next port contract](design/flash-next.md) | Numerics, acceptance setup, and 48 GiB memory budget for the Metal 4 port of basalt's Qwen3.8-Flash-Next Q2_0 pack | For installation and examples, see the [project README](../README.md). For development setup and test tiers, see [CONTRIBUTING.md](../CONTRIBUTING.md). diff --git a/docs/design/flash-next.md b/docs/design/flash-next.md new file mode 100644 index 00000000..d28af648 --- /dev/null +++ b/docs/design/flash-next.md @@ -0,0 +1,643 @@ +# Qwen3.8-Flash-Next port contract + +This page fixes what the Metal 4 port of [basalt](https://github.com/jesdga95/basalt) must reproduce, how the port's +correctness is judged, and how basalt's Q2_0 model file fits this Mac's 48 GiB. Every later pull request of the port +is checked against it. Basalt is an MIT C++/CUDA engine for Qwen3.8-Flash-Next on NVIDIA GPUs. + +The port is held to three requirements: + +- **An exact port.** The Metal 4 implementation reproduces basalt's design and arithmetic, one to one. +- **Basalt's own correctness bar.** Every Metal kernel passes basalt's parity test against its CPU reference within + basalt's tolerance; greedy tokens are identical between `--spec 0` and `--spec 7` on this Mac; and wikitext-2 + perplexity (20 chunks, basalt's harness) lands within 0.01 of the pack's README figure, 2.971 (`README.md:265`). +- **The Q2_0 pack.** Basalt's official Q2_0 file, 64.90 GiB with 31.6 GiB of experts. + +The machine is an Apple M3 Max with 40 GPU cores (Apple family 9) and 48 GiB of unified memory, on macOS 27.0.1. + +**Citations.** Basalt paths are relative to commit +[`b4c63b5`](https://github.com/jesdga95/basalt/tree/b4c63b55754637f4c72ad53a0f791d425f71eb36), and `path:a-b` means +lines a to b at that commit. `precision.md` is basalt's `docs/precision.md`. That page was measured at an older +commit, and several of its line references no longer point at the code they describe, so the rules below cite the +current code wherever the two differ. Paths under `runtime/` are this repository's. + +## Numerics contract + +### Precision of each quantity + +| Quantity | Precision on the Flash-Next path | Basalt source | +|---|---|---| +| Residual stream | fp32: four streams of 2560 values per row (`R_` holds `T x 4 x 2560` floats) | `src/core/verify.cpp:779`; `precision.md:21` | +| RMSNorm | fp32, eps `1e-6` | `src/core/verify.cpp:116` | +| Hyper-connection weights | int8 copies of the BF16 down, up and inject matrices: `s = fp16(absmax / 127)` per 32 consecutive values of a row, `q = clamp(rint(w / s), -127, 127)`, and `q = 0` when `s` is 0. Always on: decode never reads the BF16 matrices | `src/kernels/cuda/hc_fused.cu:343`, `:1168-1186` (`s = 0`: `:1185`), `:1248-1250`; `precision.md:17-18` | +| Hyper-connection read | fp32 activations, never quantized. Down and inject: the int8 weights converted exactly, fp32 FMA per group. Up: the fp32 input split into fp16 high and low parts, fp16 matrix products with fp32 accumulation | `include/basalt/kernels/hc_fused.hpp:1-17`; `precision.md:58-59`, `:70` | +| Router | fp32 activation times BF16 weight, in fp32. Softmax and top-10 in fp32, ties to the lower expert id. The ten weights are renormalized, their sum floored at `6.103515625e-5` (2^-14). Decode and the drafter route inside the fused hyper-connection read: its router GEMV and `hc_top10` give the bits of the MMVF GEMV and of `native_router.cu`'s `route`, which run only where the fused read does not | `src/kernels/cuda/hc_fused.cu:1-5`, `:737-809` (GEMV), `:811-916` (`hc_top10`; tie rule `:849`, floor `:910`); `src/core/verify.cpp:1611-1617`, `:1634`; `src/core/mtp.cpp:907-913`; `src/kernels/cuda/native_router.cu:52-99`; `precision.md:60` | +| Activations into quantized matrix products | q8_1: int8 codes per 32 values with an fp16 scale and an fp16 sum. This covers the dense projections, the shared expert, the routed experts on the GPU (gate/up from the fp32 FFN input, down from the fp32 SwiGLU) and the head | `include/basalt/kernels/iq_kernels.hpp:5-7`; `precision.md:61-67` | +| Integer dot products | exact int32 per 32-value block (`mma.sync ... s32.s8.s8.s32` on CUDA), then the format's fp32 terms, summed in fp32 | `src/kernels/cuda/dense_tc.cu:60-64`; `include/basalt/kernels/dense_tc.hpp:1-13`; `precision.md:76` | +| BF16 projections: GDN alpha/beta, indexer q/k, shared-expert scalar gate, PLE value | fp32 activation times BF16 weight, fp32 FMA | `precision.md:39-41`, `:66`; the PLE value: `src/program/generate.cpp:340`, `:1889-1893`, `src/kernels/cuda/ple.cu:14` | +| Gated DeltaNet state | fp32: a `128 x 48 x 128` recurrent state and a `10240 x 3` conv history per layer | `include/basalt/kernels/dec_gdn.hpp:19` | +| KV cache | fp16, the engine default. The int8, q4_0 and k8v4 options are outside this contract | `src/program/generate.cpp:373` | +| Attention | K/V widened to fp32, fp32 scores, online softmax per 64-cell chunk, fp32 merge, sigmoid output gate | `include/basalt/kernels/qsa_dec_attn.hpp:1-2`; `precision.md:82` | +| Sparse-attention indexer | keys rounded to fp16 and held as fp32. Block scores in fp32 (ReLU per indexer head, summed). Radix top-k, ties to the lowest cell | `include/basalt/kernels/native_qsa_indexer.hpp:12-17`; `include/basalt/kernels/qsa_select.hpp:8-15` | +| Expert combine | fp32 weighted sum in router rank order, then the shared expert | `src/kernels/cuda/native_moe.cu:46-50` | +| Logits | fp32, `T x 248320` | `src/core/verify.cpp:808` | +| Greedy pick | fp32 argmax; the lowest index wins a tie | `src/kernels/cuda/sampler.cu:88-90` | +| Sampling | Philox, counter-based on (seed, absolute position) | `include/basalt/kernels/sampler.hpp:25`; `src/core/verify.cpp:2652-2654` | +| Weights | the GGUF blocks as shipped. Two copies are requantized: the int8 hyper-connection copies, and the drafter's 2-bit copy of its draft head's leading rows, which scores drafts only | `precision.md:17-18`, `:49`; `src/core/mtp.cpp:532-539` | +| CPU expert tier (decode misses, the prompt path's CPU share) | For this pack's Q2_0 experts: the fp32 FFN input, and the fp32 SwiGLU before down, quantized per 32 values to int8 with an fp32 scale `amax / 127` (0 for an all-zero block, whose inverse scale is 0 as well: `src/kernels/cpu/expert.cpp:353-354`), codes `trunc(x * (1 / scale) ± 0.5)` clamped to ±127, where the truncation is x86's, which returns the integer indefinite rather than saturating, so every element whose scaled value is a NaN or out of range gives −127. Three reachable cases follow: a chunk whose scale is at or below `2^-128` has an infinite inverse scale, so every one of its elements, the zeros included, gives −127; a chunk holding an infinity has `inv = 0`, so its infinite elements give −127 while its finite ones give 0; and a chunk holding a NaN can reach the clamp's `+127` side, because the maximum's reduction tree swallows the true peak when the NaN meets it, leaving a scale too small for the element that peak belonged to. Products on `q2_0_gguf_rows_multi`. The GPU's q8_1 has an fp16 scale, so the two tiers round differently. The AVX-512 kernel and its AVX2 fallback sum in different orders; the port transcribes the AVX-512 one, which basalt runs wherever AVX-512 is present. The supported input range, a decision of the engineering review: the quantizer writes no NaN scale or correction `hx = scale * sum` for any float input, since a NaN maximum gives scale 0, a finite one a finite scale, and an infinite one scale `+inf` with a code sum of at most −127, so `hx = −inf` (`src/kernels/cpu/expert.cpp:353-367`). A NaN therefore reaches `q2_0_gguf_rows_multi` only through a NaN fp16 block scale, which a valid model file does not hold. The port pins GCC 14.3's single-token NaN order for such a row, so that choice decides only rows of a corrupt weight file and test inputs; every NaN made from non-NaN inputs, an infinite activation's included, is x86's indefinite `0xffc00000` under every build measured. The SwiGLU itself is the tier's only arithmetic outside those kernels, and its authority is glibc and gcc rather than nvcc (`docs/research/basalt-cpu-expf.md`): `std::exp` of a float is glibc's `expf`, which an ifunc resolves to `__expf_fma` on every host with FMA and AVX2, so the port transcribes Arm's `optimized-routines` source with the rounding step fused as that variant fuses it; gcc emits `addss`, `divss`, `mulss` in that order, and the divide and the multiply write x86's floating-point indefinite 0xffc00000 for a NaN they create, where an AArch64 instruction writes 0x7fc00000; the add cannot create one, since its only invalid form is `inf + -inf` and `expf` returns no negative value | `src/kernels/cpu/expert.cpp:336-398`, `:503-556`; `src/kernels/cpu/expert_layout.cpp:124-133`; `src/core/expert_source.cpp:1592-1593`; `src/kernels/cpu/pool.cpp:423-444`, `:434`, `:559`; `src/kernels/cpu/q2_avx2.cpp:37-62` | +| Prompt path | a different computation (fp16/BF16 GEMMs, llama.cpp MMQ for the routed experts, fp16 hi/lo attention, 3xTF32 indexer scores) that writes the same KV and state formats. Quality is scored through decode | `precision.md:23-24`, `:94-108` | +| MTP drafter | Q8_0 and BF16 dense weights, Q2_0 experts. Its precision changes drafts, never output | `precision.md:47-52` | +| Compiler arithmetic | The kernels adapted from llama.cpp's arithmetic (`native_*.cu`, `qsa_dec_fused.cu`, `q5k_head.cu`, `q6k_head.cu`) and the prompt path's MMQ build with `--use_fast_math`: approximate `expf`, division and square root, denormals flushed. Every other kernel builds with nvcc's IEEE defaults, which still contract a multiply and an add into an FMA. Several of those IEEE-built kernels write approximate or flush-to-zero operations by hand, most of them to give a fast-math kernel's bits (the list below) | `CMakeLists.txt:185-202`, `:728`; `src/kernels/cuda/hc_fused.cu:1-5`; `src/kernels/cuda/dec_gdn_rec.cu:4-5` | + +**Approximate operations in IEEE-built kernels.** These decode and drafter kernels compute some operations with +approximate or flush-to-zero instructions although their files build without `--use_fast_math`, and two of them call +CUDA math library functions that are not correctly rounded (`log1pf`, and the library `expf`): + +- `src/kernels/cuda/hc_fused.cu`, the fused hyper-connection read (decode and drafter): the router's GEMV and top-10 + as the fast-math build's flush-to-zero PTX, `fma`, `add`, `sub`, `mul` and `max` with `.ftz`, `ex2.approx.ftz.f32` + and `rcp.approx.ftz.f32` (`:270-306`, used at `:737-916`); `div.approx.ftz.f32` in the q8_1 rows (`:80-101`); + `__expf` in the stream and up sigmoids (`:341`) and the SiLU (`:538`); `rsqrtf` in the norm (`:526`). +- `src/kernels/cuda/dec_gdn_rec.cu`, the GDN recurrence: `div.approx.ftz.f32` in its q8_1 (`:40-51`, `:128`); `__expf` + in the SiLU, the gates, the decay and the output gate (`:65`, `:109`, `:111`, `:120`, `:248`); `log1pf` in the + softplus (`:111`); `rsqrtf` in the norms (`:119`, `:228-229`, `:266`). +- `src/kernels/cuda/verify_kernels.cu:315`, the GDN commit's replay (`gdn_commit_layers`, `src/core/verify.cpp:2133`): + `__expf` in the decay. +- `src/kernels/cuda/qsa_dec_attn.cu`, the attention: `__expf` in the chunk softmax and the merge (`:259-260`, `:380`; + the drafter's wide window, `:576-577`, `:667`); the output gate as `mul.ftz`, `ex2.approx.ftz`, `add.ftz` and + `rcp.approx.ftz` (`:308-319`); the q8_1 rows' `max`, `abs` and `add` with `.ftz` and `div.approx.ftz.f32` + (`:321-345`). +- `src/kernels/cuda/shared_expert.cu:170`, the shared expert's scalar gate: `__fdividef(1.0f, 1.0f + __expf(-g[t]))`. +- The routed experts' SwiGLU: `__expf` (`src/kernels/cuda/gu2.cuh:387`, the chained pass decode runs, + `src/kernels/cuda/iq_kernels.cu:2567`, `:2585`; otherwise `iq_kernels.cu:1918`). The drafter's Q2_0 experts' SwiGLU: + `__expf` (`src/kernels/cuda/s2_expert_grouped.cu:170`). +- `src/kernels/cuda/sampler.cu:311`: `__expf` in the probability of the drafter's greedy pick + (`src/core/mtp.cpp:1036`). +- `src/kernels/cuda/hc8_gr.cu`, the 8-bit hyper-connection read the drafter's prompt catch-up runs once per verify + window: `MtpDrafter::prefill_cur` (`src/core/mtp.cpp:1393-1402`) records the forward without the fused read, which + calls `gr_read` or `fused_gr_read_multi` (`:819-823`), and both run `hc8_gr_read_multi` because `hc8_enabled()` is + always true (`src/kernels/cuda/hc_fused.cu:1248`). It computes `rsqrtf` in the norm (`hc8_gr.cu:78`) and the library + `expf` in the SiLU (`hc8_gr.cu:165`) and the sigmoid (`hc8_gr.cu:233`). + +The prompt path's own kernels, `src/prefill/kernels.cu`, build the same way (`CMakeLists.txt:285`) and write `__expf`, +`rsqrtf` and `log1pf` too (for example `src/prefill/kernels.cu:39`, `:74`, `:214`); the prompt path's port lists the +ones this pack runs. + +### Exactness invariants + +1. **Window invariance.** "Token t's argmax is what plain greedy decode would produce after token t, BIT FOR BIT" + (`include/basalt/core/verify.hpp:3-8`). Every kernel sums in an order fixed by the shape alone + (`include/basalt/kernels/dense_tc.hpp:11-13`, `dec_gdn.hpp:6-8`, `qsa_dec_attn.hpp:1-2`), and basalt requires every + kernel's test to check that a token's output does not depend on the window width or its position in it + (`CONTRIBUTING.md:14`). A Metal kernel whose threadgroup partition or reduction order changes with the window width + or with a row's column breaks speculative decoding. +2. **Kernel choice.** A quantized projection's kernel is chosen per projection, never per window width + (`src/core/verify.cpp:209-219`). Where basalt does switch on the width, its multi-row kernel gives every row the + one-row kernel's bits: the BF16 projections run `bf16_gemv_fp32_mmvf` for one row and `bf16_gemv_fp32_mmvf_multi` + for more (`src/core/verify.cpp:1349`, `:1440-1442`, `:1508`; `src/kernels/cuda/shared_expert.cu:196-201`), "each + output bitwise its one-row call" (`src/kernels/cuda/native_bf16.cu:193-202`). +3. **State commit.** A window reads the GDN state and never writes it. The commit replays the kept tokens from inputs + the window stored, restores the indexer tail from a snapshot, re-appends the kept keys and restores the n-gram + history (`include/basalt/core/verify.hpp:13-18`). +4. **Per-step values are data.** Tokens, positions, step records and commit counts live in buffers, never in baked + kernel arguments (`include/basalt/core/graph.hpp:14-17`). +5. **Basalt's rounding sequence, Metal's arithmetic.** The default arithmetic is the forced `native_*` set + (`src/program/generate.cpp:1889-1893`), including its rounding sequence. The authority for that sequence is what + nvcc compiles, read from basalt's sm_120 PTX and SASS and recorded per kernel and site in + `docs/research/basalt-nvcc/` (`matvec.md` for the q8_1 quantizers and `native_mmvq`, `dequant.md` for the GGUF + dequantizers, `experts.md` for the routed experts, `bf16.md` for the BF16 GEMVs, `dense_tc.md` for the window + projections, `q5k_head.md` for the Q5_K head, `s2_experts.md` for the drafter's experts, `nan.md` for the NaN + each store holds; the CPU expert tier runs on the host rather than the GPU, so its authority is glibc and gcc + instead, recorded in `docs/research/basalt-cpu-expf.md`): which multiply-adds fuse and + with which operands, the operand order of each `a * b - c * d`, where `.FTZ` flushes subnormals, and each + approximate instruction. The source alone does not settle it: nvcc's default `--fmad=true` fuses where the source + writes no FMA, `ptxas` fuses further than the PTX (the Q4_K and Q5_K returns, `matvec.md` section 5) and replaces an + approximate division by a constant with a multiply by its correctly rounded reciprocal (`amax / 127.0f`). The Metal + kernels build in `MTLMathModeSafe`, this repository's default (`runtime/src/metal_core.mm:99`), where `+`, `-`, + `*`, `/`, `sqrt` and `fma` round correctly (MSL 4.1, section 8.4, Table 8.1), and on this GPU to nearest even, as + CUDA does (measured: `tests/kernels/test_basalt_platform.py`). Each Metal source starts with + `#pragma STDC FP_CONTRACT OFF` and writes nvcc's sequence explicitly: `fma()` exactly where SASS has an `FFMA`, + with the same operands, and a separate multiply and add everywhere else, so implicit contraction no longer differs + from CUDA's (measured: with the pragma a runtime-compiled `a * b + c` is never fused; without it safe mode fuses + it). A multiply basalt rounds on its own (`__fmul_rn`, as in `src/kernels/cuda/native_ple_postops.cu:41-50` and + the routed experts' SwiGLU product, `src/kernels/cuda/iq_kernels.cu:1902-1918`) is never contracted. Where SASS + flushes (`.FTZ`), the Metal kernel flushes the inputs and the rounded result to the zero of their sign explicitly, + with integer operations on the bits, and a multiply or fma whose exact result rounds up to 2^-126, which this GPU + flushes before rounding, is rebuilt from the exact value (`fma_ftz`, `mul_ftz`), so the result does not depend on + what the GPU does with subnormals. Where basalt's SASS keeps subnormals (the IEEE-built kernels' unflagged + operations), the Metal kernel emulates IEEE behaviour wherever a subnormal can occur: in `MTLMathModeSafe` this + GPU flushes subnormal inputs and results of add, + multiply, fma and division to the zero of their sign (MSL section 8.1 permits it), and `fmax` and `fmin` compare a + subnormal as zero but return the chosen operand unflushed, the second one on a tie (measured, + `tests/kernels/test_basalt_platform.py`). An approximate division or reciprocal + (`MUFU.RCP`, then `FMUL` for a division) becomes the correctly rounded reciprocal `1.0f / x` and the same multiply: + it gives CUDA's bits wherever `MUFU.RCP` returns the correctly rounded reciprocal, which NVIDIA does not specify, + and it needs no undocumented Metal behaviour. The tests count how often a quotient through the correctly rounded + reciprocal differs from the correctly rounded quotient. For the other approximate operations basalt computes, + whether a `--use_fast_math` file produces them or an IEEE-built kernel writes them (the list above), the mapping + is the `metal::fast::` function of the same operation: `fast::exp2` of the product with log2(e) that `__expf` or + basalt's PTX forms, `fast::rsqrt` for `rsqrtf` (Table 8.2). MSL has no `log1p`, so `log1pf` gets a helper of its + own, and the library `expf` maps to `metal::precise::exp`. One helper serves each operation at every site, so + kernels that basalt checks bitwise against each other (`qsa_dec_attn_parity`, `dec_gdn_parity`, and + `hc_fused_parity`'s window checks) stay bitwise equal on Metal. Where `MUFU.RCP` is not correctly rounded, where + basalt approximates an exponential or a square root (`ex2.approx`, `rsqrtf`), and where it calls `log1pf` or the + library `expf`, the Metal result can therefore differ from CUDA's last bits. Basalt's tolerances accept that, and + invariant 1 still holds, because each Metal kernel rounds the same way at every window width. A stored NaN carries + sm_120's canonical encoding: the `FADD`, `FMUL`, `FFMA`, `MUFU` and division sequences that make or pass a NaN give + 0x7fffffff, and its hardware fp16 conversion (`__float2half`) gives 0x7fff, where this GPU's arithmetic gives + 0x7fc00000 and its `half()` 0x7e00 (`nan.md`; measured on sm_75, inferred for sm_120, whose PTX ISA leaves the + single-precision NaN unspecified). So every store a NaN can reach rewrites it with `cuda_nan` (fp32) or, where basalt + converts with `__float2half`, `cuda_nan_f16` (fp16, `kernels/common/basalt_fp.metal`), integer operations that leave + every other value's bits unchanged. basalt's software conversion `f16_from_f32` maps a NaN to `sign | 0x7E00` + instead, so a port that stores through it, as the fp16 KV append does, keeps that encoding (`nan.md`, the note on + `f16_from_f32`). + +### How this departs from the repository-wide contract + +CLAUDE.md's numerics contract governs this repository's other models. The Flash-Next path departs from it as follows, +because the port reproduces basalt's design and is judged by basalt's bar. Every other model keeps CLAUDE.md's contract +unchanged. + +| CLAUDE.md, repository-wide | Flash-Next path | +|---|---| +| Weight-only dequantization (W4A16 / W8A16) | Activations rounded to q8_1 into every quantized matrix product; integer block dot products | +| BF16 residual stream | fp32 residual stream (four streams) | +| Weights as stored | The hyper-connection matrices are requantized to int8 copies | +| FP32 accumulators and recurrent state | The same, except that integer block dots are exact int32 and the hyper-connection up projection multiplies fp16 high and low halves into fp32 accumulators | +| Reference: the HF model run on the dequantized weights | Basalt's own kernels and their CPU references (`AGENTS.md:17`); quality against llama.cpp's Q8_0 base | +| Gates: leaf ops within 2 ULP, layers at cosine above 0.999 | Basalt's per-kernel criteria (the table below): bitwise; `1e-6` to `5e-3` against double-precision references; quantization-level bounds from `1e-3` to `0.15`; looser bounds for the drafter's approximations | +| Greedy tokens equal to the golden; repeated runs bit-identical | Greedy tokens identical between `--spec 0` and `--spec 7`; perplexity within 0.01 of 2.971. Runs are bit-identical only with expert placement pinned (`precision.md:227-228`) | + +### How basalt's test tiers carry over to Metal + +Basalt's parity programs check three kinds of results: + +1. **Bitwise:** a kernel against the kernel it replaces; every window, column and batch invariance; quantizer codes; + integer outputs (token ids, router ids, route counts); state after a commit. +2. **Floating point against a double-precision CPU reference** on the same quantized bytes, within `1e-6` to `5e-3`. +3. **Quantization-level bounds** where a kernel quantizes activations or reads a requantized copy, from `1e-3` to + `0.15` (a worst row, `tests/cuda/prefill_mmq_kq_test.cpp:375`), or relative to another path's error (the CPU + share). The drafter's 2-bit head copy has the loosest: at most 2% of its picks off the exact argmax, and the pick's + probability within 100% of the exact one (`src/kernels/q5k_head_parity.cpp:349`). + +Basalt builds for CUDA compute capability 12.0 only (`CMakeLists.txt:25-30`), so none of its tests runs on this Mac; +the port re-implements each one against its Metal kernel. Tiers 2 and 3 keep basalt's references and tolerances +unchanged. In tier 1 the invariance checks stay bitwise. A comparison against the CUDA kernel that a kernel replaced +cannot run here, so the ported test compares the Metal kernel bitwise against its own one-token or one-column calls, +which is what those comparisons establish, and the kernel's accuracy rests on the tier 2 and 3 tests of the same +operation. Where basalt has no such test, the port adds one (the end of the parity tests below). The hardware +preconditions in basalt's tests (thread-block clusters, int8 tensor cores, AVX-512) describe CUDA and x86 code +paths; the arithmetic they specify still applies. Several basalt gates fold errors with `std::max`, which drops a +NaN, so the ported tests also count non-finite outputs. + +## Acceptance setup + +### The model file + +| | | +|---|---| +| Repository | [`jesdga/Qwen3.8-Flash-Next-Basalt`](https://huggingface.co/jesdga/Qwen3.8-Flash-Next-Basalt) on Hugging Face | +| Revision | `2a6a758dc12f1d027d2d35b8964110df7e80f70b` | +| File | `Qwen3.8-FN-GSQ-RCO-Q2_0.basalt` | +| Size | 69,685,970,297 bytes (64.90 GiB) | +| LFS sha256 | `dee4ae542817d73e4f7a56c448ef97cb7bb47ef92b8b2c5b7721ec0e8c25f76c` | +| Git blob | `3a890a994737dff4292d7ee85a396e5189310799` | + +The size and the hash come from the Hugging Face API +(`/api/models/jesdga/Qwen3.8-Flash-Next-Basalt/revision/2a6a758dc12f1d027d2d35b8964110df7e80f70b?blobs=true`), +read on 2026-10-15. Basalt's engine never checks the section digests (`src/core/model_file.cpp:263-311`), so the port +checks the whole file's sha256 once after the download. + +What the pack holds, from its header and tables: + +- 18 sections. There is no `hc8` section (`meta.hc8` is `null`), so the int8 hyper-connection copies are quantized at + load (`src/program/generate.cpp:2319-2365`). +- `experts.layout` v5: all 48 layers store Q2_0 gate/up and Q2_0 down, 512 blobs of 1,382,400 bytes per layer, + 33,973,862,400 bytes in all. +- The head `output.weight` is Q5_K and the token embedding Q3_K. The n-gram table `per_layer_token_embd.weight` is + IQ4_NL, 28,800,138,240 bytes. +- The 301 natively served matrices use ten GGUF types: IQ4_XS, Q2_0, Q3_K, Q4_K, Q5_K and Q6_K, plus IQ4_NL, Q4_0, + Q5_0 and Q8_0 in the shared experts' down projections. +- The drafter's vocabulary (`mtp/draft_vocab`) holds 106,299 ids, of which 40,525 are base rows. It was read from the + pack with an HTTP range request; its sha256 `b1e1d3a7a9e4bf862dcd5923ce661fb59bbd07907e594df5cf86a62ac235cb91` + equals that of the revision's `convert/draft_vocab.bin`. + +### Wikitext-2 perplexity + +Basalt's 2.971 for this pack (`README.md:265`) was "measured with `basalt-bench --quality`: 20 chunks of wikitext-2 +(512 tokens each), scored through the decode path against the Q8_0 reference" (`README.md:258-259`). The gate runs +as follows. + +1. **Text.** `wikitext-2-raw/wiki.test.raw` (`precision.md:327`, `:402`). Basalt names only the path. The archive is + the one llama.cpp's `scripts/get-wikitext-2.sh` downloads: `wikitext-2-raw-v1.zip` from the Hugging Face dataset + `ggml-org/ci` at revision `927b3642933080f1b0e811e2f916e14c292992f9` (4,721,645 bytes, LFS sha256 + `ef7edb566e3e2b2d31b29c1fdb0c89a4cc683597484c3dc2517919c615435a11`). `wiki.test.raw` is 1,290,590 bytes with + sha256 `173c87a53759e0201f33e0ccf978e510c2042d7f2cb78229d9a50d79b9e7dd08`. +2. **Chunks.** Basalt's gate does not tokenize. It reads its chunks from a llama.cpp KL-divergence base made by + `llama-perplexity -m MODEL-Q8_0-00001-of-0000N.gguf -f wikitext-2-raw/wiki.test.raw --kl-divergence-base + flashnext-q8-base.kld -c 512 -b 2048 -ngl 99 --n-cpu-moe 99 -t 16` (`precision.md:399-404`). The base holds + `n_ctx = 512`, every chunk's 512 tokens, and the Q8_0 model's log-probabilities for positions 256 to 510 + (`include/basalt/program/ppl_gate.hpp:2-8`). `basalt-bench` takes the first 20 chunks + (`src/program/bench_main.cpp:391`, `:808-824`). +3. **Engine.** One `--serve` session with the flags `basalt-bench` sets: `--spec 5 --spec-min-p 0.7 --adapt-swaps 0 + --peer-adapt-swaps 0 --resident-experts --max-context 4096 --ppl-base BASE --ppl-out rows.tsv` + (`src/program/bench_main.cpp:900-912`, `:1066-1076`). Serving refuses to start without `--prefill` + (`src/program/generate.cpp:4805-4810`) and the bench does not set it, so the contract adds `--prefill auto`, the + value of basalt's sample configuration and of its reproduction command (`README.md:92`; `precision.md:418`). The + expert cache stays on auto, as `basalt-bench` leaves it. On this Mac auto resolves to every expert only while other + processes hold at most 930,296,392 bytes of GPU memory (see the memory budget); above that, auto puts the remaining + experts on the CPU tier, as it does on any GPU that holds fewer. Basalt's own gate ran on its default placement, + with about 0.8% of routed experts computed on the CPU for its IQ3_XXS pack (`precision.md:229-231`), so the gate + is valid at any slot count. The run records IOAccelerator's "In use system memory" before it starts and the + `expert_slots` count of the engine's `INFO` line (`src/program/generate.cpp:5965-5984`). Closing programs that use + the GPU first, so that every expert sits on the GPU tier, is preferred. KV stays fp16. +4. **Per chunk k.** The request is `GEN 255 ppl=k ppl_t=3` followed by the chunk's first 257 tokens + (`src/program/bench_main.cpp:1086-1093`; T = 3 is the bench default, `:391`). The engine checks the prompt against + the base's chunk (`include/basalt/program/ppl_gate.hpp:40-54`) and forces greedy decoding + (`src/program/generate.cpp:7313`). Tokens 0 to 255 go through the batched prompt path, because 256 tokens exceed + the default `--short-read 64` (`src/program/generate.cpp:583-586`, `:7739-7745`, `:8233-8268`). A chunk below + 1,024 tokens hands a measured share of its non-resident experts with a RAM copy (here, the lent slots' experts) to + the CPU tier, so this half is not bit-reproducible run to run (`src/prefill/prefill.cpp:1868-1895`; + `precision.md:116-119`). Positions 256 to 510 are teacher-forced through verify windows of exactly 3 rows, filled + with the reference tokens instead of drafts (`src/program/generate.cpp:8379-8382`, `:8400-8401`). Every row is + scored and committed (`:8470-8480`), and relaxed drafting is off under the gate (`:8184`). +5. **Score.** For each row, `nll = lse - logit[target]`. Each exponential `exp(logit - max)` is computed in fp32 and + only their sum is double; the sum's log is taken in double and rounded to fp32, the max is added in fp32, and + `nll` is the fp32 difference (`include/basalt/program/ppl_gate.hpp:125-145`; the float `std::exp` at `:141`, `lse` + at `:142`, `nll` at `:144`). Each row's `nll` is written to `rows.tsv` with six decimals (`:155`), and PPL is + `exp(mean nll)` in double over the 20 x 255 = 5,100 rows read back from it (`src/program/bench_main.cpp:768-806`). +6. **Pass.** `|PPL - 2.971| <= 0.01`. KLD and top-1 agreement need the base; they are not part of the bar. + +**What the port supplies itself.** No base is published (the pinned revision has no `.kld` file), and making one needs +llama.cpp on the 178.3 GiB Q8_0 model (`README.md:272`), which this Mac cannot hold. Basalt's engine reads a base row +for every row it scores (`include/basalt/program/ppl_gate.hpp:125-158`), so the port's gate differs from basalt's +harness in two ways: + +- It builds the 20 chunks as `llama-perplexity` builds a base: the whole file tokenized once with special tokens on, + no BOS (`tokenizer.ggml.add_bos_token` is false), then cut into consecutive 512-token chunks (llama.cpp + [`436f6f89e`](https://github.com/ggml-org/llama.cpp/blob/436f6f89e1e581249900b37a5b8a12a36a6d0912/tools/perplexity/perplexity.cpp), + `tools/perplexity/perplexity.cpp:473`, `:491`, `:523`; `precision.md:336` names that commit). The vocabulary is + the pack's: every `tokenizer.*` key of its meta equals that of the Q8_0 GGUF's first shard + (`unsloth/Qwen3.8-Flash-Next-GGUF` at `766911a6b7369840a91dbcd95f9f997acaab6cd6`, read 2026-10-15). That these + tokens are the base's own is [H] until a base made elsewhere is compared. +- It scores the `nll` of step 5 only, and reports neither KLD nor top-1 agreement. + +Basalt also does not record the engine flags behind 2.971. The bench passes extra engine flags through unchanged, and +`precision.md`'s reproduction command uses `--kv int8` (`precision.md:416-418`) while the engine default is fp16. +Every run of the gate records its full engine command line. + +### Greedy identity: `--spec 0` against `--spec 7` + +This is basalt's own MTP on/off check (`precision.md:183-205`, `:422-437`), with expert placement pinned and two +departures from basalt's command: fp16 KV and `--short-read 8192` (both below). + +1. Two `--serve` sessions. The first runs `--spec 0`: every step is a one-token window through the verify path, and + no drafter is loaded (`src/program/generate.cpp:1860-1867`). The second runs `--spec 7 --spec-min-p 0.5`. Its + drafts come from the MTP layer in windows of up to 7 rows, and the default prompt-lookup drafter raises the cap to + 8, so its windows run 1 to 8 rows (`src/program/generate.cpp:1868-1874`). +2. Both sessions take `--prefill auto --resident-experts --max-context 8192 --adapt-swaps 0 --peer-adapt-swaps 0 + --pcie-frac 0 --expert-cache 24576 --short-read 8192 --exp concur9_logit_hash=1`, with KV left at fp16. The run + records IOAccelerator's "In use system memory" before each session starts, and each session stops unless its + `INFO` line reports `expert_slots=24576` (`src/program/generate.cpp:5965-5984`). +3. Both sessions receive the same prompts in the same order, each as `GEN 256 temperature=0` followed by the ids. +4. Compare the token ids. Also compare the per-position logit hashes that each session prints on stderr as + `LH -1 `: FNV-1a over the fp32 logits of every accepted row + (`src/program/generate.cpp:6395-6405`, `:8481-8482`). + +The prompts are basalt's three bench fixtures `data/bench/conv.ids` (38 tokens), `struct.ids` (98) and `prose.ids` +(19). The 272 chat prompts of `precision.md`'s measurement are not in basalt's repository. + +The check passes when every prompt yields identical token ids. Basalt also measured every logit row +bit-identical (`precision.md:197-200`); the hashes test that stronger property and show where a difference starts. + +**Why placement is pinned.** The GPU and CPU expert tiers quantize activations differently, so the tier an expert +sits on changes the rounding of its rows (`precision.md:227-232`). Basalt pins the tiers with `--adapt-swaps 0 +--peer-adapt-swaps 0 --pcie-frac 0` and with cache sizes fixed to what auto-sizing picks, "so the same experts sit on +the same device in both runs" (`precision.md:194-195`). An explicit `--expert-cache` does not pin the size by +itself: with a profile, basalt caps the cache at the free figure less the 700 MiB reserve and lowers it without a +warning (`src/program/generate.cpp:3434-3449`); only the logs show the count (`:3557-3558` and the `INFO` line). On +this Mac 24,576 slots hold every expert only while other processes hold at most 1,257,594,720 bytes of GPU memory in +the `--spec 7` session and 2,089,565,712 in the `--spec 0` session (see the memory budget). Short of that, the two +sessions get different slot counts, put different experts on the CPU tier and can differ for reasons the kernels have +no part in, so step 2 stops them. With every expert in the cache, decode has no CPU tier in either session. The +peer-GPU flags of basalt's command have no counterpart on one GPU. + +The first remedy for a session that stops is basalt's own: close other programs that use the GPU +(`src/program/generate.cpp:3400-3409`). If other processes still hold more than the ceiling, the fallback +is basalt's pinning rule above, the cache size fixed to what auto-sizing picks: a first `--spec 7` session with the +cache on auto reports the slot count it picks, both sessions pass that count as `--expert-cache`, and step 2 checks +for it instead of 24,576. Both sessions then hold the same experts and run the others on the CPU tier. + +**Departures from basalt's command.** Basalt's command runs `--kv int8` (`precision.md:425-428`). This +contract keeps fp16 KV, so the check runs the verify path the contract specifies: the fused K/V and query posts run +only with int8 KV (`src/core/verify.cpp:1352`, `:1433`, `:1494-1499`), and the fp16 path normalizes and rotates K and +the queries and appends K and V with separate kernels (`:1340-1344`, `:1475`). + +The second departure is `--short-read 8192`. For chunks below 1,024 tokens, basalt's prompt path hands a measured +share of the non-resident experts to the CPU, so a prompt read twice is not bit-reproducible +(`precision.md:116-119`; `src/prefill/prefill.cpp:1868-1895`). With every expert resident, the only non-resident +experts during a prompt are the coldest slots the prompt path borrows, and those with a RAM copy (the RAM tier below) +are CPU candidates (`src/prefill/prefill.cpp:1881`). With `--short-read` at least as long as the prompt, +every prompt is read through the verify windows instead (`src/program/generate.cpp:7739-7760`). No slots are lent, +window rows do not depend on the window width, and both sessions start decoding from the same state. Of the three +prompts only `struct.ids` exceeds the default 64. + +### Per-kernel parity tests + +The port carries over each of these basalt tests and passes it with basalt's criterion, quoted from the code. The +last column says where the kernel runs for this pack: **decode** (the verify window), **prompt** (the batched prompt +path), **drafter**, or **CPU share** (the prompt path's CPU experts). Unless another file is named, a bare `:N` is a +line of the test's own source (`src/kernels/.cpp`, or `tests/cuda/.cpp` for the `prefill_*` tests). The +criterion column quotes each listed check's main gating lines. Every other gate of each test carries over with it +unchanged, for example non-finite outputs counted as failures, negative controls that must find a difference, launch +counters that must move, repeats that must be bitwise identical (`qsa_dec_attn_parity.cpp:292-295`), and +`ple_parity`'s table-reader, key-row and host-reference checks (`ple_parity.cpp:491`, `:636`, `:1119`). + +| Test | What it checks | Pass criterion | Q2_0 path | +|---|---|---|---| +| `mmvq_multi_parity` | `native_mmvq`, T columns against T one-column calls; Q8_0 against a float64 dot | `if (exact && diff != 0) ++bad;` (`:215`); `const bool ok = diff == 0 && worst <= 1e-4 * (scale + 1e-30);` (`:461`) | decode | +| `dense_tc_parity` | `dense_tc` and `dense_tc_pair`: each column of a T-column call against the 8-column call; RMS error against `native_mmvq` | `const bool ok = bits == 0 && nonfinite == 0 && rms < 1e-3;` (`:137`); `const bool k = bits == 0 && rms < 1e-3;` (`:201`) | decode | +| `iq_parity` | dequantizers against gguf-py (the Q3_K token embedding's gather shares them: `src/kernels/cuda/iq_kernels.cu:2217-2220`, `:2478-2483`); `native_mmvq` for Q2_0, Q3_K, IQ4_XS and others, 1 to 8 columns | `const bool ok = dq_err < 1e-6 && mm_err < 2e-2 && multi_bad == 0;` (`:112`) | decode | +| `iq_multi_parity` | `native_expert_grouped` on Q2_0 gate/up and down at 2560/640, new kernels against old; the q8_1 quantizers against the host formula, and their overflow clamping | `const bool ok = diff == 0 && finite;` (`:329`); `bool near = path == 1 && gs == os && std::abs((int) gd - (int) od) <= 1;` (`:465`); `g_fail += bad + (clamped != 3);` (`:480`) | decode | +| `native_grouped_parity` | `native_expert_grouped` across grid shapes and stale scratch, Q2_0 pairs at 2560/640 | `for (size_t i = 0; i < ref.size(); ++i) diff += ref[i] != got[i];` (`:234`); `if (written == 0) { std::printf(" nothing was written: the check checked nothing FAIL\n"); ++bad; }` (`:246`) | decode | +| `quantize_act_parity`, its fp16 half | the f32 to fp16 conversion `f16_from_f32` (a finite overflow becomes infinity, not NaN; the boundary ties to even; subnormals are kept), with which the fp16 KV append writes K and V (`src/kernels/cuda/qsa.cu:134-135`; `src/core/verify.cpp:1475`) | `if (got != c.want) {` (`:322`); `if (!sub_ok) ++bad;` (`:335`) | decode | +| `shared_expert_parity`, its native scalar-gate check | the shared expert's BF16 scalar gate on the native path (`bf16_gemv_fp32_mmvf`, then the sigmoid scale) against the host's sigmoid | `const bool correct = std::isfinite(rel) && rel < 2e-6 && visible > 1e-5 && refused_missing;` (`:372`) | decode, drafter | +| `route_window_parity`, its projection half | the BF16 multi-row GEMV (`bf16_gemv_fp32_mmvf_cols`, which runs `bf16_gemv_fp32_mmvf_multi`) against per-row `bf16_gemv_fp32_mmvf` at 2560 to 256 and 2560 to 1, T = 2, 3, 4, 6. The engine runs that kernel for the indexer projections and the shared expert's gate (invariant 2) | `const bool same = std::memcmp(y1.data(), yn.data(), y1.size() * 4) == 0;` (`:48`) | decode | +| `dec_gdn_parity` | the decode GDN kernel for T = 1 to 8 against the 8-token window; the window leaves the state untouched; segments against a double reference | `ok = ok && d == 0 && inv == 0 && st_ok;` (`:301`); `ok = ok && d == 0 && ec < 1e-4 && ey < 1e-3 && es < 1e-3;` (`:551`) | decode | +| `dec_commit_parity` | the GDN commit across grid sizes and the indexer commit, byte for byte | `if (ra != rb) {` (`:177`); `if (qa != qb) {` (`:189`) | decode | +| `gdn_rec_parity` | the prompt path's GDN recurrence kernels | `const bool ok = std::isfinite(co.rms) && std::isfinite(cs.rms) && co.rms < 1e-5 && co.worst < 1e-4 &&` / `cs.rms < 1e-5 && cs.worst < 1e-4;` (`src/prefill/gdn_rec_parity.cu:585-586`) | prompt | +| `hc8_parity` | `hc8_gr_read_multi`, the read on the int8 hyper-connection copies that the drafter's prompt catch-up runs, against the BF16 matrices and the dequantized copies; token-count and column independence; `Gemm::bf16_w`, the prompt path's product on a copy, against BF16 and the copy in double (`src/kernels/hc8_parity.cpp:1-10`) | `expect(e[1][k].rel() < 2e-3, "the 8-bit read against the dequantized copy");` (`:173`); `expect(e[0][k].rel() < 5e-2, "the 8-bit read against bf16");` (`:174`); `expect(same, "token count / column independence");` (`:190`); `expect(ex.rel() < 5e-3, "the product against the copy in double");` (`:269`); `expect(eb.rel() < 5e-2, "the product against bf16");` (`:270`); `const bool sliced = es.rel() < 1e-5;` (`:266`) | drafter, prompt | +| `hc_fused_parity` (not registered with ctest) | the fused hyper-connection read with the 512-expert router, on the int8 copies, run with `--tol` as its header requires for the 8-bit path (`:1-4`, `:236`): its comparison with `fused_gr_read_multi` (which runs `hc8_gr_read_multi`), the MMVF router GEMV and `native_router_top10_multi` is printed, not gated (`:262-296`); gated are each token against the widest window and the widest window with its tokens reversed | `if (std::memcmp(&by_t[T][ot + i], &by_t[t_hi][oh + i], 4) != 0) ++bad;` (`:328`); `badc += std::memcmp(&vr[off + (size_t) (TH - 1 - k) * per[pt]], &by_t[TH][off + (size_t) k * per[pt]],` (`:356`), `failures += badc ? 1 : 0;` (`:361`) | decode, drafter | +| `ple_parity` | the n-gram hash vectors, the table reader, the n-gram block, the native key and value paths | `if (got[i] != hc.rows[i]) ++diff;` (`:324`); `if (last && !le(rel, 1e-2)) ++bad;` (`:782`); `const bool correct = le(rel, 2e-6) && nf == 0 && gt(separation, 1e-5);` (`:815`) | decode | +| `qsa_parity` | the fp16 KV append (`kv_append`, which runs `kv_append_step`: `src/kernels/cuda/qsa.cu:714-718`) through a reversed page table, bit for bit; the native indexer append one cell at a time against the prompt path's batched append, bitwise. Its other checks run kernels this path does not: `kv_gather`, the table indexer (`indexer_key_append`, `qsa_index`, `topk_512`), `qsa_attend` and the fp16 `qsa_gate_apply` | `require("kv_append at page_size " + std::to_string(c.page_size) + ": the pool is BIT-EXACT",` (`:504`); `for (size_t i = 0; i < pa.size(); ++i) bad += std::memcmp(&pa[i], &pb[i], 4) != 0;` (`:1437`) | decode | +| `qsa_scores_parity` | block scores and top-k, per row against per segment | `const bool ok = same && max_rel < 1e-5;` (`:123`) | decode | +| `qsa_topk_parity` | the block top-k with continuous, tied and equal scores | `const bool ok = same_cont == nq && same_tied == nq && same_equal == nq;` (`:98`) | decode | +| `qsa_topk_active_parity` | the top-k with its `active_blocks` bound | `if (!std::equal(a.begin() + i * cap, a.begin() + i * cap + w, b.begin() + i * cap)) {` (`:62`) | decode | +| `qsa_dec_attn_parity` | decode attention with gate and q8_1 rows, bitwise against `qsa_decode_attn_batch`, `native_qsa_gate_apply` and `native_quantize_q8_1`; the draft-only wide window against double | `if (b0 \|\| b1 \|\| b2) ++g_fail;` (`:146`); `const bool ok = e_new <= 4e-3 * std::max(max_ref, 1e-6);` (`:296`) | decode, drafter | +| `qsa_dec_fused_parity` | `qsa_dec_q_post` (and `qsa_dec_kv_post`, which runs with int8 KV only) against the separate kernels. With fp16 KV the verify window runs neither (`src/core/verify.cpp:1352`, `:1433`, `:1494-1499`); the drafter runs `qsa_dec_q_post` (`src/core/mtp.cpp:861-864`) | `for (size_t i = 0; i < n; ++i) c += std::memcmp(a + i, b + i, sizeof(T)) != 0;` (`:45`) | drafter | +| `qsa_prompt_attn_parity` (not registered) | the prompt attention against the decode kernel and double | `const bool ok1 = err_new <= std::max(4.0 * err_old, 1e-6 * ref_scale);` (`:224`) | prompt | +| `rope_parity` | RoPE tables bitwise; the rotation against a float host | `if (std::memcmp(&rc, &hcos[(size_t) p * half + i], 4) != 0) ++table_bad;` (`:76`); `if (!(rel <= 1e-6)) {` (`:145`); `if (!(rel <= 3e-3)) ++agree_bad;` (`:400`) | decode | +| `q5k_head_parity` | the Q5_K head GEMV bitwise against `native_mmvq` on Q5_K, 1 to 8 columns; its fused top-1, with and without the draft vocabulary's map; its 2-bit copy's top-1 (drafter) | `for (size_t i = 0; i < a.size(); ++i) bad += std::memcmp(&a[i], &b[i], 4) != 0;` (`:74`); `if (bad) fail = 1;` (`:91`); `if (logit_bad \|\| id_bad \|\| max_rel > 1e-5) fail = 1;` (`:145`); `if (bad \|\| max_rel > 1e-5) fail = 1;` (`:210`); `if (miss > trials / 50 \|\| max_p_rel > 1.0) fail = 1;` (`:349`) | decode, drafter | +| `sampler_parity` | greedy and sampled picks against host transcriptions; a row alone against the same row in a window | `for (int t = 0; t < n_tokens; ++t) if (got[(size_t) t] != want[(size_t) t]) ++bad;` (`:124`); `if (std::memcmp(&one, &pr[(size_t) t], 4) != 0 \|\| pick1 != ref[(size_t) t]) ++width_diff;` (`:457`) | decode | +| `decode_cluster_parity` | the cluster top-k and the cluster greedy argmax | `const bool ok = diff_old == 0 && diff_ref == 0;` (`:165`) | decode | +| `s2_expert_grouped_parity` | the grouped Q2_0 expert kernels against the previous kernels and a double reference | `diff_out += std::memcmp(&r[0].out[i], &r[1].out[i], 4) != 0;` (`:175`); `return std::isfinite(got) && std::fabs((double) got - ref) <= 4e-5 * mag + 1e-30;` (`:131`) | drafter | +| `prefill_route_count_test` | the prompt path's routing counts at widths 1 to 8192 | `diff += got[(size_t) e] != want[(size_t) e];` (`:38`) | prompt | +| `prefill_cpu_share_test` | the CPU pool's experts and MMQ against a double reference, the CPU path's RMS and worst-row errors at most 1.5 times MMQ's (3 times when the activations carry a few large values); a row alone against its row in the expert's job | `if (ec.rms > lim * em.rms \|\| ec.worst > lim * em.worst)` (`:379`), with `const double lim = outliers ? 3.0 : 1.5;` (`:378`); `if (std::memcmp(y_one.data(), y_cpu.data(), y_cpu.size() * 4) != 0)` (`:329`) | CPU share | +| `dequant_f16_parity` (not registered) | the fp16 dequantizers the prompt path's GEMMs read | `const bool ok = bad_f32 == 0 && bad_scalar == 0 && bad_cpu == 0;` (`:98`) | prompt | +| `dequant_bf16_test` (not registered) | the BF16 dequantizers against the CPU's | `const double tol = 1e-6 * std::fabs((double) ref[i]) + 1e-30;` (`:91`); `const bool ok = bad_f == 0 && bad_h == 0;` (`:99`) | prompt | +| `pool_stress` | the CPU pool's liveness: every job written, no 10-second stall | `if (now - since > std::chrono::seconds(10)) {` (`src/kernels/cpu/pool_stress.cpp:60`) | CPU share | + +These basalt tests do not run on this pack's path: + +- The top-10 half of `route_window_parity` (`:51-67`): its batched router branch is skipped for 512 experts and + top-10 with the native router (`src/core/layer.cpp:354`). +- `router_top10_parity`: the generic router for packs with other than 512 experts (`precision.md:87`). The 512-expert + native router runs only inside `hc_fused_parity` (see below). +- `gdn_parity`: the single-token GDN kernels of `gdn.cu` (`gdn_step`, `gdn_conv_step`, `gdn_l2_norm`, + `gdn_out_norm`), which only the single-token layer calls (`src/core/layer.cpp:218-287`), through `block_layer` and + `session_token`, which nothing in `src/program/` calls. The verify window runs `dec_gdn_rec` + (`src/core/verify.cpp:1205-1297`), which `dec_gdn_parity` checks against a double reference. +- `gr_parity`: its read checks (`:367`, `:566`, `:752`) run `gr_read` and `fused_gr_read` on BF16 matrices without + an 8-bit copy, and this pack always reads through the copies (`src/kernels/cuda/hc_fused.cu:1248`). Its write + checks (`:645`, `:689`) run `gr_write_kernel`, because `native_mmvf` defaults to false + (`src/kernels/cuda/gr.cu:43`) and the test switches modes only after them (`:741`, `:763`). Decode folds the + write into `hc_fused` or runs `native_gr_post` (`src/kernels/cuda/gr.cu:394-395`, with `gr_native_mmvf` forced at + `src/program/generate.cpp:1890`, `:2383`); both are in the table of kernels without a reference test below. +- `elementwise_parity`: `gdn_gate`, `silu_inplace`, `rms_norm_weighted`, the S-form `embedding_gather` and + `f32_to_bf16_bulk`. Under the forced native flags neither verify nor the drafter calls them + (`src/core/verify.cpp:1341-1342`, `:1715-1717`; `src/core/mtp.cpp:946`), and the Q3_K embedding runs + `iq_embed_rows` (`src/kernels/cuda/iq_kernels.cu:2478-2483`). +- The Q8_0 and Q8_K halves of `quantize_act_parity` (`:93`, `:190`): `quantize_q8_0` and `quantize_q8_K`, which this + path does not call. The drafter's experts quantize with `quantize_q8_0_scaled` (`src/core/mtp.cpp:933`; + `src/kernels/cuda/s2_expert_grouped.cu:1111`), listed below. +- The S-form and combine checks of `shared_expert_parity` (`:298`, `:462`): the legacy S-form shared expert + (`:241-242`, `:343-344`, with no native weights) and `moe_combine`, which accumulates in double + (`src/kernels/cuda/shared_expert.cu:143-149`). Decode runs `shared_expert_multi` (`src/core/verify.cpp:1720`) and + `native_moe_combine_multi` or `native_moe_combine` (`:1850-1852`; `src/core/layer.cpp:415`), both listed below. +- `ple_q5_parity`, `q5_projection_parity`: a Q5_0 n-gram table and Q5_1 projections, neither in this pack. +- `q6k_head_parity`, `q6k_vhead_parity`: a Q6_K head; this pack's head is Q5_K. +- `kv_q8_parity`, `kv_q4_parity`, `kv_hybrid_parity`, `kv_stream_parity`: KV formats and KV streaming outside the + contract, which keeps fp16 KV fully resident. +- `qsa_seg_parity`: batch windows (`--parallel`). +- `cvec_parity`: control vectors, which are off. +- `s2_gemv_parity`, `s2_gemv_q8_parity`, `s_gemv_parity`, `s_gemv_q8k_parity`: older S-format GEMVs that the forced + native path does not call. +- `bf16_gemv_parity`: the GEMVs on BF16-rounded activations. With the native BF16 projections forced on, the engine + runs `bf16_gemv_fp32_mmvf` instead (`src/core/layer.cpp:84-90`). +- `dequant_s2_parity`: the naive S2 decode kernel, which no engine path calls (`src/kernels/cuda/dequant_s2.cu:1`). +- `ple_win_parity`: the n-gram window kernel runs only with a BF16 n-gram key (`src/core/verify.cpp:1058-1066`). This + pack's key is Q2_0 (`src/program/generate.cpp:2538-2554`), so each window row runs `ple_block` + (`src/core/verify.cpp:1105-1124`), which `ple_parity` covers. +- `expert_parity`, `expert_multi_test`, `pool_test`: the older S2 AVX-512 CPU kernels, reached only for packs that are + not native (`src/core/expert_source.cpp:1652-1653`). +- `router_dot_parity`: an AVX1 BF16 dot product that is not on the expert path. +- `native_expert_parity` (six synthetic pairs, none of them Q2_0; `--q5_1-min`, `--q8k-quant`, `--bf16-embd`, + `--q6k-embd`; the Q6_K refusal), the i-quant kernels of `iq_multi_parity`, `prefill_fused_iq_test` and + `prefill_mmq_kq_test`: formats this pack does not use. +- `prefill_fused_moe_test`: the fused int8 prompt experts run only for a layout that is not native, and every layout + is native (`src/kernels/cpu/expert_layout.cpp:145`). Q2_0 gate/up is not among the fused native kernels' formats + (`src/prefill/moe_fused_iq.cu:933-936`), so this pack's prompt experts always run on llama.cpp's MMQ + (`src/prefill/prefill.cpp:1716-1723`). +- `dec_moe_parity`: the device-planned MoE tail, which is off when every expert is resident + (`src/core/verify.cpp:313`). +- `vision_cpu_parity`, `vision_cuda_parity`: vision is off. + +The kernels below run on this pack's path, but no gated basalt test checks them against a reference: the tests that +run them compare them only with another GPU kernel, or no test runs them. The port adds a test for each, against a +double-precision reference (a host transcription, for a quantizer) with the bound of the nearest basalt test. The +same rule holds for any other ported kernel whose basalt tests end in a comparison between two GPU kernels. + +| Kernel on this path | What basalt's tests check instead | The port's test and bound | +|---|---|---| +| CPU Q2_0 gate/up, `q2_0_gguf_rows_multi` (CPU share) | `prefill_cpu_share_test` uses Q2_0 only as a down type (`tests/cuda/prefill_cpu_share_test.cpp:392-395`) | Two bars. The kernel's own, met: `tests/kernels/test_basalt_cpu_q2.py` holds the ARM NEON transcription of `act_quant_q8_1` and `q2_0_gguf_rows_multi` bit for bit against the AVX-512 semantics, with an independent float64 check through llama.cpp's dequantizer. The tier's, still owed once the CPU pool lands: Q2_0/Q2_0 blobs at 2560/640 through the CPU pool and through MMQ, both against that test's double reference. MMQ meets the next row's absolute bound, and the CPU path's errors stay within `lim` times MMQ's: `if (ec.rms > lim * em.rms \|\| ec.worst > lim * em.worst)` (`tests/cuda/prefill_cpu_share_test.cpp:379`), `lim` 1.5, or 3 with outliers (`:378`) | +| MMQ on Q2_0, the prompt path's experts | only `prefill_fused_moe_test`'s yardstick, off this path | `const double lim_rms = outliers ? 3e-2 : 2e-2, lim_worst = outliers ? 0.15 : 0.1;` (`tests/cuda/prefill_mmq_kq_test.cpp:375`) | +| `native_mmvq` on Q4_0, Q4_K, Q5_0, Q5_K and Q6_K: the shared experts' matrices (`src/kernels/cuda/shared_expert.cu:186-195`) and the attention's K and V projections, which `dense_tc_mask()` leaves on `native_mmvq` (`src/kernels/cuda/dense_tc.cu:1155`; `src/core/verify.cpp:209-219`, `:1444-1445`) | `mmvq_multi_parity` checks column invariance, with a float64 reference for Q8_0 only (`src/kernels/mmvq_multi_parity.cpp:97-176`, `:403-461`). `dense_tc_parity`, `q5k_head_parity` and `dec_gdn_parity` use `native_mmvq` as their reference; `iq_parity` covers the i-quants, Q2_0 and Q3_K (`src/kernels/iq_parity.cpp:29`) | `mmvq_multi_parity`'s Q8_0 rule on the same q8_1 bytes: `const bool ok = diff == 0 && worst <= 1e-4 * (scale + 1e-30);` (`src/kernels/mmvq_multi_parity.cpp:461`) | +| `q5k_head_mmvq`, the decode head (`src/core/verify.cpp:1935-1936`) | bitwise against `native_mmvq` on Q5_K only (`src/kernels/q5k_head_parity.cpp:67-74`, `:91`) | the same rule at the head's shape, 2560 to 248,320; the bitwise check carries over | +| The q8_1 rows the fused read writes for the projections (`src/core/verify.cpp:1151-1159`), in place of `native_quantize_q8_1` (`:1439`) | no test sets `HcFusedArgs::xq` (`src/kernels/hc_fused_parity.cpp:190-196`) | the host formula with `iq_multi_parity`'s rule for `native_quantize_q8_1`, whose arithmetic the rows copy (`src/kernels/cuda/hc_fused.cu:80-101`): `bool near = path == 1 && gs == os && std::abs((int) gd - (int) od) <= 1;` (`src/kernels/iq_multi_parity.cpp:465`) | +| The router's softmax and top-10: `hc_top10` in the fused read (`src/kernels/cuda/hc_fused.cu:811-916`), and `route` (`src/kernels/cuda/native_router.cu:46-100`) where the fused read does not run | `hc_fused_parity`, which is not registered, prints its comparison of the fused picks with `native_router_top10_multi` under `--tol` and gates only window invariance (`src/kernels/hc_fused_parity.cpp:185-187`, `:262-296`, `:328`); neither meets a host reference | `router_top10_parity`'s rule: ids exact, `if (h_ids[i] != r_ids[i]) ++id_bad;` (`src/kernels/router_top10_parity.cpp:86`), and weights `if (!(rel <= tol)) ++w_bad;` (`:90`) with `tol` 1e-5 (`:129`, `:134`, `:141`, `:146`) | +| The hyper-connection outputs of `hc_fused_read` on the int8 copies (`R_out`, `rs`, `lo`, `inject_out`, `mixed`), decode and drafter (`src/core/verify.cpp:1611-1617`; `src/core/mtp.cpp:814-818`) | `hc_fused_parity` gates only window invariance on them (`src/kernels/hc_fused_parity.cpp:328`, `:356-361`); `hc8_parity` checks `hc8_gr_read_multi` and `gr_parity` the BF16 reads, neither of which decode runs | each output against a double-precision read on the dequantized copies, with `hc8_parity`'s bound for the 8-bit read against the dequantized copy: `expect(e[1][k].rel() < 2e-3, "the 8-bit read against the dequantized copy");` (`src/kernels/hc8_parity.cpp:173`) | +| `native_gr_post`, the hyper-connection write when decode does not fold it into `hc_fused` (`src/kernels/cuda/gr.cu:394-395`) | its only test, `ple_win_parity`, runs it as the reference side (`src/kernels/ple_win_parity.cpp:74`) | against a double-precision write with `gr_parity`'s write rule: `const bool plain = worst_plain < 1e-6;` (`src/kernels/gr_parity.cpp:645`) | +| `native_expert_grouped` on Q2_0/Q2_0 at 2560/640, the routed experts (`src/core/verify.cpp:1759-1765`) | new kernels against old ones, bitwise (`src/kernels/iq_multi_parity.cpp:302-329`; `src/kernels/native_grouped_parity.cpp:1-12`); only the Q2_0 dot product meets a reference (`src/kernels/iq_parity.cpp:112`; `src/kernels/iq_multi_parity.cpp:162`), and `native_expert_parity`'s pairs include no Q2_0 (`CMakeLists.txt:771`) | the whole expert (gate/up, SwiGLU, the q8_1 of H, down) against a double-precision expert on fp32 activations, with Q2_0 dequantized by `tools/gguf_writer.py`'s codec as `iq_parity`'s fixtures are (`src/kernels/iq_parity.cpp:5-7`): `const bool ok = ec < 3e-2 && eg < 3e-2 && std::isfinite(ec) && std::isfinite(eg);` (`src/kernels/native_expert_parity.cpp:368`) | +| `shared_expert_multi` with `native_swiglu_quantize_q8_1` (decode, `src/core/verify.cpp:1720`), and the drafter's one-row native `shared_expert` (`src/core/mtp.cpp:947-949`) | `shared_expert_parity` runs the S-form expert (`src/kernels/shared_expert_parity.cpp:241-242`, `:343-344`); `shared_expert_multi` runs only in a bench (`src/kernels/pk_moe_bench.cpp:244`) | the expert against a double-precision expert on fp32 activations with `native_expert_parity`'s rule (`src/kernels/native_expert_parity.cpp:368`); the scalar gate keeps `shared_expert_parity`'s rule (`src/kernels/shared_expert_parity.cpp:372`) | +| `native_moe_combine` and `native_moe_combine_multi` (decode, `src/core/verify.cpp:1850-1852`, `src/core/layer.cpp:415`; drafter, `src/core/mtp.cpp:952`, `:962`) | `shared_expert_parity` checks the legacy `moe_combine` (`src/kernels/shared_expert_parity.cpp:445`, `:462`); `native_moe_combine_multi` runs only in `dec_moe_parity` (`src/kernels/dec_moe_parity.cpp:692`), which is not registered | the legacy combine's rule against a double reference, `if (!(rel_k <= 1e-6))` (`src/kernels/shared_expert_parity.cpp:462`); each row of a multi-row call bitwise its one-row call | +| `quantize_q8_0_scaled`, the drafter's activations into its Q2_0 experts (`src/core/mtp.cpp:933`; `src/kernels/cuda/s2_expert_grouped.cu:1111`) | `quantize_act_parity` calls `quantize_q8_0` and `quantize_q8_K` only (`src/kernels/quantize_act_parity.cpp:93`, `:190`) | codes and fp32 scales against a host transcription, byte for byte, as `quantize_act_parity` checks `quantize_q8_0`: `if (g_blocks[i] != r_blocks[i]) ++byte_bad;` (`src/kernels/quantize_act_parity.cpp:100`) | +| The attention core, `qsa_dec_attn` (decode, `src/core/verify.cpp:1563`; drafter, `src/core/mtp.cpp:883`) | `qsa_dec_attn_parity` compares it bitwise with `qsa_decode_attn_batch` and checks only the drafter's wide window against double (`src/kernels/qsa_dec_attn_parity.cpp:146`, `:296`); `qsa_parity`'s double reference runs `qsa_attend` (`src/kernels/qsa_parity.cpp:1094`, `:1117`) | `qsa_parity`'s attention rule on the same fp16 cache: `if (!(num / den <= 1e-5))` (`src/kernels/qsa_parity.cpp:1117`) | +| The attention's output gate, `native_qsa_gate_apply`'s arithmetic, which the merge reproduces (`src/kernels/cuda/qsa_dec_attn.cu:308-319`) | only a reference side (`src/kernels/qsa_dec_attn_parity.cpp:131`); `qsa_parity`'s gate check runs the fp16 `qsa_gate_apply` (`src/kernels/qsa_parity.cpp:1142-1154`) | `shared_expert_parity`'s rule for its sigmoid gate, `rel < 2e-6` (`src/kernels/shared_expert_parity.cpp:372`) | +| `native_qsa_rms_norm_weighted`, the query and key norms with fp16 KV (`src/core/verify.cpp:1340-1341`; drafter, `src/core/mtp.cpp:727`, `:764`, `:792`) | only a reference side (`src/kernels/qsa_dec_fused_parity.cpp:111`, `:123`, `:125`) | `qsa_parity`'s rule for the pooled keys: `if (!(worst <= 1e-6)) {` (`src/kernels/qsa_parity.cpp:611`) | +| `native_qsa_indexer_append`, the indexer key's norm, RoPE and pooling with fp16 KV (`src/core/verify.cpp:1478-1483`), which the commit replays (`native_qsa_indexer_commit_layers`, `:2134`) | `qsa_parity` compares it bitwise with the prompt path's batched append (`src/kernels/qsa_parity.cpp:1428-1437`) and its position-0 key with the table indexer (`:1495`); only the table indexer, `indexer_key_append`, meets a double reference (`:581`, `:611`) | the pooled keys against a double-precision reference with `rope_parity`'s bound for the native rotation: `if (!(rel <= 3e-3)) ++agree_bad;` (`src/kernels/rope_parity.cpp:400`) | + +The ported `route_window_parity` also runs the shapes this path uses, 2560 to 128 and 2560 to 512. + +## Memory budget on this Mac + +**Inputs, measured on this Mac.** Unified memory is 51,539,607,552 bytes (48 GiB, `hw.memsize`) in 16 KiB pages. The +GPU working set (`recommendedMaxWorkingSetSize`) is 40,200,896,512 bytes, `maxBufferLength` is 30,150,672,384 bytes, +and `iogpu.wired_limit_mb` is at its default of 0, with the GPU's wired-memory collector on +(`iogpu.disable_wired_collector` 0, `iogpu.dynamic_lwm` 1). A fresh Metal process reports a `currentAllocatedSize` of +81,920 bytes: the figure counts that process's allocations only. With no engine running, other processes held +962,134,016 to 2,434,203,648 bytes of GPU memory (IOAccelerator's "In use system memory", readings on 2026-10-15 +and 2026-10-16), 5.24 to 6.59 GB of RAM was wired, and 3.2 to 3.9 GB of swap was in use. + +**Mode.** Basalt's low-RAM resident mode, `--resident-experts` (`src/program/generate.cpp:872-876`; the flags it sets, +`:1608-1611`). The experts section stays memory-mapped. The experts no GPU slot holds are copied into RAM once, and so +are the experts of the cache slots the prompt path may borrow, as far as RAM allows +(`src/core/expert_source.cpp:588-760`). + +**Mapping to unified memory [H].** Basalt sizes the GPU tier from `cudaMemGetInfo`'s free VRAM and the RAM tier from +Linux's MemAvailable. `cudaMemGetInfo` covers the whole device, so its free figure already leaves out every other +program's GPU memory, and basalt's own refusal tells the user to "close other programs that use the GPU" +(`src/program/generate.cpp:3302-3303`, `:3400-3409`). The port's free figure is device-wide as well: +`recommendedMaxWorkingSetSize`, less the other processes' GPU memory read before the engine allocates anything, less +`currentAllocatedSize`. Whether macOS charges other processes' GPU memory against the same limit, or its collector +reclaims that memory under pressure (which would make this figure conservative), is [H]. The RAM figure is macOS's +available memory. Every GPU buffer and every host allocation come out of the same 48 GiB. Mapped host memory the GPU +reads, and pinned host memory basalt's copy engine reads, both become shared Metal buffers (a kernel argument or a +blit source), so both count against the working set. + +**Session.** The tables below are for the identity check's `--spec 7` session, the largest of the acceptance +sessions: 8192 cells, which also covers the quality gate's 4096, and verify buffers for 8 rows (`--spec 7` with the +lookup's eighth row, `src/program/generate.cpp:1868-1874`; `kVerifyMaxT`, +`include/basalt/kernels/verify_kernels.hpp:21`). Each cell costs 26,380 bytes over the 12 attention layers at fp16: +per layer 2,048 of K and V, 128 of pooled indexer keys and 1 of page table, plus one 256-byte RoPE row; the drafter's +own K/V costs 2,177 more (`src/core/layer.cpp:498-533`). Basalt's own figure is about 29 KB per token +(`include/basalt/kernels/kv_q8.hpp:3-4`). + +**Labels.** *Exact*: the pack's tables put through basalt's allocation code. *Estimate*: a small buffer counted +approximately. *Allowance*: a constant basalt reserves rather than allocates. *[H]*: a CUDA figure assumed to carry +over to Metal. + +### GPU working set + +| Allocation | Bytes | Label | Basis | +|---|---:|---|---| +| Dense pool: routers, norms, BF16 projections, inject matrices | 214,208,000 | exact | `dense.index` rows less the natively served, head, embedding and hyper-connection down/up rows, 64-byte aligned (`src/program/generate.cpp:2200-2248`; `src/core/weights.cpp:98-127`) | +| int8 hyper-connection copies | 691,527,680 | exact | 96 down, 96 up, 96 inject and 2 output matrices, each `rows * cols + rows * srow * 2` with `srow = (cols / 32 + 7) & ~7` (`src/kernels/cuda/hc_fused.cu:1210-1216`; `src/core/verify.cpp:566-581`) | +| Native projections | 1,443,058,432 | exact | every attention, GDN and shared-expert matrix and the Q2_0 n-gram key, GGUF bytes as shipped, and a 6,912-byte q8_1 scratch (`src/core/native_dense.cpp:26-38`, `:213-233`) | +| Output head, Q5_K | 437,043,200 | exact | no two-stage copy for a Q5_K head (`src/core/native_head.cpp:23-40`) | +| Token embedding, Q3_K | 273,152,000 | exact | mapped host memory in basalt; the GPU reads it, so on Metal it is a working-set buffer (`src/core/native_head.cpp:174-200`) | +| MTP drafter | 831,970,992 | exact | dense weights without the hyper-connection matrices 76,777,472; 512 Q2_0 experts 707,788,800; int8 copies 21,345,280; K/V 17,837,520; buffers 8,219,648 and mapped staging 2,272 (`src/core/mtp.cpp:220-234`, `:298-327`, `:333-401`, `:403-453`, `:488-503`) | +| Session at 8192 cells | 343,102,976 | exact | 36 GDN states 117,669,888; 12 attention states with indexer keys and one RoPE table 216,147,392; per-layer buffers 9,285,696 (`src/core/session.cpp:56-75`; `src/core/layer.cpp:147-179`, `:297-315`, `:515-533`, `:796-808`, `:1153-1165`) | +| Logits and small buffers | 1,372,912 | estimate | logits 993,280 (`src/program/generate.cpp:3194`), n-gram scratch 264,112 and embedding row 10,240 (`:2581-2582`), expert parts 102,400 (`:2630`), head q8_1 scratch 2,880 (`src/core/native_head.cpp:75`); kernels' own scratch, such as the fused hyper-connection read's (`src/kernels/cuda/hc_fused.cu:1150-1152`), not counted | +| **Allocated before the cache** | **4,235,436,192** | | | +| Reserve kept free (`--vram-reserve-mib 700`) | 734,003,200 | allowance [H] | for the graphs, the hit scratch and other small tables (`src/program/generate.cpp:474-476`, `:3339`); the only term an explicit cache keeps free (`:3440-3441`) | +| Draft head, bound after the cache | 229,259,012 | exact | logits for 8 rows 7,946,240; 106,811 gathered head rows 187,987,360; 2-bit copy of the 41,037 leading rows and its scratch 32,896,120; id maps 429,292 (`src/core/mtp.cpp:524-549`); auto sizing keeps it free as well (`src/program/generate.cpp:3309-3311`) | +| Verify windows and the deferred checkpoint copy | 218,333,184 | allowance [H] | 96 MiB of windows and one GDN state, 117,669,888; auto sizing keeps them free as well (`src/program/generate.cpp:2841`, `:3313-3319`) | +| Other processes' GPU memory | 962,134,016 to 2,434,203,648 | measured | IOAccelerator's "In use system memory" with no engine running; not in the sums of this table. It comes out of the free figure the cache is sized from (the next row) | +| **Expert cache** | **33,973,862,400** | exact | the identity sessions' explicit `--expert-cache 24576`, capped at the free figure less the 734,003,200-byte reserve (`src/program/generate.cpp:3434-3449`): 24,576 slots, every expert, while other processes hold at most `40,200,896,512 - 4,235,436,192 - 734,003,200 - 33,973,862,400` = 1,257,594,720 bytes, and one slot fewer for each further 1,382,400 bytes | +| Allocated after the cache | 631,122,300 | exact | verifier arena 69,878,784 and mapped staging 990,568 (`src/core/verify.cpp:733-821`), the draft head 229,259,012, the deferred GDN copy 117,669,888; the prompt path's mapped grouping table 987,408, and the pinned PLE double buffer 167,772,160 and `Stager` ring 44,236,800 its copies read (`src/prefill/prefill.cpp:153-166`, `:725-750`, set up from `src/program/generate.cpp:5016`); slot offsets 196,608 and the penalty history 131,072 (`src/core/verify.cpp:901-904`; `src/program/generate.cpp:5109-5114`); all allocated once the cache is sized. MMQ's buffer pool fills at the first prompt and is not counted (`src/prefill/mmq/mmq_host.cu:47-58`) | +| **Used at READY** | **38,840,420,892** | | 36.17 of 37.44 GiB | +| Left | 1,360,475,620 | | includes the 700 MiB reserve; other processes' GPU memory must fit here too | + +Loading also stages the BF16 hyper-connection down and up matrices, 1,271,398,400 bytes, to quantize their copies, +and frees them before the cache is sized (`src/program/generate.cpp:2334-2358`). + +### RAM + +| Allocation | Bytes | Label | Basis | +|---|---:|---|---| +| GPU buffers allocated before the RAM copy is sized | 38,209,298,592 | exact | the table above, through the expert cache | +| n-gram row cache and reader slab | 100,794,368 | exact | 1,048,576 rows of 90 bytes in 8-way sets with 4-byte keys, and 256 two-page read slots (`src/ngram/ple_reader.cpp:35-50`, `:350`; `src/program/generate.cpp:369-370`) | +| n-gram table | 0 | design | the 28,800,138,240-byte table stays on the SSD and is read unbuffered (`--ple-io direct`, `src/program/generate.cpp:368`; `include/basalt/platform/direct_file.hpp:3-5`) | +| Engine memory taken after the copy | 2,147,483,648 | allowance | `kLateHostBytes` (`include/basalt/platform/memory.hpp:33-35`). On this Mac it also holds the 631,122,300 bytes of GPU buffers allocated after the cache | +| Serving growth | 1,094,877,520 | exact; one allowance | 7 conversation checkpoints of 118,063,152 bytes (`--prompt-cache 6` plus one) and one request's 256 MiB (`src/program/generate.cpp:1175-1192`; `src/core/conversation_state.cpp:106-128`) | +| RAM margin | 2,576,980,377 | allowance | the larger of 2 GiB and 5 % of the RAM (`src/platform/memory.cpp:51-53`) | +| File-cache floor for the OS | 0 | rule | kept only while an expert is read from the file, then 5,173,673,984: the larger of 4 GiB and 3.5 GiB plus two layers' experts (`include/basalt/platform/memory.hpp:41-62`; `src/program/generate.cpp:4665-4691`). Here every expert has a GPU slot | +| **Subtotal** | **44,129,434,505** | | 41.10 GiB | +| **Left for macOS, other processes and the RAM tier** | **7,410,173,047** | | 6.90 GiB | + +**The RAM tier.** Basalt's resident copy holds the complement (the experts no GPU slot holds), which is empty here. +What remains is the lend region: the experts of the slots the prompt path may borrow, copied from the last slot +downward while they fit (`src/core/expert_source.cpp:138-158`, `:728-744`). The planned loan is for the largest +`--prefill auto` chunk, 8192 tokens (`src/program/generate.cpp:4553-4591`): `Prefill::bytes_needed(8192)` is +3,732,376,320 bytes, or 2,700 slots (`src/prefill/prefill.cpp:1141-1177`). The copy keeps 5,819,341,545 bytes free +(the margin, `kLateHostBytes` and the serving growth; `src/program/generate.cpp:4660-4662`). The RAM tier is +therefore `min(3,732,480,000, 7,410,173,047 - macOS and other processes)`, in whole 1,382,400-byte blobs: + +| macOS and other processes | RAM tier | +|---|---| +| 3 GiB | 3,732,480,000 bytes, the whole loan (2,700 slots) | +| 4 GiB | 3,114,547,200 bytes (2,253 slots) | +| 5 GiB | 2,040,422,400 bytes (1,476 slots) | +| 6 GiB | 967,680,000 bytes (700 slots) | +| 6.90 GiB or more | 0 | + +While serving, basalt stops a request with "RAM low" once available RAM falls below its guard, here the margin alone +(2,576,980,377 bytes), since no expert is read from the file (`src/program/generate.cpp:6033-6034`, `:5926-5931`, +`:8790-8800`; `include/basalt/platform/memory.hpp:64-70`). In the `--spec 7` session that happens once macOS and +other processes take more than 8,926,534,395 bytes (8.31 GiB) less the RAM tier: the 48 GiB less the working set at +READY, the n-gram cache, the serving growth and the margin. Metal's own host memory comes out of the same bytes. + +How much macOS and other processes take on this Mac, at load and while serving, has not been measured [H]. With no +engine running, 5.24 to 6.59 GB was already wired, against the 7,410,173,047 bytes the largest session leaves for +macOS, other processes and the RAM tier. A lent slot whose expert the RAM tier lacks is refilled from the file after +the prompt (`src/core/expert_source.cpp:947-951`). The quality gate's 256-token prompts take a 262,852,352-byte loan, +the last 191 slots (264,038,400 bytes of blobs), which the RAM tier holds first. Basalt also sets aside spare places +for adaptive swaps, 96 blobs or 132,710,400 bytes (`src/core/expert_source.cpp:711-726`), only when adaptation is on. +Both acceptance runs pin it off, and with every expert resident no swap would have a candidate. + +### Result + +- **GPU expert cache: 24,576 slots, 33,973,862,400 bytes (31.64 GiB), every expert, while other processes' GPU + memory stays under the session's ceiling.** Decode then runs basalt's zero-doorbell window, planned on the device + with no host service and no CPU tier (`src/core/verify.cpp:876-882`), and the device-planned MoE tail is off + (`src/core/verify.cpp:313`). +- **RAM tier: 0 to 3,732,480,000 bytes**, set by what macOS leaves when the copy is built. +- Each acceptance session holds every expert only while other processes hold at most its ceiling of GPU memory: the + identity sessions through the explicit cache's cap (`src/program/generate.cpp:3434-3449`), the quality gate through + auto sizing (`:3299-3343`). Other processes were measured holding 962,134,016 to 2,434,203,648 bytes. At the low + end both identity sessions hold every expert and the quality gate is 24 slots short; at the high end all three + ceilings are exceeded. Each session therefore checks its slot count before it runs, and other programs release GPU + memory first, or the acceptance setup's fallbacks apply. + + | Session | Working set at READY | Left of the working set | Ceiling for other processes' GPU memory | Slots with 962,134,016 to 2,434,203,648 held | Room for macOS and the RAM tier | + |---|---:|---:|---:|---:|---:| + | Identity, `--spec 7`, 8192 cells (the tables above) | 38,840,420,892 | 1,360,475,620 | 1,257,594,720 | 23,724 to 24,576 | 7,410,173,047 | + | Identity, `--spec 0`, 8192 cells: no drafter, verify buffers for 2 rows | 37,742,645,472 | 2,458,251,040 | 2,089,565,712 | 24,326 to 24,576 | 8,242,144,039 | + | Quality gate, `--spec 5`, 4096 cells: verify buffers for 7 rows | 38,714,008,260 | 1,486,888,252 | 930,296,392 | 23,488 to 24,552 | 7,529,473,635 | + +- Longer contexts: each cell backed at startup costs about 28,980 bytes of the working set (the 26,380 above, the + drafter's 2,177 and its per-cell scratch). Under auto sizing, the 810,002,524 bytes of slack at 8192 cells keep + every expert GPU-resident up to about 36,000 backed cells while no other process holds GPU memory; other processes' + GPU memory comes out of the same slack. A server backs at most 32,768 cells at startup (elastic KV, + `src/program/generate.cpp:2970-2977`); a request that needs more borrows the cache's last slots for its K/V, and + those slots' experts then run on the CPU tier from their RAM copies (`src/program/generate.cpp:6291-6324`). + +### Constraints for the Metal port + +1. **The cache needs at least two buffers.** At 33,973,862,400 bytes it exceeds `maxBufferLength` (30,150,672,384), + which holds at most 21,810 slots. Slot addressing must survive the split, and so must the prompt path's loan: + basalt bump-allocates it as one contiguous region from slot `lend_first` to the end of the cache + (`src/prefill/prefill.cpp:95-117`; `src/program/generate.cpp:4956-4958`), 2,700 slots from slot 21,876 for an + 8192-token chunk. The last buffer must therefore start at or below `lend_first`. Any two-buffer split between + slots 2,766 and 21,810 does; the rule bites with three or more buffers, and basalt-style 1 GiB segments + (776 slots) would spread the loan over four or five. Basalt's segmented arena (`src/core/expert_cache.cpp:146-264`) + is no precedent for separate buffers: it maps its segments into one reserved address range (`:146-170`). +2. **The RAM tier stays outside Metal buffers.** As a Metal buffer it would count against the working set [H]: 38.8 GB + in use plus a 3.7 GB tier exceeds 40.2 GB. The prompt path copies a lent expert into GPU memory the way basalt's + `Stager` copies blobs that are not pinned (`src/prefill/prefill.cpp:121-271`). +3. **Basalt's CUDA allowances and other processes' GPU memory need measuring on Metal [H].** The allowances are the + 700 MiB reserve, the 96 MiB window allowance and the host-mapping probe (`src/program/generate.cpp:3321-3338`), + which costs nothing on unified memory. The 1,360,475,620 bytes left in the working set must absorb Metal's own + allocations (pipelines, command buffers) and, under the port's device-wide free figure, other processes' GPU + memory, which as measured ranges from under both identity ceilings to over every session's. Measure both at the + first load. +4. **Available RAM needs a macOS reading [H].** MemAvailable has no macOS equivalent, and the port's reading of + available memory decides the RAM tier and when serving stops a request. Measure what macOS and other processes + take at the first load and while serving: above 7,410,173,047 bytes the largest session's RAM tier is 0, and above + 8,926,534,395 bytes (8.31 GiB) its requests stop with "RAM low". +5. **The GPU never waits on the host.** Basalt's decode window parks a one-thread kernel on a mapped host flag + (`wait_flag_ge_kernel`, `src/kernels/cuda/verify_kernels.cu:919-922`) while the host serves the layer's CPU expert + misses (`src/core/verify.cpp:2541-2613`). A running Metal dispatch has no documented view of CPU writes, and on the + M3 Max the GPU watchdog kills a command buffer that waits on an event for 5 s, while 4.5 s survives + (`probes/p16_host_handoff`) [M]. The port runs that work at host points: the pass before each handoff signals a + shared event, the host serves the misses, and the host then commits the command buffer that continues the layer. + Each handoff idles the GPU for a median of 136 to 137 µs as built, against 0.5 µs at a plain pass boundary [M]. + + **Which form a decode program gets is a compile-time choice with one call site.** Basalt compiles the decode + graph twice and picks on `all_resident_` (`src/core/verify.cpp:876-907`): with every expert resident the + zero-doorbell graph services nothing from the host, and only a short cache gets the DecMoe window, which + services every MoE layer whether or not that layer has a CPU entry. At 48 MoE layers the unconditional form + costs 6.5 to 6.6 ms per step of GPU idle at the median above, so installing a point in every layer is a + different program rather than a slow exact one. `monolith/compiler/cpu_tier.decode_host_points` makes that + choice and is the only place that may: the Flash-Next model package's decode-program builder passes it the MoE + layer windows and the pack's residency flag and fills `Program.host_points` with what it returns, rather than + constructing `HostPoint`s itself. Until that builder lands the helper has no caller, and a program built + without it carries no host points, which is the zero-doorbell form the identity tests need. diff --git a/docs/research/basalt-cpu-expf.md b/docs/research/basalt-cpu-expf.md new file mode 100644 index 00000000..3b65f460 --- /dev/null +++ b/docs/research/basalt-cpu-expf.md @@ -0,0 +1,128 @@ +# basalt's CPU SwiGLU: which `expf`, which order, which NaN + +`runtime/src/basalt_cpu_expf.cpp` is the one piece of arithmetic basalt's CPU expert pool performs itself: +`src/kernels/cpu/pool.cpp:434`, `res = (g / (1.f + std::exp(-g))) * u`. Every other value the pool produces comes +out of the Q2_0 kernels. The port has to return the same bits basalt does, because a token's output has to be the +same number whichever tier produced it, so three things have to be settled rather than assumed: which +implementation of `expf` runs, in which order the three arithmetic instructions execute, and which NaN each one +writes. This records the answers and where they came from. + +Evidence tags: [M] measured, [S] vendor specification, [R] third-party report. + +## 1. Which `expf` + +basalt runs on Linux, so `std::exp` of a float at pool.cpp:434 is glibc's `expf`. Apple's is a different +implementation; neither is correctly rounded, and the two differ at 1,930,129 of the 2,218,786,818 float32 +arguments in [-40, 40] [M, this repository against this machine's own libm, Apple clang 21.0.0 on an M3 Max, so +the count is a property of Apple's `expf` and moves with macOS], so calling the platform's cannot be bit-exact and +the algorithm is transcribed instead. + +glibc's generic `expf` has been Arm's `optimized-routines` `math/expf.c` since 2017 +(`sysdeps/ieee754/flt-32/e_expf.c`) [R]. That source is MIT, where glibc's copy is LGPL-2.1-or-later, so the +transcription is taken from Arm's at `f67e7daa5457646fad9f75580263dba654c988aa` and keeps this tree's licence +position (`third_party/NOTICE`, `third_party/ARM-OPTIMIZED-ROUTINES-LICENSE`). + +### The variant + +glibc's x86-64 multiarch holds a second build of that same source, `__expf_fma`, compiled with `-mfma -mavx2`, and +an ifunc picks it on any host with FMA and AVX2 [M, `expf@GLIBC_2.27` through the PLT resolving to `libm+0x7dc40`, +glibc 2.39-0ubuntu8.9, Xeon Platinum 8375C and 8488C]. Every host that can run basalt's AVX-512 expert kernels has +both features, so `__expf_fma` is the variant basalt runs and the one the port reproduces. + +The two variants are the same function except at the rounding step. Arm writes every multiply-add with operators; +the contraction sites are the three of the polynomial and, once `z = InvLn2N * xd` is substituted, `z + SHIFT` and +`z - kd`. Contracting the polynomial changes nothing at any of the 2^32 arguments [M], because the double carries +29 bits more than the float it rounds back to. Contracting the rounding step changes two: `0x4202422f` and +`0xc27c65d9` [M], because the fused form subtracts `kd` from the unrounded product where the written form +subtracts it from the rounded `z` and is itself exact. `__expf_fma` fuses them; `__expf_sse2` does not and returns +the correctly rounded value there [M, the same hosts with `GLIBC_TUNABLES=glibc.cpu.hwcaps=-AVX2,-FMA`]. The port +writes those two steps as explicit `std::fma` so that `-ffp-contract` cannot decide which function it is. + +Arm's other rounding branch, the `round`/`lround` one, is not glibc's anywhere: glibc 2.39 carries a single +`sysdeps/ieee754/flt-32/math_config.h`, which defaults `TOINT_INTRINSICS` to 0 and defines it nowhere else, so +every architecture's glibc compiles the shift branch the port transcribes [M, lines 40-44 of that file]. It would +be the same function here in any case: `InvLn2N * (double) x` is never exactly a tie at any float32 argument +[M, swept over all 2^32], so no argument reaches the one place the two branches round differently. + +## 2. The Codegen For Line 434 + +x86-64 gcc 14.3, `-std=c++20 -O3 -DNDEBUG`, no `-m` flags, which is how basalt builds `pool.cpp` [M, Compiler +Explorer, with pool.cpp:425-434 kept structurally intact]: + +``` +movss xmm1, [g] ; g +movaps xmm0, xmm1 +xorps xmm0, [.LC27] ; -g, a sign flip (0x80000000), exact +movss [rsp+8], xmm1 ; spill g across the call +call expf ; e = expf(-g), one scalar call +addss xmm0, [.LC28] ; d = e + 1.0f +movss xmm1, [rsp+8] +divss xmm1, xmm0 ; q = g / d +mulss xmm1, [u] ; res = q * u +movss [res], xmm1 +``` + +Three single-precision instructions, no fused multiply-add (there is no multiply feeding an add in the +expression), one scalar `expf` call. With `-march=x86-64-v3` the same sequence appears as the VEX encodings, so +the bits do not depend on which of basalt's build configurations compiles the pool [M]. + +The operand order is the compiler's, not the source's, and it decides the NaN. In Intel syntax the destination is +SRC1: the add takes `e` as SRC1 and the constant as SRC2, which is the source's operands swapped and is exact +since addition commutes and `1.f` is never a NaN; the divide takes `g`, which does not commute; the multiply takes +the quotient, which is the one that could have gone either way. + +## 3. Which NaN + +x86 writes the floating-point indefinite `0xffc00000`, sign bit set, where AArch64 writes the default NaN +`0x7fc00000` [S, Intel SDM Vol. 1 4.8.3.7; S, Arm ARM A1.5.3]. An SSE scalar arithmetic instruction handed a NaN +returns the first of its sources that is one, quieted, and otherwise the indefinite when the operation itself +creates one. So: + +* `g` = -inf gives `e` = +inf, `d` = +inf and `-inf / inf` at the divide: `0xffc00000`. +* The add never creates one. Its only invalid form is `inf + -inf`, and `e` is `expf`'s own return, which is + never negative at any of the 2^32 arguments [M]. It is written as the instruction for fidelity to what basalt + executes, and the recorded vectors cannot tell it from the C operator. +* `0 * inf` and `inf * 0` at the multiply: `0xffc00000`. Several recorded rows reach it, including + `g` = `0xc2b17218` (just past the overflow threshold, where `g / inf` is a signed zero) with `u` = +inf. +* A NaN argument comes back quieted with its payload and sign: `expf` returns `x + x`, which quiets on both + architectures, and then the divide returns its first source. `0x7f812345` gives `0x7fc12345`. +* With a NaN `g` and a NaN `u` the multiply keeps the quotient's payload, not `u`'s. + +`expf` itself needs no help, since `x + x` is the same on both. The add, the divide and the multiply are written +as the x86 instructions rather than as C operators (`x86_add`, `x86_div`, `x86_mul` in the kernel). + +One corner of the SSE rule is outside the recorded corpus. SSE returns the first source operand that is a NaN, +where an AArch64 instruction prefers a signalling NaN wherever it sits; the two part only when SRC1 is a quiet NaN +and SRC2 a signalling one, and no recorded row holds that pair. Case D3 asserts it [S] against the two manuals +rather than against a measurement, and says so. + +## 4. The Fixtures + +Two recorded files under `tests/kernels/fixtures/`, both measured on Compiler Explorer's x86-64 executors (Xeon +Platinum 8375C and 8488C, AVX-512) under glibc 2.39 = Ubuntu 24.04 libc6 2.39-0ubuntu8.9, libm build-id +`d53fcbff9f855463606b25cfbe2a2e10856ea3a7`, MXCSR control `0x1f80` [M, 2026-10-18]. Each carries its own +provenance in its header comment. + +`swiglu_vectors.txt`, 4,226 rows of `g u res` as binary32 bit patterns: basalt's whole line, built as basalt +builds it. 57 special `g` against two `u` (the thresholds, the two arguments of section 1, zeros, infinities, +quiet and signalling NaNs, subnormals), 16 special-`u` pairs, and 4,096 random pairs with `|g| < 40` and most of +their mass near zero. Six runs across the two CPUs agree, and every run's own digest of the `res` column is +`dfdc90ecf37deba2`. Test case A2 holds every row. + +`expf_digests.txt`, 4,096 digests: `expf` at every one of the 4,294,967,296 float32 arguments. Block k covers bit +patterns `k << 20 .. (k << 20) | 0xfffff` in increasing order, and its digest is the FNV-1a of the result bits, +`h = 0xcbf29ce484222325` then `h = (h ^ bits) * 0x100000001b3 mod 2^64` per argument. The trailer carries the two +blocks `__expf_sse2` digests differently, `0x420` and `0xc27`, which are the blocks holding the two arguments of +section 1. Test case B4 holds every block, through `_native.basalt_expf_digest`. + +## 5. What The Port Reproduces + +[M, this repository on a 48 GB 40-core M3 Max, Apple clang 21.0.0 at `-O2 -ffp-contract=off`]: + +* All 4,096 blocks of `expf_digests.txt`, so `expf_glibc` is `__expf_fma` at every float32 argument. +* All 4,226 rows of `swiglu_vectors.txt`, including every NaN row, and the digest of its own `res` column is + `dfdc90ecf37deba2`. Blocks 0x7f8-0x7ff and 0xff8-0xfff of the digest sweep are `expf`'s own output at all + 16,777,214 NaN arguments, so glibc's NaN bits are pinned too. +* Built with the rounding step unfused instead, it fails exactly blocks `0x420` and `0xc27`, and its digests at + those two blocks are the trailer's `__expf_sse2` digests exactly. The port is therefore either variant, and the + only thing that separates them is the two `std::fma` calls. diff --git a/docs/research/basalt-cpu-pool.md b/docs/research/basalt-cpu-pool.md new file mode 100644 index 00000000..508a8444 --- /dev/null +++ b/docs/research/basalt-cpu-pool.md @@ -0,0 +1,236 @@ +# basalt's CPU expert pool: the queue, the orders, and where its host point goes + +`runtime/src/basalt_pool.{h,cpp}` transcribes basalt's CPU expert pool (`src/kernels/cpu/pool.cpp` and +`include/basalt/kernels/cpu/pool.hpp` @ `b4c63b55754637f4c72ad53a0f791d425f71eb36`). The pool is the host half of +the expert tier: a set of spinning worker threads the host drives one batch at a time, so that an expert without a +resident GPU copy is computed on the CPU while the GPU runs the experts that do have one. + +Nothing bitwise depends on the pool, which is section 2 below, so what a transcription has to reproduce exactly is +its **synchronisation**. Getting that wrong does not give different numbers. It gives a run that hangs, or one that +computes a job twice. This note records the three things the port rests on: the queue and its claim protocol, every +memory order with its argument, and where the pool's work sits in a Metal step. + +Evidence tags: [M] measured, [S] vendor specification, [R] third-party report, [H] hypothesis. A line marked +**Inference** is read off basalt's source rather than stated by it. + +## 1. The pool + +### 1.1 The queue is one word + +There is no ring and no lock. The header gives both reasons, verbatim (`pool.hpp:7-11`): "A lock-free SPMC ring is +what you need when jobs arrive while others are still being computed. Here they cannot: the host must SUM all ten +outputs before the next layer starts, so a layer is a barrier by construction and the queue never holds more than +one batch." + +The whole queue is therefore one 64-bit word (`pool.cpp:22-24`, `pool.hpp:229`): + +```cpp +constexpr uint64_t pack_head(uint32_t epoch, uint32_t n, uint32_t i) { + return ((uint64_t) epoch << 32) | ((uint64_t) n << 16) | (uint64_t) i; +} +alignas(64) std::atomic head_{0}; // epoch << 32 | njobs << 16 | next index +``` + +Publishing is `begin_batch` (`pool.cpp:338-350`), in this order and no other: the completion counter is reset, the +epoch the host is about to use is computed, the word is stored with a release, and only then are sleepers notified. +basalt states why the reset is safe where it sits, verbatim: "Every job of the previous batch has completed +(`wait_done`), and a claim of it can no longer succeed, so nothing adds to `done` until this batch's first claim, +which the release below orders after the reset." + +A claim (`pool.cpp:327-336`) is a compare-exchange on that word which **succeeds only for the epoch the worker woke +for**. A late worker's claim simply fails. + +**Why the epoch is in the word.** A worker that went to sleep is still counted as parked when it wakes. Trace +`worker` (`pool.cpp:296-325`): it leaves the spin loop, re-reads `seen = epoch_.load(acquire)`, and only then does +`parked_.fetch_sub`. In the gap between those two the host may read `parked_ == n_`, pass its next pre-phase +barrier and publish batch k+1, so the worker enters `drain` holding epoch k while `head_` already carries k+1. The +park barriers narrow that window; they do not close it. + +basalt's stated reason for the epoch is that such a worker could otherwise claim from the next batch while the +host was still writing it, run a job twice, or add to `done` after the host had reset it (`pool.hpp:18-23`). In +this port the last two are not reachable even with the epoch test removed, because three other mechanisms hold: +the claim's acquire of `head_` synchronises with `begin_batch`'s release and the batch description is written +before that release, so a late claimant reads the correct body; the index compare-exchange hands out each job +exactly once, so no job runs twice; and `wait_done` has observed every increment of the previous batch before +`begin_batch` resets the counter, so no increment lands after a reset. A late claim therefore lands on the next +batch as an early and correct participant in it. **Inference** from those three sites, consistent with the +mutation measurement in section 4. + +The epoch test is kept because this is a 1:1 transcription of basalt's protocol. A port that drops it is relying +on the three mechanisms above rather than on the protocol, which is a different guarantee. + +### 1.2 The park: spin, then sleep + +A worker arrives at the park **before** its first wait (`pool.cpp:284`), with the reason verbatim (`:280-283`): +"ARRIVE at the park before the first wait, so `parked_ == n_` is true from construction. Counting only on the +RETURN from a drain leaves `parked_` at 0 until each worker has finished one batch, and the first `run()`, which +waits for `parked_ == n_` before publishing, then deadlocks." + +The park loop (`pool.cpp:296-315`) spins on `epoch_` with an acquire load, checks `stop_` each iteration, reads the +clock once every 1024 iterations, and once it has spun for `spin_before_sleep_` takes the sleep mutex and blocks on +the condition variable. + +### 1.3 A phase: two barriers around the batch + +Verbatim (`pool.hpp:13-16`): "`run()` waits for `done == n` AND for every worker to PARK. Waiting only for `done` is +not enough: a worker can still be inside the drain loop after its last `done` increment, and the host resetting +`head` underneath it would let that worker claim a job from the NEXT batch before the next batch has been +published." + +So a phase is `wait_parked`, publish, the host's own drain when it works, `wait_done`, `wait_parked` +(`pool.cpp:476-486`). A wait that sees no progress for `kStall` is a bug: basalt prints, releases its GPU waits and +calls `std::abort()` (`pool.cpp:362-368`). + +### 1.4 The constants this port carries + +| Constant | Value | Where | What it governs | +|---|---|---|---| +| `kSpinBeforeSleep` | 20 ms | `pool.hpp:184`, held as microseconds at `:239` | how long a parked worker spins before it blocks on the condition variable | +| `kStall` | 60 s | `pool.hpp:187` | "A pool wait that sees no completion for this long is a bug; the engine stops with a message instead of spinning forever, and the server starts it again" | +| spin sample period | 1024 iterations | `pool.cpp:301`, `:359`, `:382` | `if ((++spins & 1023u) != 0) continue;`, how often any spin reads the clock | +| `kMaxSplitMulti` | 96 | `pool.hpp:157` | the multi-token job limit; `run_split_multi_native` batches in chunks of it (`pool.cpp:547-548`) | +| `MAXT` | 8 | `expert.hpp:122` | tokens per job | +| `kParked`, `kSleeping`, `kBetween` | -1, -2, -3 | `pool.hpp:224-225` | worker diagnostic states | +| `kIdle`, `kWaitParked`, `kWaitDone` | -10, -11, -12 | `pool.hpp:224-225` | host diagnostic states | +| tasks per phase | `3 * threads` | `pool.cpp:524`, `:552` | "about three tasks per thread in each phase, so the tail is short" (`:494`) | +| batch size limit | `0xffff` | `pool.cpp:339` | the job count occupies 16 bits of the word, so a larger batch would overflow into the epoch | +| cache-line padding | `alignas(64)` | `pool.hpp:229-233`, `:236`, `:246`, `:255`, `:257` | each hot atomic on its own line; this chip's line is 128 [M] | + +### 1.5 Every memory order + +| Variable | Writes | Reads | +|---|---|---| +| `epoch_` | `fetch_add` **seq_cst** (`:271`), host only | **acquire** in the park test (`:298`) and after it (`:314`); **seq_cst** inside the condition-variable predicate (`:307`); **relaxed** in `begin_batch` (`:346`) | +| `head_` | **release** store (`:347`); CAS **acq_rel**, **acquire** on failure (`:333`) | **acquire** (`:328`) | +| `done_` | **relaxed** store 0 (`:345`); `fetch_add` **release** (`:472`, `:613`) | **acquire** (`:379`) | +| `parked_` | `fetch_add` and `fetch_sub` **acq_rel** (`:284`, `:315`, `:323`) | **acquire** (`:357`) | +| `stop_` | **release** (`:259`) | **relaxed** (`:299`, `:307`), **acquire** (`:312`) | +| `sleepers_` | `fetch_add` **seq_cst** (`:305`), `fetch_sub` **relaxed** (`:309`) | **seq_cst** (`:272`) | +| worker and host diagnostic states | **relaxed** (`:304`, `:310`, `:320`, `:322`, `:353-354`, `:402-403`) | default, in the diagnostic dump only | +| the batch description | plain stores by the host before `begin_batch` | plain loads by workers after the acquire | + +Two of these carry arguments that break if weakened. + +**The seq_cst pair is the lost-wakeup argument.** A worker going to sleep increments `sleepers_` and then reads +`epoch_`; the host increments `epoch_` and then reads `sleepers_`. Both pairs are seq_cst, so in one total order at +least one side sees the other's write: either the worker sees the new epoch and does not sleep, or the host sees +the sleeper and notifies under the mutex the worker holds until it is inside `wait`. The store-buffer interleaving +in which neither sees the other is exactly what seq_cst forbids. basalt's comment says this costs x86 nothing; on +arm64 it is not free, and the cost is visible in one instruction. Compiled here, the pair emits `ldaddal` followed +by `ldar`; written with `acq_rel` and `acquire` the same pair emits `ldaddal` followed by `ldapr`, the weaker RCpc +acquire load [M, Apple clang 21.0.0, -O2, arm64 on an M3 Max]. No `dmb` appears in either, so the whole difference +between a correct publish and a lost wakeup is `ldar` against `ldapr`: `ldar` orders against the preceding +`ldaddal` and `ldapr` does not. `acq_rel` would not suffice. + +**The batch description is plain, and nothing else orders it.** **Inference** from the table's last row: the +description is made visible solely by the release store of `head_` and the matching acquire load in `claim`, plus +the seq_cst epoch bump. A port that publishes the description after the epoch, or that reads it before the +acquire, is a data race. The port's first draft read it at the top of `drain`, before the claim, and every property +test passed over it; ThreadSanitizer named both sides (`tools/tsan/`). + +The header states why each hot atomic is padded, verbatim (`pool.hpp:217-221`): "`head_`, `done_`, `parked_` and +`epoch_` are the four that workers and the host actually contend on; sharing a cache line they would invalidate +each other on every access. The line the host must WRITE to publish work (`epoch_`) and READ to confirm the workers +are parked (`parked_`) must not be hammered by the very threads waiting for it, so the parked spin carries no +counter (a locked read-modify-write per iteration) and `alignas(64)` stops the four sharing." + +## 2. What does not reach the output + +The promise (`pool.hpp:54-55`), verbatim: "Every token's output is bitwise the single-token job's." So the thread +count, the thread placement, and the order in which jobs are claimed do not reach the numbers. Four independent +facts make that true, and a port has to reproduce all four: + +1. **Per token, inside the kernel.** The accumulators are per token and the block loop order does not depend on the + token count, so a row's value for a token is the same for every grouping of tokens into jobs + (`src/kernels/cpu/expert.cpp:503-541`). +2. **Per row, across tasks.** The row ranges partition the expert's rows exactly and at row granularity, and the + upper bound clamps at the expert boundary, so every (expert, row) pair is computed whole, by exactly one task, + whatever the task count, the worker count, or the claim order are. **Inference** from `pool.cpp:418-421`, + `:450`. +3. **The intermediate is quantized serially, from the whole vector.** The re-quantization of the gated activation + runs on the host thread after the phase's park barrier, over all `FF` values at once (`pool.cpp:557-559`), so + its chunk scales do not depend on how the phase was split. **Inference.** +4. **The activation is shared, not recomputed.** One quantized activation per token per layer, built by the caller + and pointed at by every job (`src/core/expert_source.cpp:1588-1598`); the pool never re-quantizes its input. + +The only arithmetic the pool itself performs is the SwiGLU at `pool.cpp:434`, which is elementwise and so +split-invariant by construction. It is also the one place a transcription can diverge from basalt, because +`std::exp` is libm and glibc's differs from Apple's: that divergence is per element, not per split, and +`docs/research/basalt-cpu-expf.md` settles it. + +## 3. The Metal mapping + +### 3.1 The two decode forms + +basalt compiles its decode graph **twice** and picks between the two on one flag, `all_resident_` +(`src/core/verify.cpp:876-907`): + +* With every expert resident it runs the **zero-doorbell** graph. The whole step is on the GPU and the host + services nothing. +* When the cache comes up short it runs the **DecMoe** graph, whose window services every MoE layer, every window, + whether or not that layer has a CPU entry. + +This is not a performance detail. Each host handoff idles the GPU for a median of 136 to 137 microseconds as built, +against 0.5 microseconds at a plain pass boundary (`docs/design/flash-next.md`, `probes/p16_host_handoff`) [M]. At +48 MoE layers that is 6.5 to 6.6 milliseconds per step, spent whether or not a layer has any CPU work to do. So a +port that installs a point in every MoE layer unconditionally is not a slow exact port: it is a **different +program** from the one basalt runs in the identity configuration, and it spends that idle to be different. + +The program is built per session from the pack and the profile, so the choice is made once at build time, not by a +predicate the step evaluates. `monolith/compiler/cpu_tier.py` is where it lives: `decode_host_points` returns an +empty list when every expert is resident, and one point per MoE layer when the cache is short. + +### 3.2 Where the point goes + +`HostPoint` (`monolith/runtime/program.py`) carries `task`, `publish`, `wait`, `writes` and `reads`, with the +semantics stated there verbatim: "The task starts once ops [0, publish) of the step have completed (publish 0: once +the previous step completed), and the GPU work from op `wait` on starts after it returns (wait = len(ops): the next +step's). publish == wait makes a sync point. `writes` and `reads` name the buffers the task touches; the ops that +may run beside it, [publish, wait), must not race them (Program.check_host_points)." + +Mapping basalt's decode caller, the verify loop's per-layer flag wait (`verify.cpp:2549-2610`): + +| basalt | the port | +|---|---| +| the per-layer flag wait, the pool call, the fence, the flag raise | one host point per MoE layer: `publish` after the layer's routing and planning op, `wait` at the combine, so the layer's **resident** experts are the `[publish, wait)` ops that run beside the pool. Without ops in that window the GPU idles for the whole of the task | +| the `seq_cst` fence and `_mm_sfence()` before raising the flag (`verify.cpp:2587-2588`) | not needed at the point, but **only because the pool's own release/acquire pair is kept**. The rows are written by the workers, not by the pump, so the chain is: a worker's stores to its output rows, then its `done_` increment with release (`pool.cpp:472`), then the pump's acquire load in `wait_done` (`:379`), then the task returns, then the pump commits the command buffer that reads them. basalt states the requirement for the host's own copy of it, verbatim (`pool.cpp:603-604`): "The host's `done_.fetch_add` is a release for the same reason a worker's is: `j.out` is read by the device after `run()` returns, so the write must be published, not merely performed." A port that made `done_` a plain counter would break GPU visibility, not just the wait | +| `h_ymiss_`, the mapped staging the pool writes (`verify.cpp:750`) | the point's `writes` names that staging buffer, so `check_host_points` refuses any `[publish, wait)` op that reads it | + +The prompt path's shape differs: its window spans the GPU's own expert ops, so the planning that builds the jobs +has to happen at an earlier point or on the host before the step, because the GPU ops in the window read those +tables. + +### 3.3 What this port changes, and why none of it is a numeric difference + +* **A stall reports instead of aborting.** basalt calls `release_gpu_waits` then `std::abort()`; the port returns + false with a message, which the host task turns into an error the engine raises. A stalled pool is **poisoned**: + its workers may still hold pointers into buffers the caller is about to free, so it is never destroyed and never + reused, which is what `abort()` buys basalt for free. +* **The stall clock is armed once per wait** rather than every 2^32 spins. The transcribed spin body costs 0.422 ns + here, so 2^32 iterations is 1.8 s against a 60 s limit and the abort could never fire [M]. +* **The worker count and the spin-before-sleep come from the chip profile.** basalt derives the count from a Linux + CPU topology this platform does not expose, and no placement control here is more than a hint. +* **Each worker's scratch is owned by the pool and indexed by worker id**, where basalt uses function-local + `thread_local` arrays. On Darwin each such access goes through the thread-local-variable descriptor and allocates + lazily on first use [M]; the buffers are scratch, so this is invisible to the output. +* **The hot atomics are padded to 128 bytes**, which is this chip's cache line, where basalt pads to 64 [M]. +* **A second concurrent driver is refused.** basalt's pool has one host thread and needs no such flag; here the + Python bindings release the GIL and the host task runs on the pump, so two native drivers of one pool are + reachable, and two of them race on the batch description. + +## 4. What is measured, and what rests on the transcription + +The property suite (`tests/kernels/test_basalt_pool.py`) asserts that each job of a phase runs exactly once, under +the schedules that break a wrong implementation. It was mutated to find its limits, and the answer is sobering: +removing the epoch test from `claim`, removing either park barrier, removing both, and removing all three together +each leave every case passing, over 4,000 phases of 8 jobs [M]. Two reasons, and only the first is about the test: +the windows these protections cover are nanoseconds wide and a trivial job never schedules into them; and for the +epoch test specifically, the analysis in section 1.1 finds its removal produces a late claim that is harmless +here, because the acquire on `head_`, the index compare-exchange and `wait_done`'s ordering against the reset +each still hold. A null result against that mutation is therefore what the code predicts rather than a gap in the +suite's reach. + +ThreadSanitizer (`tools/tsan/`) reads the happens-before edges directly and is the instrument for the rest. It +found the real ordering defect the property suite passed clean over. It does **not** catch weakening the written +memory orders to `relaxed`, which produces no warning and no wrong result over 300 phases of 16 jobs [M]. Those +orders rest on the transcription and on the arguments recorded in section 1.5, not on a test. diff --git a/docs/research/basalt-cpu-q2.md b/docs/research/basalt-cpu-q2.md new file mode 100644 index 00000000..a40fe371 --- /dev/null +++ b/docs/research/basalt-cpu-q2.md @@ -0,0 +1,283 @@ +# basalt's CPU Q2_0 expert kernels as x86 compilers compile them + +What GCC and Clang emit at every rounding site of basalt's two CPU expert kernels, `act_quant_q8_1` and +`q2_0_gguf_rows_multi`, and the ARM NEON form the port writes at each site. basalt computes an expert on the CPU +when the GPU cache misses it, so these two kernels carry the CPU tier's whole arithmetic. This page is the +authority `runtime/src/basalt_cpu.cpp` follows, as `docs/research/basalt-nvcc/matvec.md` is for the GPU kernels. + +Basalt paths are relative to commit `b4c63b55754637f4c72ad53a0f791d425f71eb36`; `path:a-b` means lines a to b +there, and a bare `:N` is a line of the file named last. Tags: **[M]** measured here, **[S]** a vendor +specification or a compiler's own header, **Inference:** a conclusion drawn from reading code. + +## The sources + +`src/kernels/cpu/expert.cpp:143-148` (`unpack64_q2_0`), `:336-370` (`act_quant_q8_1`, the AVX-512 block; the +function returns at `:369`, so the scalar loop at `:371-397` is unreachable) and `:503-556` (`q2g_row_multi`, +`q2g_rows`, `q2_0_gguf_rows_multi`), with `include/basalt/kernels/cpu/expert.hpp:25-61` for `ActQ` and the +geometry. `src/kernels/cpu/expert_layout.cpp:124-133` routes this pack to them wherever AVX-512 is present. + +## 1. Which compiler, and the values that depend on the answer + +basalt pins no compiler: `README.md:35-43` asks for "CMake 3.24 or newer and a C++20 compiler" and builds with a +bare `cmake -S . -B build`; `CMakeLists.txt` sets no `CMAKE_CXX_COMPILER` and only `-Wall -Wextra` (`:45-46`). What +it does pin is the build type and the ISA: `:12-14` forces `CMAKE_BUILD_TYPE=Release` when the caller names none, +so these kernels compile at CMake's `CMAKE_CXX_FLAGS_RELEASE`, `-O3 -DNDEBUG` — the flags come from CMake's own +default, not from basalt's file — and `:673-674` gives `expert.cpp` alone +`-mavx512f -mavx512bw -mavx512vl -mavx512dq -mavx512vnni -mavx512vbmi -mf16c -mfma`. Both matter to what follows: +the optimisation level changes which FMA form GCC emits (section 6). +`_mm512_reduce_add_ps` and `_mm512_reduce_max_ps` are header-defined, so their lane trees come from whichever +compiler builds basalt. Both candidates were read, and both were cross-compiled and their x86 output inspected [M]: + +- **GCC** `gcc/config/i386/avx512fintrin.h` (`releases/gcc-14`): the float `__MM512_REDUCE_OP` at `:16297-16306`, + used by `_mm512_reduce_add_ps` at `:16308-16312`, and the max form at `:16339-16350`, used by + `_mm512_reduce_max_ps` at `:16359-16364` [S]. +- **Clang** `avx512fintrin.h:9448-9450` and `:9579-9581`: `__builtin_ia32_reduce_fadd_ps512(-0.0f, __W)` and + `__builtin_ia32_reduce_fmax_ps512(__V)` [S], which lower to the same shape. + +Both expand to the same four-level pairwise tree, so the **grouping is compiler-independent**: + +``` +R_add(v[0..15]): u[j] = v[j] + v[j+8] (j=0..7); t[j] = u[j] + u[j+4] (j=0..3) + a = t[0] + t[2]; b = t[1] + t[3]; res = a + b +R_max(v[0..15]): u[j] = maxps(v[j+8], v[j]); t[j] = maxps(u[j+4], u[j]) + p = maxps(t[0], t[2]); q = maxps(t[1], t[3]); res = maxps(p, q) + where maxps(a, b) = (a > b) ? a : b [S] Intel SDM, MAXPS Operation +``` + +The sum is identical under both because the **grouping** is, not because addition commutes: a reduction's bits +follow its association. Clang's `reassoc llvm.vector.reduce.fadd` licenses any association [M], so that agreement +is a measurement to re-check rather than a guarantee. The grouping is all that a **numeric** result depends on; +the per-node operand order decides a **NaN** one, and that order is not even fixed within one binary — GCC treats +`+` as commutative and reassigns the add tree's registers per token and per `NT`, so a row that makes a NaN has a +different answer in token slot 0 of an `NT = 2` job than in a single-token job, and a different one again under +another GCC version (section 6, [M] `pr21-x86-ground-truth.md:258-342`). So `amax` is **not** the only +compiler-dependent value, as this section first claimed: the add tree's operand order is a second, and +`p = d * scale`'s a third (GCC emits `SRC1 = dd`, Clang `SRC1 = scale`). The other two are invisible to a NaN +activation, since `act_quant_q8_1` never writes a NaN; they are reached by a NaN fp16 block scale or by a forged +`ActQ`. `amax` is the one a NaN activation reaches: +GCC's first two levels take `src1 = hi` as written above, Clang's +take `src1 = lo`, and MAXPS returns SRC2 on an unordered compare. The port writes GCC's order, since basalt is +Linux-only (`AGENTS.md:3`, `README.md:33`), so its default `c++` is g++ (**Inference**); `runtime/src/basalt_cpu.cpp` +records both orders, and `tests/kernels/test_basalt_cpu_q2.py` case A6 asserts one while printing the other, so the +choice flips in one line if basalt's build is ever shown to be Clang. Clang's `fmax` reduction carries `nnan`, so +under Clang that value is undefined for a NaN chunk rather than merely differently ordered, and the low-half tree +is the measured realisation of it [M]. + +## 2. The one output whose bits may differ + +`res[t]` can differ where the kernel **generates** a NaN from operands that are not NaN. An infinite activation +element gives its chunk `scale = +inf`, and then `d * scale` with `d = ±0`, the accumulator's fused multiply-add on +a lane whose four codes are all zero, the same on the correction, or `inf - inf` in the final subtraction each +produce one. AArch64 writes its default NaN, `0x7fc00000` [M]; x86 writes the floating-point indefinite, +`0xffc00000`, with the sign bit set ([S] Intel SDM Vol. 1 4.8.3.7 and Table 11-1; **[M]** on a Xeon Platinum 8488C +running basalt's own kernels, `pr21-x86-ground-truth.md:22-32`, after this note was first written without an +AVX-512 machine). `act_quant_q8_1` cannot emit one, since +`amax > 0` is an ordered compare and `s = inf` requires an infinite lane, whose `sum <= -127` makes +`hx = s * sum = -inf` rather than `inf * 0`. The port's comparison was therefore bitwise everywhere and NaN-ness on +`res`; **section 6 closes that carve-out**, since the x86 bits are fixed at every site, and the port now computes +them — `runtime/src/basalt_cpu.cpp`'s `x86_row()` recomputes any NaN `res[t]` under x86's rules, and the tests +compare all 32 bits. + +## 3. The floating-point environment + +`grep -rn "setcsr|FLUSH_ZERO|DENORMALS_ZERO|ffast-math|Ofast|ffp-contract|crtfastmath|_MM_SET_"` over basalt's +`CMakeLists.txt`, `src` and `include` returns nothing [M], so basalt runs on the default MXCSR: round to nearest +even, every exception masked, flush-to-zero off, denormals-are-zero off (**Inference** from that absence plus the +x86-64 ABI default). macOS on arm64 leaves FPCR at 0 (round to nearest, flush-to-zero off), so subnormals survive on +both sides and the subnormal-scale case of section 4 is reachable here too. + +## 4. The quantizer's reachable edge cases + +`s = amax > 0 ? amax / 127 : 0` and `inv = s > 0 ? 1 / s : 0`, then `t = x * inv`, `r = t + copysign(0.5, t)` and +`VCVTTPS2DQ` (`expert.cpp:352-362`). The conversion returns the **integer indefinite** `0x80000000` for a NaN, for +either infinity and for anything outside int32 ([S] Intel SDM Vol. 1, Table 11-1 and D.4.2.2), which the clamp to +[-127, 127] then takes to **−127**, never +127. Three consequences, all reachable from finite input: + +- A chunk whose `s` falls at or below `2^-128` has `inv = +inf`, so its zeros give `0 * inf = NaN` and its nonzeros + `±inf`: **every code is −127**, zeros included. +- An infinite element gives `s = inf`, `inv = 0` and `t = inf * 0 = NaN`: that element is −127 while the finite + ones, including `−0`, take the `>= 0` branch and give 0. +- `amax` at or below `63 * 2^-149` rounds `s` to zero, so `inv = 0` and every code is 0. From `64 * 2^-149` the + quotient rounds up to the subnormal `s = 2^-149`, which falls in the `inv = +inf` band above [M]. + +The +127 side of the clamp needs a NaN in the chunk, which lets the `reduce_max` tree swallow the true peak: +`x = 0.1` everywhere with `x[4] = 0.11` and `x[16] = NaN` gives `amax = 0.1`, so `x[4]` scales to `r = 140.2` and +clamps to `+127` [M]. Without a NaN it is inert: wherever `inv` is finite, `|x| <= amax` holds `r` at 127.50003 or +below [M], measured at the exhaustive worst case in case A8. ARM's `FCVTZS` **saturates** instead (NaN gives 0, `+inf` gives +`INT32_MAX`), which after the clamp would give code 0 and +127 where x86 gives −127 for both, so the port selects on +`vcagtq_f32` against `2^31` and substitutes `INT32_MIN` itself. + +## 5. Where NEON is not x86 + +| x86 | NEON | Why they differ | +|---|---|---| +| `_mm512_and_ps(x, 0x7fffffff)` | `vabsq_f32` | identical | +| `_mm512_max_ps`, every node of the trees | `vbslq_f32(vcgtq_f32(a, b), a, b)` | `vmaxq_f32` returns the NaN and `vmaxnmq_f32` the number; MAXPS returns SRC2 on any unordered compare and on `(±0, ∓0)`. The select is MAXPS exactly, and it keeps the operand order of section 1 visible | +| `_mm512_reduce_add_ps`, `_mm512_reduce_max_ps` | the explicit four-level trees | `vaddvq_f32` gives `(t0+t1)+(t2+t3)` where x86 gives `(t0+t2)+(t1+t3)`, and `FMAXV` has the wrong NaN rule | +| `_mm512_mul_ps` then `_mm512_add_ps` | `vmulq_f32` then `vaddq_f32`, built `-ffp-contract=off` | two roundings; a contracted `fma` skips the rounding of `t` and changes codes. Apple clang keeps them apart at its default while they are separate statements and fuses them under `fast` [M], so the flag pins the guarantee | +| `_mm512_fmadd_ps` (`acc`, `corr`) | `vfmaq_f32` | one rounding; fusion is required here, which is why contraction is disabled on the file and not globally | +| `_mm512_cvttps_epi32` | `vbslq_s32(vcagtq_f32(2^31, r), vcvtq_s32_f32(r), INT32_MIN)` | section 4 | +| `_mm512_dpbusd_epi32` | `vdotq_s32` | SDOT is signed by signed, VPDPBUSD unsigned by signed, equal here because codes are 0..3. NEON vector `j` lane `k` is the x86 dword lane `4j + k` | +| `_mm512_multishift_epi64_epi8` | `vqtbl1q_u8`, `vshlq_u8`, `vandq_u8` | the port decodes the documented rule `code m = (qs[m / 4] >> 2 * (m % 4)) & 3` (`ggml/src/ggml-quants.c:220-222`), which is what VPMULTISHIFTQB produces | +| `_mm256_cvtph_ps` | `vcvt_f32_f16` | both exact for every half including subnormals at the defaults of section 3 [M] | +| `_mm512_cvtepi32_epi8`, `_mm512_reduce_add_epi32` | `vmovn_s32` with `vmovn_s16`, `vaddvq_s32` | exact after the clamp; the integer sum is order-independent (`abs(sum) <= 4064`) | + +## 6. Which NaN each site returns, and where x86 and AArch64 part + +This section supersedes three claims made earlier here: section 1's "only compiler-dependent value" (the operand +order of `p = d * scale` and of the add tree are two more, reachable not from a NaN activation but from a NaN fp16 +block scale or a forged `ActQ`), section 2's carve-out that the port's comparison is NaN-ness rather than bits on +`res`, and section 2's "[M, both measured]" on the x86 indefinite. The emitted form governs, not the written one: +GCC's `avx512fintrin.h:16297-16306` writes the add tree's level 3 as `__T6 + __T7`, and GCC emits `vaddps` with +`__T7` as SRC1. + +**How the output was obtained.** This section was first written without an AVX-512 machine, so its x86 *results* +were **[S]**, the SDM's rule applied to an instruction form that was itself **[M]**: one translation unit, +`include/basalt/kernels/cpu/expert.hpp` followed by `src/kernels/cpu/expert.cpp`, the two functions byte-identical +to the originals (`diff` over `:336-400` and `:500-560`), through the Compiler Explorer API +(`POST godbolt.org/api/compiler/g142/compile`, and `g144`) with **`-O2`** `-std=c++20 -Wall -Wextra` plus basalt's +per-file flags (`CMakeLists.txt:673-674`), Intel syntax, so the first register after the destination is SRC1. + +They are now **[M]**. The PR #21 reviewer ran basalt's own `act_quant_q8_1` and `q2_0_gguf_rows_multi`, verbatim, +on a Xeon Platinum 8488C (AVX-512) at basalt's Release flags — **`-O3 -DNDEBUG`** plus the `-m` list — under GCC +12.5, 13.4, 14.3, 14.4, 15.2 and 15.3, with per-instruction operand probes, end-to-end fixtures, a ~700,000-case +differential and a lane-level scalar model that reproduces the real kernel with **0 mismatches in 62,374 outputs** +on each of four GCC versions: `pr21-x86-ground-truth.md` (`.context/basalt-port/pr21-ground-truth/`, cited below +as `GT:`). Where that measurement and the `-O2` inference below disagree, the measurement governs and the +row says so. The AArch64 column was measured on an +Apple M3 Max, macOS 27.0.1, FPCR = 0 (DN = 0, FZ = 0) [M], with single-instruction probes and with +`reduce_add_ps` replayed verbatim from `runtime/src/basalt_cpu.cpp`. Probe inputs must be `volatile`: +LLVM's constant folder does not follow FMLA's NaN rule and folds case A below to x86's answer [M]. + +**x86's two rules** [S]. For the two-source instructions (`VMULPS`, `VADDPS`, `VSUBPS`, `VADDSS`, `VSUBSS`, +`VMULSS`), Intel SDM Vol. 1 Table 4-7, "Rules for Handling NaNs": two QNaNs give the "First source operand", two +SNaNs or a mixed pair give the first source operand converted to a QNaN, and the table's note fixes which that is +— "For AVX instructions, the first source operand is usually the 2nd operand in a non-destructive source syntax". +`MAXPS` is the documented exception (section 5). For the FMA instructions, Vol. 1 §14.5.1 maps the mnemonic's three +digits onto the arithmetic equation — first digit the multiplicand, second the multiplier, third the addend, each +naming an operand position — and Table 14-17 gives the priority as **x (multiplicand), then y (multiplier), then z +(addend)**: `Q(x)` whenever x is a NaN whatever y and z are, `Q(y)` when only y and z can be, `Q(z)` only when +neither multiplicand nor multiplier is a NaN. When a NaN is **created** rather than propagated — `INF * 0`, or +`x*y` and `z` infinite with opposite signs — Table 14-17 gives `QNaNIndefinite`, defined there as "the QNaN which +has the sign bit equal to 1, the most significand field equal to 1, and the remaining significand field bits equal +to 0", i.e. `0xffc00000`. For the two-source instructions the definitive source is Table 11-1, "Masked Responses of +SSE/SSE2/SSE3 Instructions to Invalid Arithmetic Operations" (§11.5.2.1, and Intel AVX follows SSE here per +§4.8.3.5): "Addition of opposite signed infinities or subtraction of like-signed infinities → Return the QNaN +floating-point Indefinite" and "Multiplication of infinity by zero → Return the QNaN floating-point Indefinite" +— §4.8.3.7 names that value, and Table 14-17's quoted definition gives its bits. The same table fixes `MAXPS` +("Return the source 2 operand value") and the integer indefinite of section 4. The indefinite's bits do not +depend on the compiler, the instruction form or the operand order. + +**AArch64's two rules** [M, this machine]. `FADD`/`FSUB`/`FMUL` return op1's NaN when both sources are NaNs +(`fadd A, B` → A, `fadd B, A` → B), the same first-source rule as x86. Vector `FMLA Vd, Vn, Vm` (`vfmaq_f32`) +returns the **addend** first, then Vn, then Vm (`fmla d=A n=B m=C` → A; `fmla d=1 n=A m=B` → A; `fmla d=1 n=B m=A` +→ B) — the reverse of x86's ranking. Every created NaN is the default NaN `0x7fc00000`, sign clear (`0*inf`, +`inf-inf`, `inf+-inf`). One extra AArch64 case has no x86 counterpart: when the product is `0 * Inf`, a QNaN +addend is **discarded** for the default NaN (`fmla d=A n=0 m=inf` → `7fc00000`), where x86's Table 14-17 returns +`Q(z)`, the addend. SNaN quieting agrees on both (`0x7f800005` → `0x7fc00005`). + +| Site | GCC emits (basalt's Release `-O3` build) | x86 returns | AArch64 / the port returns | +|---|---|---|---| +| `p = d * scale` (`:518`) | `vmulps p, dd, scale` — SRC1 = `dd`, in all six GCC versions [M] `GT:156` | both NaN → **`d`**; `0 * ±inf` → `0xffc00000` [M] `GT:204-217` | `fmul` op1 = `d` → **`d`**, same; created → `0x7fc00000`. The port's `x86_row()` writes the x86 rule explicitly | +| `corr = fmadd(dd, hx, corr)` (`:519`) | `vfmadd231ps corr, dd, hx` at **every** NT and token, in all six versions [M] `GT:157`. (The `-O2` run below read `vfmadd213ps` at NT ≥ 3; that was an artefact of its constant-propagated clones, and the ranking was the same either way) | **`dd` > `hx` > `corr`**; `dd * hx = 0 * inf` → `0xffc00000`, unless `corr` is a NaN, which Table 14-17 then returns [M] `GT:221-241` | `FMLA`: **`corr` first**; created → `0x7fc00000`, *including* when `corr` is a NaN and the product is `0 * inf`. `x86_row()` restores the x86 ranking | +| `acc = fmadd(perm(p), cvt(dot), acc)` (`:528`) | `vfmadd231ps acc, P, D` — priority `P`, `D`, `acc`, and `D` is a `vcvtdq2ps` result, never a NaN [M] `GT:158`. GCC 15.2/15.3 swap `P` and `D` at NT = 5, tokens 0-3, which cannot change the answer because `D` is never a NaN | effective **`P` > `acc`** [M] `GT:245-254` | **`acc` > `P`**; `x86_row()` restores it | +| add tree, levels 1–2 (`:532`; the `acc` and `corr` trees are separate reductions) | `vaddps u, hi, lo` or `lo, hi` — **the side varies with NT, the token slot and the GCC version** [M] `GT:159`, `:268-342`; the one-token job is `hi` at both levels in every version | the chosen half's NaN | `vaddq_f32(v[2], v[0])`, op1 = high → the one-token job's side. `x86_row()` pins that order for every slot | +| add tree, level 3 | `vpermilps t7, t6, 78` then `vaddps a, t7, t6` — SRC1 = the **permuted** vector, in every slot of every version [M] `GT:342` | lane 0 returns **`t[2]`**, lane 1 `t[3]` | `vaddq_f32(t, vextq_f32(t, t, 2))` emits `ext.16b v2, v1, v1, #8` then `fadd.2s v1, v1, v2`, op1 = `t` → returns **`t[0]`** [M] — the order mismatch the vector path keeps and `x86_row()` corrects | +| add tree, level 4 | `vaddss res, T8[0], T8[1]` — lane 0 or lane 1, varying with the slot as levels 1–2 do [M] `GT:159`, `:268-342`; lane 0 in the one-token job | the chosen lane's NaN | `vgetq_lane(p,0) + vgetq_lane(p,1)`, op1 = lane 0 → the one-token job's lane | +| `res = reduce(acc) - reduce(corr)` (`:532`) | `vsubss res, acc_sum, corr_sum` — SRC1 = the `acc` sum, all six versions [M] `GT:160` | the **`acc`** sum's NaN; `inf - inf` → `0xffc00000` [M] `GT:346-353` | `fsub` op1 = the `acc` sum → same; created → `0x7fc00000`, which `x86_row()` replaces with the indefinite | +| `amax` max tree (`:352`) | `vmaxps` per section 1 | `MAXPS` returns SRC2 on any unordered compare | the `maxps()` select, same — and a NaN `amax` then dies at `vcomiss`: `amax > 0.f` is false, so `s = +0` | +| `t = x * inv` (`:356`) | `vmulps t, x, inv` — SRC1 = `x` | `x`'s NaN; `0 * inf` → `0xffc00000` | op1 = `x` → same; created → `0x7fc00000` | +| `r = t ± 0.5` (`:357-358`) | `vaddps r, t, blend` — SRC1 = `t` | `t`'s NaN | `vaddq_f32(t0, c)`, op1 = `t` → same | +| `hx = s * (float) sum` (`:367`) | `vmulss hx, (float) sum, s` — GCC **swaps** the written order, SRC1 = `(float) sum` | inert: `sum` is a `vcvtsi2ss` result, so at most one operand is ever a NaN | same | + +The last four rows never reach an output. A NaN `amax` is killed by the ordered compare; a NaN `t` or `r` is killed +by `VCVTTPS2DQ`, which returns the integer indefinite that the clamp takes to −127 (section 4); and `s * sum` with +`s = +inf` needs `sum = 0`, which an infinite lane's −127 forbids (section 2). So `act_quant_q8_1` writes no NaN, +and the only NaN-valued input the row kernel can see from basalt's own pipeline is a row's own fp16 block scale. + +**Is the choice compiler-dependent?** (a) The FMA priority is not: all six measured GCC versions make `dd` the +first multiplicand and `corr` the addend, and `P` the first multiplicand with `acc` the addend [M] `GT:154-160`, +and Clang 21 the same [M, here]. The *form* does vary with the optimisation level — the `-O2` clones emit `vfmadd213ps`, +basalt's Release `-O3` build `vfmadd231ps` everywhere — without changing the ranking, since each form's own +formula names the same operand first. (b) `p = d * scale` **is** compiler-dependent: GCC emits SRC1 = `dd`, Clang +`vmulps p, scale, dd`, SRC1 = `scale` [M], so under a Clang-built basalt an `a->scale` NaN would beat the block +scale's. (c) The add tree's operand order is compiler-dependent **and** slot-dependent: GCC 12.5 differs from 14.3 +in 19 of the 36 (NT, token) slots, 13.4 in 15, 15.2 and 15.3 in 6, and 14.4 in none [M] `GT:326-340`; Clang mirrors +levels 1–2 and takes the unpermuted vector at level 3 [M]. Level 3 alone is fixed: the shuffle is SRC1 in every +slot of every version [M] `GT:342`. basalt's build is g++ (section 1's inference), so the port follows the GCC +column, at the one-token slot. (d) The subtraction and the created-NaN bits are fixed by the ISA and depend on +nothing [M] `GT:346-353`. + +**The inputs that separate them.** The port side was measured here by replaying its own operations [M]; the x86 +side is now measured too, each case through basalt's own kernels on the AVX-512 host [M]. Codes `0x55` make every +weight code 1, so each `VPDPBUSD` dword lane holds 4 * 127 = 508. + +| Case | Input | x86 | the port, before `x86_row()` | +|---|---|---|---| +| A — the `acc` FMA | `nblocks = 2`, fp16 block scales `0x7e01` then `0x7e02` (→ `0x7fc02000`, `0x7fc04000` [M]), codes `0x55`, 128 activations of `1.0` (`s = 1/127`, `hx = 32`) | `0x7fc04000` — block 1's scale is the first multiplicand [M] `GT:40`, fixture (b), every (nt, t) | `0x7fc02000` — the accumulator is the addend | +| B — add tree level 3 | finite block scales, every `a->scale` zero, `a->hx` with two payloads four lanes apart; a forged `ActQ`, since `act_quant_q8_1` writes no NaN, so this one is latent rather than reachable | the shuffle's, i.e. lane 2's [M] `GT:313`, probe P2, every (nt, t) | lane 0's | +| C — any created NaN | 64 copies of `2^124` give `scale = 1.674618e+35` (`0x7a010204`) and `hx = +inf` with no infinity in the input; one block, `d = 1.0`, codes `0x55`, so each `acc` lane stays finite at 8.51e37 and **`acc`'s reduction** overflows to `+inf` against `corr = +inf`: `res = inf - inf` | `0xffc00000` [M] `GT:29`, fixture (a), every (nt, t) | `0x7fc00000` | +| D — the reverse direction | a QNaN `acc` lane meeting an `inf * 0` product: block 1's codes are all zero while its chunk scale is `+inf`, against an `acc` already holding a QNaN | the QNaN survives — Table 14-17's `Q(z)`, the addend [M] `GT:53`, fixture (c1), every (nt, t) | `0x7fc00000` — the addend discarded | + +**The smallest correct rule.** NaN-*ness* never differs: both ISAs make a NaN at the same sites from the same +inputs, so `isnan(res[t])` is true on exactly the same rows — measured over 21,635 NaN outputs of the large +differential, where every non-NaN output and every NaN *position* agreed and only payloads differed [M] +`GT:101-103`. Only the bits differ, in three ways — the created-NaN +payload (every site, always `0xffc00000` against `0x7fc00000`), the FMA's ranking (cases A and D), and the add +tree's operand order (level 3 in every slot, case B; levels 1, 2 and 4 wherever x86's slot order is not the +one-token one). The third is *not* repairable by swapping the two arguments in the C source: LLVM's LangRef, +"Behavior of Floating-Point NaN values", gives a NaN result "a non-deterministic sign" with "the quiet bit and +payload ... non-deterministically chosen" between the preferred all-zero payload and a copy from any NaN input +[S], so no NEON expression written in C is entitled to a particular payload at all — the AArch64 column above is +this compiler's and this chip's measured behaviour, not a contract. Only explicit bit tests are. That gives a +two-case rule, which `runtime/src/basalt_cpu.cpp` implements as one scalar replay at the single write of `res[t]`: + +1. If no NaN enters the row — none among its `nblocks` fp16 block scales (one per 18-byte block) and none among + the `2 * nblocks` `ActQ` `scale` and `hx` values it reads — + then any NaN in `res[t]` was created, and every created NaN on x86 is the indefinite; a propagated indefinite + keeps its bits, so the answer is exactly `0xffc00000`. Measured on all 2,506 such outputs of the model run, + identical under GCC 12.5, 13.4, 14.3 and 15.2 [M] `GT:375-378`; it covers the whole case reachable from + `act_quant_q8_1`'s own output (section 2). The blanket rewrite "`0x7fc00000` → + `0xffc00000`" is **not** equivalent and is wrong on an ordinary input: an fp16 block scale of `0x7e00`, the + canonical half NaN, converts to `0x7fc00000` [M] and must survive unchanged, while `0xfe00` propagates to + `0xffc00000` [M] and must not be read as a created one. +2. If a NaN does enter, the row's result needs x86's rankings, which the NEON path cannot give at the two FMA + sites — and x86 has **no single answer** there: the two halves of `acc` can end on different NaNs, and which + one the add tree keeps moves with the token slot, the token count and the GCC version (1,103 of the model's + kind-0 outputs differ between slots of the 14.3 build, 309 between versions) [M] `GT:379-389`, so basalt's own + output contradicts its promise that "Every token's output is bitwise the single-token job's" + (`include/basalt/kernels/cpu/pool.hpp:54-55`). The port therefore pins **GCC 14.3's one-token order for every + slot**, which is basalt 14.3's single-token job bit for bit and keeps the promise. That is a second + build-dependent value beside `amax`. + The replay is **lane-exact**, not a single-accumulator loop: 16 lanes; lane `L` of the + group at `b0` takes block `b0 + L/2`'s `dd` and `a->hx[2*b0 + L]`; `acc` lanes 0-7 and 8-15 take `p[2i]` and + `p[2i+1]`; and both trees use the pairings and SRC1 sides of the table. A single-accumulator loop gets case B + wrong, and every row whose `corr` lanes hold different blocks' NaNs with it. It selects NaNs by + **explicit bit tests** at each site, never by letting + native float arithmetic choose: `fmaf` lowers to `FMADD`, which is addend-first with the default NaN, so a + replay written in plain C reproduces exactly the two divergences it is there to remove. It runs on no finite + row, so it costs nothing, and it subsumes case 1. + +The port in that form reproduces the reviewer's lane-level model — the one validated against basalt's real kernel +with 0 mismatches in 62,374 outputs — bit for bit on all three activation kinds, at `-O0`, `-O2` and `-O3` [M], and +matches every recorded fixture and probe at `nt = 1` (`tests/kernels/test_basalt_cpu_q2.py`, group C). What remains +different from a particular basalt binary is only case 2 at `nt > 1`, or under a GCC other than 14.3/14.4. + +## 7. The supported input range + +A decision of the engineering review. basalt's `act_quant_q8_1` writes no NaN `scale` or `hx` for any float input +(**Inference** from `expert.cpp:352-367`). A NaN `amax` fails the ordered `amax > 0.f`, so `s = +0` (`:353`) and +`hx = +0 * sum` is a zero (`:367`). A finite `amax` gives a finite `s`, so `hx` is finite or overflows to an infinity. +`amax = +inf` needs an infinite lane, whose `t = inf * (1.f / s) = inf * 0` (`:354`, `:356`) is a NaN that `VCVTTPS2DQ` +and the clamp take to −127 while every finite lane's `t = ±0` gives 0 (`:357-361`, section 4), so `sum <= -127` (`:364`) +and `hx = +inf * sum = -inf`. Case A11 asserts the exact outputs [M]: a single `+inf` gives `scale = +inf`, +`sum = -127`, `hx = -inf` at every position; a single NaN gives −127 at its own position, and where it also reaches +`amax` (position 19 alone, under GCC's tree) `scale = +0`, `sum = -127`, `hx = -0.0`; `+inf` with `-inf` gives +`sum = -254` and `hx = -inf`. The port at `-O0` and at the Release flags wrote no NaN `scale` or `hx` over 3,681,564 +chunks drawn with NaN, ±inf, huge, subnormal and zero elements, and every `+inf` scale came with `sum <= -127` and +`hx = -inf` [M]. A NaN therefore enters a row only through a NaN fp16 block scale in the weights, which a valid model +file does not hold. The pinned GCC 14.3 single-token rule of section 6's case 2 decides only rows of a corrupt weight +file and test inputs (a NaN block scale, or a NaN planted in `scale` or `hx` through the binding); every NaN generated +from non-NaN inputs, an infinite activation's included, is `0xffc00000` under every build measured — basalt's under GCC +12.5, 13.4, 14.3 and 15.2 [M] `GT:375-378`, the port's at `-O0` and at the Release flags, all 316,278 NaN outputs of +316,366 from rows with no NaN block scale fed those activations [M]. diff --git a/docs/research/basalt-nvcc/bf16.md b/docs/research/basalt-nvcc/bf16.md new file mode 100644 index 00000000..06f0d0bb --- /dev/null +++ b/docs/research/basalt-nvcc/bf16.md @@ -0,0 +1,168 @@ +# basalt's BF16 matrix-vector kernels as nvcc compiles them + +What NVIDIA's compiler emits at every rounding site of basalt's BF16-weight, fp32-activation GEMVs +(`bf16_gemv_fp32_mmvf`, `bf16_gemv_fp32_mmvf_multi`, `bf16_gemv_fp32_mmvf_cols`), read from the sm_120 PTX and SASS, +and the Metal form the port writes at each site. This page is the authority the Metal kernel follows +(`docs/design/flash-next.md`, invariant 5), as `matvec.md` is for the q8_1 quantizers and `native_mmvq`. + +Basalt paths are relative to commit `b4c63b55754637f4c72ad53a0f791d425f71eb36`; `path:a-b` means lines a to b there, +and a bare `:N` is a line of the file named last. + +## Method + +- **Sources.** `src/kernels/cuda/native_bf16.cu` with the headers it includes (`include/basalt/kernels/` + `bf16_gemv.hpp`, `bf16_bits.hpp`, `pdl.hpp`). Only basalt's public MIT source was sent. +- **Compilers.** Compiler Explorer's public API, as in `matvec.md`: NVCC 13.0.0 (`nvcc130`), 13.2.0 (`nvcc132`) + and 13.3.0 (`nvcc133`), each returning the PTX and the `SASS (sm_120)` listing. +- **Flags.** Basalt's own for this file, in all three versions: `-O3 -DNDEBUG` (`CMakeLists.txt:12-14`), + `-DBASALT_VERSION="0.0.1"` (`:7`), `--generate-code=arch=compute_120,code=[compute_120,sm_120]` (`:3-4`, `:26-31`) + and `--use_fast_math`, which `CMakeLists.txt:185-202` sets on `native_bf16.cu`. +- **Translation unit.** `native_bf16.cu:1-137` verbatim (the includes, `mmvf_warp_sum`, both kernel templates and + `mmvf_block_size`), the quoted local includes inlined under `#line` directives, then a table that takes the address + of `bf16_f32_mmvf_kernel<32>`, `<64>` and `<256>` and of `bf16_f32_mmvf_multi_kernel<32, 4>`, `<256, 4>` and + `<256, 8>`. The host launchers after line 137 hold no device arithmetic. 256 is the block every engine call on the + decode path gets (n_in = 2560, section 3); 32 is the only block without the shared-memory stage. +- **Version check.** In every function the three versions emit the same arithmetic: the same `FFMA.FTZ` chains and + `FADD.FTZ` butterflies in the same order. 13.0 and 13.2 emit the same instruction counts per function. 13.3 adds + a second copy of the block-level butterfly for a diverged warp (`BRA.DIV` to `WARPSYNC.COLLECTIVE` shuffles), with + the same adds in the same order (section 1). + +## Notation + +`matvec.md`'s: fl(e), fma(a, b, c), `.FTZ`, and the Metal helpers of `kernels/common/basalt_fp.metal` (`fma_ftz`, +`add_ftz`, `warp_sum_ftz`). bf(h): bf16 bits to fp32, the bits shifted left by 16, exact (`bf16_bits.hpp:45-50`). + +## Summary + +| Kernel | Rounding sequence nvcc 13.x emits (sm_120) | Metal | +|---|---|---| +| `bf16_f32_mmvf_kernel` (one row) | thread t: acc = fma(bf(w_lo), x.x, acc), then acc = fma(bf(w_hi), x.y, acc), per pair p = t, t + B, ... in order, from +0; all `FFMA.FTZ` | `fma_ftz` twice per pair, in the same order | +| reduction (B > 32) | XOR butterfly 16, 8, 4, 2, 1 (`FADD.FTZ`); lane 0 of warp w stores to `partials[w]` (zeroed); warp 0 runs the butterfly over all 32 `partials`, zeros included | `warp_sum_ftz`; the same zeroed threadgroup array and second `warp_sum_ftz` over 32 lanes | +| reduction (B = 32) | the warp butterfly only | `warp_sum_ftz` | +| `bf16_f32_mmvf_multi_kernel` (2 to 8 rows, NT 4 or 8) | per token k < n_tok the one-row kernel's sequence, site for site: its own accumulator, the same pair FMAs, the same two butterflies | the same kernel source with NT accumulators | + +No float operation in any function lacks `.FTZ`: the PTX has 218 `fma.rn.ftz.f32` and 165 `add.ftz.f32` in each +version and no unflagged `fma`, `add`, `mul` or `sub`; the SASS no unflagged `FFMA`, `FADD` or `FMUL`. There is no +implicit contraction site: both FMAs are the source's `__fmaf_rn` (`:62-63`, `:102-103`), and nothing else +multiplies. + +## 1. `bf16_f32_mmvf_kernel` (`native_bf16.cu:44-73`) + +Grid n_out blocks of B threads (`mmvf_block_size`, section 3); block o computes y[o] from weight row o +(`w + o * n_in`, read as 32-bit words of two bf16 values, `:49-50`) and x (read as float2 pairs, `:51`). + +| Site | basalt | PTX (13.2) | SASS (13.2) | Metal | +|---|---|---|---|---| +| `partials` zeroed (B > 32) | `:53-56` | `st.shared.b32` of 0 under `t < 32`; `bar.sync 0` | `@!P0 STS [R22], RZ`; `BAR.SYNC.DEFER_BLOCKING 0x0` | `if (t < 32) partials[k][t] = 0.0f;` barrier | +| bf16 widening | `:62-63` `f32_from_bf16((uint16_t) weight)`, `(weight >> 16)` | `shl.b32 %r22, %r19, 16`; `and.b32 %r24, %r19, -65536` | `IMAD.U32 R16, R20.reuse, 0x10000, RZ`; `LOP3.LUT R20, R20, 0xffff0000, RZ, 0xc0, !PT` | `as_type(word << 16)`, `as_type(word & 0xffff0000u)` | +| first FMA of a pair | `:62` `acc = __fmaf_rn(bf(lo), input.x, acc)` | `fma.rn.ftz.f32 %r23, %r22, %r20, %r145` | `FFMA.FTZ R18, R18, R16, R21` | `acc = fma_ftz(w0, in.x, acc)` | +| second FMA | `:63` `acc = __fmaf_rn(bf(hi), input.y, acc)` | `fma.rn.ftz.f32 %r25, %r24, %r21, %r23` | `FFMA.FTZ R21, R19, R20, R18` | `acc = fma_ftz(w1, in.y, acc)` | +| warp sum | `:65`, `mmvf_warp_sum` (`:37-42`) | `shfl.sync.bfly.b32 %r121\|%p11, %r145, 16, 31, -1`; `add.ftz.f32 %r122, %r145, %r121`; offsets 8, 4, 2, 1 likewise | `SHFL.BFLY PT, R2, R21, 0x10, 0x1f`; `FADD.FTZ R2, R2, R21`; ... ×5 | `warp_sum_ftz(acc)` | +| partial store | `:68` `if ((t & 31) == 0) partials[t / 32] = acc;` | `st.shared.f32` | `@!P0 STS [R2], R3`; `BAR.SYNC.DEFER_BLOCKING 0x0` | `if (lane == 0) partials[k][sg] = acc;` barrier | +| block sum | `:70` `if (t < 32) acc = mmvf_warp_sum(partials[t]);` | `ld.shared.f32`; 5 × (`shfl.sync.bfly`, `add.ftz.f32`) | `@P1 EXIT` (t > 31); `LDS R22, [R22]`; `SHFL.BFLY PT, R3, R22, 0x10, 0x1f`; `FADD.FTZ R3, R22, R3`; ... ×5 | `if (sg == 0) acc = warp_sum_ftz(partials[k][lane]);` | +| output | `:72` `if (t == 0) y[blockIdx.x] = acc;` | `st.global.f32` | `@P0 EXIT` (t ≠ 0); `STG.E desc[UR8][R2.64], R7` | `if (t == 0) y[o] = acc;` | + +The same sites in the other versions, `<256>`: 13.0 `IMAD.U32 R31, R18.reuse, 0x10000, RZ`; `LOP3.LUT R18, R18, +0xffff0000, RZ, 0xc0, !PT`; `FFMA.FTZ R16, R16, R31, R19`; `FFMA.FTZ R19, R17, R18, R16`; 13.3 `IMAD.U32 R16, +R20.reuse, 0x10000, RZ`; `LOP3.LUT R20, R20, 0xffff0000, RZ, 0xc0, !PT`; `FFMA.FTZ R18, R18, R16, R21`; `FFMA.FTZ R21, +R19, R20, R18`. Some unrolled iterations widen the low half with `SHF.L.U32 R, R, 0x10, RZ` instead of the multiply +by 0x10000: the same bits. + +Notes: + +- **One chain per thread, in pair order.** The loop (`:58-64`) is unrolled by 8, then 4, 2 and 1 for the remainder; + every `FFMA.FTZ` takes the previous one's result as its addend, so a thread's sum is the two FMAs of its first pair, + then its second pair's, and so on, from +0. The front end orders each FMA's operands as the source does (weight, + activation, accumulator); `ptxas` swaps the two factors (`FFMA.FTZ R18, R18, R16, R21`: the activation `R18` times + the weight `R16`). The product of two floats is commutative and exact inside the fused operation, so the bits do not + change. +- **The butterfly's operand order.** The source adds the received value to its own (`value + shfl`), as the PTX + does; the SASS adds them the other way. Float addition is commutative (a NaN's payload aside), so the Metal form + keeps the source's order. Every lane ends with the same bits: both lanes of a butterfly pair add the same two + values. +- **The block sum adds zeros.** With B = 256 the warp partials p0..p7 sit in `partials[0..7]` and `partials[8..31]` + stay +0. Warp 0's butterfly over the 32 slots adds +0 to every partial in its 16 and 8 steps, then gives + ((p0 + p4) + (p2 + p6)) + ((p1 + p5) + (p3 + p7)). An add of +0 can change only a zero's sign (−0 + +0 is +0), which + the port reproduces by running the same 32-lane tree over the same zeros. +- **Flush to zero.** `--use_fast_math` implies `-ftz=true`: each `__fmaf_rn` becomes `fma.rn.ftz.f32` and each `+=` + `add.ftz.f32`, so a subnormal bf16 weight (exponent field 0), a subnormal activation, a subnormal running sum and a + subnormal result all become the zero of their sign. The flush follows the rounding: PTX defines `fma.f32` as the + exact a·b + c "rounded to single precision" and `.ftz` as flushing "subnormal inputs and results", so an exact value + in [2^-126 − 2^-150, 2^-126) rounds to the smallest normal, 2^-126 (the tie 2^-126 − 2^-150 to its even neighbour), + and stays. This GPU's fma flushes on the exact value instead and returns the zero of its sign there (`matvec.md`, + Notation): `fma_ftz` checks such a zero against the exact value, from integer operations on the bits, and returns + ±2^-126 where the rounded value is that. An add needs no check: an exact sum below 2^-126 is a multiple of 2^-149, + so nothing rounds. With the explicit flushes, the Metal kernel does not depend on what the GPU does with + subnormals. The rounding rule rests on the PTX ISA's wording: no Blackwell GPU here has run FFMA.FTZ on these + values (`tests/kernels/test_basalt_mmvf.py::test_flush_to_zero` pins them). +- **13.3's diverged-warp copy.** 13.3 guards the block sum with `BRA.DIV UR4`: a warp that is not converged runs a + second copy of the five steps through `WARPSYNC.COLLECTIVE` / `SHFL.BFLY` / `ENDCOLLECTIVE`, with the same + `FADD.FTZ` sequence (`FADD.FTZ R3, R22, R3`, then `R2, R3, R2`, `R5, R2, R5`, `R4, R5, R4`, `R7, R4, R7`). Warp 0 is + converged there (it reaches the line together after the barrier), so the copy never runs; it changes no bit either + way. It accounts for 13.3's extra counts: `<256>` has 14 `FADD.FTZ` and 15 `SHFL.BFLY` against 10 and 10 in 13.0 and + 13.2. + +## 2. `bf16_f32_mmvf_multi_kernel` (`native_bf16.cu:78-122`) + +The same grid and block, for n_tok (1..8) activation rows x + k·ldx and outputs y[k·ldy + o], NT = 4 or 8 accumulator +slots (section 3). `partials[NT][32]` is zeroed under `t < 32` (`:86-91`); per pair the weight word is widened once +(`:97`), then per token `k < n_tok` (`:99-105`) the one-row kernel's two FMAs on that token's accumulator +(`:102-103`); then per token the warp butterfly, the lane-0 store to `partials[k][t / 32]`, the block butterfly over +`partials[k][t]` and, from thread 0, the store of each `k < n_tok` (`:107-121`). + +| Site | SASS (13.2, `<256, 4>`) | +|---|---| +| zeroing | `@!P0 STS [R2], RZ`; `@!P0 STS [R2+0x80], RZ`; `@!P0 STS [R2+0x100], RZ`; `@!P0 STS [R2+0x180], RZ`; `BAR.SYNC.DEFER_BLOCKING 0x0` | +| widening, once per pair | `IMAD.U32 R30, R12.reuse, 0x10000, RZ`; `LOP3.LUT R37, R12, 0xffff0000, RZ, 0xc0, !PT` | +| token k's pair, under `k < n_tok` | `@P1 FFMA.FTZ R24, R30, R24, R9`; `@P1 FFMA.FTZ R9, R37, R25, R24` (token 0; tokens 1..3 likewise under `@P3`, `@P4`, `@P2`) | +| warp sums | 4 × (`SHFL.BFLY` + `FADD.FTZ`) × 5, the tokens' steps interleaved, each token's offsets 16, 8, 4, 2, 1 in order | +| partial stores | `@!P0 STS [R4], R9`; `[R4+0x80]`; `[R4+0x100]`; `[R4+0x180]`; `BAR.SYNC.DEFER_BLOCKING 0x0` | +| block sums | `LDS R3, [R2]`; `LDS R6, [R2+0x80]`; ...; 4 × 5 butterfly steps, interleaved | +| outputs | `@P3 STG.E desc[UR4][R4.64], R7`, then one `STG.E` per further token under `n_tok > k` | + +**Result: per token the multi kernel computes the one-row kernel's sequence, site for site, in the three versions.** +Each token's FFMA chain is the one-row chain on that token's activations (the pair order, the operands, the flush), +predicated on `k < n_tok`; the compiler interleaves the tokens' independent chains and butterflies but never mixes +two tokens' values. Slots k ≥ n_tok keep +0 and are never stored. So each output is bit-identical to a +`bf16_f32_mmvf_kernel` launch on its own row, as the kernel's comment says (`:75-77`), and `<32, 4>` (no shared +stage: 40 `FFMA.FTZ`, 20 `FADD.FTZ`, 20 `SHFL.BFLY`, 4 `STG.E` in every version) is the B = 32 one-row kernel per +token. + +Instruction counts per function (13.0 = 13.2; 13.3 adds the diverged-warp copy of section 1 to each block sum): + +| Function | `FFMA.FTZ` | `FADD.FTZ` 13.0 / 13.3 | `SHFL.BFLY` 13.0 / 13.3 | `STS` | `LDS` 13.0 / 13.3 | +|---|---|---|---|---|---| +| `bf16_f32_mmvf_kernel<32>` | 30 | 5 / 5 | 5 / 5 | 0 | 0 / 0 | +| `bf16_f32_mmvf_kernel<64>`, `<256>` | 30 | 10 / 14 | 10 / 15 | 2 | 1 / 1 | +| `bf16_f32_mmvf_multi_kernel<32, 4>` | 40 | 20 / 20 | 20 / 20 | 0 | 0 / 0 | +| `bf16_f32_mmvf_multi_kernel<256, 4>` | 40 | 40 / 59 | 40 / 60 | 8 | 4 / 7 | +| `bf16_f32_mmvf_multi_kernel<256, 8>` | 48 | 80 / 119 | 80 / 120 | 16 | 8 / 15 | + +The `FFMA.FTZ` counts are static counts of the unrolled loop bodies, not per-output counts: the one-row kernel's +copies of 8, 4, 2 and 1 pairs (30); `<256, 4>`'s one-pair and four-pair loops over four tokens (8 and 32). + +## 3. Launches (`native_bf16.cu:124-203`) + +Host code, no arithmetic, but it fixes the block size B and so the summation order: + +- `mmvf_block_size(n_in)` (`:124-135`): start at 32 with ceil(n_in / 64) iterations; each candidate 64, 96, ..., 256 + replaces the best only with strictly fewer iterations, ceil(n_in / (2 · candidate)). n_in = 2560, every engine call + on this path, gives 256 (5 pairs per thread); n_in ≤ 64 gives 32. +- `bf16_gemv_fp32_mmvf` (`:162-189`): n_in positive, even and at most INT_MAX, n_out positive and at most INT_MAX, + x 8-byte aligned, w and y 4-byte aligned; grid n_out, block B. +- `bf16_gemv_fp32_mmvf_multi` (`:139-160`): `n_tok == 1 && ldy >= n_out` calls the one-row kernel (`:141`); + otherwise n_tok in 1..8, even n_in and ldx, x 8-byte aligned (`:142-144`), and the multi kernel with NT = 4 for + n_tok ≤ 4, else 8 (`:146-150`). +- `bf16_gemv_fp32_mmvf_cols` (`:193-203`): ncols contiguous columns (ldx = n_in, ldy = n_out) in chunks of 8; a chunk + of one takes the one-row kernel, the others the multi kernel. + +## 4. Metal + +`kernels/common/basalt_mmvf.metal` is one source for both kernels: the macro `BLOCK` is B and `NT` the accumulator +slots (1 for the one-row kernel, 4 or 8 for the multi kernel); `monolith/kernels.py` (`basalt_mmvf_macros`, +`basalt_mmvf_params`, `basalt_mmvf_cols`) reproduces section 3. A thread's index is t = 32 · sg + lane, so its pairs, +its warp and its `partials` slot are basalt's whatever order Metal gives the SIMD-groups. Each site is the form in +the tables above: `fma_ftz` twice per pair, `warp_sum_ftz` for both butterflies, the zeroed `partials[NT][32]` in +threadgroup memory, the block stage only for BLOCK > 32. `tests/kernels/test_basalt_mmvf.py` checks the kernel bit +for bit against a numpy emulation of this page (`tests/kernels/basalt_emu.py`) and every multi-row and column output +bitwise against the one-row kernel. diff --git a/docs/research/basalt-nvcc/dense_tc.md b/docs/research/basalt-nvcc/dense_tc.md new file mode 100644 index 00000000..0b971fd1 --- /dev/null +++ b/docs/research/basalt-nvcc/dense_tc.md @@ -0,0 +1,226 @@ +# basalt's dense_tc kernels as nvcc compiles them + +What NVIDIA's compiler emits at every rounding site of `dense_tc` and `dense_tc_pair`, the window projections basalt +runs for every window width on this pack's decode path, read from the sm_120 PTX and SASS, and the Metal form the port +writes at each site. This page is the authority the Metal kernels follow (`docs/design/flash-next.md`, invariant 5), +as `matvec.md` is for `native_mmvq` and the q8_1 quantizers: each weight type's fp32 terms (`half_sb_terms`, +`dense_tc.cu:100-330`), every combining step of each summation order, and the rule that picks the order. + +Basalt paths are relative to commit `b4c63b55754637f4c72ad53a0f791d425f71eb36`; `path:a-b` means lines a to b there, +and a bare `:N` is a line of the file named last. + +## Method + +- **Sources.** `src/kernels/cuda/dense_tc.cu` with the headers it includes (`include/basalt/kernels/dense_tc.hpp`, + `pdl.hpp`, and `include/basalt/ggml/ggml_common.h` under `GGML_COMMON_DECL_CUDA` / `GGML_COMMON_IMPL_CUDA`). Only + basalt's public MIT source was sent. +- **Compilers.** Compiler Explorer's public API, as in `matvec.md`: NVCC 13.0.0 (`nvcc130`) and 13.3.0 (`nvcc133`), + PTX and the `SASS (sm_120)` listing. +- **Flags.** `dense_tc.cu` is not in the `--use_fast_math` list (`CMakeLists.txt:185-202`), so it builds with nvcc's + defaults (IEEE division, no flush to zero, contraction on): `-O3 -DNDEBUG -DBASALT_VERSION="0.0.1" + --generate-code=arch=compute_120,code=[compute_120,sm_120]`, exactly, in both versions. +- **Translation units.** Each unit is basalt's file verbatim through the end of its device code (`dense_tc.cu:1-960`: + the includes, `Fmt`, the helpers, `half_sb_terms`, the four kernel templates and `dense_tc_l2_kernel`), local + includes inlined under `#line` directives, then a table that takes the address of one kernel instantiation. For each + of the six types of this pack (Q4_K 12, Q5_K 13, Q6_K 14, IQ4_XS 23, Q3_K 11, Q2_0 42): `dense_tc_one_kernel`, + `dense_tc_tile_kernel`, `dense_tc_kernel` and `dense_tc_kernel`, the four kernels the + variant rule can launch (`dense_tc.cu:1040-1059`); and `dense_tc_pair_kernel` for DB and LQ each false + and true (the decode path's n_in 2560 always takes the register-fragment build, `xr`, `:1126`). +- **The pair kernel's listing.** Compiler Explorer's device listing stops at 5,000 lines (`[truncated; too many + lines]`), and so does its PTX assembler's. `dense_tc_pair_kernel` holds all seven types' branches and runs past it; + its PTX arrives whole (6,098 to 7,866 lines). So each pair unit adds one entry point that calls basalt's + `dense_tc_pair_block` verbatim with both matrices' type set to one type T: the kernel as it runs on a + tile of type T, its type switch (`:870-906`) folded to that branch. Units: the four types of the non-LQ build and the + six of the LQ build, at DB false and true. +- **Reading a site.** As in `matvec.md`: the PTX shows what the front end fused (`fma.rn.f32`); the SASS shows what + `ptxas` made of the rest. A PTX `mul.f32` / `sub.f32` without a rounding modifier may still be fused by `ptxas`, which + it does in Q4_K and Q5_K below. +- **Version check.** The dataflow tracer of `matvec.md` (each SASS float result printed as an expression template over + the leaves `h0` / `h1`, the low or high fp16 half of a word converted by `HADD2.F32`; `i` an int32 converted by + `I2FP`, marked by its writer: `imma` the tensor-core dot, `ishfl` a shuffled integer, `iother` any other integer + arithmetic; `shm` a shared-memory load; `in` a value from before the basic block; `0` the zero register) gives the + same multiset of templates in 13.0 and 13.3 for 43 of the 44 comparable units (all 24 single-type kernels but one, + all 20 per-type pair units). The exception, `dense_tc_kernel<42, 3, 1, 1>`, differs only in where a d8 load sits: + 13.0 places it before a branch, so its leaf reads `in` instead of `h0`; with the loaded leaves (`h0`, `h1`, `in`) + merged into one class the multisets are equal. + +## Notation + +As in `matvec.md`: fl(e) rounds once to fp32, to nearest even; fma(a, b, c) rounds a·b + c once; h(x) is an fp16 value +converted to fp32 (exact); f(n) an int32 converted to fp32. dot is the exact int32 dot of a 32-value block (or a +16-value half) of weight codes with the 32 (16) q8_1 codes of a column, which `mma.sync` computes for 16 rows by 8 +columns; d8 is the column's q8_1 scale, h(the low half of the block's `ds`). Every integer converted here is below +2^24 = 16,777,216 in magnitude, so f(n) is exact. The largest is Q6_K's sc0·e0 + sc1·e1, int8 scales (|sc| ≤ 128) +on 16-value dots of codes in [−32, 31]: at most 2·128·16·32·127 = 16,646,144; next is IQ4_XS's dot·(ls − 32), at +most 32·127·127·32 = 16,516,096. + +**No flush to zero.** No float add, multiply or fma in any unit carries `.FTZ` (the only `.FTZ` instructions are +`F2I.FTZ.U32.TRUNC.NTZ` in the index arithmetic), and the PTX has no `.ftz`: every float operation is IEEE's. + +**No subnormal can occur.** This GPU flushes subnormal inputs and results of add, multiply and fma in +`MTLMathModeSafe` (`tests/kernels/test_basalt_platform.py`), where these IEEE instructions keep them; no value here is +ever subnormal. Each weight scale (d, dmin, dd, dw) and each d8 is an fp16 value, an integer multiple of 2^-24. The +products with integers (f1, f2, d8·f(n)) and every fma or add of them are then integer multiples of 2^-24 (inner) or +2^-48 (part, acc, the warp sums and the output), and a sum of multiples of 2^-K rounds to a multiple of 2^-K: below +2^(24−K) such a value is exact, above it the fp32 grid spacing is itself a multiple of 2^-K. So every result is 0 or at +least 2^-48 in magnitude, and Metal's `*`, `+` and `fma()` give the IEEE result. + +## Summary + +| Type | Per block i of a half super-block, per (row, column) as nvcc 13.x emits it (sm_120) | Metal | +|---|---|---| +| Q4_K, Q5_K | f1 = fl(dm.x·f(sc)), f2 = fl(dm.y·f(m)); inner = fma(f1, f(dot), −fl(f2·f(isum))); acc = fma(inner, d8, acc) | the same, `*` and `fma()` | +| Q6_K, Q3_K | part = fma(f(sc0·dot0 + sc1·dot1), d8, part) from +0, i = 0..3; then acc = fma(dd, part, acc) | the same | +| IQ4_XS | part = fma(f(dot·ls), d8, part) from +0, i = 0..3; then acc = fma(dw, part, acc) | the same | +| Q2_0 | per Q2_0 block b = 0, 1: part = fma(f(dot), d8, part) from +0 over its two 32-value blocks; then acc = fma(dw_b, part, acc) | the same | + +| Order | Warps a tile | Warp w = 4g + hb | Final sum per (row, column), from the SASS | +|---|---|---|---| +| one | 24 | half super-block hb of the chunks c ≡ g (mod 6) | ((((((w0 + w4) + w8) + w12) + w16) + w20) + (((((w1 + w5) + w9) + w13) + w17) + w21)) + ((((((w2 + w6) + w10) + w14) + w18) + w22) + (((((w3 + w7) + w11) + w15) + w19) + w23)) | +| tile, pair | 8 | the chunks c ≡ g (mod 2) | ((w0 + w4) + (w1 + w5)) + ((w2 + w6) + (w3 + w7)) | +| s, KS 1 | 4 | every chunk | ((w0 + w1) + w2) + w3 | +| s, KS 2 | 8 | the 512-value chunks c ≡ g (mod 2) | (((w0 + w1) + w2) + w3) + (((w4 + w5) + w6) + w7) | + +A warp's sum w is its lanes' acc after its chunks in ascending order, from +0. Every add of the tables is a plain IEEE +`FADD` in both versions. The `[H]` of the scoping report (which product of Q4_K's and Q5_K's `a·b − c·d` nvcc fuses) is +settled by the SASS: the d product, as in `native_mmvq` (`matvec.md` section 5). + +## 1. The terms per type (`half_sb_terms`, `dense_tc.cu:100-330`) + +Each lane holds four (row, column) accumulators acc[q], for rows g, g + 8 and columns 2t, 2t + 1 (lane = 4g + t), and +runs the four blocks of its half super-block in ascending order. The raw lines are from `dense_tc_tile_kernel`, the +first instance of each site; the other kernels and the pair units have the same templates (Method). + +### Q4_K (`:106-156`; `Fmt<12>`, 144-byte blocks) + +| Site | basalt | PTX (13.3) | SASS 13.0 | SASS 13.3 | Metal | +|---|---|---|---|---|---| +| f1 | `:143` `dm[h].x * (float) sc` | `cvt.rn.f32.u32`; `mul.f32 %r40, %r138, %r161` | `FMUL R64, R35, R22` | `FMUL R66, R39, R22` | `dm.x * float(sc)` | +| f2 | `:144` `dm[h].y * (float) m` | `mul.f32 %r181, %r139, %r41` | `FMUL R63, R38, R21` | `FMUL R63, R38, R63` | `dm.y * float(m)` | +| inner | `:155` `f1 * (float) d[q] - f2 * (float) isum` | `mul.f32 %r194, %r40, %r193`; `mul.f32 %r196, %r181, %r195`; `sub.f32 %r197, %r194, %r196` | `FMUL R71, R63, R68`; `FFMA R47, R64, R47, -R71` | `FMUL R71, R63, R68`; `FFMA R47, R64, R47, -R71` | `fma(f1, float(dot), -(f2 * float(isum)))` | +| acc | `:155` `acc[q] += x.d8[i][q & 1] * (...)` | `fma.rn.f32 %r42, %r449, %r197, %r482` | `FFMA R47, R47, R61, R42` | `FFMA R47, R47, R61, R42` | `fma(inner, d8, acc)` | + +`h0` / `h1` trace the operands: f1 takes the `.H0_H0` half of the `dm` word (d), f2 the `.H1_H1` half (dmin), and +the template is `FFMA(FFMA(FMUL(h0, i), imma, -FMUL(FMUL(h1, i), ishfl)), h0, acc)` in both versions. The front end +fuses only the outer `+=` (PTX: two multiplies and a subtract); `ptxas` rounds the dmin product and fuses the d product +with its negation, the choice it makes in `native_mmvq`'s Q4_K and Q5_K returns (`matvec.md` section 5). isum is the +column's code sum (`:149-152`): `__dp4a` with `0x01010101`, two XOR shuffles and an indexed shuffle, all integer. + +### Q5_K (`:106-156`; `Fmt<13>`, 176-byte blocks) + +Q4_K's arithmetic line for line, the fifth bit ORed into the codes (`:131-134`) before the dot: `FMUL R69, R40, R69` +(f1) and `FMUL R70, R41, R72` (f2) in 13.0, `FMUL R44, R70, R45` (the dmin product), `FFMA R75, R69, R4, -R44` +(inner), `FFMA R22, R75, R67, R22` (acc); 13.3 `FMUL R5, R69.reuse, R72`, `FFMA R5, R68.reuse, R77, -R5`, `FFMA R22, +R5, R67.reuse, R22`. Metal: Q4_K's forms. + +### Q6_K (`:157-195`; `Fmt<14>`, 210-byte blocks) + +| Site | basalt | PTX (13.3) | SASS 13.0 | SASS 13.3 | Metal | +|---|---|---|---|---|---| +| part, i = 0..3 | `:192` `part[q] += x.d8[i][q & 1] * (float) (sc0 * e0 + sc1 * e1)` | `fma.rn.f32 %r261, %r457, %r260, 0f00000000`, then `fma.rn.f32 %r301, %r461, %r300, %r261`, ... | `FFMA R50, R51, R44.reuse, RZ`; `FFMA R42, R42, R44, R51`; `FFMA R17, R17, R53, R50`; `FFMA R26, R26, R46, R15` | `FFMA R50, R50, R49.reuse, RZ`; `FFMA R47, R47, R41.reuse, R22`; `FFMA R47, R20, R40, R47`; `FFMA R28, R28, R42.reuse, R47` | `part = fma(float(sc0 * e0 + sc1 * e1), d8, part)` from +0 | +| acc | `:195` `acc[q] += dd[q >> 1] * part[q]` | `fma.rn.f32` | `FFMA R28, R13.reuse, R17, R28` | `FFMA R36, R9, R28, R36` | `fma(dd, part, acc)` | + +e0 and e1 are the two 16-value halves' dots (`mma.sync ... m16n8k16`, `:188-189`); sc0·e0 + sc1·e1 is integer +arithmetic. Template: `FFMA(h0, FFMA(i, h0, FFMA(i, h0, FFMA(i, h0, FFMA(i, h0, 0)))), acc)`. + +### Q3_K (`:196-234`; `Fmt<11>`, 110-byte blocks) + +Q6_K's sequence with the codes `__vsub4(...) - 4` and the scales sc − 32 (`:219-224`): 13.0 `FFMA R29, R20, +R17.reuse, RZ`, `FFMA R29, R22, R27, R29`, `FFMA R44, R44, R16, R29`, `FFMA R19, R19, R17.reuse, R44` (part), `FFMA +R32, R49, R21, R32` (acc); 13.3 `FFMA R22, R49, R16.reuse, RZ` ... `FFMA R37, R9.reuse, R30, R37`. PTX `fma.rn.f32` +at every site. Metal: Q6_K's forms. + +### IQ4_XS (`:297-329`; `Fmt<23>`, 136-byte blocks) + +| Site | basalt | PTX (13.3) | SASS 13.0 | SASS 13.3 | Metal | +|---|---|---|---|---|---| +| part, i = 0..3 | `:325` `part[q] += x.d8[i][q & 1] * (float) (d[q] * ls[q >> 1])` | `fma.rn.f32 %r206, %r432, %r205, 0f00000000`, then `fma.rn.f32 %r260, %r436, %r259, %r206`, ... | `FFMA R52, R17, R39, RZ`; `FFMA R51, R51, R53, R16`; `FFMA R51, R16, R21, R51`; `FFMA R20, R20, R16.reuse, R51` | `FFMA R16, R16, R39, RZ`; `FFMA R46, R45, R53, R16`; `FFMA R45, R22, R38, R45`; `FFMA R23, R23, R21.reuse, R46` | `part = fma(float(dot * ls), d8, part)` from +0 | +| acc | `:328` `acc[q] += dw[q >> 1] * part[q]` | `fma.rn.f32` | `FFMA R12, R33.reuse, R20, R12` | `FFMA R12, R17, R23, R12` | `fma(dw, part, acc)` | + +The codes come from `iq4_lookup` (`:79-84`), the codebook's `__byte_perm` lookup; ls = the 6-bit scale minus 32. + +### Q2_0 (`:235-270`; `Fmt<42>`, four 18-byte blocks per 256 values) + +| Site | basalt | PTX (13.3) | SASS 13.0 | SASS 13.3 | Metal | +|---|---|---|---|---|---| +| part, k = 0, 1 | `:266` `part[q] += x.d8[i][q & 1] * (float) d[q]` | `fma.rn.f32 %r183, %r374, %r182, 0f00000000`, then `fma.rn.f32 %r223, %r378, %r222, %r183` | `FFMA R40, R12, R29.reuse, RZ`; `FFMA R29, R29, R14.reuse, R40` | `FFMA R43, R12, R29.reuse, RZ`; `FFMA R31, R16, R14, R43` | `part = fma(float(dot), d8, part)` from +0 | +| acc, per Q2_0 block | `:269` `acc[q] += dw[q >> 1] * part[q]` | `fma.rn.f32` | `FFMA R23, R17.reuse, R16, R23`, then `FFMA R22, R13, R12, R22` | `FFMA R24, R15.reuse, R31, R24`, then `FFMA R26, R13.reuse, R14, R26` | `fma(dw, part, acc)` | + +A half super-block holds Q2_0 blocks 2n and 2n + 1 (`:238`); part restarts at +0 for each. The codes are +`__vsub4((q | q << 6 | q << 12 | q << 18) & 0x03030303u, 0x01010101u)` (`:261`), code − 1. + +## 2. The summation orders and their warp-sum trees + +A tile is 16 rows; each warp leaves its lanes' acc in shared memory as `red[warp][row][column]` (16 · 8 floats, 0x200 +bytes a warp), and one thread per (row, column) adds them (`dense_tc.cu:407-427`, `:552-560`, `:667-681`, +`:919-928`). The SASS loads each warp's value at the offset (warp · 0x200 + base); mapping the offsets back to warps +gives the trees of the Summary in both versions and for all six types (raw lines, Q6_K): + +| Order | SASS 13.0 | SASS 13.3 | +|---|---|---| +| one (`dense_tc_one_kernel<14, 24>`) | `FADD R6, R6, R15`; ... `FADD R23, R6, R23`; `FADD R23, R4, R23`; `FADD R43, R10, R43`; `FADD R8, R8, R43`; `FADD R23, R23, R8`: four chains h_q = w_q + w_4+q + ... + w_20+q (24 loads from base 0x80), then (h0 + h1) + (h2 + h3) | the same lines | +| tile (`dense_tc_tile_kernel<14>`) | `LDS R12, [R6+0x80]`, `LDS R13, [R6+0x880]`, ...; `FADD R12, R12, R13` (w0 + w4); `FADD R15, R14, R15` (w1 + w5); `FADD R12, R12, R15`; `FADD R16, R16, R17` (w2 + w6); `FADD R19, R18, R19` (w3 + w7); `FADD R19, R16, R19`; `FADD R19, R12, R19` | `FADD R8, R8, R9`; `FADD R17, R16, R17`; `FADD R8, R8, R17`; `FADD R18, R18, R19`; `FADD R21, R20, R21`; `FADD R21, R18, R21`; `FADD R21, R8, R21` | +| pair (per-type unit, Q6_K, LQ build) | `FADD R32, R32, R35`; `FADD R37, R34, R37`; `FADD R32, R32, R37`; `FADD R36, R36, R39`; `FADD R41, R38, R41`; `FADD R41, R36, R41`; `FADD R41, R32, R41` (loads at 0x80, 0x880, 0x280, 0xa80, ...) | the same tree | +| s, KS 1 (`dense_tc_kernel<14, 3, 1, 1>`) | `LDS R13, [R76+UR6+0x5700]` (w0), `0x5900` (w1), `0x5b00` (w2), `0x5d00` (w3); `FADD R13, R13, R14`; `FADD R13, R13, R16`; `FADD R13, R13, R18` | `FADD R17, R16, R17`; `FADD R18, R17, R18`; `FADD R19, R18, R19` | +| s, KS 2 (`dense_tc_kernel<14, 3, 1, 2>`) | loads w0..w7 from 0xa500; `FADD R8, R8, R9`; `FADD R10, R10, R15`; `FADD R8, R8, R11`; `FADD R10, R10, R17`; `FADD R13, R8, R13`; `FADD R10, R10, R19`; `FADD R13, R13, R10` | the same lines | + +For KS 2, `v = q == 0 ? vq : v + vq` (`:423`) is the last add: the first group's sum plus the second's. A warp whose +chunks are all past nchunk (the one order when n_in / 512 < 6) leaves acc at +0 and its zero takes part in the adds, +as in basalt. + +What each warp sums, from the source (the order of the per-warp loop is not a compiler choice): + +- one (`:589-595`, `:639`, `:653`): warp w takes hb = w % 4 and the 512-value chunks c = w / 4, w / 4 + 6, ... (NG = 6). +- tile (`:461`, `:519`) and pair (`pair_terms_xr`, `:796-801`): hb = w & 3, chunks w >> 2, w >> 2 + 2, ... +- s (`:343-346`, `:380`): hb = w & 3; KS 1: every chunk; KS 2: the 1024-value chunk c's half ks = w / 4, which is the + 512-value chunk 2c + ks, so warp w takes the same chunks as the tile order's warp w, in the same order. + +## 3. The variant rule (`dense_tc.cu:1017-1059`) + +`launch` picks the order from the shape, the weights' alignment and the device's multiprocessor count, never +the column count: + +1. one, when the weights are 16-byte aligned, a row is a whole number of 16-byte units ((n_in / 256)·SB % 16 == 0), + the 16-row tiles number at most the multiprocessors, and `one_smem_bytes(n_in)` = 128 + max(24·16·8·4, + 16·one_row_stride(row bytes)) ≤ 99 · 1024 (`one_ok`, `:1018-1022`; `one_row_stride` rounds the row up to an odd + number of 16-byte units, `:52-54`); +2. else tile, when aligned and two staged tiles fit: 2·16·(n_in / 256)·SB ≤ 90 · 1024 (`:1051`); +3. else s with KS 2 when n_in % 1024 == 0 and the tiles number fewer than the multiprocessors (`:1055-1056`); +4. else s with KS 1. + +`dense_tc_pair` always takes the pair kernel (the tile order; `:1107-1146`), for every type pair it supports. + +The multiprocessor count is the device's (`sm_count()`, `:967-975`), so on basalt's hardware the order, and with it +the bits, follow the GPU model. The port fixes it at 170, the count of basalt's measured RTX 5090 +(`docs/precision.md:6`; 170 SMs per KitGuru's review, quoted in the scoping report). At 170, every native weight is +its own `cudaMalloc` (aligned, `native_dense.cpp:215-216`), and this pack's projections take: + +| Projection | n_in → n_out | Tiles | Order at 170 | Why | +|---|---|---|---|---| +| ssm_out, attn_output | 6144 → 2560 | 160 | one | rows of 24·SB bytes are whole 16-byte units for every type; `one_smem_bytes` 28,032 (Q2_0) to 80,768 (Q6_K) for the six types | +| attn_q | 2560 → 12288 | 768 | tile | 768 > 170; two tiles take 23,040 (Q2_0) to 67,200 (Q6_K) bytes of the six types | +| GDN qkv + z | 2560 → 10240 + 6144 | | pair | `dense_tc_pair` | + +## 4. Metal + +`kernels/common/basalt_dense_tc.metal` holds `basalt_dense_tc` (the one, tile and s orders, chosen by macro) and +`basalt_dense_tc_pair`. Each starts with `#pragma STDC FP_CONTRACT OFF` (through `basalt_fp.metal`) and writes +`fma()` exactly at the `FFMA` sites above, plain `*` at the `FMUL` sites and `+` at the `FADD` sites; nothing +flushes, because no subnormal reaches them. + +- **The integer dots.** `mma.sync`'s only role is the exact int32 dot of a block (or half block) for 16 rows by 8 + columns. Lane 4g + t holds the same fragments as on CUDA; it fetches column c's code words for its positions + 4t.. and 16 + 4t.. from lane 4c + t (`simd_shuffle`), forms its partial dots for rows g and g + 8 against all eight + columns with `dp4a`, and the four lanes of group g add their partials (integer adds, exact in any order), each lane + keeping columns 2t and 2t + 1: the D fragment basalt's lane holds. +- **Geometry.** A threadgroup is one 16-row tile with basalt's warps as SIMD-groups (24, 8, 4 or 8), so warp w's + chunks and the tree are basalt's; the pair's threadgroups take the first matrix's tiles, then the second's. +- **Staging.** Basalt stages whole tiles in up to 99 KiB of shared memory; Apple9 has 32 KiB of threadgroup memory. + Staging carries no arithmetic, so the Metal kernels read the weights from device memory (two 16-bit loads a word: + Q6_K, Q3_K and Q2_0 blocks are only 2-byte aligned) and keep only the warp sums in threadgroup memory. Rows past + n_out read row n_out − 1 (basalt reads stale staging bytes there) and are never stored; columns at or past ncols get + zero codes and d8 = 0, as in basalt (`:381-393`), and are never stored. + +`tests/kernels/test_basalt_dense_tc.py` checks every order bit for bit against the numpy emulation of this page +(`tests/kernels/basalt_emu.py`: `dense_tc`), ports `dense_tc_parity`'s cases and pairs, and adds a float64 reference +per type. diff --git a/docs/research/basalt-nvcc/dequant.md b/docs/research/basalt-nvcc/dequant.md new file mode 100644 index 00000000..d934a319 --- /dev/null +++ b/docs/research/basalt-nvcc/dequant.md @@ -0,0 +1,41 @@ +# basalt's dequantizers as nvcc compiles them + +What NVCC 13.0 and 13.3 emit for the floating-point steps of basalt's GGUF dequantizers for this pack's types that +`iq_parity` checks: `dq_iq4_nl`, `dq_q3_k`, `dq_iq4_xs` and `dq_q2_0` (`src/kernels/cuda/iq_kernels.cu:2012-2069`). They +run under `dequant_flat_kernel` (`:2216-2220`, launched by `iq_dequant_f32`, `:2496-2500`), and the Q3_K token +embedding's gather shares them (`:2478-2483`). The page also gives the Metal form, `kernels/common/basalt_dequant.metal`. +Its conventions are those of `matvec.md`: basalt commit `b4c63b55754637f4c72ad53a0f791d425f71eb36`, fl(e) one +rounding to nearest even, h(x) the exact fp16-to-fp32 conversion and f(n) the exact int-to-fp32 conversion. + +## Method + +- **Unit.** `iq_kernels.cu` lines 1-33 (its includes and namespaces), 1923-1926 (`cvt`) and 2012-2069 (the four + functions), verbatim, with the quoted local includes inlined. Then comes one kernel per type that calls its function + as `dequant_flat_kernel` does: superblock `blockIdx.x`, thread `threadIdx.x`, `y + i * QK_K`. + `dequant_flat_kernel` selects the function with a runtime `switch` on the type, so each case is the same inlined + body. +- **Flags.** `iq_kernels.cu` builds with nvcc's defaults (no `--use_fast_math`, `CMakeLists.txt:185-202`): `-O3 + -DNDEBUG -DBASALT_VERSION="0.0.1" --generate-code=arch=compute_120,code=[compute_120,sm_120]`, on Compiler + Explorer's `nvcc130` and `nvcc133`. + +## Result + +Each value is one or two IEEE multiplies, with nothing fused and nothing flushed. The PTX has `mul.f32` (round to +nearest, no `.ftz`). The SASS has `FMUL` without `.FTZ` and no `FFMA` or `FADD`. Its conversions are `HADD2.F32 +R, -RZ, R.H0_H0` (fp16 to fp32) and `I2F.S8` / `I2F.S16` / `I2FP.F32.S32` (integer to fp32). The `HFMA2 R, -RZ, RZ, +0, 0` lines only zero registers. The two versions emit the same instructions, except that 13.3 converts the codebook +bytes with `I2F.S16` where 13.0 uses `I2F.S8`, which gives the same values. + +| Function | basalt | PTX (13.0 / 13.3) | SASS (13.0 / 13.3) | Value | Metal | +|---|---|---|---|---|---| +| `dq_iq4_nl` | `:2020-2021` `d * kvalues_iq4nl[q]` | `mul.f32 %f3, %f1, %f2` / `mul.f32 %r8, %r1, %r7` | `FMUL R7, R6.reuse, R7` / the same | fl(h(d) · f(k)) | `d * float(KVALUES_IQ4NL[q])` | +| `dq_q3_k` | `:2039` `(float) x->d * (us - 32)`; `:2043` `dl * (code)` | `mul.f32 %f4, %f2, %f3`; `mul.f32 %f6, %f4, %f5` / `mul.f32 %r21, %r11, %r20`; `mul.f32 %r32, %r21, %r31` | `FMUL R22, R17, R22`; `FMUL R21, R22.reuse, R21` / `FMUL R24, R19, R24`; `FMUL R23, R24.reuse, R23` | fl(fl(h(d) · f(us − 32)) · f(code)) | `h2f(d) * float(us - 32)`, then `dl * float(q)` | +| `dq_iq4_xs` | `:2052` `(float) x->d * (ls - 32)`; `:2054-2055` `d * kvalues_iq4nl[q]` | `mul.f32 %f3, %f1, %f2`; `mul.f32 %f5, %f3, %f4` / `mul.f32 %r25, %r1, %r24`; `mul.f32 %r27, %r25, %r26` | `FMUL R6, R6, R3`; `FMUL R9, R6.reuse, R9` / `FMUL R3, R3, R4`; `FMUL R7, R3.reuse, R7` | fl(fl(h(d) · f(ls − 32)) · f(k)) | `h2f(d) * float(ls - 32)`, then `d * float(KVALUES_IQ4NL[q])` | +| `dq_q2_0` | `:2067` `d * (float) (code - 1)` | `mul.f32 %f3, %f1, %f2` / `mul.f32 %r12, %r1, %r11` | `FMUL R9, R0.reuse, R5` / the same | fl(h(d) · f(code − 1)) | `d * float(code - 1)` | + +**No subnormal arises.** Every factor is an fp16 scale (|h(d)| ≥ 2^-24 when nonzero, normal in fp32), a small +nonzero integer, or a product of the two. So no product is subnormal, and this GPU's flushing of subnormal multiply +results in safe mode (`tests/kernels/test_basalt_platform.py`) cannot change a value. The Metal multiplies with +contraction off are therefore CUDA's operations. `tests/kernels/test_basalt_iq_parity.py` measures a relative error +of 0 against gguf-py's dequantizers on basalt's fixtures, as basalt reports for its own kernels +(`iq_parity.cpp:10`). diff --git a/docs/research/basalt-nvcc/experts.md b/docs/research/basalt-nvcc/experts.md new file mode 100644 index 00000000..6023f9f5 --- /dev/null +++ b/docs/research/basalt-nvcc/experts.md @@ -0,0 +1,199 @@ +# basalt's routed-expert kernels as nvcc compiles them + +What NVIDIA's compiler emits at every rounding site of `native_expert_grouped` for this pack's Q2_0 / Q2_0 experts +(gate and up, the SwiGLU product with its IEEE q8_1 re-quantization, then down), read from the sm_120 PTX and SASS, +and the Metal form the port writes at each site. This page is the authority the Metal kernels follow +(`docs/design/flash-next.md`, invariant 5), as `matvec.md` is for `native_mmvq` and the q8_1 quantizers. + +Basalt paths are relative to commit `b4c63b55754637f4c72ad53a0f791d425f71eb36`; `path:a-b` means lines a to b there, +and a bare `:N` is a line of the file named last. + +## Method + +- **Sources.** `src/kernels/cuda/iq_kernels.cu` with the headers it includes (`include/basalt/kernels/` + `iq_kernels.hpp`, `dp4a.hpp`, `q8_1_finite.hpp`, `pdl.hpp`, `include/basalt/core/diag.hpp`, + `include/basalt/ggml/ggml_common.h`) and `src/kernels/cuda/gu2.cuh`. Only basalt's public MIT source was sent. +- **Compilers.** Compiler Explorer's public API, as in `matvec.md`: NVCC 13.0.0 (`nvcc130`) and 13.3.0 (`nvcc133`), + PTX and the `SASS (sm_120)` listing. +- **Flags.** `iq_kernels.cu` builds with nvcc's defaults (it is not in the `--use_fast_math` list, + `CMakeLists.txt:185-202`): `-O3 -DNDEBUG -DBASALT_VERSION="0.0.1" + --generate-code=arch=compute_120,code=[compute_120,sm_120]`, exactly, in both versions. +- **Translation units.** The whole file does not fit Compiler Explorer's time limit. Each unit is basalt's text + verbatim: `iq_kernels.cu:1-1171` (the includes, the helpers, the dot products, `Fmt`, `Split`, `row_dot`, + `row_dot_multi`, `row_dot_40_sub8`, `row_dot_20_sub16`, `native_gu_kernel`, `native_gu_multi_kernel`), then + `:1641-1921` (`swiglu_entries_kernel`, `native_down_kernel`, `native_down_multi_kernel`, `q8_1_store`, + `quantize_q8_1_kernel`, `swiglu_q8_1_entries_kernel`), then `gu2.cuh` (included at `:2362`), with the local includes + inlined, then a table that takes the address of the instantiations the unit emits. The lines left out hold other + formats' kernels (the tensor-core IQ3 kernels, the dequantizers) and the host launchers; a kernel's code depends + only on its template and the inlined device functions. One kernel a unit (the SASS listing stops at 5,000 lines): + `native_gu2_kernel<42>`, `native_gu_multi_kernel<42, false>`, `native_gu_kernel<42>`, + `native_down_multi_kernel<42, true>` and `<42, false>`, `native_down_kernel<42>`; the SwiGLU unit emits + `swiglu_q8_1_entries_pdl_kernel`, `swiglu_q8_1_entries_kernel`, `swiglu_entries_kernel` and `quantize_q8_1_kernel`. +- **Version check.** The dataflow tracer of `matvec.md` (operands linked to the instructions that wrote them, printed + as expression templates with leaves `h` an fp16 half converted to fp32, `i` an int32 converted to fp32, `shfl` a value + from another lane, `in` a value from before the basic block, `0` the zero register) gives the same multiset of + templates in 13.0 and 13.3 for every expert kernel. The one difference is the quantizer's upper clamp in the SwiGLU + kernels, applied after the float-to-int conversion in 13.3 and before it in 13.0, which `matvec.md` (Method) shows + gives the same code for every input. + +## Notation + +As in `matvec.md`: fl(e) rounds once to fp32, to nearest even; fma(a, b, c) rounds a·b + c once; h(x) is an fp16 value +converted to fp32 (exact); f(n) an int32 converted to fp32 (exact here). The PTX has no `.ftz` (0 in each dump). In the +SASS, `.FTZ` appears only in `div.rn.f32`'s slow-path subroutine, `__cuda_sm3x_div_rn_noftz_f32_slowpath` (32 +instructions in each dump: four copies of eight): compares against infinity, which flushing cannot change, the add that +returns a NaN operand's NaN, and a negation and a compare on values it has scaled away from the subnormal range. Its +quotient is `div.rn.f32`'s, IEEE's, so every float operation of these kernels is IEEE's, subnormals kept. + +**Where a subnormal can occur.** This GPU flushes subnormal inputs and results of add, multiply, fma and division in +`MTLMathModeSafe` (`tests/kernels/test_basalt_platform.py`), where these IEEE instructions keep them. Each site below +says whether a subnormal can reach it: + +- **The matrix-vector parts cannot.** d2 and d8 are fp16 values, each an integer multiple of 2^-24, so d2·d8 is an + integer multiple of 2^-48 with at most 22 significant bits: exact in fp32, and 0 or at least 2^-48 in magnitude. + f(sumi) is an integer. Every fma(d2·d8, f(sumi), s) and every add of the sums then has an exact value that is a + multiple of 2^-48; below 2^-24 that value has fewer than 24 bits and is exact, above it the rounding grid is a + multiple of 2^-47. So every product, partial sum, butterfly step and output of gate, up and down is 0 or at least + 2^-48 in magnitude, never subnormal, and Metal's `*`, `+` and `fma()` give the IEEE result. +- **The SwiGLU's quotient cannot.** g is a gate output (0 or at least 2^-48 in magnitude) and t = 1 + e is at least 1. + For g < 0, t grows like e^-g, and |g| e^g is at least 2.6e-37 on [-88.72, 0) (normal); beyond -88.72, e overflows to + +inf and the quotient is -0. +- **The SwiGLU product can.** s · up for a very negative g and a small up (g = -70, up = 1e-10 gives -2.8e-39). The + port computes it with `ieee_mul`, which rebuilds a subnormal product from the exact integer product of the + significands (`kernels/common/basalt_q8_1.metal`) and gives IEEE's NaN or infinity where an infinity or a NaN (from + a non-finite fp16 scale in a gate or up row) meets a zero or a subnormal, so that a NaN stays visible as in basalt; + the q8_1 quantizer after it is the IEEE one of `matvec.md` section 3, which already emulates subnormal values. + +## Summary + +| Kernel | Rounding sequence nvcc 13.x emits (sm_120) | Metal | +|---|---|---| +| gate/up, `native_gu2_kernel<42>` (n_embd 2560) | per row and entry: s = fma(fl(d2·d8), f(sumi), s) over calls k = L, L + 32, then k = 64 + L for L < 16, from +0; row B's (d, f) of the third pass moved down 16 lanes; butterfly 16, 8, 4, 2, 1 | `fma(d2 * d8, float(sumi), s)`, `simd_shuffle_down`, `warp_sum` | +| gate/up, `native_gu_multi_kernel<42>` (other n_embd) | the same per-call sequence, lane L taking k = L, L + 32, ...; butterfly | the same | +| SwiGLU + q8_1, `swiglu_q8_1_entries_pdl_kernel` | e = `MUFU.EX2`(fl(g·(−log2 e))) (`ex2.approx.f32`, subnormal outputs kept); t = fl(1 + e); s = fl(g / t) correctly rounded; h = fl(s · up); then `quantize_q8_1_kernel`'s IEEE sequence | `fast::exp2(g * -log2 e)`; `g / (1.0f + e)`; `ieee_mul(s, up)`; `q8_1_store_ieee` | +| down, `native_down_multi_kernel<42>`, n_ff 640 | per row (16 lanes) and entry: s = fma(fl(d2·d8), f(sumi), +0) for call t, s16 = fma(…, +0) for call t + 16 (t < 4, else 0), s = fl(s + s16), then butterfly 8, 4, 2, 1 inside the 16 lanes | the same, `simd_shuffle_xor` 8..1 | +| down, other n_ff | `row_dot_multi`'s sequence from device memory, six entries a pass | the same | + +All the integer work (the Q2_0 codes through `__byte_perm`, the `__dp4a` chains, which in SASS are `IDP.4A.S8.S8`) +is exact, and the port computes it with integer multiply-adds (`dp4a`, `byte_perm` in `kernels/common/basalt_fp.metal`). + +## 1. Gate and up + +### `native_gu2_kernel<42>` (`gu2.cuh:338-357`; `rows2`, `:254-300`; `Fmt2<42>`, `:223-237`) + +Taken for n_embd 2560 (`gu2_usable`, `:360-362`; `launch_gu`, `iq_kernels.cu:2376-2382`), the decode path's shape. +A 256-thread block holds eight warps; warp w takes rows 16b + 2w and 16b + 2w + 1 (both gate or both up); a group's +entries go in batches of 1, 2, 3 or up to 6 (`pair`, `:303-330`). `Fmt2<42>::apply` splits `Split<42>::apply`'s +return into d = fl(d2·d8) and f = f(sumi) (`:230-236`). + +| Site | basalt | PTX (13.3) | SASS 13.0 | SASS 13.3 | Metal | +|---|---|---|---|---|---| +| d | `gu2.cuh:234` `r.d2 * __low2float(x->ds)` | `mul.f32` | `FMUL R6, R6, R41` | `FMUL R8, R8, R43` | `d2 * d8` | +| f | `:235` `(float) s` | `cvt.rn.f32.s32` | `I2FP.F32.S32` | `I2FP.F32.S32` | `float(sumi)` | +| first call | `:276` `__fmaf_rn(d, f, sA[c])`, sA = 0 | `fma.rn.f32 %r, %r, %r, 0f00000000` | `FFMA R7, R6, R7, RZ` | `FFMA R10, R8, R13, RZ` | `fma(d, f, s)`, s = +0 | +| second call | `:276`, `:278` | `fma.rn.f32` | `FFMA R7, R8, R16, R7` | `FFMA R10, R15, R11, R10` | `fma(d, f, s)` | +| third pass, row B's (d, f) | `:289` `__shfl_down_sync(0xffffffffu, d, 16)` (and f) | `shfl.sync.down.b32 ..., 16, 31, -1` ×2 | `SHFL.DOWN PT, R13, R70, 0x10, 0x1f` | `SHFL.DOWN PT, R19, R73, 0x10, 0x1f` | `simd_shuffle_down` of the bits, 16 | +| third pass, lanes 0..15 | `:291-292` | `fma.rn.f32` ×2 | `@!P0 FFMA R7, R70, R64, R7`; `@!P0 FFMA R6, R13, R15, R6` | `@!P0 FFMA R10, R73, R17, R10`; `@!P0 FFMA R8, R19, R20, R8` | `fma(d, f, sA)`; `fma(dB, fB, sB)` | +| `warp_sum` | `:294-295`; `iq_kernels.cu:545-549` | `shfl.sync.bfly.b32` and `add.f32`, offsets 16..1 | `SHFL.BFLY` + `FADD`, ×5 | the same | `x + simd_shuffle_xor(x, o)`, o = 16, 8, 4, 2, 1 | + +The tracer's templates, both versions: `FFMA(FMUL(h, h), i, FFMA(FMUL(h, h), i, FFMA(FMUL(h, h), i, 0)))` for row A +and `FFMA(shfl, shfl, FFMA(FMUL(h, h), i, FFMA(FMUL(..), i, 0)))` for row B, then five `FADD(…, shfl)`. Counts (13.0 +and 13.3): 60 `FMUL`, 72 `FFMA`, 120 `FADD`, 60 `I2FP`, 24 `SHFL.DOWN` and 24 `SHFL.BFLY` per offset, which is 12 +entries (the batches of 1, 2, 3 and 6) × 5 calls, × 6 fmas and × 2 rows × 5 adds. + +### `native_gu_multi_kernel<42, false>` (`iq_kernels.cu:1125-1171`; `row_dot_multi`, `:898-919`) + +Taken at other n_embd (the 512 × 256 shape of `native_grouped_parity`). One warp a row, eight rows a block; lane L +takes calls k = L, L + 32, ... (call k: block k / 2, half k % 2, against q8_1 block k of the entry's row). + +| Site | basalt | PTX (13.3) | SASS 13.0 | SASS 13.3 | Metal | +|---|---|---|---|---|---| +| `s[c] += S::apply(...)` | `:913`, apply `:894` `r.d2 * d8 * sumi` | `mul.f32`; `cvt.rn.f32.s32`; `fma.rn.f32 %r, %r, %r, %r` | `FMUL R41, R10, R41`; `FFMA R4, R41, R9, R4` | `FMUL R10, R10, R41`; `FFMA R5, R10, R9, R5` | `fma(d2 * d8, float(sumi), s)` from +0 | +| `warp_sum` | `:917` | `add.f32`, `shfl.sync.bfly.b32` ×5 | `SHFL.BFLY` + `FADD` ×5 | the same | `warp_sum` | + +The contraction is the front end's: `(d2 * d8) * sumi` added to s admits one contraction, and PTX already has +`fma.rn.f32` (the comment at `gu2.cuh:5-6` says the same). So the two gate/up kernels compute the same sequence per +(row, entry), as `gu2.cuh:5-11` states; `native_gu_kernel<42>` (the per-entry kernel of basalt's old path, +`row_dot`, `:552-561`) has the same template, `FFMA(FMUL(h, h), i, in)` then five adds, in both versions. + +## 2. The SwiGLU product and its q8_1 (`swiglu_q8_1_entries_pdl_kernel`, `gu2.cuh:375-390`) + +The value, quoted: `const float h = __fmul_rn(g / (1.0f + __expf(-g)), up[i]); q8_1_store(h, hq, i);` (`:386-388`), +over i in [grp_start[0] · n_ff, grp_start[n_groups] · n_ff), grid-strided; n_ff is a multiple of 32, so a warp is one +q8_1 block. `swiglu_q8_1_entries_kernel` (`iq_kernels.cu:1909-1921`, basalt's old path) has the same body. + +| Site | basalt | PTX (13.3) | SASS (13.3; 13.0 has the same lines) | Metal | +|---|---|---|---|---| +| `__expf(-g)` | `:387` | `mul.f32 %r, %r, 0fBFB8AA3B`; `ex2.approx.f32` | `FMUL R0, R2, -1.4426950216293334961`; `FSETP.GEU.AND P0, PT, R0, -126, PT`; `@!P0 FMUL R0, R0, 0.5`; `MUFU.EX2 R10, R0`; `@!P0 FMUL R10, R10, R10` | `fast::exp2(g * as_type(0xBFB8AA3Bu))` | +| t | `:387` `1.0f + e` | `add.f32 %r, %r, 0f3F800000` | `FADD R13, R10, 1` | `1.0f + e` | +| g / t | `:387` | `div.rn.f32` | `MUFU.RCP R10, R13`; `FCHK P0, R2, R13`; `FFMA R11, -R13, R10, 1`; `FFMA R11, R10, R11, R10`; `FFMA R10, R2, R11, RZ`; `FFMA R3, -R13, R10, R2`; `FFMA R10, R11, R3, R10`; slow path `__cuda_sm3x_div_rn_noftz_f32_slowpath` when `FCHK` fails | `g / t` (correctly rounded in `MTLMathModeSafe`) | +| h | `:387` `__fmul_rn(s, up[i])` | `mul.rn.f32` | `FMUL R0, R3, R10` | `ieee_mul(s, up)` | +| q8_1 of h | `:388`, `q8_1_store` (`iq_kernels.cu:1880-1892`) | `abs.f32`; `max.f32` ×5; `add.f32` ×5; `div.rn.f32 %r, %r, 0f42FE0000`; `div.rn.f32`; `add.rz.f32`; `cvt.rn.f16.f32` ×2 | `matvec.md` section 3's sequence | `q8_1_store_ieee` (`basalt_q8_1.metal`) | + +Notes: + +- **The exponential is the IEEE build's `ex2.approx.f32`.** Without `--use_fast_math` the product with −log2 e is a + plain `FMUL` and the exponential keeps subnormal outputs: below −126 `ptxas` halves the argument, takes `MUFU.EX2` + and squares the result. `MUFU.EX2` is NVIDIA's approximate base-2 exponential, which MSL documents no operation to + reproduce; the port keeps the contract's mapping, `fast::exp2` of the product basalt's PTX forms. The halving path + changes no result here: it runs only for e below 2^-126, and then t = fl(1 + e) is 1 for any such e. +- **The division and the product are IEEE.** `div.rn.f32` is the correctly rounded quotient (the iteration, with + `FCHK` sending the cases it cannot round to the slow path). `__fmul_rn` is a plain `mul.rn.f32`, rounded on its own: + basalt writes it so the product cannot contract into the first add of `q8_1_store`'s block sum + (`iq_kernels.cu:1902-1908`). Metal's `/` rounds correctly in safe mode (MSL 4.1 Table 8.1; measured in + `test_basalt_platform.py`), and no subnormal reaches the quotient (Notation). The product can be subnormal, hence + `ieee_mul`. +- **The SwiGLU value is the one place the port can differ from CUDA.** Where `fast::exp2` and `MUFU.EX2` disagree in + the last bit of e, t, s and h can follow, and with them a code, the block's scale or its sum. Everything after e + is CUDA's arithmetic; the tests take e from the GPU and check every other step bit for bit. + +## 3. Down + +### `native_down_multi_kernel<42>`, n_ff 640 (`iq_kernels.cu:1781-1826`; `row_dot_20_sub16`, `:980-1014`) + +The decode path's shape: 20 calls a row. A 256-thread block holds 16 rows of 16 lanes (`d_rows` 16 for Q2_0 at n_ff +640, `:2594`); the q8_1 rows of up to six entries are staged in shared memory (`s_hq_buf`, `:1726`, `:1792-1797`). +`DEP` (`true` on the decode path's chain) adds only a prefetch and the programmatic wait: `<42, true>` and +`<42, false>` have identical template multisets in each version (13.0 and 13.3 differ only in how many shared-memory +stores the staging copy unrolls into, 7 against 8). + +| Site | basalt | PTX (13.3) | SASS 13.0 | SASS 13.3 | Metal | +|---|---|---|---|---|---| +| call t | `:994` `s[c] += S::apply(...)`, s = 0 | `mul.f32`; `cvt.rn.f32.s32`; `fma.rn.f32 %r, %r, %r, 0f00000000` | `FMUL R14, R14, R17`; `FFMA R16, R14, R31, RZ` | `FMUL R14, R14, R17`; `FFMA R16, R14, R31, RZ` | `fma(d2 * d8, float(sumi), 0.0f)` | +| call t + 16, t < 4 | `:1004` `s16[c] += S::apply(...)`, s16 = 0 | `mul.f32`; `fma.rn.f32 %r, %r, %r, 0f00000000` | `FMUL R14, R14, R35`; `FFMA R17, R14, R15, RZ` | `FMUL R14, R14, R35`; `FFMA R17, R14, R15, RZ` | the same; s16 = 0 for t ≥ 4 | +| `__fadd_rn(s, s16)` | `:1009` | `add.rn.f32` | `FADD R35, R16, R17` | `FADD R35, R16, R17` | `s + s16` | +| butterfly | `:1011` offsets 8, 4, 2, 1 | `shfl.sync.bfly.b32 ..., 8, 31, -1` ... `1` with `add.f32` | `SHFL.BFLY` + `FADD` ×4 | the same | `s + simd_shuffle_xor(s, o)`, o = 8, 4, 2, 1 | + +The 16-lane tree is `row_dot_multi`'s on 32 lanes with lanes 20..31 holding zero (`:980-981`): the first butterfly +step of the 32-lane tree adds call t and call t + 16 on lane t, which `__fadd_rn` does here; s is never −0 (an fma +of a zero product with +0 is +0 in round to nearest), so adding the zero of an idle lane leaves it unchanged. + +### `native_down_multi_kernel<42>`, other n_ff (`:1864-1875`) + +`row_dot_multi<42, 6>` from device memory, one warp a row, eight rows a block: `FFMA(FMUL(h, in), i, in)` in the loop +and five adds, as `native_gu_multi_kernel`. `native_down_kernel<42>` (basalt's old path, `:1648-1668`) runs `row_dot` +per entry, the same template. + +Counts for `native_down_multi_kernel<42, true>` (13.0 and 13.3): 24 `FMUL`, 24 `FFMA`, 24 `I2FP`: the batches of 1, +2 and 6 entries take two calls each on the 16-lane path (18) and the six entries one call each in the generic loop +(6). The `FADD`s (128) include the warp-divergence fallbacks the compiler emits around each butterfly (`BRA.DIV`), +which repeat the same adds. + +## 4. Metal + +`kernels/common/basalt_experts.metal` holds the three kernels: `basalt_expert_gu` (the two gate/up kernels, selected +by n_embd as basalt's launcher does), `basalt_expert_swiglu_q8_1` and `basalt_expert_down` (the 16-lane path at n_ff +640, the generic one otherwise). Each starts with `#pragma STDC FP_CONTRACT OFF` (through `basalt_fp.metal`) and +writes `fma()` exactly at the `FFMA` sites above, plain `*` and `+` at the `FMUL` and `FADD` sites; nothing flushes, +because no subnormal reaches them, except the SwiGLU product (`ieee_mul`) and the quantizer, which emulate IEEE +subnormals. The Q2_0 decode, the q8_1 word readers and `dp4a` are the device functions `native_mmvq` uses +(`basalt_fp.metal`). Basalt's plan pointers (`grp_ptr`, one blob address a group) stay pointers: a table of 64-bit +GPU addresses, each 2-byte aligned and inside a resident buffer, so the blobs may sit in several buffers; the plan's +other arrays, the scratch and the output keep basalt's layout. + +`tests/kernels/test_basalt_experts.py` checks every stage bit for bit against the numpy emulation of this page +(`tests/kernels/basalt_emu.py`: `q2_0_dots`, `swiglu_q8_1`, with the exponential taken from the GPU's `expf_neg`), +the two gate/up kernels and the two down trees bitwise against each other, `ieee_mul` against numpy's IEEE product on +subnormal products and on infinities and NaN against zeros and subnormals, and ports `iq_multi_parity`'s +`check_grouped` and `native_grouped_parity` (512 x 256 and, as its `--gu2` run, 2560 x 640) with float64 references +for each stage and the whole expert. diff --git a/docs/research/basalt-nvcc/matvec.md b/docs/research/basalt-nvcc/matvec.md new file mode 100644 index 00000000..35b1235d --- /dev/null +++ b/docs/research/basalt-nvcc/matvec.md @@ -0,0 +1,349 @@ +# basalt's matrix-vector kernels as nvcc compiles them + +What NVIDIA's compiler emits at every rounding site of basalt's q8_1 activation quantizers and `native_mmvq`, read +from the sm_120 PTX and SASS, and the Metal form the port writes at each site. This page is the authority the Metal +kernels follow (`docs/design/flash-next.md`, invariant 5): fusion and its operands, flush-to-zero, the division +sequence and each conversion. Other kernel families get their own pages in `docs/research/basalt-nvcc/`. + +Basalt paths are relative to commit `b4c63b55754637f4c72ad53a0f791d425f71eb36`; `path:a-b` means lines a to b there, +and a bare `:N` is a line of the file named last. + +## Method + +- **Sources.** `src/kernels/cuda/native_mmvq.cu` with the headers it includes (`include/basalt/kernels/` + `native_mmvq.hpp`, `bf16_bits.hpp`, `dp4a.hpp`, `q8_1_finite.hpp`, `iq_kernels.hpp`, `pdl.hpp`), and for the IEEE + quantizer `src/kernels/cuda/iq_kernels.cu` with its headers and `include/basalt/ggml/ggml_common.h`. Only basalt's + public MIT source was sent. +- **Compilers.** Compiler Explorer's public API (`POST https://godbolt.org/api/compiler//compile` with + `"compilerOptions": {"produceDevice": true}`), which returns the PTX and the `SASS (sm_120)` listing: NVCC 13.0.0 + (`nvcc130`), 13.2.0 (`nvcc132`) and 13.3.0 (`nvcc133`). Basalt requires CUDA 13 (`CMakeLists.txt:32-33`). +- **Flags.** Basalt's own for each file: a Release build, `-O3 -DNDEBUG` (`CMakeLists.txt:12-14`), + `-DBASALT_VERSION="0.0.1"` (`:7`), `--generate-code=arch=compute_120,code=[compute_120,sm_120]` (architecture 120 + only, `:3-4`, `:26-31`), and `--use_fast_math` for `native_mmvq.cu` (`:185-202`); `iq_kernels.cu` builds with + nvcc's defaults. The 13.0 and 13.3 compiles use exactly these flags. The 13.2 compiles use `-O3 -DNDEBUG + -arch=sm_120 -lineinfo` (plus `--use_fast_math` for `native_mmvq.cu`): `-arch=sm_120` is the same target, and + `-lineinfo` attributes every PTX and SASS line to a basalt file and line. The dataflow comparison below finds the + same arithmetic in all three, so `-lineinfo` changed nothing that this page records. +- **Translation units.** Compiler Explorer's time limit does not fit the whole of `native_mmvq.cu`, and its SASS + listing stops at about 5,000 lines (`[truncated; too many lines]`). Each unit is basalt's file verbatim up to the end + of its device code (`native_mmvq.cu:1-1151`: the includes, block structs, device functions, every kernel template + and the format traits; the host launchers and the test-only tensor-core kernel after line 1151 are left out; for + the IEEE quantizer `iq_kernels.cu:1-1900`), with the quoted local includes inlined under `#line` directives, then a + table that takes the address of each kernel instantiation the unit should emit. A kernel's code depends only on its + template and the inlined device functions, so the cut changes nothing in it. One unit per weight type. +- **Reading a site.** The PTX shows what the front end (NVVM) fused (`fma.rn.ftz.f32`), the division it chose + (`div.approx.ftz.f32` or `div.rn.f32`) and each conversion; the SASS shows what `ptxas` made of it, which can fuse + further (Q4_K and Q5_K below) or replace an approximate division by a constant with a multiply. +- **Version check.** A dataflow tracer links each SASS floating-point instruction's operands to the instructions that + wrote them and prints every result as an expression template whose leaves are classes: `h.H0` / `h.H1` an fp16 + value converted to fp32 from the low or high half of a word (`HADD2.F32 -RZ, x.H0_H0`; d and the q8_1 d8 are low + halves, dmin and the q8_1 sum s8 high halves), `i` an int32 converted to fp32 (`I2FP.F32.S32`), `shm` a shared-memory + partial, `shfl` a value received from another lane, `in` a loop-carried accumulator, `0` the zero register. The + multiset of templates of every one-column kernel and of the three quantizers is identical in 13.0, 13.2 and 13.3, + with one exception: 13.3 applies the quantizers' upper clamp after the float-to-int conversion (`SEL R6, R0, 0x7f, + !P1`) where 13.0 and 13.2 select 127.0 before it (`FSEL R0, R0, 127, !P1`). Both give the same code for every input, + NaN included (`q > 127` is false for NaN, and the conversion maps NaN to 0 in both). + +## Notation + +- fl(e): e rounded once to fp32, to nearest even. fma(a, b, c): a·b + c rounded once. h(x): fp16 to fp32 (exact). + f(n): int32 to fp32 (exact here; no integer in these kernels reaches 2^24). +- **.FTZ** (`.ftz` in PTX): subnormal inputs and results are flushed to sign-preserving zero. +- Metal forms use the helpers of `kernels/common/basalt_fp.metal`: `ftz(x)` flushes a subnormal to signed zero; + `add_ftz`, `mul_ftz`, `fma_ftz`, `max_ftz` flush their inputs and result around the correctly rounded operation + (`max_ftz` returns one of its flushed inputs); `rcp_ftz(x)` is `ftz(1.0f / ftz(x))`, the correctly rounded + reciprocal that stands where SASS has `MUFU.RCP`. Every Metal source of the port starts with `#pragma STDC + FP_CONTRACT OFF`, so only an explicit `fma()` fuses. +- **This GPU flushes its arithmetic, not its comparisons.** Measured on the M3 Max (Apple family 9) in + `MTLMathModeSafe`, the repository default: `x + y`, `x * y`, `fma` and `x / y` flush subnormal inputs and subnormal + results to sign-preserving zero, as MSL section 8.1 permits. `x * y` and `fma` decide on the exact value, before + rounding: an exact result in [2^-126 − 2^-150, 2^-126), which rounds to 2^-126, comes back as zero too. `fmax` and + `fmin` do not flush: their comparison treats a subnormal as zero, and the chosen operand comes back unflushed, the + second one on a tie (`fmax(s, 0)` is +0, `fmax(0, s)` is s, and of two subnormals `fmax` returns the second, even + the smaller). `fabs`, moves and loads keep the bits (`tests/kernels/test_basalt_platform.py`). So the hardware does + what SASS does at the `.FTZ` adds (an exact sum below 2^-126 needs no rounding), but not at a `.FTZ` multiply or fma + whose exact result rounds up to 2^-126 (PTX: the result "rounded to single precision", then a subnormal result + flushed), nor at the `.FTZ` absolute value and maximum (`abs.ftz` and the amax butterfly's `FMNMX.FTZ`, section 1): + the helpers flush explicitly, and `fma_ftz` (with `mul_ftz` = `fma_ftz(a, b, -0)`) returns ±2^-126 there from the + exact value, which makes every site independent of the GPU. At basalt's IEEE sites (no `.ftz`) the arithmetic's + flushing is a difference, treated in section 3. + +## Summary + +| Kernel | Rounding sequence nvcc 13.x emits (sm_120) | Metal | +|---|---|---| +| `native_quantize_q8_1_kernel` | `amax / 127.0f` becomes `FMUL.FTZ amax, 0x3C010204` (fl(1/127)); `xi / d` becomes `MUFU.RCP` then `FMUL.FTZ`; abs, max, add `.FTZ`; `roundf` exact | `mul_ftz(amax, 1/127)`; `mul_ftz(xi, rcp_ftz(d))` | +| `native_swiglu_quantize_q8_1_kernel` | `__expf(-g)` as `MUFU.EX2(FMUL.FTZ g, -log2 e)`; `__fadd_rn`; `__fdividef` as `MUFU.RCP` + `FMUL.FTZ`; `__fmul_rn`; then the native quantizer | `fast::exp2` of the same product; the rest as the native quantizer | +| `quantize_q8_1_kernel` (IEEE) | correctly rounded `div.rn.f32` for both divisions; no `.ftz`; `roundf` exact | `/`; subnormal operands emulated (section 3) | +| Q2_0 | tmp = fma(fl(d2·d8), f(sumi), tmp) | `fma_ftz(mul_ftz(d2, d8), float(sumi), tmp)` | +| Q3_K | sumf = fma(d8_i, f(dot_i·sc_i), sumf), i = 0..3; tmp = fma(d3, sumf, tmp) | the same, `fma_ftz` | +| Q4_K, Q5_K | sumf_d = fma(d8_i, f(dot1_i·sc_i), sumf_d), sumf_m = fma(d8_i, f(dot2_i·m_i), sumf_m), i = 0, 1; v = fma(dm.x, sumf_d, −fl(dm.y·sumf_m)); tmp = tmp + v | the same, `fma_ftz`, `mul_ftz`, `add_ftz` | +| Q6_K | sumf = fma(d8_i, f(dot_i·sc_i), sumf), i = 0, 1; tmp = fma(d, sumf, tmp) | the same | +| IQ4_XS, IQ4_NL | tmp = fma(fl(h(d)·d8), f(sumi), tmp) | the same | +| Q4_0, Q5_0 | inner = fma(f(sumi), d8, fl(−k·s8)), k = 4 or 8; tmp = fma(d, inner, tmp) | the same | +| Q8_0 | tmp = fma(fl(d0·d1), f(sumi), tmp) | the same | +| every type | cross-warp: ((tmp + p0) + p1) + p2; butterfly 16, 8, 4, 2, 1; all `FADD.FTZ` | `add_ftz`, `simd_shuffle_xor` | +| `native_mmvq_multi_kernel`, 2 to 8 columns | per (column, row) the one-column kernel's sequence above, site for site (section 6) | the same `apply_acc`, one source | + +Every `[H]` of the scoping report (`a·b − c·d` in Q4_K and Q5_K, `sumi·d8 − k·s8` in Q4_0 and Q5_0) is settled by the +SASS above, identically in the three compiler versions. + +## 1. `native_quantize_q8_1_kernel` (`native_mmvq.cu:146-159`, `q8_1_finite.hpp:16-31`) + +Built with `--use_fast_math`. One warp per 32-value block, lane l holds value l. + +| Site | basalt | PTX (13.2) | SASS (13.2) | Metal | +|---|---|---|---|---| +| \|xi\| | `native_mmvq.cu:153` `fabsf(xi)` | `abs.ftz.f32 %r9, %r3` | `FADD.FTZ R4, \|R0\|, -RZ` (and `\|R0\|` folded into the first max) | `abs_ftz(xi)` = `ftz(fabs(xi))` | +| amax butterfly | `:141` `fmaxf(x, __shfl_xor_sync(...))`, offsets 16..1 | `max.ftz.f32` ×5 | `FMNMX.FTZ` ×5 | `max_ftz(x, simd_shuffle_xor(x, o))` | +| sum butterfly | `:133` `x += __shfl_xor_sync(...)` | `add.ftz.f32` ×5 | `FADD.FTZ` ×5 | `add_ftz(x, simd_shuffle_xor(x, o))` | +| d | `:155` `amax / 127.0f` | `div.approx.ftz.f32 %r30, %r19, %r29` (`%r29` = `0f42FE0000`) | `FMUL.FTZ R6, R4, 0.0078740157186985015869` | `mul_ftz(amax, as_type(0x3C010204u))` | +| finite clamp | `q8_1_finite.hpp:19` | `abs.ftz`, `setp.gt.ftz.f32 ... 0f477FE000`, `copysign.f32`, `selp.f32` | `FSETP.GT.FTZ.AND P1, PT, \|R6\|, 65504`, `LOP3.LUT` (sign), `FSEL` | `fabs(v) > 65504.0f ? copysign(65504.0f, v) : v` | +| all-zero block | `:24` `amax == 0.0f` | `setp.eq.ftz.f32 %p13, %r19, 0f00000000` | `FSETP.NEU.FTZ.AND P2, PT, R4, RZ` | `amax == 0.0f` (amax is already flushed) | +| xi / d | `:25` | `div.approx.ftz.f32 %r34, %r3, %r5` | `MUFU.RCP R9, R7`; `FMUL.FTZ R0, R0, R9` | `mul_ftz(xi, rcp_ftz(d))` | +| `roundf` | `:25` | `copysign.f32` with `0f3F000000`; `add.rz.ftz.f32`; `cvt.rzi.f32.f32` | `LOP3.LUT` (±0.5), `FADD.FTZ.RZ`, `FRND.TRUNC` | `round(q)` | +| clamp, int8 | `:26` | `setp.gt/lt.ftz.f32` with ±127, `selp.f32`, `cvt.rzi.ftz.s32.f32` | `FSETP.GT.FTZ`, `FMNMX.NAN R0, R9, -127`, `FSEL ... 127`, `F2I.FTZ.TRUNC.NTZ` | clamp to ±127; NaN to 0 | +| ds | `:29-31` | `q8_1_finite` on d and sum, then `cvt.rn.f16.f32` ×2 | `F2FP.F16.F32.PACK_AB R13, R13, R0` | `half(v)` (round to nearest even) | + +Notes: + +- **The scale is a multiply.** PTX keeps `div.approx.ftz.f32` by 127; `ptxas` replaces an approximate division by a + constant with a multiply by the constant's reciprocal, `0x3C010204`, which is fl(1/127), the correctly rounded + reciprocal. So d = fl(amax · fl(1/127)), which is not always fl(amax / 127) (`tests/kernels/test_basalt_q8_1.py` + counts how often). The Metal form multiplies by the same constant and is bit-exact to CUDA here. +- **The codes divide by a reciprocal.** `MUFU.RCP` is an approximate reciprocal (`rcp.approx.ftz.f32`) whose exact + results NVIDIA does not document; the port uses the correctly rounded `1.0f / d` and the same flush-to-zero + multiply. The port's code equals CUDA's wherever `MUFU.RCP(d)` is the correctly rounded reciprocal of d; where it + is not, the product can differ in its last bit and, near a .5 boundary, the code by one. Basalt's own test accepts + that: `native_quantize_q8_1` may be "near" (`iq_multi_parity.cpp:463-466`). +- **`roundf` is exact.** CUDA's `roundf` is trunc(x + copysign(0.5, x)) with the add rounded toward zero. For every + float x this is round half away from zero: fl_rz(|x| + 0.5) is the largest float not above |x| + 0.5, every integer + below 2^24 is a float, so its truncation is floor(|x| + 0.5); at and above 2^23 every float is an integer, which the + add leaves unchanged. Metal's `round` is correctly rounded with ties away from zero (MSL Table 8.1; measured). +- **Edge cases the Metal form keeps.** amax is the max of flushed values, so a block of subnormals is an all-zero + block (codes 0). A normal amax below 127·2^-126 gives a subnormal d that `FMUL.FTZ` flushes to 0; the codes are then + xi·rcp(0) = ±inf, clamped to ±127, or NaN for a zero or subnormal xi, which `F2I.TRUNC.NTZ` converts to 0. The + Metal form reproduces each step (`rcp_ftz(0)` is +inf, the clamp and the NaN rule are explicit). + +## 2. `native_swiglu_quantize_q8_1_kernel` (`native_mmvq.cu:161-177`) + +The SwiGLU value, quoted: `__fmul_rn(__fdividef(gi, __fadd_rn(1.0f, __expf(-gi))), up[i])` (`:170`). Then the native +quantizer's sequence of section 1, instruction for instruction. + +| Site | PTX (13.2) | SASS (13.2) | Metal | +|---|---|---|---| +| `__expf(-gi)` | `mul.ftz.f32 %r10, %r9, 0fBFB8AA3B`; `ex2.approx.ftz.f32 %r11, %r10` | `FMUL.FTZ R3, R6, -1.4426950216293334961`; `MUFU.EX2 R3, R3` | `ftz(fast::exp2(mul_ftz(gi, -1.44269502f)))` | +| `__fadd_rn(1.0f, e)` | `add.rn.ftz.f32 %r13, %r12, %r11` | `FADD.FTZ R5, R3, 1` | `add_ftz(1.0f, e)` | +| `__fdividef(gi, t)` | `div.approx.ftz.f32 %r14, %r9, %r13` | `MUFU.RCP R5, R5`; `FMUL.FTZ R4, R6, R5` | `mul_ftz(gi, rcp_ftz(t))` | +| `__fmul_rn(s, up)` | `mul.rn.ftz.f32 %r3, %r14, %r15` | `FMUL.FTZ R4, R4, R9` | `mul_ftz(s, up)` | + +`MUFU.EX2` is NVIDIA's approximate base-2 exponential; MSL documents no operation with its bits. The port keeps the +contract's mapping for approximate exponentials (`fast::exp2` of the product basalt's PTX forms), so the SwiGLU value +can differ from CUDA's in its last bits, and with it a code, the block sum or the scale. The product with −log2 e, +the add, the reciprocal's multiply and the product with `up` are CUDA's. + +## 3. `quantize_q8_1_kernel`, the IEEE quantizer (`iq_kernels.cu:1880-1900`) + +Built with nvcc's defaults. `q8_1_store` runs the two butterflies in one loop (`:1883-1887`); the rest is +`q8_1_finite.hpp`'s. + +| Site | PTX (13.2) | SASS (13.2) | Metal | +|---|---|---|---| +| \|xi\|, amax, sum | `abs.f32`; `max.f32` ×5; `add.f32` ×5 | `FADD R10, \|R0\|, -RZ`; `FMNMX` ×5; `FADD` ×5 | IEEE max and add (subnormals kept, below) | +| d = amax / 127 | `div.rn.f32 %r27, %r25, 0f42FE0000` | `FCHK P0, R2, 127`; `FFMA R3, R2, UR4, RZ`; `FFMA R8, R3, -127, R2`; `FFMA R3, R8, UR4, R3` (a correctly rounded quotient; `FCHK` sends the cases the iteration cannot round to a slow path) | `amax / 127.0f` (subnormal result emulated) | +| xi / d | `div.rn.f32 %r31, %r1, %r3` | `MUFU.RCP R2, R7`; `FCHK P0, R0, R7`; `FFMA R3, -R7, R2, 1`; `FFMA R3, R2, R3, R2`; `FFMA R2, R0, R3, RZ`; `FFMA R8, -R7, R2, R0`; `FFMA R2, R3, R8, R2` (correctly rounded) | `xi / d` (subnormal operands emulated) | +| `roundf`, clamp, int8 | `add.rz.f32`, `cvt.rzi.f32.f32`; `cvt.rzi.s32.f32` | `FADD.RZ`, `FRND.TRUNC`; `FMNMX.NAN`, `FSEL`, `F2I.TRUNC.NTZ` | as section 1 | +| ds | `cvt.rn.f16.f32` ×2 | `F2FP.F16.F32.PACK_AB` | `half(v)` | + +Nothing flushes here. Metal's add and division do, and its `fmax` compares a subnormal as zero (Notation), so a +literal port would differ from CUDA on subnormal values: in a block of subnormals every comparison of the amax +butterfly is a tie and `fmax` returns its second operand, not the larger; a subnormal activation would drop out of the +block sum; and a subnormal d would become 0. The port emulates IEEE behaviour where a subnormal can occur, from +integer operations on the bits: amax as the largest bit pattern of the absolute values, an add that rescales two small +operands by 2^64 and rebuilds a subnormal sum from its integer significand, d = amax / 127 rounded on the subnormal +grid with integer division when it falls below 2^-126, and the codes' quotient taken on rescaled operands. Above the +subnormal range each of these is the plain IEEE operation, so the emulation changes no result on normal data. + +## 4. The reduction every `native_mmvq` kernel shares + +`native_mmvq.cu:269-282` (Q5_K; every other one-column kernel repeats it): warps 1..3 store their partials, warp 0 +adds them in warp order, then `warp_sum` (`:130-136`). + +| Site | PTX (13.2) | SASS (13.2) | Metal | +|---|---|---|---| +| `tmp[i] += partial[l][i][threadIdx.x]`, l = 0, 1, 2 | `add.ftz.f32` ×3 | `FADD.FTZ R3, R3, R24`; `FADD.FTZ R3, R3, R4`; `FADD.FTZ R3, R3, R6` (Q3_K) | `add_ftz` ×3, in warp order | +| `warp_sum` | `shfl.sync.bfly.b32 ..., 16, 31, -1`; `add.ftz.f32`; offsets 8, 4, 2, 1 likewise | `SHFL.BFLY` + `FADD.FTZ` ×5 | `x = add_ftz(x, simd_shuffle_xor(x, o))`, o = 16, 8, 4, 2, 1 | + +Lane L ends with ((t_L + t_32+L) + t_64+L) + t_96+L, then the butterfly; both lanes of a butterfly pair add the same +two values, so every lane holds the same bits. `simd_sum` documents no order and is not used. + +## 5. The dot products, one column + +Every kernel below is the `false` (one row per block) instantiation; the small-K instantiation (`true`, four rows per +block) has the same templates per row. A thread's `tmp` starts at +0 and takes its blocks in ascending kbx; the first +iteration's add of +0 appears as the zero register. The fp16 values reach fp32 through conversions inlined from +CUDA 13.2's `cuda_fp16.hpp`, attributed to its lines 778 (the implicit conversion in `const float d = w->d`), 788 +(`__low2float`) and 1055 (`__half22float2`): `cvt.f32.f16` in PTX, `HADD2.F32 R, -RZ, R.H0_H0` (or `.H1_H1`) in SASS, +all exact. + +### Q2_0 (`q2_q8_dot`, `native_mmvq.cu:288-309`; kernel `:313-349`) + +| Site | PTX (13.2) | SASS (13.2) | Metal | +|---|---|---|---| +| `d2 * d8 * sumi` (`:308`) | `mul.ftz.f32 %r72, %r17, %r43`; `cvt.rn.f32.s32 %r73, %r39` | `FMUL.FTZ R0, R0, R7`; `I2FP.F32.S32 R5, R5` | `mul_ftz(d2, d8)`, `float(sumi)` | +| `tmp[i] += ...` (`:331`) | `fma.rn.ftz.f32 %r209, %r72, %r73, %r209` | `FFMA.FTZ R0, R13, R11, R0` | `fma_ftz(mul_ftz(d2, d8), float(sumi), tmp)` | + +The integer part is `__byte_perm` table lookups and `__dp4a` (`IDP.4A.S8.S8`): exact; the port computes it with +integer multiply-adds. + +### Q3_K (`q3_q8_dot_impl`, `:360-381`; `q3_q8_dot`, `:383-398`; kernel `:401-437`) + +| Site | PTX (13.2) | SASS (13.2) | Metal | +|---|---|---|---| +| `sumf += d8[i] * (DP4A(vi, u[i], 0) * sc)` (`:378`), i = 0..3 | `cvt.rn.f32.s32`; `fma.rn.ftz.f32 %r91, %r30, %r90, 0f00000000`, then `fma.rn.ftz.f32 %r117, %r32, %r116, %r91` and so on | `I2FP.F32.S32`; `FFMA.FTZ R0, R0, R25, RZ`; `FFMA.FTZ R0, R35, R27, R0`; ... | `sumf = fma_ftz(d8[i], float(dot * sc), sumf)` from 0 | +| `return d3 * sumf` into `tmp +=` (`:380`, `:419`) | `fma.rn.ftz.f32 %r184, %r29, %r159, %r184` | `FFMA.FTZ R24, R31, R13, R24` | `tmp = fma_ftz(d3, sumf, tmp)` | + +### Q4_K (`q4_q8_dot_impl`, `:522-539`; `q4_q8_dot`, `:541-574`; kernel `:578-617`) + +| Site | PTX (13.2) | SASS (13.2) | Metal | +|---|---|---|---| +| `sumf_d += d8[i] * (dot1 * sc[i])` (`:534`) | `fma.rn.ftz.f32 %r73, %r25, %r72, 0f00000000`; `fma.rn.ftz.f32 %r83, %r27, %r82, %r73` | `FFMA.FTZ R0, R0, R3, RZ`; `FFMA.FTZ R0, R33, R15, R0` | `fma_ftz(d8[i], float(dot1 * sc[i]), sumf_d)` | +| `sumf_m += d8[i] * (dot2 * m[i])` (`:535`) | `fma.rn.ftz.f32 %r77, %r25, %r76, 0f00000000`; `fma.rn.ftz.f32 %r87, %r27, %r86, %r77` | `FFMA.FTZ R14, R0, R15, RZ`; `FFMA.FTZ R14, R33, R19, R14` | `fma_ftz(d8[i], float(dot2 * m[i]), sumf_m)` | +| `dm4f.x * sumf_d - dm4f.y * sumf_m` (`:538`) | `mul.ftz.f32 %r88, %r83, %r47`; `mul.ftz.f32 %r89, %r87, %r49`; `sub.ftz.f32 %r90, %r88, %r89` (no fusion in PTX) | `HADD2.F32 R17, -RZ, R20.H1_H1`; `FMUL.FTZ R17, R14, R17`; `HADD2.F32 R3, -RZ, R20.H0_H0`; `FFMA.FTZ R0, R0, R3, -R17` | `fma_ftz(dm.x, sumf_d, -mul_ftz(dm.y, sumf_m))` | +| `tmp[i] += ...` (`:599`) | `add.ftz.f32 %r246, %r90, 0f00000000`, then `add.ftz.f32 %r246, %r246, %r157` | `FADD.FTZ R20, RZ, R0` | `tmp = add_ftz(tmp, v)` | + +The `a·b − c·d` return is fused by `ptxas`, not by the front end: PTX leaves two multiplies and a subtract, and the +SASS rounds the dmin product (`.H1_H1` of the `dm` word, times `sumf_m`) and fuses the d product (`.H0_H0`, times +`sumf_d`) with its negation. The caller's `+=` cannot fuse into an FMA result and stays an add. + +### Q5_K (`q5_q8_dot_impl`, `:180-201`; `q5_q8_dot`, `:203-240`; kernel `:244-283`) + +Q4_K's arithmetic, line for line: `sumf_d` at `:196`, `sumf_m` at `:197` (`fma.rn.ftz.f32` in PTX, `FFMA.FTZ` in +SASS, from 0), the return at `:200` (`mul.ftz.f32` ×2 and `sub.ftz.f32` in PTX; `FMUL.FTZ` of `sumf_m` by the +`.H1_H1` half and `FFMA.FTZ` of `sumf_d` by the `.H0_H0` half with the negated product in SASS), `tmp +=` at `:265` +(`FADD.FTZ`). The integer dot's different nesting (`:194`) changes no bit. Metal: Q4_K's forms. + +### Q6_K (`q6_q8_dot_impl`, `:621-634`; `q6_q8_dot`, `:636-651`; kernel `:654-691`) + +| Site | PTX (13.2) | SASS (13.2) | Metal | +|---|---|---|---| +| `sumf += d8[i] * (DP4A(vi, u[i], 0) * sc)` (`:631`), i = 0, 1 | `fma.rn.ftz.f32 %r73, %r31, %r72, 0f00000000`; `fma.rn.ftz.f32 %r87, %r33, %r86, %r73` | `FFMA.FTZ ..., RZ`; `FFMA.FTZ` | `fma_ftz(d8[i], float(dot * sc), sumf)` | +| `return d * sumf` into `tmp +=` (`:633`, `:673`) | `fma.rn.ftz.f32 %r223, %r35, %r87, 0f00000000`, then `fma.rn.ftz.f32 %r223, %r97, %r145, %r223` | `FFMA.FTZ ..., RZ`; `FFMA.FTZ` | `tmp = fma_ftz(d, sumf, tmp)` | + +### IQ4_XS (`iq4_xs_q8_dot`, `:462-479`; kernel `:482-519`) + +| Site | PTX (13.2) | SASS (13.2) | Metal | +|---|---|---|---| +| `__half2float(w->d) * __low2float(x[iqs / 4].ds)` (`:477`) | `mul.ftz.f32 %r136, %r47, %r48` | `FMUL.FTZ R31, R31, R30` | `mul_ftz(h(d), d8)` | +| `return d * sumi` into `tmp +=` (`:478`, `:501`) | `cvt.rn.f32.s32 %r137, %r135`; `fma.rn.ftz.f32 %r162, %r136, %r137, %r162` | `I2FP.F32.S32 R8, R8`; `FFMA.FTZ R16, R31, R8, R16` | `tmp = fma_ftz(d, float(sumi), tmp)` | + +`sumi *= ls - 32` (`:476`) is an integer multiply. + +### Q4_0 (`small_q8_dot`, `:696-710`; kernel `native_small_mmvq_kernel`, `:767-802`) + +| Site | PTX (13.2) | SASS (13.2) | Metal | +|---|---|---|---| +| `sumi * ds.x - 4 * ds.y` (`:709`) | `mul.ftz.f32 %r45, %r29, 0fC0800000`; `fma.rn.ftz.f32 %r46, %r27, %r44, %r45` | `FMUL.FTZ R, R, -4`; `FFMA.FTZ` | `fma_ftz(float(sumi), d8, mul_ftz(s8, -4.0f))` | +| `d * (...)` into `tmp +=` (`:709`, `:784`) | `fma.rn.ftz.f32 %r132, %r30, %r46, 0f00000000`, then `fma.rn.ftz.f32 %r132, %r64, %r77, %r132` | `FFMA.FTZ ..., RZ`; `FFMA.FTZ` | `tmp = fma_ftz(d, inner, tmp)` | + +The front end fuses the d8 product (`.H0_H0` of `ds`, `%r27`) and subtracts fl(4·s8) (`.H1_H1`, `%r29`), formed as a +multiply by −4, which is exact. + +### Q5_0 (`small_q8_dot`, `:712-735`) + +Q4_0's forms with −8: `mul.ftz.f32 %r, %r, 0fC1000000`, `fma.rn.ftz.f32` at `:734`; `fma.rn.ftz.f32` into `tmp` at +`:784`. Metal: `fma_ftz(float(sumi), d8, mul_ftz(s8, -8.0f))`, then `fma_ftz(d, inner, tmp)`. + +### IQ4_NL (`small_q8_dot`, `:751-763`) + +`mul.ftz.f32` of `__half2float(w->d)` and `__low2float(x->ds)` at `:761` (`FMUL.FTZ`), `fma.rn.ftz.f32` into `tmp` at +`:784` (`FFMA.FTZ`). Metal: `fma_ftz(mul_ftz(h(d), d8), float(sumi), tmp)`. + +### Q8_0 (`native_small_q80_kernel`, `:808-880`; `small_q8_dot`, `:737-749`) + +| Site | PTX (13.2) | SASS (13.2) | Metal | +|---|---|---|---| +| prefetched blocks: `tmp[i] += d0[i][p] * d1 * float(sumi)` (`:852`) | `mul.ftz.f32 %r45, %r38, %r184`; `cvt.rn.f32.s32 %r46, %r42`; `fma.rn.ftz.f32 %r196, %r45, %r46, 0f00000000` | `FMUL.FTZ R23, R20, R23`; `FFMA.FTZ R0, R23, R24, R0` | `fma_ftz(mul_ftz(d0, d1), float(sumi), tmp)` | +| later blocks: `return d0 * d1 * float(sumi)` into `tmp +=` (`:748`, `:862`) | `mul.ftz.f32 %r87, %r78, %r79`; `fma.rn.ftz.f32` | `FMUL.FTZ R29, R28, R29`; `FFMA.FTZ R0, R29, R21, R0` | the same | + +The first `NPRE = 3` iterations load their weights before `pdl_wait` (`:816-836`); that is scheduling, and both paths +compute the same expression. The port has no programmatic dependent launch (ICB barriers order dispatches) and runs +every iteration through the second form. + +## 6. The multi-column kernel (`native_mmvq_multi_kernel`, `native_mmvq.cu:1106-1150`) + +Two to eight columns go through one template, `native_mmvq_multi_kernel`, whose format traits +split each one-column dot into `load` (the weight block: codes, unpacked scales, the fp16 block scale) and `apply` +(the activation loads and the dot's float expression), and accumulate `tmp[j][i] += F::apply(...)` per column +(`:1117-1130`). The units for this section (NVCC 13.0 and 13.3, the flags of Method, one unit per type and +instantiation) emit, per type: `` and `` (two columns, the exact layout, regular and +small-K), ``, `` (eight columns) and `` (the upstream layout at eight columns, +`:1157-1160`, which only `mmvq_multi_parity`'s negative control runs). NVCC 13.2's multi-column responses were not +used: an earlier run set them aside without recording why, and two versions satisfy the version check. + +**Result: per (column, row) the multi-column kernel computes the one-column kernel's sequence, in both versions, for +every type and instantiation.** For each instantiation, the tracer's set of dot templates (those with no +shared-memory or shuffle leaves) equals the one-column kernel's. Q4_0 and Q5_0 are the one exception, treated below. +Two differences are only how the tracer reads the code: + +- some instantiations show the first iteration's add of +0 as the zero register; +- in Q8_0's one-column kernel, the prefetched scales cross a label (`pdl_wait`) and appear as `in`. + +No float add, multiply or FMA in any instantiation lacks `.FTZ`. The raw lines at each site, from ``, +column 0: + +| Type | SASS 13.0 | SASS 13.3 | Sequence | +|---|---|---|---| +| Q2_0 | `FMUL.FTZ R0, R10.reuse, R3`; `FFMA.FTZ R0, R27, R31, R0` | `FMUL.FTZ R0, R10.reuse, R27`; `FFMA.FTZ R0, R35, R36, R0` | tmp = fma(fl(d2·d8), f(sumi), tmp) | +| Q3_K | `FFMA.FTZ R0, R0, R41, RZ`; `FFMA.FTZ R0, R39, R40, R0`; `FFMA.FTZ R15, R43, R36, R0`; `FFMA.FTZ R14, R18, R14, R15`; `FFMA.FTZ R34, R19.reuse, R14, R34` | `FFMA.FTZ R49, R49, R48, RZ`; `FFMA.FTZ R43, R50, R43, R49`; `FFMA.FTZ R14, R14, R47, R43`; `FFMA.FTZ R14, R17, R38, R14`; `FFMA.FTZ R15, R16.reuse, R14, R15` | sumf = fma(d8_i, f(dot_i·sc_i), sumf) from 0, i = 0..3; tmp = fma(d3, sumf, tmp) | +| Q4_K | `FFMA.FTZ R30, R0.reuse, R31, RZ`; `FFMA.FTZ R16, R41.reuse, R18, R16`; `FMUL.FTZ R16, R16, R3`; `FFMA.FTZ R17, R17, R2, -R16`; `FADD.FTZ R28, R28, R17` | `FFMA.FTZ R19, R45.reuse, R36, RZ`; `FFMA.FTZ R23, R20, R23, R45`; `FMUL.FTZ R20, R23, R18`; `FFMA.FTZ R19, R19, R16, -R20`; `FADD.FTZ R32, R32, R19` | sumf_d, sumf_m as one column; v = fma(dm.x, sumf_d, −fl(dm.y·sumf_m)); tmp = tmp + v | +| Q5_K | `FFMA.FTZ R44, R39, R44, RZ`; `FFMA.FTZ R32, R15, R32, R44`; `FMUL.FTZ R15, R32, R13`; `FFMA.FTZ R15, R36, R5, -R15`; `FADD.FTZ R12, R12, R15` | `FFMA.FTZ R40, R0.reuse, R39, RZ`; `FFMA.FTZ R25, R43, R35, R40`; `FMUL.FTZ R38, R38, R3`; `FFMA.FTZ R25, R25, R2, -R38`; `FADD.FTZ R34, R34, R25` | Q4_K's | +| Q6_K | `FFMA.FTZ R24, R24, R31, RZ`; `FFMA.FTZ R24, R25, R29, R24`; `FFMA.FTZ R12, R13.reuse, R24, R12` | `FFMA.FTZ R16, R0, R17, RZ`; `FFMA.FTZ R16, R19, R21, R16`; `FFMA.FTZ R35, R0.reuse, R16, R35` | sumf = fma(d8_i, f(dot_i·sc_i), sumf) from 0, i = 0, 1; tmp = fma(d, sumf, tmp) | +| IQ4_XS | `FMUL.FTZ R39, R38.reuse, R39`; `FFMA.FTZ R22, R39, R24, R22` | `FMUL.FTZ R38, R37, R38`; `FFMA.FTZ R21, R38, R40, R21` | tmp = fma(fl(h(d)·d8), f(sumi), tmp) | +| IQ4_NL | `FMUL.FTZ R31, R30.reuse, R31`; `FFMA.FTZ R18, R31, R32, R18` | the same lines | tmp = fma(fl(h(d)·d8), f(sumi), tmp) | +| Q4_0 | `FMUL.FTZ R12, R12, 4`; `FFMA.FTZ R12, R31, R28, -R12`; `FFMA.FTZ R18, R35.reuse, R12, R18` | the same lines | inner = fma(d8, f(sumi), −fl(4·s8)); tmp = fma(d, inner, tmp) | +| Q5_0 | `FMUL.FTZ R17, R13, 8`; `FFMA.FTZ R15, R30, R15, -R17`; `FFMA.FTZ R18, R13.reuse, R15, R18` | the same lines | inner = fma(d8, f(sumi), −fl(8·s8)); tmp = fma(d, inner, tmp) | +| Q8_0 | `FMUL.FTZ R2, R0.reuse, R17`; `FFMA.FTZ R0, R27, R29, R0` | the same lines | tmp = fma(fl(d0·d1), f(sumi), tmp) | + +The operands' origins, traced back to their `HADD2.F32` conversions: in Q4_K the rounded product takes the `.H1_H1` +half of the `dm` word (dmin) and the fused one the `.H0_H0` half (d): `HADD2.F32 R3, -RZ, R2.reuse.H1_H1` and +`HADD2.F32 R2, -RZ, R2.H0_H0` (13.0; Q5_K and 13.3 likewise), as in the one-column kernel. In Q4_0 and Q5_0 the +multiply by 4 or 8 takes the q8_1 sum s8 (`HADD2.F32 R12, -RZ, R31.H1_H1`), the FFMA multiplies d8 +(`R31.H0_H0`) by the converted sumi (`I2FP.F32.S32 R28, R28`), and the outer FFMA takes the weight's d. + +**Q4_0 and Q5_0: the same bits, the negation placed differently.** For the same `small_q8_dot` source (`:709`, +`:734`), the one-column kernel's front end forms `mul.ftz.f32` by −4 (`0fC0800000`) and fuses the d8 product into +`fma.rn.ftz.f32` (section 5). In the multi-column kernel it emits `mul.ftz.f32 %f19, %f13, %f18`; `mul.ftz.f32 %f20, +%f14, 0f40800000`; `sub.ftz.f32 %f21, %f19, %f20`; `fma.rn.ftz.f32 %f59, %f15, %f21, %f59` (13.0; 13.3 the same with +`%r` registers). Then `ptxas` fuses the d8 product with the subtraction, giving the SASS above. So one kernel adds +fl(−4·s8) and the other subtracts fl(4·s8). These are the same value: rounding to nearest even is symmetric in sign, +and s8 is an fp16 value, so 4·s8 and 8·s8 are exact normal fp32 numbers. In both kernels the d8 product is the fused +one. The port's `fma_ftz(float(sumi), d8, mul_ftz(s8, -k))` gives either kernel's bits. + +**The reduction.** Per (column, row), warps 1..NW − 1 store their partials, warp 0 adds them in warp order, then +`warp_sum` (`:1131-1148`): `FADD.FTZ` and `SHFL.BFLY` only. The compiler interleaves the independent butterflies of +the NCOLS · ROWS values, so a function's `SHFL.BFLY` offsets read, for example, 16 16 8 8 4 4 2 2 1 1 at two +values. Each value still takes offsets 16, 8, 4, 2 and 1 in that order: the tracer's chains are +`FADD.FTZ(FADD.FTZ(FADD.FTZ(in, shm), shm), shm)` followed by five `shfl` adds. The counts match NCOLS · ROWS · +(NW − 1 + 5) adds and NCOLS · ROWS · 5 shuffles (Q4_K and Q5_K add one `FADD.FTZ` per column for `tmp +=`): + +| Instantiation | `FADD.FTZ` (Q3_K, Q8_0 / Q4_K) | `SHFL.BFLY` | +|---|---|---| +| `` | 16 / 18 | 10 | +| `` | 64 / 72 | 40 | +| `` | 128 / 144 | 80 | +| `` (upstream) | 96 / 112 | 80 | + +The same counts hold in 13.0 and 13.3. At eight columns the tracer prints extra templates of the form +`FADD.FTZ(in, shfl)`. They are prefixes of the same chains: the per-column store branches end a basic block, and +the tracer stops tracing at a label. + +**The upstream layout.** It has the same per-block arithmetic (its dot templates equal the one-column kernel's) but +runs two warps at five to eight columns. Each thread therefore accumulates twice as many blocks (BPI halves), and +warp 0 adds one partial instead of three. The partial sums are grouped differently, which is the difference the +negative control must see. + +**Metal.** `kernels/common/basalt_mmvq.metal` is one source for both kernels. Its `wload` / `apply_acc` are the +traits' `load` / `apply` with section 5's float forms, and the macros `NCOLS`, `ROWS` and `NW` select the +instantiation, so the per-column sequence is the same code. `tests/kernels/test_basalt_mmvq.py` checks every column of +a T-column call bitwise against the one-column launch, for T = 1..8 and every type. diff --git a/docs/research/basalt-nvcc/nan.md b/docs/research/basalt-nvcc/nan.md new file mode 100644 index 00000000..e94ccb18 --- /dev/null +++ b/docs/research/basalt-nvcc/nan.md @@ -0,0 +1,150 @@ +# NaN bit patterns: what sm_120 stores and what this GPU stores + +Which bits a NaN carries in every float, fp16 and packed word the merged basalt port kernels store: whether a NaN can +reach the store, which bits basalt's sm_120 code stores there, and which bits this GPU's operations give. Where the +two differ, the Metal kernel rewrites a NaN to sm_120's encoding at the store (`cuda_nan`, `cuda_nan_f16` in +`kernels/common/basalt_fp.metal`), so its outputs equal basalt's bit for bit for non-finite values too. This page +extends the per-site pages of `docs/research/basalt-nvcc/` (`docs/design/flash-next.md`, invariant 5) and uses their +records of each store's last instruction. + +Basalt paths are relative to commit `b4c63b55754637f4c72ad53a0f791d425f71eb36`; `path:a-b` means lines a to b there, +and a bare `:N` is a line of the file named last. Evidence tags on this page: [M] measured by us, [S] a +vendor specification (here NVIDIA's PTX ISA; `CLAUDE.md` keeps [S] for Apple's), [H] inferred. + +## Method + +- **NVIDIA hardware.** Compiler Explorer's public API runs CUDA programs on one GPU, a Tesla T4 (sm_75); no sm_120 + GPU is available to us. The probe is a single-thread kernel with one `__noinline__` device function per PTX + instruction, written as inline `asm volatile` (`add.rn.f32`, `add.rn.ftz.f32`, `mul.rn.f32`, `fma.rn.f32`, + `div.rn.f32`, `div.approx.ftz.f32`, `rcp.approx.ftz.f32`, `ex2.approx.f32`, `max.f32`, `abs.f32`, `neg.f32`, + `cvt.rn.f16.f32`, `cvt.f32.f16`, `cvt.rzi.s32.f32`, ...), plus `__float2half`, `__floats2half2_rn`, + `make_half2(__float2half(a), __float2half(b))` (basalt's `q8_1_ds`) and `roundf`. Its inputs come from device + memory so nothing folds: made NaNs (inf − inf, inf · 0, fma(inf, 0, 1), 0 / 0) and passed ones (0x7fc00000, the + signaling 0x7fa5a5a5, 0x7fd2d2d2, the negative 0xffc00001, 0x7fffffff, 0xffffffff, 0x7f800001; the fp16 NaNs 0x7e00, + 0x7d55, 0xfe01, 0x7fff). Built with NVCC 13.3.0 (`nvcc133`, `-O3`, code for sm_75 and sm_120) and run there; the + same source built for sm_120 alone with basalt's flags (`--generate-code=arch=compute_120,code=[compute_120,sm_120]`) + gives the SASS each instruction becomes on basalt's target. A host program prints NVIDIA's own NaN constants and the + host-side fp16 conversion. +- **This GPU.** The same operations in MSL, `MTLMathModeSafe` (the repository default), on the M3 Max (Apple family + 9, macOS 27.0.1), with `basalt_fp.metal`'s helpers. +- **The stores.** Each store's value is traced back through basalt's source to the instruction that wrote it, as the + per-site pages record it (`matvec.md`, `dequant.md`, `experts.md`, `bf16.md`, `dense_tc.md`, `q5k_head.md`, + `s2_experts.md`), and the inputs that can make a NaN reach it are worked out from the same arithmetic. + +## What each operation gives a NaN + +The PTX ISA (9.4, section 9.7.3, Floating-Point Instructions) leaves the single-precision NaN unspecified [S]: +"Single-precision instructions return an unspecified NaN. Note that future implementations may support NaN payloads for +single-precision instructions, so PTX programs should not rely on the specific single-precision NaNs being +generated." Its float-to-integer rule is specified [S] (section 9.7.10.24, `cvt`): "In float-to-integer conversions, +depending upon conversion types, NaN input results in following value: Zero if source is not .f64 and destination is +not .s64, .u64." The only encoding it names is the double-precision approximations' "canonical NaN with encoding +0x7fffffff00000000" (`rcp.approx.ftz.f64`, `rsqrt.approx.ftz.f64`). + +| Operation (PTX → sm_120 SASS) | NaN in or made | sm_75 [M] | sm_120 | This GPU [M] | +|---|---|---|---|---| +| `add.f32`, `sub.f32`, `add.ftz.f32`, `add.rz.ftz.f32` → `FADD`, `FADD.FTZ`, `FADD.FTZ.RZ` | inf − inf; any NaN operand, every payload and sign above | 0x7fffffff | 0x7fffffff [H] | `+`, `add_ftz`: 0x7fc00000 | +| `mul.f32`, `mul.ftz.f32` → `FMUL`, `FMUL.FTZ` | inf · 0; a NaN operand | 0x7fffffff | 0x7fffffff [H] | `*`, `mul_ftz`: 0x7fc00000 | +| `fma.rn.f32`, `fma.rn.ftz.f32` → `FFMA`, `FFMA.FTZ` | fma(inf, 0, 1); a NaN operand | 0x7fffffff | 0x7fffffff [H] | `fma`, `fma_ftz`: 0x7fc00000 | +| `div.rn.f32` → `MUFU.RCP`, `FCHK`, `FFMA` ×5, slow path | 0 / 0; a NaN operand | 0x7fffffff | 0x7fffffff [H] | `/`: 0x7fc00000 | +| `div.approx.ftz.f32`, `div.full.ftz.f32` → `MUFU.RCP`, `FMUL.FTZ` | 0 / 0; a NaN operand | 0x7fffffff | 0x7fffffff [H] | `mul_ftz(a, rcp_ftz(b))`: 0x7fc00000 | +| `rcp.approx.ftz.f32` → `MUFU.RCP`; `rcp.rn.f32` → `MUFU.RCP`, `FFMA` | a NaN | 0x7fffffff | 0x7fffffff [H] | `1.0f / x`, `rcp_ftz`: 0x7fc00000 | +| `ex2.approx.ftz.f32` → `MUFU.EX2`; `ex2.approx.f32` → `MUFU.EX2` with the halving guard | a NaN | 0x7fffffff | 0x7fffffff [H] | `fast::exp2`, `expf_ftz`, `expf_neg`, `precise::exp`: 0x7fc00000 | +| `max.f32`, `max.ftz.f32` → `FMNMX`, `FMNMX.FTZ` | one NaN operand | the other operand | the other operand [H] | `fmax`, `max_ftz`: the other operand | +| `max.f32`, `max.ftz.f32`, `min.f32` → `FMNMX`, `FMNMX.FTZ` | two NaNs | 0x7fffffff | 0x7fffffff [H] | one operand's bits (0x7fd2d2d2 or 0xffc00001 here) | +| `abs.f32`, `neg.f32` → `FADD \|x\|, -RZ`, `FADD -x, -RZ` | a NaN | 0x7fffffff | 0x7fffffff [H] | `fabs`, `-x`, `ftz`: the payload kept (`fabs` clears the sign, `-` flips it) | +| `roundf` → `FADD.RZ`, `FRND.TRUNC`; `cvt.rzi.f32.f32` → `FRND.TRUNC` | a NaN | 0x7fffffff | 0x7fffffff [H] | `round`: the payload kept; `floor`, `trunc`: 0x7fc00000 | +| `cvt.rn.f16.f32` → `F2F.F16.F32` (sm_75; sm_120 for a lone conversion) | any NaN, either sign | 0x7fff | 0x7fff [H] | `half(x)`, `f16_bits`: 0x7e00 | +| two `cvt.rn.f16.f32` packed → `F2FP.F16.F32.PACK_AB` (sm_120; sm_75 emits `F2F` ×2 and `PRMT`) | any NaN | (not on sm_75) | 0x7fff [H] | as above | +| `cvt.f32.f16` → `HADD2.F32 -RZ, x.H0_H0` | an fp16 NaN | 0x7fffffff | 0x7fffffff [H] | `h2f`: 0x7fc00000 | +| `cvt.rzi.s32.f32`, `cvt.rzi.ftz.s32.f32`, `cvt.rmi.ftz.s32.f32` → `F2I.TRUNC.NTZ`, `F2I.FTZ.TRUNC.NTZ`, `F2I.FTZ.FLOOR.NTZ` | a NaN | 0 | 0 [S] | `int(x)`: 0 (MSL section 8.6) | +| `q8_1_finite` (`q8_1_finite.hpp:18-20`) → `FSETP.GT.FTZ \|v\|, 65504`, `LOP3.LUT`, `FSEL` | a NaN | | the NaN unchanged (the compare is false) | the same expression: the NaN unchanged | +| `selp`, moves, shuffles, `__int_as_float` → `FSEL`, `MOV`, `SHFL` | a NaN | | the bits unchanged | the bits unchanged | + +NVIDIA's constants and host conversion (CUDA 13.3) [M]: `CUDART_NAN_F` is `__int_as_float(0x7fffffffU)` (stored as +0x7fffffff), `CUDART_NAN_FP16` is 0x7fff, and the host `__float2half` and `__floats2half2_rn` (`cuda_fp16.hpp`'s +software conversion) give 0x7fff for each of the NaNs above, the negative one included. + +**sm_120's encoding.** The sm_75 measurements give NVIDIA's canonical NaN for every arithmetic instruction class +basalt's stores end in, whatever NaN came in: 0x7fffffff in fp32 and 0x7fff in fp16, with the sign dropped. The sm_120 +SASS uses the same instruction classes (`FADD`, `FMUL`, `FFMA`, `MUFU.RCP`, `MUFU.EX2`, `FMNMX`, `F2F`, `HADD2.F32`, +`F2I`); NVIDIA's NaN constants and its host emulation of the fp16 conversion carry the same encodings. This page takes +them as sm_120's, as PR #18 did for its kernels (`s2_experts.md`, Summary); they are not measured on an sm_120 GPU, +and the PTX ISA does not promise them. + +**The fp16 conversion on sm_120.** basalt's q8_1 scale and sum go through `F2FP.F16.F32.PACK_AB` on sm_120 +(`matvec.md` sections 1 and 3), which sm_75 does not emit, so no run measured it. The NaN that reaches it is always +the canonical 0x7fffffff: d and the sum are results of `FADD`, `FMUL`, `FMNMX` of two NaNs or the `div.rn.f32` +sequence, and `q8_1_finite`'s select passes them unchanged. 0x7fffffff converts to 0x7fff both under the rule `F2F` +follows on sm_75 (every NaN to 0x7fff) and under a conversion that keeps the leading payload bits (sign 0, exponent +all ones, the ten leading mantissa bits all ones), so the stored half is 0x7fff unless `F2FP` produced a third +encoding, which no NVIDIA conversion measured here or documented does. + +**This GPU's encoding.** Its add, multiply, fma, division, `fast::exp2`, `precise::exp`, `floor` and `trunc` give +0x7fc00000 for a made or a passed NaN; `fabs`, negation, `round` and `ftz` keep a NaN's payload; `fmax` and `fmin` +return one operand of two NaNs; the conversion to half gives 0x7e00 for every NaN; the conversion back gives +0x7fc00000. A port kernel's stored NaN therefore differs from sm_120's wherever it is not rewritten. + +## The stores + +"NaN reaches it" names inputs that make a NaN arrive at the store in basalt's arithmetic (and so in the port's). An +infinity alone never reaches a q8_1 half: `q8_1_finite` clamps it to ±65504 (`q8_1_finite.hpp:1-9`). A NaN in a +weight scale comes only from a damaged file, in an activation only from upstream; the kernels store it either way. +Each row's sm_120 cell names the row of the operation table above it rests on (the store's last instruction, [M] on +sm_75 and [H] for sm_120, whose PTX ISA leaves the single-precision NaN unspecified, section 9.7.3; an integer result +rests on the `cvt` rule, section 9.7.10.24 [S]). The SASS lines are the per-site pages' (13.3 unless marked); +where a page records only an instruction pair and a count, the row says so. + +| Metal kernel: store | basalt | Last instruction on sm_120 | NaN reaches it | sm_120 | This GPU, unrewritten | Port | +|---|---|---|---|---|---|---| +| `native_quantize_q8_1`, `native_swiglu_quantize_q8_1`: codes | `native_mmvq.cu:157`, `:175` | `F2I.FTZ.TRUNC.NTZ` (`matvec.md` section 1) | never: a NaN quotient converts to 0 | 0 [S] (`cvt` rule) | 0 (`q8_1_code`) | no change | +| the same: fp16 d and sum | `native_mmvq.cu:158`, `:176`; `q8_1_finite.hpp:29-31` | `F2FP.F16.F32.PACK_AB R13, R13, R0` of `FMUL.FTZ` (d) and `FADD.FTZ` (sum) through `FSEL` (section 1) | sum: a NaN lane, or +inf and −inf in one block (`FADD.FTZ` butterfly); d: every lane NaN (`FMNMX.FTZ` of NaNs, then `FMUL.FTZ`); the SwiGLU's value is NaN for a NaN gate, a −inf gate (`__fdividef(−inf, inf)` is −inf · `MUFU.RCP`(inf) = −inf · 0), a NaN up, or inf · 0 in the `__fmul_rn` product (`native_mmvq.cu:170`) | 0x7fff [H] (`F2FP` row; the NaN in is `FMUL.FTZ`'s or `FADD.FTZ`'s 0x7fffffff) | 0x7e00 | `cuda_nan_f16` in `q8_1_put` | +| `quantize_q8_1`: codes | `iq_kernels.cu:1892` | `F2I.TRUNC.NTZ` (section 3) | never | 0 [S] (`cvt` rule) | 0 | no change | +| `quantize_q8_1`: fp16 d and sum | `iq_kernels.cu:1893` | `F2FP.F16.F32.PACK_AB` of the `div.rn.f32` sequence (d) and `FADD` (sum) (section 3 records no registers) | as above; d = NaN / 127 for an all-NaN block | 0x7fff [H] (`F2FP` row; the NaN in is `div.rn.f32`'s or `FADD`'s 0x7fffffff) | 0x7e00 | `cuda_nan_f16` in `q8_1_put` | +| `basalt_mmvq`: y, one and several columns | `native_mmvq.cu:281`, `:347`, `:435`, `:517`, `:615`, `:689`, `:800`, `:878`, `:1148` | `SHFL.BFLY` + `FADD.FTZ` ×5, the last add stored (`matvec.md` sections 4, 6 record the pair, no register line) | a weight's fp16 d or dmin inf against a zero integer dot or a zero d8, or NaN; a NaN d8, or a NaN s8 in Q4_0 and Q5_0 | 0x7fffffff [H] (`FADD` row) | 0x7fc00000 | `cuda_nan` | +| `basalt_dequant_f32`: y | `iq_kernels.cu:2020-2021`, `:2043`, `:2054-2055`, `:2067` | `FMUL R9, R0.reuse, R5` (Q2_0), `FMUL R7, R6.reuse, R7` (IQ4_NL), `FMUL R21, R22.reuse, R21` (Q3_K), `FMUL R9, R6.reuse, R9` (IQ4_XS), 13.0 (`dequant.md`) | the block's d NaN, or inf times a zero factor: Q2_0's code 1, Q3_K's code 0 or scale 32, IQ4_XS's scale 32 (IQ4_NL's codebook has no 0) | 0x7fffffff [H] (`FMUL` row) | 0x7fc00000 | `cuda_nan` | +| `basalt_expert_gu`: gate and up, `GU2` 1 | `gu2.cuh:296-297` | `SHFL.BFLY` + `FADD` ×5, `warp_sum`'s last add stored (`experts.md` section 1 records the pair, no register line) | a gate or up row's d2 inf against a zero sumi or d8, or NaN; a NaN d8 | 0x7fffffff [H] (`FADD` row) | 0x7fc00000 | `cuda_nan` | +| `basalt_expert_gu`: gate and up, `GU2` 0 | `iq_kernels.cu:1153`, `:1158`, `:1167` | `SHFL.BFLY` + `FADD` ×5 (section 1) | as above | 0x7fffffff [H] (`FADD` row) | 0x7fc00000 | `cuda_nan` | +| `basalt_expert_swiglu_q8_1`: codes, fp16 d and sum | `gu2.cuh:388`; `iq_kernels.cu:1892-1893` | as `quantize_q8_1` (`experts.md` section 2) | a NaN gate or up (a NaN row), a gate of −inf (`div.rn.f32` of −inf by inf), inf · 0 in the product | codes 0 [S]; halves 0x7fff [H] (`F2FP` row) | codes 0; halves 0x7e00 | `cuda_nan_f16` in `q8_1_put` | +| `basalt_expert_down`: out, `SUB16` 1 | `iq_kernels.cu:1803`, `:1808`, `:1817` | `FADD R35, R16, R17` (s + s16), then `SHFL.BFLY` + `FADD` ×4, the last add stored (`experts.md` section 3) | a down row's d2 inf or NaN; a NaN q8_1 d of the intermediate | 0x7fffffff [H] (`FADD` row) | 0x7fc00000 | `cuda_nan` | +| `basalt_expert_down`: out, `SUB16` 0 | `iq_kernels.cu:1874` | `SHFL.BFLY` + `FADD` ×5 (section 3) | as above | 0x7fffffff [H] (`FADD` row) | 0x7fc00000 | `cuda_nan` | +| `basalt_mmvf`: y | `native_bf16.cu:72`, `:121` | the block sum's `FADD.FTZ` ×5 ending `FADD.FTZ R7, R4, R7`, then `STG.E desc[UR8][R2.64], R7` (13.2; `bf16.md` section 1 and its 13.3 note); the multi kernel's `STG.E` per token (section 2) | a NaN weight or activation; inf · 0; inf − inf | 0x7fffffff [H] (`FADD` row) | 0x7fc00000 | `cuda_nan` | +| `basalt_dense_tc`: y; `basalt_dense_tc_pair`: y0, y1 | `dense_tc.cu:425`, `:559`, `:680`, `:926` | the tree's last add, 13.0 (`dense_tc.md` section 2): `FADD R23, R23, R8` (one), `FADD R19, R12, R19` (tile), `FADD R13, R13, R18` (s, KS 1), `FADD R13, R13, R10` (s, KS 2), `FADD R41, R32, R41` (pair) | a weight's fp16 scale inf against a zero term, or NaN; a NaN d8 | 0x7fffffff [H] (`FADD` row) | 0x7fc00000 | `cuda_nan` | +| `basalt_q5k_head`: y | `q5k_head.cu:139`, `:218` | `SHFL.BFLY` + `FADD.FTZ` with offsets 16..1 (`q5k_head.md` section 1 records the pair, no register line) | as `basalt_mmvq`'s Q5_K | 0x7fffffff [H] (`FADD` row) | 0x7fc00000 | `cuda_nan` | +| `basalt_q5k_head_mask_unmapped`: y | `q5k_head.cu:402` | the constant −inf | never | | | no change | +| `basalt_q5k_head_top1`: y | `q5k_head.cu:213-218` | the head's `FADD.FTZ` butterfly, or the constant −inf of a masked row | as the head | 0x7fffffff [H] (`FADD` row) | 0x7fc00000 | `cuda_nan` | +| `basalt_q5k_head_top1`: part m | `q5k_head.cu:300` | a logit through `Top::take` and `merge` (`:155-175`): m changes only to l with l > m, or to a nonempty partial's m | never: `l > m` is false for a NaN l | | | no change | +| `basalt_q5k_head_top1`: part idx | `q5k_head.cu:301` | an int's bits (`__int_as_float`; 0x7fffffff is the empty index) | not a float value | | | no change | +| `basalt_q5k_head_top1`: part s | `q5k_head.cu:302` | `@P1 FFMA.FTZ R8, R8, R3, 1` or `@!P1 FADD.FTZ R8, R8, R5` (`take`), `FFMA.FTZ R5, R2, R5, R6` or `FFMA.FTZ R5, R6, R0, R5` (`merge`; `q5k_head.md` section 2) | a NaN logit (`s += __expf(NaN − m)`); a second +inf logit (`inf − inf`) | 0x7fffffff [H] (`FFMA`, `FADD` rows) | 0x7fc00000 | `cuda_nan` | +| `basalt_q5k_head_top1_merge`: out_prob | `q5k_head.cu:332` | `MUFU.RCP R13, R6`, stored as is (`q5k_head.md` section 2) | the merged s NaN | 0x7fffffff [H] (`rcp.approx` row) | 0x7fc00000 | `cuda_nan` | +| `basalt_q5k_proxy_pack`: fp16 scale | `head_proxy.cuh:86` | `F2FP.F16.F32.PACK_AB R0, RZ, R40` (`q5k_head.md` section 4.1) | never: amax starts at 1e-9 and `FMNMX.FTZ` drops a NaN weight (`:44-45`), so amax and s = amax · fl(1/1.5) · fl(1 − 0.1t) (a positive factor) are finite or +inf | | | no change | +| `basalt_q5k_proxy_pack`: levels | `head_proxy.cuh:76-85` | `F2I.FTZ.FLOOR.NTZ R9, R9`, integer clamp (`q5k_head.md` section 4.1) | never: a NaN level converts to 0 | 0 [S] (`cvt` rule) | 0 (`px_level`) | no change | +| `basalt_q5k_proxy_score`: part m | `head_proxy.cuh:154` | `FMNMX.FTZ R10, R7, R10, !PT`, offsets 16..1 (`q5k_head.md` section 4.2) | every lane's score NaN | 0x7fffffff [H] (`FMNMX` two-NaN row) | an operand's 0x7fc00000 | `cuda_nan` | +| `basalt_q5k_proxy_score`: part e | `head_proxy.cuh:154` | `FADD.FTZ R16, R7, R16`, offsets 16..1 (section 4.2) | a +inf score (`__expf(inf − inf)`) | 0x7fffffff [H] (`FADD` row) | 0x7fc00000 | `cuda_nan` | +| `basalt_q5k_proxy_score`: cand score | `head_proxy.cuh:164` | a score's bits through `SHFL` and `FSEL` (`FSETP.GEU.FTZ` / `FSETP.NEU.FTZ`, section 4.2): `FADD.FTZ R4, R4, R7` (`:146`) or the constant −inf (`:147`) | a NaN score: no compare selects a NaN over a number, and lane 0 keeps its own NaN | 0x7fffffff [H] (`FADD` row; `FSEL` keeps the bits) | 0x7fc00000 | `cuda_nan` | +| `basalt_q5k_proxy_score`: cand row | `head_proxy.cuh:164` | an int's bits | not a float value | | | no change | +| `basalt_q5k_proxy_final`: out_prob | `head_proxy.cuh:194`, `:236-238` | the constant 1, or `MUFU.RCP` of `FMNMX.FTZ(sum, one)`, one 0 or 1 (section 4.3) | never: `FMNMX` drops a NaN sum | | | no change | +| `basalt_s2_gu`, `basalt_s2_swiglu`, `basalt_s2_down`: gate/up, out | `s2_expert_grouped.cu:963-964`, `:170`, `:1022-1023` | `FADD`, `FMUL` (`s2_experts.md`) | `s2_experts.md`, Summary | 0x7fffffff [H] (`FADD`, `FMUL` rows) | 0x7fc00000 | `cuda_nan` (PR #18) | +| `basalt_quantize_q8_0_scaled`: fp32 scale, fp16 d, codes | `quantize_act.cu:91-100` | `div.rn.f32` under `amax > 0`; `f16_from_f32` (integer); `F2I.TRUNC.NTZ` | scale and d: never, s is 0 for an all-NaN block (`s2_experts.md` section 1); codes: a NaN x, which converts to 0 | codes 0 [S] (`cvt` rule) | codes 0 (`q8_1_code`) | no change | + +The integer outputs (token ids, the head's and the proxy's `out_id`, the experts' plans) carry no float encoding. + +**A forward note on `f16_from_f32`.** basalt's software fp16 conversion (`include/basalt/kernels/f16_bits.hpp:36-65`) +maps a NaN to `sign | 0x7E00`: for the positive canonical NaN sm_120's arithmetic makes, 0x7E00, the bits this GPU's +`half()` gives and not the hardware conversion's 0x7fff; for a negative NaN, 0xFE00, where `half()` drops the sign. `f16_bits` stands for it in the drafter quantizer, where no NaN arrives. A port of the fp16 KV append +(`src/kernels/cuda/qsa.cu:134-135`), which writes K and V through `f16_from_f32`, stores a NaN; that port needs +`sign | 0x7E00` there. + +## Metal + +`basalt_fp.metal` holds the two rewrites, integer operations on the bits: + +- `cuda_nan(x)`: a float NaN (any sign or payload) becomes 0x7fffffff; every other value keeps its bits. It moves + here from `basalt_q8_1.metal`, where PR #18 introduced it. +- `cuda_nan_f16(h)`: an fp16 NaN becomes 0x7fff; every other half keeps its bits. It stands for the hardware + conversion (`__float2half`, `F2F` and `F2FP`) after `f16_bits`, and is applied in `q8_1_put`, the store every q8_1 + quantizer shares; `f16_bits` itself stays the conversion `f16_from_f32` needs for finite values. + +Each kernel applies them at the stores the table marks, so a finite value is stored as before. `tests/kernels/ +test_basalt_nan.py` plants inputs that make a NaN reach every rewritten store, requires the stored bits to be +sm_120's, and runs the same kernels without the rewrite as the negative control. diff --git a/docs/research/basalt-nvcc/q5k_head.md b/docs/research/basalt-nvcc/q5k_head.md new file mode 100644 index 00000000..635a13ac --- /dev/null +++ b/docs/research/basalt-nvcc/q5k_head.md @@ -0,0 +1,260 @@ +# basalt's Q5_K head as nvcc compiles it + +What NVIDIA's compiler emits at every rounding site of basalt's Q5_K head (`src/kernels/cuda/q5k_head.cu`) and of the +2-bit proxy it includes (`src/kernels/cuda/head_proxy.cuh`), read from the sm_120 PTX and SASS, and the Metal form the +port writes at each site (`kernels/common/basalt_q5k_head.metal`). `q5k_head.cu` builds with `--use_fast_math` +(`CMakeLists.txt:200`). The format follows `matvec.md`, whose method, notation and helpers this page uses. + +Basalt paths are relative to commit `b4c63b55754637f4c72ad53a0f791d425f71eb36`; `path:a-b` means lines a to b there, +and a bare `:N` is a line of the file named last. + +## Method + +- **Sources.** `q5k_head.cu` verbatim with the quoted includes inlined (`basalt/kernels/q5k_head.hpp`, `dp4a.hpp`, + `pdl.hpp`, `head_proxy.cuh`). Only basalt's public MIT source was sent. +- **Compilers and flags.** Compiler Explorer's public API as in `matvec.md`: NVCC 13.0.0 (`nvcc130`) and 13.3.0 + (`nvcc133`), each with basalt's flags for this file: `-O3 -DNDEBUG -DBASALT_VERSION="0.0.1" + --generate-code=arch=compute_120,code=[compute_120,sm_120] --use_fast_math`, plus `-Xptxas -v` for the register + counts. +- **Translation units.** `q5k_head.cu:1-252` (includes, block structs, `q5_load`, `q5_apply`, `q5k_row_dev`, `Top`, + `q5k_rows_10`, `q5k_head_kernel`), for the top-1 unit also `:253-335` (`q5k_head_top1_kernel`) and `:399-404` + (`mask_unmapped_kernel`), for the proxy units `:436-498` (`q5k_proxy_pack_kernel`, `q5k_proxy_final_kernel`); then a + table that takes the address of each kernel instantiation the unit emits (`q5k_head_kernel<1, 10>`, `<2, 10>`, + `<8, 10>`, `<1, 0>`, `<8, 0>`; `q5k_head_top1_kernel`, `mask_unmapped_kernel`; `q5k_proxy_pack_kernel`; + `q5k_proxy_final_kernel`; `px::score_kernel`, which every unit emits). The host launchers are left out: a kernel's + code depends only on its template and the inlined device functions. Nine units per compiler, all compiled (code 0); + only `q5k_head_kernel<8, 0>`'s SASS listing reached Compiler Explorer's 5,000-line cut (its PTX is complete, and + `<8, 10>` has the same per-(row, column) templates). +- **Reading a site.** As in `matvec.md`: the PTX shows what NVVM fused and each conversion; the SASS what `ptxas` made + of it. The dataflow tracer of `matvec.md` prints each floating-point SASS instruction as an expression template; + the templates below are 13.3's. 13.0 emits the same operations, with the same operands and modifiers, at every + site this page records; its listings differ only in scheduling and predicate choice (sections 4.2 and 4.3). + +## Register and shared-memory use (sm_120, `ptxas -v`, both compilers) + +| Kernel | Registers | Shared memory | Barriers | +|---|---|---|---| +| `q5k_head_kernel<1, 10>`, `<2, 10>` | 128 | dynamic (columns) | 1 | +| `q5k_head_kernel<8, 10>` | 156 | dynamic | 1 | +| `q5k_head_kernel<1, 0>` | 63 | dynamic | 1 | +| `q5k_head_kernel<8, 0>` | 128 | dynamic | 1 | +| `q5k_head_top1_kernel` | 126 | 7,777 B | 1 | +| `mask_unmapped_kernel` | 10 | 0 | 0 | +| `q5k_proxy_pack_kernel` | 56 | 0 | 0 | +| `q5k_proxy_final_kernel` | 40 | 8,516 B (`xe`, 7,680 B, and `px::Final`, 836 B) | 1 | +| `px::score_kernel` | 77 | 3,712 B | 1 | + +The top-1's grid (`q5k_head.cu:375-386`) is the multiprocessor count times `cudaOccupancyMaxActiveBlocksPerMultiprocessor` +for 256 threads, capped at 4,096. On sm_120 (65,536 registers per multiprocessor, allocation in 8-register units per +thread) 126 registers round to 128: 128 × 256 = 32,768 registers a block, two blocks a multiprocessor; the 7,777 bytes of +shared memory and the 1,536-thread limit allow more. Basalt's measured RTX 5090 has 170 multiprocessors +(`docs/research/basalt-nvcc/dense_tc.md` and the scoping report's decision 4), so its grid is 340 blocks for every row +count above 2,720 and ceil(n_out / 8) below. + +## Summary + +| Kernel | Rounding sequence nvcc 13.x emits (sm_120) | Metal | +|---|---|---| +| `q5k_head_mmvq` (`q5_apply`, `q5k_head.cu:92-106`; `q5k_row_dev` / `q5k_rows_10`, `:110-223`) | per (row, column) `native_mmvq`'s Q5_K sequence (`matvec.md` section 5): sumf_d = fma(d8_i, f(dot1_i·sc_i), sumf_d), sumf_m = fma(d8_i, f(dot2_i·m_i), sumf_m) from 0; v = fma(dm.x, sumf_d, −fl(dm.y·sumf_m)); p_v = 0 + v, then + v per further block; t = ((p_0 + p_1) + p_2) + p_3; butterfly 16..1; all `.FTZ` | the same, `fma_ftz`, `mul_ftz`, `add_ftz`, `warp_sum_ftz`: `basalt_mmvq.metal`'s Q5_K dot, shared | +| `Top::take` (`:155-164`) | l > m: s = fma(s, e, 1) with e = `MUFU.EX2`(fl((m − l)·fl(log2 e))); else s = s + `MUFU.EX2`(fl((l − m)·fl(log2 e))); all `.FTZ` | `fma_ftz(s, expf_ftz(m - l), 1)`; `add_ftz(s, expf_ftz(l - m))`; `expf_ftz(x)` = `ftz(fast::exp2(mul_ftz(x, fl(log2 e))))` | +| `Top::merge` (`:165-175`) | o.m > m (or empty): s = fma(s, e(m − o.m), o.s); else s = fma(o.s, e(o.m − m), s) | `fma_ftz` with the same `expf_ftz` | +| top-1 output (`:330-332`) | `1.0f / b.s` as `MUFU.RCP` alone | `rcp_ftz(s)` | +| `mask_unmapped_kernel` (`:400-403`) | a store of −inf, no arithmetic | the same | +| top-1 merge (`:303-334`) | an atomic election of the last block | a second dispatch, the same merge sequence (section 3) | +| `q5k_proxy_pack_kernel` (`:438-462`; `head_proxy.cuh:36-87`) | w = fma(FMUL(d, sc), q, −FMUL(dmin, m)); amax · fl(1/1.5); FFMA(t, −0.1, 1); sh = fp16(s); level = F2I.FLOOR(FFMA(w, MUFU.RCP(sh), 2)) clamped; e = FFMA(r, r, e) with r = FFMA(level − 1.5, sh, −w); all `.FTZ` | the same with `rcp_ftz`; NaN level 0, clamp in float (section 4.1) | +| `px::score_kernel` (`head_proxy.cuh:89-167`) | acc = FFMA(scale, FFMA(d8, P, −FMUL(xs, 1.5)), acc); the four SIMD-groups' sums left to right; max and sum butterflies with `__expf`; four argmax rounds | the same (section 4.2) | +| `q5k_proxy_final_kernel` (`:464-496`; `head_proxy.cuh:169-240`) | threshold FADD(m, −5); a warp-aggregated shared-memory atomic orders the list; rescoring by the head's row; FFMA(p.y, e, sum) per tile, FADD(e_ex, −e_lp) per row, butterfly, FMNMX, `MUFU.RCP` | the same arithmetic, the list in ascending candidate order (section 4.3) | + +The `[H]` of the scoping report (section 7.2: whether the head resolves `dm.x * sumf_d - dm.y * sumf_m` as +`native_mmvq` does) is settled: the head's SASS rounds the dmin product and fuses the d product with its negation, +`FMUL.FTZ` then `FFMA.FTZ ..., -R`, exactly `native_mmvq.cu:200`'s form (`matvec.md` section 5, Q4_K and Q5_K), in both +compilers. + +## 1. `q5k_head_mmvq` + +`q5k_head_kernel<1, 10>` (13.3), one row's five blocks for lane L (`kb = {a, a + 8, a + 2, a + 4, a + 6}`, `vt = {0, 0, +1, 2, 3}`, `q5k_head.cu:183-185`): + +| Site | SASS (13.3) | Template | Metal | +|---|---|---|---| +| `sumf_d += d8 * (dot1 * r.sc[i])` (`:102`), i = 0, 1 | `FFMA.FTZ R28, R31, R28, RZ`; `FFMA.FTZ R116, R35, R33, R28` | `FFMA.FTZ(i, in, FFMA.FTZ(i, in, 0))` | `fma_ftz(d8, float(dot1 * sc), sumf_d)` from 0 | +| `sumf_m += d8 * (dot2 * r.m[i])` (`:103`) | `FFMA.FTZ R30, R31, R30, RZ`; `FFMA.FTZ R118, R35, R34, R30` | the same | `fma_ftz(d8, float(dot2 * m), sumf_m)` | +| `r.dm.x * sumf_d - r.dm.y * sumf_m` (`:105`) | `FMUL.FTZ R45, R118, R113`; `FFMA.FTZ R116, R116, R51, -R45` | `FFMA.FTZ(sumf, in, −FMUL.FTZ(sumf, in))` | `fma_ftz(dmx, sumf_d, -mul_ftz(dmy, sumf_m))` | +| `p[vt[c]][j] += q5_apply(...)` (`:206`) | `FADD.FTZ R3, RZ, R116`; `FADD.FTZ R3, R3, R118` (virtual thread 0's two blocks); `FADD.FTZ R6, RZ, R6` (threads 1..3, one block each) | `FADD.FTZ(0, v)`, `FADD.FTZ(p, v)` | `add_ftz(p, v)` from 0 | +| `t = p[0][j]; t += p[v][j]` (`:209-211`) | `FADD.FTZ R3, R3, R6`; `FADD.FTZ R3, R2, R3`; `FADD.FTZ R3, R4, R3` | `((p0 + p1) + p2) + p3` | `add_ftz` ×3 in virtual-thread order | +| `warp_sum(t)` (`:212`) | `SHFL.BFLY` + `FADD.FTZ` with offsets 16, 8, 4, 2, 1 | `FADD.FTZ(in, shfl)` | `warp_sum_ftz` | + +That is `native_mmvq`'s Q5_K kernel per value: thread L + 32v's `tmp` starts at +0 and adds its blocks in ascending +kbx (`FADD.FTZ R20, RZ, R0` there too), warp 0 adds warps 1..3's partials in warp order, then the same butterfly +(`matvec.md` section 4). Which of the two `dm` halves is rounded alone is read from the conversions: as in +`native_mmvq`, the `FMUL.FTZ` takes the high half (dmin) and the `FFMA.FTZ` the low half (d). + +The column staging (`:229-240`) precomputes per (q8_1 block, position) `{u0, u1, dot2, d8}`: `dot2` is the same +integer `DP4A(0x01010101, u0, DP4A(0x01010101, u1, 0))` as `q5_q8_dot_impl`'s, and `d8` the exact conversion of the +block's fp16 scale (`__low2float`). Staging is not arithmetic. + +## 2. `q5k_head_top1` + +| Site | SASS (13.3) | Template | Metal | +|---|---|---|---| +| `__expf(m - l)` (`:157`) | `FADD.FTZ R0, R56, -R7`; `FMUL.FTZ R0, R0, 1.4426950216293334961`; `MUFU.EX2 R3, R0` | `MUFU.EX2(FMUL.FTZ(fl(log2 e), FADD.FTZ(−l, m)))` | `expf_ftz(m - l)`: `ftz(fast::exp2(mul_ftz(add_ftz(m, -l), 0x3FB8AA3B)))` | +| `s = s * __expf(m - l) + 1.0f` (`:157`) | `@P1 FFMA.FTZ R8, R8, R3, 1` | `FFMA.FTZ(e, s, 1)` | `fma_ftz(s, e, 1.0f)` | +| `s += __expf(l - m)` (`:161`) | `@!P1 FADD.FTZ R2, -R56, R7`; `FMUL.FTZ`; `MUFU.EX2 R5`; `@!P1 FADD.FTZ R8, R8, R5` | `FADD.FTZ(s, MUFU.EX2(...))` | `add_ftz(s, expf_ftz(l - m))` | +| `s = o.s + s * __expf(m - o.m)` (`:168`) | `FADD.FTZ`; `FMUL.FTZ ..., 1.4426950216293334961`; `MUFU.EX2`; `FFMA.FTZ R5, R2, R5, R6` | `FFMA.FTZ(e, s, o.s)` | `fma_ftz(s, expf_ftz(m - o.m), o.s)` | +| `s += o.s * __expf(o.m - m)` (`:172`) | `FFMA.FTZ R5, R6, R0, R5` | `FFMA.FTZ(e, o.s, s)` | `fma_ftz(o.s, expf_ftz(o.m - m), s)` | +| `*out_prob = 1.0f / b.s` (`:332`) | `MUFU.RCP R13, R6`, stored as is | `MUFU.RCP(s)` | `rcp_ftz(s)` | + +The comparisons (`l > m`, `l == m && row < idx`, `o.m > m`, `o.idx < idx`) are exact. The per-block merge of the 8 +warps (`:297-299`, thread 0, warp order), the last block's thread-strided merge over the block partials (`:311-317`), +the butterfly over the struct (`:318-324`, all three fields shuffled with the same offset, then `merge`) and the final +warp-order merge (`:327-329`) are the same `merge` sequence at each step. `__expf` is `ex2.approx.ftz.f32` of +`mul.ftz.f32 x, 0f3FB8AA3B` in PTX: `MUFU.EX2` has no documented Metal counterpart, and the contract +(`docs/design/flash-next.md`, invariant 5) maps it to `fast::exp2` of the same product; the tests take its values from +the GPU's own function. + +## 3. The cross-threadgroup merge + +basalt's top-1 ends in an election (`q5k_head.cu:297-335`): thread 0 of every block stores the block's partial +(m, idx, s) to `part`, calls `__threadfence()` and takes `atomicAdd(count, 1u)`; the block that reads `gridDim.x - 1` +calls `__threadfence()` again, reads every block's partial with `__ldcg` and merges them, and resets the counter. The +elected block must see the partial every other block stored before its fence and its atomic. + +What the Metal Shading Language (version 4.1, `2026-06-04` edition) documents: + +- Coherence of device memory, section 4.8 (pages 122-123): "Memory in the thread address space has thread coherence, + and memory in the threadgroup address space has threadgroup coherence. By default, memory in the device address + space has threadgroup coherence." and "Metal 3.2 and later support the coherent(device) qualifiers for buffers ... + to indicate that the object has device coherence, that is, memory operations are visible across threads on the + device if you properly synchronize them." A plain `device` partials buffer is therefore not even in scope; it would + need `coherent(device)`. +- Ordering of atomics, section 6.16.1 (page 299): "For atomic operations other than atomic_thread_fence, + memory_order_relaxed is the only enumeration value. With memory_order_relaxed, there are no synchronization or + ordering constraints; the operation only requires atomicity." (Page 300 adds that Metal 4.1 accepts other orders on + atomic operations.) +- Fences, section 6.16.1 (page 300): "In Metal 3.2 and later, you can use memory_order_seq_cst on + atomic_thread_fence to indicate that everything that happens before a store operation in one thread becomes a + visible side effect in the thread that performs the load, and establishes a single total modification order of all + tagged atomic operations." Section 6.16.3 (page 302): "an atomic_thread_fence with memory_order_seq_cst ordering prevents + all preceding writes from moving past all subsequent stores within that scope." +- Release-acquire, section 6.16.1.2 (page 300): "The synchronization is established only between the threads + releasing and acquiring the same atomic variable. Other threads can see a different order of memory accesses than + either or both synchronized threads." + +Each guarantee is stated for one store and the one load that reads it. The specification has no release-sequence +rule: nothing says that a read-modify-write that reads the value of another read-modify-write carries the release of +the threads earlier in the counter's modification order. With 340 blocks, the elected block's RMW reads the value +written by the one RMW just before it in that order; that the other 338 blocks' partials are visible to it is not +stated. So the guarantee +basalt relies on is not explicit, and the port runs the merge as a second dispatch: `basalt_q5k_head_top1` writes +each threadgroup's partial (thread 0 after the 8-SIMD-group merge, as `q5k_head.cu:297-302`), and +`basalt_q5k_head_top1_merge`, one threadgroup of 256 threads, applies the last block's sequence unchanged: thread t +merges partials t, t + 256, ... in order (`:309-317`), the XOR butterfly 16..1 over the struct (`:318-324`), thread 0 +the SIMD-groups in order (`:325-329`), then the id and `rcp_ftz(s)` (`:330-332`). The arithmetic and its order are +basalt's; the ordering between the two is the dispatch boundary (a serial compute encoder runs its dispatches in +order; in an indirect command buffer the second command needs the barrier flag, `barrier_before`, which the +program-binding PR sets), and there is no counter to reset between replays of an indirect command buffer. + +The other cross-threadgroup dependencies of these kernels: + +| Kernel | Dependency | Port | +|---|---|---| +| `q5k_head_mmvq`, `mask_unmapped_kernel` | none: each row is one SIMD-group's (one thread's), written once | as basalt | +| `q5k_proxy_pack_kernel` | none: each group is one thread's | as basalt | +| `px::score_kernel` then `q5k_proxy_final_kernel` | the final kernel reads every tile's candidates and partial; basalt launches the two in order with programmatic dependent launch (`q5k_head.cu:525-528`; `pdl_wait` before the reads, `head_proxy.cuh:109`, `q5k_head.cu:474`) | two dispatches in order: the dispatch boundary | +| `q5k_head_top1_kernel` and the score's `pdl_wait` | the column written by the kernel before (the q8_1 quantizer) | the dispatch before | + +Inside a threadgroup every dependency goes through threadgroup memory and `threadgroup_barrier(mem_flags:: +mem_threadgroup)`, as basalt's `__syncthreads()`. + +## 4. The 2-bit proxy + +The copy holds, per tile of 32 rows and per 64 weights, a 16-byte word per row (`lane = row & 31`), and after +`tiles(n_cap) * 40 * 32 * 16` bytes the fp16 scales, two per word (`head_proxy.cuh:17-28, 72-87`); the port keeps the +layout byte for byte, and the score and final kernels take `n_cap` to find the scales and the scratch's partials. + +### 4.1 `q5k_proxy_pack_kernel` (`q5k_head.cu:438-462`) with `fit_group` and `pack_group` + +The PTX divides with `div.approx.ftz.f32` (`w / sh` and `amax / 1.5f`), floors with `cvt.rmi.ftz.f32.f32` and converts +with `cvt.rzi.ftz.s32.f32`; `ptxas` makes the constant division a multiply, the division by `sh` a reciprocal shared by +the 32 weights, fuses that multiply with the `+ 2.0f`, and folds the floor into the conversion. Both compilers' listings +of this kernel give the same template multiset. + +| Site | SASS (13.3) | Template | Metal | +|---|---|---|---| +| `d = dm.x * (float) sci`, `mn = dm.y * (float) mi` (`:454`) | `FMUL.FTZ R9, R49, R9`; `FMUL.FTZ R8, R51, R52` | `FMUL.FTZ(h, i)` | `mul_ftz(h2f(d), float(sc))` | +| `w[l] = d * (float) q - mn` (`:459`) | `FFMA.FTZ R10, R9, R10, -R8` | `FFMA.FTZ(d, i, -mn)` | `fma_ftz(d, float(q), -mn)` | +| `amax = fmaxf(amax, fabsf(w[l]))` from `1e-9f` (`head_proxy.cuh:44-45`) | `FMNMX.FTZ R14, \|R10\|, 9.9999997171806853657e-10, !PT`, then `FMNMX.FTZ R38, \|R7\|, R14, !PT`, ... | `FMNMX.FTZ(\|w\|, amax)` | `max_ftz(amax, abs_ftz(w))` (exact; order-free) | +| `amax / 1.5f` (`:46`, `:48`) | `FMUL.FTZ R9, R9, 0.6666666865348815918` | `FMUL.FTZ(fl(1 / 1.5), amax)` | `mul_ftz(amax, 0x3F2AAAAB)` | +| `1.0f - 0.1f * (float) t` (`:48`) | `UI2FP.F32.U32 UR5, UR4`; `UFFMA.FTZ UR5, UR5, -UR6, 1` (`UR6 = 0x3dcccccd`) | `FFMA.FTZ(t, -0.1f, 1)` | `fma_ftz(float(t), -0.1f, 1.0f)` | +| `s = amax / 1.5f * (...)` (`:48`) | `FMUL.FTZ R41, R9, UR5` | `FMUL.FTZ` | `mul_ftz(a15, f)` | +| `sh = __half2float(__float2half(s))` (`:49`) | `F2FP.F16.F32.PACK_AB R45, RZ, R41`; `HADD2.F32 R45, -RZ, R45.H0_H0` | RNE to fp16, exact back | `float(half(s))` (round to nearest even, fp16 subnormals kept: `test_basalt_platform.py`) | +| `level(w, sh)`: `(int) floorf(w / sh + 2.0f)` clamped to 0..3 (`:36`) | `MUFU.RCP R43, R45`; `FFMA.FTZ R0, R10, R43, 2`; `F2I.FTZ.FLOOR.NTZ R0, R0`; then the integer clamp | `F2I.FLOOR(FFMA.FTZ(w, MUFU.RCP(sh), 2))` | `px_level`: `floor(fma_ftz(w, rcp_ftz(sh), 2))`, NaN to 0, clamped in float | +| `r = ((float) level - 1.5f) * sh - w[l]` (`:52`) | `FADD.FTZ R0, R44, -1.5`; `FFMA.FTZ R0, R45, R0, -R10` | `FFMA.FTZ(FADD.FTZ(-1.5, i), sh, -w)` | `fma_ftz(add_ftz(float(lv), -1.5f), sh, -w)` | +| `e += r * r` from 0 (`:50-53`) | `FFMA.FTZ R0, R0, R0, RZ`, then `FFMA.FTZ R47, R47, R47, R0`, ... in weight order | `FFMA.FTZ(r, r, e)` | `fma_ftz(r, r, e)` from `0.0f` | +| `if (e < best_e)` (`:55`) | `FSETP.GEU.FTZ.AND P0, PT, R49, R42, PT`; `FSEL R42, R49, R42, !P0`; `FSEL R40, R41, R40, !P0` | strict, first best kept | `e < best_e` | +| stored scale and the packed levels (`:57-59`, `head_proxy.cuh:76-86`) | `F2FP.F16.F32.PACK_AB R0, RZ, R40`; `HADD2.F32 R3, -RZ, R0.H0_H0`; `MUFU.RCP R3, R3`; `FFMA.FTZ R9, R10, R3, 2`; `F2I.FTZ.FLOOR.NTZ R9, R9` | as above | `half(best_s)`, `px_level` with `rcp_ftz(float(hs))` | + +`level`'s conversion is where the 2-bit copy can see a NaN: a group whose weights are all zero (both 6-bit scale +fields zero, about one group in 4,096 of random blocks) has `amax = 1e-9`, `s` near `6.7e-10`, `sh = 0` in fp16, +`MUFU.RCP` gives `+inf` and `0 * inf + 2` is NaN. The PTX ISA (`cvt`): "In float-to-integer conversions, depending upon +conversion types, NaN input results in following value: Zero if source is not .f64 and destination is not .s64, .u64." +and "For float-to-integer conversions, the result is clamped to the destination range by default". MSL takes NaN to 0 +as well (section 8.6: "When converting a floating-point type to an integer type, if the floating-point value is NaN, +the resulting integer is 0.") but converts "with no saturation" (section 2.23), so `px_level` tests the NaN and clamps +in float before converting; an `s` past fp16's range (65,520 and up) gives `sh = inf`, a reciprocal of 0 and level 2 +everywhere, through the same code. `test_proxy_pack_emulation_bit_for_bit` plants both. + +### 4.2 `px::score_kernel` (`head_proxy.cuh:89-167`) + +The PTX computes the group term as `mul.ftz.f32` (d8 times P), `mul.ftz.f32` (xs times `0f3FC00000`), `sub.ftz.f32`, +then `fma.rn.ftz.f32` into the accumulator; `ptxas` fuses the first product into the subtraction, keeping the second +rounded, in every one of the 20 groups. 13.0's listing differs from 13.3's only in scheduling: the masked exponential +is a predicated `MUFU.EX2` instead of an `FSEL` after it. + +| Site | SASS (13.3) | Template | Metal | +|---|---|---|---| +| `xs[tid] = d8 * (float) sum` (`:118`) | `FMUL.FTZ R42, R49, R42` | `FMUL.FTZ(h, i)` | `mul_ftz(d8, float(sum))` | +| `P = DP4A(...)` (`:129-138`) | `IDP.4A.S8.S8` chains | exact integer | `dp4a` | +| `acc += sg * (xdd[g] * (float) P - 1.5f * xs[g])` (`:140`) | `FMUL.FTZ R51, R40, 1.5`; `FFMA.FTZ R44, R44, R49, -R51`; `FFMA.FTZ R44, R37, R44, RZ`, then `FFMA.FTZ R37, R37, R45, R44` | `FFMA.FTZ(scale, FFMA.FTZ(xdd, P, -FMUL.FTZ(xs, 1.5)), acc)` | `fma_ftz(scale, fma_ftz(xdd, float(P), -mul_ftz(xs, 1.5f)), acc)` from 0, j = 0..9, h = 0, 1 | +| `red[0] + red[1] + red[2] + red[3]` (`:146`) | `FADD.FTZ R5, R2, R5`; `FADD.FTZ R4, R5, R4`; `FADD.FTZ R4, R4, R7` | left to right | `add_ftz` ×3 | +| `m = fmaxf(m, shfl)` (`:150`) | `FMNMX.FTZ R10, R7, R10, !PT`, offsets 16..1 | `FMNMX.FTZ` | `max_ftz` butterfly | +| `e = v > -inf ? __expf(v - m) : 0` (`:151`) | `FADD.FTZ R11, R7, -R10`; `FMUL.FTZ R11, R11, 1.4426950216293334961`; `MUFU.EX2 R11, R11`; `FSETP.NE.FTZ.AND P4, PT, R7, -INF, PT`; `FSEL R7, R11, RZ, P4` | `MUFU.EX2(FMUL.FTZ(log2 e, FADD.FTZ(v, -m)))` | `expf_ftz(add_ftz(v, -m))` | +| `e += shfl` (`:153`) | `FADD.FTZ R16, R7, R16`, offsets 16..1 | butterfly | `warp_sum_ftz` | +| the kPer argmax rounds (`:155-166`) | `FSETP.GEU.FTZ` / `FSETP.NEU.FTZ` and `FSEL` | exact | `ov > bv \|\| (ov == bv && oi < bi)` | + +### 4.3 `q5k_proxy_final_kernel` (`q5k_head.cu:464-496`) with `collect` and `pick` + +13.0's listing of this kernel has the same operations at every site. It differs from 13.3's in scheduling, in the +predicate registers its `FSEL`s test, and in the tracer's leaf classes where a register was loaded outside the traced +block. + +| Site | SASS (13.3) | Template | Metal | +|---|---|---|---| +| `m = fmaxf(m, cand[i].x)`, butterfly, `wmax` (`head_proxy.cuh:185-191`) | `FMNMX.FTZ` chains | exact, order-free | `max_ftz` | +| `c.x >= m - kDelta` (`:199`) | `FADD.FTZ R11, R18, -5`; `FSETP.GE.FTZ.AND P1, PT, R8, R11, PT` | `FADD.FTZ(m, -5)` | `add_ftz(m, -5.0f)` | +| `atomicAdd(&f.cnt, 1)` (`:200`) | `VOTEU.ANY UR8, UPT, PT`; `FLO.U32 R13, UR8`; `POPC R12, UR8`; `POPC R15, R14` (the mask and `SR_LTMASK`); `@P0 ATOMS.ADD R12, [UR4+0x340], R12`; `SHFL.IDX PT, R10, R12, R13, 0x1f`; `IADD R10, R10, R15` | per warp request: one shared-memory add of the requesting lanes' count by the highest of them, each lane at the base plus its rank among them | the port's fixed order, below | +| rescoring (`q5k_head.cu:488-492`) | `q5k_row_dev<1, 10>`'s sequence (section 1) | the head's bits | `q5k_row<1>` | +| `sum += p.y * __expf(p.x - bv)` where `p.y > 0` (`:228`) | `@P0 FADD.FTZ R0, -R3, R10`; `@P0 FMUL.FTZ R0, R0, 1.4426950216293334961`; `@P0 MUFU.EX2 R0, R0`; `@P0 FFMA.FTZ R4, R11, R0, R4` | `FFMA.FTZ(p.y, e, sum)` | `fma_ftz(p.y, expf_ftz(add_ftz(p.x, -bv)), sum)` | +| `sum += __expf(ex - bv) - __expf(lp - bv)` (`:230`) | `MUFU.EX2` pairs; `FADD.FTZ R7, R8, -R7`; `FADD.FTZ R7, R7, R4` | `FADD.FTZ(sum, FADD.FTZ(e_ex, -e_lp))` | `add_ftz(sum, add_ftz(expf_ftz(...), -expf_ftz(...)))` | +| `sum += shfl` (`:232`) | `FADD.FTZ R3, R3, R4`, offsets 16..1 | butterfly | `warp_sum_ftz` | +| `sum = fmaxf(sum, one)`; `1.0f / sum` (`:236-238`) | `FMNMX.FTZ R0, R0, R3, !PT`; `MUFU.RCP R9, R0` | | `rcp_ftz(max_ftz(sum, one))` | + +The list's order. basalt's `collect` appends every qualifying candidate with `atomicAdd(&f.cnt, 1)` on shared memory, +and nvcc compiles it as a warp-aggregated atomic: within one warp's request the slots go to the requesting lanes in +lane order, and the requests take their slots in the order they reach the shared-memory unit, which CUDA leaves +unspecified (each warp's requests in its own program order: its loop's candidates `i`, `i + 512`, ...). The order +matters: `pick` gives lane L the listed rows L and L + 32, so the order sets which lane adds which exact-minus- +approximate term before the butterfly, and so the probability's last bits; and when more than 64 candidates qualify, +it decides which 64 are rescored, and so possibly the pick. The scoping report's inference (section 7.4) that on CUDA +these vary from run to run follows. A threadgroup atomic would port the mechanism with documented Metal semantics, but +its order is just as unspecified, so neither the tests nor repeated runs could rely on the bits. The port fixes the +arrival order to ascending candidate index: pass k of the 512-strided loop, SIMD-groups 0..15 in order, lanes in order, +each slot `cnt + (the counts of the SIMD-groups before) + simd_prefix_exclusive_sum(take)` (the lane's rank among the +requesting lanes, as `POPC(mask & SR_LTMASK)`), the counts through threadgroup memory between two barriers per pass. +That is one of the orders basalt's kernel produces (every warp's request of pass k arriving before any of pass k + 1, +in warp order), with basalt's arithmetic on it; the list, the rescored set past 64 candidates and the probability then +repeat run to run, and the emulation checks them bit for bit. On the test's 400 trials, between 1 and 78 candidates +qualified (12.8 on average); the trials above 64 were checked bit for bit like the others. + +Every value these kernels compare (`FSETP.*.FTZ`, `FMNMX.FTZ`) is the result of an `.FTZ` operation or a stored fp32 +value written by one, so it is never subnormal, and the port's plain comparisons are the flushed ones. diff --git a/docs/research/basalt-nvcc/s2_experts.md b/docs/research/basalt-nvcc/s2_experts.md new file mode 100644 index 00000000..e447b49b --- /dev/null +++ b/docs/research/basalt-nvcc/s2_experts.md @@ -0,0 +1,220 @@ +# basalt's drafter experts as nvcc compiles them + +What NVIDIA's compiler emits at every rounding site of the drafter's routed Q2_0 experts (`src/core/mtp.cpp:932-935`): +`quantize_q8_0_scaled` on the activations, then `moe_grouped_s2` (gate/up, the SwiGLU, `quantize_q8_0_scaled` on the +intermediate, down), with the plan built on the device by `moe_group_resident`. Read from the sm_120 PTX and SASS, with +the Metal form the port writes at each site. This page is the authority the Metal kernels follow +(`docs/design/flash-next.md`, invariant 5), as `experts.md` is for the decode path's routed experts. + +Basalt paths are relative to commit `b4c63b55754637f4c72ad53a0f791d425f71eb36`; `path:a-b` means lines a to b there, +and a bare `:N` is a line of the file named last. + +## Method + +- **Sources.** `src/kernels/cuda/quantize_act.cu` and `src/kernels/cuda/s2_expert_grouped.cu` with the headers they + include (`include/basalt/kernels/quantize_act.hpp`, `f16_bits.hpp`, `s2_expert_grouped.hpp`, `dp4a.hpp`, + `verify_kernels.hpp`). Only basalt's public MIT source was sent. +- **Compilers.** Compiler Explorer's public API, as in `matvec.md`: NVCC 13.0.0 (`nvcc130`) and 13.3.0 (`nvcc133`), + PTX and the `SASS (sm_120)` listing. +- **Flags.** Neither file is in the `--use_fast_math` list (`CMakeLists.txt:185-202`), so both build with nvcc's + defaults: `-O3 -DNDEBUG -DBASALT_VERSION="0.0.1" --generate-code=arch=compute_120,code=[compute_120,sm_120]`, exactly, + in both versions. +- **Translation units.** Basalt's text verbatim, the local includes inlined under `#line` directives: the whole of + `quantize_act.cu`; and `s2_expert_grouped.cu:1-279` (the helpers, `row_dot_s2_q8`, `warp_sum`, the per-hit kernels, + `swiglu_kernel`, `f16_ld`, `expand_codes`, `load_x_chunk`, `chunk_s`) then `:736-1028` (the grouped kernels), with a + table taking the addresses of `gu_grouped_t_kernel`, `down_grouped_t_kernel`, `swiglu_kernel` and the previous + grouped kernels. The lines left out hold the per-hit pair kernels, the host launchers and `group_resident_kernel`, + which has no floating-point operation (it compares expert ids, counts, and writes addresses and indices; `:1033-1073`). +- **Version check.** Per kernel, the float instructions of 13.0 and 13.3 are the same multiset (`FMUL`, `FFMA` with its + rounding-mode variants, `FADD`, `I2FP`, `SHFL`, `MUFU`, `FSETP`, `FSEL`, `FMNMX`, `F2I`, `FCHK`): + `quantize_q8_0_scaled_warp_kernel` 1 `FMUL`, 2 `FADD`, 18 `FFMA`, 5 `FMNMX`, 5 `SHFL.BFLY`, 6 `MUFU.RCP`, 1 `F2I.TRUNC.NTZ` + in both; `gu_grouped_t_kernel` 6 `FMUL`, 6 `FFMA`, 6 `I2FP`, 19 `FADD`, 20 `SHFL.DOWN`; `down_grouped_t_kernel` 2, 2, + 2, 19, 20; `swiglu_kernel` 4 `FMUL`, 14 `FFMA`, 1 `MUFU.EX2`, 2 `MUFU.RCP`, 1 `FCHK`. The listings of the sites below + are line for line the same in both versions apart from register numbers; the one difference is an integer `VIMNMX` + in `gu_grouped_t_kernel` (2 against 3, the loop bounds). + +## Notation + +As in `matvec.md`: fl(e) rounds once to fp32, to nearest even; fma(a, b, c) rounds a·b + c once; h(x) is an fp16 value +converted to fp32 (exact); f(n) an int32 converted to fp32 (exact here: |n| ≤ 32 · 2 · 127). The PTX has no `.ftz` +(0 in each dump). In the SASS, `.FTZ` appears only inside `div.rn.f32` and `rcp.rn.f32`'s sequences and their slow +paths (`__cuda_sm3x_div_rn_noftz_f32_slowpath`, `__cuda_sm20_rcp_rn_f32_slowpath`): compares against infinity, which +flushing cannot change, and a negation (`FADD.FTZ R, -R, -RZ`) of a Newton residual that the exponent guards keep away +from the subnormal range. Both operations return IEEE's correctly rounded result, so every float operation of these +kernels is IEEE's, subnormals kept. + +## Summary + +| Kernel | Rounding sequence nvcc 13.x emits (sm_120) | Metal | +|---|---|---| +| `quantize_q8_0_scaled_warp_kernel` (`quantize_act.cu:78-101`) | amax = the largest \|x\| by an `FMNMX` butterfly (exact, subnormals compared as IEEE does); s = amax > 0 ? fl(amax / 127) : 0 (`div.rn.f32`); inv = s > 0 ? fl(1 / s) : 0 (`rcp.rn.f32`); t = fl(x · inv); r = fl(t + (t ≥ 0 ? 0.5 : −0.5)) (not fused); code = clamp(trunc(r), ±127), NaN to 0; fp16 d by `f16_from_f32` (integer operations) | amax by bit pattern; s by `ieee_div127`; inv by `ieee_rcp`; t = `ieee_mul(x, inv)`; `t + 0.5f` / `t - 0.5f`; `q8_1_code`; `f16_bits` (half()) | +| `gu_grouped_t_kernel` (`s2_expert_grouped.cu:904-968`) | per (row, entry), lane L, chunks c = L, L + 32, L + 64 (< 80) in order: acc = fma(fl(dw · dx), f(s − hx), acc) from +0; then `warp_sum`: five `SHFL.DOWN` + `FADD`, 16 down to 1; lane 0's value | `ieee_mul`, `ieee_fma`, `warp_sum_ieee` (an XOR butterfly of `ieee_add`, lane 0) | +| `swiglu_kernel` (`:165-171`) | e = `MUFU.EX2`(fl(g · (−log2 e))) (`ex2.approx.f32`, subnormal outputs kept); t = fl(e + 1); q = fl(g / t) (`div.rn.f32`); h = fl(u · q) | `expf_neg(g)`; `e + 1.0f`; `ieee_div(g, t)`; `ieee_mul(u, q)` | +| `down_grouped_t_kernel` (`:970-1027`) | per (row, entry): lane c < 20 holds chunk c: acc = fma(fl(dw · dx), f(s − hx), +0), the other lanes +0; `warp_sum` | `ieee_mul`, `ieee_fma`, `warp_sum_ieee` | +| `group_resident_kernel` (`:1033-1073`) | integer only | the same integer steps | + +The integer work (the Q2_0 codes through `expand_codes`, the activations regrouped through `__byte_perm` in +`load_x_chunk`, the `__dp4a` chains, which in SASS are `IDP.4A`) is exact, and the port computes it with the shared +integer helpers (`dp4a`, `byte_perm` in `kernels/common/basalt_fp.metal`). + +**Where a subnormal can occur.** This GPU flushes subnormal inputs and results of add, multiply, fma and division in +`MTLMathModeSafe`, and its `fmax` compares a subnormal as zero (`tests/kernels/test_basalt_platform.py`). The decode +path's routed experts never see a subnormal in their matrix-vector parts because the activation scale there is an fp16 +value, so every product is a multiple of 2^-48 (`experts.md`, Notation). That argument fails here: the activation scale +dx is the quantizer's fp32 s, any non-negative float. Site by site: + +- **amax** (`quantize_act.cu:84-86`): x can hold subnormals, which `FMNMX` orders exactly. The port takes the largest + bit pattern of |x|, as `q8_1_store_ieee` does (`matvec.md` section 3). +- **s = amax / 127** (`:87`): subnormal for amax < 127 · 2^-126. The port's `ieee_div127` is `q8_1_store_ieee`'s + division (scaled by 2^64 for amax ≥ 2^-119, integer division on the subnormal grid below). +- **inv = 1 / s** (`:88`): a subnormal s (the GPU would flush it, giving infinity) has a finite reciprocal when + s > 2^-128. `rcp.rn.f32`'s slow path scales such an s by 2^64 (`FFMA R, R0, 1.8446744e+19, RZ` at `quantize_act.cu:101` + in the listing) and so does the port's `ieee_rcp`: fl(1 / (s · 2^64)) · 2^64, exact scaling of a correctly rounded + normal reciprocal (an overflow of the last multiply is IEEE's overflow of 1 / s). For a normal s, 1 / s is at least + 127 / FLT_MAX, normal. +- **t = x · inv** (`:96`): subnormal x against a large inv (a block of tiny values) and subnormal products occur: + `ieee_mul`. An infinite inv (s ≤ 2^-128) meets a zero x as NaN, which `ieee_mul` returns as CUDA does. +- **r = t ± 0.5 and the compare** (`:97`): only the code of r matters, and for |t| < 0.5 it is 0 whichever sign the + compare sees and whether t is flushed (r is then in (−1, 1), and truncation gives 0); for |t| ≥ 0.5 t is normal and + the GPU's add and compare are IEEE's. So the port writes the plain add and compare after an IEEE t. +- **The dot products** (`s2_expert_grouped.cu:956-957`, `:1015-1016`): p = dw · dx is subnormal when dx < 2^-126 / |dw|. + Each p is a multiple of its own ulp, and f(s − hx) an integer, so when every |p| ≥ 2^-103 all terms, partial sums and + butterfly sums are multiples of 2^-126 and none is subnormal; with a smaller p, a term or a cancelling sum can be. + The port's `ieee_fma(a, n, c)` (n an integer, |n| < 2^24) takes the hardware fma when a and c are each zero or at + least 2^-100 (then a·n + c is a multiple of 2^-123: zero or normal). With a nonzero a below 2^-100 and |c| < 2^62 it + computes on operands scaled by 2^64: the exact a·n + c is a multiple of 2^-149, so a subnormal result is exact and + the scaled result scales back exactly (`ieee_down64`); with a larger c the sum rounds to c, the hardware's result. + With a nonzero c below 2^-100 and a zero or at least 2^-100, a finite a·n of zero leaves c; otherwise |a·n| ≥ 2^-100, + the sum is at least 2^-124, and a subnormal c changes its rounding only by breaking a tie, which ±2^-126 (normal, not + flushed) does the same way. The butterfly's adds are `ieee_add`. +- **The SwiGLU** (`:170`): g can now be subnormal or below 2^-125. Then g · (−log2 e) is tiny, e rounds to 1 on both + sides (2^x for |x| < 2^-24 is 1 to fp32), t = 2, and g / 2 is subnormal: `ieee_div(g, t)`, which takes the hardware + quotient when g or t is infinite or NaN (t = +inf past g = −88.72: the quotient is −0), or when |g| ≥ 2^-100 and the + quotient is at least 2^-125; a zero g gives its signed zero; otherwise it divides the significands as integers and + rounds to nearest even on the result's grid. For |g| ≥ 2^-100 (up to g = −88.72), |q| ≥ 2.6e-37, and beyond −88.72 + e overflows and q = −0 (`experts.md`, Notation). The integer path is for |g| < 2^-100, normal g included + (g = −2^-126 gives q = −2^-127). e itself can be subnormal + (g > 87.3: `ex2.approx.f32` keeps it through the halving path below −126) and the GPU's `fast::exp2` may flush it; t = + fl(e + 1) = 1 either way. h = u · q can be subnormal: `ieee_mul`. +- **The intermediate's quantizer**: as the first row, on h. +- **NaN bit patterns**: sm_120's `FFMA`, `FADD`, `FMUL` and `div.rn.f32` give the canonical NaN 0x7fffffff whatever + their operands; this GPU's fma, add and division give 0x7fc00000 (`ieee_mul`'s explicit path returns 0x7fffffff). + A NaN in gate/up, the SwiGLU or down comes from one of those operations or passes through them (a NaN g makes e and + t NaN), so the port rewrites a NaN to 0x7fffffff in every float those kernels store (`cuda_nan`, now in + `basalt_fp.metal`; `nan.md`) and stores CUDA's bits. The quantizer stores no NaN: s never is one, and a NaN r gives + code 0. + +## 1. `quantize_q8_0_scaled_warp_kernel` (`quantize_act.cu:78-101`; launch `:219-238`) + +One warp a 32-value block, lane = value; grid ceil(nb · 32 / 256) blocks of 256 (`:230-231`). + +| Site | basalt | PTX (13.3) | SASS 13.0 | SASS 13.3 | Metal | +|---|---|---|---|---|---| +| \|x\| | `:84` `fabsf(xv)` | `abs.f32` | `FADD R12, \|R6\|, -RZ` | `FADD R12, \|R6\|, -RZ` | bit pattern `as_type(fabs(x))` | +| amax | `:86` `fmaxf(amax, __shfl_xor_sync(..., o))`, o = 16..1 | `max.f32` ×5 | `SHFL.BFLY` + `FMNMX R5, \|R6\|, R5, !PT` ... ×5 | the same | `max` of the bit patterns over `simd_shuffle_xor`, 16..1 | +| s | `:87` `amax > 0.f ? amax / 127.f : 0.f` | `div.rn.f32 %r24, %r23, 0f42FE0000`; `selp.f32` | `FCHK P0, R0, 127`; `FFMA R5, R0, UR4, RZ`; `FFMA R8, R5, -127, R0`; `FFMA R7, R8, UR4, R5`; slow path `__cuda_sm3x_div_rn_noftz_f32_slowpath`; `FSEL R0, R7, RZ, P2` | the same | `ieee_div127(amax)` (0 for amax 0) | +| inv | `:88` `s > 0.f ? 1.f / s : 0.f` | `rcp.rn.f32`; `selp.f32` | `MUFU.RCP R3, R0`; `FFMA R2, R0, R3, -1`; `FADD.FTZ R2, -R2, -RZ`; `FFMA R2, R3, R2, R3`; slow path `__cuda_sm20_rcp_rn_f32_slowpath` (scales by 2^64); `FSEL R3, R2, RZ, P0` | the same | `ieee_rcp(s)` (0 for s 0) | +| t | `:96` `xv * inv` | `mul.f32` | `FMUL R3, R6, R3` | `FMUL R3, R6, R3` | `ieee_mul(x, inv)` | +| r | `:97` `t + (t >= 0.f ? 0.5f : -0.5f)` | `setp.ge.f32`; `selp.f32 0f3F000000, 0fBF000000`; `add.f32` | `FSETP.GE.AND P0, PT, R3, RZ, PT`; `FSEL R0, R0, -0.5, P0`; `FADD R0, R3, R0` | the same | `t >= 0.0f ? t + 0.5f : t - 0.5f` | +| code | `:98-100` `(int) r`, clamp ±127 | `cvt.rzi.s32.f32`; `min`/`max` | `F2I.TRUNC.NTZ`; `VIMNMX.S32` ×2 | the same | `q8_1_code(r)` (clamp, truncate, NaN to 0) | +| fp16 d | `:92-94` `f16_from_f32(s)` | integer operations (`f16_bits.hpp:36-65`) | integer | integer | `f16_bits(s)`: `half(s)`'s bits | + +Notes: + +- **The code rounding is not fused.** The PTX has `mul.f32` then `add.f32`, which `ptxas` may contract, but the SASS + keeps `FMUL` then `FADD`: t feeds the compare as well. So r = fl(fl(x · inv) ± 0.5), as written, and the scope's + hypothesis of fma(x, inv, ±0.5) does not hold in either version. +- **The division and the reciprocal round correctly.** `div.rn.f32` is the `FCHK`-guarded iteration with its IEEE slow + path, `rcp.rn.f32` the `MUFU.RCP` iteration with an exponent-range guard and its slow path; both are IEEE's + correctly rounded operations, which Metal's `/` gives in safe mode for normal operands and results + (`test_basalt_platform.py`), and the IEEE helpers give elsewhere. +- **`f16_from_f32` is round to nearest even**, with a finite overflow to infinity, the 65520 tie to even (infinity), + fp16 subnormals kept, an fp32 subnormal to the zero of its sign and a NaN to `sign | 0x7E00` (`f16_bits.hpp:36-65`). + Metal's float-to-half conversion is IEEE's round to nearest even (MSL 4.1 section 2.7 and `test_basalt_platform.py`); + `tests/kernels/test_basalt_s2_experts.py` checks it against a transcription of `f16_from_f32` on basalt's own vectors + (`quantize_act_parity.cpp:298-336`), the fp16 subnormal range, the 65504 to 65536 boundary and 2^20 random bit + patterns, and the quantizer's tests compare every block's fp16 d with the transcription. s is never NaN (a NaN x is + dropped by `fmaxf`, and an all-NaN block has amax NaN, so `amax > 0.f` is false and s = 0). +- **The fp32 scale is stored unrounded**: `scales[b] = s` (`:91`), the value the next matrix-vector step multiplies by. + +## 2. Gate and up: `gu_grouped_t_kernel` (`s2_expert_grouped.cu:904-968`) + +Grid (2 · 640 / 32 = 40, cap_groups) blocks of 256 (`:1096-1105`). A block takes the 32 row slots +[32 bx, 32 bx + 32) of group blockIdx.y (16 gate/up pairs; warp w takes pairs w and w + 8) after staging the group's +entries (at most GMAX = 8, `:742-745`) in shared memory: per entry and chunk the eight regrouped activation words +(`load_x_chunk`, `:240-270`) and (dx as bits, hx) (`stage_chunk`, `:895-902`). A pair's codes are expanded once +(`expand_codes`, `:221-231`); per entry k and lane L, the chunks c = L, L + 32, L + 64 below 80, in that order. + +| Site | basalt | PTX (13.3) | SASS 13.0 | SASS 13.3 | Metal | +|---|---|---|---|---|---| +| p = dw · dx | `:956` `dw0[q] * dx` (and `:957` row 1) | `mul.f32 %r235, %r233, %r85` | `FMUL R41, R25, R40` | `FMUL R0, R45, R2` | `ieee_mul(dw, dx)` | +| f | `:956` `(float) (chunk_s(m0[q], X) - dh.y)` | `cvt.rn.f32.s32` | `I2FP.F32.S32 R42, R42` | `I2FP.F32.S32 R81, R81` | `float(s - hx)` | +| first chunk | `:956` `acc0 += ...`, acc0 = 0 | `fma.rn.f32 %r238, %r235, %r237, 0f00000000` | `FFMA R73, R41, R42, RZ` | `FFMA R0, R0, R81, RZ` | `ieee_fma(p, f, 0.0f)` | +| later chunks | `:956` | `fma.rn.f32 %r335, %r245, %r247, %r238` | `FFMA R43, R72, R43, R73` | `FFMA R0, R3, R78, R0` | `ieee_fma(p, f, acc)` | +| `warp_sum` | `:961-962`; `:104-108` `v += __shfl_down_sync(0xFFFFFFFFu, v, off)`, off 16..1 | `shfl.sync.down.b32 ..., 16, 31, -1` and `add.f32`, ×5 | `SHFL.DOWN PT, R75, R43, 0x10, 0x1f` + `FADD` ×5 | the same | `warp_sum_ieee` (lane 0) | +| stores | `:961-965` gate at `e * 640 + r`, up at `cap * 640 + e * 640 + r` | | | | the same | + +`warp_sum` shifts down where the decode path's butterfly XORs. Lane 0's value is the same: at the step with offset o, +lane 0 adds lane o, and every lane below 2o holds the same partial in both trees (lane i < o adds lane i + o in both), +and an add is commutative. Lanes past 31 − o read their own value in a shift-down; only lane 0 is stored. The port +keeps the XOR butterfly the other kernels share, with `ieee_add`. + +## 3. The SwiGLU: `swiglu_kernel` (`:165-171`) + +`gate_up[i] = (g / (1.0f + __expf(-g))) * u;` in place over the gate half, i < cap_entries · 640 (`:1106-1110`): every +capacity entry, the ones past the plan included. + +| Site | basalt | PTX (13.3) | SASS (13.0 and 13.3, the same lines) | Metal | +|---|---|---|---|---| +| `__expf(-g)` | `:170` | `mul.f32 %r6, %r4, 0fBFB8AA3B`; `ex2.approx.f32` | `FMUL R6, R0, -1.4426950216293334961`; `FSETP.GEU.AND P0, PT, R6, -126, PT`; `@!P0 FMUL R6, R6, 0.5`; `MUFU.EX2 R7, R6`; `@!P0 FMUL R7, R7, R7` | `expf_neg(g)` = `fast::exp2(g * as_type(0xBFB8AA3Bu))` | +| t | `:170` `1.0f + e` | `add.f32 %r8, %r7, 0f3F800000` | `FADD R7, R7, 1` | `e + 1.0f` | +| q | `:170` `g / t` | `div.rn.f32 %r9, %r4, %r8` | `MUFU.RCP R8, R7`; `FCHK P0, R0, R7`; `FFMA R9, -R7, R8, 1`; `FFMA R9, R8, R9, R8`; `FFMA R8, R0, R9, RZ`; `FFMA R3, -R7, R8, R0`; `FFMA R3, R9, R3, R8`; slow path when `FCHK` fails | `ieee_div(g, t)` | +| h | `:170` `(...) * u` | `mul.f32 %r10, %r5, %r9` | `FMUL R3, R2, R3` | `ieee_mul(u, q)` | + +The exponential is the IEEE build's `ex2.approx.f32` (as in `experts.md` section 2): `MUFU.EX2` is NVIDIA's approximate +base-2 exponential, with no documented Metal counterpart; the port keeps the contract's mapping, `fast::exp2` of the +product basalt's PTX forms, and the tests take e from the GPU and check every other step bit for bit. The product with +u is a plain `mul.f32` with no add after it, so nothing contracts. + +## 4. The intermediate's quantizer (`:1111`) + +`quantize_q8_0_scaled(gate_up, h_q8_0, h_scales, cap_entries * 640, stream)`: section 1's kernel over the SwiGLU +values of every capacity entry, 20 blocks an entry. The scratch is basalt's (`:1090-1094`): gate/up (cap · 1280 +floats, the bytes rounded up to 16), the quantized intermediate (cap · 20 blocks of 34 bytes, rounded up to 16), then +its fp32 scales (cap · 20). + +## 5. Down: `down_grouped_t_kernel` (`:970-1027`) + +Grid (2560 / 64 = 40, cap_groups) blocks of 256 (`:1113-1121`); 64 rows a block, warp w takes the row pairs w, w + 8, +w + 16, w + 24 of them; a down row is 20 chunks, lane c < 20 holds chunk c. The entries' intermediate rows (entry e's +20 blocks at e · 680 bytes) and h_scales are staged as in gate/up. + +| Site | basalt | PTX (13.3) | SASS 13.0 | SASS 13.3 | Metal | +|---|---|---|---|---|---| +| p | `:1015` `dw0 * dx` (and `:1016`) | `mul.f32 %r130, %r174, %r128` | `FMUL R21, R20, R29` | `FMUL R25, R24, R6` | `ieee_mul(dw, dx)` | +| term | `:1015` `acc0 += ...`, acc0 = 0 | `cvt.rn.f32.s32`; `fma.rn.f32 %r180, %r130, %r132, 0f00000000` | `I2FP.F32.S32 R34, R34`; `FFMA R35, R21, R34, RZ` | `I2FP.F32.S32 R38, R39`; `FFMA R38, R25, R38, RZ` | `ieee_fma(p, f, 0.0f)` | +| idle lanes | `:1007-1008` `acc0 = 0.0f`, kept for c ≥ 20 | | | | +0 | +| `warp_sum` | `:1018-1019` | `shfl.sync.down.b32` + `add.f32` ×5 | `SHFL.DOWN` + `FADD` ×5 | the same | `warp_sum_ieee` (lane 0) | +| stores | `:1020-1024` `out[ent_dst[e0 + k] * 2560 + r]` and `+ 1` | | | | the same | + +## 6. `group_resident_kernel` (`:1033-1073`) + +One block of 128 threads over n ≤ 128 routed ids (`moe_group_resident` refuses other n, `:1079`): a group per distinct +expert in first-appearance order, its entries in routing order; `grp_ptr[g] = base + id · blob`, `grp_start`, +`counts = {groups, entries}`, `ent_dst[at] = i`, `ent_tok[at] = i / k_per_tok`. No float arithmetic; the port writes +the same values, the addresses as `GrpPtr` (a 64-bit GPU address a group). + +## 7. Metal + +`kernels/common/basalt_s2_experts.metal` holds `basalt_quantize_q8_0_scaled`, `basalt_s2_group_resident`, +`basalt_s2_gu`, `basalt_s2_swiglu` and `basalt_s2_down`. Each source starts with `#pragma STDC FP_CONTRACT OFF` +(through `basalt_fp.metal`), so nothing fuses unless `fma()` is written, and no `fma()` is: every `FFMA` above is an +`ieee_fma`, whose hardware path is `fma()`. The IEEE helpers live with their siblings in `basalt_q8_1.metal`: +`ieee_div127` (factored out of `q8_1_store_ieee`, which now calls it), `ieee_rcp`, `ieee_fma`, `ieee_div` next to the +existing `ieee_up64`, `ieee_down64`, `ieee_add` and `ieee_mul`, and `warp_sum_ieee`; `f16_bits` (the float-to-half +conversion `q8_1_put` already used, as bits) and `GrpPtr` move into `basalt_fp.metal`. Every compare a subnormal can +reach is on bits: basalt's `amax > 0.f` is the integer key's `key > 0`, and `s > 0.f` is `s`'s bits being nonzero (s is +never negative or NaN), since this GPU compares a subnormal as zero. Basalt's plan pointers stay pointers: a table +of 64-bit GPU addresses (`GrpPtr`, as `basalt_experts.metal`), each 2-byte aligned and inside a buffer the dispatch makes +resident, so the blobs may sit in several buffers; the codes are read as 16-bit words (CUDA's `uint2` loads need an +8-byte aligned blob, a precondition the 16-bit reads do not have). diff --git a/kernels/common/basalt_dense_tc.metal b/kernels/common/basalt_dense_tc.metal new file mode 100644 index 00000000..4f397d1a --- /dev/null +++ b/kernels/common/basalt_dense_tc.metal @@ -0,0 +1,367 @@ +// Copyright (c) 2023-2026 The ggml authors (MIT) +// Copyright (c) 2026 Jesús Gulfo (MIT) +// Adapted from basalt (jesdga95/basalt) src/kernels/cuda/dense_tc.cu:32-931 +// @ b4c63b55754637f4c72ad53a0f791d425f71eb36 (MIT; third_party/NOTICE), whose block formats are ggml-org/llama.cpp +// ggml/src/ggml-common.h's @ 3cf03257f219afbe7334045ff7c6a06ac68c627d (MIT; third_party/NOTICE). +// +// basalt's dense_tc and dense_tc_pair: y[j][r] = row r of a GGUF weight matrix (rows of n_in / 256 super-blocks of +// Fmt::SB bytes) times column j of q8_1 activations (basalt_q8_1.metal's layout: column j's blocks start at +// block j * n_in / 32), for j < ncols <= 8; y[j] starts at j * n_out. Needs basalt_fp.metal ahead of it. +// +// A threadgroup is one 16-row tile. basalt's warps of the tile are virtual SIMD-groups (24 for the one order, 8 for +// tile, pair and s with KS 2, 4 for s with KS 1), run by the threadgroup's SIMD-groups in turn: warp w takes half +// super-block w & 3 of the 512-value chunks w >> 2, w >> 2 + NG, ... (NG = warps / 4) in ascending order, each lane +// adding its four (row, column) terms (half_sb_terms, dense_tc.cu:100-330) from +0; the tile's warp sums are then +// added by the order's tree (docs/research/basalt-nvcc/dense_tc.md section 2). mma.sync's only role there is the exact +// int32 dot of a block (or half block) for 16 rows by 8 columns: lane 4g + t holds basalt's A and B fragments, +// fetches column c's code words from lane 4c + t, forms its partial dots with dp4a, and the four lanes of group g add +// them (integer adds, exact in any order), each keeping columns 2t and 2t + 1, the D fragment basalt's lane holds. The +// float steps are the ones nvcc compiles (dense_tc.md section 1): fma() exactly where SASS has FFMA, plain * and + at +// FMUL and FADD, nothing flushed (no subnormal reaches them). Basalt stages the tile in shared memory; staging is not +// arithmetic, so the weights are read from device memory (two 16-bit loads a word where a block is only 2-byte +// aligned). Rows past n_out read row n_out - 1 and columns at or past ncols get zero codes and d8 = 0; neither is +// stored. A NaN is stored as sm_120's (cuda_nan; docs/research/basalt-nvcc/nan.md). +// +// Macros: DTC_TYPE the ggml type id (11 Q3_K, 12 Q4_K, 13 Q5_K, 14 Q6_K, 23 IQ4_XS, 42 Q2_0); DTC_ORDER 0 one, 1 tile, +// 2 s with KS 1, 3 s with KS 2 (monolith/kernels.py basalt_dense_tc_macros); DTC_TYPE0 / DTC_TYPE1 the pair's +// matrices' types. Grid: one threadgroup per 16-row tile (the pair: the first matrix's tiles, then the second's), of +// at least 4 SIMD-groups. +#pragma STDC FP_CONTRACT OFF + +#ifndef DTC_TYPE +#define DTC_TYPE 12 +#endif +#ifndef DTC_ORDER +#define DTC_ORDER 1 +#endif +#ifndef DTC_TYPE0 +#define DTC_TYPE0 DTC_TYPE +#endif +#ifndef DTC_TYPE1 +#define DTC_TYPE1 DTC_TYPE0 +#endif +#define DTC_NWV (DTC_ORDER == 0 ? 24 : DTC_ORDER == 2 ? 4 : 8) // basalt's warps per tile + +struct DtcParams { uint n_in; uint n_out; uint ncols; uint n_out1; }; + +// Fmt::SB (dense_tc.cu:35-42): the bytes of 256 values (Q2_0: four 64-value blocks) +static constexpr int dtc_sb(int t) { + return t == 12 ? 144 : t == 13 ? 176 : t == 14 ? 210 : t == 23 ? 136 : t == 11 ? 110 : 72; +} + +static inline uint ld16(device const uchar* p) { return uint(*(device const ushort*)p); } +static inline uint ld32(device const uchar* p) { return *(device const uint*)p; } // 4-byte aligned +static inline uint ld32_b2(device const uchar* p) { return ld16(p) | (ld16(p + 2) << 16); } // 2-byte aligned +static inline int byte_of(uint w, int b) { return int((w >> (8 * b)) & 0xffu); } +static inline int sbyte_of(uint w, int b) { return int(as_type(uchar(w >> (8 * b)))); } +static inline uint vsub4u(uint a, uint b) { return as_type(vsub4(as_type(a), as_type(b))); } + +// The quad's sums of each lane's partial dots p0 (row g) and p1 (row g + 8) for columns 0..3 (lo) and 4..7 (hi): an +// exchange over XOR 2 leaves lanes t = 0, 1 columns 0..3 and lanes 2, 3 columns 4..7, one over XOR 1 leaves lane t +// columns 2t and 2t + 1. Returns the D fragment: (g, 2t), (g, 2t + 1), (g + 8, 2t), (g + 8, 2t + 1). +static inline int4 quad_sum(int4 p0lo, int4 p0hi, int4 p1lo, int4 p1hi, ushort t) { + const bool b1 = (t & 2) != 0, b0 = (t & 1) != 0; + const int4 s0 = (b1 ? p0hi : p0lo) + simd_shuffle_xor(b1 ? p0lo : p0hi, ushort(2)); + const int4 s1 = (b1 ? p1hi : p1lo) + simd_shuffle_xor(b1 ? p1lo : p1hi, ushort(2)); + const int2 u0 = (b0 ? s0.zw : s0.xy) + simd_shuffle_xor(b0 ? s0.xy : s0.zw, ushort(1)); + const int2 u1 = (b0 ? s1.zw : s1.xy) + simd_shuffle_xor(b0 ? s1.xy : s1.zw, ushort(1)); + return int4(u0, u1); +} + +// mma.sync.aligned.m16n8k32.row.col.s32.s8.s8.s32 with C = 0 (dense_tc.cu:60-65): a0 / a1 rows g / g + 8 values +// 4t.., a2 / a3 values 16 + 4t..; b0 / b1 column g's codes 4t.. and 16 + 4t... +static inline int4 mma_k32(uint a0, uint a1, uint a2, uint a3, uint b0, uint b1, ushort t) { + int p0[8], p1[8]; + for (ushort c = 0; c < 8; ++c) { + const int x0 = simd_shuffle(as_type(b0), ushort(4 * c + t)); + const int x1 = simd_shuffle(as_type(b1), ushort(4 * c + t)); + p0[c] = dp4a(as_type(a2), x1, dp4a(as_type(a0), x0, 0)); + p1[c] = dp4a(as_type(a3), x1, dp4a(as_type(a1), x0, 0)); + } + return quad_sum(int4(p0[0], p0[1], p0[2], p0[3]), int4(p0[4], p0[5], p0[6], p0[7]), + int4(p1[0], p1[1], p1[2], p1[3]), int4(p1[4], p1[5], p1[6], p1[7]), t); +} + +// mma.sync.aligned.m16n8k16 (dense_tc.cu:66-70): a0 / a1 rows g / g + 8 values 4t.. of a 16-value half, b column g's. +static inline int4 mma_k16(uint a0, uint a1, uint b, ushort t) { + int p0[8], p1[8]; + for (ushort c = 0; c < 8; ++c) { + const int x = simd_shuffle(as_type(b), ushort(4 * c + t)); + p0[c] = dp4a(as_type(a0), x, 0); + p1[c] = dp4a(as_type(a1), x, 0); + } + return quad_sum(int4(p0[0], p0[1], p0[2], p0[3]), int4(p0[4], p0[5], p0[6], p0[7]), + int4(p1[0], p1[1], p1[2], p1[3]), int4(p1[4], p1[5], p1[6], p1[7]), t); +} + +// The column data of a warp's four blocks (XFrag, dense_tc.cu:93-98): column g's codes 4t.. (b0) and 16 + 4t.. (b1), +// and the q8_1 scales of columns 2t and 2t + 1. +struct XFrag { uint b0[4]; uint b1[4]; float d8[4][2]; }; + +// Half super-block n (blocks 4n..4n + 3) of the super-blocks at p0 (row g) and p1 (row g + 8): the four (row, column) +// terms added to acc (half_sb_terms, dense_tc.cu:100-330; the float sites of dense_tc.md section 1). +template +static inline void half_sb_terms(thread float4& acc, device const uchar* p0, device const uchar* p1, int n, ushort t, + thread const XFrag& x) { + device const uchar* p[2] = {p0, p1}; + if (TYPE == 12 || TYPE == 13) { // :106-156 + uint qw[2][4], hw[2][2] = {{0u, 0u}, {0u, 0u}}, sw[2][3]; + float dmx[2], dmy[2]; + for (int h = 0; h < 2; ++h) { + device const uchar* qs = p[h] + (TYPE == 12 ? 16 : 48) + 64 * n; + for (int i = 0; i < 4; ++i) qw[h][i] = ld32(qs + 16 * i + 4 * t); // pairs 2n, 2n + 1: words 4t, 16 + 4t + if (TYPE == 13) { + hw[h][0] = ld32(p[h] + 16 + 4 * t); + hw[h][1] = ld32(p[h] + 32 + 4 * t); + } + for (int i = 0; i < 3; ++i) sw[h][i] = ld32(p[h] + 4 + 4 * i); + dmx[h] = h2f(ushort(ld16(p[h]))); + dmy[h] = h2f(ushort(ld16(p[h] + 2))); + } + for (int i = 0; i < 4; ++i) { + const int j = 4 * n + i, pp = i >> 1, sh = 4 * (i & 1); + uint lo[2], hi[2]; + float f1[2], f2[2]; + for (int h = 0; h < 2; ++h) { + lo[h] = (qw[h][2 * pp] >> sh) & 0x0f0f0f0fu; + hi[h] = (qw[h][2 * pp + 1] >> sh) & 0x0f0f0f0fu; + if (TYPE == 13) { + lo[h] |= ((hw[h][0] >> j) & 0x01010101u) << 4; + hi[h] |= ((hw[h][1] >> j) & 0x01010101u) << 4; + } + int sc, m; // get_scale_min_k4 + if (n == 0) { + sc = byte_of(sw[h][0], i) & 63; + m = byte_of(sw[h][1], i) & 63; + } else { + sc = (byte_of(sw[h][2], i) & 0xF) | ((byte_of(sw[h][0], i) >> 6) << 4); + m = (byte_of(sw[h][2], i) >> 4) | ((byte_of(sw[h][1], i) >> 6) << 4); + } + f1[h] = dmx[h] * float(sc); // FMUL + f2[h] = dmy[h] * float(m); // FMUL + } + const int4 d = mma_k32(lo[0], lo[1], hi[0], hi[1], x.b0[i], x.b1[i], t); + // the code sums of columns 2t and 2t + 1 (column g's from lanes 4g..4g + 3) + int is = dp4a(0x01010101, as_type(x.b0[i]), dp4a(0x01010101, as_type(x.b1[i]), 0)); + is += simd_shuffle_xor(is, ushort(1)); + is += simd_shuffle_xor(is, ushort(2)); + const int isum[2] = {simd_shuffle(is, ushort(8 * t)), simd_shuffle(is, ushort(8 * t + 4))}; + for (int q = 0; q < 4; ++q) { + // f1 * dot - f2 * isum: ptxas rounds the dmin product and fuses the d product (dense_tc.md, Q4_K) + const float inner = fma(f1[q >> 1], float(d[q]), -(f2[q >> 1] * float(isum[q & 1]))); + acc[q] = fma(inner, x.d8[i][q & 1], acc[q]); + } + } + } else if (TYPE == 14) { // :157-195 + uint lw[2][4], hw[2][2], sw[2][2]; + float dd[2]; + for (int h = 0; h < 2; ++h) { + device const uchar* ql = p[h] + 64 * n; + device const uchar* qh = p[h] + 128 + 32 * n; + for (int i = 0; i < 4; ++i) lw[h][i] = ld32_b2(ql + 16 * i + 4 * t); + hw[h][0] = ld32_b2(qh + 4 * t); + hw[h][1] = ld32_b2(qh + 16 + 4 * t); + sw[h][0] = ld32_b2(p[h] + 192 + 8 * n); + sw[h][1] = ld32_b2(p[h] + 196 + 8 * n); + dd[h] = h2f(ushort(ld16(p[h] + 208))); + } + float4 part = 0.0f; + for (int i = 0; i < 4; ++i) { // block 4n + i: ql bytes 32 (i & 1) + .., nibble i >> 1, qh bits 2i + const int sh = 4 * (i >> 1), sq = 2 * i, li = 2 * (i & 1); + uint lo[2], hi[2]; + int sc0[2], sc1[2]; + for (int h = 0; h < 2; ++h) { + lo[h] = vsub4u(((lw[h][li] >> sh) & 0x0f0f0f0fu) | (((hw[h][0] >> sq) & 0x03030303u) << 4), 0x20202020u); + hi[h] = vsub4u(((lw[h][li + 1] >> sh) & 0x0f0f0f0fu) | (((hw[h][1] >> sq) & 0x03030303u) << 4), + 0x20202020u); + sc0[h] = sbyte_of(sw[h][i >> 1], 2 * (i & 1)); + sc1[h] = sbyte_of(sw[h][i >> 1], 2 * (i & 1) + 1); + } + const int4 e0 = mma_k16(lo[0], lo[1], x.b0[i], t); + const int4 e1 = mma_k16(hi[0], hi[1], x.b1[i], t); + for (int q = 0; q < 4; ++q) + part[q] = fma(float(sc0[q >> 1] * e0[q] + sc1[q >> 1] * e1[q]), x.d8[i][q & 1], part[q]); + } + for (int q = 0; q < 4; ++q) acc[q] = fma(dd[q >> 1], part[q], acc[q]); + } else if (TYPE == 11) { // :196-234; Q3_K: hmask[32], qs[64], scales[12], d + uint qw[2][2], hw[2][2], sc[2][2]; + float dd[2]; + for (int h = 0; h < 2; ++h) { + qw[h][0] = ld32_b2(p[h] + 32 + 32 * n + 4 * t); // values 4t.. of every block of the half + qw[h][1] = ld32_b2(p[h] + 48 + 32 * n + 4 * t); // values 16 + 4t.. + hw[h][0] = ld32_b2(p[h] + 4 * t); + hw[h][1] = ld32_b2(p[h] + 16 + 4 * t); + const uint a0 = ld32_b2(p[h] + 96), a1 = ld32_b2(p[h] + 100), a2 = ld32_b2(p[h] + 104); + // the half's eight 6-bit scales (ggml's aux[2n], aux[2n + 1]) + sc[h][0] = ((n ? a0 >> 4 : a0) & 0x0f0f0f0fu) | (((a2 >> (4 * n)) & 0x03030303u) << 4); + sc[h][1] = ((n ? a1 >> 4 : a1) & 0x0f0f0f0fu) | (((a2 >> (4 * n + 2)) & 0x03030303u) << 4); + dd[h] = h2f(ushort(ld16(p[h] + 108))); + } + float4 part = 0.0f; + for (int i = 0; i < 4; ++i) { // block 4n + i: 2-bit plane i of the half's qs, hmask bit 4n + i + const int j = 4 * n + i; + uint lo[2], hi[2]; + int sc0[2], sc1[2]; + for (int h = 0; h < 2; ++h) { + lo[h] = vsub4u(((qw[h][0] >> (2 * i)) & 0x03030303u) | (((hw[h][0] >> j) & 0x01010101u) << 2), + 0x04040404u); + hi[h] = vsub4u(((qw[h][1] >> (2 * i)) & 0x03030303u) | (((hw[h][1] >> j) & 0x01010101u) << 2), + 0x04040404u); + sc0[h] = byte_of(sc[h][i >> 1], 2 * (i & 1)) - 32; + sc1[h] = byte_of(sc[h][i >> 1], 2 * (i & 1) + 1) - 32; + } + const int4 e0 = mma_k16(lo[0], lo[1], x.b0[i], t); + const int4 e1 = mma_k16(hi[0], hi[1], x.b1[i], t); + for (int q = 0; q < 4; ++q) + part[q] = fma(float(sc0[q >> 1] * e0[q] + sc1[q >> 1] * e1[q]), x.d8[i][q & 1], part[q]); + } + for (int q = 0; q < 4; ++q) acc[q] = fma(dd[q >> 1], part[q], acc[q]); + } else if (TYPE == 42) { // :235-270; four 18-byte blocks d, qs[16] + for (int b = 0; b < 2; ++b) { // Q2_0 block 2n + b: the 32-value blocks 4n + 2b, 4n + 2b + 1 + float dw[2]; + uint qb[2][2][2]; + for (int h = 0; h < 2; ++h) { + device const uchar* bp = p[h] + 18 * (2 * n + b); + dw[h] = h2f(ushort(ld16(bp))); + for (int k = 0; k < 2; ++k) { + qb[h][k][0] = bp[2 + 8 * k + t]; + qb[h][k][1] = bp[6 + 8 * k + t]; + } + } + float4 part = 0.0f; + for (int k = 0; k < 2; ++k) { + const int i = 2 * b + k; + uint v[2][2]; + for (int h = 0; h < 2; ++h) + for (int e = 0; e < 2; ++e) { + const uint q = qb[h][k][e]; + v[h][e] = vsub4u((q | q << 6 | q << 12 | q << 18) & 0x03030303u, 0x01010101u); + } + const int4 d = mma_k32(v[0][0], v[1][0], v[0][1], v[1][1], x.b0[i], x.b1[i], t); + for (int q = 0; q < 4; ++q) part[q] = fma(float(d[q]), x.d8[i][q & 1], part[q]); + } + for (int q = 0; q < 4; ++q) acc[q] = fma(dw[q >> 1], part[q], acc[q]); + } + } else { // :297-329; IQ4_XS + uint qw[2][4]; + int sl[2], shh[2]; + float dw[2]; + for (int h = 0; h < 2; ++h) { + for (int i = 0; i < 4; ++i) qw[h][i] = ld32(p[h] + 8 + 16 * (4 * n + i) + 4 * t); + sl[h] = int(ld16(p[h] + 4 + 2 * n)); + shh[h] = int(ld16(p[h] + 2)); + dw[h] = h2f(ushort(ld16(p[h]))); + } + float4 part = 0.0f; + for (int i = 0; i < 4; ++i) { + const int j = 4 * n + i; + uint lo[2], hi[2]; + int ls[2]; + for (int h = 0; h < 2; ++h) { + const int2 v = iq4_table_lookup(as_type(qw[h][i])); // dense_tc.cu's iq4_lookup: the same bytes + lo[h] = as_type(v.x); + hi[h] = as_type(v.y); + ls[h] = (((sl[h] >> (4 * i)) & 0xf) | (((shh[h] >> (2 * j)) & 3) << 4)) - 32; + } + const int4 d = mma_k32(lo[0], lo[1], hi[0], hi[1], x.b0[i], x.b1[i], t); + for (int q = 0; q < 4; ++q) part[q] = fma(float(d[q] * ls[q >> 1]), x.d8[i][q & 1], part[q]); + } + for (int q = 0; q < 4; ++q) acc[q] = fma(dw[q >> 1], part[q], acc[q]); + } +} + +// The warp sums of the tile at row0 of a matrix with NWV warps a tile, into red[warp][row][column] (16 x 8 floats a +// warp): warp w's chunks and its terms as in dense_tc_one_block / dense_tc_tile_block / dense_tc_block +// (dense_tc.cu:519-540, 639-659, 375-406). +template +static inline void warp_sums(threadgroup float* red, device const uchar* w, int row0, int n_out, device const uint* x, + int n_in, int ncols, ushort sg, ushort nsg, ushort lane) { + const int g = lane >> 2; + const ushort t = lane & 3; + const int nchunk = n_in / 512, nb32 = n_in / 32; + const uint row_bytes = uint(n_in / 256) * uint(dtc_sb(TYPE)); + device const uchar* rowA = w + uint(min(row0 + g, n_out - 1)) * row_bytes; + device const uchar* rowB = w + uint(min(row0 + g + 8, n_out - 1)) * row_bytes; + device const uint* xg = x + 9u * uint(g) * uint(nb32); + device const uint* xc0 = x + 9u * uint(2 * t) * uint(nb32); + device const uint* xc1 = x + 9u * uint(2 * t + 1) * uint(nb32); + for (int vw = sg; vw < NWV; vw += nsg) { + const int hb = vw & 3; + float4 acc = 0.0f; + for (int c = vw >> 2; c < nchunk; c += NWV / 4) { + XFrag xf; + for (int k4 = 0; k4 < 4; ++k4) { + const int k = 16 * c + 4 * hb + k4; // the 32-value block of the columns + xf.b0[k4] = g < ncols ? uint(q8_w(xg, k, t)) : 0u; + xf.b1[k4] = g < ncols ? uint(q8_w(xg, k, 4 + t)) : 0u; + xf.d8[k4][0] = 2 * t < ncols ? q8_d(xc0, k) : 0.0f; + xf.d8[k4][1] = 2 * t + 1 < ncols ? q8_d(xc1, k) : 0.0f; + } + const uint off = uint(2 * c + (hb >> 1)) * uint(dtc_sb(TYPE)); + half_sb_terms(acc, rowA + off, rowB + off, hb & 1, t, xf); + } + threadgroup float* rw = red + 128 * vw; + rw[g * 8 + 2 * t] = acc[0]; + rw[g * 8 + 2 * t + 1] = acc[1]; + rw[(g + 8) * 8 + 2 * t] = acc[2]; + rw[(g + 8) * 8 + 2 * t + 1] = acc[3]; + } +} + +// A (row, column)'s value from the warp sums rr[128 * w] (dense_tc.md section 2): one (:667-681), tile and pair +// (:552-560, :919-928), s with KS 1 and 2 (:407-427). +template +static inline float tree(threadgroup const float* rr) { + if (ORDER == 0) { + float h[4]; + for (int q = 0; q < 4; ++q) { + float v = rr[128 * q]; + for (int j = 1; j < 6; ++j) v = v + rr[128 * (4 * j + q)]; + h[q] = v; + } + return (h[0] + h[1]) + (h[2] + h[3]); + } else if (ORDER == 1) { + return ((rr[0] + rr[512]) + (rr[128] + rr[640])) + ((rr[256] + rr[768]) + (rr[384] + rr[896])); + } else if (ORDER == 2) { + return ((rr[0] + rr[128]) + rr[256]) + rr[384]; + } else { + const float v = ((rr[0] + rr[128]) + rr[256]) + rr[384]; + return v + (((rr[512] + rr[640]) + rr[768]) + rr[896]); + } +} + +kernel void basalt_dense_tc(device const uchar* w [[buffer(0)]], device const uint* x [[buffer(1)]], + device float* y [[buffer(2)]], constant DtcParams& p [[buffer(3)]], + uint tg [[threadgroup_position_in_grid]], ushort lane [[thread_index_in_simdgroup]], + ushort sg [[simdgroup_index_in_threadgroup]], + ushort nsg [[simdgroups_per_threadgroup]]) { + threadgroup float red[DTC_NWV * 128]; + const int n_out = int(p.n_out), ncols = int(p.ncols), row0 = 16 * int(tg); + warp_sums(red, w, row0, n_out, x, int(p.n_in), ncols, sg, nsg, lane); + threadgroup_barrier(mem_flags::mem_threadgroup); + const int tid = 32 * int(sg) + int(lane), row = tid >> 3, col = tid & 7; + if (tid < 128 && col < ncols && row0 + row < n_out) + y[col * n_out + row0 + row] = cuda_nan(tree(red + row * 8 + col)); +} + +// dense_tc_pair (dense_tc.cu:704-931): two matrices of one input, the first matrix's tiles (n_out rows) then the +// second's (n_out1 rows), each in its own format with the tile order's arithmetic. +kernel void basalt_dense_tc_pair(device const uchar* w0 [[buffer(0)]], device const uchar* w1 [[buffer(1)]], + device const uint* x [[buffer(2)]], device float* y0 [[buffer(3)]], + device float* y1 [[buffer(4)]], constant DtcParams& p [[buffer(5)]], + uint tg [[threadgroup_position_in_grid]], ushort lane [[thread_index_in_simdgroup]], + ushort sg [[simdgroup_index_in_threadgroup]], + ushort nsg [[simdgroups_per_threadgroup]]) { + threadgroup float red[8 * 128]; + const int nt0 = (int(p.n_out) + 15) / 16, ncols = int(p.ncols); + const bool second = int(tg) >= nt0; + const int n_out = second ? int(p.n_out1) : int(p.n_out), row0 = 16 * (second ? int(tg) - nt0 : int(tg)); + if (second) + warp_sums(red, w1, row0, n_out, x, int(p.n_in), ncols, sg, nsg, lane); + else + warp_sums(red, w0, row0, n_out, x, int(p.n_in), ncols, sg, nsg, lane); + threadgroup_barrier(mem_flags::mem_threadgroup); + const int tid = 32 * int(sg) + int(lane), row = tid >> 3, col = tid & 7; + if (tid < 128 && col < ncols && row0 + row < n_out) + (second ? y1 : y0)[col * n_out + row0 + row] = cuda_nan(tree<1>(red + row * 8 + col)); +} diff --git a/kernels/common/basalt_dequant.metal b/kernels/common/basalt_dequant.metal new file mode 100644 index 00000000..4d8905a1 --- /dev/null +++ b/kernels/common/basalt_dequant.metal @@ -0,0 +1,89 @@ +// Copyright (c) 2023-2026 The ggml authors (MIT) +// Copyright (c) 2026 Jesús Gulfo (MIT) +// Adapted from basalt (jesdga95/basalt) src/kernels/cuda/iq_kernels.cu:2012-2069 and :2216-2220 +// @ b4c63b55754637f4c72ad53a0f791d425f71eb36 (MIT; third_party/NOTICE), which transcribes ggml-org/llama.cpp +// ggml/src/ggml-cuda/dequantize.cuh and convert.cu (and ggml/src/ggml-common.h's kvalues_iq4nl) @ +// 3cf03257f219afbe7334045ff7c6a06ac68c627d (MIT; third_party/NOTICE). +// +// basalt's dequantizers for the in-pack types iq_parity checks: dq_iq4_nl, dq_q3_k, dq_iq4_xs and dq_q2_0 under +// dequant_flat_kernel (threadgroup i = the 256-value superblock i, 32 threads, each thread writing basalt's +// values). GGUF blocks as the file stores them, in; fp32 values, out. Macro DQ_TYPE: the ggml type id (11 Q3_K, +// 20 IQ4_NL, 23 IQ4_XS, 42 Q2_0). Grid: n / 256 threadgroups of 32 threads. Needs basalt_fp.metal ahead of it. +// +// Arithmetic (docs/research/basalt-nvcc/dequant.md): iq_kernels.cu builds with nvcc's IEEE defaults, and each value +// is one or two correctly rounded multiplies, FMUL in SASS, no .FTZ: fl(h(d) * f(k)) (IQ4_NL, Q2_0) and +// fl(fl(h(d) * f(s - 32)) * f(k)) (Q3_K, IQ4_XS). Every factor is an fp16 value or a small integer, so no product is +// subnormal (the smallest nonzero one is 2^-24) and this GPU's flushing changes nothing; the products are not exact +// in general, so the rounding is the multiply's own, as CUDA's. A NaN (a NaN scale, or an infinite one times a zero +// factor) is stored as sm_120's (cuda_nan; docs/research/basalt-nvcc/nan.md). +#pragma STDC FP_CONTRACT OFF + +#ifndef DQ_TYPE +#define DQ_TYPE 11 +#endif + +constant char KVALUES_IQ4NL[16] = {-127, -104, -83, -65, -49, -35, -22, -10, 1, 13, 25, 38, 53, 69, 89, 113}; + +kernel void basalt_dequant_f32(device const ushort* vx [[buffer(0)]], device float* y [[buffer(1)]], + uint ibs [[threadgroup_position_in_grid]], ushort tid_ [[thread_index_in_threadgroup]]) { + const int tid = int(tid_); + device float* yy = y + 256u * ibs; +#if DQ_TYPE == 20 + // dq_iq4_nl (:2012-2023): 8 blocks of 18 bytes (d, qs[16]) per superblock + const int il = tid / 8, ib = tid % 8; + device const ushort* x = vx + 9u * (8u * ibs + uint(ib)); + device float* yo = yy + 32 * ib + 4 * il; + const float d = h2f(x[0]); + for (int j = 0; j < 4; ++j) { + const uint q = uint(w_u8(x, 2 + 4 * il + j)); + yo[j + 0] = cuda_nan(d * float(KVALUES_IQ4NL[q & 0xfu])); + yo[j + 16] = cuda_nan(d * float(KVALUES_IQ4NL[q >> 4])); + } +#elif DQ_TYPE == 11 + // dq_q3_k (:2025-2045): one 110-byte block (hmask[32], qs[64], scales[12], d) per superblock + device const ushort* x = vx + 55u * ibs; + for (int tt = tid; tt < 64; tt += 32) { + const int r = tt / 4, t2 = r / 2, is0 = r % 2; + const int l0 = 16 * is0 + 4 * (tt % 4); + const int n = t2 / 4, j = t2 - 4 * n; + const uint m = 1u << (4 * n + j); + const int is = 8 * n + 2 * j + is0; + const int shift = 2 * j; + const uint sc = 96u; // scales[] at byte 96 + const int us = is < 4 ? int((w_u8(x, sc + is) & 0xFu) | (((w_u8(x, sc + is + 8) >> 0) & 3u) << 4)) : + is < 8 ? int((w_u8(x, sc + is) & 0xFu) | (((w_u8(x, sc + is + 4) >> 2) & 3u) << 4)) : + is < 12 ? int((w_u8(x, sc + is - 8) >> 4) | (((w_u8(x, sc + is) >> 4) & 3u) << 4)) : + int((w_u8(x, sc + is - 8) >> 4) | (((w_u8(x, sc + is - 4) >> 6) & 3u) << 4)); + const float dl = h2f(x[54]) * float(us - 32); // (float) x->d * (us - 32) + device float* yo = yy + 128 * n + 32 * j; + for (int l = l0; l < l0 + 4; ++l) { + const int q = int((w_u8(x, 32u + uint(32 * n + l)) >> shift) & 3u) - ((w_u8(x, uint(l)) & m) ? 0 : 4); + yo[l] = cuda_nan(dl * float(q)); + } + } +#elif DQ_TYPE == 23 + // dq_iq4_xs (:2046-2057): one 136-byte block (d, scales_h, scales_l[4], qs[128]) per superblock + device const ushort* x = vx + 68u * ibs; + const int il = tid / 8, ib = tid % 8; + device float* yo = yy + 32 * ib + 4 * il; + const int ls = int(((w_u8(x, 4u + uint(ib / 2)) >> (4 * (ib % 2))) & 0xfu) | (((uint(x[1]) >> (2 * ib)) & 3u) << 4)); + const float d = h2f(x[0]) * float(ls - 32); + for (int j = 0; j < 4; ++j) { + const uint q = uint(w_u8(x, 8u + uint(16 * ib + 4 * il + j))); + yo[j + 0] = cuda_nan(d * float(KVALUES_IQ4NL[q & 0xfu])); + yo[j + 16] = cuda_nan(d * float(KVALUES_IQ4NL[q >> 4])); + } +#elif DQ_TYPE == 42 + // dq_q2_0 (:2058-2069): 4 blocks of 18 bytes (d, qs[16] of 2-bit codes) per superblock, value d * (code - 1) + const int b = tid / 8, part = tid % 8; + device const ushort* x = vx + 9u * (4u * ibs + uint(b)); + const float d = h2f(x[0]); + for (int j = 0; j < 8; ++j) { + const int i = part * 8 + j; + const int code = int((w_u8(x, 2u + uint(i / 4)) >> ((i % 4) * 2)) & 3u); + yy[b * 64 + i] = cuda_nan(d * float(code - 1)); + } +#else +#error "basalt_dequant: unsupported DQ_TYPE" +#endif +} diff --git a/kernels/common/basalt_experts.metal b/kernels/common/basalt_experts.metal new file mode 100644 index 00000000..5f20575f --- /dev/null +++ b/kernels/common/basalt_experts.metal @@ -0,0 +1,303 @@ +// Copyright (c) 2023-2026 The ggml authors (MIT) +// Copyright (c) 2026 Jesús Gulfo (MIT) +// Adapted from basalt (jesdga95/basalt) src/kernels/cuda/iq_kernels.cu:864-1014, :1087-1171, :1648-1921 and +// src/kernels/cuda/gu2.cuh:223-390 @ b4c63b55754637f4c72ad53a0f791d425f71eb36 (MIT; third_party/NOTICE), which adapt +// ggml-org/llama.cpp ggml/src/ggml-cuda/{vecdotq.cuh,quantize.cu} @ 3cf03257f219afbe7334045ff7c6a06ac68c627d (MIT; +// third_party/NOTICE). +// +// basalt's native_expert_grouped for Q2_0 gate/up and Q2_0 down (iq_kernels.cu:2553-2603): three dispatches in order, +// gate/up -> SwiGLU + q8_1 -> down. Needs basalt_fp.metal and basalt_q8_1.metal ahead of it. +// +// The plan (basalt's, read on the device): n_groups[0] groups; group g's expert blob starts at grp_ptr[g] (basalt's +// grp_ptr: a table of 64-bit GPU addresses, one a group, each 2-byte aligned and inside a resident buffer, so the +// blobs may sit in several buffers) and owns the entries [grp_start[g], grp_start[g + 1]); entry e reads token +// ent_tok[e]'s q8_1 row (n_embd / 32 blocks) and writes row ent_dst[e] of `out` (n_embd floats). A blob is basalt's +// native_expert_layout(42, 42, n_embd, n_ff): n_ff gate rows, n_ff up rows (n_embd / 64 Q2_0 blocks each, up at +// up_off) and n_embd down rows (n_ff / 64 blocks each, at down_off). +// Scratch, basalt's: gate and up (entry e's n_ff floats at e * n_ff) and hq (entry e's n_ff / 32 q8_1 blocks). +// +// Threadgroup row y takes groups y, y + gy, ... (gy = threadgroups in y; basalt's group stride: the result does not +// depend on gy). Every float step is the one nvcc compiles for iq_kernels.cu (nvcc's IEEE defaults; +// docs/research/basalt-nvcc/experts.md): fma() exactly at its FFMA sites, plain multiplies and adds elsewhere. No +// subnormal can reach the matrix-vector parts (every value is a multiple of 2^-48), so the GPU's operations are +// CUDA's there; the SwiGLU product can be subnormal and goes through ieee_mul, then the IEEE q8_1 store. A NaN is +// stored as sm_120's (cuda_nan, and the q8_1 store's cuda_nan_f16; docs/research/basalt-nvcc/nan.md). +// +// - basalt_expert_gu: gate/up. GU2 1: native_gu2_kernel<42> (gu2.cuh:338-357, n_embd 2560 only): 16 rows a +// threadgroup, rows 16b + 2w and + 1 on SIMD-group w. GU2 0: native_gu_multi_kernel<42> (iq_kernels.cu:1125-1171): +// 8 rows a threadgroup, one a SIMD-group. Grid (ceil(2 n_ff / rows), gy) threadgroups of 256. +// - basalt_expert_swiglu_q8_1: swiglu_q8_1_entries_pdl_kernel (gu2.cuh:375-390) over the call's own entries +// [grp_start[0], grp_start[n_groups]); grid ceil(cap_entries * n_ff / 256) threadgroups of 256, grid-strided. +// - basalt_expert_down: native_down_multi_kernel<42> (iq_kernels.cu:1688-1878). SUB16 1 (n_ff 640): 16 rows of 16 +// lanes a threadgroup, row_dot_20_sub16 on the entries' q8_1 rows staged in threadgroup memory; SUB16 0: 8 rows a +// threadgroup, one a SIMD-group, row_dot_multi from device memory. Grid (ceil(n_embd / rows), gy) of 256. +#pragma STDC FP_CONTRACT OFF + +#ifndef GU2 +#define GU2 0 +#endif +#ifndef SUB16 +#define SUB16 0 +#endif +#define GRP_NC 6 // entries a pass (iq_kernels.cu:1123) + +struct ExpertParams { uint n_embd; uint n_ff; uint gu_row; uint d_row; uint up_off; uint down_off; uint pad0; uint pad1; }; + +// Split<42>::apply into s: s = fma(fl(d2 * d8), f(sumi), s), the contracted `s += r.d2 * d8 * sumi` (FFMA in SASS) +template static inline float q2_0_acc(thread const Q20W& w, P x, int b, float s) { + return fma(w.d2 * q8_d(x, b), float(q2_0_sumi(w, x, b)), s); +} + +// row_dot_multi<42, NC> (iq_kernels.cu:898-919): one row against the n <= NC activations x + off[c] (offsets in q8_1 +// blocks), the whole SIMD-group: lane L takes calls k = L, L + 32, ... (block k / 2, half k % 2, q8_1 block k), then +// the butterfly. EXACT_N: every c < NC is an entry. +template +static inline void row_dot_multi(device const ushort* row, P x, thread const int* off, int n, int nb, int lane, + thread float* s) { + for (int c = 0; c < NC; ++c) s[c] = 0.0f; + for (int k = lane; k < nb * 2; k += 32) { + const Q20W w = q2_0_load(row + 9 * (k / 2), k % 2); + for (int c = 0; c < NC; ++c) + if (EXACT_N || c < n) s[c] = q2_0_acc(w, x + 9 * off[c], k, s[c]); + } + for (int c = 0; c < NC; ++c) + if (EXACT_N || c < n) s[c] = warp_sum(s[c]); +} + +// ---- gate / up --------------------------------------------------------------------------------------------------- + +#if GU2 +// gu2::rows2<42, NC> (gu2.cuh:254-300): rows r, r + 1 (row A at rowA, row B gu_row bytes after it) for the n <= NC +// entries from e. Lane L sums calls L and L + 32 of both rows, then call 64 + (L & 15) of row A (lanes 0..15) or of +// row B (lanes 16..31), whose scale product and integer sum move down 16 lanes before lanes 0..15 add them. +template +static inline void rows2(device const ushort* rowA, uint row_halves, int r, int e, int n, device const int* ent_tok, + device const uint* xq, device float* dst, int n_ff, int lane) { + device const ushort* rowB = rowA + row_halves; + device const uint* xc[NC]; + for (int c = 0; c < NC; ++c) xc[c] = xq + 9 * 80 * ent_tok[e + min(c, n - 1)]; // 2560 values: 80 blocks + float sA[NC], sB[NC]; + for (int c = 0; c < NC; ++c) sA[c] = sB[c] = 0.0f; + for (int it = 0; it < 2; ++it) { + const int k = lane + 32 * it; + const Q20W wa = q2_0_load(rowA + 9 * (k >> 1), k & 1); + const Q20W wb = q2_0_load(rowB + 9 * (k >> 1), k & 1); + for (int c = 0; c < NC; ++c) { + if (c < n) { + sA[c] = fma(wa.d2 * q8_d(xc[c], k), float(q2_0_sumi(wa, xc[c], k)), sA[c]); + sB[c] = fma(wb.d2 * q8_d(xc[c], k), float(q2_0_sumi(wb, xc[c], k)), sB[c]); + } + } + } + const int k2 = 64 + (lane & 15); + const Q20W w2 = q2_0_load((lane < 16 ? rowA : rowB) + 9 * (k2 >> 1), k2 & 1); + for (int c = 0; c < NC; ++c) { + if (c < n) { + const float d = w2.d2 * q8_d(xc[c], k2), f = float(q2_0_sumi(w2, xc[c], k2)); + const float dB = as_type(simd_shuffle_down(as_type(d), ushort(16))); + const float fB = as_type(simd_shuffle_down(as_type(f), ushort(16))); + if (lane < 16) { + sA[c] = fma(d, f, sA[c]); + sB[c] = fma(dB, fB, sB[c]); + } + sA[c] = warp_sum(sA[c]); + sB[c] = warp_sum(sB[c]); + if (lane == 2 * c) dst[(e + c) * n_ff + r] = cuda_nan(sA[c]); + if (lane == 2 * c + 1) dst[(e + c) * n_ff + r + 1] = cuda_nan(sB[c]); + } + } +} +#endif + +kernel void basalt_expert_gu(device const GrpPtr* grp_ptr [[buffer(1)]], + device const int* grp_start [[buffer(2)]], device const int* n_groups [[buffer(3)]], + device const int* ent_tok [[buffer(4)]], device const uint* xq [[buffer(5)]], + device float* gate [[buffer(6)]], device float* up [[buffer(7)]], + constant ExpertParams& p [[buffer(8)]], uint2 tg [[threadgroup_position_in_grid]], + uint2 ntg [[threadgroups_per_grid]], ushort lane [[thread_index_in_simdgroup]], + ushort sg [[simdgroup_index_in_threadgroup]]) { + const int ng = n_groups[0]; + if (int(tg.y) >= ng) return; + const int n_ff = int(p.n_ff); +#if GU2 + const int row = int(tg.x) * 16 + 2 * int(sg); // rows row, row + 1: both gate or both up + if (row >= 2 * n_ff) return; + const bool is_up = row >= n_ff; + const int r = is_up ? row - n_ff : row; + const ulong w_off = ulong(is_up ? p.up_off : 0u) + ulong(r) * p.gu_row; + device float* dst = is_up ? up : gate; + for (int g = int(tg.y); g < ng; g += int(ntg.y)) { + device const ushort* wr = grp_ptr[g].p + w_off / 2; + const int e1 = grp_start[g + 1]; + for (int e = grp_start[g]; e < e1;) { // gu2::pair (gu2.cuh:303-330) + const int n = e1 - e; + if (n == 1) { + rows2<1>(wr, p.gu_row / 2, r, e, 1, ent_tok, xq, dst, n_ff, lane); + e += 1; + } else if (n == 2) { + rows2<2>(wr, p.gu_row / 2, r, e, 2, ent_tok, xq, dst, n_ff, lane); + e += 2; + } else if (n == 3) { + rows2<3>(wr, p.gu_row / 2, r, e, 3, ent_tok, xq, dst, n_ff, lane); + e += 3; + } else { + const int m = min(n, GRP_NC); + rows2(wr, p.gu_row / 2, r, e, m, ent_tok, xq, dst, n_ff, lane); + e += m; + } + } + } +#else + const int row = int(tg.x) * 8 + int(sg); + if (row >= 2 * n_ff) return; + const bool is_up = row >= n_ff; + const int r = is_up ? row - n_ff : row; + const ulong w_off = ulong(is_up ? p.up_off : 0u) + ulong(r) * p.gu_row; + const int nb = int(p.n_embd) / 64, xb = int(p.n_embd) / 32; + device float* dst = is_up ? up : gate; + for (int g = int(tg.y); g < ng; g += int(ntg.y)) { + device const ushort* wr = grp_ptr[g].p + w_off / 2; + const int e0 = grp_start[g], e1 = grp_start[g + 1]; + for (int e = e0; e < e1; e += GRP_NC) { + const int n = min(GRP_NC, e1 - e); + if (n == 1) { + const int off1[1] = {ent_tok[e] * xb}; + float s1[1]; + row_dot_multi<1, true>(wr, xq, off1, 1, nb, lane, s1); + if (lane == 0) dst[e * n_ff + r] = cuda_nan(s1[0]); + } else if (n == 2) { + const int off2[2] = {ent_tok[e] * xb, ent_tok[e + 1] * xb}; + float s2[2]; + row_dot_multi<2, true>(wr, xq, off2, 2, nb, lane, s2); + if (lane < 2) dst[(e + int(lane)) * n_ff + r] = cuda_nan(s2[lane]); + } else { + int off[GRP_NC]; + for (int c = 0; c < GRP_NC; ++c) off[c] = ent_tok[e + min(c, n - 1)] * xb; + float s[GRP_NC]; + row_dot_multi(wr, xq, off, n, nb, lane, s); + for (int c = 0; c < GRP_NC; ++c) + if (c < n && int(lane) == c) dst[(e + c) * n_ff + r] = cuda_nan(s[c]); + } + } + } +#endif +} + +// ---- SwiGLU + q8_1 ----------------------------------------------------------------------------------------------- + +// h = __fmul_rn(g / (1.0f + __expf(-g)), up[i]), then q8_1_store (gu2.cuh:386-388); n_ff is a multiple of 32, so a +// SIMD-group is one q8_1 block and the bounds are SIMD-group uniform. +kernel void basalt_expert_swiglu_q8_1(device const float* gate [[buffer(0)]], device const float* up [[buffer(1)]], + device const int* grp_start [[buffer(2)]], device const int* n_groups [[buffer(3)]], + device uchar* hq [[buffer(4)]], constant ExpertParams& p [[buffer(5)]], + uint tg [[threadgroup_position_in_grid]], uint ntg [[threadgroups_per_grid]], + uint tid [[thread_index_in_threadgroup]]) { + const uint lo = uint(grp_start[0]) * p.n_ff, hi = uint(grp_start[n_groups[0]]) * p.n_ff; + for (uint i = lo + tg * 256u + tid; i < hi; i += ntg * 256u) { + const float g = gate[i]; + const float s = g / (1.0f + expf_neg(g)); // div.rn.f32: correctly rounded + q8_1_store_ieee(ieee_mul(s, up[i]), hq, i); + } +} + +// ---- down -------------------------------------------------------------------------------------------------------- + +#if SUB16 +// row_dot_20_sub16<42, NC> (iq_kernels.cu:980-1014): 20 calls on 16 lanes, t = lane & 15: call t, then call t + 16 +// for t < 4 into s16, s + s16, then the butterfly 8, 4, 2, 1 inside the 16 lanes (row_dot_multi's tree on 32 lanes +// with lanes 20..31 at zero). +template +static inline void row_dot_20_sub16(device const ushort* row, threadgroup const uint* x, thread const int* off, int n, + int t, thread float* s) { + for (int c = 0; c < NC; ++c) s[c] = 0.0f; + { + const Q20W w = q2_0_load(row + 9 * (t / 2), t % 2); + for (int c = 0; c < NC; ++c) + if (EXACT_N || c < n) s[c] = q2_0_acc(w, x + 9 * off[c], t, s[c]); + } + float s16[NC]; + for (int c = 0; c < NC; ++c) s16[c] = 0.0f; + if (t < 4) { + const int k = t + 16; + const Q20W w = q2_0_load(row + 9 * (k / 2), k % 2); + for (int c = 0; c < NC; ++c) + if (EXACT_N || c < n) s16[c] = q2_0_acc(w, x + 9 * off[c], k, s16[c]); + } + for (int c = 0; c < NC; ++c) { + if (EXACT_N || c < n) { + s[c] = s[c] + s16[c]; // __fadd_rn + for (ushort o = 8; o > 0; o >>= 1) s[c] = s[c] + shfl_xor(s[c], o); + } + } +} +#endif + +kernel void basalt_expert_down(device const GrpPtr* grp_ptr [[buffer(1)]], + device const int* grp_start [[buffer(2)]], device const int* n_groups [[buffer(3)]], + device const int* ent_dst [[buffer(4)]], device const uint* hq [[buffer(5)]], + device float* out [[buffer(6)]], constant ExpertParams& p [[buffer(7)]], + uint2 tg [[threadgroup_position_in_grid]], uint2 ntg [[threadgroups_per_grid]], + ushort tid [[thread_index_in_threadgroup]], ushort lane [[thread_index_in_simdgroup]], + ushort sg [[simdgroup_index_in_threadgroup]]) { + const int ng = n_groups[0]; + if (int(tg.y) >= ng) return; + const int n_embd = int(p.n_embd), hb = int(p.n_ff) / 32; +#if SUB16 + threadgroup uint s_hq[GRP_NC * 20 * 9]; // six entries' 20 q8_1 blocks (iq_kernels.cu:1726) + const int r = int(tg.x) * 16 + int(tid >> 4), t = int(tid & 15); + const bool valid_r = r < n_embd; + const ulong w_off = ulong(p.down_off) + ulong(valid_r ? r : 0) * p.d_row; + for (int g = int(tg.y); g < ng; g += int(ntg.y)) { + device const ushort* wr = grp_ptr[g].p + w_off / 2; + const int e0 = grp_start[g], e1 = grp_start[g + 1]; + for (int e = e0; e < e1; e += GRP_NC) { + const int n = min(GRP_NC, e1 - e); + device const uint* src = hq + 9 * 20 * e; + const int words = n * (20 * 9); + threadgroup_barrier(mem_flags::mem_threadgroup); + for (int i = int(tid); i < words; i += 256) s_hq[i] = src[i]; + threadgroup_barrier(mem_flags::mem_threadgroup); + if (valid_r) { + if (n == 1) { + const int off1[1] = {0}; + float s1[1]; + row_dot_20_sub16<1, true>(wr, s_hq, off1, 1, t, s1); + if (t == 0) out[ent_dst[e] * n_embd + r] = cuda_nan(s1[0]); + } else if (n == 2) { + const int off2[2] = {0, 20}; + float s2[2]; + row_dot_20_sub16<2, true>(wr, s_hq, off2, 2, t, s2); + if (t < 2) out[ent_dst[e + t] * n_embd + r] = cuda_nan(t == 0 ? s2[0] : s2[1]); + } else { + int off[GRP_NC]; + for (int c = 0; c < GRP_NC; ++c) off[c] = min(c, n - 1) * 20; + float s[GRP_NC]; + row_dot_20_sub16(wr, s_hq, off, n, t, s); + for (int c = 0; c < GRP_NC; ++c) + if (c < n && t == c) out[ent_dst[e + c] * n_embd + r] = cuda_nan(s[c]); + } + } + } + } +#else + const int r = int(tg.x) * 8 + int(sg); + const bool valid_r = r < n_embd; + const ulong w_off = ulong(p.down_off) + ulong(valid_r ? r : 0) * p.d_row; + const int nb = int(p.n_ff) / 64; + for (int g = int(tg.y); g < ng; g += int(ntg.y)) { + device const ushort* wr = grp_ptr[g].p + w_off / 2; + const int e0 = grp_start[g], e1 = grp_start[g + 1]; + if (valid_r) { + for (int e = e0; e < e1; e += GRP_NC) { + const int n = min(GRP_NC, e1 - e); + int off[GRP_NC]; + for (int c = 0; c < GRP_NC; ++c) off[c] = (e + min(c, n - 1)) * hb; + float s[GRP_NC]; + row_dot_multi(wr, hq, off, n, nb, lane, s); + for (int c = 0; c < GRP_NC; ++c) + if (c < n && int(lane) == c) out[ent_dst[e + c] * n_embd + r] = cuda_nan(s[c]); + } + } + } +#endif +} diff --git a/kernels/common/basalt_fp.metal b/kernels/common/basalt_fp.metal new file mode 100644 index 00000000..e9db9808 --- /dev/null +++ b/kernels/common/basalt_fp.metal @@ -0,0 +1,255 @@ +// Copyright (c) 2023-2026 The ggml authors (MIT) +// Copyright (c) 2026 Jesús Gulfo (MIT) +// Adapted from basalt (jesdga95/basalt) src/kernels/cuda/native_mmvq.cu, src/kernels/cuda/iq_kernels.cu, +// src/kernels/cuda/q5k_head.cu, include/basalt/kernels/dp4a.hpp and include/basalt/kernels/q8_1_finite.hpp +// @ b4c63b55754637f4c72ad53a0f791d425f71eb36 (MIT; third_party/NOTICE), +// which adapt ggml-org/llama.cpp ggml/src/ggml-cuda/{quantize.cu,vecdotq.cuh,mmvq.cu,common.cuh} @ +// 3cf03257f219afbe7334045ff7c6a06ac68c627d (MIT; third_party/NOTICE). +// +// The arithmetic helpers every basalt port kernel shares. Each kernel source starts with this file (and the pragma +// below), so a multiply feeding an add never fuses unless fma() is written: the fusion, flush-to-zero and division +// sequence nvcc compiles for basalt's sm_120 kernels are written out explicitly, as recorded per site in +// docs/research/basalt-nvcc/matvec.md. +// +// - ftz(x): a subnormal becomes the zero of its sign; every other value keeps its bits. Integer operations only, so +// it means the same on any GPU, whatever the hardware does with subnormals. +// - add_ftz, mul_ftz, fma_ftz, max_ftz, abs_ftz: CUDA's FADD.FTZ, FMUL.FTZ, FFMA.FTZ, FMNMX.FTZ and the .FTZ absolute +// value: the operation on flushed inputs, correctly rounded (to nearest even on the float32 grid, subnormals +// included: PTX's "rounded to single precision"), then a subnormal result flushed. This GPU's multiply and fma flush +// on the exact value instead, before rounding: an exact result in [2^-126 - 2^-150, 2^-126), which rounds up to the +// smallest normal 2^-126, comes back as the zero of its sign (tests/kernels/test_basalt_platform.py). So fma_ftz +// checks a zero from nonzero factors against the exact value (fma_ftz_min_normal), and mul_ftz is fma_ftz(a, b, -0) +// (a * b + -0 is a * b, zeros included). A sum below 2^-126 is exact, so add_ftz needs no check, and no reciprocal +// of a float lies in that interval. max_ftz needs its explicit flush: this GPU's fmax compares a subnormal as zero +// but returns it unflushed. On +0 against -0 it returns the second operand (CUDA's choice there is not checked); the +// port takes max_ftz of absolute values only. +// - rcp_ftz(x): stands where SASS has MUFU.RCP (an approximate reciprocal NVIDIA does not specify bit for bit): the +// correctly rounded 1 / x of the flushed input, flushed. +// - warp_sum_ftz / warp_max_ftz: basalt's warp_sum and warp_max (native_mmvq.cu:130-144), XOR butterflies with offsets +// 16, 8, 4, 2, 1 on the value's bits (simd_sum documents no order and is never used); warp_sum: the IEEE-built +// files' butterfly (iq_kernels.cu:545-549), plain adds. +// - expf_neg: __expf(-g) as an IEEE-built file compiles it (docs/research/basalt-nvcc/experts.md). +// - load_int_b2, dp4a, byte_perm, vsubss4, vsub4: CUDA's two 16-bit loads, __dp4a, __byte_perm (3-bit selectors), +// __vsubss4 and __vsub4 as exact integer arithmetic; iq4_table_lookup: the IQ4 codebook's two-stage byte lookup +// (native_mmvq.cu:441-457; dense_tc.cu:79-84 computes the same bytes). +// - h2f, f16_bits: fp16 bits to fp32 and back; GrpPtr: an address in basalt's grp_ptr table. +// - cuda_nan, cuda_nan_f16: a stored float's or fp16 value's NaN as sm_120's, 0x7fffffff and 0x7fff, where this GPU's +// arithmetic gives 0x7fc00000 and its half() 0x7e00 (docs/research/basalt-nvcc/nan.md); every other value keeps +// its bits. Each port kernel applies them at the stores a NaN can reach. +// - q8_d, q8_s, q8_w: a q8_1 block's scale, sum and code words; q2_0_load, q2_0_sumi: the Q2_0 decode and its exact +// integer dot, shared by native_mmvq and the routed experts; q5k_load, q5k_dot: the Q5_K decode and dot, shared by +// native_mmvq and the Q5_K head. +// - expf_ftz: __expf(x) in a --use_fast_math file (docs/research/basalt-nvcc/q5k_head.md section 2). +#pragma STDC FP_CONTRACT OFF + +static inline float ftz(float x) { + const uint b = as_type(x); + return (b & 0x7f800000u) == 0u ? as_type(b & 0x80000000u) : x; +} +static inline float add_ftz(float a, float b) { return ftz(ftz(a) + ftz(b)); } + +// fma_ftz's check where the hardware fma of flushed operands, a and b nonzero, gave a zero r. The exact v = a * b + c +// in units of 2^-150: |a * b| = q * 2^k (q the 48-bit product of the significands), |c| = mc * 2^ec (ec its exponent +// field; 0 for a zero c). v rounds to +-2^-126 exactly when floor(|v|) is 2^24 - 1 units: from the tie 2^-126 - 2^-150 +// (2^-126 is the even neighbour) up to 2^-126. With k > 0, v is a multiple of 2^-149; with ec > 25 (and k <= 0), |v| is +// above 2^-102: either way r is v's flushed value. +static inline float fma_ftz_min_normal(float a, float b, float c, float r) { + const uint ua = as_type(a), ub = as_type(b), uc = as_type(c); + const int k = int((ua >> 23) & 0xffu) + int((ub >> 23) & 0xffu) - 150; + const uint ec = (uc >> 23) & 0xffu; + if (k > 0 || ec > 25u) return r; + const ulong q = ulong((ua & 0x7fffffu) | 0x800000u) * ulong((ub & 0x7fffffu) | 0x800000u); + const uint s = uint(-k); // 0 <= s <= 148 + const ulong p = s < 64u ? q >> s : 0ul; // floor(|a * b|) + const bool f = s != 0u && (s >= 64u || (q << (64u - s)) != 0ul); // |a * b| has a fraction of a unit + long n = ((ua ^ ub) >> 31) != 0u ? -long(p) - long(f) : long(p); // floor(a * b) + if (ec != 0u) { // c: whole units + const long m = long((uc & 0x7fffffu) | 0x800000u) << ec; + n += (uc >> 31) != 0u ? -m : m; + } + const long fl = n < 0 ? -n - long(f) : n; // floor(|v|); n < 0 exactly when v < 0 + return fl == long(0xffffff) ? as_type((n < 0 ? 0x80000000u : 0u) | 0x00800000u) : r; +} +static inline float fma_ftz(float a, float b, float c) { + a = ftz(a); + b = ftz(b); + c = ftz(c); + const float r = ftz(fma(a, b, c)); + return r != 0.0f || a == 0.0f || b == 0.0f ? r : fma_ftz_min_normal(a, b, c, r); +} +static inline float mul_ftz(float a, float b) { return fma_ftz(a, b, -0.0f); } +static inline float max_ftz(float a, float b) { return fmax(ftz(a), ftz(b)); } +static inline float abs_ftz(float x) { return ftz(fabs(x)); } +static inline float rcp_ftz(float x) { return ftz(1.0f / ftz(x)); } + +static inline float shfl_xor(float x, ushort o) { return as_type(simd_shuffle_xor(as_type(x), o)); } + +static inline float warp_sum_ftz(float x) { + for (ushort o = 16; o > 0; o >>= 1) x = add_ftz(x, shfl_xor(x, o)); + return x; +} +static inline float warp_max_ftz(float x) { + for (ushort o = 16; o > 0; o >>= 1) x = max_ftz(x, shfl_xor(x, o)); + return x; +} +// basalt's warp_sum in an IEEE-built file (iq_kernels.cu:545-549): the same butterfly, plain FADD. The port uses it +// only where no subnormal can reach the sum (docs/research/basalt-nvcc/experts.md), so the GPU's add is CUDA's. +static inline float warp_sum(float x) { + for (ushort o = 16; o > 0; o >>= 1) x = x + shfl_xor(x, o); + return x; +} + +// CUDA's __expf(-g) in an IEEE-built file: ex2.approx.f32 of fl(g * -log2 e) (experts.md section 2). MUFU.EX2 has no +// documented Metal counterpart; the contract maps it to fast::exp2 of the same product. +static inline float expf_neg(float g) { return fast::exp2(g * as_type(0xBFB8AA3Bu)); } +// CUDA's __expf(x) in a --use_fast_math file: ex2.approx.ftz.f32 of fl(x * log2 e), FMUL.FTZ then MUFU.EX2 +// (q5k_head.md section 2); fast::exp2 as in expf_neg, its result flushed as .ftz flushes. +static inline float expf_ftz(float x) { return ftz(fast::exp2(mul_ftz(x, as_type(0x3FB8AA3Bu)))); } + +// fp16 field to fp32 (exact): CUDA's __half2float / __low2float, HADD2.F32 in SASS. +static inline float h2f(ushort h) { return float(as_type(h)); } + +// fp32 to fp16 bits, round to nearest even: a finite overflow to infinity, fp16 subnormals kept, an fp32 subnormal to +// the zero of its sign (basalt's f16_from_f32, f16_bits.hpp:36-65, and __float2half; +// docs/research/basalt-nvcc/s2_experts.md section 1). A NaN's payload is the GPU's. +static inline ushort f16_bits(float x) { return as_type(half(x)); } + +// x with a NaN as sm_120's: every FADD, FMUL, FFMA, MUFU.RCP, MUFU.EX2 and div.rn.f32 that makes or passes a NaN, and +// FMNMX of two NaNs, gives the canonical 0x7fffffff, where this GPU's arithmetic gives 0x7fc00000 and fabs, negation, +// round and fmax keep an operand's bits (nan.md). Applied to a float the kernel stores. +static inline float cuda_nan(float x) { + return (as_type(x) & 0x7fffffffu) > 0x7f800000u ? as_type(0x7fffffffu) : x; +} +// fp16 bits h with a NaN as sm_120's hardware conversion stores it: __float2half (F2F.F16.F32, F2FP.F16.F32.PACK_AB) +// takes every NaN to 0x7fff, where half() gives 0x7e00 (nan.md). Applied to f16_bits' result where basalt converts +// with __float2half; basalt's software f16_from_f32 gives sign | 0x7E00 instead. +static inline ushort cuda_nan_f16(ushort h) { return (h & 0x7fffu) > 0x7c00u ? ushort(0x7fffu) : h; } + +// one entry of basalt's grp_ptr table: a blob's 64-bit GPU address (MSL takes no pointer-to-pointer kernel argument) +struct GrpPtr { device const ushort* p; }; + +// native_mmvq.cu:353-358: a 32-bit word of a 2-byte aligned block, as two 16-bit loads combined little-endian. +static inline int load_int_b2(device const ushort* p, int i32) { + return int(uint(p[2 * i32]) | (uint(p[2 * i32 + 1]) << 16)); +} + +// byte `byte` of a 2-byte aligned block, through a 16-bit load (little-endian) +static inline uchar w_u8(device const ushort* blk, uint byte) { return uchar(blk[byte >> 1] >> (8u * (byte & 1u))); } + +// __dp4a(a, b, c): c plus the four products of sign-extended bytes (no sum here comes near 2^31). +static inline int dp4a(int a, int b, int c) { + const char4 x = as_type(a), y = as_type(b); + return c + int(x.x) * int(y.x) + int(x.y) * int(y.y) + int(x.z) * int(y.z) + int(x.w) * int(y.w); +} + +// __byte_perm(x, y, s): byte n of the result is byte s<4n+2:4n> of {y:x}; the selectors' fourth bits and the upper +// 16 bits of s are not used (CUDA Math API). +static inline int byte_perm(int x, int y, int s) { + uint r = 0u; + for (uint n = 0u; n < 4u; ++n) { + const uint sel = (uint(s) >> (4u * n)) & 7u; + const uint src = sel < 4u ? uint(x) : uint(y); + r |= ((src >> (8u * (sel & 3u))) & 0xffu) << (8u * n); + } + return int(r); +} + +// __vsubss4(a, b): per signed byte a - b, saturated to [-128, 127]. +static inline int vsubss4(int a, int b) { + const int4 d = clamp(int4(as_type(a)) - int4(as_type(b)), int4(-128), int4(127)); + return as_type(char4(d)); +} + +// __vsub4(a, b): per byte a - b, modulo 256. +static inline int vsub4(int a, int b) { return as_type(as_type(a) - as_type(b)); } + +// The IQ4 codebook as four words and its two-stage byte lookup: eight 4-bit codes q4 to their int8 values, .x the low +// nibbles', .y the high nibbles' (native_mmvq.cu:441-457; dense_tc.cu:56-57, 79-84 with the same table). +static inline int2 iq4_table_lookup(int q4) { + const int t0 = int(0xbfad9881u), t1 = int(0xf6eaddcfu), t2 = int(0x26190d01u), t3 = int(0x71594535u); + const int sel = int(0x32103210u | ((uint(q4) & 0x88888888u) >> 1)); + int tmp[2]; + for (int i = 0; i < 2; ++i) { + const int shift = 16 * i; + const int low = byte_perm(t0, t1, q4 >> shift); + const int high = byte_perm(t2, t3, q4 >> shift); + tmp[i] = byte_perm(low, high, int(uint(sel) >> shift)); + } + return int2(byte_perm(tmp[0], tmp[1], 0x6420), byte_perm(tmp[0], tmp[1], 0x7531)); +} + +// q8_1 block b of an activation row (basalt_q8_1.metal's layout): 9 words, word 0 the fp16 pair (d, s), words 1..8 +// the codes. P is a device or threadgroup pointer to the row's words. +template static inline float q8_d(P x, int b) { return h2f(ushort(x[9 * b] & 0xffffu)); } +template static inline float q8_s(P x, int b) { return h2f(ushort(x[9 * b] >> 16)); } +template static inline int q8_w(P x, int b, int k) { return int(x[9 * b + 1 + k]); } + +// Q2_0 (18-byte blocks: fp16 d, qs[16] of 2-bit codes, value = d * (code - 1)): basalt's Split<42> / Q20Traits +// (iq_kernels.cu:864-895, native_mmvq.cu:976-1007). q2_0_load decodes the 32-value half iqs of the block at blk +// (qs read as int16: the block is only 2-byte aligned), each code c as the byte c - 1 through __byte_perm; +// q2_0_sumi is the exact integer dot with q8_1 block b of x. +struct Q20W { int qx[4]; int qy[4]; float d2; }; +static inline Q20W q2_0_load(device const ushort* blk, int iqs) { + Q20W r; + r.d2 = h2f(blk[0]); + for (int j = 0; j < 4; ++j) { + const int q = int(short(blk[1 + iqs * 4 + j])); + const int qe = byte_perm(0x020100ff, 0x020100ff, q >> 0); + const int qo = byte_perm(0x020100ff, 0x020100ff, q >> 2); + r.qx[j] = byte_perm(qe, qo, 0x5140); + r.qy[j] = byte_perm(qe, qo, 0x7362); + } + return r; +} +template static inline int q2_0_sumi(thread const Q20W& r, P x, int b) { + int sumi = 0; + for (int j = 0; j < 4; ++j) { + sumi = dp4a(q8_w(x, b, j * 2), r.qx[j], sumi); + sumi = dp4a(q8_w(x, b, j * 2 + 1), r.qy[j], sumi); + } + return sumi; +} + +// Q5_K (176-byte blocks: fp16 d and dmin, scales[12], qh[32], qs[128]): native_mmvq's Q5KTraits load and +// q5_q8_dot_impl (native_mmvq.cu:180-240, 897-937), which the Q5_K head repeats (q5k_head.cu:41-106). q5k_load +// decodes sub-position iqs of the block at blk once (qs and qh read as int16 pairs: the block is 2-byte aligned); +// q5k_dot is its dot with q8_1 blocks bq8_offset and bq8_offset + 1 of x (x at the block's first q8_1 block): +// dm.x * sumf_d - dm.y * sumf_m as ptxas compiles it, the dmin product rounded and the d product fused +// (docs/research/basalt-nvcc/matvec.md section 5; q5k_head.md section 1). The caller adds the result. +struct Q5KW { int vl[2]; int vh[2]; uchar sc[2]; uchar m[2]; float dmx, dmy; int bq8_offset; }; +static inline Q5KW q5k_load(device const ushort* blk, int iqs) { + Q5KW r; + r.bq8_offset = 2 * ((iqs / 2) / 4); + const int ql = (48 + 16 * r.bq8_offset + 4 * ((iqs / 2) % 4)) / 4; + r.vl[0] = load_int_b2(blk, ql); + r.vl[1] = load_int_b2(blk, ql + 4); + const int qh = (16 + 4 * ((iqs / 2) % 4)) / 4; + r.vh[0] = load_int_b2(blk, qh) >> r.bq8_offset; + r.vh[1] = load_int_b2(blk, qh + 4) >> r.bq8_offset; + const int j = r.bq8_offset / 2; + const int jm = j & 1; + const uint s0 = blk[2 + jm], s2 = blk[2 + jm + 2], s4 = blk[2 + jm + 4]; + const uint hi = uint(-int(j >= 2)); + const uint aux0 = ((s0 & 0x3f3fu) & ~hi) | ((((s4 >> 0) & 0x0f0fu) | ((s0 & 0xc0c0u) >> 2)) & hi); + const uint aux1 = ((s2 & 0x3f3fu) & ~hi) | ((((s4 >> 4) & 0x0f0fu) | ((s2 & 0xc0c0u) >> 2)) & hi); + r.sc[0] = uchar(aux0); r.sc[1] = uchar(aux0 >> 8); + r.m[0] = uchar(aux1); r.m[1] = uchar(aux1 >> 8); + r.dmx = h2f(blk[0]); + r.dmy = h2f(blk[1]); + return r; +} +static inline float q5k_dot(thread const Q5KW& r, device const uint* x, int iqs) { + float sumf_d = 0.0f, sumf_m = 0.0f; + for (int i = 0; i < 2; ++i) { + const int b = r.bq8_offset + i; + const float d8 = q8_d(x, b); + const int u0 = q8_w(x, b, (iqs / 2) % 4), u1 = q8_w(x, b, (iqs / 2) % 4 + 4); + const int v0i = ((r.vl[0] >> (4 * i)) & 0x0f0f0f0f) | (((r.vh[0] >> i) << 4) & 0x10101010); + const int v1i = ((r.vl[1] >> (4 * i)) & 0x0f0f0f0f) | (((r.vh[1] >> i) << 4) & 0x10101010); + const int dot1 = dp4a(v0i, u0, dp4a(v1i, u1, 0)); + const int dot2 = dp4a(0x01010101, u0, dp4a(0x01010101, u1, 0)); + sumf_d = fma_ftz(d8, float(dot1 * int(r.sc[i])), sumf_d); + sumf_m = fma_ftz(d8, float(dot2 * int(r.m[i])), sumf_m); + } + return fma_ftz(r.dmx, sumf_d, -mul_ftz(r.dmy, sumf_m)); +} diff --git a/kernels/common/basalt_mmvf.metal b/kernels/common/basalt_mmvf.metal new file mode 100644 index 00000000..16cd3461 --- /dev/null +++ b/kernels/common/basalt_mmvf.metal @@ -0,0 +1,70 @@ +// Copyright (c) 2023-2026 The ggml authors (MIT) +// Copyright (c) 2026 Jesús Gulfo (MIT) +// Adapted from basalt (jesdga95/basalt) src/kernels/cuda/native_bf16.cu:37-135 +// @ b4c63b55754637f4c72ad53a0f791d425f71eb36 (MIT; third_party/NOTICE), which adapts ggml-org/llama.cpp +// ggml/src/ggml-cuda/{mmvf.cu,common.cuh} @ 3cf03257f219afbe7334045ff7c6a06ac68c627d (MIT; third_party/NOTICE). +// +// basalt's BF16-weight, fp32-activation GEMV: y[k * ldy + o] = row o of a BF16 matrix (n_out rows of n_in values, +// row-major, n_in even) times the fp32 activation row x + k * ldx, for k < n_tok. Needs basalt_fp.metal ahead of it. +// +// One kernel for basalt's one-row kernel (NT 1: bf16_f32_mmvf_kernel) and its multi-row kernel (NT 4 or 8: +// bf16_f32_mmvf_multi_kernel), which give every output the same operations in the same order (native_bf16.cu:75-77): +// thread t of threadgroup o takes the bf16 pairs t, t + BLOCK, ... of row o in order and, for each row k < n_tok of x, +// adds fma(bf(w_lo), x.x, acc) then fma(bf(w_hi), x.y, acc) from +0; each SIMD-group reduces with basalt's XOR +// butterfly; with more than one SIMD-group, lane 0 of each stores its sum into a zeroed 32-slot array and SIMD-group 0 +// runs the butterfly over all 32 slots; thread 0 writes. The float steps are the ones nvcc compiles +// (docs/research/basalt-nvcc/bf16.md): FFMA.FTZ and FADD.FTZ, written as fma_ftz and add_ftz. A NaN is stored as +// sm_120's (cuda_nan; docs/research/basalt-nvcc/nan.md). +// +// Macros: BLOCK threads per threadgroup (basalt's mmvf_block_size: 32, 64, ..., 256); NT accumulator rows (1, 4 or +// 8). monolith/kernels.py's basalt_mmvf_macros picks both as basalt's launchers do. Grid: n_out threadgroups of BLOCK +// threads. +#pragma STDC FP_CONTRACT OFF + +#ifndef BLOCK +#define BLOCK 256 +#endif +#ifndef NT +#define NT 1 +#endif + +struct MmvfParams { uint n_in; uint n_out; uint n_tok; uint ldx; uint ldy; uint pad0; uint pad1; uint pad2; }; + +kernel void basalt_mmvf(device const float2* x [[buffer(0)]], device const uint* w [[buffer(1)]], + device float* y [[buffer(2)]], constant MmvfParams& p [[buffer(3)]], + uint o [[threadgroup_position_in_grid]], ushort lane [[thread_index_in_simdgroup]], + ushort sg [[simdgroup_index_in_threadgroup]]) { + const uint t = 32u * uint(sg) + uint(lane); // basalt's threadIdx.x: warp t / 32, lane t % 32 + const uint pairs = p.n_in / 2u; + device const uint* row = w + ulong(o) * pairs; // row o as words of two bf16 values, low half first +#if BLOCK > 32 + threadgroup float partials[NT][32]; + if (sg == 0) + for (int k = 0; k < NT; ++k) partials[k][lane] = 0.0f; + threadgroup_barrier(mem_flags::mem_threadgroup); +#endif + float acc[NT]; + for (int k = 0; k < NT; ++k) acc[k] = 0.0f; + for (uint pair = t; pair < pairs; pair += BLOCK) { + const uint word = row[pair]; + const float w0 = as_type(word << 16), w1 = as_type(word & 0xffff0000u); + for (uint k = 0; k < NT; ++k) { + if (k < p.n_tok) { + const float2 in = x[ulong(k) * (p.ldx / 2u) + pair]; + acc[k] = fma_ftz(w0, in.x, acc[k]); + acc[k] = fma_ftz(w1, in.y, acc[k]); + } + } + } + for (int k = 0; k < NT; ++k) acc[k] = warp_sum_ftz(acc[k]); +#if BLOCK > 32 + if (lane == 0) + for (int k = 0; k < NT; ++k) partials[k][sg] = acc[k]; + threadgroup_barrier(mem_flags::mem_threadgroup); + if (sg != 0) return; + for (int k = 0; k < NT; ++k) acc[k] = warp_sum_ftz(partials[k][lane]); +#endif + if (t == 0) + for (uint k = 0; k < NT; ++k) + if (k < p.n_tok) y[ulong(k) * p.ldy + o] = cuda_nan(acc[k]); +} diff --git a/kernels/common/basalt_mmvq.metal b/kernels/common/basalt_mmvq.metal new file mode 100644 index 00000000..cd4ea74f --- /dev/null +++ b/kernels/common/basalt_mmvq.metal @@ -0,0 +1,307 @@ +// Copyright (c) 2023-2026 The ggml authors (MIT) +// Copyright (c) 2026 Jesús Gulfo (MIT) +// Adapted from basalt (jesdga95/basalt) src/kernels/cuda/native_mmvq.cu:179-1172 +// @ b4c63b55754637f4c72ad53a0f791d425f71eb36 (MIT; third_party/NOTICE), which adapts ggml-org/llama.cpp +// ggml/src/ggml-cuda/{vecdotq.cuh,mmvq.cu,common.cuh} and ggml/src/ggml-common.h @ +// 3cf03257f219afbe7334045ff7c6a06ac68c627d (MIT; third_party/NOTICE). +// +// basalt's native_mmvq: y[j][r] = row r of a GGUF weight matrix (blocks as in the file, rows of n_in / DIV blocks) +// times column j of q8_1 activations (basalt_q8_1.metal's layout: column j's blocks start at block j * n_in / 32), +// for j < NCOLS; y[j] starts at j * n_out. Needs basalt_fp.metal ahead of it. +// +// One kernel for basalt's one-column kernels and its multi-column kernel (native_mmvq_multi_kernel), which give every +// (row, column) value the same operations in the same order (native_mmvq.cu:882-896): each thread takes the weight +// blocks kbx = tid / T, tid / T + BPI', ... of its rows in ascending order at sub-position kqs, `load` decodes the +// block once and `apply` runs the format's dot product per column; SIMD-groups 1..NW-1 store their partial sums, SIMD- +// group 0 adds them in SIMD-group order and reduces with basalt's XOR butterfly; lane i writes row row0 + i. The float +// steps are the ones nvcc compiles (docs/research/basalt-nvcc/matvec.md): fma() exactly where SASS has FFMA.FTZ, the +// rest .FTZ adds and multiplies. Integer steps are basalt's, as exact int32 arithmetic. A NaN is stored as sm_120's +// (cuda_nan; docs/research/basalt-nvcc/nan.md). +// +// Macros: MMVQ_TYPE the ggml type id (2 Q4_0, 6 Q5_0, 8 Q8_0, 11 Q3_K, 12 Q4_K, 13 Q5_K, 14 Q6_K, 20 IQ4_NL, +// 23 IQ4_XS, 42 Q2_0); NCOLS 1..8; ROWS rows per threadgroup; NW SIMD-groups per threadgroup (BPI' = BPI * NW / 4). +// basalt's layouts (monolith/kernels.py basalt_mmvq_macros): one column NW 4, ROWS 1 (4 for small K); several +// columns, exact (the default) NW 4, ROWS 1 (2 for small K); the upstream layout (mmvq_multi_parity's negative +// control only) NW 4 for <= 4 columns else 2, ROWS 2. Grid: ceil(n_out / ROWS) threadgroups of 32 * NW threads. +#pragma STDC FP_CONTRACT OFF + +#ifndef MMVQ_TYPE +#define MMVQ_TYPE 8 +#endif +#ifndef NCOLS +#define NCOLS 1 +#endif +#ifndef ROWS +#define ROWS 1 +#endif +#ifndef NW +#define NW 4 +#endif + +struct MmvqParams { uint n_in; uint n_out; uint pad0; uint pad1; }; + +// q8_d, q8_s, q8_w (a q8_1 block's scale, sum and code words) and iq4_table_lookup are basalt_fp.metal's. + +#if MMVQ_TYPE == 13 +// Q5_K: basalt_fp.metal's q5k_load and q5k_dot (native_mmvq.cu:180-240, 897-937), shared with the Q5_K head +#define DIV 256 +#define T_PER 16 +#define KBY 8 +#define BPI 8 +#define BLOCK_BYTES 176 +static inline int kqs_of(int tid) { return 2 * (tid % 16); } +typedef Q5KW Wt; +static inline Wt wload(device const ushort* blk, int iqs) { return q5k_load(blk, iqs); } +static inline float apply_acc(float tmp, thread const Wt& r, device const uint* x, int iqs) { + return add_ftz(tmp, q5k_dot(r, x, iqs)); +} + +#elif MMVQ_TYPE == 12 +// Q4_K (144-byte blocks: dm, scales[12], qs[128]); native_mmvq.cu:938-975 (Q4KTraits), dot :522-574 +#define DIV 256 +#define T_PER 16 +#define KBY 8 +#define BPI 8 +#define BLOCK_BYTES 144 +static inline int kqs_of(int tid) { return 2 * (tid % 16); } +struct Wt { int vl[2]; uchar sc[2]; uchar m[2]; float dmx, dmy; int bq8_offset; }; +static inline Wt wload(device const ushort* blk, int iqs) { + Wt r; + r.bq8_offset = 2 * ((iqs / 2) / 4); + const int ql = (16 + 16 * r.bq8_offset + 4 * ((iqs / 2) % 4)) / 4; + r.vl[0] = load_int_b2(blk, ql); + r.vl[1] = load_int_b2(blk, ql + 4); + const int j = r.bq8_offset / 2; + const int jm = j & 1; + const uint s0 = blk[2 + jm], s2 = blk[2 + jm + 2], s4 = blk[2 + jm + 4]; + const uint hi = uint(-int(j >= 2)); + const uint aux0 = ((s0 & 0x3f3fu) & ~hi) | ((((s4 >> 0) & 0x0f0fu) | ((s0 & 0xc0c0u) >> 2)) & hi); + const uint aux1 = ((s2 & 0x3f3fu) & ~hi) | ((((s4 >> 4) & 0x0f0fu) | ((s2 & 0xc0c0u) >> 2)) & hi); + r.sc[0] = uchar(aux0); r.sc[1] = uchar(aux0 >> 8); + r.m[0] = uchar(aux1); r.m[1] = uchar(aux1 >> 8); + r.dmx = h2f(blk[0]); + r.dmy = h2f(blk[1]); + return r; +} +static inline float apply_acc(float tmp, thread const Wt& r, device const uint* x, int iqs) { + float sumf_d = 0.0f, sumf_m = 0.0f; + for (int i = 0; i < 2; ++i) { + const int b = r.bq8_offset + i; + const float d8 = q8_d(x, b); + const int u0 = q8_w(x, b, (iqs / 2) % 4), u1 = q8_w(x, b, (iqs / 2) % 4 + 4); + const int v0i = (r.vl[0] >> (4 * i)) & 0x0f0f0f0f; + const int v1i = (r.vl[1] >> (4 * i)) & 0x0f0f0f0f; + const int dot1 = dp4a(v1i, u1, dp4a(v0i, u0, 0)); + const int dot2 = dp4a(0x01010101, u1, dp4a(0x01010101, u0, 0)); + sumf_d = fma_ftz(d8, float(dot1 * int(r.sc[i])), sumf_d); + sumf_m = fma_ftz(d8, float(dot2 * int(r.m[i])), sumf_m); + } + // dm.x * sumf_d - dm.y * sumf_m: ptxas rounds the dmin product and fuses the d product (matvec.md section 5) + return add_ftz(tmp, fma_ftz(r.dmx, sumf_d, -mul_ftz(r.dmy, sumf_m))); +} + +#elif MMVQ_TYPE == 42 +// Q2_0 (18-byte blocks: d, qs[16] of 2-bit codes, value = d * (code - 1)); Q20Traits, native_mmvq.cu:976-1007 +#define DIV 64 +#define T_PER 2 +#define KBY 2 +#define BPI 64 +#define BLOCK_BYTES 18 +static inline int kqs_of(int tid) { return tid % 2; } +typedef Q20W Wt; // basalt_fp.metal's Q2_0 decode +static inline Wt wload(device const ushort* blk, int iqs) { return q2_0_load(blk, iqs); } +static inline float apply_acc(float tmp, thread const Wt& r, device const uint* x, int iqs) { + return fma_ftz(mul_ftz(r.d2, q8_d(x, iqs)), float(q2_0_sumi(r, x, iqs)), tmp); // d2 * d8 * sumi into tmp += +} + +#elif MMVQ_TYPE == 11 +// Q3_K (110-byte blocks: hmask[32], qs[64], scales[12], d); Q3KTraits, native_mmvq.cu:1008-1033, dot :360-398 +#define DIV 256 +#define T_PER 16 +#define KBY 8 +#define BPI 8 +#define BLOCK_BYTES 110 +static inline int kqs_of(int tid) { return tid % 16; } +struct Wt { int vl; int vh; float d; device const ushort* blk; int scale_offset; int bq8_offset; }; +static inline Wt wload(device const ushort* blk, int iqs) { + Wt r; + r.bq8_offset = 4 * (iqs / 8); + r.scale_offset = iqs - iqs % 8 + (iqs % 8) / 4; + r.d = h2f(blk[54]); + r.vl = load_int_b2(blk + 16, iqs); + r.vh = ~load_int_b2(blk, iqs % 8) >> r.bq8_offset; + r.blk = blk; + return r; +} +static inline float apply_acc(float tmp, thread const Wt& r, device const uint* x, int iqs) { + float sumf = 0.0f; + for (int i = 0; i < 4; ++i) { + const int isc = r.scale_offset + 2 * i; + const int sc_low = (int(w_u8(r.blk, 96 + isc % 8)) >> (4 * (isc / 8))) & 0xf; + const int sc_high = ((int(w_u8(r.blk, 96 + 8 + isc % 4)) >> (2 * (isc / 4))) & 3) << 4; + const int sc = (sc_low | sc_high) - 32; + const int vil = (r.vl >> (2 * i)) & 0x03030303; + const int vih = ((r.vh >> i) << 2) & 0x04040404; + const int vi = vsubss4(vil, vih); + const int b = r.bq8_offset + i; + sumf = fma_ftz(q8_d(x, b), float(dp4a(vi, q8_w(x, b, iqs % 8), 0) * sc), sumf); + } + return fma_ftz(r.d, sumf, tmp); // d3 * sumf into tmp += +} + +#elif MMVQ_TYPE == 14 +// Q6_K (210-byte blocks: ql[128], qh[64], scales[16] int8, d); Q6KTraits, native_mmvq.cu:1034-1060, dot :621-651 +#define DIV 256 +#define T_PER 32 +#define KBY 8 +#define BPI 4 +#define BLOCK_BYTES 210 +static inline int kqs_of(int tid) { return tid % 32; } +struct Wt { int vl; int vh; float d; int sc[2]; int bq8_offset; }; +static inline Wt wload(device const ushort* blk, int iqs) { + Wt r; + r.bq8_offset = 4 * (iqs / 16) + (iqs % 16) / 8; + const int scale_offset = 8 * (iqs / 16) + (iqs % 16) / 4; + const int vh_shift = 2 * ((iqs % 16) / 8); + r.vl = load_int_b2(blk, iqs); + r.vh = load_int_b2(blk + 64, 8 * (iqs / 16) + iqs % 8) >> vh_shift; + r.sc[0] = int(as_type(w_u8(blk, 192 + scale_offset))); + r.sc[1] = int(as_type(w_u8(blk, 192 + scale_offset + 4))); + r.d = h2f(blk[104]); + return r; +} +static inline float apply_acc(float tmp, thread const Wt& r, device const uint* x, int iqs) { + float sumf = 0.0f; + for (int i = 0; i < 2; ++i) { + const int vil = (r.vl >> (4 * i)) & 0x0f0f0f0f; + const int vih = ((r.vh >> (4 * i)) << 4) & 0x30303030; + const int vi = vsubss4(vil | vih, 0x20202020); + const int b = r.bq8_offset + 2 * i; + sumf = fma_ftz(q8_d(x, b), float(dp4a(vi, q8_w(x, b, iqs % 8), 0) * r.sc[i]), sumf); + } + return fma_ftz(r.d, sumf, tmp); // d * sumf into tmp += +} + +#elif MMVQ_TYPE == 23 +// IQ4_XS (136-byte blocks: d, scales_h, scales_l[4], qs[128]); IQ4XSTraits, native_mmvq.cu:1061-1087, dot :462-479 +#define DIV 256 +#define T_PER 8 +#define KBY 8 +#define BPI 16 +#define BLOCK_BYTES 136 +static inline int kqs_of(int tid) { return 4 * (tid % 8); } +struct Wt { int2 v[4]; int ls; float dw; }; +static inline Wt wload(device const ushort* blk, int iqs) { + Wt r; + for (int j = 0; j < 4; ++j) r.v[j] = iq4_table_lookup(load_int_b2(blk + 4, iqs + j)); + r.ls = ((int(w_u8(blk, 4 + iqs / 8)) >> (iqs & 0x04)) & 0x0f) | (((int(blk[1]) >> (iqs / 2)) & 0x03) << 4); + r.dw = h2f(blk[0]); + return r; +} +static inline float apply_acc(float tmp, thread const Wt& r, device const uint* x, int iqs) { + int sumi = 0; + for (int j = 0; j < 4; ++j) { + sumi = dp4a(r.v[j].x, q8_w(x, iqs / 4, j), sumi); + sumi = dp4a(r.v[j].y, q8_w(x, iqs / 4, j + 4), sumi); + } + sumi *= r.ls - 32; + return fma_ftz(mul_ftz(r.dw, q8_d(x, iqs / 4)), float(sumi), tmp); // d * sumi into tmp += +} + +#elif MMVQ_TYPE == 2 || MMVQ_TYPE == 6 || MMVQ_TYPE == 20 || MMVQ_TYPE == 8 +// The 32-value formats (SmallTraits, native_mmvq.cu:1088-1098; small_q8_dot :696-763): Q4_0 and IQ4_NL (18 bytes: +// d, qs[16]), Q5_0 (22: d, qh[4], qs[16]), Q8_0 (34: d, qs[32]); Qi 4, or 8 for Q8_0 +#define DIV 32 +#define KBY 1 +#define QI_S (MMVQ_TYPE == 8 ? 8 : 4) +#define T_PER (QI_S / 2) +#define BPI (2 * 4 * 32 / QI_S) +#define BLOCK_BYTES (MMVQ_TYPE == 8 ? 34 : MMVQ_TYPE == 6 ? 22 : 18) +static inline int kqs_of(int tid) { return 2 * (tid % (QI_S / 2)); } +struct Wt { device const ushort* blk; }; +static inline Wt wload(device const ushort* blk, int) { return Wt{blk}; } +static inline float apply_acc(float tmp, thread const Wt& r, device const uint* x, int iqs) { + device const ushort* w = r.blk; + int sumi = 0; +#if MMVQ_TYPE == 8 + for (int i = 0; i < 2; ++i) sumi = dp4a(load_int_b2(w + 1, iqs + i), q8_w(x, 0, iqs + i), sumi); + return fma_ftz(mul_ftz(h2f(w[0]), q8_d(x, 0)), float(sumi), tmp); // d0 * d1 * float(sumi) into tmp += +#elif MMVQ_TYPE == 20 + for (int i = 0; i < 2; ++i) { + const int2 v = iq4_table_lookup(load_int_b2(w + 1, iqs + i)); + sumi = dp4a(v.x, q8_w(x, 0, iqs + i), sumi); + sumi = dp4a(v.y, q8_w(x, 0, iqs + i + 4), sumi); + } + return fma_ftz(mul_ftz(h2f(w[0]), q8_d(x, 0)), float(sumi), tmp); // d * sumi into tmp += +#else + for (int i = 0; i < 2; ++i) { +#if MMVQ_TYPE == 2 + const int v = load_int_b2(w + 1, iqs + i); + const int vi0 = (v >> 0) & 0x0f0f0f0f; + const int vi1 = (v >> 4) & 0x0f0f0f0f; +#else + const int vl = load_int_b2(w + 3, iqs + i); + const int vh = load_int_b2(w + 1, 0) >> (4 * (iqs + i)); + int vi0 = (vl >> 0) & 0x0f0f0f0f; + vi0 |= (vh << 4) & 0x00000010; + vi0 |= (vh << 11) & 0x00001000; + vi0 |= (vh << 18) & 0x00100000; + vi0 |= (vh << 25) & 0x10000000; + int vi1 = (vl >> 4) & 0x0f0f0f0f; + vi1 |= (vh >> 12) & 0x00000010; + vi1 |= (vh >> 5) & 0x00001000; + vi1 |= (vh << 2) & 0x00100000; + vi1 |= (vh << 9) & 0x10000000; +#endif + sumi = dp4a(vi0, q8_w(x, 0, iqs + i), sumi); + sumi = dp4a(vi1, q8_w(x, 0, iqs + i + 4), sumi); + } + // d * (sumi * ds.x - k * ds.y), k = 4 (Q4_0) or 8 (Q5_0): fma(sumi, d8, fl(-k * s8)), then fma into tmp + const float k = MMVQ_TYPE == 2 ? -4.0f : -8.0f; + return fma_ftz(h2f(w[0]), fma_ftz(float(sumi), q8_d(x, 0), mul_ftz(q8_s(x, 0), k)), tmp); +#endif +} +#else +#error "basalt_mmvq: unsupported MMVQ_TYPE" +#endif + +kernel void basalt_mmvq(device const ushort* w [[buffer(0)]], device const uint* x [[buffer(1)]], + device float* y [[buffer(2)]], constant MmvqParams& p [[buffer(3)]], + uint tg [[threadgroup_position_in_grid]], ushort lane [[thread_index_in_simdgroup]], + ushort sg [[simdgroup_index_in_threadgroup]]) { + const int tid = 32 * int(sg) + int(lane); + const int row0 = ROWS * int(tg); + const int n_in = int(p.n_in), n_out = int(p.n_out); + const int blocks_per_row = n_in / DIV; + const int x_stride = n_in / 32; // q8_1 blocks per activation column + float tmp[NCOLS][ROWS]; + for (int j = 0; j < NCOLS; ++j) + for (int i = 0; i < ROWS; ++i) tmp[j][i] = 0.0f; + for (int kbx = tid / T_PER; kbx < blocks_per_row; kbx += BPI * NW / 4) { + const int kby = kbx * KBY; + const int kqs = kqs_of(tid); + for (int i = 0; i < ROWS; ++i) { + if (row0 + i < n_out) { + device const ushort* blk = w + (uint(row0 + i) * uint(blocks_per_row) + uint(kbx)) * (BLOCK_BYTES / 2); + const Wt wv = wload(blk, kqs); // once per (row, block) + for (int j = 0; j < NCOLS; ++j) // then per column + tmp[j][i] = apply_acc(tmp[j][i], wv, x + 9 * (j * x_stride + kby), kqs); + } + } + } + threadgroup float partial[NW > 1 ? NW - 1 : 1][NCOLS][ROWS][32]; + if (sg > 0) { + for (int j = 0; j < NCOLS; ++j) + for (int i = 0; i < ROWS; ++i) partial[sg - 1][j][i][lane] = tmp[j][i]; + } + threadgroup_barrier(mem_flags::mem_threadgroup); + if (sg > 0) return; + for (int j = 0; j < NCOLS; ++j) { + for (int i = 0; i < ROWS; ++i) { + float t = tmp[j][i]; + for (int l = 0; l < NW - 1; ++l) t = add_ftz(t, partial[l][j][i][lane]); + t = warp_sum_ftz(t); + if (int(lane) == i && row0 + i < n_out) y[j * n_out + row0 + i] = cuda_nan(t); + } + } +} diff --git a/kernels/common/basalt_q5k_head.metal b/kernels/common/basalt_q5k_head.metal new file mode 100644 index 00000000..98d2bac2 --- /dev/null +++ b/kernels/common/basalt_q5k_head.metal @@ -0,0 +1,423 @@ +// Copyright (c) 2023-2026 The ggml authors (MIT) +// Copyright (c) 2026 Jesús Gulfo (MIT) +// Adapted from basalt (jesdga95/basalt) src/kernels/cuda/q5k_head.cu:19-496 and src/kernels/cuda/head_proxy.cuh:17-240 +// @ b4c63b55754637f4c72ad53a0f791d425f71eb36 (MIT; third_party/NOTICE), whose Q5_K dot repeats native_mmvq.cu's, an +// adaptation of ggml-org/llama.cpp +// ggml/src/ggml-cuda/vecdotq.cuh @ 3cf03257f219afbe7334045ff7c6a06ac68c627d (MIT; third_party/NOTICE). +// +// basalt's Q5_K head (n_in a multiple of 256, at most 64 blocks a row): y[j][r] = Q5_K row r times q8_1 column j +// (basalt_q8_1.metal's layout, column j's blocks from block j * n_in / 32), each value bit for bit native_mmvq's +// (basalt_mmvq.metal, MMVQ_TYPE 13): the same q5k_load / q5k_dot (basalt_fp.metal) per (row, block, column), the +// same order. Needs basalt_fp.metal ahead of it. Arithmetic: docs/research/basalt-nvcc/q5k_head.md. +// +// Mapping (q5k_head.cu:108-141, 225-252): threadgroups of 8 SIMD-groups (basalt's WPB warps), one row per SIMD-group, +// rows row0 = 8 tg + sg strided by 8 * threadgroups; lane L stands for native_mmvq's threads L + 32v, v = 0..3, whose +// blocks kbx = (L + 32v) / 16, + 8, ... it takes in ascending order at kqs = 2 (L % 16), each thread's sum from +0; +// then ((p0 + p1) + p2) + p3 (native_mmvq's warp order) and the XOR butterfly. At 10 blocks a row this is +// q5k_rows_10's assignment (thread L: a = L / 16 and a + 8; threads L + 32, L + 64, L + 96: a + 2, a + 4, a + 6). +// q5k_rows_10's next-row register prefetch and the top-1's L2 prefetch schedule loads only and are not ported. The +// columns are read from device memory: basalt stages them in shared memory (61,440 bytes at 8 columns and n_in 2560, +// more than Apple9's 32 KiB), which is not arithmetic. The row offsets and the output index are ulong, as basalt +// casts them to size_t (q5k_head.cu:120, 139, 189, 196, 218, 490); the row loop is int, as basalt's. +// +// Kernels: +// - basalt_q5k_head (q5k_head_mmvq; NC columns, 1..8): grid basalt_q5k_head_grid threadgroups of 256 threads. +// - basalt_q5k_head_mask_unmapped (q5k_head_mask_unmapped): y[i] = -inf where map[i] < 0; ceil(n / 256) x 256. +// - basalt_q5k_head_top1 then basalt_q5k_head_top1_merge (q5k_head_top1, one column, n_in 2560): the first writes the +// logits and each threadgroup's (max, its first row, sum of exp(l - max)) to part[3 tg .. 3 tg + 2]; the second, one +// threadgroup of 256, merges the partials in basalt's order and writes the token id and its probability. basalt +// elects the last block with an atomic counter and merges there (q5k_head.cu:303-334); Metal documents no ordering +// that makes the other threadgroups' partials visible to the elected one, so the merge is a second dispatch, ordered +// after the first by the dispatch boundary (q5k_head.md section 3). Same arithmetic, same order. +// Every float stored that a NaN can reach carries sm_120's NaN (cuda_nan; docs/research/basalt-nvcc/nan.md). +#pragma STDC FP_CONTRACT OFF + +#ifndef NC +#define NC 1 +#endif + +constant constexpr int Q5K_WPB = 8; // SIMD-groups (rows in flight) per threadgroup +constant constexpr int Q5K_USHORTS = 88; // a Q5_K block, as 16-bit words +constant constexpr int TOP_NONE = 0x7fffffff; // Top::idx before any row + +// n_in, n_out, has_map (0: no map; basalt's nullptr) and, for the merge, the first dispatch's threadgroup count +struct Q5kHeadParams { uint n_in; uint n_out; uint has_map; uint n_blocks; }; + +static inline float neg_inf() { return as_type(0xff800000u); } + +// q5k_row_dev (q5k_head.cu:110-141): row `wr` (bpr blocks) times NCOL columns of x, every lane's t[j] the same bits. +template +static inline void q5k_row(device const ushort* wr, device const uint* x, int x_stride, int bpr, int lane, + thread float* t) { + const int kqs = 2 * (lane % 16); + float p[4][NCOL]; + for (int v = 0; v < 4; ++v) + for (int j = 0; j < NCOL; ++j) p[v][j] = 0.0f; + for (int v = 0; v < 4; ++v) { + for (int kbx = (lane + 32 * v) / 16; kbx < bpr; kbx += 8) { + const Q5KW wv = q5k_load(wr + kbx * Q5K_USHORTS, kqs); + for (int j = 0; j < NCOL; ++j) p[v][j] = add_ftz(p[v][j], q5k_dot(wv, x + 9 * (j * x_stride + 8 * kbx), kqs)); + } + } + for (int j = 0; j < NCOL; ++j) { + float s = p[0][j]; + for (int v = 1; v < 4; ++v) s = add_ftz(s, p[v][j]); + t[j] = warp_sum_ftz(s); + } +} + +kernel void basalt_q5k_head(device const ushort* w [[buffer(0)]], device const uint* x [[buffer(1)]], + device float* y [[buffer(2)]], constant Q5kHeadParams& p [[buffer(3)]], + uint tg [[threadgroup_position_in_grid]], uint ntg [[threadgroups_per_grid]], + ushort lane [[thread_index_in_simdgroup]], ushort sg [[simdgroup_index_in_threadgroup]]) { + const int n_in = int(p.n_in), n_out = int(p.n_out), bpr = n_in / 256; + for (int row = Q5K_WPB * int(tg) + int(sg); row < n_out; row += Q5K_WPB * int(ntg)) { + float t[NC]; + q5k_row(w + ulong(row) * ulong(bpr * Q5K_USHORTS), x, n_in / 32, bpr, int(lane), t); + if (lane == 0) + for (int j = 0; j < NC; ++j) y[ulong(j) * ulong(n_out) + ulong(row)] = cuda_nan(t[j]); + } +} + +kernel void basalt_q5k_head_mask_unmapped(device float* y [[buffer(0)]], device const int* map [[buffer(1)]], + constant Q5kHeadParams& p [[buffer(2)]], + uint i [[thread_position_in_grid]]) { + if (i < p.n_out && map[i] < 0) y[i] = neg_inf(); +} + +// ---- the top-1 (q5k_head.cu:146-176, 256-335) ---------------------------------------------------------------------- + +// the running (max, its first row, sum of exp(l - max)) of the logits taken so far +struct Top { float m; int idx; float s; }; +static inline Top top_init() { return Top{neg_inf(), TOP_NONE, 0.0f}; } +static inline void top_take(thread Top& t, float l, int row) { + if (l > t.m) { + t.s = fma_ftz(t.s, expf_ftz(add_ftz(t.m, -l)), 1.0f); + t.m = l; + t.idx = row; + } else { + t.s = add_ftz(t.s, expf_ftz(add_ftz(l, -t.m))); + if (l == t.m && row < t.idx) t.idx = row; + } +} +static inline void top_merge(thread Top& t, Top o) { + if (o.idx == TOP_NONE) return; + if (t.idx == TOP_NONE || o.m > t.m) { + t.s = fma_ftz(t.s, expf_ftz(add_ftz(t.m, -o.m)), o.s); + t.m = o.m; + t.idx = o.idx; + } else { + t.s = fma_ftz(o.s, expf_ftz(add_ftz(o.m, -t.m)), t.s); + if (o.m == t.m && o.idx < t.idx) t.idx = o.idx; + } +} + +kernel void basalt_q5k_head_top1(device const ushort* w [[buffer(0)]], device const uint* x [[buffer(1)]], + device float* y [[buffer(2)]], device const int* map [[buffer(3)]], + device float* part [[buffer(4)]], constant Q5kHeadParams& p [[buffer(5)]], + uint tg [[threadgroup_position_in_grid]], uint ntg [[threadgroups_per_grid]], + ushort tid [[thread_index_in_threadgroup]], ushort lane [[thread_index_in_simdgroup]], + ushort sg [[simdgroup_index_in_threadgroup]]) { + threadgroup Top wt[Q5K_WPB]; + const int n_out = int(p.n_out); + Top top = top_init(); + for (int row = Q5K_WPB * int(tg) + int(sg); row < n_out; row += Q5K_WPB * int(ntg)) { + float t[1]; + q5k_row<1>(w + ulong(row) * ulong(10 * Q5K_USHORTS), x, 80, 10, int(lane), t); + // a row whose id is negative holds no token: it never wins and adds nothing to the sum + if (p.has_map != 0u && map[row] < 0) t[0] = neg_inf(); + else top_take(top, t[0], row); + if (lane == 0) y[row] = cuda_nan(t[0]); + } + if (lane == 0) wt[sg] = top; + threadgroup_barrier(mem_flags::mem_threadgroup); + if (tid == 0) { + Top b = wt[0]; + for (int i = 1; i < Q5K_WPB; ++i) top_merge(b, wt[i]); + part[3 * tg] = b.m; // never NaN: l > m is false for a NaN l + part[3 * tg + 1] = as_type(b.idx); + part[3 * tg + 2] = cuda_nan(b.s); + } +} + +kernel void basalt_q5k_head_top1_merge(device const float* part [[buffer(0)]], device const int* map [[buffer(1)]], + device int* out_id [[buffer(2)]], device float* out_prob [[buffer(3)]], + constant Q5kHeadParams& p [[buffer(4)]], + ushort tid [[thread_index_in_threadgroup]], + ushort lane [[thread_index_in_simdgroup]], + ushort sg [[simdgroup_index_in_threadgroup]]) { + threadgroup Top wt[Q5K_WPB]; + Top g = top_init(); // each thread a strided share of the block partials, then the block + for (int i = int(tid); i < int(p.n_blocks); i += 32 * Q5K_WPB) + top_merge(g, Top{part[3 * i], as_type(part[3 * i + 1]), part[3 * i + 2]}); + for (ushort off = 16; off > 0; off >>= 1) + top_merge(g, Top{shfl_xor(g.m, off), simd_shuffle_xor(g.idx, off), shfl_xor(g.s, off)}); + if (lane == 0) wt[sg] = g; + threadgroup_barrier(mem_flags::mem_threadgroup); + if (tid == 0) { + Top b = wt[0]; + for (int i = 1; i < Q5K_WPB; ++i) top_merge(b, wt[i]); + const int id = b.idx < int(p.n_out) ? b.idx : 0; + *out_id = p.has_map != 0u ? map[id] : id; + *out_prob = cuda_nan(rcp_ftz(b.s)); + } +} + +// ---- the 2-bit proxy (head_proxy.cuh; q5k_head.cu:434-535) -------------------------------------------------------- +// A copy of the head's leading rows (n_in 2560) at four levels and an fp16 scale per 32 weights; the proxy buffer is +// basalt's px::bytes(n_cap): per tile of 32 rows and per 64 weights (w4 = 0..39) a 16-byte word per row (lane = row), +// then from px::scales(proxy, n_cap) the fp16 scales, two per (tile, w4, lane) (head_proxy.cuh:17-28, 72-87). + +constant constexpr uint PX_NW4 = 40; // kNw4: 16-byte weight words per row +constant constexpr int PX_PER = 4; // kPer: candidates kept per tile +constant constexpr int PX_MAX_CAND = 64; // kMaxCand: rows rescored exactly + +// pack: the rows row0 .. row0 + n - 1; score and final: the first n_rows rows; n_cap: the copy's row capacity. +// Offsets and counts basalt computes in int64_t or size_t (px::tiles, px::scales, the pack's index and stores, the +// score's word index, the rows' byte offsets) are ulong here; the ones it computes in int stay int. +struct PxParams { uint row0; uint n; uint n_cap; uint n_rows; }; + +static inline ulong px_tiles(ulong n) { return (n + 31) / 32; } + +// level(w, sh) (head_proxy.cuh:36) as ptxas compiles it: F2I.FTZ.FLOOR.NTZ(FFMA.FTZ(w, MUFU.RCP(sh), 2)), then the +// clamp to 0..3; rs = rcp_ftz(sh). F2I takes NaN to 0 and saturates the infinities, which the clamp makes 0 and 3: the +// NaN case is real (a group of zeros has sh = 0, rs = +inf, 0 * inf + 2 = NaN). MSL takes NaN to 0 (section 8.6) but +// converts without saturation (section 2.23), so the clamp is done in float. +static inline int px_level(float w, float rs) { + const float f = floor(fma_ftz(w, rs, 2.0f)); + return isnan(f) ? 0 : int(clamp(f, 0.0f, 3.0f)); +} + +// fit_group (head_proxy.cuh:42-70; q5k_head.md section 4): the fp16 scale's bits, sh_out its value. +// amax / 1.5f is FMUL.FTZ by fl(1 / 1.5) (ptxas's constant division), 1.0f - 0.1f * t is FFMA.FTZ(t, -0.1f, 1), +// each squared error FFMA.FTZ(r, r, e) from 0 in weight order, r = FFMA.FTZ(level - 1.5, sh, -w). +static inline ushort px_fit(thread const float* w, thread float& sh_out) { + float amax = as_type(0x3089705Fu); // 1e-9f + for (int l = 0; l < 32; ++l) amax = max_ftz(amax, abs_ftz(w[l])); + const float a15 = mul_ftz(amax, as_type(0x3F2AAAABu)); + float best_s = a15, best_e = INFINITY; + for (int t = 0; t < 6; ++t) { + const float s = mul_ftz(a15, fma_ftz(float(t), -0.1f, 1.0f)); + const float sh = float(half(s)); // __half2float(__float2half(s)): RNE + const float rs = rcp_ftz(sh); + float e = 0.0f; + for (int l = 0; l < 32; ++l) { + const float r = fma_ftz(add_ftz(float(px_level(w[l], rs)), -1.5f), sh, -w[l]); + e = fma_ftz(r, r, e); + } + if (e < best_e) { best_e = e; best_s = s; } + } + const half hs = half(best_s); + sh_out = float(hs); + return as_type(hs); +} + +// q5k_proxy_pack_kernel (q5k_head.cu:438-462) with pack_group (head_proxy.cuh:72-87): one thread per 32-weight +// group g of row row0 + i / 80, w = FFMA.FTZ(FMUL.FTZ(d, sc), q, -FMUL.FTZ(dmin, m)). ceil(n * 80 / 128) x 128. +// i is basalt's (int64_t) blockIdx.x * blockDim.x + threadIdx.x, from the threadgroup's position: a 32-bit +// thread_position_in_grid would wrap past 2^32 threads. +kernel void basalt_q5k_proxy_pack(device const uchar* q5 [[buffer(0)]], device uint* proxy [[buffer(1)]], + constant PxParams& p [[buffer(2)]], uint tg [[threadgroup_position_in_grid]], + uint ntt [[threads_per_threadgroup]], uint tid [[thread_index_in_threadgroup]]) { + const ulong i = ulong(tg) * ulong(ntt) + ulong(tid); + if (i >= ulong(p.n) * 80) return; + const ulong row = ulong(p.row0) + i / 80; + const int g = int(i % 80), j = g % 8; + device const uchar* b = q5 + row * 1760 + uint(g / 8) * 176u; // Q5KBlock: dm, scales[12], qh[32], qs[128] + device const uchar* scl = b + 4; + int sci, mi; + if (j < 4) { sci = scl[j] & 63; mi = scl[j + 4] & 63; } + else { + sci = (scl[j + 4] & 0xF) | ((scl[j - 4] >> 6) << 4); + mi = (scl[j + 4] >> 4) | ((scl[j] >> 6) << 4); + } + const float d = mul_ftz(h2f(ushort(b[0] | (b[1] << 8))), float(sci)); + const float mn = mul_ftz(h2f(ushort(b[2] | (b[3] << 8))), float(mi)); + float w[32]; + for (int l = 0; l < 32; ++l) { + const int qs = b[48 + 32 * (j / 2) + l]; + const int q = ((j & 1) ? (qs >> 4) : (qs & 15)) | (((b[16 + l] >> j) & 1) << 4); + w[l] = fma_ftz(d, float(q), -mn); + } + float sh; + const ushort hs = px_fit(w, sh); + const float rs = rcp_ftz(sh); + uint words[2] = {0u, 0u}; + for (int c = 0; c < 2; ++c) + for (int ii = 0; ii < 4; ++ii) + for (int bb = 0; bb < 4; ++bb) words[c] |= uint(px_level(w[c * 16 + 4 * ii + bb], rs)) << (8 * bb + 2 * ii); + const ulong slot = ((row >> 5) * PX_NW4 + ulong(g / 2)) * 32 + (row & 31), h = ulong(g & 1); + proxy[slot * 4 + 2 * h] = words[0]; + proxy[slot * 4 + 2 * h + 1] = words[1]; + device ushort* sc = (device ushort*)(proxy + px_tiles(p.n_cap) * PX_NW4 * 32 * 4); // px::scales(proxy, n_cap) + sc[slot * 2 + h] = hs; +} + +// px::score_kernel (head_proxy.cuh:89-167): a threadgroup of 4 SIMD-groups per tile of 32 rows (lane = row), SIMD-group +// k scoring the weights 640 k .. 640 k + 639 of its rows; the tile's 4 best approximate scores with their rows go to +// cand[4 tile + k] and its softmax partial (max, sum of exp(score - max)) to part[tile], cand and part in one scratch +// (basalt's layout, q5k_head.cu:523-524). Per group g: P the exact integer dot of the levels and the q8_1 codes, then +// acc = FFMA.FTZ(scale, FFMA.FTZ(d8, P, -FMUL.FTZ(d8 * sum, 1.5)), acc) (q5k_head.md section 4). Grid: tiles(n_rows). +kernel void basalt_q5k_proxy_score(device const uint4* proxy [[buffer(0)]], device const uint* x [[buffer(1)]], + device const int* map [[buffer(2)]], device float2* scratch [[buffer(3)]], + constant PxParams& p [[buffer(4)]], uint tile [[threadgroup_position_in_grid]], + ushort tid [[thread_index_in_threadgroup]], + ushort lane [[thread_index_in_simdgroup]], + ushort sg [[simdgroup_index_in_threadgroup]]) { + threadgroup int xi[640]; + threadgroup float xs[80], xdd[80]; + threadgroup float red[4][32]; + const ulong ntc = px_tiles(p.n_cap); + device const uint* sc = (device const uint*)(proxy + ntc * PX_NW4 * 32); // px::scales, two per word + const ulong base = (ulong(tile) * PX_NW4 + uint(sg) * 10u) * 32 + lane; + const int row = int(tile) * 32 + int(lane), n_rows = int(p.n_rows); + const int id = (sg == 0 && row < n_rows) ? map[row] : 0; + for (int i = tid; i < 640; i += 128) xi[i] = q8_w(x, i / 8, i % 8); + if (tid < 80) { + int sum = 0; + for (int i = 0; i < 8; ++i) sum = dp4a(0x01010101, q8_w(x, tid, i), sum); + const float d8 = q8_d(x, tid); + xdd[tid] = d8; + xs[tid] = mul_ftz(d8, float(sum)); + } + threadgroup_barrier(mem_flags::mem_threadgroup); + float acc = 0.0f; + for (int j = 0; j < 10; ++j) { + const uint4 wv = proxy[base + ulong(j) * 32]; + const uint s = sc[base + ulong(j) * 32]; + for (int h = 0; h < 2; ++h) { + const int g = 2 * (int(sg) * 10 + j) + h; + int P = 0; + for (int c = 0; c < 2; ++c) { + const uint v = wv[2 * h + c]; + const int o = g * 8 + c * 4; + P = dp4a(int(v & 0x03030303u), xi[o], P); + P = dp4a(int((v >> 2) & 0x03030303u), xi[o + 1], P); + P = dp4a(int((v >> 4) & 0x03030303u), xi[o + 2], P); + P = dp4a(int((v >> 6) & 0x03030303u), xi[o + 3], P); + } + const float scale = h2f(ushort(h ? (s >> 16) : (s & 0xffffu))); + acc = fma_ftz(scale, fma_ftz(xdd[g], float(P), -mul_ftz(xs[g], 1.5f)), acc); + } + } + red[sg][lane] = acc; + threadgroup_barrier(mem_flags::mem_threadgroup); + if (sg != 0) return; + float v = add_ftz(add_ftz(add_ftz(red[0][lane], red[1][lane]), red[2][lane]), red[3][lane]); + if (row >= n_rows || id < 0) v = neg_inf(); + float m = v; + for (ushort o = 16; o > 0; o >>= 1) m = max_ftz(m, shfl_xor(m, o)); + const float e = warp_sum_ftz(v > neg_inf() ? expf_ftz(add_ftz(v, -m)) : 0.0f); + device float2* cand = scratch; + device float2* part = scratch + ntc * PX_PER; + if (lane == 0) part[tile] = float2(cuda_nan(m), cuda_nan(e)); + for (int k = 0; k < PX_PER; ++k) { // the tile's best, then the next: a butterfly argmax, ties to the lower row + float bv = v; + int bi = lane; + for (ushort o = 16; o > 0; o >>= 1) { + const float ov = shfl_xor(bv, o); + const int oi = simd_shuffle_xor(bi, o); + if (ov > bv || (ov == bv && oi < bi)) { bv = ov; bi = oi; } + } + if (lane == 0) + cand[tile * uint(PX_PER) + uint(k)] = float2(cuda_nan(bv), as_type(int(tile) * 32 + bi)); + if (int(lane) == bi) v = neg_inf(); + } +} + +// q5k_proxy_final_kernel (q5k_head.cu:464-496) with px::collect and px::pick (head_proxy.cuh:169-240): one threadgroup +// of 512 threads (16 SIMD-groups) after the score pass. collect: m, the best approximate score over the candidates +// (FMNMX.FTZ), then every candidate above -inf and at least FADD.FTZ(m, -5) into the list, at most 64 (the others are +// dropped); each listed row is rescored by the head's own row (q5k_row: the Q5_K head's bits, a SIMD-group per row); +// pick (SIMD-group 0): the largest exact score, the lowest row on ties; the sum of the tiles' partials rescaled, +// FFMA.FTZ(sum_t, expf_ftz(m_t - best), acc) where sum_t > 0, plus each listed row's +// FADD.FTZ(expf_ftz(exact - best), -expf_ftz(approx - best)), in lane order, then the butterfly; the probability is +// rcp_ftz(max_ftz(sum, the pick's own term 1)). When every row is masked: map[0] (0 when negative), probability 1. +// The list's order: basalt fills it with a shared-memory atomicAdd, which nvcc aggregates per warp (VOTEU.ANY, POPC, +// one ATOMS.ADD per request, each requesting lane at base + its rank among them), the requests taking slots in arrival +// order. The port fixes that order to ascending candidate index (pass k of the 512-strided loop, SIMD-groups 0..15, +// lanes in order), one of the orders basalt's kernel produces, so the list, the rows rescored when more than 64 +// qualify and the probability's last bits repeat run to run (q5k_head.md section 4). The column is read from device +// memory (basalt stages it in shared memory: not arithmetic). +kernel void basalt_q5k_proxy_final(device const ushort* w [[buffer(0)]], device const uint* x [[buffer(1)]], + device const int* map [[buffer(2)]], device const float2* scratch [[buffer(3)]], + device int* out_id [[buffer(4)]], device float* out_prob [[buffer(5)]], + constant PxParams& p [[buffer(6)]], ushort tid [[thread_index_in_threadgroup]], + ushort lane [[thread_index_in_simdgroup]], + ushort sg [[simdgroup_index_in_threadgroup]]) { + threadgroup float wmax[16]; + threadgroup int counts[16]; + threadgroup int list[PX_MAX_CAND]; + threadgroup float lp[PX_MAX_CAND], ex[PX_MAX_CAND]; + const int n_tiles = int(px_tiles(p.n_rows)), nc = n_tiles * PX_PER; + device const float2* cand = scratch; + device const float2* part = scratch + px_tiles(p.n_cap) * PX_PER; + float m = neg_inf(); + for (int i = tid; i < nc; i += 512) m = max_ftz(m, cand[i].x); + for (ushort o = 16; o > 0; o >>= 1) m = max_ftz(m, shfl_xor(m, o)); + if (lane == 0) wmax[sg] = m; + threadgroup_barrier(mem_flags::mem_threadgroup); + m = wmax[0]; + for (int i = 1; i < 16; ++i) m = max_ftz(m, wmax[i]); + if (m == neg_inf()) { // every row is masked + if (tid == 0) { + *out_id = map[0] < 0 ? 0 : map[0]; + *out_prob = 1.0f; + } + return; + } + const float lo = add_ftz(m, -5.0f); // m - kDelta + int cnt = 0; + for (int i0 = 0; i0 < nc; i0 += 512) { + const int i = i0 + int(tid); + const float2 c = i < nc ? cand[i] : float2(neg_inf(), 0.0f); + const int take = c.x > neg_inf() && c.x >= lo ? 1 : 0; + const int rank = simd_prefix_exclusive_sum(take); // POPC(ballot & lanemask_lt): lane order + const int total = simd_sum(take); + if (lane == 0) counts[sg] = total; + threadgroup_barrier(mem_flags::mem_threadgroup); + int slot = cnt + rank, all = 0; + for (int k = 0; k < 16; ++k) { + slot += k < int(sg) ? counts[k] : 0; + all += counts[k]; + } + if (take != 0 && slot < PX_MAX_CAND) { + list[slot] = as_type(c.y); + lp[slot] = c.x; + } + cnt += all; + threadgroup_barrier(mem_flags::mem_threadgroup); + } + const int n = cnt < PX_MAX_CAND ? cnt : PX_MAX_CAND; + for (int c = sg; c < n; c += 16) { + float t[1]; + q5k_row<1>(w + ulong(list[c]) * ulong(10 * Q5K_USHORTS), x, 80, 10, int(lane), t); + if (lane == 0) ex[c] = t[0]; + } + threadgroup_barrier(mem_flags::mem_threadgroup); + if (sg != 0) return; + float bv = neg_inf(); + int bi = TOP_NONE; + for (int c = lane; c < n; c += 32) + if (ex[c] > bv || (ex[c] == bv && list[c] < bi)) { bv = ex[c]; bi = list[c]; } + for (ushort o = 16; o > 0; o >>= 1) { + const float ov = shfl_xor(bv, o); + const int oi = simd_shuffle_xor(bi, o); + if (ov > bv || (ov == bv && oi < bi)) { bv = ov; bi = oi; } + } + float sum = 0.0f; + for (int t = lane; t < n_tiles; t += 32) { + const float2 q = part[t]; + if (q.y > 0.0f) sum = fma_ftz(q.y, expf_ftz(add_ftz(q.x, -bv)), sum); + } + for (int c = lane; c < n; c += 32) + sum = add_ftz(sum, add_ftz(expf_ftz(add_ftz(ex[c], -bv)), -expf_ftz(add_ftz(lp[c], -bv)))); + sum = warp_sum_ftz(sum); + if (lane == 0) { + float one = 0.0f; // the pick's own term is exactly 1 + for (int c = 0; c < n; ++c) + if (list[c] == bi) one = 1.0f; + *out_id = map[bi < TOP_NONE ? bi : 0]; + *out_prob = rcp_ftz(max_ftz(sum, one)); + } +} diff --git a/kernels/common/basalt_q8_1.metal b/kernels/common/basalt_q8_1.metal new file mode 100644 index 00000000..14a60c51 --- /dev/null +++ b/kernels/common/basalt_q8_1.metal @@ -0,0 +1,230 @@ +// Copyright (c) 2023-2026 The ggml authors (MIT) +// Copyright (c) 2026 Jesús Gulfo (MIT) +// Adapted from basalt (jesdga95/basalt) src/kernels/cuda/native_mmvq.cu:146-177, src/kernels/cuda/iq_kernels.cu:1880-1900 +// and include/basalt/kernels/q8_1_finite.hpp @ b4c63b55754637f4c72ad53a0f791d425f71eb36 (MIT; third_party/NOTICE), +// which adapt ggml-org/llama.cpp ggml/src/ggml-cuda/quantize.cu @ 3cf03257f219afbe7334045ff7c6a06ac68c627d (MIT; +// third_party/NOTICE). +// +// basalt's q8_1 activation quantizers. A q8_1 block is 36 bytes: the fp16 scale d (bytes 0-1), the fp16 sum s of the +// block's 32 raw values (bytes 2-3), 32 int8 codes (bytes 4-35); column j's blocks follow column j - 1's, so a vector +// of ncols * n_in values (n_in % 32 == 0) is ncols columns. One thread per value, 256 per threadgroup, SIMD-group = +// block (whole SIMD-groups past the end return). Needs basalt_fp.metal ahead of it. A NaN in d or s is stored as +// sm_120's fp16 0x7fff (cuda_nan_f16; docs/research/basalt-nvcc/nan.md); a NaN quotient's code is 0, as on sm_120. +// +// - native_quantize_q8_1: the sequence nvcc compiles for native_mmvq.cu (--use_fast_math; matvec.md section 1): +// flush-to-zero abs, max and add; d = fl(amax * fl(1/127)) (ptxas replaces the approximate division by 127 with +// this multiply); the codes' xi / d as MUFU.RCP then FMUL.FTZ, here the correctly rounded reciprocal and the same +// multiply; roundf; the +-127 clamp with NaN to 0. +// - native_swiglu_quantize_q8_1: the shared expert's SwiGLU value (native_mmvq.cu:170; matvec.md section 2), then the +// native sequence. __expf is MUFU.EX2 of fl(g * -log2 e), here fast::exp2 of the same product. +// - quantize_q8_1: quantize_q8_1_kernel (iq_kernels.cu, nvcc's IEEE defaults; matvec.md section 3): correctly rounded +// divisions and no flushing. This GPU flushes subnormal inputs and results of add and division, and its fmax +// compares a subnormal as zero, returning the second operand of a tie rather than the larger +// (tests/kernels/test_basalt_platform.py), so wherever a subnormal can occur the IEEE result is rebuilt from integer +// operations: amax as the largest bit pattern, the block sum and the codes on operands scaled by 2^64, d = amax / 127 +// on the subnormal grid by integer division. Above 2^-100 every one of these is the plain operation. The IEEE +// helpers (ieee_add, ieee_mul, ieee_div127, ieee_rcp, ieee_fma, ieee_div, warp_sum_ieee) serve every IEEE-built +// port kernel. +#pragma STDC FP_CONTRACT OFF + +struct Q81Params { uint n; uint pad0; uint pad1; uint pad2; }; // n: values (ncols * n_in), a multiple of 32 + +constant constexpr float Q8_1_HALF_MAX = 65504.0f; + +static inline float q8_1_finite(float v) { return fabs(v) > Q8_1_HALF_MAX ? copysign(Q8_1_HALF_MAX, v) : v; } + +// (int8_t) of the clamped roundf: q > 127 -> 127, q < -127 -> -127, NaN -> 0 (F2I.TRUNC.NTZ / cvt.rzi of NaN). +static inline char q8_1_code(float q) { + return isnan(q) ? char(0) : char(int(q > 127.0f ? 127.0f : q < -127.0f ? -127.0f : q)); +} + +// q8_1_ds (q8_1_finite.hpp:29-31): make_half2(__float2half(...)), F2FP.F16.F32.PACK_AB on sm_120, whose NaN is 0x7fff +static inline void q8_1_put(device uchar* y, uint i, char code, float d, float sum) { + y[36u * (i / 32u) + 4u + i % 32u] = as_type(code); + if (i % 32u == 0u) { + *(device uint*) (y + 36u * (i / 32u)) = uint(cuda_nan_f16(f16_bits(q8_1_finite(d)))) + | (uint(cuda_nan_f16(f16_bits(q8_1_finite(sum)))) << 16); + } +} + +// The native sequence for value xi of block i / 32 (lane i % 32): the device function every native call site +// shares (native_quantize_q8_1, the SwiGLU quantizer, and the fused epilogues that reproduce it). +static inline void q8_1_store_native(float xi, device uchar* y, uint i) { + const float amax = warp_max_ftz(abs_ftz(xi)); + const float sum = warp_sum_ftz(xi); + const float d = q8_1_finite(mul_ftz(amax, as_type(0x3C010204u))); // fl(1/127) + const char code = amax == 0.0f ? char(0) : q8_1_code(round(mul_ftz(xi, rcp_ftz(d)))); + q8_1_put(y, i, code, d, sum); +} + +kernel void native_quantize_q8_1(device const float* x [[buffer(0)]], device uchar* y [[buffer(1)]], + constant Q81Params& p [[buffer(2)]], uint i [[thread_position_in_grid]]) { + if (i >= p.n) return; // n is a multiple of 32: only whole SIMD-groups return + q8_1_store_native(x[i], y, i); +} + +kernel void native_swiglu_quantize_q8_1(device const float* gate [[buffer(0)]], device const float* up [[buffer(1)]], + device uchar* y [[buffer(2)]], constant Q81Params& p [[buffer(3)]], + uint i [[thread_position_in_grid]]) { + if (i >= p.n) return; + const float g = gate[i]; + const float e = ftz(fast::exp2(mul_ftz(g, as_type(0xBFB8AA3Bu)))); // __expf(-g): ex2.approx(g * -log2 e) + const float s = mul_ftz(g, rcp_ftz(add_ftz(1.0f, e))); // __fdividef(g, __fadd_rn(1, e)) + q8_1_store_native(mul_ftz(s, up[i]), y, i); // __fmul_rn(s, up) +} + +// ---- IEEE operations where a subnormal can occur --------------------------------------------------------------- + +constant constexpr uint IEEE_SMALL = 27u << 23; // 2^-100: below it an operand or result may be subnormal + +// x * 2^64, exactly, for |x| < 2^-100 (a subnormal's significand rebuilt as an integer: the hardware would flush it) +static inline float ieee_up64(float x) { + const uint b = as_type(x); + if ((b & 0x7f800000u) != 0u) return x * 0x1p64f; + return copysign(float(b & 0x007fffffu) * 0x1p-85f, x); +} + +// s * 2^-64 rounded as IEEE would: exact when the result is normal; a subnormal result is exact too (see ieee_add) +static inline float ieee_down64(float s) { + if (fabs(s) >= 0x1p-62f || s == 0.0f) return s * 0x1p-64f; + return as_type((as_type(s) & 0x80000000u) | uint(fabs(s) * 0x1p85f)); +} + +// a + b with IEEE subnormals: below 2^-100 both operands are scaled by 2^64 (exactly), added, and scaled back; a sum +// whose exact value is subnormal is representable (Hauser), so the scaled sum is exact and the integer rebuild too. +static inline float ieee_add(float a, float b) { + if ((as_type(a) & 0x7fffffffu) >= IEEE_SMALL || (as_type(b) & 0x7fffffffu) >= IEEE_SMALL) return a + b; + return ieee_down64(ieee_up64(a) + ieee_up64(b)); +} + +// a * b with IEEE subnormals (CUDA's mul.rn.f32 in an IEEE-built kernel). Two operands with nonzero exponent fields +// (normal, infinite or NaN) whose product is at least 2^-125, infinite or NaN take the hardware's correctly rounded +// product. An infinity or NaN against a zero or a subnormal (which the hardware flushes, making a subnormal times inf +// 0 * inf) gives IEEE's result from the bits: NaN (CUDA's canonical 0x7fffffff) for a NaN or a zero operand, else the +// signed infinity. Otherwise (a subnormal operand, or a product the hardware may flush) the product is rebuilt from +// the exact integer product m of the significands: |a * b| = m * 2^e units of 2^-149, rounded to nearest even on the +// grid of its binade (k = 0 is the subnormal grid and binade -126), so that the float's bits are (k << 23) + r for r +// units of 2^(k - 149). +static inline float ieee_mul(float a, float b) { + const float p = a * b; + const uint ab = as_type(a), bb = as_type(b); + uint ea = (ab >> 23) & 0xffu, eb = (bb >> 23) & 0xffu, ma = ab & 0x7fffffu, mb = bb & 0x7fffffu; + if (ea != 0u && eb != 0u && !(fabs(p) < 0x1p-125f)) return p; // p infinite or NaN included + const uint sign = (ab ^ bb) & 0x80000000u; + const bool za = (ea | ma) == 0u, zb = (eb | mb) == 0u; // zeros by their bits (a compare may flush) + if (ea == 0xffu || eb == 0xffu) // the other operand is a zero or a subnormal + return as_type((ea == 0xffu && ma != 0u) || (eb == 0xffu && mb != 0u) || za || zb + ? 0x7fffffffu : sign | 0x7f800000u); + if (za || zb) return as_type(sign); + if (ea == 0u) ea = 1u; else ma |= 0x800000u; + if (eb == 0u) eb = 1u; else mb |= 0x800000u; + const ulong m = ulong(ma) * ulong(mb); + const int e = int(ea + eb) - 151; // |a * b| = m * 2^e units of 2^-149 + const int lead = 63 - int(clz(m)); + const int k = max(0, lead + e - 23); // the grid: 24 significant bits, or 2^-149 + const int s = k - e; // m * 2^e / 2^k = m >> s + ulong r; + if (s <= 0) { + r = m << uint(-s); + } else if (s > 63) { + r = 0; + } else { + r = m >> uint(s); + const ulong rem = m & ((1ul << uint(s)) - 1ul), tie = 1ul << uint(s - 1); + if (rem > tie || (rem == tie && (r & 1ul) != 0ul)) r += 1ul; + } + return as_type(sign | (uint(k) << 23) + uint(r)); // r == 2^24 carries into the exponent +} + +// amax / 127 rounded as IEEE does, for amax >= 0 or NaN, decided on its bits (a compare may flush): the plain division +// from 2^-100 (and for 0 and NaN); from 2^-119, where the quotient is normal, on amax scaled by 2^64; below, on the +// subnormal grid by integer division (127 is odd: no ties). +static inline float ieee_div127(float amax) { + const uint b = as_type(amax); + if (b >= IEEE_SMALL || b == 0u) return amax / 127.0f; + if (b >= (8u << 23)) return (ieee_up64(amax) / 127.0f) * 0x1p-64f; + const uint m = (b & 0x7f800000u) == 0u ? b : ((b & 0x007fffffu) | 0x00800000u) << ((b >> 23) - 1u); + return as_type(m / 127u + (m % 127u >= 64u ? 1u : 0u)); +} + +// 1 / s rounded as IEEE does (rcp.rn.f32 without .ftz) for |s| <= 2^126 (the quantizer's s is at most FLT_MAX / 127), +// an infinity or NaN: below 2^-100 (zero included) on s scaled by 2^64, rcp.rn.f32's own slow path: the correctly +// rounded reciprocal of a normal value, scaled back exactly or overflowing where 1 / s does. +static inline float ieee_rcp(float s) { + if ((as_type(s) & 0x7fffffffu) >= IEEE_SMALL) return 1.0f / s; + return (1.0f / ieee_up64(s)) * 0x1p64f; +} + +// fma(a, n, c) rounded as IEEE does (fma.rn.f32 without .ftz) for an integer n, |n| < 2^24, decided on bits: +// - a and c each zero or at least 2^-100: a * n + c is a multiple of 2^-123, zero or normal: the hardware's fma. +// - a nonzero below 2^-100: |a * n| < 2^-76. With |c| < 2^62, on the operands scaled by 2^64 (exactly): a * n + c is +// a multiple of 2^-149, so a subnormal result is exact in the scaled form and scales back exactly (ieee_down64), and +// a normal one rounds as its scaled form does. With a larger c (or an infinite or NaN one) the sum rounds to c +// whether or not the hardware flushes a: its fma. +// - c nonzero below 2^-100, a zero or at least 2^-100: a finite a * n of zero leaves c. Otherwise |a * n| >= 2^-100 +// (or a is infinite or NaN): the sum is at least 2^-124, and a subnormal c changes its rounding only by breaking a +// tie, as any value of its sign below 2^-123 does: the hardware's fma with c at +-2^-126. +static inline float ieee_fma(float a, float n, float c) { + const uint ua = as_type(a) & 0x7fffffffu, uc = as_type(c) & 0x7fffffffu; + const bool a_ok = ua == 0u || ua >= IEEE_SMALL, c_ok = uc == 0u || uc >= IEEE_SMALL; + if (a_ok && c_ok) return fma(a, n, c); + if (!a_ok) return uc < (189u << 23) ? ieee_down64(fma(ieee_up64(a), n, ieee_up64(c))) : fma(a, n, c); + if ((ua == 0u || n == 0.0f) && ua < 0x7f800000u) return c; + return fma(a, n, uc < 0x00800000u ? copysign(0x1p-126f, c) : c); +} + +// a / b rounded as IEEE does (div.rn.f32 without .ftz) for b >= 1, infinite or NaN (the SwiGLU's 1 + e): the +// hardware's quotient when a or b is infinite or NaN, or when |a| >= 2^-100 and the quotient is at least 2^-125 +// (normal operands and result: Metal's division is IEEE's, tests/kernels/test_basalt_platform.py); a zero a gives its +// signed zero. Otherwise the quotient is below 2^-100 and is rebuilt from the integer quotient of the significands, +// rounded to nearest even on the grid of its binade (k = 0 the subnormal grid), as ieee_mul does. +static inline float ieee_div(float a, float b) { + const float q = a / b; + const uint ab = as_type(a), bb = as_type(b), ua = ab & 0x7fffffffu; + if (ua >= 0x7f800000u || (bb & 0x7f800000u) == 0x7f800000u) return q; + if (ua >= IEEE_SMALL && !(fabs(q) < 0x1p-125f)) return q; + const uint sign = (ab ^ bb) & 0x80000000u; + if (ua == 0u) return as_type(sign); + uint ea = ua >> 23, ma = ua & 0x7fffffu; + if (ea == 0u) ea = 1u; else ma |= 0x800000u; + const int z = int(clz(ma)) - 8; // normalize ma to [2^23, 2^24) + ma <<= uint(z); + const uint mb = (bb & 0x7fffffu) | 0x800000u; + const int s = int(ea) - z - int((bb >> 23) & 0xffu) + 149; // |a / b| = ma / mb * 2^s units of 2^-149 + const int k = max(0, s - (ma < mb ? 1 : 0) - 23); // the grid: 24 significant bits, or 2^-149 + ulong num = ulong(ma), den = ulong(mb); + if (s - k >= 0) num <<= uint(s - k); + else if (k - s < 40) den <<= uint(k - s); + else num = 0ul; + ulong r = num / den; + const ulong rem = num - r * den; + if (2ul * rem > den || (2ul * rem == den && (r & 1ul) != 0ul)) r += 1ul; + return as_type(sign | (uint(k) << 23) + uint(r)); // r == 2^24 carries into the exponent +} + +// basalt's warp_sum with IEEE adds (the XOR butterfly the port shares; lane 0 is a shift-down tree's lane 0 too) +static inline float warp_sum_ieee(float x) { + for (ushort o = 16; o > 0; o >>= 1) x = ieee_add(x, shfl_xor(x, o)); + return x; +} + +static inline void q8_1_store_ieee(float xi, device uchar* y, uint i) { + int key = isnan(xi) ? -1 : int(as_type(fabs(xi))); // fmaxf drops a NaN operand + float sum = xi; + for (ushort o = 16; o > 0; o >>= 1) { + key = max(key, simd_shuffle_xor(key, o)); + sum = ieee_add(sum, shfl_xor(sum, o)); + } + const float amax = key < 0 ? as_type(0x7fffffffu) : as_type(uint(key)); + const bool small = uint(key) < IEEE_SMALL; // NaN (key -1) is not small + const float d = q8_1_finite(ieee_div127(amax)); + char code = char(0); + if (key != 0) code = q8_1_code(round(small ? ieee_up64(xi) / ieee_up64(d) : xi / d)); + q8_1_put(y, i, code, d, sum); +} + +kernel void quantize_q8_1(device const float* x [[buffer(0)]], device uchar* y [[buffer(1)]], + constant Q81Params& p [[buffer(2)]], uint i [[thread_position_in_grid]]) { + if (i >= p.n) return; + q8_1_store_ieee(x[i], y, i); +} diff --git a/kernels/common/basalt_s2_experts.metal b/kernels/common/basalt_s2_experts.metal new file mode 100644 index 00000000..dee3e925 --- /dev/null +++ b/kernels/common/basalt_s2_experts.metal @@ -0,0 +1,337 @@ +// Copyright (c) 2026 Jesús Gulfo (MIT) +// Adapted from basalt (jesdga95/basalt) src/kernels/cuda/s2_expert_grouped.cu:34-46, :104-108, :165-171, :215-279, +// :736-1083 and src/kernels/cuda/quantize_act.cu:74-101 @ b4c63b55754637f4c72ad53a0f791d425f71eb36 (MIT; +// third_party/NOTICE). +// +// The drafter's routed Q2_0 experts (src/core/mtp.cpp:931-935): basalt_s2_group_resident builds the plan on the device, +// basalt_quantize_q8_0_scaled quantizes the activations, then moe_grouped_s2 (s2_expert_grouped.cu:1085-1122) is four +// dispatches in order: basalt_s2_gu, basalt_s2_swiglu, basalt_quantize_q8_0_scaled over the intermediate and +// basalt_s2_down. +// Needs basalt_fp.metal and basalt_q8_1.metal ahead of it. +// +// Both files build with nvcc's IEEE defaults: every float operation is IEEE's, subnormals kept +// (docs/research/basalt-nvcc/s2_experts.md). This GPU flushes subnormals, and here the activation scale is the +// quantizer's fp32 s, any non-negative float, so a subnormal can occur at every rounding site: each goes through +// basalt_q8_1.metal's IEEE helpers (ieee_div127, ieee_rcp, ieee_mul, ieee_fma, ieee_div, warp_sum_ieee), whose +// hardware path is the plain operation (fma() where SASS has FFMA), and every compare that a subnormal could reach is +// on bits. Contraction is off (basalt_fp.metal's pragma). A NaN can come only from FFMA, FADD, FMUL and div.rn.f32 (or +// pass through them), each of which gives sm_120's canonical 0x7fffffff, so every float the gate/up, SwiGLU and down +// kernels store goes through basalt_fp.metal's cuda_nan (this GPU's NaN is 0x7fc00000; +// docs/research/basalt-nvcc/nan.md). +// +// The plan (basalt's): n_groups[0] groups; group g's blob starts at grp_ptr[g] (a table of 64-bit GPU addresses, one a +// group, each 2-byte aligned and inside a buffer the dispatch makes resident, so the blobs may sit in several buffers) +// and owns the entries [grp_start[g], grp_start[g + 1]), of which the kernels take at most GMAX = 8 (basalt's +// min(..., GMAX)). Entry e reads token ent_tok[e]'s activation row (80 blocks of 34 bytes, x 4-byte aligned) with its +// fp32 scales, and writes row ent_dst[e] of `out` (2560 floats). The blob (cpu/expert.hpp, restated at +// s2_expert_grouped.cu:34-46): 1280 gate/up code rows of 640 bytes (row slot 2r is gate row r, 2r + 1 up row r; value +// 4j + k in bits 2k of byte j), 2560 down code rows of 160 bytes, the gate/up fp16 scales (40 a row), the down scales +// (10 a row); a weight is d_w * (code - 1). +// Scratch, basalt's (one buffer, 4-byte aligned, bound at these offsets): gate/up (entry e's gate row at e * 640, its +// up row at (cap + e) * 640 floats), the quantized intermediate (cap * 20 blocks of 34 bytes, from the gate/up bytes +// rounded up to 16), its fp32 scales (cap * 20, from the next multiple of 16). +#pragma STDC FP_CONTRACT OFF + +#define S2_H 2560 +#define S2_FF 640 +#define S2_GMAX 8 // entries a group the kernels take (s2_expert_grouped.cu:742) +#define S2_ROW_GU (S2_H / 4) // bytes of a gate/up code row +#define S2_ROW_D (S2_FF / 4) // bytes of a down code row +#define S2_SC_GU (S2_H / 64) // fp16 scales of a gate/up row +#define S2_SC_D (S2_FF / 64) // of a down row +#define S2_O_D_CODES (2 * S2_FF * S2_ROW_GU) +#define S2_O_GU_SCALES (S2_O_D_CODES + S2_H * S2_ROW_D) +#define S2_O_D_SCALES (S2_O_GU_SCALES + 2 * S2_FF * S2_SC_GU * 2) + +struct Q80Params { ulong n_blocks; ulong pad0; }; // n_blocks: basalt's long long (quantize_act.cu:79) +struct S2Params { uint cap_entries; uint pad0; uint pad1; uint pad2; }; +struct S2ResidentParams { int n; int k_per_tok; uint blob; uint pad0; }; + +// ---- quantize_q8_0_scaled --------------------------------------------------------------------------------------- + +// quantize_q8_0_scaled_warp_kernel (quantize_act.cu:78-101; s2_experts.md section 1): SIMD-group = 34-byte block, +// lane = value; grid ceil(n_blocks * 32 / 256) threadgroups of 256 (whole SIMD-groups past the end return). The block +// index and the offsets are 64-bit, as basalt's long long (:80-83, :89): past 2^32 values the grid's 32-bit +// thread_position_in_grid would wrap. amax is the largest |x| by its bits (fmaxf drops a NaN; an all-NaN block has +// amax NaN and s 0); s = amax / 127 and inv = 1 / s correctly rounded, subnormals kept; t = fl(x * inv), r = fl(t +- +// 0.5) (FMUL then FADD: not fused); the code is (int) r clamped to +-127, NaN to 0. The block's fp16 d is +// f16_from_f32(s) (round to nearest even), the fp32 scale s. +kernel void basalt_quantize_q8_0_scaled(device const float* x [[buffer(0)]], device uchar* blocks [[buffer(1)]], + device float* scales [[buffer(2)]], constant Q80Params& p [[buffer(3)]], + uint tg [[threadgroup_position_in_grid]], uint tpg [[threads_per_threadgroup]], + uint tid [[thread_index_in_threadgroup]]) { + const ulong b = (ulong(tg) * tpg + tid) >> 5; + const uint lane = tid & 31u; + if (b >= p.n_blocks) return; + const float xv = x[b * 32ul + lane]; + int key = isnan(xv) ? -1 : int(as_type(xv) & 0x7fffffffu); + for (ushort o = 16; o > 0; o >>= 1) key = max(key, simd_shuffle_xor(key, o)); + const float s = key > 0 ? ieee_div127(as_type(uint(key))) : 0.0f; // amax > 0.f, by its bits + const float inv = as_type(s) != 0u ? ieee_rcp(s) : 0.0f; // s > 0.f: s is never negative or NaN + device uchar* out = blocks + b * 34ul; + if (lane == 0u) { + scales[b] = s; + const ushort d16 = f16_bits(s); + out[0] = uchar(d16 & 0xffu); + out[1] = uchar(d16 >> 8); + } + const float t = ieee_mul(xv, inv); + const float r = t + (t >= 0.0f ? 0.5f : -0.5f); // a subnormal t gives code 0 whichever way the compare goes + out[2u + lane] = as_type(q8_1_code(r)); +} + +// ---- the plan: moe_group_resident -------------------------------------------------------------------------------- + +// group_resident_kernel (s2_expert_grouped.cu:1033-1073): one threadgroup of 128 over the n <= 128 routed ids; a group +// per distinct expert in first-appearance order, its entries in routing order; group g's blob at base + id * blob +// bytes (base: the resident experts' buffer, bound at its first blob), ent_dst = the routing index, ent_tok = that +// index / k_per_tok; counts = {groups, entries}. Integer work only. +kernel void basalt_s2_group_resident(device const int* ids [[buffer(0)]], device const uchar* base [[buffer(1)]], + device GrpPtr* grp_ptr [[buffer(2)]], device int* grp_start [[buffer(3)]], + device int* counts [[buffer(4)]], device int* ent_dst [[buffer(5)]], + device int* ent_tok [[buffer(6)]], constant S2ResidentParams& p [[buffer(7)]], + ushort tid [[thread_index_in_threadgroup]]) { + threadgroup int e_s[128], first_s[128], size_s[128], gidx_s[128], gstart_s[129]; + const int i = int(tid), n = p.n; + const int e = i < n ? ids[i] : -1; + e_s[i] = e; + threadgroup_barrier(mem_flags::mem_threadgroup); + int first = i, rank = 0, size = 0; + if (i < n) { + for (int j = 0; j < i; ++j) + if (e_s[j] == e) { + if (first == i) first = j; + ++rank; + } + if (first == i) + for (int j = i; j < n; ++j) size += e_s[j] == e; + } + first_s[i] = first; + size_s[i] = (i < n && first == i) ? size : 0; + threadgroup_barrier(mem_flags::mem_threadgroup); + if (i == 0) { + int gi = 0, acc = 0; + for (int j = 0; j < n; ++j) + if (first_s[j] == j) { + gidx_s[j] = gi; + gstart_s[gi] = acc; + grp_ptr[gi].p = (device const ushort*) (base + ulong(long(e_s[j])) * ulong(p.blob)); + grp_start[gi] = acc; + acc += size_s[j]; + ++gi; + } + grp_start[gi] = acc; + counts[0] = gi; + counts[1] = acc; + } + threadgroup_barrier(mem_flags::mem_threadgroup); + if (i < n) { + const int at = gstart_s[gidx_s[first]] + rank; + ent_dst[at] = i; + ent_tok[at] = i / p.k_per_tok; + } +} + +// ---- the grouped kernels' integer parts -------------------------------------------------------------------------- + +// load_x_chunk (s2_expert_grouped.cu:240-270): the 32 int8 of the block_q8_0 at byte xb (64-bit, as basalt's pointer) +// of the 4-byte aligned row words xw as the eight words X[4h + f] = {x[16h + f], x[16h + 4 + f], x[16h + 8 + f], +// x[16h + 12 + f]}, read as nine aligned words (the ninth, inside the row's next block, only when the codes start 2 +// bytes into a word: an even chunk, never a row's last), and their sum hx. +static inline int s2_load_chunk(device const uint* xw, ulong xb, thread int* X) { + const ulong q = xb + 2ul; + const uint off = uint(q & 3ul), sh = off * 8u; + device const uint* w = xw + (q - off) / 4ul; + uint v[9]; + for (int j = 0; j < 8; ++j) v[j] = w[j]; + v[8] = off != 0u ? w[8] : 0u; + int n[8]; + int hx = 0; + for (int j = 0; j < 8; ++j) { + n[j] = int(uint(((ulong(v[j + 1]) << 32) | ulong(v[j])) >> sh)); + hx = dp4a(0x01010101, n[j], hx); + } + for (int h = 0; h < 2; ++h) { + const int t0 = byte_perm(n[4 * h], n[4 * h + 1], 0x5140); + const int t1 = byte_perm(n[4 * h], n[4 * h + 1], 0x7362); + const int t2 = byte_perm(n[4 * h + 2], n[4 * h + 3], 0x5140); + const int t3 = byte_perm(n[4 * h + 2], n[4 * h + 3], 0x7362); + X[4 * h + 0] = byte_perm(t0, t2, 0x5410); + X[4 * h + 1] = byte_perm(t0, t2, 0x7632); + X[4 * h + 2] = byte_perm(t1, t3, 0x5410); + X[4 * h + 3] = byte_perm(t1, t3, 0x7632); + } + return hx; +} + +// stage_chunk (:895-902): chunk i = k * NC + c of a group, its words at xs_w[j * STRIDE + i] and (dx as bits, hx) at +// xs_dh[i]. +template +static inline void s2_stage(device const uint* xw, ulong xb, float dx, threadgroup int* xs_w, threadgroup int2* xs_dh, + int i) { + int X[8]; + const int hx = s2_load_chunk(xw, xb, X); + for (int j = 0; j < 8; ++j) xs_w[j * STRIDE + i] = X[j]; + xs_dh[i] = int2(as_type(dx), hx); +} + +// expand_codes (:221-231): a chunk's 8 code bytes (four 16-bit reads of a 2-byte aligned row: CUDA's uint2 load, the +// same bits) as the eight dp4a operands m[4h + f], byte b the code of value 16h + 4b + f. +static inline void s2_expand(device const ushort* cw, thread int* m) { + const uint x = uint(cw[0]) | (uint(cw[1]) << 16), y = uint(cw[2]) | (uint(cw[3]) << 16), M = 0x03030303u; + m[0] = int(x & M); + m[1] = int((x >> 2) & M); + m[2] = int((x >> 4) & M); + m[3] = int((x >> 6) & M); + m[4] = int(y & M); + m[5] = int((y >> 2) & M); + m[6] = int((y >> 4) & M); + m[7] = int((y >> 6) & M); +} + +// chunk_s (:273-278): sum of code * x over the chunk +static inline int s2_chunk_s(thread const int* m, thread const int* X) { + int s = 0; + for (int j = 0; j < 8; ++j) s = dp4a(m[j], X[j], s); + return s; +} + +// ---- gate / up ----------------------------------------------------------------------------------------------------- + +// gu_grouped_t_kernel (:904-968; s2_experts.md section 2): grid (40, cap_groups) threadgroups of 256; threadgroup +// (bx, g) takes row slots [32 bx, 32 bx + 32) of group g: SIMD-group w the (gate r, up r) pairs w and w + 8. Per +// (row, entry), lane L: the chunks c = L, L + 32, L + 64 (< 80) in order, acc = fma(fl(dw * dx), f(s - hx), acc) from +// +0 (FFMA), then basalt's warp_sum (shift-down; lane 0 is the XOR butterfly's lane 0), lane 0 stores. Activation +// offsets and gate_up indices are 64-bit where basalt's are size_t (:921-922, :963-964). +kernel void basalt_s2_gu(device const GrpPtr* grp_ptr [[buffer(0)]], device const int* grp_start [[buffer(1)]], + device const int* n_groups [[buffer(2)]], device const int* ent_tok [[buffer(3)]], + device const uint* x_q8_0 [[buffer(4)]], device const float* x_scales [[buffer(5)]], + device float* gate_up [[buffer(6)]], constant S2Params& p [[buffer(7)]], + uint2 tg [[threadgroup_position_in_grid]], ushort tid [[thread_index_in_threadgroup]], + ushort lane [[thread_index_in_simdgroup]], ushort warp [[simdgroup_index_in_threadgroup]]) { + constexpr int NC = S2_H / 32; + threadgroup int xs_w[8 * S2_GMAX * NC]; // 20 KB: word j of entry k's chunk c at [j][k * NC + c] + threadgroup int2 xs_dh[S2_GMAX * NC]; // 5 KB: (dx as bits, hx) + const int g = int(tg.y); + if (g >= n_groups[0]) return; + const int e0 = grp_start[g], ne = min(grp_start[g + 1] - e0, S2_GMAX); + for (int i = int(tid); i < ne * NC; i += 256) { + const int k = i / NC, c = i - k * NC; + const int tok = ent_tok[e0 + k]; + s2_stage(x_q8_0, ulong(tok) * NC * 34 + ulong(c) * 34, x_scales[ulong(tok) * NC + ulong(c)], xs_w, + xs_dh, i); + } + threadgroup_barrier(mem_flags::mem_threadgroup); + device const ushort* blob = grp_ptr[g].p; + const int row0 = int(tg.x) * 32; // even: a pair is always (gate r, up r) + for (int pp = int(warp); pp < 16; pp += 8) { + const int i = row0 + 2 * pp; + device const ushort* codes = blob + i * (S2_ROW_GU / 2); + device const ushort* scales = blob + S2_O_GU_SCALES / 2 + i * S2_SC_GU; + int m0[3][8], m1[3][8]; + float dw0[3], dw1[3]; + for (int q = 0; q < 3; ++q) { + const int c = int(lane) + 32 * q; + if (c < NC) { + s2_expand(codes + 4 * c, m0[q]); + s2_expand(codes + S2_ROW_GU / 2 + 4 * c, m1[q]); + dw0[q] = h2f(scales[c >> 1]); + dw1[q] = h2f(scales[S2_SC_GU + (c >> 1)]); + } + } + for (int k = 0; k < ne; ++k) { + float acc0 = 0.0f, acc1 = 0.0f; + for (int q = 0; q < 3; ++q) { + const int c = int(lane) + 32 * q; + if (c >= NC) break; + const int at = k * NC + c; + int X[8]; + for (int j = 0; j < 8; ++j) X[j] = xs_w[j * (S2_GMAX * NC) + at]; + const int2 dh = xs_dh[at]; + const float dx = as_type(dh.x); + acc0 = ieee_fma(ieee_mul(dw0[q], dx), float(s2_chunk_s(m0[q], X) - dh.y), acc0); + acc1 = ieee_fma(ieee_mul(dw1[q], dx), float(s2_chunk_s(m1[q], X) - dh.y), acc1); + } + const float s0 = warp_sum_ieee(acc0), s1 = warp_sum_ieee(acc1); + if (lane == 0) { + const int e = e0 + k, r = i >> 1; + gate_up[ulong(e) * S2_FF + ulong(r)] = cuda_nan(s0); + gate_up[ulong(p.cap_entries) * S2_FF + ulong(e) * S2_FF + ulong(r)] = cuda_nan(s1); + } + } + } +} + +// ---- SwiGLU --------------------------------------------------------------------------------------------------------- + +// swiglu_kernel (:165-171; s2_experts.md section 3): gate_up[i] = (g / (1 + __expf(-g))) * u in place over the gate +// half, every capacity entry (i < cap * 640); grid ceil(cap * 640 / 256) threadgroups of 256; the pair count and i are +// 64-bit, as basalt's long long (:165-166). __expf(-g) is ex2.approx.f32 of fl(g * -log2 e) (expf_neg), the add plain +// (1 + a subnormal e is 1 either way), the division and the product IEEE's. +kernel void basalt_s2_swiglu(device float* gate_up [[buffer(0)]], constant S2Params& p [[buffer(1)]], + uint tg [[threadgroup_position_in_grid]], uint tpg [[threads_per_threadgroup]], + uint tid [[thread_index_in_threadgroup]]) { + const ulong n_pairs = ulong(p.cap_entries) * S2_FF, i = ulong(tg) * tpg + tid; + if (i >= n_pairs) return; + const float g = gate_up[i], u = gate_up[n_pairs + i]; + gate_up[i] = cuda_nan(ieee_mul(ieee_div(g, expf_neg(g) + 1.0f), u)); +} + +// ---- down ----------------------------------------------------------------------------------------------------------- + +// down_grouped_t_kernel (:970-1027; s2_experts.md section 5): grid (40, cap_groups) threadgroups of 256; 64 rows a +// threadgroup, SIMD-group w the row pairs (r, r + 1) w, w + 8, w + 16, w + 24; lane c < 20 holds chunk c: acc = +// fma(fl(dw * dx), f(s - hx), +0), the other lanes +0; warp_sum; lane 0 stores rows r and r + 1 of ent_dst[e]. +// Intermediate offsets and out indices are 64-bit where basalt's are size_t (:986-987, :1021). +kernel void basalt_s2_down(device const GrpPtr* grp_ptr [[buffer(0)]], device const int* grp_start [[buffer(1)]], + device const int* n_groups [[buffer(2)]], device const int* ent_dst [[buffer(3)]], + device const uint* h_q8_0 [[buffer(4)]], device const float* h_scales [[buffer(5)]], + device float* out [[buffer(6)]], uint2 tg [[threadgroup_position_in_grid]], + ushort tid [[thread_index_in_threadgroup]], ushort lane [[thread_index_in_simdgroup]], + ushort warp [[simdgroup_index_in_threadgroup]]) { + constexpr int NC = S2_FF / 32; + threadgroup int hs_w[8 * S2_GMAX * NC]; + threadgroup int2 hs_dh[S2_GMAX * NC]; + const int g = int(tg.y); + if (g >= n_groups[0]) return; + const int e0 = grp_start[g], ne = min(grp_start[g + 1] - e0, S2_GMAX); + for (int i = int(tid); i < ne * NC; i += 256) { + const int k = i / NC, c = i - k * NC; + const ulong e = ulong(e0 + k); + s2_stage(h_q8_0, e * NC * 34 + ulong(c) * 34, h_scales[e * NC + ulong(c)], hs_w, hs_dh, i); + } + threadgroup_barrier(mem_flags::mem_threadgroup); + device const ushort* blob = grp_ptr[g].p; + const int row0 = int(tg.x) * 64, c = int(lane); + for (int pp = int(warp); pp < 32; pp += 8) { + const int r = row0 + 2 * pp; + device const ushort* codes = blob + S2_O_D_CODES / 2 + r * (S2_ROW_D / 2); + device const ushort* scales = blob + S2_O_D_SCALES / 2 + r * S2_SC_D; + int m0[8], m1[8]; + float dw0 = 0.0f, dw1 = 0.0f; + if (c < NC) { + s2_expand(codes + 4 * c, m0); + s2_expand(codes + S2_ROW_D / 2 + 4 * c, m1); + dw0 = h2f(scales[c >> 1]); + dw1 = h2f(scales[S2_SC_D + (c >> 1)]); + } + for (int k = 0; k < ne; ++k) { + float acc0 = 0.0f, acc1 = 0.0f; + if (c < NC) { + const int at = k * NC + c; + int X[8]; + for (int j = 0; j < 8; ++j) X[j] = hs_w[j * (S2_GMAX * NC) + at]; + const int2 dh = hs_dh[at]; + const float dx = as_type(dh.x); + acc0 = ieee_fma(ieee_mul(dw0, dx), float(s2_chunk_s(m0, X) - dh.y), acc0); + acc1 = ieee_fma(ieee_mul(dw1, dx), float(s2_chunk_s(m1, X) - dh.y), acc1); + } + const float s0 = warp_sum_ieee(acc0), s1 = warp_sum_ieee(acc1); + if (lane == 0) { + const ulong o = ulong(ent_dst[e0 + k]) * S2_H + ulong(r); + out[o] = cuda_nan(s0); + out[o + 1] = cuda_nan(s1); + } + } + } +} diff --git a/monolith/compiler/cpu_tier.py b/monolith/compiler/cpu_tier.py new file mode 100644 index 00000000..eaccf932 --- /dev/null +++ b/monolith/compiler/cpu_tier.py @@ -0,0 +1,86 @@ +"""The host points that drive the CPU expert tier, and the choice of whether to install any. + +basalt compiles its decode graph in two forms and picks between them on one flag. With every expert resident it +runs the **zero-doorbell** graph: the whole step is on the GPU and the host services nothing. When the cache comes +up short it runs the **DecMoe** graph instead, whose window services every MoE layer, every window, whether or not +that layer has a CPU entry (``src/core/verify.cpp:876-907`` on ``all_resident_``). + +The distinction is not a performance detail, which is why this module exists rather than a flag somewhere in a +builder. A port that installs a point in every MoE layer unconditionally is not a slow exact port: it is a +**different program** from the one basalt runs in the identity configuration, and it spends the price below of GPU +idle to be different. + +**The price.** Each host handoff idles the GPU for a median of 136 to 137 microseconds as built, against 0.5 +microseconds at a plain pass boundary (``docs/design/flash-next.md:616-622`` [M]). At 48 MoE layers that is 6.5 to +6.6 milliseconds per step, spent whether or not a layer has any CPU work to do. The decode budget it comes out of +is the whole reason the zero-doorbell form exists. + +So: ``decode_host_points`` returns an empty list when every expert is resident, and one point per MoE layer when +the cache is short. The choice is made once, when the program is built from the pack and the profile, not by a +predicate the step evaluates. +""" + +from __future__ import annotations + +from dataclasses import dataclass +from typing import List, Sequence + +from monolith.runtime.program import HostPoint + +# What one handoff costs, measured on the 48 GB 40-core M3 Max (docs/design/flash-next.md:616-622, probes/p16). +HANDOFF_IDLE_US = 136.5 + + +@dataclass(frozen=True) +class MoeLayerWindow: + """Where one MoE layer's host point sits, as op boundaries of the step. + + ``publish`` goes after the layer's routing and planning op, so the tables the task reads are written before it + starts; ``wait`` goes at the combine, so the layer's **resident** experts are the ops of ``[publish, wait)`` + that run on the GPU beside the pool. The window is what buys the handoff back: without ops in it the GPU idles + for the whole of the task. + """ + publish: int + wait: int + + def __post_init__(self) -> None: + if self.publish > self.wait: + raise ValueError(f"a layer window needs publish <= wait, got {self.publish} > {self.wait}") + + +def decode_host_points( + layers: Sequence[MoeLayerWindow], + *, + all_resident: bool, + task: str = "cpu_experts", + staging: str = "cpu_staging", + step_state: str = "step_state", +) -> List[HostPoint]: + """The decode program's host points, in program order. + + ``all_resident`` is basalt's own flag: true when the cache holds every expert, which is the configuration the + identity tests run in. It selects between the two forms and nothing else does. + + ``staging`` is the buffer the pool writes its rows into. It is named in each point's ``writes`` so that + ``Program.check_host_points`` refuses any op of the window that reads it; the step-state buffer is named in + ``reads`` for the same reason, since the task reads the step's own state. ``step_state`` takes the program's + own ``Program.step_state`` name rather than assuming the default, because a program that renamed it would get + points declaring a buffer it does not have, which ``check_host_points`` rejects, or a buffer that is not the + one its ops actually write. + """ + if all_resident: + return [] # the zero-doorbell graph: the host services nothing + return [ + HostPoint(task=task, publish=w.publish, wait=w.wait, writes=[staging], reads=[step_state]) + for w in layers + ] + + +def handoff_cost_ms(points: Sequence[HostPoint]) -> float: + """What installing these points costs the step in GPU idle, in milliseconds, at the measured median handoff. + + This is a floor and not an estimate of the step: it counts only the idle each handoff imposes, and says + nothing about the CPU work the task then does. It exists so a builder can report the price of the form it + chose rather than leave it implicit. + """ + return len(points) * HANDOFF_IDLE_US / 1000.0 diff --git a/monolith/compiler/emit.py b/monolith/compiler/emit.py index 4387626b..9556db90 100644 --- a/monolith/compiler/emit.py +++ b/monolith/compiler/emit.py @@ -5,7 +5,8 @@ ``rmsnorm_stat`` → ``norm_apply`` → plain GEMV (the fuse pass that hoists the statistic into the producer's epilogue comes next), kernels specialized to the program's static ``T`` (a prefill program at ``T = P`` and a decode program at ``T = 1`` share their buffers by name), weights and constants -mapped straight from the pack file in page-aligned windows (no copy). The op handlers below are the only place an op +mapped straight from the pack file in page-aligned windows (no copy), or from a ``.basalt`` file through +:class:`~monolith.packs.basalt.BasaltSource` (``basalt_windows``). The op handlers below are the only place an op kind meets a kernel source; a new op kind adds a handler and a kernel, nothing else. Row counts. A value's leading dimension is the ``T`` symbol (the step's tokens, ``StepState.t_this_step``), the @@ -16,10 +17,13 @@ from __future__ import annotations +import hashlib +import json + from ..backends.metal.context import dispatch, current_backend from dataclasses import dataclass, field -from typing import Any, Dict, List, Optional, Sequence, Set, Tuple, Union +from typing import Any, Dict, Iterable, List, Optional, Sequence, Set, Tuple, Union from .. import kernels from ..core.dtypes import DType @@ -30,10 +34,12 @@ from ..formats import FORMATS from ..formats.blm import PackInfo from ..nn.module import Model +from ..packs.basalt import BasaltSource from ..packs.packer import ALIGN, PackFile from ..runtime.program import BufferSpec, KernelSpec, OpSpec, Program from .barriers import place_barriers from .coverage import check_coverage +from .emit_basalt import BASALT_HANDLERS from .passes import DEFAULT_PASSES WINDOW_BYTES = 2 << 30 # pack windows: ICB bind offsets are 32-bit (design §5.1) @@ -47,7 +53,7 @@ @dataclass class _Ctx: program: Program - packs: List[PackFile] + packs: List[Union[PackFile, BasaltSource]] layout: StepStateLayout t: int n_sg: int @@ -214,11 +220,71 @@ def _size_stat(ctx: _Ctx, name: str) -> None: ctx.program.buffers[name] = BufferSpec(max(rows * ctx.stat_parts[name] * 4, 16), None, "arena") +def basalt_windows(src: BasaltSource, values: Iterable[Value], t: int = 1 + ) -> Tuple[Dict[str, BufferSpec], Dict[str, Tuple[str, int]]]: + """``(buffers, {value name: (buffer, byte offset)})`` for the weight and constant values ``src`` holds: read-only + windows of the file over only the entries these values bind (a program maps none of the bytes it never reads), one + per run of 16 KiB pages they touch, cut at every whole page none touches and wherever a window would pass + ``WINDOW_BYTES``. Each window starts and ends on a page inside the file (the file's last partial page is never + mapped) and is named by a digest of the file's resolved path, its offset and its size, so programs that share a + session's buffers by name share only identical ranges. Refuses a value its entry refuses (``BasaltSource.bind``), + an entry not at a multiple of 16 bytes (windows start on pages, so this is the binding offset's alignment, which + covers every kernel's), and an entry whose pages pass ``WINDOW_BYTES`` or the end of the file. With + ``src.copy`` each entry is instead a buffer of exactly its bytes, bound at 0 (the test mode).""" + want: Dict[str, Any] = {} + for v in values: + if (v.is_weight or v.is_const) and v.name in src: + e = src.bind(v.name, v.format if v.is_weight else v.dtype.short, bind(v.shape, step_bindings(t))) + if e.offset % 16: + raise ValueError(f"emit: {v.name!r} lies at {e.offset} in {src.path}, not a multiple of 16 bytes") + lo, hi = e.offset - e.offset % ALIGN, -(-(e.offset + e.nbytes) // ALIGN) * ALIGN + if hi - lo > WINDOW_BYTES: + raise ValueError(f"emit: {v.name!r} spans {hi - lo} bytes of pages; a window holds at most {WINDOW_BYTES}") + if hi > src.file_bytes: + raise ValueError(f"emit: {v.name!r} ends in the last page of {src.path}, which runs past the end of the " + f"file ({src.file_bytes} bytes); a window ends on a page inside it") + want[v.name] = e + + def name(prefix: str, offset: int, nbytes: int) -> str: + return f"{prefix}.{hashlib.sha256(json.dumps([src.path, offset, nbytes]).encode()).hexdigest()[:16]}" + + buffers: Dict[str, BufferSpec] = {} + bound: Dict[str, Tuple[str, int]] = {} + if src.copy: + for vname, e in want.items(): + b = name("basalt.copy", e.offset, e.nbytes) + buffers[b] = BufferSpec(e.nbytes, src.read(e), "weights") + bound[vname] = (b, 0) + return buffers, bound + runs: List[Tuple[int, int, List[str]]] = [] # (first page, end page, value names) + for vname, e in sorted(want.items(), key=lambda kv: (kv[1].offset, kv[1].nbytes)): + lo, hi = e.offset - e.offset % ALIGN, -(-(e.offset + e.nbytes) // ALIGN) * ALIGN + if runs and lo <= runs[-1][1] and max(hi, runs[-1][1]) - runs[-1][0] <= WINDOW_BYTES: + runs[-1] = (runs[-1][0], max(hi, runs[-1][1]), runs[-1][2] + [vname]) + else: + runs.append((lo, hi, [vname])) + for lo, hi, members in runs: + b = name("basalt", lo, hi - lo) + buffers[b] = BufferSpec(hi - lo, None, "weights", src.path, lo) + for vname in members: + bound[vname] = (b, want[vname].offset - lo) + return buffers, bound + + def _pack_windows(ctx: _Ctx) -> None: """Group each pack's slabs, row-scale tables and aux entries into ≤ 2 GiB file-backed windows (the target's pack - first, then a drafter's; entry names are distinct across them).""" + first, then a drafter's; entry names are distinct across them); a ``.basalt`` source maps only the values the + graph binds (``basalt_windows``).""" n_win = 0 for pk in ctx.packs: + if isinstance(pk, BasaltSource): + buffers, bound = basalt_windows(pk, ctx.values.values(), ctx.t) + for name in bound: + if name in ctx.windows: + raise ValueError(f"emit: the packs both hold an entry named {name!r}") + ctx.program.buffers.update(buffers) + ctx.windows.update(bound) + continue path = pk.dir / pk.manifest["pack"] entries: List[Tuple[int, int, str, str]] = [] # (offset, nbytes, kind, name) for s in pk.manifest["slabs"]: @@ -1364,11 +1430,11 @@ def _moe_combine(ctx: _Ctx, op: Op) -> None: "gqa_decode": _gqa, "gqa_merge": _gqa_merge, "gdn_mixer": _gdn, "gdn_commit": _gdn, "gdn_norm": _gdn_norm, "argmax": _argmax, "sample": _sample, "tap_concat": _tap_concat, "draft_attn": _draft_attn, "confidence": _confidence, "verify_select": _verify_select, - "accept_scan": _accept_scan} + "accept_scan": _accept_scan, **BASALT_HANDLERS} @dispatch("emit") -def emit_program(g: Graph, *, pack: Union[PackFile, Sequence[PackFile]], profile: Profile, t: Optional[int] = None, dynamic_t: bool = False, +def emit_program(g: Graph, *, pack: Union[PackFile, BasaltSource, Sequence[Union[PackFile, BasaltSource]]], profile: Profile, t: Optional[int] = None, dynamic_t: bool = False, layout: Optional[StepStateLayout] = None, eos: Union[int, Sequence[int]] = -1, ring_capacity: int = 4096, tg: int = 384, tuner: Any = None, tail: Optional[str] = "advance", token: Optional[Value] = None, speculative: bool = False, barriers: str = "minimal", attention: Optional[str] = None, accelerator: Optional[str] = None, t_min: int = 1, commute_norm: bool = True, @@ -1377,7 +1443,7 @@ def emit_program(g: Graph, *, pack: Union[PackFile, Sequence[PackFile]], profile ``T = t`` (kernels specialized, T from params), or with ``dynamic_t`` for any T ≤ ``t`` read from StepState at run time. The dynamic bound defaults to ``layout.t_max``; an explicit smaller ``t`` lets programs share a StepState ABI without sharing their activation sizes. ``pack`` is the pack (or the packs: the target's, then a drafter's) - the graph's weights and constants come from. ``tail="advance"`` appends the step's advance on ``token`` (the + the graph's weights and constants come from; a :class:`BasaltSource` serves as one. ``tail="advance"`` appends the step's advance on ``token`` (the sampled tokens); ``None`` leaves the closing op to the graph (a program with the DSpark round emits its own ``accept_scan``). ``barriers``: ``"minimal"`` keeps an ICB barrier only where a dependency needs one (the barrier pass), ``"all"`` after every op (v0; the A/B baseline). The profile's ``sibling_order`` decides whether a @@ -1387,7 +1453,7 @@ def emit_program(g: Graph, *, pack: Union[PackFile, Sequence[PackFile]], profile static T=8, matching GDN shapes and a complete native MLP normalization boundary. Set it false to retain original dispatches; dynamic/speculative programs are unchanged.""" layout = layout or StepStateLayout() - packs = [pack] if isinstance(pack, PackFile) else list(pack) + packs = [pack] if isinstance(pack, (PackFile, BasaltSource)) else list(pack) if dynamic_t and t is None: t = layout.t_max if t is None or t < 1 or t > layout.t_max: diff --git a/monolith/compiler/emit_basalt.py b/monolith/compiler/emit_basalt.py new file mode 100644 index 00000000..c5f7970d --- /dev/null +++ b/monolith/compiler/emit_basalt.py @@ -0,0 +1,176 @@ +"""The emitter's handlers for basalt's ops (``monolith/ops/basalt.py``), merged into ``emit.HANDLERS``. Each handler +emits one dispatch with the macros, grid, threadgroup and params of ``monolith/kernels.py``'s builders, after the +checks basalt's launchers make (shapes, column counts, pointer alignment) and the ones its call sites satisfy (the IEEE +q8_1 rows feed only the routed experts; outputs are contiguous columns); a static program only (one per window width). +""" + +# The launcher checks are adapted from basalt (jesdga95/basalt) src/kernels/cuda/native_mmvq.cu:1465-1475, :1490-1494, +# :1549-1552 and :1563-1568, src/kernels/cuda/dense_tc.cu:1077-1082 and :1107-1113, +# src/kernels/cuda/native_bf16.cu:139-171 and src/kernels/cuda/iq_kernels.cu:2450-2455 @ +# b4c63b55754637f4c72ad53a0f791d425f71eb36 (MIT; third_party/NOTICE). + +from __future__ import annotations + +from typing import TYPE_CHECKING, Dict, Sequence, Tuple + +from .. import kernels +from ..core.dtypes import DType +from ..core.ir import Op, Value +from ..formats.gguf import GGML_TYPES, ggml_row_bytes + +if TYPE_CHECKING: + from .emit import _Ctx + +GGML_IDS = {name: type_id for type_id, (name, _, _) in GGML_TYPES.items()} +Q8_1_KERNELS = {"native": "native_quantize_q8_1", "swiglu": "native_swiglu_quantize_q8_1", "ieee": "quantize_q8_1"} +IEEE_READERS = ("basalt_experts",) # the routed experts (OI-013 PR 4): basalt's only reader of the IEEE rows (F4) + + +def _columns(ctx: _Ctx, op: Op) -> int: + """T, the window's columns: the first output's rows. basalt bakes T into each width's graph; a dynamic-T program + would bind StepState, which none of its kernels reads, and run every narrower window at the compiled width.""" + if ctx.dynamic_t: + raise ValueError(f"{op.kind}: basalt's kernels take the window's width as a compiled count, one static program " + "per width; a dynamic-T program cannot run them") + return ctx.rows_of(op)[0] + + +def _expect(ctx: _Ctx, op: Op, v: Value, shape: Tuple[int, int], dtype: DType, why: str) -> None: + if (ctx.shape(v), v.dtype) != (shape, dtype): + raise ValueError(f"{op.kind}: {v.name!r} is {v.dtype} {list(ctx.shape(v))}, not {dtype} {list(shape)} ({why})") + + +def _weight(ctx: _Ctx, op: Op, w: Value, types: Sequence[int]) -> Tuple[int, int, int]: + """``(ggml type id, n_out, n_in)`` of a weight as shipped: a weight whose format, or a constant whose dtype, names a + ggml type in ``types``, ``[n_out, n_in]`` values, and not a pack's block-lane-major slab (a ``bf16`` slab's rows + are re-laid-out; the kernels read rows as stored). A pack's aux entry holds exactly those rows, as a ``.basalt`` + entry does (``BasaltSource.bind``): the kernels read every row, and a shorter entry would send them past it.""" + name = w.format if w.is_weight else w.dtype.short if w.is_const else None + shape = ctx.shape(w) + if GGML_IDS.get(name) not in types or len(shape) != 2 or min(shape) < 1: + raise ValueError(f"{op.kind}: the weight {w.name!r} ({name} {list(shape)}) is not a weight or constant " + f"[n_out, n_in] of ggml type {sorted(GGML_TYPES[t][0] for t in types)}") + if any(w.name in pk.slabs for pk in ctx.packs): + raise ValueError(f"{op.kind}: the weight {w.name!r} is a block-lane-major pack slab, not rows as stored") + tid, (n_out, n_in) = GGML_IDS[name], shape + aux = next((pk.aux[w.name] for pk in ctx.packs if w.name in pk.aux), None) + if aux is not None and int(aux["nbytes"]) != (need := n_out * ggml_row_bytes(tid, n_in)): + raise ValueError(f"{op.kind}: the weight {w.name!r} is {need} bytes of {name} {list(shape)}, but its pack " + f"entry holds {aux['nbytes']}") + return tid, n_out, n_in + + +def _bind(ctx: _Ctx, op: Op, slot: int, v: Value, align: int) -> Tuple[int, str, int]: + """``(slot, buffer, offset)`` of ``v``, refused unless the offset is a multiple of ``align`` bytes (basalt's + launchers check most of these pointers, ``ops/basalt.py`` says which; a window's buffer starts on a page).""" + buf, off = ctx.buf(v) + if off % align: + raise ValueError(f"{op.kind}: {v.name!r} binds at byte {off} of {buf}; slot {slot} needs {align}-byte " + "alignment") + return slot, buf, off + + +def _q8_1(ctx: _Ctx, op: Op) -> None: + kind = op.attrs.get("quantizer") + if kind not in Q8_1_KERNELS: + raise ValueError(f"basalt_q8_1: attr quantizer must be one of {sorted(Q8_1_KERNELS)}, got {kind!r}") + t = _columns(ctx, op) + xs, (y,) = list(op.inputs), op.outputs + if len(xs) != (2 if kind == "swiglu" else 1): + raise ValueError(f"basalt_q8_1 {kind}: {len(xs)} inputs") + n_in = ctx.shape(xs[0])[-1] + if n_in < 1 or n_in % 32: + raise ValueError(f"basalt_q8_1: a column of {n_in} values is not whole 32-value blocks") + if kind != "ieee" and t > 8: # validate_shape (native_mmvq.cu:1465-1470); quantize_q8_1_rows has none + raise ValueError(f"basalt_q8_1 {kind}: {t} columns; basalt quantizes 1 to 8") + for x in xs: + _expect(ctx, op, x, (t, n_in), DType.F32, "the quantized columns") + _expect(ctx, op, y, (t, n_in // 32 * kernels.Q8_1_BLOCK_BYTES), DType.U8, "q8_1 rows of the input's columns") + if kind == "ieee": + other = sorted({c.kind for c in y.consumers} - set(IEEE_READERS)) + if other: + raise ValueError(f"basalt_q8_1 ieee: {y.name!r} is read by {other}; basalt's IEEE rows feed only the " + f"routed experts ({', '.join(IEEE_READERS)})") + shared = [y.view_of[0]] if y.view_of else [v.name for v in ctx.values.values() if v.view_of and + v.view_of[0] == y.name] + if shared: # a view's readers are not the base's consumers, nor the base's the view's + raise ValueError(f"basalt_q8_1 ieee: {y.name!r} shares its buffer with {shared}; basalt's IEEE rows are a " + "buffer of their own, read only by the routed experts") + n = t * n_in + k = ctx.kernel("basalt_q8_1", kernels.basalt_q8_1_source(), Q8_1_KERNELS[kind], {}) + prm = ctx.params("basalt_q8_1", kernels.basalt_q8_1_params(n)) + grid, threads = kernels.basalt_q8_1_grid(n) + bindings = [_bind(ctx, op, i, v, 4) for i, v in enumerate(xs + [y])] + ctx.add(k, bindings + [(len(xs) + 1, prm, 0)], (grid, 1, 1), (threads, 1, 1), f"{op.kind}:{kind}", writes=[len(xs)]) + + +def _gemv_values(ctx: _Ctx, op: Op, t: int, xq: Value, n_in: int, ys: Sequence[Value], n_outs: Sequence[int]) -> None: + _expect(ctx, op, xq, (t, n_in // 32 * kernels.Q8_1_BLOCK_BYTES), DType.U8, "q8_1 rows of the weight's columns") + for y, n_out in zip(ys, n_outs): + _expect(ctx, op, y, (t, n_out), DType.F32, "contiguous columns of the weight's rows") + + +def _mmvq(ctx: _Ctx, op: Op) -> None: + t = _columns(ctx, op) + (xq, w), (y,) = op.inputs, op.outputs + tid, n_out, n_in = _weight(ctx, op, w, kernels.MMVQ_TRAITS) + macros = kernels.basalt_mmvq_macros(tid, n_in, t) + _gemv_values(ctx, op, t, xq, n_in, [y], [n_out]) + grid, threads = kernels.basalt_mmvq_grid(macros, n_out) + k = ctx.kernel("basalt_mmvq", kernels.basalt_mmvq_source(), "basalt_mmvq", macros) + prm = ctx.params("basalt_mmvq", kernels.basalt_mmvq_params(n_in, n_out)) + ctx.add(k, [_bind(ctx, op, 0, w, 4), _bind(ctx, op, 1, xq, 4), _bind(ctx, op, 2, y, 4), (3, prm, 0)], + (grid, 1, 1), (threads, 1, 1), f"{op.kind}:{w.name}", writes=[2]) + + +def _dense_tc(ctx: _Ctx, op: Op) -> None: + t = _columns(ctx, op) + (xq, w), (y,) = op.inputs, op.outputs + tid, n_out, n_in = _weight(ctx, op, w, kernels.DENSE_TC_SB) + macros = kernels.basalt_dense_tc_macros(tid, n_in, n_out) # basalt's order: 170 multiprocessors, aligned + _gemv_values(ctx, op, t, xq, n_in, [y], [n_out]) + grid, threads = kernels.basalt_dense_tc_grid(macros, n_out) + k = ctx.kernel("basalt_dense_tc", kernels.basalt_dense_tc_source(), "basalt_dense_tc", macros) + prm = ctx.params("basalt_dense_tc", kernels.basalt_dense_tc_params(n_in, n_out, t)) + ctx.add(k, [_bind(ctx, op, 0, w, 4), _bind(ctx, op, 1, xq, 4), _bind(ctx, op, 2, y, 4), (3, prm, 0)], + (grid, 1, 1), (threads, 1, 1), f"{op.kind}:{w.name}", writes=[2]) + + +def _dense_tc_pair(ctx: _Ctx, op: Op) -> None: + t = _columns(ctx, op) + (xq, w0, w1), (y0, y1) = op.inputs, op.outputs + t0, n_out0, n_in = _weight(ctx, op, w0, kernels.DENSE_TC_SB) + t1, n_out1, n_in1 = _weight(ctx, op, w1, kernels.DENSE_TC_SB) + if n_in1 != n_in: + raise ValueError(f"basalt_dense_tc_pair: {w0.name!r} has {n_in} columns, {w1.name!r} {n_in1}; the pair reads " + "one input") + macros = kernels.basalt_dense_tc_pair_macros(t0, t1, n_in) + _gemv_values(ctx, op, t, xq, n_in, [y0, y1], [n_out0, n_out1]) + grid, threads = kernels.basalt_dense_tc_pair_grid(n_out0, n_out1) + k = ctx.kernel("basalt_dense_tc", kernels.basalt_dense_tc_source(), "basalt_dense_tc_pair", macros) + prm = ctx.params("basalt_dense_tc_pair", kernels.basalt_dense_tc_params(n_in, n_out0, t, n_out1)) + bindings = [_bind(ctx, op, 0, w0, 16), _bind(ctx, op, 1, w1, 16), _bind(ctx, op, 2, xq, 4), + _bind(ctx, op, 3, y0, 4), _bind(ctx, op, 4, y1, 4), (5, prm, 0)] + ctx.add(k, bindings, (grid, 1, 1), (threads, 1, 1), f"{op.kind}:{w0.name}+{w1.name}", writes=[3, 4]) + + +def _mmvf(ctx: _Ctx, op: Op) -> None: + t = _columns(ctx, op) + (x, w), (y,) = op.inputs, op.outputs + _, n_out, n_in = _weight(ctx, op, w, (GGML_IDS["bf16"],)) + ldy = ctx.shape(y)[-1] + if ldy < n_out: # basalt never checks it: every call passes ldy == n_out + raise ValueError(f"basalt_mmvf: {y.name!r} holds {ldy} values a row and the weight has {n_out} rows; output " + "row k starts at k * ldy, so ldy >= n_out") + macros = kernels.basalt_mmvf_macros(n_in, n_out, t) + _expect(ctx, op, x, (t, n_in), DType.F32, "contiguous columns of the weight's width") + _expect(ctx, op, y, (t, n_out), DType.F32, "contiguous columns of the weight's rows") + grid, threads = kernels.basalt_mmvf_grid(macros, n_out) + k = ctx.kernel("basalt_mmvf", kernels.basalt_mmvf_source(), "basalt_mmvf", macros) + prm = ctx.params("basalt_mmvf", kernels.basalt_mmvf_params(n_in, n_out, t)) + ctx.add(k, [_bind(ctx, op, 0, x, 8), _bind(ctx, op, 1, w, 4), _bind(ctx, op, 2, y, 4), (3, prm, 0)], + (grid, 1, 1), (threads, 1, 1), f"{op.kind}:{w.name}", writes=[2]) + + +BASALT_HANDLERS: Dict[str, object] = {"basalt_q8_1": _q8_1, "basalt_mmvq": _mmvq, "basalt_dense_tc": _dense_tc, + "basalt_dense_tc_pair": _dense_tc_pair, "basalt_mmvf": _mmvf} diff --git a/monolith/formats/__init__.py b/monolith/formats/__init__.py index 3d6435ac..73c77530 100644 --- a/monolith/formats/__init__.py +++ b/monolith/formats/__init__.py @@ -1,11 +1,13 @@ """Quantization-format plugins: ``unpack(checkpoint tensors) → exact dequant recipe``, ``dequantize`` (the numerics reference), ``pack(...)`` → block-lane-major pack in the profile's lane order, plus the MSL decode snippet the GEMV -template uses (design §5.5). Importing this package registers ``nvfp4``, ``fp8_e4m3``, ``bf16``, ``int8`` and -``int4_affine`` (the MLX / AWQ / GPTQ 4-bit groups).""" +template uses (design §5.5). Importing this package registers ``nvfp4``, ``fp8_e4m3``, ``bf16``, ``int8``, +``int4_affine`` (the MLX / AWQ / GPTQ 4-bit groups) and the ggml block formats of GGUF files (``gguf``: ``f32``, +``f16``, ``q2_0``, ``q4_0``, ``q5_0``, ``q8_0``, ``q3_k`` … ``q6_k``, ``iq4_nl``, ``iq4_xs``, with GGUF's BF16 rows read +by ``bf16``; unpack and oracle only so far).""" from .base import DequantSpec, Format, PackLayout from .blm import PackInfo, pack_blm, unpack_blm from .registry import FORMATS, register_format -from . import bf16, fp8_e4m3, int4_affine, int8, nvfp4 # noqa: F401 (registration) +from . import bf16, fp8_e4m3, gguf, int4_affine, int8, nvfp4 # noqa: F401 (registration) __all__ = ["DequantSpec", "Format", "PackLayout", "PackInfo", "pack_blm", "unpack_blm", "FORMATS", "register_format"] diff --git a/monolith/formats/basalt_reader.py b/monolith/formats/basalt_reader.py new file mode 100644 index 00000000..3fe4b3b7 --- /dev/null +++ b/monolith/formats/basalt_reader.py @@ -0,0 +1,317 @@ +# SPDX-License-Identifier: MIT +# Copyright (c) 2026 Jesús Gulfo +"""Reader for basalt's ``.basalt`` model file (github.com/jesdga95/basalt, MIT): the layout of +include/basalt/core/model_format.hpp, whose Python side is basalt's tools/model_file.py, with the checks basalt's own +readers make (src/core/model_file.cpp, src/core/weights.cpp, src/kernels/cpu/expert_layout.cpp, +src/core/expert_source.cpp, src/core/mtp.cpp). +Where a looser parse could still decode a plausible weight from a wrong offset, it is stricter and also refuses: + +* a section named twice (basalt takes the first); +* a ``meta`` number that is negative or not an integer (basalt reads the first as its magnitude, the second as 0), and + a negative offset, size or shape in an index (basalt reads an offset or size as unsigned, which can wrap past its + bounds checks); +* a ``meta`` tensor without ``bytes`` (basalt's converter always writes it; basalt's reader treats it as optional); +* a ``dense.index`` that is not v3 (basalt does not check the version), a row of more than 19 fields (basalt refuses + fewer and ignores the extra ones), or a header whose tensor count is not the table's; +* an ``experts.layout`` layer listed twice (basalt keeps the last) or a header total the layers do not fill; +* an ``mtp/dense.index`` line of more than 6 fields (basalt refuses fewer and ignores the extra ones), or one whose + size disagrees with its kind and shape. + +Little-endian. A 64 KiB header — ``FileHeader`` (magic ``BASALTMF``, version 1, section count, file size) and one +128-byte ``SectionEntry`` per section (NUL-padded name, offset, size, SHA-256) — then the sections, each at a multiple of +2 MiB. Sections are found by name; this module parses: + +* ``meta`` — JSON. ``meta["tensors"][name]`` is every non-expert tensor of the source GGUF files: its ggml type id, its + GGUF shape (``ne0`` first, the contiguous axis), its size and its offset inside the ``gguf`` section (``tensor``). +* ``dense.index`` v3 — the ``dense`` pool's table: ``# align A pool P tensors T``, then 19 fields per tensor + (``DenseRow``). A row with ``code_bits != 0`` and no bytes (``in_gguf``) holds a shape only: the tensor is served + from ``gguf`` and its placeholder fields (``8 0 32``) are not its format; ``meta`` has the type. +* ``experts.layout`` v5 — ``layer gu_type d_type offset blob_bytes`` per layer: each layer's ``n_expert`` routed expert + blobs start at ``offset`` in ``experts`` and are ``blob_bytes`` each, an expert's GGUF rows ``[gate | up | down]`` + back to back (``ExpertsLayout.matrices``). The routed experts are not in ``meta``. +* ``mtp/dense.index`` — the drafter's dense tensors: ``name kind rows cols offset bytes`` (``kind`` ``f32``, ``bf16`` + or ``q8_0``; offsets into ``mtp/dense``). + +The other sections (``tokenizer/*``, ``gguf``, ``dense``, ``experts``, ``mtp/experts``, ``profile``, ``vision/*``) are +bytes by name. ``mtp/experts`` is not GGUF blocks: basalt writes its Q2_0 experts planar (all codes, then all fp16 +scales; gate and up rows interleaved), see basalt's include/basalt/kernels/cpu/expert.hpp. +""" + +# adapted from jesdga95/basalt tools/model_file.py @ b4c63b55754637f4c72ad53a0f791d425f71eb36 (MIT, +# third_party/BASALT-LICENSE): the layout constants and the FileHeader / SectionEntry structs + +from __future__ import annotations + +import hashlib +import json +import math +import os +import re +import struct +from collections import namedtuple +from typing import Any, Dict, List, Optional, Sequence, Tuple + +import numpy as np + +from .gguf import GGML_TYPES, ggml_row_bytes + +MAGIC = b"BASALTMF" +VERSION = 1 +SECTION_ALIGN = 2 << 20 +HEADER_BYTES = 64 << 10 +HEADER = struct.Struct("<8sIIQ40s") # magic, version, n_sections, file_bytes, reserved +ENTRY = struct.Struct("<64sQQ32s16s") # name, offset, bytes, sha256, reserved +MAX_SECTIONS = (HEADER_BYTES - HEADER.size) // ENTRY.size +EXPERTS_LAYOUT_VERSION = 5 # the newest basalt writes and reads (kExpertLayoutVersion) +MTP_KINDS = {"f32": 0, "bf16": 30, "q8_0": 8} # mtp/dense.index kind -> ggml type id + +Section = namedtuple("Section", "name offset nbytes sha256") +GgufTensor = namedtuple("GgufTensor", "name type_id ne offset nbytes") # offset: from the start of the file +DenseIndex = namedtuple("DenseIndex", "version align pool rows") +ExpertLayer = namedtuple("ExpertLayer", "layer gu_type d_type offset blob_bytes") +MtpTensor = namedtuple("MtpTensor", "name kind rows cols offset nbytes") + + +def parse_header(head: bytes) -> Tuple[int, Dict[str, Section]]: + """``(file_bytes, sections by name)`` from the file's first bytes (the header and its table at least).""" + if len(head) < HEADER.size: + raise ValueError("not a .basalt model file (too short)") + magic, version, n, file_bytes, _ = HEADER.unpack_from(head) + if magic != MAGIC: + raise ValueError("not a .basalt model file (bad magic)") + if version != VERSION: + raise ValueError(f"model file version {version}, this reader reads {VERSION}") + if n > MAX_SECTIONS or len(head) < HEADER.size + n * ENTRY.size: + raise ValueError("the section table is too long or cut short") + sections: Dict[str, Section] = {} + for i in range(n): + raw, off, size, digest, _ = ENTRY.unpack_from(head, HEADER.size + i * ENTRY.size) + name = raw.split(b"\0", 1)[0].decode() + if off % SECTION_ALIGN or off < HEADER_BYTES or off > file_bytes or size > file_bytes - off: + raise ValueError(f"section {name!r} lies outside the file or is misaligned") + if name in sections: + raise ValueError(f"section {name!r} appears twice") + sections[name] = Section(name, off, size, digest) + return file_bytes, sections + + +class DenseRow(namedtuple("DenseRow", "name file kind src_off src_bytes dst_off dst_bytes ne0 ne1 code_bits code_bias " + "group_elems codebook has_offset codes_bytes scales_bytes offset_bytes " + "scales_fp16 act_kind")): + """One ``dense.index`` row, basalt's ``IndexRow`` field for field. ``kind``: 0 verbatim, 1 BF16 promoted to F32, + 2 F32, 3 F16 promoted to F32, 4 BF16 and 5 F16 as stored; offsets are into ``dense``.""" + + @property + def in_gguf(self) -> bool: + """A shape-only row: the tensor's bytes are in ``gguf`` (``meta`` has its type).""" + return self.code_bits != 0 and self.dst_bytes == 0 + + +def _check_loaded_row(r: DenseRow, dense_bytes: int) -> None: + """weights.cpp's ``WeightTable::load`` on a row it copies out of ``dense`` (lines 284-386).""" + if r.file != 0: + raise ValueError(f"dense.index: {r.name} names file {r.file}; a .basalt pack has file 0 (dense) only") + if r.codes_bytes: # codes, scales (fp16 ones widen to f32), then offsets + if r.scales_fp16 and r.scales_bytes % 4: + raise ValueError(f"dense.index: {r.name}: an fp16 scale plane of an odd byte count") + scales = r.scales_bytes // 2 if r.scales_fp16 else r.scales_bytes + planes = (r.codes_bytes + scales + r.offset_bytes, r.codes_bytes + r.scales_bytes + r.offset_bytes) + elif r.kind in (1, 3): # BF16 or F16 promoted to F32: 4 bytes in, 2 out + planes = (4 * r.ne0 * max(r.ne1, 1), 2 * r.ne0 * max(r.ne1, 1)) + else: + planes = (r.src_bytes, r.dst_bytes) + if planes != (r.src_bytes, r.dst_bytes): + raise ValueError(f"dense.index: {r.name} is {r.src_bytes}/{r.dst_bytes} bytes in/out, its planes make " + f"{planes[0]}/{planes[1]}") + if r.src_bytes and r.src_off + r.src_bytes > dense_bytes: # an empty row reads nothing + raise ValueError(f"dense.index: {r.name} runs past the end of the dense section") + + +def parse_dense_index(text: str, dense_bytes: int) -> DenseIndex: + """``dense.index`` v3 over a ``dense`` section of ``dense_bytes``. A row that is not exactly 19 fields is refused + (basalt refuses fewer): a misparsed row is a wrong byte offset that decodes to a plausible weight. A row basalt + loads (any but an ``in_gguf`` one) must name file 0, have planes that add up to its sizes and lie in ``dense``.""" + version = header = None + rows: List[DenseRow] = [] + for line in text.splitlines(): + if line.startswith("#"): + m = re.match(r"# dense index v(\d+)", line) + version = int(m.group(1)) if m else version + m = re.match(r"# align (\d+) pool (\d+) tensors (\d+)", line) + header = tuple(int(g) for g in m.groups()) if m else header + continue + f = line.split() + if len(f) != 19: + raise ValueError(f"dense.index: a row of {len(f)} of 19 fields: {line!r}") + r = DenseRow(f[0], *(int(x) for x in f[1:])) + if min(r.src_off, r.src_bytes, r.dst_off, r.dst_bytes, r.ne0, r.ne1, r.codes_bytes, r.scales_bytes, + r.offset_bytes) < 0: + raise ValueError(f"dense.index: a negative offset, size or shape: {line!r}") + rows.append(r) + if version != 3: + raise ValueError(f"dense.index: version {version}, this reader reads v3") + if header is None or not header[1] or not rows: + raise ValueError("dense.index: no '# align … pool …' header or no rows") + if header[2] != len(rows): + raise ValueError(f"dense.index: the header counts {header[2]} tensors, the table has {len(rows)}") + for r in rows: + if not r.in_gguf: + _check_loaded_row(r, dense_bytes) + return DenseIndex(version, header[0], header[1], tuple(rows)) + + +class ExpertsLayout(namedtuple("ExpertsLayout", "version n_expert total layers")): + """``experts.layout``: ``layers[l]`` is layer ``l``'s :data:`ExpertLayer`; offsets are into ``experts``.""" + + def _layer(self, layer: int) -> ExpertLayer: + if not 0 <= layer < len(self.layers): + raise IndexError(f"layer {layer} of {len(self.layers)}") + return self.layers[layer] + + def blob_offset(self, layer: int, expert: int) -> int: + if not 0 <= expert < self.n_expert: + raise IndexError(f"expert {expert} of {self.n_expert}") + e = self._layer(layer) + return e.offset + expert * e.blob_bytes + + def matrices(self, layer: int, n_embd: int, n_ff: int) -> Tuple[Tuple[int, int, int, int], ...]: + """``(type id, byte offset in the blob, rows, values per row)`` of the blob's gate, up and down matrices — + ``[n_ff, n_embd]``, ``[n_ff, n_embd]``, ``[n_embd, n_ff]`` as GGUF rows (basalt's native_fmt). The model's + sizes are the caller's; a blob they do not fill exactly is refused.""" + e = self._layer(layer) + gu_row, d_row = ggml_row_bytes(e.gu_type, n_embd), ggml_row_bytes(e.d_type, n_ff) + up = gu_row * n_ff + if 2 * up + d_row * n_embd != e.blob_bytes: + raise ValueError(f"experts.layout: layer {layer}'s {e.blob_bytes}-byte blob is not gate/up/down of " + f"{n_embd} x {n_ff} in types {e.gu_type}/{e.d_type}") + return (e.gu_type, 0, n_ff, n_embd), (e.gu_type, up, n_ff, n_embd), (e.d_type, 2 * up, n_embd, n_ff) + + +def parse_experts_layout(text: str, experts_bytes: int, n_expert: Optional[int] = None) -> ExpertsLayout: + """``experts.layout`` up to v5 over an ``experts`` section of ``experts_bytes``; the header's ``n_expert`` wins + over the argument (a pruned pack ships fewer). Columns past the fifth are ignored, as basalt ignores them. The + layers must tile the section from offset 0 and fill it, or fill all of it but one blob of padding: basalt's + default (arena) expert source takes either, its ``--mmap-experts`` one the first only (expert_source.cpp).""" + version, total, layers = 0, None, {} + for line in text.splitlines(): + if line.startswith("#"): + m = re.match(r"# experts v(\d+)", line) + if m: + version = int(m.group(1)) + if version > EXPERTS_LAYOUT_VERSION: + raise ValueError(f"experts.layout v{version}: this reader reads up to v{EXPERTS_LAYOUT_VERSION}") + m = re.search(r"\(n_expert (\d+)", line) + n_expert = int(m.group(1)) if m else n_expert + m = re.search(r"total (\d+)\)", line) + total = int(m.group(1)) if m else total + continue + f = line.split() + if not f: + continue + try: + layer = ExpertLayer(*(int(x) for x in f[:5])) + except (TypeError, ValueError): + raise ValueError(f"experts.layout: a malformed line: {line!r}") from None + if min(layer) < 0 or layer.layer in layers: + raise ValueError(f"experts.layout: a malformed line: {line!r}") + layers[layer.layer] = layer + if not n_expert or not layers: + raise ValueError("experts.layout: no expert count or no layers") + at = 0 + for i in range(len(layers)): + if i not in layers or layers[i].offset != at: + raise ValueError(f"experts.layout: layer {i} is missing or not contiguous") + at += layers[i].blob_bytes * n_expert + if total is not None and total != at: + raise ValueError(f"experts.layout: the layers fill {at} bytes, the header says {total}") + if experts_bytes not in (at, at + max(e.blob_bytes for e in layers.values())): + raise ValueError(f"experts.layout: the layers fill {at} bytes, the experts section is {experts_bytes}") + return ExpertsLayout(version, n_expert, at, tuple(layers[i] for i in range(len(layers)))) + + +def parse_mtp_dense_index(text: str, dense_bytes: int) -> Tuple[MtpTensor, ...]: + """``mtp/dense.index`` over an ``mtp/dense`` section of ``dense_bytes``: six fields per line, the size of a known + kind matching its rows and columns, every tensor inside the section (mtp.cpp's ``MtpDrafter::load``).""" + out = [] + for line in text.splitlines(): + if not line or line.startswith("#"): + continue + f = line.split() + try: + if len(f) != 6: + raise ValueError + t = MtpTensor(f[0], f[1], *(int(x) for x in f[2:])) + except ValueError: + raise ValueError(f"mtp/dense.index: a malformed line: {line!r}") from None + if min(t.rows, t.cols, t.offset, t.nbytes) < 0: + raise ValueError(f"mtp/dense.index: a negative shape, offset or size: {line!r}") + if t.kind in MTP_KINDS and t.nbytes != t.rows * ggml_row_bytes(MTP_KINDS[t.kind], t.cols): + raise ValueError(f"mtp/dense.index: {t.name} is {t.nbytes} bytes, not {t.rows} x {t.cols} {t.kind}") + if t.offset + t.nbytes > dense_bytes: + raise ValueError(f"mtp/dense.index: {t.name} names bytes past the mtp/dense section") + out.append(t) + return tuple(out) + + +class BasaltFile: + """A ``.basalt`` file. ``BasaltFile(path)`` maps it; any buffer with a length that slices to bytes (``bytes``, a + range reader over HTTP) works the same way. ``data`` is that buffer.""" + + def __init__(self, source: Any) -> None: + self.data = np.memmap(source, dtype=np.uint8, mode="r") if isinstance(source, (str, os.PathLike)) else source + if len(self.data) < HEADER_BYTES: + raise ValueError("not a .basalt model file (too short)") + self.file_bytes, self.sections = parse_header(bytes(self.data[:HEADER_BYTES])) + if len(self.data) < self.file_bytes: + raise ValueError(f".basalt file truncated ({len(self.data)} of {self.file_bytes} bytes)") + self._meta: Optional[Dict[str, Any]] = None + + def section(self, name: str) -> Section: + if name not in self.sections: + raise KeyError(f"the .basalt file has no {name!r} section") + return self.sections[name] + + def view(self, name: str) -> Sequence[int]: + s = self.section(name) + return self.data[s.offset: s.offset + s.nbytes] + + def read(self, name: str) -> bytes: + return bytes(self.view(name)) + + def verify(self, name: str, chunk: int = 64 << 20) -> bool: + """The section's bytes against the SHA-256 in the table (basalt's engine never checks it).""" + s, h = self.section(name), hashlib.sha256() + for at in range(s.offset, s.offset + s.nbytes, chunk): + h.update(bytes(self.data[at: min(at + chunk, s.offset + s.nbytes)])) + return h.digest() == s.sha256 + + def meta(self) -> Dict[str, Any]: + if self._meta is None: + self._meta = json.loads(self.read("meta")) + return self._meta + + def tensor(self, name: str) -> GgufTensor: + """A ``gguf``-section tensor, its offset from the start of the file; the size must match its type and shape.""" + t, g = self.meta()["tensors"][name], self.section("gguf") + try: + ne, off, nbytes, type_id = tuple(t["shape"]), t["offset"], t["bytes"], t["type_id"] + except (KeyError, TypeError): + raise ValueError(f"meta.tensors[{name!r}] is malformed (a field is missing)") from None + if not all(type(x) is int and x >= 0 for x in (off, nbytes, type_id) + ne): + raise ValueError(f"meta.tensors[{name!r}] is malformed (a number that is negative or not an integer)") + if not 1 <= len(ne) <= 4: + raise ValueError(f"meta.tensors[{name!r}] is malformed (a shape of rank {len(ne)})") + if off + nbytes > g.nbytes: + raise ValueError(f"meta.tensors[{name!r}] runs past the gguf section") + if type_id in GGML_TYPES and nbytes != ggml_row_bytes(type_id, ne[0]) * math.prod(ne[1:]): # exact, no int64 wrap + raise ValueError(f"meta.tensors[{name!r}]: {nbytes} bytes do not match type {type_id} and shape {list(ne)}") + return GgufTensor(name, type_id, ne, g.offset + off, nbytes) + + def dense_index(self) -> DenseIndex: + return parse_dense_index(self.read("dense.index").decode(), self.section("dense").nbytes) + + def experts_layout(self) -> ExpertsLayout: + return parse_experts_layout(self.read("experts.layout").decode(), self.section("experts").nbytes) + + def mtp_dense_index(self) -> Tuple[MtpTensor, ...]: + return parse_mtp_dense_index(self.read("mtp/dense.index").decode(), self.section("mtp/dense").nbytes) diff --git a/monolith/formats/gguf.py b/monolith/formats/gguf.py new file mode 100644 index 00000000..c0fa039e --- /dev/null +++ b/monolith/formats/gguf.py @@ -0,0 +1,265 @@ +# SPDX-License-Identifier: MIT +# Copyright (c) 2023-2026 The ggml authors +"""The ggml block formats of GGUF files (llama.cpp), as the ``.basalt`` packs ship them (``basalt_reader.py``). + +A GGUF tensor ``[ne0, ne1]`` is ``ne1`` rows of ``ne0`` values, ``ne0`` the contiguous axis: the ``[N, K]`` matrix with +``N = ne1``, ``K = ne0``. A row is ``K / block`` blocks back to back; a block is the struct of ggml-common.h, given here +as a numpy structured dtype field for field (``layout``). ``unpack({"weight": rows}, shape=(N, K))`` takes the rows' +raw bytes (an array of any dtype, viewed as bytes); ``dequantize`` is the oracle: the float32 values of ggml's +reference ``dequantize_row_*`` (ggml/src/ggml-quants.c of llama.cpp 3cf03257), bit for bit. + +Exactness (an inference from the operand widths, checked by the contract tests): every product these decoders form is +exact in float32. A value is an fp16 scale (at most 11 significant bits) times at most two small integers, and the +widest product, Q6_K's ``d·sc·q`` or IQ4_XS's ``d·(ls − 32)·kvalue``, needs 23 bits, inside float32's normal range. +The one rounding step in all of them is the ``d·sc·q − dmin·m`` subtraction of Q4_K and Q5_K, and an FMA rounds it +the same way: the oracle's values do not depend on the evaluation order, on FP contraction or on the device. + +Type ids are the GGUF tensor type numbers (ggml.h ``enum ggml_type``); ``GGML_TYPES`` maps the ones the format +understands. 42 is ``GGML_TYPE_Q2_0`` (ggml.h at 3cf03257: ``GGML_TYPE_Q1_0 = 41, GGML_TYPE_Q2_0 = 42``; basalt's +include/basalt/ggml/ggml.h carries the same id): 64 values per block, an fp16 scale ``d`` and sixteen bytes of 2-bit +codes, value ``(code − 1) · d``. BF16 rows are the ``bf16`` plugin's ``[N, K]`` uint16 matrix. F32 and F16 are +one-value blocks, ``f32`` and ``f16``: a dtype view, exact (in a pack they are norms, biases and convolution taps). + +``pack`` / ``unpack_pack`` (the block-lane-major GEMV packs) and ``msl_decode`` arrive with the Metal decode kernels. +""" + +# adapted from ggml-org/llama.cpp ggml/src/ggml-common.h and ggml/src/ggml-quants.c @ 3cf03257f219afbe7334045ff7c6a06ac68c627d +# (MIT, third_party/GGML-LICENSE): the block structs as dtypes and the dequantize_row_* rules, re-implemented in numpy + +from __future__ import annotations + +from typing import Any, Dict, Mapping, Tuple + +import numpy as np + +from .base import DequantSpec, Format, PackLayout +from .registry import FORMATS, register_format + +QK_K = 256 + +# ggml type id -> (name, values per block, bytes per block); ggml.h and ggml-common.h of llama.cpp 3cf03257 +GGML_TYPES: Dict[int, Tuple[str, int, int]] = { + 0: ("f32", 1, 4), 1: ("f16", 1, 2), 2: ("q4_0", 32, 18), 6: ("q5_0", 32, 22), 8: ("q8_0", 32, 34), + 11: ("q3_k", QK_K, 110), 12: ("q4_k", QK_K, 144), 13: ("q5_k", QK_K, 176), 14: ("q6_k", QK_K, 210), + 20: ("iq4_nl", 32, 18), 23: ("iq4_xs", QK_K, 136), 30: ("bf16", 1, 2), 42: ("q2_0", 64, 18), +} + +# kvalues_iq4nl, copied from ggml/src/ggml-common.h (the commit above) +KVALUES_IQ4NL = np.array([-127, -104, -83, -65, -49, -35, -22, -10, 1, 13, 25, 38, 53, 69, 89, 113], np.float32) + +_E = np.arange(QK_K) # value index inside a 256-value super-block + + +def ggml_row_bytes(type_id: int, ne0: int) -> int: + """Bytes of one row of ``ne0`` values (ggml_row_size).""" + if type_id not in GGML_TYPES: + raise ValueError(f"ggml type {type_id} has no format here") + name, block, size = GGML_TYPES[type_id] + if ne0 % block: + raise ValueError(f"{name}: a row of {ne0} values is not whole blocks of {block}") + return ne0 // block * size + + +def ggml_dequantize(type_id: int, rows: Any, shape: Tuple[int, int]) -> np.ndarray: + """``N`` GGUF rows of type ``type_id`` (``shape = (N, K)``, their raw bytes in ``rows``) as float32 ``[N, K]``.""" + n, k = shape + raw = np.ascontiguousarray(rows).reshape(-1).view(np.uint8) + if raw.size != n * ggml_row_bytes(type_id, k): + raise ValueError(f"ggml type {type_id}: {raw.size} bytes are not {n} rows of {k} values") + name = GGML_TYPES[type_id][0] + fmt = FORMATS.get(name) + weight = raw.view(" np.ndarray: + return x.astype(np.float32) # fp16 -> fp32 is exact + + +def _nibbles(qs: np.ndarray) -> np.ndarray: + """``[nb, 16]`` bytes -> 32 codes: low nibbles of bytes 0 … 15, then their high nibbles (ggml's split halves).""" + return np.concatenate([qs & 0xF, qs >> 4], axis=-1) + + +def _scale_min_k4(s: np.ndarray) -> Tuple[np.ndarray, np.ndarray]: + """The eight 6-bit (scale, min) pairs of a Q4_K / Q5_K block's 12 scale bytes (ggml-quants.c get_scale_min_k4).""" + sc = np.concatenate([s[:, 0:4] & 63, (s[:, 8:12] & 0xF) | ((s[:, 0:4] >> 6) << 4)], axis=1) + mn = np.concatenate([s[:, 4:8] & 63, (s[:, 8:12] >> 4) | ((s[:, 4:8] >> 6) << 4)], axis=1) + return sc.astype(np.float32), mn.astype(np.float32) + + +class GGMLBlocks(Format): + """A ggml block format: ``type_id`` and ``layout`` (one block); ``_values`` decodes ``[nb]`` blocks to ``[nb, block]``.""" + + type_id: int = -1 + layout: np.dtype = np.dtype([]) + + def unpack(self, tensors: Mapping[str, Any], *, shape: Tuple[int, int]) -> DequantSpec: + n, k = shape + raw = np.ascontiguousarray(tensors["weight"]).reshape(-1).view(np.uint8) + if raw.size != n * ggml_row_bytes(self.type_id, k): + raise ValueError(f"{self.name}: {raw.size} bytes are not {n} rows of {k} values") + return DequantSpec(self.name, (n, k), {"weight": raw.reshape(n, -1)}, {"type_id": self.type_id}) + + def dequantize(self, spec: DequantSpec) -> np.ndarray: + n, k = spec.shape + blocks = np.ascontiguousarray(spec.tensors["weight"]).reshape(-1).view(self.layout) + return self._values(blocks).reshape(n, k) + + def _values(self, b: np.ndarray) -> np.ndarray: + raise NotImplementedError + + def pack(self, spec: DequantSpec, layout: PackLayout) -> Tuple[bytes, Any]: + raise NotImplementedError(f"{self.name}: no GEMV pack yet; it comes with the Metal decode kernels") + + def unpack_pack(self, data: bytes, info: Any) -> DequantSpec: + raise NotImplementedError(f"{self.name}: no GEMV pack yet; it comes with the Metal decode kernels") + + +def _ggml(type_id: int, layout: list): + """Register a block format under its ggml name, checking its layout against the type table.""" + name, block, size = GGML_TYPES[type_id] + + def deco(cls): + cls.type_id, cls.layout, cls.bytes_per_weight = type_id, np.dtype(layout), size / block + if cls.layout.itemsize != size: + raise TypeError(f"{name}: the block layout is {cls.layout.itemsize} bytes, ggml's is {size}") + return register_format(name)(cls) + + return deco + + +@_ggml(0, [("v", "> 2 (j % 4)) & 3) − 1, times d: the codes {0, 1, 2, 3} are {−1, 0, +1, +2}.""" + + def _values(self, b): + q = (b["qs"][:, :, None] >> np.array([0, 2, 4, 6], np.uint8)) & 3 + return (q.reshape(-1, 64).astype(np.float32) - 1) * _f32(b["d"])[:, None] + + +@_ggml(2, [("d", "> np.arange(32, dtype=np.uint32)) & 1).astype(np.uint8) + return ((_nibbles(b["qs"]) | (hi << 4)).astype(np.float32) - 16) * _f32(b["d"])[:, None] + + +@_ggml(8, [("d", "> 2) & k1) << 4), + ((a0 >> 4) & k2) | (((t >> 4) & k1) << 4), ((a1 >> 4) & k2) | (((t >> 6) & k1) << 4)], axis=1) + dl = _f32(b["d"])[:, None] * (np.ascontiguousarray(aux).view(np.int8).astype(np.float32) - 32) + q = (b["qs"][:, _Q3_QS] >> _Q3_SHIFT) & 3 + high = (b["hmask"][:, _Q3_HM] >> _Q3_BIT) & 1 + return dl[:, _E // 16] * (q.astype(np.float32) - np.where(high, np.float32(0), np.float32(4))) + + +_K4_SB = _E // 32 # Q4_K / Q5_K: sub-block of value e (its scale and min) +_K4_BYTE = (_K4_SB // 2) * 32 + _E % 32 # the byte holding its low four bits: low nibble for even sub-blocks +_K4_SHIFT, _K4_HBIT = (4 * (_K4_SB % 2)).astype(np.uint8), _K4_SB.astype(np.uint8) + + +@_ggml(12, [("d", "> _K4_SHIFT) & 0xF + return d[:, _K4_SB] * q.astype(np.float32) - m[:, _K4_SB] + + +@_ggml(13, [("d", "> _K4_SHIFT) & 0xF) | (((b["qh"][:, _E % 32] >> _K4_HBIT) & 1) << 4) + return d[:, _K4_SB] * q.astype(np.float32) - m[:, _K4_SB] + + +_Q6_H, _Q6_K = _E // 128, (_E % 128) // 32 +_Q6_QL, _Q6_QH = 64 * _Q6_H + 32 * (_Q6_K % 2) + _E % 32, 32 * _Q6_H + _E % 32 +_Q6_LSHIFT, _Q6_HSHIFT = (4 * (_Q6_K // 2)).astype(np.uint8), (2 * _Q6_K).astype(np.uint8) + + +@_ggml(14, [("ql", "u1", 128), ("qh", "u1", 64), ("scales", "i1", 16), ("d", "> _Q6_LSHIFT) & 0xF + hi = (b["qh"][:, _Q6_QH] >> _Q6_HSHIFT) & 3 + d = _f32(b["d"])[:, None] * b["scales"].astype(np.float32) + return d[:, _E // 16] * ((lo | (hi << 4)).astype(np.float32) - 32) + + +@_ggml(20, [("d", "> (4 * (_IB % 2))) & 0xF) | (((b["scales_h"][:, None] >> (2 * _IB)) & 3) << 4) + dl = _f32(b["d"])[:, None] * (ls.astype(np.float32) - 32) + q = _nibbles(b["qs"].reshape(-1, 8, 16)).reshape(-1, QK_K) + return dl[:, _E // 32] * KVALUES_IQ4NL[q] diff --git a/monolith/kernels.py b/monolith/kernels.py index cff79a04..ed084a5e 100644 --- a/monolith/kernels.py +++ b/monolith/kernels.py @@ -256,6 +256,451 @@ def moe_combine_params(hidden: int, top_k: int, t_active: int) -> bytes: return struct.pack(" str: + """The native, SwiGLU and IEEE q8_1 quantizers (``native_quantize_q8_1``, ``native_swiglu_quantize_q8_1``, + ``quantize_q8_1``).""" + return PRELUDE + template("basalt_fp.metal") + template("basalt_q8_1.metal") + + +def basalt_q8_1_params(n_values: int) -> bytes: + """``Q81Params`` for ``n_values`` = ncols * n_in values (n_in a multiple of 32); the grid is + ceil(n_values / 256) threadgroups of 256 threads.""" + if n_values <= 0 or n_values % 32: + raise ValueError(f"q8_1: the value count must be a positive multiple of 32, got {n_values}") + return struct.pack(" Tuple[int, int]: + """(threadgroups, threads per threadgroup) of a q8_1 quantizer over ``n_values`` values: one thread per value.""" + return -(-n_values // Q8_1_THREADS), Q8_1_THREADS + + +# basalt's iteration traits per ggml type (native_mmvq.cu:897-1098): values per block (DIV), threads per block (T), +# blocks per iteration with four SIMD-groups (BPI) +MMVQ_TRAITS = {2: (32, 2, 64), 6: (32, 2, 64), 8: (32, 4, 32), 20: (32, 2, 64), 11: (256, 16, 8), 12: (256, 16, 8), + 13: (256, 16, 8), 14: (256, 32, 4), 23: (256, 8, 16), 42: (64, 2, 64)} + + +def basalt_mmvq_source() -> str: + """basalt's ``native_mmvq`` for the ten GGUF types of ``MMVQ_TRAITS`` (``basalt_mmvq``).""" + return PRELUDE + template("basalt_fp.metal") + template("basalt_mmvq.metal") + + +def basalt_mmvq_macros(type_id: int, n_in: int, ncols: int, *, upstream: bool = False) -> Dict[str, str]: + """basalt's launch for ``ncols`` columns: one column, 4 SIMD-groups and 1 row per threadgroup (4 rows for small + K: fewer blocks per row than BPI); several, the exact layout (basalt's default) with 1 row (2 for small K); + ``upstream``: llama.cpp's table that mmvq_multi_parity's negative control runs (4 SIMD-groups up to 4 columns, + else 2; always 2 rows). One column is always the one-column launch, as in basalt (native_mmvq.cu:1585-1599).""" + if type_id not in MMVQ_TRAITS: + raise ValueError(f"basalt_mmvq: unsupported ggml type {type_id}") + div, _, bpi = MMVQ_TRAITS[type_id] + if n_in <= 0 or n_in % div or not 1 <= ncols <= 8: + raise ValueError(f"basalt_mmvq: n_in must be a positive multiple of {div} and ncols in 1..8") + small = n_in // div < bpi + if upstream and ncols > 1: + nw, rows = (4 if ncols <= 4 else 2), 2 + else: + nw, rows = 4, ((4 if small else 1) if ncols == 1 else (2 if small else 1)) + return {"MMVQ_TYPE": str(type_id), "NCOLS": str(ncols), "ROWS": str(rows), "NW": str(nw)} + + +def basalt_mmvq_grid(macros: Mapping[str, str], n_out: int) -> Tuple[int, int]: + """(threadgroups, threads per threadgroup) for a ``basalt_mmvq_macros`` launch.""" + return -(-n_out // int(macros["ROWS"])), 32 * int(macros["NW"]) + + +def basalt_mmvq_params(n_in: int, n_out: int) -> bytes: + return struct.pack(" str: + """basalt's ``native_expert_grouped`` for Q2_0 gate/up and down: ``basalt_expert_gu``, ``basalt_expert_swiglu_q8_1`` + and ``basalt_expert_down``, dispatched in that order. The gate/up and down kernels take basalt's ``grp_ptr`` at + buffer(1): one 64-bit GPU address a group (each 2-byte aligned, inside a buffer the dispatch makes resident).""" + return PRELUDE + template("basalt_fp.metal") + template("basalt_q8_1.metal") + template("basalt_experts.metal") + + +def basalt_expert_layout(n_embd: int, n_ff: int) -> Dict[str, int]: + """basalt's ``native_expert_layout(42, 42, n_embd, n_ff)`` (iq_kernels.cu:2517-2529): row bytes, the up and down + offsets and the bytes of one blob (n_ff gate rows, n_ff up rows, n_embd down rows), after its checks + (``native_expert_supported``, iq_kernels.cu:2511-2515).""" + if n_embd <= 0 or n_ff <= 0 or n_embd % 256 or n_ff % 64: + raise ValueError(f"basalt_experts: n_embd must be a multiple of 256 and n_ff of 64, got {n_embd}, {n_ff}") + gu_row, d_row = n_embd // 64 * 18, n_ff // 64 * 18 + up_off = n_ff * gu_row + return {"n_embd": n_embd, "n_ff": n_ff, "gu_row": gu_row, "d_row": d_row, "up_off": up_off, + "down_off": 2 * up_off, "bytes": 2 * up_off + n_embd * d_row} + + +def basalt_expert_macros(n_embd: int, n_ff: int, *, gu2: Optional[bool] = None, + sub16: Optional[bool] = None) -> Dict[str, str]: + """basalt's kernel choice (iq_kernels.cu:2376-2382, 2594): gate/up on the two-rows-a-SIMD-group kernel where + ``gu2_usable`` holds (n_embd 2560, even n_ff, 4-byte aligned rows), the down kernel's 16-lane rows at n_ff 640. + ``gu2`` / ``sub16`` force a choice (tests compare the paths); gu2 needs n_embd 2560, sub16 n_ff 640.""" + lay = basalt_expert_layout(n_embd, n_ff) + usable = n_embd == 2560 and n_ff % 2 == 0 and lay["gu_row"] % 4 == 0 and lay["up_off"] % 4 == 0 + gu2 = usable if gu2 is None else gu2 + sub16 = n_ff == 640 if sub16 is None else sub16 + if (gu2 and not usable) or (sub16 and n_ff != 640): + raise ValueError("basalt_experts: the gu2 kernel needs n_embd 2560, the 16-lane down kernel n_ff 640") + return {"GU2": str(int(gu2)), "SUB16": str(int(sub16))} + + +def basalt_expert_group_rows(cap_groups: int, grid_groups: int = 0) -> int: + """Threadgroup rows of the gate/up and down dispatches: basalt's gy (iq_kernels.cu:2566-2569), cap_groups when the + caller passes 0 or more than cap, capped at ``EXPERT_GROUP_ROWS`` when it passes 0. The result does not depend on + it.""" + gy = cap_groups if grid_groups <= 0 or grid_groups > cap_groups else grid_groups + return min(gy, EXPERT_GROUP_ROWS) if grid_groups <= 0 else gy + + +def basalt_expert_grids(macros: Mapping[str, str], n_embd: int, n_ff: int, cap_groups: int, cap_entries: int, + grid_groups: int = 0) -> Tuple[Tuple[int, int], int, Tuple[int, int]]: + """Threadgroup grids of the gate/up, SwiGLU and down dispatches (each of ``EXPERT_THREADS`` threads).""" + gy = basalt_expert_group_rows(cap_groups, grid_groups) + gu_rows = 16 if macros["GU2"] == "1" else 8 + d_rows = 16 if macros["SUB16"] == "1" else 8 + return ((-(-2 * n_ff // gu_rows), gy), -(-cap_entries * n_ff // EXPERT_THREADS), (-(-n_embd // d_rows), gy)) + + +def basalt_expert_params(n_embd: int, n_ff: int) -> bytes: + """``ExpertParams``: the layout's n_embd, n_ff, row bytes and offsets.""" + lay = basalt_expert_layout(n_embd, n_ff) + return struct.pack("<8I", n_embd, n_ff, lay["gu_row"], lay["d_row"], lay["up_off"], lay["down_off"], 0, 0) + + +# ---- basalt's drafter experts (kernels/common/basalt_s2_experts.metal; docs/research/basalt-nvcc/s2_experts.md) ---- +# The constants and the scratch layout are adapted from basalt (jesdga95/basalt) src/kernels/cuda/s2_expert_grouped.cu +# :34-46, :554-562, :1085-1122 and src/kernels/cuda/quantize_act.cu:219-238 @ b4c63b55754637f4c72ad53a0f791d425f71eb36 +# (MIT; third_party/NOTICE). + +Q8_0_BLOCK_BYTES = 34 # fp16 d, 32 int8 codes +S2_THREADS = 256 # every dispatch but the plan's: 256-thread threadgroups +S2_H, S2_FF, S2_GMAX = 2560, 640, 8 +S2_BLOB_BYTES = 2 * S2_FF * S2_H // 4 + S2_H * S2_FF // 4 + 2 * S2_FF * S2_H // 64 * 2 + S2_H * S2_FF // 64 * 2 + + +def basalt_s2_experts_source() -> str: + """basalt's drafter experts: ``basalt_s2_group_resident`` (moe_group_resident), ``basalt_quantize_q8_0_scaled`` and + moe_grouped_s2's ``basalt_s2_gu``, ``basalt_s2_swiglu``, ``basalt_quantize_q8_0_scaled`` (the intermediate) and + ``basalt_s2_down``, dispatched in that order. The gate/up and down kernels take basalt's ``grp_ptr`` at buffer(0): + one 64-bit GPU address a group (each 2-byte aligned, inside a buffer the dispatch makes resident).""" + return PRELUDE + template("basalt_fp.metal") + template("basalt_q8_1.metal") + template("basalt_s2_experts.metal") + + +CUDA_GRID_X, CUDA_GRID_Y = 2 ** 31 - 1, 65535 # CUDA's largest gridDim.x and .y: a larger basalt launch exits + + +def basalt_q8_0_scaled_params(n_values: int) -> bytes: + """``Q80Params`` for ``basalt_quantize_q8_0_scaled`` over ``n_values`` floats, a positive multiple of 32 (basalt + refuses others, quantize_act.cu:222-225) on a grid basalt can launch (``basalt_q8_0_scaled_grid``, threadgroups of + 256). The block count is 64-bit, basalt's long long.""" + if n_values <= 0 or n_values % 32: + raise ValueError(f"quantize_q8_0_scaled: the value count must be a positive multiple of 32, got {n_values}") + basalt_q8_0_scaled_grid(n_values) + return struct.pack(" int: + """Threadgroups of 256 for ``n_values`` floats: one SIMD-group a block (quantize_act.cu:229-231). At most + ``CUDA_GRID_X``: basalt launches ``(unsigned) ((nb * 32 + 255) / 256)`` blocks and exits when the launch fails + (:230-236). Within it no 32-bit threadgroup position wraps.""" + grid = -(-n_values // S2_THREADS) + if grid > CUDA_GRID_X: + raise ValueError(f"quantize_q8_0_scaled: {n_values} values need {grid} threadgroups, above {CUDA_GRID_X}") + return grid + + +def basalt_s2_scratch(cap_entries: int) -> Dict[str, int]: + """moe_grouped_s2's scratch for ``cap_entries`` entries (s2_expert_grouped.cu:1090-1094): the byte offsets of the + quantized intermediate ("hq") and its fp32 scales ("hs") after gate/up at 0, each region's bytes rounded up to 16, + and the size basalt allocates (``moe_hit_grouped_scratch_bytes``, :554-562). At most 858,993,458 entries: basalt's + SwiGLU and quantizer grids of cap_entries * 640 / 256 blocks (:1107-1108, :1111) stop at ``CUDA_GRID_X``, which + also keeps the ``(int) cap_entries`` basalt hands the gate/up kernel (:1100) in range.""" + if cap_entries <= 0: + raise ValueError(f"moe_grouped_s2: cap_entries must be positive, got {cap_entries}") + basalt_q8_0_scaled_grid(cap_entries * S2_FF) + r16 = lambda n: (n + 15) // 16 * 16 + nc = S2_FF // 32 + gu, q8, hs = r16(cap_entries * 2 * S2_FF * 4), r16(cap_entries * nc * Q8_0_BLOCK_BYTES), r16(cap_entries * nc * 4) + return {"hq": gu, "hs": gu + q8, "bytes": gu + q8 + 2 * hs + r16(S2_H // 32 * 4)} + + +def basalt_s2_params(cap_entries: int) -> bytes: + """``S2Params`` of the gate/up and SwiGLU dispatches.""" + basalt_s2_scratch(cap_entries) + return struct.pack(" Dict[str, object]: + """Threadgroup grids (each of 256 threads) of moe_grouped_s2's four dispatches (s2_expert_grouped.cu:1096-1121): + gate/up (40, cap_groups), the SwiGLU, the intermediate's quantizer, down (40, cap_groups). cap_groups is at most + ``CUDA_GRID_Y`` (basalt's grid y, :1097), so the kernels' ``int(tg.y)`` (basalt's ``int g = blockIdx.y``) stays + non-negative; cap_entries as ``basalt_s2_scratch`` takes it.""" + if not 0 < cap_groups <= CUDA_GRID_Y: + raise ValueError(f"moe_grouped_s2: cap_groups must be 1..{CUDA_GRID_Y}, got {cap_groups}") + basalt_s2_scratch(cap_entries) + grid = basalt_q8_0_scaled_grid(cap_entries * S2_FF) # the SwiGLU's too: a thread a value + return {"gu": (2 * S2_FF // 32, cap_groups), "swiglu": grid, "quant": grid, "down": (S2_H // 64, cap_groups)} + + +def basalt_s2_resident_params(n: int, k_per_tok: int, blob: int = S2_BLOB_BYTES) -> bytes: + """``S2ResidentParams`` of ``basalt_s2_group_resident`` (one threadgroup of 128): n routed ids, 1..128 as basalt + requires (s2_expert_grouped.cu:1079), k_per_tok of them a token, experts ``blob`` bytes apart.""" + if not 1 <= n <= 128 or k_per_tok <= 0: + raise ValueError(f"moe_group_resident: n must be 1..128 and k_per_tok positive, got {n}, {k_per_tok}") + return struct.pack(" str: + """basalt's ``dequant_flat_kernel`` for ``DEQUANT_TYPES`` (``basalt_dequant_f32``): n / 256 threadgroups of + 32 threads, one 256-value superblock each.""" + return PRELUDE + template("basalt_fp.metal") + template("basalt_dequant.metal") + + +def basalt_dequant_macros(type_id: int) -> Dict[str, str]: + if type_id not in DEQUANT_TYPES: + raise ValueError(f"basalt_dequant: unsupported ggml type {type_id}") + return {"DQ_TYPE": str(type_id)} + + +# ---- basalt's BF16 GEMVs on fp32 activations (kernels/common/basalt_mmvf.metal; docs/research/basalt-nvcc/bf16.md) -- +# The launch rules below are adapted from basalt (jesdga95/basalt) src/kernels/cuda/native_bf16.cu:124-203 @ +# b4c63b55754637f4c72ad53a0f791d425f71eb36 (MIT; third_party/NOTICE), whose block-size rule is ggml-org/llama.cpp's +# ggml/src/ggml-cuda/mmvf.cu @ 3cf03257f219afbe7334045ff7c6a06ac68c627d (MIT; third_party/NOTICE). + +def basalt_mmvf_source() -> str: + """basalt's ``bf16_gemv_fp32_mmvf`` and ``bf16_gemv_fp32_mmvf_multi`` (``basalt_mmvf``).""" + return PRELUDE + template("basalt_fp.metal") + template("basalt_mmvf.metal") + + +def basalt_mmvf_block(n_in: int) -> int: + """basalt's ``mmvf_block_size`` (native_bf16.cu:124-135): 32 threads, unless a block of 64, 96, ..., 256 takes + strictly fewer iterations over the n_in / 2 pairs (the first such, then the next that improves on it).""" + best, best_it = 32, (n_in + 63) // 64 + for c in range(64, 257, 32): + it = (n_in + 2 * c - 1) // (2 * c) + if it < best_it: + best, best_it = c, it + return best + + +def basalt_mmvf_macros(n_in: int, n_out: int, n_tok: int = 1, ldx: Optional[int] = None, + ldy: Optional[int] = None) -> Dict[str, str]: + """basalt's launch for ``n_tok`` activation rows (x row k at k * ldx floats, y row k at k * ldy) after its checks + (native_bf16.cu:139-189): one row with ldy >= n_out takes the one-row kernel (NT 1); otherwise the multi kernel, + NT 4 up to 4 rows, else 8. BLOCK is ``basalt_mmvf_block(n_in)``; the grid n_out threadgroups of BLOCK threads. + ldx and ldy default to n_in and n_out.""" + ldx = n_in if ldx is None else ldx + ldy = n_out if ldy is None else ldy + if not (0 < n_in < 2 ** 31 and n_in % 2 == 0 and 0 < n_out < 2 ** 31): + raise ValueError("basalt_mmvf: require positive even n_in and positive n_out <= INT_MAX") + one_row = n_tok == 1 and ldy >= n_out + if not one_row and not (1 <= n_tok <= 8 and ldx % 2 == 0): + raise ValueError("basalt_mmvf: 1..8 rows, even n_in/ldx") + nt = 1 if one_row else (4 if n_tok <= 4 else 8) + return {"BLOCK": str(basalt_mmvf_block(n_in)), "NT": str(nt)} + + +def basalt_mmvf_params(n_in: int, n_out: int, n_tok: int = 1, ldx: Optional[int] = None, + ldy: Optional[int] = None) -> bytes: + """``MmvfParams``: n_in, n_out, n_tok, ldx and ldy (defaults n_in and n_out).""" + return struct.pack("<8I", n_in, n_out, n_tok, n_in if ldx is None else ldx, n_out if ldy is None else ldy, 0, 0, 0) + + +def basalt_mmvf_grid(macros: Mapping[str, str], n_out: int) -> Tuple[int, int]: + """(threadgroups, threads per threadgroup) for a ``basalt_mmvf_macros`` launch: one threadgroup of BLOCK threads + per output row.""" + return n_out, int(macros["BLOCK"]) + + +def basalt_mmvf_cols(ncols: int) -> List[Tuple[int, int]]: + """basalt's ``bf16_gemv_fp32_mmvf_cols`` (native_bf16.cu:193-203): (first column, columns) of each launch over + ``ncols`` contiguous columns (ldx = n_in, ldy = n_out), chunks of 8; a chunk of one is the one-row kernel's.""" + return [(c0, min(8, ncols - c0)) for c0 in range(0, ncols, 8)] + + +# ---- basalt's dense_tc and dense_tc_pair (kernels/common/basalt_dense_tc.metal; docs/research/basalt-nvcc/dense_tc.md) +# adapted from basalt (jesdga95/basalt) src/kernels/cuda/dense_tc.cu:35-42, :52-54, :698-702, :1017-1105 @ +# b4c63b55754637f4c72ad53a0f791d425f71eb36 (MIT; third_party/NOTICE) + +DENSE_TC_SB = {11: 110, 12: 144, 13: 176, 14: 210, 23: 136, 42: 72} # Fmt::SB: bytes of 256 values +DENSE_TC_ORDERS = {"one": 0, "tile": 1, "s1": 2, "s2": 3} # DTC_ORDER; s1 / s2: dense_tc_kernel at KS 1 / 2 +DENSE_TC_SM_COUNT = 170 # the multiprocessors of basalt's measured GPU (an RTX 5090), which its variant rule reads + + +def basalt_dense_tc_source() -> str: + """basalt's ``dense_tc`` (``basalt_dense_tc``) and ``dense_tc_pair`` (``basalt_dense_tc_pair``).""" + return PRELUDE + template("basalt_fp.metal") + template("basalt_dense_tc.metal") + + +def _dense_tc_check(type_id: int, n_in: int) -> int: + """dense_tc_supported (dense_tc.cu:1063-1065) for the pack's types: n_in a positive multiple of 512. Returns SB.""" + if type_id not in DENSE_TC_SB: + raise ValueError(f"basalt_dense_tc: unsupported ggml type {type_id}") + if n_in <= 0 or n_in % 512: + raise ValueError(f"basalt_dense_tc: n_in must be a positive multiple of 512, got {n_in}") + return DENSE_TC_SB[type_id] + + +def basalt_dense_tc_variant(type_id: int, n_in: int, n_out: int, *, sm_count: int = DENSE_TC_SM_COUNT, + aligned: bool = True) -> str: + """basalt's summation order for a shape (``launch``, dense_tc.cu:1017-1059; never the column count): "one" + where the weights are 16-byte aligned, a row is whole 16-byte units, the 16-row tiles number at most ``sm_count`` + and ``one_smem_bytes`` fits 99 KiB; else "tile" where aligned and two tiles fit 90 KiB; else "s2" (KS 2) + where n_in % 1024 == 0 and the tiles number fewer than ``sm_count``; else "s1". ``aligned``: the weights' base + is 16-byte aligned (every Metal buffer is).""" + sb = _dense_tc_check(type_id, n_in) + if n_out < 1: + raise ValueError(f"basalt_dense_tc: n_out must be positive, got {n_out}") + row_bytes, tiles = n_in // 256 * sb, -(-n_out // 16) + one_stride = row_bytes if (row_bytes // 16) % 2 else row_bytes + 16 # one_row_stride, :52-54 + one_smem = 128 + max(24 * 16 * 8 * 4, 16 * one_stride) # one_smem_bytes, :698-702 + if aligned and row_bytes % 16 == 0 and tiles <= sm_count and one_smem <= 99 * 1024: + return "one" + if aligned and 2 * 16 * row_bytes <= 90 * 1024: + return "tile" + return "s2" if n_in % 1024 == 0 and tiles < sm_count else "s1" + + +def basalt_dense_tc_macros(type_id: int, n_in: int, n_out: int, variant: Optional[str] = None, *, + sm_count: int = DENSE_TC_SM_COUNT) -> Dict[str, str]: + """``variant`` (default: ``basalt_dense_tc_variant``'s at ``sm_count``) of a dense_tc launch; KS 2 needs + n_in % 1024 == 0.""" + variant = variant or basalt_dense_tc_variant(type_id, n_in, n_out, sm_count=sm_count) + _dense_tc_check(type_id, n_in) + if variant not in DENSE_TC_ORDERS: + raise ValueError(f"basalt_dense_tc: unknown variant {variant!r}") + if variant == "s2" and n_in % 1024: + raise ValueError(f"basalt_dense_tc: KS 2 needs n_in % 1024 == 0, got {n_in}") + return {"DTC_TYPE": str(type_id), "DTC_ORDER": str(DENSE_TC_ORDERS[variant])} + + +def basalt_dense_tc_grid(macros: Mapping[str, str], n_out: int) -> Tuple[int, int]: + """(threadgroups, threads per threadgroup): one threadgroup per 16-row tile, basalt's warps run by up to 8 + SIMD-groups (the kernel takes any count from 4).""" + warps = (24, 8, 4, 8)[int(macros["DTC_ORDER"])] # basalt's warps per tile + return -(-n_out // 16), 32 * min(warps, 8) + + +def basalt_dense_tc_params(n_in: int, n_out: int, ncols: int, n_out1: int = 0) -> bytes: + """``DtcParams``: n_in, n_out (the pair: the first matrix's), ncols 1..8 and the pair's second n_out.""" + if not 1 <= ncols <= 8: + raise ValueError(f"basalt_dense_tc: ncols must be in 1..8, got {ncols}") + return struct.pack(" Dict[str, str]: + """dense_tc_pair's two types, after ``dense_tc_pair_supported`` (dense_tc.cu:1100-1105): two staged tiles of the + larger format fit basalt's 99 KiB.""" + sb = max(_dense_tc_check(type0, n_in), _dense_tc_check(type1, n_in)) + if 128 + 8 * 16 * 8 * 4 + 2048 + 2 * 16 * (n_in // 256) * sb > 99 * 1024: + raise ValueError(f"basalt_dense_tc_pair: types {type0}/{type1} at n_in {n_in} not supported") + return {"DTC_TYPE0": str(type0), "DTC_TYPE1": str(type1)} + + +def basalt_dense_tc_pair_grid(n_out0: int, n_out1: int) -> Tuple[int, int]: + return -(-n_out0 // 16) + -(-n_out1 // 16), 256 + + +# ---- basalt's Q5_K head (kernels/common/basalt_q5k_head.metal; docs/research/basalt-nvcc/q5k_head.md) +# adapted from basalt (jesdga95/basalt) src/kernels/cuda/q5k_head.cu:337-386, :500-535 and +# src/kernels/cuda/head_proxy.cuh:17-28 @ b4c63b55754637f4c72ad53a0f791d425f71eb36 (MIT; third_party/NOTICE) + +Q5K_HEAD_THREADS = 256 # basalt's WPB * WARP: 8 SIMD-groups, one row each +Q5K_TOP1_SM_COUNT = 170 # the multiprocessors of basalt's measured GPU (an RTX 5090) +Q5K_TOP1_PER_SM = 2 # cudaOccupancyMaxActiveBlocksPerMultiprocessor of q5k_head_top1_kernel on sm_120: 126 + # registers (ptxas, NVCC 13.0 and 13.3) round to 128; 128 x 256 of 65,536 (q5k_head.md) +Q5K_TOP1_MAX_BLOCKS = 4096 # basalt's cap: q5k_head_top1_scratch_bytes holds 4096 partials + + +def basalt_q5k_head_source() -> str: + """basalt's ``q5k_head_mmvq`` (``basalt_q5k_head``), ``q5k_head_mask_unmapped`` (``basalt_q5k_head_mask_unmapped``), + ``q5k_head_top1`` (``basalt_q5k_head_top1`` then ``basalt_q5k_head_top1_merge``), ``q5k_proxy_pack`` + (``basalt_q5k_proxy_pack``) and ``q5k_proxy_top1`` (``basalt_q5k_proxy_score`` then ``basalt_q5k_proxy_final``).""" + return PRELUDE + template("basalt_fp.metal") + template("basalt_q5k_head.metal") + + +def basalt_q5k_head_macros(n_in: int, ncols: int) -> Dict[str, str]: + """``q5k_head_supported`` (q5k_head.cu:365-368): n_in a positive multiple of 256 with at most 64 blocks a row, 1..8 + columns whose staging (6 int4 per q8_1 block) fits basalt's 96 KiB; the port reads the columns from device memory, + so the rule is the API's, not Metal's.""" + if n_in <= 0 or n_in % 256 or n_in // 256 > 64 or not 1 <= ncols <= 8 or ncols * (n_in // 32) * 96 > 96 * 1024: + raise ValueError(f"basalt_q5k_head: unsupported shape (n_in {n_in}, ncols {ncols})") + return {"NC": str(ncols)} + + +def basalt_q5k_head_grid(n_out: int, *, sm_count: int = Q5K_TOP1_SM_COUNT, per_sm: int = Q5K_TOP1_PER_SM, + cap: int = Q5K_TOP1_MAX_BLOCKS) -> int: + """basalt's grid rule (q5k_head.cu:353-354, 375-386): min(ceil(n_out / 8), sm_count * per_sm, cap) threadgroups of + 256 threads. The top-1's probability sums in this order, so its last bits follow ``sm_count`` and ``per_sm`` + (mtp.cpp:1007-1008); the defaults are basalt's on its measured GPU. The plain head's values do not depend on the + grid (basalt sizes it with the head kernel's own occupancy; the cap is the top-1's). The rows' loop steps an int + by 8 per threadgroup, as basalt's (q5k_head.cu:191-192, 249), so a grid whose last step would pass INT_MAX + (n_out > 2^31 - 8 * grid) is refused.""" + if n_out <= 0 or sm_count <= 0 or per_sm <= 0: + raise ValueError(f"basalt_q5k_head: n_out, sm_count and per_sm must be positive") + grid = min(-(-n_out // 8), sm_count * per_sm, cap) + if n_out > 2 ** 31 - 8 * grid: + raise ValueError(f"basalt_q5k_head: n_out {n_out} with {grid} threadgroups steps a row past INT_MAX") + return grid + + +def basalt_q5k_head_params(n_in: int, n_out: int, has_map: bool = False, n_blocks: int = 0) -> bytes: + """``Q5kHeadParams``: n_in, n_out (basalt's int: 1..INT_MAX), whether a map is bound, and for the top-1's merge + the first dispatch's threadgroup count.""" + if not 0 < n_out < 2 ** 31: + raise ValueError(f"basalt_q5k_head: n_out must be in 1..INT_MAX, got {n_out}") + return struct.pack(" int: + """``px::tiles``: tiles of 32 rows.""" + return (n + 31) // 32 + + +def basalt_q5k_proxy_bytes(n_cap: int) -> int: + """``q5k_proxy_bytes``: a 16-byte word per (tile, 64 weights, row), then two fp16 scales per word.""" + return basalt_q5k_proxy_tiles(n_cap) * 40 * 32 * (16 + 4) + + +def basalt_q5k_proxy_scratch_bytes(n_cap: int) -> int: + """``q5k_proxy_scratch_bytes``: the score's 4 candidates per tile, then its (max, sum) per tile, float2 each.""" + return basalt_q5k_proxy_tiles(n_cap) * (4 + 1) * 8 + + +def basalt_q5k_proxy_params(n_cap: int, *, row0: int = 0, n: int = 0, n_rows: Optional[int] = None) -> bytes: + """``PxParams`` (row0, n, n_cap, n_rows): a pack's (rows row0 .. row0 + n - 1 of a copy sized for n_cap; n_rows + None) or the score's and top-1's (the first n_rows rows). basalt's API refuses n_rows outside 1..n_cap + (q5k_head.cu:518), and n_rows is its int (at most INT_MAX); the port also refuses a pack past n_cap, which would + store outside the copy, and an n_cap past the 32-bit field (basalt's int64_t: a copy of 2^32 rows is 3.4 TB).""" + if (not 0 < n_cap < 2 ** 32 or row0 < 0 or n < 0 or row0 + n > n_cap + or (n_rows is not None and not 0 < n_rows <= min(n_cap, 2 ** 31 - 1))): + raise ValueError(f"basalt_q5k_proxy: rows out of range (row0 {row0}, n {n}, n_rows {n_rows}, n_cap {n_cap})") + return struct.pack(", MPP) diff --git a/monolith/ops/__init__.py b/monolith/ops/__init__.py index 456f2d0f..ea38d2f8 100644 --- a/monolith/ops/__init__.py +++ b/monolith/ops/__init__.py @@ -5,6 +5,6 @@ ``confidence``, ``verify_select``, ``accept_scan``); kernels bind to them per profile.""" from .registry import OPS, CostModel, KernelBinding, OpDef, register_op -from . import attention, draft, embed, gdn, gemv, moe, norm, sample # noqa: F401 (registration) +from . import attention, basalt, draft, embed, gdn, gemv, moe, norm, sample # noqa: F401 (registration) __all__ = ["OPS", "CostModel", "KernelBinding", "OpDef", "register_op"] diff --git a/monolith/ops/basalt.py b/monolith/ops/basalt.py new file mode 100644 index 00000000..638ff410 --- /dev/null +++ b/monolith/ops/basalt.py @@ -0,0 +1,54 @@ +"""basalt's single-dispatch GEMVs and q8_1 quantizers (OI-013; docs/design/flash-next.md): one op kind per basalt host +launcher, whose kernel and grid follow from the shape alone, as the launcher picks them. Each op is one dispatch of a +merged kernel (``kernels/common/basalt_*.metal``); the emitter (``compiler/emit_basalt.py``) takes its macros, grid, +threadgroup and params from ``monolith/kernels.py``'s builders only, never from the profile's crew or core count. + +Values. A weight is the GGUF tensor as shipped, ``[n_out, n_in]`` values: a weight value whose format is the ggml type's +name, or, for BF16 rows, a constant whose dtype is (a ``.basalt`` file's ``dense`` rows; ``packs/basalt.py``), never a +pack's block-lane-major slab. Activations are F32 ``[T, n]``; q8_1 rows are U8 ``[T, n_in / 32 * 36]``, column j's +36-byte blocks after column j - 1's (``basalt_q8_1.metal``). T, the window's columns, is the first output's rows. +Columns are contiguous: an output is exactly ``[T, n_out]``, an input exactly its op's width (basalt's kernels address +column j at j times the width). + +Programs. basalt captures one graph per window width (T = 1 .. 8) and bakes T into every launch, so these ops compile T +into their macros and params: one static program per width, sharing the weight windows by name. A dynamic-T program +is refused (it binds StepState, which none of these kernels reads). + +* ``basalt_q8_1``, attr ``quantizer``: ``native`` (``native_quantize_q8_1``) ``(x [T, n_in] F32)`` → ``xq``; + ``swiglu`` (``native_swiglu_quantize_q8_1``) ``(gate, up [T, n_in] F32)`` → the q8_1 rows of their SwiGLU; + ``ieee`` (``quantize_q8_1_rows``) ``(x)`` → ``xq`` in nvcc's IEEE arithmetic. n_in is a multiple of 32. The native + and SwiGLU kinds refuse more than 8 columns (basalt's ``validate_shape``); the IEEE rows feed only the routed experts + (basalt's F4), so any other reader is refused, and they are a buffer of their own: neither a view nor viewed. +* ``basalt_mmvq`` (``native_mmvq``): ``(xq, w [n_out, n_in])`` → ``y [T, n_out] F32``, w of a type of ``MMVQ_TRAITS``. +* ``basalt_dense_tc`` (``dense_tc``): the same values, w of a type of ``DENSE_TC_SB``, n_in a multiple of 512. The + summation order is the one basalt's variant rule picks on its 170 multiprocessors for a 16-byte-aligned weight + (``basalt_dense_tc_variant``'s defaults; every basalt weight is a 256-byte-aligned allocation), never the order this + GPU's core count or a binding's offset would give. +* ``basalt_dense_tc_pair`` (``dense_tc_pair``): ``(xq, w0 [n_out0, n_in], w1 [n_out1, n_in])`` → + ``(y0 [T, n_out0], y1 [T, n_out1])``, two projections of one input in the tile order. basalt runs it for every GDN + layer's qkv and z projections whose weights are both 16-byte aligned (``pair_ok``), which every ``.basalt`` binding + is. +* ``basalt_mmvf`` (``bf16_gemv_fp32_mmvf``, ``bf16_gemv_fp32_mmvf_multi``): ``(x [T, n_in] F32, w [n_out, n_in] bf16)`` + → ``y [T, n_out] F32``; the one-row kernel at T = 1, the multi-row kernel above, which gives every row the one-row + kernel's bits. + +Alignment, checked at every binding: 4 bytes for each q8_1, ``basalt_mmvq`` and ``basalt_dense_tc`` binding, and for +the BF16 GEMV's weight and output; 8 for the BF16 GEMV's activation (read as float2); 16 for both pair weights. +basalt's launchers check most of these (at b4c63b5): every pointer of ``native_mmvq`` and of the native and SwiGLU +quantizers at 4 (``validate_pointer``, ``native_mmvq.cu:1471-1475``, called by each type's launcher and at +``:1551-1552``, ``:1566-1568``), dense_tc's weight and rows at 4 (``dense_tc.cu:1078-1079``), the pair's weights at +16 and its rows at 4 (``:1109-1110``), the one-row BF16 GEMV's activation at 8 and its weight and output at 4 +(``native_bf16.cu:167-171``), the multi-row one's activation at 8 (``:142-143``). The port adds the rest, which +basalt's allocations meet unchecked: the IEEE quantizer's (``quantize_q8_1_rows`` checks none, +``iq_kernels.cu:2450-2455``), dense_tc's output, the pair's outputs, the multi-row BF16 GEMV's weight and output. +""" + +from ..core.ir import OpClass +from .registry import KernelBinding, OpDef, register_op + +BASALT_Q8_1 = register_op(OpDef("basalt_q8_1", OpClass.MAP, "rows").bind("*", KernelBinding("basalt_q8_1"))) +BASALT_MMVQ = register_op(OpDef("basalt_mmvq", OpClass.MAP, "rows").bind("*", KernelBinding("basalt_mmvq"))) +BASALT_MMVF = register_op(OpDef("basalt_mmvf", OpClass.MAP, "rows").bind("*", KernelBinding("basalt_mmvf"))) +BASALT_DENSE_TC = register_op(OpDef("basalt_dense_tc", OpClass.MAP, "rows").bind("*", KernelBinding("basalt_dense_tc"))) +BASALT_DENSE_TC_PAIR = register_op(OpDef("basalt_dense_tc_pair", OpClass.MAP, "rows") + .bind("*", KernelBinding("basalt_dense_tc_pair"))) diff --git a/monolith/packs/basalt.py b/monolith/packs/basalt.py new file mode 100644 index 00000000..8dc049e2 --- /dev/null +++ b/monolith/packs/basalt.py @@ -0,0 +1,141 @@ +"""A ``.basalt`` model file as a weight source beside :class:`~monolith.packs.packer.PackFile` (OI-013): the tensors +basalt's kernels read as shipped, each an absolute byte range of the file, by IR name. ``emit_program`` takes a source +wherever it takes a pack and binds each weight or constant value the source holds through a read-only window of the +file (``compiler/emit.py``, ``basalt_windows``), without a copy, as packs bind their slabs. Basalt copies these bytes +into CUDA allocations of its own; the bytes, and so every kernel's arithmetic, are the same. + +IR names and what each entry holds (``BasaltEntry``: absolute ``offset``, ``nbytes``, ggml ``type_id``, ``shape``): + +* ``gguf/``: a ``meta["tensors"]`` tensor (``BasaltFile.tensor``), its shape ``ne`` reversed (row-major: + ``(N, K)`` for a ``[K, N]`` GGUF matrix, ``(K,)`` for a vector); +* ``dense/``: a ``dense.index`` row basalt copies to its GPU arena byte for byte, kinds 2 (F32), 4 (BF16) and + 5 (F16) (basalt's weights.cpp), shape ``(ne1, ne0)``, or ``(ne0,)`` when ``ne1`` is 0; +* ``mtp/``: an ``mtp/dense.index`` tensor (``f32``, ``bf16``, ``q8_0``), shape ``(rows, cols)``; +* ``
``: a whole section (``mtp/experts``, ``experts`` …) as bytes, ``type_id`` None, shape ``(nbytes,)``. + +A value binds an entry only when it declares it exactly: a weight's format, or a constant's dtype, is the entry's +ggml type name (``u8`` for a section), and its shape is the entry's. Refused when a value binds it, with the reason: a +``dense`` row with no ggml type a value can declare (an ``in_gguf`` row, which ``gguf/`` serves; kind 0, basalt's +verbatim planes; kinds 1 and 3, which basalt converts at load) or with source bytes that do not fill its arena slot +exactly (basalt copies every source byte into the slot), a hyper-connection down/up matrix (``held_as_hc8``: basalt's +kernels read only its 8-bit copy, which the load quantizes from these bytes), a type the format plugins lack, a size +its type and shape do not give, an entry of no bytes. Two entries of one name make the file unreadable. + +``copy=True`` is a test mode: each bound tensor becomes a buffer of exactly its own bytes, so shader validation bounds +every access by its tensor, not by a page-rounded window that holds its neighbours too. The bytes are the same. +""" + +from __future__ import annotations + +import math +import os +from collections import namedtuple +from typing import Dict, Optional, Sequence + +from ..formats.basalt_reader import MTP_KINDS, BasaltFile +from ..formats.gguf import GGML_TYPES, ggml_row_bytes + +BasaltEntry = namedtuple("BasaltEntry", "name offset nbytes type_id shape") +DENSE_KINDS = {2: 0, 4: 30, 5: 1} # dense.index kinds copied as stored -> ggml type id (F32, BF16, F16) +HC8 = ("basalt's kernels read this hyper-connection matrix only through its 8-bit copy, which the load makes from the " + "stored form and then drops it (generate.cpp:2233-2244, :2319-2368 for the target; mtp.cpp:215-218, :254-260 " + "for the drafter; hc8_only() is true at hc_fused.cu:1250): only a port of that load-time quantizer may read it") + + +def held_as_hc8(name: str, mtp: Optional[tuple] = None) -> bool: + """Whether basalt leaves this matrix out of its arena on one GPU and computes with its 8-bit hyper-connection copy + instead: the target's ``blk.*.hc_{attn,ffn}_{down,up}.weight`` and ``output_hc_{down,up}.weight`` + (``generate.cpp:2235-2243``), or, for a drafter tensor ``mtp = (kind, rows, cols, nbytes)``, a bf16 + ``hyper_connection`` ``input_mix_weight_`` matrix of exactly ``rows * cols * 2`` bytes (``mtp.cpp:215-218``).""" + if mtp is not None: + kind, rows, cols, nbytes = mtp + return (kind == "bf16" and "hyper_connection" in name and "input_mix_weight_" in name + and rows * cols * 2 == nbytes) + return ((name.startswith("blk.") and name.endswith((".hc_attn_down.weight", ".hc_attn_up.weight", + ".hc_ffn_down.weight", ".hc_ffn_up.weight"))) + or name in ("output_hc_down.weight", "output_hc_up.weight")) + + +class BasaltSource: + """The bindable tensors of a ``.basalt`` file. ``file`` is the opened file (``BasaltFile(path)`` by default; any + ``BasaltFile`` over the same bytes works, such as a range reader); ``path`` is the file a program reads: the + windows map it, and the copy mode reads each tensor from it, so both modes serve the same bytes.""" + + slabs: Dict[str, dict] = {} # no block-lane-major slabs and no pack aux: the emitter's pack paths + aux: Dict[str, dict] = {} # find nothing here, and only its window planner reads a source + + def __init__(self, path: str | os.PathLike, file: Optional[BasaltFile] = None, *, copy: bool = False) -> None: + self.path = os.path.realpath(path) + self.file = f = file if file is not None else BasaltFile(self.path) + self.file_bytes = f.file_bytes + self.copy = copy + self.entries: Dict[str, BasaltEntry] = {} + self.refused: Dict[str, str] = {} # IR name -> why a value cannot bind it + if "meta" in f.sections and "gguf" in f.sections: + for name in f.meta().get("tensors", {}): + try: + t = f.tensor(name) + except ValueError as err: # a tensor the reader refuses is refused alone + self.refused[f"gguf/{name}"] = str(err) + continue + self._add(f"gguf/{name}", t.offset, t.nbytes, t.type_id, tuple(reversed(t.ne)), + HC8 if held_as_hc8(name) else None) + if "dense.index" in f.sections: + base = f.section("dense").offset + for r in f.dense_index().rows: + why = (HC8 if held_as_hc8(r.name) else + f"its bytes are in gguf: bind gguf/{r.name}" if r.in_gguf else + f"kind {r.kind} has no ggml type to declare (kind 0 is basalt's verbatim planes; it converts " + "kinds 1 and 3 at load)" if r.kind not in DENSE_KINDS else + f"its row gives {r.src_bytes} source bytes but a {r.dst_bytes}-byte slot (basalt's loader " + "copies every source byte into the slot)" if r.src_bytes != r.dst_bytes else None) + self._add(f"dense/{r.name}", base + r.src_off, r.src_bytes, DENSE_KINDS.get(r.kind), + (r.ne1, r.ne0) if r.ne1 else (r.ne0,), why) + if "mtp/dense.index" in f.sections: + base = f.section("mtp/dense").offset + for t in f.mtp_dense_index(): + self._add(f"mtp/{t.name}", base + t.offset, t.nbytes, MTP_KINDS.get(t.kind), (t.rows, t.cols), + HC8 if held_as_hc8(t.name, (t.kind, t.rows, t.cols, t.nbytes)) else + None if t.kind in MTP_KINDS else f"mtp kind {t.kind!r} has no format here") + for s in f.sections.values(): + self._add(s.name, s.offset, s.nbytes, None, (s.nbytes,)) + + def _add(self, name: str, offset: int, nbytes: int, type_id: Optional[int], shape: Sequence[int], + why: Optional[str] = None) -> None: + if name in self: + raise ValueError(f"{self.path}: two entries are named {name!r}") + if why is None and type_id is not None: # a section (no type) is bytes + if type_id not in GGML_TYPES: + why = f"ggml type {type_id} has no format here" + elif nbytes != ggml_row_bytes(type_id, shape[-1]) * math.prod(shape[:-1]): # exact: no int64 wrap + why = f"{nbytes} bytes are not {GGML_TYPES[type_id][0]} {list(shape)}" + if why is None and not nbytes: + why = "it holds no bytes" + if why is None: + self.entries[name] = BasaltEntry(name, offset, nbytes, type_id, tuple(shape)) + else: + self.refused[name] = why + + def __contains__(self, name: str) -> bool: + return name in self.entries or name in self.refused + + def bind(self, name: str, kind: str, shape: Sequence[int]) -> BasaltEntry: + """The entry a value named ``name`` binds: ``kind`` is a weight's format or a constant's dtype (``u8`` for a + section), ``shape`` the value's static shape. Refuses an entry that cannot be bound and a value that does not + declare its entry exactly.""" + if name in self.refused: + raise ValueError(f"{self.path}: {name!r} cannot be bound: {self.refused[name]}") + e = self.entries[name] + want = "u8" if e.type_id is None else GGML_TYPES[e.type_id][0] + if (kind, tuple(shape)) != (want, e.shape): + raise ValueError(f"{self.path}: {name!r} is {want} {list(e.shape)}; the graph declares {kind} {list(shape)}") + return e + + def read(self, e: BasaltEntry) -> bytes: + """``e``'s bytes from ``path``; refuses a file that ends inside them.""" + with open(self.path, "rb") as fh: + fh.seek(e.offset) + data = fh.read(e.nbytes) + if len(data) != e.nbytes: + raise ValueError(f"{self.path} ends inside {e.name!r} ({len(data)} of its {e.nbytes} bytes)") + return data diff --git a/monolith/runtime/engine.py b/monolith/runtime/engine.py index aeb3df98..34ce700f 100644 --- a/monolith/runtime/engine.py +++ b/monolith/runtime/engine.py @@ -2,6 +2,7 @@ from __future__ import annotations +import math from dataclasses import dataclass from typing import Dict, List, Optional @@ -75,6 +76,15 @@ def __init__(self, program: Program, device: Optional[nt.Device] = None, buffers buf.fill(0) self.buffers[name] = buf self.pipelines = compile_pipelines(program, self.dev, fast_math=fast_math, cache=pipeline_cache) + for key, pso in self.pipelines.items(): # the crews and butterflies take 32-lane SIMD-groups + if pso.thread_execution_width != 32: + raise ValueError(f"kernel {key}: SIMD-groups of {pso.thread_execution_width} lanes; the kernels " + "assume 32") + for o in program.ops: # a larger threadgroup would not run as encoded + limit = self.pipelines[o.kernel].max_threads_per_threadgroup + if math.prod(o.threadgroup) > limit: + raise ValueError(f"op {o.name or o.kernel}: a threadgroup of {math.prod(o.threadgroup)} threads; its " + f"pipeline takes at most {limit}") self.ops = [] for o in program.ops: d = nt.Dispatch().pipeline(self.pipelines[o.kernel]).grid(*o.grid).threadgroup(*o.threadgroup).barrier(o.barrier_before) diff --git a/pyproject.toml b/pyproject.toml index 757b59d4..d88c9d3a 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -34,3 +34,6 @@ include = ["monolith*"] [tool.pytest.ini_options] testpaths = ["tests"] addopts = "-q" +markers = [ + "slow: a case whose own timing makes it minutes long; run it with -m slow", +] diff --git a/runtime/CMakeLists.txt b/runtime/CMakeLists.txt index 1ec6f6ef..79a370b3 100644 --- a/runtime/CMakeLists.txt +++ b/runtime/CMakeLists.txt @@ -12,8 +12,21 @@ if(NOT NB_RC EQUAL 0) endif() list(APPEND CMAKE_PREFIX_PATH "${NB_DIR}") find_package(nanobind CONFIG REQUIRED) -nanobind_add_module(_native NB_STATIC src/native.mm src/metal_core.mm) +nanobind_add_module(_native NB_STATIC src/native.mm src/metal_core.mm src/basalt_cpu.cpp src/basalt_cpu_expf.cpp src/basalt_pool.cpp) set_source_files_properties(src/native.mm src/metal_core.mm PROPERTIES COMPILE_FLAGS "-fobjc-arc") +# basalt's CPU kernels transcribe two AVX-512 roundings (a vmulps then a vaddps) that a contracted fmla would +# collapse into one, changing the activation codes. Measured, Apple clang keeps them apart at every contraction +# setting while they are separate statements, so this pins the guarantee rather than repairing today's output; the +# Metal core keeps the default. These files must never see -ffast-math, which is a different hazard: it substitutes +# FMAXNM for the kernels' maxps selects [M], and FMAXNM returns the number where MAXPS returns its second operand, +# so every chunk holding a NaN would take a different maximum. +# +# The transcribed expf evaluates its polynomial as separate multiplies and adds, as the source it comes from does. +# Contracting those three sites is bit-neutral, measured over all 2^32 arguments; the flag holds the written form +# so that a build setting cannot silently choose a variant of the function, and the one site where the variants do +# part is written as an explicit fma instead, immune to the flag (runtime/src/basalt_cpu_expf.cpp, WHICH VARIANT, +# AND WHAT FUSES IN IT). +set_source_files_properties(src/basalt_cpu.cpp src/basalt_cpu_expf.cpp PROPERTIES COMPILE_FLAGS "-ffp-contract=off") target_include_directories(_native PRIVATE src) target_link_libraries(_native PRIVATE "-framework Metal" "-framework Foundation" "-framework IOKit") set(LITHOS_METAL_NATIVE_OUTPUT_DIRECTORY "${CMAKE_SOURCE_DIR}/monolith/runtime" CACHE PATH "Python extension output directory") diff --git a/runtime/src/basalt_cpu.cpp b/runtime/src/basalt_cpu.cpp new file mode 100644 index 00000000..3b4e925d --- /dev/null +++ b/runtime/src/basalt_cpu.cpp @@ -0,0 +1,358 @@ +// SPDX-License-Identifier: MIT +// Copyright (c) 2023-2026 The ggml authors (MIT) +// Copyright (c) 2026 Jesús Gulfo (MIT) +// Adapted from basalt (jesdga95/basalt) src/kernels/cpu/expert.cpp:143-148, :336-370, :503-556 and +// include/basalt/kernels/cpu/expert.hpp:25-61 @ b4c63b55754637f4c72ad53a0f791d425f71eb36 (MIT; third_party/NOTICE), +// which adapt ggml-org/llama.cpp ggml/src/ggml-common.h (block_q2_0) and ggml/src/ggml-quants.c +// (dequantize_row_q2_0's code rule) @ 3cf03257f219afbe7334045ff7c6a06ac68c627d (MIT; third_party/NOTICE). +// +// ============================== the transcription contract ============================== +// +// Every output bit must equal what basalt's AVX-512 kernels produce for the same input. No exception is left: the +// one place where the NEON path writes different bits is the payload of a NaN res[t], and THE NaN PATH below +// recomputes that row and token on a scalar path that applies x86's rules instead. These are the steps where the +// obvious NEON intrinsic silently changes bits, and what stands in for each AVX-512 instruction: +// +// _mm512_and_ps(x, 0x7fffffff) -> vabsq_f32 identical: clears the sign bit, NaN stays NaN. +// _mm512_max_ps, every reduce node -> maxps() below NOT vmaxq_f32 (FMAX keeps the NaN) and NOT +// vmaxnmq_f32 (FMAXNM keeps the number): MAXPS returns +// SRC2 on an unordered compare and on (+-0, -+0). +// _mm512_reduce_{add,max}_ps -> the trees below NOT vaddvq_f32 / vmaxvq_f32: FADDP pairs +// (t0+t1)+(t2+t3) where x86 gives (t0+t2)+(t1+t3), and +// FMAXV has the wrong NaN rule. +// _mm512_mul_ps then _mm512_add_ps -> vmulq_f32+vaddq_f32 TWO roundings. GCC 12.2/13.2/14.3/15.2 and Clang 21 +// (and p = d * s, rounded before use) all emit a separate vmulps and vaddps for these, so +// this TU is built -ffp-contract=off (CMakeLists.txt): +// a contracted fma(x, inv, +-0.5) changes codes. +// _mm512_fmadd_ps (acc, corr) -> vfmaq_f32 one rounding; FMA is wanted here, which is why +// contraction is turned off rather than globally fused. +// _mm512_cvttps_epi32 -> cvttps() below FCVTZS SATURATES (NaN -> 0, +inf -> INT32_MAX), which +// after the clamp would give 0 and +127 where x86 gives +// -127 for both; x86 returns the integer indefinite. +// _mm512_dpbusd_epi32 -> vdotq_s32 SDOT is signed x signed, VPDPBUSD unsigned x signed - +// equal here because the codes are 0..3. Vector j lane k +// covers weights 16j+4k .. 16j+4k+3, i.e. the x86 dword +// lane L = 4j + k, which holds weights 4L .. 4L+3. +// _mm512_multishift_epi64_epi8 -> vqtbl1q_u8 + vshlq_u8 + vandq_u8, decoding the documented rule +// code m = (qs[m/4] >> 2(m%4)) & 3 (ggml_quants.c:220-222), which is what +// VPMULTISHIFTQB with basalt's (ctrl, lanes) argument order produces. +// _mm256_cvtph_ps -> vcvt_f32_f16 both exact for every half, subnormals included, with +// MXCSR and FPCR at their defaults. +// _mm512_cvtepi32_epi8, _mm512_reduce_add_epi32 -> vmovn_s32/vmovn_s16, vaddvq_s32: exact after the clamp, and +// the integer sum is order-independent (|sum| <= 4064). +// +// The 16 x86 lanes are four float32x4_t: lane L lives in vector L/4 at position L%4. +// +// THE NaN PATH. res[t] is the one output whose bits the NEON path gets wrong, in two ways: AArch64 writes its +// default NaN 0x7fc00000 where x86 writes the floating-point indefinite 0xffc00000, sign bit set ([S] Intel SDM +// Vol. 1 4.8.3.7), and FMLA prefers the addend's NaN where VFMADD231PS prefers the multiplicand's. NaN-ness itself +// never differs - both ISAs make a NaN at the same sites from the same inputs - so the vector result decides: +// where res[t] is a NaN, x86_row() below recomputes that (row, token) lane by lane under x86's rules, picking the +// NaN at every site by an explicit bit test rather than letting FMUL, FMLA or FADD pick. That is not pedantry: +// this port's own NaN payloads move with clang's optimisation level, and LLVM's LangRef entitles no expression +// written in C to a particular payload. The replay runs on no finite row, so it costs nothing. +// +// What the port then guarantees, from the AVX-512 ground truth (a Xeon Platinum 8488C running basalt's own +// kernels at basalt's own flags; .context/basalt-port/pr21-ground-truth/pr21-x86-ground-truth.md, cited below as +// ground-truth:): +// - A row whose fp16 block scales are all non-NaN, with activations from act_quant_q8_1 - which never writes a +// NaN, since amax > 0 is an ordered compare and s = inf needs an infinite lane, whose sum <= -127 makes +// hx = s * sum = -inf rather than inf * 0: every NaN in res[t] was GENERATED, every generated NaN on x86 is +// the indefinite, and a propagated indefinite keeps its bits, so res[t] is exactly 0xffc00000. Measured over +// 2,506 such outputs under each of GCC 12.5, 13.4, 14.3 and 15.2 (ground-truth:375-378). +// - A row a NaN ENTERS - a NaN fp16 block scale, or a NaN planted in scale or hx through the binding - has no +// single x86 answer. The two halves of acc can end on different NaNs, and which one survives depends on the +// token slot, on how many tokens share the job and on the GCC version (ground-truth:379-389), so basalt's own +// x86 output there contradicts its promise that "Every token's output is bitwise the single-token job's" +// (pool.hpp:54-55). This port pins one of those answers: GCC 14.3's NT = 1 operand order, for every token +// slot, which is basalt 14.3's single-token job bit for bit and keeps the promise. That pin is a SECOND +// build-dependent value beside amax below - a basalt built by another GCC, or run with nt > 1, may hold +// different bits in this case alone. +// +// THE SUPPORTED INPUT RANGE, a decision of the engineering review. basalt's act_quant_q8_1 writes no NaN scale or +// hx for any float input (expert.cpp:352-367): a NaN amax fails amax > 0.f, so s = +0 (:353) and hx = +0 * sum is +// a zero (:367); a finite amax gives a finite s, so hx is finite or overflows to an infinity; and amax = +inf needs +// an infinite lane, whose t = inf * (1.f / s) = inf * 0 (:354, :356) is a NaN that VCVTTPS2DQ converts to INT_MIN +// and the clamp to -127, while every finite lane's t = +-0 gives 0 (:357-361), so sum <= -127 (:364) and +// hx = +inf * sum = -inf. Case A11 asserts the exact outputs for a single +inf, a single NaN and +inf with -inf. +// A NaN therefore enters a row only through a NaN fp16 block scale in the weights, which a valid model file does +// not hold: the pinned GCC 14.3 single-token rule above decides only rows of a corrupt weight file and test inputs, +// and every NaN generated from non-NaN inputs, an infinite activation's included, is 0xffc00000 under every build +// measured - basalt's under GCC 12.5, 13.4, 14.3 and 15.2 (ground-truth:375-378), this port's at -O0 and at the +// Release flags. +// +// THE TWO COMPILER-DEPENDENT VALUES. The first is amax. _mm512_reduce_max_ps is header-defined and basalt pins +// no compiler (README.md:35-43, CMakeLists.txt:45-46). GCC 14's gcc/config/i386/avx512fintrin.h:16339-16350 (used by +// _mm512_reduce_max_ps at :16359-16364) passes the HIGH half as SRC1 at the first two levels; Clang 21's +// avx512fintrin.h:9580 lowers __builtin_ia32_reduce_fmax_ps512 with the LOW half as SRC1. Levels 3 and 4 agree. +// MAXPS returns SRC2 on an unordered compare, so the two orders swallow different lanes and a chunk containing a +// NaN can get a different amax - sometimes a different FINITE amax. basalt's own binary therefore differs between +// its own builds and no bit-contract exists for a NaN activation. Clang's lowering also carries nnan, so there a +// NaN chunk's amax is undefined rather than merely differently ordered, and the low-half tree is the measured +// realisation of it [M]. This port writes GCC's order (basalt builds only on Linux - AGENTS.md:3, README.md:33 - +// where the default c++ is g++); flipping it is the operand order of the three maxps calls at the first two levels +// of reduce_max_ps. The second is the NaN path's pinned tree order above. _mm512_reduce_add_ps needs no choice for +// a NUMERIC result, but not because addition commutes: a reduction's bits follow its GROUPING, and both headers +// expand to the same four-level pairwise tree (GCC's avx512fintrin.h:16297-16306; Clang's reassoc +// llvm.vector.reduce.fadd, measured lowering [M]). Clang's reassoc licenses any association, so that agreement is +// a measurement to re-check, not a guarantee. Its per-node operand order is invisible to a numeric result and +// decides a NaN one, which is why the NaN path owns that order and the vector trees below do not. +// +// WHERE THE RESEARCH (docs/research/basalt-cpu-q2.md) AND basalt's SOURCE DISAGREE - the source governs: +// - Step 6's "inv = +inf when s < 2^-128" (:155) is off by one value: 1.f / 2^-128 is already +inf, so the band +// is s <= 2^-128. The source is a plain 1.f / s and that is what this file computes. A subnormal s ABOVE +// 2^-128 has a finite inv and ordinary codes. +// - Step 11's clamp acts on both sides. The low side is the integer indefinite: NaN, +-inf and overflow give +// -127. The high side needs a NaN in the chunk, because the reduce_max tree can then swallow the true peak: +// x = 0.1 everywhere, x[4] = 0.11, x[16] = NaN gives amax = 0.1 (GCC's maxps drops lane 4 through the NaN), +// so x[4] scales to r = 140.2 and clamps to +127 [M]. Without a NaN, |x| <= amax and the rounding is monotone, +// so trunc(r) never exceeds 127 over any positive finite amax with a finite inv (the largest r is 127.50003, +// at amax = 3.7322113794423347e-37) [M]. +// - A regime the specification does not name: amax > 0 with fl(amax / 127) == 0 makes s = 0, so the s > 0.f +// guard gives inv = 0 and every code 0, with scale = 0 and hx = +0.0. That is amax <= 63 * 2^-149; from +// 64 * 2^-149 the quotient rounds up to the subnormal s = 2^-149, whose inv is +inf, so every code is -127 [M]. +// basalt's act_quant_q8_1 opens with an --cpu-oracle-q8-0 branch (expert.cpp:337-340) that swaps the quantizer for +// quantize_oracle_q8_0, a debug path with an fp16 scale. It is not ported: the pack's sessions never set it, and +// the port reproduces the kernel this path runs, not basalt's debugging options. +#include "basalt_cpu.h" + +#include "basalt_x86.h" + +#if !defined(__ARM_NEON) +#error "basalt_cpu.cpp is an ARM NEON transcription of basalt's AVX-512 CPU kernels; build it on Apple silicon." +#endif + +#include + +#include +#include +#include +#include + +namespace monolith::basalt_cpu { +namespace { +using namespace x86; + + +/// MAXPS(SRC1, SRC2) per lane, exactly: "IF ((SRC1 = 0.0) and (SRC2 = 0.0)) THEN DEST := SRC2; ELSE IF (SRC1 = NaN) +/// THEN DEST := SRC2; ... ELSE IF (SRC2 = NaN) THEN DEST := SRC2; ... ELSE IF (SRC1 > SRC2) THEN DEST := SRC1; ELSE +/// DEST := SRC2" (Intel SDM, MAXPS Operation) - an ordered greater-than select, which is false for either NaN and +/// for (+-0, -+0). +inline float32x4_t maxps(float32x4_t src1, float32x4_t src2) { + return vbslq_f32(vcgtq_f32(src1, src2), src1, src2); +} + +/// _mm512_reduce_max_ps's four-level tree over the 16 lanes held as v[0..3], in GCC's operand order (see the +/// contract above): u[j] = maxps(v[j+8], v[j]), t[j] = maxps(u[j+4], u[j]), p0 = maxps(t0, t2), p1 = maxps(t1, t3), +/// res = maxps(p0, p1). +inline float reduce_max_ps(const float32x4_t v[4]) { + const float32x4_t u0 = maxps(v[2], v[0]); // SRC1 = the high half (Clang: maxps(v[0], v[2])) + const float32x4_t u1 = maxps(v[3], v[1]); // (Clang: maxps(v[1], v[3])) + const float32x4_t t = maxps(u1, u0); // SRC1 = the high quarter (Clang: maxps(u0, u1)) + const float32x4_t p = maxps(t, vextq_f32(t, t, 2)); // p[0] = maxps(t0, t2), p[1] = maxps(t1, t3) + return vgetq_lane_f32(maxps(p, vdupq_laneq_f32(p, 1)), 0); // maxps(p0, p1) +} + +/// _mm512_reduce_add_ps's four-level tree, same grouping. Written in GCC's operand order for symmetry; float +/// addition is bitwise commutative on non-NaN operands, so a numeric result does not depend on it, and a NaN one +/// is not taken from here at all (THE NaN PATH: x86_row() recomputes it). +inline float reduce_add_ps(const float32x4_t v[4]) { + const float32x4_t u0 = vaddq_f32(v[2], v[0]); + const float32x4_t u1 = vaddq_f32(v[3], v[1]); + const float32x4_t t = vaddq_f32(u1, u0); + const float32x4_t p = vaddq_f32(t, vextq_f32(t, t, 2)); // p[0] = t0 + t2, p[1] = t1 + t3 + return vgetq_lane_f32(p, 0) + vgetq_lane_f32(p, 1); +} + +/// _mm512_cvttps_epi32: truncation toward zero, and the integer indefinite 0x80000000 for a NaN, an infinity or a +/// value outside int32 (Intel SDM Vol. 1 Table 11-1 and D.4.2.2, with the invalid exception masked). vcagtq_f32 is +/// false for a NaN and for |r| >= 2^31, so the one select covers all of them; r = +-2^31 exactly lands on +/// INT32_MIN, which is what x86 gives there too. +inline int32x4_t cvttps_epi32(float32x4_t r) { + return vbslq_s32(vcagtq_f32(vdupq_n_f32(2147483648.0f), r), vcvtq_s32_f32(r), vdupq_n_s32(INT_MIN)); +} + +/// unpack64_q2_0 (expert.cpp:143-148): the 64 codes of one block in weight order, as four vectors - byte i of w[j] +/// is the code of weight 16j+i, which is (qs[(16j+i)/4] >> (2 * ((16j+i) % 4))) & 3. +inline void unpack64_q2_0(const uint8_t* codes, uint8x16_t w[4]) { + static const uint8_t kByte[16] = {0, 0, 0, 0, 1, 1, 1, 1, 2, 2, 2, 2, 3, 3, 3, 3}; // (16j+i)/4 - 4j + static const int8_t kShift[16] = {0, -2, -4, -6, 0, -2, -4, -6, 0, -2, -4, -6, 0, -2, -4, -6}; + const uint8x16_t qs = vld1q_u8(codes); + const uint8x16_t byte = vld1q_u8(kByte); + const int8x16_t shift = vld1q_s8(kShift); // USHL right-shifts where the count is negative + const uint8x16_t three = vdupq_n_u8(3); + for (int j = 0; j < 4; ++j) + w[j] = vandq_u8(vshlq_u8(vqtbl1q_u8(qs, vaddq_u8(byte, vdupq_n_u8((uint8_t) (4 * j)))), shift), three); +} + +/// The eight fp16 block scales of the group at b0, converted as _mm256_cvtph_ps does, with the tail left at +/// 0x0000 (= +0.0) exactly as basalt's sc[8] is (:523). vcvt_f32_f16 is VCVTPH2PS for every half, NaN payloads +/// included (case B6 checks all 65,536 against the x86 rule). +inline void group_scales(const uint8_t* row, int b0, int nb, float d[8]) { + alignas(16) uint16_t sc[8] = {0, 0, 0, 0, 0, 0, 0, 0}; + for (int i = 0; i < nb; ++i) std::memcpy(&sc[i], row + (size_t) (b0 + i) * BB, 2); + vst1q_f32(d, vcvt_f32_f16(vreinterpret_f16_u16(vld1_u16(sc)))); + vst1q_f32(d + 4, vcvt_f32_f16(vreinterpret_f16_u16(vld1_u16(sc + 4)))); +} + +// The x86 NaN rules these kernels apply live in basalt_x86.h, shared with the expert pool's SwiGLU. + +/// _mm512_reduce_add_ps as GCC 14.3's build emits it for a ONE-token job: SRC1 is the high half at levels 1 and 2, +/// the {2,3,0,1} shuffle at level 3 and lane 0 at level 4 ("hhs0" for both trees, ground-truth:270; level 3 is the +/// shuffle in every slot of every version, :342). Pinning NT = 1 for every token slot is what keeps pool.hpp:54-55. +inline float reduce_add_x86(const float v[16]) { + float u[8], t[4], w[2]; + for (int j = 0; j < 8; ++j) u[j] = x86_add(v[j + 8], v[j]); + for (int j = 0; j < 4; ++j) t[j] = x86_add(u[j + 4], u[j]); + for (int j = 0; j < 2; ++j) w[j] = x86_add(t[j + 2], t[j]); + return x86_add(w[0], w[1]); +} + +/// q2g_row_multi for ONE row and ONE token under the rules above, 16 lanes wide like the AVX-512 original: lane L +/// of the group at b0 takes block b0 + L/2's fp16 scale and the activation's chunk 2*b0 + L, and acc lanes 0-7 and +/// 8-15 take the block's first and second chunk. A single-accumulator loop would get the trees wrong. +/// The masked lanes (L >= 2 * nb) read nothing - they would read scale and hx past the width, which case B5 +/// poisons - but still run sites 1 and 2 on the zeros the masked loads leave, as x86's unmasked vmulps and +/// vfmadd231ps do. fma(+0, +0, corr) is corr except where corr is -0.0, and there it is +0.0; corr can be -0.0, +/// because an underflowing product rounds to a signed zero (dd * hx = 2^-24 * -2^-149 = -2^-173 gives -0.0). +float x86_row(const uint8_t* row, const ActQ* a, int nblocks) { + float acc[16] = {0.0f}, corr[16] = {0.0f}; + for (int b0 = 0; b0 < nblocks; b0 += 8) { + const int nb = nblocks - b0 < 8 ? nblocks - b0 : 8; + float d[8], p[16]; + group_scales(row, b0, nb, d); // d[nb..7] = +0.0: the masked dd + for (int L = 0; L < 16; ++L) { + const bool on = L < 2 * nb; + p[L] = x86_mul(d[L / 2], on ? a->scale[2 * b0 + L] : 0.0f); // site 1: vmulps, SRC1 = dd + corr[L] = x86_fma(d[L / 2], on ? a->hx[2 * b0 + L] : 0.0f, corr[L]); // site 2: dd, hx, corr + } + for (int i = 0; i < nb; ++i) { + const uint8_t* qs = row + (size_t) (b0 + i) * BB + 2; + const int8_t* q = a->q + (size_t) (b0 + i) * QK; + for (int L = 0; L < 16; ++L) { + int dot = 0; + for (int k = 0; k < 4; ++k) { + const int m = 4 * L + k; + dot += ((qs[m / 4] >> (2 * (m % 4))) & 3) * q[m]; + } + acc[L] = x86_fma(p[2 * i + (L >= 8)], (float) dot, acc[L]); // site 3: P, D (never a NaN), acc + } + } + } + return x86_sub(reduce_add_x86(acc), reduce_add_x86(corr)); // sites 4 and 5: vsubss, SRC1 = A +} + +/// q2g_row_multi (expert.cpp:503-533) for nt tokens. The port drops basalt's template switch, which is a +/// register-allocation device: a numeric result does not depend on NT (acc[t], corr[t] and p[t] are per token), +/// and a NaN one comes from x86_row(), which pins NT = 1 for every token slot (THE NaN PATH). +inline void q2g_row_multi(const uint8_t* row, const ActQ* const* a, int nt, int nblocks, float* res) { + float32x4_t acc[MAXT][4], corr[MAXT][4]; + for (int t = 0; t < nt; ++t) + for (int v = 0; v < 4; ++v) acc[t][v] = corr[t][v] = vdupq_n_f32(0.0f); + for (int b0 = 0; b0 < nblocks; b0 += 8) { + const int nb = nblocks - b0 < 8 ? nblocks - b0 : 8; + float d[8]; + group_scales(row, b0, nb, d); + // dd = permutexvar(dup, d8) masked by m16 = (1 << 2*nb) - 1: dd[L] = d[L/2] where 2*b0+L is a real chunk, + // +0.0 beyond - which the zero tail of sc already gives, since L >= 2*nb implies L/2 >= nb. + float32x4_t dd[4]; + for (int v = 0; v < 4; ++v) { + const float lane[4] = {d[(4 * v) / 2], d[(4 * v + 1) / 2], d[(4 * v + 2) / 2], d[(4 * v + 3) / 2]}; + dd[v] = vld1q_f32(lane); + } + float p[MAXT][8][2]; + for (int t = 0; t < nt; ++t) { + // corr_L = fma(dd_L, hx_{2*b0+L}, corr_L). The masked lanes read nothing (_mm512_maskz_loadu_ps does + // not touch them) but still run the FMA, as x86's does, with dd = hx = +0.0: fma(+0, +0, corr) is corr + // except where corr is -0.0 - an underflowing product leaves one, as in x86_row() - and +0.0 there. + float hx[16]; + for (int L = 0; L < 16; ++L) hx[L] = L < 2 * nb ? a[t]->hx[2 * b0 + L] : 0.0f; + for (int v = 0; v < 4; ++v) corr[t][v] = vfmaq_f32(corr[t][v], dd[v], vld1q_f32(hx + 4 * v)); + // p[2i+h] = RN(d_{b0+i} * scale_{2(b0+i)+h}): the lane-wise _mm512_mul_ps of :518, rounded before use. + // Only the lanes the permute of :528 can select are computed, which is also the whole read set. + for (int i = 0; i < nb; ++i) { + p[t][i][0] = d[i] * a[t]->scale[2 * (b0 + i)]; + p[t][i][1] = d[i] * a[t]->scale[2 * (b0 + i) + 1]; + } + } + for (int i = 0; i < nb; ++i) { + const int b = b0 + i; + uint8x16_t w[4]; + unpack64_q2_0(row + (size_t) b * BB + 2, w); + for (int t = 0; t < nt; ++t) { + const int8_t* q = a[t]->q + b * QK; + for (int v = 0; v < 4; ++v) { + // Lanes 0-7 (vectors 0-1) carry the block's first activation chunk, 8-15 (vectors 2-3) the + // second: the base + 2i permute of :524-528. + const int32x4_t dot = vdotq_s32(vdupq_n_s32(0), vreinterpretq_s8_u8(w[v]), vld1q_s8(q + 16 * v)); + acc[t][v] = vfmaq_f32(acc[t][v], vdupq_n_f32(p[t][i][v >> 1]), vcvtq_f32_s32(dot)); + } + } + } + } + for (int t = 0; t < nt; ++t) { + res[t] = reduce_add_ps(acc[t]) - reduce_add_ps(corr[t]); + // NaN-ness is the same on both ISAs, so the vector path decides WHETHER this row made a NaN and the + // scalar replay decides WHICH one (THE NaN PATH). + if (is_nan(res[t])) res[t] = x86_row(row, a[t], nblocks); + } +} + +} // namespace + +void act_quant_q8_1(const float* x, int n, ActQ& a) { + if (n <= 0 || n % QKA != 0 || n > H) // the header's precondition: q[0, n) and the chunk arrays must fit + throw std::invalid_argument("act_quant_q8_1: n must be a positive multiple of 32, at most 2560"); + a.nchunks = n / QKA; + const float32x4_t half = vdupq_n_f32(0.5f), mhalf = vdupq_n_f32(-0.5f), zero = vdupq_n_f32(0.0f); + const int32x4_t lo = vdupq_n_s32(-127), hi = vdupq_n_s32(127); + for (int k = 0; k < a.nchunks; ++k) { + const float* xb = x + k * QKA; + float32x4_t x0[4], x1[4], m[4]; + for (int v = 0; v < 4; ++v) { + x0[v] = vld1q_f32(xb + 4 * v); + x1[v] = vld1q_f32(xb + 16 + 4 * v); + m[v] = maxps(vabsq_f32(x0[v]), vabsq_f32(x1[v])); // SRC1 = |x0|, as _mm512_max_ps(abs(x0), abs(x1)) + } + const float amax = reduce_max_ps(m); + const float s = amax > 0.f ? amax / 127.f : 0.f; // ordered: a NaN amax gives s = +0.0 + const float inv = s > 0.f ? 1.f / s : 0.f; // s <= 2^-128 gives +inf; see the contract above + const float32x4_t vinv = vdupq_n_f32(inv); + int32x4_t v0[4], v1[4], sv = vdupq_n_s32(0); + for (int v = 0; v < 4; ++v) { + // r = t + (t >= 0 ? 0.5f : -0.5f), the ordered compare of :357-358: true for +0 and -0, false for a NaN. + const float32x4_t t0 = vmulq_f32(x0[v], vinv), t1 = vmulq_f32(x1[v], vinv); + const float32x4_t r0 = vaddq_f32(t0, vbslq_f32(vcgeq_f32(t0, zero), half, mhalf)); + const float32x4_t r1 = vaddq_f32(t1, vbslq_f32(vcgeq_f32(t1, zero), half, mhalf)); + v0[v] = vminq_s32(vmaxq_s32(cvttps_epi32(r0), lo), hi); + v1[v] = vminq_s32(vmaxq_s32(cvttps_epi32(r1), lo), hi); + sv = vaddq_s32(sv, vaddq_s32(v0[v], v1[v])); + } + int8_t* q = a.q + k * QKA; + vst1q_s8(q, vcombine_s8(vmovn_s16(vcombine_s16(vmovn_s32(v0[0]), vmovn_s32(v0[1]))), + vmovn_s16(vcombine_s16(vmovn_s32(v0[2]), vmovn_s32(v0[3]))))); + vst1q_s8(q + 16, vcombine_s8(vmovn_s16(vcombine_s16(vmovn_s32(v1[0]), vmovn_s32(v1[1]))), + vmovn_s16(vcombine_s16(vmovn_s32(v1[2]), vmovn_s32(v1[3]))))); + const int32_t sum = vaddvq_s32(sv); // |sum| <= 4064, so any order is exact + a.scale[k] = s; + a.sum[k] = sum; + a.hx[k] = s * (float) sum; + } +} + +void q2_0_gguf_rows_multi(const uint8_t* w, size_t row_bytes, int nblocks, const ActQ* const* a, int nt, + float* const* out, int r0, int r1) { + // The accumulators below are MAXT wide and the ActQ reads run to 64 * nblocks of an H-element array, so a + // caller past either bound writes or reads off the end. basalt bounds nt by instantiating q2g_rows<8> for + // every nt above 8 (expert.cpp:554); here it is a precondition the header states and this holds a C++ caller + // to. Not an assert: the wheel builds Release, which defines NDEBUG (setup.py:30). + if (nt < 1 || nt > MAXT || nblocks < 1 || nblocks > H / QK) + throw std::invalid_argument("q2_0_gguf_rows_multi: need 1 <= nt <= 8 and 1 <= nblocks <= 40"); + float res[MAXT]; + for (int r = r0; r < r1; ++r) { + q2g_row_multi(w + (size_t) r * row_bytes, a, nt, nblocks, res); + for (int t = 0; t < nt; ++t) out[t][r] = res[t]; // the ABSOLUTE row r, not r - r0 + } +} + +} // namespace monolith::basalt_cpu diff --git a/runtime/src/basalt_cpu.h b/runtime/src/basalt_cpu.h new file mode 100644 index 00000000..150566ca --- /dev/null +++ b/runtime/src/basalt_cpu.h @@ -0,0 +1,54 @@ +// SPDX-License-Identifier: MIT +// Copyright (c) 2023-2026 The ggml authors (MIT) +// Copyright (c) 2026 Jesús Gulfo (MIT) +// Adapted from basalt (jesdga95/basalt) src/kernels/cpu/expert.cpp:143-148, :336-370, :503-556 and +// include/basalt/kernels/cpu/expert.hpp:25-61 @ b4c63b55754637f4c72ad53a0f791d425f71eb36 (MIT; third_party/NOTICE), +// which adapt ggml-org/llama.cpp ggml/src/ggml-common.h (block_q2_0) and ggml/src/ggml-quants.c +// (dequantize_row_q2_0's code rule) @ 3cf03257f219afbe7334045ff7c6a06ac68c627d (MIT; third_party/NOTICE). +// +// basalt's two CPU Q2_0 kernels, transcribed to ARM NEON operation for operation: the activation quantizer the CPU +// expert tier feeds its dot products, and the Q2_0 GGUF row dot. basalt's signatures, unchanged, so its call sites +// (src/kernels/cpu/pool.cpp:423-444) transcribe one for one when the pool follows. +#pragma once + +#include +#include + +namespace monolith::basalt_cpu { + +// basalt's geometry (expert.hpp:25-36). H and MAXC bound the ActQ buffers; both kernels take their widths at run +// time (n, nblocks, row_bytes), so nothing here pins a model. +inline constexpr int H = 2560; // n_embd: the widest reduction an ActQ holds +inline constexpr int FF = 640; // expert intermediate width: the second width the pool's callers quantize +inline constexpr int QK = 64; // QK2_0: weights per fp16 block scale +inline constexpr int QKA = 32; // activation elements per q8_1 scale +inline constexpr int BB = 18; // bytes per Q2_0 block: fp16 scale, then 16 code bytes +inline constexpr int MAXC = H / QKA; // 80 activation chunks +inline constexpr int MAXT = 8; // tokens per job (expert.hpp:122) + +/// One quantized activation, field for field as expert.hpp:55-61 declares it. +/// hx[k] = scale[k] * (float) sum[k] is the weight-independent correction the Q2_0 identity needs. +struct ActQ { + alignas(64) int8_t q[H]; + float scale[MAXC]; + int32_t sum[MAXC]; + float hx[MAXC]; + int nchunks; +}; + +/// expert.cpp:336-370 (the AVX-512 block; the scalar loop after it is unreachable, and the --cpu-oracle-q8-0 +/// branch at :337-340 is not ported). Writes q[0, n), and scale / sum / hx over [0, n / QKA), and sets nchunks. +/// n must be a positive multiple of QKA, at most H; the kernel throws std::invalid_argument otherwise. +void act_quant_q8_1(const float* x, int n, ActQ& a); + +/// expert.cpp:544-556 through q2g_rows / q2g_row_multi. Row r is w + r * row_bytes; out[t] is indexed by the +/// ABSOLUTE row r, and rows outside [r0, r1) are left alone. Reads a[t]->q[0, 64 * nblocks), +/// a[t]->scale[0, 2 * nblocks) and a[t]->hx[0, 2 * nblocks), and nothing else - never nchunks, never sum. +/// nt must be 1..MAXT and nblocks 1..H / QK: the per-token accumulators are MAXT wide and the reads above run to +/// 64 * nblocks of an H-element array. basalt bounds nt by instantiating q2g_rows<8> for every nt above 8 +/// (expert.cpp:554); the caller here bounds it, and the kernel throws std::invalid_argument on either, in a form +/// that survives the Release build's NDEBUG. +void q2_0_gguf_rows_multi(const uint8_t* w, size_t row_bytes, int nblocks, const ActQ* const* a, int nt, + float* const* out, int r0, int r1); + +} // namespace monolith::basalt_cpu diff --git a/runtime/src/basalt_cpu_expf.cpp b/runtime/src/basalt_cpu_expf.cpp new file mode 100644 index 00000000..ea3ca3f9 --- /dev/null +++ b/runtime/src/basalt_cpu_expf.cpp @@ -0,0 +1,168 @@ +// SPDX-License-Identifier: MIT +// Copyright (c) 2017-2025, Arm Limited (MIT OR Apache-2.0 WITH LLVM-exception; taken under MIT) +// Copyright (c) 2026 Jesús Gulfo (MIT) +// Adapted from ARM-software/optimized-routines math/expf.c and math/exp2f_data.c @ +// f67e7daa5457646fad9f75580263dba654c988aa (third_party/NOTICE, third_party/ARM-OPTIMIZED-ROUTINES-LICENSE), with +// the error returns of math/math_errf.c and the helpers of math/math_config.h at the same commit; and from basalt +// (jesdga95/basalt) src/kernels/cpu/pool.cpp:434 @ b4c63b55754637f4c72ad53a0f791d425f71eb36 (MIT; +// third_party/NOTICE): the SwiGLU expression, in its order. +// +// WHICH BUILD OF ARM'S SOURCE THIS IS. The file has knobs; glibc picks these, and they are the ones transcribed. +// * The `#else` of TOINT_INTRINSICS: `kd = z + SHIFT; ki = asuint64(kd); kd -= SHIFT`, which rounds to nearest +// EVEN. glibc leaves TOINT_INTRINSICS at the 0 its own header defaults it to, and defines it nowhere else, so +// every architecture's glibc compiles that branch [M, glibc 2.39's single sysdeps/ieee754/flt-32/math_config.h, +// lines 40-44]. `round`/`lround`, which the other branch uses, take a tie away from zero instead, and that +// branch would be the same function here anyway: over all 2^32 patterns on which the main path runs, +// `InvLn2N * (double) x` is never exactly k + 0.5 [M, swept here], so no argument reaches a tie. +// * WANT_ERRNO_UFLOW = 1, which glibc derives from WANT_ROUNDING && WANT_ERRNO: x in +// [-0x1.9fe368p6, -0x1.9d1d9ep6) returns (0x1.4p-75f)^2 rather than taking the main path. Under round to +// nearest that changes errno and not the result: the main path computes 0x00000001 at all 90,854 arguments of +// the band [M, swept here], which is what the branch returns. It is transcribed because glibc has it. +// * `poly_scaled` and `invln2_scaled`, the N = 32 rows; `poly` and `shift_scaled` belong to exp2f and powf. +// `eval_as_double` and `eval_as_float` are Arm's no-ops for FLT_EVAL_METHOD == 0, which is arm64 and x86-64 SSE2; +// the casts are written out instead, and `unlikely` on the special-case branch, a hint with no arithmetic in it, +// is dropped. errno is not set - ERANGE is all glibc adds there, nothing in this tree reads it, and the returned +// bits are the contract. +// +// WHICH VARIANT, AND WHAT FUSES IN IT. Arm writes every multiply-add with operators and leaves contraction to the +// compiler, so the source alone does not say what the function is. glibc's x86-64 multiarch holds __expf_fma, +// this same source compiled with -mfma -mavx2, and an ifunc picks it on any host with FMA and AVX2 - every host +// that can run basalt's AVX-512 expert kernels. That is the variant basalt runs and the one transcribed here. The +// contraction sites are the three of the polynomial - `C[0]*r + C[1]`, `C[2]*r + 1`, `z*r2 + y` - and, once +// `z = InvLn2N * xd` is substituted, `z + SHIFT` and `z - kd`; `r2 = r*r` and `y = y*s` have nothing to fuse into. +// Both orders were built here and swept over all 2^32 float inputs [M, Apple clang 21.0.0, -O2]: +// * The three polynomial sites: `std::fma` at all three returns the identical bits at every one of the 2^32 +// inputs. The double carries 29 bits more than the float it is rounded back to, which is why fusing a double +// rounding this far from the boundary cannot be seen. Written as Arm writes them, left to the build flag. +// * `z + SHIFT` and `z - kd`: fusing those two changes 2 of the 2^32 - 0x4202422f (32.5646324), where unfused +// gives 0x56fc9f1b and fused 0x56fc9f1c, and 0xc27c65d9 - because the fused form subtracts kd from the +// unrounded product, where `z - kd` as written subtracts it from the rounded z and is itself exact. A +// different r is a different function, and this is the one place the two glibc variants part: __expf_fma +// fuses them and __expf_sse2 does not [M, Xeon Platinum 8375C, glibc 2.39-0ubuntu8.9, the ifunc intact and +// again with GLIBC_TUNABLES disabling AVX2 and FMA]. They are written as explicit `std::fma` below so that +// -ffp-contract cannot decide which function this is. +// The file is still built with -ffp-contract=off (runtime/CMakeLists.txt): that pins the polynomial, where Arm's +// operators stand, and the two explicit calls stand over it. +// +// WHERE NaN BITS COME FROM. x86 writes the floating-point indefinite 0xffc00000, sign bit set, where AArch64 +// writes the default NaN 0x7fc00000 ([S] Intel SDM Vol. 1 4.8.3.7; [S] Arm ARM A1.5.3), and an SSE scalar +// operation that is handed a NaN returns the first of its sources that is one, quieted. expf itself needs no +// helper - its NaN return is `x + x`, which quiets the argument's payload and sign on both architectures - and +// neither does the SwiGLU's add, whose only invalid form is inf + -inf and whose `e` is never negative [M: swept +// here, expf_glibc returns no negative value at any of the 2^32 arguments]. The divide and the multiply do reach +// the indefinite from finite or infinite inputs. All three are written below as the x86 instructions basalt's +// codegen emits rather than as C operators, the add for fidelity to what basalt executes. + +#include "basalt_cpu_expf.h" + +#include "basalt_x86.h" + +#include +#include +#include +#include + +namespace monolith::basalt_cpu { + +using namespace x86; +namespace { + +constexpr int EXP2F_TABLE_BITS = 5; +constexpr int N = 1 << EXP2F_TABLE_BITS; + +// exp2f_data.c, the N == 32 rows, copied. tab[i] = uint(2^(i/N)) - (i << 52-BITS), used for computing 2^(k/N) for +// an int |k| < 150 N as double(tab[k%N] + (k << 52-BITS)). +constexpr uint64_t T[N] = { + 0x3ff0000000000000, 0x3fefd9b0d3158574, 0x3fefb5586cf9890f, 0x3fef9301d0125b51, + 0x3fef72b83c7d517b, 0x3fef54873168b9aa, 0x3fef387a6e756238, 0x3fef1e9df51fdee1, + 0x3fef06fe0a31b715, 0x3feef1a7373aa9cb, 0x3feedea64c123422, 0x3feece086061892d, + 0x3feebfdad5362a27, 0x3feeb42b569d4f82, 0x3feeab07dd485429, 0x3feea47eb03a5585, + 0x3feea09e667f3bcd, 0x3fee9f75e8ec5f74, 0x3feea11473eb0187, 0x3feea589994cce13, + 0x3feeace5422aa0db, 0x3feeb737b0cdc5e5, 0x3feec49182a3f090, 0x3feed503b23e255d, + 0x3feee89f995ad3ad, 0x3feeff76f2fb5e47, 0x3fef199bdd85529c, 0x3fef3720dcef9069, + 0x3fef5818dcfba487, 0x3fef7c97337b9b5f, 0x3fefa4afa2a490da, 0x3fefd0765b6e4540, +}; +constexpr double InvLn2N = 0x1.71547652b82fep+0 * N; +constexpr double SHIFT = 0x1.8p+52; +constexpr double C[3] = {0x1.c6af84b912394p-5 / N / N / N, 0x1.ebfce50fac4f3p-3 / N / N, 0x1.62e42ff0c52d6p-1 / N}; + +inline uint32_t asuint(float f) { return std::bit_cast(f); } +inline uint64_t asuint64(double f) { return std::bit_cast(f); } +inline double asdouble(uint64_t i) { return std::bit_cast(i); } +inline uint32_t top12(float x) { return asuint(x) >> 20; } + +// math_config.h's barrier for a target without the aarch64 asm, and math_errf.c's xflowf: the value is the +// product, so the bits and the floating-point flag both come out of the arithmetic rather than a literal. +inline float opt_barrier_float(float x) { + volatile float y = x; + return y; +} +inline float xflowf(uint32_t sign, float y) { return opt_barrier_float(sign ? -y : y) * y; } +inline float math_oflowf(uint32_t sign) { return xflowf(sign, 0x1p97f); } // -> +-inf +inline float math_uflowf(uint32_t sign) { return xflowf(sign, 0x1p-95f); } // -> +-0 +inline float math_may_uflowf(uint32_t sign) { return xflowf(sign, 0x1.4p-75f); } // -> +-0x1p-149 + +} // namespace + +// expf.c, operation for operation. EXP2F_TABLE_BITS = 5, EXP2F_POLY_ORDER = 3; Arm records the worst case as +// 0.502 ulp (nearest rounding) and the relative error before rounding as 1.69 * 2^-34 in [-ln2/64, ln2/64]. +float expf_glibc(float x) { + uint32_t abstop; + uint64_t ki, t; + double kd, xd, z, r, r2, y, s; + + xd = x; + abstop = top12(x) & 0x7ff; + if (abstop >= top12(88.0f)) { + /* |x| >= 88 or x is nan. */ + if (asuint(x) == asuint(-std::numeric_limits::infinity())) return 0.0f; + if (abstop >= top12(std::numeric_limits::infinity())) return x + x; // +inf, or a NaN quieted + if (x > 0x1.62e42ep6f) /* x > log(0x1p128) ~= 88.72 */ + return math_oflowf(0); + if (x < -0x1.9fe368p6f) /* x < log(0x1p-150) ~= -103.97 */ + return math_uflowf(0); + if (x < -0x1.9d1d9ep6f) /* x < log(0x1p-149) ~= -103.28 */ + return math_may_uflowf(0); + } + + /* x*N/Ln2 = k + r with r in [-1/2, 1/2] and int k. */ + z = InvLn2N * xd; + + /* Round and convert z to int, the result is in [-150*N, 128*N] and + ideally nearest int is used, otherwise the magnitude of r can be + bigger which gives larger approximation error. */ + // Written as explicit fma, not left to the compiler: glibc's x86-64 ifunc picks __expf_fma on any host with + // FMA and AVX2, which is every host basalt's AVX-512 expert kernels run on, and its disassembly fuses these two + // (libm+0x7dc40, glibc 2.39-0ubuntu8.9, measured). The two variants differ at exactly two of the 2^32 float32 + // arguments, 0x4202422f and 0xc27c65d9, where the fused rounding step rounds the other way; basalt holds the + // fused bits, so the port computes them whatever -ffp-contract says. + kd = std::fma(InvLn2N, xd, SHIFT); + ki = asuint64(kd); + kd -= SHIFT; + r = std::fma(InvLn2N, xd, -kd); + + /* exp(x) = 2^(k/N) * 2^(r/N) ~= s * (C0*r^3 + C1*r^2 + C2*r + 1) */ + t = T[ki % N]; + t += ki << (52 - EXP2F_TABLE_BITS); + s = asdouble(t); + z = C[0] * r + C[1]; + r2 = r * r; + y = C[2] * r + 1; + y = z * r2 + y; + y = y * s; + return (float) y; +} + +float swiglu(float g, float u) { + // gcc 14.3 at -O3 compiles pool.cpp:434 to a sign flip, one scalar `call expf`, `addss` 1.0f, `divss`, `mulss` + // and a store [M, docs/research/basalt-cpu-expf.md section 2]. The add takes `e` as SRC1 and the constant as + // SRC2, which is the source's operands swapped and exact, since 1.f is never a NaN; + // the divide takes `g`, which does not commute; the multiply takes the quotient, which is why a NaN `g` with + // a NaN `u` returns the quotient's payload and not `u`'s. + const float e = expf_glibc(-g); + const float d = x86_add(e, 1.f); + const float q = x86_div(g, d); + return x86_mul(q, u); +} + +} // namespace monolith::basalt_cpu diff --git a/runtime/src/basalt_cpu_expf.h b/runtime/src/basalt_cpu_expf.h new file mode 100644 index 00000000..76826e30 --- /dev/null +++ b/runtime/src/basalt_cpu_expf.h @@ -0,0 +1,26 @@ +// SPDX-License-Identifier: MIT +// Copyright (c) 2017-2025, Arm Limited (MIT OR Apache-2.0 WITH LLVM-exception; taken under MIT) +// Copyright (c) 2026 Jesús Gulfo (MIT) +// Adapted from ARM-software/optimized-routines math/expf.c and math/exp2f_data.c @ +// f67e7daa5457646fad9f75580263dba654c988aa (third_party/NOTICE, third_party/ARM-OPTIMIZED-ROUTINES-LICENSE), the +// source glibc's generic expf has carried since 2017 (sysdeps/ieee754/flt-32/e_expf.c); and from basalt +// (jesdga95/basalt) src/kernels/cpu/pool.cpp:434 @ b4c63b55754637f4c72ad53a0f791d425f71eb36 (MIT; +// third_party/NOTICE): the SwiGLU expression the CPU expert pool applies, in its order. +// +// The one piece of arithmetic basalt's CPU expert pool performs itself. basalt runs on Linux with glibc, where the +// `std::exp` of a float at pool.cpp:434 is glibc's `expf`; Apple's `expf` is a different implementation and neither +// is correctly rounded, so calling the platform's cannot be bit-exact. These are the algorithm and the table +// instead, in portable C++. +#pragma once + +namespace monolith::basalt_cpu { + +/// glibc's `expf`, transcribed from the Arm source it is compiled from: 0.502 ulp worst case under round to +/// nearest, not correctly rounded. Every input is valid, specials included. +float expf_glibc(float x); + +/// basalt's SwiGLU, `(g / (1.f + std::exp(-g))) * u` (pool.cpp:434) - the add, the divide and the multiply in the +/// order gcc emits them, each with the NaN x86 writes, which are both part of the result. +float swiglu(float g, float u); + +} // namespace monolith::basalt_cpu diff --git a/runtime/src/basalt_pool.cpp b/runtime/src/basalt_pool.cpp new file mode 100644 index 00000000..55b883d8 --- /dev/null +++ b/runtime/src/basalt_pool.cpp @@ -0,0 +1,318 @@ +// SPDX-License-Identifier: MIT +// Copyright (c) 2026 Jesús Gulfo (MIT) +// Adapted from basalt (jesdga95/basalt) src/kernels/cpu/pool.cpp @ b4c63b55754637f4c72ad53a0f791d425f71eb36 +// (MIT; third_party/NOTICE): the constructor, `publish`, `worker`, `claim`, `begin_batch`, `wait_parked`, +// `wait_done` and `run_phase`, transcribed with the memory orders as written. +// +// The memory orders are the specification, not a detail. docs/research/basalt-cpu-pool.md section 1.5 lists every +// one against its line in basalt, and two of them carry arguments that break if weakened: +// +// * `publish` and the sleep path are BOTH seq_cst, and that is the whole lost-wakeup argument: a worker going to +// sleep does `sleepers_++` then reads `epoch_`, the host does `epoch_++` then reads `sleepers_`. In one total +// order at least one sees the other's write, so either the worker sees the new epoch and does not sleep, or +// the host sees the sleeper and notifies under the mutex the worker holds until it is inside `wait`. The +// store-buffer interleaving in which neither sees the other is exactly what seq_cst forbids. On arm64 this is +// not free, where basalt's comment says it costs x86 nothing: the seq_cst load is `ldar` where an acquire +// load would be `ldapr`, and `ldar` is what orders it against the `ldaddal` before it [M, Apple clang 21.0.0, +// -O2, arm64; no `dmb` is emitted, the LSE and RCpc instructions carrying it]. It is still required. +// * The batch description is plain, and is made visible solely by the release store of `head_` and the matching +// acquire load in `claim`. + +#include "basalt_pool.h" + +#include +#include + +namespace monolith::basalt_cpu { + +namespace { + +/// `_mm_pause()`'s place. There is no SMT sibling on this chip to yield to, so the hint's only job is to lower the +/// spin's power and memory traffic. +inline void spin_pause() { +#if defined(__aarch64__) || defined(__arm64__) + __asm__ __volatile__("yield" ::: "memory"); +#else + __asm__ __volatile__("pause" ::: "memory"); +#endif +} + +/// epoch << 32 | njobs << 16 | next index (`pool.cpp:22-24`). +constexpr uint64_t pack_head(uint32_t epoch, uint32_t n, uint32_t i) { + return ((uint64_t) epoch << 32) | ((uint64_t) n << 16) | (uint64_t) i; +} + +double ms_since(std::chrono::steady_clock::time_point t0) { + return std::chrono::duration(std::chrono::steady_clock::now() - t0).count(); +} + +} // namespace + +ExpertPool::ExpertPool(int n_workers, bool host_works, std::chrono::microseconds spin_before_sleep) + : host_works_(host_works), spin_before_sleep_(spin_before_sleep) { + if (n_workers > 0) { + n_ = n_workers; + } else { + // basalt drops the first physical core and keeps one logical per physical. This chip has no SMT and no way + // to pin, so that collapses to "every core but the host's". + const unsigned hc = std::thread::hardware_concurrency(); + n_ = hc > 1 ? (int) hc - 1 : 1; + } + if (n_ < 1) n_ = 1; + + wstate_.reset(new std::atomic[(size_t) n_]); + for (int i = 0; i < n_; ++i) wstate_[(size_t) i].store(kParked); + scratch_.resize((size_t) n_ + 1); // one per worker, plus the host's at index n_ + threads_.reserve((size_t) n_); + for (int i = 0; i < n_; ++i) threads_.emplace_back([this, i] { worker(i); }); +} + +ExpertPool::~ExpertPool() { + stop_.store(true, std::memory_order_release); + publish(); // so a PARKED worker notices the stop flag rather than sleeping through it + for (auto& t : threads_) t.join(); +} + +bool ExpertPool::claim_owner(const void* owner) { + const void* expected = nullptr; + return owner_.compare_exchange_strong(expected, owner, std::memory_order_acq_rel, std::memory_order_acquire) || + expected == owner; +} + +void ExpertPool::release_owner(const void* owner) { + const void* expected = owner; + owner_.compare_exchange_strong(expected, nullptr, std::memory_order_acq_rel, std::memory_order_acquire); +} + +void* ExpertPool::scratch(int worker_id, size_t bytes) { + const size_t slot = worker_id < 0 ? (size_t) n_ : (size_t) worker_id; + auto& buf = scratch_[slot]; + if (buf.size() < bytes) buf.assign(bytes, 0); + return buf.data(); +} + +void ExpertPool::publish() { + epoch_.fetch_add(1, std::memory_order_seq_cst); + if (sleepers_.load(std::memory_order_seq_cst) != 0) { + std::lock_guard lk(sleep_mu_); + sleep_cv_.notify_all(); + } +} + +uint32_t ExpertPool::begin_batch(int n) { + // Every job of the previous batch has completed (`wait_done`), and a claim of it can no longer succeed, so + // nothing adds to `done` until this batch's first claim, which the release below orders after the reset. + done_.store(0, std::memory_order_relaxed); + const uint32_t e = epoch_.load(std::memory_order_relaxed) + 1; // only the host bumps the epoch + head_.store(pack_head(e, (uint32_t) n, 0), std::memory_order_release); + publish(); + return e; +} + +int ExpertPool::claim(uint32_t epoch) { + uint64_t h = head_.load(std::memory_order_acquire); + for (;;) { + if ((uint32_t) (h >> 32) != epoch) return -1; // not the batch this thread woke for + const uint32_t n = (uint32_t) (h >> 16) & 0xffffu, i = (uint32_t) h & 0xffffu; + if (i >= n) return -1; // exhausted + // h + 1 increments the index field only: i < n <= 0xffff, so it never carries into njobs. + if (head_.compare_exchange_weak(h, h + 1, std::memory_order_acq_rel, std::memory_order_acquire)) + return (int) i; + } +} + +void ExpertPool::drain(int id, uint32_t epoch) { + for (;;) { + const int job = claim(epoch); + if (job < 0) return; + // Read AFTER the claim, never before it. The claim's acquire load of `head_` is the only thing that + // orders this plain member against the host's write of it, and a read hoisted above the claim is a data + // race on the host's next phase even though every worker reaching here came through an acquire of + // `epoch_` (ThreadSanitizer reports it; the first draft of this file had the read at the top). + (*body_)(job, id); + done_.fetch_add(1, std::memory_order_release); + } +} + +void ExpertPool::worker(int id) { + uint32_t seen = epoch_.load(std::memory_order_acquire); + // ARRIVE at the park before the first wait, so `parked_ == n_` is true from construction. Counting only on the + // return from a drain leaves `parked_` at 0 until each worker has finished one batch, and the first phase, + // which waits for `parked_ == n_` before publishing, then deadlocks. + parked_.fetch_add(1, std::memory_order_acq_rel); + for (;;) { + const auto parked_at = std::chrono::steady_clock::now(); + uint32_t spins = 0; + while (epoch_.load(std::memory_order_acquire) == seen) { + if (stop_.load(std::memory_order_relaxed)) return; + spin_pause(); + if ((++spins & (kSpinSample - 1)) != 0) continue; // the clock is read once per 1024 pauses, + if (std::chrono::steady_clock::now() - parked_at < spin_before_sleep_) continue; // so the spin is unchanged + std::unique_lock lk(sleep_mu_); + wstate_[(size_t) id].store(kSleeping, std::memory_order_relaxed); + sleepers_.fetch_add(1, std::memory_order_seq_cst); + sleep_cv_.wait(lk, [&] { + return epoch_.load(std::memory_order_seq_cst) != seen || stop_.load(std::memory_order_relaxed); + }); + sleepers_.fetch_sub(1, std::memory_order_relaxed); + wstate_[(size_t) id].store(kParked, std::memory_order_relaxed); + } + if (stop_.load(std::memory_order_acquire)) return; + seen = epoch_.load(std::memory_order_acquire); + parked_.fetch_sub(1, std::memory_order_acq_rel); // leaving the park + wstate_[(size_t) id].store(kBetween, std::memory_order_relaxed); + drain(id, seen); + wstate_[(size_t) id].store(kParked, std::memory_order_relaxed); + parked_.fetch_add(1, std::memory_order_acq_rel); + } +} + +void ExpertPool::poison() { + poisoned_.store(true, std::memory_order_release); + // Exhaust the queue in the same step. A worker blocked inside its job is unreachable, but it returns to + // `drain` eventually, and `claim` tests only the epoch and the index: without this it would take the rest of + // this batch and call a body whose owner has already returned. Setting the index to the job count makes every + // later claim fail, and the epoch field is left alone so a claim in flight still fails on it. + uint64_t h = head_.load(std::memory_order_acquire); + for (;;) { + const uint64_t n = (h >> 16) & 0xffffu; + const uint64_t drained = (h & ~0xffffull) | n; // index := njobs + if (head_.compare_exchange_weak(h, drained, std::memory_order_acq_rel, std::memory_order_acquire)) return; + } +} + +bool ExpertPool::wait_parked(const char* what, std::string& error) { + hstate_.store(kWaitParked, std::memory_order_relaxed); + uint32_t spins = 0; + // Armed once, where basalt re-arms it whenever `spins` hits 1024 and so restarts the clock every 2^32 + // iterations. The transcribed body costs 0.422 ns here, which is 1.8 s per wrap against a 60 s limit [M]. + const auto t0 = std::chrono::steady_clock::now(); + while (parked_.load(std::memory_order_acquire) != (uint32_t) n_) { + spin_pause(); + if ((++spins & (kSpinSample - 1)) != 0) continue; + if (std::chrono::steady_clock::now() - t0 > kStall) { + poison(); + error = std::string("the CPU expert pool stalled ") + what + " (" + + std::to_string(parked_.load(std::memory_order_acquire)) + " of " + std::to_string(n_) + + " workers parked)"; + return false; + } + } + return true; +} + +bool ExpertPool::wait_done(int n, std::string& error) { + hstate_.store(kWaitDone, std::memory_order_relaxed); + uint32_t spins = 0; + auto t0 = std::chrono::steady_clock::now(); + uint32_t seen = 0; + for (;;) { + const uint32_t d = done_.load(std::memory_order_acquire); + if (d >= (uint32_t) n) return true; // >=: never a wait that an overshoot outlives + spin_pause(); + if ((++spins & (kSpinSample - 1)) != 0) continue; + const auto now = std::chrono::steady_clock::now(); + if (d != seen) { // restarted on progress, which is deliberate + t0 = now; + seen = d; + } else if (now - t0 > kStall) { + poison(); + error = "the CPU expert pool stalled waiting for a batch to finish (" + std::to_string(d) + " of " + + std::to_string(n) + " jobs done)"; + return false; + } + } +} + +bool ExpertPool::run_phase(int n_tasks, const std::function& body, std::string& error, + PhaseTimes* times) { + if (poisoned_.load(std::memory_order_acquire)) { + error = "the CPU expert pool stalled earlier and cannot be reused"; + return false; + } + if (n_tasks < 0 || n_tasks > 0xffff) { + error = "a pool batch holds 0 to 65535 jobs, not " + std::to_string(n_tasks); + return false; + } + // One driver at a time, and refused here rather than left to block: a second driver that passes the park + // barrier before the first publishes overwrites `body_` and resets `done_` and `head_` under it, so the first + // waits on a count the second is filling and runs a body it did not publish. ThreadSanitizer names the race + // on `body_` (tools/tsan/pool_tsan.cpp). `claim_owner` cannot serve here: an owner holds its claim across + // calls, so it is the wrong grain. + if (driving_.exchange(true, std::memory_order_acq_rel)) { + error = "the CPU expert pool is already running a phase on another thread"; + return false; + } + struct Driving { // cleared on every exit, the stall returns included + std::atomic& flag; + ~Driving() { flag.store(false, std::memory_order_release); } + } driving_guard{driving_}; + + const auto t_before = std::chrono::steady_clock::now(); + if (!wait_parked("before a phase", error)) return false; + if (times) times->wait_parked_before_ms = ms_since(t_before); + + const auto t_work = std::chrono::steady_clock::now(); + body_ = &body; // plain; ordered by begin_batch's release + const uint32_t e = begin_batch(n_tasks); + if (host_works_) drain(-1, e); + if (!wait_done(n_tasks, error)) return false; + if (times) times->work_ms = ms_since(t_work); + + const auto t_after = std::chrono::steady_clock::now(); + if (!wait_parked("after a phase", error)) return false; + if (times) times->wait_parked_after_ms = ms_since(t_after); + + hstate_.store(kIdle, std::memory_order_relaxed); + return true; +} + +PoolTask::PoolTask(std::shared_ptr pool, Work work) : pool_(std::move(pool)), work_(std::move(work)) {} + +PoolTask::~PoolTask() { + if (pool_) pool_->release_owner(this); // a poisoned pool was already abandoned +} + +bool PoolTask::run(const HostCall& call, std::string& error) { + if (!pool_) { + error = "this host point's pool is gone"; + return false; + } + // One owner at a time, so two tasks cannot drive one pool and overlap their phases. Claimed on the first call + // rather than at construction, because the owner is the task and the pool may outlive any one program. + if (!pool_->claim_owner(this)) { + error = "the CPU expert pool is already driven by another host task"; + return false; + } + // The body lives on the heap because a stalled phase leaves a worker that may still call it. basalt's + // abort() takes the whole process and so never has to answer this; here the phase returns and this frame + // goes away, so the body has to outlive the frame whenever the pool is poisoned. + auto body = std::make_unique>(); + const int n = work_(call.step, call.point, *body); + if (n <= 0) return true; // a point with nothing to do + if (!*body) { + error = "the host point asked for " + std::to_string(n) + " jobs and gave no body to run"; + return false; + } + const bool ok = pool_->run_phase(n, *body, error, &last_); + if (!ok && pool_->poisoned()) abandon(std::move(body)); + return ok; +} + +void PoolTask::abandon(std::unique_ptr> body) { + // A poisoned pool's workers may still hold this body and pointers into the caller's buffers, and there is no + // way to interrupt them. Both the body and one reference to the pool are leaked on purpose, for the process's + // life: the destructor would join a worker that never returns, and freeing the body under a running one is a + // use-after-free. This is what basalt's abort() buys for free. + // + // Leaked with `new`, never parked in a function-local static container: such a container is destroyed at exit, + // and dropping the last reference to the pool there runs ~ExpertPool, which joins the worker that never + // returns. That is the hang this leak exists to prevent. Nothing here is ever freed, so there is also no + // container for two abandoning tasks to race on. + (void) body.release(); // never freed: a worker may still call it + (void) new std::shared_ptr(std::move(pool_)); // never released: ~ExpertPool must not run + // the move leaves pool_ empty: this task no + // longer reaches it +} + +} // namespace monolith::basalt_cpu diff --git a/runtime/src/basalt_pool.h b/runtime/src/basalt_pool.h new file mode 100644 index 00000000..d23ca9b5 --- /dev/null +++ b/runtime/src/basalt_pool.h @@ -0,0 +1,207 @@ +// SPDX-License-Identifier: MIT +// Copyright (c) 2026 Jesús Gulfo (MIT) +// Adapted from basalt (jesdga95/basalt) include/basalt/kernels/cpu/pool.hpp and src/kernels/cpu/pool.cpp @ +// b4c63b55754637f4c72ad53a0f791d425f71eb36 (MIT; third_party/NOTICE): the CPU expert pool's structure, its +// epoch-tagged claim protocol, its park and its phase barriers. +// +// The worker pool that runs the CPU expert tier. basalt's CPU experts are computed by a pool of spinning threads +// the host drives one batch at a time, and nothing bitwise depends on the thread count, the placement or the order +// in which jobs are claimed: a job writes its own rows and the host sums them in a fixed order +// (docs/research/basalt-cpu-pool.md section 2). What the pool must reproduce exactly is its SYNCHRONISATION, since +// getting that wrong does not give different numbers, it gives a run that hangs or computes a job twice. +// +// THE QUEUE IS ONE 64-BIT WORD. There is no ring and no lock, because jobs cannot arrive while others are still +// being computed: the host must sum every output before the next layer starts, so a layer is a barrier by +// construction and the queue never holds more than one batch. The word is `epoch << 32 | njobs << 16 | index`, a +// claim is a compare-exchange that only succeeds for the epoch the worker woke for, and a late worker's claim +// simply fails. +// +// WHY THE EPOCH IS IN THE WORD. A worker that went to sleep is still counted as parked when it wakes: it reads +// the new epoch, and only then decrements `parked_`. In that gap the host may read `parked_ == n_`, pass its next +// pre-phase barrier and publish the next batch, so the worker enters `drain` holding the epoch it woke for while +// `head_` already carries the next. The park barriers narrow that window and do not close it. basalt's reason for +// the epoch is that such a worker could otherwise claim from the next batch while the host was still writing it, +// run a job twice, or add to `done` after the host had reset it (`pool.hpp:18-23`). +// +// Here, neither of the last two is reachable even with the epoch test removed, because three other things hold: +// the claim's acquire of `head_` synchronises with `begin_batch`'s release and the batch description is written +// before it, the index CAS hands out each job exactly once, and `wait_done` has seen every increment of the +// previous batch before the reset. A late claim therefore lands on the next batch as an early, correct +// participant. The epoch test stays because this is a 1:1 port of basalt's protocol, not because a measurement +// here showed its removal breaking (docs/research/basalt-cpu-pool.md section 4 records what was measured). +// +// WHAT THIS PORT CHANGES, and why each is not a numeric difference: +// * A stall reports instead of aborting. basalt calls `release_gpu_waits` then `std::abort()`; this returns +// false with a message, which the host task turns into StepState.error = 4 and Engine.run raises. A stalled +// pool is POISONED: its workers may still hold pointers into buffers the caller is about to free, so it is +// never destroyed and never reused, which is what abort() buys basalt for free. +// * The stall clock is armed once per wait rather than every 2^32 spins. The transcribed spin body costs +// 0.422 ns here, so 2^32 iterations is 1.8 s against a 60 s limit and the abort could never fire [M]. +// * The worker count and the spin-before-sleep come from the chip profile. basalt derives the count from a Linux +// CPU topology this platform does not expose, and no placement control here is more than a hint. +// * Each worker's gate and up buffers are owned by the pool and indexed by worker id, where basalt uses +// function-local `thread_local` arrays. On Darwin each such access goes through the thread-local-variable +// descriptor and allocates lazily on first use; the buffers are scratch, so this is invisible to the output. +// * The hot atomics are padded to 128 bytes, which is this chip's cache line, where basalt pads to 64 [M]. +// * `run_phase` refuses a second concurrent driver. basalt's pool has one host thread and needs no such flag; +// here the Python bindings release the GIL and `PoolTask` runs on the pump, so two native drivers of one pool +// are reachable, and two of them race on the batch description (ThreadSanitizer names it). +#pragma once + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#include "metal_core.h" +#include + +namespace monolith::basalt_cpu { + +/// This chip's cache line, so each hot atomic gets a line of its own. basalt uses 64, which is x86's; here that +/// would leave two of them sharing. Not `std::hardware_destructive_interference_size`, which this toolchain +/// reports as 256 and which would over-pad by two [M]. +inline constexpr size_t kCacheLine = 128; + +/// A pool wait that sees no completion for this long is a bug (`pool.hpp:187`). +inline constexpr std::chrono::seconds kStall{60}; + +/// How often any spin reads the clock, in iterations (`pool.cpp:301`, `:359`, `:382`). +inline constexpr uint32_t kSpinSample = 1024; + +/// Worker and host diagnostic states (`pool.hpp:224-225`). +enum : int32_t { kParked = -1, kSleeping = -2, kBetween = -3, kIdle = -10, kWaitParked = -11, kWaitDone = -12 }; + +/// What one phase cost, in milliseconds. basalt keeps three such timers and reports them; a slow pool poses one +/// question, slow at the work or slow at the synchronisation, and only these answer it (`pool.hpp:158-160`). +struct PhaseTimes { + double wait_parked_before_ms = 0; + double work_ms = 0; // the host's own drain plus the wait for `done` + double wait_parked_after_ms = 0; +}; + +/// basalt's CPU expert pool. One host thread drives it. Two exclusions, answering different questions: `run_phase` +/// refuses a second concurrent driver, and `claim_owner` refuses a second owner as a `HostTask` refuses a second +/// runner. An owner holds its claim across calls, so the owner claim cannot serve as the per-phase exclusion. +class ExpertPool { + public: + /// `n_workers` worker threads, plus the calling thread when `host_works`. A count at or below zero takes + /// `std::thread::hardware_concurrency() - 1`, which is basalt's rule once this platform's topology collapses + /// to "every core" (no SMT here, so the one-logical-per-physical dance has nothing to do). + explicit ExpertPool(int n_workers = 0, bool host_works = true, + std::chrono::microseconds spin_before_sleep = std::chrono::milliseconds{20}); + + /// Joins every worker. A poisoned pool must never reach this: see `poisoned()`. + ~ExpertPool(); + + ExpertPool(const ExpertPool&) = delete; + ExpertPool& operator=(const ExpertPool&) = delete; + + int workers() const { return n_; } + bool host_works() const { return host_works_; } + + /// True once a wait has stalled. The workers may still hold pointers into the caller's buffers, so a poisoned + /// pool is never destroyed, never reused and leaked for the process's life. `PoolTask` enforces that by + /// abandoning its reference and its job body; a caller that drives the pool directly owns the same duty, and + /// `run_phase` refuses a poisoned pool so the refusal does not depend on the caller remembering. + bool poisoned() const { return poisoned_.load(std::memory_order_acquire); } + + /// Claim the pool for one owner, by compare-exchange. Returns false and names nothing it does not know when + /// another owner holds it; `release` gives it back. Two distinct host tasks could otherwise drive one pool and + /// overlap their phases. + bool claim_owner(const void* owner); + void release_owner(const void* owner); + const void* owner() const { return owner_.load(std::memory_order_acquire); } + + /// Run one phase: `n_tasks` jobs, each `body(job_index, worker_id)`, where `worker_id` is 0..workers()-1 for a + /// worker and -1 for the host's own drain. Returns false on a stall, leaving `error` set and the pool + /// poisoned, and false without running anything when another thread is already inside a phase. The body must + /// not throw. + bool run_phase(int n_tasks, const std::function& body, std::string& error, + PhaseTimes* times = nullptr); + + /// Per-worker scratch the caller may index by the `worker_id` its body is given, sized `bytes` per worker on + /// the first call and kept for the pool's life. Slot `workers()` is the host's. basalt uses function-local + /// `thread_local` arrays for this, which on Darwin allocate lazily and cost two indirect calls per access. + void* scratch(int worker_id, size_t bytes); + + private: + void worker(int id); + void drain(int id, uint32_t epoch); + int claim(uint32_t epoch); + uint32_t begin_batch(int n); + void publish(); + void poison(); // marks the pool and exhausts the queue, in that order + bool wait_parked(const char* what, std::string& error); + bool wait_done(int n, std::string& error); + + const bool host_works_; + int n_ = 1; + std::chrono::microseconds spin_before_sleep_; + + // The four the workers and the host contend on, each on its own line: the line the host writes to publish work + // and reads to confirm the workers are parked must not be hammered by the threads waiting for it. + alignas(kCacheLine) std::atomic head_{0}; // epoch << 32 | njobs << 16 | next index + alignas(kCacheLine) std::atomic done_{0}; + alignas(kCacheLine) std::atomic parked_{0}; + alignas(kCacheLine) std::atomic epoch_{0}; + alignas(kCacheLine) std::atomic stop_{false}; + alignas(kCacheLine) std::atomic sleepers_{0}; + + std::atomic poisoned_{false}; + std::atomic owner_{nullptr}; + std::atomic driving_{false}; // a phase is in flight: `run_phase`'s own exclusion + + // The batch description. Plain, not atomic: it is made visible to a worker solely by the release/acquire pair + // on `head_` plus the seq_cst epoch bump, so the host writes it BEFORE `begin_batch` and a worker reads it + // only after its acquire. Publishing it after the epoch, or reading it before the acquire, is a data race. + const std::function* body_ = nullptr; + + std::mutex sleep_mu_; + std::condition_variable sleep_cv_; + std::unique_ptr[]> wstate_; + std::atomic hstate_{kIdle}; + std::vector> scratch_; + std::vector threads_; +}; + +/// A host task that drives the pool, for a program whose points carry CPU expert work. +/// +/// It is a C++ `HostTask` and not a `CallableTask` on purpose: a Python task takes the GIL on every call, and this +/// one runs on the pump thread once per MoE layer, which is 48 times a step. The pump commits nothing while it +/// runs, so the GPU's own experts for the layer must already be in flight; that is what the point's +/// [publish, wait) window is for. +/// +/// The pool's release/acquire pair is what publishes the workers' rows to the GPU, not just to the waiting host: +/// a worker's stores land, then its `done_` increment releases, then the pump's `wait_done` acquires, then the +/// pump commits the command buffer that reads them. A port that made `done_` a plain counter would break GPU +/// visibility and not merely the wait. +class PoolTask : public HostTask { + public: + /// `work(step, point)` returns the jobs for this call: the count, and the body each job runs. A count of zero + /// is a point with nothing to do, which still returns true. + using Work = std::function&)>; + + PoolTask(std::shared_ptr pool, Work work); + ~PoolTask() override; + + bool run(const HostCall& call, std::string& error) override; + + /// The phase times of the last call that ran jobs, for the caller to report. + PhaseTimes last_times() const { return last_; } + + private: + void abandon(std::unique_ptr> body); + + std::shared_ptr pool_; + Work work_; + PhaseTimes last_; +}; + +} // namespace monolith::basalt_cpu diff --git a/runtime/src/basalt_x86.h b/runtime/src/basalt_x86.h new file mode 100644 index 00000000..40a67f58 --- /dev/null +++ b/runtime/src/basalt_x86.h @@ -0,0 +1,58 @@ +// x86's scalar NaN rules, applied lane-exact on ARM. basalt's CPU tier runs on x86-64, and two of its pieces have +// to return the same bits here: the Q2_0 expert kernels (basalt_cpu.cpp) and the expert pool's own SwiGLU +// (basalt_cpu_expf.cpp). Both reach the same two rules, so they share them. +// +// An SSE or AVX arithmetic instruction handed a NaN returns the FIRST of its sources that is one, quieted, where +// an AArch64 instruction prefers a signalling NaN wherever it sits and otherwise takes its own order. A NaN the +// operation itself CREATES is the floating-point indefinite 0xffc00000, sign bit set, where AArch64 writes the +// default NaN 0x7fc00000 ([S] Intel SDM Vol. 1 4.8.3.7; [S] Arm ARM A1.5.3). +// +// Each helper therefore selects the NaN by an explicit bit test, in the operand order of the instruction GCC +// emits at that site, and no NEON NaN rule is consulted. The operand order is the compiler's rather than the +// source's, so every call site names its operands in the order its disassembly has them. +#pragma once + +#include +#include +#include + +namespace monolith::basalt_cpu::x86 { + +inline uint32_t to_bits(float f) { + uint32_t b; + std::memcpy(&b, &f, 4); + return b; +} +inline float from_bits(uint32_t b) { + float f; + std::memcpy(&f, &b, 4); + return f; +} +inline bool is_nan(float x) { return (to_bits(x) & 0x7F800000u) == 0x7F800000u && (to_bits(x) & 0x007FFFFFu) != 0; } +inline float quiet(float x) { return from_bits(to_bits(x) | 0x00400000u); } // an SNaN keeps its payload, bit 22 set + +/// VMULPS, VADDPS, VADDSS, VSUBSS, DIVSS and MULSS: SRC1's NaN if it has one, else SRC2's, each quieted ([S] Intel +/// SDM Vol. 1 Table 4-8; [M] the recorded ground truth of both tiers); a NaN the operation CREATES (inf * 0, +/// inf - inf, inf / inf, 0 / 0) is the floating-point indefinite 0xffc00000 (4.8.3.7). +inline float x86_src1_first(float src1, float src2, float computed) { + if (is_nan(src1)) return quiet(src1); + if (is_nan(src2)) return quiet(src2); + return is_nan(computed) ? from_bits(0xFFC00000u) : computed; +} +inline float x86_mul(float src1, float src2) { return x86_src1_first(src1, src2, src1 * src2); } +inline float x86_add(float src1, float src2) { return x86_src1_first(src1, src2, src1 + src2); } +inline float x86_sub(float src1, float src2) { return x86_src1_first(src1, src2, src1 - src2); } +inline float x86_div(float src1, float src2) { return x86_src1_first(src1, src2, src1 / src2); } + +/// VFMADD231PS: the first NaN in the order first multiplicand, second multiplicand, addend, quieted ([S] Vol. 1 +/// Table 14-17; [M] ground-truth:137-141). A QNaN addend therefore survives an inf * 0 product, where FMLA +/// discards it for the default NaN. +inline float x86_fma(float m1, float m2, float addend) { + if (is_nan(m1)) return quiet(m1); + if (is_nan(m2)) return quiet(m2); + if (is_nan(addend)) return quiet(addend); + const float r = std::fma(m1, m2, addend); + return is_nan(r) ? from_bits(0xFFC00000u) : r; +} + +} // namespace monolith::basalt_cpu::x86 diff --git a/runtime/src/metal_core.h b/runtime/src/metal_core.h index 695ce94a..4d1dfa54 100644 --- a/runtime/src/metal_core.h +++ b/runtime/src/metal_core.h @@ -76,6 +76,8 @@ struct Dispatch { uint32_t grid[3] = {1, 1, 1}; // threadgroups uint32_t threadgroup[3] = {1, 1, 1}; // threads per threadgroup bool barrier_before = false; // this dispatch waits for every dispatch before it (ICBs, concurrent encoders) + std::vector uses; // buffers the kernel reaches only through GPU addresses: Queue.run and + // Queue.profile make them resident for its dispatch (useResource, read) }; struct RunResult { double gpu_ms; double wall_ms; std::string error; }; diff --git a/runtime/src/metal_core.mm b/runtime/src/metal_core.mm index 0372f504..4cc3b24c 100644 --- a/runtime/src/metal_core.mm +++ b/runtime/src/metal_core.mm @@ -3,6 +3,7 @@ #import #include #include +#include #include #include #include @@ -72,6 +73,17 @@ static int ioreg_gpu_cores() { if (offset % page || nbytes % page) throw std::runtime_error("mmap buffers need page-aligned offset and length"); int fd = open(path.c_str(), O_RDONLY); if (fd < 0) throw std::runtime_error("open failed: " + path); + // A mapped page wholly past the end of the file faults only when the GPU or the host touches it, and then kills the + // process with SIGBUS. Refuse any window that runs past the end, from the file's own size (packs pad their file to + // whole pages, and the .basalt planner never maps the file's last partial page). + struct stat st; + if (fstat(fd, &st) != 0) { close(fd); throw std::runtime_error("fstat failed: " + path); } + const uint64_t file_bytes = (uint64_t)st.st_size; + if (offset > file_bytes || nbytes > file_bytes - offset) { + close(fd); + throw std::runtime_error("mmap window [" + std::to_string(offset) + ", " + std::to_string(offset + nbytes) + + ") runs past the end of " + path + " (" + std::to_string(file_bytes) + " bytes)"); + } // Immutable weights need no private copy-on-write mapping. MAP_PRIVATE // makes Metal's first residency preparation expensive even for cached file // pages; shared read-only mappings avoid that work across layout switches. @@ -135,6 +147,7 @@ static int ioreg_gpu_cores() { for (auto& b : d.buffers) [en setBuffer:b.buffer->impl->buf offset:b.offset atIndex:b.index]; for (auto& b : d.bytes) [en setBytes:b.bytes.data() length:b.bytes.size() atIndex:b.index]; for (auto& t : d.threadgroup_memory) [en setThreadgroupMemoryLength:t.second atIndex:t.first]; + for (auto* b : d.uses) [en useResource:b->impl->buf usage:MTLResourceUsageRead]; if (concurrent && d.barrier_before) [en memoryBarrierWithScope:MTLBarrierScopeBuffers]; // the same semantics as the ICB flag [en dispatchThreadgroups:MTLSizeMake(d.grid[0], d.grid[1], d.grid[2]) threadsPerThreadgroup:MTLSizeMake(d.threadgroup[0], d.threadgroup[1], d.threadgroup[2])]; } @@ -186,6 +199,7 @@ static int ioreg_gpu_cores() { for (auto& b : d.buffers) [en setBuffer:b.buffer->impl->buf offset:b.offset atIndex:b.index]; for (auto& b : d.bytes) [en setBytes:b.bytes.data() length:b.bytes.size() atIndex:b.index]; for (auto& t : d.threadgroup_memory) [en setThreadgroupMemoryLength:t.second atIndex:t.first]; + for (auto* b : d.uses) [en useResource:b->impl->buf usage:MTLResourceUsageRead]; [en dispatchThreadgroups:MTLSizeMake(d.grid[0], d.grid[1], d.grid[2]) threadsPerThreadgroup:MTLSizeMake(d.threadgroup[0], d.threadgroup[1], d.threadgroup[2])]; [en endEncoding]; } diff --git a/runtime/src/native.mm b/runtime/src/native.mm index 3a41081b..2d60cf71 100644 --- a/runtime/src/native.mm +++ b/runtime/src/native.mm @@ -1,15 +1,52 @@ // nanobind layer over metal_core: keeps Python free of Objective-C and the core free of Python. #include +#include #include #include #include #include +#import +#include +#include +#include #include +#include +#include "basalt_cpu.h" +#include "basalt_pool.h" +#include "basalt_cpu_expf.h" #include "metal_core.h" namespace nb = nanobind; using namespace monolith; +// ---- basalt's CPU kernels (basalt_cpu.h, basalt_cpu_expf.h) --------------------------------------------------- +// Caller-owned numpy arrays, C-contiguous and of the shape each kernel reads: nanobind refuses a wrong dtype, rank +// or layout (the arguments are .noconvert(), so it cannot quietly write into a copy), and these checks refuse a +// short buffer - a kernel here reads and writes raw pointers, so the binding is where "every store is inside its +// binding" is kept. The float32 arrays also keep a bit pattern intact on the way in: a scalar argument would cross +// Python as a double, and float -> double -> float quiets a signalling NaN. +namespace bc = monolith::basalt_cpu; +using F32In1 = nb::ndarray, nb::c_contig, nb::device::cpu>; +using U8In1 = nb::ndarray, nb::c_contig, nb::device::cpu>; +using I8Out1 = nb::ndarray, nb::c_contig, nb::device::cpu>; +using I32Out1 = nb::ndarray, nb::c_contig, nb::device::cpu>; +using F32Out1 = nb::ndarray, nb::c_contig, nb::device::cpu>; +using I8In2 = nb::ndarray, nb::c_contig, nb::device::cpu>; +using F32In2 = nb::ndarray, nb::c_contig, nb::device::cpu>; +using F32Out2 = nb::ndarray, nb::c_contig, nb::device::cpu>; + +static void need(bool ok, const char* what) { + if (!ok) throw std::invalid_argument(what); +} + +// An elementwise kernel writes out[i] from in[i], so it is well defined when the two are the same buffer and not +// when they merely overlap: a shifted view (x = a[:-1], out = a[1:]) is contiguous and passes every other check, +// and the store to out[i] would change the value read as x[i+1]. Refused rather than copied, because a copy would +// quietly give a different answer than the docstring states where the caller meant the arrays to be distinct. +static void no_partial_overlap(const float* in, const float* out, size_t n, const char* what) { + need(in == out || in + n <= out || out + n <= in, what); +} + NB_MODULE(_native, m) { m.doc() = "Metal runtime core (v0): device, buffers, runtime-compiled libraries, pipelines, timed dispatches"; @@ -59,7 +96,9 @@ nb::arg("x"), nb::arg("y") = 1, nb::arg("z") = 1, nb::rv_policy::reference_internal) .def("threadgroup", [](Dispatch& d, uint32_t x, uint32_t y, uint32_t z) -> Dispatch& { d.threadgroup[0] = x; d.threadgroup[1] = y; d.threadgroup[2] = z; return d; }, nb::arg("x"), nb::arg("y") = 1, nb::arg("z") = 1, nb::rv_policy::reference_internal) - .def("barrier", [](Dispatch& d, bool on) -> Dispatch& { d.barrier_before = on; return d; }, nb::arg("on") = true, nb::rv_policy::reference_internal); + .def("barrier", [](Dispatch& d, bool on) -> Dispatch& { d.barrier_before = on; return d; }, nb::arg("on") = true, nb::rv_policy::reference_internal) + .def("use", [](Dispatch& d, const Buffer& b) -> Dispatch& { d.uses.push_back(&b); return d; }, + nb::arg("buffer"), nb::rv_policy::reference_internal, nb::keep_alive<1, 2>()); nb::class_(m, "RunResult") .def_ro("gpu_ms", &RunResult::gpu_ms).def_ro("wall_ms", &RunResult::wall_ms).def_ro("error", &RunResult::error); @@ -92,4 +131,169 @@ .def("run", &Runner::run, nb::arg("max_steps"), nb::arg("steps_per_cb") = 8, nb::arg("in_flight") = 3, nb::arg("reencode") = false, nb::arg("max_tokens") = 0, nb::call_guard()) .def("drain", &Runner::drain); + + m.def("basalt_act_quant_q8_1", [](F32In1 x, I8Out1 q, F32Out1 scale, I32Out1 sum, F32Out1 hx) { + const size_t len = x.shape(0); // checked at full width: a narrowing cast first would accept a + need(len > 0 && len % bc::QKA == 0 && len <= (size_t)bc::H, // length whose low 32 bits look valid + "basalt_act_quant_q8_1: len(x) must be a positive multiple of 32, at most 2560"); + const int n = (int)len; + need(q.shape(0) == (size_t)bc::H, "basalt_act_quant_q8_1: q must hold H = 2560 int8 codes"); + need(scale.shape(0) == (size_t)bc::MAXC && sum.shape(0) == (size_t)bc::MAXC && hx.shape(0) == (size_t)bc::MAXC, + "basalt_act_quant_q8_1: scale, sum and hx must each hold MAXC = 80 elements"); + bc::ActQ a; + nb::gil_scoped_release unlock; + bc::act_quant_q8_1(x.data(), n, a); + std::memcpy(q.data(), a.q, (size_t)n); // only what the kernel wrote + std::memcpy(scale.data(), a.scale, (size_t)a.nchunks * sizeof(float)); + std::memcpy(sum.data(), a.sum, (size_t)a.nchunks * sizeof(int32_t)); + std::memcpy(hx.data(), a.hx, (size_t)a.nchunks * sizeof(float)); + return a.nchunks; + }, nb::arg("x").noconvert(), nb::arg("q").noconvert(), nb::arg("scale").noconvert(), nb::arg("sum").noconvert(), + nb::arg("hx").noconvert(), + "basalt's act_quant_q8_1 on ARM NEON: writes q[:n] and scale/sum/hx[:n // 32], and returns nchunks"); + + m.def("basalt_q2_0_gguf_rows_multi", [](U8In1 w, size_t row_bytes, int nblocks, I8In2 q, F32In2 scale, F32In2 hx, + F32Out2 out, int r0, int r1) { + const int nt = (int)q.shape(0); + const size_t nrows = out.shape(1); // full width: the row stride below, and a narrowing cast here would + // accept a shape whose low 32 bits look small and stride past it + need(nt >= 1 && nt <= bc::MAXT, "basalt_q2_0_gguf_rows_multi: nt must be 1..8"); + need(scale.shape(0) == (size_t)nt && hx.shape(0) == (size_t)nt && out.shape(0) == (size_t)nt, + "basalt_q2_0_gguf_rows_multi: q, scale, hx and out must agree on nt"); + need(q.shape(1) == (size_t)bc::H, "basalt_q2_0_gguf_rows_multi: q rows must hold H = 2560 int8 codes"); + need(scale.shape(1) == (size_t)bc::MAXC && hx.shape(1) == (size_t)bc::MAXC, + "basalt_q2_0_gguf_rows_multi: scale and hx rows must hold MAXC = 80 elements"); + // Every bound divides rather than multiplies: the products overflow, and a wrapped product passes the check it + // is meant to fail (nblocks = 2^25 makes QK * nblocks reach INT_MIN, row_bytes * nrows reaches 2^64 and wraps + // to 0), which the kernel then reads past the ActQ arrays and past w. + need(nblocks >= 1 && nblocks <= bc::H / bc::QK, "basalt_q2_0_gguf_rows_multi: nblocks must be 1..40"); + need(row_bytes >= (size_t)bc::BB * (size_t)nblocks, "basalt_q2_0_gguf_rows_multi: row_bytes is below 18 * nblocks"); + need(r0 >= 0 && r1 >= r0 && (size_t)r1 <= nrows, "basalt_q2_0_gguf_rows_multi: need 0 <= r0 <= r1 <= out.shape[1]"); + need(nrows == 0 || row_bytes <= w.size() / nrows, "basalt_q2_0_gguf_rows_multi: w is shorter than row_bytes * nrows"); + std::array act{}; + const bc::ActQ* ap[bc::MAXT]; + float* op[bc::MAXT]; + for (int t = 0; t < nt; ++t) { + std::memcpy(act[t].q, q.data() + (size_t)t * bc::H, bc::H); + std::memcpy(act[t].scale, scale.data() + (size_t)t * bc::MAXC, bc::MAXC * sizeof(float)); + std::memcpy(act[t].hx, hx.data() + (size_t)t * bc::MAXC, bc::MAXC * sizeof(float)); + ap[t] = &act[t]; // sum and nchunks stay zero: unread + op[t] = out.data() + (size_t)t * nrows; // nrows is size_t: the stride is the row's real width + } + nb::gil_scoped_release unlock; + bc::q2_0_gguf_rows_multi(w.data(), row_bytes, nblocks, ap, nt, op, r0, r1); + }, nb::arg("w").noconvert(), nb::arg("row_bytes"), nb::arg("nblocks"), nb::arg("q").noconvert(), + nb::arg("scale").noconvert(), nb::arg("hx").noconvert(), nb::arg("out").noconvert(), nb::arg("r0"), nb::arg("r1"), + "basalt's q2_0_gguf_rows_multi on ARM NEON: writes out[t][r] for r0 <= r < r1 and nothing else"); + + m.def("basalt_expf", [](F32In1 x, F32Out1 out) { + need(out.shape(0) == x.shape(0), "basalt_expf: out must hold as many floats as x"); + const size_t n = x.shape(0); + const float* xp = x.data(); + float* op = out.data(); + no_partial_overlap(xp, op, n, "basalt_expf: out may be x itself but must not partly overlap it"); + nb::gil_scoped_release unlock; + for (size_t i = 0; i < n; ++i) op[i] = bc::expf_glibc(xp[i]); + }, nb::arg("x").noconvert(), nb::arg("out").noconvert(), + "glibc's expf, element by element: out[i] = expf_glibc(x[i])"); + + m.def("basalt_swiglu", [](F32In1 g, F32In1 u, F32Out1 out) { + need(u.shape(0) == g.shape(0) && out.shape(0) == g.shape(0), + "basalt_swiglu: g, u and out must hold the same number of floats"); + const size_t n = g.shape(0); + const float* gp = g.data(); + const float* up = u.data(); + float* op = out.data(); + no_partial_overlap(gp, op, n, "basalt_swiglu: out may be g itself but must not partly overlap it"); + no_partial_overlap(up, op, n, "basalt_swiglu: out may be u itself but must not partly overlap it"); + nb::gil_scoped_release unlock; + for (size_t i = 0; i < n; ++i) op[i] = bc::swiglu(gp[i], up[i]); + }, nb::arg("g").noconvert(), nb::arg("u").noconvert(), nb::arg("out").noconvert(), + "basalt's CPU SwiGLU (pool.cpp:434): out[i] = (g[i] / (1.f + expf_glibc(-g[i]))) * u[i]"); + + // The acceptance oracle sweeps all 2^32 float32 arguments, which no Python loop can hash in reasonable time and + // which would be 16 GB as an array. The digest runs here instead, over one range of bit patterns per call: the + // FNV-1a of the result bits in increasing argument order, the rule tests/kernels/fixtures/expf_digests.txt + // records glibc's own output under. + // ---- the CPU expert pool (basalt_pool.h) ---------------------------------------------------------------- + // Driven from the tests with a native body, never a Python callable: a body that took the GIL would serialise + // every worker and the synchronisation this pool exists to get right would never be exercised. + nb::class_(m, "ExpertPool") + .def("__init__", [](bc::ExpertPool* self, int n_workers, bool host_works, double spin_before_sleep_ms) { + // Checked before the conversion: a NaN, an infinity, or a value past the integer's range makes the + // float-to-integer conversion undefined rather than merely wrong. + need(std::isfinite(spin_before_sleep_ms) && spin_before_sleep_ms >= 0.0 && + spin_before_sleep_ms <= 24.0 * 60.0 * 60.0 * 1000.0, + "ExpertPool: spin_before_sleep_ms must be finite and 0 to 86,400,000"); + new (self) bc::ExpertPool(n_workers, host_works, + std::chrono::microseconds((long long) (spin_before_sleep_ms * 1000.0))); + }, + nb::arg("n_workers") = 0, nb::arg("host_works") = true, nb::arg("spin_before_sleep_ms") = 20.0) + .def_prop_ro("workers", &bc::ExpertPool::workers) + .def_prop_ro("host_works", &bc::ExpertPool::host_works) + .def_prop_ro("poisoned", &bc::ExpertPool::poisoned) + .def("claim_owner", [](bc::ExpertPool& p, uintptr_t owner) { return p.claim_owner((const void*) owner); }) + .def("release_owner", [](bc::ExpertPool& p, uintptr_t owner) { p.release_owner((const void*) owner); }) + // One phase whose job j does out[j] += 1 and records the worker that ran it in who[j]. Every job running + // exactly once per phase is the property the epoch-tagged claim exists to give. + .def("count_phase", [](bc::ExpertPool& p, I32Out1 out, I32Out1 who) { + need(who.shape(0) == out.shape(0), "count_phase: who must hold as many ints as out"); + need(out.shape(0) <= (size_t) 0xffff, "count_phase: a pool batch holds 0 to 65535 jobs"); + const int n = (int) out.shape(0); // bounded above, so the narrowing is exact + int32_t* op = out.data(); + int32_t* wp = who.data(); + // Two different arrays, not merely two of the same length: sharing storage would let the worker-id + // write replace the count, and a shifted view would let two jobs write one element concurrently. + need(op + n <= wp || wp + n <= op, "count_phase: out and who must not share storage"); + std::string err; + bc::PhaseTimes t; + bool ok; + { + nb::gil_scoped_release unlock; + ok = p.run_phase(n, [op, wp](int job, int id) { op[job] += 1; wp[job] = id; }, err, &t); + } + need(ok, err.c_str()); + return nb::make_tuple(t.wait_parked_before_ms, t.work_ms, t.wait_parked_after_ms); + }, nb::arg("out").noconvert(), nb::arg("who").noconvert(), + "run one phase of out.size() jobs; job j does out[j] += 1 and writes its worker id to who[j]") + .def("stall_phase", [](bc::ExpertPool& p, double hold_s) { + need(std::isfinite(hold_s) && hold_s >= 0.0 && hold_s <= 24.0 * 60.0 * 60.0, + "stall_phase: hold_s must be finite and 0 to 86,400"); + // One job that outlives kStall, so the stall path and the poisoning can be tested. A poisoned pool's + // worker is still inside this body, so neither the body nor the pool may be freed. The body is on the + // heap and is leaked on the poisoning path, and the pool is held through a non-owning reference the + // binding cannot free, but the Python object CAN still be collected, so the test keeps its own + // reference. That is the same bargain PoolTask::abandon makes. + std::string err; + bool ok; + { + nb::gil_scoped_release unlock; + auto* body = new std::function([hold_s](int, int) { + std::this_thread::sleep_for(std::chrono::duration(hold_s)); + }); + ok = p.run_phase(1, *body, err, nullptr); + if (ok || !p.poisoned()) delete body; // nothing can still be running it + } + return nb::make_tuple(ok, err); + }, nb::arg("hold_s"), "run one job that sleeps hold_s seconds, so a wait can be made to stall"); + + m.def("basalt_expf_digest", [](uint32_t first_bits, uint32_t count) { + // Refused rather than wrapped: a range that runs off the end of the bit patterns would silently digest a + // different set of arguments than the caller named. + need(uint64_t(first_bits) + count <= (uint64_t(1) << 32), + "basalt_expf_digest: first_bits + count must not run past 2^32"); + uint64_t h = 0xCBF29CE484222325ull; + nb::gil_scoped_release unlock; + for (uint32_t i = 0; i < count; ++i) { + const uint32_t bits = first_bits + i; + float x; + std::memcpy(&x, &bits, sizeof x); + const float y = bc::expf_glibc(x); + uint32_t yb; + std::memcpy(&yb, &y, sizeof yb); + h = (h ^ yb) * 0x100000001B3ull; + } + return h; + }, nb::arg("first_bits"), nb::arg("count"), + "FNV-1a over the result bits of expf_glibc at `count` consecutive float32 bit patterns from `first_bits`"); } diff --git a/tests/contract/fixtures/basalt_pack.safetensors b/tests/contract/fixtures/basalt_pack.safetensors new file mode 100644 index 00000000..5202497d Binary files /dev/null and b/tests/contract/fixtures/basalt_pack.safetensors differ diff --git a/tests/contract/fixtures/make_basalt_fixture.py b/tests/contract/fixtures/make_basalt_fixture.py new file mode 100644 index 00000000..aedb28f5 --- /dev/null +++ b/tests/contract/fixtures/make_basalt_fixture.py @@ -0,0 +1,108 @@ +"""Write ``basalt_pack.safetensors``, the real-data fixture of tests/contract/test_basalt_pack.py, by HTTP range reads of +the official pack at a pinned revision (the 65 GB file is never downloaded): + + python tests/contract/fixtures/make_basalt_fixture.py + +It keeps the header and section table, the ``experts.layout`` and ``mtp/dense.index`` sections, ``dense.index`` +gzipped, and up to ``ROW_BYTES`` of the first and last rows of the first ``meta`` tensor of each ggml type, plus the +first and last gate, up and down rows of the first and last routed expert, located through ``experts.layout``. +""" + +from __future__ import annotations + +import gzip +import json +import sys +import urllib.request +from pathlib import Path + +import numpy as np + +ROOT = Path(__file__).resolve().parents[3] +sys.path.insert(0, str(ROOT)) +from monolith.formats.basalt_reader import ENTRY, HEADER, BasaltFile # noqa: E402 +from monolith.formats.gguf import GGML_TYPES, ggml_row_bytes # noqa: E402 +from monolith.formats.safetensors_reader import write_safetensors # noqa: E402 + +REPO = "jesdga/Qwen3.8-Flash-Next-Basalt" +REVISION = "2a6a758dc12f1d027d2d35b8964110df7e80f70b" +FILE = "Qwen3.8-FN-GSQ-RCO-Q2_0.basalt" +URL = f"https://huggingface.co/{REPO}/resolve/{REVISION}/{FILE}" +ROW_BYTES = 1024 # at most this much of each row, in whole blocks +EXPERT_DIMS = (2560, 640) # the routed experts' n_embd, n_ff (meta gguf_kv: embedding / expert FFN length) +OUT = Path(__file__).with_name("basalt_pack.safetensors") + + +class HttpRange: + """The remote file as a sliceable buffer: each slice is one HTTP range request, refused unless it is a 206 of + exactly the requested length (a 200 would be the whole 65 GB).""" + + def __init__(self, url: str) -> None: + self.url = url + with self._get(0, 1) as r: + self.size = int(r.headers["Content-Range"].rsplit("/", 1)[1]) + + def _get(self, start: int, stop: int): + r = urllib.request.urlopen(urllib.request.Request(self.url, headers={"Range": f"bytes={start}-{stop - 1}"}), + timeout=300) + if r.status != 206: + r.close() + raise IOError(f"{self.url}: HTTP {r.status} to a range request") + return r + + def __len__(self) -> int: + return self.size + + def __getitem__(self, s: slice) -> bytes: + start, stop = s.start or 0, min(s.stop, self.size) + if stop <= start: + return b"" + with self._get(start, stop) as r: + data = r.read() + if len(data) != stop - start: + raise IOError(f"{self.url}: {len(data)} bytes for a range of {stop - start}") + return data + + +def main() -> int: + f = BasaltFile(HttpRange(URL)) + tensors = {"header": f.data[: HEADER.size + len(f.sections) * ENTRY.size], + "section/experts.layout": f.read("experts.layout"), + "section/mtp/dense.index": f.read("mtp/dense.index"), + "section/dense.index.gz": gzip.compress(f.read("dense.index"), mtime=0)} + entries = [] + + def take(key, type_id, ne0, offsets, **where): + row = ggml_row_bytes(type_id, ne0) + block, size = GGML_TYPES[type_id][1:] + keep = min(row, ROW_BYTES // size * size) + tensors[key] = b"".join(f.data[o: o + keep] for o in offsets) + entries.append(dict(key=key, type_id=type_id, ne0=ne0, row_bytes=row, values=keep // size * block, + offsets=offsets, **where)) + + first = {} + for name, t in f.meta()["tensors"].items(): + first.setdefault(int(t["type_id"]), name) + for type_id, name in sorted(first.items()): + t, m = f.tensor(name), f.meta()["tensors"][name] + n = int(np.prod(t.ne[1:], dtype=np.int64)) + rows = sorted({0, n - 1}) + take(f"gguf/{name}", type_id, t.ne[0], [t.offset + r * ggml_row_bytes(type_id, t.ne[0]) for r in rows], + source="gguf", tensor=name, rows=rows, meta=m) + layout, experts = f.experts_layout(), f.section("experts").offset + for layer, expert in ((0, 0), (len(layout.layers) - 1, layout.n_expert - 1)): + for role, (type_id, off, n, ne0) in zip(("gate", "up", "down"), layout.matrices(layer, *EXPERT_DIMS)): + base = experts + layout.blob_offset(layer, expert) + off + rows = [0, n - 1] + take(f"experts/{layer}/{expert}/{role}", type_id, ne0, [base + r * ggml_row_bytes(type_id, ne0) for r in rows], + source="experts", layer=layer, expert=expert, role=role, rows=rows) + meta = {"repo": REPO, "revision": REVISION, "file": FILE, "file_bytes": f.file_bytes, "expert_dims": EXPERT_DIMS, + "row_bytes_kept": ROW_BYTES, "entries": entries} + write_safetensors(OUT, {k: ("U8", np.frombuffer(bytes(v), np.uint8)) for k, v in tensors.items()}, + {"fixture": json.dumps(meta)}) + print(f"wrote {OUT} ({OUT.stat().st_size} bytes): {len(entries)} row sets") + return 0 + + +if __name__ == "__main__": + raise SystemExit(main()) diff --git a/tests/contract/gguf_reference.py b/tests/contract/gguf_reference.py new file mode 100644 index 00000000..335aee50 --- /dev/null +++ b/tests/contract/gguf_reference.py @@ -0,0 +1,299 @@ +# SPDX-License-Identifier: MIT +# Copyright (c) 2023-2026 The ggml authors +# Copyright (c) 2023 Georgi Gerganov +# adapted from ggml-org/llama.cpp gguf-py/gguf/quants.py @ 3cf03257f219afbe7334045ff7c6a06ac68c627d (MIT, +# third_party/GGML-LICENSE): the dequantize_blocks of BF16, Q4_0, Q5_0, Q8_0, Q3_K, Q4_K, Q5_K, Q6_K, IQ4_NL and IQ4_XS +# and dequantize()'s F32 / F16 views, the bodies unchanged; the block sizes from gguf-py/gguf/constants.py +# GGML_QUANT_SIZES. Q2_0 is a scalar port of ggml/src/ggml-quants.c dequantize_row_q2_0 (lines 439-457) at the same +# commit, because gguf-py has no dequantizer for it there. +"""An independent decode of the ggml block formats for the contract tests: llama.cpp's own numpy dequantizers, written +apart from the C reference the format plugins (monolith/formats/gguf.py) follow.""" +from __future__ import annotations + +import numpy as np + +QK_K = 256 + +# GGML_QUANT_SIZES: ggml type id -> (values per block, bytes per block) +SIZES = {0: (1, 4), 1: (1, 2), 2: (32, 2 + 16), 6: (32, 2 + 4 + 16), 8: (32, 2 + 32), + 11: (256, 2 + QK_K // 4 + QK_K // 8 + 12), 12: (256, 2 + 2 + QK_K // 2 + 12), + 13: (256, 2 + 2 + QK_K // 2 + QK_K // 8 + 12), 14: (256, 2 + QK_K // 2 + QK_K // 4 + QK_K // 16), + 20: (32, 2 + 16), 23: (256, 2 + 2 + QK_K // 2 + QK_K // 64), 30: (1, 2), 42: (64, 2 + 16)} + + +class BF16: + @classmethod + def dequantize_blocks(cls, blocks: np.ndarray) -> np.ndarray: + return (blocks.view(np.int16).astype(np.int32) << 16).view(np.float32) + + +class Q4_0: + block_size = 32 + + @classmethod + def dequantize_blocks(cls, blocks: np.ndarray) -> np.ndarray: + n_blocks = blocks.shape[0] + + d, qs = np.hsplit(blocks, [2]) + + d = d.view(np.float16).astype(np.float32) + + qs = qs.reshape((n_blocks, -1, 1, cls.block_size // 2)) >> np.array([0, 4], dtype=np.uint8).reshape((1, 1, 2, 1)) + qs = (qs & np.uint8(0x0F)).reshape((n_blocks, -1)).astype(np.int8) - np.int8(8) + + return (d * qs.astype(np.float32)) + + +class Q5_0: + block_size = 32 + + @classmethod + def dequantize_blocks(cls, blocks: np.ndarray) -> np.ndarray: + n_blocks = blocks.shape[0] + + d, rest = np.hsplit(blocks, [2]) + qh, qs = np.hsplit(rest, [4]) + + d = d.view(np.float16).astype(np.float32) + qh = qh.view(np.uint32) + + qh = qh.reshape((n_blocks, 1)) >> np.array([i for i in range(32)], dtype=np.uint32).reshape((1, 32)) + ql = qs.reshape((n_blocks, -1, 1, cls.block_size // 2)) >> np.array([0, 4], dtype=np.uint8).reshape((1, 1, 2, 1)) + qh = (qh & np.uint32(0x01)).astype(np.uint8) + ql = (ql & np.uint8(0x0F)).reshape((n_blocks, -1)) + + qs = (ql | (qh << np.uint8(4))).astype(np.int8) - np.int8(16) + + return (d * qs.astype(np.float32)) + + +class Q8_0: + @classmethod + def dequantize_blocks(cls, blocks: np.ndarray) -> np.ndarray: + d, x = np.split(blocks, [2], axis=1) + d = d.view(np.float16).astype(np.float32) + x = x.view(np.int8).astype(np.float32) + + return (x * d) + + +class Q3_K: + @classmethod + def dequantize_blocks(cls, blocks: np.ndarray) -> np.ndarray: + n_blocks = blocks.shape[0] + + hmask, rest = np.hsplit(blocks, [QK_K // 8]) + qs, rest = np.hsplit(rest, [QK_K // 4]) + scales, d = np.hsplit(rest, [12]) + + d = d.view(np.float16).astype(np.float32) + + # The scales are packed at 6-bit each in this pattern: + # 0: IIIIAAAA + # 1: JJJJBBBB + # 2: KKKKCCCC + # 3: LLLLDDDD + # 4: MMMMEEEE + # 5: NNNNFFFF + # 6: OOOOGGGG + # 7: PPPPHHHH + # 8: MMIIEEAA + # 9: NNJJFFBB + # 10: OOKKGGCC + # 11: PPLLHHDD + lscales, hscales = np.hsplit(scales, [8]) + lscales = lscales.reshape((n_blocks, 1, 8)) >> np.array([0, 4], dtype=np.uint8).reshape((1, 2, 1)) + lscales = lscales.reshape((n_blocks, 16)) + hscales = hscales.reshape((n_blocks, 1, 4)) >> np.array([0, 2, 4, 6], dtype=np.uint8).reshape((1, 4, 1)) + hscales = hscales.reshape((n_blocks, 16)) + scales = (lscales & np.uint8(0x0F)) | ((hscales & np.uint8(0x03)) << np.uint8(4)) + scales = (scales.astype(np.int8) - np.int8(32)).astype(np.float32) + + dl = (d * scales).reshape((n_blocks, 16, 1)) + + ql = qs.reshape((n_blocks, -1, 1, 32)) >> np.array([0, 2, 4, 6], dtype=np.uint8).reshape((1, 1, 4, 1)) + qh = hmask.reshape(n_blocks, -1, 1, 32) >> np.array([i for i in range(8)], dtype=np.uint8).reshape((1, 1, 8, 1)) + ql = ql.reshape((n_blocks, 16, QK_K // 16)) & np.uint8(3) + qh = (qh.reshape((n_blocks, 16, QK_K // 16)) & np.uint8(1)) + qh = qh ^ np.uint8(1) # strangely, the offset is zero when the bitmask is 1 + q = (ql.astype(np.int8) - (qh << np.uint8(2)).astype(np.int8)).astype(np.float32) + + return (dl * q).reshape((n_blocks, QK_K)) + + +class Q4_K: + K_SCALE_SIZE = 12 + + @staticmethod + def get_scale_min(scales: np.ndarray) -> tuple[np.ndarray, np.ndarray]: + n_blocks = scales.shape[0] + scales = scales.view(np.uint8) + ### Unpacking the following: ### + # 0 EEAAAAAA + # 1 FFBBBBBB + # 2 GGCCCCCC + # 3 HHDDDDDD + # 4 eeaaaaaa + # 5 ffbbbbbb + # 6 ggcccccc + # 7 hhdddddd + # 8 eeeeEEEE + # 9 ffffFFFF + # 10 ggggGGGG + # 11 hhhhHHHH + scales = scales.reshape((n_blocks, 3, 4)) + d, m, m_d = np.split(scales, 3, axis=-2) + + sc = np.concatenate([d & 0x3F, (m_d & 0x0F) | ((d >> 2) & 0x30)], axis=-1) + min = np.concatenate([m & 0x3F, (m_d >> 4) | ((m >> 2) & 0x30)], axis=-1) + + return (sc.reshape((n_blocks, 8)), min.reshape((n_blocks, 8))) + + @classmethod + def dequantize_blocks(cls, blocks: np.ndarray) -> np.ndarray: + n_blocks = blocks.shape[0] + + d, rest = np.hsplit(blocks, [2]) + dmin, rest = np.hsplit(rest, [2]) + scales, qs = np.hsplit(rest, [cls.K_SCALE_SIZE]) + + d = d.view(np.float16).astype(np.float32) + dmin = dmin.view(np.float16).astype(np.float32) + + sc, m = Q4_K.get_scale_min(scales) + + d = (d * sc.astype(np.float32)).reshape((n_blocks, -1, 1)) + dm = (dmin * m.astype(np.float32)).reshape((n_blocks, -1, 1)) + + qs = qs.reshape((n_blocks, -1, 1, 32)) >> np.array([0, 4], dtype=np.uint8).reshape((1, 1, 2, 1)) + qs = (qs & np.uint8(0x0F)).reshape((n_blocks, -1, 32)).astype(np.float32) + + return (d * qs - dm).reshape((n_blocks, QK_K)) + + +class Q5_K: + @classmethod + def dequantize_blocks(cls, blocks: np.ndarray) -> np.ndarray: + n_blocks = blocks.shape[0] + + d, rest = np.hsplit(blocks, [2]) + dmin, rest = np.hsplit(rest, [2]) + scales, rest = np.hsplit(rest, [Q4_K.K_SCALE_SIZE]) + qh, qs = np.hsplit(rest, [QK_K // 8]) + + d = d.view(np.float16).astype(np.float32) + dmin = dmin.view(np.float16).astype(np.float32) + + sc, m = Q4_K.get_scale_min(scales) + + d = (d * sc.astype(np.float32)).reshape((n_blocks, -1, 1)) + dm = (dmin * m.astype(np.float32)).reshape((n_blocks, -1, 1)) + + ql = qs.reshape((n_blocks, -1, 1, 32)) >> np.array([0, 4], dtype=np.uint8).reshape((1, 1, 2, 1)) + qh = qh.reshape((n_blocks, -1, 1, 32)) >> np.array([i for i in range(8)], dtype=np.uint8).reshape((1, 1, 8, 1)) + ql = (ql & np.uint8(0x0F)).reshape((n_blocks, -1, 32)) + qh = (qh & np.uint8(0x01)).reshape((n_blocks, -1, 32)) + q = (ql | (qh << np.uint8(4))).astype(np.float32) + + return (d * q - dm).reshape((n_blocks, QK_K)) + + +class Q6_K: + @classmethod + def dequantize_blocks(cls, blocks: np.ndarray) -> np.ndarray: + n_blocks = blocks.shape[0] + + ql, rest = np.hsplit(blocks, [QK_K // 2]) + qh, rest = np.hsplit(rest, [QK_K // 4]) + scales, d = np.hsplit(rest, [QK_K // 16]) + + scales = scales.view(np.int8).astype(np.float32) + d = d.view(np.float16).astype(np.float32) + d = (d * scales).reshape((n_blocks, QK_K // 16, 1)) + + ql = ql.reshape((n_blocks, -1, 1, 64)) >> np.array([0, 4], dtype=np.uint8).reshape((1, 1, 2, 1)) + ql = (ql & np.uint8(0x0F)).reshape((n_blocks, -1, 32)) + qh = qh.reshape((n_blocks, -1, 1, 32)) >> np.array([0, 2, 4, 6], dtype=np.uint8).reshape((1, 1, 4, 1)) + qh = (qh & np.uint8(0x03)).reshape((n_blocks, -1, 32)) + q = (ql | (qh << np.uint8(4))).astype(np.int8) - np.int8(32) + q = q.reshape((n_blocks, QK_K // 16, -1)).astype(np.float32) + + return (d * q).reshape((n_blocks, QK_K)) + + +class IQ4_NL: + block_size = 32 + kvalues = (-127, -104, -83, -65, -49, -35, -22, -10, 1, 13, 25, 38, 53, 69, 89, 113) + + @classmethod + def dequantize_blocks(cls, blocks: np.ndarray) -> np.ndarray: + n_blocks = blocks.shape[0] + + d, qs = np.hsplit(blocks, [2]) + + d = d.view(np.float16).astype(np.float32) + + qs = qs.reshape((n_blocks, -1, 1, cls.block_size // 2)) >> np.array([0, 4], dtype=np.uint8).reshape((1, 1, 2, 1)) + + qs = (qs & np.uint8(0x0F)).reshape((n_blocks, -1, 1)) + + kvalues = np.array(cls.kvalues, dtype=np.int8).reshape(1, 1, 16) + qs = np.take_along_axis(kvalues, qs, axis=-1).astype(np.float32).reshape((n_blocks, -1)) + + return (d * qs) + + +class IQ4_XS: + @classmethod + def dequantize_blocks(cls, blocks: np.ndarray) -> np.ndarray: + n_blocks = blocks.shape[0] + + d, rest = np.hsplit(blocks, [2]) + scales_h, rest = np.hsplit(rest, [2]) + scales_l, qs = np.hsplit(rest, [QK_K // 64]) + + d = d.view(np.float16).astype(np.float32) + scales_h = scales_h.view(np.uint16) + + scales_l = scales_l.reshape((n_blocks, -1, 1)) >> np.array([0, 4], dtype=np.uint8).reshape((1, 1, 2)) + scales_h = scales_h.reshape((n_blocks, 1, -1)) >> np.array([2 * i for i in range(QK_K // 32)], dtype=np.uint16).reshape((1, -1, 1)) + scales_l = scales_l.reshape((n_blocks, -1)) & np.uint8(0x0F) + scales_h = scales_h.reshape((n_blocks, -1)).astype(np.uint8) & np.uint8(0x03) + + scales = (scales_l | (scales_h << np.uint8(4))).astype(np.int8) - np.int8(32) + dl = (d * scales.astype(np.float32)).reshape((n_blocks, -1, 1)) + + qs = qs.reshape((n_blocks, -1, 1, 16)) >> np.array([0, 4], dtype=np.uint8).reshape((1, 1, 2, 1)) + qs = qs.reshape((n_blocks, -1, 32, 1)) & np.uint8(0x0F) + + kvalues = np.array(IQ4_NL.kvalues, dtype=np.int8).reshape((1, 1, 1, -1)) + qs = np.take_along_axis(kvalues, qs, axis=-1).astype(np.float32).reshape((n_blocks, -1, 32)) + + return (dl * qs).reshape((n_blocks, -1)) + + +def q2_0(blocks: np.ndarray) -> np.ndarray: + """dequantize_row_q2_0, one value at a time as the C does it.""" + y = np.empty((blocks.shape[0], 64), np.float32) + for i, x in enumerate(blocks): + d = np.float32(x[:2].view(np.float16)[0]) # GGML_FP16_TO_FP32(x[i].d) + for j in range(64): + byte_index = j // 4 + bit_offset = (j % 4) * 2 + q = (int(x[2 + byte_index]) >> bit_offset) & 0x03 + y[i, j] = np.float32(q - 1) * d # ((int)q - 1) * d + return y + + +DEQUANTIZE = {0: lambda b: b.view(np.float32), 1: lambda b: b.view(np.float16).astype(np.float32), + 2: Q4_0.dequantize_blocks, 6: Q5_0.dequantize_blocks, 8: Q8_0.dequantize_blocks, + 11: Q3_K.dequantize_blocks, 12: Q4_K.dequantize_blocks, 13: Q5_K.dequantize_blocks, + 14: Q6_K.dequantize_blocks, 20: IQ4_NL.dequantize_blocks, 23: IQ4_XS.dequantize_blocks, + 30: BF16.dequantize_blocks, 42: q2_0} + + +def dequantize(type_id: int, rows: np.ndarray) -> np.ndarray: + """``[N, row bytes]`` uint8 GGUF rows -> float32 ``[N, K]``.""" + rows = np.ascontiguousarray(rows, dtype=np.uint8) + blocks = rows.reshape(-1, SIZES[type_id][1]) + return DEQUANTIZE[type_id](blocks).astype(np.float32, copy=False).reshape(rows.shape[0], -1) diff --git a/tests/contract/test_basalt_dense_tc_variant.py b/tests/contract/test_basalt_dense_tc_variant.py new file mode 100644 index 00000000..7a753359 --- /dev/null +++ b/tests/contract/test_basalt_dense_tc_variant.py @@ -0,0 +1,33 @@ +"""basalt's dense_tc variant rule (monolith/kernels.py ``basalt_dense_tc_variant``; basalt dense_tc.cu:1017-1059; +docs/research/basalt-nvcc/dense_tc.md section 3): the summation order follows the shape, the weights' alignment and the +multiprocessor count, 170 by default (basalt's measured RTX 5090), never the column count.""" + +import pytest + +from monolith import kernels + +rule = kernels.basalt_dense_tc_variant + + +@pytest.mark.parametrize("t", (11, 12, 13, 14, 23, 42)) # Q3_K, Q4_K, Q5_K, Q6_K, IQ4_XS, Q2_0 +def test_pack_projections(t): + assert rule(t, 6144, 2560) == "one" # ssm_out, attn_output: 160 tiles <= 170 + assert rule(t, 2560, 12288) == "tile" # attn_q: 768 tiles + assert rule(t, 2560, 10240) == rule(t, 2560, 6144) == "tile" + assert kernels.basalt_dense_tc_macros(t, 6144, 2560)["DTC_ORDER"] == "0" + # the count and the alignment are live inputs + assert rule(t, 6144, 2560, sm_count=40) == ("tile" if t in (11, 42) else "s1") + assert rule(t, 6144, 2560, aligned=False) == "s2" # n_in % 1024 == 0 and 160 tiles < 170 + assert rule(t, 2560, 2560, aligned=False) == "s1" + + +def test_rule_boundaries(): + # dense_tc_parity's other cases at 170 (kv Q6_K, the tails) + assert [rule(14, 2560, 512), rule(12, 1024, 1000), rule(14, 1536, 999), rule(11, 1536, 999), rule(42, 1024, 1000)] \ + == ["tile", "one", "tile", "tile", "one"] + # one_smem_bytes<12, 24> = 128 + 16 * one_row_stride: 97,152 at n_in 10752, 101,760 > 99 KiB at 11264 + assert rule(12, 10752, 2560) == "one" and rule(12, 11264, 2560) == "s2" + # the tiles against the count: 170 tiles take the one order, 171 neither one nor KS 2 + assert rule(12, 6144, 2720) == "one" and rule(12, 6144, 2721) == "s1" + with pytest.raises(ValueError): # dense_tc_pair_supported: two Q6_K tiles past 99 KiB + kernels.basalt_dense_tc_pair_macros(14, 14, 4096) diff --git a/tests/contract/test_basalt_ops.py b/tests/contract/test_basalt_ops.py new file mode 100644 index 00000000..e8ab5bd8 --- /dev/null +++ b/tests/contract/test_basalt_ops.py @@ -0,0 +1,499 @@ +"""basalt's op family (monolith/ops/basalt.py) as compiler/emit_basalt.py emits it over a synthetic .basalt file bound +through its windows (compiler/emit.py ``basalt_windows``): each op's dispatch (function, macros, grid, threadgroup, +params and written slots) equal to monolith/kernels.py's builders, and each refusal, a valid input with exactly one +defect refused by that defect's own check (its message). The GPU side is tests/kernels/test_basalt_ops_program.py.""" + +import json + +import numpy as np +import pytest + +from monolith import kernels +from monolith.compiler import emit_program +from monolith.compiler.coverage import check_coverage +from monolith.compiler.emit import basalt_windows +from monolith.core import DType, Graph +from monolith.core.ir import BlockDomain, OpClass +from monolith.core.shapes import T +from monolith.core.step_state import StepStateLayout +from monolith.formats.gguf import GGML_TYPES, ggml_row_bytes +from monolith.ops import OPS +from monolith.packs import PackFile +from monolith.packs.basalt import BasaltSource +from monolith.packs.packer import ALIGN +from tests.contract.test_basalt_reader import write_basalt +from tests.contract.test_basalt_windows import PROFILE + +F32, U8 = DType.F32, DType.U8 +KINDS = ("basalt_q8_1", "basalt_mmvq", "basalt_mmvf", "basalt_dense_tc", "basalt_dense_tc_pair") +Q8_1_FUNCTIONS = {"native": "native_quantize_q8_1", "swiglu": "native_swiglu_quantize_q8_1", "ieee": "quantize_q8_1"} +QK = kernels.Q8_1_BLOCK_BYTES + +# The tensors (name: (ggml type id, n_out, n_in)): every native_mmvq type at basalt's 2560 inputs, Q8_0 at 640 (the +# shared expert's down, fed by the SwiGLU quantizer), every dense_tc type in every summation order at basalt's defaults +# (170 multiprocessors, an aligned weight; "tile" at 2721 rows, 171 tiles, where a row is whole 16-byte units and 170 +# tiles would take the one order), the pair's types, and Q4_K at 2048 x 2720, 170 tiles, which 170 multiprocessors run +# in the one order and any fewer (PROFILE's 20, this M3 Max's 40) in the tile order. BF16 rows (name: (n_out, n_in)) +# live in the dense section, as basalt's do. +DTC_IN = {"one": 2048, "tile": 512, "s2": 22528, "s1": 23040} +MMVQ = {f"mmvq.{t}": (t, 70, 2560) for t in kernels.MMVQ_TRAITS} +MMVQ["mmvq.down"] = (8, 70, 640) +DTC = {f"dtc.{t}.{o}": (t, 2721 if o == "tile" and DTC_IN[o] // 256 * sb % 16 == 0 else 16, DTC_IN[o]) + for t, sb in kernels.DENSE_TC_SB.items() for o in DTC_IN} +PAIRS = [(14, 23), (12, 11), (42, 13)] # (w0, w1) types at 2560 inputs, 35 and 18 rows +PAIR = {f"pair.{a}.{b}.{m}": (ty, (35, 18)[m], 2560) for a, b in PAIRS for m, ty in enumerate((a, b))} +GGUF = {**MMVQ, **DTC, **PAIR, "order.q4_k": (12, 2720, 2048)} +BF16 = {"mmvf.q": (128, 2560), "mmvf.gate": (1, 2560)} + + +def gguf_bytes(type_id, n_out, n_in): + return n_out * ggml_row_bytes(type_id, n_in) + + +def write_file(path, gguf, bf16): + """A .basalt file with ``gguf`` ({name: (type id, n_out, n_in, bytes)}) in its gguf section, each tensor at the next + multiple of 4096 (basalt's kTensorAlign), and the BF16 matrices ``bf16`` ({name: (n_out, n_in, bytes)}) as dense + rows of kind 4 at multiples of 64 (its arena's alignment), so that tensors bind at offsets inside their windows.""" + blob, tensors = bytearray(), {} + for name, (t, n_out, n_in, data) in gguf.items(): + blob += bytes(-len(blob) % 4096) + tensors[name] = {"type_id": t, "shape": [n_in, n_out], "offset": len(blob), "bytes": len(data)} + blob += data + dense, rows = bytearray(), [] + for name, (n_out, n_in, data) in bf16.items(): + dense += bytes(-len(dense) % 64) + rows.append(f"{name} 0 4 {len(dense)} {len(data)} {len(dense)} {len(data)} {n_in} {n_out} 0 0 1 0 0 0 0 0 0 0") + dense += data + index = f"# dense index v3\n# align 64 pool {len(dense)} tensors {len(rows)}\n" + "\n".join(rows) + "\n" + meta = {"format": "basalt", "version": 1, "tensors": tensors} + path.write_bytes(write_basalt({"meta": json.dumps(meta).encode(), "gguf": bytes(blob), "dense": bytes(dense), + "dense.index": index.encode()})) + return path + + +@pytest.fixture(scope="module") +def src(tmp_path_factory): + """The tensors above as random bytes (the planner and the emitter never read them).""" + rng = np.random.default_rng(3) + noise = lambda n: rng.integers(0, 256, n, dtype=np.uint8).tobytes() # noqa: E731 + gguf = {n: (t, o, i, noise(gguf_bytes(t, o, i))) for n, (t, o, i) in GGUF.items()} + bf16 = {n: (o, i, noise(2 * o * i)) for n, (o, i) in BF16.items()} + return BasaltSource(write_file(tmp_path_factory.mktemp("ops") / "ops.basalt", gguf, bf16)) + + +# ---- graph builders (the GPU test uses them too) ------------------------------------------------------------------- + +def weight(g, name, src): + """The value that declares a gguf tensor or a BF16 dense row exactly (``gguf/`` a weight, ``dense/`` a constant).""" + e = src.entries[name] + if name.startswith("dense/"): + return g.const(name, e.shape, DType.BF16) + return g.weight(name, e.shape, GGML_TYPES[e.type_id][0]) + + +def op(g, kind, ins, outs, **attrs): + return g.op(kind, ins, outs, domain=BlockDomain("rows", 1), klass=OpClass.MAP, **attrs) + + +def q8_1(g, name, xs, kind="native", rows=T, width=None): + """``basalt_q8_1`` of ``xs`` (``[x]``, or ``[gate, up]`` for swiglu) into q8_1 rows named ``name``.""" + n_in = xs[0].shape[1] + y = g.value(name, (rows, n_in // 32 * QK if width is None else width), U8) + op(g, "basalt_q8_1", xs, [y], quantizer=kind) + return y + + +def gemv(g, kind, name, x, *ws, rows=T, widths=None): + """``kind`` (basalt_mmvq, basalt_dense_tc, basalt_dense_tc_pair, basalt_mmvf) of ``x`` by ``ws`` into F32 outputs + named ``name`` (the pair: ``name.0``, ``name.1``), each as wide as its weight's rows unless ``widths`` says.""" + widths = widths or [w.shape[0] for w in ws] + names = [name] if len(ws) == 1 else [f"{name}.{m}" for m in range(len(ws))] + ys = [g.value(n, (rows, wd), F32) for n, wd in zip(names, widths)] + op(g, kind, [x, *ws], ys) + return ys + + +def emit(g, src, t=1, packs=(), **kw): + return emit_program(g, pack=[src, *packs], profile=PROFILE, t=t, tail=None, **kw) + + +def specs(prog, kind): + return [o for o in prog.ops if o.name.startswith(kind + ":")] + + +def spliced(source): + """A builder's source as the emitter registers it: the StepState struct after the prelude (``_Ctx.kernel``).""" + return source.replace(kernels.PRELUDE, kernels.PRELUDE + StepStateLayout().to_msl() + "\n", 1) + + +def all_ops(g, src): + """Every kind over every tensor: one native q8_1 per input width, the SwiGLU into the Q8_0 down, the IEEE rows on + their own.""" + widths = sorted({e[2] for e in GGUF.values()}) + xs = {n: g.input(f"x{n}", (T, n), F32) for n in widths} + xq = {n: q8_1(g, f"xq{n}", [xs[n]]) for n in widths} + gate, up = g.input("gate", (T, 640), F32), g.input("up", (T, 640), F32) + hq = q8_1(g, "hq", [gate, up], "swiglu") + q8_1(g, "xq_ieee", [xs[2560]], "ieee") + for name, (_, _, n_in) in {**MMVQ, **DTC, "order.q4_k": GGUF["order.q4_k"]}.items(): + kind = "basalt_mmvq" if name.startswith("mmvq.") else "basalt_dense_tc" + gemv(g, kind, f"y.{name}", hq if name == "mmvq.down" else xq[n_in], weight(g, f"gguf/{name}", src)) + for a, b in PAIRS: + gemv(g, "basalt_dense_tc_pair", f"y.pair.{a}.{b}", xq[2560], + *[weight(g, f"gguf/pair.{a}.{b}.{m}", src) for m in (0, 1)]) + for name in BF16: + gemv(g, "basalt_mmvf", f"y.{name}", xs[2560], weight(g, f"dense/{name}", src)) + + +# ---- registration, and each dispatch against the builders ---------------------------------------------------------- + +def test_registered_and_covered(src): + for kind in KINDS: + od = OPS.get(kind) + assert od.klass == OpClass.MAP and od.binding_for(PROFILE.key).kernel == kind + g = Graph("step") + all_ops(g, src) + assert {o.kind for o in g.ops} == set(KINDS) + check_coverage(g, PROFILE) + + +def test_grid_builders_are_the_launchers(): + """The two grid builders this PR adds, against the harness's own formulas (tests/kernels/basalt_gpu.py).""" + for n in (32, 256, 2560, 8 * 23040): + assert kernels.basalt_q8_1_grid(n) == (-(-n // 256), 256) + for n_in, n_out, t in ((2560, 128, 1), (2560, 1, 5), (640, 7, 8)): + m = kernels.basalt_mmvf_macros(n_in, n_out, t) + assert kernels.basalt_mmvf_grid(m, n_out) == (n_out, kernels.basalt_mmvf_block(n_in)) + + +def expected(gop, src, t): + """(function, macros, source, params, grid, threadgroup) of ``gop``'s dispatch from the builders.""" + if gop.kind == "basalt_q8_1": + n = t * gop.inputs[0].shape[1] + return (Q8_1_FUNCTIONS[gop.attrs["quantizer"]], {}, kernels.basalt_q8_1_source(), kernels.basalt_q8_1_params(n), + -(-n // 256), 256) + ws = [src.entries[w.name] for w in gop.inputs[1:]] + tid, (n_out, n_in) = ws[0].type_id, ws[0].shape + if gop.kind == "basalt_mmvq": + m = kernels.basalt_mmvq_macros(tid, n_in, t) + return ("basalt_mmvq", m, kernels.basalt_mmvq_source(), kernels.basalt_mmvq_params(n_in, n_out), + *kernels.basalt_mmvq_grid(m, n_out)) + if gop.kind == "basalt_dense_tc": + m = kernels.basalt_dense_tc_macros(tid, n_in, n_out) + return ("basalt_dense_tc", m, kernels.basalt_dense_tc_source(), kernels.basalt_dense_tc_params(n_in, n_out, t), + *kernels.basalt_dense_tc_grid(m, n_out)) + if gop.kind == "basalt_dense_tc_pair": + t1, n_out1 = ws[1].type_id, ws[1].shape[0] + m = kernels.basalt_dense_tc_pair_macros(tid, t1, n_in) + return ("basalt_dense_tc_pair", m, kernels.basalt_dense_tc_source(), + kernels.basalt_dense_tc_params(n_in, n_out, t, n_out1), + *kernels.basalt_dense_tc_pair_grid(n_out, n_out1)) + m = kernels.basalt_mmvf_macros(n_in, n_out, t) + return ("basalt_mmvf", m, kernels.basalt_mmvf_source(), kernels.basalt_mmvf_params(n_in, n_out, t), + n_out, kernels.basalt_mmvf_block(n_in)) + + +def slot_values(gop): + """The values in the kernel's buffer slots 0, 1, ...: weights first for the q8_1 GEMVs, as the kernels take them.""" + ins, outs = list(gop.inputs), list(gop.outputs) + if gop.kind in ("basalt_mmvq", "basalt_dense_tc", "basalt_dense_tc_pair"): + ins = ins[1:] + ins[:1] + return ins + outs + + +@pytest.mark.parametrize("t", range(1, 9)) +def test_dispatches_are_the_builders(src, t): + """Every op of ``all_ops`` at T = t: one dispatch whose kernel, macros, grid, threadgroup and params record are the + builders' (the q8_1 and BF16 grids as the harness writes them), binding each weight at the window and offset the + planner gives it and each activation at 0 of its own buffer, writing exactly its outputs' slots, the params at + the slot after them; no StepState and no threadgroup memory.""" + g = Graph("step") + all_ops(g, src) + prog = emit(g, src, t) + _, bound = basalt_windows(src, g.values.values(), t) + assert len(prog.ops) == len(g.ops) + writer = {name: o for o in prog.ops for i, name, _ in o.bindings if i in o.meta["writes"]} + for gop in g.ops: + o = writer[gop.outputs[0].name] + fn, macros, source, params, grid, tg = expected(gop, src, t) + k = prog.kernels[o.kernel] + assert (k.function, k.macros, k.source) == (fn, macros, spliced(source)), gop + assert (o.grid, o.threadgroup, o.threadgroup_memory) == ((grid, 1, 1), (tg, 1, 1), []), gop + vals = slot_values(gop) + assert o.bindings[:-1] == [(i, *bound.get(v.name, (v.name, 0))) for i, v in enumerate(vals)], gop + slot, prm, off = o.bindings[-1] + assert (slot, off, prog.buffers[prm].role, prog.buffers[prm].init) == (len(vals), 0, "params", params), gop + assert o.meta["writes"] == list(range(len(gop.inputs), len(vals))), gop + + +def test_dense_tc_runs_basalts_orders(src): + """Each dtc.. tensor runs in the order it names (basalt's 170 multiprocessors, aligned weights).""" + g = Graph("step") + all_ops(g, src) + prog = emit(g, src, 8) + seen = set() + for o in [o for o in specs(prog, "basalt_dense_tc") if "/dtc." in o.name]: + _, ty, order = o.name.split("/")[1].split(".") + assert prog.kernels[o.kernel].macros["DTC_ORDER"] == str(kernels.DENSE_TC_ORDERS[order]), o.name + seen.add((int(ty), order)) + assert seen == {(t, o) for t in kernels.DENSE_TC_SB for o in DTC_IN} + + +def test_q8_1_rows_reach_their_readers_behind_a_barrier(src): + """The barrier pass orders each GEMV behind the quantizer whose rows it reads (``writes`` declares them).""" + g = Graph("step") + x = g.input("x", (T, 2560), F32) + xq = q8_1(g, "xq", [x]) + gemv(g, "basalt_mmvq", "y0", xq, weight(g, "gguf/mmvq.8", src)) + gemv(g, "basalt_dense_tc", "y1", xq, weight(g, "gguf/pair.14.23.0", src)) + gemv(g, "basalt_mmvf", "y2", x, weight(g, "dense/mmvf.q", src)) + prog = emit(g, src, 2) + assert [o.barrier_before for o in prog.ops] == [True, True, False, False] + + +# ---- refusals: each case's valid input emits, and the same input with its one defect is refused by its own check --- + +def pack(directory, entries, slab=False): + """A pack of zeros whose aux entries ``{name: (offset, nbytes)}`` sit at those offsets: the only route to a + misaligned binding (a .basalt entry binds at a multiple of 16, ``basalt_windows``; activations at whole rows). + ``slab``: the entries are block-lane-major bf16 slabs instead, one row-scale word each after the last.""" + directory.mkdir() + end = max(o + n for o, n in entries.values()) + size = -(-(end + 4 * len(entries)) // ALIGN) * ALIGN + (directory / "weights.pack").write_bytes(bytes(size)) + rows = [{"name": n, "offset": o, "nbytes": nb, "dtype": "U8", "shape": [nb]} for n, (o, nb) in entries.items()] + slabs = [dict(r, format="bf16", n=1, row_scales_offset=end + 4 * i) for i, r in enumerate(rows)] if slab else [] + (directory / "manifest.json").write_text(json.dumps({ + "version": 2, "alignment": ALIGN, "pack": "weights.pack", "nbytes": size, "slabs": slabs, + "aux": [] if slab else rows})) + return PackFile(directory) + + +def one_op(kind, g, src): + """A valid op of ``kind`` at T columns (with the quantizer feeding a q8_1 GEMV).""" + x = g.input("x", (T, 2560), F32) + if kind == "basalt_q8_1": + return q8_1(g, "xq", [x]) + if kind == "basalt_mmvf": + return gemv(g, kind, "y", x, weight(g, "dense/mmvf.q", src)) + ws = [weight(g, f"gguf/pair.14.23.{m}", src) for m in (0, 1)] + return gemv(g, kind, "y", q8_1(g, "xq", [x]), *(ws if kind == "basalt_dense_tc_pair" else ws[:1])) + + +def _dynamic(kind): + def build(g, src, bad, tmp): + one_op(kind, g, src) + return {"dynamic_t": bad} + return build + + +def _q8_1_columns(quantizer): + def build(g, src, bad, tmp): # 16 columns: a static count, as the default t_max (8) allows no T past 8 + rows = 16 if bad else 8 + xs = [g.input(n, (rows, 64), F32) for n in (("gate", "up") if quantizer == "swiglu" else ("x",))] + q8_1(g, "xq", xs, quantizer, rows=rows) + return {} + return build + + +def _q8_1_block(g, src, bad, tmp): + q8_1(g, "xq", [g.input("x", (T, 48 if bad else 64), F32)], width=72) + return {} + + +def _q8_1_width(g, src, bad, tmp): + q8_1(g, "xq", [g.input("x", (T, 64), F32)], width=76 if bad else 72) + return {} + + +def _q8_1_rows(g, src, bad, tmp): + q8_1(g, "xq", [g.input("x", (T, 64), F32)], rows=1 if bad else T) + return {} + + +def _q8_1_quantizer(g, src, bad, tmp): + q8_1(g, "xq", [g.input("x", (T, 64), F32)], "fast" if bad else "native") + return {} + + +def _ieee_reader(g, src, bad, tmp): + x = g.input("x", (T, 2560), F32) + ieee, native = q8_1(g, "xq_ieee", [x], "ieee"), q8_1(g, "xq", [x]) + gemv(g, "basalt_mmvq", "y", ieee if bad else native, weight(g, "gguf/mmvq.8", src)) + return {} + + +def _ieee_view(written): + """A native GEMV over rows a quantizer writes through a view (``written``) or the GEMV reads through one; the + rows are native (valid) or IEEE, which then reach the GEMV past the readers check.""" + def build(g, src, bad, tmp): + rows = g.value("rows", (2, 2880), U8) + view = g.view("rows_v", rows, 0, 2) + op(g, "basalt_q8_1", [g.input("x", (2, 2560), F32)], [view if written else rows], + quantizer="ieee" if bad else "native") + gemv(g, "basalt_mmvq", "y", rows if written else view, weight(g, "gguf/mmvq.8", src), rows=2) + return {} + return build + + +def _weight_type(kind, good, other): + def build(g, src, bad, tmp): + x = g.input("x", (T, 2560), F32) + gemv(g, kind, "y", x if kind == "basalt_mmvf" else q8_1(g, "xq", [x]), weight(g, other if bad else good, src)) + return {} + return build + + +def _xq_width(g, src, bad, tmp): + xq = q8_1(g, "xq", [g.input("x", (T, 640 if bad else 2560), F32)]) + gemv(g, "basalt_mmvq", "y", xq, weight(g, "gguf/mmvq.8", src)) + return {} + + +def _out_width(kind, extra): + """``kind`` whose (last) output is ``extra`` values wider than its weight's rows.""" + def build(g, src, bad, tmp): + x = g.input("x", (T, 2560), F32) + names = {"basalt_mmvf": ["dense/mmvf.q"], "basalt_dense_tc_pair": ["gguf/pair.14.23.0", "gguf/pair.14.23.1"]} + ws = [weight(g, n, src) for n in names.get(kind, ["gguf/pair.14.23.0"])] + widths = [w.shape[0] + (extra if bad and m == len(ws) - 1 else 0) for m, w in enumerate(ws)] + gemv(g, kind, "y", x if kind == "basalt_mmvf" else q8_1(g, "xq", [x]), *ws, widths=widths) + return {} + return build + + +def _pair_inputs(g, src, bad, tmp): + xq = q8_1(g, "xq", [g.input("x", (T, 2560), F32)]) + gemv(g, "basalt_dense_tc_pair", "y", xq, weight(g, "gguf/pair.14.23.0", src), + weight(g, "gguf/dtc.12.one" if bad else "gguf/pair.14.23.1", src)) + return {} + + +def _mmvf_x_width(g, src, bad, tmp): + gemv(g, "basalt_mmvf", "y", g.input("x", (T, 2562 if bad else 2560), F32), weight(g, "dense/mmvf.q", src)) + return {} + + +def _blm_slab(g, src, bad, tmp): + """The same bytes as a pack's aux entry (rows as stored) or as its bf16 slab (re-laid-out lanes).""" + w = g.weight("p", (128, 2560), "bf16") + gemv(g, "basalt_mmvf", "y", g.input("x", (T, 2560), F32), w) + return {"packs": [pack(tmp, {"p": (0, 128 * 2560 * 2)}, slab=bad)]} + + +def _aligned(kind, slot, offset): + """``kind`` with the value of kernel slot ``slot`` read from a pack entry at byte 16 (valid) or ``offset``.""" + def build(g, src, bad, tmp): + at = offset if bad else 16 + x = g.input("x", (T, 2560), F32) + if kind == "basalt_q8_1": + q8_1(g, "xq", [g.const("p", (2, 64), F32)]) + return {"packs": [pack(tmp, {"p": (at, 2 * 64 * 4)})]} + if kind == "basalt_mmvf": + v = g.const("p", *(((2, 2560), F32) if slot == 0 else ((128, 2560), DType.BF16))) + gemv(g, kind, "y", v if slot == 0 else x, v if slot == 1 else weight(g, "dense/mmvf.q", src)) + return {"packs": [pack(tmp, {"p": (at, int(np.prod(v.shape)) * v.dtype.itemsize)})]} + ws = [weight(g, f"gguf/pair.14.23.{m}", src) for m in (0, 1)][: 2 if kind == "basalt_dense_tc_pair" else 1] + if slot == len(ws): # the q8_1 rows + gemv(g, kind, "y", g.const("p", (2, 2880), U8), *ws) + return {"packs": [pack(tmp, {"p": (at, 2 * 2880)})]} + e = src.entries[ws[slot].name] + ws[slot] = g.weight("p", e.shape, GGML_TYPES[e.type_id][0]) + gemv(g, kind, "y", q8_1(g, "xq", [x]), *ws) + return {"packs": [pack(tmp, {"p": (at, e.nbytes)})]} + return build + + +def _entry_rows(kind, rows): + """``kind`` whose weight (the pair's second) is a pack entry at byte 16 holding exactly its rows (valid), or + ``rows`` rows more (-1: a row short, which the kernel would read past). ``emit_program``'s constant check refuses + a short BF16 constant before the handler runs, so the BF16 GEMV's case is a row long.""" + def build(g, src, bad, tmp): + x, more = g.input("x", (T, 2560), F32), rows if bad else 0 + if kind == "basalt_mmvf": + gemv(g, kind, "y", x, g.const("p", (128, 2560), DType.BF16)) + return {"packs": [pack(tmp, {"p": (16, (128 + more) * 2560 * 2)})]} + ws = [weight(g, f"gguf/pair.14.23.{m}", src) for m in (0, 1)][: 2 if kind == "basalt_dense_tc_pair" else 1] + e = src.entries[ws[-1].name] + ws[-1] = g.weight("p", e.shape, GGML_TYPES[e.type_id][0]) + gemv(g, kind, "y", q8_1(g, "xq", [x]), *ws) + return {"packs": [pack(tmp, {"p": (16, e.nbytes + more * e.nbytes // e.shape[0])})]} + return build + + +REFUSALS = [ + *[(f"dynamic-T {k}", _dynamic(k), "a dynamic-T program cannot run them") for k in KINDS], + ("native q8_1 of 16 columns", _q8_1_columns("native"), "16 columns; basalt quantizes 1 to 8"), + ("swiglu q8_1 of 16 columns", _q8_1_columns("swiglu"), "16 columns; basalt quantizes 1 to 8"), + ("q8_1 column not whole blocks", _q8_1_block, "a column of 48 values is not whole 32-value blocks"), + ("q8_1 rows of another width", _q8_1_width, r"is u8 \[2, 76\], not u8 \[2, 72\] \(q8_1 rows"), + ("q8_1 rows for other columns", _q8_1_rows, r"'x' is f32 \[2, 64\], not f32 \[1, 64\] \(the quantized columns\)"), + ("q8_1 quantizer unknown", _q8_1_quantizer, "attr quantizer must be one of"), + ("IEEE q8_1 rows read by a GEMV", _ieee_reader, r"is read by \['basalt_mmvq'\]; basalt's IEEE rows feed only"), + ("IEEE q8_1 rows written to a view", _ieee_view(True), r"'rows_v' shares its buffer with \['rows'\]"), + ("IEEE q8_1 rows read through a view", _ieee_view(False), r"'rows' shares its buffer with \['rows_v'\]"), + ("mmvq on a BF16 matrix", _weight_type("basalt_mmvq", "gguf/mmvq.8", "dense/mmvf.q"), "of ggml type"), + ("dense_tc on a Q8_0 matrix", _weight_type("basalt_dense_tc", "gguf/mmvq.12", "gguf/mmvq.8"), "of ggml type"), + ("mmvf on a Q8_0 matrix", _weight_type("basalt_mmvf", "dense/mmvf.q", "gguf/mmvq.8"), r"of ggml type \['bf16'\]"), + ("mmvq rows of another input", _xq_width, r"is u8 \[2, 720\], not u8 \[2, 2880\] \(q8_1 rows of the weight's"), + *[(f"{k} output wider than its rows", _out_width(k, 2), "contiguous columns of the weight's rows") + for k in ("basalt_mmvq", "basalt_dense_tc", "basalt_dense_tc_pair", "basalt_mmvf")], + ("mmvf ldy < n_out", _out_width("basalt_mmvf", -1), r"holds 127 values a row .* so ldy >= n_out"), + ("mmvf on a BLM bf16 slab", _blm_slab, "is a block-lane-major pack slab, not rows as stored"), + ("mmvf input wider than its weight", _mmvf_x_width, "contiguous columns of the weight's width"), + ("pair over two input widths", _pair_inputs, "the pair reads one input"), + ("q8_1 input off 4 bytes", _aligned("basalt_q8_1", 0, 2), "slot 0 needs 4-byte alignment"), + ("mmvq weight off 4 bytes", _aligned("basalt_mmvq", 0, 2), "slot 0 needs 4-byte alignment"), + ("mmvq rows off 4 bytes", _aligned("basalt_mmvq", 1, 2), "slot 1 needs 4-byte alignment"), + ("dense_tc weight off 4 bytes", _aligned("basalt_dense_tc", 0, 2), "slot 0 needs 4-byte alignment"), + ("dense_tc rows off 4 bytes", _aligned("basalt_dense_tc", 1, 2), "slot 1 needs 4-byte alignment"), + ("pair w0 off 16 bytes", _aligned("basalt_dense_tc_pair", 0, 8), "slot 0 needs 16-byte alignment"), + ("pair w1 off 16 bytes", _aligned("basalt_dense_tc_pair", 1, 8), "slot 1 needs 16-byte alignment"), + ("pair rows off 4 bytes", _aligned("basalt_dense_tc_pair", 2, 2), "slot 2 needs 4-byte alignment"), + ("mmvf input off 8 bytes", _aligned("basalt_mmvf", 0, 4), "slot 0 needs 8-byte alignment"), + ("mmvf weight off 4 bytes", _aligned("basalt_mmvf", 1, 2), "slot 1 needs 4-byte alignment"), + *[(f"{k} weight entry a row short", _entry_rows(k, -1), r"bytes of \w+ \[\d+, 2560\], but its pack entry holds") + for k in ("basalt_mmvq", "basalt_dense_tc", "basalt_dense_tc_pair")], + ("mmvf weight entry a row long", _entry_rows("basalt_mmvf", 1), + r"'p' is 655360 bytes of bf16 \[128, 2560\], but its pack entry holds 660480"), +] + + +@pytest.mark.parametrize("build, why", [r[1:] for r in REFUSALS], ids=[r[0] for r in REFUSALS]) +def test_refusals(src, tmp_path, build, why): + for bad in (False, True): + g = Graph("step") + kw = build(g, src, bad, tmp_path / f"pack{int(bad)}") + packs = kw.pop("packs", []) + if not bad: + emit(g, src, 2, packs, **kw) + continue + with pytest.raises(ValueError, match=why): + emit(g, src, 2, packs, **kw) + + +def test_ieee_q8_1_takes_any_column_count(src): + """basalt's quantize_q8_1_rows checks only that it has values (iq_kernels.cu:2450-2453): 16 columns emit.""" + g = Graph("step") + q8_1(g, "xq", [g.input("x", (16, 64), F32)], "ieee", rows=16) + (o,) = emit(g, src, 1).ops + assert o.grid == (4, 1, 1) + + +def test_dense_tc_order_is_basalts_not_this_gpus(src, tmp_path): + """Q4_K at 2048 x 2720 (170 tiles): basalt's 170 multiprocessors run the one order, any fewer cores would give the + tile order (PROFILE's 20, this M3 Max's 40, every Apple GPU's), and a weight off a 16-byte boundary the KS 1 order. + The emitted order stays basalt's for the file's weight and for the same shape bound at byte 8 of a pack (4-byte + aligned, which dense_tc takes).""" + rule = kernels.basalt_dense_tc_variant + assert (rule(12, 2048, 2720), rule(12, 2048, 2720, aligned=False)) == ("one", "s1") + assert {rule(12, 2048, 2720, sm_count=n) for n in range(1, 170)} == {"tile"} + for at in (None, 8): + g = Graph("step") + xq = q8_1(g, "xq", [g.input("x", (T, 2048), F32)]) + w = weight(g, "gguf/order.q4_k", src) if at is None else g.weight("p", (2720, 2048), "q4_k") + gemv(g, "basalt_dense_tc", "y", xq, w) + prog = emit(g, src, 4, [] if at is None else [pack(tmp_path / "p", {"p": (at, 2720 * 1152)})]) + (o,) = specs(prog, "basalt_dense_tc") + assert o.bindings[0][2] % 16 == (0 if at is None else 8) + assert prog.kernels[o.kernel].macros == {"DTC_TYPE": "12", "DTC_ORDER": "0"} diff --git a/tests/contract/test_basalt_pack.py b/tests/contract/test_basalt_pack.py new file mode 100644 index 00000000..be3bd2b7 --- /dev/null +++ b/tests/contract/test_basalt_pack.py @@ -0,0 +1,89 @@ +"""The official Q2_0 pack (jesdga/Qwen3.8-Flash-Next-Basalt, Qwen3.8-FN-GSQ-RCO-Q2_0.basalt @ 2a6a758) through the +reader and the format plugins: its header, its index sections and where its rows lie, and real rows of every ggml type +it uses decoded byte for byte like the independent reference (and, with BASALT_SRC, like basalt's compiled ones). +fixtures/basalt_pack.safetensors holds the bytes, range-read by fixtures/make_basalt_fixture.py.""" + +import gzip +import hashlib +import json +from pathlib import Path + +import numpy as np +import pytest + +from monolith.formats.basalt_reader import MTP_KINDS, parse_dense_index, parse_experts_layout, parse_header, parse_mtp_dense_index +from monolith.formats.gguf import GGML_TYPES, ggml_dequantize, ggml_row_bytes +from monolith.formats.safetensors_reader import SafetensorsDir, read_header +from tests.contract import gguf_reference as ref +from tests.contract.test_gguf_formats import assert_matches_basalt, basalt_references # noqa: F401 (fixture) + +FIXTURE = Path(__file__).with_name("fixtures") / "basalt_pack.safetensors" +PACK = json.loads(read_header(FIXTURE)[1]["fixture"]) +ROWS = PACK["entries"] + + +def rows_of(entry): + rows = np.ascontiguousarray(SafetensorsDir(FIXTURE).get(entry["key"])) + return rows.reshape(len(entry["rows"]), -1), entry["values"] + + +def test_header_indexes_and_row_offsets(): + st = SafetensorsDir(FIXTURE) + file_bytes, secs = parse_header(st.get("header").tobytes()) + assert file_bytes == PACK["file_bytes"] == 69685970297 and len(secs) == 18 + assert list(secs)[5:12] == ["dense", "dense.index", "experts", "experts.layout", "gguf", "mtp/dense", "mtp/dense.index"] + text = {"experts.layout": st.get("section/experts.layout").tobytes(), "mtp/dense.index": st.get("section/mtp/dense.index").tobytes(), + "dense.index": gzip.decompress(st.get("section/dense.index.gz").tobytes())} + for name, data in text.items(): # the range reads and the table agree + assert len(data) == secs[name].nbytes and hashlib.sha256(data).digest() == secs[name].sha256 + + di = parse_dense_index(text["dense.index"].decode(), secs["dense"].nbytes) # every check, real sizes + assert (di.version, di.align, len(di.rows)) == (3, 64, 1079) and {r.kind for r in di.rows} == {0, 2, 4, 5} + at = 0 + for r in di.rows: # the pool is the rows, 64-aligned, in order + assert r.dst_off == at and r.file == 0 + at += -(-r.dst_bytes // di.align) * di.align + assert at == di.pool <= secs["dense"].nbytes + native = [r for r in di.rows if r.in_gguf] + assert len(native) == 303 and all((r.kind, r.src_bytes, r.code_bits, r.group_elems) == (0, 0, 8, 32) for r in native) + + lay = parse_experts_layout(text["experts.layout"].decode(), secs["experts"].nbytes) + assert (lay.version, lay.n_expert, len(lay.layers), lay.total) == (5, 512, 48, secs["experts"].nbytes) + assert {(e.gu_type, e.d_type, e.blob_bytes) for e in lay.layers} == {(42, 42, 1382400)} # every routed expert Q2_0 + dims = PACK["expert_dims"] + assert lay.matrices(47, *dims) == ((42, 0, 640, 2560), (42, 460800, 640, 2560), (42, 921600, 2560, 640)) + + mtp = parse_mtp_dense_index(text["mtp/dense.index"].decode(), secs["mtp/dense"].nbytes) + assert len(mtp) == 29 and {t.kind for t in mtp} == set(MTP_KINDS) + assert all(t.offset % 256 == 0 for t in mtp) and max(t.offset + t.nbytes for t in mtp) == secs["mtp/dense"].nbytes + + for e in ROWS: # where every fixture row was read + row = ggml_row_bytes(e["type_id"], e["ne0"]) + if e["source"] == "gguf": + m = e["meta"] + assert m["type_id"] == e["type_id"] and m["offset"] % 4096 == 0 + assert m["bytes"] == row * int(np.prod(m["shape"][1:], dtype=np.int64)) + base = secs["gguf"].offset + m["offset"] + else: + matrix = dict(zip(("gate", "up", "down"), lay.matrices(e["layer"], *dims)))[e["role"]] + assert matrix[0] == e["type_id"] and matrix[3] == e["ne0"] + base = secs["experts"].offset + lay.blob_offset(e["layer"], e["expert"]) + matrix[1] + assert e["offsets"] == [base + r * row for r in e["rows"]] + + +def test_rows_cover_every_type_the_pack_uses(): + assert {e["type_id"] for e in ROWS} == set(GGML_TYPES) + + +@pytest.mark.parametrize("entry", ROWS, ids=lambda e: e["key"]) +def test_real_rows_match_the_reference(entry): + rows, k = rows_of(entry) + ours = ggml_dequantize(entry["type_id"], rows, (rows.shape[0], k)) + assert np.array_equal(ours.view(np.uint32), ref.dequantize(entry["type_id"], rows).view(np.uint32)) + rms = float(np.sqrt(np.mean(ours.astype(np.float64) ** 2))) + assert np.isfinite(ours).all() and 1e-4 < rms < 10, rms # weights, not padding + + +@pytest.mark.parametrize("entry", ROWS, ids=lambda e: e["key"]) +def test_real_rows_match_basalts_compiled_references(basalt_references, entry): + assert_matches_basalt(basalt_references, entry["type_id"], *rows_of(entry)) diff --git a/tests/contract/test_basalt_reader.py b/tests/contract/test_basalt_reader.py new file mode 100644 index 00000000..408c335c --- /dev/null +++ b/tests/contract/test_basalt_reader.py @@ -0,0 +1,205 @@ +"""The .basalt reader (monolith/formats/basalt_reader.py) on a file written the way basalt's tools/model_file.py writes +one, and the refusals basalt's own readers make (test_basalt_pack.py reads the official pack's sections). Each refusal +case is a valid input with exactly one defect, and must be refused by that defect's own check (its message).""" + +import hashlib +import json + +import numpy as np +import pytest + +from monolith.formats.basalt_reader import (ENTRY, HEADER, HEADER_BYTES, MAGIC, MAX_SECTIONS, SECTION_ALIGN, BasaltFile, + parse_dense_index, parse_experts_layout, parse_header, parse_mtp_dense_index) +from monolith.formats.gguf import ggml_dequantize, ggml_row_bytes + + +def write_basalt(sections, version=1): + """tools/model_file.py's ModelWriter: 64 KiB of header, each section at the next 2 MiB boundary, then the table.""" + out, table = bytearray(HEADER_BYTES), [] + for name, data in sections.items(): + at = -(-len(out) // SECTION_ALIGN) * SECTION_ALIGN + out += bytes(at - len(out)) + data + table.append(ENTRY.pack(name.encode(), at, len(data), hashlib.sha256(data).digest(), bytes(16))) + out[: HEADER.size] = HEADER.pack(MAGIC, version, len(table), len(out), bytes(40)) + out[HEADER.size: HEADER.size + ENTRY.size * len(table)] = b"".join(table) + return out + + +def q8_0_rows(): + """Two rows of two Q8_0 blocks: d = 1, codes −16 … 15 and 0 … 31, so row r holds its own codes as values.""" + codes = np.array([np.arange(-16, 16), np.arange(32)] * 2, np.int8).reshape(2, 2, 32) + blocks = np.zeros((2, 2, 34), np.uint8) + blocks[..., :2] = np.array([0x3C00], " 8, offsets 4 + "p.weight 0 1 32 16 32 8 4 0 0 0 1 0 0 0 0 0 0 0"] # BF16 in F32: 16 bytes in, 8 out + + +def dense_index(rows, header="# dense index v3\n# align 64 pool 64 tensors {}\n"): + return header.format(len(rows)) + "".join(r + "\n" for r in rows) + + +def test_refuses_a_broken_dense_index(): + """weights.cpp's parse, then its checks of every row it loads, over a 64-byte ``dense``.""" + assert [r.name for r in parse_dense_index(dense_index(DENSE_ROWS), 64).rows] == [r.split()[0] for r in DENSE_ROWS] + + def edit(i, row): + return dense_index(DENSE_ROWS[:i] + [row] + DENSE_ROWS[i + 1:]) + + for text, why in [(edit(1, DENSE_ROWS[1][:-2]), "18 of 19"), (edit(1, DENSE_ROWS[1] + " 0"), "20 of 19"), + (dense_index(DENSE_ROWS).replace("v3", "v4"), "version 4"), + (dense_index(DENSE_ROWS, "# dense index v3\n# align 64 pool 64 tensors 5\n"), "counts 5"), + (dense_index(DENSE_ROWS, "# dense index v3\n# align 64 pool 0 tensors {}\n"), "no rows"), + (dense_index([]), "no rows"), (dense_index(DENSE_ROWS, "# dense index v3\n"), "no rows"), + (edit(1, "b.weight 1 2 0 16 0 16 4 0 0 0 1 0 0 0 0 0 0 0"), "names file 1"), + (edit(1, "b.weight 0 2 49 16 0 16 4 0 0 0 1 0 0 0 0 0 0 0"), "runs past"), + (edit(1, "b.weight 0 2 -4 16 0 16 4 0 0 0 1 0 0 0 0 0 0 0"), "negative"), + (edit(1, "b.weight 0 2 0 16 0 16 -4 0 0 0 1 0 0 0 0 0 0 0"), "negative"), # a shape + (edit(2, "q.weight 0 0 16 16 16 20 32 1 2 0 16 0 1 -8 8 20 1 0"), "negative"), # planes add up + (edit(2, "q.weight 0 0 16 20 16 20 32 1 2 0 16 0 1 8 8 4 1 0"), "planes make 16/20"), + (edit(2, "q.weight 0 0 16 15 16 18 32 1 2 0 16 0 1 8 6 4 1 0"), "odd byte count"), + (edit(3, "p.weight 0 1 32 16 32 16 4 0 0 0 1 0 0 0 0 0 0 0"), "planes make 16/8"), + (edit(3, "p.weight 0 3 32 16 32 16 4 0 0 0 1 0 0 0 0 0 0 0"), "planes make 16/8")]: + with pytest.raises(ValueError, match=why): + parse_dense_index(text, 64) + + +def test_refuses_a_broken_experts_layout(): + layout = sample_sections()["experts.layout"].decode() # two layers of two blobs + blob = int(layout.splitlines()[1].split()[4]) + lay = parse_experts_layout(layout, 4 * blob) + assert parse_experts_layout(layout, 5 * blob) == lay # one blob of padding + negative = layout.replace(f"total {4 * blob}", f"total {blob}").replace(f" {blob} extra", f" -{blob // 2} extra") + for text, size, why in [(layout.replace("experts v5", "experts v6"), 4 * blob, "v6"), + (layout.replace(f" {2 * blob} ", f" {2 * blob + 1} "), 4 * blob, "not contiguous"), + (layout.replace("total ", "total 1"), 4 * blob, "the header says"), + (layout.replace("(n_expert 2, ", "("), 4 * blob, "no expert count"), + (layout + f"1 42 42 {2 * blob} {blob}\n", 4 * blob, "malformed"), # layer 1 twice + (negative, blob, "malformed"), # a negative blob that still adds up + (layout, 4 * blob - 1, "the experts section is"), + (layout, 6 * blob, "the experts section is"), + (f"# experts v5 (n_expert 2, total {2 * blob})\n0 42 42 0 {blob}\n", 4 * blob, + "the experts section is")]: # a layer short + with pytest.raises(ValueError, match=why): + parse_experts_layout(text, size) + with pytest.raises(ValueError, match="not gate/up/down"): + lay.matrices(0, 128, 128) # not this blob's geometry + for layer, expert, why in [(-1, 0, "layer -1 of 2"), (2, 0, "layer 2 of 2"), (0, -1, "expert -1 of 2"), + (0, 2, "expert 2 of 2")]: + with pytest.raises(IndexError, match=why): + lay.blob_offset(layer, expert) + with pytest.raises(IndexError, match="layer -1 of 2"): + lay.matrices(-1, 128, 64) + + +def test_refuses_a_broken_mtp_dense_index(): + good = sample_sections()["mtp/dense.index"].decode() # 136 bytes at 0, 256 at 256 + assert len(parse_mtp_dense_index(good, 512)) == 2 + for text, size, why in [("fc.weight q8_0 2 64 0\n", 512, "malformed"), + ("fc.weight q8_0 2 64 0 136 0\n", 512, "malformed"), + ("fc.weight q8_0 2 64 0 137\n", 512, "137 bytes"), + (good, 511, "past the mtp/dense section"), + ("fc.weight q8_0 2 64 -8 136\n", 512, "negative"), + ("fc.weight q8_0 -1 -64 0 68\n", 512, "negative")]: # sizes that add up + with pytest.raises(ValueError, match=why): + parse_mtp_dense_index(text, size) + + +def test_checks_each_index_against_its_own_section(): + """A file one byte short of what an index names, in that index's section.""" + secs = sample_sections() + for name, read, why in [("dense", BasaltFile.dense_index, "runs past"), + ("experts", BasaltFile.experts_layout, "the experts section is"), + ("mtp/dense", BasaltFile.mtp_dense_index, "past the mtp/dense section")]: + with pytest.raises(ValueError, match=why): + read(BasaltFile(bytes(write_basalt({**secs, name: secs[name][:-1]})))) diff --git a/tests/contract/test_basalt_windows.py b/tests/contract/test_basalt_windows.py new file mode 100644 index 00000000..34a01e90 --- /dev/null +++ b/tests/contract/test_basalt_windows.py @@ -0,0 +1,412 @@ +"""A .basalt file as a weight source (monolith/packs/basalt.py) and the emitter's window planner for it +(compiler/emit.py ``basalt_windows``), on a synthetic file written with the reader tests' ``write_basalt`` and on the +official pack's header and index sections (fixtures/basalt_pack.safetensors). Each refusal case is a valid input with +exactly one defect, refused by that defect's own check (its message).""" + +import gzip +import json +import re +from pathlib import Path + +import numpy as np +import pytest + +from monolith.compiler import emit_program +from monolith.compiler.emit import WINDOW_BYTES, basalt_windows +from monolith.core import DType, Graph, Profile +from monolith.formats.basalt_reader import HEADER_BYTES, BasaltFile, parse_header +from monolith.formats.gguf import GGML_TYPES, ggml_row_bytes +from monolith.formats.safetensors_reader import SafetensorsDir, read_header +from monolith.packs import PackFile +from monolith.packs.basalt import HC8, BasaltEntry, BasaltSource +from monolith.packs.packer import ALIGN +from monolith.runtime.program import BufferSpec +from tests.contract.test_basalt_reader import write_basalt + +PROFILE = Profile.from_dict("p", {"gpu_cores": 20, "nominal_gbps": 307.0, + "engine": {"family": "Apple10", "lane_order": "interleaved16"}}) +GGUF = { # name: (ggml type id, ne, offset in gguf); the comments are 16 KiB pages + "a.weight": (8, [64, 4], 0), # Q8_0, 272 bytes, page 0 + "b.weight": (12, [256, 2], 4096), # Q4_K, 288 bytes, page 0 at 4096 + "c.weight": (30, [8192, 3], 16384), # BF16, pages 1 to 3 exactly + "d.weight": (42, [128, 2], 69632), # Q2_0, page 4 + "e.weight": (0, [64], 98304), # F32, page 6 + "q3.weight": (11, [256, 1], 102400), # Q3_K, 110 bytes, page 6 at 4096 + "x.weight": (99, [16], 106496), # a type no format plugin reads + "z.weight": (0, [0], 110592), # no bytes + "pre.weight": (0, [16], 114688), # page 7: the last whole page of the file + "tail.weight": (0, [16], 131072), # page 8: the file's last page, which the file ends inside +} +GGUF_BYTES = 131072 + 100 # gguf is the last section, so the file does not end on a page +DENSE = [ # dense.index v3 rows: name file kind src_off src_bytes dst_off dst_bytes ne0 ne1 ... + "n0.weight 0 2 0 256 0 256 64 0 0 0 1 0 0 0 0 0 0 0", # F32 [64], page 0 + "hc.weight 0 4 256 65536 256 65536 16384 2 0 0 1 0 0 0 0 0 0 0", # BF16 [2, 16384]: pages 0 to 4, bound by none + "n1.weight 0 5 65792 256 65792 256 64 2 0 0 1 0 0 0 0 0 0 0", # F16 [2, 64], page 4 + "n2.weight 0 2 66048 256 67072 256 16 4 0 0 1 0 0 0 0 0 0 0", # F32 [4, 16], page 4; slot past m's + "g.weight 0 0 0 0 0 0 64 2 8 0 32 0 0 0 0 0 0 0", # shape only: served from gguf + "p.weight 0 1 66304 256 66304 128 64 0 0 0 1 0 0 0 0 0 0 0", # BF16 promoted to F32: converted at load + "k0.weight 0 0 66560 64 66560 64 256 0 2 0 32 0 0 64 0 0 0 0", # kind 0: basalt's verbatim planes + "s.weight 0 2 66624 256 66624 128 64 0 0 0 1 0 0 0 0 0 0 0", # 256 source bytes for a 128-byte slot + "m.weight 0 2 66880 192 66880 192 64 0 0 0 1 0 0 0 0 0 0 0", # 192 bytes for F32 [64] +] +MTP = b"fc.weight q8_0 2 64 0 136\nnorm.weight f32 1 64 256 256\nproj.weight bf16 4 64 512 512\nodd.weight f64 1 8 1024 64\n" +BOUND = ["gguf/a.weight", "gguf/b.weight", "gguf/c.weight", "gguf/e.weight", "gguf/q3.weight", "dense/n0.weight", + "dense/n1.weight", "dense/n2.weight", "mtp/fc.weight", "mtp/norm.weight", "mtp/proj.weight", "mtp/experts"] + + +def write(tmp_path, gguf=None, dense=None, name="model.basalt", mtp=None): + """A synthetic .basalt file of random bytes with the tensors above; ``gguf`` / ``dense`` / ``mtp`` replace the + tables.""" + gguf, dense, mtp = gguf or GGUF, dense or DENSE, mtp or MTP + rng = np.random.default_rng(7) + noise = lambda n: rng.integers(0, 256, n, dtype=np.uint8).tobytes() # noqa: E731 + meta = {"format": "basalt", "version": 1, "tensors": { + k: {"type_id": t, "shape": ne, "offset": off, + "bytes": nb[0] if nb else 64 if t not in GGML_TYPES else ggml_row_bytes(t, ne[0]) * int(np.prod(ne[1:], dtype=np.int64))} + for k, (t, ne, off, *nb) in gguf.items()}} # an optional fourth item states the bytes + index = f"# dense index v3\n# align 64 pool 81920 tensors {len(dense)}\n" + "\n".join(dense) + "\n" + path = tmp_path / name + path.write_bytes(write_basalt({"meta": json.dumps(meta).encode(), "dense": noise(81920), + "dense.index": index.encode(), "mtp/dense": noise(2048), "mtp/dense.index": mtp, + "mtp/experts": noise(33768), "gguf": noise(GGUF_BYTES)})) + return path + + +def value(g, src, name): + """The graph value that declares ``name``'s entry exactly: a constant for dense rows and sections (the dtype names + the type), a weight elsewhere (the format names the type).""" + e = src.entries[name] + kind = "u8" if e.type_id is None else GGML_TYPES[e.type_id][0] + if name.startswith("dense/") or e.type_id is None: + return g.const(name, e.shape, DType.parse(kind)) + return g.weight(name, e.shape, kind) + + +def plan(src, *names): + g = Graph("step") + for n in names: + value(g, src, n) + return basalt_windows(src, g.values.values()) + + +def pages(offset, nbytes, whole=False): + """The 16 KiB pages a byte range touches, or (``whole``) the ones it fills.""" + return set(range(-(-offset // ALIGN), (offset + nbytes) // ALIGN) if whole else + range(offset // ALIGN, -(-(offset + nbytes) // ALIGN))) + + +def mapped(buffers): + return set().union(*(pages(b.file_offset, b.nbytes) for b in buffers.values())) + + +def test_source_names_each_tensor_by_its_name_space(tmp_path): + """Every entry the other tests bind (BOUND) at the offset the tables above give it, so the GPU test, which takes + its expected bytes from the entries, reads the right ones: a dense row at its file offset (src_off), not at its + arena slot (dst_off).""" + src = BasaltSource(write(tmp_path)) + gg, de, mt, mx = (src.file.section(s).offset for s in ("gguf", "dense", "mtp/dense", "mtp/experts")) + E = BasaltEntry + want = [E("gguf/a.weight", gg, 272, 8, (4, 64)), E("gguf/b.weight", gg + 4096, 288, 12, (2, 256)), + E("gguf/c.weight", gg + 16384, 49152, 30, (3, 8192)), E("gguf/q3.weight", gg + 102400, 110, 11, (1, 256)), + E("gguf/e.weight", gg + 98304, 256, 0, (64,)), E("dense/n0.weight", de, 256, 0, (64,)), + E("dense/n1.weight", de + 65792, 256, 1, (2, 64)), E("dense/n2.weight", de + 66048, 256, 0, (4, 16)), + E("dense/hc.weight", de + 256, 65536, 30, (2, 16384)), E("mtp/fc.weight", mt, 136, 8, (2, 64)), + E("mtp/norm.weight", mt + 256, 256, 0, (1, 64)), E("mtp/proj.weight", mt + 512, 512, 30, (4, 64)), + E("mtp/experts", mx, 33768, None, (33768,))] + assert [src.entries[e.name] for e in want] == want and set(BOUND) <= {e.name for e in want} + assert set(src.refused) == {"gguf/x.weight", "gguf/z.weight", "dense/g.weight", "dense/p.weight", + "dense/k0.weight", "dense/s.weight", "dense/m.weight", "mtp/odd.weight"} + assert src.slabs == {} and src.aux == {} and src.file_bytes % ALIGN == 100 + + +def test_windows_map_only_the_pages_bound_entries_touch(tmp_path): + src = BasaltSource(write(tmp_path)) + buffers, bound = plan(src, *BOUND) + assert sorted(bound) == sorted(BOUND) and all(name.startswith("basalt.") for name in buffers) + for b in buffers.values(): + assert (b.role, b.file, b.init) == ("weights", src.path, None) + assert b.file_offset % ALIGN == 0 and b.nbytes % ALIGN == 0 and b.file_offset + b.nbytes <= src.file_bytes + for n in BOUND: + e, (w, off) = src.entries[n], bound[n] + assert off == e.offset - buffers[w].file_offset and off % 16 == 0 and off + e.nbytes <= buffers[w].nbytes + assert bound["gguf/b.weight"][1] == 4096 and bound["gguf/q3.weight"][1] == 4096 + gg, de, mt, mx = (src.file.section(s).offset for s in ("gguf", "dense", "mtp/dense", "mtp/experts")) + assert sorted((b.file_offset, b.nbytes) for b in buffers.values()) == sorted([ + (gg, 4 * ALIGN), # a and b on page 0, c on pages 1 to 3: one run of touched pages + (gg + 6 * ALIGN, ALIGN), # e and q3 on page 6; d's page 4 and the empty page 5 are not mapped + (de, ALIGN), (de + 4 * ALIGN, ALIGN), # n0, then n1 and n2: hc's pages 1 to 3 between them are not mapped + (mt, ALIGN), (mx, 3 * ALIGN)]) + assert mapped(buffers) == set().union(*(pages(src.entries[n].offset, src.entries[n].nbytes) for n in BOUND)) + hc = src.entries["dense/hc.weight"] + assert not pages(hc.offset, hc.nbytes, whole=True) & mapped(buffers) + + +def test_no_window_reaches_the_files_last_partial_page(tmp_path): + src = BasaltSource(write(tmp_path)) + buffers, bound = plan(src, "gguf/pre.weight") # ends on the file's last whole page + (w,) = buffers.values() + assert w.file_offset + w.nbytes == src.file_bytes - src.file_bytes % ALIGN + with pytest.raises(ValueError, match="runs past the end of the file"): + plan(src, "gguf/pre.weight", "gguf/tail.weight") + + +def test_window_names_follow_the_file_range(tmp_path): + path = write(tmp_path) + src = BasaltSource(path) + a = plan(src, "gguf/a.weight", "gguf/e.weight")[1] + b = plan(src, "gguf/e.weight", "dense/n0.weight")[1] + c = plan(src, "gguf/e.weight", "gguf/q3.weight")[1] # q3 shares e's page: the same range + d = plan(src, "gguf/a.weight", "gguf/c.weight")[1] # a's page and c's: a longer range, a's start + assert a["gguf/e.weight"][0] == b["gguf/e.weight"][0] == c["gguf/e.weight"][0] == c["gguf/q3.weight"][0] + assert len({a["gguf/a.weight"][0], d["gguf/a.weight"][0], b["dense/n0.weight"][0], a["gguf/e.weight"][0]}) == 4 + assert plan(src, "gguf/a.weight", "gguf/e.weight") == plan(BasaltSource(path), "gguf/a.weight", "gguf/e.weight") + (tmp_path / "link.basalt").symlink_to(path) # the resolved path names the window + assert plan(BasaltSource(tmp_path / "link.basalt"), "gguf/e.weight")[1] == plan(src, "gguf/e.weight")[1] + other = write(tmp_path, name="other.basalt") # the same bytes in another file + assert plan(BasaltSource(other), "gguf/e.weight")[1]["gguf/e.weight"][0] != a["gguf/e.weight"][0] + + +def test_copy_mode_binds_an_exact_buffer_per_tensor(tmp_path): + path = write(tmp_path) + src, data = BasaltSource(path), path.read_bytes() + buffers, bound = plan(BasaltSource(path, copy=True), *BOUND) + assert len(buffers) == len(BOUND) + for n in BOUND: + e, (name, off) = src.entries[n], bound[n] + assert name.startswith("basalt.copy.") and off == 0 + assert buffers[name] == BufferSpec(e.nbytes, data[e.offset: e.offset + e.nbytes], "weights") + with pytest.raises(ValueError, match="runs past the end of the file"): + plan(BasaltSource(path, copy=True), "gguf/tail.weight") + + +def test_copy_mode_reads_the_file_the_windows_map(tmp_path): + """A source over ``b`` whose tables come from ``a``, a file of the same size that differs only inside e: the copy + mode serves ``b``'s bytes, as the windows do, and refuses a ``b`` that ends inside a tensor.""" + a = write(tmp_path, name="a.basalt") + e = BasaltSource(a).entries["gguf/e.weight"] + data = bytearray(a.read_bytes()) + data[e.offset: e.offset + e.nbytes] = bytes(255 - x for x in data[e.offset: e.offset + e.nbytes]) + b = tmp_path / "b.basalt" + b.write_bytes(bytes(data)) + buffers, bound = plan(BasaltSource(b, BasaltFile(a), copy=True), "gguf/e.weight") + assert buffers[bound["gguf/e.weight"][0]].init == bytes(data[e.offset: e.offset + e.nbytes]) + b.write_bytes(bytes(data[: e.offset + e.nbytes - 1])) + with pytest.raises(ValueError, match="ends inside 'gguf/e.weight' \\(255 of its 256 bytes\\)"): + plan(BasaltSource(b, BasaltFile(a), copy=True), "gguf/e.weight") + + +@pytest.mark.parametrize("name, why", [ + ("dense/g.weight", "its bytes are in gguf: bind gguf/g.weight"), + ("dense/p.weight", "kind 1 has no ggml type to declare"), + ("dense/k0.weight", "kind 0 has no ggml type to declare"), + ("dense/s.weight", "its row gives 256 source bytes but a 128-byte slot"), + ("dense/m.weight", r"192 bytes are not f32 \[64\]"), + ("gguf/x.weight", "ggml type 99 has no format here"), + ("gguf/z.weight", "it holds no bytes"), + ("mtp/odd.weight", "mtp kind 'f64' has no format here")]) +def test_refuses_an_entry_basalt_does_not_ship_as_stored(tmp_path, name, why): + src = BasaltSource(write(tmp_path)) + g = Graph("step") + value(g, src, "gguf/a.weight") + basalt_windows(src, g.values.values()) + g.const(name, (64,), DType.F32) + with pytest.raises(ValueError, match=why): + basalt_windows(src, g.values.values()) + + +@pytest.mark.parametrize("name", ["dense/blk.0.hc_attn_down.weight", "dense/blk.3.hc_ffn_up.weight", + "gguf/output_hc_up.weight", "mtp/hyper_connection.input_mix_weight_attn"]) +def test_refuses_a_hyper_connection_matrix_basalt_holds_only_as_8_bit_copies(tmp_path, name): + """basalt's kernels read the hyper-connection down/up matrices only through their 8-bit copies, which its load + quantizes from the stored form and then drops (generate.cpp:2233-2244, mtp.cpp:215-218), so a step kernel must not + bind the stored bytes.""" + path = write(tmp_path, gguf={**GGUF, "output_hc_up.weight": (0, [16], 112640)}, + dense=DENSE + ["blk.0.hc_attn_down.weight 0 4 67072 256 67328 256 64 2 0 0 1 0 0 0 0 0 0 0", + "blk.3.hc_ffn_up.weight 0 4 67328 256 67584 256 64 2 0 0 1 0 0 0 0 0 0 0", + "blk.0.hc_attn_scale.weight 0 2 67584 256 67840 256 64 0 0 0 1 0 0 0 0 0 0 0"], + mtp=MTP + b"hyper_connection.input_mix_weight_attn bf16 2 64 1280 256\n" + b"hyper_connection.output_weight bf16 2 64 1536 256\n") + src = BasaltSource(path) + assert src.refused[name] == HC8 and name not in src.entries + assert {"dense/blk.0.hc_attn_scale.weight", "mtp/hyper_connection.output_weight"} <= set(src.entries) + g = Graph("step") + g.const(name, (64,), DType.F32) + with pytest.raises(ValueError, match="only through its 8-bit copy"): + basalt_windows(src, g.values.values()) + + +def test_refuses_a_row_its_block_size_does_not_divide_alone(tmp_path): + """A Q8_0 tensor of 48 columns (its blocks hold 32) is refused by itself; every other entry stays bindable.""" + src = BasaltSource(write(tmp_path, gguf={**GGUF, "u.weight": (8, [48, 1], 112640, 51)})) + assert src.refused["gguf/u.weight"] == "q8_0: a row of 48 values is not whole blocks of 32" and "gguf/u.weight" in src + assert set(BOUND) <= set(src.entries) + + +def test_refuses_a_shape_whose_size_wraps_64_bits(tmp_path): + """(274177 * 67280421310721) = 2^64 + 1, so a 64-bit product of the leading dimensions reads 1 and this header's + 64 bytes would pass for an F32 [274177, 67280421310721, 16]; the exact product refuses it.""" + src = BasaltSource(write(tmp_path, gguf={**GGUF, "w.weight": (0, [16, 67280421310721, 274177], 112640)})) + assert src.refused["gguf/w.weight"].endswith("64 bytes do not match type 0 and shape [16, 67280421310721, 274177]") + + +@pytest.mark.parametrize("declare, why", [ + (lambda g: g.weight("gguf/a.weight", (4, 96), "q8_0"), r"is q8_0 \[4, 64\]; the graph declares q8_0 \[4, 96\]"), + (lambda g: g.weight("gguf/a.weight", (4, 64), "q4_0"), r"is q8_0 \[4, 64\]; the graph declares q4_0 \[4, 64\]"), + (lambda g: g.const("dense/n0.weight", (64,), DType.F16), r"is f32 \[64\]; the graph declares f16 \[64\]"), + (lambda g: g.const("dense/n1.weight", (128,), DType.F16), r"is f16 \[2, 64\]; the graph declares f16 \[128\]"), + (lambda g: g.weight("mtp/experts", (33768,), "q2_0"), r"is u8 \[33768\]; the graph declares q2_0 \[33768\]")]) +def test_refuses_a_value_that_does_not_declare_its_entry(tmp_path, declare, why): + src = BasaltSource(write(tmp_path)) + g = Graph("step") + value(g, src, "gguf/e.weight") + declare(g) + with pytest.raises(ValueError, match=why): + basalt_windows(src, g.values.values()) + + +def test_refuses_an_entry_off_a_16_byte_boundary(tmp_path): + src = BasaltSource(write(tmp_path)) + plan(src, "gguf/a.weight", "gguf/e.weight") + t, ne, off = GGUF["e.weight"] + moved = BasaltSource(write(tmp_path, gguf={**GGUF, "e.weight": (t, ne, off + 8)}, name="moved.basalt")) + with pytest.raises(ValueError, match="not a multiple of 16 bytes"): + plan(moved, "gguf/a.weight", "gguf/e.weight") + + +def test_refuses_two_entries_of_one_name(tmp_path): + BasaltSource(write(tmp_path)) + with pytest.raises(ValueError, match="two entries are named 'dense/n1.weight'"): + BasaltSource(write(tmp_path, dense=[r.replace("n2.weight", "n1.weight") for r in DENSE], name="twice.basalt")) + + +def test_windows_hold_at_most_two_gib(tmp_path): + """Entries far larger than the file: the planner reads offsets and sizes, never the bytes.""" + src = BasaltSource(write(tmp_path)) + G = 1 << 30 + src.file_bytes = 16 * G + src.entries = {n: BasaltEntry(n, off, nb, None, (nb,)) for n, off, nb in [ + ("big/a", 0, G), ("big/b", G, G), # two adjacent GiB: one window of exactly WINDOW_BYTES + ("big/c", 2 * G, 16), # the next page: one more would pass it, so a new window + ("big/d", 3 * G, G + G // 2), ("big/e", 4 * G + G // 2, G // 2 + 1), # adjacent, 2 GiB and a page together + ("big/f", 8 * G, 2 * G + 1)]} # alone more than a window holds + buffers, bound = plan(src, "big/a", "big/b", "big/c", "big/d", "big/e") + assert sorted((b.file_offset, b.nbytes) for b in buffers.values()) == [ + (0, WINDOW_BYTES), (2 * G, ALIGN), (3 * G, G + G // 2), (4 * G + G // 2, G // 2 + ALIGN)] + assert {n: off for n, (_, off) in bound.items()} == {"big/a": 0, "big/b": G, "big/c": 0, "big/d": 0, "big/e": 0} + with pytest.raises(ValueError, match=f"spans {2 * G + ALIGN} bytes of pages; a window holds at most {WINDOW_BYTES}"): + plan(src, "big/a", "big/f") + + +def _pack(directory, name): + """A one-entry pack: an F32 [16] aux entry named ``name`` in a one-page weights.pack.""" + directory.mkdir() + (directory / "weights.pack").write_bytes(np.arange(ALIGN // 4, dtype="to_float == nullptr) return -1; + t->to_float(x, y, k); + return 0; +} +extern "C" int basalt_rows(int type, const uint8_t* x, float* y, int64_t k) { + using namespace basalt; + void (*f)(const uint8_t*, float*) = nullptr; + int64_t qk = 0, bs = 0; + switch (type) { + case 0: dequantize_f32(x, y, (int) k); return 0; + case 1: dequantize_f16(x, y, (int) k); return 0; + case 30: dequantize_bf16(x, y, (int) k); return 0; + case 42: f = dequantize_q2_0; qk = 64; bs = 18; break; + case 2: f = dequantize_q4_0; qk = 32; bs = 18; break; + case 6: f = dequantize_q5_0; qk = 32; bs = 22; break; + case 8: f = dequantize_q8_0; qk = 32; bs = 34; break; + case 11: f = dequantize_q3_K; qk = 256; bs = 110; break; + case 12: f = dequantize_q4_K; qk = 256; bs = 144; break; + case 13: f = dequantize_q5_K; qk = 256; bs = 176; break; + case 14: f = dequantize_q6_K; qk = 256; bs = 210; break; + case 20: f = dequantize_iq4_nl; qk = 32; bs = 18; break; + case 23: f = dequantize_iq4_xs; qk = 256; bs = 136; break; + default: return -1; + } + for (int64_t i = 0; i < k / qk; ++i) f(x + i * bs, y + i * qk); + return 0; +} +""" + + +@pytest.fixture(scope="module") +def basalt_references(tmp_path_factory): + """basalt's two CPU references, compiled from the checkout at $BASALT_SRC (as basalt builds them: -O2).""" + src = os.environ.get("BASALT_SRC") + cc, cxx = shutil.which("cc"), shutil.which("c++") + if not src or not cc or not cxx: + pytest.skip("set BASALT_SRC to a basalt checkout (and have cc / c++) to compare with its compiled references") + out = tmp_path_factory.mktemp("basalt") + (out / "driver.cpp").write_text(DRIVER) + inc = f"-I{Path(src) / 'include'}" + subprocess.run([cc, "-O2", "-fPIC", inc, "-c", str(Path(src) / "src/kernels/cpu/ggml/ggml_quants.c"), + "-o", str(out / "ggml_quants.o")], check=True) + subprocess.run([cxx, "-std=c++17", "-O2", "-fPIC", "-shared", inc, str(out / "driver.cpp"), str(out / "ggml_quants.o"), + "-o", str(out / "libbasalt_ref.so")], check=True) + lib = ctypes.CDLL(str(out / "libbasalt_ref.so")) + for fn in (lib.ggml_rows, lib.basalt_rows): + fn.argtypes, fn.restype = [ctypes.c_int, ctypes.c_void_p, ctypes.c_void_p, ctypes.c_int64], ctypes.c_int + return lib + + +def assert_matches_basalt(lib, type_id, rows, k): + """The oracle against both of basalt's references (basalt's ggml table lacks F32, F16, Q4_0 and BF16).""" + rows = np.ascontiguousarray(rows, dtype=np.uint8) + ours = ggml_dequantize(type_id, rows, (rows.shape[0], k)).reshape(-1) + for fn in (lib.ggml_rows, lib.basalt_rows): + y = np.full(ours.size, np.nan, np.float32) + if fn(type_id, rows.ctypes.data, y.ctypes.data, y.size): + assert fn is lib.ggml_rows and type_id in (0, 1, 2, 30) + continue + assert np.array_equal(y.view(np.uint32), ours.view(np.uint32)) + + +@pytest.mark.parametrize("type_id", sorted(GGML_TYPES), ids=lambda t: GGML_TYPES[t][0]) +def test_synthetic_blocks_match_basalts_compiled_references(basalt_references, type_id): + assert_matches_basalt(basalt_references, type_id, *synthetic(type_id, 2, 16, seed=100 + type_id)) diff --git a/tests/kernels/basalt_cpu_emu.py b/tests/kernels/basalt_cpu_emu.py new file mode 100644 index 00000000..265e474c --- /dev/null +++ b/tests/kernels/basalt_cpu_emu.py @@ -0,0 +1,220 @@ +# SPDX-License-Identifier: MIT +# Copyright (c) 2023-2026 The ggml authors +# Copyright (c) 2026 Jesús Gulfo +# adapted from basalt (jesdga95/basalt) src/kernels/cpu/expert.cpp:143-148, :336-370, :503-556 and +# include/basalt/kernels/cpu/expert.hpp:25-61 @ b4c63b55754637f4c72ad53a0f791d425f71eb36 (MIT; third_party/NOTICE), +# which adapt ggml-org/llama.cpp ggml/src/ggml-common.h (block_q2_0) and ggml/src/ggml-quants.c +# (dequantize_row_q2_0's code rule) @ 3cf03257f219afbe7334045ff7c6a06ac68c627d (MIT; third_party/NOTICE). +"""numpy emulation of basalt's two CPU Q2_0 kernels as AVX-512 defines them, for the bit-for-bit tests of the ARM +NEON port (runtime/src/basalt_cpu.cpp). + +A sibling of ``basalt_emu`` rather than part of it: that module is basalt's float32 arithmetic *as nvcc compiles it* +and its ``*_ftz`` forms are CUDA's, while these are AVX-512 semantics on a machine whose MXCSR (x86) and FPCR +(arm64) are at their defaults - round to nearest even, subnormals kept, every exception masked. Same primitives +(``F32``, ``fma32``), different source machine; ``h2f`` is this module's own, because a NaN half's conversion is +the instruction's rule and VCVTPH2PS is not what the GPU side converts with. + +Every step has an exact numpy counterpart, so the infinity and subnormal-scale cases fall out rather than being +special-cased - but a NaN's *bits* do not: numpy inherits this machine's AArch64 rules, which rank a NaN FMA's +operands the other way round from x86's and write 0x7fc00000 where x86 writes the indefinite 0xffc00000. So every +site that can see or make a NaN goes through the ``x86_*`` helpers below, which select by explicit bit test: + +- ``x86_mul``, ``x86_add``, ``x86_sub`` are VMULPS / VADDPS / VSUBSS: SRC1's NaN, else SRC2's, each quieted. +- ``x86_fma`` is VFMADD231PS: first multiplicand, second multiplicand, addend, so a QNaN addend survives an + ``inf * 0`` product where AArch64's FMLA discards it. +- a NaN any of them CREATES is the floating-point indefinite 0xffc00000. +- ``reduce_add_ps`` is GCC 14.3's four-level tree with the operand order of a ONE-token job, which is what the + port pins for every token slot (runtime/src/basalt_cpu.cpp, THE NaN PATH). +- MAXPS is an ordered ``a > b`` select at every node of the explicit reduction trees, which gives its NaN rule + (unordered takes SRC2) and its (+-0, -+0) rule for free; it copies the operand, so payloads survive. +- VCVTTPS2DQ is the range test evaluated *before* any integer cast, so NaN, +-inf and out-of-range values all give + the integer indefinite 0x80000000, which the clamp then turns into -127. +- ``h2f`` is VCVTPH2PS: exact for every finite half including subnormals, and a NaN half's payload shifts left 13 + with the quiet bit forced on. + +``order`` selects the compiler-dependent ``amax``: ``_mm512_reduce_max_ps``'s first two levels pass the high half +as SRC1 under GCC and the low half under Clang, which matters only when a chunk holds a NaN. See +runtime/src/basalt_cpu.cpp's transcription contract. +""" + +from __future__ import annotations + +import numpy as np + +from tests.kernels.basalt_emu import F32, fma32 + +QK, QKA, BB, H, MAXC, MAXT = 64, 32, 18, 2560, 80, 8 +INDEF = -(2 ** 31) # the integer indefinite VCVTTPS2DQ returns (Intel SDM Vol. 1 D.4.2.2) +FP_INDEF = np.uint32(0xFFC00000).view(F32) # the QNaN floating-point indefinite (Intel SDM Vol. 1 4.8.3.7) + + +def is_nan(x): + """A NaN by its bits, so an SNaN counts and no float compare is involved.""" + b = np.ascontiguousarray(x, F32).view(np.uint32) + return ((b & np.uint32(0x7F800000)) == np.uint32(0x7F800000)) & ((b & np.uint32(0x7FFFFF)) != 0) + + +def quiet(x): + """x86 quieting: bit 22 set, payload and sign kept.""" + return (np.ascontiguousarray(x, F32).view(np.uint32) | np.uint32(0x400000)).view(F32) + + +def _x86_nan(computed, *operands): + """``computed`` with x86's NaN selection applied: the first NaN operand in priority order, quieted; otherwise + the indefinite if the operation created a NaN itself (``inf * 0``, ``inf - inf``), otherwise ``computed``.""" + out = np.where(is_nan(computed), FP_INDEF, np.asarray(computed, F32)) + for src in reversed(operands): # reversed, so the highest priority is applied last + src = np.broadcast_to(np.asarray(src, F32), out.shape) + out = np.where(is_nan(src), quiet(src), out) + return np.ascontiguousarray(out, F32) + + +def x86_mul(src1, src2): + """VMULPS: SRC1's NaN, else SRC2's ([S] Intel SDM Vol. 1 Table 4-8).""" + with np.errstate(invalid="ignore", over="ignore"): + return _x86_nan((np.asarray(src1, F32) * np.asarray(src2, F32)).astype(F32), src1, src2) + + +def x86_add(src1, src2): + """VADDPS / VADDSS: SRC1's NaN, else SRC2's.""" + with np.errstate(invalid="ignore", over="ignore"): + return _x86_nan((np.asarray(src1, F32) + np.asarray(src2, F32)).astype(F32), src1, src2) + + +def x86_sub(src1, src2): + """VSUBSS: SRC1's NaN, else SRC2's - a subtraction keeps its written order.""" + with np.errstate(invalid="ignore", over="ignore"): + return _x86_nan((np.asarray(src1, F32) - np.asarray(src2, F32)).astype(F32), src1, src2) + + +def x86_fma(m1, m2, addend): + """VFMADD231PS: the first NaN in the order first multiplicand, second multiplicand, addend ([S] Intel SDM + Vol. 1 Table 14-17), so a QNaN addend outranks an ``inf * 0`` product.""" + with np.errstate(invalid="ignore", over="ignore"): + return _x86_nan(fma32(m1, m2, addend), m1, m2, addend) + + +def h2f(bits): + """VCVTPH2PS of the fp16 block scale. Exact for every finite half, subnormals included; a NaN half keeps its + sign and payload shifted left 13, with the quiet bit forced on, so an SNaN half is quieted.""" + b = np.ascontiguousarray(bits, np.uint16) + with np.errstate(invalid="ignore"): + finite = b.view(np.float16).astype(F32) + m = (b & np.uint16(0x3FF)).astype(np.uint32) + nan = ((b & np.uint16(0x7C00)) == np.uint16(0x7C00)) & (m != 0) + sign = (b >> np.uint16(15)).astype(np.uint32) << np.uint32(31) + return np.where(nan, (sign | np.uint32(0x7FC00000) | (m << np.uint32(13))).view(F32), finite).astype(F32) + + +def maxps(src1, src2): + """MAXPS(SRC1, SRC2) per lane: an ordered ``SRC1 > SRC2`` select, so either operand being NaN, and (+-0, -+0), + give SRC2.""" + with np.errstate(invalid="ignore"): + return np.where(src1 > src2, src1, src2).astype(F32) + + +def reduce_max_ps(v, order="gcc"): + """``_mm512_reduce_max_ps`` over the last axis (16 lanes). The four-level tree of both compilers' headers; only + the first two levels' operand order differs (GCC passes the high half as SRC1, Clang the low half). Clang's + lowering carries ``nnan``, so ``order="clang"`` is the measured realisation of a value its compiler leaves + undefined for a chunk holding a NaN, not a prediction of what every Clang build gives.""" + + def node(hi, lo): + return maxps(hi, lo) if order == "gcc" else maxps(lo, hi) + + u = node(v[..., 8:], v[..., :8]) + t = node(u[..., 4:], u[..., :4]) + p = maxps(t[..., :2], t[..., 2:]) # p0 = maxps(t0, t2), p1 = maxps(t1, t3); both agree + return maxps(p[..., 0], p[..., 1]) + + +def reduce_add_ps(v): + """``_mm512_reduce_add_ps`` over the last axis: the same four-level tree. The grouping is compiler-independent + and a numeric result does not depend on the operand order, but a NaN one does, and GCC reassigns that order + per token slot. This is the order of the real build's ONE-token job, which the port pins for every slot: SRC1 + is the high half at levels 1 and 2, the {2,3,0,1} shuffle at level 3 and lane 0 at level 4.""" + u = x86_add(v[..., 8:], v[..., :8]) + t = x86_add(u[..., 4:], u[..., :4]) + p = x86_add(t[..., 2:], t[..., :2]) + return x86_add(p[..., 0], p[..., 1]) + + +def cvttps_epi32(r): + """``_mm512_cvttps_epi32``: truncation toward zero, and the integer indefinite for a NaN, an infinity or a value + outside int32. The comparison is false for a NaN, so the cast never sees one.""" + rr = np.asarray(r, F32).astype(np.float64) + with np.errstate(invalid="ignore"): + return np.where(np.abs(rr) < 2.0 ** 31, np.trunc(rr), float(INDEF)).astype(np.int64) + + +def act_quant_q8_1(x, order="gcc"): + """``act_quant_q8_1`` (expert.cpp:336-370, the AVX-512 block). Returns (q, scale, sum, hx, nchunks).""" + x = np.ascontiguousarray(x, F32) + nchunks = x.size // QKA + xb = x.reshape(nchunks, QKA) + with np.errstate(invalid="ignore", over="ignore", divide="ignore"): + a = np.abs(xb) # _mm512_and_ps(x, 0x7fffffff): clears the sign bit + amax = reduce_max_ps(maxps(a[:, :16], a[:, 16:]), order) # SRC1 = |x0| + # The two divisions are guarded by ordered compares that a NaN fails, so neither can see or make one. + s = np.where(amax > 0, (amax / F32(127.0)).astype(F32), F32(0)).astype(F32) + inv = np.where(s > 0, (F32(1.0) / s).astype(F32), F32(0)).astype(F32) + t = x86_mul(xb, inv[:, None]) # VMULPS, one rounding + c = np.where(t >= 0, F32(0.5), F32(-0.5)).astype(F32) # ordered: true for +0 and -0, false for NaN + r = x86_add(t, c) # VADDPS, a second rounding + v = np.clip(cvttps_epi32(r), -127, 127).astype(np.int32) + total = v.sum(axis=1, dtype=np.int64).astype(np.int32) # |sum| <= 4064, exact in any order + hx = x86_mul(s, total.astype(F32)) # inert: a vcvtsi2ss result is never a NaN + return v.astype(np.int8).reshape(-1), s, total, hx, nchunks + + +def unpack64_q2_0(block_codes): + """The 64 codes of a block in weight order from its 16 code bytes (last axis): code m is + ``(qs[m // 4] >> (2 * (m % 4))) & 3`` (ggml_quants.c:220-222).""" + m = np.arange(64) + return (np.asarray(block_codes, np.uint8)[..., m // 4] >> (2 * (m % 4)).astype(np.uint8)) & np.uint8(3) + + +def q2_0_rows(w, row_bytes, nblocks, q, scale, hx, rows): + """``q2g_row_multi`` (expert.cpp:503-533) for one token over the given absolute row indices, vectorized over + rows. Reads q[:64 * nblocks], scale[:2 * nblocks] and hx[:2 * nblocks] and nothing else.""" + raw = np.ascontiguousarray(w, np.uint8) + q = np.ascontiguousarray(q, np.int8).astype(np.int32) + scale = np.ascontiguousarray(scale, F32) + hx = np.ascontiguousarray(hx, F32) + base = np.asarray(rows, np.int64) * np.int64(row_bytes) + nr = base.size + acc = np.zeros((nr, 16), F32) + corr = np.zeros((nr, 16), F32) + lanes = np.arange(16) + with np.errstate(invalid="ignore", over="ignore"): + for b0 in range(0, nblocks, 8): + nb = min(8, nblocks - b0) + d = np.zeros((nr, 8), F32) # basalt's sc[8] keeps its zero tail -> h2f(0) = +0.0 + for i in range(nb): + off = base + (b0 + i) * BB + d[:, i] = h2f(raw[off].astype(np.uint16) | (raw[off + 1].astype(np.uint16) << 8)) + dd = d[:, lanes // 2] # _mm512_permutexvar_ps(dup, d8), masked beyond 2 * nb + hxv = np.zeros(16, F32) + hxv[: 2 * nb] = hx[2 * b0: 2 * b0 + 2 * nb] # the masked lanes are never read + corr = x86_fma(dd, hxv[None, :], corr) # site 2: dd, hx, corr + for i in range(nb): + b = b0 + i + off = base + b * BB + 2 + codes = unpack64_q2_0(raw[off[:, None] + np.arange(16)[None, :]]).astype(np.int32) + dot = (codes.reshape(nr, 16, 4) * q[b * QK: (b + 1) * QK].reshape(1, 16, 4)).sum(-1) + p0 = x86_mul(d[:, i], scale[2 * b]) # site 1: RN(d_b * s_{2b}), SRC1 = d, rounded before use + p1 = x86_mul(d[:, i], scale[2 * b + 1]) + p = np.where(lanes[None, :] < 8, p0[:, None], p1[:, None]).astype(F32) + acc = x86_fma(p, dot.astype(F32), acc) # site 3: P, D (never a NaN), acc + return x86_sub(reduce_add_ps(acc), reduce_add_ps(corr)) # sites 4 and 5: SRC1 = the acc sum + + +def q2_0_gguf_rows_multi(w, row_bytes, nblocks, acts, out, r0, r1): + """``q2_0_gguf_rows_multi`` (expert.cpp:544-556): writes out[t][r] for r0 <= r < r1, at the ABSOLUTE row r, and + leaves every other element of ``out`` alone. ``acts`` is a sequence of (q, scale, hx).""" + if r1 <= r0: + return out + rows = np.arange(r0, r1) + for t, (q, scale, hx) in enumerate(acts): + out[t, rows] = q2_0_rows(w, row_bytes, nblocks, q, scale, hx, rows) + return out diff --git a/tests/kernels/basalt_emu.py b/tests/kernels/basalt_emu.py new file mode 100644 index 00000000..eea1feb7 --- /dev/null +++ b/tests/kernels/basalt_emu.py @@ -0,0 +1,793 @@ +# SPDX-License-Identifier: MIT +# Copyright (c) 2023-2026 The ggml authors +# Copyright (c) 2026 Jesús Gulfo +# adapted from basalt (jesdga95/basalt) src/kernels/cuda/native_mmvq.cu, src/kernels/cuda/iq_kernels.cu, +# src/kernels/cuda/native_bf16.cu, src/kernels/cuda/dense_tc.cu, src/kernels/cuda/q5k_head.cu, +# src/kernels/cuda/head_proxy.cuh, src/kernels/cuda/quantize_act.cu, src/kernels/cuda/s2_expert_grouped.cu, +# include/basalt/kernels/q8_1_finite.hpp and include/basalt/kernels/f16_bits.hpp @ +# b4c63b55754637f4c72ad53a0f791d425f71eb36, which adapt ggml-org/llama.cpp ggml/src/ggml-common.h (kvalues_iq4nl), +# ggml/src/ggml-quants.c (get_scale_min_k4), ggml/src/ggml-cuda/quantize.cu and ggml/src/ggml-cuda/mmvf.cu @ +# 3cf03257f219afbe7334045ff7c6a06ac68c627d (MIT; third_party/NOTICE). +"""numpy emulation of basalt's float32 arithmetic as nvcc compiles it (docs/research/basalt-nvcc/matvec.md), for the +bit-for-bit tests of the Metal port. Every float operation rounds once to float32, to nearest even on the float32 +grid, subnormals included (gradual underflow): numpy's float32 add, multiply and divide do; ``fma32`` does by rounding +the exact float64 sum to odd before the float32 cast. The ``*_ftz`` forms flush subnormal inputs, then flush the +rounded result if it is subnormal, as PTX defines ``.ftz`` (``fma.f32``: the exact value "rounded to single +precision"; ``.ftz`` flushes "subnormal inputs and results"): an exact result in [2^-126 - 2^-150, 2^-126) gives +2^-126, the tie 2^-126 - 2^-150 included (2^-126 is the even neighbour).""" + +import numpy as np + +F32 = np.float32 + + +def ftz(x): + """A subnormal becomes the zero of its sign; every other value keeps its bits.""" + x = np.asarray(x, F32) + b = x.view(np.uint32) + return np.where((b & 0x7F800000) == 0, (b & 0x80000000).view(F32), x).astype(F32) + + +def fma32(a, b, c): + """a * b + c rounded once to float32 (to nearest even, on the grid with subnormals). a * b is exact in float64; + the float64 sum is rounded to odd (TwoSum gives its exact error), which a float32 cast then rounds correctly + (53 >= 24 + 2 bits).""" + a, b, c = (np.asarray(v, F32).astype(np.float64) for v in (a, b, c)) + s = a * b + t = s + c + bp = t - s + err = (s - (t - bp)) + (c - bp) + even = (t.view(np.int64) & 1) == 0 + bump = (err != 0) & even & np.isfinite(t) + t = np.where(bump, np.nextafter(t, np.where(err > 0, np.inf, -np.inf)), t) + with np.errstate(over="ignore"): + return t.astype(F32) + + +def add_ftz(a, b): + with np.errstate(over="ignore", invalid="ignore"): + return ftz(ftz(a) + ftz(b)) + + +def mul_ftz(a, b): + with np.errstate(over="ignore", invalid="ignore"): + return ftz(ftz(a) * ftz(b)) + + +def fma_ftz(a, b, c): + """fma.rn.ftz.f32: rounded first, then flushed, so 2^-126 - 2^-151 exactly gives 2^-126 (module docstring).""" + return ftz(fma32(ftz(a), ftz(b), ftz(c))) + + +def max_ftz(a, b): + return np.fmax(ftz(a), ftz(b)) + + +def rcp_ftz(x): + """The correctly rounded reciprocal the port writes where SASS has MUFU.RCP.""" + with np.errstate(divide="ignore", over="ignore"): + return ftz(F32(1.0) / ftz(x)) + + +def roundf(x): + """CUDA's roundf: half away from zero (trunc of |x| + 0.5 rounded toward zero, which is exact here).""" + x = np.asarray(x, F32).astype(np.float64) + return np.trunc(x + np.copysign(0.5, x)).astype(F32) + + +def half_bits(x): + """float32 to fp16 bits, round to nearest even (CUDA's __float2half, Metal's half()); a NaN's bits are numpy's.""" + with np.errstate(over="ignore"): + return np.asarray(x, F32).astype(np.float16).view(np.uint16) + + +def cuda_half_bits(x): + """half_bits with a NaN as sm_120's conversion stores it, 0x7fff (docs/research/basalt-nvcc/nan.md).""" + return np.where(np.isnan(np.asarray(x, F32)), np.uint16(0x7FFF), half_bits(x)).astype(np.uint16) + + +def h2f(bits): + with np.errstate(invalid="ignore"): # NaN patterns stay NaN + return np.asarray(bits, np.uint16).view(np.float16).astype(F32) + + +# ---- the q8_1 quantizers (matvec.md sections 1 and 3) ------------------------------------------------------------- + +RCP127 = np.uint32(0x3C010204).view(F32) # fl(1/127): ptxas's multiply for the native amax / 127 + + +def butterfly(v, op): + """basalt's XOR butterfly over the 32 lanes of each row of ``v`` (offsets 16, 8, 4, 2, 1); every lane ends equal.""" + for o in (16, 8, 4, 2, 1): + v = op(v, v[:, np.arange(32) ^ o]) + return v[:, 0] + + +def q8_1_finite(v): + v = np.asarray(v, F32) + return np.where(np.abs(v) > F32(65504.0), np.copysign(F32(65504.0), v), v).astype(F32) + + +def q8_1_codes(q, amax): + with np.errstate(invalid="ignore"): + c = np.where(np.isnan(q), 0, np.clip(q, -127, 127)).astype(np.int8) + return np.where((amax == 0)[:, None], np.int8(0), c) + + +def q8_1_pack(d, s, codes): + out = np.zeros((len(d), 36), np.uint8) + out[:, 0:2] = cuda_half_bits(q8_1_finite(d)).view(np.uint8).reshape(-1, 2) + out[:, 2:4] = cuda_half_bits(q8_1_finite(s)).view(np.uint8).reshape(-1, 2) + out[:, 4:] = codes.view(np.uint8) + return out.reshape(-1) + + +def q8_1_native(x): + """native_quantize_q8_1 as nvcc compiles it, with the correctly rounded reciprocal in place of MUFU.RCP.""" + v = np.asarray(x, F32).reshape(-1, 32) + amax = butterfly(ftz(np.abs(v)), max_ftz) + s = butterfly(v, add_ftz) + d = q8_1_finite(mul_ftz(amax, RCP127)) + with np.errstate(invalid="ignore"): + q = roundf(mul_ftz(v, rcp_ftz(d)[:, None])) + return q8_1_pack(d, s, q8_1_codes(q, amax)) + + +def q8_1_ieee(x): + """quantize_q8_1_kernel (IEEE: correctly rounded divisions, subnormals kept), the host formula numpy computes.""" + v = np.asarray(x, F32).reshape(-1, 32) + amax = np.fmax.reduce(np.abs(v), axis=1) # fmaxf drops a NaN operand + s = butterfly(v, np.add) + with np.errstate(divide="ignore", invalid="ignore", over="ignore", under="ignore"): + d = q8_1_finite(amax / F32(127.0)) + q = roundf(v / d[:, None]) + return q8_1_pack(d, s, q8_1_codes(q, amax)) + + +# ---- native_mmvq (matvec.md sections 4-5) ------------------------------------------------------------------------- +# The integer parts are computed from the decoded codes (each value's code, sub-block scale and min as ggml defines +# them), independently of basalt's byte tricks; the float parts follow the sequence nvcc compiles, per thread. + +TRAITS = {2: (32, 2, 64, 18), 6: (32, 2, 64, 22), 8: (32, 4, 32, 34), 20: (32, 2, 64, 18), 11: (256, 16, 8, 110), + 12: (256, 16, 8, 144), 13: (256, 16, 8, 176), 14: (256, 32, 4, 210), 23: (256, 8, 16, 136), 42: (64, 2, 64, 18)} +KVALUES = np.array([-127, -104, -83, -65, -49, -35, -22, -10, 1, 13, 25, 38, 53, 69, 89, 113], np.int64) + + +def kqs_of(type_id, tid): + return {2: 2 * (tid % 2), 6: 2 * (tid % 2), 20: 2 * (tid % 2), 8: 2 * (tid % 4), 11: tid % 16, 12: 2 * (tid % 16), + 13: 2 * (tid % 16), 14: tid % 32, 23: 4 * (tid % 8), 42: tid % 2}[type_id] + + +def _h(b, off): + return h2f(b[..., off].astype(np.uint16) | (b[..., off + 1].astype(np.uint16) << 8)) + + +def _scale_min_k4(sc, sb): + """get_scale_min_k4 on the 12 scale bytes ``sc`` (..., 12) for sub-block indices ``sb`` (broadcast).""" + g = lambda k: np.take_along_axis(sc, np.broadcast_to(k, sc.shape[:-1] + k.shape[-1:]), axis=-1).astype(np.int64) + lo, hi = sb < 4, np.clip(sb, 4, 7) + s = np.where(lo, g(np.clip(sb, 0, 3)) & 63, (g(hi + 4) & 0xF) | ((g(hi - 4) >> 6) << 4)) + m = np.where(lo, g(np.clip(sb, 0, 3) + 4) & 63, (g(hi + 4) >> 4) | ((g(hi) >> 6) << 4)) + return s, m + + +def _dot(codes, a): + return (codes[None] * a).sum(axis=-1) + + +def _contrib(type_id, tmp, blk, kby, kqs, d8, s8, a): + """One block step for every (column, row, thread): ``blk`` (rows, nt, bytes), ``kby`` and ``kqs`` (nt,), the q8_1 + scales d8 / sums s8 (cols, blocks) and codes a (cols, blocks, 32) of the activations.""" + nt = kqs.shape[0] + t = np.arange(nt) + xa = lambda b, pos: a[:, b[:, None], pos][:, None] # (cols, 1, nt, npos) + if type_id in (2, 6, 20, 8): + if type_id == 8: + pos = 4 * kqs[:, None] + np.arange(8) + codes = blk[..., 2:34].view(np.int8).astype(np.int64) + else: + pos = np.concatenate([4 * kqs[:, None] + np.arange(8), 16 + 4 * kqs[:, None] + np.arange(8)], axis=1) + qs = blk[..., 6:22] if type_id == 6 else blk[..., 2:18] + nib = np.concatenate([qs & 15, qs >> 4], axis=-1).astype(np.int64) + if type_id == 6: + qh = blk[..., 2:6].astype(np.int64) + qh = qh[..., 0] | (qh[..., 1] << 8) | (qh[..., 2] << 16) | (qh[..., 3] << 24) + nib = nib | (((qh[..., None] >> np.arange(32)) & 1) << 4) + codes = KVALUES[nib] if type_id == 20 else nib + c = np.take_along_axis(codes, np.broadcast_to(pos, codes.shape[:-1] + pos.shape[-1:]), axis=-1) + sumi = _dot(c, xa(kby, pos)).astype(F32) + d, dx, sx = _h(blk, 0)[None], d8[:, kby][:, None], s8[:, kby][:, None] + if type_id in (8, 20): + return fma_ftz(mul_ftz(d, dx), sumi, tmp) + k = F32(-4.0) if type_id == 2 else F32(-8.0) + return fma_ftz(d, fma_ftz(sumi, dx, mul_ftz(sx, k)), tmp) + if type_id == 42: + qs = blk[..., 2:18].astype(np.int64) + codes = ((qs[..., np.arange(64) // 4] >> (2 * (np.arange(64) % 4))) & 3) - 1 + pos = 32 * kqs[:, None] + np.arange(32) + c = np.take_along_axis(codes, np.broadcast_to(pos, codes.shape[:-1] + pos.shape[-1:]), axis=-1) + b = kby + kqs + sumi = _dot(c, xa(b, np.broadcast_to(np.arange(32), (nt, 32)))).astype(F32) + return fma_ftz(mul_ftz(_h(blk, 0)[None], d8[:, b][:, None]), sumi, tmp) + if type_id == 23: + ib = kqs // 4 + qs = blk[..., 8:136].astype(np.int64) + idx = 16 * ib[:, None] + np.arange(32) % 16 + nib = (np.take_along_axis(qs, np.broadcast_to(idx, qs.shape[:-1] + idx.shape[-1:]), axis=-1) + >> (4 * (np.arange(32) // 16))) & 15 + b = kby + ib + sumi = _dot(KVALUES[nib], xa(b, np.broadcast_to(np.arange(32), (nt, 32)))) + sl = np.take_along_axis(blk[..., 4:8].astype(np.int64), np.broadcast_to((ib // 2)[None, :, None], blk.shape[:-1] + (1,)), axis=-1)[..., 0] + sh = blk[..., 2].astype(np.int64) | (blk[..., 3].astype(np.int64) << 8) + ls = ((sl >> (4 * (ib % 2))) & 15) | (((sh >> (2 * ib)) & 3) << 4) + sumi = (sumi * (ls - 32)[None]).astype(F32) + return fma_ftz(mul_ftz(_h(blk, 0)[None], d8[:, b][:, None]), sumi, tmp) + if type_id in (12, 13): + t16 = kqs // 2 + ch, mm = t16 // 4, t16 % 4 + pos = np.concatenate([4 * mm[:, None] + np.arange(4), 16 + 4 * mm[:, None] + np.arange(4)], axis=1) # (nt, 8) + qs0 = 48 if type_id == 13 else 16 + sc = blk[..., 4:16] + sumf_d = sumf_m = np.zeros(tmp.shape, F32) + for i in range(2): + sb = 2 * ch + i + qidx = qs0 + 32 * ch[:, None] + pos + q = np.take_along_axis(blk, np.broadcast_to(qidx, blk.shape[:-1] + qidx.shape[-1:]), axis=-1).astype(np.int64) + code = (q >> (4 * i)) & 15 + if type_id == 13: + h = np.take_along_axis(blk, np.broadcast_to(16 + pos, blk.shape[:-1] + pos.shape[-1:]), axis=-1).astype(np.int64) + code = code | (((h >> sb[:, None]) & 1) << 4) + b = kby + sb + av = xa(b, pos) + dot1, dot2 = _dot(code, av), av.sum(axis=-1) + s, m = _scale_min_k4(sc, np.broadcast_to(sb[None, :, None], sc.shape[:-1] + (1,))) + dx = d8[:, b][:, None] + sumf_d = fma_ftz(dx, (dot1 * s[None, ..., 0]).astype(F32), sumf_d) + sumf_m = fma_ftz(dx, (dot2 * m[None, ..., 0]).astype(F32), sumf_m) + return add_ftz(tmp, fma_ftz(_h(blk, 0)[None], sumf_d, -mul_ftz(_h(blk, 2)[None], sumf_m))) + if type_id == 11: + iqs = kqs + h, pos = iqs // 8, 4 * (iqs % 8)[:, None] + np.arange(4) + sumf = np.zeros(tmp.shape, F32) + sc = blk[..., 96:108].astype(np.int64) + for i in range(4): + q = np.take_along_axis(blk, np.broadcast_to(32 + 32 * h[:, None] + pos, blk.shape[:-1] + (4,)), axis=-1).astype(np.int64) + hm = np.take_along_axis(blk, np.broadcast_to(pos, blk.shape[:-1] + (4,)), axis=-1).astype(np.int64) + code = ((q >> (2 * i)) & 3) - np.where((hm >> (4 * h[:, None] + i)) & 1, 0, 4) + isc = 8 * h + 2 * i + (iqs % 8) // 4 + g = lambda k: np.take_along_axis(sc, np.broadcast_to(k[None, :, None], sc.shape[:-1] + (1,)), axis=-1)[..., 0] + s = (((g(isc % 8) >> (4 * (isc // 8))) & 15) | (((g(8 + isc % 4) >> (2 * (isc // 4))) & 3) << 4)) - 32 + b = kby + 4 * h + i + sumf = fma_ftz(d8[:, b][:, None], (_dot(code, xa(b, pos)) * s[None]).astype(F32), sumf) + return fma_ftz(_h(blk, 108)[None], sumf, tmp) + if type_id == 14: + iqs = kqs + h, l = iqs // 16, 4 * (iqs % 16)[:, None] + np.arange(4) + sumf = np.zeros(tmp.shape, F32) + for i in range(2): + ql = np.take_along_axis(blk, np.broadcast_to(64 * h[:, None] + l, blk.shape[:-1] + (4,)), axis=-1).astype(np.int64) + qh = np.take_along_axis(blk, np.broadcast_to(128 + 32 * h[:, None] + l % 32, blk.shape[:-1] + (4,)), axis=-1).astype(np.int64) + code = (((ql >> (4 * i)) & 15) | (((qh >> (2 * (l // 32) + 4 * i)) & 3) << 4)) - 32 + sidx = 192 + 8 * h + 4 * i + (iqs % 16) // 4 + s = np.take_along_axis(blk, np.broadcast_to(sidx[None, :, None], blk.shape[:-1] + (1,)), axis=-1)[..., 0].view(np.int8).astype(np.int64) + b = kby + 4 * h + 2 * i + (iqs % 16) // 8 + sumf = fma_ftz(d8[:, b][:, None], (_dot(code, xa(b, l % 32)) * s[None]).astype(F32), sumf) + return fma_ftz(_h(blk, 208)[None], sumf, tmp) + raise ValueError(type_id) + + +def mmvq(type_id, w, xq, n_in, n_out, ncols, nw=4, row_chunk=64): + """native_mmvq's output (ncols, n_out) for GGUF rows ``w`` (n_out, row bytes) and q8_1 bytes ``xq``, in basalt's + thread mapping with ``nw`` SIMD-groups (4: the one-column and exact layouts; 2: the upstream layout above 4 + columns): per thread the blocks kbx = tid / T + k * BPI', then SIMD-group order and the XOR butterfly.""" + div, T, bpi, bb = TRAITS[type_id] + nb = n_in // div + blocks = np.asarray(w, np.uint8).reshape(n_out, nb, bb) + xb = np.asarray(xq, np.uint8).reshape(ncols, n_in // 32, 36) + d8, s8, a = _h(xb, 0), _h(xb, 2), xb[..., 4:].view(np.int8).astype(np.int64) + nt, bpi_l = 32 * nw, bpi * nw // 4 + tid = np.arange(nt) + kqs, kby_per_block = kqs_of(type_id, tid), div // 32 + out = np.zeros((ncols, n_out), F32) + for r0 in range(0, n_out, row_chunk): + rows = blocks[r0: r0 + row_chunk] + tmp = np.zeros((ncols, len(rows), nt), F32) + for k in range(-(-nb // bpi_l) + 1): + kbx = tid // T + k * bpi_l + valid = kbx < nb + if not valid.any(): + break + kb = np.minimum(kbx, nb - 1) + new = _contrib(type_id, tmp, rows[:, kb], kb * kby_per_block, kqs, d8, s8, a) + tmp = np.where(valid[None, None], new, tmp) + t = tmp[..., :32] + for sgi in range(1, nw): + t = add_ftz(t, tmp[..., 32 * sgi: 32 * sgi + 32]) + out[:, r0: r0 + row_chunk] = butterfly(t.reshape(-1, 32), add_ftz).reshape(ncols, len(rows)) + return out + + +# ---- the routed experts (docs/research/basalt-nvcc/experts.md) ---------------------------------------------------- +# iq_kernels.cu builds with nvcc's IEEE defaults: no flush; numpy's float32 operations keep subnormals as CUDA does. + +def q2_0_dots(rows, n, xq): + """Q2_0 rows (R rows of ``n`` values, GGUF blocks) against q8_1 rows ``xq`` (E rows of n / 32 blocks): (E, R), in + the order basalt's row_dot_multi sums (experts.md sections 1 and 3): call k (Q2_0 block k / 2, half k % 2, q8_1 + block k) on lane k % 32, s = fma(fl(d2 * d8), f(sumi), s) over the lane's calls in ascending k from +0, then the + 32-lane butterfly of plain adds. gu2's rows2 and the down kernel's 16-lane tree give the same bits.""" + rows = np.asarray(rows, np.uint8).reshape(-1, n // 64, 18) + nr, nk = rows.shape[0], n // 32 + qs = rows[..., 2:18].astype(np.int64) + codes = ((qs[..., np.arange(64) // 4] >> (2 * (np.arange(64) % 4))) & 3) - 1 # (R, n / 64, 64): code - 1 + xb = np.asarray(xq, np.uint8).reshape(-1, nk, 36) + a = xb[..., 4:].view(np.int8).astype(np.float64) # (E, K, 32) + # exact integer dots (|sumi| <= 32 * 2 * 127), per call: (K, R, 32) @ (K, 32, E) + sumi = np.matmul(codes.reshape(nr, nk, 32).transpose(1, 0, 2).astype(np.float64), a.transpose(1, 2, 0)) + d = _h(rows, 0)[:, np.arange(nk) // 2][None] * _h(xb, 0)[:, None, :] # (E, R, K): exact products + f = sumi.transpose(2, 1, 0).astype(F32) + s = np.zeros(d.shape[:2] + (32,), F32) + for k0 in range(0, nk, 32): + ks = np.arange(k0, min(k0 + 32, nk)) + s[..., ks - k0] = fma32(d[..., ks], f[..., ks], s[..., ks - k0]) + for o in (16, 8, 4, 2, 1): + s = s + s[..., np.arange(32) ^ o] + return s[..., 0] + + +def swiglu_q8_1(gate, up, e): + """The experts' SwiGLU + q8_1 (experts.md section 2): t = fl(1 + e), s = fl(g / t) correctly rounded, + h = fl(s * up) with IEEE subnormals, then the IEEE quantizer. ``e`` is __expf(-g), taken from the GPU's expf_neg + (MUFU.EX2 and fast::exp2 have no bit-exact host model).""" + g, up, e = (np.asarray(v, F32) for v in (gate, up, e)) + with np.errstate(over="ignore", under="ignore", invalid="ignore", divide="ignore"): + h = (g / (F32(1.0) + e)) * up + return q8_1_ieee(h) + + +# ---- the drafter's experts (docs/research/basalt-nvcc/s2_experts.md) ---------------------------------------------- +# quantize_act.cu and s2_expert_grouped.cu build with nvcc's IEEE defaults: no flush, as numpy's float32 operations. + +def f16_from_f32(x): + """f16_bits.hpp:36-65's f16_from_f32, transcribed in integer operations: round to nearest even, a finite overflow + to infinity, fp16 subnormals kept, a NaN to sign | 0x7E00.""" + xb = np.asarray(x, F32).view(np.uint32).astype(np.int64) + sign, rawexp, man = (xb >> 16) & 0x8000, (xb >> 23) & 0xFF, xb & 0x7FFFFF + exp = rawexp - 127 + 15 + sh = np.clip(14 - exp, 1, 24) + mm = man | 0x800000 + h_sub = (mm >> sh) & 0x3FF + rem, half = mm & ((1 << sh) - 1), 1 << (sh - 1) + h_sub = h_sub + ((rem > half) | ((rem == half) & ((h_sub & 1) == 1))) + h_norm = sign | (np.clip(exp, 0, 31) << 10) | (man >> 13) + rem_n = man & 0x1FFF + h_norm = h_norm + ((rem_n > 0x1000) | ((rem_n == 0x1000) & ((h_norm & 1) == 1))) + out = np.where(exp <= 0, np.where(exp < -10, sign, sign | h_sub), h_norm) + out = np.where(exp >= 31, sign | 0x7C00, out) + out = np.where(rawexp == 0xFF, sign | 0x7C00 | np.where(man != 0, 0x200, 0), out) + return out.astype(np.uint16) + + +def q8_0_scaled(x): + """quantize_q8_0_scaled_warp_kernel (s2_experts.md section 1), the host transcription: per 32-value block amax = + fmaxf over |x| (a NaN dropped), s = amax > 0 ? amax / 127 : 0, inv = s > 0 ? 1 / s : 0, t = x * inv, + r = t + (t >= 0 ? 0.5 : -0.5), code (int) r clamped to +-127 (NaN to 0); d = f16_from_f32(s). Returns (34-byte + blocks as bytes, fp32 scales).""" + v = np.asarray(x, F32).reshape(-1, 32) + with np.errstate(divide="ignore", invalid="ignore", over="ignore", under="ignore"): + amax = np.fmax.reduce(np.abs(v), axis=1) + s = np.where(amax > 0, amax / F32(127.0), F32(0.0)).astype(F32) + inv = np.where(s > 0, F32(1.0) / s, F32(0.0)).astype(F32) + t = v * inv[:, None] + r = t + np.where(t >= 0, F32(0.5), F32(-0.5)) + code = np.where(np.isnan(r), 0, np.trunc(np.clip(r, -127, 127))).astype(np.int8) + out = np.zeros((len(v), 34), np.uint8) + out[:, :2] = f16_from_f32(s).view(np.uint8).reshape(-1, 2) + out[:, 2:] = code.view(np.uint8) + return out.reshape(-1), s + + +def s2_dots(codes, scales, xq, xs): + """Q2_0 rows of the drafter's blob against Q8_0 activation rows with fp32 scales, as gu_grouped_t_kernel and + down_grouped_t_kernel sum them (s2_experts.md sections 2 and 5): (E, R) for code rows ``codes`` (R, n / 4 bytes), + their fp16 scale bits ``scales`` (R, n / 64), the activation rows ``xq`` (E, n / 32 blocks of 34 bytes) and their + scales ``xs`` (E, n / 32). Per (row, entry) lane L takes the chunks L, L + 32, ... in order, acc = fma(fl(dw * dx), + f(s - hx), acc) from +0, s - hx the exact sum of (code - 1) * x; then the 32-lane butterfly of IEEE adds.""" + codes = np.asarray(codes, np.uint8) + nr, nk = codes.shape[0], codes.shape[1] // 8 + w = ((codes[:, np.arange(32 * nk) // 4].astype(np.int64) >> (2 * (np.arange(32 * nk) % 4))) & 3) - 1 + xb = np.asarray(xq, np.uint8).reshape(-1, nk, 34) + a = xb[..., 2:].view(np.int8).astype(np.float64) # (E, K, 32) + n = np.einsum("rkv,ekv->erk", w.reshape(nr, nk, 32).astype(np.float64), a).astype(F32) # exact integers + dw = h2f(np.asarray(scales, np.uint16))[:, np.arange(nk) // 2] # (R, K) + with np.errstate(over="ignore", under="ignore", invalid="ignore"): + p = dw[None] * np.asarray(xs, F32).reshape(-1, nk)[:, None, :] # (E, R, K): fl(dw * dx) + acc = np.zeros(n.shape[:2] + (32,), F32) + for k0 in range(0, nk, 32): + ks = np.arange(k0, min(k0 + 32, nk)) + acc[..., ks - k0] = fma32(p[..., ks], n[..., ks], acc[..., ks - k0]) + with np.errstate(over="ignore", invalid="ignore"): + for o in (16, 8, 4, 2, 1): + acc = acc + acc[..., np.arange(32) ^ o] + return acc[..., 0] + + +def s2_swiglu(g, u, e): + """swiglu_kernel (s2_experts.md section 3): fl(fl(g / fl(1 + e)) * u), IEEE; ``e`` is __expf(-g), taken from the + GPU's expf_neg (MUFU.EX2 and fast::exp2 have no bit-exact host model).""" + g, u, e = (np.asarray(v, F32) for v in (g, u, e)) + with np.errstate(over="ignore", under="ignore", invalid="ignore", divide="ignore"): + return (g / (e + F32(1.0))) * u + + +# ---- the BF16 GEMVs on fp32 activations (docs/research/basalt-nvcc/bf16.md) ----------------------------------------- +# native_bf16.cu builds with --use_fast_math: every FMA and add is .FTZ. + +def bf16_bits(x): + """float32 to bf16 bits, round to nearest even (bf16_bits.hpp's bf16_from_f32 for non-NaN values).""" + b = np.asarray(x, F32).view(np.uint32).astype(np.uint64) + return ((b + ((b >> 16) & 1) + 0x7FFF) >> 16).astype(np.uint16) + + +def mmvf(w, x, block, flush=True): + """bf16_gemv_fp32_mmvf's outputs (n_tok, n_out) for BF16 bits ``w`` (n_out, n_in) and float32 rows ``x`` + (n_tok, n_in) with ``block`` threads (basalt's mmvf_block_size), as bf16.md records it: thread t takes the pairs + t, t + block, ... in order, acc = fma(bf(w[2p]), x[2p], acc) then fma(bf(w[2p + 1]), x[2p + 1], acc) from +0, + all .FTZ; the XOR butterfly per warp; for block > 32 the butterfly again over 32 slots, the warp sums and +0s. + ``flush=False``: the same sequence in IEEE float32 (``fma32`` and plain adds), what the kernel would give without + .FTZ.""" + fma, add = (fma_ftz, add_ftz) if flush else (fma32, np.add) + w = np.asarray(w, np.uint16) + n_out, n_in = w.shape + x = np.asarray(x, F32).reshape(-1, n_in) + wf = (w.astype(np.uint32) << 16).view(F32) + acc = np.zeros((x.shape[0], n_out, block), F32) + pairs = n_in // 2 + for p0 in range(0, pairs, block): + p = np.arange(p0, min(p0 + block, pairs)) + a = fma(wf[None, :, 2 * p], x[:, None, 2 * p], acc[..., p - p0]) + acc[..., p - p0] = fma(wf[None, :, 2 * p + 1], x[:, None, 2 * p + 1], a) + s = butterfly(acc.reshape(-1, 32), add).reshape(x.shape[0], n_out, block // 32) + if block > 32: + slots = np.zeros(s.shape[:2] + (32,), F32) + slots[..., : block // 32] = s + s = butterfly(slots.reshape(-1, 32), add).reshape(x.shape[0], n_out, 1) + return s[..., 0] + + +# ---- dense_tc and dense_tc_pair (docs/research/basalt-nvcc/dense_tc.md) ---------------------------------------------- +# dense_tc.cu builds with nvcc's IEEE defaults: no flush. The integer dots come from the decoded codes (each value's +# code and its block's scales as ggml defines the format), independently of basalt's byte tricks; the float steps +# follow dense_tc.md section 1 per (row, column) and section 2's warp chunks and trees. + +DTC_SB = {11: 110, 12: 144, 13: 176, 14: 210, 23: 136, 42: 72} +DTC_WARPS = {"one": 24, "tile": 8, "pair": 8, "s1": 4, "s2": 8} + + +def _u16(b, off): + return b[..., off].astype(np.int64) | (b[..., off + 1].astype(np.int64) << 8) + + +def dtc_decode(type_id, w, n_in, n_out): + """The codes (n_out, n_in / 32, 32) of every 32-value block and its scale terms, as ggml's formats define them: + Q4_K / Q5_K {"sc", "m"} per block and {"d", "dmin"} per super-block; Q6_K / Q3_K {"s16"} per 16 values and {"d"} + per super-block; IQ4_XS {"ls"} (the scale minus 32) per block and {"d"} per super-block; Q2_0 {"d"} per 64-value + block.""" + nk = n_in // 32 + if type_id == 42: + blk = np.asarray(w, np.uint8).reshape(n_out, n_in // 64, 18) + v = np.arange(64) + codes = ((blk[..., 2 + v // 4].astype(np.int64) >> (2 * (v % 4))) & 3) - 1 + return codes.reshape(n_out, nk, 32), {"d": _h(blk, 0)} + blk = np.asarray(w, np.uint8).reshape(n_out, n_in // 256, DTC_SB[type_id]) + v = np.arange(256) + if type_id in (12, 13): + qs = blk[..., 48:176] if type_id == 13 else blk[..., 16:144] + q = (qs[..., 32 * (v // 64) + v % 32].astype(np.int64) >> (4 * ((v // 32) % 2))) & 15 + if type_id == 13: + q = q | (((blk[..., 16 + v % 32].astype(np.int64) >> (v // 32)) & 1) << 4) + sc = np.broadcast_to(blk[..., None, 4:16], blk.shape[:-1] + (8, 12)) + s, m = _scale_min_k4(sc, np.arange(8)[:, None]) + terms = {"sc": s[..., 0].reshape(n_out, nk), "m": m[..., 0].reshape(n_out, nk), "d": _h(blk, 0), + "dmin": _h(blk, 2)} + elif type_id == 14: + hh, l = v // 128, v % 128 + ql = (blk[..., 64 * hh + l % 64].astype(np.int64) >> (4 * (l // 64))) & 15 + qh = (blk[..., 128 + 32 * hh + l % 32].astype(np.int64) >> (2 * (l // 32))) & 3 + q = (ql | (qh << 4)) - 32 + terms = {"s16": blk[..., 192:208].view(np.int8).astype(np.int64).reshape(n_out, 2 * nk), "d": _h(blk, 208)} + elif type_id == 11: + hh, j, pos = v // 128, (v % 128) // 32, v % 32 + q = (blk[..., 32 + 32 * hh + pos].astype(np.int64) >> (2 * j)) & 3 + hm = (blk[..., pos].astype(np.int64) >> (4 * hh + j)) & 1 + q = q - np.where(hm == 1, 0, 4) + sc = blk[..., 96:108].astype(np.int64) + isc = np.arange(16) + s16 = (((sc[..., isc % 8] >> (4 * (isc // 8))) & 15) | (((sc[..., 8 + isc % 4] >> (2 * (isc // 4))) & 3) << 4)) - 32 + terms = {"s16": s16.reshape(n_out, 2 * nk), "d": _h(blk, 108)} + elif type_id == 23: + b, pos = v // 32, v % 32 + q = KVALUES[(blk[..., 8 + 16 * b + pos % 16].astype(np.int64) >> (4 * (pos // 16))) & 15] + ib = np.arange(8) + sl = (blk[..., 4 + ib // 2].astype(np.int64) >> (4 * (ib % 2))) & 15 + sh = (_u16(blk, 2)[..., None] >> (2 * ib)) & 3 + terms = {"ls": ((sl | (sh << 4)) - 32).reshape(n_out, nk), "d": _h(blk, 0)} + else: + raise ValueError(type_id) + return q.reshape(n_out, nk, 32), terms + + +def dense_tc(type_id, w, xq, n_in, n_out, ncols, order): + """dense_tc's output (ncols, n_out) in summation order ``order`` ("one", "tile", "pair", "s1", "s2") for GGUF rows + ``w`` and q8_1 bytes ``xq`` (at least ncols columns).""" + codes, terms = dtc_decode(type_id, w, n_in, n_out) + nk, nchunk = n_in // 32, n_in // 512 + xb = np.asarray(xq, np.uint8).reshape(-1, nk, 36)[:ncols] + d8, a = _h(xb, 0), xb[..., 4:].view(np.int8).astype(np.int64) # (C, K), (C, K, 32) + if type_id in (14, 11): # the 16-value halves' dots + dots = [np.einsum("rkv,ckv->rck", codes[..., 16 * e: 16 * e + 16], a[..., 16 * e: 16 * e + 16]) for e in (0, 1)] + else: + dot = np.einsum("rkv,ckv->rck", codes, a) + isum = a.sum(axis=-1) # (C, K): the code sums + col = lambda v: np.asarray(v, F32)[:, None] # a row term over the columns + f32 = lambda n: np.asarray(n).astype(F32) + zero = np.zeros((n_out, ncols), F32) + + def half_sb(acc, c, hb): + sb, ks = 2 * c + (hb >> 1), [16 * c + 4 * hb + i for i in range(4)] + if type_id in (12, 13): + for k in ks: + f1 = terms["d"][:, sb] * f32(terms["sc"][:, k]) + f2 = terms["dmin"][:, sb] * f32(terms["m"][:, k]) + inner = fma32(col(f1), f32(dot[:, :, k]), -(col(f2) * f32(isum[None, :, k]))) + acc = fma32(inner, d8[None, :, k], acc) + return acc + if type_id == 42: + for b in (0, 1): + part = zero + for k in ks[2 * b: 2 * b + 2]: + part = fma32(f32(dot[:, :, k]), d8[None, :, k], part) + acc = fma32(col(terms["d"][:, ks[2 * b] // 2]), part, acc) + return acc + part = zero + for k in ks: + if type_id == 23: + ival = dot[:, :, k] * terms["ls"][:, k, None] + else: + ival = terms["s16"][:, 2 * k, None] * dots[0][:, :, k] + terms["s16"][:, 2 * k + 1, None] * dots[1][:, :, k] + part = fma32(f32(ival), d8[None, :, k], part) + return fma32(col(terms["d"][:, sb]), part, acc) + + nw = DTC_WARPS[order] + ws = [] + for wp in range(nw): + acc = zero + for c in range(wp >> 2, nchunk, nw // 4): + acc = half_sb(acc, c, wp & 3) + ws.append(acc) + if order == "one": + h = [] + for q in range(4): + v = ws[q] + for j in range(1, 6): + v = v + ws[4 * j + q] + h.append(v) + out = (h[0] + h[1]) + (h[2] + h[3]) + elif order in ("tile", "pair"): + out = ((ws[0] + ws[4]) + (ws[1] + ws[5])) + ((ws[2] + ws[6]) + (ws[3] + ws[7])) + elif order == "s1": + out = ((ws[0] + ws[1]) + ws[2]) + ws[3] + else: + out = (((ws[0] + ws[1]) + ws[2]) + ws[3]) + (((ws[4] + ws[5]) + ws[6]) + ws[7]) + return out.T.copy() + + +# ---- the Q5_K head's top-1 (docs/research/basalt-nvcc/q5k_head.md section 2) ------------------------------------- +# A Top is (m, idx, s) arrays. m and idx change only through comparisons of logits, so every __expf argument follows +# from the logits; ``expf`` evaluates the kernel's own expf_ftz on an array (MUFU.EX2 has no bit-exact model). + +TOP_NONE = 0x7FFFFFFF + + +def top_take(t, l, row, on, expf): + """Top::take of logit l at row ``row`` where ``on`` (q5k_head.cu:155-164).""" + m, idx, s = t + up = l > m + with np.errstate(invalid="ignore"): + e = expf(np.where(up, add_ftz(m, -l), add_ftz(l, -m))) + s2 = np.where(up, fma_ftz(s, e, F32(1.0)), add_ftz(s, e)) + i2 = np.where(up | ((l == m) & (row < idx)), row, idx) + return np.where(on, np.where(up, l, m), m).astype(F32), np.where(on, i2, idx), np.where(on, s2, s).astype(F32) + + +def top_merge(t, o, expf): + """Top::merge of o into t (q5k_head.cu:165-175), elementwise.""" + (m, idx, s), (om, oidx, os_) = t, o + on = oidx != TOP_NONE + take = (idx == TOP_NONE) | (om > m) + with np.errstate(invalid="ignore"): + e = expf(np.where(on, np.where(take, add_ftz(m, -om), add_ftz(om, -m)), F32(0.0))) + s2 = np.where(take, fma_ftz(s, e, os_), fma_ftz(os_, e, s)) + i2 = np.where(take | ((om == m) & (oidx < idx)), oidx, idx) + return np.where(on & take, om, m).astype(F32), np.where(on, i2, idx), np.where(on, s2, s).astype(F32) + + +def q5k_top1(logits, mapped, blocks, expf): + """q5k_head_top1 from the kernel's logits: SIMD-group k of threadgroup g takes rows 8g + k + 8 blocks i in order, + unmapped rows skipped (:191-219); thread 0 merges SIMD-groups 0..7 (:297-299) into the partial; the merge: thread t + merges partials t, t + 256, ... (:309-317), the XOR butterfly 16..1 over each SIMD-group (:318-324), thread 0 the + SIMD-groups in order (:327-329). Returns (the partials (m, idx, s) per threadgroup, the row, the probability).""" + n = len(logits) + nw = 8 * blocks + t = (np.full(nw, -np.inf, F32), np.full(nw, TOP_NONE, np.int64), np.zeros(nw, F32)) + for r0 in range(0, n, nw): + row = r0 + np.arange(nw) + ok = row < n + rr = np.minimum(row, n - 1) + t = top_take(t, np.asarray(logits, F32)[rr], row, ok & np.asarray(mapped)[rr], expf) + w = [a.reshape(blocks, 8) for a in t] + b = tuple(a[:, 0] for a in w) + for k in range(1, 8): + b = top_merge(b, tuple(a[:, k] for a in w), expf) + part = b + g = (np.full(256, -np.inf, F32), np.full(256, TOP_NONE, np.int64), np.zeros(256, F32)) + for i0 in range(0, blocks, 256): + i = i0 + np.arange(256) + ok = i < blocks + ii = np.minimum(i, blocks - 1) + o = (part[0][ii], np.where(ok, part[1][ii], TOP_NONE), part[2][ii]) + g = top_merge(g, o, expf) + for off in (16, 8, 4, 2, 1): + src = np.arange(256) ^ off + g = top_merge(g, tuple(a[src] for a in g), expf) + f = tuple(a[0:1] for a in g) + for k in range(1, 8): + f = top_merge(f, tuple(a[32 * k: 32 * k + 1] for a in g), expf) + return part, int(f[1][0]), rcp_ftz(f[2])[0] + + +# ---- the 2-bit proxy (q5k_head.md section 4) ------------------------------------------------------------------------ + +PX_RCP15 = np.uint32(0x3F2AAAAB).view(F32) # fl(1 / 1.5): ptxas's multiply for amax / 1.5f + + +def px_tiles(n): + return (n + 31) // 32 + + +def px_level(w, rs): + """level(w, sh) as compiled: floor(FFMA.FTZ(w, rcp(sh), 2)) converted by F2I (NaN to 0, saturating), clamped.""" + with np.errstate(invalid="ignore"): + f = np.floor(fma_ftz(w, rs, F32(2.0))) + return np.where(np.isnan(f), 0, np.clip(f, 0, 3)).astype(np.int64) + + +def px_fit(w): + """fit_group on groups ``w`` (..., 32): (the fp16 scale bits, its value).""" + amax = np.full(w.shape[:-1], F32(1e-9), F32) + for l in range(32): + amax = max_ftz(amax, ftz(np.abs(w[..., l]))) + a15 = mul_ftz(amax, PX_RCP15) + best_s, best_e = a15, np.full(a15.shape, np.inf, F32) + for t in range(6): + s = mul_ftz(a15, fma_ftz(F32(t), F32(-0.1), F32(1.0))) + sh = h2f(half_bits(s)) + lv = px_level(w, rcp_ftz(sh)[..., None]) + with np.errstate(invalid="ignore", over="ignore"): + r = fma_ftz(add_ftz(lv.astype(F32), F32(-1.5)), sh[..., None], -w) + e = np.zeros(a15.shape, F32) + for l in range(32): + e = fma_ftz(r[..., l], r[..., l], e) + better = e < best_e + best_e, best_s = np.where(better, e, best_e), np.where(better, s, best_s) + hs = half_bits(best_s) + return hs, h2f(hs) + + +def q5k_proxy_pack(q5, row0, n, n_cap, proxy=None): + """q5k_proxy_pack_kernel with pack_group: rows row0 .. row0 + n - 1 of the Q5_K rows ``q5`` (1760 bytes + each) into the copy ``proxy`` (uint8 bytes; zeros when None). Returns the copy.""" + out = np.zeros(px_tiles(n_cap) * 40 * 32 * 20, np.uint8) if proxy is None else np.array(proxy, np.uint8) + rows = row0 + np.arange(n) + b = np.asarray(q5, np.uint8).reshape(-1, 1760)[rows].reshape(n, 10, 176)[:, np.arange(80) // 8] # (n, 80, 176) + j = np.arange(80) % 8 + scl = b[..., 4:16].astype(np.int64) + at = lambda k: np.take_along_axis(scl, np.broadcast_to(k[None, :, None], (n, 80, 1)), axis=-1)[..., 0] + lo = j < 4 + sci = np.where(lo, at(np.clip(j, 0, 3)) & 63, (at(np.clip(j, 4, 7) + 4) & 0xF) | ((at(np.clip(j, 4, 7) - 4) >> 6) << 4)) + mi = np.where(lo, at(np.clip(j, 0, 3) + 4) & 63, (at(np.clip(j, 4, 7) + 4) >> 4) | ((at(np.clip(j, 4, 7)) >> 6) << 4)) + d = mul_ftz(_h(b, 0), sci.astype(F32)) + mn = mul_ftz(_h(b, 2), mi.astype(F32)) + l = np.arange(32) + qs = np.take_along_axis(b, np.broadcast_to((48 + 32 * (j // 2))[None, :, None] + l, (n, 80, 32)), axis=-1) + qs = qs.astype(np.int64) + nib = np.where((j & 1)[None, :, None] == 1, qs >> 4, qs & 15) + q = nib | (((b[..., 16:48].astype(np.int64) >> j[None, :, None]) & 1) << 4) + with np.errstate(invalid="ignore", over="ignore"): + w = fma_ftz(d[..., None], q.astype(F32), -mn[..., None]) + hs, sh = px_fit(w) + lv = px_level(w, rcp_ftz(sh)[..., None]) # (n, 80, 32) + sh_bits = (8 * (np.arange(16) % 4) + 2 * (np.arange(16) // 4)).astype(np.uint64) # value 4 ii + bb: bit 8 bb + 2 ii + words = [(lv[..., 16 * c: 16 * c + 16].astype(np.uint64) << sh_bits).sum(axis=-1).astype(np.uint32) for c in (0, 1)] + g = np.arange(80) + slot = ((rows[:, None] >> 5) * 40 + g[None] // 2) * 32 + (rows[:, None] & 31) + h = (g & 1)[None] + u32 = out[: px_tiles(n_cap) * 40 * 32 * 16].view(np.uint32) + u32[slot * 4 + 2 * h] = words[0] + u32[slot * 4 + 2 * h + 1] = words[1] + out[px_tiles(n_cap) * 40 * 32 * 16:].view(np.uint16)[slot * 2 + h] = hs + return out + + + +def q5k_proxy_score(proxy, xq, n_rows, n_cap, map_, tiles, expf): + """px::score_kernel on the tiles ``tiles`` of the copy ``proxy`` (``n_cap`` rows) against one q8_1 column ``xq``: + (cand (tiles, 4, 2) float32 with the rows' bits in [..., 1], part (tiles, 2)). The exponent arguments follow from + the scores; ``expf`` evaluates the kernel's own expf_ftz on them.""" + ntc, tiles = px_tiles(n_cap), np.asarray(tiles) + nt_ = len(tiles) + proxy = np.asarray(proxy, np.uint8) + words = proxy[: ntc * 40 * 32 * 16].view(np.uint32).reshape(ntc, 40, 32, 4)[tiles] # (tile, w4, lane, word) + scw = proxy[ntc * 40 * 32 * 16:].view(np.uint32).reshape(ntc, 40, 32)[tiles] + xb = np.asarray(xq, np.uint8).reshape(80, 36) + d8 = h2f(xb[:, 0].astype(np.uint16) | (xb[:, 1].astype(np.uint16) << 8)) + codes = xb[:, 4:].view(np.int8).astype(np.int64) # (80, 32) + xs = mul_ftz(d8, codes.sum(axis=1).astype(F32)) + shifts = (8 * (np.arange(16) % 4) + 2 * (np.arange(16) // 4)).astype(np.uint32) # value 4 ii + bb of a word + lv = ((words[..., None] >> shifts) & 3).astype(np.int64).reshape(nt_, 40, 32, 2, 32) # (.., h, 16 c + value) + g = 2 * np.arange(40)[:, None] + np.arange(2)[None, :] # group of (w4, h) + P = (lv * codes[g][None, :, None]).sum(axis=-1) # exact, as DP4A + inner = fma_ftz(d8[g][None, :, None], P.astype(F32), -mul_ftz(xs[g], F32(1.5))[None, :, None]) + scale = h2f(np.stack([scw & 0xFFFF, scw >> 16], axis=-1).astype(np.uint16)) + red = [] + for k in range(4): # SIMD-group k: w4 = 10 k + j for j = 0..9, then h = 0, 1 + acc = np.zeros((nt_, 32), F32) + for j in range(10): + for h in range(2): + acc = fma_ftz(scale[:, 10 * k + j, :, h], inner[:, 10 * k + j, :, h], acc) + red.append(acc) + v = add_ftz(add_ftz(add_ftz(red[0], red[1]), red[2]), red[3]) + row = tiles[:, None] * 32 + np.arange(32)[None] + masked = (row >= n_rows) | (np.asarray(map_, np.int64)[np.minimum(row, n_rows - 1)] < 0) + v = np.where(masked, F32(-np.inf), v).astype(F32) + m = butterfly(v, max_ftz) + live = v > -np.inf + with np.errstate(invalid="ignore"): + arg = np.where(live, add_ftz(v, -m[:, None]), F32(0.0)) + e = np.where(live, expf(arg), F32(0.0)).astype(F32) + part = np.stack([m, butterfly(e, add_ftz)], axis=-1) + cand = np.zeros((nt_, 4, 2), F32) + vv, at = v.copy(), np.arange(nt_) + for k in range(4): + bi = np.argmax(vv, axis=1) # the first maximum: ties to the lower row + cand[:, k, 0] = vv[at, bi] + cand[:, k, 1] = (tiles * 32 + bi).astype(np.int32).view(F32) + vv[at, bi] = -np.inf + return cand, part + + +def q5k_proxy_final(cand, part, exact, map_, expf): + """q5k_proxy_final_kernel (collect, the exact rescoring, pick) from the score's ``cand`` (tiles, 4, 2) and ``part`` + (tiles, 2); ``exact``: the head's logits of every row (the kernel rescores the listed rows with the head's own row, + native_mmvq's bits). The list in ascending candidate order, the port's fixed order (q5k_head.md section 4); ``expf`` + evaluates the kernel's expf_ftz. Returns (id, probability, the listed rows).""" + c, pt = np.asarray(cand, F32).reshape(-1, 2), np.asarray(part, F32) + m = np.max(c[:, 0]) + if m == -np.inf: # every row is masked + return (0 if map_[0] < 0 else int(map_[0])), F32(1.0), np.zeros(0, np.int64) + sel = np.flatnonzero((c[:, 0] > -np.inf) & (c[:, 0] >= add_ftz(m, F32(-5.0))))[:64] + rows, lp = c[sel, 1].view(np.int32).astype(np.int64), c[sel, 0] + ex = np.asarray(exact, F32)[rows] + bv = np.max(ex) + bi = int(np.min(rows[ex == bv])) # the largest exact score, the lowest row on ties + live = pt[:, 1] > 0 + et = expf(np.where(live, add_ftz(pt[:, 0], -bv), F32(0.0))) + ed = add_ftz(expf(add_ftz(ex, -bv)), -expf(add_ftz(lp, -bv))) + s = np.zeros(32, F32) # lane L: tiles L, L + 32, ..., then rows L, L + 32 + for t0 in range(0, len(pt), 32): + k = min(32, len(pt) - t0) + s[:k] = np.where(live[t0:t0 + k], fma_ftz(pt[t0:t0 + k, 1], et[t0:t0 + k], s[:k]), s[:k]) + for c0 in range(0, len(rows), 32): + k = min(32, len(rows) - c0) + s[:k] = add_ftz(s[:k], ed[c0:c0 + k]) + total = max_ftz(butterfly(s[None], add_ftz)[0], F32(1.0 if bi in rows else 0.0)) + return int(np.asarray(map_)[bi]), rcp_ftz(total), rows diff --git a/tests/kernels/basalt_gpu.py b/tests/kernels/basalt_gpu.py new file mode 100644 index 00000000..6b3ea600 --- /dev/null +++ b/tests/kernels/basalt_gpu.py @@ -0,0 +1,448 @@ +"""Single-kernel runs of the basalt port (kernels/common/basalt_*.metal) for the GPU tests.""" + +import functools + +import numpy as np + +from monolith import kernels +from monolith.runtime import _native as nt + + +@functools.lru_cache(maxsize=None) +def device(): + return nt.Device() + + +@functools.lru_cache(maxsize=None) +def pipeline(source: str, name: str, macros: tuple = ()): + return nt.Pipeline(nt.Library(device(), source, dict(macros)), name) + + +def run(pso, buffers, params, slot, grid, threads, fill=None): + """Bind ``buffers`` (bytes or byte counts) at 0, 1, ...; ``params`` (if any) at ``slot``; return the buffers' + bytes. ``fill``: the byte every buffer given as a byte count starts as.""" + dev = device() + bufs = [nt.Buffer(dev, b) for b in buffers] + for buf, src in zip(bufs, buffers): + if fill is not None and not isinstance(src, (bytes, bytearray)): + buf.fill(fill) + d = nt.Dispatch().pipeline(pso) + for k, b in enumerate(bufs): + d = d.buffer(k, b) + if params is not None: + d = d.bytes(slot, params) + d = d.grid(grid).threadgroup(threads) + r = nt.Queue(dev).run([d]) + assert not r.error, r.error + return [b.read(0, len(src) if isinstance(src, (bytes, bytearray)) else src) for b, src in zip(bufs, buffers)] + + +def q8_1(x, kind="native", up=None): + """Quantize the float32 vector ``x`` (ncols * n_in values) with ``native_quantize_q8_1`` (kind "native"), + ``quantize_q8_1`` ("ieee") or ``native_swiglu_quantize_q8_1`` ("swiglu", gate ``x`` and ``up``); q8_1 bytes.""" + x = np.ascontiguousarray(x, np.float32) + n = x.size + nbytes = n // 32 * kernels.Q8_1_BLOCK_BYTES + name = {"native": "native_quantize_q8_1", "ieee": "quantize_q8_1", "swiglu": "native_swiglu_quantize_q8_1"}[kind] + pso = pipeline(kernels.basalt_q8_1_source(), name) + ins = [x.tobytes()] + ([np.ascontiguousarray(up, np.float32).tobytes()] if kind == "swiglu" else []) + out = run(pso, ins + [nbytes], kernels.basalt_q8_1_params(n), len(ins) + 1, + -(-n // kernels.Q8_1_THREADS), kernels.Q8_1_THREADS) + return np.frombuffer(out[-1], np.uint8) + + +def mmvq(type_id, w, xq, n_in, n_out, ncols, upstream=False, fill=None): + """``basalt_mmvq`` in basalt's launch for ``ncols`` columns (``upstream``: the negative control's layout), into + an output whose bytes start as ``fill``.""" + macros = kernels.basalt_mmvq_macros(type_id, n_in, ncols, upstream=upstream) + pso = pipeline(kernels.basalt_mmvq_source(), "basalt_mmvq", tuple(sorted(macros.items()))) + grid, threads = kernels.basalt_mmvq_grid(macros, n_out) + out = run(pso, [np.ascontiguousarray(w, np.uint8).tobytes(), np.ascontiguousarray(xq, np.uint8).tobytes(), + 4 * ncols * n_out], kernels.basalt_mmvq_params(n_in, n_out), 3, grid, threads, fill) + return np.frombuffer(out[2], np.float32).reshape(ncols, n_out) + + +def experts(blobs, grp_off, grp_start, ent_tok, ent_dst, xq, n_embd, n_ff, n_out_rows, *, n_groups=None, + cap_groups=None, cap_entries=None, grid_groups=0, gu2=None, sub16=None, out_fill=0xFF, scratch_fill=0x00, + grp_buf=None): + """basalt's ``native_expert_grouped`` for Q2_0 / Q2_0: the gate/up, SwiGLU + q8_1 and down dispatches in order, in + one command buffer. ``blobs``: the expert blobs' bytes, or a list of them (one buffer each); group g's blob starts + ``grp_off[g]`` bytes into buffer ``grp_buf[g]`` (default 0), and the kernels get basalt's grp_ptr, that buffer's GPU + address plus the offset; ``grp_start`` (n_groups + 1 entries), ``ent_tok``, ``ent_dst`` and ``xq`` (q8_1 rows) as + basalt's. The output (``n_out_rows`` rows of n_embd floats) starts as ``out_fill`` bytes, the scratch as + ``scratch_fill``. Returns the gate, up, q8_1 and output buffers' contents.""" + n_groups = len(grp_off) if n_groups is None else n_groups + cap_groups = max(n_groups, 1) if cap_groups is None else cap_groups + cap_entries = max(len(ent_tok), 1) if cap_entries is None else cap_entries + macros = kernels.basalt_expert_macros(n_embd, n_ff, gu2=gu2, sub16=sub16) + key = tuple(sorted(macros.items())) + src = kernels.basalt_experts_source() + pgu, psw, pdn = (pipeline(src, name, key) for name in + ("basalt_expert_gu", "basalt_expert_swiglu_q8_1", "basalt_expert_down")) + ggu, gsw, gdn = kernels.basalt_expert_grids(macros, n_embd, n_ff, cap_groups, cap_entries, grid_groups) + dev = device() + + def arr(a, dt, n): # a plan array, zero-padded to its capacity + v = np.zeros(max(n, len(a), 1), dt) + v[: len(a)] = a + return nt.Buffer(dev, v.tobytes()) + + arenas = blobs if isinstance(blobs, (list, tuple)) else [blobs] + b_blobs = [nt.Buffer(dev, np.ascontiguousarray(a, np.uint8).tobytes()) for a in arenas] + grp_buf = [0] * len(grp_off) if grp_buf is None else grp_buf + b_ptr = arr([b_blobs[i].gpu_address + int(o) for i, o in zip(grp_buf, grp_off)], np.uint64, cap_groups) + b_start = arr(grp_start, np.int32, cap_groups + 1) + b_ng = nt.Buffer(dev, np.int32(n_groups).tobytes()) + b_tok, b_dst = arr(ent_tok, np.int32, cap_entries), arr(ent_dst, np.int32, cap_entries) + b_xq = nt.Buffer(dev, np.ascontiguousarray(xq, np.uint8).tobytes()) + scratch = [nt.Buffer(dev, n) for n in (4 * cap_entries * n_ff, 4 * cap_entries * n_ff, + cap_entries * n_ff // 32 * kernels.Q8_1_BLOCK_BYTES)] + for b in scratch: + b.fill(scratch_fill) + b_gate, b_up, b_hq = scratch + b_out = nt.Buffer(dev, 4 * n_out_rows * n_embd) + b_out.fill(out_fill) + params = kernels.basalt_expert_params(n_embd, n_ff) + d1 = nt.Dispatch().pipeline(pgu) + for k, b in enumerate((b_ptr, b_start, b_ng, b_tok, b_xq, b_gate, b_up), start=1): + d1 = d1.buffer(k, b) + for b in b_blobs: + d1 = d1.use(b) + d1 = d1.bytes(8, params).grid(*ggu).threadgroup(kernels.EXPERT_THREADS) + d2 = nt.Dispatch().pipeline(psw) + for k, b in enumerate((b_gate, b_up, b_start, b_ng, b_hq)): + d2 = d2.buffer(k, b) + d2 = d2.bytes(5, params).grid(gsw).threadgroup(kernels.EXPERT_THREADS) + d3 = nt.Dispatch().pipeline(pdn) + for k, b in enumerate((b_ptr, b_start, b_ng, b_dst, b_hq, b_out), start=1): + d3 = d3.buffer(k, b) + for b in b_blobs: + d3 = d3.use(b) + d3 = d3.bytes(7, params).grid(*gdn).threadgroup(kernels.EXPERT_THREADS) + r = nt.Queue(dev).run([d1, d2, d3]) + assert not r.error, r.error + f32 = lambda b: np.frombuffer(b.read(0, b.nbytes), np.float32) + return {"gate": f32(b_gate).reshape(cap_entries, n_ff), "up": f32(b_up).reshape(cap_entries, n_ff), + "hq": np.frombuffer(b_hq.read(0, b_hq.nbytes), np.uint8), "out": f32(b_out).reshape(n_out_rows, n_embd)} + + +def q8_0_scaled(x, fill=0x5A, src=None): + """``basalt_quantize_q8_0_scaled`` over the float32 vector ``x`` (a multiple of 32 values), into blocks and scales + whose bytes start as ``fill``: (34-byte blocks as bytes, fp32 scales). ``src``: another source of the kernels (the + tests' negative controls).""" + x = np.ascontiguousarray(x, np.float32) + nb = x.size // 32 + pso = pipeline(src or kernels.basalt_s2_experts_source(), "basalt_quantize_q8_0_scaled") + out = run(pso, [x.tobytes(), nb * kernels.Q8_0_BLOCK_BYTES, 4 * nb], kernels.basalt_q8_0_scaled_params(x.size), 3, + kernels.basalt_q8_0_scaled_grid(x.size), kernels.S2_THREADS, fill) + return np.frombuffer(out[1], np.uint8), np.frombuffer(out[2], np.float32) + + +def s2_experts(blob_bufs, grp, grp_start, n_groups, ent_tok, ent_dst, xq, xs, cap_groups, cap_entries, n_out_rows, *, + resident=None, out_fill=0xA5, scratch_fill=0x5A, src=None): + """basalt's ``moe_grouped_s2`` (with ``resident``: ``moe_group_resident`` first) in one command buffer. + ``blob_bufs``: device buffers holding the expert blobs; group g's blob is ``grp[g]`` = (buffer index, byte offset), + and the kernels get basalt's grp_ptr, that buffer's GPU address plus the offset (the table padded to cap_groups + with group 0's, the starts with the last, as basalt's test pads them). ``resident`` = (ids, k_per_tok, buffer + index, byte offset of expert 0): the plan comes from ``basalt_s2_group_resident`` instead, and ``grp``, + ``grp_start``, ``n_groups``, ``ent_tok`` and ``ent_dst`` are ignored. ``xq``: the activation rows (34-byte + blocks), ``xs`` their fp32 scales. The output (``n_out_rows`` rows of 2560 floats) starts as ``out_fill`` bytes, + the scratch (``basalt_s2_scratch``'s size) as ``scratch_fill``. Returns the output and scratch bytes, and the plan + the kernels read. ``src``: another source of the kernels (the tests' negative controls).""" + dev, src = device(), src or kernels.basalt_s2_experts_source() + pgu, psw, pq, pdn = (pipeline(src, n) for n in ("basalt_s2_gu", "basalt_s2_swiglu", "basalt_quantize_q8_0_scaled", + "basalt_s2_down")) + grids, sc = kernels.basalt_s2_grids(cap_groups, cap_entries), kernels.basalt_s2_scratch(cap_entries) + + def arr(a, dt, n, pad=0): + v = np.full(max(n, len(a), 1), pad, dt) + v[: len(a)] = a + return nt.Buffer(dev, v.tobytes()) + + ds = [] + if resident is None: + b_ptr = arr([blob_bufs[i].gpu_address + int(o) for i, o in grp], np.uint64, cap_groups, + blob_bufs[grp[0][0]].gpu_address + int(grp[0][1]) if len(grp) else 0) + b_start = arr(grp_start, np.int32, cap_groups + 1, grp_start[-1]) + b_ng = nt.Buffer(dev, np.int32(n_groups).tobytes()) + b_tok, b_dst = arr(ent_tok, np.int32, cap_entries), arr(ent_dst, np.int32, cap_entries) + else: + ids, k_per_tok, bi, bo = resident + n = len(ids) + b_ids = nt.Buffer(dev, np.asarray(ids, np.int32).tobytes()) + b_ptr, b_start = nt.Buffer(dev, 8 * n), nt.Buffer(dev, 4 * (n + 1)) + b_ng, b_dst, b_tok = nt.Buffer(dev, 16), nt.Buffer(dev, 4 * n), nt.Buffer(dev, 4 * n) + for b in (b_ptr, b_start, b_ng, b_dst, b_tok): + b.fill(0) + d0 = nt.Dispatch().pipeline(pipeline(src, "basalt_s2_group_resident")).buffer(0, b_ids) + d0 = d0.buffer(1, blob_bufs[bi], bo) + for k, b in enumerate((b_ptr, b_start, b_ng, b_dst, b_tok), start=2): + d0 = d0.buffer(k, b) + ds.append(d0.bytes(7, kernels.basalt_s2_resident_params(n, k_per_tok)).grid(1).threadgroup(128)) + b_x = nt.Buffer(dev, np.ascontiguousarray(xq, np.uint8).tobytes()) + b_xs = nt.Buffer(dev, np.ascontiguousarray(xs, np.float32).tobytes()) + b_s, b_out = nt.Buffer(dev, sc["bytes"]), nt.Buffer(dev, 4 * n_out_rows * kernels.S2_H) + b_s.fill(scratch_fill) + b_out.fill(out_fill) + params = kernels.basalt_s2_params(cap_entries) + d1 = nt.Dispatch().pipeline(pgu) + for k, b in enumerate((b_ptr, b_start, b_ng, b_tok, b_x, b_xs, b_s)): + d1 = d1.buffer(k, b) + for b in blob_bufs: + d1 = d1.use(b) + ds.append(d1.bytes(7, params).grid(*grids["gu"]).threadgroup(kernels.S2_THREADS)) + ds.append(nt.Dispatch().pipeline(psw).buffer(0, b_s).bytes(1, params).grid(grids["swiglu"]) + .threadgroup(kernels.S2_THREADS)) + ds.append(nt.Dispatch().pipeline(pq).buffer(0, b_s).buffer(1, b_s, sc["hq"]).buffer(2, b_s, sc["hs"]) + .bytes(3, kernels.basalt_q8_0_scaled_params(cap_entries * kernels.S2_FF)).grid(grids["quant"]) + .threadgroup(kernels.S2_THREADS)) + d4 = nt.Dispatch().pipeline(pdn) + for k, b in enumerate((b_ptr, b_start, b_ng, b_dst)): + d4 = d4.buffer(k, b) + d4 = d4.buffer(4, b_s, sc["hq"]).buffer(5, b_s, sc["hs"]).buffer(6, b_out) + for b in blob_bufs: + d4 = d4.use(b) + ds.append(d4.grid(*grids["down"]).threadgroup(kernels.S2_THREADS)) + r = nt.Queue(dev).run(ds) + assert not r.error, r.error + i32 = lambda b: np.frombuffer(b.read(0, b.nbytes), np.int32) + return {"out": np.frombuffer(b_out.read(0, b_out.nbytes), np.uint32).reshape(n_out_rows, kernels.S2_H), + "scratch": np.frombuffer(b_s.read(0, b_s.nbytes), np.uint8), "grp_ptr": np.frombuffer( + b_ptr.read(0, b_ptr.nbytes), np.uint64), "grp_start": i32(b_start), "n_groups": i32(b_ng), + "ent_dst": i32(b_dst), "ent_tok": i32(b_tok)} + + +def mmvf(w, x, n_in, n_out, n_tok=1, ldx=None, ldy=None, fill=None): + """``basalt_mmvf`` in basalt's launch (``bf16_gemv_fp32_mmvf_multi``; one row with ldy >= n_out: + ``bf16_gemv_fp32_mmvf``) for BF16 bits ``w`` (n_out rows of n_in) and the float32 rows of ``x`` (row k at k * ldx, + (n_tok - 1) * ldx + n_in values); the output, (n_tok - 1) * ldy + n_out floats, starts as ``fill`` bytes.""" + ldx = n_in if ldx is None else ldx + ldy = n_out if ldy is None else ldy + macros = kernels.basalt_mmvf_macros(n_in, n_out, n_tok, ldx, ldy) + pso = pipeline(kernels.basalt_mmvf_source(), "basalt_mmvf", tuple(sorted(macros.items()))) + out = run(pso, [np.ascontiguousarray(x, np.float32).tobytes(), np.ascontiguousarray(w, np.uint16).tobytes(), + 4 * ((n_tok - 1) * ldy + n_out)], kernels.basalt_mmvf_params(n_in, n_out, n_tok, ldx, ldy), 3, + n_out, int(macros["BLOCK"]), fill) + return np.frombuffer(out[2], np.float32) + + +def mmvf_cols(w, x, n_in, n_out, ncols, fill=None): + """basalt's ``bf16_gemv_fp32_mmvf_cols``: ``ncols`` contiguous columns of ``x`` in launches of up to 8 (one command + buffer, x and y bound at each chunk's offset), into an (ncols, n_out) output that starts as ``fill`` bytes.""" + dev = device() + bx = nt.Buffer(dev, np.ascontiguousarray(x, np.float32).tobytes()) + bw = nt.Buffer(dev, np.ascontiguousarray(w, np.uint16).tobytes()) + by = nt.Buffer(dev, 4 * ncols * n_out) + if fill is not None: + by.fill(fill) + ds = [] + for c0, nc in kernels.basalt_mmvf_cols(ncols): + macros = kernels.basalt_mmvf_macros(n_in, n_out, nc) + pso = pipeline(kernels.basalt_mmvf_source(), "basalt_mmvf", tuple(sorted(macros.items()))) + ds.append(nt.Dispatch().pipeline(pso).buffer(0, bx, 4 * c0 * n_in).buffer(1, bw).buffer(2, by, 4 * c0 * n_out) + .bytes(3, kernels.basalt_mmvf_params(n_in, n_out, nc)).grid(n_out).threadgroup(int(macros["BLOCK"]))) + r = nt.Queue(dev).run(ds) + assert not r.error, r.error + return np.frombuffer(by.read(0, by.nbytes), np.float32).reshape(ncols, n_out) + + +def dequant(type_id, raw, n): + """``basalt_dequant_f32``: the ``n`` values (a multiple of 256) of the GGUF blocks ``raw``, as float32.""" + pso = pipeline(kernels.basalt_dequant_source(), "basalt_dequant_f32", + tuple(sorted(kernels.basalt_dequant_macros(type_id).items()))) + out = run(pso, [np.ascontiguousarray(raw, np.uint8).tobytes(), 4 * n], None, 0, n // 256, 32) + return np.frombuffer(out[1], np.float32) + + +def dense_tc(type_id, w, xq, n_in, n_out, widths, variant=None, fill=0xFF): + """``basalt_dense_tc`` in ``variant`` (default: the rule's at 170 multiprocessors), one call per column count T in + ``widths``, in one command buffer with the weights bound once: call T reads the first T columns of ``xq`` (its + buffer holds only those) and writes an output of 8 columns whose bytes start as ``fill``. Returns {T: (8, n_out)}.""" + macros = kernels.basalt_dense_tc_macros(type_id, n_in, n_out, variant) + pso = pipeline(kernels.basalt_dense_tc_source(), "basalt_dense_tc", tuple(sorted(macros.items()))) + grid, threads = kernels.basalt_dense_tc_grid(macros, n_out) + dev, qcol = device(), n_in // 32 * kernels.Q8_1_BLOCK_BYTES + xq = np.ascontiguousarray(xq, np.uint8) + b_w = nt.Buffer(dev, np.ascontiguousarray(w, np.uint8).tobytes()) + ds, outs = [], {} + for t in widths: + b_x, b_y = nt.Buffer(dev, xq[: t * qcol].tobytes()), nt.Buffer(dev, 4 * 8 * n_out) + b_y.fill(fill) + d = nt.Dispatch().pipeline(pso).buffer(0, b_w).buffer(1, b_x).buffer(2, b_y) + ds.append(d.bytes(3, kernels.basalt_dense_tc_params(n_in, n_out, t)).grid(grid).threadgroup(threads)) + outs[t] = (b_x, b_y) + r = nt.Queue(dev).run(ds) + assert not r.error, r.error + return {t: np.frombuffer(b_y.read(0, 4 * 8 * n_out), np.float32).reshape(8, n_out) for t, (_, b_y) in outs.items()} + + +def dense_tc_pair(type0, w0, n_out0, type1, w1, n_out1, xq, n_in, widths, fill=0xFF): + """``basalt_dense_tc_pair`` as ``dense_tc``: {T: ((8, n_out0), (8, n_out1))}.""" + pso = pipeline(kernels.basalt_dense_tc_source(), "basalt_dense_tc_pair", + tuple(sorted(kernels.basalt_dense_tc_pair_macros(type0, type1, n_in).items()))) + grid, threads = kernels.basalt_dense_tc_pair_grid(n_out0, n_out1) + dev, qcol = device(), n_in // 32 * kernels.Q8_1_BLOCK_BYTES + xq = np.ascontiguousarray(xq, np.uint8) + b_w0 = nt.Buffer(dev, np.ascontiguousarray(w0, np.uint8).tobytes()) + b_w1 = nt.Buffer(dev, np.ascontiguousarray(w1, np.uint8).tobytes()) + ds, outs = [], {} + for t in widths: + b_x, b_y0, b_y1 = nt.Buffer(dev, xq[: t * qcol].tobytes()), nt.Buffer(dev, 32 * n_out0), nt.Buffer(dev, 32 * n_out1) + b_y0.fill(fill) + b_y1.fill(fill) + d = nt.Dispatch().pipeline(pso) + for k, b in enumerate((b_w0, b_w1, b_x, b_y0, b_y1)): + d = d.buffer(k, b) + ds.append(d.bytes(5, kernels.basalt_dense_tc_params(n_in, n_out0, t, n_out1)).grid(grid).threadgroup(threads)) + outs[t] = (b_x, b_y0, b_y1) + r = nt.Queue(dev).run(ds) + assert not r.error, r.error + f = lambda b, n: np.frombuffer(b.read(0, 32 * n), np.float32).reshape(8, n) + return {t: (f(b0, n_out0), f(b1, n_out1)) for t, (_, b0, b1) in outs.items()} + + +def _map_buffer(dev, map_, n): + """basalt's map (int32 ids, negative: no token) or, for nullptr, a dummy buffer with has_map 0.""" + if map_ is None: + return nt.Buffer(dev, 4), False + return nt.Buffer(dev, np.ascontiguousarray(map_, np.int32).tobytes()), True + + +def q5k_head(w, xq, n_in, n_out, ncols, fill=0xEE, **grid): + """``basalt_q5k_head`` (basalt's ``q5k_head_mmvq``) for ``ncols`` columns, into an output whose bytes start as + ``fill``; ``grid``: ``basalt_q5k_head_grid``'s keywords.""" + macros = kernels.basalt_q5k_head_macros(n_in, ncols) + pso = pipeline(kernels.basalt_q5k_head_source(), "basalt_q5k_head", tuple(sorted(macros.items()))) + out = run(pso, [np.ascontiguousarray(w, np.uint8).tobytes(), np.ascontiguousarray(xq, np.uint8).tobytes(), + 4 * ncols * n_out], kernels.basalt_q5k_head_params(n_in, n_out), 3, + kernels.basalt_q5k_head_grid(n_out, **grid), kernels.Q5K_HEAD_THREADS, fill) + return np.frombuffer(out[2], np.float32).reshape(ncols, n_out) + + +def q5k_head_masked(w, xq, n_in, n_out, map_): + """basalt's plain head then ``q5k_head_mask_unmapped`` on its logits, in one command buffer: one column.""" + dev = device() + src = kernels.basalt_q5k_head_source() + macros = tuple(sorted(kernels.basalt_q5k_head_macros(n_in, 1).items())) + bw = nt.Buffer(dev, np.ascontiguousarray(w, np.uint8).tobytes()) + bx = nt.Buffer(dev, np.ascontiguousarray(xq, np.uint8).tobytes()) + by = nt.Buffer(dev, 4 * n_out) + by.fill(0xEE) + bm, _ = _map_buffer(dev, map_, n_out) + params = kernels.basalt_q5k_head_params(n_in, n_out) + d1 = (nt.Dispatch().pipeline(pipeline(src, "basalt_q5k_head", macros)).buffer(0, bw).buffer(1, bx).buffer(2, by) + .bytes(3, params).grid(kernels.basalt_q5k_head_grid(n_out)).threadgroup(kernels.Q5K_HEAD_THREADS)) + d2 = (nt.Dispatch().pipeline(pipeline(src, "basalt_q5k_head_mask_unmapped", macros)).buffer(0, by).buffer(1, bm) + .bytes(2, params).grid(-(-n_out // 256)).threadgroup(256)) + r = nt.Queue(dev).run([d1, d2]) + assert not r.error, r.error + return np.frombuffer(by.read(0, 4 * n_out), np.float32) + + +def q5k_top1(w, xq, n_out, map_=None, **grid): + """basalt's ``q5k_head_top1`` (n_in 2560, one column): ``basalt_q5k_head_top1`` then ``basalt_q5k_head_top1_merge`` + in one command buffer. Returns (logits, id, probability, the threadgroup partials as (m, idx, s) rows).""" + dev = device() + src = kernels.basalt_q5k_head_source() + macros = tuple(sorted(kernels.basalt_q5k_head_macros(2560, 1).items())) + blocks = kernels.basalt_q5k_head_grid(n_out, **grid) + bw = nt.Buffer(dev, np.ascontiguousarray(w, np.uint8).tobytes()) + bx = nt.Buffer(dev, np.ascontiguousarray(xq, np.uint8).tobytes()) + by, bpart, bid, bp = nt.Buffer(dev, 4 * n_out), nt.Buffer(dev, 12 * blocks), nt.Buffer(dev, 4), nt.Buffer(dev, 4) + for b in (by, bpart, bid, bp): + b.fill(0xEE) + bm, has = _map_buffer(dev, map_, n_out) + params = kernels.basalt_q5k_head_params(2560, n_out, has, blocks) + d1 = nt.Dispatch().pipeline(pipeline(src, "basalt_q5k_head_top1", macros)) + for k, b in enumerate((bw, bx, by, bm, bpart)): + d1 = d1.buffer(k, b) + d1 = d1.bytes(5, params).grid(blocks).threadgroup(kernels.Q5K_HEAD_THREADS) + d2 = nt.Dispatch().pipeline(pipeline(src, "basalt_q5k_head_top1_merge", macros)) + for k, b in enumerate((bpart, bm, bid, bp)): + d2 = d2.buffer(k, b) + d2 = d2.bytes(4, params).grid(1).threadgroup(kernels.Q5K_HEAD_THREADS) + r = nt.Queue(dev).run([d1, d2]) + assert not r.error, r.error + part = np.frombuffer(bpart.read(0, 12 * blocks), np.float32).reshape(blocks, 3) + return (np.frombuffer(by.read(0, 4 * n_out), np.float32), int(np.frombuffer(bid.read(0, 4), np.int32)[0]), + np.frombuffer(bp.read(0, 4), np.float32)[0], part) + + +def expf_ftz(x): + """basalt_fp.metal's expf_ftz (``__expf`` in a fast-math file) on the GPU, elementwise: the values the kernels use.""" + src = kernels.PRELUDE + kernels.template("basalt_fp.metal") + """ +kernel void ex(device const float* x [[buffer(0)]], device float* e [[buffer(1)]], constant uint& n [[buffer(2)]], + uint i [[thread_position_in_grid]]) { + if (i < n) e[i] = expf_ftz(x[i]); +} +""" + x = np.ascontiguousarray(x, np.float32) + flat = x.reshape(-1) + out = run(pipeline(src, "ex"), [flat.tobytes(), 4 * flat.size], np.uint32(flat.size).tobytes(), 2, + -(-flat.size // 256), 256) + return np.frombuffer(out[1], np.float32).reshape(x.shape) + + +def q5k_proxy_pack(q5, n_cap, packs, proxy=None): + """basalt's ``q5k_proxy_pack`` for each (row0, n) of ``packs`` in order, in one command buffer, into a copy for + ``n_cap`` rows that starts as ``proxy`` (bytes) or zeros (basalt's test clears it, q5k_head_parity.cpp:243).""" + dev = device() + pso = pipeline(kernels.basalt_q5k_head_source(), "basalt_q5k_proxy_pack") + nbytes = kernels.basalt_q5k_proxy_bytes(n_cap) + bq = nt.Buffer(dev, np.ascontiguousarray(q5, np.uint8).tobytes()) + bp = nt.Buffer(dev, bytes(proxy) if proxy is not None else bytes(nbytes)) + ds = [nt.Dispatch().pipeline(pso).buffer(0, bq).buffer(1, bp) + .bytes(2, kernels.basalt_q5k_proxy_params(n_cap, row0=row0, n=n)) + .grid(-(-n * 80 // kernels.PX_THREADS_PACK)).threadgroup(kernels.PX_THREADS_PACK) for row0, n in packs] + r = nt.Queue(dev).run(ds) + assert not r.error, r.error + return np.frombuffer(bp.read(0, nbytes), np.uint8) + + +def q5k_proxy_score(proxy, xq, n_rows, n_cap, map_): + """``px::score_kernel`` over the first ``n_rows`` rows of the copy ``proxy`` (``n_cap`` rows) for one q8_1 column: + (cand: (tiles, 4, 2) pairs (score, row bits), part: (tiles, 2) (max, sum)) from basalt's scratch layout.""" + dev = device() + pso = pipeline(kernels.basalt_q5k_head_source(), "basalt_q5k_proxy_score") + nbytes = kernels.basalt_q5k_proxy_scratch_bytes(n_cap) + bs = nt.Buffer(dev, nbytes) + bs.fill(0xEE) + d = (nt.Dispatch().pipeline(pso).buffer(0, nt.Buffer(dev, np.ascontiguousarray(proxy, np.uint8).tobytes())) + .buffer(1, nt.Buffer(dev, np.ascontiguousarray(xq, np.uint8).tobytes())) + .buffer(2, nt.Buffer(dev, np.ascontiguousarray(map_, np.int32).tobytes())).buffer(3, bs) + .bytes(4, kernels.basalt_q5k_proxy_params(n_cap, n_rows=n_rows)) + .grid(kernels.basalt_q5k_proxy_tiles(n_rows)).threadgroup(kernels.PX_THREADS_SCORE)) + r = nt.Queue(dev).run([d]) + assert not r.error, r.error + s = np.frombuffer(bs.read(0, nbytes), np.float32) + ntc, t = kernels.basalt_q5k_proxy_tiles(n_cap), kernels.basalt_q5k_proxy_tiles(n_rows) + return s[: 8 * t].reshape(t, 4, 2), s[8 * ntc: 8 * ntc + 2 * t].reshape(t, 2) + + +def q5k_proxy_top1(proxy, q5, xq, n_rows, n_cap, map_): + """basalt's ``q5k_proxy_top1`` (q5k_head.cu:516-535): ``basalt_q5k_proxy_score`` then ``basalt_q5k_proxy_final`` + in one command buffer, over the first ``n_rows`` rows of the copy ``proxy`` and of the Q5_K rows ``q5``, for one + q8_1 column. Returns (id, probability, the score's cand (tiles, 4, 2) and part (tiles, 2)).""" + dev = device() + src = kernels.basalt_q5k_head_source() + final = pipeline(src, "basalt_q5k_proxy_final") + assert final.max_threads_per_threadgroup >= kernels.PX_THREADS_FINAL, final.max_threads_per_threadgroup + nbytes = kernels.basalt_q5k_proxy_scratch_bytes(n_cap) + bp, bq = (nt.Buffer(dev, np.ascontiguousarray(a, np.uint8).tobytes()) for a in (proxy, q5)) + bx = nt.Buffer(dev, np.ascontiguousarray(xq, np.uint8).tobytes()) + bm = nt.Buffer(dev, np.ascontiguousarray(map_, np.int32).tobytes()) + bs, bid, bpr = nt.Buffer(dev, nbytes), nt.Buffer(dev, 4), nt.Buffer(dev, 4) + for b in (bs, bid, bpr): + b.fill(0xEE) + params = kernels.basalt_q5k_proxy_params(n_cap, n_rows=n_rows) + d1 = (nt.Dispatch().pipeline(pipeline(src, "basalt_q5k_proxy_score")).buffer(0, bp).buffer(1, bx).buffer(2, bm) + .buffer(3, bs).bytes(4, params).grid(kernels.basalt_q5k_proxy_tiles(n_rows)) + .threadgroup(kernels.PX_THREADS_SCORE)) + d2 = (nt.Dispatch().pipeline(final).buffer(0, bq).buffer(1, bx).buffer(2, bm).buffer(3, bs).buffer(4, bid) + .buffer(5, bpr).bytes(6, params).grid(1).threadgroup(kernels.PX_THREADS_FINAL)) + r = nt.Queue(dev).run([d1, d2]) + assert not r.error, r.error + s = np.frombuffer(bs.read(0, nbytes), np.float32) + ntc, t = kernels.basalt_q5k_proxy_tiles(n_cap), kernels.basalt_q5k_proxy_tiles(n_rows) + return (int(np.frombuffer(bid.read(0, 4), np.int32)[0]), np.frombuffer(bpr.read(0, 4), np.float32)[0], + s[: 8 * t].reshape(t, 4, 2), s[8 * ntc: 8 * ntc + 2 * t].reshape(t, 2)) diff --git a/tests/kernels/fixtures/expf_digests.txt b/tests/kernels/fixtures/expf_digests.txt new file mode 100644 index 00000000..4ee0729d --- /dev/null +++ b/tests/kernels/fixtures/expf_digests.txt @@ -0,0 +1,4110 @@ +# glibc expf on x86-64: per-block digests over all 2^32 float32 arguments +# (docs/research/basalt-cpu-expf.md section 4). +# Measured 2026-10-18 on Compiler Explorer x86-64 executors (Xeon Platinum 8375C and 8488C, AVX-512), glibc 2.39 = +# Ubuntu 24.04 libc6 2.39-0ubuntu8.9 (libm build-id d53fcbff9f855463606b25cfbe2a2e10856ea3a7), MXCSR 0x00001f80. +# The call is the program's own `expf` (expf@GLIBC_2.27 via the PLT), which the ifunc resolves to __expf_fma +# (libm+0x7dc40) on these CPUs: the variant basalt's pool.cpp:434 runs on any FMA+AVX2 host. +# Block k (0..4095) = the 2^20 arguments whose bit patterns are k<<20 .. (k<<20)|0xfffff, in increasing bit order. +# Digest: h = 0xcbf29ce484222325; for each argument, h = (h XOR bits(expf(x))) * 0x100000001b3 mod 2^64, where +# bits() is the result's IEEE binary32 bit pattern as a uint32 (FNV-1a's step applied to whole 32-bit words). +# The other ifunc variant (__expf_sse2) has the same digest in every block except 420 and c27; see the end. +# columns: block first_arg last_arg digest (hex) +000 00000000 000fffff 70a8716626622325 +001 00100000 001fffff 70a8716626622325 +002 00200000 002fffff 70a8716626622325 +003 00300000 003fffff 70a8716626622325 +004 00400000 004fffff 70a8716626622325 +005 00500000 005fffff 70a8716626622325 +006 00600000 006fffff 70a8716626622325 +007 00700000 007fffff 70a8716626622325 +008 00800000 008fffff 70a8716626622325 +009 00900000 009fffff 70a8716626622325 +00a 00a00000 00afffff 70a8716626622325 +00b 00b00000 00bfffff 70a8716626622325 +00c 00c00000 00cfffff 70a8716626622325 +00d 00d00000 00dfffff 70a8716626622325 +00e 00e00000 00efffff 70a8716626622325 +00f 00f00000 00ffffff 70a8716626622325 +010 01000000 010fffff 70a8716626622325 +011 01100000 011fffff 70a8716626622325 +012 01200000 012fffff 70a8716626622325 +013 01300000 013fffff 70a8716626622325 +014 01400000 014fffff 70a8716626622325 +015 01500000 015fffff 70a8716626622325 +016 01600000 016fffff 70a8716626622325 +017 01700000 017fffff 70a8716626622325 +018 01800000 018fffff 70a8716626622325 +019 01900000 019fffff 70a8716626622325 +01a 01a00000 01afffff 70a8716626622325 +01b 01b00000 01bfffff 70a8716626622325 +01c 01c00000 01cfffff 70a8716626622325 +01d 01d00000 01dfffff 70a8716626622325 +01e 01e00000 01efffff 70a8716626622325 +01f 01f00000 01ffffff 70a8716626622325 +020 02000000 020fffff 70a8716626622325 +021 02100000 021fffff 70a8716626622325 +022 02200000 022fffff 70a8716626622325 +023 02300000 023fffff 70a8716626622325 +024 02400000 024fffff 70a8716626622325 +025 02500000 025fffff 70a8716626622325 +026 02600000 026fffff 70a8716626622325 +027 02700000 027fffff 70a8716626622325 +028 02800000 028fffff 70a8716626622325 +029 02900000 029fffff 70a8716626622325 +02a 02a00000 02afffff 70a8716626622325 +02b 02b00000 02bfffff 70a8716626622325 +02c 02c00000 02cfffff 70a8716626622325 +02d 02d00000 02dfffff 70a8716626622325 +02e 02e00000 02efffff 70a8716626622325 +02f 02f00000 02ffffff 70a8716626622325 +030 03000000 030fffff 70a8716626622325 +031 03100000 031fffff 70a8716626622325 +032 03200000 032fffff 70a8716626622325 +033 03300000 033fffff 70a8716626622325 +034 03400000 034fffff 70a8716626622325 +035 03500000 035fffff 70a8716626622325 +036 03600000 036fffff 70a8716626622325 +037 03700000 037fffff 70a8716626622325 +038 03800000 038fffff 70a8716626622325 +039 03900000 039fffff 70a8716626622325 +03a 03a00000 03afffff 70a8716626622325 +03b 03b00000 03bfffff 70a8716626622325 +03c 03c00000 03cfffff 70a8716626622325 +03d 03d00000 03dfffff 70a8716626622325 +03e 03e00000 03efffff 70a8716626622325 +03f 03f00000 03ffffff 70a8716626622325 +040 04000000 040fffff 70a8716626622325 +041 04100000 041fffff 70a8716626622325 +042 04200000 042fffff 70a8716626622325 +043 04300000 043fffff 70a8716626622325 +044 04400000 044fffff 70a8716626622325 +045 04500000 045fffff 70a8716626622325 +046 04600000 046fffff 70a8716626622325 +047 04700000 047fffff 70a8716626622325 +048 04800000 048fffff 70a8716626622325 +049 04900000 049fffff 70a8716626622325 +04a 04a00000 04afffff 70a8716626622325 +04b 04b00000 04bfffff 70a8716626622325 +04c 04c00000 04cfffff 70a8716626622325 +04d 04d00000 04dfffff 70a8716626622325 +04e 04e00000 04efffff 70a8716626622325 +04f 04f00000 04ffffff 70a8716626622325 +050 05000000 050fffff 70a8716626622325 +051 05100000 051fffff 70a8716626622325 +052 05200000 052fffff 70a8716626622325 +053 05300000 053fffff 70a8716626622325 +054 05400000 054fffff 70a8716626622325 +055 05500000 055fffff 70a8716626622325 +056 05600000 056fffff 70a8716626622325 +057 05700000 057fffff 70a8716626622325 +058 05800000 058fffff 70a8716626622325 +059 05900000 059fffff 70a8716626622325 +05a 05a00000 05afffff 70a8716626622325 +05b 05b00000 05bfffff 70a8716626622325 +05c 05c00000 05cfffff 70a8716626622325 +05d 05d00000 05dfffff 70a8716626622325 +05e 05e00000 05efffff 70a8716626622325 +05f 05f00000 05ffffff 70a8716626622325 +060 06000000 060fffff 70a8716626622325 +061 06100000 061fffff 70a8716626622325 +062 06200000 062fffff 70a8716626622325 +063 06300000 063fffff 70a8716626622325 +064 06400000 064fffff 70a8716626622325 +065 06500000 065fffff 70a8716626622325 +066 06600000 066fffff 70a8716626622325 +067 06700000 067fffff 70a8716626622325 +068 06800000 068fffff 70a8716626622325 +069 06900000 069fffff 70a8716626622325 +06a 06a00000 06afffff 70a8716626622325 +06b 06b00000 06bfffff 70a8716626622325 +06c 06c00000 06cfffff 70a8716626622325 +06d 06d00000 06dfffff 70a8716626622325 +06e 06e00000 06efffff 70a8716626622325 +06f 06f00000 06ffffff 70a8716626622325 +070 07000000 070fffff 70a8716626622325 +071 07100000 071fffff 70a8716626622325 +072 07200000 072fffff 70a8716626622325 +073 07300000 073fffff 70a8716626622325 +074 07400000 074fffff 70a8716626622325 +075 07500000 075fffff 70a8716626622325 +076 07600000 076fffff 70a8716626622325 +077 07700000 077fffff 70a8716626622325 +078 07800000 078fffff 70a8716626622325 +079 07900000 079fffff 70a8716626622325 +07a 07a00000 07afffff 70a8716626622325 +07b 07b00000 07bfffff 70a8716626622325 +07c 07c00000 07cfffff 70a8716626622325 +07d 07d00000 07dfffff 70a8716626622325 +07e 07e00000 07efffff 70a8716626622325 +07f 07f00000 07ffffff 70a8716626622325 +080 08000000 080fffff 70a8716626622325 +081 08100000 081fffff 70a8716626622325 +082 08200000 082fffff 70a8716626622325 +083 08300000 083fffff 70a8716626622325 +084 08400000 084fffff 70a8716626622325 +085 08500000 085fffff 70a8716626622325 +086 08600000 086fffff 70a8716626622325 +087 08700000 087fffff 70a8716626622325 +088 08800000 088fffff 70a8716626622325 +089 08900000 089fffff 70a8716626622325 +08a 08a00000 08afffff 70a8716626622325 +08b 08b00000 08bfffff 70a8716626622325 +08c 08c00000 08cfffff 70a8716626622325 +08d 08d00000 08dfffff 70a8716626622325 +08e 08e00000 08efffff 70a8716626622325 +08f 08f00000 08ffffff 70a8716626622325 +090 09000000 090fffff 70a8716626622325 +091 09100000 091fffff 70a8716626622325 +092 09200000 092fffff 70a8716626622325 +093 09300000 093fffff 70a8716626622325 +094 09400000 094fffff 70a8716626622325 +095 09500000 095fffff 70a8716626622325 +096 09600000 096fffff 70a8716626622325 +097 09700000 097fffff 70a8716626622325 +098 09800000 098fffff 70a8716626622325 +099 09900000 099fffff 70a8716626622325 +09a 09a00000 09afffff 70a8716626622325 +09b 09b00000 09bfffff 70a8716626622325 +09c 09c00000 09cfffff 70a8716626622325 +09d 09d00000 09dfffff 70a8716626622325 +09e 09e00000 09efffff 70a8716626622325 +09f 09f00000 09ffffff 70a8716626622325 +0a0 0a000000 0a0fffff 70a8716626622325 +0a1 0a100000 0a1fffff 70a8716626622325 +0a2 0a200000 0a2fffff 70a8716626622325 +0a3 0a300000 0a3fffff 70a8716626622325 +0a4 0a400000 0a4fffff 70a8716626622325 +0a5 0a500000 0a5fffff 70a8716626622325 +0a6 0a600000 0a6fffff 70a8716626622325 +0a7 0a700000 0a7fffff 70a8716626622325 +0a8 0a800000 0a8fffff 70a8716626622325 +0a9 0a900000 0a9fffff 70a8716626622325 +0aa 0aa00000 0aafffff 70a8716626622325 +0ab 0ab00000 0abfffff 70a8716626622325 +0ac 0ac00000 0acfffff 70a8716626622325 +0ad 0ad00000 0adfffff 70a8716626622325 +0ae 0ae00000 0aefffff 70a8716626622325 +0af 0af00000 0affffff 70a8716626622325 +0b0 0b000000 0b0fffff 70a8716626622325 +0b1 0b100000 0b1fffff 70a8716626622325 +0b2 0b200000 0b2fffff 70a8716626622325 +0b3 0b300000 0b3fffff 70a8716626622325 +0b4 0b400000 0b4fffff 70a8716626622325 +0b5 0b500000 0b5fffff 70a8716626622325 +0b6 0b600000 0b6fffff 70a8716626622325 +0b7 0b700000 0b7fffff 70a8716626622325 +0b8 0b800000 0b8fffff 70a8716626622325 +0b9 0b900000 0b9fffff 70a8716626622325 +0ba 0ba00000 0bafffff 70a8716626622325 +0bb 0bb00000 0bbfffff 70a8716626622325 +0bc 0bc00000 0bcfffff 70a8716626622325 +0bd 0bd00000 0bdfffff 70a8716626622325 +0be 0be00000 0befffff 70a8716626622325 +0bf 0bf00000 0bffffff 70a8716626622325 +0c0 0c000000 0c0fffff 70a8716626622325 +0c1 0c100000 0c1fffff 70a8716626622325 +0c2 0c200000 0c2fffff 70a8716626622325 +0c3 0c300000 0c3fffff 70a8716626622325 +0c4 0c400000 0c4fffff 70a8716626622325 +0c5 0c500000 0c5fffff 70a8716626622325 +0c6 0c600000 0c6fffff 70a8716626622325 +0c7 0c700000 0c7fffff 70a8716626622325 +0c8 0c800000 0c8fffff 70a8716626622325 +0c9 0c900000 0c9fffff 70a8716626622325 +0ca 0ca00000 0cafffff 70a8716626622325 +0cb 0cb00000 0cbfffff 70a8716626622325 +0cc 0cc00000 0ccfffff 70a8716626622325 +0cd 0cd00000 0cdfffff 70a8716626622325 +0ce 0ce00000 0cefffff 70a8716626622325 +0cf 0cf00000 0cffffff 70a8716626622325 +0d0 0d000000 0d0fffff 70a8716626622325 +0d1 0d100000 0d1fffff 70a8716626622325 +0d2 0d200000 0d2fffff 70a8716626622325 +0d3 0d300000 0d3fffff 70a8716626622325 +0d4 0d400000 0d4fffff 70a8716626622325 +0d5 0d500000 0d5fffff 70a8716626622325 +0d6 0d600000 0d6fffff 70a8716626622325 +0d7 0d700000 0d7fffff 70a8716626622325 +0d8 0d800000 0d8fffff 70a8716626622325 +0d9 0d900000 0d9fffff 70a8716626622325 +0da 0da00000 0dafffff 70a8716626622325 +0db 0db00000 0dbfffff 70a8716626622325 +0dc 0dc00000 0dcfffff 70a8716626622325 +0dd 0dd00000 0ddfffff 70a8716626622325 +0de 0de00000 0defffff 70a8716626622325 +0df 0df00000 0dffffff 70a8716626622325 +0e0 0e000000 0e0fffff 70a8716626622325 +0e1 0e100000 0e1fffff 70a8716626622325 +0e2 0e200000 0e2fffff 70a8716626622325 +0e3 0e300000 0e3fffff 70a8716626622325 +0e4 0e400000 0e4fffff 70a8716626622325 +0e5 0e500000 0e5fffff 70a8716626622325 +0e6 0e600000 0e6fffff 70a8716626622325 +0e7 0e700000 0e7fffff 70a8716626622325 +0e8 0e800000 0e8fffff 70a8716626622325 +0e9 0e900000 0e9fffff 70a8716626622325 +0ea 0ea00000 0eafffff 70a8716626622325 +0eb 0eb00000 0ebfffff 70a8716626622325 +0ec 0ec00000 0ecfffff 70a8716626622325 +0ed 0ed00000 0edfffff 70a8716626622325 +0ee 0ee00000 0eefffff 70a8716626622325 +0ef 0ef00000 0effffff 70a8716626622325 +0f0 0f000000 0f0fffff 70a8716626622325 +0f1 0f100000 0f1fffff 70a8716626622325 +0f2 0f200000 0f2fffff 70a8716626622325 +0f3 0f300000 0f3fffff 70a8716626622325 +0f4 0f400000 0f4fffff 70a8716626622325 +0f5 0f500000 0f5fffff 70a8716626622325 +0f6 0f600000 0f6fffff 70a8716626622325 +0f7 0f700000 0f7fffff 70a8716626622325 +0f8 0f800000 0f8fffff 70a8716626622325 +0f9 0f900000 0f9fffff 70a8716626622325 +0fa 0fa00000 0fafffff 70a8716626622325 +0fb 0fb00000 0fbfffff 70a8716626622325 +0fc 0fc00000 0fcfffff 70a8716626622325 +0fd 0fd00000 0fdfffff 70a8716626622325 +0fe 0fe00000 0fefffff 70a8716626622325 +0ff 0ff00000 0fffffff 70a8716626622325 +100 10000000 100fffff 70a8716626622325 +101 10100000 101fffff 70a8716626622325 +102 10200000 102fffff 70a8716626622325 +103 10300000 103fffff 70a8716626622325 +104 10400000 104fffff 70a8716626622325 +105 10500000 105fffff 70a8716626622325 +106 10600000 106fffff 70a8716626622325 +107 10700000 107fffff 70a8716626622325 +108 10800000 108fffff 70a8716626622325 +109 10900000 109fffff 70a8716626622325 +10a 10a00000 10afffff 70a8716626622325 +10b 10b00000 10bfffff 70a8716626622325 +10c 10c00000 10cfffff 70a8716626622325 +10d 10d00000 10dfffff 70a8716626622325 +10e 10e00000 10efffff 70a8716626622325 +10f 10f00000 10ffffff 70a8716626622325 +110 11000000 110fffff 70a8716626622325 +111 11100000 111fffff 70a8716626622325 +112 11200000 112fffff 70a8716626622325 +113 11300000 113fffff 70a8716626622325 +114 11400000 114fffff 70a8716626622325 +115 11500000 115fffff 70a8716626622325 +116 11600000 116fffff 70a8716626622325 +117 11700000 117fffff 70a8716626622325 +118 11800000 118fffff 70a8716626622325 +119 11900000 119fffff 70a8716626622325 +11a 11a00000 11afffff 70a8716626622325 +11b 11b00000 11bfffff 70a8716626622325 +11c 11c00000 11cfffff 70a8716626622325 +11d 11d00000 11dfffff 70a8716626622325 +11e 11e00000 11efffff 70a8716626622325 +11f 11f00000 11ffffff 70a8716626622325 +120 12000000 120fffff 70a8716626622325 +121 12100000 121fffff 70a8716626622325 +122 12200000 122fffff 70a8716626622325 +123 12300000 123fffff 70a8716626622325 +124 12400000 124fffff 70a8716626622325 +125 12500000 125fffff 70a8716626622325 +126 12600000 126fffff 70a8716626622325 +127 12700000 127fffff 70a8716626622325 +128 12800000 128fffff 70a8716626622325 +129 12900000 129fffff 70a8716626622325 +12a 12a00000 12afffff 70a8716626622325 +12b 12b00000 12bfffff 70a8716626622325 +12c 12c00000 12cfffff 70a8716626622325 +12d 12d00000 12dfffff 70a8716626622325 +12e 12e00000 12efffff 70a8716626622325 +12f 12f00000 12ffffff 70a8716626622325 +130 13000000 130fffff 70a8716626622325 +131 13100000 131fffff 70a8716626622325 +132 13200000 132fffff 70a8716626622325 +133 13300000 133fffff 70a8716626622325 +134 13400000 134fffff 70a8716626622325 +135 13500000 135fffff 70a8716626622325 +136 13600000 136fffff 70a8716626622325 +137 13700000 137fffff 70a8716626622325 +138 13800000 138fffff 70a8716626622325 +139 13900000 139fffff 70a8716626622325 +13a 13a00000 13afffff 70a8716626622325 +13b 13b00000 13bfffff 70a8716626622325 +13c 13c00000 13cfffff 70a8716626622325 +13d 13d00000 13dfffff 70a8716626622325 +13e 13e00000 13efffff 70a8716626622325 +13f 13f00000 13ffffff 70a8716626622325 +140 14000000 140fffff 70a8716626622325 +141 14100000 141fffff 70a8716626622325 +142 14200000 142fffff 70a8716626622325 +143 14300000 143fffff 70a8716626622325 +144 14400000 144fffff 70a8716626622325 +145 14500000 145fffff 70a8716626622325 +146 14600000 146fffff 70a8716626622325 +147 14700000 147fffff 70a8716626622325 +148 14800000 148fffff 70a8716626622325 +149 14900000 149fffff 70a8716626622325 +14a 14a00000 14afffff 70a8716626622325 +14b 14b00000 14bfffff 70a8716626622325 +14c 14c00000 14cfffff 70a8716626622325 +14d 14d00000 14dfffff 70a8716626622325 +14e 14e00000 14efffff 70a8716626622325 +14f 14f00000 14ffffff 70a8716626622325 +150 15000000 150fffff 70a8716626622325 +151 15100000 151fffff 70a8716626622325 +152 15200000 152fffff 70a8716626622325 +153 15300000 153fffff 70a8716626622325 +154 15400000 154fffff 70a8716626622325 +155 15500000 155fffff 70a8716626622325 +156 15600000 156fffff 70a8716626622325 +157 15700000 157fffff 70a8716626622325 +158 15800000 158fffff 70a8716626622325 +159 15900000 159fffff 70a8716626622325 +15a 15a00000 15afffff 70a8716626622325 +15b 15b00000 15bfffff 70a8716626622325 +15c 15c00000 15cfffff 70a8716626622325 +15d 15d00000 15dfffff 70a8716626622325 +15e 15e00000 15efffff 70a8716626622325 +15f 15f00000 15ffffff 70a8716626622325 +160 16000000 160fffff 70a8716626622325 +161 16100000 161fffff 70a8716626622325 +162 16200000 162fffff 70a8716626622325 +163 16300000 163fffff 70a8716626622325 +164 16400000 164fffff 70a8716626622325 +165 16500000 165fffff 70a8716626622325 +166 16600000 166fffff 70a8716626622325 +167 16700000 167fffff 70a8716626622325 +168 16800000 168fffff 70a8716626622325 +169 16900000 169fffff 70a8716626622325 +16a 16a00000 16afffff 70a8716626622325 +16b 16b00000 16bfffff 70a8716626622325 +16c 16c00000 16cfffff 70a8716626622325 +16d 16d00000 16dfffff 70a8716626622325 +16e 16e00000 16efffff 70a8716626622325 +16f 16f00000 16ffffff 70a8716626622325 +170 17000000 170fffff 70a8716626622325 +171 17100000 171fffff 70a8716626622325 +172 17200000 172fffff 70a8716626622325 +173 17300000 173fffff 70a8716626622325 +174 17400000 174fffff 70a8716626622325 +175 17500000 175fffff 70a8716626622325 +176 17600000 176fffff 70a8716626622325 +177 17700000 177fffff 70a8716626622325 +178 17800000 178fffff 70a8716626622325 +179 17900000 179fffff 70a8716626622325 +17a 17a00000 17afffff 70a8716626622325 +17b 17b00000 17bfffff 70a8716626622325 +17c 17c00000 17cfffff 70a8716626622325 +17d 17d00000 17dfffff 70a8716626622325 +17e 17e00000 17efffff 70a8716626622325 +17f 17f00000 17ffffff 70a8716626622325 +180 18000000 180fffff 70a8716626622325 +181 18100000 181fffff 70a8716626622325 +182 18200000 182fffff 70a8716626622325 +183 18300000 183fffff 70a8716626622325 +184 18400000 184fffff 70a8716626622325 +185 18500000 185fffff 70a8716626622325 +186 18600000 186fffff 70a8716626622325 +187 18700000 187fffff 70a8716626622325 +188 18800000 188fffff 70a8716626622325 +189 18900000 189fffff 70a8716626622325 +18a 18a00000 18afffff 70a8716626622325 +18b 18b00000 18bfffff 70a8716626622325 +18c 18c00000 18cfffff 70a8716626622325 +18d 18d00000 18dfffff 70a8716626622325 +18e 18e00000 18efffff 70a8716626622325 +18f 18f00000 18ffffff 70a8716626622325 +190 19000000 190fffff 70a8716626622325 +191 19100000 191fffff 70a8716626622325 +192 19200000 192fffff 70a8716626622325 +193 19300000 193fffff 70a8716626622325 +194 19400000 194fffff 70a8716626622325 +195 19500000 195fffff 70a8716626622325 +196 19600000 196fffff 70a8716626622325 +197 19700000 197fffff 70a8716626622325 +198 19800000 198fffff 70a8716626622325 +199 19900000 199fffff 70a8716626622325 +19a 19a00000 19afffff 70a8716626622325 +19b 19b00000 19bfffff 70a8716626622325 +19c 19c00000 19cfffff 70a8716626622325 +19d 19d00000 19dfffff 70a8716626622325 +19e 19e00000 19efffff 70a8716626622325 +19f 19f00000 19ffffff 70a8716626622325 +1a0 1a000000 1a0fffff 70a8716626622325 +1a1 1a100000 1a1fffff 70a8716626622325 +1a2 1a200000 1a2fffff 70a8716626622325 +1a3 1a300000 1a3fffff 70a8716626622325 +1a4 1a400000 1a4fffff 70a8716626622325 +1a5 1a500000 1a5fffff 70a8716626622325 +1a6 1a600000 1a6fffff 70a8716626622325 +1a7 1a700000 1a7fffff 70a8716626622325 +1a8 1a800000 1a8fffff 70a8716626622325 +1a9 1a900000 1a9fffff 70a8716626622325 +1aa 1aa00000 1aafffff 70a8716626622325 +1ab 1ab00000 1abfffff 70a8716626622325 +1ac 1ac00000 1acfffff 70a8716626622325 +1ad 1ad00000 1adfffff 70a8716626622325 +1ae 1ae00000 1aefffff 70a8716626622325 +1af 1af00000 1affffff 70a8716626622325 +1b0 1b000000 1b0fffff 70a8716626622325 +1b1 1b100000 1b1fffff 70a8716626622325 +1b2 1b200000 1b2fffff 70a8716626622325 +1b3 1b300000 1b3fffff 70a8716626622325 +1b4 1b400000 1b4fffff 70a8716626622325 +1b5 1b500000 1b5fffff 70a8716626622325 +1b6 1b600000 1b6fffff 70a8716626622325 +1b7 1b700000 1b7fffff 70a8716626622325 +1b8 1b800000 1b8fffff 70a8716626622325 +1b9 1b900000 1b9fffff 70a8716626622325 +1ba 1ba00000 1bafffff 70a8716626622325 +1bb 1bb00000 1bbfffff 70a8716626622325 +1bc 1bc00000 1bcfffff 70a8716626622325 +1bd 1bd00000 1bdfffff 70a8716626622325 +1be 1be00000 1befffff 70a8716626622325 +1bf 1bf00000 1bffffff 70a8716626622325 +1c0 1c000000 1c0fffff 70a8716626622325 +1c1 1c100000 1c1fffff 70a8716626622325 +1c2 1c200000 1c2fffff 70a8716626622325 +1c3 1c300000 1c3fffff 70a8716626622325 +1c4 1c400000 1c4fffff 70a8716626622325 +1c5 1c500000 1c5fffff 70a8716626622325 +1c6 1c600000 1c6fffff 70a8716626622325 +1c7 1c700000 1c7fffff 70a8716626622325 +1c8 1c800000 1c8fffff 70a8716626622325 +1c9 1c900000 1c9fffff 70a8716626622325 +1ca 1ca00000 1cafffff 70a8716626622325 +1cb 1cb00000 1cbfffff 70a8716626622325 +1cc 1cc00000 1ccfffff 70a8716626622325 +1cd 1cd00000 1cdfffff 70a8716626622325 +1ce 1ce00000 1cefffff 70a8716626622325 +1cf 1cf00000 1cffffff 70a8716626622325 +1d0 1d000000 1d0fffff 70a8716626622325 +1d1 1d100000 1d1fffff 70a8716626622325 +1d2 1d200000 1d2fffff 70a8716626622325 +1d3 1d300000 1d3fffff 70a8716626622325 +1d4 1d400000 1d4fffff 70a8716626622325 +1d5 1d500000 1d5fffff 70a8716626622325 +1d6 1d600000 1d6fffff 70a8716626622325 +1d7 1d700000 1d7fffff 70a8716626622325 +1d8 1d800000 1d8fffff 70a8716626622325 +1d9 1d900000 1d9fffff 70a8716626622325 +1da 1da00000 1dafffff 70a8716626622325 +1db 1db00000 1dbfffff 70a8716626622325 +1dc 1dc00000 1dcfffff 70a8716626622325 +1dd 1dd00000 1ddfffff 70a8716626622325 +1de 1de00000 1defffff 70a8716626622325 +1df 1df00000 1dffffff 70a8716626622325 +1e0 1e000000 1e0fffff 70a8716626622325 +1e1 1e100000 1e1fffff 70a8716626622325 +1e2 1e200000 1e2fffff 70a8716626622325 +1e3 1e300000 1e3fffff 70a8716626622325 +1e4 1e400000 1e4fffff 70a8716626622325 +1e5 1e500000 1e5fffff 70a8716626622325 +1e6 1e600000 1e6fffff 70a8716626622325 +1e7 1e700000 1e7fffff 70a8716626622325 +1e8 1e800000 1e8fffff 70a8716626622325 +1e9 1e900000 1e9fffff 70a8716626622325 +1ea 1ea00000 1eafffff 70a8716626622325 +1eb 1eb00000 1ebfffff 70a8716626622325 +1ec 1ec00000 1ecfffff 70a8716626622325 +1ed 1ed00000 1edfffff 70a8716626622325 +1ee 1ee00000 1eefffff 70a8716626622325 +1ef 1ef00000 1effffff 70a8716626622325 +1f0 1f000000 1f0fffff 70a8716626622325 +1f1 1f100000 1f1fffff 70a8716626622325 +1f2 1f200000 1f2fffff 70a8716626622325 +1f3 1f300000 1f3fffff 70a8716626622325 +1f4 1f400000 1f4fffff 70a8716626622325 +1f5 1f500000 1f5fffff 70a8716626622325 +1f6 1f600000 1f6fffff 70a8716626622325 +1f7 1f700000 1f7fffff 70a8716626622325 +1f8 1f800000 1f8fffff 70a8716626622325 +1f9 1f900000 1f9fffff 70a8716626622325 +1fa 1fa00000 1fafffff 70a8716626622325 +1fb 1fb00000 1fbfffff 70a8716626622325 +1fc 1fc00000 1fcfffff 70a8716626622325 +1fd 1fd00000 1fdfffff 70a8716626622325 +1fe 1fe00000 1fefffff 70a8716626622325 +1ff 1ff00000 1fffffff 70a8716626622325 +200 20000000 200fffff 70a8716626622325 +201 20100000 201fffff 70a8716626622325 +202 20200000 202fffff 70a8716626622325 +203 20300000 203fffff 70a8716626622325 +204 20400000 204fffff 70a8716626622325 +205 20500000 205fffff 70a8716626622325 +206 20600000 206fffff 70a8716626622325 +207 20700000 207fffff 70a8716626622325 +208 20800000 208fffff 70a8716626622325 +209 20900000 209fffff 70a8716626622325 +20a 20a00000 20afffff 70a8716626622325 +20b 20b00000 20bfffff 70a8716626622325 +20c 20c00000 20cfffff 70a8716626622325 +20d 20d00000 20dfffff 70a8716626622325 +20e 20e00000 20efffff 70a8716626622325 +20f 20f00000 20ffffff 70a8716626622325 +210 21000000 210fffff 70a8716626622325 +211 21100000 211fffff 70a8716626622325 +212 21200000 212fffff 70a8716626622325 +213 21300000 213fffff 70a8716626622325 +214 21400000 214fffff 70a8716626622325 +215 21500000 215fffff 70a8716626622325 +216 21600000 216fffff 70a8716626622325 +217 21700000 217fffff 70a8716626622325 +218 21800000 218fffff 70a8716626622325 +219 21900000 219fffff 70a8716626622325 +21a 21a00000 21afffff 70a8716626622325 +21b 21b00000 21bfffff 70a8716626622325 +21c 21c00000 21cfffff 70a8716626622325 +21d 21d00000 21dfffff 70a8716626622325 +21e 21e00000 21efffff 70a8716626622325 +21f 21f00000 21ffffff 70a8716626622325 +220 22000000 220fffff 70a8716626622325 +221 22100000 221fffff 70a8716626622325 +222 22200000 222fffff 70a8716626622325 +223 22300000 223fffff 70a8716626622325 +224 22400000 224fffff 70a8716626622325 +225 22500000 225fffff 70a8716626622325 +226 22600000 226fffff 70a8716626622325 +227 22700000 227fffff 70a8716626622325 +228 22800000 228fffff 70a8716626622325 +229 22900000 229fffff 70a8716626622325 +22a 22a00000 22afffff 70a8716626622325 +22b 22b00000 22bfffff 70a8716626622325 +22c 22c00000 22cfffff 70a8716626622325 +22d 22d00000 22dfffff 70a8716626622325 +22e 22e00000 22efffff 70a8716626622325 +22f 22f00000 22ffffff 70a8716626622325 +230 23000000 230fffff 70a8716626622325 +231 23100000 231fffff 70a8716626622325 +232 23200000 232fffff 70a8716626622325 +233 23300000 233fffff 70a8716626622325 +234 23400000 234fffff 70a8716626622325 +235 23500000 235fffff 70a8716626622325 +236 23600000 236fffff 70a8716626622325 +237 23700000 237fffff 70a8716626622325 +238 23800000 238fffff 70a8716626622325 +239 23900000 239fffff 70a8716626622325 +23a 23a00000 23afffff 70a8716626622325 +23b 23b00000 23bfffff 70a8716626622325 +23c 23c00000 23cfffff 70a8716626622325 +23d 23d00000 23dfffff 70a8716626622325 +23e 23e00000 23efffff 70a8716626622325 +23f 23f00000 23ffffff 70a8716626622325 +240 24000000 240fffff 70a8716626622325 +241 24100000 241fffff 70a8716626622325 +242 24200000 242fffff 70a8716626622325 +243 24300000 243fffff 70a8716626622325 +244 24400000 244fffff 70a8716626622325 +245 24500000 245fffff 70a8716626622325 +246 24600000 246fffff 70a8716626622325 +247 24700000 247fffff 70a8716626622325 +248 24800000 248fffff 70a8716626622325 +249 24900000 249fffff 70a8716626622325 +24a 24a00000 24afffff 70a8716626622325 +24b 24b00000 24bfffff 70a8716626622325 +24c 24c00000 24cfffff 70a8716626622325 +24d 24d00000 24dfffff 70a8716626622325 +24e 24e00000 24efffff 70a8716626622325 +24f 24f00000 24ffffff 70a8716626622325 +250 25000000 250fffff 70a8716626622325 +251 25100000 251fffff 70a8716626622325 +252 25200000 252fffff 70a8716626622325 +253 25300000 253fffff 70a8716626622325 +254 25400000 254fffff 70a8716626622325 +255 25500000 255fffff 70a8716626622325 +256 25600000 256fffff 70a8716626622325 +257 25700000 257fffff 70a8716626622325 +258 25800000 258fffff 70a8716626622325 +259 25900000 259fffff 70a8716626622325 +25a 25a00000 25afffff 70a8716626622325 +25b 25b00000 25bfffff 70a8716626622325 +25c 25c00000 25cfffff 70a8716626622325 +25d 25d00000 25dfffff 70a8716626622325 +25e 25e00000 25efffff 70a8716626622325 +25f 25f00000 25ffffff 70a8716626622325 +260 26000000 260fffff 70a8716626622325 +261 26100000 261fffff 70a8716626622325 +262 26200000 262fffff 70a8716626622325 +263 26300000 263fffff 70a8716626622325 +264 26400000 264fffff 70a8716626622325 +265 26500000 265fffff 70a8716626622325 +266 26600000 266fffff 70a8716626622325 +267 26700000 267fffff 70a8716626622325 +268 26800000 268fffff 70a8716626622325 +269 26900000 269fffff 70a8716626622325 +26a 26a00000 26afffff 70a8716626622325 +26b 26b00000 26bfffff 70a8716626622325 +26c 26c00000 26cfffff 70a8716626622325 +26d 26d00000 26dfffff 70a8716626622325 +26e 26e00000 26efffff 70a8716626622325 +26f 26f00000 26ffffff 70a8716626622325 +270 27000000 270fffff 70a8716626622325 +271 27100000 271fffff 70a8716626622325 +272 27200000 272fffff 70a8716626622325 +273 27300000 273fffff 70a8716626622325 +274 27400000 274fffff 70a8716626622325 +275 27500000 275fffff 70a8716626622325 +276 27600000 276fffff 70a8716626622325 +277 27700000 277fffff 70a8716626622325 +278 27800000 278fffff 70a8716626622325 +279 27900000 279fffff 70a8716626622325 +27a 27a00000 27afffff 70a8716626622325 +27b 27b00000 27bfffff 70a8716626622325 +27c 27c00000 27cfffff 70a8716626622325 +27d 27d00000 27dfffff 70a8716626622325 +27e 27e00000 27efffff 70a8716626622325 +27f 27f00000 27ffffff 70a8716626622325 +280 28000000 280fffff 70a8716626622325 +281 28100000 281fffff 70a8716626622325 +282 28200000 282fffff 70a8716626622325 +283 28300000 283fffff 70a8716626622325 +284 28400000 284fffff 70a8716626622325 +285 28500000 285fffff 70a8716626622325 +286 28600000 286fffff 70a8716626622325 +287 28700000 287fffff 70a8716626622325 +288 28800000 288fffff 70a8716626622325 +289 28900000 289fffff 70a8716626622325 +28a 28a00000 28afffff 70a8716626622325 +28b 28b00000 28bfffff 70a8716626622325 +28c 28c00000 28cfffff 70a8716626622325 +28d 28d00000 28dfffff 70a8716626622325 +28e 28e00000 28efffff 70a8716626622325 +28f 28f00000 28ffffff 70a8716626622325 +290 29000000 290fffff 70a8716626622325 +291 29100000 291fffff 70a8716626622325 +292 29200000 292fffff 70a8716626622325 +293 29300000 293fffff 70a8716626622325 +294 29400000 294fffff 70a8716626622325 +295 29500000 295fffff 70a8716626622325 +296 29600000 296fffff 70a8716626622325 +297 29700000 297fffff 70a8716626622325 +298 29800000 298fffff 70a8716626622325 +299 29900000 299fffff 70a8716626622325 +29a 29a00000 29afffff 70a8716626622325 +29b 29b00000 29bfffff 70a8716626622325 +29c 29c00000 29cfffff 70a8716626622325 +29d 29d00000 29dfffff 70a8716626622325 +29e 29e00000 29efffff 70a8716626622325 +29f 29f00000 29ffffff 70a8716626622325 +2a0 2a000000 2a0fffff 70a8716626622325 +2a1 2a100000 2a1fffff 70a8716626622325 +2a2 2a200000 2a2fffff 70a8716626622325 +2a3 2a300000 2a3fffff 70a8716626622325 +2a4 2a400000 2a4fffff 70a8716626622325 +2a5 2a500000 2a5fffff 70a8716626622325 +2a6 2a600000 2a6fffff 70a8716626622325 +2a7 2a700000 2a7fffff 70a8716626622325 +2a8 2a800000 2a8fffff 70a8716626622325 +2a9 2a900000 2a9fffff 70a8716626622325 +2aa 2aa00000 2aafffff 70a8716626622325 +2ab 2ab00000 2abfffff 70a8716626622325 +2ac 2ac00000 2acfffff 70a8716626622325 +2ad 2ad00000 2adfffff 70a8716626622325 +2ae 2ae00000 2aefffff 70a8716626622325 +2af 2af00000 2affffff 70a8716626622325 +2b0 2b000000 2b0fffff 70a8716626622325 +2b1 2b100000 2b1fffff 70a8716626622325 +2b2 2b200000 2b2fffff 70a8716626622325 +2b3 2b300000 2b3fffff 70a8716626622325 +2b4 2b400000 2b4fffff 70a8716626622325 +2b5 2b500000 2b5fffff 70a8716626622325 +2b6 2b600000 2b6fffff 70a8716626622325 +2b7 2b700000 2b7fffff 70a8716626622325 +2b8 2b800000 2b8fffff 70a8716626622325 +2b9 2b900000 2b9fffff 70a8716626622325 +2ba 2ba00000 2bafffff 70a8716626622325 +2bb 2bb00000 2bbfffff 70a8716626622325 +2bc 2bc00000 2bcfffff 70a8716626622325 +2bd 2bd00000 2bdfffff 70a8716626622325 +2be 2be00000 2befffff 70a8716626622325 +2bf 2bf00000 2bffffff 70a8716626622325 +2c0 2c000000 2c0fffff 70a8716626622325 +2c1 2c100000 2c1fffff 70a8716626622325 +2c2 2c200000 2c2fffff 70a8716626622325 +2c3 2c300000 2c3fffff 70a8716626622325 +2c4 2c400000 2c4fffff 70a8716626622325 +2c5 2c500000 2c5fffff 70a8716626622325 +2c6 2c600000 2c6fffff 70a8716626622325 +2c7 2c700000 2c7fffff 70a8716626622325 +2c8 2c800000 2c8fffff 70a8716626622325 +2c9 2c900000 2c9fffff 70a8716626622325 +2ca 2ca00000 2cafffff 70a8716626622325 +2cb 2cb00000 2cbfffff 70a8716626622325 +2cc 2cc00000 2ccfffff 70a8716626622325 +2cd 2cd00000 2cdfffff 70a8716626622325 +2ce 2ce00000 2cefffff 70a8716626622325 +2cf 2cf00000 2cffffff 70a8716626622325 +2d0 2d000000 2d0fffff 70a8716626622325 +2d1 2d100000 2d1fffff 70a8716626622325 +2d2 2d200000 2d2fffff 70a8716626622325 +2d3 2d300000 2d3fffff 70a8716626622325 +2d4 2d400000 2d4fffff 70a8716626622325 +2d5 2d500000 2d5fffff 70a8716626622325 +2d6 2d600000 2d6fffff 70a8716626622325 +2d7 2d700000 2d7fffff 70a8716626622325 +2d8 2d800000 2d8fffff 70a8716626622325 +2d9 2d900000 2d9fffff 70a8716626622325 +2da 2da00000 2dafffff 70a8716626622325 +2db 2db00000 2dbfffff 70a8716626622325 +2dc 2dc00000 2dcfffff 70a8716626622325 +2dd 2dd00000 2ddfffff 70a8716626622325 +2de 2de00000 2defffff 70a8716626622325 +2df 2df00000 2dffffff 70a8716626622325 +2e0 2e000000 2e0fffff 70a8716626622325 +2e1 2e100000 2e1fffff 70a8716626622325 +2e2 2e200000 2e2fffff 70a8716626622325 +2e3 2e300000 2e3fffff 70a8716626622325 +2e4 2e400000 2e4fffff 70a8716626622325 +2e5 2e500000 2e5fffff 70a8716626622325 +2e6 2e600000 2e6fffff 70a8716626622325 +2e7 2e700000 2e7fffff 70a8716626622325 +2e8 2e800000 2e8fffff 70a8716626622325 +2e9 2e900000 2e9fffff 70a8716626622325 +2ea 2ea00000 2eafffff 70a8716626622325 +2eb 2eb00000 2ebfffff 70a8716626622325 +2ec 2ec00000 2ecfffff 70a8716626622325 +2ed 2ed00000 2edfffff 70a8716626622325 +2ee 2ee00000 2eefffff 70a8716626622325 +2ef 2ef00000 2effffff 70a8716626622325 +2f0 2f000000 2f0fffff 70a8716626622325 +2f1 2f100000 2f1fffff 70a8716626622325 +2f2 2f200000 2f2fffff 70a8716626622325 +2f3 2f300000 2f3fffff 70a8716626622325 +2f4 2f400000 2f4fffff 70a8716626622325 +2f5 2f500000 2f5fffff 70a8716626622325 +2f6 2f600000 2f6fffff 70a8716626622325 +2f7 2f700000 2f7fffff 70a8716626622325 +2f8 2f800000 2f8fffff 70a8716626622325 +2f9 2f900000 2f9fffff 70a8716626622325 +2fa 2fa00000 2fafffff 70a8716626622325 +2fb 2fb00000 2fbfffff 70a8716626622325 +2fc 2fc00000 2fcfffff 70a8716626622325 +2fd 2fd00000 2fdfffff 70a8716626622325 +2fe 2fe00000 2fefffff 70a8716626622325 +2ff 2ff00000 2fffffff 70a8716626622325 +300 30000000 300fffff 70a8716626622325 +301 30100000 301fffff 70a8716626622325 +302 30200000 302fffff 70a8716626622325 +303 30300000 303fffff 70a8716626622325 +304 30400000 304fffff 70a8716626622325 +305 30500000 305fffff 70a8716626622325 +306 30600000 306fffff 70a8716626622325 +307 30700000 307fffff 70a8716626622325 +308 30800000 308fffff 70a8716626622325 +309 30900000 309fffff 70a8716626622325 +30a 30a00000 30afffff 70a8716626622325 +30b 30b00000 30bfffff 70a8716626622325 +30c 30c00000 30cfffff 70a8716626622325 +30d 30d00000 30dfffff 70a8716626622325 +30e 30e00000 30efffff 70a8716626622325 +30f 30f00000 30ffffff 70a8716626622325 +310 31000000 310fffff 70a8716626622325 +311 31100000 311fffff 70a8716626622325 +312 31200000 312fffff 70a8716626622325 +313 31300000 313fffff 70a8716626622325 +314 31400000 314fffff 70a8716626622325 +315 31500000 315fffff 70a8716626622325 +316 31600000 316fffff 70a8716626622325 +317 31700000 317fffff 70a8716626622325 +318 31800000 318fffff 70a8716626622325 +319 31900000 319fffff 70a8716626622325 +31a 31a00000 31afffff 70a8716626622325 +31b 31b00000 31bfffff 70a8716626622325 +31c 31c00000 31cfffff 70a8716626622325 +31d 31d00000 31dfffff 70a8716626622325 +31e 31e00000 31efffff 70a8716626622325 +31f 31f00000 31ffffff 70a8716626622325 +320 32000000 320fffff 70a8716626622325 +321 32100000 321fffff 70a8716626622325 +322 32200000 322fffff 70a8716626622325 +323 32300000 323fffff 70a8716626622325 +324 32400000 324fffff 70a8716626622325 +325 32500000 325fffff 70a8716626622325 +326 32600000 326fffff 70a8716626622325 +327 32700000 327fffff 70a8716626622325 +328 32800000 328fffff 70a8716626622325 +329 32900000 329fffff 70a8716626622325 +32a 32a00000 32afffff 70a8716626622325 +32b 32b00000 32bfffff 70a8716626622325 +32c 32c00000 32cfffff 70a8716626622325 +32d 32d00000 32dfffff 70a8716626622325 +32e 32e00000 32efffff 70a8716626622325 +32f 32f00000 32ffffff 70a8716626622325 +330 33000000 330fffff 70a8716626622325 +331 33100000 331fffff 70a8716626622325 +332 33200000 332fffff 70a8716626622325 +333 33300000 333fffff 70a8716626622325 +334 33400000 334fffff 70a8716626622325 +335 33500000 335fffff 70a8716626622325 +336 33600000 336fffff 70a8716626622325 +337 33700000 337fffff 70a8716626622325 +338 33800000 338fffff 9747a37040722325 +339 33900000 339fffff 9747a37040722325 +33a 33a00000 33afffff 9747a37040722325 +33b 33b00000 33bfffff 9747a37040722325 +33c 33c00000 33cfffff 9747a37040722325 +33d 33d00000 33dfffff 9747a37040722325 +33e 33e00000 33efffff 9747a37040722325 +33f 33f00000 33ffffff 9747a37040722325 +340 34000000 340fffff 9747a37040722325 +341 34100000 341fffff 9747a37040722325 +342 34200000 342fffff 9747a37040722325 +343 34300000 343fffff 9747a07040721e0c +344 34400000 344fffff 7e75bc7de0222325 +345 34500000 345fffff 7e75bc7de0222325 +346 34600000 346fffff 7e75bc7de0222325 +347 34700000 347fffff 7e75bc7de0222325 +348 34800000 348fffff 7e75bc7de0222325 +349 34900000 349fffff 7e75bb7de0222172 +34a 34a00000 34afffff 9267b15909f22325 +34b 34b00000 34bfffff 9267b15909f22325 +34c 34c00000 34cfffff 9267b15909f22325 +34d 34d00000 34dfffff 7867d358fb373816 +34e 34e00000 34efffff 6af97ae60fa22325 +34f 34f00000 34ffffff 6af97ae60fa22325 +350 35000000 350fffff 6af615e60f9f41af +351 35100000 351fffff 26b7a55518722325 +352 35200000 352fffff 2f428b551d402712 +353 35300000 353fffff bdd949450d622325 +354 35400000 354fffff 6091bb8f1971660e +355 35500000 355fffff 5b93d284d4f22325 +356 35600000 356fffff 00fc190099bba7b2 +357 35700000 357fffff 6dabbb3eb2622325 +358 35800000 358fffff 9ec4e8f145c7b659 +359 35900000 359fffff 1608da2e4ee1e3b0 +35a 35a00000 35afffff cca6a9c592d46df7 +35b 35b00000 35bfffff 5c31808660fb18cd +35c 35c00000 35cfffff 552b0374dda8fe2a +35d 35d00000 35dfffff 3838f977b2b016ea +35e 35e00000 35efffff acea85c66b807156 +35f 35f00000 35ffffff 1f9685f85ede75ca +360 36000000 360fffff 42d0bb45113554dc +361 36100000 361fffff 8c1ccae017065ff8 +362 36200000 362fffff 566705742c2ba778 +363 36300000 363fffff 8b6e859644c3fbd9 +364 36400000 364fffff 0007a8702538ecab +365 36500000 365fffff 124e4a4354da7e01 +366 36600000 366fffff 6ff26ae8e724f865 +367 36700000 367fffff f23769b3424968b9 +368 36800000 368fffff 81eb6dedde579735 +369 36900000 369fffff 9da6c3662ab4d9d5 +36a 36a00000 36afffff 45dd7972129cda25 +36b 36b00000 36bfffff 14c2c71e561214bb +36c 36c00000 36cfffff 6649625162372233 +36d 36d00000 36dfffff 32a3feacedb57e62 +36e 36e00000 36efffff 599c8bffb3680c21 +36f 36f00000 36ffffff 3c3dcbf4dd79daf9 +370 37000000 370fffff 67c1fdfd6b36f295 +371 37100000 371fffff f1cd765b1c12d959 +372 37200000 372fffff bf3a0ffe79bbc9c0 +373 37300000 373fffff 297cf45eb2f4023a +374 37400000 374fffff b40527234255eecc +375 37500000 375fffff c2a15189e529cf2e +376 37600000 376fffff 9f3318495d17ea70 +377 37700000 377fffff 1436fd7415eb9a7d +378 37800000 378fffff e6410ac41466c21a +379 37900000 379fffff a10c9b2268389a6e +37a 37a00000 37afffff 1c1b941f157f4d81 +37b 37b00000 37bfffff a88f343901e26d8c +37c 37c00000 37cfffff 08a28849c91db392 +37d 37d00000 37dfffff b35270fef56f3851 +37e 37e00000 37efffff 8816fc92b7516926 +37f 37f00000 37ffffff 0ebc29786eec9235 +380 38000000 380fffff ce9dbf66c4c68261 +381 38100000 381fffff 0fd0c9849c4fa3c4 +382 38200000 382fffff 041dc25d26e5611e +383 38300000 383fffff 748bb42f1f3b794d +384 38400000 384fffff d9288c55c8f4e855 +385 38500000 385fffff 731887288cfa3085 +386 38600000 386fffff e8ca6a517b2eceef +387 38700000 387fffff 15e0db16e25162eb +388 38800000 388fffff b6bad3d1b73d1880 +389 38900000 389fffff bddc7d4eefcdd6fc +38a 38a00000 38afffff 4f1d61e86d1340a1 +38b 38b00000 38bfffff 233d1b494b808b96 +38c 38c00000 38cfffff 0d8a73238395a7a7 +38d 38d00000 38dfffff 182655ee91dd60ae +38e 38e00000 38efffff 7e5dc3bd79fda592 +38f 38f00000 38ffffff 4fb969fbe4ebf7f8 +390 39000000 390fffff e5b28080ffb8cc65 +391 39100000 391fffff cf596f059b76a038 +392 39200000 392fffff 3e3fa2e3712b89c4 +393 39300000 393fffff 19c7074add187f00 +394 39400000 394fffff ab9dbab4028f84a9 +395 39500000 395fffff fe8331265baa96ae +396 39600000 396fffff d15970bff33148b0 +397 39700000 397fffff 2df7075d8160bb62 +398 39800000 398fffff 145d60a33152268d +399 39900000 399fffff 457131eb2b154f37 +39a 39a00000 39afffff 9ad25ef48c9cba91 +39b 39b00000 39bfffff db17eaf8ed149027 +39c 39c00000 39cfffff bb0b9ac0f3e43f55 +39d 39d00000 39dfffff 587b0f60878a48fb +39e 39e00000 39efffff bb9bded6d627d5c6 +39f 39f00000 39ffffff 03cd7e459e6fc857 +3a0 3a000000 3a0fffff 6f7ebaa9729cd748 +3a1 3a100000 3a1fffff 6c0529c85f195092 +3a2 3a200000 3a2fffff ad206549b7cf2cfa +3a3 3a300000 3a3fffff 8bc99b705cf7ae61 +3a4 3a400000 3a4fffff 1798fc25df395cf6 +3a5 3a500000 3a5fffff 79044edfdc235af6 +3a6 3a600000 3a6fffff 967928132406ed08 +3a7 3a700000 3a7fffff f6b08fa34ae3e19b +3a8 3a800000 3a8fffff 628bffbfb9cc4446 +3a9 3a900000 3a9fffff aba97fd9e960e256 +3aa 3aa00000 3aafffff 13388a4e1645db92 +3ab 3ab00000 3abfffff cdd02b9bb8fd4900 +3ac 3ac00000 3acfffff 3fc0d4af7c9cdd5c +3ad 3ad00000 3adfffff 0940d3a7bbe50f32 +3ae 3ae00000 3aefffff 8b35b9165a6ea4bb +3af 3af00000 3affffff 1f195d62cca57402 +3b0 3b000000 3b0fffff f431191bab812020 +3b1 3b100000 3b1fffff d39bfca7de4064be +3b2 3b200000 3b2fffff e352d438512e6e0a +3b3 3b300000 3b3fffff b9cdb2618793fe18 +3b4 3b400000 3b4fffff 756aa8056a19dee9 +3b5 3b500000 3b5fffff 428a6c9904b7b749 +3b6 3b600000 3b6fffff 09c6adf6d6339a3e +3b7 3b700000 3b7fffff 2b63472de370b928 +3b8 3b800000 3b8fffff ec92e5dddaa66053 +3b9 3b900000 3b9fffff 2ab9c00ed2fbb685 +3ba 3ba00000 3bafffff 29d3d7e826ea1270 +3bb 3bb00000 3bbfffff c481a3284a9b0ec5 +3bc 3bc00000 3bcfffff 405cac1b41463632 +3bd 3bd00000 3bdfffff 77e86b1d76dab39a +3be 3be00000 3befffff 3b52b0c3b4a62b60 +3bf 3bf00000 3bffffff 5f60878d7341b0a2 +3c0 3c000000 3c0fffff af057345058b9e34 +3c1 3c100000 3c1fffff c8d7f297e5101c43 +3c2 3c200000 3c2fffff ecab60c3e2baa728 +3c3 3c300000 3c3fffff 054c49c0fab9fad9 +3c4 3c400000 3c4fffff 3994e5235ff4f398 +3c5 3c500000 3c5fffff 95f721b3d108467a +3c6 3c600000 3c6fffff a5925a274e65874d +3c7 3c700000 3c7fffff a5af5cd2251fdb29 +3c8 3c800000 3c8fffff 36d5699b312182fd +3c9 3c900000 3c9fffff b8fc82eea668ff93 +3ca 3ca00000 3cafffff 62e3049bf9c8b8ab +3cb 3cb00000 3cbfffff b7d6a668017c4ee9 +3cc 3cc00000 3ccfffff 56fc316f567185de +3cd 3cd00000 3cdfffff 619e122b3bb10972 +3ce 3ce00000 3cefffff 082340c6cd7120a6 +3cf 3cf00000 3cffffff 9388be74830350cd +3d0 3d000000 3d0fffff 74b8ae49dae9b671 +3d1 3d100000 3d1fffff 4af7835acbe95f79 +3d2 3d200000 3d2fffff 9e816f223f2b7140 +3d3 3d300000 3d3fffff 8da8fc41a884d5d6 +3d4 3d400000 3d4fffff d69e36d14ffc9225 +3d5 3d500000 3d5fffff 4e440132a37fb0a3 +3d6 3d600000 3d6fffff 4e8d070f9e2ca1ec +3d7 3d700000 3d7fffff 09e30ab242a82d8d +3d8 3d800000 3d8fffff cd0599ae49af1385 +3d9 3d900000 3d9fffff b91059632ffb643d +3da 3da00000 3dafffff e46830710d1d0f79 +3db 3db00000 3dbfffff f0641ca001c32d6d +3dc 3dc00000 3dcfffff 3b2d0659cbbc61b6 +3dd 3dd00000 3ddfffff 3bda8a7d2bc53f2c +3de 3de00000 3defffff f513403bd97fcbc8 +3df 3df00000 3dffffff 1d1869cfdaf307e7 +3e0 3e000000 3e0fffff 12db373bb9ebb468 +3e1 3e100000 3e1fffff 2ed9663bd9859b45 +3e2 3e200000 3e2fffff 63ff5eb6f6f47fc4 +3e3 3e300000 3e3fffff a62eaed121216a30 +3e4 3e400000 3e4fffff cc749ce22587888a +3e5 3e500000 3e5fffff f5505de5a8045e52 +3e6 3e600000 3e6fffff 62c55cabb94155e1 +3e7 3e700000 3e7fffff aff245398fe99eef +3e8 3e800000 3e8fffff f0a203e5bbc6b134 +3e9 3e900000 3e9fffff 8bb0cd26d2cf02bb +3ea 3ea00000 3eafffff 88ce7e85010b2172 +3eb 3eb00000 3ebfffff 621bec9e712c90f2 +3ec 3ec00000 3ecfffff b202f295b7f57d67 +3ed 3ed00000 3edfffff 8edb0219f4a12486 +3ee 3ee00000 3eefffff b42d084cda12532c +3ef 3ef00000 3effffff 4d6d7ac76064081c +3f0 3f000000 3f0fffff 4d3e7de3a3415f69 +3f1 3f100000 3f1fffff 80c71f915ba6718b +3f2 3f200000 3f2fffff 0b10311d83fab1ce +3f3 3f300000 3f3fffff 66a0b6795a5fe5db +3f4 3f400000 3f4fffff 1bf6bbe464adc2d0 +3f5 3f500000 3f5fffff c2cd9ab7c5588e4d +3f6 3f600000 3f6fffff 91c5889fc5e757fa +3f7 3f700000 3f7fffff 5a9f9ef1f3778c7b +3f8 3f800000 3f8fffff 10e471cbfc063e0f +3f9 3f900000 3f9fffff 7ff025f3c8c520d5 +3fa 3fa00000 3fafffff 5a624af5b3ae6e89 +3fb 3fb00000 3fbfffff c608edd7a956bbd8 +3fc 3fc00000 3fcfffff 724184a5da28650a +3fd 3fd00000 3fdfffff 4493e8245f10d19e +3fe 3fe00000 3fefffff e455122d0ea143bc +3ff 3ff00000 3fffffff 49c4f6f93f766345 +400 40000000 400fffff d148af2dbda56f9b +401 40100000 401fffff 625ddb21796cc1b3 +402 40200000 402fffff 36d6e8815ef4b058 +403 40300000 403fffff 7978c11a5183c716 +404 40400000 404fffff bbe29d9a59102299 +405 40500000 405fffff 17400654077ccb16 +406 40600000 406fffff 2f199ca2caa71294 +407 40700000 407fffff 80ff6de8fe6d19be +408 40800000 408fffff d5dda7def6590436 +409 40900000 409fffff 18cb62959d6b940d +40a 40a00000 40afffff b5e7959050162b76 +40b 40b00000 40bfffff 8d57719a39881917 +40c 40c00000 40cfffff e06d6ecf432604af +40d 40d00000 40dfffff 7f5dc71f35c089af +40e 40e00000 40efffff 79a0e0c54d2389c4 +40f 40f00000 40ffffff 639fae5eff5ccf29 +410 41000000 410fffff 1eed740d8c214539 +411 41100000 411fffff 8f29670879bd0315 +412 41200000 412fffff 9945e3d96b150f60 +413 41300000 413fffff 518da031e96719f9 +414 41400000 414fffff 316f914b9dd468c2 +415 41500000 415fffff 4123734655c5f591 +416 41600000 416fffff 9fcb509ae8d3ee26 +417 41700000 417fffff 10a4f939e6c0ab30 +418 41800000 418fffff f630f3266af7eebf +419 41900000 419fffff cc080f04360e9db4 +41a 41a00000 41afffff 50f86e0b2afabceb +41b 41b00000 41bfffff a53ac17cb723325e +41c 41c00000 41cfffff ef62e133ca945586 +41d 41d00000 41dfffff a7ded08a45b26471 +41e 41e00000 41efffff 08545e94a844d806 +41f 41f00000 41ffffff baf61d3eded9cfd2 +420 42000000 420fffff bcf4dc5f666df1cd +421 42100000 421fffff 9a17620c7ae8c117 +422 42200000 422fffff bc447912ac2cf0c3 +423 42300000 423fffff cccf87b532f60db0 +424 42400000 424fffff c57bc4b2ee6bdca0 +425 42500000 425fffff e4becb2543732cf7 +426 42600000 426fffff 5a425bbc9a2af52c +427 42700000 427fffff 2e4cb74d8c9836c8 +428 42800000 428fffff 36afb955e56f0c26 +429 42900000 429fffff cc489c3c43ea0414 +42a 42a00000 42afffff 24a22a1da1f65d6e +42b 42b00000 42bfffff 87166d9183e64366 +42c 42c00000 42cfffff aedd460726622325 +42d 42d00000 42dfffff aedd460726622325 +42e 42e00000 42efffff aedd460726622325 +42f 42f00000 42ffffff aedd460726622325 +430 43000000 430fffff aedd460726622325 +431 43100000 431fffff aedd460726622325 +432 43200000 432fffff aedd460726622325 +433 43300000 433fffff aedd460726622325 +434 43400000 434fffff aedd460726622325 +435 43500000 435fffff aedd460726622325 +436 43600000 436fffff aedd460726622325 +437 43700000 437fffff aedd460726622325 +438 43800000 438fffff aedd460726622325 +439 43900000 439fffff aedd460726622325 +43a 43a00000 43afffff aedd460726622325 +43b 43b00000 43bfffff aedd460726622325 +43c 43c00000 43cfffff aedd460726622325 +43d 43d00000 43dfffff aedd460726622325 +43e 43e00000 43efffff aedd460726622325 +43f 43f00000 43ffffff aedd460726622325 +440 44000000 440fffff aedd460726622325 +441 44100000 441fffff aedd460726622325 +442 44200000 442fffff aedd460726622325 +443 44300000 443fffff aedd460726622325 +444 44400000 444fffff aedd460726622325 +445 44500000 445fffff aedd460726622325 +446 44600000 446fffff aedd460726622325 +447 44700000 447fffff aedd460726622325 +448 44800000 448fffff aedd460726622325 +449 44900000 449fffff aedd460726622325 +44a 44a00000 44afffff aedd460726622325 +44b 44b00000 44bfffff aedd460726622325 +44c 44c00000 44cfffff aedd460726622325 +44d 44d00000 44dfffff aedd460726622325 +44e 44e00000 44efffff aedd460726622325 +44f 44f00000 44ffffff aedd460726622325 +450 45000000 450fffff aedd460726622325 +451 45100000 451fffff aedd460726622325 +452 45200000 452fffff aedd460726622325 +453 45300000 453fffff aedd460726622325 +454 45400000 454fffff aedd460726622325 +455 45500000 455fffff aedd460726622325 +456 45600000 456fffff aedd460726622325 +457 45700000 457fffff aedd460726622325 +458 45800000 458fffff aedd460726622325 +459 45900000 459fffff aedd460726622325 +45a 45a00000 45afffff aedd460726622325 +45b 45b00000 45bfffff aedd460726622325 +45c 45c00000 45cfffff aedd460726622325 +45d 45d00000 45dfffff aedd460726622325 +45e 45e00000 45efffff aedd460726622325 +45f 45f00000 45ffffff aedd460726622325 +460 46000000 460fffff aedd460726622325 +461 46100000 461fffff aedd460726622325 +462 46200000 462fffff aedd460726622325 +463 46300000 463fffff aedd460726622325 +464 46400000 464fffff aedd460726622325 +465 46500000 465fffff aedd460726622325 +466 46600000 466fffff aedd460726622325 +467 46700000 467fffff aedd460726622325 +468 46800000 468fffff aedd460726622325 +469 46900000 469fffff aedd460726622325 +46a 46a00000 46afffff aedd460726622325 +46b 46b00000 46bfffff aedd460726622325 +46c 46c00000 46cfffff aedd460726622325 +46d 46d00000 46dfffff aedd460726622325 +46e 46e00000 46efffff aedd460726622325 +46f 46f00000 46ffffff aedd460726622325 +470 47000000 470fffff aedd460726622325 +471 47100000 471fffff aedd460726622325 +472 47200000 472fffff aedd460726622325 +473 47300000 473fffff aedd460726622325 +474 47400000 474fffff aedd460726622325 +475 47500000 475fffff aedd460726622325 +476 47600000 476fffff aedd460726622325 +477 47700000 477fffff aedd460726622325 +478 47800000 478fffff aedd460726622325 +479 47900000 479fffff aedd460726622325 +47a 47a00000 47afffff aedd460726622325 +47b 47b00000 47bfffff aedd460726622325 +47c 47c00000 47cfffff aedd460726622325 +47d 47d00000 47dfffff aedd460726622325 +47e 47e00000 47efffff aedd460726622325 +47f 47f00000 47ffffff aedd460726622325 +480 48000000 480fffff aedd460726622325 +481 48100000 481fffff aedd460726622325 +482 48200000 482fffff aedd460726622325 +483 48300000 483fffff aedd460726622325 +484 48400000 484fffff aedd460726622325 +485 48500000 485fffff aedd460726622325 +486 48600000 486fffff aedd460726622325 +487 48700000 487fffff aedd460726622325 +488 48800000 488fffff aedd460726622325 +489 48900000 489fffff aedd460726622325 +48a 48a00000 48afffff aedd460726622325 +48b 48b00000 48bfffff aedd460726622325 +48c 48c00000 48cfffff aedd460726622325 +48d 48d00000 48dfffff aedd460726622325 +48e 48e00000 48efffff aedd460726622325 +48f 48f00000 48ffffff aedd460726622325 +490 49000000 490fffff aedd460726622325 +491 49100000 491fffff aedd460726622325 +492 49200000 492fffff aedd460726622325 +493 49300000 493fffff aedd460726622325 +494 49400000 494fffff aedd460726622325 +495 49500000 495fffff aedd460726622325 +496 49600000 496fffff aedd460726622325 +497 49700000 497fffff aedd460726622325 +498 49800000 498fffff aedd460726622325 +499 49900000 499fffff aedd460726622325 +49a 49a00000 49afffff aedd460726622325 +49b 49b00000 49bfffff aedd460726622325 +49c 49c00000 49cfffff aedd460726622325 +49d 49d00000 49dfffff aedd460726622325 +49e 49e00000 49efffff aedd460726622325 +49f 49f00000 49ffffff aedd460726622325 +4a0 4a000000 4a0fffff aedd460726622325 +4a1 4a100000 4a1fffff aedd460726622325 +4a2 4a200000 4a2fffff aedd460726622325 +4a3 4a300000 4a3fffff aedd460726622325 +4a4 4a400000 4a4fffff aedd460726622325 +4a5 4a500000 4a5fffff aedd460726622325 +4a6 4a600000 4a6fffff aedd460726622325 +4a7 4a700000 4a7fffff aedd460726622325 +4a8 4a800000 4a8fffff aedd460726622325 +4a9 4a900000 4a9fffff aedd460726622325 +4aa 4aa00000 4aafffff aedd460726622325 +4ab 4ab00000 4abfffff aedd460726622325 +4ac 4ac00000 4acfffff aedd460726622325 +4ad 4ad00000 4adfffff aedd460726622325 +4ae 4ae00000 4aefffff aedd460726622325 +4af 4af00000 4affffff aedd460726622325 +4b0 4b000000 4b0fffff aedd460726622325 +4b1 4b100000 4b1fffff aedd460726622325 +4b2 4b200000 4b2fffff aedd460726622325 +4b3 4b300000 4b3fffff aedd460726622325 +4b4 4b400000 4b4fffff aedd460726622325 +4b5 4b500000 4b5fffff aedd460726622325 +4b6 4b600000 4b6fffff aedd460726622325 +4b7 4b700000 4b7fffff aedd460726622325 +4b8 4b800000 4b8fffff aedd460726622325 +4b9 4b900000 4b9fffff aedd460726622325 +4ba 4ba00000 4bafffff aedd460726622325 +4bb 4bb00000 4bbfffff aedd460726622325 +4bc 4bc00000 4bcfffff aedd460726622325 +4bd 4bd00000 4bdfffff aedd460726622325 +4be 4be00000 4befffff aedd460726622325 +4bf 4bf00000 4bffffff aedd460726622325 +4c0 4c000000 4c0fffff aedd460726622325 +4c1 4c100000 4c1fffff aedd460726622325 +4c2 4c200000 4c2fffff aedd460726622325 +4c3 4c300000 4c3fffff aedd460726622325 +4c4 4c400000 4c4fffff aedd460726622325 +4c5 4c500000 4c5fffff aedd460726622325 +4c6 4c600000 4c6fffff aedd460726622325 +4c7 4c700000 4c7fffff aedd460726622325 +4c8 4c800000 4c8fffff aedd460726622325 +4c9 4c900000 4c9fffff aedd460726622325 +4ca 4ca00000 4cafffff aedd460726622325 +4cb 4cb00000 4cbfffff aedd460726622325 +4cc 4cc00000 4ccfffff aedd460726622325 +4cd 4cd00000 4cdfffff aedd460726622325 +4ce 4ce00000 4cefffff aedd460726622325 +4cf 4cf00000 4cffffff aedd460726622325 +4d0 4d000000 4d0fffff aedd460726622325 +4d1 4d100000 4d1fffff aedd460726622325 +4d2 4d200000 4d2fffff aedd460726622325 +4d3 4d300000 4d3fffff aedd460726622325 +4d4 4d400000 4d4fffff aedd460726622325 +4d5 4d500000 4d5fffff aedd460726622325 +4d6 4d600000 4d6fffff aedd460726622325 +4d7 4d700000 4d7fffff aedd460726622325 +4d8 4d800000 4d8fffff aedd460726622325 +4d9 4d900000 4d9fffff aedd460726622325 +4da 4da00000 4dafffff aedd460726622325 +4db 4db00000 4dbfffff aedd460726622325 +4dc 4dc00000 4dcfffff aedd460726622325 +4dd 4dd00000 4ddfffff aedd460726622325 +4de 4de00000 4defffff aedd460726622325 +4df 4df00000 4dffffff aedd460726622325 +4e0 4e000000 4e0fffff aedd460726622325 +4e1 4e100000 4e1fffff aedd460726622325 +4e2 4e200000 4e2fffff aedd460726622325 +4e3 4e300000 4e3fffff aedd460726622325 +4e4 4e400000 4e4fffff aedd460726622325 +4e5 4e500000 4e5fffff aedd460726622325 +4e6 4e600000 4e6fffff aedd460726622325 +4e7 4e700000 4e7fffff aedd460726622325 +4e8 4e800000 4e8fffff aedd460726622325 +4e9 4e900000 4e9fffff aedd460726622325 +4ea 4ea00000 4eafffff aedd460726622325 +4eb 4eb00000 4ebfffff aedd460726622325 +4ec 4ec00000 4ecfffff aedd460726622325 +4ed 4ed00000 4edfffff aedd460726622325 +4ee 4ee00000 4eefffff aedd460726622325 +4ef 4ef00000 4effffff aedd460726622325 +4f0 4f000000 4f0fffff aedd460726622325 +4f1 4f100000 4f1fffff aedd460726622325 +4f2 4f200000 4f2fffff aedd460726622325 +4f3 4f300000 4f3fffff aedd460726622325 +4f4 4f400000 4f4fffff aedd460726622325 +4f5 4f500000 4f5fffff aedd460726622325 +4f6 4f600000 4f6fffff aedd460726622325 +4f7 4f700000 4f7fffff aedd460726622325 +4f8 4f800000 4f8fffff aedd460726622325 +4f9 4f900000 4f9fffff aedd460726622325 +4fa 4fa00000 4fafffff aedd460726622325 +4fb 4fb00000 4fbfffff aedd460726622325 +4fc 4fc00000 4fcfffff aedd460726622325 +4fd 4fd00000 4fdfffff aedd460726622325 +4fe 4fe00000 4fefffff aedd460726622325 +4ff 4ff00000 4fffffff aedd460726622325 +500 50000000 500fffff aedd460726622325 +501 50100000 501fffff aedd460726622325 +502 50200000 502fffff aedd460726622325 +503 50300000 503fffff aedd460726622325 +504 50400000 504fffff aedd460726622325 +505 50500000 505fffff aedd460726622325 +506 50600000 506fffff aedd460726622325 +507 50700000 507fffff aedd460726622325 +508 50800000 508fffff aedd460726622325 +509 50900000 509fffff aedd460726622325 +50a 50a00000 50afffff aedd460726622325 +50b 50b00000 50bfffff aedd460726622325 +50c 50c00000 50cfffff aedd460726622325 +50d 50d00000 50dfffff aedd460726622325 +50e 50e00000 50efffff aedd460726622325 +50f 50f00000 50ffffff aedd460726622325 +510 51000000 510fffff aedd460726622325 +511 51100000 511fffff aedd460726622325 +512 51200000 512fffff aedd460726622325 +513 51300000 513fffff aedd460726622325 +514 51400000 514fffff aedd460726622325 +515 51500000 515fffff aedd460726622325 +516 51600000 516fffff aedd460726622325 +517 51700000 517fffff aedd460726622325 +518 51800000 518fffff aedd460726622325 +519 51900000 519fffff aedd460726622325 +51a 51a00000 51afffff aedd460726622325 +51b 51b00000 51bfffff aedd460726622325 +51c 51c00000 51cfffff aedd460726622325 +51d 51d00000 51dfffff aedd460726622325 +51e 51e00000 51efffff aedd460726622325 +51f 51f00000 51ffffff aedd460726622325 +520 52000000 520fffff aedd460726622325 +521 52100000 521fffff aedd460726622325 +522 52200000 522fffff aedd460726622325 +523 52300000 523fffff aedd460726622325 +524 52400000 524fffff aedd460726622325 +525 52500000 525fffff aedd460726622325 +526 52600000 526fffff aedd460726622325 +527 52700000 527fffff aedd460726622325 +528 52800000 528fffff aedd460726622325 +529 52900000 529fffff aedd460726622325 +52a 52a00000 52afffff aedd460726622325 +52b 52b00000 52bfffff aedd460726622325 +52c 52c00000 52cfffff aedd460726622325 +52d 52d00000 52dfffff aedd460726622325 +52e 52e00000 52efffff aedd460726622325 +52f 52f00000 52ffffff aedd460726622325 +530 53000000 530fffff aedd460726622325 +531 53100000 531fffff aedd460726622325 +532 53200000 532fffff aedd460726622325 +533 53300000 533fffff aedd460726622325 +534 53400000 534fffff aedd460726622325 +535 53500000 535fffff aedd460726622325 +536 53600000 536fffff aedd460726622325 +537 53700000 537fffff aedd460726622325 +538 53800000 538fffff aedd460726622325 +539 53900000 539fffff aedd460726622325 +53a 53a00000 53afffff aedd460726622325 +53b 53b00000 53bfffff aedd460726622325 +53c 53c00000 53cfffff aedd460726622325 +53d 53d00000 53dfffff aedd460726622325 +53e 53e00000 53efffff aedd460726622325 +53f 53f00000 53ffffff aedd460726622325 +540 54000000 540fffff aedd460726622325 +541 54100000 541fffff aedd460726622325 +542 54200000 542fffff aedd460726622325 +543 54300000 543fffff aedd460726622325 +544 54400000 544fffff aedd460726622325 +545 54500000 545fffff aedd460726622325 +546 54600000 546fffff aedd460726622325 +547 54700000 547fffff aedd460726622325 +548 54800000 548fffff aedd460726622325 +549 54900000 549fffff aedd460726622325 +54a 54a00000 54afffff aedd460726622325 +54b 54b00000 54bfffff aedd460726622325 +54c 54c00000 54cfffff aedd460726622325 +54d 54d00000 54dfffff aedd460726622325 +54e 54e00000 54efffff aedd460726622325 +54f 54f00000 54ffffff aedd460726622325 +550 55000000 550fffff aedd460726622325 +551 55100000 551fffff aedd460726622325 +552 55200000 552fffff aedd460726622325 +553 55300000 553fffff aedd460726622325 +554 55400000 554fffff aedd460726622325 +555 55500000 555fffff aedd460726622325 +556 55600000 556fffff aedd460726622325 +557 55700000 557fffff aedd460726622325 +558 55800000 558fffff aedd460726622325 +559 55900000 559fffff aedd460726622325 +55a 55a00000 55afffff aedd460726622325 +55b 55b00000 55bfffff aedd460726622325 +55c 55c00000 55cfffff aedd460726622325 +55d 55d00000 55dfffff aedd460726622325 +55e 55e00000 55efffff aedd460726622325 +55f 55f00000 55ffffff aedd460726622325 +560 56000000 560fffff aedd460726622325 +561 56100000 561fffff aedd460726622325 +562 56200000 562fffff aedd460726622325 +563 56300000 563fffff aedd460726622325 +564 56400000 564fffff aedd460726622325 +565 56500000 565fffff aedd460726622325 +566 56600000 566fffff aedd460726622325 +567 56700000 567fffff aedd460726622325 +568 56800000 568fffff aedd460726622325 +569 56900000 569fffff aedd460726622325 +56a 56a00000 56afffff aedd460726622325 +56b 56b00000 56bfffff aedd460726622325 +56c 56c00000 56cfffff aedd460726622325 +56d 56d00000 56dfffff aedd460726622325 +56e 56e00000 56efffff aedd460726622325 +56f 56f00000 56ffffff aedd460726622325 +570 57000000 570fffff aedd460726622325 +571 57100000 571fffff aedd460726622325 +572 57200000 572fffff aedd460726622325 +573 57300000 573fffff aedd460726622325 +574 57400000 574fffff aedd460726622325 +575 57500000 575fffff aedd460726622325 +576 57600000 576fffff aedd460726622325 +577 57700000 577fffff aedd460726622325 +578 57800000 578fffff aedd460726622325 +579 57900000 579fffff aedd460726622325 +57a 57a00000 57afffff aedd460726622325 +57b 57b00000 57bfffff aedd460726622325 +57c 57c00000 57cfffff aedd460726622325 +57d 57d00000 57dfffff aedd460726622325 +57e 57e00000 57efffff aedd460726622325 +57f 57f00000 57ffffff aedd460726622325 +580 58000000 580fffff aedd460726622325 +581 58100000 581fffff aedd460726622325 +582 58200000 582fffff aedd460726622325 +583 58300000 583fffff aedd460726622325 +584 58400000 584fffff aedd460726622325 +585 58500000 585fffff aedd460726622325 +586 58600000 586fffff aedd460726622325 +587 58700000 587fffff aedd460726622325 +588 58800000 588fffff aedd460726622325 +589 58900000 589fffff aedd460726622325 +58a 58a00000 58afffff aedd460726622325 +58b 58b00000 58bfffff aedd460726622325 +58c 58c00000 58cfffff aedd460726622325 +58d 58d00000 58dfffff aedd460726622325 +58e 58e00000 58efffff aedd460726622325 +58f 58f00000 58ffffff aedd460726622325 +590 59000000 590fffff aedd460726622325 +591 59100000 591fffff aedd460726622325 +592 59200000 592fffff aedd460726622325 +593 59300000 593fffff aedd460726622325 +594 59400000 594fffff aedd460726622325 +595 59500000 595fffff aedd460726622325 +596 59600000 596fffff aedd460726622325 +597 59700000 597fffff aedd460726622325 +598 59800000 598fffff aedd460726622325 +599 59900000 599fffff aedd460726622325 +59a 59a00000 59afffff aedd460726622325 +59b 59b00000 59bfffff aedd460726622325 +59c 59c00000 59cfffff aedd460726622325 +59d 59d00000 59dfffff aedd460726622325 +59e 59e00000 59efffff aedd460726622325 +59f 59f00000 59ffffff aedd460726622325 +5a0 5a000000 5a0fffff aedd460726622325 +5a1 5a100000 5a1fffff aedd460726622325 +5a2 5a200000 5a2fffff aedd460726622325 +5a3 5a300000 5a3fffff aedd460726622325 +5a4 5a400000 5a4fffff aedd460726622325 +5a5 5a500000 5a5fffff aedd460726622325 +5a6 5a600000 5a6fffff aedd460726622325 +5a7 5a700000 5a7fffff aedd460726622325 +5a8 5a800000 5a8fffff aedd460726622325 +5a9 5a900000 5a9fffff aedd460726622325 +5aa 5aa00000 5aafffff aedd460726622325 +5ab 5ab00000 5abfffff aedd460726622325 +5ac 5ac00000 5acfffff aedd460726622325 +5ad 5ad00000 5adfffff aedd460726622325 +5ae 5ae00000 5aefffff aedd460726622325 +5af 5af00000 5affffff aedd460726622325 +5b0 5b000000 5b0fffff aedd460726622325 +5b1 5b100000 5b1fffff aedd460726622325 +5b2 5b200000 5b2fffff aedd460726622325 +5b3 5b300000 5b3fffff aedd460726622325 +5b4 5b400000 5b4fffff aedd460726622325 +5b5 5b500000 5b5fffff aedd460726622325 +5b6 5b600000 5b6fffff aedd460726622325 +5b7 5b700000 5b7fffff aedd460726622325 +5b8 5b800000 5b8fffff aedd460726622325 +5b9 5b900000 5b9fffff aedd460726622325 +5ba 5ba00000 5bafffff aedd460726622325 +5bb 5bb00000 5bbfffff aedd460726622325 +5bc 5bc00000 5bcfffff aedd460726622325 +5bd 5bd00000 5bdfffff aedd460726622325 +5be 5be00000 5befffff aedd460726622325 +5bf 5bf00000 5bffffff aedd460726622325 +5c0 5c000000 5c0fffff aedd460726622325 +5c1 5c100000 5c1fffff aedd460726622325 +5c2 5c200000 5c2fffff aedd460726622325 +5c3 5c300000 5c3fffff aedd460726622325 +5c4 5c400000 5c4fffff aedd460726622325 +5c5 5c500000 5c5fffff aedd460726622325 +5c6 5c600000 5c6fffff aedd460726622325 +5c7 5c700000 5c7fffff aedd460726622325 +5c8 5c800000 5c8fffff aedd460726622325 +5c9 5c900000 5c9fffff aedd460726622325 +5ca 5ca00000 5cafffff aedd460726622325 +5cb 5cb00000 5cbfffff aedd460726622325 +5cc 5cc00000 5ccfffff aedd460726622325 +5cd 5cd00000 5cdfffff aedd460726622325 +5ce 5ce00000 5cefffff aedd460726622325 +5cf 5cf00000 5cffffff aedd460726622325 +5d0 5d000000 5d0fffff aedd460726622325 +5d1 5d100000 5d1fffff aedd460726622325 +5d2 5d200000 5d2fffff aedd460726622325 +5d3 5d300000 5d3fffff aedd460726622325 +5d4 5d400000 5d4fffff aedd460726622325 +5d5 5d500000 5d5fffff aedd460726622325 +5d6 5d600000 5d6fffff aedd460726622325 +5d7 5d700000 5d7fffff aedd460726622325 +5d8 5d800000 5d8fffff aedd460726622325 +5d9 5d900000 5d9fffff aedd460726622325 +5da 5da00000 5dafffff aedd460726622325 +5db 5db00000 5dbfffff aedd460726622325 +5dc 5dc00000 5dcfffff aedd460726622325 +5dd 5dd00000 5ddfffff aedd460726622325 +5de 5de00000 5defffff aedd460726622325 +5df 5df00000 5dffffff aedd460726622325 +5e0 5e000000 5e0fffff aedd460726622325 +5e1 5e100000 5e1fffff aedd460726622325 +5e2 5e200000 5e2fffff aedd460726622325 +5e3 5e300000 5e3fffff aedd460726622325 +5e4 5e400000 5e4fffff aedd460726622325 +5e5 5e500000 5e5fffff aedd460726622325 +5e6 5e600000 5e6fffff aedd460726622325 +5e7 5e700000 5e7fffff aedd460726622325 +5e8 5e800000 5e8fffff aedd460726622325 +5e9 5e900000 5e9fffff aedd460726622325 +5ea 5ea00000 5eafffff aedd460726622325 +5eb 5eb00000 5ebfffff aedd460726622325 +5ec 5ec00000 5ecfffff aedd460726622325 +5ed 5ed00000 5edfffff aedd460726622325 +5ee 5ee00000 5eefffff aedd460726622325 +5ef 5ef00000 5effffff aedd460726622325 +5f0 5f000000 5f0fffff aedd460726622325 +5f1 5f100000 5f1fffff aedd460726622325 +5f2 5f200000 5f2fffff aedd460726622325 +5f3 5f300000 5f3fffff aedd460726622325 +5f4 5f400000 5f4fffff aedd460726622325 +5f5 5f500000 5f5fffff aedd460726622325 +5f6 5f600000 5f6fffff aedd460726622325 +5f7 5f700000 5f7fffff aedd460726622325 +5f8 5f800000 5f8fffff aedd460726622325 +5f9 5f900000 5f9fffff aedd460726622325 +5fa 5fa00000 5fafffff aedd460726622325 +5fb 5fb00000 5fbfffff aedd460726622325 +5fc 5fc00000 5fcfffff aedd460726622325 +5fd 5fd00000 5fdfffff aedd460726622325 +5fe 5fe00000 5fefffff aedd460726622325 +5ff 5ff00000 5fffffff aedd460726622325 +600 60000000 600fffff aedd460726622325 +601 60100000 601fffff aedd460726622325 +602 60200000 602fffff aedd460726622325 +603 60300000 603fffff aedd460726622325 +604 60400000 604fffff aedd460726622325 +605 60500000 605fffff aedd460726622325 +606 60600000 606fffff aedd460726622325 +607 60700000 607fffff aedd460726622325 +608 60800000 608fffff aedd460726622325 +609 60900000 609fffff aedd460726622325 +60a 60a00000 60afffff aedd460726622325 +60b 60b00000 60bfffff aedd460726622325 +60c 60c00000 60cfffff aedd460726622325 +60d 60d00000 60dfffff aedd460726622325 +60e 60e00000 60efffff aedd460726622325 +60f 60f00000 60ffffff aedd460726622325 +610 61000000 610fffff aedd460726622325 +611 61100000 611fffff aedd460726622325 +612 61200000 612fffff aedd460726622325 +613 61300000 613fffff aedd460726622325 +614 61400000 614fffff aedd460726622325 +615 61500000 615fffff aedd460726622325 +616 61600000 616fffff aedd460726622325 +617 61700000 617fffff aedd460726622325 +618 61800000 618fffff aedd460726622325 +619 61900000 619fffff aedd460726622325 +61a 61a00000 61afffff aedd460726622325 +61b 61b00000 61bfffff aedd460726622325 +61c 61c00000 61cfffff aedd460726622325 +61d 61d00000 61dfffff aedd460726622325 +61e 61e00000 61efffff aedd460726622325 +61f 61f00000 61ffffff aedd460726622325 +620 62000000 620fffff aedd460726622325 +621 62100000 621fffff aedd460726622325 +622 62200000 622fffff aedd460726622325 +623 62300000 623fffff aedd460726622325 +624 62400000 624fffff aedd460726622325 +625 62500000 625fffff aedd460726622325 +626 62600000 626fffff aedd460726622325 +627 62700000 627fffff aedd460726622325 +628 62800000 628fffff aedd460726622325 +629 62900000 629fffff aedd460726622325 +62a 62a00000 62afffff aedd460726622325 +62b 62b00000 62bfffff aedd460726622325 +62c 62c00000 62cfffff aedd460726622325 +62d 62d00000 62dfffff aedd460726622325 +62e 62e00000 62efffff aedd460726622325 +62f 62f00000 62ffffff aedd460726622325 +630 63000000 630fffff aedd460726622325 +631 63100000 631fffff aedd460726622325 +632 63200000 632fffff aedd460726622325 +633 63300000 633fffff aedd460726622325 +634 63400000 634fffff aedd460726622325 +635 63500000 635fffff aedd460726622325 +636 63600000 636fffff aedd460726622325 +637 63700000 637fffff aedd460726622325 +638 63800000 638fffff aedd460726622325 +639 63900000 639fffff aedd460726622325 +63a 63a00000 63afffff aedd460726622325 +63b 63b00000 63bfffff aedd460726622325 +63c 63c00000 63cfffff aedd460726622325 +63d 63d00000 63dfffff aedd460726622325 +63e 63e00000 63efffff aedd460726622325 +63f 63f00000 63ffffff aedd460726622325 +640 64000000 640fffff aedd460726622325 +641 64100000 641fffff aedd460726622325 +642 64200000 642fffff aedd460726622325 +643 64300000 643fffff aedd460726622325 +644 64400000 644fffff aedd460726622325 +645 64500000 645fffff aedd460726622325 +646 64600000 646fffff aedd460726622325 +647 64700000 647fffff aedd460726622325 +648 64800000 648fffff aedd460726622325 +649 64900000 649fffff aedd460726622325 +64a 64a00000 64afffff aedd460726622325 +64b 64b00000 64bfffff aedd460726622325 +64c 64c00000 64cfffff aedd460726622325 +64d 64d00000 64dfffff aedd460726622325 +64e 64e00000 64efffff aedd460726622325 +64f 64f00000 64ffffff aedd460726622325 +650 65000000 650fffff aedd460726622325 +651 65100000 651fffff aedd460726622325 +652 65200000 652fffff aedd460726622325 +653 65300000 653fffff aedd460726622325 +654 65400000 654fffff aedd460726622325 +655 65500000 655fffff aedd460726622325 +656 65600000 656fffff aedd460726622325 +657 65700000 657fffff aedd460726622325 +658 65800000 658fffff aedd460726622325 +659 65900000 659fffff aedd460726622325 +65a 65a00000 65afffff aedd460726622325 +65b 65b00000 65bfffff aedd460726622325 +65c 65c00000 65cfffff aedd460726622325 +65d 65d00000 65dfffff aedd460726622325 +65e 65e00000 65efffff aedd460726622325 +65f 65f00000 65ffffff aedd460726622325 +660 66000000 660fffff aedd460726622325 +661 66100000 661fffff aedd460726622325 +662 66200000 662fffff aedd460726622325 +663 66300000 663fffff aedd460726622325 +664 66400000 664fffff aedd460726622325 +665 66500000 665fffff aedd460726622325 +666 66600000 666fffff aedd460726622325 +667 66700000 667fffff aedd460726622325 +668 66800000 668fffff aedd460726622325 +669 66900000 669fffff aedd460726622325 +66a 66a00000 66afffff aedd460726622325 +66b 66b00000 66bfffff aedd460726622325 +66c 66c00000 66cfffff aedd460726622325 +66d 66d00000 66dfffff aedd460726622325 +66e 66e00000 66efffff aedd460726622325 +66f 66f00000 66ffffff aedd460726622325 +670 67000000 670fffff aedd460726622325 +671 67100000 671fffff aedd460726622325 +672 67200000 672fffff aedd460726622325 +673 67300000 673fffff aedd460726622325 +674 67400000 674fffff aedd460726622325 +675 67500000 675fffff aedd460726622325 +676 67600000 676fffff aedd460726622325 +677 67700000 677fffff aedd460726622325 +678 67800000 678fffff aedd460726622325 +679 67900000 679fffff aedd460726622325 +67a 67a00000 67afffff aedd460726622325 +67b 67b00000 67bfffff aedd460726622325 +67c 67c00000 67cfffff aedd460726622325 +67d 67d00000 67dfffff aedd460726622325 +67e 67e00000 67efffff aedd460726622325 +67f 67f00000 67ffffff aedd460726622325 +680 68000000 680fffff aedd460726622325 +681 68100000 681fffff aedd460726622325 +682 68200000 682fffff aedd460726622325 +683 68300000 683fffff aedd460726622325 +684 68400000 684fffff aedd460726622325 +685 68500000 685fffff aedd460726622325 +686 68600000 686fffff aedd460726622325 +687 68700000 687fffff aedd460726622325 +688 68800000 688fffff aedd460726622325 +689 68900000 689fffff aedd460726622325 +68a 68a00000 68afffff aedd460726622325 +68b 68b00000 68bfffff aedd460726622325 +68c 68c00000 68cfffff aedd460726622325 +68d 68d00000 68dfffff aedd460726622325 +68e 68e00000 68efffff aedd460726622325 +68f 68f00000 68ffffff aedd460726622325 +690 69000000 690fffff aedd460726622325 +691 69100000 691fffff aedd460726622325 +692 69200000 692fffff aedd460726622325 +693 69300000 693fffff aedd460726622325 +694 69400000 694fffff aedd460726622325 +695 69500000 695fffff aedd460726622325 +696 69600000 696fffff aedd460726622325 +697 69700000 697fffff aedd460726622325 +698 69800000 698fffff aedd460726622325 +699 69900000 699fffff aedd460726622325 +69a 69a00000 69afffff aedd460726622325 +69b 69b00000 69bfffff aedd460726622325 +69c 69c00000 69cfffff aedd460726622325 +69d 69d00000 69dfffff aedd460726622325 +69e 69e00000 69efffff aedd460726622325 +69f 69f00000 69ffffff aedd460726622325 +6a0 6a000000 6a0fffff aedd460726622325 +6a1 6a100000 6a1fffff aedd460726622325 +6a2 6a200000 6a2fffff aedd460726622325 +6a3 6a300000 6a3fffff aedd460726622325 +6a4 6a400000 6a4fffff aedd460726622325 +6a5 6a500000 6a5fffff aedd460726622325 +6a6 6a600000 6a6fffff aedd460726622325 +6a7 6a700000 6a7fffff aedd460726622325 +6a8 6a800000 6a8fffff aedd460726622325 +6a9 6a900000 6a9fffff aedd460726622325 +6aa 6aa00000 6aafffff aedd460726622325 +6ab 6ab00000 6abfffff aedd460726622325 +6ac 6ac00000 6acfffff aedd460726622325 +6ad 6ad00000 6adfffff aedd460726622325 +6ae 6ae00000 6aefffff aedd460726622325 +6af 6af00000 6affffff aedd460726622325 +6b0 6b000000 6b0fffff aedd460726622325 +6b1 6b100000 6b1fffff aedd460726622325 +6b2 6b200000 6b2fffff aedd460726622325 +6b3 6b300000 6b3fffff aedd460726622325 +6b4 6b400000 6b4fffff aedd460726622325 +6b5 6b500000 6b5fffff aedd460726622325 +6b6 6b600000 6b6fffff aedd460726622325 +6b7 6b700000 6b7fffff aedd460726622325 +6b8 6b800000 6b8fffff aedd460726622325 +6b9 6b900000 6b9fffff aedd460726622325 +6ba 6ba00000 6bafffff aedd460726622325 +6bb 6bb00000 6bbfffff aedd460726622325 +6bc 6bc00000 6bcfffff aedd460726622325 +6bd 6bd00000 6bdfffff aedd460726622325 +6be 6be00000 6befffff aedd460726622325 +6bf 6bf00000 6bffffff aedd460726622325 +6c0 6c000000 6c0fffff aedd460726622325 +6c1 6c100000 6c1fffff aedd460726622325 +6c2 6c200000 6c2fffff aedd460726622325 +6c3 6c300000 6c3fffff aedd460726622325 +6c4 6c400000 6c4fffff aedd460726622325 +6c5 6c500000 6c5fffff aedd460726622325 +6c6 6c600000 6c6fffff aedd460726622325 +6c7 6c700000 6c7fffff aedd460726622325 +6c8 6c800000 6c8fffff aedd460726622325 +6c9 6c900000 6c9fffff aedd460726622325 +6ca 6ca00000 6cafffff aedd460726622325 +6cb 6cb00000 6cbfffff aedd460726622325 +6cc 6cc00000 6ccfffff aedd460726622325 +6cd 6cd00000 6cdfffff aedd460726622325 +6ce 6ce00000 6cefffff aedd460726622325 +6cf 6cf00000 6cffffff aedd460726622325 +6d0 6d000000 6d0fffff aedd460726622325 +6d1 6d100000 6d1fffff aedd460726622325 +6d2 6d200000 6d2fffff aedd460726622325 +6d3 6d300000 6d3fffff aedd460726622325 +6d4 6d400000 6d4fffff aedd460726622325 +6d5 6d500000 6d5fffff aedd460726622325 +6d6 6d600000 6d6fffff aedd460726622325 +6d7 6d700000 6d7fffff aedd460726622325 +6d8 6d800000 6d8fffff aedd460726622325 +6d9 6d900000 6d9fffff aedd460726622325 +6da 6da00000 6dafffff aedd460726622325 +6db 6db00000 6dbfffff aedd460726622325 +6dc 6dc00000 6dcfffff aedd460726622325 +6dd 6dd00000 6ddfffff aedd460726622325 +6de 6de00000 6defffff aedd460726622325 +6df 6df00000 6dffffff aedd460726622325 +6e0 6e000000 6e0fffff aedd460726622325 +6e1 6e100000 6e1fffff aedd460726622325 +6e2 6e200000 6e2fffff aedd460726622325 +6e3 6e300000 6e3fffff aedd460726622325 +6e4 6e400000 6e4fffff aedd460726622325 +6e5 6e500000 6e5fffff aedd460726622325 +6e6 6e600000 6e6fffff aedd460726622325 +6e7 6e700000 6e7fffff aedd460726622325 +6e8 6e800000 6e8fffff aedd460726622325 +6e9 6e900000 6e9fffff aedd460726622325 +6ea 6ea00000 6eafffff aedd460726622325 +6eb 6eb00000 6ebfffff aedd460726622325 +6ec 6ec00000 6ecfffff aedd460726622325 +6ed 6ed00000 6edfffff aedd460726622325 +6ee 6ee00000 6eefffff aedd460726622325 +6ef 6ef00000 6effffff aedd460726622325 +6f0 6f000000 6f0fffff aedd460726622325 +6f1 6f100000 6f1fffff aedd460726622325 +6f2 6f200000 6f2fffff aedd460726622325 +6f3 6f300000 6f3fffff aedd460726622325 +6f4 6f400000 6f4fffff aedd460726622325 +6f5 6f500000 6f5fffff aedd460726622325 +6f6 6f600000 6f6fffff aedd460726622325 +6f7 6f700000 6f7fffff aedd460726622325 +6f8 6f800000 6f8fffff aedd460726622325 +6f9 6f900000 6f9fffff aedd460726622325 +6fa 6fa00000 6fafffff aedd460726622325 +6fb 6fb00000 6fbfffff aedd460726622325 +6fc 6fc00000 6fcfffff aedd460726622325 +6fd 6fd00000 6fdfffff aedd460726622325 +6fe 6fe00000 6fefffff aedd460726622325 +6ff 6ff00000 6fffffff aedd460726622325 +700 70000000 700fffff aedd460726622325 +701 70100000 701fffff aedd460726622325 +702 70200000 702fffff aedd460726622325 +703 70300000 703fffff aedd460726622325 +704 70400000 704fffff aedd460726622325 +705 70500000 705fffff aedd460726622325 +706 70600000 706fffff aedd460726622325 +707 70700000 707fffff aedd460726622325 +708 70800000 708fffff aedd460726622325 +709 70900000 709fffff aedd460726622325 +70a 70a00000 70afffff aedd460726622325 +70b 70b00000 70bfffff aedd460726622325 +70c 70c00000 70cfffff aedd460726622325 +70d 70d00000 70dfffff aedd460726622325 +70e 70e00000 70efffff aedd460726622325 +70f 70f00000 70ffffff aedd460726622325 +710 71000000 710fffff aedd460726622325 +711 71100000 711fffff aedd460726622325 +712 71200000 712fffff aedd460726622325 +713 71300000 713fffff aedd460726622325 +714 71400000 714fffff aedd460726622325 +715 71500000 715fffff aedd460726622325 +716 71600000 716fffff aedd460726622325 +717 71700000 717fffff aedd460726622325 +718 71800000 718fffff aedd460726622325 +719 71900000 719fffff aedd460726622325 +71a 71a00000 71afffff aedd460726622325 +71b 71b00000 71bfffff aedd460726622325 +71c 71c00000 71cfffff aedd460726622325 +71d 71d00000 71dfffff aedd460726622325 +71e 71e00000 71efffff aedd460726622325 +71f 71f00000 71ffffff aedd460726622325 +720 72000000 720fffff aedd460726622325 +721 72100000 721fffff aedd460726622325 +722 72200000 722fffff aedd460726622325 +723 72300000 723fffff aedd460726622325 +724 72400000 724fffff aedd460726622325 +725 72500000 725fffff aedd460726622325 +726 72600000 726fffff aedd460726622325 +727 72700000 727fffff aedd460726622325 +728 72800000 728fffff aedd460726622325 +729 72900000 729fffff aedd460726622325 +72a 72a00000 72afffff aedd460726622325 +72b 72b00000 72bfffff aedd460726622325 +72c 72c00000 72cfffff aedd460726622325 +72d 72d00000 72dfffff aedd460726622325 +72e 72e00000 72efffff aedd460726622325 +72f 72f00000 72ffffff aedd460726622325 +730 73000000 730fffff aedd460726622325 +731 73100000 731fffff aedd460726622325 +732 73200000 732fffff aedd460726622325 +733 73300000 733fffff aedd460726622325 +734 73400000 734fffff aedd460726622325 +735 73500000 735fffff aedd460726622325 +736 73600000 736fffff aedd460726622325 +737 73700000 737fffff aedd460726622325 +738 73800000 738fffff aedd460726622325 +739 73900000 739fffff aedd460726622325 +73a 73a00000 73afffff aedd460726622325 +73b 73b00000 73bfffff aedd460726622325 +73c 73c00000 73cfffff aedd460726622325 +73d 73d00000 73dfffff aedd460726622325 +73e 73e00000 73efffff aedd460726622325 +73f 73f00000 73ffffff aedd460726622325 +740 74000000 740fffff aedd460726622325 +741 74100000 741fffff aedd460726622325 +742 74200000 742fffff aedd460726622325 +743 74300000 743fffff aedd460726622325 +744 74400000 744fffff aedd460726622325 +745 74500000 745fffff aedd460726622325 +746 74600000 746fffff aedd460726622325 +747 74700000 747fffff aedd460726622325 +748 74800000 748fffff aedd460726622325 +749 74900000 749fffff aedd460726622325 +74a 74a00000 74afffff aedd460726622325 +74b 74b00000 74bfffff aedd460726622325 +74c 74c00000 74cfffff aedd460726622325 +74d 74d00000 74dfffff aedd460726622325 +74e 74e00000 74efffff aedd460726622325 +74f 74f00000 74ffffff aedd460726622325 +750 75000000 750fffff aedd460726622325 +751 75100000 751fffff aedd460726622325 +752 75200000 752fffff aedd460726622325 +753 75300000 753fffff aedd460726622325 +754 75400000 754fffff aedd460726622325 +755 75500000 755fffff aedd460726622325 +756 75600000 756fffff aedd460726622325 +757 75700000 757fffff aedd460726622325 +758 75800000 758fffff aedd460726622325 +759 75900000 759fffff aedd460726622325 +75a 75a00000 75afffff aedd460726622325 +75b 75b00000 75bfffff aedd460726622325 +75c 75c00000 75cfffff aedd460726622325 +75d 75d00000 75dfffff aedd460726622325 +75e 75e00000 75efffff aedd460726622325 +75f 75f00000 75ffffff aedd460726622325 +760 76000000 760fffff aedd460726622325 +761 76100000 761fffff aedd460726622325 +762 76200000 762fffff aedd460726622325 +763 76300000 763fffff aedd460726622325 +764 76400000 764fffff aedd460726622325 +765 76500000 765fffff aedd460726622325 +766 76600000 766fffff aedd460726622325 +767 76700000 767fffff aedd460726622325 +768 76800000 768fffff aedd460726622325 +769 76900000 769fffff aedd460726622325 +76a 76a00000 76afffff aedd460726622325 +76b 76b00000 76bfffff aedd460726622325 +76c 76c00000 76cfffff aedd460726622325 +76d 76d00000 76dfffff aedd460726622325 +76e 76e00000 76efffff aedd460726622325 +76f 76f00000 76ffffff aedd460726622325 +770 77000000 770fffff aedd460726622325 +771 77100000 771fffff aedd460726622325 +772 77200000 772fffff aedd460726622325 +773 77300000 773fffff aedd460726622325 +774 77400000 774fffff aedd460726622325 +775 77500000 775fffff aedd460726622325 +776 77600000 776fffff aedd460726622325 +777 77700000 777fffff aedd460726622325 +778 77800000 778fffff aedd460726622325 +779 77900000 779fffff aedd460726622325 +77a 77a00000 77afffff aedd460726622325 +77b 77b00000 77bfffff aedd460726622325 +77c 77c00000 77cfffff aedd460726622325 +77d 77d00000 77dfffff aedd460726622325 +77e 77e00000 77efffff aedd460726622325 +77f 77f00000 77ffffff aedd460726622325 +780 78000000 780fffff aedd460726622325 +781 78100000 781fffff aedd460726622325 +782 78200000 782fffff aedd460726622325 +783 78300000 783fffff aedd460726622325 +784 78400000 784fffff aedd460726622325 +785 78500000 785fffff aedd460726622325 +786 78600000 786fffff aedd460726622325 +787 78700000 787fffff aedd460726622325 +788 78800000 788fffff aedd460726622325 +789 78900000 789fffff aedd460726622325 +78a 78a00000 78afffff aedd460726622325 +78b 78b00000 78bfffff aedd460726622325 +78c 78c00000 78cfffff aedd460726622325 +78d 78d00000 78dfffff aedd460726622325 +78e 78e00000 78efffff aedd460726622325 +78f 78f00000 78ffffff aedd460726622325 +790 79000000 790fffff aedd460726622325 +791 79100000 791fffff aedd460726622325 +792 79200000 792fffff aedd460726622325 +793 79300000 793fffff aedd460726622325 +794 79400000 794fffff aedd460726622325 +795 79500000 795fffff aedd460726622325 +796 79600000 796fffff aedd460726622325 +797 79700000 797fffff aedd460726622325 +798 79800000 798fffff aedd460726622325 +799 79900000 799fffff aedd460726622325 +79a 79a00000 79afffff aedd460726622325 +79b 79b00000 79bfffff aedd460726622325 +79c 79c00000 79cfffff aedd460726622325 +79d 79d00000 79dfffff aedd460726622325 +79e 79e00000 79efffff aedd460726622325 +79f 79f00000 79ffffff aedd460726622325 +7a0 7a000000 7a0fffff aedd460726622325 +7a1 7a100000 7a1fffff aedd460726622325 +7a2 7a200000 7a2fffff aedd460726622325 +7a3 7a300000 7a3fffff aedd460726622325 +7a4 7a400000 7a4fffff aedd460726622325 +7a5 7a500000 7a5fffff aedd460726622325 +7a6 7a600000 7a6fffff aedd460726622325 +7a7 7a700000 7a7fffff aedd460726622325 +7a8 7a800000 7a8fffff aedd460726622325 +7a9 7a900000 7a9fffff aedd460726622325 +7aa 7aa00000 7aafffff aedd460726622325 +7ab 7ab00000 7abfffff aedd460726622325 +7ac 7ac00000 7acfffff aedd460726622325 +7ad 7ad00000 7adfffff aedd460726622325 +7ae 7ae00000 7aefffff aedd460726622325 +7af 7af00000 7affffff aedd460726622325 +7b0 7b000000 7b0fffff aedd460726622325 +7b1 7b100000 7b1fffff aedd460726622325 +7b2 7b200000 7b2fffff aedd460726622325 +7b3 7b300000 7b3fffff aedd460726622325 +7b4 7b400000 7b4fffff aedd460726622325 +7b5 7b500000 7b5fffff aedd460726622325 +7b6 7b600000 7b6fffff aedd460726622325 +7b7 7b700000 7b7fffff aedd460726622325 +7b8 7b800000 7b8fffff aedd460726622325 +7b9 7b900000 7b9fffff aedd460726622325 +7ba 7ba00000 7bafffff aedd460726622325 +7bb 7bb00000 7bbfffff aedd460726622325 +7bc 7bc00000 7bcfffff aedd460726622325 +7bd 7bd00000 7bdfffff aedd460726622325 +7be 7be00000 7befffff aedd460726622325 +7bf 7bf00000 7bffffff aedd460726622325 +7c0 7c000000 7c0fffff aedd460726622325 +7c1 7c100000 7c1fffff aedd460726622325 +7c2 7c200000 7c2fffff aedd460726622325 +7c3 7c300000 7c3fffff aedd460726622325 +7c4 7c400000 7c4fffff aedd460726622325 +7c5 7c500000 7c5fffff aedd460726622325 +7c6 7c600000 7c6fffff aedd460726622325 +7c7 7c700000 7c7fffff aedd460726622325 +7c8 7c800000 7c8fffff aedd460726622325 +7c9 7c900000 7c9fffff aedd460726622325 +7ca 7ca00000 7cafffff aedd460726622325 +7cb 7cb00000 7cbfffff aedd460726622325 +7cc 7cc00000 7ccfffff aedd460726622325 +7cd 7cd00000 7cdfffff aedd460726622325 +7ce 7ce00000 7cefffff aedd460726622325 +7cf 7cf00000 7cffffff aedd460726622325 +7d0 7d000000 7d0fffff aedd460726622325 +7d1 7d100000 7d1fffff aedd460726622325 +7d2 7d200000 7d2fffff aedd460726622325 +7d3 7d300000 7d3fffff aedd460726622325 +7d4 7d400000 7d4fffff aedd460726622325 +7d5 7d500000 7d5fffff aedd460726622325 +7d6 7d600000 7d6fffff aedd460726622325 +7d7 7d700000 7d7fffff aedd460726622325 +7d8 7d800000 7d8fffff aedd460726622325 +7d9 7d900000 7d9fffff aedd460726622325 +7da 7da00000 7dafffff aedd460726622325 +7db 7db00000 7dbfffff aedd460726622325 +7dc 7dc00000 7dcfffff aedd460726622325 +7dd 7dd00000 7ddfffff aedd460726622325 +7de 7de00000 7defffff aedd460726622325 +7df 7df00000 7dffffff aedd460726622325 +7e0 7e000000 7e0fffff aedd460726622325 +7e1 7e100000 7e1fffff aedd460726622325 +7e2 7e200000 7e2fffff aedd460726622325 +7e3 7e300000 7e3fffff aedd460726622325 +7e4 7e400000 7e4fffff aedd460726622325 +7e5 7e500000 7e5fffff aedd460726622325 +7e6 7e600000 7e6fffff aedd460726622325 +7e7 7e700000 7e7fffff aedd460726622325 +7e8 7e800000 7e8fffff aedd460726622325 +7e9 7e900000 7e9fffff aedd460726622325 +7ea 7ea00000 7eafffff aedd460726622325 +7eb 7eb00000 7ebfffff aedd460726622325 +7ec 7ec00000 7ecfffff aedd460726622325 +7ed 7ed00000 7edfffff aedd460726622325 +7ee 7ee00000 7eefffff aedd460726622325 +7ef 7ef00000 7effffff aedd460726622325 +7f0 7f000000 7f0fffff aedd460726622325 +7f1 7f100000 7f1fffff aedd460726622325 +7f2 7f200000 7f2fffff aedd460726622325 +7f3 7f300000 7f3fffff aedd460726622325 +7f4 7f400000 7f4fffff aedd460726622325 +7f5 7f500000 7f5fffff aedd460726622325 +7f6 7f600000 7f6fffff aedd460726622325 +7f7 7f700000 7f7fffff aedd460726622325 +7f8 7f800000 7f8fffff dacbf78aa6f22325 +7f9 7f900000 7f9fffff e02d194a5f722325 +7fa 7fa00000 7fafffff 93d1dce0ccf22325 +7fb 7fb00000 7fbfffff 681aed3447b22325 +7fc 7fc00000 7fcfffff 97952a9da6b22325 +7fd 7fd00000 7fdfffff e02d194a5f722325 +7fe 7fe00000 7fefffff 93d1dce0ccf22325 +7ff 7ff00000 7fffffff 681aed3447b22325 +800 80000000 800fffff 70a8716626622325 +801 80100000 801fffff 70a8716626622325 +802 80200000 802fffff 70a8716626622325 +803 80300000 803fffff 70a8716626622325 +804 80400000 804fffff 70a8716626622325 +805 80500000 805fffff 70a8716626622325 +806 80600000 806fffff 70a8716626622325 +807 80700000 807fffff 70a8716626622325 +808 80800000 808fffff 70a8716626622325 +809 80900000 809fffff 70a8716626622325 +80a 80a00000 80afffff 70a8716626622325 +80b 80b00000 80bfffff 70a8716626622325 +80c 80c00000 80cfffff 70a8716626622325 +80d 80d00000 80dfffff 70a8716626622325 +80e 80e00000 80efffff 70a8716626622325 +80f 80f00000 80ffffff 70a8716626622325 +810 81000000 810fffff 70a8716626622325 +811 81100000 811fffff 70a8716626622325 +812 81200000 812fffff 70a8716626622325 +813 81300000 813fffff 70a8716626622325 +814 81400000 814fffff 70a8716626622325 +815 81500000 815fffff 70a8716626622325 +816 81600000 816fffff 70a8716626622325 +817 81700000 817fffff 70a8716626622325 +818 81800000 818fffff 70a8716626622325 +819 81900000 819fffff 70a8716626622325 +81a 81a00000 81afffff 70a8716626622325 +81b 81b00000 81bfffff 70a8716626622325 +81c 81c00000 81cfffff 70a8716626622325 +81d 81d00000 81dfffff 70a8716626622325 +81e 81e00000 81efffff 70a8716626622325 +81f 81f00000 81ffffff 70a8716626622325 +820 82000000 820fffff 70a8716626622325 +821 82100000 821fffff 70a8716626622325 +822 82200000 822fffff 70a8716626622325 +823 82300000 823fffff 70a8716626622325 +824 82400000 824fffff 70a8716626622325 +825 82500000 825fffff 70a8716626622325 +826 82600000 826fffff 70a8716626622325 +827 82700000 827fffff 70a8716626622325 +828 82800000 828fffff 70a8716626622325 +829 82900000 829fffff 70a8716626622325 +82a 82a00000 82afffff 70a8716626622325 +82b 82b00000 82bfffff 70a8716626622325 +82c 82c00000 82cfffff 70a8716626622325 +82d 82d00000 82dfffff 70a8716626622325 +82e 82e00000 82efffff 70a8716626622325 +82f 82f00000 82ffffff 70a8716626622325 +830 83000000 830fffff 70a8716626622325 +831 83100000 831fffff 70a8716626622325 +832 83200000 832fffff 70a8716626622325 +833 83300000 833fffff 70a8716626622325 +834 83400000 834fffff 70a8716626622325 +835 83500000 835fffff 70a8716626622325 +836 83600000 836fffff 70a8716626622325 +837 83700000 837fffff 70a8716626622325 +838 83800000 838fffff 70a8716626622325 +839 83900000 839fffff 70a8716626622325 +83a 83a00000 83afffff 70a8716626622325 +83b 83b00000 83bfffff 70a8716626622325 +83c 83c00000 83cfffff 70a8716626622325 +83d 83d00000 83dfffff 70a8716626622325 +83e 83e00000 83efffff 70a8716626622325 +83f 83f00000 83ffffff 70a8716626622325 +840 84000000 840fffff 70a8716626622325 +841 84100000 841fffff 70a8716626622325 +842 84200000 842fffff 70a8716626622325 +843 84300000 843fffff 70a8716626622325 +844 84400000 844fffff 70a8716626622325 +845 84500000 845fffff 70a8716626622325 +846 84600000 846fffff 70a8716626622325 +847 84700000 847fffff 70a8716626622325 +848 84800000 848fffff 70a8716626622325 +849 84900000 849fffff 70a8716626622325 +84a 84a00000 84afffff 70a8716626622325 +84b 84b00000 84bfffff 70a8716626622325 +84c 84c00000 84cfffff 70a8716626622325 +84d 84d00000 84dfffff 70a8716626622325 +84e 84e00000 84efffff 70a8716626622325 +84f 84f00000 84ffffff 70a8716626622325 +850 85000000 850fffff 70a8716626622325 +851 85100000 851fffff 70a8716626622325 +852 85200000 852fffff 70a8716626622325 +853 85300000 853fffff 70a8716626622325 +854 85400000 854fffff 70a8716626622325 +855 85500000 855fffff 70a8716626622325 +856 85600000 856fffff 70a8716626622325 +857 85700000 857fffff 70a8716626622325 +858 85800000 858fffff 70a8716626622325 +859 85900000 859fffff 70a8716626622325 +85a 85a00000 85afffff 70a8716626622325 +85b 85b00000 85bfffff 70a8716626622325 +85c 85c00000 85cfffff 70a8716626622325 +85d 85d00000 85dfffff 70a8716626622325 +85e 85e00000 85efffff 70a8716626622325 +85f 85f00000 85ffffff 70a8716626622325 +860 86000000 860fffff 70a8716626622325 +861 86100000 861fffff 70a8716626622325 +862 86200000 862fffff 70a8716626622325 +863 86300000 863fffff 70a8716626622325 +864 86400000 864fffff 70a8716626622325 +865 86500000 865fffff 70a8716626622325 +866 86600000 866fffff 70a8716626622325 +867 86700000 867fffff 70a8716626622325 +868 86800000 868fffff 70a8716626622325 +869 86900000 869fffff 70a8716626622325 +86a 86a00000 86afffff 70a8716626622325 +86b 86b00000 86bfffff 70a8716626622325 +86c 86c00000 86cfffff 70a8716626622325 +86d 86d00000 86dfffff 70a8716626622325 +86e 86e00000 86efffff 70a8716626622325 +86f 86f00000 86ffffff 70a8716626622325 +870 87000000 870fffff 70a8716626622325 +871 87100000 871fffff 70a8716626622325 +872 87200000 872fffff 70a8716626622325 +873 87300000 873fffff 70a8716626622325 +874 87400000 874fffff 70a8716626622325 +875 87500000 875fffff 70a8716626622325 +876 87600000 876fffff 70a8716626622325 +877 87700000 877fffff 70a8716626622325 +878 87800000 878fffff 70a8716626622325 +879 87900000 879fffff 70a8716626622325 +87a 87a00000 87afffff 70a8716626622325 +87b 87b00000 87bfffff 70a8716626622325 +87c 87c00000 87cfffff 70a8716626622325 +87d 87d00000 87dfffff 70a8716626622325 +87e 87e00000 87efffff 70a8716626622325 +87f 87f00000 87ffffff 70a8716626622325 +880 88000000 880fffff 70a8716626622325 +881 88100000 881fffff 70a8716626622325 +882 88200000 882fffff 70a8716626622325 +883 88300000 883fffff 70a8716626622325 +884 88400000 884fffff 70a8716626622325 +885 88500000 885fffff 70a8716626622325 +886 88600000 886fffff 70a8716626622325 +887 88700000 887fffff 70a8716626622325 +888 88800000 888fffff 70a8716626622325 +889 88900000 889fffff 70a8716626622325 +88a 88a00000 88afffff 70a8716626622325 +88b 88b00000 88bfffff 70a8716626622325 +88c 88c00000 88cfffff 70a8716626622325 +88d 88d00000 88dfffff 70a8716626622325 +88e 88e00000 88efffff 70a8716626622325 +88f 88f00000 88ffffff 70a8716626622325 +890 89000000 890fffff 70a8716626622325 +891 89100000 891fffff 70a8716626622325 +892 89200000 892fffff 70a8716626622325 +893 89300000 893fffff 70a8716626622325 +894 89400000 894fffff 70a8716626622325 +895 89500000 895fffff 70a8716626622325 +896 89600000 896fffff 70a8716626622325 +897 89700000 897fffff 70a8716626622325 +898 89800000 898fffff 70a8716626622325 +899 89900000 899fffff 70a8716626622325 +89a 89a00000 89afffff 70a8716626622325 +89b 89b00000 89bfffff 70a8716626622325 +89c 89c00000 89cfffff 70a8716626622325 +89d 89d00000 89dfffff 70a8716626622325 +89e 89e00000 89efffff 70a8716626622325 +89f 89f00000 89ffffff 70a8716626622325 +8a0 8a000000 8a0fffff 70a8716626622325 +8a1 8a100000 8a1fffff 70a8716626622325 +8a2 8a200000 8a2fffff 70a8716626622325 +8a3 8a300000 8a3fffff 70a8716626622325 +8a4 8a400000 8a4fffff 70a8716626622325 +8a5 8a500000 8a5fffff 70a8716626622325 +8a6 8a600000 8a6fffff 70a8716626622325 +8a7 8a700000 8a7fffff 70a8716626622325 +8a8 8a800000 8a8fffff 70a8716626622325 +8a9 8a900000 8a9fffff 70a8716626622325 +8aa 8aa00000 8aafffff 70a8716626622325 +8ab 8ab00000 8abfffff 70a8716626622325 +8ac 8ac00000 8acfffff 70a8716626622325 +8ad 8ad00000 8adfffff 70a8716626622325 +8ae 8ae00000 8aefffff 70a8716626622325 +8af 8af00000 8affffff 70a8716626622325 +8b0 8b000000 8b0fffff 70a8716626622325 +8b1 8b100000 8b1fffff 70a8716626622325 +8b2 8b200000 8b2fffff 70a8716626622325 +8b3 8b300000 8b3fffff 70a8716626622325 +8b4 8b400000 8b4fffff 70a8716626622325 +8b5 8b500000 8b5fffff 70a8716626622325 +8b6 8b600000 8b6fffff 70a8716626622325 +8b7 8b700000 8b7fffff 70a8716626622325 +8b8 8b800000 8b8fffff 70a8716626622325 +8b9 8b900000 8b9fffff 70a8716626622325 +8ba 8ba00000 8bafffff 70a8716626622325 +8bb 8bb00000 8bbfffff 70a8716626622325 +8bc 8bc00000 8bcfffff 70a8716626622325 +8bd 8bd00000 8bdfffff 70a8716626622325 +8be 8be00000 8befffff 70a8716626622325 +8bf 8bf00000 8bffffff 70a8716626622325 +8c0 8c000000 8c0fffff 70a8716626622325 +8c1 8c100000 8c1fffff 70a8716626622325 +8c2 8c200000 8c2fffff 70a8716626622325 +8c3 8c300000 8c3fffff 70a8716626622325 +8c4 8c400000 8c4fffff 70a8716626622325 +8c5 8c500000 8c5fffff 70a8716626622325 +8c6 8c600000 8c6fffff 70a8716626622325 +8c7 8c700000 8c7fffff 70a8716626622325 +8c8 8c800000 8c8fffff 70a8716626622325 +8c9 8c900000 8c9fffff 70a8716626622325 +8ca 8ca00000 8cafffff 70a8716626622325 +8cb 8cb00000 8cbfffff 70a8716626622325 +8cc 8cc00000 8ccfffff 70a8716626622325 +8cd 8cd00000 8cdfffff 70a8716626622325 +8ce 8ce00000 8cefffff 70a8716626622325 +8cf 8cf00000 8cffffff 70a8716626622325 +8d0 8d000000 8d0fffff 70a8716626622325 +8d1 8d100000 8d1fffff 70a8716626622325 +8d2 8d200000 8d2fffff 70a8716626622325 +8d3 8d300000 8d3fffff 70a8716626622325 +8d4 8d400000 8d4fffff 70a8716626622325 +8d5 8d500000 8d5fffff 70a8716626622325 +8d6 8d600000 8d6fffff 70a8716626622325 +8d7 8d700000 8d7fffff 70a8716626622325 +8d8 8d800000 8d8fffff 70a8716626622325 +8d9 8d900000 8d9fffff 70a8716626622325 +8da 8da00000 8dafffff 70a8716626622325 +8db 8db00000 8dbfffff 70a8716626622325 +8dc 8dc00000 8dcfffff 70a8716626622325 +8dd 8dd00000 8ddfffff 70a8716626622325 +8de 8de00000 8defffff 70a8716626622325 +8df 8df00000 8dffffff 70a8716626622325 +8e0 8e000000 8e0fffff 70a8716626622325 +8e1 8e100000 8e1fffff 70a8716626622325 +8e2 8e200000 8e2fffff 70a8716626622325 +8e3 8e300000 8e3fffff 70a8716626622325 +8e4 8e400000 8e4fffff 70a8716626622325 +8e5 8e500000 8e5fffff 70a8716626622325 +8e6 8e600000 8e6fffff 70a8716626622325 +8e7 8e700000 8e7fffff 70a8716626622325 +8e8 8e800000 8e8fffff 70a8716626622325 +8e9 8e900000 8e9fffff 70a8716626622325 +8ea 8ea00000 8eafffff 70a8716626622325 +8eb 8eb00000 8ebfffff 70a8716626622325 +8ec 8ec00000 8ecfffff 70a8716626622325 +8ed 8ed00000 8edfffff 70a8716626622325 +8ee 8ee00000 8eefffff 70a8716626622325 +8ef 8ef00000 8effffff 70a8716626622325 +8f0 8f000000 8f0fffff 70a8716626622325 +8f1 8f100000 8f1fffff 70a8716626622325 +8f2 8f200000 8f2fffff 70a8716626622325 +8f3 8f300000 8f3fffff 70a8716626622325 +8f4 8f400000 8f4fffff 70a8716626622325 +8f5 8f500000 8f5fffff 70a8716626622325 +8f6 8f600000 8f6fffff 70a8716626622325 +8f7 8f700000 8f7fffff 70a8716626622325 +8f8 8f800000 8f8fffff 70a8716626622325 +8f9 8f900000 8f9fffff 70a8716626622325 +8fa 8fa00000 8fafffff 70a8716626622325 +8fb 8fb00000 8fbfffff 70a8716626622325 +8fc 8fc00000 8fcfffff 70a8716626622325 +8fd 8fd00000 8fdfffff 70a8716626622325 +8fe 8fe00000 8fefffff 70a8716626622325 +8ff 8ff00000 8fffffff 70a8716626622325 +900 90000000 900fffff 70a8716626622325 +901 90100000 901fffff 70a8716626622325 +902 90200000 902fffff 70a8716626622325 +903 90300000 903fffff 70a8716626622325 +904 90400000 904fffff 70a8716626622325 +905 90500000 905fffff 70a8716626622325 +906 90600000 906fffff 70a8716626622325 +907 90700000 907fffff 70a8716626622325 +908 90800000 908fffff 70a8716626622325 +909 90900000 909fffff 70a8716626622325 +90a 90a00000 90afffff 70a8716626622325 +90b 90b00000 90bfffff 70a8716626622325 +90c 90c00000 90cfffff 70a8716626622325 +90d 90d00000 90dfffff 70a8716626622325 +90e 90e00000 90efffff 70a8716626622325 +90f 90f00000 90ffffff 70a8716626622325 +910 91000000 910fffff 70a8716626622325 +911 91100000 911fffff 70a8716626622325 +912 91200000 912fffff 70a8716626622325 +913 91300000 913fffff 70a8716626622325 +914 91400000 914fffff 70a8716626622325 +915 91500000 915fffff 70a8716626622325 +916 91600000 916fffff 70a8716626622325 +917 91700000 917fffff 70a8716626622325 +918 91800000 918fffff 70a8716626622325 +919 91900000 919fffff 70a8716626622325 +91a 91a00000 91afffff 70a8716626622325 +91b 91b00000 91bfffff 70a8716626622325 +91c 91c00000 91cfffff 70a8716626622325 +91d 91d00000 91dfffff 70a8716626622325 +91e 91e00000 91efffff 70a8716626622325 +91f 91f00000 91ffffff 70a8716626622325 +920 92000000 920fffff 70a8716626622325 +921 92100000 921fffff 70a8716626622325 +922 92200000 922fffff 70a8716626622325 +923 92300000 923fffff 70a8716626622325 +924 92400000 924fffff 70a8716626622325 +925 92500000 925fffff 70a8716626622325 +926 92600000 926fffff 70a8716626622325 +927 92700000 927fffff 70a8716626622325 +928 92800000 928fffff 70a8716626622325 +929 92900000 929fffff 70a8716626622325 +92a 92a00000 92afffff 70a8716626622325 +92b 92b00000 92bfffff 70a8716626622325 +92c 92c00000 92cfffff 70a8716626622325 +92d 92d00000 92dfffff 70a8716626622325 +92e 92e00000 92efffff 70a8716626622325 +92f 92f00000 92ffffff 70a8716626622325 +930 93000000 930fffff 70a8716626622325 +931 93100000 931fffff 70a8716626622325 +932 93200000 932fffff 70a8716626622325 +933 93300000 933fffff 70a8716626622325 +934 93400000 934fffff 70a8716626622325 +935 93500000 935fffff 70a8716626622325 +936 93600000 936fffff 70a8716626622325 +937 93700000 937fffff 70a8716626622325 +938 93800000 938fffff 70a8716626622325 +939 93900000 939fffff 70a8716626622325 +93a 93a00000 93afffff 70a8716626622325 +93b 93b00000 93bfffff 70a8716626622325 +93c 93c00000 93cfffff 70a8716626622325 +93d 93d00000 93dfffff 70a8716626622325 +93e 93e00000 93efffff 70a8716626622325 +93f 93f00000 93ffffff 70a8716626622325 +940 94000000 940fffff 70a8716626622325 +941 94100000 941fffff 70a8716626622325 +942 94200000 942fffff 70a8716626622325 +943 94300000 943fffff 70a8716626622325 +944 94400000 944fffff 70a8716626622325 +945 94500000 945fffff 70a8716626622325 +946 94600000 946fffff 70a8716626622325 +947 94700000 947fffff 70a8716626622325 +948 94800000 948fffff 70a8716626622325 +949 94900000 949fffff 70a8716626622325 +94a 94a00000 94afffff 70a8716626622325 +94b 94b00000 94bfffff 70a8716626622325 +94c 94c00000 94cfffff 70a8716626622325 +94d 94d00000 94dfffff 70a8716626622325 +94e 94e00000 94efffff 70a8716626622325 +94f 94f00000 94ffffff 70a8716626622325 +950 95000000 950fffff 70a8716626622325 +951 95100000 951fffff 70a8716626622325 +952 95200000 952fffff 70a8716626622325 +953 95300000 953fffff 70a8716626622325 +954 95400000 954fffff 70a8716626622325 +955 95500000 955fffff 70a8716626622325 +956 95600000 956fffff 70a8716626622325 +957 95700000 957fffff 70a8716626622325 +958 95800000 958fffff 70a8716626622325 +959 95900000 959fffff 70a8716626622325 +95a 95a00000 95afffff 70a8716626622325 +95b 95b00000 95bfffff 70a8716626622325 +95c 95c00000 95cfffff 70a8716626622325 +95d 95d00000 95dfffff 70a8716626622325 +95e 95e00000 95efffff 70a8716626622325 +95f 95f00000 95ffffff 70a8716626622325 +960 96000000 960fffff 70a8716626622325 +961 96100000 961fffff 70a8716626622325 +962 96200000 962fffff 70a8716626622325 +963 96300000 963fffff 70a8716626622325 +964 96400000 964fffff 70a8716626622325 +965 96500000 965fffff 70a8716626622325 +966 96600000 966fffff 70a8716626622325 +967 96700000 967fffff 70a8716626622325 +968 96800000 968fffff 70a8716626622325 +969 96900000 969fffff 70a8716626622325 +96a 96a00000 96afffff 70a8716626622325 +96b 96b00000 96bfffff 70a8716626622325 +96c 96c00000 96cfffff 70a8716626622325 +96d 96d00000 96dfffff 70a8716626622325 +96e 96e00000 96efffff 70a8716626622325 +96f 96f00000 96ffffff 70a8716626622325 +970 97000000 970fffff 70a8716626622325 +971 97100000 971fffff 70a8716626622325 +972 97200000 972fffff 70a8716626622325 +973 97300000 973fffff 70a8716626622325 +974 97400000 974fffff 70a8716626622325 +975 97500000 975fffff 70a8716626622325 +976 97600000 976fffff 70a8716626622325 +977 97700000 977fffff 70a8716626622325 +978 97800000 978fffff 70a8716626622325 +979 97900000 979fffff 70a8716626622325 +97a 97a00000 97afffff 70a8716626622325 +97b 97b00000 97bfffff 70a8716626622325 +97c 97c00000 97cfffff 70a8716626622325 +97d 97d00000 97dfffff 70a8716626622325 +97e 97e00000 97efffff 70a8716626622325 +97f 97f00000 97ffffff 70a8716626622325 +980 98000000 980fffff 70a8716626622325 +981 98100000 981fffff 70a8716626622325 +982 98200000 982fffff 70a8716626622325 +983 98300000 983fffff 70a8716626622325 +984 98400000 984fffff 70a8716626622325 +985 98500000 985fffff 70a8716626622325 +986 98600000 986fffff 70a8716626622325 +987 98700000 987fffff 70a8716626622325 +988 98800000 988fffff 70a8716626622325 +989 98900000 989fffff 70a8716626622325 +98a 98a00000 98afffff 70a8716626622325 +98b 98b00000 98bfffff 70a8716626622325 +98c 98c00000 98cfffff 70a8716626622325 +98d 98d00000 98dfffff 70a8716626622325 +98e 98e00000 98efffff 70a8716626622325 +98f 98f00000 98ffffff 70a8716626622325 +990 99000000 990fffff 70a8716626622325 +991 99100000 991fffff 70a8716626622325 +992 99200000 992fffff 70a8716626622325 +993 99300000 993fffff 70a8716626622325 +994 99400000 994fffff 70a8716626622325 +995 99500000 995fffff 70a8716626622325 +996 99600000 996fffff 70a8716626622325 +997 99700000 997fffff 70a8716626622325 +998 99800000 998fffff 70a8716626622325 +999 99900000 999fffff 70a8716626622325 +99a 99a00000 99afffff 70a8716626622325 +99b 99b00000 99bfffff 70a8716626622325 +99c 99c00000 99cfffff 70a8716626622325 +99d 99d00000 99dfffff 70a8716626622325 +99e 99e00000 99efffff 70a8716626622325 +99f 99f00000 99ffffff 70a8716626622325 +9a0 9a000000 9a0fffff 70a8716626622325 +9a1 9a100000 9a1fffff 70a8716626622325 +9a2 9a200000 9a2fffff 70a8716626622325 +9a3 9a300000 9a3fffff 70a8716626622325 +9a4 9a400000 9a4fffff 70a8716626622325 +9a5 9a500000 9a5fffff 70a8716626622325 +9a6 9a600000 9a6fffff 70a8716626622325 +9a7 9a700000 9a7fffff 70a8716626622325 +9a8 9a800000 9a8fffff 70a8716626622325 +9a9 9a900000 9a9fffff 70a8716626622325 +9aa 9aa00000 9aafffff 70a8716626622325 +9ab 9ab00000 9abfffff 70a8716626622325 +9ac 9ac00000 9acfffff 70a8716626622325 +9ad 9ad00000 9adfffff 70a8716626622325 +9ae 9ae00000 9aefffff 70a8716626622325 +9af 9af00000 9affffff 70a8716626622325 +9b0 9b000000 9b0fffff 70a8716626622325 +9b1 9b100000 9b1fffff 70a8716626622325 +9b2 9b200000 9b2fffff 70a8716626622325 +9b3 9b300000 9b3fffff 70a8716626622325 +9b4 9b400000 9b4fffff 70a8716626622325 +9b5 9b500000 9b5fffff 70a8716626622325 +9b6 9b600000 9b6fffff 70a8716626622325 +9b7 9b700000 9b7fffff 70a8716626622325 +9b8 9b800000 9b8fffff 70a8716626622325 +9b9 9b900000 9b9fffff 70a8716626622325 +9ba 9ba00000 9bafffff 70a8716626622325 +9bb 9bb00000 9bbfffff 70a8716626622325 +9bc 9bc00000 9bcfffff 70a8716626622325 +9bd 9bd00000 9bdfffff 70a8716626622325 +9be 9be00000 9befffff 70a8716626622325 +9bf 9bf00000 9bffffff 70a8716626622325 +9c0 9c000000 9c0fffff 70a8716626622325 +9c1 9c100000 9c1fffff 70a8716626622325 +9c2 9c200000 9c2fffff 70a8716626622325 +9c3 9c300000 9c3fffff 70a8716626622325 +9c4 9c400000 9c4fffff 70a8716626622325 +9c5 9c500000 9c5fffff 70a8716626622325 +9c6 9c600000 9c6fffff 70a8716626622325 +9c7 9c700000 9c7fffff 70a8716626622325 +9c8 9c800000 9c8fffff 70a8716626622325 +9c9 9c900000 9c9fffff 70a8716626622325 +9ca 9ca00000 9cafffff 70a8716626622325 +9cb 9cb00000 9cbfffff 70a8716626622325 +9cc 9cc00000 9ccfffff 70a8716626622325 +9cd 9cd00000 9cdfffff 70a8716626622325 +9ce 9ce00000 9cefffff 70a8716626622325 +9cf 9cf00000 9cffffff 70a8716626622325 +9d0 9d000000 9d0fffff 70a8716626622325 +9d1 9d100000 9d1fffff 70a8716626622325 +9d2 9d200000 9d2fffff 70a8716626622325 +9d3 9d300000 9d3fffff 70a8716626622325 +9d4 9d400000 9d4fffff 70a8716626622325 +9d5 9d500000 9d5fffff 70a8716626622325 +9d6 9d600000 9d6fffff 70a8716626622325 +9d7 9d700000 9d7fffff 70a8716626622325 +9d8 9d800000 9d8fffff 70a8716626622325 +9d9 9d900000 9d9fffff 70a8716626622325 +9da 9da00000 9dafffff 70a8716626622325 +9db 9db00000 9dbfffff 70a8716626622325 +9dc 9dc00000 9dcfffff 70a8716626622325 +9dd 9dd00000 9ddfffff 70a8716626622325 +9de 9de00000 9defffff 70a8716626622325 +9df 9df00000 9dffffff 70a8716626622325 +9e0 9e000000 9e0fffff 70a8716626622325 +9e1 9e100000 9e1fffff 70a8716626622325 +9e2 9e200000 9e2fffff 70a8716626622325 +9e3 9e300000 9e3fffff 70a8716626622325 +9e4 9e400000 9e4fffff 70a8716626622325 +9e5 9e500000 9e5fffff 70a8716626622325 +9e6 9e600000 9e6fffff 70a8716626622325 +9e7 9e700000 9e7fffff 70a8716626622325 +9e8 9e800000 9e8fffff 70a8716626622325 +9e9 9e900000 9e9fffff 70a8716626622325 +9ea 9ea00000 9eafffff 70a8716626622325 +9eb 9eb00000 9ebfffff 70a8716626622325 +9ec 9ec00000 9ecfffff 70a8716626622325 +9ed 9ed00000 9edfffff 70a8716626622325 +9ee 9ee00000 9eefffff 70a8716626622325 +9ef 9ef00000 9effffff 70a8716626622325 +9f0 9f000000 9f0fffff 70a8716626622325 +9f1 9f100000 9f1fffff 70a8716626622325 +9f2 9f200000 9f2fffff 70a8716626622325 +9f3 9f300000 9f3fffff 70a8716626622325 +9f4 9f400000 9f4fffff 70a8716626622325 +9f5 9f500000 9f5fffff 70a8716626622325 +9f6 9f600000 9f6fffff 70a8716626622325 +9f7 9f700000 9f7fffff 70a8716626622325 +9f8 9f800000 9f8fffff 70a8716626622325 +9f9 9f900000 9f9fffff 70a8716626622325 +9fa 9fa00000 9fafffff 70a8716626622325 +9fb 9fb00000 9fbfffff 70a8716626622325 +9fc 9fc00000 9fcfffff 70a8716626622325 +9fd 9fd00000 9fdfffff 70a8716626622325 +9fe 9fe00000 9fefffff 70a8716626622325 +9ff 9ff00000 9fffffff 70a8716626622325 +a00 a0000000 a00fffff 70a8716626622325 +a01 a0100000 a01fffff 70a8716626622325 +a02 a0200000 a02fffff 70a8716626622325 +a03 a0300000 a03fffff 70a8716626622325 +a04 a0400000 a04fffff 70a8716626622325 +a05 a0500000 a05fffff 70a8716626622325 +a06 a0600000 a06fffff 70a8716626622325 +a07 a0700000 a07fffff 70a8716626622325 +a08 a0800000 a08fffff 70a8716626622325 +a09 a0900000 a09fffff 70a8716626622325 +a0a a0a00000 a0afffff 70a8716626622325 +a0b a0b00000 a0bfffff 70a8716626622325 +a0c a0c00000 a0cfffff 70a8716626622325 +a0d a0d00000 a0dfffff 70a8716626622325 +a0e a0e00000 a0efffff 70a8716626622325 +a0f a0f00000 a0ffffff 70a8716626622325 +a10 a1000000 a10fffff 70a8716626622325 +a11 a1100000 a11fffff 70a8716626622325 +a12 a1200000 a12fffff 70a8716626622325 +a13 a1300000 a13fffff 70a8716626622325 +a14 a1400000 a14fffff 70a8716626622325 +a15 a1500000 a15fffff 70a8716626622325 +a16 a1600000 a16fffff 70a8716626622325 +a17 a1700000 a17fffff 70a8716626622325 +a18 a1800000 a18fffff 70a8716626622325 +a19 a1900000 a19fffff 70a8716626622325 +a1a a1a00000 a1afffff 70a8716626622325 +a1b a1b00000 a1bfffff 70a8716626622325 +a1c a1c00000 a1cfffff 70a8716626622325 +a1d a1d00000 a1dfffff 70a8716626622325 +a1e a1e00000 a1efffff 70a8716626622325 +a1f a1f00000 a1ffffff 70a8716626622325 +a20 a2000000 a20fffff 70a8716626622325 +a21 a2100000 a21fffff 70a8716626622325 +a22 a2200000 a22fffff 70a8716626622325 +a23 a2300000 a23fffff 70a8716626622325 +a24 a2400000 a24fffff 70a8716626622325 +a25 a2500000 a25fffff 70a8716626622325 +a26 a2600000 a26fffff 70a8716626622325 +a27 a2700000 a27fffff 70a8716626622325 +a28 a2800000 a28fffff 70a8716626622325 +a29 a2900000 a29fffff 70a8716626622325 +a2a a2a00000 a2afffff 70a8716626622325 +a2b a2b00000 a2bfffff 70a8716626622325 +a2c a2c00000 a2cfffff 70a8716626622325 +a2d a2d00000 a2dfffff 70a8716626622325 +a2e a2e00000 a2efffff 70a8716626622325 +a2f a2f00000 a2ffffff 70a8716626622325 +a30 a3000000 a30fffff 70a8716626622325 +a31 a3100000 a31fffff 70a8716626622325 +a32 a3200000 a32fffff 70a8716626622325 +a33 a3300000 a33fffff 70a8716626622325 +a34 a3400000 a34fffff 70a8716626622325 +a35 a3500000 a35fffff 70a8716626622325 +a36 a3600000 a36fffff 70a8716626622325 +a37 a3700000 a37fffff 70a8716626622325 +a38 a3800000 a38fffff 70a8716626622325 +a39 a3900000 a39fffff 70a8716626622325 +a3a a3a00000 a3afffff 70a8716626622325 +a3b a3b00000 a3bfffff 70a8716626622325 +a3c a3c00000 a3cfffff 70a8716626622325 +a3d a3d00000 a3dfffff 70a8716626622325 +a3e a3e00000 a3efffff 70a8716626622325 +a3f a3f00000 a3ffffff 70a8716626622325 +a40 a4000000 a40fffff 70a8716626622325 +a41 a4100000 a41fffff 70a8716626622325 +a42 a4200000 a42fffff 70a8716626622325 +a43 a4300000 a43fffff 70a8716626622325 +a44 a4400000 a44fffff 70a8716626622325 +a45 a4500000 a45fffff 70a8716626622325 +a46 a4600000 a46fffff 70a8716626622325 +a47 a4700000 a47fffff 70a8716626622325 +a48 a4800000 a48fffff 70a8716626622325 +a49 a4900000 a49fffff 70a8716626622325 +a4a a4a00000 a4afffff 70a8716626622325 +a4b a4b00000 a4bfffff 70a8716626622325 +a4c a4c00000 a4cfffff 70a8716626622325 +a4d a4d00000 a4dfffff 70a8716626622325 +a4e a4e00000 a4efffff 70a8716626622325 +a4f a4f00000 a4ffffff 70a8716626622325 +a50 a5000000 a50fffff 70a8716626622325 +a51 a5100000 a51fffff 70a8716626622325 +a52 a5200000 a52fffff 70a8716626622325 +a53 a5300000 a53fffff 70a8716626622325 +a54 a5400000 a54fffff 70a8716626622325 +a55 a5500000 a55fffff 70a8716626622325 +a56 a5600000 a56fffff 70a8716626622325 +a57 a5700000 a57fffff 70a8716626622325 +a58 a5800000 a58fffff 70a8716626622325 +a59 a5900000 a59fffff 70a8716626622325 +a5a a5a00000 a5afffff 70a8716626622325 +a5b a5b00000 a5bfffff 70a8716626622325 +a5c a5c00000 a5cfffff 70a8716626622325 +a5d a5d00000 a5dfffff 70a8716626622325 +a5e a5e00000 a5efffff 70a8716626622325 +a5f a5f00000 a5ffffff 70a8716626622325 +a60 a6000000 a60fffff 70a8716626622325 +a61 a6100000 a61fffff 70a8716626622325 +a62 a6200000 a62fffff 70a8716626622325 +a63 a6300000 a63fffff 70a8716626622325 +a64 a6400000 a64fffff 70a8716626622325 +a65 a6500000 a65fffff 70a8716626622325 +a66 a6600000 a66fffff 70a8716626622325 +a67 a6700000 a67fffff 70a8716626622325 +a68 a6800000 a68fffff 70a8716626622325 +a69 a6900000 a69fffff 70a8716626622325 +a6a a6a00000 a6afffff 70a8716626622325 +a6b a6b00000 a6bfffff 70a8716626622325 +a6c a6c00000 a6cfffff 70a8716626622325 +a6d a6d00000 a6dfffff 70a8716626622325 +a6e a6e00000 a6efffff 70a8716626622325 +a6f a6f00000 a6ffffff 70a8716626622325 +a70 a7000000 a70fffff 70a8716626622325 +a71 a7100000 a71fffff 70a8716626622325 +a72 a7200000 a72fffff 70a8716626622325 +a73 a7300000 a73fffff 70a8716626622325 +a74 a7400000 a74fffff 70a8716626622325 +a75 a7500000 a75fffff 70a8716626622325 +a76 a7600000 a76fffff 70a8716626622325 +a77 a7700000 a77fffff 70a8716626622325 +a78 a7800000 a78fffff 70a8716626622325 +a79 a7900000 a79fffff 70a8716626622325 +a7a a7a00000 a7afffff 70a8716626622325 +a7b a7b00000 a7bfffff 70a8716626622325 +a7c a7c00000 a7cfffff 70a8716626622325 +a7d a7d00000 a7dfffff 70a8716626622325 +a7e a7e00000 a7efffff 70a8716626622325 +a7f a7f00000 a7ffffff 70a8716626622325 +a80 a8000000 a80fffff 70a8716626622325 +a81 a8100000 a81fffff 70a8716626622325 +a82 a8200000 a82fffff 70a8716626622325 +a83 a8300000 a83fffff 70a8716626622325 +a84 a8400000 a84fffff 70a8716626622325 +a85 a8500000 a85fffff 70a8716626622325 +a86 a8600000 a86fffff 70a8716626622325 +a87 a8700000 a87fffff 70a8716626622325 +a88 a8800000 a88fffff 70a8716626622325 +a89 a8900000 a89fffff 70a8716626622325 +a8a a8a00000 a8afffff 70a8716626622325 +a8b a8b00000 a8bfffff 70a8716626622325 +a8c a8c00000 a8cfffff 70a8716626622325 +a8d a8d00000 a8dfffff 70a8716626622325 +a8e a8e00000 a8efffff 70a8716626622325 +a8f a8f00000 a8ffffff 70a8716626622325 +a90 a9000000 a90fffff 70a8716626622325 +a91 a9100000 a91fffff 70a8716626622325 +a92 a9200000 a92fffff 70a8716626622325 +a93 a9300000 a93fffff 70a8716626622325 +a94 a9400000 a94fffff 70a8716626622325 +a95 a9500000 a95fffff 70a8716626622325 +a96 a9600000 a96fffff 70a8716626622325 +a97 a9700000 a97fffff 70a8716626622325 +a98 a9800000 a98fffff 70a8716626622325 +a99 a9900000 a99fffff 70a8716626622325 +a9a a9a00000 a9afffff 70a8716626622325 +a9b a9b00000 a9bfffff 70a8716626622325 +a9c a9c00000 a9cfffff 70a8716626622325 +a9d a9d00000 a9dfffff 70a8716626622325 +a9e a9e00000 a9efffff 70a8716626622325 +a9f a9f00000 a9ffffff 70a8716626622325 +aa0 aa000000 aa0fffff 70a8716626622325 +aa1 aa100000 aa1fffff 70a8716626622325 +aa2 aa200000 aa2fffff 70a8716626622325 +aa3 aa300000 aa3fffff 70a8716626622325 +aa4 aa400000 aa4fffff 70a8716626622325 +aa5 aa500000 aa5fffff 70a8716626622325 +aa6 aa600000 aa6fffff 70a8716626622325 +aa7 aa700000 aa7fffff 70a8716626622325 +aa8 aa800000 aa8fffff 70a8716626622325 +aa9 aa900000 aa9fffff 70a8716626622325 +aaa aaa00000 aaafffff 70a8716626622325 +aab aab00000 aabfffff 70a8716626622325 +aac aac00000 aacfffff 70a8716626622325 +aad aad00000 aadfffff 70a8716626622325 +aae aae00000 aaefffff 70a8716626622325 +aaf aaf00000 aaffffff 70a8716626622325 +ab0 ab000000 ab0fffff 70a8716626622325 +ab1 ab100000 ab1fffff 70a8716626622325 +ab2 ab200000 ab2fffff 70a8716626622325 +ab3 ab300000 ab3fffff 70a8716626622325 +ab4 ab400000 ab4fffff 70a8716626622325 +ab5 ab500000 ab5fffff 70a8716626622325 +ab6 ab600000 ab6fffff 70a8716626622325 +ab7 ab700000 ab7fffff 70a8716626622325 +ab8 ab800000 ab8fffff 70a8716626622325 +ab9 ab900000 ab9fffff 70a8716626622325 +aba aba00000 abafffff 70a8716626622325 +abb abb00000 abbfffff 70a8716626622325 +abc abc00000 abcfffff 70a8716626622325 +abd abd00000 abdfffff 70a8716626622325 +abe abe00000 abefffff 70a8716626622325 +abf abf00000 abffffff 70a8716626622325 +ac0 ac000000 ac0fffff 70a8716626622325 +ac1 ac100000 ac1fffff 70a8716626622325 +ac2 ac200000 ac2fffff 70a8716626622325 +ac3 ac300000 ac3fffff 70a8716626622325 +ac4 ac400000 ac4fffff 70a8716626622325 +ac5 ac500000 ac5fffff 70a8716626622325 +ac6 ac600000 ac6fffff 70a8716626622325 +ac7 ac700000 ac7fffff 70a8716626622325 +ac8 ac800000 ac8fffff 70a8716626622325 +ac9 ac900000 ac9fffff 70a8716626622325 +aca aca00000 acafffff 70a8716626622325 +acb acb00000 acbfffff 70a8716626622325 +acc acc00000 accfffff 70a8716626622325 +acd acd00000 acdfffff 70a8716626622325 +ace ace00000 acefffff 70a8716626622325 +acf acf00000 acffffff 70a8716626622325 +ad0 ad000000 ad0fffff 70a8716626622325 +ad1 ad100000 ad1fffff 70a8716626622325 +ad2 ad200000 ad2fffff 70a8716626622325 +ad3 ad300000 ad3fffff 70a8716626622325 +ad4 ad400000 ad4fffff 70a8716626622325 +ad5 ad500000 ad5fffff 70a8716626622325 +ad6 ad600000 ad6fffff 70a8716626622325 +ad7 ad700000 ad7fffff 70a8716626622325 +ad8 ad800000 ad8fffff 70a8716626622325 +ad9 ad900000 ad9fffff 70a8716626622325 +ada ada00000 adafffff 70a8716626622325 +adb adb00000 adbfffff 70a8716626622325 +adc adc00000 adcfffff 70a8716626622325 +add add00000 addfffff 70a8716626622325 +ade ade00000 adefffff 70a8716626622325 +adf adf00000 adffffff 70a8716626622325 +ae0 ae000000 ae0fffff 70a8716626622325 +ae1 ae100000 ae1fffff 70a8716626622325 +ae2 ae200000 ae2fffff 70a8716626622325 +ae3 ae300000 ae3fffff 70a8716626622325 +ae4 ae400000 ae4fffff 70a8716626622325 +ae5 ae500000 ae5fffff 70a8716626622325 +ae6 ae600000 ae6fffff 70a8716626622325 +ae7 ae700000 ae7fffff 70a8716626622325 +ae8 ae800000 ae8fffff 70a8716626622325 +ae9 ae900000 ae9fffff 70a8716626622325 +aea aea00000 aeafffff 70a8716626622325 +aeb aeb00000 aebfffff 70a8716626622325 +aec aec00000 aecfffff 70a8716626622325 +aed aed00000 aedfffff 70a8716626622325 +aee aee00000 aeefffff 70a8716626622325 +aef aef00000 aeffffff 70a8716626622325 +af0 af000000 af0fffff 70a8716626622325 +af1 af100000 af1fffff 70a8716626622325 +af2 af200000 af2fffff 70a8716626622325 +af3 af300000 af3fffff 70a8716626622325 +af4 af400000 af4fffff 70a8716626622325 +af5 af500000 af5fffff 70a8716626622325 +af6 af600000 af6fffff 70a8716626622325 +af7 af700000 af7fffff 70a8716626622325 +af8 af800000 af8fffff 70a8716626622325 +af9 af900000 af9fffff 70a8716626622325 +afa afa00000 afafffff 70a8716626622325 +afb afb00000 afbfffff 70a8716626622325 +afc afc00000 afcfffff 70a8716626622325 +afd afd00000 afdfffff 70a8716626622325 +afe afe00000 afefffff 70a8716626622325 +aff aff00000 afffffff 70a8716626622325 +b00 b0000000 b00fffff 70a8716626622325 +b01 b0100000 b01fffff 70a8716626622325 +b02 b0200000 b02fffff 70a8716626622325 +b03 b0300000 b03fffff 70a8716626622325 +b04 b0400000 b04fffff 70a8716626622325 +b05 b0500000 b05fffff 70a8716626622325 +b06 b0600000 b06fffff 70a8716626622325 +b07 b0700000 b07fffff 70a8716626622325 +b08 b0800000 b08fffff 70a8716626622325 +b09 b0900000 b09fffff 70a8716626622325 +b0a b0a00000 b0afffff 70a8716626622325 +b0b b0b00000 b0bfffff 70a8716626622325 +b0c b0c00000 b0cfffff 70a8716626622325 +b0d b0d00000 b0dfffff 70a8716626622325 +b0e b0e00000 b0efffff 70a8716626622325 +b0f b0f00000 b0ffffff 70a8716626622325 +b10 b1000000 b10fffff 70a8716626622325 +b11 b1100000 b11fffff 70a8716626622325 +b12 b1200000 b12fffff 70a8716626622325 +b13 b1300000 b13fffff 70a8716626622325 +b14 b1400000 b14fffff 70a8716626622325 +b15 b1500000 b15fffff 70a8716626622325 +b16 b1600000 b16fffff 70a8716626622325 +b17 b1700000 b17fffff 70a8716626622325 +b18 b1800000 b18fffff 70a8716626622325 +b19 b1900000 b19fffff 70a8716626622325 +b1a b1a00000 b1afffff 70a8716626622325 +b1b b1b00000 b1bfffff 70a8716626622325 +b1c b1c00000 b1cfffff 70a8716626622325 +b1d b1d00000 b1dfffff 70a8716626622325 +b1e b1e00000 b1efffff 70a8716626622325 +b1f b1f00000 b1ffffff 70a8716626622325 +b20 b2000000 b20fffff 70a8716626622325 +b21 b2100000 b21fffff 70a8716626622325 +b22 b2200000 b22fffff 70a8716626622325 +b23 b2300000 b23fffff 70a8716626622325 +b24 b2400000 b24fffff 70a8716626622325 +b25 b2500000 b25fffff 70a8716626622325 +b26 b2600000 b26fffff 70a8716626622325 +b27 b2700000 b27fffff 70a8716626622325 +b28 b2800000 b28fffff 70a8716626622325 +b29 b2900000 b29fffff 70a8716626622325 +b2a b2a00000 b2afffff 70a8716626622325 +b2b b2b00000 b2bfffff 70a8716626622325 +b2c b2c00000 b2cfffff 70a8716626622325 +b2d b2d00000 b2dfffff 70a8716626622325 +b2e b2e00000 b2efffff 70a8716626622325 +b2f b2f00000 b2ffffff 70a8716626622325 +b30 b3000000 b30fffff 361c07121e4ddcda +b31 b3100000 b31fffff c284ce789f522325 +b32 b3200000 b32fffff c284ce789f522325 +b33 b3300000 b33fffff c284ce789f522325 +b34 b3400000 b34fffff c284ce789f522325 +b35 b3500000 b35fffff c284ce789f522325 +b36 b3600000 b36fffff c284ce789f522325 +b37 b3700000 b37fffff c284ce789f522325 +b38 b3800000 b38fffff c284ce789f522325 +b39 b3900000 b39fffff c284ce789f522325 +b3a b3a00000 b3afffff c284ce789f522325 +b3b b3b00000 b3bfffff c284ce789f522325 +b3c b3c00000 b3cfffff a879bcaae4022324 +b3d b3d00000 b3dfffff 07c6015fe8622325 +b3e b3e00000 b3efffff 07c6015fe8622325 +b3f b3f00000 b3ffffff 07c6015fe8622325 +b40 b4000000 b40fffff 07c6015fe8622325 +b41 b4100000 b41fffff 07c6015fe8622325 +b42 b4200000 b42fffff f0018af2c3922326 +b43 b4300000 b43fffff 2951cd78bcd22325 +b44 b4400000 b44fffff 2951cd78bcd22325 +b45 b4500000 b45fffff 2951cd78bcd22325 +b46 b4600000 b46fffff c0867d03252b8daf +b47 b4700000 b47fffff 59b3f67da8222325 +b48 b4800000 b48fffff 59b3f67da8222325 +b49 b4900000 b49fffff 26595f2becdb8daf +b4a b4a00000 b4afffff 478358a8db522325 +b4b b4b00000 b4bfffff 7704ff573bab8da3 +b4c b4c00000 b4cfffff 11f7f3ceffa22325 +b4d b4d00000 b4dfffff 92d5c4c7a07ca290 +b4e b4e00000 b4efffff e1747b755dd22325 +b4f b4f00000 b4ffffff 3d7f5208b2555379 +b50 b5000000 b50fffff 11e975d9b9c4614c +b51 b5100000 b51fffff 5565205f35b44f86 +b52 b5200000 b52fffff 2b739b850dc506d9 +b53 b5300000 b53fffff ba4da6f04c74cb40 +b54 b5400000 b54fffff 0a54e3390b57aa26 +b55 b5500000 b55fffff e3e5b46562030957 +b56 b5600000 b56fffff c9c72da2b456d634 +b57 b5700000 b57fffff 93f4c82af284140d +b58 b5800000 b58fffff 103e93523c9399fb +b59 b5900000 b59fffff 11aae20a6fa5897d +b5a b5a00000 b5afffff 22dfd95cfc438f10 +b5b b5b00000 b5bfffff c62889bc60978fe4 +b5c b5c00000 b5cfffff 6ef06e1dac6dd020 +b5d b5d00000 b5dfffff 80770c81799fec8c +b5e b5e00000 b5efffff 1c6f04a670a26e1c +b5f b5f00000 b5ffffff 5b8706bea737970c +b60 b6000000 b60fffff d8714964d7b68973 +b61 b6100000 b61fffff 654b0da2535a3a72 +b62 b6200000 b62fffff f3b30f3bed802482 +b63 b6300000 b63fffff 361a9aaf6a8c3861 +b64 b6400000 b64fffff b5dc355948a91879 +b65 b6500000 b65fffff f6fb6b08b3a71a61 +b66 b6600000 b66fffff 81a47a1939f1bc85 +b67 b6700000 b67fffff e06ab927999f0d55 +b68 b6800000 b68fffff f6f6f75a1901ab75 +b69 b6900000 b69fffff 5a11e9a8a5985b56 +b6a b6a00000 b6afffff 6267a2317c0d8f35 +b6b b6b00000 b6bfffff 044ca4e796bbe50d +b6c b6c00000 b6cfffff b7321dbb1521ea2c +b6d b6d00000 b6dfffff d8d417759de7c389 +b6e b6e00000 b6efffff 2417319e401c7b60 +b6f b6f00000 b6ffffff 9f127e4dcf586f35 +b70 b7000000 b70fffff 652bd9a8134351a2 +b71 b7100000 b71fffff 29125133925af956 +b72 b7200000 b72fffff cfb3c8440455d922 +b73 b7300000 b73fffff 4f4f4f3a2af25a53 +b74 b7400000 b74fffff 80b378e7e1bff3e2 +b75 b7500000 b75fffff a683f39d4b67a84d +b76 b7600000 b76fffff aac5a4188a388049 +b77 b7700000 b77fffff d4624cf353938705 +b78 b7800000 b78fffff 8b5d8d5a650580e3 +b79 b7900000 b79fffff 94e8b50fbf93860f +b7a b7a00000 b7afffff 458cafccb104e2c0 +b7b b7b00000 b7bfffff 5dfa010ba558d64c +b7c b7c00000 b7cfffff a7f480839fca4930 +b7d b7d00000 b7dfffff 284d84cc3cefb63f +b7e b7e00000 b7efffff ee4aa7c9db19283b +b7f b7f00000 b7ffffff d1034ea4af2c92d8 +b80 b8000000 b80fffff 42ae4a9174aec06f +b81 b8100000 b81fffff e9c6d741a1348c11 +b82 b8200000 b82fffff b6d730fd304b5c7f +b83 b8300000 b83fffff 2c08cdae6674c4fc +b84 b8400000 b84fffff 7dd5b6e28ac0f345 +b85 b8500000 b85fffff d8145b8d14844a3b +b86 b8600000 b86fffff 618cb01a1882d0f5 +b87 b8700000 b87fffff f47fdd1db74edb6b +b88 b8800000 b88fffff cb4b33030fc19617 +b89 b8900000 b89fffff 8c3081b22d25111d +b8a b8a00000 b8afffff 27f993149eca475c +b8b b8b00000 b8bfffff d4b6e9881da0b13c +b8c b8c00000 b8cfffff 5fed7234522030b7 +b8d b8d00000 b8dfffff eebfe23232b0eb4c +b8e b8e00000 b8efffff 6ad43ccd4df2358c +b8f b8f00000 b8ffffff 6d9f71e7ff139ce4 +b90 b9000000 b90fffff 53866ab1986be486 +b91 b9100000 b91fffff fa993ee2fe1e13d1 +b92 b9200000 b92fffff f7b363976f7f2511 +b93 b9300000 b93fffff a2583f938e97589e +b94 b9400000 b94fffff 975efec22c2d4326 +b95 b9500000 b95fffff a9a5e1103b30e709 +b96 b9600000 b96fffff a8b7ffed7b882609 +b97 b9700000 b97fffff c9170d170bd50c2a +b98 b9800000 b98fffff 396f9678e442662b +b99 b9900000 b99fffff 21e845db8ac1bb58 +b9a b9a00000 b9afffff 78107bdfc402d540 +b9b b9b00000 b9bfffff 776206e1b5310e94 +b9c b9c00000 b9cfffff 88db6b68c7d06b02 +b9d b9d00000 b9dfffff b697c0be1de084fe +b9e b9e00000 b9efffff f999f5abcfe072ce +b9f b9f00000 b9ffffff 1b52c5ad8ee88dd4 +ba0 ba000000 ba0fffff 6f57321a6dbb1faa +ba1 ba100000 ba1fffff ce5896994679fca1 +ba2 ba200000 ba2fffff 4a0bbed47bcd94e4 +ba3 ba300000 ba3fffff 2bc83aa0d754ce25 +ba4 ba400000 ba4fffff 47a8cebdf20c3755 +ba5 ba500000 ba5fffff f1c3b31ec35c2132 +ba6 ba600000 ba6fffff d7c99db58f4a8919 +ba7 ba700000 ba7fffff 70d1d2ce2ee62771 +ba8 ba800000 ba8fffff 1b92ce4f5a1fe5c8 +ba9 ba900000 ba9fffff a473d28565d6f1b6 +baa baa00000 baafffff ed8397f5f47e567a +bab bab00000 babfffff 0679e17eface2b48 +bac bac00000 bacfffff 83430007e7f9da85 +bad bad00000 badfffff 6f8e1564153bfd92 +bae bae00000 baefffff 98ab4b3ef7227a27 +baf baf00000 baffffff 4ea990d43ae9e80a +bb0 bb000000 bb0fffff b3979c4d053b14b2 +bb1 bb100000 bb1fffff 2458774e3898950a +bb2 bb200000 bb2fffff 7447f9b2ddce6874 +bb3 bb300000 bb3fffff 4696a3fa7b640a10 +bb4 bb400000 bb4fffff 87ea1de6086d7109 +bb5 bb500000 bb5fffff 55e92df906f5147c +bb6 bb600000 bb6fffff ca9210953d246e5c +bb7 bb700000 bb7fffff 87422a0d7ff852b6 +bb8 bb800000 bb8fffff 1849035199542364 +bb9 bb900000 bb9fffff ebe5e680f39f7212 +bba bba00000 bbafffff e2cd0e7b1d0bda1a +bbb bbb00000 bbbfffff f8d638b72f310244 +bbc bbc00000 bbcfffff 53b1c064d9cf4a24 +bbd bbd00000 bbdfffff bb0b1e781fd5c163 +bbe bbe00000 bbefffff 1ac67012771ce75f +bbf bbf00000 bbffffff 6818d20afa9d6912 +bc0 bc000000 bc0fffff 394b57f4030482f8 +bc1 bc100000 bc1fffff 6516fcbcd38b77fb +bc2 bc200000 bc2fffff c22903f49ad83e29 +bc3 bc300000 bc3fffff 3780ca984a0790ec +bc4 bc400000 bc4fffff dcc5a1799c5094a6 +bc5 bc500000 bc5fffff 63b3e6374a653b66 +bc6 bc600000 bc6fffff a6710f8b399e817f +bc7 bc700000 bc7fffff 07b8a1a7fc86859c +bc8 bc800000 bc8fffff 527ef23c3bf733fb +bc9 bc900000 bc9fffff 53aa3b39ab0fba9f +bca bca00000 bcafffff 6974fe7e81d534d9 +bcb bcb00000 bcbfffff 1727e2665f48047f +bcc bcc00000 bccfffff 359120773f06c46f +bcd bcd00000 bcdfffff d673c0b0c365da13 +bce bce00000 bcefffff 275a725a34538247 +bcf bcf00000 bcffffff 55a1c42512bb1ae0 +bd0 bd000000 bd0fffff 99848118d9d3c9fd +bd1 bd100000 bd1fffff 35537baa83c2831d +bd2 bd200000 bd2fffff 1f111e91eae80e1a +bd3 bd300000 bd3fffff 213fce09032bc414 +bd4 bd400000 bd4fffff 77597c003230a07f +bd5 bd500000 bd5fffff 2eb3f1270888d16e +bd6 bd600000 bd6fffff f2b2c6fdb0aa378e +bd7 bd700000 bd7fffff 1a6477b834c85d37 +bd8 bd800000 bd8fffff daef7e4d9aabb827 +bd9 bd900000 bd9fffff 2bc2aeedd6018a34 +bda bda00000 bdafffff 033e8563ed052a9e +bdb bdb00000 bdbfffff 5bd260d417a8b0a1 +bdc bdc00000 bdcfffff 61f4f5b3c1bd74b9 +bdd bdd00000 bddfffff e16029ae15d33dd0 +bde bde00000 bdefffff d6873174e0793ba8 +bdf bdf00000 bdffffff 27f045aab648bb4f +be0 be000000 be0fffff 64068898bec8025f +be1 be100000 be1fffff 440eee64b06df0d9 +be2 be200000 be2fffff 591eee0a277abbba +be3 be300000 be3fffff 8aca97eedcd1c3f4 +be4 be400000 be4fffff 6213dd20241219ff +be5 be500000 be5fffff c23d4f1cd1f81f4a +be6 be600000 be6fffff 0c9a3877a0050b1d +be7 be700000 be7fffff 05a4e20fe7315ec8 +be8 be800000 be8fffff e7bce7ff09368d8d +be9 be900000 be9fffff 0aa66e25324a59b1 +bea bea00000 beafffff 973ea1a271a20b47 +beb beb00000 bebfffff 0d9d4a7d73b0442d +bec bec00000 becfffff 7469d0e70a2f4fe2 +bed bed00000 bedfffff 991c043d39c663e9 +bee bee00000 beefffff d3a38a9c63e425b0 +bef bef00000 beffffff 107932c9af09a560 +bf0 bf000000 bf0fffff 0df4b161fa0f8965 +bf1 bf100000 bf1fffff fca5c93239644b8b +bf2 bf200000 bf2fffff f83063ff32a7cffb +bf3 bf300000 bf3fffff 05b62dc9336f0d94 +bf4 bf400000 bf4fffff d193f85f947d9755 +bf5 bf500000 bf5fffff 753e79738326d1c6 +bf6 bf600000 bf6fffff 8f2e1ad68ed21654 +bf7 bf700000 bf7fffff 79057d3db1b316c2 +bf8 bf800000 bf8fffff dde2cfba8bed0d13 +bf9 bf900000 bf9fffff 8a1227bf2e170394 +bfa bfa00000 bfafffff f2d94d651323cb74 +bfb bfb00000 bfbfffff b489659e46c8a249 +bfc bfc00000 bfcfffff fa732b07e37a1ded +bfd bfd00000 bfdfffff f2514f4a1dcdbb5b +bfe bfe00000 bfefffff a2ce160daaadace9 +bff bff00000 bfffffff 65b5a443695d460e +c00 c0000000 c00fffff 9dbe76602a8b7071 +c01 c0100000 c01fffff 016b68f36fb72b09 +c02 c0200000 c02fffff 20c52c6cef4e5c7f +c03 c0300000 c03fffff 5079d445ec75fc37 +c04 c0400000 c04fffff f739b1e1ead81a68 +c05 c0500000 c05fffff 8b6b16160c25f104 +c06 c0600000 c06fffff 23fb156f55241a0d +c07 c0700000 c07fffff de36799db45cd438 +c08 c0800000 c08fffff d743abc8ff796d2b +c09 c0900000 c09fffff 0c5dff7f5085ebef +c0a c0a00000 c0afffff 45a15cba868b0957 +c0b c0b00000 c0bfffff bb8f8e2f04eefe00 +c0c c0c00000 c0cfffff f14ca7ef2e649f4f +c0d c0d00000 c0dfffff f11b6e5db1d7450b +c0e c0e00000 c0efffff 1d4a75f77aae344d +c0f c0f00000 c0ffffff 03ff5dd94cca6e3e +c10 c1000000 c10fffff 0546ec264afc4e29 +c11 c1100000 c11fffff 87d377133090273a +c12 c1200000 c12fffff 5ced3c34f5c3a2d3 +c13 c1300000 c13fffff 1c2d3aa591bd0971 +c14 c1400000 c14fffff 0d6f36fb8f3c1251 +c15 c1500000 c15fffff 2ef7fa991be15b5d +c16 c1600000 c16fffff fe180168bdc4d324 +c17 c1700000 c17fffff 9a26077b144598f4 +c18 c1800000 c18fffff fb5b672e86d8b154 +c19 c1900000 c19fffff 36dba4dbecdd2bec +c1a c1a00000 c1afffff 15ab7eb739de4888 +c1b c1b00000 c1bfffff 0d771837e954ca87 +c1c c1c00000 c1cfffff 9e8d2aee9ada5ab2 +c1d c1d00000 c1dfffff ecda9140f7d81a5f +c1e c1e00000 c1efffff 42acd3680a25a5b2 +c1f c1f00000 c1ffffff a9e0dd682dfe1a4e +c20 c2000000 c20fffff a6d03ac25b2ebf94 +c21 c2100000 c21fffff 047f8928bd03ca49 +c22 c2200000 c22fffff 9baa9b2ba4c17636 +c23 c2300000 c23fffff 746ac093931e4f77 +c24 c2400000 c24fffff 880245ab4541e76d +c25 c2500000 c25fffff 2052dc5f62c046fe +c26 c2600000 c26fffff c2b9a7028d0ff316 +c27 c2700000 c27fffff 27a5278eee337f69 +c28 c2800000 c28fffff 5bff476d22205391 +c29 c2900000 c29fffff 1de6f1eca291e2c4 +c2a c2a00000 c2afffff 1a365d41a0c7308a +c2b c2b00000 c2bfffff 156b29d0d96974f4 +c2c c2c00000 c2cfffff 28076ba66bc3a398 +c2d c2d00000 c2dfffff a96777069d622325 +c2e c2e00000 c2efffff a96777069d622325 +c2f c2f00000 c2ffffff a96777069d622325 +c30 c3000000 c30fffff a96777069d622325 +c31 c3100000 c31fffff a96777069d622325 +c32 c3200000 c32fffff a96777069d622325 +c33 c3300000 c33fffff a96777069d622325 +c34 c3400000 c34fffff a96777069d622325 +c35 c3500000 c35fffff a96777069d622325 +c36 c3600000 c36fffff a96777069d622325 +c37 c3700000 c37fffff a96777069d622325 +c38 c3800000 c38fffff a96777069d622325 +c39 c3900000 c39fffff a96777069d622325 +c3a c3a00000 c3afffff a96777069d622325 +c3b c3b00000 c3bfffff a96777069d622325 +c3c c3c00000 c3cfffff a96777069d622325 +c3d c3d00000 c3dfffff a96777069d622325 +c3e c3e00000 c3efffff a96777069d622325 +c3f c3f00000 c3ffffff a96777069d622325 +c40 c4000000 c40fffff a96777069d622325 +c41 c4100000 c41fffff a96777069d622325 +c42 c4200000 c42fffff a96777069d622325 +c43 c4300000 c43fffff a96777069d622325 +c44 c4400000 c44fffff a96777069d622325 +c45 c4500000 c45fffff a96777069d622325 +c46 c4600000 c46fffff a96777069d622325 +c47 c4700000 c47fffff a96777069d622325 +c48 c4800000 c48fffff a96777069d622325 +c49 c4900000 c49fffff a96777069d622325 +c4a c4a00000 c4afffff a96777069d622325 +c4b c4b00000 c4bfffff a96777069d622325 +c4c c4c00000 c4cfffff a96777069d622325 +c4d c4d00000 c4dfffff a96777069d622325 +c4e c4e00000 c4efffff a96777069d622325 +c4f c4f00000 c4ffffff a96777069d622325 +c50 c5000000 c50fffff a96777069d622325 +c51 c5100000 c51fffff a96777069d622325 +c52 c5200000 c52fffff a96777069d622325 +c53 c5300000 c53fffff a96777069d622325 +c54 c5400000 c54fffff a96777069d622325 +c55 c5500000 c55fffff a96777069d622325 +c56 c5600000 c56fffff a96777069d622325 +c57 c5700000 c57fffff a96777069d622325 +c58 c5800000 c58fffff a96777069d622325 +c59 c5900000 c59fffff a96777069d622325 +c5a c5a00000 c5afffff a96777069d622325 +c5b c5b00000 c5bfffff a96777069d622325 +c5c c5c00000 c5cfffff a96777069d622325 +c5d c5d00000 c5dfffff a96777069d622325 +c5e c5e00000 c5efffff a96777069d622325 +c5f c5f00000 c5ffffff a96777069d622325 +c60 c6000000 c60fffff a96777069d622325 +c61 c6100000 c61fffff a96777069d622325 +c62 c6200000 c62fffff a96777069d622325 +c63 c6300000 c63fffff a96777069d622325 +c64 c6400000 c64fffff a96777069d622325 +c65 c6500000 c65fffff a96777069d622325 +c66 c6600000 c66fffff a96777069d622325 +c67 c6700000 c67fffff a96777069d622325 +c68 c6800000 c68fffff a96777069d622325 +c69 c6900000 c69fffff a96777069d622325 +c6a c6a00000 c6afffff a96777069d622325 +c6b c6b00000 c6bfffff a96777069d622325 +c6c c6c00000 c6cfffff a96777069d622325 +c6d c6d00000 c6dfffff a96777069d622325 +c6e c6e00000 c6efffff a96777069d622325 +c6f c6f00000 c6ffffff a96777069d622325 +c70 c7000000 c70fffff a96777069d622325 +c71 c7100000 c71fffff a96777069d622325 +c72 c7200000 c72fffff a96777069d622325 +c73 c7300000 c73fffff a96777069d622325 +c74 c7400000 c74fffff a96777069d622325 +c75 c7500000 c75fffff a96777069d622325 +c76 c7600000 c76fffff a96777069d622325 +c77 c7700000 c77fffff a96777069d622325 +c78 c7800000 c78fffff a96777069d622325 +c79 c7900000 c79fffff a96777069d622325 +c7a c7a00000 c7afffff a96777069d622325 +c7b c7b00000 c7bfffff a96777069d622325 +c7c c7c00000 c7cfffff a96777069d622325 +c7d c7d00000 c7dfffff a96777069d622325 +c7e c7e00000 c7efffff a96777069d622325 +c7f c7f00000 c7ffffff a96777069d622325 +c80 c8000000 c80fffff a96777069d622325 +c81 c8100000 c81fffff a96777069d622325 +c82 c8200000 c82fffff a96777069d622325 +c83 c8300000 c83fffff a96777069d622325 +c84 c8400000 c84fffff a96777069d622325 +c85 c8500000 c85fffff a96777069d622325 +c86 c8600000 c86fffff a96777069d622325 +c87 c8700000 c87fffff a96777069d622325 +c88 c8800000 c88fffff a96777069d622325 +c89 c8900000 c89fffff a96777069d622325 +c8a c8a00000 c8afffff a96777069d622325 +c8b c8b00000 c8bfffff a96777069d622325 +c8c c8c00000 c8cfffff a96777069d622325 +c8d c8d00000 c8dfffff a96777069d622325 +c8e c8e00000 c8efffff a96777069d622325 +c8f c8f00000 c8ffffff a96777069d622325 +c90 c9000000 c90fffff a96777069d622325 +c91 c9100000 c91fffff a96777069d622325 +c92 c9200000 c92fffff a96777069d622325 +c93 c9300000 c93fffff a96777069d622325 +c94 c9400000 c94fffff a96777069d622325 +c95 c9500000 c95fffff a96777069d622325 +c96 c9600000 c96fffff a96777069d622325 +c97 c9700000 c97fffff a96777069d622325 +c98 c9800000 c98fffff a96777069d622325 +c99 c9900000 c99fffff a96777069d622325 +c9a c9a00000 c9afffff a96777069d622325 +c9b c9b00000 c9bfffff a96777069d622325 +c9c c9c00000 c9cfffff a96777069d622325 +c9d c9d00000 c9dfffff a96777069d622325 +c9e c9e00000 c9efffff a96777069d622325 +c9f c9f00000 c9ffffff a96777069d622325 +ca0 ca000000 ca0fffff a96777069d622325 +ca1 ca100000 ca1fffff a96777069d622325 +ca2 ca200000 ca2fffff a96777069d622325 +ca3 ca300000 ca3fffff a96777069d622325 +ca4 ca400000 ca4fffff a96777069d622325 +ca5 ca500000 ca5fffff a96777069d622325 +ca6 ca600000 ca6fffff a96777069d622325 +ca7 ca700000 ca7fffff a96777069d622325 +ca8 ca800000 ca8fffff a96777069d622325 +ca9 ca900000 ca9fffff a96777069d622325 +caa caa00000 caafffff a96777069d622325 +cab cab00000 cabfffff a96777069d622325 +cac cac00000 cacfffff a96777069d622325 +cad cad00000 cadfffff a96777069d622325 +cae cae00000 caefffff a96777069d622325 +caf caf00000 caffffff a96777069d622325 +cb0 cb000000 cb0fffff a96777069d622325 +cb1 cb100000 cb1fffff a96777069d622325 +cb2 cb200000 cb2fffff a96777069d622325 +cb3 cb300000 cb3fffff a96777069d622325 +cb4 cb400000 cb4fffff a96777069d622325 +cb5 cb500000 cb5fffff a96777069d622325 +cb6 cb600000 cb6fffff a96777069d622325 +cb7 cb700000 cb7fffff a96777069d622325 +cb8 cb800000 cb8fffff a96777069d622325 +cb9 cb900000 cb9fffff a96777069d622325 +cba cba00000 cbafffff a96777069d622325 +cbb cbb00000 cbbfffff a96777069d622325 +cbc cbc00000 cbcfffff a96777069d622325 +cbd cbd00000 cbdfffff a96777069d622325 +cbe cbe00000 cbefffff a96777069d622325 +cbf cbf00000 cbffffff a96777069d622325 +cc0 cc000000 cc0fffff a96777069d622325 +cc1 cc100000 cc1fffff a96777069d622325 +cc2 cc200000 cc2fffff a96777069d622325 +cc3 cc300000 cc3fffff a96777069d622325 +cc4 cc400000 cc4fffff a96777069d622325 +cc5 cc500000 cc5fffff a96777069d622325 +cc6 cc600000 cc6fffff a96777069d622325 +cc7 cc700000 cc7fffff a96777069d622325 +cc8 cc800000 cc8fffff a96777069d622325 +cc9 cc900000 cc9fffff a96777069d622325 +cca cca00000 ccafffff a96777069d622325 +ccb ccb00000 ccbfffff a96777069d622325 +ccc ccc00000 cccfffff a96777069d622325 +ccd ccd00000 ccdfffff a96777069d622325 +cce cce00000 ccefffff a96777069d622325 +ccf ccf00000 ccffffff a96777069d622325 +cd0 cd000000 cd0fffff a96777069d622325 +cd1 cd100000 cd1fffff a96777069d622325 +cd2 cd200000 cd2fffff a96777069d622325 +cd3 cd300000 cd3fffff a96777069d622325 +cd4 cd400000 cd4fffff a96777069d622325 +cd5 cd500000 cd5fffff a96777069d622325 +cd6 cd600000 cd6fffff a96777069d622325 +cd7 cd700000 cd7fffff a96777069d622325 +cd8 cd800000 cd8fffff a96777069d622325 +cd9 cd900000 cd9fffff a96777069d622325 +cda cda00000 cdafffff a96777069d622325 +cdb cdb00000 cdbfffff a96777069d622325 +cdc cdc00000 cdcfffff a96777069d622325 +cdd cdd00000 cddfffff a96777069d622325 +cde cde00000 cdefffff a96777069d622325 +cdf cdf00000 cdffffff a96777069d622325 +ce0 ce000000 ce0fffff a96777069d622325 +ce1 ce100000 ce1fffff a96777069d622325 +ce2 ce200000 ce2fffff a96777069d622325 +ce3 ce300000 ce3fffff a96777069d622325 +ce4 ce400000 ce4fffff a96777069d622325 +ce5 ce500000 ce5fffff a96777069d622325 +ce6 ce600000 ce6fffff a96777069d622325 +ce7 ce700000 ce7fffff a96777069d622325 +ce8 ce800000 ce8fffff a96777069d622325 +ce9 ce900000 ce9fffff a96777069d622325 +cea cea00000 ceafffff a96777069d622325 +ceb ceb00000 cebfffff a96777069d622325 +cec cec00000 cecfffff a96777069d622325 +ced ced00000 cedfffff a96777069d622325 +cee cee00000 ceefffff a96777069d622325 +cef cef00000 ceffffff a96777069d622325 +cf0 cf000000 cf0fffff a96777069d622325 +cf1 cf100000 cf1fffff a96777069d622325 +cf2 cf200000 cf2fffff a96777069d622325 +cf3 cf300000 cf3fffff a96777069d622325 +cf4 cf400000 cf4fffff a96777069d622325 +cf5 cf500000 cf5fffff a96777069d622325 +cf6 cf600000 cf6fffff a96777069d622325 +cf7 cf700000 cf7fffff a96777069d622325 +cf8 cf800000 cf8fffff a96777069d622325 +cf9 cf900000 cf9fffff a96777069d622325 +cfa cfa00000 cfafffff a96777069d622325 +cfb cfb00000 cfbfffff a96777069d622325 +cfc cfc00000 cfcfffff a96777069d622325 +cfd cfd00000 cfdfffff a96777069d622325 +cfe cfe00000 cfefffff a96777069d622325 +cff cff00000 cfffffff a96777069d622325 +d00 d0000000 d00fffff a96777069d622325 +d01 d0100000 d01fffff a96777069d622325 +d02 d0200000 d02fffff a96777069d622325 +d03 d0300000 d03fffff a96777069d622325 +d04 d0400000 d04fffff a96777069d622325 +d05 d0500000 d05fffff a96777069d622325 +d06 d0600000 d06fffff a96777069d622325 +d07 d0700000 d07fffff a96777069d622325 +d08 d0800000 d08fffff a96777069d622325 +d09 d0900000 d09fffff a96777069d622325 +d0a d0a00000 d0afffff a96777069d622325 +d0b d0b00000 d0bfffff a96777069d622325 +d0c d0c00000 d0cfffff a96777069d622325 +d0d d0d00000 d0dfffff a96777069d622325 +d0e d0e00000 d0efffff a96777069d622325 +d0f d0f00000 d0ffffff a96777069d622325 +d10 d1000000 d10fffff a96777069d622325 +d11 d1100000 d11fffff a96777069d622325 +d12 d1200000 d12fffff a96777069d622325 +d13 d1300000 d13fffff a96777069d622325 +d14 d1400000 d14fffff a96777069d622325 +d15 d1500000 d15fffff a96777069d622325 +d16 d1600000 d16fffff a96777069d622325 +d17 d1700000 d17fffff a96777069d622325 +d18 d1800000 d18fffff a96777069d622325 +d19 d1900000 d19fffff a96777069d622325 +d1a d1a00000 d1afffff a96777069d622325 +d1b d1b00000 d1bfffff a96777069d622325 +d1c d1c00000 d1cfffff a96777069d622325 +d1d d1d00000 d1dfffff a96777069d622325 +d1e d1e00000 d1efffff a96777069d622325 +d1f d1f00000 d1ffffff a96777069d622325 +d20 d2000000 d20fffff a96777069d622325 +d21 d2100000 d21fffff a96777069d622325 +d22 d2200000 d22fffff a96777069d622325 +d23 d2300000 d23fffff a96777069d622325 +d24 d2400000 d24fffff a96777069d622325 +d25 d2500000 d25fffff a96777069d622325 +d26 d2600000 d26fffff a96777069d622325 +d27 d2700000 d27fffff a96777069d622325 +d28 d2800000 d28fffff a96777069d622325 +d29 d2900000 d29fffff a96777069d622325 +d2a d2a00000 d2afffff a96777069d622325 +d2b d2b00000 d2bfffff a96777069d622325 +d2c d2c00000 d2cfffff a96777069d622325 +d2d d2d00000 d2dfffff a96777069d622325 +d2e d2e00000 d2efffff a96777069d622325 +d2f d2f00000 d2ffffff a96777069d622325 +d30 d3000000 d30fffff a96777069d622325 +d31 d3100000 d31fffff a96777069d622325 +d32 d3200000 d32fffff a96777069d622325 +d33 d3300000 d33fffff a96777069d622325 +d34 d3400000 d34fffff a96777069d622325 +d35 d3500000 d35fffff a96777069d622325 +d36 d3600000 d36fffff a96777069d622325 +d37 d3700000 d37fffff a96777069d622325 +d38 d3800000 d38fffff a96777069d622325 +d39 d3900000 d39fffff a96777069d622325 +d3a d3a00000 d3afffff a96777069d622325 +d3b d3b00000 d3bfffff a96777069d622325 +d3c d3c00000 d3cfffff a96777069d622325 +d3d d3d00000 d3dfffff a96777069d622325 +d3e d3e00000 d3efffff a96777069d622325 +d3f d3f00000 d3ffffff a96777069d622325 +d40 d4000000 d40fffff a96777069d622325 +d41 d4100000 d41fffff a96777069d622325 +d42 d4200000 d42fffff a96777069d622325 +d43 d4300000 d43fffff a96777069d622325 +d44 d4400000 d44fffff a96777069d622325 +d45 d4500000 d45fffff a96777069d622325 +d46 d4600000 d46fffff a96777069d622325 +d47 d4700000 d47fffff a96777069d622325 +d48 d4800000 d48fffff a96777069d622325 +d49 d4900000 d49fffff a96777069d622325 +d4a d4a00000 d4afffff a96777069d622325 +d4b d4b00000 d4bfffff a96777069d622325 +d4c d4c00000 d4cfffff a96777069d622325 +d4d d4d00000 d4dfffff a96777069d622325 +d4e d4e00000 d4efffff a96777069d622325 +d4f d4f00000 d4ffffff a96777069d622325 +d50 d5000000 d50fffff a96777069d622325 +d51 d5100000 d51fffff a96777069d622325 +d52 d5200000 d52fffff a96777069d622325 +d53 d5300000 d53fffff a96777069d622325 +d54 d5400000 d54fffff a96777069d622325 +d55 d5500000 d55fffff a96777069d622325 +d56 d5600000 d56fffff a96777069d622325 +d57 d5700000 d57fffff a96777069d622325 +d58 d5800000 d58fffff a96777069d622325 +d59 d5900000 d59fffff a96777069d622325 +d5a d5a00000 d5afffff a96777069d622325 +d5b d5b00000 d5bfffff a96777069d622325 +d5c d5c00000 d5cfffff a96777069d622325 +d5d d5d00000 d5dfffff a96777069d622325 +d5e d5e00000 d5efffff a96777069d622325 +d5f d5f00000 d5ffffff a96777069d622325 +d60 d6000000 d60fffff a96777069d622325 +d61 d6100000 d61fffff a96777069d622325 +d62 d6200000 d62fffff a96777069d622325 +d63 d6300000 d63fffff a96777069d622325 +d64 d6400000 d64fffff a96777069d622325 +d65 d6500000 d65fffff a96777069d622325 +d66 d6600000 d66fffff a96777069d622325 +d67 d6700000 d67fffff a96777069d622325 +d68 d6800000 d68fffff a96777069d622325 +d69 d6900000 d69fffff a96777069d622325 +d6a d6a00000 d6afffff a96777069d622325 +d6b d6b00000 d6bfffff a96777069d622325 +d6c d6c00000 d6cfffff a96777069d622325 +d6d d6d00000 d6dfffff a96777069d622325 +d6e d6e00000 d6efffff a96777069d622325 +d6f d6f00000 d6ffffff a96777069d622325 +d70 d7000000 d70fffff a96777069d622325 +d71 d7100000 d71fffff a96777069d622325 +d72 d7200000 d72fffff a96777069d622325 +d73 d7300000 d73fffff a96777069d622325 +d74 d7400000 d74fffff a96777069d622325 +d75 d7500000 d75fffff a96777069d622325 +d76 d7600000 d76fffff a96777069d622325 +d77 d7700000 d77fffff a96777069d622325 +d78 d7800000 d78fffff a96777069d622325 +d79 d7900000 d79fffff a96777069d622325 +d7a d7a00000 d7afffff a96777069d622325 +d7b d7b00000 d7bfffff a96777069d622325 +d7c d7c00000 d7cfffff a96777069d622325 +d7d d7d00000 d7dfffff a96777069d622325 +d7e d7e00000 d7efffff a96777069d622325 +d7f d7f00000 d7ffffff a96777069d622325 +d80 d8000000 d80fffff a96777069d622325 +d81 d8100000 d81fffff a96777069d622325 +d82 d8200000 d82fffff a96777069d622325 +d83 d8300000 d83fffff a96777069d622325 +d84 d8400000 d84fffff a96777069d622325 +d85 d8500000 d85fffff a96777069d622325 +d86 d8600000 d86fffff a96777069d622325 +d87 d8700000 d87fffff a96777069d622325 +d88 d8800000 d88fffff a96777069d622325 +d89 d8900000 d89fffff a96777069d622325 +d8a d8a00000 d8afffff a96777069d622325 +d8b d8b00000 d8bfffff a96777069d622325 +d8c d8c00000 d8cfffff a96777069d622325 +d8d d8d00000 d8dfffff a96777069d622325 +d8e d8e00000 d8efffff a96777069d622325 +d8f d8f00000 d8ffffff a96777069d622325 +d90 d9000000 d90fffff a96777069d622325 +d91 d9100000 d91fffff a96777069d622325 +d92 d9200000 d92fffff a96777069d622325 +d93 d9300000 d93fffff a96777069d622325 +d94 d9400000 d94fffff a96777069d622325 +d95 d9500000 d95fffff a96777069d622325 +d96 d9600000 d96fffff a96777069d622325 +d97 d9700000 d97fffff a96777069d622325 +d98 d9800000 d98fffff a96777069d622325 +d99 d9900000 d99fffff a96777069d622325 +d9a d9a00000 d9afffff a96777069d622325 +d9b d9b00000 d9bfffff a96777069d622325 +d9c d9c00000 d9cfffff a96777069d622325 +d9d d9d00000 d9dfffff a96777069d622325 +d9e d9e00000 d9efffff a96777069d622325 +d9f d9f00000 d9ffffff a96777069d622325 +da0 da000000 da0fffff a96777069d622325 +da1 da100000 da1fffff a96777069d622325 +da2 da200000 da2fffff a96777069d622325 +da3 da300000 da3fffff a96777069d622325 +da4 da400000 da4fffff a96777069d622325 +da5 da500000 da5fffff a96777069d622325 +da6 da600000 da6fffff a96777069d622325 +da7 da700000 da7fffff a96777069d622325 +da8 da800000 da8fffff a96777069d622325 +da9 da900000 da9fffff a96777069d622325 +daa daa00000 daafffff a96777069d622325 +dab dab00000 dabfffff a96777069d622325 +dac dac00000 dacfffff a96777069d622325 +dad dad00000 dadfffff a96777069d622325 +dae dae00000 daefffff a96777069d622325 +daf daf00000 daffffff a96777069d622325 +db0 db000000 db0fffff a96777069d622325 +db1 db100000 db1fffff a96777069d622325 +db2 db200000 db2fffff a96777069d622325 +db3 db300000 db3fffff a96777069d622325 +db4 db400000 db4fffff a96777069d622325 +db5 db500000 db5fffff a96777069d622325 +db6 db600000 db6fffff a96777069d622325 +db7 db700000 db7fffff a96777069d622325 +db8 db800000 db8fffff a96777069d622325 +db9 db900000 db9fffff a96777069d622325 +dba dba00000 dbafffff a96777069d622325 +dbb dbb00000 dbbfffff a96777069d622325 +dbc dbc00000 dbcfffff a96777069d622325 +dbd dbd00000 dbdfffff a96777069d622325 +dbe dbe00000 dbefffff a96777069d622325 +dbf dbf00000 dbffffff a96777069d622325 +dc0 dc000000 dc0fffff a96777069d622325 +dc1 dc100000 dc1fffff a96777069d622325 +dc2 dc200000 dc2fffff a96777069d622325 +dc3 dc300000 dc3fffff a96777069d622325 +dc4 dc400000 dc4fffff a96777069d622325 +dc5 dc500000 dc5fffff a96777069d622325 +dc6 dc600000 dc6fffff a96777069d622325 +dc7 dc700000 dc7fffff a96777069d622325 +dc8 dc800000 dc8fffff a96777069d622325 +dc9 dc900000 dc9fffff a96777069d622325 +dca dca00000 dcafffff a96777069d622325 +dcb dcb00000 dcbfffff a96777069d622325 +dcc dcc00000 dccfffff a96777069d622325 +dcd dcd00000 dcdfffff a96777069d622325 +dce dce00000 dcefffff a96777069d622325 +dcf dcf00000 dcffffff a96777069d622325 +dd0 dd000000 dd0fffff a96777069d622325 +dd1 dd100000 dd1fffff a96777069d622325 +dd2 dd200000 dd2fffff a96777069d622325 +dd3 dd300000 dd3fffff a96777069d622325 +dd4 dd400000 dd4fffff a96777069d622325 +dd5 dd500000 dd5fffff a96777069d622325 +dd6 dd600000 dd6fffff a96777069d622325 +dd7 dd700000 dd7fffff a96777069d622325 +dd8 dd800000 dd8fffff a96777069d622325 +dd9 dd900000 dd9fffff a96777069d622325 +dda dda00000 ddafffff a96777069d622325 +ddb ddb00000 ddbfffff a96777069d622325 +ddc ddc00000 ddcfffff a96777069d622325 +ddd ddd00000 dddfffff a96777069d622325 +dde dde00000 ddefffff a96777069d622325 +ddf ddf00000 ddffffff a96777069d622325 +de0 de000000 de0fffff a96777069d622325 +de1 de100000 de1fffff a96777069d622325 +de2 de200000 de2fffff a96777069d622325 +de3 de300000 de3fffff a96777069d622325 +de4 de400000 de4fffff a96777069d622325 +de5 de500000 de5fffff a96777069d622325 +de6 de600000 de6fffff a96777069d622325 +de7 de700000 de7fffff a96777069d622325 +de8 de800000 de8fffff a96777069d622325 +de9 de900000 de9fffff a96777069d622325 +dea dea00000 deafffff a96777069d622325 +deb deb00000 debfffff a96777069d622325 +dec dec00000 decfffff a96777069d622325 +ded ded00000 dedfffff a96777069d622325 +dee dee00000 deefffff a96777069d622325 +def def00000 deffffff a96777069d622325 +df0 df000000 df0fffff a96777069d622325 +df1 df100000 df1fffff a96777069d622325 +df2 df200000 df2fffff a96777069d622325 +df3 df300000 df3fffff a96777069d622325 +df4 df400000 df4fffff a96777069d622325 +df5 df500000 df5fffff a96777069d622325 +df6 df600000 df6fffff a96777069d622325 +df7 df700000 df7fffff a96777069d622325 +df8 df800000 df8fffff a96777069d622325 +df9 df900000 df9fffff a96777069d622325 +dfa dfa00000 dfafffff a96777069d622325 +dfb dfb00000 dfbfffff a96777069d622325 +dfc dfc00000 dfcfffff a96777069d622325 +dfd dfd00000 dfdfffff a96777069d622325 +dfe dfe00000 dfefffff a96777069d622325 +dff dff00000 dfffffff a96777069d622325 +e00 e0000000 e00fffff a96777069d622325 +e01 e0100000 e01fffff a96777069d622325 +e02 e0200000 e02fffff a96777069d622325 +e03 e0300000 e03fffff a96777069d622325 +e04 e0400000 e04fffff a96777069d622325 +e05 e0500000 e05fffff a96777069d622325 +e06 e0600000 e06fffff a96777069d622325 +e07 e0700000 e07fffff a96777069d622325 +e08 e0800000 e08fffff a96777069d622325 +e09 e0900000 e09fffff a96777069d622325 +e0a e0a00000 e0afffff a96777069d622325 +e0b e0b00000 e0bfffff a96777069d622325 +e0c e0c00000 e0cfffff a96777069d622325 +e0d e0d00000 e0dfffff a96777069d622325 +e0e e0e00000 e0efffff a96777069d622325 +e0f e0f00000 e0ffffff a96777069d622325 +e10 e1000000 e10fffff a96777069d622325 +e11 e1100000 e11fffff a96777069d622325 +e12 e1200000 e12fffff a96777069d622325 +e13 e1300000 e13fffff a96777069d622325 +e14 e1400000 e14fffff a96777069d622325 +e15 e1500000 e15fffff a96777069d622325 +e16 e1600000 e16fffff a96777069d622325 +e17 e1700000 e17fffff a96777069d622325 +e18 e1800000 e18fffff a96777069d622325 +e19 e1900000 e19fffff a96777069d622325 +e1a e1a00000 e1afffff a96777069d622325 +e1b e1b00000 e1bfffff a96777069d622325 +e1c e1c00000 e1cfffff a96777069d622325 +e1d e1d00000 e1dfffff a96777069d622325 +e1e e1e00000 e1efffff a96777069d622325 +e1f e1f00000 e1ffffff a96777069d622325 +e20 e2000000 e20fffff a96777069d622325 +e21 e2100000 e21fffff a96777069d622325 +e22 e2200000 e22fffff a96777069d622325 +e23 e2300000 e23fffff a96777069d622325 +e24 e2400000 e24fffff a96777069d622325 +e25 e2500000 e25fffff a96777069d622325 +e26 e2600000 e26fffff a96777069d622325 +e27 e2700000 e27fffff a96777069d622325 +e28 e2800000 e28fffff a96777069d622325 +e29 e2900000 e29fffff a96777069d622325 +e2a e2a00000 e2afffff a96777069d622325 +e2b e2b00000 e2bfffff a96777069d622325 +e2c e2c00000 e2cfffff a96777069d622325 +e2d e2d00000 e2dfffff a96777069d622325 +e2e e2e00000 e2efffff a96777069d622325 +e2f e2f00000 e2ffffff a96777069d622325 +e30 e3000000 e30fffff a96777069d622325 +e31 e3100000 e31fffff a96777069d622325 +e32 e3200000 e32fffff a96777069d622325 +e33 e3300000 e33fffff a96777069d622325 +e34 e3400000 e34fffff a96777069d622325 +e35 e3500000 e35fffff a96777069d622325 +e36 e3600000 e36fffff a96777069d622325 +e37 e3700000 e37fffff a96777069d622325 +e38 e3800000 e38fffff a96777069d622325 +e39 e3900000 e39fffff a96777069d622325 +e3a e3a00000 e3afffff a96777069d622325 +e3b e3b00000 e3bfffff a96777069d622325 +e3c e3c00000 e3cfffff a96777069d622325 +e3d e3d00000 e3dfffff a96777069d622325 +e3e e3e00000 e3efffff a96777069d622325 +e3f e3f00000 e3ffffff a96777069d622325 +e40 e4000000 e40fffff a96777069d622325 +e41 e4100000 e41fffff a96777069d622325 +e42 e4200000 e42fffff a96777069d622325 +e43 e4300000 e43fffff a96777069d622325 +e44 e4400000 e44fffff a96777069d622325 +e45 e4500000 e45fffff a96777069d622325 +e46 e4600000 e46fffff a96777069d622325 +e47 e4700000 e47fffff a96777069d622325 +e48 e4800000 e48fffff a96777069d622325 +e49 e4900000 e49fffff a96777069d622325 +e4a e4a00000 e4afffff a96777069d622325 +e4b e4b00000 e4bfffff a96777069d622325 +e4c e4c00000 e4cfffff a96777069d622325 +e4d e4d00000 e4dfffff a96777069d622325 +e4e e4e00000 e4efffff a96777069d622325 +e4f e4f00000 e4ffffff a96777069d622325 +e50 e5000000 e50fffff a96777069d622325 +e51 e5100000 e51fffff a96777069d622325 +e52 e5200000 e52fffff a96777069d622325 +e53 e5300000 e53fffff a96777069d622325 +e54 e5400000 e54fffff a96777069d622325 +e55 e5500000 e55fffff a96777069d622325 +e56 e5600000 e56fffff a96777069d622325 +e57 e5700000 e57fffff a96777069d622325 +e58 e5800000 e58fffff a96777069d622325 +e59 e5900000 e59fffff a96777069d622325 +e5a e5a00000 e5afffff a96777069d622325 +e5b e5b00000 e5bfffff a96777069d622325 +e5c e5c00000 e5cfffff a96777069d622325 +e5d e5d00000 e5dfffff a96777069d622325 +e5e e5e00000 e5efffff a96777069d622325 +e5f e5f00000 e5ffffff a96777069d622325 +e60 e6000000 e60fffff a96777069d622325 +e61 e6100000 e61fffff a96777069d622325 +e62 e6200000 e62fffff a96777069d622325 +e63 e6300000 e63fffff a96777069d622325 +e64 e6400000 e64fffff a96777069d622325 +e65 e6500000 e65fffff a96777069d622325 +e66 e6600000 e66fffff a96777069d622325 +e67 e6700000 e67fffff a96777069d622325 +e68 e6800000 e68fffff a96777069d622325 +e69 e6900000 e69fffff a96777069d622325 +e6a e6a00000 e6afffff a96777069d622325 +e6b e6b00000 e6bfffff a96777069d622325 +e6c e6c00000 e6cfffff a96777069d622325 +e6d e6d00000 e6dfffff a96777069d622325 +e6e e6e00000 e6efffff a96777069d622325 +e6f e6f00000 e6ffffff a96777069d622325 +e70 e7000000 e70fffff a96777069d622325 +e71 e7100000 e71fffff a96777069d622325 +e72 e7200000 e72fffff a96777069d622325 +e73 e7300000 e73fffff a96777069d622325 +e74 e7400000 e74fffff a96777069d622325 +e75 e7500000 e75fffff a96777069d622325 +e76 e7600000 e76fffff a96777069d622325 +e77 e7700000 e77fffff a96777069d622325 +e78 e7800000 e78fffff a96777069d622325 +e79 e7900000 e79fffff a96777069d622325 +e7a e7a00000 e7afffff a96777069d622325 +e7b e7b00000 e7bfffff a96777069d622325 +e7c e7c00000 e7cfffff a96777069d622325 +e7d e7d00000 e7dfffff a96777069d622325 +e7e e7e00000 e7efffff a96777069d622325 +e7f e7f00000 e7ffffff a96777069d622325 +e80 e8000000 e80fffff a96777069d622325 +e81 e8100000 e81fffff a96777069d622325 +e82 e8200000 e82fffff a96777069d622325 +e83 e8300000 e83fffff a96777069d622325 +e84 e8400000 e84fffff a96777069d622325 +e85 e8500000 e85fffff a96777069d622325 +e86 e8600000 e86fffff a96777069d622325 +e87 e8700000 e87fffff a96777069d622325 +e88 e8800000 e88fffff a96777069d622325 +e89 e8900000 e89fffff a96777069d622325 +e8a e8a00000 e8afffff a96777069d622325 +e8b e8b00000 e8bfffff a96777069d622325 +e8c e8c00000 e8cfffff a96777069d622325 +e8d e8d00000 e8dfffff a96777069d622325 +e8e e8e00000 e8efffff a96777069d622325 +e8f e8f00000 e8ffffff a96777069d622325 +e90 e9000000 e90fffff a96777069d622325 +e91 e9100000 e91fffff a96777069d622325 +e92 e9200000 e92fffff a96777069d622325 +e93 e9300000 e93fffff a96777069d622325 +e94 e9400000 e94fffff a96777069d622325 +e95 e9500000 e95fffff a96777069d622325 +e96 e9600000 e96fffff a96777069d622325 +e97 e9700000 e97fffff a96777069d622325 +e98 e9800000 e98fffff a96777069d622325 +e99 e9900000 e99fffff a96777069d622325 +e9a e9a00000 e9afffff a96777069d622325 +e9b e9b00000 e9bfffff a96777069d622325 +e9c e9c00000 e9cfffff a96777069d622325 +e9d e9d00000 e9dfffff a96777069d622325 +e9e e9e00000 e9efffff a96777069d622325 +e9f e9f00000 e9ffffff a96777069d622325 +ea0 ea000000 ea0fffff a96777069d622325 +ea1 ea100000 ea1fffff a96777069d622325 +ea2 ea200000 ea2fffff a96777069d622325 +ea3 ea300000 ea3fffff a96777069d622325 +ea4 ea400000 ea4fffff a96777069d622325 +ea5 ea500000 ea5fffff a96777069d622325 +ea6 ea600000 ea6fffff a96777069d622325 +ea7 ea700000 ea7fffff a96777069d622325 +ea8 ea800000 ea8fffff a96777069d622325 +ea9 ea900000 ea9fffff a96777069d622325 +eaa eaa00000 eaafffff a96777069d622325 +eab eab00000 eabfffff a96777069d622325 +eac eac00000 eacfffff a96777069d622325 +ead ead00000 eadfffff a96777069d622325 +eae eae00000 eaefffff a96777069d622325 +eaf eaf00000 eaffffff a96777069d622325 +eb0 eb000000 eb0fffff a96777069d622325 +eb1 eb100000 eb1fffff a96777069d622325 +eb2 eb200000 eb2fffff a96777069d622325 +eb3 eb300000 eb3fffff a96777069d622325 +eb4 eb400000 eb4fffff a96777069d622325 +eb5 eb500000 eb5fffff a96777069d622325 +eb6 eb600000 eb6fffff a96777069d622325 +eb7 eb700000 eb7fffff a96777069d622325 +eb8 eb800000 eb8fffff a96777069d622325 +eb9 eb900000 eb9fffff a96777069d622325 +eba eba00000 ebafffff a96777069d622325 +ebb ebb00000 ebbfffff a96777069d622325 +ebc ebc00000 ebcfffff a96777069d622325 +ebd ebd00000 ebdfffff a96777069d622325 +ebe ebe00000 ebefffff a96777069d622325 +ebf ebf00000 ebffffff a96777069d622325 +ec0 ec000000 ec0fffff a96777069d622325 +ec1 ec100000 ec1fffff a96777069d622325 +ec2 ec200000 ec2fffff a96777069d622325 +ec3 ec300000 ec3fffff a96777069d622325 +ec4 ec400000 ec4fffff a96777069d622325 +ec5 ec500000 ec5fffff a96777069d622325 +ec6 ec600000 ec6fffff a96777069d622325 +ec7 ec700000 ec7fffff a96777069d622325 +ec8 ec800000 ec8fffff a96777069d622325 +ec9 ec900000 ec9fffff a96777069d622325 +eca eca00000 ecafffff a96777069d622325 +ecb ecb00000 ecbfffff a96777069d622325 +ecc ecc00000 eccfffff a96777069d622325 +ecd ecd00000 ecdfffff a96777069d622325 +ece ece00000 ecefffff a96777069d622325 +ecf ecf00000 ecffffff a96777069d622325 +ed0 ed000000 ed0fffff a96777069d622325 +ed1 ed100000 ed1fffff a96777069d622325 +ed2 ed200000 ed2fffff a96777069d622325 +ed3 ed300000 ed3fffff a96777069d622325 +ed4 ed400000 ed4fffff a96777069d622325 +ed5 ed500000 ed5fffff a96777069d622325 +ed6 ed600000 ed6fffff a96777069d622325 +ed7 ed700000 ed7fffff a96777069d622325 +ed8 ed800000 ed8fffff a96777069d622325 +ed9 ed900000 ed9fffff a96777069d622325 +eda eda00000 edafffff a96777069d622325 +edb edb00000 edbfffff a96777069d622325 +edc edc00000 edcfffff a96777069d622325 +edd edd00000 eddfffff a96777069d622325 +ede ede00000 edefffff a96777069d622325 +edf edf00000 edffffff a96777069d622325 +ee0 ee000000 ee0fffff a96777069d622325 +ee1 ee100000 ee1fffff a96777069d622325 +ee2 ee200000 ee2fffff a96777069d622325 +ee3 ee300000 ee3fffff a96777069d622325 +ee4 ee400000 ee4fffff a96777069d622325 +ee5 ee500000 ee5fffff a96777069d622325 +ee6 ee600000 ee6fffff a96777069d622325 +ee7 ee700000 ee7fffff a96777069d622325 +ee8 ee800000 ee8fffff a96777069d622325 +ee9 ee900000 ee9fffff a96777069d622325 +eea eea00000 eeafffff a96777069d622325 +eeb eeb00000 eebfffff a96777069d622325 +eec eec00000 eecfffff a96777069d622325 +eed eed00000 eedfffff a96777069d622325 +eee eee00000 eeefffff a96777069d622325 +eef eef00000 eeffffff a96777069d622325 +ef0 ef000000 ef0fffff a96777069d622325 +ef1 ef100000 ef1fffff a96777069d622325 +ef2 ef200000 ef2fffff a96777069d622325 +ef3 ef300000 ef3fffff a96777069d622325 +ef4 ef400000 ef4fffff a96777069d622325 +ef5 ef500000 ef5fffff a96777069d622325 +ef6 ef600000 ef6fffff a96777069d622325 +ef7 ef700000 ef7fffff a96777069d622325 +ef8 ef800000 ef8fffff a96777069d622325 +ef9 ef900000 ef9fffff a96777069d622325 +efa efa00000 efafffff a96777069d622325 +efb efb00000 efbfffff a96777069d622325 +efc efc00000 efcfffff a96777069d622325 +efd efd00000 efdfffff a96777069d622325 +efe efe00000 efefffff a96777069d622325 +eff eff00000 efffffff a96777069d622325 +f00 f0000000 f00fffff a96777069d622325 +f01 f0100000 f01fffff a96777069d622325 +f02 f0200000 f02fffff a96777069d622325 +f03 f0300000 f03fffff a96777069d622325 +f04 f0400000 f04fffff a96777069d622325 +f05 f0500000 f05fffff a96777069d622325 +f06 f0600000 f06fffff a96777069d622325 +f07 f0700000 f07fffff a96777069d622325 +f08 f0800000 f08fffff a96777069d622325 +f09 f0900000 f09fffff a96777069d622325 +f0a f0a00000 f0afffff a96777069d622325 +f0b f0b00000 f0bfffff a96777069d622325 +f0c f0c00000 f0cfffff a96777069d622325 +f0d f0d00000 f0dfffff a96777069d622325 +f0e f0e00000 f0efffff a96777069d622325 +f0f f0f00000 f0ffffff a96777069d622325 +f10 f1000000 f10fffff a96777069d622325 +f11 f1100000 f11fffff a96777069d622325 +f12 f1200000 f12fffff a96777069d622325 +f13 f1300000 f13fffff a96777069d622325 +f14 f1400000 f14fffff a96777069d622325 +f15 f1500000 f15fffff a96777069d622325 +f16 f1600000 f16fffff a96777069d622325 +f17 f1700000 f17fffff a96777069d622325 +f18 f1800000 f18fffff a96777069d622325 +f19 f1900000 f19fffff a96777069d622325 +f1a f1a00000 f1afffff a96777069d622325 +f1b f1b00000 f1bfffff a96777069d622325 +f1c f1c00000 f1cfffff a96777069d622325 +f1d f1d00000 f1dfffff a96777069d622325 +f1e f1e00000 f1efffff a96777069d622325 +f1f f1f00000 f1ffffff a96777069d622325 +f20 f2000000 f20fffff a96777069d622325 +f21 f2100000 f21fffff a96777069d622325 +f22 f2200000 f22fffff a96777069d622325 +f23 f2300000 f23fffff a96777069d622325 +f24 f2400000 f24fffff a96777069d622325 +f25 f2500000 f25fffff a96777069d622325 +f26 f2600000 f26fffff a96777069d622325 +f27 f2700000 f27fffff a96777069d622325 +f28 f2800000 f28fffff a96777069d622325 +f29 f2900000 f29fffff a96777069d622325 +f2a f2a00000 f2afffff a96777069d622325 +f2b f2b00000 f2bfffff a96777069d622325 +f2c f2c00000 f2cfffff a96777069d622325 +f2d f2d00000 f2dfffff a96777069d622325 +f2e f2e00000 f2efffff a96777069d622325 +f2f f2f00000 f2ffffff a96777069d622325 +f30 f3000000 f30fffff a96777069d622325 +f31 f3100000 f31fffff a96777069d622325 +f32 f3200000 f32fffff a96777069d622325 +f33 f3300000 f33fffff a96777069d622325 +f34 f3400000 f34fffff a96777069d622325 +f35 f3500000 f35fffff a96777069d622325 +f36 f3600000 f36fffff a96777069d622325 +f37 f3700000 f37fffff a96777069d622325 +f38 f3800000 f38fffff a96777069d622325 +f39 f3900000 f39fffff a96777069d622325 +f3a f3a00000 f3afffff a96777069d622325 +f3b f3b00000 f3bfffff a96777069d622325 +f3c f3c00000 f3cfffff a96777069d622325 +f3d f3d00000 f3dfffff a96777069d622325 +f3e f3e00000 f3efffff a96777069d622325 +f3f f3f00000 f3ffffff a96777069d622325 +f40 f4000000 f40fffff a96777069d622325 +f41 f4100000 f41fffff a96777069d622325 +f42 f4200000 f42fffff a96777069d622325 +f43 f4300000 f43fffff a96777069d622325 +f44 f4400000 f44fffff a96777069d622325 +f45 f4500000 f45fffff a96777069d622325 +f46 f4600000 f46fffff a96777069d622325 +f47 f4700000 f47fffff a96777069d622325 +f48 f4800000 f48fffff a96777069d622325 +f49 f4900000 f49fffff a96777069d622325 +f4a f4a00000 f4afffff a96777069d622325 +f4b f4b00000 f4bfffff a96777069d622325 +f4c f4c00000 f4cfffff a96777069d622325 +f4d f4d00000 f4dfffff a96777069d622325 +f4e f4e00000 f4efffff a96777069d622325 +f4f f4f00000 f4ffffff a96777069d622325 +f50 f5000000 f50fffff a96777069d622325 +f51 f5100000 f51fffff a96777069d622325 +f52 f5200000 f52fffff a96777069d622325 +f53 f5300000 f53fffff a96777069d622325 +f54 f5400000 f54fffff a96777069d622325 +f55 f5500000 f55fffff a96777069d622325 +f56 f5600000 f56fffff a96777069d622325 +f57 f5700000 f57fffff a96777069d622325 +f58 f5800000 f58fffff a96777069d622325 +f59 f5900000 f59fffff a96777069d622325 +f5a f5a00000 f5afffff a96777069d622325 +f5b f5b00000 f5bfffff a96777069d622325 +f5c f5c00000 f5cfffff a96777069d622325 +f5d f5d00000 f5dfffff a96777069d622325 +f5e f5e00000 f5efffff a96777069d622325 +f5f f5f00000 f5ffffff a96777069d622325 +f60 f6000000 f60fffff a96777069d622325 +f61 f6100000 f61fffff a96777069d622325 +f62 f6200000 f62fffff a96777069d622325 +f63 f6300000 f63fffff a96777069d622325 +f64 f6400000 f64fffff a96777069d622325 +f65 f6500000 f65fffff a96777069d622325 +f66 f6600000 f66fffff a96777069d622325 +f67 f6700000 f67fffff a96777069d622325 +f68 f6800000 f68fffff a96777069d622325 +f69 f6900000 f69fffff a96777069d622325 +f6a f6a00000 f6afffff a96777069d622325 +f6b f6b00000 f6bfffff a96777069d622325 +f6c f6c00000 f6cfffff a96777069d622325 +f6d f6d00000 f6dfffff a96777069d622325 +f6e f6e00000 f6efffff a96777069d622325 +f6f f6f00000 f6ffffff a96777069d622325 +f70 f7000000 f70fffff a96777069d622325 +f71 f7100000 f71fffff a96777069d622325 +f72 f7200000 f72fffff a96777069d622325 +f73 f7300000 f73fffff a96777069d622325 +f74 f7400000 f74fffff a96777069d622325 +f75 f7500000 f75fffff a96777069d622325 +f76 f7600000 f76fffff a96777069d622325 +f77 f7700000 f77fffff a96777069d622325 +f78 f7800000 f78fffff a96777069d622325 +f79 f7900000 f79fffff a96777069d622325 +f7a f7a00000 f7afffff a96777069d622325 +f7b f7b00000 f7bfffff a96777069d622325 +f7c f7c00000 f7cfffff a96777069d622325 +f7d f7d00000 f7dfffff a96777069d622325 +f7e f7e00000 f7efffff a96777069d622325 +f7f f7f00000 f7ffffff a96777069d622325 +f80 f8000000 f80fffff a96777069d622325 +f81 f8100000 f81fffff a96777069d622325 +f82 f8200000 f82fffff a96777069d622325 +f83 f8300000 f83fffff a96777069d622325 +f84 f8400000 f84fffff a96777069d622325 +f85 f8500000 f85fffff a96777069d622325 +f86 f8600000 f86fffff a96777069d622325 +f87 f8700000 f87fffff a96777069d622325 +f88 f8800000 f88fffff a96777069d622325 +f89 f8900000 f89fffff a96777069d622325 +f8a f8a00000 f8afffff a96777069d622325 +f8b f8b00000 f8bfffff a96777069d622325 +f8c f8c00000 f8cfffff a96777069d622325 +f8d f8d00000 f8dfffff a96777069d622325 +f8e f8e00000 f8efffff a96777069d622325 +f8f f8f00000 f8ffffff a96777069d622325 +f90 f9000000 f90fffff a96777069d622325 +f91 f9100000 f91fffff a96777069d622325 +f92 f9200000 f92fffff a96777069d622325 +f93 f9300000 f93fffff a96777069d622325 +f94 f9400000 f94fffff a96777069d622325 +f95 f9500000 f95fffff a96777069d622325 +f96 f9600000 f96fffff a96777069d622325 +f97 f9700000 f97fffff a96777069d622325 +f98 f9800000 f98fffff a96777069d622325 +f99 f9900000 f99fffff a96777069d622325 +f9a f9a00000 f9afffff a96777069d622325 +f9b f9b00000 f9bfffff a96777069d622325 +f9c f9c00000 f9cfffff a96777069d622325 +f9d f9d00000 f9dfffff a96777069d622325 +f9e f9e00000 f9efffff a96777069d622325 +f9f f9f00000 f9ffffff a96777069d622325 +fa0 fa000000 fa0fffff a96777069d622325 +fa1 fa100000 fa1fffff a96777069d622325 +fa2 fa200000 fa2fffff a96777069d622325 +fa3 fa300000 fa3fffff a96777069d622325 +fa4 fa400000 fa4fffff a96777069d622325 +fa5 fa500000 fa5fffff a96777069d622325 +fa6 fa600000 fa6fffff a96777069d622325 +fa7 fa700000 fa7fffff a96777069d622325 +fa8 fa800000 fa8fffff a96777069d622325 +fa9 fa900000 fa9fffff a96777069d622325 +faa faa00000 faafffff a96777069d622325 +fab fab00000 fabfffff a96777069d622325 +fac fac00000 facfffff a96777069d622325 +fad fad00000 fadfffff a96777069d622325 +fae fae00000 faefffff a96777069d622325 +faf faf00000 faffffff a96777069d622325 +fb0 fb000000 fb0fffff a96777069d622325 +fb1 fb100000 fb1fffff a96777069d622325 +fb2 fb200000 fb2fffff a96777069d622325 +fb3 fb300000 fb3fffff a96777069d622325 +fb4 fb400000 fb4fffff a96777069d622325 +fb5 fb500000 fb5fffff a96777069d622325 +fb6 fb600000 fb6fffff a96777069d622325 +fb7 fb700000 fb7fffff a96777069d622325 +fb8 fb800000 fb8fffff a96777069d622325 +fb9 fb900000 fb9fffff a96777069d622325 +fba fba00000 fbafffff a96777069d622325 +fbb fbb00000 fbbfffff a96777069d622325 +fbc fbc00000 fbcfffff a96777069d622325 +fbd fbd00000 fbdfffff a96777069d622325 +fbe fbe00000 fbefffff a96777069d622325 +fbf fbf00000 fbffffff a96777069d622325 +fc0 fc000000 fc0fffff a96777069d622325 +fc1 fc100000 fc1fffff a96777069d622325 +fc2 fc200000 fc2fffff a96777069d622325 +fc3 fc300000 fc3fffff a96777069d622325 +fc4 fc400000 fc4fffff a96777069d622325 +fc5 fc500000 fc5fffff a96777069d622325 +fc6 fc600000 fc6fffff a96777069d622325 +fc7 fc700000 fc7fffff a96777069d622325 +fc8 fc800000 fc8fffff a96777069d622325 +fc9 fc900000 fc9fffff a96777069d622325 +fca fca00000 fcafffff a96777069d622325 +fcb fcb00000 fcbfffff a96777069d622325 +fcc fcc00000 fccfffff a96777069d622325 +fcd fcd00000 fcdfffff a96777069d622325 +fce fce00000 fcefffff a96777069d622325 +fcf fcf00000 fcffffff a96777069d622325 +fd0 fd000000 fd0fffff a96777069d622325 +fd1 fd100000 fd1fffff a96777069d622325 +fd2 fd200000 fd2fffff a96777069d622325 +fd3 fd300000 fd3fffff a96777069d622325 +fd4 fd400000 fd4fffff a96777069d622325 +fd5 fd500000 fd5fffff a96777069d622325 +fd6 fd600000 fd6fffff a96777069d622325 +fd7 fd700000 fd7fffff a96777069d622325 +fd8 fd800000 fd8fffff a96777069d622325 +fd9 fd900000 fd9fffff a96777069d622325 +fda fda00000 fdafffff a96777069d622325 +fdb fdb00000 fdbfffff a96777069d622325 +fdc fdc00000 fdcfffff a96777069d622325 +fdd fdd00000 fddfffff a96777069d622325 +fde fde00000 fdefffff a96777069d622325 +fdf fdf00000 fdffffff a96777069d622325 +fe0 fe000000 fe0fffff a96777069d622325 +fe1 fe100000 fe1fffff a96777069d622325 +fe2 fe200000 fe2fffff a96777069d622325 +fe3 fe300000 fe3fffff a96777069d622325 +fe4 fe400000 fe4fffff a96777069d622325 +fe5 fe500000 fe5fffff a96777069d622325 +fe6 fe600000 fe6fffff a96777069d622325 +fe7 fe700000 fe7fffff a96777069d622325 +fe8 fe800000 fe8fffff a96777069d622325 +fe9 fe900000 fe9fffff a96777069d622325 +fea fea00000 feafffff a96777069d622325 +feb feb00000 febfffff a96777069d622325 +fec fec00000 fecfffff a96777069d622325 +fed fed00000 fedfffff a96777069d622325 +fee fee00000 feefffff a96777069d622325 +fef fef00000 feffffff a96777069d622325 +ff0 ff000000 ff0fffff a96777069d622325 +ff1 ff100000 ff1fffff a96777069d622325 +ff2 ff200000 ff2fffff a96777069d622325 +ff3 ff300000 ff3fffff a96777069d622325 +ff4 ff400000 ff4fffff a96777069d622325 +ff5 ff500000 ff5fffff a96777069d622325 +ff6 ff600000 ff6fffff a96777069d622325 +ff7 ff700000 ff7fffff a96777069d622325 +ff8 ff800000 ff8fffff 658347799e722325 +ff9 ff900000 ff9fffff c9fc43625f722325 +ffa ffa00000 ffafffff f9debd71ccf22325 +ffb ffb00000 ffbfffff 5691c6ac47b22325 +ffc ffc00000 ffcfffff 14cc4435a6b22325 +ffd ffd00000 ffdfffff c9fc43625f722325 +ffe ffe00000 ffefffff f9debd71ccf22325 +fff fff00000 ffffffff 5691c6ac47b22325 +# __expf_sse2 (GLIBC_TUNABLES=glibc.cpu.hwcaps=-AVX2,-FMA), blocks whose digest differs from the above: +# sse2 420 42000000 420fffff 5f7f0cb4bfc51070 +# sse2 c27 c2700000 c27fffff dd918255a85a42b2 diff --git a/tests/kernels/fixtures/swiglu_vectors.txt b/tests/kernels/fixtures/swiglu_vectors.txt new file mode 100644 index 00000000..38c0a1f0 --- /dev/null +++ b/tests/kernels/fixtures/swiglu_vectors.txt @@ -0,0 +1,4235 @@ +# basalt's SwiGLU on x86-64 (docs/research/basalt-cpu-expf.md section 4): res = (g / (1.f + std::exp(-g))) * u, pool.cpp:434 as basalt +# builds it (x86-64 gcc 14.3, -std=c++20 -O3 -DNDEBUG, baseline x86-64: one scalar expf call, then addss, divss, mulss). +# Measured 2026-10-18 on Compiler Explorer (Xeon Platinum 8375C and 8488C), glibc 2.39 (Ubuntu 24.04 libc6 +# 2.39-0ubuntu8.9), expf resolved to __expf_fma (libm+0x7dc40), MXCSR control 0x1f80. +# Rows 0-113: 57 special g (thresholds, the variant-sensitive g = c202422f, zeros, infinities, NaNs, subnormals), +# each with u = 3f800000 then u = 3fb504f3; rows 114-129: special (g, u) pairs; rows 130-4225: 4096 random pairs, +# s = 0x20261018, a = 2 * (splitmix64(s) >> 11) * 2^-53 - 1, b likewise (next draw), g = (float) (40 a^3), +# u = (float) (4 b^3). FNV digest of the res column (the sweep's digest rule): dfdc90ecf37deba2. +# columns: g u res (IEEE binary32 bit patterns, hex) +c202422f 3f800000 aa840025 +c202422f 3fb504f3 aabaad4f +427c65d9 3f800000 427c65d9 +427c65d9 3fb504f3 42b278e4 +c2b17215 3f800000 82b1731c +c2b17215 3fb504f3 82faf3a2 +c2b17216 3f800000 82b172c5 +c2b17216 3fb504f3 82faf327 +c2b17217 3f800000 82b1726d +c2b17217 3fb504f3 82faf2ab +c2b17218 3f800000 80000000 +c2b17218 3fb504f3 80000000 +c2b17219 3f800000 80000000 +c2b17219 3fb504f3 80000000 +c2b00000 3f800000 83354ddc +c2b00000 3fb504f3 8380338e +c2afffff 3f800000 83354e35 +c2afffff 3fb504f3 838033cd +42b00000 3f800000 42b00000 +42b00000 3fb504f3 42f8e6ce +42afffff 3f800000 42afffff +42afffff 3fb504f3 42f8e6cd +42aeac4e 3f800000 42aeac4e +42aeac4e 3fb504f3 42f70667 +42aeac4f 3f800000 42aeac4f +42aeac4f 3fb504f3 42f70669 +42aeac50 3f800000 42aeac50 +42aeac50 3fb504f3 42f7066a +42aeac51 3f800000 42aeac51 +42aeac51 3fb504f3 42f7066c +42aeac52 3f800000 42aeac52 +42aeac52 3fb504f3 42f7066d +42ce8ecd 3f800000 42ce8ecd +42ce8ecd 3fb504f3 43120ef5 +42ce8ece 3f800000 42ce8ece +42ce8ece 3fb504f3 43120ef6 +42ce8ecf 3f800000 42ce8ecf +42ce8ecf 3fb504f3 43120ef7 +42ce8ed0 3f800000 42ce8ed0 +42ce8ed0 3fb504f3 43120ef7 +42ce8ed1 3f800000 42ce8ed1 +42ce8ed1 3fb504f3 43120ef8 +42cff1b2 3f800000 42cff1b2 +42cff1b2 3fb504f3 431309e8 +42cff1b3 3f800000 42cff1b3 +42cff1b3 3fb504f3 431309e9 +42cff1b4 3f800000 42cff1b4 +42cff1b4 3fb504f3 431309e9 +42cff1b5 3f800000 42cff1b5 +42cff1b5 3fb504f3 431309ea +42cff1b6 3f800000 42cff1b6 +42cff1b6 3fb504f3 431309eb +4185158f 3f800000 4185158e +4185158f 3fb504f3 41bc35a0 +41851590 3f800000 4185158f +41851590 3fb504f3 41bc35a2 +41851591 3f800000 41851590 +41851591 3fb504f3 41bc35a3 +41851592 3f800000 41851592 +41851592 3fb504f3 41bc35a6 +41851593 3f800000 41851593 +41851593 3fb504f3 41bc35a7 +41851594 3f800000 41851594 +41851594 3fb504f3 41bc35a9 +41851595 3f800000 41851595 +41851595 3fb504f3 41bc35aa +c185158f 3f800000 b58515c0 +c185158f 3fb504f3 b5bc35e7 +c1851590 3f800000 b58515b0 +c1851590 3fb504f3 b5bc35d0 +c1851591 3f800000 b58515a1 +c1851591 3fb504f3 b5bc35bb +c1851592 3f800000 b5851592 +c1851592 3fb504f3 b5bc35a6 +c1851593 3f800000 b5851582 +c1851593 3fb504f3 b5bc358f +c1851594 3f800000 b5851573 +c1851594 3fb504f3 b5bc357a +c1851595 3f800000 b5851563 +c1851595 3fb504f3 b5bc3563 +00000000 3f800000 00000000 +00000000 3fb504f3 00000000 +80000000 3f800000 80000000 +80000000 3fb504f3 80000000 +7f800000 3f800000 7f800000 +7f800000 3fb504f3 7f800000 +ff800000 3f800000 ffc00000 +ff800000 3fb504f3 ffc00000 +7fc00000 3f800000 7fc00000 +7fc00000 3fb504f3 7fc00000 +ffc00000 3f800000 ffc00000 +ffc00000 3fb504f3 ffc00000 +7fc12345 3f800000 7fc12345 +7fc12345 3fb504f3 7fc12345 +7f812345 3f800000 7fc12345 +7f812345 3fb504f3 7fc12345 +ff812345 3f800000 ffc12345 +ff812345 3fb504f3 ffc12345 +00000001 3f800000 00000000 +00000001 3fb504f3 00000000 +80000001 3f800000 80000000 +80000001 3fb504f3 80000000 +007fffff 3f800000 00400000 +007fffff 3fb504f3 005a827a +807fffff 3f800000 80400000 +807fffff 3fb504f3 805a827a +7f7fffff 3f800000 7f7fffff +7f7fffff 3fb504f3 7f800000 +ff7fffff 3f800000 80000000 +ff7fffff 3fb504f3 80000000 +3f800000 3f800000 3f3b26a8 +3f800000 3fb504f3 3f8455f3 +bf800000 3f800000 be89b2b1 +bf800000 3fb504f3 bec2bc01 +3f800000 00000000 00000000 +3f800000 80000000 80000000 +3f800000 7f800000 7f800000 +3f800000 ff800000 ff800000 +3f800000 7fc00000 7fc00000 +3f800000 7fa00000 7fe00000 +3f800000 7f7fffff 7f3b26a7 +3f800000 00000001 00000001 +00000000 7f800000 ffc00000 +80000000 ff800000 ffc00000 +00000000 7fc00000 7fc00000 +7fc12345 7fc54321 7fc12345 +c2b17218 7f800000 ffc00000 +7f800000 00000000 ffc00000 +7f7fffff 3fb504f3 7f800000 +42cff1b5 7f800000 7f800000 +403ce3f4 bd9fd537 be6026a7 +bf457fbf be239b05 3d1f9ed3 +c1993e6b 3f15fe8c b36730b4 +c0df47d1 3e836194 badaa951 +40abc348 3f99df3a 40cd8581 +c029aed8 3f0fec3c bdc932ab +c1957699 bfd6827f 34815208 +413826c9 3d43e50e 3f0ce9f3 +c0409026 3fc387da be5d58b7 +bbb5b047 3bd3db86 b795f161 +c0f2443b 3ebdab0e babd50a2 +4205b2da bde30ce9 c06d28ab +412ac84b 3f25182e 40dc4526 +bf9b2a7f 3ed0d24b bde82fc0 +3b8a3b1f 3b92dbb0 371eee51 +4085e070 bf636eac c06a4d7d +c18aa221 3ec23835 b452407e +40b2ab91 3e5b82fc 3f98a149 +3b20d404 c02835be bb539c30 +404df34d 3f052657 3fcdfd43 +c2161143 bffd64db 27882ce3 +bbe6f072 3fb9a5d1 bba6e244 +3f83cd67 3e2c7372 3e02d8c8 +c1bb65e0 3c1f8478 ad869f3b +c176b4e6 3c882228 b35d6124 +3d54cd2a bea49056 bc0c58e6 +4188311e bf345f40 c13fea6b +3ced394e 3fc3cf1a 3cb81313 +c18f5d67 bddbf5b9 33084d93 +40ae8ca1 3f550e87 4090a68f +bfea49af bf534231 3e55bf8c +41a54fdc beec19e0 c1187654 +40e71346 ba0cd0ba bb7e065a +3c600c96 bfa7ef00 bc13faa3 +bccad9cf bfb0b207 3c8a4710 +bfa65435 40242236 bf36ca58 +3e8e01de bc820b95 bb24283c +be58f6be 3f444388 bd94c7d1 +c1c49070 bf1bf4c4 2faf975b +bbe62cc4 4050bf43 bc3b0796 +40a4eab9 bd395b6f be6d71d0 +c0cb73a2 c06ec908 3d2818f0 +be4e5412 404652bf be8fcb19 +41aeb6b0 be1f7d2e c059b1cc +bc14bc4d 3b977ee7 b7af3d0a +c105046f be1f2227 39a60611 +c128b731 3bc41254 b5defd18 +3fb1dff8 3ec66c87 3edcbd3f +42049c10 40501470 42d792c6 +c191b85f b968082e 2e59bf4a +39ecb053 402136bb 3a15161b +bf48f978 bf1b628e 3e18d6d8 +c087f079 3bea1316 b9e02ba1 +bb806dcf be32dd54 39b31cbd +c19fc2df be933999 3251803f +3a2aacf7 3c336f33 366f5617 +c1bb2913 3e27fbfc af91dab0 +c096a1ee bfd3c72d 3d8ebbc6 +c0046a13 3f66a0ae be560db4 +c1b5ae0d bf419baf 3121de01 +c1479e4a 3d3b35e8 b6120d5f +42073655 400e9743 4296a00f +414c73c0 3c1e6cad 3dfd0c48 +4040e4f1 3e932049 3f535750 +4215cd03 bf128151 c1ab752f +c168f51a c006ba17 37744863 +3c95c80f 3dae1fcc 3a4d9e00 +40d038a1 bfc394be c11ed767 +3f905dc2 3c3a8101 3c1ee876 +c1845fcd 3f5e5e78 b57b4fe3 +40b851ef 3c9cdcdc 3de12c41 +c16e9509 c064b6c3 379569b0 +4209fd09 3ff6bf78 4285005b +3fc7d69e 3fdf05fe 400fe558 +420fa2c0 3e625e8c 40fe0574 +be3fab9d 3fabf2f0 bde97411 +c14eb8b7 c05e91d8 38e6b416 +3fcb5f68 bff06f77 c01e9f8a +3da4de50 3d704c19 3b20fb36 +40fde3b5 3fb70015 41356d37 +4095ddc6 3e59e5eb 3f7cc8b0 +4219cf0c 400f0568 42abdbce +c1936729 bfbbf89f 3490965e +40c3aa3b bdc8290e bf18a5fd +c0a1758d c0090ac9 3d8d8824 +c08a776d bfe6e192 3dd057d7 +bd27a2c8 ba825f02 37a73f6e +c1966fd5 3d4ba3e1 b1dad12a +c02e9391 40647693 bf18f1c0 +41dc7bd2 c05551a3 c2b7b955 +421a9c06 c04bcfa2 c2f62e3e +393ddde0 bfa26cb4 b8f0f3a4 +4150162d bf2bc27a c10b9ccf +40c2bfda 3e43f127 3f94b8fe +c1c5ea44 368ba4d6 a705b58d +c1fee779 bf4f2cf9 2ad2d2f5 +c02d2f77 3f7c04d6 be2ad10f +c0f9b1cb 3f00282e bad114b1 +41b11907 bea7a4c2 c0e7f29c +41b446e0 3e2de9be 4074f0ff +3b48d5dd 3d3eb0ff 3895d444 +c1e38f57 bd993d2c 2b84b996 +3c59ae12 bbbbd00d b820c2a6 +bf2de626 c06cfc47 3f58a165 +ba47b4d4 bf69fa6e 39b67525 +c1f1f8b3 bfaa54fc 2c4f25d6 +c0392f20 bde46ccf 3c8abc29 +4212a0bf 4034a029 42cee984 +c08ac7f0 3e97931e bc87c3fe +c1f9aff8 bdbb250c 29b30a85 +41bd477b beb6dd9d c10734ac +41602d88 be5e2db4 c0428f77 +c1912120 407f9433 b5809722 +bfb07cee bebf2115 3dd416ff +c1dfaddc 3e46120a ac88f480 +40517891 b8d83454 b9aa7313 +c18478c7 3f7a7628 b58beb02 +c158296f bf8eaae4 37ab6ee5 +41a867bf be9f6fb0 c0d1c3d1 +409f0557 40583134 41855de0 +c16fbc93 3ca91271 b3ce849a +bdabe509 bf28875d 3cd8d459 +4178007d bdf81e66 bff05de8 +c04fe1b4 3f9bdd71 be17733c +412d7f64 3fe0a99c 419841a7 +40e10b56 c0682198 c1cbe1bd +bb99a700 3cb0def8 b853d1d8 +c13d2f21 beeb57dc 3827038c +c0a73c63 3dc00188 bb2ba617 +41d9b02c bf4b71e3 c1acff8b +bf845d50 3e77a0f9 bd8654a7 +c0583191 4033c543 bea0446f +c123c080 3ecfeb8e b91c7dec +bde89a39 405f2c6c be3f45fa +40bcbad2 3f84c0b6 40c3339b +40683b20 3e6cf8c3 3f5168b1 +c056f9f0 bf9881ee 3e09b493 +c017b13a 3b8167ee ba51bb1f +bfe32aaf bf19a364 3e1e18da +4214bf8f bc247e91 bebf2884 +40651aa5 bf495461 c02f4a3a +409a2623 3ed39d6f 3ffcccea +bfe8f63e 3ded9a53 bcf12f37 +405d2714 401f413a 41055dba +c0296561 c0204a8c 3ee0a3dc +421281f0 3bfcd42f 3e90b157 +3cb15c04 bcc40e5c b9894ccc +c0bc2a25 c07c1dac 3d8431af +3df7725f 4013815c 3e172e0c +3f0d42ff 3e9e6781 3ddddc4a +bd3a7fcc 3d04b1ce ba3cf040 +c009772c b639ed3e 3526f92f +c0a9e1aa be1691c1 3b7be06e +b5468d63 400302e5 b54b392c +c1baa6df 3fa7f6e0 b11afcc3 +c13a04b7 be81f70d 37dd0eba +bf7e99d6 be0044e5 3d09c84a +4107d100 ba5c8e9f bbe9fa38 +3f8ff714 407609b4 4050e3f1 +c14abd4e bf807d12 38278799 +bf1870e5 3e7d73b4 bd568a8b +c03e05c9 3b555e3f b9f78865 +4148303c 3f032b91 40cd254f +c1bc1ff4 3c9545b2 ade6f609 +c145e057 bf2a0af3 3812a06a +bfcd4baf be0df70c 3d18804e +ba8301cb bf88b6cd 3a0bdb1a +3fa87e4b bf243dce bf2a7d5f +c1ff528f 3c304d8e a7aa8c18 +41ed9d66 bf6f8135 c1de4de0 +bb854c34 c0067732 3b8bbefe +c0b38edf be165b43 3b44b9ff +bf93b0fe bee813e0 3e006bd9 +c2047848 3ca4757a a74675c7 +bb156aa9 3fe9be30 bb084545 +407e2ce8 bd7152db be6b2bfa +c1832788 c0632ec1 369424c3 +c21e73c3 402ecfa8 a643177a +c0abba3f 3d303696 ba8cad0c +c1751282 40212b72 b7102dba +be5e3397 c0364d74 3e8d2217 +bdc99aae bfce4590 3d9a7416 +4180639f 40588e4a 425936d3 +3c876f83 bfee03a9 bc7dec26 +40d51e07 c0495f86 c1a76d2f +3dc3e70f befdfd7f bccba74e +c1957174 beef9910 3390c9fe +c0265b33 3de782a6 bca686fc +c2043485 406e25b4 ab193711 +c0ec961c c008fa6c 3c1f6f6b +bf13e5de becebae1 3dabb95f +3e61313e bed5cfc2 bd50adca +bb1272f6 403532c7 bb4f155d +bff15bd4 3fff6305 befdc60b +41c779a0 be2dc372 c087657c +bcb22563 3f468c8b bc08aa24 +bbb25f88 bf86f63d 3b3b901b +40814ef4 be06196b bf05211f +bd8b84b9 bfb506bd 3d3e991a +bf80473f 3d8a4851 bc94d89c +3f1370ed 40112c96 3f561746 +bbab8cb1 3c177dc0 b7ca8074 +40dedeca bce9a47b be4b36d3 +c1927767 3d31646c b2186c14 +bf248356 388badfa b7777e78 +3e08b8fb 3fed6aa3 3e074001 +c1eca55a 40019069 ad15ed85 +38469d84 bf8461d1 b7cd6b76 +3f73a5a5 3f34a07b 3ef80e50 +c1e10235 be9b2166 2cb6c30f +c18f8bdc 3f2cd5cc b451a9be +c03cbf1d becb6d89 3d6ee6e0 +be9f2478 407c388a bf049ead +3f1527ae be4c3724 bd98b273 +be292ada bd102f30 3b2eda36 +3ff168a0 3f0f949f 3f6b2147 +41915b11 c01dc810 c2332ce3 +3fb97d8f 3f359fb1 3f5527fb +421930dd 3b83139a 3e1cdf78 +3e818eab 4069dc8a 3f053f85 +b7f542f9 3ff4620f b7ea20e8 +40d8e1f7 bf635201 c0c05dbf +3db19b4a 3f958ee8 3d58832c +409ec5b2 bf26c9f9 c04d72ad +c0a7e68d 3ecbfdb7 bc335806 +bfffefa2 c009dd74 3f037f10 +c1903da0 401d89c1 b53010cf +3f1e67e6 3e9a7401 3df87667 +41899af3 bc08d51b be1319bb +41ccc81a 3ec1cb55 411b0582 +c181dd2c be918263 34dccb91 +3fc57e59 c01b7508 c0459db3 +418bfab3 be4755b4 c059fd7c +41e018ca beccb41b c133316a +3f89867f 40042978 3fd3b311 +3fbc247c 400a7424 4025759f +b7233d71 bf2dfdfc 365de4ad +4150f12d 3ff1564c 41c4f95f +3f6db74d be99816f be4c5827 +40012518 bf9b4f27 c00a4fd1 +c20b8568 bcfd134e 265cbb95 +c0306f8f bde77539 3c986210 +c1a5b28c 3e4f213f b1918e8b +3f1b3364 bf47b36a be9caf2e +c00db0ef bceedc02 3bd05e60 +c1c27838 4053d2f5 b1194934 +3f4c68f0 bd168e1f bca5cfd1 +bbb1d305 b9c6e49b 3589c80a +3ed32559 3f0ba7c2 3e0a9b2e +40da4b6c 3a0296e6 3b5e77e1 +421110eb c018b37f c2ad0f85 +3f74cb39 c0649383 c01de348 +42146617 3b518aeb 3df2efc0 +3d9e5e43 3ec499d7 3c7ca51e +c1b59704 40140772 b1fa3268 +befd29c8 bffc7a67 3ebd2dfc +bc32151f 3fff802e bc30c4ee +c2019a1c 3d814a1e a89c5232 +c093ae7e c06009ff 3e223322 +c00bd5d9 3f547186 be3bbc05 +419c5db5 c010e24e c230fde0 +4017fcc1 4049d8fa 40db4636 +bf2fb5c6 3feaabd7 bed7bb92 +c03e1fbd be3e9409 3cdce0f0 +3f8e08a3 bfb2a877 bf9517d8 +420be22c be0bbde7 c098b724 +c0fba02b 3fc5f1ac bb9930c3 +c190a9d9 bc70d4a5 31800637 +bb49c701 b9d9ba7b 352b5909 +3aced8ec bf16e2f3 b9f40636 +c201b54b 3d95cb6e a8b08362 +41815bd4 be26ef56 c028b4f6 +c1ddce51 bfcec530 2e332d9a +40637a2d 3fcc0588 40b03fd3 +c0330408 bf76efc5 3e1eceea +38bf17a8 3b9b407f 3467c9a2 +402eb36d 3e886cc4 3f2ecbcd +41b9674d b866149f baa6a1be +4119028d be1e336c bfbd1938 +c1bec1d5 3c045ac8 ad156d97 +c14eed6f bd1f4c59 35a32ba8 +c1e74086 bf0c9dfc 2c9c07a6 +c01653e7 c036b7e1 3f159f4d +c157674d 3b1754d5 b33e0048 +bfd453da c04668b0 3f528920 +c1e94581 3dc129b7 ab27f91e +c16e2fba 3e19fac5 b54de0ab +c20d914e 3afcdeb1 a4062aa4 +bdbe06b3 bd87aa7a 3b4011d5 +bbb59fca c04268c0 3c098b8e +be4ee5cf 3e42820f bc8d5f7e +3e85eb34 bd6560e5 bc0798a6 +4190d87b bf541e3e c17008c5 +c059100a 3d3aa7db bba4e4f9 +c2083ec3 3da5c9c2 a7a02434 +c2036958 3fe8a88a aab57047 +c123d273 37b92ab4 b20ad10a +41bd21f6 3a568351 3c9e7b68 +bf34ff2a 3f447575 be377dc9 +408d960f bcdd4ff3 bdf1e7ac +3f2cb2b7 bf31d8cb be9ef9d2 +c1a18f73 bfacd47d 33469e21 +c10d9ee1 c035b2bf 3b6bcac1 +3eb1e5f1 3fc13728 3e9d5cd8 +41f27967 3e2d95be 40a469df +3ef2b4bd 3d9becf6 3cb63986 +c03fbc0f bf42efc2 3dde7379 +c0653e8b 395c2673 b7aac329 +c21dfa89 bfd3e444 2604b2f4 +3ef28404 3f535f15 3e76cb17 +c1e6902a c077f5f0 2e157e95 +bb00741e 3fae9fed baaf1260 +3d13cbb5 c00c03ab bd2495a5 +c1b1bab0 3e69fa5a b09cc885 +4110cc33 3e19d171 3fadfbc8 +c0a120c4 3efec7a6 bc84a68e +410b37ac bde35fb9 bf77424f +41499413 3ff9ca9e 41c4b067 +41dd985b 4039855a 42a09688 +414fd881 bf18fd08 c0f86bd3 +c0798f75 bf39d3e2 3d662a0e +c18b9350 3f08b4bf b4847195 +c0392c4e bdac5fc2 3c5167f4 +3f27d97e c05578d7 bfb8464c +42041b44 bfecdd5e c27476bd +c126e686 4043652d ba763c60 +41a075de 3f12517f 41376c9b +408e4add bfec2d36 c101c0e9 +3dd5b314 bf826c5b bd651866 +be273afc 3eb831da bcdd0a9c +c213f562 402a2a6a a818c197 +c10c6f30 be7438c7 39a93aa2 +bf28232e bfbe3bca 3eaaa723 +3a6bda38 ba557c05 b4c4c579 +41b891ab be6f0071 c0ac5050 +3e90af66 3eb47235 3d6898d0 +4196cc7c c01b37e8 c236dd7b +bd3ff8ed bf33c2b7 3c83a487 +39ecd7dd 401c052f 3a1060af +c1b6ecb3 3f45dc52 b10e8e8c +c0ca46f5 beb8527f 3b85d28a +c10eaa03 c0638364 3b8b52be +3b265634 b840f203 b37b0d42 +c0fa575e c03da77a 3c1800e8 +bf0c87ea 3ce663bb bbb935c0 +c21ba0ac bf8f5a2d 261f2fc1 +3e363f62 bf304433 bd889f45 +4150082c bed8327b c0afafd0 +3efd28de bafbf0f5 ba1ac217 +404c52d2 bfd9e565 c0a70d12 +c0738611 40652f9a be97e6e2 +bd08bbb2 3c20ca85 b928e51a +c1950937 bfb4f8e8 34658448 +405c8ef2 3eb7ebc2 3f999094 +418c04e7 3c77a254 3e877184 +c1d12abe beaec36e 2e2d50a7 +c09876ab bed730ac 3c8ab38e +41034840 36be0298 3842d448 +40dcd790 3e1d1de2 3f876718 +3bafeacd bfa0edb6 bb5dc42f +c0bf31c4 3e8fa360 bb8b4399 +41b775bb 3f60e9b1 41a12e7d +3dacb52f 3f14cb10 3cd1394a +3ef99766 3ef867d7 3e1609c6 +be88b183 bb3f962b 39b172a9 +3e58520f bffccec2 be6c1a7b +3be31d2c bff11851 bbd6a1ca +bdaca5e5 3bb7da9c b96d89c1 +420fea41 be8a7da5 c11bb5d2 +c1c5c23d 3f0cebd8 af897c9a +c1837e8d 3d503909 b382780a +c0a6ada3 bfdd3ed4 3d489333 +c00fe179 c04c1b35 3f2f4d90 +beb4544c c02ed9ab 3ecb6561 +c1db10df beff8415 2d9a012a +411a165e bfab764a c14e64cf +b9db8626 3dd9aac9 b7ba9d2a +c11714cf bf922c23 3a6012e6 +411106cc 3c2ff79d 3dc759f0 +bf2a4fd1 c00d1a4f 3efeffec +c158d455 3f85da74 b79abed7 +407d791b bbf8a51f bcf19670 +c19cc7cf 3d8554ab b1872041 +420388b2 bf2c3f3b c1b100a9 +42017a00 3b3fd577 3dc20bf9 +410f3d5b bedb154c c07522af +39870eae bd8fb362 b717a4ac +bf12f580 bfaea2a5 3e907b61 +bf02885d bc3a66b8 3b0ea673 +418f9722 4036541b 424c893e +c119b130 4000a5da baaa6a26 +c18bdceb bfe165f1 35531876 +40ba7c4f be3d5dc2 bf898a62 +c157bc1e 403f12b5 b86b57c9 +bfd26be7 bfd3511d 3ee10379 +41a13bb8 bf7f68d3 c1a0dc81 +c216da04 bf516b17 26b9fb05 +c1e09f6a be8644c6 2ca5b79b +420e7f2a 3dff7f12 408e3766 +3faf9912 bf89f55b bf96f7f4 +b9b4b74b be422258 3809051a +c1dd8c1d 3f60c376 adc8ef4a +3e472301 3df8d78c 3c5454c8 +40d37bef 3b58bd33 3cb2cf26 +ba8fe1fd 39e0ce17 b47c8fa2 +be5a843c c0795b5d 3ebe38c5 +be0bc831 c01cfa1e 3e1fbe79 +c1e7a880 bfc4a586 2d4fc36d +c0a65054 bca68a57 3a185df5 +bfab2483 b7991f73 36aa558d +c1079261 3f5cf51b bac849fd +41230a93 3c3dd306 3df1c815 +421fc8fe be1f6bf0 c0c70269 +3ee8a6b9 3eaa89c9 3dbd9a47 +bc11e65d bea56b67 3abbb675 +415e3a51 402361c0 420dd3f3 +be9f3249 401bd2ed bea3e9a3 +bd1a6793 3e620d0b bb85c585 +3fb86434 3f3f7de9 3f5f0a48 +41e2223d 3f2435d2 41910d7a +c18496a2 beed3d42 3502ba7e +418fe140 bf518a76 c16b896e +3f0d1095 4052b29a 3f934dd8 +c1fd4716 40688e75 ac1013fd +c1278cd1 3c95f773 b6b62caa +bf8c533d 3f869b80 be93d371 +c20082fa 3f47e52f aa9d6097 +c147f320 bc1afee7 34ed4687 +c20fedf6 3f6560f4 a8091c68 +bfb08e11 b673e1e1 35874f13 +4115910f 3c8d877f 3e255c6e +bfa20fed 4072eb68 bf8747e6 +bfc6b180 be9b7896 3da8b311 +3f8d46d7 328eead6 326ce9fd +4203fdd1 3bf71644 3e7ecabf +41e07c91 bf343d39 c19e0d46 +407736fd 3c455aa4 3d3aa8dd +bff27000 bc9f90d8 3b9e1acf +4165944a bc5823da be41d53e +bcd37db4 bf3bb0f7 3c190ea5 +41ade4de c009a883 c23b03e4 +3e62e6e6 3d79adb8 3bf5b7a7 +4122e80c ba01756c bba4c1b4 +be431c97 c02f8af6 3e722a8a +39986c03 be07a97c b7a191c0 +41de496e bf3f0acd c1a5e22a +bf0e483f c03027e2 3f0ec14b +c10d1558 bffd6672 3b296397 +c13cd1a8 be7d6530 37b79ed5 +40aaa86f 40145cbc 4144db05 +3cb56a95 3f4fc7b3 3c14e011 +c0955ac0 bed22815 3c921bae +3d6b5c6a bf910f5e bd09321b +be0f33d8 bfad6084 3db46d98 +c1c63012 3eda6b31 af4a6811 +41729875 bcd818ba beccc80e +420b93d6 3aaa79cf 3d39e52c +4211715d be1ccc1f c0b22a19 +c118d17e be31d81e 38f7642d +c1da1a78 4011a65d aec5262b +41c63c74 c0477786 c29a758c +3f532d90 3a8701a5 3a1add50 +3f48beb1 3d88decd 3d1360bf +bec5ec3c bb31d5c3 39de7be1 +3f832f36 3ec71066 3e9623df +c1367f45 bf4ff5f2 38d839f0 +4181c22d c01cd626 c21efdbd +c1c30520 bff632ea 30a6c94a +c1108315 3ec88fd1 b9ddaeb9 +b984831a c07fac41 3a045379 +c085d6e1 3f608eab bd61e0f7 +38deff20 c0396256 b9217e39 +bee0bf4a 3eca3f28 bd8b333c +bc8700ff 405160fe bcdb041a +4062aba8 3e66c2b7 3f46924e +4122f6f8 c0313f12 c1e1a7a3 +c0cef77a babcf26e 37728379 +ba4571df bfb0ffa2 3a087649 +3fac273c bf29d277 bf353114 +c0783503 3fa5c625 bdd07cfe +41aa1750 bf3fddce c17ef587 +bddb0222 bc4be09a 3a2519af +bddf6b2c 3da2a747 bb863799 +bdc260af bfe5a0e0 3da61611 +c09da96e 3d426e90 badc9b33 +c1f962e7 bf0926c0 2b081472 +c039cf2d 3fc92500 be72e5d0 +3e11b6c5 3cbcfd04 3ae66c89 +40bb58af 3fafc9c4 41004724 +414fc008 3f488a60 4122be39 +c1dd39b0 bf6b204a 2dda835a +bfe04abb bcb22d74 3bb88851 +c18749af beb9d090 34951bee +be143745 c072e235 3e827673 +41fd9633 4037db89 42b61fd6 +402559fc 3fde3517 40857301 +c0fc1f0b 3f54cc1b bb227994 +c1052c1f 3e0dc1fe b992a404 +bd7b4e63 403df8c0 bdb4c4f7 +bd49a72a 3d88e92f bad26209 +bf2ca4e8 bfc18abd 3eb036a8 +bb4313f8 3e8dadf8 b9d79add +3f3547f0 c06ae379 bfdee143 +bfa6df54 3e875ee2 bd96bf20 +3e80cfeb be210fd7 bcb65db3 +3e05fe79 3e7bd949 3c8c6efe +42096cb8 bce8bb51 bf79de29 +c215c97b bf9e47e5 27362265 +c1b56ff7 3ea02ee1 b089dc1d +3f8fcdbd c061e3e3 c03f82a0 +be3245f9 3fd15e99 be052422 +40c7e949 3c6766a8 3db45a4a +4206dd7b 4042e582 42cd5980 +bf2c25c9 bef61da3 3ddfb912 +41062c54 be007c3d bf86a6b2 +3441c10e 3f1cd0f1 336d5f92 +c19d139a 381b4e49 ac17f700 +3f50f68d bc87a3b9 bc198d63 +bb478a3f be3a85d0 39912a16 +4210e34b c01188e6 c2a4bc71 +400e13f4 bc5859e8 bcd89e6a +40af858a 3c1cfb3b 3d565f98 +3dedde44 c02aba8a be27d6b1 +c21a9bf8 3d4f29d1 a41366c8 +bed3f4e4 bc9195f8 3b3fe0a4 +bf1a75d6 3f35e9a6 be1b3b70 +c0d586ca 3bcb4728 b85b5937 +c13a7821 be97a2cf 37fb5c03 +c20ec796 3fbb2f47 a893f6ab +c12f8a67 3a9ae263 b46f438c +c09e12ca be4d011b 3be64009 +3ebd5f08 405103db 3f36e306 +3ef2eea1 bfb5c560 bed4a9c9 +c0218c2c bcae9820 3b82c46c +41a9af82 4042162b 4280a5b2 +c1f6009e bde97a76 2a2e69cf +40eda265 bf674f62 c0d69681 +bce23e42 baf2fb05 37d3c5a3 +418dd6c7 beb58ae8 c0c92ba2 +3c4c4232 3ff83f97 3c474ef1 +3f85c980 3e9f757c 3e769ee0 +bc90ed00 3eb561bc bb4b8cc3 +c0856101 3f106e00 bd12d89c +c00ba5fc bd110267 3c004f03 +bffe6e57 3fe6c0af bedd1323 +bfe4cbee 3eacd433 bdb12de5 +c19c6495 bbfde4f3 3006b5a3 +419833ef 38271421 3a46abb1 +c20fa944 3e53dd47 a7072d30 +42163d79 37350b3c 39d4801d +3fef8214 c07fca8b c0cf62f5 +be525070 3f59f63d bda0bd7b +c1fe1f19 4037a9a2 abcd7971 +c0de51a5 373a80da b39f3e21 +3e36c3cb bfc8085f be1b84da +417fb234 bbbb774f bdbb3e55 +c1f84524 bfafcbec 2bc7a495 +bf0592bc be491ef4 3d1c5546 +bc4ae62b bf6bfb72 3bb9e01b +c1c66eed bfa71f95 3016606f +4195f7cd bf6ca707 c18aa24a +3ea049bd 3ce2a4be 3ba3f0c3 +4045eb3c bdb3e257 be8508aa +3cec71d8 3f8bc265 3c82f237 +be384d29 bc248a38 3a57a6a1 +c0ade15f c05a0e45 3da4d814 +c1f331d4 bfce310c 2c584b22 +404b83e7 bbd3dfe1 bca1b601 +c07719d2 3e5accc2 bc8b5071 +413a5b74 40080bef 41c6121a +4069717b bfdedf16 c0c612ae +be1244eb be83ecf0 3c8c019d +37640605 3c927bf0 34027a0e +41ce9a19 3ffa0bbd 4249cbf6 +419f72f4 3ef76984 411a19a2 +41e44819 c020c816 c28f5f7c +bfb948e4 be658222 3d7cfea9 +c141009a 3d3a1e78 b65447c7 +c14a0942 bf19d564 37d0dca9 +40983416 3f147924 402f0b0a +4128473d 3e901a70 403d7197 +4215ee3d 3e04bf69 409b7de3 +3c33defd becf5212 bb1277ab +ba81ed1f 402b446a baadc229 +3f892416 bf177137 bef1b845 +41572e0a 3e82828f 405b6629 +c1656f69 40389ade b7cd6b43 +4123a29d 3b08b341 3caec052 +403cf5e0 bf99d958 c057d9d1 +40e65294 bd1c90af be8cc187 +c1985ae5 be5e1ea9 32be2f1a +c1596c2e bff05838 38063d3c +c061b635 b8ca655d 372317ce +411de1be 4019ecca 41bdd961 +c21ea9e5 bef830b7 25038940 +c145c501 3b97a3a3 b4838fd8 +3b5f4446 bffb6a3f bb5ba437 +4179a729 c02d3c24 c228f09c +bf7671d4 bdff8882 3d07f54b +419a5499 bf29cf69 c14cbdc5 +bc6d0979 c014ba0d 3c88b6bc +4204144f be1560a6 c09a235e +41c677e7 bc75ab4a bebe758c +c1101267 bf48d3ee 3a6378e0 +c14a6195 3dad365c b6668c89 +41116564 bea029cd c035e8f3 +41b62456 be32afae c07e4485 +ba907f77 4031f128 bac8c428 +bda9b997 3ecf3312 bc83ae8f +c11a6709 3efb211a b99fd7e6 +c0882dc0 4055f335 be4bbffd +3fd5e1e9 3fc78f10 400c55b2 +c113594e 3d310364 b82715f7 +c0a22a38 c0494c6f 3dcc46a7 +408bfc33 3a1fbc89 3b2c8540 +3cbdb82b 403e5146 3d0ead00 +c129d2c6 bd9dcd88 37a88fb4 +4187eb03 bdfed44c c0074be4 +3fcb3212 bbbfec38 bbfcf4a8 +40613da7 3ef1f66b 3fcec421 +be46a980 3d22d96e bb644f1d +c0a6c644 3dea1426 bb53b2a5 +bb16d925 be9ce816 39b8b3ad +c1222ee7 401e1165 ba81f7eb +c0c684a8 3e175d35 baf28933 +bec45e33 bdd72906 3c85c640 +c09d9106 bef81834 3c8d13fb +c0baa647 bf2c42c2 3c3bdaae +c01d5fe7 39823245 b849c863 +c0457b8a becec68d 3d5f1242 +b927a6a3 c02c446e 39619cef +41dc1302 bd410e23 bfa5f67c +c09c259f 3f6223bc bd052bf2 +c0b7b5c6 bc8ed71f 39a8054f +c0dfa35b 3b30a38a b79197ea +bfb49c6e be566f1d 3d6d4dd2 +3e46ed8c 401b00f2 3e841c39 +be3d78e6 3d3c0c49 bb7cadda +c0e10f9b bf19cff3 3b74154d +c0660467 b393d0ee 31e36569 +bd9fd017 3f07fe3c bca32bcf +c1172514 c0025338 3ac71295 +c03507d0 3f76a03a be1bb341 +40d8b3ca 3f7fd2cc 40d84e19 +bf213af0 3faf2659 be995aff +3bb6e31f 402003b4 3be54486 +c19f9439 3f6798ca b3286296 +be0bc9b7 3df467f2 bbf8b956 +3ae34f83 be91feb4 b981bef9 +416f3f0c bf8fa537 c1863e9b +41ade0e4 3f6ca899 41a0bdd6 +41adaaf5 3d5f88d4 3f97a4be +4118edf3 40408694 41e6018f +3e87159e bfd252db be7b13b6 +40e39661 3d127405 3e8217c2 +c1973dac bdcda3fc 3248e7c9 +bed9ae4f bec5ec14 3d850ca9 +41056c80 4043b84b 41cbf6eb +c196303a 3f41e3cb b3d68e9f +41756ce4 c034899c c22d147a +3e05fcd8 3e181af5 3c299f5f +bbe11bb8 bd701a8e 395267b0 +41f7ed01 c045dd06 c2bf9f6f +c18bb0d6 bfce68ad 35454628 +4144123c bf19d428 c0eba27e +c0a0f973 3d041f9b ba8a1afc +bf94657f bd4fb761 3c660367 +4112a9b5 bebbd07b c0572d0d +b95465e8 3a7d3f94 b3d21803 +41b335e0 be343acf c07c5619 +be016ad3 b9f00b5c 37e362c4 +3d27ccf9 c0751970 bda3f22a +3d74e6bf be4ef021 bbcbe204 +c175b4bd bf45d278 362a88e3 +419673d7 bff1f811 c20e34d8 +c180b9dc 3dd33118 b4371ab3 +3ebd62a1 c0105ea0 befcaaa2 +c0e9d368 367e5f82 b29f7bfe +3e032b0f 3e6f4f8e 3c8275a6 +bf6f3e43 3ea2790b bdab4689 +bc94ac67 3e95a7b5 bb2c3fb0 +417f14a5 bddff3ad bfdf25c7 +41f4630e bdb1c76d c029b6de +3c68e553 3fe6ad25 3c535961 +3ffcc359 bf844af5 bfe56632 +c1a34a56 bf96c6c1 330d1262 +3aadbdde 3f7fd7c3 3a2dc004 +c1bf3fe0 bb0f20ab 2c18567a +38674b40 bf824d85 b7eb7629 +3f69eaa3 36bcb2ea 367622cd +420b16df 3cba373c 3f4a5941 +bfedca54 bfb6e3b3 3eb76d06 +419d4185 3c4402d0 3e70cfc8 +c21dc8c3 bd2d4dd5 236398f3 +3dd4f1e1 b8f707d9 b6d8283d +420067d4 bb54c15a bdd56dee +bbc9973d bf817a63 3b4b4a98 +bc822dfc 3dc22b18 ba43e7dc +c0a0aed2 bde604d3 3b722dfc +41f1f944 3ec3c703 41390cfa +3d06dfd2 bea04a29 bbabadba +41aa706d 3ded69e0 401e1092 +c08b1ee7 3f36a273 bd2246e1 +bf7bb346 3eb2f70e bdbf9fc7 +c2173ad2 3fdbc484 a73202e3 +c1afd62a bb7976e8 2dd185c9 +3da86fa5 bcd5a68e ba92597c +bd030e4f 40196df2 bd1a945b +3fba665f 3e40434e 3e630de6 +c157a166 c02871b0 3850ba4f +40d38556 3c5863b9 3db28d56 +421d4b12 bf2ff6f2 c1d83c18 +c20dbd73 405ceff3 a960d440 +bf39f6e3 3e92ef65 bd8b2d3d +40219c7b 3fa92ab4 4045c22f +c18cceb1 bc244a3f 3189a7bb +bea186c3 c044cb05 3ed17c9d +410d9636 3d6aaf4b 3f01c77b +3f484ea4 b8ccf1ab b85c1416 +421407b5 b9131572 bbaa19a7 +40d2b884 404f320c 41aa502f +c0044fd1 3ebed3b0 bdb13a56 +41c2319f 3d26edcc 3f7d4120 +414cf9a7 401f40a8 41ff0579 +c04c7a82 3ecbe916 bd4d1da7 +39603cbe 40095e82 3970ad2b +400c370c 401f19ae 409cc13c +41866037 4019887f 42212e4d +c1e90123 bba18070 29110ab7 +3d4dcdb9 3f6e42ac 3cc45a7a +4068409c bb0b8f33 bbf6adbc +c1f0a18e ba8c3dbb 27488bba +417e50e7 4040d561 423f90a5 +414fad0f 3f0ec506 40e7a384 +41788dff 3b9765d5 3d92fe9e +c069c2ed 3cc44a69 bb10f155 +c16683ae be56926b 35e03dc6 +409483a1 c07827dd c18e967d +3f937785 3e191882 3e060775 +bf2a8285 3d82005a bc6b1724 +3f3bbc57 3e87927f 3e065344 +ba703dc0 bf99597e 3a0fd802 +c1d366f2 3f50534a ae9de870 +c1c3de5b 3f6e8562 b011f4aa +4101a8fa bd8c45fd bf0e0cb7 +c0d8f680 be1c6556 3a9a092a +c011cc23 3e8016b1 bd58fd7c +40e45431 bd0982df be751995 +3c800109 4012e12f 3c940825 +4191c5be bf86bd9c c19972f3 +c12ae581 bf523134 395348bb +3fd7b9c9 c059597d c09a8337 +c1b856ce be01d1f8 2f9df6da +bcda3f6a 3f2a0da4 bc0f0b63 +c0afe67c 3d2ee559 ba7b351d +3ccb1126 bfe351ac bcb68d17 +c15d4249 3cbd2b3f b4a9321c +406ba57f bec07258 bfaccbd1 +418c35d3 bfd78df6 c1ec1de9 +c1fe2ace be1e2f0d 29affe1d +bd72cd70 3fa391fc bd168a7e +41c618c0 3ff9fd52 42417219 +bfc2a333 3bb55e0e bac5e00d +bd7aedf3 be26e8bf 3b9e97ee +bfef15d1 4010203d bf101194 +3f2f3144 bc848376 bbf11dc0 +41ff2510 3ec3f60a 41434e73 +c1ff7c69 3f1db117 aa958dbf +3b42ddc1 3b9bf092 36edc121 +c002e76f c0591843 3f4b682a +4152f0d3 c072f192 c2482e9c +3ce2a55b bf79b29f bc601fcb +41addd23 3bbdaad2 3e00d046 +406a8b3a 40464184 41311a8f +3b020adb 3f51ea12 3a5579b3 +c1a6e5b6 bf01c6bb 321e2113 +c03c0c4c 4016f020 beb2717c +c10f1e94 3ae8a3ff b60ae88b +4203dcfe 3e02e82c 4086dba0 +bf8aefad bf2147cb 3e30cb9d +3cdaae9d 4023f06d 3d0de90a +3da281ab c056554b be0d73b2 +c10739b7 c0360560 3ba82c76 +c203c9ce c071e141 2b2c2a1d +42126e54 bfdd759b c27d5907 +3ecf0b89 405acfd7 3f544535 +c037b6f7 3bc6cb91 ba74d3e1 +c01c4e7b 3da83cb6 bc837d60 +bbd251b3 be05ad2a 39daf0f7 +bc9178d6 3eebba80 bb84c370 +409c8eb3 bfebb45a c10f1279 +3e22e0fb c0731061 bea6ebf9 +c07578ad 3f7de884 bda4a805 +411c0b5c c0744fe0 c214e94c +c186c5fc bff2d1a7 35cf0129 +bb5c9110 be86aaf8 39e7aa81 +c19f7d01 3e985a96 b25ff096 +41493ad4 bdf95d50 bfc40365 +c1ecad73 3e2bee13 ab46319a +c19b9bb2 3e41dd57 b261c822 +41ea0f68 40750d08 42e00ca9 +c1f78db2 3d91f80c a9b4c798 +c1f08949 3f57f405 ac1c2fb9 +c0f74582 3f923bfc bb7ed562 +418a4b83 3ee7a7c4 40fa4989 +c16331d9 c063588d 381014be +4004177c 3e323b46 3ea33583 +c0c48428 bb8f6979 38722182 +3d82e80a 3fb51690 3d3f1dec +3ff130de bfe4759e c03ada97 +41e7a17b 3fd6a625 42423751 +412ff905 40631511 421c17a0 +bd5fdf47 c0153d51 3d7de381 +c1c7aeaf bfb613b7 300d0817 +c0f3bc3a 3c5405b3 b84b5d24 +c213af8e 404e1add a845b5d1 +be47cdaf bfb540a8 3dff69d8 +3c5946da bfcda75e bc2fb413 +41700625 404fd7ec 4242df65 +40fad294 bac5d74c bc41c36d +4113c821 bf239148 c0bcd3e1 +3f2503fa bf530c30 beb26d4f +c21e9cc6 c0705f04 2680fe48 +3c1251e4 bd444067 b9615777 +bdfc9bae bfb04f0d 3da341d4 +4216cfcb 3fba59d6 425b8fcc +41f0869e bdb8837a c02d5c49 +c13a3ea4 bdc72212 37272d7f +3ff90b0e 3ff0a6db 404cd765 +c07436f2 c0318180 3e697c7b +babbd86c bf8dece9 3a5021de +c190a60f bc450903 3151da28 +c0b69de5 b8ae9287 35d3320d +3f0ee7f2 bc069821 bb3f2761 +c0eb6d10 3e536cf5 ba7deaf1 +c111b588 3f83ed59 ba886e32 +bffdb51a bb8a9289 3a850aea +3b960ca4 bfb71092 bb571748 +3c1d39c7 3f8d4c58 3bae649b +c10f074b be9b9305 39bab9af +beabc9f8 3fa00c14 be331934 +c10711a0 400bc4c8 bb82412b +3f212765 3fef77f1 3f44b02f +c00a22a8 3d6f21d4 bc55c98a +bf170da7 3acad2b3 b9aab78f +40a8b4be bfba8503 c0f4948f +414e9d8b bedd7b56 c0b2c16f +41f93e98 bda1cd99 c01d888a +3bd58fb4 3d2eded5 39125b43 +bfd97e0a b9136f45 381ae4bd +40b43412 3da2d846 3ee470ce +c15d5f55 bbe3ad5a 33ca4d86 +41c4b825 c022c9ee c27a2f66 +c0071730 b99d46a9 388f7bcf +c00ec4bc 3cf03800 bbcff715 +c12410ce 3f305429 b9826325 +41b216a9 c06224a5 c29d517f +418e2c2d be8438ba c092dc90 +3d94f938 3f0aacde 3ca743f8 +400234a6 bed6ce99 bf413df3 +bece44dc 3e13933b bcbe8c28 +c1e601a3 b95b8edb 270d9175 +c1472d6c 3fb7f476 b8933230 +3fcd7d87 3c4f4c63 3c8a9238 +c13402ce bfbb17b6 3960228d +bfa34720 bf6ebdb4 3e84f61d +bdf841f6 bdaec90f 3b9f3d0e +c1d98239 bf1a16c9 2de00e33 +41c15131 3d7e75b9 3fc02774 +3f8f56fa c07c1274 c054d40b +41100f3e be2ca4c4 bfc247cf +bf89383b be9c4a10 3daae8c5 +c1fd9d49 b6be3a7a 22624b34 +410ad003 bf7719fb c105f6ee +415529e5 bf84d321 c15d32b6 +4199a42c c00412b5 c21e87c2 +3fc8e5b1 baa61166 bad7bd5a +41585575 bff01e4f c1cae9a9 +4152fa01 be80ec8d c0547fcc +3d577c27 405bb7c3 3dbdcf01 +418bbef6 bf4e6037 c161505f +bf0bcfb8 be58f374 3d2dd2af +41c43a5c c06be060 c2b4cd8f +41f327a1 3fe5d8cd 425a505f +bea291f0 3f76514a be03cb61 +41015fb9 3f775439 40f9e824 +3e4bbf13 ba9962eb b9062ed2 +bd1abd93 bcfc128b 3a157d1e +4168ba0e 3e0e0e22 40012409 +41c65510 be03e137 c04c5805 +3f7e55ad 401c49b8 3fe2a084 +41fc58a1 3e94f6ec 4112d6a3 +3fd8ef73 c03e0207 c0880875 +bc6feeca c01fd566 3c94b486 +40a84ab4 bdb2d928 bee9edff +415c8afd 40094c37 41ec9003 +c13d13db 3ff9cc3f b9325b04 +40216d17 3e7025b2 3f0c2d4f +bf06967f b804dea6 36cf9d06 +bd12f8c8 3f079f49 bc18ee24 +4100655b 3fdec4cd 415f627b +c1fd7ca9 bf1f2528 2ac042c2 +411346be c03d8558 c1da0a44 +4163884b bba92022 bd965182 +c1dcc4a2 ba3d7c1e 28ba11c1 +c21297d7 bff828de 281b4187 +c205025f 3fbf66d2 aa4aa807 +3c1883c8 bd4d76d6 b975f45a +41761bb0 3f4be3b1 414402d6 +3d00036c bf968b77 bc98e9bf +420194c5 bd1c14c3 bf9e0255 +401b885d 3e03d67d 3e933c83 +bfbf415e be3bb961 3d4da706 +c21ae5e5 405c375d a7120c49 +400beecf 4067c17f 40e3c74b +c0a20bc9 3f0c13c4 bc8e91fc +bfc6fce6 3f965bdc bea31587 +c1cc3b8f bfc037e2 2fac71ec +c21fbb6c 3f35cc10 a514851c +be05d6e4 403d4d4e be390559 +c1ec4ef2 40230b5d ad44851b +41970555 bd952c8f bfb000c7 +c10e1aaa 3ee788da ba124238 +bed6585f bf018927 3dac29ce +c21b5da0 bed8f91f 258067ad +c0c4db97 c02fc3a2 3d130f4e +4076be0c 3ff44e13 40e696ee +bbcbbca1 c037e756 3c11e778 +41f39f6d 3ef8a0bd 416c9b69 +c2001d31 3e3f7acd a9a5fdc5 +4140c5b9 be5f26c4 c028092d +c21da11e 3cacf895 a2ebe53b +4201a394 c07685b9 c2f9add0 +c1f27acd bda466ea 2a3c0627 +c127e00a 405b643d ba82d3fd +421522e5 bea7b8c1 c1436aca +41702092 bfdcf885 c1cf4515 +400a8885 bf2566f5 bfa09445 +40a7bc57 baa03a47 bbd0dce4 +416b0913 3db5ad39 3fa6cc70 +c1f56e8b 3413770a a06c0ef9 +bba13d0f bfaa93ab 3b5657c4 +bf6e7806 3a5b908e b967367b +41ad0df2 3fd07446 420ce9ee +c198c999 4027fab8 b488a57a +41a17890 bfde0845 c20c0bc4 +c00862c7 bf9fcd7b 3e908cf0 +bed37c1b bf16e6b2 3dc68ce3 +421b8c22 bffcbe34 c2999183 +bf92d8c7 bf690e1d 3e80de76 +bf46f69d c0199c12 3f1663a4 +3eb5ef94 3fb50677 3e9745cb +3f497d56 c0789b48 c006770e +c21535ff bd101ea4 24becb26 +41376801 4028eb10 41f208ab +c1410dfd 4029646e b9409fd0 +c0a72917 be0cefbe 3b7c770b +c0c3dc80 40036a65 bce1b31a +418c45ef bd0a53ae bf17971a +c1ecbbb5 3f9cde53 acb39e83 +c216d69e 3ed30217 a63bffb6 +c0ab0225 3fe8bd9a bd3d35e3 +c123a65f bea71818 38fcfad8 +bf5c46ff c06e8251 3f740280 +4178b961 c03731e0 c231fcf8 +40694368 3b74e2a0 3c59743c +41153ede bfdee30e c181edee +c0e9a4e1 bf579616 3b87d473 +3ba627c4 3c2341f2 37d475c9 +c08b3da9 bed64285 3cbdd61f +c09e8f00 3b13660c b8a393c4 +41194f7a 402b5909 41cd3731 +411a7338 bedfa0a2 c086e910 +c0837f4e 3f0fd492 bd18c3b4 +414d16b1 bffb4f41 c1c95499 +bea75b43 3ea2814d bd320d47 +40e10728 bb134521 bc8156a2 +bf749c23 ba519b19 395e88b0 +3e56ea6c bf5c71e3 bdcc6a9d +421fcf7d 3f2d1eaa 41d824b8 +c13b2fb3 bd0e2034 366222bc +c0ce904b 3f3b9bf8 bbf35e7c +41eded0a be90794a c106460f +3d418be4 be095962 bb5496c8 +3f8206d7 4023e96b 3ff47c61 +3f8b6cec bf42bd6f bf1eb823 +c0ebf92f 3fb4cf70 bbd5f71f +418ea7eb bdbaa102 bfcfff73 +c07b861a be10bd39 3c2f543e +401551f3 bf8792ac c0102bc6 +c0180111 bbfa852d 3aca8638 +420f2029 c0039e32 c2932bce +3f3720dc bee7acaf be5e993e +39bcd348 c054b3c8 ba1ceace +40e72aa4 3e9bc238 400c8bf8 +bf9c41e3 40364035 bf4abaf6 +c0fe1025 3f73f2ad bb30a590 +42074eb9 4001ece3 428957c0 +405dc508 3f467050 4026b15e +bf5ccb80 4051c0a6 bf56c9ed +3e5276a6 bf849c9c bdf0601a +418e316f bfcc8aca c1e338f7 +c0bbd280 bf6ed759 3c7cb173 +bd3d1cc7 3d594446 ba9ccb7c +c058ce3f 3e1f224d bc8cf621 +bc0c909e 406596a3 bc7b0b47 +41208aeb c01e0ad1 c1c636d1 +409cef3d 3ea11e94 3fc4162c +41c3d36e 4026f010 427f6578 +c18f37a3 3fb40266 b4e30309 +4207710a baf5dd3d bd82143b +4208d191 401323bc 429d46df +c12f33d1 3ece383e b8a25f5f +c0437ba6 3d1f6789 bbaf6283 +c1151fb0 3b6ea123 b64c0692 +41f430f7 c05c0472 c2d1de52 +bc10be6c be32abe2 3a4926b4 +3fb09615 bd8e76f2 bd9d0583 +bd99211f bfdea900 3d8035bb +40ae905a 3f995cd2 40d0433e +c1f7e5cb bd004402 291860a9 +41c720bf 3fe91f84 42355551 +41f95fa9 bece4a0a c148f319 +c12a45c3 3eaacd76 b8b1ddb1 +40685690 bc7f1fa6 bd61903a +bf07b927 bb0fa47a 39e1b586 +3e878fbd 3f833862 3e1d4350 +3fb7af15 3a20b242 3a3a4159 +c1b010dc 3d7964f4 afcbcfa5 +3fd8af49 bf3caa34 bf86dfdb +c1149896 3e17711c b9055964 +c1a2bec2 3e7c2160 b1fbb274 +c1315e90 3d13dbe5 b6cddd34 +3b94c1eb 380b55b3 33a24c47 +bfea7d69 bd67fcd3 3c6a9ac5 +c1b86bcf bde582a9 2f8a4523 +3ebde97d 3ea64b42 3d91fc14 +bf25db7e bf9a369e 3e89440a +bc06a200 bf9f414d 3ba6d1bb +c152c331 bb09a1c0 3361f995 +40348e06 3cb86186 3d757870 +c151f64c bb900399 33f7a384 +c1bbde89 be653449 2fb6d314 +4211f80b bd4bf606 bfe897f1 +3e42e5a4 3f900d28 3df025d5 +c100abbb bdb75313 3972be32 +bc2aef52 386a346f b49b90ef +c1b35e64 bf8e00ee 319c7936 +41d78bf1 3fd72141 42352287 +c21a293d bfb60b9e 26907766 +c1b8c4b3 3d7990ec af103cd1 +c131bec3 be612818 38196dc9 +c213ec79 bcb96f4b 24a7e0dc +c190c337 bc21e9f6 312a247b +408e248b bf0baaec c0194b7b +3ec72fca 4025b9cf 3f19b7b7 +c20de8c0 3ec1e296 a7bd5b63 +407f5f7e 3f531241 404ebb0e +c1019d42 3ea6b955 ba51a68c +b4c2b3ff bfae02f6 34845896 +bf92284f 3f059c1e be13ab37 +c1c2346b baaa0989 2b7e07fa +bfcdbdaa bcf4739d 3c03337c +bd89c9ab 3f3bcb6b bcc35b5b +be330efe 404dab2a be834f1d +bf80131b c05b0bb1 3f6badc1 +c0975414 39c5822c b782e127 +3fe8a1db 31a67b79 32022517 +4024832b bcbc1f49 bd609a6a +4179899f bfb95ea1 c1b4b0b0 +3f19b058 4055afe2 3fa5ad9f +3f553e2b bfbfd923 bf5ec3a3 +4111da9e 3e008d28 3f927758 +c04d5b6e 4053f1f6 bed34ee3 +3fb48d7d bf8ba03a bf9e521e +c07d045b bc222f94 3a41285b +bde15fae bf8d9de1 3d6ba4a0 +bf0fba9e bde565ce 3cbb1e41 +3dd11da5 bd743f43 bb51b148 +40a5388e bf19ebdf c0458c9a +bf52c330 bbba7f57 3abb5c6d +3fd04fa2 3986fbd2 39b79c03 +c1bc5ee3 3d4fdcbf ae9c2507 +41c99e75 bd29419f bf854d4a +419d354d be21365a c045ffcc +c1cc3cab 3d81b98a ad68a39d +bc9b6f48 c0438bb9 3ceb3484 +bfd055ff 3a7b686f b9865835 +407f4122 bf029f37 bfffbe78 +4198e89c c00aa1ed c2259c38 +c02ddf15 400ec3ec bec05aaa +c046a630 bde030d5 3c6f14fa +c116754a bfe1e72b 3ab34807 +41019e97 400c1abe 418dd588 +c0112378 3f63a898 be41c335 +bf516503 bed59603 3dd5f98e +bc1304ad bc9c44a5 38b2ae64 +c002c1ce bd902d21 3c873579 +3fd799f5 3efaa584 3f320db0 +3ac1c156 c06e58aa bb3486fb +c20c9254 404e0814 a98b3ca3 +bf7f0aa8 bc6935de 3b7aa00d +401b0569 be5565fd beed629b +3fca8dbb bf56caf0 bf8cfb54 +c18ae1b8 3eb80b5d b4417ddf +4092e320 3ff42a2b 410ab049 +c1dbb51d 3e5d73ef acf718ea +3c0ae549 3e002498 3a0ba3e2 +c10c139a 3fa3645b bae6f7f0 +3fa9835f 3d8f9a5a 3d96386a +4210db2d 3ef5989f 418af81e +3c927683 bf0ac1a2 bba030ac +3dce7ac2 3d4a316a 3b2b4b7f +bf347c6d bfe3433d 3ed3f229 +c1a3291a 3fed9d6e b361c756 +41dce54f bfe336ab c2440e81 +3f468e5c bea93bc1 be33c140 +3f935d75 3f123018 3effbcd1 +c166e259 3e977913 b61aee28 +c1a6b525 bced88cc 301404ec +bf8c180b 40010565 bf0da630 +c1cde56d 3d78aaf8 ad36adfe +bffd0e89 bfe21434 3ed97839 +3e1ca27c c0014486 be2a42c3 +c1e94bcf 404bd2de adb0b7ac +bdacbb04 400d77b7 bdb6dbd8 +3feec89b 3f1a2a04 3f790978 +41f75fb5 3f5a965a 41d338c9 +bf14a4c5 3c0e86b1 baed88b4 +ba9246fc 3db34d4e b84cca56 +c2156566 be6e934b 2616f687 +419d784f 3f356fb4 415f358b +3ff50737 4014844a 4077c51d +be1d7a05 3f54c0dd bd71a91b +ba064389 bb5608f2 35607392 +30ebae7f be869846 af77d30d +3d3128a9 3daad29f 3af18a39 +c1b65e9f c05d705d 322a7cb8 +411905d7 c060206a c205f614 +41e73b21 3c96c6b3 3f08301f +bf0ed704 4026de01 bf0791e0 +c1924852 bff684a0 34d878b2 +402f6715 baed5d4a bb98c6a6 +bf07feae 407e6fa6 bf482ace +421101be 3b167d31 3daa7bde +c0a39c83 3f382781 bcb44317 +bc14fc7a 3c45e9a1 b8655063 +c0916001 3f2bac7e bd036537 +409ed871 be9f2601 bfc4214a +41b7d635 4039fdd4 42859013 +c1fde522 b95c07b1 24fd0077 +c1728f09 3d042c50 b408eefd +3bd6a4e6 3f599eb9 3b370fd9 +3fc49685 3ed3a79e 3f05be2f +3fd93694 3f987a78 3fdaae97 +3f4e8a1b 3a8f330b 3a1fc3b0 +c1efe15c bf1a501a 2bf19fb4 +c1d5ec8b be7a3065 2d8c03fb +3fad2248 c026110c c03279c1 +c18e1a2c 3ed2f62e b417ba83 +4140f4a5 b4ce3b77 b69b7173 +c1da3301 3e8c2052 ad3b7efe +41f6f96a bf27e995 c1a1fe0d +c10f5821 bf1ab598 3a3675ff +41eecb76 c03387b7 c2a776dc +41de9573 3a51aaa9 3cb64c65 +bee2cb2f 3fbfa731 be84c962 +419b5740 bce30fa1 bf09c7da +4185fc06 3dd30d16 3fdceb25 +c18bfead bf406369 34b166db +417c75a2 bfb85427 c1b5c788 +c206510a bf61001a 29ad80d4 +3e5449ba bfdcbbe3 be49f316 +421c98a2 3dfb1934 40999912 +41e42be6 3ed86adb 4140e447 +42149d1d bd8743c8 c01d0c67 +40358ed0 bf552a91 c00ecf42 +3f811ed8 3e9c09dd 3e66af3a +c0295b8e bde3d15e 3c9fb0dc +c1220a7c 3fb6aec8 ba176a7d +c171c619 3ee7432d b5fad2fe +3fe720f0 3f174453 3f6a95c2 +bd34af31 bf937636 3ccb90ec +c21e5189 3ec4fb76 a4e31d7e +3f053686 3d68d46d 3c97fc70 +bf48ebd0 c001d2d8 3eff5caf +3e7d3b0f bee3de20 bd7d21cf +c21ede7d 3f634ece a5652bee +c20f81f7 3f492dbb a8053cfe +3f3cd97e 3f86b711 3f067515 +bf128e43 bf5c9b00 3e363280 +411d46e4 3b23ab29 3cc917d0 +417d429c b79ee3a2 b99d304d +c1f2b420 3eb0aa94 ab44a7aa +bfe068b4 4006c869 bf0b8dd9 +bec41251 be76490b 3d18f29e +c145935a b946adbe 322e4dec +c0529214 bd2c7b0c 3ba3076b +b96a08ed bd67c6aa 36d3dd9f +420164be 3f0fd6bd 419167a0 +3cf409f3 3e932e89 3b8e6508 +4026978b 3fc39437 406cff02 +3db44a4d bf2b5552 bcfbf0fa +bd440e89 40347d3c bd86eb68 +be6980f9 c00b66cf 3e616f01 +3a8a4af9 c04f4a8f bae0140b +c03ad32b 3fab3a68 be4ccbcb +c18344ec bfbb6b23 35f127e3 +bf0374f0 c0217e2b 3ef85d74 +3dca6fd5 3eda8a30 3cb5593a +41631b00 40644523 424a8158 +c0b54a87 3fb85c7b bce6c07a +3f87b1e8 ba70726d ba3d51a3 +4156264a 3fe6497a 41c0a3ca +c1ee891d 3f66ad18 ac5474bc +bee41676 bdbd0cfb 3c83873c +3e37633d 40680ba5 3eb512a3 +c129ad40 bd4864c0 3757d6d6 +bba40253 bec6984d 3a7dd3b7 +41a6259e bc7fcb5b bea60373 +bd1dd516 bf25eb91 3c48a62f +421bffe5 bec60b8d c1715dea +bf6b6e0a 400a17f8 bf10cacf +40d1d0e4 4059810b 41b20319 +c0bf21c4 3fbd9678 bcb81cd4 +c0d4af0f 3fcaef1c bc5fecff +bde4fbd4 bf724a08 3d4c9dec +3f2f3642 be5d2673 bdc939b9 +3d08c0dd 3f2eaff2 3c3dbfaa +c16c7616 be8683f9 35c6e0ec +beca2b3f 3b17884b b9c0b06a +3a3b0a7f bfdb798c ba20696e +c10e7918 bdb78e86 38e334e6 +3dbaacdc bfc8bfd1 bd990da8 +410bc702 3b95f3d6 3d23b931 +c081f8e5 3f581fc9 bd6dc618 +41262080 bc7d6ec9 be2474b5 +bc1e74bb 3e8d8de5 baae634f +c10f0b96 c0126e21 3b2f9636 +c1e98338 bfd1db00 2d314131 +3d4b2116 3e1e7e3f 3b80e0ba +3e103888 bf581390 bd824996 +c2122b96 3e729b7e a6a8386f +408b8b13 c0410521 c14fc619 +c0ad7eee c028db10 3d80e6a2 +41e46fa5 3d5fbece 3fc7a783 +3fdb0db6 40607c9b 40a2b37f +c1c21a2d 3ea84078 af7e7892 +4196aaa8 3f8f9d82 41a90c0e +41ba19e0 bf7c3624 c1b758d4 +c18b8420 be3ccd20 33b832a3 +bf3a345b 3fbf27e5 beb52e81 +bfb55df8 c03a240f 3f4de005 +bfb25300 bf91559f 3ea1176e +398f0ebf be4e434a b7e68efd +bcc40acc be497a27 3b18716f +c09b8ff3 406749c9 be0a2d2b +b9728572 3e1f6a17 b79700ea +40322d0a bd4dda56 be06ef8c +3ed21c1b 3f9457a8 3e926330 +c0124883 c012ef83 3ef80880 +41a5b74f 3db725ec 3fed1d2b +befa757a 40538700 bf1d5138 +be7db06f 3e473b3a bcad19d7 +bdfed971 3de292b5 bbd389fb +40c5659a be214a98 bf7837c5 +c1b0a7c8 400ae923 b2539e73 +c12a3329 3bdcb86c b5e6cbb9 +3d1d62ec 3dc3cb3a 3af55e80 +40be218c 3fc830fd 41144ad5 +3e168595 bfeca5a6 be1559d8 +3dffd1e6 3cedf391 3afc9da6 +c0be0705 c01391f9 3d137883 +3e75731e 3f813141 3e0aa490 +411243db 4003ed1e 4196bc44 +41fab00b bf2965f5 c1a5e20f +3f900d0f be4e352f be2f3507 +bbe2652c 3e94b49a ba830de8 +419cfcd3 bc7dbedc be9b9ae7 +3f786ef7 b8dc3cb6 b89aff39 +401d4591 3d4bfe0b 3de6ddd0 +c0541513 3a3786a7 b8aac772 +bc45c6cd bf2c134a 3b842310 +bf06b63b 3ed008b8 bda2a15a +3fe17d73 3c16ec7e 3c62e685 +c10cb18a 3a0fd424 b5447c89 +c1a428c2 bf3e8ca8 32a0c9a9 +c1307090 c0220449 39edd170 +c1500585 3ec1984a b73a2c66 +421754d4 3e2ec2c9 40ce9d9a +3872cb50 bf464a43 b7bc1113 +4107b11d c05a07cc c1e715a4 +40dcfa3e bd36add6 be9d878c +421117d7 3f417053 41db4545 +3e471fbb c00116bc be5c481b +c0c373f5 383733f7 b51f0136 +413f9a4f 3b9fa94f 3d6efebc +c00694be bd4e2c00 3c3cb787 +c209c226 bfaefe53 296a2785 +3f51e992 c0297eef bfc0f867 +41bf1f38 3f83df47 41c4e756 +3ef391ba c025f4fa bf42c37f +3b1235c9 bfac3102 bac4e86c +c0c33c3c bf6eb65e 3c505c5f +41a3b801 bcf8721e bf1ee33c +420ff0a0 3d95db6e 402884dc +41ec5c7e 3c1d9b22 3e9183f5 +3e57d7b3 c06dff5d beddbc05 +4123c008 bf9cbc2b c14880eb +c0522ac7 bf01c456 3d765599 +c04b9715 bdccbe3f 3c4fcf81 +bdb00a3a c0770a90 3e229530 +c15f6db5 3ed2c973 b6a63cf0 +4167a725 3fc5c88d 41b2f914 +41a0ddcc bd856066 bfa79f9d +beb16a1a bf39ed59 3dd57f37 +c01a2de2 3ccd76d5 bba34fd8 +3e60a34a bd856792 bc01d9a7 +c1b3743f b9d23276 2be54428 +3f85dfc6 3ded50c3 3db7ab3f +3f5f2a4f bd650c53 bd0cc9fc +40098394 40111e04 408b9e4a +4195c7be 3cba0bde 3ed9b423 +3ebd0786 bf9b0bd3 be8761f0 +be574d9c bb7ca5b8 39be3a33 +3ea17f6f be572bc8 bd1cf91c +c099f091 bf23044e 3ccab133 +c201948d c034d17e 2b5bc6ce +bfdde64b 39669863 b8700f8d +3e9d0802 3f28cd91 3dee996a +3fc278a1 3fbe74f1 3fed673b +410f0b76 bf10dc80 c0a1dde2 +41b38e3d 401a9c61 4258e27f +3f0c52d2 401c0e2f 3f58d3fd +bd936636 3fe1e966 bd7acadb +bd22cb30 beea3a03 3c11fcf9 +be076e78 3d439657 bb414723 +41b5491d 4014bd6e 4252a8d3 +bbad132e 3fa836eb bb62d9a8 +c12a5acf 4013dad6 ba19410e +41b13f9f ba4e504f bc8ed8cd +c1d69a08 bb351917 2a3ad348 +c194b1de be1b7818 32cd4af6 +3f5d7972 bd6efc96 bd118025 +4183bcdb 4043b5e4 42496ce8 +c2177765 400a8e09 a753e586 +3d3edb4a bf40a913 bc92fb0b +bc9e3131 bfc4902a 3c70950c +42129140 3fbc8a58 4257e3bf +c016c073 bf1a1382 3dfb859a +bf14dc76 3a36528d b9181198 +be79ce42 bd0aff70 3b6e5814 +41356d5e 3f020ce0 40b854c3 +c09549e0 3f78a843 bd2d26df +3f51ada2 3d348617 3ccd3d2c +bf9744d9 bf30abc7 3e440921 +c2148251 3ff50799 a7c06446 +3fc7afed 3fabc332 3fdd6e5d +c19f9e59 bfee1bba 33ac4eea +c18722a3 39619da4 af385327 +40d34266 3e1fea32 3f83c9b2 +c0c375d6 be6b322f 3b4c175d +3f9cfeae 3d442063 3d39ff8b +bde6e79c 3d537fb1 bb3405f0 +41b1d332 3dcc442e 400de3a8 +c1b82ae9 c02509bb 31ccfa0c +411fc9b6 4067327d 42104cd3 +bf13a324 bd5e86ab 3c38a3d6 +c1e7ed3b 3f2d7180 acb167f4 +bf65c42b be5b743c 3d6421fe +4025df76 3dab888f 3e4eccde +40c60657 be3ad8cf bf903c7e +420d5007 40731a07 43063155 +c1937b11 bb8e71fb 305921ea +bf9542b0 c03597f2 3f49383f +c152e4fc 3d98e102 b5f91a37 +3d5d50e9 bf931834 bd0299aa +c1de43cf bec92d28 2d24f39c +409b2010 405383c1 417e579d +41c49d17 40033d1f 424996a8 +41ec66e7 be873e0d c0f9c721 +c12a7991 bf935f71 3997b7fc +bff46e83 3dbd1ef2 bcba6302 +41c90bb6 401c28f6 4275469c +bdc1ddf5 b61fb340 33e6709c +c0e88045 40280541 bc5a57b9 +41812be3 be9c04cf c09d7256 +3ff22da4 bba883b6 bc0a87c6 +c0458573 3de65d9d bc786ced +c1e5fae3 be661ad0 2c14d760 +403f2655 3f87d16d 40411552 +4109e4b0 3f1d4b1b 40a96b92 +c013bbc7 be0f3cf6 3cef3664 +c194b118 bd9e58af 32512abd +3e4d2c46 b822a640 b68f5f53 +c1aaaa3c 391cb8c1 abf3db86 +405ded55 bd014ef4 bdd96a05 +41aae065 bf042bd8 c13071f0 +3f0780d7 c0009af1 bf2b5b5b +c013d68a 3dfc4ea4 bcd2844d +41dd167a bac0e1b7 bd2693ca +41ad6285 bffc47ab c22add85 +c1906bcf 4048398b b55b0e77 +3d856b26 bb570992 b8e77051 +c0d31d9a 3d91e2b8 ba27cdd3 +4163ab07 bcc957c1 beb30f4b +c1ae09ce 3e1afbc8 b0a14fd2 +4217121e be1e2352 c0baa40d +c173d971 be042c93 34fdfd42 +c10b3459 bf9c5bcf 3ae7f3d7 +42141c04 3709fd2b 399faaed +c1e812a1 c0563f31 2dd74fda +bfd73e93 400e9678 bf1677b8 +3f4a18c9 ba43fa36 b9d4cb8b +c1b4f7b5 bd0265de 2eed68b9 +bea51e37 40499416 beda7683 +c1b4f944 bf10415d 3103394b +40b574cb c01ced6a c15db352 +c15bfd3c bea163c9 369b5ffc +3fdcf84d bf28dd9f bf777b43 +c10448d4 b987aae9 35135b86 +c1f9ad26 b6a8bba9 22a1a459 +c1810ef1 bff58b9a 364cc0d2 +c085e611 407c34ab be7d56dd +4006ebfc c031a4b8 c0a6f827 +40c294d6 bedd4955 c027cffe +c21af5ef 3fe2c823 a6941fef +3aa7a357 bdca0988 b88462c9 +41aadce4 bef5e3d2 c1241d74 +3b68eab6 b3b13548 af21841a +41d35266 3b2f8798 3d90e542 +bb07aea5 bf9ca135 3aa5dbbc +c1947ca6 bf1667e1 33cb8ce9 +c1a17fc3 407dc073 b412df4b +40b6e160 bf1f54a7 c062e573 +3d9b5d9c 4055a569 3e0693ba +41efdf97 c00df8a2 c285071f +3ab247ef bee76d10 b9a146ec +c0937fc7 3f4ff3af bd1737e7 +35cdd125 bd586e04 b32e00f3 +bfd2668d 4038b443 bf44aeed +c2192357 4047a3f8 a74b3eab +c0fc640c 39b523d7 b5894a7b +c143b9ff bed6f86a 37d1b87d +bfe0ad8a bcb01a69 3bb63a9d +40a0bd0d 3f975ae4 40bcd2e2 +c054bc8b be82d529 3cf1d844 +c1b9e172 bcf29b52 2e757fb6 +c0830f99 3aa12642 b8ace52a +41d6f109 3fe53857 424074eb +3995bcf0 c021b537 b9bd328f +36f747e0 3f99ef1d 3694b111 +3cb0af30 c0077c14 bcbd0850 +4055385e 405edef0 413338e9 +3e97feed 39201c74 37da2478 +3f2734ae bd904a11 bcf7f094 +c06995b9 3e9d9efa bce93a58 +40cefbe8 bd231387 be83a5e0 +3f39fde9 35b3ee41 35303a97 +bfe5e922 be4b0db5 3d4f9fa3 +c20489eb 3e830c36 a91b858e +3f37047c 388653a4 3800f7cd +c21aa367 3e0ff6cc a4cb6c81 +b9a050c5 bde1e7c2 378d7297 +bcb206bb bdb93d35 3a7ed63b +404045d8 3d7b662c 3e33e612 +3d908aea 3cfd6990 3a9420f0 +3bf18b06 c042abe1 bc385ad5 +bf7e88a2 c005f3fe 3f0fe0a4 +c0c773f6 bd76991b 3a40cb11 +387d5757 401e652a 389cc13b +3fe46db7 bd8325b9 bdc86790 +c0b27d4e ba5cf929 37948fd8 +c1d7d16c bbcdd4c0 2ab76c65 +c11089c1 3ebd39c4 b9d0d994 +c0ae43bb 3f59237a bca28ef3 +4217fe9e 3e3b3529 40de4d1b +bbea8f4b 3d02cc05 b8eed3c8 +c0df1e46 baa04e99 3705fb5e +401ba94b bf702f82 c0064092 +bb179623 3cddfacc b8034a33 +c0008617 3ee79900 bddc2ac7 +40bc8461 3fa384a9 40f02a09 +3e9321bb 402746a2 3edbb77b +bf9cc5ed bd4d08b4 3c641d81 +c0c81ef3 bb24e157 37fd5746 +4001a514 be67f8ff becf9300 +41dc0f27 3a936857 3cfd6cc9 +c0d4fc9d bb8beeec 38192c49 +bf3da73a bf941ab8 3e8dae4f +c198992d 3ec789a9 b325fef7 +40b61487 c069df28 c1a5c7f9 +41a79d26 3f538613 418a7e4f +403b0ac7 bfa474ec c0640bfb +c1360861 bf11572c 389b2c01 +c21f4640 3db38b7e a3a3fd9b +3aa8c797 bf3e487d b9fb1135 +3fa5048b 3e978f4f 3e99305e +c2099ec8 beb9c2eb 28808510 +3ec9cdb8 bebe5c7d bdb341ca +4027aee0 bed1d86e bf801fbc +3887795c 33599d6a 2be65441 +4219fcc0 3ef86373 419568ac +41bcc15b bfa71d1c c1f66f32 +3f8d5c26 407f6ad0 4053dc90 +3a4123a8 bff41a87 ba383b5e +41b8e1b4 3fa468e4 41ed78af +40deca96 b249828e b3af3435 +4196eddd bfd7fad8 c1feab50 +421bdf5d 3ff4ed67 42952171 +c012c376 3fadf2e3 be924c4b +c1c1c5c9 3fedc990 b0bb10e1 +409db94a 406f9dfc 419291dc +bf8517e3 b6b4e921 35c48781 +40a5d026 3ea6195f 3fd5f70b +41fd70d5 3c37f4dc 3eb61e12 +41e437b4 39bbe049 3c277ca2 +400b7de7 3f492088 3fc4ea34 +c1199e6c bed8b89b 39902196 +41856c2a c03a043a c241e595 +411091b9 bf6386aa c1007959 +c1f077fd bfff84fc 2cba5144 +35ddce4e bee813f0 b4c91448 +3ffd56d3 3fd495e3 4038d5ee +3e7108c9 be66dc7c bcf2d47a +c1fce1b8 4066ea28 ac1615c0 +c20a5aa5 4038f173 a9d62638 +3f35a62c bd0141d5 bc75e99c +403e45d1 b9d1b15b ba944557 +c04f2f26 3d8b51d1 bc08577b +bf4d5271 bf4a9ba9 3e493b8f +3d063f84 bf9e2016 bca88fc0 +be2d48d4 baa7de74 38d01357 +3f6e4fdd bdf449a7 bda31c71 +c215bb75 4034912d a7d29138 +bf44522e be198966 3d155f50 +404eaae4 bdb8a1ea be8f606a +c1af19f4 3d99dc6b b00d1296 +c1a9f4c3 3f6f3495 b24a7fc4 +c0aee3ca 3fa1c2af bcee62d6 +4192d98b 3beac6bd 3e06acda +37d4ff63 c0037855 b7dac652 +3f010410 bd1fe6e3 bc48f1f7 +c1647297 3fed12c6 b78bb214 +4042321e 3d2b2724 3df7bf2f +c1ef1899 b91346df 25fd86bc +3da42ef1 be934de6 bc4483a3 +c1a5ddb2 bf230c83 32609c2a +bc86721c 407f6730 bd050817 +40c6b08d 3c57b945 3da7180a +3dca9aa4 403974e7 3e1a0753 +c1858714 bed1adca 34cef0c9 +3e183fd9 be08abee bc2ea06f +3806dd70 bfde7401 b7ea633f +40701d4a 3f33e67c 4024ddd9 +42135926 3f1dc799 41b5a11d +c15d4400 b9adc3be 319b5b87 +3e0aa78e 3e03e282 3c188523 +41bea7e5 be14c3e0 c05d95e2 +c11e86e4 bcbb127a 373cf276 +4063ed6d 3d53cdb0 3e375ea7 +c052b013 bf0a3a2b 3d827ea7 +413e8b56 beb2b043 c084ffda +3b6354b4 bf1f6df2 ba8dd21a +b68bd255 3f570e6c b5eaeaea +c075f4d5 3e33ed37 bc6817de +41878f89 37e421f4 39f19ba1 +3e5aecda c019aea7 be916bd2 +41df7291 bcda86fd bf3ebd62 +bda74bbf 3474e144 b2197f13 +c1906076 b437951c 2949e724 +c1592ceb 3fd8587b b7f5271a +402b4550 3cbb4412 3d6a6f6f +ba50fd5a 3fb7879a ba15c485 +c116bb43 bb283372 36037722 +c209ec01 3f0304d3 a8a87dcf +40214888 3f964739 402f411a +bb677054 3620d230 b1912282 +c193e7e8 3a7d1263 af376d04 +3f7ea2fe 3bd8e625 3b9d7ecb +41ed8a14 3ec571b5 413734c3 +c0fdd42c 3c91eab7 b854ad70 +bff3edca bfde012c 3edb17d5 +c094e929 3ed2e7cb bc943712 +4142aa79 be5f93e4 c02a02ba +c1e86af6 3f061eb1 ac8149e8 +3e82215b bfb1e056 be4bb1d0 +c21ea665 3e820c6e a48a4e7a +c140ce4e 3d7c2abc b6916f43 +be993685 404d9955 bed18c41 +be4f0c3d 40091e34 be47731f +bdbbc6f5 3d18c94a bad5dee3 +c1be3410 c0117cb2 312f8445 +bb5f9cdd c065fff5 3bc88f26 +c1a8c59d bc066de2 2f03097f +3fe940c0 40235d85 408022b4 +bed61923 3c663aa3 bb18dd50 +bf247dc7 be997d7f 3d87f8d0 +bbabdc0d 403c4f05 bbfc2b8f +41e91507 3f82cd45 41ee2f24 +3958e115 bfd584fe b934e8bc +bea50b4b c02ea7ed 3ebd376b +bc1604b9 bfed01b8 3c0a409a +41c7ef0b c030bbda c28a070d +402a7f2b 4053b2c0 4103cf0b +c10882d5 c0638fe0 3bc3dd73 +3e96c030 3e4742fb 3d067d69 +c1cbb18d c051d4b0 3048d62d +42047f45 bfa12a0b c226d39a +c18db5c1 bf2997f6 347f80f3 +37877de2 3f41944f 36cce939 +bf982ba7 bf871606 3e95f988 +c1a9dc7a bd66dbb8 3045a758 +40f63ec8 3ab33e3c 3c2c55b0 +3d04148e 3e2d18e0 3b357e9f +c0499957 3fdeb16f be6699e2 +bf9c235c 3e9d00dd bdaea35b +3ee5207c bee2614b bdf73613 +3df60408 c05cf113 be610fea +c1d9c7a7 bfbf5d70 2e86a8a2 +333da9eb 3ee5243d 3229c3d8 +ba8d8170 3e236903 b8b48df7 +c196e779 3dcf2415 b25299d0 +bf1f1401 3e5179e7 bd35f4c8 +c1964c3e bed8551c 336c4fc4 +40dedda6 bfbb3e2e c122daa7 +41ce02d4 3c33bd1f 3e90a42b +3de5df80 3fcd6ac5 3dc2cb1c +c122c214 3f03e55e b951fc21 +40556aef 3fbd8768 40989155 +3e179bc6 bd7a01e3 bb9f0002 +3e417cb2 3c3669be 3a96db2e +420b0fdf 3ef00676 41826264 +3efcd01d 4021f4aa 3f46a4b1 +3f0169b2 bb6e61b3 ba965547 +3d0bacb5 bef75b2c bc094265 +41818717 3f1a56bf 411c2e4f +c1799bc9 bf53fc67 3611773c +4012781b bd81086d be060e71 +3ebafa54 3cf6b30d 3bd4b998 +41c1cbd6 3ccd00ea 3f1b30ec +407b0189 3e57fec0 3f4fab53 +3900b0aa c05ffce5 b9613595 +3dd96e9f b945432e b7306de3 +3fd629e3 3f634d18 3fa01c0d +3f9d5e58 3d85fb93 3d7ee693 +3e00c579 3f65ac3e 3d7590de +bfc46948 402ac098 bf39dd03 +bcc1d242 bfa6154a 3c788354 +beb63406 bd11ce75 3bab0145 +c1e50e75 bfc6f576 2d8fdd09 +417315a7 3e669e7a 405afbec +c028e468 3a60523f b91de040 +41511cd8 bf11c58b c0ee2545 +401bc9f9 3c38b641 3cceb15f +bfe23a02 bd9884ff 3c9d47cd +c05ae6a6 be672d6e 3cc84eea +41cd43e8 bfd45492 c22a400b +bfc25fbd c0788112 3f879b4e +4010e3d8 3ec70c54 3f4c1936 +bc7a737a c05e6ec5 3cd7f2ba +421590d6 bf690bb0 c20827a7 +bd3749b1 403198f7 bd789e91 +bc45987a 3d943814 b9e36daa +c108c05a 40794a97 bbd3bde9 +3f49e03e bf57b2c5 bee9e3ab +3c2fccb5 c0157318 bc4e5c45 +bf6d781a bf22a107 3e2b0453 +40361201 3dfbd8d9 3ea9464b +c1ef4108 40229ec4 ad0952de +40aa817a 3ee965cd 401ab37b +c0e45bbb 3fef488e bc2dcb0e +3fc21199 3918c3e2 393deb5e +c12974e3 405a40a3 ba6e05bd +3e162213 3e8d6165 3cb1f63a +bb967e5a 3f6774ca bb07c0ae +421c8152 3f1c92cb 41bf7118 +41d00ac5 40468564 42a154bb +3fc4117d 3fe32864 400f0e80 +41a93800 3c19e82c 3e4b77e0 +3f7647a5 bee422da be9ecbad +41eab85e bcc3ddb5 bf3395b7 +c08fbe65 c07c90b2 3e490645 +c00b0ed6 bc07ea1b 3af17f93 +3f0118f3 3f986415 3ebfa683 +befb663e bf364df6 3e07f017 +c067404c 3e16669e bc6449cb +4026160a 3f512d6d 3ffc9103 +c00f440a beb87b36 3d9f2593 +c16c5a59 bfb09b7e 370361d8 +c0c218ef 3e39ba84 bb26fd52 +41b56797 40614473 429fa08d +bc241be1 3f586a9c bb8a09ff +40fb3566 400f856c 418cc7b5 +4098b2f3 39a656b1 3ac4c518 +41c71f1c 38057bd2 3a4fa6f2 +c111ff6f 404a3ac8 bb4dccf3 +c1da01a0 bd065f20 2bb8055a +39cf6fff bd46580c b720c01b +40d76a8a 400eec7f 41703edd +41823be0 3d789bbf 3f7cf277 +c1a62db2 3e3a7c67 b177851f +c0be0c5d bd31c983 3a31923f +40a17838 3bdfb44a 3d0c3276 +bfe8ae13 be094709 3d0b7133 +c20756e6 bbae8593 25d20293 +3e1a12aa 3f9cb921 3dcacfeb +bc918cf5 bc80b9a2 39111329 +bf5423f3 3de987fd bceb439e +be3f51ba c05ec193 3e96f7da +c0a1d45d 3de0f136 bb662e9b +42093de3 be8fe284 c11a4602 +420cd2d0 bfc247cf c255be84 +be29b47c 3f4057d4 bd69ede8 +413487aa 3b845b7e 3d3aac57 +bf87df4d c06f3d93 3f828b40 +40895790 3ace8ecd 3bdaa487 +4007efc1 bb7141bc bbe4db0e +c1e00947 bae10232 291506dc +3f0d2871 3fbf7724 3f05f6ee +bde70fc3 b4f370e2 32cf5811 +3dc9ee11 3ed75e6b 3cb23fad +417bdb99 b934156d bb312b7a +c085650a bf5dee94 3d618ff2 +3b100ae8 bd15df80 b828d7a8 +c00cc041 bf5e7e96 3e435f8e +41c834a3 c009e845 c257b3a2 +401c4975 3f747ff1 40095222 +c03c0211 3d3777dd bbd8fbe7 +3d971830 c05edbd6 be08624b +4216a823 bf8e7fb3 c227b8d4 +3e4acdd7 3c1be5ee 3a87b174 +3df9ff69 3fa0996e 3da664ee +bc9689e4 3cac7148 b948f17f +41fb0721 bf54eac7 c1d0c81f +bfb97fbb b789952f 3697a1be +3dfb5bf2 3d7e2e53 3b846f4a +bfdf1699 beafeca6 3db6ada9 +c1a24a12 bf22aa6b 32ab6ced +bf799323 be8e1f8f 3d97ce02 +c09d5cfe bffbb227 3d8fd871 +408f80b7 3f39661d 404d88d8 +40598abe bb2169f6 bc04bb45 +412c6e2d 3e76b63d 40262bbb +413b1100 be9cac0d c064f7ad +ba1c3008 3e6a6437 b88ef623 +bf45b76d 3b540d66 ba4efea1 +3eba4ad8 403f753a 3f246548 +c1d723fb 4022ba94 af1d557e +c1611de5 be712fdd 362c7577 +3f2eba93 bf230ad1 be93d9a1 +419e0591 bf69d4a5 c1905653 +bf52ef27 c068e0e1 3f6a09d0 +c182ee90 3e7b1fd3 b4a816d3 +3d0dbd00 c055b590 bd70bda3 +41cc7cf2 bf4b9827 c1a2a09d +c2148f71 3d164ed8 a4e91c75 +c1cdfa0f 4054a300 b01ab466 +bf4c5eff bf66919b 3e648728 +bf488cd8 bfbf731a 3ebc2120 +3d11d066 ba8dc277 b7a45cde +4211f9f7 3ca6d12b 3f3e3eb8 +41f782f4 3f3027ac 41aa5063 +c1949363 c033f070 34f0f97c +3f344290 3e277832 3d9dcdf8 +40d8552b 3f90a377 40f42ba8 +3e4168f2 3c76d70e 3acc0c94 +4169a2b4 c0470a9e c235a725 +c0d9e139 bb225d29 379c0eff +c1daf354 bf7df561 2e1b3544 +be173f38 bd8cb0e8 3b99fcea +c1d3ab26 4060d8a4 afa50e5b +c10548c4 3ffb68ab bb813ca6 +c0f2e8ff bba0115e 379d018a +bd427c93 3b61d6ae b8a78004 +c07118a1 38823056 b6b14f90 +40829d80 3e976894 3f97f003 +39d7680d 3e4a389c 382a30af +41d455f5 3e8c2cb7 40e88831 +c0c74cc5 4065b905 bd34522a +b78c1604 3ff8c562 b788210c +bf917c6f 404127b1 bf555852 +bcb49750 3c96b370 b952468c +bf5f4e51 3f231790 be27be9d +3fcca74a 3fd4b6f1 400d751c +bd1750a9 3c068f36 b91c21a6 +39b10412 bc0b4fef b5c0b14b +3d960a51 3fd6db91 3d8289ab +c16f1626 bee1834c 360f0d52 +3fee2afe 3a4118e8 3a9b7654 +c16d6216 3d744464 b4ab206f +3f06406c 407633ca 3fa2369b +c21b2af5 beacf894 2556d6ff +bcb90482 bd722ef3 3a2d0e37 +c1476259 3ebdd2aa b79618da +bfb32e72 bfcf8d8b 3ee5ec81 +3f246e15 bc005618 bb580f47 +41aa0406 bc1de4ff be51b919 +c0d46903 3f9896e7 bc29995a +404b8677 bf36d39b c00b8c55 +bedf5ffa bf28e844 3de776db +4219fe03 bda5acfc c047518c +bc71ddbe c03b4638 3cafa0fe +bef4dc23 b87e1672 3739fff9 +3eaf74f4 407630cf 3f455d9e +3fe08a65 3bb66000 3c085dc1 +42048490 3f90c0a8 4215dc97 +3f0d7264 c04e5ec4 bf90bf91 +3f9b59d8 3b19b944 3b0fd645 +c1b2d70c 3ba507fb adc1b2c9 +409ea611 bea31e62 bfc8c3e4 +3a183fec bfd72f06 ba00032a +c21df7da c04bee9f 26800a7a +40e5997f 3f1ee35a 408e64bd +bd8e874a 3d79e005 bb06478b +bf4a6969 becf4b6c 3dcc90cd +3f84b86f 3f87da02 3f4ffb3b +3d58df67 be028478 bb62fdb4 +41d1c4d1 bed29d72 c12c9477 +413b4e24 386d8f51 3a2dcfd6 +bf1bcf6a be1ea2fb 3d081682 +bdae9635 bf7731cc 3d21667f +c17df795 be1125a9 349a594e +3f26d2a7 be513bd6 bdb343d7 +c1ef4486 bb01bbd1 27dabeb2 +c1b65e58 3ac48454 ac9751b4 +c1bb79bd bc657740 2dbfdd2d +c195f3b1 3cf5f261 b18bf174 +c0e39f55 bef9f2c3 3b392915 +3fb815f2 bcc9128e bce9b436 +be6f5832 3f9d3079 be01dd7b +bf20fd00 c02d230b 3f177579 +c1a31f00 40716a81 b3e67808 +412fe834 3c54309c 3e11cd11 +bff6d39d 3c3f82da bb3b81de +420527fa be9d3317 c123882e +c023297d bf00ea24 3dbe8825 +c21f17f6 bc5fac76 22558034 +bf44ae21 3ffbc2f1 bef52561 +40a43606 3fdc373b 410c6d7f +c2177996 3e92ee5a a5e03d2a +c1c48241 3eb0418a af47c50c +411f9187 be144a3f bfb8da9f +4072e40c 3e18d4d0 3f0dd136 +be9a7d15 3c12b52b ba968e04 +c1040030 c0588543 3beedede +40517611 3b999441 3c72246f +413cb258 bf9e8fe0 c169bfcb +41b236a7 3e181c14 4053c7fe +c2110b99 4058d598 a8c5a55b +4152d0e1 c05f3289 c237cd7b +41beded1 bfc0663d c20f7357 +3f225922 bd2ce1f4 bc8f4827 +b75e2b40 40121940 b77d94ba +bf797966 be86b1bd 3d8fda4c +bf0ff41c bda30830 3c851e15 +c2138bd4 3fb22aa5 a7b0cf8b +41a9f3d3 bf927c01 c1c27ec2 +c0a06b07 c05598d4 3de25f4f +4152b33b 3f952152 41757b5e +c20c89ea c02e552c 296d8493 +40b42216 3e84c40f 3fba2be4 +bbb6223c be74a79a 3a2d9408 +42029a58 4008bb3b 428b8307 +413e4b09 3e46a083 4013a517 +3ca5a948 bef68ee0 bba12a1a +421db73b bb9119a1 be32c925 +3e020f8d bb651ab9 b9778e8c +c1db421c c058cd34 2eff5b64 +401f381a 3fe46d65 40832bc5 +be512c70 c052bc69 3e9aa9d0 +416a390d 3f6c0a3d 4157f5f0 +413f6b05 40180cb5 41e361b9 +3f001e77 406c5b5f 3f934902 +405028eb 3d89f40b 3e57fe09 +3eaa8370 3d8216d1 3c49e3b3 +bbca08c1 3d88826c b956cd1e +3f6a3891 406aa314 4019479f +4197ee21 402ebc3f 424f6725 +c0010bc4 bea8a209 3d9fce9d +c0ca33c9 3fc97dbd bc929349 +c09c1b21 3f169114 bcb1838c +bf0a1448 3f94a22c be6c3b14 +c20b0c4a 395b5234 a2d6948c +41d76e54 3e0db842 406e85a6 +c12271b6 3edd6f3a b93369c2 +c04ace13 bf34f8f7 3db92496 +c1f3217f 3e0a56b1 aa923d60 +c102b94c bd8b0c83 3924891b +414718ad 3f2cb71c 410652da +3ffefdfc bf1dda9e bf8a5c0c +bdf7d4d6 bbb85f7e 39a7b414 +40f0c991 4061faf5 41d46fdb +bdfebb66 bee98c35 3cd9f4ff +3debd29f 4048e217 3e43b13f +4125efe9 401252a7 41bdaf46 +416e59ac bde09e71 bfd121f6 +3ecdad8e c018d378 bf131eef +bbae1565 c06864dc 3c1d9c83 +41986753 bb1372b1 bd2f8f38 +40830dcf 3f99e217 409af97d +bf99d033 3723f128 b6362c1e +3d1aa10a 3f87dc0c 3ca738a7 +41656fb6 3e167c4e 4006ded7 +c0de6674 c0169d3f 3c805204 +4117ced1 ba1115b4 bbac0eb1 +41a1d59d 3e5978c1 40897a68 +c2071611 bf18a57e 29435374 +ba0698d4 3fc290dd b9cc8a84 +420ee29b c00594ad c2951d6c +c068cf6b 3ca08f43 baef9903 +41956d21 bddad558 bfff76eb +c1d53988 40218d4a af44b16c +c1818bad bce768c2 33363fc4 +bf956488 c0565f64 3f6d9093 +c0071904 c067aedb 3f535b0a +c17fec02 bcb56879 332c097e +42054916 bf94f1d4 c21b1852 +c05daac7 3eb8ea52 bd1b97ee +c1f0d9cf 3faecafe ac7367a9 +bf0e1d33 c06f7923 3f41eb20 +405ad0a2 befb4bd4 bfcffbdd +c1fe779c be00330e 29898b72 +40086f80 bf3019f6 bfa7cd44 +405c1063 c0182b71 c0fd7a56 +c082a6c8 be7b7aac 3c882f9e +c10cdd7d bce9011d 381da62e +bbe84428 bdf9265a 39e13ffe +405f3cb8 bf74759c c04eda2e +41acbb31 bdccde2a c00a3b12 +411667fc 3f0ab9c1 40a2feed +bd581398 3e139a26 bb7298a4 +bb881005 bea68c29 3a30abab +419c7c18 3b53b3a5 3d816817 +3e0e6886 bb91f2ab b9ada636 +417d4c40 c058be1f c2567472 +418ae8f7 3f2cbaf4 413b73ef +4133b09c 3f6ec8c2 41279a8a +c12891a7 3ea72c19 b8bfb4a2 +bc357361 bf146698 3b51349f +41ebb4cf 3d173f95 3f8b4231 +bd4588e5 bc16a693 3962e29d +3ee5b256 3fa6d71b 3eb6b995 +bc196c48 bc80597f 38991f28 +bd0980b3 3d36b28a ba40f78a +41bfab42 c02c70c6 c2811b80 +41d81628 bfdfc1a3 c23cdebf +c20a3d4d be9140aa 282cefd4 +bf68a54a 3bff6546 bb055705 +c112a69d 3df89d88 b8f3f96b +417f114d bb56a8f0 bd55e0c7 +41085542 3f719c8c 4100a512 +bfb321d5 bfd1958e 3ee82e94 +3ef17856 3eda603b 3dfdac5c +bfce4b64 be76d058 3d8458f8 +bf1a0685 bf1ed14a 3e074a8c +c0ad09c4 bee722a9 3c32808c +c2044fff 3dca21ea a87d6895 +41d7a46c c06d7fb9 c2c80ece +bfd189dd bff3b1a1 3f01f2e4 +41a43008 be45f723 c07deeee +c16fc270 c03248cc 37597ada +41906b21 c06fa6fa c2873236 +410da0f4 3bea5db8 3d81a438 +41c10be3 39556731 3ba0ecb5 +ada97355 bfa11336 2d553c80 +c1809127 beeef26b 355310eb +3dced2d3 b9d8714d b7b7afe3 +c1f960bb bf217e46 2b206569 +414098b7 bb916c5d bd5acfb7 +bf9e610f bf1a5425 3e2bc8d2 +3b1cb157 bd9d8e91 b8c11b12 +41ae9ede 3b79fba0 3daa8429 +3fa23c02 3cf66e30 3cf3b88f +c0c0ba72 3f6fd7e4 bc5f75e8 +3c65eaa4 bfd7fb0a bc4355f0 +41588740 3fec646b 41c7f18d +3fd4cd78 3586f7c2 35bc9d37 +3f89f6df bfc01402 bf9a767a +408a8d20 c02f9ad4 c13b9bf3 +bd1cc20a 3d9c9dd9 babc2252 +410717b7 c0148106 c19cb2f5 +414de259 c03aa6c9 c2161c7e +bb9fe82c ba81e004 3621da7f +bf9a816c c01695b6 3f276290 +bf61c86e 3f122b76 be16f8d7 +41889076 3fe9ccde 41f9718a +41f3bc71 be436f8f c0ba12c1 +bf40d680 400849ee bf0373ea +c1f3a3be 3e9d3a48 ab1c4af5 +bf3111e9 bf0aaf71 3e0006b7 +c1430716 3ea5cde0 b7a85faa +bfdcec6b 3e0d7260 bd138ecd +3faf14e5 3f0ae0b5 3f176768 +3c4415e2 bbf56fb1 b83d1e7c +40c114ad 3ef8cccf 403b33a7 +be16cc21 3d06e3cd bb133bfd +4104735d 40057858 418a136b +32355a40 3bddb804 2e1d1145 +c0530b02 3fc7363b be3b6123 +3d360706 be6a7c4d bbaa6f10 +41c7bea8 c0402e31 c295f308 +c1b41b63 bd1b9964 2f1cfbce +bd2dd8cb becd018c 3c084371 +bf00d22f 4036b0f2 bf0a8df3 +c215cb7f bfe16080 27816c41 +4186b7bb 405ee7e5 426a9ab9 +c123753f 3bae07fd b6052ca8 +c11696b5 3f6b0fec ba3931f4 +c1be93f3 3a3a7af6 ab571a88 +3fad7332 403f59f5 404e212f +400549f2 3f82abbb 3ff1fcf4 +416df400 bef7b054 c0e63a4c +411937c6 bf8624e4 c1208fb1 +b9195795 bd062377 3620af29 +c1bb6b8b 40225177 b1889f8a +3c9d2ba7 b9f11e6a b695744c +bec50818 4048df7e befa6f10 +be471e7d bfba2d62 3e02c674 +bed71e0e 3e172049 bcc9661d +bc26c223 401b69f2 bc497156 +40f98ca2 bc48023c bdc2e392 +bf1086c7 3ab8b54d b997336b +4027733a 3c0553ab 3ca28ae4 +4088653c bf35d77d c03f139a +410a7fee 4005c445 4190b6da +c182bebd c02d6833 366d48c8 +411dd606 bf55d35c c103d3a2 +bc65f5fd 3f7e0c73 bbe29b44 +bf98ca85 3e986074 bda93b0e +c15b3c1f 3efb7d7d b6fcef7c +40f94546 bf8b28e4 c1077213 +39b6d3b0 badb0372 b49c7089 +c08a488e 3fb8dc85 bda789dd +40829597 bb8c1719 bc8c8b53 +c1b12692 bf322e9d 317fdda2 +c1d3a753 3fbee5e1 af0c631f +419e8121 3f5c8284 418887c8 +410e3726 c07666fc c208dd60 +c1c479b9 3dd405fa ae714556 +c0244b14 3a096634 b8c92715 +415e63a6 3ebed265 40a5c4b0 +4108746d 3ef09acb 4080392b +c114a5f5 bf81a945 3a63ad60 +405cdb1d 4043947f 41238b14 +4085b1d7 40190af4 411d702a +c093d80e bf6ac421 3d294cd3 +3ea1c9b4 400db271 3ecf2a20 +4186c0ce 3e8f45ae 4096d4c1 +bb945807 bba9da5b 37446737 +c180bc96 4018a0b1 b68429f2 +c121ef53 3ce5c35c b73f946c +c0a2ee1d 3da3a0c3 bb22e9ea +41e57c9b 33e76ad5 364f7334 +4146dbc9 3b3964f3 3d100318 +387ccbe8 bf859da8 b803f2a3 +3fa9ff8f 3d99ea9a 3da1992a +42174836 3cac23b3 3f4b733a +3c2985c4 3fa34b97 3bd962df +bc01146e 3fc9bd8c bbcaa412 +c0ee01af bff0f153 3c06f197 +c200c045 be66dc41 29ab83d5 +41d619cd 3f8953bb 41e5b3ab +c0245bec 3e56f972 bd1d4631 +3d84df04 be83aa4d bc0d1ba5 +41acc2e8 c0032cf6 c2310c28 +412c866c bc1204b7 bdc4cea2 +bec061ad 401d3aa4 bec06e45 +41f65143 3f03160f 417c419d +3f93180f baeb6fde bacd7350 +c200aebf 3dc93bf8 a9180113 +3f8b5104 3d349856 3d130b4b +3ce0ab66 383f2f18 352a162e +bd9ca0f6 3b96ff44 b931b51b +42127554 3bd9f40e 3e796228 +417e9bc3 c04c9f63 c24b82a3 +be45183f 3f746074 bdaa184f +c1930984 3ace8788 afa5e1de +c1ce7946 39edae6b a9a2e73d +bd54b2d2 403c2198 bd984080 +3f0340d7 c078d512 bf9f95e2 +40cf22dd 3e896592 3fddffe6 +419df459 bfa13ba4 c1c6f6f1 +3d9838ea 400265e3 3da0d5a6 +3c6b0104 bcbf82ad b931107b +4092898a 3fa7e2d1 40be3f4f +bc673648 be860beb 3af06cfc +c1b3f017 bfd990b5 31dffafc +40f1b0c8 3cf149ea 3e63aea0 +c1ce794f bfc9c6ba 2f8a4ace +c16b2319 bf171f86 36715a08 +41770ae3 3b0d428c 3d085135 +c195d9c1 3d8b6d13 b2209475 +41097d24 3f1af784 40a66c87 +c20cb2e8 c0489fb7 298374a4 +c1283db4 bee98e5f 39086c3e +c1b3d2e5 400b2fbd b2114177 +c08d75fc 3e87c34f bc643945 +40d5992d 3e86b563 3fe08280 +3fd8fc72 3f00a3e3 3f384005 +c097f0ad 3f1a9a39 bcc9dca3 +412f5a2f be728ab0 c0262182 +c184a635 3e68e624 b47ed893 +3c31f046 bfc41de2 bc090e3a +b7382f5d 39f14bf9 b12d9b01 +c0aae198 bfc260ce 3d1e87ff +41d3da17 3aa779d8 3d0a981a +c21d27ca 3f002b46 a54430da +beb20a0e 3f01f8ac bd95a997 +41ac0d4a 3fa11f8f 41d89323 +bd191abb 3e4308a4 bb64ed08 +41b741a2 3afd0828 3d3521b4 +4032e84f c063da98 c11611dd +3b10105b 3fbf6265 3ad7a3c2 +be41cd21 3f875a71 bdb99979 +413de116 c06901d8 c22cd2eb +bf5471e7 bbd53f1e 3ad6f591 +3fe4052a 3f8a97dc 3fd34e85 +40d35f5c be12d13a bf721e6a +414dbe9a ba2211d1 bc0240d9 +bebf0a5d 3fa30e7c be467aca +408f5568 3ed1900c 3fe808fd +3f11dc4f bff3b72b bf316252 +b818c8fe bf86cece 37a0e883 +ba244178 40795eda ba9ff3b4 +c0db75cb 3d4ed339 b9be98b9 +c0d554b3 3f709099 bc027789 +3d513ceb 4068d993 3dc32d30 +3dc54c5d be995270 bc77b44f +ba3d684b c00ca3c4 3a500927 +c0660ee6 c0600900 3eac3f78 +41802341 bfd37284 c1d3acbf +40dacedb bb35e180 bc9b4a5b +40c708cd 3f96bc35 40e9ebd2 +3fcbc279 bd70ad24 bd9f2a6e +4116363f 3ed53180 407a2aff +41a18de8 bbd6f593 be07a79a +41875fdb 3fc1bae7 41cce434 +c1c63a53 3f64c1ff afd2f8b6 +41df8d19 401b92e5 4287dab5 +4145ce0b 3f1bed4e 40f0f5f5 +42098642 bd8ed360 c019740c +3d705715 40531406 3dcbfa80 +41ad16f0 3f9131ba 41c4573a +be50725b bc6f5d0a 3aaf21af +bfb40e32 407971e3 bf8a14a2 +bf0d03af bcb256af 3b8faff2 +c1a99957 3d5b1383 b0418483 +c0b8d56e 3d9eb777 bab5605f +c16efd0f bf0edff1 36364d35 +c08ab56f c0186f50 3e08c4ff +b81793fc bd2efff9 354f3b54 +c07bade3 c035f29a 3e5c0353 +415a5305 3f1240e4 40f9754d +c15b8bb1 bf0aa087 3708ef6e +4173921b 3e92c563 408ba51f +be4d4766 bb32e8c8 3981215d +bebab24b bfbab1d9 3e5f33cc +c215d1c6 c0142258 27a91ec5 +c0fc89ba 400ecc63 bbd79820 +3ce4e371 bc030cbf b8ed9d9b +bba6cd72 3f945925 bb40d3c1 +c1b59d16 bf8501b0 31602b86 +c16c4b67 bb206695 326f76f0 +408e4462 3df2d9c9 3f056532 +3dd24415 40152e12 3e00d049 +be81e033 3f13f931 bd833359 +c0461182 3ed3e904 bd634a41 +c0d6e98b c01d28f0 3ca375c9 +bf378367 bad7acac 39cae5a6 +bdbab287 3bc8edb3 b98bdc28 +413a7cb6 bf0406bc c0c059fe +3d403690 3f1d9ca1 3c723b87 +c1ac4884 bd4895b5 3000aeec +408632ca be269100 bf2c094a +418c628e c02caf3a c23d649d +3b95508d 3dd2e56e 39769348 +41cf25af bbbdea3a be19ac5a +3f803e46 b7228f6d b6ee4169 +3fdc4a5c c076333c c0b3b5d8 +42088016 bf846e24 c20d398b +3b894a4e bff80850 bb854bc7 +40198d6e 3f5c4916 3ff2443a +3ffe28fc c0616dcb c0c4ca59 +c17fb858 c00ed320 36890ed1 +c1d475d7 4052157a af8c35aa +bfb72eab bfd5cbb3 3eec1d3f +4216bbc1 3e2cbbbe 40cb6961 +3f8fa33d bfa81fc0 bf8e537a +bc28179b bfc59018 3c010e6e +c11874ee bfa08953 3a63e0de +3eac1c3f be48e8a6 bd1d9031 +c1d5fcfd 3d573c65 ac6f0dca +be0b5843 bf314cde 3d33e6f6 +3f228d7c 3f5f0c84 3eb9248e +40959f68 3f216df0 403af4ff +c0ab4f15 3c322ccc b98fc145 +40d7648e bd05cda4 be60e3d4 +c01145be bd716c8c 3c4d4749 +c1fbaeb0 bfc43bc3 2b937837 +40016c6a 3ee00d5c 3f481054 +c1f4f665 bd861318 29e327f2 +41d78aea bfa43dec c20a4921 +4183420d 4067f0a9 426dd7fb +c202569f ba755c21 25782e33 +411954a4 bf143c28 c0b18ecc +41bae3cb bea62458 c0f2947c +3c254ace c02828bc bc5a3f32 +c1011270 bb808526 37267af3 +40d62398 3fa44ed8 41094525 +4003401a 3e6c898d 3ed6e684 +c18bc4cc bef22066 34654b5d +bf22dbdc 3d3fc463 bc28e5d7 +c1470070 40655e44 b93965ce +406c32b1 be2e7720 bf1d0cf6 +baa8303f 4055827e bb0c2ed5 +4202a953 3daf83ab 403329e7 +4022e9df c03b4c86 c0dd0cb4 +c077edc7 bf3cf6b0 3d6e6661 +c06008e4 b5059919 335b37b9 +bbedd7be bddc4798 39cbe9c8 +c10c70e9 3fecd6b8 bb240d4d +c078a1cd bfd671d2 3e063468 +c1de6fb2 c033b5fe 2e9056a9 +c1b1bb1e 406df48d b29f6a9d +c120122c bbb06059 3623550b +bd45b31e beaeae90 3c03a548 +c1cbf0a1 3dd9725b adca0ec3 +c137cdfe bede8f5c 3856c68b +c1c1ed7f 3a523832 ab225520 +39881c64 3f2f1f9a 38ba3e9c +3f1da970 bf1b0fb8 be78044a +c0e2ca03 3dbf2c56 ba10d237 +3d390c9f 3f78ea35 3cb7fdd5 +c15040d7 bba2541a 341a0855 +3ffa1919 bf196478 bf834125 +c0c92fc1 3f8a04de bc4e3a46 +41055ada bedc1510 c0653c01 +c20045cc 400a20cb ab667513 +3d4f03ae 4051486c 3dad8329 +c0555e1a bf4b2973 3dba8bab +3effc5ea 3e2bf337 3d55d69c +41a98333 3f22020a 41568cc0 +bf87deec bc48a375 3b5af5d3 +bf785036 be8eed12 3d986f43 +3ac3ae4e bfc8db4b ba99a523 +403cedc7 bd392093 be01d79f +40ff2399 3bd9fd19 3d592e42 +be8a25f4 bed217b8 3d4457c7 +c0a959fe 3d196296 ba8204af +409833fc 3c0f5252 3d28f817 +3d23c870 bbd0bdbf b90837b0 +420a43e3 babdeb33 bd4d264d +3c4f1b40 3fa1014e 3c0313f2 +c21687d6 3fda2633 a75179f3 +bed778da 402254ee bed89923 +c0ecc8c8 c031ac6a 3c4db327 +bfe3e8cf 3ec89eed bdce17b8 +beb5fee2 3a0fea4d b8a8a280 +bf323dfb bfebbd55 3eda64d3 +c1edef63 3f480305 ac4612c9 +4197c754 40332a3b 425472d3 +c123acc4 bf42ea9e 399357ff +bcc17c99 35d0b747 b29be2df +c09aa459 be0d04a3 3bac5898 +41125245 bf8013ea c1126509 +4108eb1a c003837e c18ca659 +c1156095 c04ab71d 3b2ae2a7 +4195cbea 3df3c688 400ea4ba +40c6c65c 3fb35e58 410afe94 +401b7627 bc3717cc bccc5dba +c1e2a201 bf0a4f74 2d05f741 +41beb4e0 378af8f9 39cf0df3 +4017535d 38ed7669 39804e99 +c1e2c934 3f910711 ad89e6ef +41e3664d be914f19 c1011334 +be1e2e6f 3b4a410c b966ad68 +c0de2d38 bccb46cd 392e39b2 +40ec72ef be0fc9c6 bf84b991 +bf188de8 3fd409b1 beb3913a +42018817 3d9466b0 40162d45 +bf94d192 38b74866 b7cb0618 +c03424f7 c0601cad 3f0ea569 +bd172c77 3ee0404b bc01fb58 +bb891bc8 bf85b2c0 3b0ee9a3 +bd02212e beca4eff 3bca685c +c1782358 3c831b4e b344171c +412b6b8f bf4c0417 c1089bac +4206d76f 3a89b653 3d1112a7 +3d8e29a7 3fb2d6af 3d4d847b +41d6d743 3fadc2d4 4211d2f9 +bf10361d be976bba 3d778ec4 +b15d9d01 3f1e74b9 b0892bf2 +3fbdb6aa bfa15589 bfc2db6d +bfb65341 bdc9ee13 3cdf2b1c +40b0c06f bfb9fd7e c0ffcec1 +bc963a4f bf4cabe4 3bee02d4 +3e5db9bb 3f72839b 3de8b278 +bec73e5e be35bb97 3ce486ac +4212ddaa be6fd959 c10999a3 +42009c85 403da3eb 42be8bd0 +3f8235c7 3e8eb89d 3e554286 +bf4cbae3 3c711e00 bb6f2bdb +be3a331a bf47c9a0 3d84237c +4187df32 c07d7189 c28683d7 +c12d99b0 3f0cf8dd b8f3219f +c052268a c05bb0fd 3ed08dc4 +c1d7ebea 404d2b00 af3491b9 +c0b3c69d 3d6e4283 ba9b0114 +40067ac8 37b034d5 3824f3b5 +4095e464 bdf15877 bf0c0493 +c1fc2dad c007d711 2bc0455d +41e41563 3eaae7f4 411844dc +c1ce80be c0289320 2fe644c3 +3ecf395e 3f3fa2a3 3e3a17d0 +c21889f0 bfe30a04 2705b889 +3d33393e beeeb057 bc2ac26e +be3f773e bb5ef5d2 399735dd +41069450 402e5235 41b73d9e +4218a770 4035df08 42d8e6c2 +bdbacfa0 beae5faf 3c72e494 +40d59003 bf2dd74b c090d713 +42086765 404bcdf0 42d92f70 +3d9d4fb5 38c507ae 367b71bd +421436f7 402ad8c1 42c5d3fc +41277068 393cda15 3af70892 +3f3236fb bf5d9b11 becde697 +4068662d 3f61e33a 4047c5ad +40bc33ee 3ecf3232 4017e65c +bff26fec bd03c0a8 3c028bd8 +41b85bdd 3ffa7155 42345b54 +3f33ef66 3cd1807d 3c44f901 +bcc7b0c0 4036885e bd0ca5cb +414309fe bf607a84 c12b05dc +bf17f64a 38b1b914 b7962588 +396eb478 bf35c96e b8a9865c +c182e8c3 3e63ba0e b498d581 +bd7290b0 40280766 bd9a7f78 +3fa2f56d bcd51231 bcd3ee8e +4022a7a7 407c1312 41147809 +3fccac13 beecda01 bf1d86ec +c209bff2 c0131a80 29c53f46 +c1a780ee 3d487aec b06345de +4126105a 3e80c1a2 40270a3c +41f5e63d 40032fca 427c0571 +4001d42f beaeb125 bf1c97ad +410c50f1 3c53ab3d 3de7ffeb +b348d82d 3fee6ece b33b0fe8 +3d9606d1 c01b543c bdbcb953 +c17735c7 3f6d4181 b63b5175 +c0764032 be8ed1eb 3cb79eb0 +41889f9a 3eafa8aa 40bb7e3b +41bfb053 bee3cd20 c12a92f2 +41fa82fe 3e914cbd 410e2f4a +3a25eb5f 3cefc7ba 371b74c7 +41fa3e95 bf66f9d6 c1e1c872 +40ba0cdc 3917c64a 3a5bf34b +412356ba be8ea213 c0360151 +39b7dc21 be8fd721 b84ea637 +3cc9d047 3fe6e797 3cb845aa +c127429e 3eb2c2ef b8dcbd90 +c1836958 3f979fb9 b5bfdde7 +3a790ad4 bec9a361 b944404b +be2eb451 bd2ba4fe 3b565661 +41612758 bc0e9ed2 bdfadef7 +3f04047f c0216cd3 bf507e91 +3f81b646 bf990e85 bf6397de +3c0162db 3fb429f5 3bb6d583 +c0551790 402b56ea be9dc6f8 +41a30ad4 3e0459bf 4028957b +c2058f1f 3d32eeb1 a7a5ce62 +3e6b2fda bebeb5b6 bd433caa +4007a98e 3e986911 3f1037ec +beb1c2ff 3fb18e86 be4c3409 +c06bd900 ba0333a1 383d5fb7 +4066172d 3e8bc08e 3f7480be +410a26fc 3ca6888b 3e33b5c0 +bd535847 bf896e3d 3cdd1029 +c0e65d63 3e0896d5 ba3bffbd +41197dac 3ef78fb7 40946bd4 +c21268c8 bf82a748 27aaf470 +bf47c366 bef7b12e 3df2f40d +c16186e1 403c9b9a b803b074 +beeb94ed bebee197 3d87f17c +41ee3b85 c02cc1e8 c2a0c470 +41441fd1 3aa26a85 3c78db2d +c0a4a8bd 4068aa1a bddddd6c +be192ff9 bf24d248 3d36870b +c219f7ee c049a35e 2727b2d9 +3d047613 bdf47407 bb00881d +c188fceb bbb2bb24 316ad887 +c1348606 3e6ad374 b8089cdd +3c0b5867 befd8818 bb0a96ad +4133821e bfb4db46 c17da19e +c0c5779a 3c9842c9 b97ac468 +408a3d52 bf8d39cc c0968578 +41ff4c39 c04fbe1c c2cf2c39 +b5716538 bfa0cd64 3517a0ea +c1b65e8e 403dfe7a b2124839 +c04d1d58 4028516c bea839bd +c21c9f51 c07be21f 26db8485 +c00b1248 be43362b 3d2d69fa +bee62ea6 bbf0a6d3 3aa88b80 +c1853dce 3b207844 b123ca8b +41eccb72 bb18f46f bd8d7ae4 +be9fed51 3f4899aa bdd3cea0 +42164dc6 3c83c249 3f1ab7bc +bfcc489f 3e241d1c bd309518 +c0d6ac87 bf7344df 3bfea0b0 +c0e914b8 bfb2ddf6 3be4d5f3 +40366c0a bd04fc7b bdb32b03 +40d21181 3f3aa22a 4098ee9d +410e1fb0 3b69b5f2 3d01bb3e +3f299389 3ffb8087 3f5bd76d +bb897347 c0236ade 3baf1d57 +c2149fa4 bbc11b19 2393749e +3d30e57c bed32e23 bc151395 +be832a70 be733775 3cd97b20 +c1a9c282 c0479a62 332cf8a8 +c00fcecc c039d7d8 3f1fb364 +4119f16b bbc5ef84 bd6e0994 +3f1ab51b c0309eeb bf8a0a96 +c0dd1004 be6a4913 3aceddf7 +3f18a836 bfade91e bf05bde3 +c15994bb 40691e86 b88103d0 +c14aa084 bff60e7f 38a173c0 +c1e795c0 3ff24489 ad811e37 +c1e2949f b98bb989 2788310f +3b2470ec 347b38a4 2fa192ed +40e01ec1 3d54e047 3eba3283 +3a4640b0 bd36ea0d b78db4f5 +40f5c6d1 4008df8e 418358b9 +3f400012 be1f5bdd bda25999 +40bf961a 3f82f0ee 40c37f64 +411a2ec1 402b5549 41ce5dbd +c060e6a9 3cf56c4a bb477e6a +c0f68cd4 3f3f3b1d bb29ec5b +3d02217b bfcdbc09 bcd47b48 +bed3968e bd3d3ca9 3bf91526 +40adea39 bfb2a2da c0f1a923 +4209f70b c0771a8b c3052baa +4040593e 3db4752c 3e81311e +c0d42f0b 3a98c4c9 b72ad1f4 +41e8298c c038a877 c2a776a4 +40beb9e5 3d232d58 3e728425 +41702c1d 3c9fdb38 3e95f90d +4101201a 4012d4d9 4194137c +c1ec84bd 3da61572 aac32acc +c1a409f8 3754d939 aab630de +bbc9cae7 bfecd771 3bba1db7 +c0cd1a13 3f2cac33 bbe8c950 +c1236203 bc1cdd85 3671189f +bcfe590f bde24141 3add4e26 +389f281a b93ad051 b1e84b8c +3f84638c bf5069c5 bf1f072c +3d1e0a38 bfc6ca62 bcfa2db9 +bff04702 3f880229 be8788a5 +3eff5f66 bf670c58 be8f6639 +be6e605d 3cb83edb bb17aeb8 +3f2ce8c1 3dca0d9e 3d34e282 +bfe8d925 bc409d80 3b43929d +3ee98bf7 3fc10686 3ed79378 +40a4db59 3e461be6 3f7daf45 +c18583e6 402223ae b6204173 +403a090f be833e19 bf34dd28 +c115bbf9 3feed416 bac55b52 +bf610769 be2afc64 3d30616d +3faf8eb8 be2469fe be33ddbc +3ee5417e 3f17349c 3e253a75 +420562d8 3e076c5f 408d1f2e +3a761d52 3d90b800 380b321c +c0364818 3f7e6241 be1ebfb7 +c08bf6c3 3cea97e3 bacc5251 +40f9836d be6c3ac5 bfe6263c +3f46c0b4 bfd8de8c bf66a2e9 +4082956f bb9c4f0c bc9cd086 +bf501172 3d57d145 bc579d26 +41100139 bf4ef267 c0e8cb54 +419321a3 3fbb830b 41d789c5 +c06e209e be28aca3 3c6d6a75 +3f33c50a 40300590 3fa54ea4 +bdc434a5 bf96b501 3d5bf471 +c1b084ff 3e7e260a b0c4c07a +bfa46d7c bfabd6af 3ebf66ab +c08a4e7d 3f0cd1f4 bcff1bdd +c09546c4 bd38b925 3b00ab61 +bff6c1b4 bd15b516 3c129b1c +4139db4f 404fae15 4216c65e +3f178d5b c005f9d9 bf4c41b7 +c17f5081 3f25521d b5a275f8 +be44721c bf9bfb51 3dd87f72 +c1508d0b 4003461d b874e332 +3eb08c27 3c6ece6e 3b40ce64 +c078eff4 bec5494e 3cf61565 +c0c439b2 3dc79985 baa9c80e +421d2a72 3f6e945c 4212788b +3c342607 3f8cda4d 3bc753d4 +406ab715 bf7dbd86 c062d962 +3eb41453 bfc09caf be9f1317 +bff4a9cd 3d3b92ad bc38beb5 +c2004663 33b64563 9f17f7f5 +41bc98c6 bf804dca c1bd0b64 +3a5aabb5 3f72d72c 39cf8443 +3b25b5d4 c0785bd0 bba0f79c +bc5e1e40 3fbba2d8 bc21b2e1 +bd82cbce bf584219 3cd5ed99 +405dcf4d 3e86078e 3f61386c +3f17c7fe 40302eb3 3f868c35 +be5b8cbc 400ede87 be5ae243 +c19ddc73 bf549ecd 333d8dcb +c0df56de 3f00897f bb559783 +41139428 be91e0e6 c0282ce1 +41e1be60 c0760956 c2d8f52c +4214803d bf08c647 c19eae4a +bfe4efb6 bd2d7723 3c31c627 +3f008489 bcb48720 bbe1d2df +3787e8e3 3e4e48ea 35db08ad +3ea9259c be60d101 bd2cdbe3 +b7b43db8 bce107cb 349e6f4c +41326be7 3e18a850 3fd4c9f8 +40d1c8b9 bf20ec7f c083af52 +3936b595 3d309d6d 367c2004 +c1dea86c bd4f32c1 2ba207d5 +c1db95f3 b126abbf 1fbcb7ed +41942690 3f19ee36 413229ce +bfd3f36b b990cc50 3899c14f +c0ef89f5 c043f9a0 3c529b60 +3f7127ca 3ec48880 3e853508 +be45cc96 c032fa65 3e79f250 +c1c99d08 39a572f2 a9cb48e7 +3e865d0e 3e8e4a70 3d28da10 +bfa9cbf2 407bc524 bf8c1815 +3f56c2f7 4058ff1a 3ffe371d +c06b1fc2 3f69c9fa bdaa121d +415a4d42 3f40d693 412470df +3d523ee6 bfff3440 bd56f851 +40369c3b c0342e9f c0f30b00 +4180d82b becde6da c0cf4293 +3fd20322 4008ac00 403bd4c5 +40d39e27 3b93ed78 3cf43c46 +c0a460f7 4042c856 bdbb0c1c +3e58c9da 3c3f85a2 3ab34a72 +40af78d6 c03a5dca c17e6d8c +41d899e7 3ed2c578 41325553 +c0d62efa b1a0ddb5 2e2a9572 +3ffba73d 3c8f17e7 3cf6c6bc +c07eb30a 3f782caf bd90fa37 +40815556 bf02bdd9 c001d2a0 +3e1ac5be c051b809 be885b07 +3e37870a 400c814e 3e5b7663 +bdd03667 c02eb857 3e06e33e +41a5d5e6 3f8a432c 41b321a3 +c1d57026 bce1a1aa 2c05dff6 +c0188891 403ca227 bf17df05 +3a1233d0 3a17d083 342d73aa +bff44fef bf9d900c 3e9b55c9 +402ab317 4001af46 40a1b727 +404f854e be979abc bf6c8c70 +bfb23953 b7ecc412 370339fb +c127b718 bee0360e 3906eaaa +41dc1539 be851164 c0e4cbf4 +3f5edbf4 bfaad525 bf51a63b +41f11997 bec88bd5 c13cdfaf +c1fb9281 bdc65aba 2997101a +c1f01117 bffb5cf7 2cc068a9 +3d8293f0 bd9092d0 bb182f6f +4026c0a0 3ccf1a18 3d7b3e93 +bc7f86d5 c047db83 3cc5eeaf +40ce3294 3f82ba03 40d24168 +407353c5 3fbb00e5 40addd50 +c0b800dc c053fa44 3d7778f6 +c2064177 3b8cb4de a5dc3af2 +b837adf0 3eec2119 b7296b25 +3f2dba3a bf89f400 bef86fd2 +3fc239ec 3e9ff871 3ec71526 +3cc784cc bfc1c25a bc98d957 +c01a671f 3e37bb97 bd11c852 +c09418a2 4057a091 be1a8d62 +bf9c8516 c05b5d85 3f7409d8 +bd777d4e bc945012 3a0b0d43 +c1b00616 3dee8dd6 b043eeff +c12abf9d 39a5f072 b3a834a1 +408d8b26 bd33a263 be444967 +4045067e beea23f4 bfac45b9 +3f1f69ab 3d977422 3cf585fe +c0c15dce 398f73f3 b6837498 +c16cee67 3ff82916 b7327e77 +c1adc026 bf8178db 320b7669 +418ab335 3f1d9459 412ac08f +3ccb04ce bee1a732 bbb52b74 +3d34ee50 3fa0fa76 3ce89249 +40876750 3fdfe91a 40e977fe +3e0aa85a 3e02cdb0 3c1745ee +c0e63b5b 3f99b94c bbd4571f +be7177ba bacc6b25 392a2f7c +c16378a6 b5c8c6f9 2d7a6df5 +c19f655a 3e4c52af b217d1ed +c1f586a3 bfb3eefa 2c0e630a +c21510b6 bfb7f59c 277c51e3 +bfb9f13c bf772570 3e882274 +be0caf24 bbda2872 39df54c6 +b498b16d c075d8e4 3512a32a +42107ad2 3f8cce84 421eef70 +40af97b6 3c62869d 3d9abc4d +416c68e6 bf5a81e5 c149c943 +bb313c42 c0207a18 3b5de776 +41c82b64 3f89552f 41d6c3a7 +c00a6147 c023ad7d 3f12166e +c0247ca6 be9c7877 3d64b313 +c06c0026 3ee10a23 bd2222c1 +3f85c017 bffff95b bfc5e070 +bae0b705 3f9068b4 ba7d4e14 +c0dedd0b 3b366c37 b799820f +4138a786 c04f4d5c c21586e3 +4139ca15 bea0de0f c0697e60 +c03f7958 3a6bbf9b b906d9cd +c1f7936a 3eabee43 aad45bb6 +41644b2b b9259915 bb13acf1 +c1719d2d 3f742b18 b685a6e8 +c205a441 bfee679c 2a58897c +c1a662d4 3f2363ee b2539356 +c213e99f 3a1680ff a2089fd4 +41d0a54e 3fb4bc09 42134d7c +c1a9a13c 4023c2dd b3102028 +c01c2f41 3f37db6b be0fd674 +c02326f5 be0ff185 3cd4c2f6 +3fe8662f 3cdf7892 3d2e79b2 +c022d4ed 3f28a422 bdf9ef6c +3f79a103 3cb47a6e 3c7f94c1 +c1cb6372 3f4e1e95 af4ca588 +c13fe985 bf8b6a02 38a942c2 +c0f40450 40796363 bc6d6216 +4209a7f1 bf4c55b4 c1dbbfd3 +3fc12d68 3f8403ad 3fa329a4 +40a8fa9e 3f236428 40569bc1 +401b7e55 bcdde924 bd77c144 +ba5b891d bf5f5018 39bf6c99 +ba010141 beaab052 38abfc89 +bf89a440 3f279ca2 be376747 +c030797f bf5c6b98 3e1110c3 +c21d6716 3f157545 a5576745 +c083da60 3e0c1fdf bc139b8c +c1a3cca6 beb4c55e 321f342f +bf1d07ee 402db6a6 bf15b9cd +baf17a98 401072ae bb082101 +4214aa00 3f6da4ba 420a010b +3fa41f81 3fe3f504 3fe4cfc3 +41c99804 bf9ab3f8 c1f3a656 +372acf28 3fc81e8c 37058665 +41dbbaea 3ff44797 4251ab99 +3b976ce9 bcd87ce4 b8805983 +bffc49f4 37c849e9 b6c11762 +bf07d2a8 3ce32408 bbb28b13 +bd55b188 c00980aa 3d5f9231 +c1a063fc be6c2da9 321bf091 +c1a32f2e c06058d5 33d49222 +c03ea7c4 4052ec03 bef33613 +3ed41838 bf65700f be64e7f5 +4185db52 be9679fa c09d5c93 +bf135627 b6f8898a 35cdf51a +c1aae2b5 beeec310 31b4efe8 +c20bab6f be614dec 27bd8c71 +404047f9 403358ed 41005875 +41e50a2d c0357c9a c2a25fad +41cee872 3e41a7ca 409c84db +bf9c52f8 bf8331b9 3e91f0a8 +41a83786 b9dc0dc5 bc1098c3 +3f06162b 400285d3 3f2bbd83 +40d91f1c b7e58133 b9426e22 +c1f541c2 3d3e6ef8 a99badf1 +bd1ed02d b7e8d48e 350da3c6 +bfd62171 3ab22eee b9bc6f0d +3ac5fa0e be04423a b8ccb7da +c00c29a2 bfcf1647 3eb6967e +404b39f3 c055b44d c122d8b9 +41fc0e33 be50116b c0ccdcb0 +bf8bbe51 3f988c28 bea766f8 +41d91504 3cb2af28 3f178524 +c162960a c07a4588 38245188 +363e596d 3c6aacad 32ae7e33 +41969b01 bf40f1d5 c163050c +417dd1aa 3fcf429a 41cd7e90 +3cd133d6 c074e392 bd4aad7f +41e0344b 402c9616 42972694 +bca5b45d bf3f2233 3bf4eecc +416a0f54 c07651b2 c2613566 +c1d5f882 bff45824 2f07fa4d +bfc984c5 bf6030c6 3e72435f +c1f88a3d c02d747d 2c3ea7d6 +41af1992 407c378e 42ac832b +420103ac 3e8355e7 41046057 +40fa764b bd177a01 be942403 +405333c1 c0791601 c146303e +c0dd2f35 3f14b5c0 bb82e14a +c1bfed36 4061fecf b15dccc7 +c18a5e7a 3f78c576 b50ae913 +40c4caf1 bca72b16 be003b75 +41977135 3f3961de 415b5569 +c201c7be bde18fb9 290298c5 +3cfb0484 405fc3f9 3d5ec596 +4217176f be6cbad3 c10bb7de +3faaf70a 3c317d49 3c3bb40c +c1650195 3ca26d8a b4394e64 +40ad3dfa bd052fbe be33765b +41e479e3 3694c3e2 3904c54a +408ff086 bfe3669c c0fce759 +3fbe0eed 3ff49dee 4014108d +c0dc3fb8 3ef131ae bb59a45b +41c71257 bf8cf86f c1db3e6f +bf96cc21 bd06c871 3c1582c7 +3f32b1b9 bdd02791 bd420b40 +c1cd4fca 3fbb1829 af9371c3 +bd9fe31b bfb0706a 3d53cb6d +408ca229 bb1e95ee bc2c1d1f +c1515a35 ba78afaf 32dd7950 +4019ca4a c04464d9 c0d86464 +c0e75b51 3e0d953f ba3dbe09 +420ffad3 bf5ddc3f c1f98ece +c1a6738f 3e632fb4 b191f40c +3e5fce20 bf3834ab bdb2918b +40b86780 3e076c14 3f427c63 +c08a9ed1 bfa9b863 3d9898cd +400e3433 391c66db 399cc3a7 +40439237 be3bafe7 bf08ef98 +41bf4881 3e9a5b30 40e6ab80 +c20f477c bfb6fa3c 28801a11 +bea1b143 be6ca0c6 3cfc1a54 +c182c1e0 3b18d069 b150ce21 +c1d98287 c0319c2a 2f011c1a +c17127e1 3e240576 b5386dc9 +c0d07578 bf502cfe 3c00704a +b9505072 bd09bc8a 3660233d +c2145b5c 3ff35a71 a7c64807 +4091e821 bfcbea88 c0e60921 +c1c7b93f bf5900b5 2fa74104 +c0703627 bcb2307f 3af51550 +bfcbf874 bf45bb56 3e54dc66 +398fa74e c00076e5 b99031cc +3b29f486 377248d8 32a10ee7 +c0933ab0 bc480a34 3a126a91 +c114fb8e 3e4a03d5 b92e1605 +3ff809cc bca8a0d5 bd0ed0c2 +c144b5e4 38948357 b188edf5 +416af502 3f05438f 40f49e90 +41b59500 3e4cbd4b 40913900 +c20a0361 378505c1 a127516c +c0e8bcdc c07d95d5 3ca3b85f +bfa3f17c bdce092b 3ce57e82 +41d6aec1 ba4cc2bc bcabb690 +3e898569 be55c6a2 bd022b54 +3ce77331 3e6e440f 3b5a759b +c10d4b44 c03f8d56 3b7d1ec2 +bcc4ec8a 3e546e6d bb21720e +3e841b4d bdd22704 bc74b8e4 +419a2a6f 3ebec712 40e5c6c0 +c1de7a66 bf4a0095 2da16d4c +40aae428 40574836 418f0648 +3ff58b30 bd59091c bdb583b6 +c203207e be1a42bc 2900e411 +3d81f58b 3ffaf895 3d83727c +40cb354c c02d33a6 c1893ea9 +ba5300bb 3813d098 b2739197 +41bddb35 bcbe503b bf0d2432 +b860e7d8 3faf5085 b81a042b +c02f3191 3ec3bbdc bd824fcc +40842589 be0a3b4a bf0c732d +3f1a091f c061a146 bfaf6ab2 +c18bbad2 bd08907c 3281ec0e +41d0cd5c c0196003 c27a3217 +3940b588 3ee1e1db 382a0d91 +3efa7277 bf151173 be34ceda +3f87781f bfa92b14 bf84ea30 +421b10bb b5e67bb2 b88b9bf5 +c15cd726 bb5d10b3 334a9495 +3db2687e 3ff00787 3dae8f44 +bf685be1 bdcc9bad 3cd58e32 +bd51f3f2 3d8e0e6a bae309d4 +c0f85e59 3ff16d36 bbcc2cd5 +3f5c41a0 3fe88888 3f8c9828 +bfbc69c4 3f880eb3 be958497 +c1c1a142 bfb6f93b 30926d3d +418dfbf6 c04661c8 c25c0e37 +c1ebaf08 c041c518 2d7bda96 +3e1440eb 4073a4b3 3e974b39 +3b98ea23 3fa9729b 3b4ae6f7 +421076a7 3ed6443d 4171d363 +40cbde43 bd7d1691 bec93483 +4080dd49 bef5adc0 bff30170 +c0a77fb7 c00cc553 3d7a08ef +bf66e990 bfed30fa 3ef70395 +3da6a848 ba4a26b8 b808f402 +408c31e0 baafaa58 bbbe061d +4129c872 bd3dc1e9 befbb196 +400daa8b 3caaa8e8 3d2a449d +be85c4d7 bf39bd9d 3da8e5cb +3dbad021 403107d6 3e0712ed +c1144aa1 3c610794 b74989e0 +3fc21542 3f38f01c 3f65f040 +3dd8d5f4 3f01419a 3ce68b70 +3d401848 bf4a9657 bc9b9459 +c1ead8de c04bb3de 2d927418 +bec6688a be047637 3ca60817 +402f0043 3f2bc272 3fdc82a7 +c0de77d8 3d80482d b9da30e0 +412897e1 3fd5b4d5 418cbc80 +400889fa 3b36c2aa 3bae4f10 +3e542b27 c01c423f be8edf91 +3f19b2b6 3db50dc5 3d0c6309 +c1b4197c 40652acc b2676958 +bf1e80b8 3ccccb96 bbb1818e +c1172b02 3ee12a78 b9abbfb8 +c018c35c 3f454e81 be1e9246 +b89d7646 3f87cc66 b8270c95 +c039b971 3d7d4684 bc190c24 +414e3cda bc2a9f7c be0974ce +3e7324d3 bf80978f be08910a +c13841bc b7f8e27a 316a0fe2 +412ef270 3c0ebbb7 3dc314a0 +bfc8a551 3f989448 bea51829 +c0e8a7f4 3dc5f042 ba001325 +be588247 3f96872f bde3cc19 +c105b1bf bb5e1dd0 36df4416 +414ba9d1 3f0e6d1d 40e29dd4 +3aef591f be691636 b95a1fd1 +c13baf64 3cd289d2 b622c8f4 +bffdb6dc b4f20d42 33e86352 +4215b1f8 bd01664b bf9754fd +c1d68463 b8c7353b 27cf9c0f +c083a609 3d6d3787 bb7b122f +3feb453b 3dc4195d 3e1b7aa1 +41a4a778 bfff00a3 c2240339 +c04d5d45 bee50f95 3d645b13 +c074152c bfb4665d 3deda4c1 +411bf7c4 b87350cc ba143b31 +40245123 bf9ca3e7 c03ac0e0 +3b55561e 3f936618 3af6116c +41ef1232 bdfd17a5 c06c5b10 +c1ebda7f 4044d8ce ad7aa92e +3e20ee5f bfd94a54 be134efa +41a98803 b9f072a5 bc1f3b6f +4018562e 3f9c0c5e 4029fd40 +c13c89a0 406f5eb1 b9b04578 +3e4fda21 ba58446e b8c15a28 +40896e85 3f5ba3cd 4068a695 +3a219c98 bd80cf0e b7a2aedb +c09eebca 3d7bd34a bb0a7c64 +3d7c8d69 3e303320 3bb32f1b +c119cdc9 bbf0b133 369e6c73 +3fae7918 3f57ebfd 3f6a5a22 +41c3ba3f 3eec2066 41348877 +3e93b454 4045d018 3f027b4d +bc0d6b27 40543c85 bc697945 +419500cb 3ee542d3 4105709b +c0ca8593 3ec800f7 bb904733 +421e4420 3ca7d1ff 3f4f8088 +bd92077d be40030e 3bd34044 +c218fb7b bcf638f2 24022d1c +c14ac60d 3e2c7de9 b6e0761e +c1add2b2 406baddc b2fbae5c +c13ccb29 be70497b 37ae5fe7 +3fdc41eb 3e21e42e 3e6c4bc6 +c18061bb 37b48e4a ae22fd33 +41f7a31d 3c69ac6c 3ee20a3f +41268d29 bfb4734e c16acaba +4068b005 4003c3a6 40e960ae +3f78de32 3f9c69e6 3f5ca5b5 +c0c994ed c02551e6 3cf47934 +3ee59447 3c068324 3b133b06 +c1641c70 bfa17fc4 3742160e +41d8e7b7 3fa75166 420dc420 +bb18a074 bf9b3896 3ab8de98 +c1c6efe6 be8adcdf 2eeb3d61 +402b9bce 3f5d15cb 400ab4e1 +3fd66e32 bb9c90cf bbdcea53 +c014c516 c06f5081 3f464a03 +3f1f0c8b c0515623 bfa93531 +416d5f2b c02006b9 c21461b3 +bfcab6cb 3eeabffa bdfd35de +bdb614a7 b6fd9962 34ac5c35 +41535e95 bfa214bc c185d2e9 +c17988ba be84764d 353695ec +41b2f4c2 be8d81c4 c0c5d70a +c1b79beb 3e4de25c b008af10 +3ed388f8 bf235b6d be227a59 +400340af 3ebc92cf 3f2b53e4 +be5ef0ff 33ca3c95 b21d0623 +40a7f031 bf2a4905 c05e3fab +c08958df c068cd10 3e57b1fd +3eb5dd1f bd81bd6d bc58bbf8 +bf1e8297 bec1f44c 3da81d42 +bf51ecf3 bea5aecc 3da62a7e +3c5bc7ea 3fd80aa0 3c3ab843 +41d23cbc 3e72a3aa 40c743d2 +c02d61f9 38b86039 b7797ffe +411e627e 3ced709f 3e92e4f9 +41f3b910 bef1d710 c1663df8 +bfa5bca6 3f0f3cb3 be1f877e +3dd94a55 3ed3e7b5 3cbd654d +375fabda bd37f358 b4a0b8bc +41216ca2 b8f10f63 ba97ff5b +c1bfea2a bfaf7e87 30ac7b69 +41acc0c4 4027dc05 42628c72 +3db86c83 3d6a70c4 3b307dd8 +4176028d 3fe9e031 41e0bfc0 +3fc18c2f b95f2495 b98a3b9e +411e1418 3fc1aff1 416f3073 +bcb0dd9d bebfeab7 3b832919 +4185ea0e bece7782 c0d801b6 +3cbca5a6 c00c2d95 bcd0f94b +410b9ee5 be252379 bfb41a0a +3d54a0a2 bf998b14 bd02d6b6 +c15a9c2b baceb160 32d78b11 +41a68505 3e817653 40a86bfe +3ba79a83 3ea38215 3a56a543 +be30190d 4042838f be74a6d9 +41290063 3f1519bd 40c4db21 +c160e964 3ab1194f b2802663 +bc85f5bc 40119b34 bc9723d8 +3ff4bbc4 bd75b228 bdcca3c3 +3e9a2fa3 beda13b7 bd96f96f +417f1046 3dd17c3a 3fd0b80d +3f9e7a77 bf5285c8 bf4a10c7 +4089be80 bfad309b c0b7e3e5 +42178eef bfc014f1 c2636f32 +3eab59a0 3f337411 3e0c0747 +405f319b 3d6da460 3e490a63 +3a7dd5e9 3a365c2b 34b4e7e0 +c1fbb8f9 ba6ca446 2630f94a +c139469c c062ea2e 39c95721 +c21cfbbc 3fcafa59 a62200bf +c2182e41 bfc0ded4 26f7e3a3 +c0298e78 bd1c1f4d 3bda7e15 +3f1e432c c062f497 bfb6588d +40bf1a69 befee0fa c03dc84c +41377253 c01b3646 c1de71a0 +bea8282a bd98e3e6 3c282a5d +41685166 c07901a5 c261f8a3 +4017da74 bd5ffc5a bdf310df +bf096fce bf29741f 3e063f20 +c00623f9 3e567798 bd44deeb +405dbf56 be690def bf43bfc2 +401e7eaa b6df785b b77f421c +c09b3a73 3c61a1ba ba07e872 +be3db946 bec4473e 3d0406c0 +41b9ac3d bc0fcdfb be509936 +bdd0d6bb bb04d567 38cdaf48 +41a8cdde 407b0423 42a58493 +c07b5f39 3d5c7858 bb85c353 +418d0604 3f8a6448 419878f8 +415e31e9 bfb807fb c19fbac3 +420e31a5 c06290e1 c2fbb099 +c08c1112 3f8afe2d bd718673 +c08299d6 bf8966fe 3d94fdcd +41dda5c5 bbfeabb1 be5c7f20 +3fadd938 c025b839 c0330ae7 +3f5a577d be21a6b1 bdc1582f +c16c3323 bda887a9 34fcfe88 +41070450 be0b4b3f bf92e5eb +420ac25a 3fcbf5b5 425d1a97 +40901c3b 4017ec18 41292baa +3e82d0f2 bb0cca44 b9a22b87 +41be88c9 38c463aa 3b122ae7 +c1f965af 3e0b41ad aa09fcb3 +421a3b7d b9ac925a bc4ff048 +c07ac016 be1e5b7c 3c4183f6 +4008eeb2 be34ad8c beacee72 +bd244ba4 bbe3324c 390ee2d4 +4178aa53 3ac7634d 3cc1acda +c0f0073f be967800 3a9f9351 +bdf237ce c06fec8c 3e559956 +c191bd9b 3d16561a b20cbda0 +40ca144b 3d57d7d1 3eaa12a4 +c01eaef8 c0518460 3f20a6a1 +4132ea9f 3fec1559 41a4fe9f +c1488635 be99716c 376343b8 +4051ccdf c03c068d c1147eb7 +b9a60acf 3eff835c b8a5b341 +b77526c0 bfbd1a8a 373516ae +41c85444 3f73819d 41be8d6a +3fde1def c0019389 c03f24e7 +bf85a993 bd90074a 3c9c9dca +bf888cfb c06929f9 3f7eb8a2 +beb75a42 3dca2ea9 bc6e4dfa +c083f635 3ea4d35f bcad30ea +bf9dcff1 3f327049 be469737 +c0c7dfd6 bba41975 387dc644 +41061863 401b51f8 41a2addb +c09acd70 3ede94b1 bc877ac1 +bb430ee1 bb7734e7 36bc13e9 +bfdd0e8f 405fb4c0 bf694e31 +c0d7022a 4004b8cd bc89b0b2 +3e09522c 3dfde283 3c114ddf +c16b27ea 3b4d9cdb b2a401e4 +41898b53 bbb24cd9 bdbf9853 +4213de68 be6a2f36 c1074490 +c1b0e7d6 bfaa2c21 31fb9ddc +bc6de066 c044b0b9 3cb57060 +4142932a c0126a02 c1de90b4 +c1785149 bef0cbaf 35b231a2 +bf3f58c9 3c0d2089 bb079a32 +3e427d10 c03e8b4e be9e7764 +3f5c17f5 c039ac13 bfe05062 +c1caebf4 be647492 2e6fe621 +c02769f3 bfa26039 3e677dc4 +3f85eb71 40048e57 3fcd4552 +c039813b 3d20c3c3 bbc2b19d +bdc02699 be8e56d3 3c4ba8e8 +c1450b06 bfad569f 389ccbb6 +c1b7caa6 3e0f5613 afba35a7 +41e37175 b540f829 b7ab7192 +c1ca455c 4061f6d7 b0804874 +40706591 c00959a3 c0fc10dc +bbbeabcd 3f402e8c bb0eb8e9 +421feeb2 3f3fb578 41ef88eb +c21414f1 3d3ad4dc a522c32e +c08b7e8c 3a8d2a8a b878a70c +c0e9d8ca 400338e1 bc24739b +3ea4a84f bfe3f236 bea9fccb +3fa9302c 3d01076c 3d06a4e6 +4138720e 3dbaf024 3f86af8b +bbf21e7e 3dfe6250 b9efb3b1 +40e002eb c077e2bc c1d8b6a5 +bb18267e bf402582 3a642273 +be2d49ca 400e8f83 be30b582 +420e7237 bd8de3f7 c01de782 +41144fb6 bff4249d c18d6dc6 +c072b891 3bdf806b ba1577f3 +421b3d9d 3efc8bd2 41992570 +c1318d44 3ea9e2dc b86a176b +3c264ba7 be658b7f ba95de02 +c2047099 bf7274df 2a135c32 +bb554849 3ea4a901 ba08f5f7 +40cdb781 bf48f417 c0a138df +41d44a70 3ff3b74f 424a1aab +c1f10a26 3e7112bb ab241071 +3f9fb74d bb140fc7 bb0f88b6 +3f063ddd c031dd88 bf6a5b46 +bfa17c7f 3f8df8a0 be9e1e3a +41d203c1 bd0e0203 bf68ff77 +c1a23753 bf4ad1d5 32d79c25 +bd4caf81 3eab90f1 bc05bfdc +4140103a bba0427a bd7077a8 +c00092fd be0d8eb4 3d0687ba +3f7b585f b892d92c b851c52f +c21012da bf305572 27cb8d0e +c20fad69 407a2e9c a91eff66 +40cd1195 3fa74708 4105c6f1 +41b430d9 bb2d1bae bd73b0fd +3d442c20 b990f3f5 b6e37929 +c2020e2a 3e4911d1 a959d1c3 +3f1c766f 3f24254b 3e820f8b +411b871a c0037c5a c19fc0e8 +41e655df c077566c c2de8a9c +40fc6c26 40231c24 41a0c52b +4052038f bfd7a25f c0aa7e45 +c1ad5f45 3f654b56 b201319c +c1c24e7c b91dcc6f 29e8e32d +41962151 bf50689f c17470d9 +39b03636 bd2f4d2b b6f15ebc +3ecadb03 bffb312b beedf811 +c19ac09b bd31da8e 31654127 +40780d36 bf18bb28 c010fb80 +41429efb bfda730a c1a6129e +3eee6bcf 406d6a5b 3f87d79e +bf21e7a9 ba3d2578 3926047e +3de2bd43 3c89ab0f 3a80acf7 +3e8515c5 3f346455 3dd3cc56 +40b77c6b bf0c55b0 c04884e4 +c16dcc30 3fd35808 b7108702 +384e758b 3fd3b10f 382abac0 +c08d97cc 40146a2b bdf8b55d +40bbf6d5 3dc86503 3f12b963 +c1aace63 bf9f0faf 32735e53 +3bb4faf2 c061f66d bc202fb4 +3ebcb543 bcd0aa1a bbb5d827 +c1dd17e7 bf818e6f 2df4aa12 +3db46cf6 c041b8bd be0e8afa +c21f0aa0 bcad1402 22a75135 +c0662636 3d8902ee bbd278ee +c140aa12 bec773e6 37e7f037 +3e92e6e5 bad0d23a b988e713 +41c9351a 3ffa8b08 4244eb22 +41007a6a 4042112c 41c2ba8b +bd9e305c bdf2aefc 3b902bf3 +bd7506ed bdfbb028 3b69b25b +bfdbb29d bf26e373 3e2e8b7e +c071c019 3f01749d bd2f0869 +3e0011ef bad1e5ad b8df20bd +bdbb0d83 3e0a1377 bbc091b5 +40da1d58 c05c25d1 c1bb5cde +c207a1f7 3db3fbb7 a7c9b58e +bab4f609 be8aba41 3943fdea +41ba5ed1 bd5e2341 bfa1b7e4 +421939a6 beb7a13f c15bd171 +c15e17a4 3bc32735 b3a65021 +bf12ef55 3e9a6994 bd7f79a3 +3e886a28 b8260bab b6c865b0 +417d7666 3e017b0e 4000327e +b159c8b7 3b09661f ac69c695 +bc307b5e be5b7aa7 3a967d7a +c032be29 3bbc6489 ba72ebb0 +41a5c1b8 ba2738b4 bc588c2c +c0421c63 bf6bbcd7 3e036ff7 +42050081 3fbf3cc7 4246b5e8 +b746606a c00f9383 375e83fe +4092eaad bf4952ee c064c1cf +41234925 3af65507 3c9d1d09 +41f0bef1 c0105d78 c287c34e +41b724a1 bf5f07a3 c19f8e5f +420e61ab bf740365 c207b6fa +3fbf5065 3f06a4a4 3f245ec0 +41f830f6 be9429dc c10fa4e3 +c16310c6 bb678b59 3313d8ec +bd85befc 3f7937a1 bcfbe7a9 +bd8b4092 3e666df4 bbf22ab1 +41298280 3f1113b4 40c01eb2 +bfa934a3 401b9465 bf2d2b0e +c1fc6282 3d0f2b16 a8c5a4f3 +400c60b8 bc5e067c bcdb0fe7 +bd273838 39ef8934 b7194598 +410288ab bcbfc0d7 be437e43 +41f603cf bf552c2b c1ccdb9d +c09d814b 3ef481c9 bc8b3fbc +c1014530 c064f657 3c12b1b5 +3fbc5a45 bfcdb182 bff62a1a +4184ac01 3fad8510 41b3da63 +3ebc93d7 bf055154 bde82de0 +3f53e4ba 3f322ed7 3ecd4249 +c143b560 c073de09 396e2895 +c036578c 343c2cef b2eabb35 +3d9614c3 be1840a7 bbb90e37 +3a82263c 3f9587a8 3a181dc4 +bf1a6b70 bb474ac5 3a2a0908 +c16e80f3 3f74c859 b6a0a4b2 +41bc1ce9 3ef535ec 41342f4a +c1805349 40491ad5 b6b6be51 +41b2ec19 3fe361bc 421eeba9 +405f1d9b 3eaed12e 3f93d5b0 +c1512f83 b6daacc8 2f44a15d +bbf901f4 402104f0 bc1c06b1 +3c8f7baa 3e150ce7 3aa88afd +3e25fb13 3ccccf05 3b0f875c +406ec699 3f19e402 400c2d20 +c1c20aff 3aea96e4 abb2aaa1 +3fa67b8b 4013a505 4016ed63 +42135127 3c9ea784 3f3698f8 +c21855c4 be05cc71 2525a009 +40c014b7 3d1b3298 3e6851f5 +40c14b5d 3ea65903 3ffa9b6f +3f50140c bfab5697 bf40f078 +c213de5b 3e06b3be a5f73103 +3b4b707c 3f1b8de9 3a779dff +c1fe0578 39088135 a49a9404 +c215a2d6 4036ac37 a7da110a +bfe060b9 4046f3b6 bf4e024a +3908af6f 3baa8dd8 34b62381 +c1b30331 c0509de2 326fdd63 +c1bedbd4 3ffd8276 b10d604a +c1ba8113 3d1ec844 ae952032 +bda4c6b6 bd237e40 3aca013d +3c5332c7 3fd4c09c 3c30a68e +41f4b4a5 3eaf0c58 41275349 +421bc946 bf6137f8 c2090df6 +c15930ea 3c01243c b4123478 +3fe72315 bf323e87 bf8a3791 +3fadca1e bf272d8f bf348a35 +3aebd0d3 3d45fd62 38368b1a +411b0f61 be83e4bb c01fc44b +c12e08df bfadae31 39922012 +40efe8d6 bf62f4b9 c0d492b5 +bdc463cf 40294af5 bdf74d05 +beeaa8c5 3fdcd655 be9cd5b6 +40b970fd 3c547236 3d996ccc +4190a485 c036d304 c24e9861 +41e48dc4 3f9ae0f8 420a4621 +c1992b04 be9d6196 32f4c385 +c1cbb63c c003c729 2ffbb48b +3f1abd8b beca7a21 be1e4a6e +417a9712 4062a9db 425ddfa0 +41c388b9 402449db 427af800 +c19215bd 3f7f7da3 b465a665 +3ffaa445 3da7a611 3e0fd739 +c0dd560e c01d7c1d 3c8a0ad9 +4069124f be864bb7 bf6e4a5f +41a216cb bf6170fa c18ebd91 +b9d04eb1 3f44432d b91faaca +3efdbc3c 3f565439 3e84028a +c0c40569 3e6b9573 bb4975d4 +40feb167 c029eea0 c1a90167 +bca4ad02 3e100999 bab77230 +419f3021 3ecefcba 4100b5e2 +bcfe02ad 3c3bab95 b9375335 +bece9fb4 3df72ce6 bc9fc885 +be8ebf6d bd2bf2bd 3ba5331e +bdbdccbc bfb4afe2 3d7f84b9 +409852bd bf31cfb6 c051cd97 +404a1855 395ae34c 3a25bfdf +bc1acd15 3c9a0ef7 b8b96f82 +be83e698 bf492c3f 3db4bf63 +3e976b3e bd54a91a bc103ff7 +3ebbc437 3b3d895d 3a243a2d +42104c3a c001644d c291dde5 +c20621ae 3cd546f3 a72c02c8 +c1df7750 c02d9ee3 2e765834 +bc5b6d42 b4286e5f 308f66d2 +be1f63a4 bad88366 38f8ab00 +be9dc034 3e89a6b8 bd0fb733 +41db89b5 38ffdb7a 3b5b6a63 +413dbafb bf15b4ba c0dde725 +c1897ed0 3f7b8fb8 b51bb054 +c0357c03 3cbe00d3 bb6ee6f9 +be8a253e 3e012019 bc715858 +3ebaee00 bf4ab5cf be2ebdf5 +c1fce8dc bd4e95d7 2905d1be +3c8c3b63 c0208f8c bcb168eb +3f836ee7 be3fcb97 be1101aa +bd91a400 3f398c7b bccb9df1 +bf6e9430 bf2dc938 3e370896 +c11aa7c5 be0d4347 38b14c23 +41ec5845 400a6cee 427f984c +41ff0df9 bec2c618 c1420df3 +c1d6fdee 404b9816 af4865b9 +c15c236b 40750866 b869dec9 +bf393032 3f2cc464 be234b81 +41e8587e bea5268b c115e405 +4208966c 3b7fa67f 3e0866ab +bf95c2e3 bf86b604 3e955323 +3f9dad60 4054a860 404acc00 +40d91953 373313a7 3897b171 +40629ee1 bf8b2b9c c06f74e2 +c1a3d952 4043d2a6 b3ab72ad +3cd8db95 bc378fd9 b91d8dac +3d2b8ae2 40074037 3d390e13 +c194165c beef5028 33a9c586 +407bf7f3 3b2d3df3 3c274057 +bf626bd7 3ea53a09 bdaad5fe +c119b178 3bc8334e b6849730 +c140c13d 3fd9a280 b8fbc5c5 +40597aed bcd25c8c bdaced48 +418250b8 be996c6d c09c32de +bf9e74cf be71ce5a 3d8694ac +3fa84bb4 3f1a1bf1 3f1fbb6f +c2026758 be02ef2b 29025c07 +c04121fb bb85e287 3a16b9cf +418454f3 bc4b7698 be525953 +4184d1f8 3e41f685 40494464 +c21fdd99 bf9bd0d9 25767021 +421db457 3fa021f7 42454b46 +3f0ef9c9 bf803764 beb633e2 +c208c2b8 b42d6e54 1e13d38c +b9ff9565 40430219 ba42a4bf +3d69646d 3e184ed4 3b8ecffa +bbb65e29 b76cf6b1 33285649 +bf37e4a5 bf4f2c4a 3e431ba4 +bbfca968 3f7e0955 bb79c1d7 +c1727254 3faf5744 b6b6d963 +4077741c 3ed05d65 3fc54776 +bf2210e7 406dde18 bf50e72b +c1ae4d67 3d524d41 afd41a6e +3a528686 bfff013b ba51ca91 +c1742c67 402af1f5 b7212ac4 +41a8c465 c0562399 c28d2ba4 +bf7d28eb bda9713a 3cb5b942 +416647b7 bb8883bf bd75992e +c1343b00 be9c05d8 38389779 +3d38eeb1 c04136d2 bd8eba0c +406e011c bf3dc0b8 c02c3c32 +413e6daa bf84c277 c145820e +3fa649d5 c0402304 c0441dab +3cea5376 3f0c4824 3c023dc7 +41f31fa1 c07951a1 c2ecc74a +41b1ee8c bf1c1831 c158fc5b +c1df6104 bec4cca6 2d0d16e1 +3e357dc8 c0252c86 be7ee692 +3a578a92 3be4ef9a 3640d56f +c1b7d8ce b7e44fba 299352da +40f1130b be1bfe9a bf92d230 +3d6670fb bf86adb8 bcf948a1 +3fc21bf0 4021d905 404943a6 +3d4825f1 3d1e24e1 3a7d52dc +c108f1ae becb2aeb 3a2abd8c +c1a1f451 bec03c4e 3252d089 +c052c4d7 bfd81a7b 3e4bd805 +3f94fd22 3e9232b2 3e81adef +3d62e079 b9e5ae0d b7512fd6 +3d4002b6 4076ed6d 3dbd8bc7 +c0f32ae9 b95d6b4c 3557ac29 +41d37386 3d3a9200 3f9a1a87 +4117fe9e 3d9c7d7d 3f39cfc4 +b7e454cb 3e0c2517 b5f9fe09 +4196a015 3b94443b 3dae7963 +c0e1827e 3fa55e63 bc01a4ad +bf31cba1 3ca39364 bb97560d +3f652d2a c0477a9c bffd9174 +be91fbbc 406380a0 bedeb95d +3e090875 c0035c51 be1606c8 +c173410b 3f9f1530 b69e4172 +3ff7c527 c06e2816 c0c96df4 +c1181d7f be7e1929 3937d263 +419c398e 3fe14324 4209778f +3e9b5498 4047900e 3f0b5089 +41a79bb5 bb83b5de bdac7780 +c209a0bd 3e745547 a828babe +404217fc 3fdeff9e 40a14ceb +3a1388a7 3a1f51eb 3437af66 +41353020 3f79db3a 4130d66d +c14f9fe8 40776522 b8f36bf4 +421c3f8e 3f715220 421349f5 +401b1818 3e12b56a 3ea34a90 +41c07c13 3e905cc6 40d91718 +bd9738e1 3fd91837 bd77040a +bccab283 be75f324 3b40549e +c04ff0d2 c03c200c 3eb6afa6 +c12ff6c9 3fe2eb4f b9ab1b29 +3f15fcab bfd861a1 bf22e2c0 +4083b3fe 40688514 416b6802 +be6b1b86 b5d23ffb 342b057c +41c3ab74 3fba49d9 420e6304 +417ecd79 c0238919 c222c548 +c03db4e8 bf4bf429 3ded5442 +c001236c be95a9da 3d8dc052 +c1011c41 b836478f 33eb9f8c +41bda00b bfc33c43 c2109d8c +c1689a89 c048b272 37b9bbfa +41064f75 405ba5f2 41e66cbc +be9ab278 c0230032 3ea7762e +40c6e23c bdaa78e0 bf042c80 +40d2f84c 3e5b15d1 3fb44d25 +c1cf2d91 bc366c6e 2be5c4f1 +4133fa56 3e95c5ad 405296a8 +c01104bf bebabcc4 3d9f129c +3b12cf74 bca50185 b7bd776d +412ed825 3e25b7ad 3fe25c7a +41393849 bf9c26c1 c161f422 +40e81a7b bfe2964c c14d4a71 +c14672c0 bf85cbe0 385f48dc +40b95988 3ebfc2f2 400a6ad3 +c08e5ed0 3caaaf42 ba8c6335 +3fc0b2e4 bf1ab328 bf3e9905 +3f650682 bb3eda58 baf266df +c1b581fa c00e64ea 31f30c4b +bf22c5a5 3e1efa45 bd0bf99b +c1b2da05 bb7e19b0 2d94e9c5 +c13cf20a 3fab1311 b8f625b8 +be0e1337 bd0ffd8c 3b14c111 +3f017d07 bd369d24 bc667cc2 +41a478b5 be8843ae c0af1737 +421df6f3 4077a46e 4318cebb +bf1bcdb9 40331013 bf199b52 +3c5572db 3d924e6e 39f590a2 +c09524f5 bca1104c 3a61193a +3dc6a067 bfc2a78f bd9e5900 +3d8d4dd1 3e5e45e8 3bfdd650 +3ea089ee b9a0518e b868573a +c13d7618 beb0e9c1 37f72536 +c034f50d be28918b 3cd4fc61 +c0ac4c16 400742c9 bd54e028 +41ce348f bcf07359 bf41ae2f +3ef65174 c0426583 bf673062 +c0388a71 401c0f05 bebeb6f5 +c0f588ac 3df3e84c b9decc56 +4056f138 3ef2c54d 3fc4fb66 +be9a288c 3fa563ce be296d44 +c1520715 40310733 b897a0fd +bedf7167 403f8cea bf0346b6 +c1fa9a95 bfac011e 2b934894 +c0b7cb7b 3fa8af6a bcc5fd58 +3cb098bf 3f8ad8c5 3c41a04f +bccb1de6 bfa3c33c 3c805297 +c1fdf254 3c714466 a809d90b +bc41663e bfd597c4 3c2068eb +c1884f89 3ff0dc23 b5ab5e73 +40989a10 bf6ba6b1 c08b4a09 +c0a87efb bf15db06 3c81caa5 +c00e1c3e 40295f0d bf1350b3 +ba8391d1 3c781c22 b6fee6ad +bc693993 bf319e60 3ba0aa42 +c21e5ae6 3f80bcbf a5931d10 +41f0f9cf 3a6a8353 3cdcbff5 +4066b8cd 401e6470 410af959 +41d48d12 baeba9de bd43aa89 +4158366d bdead6c8 bfc65715 +bfd88ec2 b8425c6e 374c9324 +c08e7fc0 c07174bf 3e45fce4 +3f507030 c01535af bfa86263 +411e7223 3f4270ed 40f0adb0 +420e01d9 3fac7f07 423f5f69 +40d58abe 3ed793ce 403398ae +41ff30f2 bc9d7f3a bf1cffd8 +3c98749f 3e1bd99b 3abb5a93 +3a9a3210 bc870fed b722cc7c +bf81e975 3fc45c58 bed40f74 +c1300812 bd5a8ab4 37242883 +41e094c3 3f312105 419b63d2 +3d1c56d1 3c904388 39b390e9 +3e08a506 3a771a0a 388caea0 +3f0bdc57 404179cd 3f85e0e5 +41250132 3eef806a 409a5d92 +bf0a6fef 3fa2133b be81045c +beba3509 3e37c766 bcdb439c +3b1e53ad c0423f17 bb708f29 +3df56a47 bdb6a63b bbb9936c +415d439e 40101b53 41f91b3e +be3e749f 3ff8eb63 be280401 +c0f6470b bfd18017 3bbb8a95 +bf8438fe 3f6dbf79 be80f011 +c0466e05 3ec7a531 bd555ead +42000eb7 bf701675 c1f0320f +4203754c be91303b c1151c69 +3c2dfec2 b8c2bfea b505116c +be55c32c c07e7ef7 3ebe67f5 +40055582 c002beb1 c07239ea +bcfe1d8a 3c78f7de b9734d79 +c18bfd9e 3f0957a8 b47d693c +c10ab6ce bc45ef95 3796d9d6 +41933b50 3e0e0564 40235c00 +412f890d 3f5333d2 4110d0db +41e42ed8 bfe02ff2 c247d3b9 +c090da79 bd9b89c0 3b7117f7 +bbd888c1 405b4b21 bc38dfa5 +42117efd 3d611e5c 3fffe3bb +bd19a2ea be21436a 3b3dee9e +bf513071 c045d1dc 3f461883 +4170d83c 3dc441ec 3fb8a390 +c196f107 bbf378ec 307672a4 +c1e27c27 bf016a3d 2cff35b1 +c1f672f1 3e1e8d56 aa606dde +bf2cd031 3e941cdd bd86ecbb +bd02a5a3 3fd116d4 bcd20285 +4178f7a6 bf413219 c13be36b +bda139e3 3ec1c913 bc6a7c3c +40478fa9 3f93cc5e 405caa82 +c1140b59 bfcd3b6d 3aba5bae +c1120f3d 3ee2ea53 b9e62158 +3ea6ff0c 3ef4a5e9 3db963a7 +c17974c6 c03dfaff 37038860 +41ac1d87 be16f7b2 c04affab +c20345a4 c0159fd7 2af16492 +c0842627 3fc31c7f bdcc202b +c189a224 c04e74cb 35fb6dd5 +3febf682 3dad4a35 3e09e6ac +c137ca64 bf7825c7 38efa915 +bffb80b4 40169a7d bf11856b +c1521288 407d93e3 b8d8a2a1 +3fd65ced bfac5007 bff309a7 +41bc5b4f bfe2ade6 c226c88f +41b282a5 3f19365f 4155abfd +3d824f0c 3fe45db7 3d6fe0ff +c0bd6241 3e7a21b1 bb7e29fd +3e57722a bf03304e bd73f4f8 +c1dfc413 bd26e6dc 2b6467df +3ef85aa6 3df32542 3d11ffa5 +39683efc c027118d b997954f +c184b6dc c0322c97 36417af1 +c102cd79 bb3062f9 36cfd127 +3e2aa511 bb01910b b93b17b9 +420a31d1 40194689 42a57bb3 +b8831626 c0554392 38da6650 +bdf7c994 3e16f7a0 bc094b92 +c05e1802 c006ac51 3e619bf5 +bc223b1a bef25e66 3b18d506 +3edcb037 bd10b362 bc173762 +c09f8ff7 be13b703 3b9fe7fe +c1ef9cfd 3c6a127b a93d440e +bfdacef3 3ea182ae bda93ac6 +baa93be7 354d7302 b007ba8d +bd4048bf be1407b7 3b5927ba +ba85ccc1 bf2cf41b 39b4b2ae +c10cba55 3f3ea625 ba81fa09 +41d88a7c 401fde0a 428739d4 +c114350c 3d7cb2df b86362ad +410eaccd 3ad663c1 3c6eefe3 +4175f98d 3fe65825 41dd52e2 +c029e112 3dd4d68e bc9483f0 +c1f42be5 3d1ba2f8 a991138c +c0679816 be27bc68 3c7da6b4 +404ae47e c06210e0 c12bf284 +c0527285 404d341a bec23497 +c1353173 3f5ec22d b8f97bb8 +4094304b 3784149b 38976fd3 +c0f28106 bfa171ae 3ba01c00 +bcabb3f4 be094379 3ab63323 +42006652 c00c3d1f c28cad3a +374e46d9 c0387186 b7949ea1 +bbdb2e35 bfb42793 3b99ba50 +be30aaa7 40074eed be2aaefa +41d6a8c1 b632b73a b895daf9 +c21f33ff b9c98de7 1fbb520f +409251a0 3fac25b6 40c2c59a +41b84d25 bc7aea89 beb4a42f +c20c6cd5 3fa3684e a8e4dc79 +41fc1ecd be5b60d1 c0d80db3 +c14d403e bd8625fc 36175a42 +c0590f0b 403fa71e bea950dd +3e5683ff 3da6e7ec 3c1a7486 +c15cf70d 3fa5525b b796684d +3f059fac 401bdf2d 3f4c3fad +4107c950 3b2d6fd8 3cb7f305 +beb42c77 bfa87de4 3e43dd82 +be64d15a beb57503 3d1024d3 +c20dec9b 3f1c4417 a8180f1d +c0ee4139 c04b116a 3c61f11a +4092b9f7 c07fcfaa c1912337 +409bac8d 4009e852 41267094 +410986bc c0509fe0 c1e01c1b +4122c615 c01961fc c1c30b78 +bea3cfbd 407364b3 bf030a4b +c1c5c094 bf164953 2f92bcdb +4028acf2 be9f89c2 bf442c99 +41d22da1 39a296c2 3c057ca6 +3c4c72a8 c00b3014 bc5fb465 +c175a4c2 3dbc28c7 b4a2cc25 +bf980d8c 3f083cd3 be173e28 +41ec74a6 bbaf508a be21ee21 +c08107a0 bf55fba1 3d70932a +c021d115 becc9dee 3d98e98c +415c9076 c06ff9a8 c24ec1e8 +4215ed8d 3fb04d0e 424e80e3 +bbc8b615 3e04b5e3 b9cf75d4 +3f62ce98 3ce4c95b 3c8f8558 +414546de 3a252125 3bfe8026 +3e4531ca 3c0f80e5 3a724cdc +b9977f96 bf51b089 38f82617 +3d13ebad 3e642eeb 3b863a69 +bf8d121d 3b809bbf ba8d5e83 +407b07b5 40360fb8 412f0fc8 +3e617e30 3d1fa1a4 3b9c0717 +3e7989ed 4056492e 3eea33f5 +c13481ba bec90911 386a2213 +41e8f12f 3daa0722 401ab6a7 +c21c0453 c078a29b 26fb1f4d +bdc75bcc 3fc1f0a5 bd8faf46 +c084dc5d 400aacac be0eb438 +40b15232 400a9253 413f375c +410ec3d5 3ebc3a3f 4051e96e +bffb10d1 baa6cd1e 39a15fec +c21ed848 be90c852 2492d5af +c1157c64 3f3f6f9a ba2066dd +40f8396c bea8ff55 c023cb53 +c1a18849 bee7de1d 3285ad02 +c12f0729 3bb11f87 b58cd9dc +41897f07 3ea36785 40af86f6 +bd94af26 bf941f1d 3d25d079 +be01ad33 bd32c589 3b29a920 +c1bb9869 3d1bc40a ae80630c +bf5485b7 c001c95b 3f02d959 +410c73cc b6994461 b82826d1 +41e8d6a7 3e159a46 40881140 +3c9d3f92 be5098d1 bb015c54 +c1a69183 bf1483f0 323c2f87 +c1a271a6 3bf4b7f5 af7d33b3 +c09ce562 c034bc7a 3dd0fa20 +c15b1f56 c00e5092 3810116f +3b08d970 bf0bf7f2 ba15cd36 +4058323d bd2b0d46 be0bb0d8 +c215c3d9 bec26aeb 2660eb09 +41a82b62 3fe809d4 42186dc6 +41703926 c05c96e8 c24efeb3 +c1358c2b 3f87e10a b915236f +bf99ddf6 3e0bd44d bd1b61e5 +be32b2eb 3ff0620f be193183 +c10e42c2 3fd828c6 bb075d87 +c128f5c4 3c623adc b67dc0f2 +41b3e83d bd0d2990 bf46683e +c08cf878 bd829015 3b5e0ec1 +bfe1d4a7 3e702a25 bd77e1c5 +3d961bbb 3f32c476 3cd952ea +3b35c745 c0411257 bb8948ed +c1326a43 bf833302 392c1ef6 +3cb72263 c017d808 bcdbad46 +40c2d291 c06edfc7 c1b560af +c0bbd57f c06e23af 3d7bdfde +c1bf4cbd bd627064 2e6f906d +3d18d870 be127e3e bb32310e +41056881 3c61c105 3deb3c78 +419b8bb0 3d1eed5e 3f4120e0 +4019f7a9 bf27288d bfb86f27 +41a0311e c00071a9 c220bf5d +3e1e6c6d bf8607df bdb2b1c7 +c1508f08 3e7848d5 b6e77ad9 +365c55d2 3d9541a4 34007680 +3dadfb8e 3e1ccee8 3bde3017 +41706bf1 bf3f595c c133b472 +c074339f 3fd320b1 be0ae03c +420139e8 bfaff54f c231a4d4 +bfccec27 bfa6174b 3eb286ad +c1cd172d c009e942 2fdf3877 +bd8a3095 c07fbe25 3e056528 +c199b34a 40278789 b4749f0d +bff9388a be98cec0 3d949d49 +420f5e02 bf165597 c1a86208 +c047ba34 3f08d927 bd9061e8 +3aca4aea 40337fce 3b0df365 +c0825f50 bf630be0 3d777f80 +c15cd131 3fedc4c8 b7da2e68 +c02bb37f 3fc80128 be8959f6 +4199a8e7 3e88d829 40a446f4 +c214770e bf657b27 27361f34 +bf26e2d4 3ace2a52 b9b828e2 +3c81b82a bfde5b9b bc6320fb +c0e3dadf bdddbed0 3a233ef3 +40a54ffe bd63865c be92173f +4193c16c bce362e9 bf033d99 +c049b343 be58fd09 3ce07744 +3f3a6421 bfb8d285 bf35802e +bf2acf95 bd838caf 3c6e1ffc +c11244a7 3f2f8ce5 ba2ffb73 +416aeb47 bdf4ebb5 bfe0c085 +4056709a 3db7b11f 3e94a880 +bec4ee97 bcfc943d 3b9d631f +3f03bd8a bf25b0d0 be5577ce +c171a05d c00b78c6 37189382 +3f3deae8 c03caa93 bfbda02c +c204537b 3e277318 a8d13c61 +c03974fd bf3ddbe9 3de60830 +ba8af5a7 3fe74235 ba7aed23 +3a3cbc4f 407878fc 3ab74081 +bea6ab0c beffdc34 3d8bb39d +420f7f81 bc114785 bea2de9e +c218e993 bf91f33e 269cf9f4 +4035a823 c032eae7 c0efe181 +40bd9ffa 3fa40de2 40f263e0 +c131b4c4 407b1dc0 ba2b7fbb +c0901c96 406f730f be3ce9a1 +3fe1242a bfa4f13b bff77e58 +40051bd8 c076f5f1 c0e44ab9 +421e5d3f 3fe1ae42 428b9bc1 +bf6edcfa c01c685b 3f24cb9c +420e1f40 3ae52420 3d7e6c05 +c1c87da5 bddfc4c4 2e1d4cb1 +bded2beb 406dec92 be4fad12 +421bac35 c0093ec1 c2a6eaa3 +401682b9 bfd57b08 c06533fb +c1c70bef 4006e66c b0618b3c +c19ce0ab 3f865ab4 b3869a95 +3d7160e4 3b77b756 38f072a9 +4033e2a2 c02dcf76 c0e66749 +4109b465 3f8e5c16 41192006 +bdd2b939 3fd83b97 bda8d73c +c1556b0c 3c723b89 b4aa916e +41b29162 3fdb4363 4218f160 +c199cfd0 3b0f33cc af4e5b68 +3aba9fe6 bd89f6e1 b8494bc1 +414ab7aa bf86c0df c155698f +ba3426cb c016b44b 3a54088c +3da6b721 be6d9ae4 bc2107d2 +bff36763 3e326f4f bd305816 +be77d280 b6ccebca 352e7c9a +bd0bfb36 3c1dbe26 b9298f87 +bd6e6e75 4029cdaa bd998c6d +4216decb 3c953430 3f2fdcdb +414ab399 bb084764 bcd7cfb5 +c1e3ef85 bfb33f59 2d945faf +3e59bad0 407063f6 3ee21bbe +3e085167 37b0c315 35c8c2ab +c1252a05 3e04904a b838447a +c0bc0321 bf4b3737 3c55f2de +418bc3a9 4044a734 4256ba2d +419fbe4f bd119e72 bf35bb53 +c0762ffe c07db113 3ea332c8 +bf5a0567 c05ebd4d 3f62f11e +4103cca9 3ea5632e 402a406a +41e73aa6 35b95e14 38276e5c +416d3432 4034e3f6 42279be8 +c00013ce bd0bf250 3c056514 +3e26b471 3deb10b5 3c25813b +c0336d12 bfbb200b 3e6fc895 +3ff3e8e9 b8245783 b8884e5a +4154ac63 beb30dbb c094bfe1 +c2048863 c0718460 2b0f84db +41d44605 c05d34c8 c2b76c36 +3dc02cd4 40455200 3e1b11df +beb50750 bf48c642 3dea452b +bfc6c3cc bfc7cdbe 3ed8c842 +420bb919 3d4779ef 3fd9bedf +41e397b3 3e750290 40d9d276 +3d01bbfc be04ae75 bb089bd7 +3c0005c5 3e159993 3a1635f8 +3f12b3cc c00b3df5 bf4c19fb +c1671ac4 be53f80c 35d60ba0 +c0034f23 bac66f45 39b974b6 +bf93c22f 3a1fd64d b930e734 +c0091399 bb01223d 39e88b90 +ba066044 c01fc0e9 3a27ab19 +c1ff06b7 4042bde5 abc343b5 +41be1b1f 3f6644a5 41aaff58 +40ab8870 3ec5ef64 4004019a +3e0b74c3 3da43297 3bbf0e61 +c0c0e1a4 3f09c23b bbffadb7 +bd09a9ec 3f8e0bf0 bc96342f +b99d69fa 3d79553a b7194a97 +3f885228 be7154cd be3f21b1 +bc90ed3c 40301d5f bcc5a3ec +c198053b 3e7b5054 b2dfe117 +c0da40f3 3f9dd059 bc162ea9 +bc0e14df 3f379d39 bb4aee20 +418b5a8b 3d1ebf9e 3f2cd461 +41197ccc 3ea15ee2 40417d5e +41a11e7c 4030323c 425dc926 +c01cae4f 3e43bfd8 bd18892a +406230aa be2e45ec bf159d2c +4106a669 3d88c236 3f0fd4f6 +400a2a78 bed50f98 bf4e2d6d +c1c4a95c bf5d02ce 2ff5f2d8 +c00e7691 bfe09c7d 3ec2dffb +3dba609d bcbdd04e ba90799b +c1e41b60 bcb3ce83 2a91cafb +b4939b52 4054500f b4f4d591 +3e663422 bcf49017 bb748903 +c1a3298c 405d5bbc b3d249d1 +c1355ca4 bf18b3f7 38a96301 +c039467d 3a6e54aa b910a087 +bf8d4dd4 b76640b5 367d2bba +c2098d5f 4015fdcd a9d2ffb6 +41a9460b bfdbd537 c2115be7 +b94bb151 3d015ed7 b64dda81 +40af2622 bf815e51 c0b04817 +4194496c bf8040bf c194946e +3e3da6ed 3e6aff4c 3cbe2b15 +414be49b 3c99b5f7 3e74d8ec +3ed70020 407313df 3f766452 +3b8cb2f1 ba304907 b5c230d1 +c122d4f4 bb518098 35a613d7 +40a9fed7 3e041dd1 3f2e9a07 +401ba6f4 c047a62e c0df2c45 +c1120859 3d0891df b80ab65b +be88114d 40324a60 bea47da7 +c00f8ee4 3fc53a77 bea9c9bb +c067da62 3d529567 bb9ec61e +3a5b46dd 3f6b8706 39c9d34e +c0b0f835 3ec9d2aa bc0d0cbd +420e6e33 3d541ed1 3fec08cf +412f716f bd810642 bf30d81d +bbb05fc9 403893a5 bbfda5e8 +beba2dbf bf9e6a64 3e3cfb13 +bfc39857 bcc19f78 3bd2fc3f +be432d08 bcce0d65 3b0e2b5a +bfef3416 b9c7d18a 38c7ad95 +42029f4b 3d2df742 3fb1879e +c1080678 3ef6cd79 ba5a3196 +c217b921 bf55986d 26996f09 +4086a265 4015bd2f 411b309f +c1b143ac 3e9cbd3d b0de0a7e +40c44f80 bcd45c73 be227e9d +c1cd2950 3c9f8760 ac8002dc +3fd6c723 c00bb595 c04588e5 +be77d4f1 3da91908 bc0ffd16 +3f6afe09 403ebaea 3ffa3ae0 +3dae434e bf23bd62 bce865ff +40b2c56a be51a1aa bf91d824 +3ef71125 bf19bc5b be377da5 +420dc7b0 bf4b50b0 c1e13411 +c1cd3cf9 bf1e9dc1 2efc385d +beed2ee7 405dd8a9 bf1ec3f2 +c1728957 bf22d845 3628ede1 +41419901 3ea2cdf9 40763cd3 +4197025a 407ce59f 42952dc3 +420aa829 3e165fdc 40a2e4e7 +b91b819a 3f9acda8 b8bc0e35 +4092dad3 c041673e c15ba906 +bf8f3bee bf6cea29 3e82899e +bdde250c c0480831 3e242c70 +c1a323c2 3d62ee3b b0d82986 +40b29b69 bf2b5520 c06e2cb7 +3e6b4705 bf01d7cf bd84fb4d +c1884b56 402a8aa1 b5f32534 +bf4a8aae ba842b24 3982777a +3f139caa 3b371ee3 3a8736ee +be31a77f bd9452ce 3bbc0c81 +bdae9a8d c00628e2 3daf35ad +c0ebb473 3e41dd03 ba671495 +bc1a9ae6 b9f39f68 36126f98 +bd3dadd1 bf1a97e9 3c5fc892 +bf53fa76 3e235aa1 bd248350 +c0d5fe1a 3f48b2a8 bbd5e725 +c13d0177 befbb211 3834735d +3d0e13ea bfb8dce3 bcd0c0c3 +41930d20 bea5fbf9 c0beb065 +c15b5746 c0553f2c 38552889 +41dd5e61 bd6b21a8 bfcb52bd +41407dbc bf4a4f03 c1181e64 +c06c8483 bf1a1809 3d5cc80a +beabc32a befa9dc1 3d8c34ee +4191e3aa bf859355 c1983e7b +bf248400 bb39e384 3a24afd2 +bfa054ad 3dc5f177 bcdc6c19 +c00fc2f1 3f290f3a be11538a +3fe4148f 39b6eb44 3a0b7d88 +bce2ade7 3f8b3006 bc7314ea +bd62a100 3e8e63f1 bbf5228d +3e53aa30 bbcfc19f ba3d7775 +41244655 bc83823c be28c59e +c08cfe21 be017636 3bdc11bb +3f31fd16 c017836b bf8c8e48 +c119f575 40760f86 bb208ecc +3cfc5ab1 c01ccae9 bd1cf0ac +bf35c31c bdb88e68 3cacc1c7 +c15aec53 c06949e4 386ee7ad +c1c565fe bb477f35 2bcb3b1f +41a858a6 4035c6d2 426f12d8 +401ecda1 bbbfc548 bc5b8ec6 +be1e6c40 3ddc02b2 bbfb47c1 +3fd0eb88 3fd9d267 4014b180 +c2102522 bea61d7e 273c74a0 +417e4da9 40757e3e 4273ddb9 +3f8adb2f 3fca3af5 3fa3f797 +c0afd61d 3cac25d7 b9f7a9b1 +3c0949f2 3e17890a 3a23368b +4156e929 be83dd7b c05d6668 +3fcbb839 3fedd57c 401d3f2b +c21146af bfb7cdfa 281e65ac +3b246e10 4023924e 3b526395 +421a76c6 3c6f468e 3f105f75 +3f8ebd5d c0104d64 bff25f7b +c10126c4 bdbf843b 397701f3 +c09748c5 3fdd102c bd92a555 +c148fe93 bd273a7a 35f112c9 +40550bff 3c7562f9 3d45264b +bd9e7148 bd230788 3ac20031 +c207bde7 c000af96 2a0c7379 +bce3d0ea b60b2ea4 32f44626 +3b83194e c005edb7 bb897202 +bfb1229c bde3fe55 3cfce68f +c19a3e68 bf45981c 33874358 +3d8746ab bff76cff bd870fcd +c0861e34 bffdeddd 3dfdc4f7 +40ad3ead 4072f067 41a3ad4d +4108473a bf5a30e5 c0e8417b +4215d181 bd9e1264 c0390422 +404d84eb c0444f27 c1177e21 +3848abe8 b9da1ce9 b22afa19 +41edbbc9 402893d9 429c8c88 +c15f8f62 be77e23a 36420210 +c046d8fd bdeff7c0 3c7f6748 +409cb6bb 3ff342bc 4113cfc5 +c0a68221 3daf4e59 bb1f9b3d +c0a9603f 3d8a8470 baeaafc0 +3eb74052 3bb9038f 3a9be36b +403b98b0 3f2c4367 3fefaf75 +3fa69eb4 bb4ed185 bb53a3c9 +c03ad7dd 3ebfa1fa bd652936 +420b6b46 c0064194 c2923bbb +bf31387a c0754d09 3f628d26 +bef8b407 bdfccc9e 3cbb1758 +41305ed0 4002c22d 41b42b18 +bef30f0e bfae0ec0 3e7d818c +41c8a6af 3bd21e91 3e24b0b1 +c17a51ec 407edd55 b727c279 +c142e0bf bbee2eb5 34f3f5f3 +beaa6409 be223a1d 3cb458d6 +c009dfbd 4029760f bf17c4b3 +413470ef 3fb73ed3 41812898 +c0a56b5c bcd57260 3a47b49d +3e958021 3d0ea31b 3bbebf56 +3e23fdb0 bf40fd15 bd858131 +3e39d2d3 3eddbf05 3d2f8631 +c18f6c88 c0240342 3549dafc +c1ec8fde 4008b1c6 ad1fca4d +bf7cb93f 40794be4 bf859e4b +40b0205b 3eb87aa9 3ffccfd7 +c1cf7df8 be49c69c 2df4bb02 +3fd4d6bf 3d195b10 3d565b5f +3dad381d bd031cbc bab8ee13 +416c5b35 3f10ae27 41059414 +be851841 be3a91fe 3ca8ec2f +bb30ccd5 3d1d3827 b858ddd1 +3ec903f9 3e48945c 3d3c0661 +bb2939c9 3fe35106 bb161223 +beeb8878 ba2bd941 38f4bda2 +4206b3eb bd24b80f bfad5838 +41c50d36 3dd68203 40251d1e +bda6d9b5 3c16b448 b9bc72b1 +c172aa63 bd9b9302 34a02ce5 +bf0d53dc 3ef5aca3 bdc639af +c1f0dd3f 37a68053 a4677b8a +c1517963 bc52f328 34ba8cf0 +3f6c0a83 bce1c7a0 bc94f10c +c215c831 3fbb5c4e a757dc5e +40447eba 3f094051 3fc95a1a +3ff5abc6 3929bed6 398e0e46 +4167a764 3ea8c122 4098b499 +bce227a9 be34df7e 3b1d94bb +c1ddf8c5 bf4e81af 2daf68cf +41ae6dce 3ce0a89e 3f1912f8 +40c292d0 407019a3 41b61283 +3e02d48f 3edf7ee9 3cf302c7 +c217a923 3a0a9107 a14a201a +c08934ac 3e626be1 bc527be4 +c08bdac6 4002016b bde30c1b +bd976cfb be955f6c 3c2a2e1c +c1d798f6 bd8b2b73 2c7eb5ff +bdad872c 3f934b44 bd3f3ae3 +40ca1f86 3fdc3465 412d8c33 +41450527 bf08e47a c0d2b4e8 +bf8a9cf1 bc2d569a 3b3deddf +bf8b7f08 be8321ba 3d8fdab4 +c1d7712e c045814a 2f3826a0 +3e3fcc4b bde73fcc bc3d6ec6 +417116e9 bc82d5a4 be766da6 +40959199 3aeb901a 3c085b00 +421b70c5 bc47b9fa bef28b2b +c0b6c983 406ce9ec bd8eaea3 +3e87f7ff 3e9a602a 3d39a23f +418e4255 bb67d922 bd80d684 +c082c859 bd4f0ccf 3b5f92f1 +41ef5067 3f85138d 41f8ce19 +3e3aa27b bedde53b bd3078fc +be9f9021 3de68986 bc72f654 +bf83fc24 be311f2c 3d4008be +416ddf89 bf8de45a c183d84a +421807a9 bfc0698d c26488db +c1ba4a6e 38906ac2 aa0b2473 +41a7ebbb b49e7fbd b6cfee8f +40c1557f 3f10f9aa 405a7452 +c1836276 40276e7c b6548a2f +c1c375e6 c00fbef1 30b8bde3 +c09bb932 bebdde4e 3c61f742 +c1f1804f bce29404 2991d55c +c0b9fcfc 3fa9fbfd bcbc8f76 +c0f042d8 4004a492 bc0bc97a +3f013832 404fb05b 3f82be81 +bedd71b2 3c05e8fa bab65609 +410cd9d9 3fb7f1f7 414a61ee +40923340 c01d7fc9 c1320c1d +bf4fc48d c01a4a00 3f1a0bcd +c014a7a5 bf99e823 3e7f440b +41912320 406bbc78 4285a618 +c13b0c01 c02138ee 3981494d +c0009f8b 3f050af9 bdfccd5b +be8b931b bf975587 3e0eaa17 +c1ddf905 3fa545f4 ae0c5e67 +c2157f19 392657d9 a0cd6f14 +c0616e2d bfb7ffd2 3e14b7ba +c09d425d 3aedeec6 b888543e +415e1665 bfdaeabc c1bdeaaa +3dbbdeaf 3ff3ba17 3dbb0fa8 +c1f0f311 beb1031b 2b7392d9 +3f66fd96 3c32d7ec 3be59b6e +c02db21f bfdb3438 3e93e719 +40811347 3b8dd98d 3c8c8d5e +c1dc256c bcc9349d 2b54f31f +41e305a8 bfbb35f2 c22604f8 +3f17e0c5 bf1ed58b be72c919 +3a07ff1a 3f117d67 391a9e7c +c033a1aa 3e06a759 bcac38c1 +b59916c8 37a69f1b ad4747ce +410be45f 3be08d8d 3d756055 +410b85f8 beaf86e2 c03f4c32 +bbd71825 3f8ced40 bb6c0a1f +c1323a35 3ec1720e b88040e0 +c19adb32 407cb80f b4a0e291 +3f8ce314 3a9c5ae4 3a8123ab +bfd5ba80 bfa7f7e8 3eb1c461 +c1b0067a be7b216c 30ce39bf +c005451c 3f505f35 be405932 +bf09decf 405a2219 bf2d2c0e +be03cb05 3f1debae bd1826ad +becdfb9a bd488405 3c0150cc +3e436c2d b242068f b0a23420 +c1259af4 bcafc4fd 36ee50c8 +3d3549b8 c05ee8e5 bda158ff +bebd1fc9 3f9cd6ef be3d6a85 +c205e4db be960b65 290030f3 +3e60eb62 4042a65f 3ebdb977 +3dc07ea0 4050ecb8 3e247983 +3f99f70c baa2377b ba960e37 +401a90e3 b0df06e2 b1773943 +4134e36a 3d73f463 3f2c6001 +c12ed1e4 be31b038 380efada +38f88f48 3dfbf68e 36f4a795 +410be805 beb75715 c0485cb9 +c0faae3d 3eb544de ba8ff22c +c1513df9 be1b3ac8 368b2067 +40b87e97 3f742118 40af63ca +bfdf15ad bc8379a8 3b888617 +c114dd16 4002de66 bae30dde +be90b4ab 3daf2ee0 bc2a3eb0 +3c6e8809 3b266295 379c28f8 +41d6401c bfdbfb07 c2381aef +bd180720 bc62731f 3983fbd6 +c02cdefe c03de017 3f010e28 +c08e58f1 3e1c5778 bc00a932 +c02a3510 3f3a893a be01ca54 +c11af71b 3b9d57a0 b642142a +414ada11 bfe0bccc c1b21445 +bfcdae0a bebb57b6 3dc91eae +bda033e0 c06d9248 3e0edbbe +c00f24b7 bf497f48 3e2dfa4d +c210cce8 bf81b768 27fafae7 +41bd5474 3f77fdc8 41b7682c +3ca98e40 c0389d56 bcf714c4 +3d723119 401bf3ae 3d97e699 +c013a0f3 4005103f bede64cd +4088baca 3f32b0c4 403c40a3 +41c1fa56 3fc5660c 421592f7 +bda4c770 bebaf550 3c670046 +3f4d4f8d 3ea4ddc9 3e36928b +409f8b93 c05a9d45 c187521d +4096e995 3d603e3d 3e8304db +405b2d64 40574e04 413285d4 +419e23a9 bfc948a9 c1f8adc4 +416d4ef1 3fb44947 41a71f6b +c0393038 bd4d4e67 3bf9609e +3e58aab5 400c03f5 3e82fe3c +406da268 40068398 40f3c761 +c027ce85 3eb10fcc bd7b93b7 +c17aa683 c0383c70 36ede54f +bf83d888 bf7bdf3d 3e88811b +40a57e8f 400d745c 4135dba8 +be977cbe befa43b5 3d7cafc3 +c0d96c49 3eb0b850 bb2bef6a +3b1f27f5 3fdae753 3b084226 +c05b53d7 bfbdd741 3e23c065 +bf98afa9 bfcc6ba5 3ee30481 +bfe8ecf6 bbd03d1e 3ad36577 +c1140670 bfb143a3 3aa1226a +c1063bfc be9728b3 3a137e4c +bdac6640 3d9151bf bb3b7e3d +c0881b42 404a04f4 be40b6e8 +3c0566e5 c026050a bc2dbb05 +41903e4b 3cb47c5e 3ecb63c0 +41622c5b bf0cbef3 c0f8b1df +40be1cfb 3d6979c6 3eacee69 +bf4991fb bcd280f9 3bcf5649 +c1f380c0 3d6c1aaf a9ee9c6b +bf6b9b06 3fd6bfcc bee13942 +c1664c3e bde25dce 356f90cc +c0df8b4b 3f3fcf69 bb9e7f0f +3d707844 3f8ce122 3d083766 +b983b966 403ac191 b9c02a6c +4202c892 401591ef 4298d295 +418513c0 bfbe3163 c1c5bca8 +c1391ffe c011b7bd 398269c1 +c20656ce c029a975 2a821e1f +c1ea711a c00460e7 2d47e574 +c202825f c010c06d 2b0c79d1 +412b9a1e 3e888c3e 40370ebc +41214540 be9a8218 c042a923 +c21559f3 bc189fe1 23c343e9 +c084ed4d 3ef75aae bcfe2686 +3faffc4a c0508114 c064cf8b +41e2c284 4034139f 429f8226 +408f6630 402c3222 413ec0b7 +bd298691 becb006c 3c03a5ed +c1e06187 bfa71396 2dd44e98 +40e39ca1 3eb7bc3f 40233a4c +c19ef871 4000cf5a b3c9568a +bf20b96f 3f163a05 be034a3a +41e1fe38 3c4d0da5 3eb5049e +411dd6fb 3f67bd33 410edfbd +c139a958 4059c942 b9bd07ea +bfe4909f 3a5a8af9 b9602a10 +3987cefc 3f3584e2 38c09e0f +bdaf5f94 403d523f bdf84a6c +beea566e bed01f52 3d93a8be +40b8e709 c04a7399 c191c652 +40797f03 be9d3e2e bf9633e4 +419855e0 3f581b93 418098de +bc8fe0cd 3bc9c819 b860d20c +3fe41910 be42875b be945bab +40dc121b bc6ee037 bdcd236f +41a88b4a c005a2b5 c22ff6fa +c21c668f bcb4240c 2325b4cc +3fd3d1ec 3db055d4 3df4fc3b +40a70ca7 bf09232f c032031d +bf49d03f 3f8f2996 be8d1634 +41a2bffe 3e08f8a1 402e281f +419e2944 c053e35f c282e87c +c1cac24a 3fba782e afc7ac88 +c207a413 bc8fb6eb 26a0bda2 +c0a0249f 400074cc bd891234 +42181bdc 3ca2e447 3f419288 +c1989d32 34a5ff5f a909d652 +c165f4a8 bfa16492 372e3c67 +c1be9879 bc524d82 2d7211e3 +41b52e43 3dcbf6ea 40105a6f +417ea0d0 3a783c39 3c76e7ae +c0b66d72 bfd427b1 3d00f4c9 +c17e53e0 3f8bc9b2 b6118b50 +c1d31103 c0449be3 2f9b2a9e +c1c8edb4 3e4010f8 ae801ab4 +bf643144 becafade 3dd27a73 +c01d0990 bcc0f2f2 3b95ecc9 +bfe692a1 ba6407cc 3968cc73 +41cf5144 3db5b72c 401328cc +412b3b68 40573c09 420ff638 +3dd59668 bf888fef bd6fbf2e +421fba46 3709e44b 39ac1240 +bf3c85f0 bc829ef4 3b792a60 +c11cec4e 4049dab0 badf179b +4136bfa1 bebfe50d c088fc1a +bfa7418d 4051e44a bf69b7bd +c0c62230 3fc356b2 bc9e14a8 +c1569e81 bda60ede 35da2b46 +c18bfb06 ba99d61f 300e1779 +bf2566f8 3f53715a be3be895 diff --git a/tests/kernels/test_basalt_cpu_expf.py b/tests/kernels/test_basalt_cpu_expf.py new file mode 100644 index 00000000..cc2910da --- /dev/null +++ b/tests/kernels/test_basalt_cpu_expf.py @@ -0,0 +1,407 @@ +# SPDX-License-Identifier: MIT +# Copyright (c) 2026 Jesús Gulfo +# adapted from basalt (jesdga95/basalt) src/kernels/cpu/pool.cpp:434 @ b4c63b55754637f4c72ad53a0f791d425f71eb36 +# (MIT; third_party/NOTICE): the CPU expert pool's SwiGLU and its order of operations. +"""``expf_glibc`` and the SwiGLU of ``runtime/src/basalt_cpu_expf.cpp``, the one piece of arithmetic basalt's CPU +expert pool performs itself. + +**What the bits are held against.** The function must return glibc's bits, because basalt runs on Linux +with glibc and a token's output has to be the same number whichever tier produced it. Group A is the acceptance +oracle and it is exhaustive: A1 the six values read straight out of a running glibc, and A2 the 4,226 recorded +(g, u, res) triples of basalt's own line; B4 carries the rest, glibc's ``expf`` at every one of the 4,294,967,296 +float32 arguments as 4,096 block digests. No value ``expf_glibc`` returns, and no SwiGLU result at a recorded +argument pair, can be wrong without showing up in one of them (``docs/research/basalt-cpu-expf.md``, +``tests/kernels/fixtures/``). + +One rule sits outside that: SSE takes the FIRST source operand that is a NaN, where an AArch64 instruction +prefers a signalling NaN wherever it sits. The two part only when `src1` is a quiet NaN and `src2` a signalling +one, and no recorded row has that pair, so D3 asserts it against the manual rather than against a measurement. + +The other cases say what each part of the result is, which a digest cannot: group B holds the transcription to +the 0.502 ulp Arm records for this algorithm, against a float64 reference, over the SwiGLU's reachable range, and +names the two arguments at which glibc's own two x86-64 variants part; group C pins the specials and the three +thresholds against that same reference; group D pins the SwiGLU's order of operations and the NaN each of its +three instructions writes. + +The float64 reference is ``np.exp`` in double, which carries 29 bits more than the float32 result and is itself +accurate to well under 2^-29 of a float32 ulp. Its own error is therefore invisible at the 10^-3 ulp the group B +assertions turn on. Where a case asserts the *correctly rounded* value it is written ``np.float32(np.exp(x64))``: +one rounding, from the double to the float. + +Cases. **A**, the recorded x86 bits: A1 the six ``expf`` values, A2 the 4,226 SwiGLU vectors. **B**, the error +bound and the exhaustive sweep: B1 a stratified sample of [-40, 40] - the SwiGLU's reachable range, with most of +its mass near zero - B2 the measured worst case and the window around it, B3 the two arguments the rounding +step's fusion moves, and B4 all 4,096 block digests. **C**, the specials: C1 both zeros, C2 both infinities, +C3 NaN (quiet and signalling), C4 the overflow threshold and the largest argument with a finite result, C5 the +two underflow thresholds and the ``may_uflow`` band, C6 the subnormal results. **D**, the SwiGLU: D1 its order +against basalt's expression, D2 that the order is load-bearing, D3 the NaN rule at each instruction. + +The suite bites, measured by mutating the kernel and rebuilding: ``poly`` in place of ``poly_scaled`` fails A1, +A2, B1, B2, B3, B4, C4 and C6; the platform's ``expf`` fails A2, B1, B2, B3, B4 and C6 - it exceeds the 0.502 ulp +this algorithm holds to, and differs from the transcription at 1,930,129 of the 2,218,786,818 float32 arguments in +[-40, 40] (measured here against this machine's own libm, so the count is a property of Apple's ``expf`` and moves +with macOS), though not at any of the recorded six, so A1 alone would miss it; the rounding step written as +``z + SHIFT`` and ``z - kd`` instead of the two ``fma()`` calls fails A2, B3 and B4, and B4 at exactly the two +blocks the fixture's trailer records ``__expf_sse2`` digests for, 0x420 and 0xc27, with those digests exactly - the +unfused build is ``__expf_sse2`` over those 2,097,152 arguments; and the SwiGLU as ``g * (1 / (1 + e)) * u`` +fails D1. + +The three x86 NaN rules are not alike there. Dropping the divide's for the C operator fails A2, D1 and D3; +dropping the multiply's fails A2 and D3, on the four recorded rows where the multiply itself creates the NaN from +``0 * inf`` and the C operator writes AArch64's sign (rows 122, 123, 126 and 127), not on the row with a NaN on +both sides, where this machine's own operand order happens to give x86's answer anyway. Dropping the add's fails +nothing: ``1.f`` is never a NaN, and the only other source is ``expf``'s own return, which is never negative and +quiets the same way on both architectures, so neither the add's source order nor its created NaN is reachable. It +is written as the add anyway, because the transcription is of what basalt executes and not of what a test can +catch. + +Two mutations fail nothing, and both are findings rather than gaps. ``round``/``lround`` for the rounding - Arm's +other branch, the one glibc compiles on aarch64 - passes, because no float32 argument makes ``InvLn2N * x`` an +exact tie (swept here over all 2^32), so the two branches are the same function. Dropping the +``WANT_ERRNO_UFLOW`` band passes, because the main path computes 0x00000001 across the whole band anyway (C5 +asserts exactly that); the band is transcribed because glibc has it, and ``errno``, which nothing here reads, is +the only thing it changes. + +Run with ``-s`` for the measured worst ulp and its argument. +""" + +from pathlib import Path + +import numpy as np +import pytest + +from monolith.runtime import _native as _nt + +F32, U32 = np.float32, np.uint32 + +FIXTURES = Path(__file__).parent / "fixtures" # the recorded x86 corpus, docs/research/basalt-cpu-expf.md + +# Read out of a running glibc 2.39 on a Xeon Platinum 8375C, with the ifunc dispatch intact and again with +# GLIBC_TUNABLES disabling AVX2 and FMA (docs/research/basalt-cpu-expf.md section 1). The two variants agree on +# these six, which is why no variant is named here; B4's digests carry the arguments where they do not. +GLIBC_SIX = ( + (0x3F000000, 0x3FD3094C), # 0.5 + (0xBF800000, 0x3EBC5AB2), # -1 + (0x3A83126F, 0x3F8020C9), # 0.001 + (0xC2AF0000, 0x006CB2BC), # -87.5, a subnormal result + (0x42B10000, 0x7F4CDCC4), # 88.5, near overflow + (0xC2C80000, 0x0000001B), # -100, a tiny subnormal +) + +# the thresholds expf.c branches on, as float32 bit patterns (runtime/src/basalt_cpu_expf.cpp) +OFLOW = 0x42B17217 # 0x1.62e42ep6f, log(0x1p128); x above it takes the overflow return +UFLOW = 0xC2CFF1B4 # -0x1.9fe368p6f, log(0x1p-150); x below it takes the underflow return +MAY_UFLOW = 0xC2CE8ECF # -0x1.9d1d9ep6f, log(0x1p-149); x below it returns (0x1.4p-75f)^2 + + +def f32(bits): + """The float32 array of these bit patterns. Bits in, bits out: nothing converts through a double, so a + signalling NaN reaches the kernel as one.""" + return np.asarray(bits, dtype=U32).view(F32) + + +def bits_of(x): + return np.asarray(x, dtype=F32).view(U32) + + +def expf(x): + out = np.empty_like(np.asarray(x, dtype=F32)) + _nt.basalt_expf(np.asarray(x, dtype=F32), out) + return out + + +def swiglu(g, u): + g, u = np.asarray(g, dtype=F32), np.asarray(u, dtype=F32) + out = np.empty_like(g) + _nt.basalt_swiglu(g, u, out) + return out + + +def _recorded(name, ncols): + """The hex columns of a fixture, as uint32 arrays. Comment and short lines are skipped, which drops the + trailing __expf_sse2 block of expf_digests.txt with them.""" + cols = [[] for _ in range(ncols)] + for line in (FIXTURES / name).read_text().splitlines(): + parts = line.split() + if line.startswith("#") or len(parts) != ncols: + continue + for c, part in zip(cols, parts): + c.append(int(part, 16)) + assert cols[0], f"{name} holds no {ncols}-column rows" + return [np.array(c, dtype=np.uint64 if max(c) > 0xFFFFFFFF else U32) for c in cols] + + +def ulp_error(x): + """|expf(x) - exp(x)| in units of the float32 ulp at the exact value, which is 2^-149 below 2^-126.""" + ref = np.exp(np.asarray(x, dtype=F32).astype(np.float64)) + exponent = np.maximum(np.floor(np.log2(np.abs(ref))), -126.0) + ulp = np.ldexp(1.0, (exponent - 23).astype(np.int64)) + return np.abs(expf(x).astype(np.float64) - ref) / ulp + + +def correctly_rounded(x): + """exp(x) in double, rounded once to float32 - the value an infinitely precise expf would return. The cast is + allowed to overflow to +inf and to flush to zero: those are the right answers at the two ends.""" + with np.errstate(over="ignore", under="ignore"): + return np.exp(np.asarray(x, dtype=F32).astype(np.float64)).astype(F32) + + +# ---- A: the recorded x86 bits ------------------------------------------------------------------------------------ + +def test_a1_recorded_glibc_values(): + """A1. Six values read straight out of a running glibc 2.39, bit for bit - the only ones in this suite that + came from a call rather than from a recorded sweep, and the case that says the sweep's own harness was + measuring the same function.""" + arg, want = zip(*GLIBC_SIX) + got = bits_of(expf(f32(arg))) + for a, w, g in zip(arg, want, got): + assert g == w, f"expf({a:#010x}) = {g:#010x}, glibc 2.39 gives {w:#010x}" + + +def test_a2_recorded_swiglu_vectors(): + """A2. basalt's own line, recorded: 4,226 (g, u, res) triples from pool.cpp:425-434 compiled as basalt compiles + it (x86-64 gcc 14.3, -std=c++20 -O3 -DNDEBUG, no -m flags) and run on a Xeon 8375C and a Xeon 8488C under + glibc 2.39-0ubuntu8.9, six runs agreeing. 57 special g against two u, 16 special-u pairs, and 4,096 random + pairs with |g| < 40. This is the case that pins the whole expression - the variant of expf, the order gcc + emits, and the NaN each instruction writes - rather than any part of it.""" + g_bits, u_bits, want = _recorded("swiglu_vectors.txt", 3) + assert len(want) == 4226, f"expected 4,226 recorded vectors, read {len(want)}" + got = bits_of(swiglu(f32(g_bits), f32(u_bits))) + bad = np.nonzero(got != want)[0] + assert len(bad) == 0, (f"{len(bad)} of {len(want)} rows differ, first at row {bad[0]}: " + f"g={g_bits[bad[0]]:#010x} u={u_bits[bad[0]]:#010x} " + f"{got[bad[0]]:#010x} against the recorded {want[bad[0]]:#010x}") + + +# ---- B: the error bound against a float64 reference -------------------------------------------------------------- + +def test_b1_ulp_bound_over_the_reachable_range(capsys): + """B1. Arm records this algorithm's worst case as 0.502 ulp under round to nearest, and the transcription has + to stay inside that. The sample is the SwiGLU's reachable range: uniform over [-40, 40], a normal sample with + most of its mass near zero, the exact zero neighbourhood, and the whole underflow region, where the result is + subnormal and the ulp is 2^-149.""" + rng = np.random.default_rng(20261018) + sample = np.concatenate([ + rng.uniform(-40.0, 40.0, 1 << 20).astype(F32), # the range, flat + rng.normal(0.0, 2.0, 1 << 20).astype(F32), # where the mass is + rng.normal(0.0, 0.01, 1 << 16).astype(F32), # and nearer still + f32(np.arange(0xC2AE0000, 0xC2D10000, dtype=U32)), # -87 .. -104.5, subnormal results + f32(np.arange(0x42B00000, OFLOW + 1, dtype=U32)), # 88 .. 88.72, up to the threshold + ]) + err = ulp_error(sample) + worst = int(np.argmax(err)) + with capsys.disabled(): + print(f"\n B1: {sample.size} arguments, worst {err[worst]:.6f} ulp at " + f"{bits_of(sample)[worst]:#010x} ({float(sample[worst])!r})") + assert err.max() <= 0.502, f"worst {err.max():.6f} ulp at {bits_of(sample)[worst]:#010x}" + + +def test_b2_the_measured_worst_case(): + """B2. The worst argument of an exhaustive sweep of every float32 whose result is finite and nonzero (measured + here, 4,294,967,296 inputs): 0.501637 ulp, above a half and so not the correctly rounded value, which is what + "not correctly rounded" means for this algorithm. The window around it is swept here so a transcription that + drifts has to beat the bound somewhere in the neighbourhood too.""" + x = f32([0xBBE7328F]) + assert bits_of(expf(x))[0] == 0x3F7E333C + assert bits_of(correctly_rounded(x))[0] == 0x3F7E333B, "the correctly rounded value is one ulp below" + assert 0.5 < ulp_error(x)[0] <= 0.502 + window = f32(np.arange(0xBBE70000, 0xBBE80000, dtype=U32)) + assert ulp_error(window).max() <= 0.502 + + +def test_b3_the_two_arguments_contraction_would_move(): + """B3. The two arguments where glibc's own variants disagree, and the only place the rounding step's fusion is + visible: it changes the result at exactly two of the 4,294,967,296 float32 inputs (measured here, both orders + swept). glibc's x86-64 ifunc picks __expf_fma on any host with FMA and AVX2, so these are basalt's bits, and + the port writes those two mul-adds as explicit fma() to hold them whatever -ffp-contract says. Measured on a + Xeon 8375C under glibc 2.39-0ubuntu8.9: __expf_fma gives these, __expf_sse2 gives 0x56FC9F1B and 0x11FA2992, + which are the correctly rounded ones. basalt runs the fused variant, so the port is wrong when it agrees with + the correctly rounded answer here.""" + assert list(bits_of(expf(f32([0x4202422F, 0xC27C65D9])))) == [0x56FC9F1C, 0x11FA2993] + + +def test_b4_every_block_of_the_recorded_sweep(): + """B4. glibc's own output at every one of the 4,294,967,296 float32 arguments, as 4,096 digests over blocks of + 2^20, measured on a Xeon 8375C and a Xeon 8488C under glibc 2.39-0ubuntu8.9 with the ifunc resolving to + __expf_fma. Block k covers bit patterns k << 20 .. (k << 20) | 0xfffff in order; the digest is the FNV-1a of + the result bits, h = 0xcbf29ce484222325 then h = (h ^ bits) * 0x100000001b3 mod 2^64 per argument, which + ``_native.basalt_expf_digest`` computes. This is what closes the gap A1's six values leave: nothing about the + transcription can be wrong anywhere without showing up in a block. + + The trailer of the fixture carries the two blocks __expf_sse2 digests differently, 0x420 and 0xc27, which hold + the two arguments of B3; those are the blocks the unfused rounding step fails.""" + block, first, last, want = _recorded("expf_digests.txt", 4) + assert len(want) == 4096, f"expected 4,096 block digests, read {len(want)}" + # the fixture's own shape, so a duplicated or reordered row cannot stand in for the block it is missing, and + # the block-to-bit-pattern mapping this case relies on is the one the fixture recorded + assert np.array_equal(block, np.arange(4096, dtype=U32)) + starts = block.astype(np.uint64) << np.uint64(20) + assert np.array_equal(first.astype(np.uint64), starts) + assert np.array_equal(last.astype(np.uint64), starts + 0xFFFFF) + bad = [(int(k), int(w)) for k, w in zip(block, want) + if _nt.basalt_expf_digest(int(k) << 20, 1 << 20) != int(w)] + assert not bad, (f"{len(bad)} of 4,096 blocks differ, first block {bad[0][0]:#x} " + f"({_nt.basalt_expf_digest(bad[0][0] << 20, 1 << 20):#018x} " + f"against the recorded {bad[0][1]:#018x})") + + +# ---- C: the specials --------------------------------------------------------------------------------------------- + +def test_c1_zeros(): + """C1. Both zeros take the main path and give exactly 1.""" + assert list(bits_of(expf(f32([0x00000000, 0x80000000])))) == [0x3F800000, 0x3F800000] + + +def test_c2_infinities(): + """C2. +inf passes through `x + x`; -inf is the one early return expf.c makes by bit pattern, before the NaN + test, and gives +0 rather than an underflow.""" + assert list(bits_of(expf(f32([0x7F800000, 0xFF800000])))) == [0x7F800000, 0x00000000] + + +def test_c3_nan(): + """C3. A NaN reaches `x + x`, which quiets a signalling NaN and leaves a quiet one alone, payload included. + B4's blocks 0x7f8-0x7ff and 0xff8-0xfff are glibc's own output at all 16,777,214 NaN arguments, so the bits + are pinned there; this case names the rule they follow.""" + got = bits_of(expf(f32([0x7FC00001, 0xFFC00001, 0x7F800001]))) + assert list(got) == [0x7FC00001, 0xFFC00001, 0x7FC00001] + + +def test_c4_overflow_boundary(): + """C4. The literal `0x1.62e42ep6f` is itself the largest argument with a finite result, and the next float up + takes the overflow return. Both sides agree with the reference: above the literal the true value is past + FLT_MAX, which rounds to +inf.""" + assert OFLOW == bits_of(F32(float.fromhex("0x1.62e42ep6"))) + assert bits_of(expf(f32([OFLOW])))[0] == 0x7F7FFF84 # finite, just under FLT_MAX + assert bits_of(correctly_rounded(f32([OFLOW])))[0] == 0x7F7FFF84 + assert bits_of(expf(f32([OFLOW + 1])))[0] == 0x7F800000 # the overflow return + assert np.isinf(correctly_rounded(f32([OFLOW + 1])))[0] + assert bits_of(expf(f32([0x7F7FFFFF])))[0] == 0x7F800000 # the largest finite float + + +def test_c5_underflow_boundaries_and_the_band(): + """C5. The two underflow thresholds. `x < -0x1.9fe368p6f` returns (0x1p-95f)^2 = +0; the band above it, + `x < -0x1.9d1d9ep6f`, returns (0x1.4p-75f)^2 = 0x00000001, which is WANT_ERRNO_UFLOW - a glibc choice Arm's own + default build leaves off. Both agree with the correctly rounded value across the band, which is why the + constant is allowed to stand in for the computation.""" + assert UFLOW == bits_of(F32(-float.fromhex("0x1.9fe368p6"))) + assert MAY_UFLOW == bits_of(F32(-float.fromhex("0x1.9d1d9ep6"))) + assert bits_of(expf(f32([UFLOW])))[0] == 0x00000001 # the comparison is strict: this one computes + assert bits_of(expf(f32([UFLOW + 1])))[0] == 0x00000000 # and one float further down underflows + band = f32(np.arange(MAY_UFLOW, UFLOW + 1, dtype=U32)) # the whole may_uflow band, 90,854 arguments + assert (bits_of(expf(band)) == 0x00000001).all() + assert (bits_of(expf(band)) == bits_of(correctly_rounded(band))).all() + below = f32(np.arange(UFLOW + 1, UFLOW + 0x4000, dtype=U32)) + assert (bits_of(expf(below)) == 0).all() and (bits_of(correctly_rounded(below)) == 0).all() + + +def test_c6_subnormal_results(): + """C6. Every argument whose result is subnormal: from -87.3365478515625, the first whose result falls below + 2^-126, to the underflow threshold, the last with a result above zero - 2,180,453 of them, swept. The bound + holds there too, where the ulp is 2^-149 and the double has 20-odd bits rounded away rather than one.""" + x = f32(np.arange(0xC2AE8000, UFLOW + 1, dtype=U32)) + out = bits_of(expf(x)) + assert (out > 0).all(), "nothing underflows to zero above the threshold" + first = int(np.argmax(out < 0x00800000)) + assert bits_of(x)[first] == 0xC2AEAC50 and out[first] == 0x007FFFE6 + assert (out[first:] < 0x00800000).all(), "the results are monotone: subnormal from there down" + assert ulp_error(x[first:]).max() <= 0.502 + + +# ---- D: the SwiGLU ----------------------------------------------------------------------------------------------- + +def _swiglu_sample(): + rng = np.random.default_rng(1434) + g = np.concatenate([ + rng.uniform(-40.0, 40.0, 1 << 18).astype(F32), + rng.normal(0.0, 2.0, 1 << 18).astype(F32), + f32([0x00000000, 0x80000000, 0x7F800000, 0xFF800000, 0x7FC00001, OFLOW, UFLOW, MAY_UFLOW]), + ]) + u = np.concatenate([ + rng.normal(0.0, 1.0, 1 << 19).astype(F32), + f32([0x3F800000, 0x80000000, 0x7F800000, 0xFF800000, 0x7FC00002, 0x00000001, 0x7F7FFFFF, 0x00000000]), + ]) + return g, u + + +def test_d1_swiglu_is_basalts_expression(): + """D1. `(g / (1.f + std::exp(-g))) * u` (pool.cpp:434): the add, then the divide, then the multiply, each in + float32. The order is part of the result, so the check is bitwise against that expression and nothing looser. + Where the expression creates a NaN the two sides hold different bits by construction, numpy writing the + AArch64 default NaN and the kernel x86's indefinite; those rows are A2's and D3's, and are excluded here so + that this case says one thing.""" + g, u = _swiglu_sample() + with np.errstate(invalid="ignore"): # -inf / inf is a NaN on both sides, not an error + want = (g / (F32(1.0) + expf(-g))) * u + got = swiglu(g, u) + created_nan = np.isnan(want) & ~np.isnan(g) & ~np.isnan(u) + bad = np.flatnonzero((bits_of(got) != bits_of(want)) & ~created_nan) + assert bad.size == 0, (f"{bad.size} of {g.size} differ, first at g={bits_of(g)[bad[0]]:#010x} " + f"u={bits_of(u)[bad[0]]:#010x}: {bits_of(got)[bad[0]]:#010x} vs " + f"{bits_of(want)[bad[0]]:#010x}") + assert (bits_of(got)[created_nan] == 0xFFC00000).all() # and those rows are x86's indefinite, every one + + +def test_d2_the_order_is_load_bearing(): + """D2. The witness for D1: the same algebra with the reciprocal taken first, which is what a port reaching for + a sigmoid would write, differs on this sample. Without this, D1 would pass for a reordered kernel.""" + g, u = _swiglu_sample() + with np.errstate(invalid="ignore"): + reciprocal_first = (g * (F32(1.0) / (F32(1.0) + expf(-g)))) * u + assert (bits_of(swiglu(g, u)) != bits_of(reciprocal_first)).any() + + +def test_d3_swiglu_specials(): + """D3. The specials basalt's expression itself produces, as bits. An operation that creates a NaN writes x86's + floating-point indefinite 0xffc00000, where an AArch64 instruction writes 0x7fc00000; a NaN that arrives as an + operand comes back quieted with its payload, from whichever source of the instruction is the first NaN, which + is `g` at the divide and the quotient at the multiply. A2's recorded vectors carry every rule this case names, + though not every row: the last two rows below are not among them, and the last is the one place this suite + asserts against the manual rather than against a measurement.""" + g = f32([0x7F800000, 0xFF800000, 0x00000000, 0x80000000, 0x7F812345, 0x3F800000, 0x7F812345, 0x00000000, + 0x7FC12345]) + u = f32([0x3F800000, 0x3F800000, 0x3F800000, 0x3F800000, 0x3F800000, 0x7F812345, 0x7FC54321, 0x7F800000, + 0x7FA54321]) + got = bits_of(swiglu(g, u)) + assert got[0] == 0x7F800000 # inf / (1 + 0) * 1 + assert got[1] == 0xFFC00000 # -inf / inf, an indefinite the divide creates + assert got[2] == 0x00000000 and got[3] == 0x80000000 # +-0 keep their sign + assert got[4] == 0x7FC12345 # a NaN g, quieted, through both instructions + assert got[5] == 0x7FC12345 # a NaN u, the multiply's SRC1 being finite + assert got[6] == 0x7FC12345 # both NaN: the multiply keeps the quotient's + assert got[7] == 0xFFC00000 # 0 * inf, an indefinite the multiply creates + # The one assertion with no measurement behind it [S, Intel SDM Vol. 1 4.8.3.7 against Arm ARM A1.5.3]: the + # quotient is a quiet NaN and `u` a signalling one, so SSE returns the first source, 0x7fc12345, where an + # AArch64 multiply would prefer the signalling second and give 0x7fe54321. No recorded row holds this pair. + assert got[8] == 0x7FC12345 + + +# ---- the binding's own checks ------------------------------------------------------------------------------------ + +def test_binding_refuses_mismatched_lengths_and_dtypes(): + x = np.zeros(8, F32) + with pytest.raises(ValueError, match="as many floats"): + _nt.basalt_expf(x, np.zeros(7, F32)) + with pytest.raises(ValueError, match="same number of floats"): + _nt.basalt_swiglu(x, x, np.zeros(9, F32)) + with pytest.raises(TypeError): + _nt.basalt_expf(np.zeros(8, np.float64), np.zeros(8, np.float64)) + with pytest.raises(TypeError): + _nt.basalt_expf(np.zeros((2, 4), F32), np.zeros((2, 4), F32)) + with pytest.raises(TypeError): + _nt.basalt_expf(np.zeros(16, F32)[::2], np.zeros(8, F32)) # not contiguous + a = np.arange(9, dtype=F32) + with pytest.raises(ValueError, match="partly overlap"): + _nt.basalt_expf(a[:8], a[1:]) # a shifted view of the same buffer + with pytest.raises(ValueError, match="partly overlap"): + _nt.basalt_swiglu(a[:8], np.zeros(8, F32), a[1:]) + with pytest.raises(ValueError, match="partly overlap"): + _nt.basalt_swiglu(np.zeros(8, F32), a[:8], a[1:]) + b = f32([0x3F000000] * 4) # out being x itself is well defined + _nt.basalt_expf(b, b) + assert list(bits_of(b)) == [0x3FD3094C] * 4 + with pytest.raises(ValueError, match="past 2\\^32"): + _nt.basalt_expf_digest(0xFFFFFFFF, 2) # a range that would wrap + # the top of the range is accepted and digests 0xFFFFFFFF itself rather than wrapping to 0: that pattern is a + # quiet NaN, which `x + x` returns unchanged, so the digest is one FNV step over its own bits + assert _nt.basalt_expf_digest(0xFFFFFFFF, 1) == (0xCBF29CE484222325 ^ 0xFFFFFFFF) * 0x100000001B3 % (1 << 64) + assert _nt.basalt_expf_digest(0, 0) == 0xCBF29CE484222325 # the empty digest is the seed diff --git a/tests/kernels/test_basalt_cpu_q2.py b/tests/kernels/test_basalt_cpu_q2.py new file mode 100644 index 00000000..eae4ee1a --- /dev/null +++ b/tests/kernels/test_basalt_cpu_q2.py @@ -0,0 +1,924 @@ +# SPDX-License-Identifier: MIT +# Copyright (c) 2026 Jesús Gulfo +# adapted from basalt (jesdga95/basalt) src/kernels/cpu/expert.cpp:143-148, :336-370, :503-556 and +# src/kernels/cpu/expert_multi_test.cpp:56-72 @ b4c63b55754637f4c72ad53a0f791d425f71eb36 (MIT; third_party/NOTICE): +# the two kernels' operation order and its per-token independence check. +"""basalt's two CPU Q2_0 kernels on ARM NEON (runtime/src/basalt_cpu.cpp), against the numpy emulation of the +AVX-512 semantics they transcribe (tests/kernels/basalt_cpu_emu.py) and, for the row dot, against an independent +float64 reference. + +Comparison policy, the same everywhere: **all 32 bits**, NaN payloads included. Nothing is compared loosely. The +kernel reproduces x86's NaN bits as well as its numbers (runtime/src/basalt_cpu.cpp, THE NaN PATH) and the +reference models x86's rule at every site, so a NaN payload is as much a result as any other. Where a case pins a +value rather than a match - the all-zero chunk's ``+0.0``, the band's -127 codes, the untouched output rows - the +test asserts that value directly, because the kernel and the emulator share one reading of the specification and a +case that drifts into a harmless regime would otherwise still pass. + +Group C is the answer to "both sides could be wrong together": golden constants recorded from basalt's own kernels +running on an AVX-512 machine (a Xeon Platinum 8488C, GCC 14.3, basalt's Release flags), which depend on neither +the port nor the numpy reference. They are cited as ``pr21-x86-ground-truth.md:``, the PR #21 reviewer's +measurement at ``.context/basalt-port/pr21-ground-truth/`` beside basalt's checkout. C5's are that measurement's +per-site rows composed through its lane model ``mo::row``, which matched basalt's kernel there bit for bit. + +Two values are compiler-dependent, and both are pinned here rather than hidden. ``amax`` when a chunk holds a NaN: +``_mm512_reduce_max_ps`` is header-defined, and GCC's first two levels pass the high half to MAXPS as SRC1 where +Clang's pass the low half - case A6 asserts GCC's at the positions where the two differ and prints Clang's beside +it. And a NaN ``res[t]`` of a row a NaN ENTERS: x86's own answer there moves with the token slot, the token count +and the GCC version, so the port pins GCC 14.3's one-token order for every slot, which case C3 asserts against the +recorded nt = 1 column. + +Cases (the plan's section 7). A, ``act_quant_q8_1``: A1 the two caller widths, A2 an all-zero chunk, A3 +-0 and the +maximum planted in each of the 32 positions, A4 the scale band's four regimes, A5 +-inf, A6 the NaN sweep over both +reduction orders, A7 the half-away-from-zero rounding and the ``0.49999997f`` tie, A8 the saturation trap, A9 the +contraction trap, A10 the reciprocal's witness, A11 the non-finite chunks' exact outputs. B, +``q2_0_gguf_rows_multi``: B1 both pack shapes, B2 nt = 1..8 token independence, B3 the row ranges and the +absolute-index write, B4 stride padding, B5 the unread tail, B6 all 65,536 fp16 block scales, B7 adversarial +activations, B8 the independent float64 check, B9 determinism. C, the recorded x86 values: C1 the five end-to-end +fixtures, C2 the quantizer's own outputs, C3 the nine site probes, C4 the per-site NaN tables, C5 those tables' rows +through the kernel - signaling NaNs in scale and hx, the NaNs sites 1 and 2 create, the acc tree's last three +levels. + +Fixtures are the repository's: ``random_rows`` (test_basalt_experts, basalt's own Q2_0 row fixture - random code +bytes with a finite fp16 scale per block) for the bitwise cases, and ``quantize_q2_0`` (test_basalt_iq_parity, +tools/gguf_writer.py's quantizer) for B8, which needs rows that mean something. + +The suite bites, checked by mutating the kernel, with the same failures at -O0 and at the Release flags: the +saturating FCVTZS in place of the integer indefinite fails A4, A5, A6, A8, A11 and C2's c3, d1, d2 and e64; +Clang's operand order in ``reduce_max_ps`` fails A6, A11 and C2's d1 and d2; ``inv = 127.f / amax`` in place of +basalt's ``1.f / s`` fails A10 alone; a reversed code shift in both of the kernel's decodes (the vector unpack and +``x86_row``'s) fails B1 to B8; and the same reversed shift applied to the emulator as well - a misreading the kernel +and its reference share - fails B8 alone, which is what B8 is for. Group C catches the third kind, where both sides +move together: swapping the add tree's level-3 operands in the *reference* fails C3's P2 probe and C5's acc-tree +case, which no kernel-side mutation could have shown. And ``x86_row``'s NaN rules, mutated one site at a time - a +wrong priority, an SNaN-first rule, the hardware's own NaN, a missing quieting, the default NaN for a created one, a +swapped tree operand - fail a case wherever the mutant can change ``res``: a C case, except where the trees take the +default NaN or the hardware's own, which B6 and B7 catch. Those that survive cannot: dd, P, acc, corr and the +trees' sums are never SNaNs and D is never a NaN, a quieting skipped at one site is applied at the next, a NaN dd +makes ``A`` a NaN, which outranks ``B`` whatever site 2 picked, and the zero sign of a masked ``corr`` lane never +reaches ``res``, because ``A`` is never -0.0. + +Run with ``-s`` for the A6 Clang-order table, the A8 pre-clamp margin and the B7 cancellation residue. +""" + +import numpy as np +import pytest + +from monolith.runtime import _native as _nt +from tests.contract import gguf_reference +from tests.kernels import basalt_cpu_emu as emu +from tests.kernels.basalt_emu import fma32 +from tests.kernels.test_basalt_experts import random_rows +from tests.kernels.test_basalt_iq_parity import quantize_q2_0 + +F32 = np.float32 +H, MAXC, QKA, QK, BB, MAXT = emu.H, emu.MAXC, emu.QKA, emu.QK, emu.BB, emu.MAXT +TWO_M128 = F32(2.0) ** -128 # s <= this gives inv = +inf (docs/research/basalt-cpu-q2.md, 4) +TWO_M149 = F32(2.0) ** -149 # the smallest positive float32 + + +# ---- the comparison policy and the two kernels through their bindings -------------------------------------------- + +def recip(s): + """``1.f / s`` in float32, overflowing to +inf quietly as basalt's step 6 does.""" + with np.errstate(divide="ignore", over="ignore"): + return (F32(1.0) / F32(s)).astype(F32) + + +def same_bits(got, want, what): + """All 32 bits of every element, NaN payloads included - the whole comparison, everywhere.""" + gb = np.ascontiguousarray(got, F32).reshape(-1).view(np.uint32) + wb = np.ascontiguousarray(want, F32).reshape(-1).view(np.uint32) + assert gb.shape == wb.shape, f"{what}: {gb.shape} against {wb.shape}" + bad = np.flatnonzero(gb != wb) + assert bad.size == 0, (f"{what}: bits differ at {bad[:8]} (got {[hex(v) for v in gb[bad[:8]]]}, " + f"want {[hex(v) for v in wb[bad[:8]]]})") + + +def kernel_act(x): + """``act_quant_q8_1`` through the binding, trimmed to what it writes: (q[:n], scale, sum, hx, nchunks).""" + x = np.ascontiguousarray(x, F32) + q, scale = np.zeros(H, np.int8), np.zeros(MAXC, F32) + total, hx = np.zeros(MAXC, np.int32), np.zeros(MAXC, F32) + nchunks = _nt.basalt_act_quant_q8_1(x, q, scale, total, hx) + return q[: x.size], scale[:nchunks], total[:nchunks], hx[:nchunks], nchunks + + +def check_act(x, order="gcc"): + """kernel == emulator on every output. Returns the kernel's (q, scale, sum, hx, nchunks).""" + got, want = kernel_act(x), emu.act_quant_q8_1(x, order) + assert got[4] == want[4], f"nchunks {got[4]} != {want[4]}" + assert np.array_equal(got[0], want[0]), f"codes differ at {np.flatnonzero(got[0] != want[0])[:8]}" + assert np.array_equal(got[2], want[2]), f"sum differs at {np.flatnonzero(got[2] != want[2])[:8]}" + same_bits(got[1], want[1], "scale") + same_bits(got[3], want[3], "hx") + return got + + +def act_arrays(xs): + """``len(xs)`` tokens' quantized activations, in the (nt, H) / (nt, MAXC) arrays the row kernel's binding takes. + Planting ``scale`` and ``hx`` by hand is what makes the adversarial cases of B7 reachable.""" + q, scale, hx = np.zeros((len(xs), H), np.int8), np.zeros((len(xs), MAXC), F32), np.zeros((len(xs), MAXC), F32) + for t, x in enumerate(xs): + qt, st, _, ht, nchunks = kernel_act(x) + q[t, : qt.size], scale[t, :nchunks], hx[t, :nchunks] = qt, st, ht + return q, scale, hx + + +def prefilled(ntok, nrows, fill=0xFF): + """An output array pre-filled with ``fill`` bytes, as basalt's tests pre-fill theirs (basalt_gpu.py:21-28).""" + return np.full((ntok, nrows, 4), fill, np.uint8).view(F32).reshape(ntok, nrows) + + +def kernel_rows(w, row_bytes, nblocks, act, nrows, r0, r1, fill=0xFF): + """``q2_0_gguf_rows_multi`` through the binding, on a caller-owned pre-filled ``out``.""" + q, scale, hx = act + out = prefilled(q.shape[0], nrows, fill) + _nt.basalt_q2_0_gguf_rows_multi(np.ascontiguousarray(w, np.uint8), row_bytes, nblocks, + np.ascontiguousarray(q, np.int8), np.ascontiguousarray(scale, F32), + np.ascontiguousarray(hx, F32), out, r0, r1) + return out + + +def check_rows(w, row_bytes, nblocks, act, nrows, r0=0, r1=None, what=""): + """kernel == emulator over the whole output, the pre-filled rows included. Returns the kernel's ``out``.""" + r1 = nrows if r1 is None else r1 + got = kernel_rows(w, row_bytes, nblocks, act, nrows, r0, r1) + want = emu.q2_0_gguf_rows_multi(w, row_bytes, nblocks, list(zip(*act)), prefilled(act[0].shape[0], nrows), r0, r1) + same_bits(got, want, what or f"rows({row_bytes}, {nblocks}, {r0}:{r1})") + return got + + +# ---- A. act_quant_q8_1 ------------------------------------------------------------------------------------------- + +@pytest.mark.parametrize("n", [2560, 640]) +def test_a1_normal_activations(n): + """A1. N(0, 1) at the two widths the callers pass: the FFN input (2560) and the SwiGLU vector (640).""" + x = np.random.default_rng(7).standard_normal(n).astype(F32) + q, scale, total, hx, nchunks = check_act(x) + assert nchunks == n // QKA and np.isfinite(scale).all() and np.abs(q).max() == 127 + + +def test_a2_all_zero_chunk(): + """A2. An all-zero chunk: ``amax > 0`` is false, so s = 0, inv = 0, every code 0, sum 0 and hx exactly +0.0 + (the sign bit matters: a -0.0 would be a different float32).""" + q, scale, total, hx, _ = check_act(np.zeros(QKA, F32)) + assert np.array_equal(q, np.zeros(QKA, np.int8)) and total[0] == 0 + assert scale.view(np.uint32)[0] == 0 and hx.view(np.uint32)[0] == 0, "scale and hx must be +0.0, not -0.0" + + +def test_a3_signed_zeros_and_every_amax_position(): + """A3. +-0 mixes (the sign clear of step 2 leaves +0.0, so s = 0 and every code 0), then the maximum planted in + each of the 32 positions in turn: the fixed ``maxps(|x0|, |x1|)`` pairing of expert.cpp:352 feeds element j and + element 16+j to one lane, and the four-level tree must reach every lane. With no NaN present both are + order-independent (maximum is associative and commutative there), which is why A6 is the case that pins the + operand order.""" + z = np.where(np.arange(QKA) % 3 == 0, F32(-0.0), F32(0.0)).astype(F32) + q, scale, total, hx, _ = check_act(z) + assert np.array_equal(q, np.zeros(QKA, np.int8)) and total[0] == 0 + assert scale.view(np.uint32)[0] == 0 and hx.view(np.uint32)[0] == 0 + + base = (F32(0.001) * np.arange(1, QKA + 1)).astype(F32) # distinct, so the maximum is unique + for p in range(QKA): + for sign in (F32(1.0), F32(-1.0)): + x = base.copy() + x[p] = sign * F32(9.5) + _, scale, _, _, _ = check_act(x) + assert scale[0] == F32(9.5) / F32(127.0), (p, sign, scale[0]) + + +def test_a4_the_scale_band(): + """A4. The four regimes of ``s = amax / 127`` and ``inv = 1 / s``, at the boundaries the plan measured: + + (a) ``amax = 127 * 2^-128`` puts s exactly on 2^-128, where ``1.f / s`` is already +inf (the specification's + the band's open form is off by this one value; basalt's plain ``1.f / s`` governs). Then + ``0 * inf = NaN`` and ``x * inf = +-inf``, every one of which VCVTTPS2DQ turns into the integer indefinite: + **every code -127, the zeros included**, sum -4064 and hx = s * (float) -4064. + (b) one ulp of s above that, ``inv`` is the finite 3.402822e38 and the codes are ordinary - and subnormal + arithmetic is live, so this case also fails loudly if FTZ is ever switched on. + (c) a subnormal s well inside the finite-``inv`` band (``amax = 127 * 2^-127``). + (d) ``amax = 2^-149`` makes ``fl(amax / 127) = 0``, a regime the specification does not name: the ``s > 0.f`` + guard gives inv = 0, so every code is 0 with scale +0.0 - while ``amax = 127 * 2^-149`` keeps s nonzero + (2^-149) and therefore lands back in (a)'s band, every code -127.""" + x = np.zeros(QKA, F32) + x[5], x[9], x[17] = F32(127.0) * TWO_M128, -F32(127.0) * TWO_M128 / F32(2.0), TWO_M128 + q, scale, total, hx, _ = check_act(x) # (a) + assert scale[0] == TWO_M128 and recip(scale[0]) == F32(np.inf) + assert np.array_equal(q, np.full(QKA, -127, np.int8)), "every code, zeros included, must be -127" + assert total[0] == -4064 and hx[0] == (scale[0] * F32(-4064.0)).astype(F32) + + s_b = np.nextafter(TWO_M128, F32(1.0)) # (b) + x = np.zeros(QKA, F32) + x[3], x[21] = F32(s_b * F32(127.0)), -F32(s_b * F32(127.0)) / F32(2.0) + q, scale, _, _, _ = check_act(x) + assert scale[0] == s_b and recip(scale[0]) == F32(3.402822e38) and np.isfinite(recip(scale[0])) + assert q[3] == 127 and q[21] == -64 and q[0] == 0, "an ordinary chunk, zeros staying 0" + + x = np.zeros(QKA, F32) # (c) + x[11], x[30] = F32(127.0) * (F32(2.0) ** -127), -F32(2.0) ** -127 + q, scale, _, _, _ = check_act(x) + assert scale[0] == F32(2.0) ** -127 and (scale.view(np.uint32)[0] & 0x7F800000) == 0, "s must be subnormal" + assert np.isfinite(recip(scale[0])) and q[11] == 127 and q[30] == -1 + + x = np.zeros(QKA, F32) # (d) + x[1] = TWO_M149 + q, scale, total, hx, _ = check_act(x) + assert scale.view(np.uint32)[0] == 0 and np.array_equal(q, np.zeros(QKA, np.int8)) + assert total[0] == 0 and hx.view(np.uint32)[0] == 0 + + x = np.zeros(QKA, F32) # (d), the neighbour that is not this regime + x[1] = F32(127.0) * TWO_M149 + q, scale, total, _, _ = check_act(x) + assert scale[0] == TWO_M149 and np.array_equal(q, np.full(QKA, -127, np.int8)) and total[0] == -4064 + + +def test_a5_infinite_elements(): + """A5. An infinite element makes ``amax = inf``, so s = inf and inv = 0: the infinite lanes compute + ``inf * 0 = NaN`` and clamp to -127, while every finite lane gets t = +-0 and code 0 - including the -0.0 + element, whose ``t = -0.0`` still takes the ordered ``t >= 0`` branch and adds +0.5.""" + x = np.zeros(QKA, F32) + x[0], x[4], x[6], x[8] = F32(np.inf), F32(-np.inf), F32(-0.0), F32(1.0) + q, scale, total, _, _ = check_act(x) + assert scale[0] == F32(np.inf) and q[0] == -127 and q[4] == -127 + assert q[6] == 0 and q[8] == 0 and total[0] == -254 + + +def test_a6_nan_sweep_over_both_reduction_orders(): + """A6. A NaN swept over all 32 positions of a ramp peaking at element 31, checked bit for bit against the + emulator in **GCC's** operand order, with Clang's value printed beside it. + + The divergence is not only NaN-ness. MAXPS returns SRC2 on an unordered compare, so the two orders swallow + different lanes: at position 19 GCC's tree ends on the NaN (and ``amax > 0.f`` is then false, so s = 0 and every + finite element's code is 0) where Clang's keeps 0.32; at 31 it is the other way round; at 23 both are finite and + different (0.31 against 0.32). A flat chunk with the NaN at 16 and the true maximum at 4 shows the same thing + without any NaN surviving: GCC's tree swallows the 9.0, Clang's keeps it. A test that planted a NaN "somewhere + in the upper half" would pass under either order and prove nothing.""" + ramp = (F32(0.01) * np.arange(1, QKA + 1)).astype(F32) # 0.01 .. 0.32, the maximum at element 31 + table = [] + for p in range(QKA): + x = ramp.copy() + x[p] = F32(np.nan) + check_act(x, "gcc") # the port's order, bit for bit + g, c = (emu.act_quant_q8_1(x, o)[1][0] for o in ("gcc", "clang")) + table.append((p, float(g), float(c))) + print("\nA6 scale by NaN position (GCC's order is the port's):") + print(" " + ", ".join(f"{p}: {g:.8g}/{c:.8g}" for p, g, c in table if g != c)) + + s = {p: (g, c) for p, g, c in table} + assert s[19] == (0.0, float(ramp[31] / F32(127.0))), "19: GCC ends on the NaN (s = 0), Clang keeps 0.32" + assert s[31] == (float(ramp[30] / F32(127.0)), 0.0), "31: the other way round" + assert s[23] == (float(ramp[30] / F32(127.0)), float(ramp[31] / F32(127.0))), "23: two different finite maxima" + + flat = np.full(QKA, F32(0.1), F32) + flat[4], flat[16] = F32(9.0), F32(np.nan) + check_act(flat, "gcc") + g, c = (emu.act_quant_q8_1(flat, o)[1][0] for o in ("gcc", "clang")) + print(f" flat chunk, NaN at 16, maximum 9.0 at 4: GCC {float(g):.8g}, Clang {float(c):.8g}") + assert g == F32(0.1) / F32(127.0) and c == F32(9.0) / F32(127.0), "GCC swallows the maximum, Clang keeps it" + + +def test_a7_rounding_half_away_from_zero_and_the_tie(): + """A7. ``r = t + copysign(0.5, t)`` truncated is lround's rule, round half AWAY from zero: with amax = 127 the + scale is exactly 1 and every t is exact, so +-2.5 must give +-3. And the second rounding is part of the + contract: ``t = 0.49999997f`` makes the exact sum ``1 - 2^-25``, a tie that rounds to the even 1.0f, so the code + is 1 where ``lround(t)`` would give 0 (docs/research/basalt-cpu-q2.md, section 4).""" + x = np.zeros(QKA, F32) + x[0], x[1], x[2], x[3], x[4] = F32(127.0), F32(2.5), F32(-2.5), F32(0.5), F32(-0.5) + q, scale, _, _, _ = check_act(x) + assert scale[0] == F32(1.0) + assert (q[1], q[2], q[3], q[4]) == (3, -3, 1, -1), "half away from zero, both signs" + + amax, xt = F32(np.e), F32(0.01070189569145441) # t = 0.49999997f exactly + x = np.zeros(QKA, F32) + x[0], x[7], x[9] = amax, xt, -xt + q, scale, _, _, _ = check_act(x) + inv = recip(scale[0]) + assert F32(xt * inv) == F32(0.49999997), f"t is {F32(xt * inv):.9g}, not the 0.49999997f this case needs" + assert F32(F32(xt * inv) + F32(0.5)) == F32(1.0) and np.round(F32(xt * inv)) == 0 + assert (q[7], q[9]) == (1, -1), "the second rounding carries t over the integer; lround would give 0" + + +def test_a8_the_saturation_trap(): + """A8. The clamp's reachable side. VCVTTPS2DQ returns the integer indefinite 0x80000000 for a NaN, for +-inf and + for an out-of-range value, which the clamp turns into **-127**; FCVTZS instead saturates (NaN -> 0, + +inf -> INT32_MAX), which would give 0 and +127 here. Both NaN and +inf are reachable: a chunk in the band of + A4(a) has inv = +inf, so its zeros compute ``0 * inf = NaN`` and its nonzeros ``+-inf``. + + The clamp's high side is not reachable at all: ``|x| <= amax`` and the rounding is monotone, so r is largest at + x = amax, and over every positive finite float32 amax with a finite inv ``trunc(r)`` never exceeds 127 (the + largest is 127.50003051757812, at amax = 3.7322113794423347e-37). This asserts that at the measured worst case + and over a random sweep, so the +127 arm is shown inert rather than tested. A finite ``r >= 2^31`` - the third + FCVTZS saturation case - is unreachable through this kernel for the same reason, and is checked on the + reference's own VCVTTPS2DQ instead.""" + x = np.zeros(QKA, F32) + x[2] = F32(127.0) * TWO_M128 # inv = +inf: zeros -> NaN, x[2] -> +inf + x[3] = -x[2] # -> -inf + q, _, _, _, _ = check_act(x) + assert q[0] == -127 and q[2] == -127 and q[3] == -127, "NaN, +inf and -inf must all clamp to -127" + + def pre_clamp(chunk): + """The chunk's steps 5-10 without basalt's clamp, in the reference's own arithmetic.""" + a = np.abs(np.asarray(chunk, F32)) + amax = emu.reduce_max_ps(emu.maxps(a[None, :16], a[None, 16:])) + s = np.where(amax > 0, (amax / F32(127.0)).astype(F32), F32(0)).astype(F32) + with np.errstate(divide="ignore", over="ignore", invalid="ignore"): + inv = np.where(s > 0, (F32(1.0) / s).astype(F32), F32(0)).astype(F32) + t = (np.asarray(chunk, F32) * inv).astype(F32) + r = (t + np.where(t >= 0, F32(0.5), F32(-0.5)).astype(F32)).astype(F32) + return r, emu.cvttps_epi32(r) + + rng = np.random.default_rng(3) + worst, worst_amax = -np.inf, None + sweep = [F32(3.7322113794423347e-37)] + [F32(v) for v in rng.standard_normal(64) * 10 ** rng.uniform(-30, 30, 64)] + for amax in sweep: + amax = F32(np.abs(amax)) # the sweep's draw is signed; amax is not + if not (amax > 0) or not np.isfinite(recip(F32(amax / F32(127.0)))): + continue + chunk = (amax * np.linspace(-1.0, 1.0, QKA)).astype(F32) + chunk[0], chunk[QKA - 1] = amax, -amax + r, v = pre_clamp(chunk) + assert v.max() <= 127, f"the +127 clamp fired at amax = {float(amax)!r}: trunc(r) = {v.max()}" + check_act(chunk) + if r.max() > worst: + worst, worst_amax = float(r.max()), float(amax) + print(f"\nA8 largest pre-clamp r over the sweep: {worst!r} at amax = {worst_amax!r} (the clamp's high side is " + f"inert)") + assert worst == 127.50003051757812, "the tight-band worst case must be in the sweep" + + big = np.asarray([2.0 ** 31, -(2.0 ** 31) - 2.0 ** 8, np.inf, -np.inf, np.nan], F32) # not reachable through + assert np.array_equal(emu.cvttps_epi32(big), np.full(5, emu.INDEF, np.int64)) # the kernel; see above + assert np.array_equal(np.clip(emu.cvttps_epi32(big), -127, 127), np.full(5, -127, np.int64)) + + +def test_a9_the_contraction_trap(): + """A9. Step 7's ``_mm512_mul_ps`` and step 9's ``_mm512_add_ps`` round twice, which GCC 12.2/13.2/14.3/15.2 and + Clang 21 all emit as a separate vmulps and vaddps. A contracted ``fma(x, inv, +-0.5)`` skips the rounding of t + and changes the code, so this input fails the moment the two statements are written as one expression. Measured, + no contraction setting fuses them while they are two statements, because ``t`` also feeds the ``>= 0`` compare + and has to be materialised either way; what ``-ffast-math`` does to this file instead is substitute FMAXNM for + the nine ``maxps`` selects, which case A6 catches. The mutant that this case does catch is the one where the two + statements are merged into one expression by hand, ``vfmaq_f32(+-0.5, x, inv)``, which no flag can undo.""" + amax, xt = F32(np.e), F32(0.01070189569145441) + x = np.zeros(QKA, F32) + x[0], x[6], x[11] = amax, xt, -xt + q, scale, _, _, _ = check_act(x) + inv = recip(scale[0]) + two = np.asarray([F32(F32(xt * inv) + F32(0.5)), F32(F32(-xt * inv) + F32(-0.5))], F32) + fused = np.asarray([fma32(xt, inv, F32(0.5)), fma32(-xt, inv, F32(-0.5))], F32) + assert not np.array_equal(np.trunc(two.astype(np.float64)), np.trunc(fused.astype(np.float64))), \ + f"this input no longer separates the two roundings from the FMA: {two} against {fused}" + assert (q[6], q[11]) == (1, -1), f"contracted codes would be {np.trunc(fused.astype(np.float64)).astype(int)}" + + +def test_a10_the_reciprocal_is_one_over_s_not_127_over_amax(): + """A10. basalt divides twice - ``s = amax / 127.f`` then ``inv = 1.f / s`` (expert.cpp:353-354) - and the + algebraically equal ``inv = 127.f / amax`` (the oracle quantizer's expression at :90) is a different float32, + because ``s`` rounds first. Every other case in this suite survives that substitution: it moves ``inv`` by an + ulp, and a code changes only where ``t = x * inv`` straddles a rounding boundary. This chunk straddles one.""" + amax, x = np.uint32([0x3FB8DD4C, 0x3EE5FD24]).view(F32) + chunk = np.zeros(QKA, F32) + chunk[0], chunk[5] = amax, x + q, scale, _, _, _ = check_act(chunk) + assert scale[0] == F32(amax / F32(127.0)) + mutant = F32(F32(127.0) / amax) + assert mutant != recip(scale[0]), "this witness no longer separates the two reciprocals" + assert int(np.trunc(np.float64(F32(F32(x * mutant) + F32(0.5))))) == 40, "the mutant's code is 40 here" + assert q[5] == 39, "1.f / s gives 39; 127.f / amax gives 40" + + +def test_a11_a_non_finite_activation_writes_no_nan(): + """A11. The exact outputs for a chunk holding a single +inf, a single NaN, and +inf with -inf, as basalt's + expert.cpp:352-367 computes them. A single +inf: amax = s = +inf and ``inv = 1.f / s = +0``, so the infinite + lane's ``t = inf * 0`` is a NaN, which VCVTTPS2DQ converts to INT_MIN and the clamp to -127, while every finite + lane's t is +-0 and its code 0: sum -127, scale +inf, ``hx = +inf * -127 = -inf``. A NaN lane gives -127 the same + way wherever it sits. Where it also reaches amax - position 19 alone, in GCC's tree (A6) - the ordered + ``amax > 0.f`` fails, so s = +0, every finite code is 0 and ``hx = +0 * -127 = -0.0``; elsewhere the tree + swallows it and the chunk scales by its finite peak. +inf with -inf: -127 twice, sum -254, hx -inf. No case + writes a NaN scale or hx. FCVTZS converts a NaN to 0, so a port on it would write q = 0, sum 0 and + ``hx = +inf * 0 = NaN`` for the first chunk.""" + for p in range(QKA): # a single +inf, at every position + x = np.full(QKA, F32(0.25), F32) + x[p] = F32(np.inf) + q, scale, total, hx, _ = check_act(x) + assert q[p] == -127 and np.count_nonzero(q) == 1 and total[0] == -127, f"+inf at {p}" + assert scale.view(np.uint32)[0] == 0x7F800000 and hx.view(np.uint32)[0] == 0xFF800000, f"+inf at {p}" + + for p in range(QKA): # a single NaN, at every position + x = np.full(QKA, F32(0.1), F32) + x[p] = F32(np.nan) + q, scale, total, hx, _ = check_act(x) + assert q[p] == -127, f"NaN at {p}: code {q[p]}" + if p == 19: # amax is the NaN: s = +0 + assert np.count_nonzero(q) == 1 and total[0] == -127 + assert scale.view(np.uint32)[0] == 0x00000000 and hx.view(np.uint32)[0] == 0x80000000 + else: # swallowed: amax = 0.1, the other 31 codes 127 + assert np.count_nonzero(q == 127) == QKA - 1 and total[0] == 3810, f"NaN at {p}" + assert scale.view(np.uint32)[0] == 0x3A4E69A0 and hx.view(np.uint32)[0] == 0x40400000, f"NaN at {p}" + + x = np.full(QKA, F32(0.25), F32) # +inf and -inf together + x[2], x[21] = F32(np.inf), F32(-np.inf) + q, scale, total, hx, _ = check_act(x) + assert q[2] == -127 and q[21] == -127 and np.count_nonzero(q) == 2 and total[0] == -254 + assert scale.view(np.uint32)[0] == 0x7F800000 and hx.view(np.uint32)[0] == 0xFF800000 + + +# ---- B. q2_0_gguf_rows_multi ------------------------------------------------------------------------------------- + +SHAPES = [(2560, 40, 720), (640, 10, 180)] # (n, nblocks, row_bytes): gate/up, then down + + +@pytest.mark.parametrize("n, nblocks, row_bytes", SHAPES) +def test_b1_both_pack_shapes(n, nblocks, row_bytes): + """B1. The two shapes this pack has (native_expert.cpp:49-53 at 2560/640): 40 blocks in 5 full groups of 8, and + 10 blocks in one full group and a ragged one whose mask keeps only ``corr`` lanes 0-3.""" + rng = np.random.default_rng(101) + nrows = 17 + w = random_rows(rng, nrows, n) + act = act_arrays([rng.standard_normal(n).astype(F32)]) + out = check_rows(w, row_bytes, nblocks, act, nrows, what=f"B1 {n}") + assert np.isfinite(out).all() + + +def test_b2_every_token_equals_its_single_token_run(): + """B2. The kernel's own promise (pool.hpp:54-55, "Every token's output is bitwise the single-token job's"), + in the shape of expert_multi_test.cpp:56-72: nt = 1..8 against each token's own nt = 1 run, bit for bit.""" + rng = np.random.default_rng(23) + n, nblocks, row_bytes, nrows = 640, 10, 180, 13 + w = random_rows(rng, nrows, n) + q, scale, hx = act_arrays([rng.standard_normal(n).astype(F32) * (1 + t) for t in range(MAXT)]) + single = [kernel_rows(w, row_bytes, nblocks, (q[t: t + 1], scale[t: t + 1], hx[t: t + 1]), nrows, 0, nrows)[0] + for t in range(MAXT)] + for ntok in range(1, MAXT + 1): + got = check_rows(w, row_bytes, nblocks, (q[:ntok], scale[:ntok], hx[:ntok]), nrows, what=f"B2 nt={ntok}") + for t in range(ntok): + assert np.array_equal(got[t].view(np.uint32), single[t].view(np.uint32)), (ntok, t) + + +def test_b3_row_ranges_and_the_absolute_index(): + """B3. ``out[t]`` is indexed by the ABSOLUTE row r, and rows outside [r0, r1) are not touched - which is what + lets the pool hand row slices of one buffer to different workers (expert.hpp:123-126, pool.cpp:418-431). The + output is pre-filled with 0xFF bytes and checked raw, so an untouched row is 0xFFFFFFFF, not merely a NaN.""" + rng = np.random.default_rng(55) + n, nblocks, row_bytes, nrows = 640, 10, 180, 11 + w = random_rows(rng, nrows, n) + act = act_arrays([rng.standard_normal(n).astype(F32), rng.standard_normal(n).astype(F32)]) + full = check_rows(w, row_bytes, nblocks, act, nrows, what="B3 full") + for r0, r1 in ((0, nrows), (3, 7), (nrows - 1, nrows), (5, 5)): + got = check_rows(w, row_bytes, nblocks, act, nrows, r0, r1, what=f"B3 {r0}:{r1}") + inside = np.zeros(nrows, bool) + inside[r0:r1] = True + assert np.all(got.view(np.uint32)[:, ~inside] == 0xFFFFFFFF), f"{r0}:{r1} wrote outside its range" + assert np.array_equal(got.view(np.uint32)[:, inside], full.view(np.uint32)[:, inside]), \ + f"{r0}:{r1} did not write out[t][r] at the absolute r" + + +def test_b4_stride_padding_is_never_read(): + """B4. ``row_bytes`` is a stride, not a length: with 64 bytes of garbage after each row's 10 blocks the result + must equal the same blocks packed at ``row_bytes = 18 * nblocks``.""" + rng = np.random.default_rng(77) + n, nblocks, nrows = 640, 10, 9 + tight = random_rows(rng, nrows, n).reshape(nrows, BB * nblocks) + pad = 64 + padded = np.concatenate([tight, rng.integers(0, 256, (nrows, pad), dtype=np.uint8)], axis=1) + act = act_arrays([rng.standard_normal(n).astype(F32)]) + a = check_rows(tight.reshape(-1), BB * nblocks, nblocks, act, nrows, what="B4 tight") + b = check_rows(padded.reshape(-1), BB * nblocks + pad, nblocks, act, nrows, what="B4 padded") + assert np.array_equal(a.view(np.uint32), b.view(np.uint32)), "the stride padding changed the result" + + +def test_b5_the_unread_tail(): + """B5. The read set of section 3: ``q[0, 64 * nblocks)``, ``scale[0, 2 * nblocks)`` and ``hx[0, 2 * nblocks)``, + and nothing else - never ``sum``, never ``nchunks``, and nothing past the width (``_mm512_maskz_loadu_ps`` does + not touch its masked-off elements). At nblocks = 10 the tail is poisoned with NaNs in scale and hx and with + alternating +-127 in q; the result must not move a bit.""" + rng = np.random.default_rng(91) + n, nblocks, row_bytes, nrows = 640, 10, 180, 7 + w = random_rows(rng, nrows, n) + q, scale, hx = act_arrays([rng.standard_normal(n).astype(F32)]) + base = check_rows(w, row_bytes, nblocks, (q, scale, hx), nrows, what="B5 clean") + q[0, QK * nblocks:] = np.where(np.arange(H - QK * nblocks) % 2, 127, -127) + scale[0, 2 * nblocks:] = F32(np.nan) + hx[0, 2 * nblocks:] = F32(np.nan) + poisoned = check_rows(w, row_bytes, nblocks, (q, scale, hx), nrows, what="B5 poisoned") + assert np.array_equal(base.view(np.uint32), poisoned.view(np.uint32)), "the kernel read past its width" + + +def test_b6_every_fp16_block_scale(): + """B6. All 65,536 half bit patterns as a block's ``d`` against one fixed activation: +-0, every subnormal, 65504, + +-inf and every NaN. ``_mm256_cvtph_ps`` and ``vcvt_f32_f16`` are both exact for every half, subnormals included + (MXCSR.DAZ is ignored, and FPCR's FZ16 is off), and this case is what proves the NaN halves too: the reference + converts them by VCVTPH2PS's own rule (payload << 13, quiet bit forced), the kernel by the instruction, and the + comparison is bitwise, so all 2,046 NaN patterns are checked against x86's conversion rather than assumed.""" + rng = np.random.default_rng(13) + nrows, nblocks, row_bytes = 1 << 16, 1, BB + w = np.empty((nrows, row_bytes), np.uint8) + w[:, :2] = np.arange(nrows, dtype=np.uint16).view(np.uint8).reshape(-1, 2) + w[:, 2:] = rng.integers(0, 256, (nrows, 16), dtype=np.uint8) + act = act_arrays([rng.standard_normal(QK).astype(F32)]) + out = check_rows(w.reshape(-1), row_bytes, nblocks, act, nrows, what="B6 halves") + halves = np.frombuffer(np.arange(nrows, dtype=np.uint16).tobytes(), np.float16) + assert np.isnan(out[0][np.isnan(halves)]).all(), "a NaN scale must give a NaN row" + assert np.isfinite(out[0][: 0x7C00]).all(), "a finite scale must give a finite row" + assert np.isnan(out[0][[0x7C00, 0xFC00]]).all(), "an infinite scale reaches inf * 0 = NaN on a zero code" + assert out[0][[0, 0x8000]].view(np.uint32).tolist() == [0, 0], "+-0 as a scale leaves res at +0.0" + + +def test_b7_adversarial_activations(): + """B7. ``scale`` and ``hx`` are planted directly, which the binding allows and the quantizer cannot produce: + subnormal, zero and huge values; a row whose ``P = RN(d * s)`` overflows to +-inf (and whose lanes then compute + ``inf * 0 = NaN``); blocks carrying all four codes 0..3; and nblocks = 9, a ragged second group where the mask + keeps only ``corr`` lanes 0-1. + + The cancelling case is the sharpest of them: with every code byte 0x55 every code is 1, so every weight + dequantizes to ``(1 - 1) * d = 0`` and the exact result is zero - ``R(acc)`` and ``R(corr)`` are then the same + sum reached through different lane structures (acc's lane L carries weights 4L..4L+3, corr's carries chunk + 16g+L), and what is left is pure rounding residue, where the tree shape and the FMA order are visible.""" + rng = np.random.default_rng(5) + n, nblocks, row_bytes, nrows = 640, 10, 180, 12 + w = random_rows(rng, nrows, n).reshape(nrows, row_bytes) + for b in range(nblocks): # all four codes 0..3 in every block + w[0, b * BB + 2: (b + 1) * BB] = np.tile(np.asarray([0x1B, 0xE4, 0x4E, 0xB1], np.uint8), 4) + w[1, b * BB + 2: (b + 1) * BB] = 0x1B + q, scale, hx = act_arrays([rng.standard_normal(n).astype(F32)]) + scale[0, 0], hx[0, 0] = TWO_M149, -TWO_M149 # subnormal + scale[0, 1], hx[0, 1] = F32(0.0), F32(-0.0) # zero, and a -0.0 hx + scale[0, 2], hx[0, 2] = F32(3.0e38), F32(-3.0e38) # P = d * s overflows for any sane d + scale[0, 19], hx[0, 19] = F32(np.inf), F32(1.0) # the ragged group's last kept lane + out = check_rows(w.reshape(-1), row_bytes, nblocks, (q, scale, hx), nrows, what="B7 planted") + assert np.isnan(out).any() or np.isinf(out).any(), "the overflow regime must be reached" + + for nb in (9, 2, 1): # ragged groups: 1, 2 and 8+1 blocks + rb = BB * nb + ww = random_rows(rng, nrows, QK * nb) + check_rows(ww, rb, nb, act_arrays([rng.standard_normal(QK * nb).astype(F32)]), nrows, what=f"B7 nb={nb}") + + nblocks, row_bytes, n = 40, 720, 2560 # the cancelling row set + w = random_rows(rng, nrows, n).reshape(nrows, row_bytes) + for b in range(nblocks): + w[:, b * BB + 2: (b + 1) * BB] = 0x55 # every code 1: (code - 1) * d = 0 + act = act_arrays([rng.standard_normal(n).astype(F32)]) + out = check_rows(w.reshape(-1), row_bytes, nblocks, act, nrows, what="B7 cancellation") + print(f"\nB7 R(acc) - R(corr) where the exact sum is zero: max |res| = {np.abs(out).max():.3e}") + assert np.abs(out).max() < 1e-5, "the correction no longer cancels the dot; check the lane mapping" + + +@pytest.mark.parametrize("n, nblocks, row_bytes", SHAPES) +def test_b8_against_a_float64_reference(n, nblocks, row_bytes): + """B8. The independent check. The emulation and the kernel share one reading of section 3's unpack and lane + mapping; this builds ``sum (code - 1) * d * q * s`` in float64 from llama.cpp's own numpy dequantizer + (tests/contract/gguf_reference.dequantize, written apart from the C reference the format plugins follow) and + compares against it, which is the only case that catches a misreading of either. + + The bound is on ``sum |terms|``, not on ``|ref|``: a row whose terms cancel has a large relative error for a + correct kernel. A misread unpack or lane mapping is an O(1) error, so 1e-6 of the row's own magnitude - about + twenty times the worst per-row observation (5.3e-08) and about two and a half times the aggregate (3.9e-07) - + still catches it.""" + rng = np.random.default_rng(42) + nrows = 48 + values = (rng.standard_normal((nrows, n)) * 0.02 * (0.5 + (np.arange(nrows)[:, None] % 7) / 7.0)).astype(F32) + w = quantize_q2_0(values) # real weights, not random bytes + q, scale, hx = act_arrays([rng.standard_normal(n).astype(F32)]) + got = check_rows(w, row_bytes, nblocks, (q, scale, hx), nrows, what=f"B8 {n}")[0].astype(np.float64) + + weights = gguf_reference.dequantize(42, w.reshape(nrows, row_bytes)).astype(np.float64) + x = (q[0, :n].astype(np.float64).reshape(-1, QKA) * scale[0, : n // QKA, None].astype(np.float64)).reshape(-1) + ref = weights @ x + magnitude = np.abs(weights) @ np.abs(x) + rel = np.abs(got - ref) / magnitude + aggregate = np.abs(got - ref).sum() / np.abs(ref).sum() + print(f"\nB8 n={n}: max |res - ref| / sum|terms| = {rel.max():.2e}, aggregate L1 = {aggregate:.2e}") + assert rel.max() < 1e-6 and aggregate < 1e-6, (rel.max(), aggregate) + + +def test_b9_determinism(): + """B9. Repeated runs bit-identical, the numerics contract's last gate (CLAUDE.md).""" + rng = np.random.default_rng(2026) + n, nblocks, row_bytes, nrows = 2560, 40, 720, 9 + w = random_rows(rng, nrows, n) + act = act_arrays([rng.standard_normal(n).astype(F32) for _ in range(3)]) + first = kernel_rows(w, row_bytes, nblocks, act, nrows, 0, nrows) + for _ in range(4): + again = kernel_rows(w, row_bytes, nblocks, act, nrows, 0, nrows) + assert np.array_equal(first.view(np.uint32), again.view(np.uint32)), "the row dot is not deterministic" + x = rng.standard_normal(n).astype(F32) + one = kernel_act(x) + for _ in range(4): + other = kernel_act(x) + assert np.array_equal(one[0], other[0]) and np.array_equal(one[2], other[2]) + assert np.array_equal(one[1].view(np.uint32), other[1].view(np.uint32)) + assert np.array_equal(one[3].view(np.uint32), other[3].view(np.uint32)) + + +@pytest.mark.parametrize( + "name, w_len, row_bytes, nblocks, nrows, message", + [("nblocks wraps the int product", 1024, 603979776, 1 << 25, 1, "nblocks must be 1..40"), + ("row_bytes * nrows wraps size_t", 18, 1 << 48, 1, 65536, "w is shorter than row_bytes")], +) +def test_b10_a_bound_that_would_overflow_still_refuses(name, w_len, row_bytes, nblocks, nrows, message): + """The binding's bounds divide rather than multiply. Written as products, both of these pass the check meant to + fail them - ``QK * nblocks`` reaches INT_MIN at nblocks = 2^25, and ``row_bytes * nrows`` wraps to 0 - and the + kernel then reads past the ActQ arrays or past ``w``, which segfaults.""" + q = np.zeros((1, H), np.int8) + scale = np.zeros((1, MAXC), np.float32) + hx = np.zeros((1, MAXC), np.float32) + out = np.zeros((1, nrows), np.float32) + with pytest.raises(ValueError, match=message): + _nt.basalt_q2_0_gguf_rows_multi(np.zeros(w_len, np.uint8), row_bytes, nblocks, q, scale, hx, out, 0, 1) + + +# ---- C. the recorded x86 ground truth ----------------------------------------------------------------------------- +# +# Every value in C1-C4 was measured by running basalt's own kernels, or the instructions they emit, on an AVX-512 +# machine (module docstring); C5's compose those measured rows through the reviewer's hardware-validated lane model. +# None of it comes from this port or from the numpy reference, which is the point of the group. Citations are lines +# of ``pr21-x86-ground-truth.md``. + +GT = "pr21-x86-ground-truth.md" +PX, PY = 0x7FC000A1, 0x7FC000B1 # the two planted payloads of the site probes (GT:307-309) +QA, QB, QC, SNAN = 0x7FC0000A, 0x7FC0000B, 0xFFC0000C, 0x7F80000D # the per-site tables' operands (GT:120-123) +INDEF, INF, NINF = 0xFFC00000, 0x7F800000, 0xFF800000 +ONE, FOUR, PZERO, NZERO = 0x3F800000, 0x40800000, 0x00000000, 0x80000000 + + +def f32(bits): + """The float32 holding these bits.""" + return np.uint32(bits).view(F32) + + +def u32(x): + """The 32 bits of a one-element float32 result.""" + return int(np.ascontiguousarray(x, F32).reshape(-1).view(np.uint32)[0]) + + +def packed_row(blocks): + """One Q2_0 row from a (fp16 scale bits, code byte) pair per block, the weight shape the fixtures use.""" + w = np.zeros((len(blocks), BB), np.uint8) + for b, (d, code) in enumerate(blocks): + w[b, :2] = np.asarray([d], np.uint16).view(np.uint8) + w[b, 2:] = code + return w.reshape(-1) + + +def blank_act(): + """A full-width (q, scale, hx) to plant into, as the fixtures' ``memset`` leaves theirs.""" + return np.zeros(H, np.int8), np.zeros(MAXC, F32), np.zeros(MAXC, F32) + + +def quantized_act(x): + """``act_quant_q8_1(x)`` as one token's full-width (q, scale, hx).""" + q, scale, hx = act_arrays([x]) + return q[0], scale[0], hx[0] + + +def tiled(act, ntok): + """One activation handed to ``ntok`` identical tokens, as every fixture and probe hands it.""" + return tuple(np.tile(v, (ntok, 1)) for v in act) + + +def fixture_a(): + return packed_row([(0x3C00, 0x55)]), 1, quantized_act(np.full(64, f32(0x7D800000), F32)), INDEF + + +def fixture_b(): + return packed_row([(0x7E01, 0x55), (0x7E02, 0x55)]), 2, quantized_act(np.ones(128, F32)), 0x7FC04000 + + +def fixture_c1(): + q, scale, hx = blank_act() + q[:128] = 1 + scale[:4] = [f32(0x7FC12345), F32(1.0), F32(np.inf), F32(1.0)] + return packed_row([(0x3C00, 0x55), (0x3C00, 0x00)]), 2, (q, scale, hx), 0x7FC12345 + + +def fixture_c2(): + q, scale, hx = blank_act() + scale[:18] = F32(1.0) + hx[0], hx[16] = f32(0x7FC54321), F32(-np.inf) + return packed_row([(0x3C00, 0x55)] * 8 + [(0x0000, 0x55)]), 9, (q, scale, hx), 0x7FC54321 + + +def fixture_c3(): + x = np.full(64, F32(0.25), F32) + x[3] = F32(np.inf) + return packed_row([(0x3C00, 0x1B)]), 1, quantized_act(x), INDEF + + +@pytest.mark.parametrize( + "name, build, nts, cite", + [("a, inf - inf in the final subtraction", fixture_a, range(1, MAXT + 1), "29"), + ("b, two NaN block scales at the acc FMA", fixture_b, range(1, MAXT + 1), "40"), + ("c1, a QNaN accumulator against inf * 0", fixture_c1, range(1, MAXT + 1), "53"), + ("c2, a QNaN correction against 0 * inf", fixture_c2, range(1, MAXT + 1), "64"), + ("c3, a quantized chunk holding +inf", fixture_c3, (1, 2), "75")], +) +def test_c1_the_end_to_end_fixtures(name, build, nts, cite): + """C1. The five end-to-end fixtures, each against the 32 bits x86 wrote for it. (a) and (c3) are the + generated-NaN case - every NaN in the row was made, not propagated, so x86's indefinite is the whole answer + and all four GCC versions agree (GT:375-378). (b), (c1) and (c2) are the propagated case, where x86 ranks the + FMA's operands the other way round from AArch64's FMLA: (b) keeps the second block's scale over the + accumulator, (c1) and (c2) keep a QNaN addend that FMLA would discard for the default NaN. + + x86 gives the same bits at every (nt, t) for all five, so each is checked at every token count the ground + truth records.""" + w, nblocks, act, golden = build() + for ntok in nts: + out = check_rows(w, BB * nblocks, nblocks, tiled(act, ntok), 1, what=f"C1 ({name}) nt={ntok}") + got = out.view(np.uint32).reshape(-1) + assert np.all(got == golden), \ + f"({name}) nt={ntok}: {[hex(int(v)) for v in got]} != {hex(golden)} ({GT}:{cite})" + + +def _nan_swallows(peak): + """Fixture (d): a flat chunk whose true maximum at element 4 is swallowed by the NaN at 16.""" + x = np.full(QKA, F32(0.1), F32) + x[4], x[16] = peak, f32(0x7FC00000) + return x + + +def _subnormal_peak(k): + """Fixture (e): a zero chunk with ``k * 2^-149`` at 0 and ``-2^-149`` at 1.""" + x = np.zeros(QKA, F32) + x[0], x[1] = f32(k), f32(0x80000001) + return x + + +# name, x, [(scale, inv, sum, hx, every code, the exceptions) per chunk], citation +QUANTIZER_GOLDENS = [ + ("a", np.full(64, f32(0x7D800000), F32), + [(0x7A010204, 0x04FE0000, 4064, 0x7F800000, 127, {})] * 2, "24-25"), + ("b", np.ones(128, F32), [(0x3C010204, 0x42FE0000, 4064, 0x42000000, 127, {})] * 4, "36"), + ("c3", np.where(np.arange(64) == 3, F32(np.inf), F32(0.25)).astype(F32), + [(0x7F800000, 0x00000000, -127, 0xFF800000, 0, {3: -127}), + (0x3B010204, 0x43FE0000, 4064, 0x41000000, 127, {})], "69-71"), + ("d1", _nan_swallows(F32(0.11)), [(0x3A4E69A0, 0x449EC000, 3810, 0x40400000, 127, {4: 127, 16: -127})], "82"), + ("d2", _nan_swallows(F32(1e7)), [(0x3A4E69A0, 0x449EC000, 3556, 0x40333333, 127, {4: -127, 16: -127})], "83"), + ("e63", _subnormal_peak(63), [(0x00000000, 0x00000000, 0, 0x00000000, 0, {})], "92"), + ("e64", _subnormal_peak(64), [(0x00000001, 0x7F800000, -4064, 0x80000FE0, -127, {})], "93"), +] + + +@pytest.mark.parametrize("name, x, chunks, cite", QUANTIZER_GOLDENS) +def test_c2_the_quantizer_goldens(name, x, chunks, cite): + """C2. ``act_quant_q8_1``'s own outputs, recorded from the x86 run: the fixtures' two scales, (c3)'s infinite + chunk, (d)'s two NaN-swallowed maxima - the one input that reaches the clamp's +127 side (d1) and the one that + reaches the integer indefinite from a finite element (d2) - and (e)'s 63 against 64 times 2^-149 threshold. + ``inv`` is not an output; it is basalt's guarded ``s > 0.f ? 1.f / s : 0.f`` on the recorded scale, checked + because the band's whole behaviour turns on it.""" + got = check_act(np.asarray(x, F32)) + q, scale, total, hx, nchunks = got + assert nchunks == len(chunks), f"{name}: {nchunks} chunks, not {len(chunks)} ({GT}:{cite})" + for k, (sc, inv, sm, hxb, default, exceptions) in enumerate(chunks): + where = f"{name} chunk {k} ({GT}:{cite})" + assert scale.view(np.uint32)[k] == sc, f"{where}: scale {hex(int(scale.view(np.uint32)[k]))} != {hex(sc)}" + guarded = recip(scale[k]) if scale[k] > 0 else F32(0.0) # basalt's `s > 0.f ? 1.f / s : 0.f` (:354) + assert u32(guarded) == inv, f"{where}: inv is {hex(u32(guarded))}, not {hex(inv)}" + assert total[k] == sm, f"{where}: sum {total[k]} != {sm}" + assert hx.view(np.uint32)[k] == hxb, f"{where}: hx {hex(int(hx.view(np.uint32)[k]))} != {hex(hxb)}" + want = np.full(QKA, default, np.int8) + for pos, code in exceptions.items(): + want[pos] = code + assert np.array_equal(q[k * QKA: (k + 1) * QKA], want), f"{where}: codes" + + +def probe(pat): + """The nine site probes of ``probes_main.inc``: q = 1 everywhere, scale and hx zero, every block d = 1.0 with + code bytes 0x55, and two distinct QNaN payloads planted where exactly one site decides between them.""" + q, scale, hx = np.ones(H, np.int8), np.zeros(MAXC, F32), np.zeros(MAXC, F32) + nblocks, d0 = (8, 8, 8, 8, 1, 1, 9, 2, 1)[pat], 0x3C00 + plant = {0: ((hx, 0, PX), (hx, 8, PY)), 1: ((hx, 0, PX), (hx, 4, PY)), 2: ((hx, 0, PX), (hx, 2, PY)), + 3: ((hx, 0, PX), (hx, 1, PY)), 4: ((scale, 0, PX), (scale, 1, PY)), 5: ((scale, 0, PX), (hx, 0, PY)), + 6: ((hx, 0, PX), (hx, 16, PY)), 7: ((scale, 0, PX), (scale, 2, PY)), + 8: ((scale, 0, PY), (scale, 1, ONE))}[pat] + for arr, idx, val in plant: + arr[idx] = f32(val) + if pat == 8: + d0 = 0x7E05 # -> 0x7fc0a000 after vcvtph2ps, against a QNaN scale + return packed_row([(d0, 0x55)] + [(0x3C00, 0x55)] * (nblocks - 1)), nblocks, (q, scale, hx) + + +@pytest.mark.parametrize( + "pat, golden, cite, what", + [(0, PY, "313", "add tree level 1, corr lanes 0 and 8: SRC1 is the high half"), + (1, PY, "313", "add tree level 2, corr lanes 0 and 4: SRC1 is the high quarter"), + (2, PY, "313", "add tree level 3, corr lanes 0 and 2: SRC1 is the shuffle, in every slot of every GCC (GT:342)"), + (3, PX, "313", "add tree level 4, corr lanes 0 and 1: SRC1 is lane 0"), + (4, PY, "313", "add tree level 1 on acc, lanes 0-7 against 8-15"), + (5, PX, "351", "site 5, vsubss: the acc sum is SRC1 and outranks the corr sum"), + (6, PY, "231", "site 2, vfmadd231ps corr, dd, hx: hx outranks the accumulated corr"), + (7, PY, "251", "site 3, vfmadd231ps acc, P, D: P outranks the accumulator"), + (8, 0x7FC0A000, "209", "site 1, a QNaN dd against a QNaN scale in chunk 0 only: the one-token tree takes " + "chunk 1's lanes, where dd meets 1.0, so C5 isolates site 1")], +) +def test_c3_the_site_probes(pat, golden, cite, what): + """C3. Each probe plants two payloads where one site decides between them, and the golden is x86's answer for + a ONE-token job (GT:313 for P0-P4; P5-P8 gave one answer in every slot, at the line each cites). That column is + what the port pins for every token slot, so the same value is also asserted at nt = 2 - where x86 itself would + answer differently for P0, P1, P3 and P4 (GT:314), because GCC reassigns the add tree's operands per token and + basalt's own output there stops being the single-token job's (pool.hpp:54-55). Pinning is the deliberate + divergence; the fixed value is checked, not assumed.""" + w, nblocks, act = probe(pat) + for ntok in (1, 2): + out = check_rows(w, BB * nblocks, nblocks, tiled(act, ntok), 1, what=f"C3 P{pat} nt={ntok}") + got = out.view(np.uint32).reshape(-1) + assert np.all(got == golden), \ + f"P{pat} ({what}) nt={ntok}: {[hex(int(v)) for v in got]} != {hex(golden)} ({GT}:{cite})" + + +SITE1 = [(PZERO, INF, INDEF), (INF, PZERO, INDEF), (NZERO, INF, INDEF), (0x7FC02000, ONE, 0x7FC02000), + (ONE, QA, QA), (0x7FC02000, QA, 0x7FC02000), (0x7FC02000, QC, 0x7FC02000), (0x7FE02000, ONE, 0x7FE02000), + (ONE, SNAN, 0x7FC0000D), (0x7FE02000, QA, 0x7FE02000), (0x7FC02000, SNAN, 0x7FC02000), + (0x7FE02000, SNAN, 0x7FE02000), (0x7FC02000, INF, 0x7FC02000), (PZERO, QA, QA)] +SITE2 = [(PZERO, INF, ONE, INDEF), (INF, PZERO, ONE, INDEF), (ONE, INF, NINF, INDEF), + (0x7FC02000, ONE, ONE, 0x7FC02000), (ONE, QA, ONE, QA), (ONE, ONE, QB, QB), (QA, QB, ONE, QA), + (QA, ONE, QB, QA), (ONE, QA, QB, QA), (QA, QB, QC, QA), (PZERO, INF, QB, QB), (INF, PZERO, QB, QB), + (0x7FE02000, ONE, ONE, 0x7FE02000), (ONE, SNAN, ONE, 0x7FC0000D), (ONE, SNAN, QB, 0x7FC0000D), + (QA, SNAN, ONE, QA), (0x7FE02000, QA, ONE, 0x7FE02000), (0x7FE02000, ONE, QB, 0x7FE02000), + (PZERO, SNAN, QB, 0x7FC0000D)] +SITE3 = [(INF, PZERO, ONE, INDEF), (INF, FOUR, NINF, INDEF), (QA, FOUR, ONE, QA), (ONE, FOUR, QB, QB), + (QA, FOUR, QB, QA), (QC, FOUR, QB, QC), (INF, PZERO, QB, QB), (QA, PZERO, ONE, QA)] +SITE5 = [(INF, INF, INDEF), (QA, ONE, QA), (ONE, QB, QB), (QA, QB, QA), (QC, QB, QC), (QA, INF, QA)] +HALVES = [(0x7E01, 0x7FC02000), (0x7E02, 0x7FC04000), (0xFE03, 0xFFC06000), (0x7D01, 0x7FE02000), + (0xFD05, 0xFFE0A000), (0x7C01, 0x7FC02000), (0x0001, 0x33800000)] + + +def test_c4_the_per_site_nan_tables(): + """C4. The reference's own rule at each site, against the rows the reviewer measured on the hardware and on + basalt's emitted instruction forms: site 1 ``vmulps``, SRC1 = dd (GT:202-217); site 2 + ``vfmadd231ps corr, dd, hx``, priority dd, hx, corr (GT:221-241); site 3 ``vfmadd231ps acc, P, D``, priority + P, D, acc (GT:245-254); site 5 ``vsubss``, SRC1 = A (GT:346-353); and VCVTPH2PS's NaN conversion (GT:142-146). + An SNaN never outranks a QNaN in a later slot, and a QNaN addend beats an ``inf * 0`` product - the two rules + AArch64 has backwards. The kernel meets the same rows end to end through C1 and C3.""" + for src1, src2, want in SITE1: + got = u32(emu.x86_mul(f32(src1), f32(src2))) + assert got == want, f"site 1 ({GT}:202-217): mul({hex(src1)}, {hex(src2)}) = {hex(got)} != {hex(want)}" + for dd, hx, corr, want in SITE2: + got = u32(emu.x86_fma(f32(dd), f32(hx), f32(corr))) + assert got == want, \ + f"site 2 ({GT}:221-241): fma({hex(dd)}, {hex(hx)}, {hex(corr)}) = {hex(got)} != {hex(want)}" + for p, d, acc, want in SITE3: + got = u32(emu.x86_fma(f32(p), f32(d), f32(acc))) + assert got == want, f"site 3 ({GT}:245-254): fma({hex(p)}, {hex(d)}, {hex(acc)}) = {hex(got)} != {hex(want)}" + for a, b, want in SITE5: + got = u32(emu.x86_sub(f32(a), f32(b))) + assert got == want, f"site 5 ({GT}:346-353): sub({hex(a)}, {hex(b)}) = {hex(got)} != {hex(want)}" + for half, want in HALVES: + got = u32(emu.h2f(np.uint16(half))) + assert got == want, f"vcvtph2ps ({GT}:142-146): h2f({hex(half)}) = {hex(got)} != {hex(want)}" + + +SNAN2 = 0xFF80000E # a second SNaN, sign set: site 5's B below + + +def planted(nblocks, plants, d0, zero_byte): + """The probes' shape: q = 1 everywhere, scale and hx +0.0 but for the plants, block 0's fp16 d = ``d0`` and every + other block's 1.0, code bytes 0x55 - except block 0's byte ``zero_byte``, whose four codes are 0, which leaves + acc lane ``zero_byte`` alone with a zero dot.""" + q, scale, hx = np.ones(H, np.int8), np.zeros(MAXC, F32), np.zeros(MAXC, F32) + for arr, idx, bits in plants: + {"scale": scale, "hx": hx}[arr][idx] = f32(bits) + w = packed_row([(d0, 0x55)] + [(0x3C00, 0x55)] * (nblocks - 1)) + if zero_byte is not None: + w[2 + zero_byte] = 0 + return w, nblocks, (q, scale, hx) + + +# id, nblocks, block 0's d, plants, block 0's zero code byte, golden, the rows that decide it +MODEL_GOLDENS = [ + ("s1-snan-scale", 1, 0x3C00, (("scale", 0, SNAN), ("scale", 1, SNAN)), None, 0x7FC0000D, "212"), + ("s1-qnan-dd-over-snan-scale", 1, 0x7E01, (("scale", 0, SNAN), ("scale", 1, SNAN)), None, 0x7FC02000, "142, 214"), + ("s1-snan-half-over-snan-scale", 1, 0x7D01, (("scale", 0, SNAN), ("scale", 1, SNAN)), None, 0x7FE02000, + "143, 215"), + ("s1-zero-times-inf", 1, 0x0000, (("scale", 0, INF), ("scale", 1, INF)), None, INDEF, "204"), + ("s2-snan-hx", 1, 0x3C00, (("hx", 0, SNAN),), None, 0x7FC0000D, "236"), + ("s2-snan-hx-over-qnan-corr", 9, 0x3C00, (("hx", 0, PX), ("hx", 16, SNAN)), None, 0x7FC0000D, "237"), + ("s2-zero-times-inf", 1, 0x0000, (("hx", 0, INF),), None, INDEF, "223"), + ("s3-quieted-snan-p-over-qnan-acc", 2, 0x3C00, (("scale", 0, PX), ("scale", 2, SNAN)), None, 0x7FC0000D, + "212, 251"), + ("s4-level-1-high-half", 8, 0x3C00, (("hx", 0, SNAN), ("hx", 8, PY)), None, PY, "236, 270, 307-313"), + ("s4-acc-levels-2-to-4", 1, 0x3C00, (("scale", 0, PX), ("scale", 1, INF)), 14, INDEF, "247, 270"), + ("s5-quieted-snans-a-over-b", 1, 0x3C00, (("scale", 0, SNAN), ("hx", 0, SNAN2)), None, 0x7FC0000D, "212, 351"), +] + + +@pytest.mark.parametrize("name, nblocks, d0, plants, zero_byte, golden, cite", MODEL_GOLDENS, + ids=[case[0] for case in MODEL_GOLDENS]) +def test_c5_the_site_rows_through_the_kernel(name, nblocks, d0, plants, zero_byte, golden, cite): + """C5. C4's rows through the kernel, where no recorded fixture or probe takes them: a signaling NaN in + ``scale`` or ``hx``, alone (its quieting) and against a QNaN at each site it meets; the indefinite that sites 1 + and 2 create from ``+0 * +inf``; and the acc tree's levels 2-4, which the probes reach on the corr tree only + (lane 14's ``+inf * 0`` is the one indefinite among X's, so a swapped operand at level 2, 3 or 4 gives X). + + These goldens were not recorded end to end. Each composes measured rows (cited) through ``mo::row``, the + reviewer's lane model, which matched basalt's kernel bit for bit on the AVX-512 host over 62,374 outputs + (GT:355-371), with GCC 14.3's one-token tree order - asserted at every nt, because the port pins that order for + every token slot (C3). + + Each case fails a mutant of ``x86_row`` that picks the wrong NaN at its site, and the mutants the rest of the + suite let through fail here: an SNaN-first or SRC2-first ``vmulps`` and the hardware's own FMUL (the site 1 dd + cases), a missing quieting (the lone SNaNs), the default NaN 0x7fc00000 for a created one (the ``+0 * +inf`` + cases), and a swapped operand at the acc tree's levels 2-4.""" + w, nblocks, act = planted(nblocks, plants, d0, zero_byte) + for ntok in range(1, MAXT + 1): + out = check_rows(w, BB * nblocks, nblocks, tiled(act, ntok), 1, what=f"C5 {name} nt={ntok}") + got = out.view(np.uint32).reshape(-1) + assert np.all(got == golden), \ + f"{name} nt={ntok}: {[hex(int(v)) for v in got]} != {hex(golden)} ({GT}:{cite} through mo::row)" diff --git a/tests/kernels/test_basalt_dense_tc.py b/tests/kernels/test_basalt_dense_tc.py new file mode 100644 index 00000000..214f55a2 --- /dev/null +++ b/tests/kernels/test_basalt_dense_tc.py @@ -0,0 +1,210 @@ +# SPDX-License-Identifier: MIT +# Copyright (c) 2026 Jesús Gulfo +# adapted from basalt (jesdga95/basalt) src/kernels/dense_tc_parity.cpp @ b4c63b55754637f4c72ad53a0f791d425f71eb36 +# (MIT; third_party/NOTICE): its cases, pairs, scale offsets and sane_half scales, the T = 1..8 sweep, the 0xff output +# pre-fill and the pass criteria. +"""basalt's dense_tc and dense_tc_pair on Metal (kernels/common/basalt_dense_tc.metal) for this pack's Q2_0, Q3_K, +Q4_K, Q5_K, Q6_K and IQ4_XS weights, in every summation order basalt's variant rule can pick. + +- dense_tc_parity, ported (basalt src/kernels/dense_tc_parity.cpp): its cases (:37-63) and pairs (:386-388), random + weights with normal fp16 scales (:65-90) and N(0, 1) activations quantized once by the native quantizer (:108). Each + case runs through the order the rule picks at 170 multiprocessors (basalt's measured RTX 5090) and through every + other order; each order: every column of a T-column call (T = 1..8, the activation buffer holding T columns) bitwise + equal to the same column of the 8-column call, columns past T never stored, and the 8-column output's RMS error + against native_mmvq's one-column outputs. Criteria, quoted: ``const bool ok = bits == 0 && nonfinite == 0 && rms < + 1e-3;`` (:137) and for the pairs ``const bool k = bits == 0 && rms < 1e-3;`` (:201). The cases and pairs with IQ3_S + (z IQ3_S, out IQ3_S; {qkv Q6_K, z IQ3_S}, {qkv IQ4_XS, z IQ3_S}) are left out: this pack has no IQ3_S weights, and + the port has no IQ3_S terms. +- The pair's outputs bitwise equal to dense_tc's tile order (``a tile's arithmetic is dense_tc_tile_block's``, + dense_tc.cu:704-705). +- Bit for bit against the numpy emulation of what nvcc compiles (tests/kernels/basalt_emu.py ``dense_tc``, + docs/research/basalt-nvcc/dense_tc.md), every order, at shapes with empty warp groups (n_in 2560 in the one order), + KS 2 at n_in 1024 and 2048, and row tails; the orders must differ somewhere, so the comparison can tell them apart. +- A float64 reference per type, every order, under the bound docs/design/flash-next.md gives dense_tc's comparand + native_mmvq: for Q4_K, Q5_K and Q6_K, which no basalt test checks against a reference, mmvq_multi_parity's Q8_0 + rule on the same q8_1 bytes, ``const bool ok = diff == 0 && worst <= 1e-4 * (scale + 1e-30);`` + (mmvq_multi_parity.cpp:461); for Q3_K, IQ4_XS and Q2_0, which iq_parity runs (iq_parity.cpp:29), ``const bool ok = + dq_err < 1e-6 && mm_err < 2e-2 && multi_bad == 0;`` (iq_parity.cpp:112), mm_err the relative L1 error against + ref . x in float64 on the float activations.""" + +import numpy as np +import pytest + +from monolith import kernels +from tests.contract import gguf_reference +from tests.kernels import basalt_emu as emu +from tests.kernels import basalt_gpu as gpu +from tests.kernels.test_basalt_mmvq import columns, reference, weights + +F32 = np.float32 +NAMES = {11: "Q3_K", 12: "Q4_K", 13: "Q5_K", 14: "Q6_K", 23: "IQ4_XS", 42: "Q2_0"} +VARIANTS = ("one", "tile", "s1", "s2") + +# dense_tc_parity.cpp:37-63, in its order (the pairs index it); type 21 is IQ3_S +CASES = [("qkv Q6_K", 14, 2560, 10240), ("qkv Q4_K", 12, 2560, 10240), ("qkv Q5_K", 13, 2560, 10240), + ("qkv IQ4_XS", 23, 2560, 10240), ("z Q6_K", 14, 2560, 6144), ("z IQ4_XS", 23, 2560, 6144), + ("z IQ3_S", 21, 2560, 6144), ("out Q6_K", 14, 6144, 2560), ("out IQ4_XS", 23, 6144, 2560), + ("out Q4_K", 12, 6144, 2560), ("out Q5_K", 13, 6144, 2560), ("out IQ3_S", 21, 6144, 2560), + ("q Q6_K", 14, 2560, 12288), ("kv Q6_K", 14, 2560, 512), ("tail Q4_K", 12, 1024, 1000), + ("tail Q6_K", 14, 1536, 999), ("qkv Q3_K", 11, 2560, 10240), ("z Q3_K", 11, 2560, 6144), + ("out Q3_K", 11, 6144, 2560), ("q Q3_K", 11, 2560, 12288), ("qkv Q2_0", 42, 2560, 10240), + ("z Q2_0", 42, 2560, 6144), ("q Q2_0", 42, 2560, 12288), ("tail Q3_K", 11, 1536, 999), + ("tail Q2_0", 42, 1024, 1000)] +PAIRS = [(0, 6), (1, 5), (2, 4), (3, 6), (0, 5), (16, 17), (3, 17), (20, 21), (16, 21), (1, 17), (20, 17)] +PACK_CASES = [c for c in CASES if c[1] != 21] +PACK_PAIRS = [p for p in PAIRS if CASES[p[0]][1] != 21 and CASES[p[1]][1] != 21] + + +def variants(n_in): + """Every order the rule can pick; KS 2 only where n_in % 1024 == 0 (dense_tc.cu:1056).""" + return [v for v in VARIANTS if v != "s2" or n_in % 1024 == 0] + + +PARITY = [(c, v) for c in PACK_CASES for v in variants(c[2])] + + +def native_ref(type_id, w, xq, n_in, n_out): + """native_mmvq's one-column outputs of the eight columns (dense_tc_parity.cpp:109-111).""" + return np.stack([gpu.mmvq(type_id, w, columns(xq, n_in, j), n_in, n_out, 1)[0] for j in range(8)]) + + +def rms_err(got, ref): + d = got.astype(np.float64) - ref.astype(np.float64) + return np.sqrt((d * d).sum() / max((ref.astype(np.float64) ** 2).sum(), 1e-300)) + + +def width_checks(outs, n_out): + """bits: values of a T-column call that differ from the 8-column call's; nonfinite: non-finite values written; + stray: values written past column T (the output starts as 0xff bytes).""" + g8 = outs[8] + bits = nonfinite = stray = 0 + for t, y in outs.items(): + bits += np.count_nonzero(y[:t].view(np.uint32) != g8[:t].view(np.uint32)) + nonfinite += np.count_nonzero(~np.isfinite(y[:t])) + stray += np.count_nonzero(y[t:].view(np.uint32) != 0xFFFFFFFF) + return bits, nonfinite, stray + + +_FIXTURES = {} + + +def case_fixture(case): + """dense_tc_parity's per-case data: weights, the 8 columns' q8_1 bytes and native_mmvq's outputs, made once.""" + if case not in _FIXTURES: + _, type_id, n_in, n_out = case + rng = np.random.default_rng(777 + type_id * 31 + n_out) + w = weights(type_id, n_in, n_out, rng) + xq = gpu.q8_1(rng.standard_normal(8 * n_in).astype(F32), "native") + _FIXTURES.clear() + _FIXTURES[case] = (w, xq, native_ref(type_id, w, xq, n_in, n_out)) + return _FIXTURES[case] + + +@pytest.mark.parametrize("case,variant", PARITY, ids=[f"{c[0]}-{v}" for c, v in PARITY]) +def test_dense_tc_parity(case, variant): + name, type_id, n_in, n_out = case + w, xq, ref = case_fixture(case) + outs = gpu.dense_tc(type_id, w, xq, n_in, n_out, range(1, 9), variant) + bits, nonfinite, stray = width_checks(outs, n_out) + rms = rms_err(outs[8], ref) + picked = kernels.basalt_dense_tc_variant(type_id, n_in, n_out) + print(f"{name} {variant}{' (the rule at 170)' if variant == picked else ''}: {bits} diff, {nonfinite} nonfinite, " + f"rms {rms:.3e}") + # basalt: ``const bool ok = bits == 0 && nonfinite == 0 && rms < 1e-3;`` (dense_tc_parity.cpp:137) + assert bits == 0 and nonfinite == 0 and rms < 1e-3, (bits, nonfinite, rms) + assert stray == 0 # columns past T are never stored + + +@pytest.mark.parametrize("pair", PACK_PAIRS, ids=[f"{CASES[a][0]}+{CASES[b][0]}" for a, b in PACK_PAIRS]) +def test_dense_tc_pair_parity(pair): + a, b = CASES[pair[0]], CASES[pair[1]] + rng = np.random.default_rng(4242 + a[1] * 7 + b[1]) + n_in = a[2] + wa, wb = weights(a[1], n_in, a[3], rng), weights(b[1], n_in, b[3], rng) + xq = gpu.q8_1(rng.standard_normal(8 * n_in).astype(F32), "native") + outs = gpu.dense_tc_pair(a[1], wa, a[3], b[1], wb, b[3], xq, n_in, range(1, 9)) + for m, (c, w) in enumerate(((a, wa), (b, wb))): + mine = {t: o[m] for t, o in outs.items()} + bits, nonfinite, stray = width_checks(mine, c[3]) + rms = rms_err(mine[8], native_ref(c[1], w, xq, n_in, c[3])) + print(f"pair {a[0]} + {b[0]} [{m}]: {bits} diff, rms {rms:.3e}") + # basalt: ``const bool k = bits == 0 && rms < 1e-3;`` (dense_tc_parity.cpp:201) + assert bits == 0 and rms < 1e-3, (m, bits, rms) + assert stray == 0 and nonfinite == 0, m + # the pair's tile arithmetic is dense_tc_tile_block's (dense_tc.cu:704-705) + tile = gpu.dense_tc(c[1], w, xq, n_in, c[3], (8,), "tile")[8] + assert np.array_equal(mine[8].view(np.uint32), tile.view(np.uint32)), m + + +EMU_SHAPES = [(2560, 37), (6144, 21), (1024, 19), (2048, 33)] + + +@pytest.mark.parametrize("type_id", sorted(NAMES), ids=[NAMES[t] for t in sorted(NAMES)]) +def test_emulation_bit_for_bit(type_id): + """Every order against the numpy emulation, one, three and eight columns; at n_in 2560 the one order's warps of + group 5 have no chunk (5 chunks for 6 groups) and add their zeros, as in basalt.""" + for n_in, n_out in EMU_SHAPES: + rng = np.random.default_rng(99 + type_id + n_in) + w = weights(type_id, n_in, n_out, rng) + x = rng.standard_normal(8 * n_in).astype(F32) + x[: 64] = 0.0 # all-zero q8_1 blocks + xq = gpu.q8_1(x, "native") + got = {} + for v in variants(n_in): + want = emu.dense_tc(type_id, w, xq, n_in, n_out, 8, v) + got[v] = gpu.dense_tc(type_id, w, xq, n_in, n_out, (1, 3, 8), v) + for t, y in got[v].items(): + # the bar is docs/design/flash-next.md invariant 5 (nvcc's sequence, bit for bit); basalt has no + # counterpart test + assert np.array_equal(y[:t].view(np.uint32), want[:t].view(np.uint32)), (n_in, v, t) + if n_in == 6144: # power: the orders' bits differ + for i, u in enumerate(VARIANTS): + for v in VARIANTS[i + 1:]: + assert not np.array_equal(got[u][8].view(np.uint32), got[v][8].view(np.uint32)), (u, v) + + +def test_pair_emulation_bit_for_bit(): + """dense_tc_pair with two formats against the emulation of the pair order, row tails in both matrices.""" + n_in = 2560 + for t0, t1 in ((14, 23), (12, 11), (42, 13)): + rng = np.random.default_rng(5 + t0 + t1) + w0, w1 = weights(t0, n_in, 35, rng), weights(t1, n_in, 18, rng) + xq = gpu.q8_1(rng.standard_normal(8 * n_in).astype(F32), "native") + outs = gpu.dense_tc_pair(t0, w0, 35, t1, w1, 18, xq, n_in, (2, 8)) + for m, (ty, w, n_out) in enumerate(((t0, w0, 35), (t1, w1, 18))): + want = emu.dense_tc(ty, w, xq, n_in, n_out, 8, "pair") + for t, o in outs.items(): + # flash-next.md invariant 5, bit for bit; basalt has no counterpart test + assert np.array_equal(o[m][:t].view(np.uint32), want[:t].view(np.uint32)), (t0, t1, m, t) + + +@pytest.mark.parametrize("type_id", sorted(NAMES), ids=[NAMES[t] for t in sorted(NAMES)]) +def test_float64_reference(type_id): + """Every order, eight columns. Q4_K, Q5_K and Q6_K: mmvq_multi_parity.cpp:461's rule, worst |y - ref| <= 1e-4 * + max |ref| per column, ref the float64 product on the same q8_1 bytes (test_basalt_mmvq.reference); its diff == 0 + is test_dense_tc_parity's bits == 0. Q3_K, IQ4_XS and Q2_0: iq_parity's rule (iq_parity.cpp:103-112), mm_err = + sum |y - ref . x| / sum |ref . x| < 2e-2, ref the weights dequantized by gguf-py's decoders + (tests/contract/gguf_reference.py) and x the float activations, ref . x in float64.""" + n_in, n_out = 6144, 40 + rng = np.random.default_rng(31 * type_id) + w = weights(type_id, n_in, n_out, rng) + x = rng.standard_normal(8 * n_in).astype(F32) + xq = gpu.q8_1(x, "native") + same_bytes = type_id in (12, 13, 14) + if same_bytes: + ref = np.stack([reference(type_id, w, columns(xq, n_in, j), n_in, n_out) for j in range(8)]) # (8, n_out) + else: + ref = x.reshape(8, n_in).astype(np.float64) @ gguf_reference.dequantize(type_id, w).astype(np.float64).T + for v in variants(n_in): + y = gpu.dense_tc(type_id, w, xq, n_in, n_out, (8,), v)[8].astype(np.float64) + assert np.all(np.isfinite(y)), v + if same_bytes: + worst, scale = np.abs(y - ref).max(axis=1), np.abs(ref).max(axis=1) + print(f"{NAMES[type_id]} {v}: worst / scale up to {(worst / scale).max():.2e}") + # basalt: ``const bool ok = diff == 0 && worst <= 1e-4 * (scale + 1e-30);`` (mmvq_multi_parity.cpp:461) + assert np.all(worst <= 1e-4 * (scale + 1e-30)), (v, worst / scale) + else: + mm_err = np.abs(y - ref).sum() / (np.abs(ref).sum() + 1e-30) + print(f"{NAMES[type_id]} {v}: mm_err {mm_err:.2e}") + # basalt: ``const bool ok = dq_err < 1e-6 && mm_err < 2e-2 && multi_bad == 0;`` (iq_parity.cpp:112) + assert mm_err < 2e-2, (v, mm_err) diff --git a/tests/kernels/test_basalt_experts.py b/tests/kernels/test_basalt_experts.py new file mode 100644 index 00000000..8d990c41 --- /dev/null +++ b/tests/kernels/test_basalt_experts.py @@ -0,0 +1,428 @@ +# SPDX-License-Identifier: MIT +# Copyright (c) 2026 Jesús Gulfo +# adapted from basalt (jesdga95/basalt) src/kernels/iq_multi_parity.cpp, src/kernels/native_grouped_parity.cpp and +# src/kernels/native_expert_parity.cpp @ b4c63b55754637f4c72ad53a0f791d425f71eb36 (MIT; third_party/NOTICE): their +# fixtures, plans, pre-fills and pass criteria. +"""basalt's routed experts for Q2_0 / Q2_0 on Metal (kernels/common/basalt_experts.metal): native_expert_grouped's +gate/up, SwiGLU + IEEE q8_1 and down dispatches. + +Fixtures follow basalt's tests: Q2_0 rows of random bytes with a finite fp16 scale per block, sign | exponent 2..8 | +any mantissa (2^-13 .. 2^-6; ``random_rows``, iq_multi_parity.cpp:72-90, native_grouped_parity.cpp:73-98); token +activations N(0, 1) quantized by the IEEE q8_1 quantizer (``quantize_q8_1_rows``). basalt draws them with +std::mt19937 and std:: distributions, whose outputs are implementation-defined; these draw the same distributions +with numpy.""" + +import numpy as np +import pytest + +from monolith import kernels +from tests.contract import gguf_reference +from tests.kernels import basalt_emu as emu +from tests.kernels import basalt_gpu as gpu +from tests.kernels.test_basalt_iq_parity import quantize_q2_0 + +F32 = np.float32 + + +def random_rows(rng, rows, n, neg=0.5): + """``rows`` Q2_0 rows of ``n`` values: random bytes, then each block's fp16 scale (negative with probability + ``neg``; basalt's iq_multi_parity uses 1/4, native_grouped_parity 1/2).""" + blk = rng.integers(0, 256, (rows * (n // 64), 18), dtype=np.uint8) + h = ((rng.random(len(blk)) < neg).astype(np.uint16) << 15) | (rng.integers(2, 9, len(blk)).astype(np.uint16) << 10) \ + | rng.integers(0, 1024, len(blk)).astype(np.uint16) + blk[:, :2] = h.view(np.uint8).reshape(-1, 2) + return blk.reshape(-1) + + +def random_blob(rng, n_embd, n_ff, neg=0.5): + """One expert blob: gate rows | up rows (n_embd values each) | down rows (n_ff values each).""" + blob = np.concatenate([random_rows(rng, 2 * n_ff, n_embd, neg), random_rows(rng, n_embd, n_ff, neg)]) + assert blob.size == kernels.basalt_expert_layout(n_embd, n_ff)["bytes"] + return blob + + +@pytest.mark.parametrize("n_embd, n_ff", [(512, 256), (2560, 640)]) +def test_every_variant_builds_and_runs(n_embd, n_ff): + """Each kernel variant compiles and a one-group call writes finite rows and nothing else.""" + rng = np.random.default_rng(1) + blob = random_blob(rng, n_embd, n_ff) + xq = gpu.q8_1(rng.standard_normal(3 * n_embd).astype(F32), "ieee") + for gu2 in ((False, True) if n_embd == 2560 else (False,)): + for sub16 in ((False, True) if n_ff == 640 else (False,)): + r = gpu.experts(blob, [0], [0, 3], [2, 0, 1], [1, 3, 0], xq, n_embd, n_ff, 5, gu2=gu2, sub16=sub16) + out = r["out"] + assert np.isfinite(out[[0, 1, 3]]).all(), (gu2, sub16) + assert np.all(out[[2, 4]].view(np.uint32) == 0xFFFFFFFF), (gu2, sub16) + + +# ---- calls as basalt's tests build them -------------------------------------------------------------------------- + +class Call: + """One expert call: ``n_blobs`` blobs in one arena (each at a 256-byte aligned slot, native_grouped_parity.cpp:118), + groups of ``sizes`` entries from entry ``base`` on, each group its own blob while there are enough (plan_sizes, + :164-188), random tokens and scattered destinations (a permutation of the cap rows), and ``tokens`` q8_1 rows of + N(0, 1) activations from the IEEE quantizer.""" + + def __init__(self, rng, n_embd, n_ff, sizes, tokens, *, base=0, cap=None, n_blobs=None, neg=0.5, cap_groups=None): + self.n_embd, self.n_ff = n_embd, n_ff + self.lay = kernels.basalt_expert_layout(n_embd, n_ff) + slot = (self.lay["bytes"] + 255) // 256 * 256 + n_blobs = n_blobs or max(len(sizes), 1) + self.arena = np.zeros(slot * n_blobs, np.uint8) + for b in range(n_blobs): + self.arena[slot * b: slot * b + self.lay["bytes"]] = random_blob(rng, n_embd, n_ff, neg) + order = rng.permutation(n_blobs) + self.grp_off = [int(slot * order[g % n_blobs]) for g in range(len(sizes))] + self.grp_start = [base + int(v) for v in np.cumsum([0] + list(sizes))] + self.n_ent = self.grp_start[-1] + self.cap = cap or self.n_ent + 3 + self.cap_groups = cap_groups or max(len(sizes), 1) + assert self.n_ent <= self.cap + self.ent_tok = rng.integers(0, tokens, self.cap).astype(np.int32) + self.ent_dst = rng.permutation(self.cap).astype(np.int32) + self.x = rng.standard_normal(tokens * n_embd).astype(F32) + self.xq = gpu.q8_1(self.x, "ieee") + + def entries(self): + return range(self.grp_start[0], self.n_ent) + + def group_of(self, e): + return next(g for g in range(len(self.grp_off)) if self.grp_start[g] <= e < self.grp_start[g + 1]) + + def run(self, **kw): + return gpu.experts(self.arena, self.grp_off, self.grp_start, self.ent_tok, self.ent_dst, self.xq, self.n_embd, + self.n_ff, self.cap, cap_groups=self.cap_groups, cap_entries=self.cap, **kw) + + def per_entry(self, **kw): + """Each entry alone (one group of one entry): the grouped kernels' arithmetic one entry a call, the comparand + that stands for basalt's older kernels. Rows no entry writes keep the NaN pattern; each call must leave every + row but its own as it was, as basalt diffs the whole buffer (native_grouped_parity.cpp:226-234).""" + out = np.full((self.cap, self.n_embd), 0xFFFFFFFF, np.uint32) + for e in self.entries(): + g, d = self.group_of(e), int(self.ent_dst[e]) + r = gpu.experts(self.arena, [self.grp_off[g]], [0, 1], [self.ent_tok[e]], [d], self.xq, self.n_embd, + self.n_ff, self.cap, **kw) + got = r["out"].view(np.uint32) + assert np.all(np.delete(got, d, axis=0) == 0xFFFFFFFF), ("stray store", e) + out[d] = got[d] + return out + + def blob(self, e, part): + """Entry e's gate, up or down rows (GGUF bytes).""" + o, lay = self.grp_off[self.group_of(e)], self.lay + start = {"gate": 0, "up": lay["up_off"], "down": lay["down_off"]}[part] + n = lay["n_ff"] * lay["gu_row"] if part != "down" else lay["n_embd"] * lay["d_row"] + return self.arena[o + start: o + start + n] + + +def q8_rows(xq, rows, n): + """The q8_1 rows ``rows`` (n values each) of the q8_1 bytes ``xq``.""" + b = n // 32 * kernels.Q8_1_BLOCK_BYTES + return np.concatenate([np.asarray(xq)[r * b: (r + 1) * b] for r in rows]) + + +def gpu_expf_neg(g): + """The SwiGLU's __expf(-g) as the kernel computes it: basalt_fp.metal's expf_neg, the same device function.""" + src = kernels.PRELUDE + kernels.template("basalt_fp.metal") + """ +kernel void ex(device const float* g [[buffer(0)]], device float* e [[buffer(1)]], constant uint& n [[buffer(2)]], + uint i [[thread_position_in_grid]]) { + if (i < n) e[i] = expf_neg(g[i]); +} +""" + g = np.ascontiguousarray(g, F32).reshape(-1) + out = gpu.run(gpu.pipeline(src, "ex"), [g.tobytes(), 4 * g.size], np.uint32(g.size).tobytes(), 2, + -(-g.size // 256), 256) + return np.frombuffer(out[1], F32) + + +def check_against_emulation(c, r): + """Every stage bit for bit against tests/kernels/basalt_emu.py (experts.md): gate and up rows per entry, the q8_1 of + the SwiGLU product from the GPU's gate and up (with the GPU's __expf), the down rows from the GPU's q8_1.""" + n_embd, n_ff = c.n_embd, c.n_ff + ents = list(c.entries()) + if not ents: # an empty call: nothing to emulate + return + for e in ents: + xr = q8_rows(c.xq, [c.ent_tok[e]], n_embd) + for part in ("gate", "up"): + want = emu.q2_0_dots(c.blob(e, part), n_embd, xr)[0] + assert np.array_equal(r[part][e].view(np.uint32), want.view(np.uint32)), (part, e) + lo, hi = c.grp_start[0] * n_ff, c.n_ent * n_ff + g, u = r["gate"].reshape(-1)[lo:hi], r["up"].reshape(-1)[lo:hi] + hq = emu.swiglu_q8_1(g, u, gpu_expf_neg(g)) + blk = kernels.Q8_1_BLOCK_BYTES + assert np.array_equal(r["hq"][lo // 32 * blk: hi // 32 * blk], hq) + for e in ents: + want = emu.q2_0_dots(c.blob(e, "down"), n_ff, q8_rows(r["hq"], [e], n_ff))[0] + assert np.array_equal(r["out"][c.ent_dst[e]].view(np.uint32), want.view(np.uint32)), ("down", e) + + +# ---- iq_multi_parity's check_grouped (iq_multi_parity.cpp:239-337) ----------------------------------------------- + +def grouped_case(seed=18): + """check_grouped's call: 9 groups of {1, 3, 4, 5, 0, 8, 2, 11, 1} entries (one pass of GRP_NC, partial passes, two + passes and more), 8 tokens, cap_groups = groups + 2 (the extra threadgroup rows must exit), cap = entries + 3, the + entries' destinations a permutation of the first rows, random tokens (:254-264, :321); Q2_0 / Q2_0 at 2560 x 640 + (:497-500).""" + rng = np.random.default_rng(seed) + sizes = [1, 3, 4, 5, 0, 8, 2, 11, 1] + c = Call(rng, 2560, 640, sizes, 8, neg=0.25, cap_groups=len(sizes) + 2) + c.ent_dst = np.concatenate([rng.permutation(c.n_ent), np.arange(c.n_ent, c.cap)]).astype(np.int32) + return c + + +def test_check_grouped(): + """The grouped call against the same kernels one entry a call (basalt: old kernels against new), every float + compared, the NaN rows nothing may write included; basalt's criterion, quoted: ``const bool ok = diff == 0 && + finite;`` (iq_multi_parity.cpp:329), finite over the written rows. Also the kernel choices against each other + (gate/up two rows or one row a SIMD-group, down on 16 or 32 lanes) and every stage against the emulation.""" + c = grouped_case() + r = c.run(scratch_fill=0x00) # out NaN-filled, scratch zeroed (:309-310) + got = r["out"].view(np.uint32) + diff = np.count_nonzero(got != c.per_entry()) + finite = np.isfinite(r["out"][: c.n_ent]).all() + assert diff == 0 and finite, (diff, finite) + assert np.all(got[c.n_ent:] == 0xFFFFFFFF) + for gu2, sub16 in ((False, True), (True, False), (False, False)): + other = c.run(gu2=gu2, sub16=sub16)["out"].view(np.uint32) + assert np.count_nonzero(other != got) == 0, (gu2, sub16) + check_against_emulation(c, r) + + +# ---- native_grouped_parity (native_grouped_parity.cpp:219-248, 513-532) ------------------------------------------ + +@pytest.mark.parametrize("n_embd, n_ff", [(512, 256), (2560, 640)]) +def test_native_grouped_parity(n_embd, n_ff): + """native_grouped_parity's check on Q2_0 / Q2_0: T = 6 tokens x 4 experts (cap 24 entries), 9 blobs, calls of 0, 1, + 2, 3, 5, 8 and 24 groups of 1..T entries from entry 0 and from entry 7, scattered destinations over the cap rows; + each call with grid_groups 0, 1, 2, 3, 4 and cap + 3 and stale scratch (0x00 or 0x7F alternately) against the same + kernels one entry a call (basalt: against v1). 512 x 256 is the registered test's shape (gate/up one row a + SIMD-group); 2560 x 640 is its ``--gu2`` run (the kernels decode runs), where the per-entry comparand takes the + one-row gate/up kernel as basalt's v1 does, against gu2 in the grouped call. Criteria, quoted: ``for (size_t i = 0; i < + ref.size(); ++i) diff += ref[i] != got[i];`` (:234) and ``if (written == 0) { std::printf(" nothing was written: + the check checked nothing FAIL\\n"); ++bad; }`` (:246). Every stage of each call's first run is also checked + against the emulation.""" + rng = np.random.default_rng(316 + n_embd) + T, K, n_blobs = 6, 4, 9 + cap = T * K + calls = written = 0 + for base in (0, 7): + for groups in (0, 1, 2, 3, 5, 8, 24): + sizes, used = [], base + for _ in range(groups): # plan(): groups of 1..T while they fit + m = min(int(rng.integers(1, T + 1)), cap - used) + if m <= 0: + break + sizes.append(m) + used += m + c = Call(rng, n_embd, n_ff, sizes, T, base=base, cap=cap, n_blobs=n_blobs, cap_groups=cap) + # basalt's --gu2 run compares gu2 against v1's gate/up kernel (the one-row kernel): so does the comparand + ref = c.per_entry(gu2=False if n_embd == 2560 else None) + written += np.count_nonzero(ref != 0xFFFFFFFF) + for gy in (0, 1, 2, 3, 4, cap + 3): + r = c.run(grid_groups=gy, scratch_fill=0x7F if calls & 1 else 0x00) + if gy == 0: + check_against_emulation(c, r) + diff = np.count_nonzero(ref != r["out"].view(np.uint32)) + calls += 1 + assert diff == 0, (base, groups, gy, diff) + # basalt: if (written == 0) { ... "nothing was written: the check checked nothing FAIL" ... } + assert written > 0 + print(f"\nQ2_0/Q2_0 {n_embd} x {n_ff}: {calls} calls bitwise equal to per-entry calls, {written} floats written") + + +# ---- IEEE subnormals in the SwiGLU product ------------------------------------------------------------------------ + +@pytest.mark.parametrize("n_embd, n_ff", [(512, 256), (2560, 640)]) +def test_groups_read_their_blobs_across_buffers(n_embd, n_ff): + """basalt's grp_ptr is an address a group: the same call with its blobs moved into two separate buffers, at offsets + other than the arena's, writes the same bits (gate, up, the q8_1 of H and the output).""" + rng = np.random.default_rng(7) + c = Call(rng, n_embd, n_ff, [3, 1, 2, 6], 4, n_blobs=4) + ref = c.run() + blob = c.lay["bytes"] + pad = 512 # each blob 512 bytes past the previous one's end + arenas = [np.zeros(pad + 2 * (blob + pad), np.uint8), np.zeros(pad + 2 * (blob + pad), np.uint8)] + grp_buf, grp_off, used = [], [], [0, 0] + for g, o in enumerate(c.grp_off): + b = g % 2 + at = pad + used[b] * (blob + pad) + arenas[b][at: at + blob] = c.arena[o: o + blob] + grp_buf.append(b) + grp_off.append(at) + used[b] += 1 + got = gpu.experts(arenas, grp_off, c.grp_start, c.ent_tok, c.ent_dst, c.xq, n_embd, n_ff, c.cap, + cap_groups=c.cap_groups, cap_entries=c.cap, grp_buf=grp_buf) + assert sorted(set(grp_buf)) == [0, 1] and grp_off != c.grp_off + for k in ("gate", "up", "hq", "out"): + assert np.array_equal(np.asarray(got[k]).view(np.uint8), np.asarray(ref[k]).view(np.uint8)), k + + +def test_ieee_mul_keeps_subnormals(): + """ieee_mul (basalt_q8_1.metal), CUDA's mul.rn.f32 without .ftz, bit for bit against numpy's IEEE float32 product + on planted pairs: products across the subnormal range, at the 2^-126 boundary (rounding up into it), at ties of + the subnormal grid, below half the smallest subnormal, signed zeros, subnormal operands, normal products, and + infinities and NaN against zeros and subnormals (NaN for 0 * inf and a NaN, the signed infinity for a subnormal + times inf; a NaN's payload is the GPU's).""" + rng = np.random.default_rng(9) + n = 1 << 16 + a = (rng.choice([-1, 1], n) * np.exp2(rng.uniform(-90, -20, n))).astype(F32) + b = (rng.choice([-1, 1], n) * np.exp2(rng.uniform(-90, -20, n))).astype(F32) + tie = np.full(64, F32(2.0 ** -75)) # 2^-75 * (2k + 1) 2^-75 = (k + 0.5) 2^-149 + inf, nan, sub = F32(np.inf), F32(np.nan), np.uint32(5).view(F32) + planted = [(F32(2.0 ** -63), F32(2.0 ** -63) * F32(1 - 2.0 ** -24)), # just below 2^-126: rounds up + (F32(2.0 ** -75), F32(2.0 ** -75)), (F32(2.0 ** -100), F32(2.0 ** -50)), # exactly 2^-150: to +0 + (F32(-(2.0 ** -100)), F32(2.0 ** -49) * F32(1.5)), # 1.5 * 2^-149: tie, to even (2 units) + (F32(0.0), F32(-3.0)), (F32(-0.0), F32(-0.0)), (F32(2.0 ** -140), F32(3.0)), # zeros, a subnormal + (np.uint32(1).view(F32), F32(2.0 ** 100)), (F32(1.5), F32(2.0 ** -128)), (F32(3.0), F32(5.0)), + (F32(0.0), inf), (F32(-0.0), inf), (F32(0.0), -inf), (-inf, F32(-0.0)), # 0 * inf: NaN + (F32(0.0), nan), (F32(-0.0), nan), (nan, F32(0.0)), (nan, F32(-0.0)), # a NaN: NaN + (sub, inf), (-inf, sub), (-sub, -inf), (sub, nan), (nan, -sub), (inf, F32(-3.0))] # inf, NaN, -inf + pa = np.concatenate([a, tie, np.array([p[0] for p in planted], F32)]) + pb = np.concatenate([b, (np.arange(64) * 2 + 1).astype(F32) * F32(2.0 ** -75), np.array([p[1] for p in planted], F32)]) + src = kernels.basalt_q8_1_source() + """ +kernel void mul(device const float* a [[buffer(0)]], device const float* b [[buffer(1)]], device float* c [[buffer(2)]], + constant uint& n [[buffer(3)]], uint i [[thread_position_in_grid]]) { + if (i < n) c[i] = ieee_mul(a[i], b[i]); +} +""" + out = gpu.run(gpu.pipeline(src, "mul"), [pa.tobytes(), pb.tobytes(), 4 * pa.size], np.uint32(pa.size).tobytes(), 3, + -(-pa.size // 256), 256) + got = np.frombuffer(out[2], F32) + with np.errstate(under="ignore", invalid="ignore"): + want = pa * pb + units = pa.astype(np.float64) * pb.astype(np.float64) * 2.0 ** 149 # exact products, units of 2^-149 + ties = np.count_nonzero((np.abs(units) < 2.0 ** 23) & (np.abs(units) % 1 == 0.5)) + sub = np.count_nonzero((np.abs(want) < F32(2.0 ** -126)) & (want != 0)) + same = (got.view(np.uint32) == want.view(np.uint32)) | (np.isnan(got) & np.isnan(want)) + assert same.all(), np.flatnonzero(~same)[:8] + assert sub > 1000 and ties >= 64, (sub, ties) # the subnormal path ran, on grid ties too + print(f"\nieee_mul: {pa.size} products bit for bit, {sub} of them subnormal, {ties} grid ties, " + f"{np.count_nonzero(np.isnan(want))} NaN") + + +def test_swiglu_q8_1_edges(): + """The SwiGLU + q8_1 dispatch alone on planted gate and up values, bit for bit against the emulation (the + exponential taken from the GPU): very negative gates (-88.7 .. -60) with small up values, whose IEEE products are + subnormal; gates past -88.72, where the exponential overflows and the quotient is -0; large positive gates, zeros, + multiples of 2^-48 (the GEMV's grid), and N(0, 4) gates; non-finite gates and ups (a weight row with a non-finite + fp16 scale), whose IEEE products are NaN: five in a finite block (its sum NaN) and a whole block of inf * 0 (its + scale and sum NaN, each stored as sm_120's fp16 0x7fff, as in test_basalt_q8_1). Entries [1, 5) of a 6-entry + scratch, so the dispatch must leave entry 0's and entry 5's q8_1 blocks as they were.""" + rng = np.random.default_rng(10) + n_ff, ents = 640, 4 + g = np.concatenate([rng.standard_normal(n_ff) * 4, rng.uniform(-88.7, -60, n_ff), rng.uniform(-91, -86, n_ff), + np.concatenate([rng.uniform(80, 120, 160), np.zeros(160), + rng.integers(-1000, 1000, 320) * 2.0 ** -48])]).astype(F32) + up = np.concatenate([rng.standard_normal(n_ff), rng.choice([-1, 1], n_ff) * np.exp2(rng.uniform(-40, -1, n_ff)), + rng.standard_normal(n_ff), rng.standard_normal(n_ff) * 1e-3]).astype(F32) + nf = 3 * n_ff + 96 # blocks nf / 32 and nf / 32 + 1 + g[nf: nf + 5] = [np.inf, np.nan, 0.0, -100.0, -np.inf] # s = inf, NaN, 0, -0, NaN against + up[nf: nf + 5] = [0.0, -0.0, np.inf, np.nan, 0.0] # up = 0, -0, inf, NaN, 0: five NaN products + g[nf + 32: nf + 64], up[nf + 32: nf + 64] = np.inf, 0.0 # a whole block of inf * 0 + gate = np.concatenate([np.full(n_ff, np.nan, F32), g, np.full(n_ff, np.nan, F32)]) + upp = np.concatenate([np.zeros(n_ff, F32), up, np.zeros(n_ff, F32)]) + nb = 6 * n_ff // 32 * kernels.Q8_1_BLOCK_BYTES + pso = gpu.pipeline(kernels.basalt_experts_source(), "basalt_expert_swiglu_q8_1", + tuple(sorted(kernels.basalt_expert_macros(512, n_ff).items()))) + out = gpu.run(pso, [gate.tobytes(), upp.tobytes(), np.array([1, 3, 5], np.int32).tobytes(), + np.int32(2).tobytes(), nb], kernels.basalt_expert_params(512, n_ff), 5, + -(-6 * n_ff // kernels.EXPERT_THREADS), kernels.EXPERT_THREADS, fill=0xA5) + hq = np.frombuffer(out[4], np.uint8) + per = n_ff // 32 * kernels.Q8_1_BLOCK_BYTES + assert np.all(hq[:per] == 0xA5) and np.all(hq[5 * per:] == 0xA5) + got, want = hq[per: 5 * per].reshape(-1, 36), emu.swiglu_q8_1(g, up, gpu_expf_neg(g)).reshape(-1, 36) + gh, wh = (b[:, :4].copy().view(np.uint16) for b in (got, want)) # each block's fp16 d and s + nan_h = ((wh & 0x7C00) == 0x7C00) & ((wh & 0x3FF) != 0) + assert nan_h[nf // 32, 1] and nan_h[nf // 32 + 1].all() and nan_h.sum() == 3 # the planted NaN halves + assert np.array_equal(got[:, 4:], want[:, 4:]) # every code bit for bit + # every half bit for bit, the NaN ones sm_120's 0x7fff (nan.md) + assert np.array_equal(gh, wh) and np.all(gh[nan_h] == 0x7FFF), np.flatnonzero(np.any(gh != wh, axis=1)) + with np.errstate(over="ignore", under="ignore", invalid="ignore"): + h = (g / (F32(1) + gpu_expf_neg(g))) * up + sub = np.count_nonzero((h != 0) & (np.abs(h) < F32(2.0 ** -126))) + assert sub > 50, sub # ieee_mul's subnormal path ran + print(f"\nSwiGLU + q8_1 edges: {g.size} values bit for bit, {sub} subnormal products") + + +# ---- float64 references ------------------------------------------------------------------------------------------ + +def dequant_q8_1(xq, n): + """q8_1 rows back to float64: d * code (iq_multi_parity.cpp:99-109).""" + b = np.asarray(xq, np.uint8).reshape(-1, 36) + return (b[:, :2].copy().view(np.float16).astype(np.float64) * b[:, 4:].view(np.int8)).reshape(-1, n) + + +def test_stages_against_float64(): + """Each stage of check_grouped's call against a float64 product over the GPU dequantizer's weights (iq_parity + checks it against gguf-py; basalt_dequant.metal) and the dequantized q8_1 rows each stage reads: gate and up on the + tokens' rows, down on the GPU's q8_1 of the SwiGLU product. iq_multi_parity's check_mmvq bound for these Q2_0 rows + (the nearest basalt has for the expert's call arithmetic), quoted: ``if (diff != 0 || !finite || !(rel < 1e-2)) + {`` (iq_multi_parity.cpp:162), rel = sum |y - ref| / sum |ref| over the stage's outputs (:150-160); diff, the + bitwise check against the other kernels, is test_check_grouped's.""" + c = grouped_case() + r = c.run() + blk = kernels.Q8_1_BLOCK_BYTES + rel, worst = {}, {} + for part, n_in, n_out in (("gate", c.n_embd, c.n_ff), ("up", c.n_embd, c.n_ff), ("down", c.n_ff, c.n_embd)): + num = den = 0.0 + finite = True + per_entry = [] + for g in range(len(c.grp_off)): + ents = range(c.grp_start[g], c.grp_start[g + 1]) + if not ents: + continue + w = gpu.dequant(42, c.blob(ents[0], part), n_in * n_out).reshape(n_out, n_in).astype(np.float64) + if part == "down": + x = dequant_q8_1(q8_rows(r["hq"], list(ents), n_in), n_in) + y = r["out"][c.ent_dst[list(ents)]] + else: + x = dequant_q8_1(q8_rows(c.xq, c.ent_tok[list(ents)], n_in), n_in) + y = r[part][list(ents)] + ref = x @ w.T + finite = finite and np.isfinite(y).all() + num += np.abs(y - ref).sum() + den += np.abs(ref).sum() + per_entry += list(np.abs(y - ref).sum(axis=1) / (np.abs(ref).sum(axis=1) + 1e-30)) + rel[part], worst[part] = num / (den + 1e-30), max(per_entry) + # basalt: if (diff != 0 || !finite || !(rel < 1e-2)) { -- over the call, and here per entry as well + assert finite and rel[part] < 1e-2 and worst[part] < 1e-2, (part, rel[part], worst[part]) + print("\nstages against float64: " + ", ".join(f"{k} rel {v:.2e} (worst entry {worst[k]:.2e})" + for k, v in rel.items())) + raw = c.blob(0, "gate")[: 64 * c.lay["gu_row"]].reshape(64, -1) + assert np.array_equal(gpu.dequant(42, raw, 64 * c.n_embd).reshape(64, -1), gguf_reference.dequantize(42, raw)) + + +def test_whole_expert_against_float64(): + """The contract's reference for native_expert_grouped (docs/design/flash-next.md, the table of kernels without a + basalt reference): the whole expert (gate/up, SwiGLU, the q8_1 of the product, down) against a float64 expert on + the fp32 activations, built as native_expert_parity.cpp builds it (:46-78, :387-402): 3 tokens of N(0, 1) values, + 2560 x 640, row r's weights 0.02 (0.5 + (r % 7) / 7) N(0, 1) quantized to Q2_0 (tools/gguf_writer.py's + quantize_q2_0; basalt's test calls ggml's quantizer, and has no Q2_0 pair) and dequantized on the host by ggml's + dequantize_row_q2_0 (tests/contract/gguf_reference.py; tools/gguf_writer.py's dequantize_q2_0 mirrors it), as + basalt's reference takes ggml's to_float (:56-61); h = (float) (g / (1 + exp(-g)) * u) in double; out = D h in + double. Criterion, quoted: ``const bool ok = ec < 3e-2 && eg < 3e-2 && std::isfinite(ec) && std::isfinite(eg);`` + (native_expert_parity.cpp:368), eg the GPU's relative L1 error (:38-42); ec, the CPU tier's, belongs to the CPU + expert's port.""" + n_embd, n_ff, nt = 2560, 640, 3 + rng = np.random.default_rng(11) + + def quant(rows, cols): + scale = (0.02 * (0.5 + (np.arange(rows) % 7) / 7.0)).astype(F32)[:, None] + return quantize_q2_0(scale * rng.standard_normal((rows, cols)).astype(F32)) + + blob = np.concatenate([quant(n_ff, n_embd), quant(n_ff, n_embd), quant(n_embd, n_ff)]) + lay = kernels.basalt_expert_layout(n_embd, n_ff) + G, U, D = (gguf_reference.dequantize(42, blob[o: o + rows * row].reshape(rows, row)).astype(np.float64) + for o, rows, row in ((0, n_ff, lay["gu_row"]), (lay["up_off"], n_ff, lay["gu_row"]), + (lay["down_off"], n_embd, lay["d_row"]))) + x = rng.standard_normal((nt, n_embd)).astype(F32) + g, u = x.astype(np.float64) @ G.T, x.astype(np.float64) @ U.T + h = (g / (1.0 + np.exp(-g)) * u).astype(F32) + ref = (h.astype(np.float64) @ D.T).astype(F32) + got = gpu.experts(blob, [0], [0, nt], np.arange(nt), np.arange(nt), gpu.q8_1(x.reshape(-1), "ieee"), n_embd, n_ff, + nt)["out"] + eg = np.abs(got.astype(np.float64) - ref).sum() / (np.abs(ref.astype(np.float64)).sum() + 1e-30) + print(f"\nwhole expert Q2_0/Q2_0 {n_embd} x {n_ff}, {nt} tokens: gpu rel {eg:.2e}") + # basalt: const bool ok = ec < 3e-2 && eg < 3e-2 && std::isfinite(ec) && std::isfinite(eg); + assert np.isfinite(eg) and eg < 3e-2 and np.isfinite(got).all(), eg diff --git a/tests/kernels/test_basalt_iq_parity.py b/tests/kernels/test_basalt_iq_parity.py new file mode 100644 index 00000000..2815fdf5 --- /dev/null +++ b/tests/kernels/test_basalt_iq_parity.py @@ -0,0 +1,84 @@ +# SPDX-License-Identifier: MIT +# Copyright (c) 2026 Jesús Gulfo +# The fixtures follow basalt (jesdga95/basalt) tools/iq_fixture.py and tools/gguf_writer.py's quantize_q2_0 +# @ b4c63b55754637f4c72ad53a0f791d425f71eb36 (MIT; third_party/NOTICE). +"""basalt's iq_parity (src/kernels/iq_parity.cpp) on Metal, for this pack's types it checks: Q2_0, Q3_K, IQ4_NL and +IQ4_XS (its six other types go to iq_mmvq, outside this pack). + +- Fixtures: tools/iq_fixture.py's, byte for byte (its defaults: seed 7, 32 rows of 256 values). numpy's + RandomState((seed, kernel id)) drives every choice: Q3_K, IQ4_NL and IQ4_XS are random bytes with each block's fp16 + scale set to 1.0; Q2_0 is quantize_q2_0 of standard normal values. The reference values are gguf-py's dequantizers + (tests/contract/gguf_reference.py: llama.cpp's own numpy code, with ggml's dequantize_row_q2_0 for Q2_0, as basalt's + tools/gguf_writer.py's codec decodes it). +- dq_err: basalt's dequantizer (kernels/common/basalt_dequant.metal) against the reference, a relative L1 error. +- The dot: activations N(0, 1), 8 columns of 256 values, quantized once by the IEEE quantizer; one-column calls, + then 2..8 columns, each column bitwise equal to its one-column call; mm_err = sum |y - ref . x| / sum |ref . x| + over the eight columns, ref . x in float64 on the float activations (iq_parity.cpp:103-111). +- Pass criterion, quoted (iq_parity.cpp:112): ``const bool ok = dq_err < 1e-6 && mm_err < 2e-2 && multi_bad == 0;``""" + +import struct + +import numpy as np +import pytest + +from tests.contract import gguf_reference +from tests.kernels import basalt_gpu as gpu + +KERNEL_IDS = {"IQ4_NL": 20, "IQ4_XS": 23, "Q2_0": 42, "Q3_K": 11} # iq_fixture.py KERNEL_IDS, this pack's +LAYOUT = {"IQ4_NL": (32, 18), "IQ4_XS": (256, 136), "Q3_K": (256, 110)} # (block values, block bytes) +SEED, ROWS, COLS, MC = 7, 32, 256, 8 # iq_fixture.py defaults; iq_parity's MC +HALF_ONE = np.frombuffer(struct.pack(", whose stream + is library-specific; the port draws the same distributions from numpy. The outputs start apart (0xFE one-row, 0xFF + _cols) where basalt's cudaMalloc leaves them unset, so an output neither call writes fails. +- ple_parity's native PLE value check (src/kernels/ple_parity.cpp:785-818) as a standalone test, for the one-row kernel + and the multi kernel (T = 2 to 8) at 2560 to 2560: the witness of halfway BF16 values (:789) against the float64 + sum over the weights' bits (:790-799), criterion quoted: + ``const bool correct = le(rel, 2e-6) && nf == 0 && gt(separation, 1e-5);`` (:815). basalt's weights are the PLE + fixture's ple_value, and the test runs only with PLE_FIXTURE_DIR; here they are route_window_parity's + bf16(N(0, 1) * 0.05). The separation's comparand, basalt's legacy path (the activations rounded to BF16, then + bf16_gemv; ple.cu:315-317), is the float64 sum over the BF16-rounded witness. Each multi-kernel row takes the + witness shifted by its row index and meets the same criterion. +- Column invariance, bitwise: each output is bit-identical to a one-row launch of its own (native_bf16.cu:75-77): + the multi kernel at T = 1 to 8 (NT 4 and 8), _cols at T = 9 and 17 (a chunk of one runs the one-row kernel), the + multi kernel for one row with ldy < n_out (native_bf16.cu:141), and strided ldx and ldy, whose gaps stay unread and + unwritten, at block sizes 32, 96 and 256. +- Bit for bit against the numpy emulation of docs/research/basalt-nvcc/bf16.md (tests/kernels/basalt_emu.py) at + block sizes 32, 96, 192 and 256, with pair counts that leave threads idle, and with planted subnormal weights, + subnormal activations, subnormal products and a subnormal block sum, each of which .FTZ turns into +0, and exact + FMA results just below 2^-126, which FFMA.FTZ rounds up to 2^-126 before it flushes.""" + +import numpy as np +import pytest + +from monolith import kernels +from tests.kernels import basalt_emu as emu +from tests.kernels import basalt_gpu as gpu + +F32 = np.float32 + + +def bf16_weights(rng, n_out, n_in): + """route_window_parity.cpp:34: bf16(nd(rng) * 0.05f), the float32 product rounded to BF16 (nearest even).""" + return emu.bf16_bits(rng.standard_normal((n_out, n_in)).astype(F32) * F32(0.05)) + + +def weight_values(w): + return (np.asarray(w, np.uint16).astype(np.uint32) << 16).view(F32) + + +def bits(a): + return np.ascontiguousarray(a, F32).view(np.uint32) + + +def one_row(w, x, n_in, n_out): + return np.stack([gpu.mmvf(w, row, n_in, n_out, fill=0xFE) for row in x]) + + +@pytest.mark.parametrize("n_out", [256, 1, 128, 512]) +def test_route_window_parity(n_out): + n = 2560 + rng = np.random.default_rng(7 + n_out) + for t in (2, 3, 4, 6): + w = bf16_weights(rng, n_out, n) + x = rng.standard_normal((t, n)).astype(F32) + y1 = one_row(w, x, n, n_out) + yn = gpu.mmvf_cols(w, x, n, n_out, t, fill=0xFF) + assert np.isfinite(y1).all() and np.isfinite(yn).all(), (n_out, t) + # basalt: ``const bool same = std::memcmp(y1.data(), yn.data(), y1.size() * 4) == 0;`` (:48) + assert y1.tobytes() == yn.tobytes(), (n_out, t) + + +def rel_l1(a, b): + """ple_parity.cpp:64-78: sum |a - b| / sum |a| (floored at 1e-30) in float64 over the finite pairs, NaN if any + pair has a non-finite entry; and the count of those.""" + a, b = np.asarray(a, np.float64), np.asarray(b, np.float64) + ok = np.isfinite(a) & np.isfinite(b) + nf = int(np.count_nonzero(~ok)) + if nf: + return np.nan, nf + m = np.abs(a).sum() + return np.abs(a - b).sum() / (m if m > 1e-30 else 1e-30), 0 + + +def le(x, t): + return bool(np.isfinite(x) and x <= t) # ple_parity.cpp:48 + + +def gt(x, t): + return bool(np.isfinite(x) and x > t) # ple_parity.cpp:49 + + +def test_ple_value_float64(): + nd = 2560 + rng = np.random.default_rng(790) + w = bf16_weights(rng, nd, nd) + wv = weight_values(w).astype(np.float64) + i = np.arange(nd) + # :789 ``witness[i] = i % 7 == 0 ? 1.00390625f : -0.501953125f;`` (halfway between two BF16 values) + witness = np.where(i % 7 == 0, F32(1.00390625), F32(-0.501953125)).astype(F32) + + def check(native, x): + reference = (wv @ x.astype(np.float64)).astype(F32) # :790-799, float(sum) + legacy = (wv @ weight_values(emu.bf16_bits(x)).astype(np.float64)).astype(F32) + rel, nf = rel_l1(reference, native) + separation, _ = rel_l1(native, legacy) + # basalt: ``const bool correct = le(rel, 2e-6) && nf == 0 && gt(separation, 1e-5);`` (:815) + assert le(rel, 2e-6) and nf == 0 and gt(separation, 1e-5), (rel, nf, separation) + return rel + + rels = [check(gpu.mmvf(w, witness, nd, nd, fill=0xFE), witness)] + for t in range(2, 9): + x = np.stack([np.roll(witness, k) for k in range(t)]) + y = gpu.mmvf(w, x, nd, nd, t, fill=0xFF).reshape(t, nd) + rels += [check(y[k], x[k]) for k in range(t)] + print(f"ple value rel_l1: max {max(rels):.3e}") + + +@pytest.mark.parametrize("n_in", [2560, 64, 130], ids=["block256", "block32", "block96"]) +def test_column_invariance(n_in): + n_out = 37 + rng = np.random.default_rng(n_in) + w = bf16_weights(rng, n_out, n_in) + x = rng.standard_normal((17, n_in)).astype(F32) + single = one_row(w, x, n_in, n_out) + # every output bit-identical to a one-row launch of its own (native_bf16.cu:75-77); T = 1 is the one-row kernel + for t in range(1, 9): + multi = gpu.mmvf(w, x[:t], n_in, n_out, t, fill=0xFF).reshape(t, n_out) + assert np.array_equal(bits(multi), bits(single[:t])), t + for t in (9, 17): # chunks 8 + 1 and 8 + 8 + 1 + cols = gpu.mmvf_cols(w, x[:t], n_in, n_out, t, fill=0xFF) + assert np.array_equal(bits(cols), bits(single[:t])), t + # one row with ldy < n_out takes the multi kernel (native_bf16.cu:141) + assert kernels.basalt_mmvf_macros(n_in, n_out, 1, ldy=n_out - 1)["NT"] == "4" + one = gpu.mmvf(w, x[0], n_in, n_out, 1, ldy=n_out - 1, fill=0xFF) + assert np.array_equal(bits(one), bits(single[0])) + # strided rows: NaN in the activation gaps, the output gaps keep their fill + for t in (3, 6): + ldx, ldy = n_in + 6, n_out + 5 + xs = np.full((t, ldx), np.nan, F32) + xs[:, :n_in] = x[:t] + out = gpu.mmvf(w, xs.reshape(-1)[: (t - 1) * ldx + n_in], n_in, n_out, t, ldx, ldy, fill=0xFF) + at = (np.arange(t)[:, None] * ldy + np.arange(n_out)).reshape(-1) + assert np.array_equal(bits(out[at]), bits(single[:t]).reshape(-1)), t + gap = np.setdiff1d(np.arange(out.size), at) + assert (bits(out[gap]) == 0xFFFFFFFF).all(), t + + +EMU_CASES = [(2, 5, 1), (64, 33, 3), (130, 17, 5), (700, 9, 2), (1000, 7, 8), (2560, 128, 1), (2560, 512, 4), + (2560, 1, 8), (2560, 2560, 1)] + + +@pytest.mark.parametrize("case", EMU_CASES, ids=[f"{a}x{b}x{c}" for a, b, c in EMU_CASES]) +def test_matches_emulation(case): + n_in, n_out, t = case + rng = np.random.default_rng(n_in * 31 + n_out) + w = bf16_weights(rng, n_out, n_in) + x = rng.standard_normal((t, n_in)).astype(F32) + got = gpu.mmvf(w, x, n_in, n_out, t, fill=0xFF).reshape(t, n_out) + want = emu.mmvf(w, x, kernels.basalt_mmvf_block(n_in)) + assert np.array_equal(bits(got), bits(want)) + + +def p2(e): + return np.ldexp(F32(1), e) # 2^e, exact (a subnormal below 2^-126) + + +def test_flush_to_zero(): + """Each .FTZ site of bf16.md planted so that the flush gives +0 where IEEE float32 arithmetic (the emulation + without flushes) gives a nonzero result: a subnormal product (row A times x0, output (0, 0)), a subnormal weight + (row B times x2, (2, 1)), a subnormal activation (row C times x1, (1, 2)) and a block sum whose last add is + subnormal (row D times x2, (2, 3): 2^-125 from warp 0 plus -1.75 * 2^-126 from warp 1). This GPU's arithmetic + flushes these itself (docs/research/basalt-nvcc/matvec.md, Notation), so the kernel would pass them without its + explicit flushes too. Then the other side of the flush: FFMA.FTZ rounds before it flushes (PTX ISA, fma.f32), so an + exact value in [2^-126 - 2^-150, 2^-126) gives 2^-126, where this GPU's fma gives +0 and fma_ftz rebuilds it: R1 + (2^-126 - 2^-151) at the first FMA of a pair, from +0; the second FMA from a normal acc (2^-126 - 2^-25 * 2^-126) + and its negative; and the tie 2^-126 - 2^-150, to 2^-126 (the even neighbour).""" + n_in, n_out = 2560, 8 + rng = np.random.default_rng(3) + x = np.stack([np.full(n_in, p2(-30), F32), np.full(n_in, p2(-140), F32), + rng.standard_normal(n_in).astype(F32)]) + x[2, [0, 64]] = p2(-65) + w = bf16_weights(rng, n_out, n_in) + w[4:, ::97], w[4:, 1::97] = 0x0003, 0x8005 # subnormal weights among normal ones + w[0], w[1], w[2], w[3] = 0x0D80, 0x0040, 0x5380, 0 # A 2^-100, B 2^-127 (subnormal), C 2^40, D + w[3, 0], w[3, 64] = emu.bf16_bits(p2(-60)), emu.bf16_bits(F32(-1.75) * p2(-61)) + got = gpu.mmvf(w, x, n_in, n_out, 3, fill=0xFF).reshape(3, n_out) + want = emu.mmvf(w, x, kernels.basalt_mmvf_block(n_in)) + assert np.array_equal(bits(got), bits(want)) + ieee = emu.mmvf(w, x, kernels.basalt_mmvf_block(n_in), flush=False) + for k, r in [(0, 0), (2, 1), (1, 2), (2, 3)]: + assert bits(got)[k, r] == 0 and ieee[k, r] != 0, (k, r) + # one pair (n_in 2): output (k, k) for k = 0, 1, 2 and (1, 3), on the one-row and the multi kernel + w = emu.bf16_bits(np.array([[31 * 2.0 ** -70, 0], [1, -2.0 ** -25], [2.0 ** -126, 0], [-1, 2.0 ** -25]], F32)) + x = np.array([[1082401 * 2.0 ** -81, 0], [2.0 ** -126, 2.0 ** -126], [1 - 2.0 ** -24, 0]], F32) + want = emu.mmvf(w, x, 32) + assert list(bits(want)[[0, 1, 2, 1], [0, 1, 2, 3]]) == [0x00800000, 0x00800000, 0x00800000, 0x80800000] + assert np.array_equal(bits(one_row(w, x, 2, 4)), bits(want)) + assert np.array_equal(bits(gpu.mmvf(w, x, 2, 4, 3, fill=0xFF).reshape(3, 4)), bits(want)) + + +def test_launch_rules(): + """basalt's mmvf_block_size and launcher routing (native_bf16.cu:124-203), values worked by hand.""" + assert [kernels.basalt_mmvf_block(n) for n in (2, 64, 66, 130, 700, 1000, 2560)] == [32, 32, 64, 96, 192, 256, 256] + assert kernels.basalt_mmvf_macros(2560, 128) == {"BLOCK": "256", "NT": "1"} + assert [kernels.basalt_mmvf_macros(2560, 1, t)["NT"] for t in (2, 4, 5, 8)] == ["4", "4", "8", "8"] + assert kernels.basalt_mmvf_cols(17) == [(0, 8), (8, 8), (16, 1)] + for bad in [(2559, 1, 1, None), (0, 1, 1, None), (2560, 0, 1, None), (2560, 1, 9, None), (2560, 1, 2, 2561)]: + with pytest.raises(ValueError): + kernels.basalt_mmvf_macros(*bad) diff --git a/tests/kernels/test_basalt_mmvq.py b/tests/kernels/test_basalt_mmvq.py new file mode 100644 index 00000000..bcde0a43 --- /dev/null +++ b/tests/kernels/test_basalt_mmvq.py @@ -0,0 +1,235 @@ +# SPDX-License-Identifier: MIT +# Copyright (c) 2026 Jesús Gulfo +# adapted from basalt (jesdga95/basalt) src/kernels/mmvq_multi_parity.cpp @ b4c63b55754637f4c72ad53a0f791d425f71eb36 +# (MIT; third_party/NOTICE): its cases, sane_half, widths, seeds and Q8_0 geometries, compare_q80's float64 reference +# and output pre-fills, and its pass criteria. +"""basalt's native_mmvq on Metal (kernels/common/basalt_mmvq.metal), one column and several, for the ten GGUF types. + +- mmvq_multi_parity, ported (basalt src/kernels/mmvq_multi_parity.cpp): the cases of :69-77 at widths 1, 2, 3, 4, 5, + 6, 8 with weights of random bytes and fp16 scales in +-[2^-10, 2^-5) (:79-83) and N(0, 1) activations quantized + once by the IEEE quantizer (:143-145); T columns against T one-column calls, criterion quoted: + ``if (exact && diff != 0) ++bad;`` (:215), any non-finite output fails (:531-535). Its negative control: the + upstream layout must differ somewhere at T > 4 in every case, else ``if (off.powerless_cases != 0) {`` (:555) + fails for lack of power. The tensor-core section (:333-348) is skipped as basalt skips it without int8 tensor + cores. The Q8_0 one-column section (:390-472): the one-column call bitwise column 0 of a two-column call and + ``const bool ok = diff == 0 && worst <= 1e-4 * (scale + 1e-30);`` (:461) against a float64 dot on the same bytes. +- New float64 references under :461's rule for Q4_0, Q5_0, Q4_K, Q5_K and Q6_K, which basalt does not check + against a reference (pr-b-scope-basalt.md section 3.7). +- Bitwise invariance for every type: each column of a T-column call equals the one-column call, T = 1 to 8, in the + small-K and the regular layout. +- Bit for bit against the numpy emulation of the arithmetic nvcc compiles (tests/kernels/basalt_emu.py).""" + +import numpy as np +import pytest + +from tests.kernels import basalt_emu as emu +from tests.kernels import basalt_gpu as gpu + +F32 = np.float32 +NAMES = {2: "Q4_0", 6: "Q5_0", 8: "Q8_0", 20: "IQ4_NL", 11: "Q3_K", 12: "Q4_K", 13: "Q5_K", 14: "Q6_K", 23: "IQ4_XS", + 42: "Q2_0"} +SCALES = {42: [0], 2: [0], 6: [0], 8: [0], 11: [108], 12: [0, 2], 13: [0, 2], 14: [208], 20: [0], 23: [0]} + + +def sane_halves(rng, n): + """mmvq_multi_parity.cpp:79-83: a normal fp16 in +-[2^-10, 2^-5): exponent field 5..9, any mantissa and sign.""" + return ((rng.integers(0, 2, n) << 15) | (rng.integers(5, 10, n) << 10) | rng.integers(0, 1024, n)).astype(np.uint16) + + +def weights(type_id, n_in, n_out, rng): + div, _, _, bb = emu.TRAITS[type_id] + nb = n_out * (n_in // div) + w = rng.integers(0, 256, (nb, bb), dtype=np.uint8) + for at in SCALES[type_id]: + w[:, at: at + 2] = sane_halves(rng, nb).view(np.uint8).reshape(nb, 2) + return w.reshape(n_out, -1) + + +def activations(n_in, ncols, rng, kind="ieee"): + x = rng.standard_normal(ncols * n_in).astype(F32) + return x, gpu.q8_1(x, kind) + + +def columns(xq, n_in, j): + qcol = n_in // 32 * 36 + return xq[j * qcol: (j + 1) * qcol] + + +CASES = [("Q4_0", 2, 2048, 512), ("Q8_0", 8, 2048, 512), ("Q4_K", 12, 2048, 512), ("Q5_K", 13, 2048, 512), + ("Q6_K", 14, 2048, 512), ("IQ4_XS", 23, 4096, 512), ("Q5_K wide", 13, 4096, 2048)] +WIDTHS = [1, 2, 3, 4, 5, 6, 8] + + +def multi_vs_single(type_id, n_in, n_out, t, upstream, seed): + rng = np.random.default_rng(seed) + w = weights(type_id, n_in, n_out, rng) + _, xq = activations(n_in, t, rng) + # outputs pre-filled apart, so a row neither call writes differs; the multi side's 0xff is NaN, so an unwritten + # row of the control's layout is non-finite and cannot pass for its power + multi = gpu.mmvq(type_id, w, xq, n_in, n_out, t, upstream=upstream, fill=0xFF) + single = np.stack([gpu.mmvq(type_id, w, columns(xq, n_in, j), n_in, n_out, 1, fill=0xFE)[0] for j in range(t)]) + return multi, single + + +@pytest.mark.parametrize("case", CASES, ids=[c[0] for c in CASES]) +def test_mmvq_multi_parity(case): + name, type_id, n_in, n_out = case + bad = nonfinite = 0 + for t in WIDTHS: + multi, single = multi_vs_single(type_id, n_in, n_out, t, False, 1234 + type_id * 97 + t) + nonfinite += np.count_nonzero(~np.isfinite(multi)) + np.count_nonzero(~np.isfinite(single)) + bad += np.count_nonzero(multi.view(np.uint32) != single.view(np.uint32)) != 0 + # basalt: "any non-finite output fails" (:531-535) and ``if (exact && diff != 0) ++bad;`` (:215) + assert nonfinite == 0, name + assert bad == 0, name + + +@pytest.mark.parametrize("case", CASES, ids=[c[0] for c in CASES]) +def test_mmvq_multi_parity_negative_control(case): + """The upstream layout groups the partial sums differently above 4 columns: the comparison must see it. T = 1 is + the one-column launch in both sweeps, as in basalt (ncols 1 never reaches launch_multi).""" + name, type_id, n_in, n_out = case + wide = nonfinite = 0 + for t in WIDTHS: + multi, single = multi_vs_single(type_id, n_in, n_out, t, True, 1234 + type_id * 97 + t) + nonfinite += np.count_nonzero(~np.isfinite(multi)) + np.count_nonzero(~np.isfinite(single)) + diff = np.count_nonzero(multi.view(np.uint32) != single.view(np.uint32)) + if t <= 4: + assert diff == 0, (name, t) # the layouts coincide up to 4 columns (4 SIMD-groups, 2 rows) + else: + wide += diff + # basalt: case_wide counts the differing finite outputs at T > 4; ``if (off.powerless_cases != 0) {`` (:555) fails + assert nonfinite == 0 and wide > 0, name + + +def half_to_double(h): + return h.view(np.float16).astype(np.float64) + + +Q80_GEOMS = [(2560, 12288), (6144, 2560), (2560, 512), (2560, 2048), (512, 640), (1024, 130), (2560, 1)] + + +@pytest.mark.parametrize("geom", Q80_GEOMS, ids=[f"{a}x{b}" for a, b in Q80_GEOMS]) +def test_q8_0_one_column(geom): + n_in, n_out = geom + rng = np.random.default_rng(4242 + n_in + n_out) + w = weights(8, n_in, n_out, rng) + x = rng.standard_normal(n_in).astype(F32) + xq = gpu.q8_1(np.concatenate([x, x]), "ieee") + a = gpu.mmvq(8, w, columns(xq, n_in, 0), n_in, n_out, 1, fill=0xFF)[0] # basalt's pre-fills (:426-427) + b = gpu.mmvq(8, w, xq, n_in, n_out, 2, fill=0xFE)[0] + ref = reference(8, w, columns(xq, n_in, 0), n_in, n_out) + diff = np.count_nonzero(a.view(np.uint32) != b.view(np.uint32)) + worst, scale = np.max(np.abs(a.astype(np.float64) - ref)), np.max(np.abs(ref)) + # basalt: ``const bool ok = diff == 0 && worst <= 1e-4 * (scale + 1e-30);`` (:461) + assert diff == 0 and worst <= 1e-4 * (scale + 1e-30), (diff, worst, scale) + + +def reference(type_id, w, xq, n_in, n_out): + """The float64 product on the same bytes: the weights' exact values (fp16 scales times integer codes) times the + q8_1 activations' d8 * code; for Q4_0 and Q5_0 the offset term takes the stored fp16 block sum s8, as the kernel's + definition does (native_mmvq.cu:693-695: ``d * (sumi * d8 - k * s8)``).""" + div, _, _, bb = emu.TRAITS[type_id] + blk = np.asarray(w, np.uint8).reshape(n_out, n_in // div, bb) + xb = np.asarray(xq, np.uint8).reshape(n_in // 32, 36) + d8 = half_to_double(xb[:, 0:2].copy().view(np.uint16)[:, 0]) + s8 = half_to_double(xb[:, 2:4].copy().view(np.uint16)[:, 0]) + a = xb[:, 4:].view(np.int8).astype(np.float64) + xv = (d8[:, None] * a).reshape(-1) # exact + h = lambda off: half_to_double(blk[..., off: off + 2].copy().view(np.uint16)[..., 0]) + if type_id in (8, 2, 6): + if type_id == 8: + c = blk[..., 2:34].view(np.int8).astype(np.float64) + else: + qs = blk[..., 6:22] if type_id == 6 else blk[..., 2:18] + c = np.concatenate([qs & 15, qs >> 4], axis=-1).astype(np.int64) + if type_id == 6: + qh = blk[..., 2:6].copy().view(np.uint32)[..., 0].astype(np.int64) + c = c | (((qh[..., None] >> np.arange(32)) & 1) << 4) + c = c.astype(np.float64) + y = ((h(0)[..., None] * c).reshape(n_out, -1) * xv).sum(axis=1) + if type_id != 8: + y -= (h(0) * (8.0 if type_id == 2 else 16.0) * s8[None, :]).sum(axis=1) + return y + if type_id in (12, 13): + sc = blk[..., 4:16] + sb = np.arange(8) + s, m = emu._scale_min_k4(np.broadcast_to(sc[..., None, :], sc.shape[:-1] + (8, 12)), sb[:, None]) + s, m = s[..., 0].astype(np.float64), m[..., 0].astype(np.float64) + qs = blk[..., 48:176] if type_id == 13 else blk[..., 16:144] + v = np.arange(256) + q = (qs[..., 32 * (v // 64) + v % 32].astype(np.int64) >> (4 * ((v // 32) % 2))) & 15 + if type_id == 13: + q = q | (((blk[..., 16 + v % 32].astype(np.int64) >> (v // 32)) & 1) << 4) + val = h(0)[..., None] * s[..., v // 32] * q - h(2)[..., None] * m[..., v // 32] + return (val.reshape(n_out, -1) * xv).sum(axis=1) + if type_id == 14: + v = np.arange(256) + hh, l = v // 128, v % 128 + ql = blk[..., 64 * hh + l % 64].astype(np.int64) >> (4 * (l // 64)) & 15 + qh = blk[..., 128 + 32 * hh + l % 32].astype(np.int64) >> (2 * (l // 32)) & 3 + q = (ql | (qh << 4)) - 32 + sc = blk[..., 192:208].view(np.int8).astype(np.float64) + val = h(208)[..., None] * sc[..., v // 16] * q + return (val.reshape(n_out, -1) * xv).sum(axis=1) + raise ValueError(type_id) + + +REF_TYPES = [8, 2, 6, 12, 13, 14] +REF_SHAPES = [(2560, 640), (640, 2560), (6144, 512), (2048, 512)] + + +@pytest.mark.parametrize("type_id", REF_TYPES, ids=[NAMES[t] for t in REF_TYPES]) +def test_float64_reference(type_id): + """mmvq_multi_parity.cpp:461's rule, for the types basalt leaves without a reference (and Q8_0 again at this + pack's shapes): worst |y - ref| <= 1e-4 * max |ref| on the same q8_1 bytes, one column and every column of 8.""" + for n_in, n_out in REF_SHAPES: + if n_in % emu.TRAITS[type_id][0]: + continue + rng = np.random.default_rng(type_id * 1000 + n_in) + w = weights(type_id, n_in, n_out, rng) + _, xq = activations(n_in, 8, rng, "native") + y8 = gpu.mmvq(type_id, w, xq, n_in, n_out, 8) + for j in range(8): + ref = reference(type_id, w, columns(xq, n_in, j), n_in, n_out) + worst, scale = np.max(np.abs(y8[j].astype(np.float64) - ref)), np.max(np.abs(ref)) + assert np.all(np.isfinite(y8[j])) and worst <= 1e-4 * (scale + 1e-30), (n_in, n_out, j, worst, scale) + + +# n_in for each type's small-K and regular layout (small K: fewer blocks per row than BPI) +SHAPES = {2: (640, 2560), 6: (640, 2560), 20: (640, 2560), 8: (640, 2560), 11: (1024, 2560), 12: (1024, 2560), + 13: (1024, 6144), 14: (512, 2560), 23: (2560, 4096), 42: (2560, 6144)} + + +@pytest.mark.parametrize("type_id", sorted(NAMES), ids=[NAMES[t] for t in sorted(NAMES)]) +def test_column_invariance(type_id): + """Every column of a T-column call equals basalt's one-column call (its own launch: 4 rows per threadgroup for + small K) bit for bit, T = 1 to 8.""" + for n_in in SHAPES[type_id]: + n_out = 71 # odd: a row tail for ROWS 2 and 4 + rng = np.random.default_rng(type_id + n_in) + w = weights(type_id, n_in, n_out, rng) + _, xq = activations(n_in, 8, rng, "native") + single = np.stack([gpu.mmvq(type_id, w, columns(xq, n_in, j), n_in, n_out, 1, fill=0xFE)[0] for j in range(8)]) + assert np.all(np.isfinite(single)) + for t in range(1, 9): + multi = gpu.mmvq(type_id, w, xq[: t * (n_in // 32) * 36], n_in, n_out, t, fill=0xFF) + assert np.array_equal(multi.view(np.uint32), single[:t].view(np.uint32)), (n_in, t) + + +@pytest.mark.parametrize("type_id", sorted(NAMES), ids=[NAMES[t] for t in sorted(NAMES)]) +def test_emulation_bit_for_bit(type_id): + """The kernel against the numpy emulation of what nvcc compiles, one column and three, both layouts' K.""" + for n_in in SHAPES[type_id]: + n_out = 37 + rng = np.random.default_rng(99 + type_id + n_in) + w = weights(type_id, n_in, n_out, rng) + x = rng.standard_normal(3 * n_in).astype(F32) + x[: 64] = 0.0 # all-zero q8_1 blocks + xq = gpu.q8_1(x, "native") + for t in (1, 3): + got = gpu.mmvq(type_id, w, xq[: t * (n_in // 32) * 36], n_in, n_out, t) + want = emu.mmvq(type_id, w, xq[: t * (n_in // 32) * 36], n_in, n_out, t) + assert np.array_equal(got.view(np.uint32), want.view(np.uint32)), (n_in, t) + up = gpu.mmvq(type_id, w, xq, n_in, n_out, 3, upstream=True) # the upstream layout's NW = 4 at 3 columns + assert np.array_equal(up.view(np.uint32), emu.mmvq(type_id, w, xq, n_in, n_out, 3).view(np.uint32)) diff --git a/tests/kernels/test_basalt_nan.py b/tests/kernels/test_basalt_nan.py new file mode 100644 index 00000000..668c7d76 --- /dev/null +++ b/tests/kernels/test_basalt_nan.py @@ -0,0 +1,312 @@ +"""The NaN every basalt port kernel stores is sm_120's (docs/research/basalt-nvcc/nan.md): 0x7fffffff in fp32 and +0x7fff in an fp16 half, where this GPU's arithmetic gives 0x7fc00000 and its half() 0x7e00. + +Each test plants inputs that make a NaN reach a store the page marks (a NaN or infinite fp16 weight scale, an infinite +scale against a block of zero activations, NaN and infinite activations) and runs the kernel twice: as built, and as +the negative control with ``cuda_nan`` and ``cuda_nan_f16`` taken out of the kernel sources (``basalt_fp.metal``, which +defines them, unchanged). ``check`` then requires that every planted value is NaN and sm_120's, that the control +stores another NaN there, and that the rewrite changes nothing else: the same values are NaN in both runs, and every +other value has the same bits. The drafter experts' stores have their own tests (test_basalt_s2_experts.py).""" + +import numpy as np +import pytest + +from monolith import kernels +from tests.kernels import basalt_emu as emu +from tests.kernels import basalt_gpu as gpu +from tests.kernels.test_basalt_experts import Call +from tests.kernels.test_basalt_mmvq import SCALES, weights +from tests.kernels.test_basalt_q5k_head import weights as q5k_weights + +F32 = np.float32 +NAN16, INF16 = 0x7E00, 0x7C00 # an fp16 NaN and +inf, planted as weight or activation scales +SOURCES = ("basalt_q8_1_source", "basalt_mmvq_source", "basalt_experts_source", "basalt_dequant_source", + "basalt_mmvf_source", "basalt_dense_tc_source", "basalt_q5k_head_source") + + +@pytest.fixture +def hw(monkeypatch): + """``hw(call)``: ``call()`` with every port kernel storing this GPU's NaN, the negative control.""" + fp = kernels.PRELUDE + kernels.template("basalt_fp.metal") + + def run(call): + with monkeypatch.context() as m: + for name in SOURCES: + src = getattr(kernels, name)() + assert src.startswith(fp) + body = src[len(fp):].replace("cuda_nan_f16(", "(").replace("cuda_nan(", "(") + m.setattr(kernels, name, lambda s=fp + body: s) + return call() + return run + + +def check(got, ctl, at, fp16=False): + """``at``: the values a planted NaN reaches. Returns how many there are.""" + u = np.uint16 if fp16 else np.uint32 + canon, inf = (0x7FFF, 0x7C00) if fp16 else (0x7FFFFFFF, 0x7F800000) + g, c = (np.ascontiguousarray(a).view(u) for a in (got, ctl)) + gn, cn = (g & canon) > inf, (c & canon) > inf + assert np.count_nonzero(at) and np.all(gn[at]), "a planted NaN did not reach the store" + assert np.all(g[gn] == canon), [hex(int(v)) for v in np.unique(g[gn])] + assert np.all(c[at] != canon), "the control stores sm_120's NaN too: the test has no power" + assert np.array_equal(gn, cn) and np.array_equal(g[~gn], c[~gn]), "the rewrite changed more than NaN bits" + return int(np.count_nonzero(at)) + + +def put16(a, at, value): + """Write the fp16 bits ``value`` into the byte array ``a`` at byte offset ``at``.""" + a.reshape(-1)[at: at + 2] = np.array([value], np.uint16).view(np.uint8) + + +def halves(q): + """Each q8_1 block's (d, s) fp16 bits, and its codes.""" + b = np.asarray(q, np.uint8).reshape(-1, 36) + return b[:, :4].copy().view(np.uint16), b[:, 4:] + + +# ---- the q8_1 quantizers ----------------------------------------------------------------------------------------- + +@pytest.mark.parametrize("kind", ["native", "ieee", "swiglu"]) +def test_q8_1_halves(hw, kind): + """q8_1_put: a NaN lane makes its block's sum NaN, an all-NaN block its scale and sum, +inf and -inf in one block + its sum (an infinity alone is clamped to 65504). For the SwiGLU quantizer the gates make those values.""" + rng = np.random.default_rng(1) + x = rng.standard_normal(8 * 32).astype(F32) + up = rng.standard_normal(x.size).astype(F32) + x[32 + 3] = np.nan + x[64: 96] = np.nan + if kind == "swiglu": + x[97], x[98], up[97], up[98] = np.inf, np.inf, 1.0, -1.0 # SiLU(inf) * +-1: +inf and -inf + else: + x[97], x[98] = np.inf, -np.inf + x[160 + 4] = np.inf # block 5: no NaN + run = lambda: halves(gpu.q8_1(x, kind, up if kind == "swiglu" else None)) + (got, codes), (ctl, ctl_codes) = run(), hw(run) + at = np.zeros_like(got, bool) + at[1, 1] = at[2, 0] = at[2, 1] = at[3, 1] = True + assert check(got, ctl, at, fp16=True) == 4 and np.array_equal(codes, ctl_codes) + + +# ---- native_mmvq ------------------------------------------------------------------------------------------------- + +@pytest.mark.parametrize("type_id", sorted(SCALES)) +def test_mmvq(hw, type_id): + """Row 1's first block: its fp16 scales +inf against a first superblock of zero activations (inf * 0, a NaN made); + row 2's: NaN (a NaN passed). One and three columns, at a small K (4 or 2 rows a threadgroup) and a large one (at + 4096 every type has at least BPI blocks a row: one row a threadgroup).""" + for n_in in (512, 4096): + rng = np.random.default_rng(type_id) + n_out = 16 + w = weights(type_id, n_in, n_out, rng) + for off in SCALES[type_id]: + put16(w[1], off, INF16) + put16(w[2], off, NAN16) + for ncols in (1, 3): + x = rng.standard_normal((ncols, n_in)).astype(F32) + x[:, :256] = 0.0 + xq = gpu.q8_1(x.reshape(-1), "ieee") + run = lambda: gpu.mmvq(type_id, w, xq, n_in, n_out, ncols, fill=0) + got, ctl = run(), hw(run) + at = np.zeros_like(got, bool) + at[:, 1:3] = True + check(got, ctl, at) + + +# ---- the dequantizers -------------------------------------------------------------------------------------------- + +@pytest.mark.parametrize("type_id", kernels.DEQUANT_TYPES) +def test_dequant(hw, type_id): + """Superblock 0's first block with a NaN scale; for Q2_0 also block 1 (values 64..127) with +inf, a NaN wherever + its code is 1 (d * 0).""" + rng = np.random.default_rng(2) + n = 4 * 256 + raw = weights(type_id, 256, n // 256, rng) + bb = emu.TRAITS[type_id][3] + put16(raw[0], SCALES[type_id][0], NAN16) + if type_id == 42: + put16(raw[0], bb + SCALES[42][0], INF16) + run = lambda: gpu.dequant(type_id, raw, n) + got, ctl = run(), hw(run) + at = np.zeros(n, bool) + at[: emu.TRAITS[type_id][0]] = True # the NaN block's values + if type_id == 42: + codes = np.unpackbits(raw[0, bb + 2: bb + 18][:, None], axis=1, bitorder="little").reshape(-1, 2) + at[64: 128] = codes @ [1, 2] == 1 + check(got, ctl, at) + + +# ---- the routed experts ------------------------------------------------------------------------------------------ + +@pytest.mark.parametrize("n_embd, n_ff, gu2, sub16", [(2560, 640, True, True), (2560, 640, False, False), + (512, 256, False, False)]) +def test_experts(hw, n_embd, n_ff, gu2, sub16): + """Groups of 1, 2, 3 and 7 entries (each batch size its own store, six then one for the seven), every blob with a + NaN scale in gate rows 5 and 8 (rows B and A of a two-row SIMD-group on the gu2 path) and in down row 7: gate[e, 5] + and gate[e, 8], the q8_1 sum of the intermediate's first block, and out[ent_dst[e], 7] are NaN for every entry.""" + rng = np.random.default_rng(3) + c = Call(rng, n_embd, n_ff, [1, 2, 3, 7], 5) + lay = c.lay + for o in c.grp_off: + put16(c.arena, o + 5 * lay["gu_row"], NAN16) + put16(c.arena, o + 8 * lay["gu_row"], NAN16) + put16(c.arena, o + lay["down_off"] + 7 * lay["d_row"], NAN16) + run = lambda: c.run(gu2=gu2, sub16=sub16, out_fill=0x00) + got, ctl = run(), hw(run) + ents = list(c.entries()) + at = np.zeros_like(got["gate"], bool) + at[ents, 5] = at[ents, 8] = True + check(got["gate"], ctl["gate"], at) + assert np.array_equal(got["up"].view(np.uint32), ctl["up"].view(np.uint32)) + gh, gcodes = halves(got["hq"]) + ch, ccodes = halves(ctl["hq"]) + at = np.zeros_like(gh, bool) + at[[e * (n_ff // 32) for e in ents], 1] = True # block 0 of each entry: its sum + check(gh, ch, at, fp16=True) + assert np.array_equal(gcodes, ccodes) + at = np.zeros_like(got["out"], bool) + at[c.ent_dst[ents], 7] = True + check(got["out"], ctl["out"], at) + + +# ---- the BF16 GEMVs ---------------------------------------------------------------------------------------------- + +@pytest.mark.parametrize("n_in, n_tok", [(64, 1), (512, 1), (512, 3), (512, 6)]) +def test_mmvf(hw, n_in, n_tok): + """Row 1's first weight a NaN, row 2's +inf against a zero first activation (inf * 0): the one-row kernel and the + multi kernel (NT 4, 8), threadgroups of 32 and of 256 threads.""" + rng = np.random.default_rng(4) + n_out = 8 + w = emu.bf16_bits(rng.standard_normal((n_out, n_in)).astype(F32) * F32(0.05)) + w[1, 0], w[2, 0] = 0x7FA5, 0x7F80 + x = rng.standard_normal((n_tok, n_in)).astype(F32) + x[:, 0] = 0.0 + run = lambda: gpu.mmvf(w, x, n_in, n_out, n_tok, fill=0).reshape(n_tok, n_out) + got, ctl = run(), hw(run) + at = np.zeros_like(got, bool) + at[:, 1:3] = True + check(got, ctl, at) + + +# ---- dense_tc ---------------------------------------------------------------------------------------------------- + +DTC_TYPES = (11, 12, 13, 14, 23, 42) + + +def dtc_case(type_id, rng, n_in=1024, n_out=32): + """Weights with row 1's first block's scales +inf (against zero activations: a NaN made) and row 17's NaN (the + second tile), and 8 columns whose first 256 values are 0.""" + w = weights(type_id, n_in, n_out, rng) + for off in SCALES[type_id]: + put16(w[1], off, INF16) + put16(w[17], off, NAN16) + x = rng.standard_normal((8, n_in)).astype(F32) + x[:, :256] = 0.0 + return w, gpu.q8_1(x.reshape(-1), "native") + + +@pytest.mark.parametrize("type_id", DTC_TYPES) +def test_dense_tc(hw, type_id): + """Every order (one, tile, s with KS 1 and 2) at 1, 3 and 8 columns.""" + w, xq = dtc_case(type_id, np.random.default_rng(5)) + for variant in ("one", "tile", "s1", "s2"): + run = lambda: gpu.dense_tc(type_id, w, xq, 1024, 32, (1, 3, 8), variant, fill=0) + got, ctl = run(), hw(run) + for t in (1, 3, 8): + at = np.zeros_like(got[t], bool) + at[:t, 1] = at[:t, 17] = True + check(got[t], ctl[t], at) + + +def test_dense_tc_pair(hw): + """dense_tc_pair, both matrices planted (Q4_K then Q2_0), at 2 and 8 columns.""" + rng = np.random.default_rng(6) + w0, xq = dtc_case(12, rng) + w1, _ = dtc_case(42, rng) + run = lambda: gpu.dense_tc_pair(12, w0, 32, 42, w1, 32, xq, 1024, (2, 8), fill=0) + got, ctl = run(), hw(run) + for t in (2, 8): + for k in (0, 1): + at = np.zeros_like(got[t][k], bool) + at[:t, 1] = at[:t, 17] = True + check(got[t][k], ctl[t][k], at) + + +# ---- the Q5_K head ----------------------------------------------------------------------------------------------- + +def test_q5k_head(hw): + """basalt_q5k_head at n_in 512, one and three columns: row 1's first block's d +inf against zero activations, row + 2's NaN.""" + rng = np.random.default_rng(7) + n_in, n_out = 512, 24 + w = q5k_weights(n_out, rng, n_in) + put16(w[1], 0, INF16) + put16(w[2], 0, NAN16) + for ncols in (1, 3): + x = rng.standard_normal((ncols, n_in)).astype(F32) + x[:, :256] = 0.0 + xq = gpu.q8_1(x.reshape(-1), "native") + run = lambda: gpu.q5k_head(w, xq, n_in, n_out, ncols) + got, ctl = run(), hw(run) + at = np.zeros_like(got, bool) + at[:, 1:3] = True + check(got, ctl, at) + + +def test_q5k_top1(hw): + """q5k_head_top1 with row 0's logit NaN (its first block's d NaN): the logit, threadgroup 0's partial sum (its + SIMD-group 0 holds only that row, so the threadgroup's merge starts from an empty top with a NaN sum) and the + merged probability are NaN; the partial maxima and the id are not.""" + rng = np.random.default_rng(8) + n_out = 640 # 80 threadgroups: one row a SIMD-group + w = q5k_weights(n_out, rng) + put16(w[0], 0, NAN16) + xq = gpu.q8_1(rng.standard_normal(2560).astype(F32), "native") + run = lambda: gpu.q5k_top1(w, xq, n_out) + (y, i, p, part), (cy, ci, cp, cpart) = run(), hw(run) + at = np.zeros(n_out, bool) + at[0] = True + check(y, cy, at) + at = np.zeros_like(part, bool) + at[0, 2] = True + check(part, cpart, at) + check(np.array([p]), np.array([cp]), np.array([True])) + assert i == ci + + +def test_q5k_proxy_score(hw): + """px::score_kernel on a copy of 64 rows (two tiles). An activation block with a NaN scale makes every score NaN: + each tile's maximum and its first candidate are NaN. Then, on positive activations, row 5 with every level 3 and + every scale +inf scores +inf, so tile 0's sum takes exp(inf - inf); row 32's NaN scales give tile 1's first + candidate a NaN.""" + rng = np.random.default_rng(9) + rows, n_cap = 64, 64 + q5 = q5k_weights(rows, rng) + proxy = gpu.q5k_proxy_pack(q5, n_cap, [(0, rows)]) + mp = np.arange(rows, dtype=np.int32) + xq = gpu.q8_1((np.abs(rng.standard_normal(2560)) + 0.1).astype(F32), "native") + + xa = xq.copy() + put16(xa, 0, NAN16) + run = lambda: gpu.q5k_proxy_score(proxy, xa, rows, n_cap, mp) + (cand, part), (ccand, cpart) = run(), hw(run) + at = np.zeros_like(part, bool) + at[:, 0] = True + check(part, cpart, at) + at = np.zeros_like(cand, bool) + at[:, 0, 0] = True + check(cand, ccand, at) + + pb = proxy.copy() # per (tile, 64 weights, row): a 16-byte word, then two scales + words = pb[: 2 * 40 * 32 * 16].reshape(2, 40, 32, 16) + sc = pb[2 * 40 * 32 * 16:].view(np.uint16).reshape(2, 40, 32, 2) + words[0, :, 5] = 0xFF + sc[0, :, 5] = INF16 + sc[1, :, 0] = NAN16 + run = lambda: gpu.q5k_proxy_score(pb, xq, rows, n_cap, mp) + (cand, part), (ccand, cpart) = run(), hw(run) + at = np.zeros_like(part, bool) + at[0, 1] = True + check(part, cpart, at) + at = np.zeros_like(cand, bool) + at[1, 0, 0] = True + check(cand, ccand, at) diff --git a/tests/kernels/test_basalt_ops_program.py b/tests/kernels/test_basalt_ops_program.py new file mode 100644 index 00000000..cb87b3da --- /dev/null +++ b/tests/kernels/test_basalt_ops_program.py @@ -0,0 +1,156 @@ +"""basalt's op family (monolith/ops/basalt.py) in compiled programs on the GPU: one static program per window width, +T = 1 .. 8 (basalt captures one graph per width), each running every kind over a synthetic .basalt file +(tests/contract/test_basalt_ops.py ``all_ops``): a native q8_1 per input width into every native_mmvq type and every +dense_tc type in every summation order, the pairs and the BF16 GEMVs on dense rows, the SwiGLU quantizer into a Q8_0 +down, the IEEE quantizer on its own. The file is bound through its windows, and again through exact per-tensor copies +(``BasaltSource(copy=True)``), so that shader validation bounds every read by its own tensor, not by a window that +holds its neighbours. + +- Each output bitwise equal to the merged single-kernel harness (tests/kernels/basalt_gpu.py) on the same bytes: the + q8_1 rows against the harness's quantizer on the same activations, each GEMV against the harness's launch on the + program's own q8_1 rows (or activations) and the file's weights. The program's outputs start as 0xff bytes, the + harness's as 0xfe, so a value neither writes cannot match. +- Window invariance at program level (docs/design/flash-next.md invariant 1, ``CONTRIBUTING.md:14`` of basalt): column + j of the T-wide program bitwise equal to the 1-wide program run on column j alone, every output finite. +- The eight programs share their weight windows: the same buffer names, and one buffer per name across the engines. +""" + +import numpy as np +import pytest + +from monolith.compiler import emit_program +from monolith.core import Graph +from monolith.packs.basalt import BasaltSource +from monolith.runtime import Engine +from tests.contract.test_basalt_ops import BF16, DTC, GGUF, MMVQ, PAIRS, PROFILE, all_ops, write_file +from tests.kernels import basalt_gpu as gpu +from tests.kernels.test_basalt_mmvf import bf16_weights +from tests.kernels.test_basalt_mmvq import weights + +F32 = np.float32 +WIDTHS = range(1, 9) +PIPELINES = {} # one pipeline cache for every engine of the module + + +def bits(a): + return np.ascontiguousarray(a, F32).view(np.uint32) + + +@pytest.fixture(scope="module", params=[False, True], ids=["windows", "exact-copies"]) +def runs(request, tmp_path_factory): + """The file's tensors, the activations (8 columns per input), the eight programs and engines, every output of the + T-wide program over columns 0 .. T - 1 (``wide[T]``) and of the 1-wide program over column j alone (``ones[j]``).""" + rng = np.random.default_rng(2026) + gguf = {n: (t, o, i, weights(t, i, o, rng).tobytes()) for n, (t, o, i) in GGUF.items()} + bf16 = {n: (o, i, bf16_weights(rng, o, i).tobytes()) for n, (o, i) in BF16.items()} + src = BasaltSource(write_file(tmp_path_factory.mktemp("ops") / "ops.basalt", gguf, bf16), copy=request.param) + graphs = {t: Graph("step") for t in WIDTHS} + for g in graphs.values(): + all_ops(g, src) + progs = {t: emit_program(g, pack=src, profile=PROFILE, t=t, tail=None) for t, g in graphs.items()} + g = graphs[1] + inputs = {v.name: rng.standard_normal((8, v.shape[1])).astype(F32) for v in g.values.values() if v.is_input} + outputs = {v.name: v.shape[1] * v.dtype.itemsize for o in g.ops for v in o.outputs} # bytes per column + dev = gpu.device() + engines = {8: Engine(progs[8], dev, pipeline_cache=PIPELINES)} + shared = {n: b for n, b in engines[8].buffers.items() if progs[8].buffers[n].role == "weights"} + for t in WIDTHS[:-1]: + engines[t] = Engine(progs[t], dev, buffers=shared, pipeline_cache=PIPELINES) + + def run(t, cols): + eng = engines[t] + for name, x in inputs.items(): + eng.buffers[name].write(x[cols].tobytes(), 0) + for name in outputs: + eng.buffers[name].fill(0xFF) + assert eng.run(1, steps_per_cb=1, in_flight=1).steps == 1 + return {name: eng.read(name, t * wb) for name, wb in outputs.items()} + + wide = {t: run(t, list(range(t))) for t in WIDTHS} + ones = [run(1, [j]) for j in range(8)] + return {"src": src, "gguf": gguf, "bf16": bf16, "progs": progs, "engines": engines, "inputs": inputs, + "outputs": outputs, "wide": wide, "ones": ones} + + +def test_programs_share_their_weight_windows(runs): + progs, engines, src = runs["progs"], runs["engines"], runs["src"] + names = {t: sorted(n for n, b in p.buffers.items() if b.role == "weights") for t, p in progs.items()} + assert names[8] and all(names[t] == names[8] for t in WIDTHS) + for t in WIDTHS: + assert all(engines[t].buffers[n] is engines[8].buffers[n] for n in names[t]) + assert all((progs[8].buffers[n].file is None) == src.copy for n in names[8]) + + +def test_q8_1_rows_are_the_harness(runs): + x = runs["inputs"] + for t in WIDTHS: + got = runs["wide"][t] + for name in got: + if name.startswith("xq") and name != "xq_ieee": + want = gpu.q8_1(x["x" + name[2:]][:t].ravel(), "native") + elif name == "hq": + want = gpu.q8_1(x["gate"][:t].ravel(), "swiglu", x["up"][:t].ravel()) + elif name == "xq_ieee": + want = gpu.q8_1(x["x2560"][:t].ravel(), "ieee") + else: + continue + assert got[name] == want.tobytes(), (name, t) + + +def _input_rows(runs, t, n_in, name): + """The q8_1 rows the program's GEMV ``name`` read at width t.""" + return np.frombuffer(runs["wide"][t]["hq" if name == "mmvq.down" else f"xq{n_in}"], np.uint8) + + +def _w(runs, name): + return np.frombuffer(runs["gguf"][name][3], np.uint8) + + +@pytest.mark.parametrize("name", sorted(MMVQ)) +def test_mmvq_is_the_harness(runs, name): + tid, n_out, n_in = GGUF[name] + for t in WIDTHS: + y = np.frombuffer(runs["wide"][t][f"y.{name}"], F32).reshape(t, n_out) + want = gpu.mmvq(tid, _w(runs, name), _input_rows(runs, t, n_in, name), n_in, n_out, t, fill=0xFE) + assert np.array_equal(bits(y), bits(want)), t + + +@pytest.mark.parametrize("name", sorted(DTC) + ["order.q4_k"]) +def test_dense_tc_is_the_harness(runs, name): + tid, n_out, n_in = GGUF[name] + for t in WIDTHS: + y = np.frombuffer(runs["wide"][t][f"y.{name}"], F32).reshape(t, n_out) + want = gpu.dense_tc(tid, _w(runs, name), _input_rows(runs, t, n_in, name), n_in, n_out, (t,), fill=0xFE)[t] + assert np.array_equal(bits(y), bits(want[:t])), t + + +@pytest.mark.parametrize("pair", PAIRS, ids=[f"{a}+{b}" for a, b in PAIRS]) +def test_dense_tc_pair_is_the_harness(runs, pair): + a, b = pair + (t0, n0, n_in), (t1, n1, _) = GGUF[f"pair.{a}.{b}.0"], GGUF[f"pair.{a}.{b}.1"] + for t in WIDTHS: + want = gpu.dense_tc_pair(t0, _w(runs, f"pair.{a}.{b}.0"), n0, t1, _w(runs, f"pair.{a}.{b}.1"), n1, + _input_rows(runs, t, n_in, ""), n_in, (t,), fill=0xFE)[t] + for m, n_out in enumerate((n0, n1)): + y = np.frombuffer(runs["wide"][t][f"y.pair.{a}.{b}.{m}"], F32).reshape(t, n_out) + assert np.array_equal(bits(y), bits(want[m][:t])), (t, m) + + +@pytest.mark.parametrize("name", sorted(BF16)) +def test_mmvf_is_the_harness(runs, name): + n_out, n_in, data = runs["bf16"][name] + for t in WIDTHS: + y = np.frombuffer(runs["wide"][t][f"y.{name}"], F32) + want = gpu.mmvf(np.frombuffer(data, np.uint16), runs["inputs"]["x2560"][:t], n_in, n_out, t, fill=0xFE) + assert np.array_equal(bits(y), bits(want)), t + + +def test_window_invariance(runs): + """Column j of every output of the T-wide program, bit for bit the 1-wide program's on column j alone.""" + for t in WIDTHS: + for name, wb in runs["outputs"].items(): + got = runs["wide"][t][name] + if name.startswith("y."): + assert np.all(np.isfinite(np.frombuffer(got, F32))), (name, t) + for j in range(t): + assert got[j * wb: (j + 1) * wb] == runs["ones"][j][name], (name, t, j) diff --git a/tests/kernels/test_basalt_platform.py b/tests/kernels/test_basalt_platform.py new file mode 100644 index 00000000..a0bf9d43 --- /dev/null +++ b/tests/kernels/test_basalt_platform.py @@ -0,0 +1,231 @@ +# SPDX-License-Identifier: MIT +# Copyright (c) 2026 Jesús Gulfo +# adapted from basalt (jesdga95/basalt) src/kernels/elementwise_parity.cpp @ b4c63b55754637f4c72ad53a0f791d425f71eb36 +# (MIT; third_party/NOTICE): the contraction check's pass criterion. +"""The platform facts the exact basalt port rests on, measured on this GPU in MTLMathModeSafe (the repository default): +fp32 add, multiply, fma and division round to nearest even; how they treat subnormals; fp16 conversions; and that +``#pragma STDC FP_CONTRACT OFF`` stops contraction in a runtime-compiled source, told apart the way basalt's +elementwise_parity does (src/kernels/elementwise_parity.cpp:410: ``if (mismatches || guards || fma_diff == 0) ++bad;`` +- the kernel must match the unfused result, and the inputs must be ones where fusing would change it).""" + +import numpy as np +import pytest + +from monolith import kernels +from monolith.runtime import _native as nt +from tests.kernels import basalt_emu as emu + +F32 = np.float32 +NCOL = 14 # one output column per operation of OPS + +OPS = """ +kernel void ops(device const float* a [[buffer(0)]], device const float* b [[buffer(1)]], + device const float* c [[buffer(2)]], device float* out [[buffer(3)]], + constant uint& n [[buffer(4)]], uint i [[thread_position_in_grid]]) { + if (i >= n) return; + const float x = a[i], y = b[i], z = c[i]; + device float* o = out + NCOL * i; + o[0] = x + y; + o[1] = x * y; + o[2] = fma(x, y, z); + o[3] = x / y; + o[4] = x * y + z; + o[5] = fmax(x, y); + o[6] = fabs(x); + o[7] = add_ftz(x, y); + o[8] = mul_ftz(x, y); + o[9] = fma_ftz(x, y, z); + o[10] = max_ftz(x, y); + o[11] = rcp_ftz(x); + o[12] = abs_ftz(x); + o[13] = fmin(x, y); +} +""" + + +def run_ops(a, b, c, pragma=True): + dev = nt.Device() + src = kernels.PRELUDE + kernels.template("basalt_fp.metal") + OPS + if not pragma: + src = src.replace("#pragma STDC FP_CONTRACT OFF", "") + pso = nt.Pipeline(nt.Library(dev, src, {"NCOL": str(NCOL)}), "ops") + n = len(a) + out = nt.Buffer(dev, 4 * NCOL * n) + bufs = [nt.Buffer(dev, np.ascontiguousarray(v, F32).tobytes()) for v in (a, b, c)] + d = nt.Dispatch().pipeline(pso) + for k, buf in enumerate(bufs): + d = d.buffer(k, buf) + d = d.buffer(3, out).bytes(4, np.uint32(n).tobytes()).grid((n + 255) // 256).threadgroup(256) + r = nt.Queue(dev).run([d]) + assert not r.error, r.error + return np.frombuffer(out.read(0, 4 * NCOL * n), F32).reshape(n, NCOL) + + +def normals(rng, n, lo=100, hi=154): + """Random float32 with biased exponents in [lo, hi): far from overflow and from the subnormal range.""" + bits = (rng.integers(0, 2, n, dtype=np.uint32) << 31) | (rng.integers(lo, hi, n, dtype=np.uint32) << 23) \ + | rng.integers(0, 1 << 23, n, dtype=np.uint32) + return bits.view(F32) + + +def ulp(x): + return (np.nextafter(np.abs(x), F32(np.inf)) - np.abs(x)).astype(F32) + + +def test_rounding_is_to_nearest_even(): + rng = np.random.default_rng(1) + n = 1 << 20 + a, b, c = normals(rng, n), normals(rng, n), normals(rng, n) + # planted ties: a + ulp(a) / 2 (both neighbours' parities occur), and the same as fma(a, 1, ulp / 2) + t = 1 << 16 + a[:t] = normals(rng, t, 120, 135) + b[:t] = ulp(a[:t]) * F32(0.5) * np.sign(rng.standard_normal(t)).astype(F32) + b[t: 2 * t], c[t: 2 * t] = F32(1.0), ulp(a[t: 2 * t]) * F32(0.5) + # products with 13-bit significands: exact 25- and 26-bit products, a quarter of them ties + m = rng.integers(1 << 12, 1 << 13, (2, t)).astype(F32) * F32(2.0 ** -12) + a[2 * t: 3 * t], b[2 * t: 3 * t] = m + got = run_ops(a, b, c) + with np.errstate(over="ignore", under="ignore"): + want = [a + b, a * b, emu.fma32(a, b, c), a / b] + for k, name in enumerate(["add", "mul", "fma", "div"]): + assert np.array_equal(got[:, k].view(np.uint32), want[k].view(np.uint32)), name + exact = a[2 * t: 3 * t].astype(np.float64) * b[2 * t: 3 * t] + assert np.count_nonzero(exact != (a[2 * t: 3 * t] * b[2 * t: 3 * t]).astype(np.float64)) > t // 8 # ties exercised + # round toward zero would have differed on about half of the inexact random results + assert np.count_nonzero((a + b).astype(np.float64) != a.astype(np.float64) + b) > n // 4 + + +def test_subnormals_in_safe_mode(): + """Measured: add, multiply, fma and division flush a subnormal input and a subnormal result to the zero of its + sign (MSL section 8.1 permits it); each input case has a normal exact result, so an input flush is told apart from + a result flush. Multiply and fma flush on the exact value, before rounding: an exact product of 2^-126 - 2^-151, + which rounds to 2^-126, comes back as +0 (CUDA's .ftz flushes the rounded result: fma_ftz and mul_ftz rebuild it). + fmax and fmin do not flush: their comparison treats a subnormal as zero, and the chosen operand comes back + unflushed, the second one on a tie. fabs and moves keep the bits. Hence the *_ftz helpers flush explicitly + (test_ftz_helpers_match_the_emulation).""" + s, s2 = F32(1.5e-39), F32(3e-39) # subnormals, s < s2 + m = F32(2.0 ** -126) # the smallest normal + rows = np.array([(s, m, 0), (-s, 2.0 ** 100, 0), (m, 1, s), (1.5 * m, -m, 0), (-1.5 * m, m, 0), (m, 0.5, 0), + (-m, 0.5, 0), (m, 2, 0), (s, 0, 0), (0, s, 0), (s2, s, 0), (s, -1, 0), (0, -0.0, 0), + (31 * 2.0 ** -70, 1082401 * 2.0 ** -81, 0)], F32) + got = run_ops(rows[:, 0], rows[:, 1], rows[:, 2]) + bits = got.view(np.uint32) + sb, nsb, neg0 = s.view(np.uint32), (-s).view(np.uint32), 0x80000000 + # a subnormal input flushed to the zero of its sign, where the exact result is normal + assert got[0, 0] == m # s + m (exact m + s) + assert bits[1, 1] == neg0 # -s * 2^100 (exact -1.9e-9) + assert bits[0, 3] == 0 # s / m (exact 0.128) + assert got[2, 2] == m # fma(m, 1, s) (exact m + s) + # a subnormal result of normal inputs flushed to the zero of its sign + assert bits[3, 0] == 0 and bits[4, 0] == neg0 # 1.5m - m, -1.5m + m + assert bits[5, 1] == 0 and bits[6, 1] == neg0 # m * 0.5, -m * 0.5 + assert bits[5, 2] == 0 and bits[6, 2] == neg0 # fma(m, 0.5, 0), fma(-m, 0.5, 0) + assert bits[5, 4] == 0 and bits[7, 3] == 0 # m * 0.5 + 0, m / 2 + assert got[7, 1] == F32(2.0 ** -125) # normal results are untouched + # (2^25 - 1) * 2^-151 rounds to 2^-126 but is below it: flushed before rounding + assert bits[13, 1] == 0 and bits[13, 2] == 0 and bits[13, 4] == 0 + # fmax and fmin: a subnormal compares as zero, the chosen operand comes back unflushed, the second on a tie + assert bits[8, 5] == 0 and bits[9, 5] == sb # fmax(s, 0) = +0, fmax(0, s) = s + assert bits[10, 5] == sb # fmax(s2, s) = s, the smaller + assert bits[11, 5] == sb # fmax(s, -1) = s + assert bits[12, 5] == neg0 # fmax(+0, -0) = -0 + assert bits[8, 13] == 0 and bits[9, 13] == sb # fmin(s, 0) = +0, fmin(0, s) = s + assert bits[1, 13] == nsb # fmin(-s, 2^100) = -s + assert bits[0, 6] == sb and bits[1, 6] == sb # fabs keeps a subnormal + + +def test_ftz_helpers_match_the_emulation(): + """Each *_ftz helper bit for bit against basalt_emu, on random values of every exponent below 2^13 and planted + blocks: subnormal inputs (and pairs of them), sums and fma results that land in the subnormal range, exact + subnormal products beside a normal addend (fused, so they count), reciprocals that underflow, and products and fma + results within 40 * 2^-152 of +-2^-126, where rounding first gives 2^-126 from just below it (planted cases: the + tie 2^-126 - 2^-150 and its neighbours, a product of 2^-252 beside +-2^-126, an exact cancellation). This GPU's + multiply and fma flush before rounding (test_subnormals_in_safe_mode), so fma_ftz and mul_ftz rebuild those; + fmax and fabs do not flush, so max_ftz and abs_ftz carry it.""" + rng = np.random.default_rng(2) + n, t = 1 << 18, 1 << 14 + a, b, c = normals(rng, n, 0, 140), normals(rng, n, 0, 140), normals(rng, n, 0, 140) + a[: 2 * t], b[:t] = normals(rng, 2 * t, 0, 1), normals(rng, t, 0, 1) # subnormal (or zero) inputs + a[2 * t: 3 * t], b[2 * t: 3 * t] = normals(rng, t, 1, 3), normals(rng, t, 1, 3) # sums below 2^-126 + p = slice(3 * t, 4 * t) # exact products in [2^-150, 2^-102) beside an addend in [2^-126, 2^-123) + a[p], b[p], c[p] = normals(rng, t, 52, 76), normals(rng, t, 52, 76), normals(rng, t, 1, 4) + q = slice(4 * t, 5 * t) # fma(a, b, -fl(a * b)): the product's rounding error, often subnormal + a[q], b[q] = normals(rng, t, 40, 88), normals(rng, t, 40, 88) + c[q] = -(a[q] * b[q]) + a[5 * t: 6 * t] = normals(rng, t, 251, 255) # 1 / a below 2^-126 + r = slice(6 * t, 7 * t) # a * b + c near +-2^-126, c = 0 in the first half, else 0 or +-k * 2^-126 + a[r] = normals(rng, t, 67, 127) + c[r] = np.where(np.arange(t) < t // 2, 0, rng.integers(-3, 4, t) * 2.0 ** -126).astype(F32) + near = 2.0 ** -126 * (1 + rng.integers(-40, 40, t) * 2.0 ** -26) * np.where(rng.integers(0, 2, t), 1, -1) + b[r] = ((near - c[r]) / a[r].astype(np.float64)).astype(F32) + planted = [(31 * 2.0 ** -70, 1082401 * 2.0 ** -81, 0, 0x00800000), # 2^-126 - 2^-151 + (2.0 ** -126, 1 - 2.0 ** -24, 0, 0x00800000), # the tie 2^-126 - 2^-150: to even + (2.0 ** -126, 1 - 2.0 ** -23, 0, 0), # 2^-126 - 2^-149: subnormal + (-31 * 2.0 ** -70, 1082401 * 2.0 ** -81, 0, 0x80800000), + (2.0 ** -126, -2.0 ** -25, 2.0 ** -126, 0x00800000), # c + a * b = 2^-126 - 2^-151 + (2.0 ** -126, 2.0 ** -25, -2.0 ** -126, 0x80800000), + (2.0 ** -126 * (1 + 2.0 ** -23), -2.0 ** -24, 2.0 ** -126, 0), # just below the tie + (2.0 ** -100 * (1 - 2.0 ** -24), -2.0 ** -50, 2.0 ** -126, 0x00800000), # just above it + (2.0 ** -126, -2.0 ** -126, 2.0 ** -126, 0x00800000), # 2^-126 - 2^-252 + (2.0 ** -126, 2.0 ** -126, -2.0 ** -126, 0x80800000), + (2.0 ** -100, 2.0 ** -26, -2.0 ** -126, 0)] # exactly 0: +0 + k = slice(7 * t, 7 * t + len(planted)) + a[k], b[k], c[k] = np.array([v[:3] for v in planted], F32).T + got = run_ops(a, b, c) + assert np.array_equal(emu.fma_ftz(a[k], b[k], c[k]).view(np.uint32), [v[3] for v in planted]) + exact = a[r].astype(np.float64) * b[r] # exact products: below 2^-126, rounding up to it + assert np.count_nonzero((np.abs(exact) < 2.0 ** -126) & (np.abs(emu.mul_ftz(a[r], b[r])) == 2.0 ** -126)) > t // 64 + fa, fb = emu.ftz(a), emu.ftz(b) + # the port takes max_ftz of flushed absolute values only, so no -0 reaches it; on +0 against -0 this GPU's fmax + # returns the second operand, numpy's fmax +0, and CUDA's FMNMX was not checked: those pairs are left out + mixed_zeros = (fa == 0) & (fb == 0) & (np.signbit(fa) != np.signbit(fb)) + want = {7: emu.add_ftz(a, b), 8: emu.mul_ftz(a, b), 9: emu.fma_ftz(a, b, c), 10: emu.max_ftz(a, b), + 11: emu.rcp_ftz(a), 12: emu.ftz(np.abs(a))} + for k, w in want.items(): + keep = ~mixed_zeros if k == 10 else slice(None) + assert np.array_equal(got[keep, k].view(np.uint32), w[keep].view(np.uint32)), k + + +@pytest.mark.parametrize("pragma", [True, False]) +def test_contraction_is_off_with_the_pragma(pragma): + rng = np.random.default_rng(3) + n = 1 << 16 + a, b = normals(rng, n, 120, 135), normals(rng, n, 120, 135) + c = -(a * b) * (F32(1.0) + rng.standard_normal(n).astype(F32) * F32(1e-3)) # cancellation: fusing shows + got = run_ops(a, b, c, pragma)[:, 4] + unfused = (a * b) + c + fused = emu.fma32(a, b, c) + fma_diff = np.count_nonzero(fused.view(np.uint32) != unfused.view(np.uint32)) + mismatches = np.count_nonzero(got.view(np.uint32) != unfused.view(np.uint32)) + assert fma_diff > n // 2 # the inputs tell fused from unfused + if pragma: + assert mismatches == 0 + else: # the default (safe mode) contracts a * b + c + assert np.array_equal(got.view(np.uint32), fused.view(np.uint32)) + + +def test_half_conversions(): + dev = nt.Device() + src = kernels.PRELUDE + kernels.template("basalt_fp.metal") + """ +kernel void conv(device const ushort* h [[buffer(0)]], device const float* f [[buffer(1)]], + device float* hf [[buffer(2)]], device ushort* fh [[buffer(3)]], uint i [[thread_position_in_grid]]) { + hf[i] = h2f(h[i]); + fh[i] = as_type(half(f[i])); +} +""" + pso = nt.Pipeline(nt.Library(dev, src, {}), "conv") + n = 1 << 16 + h = np.arange(n, dtype=np.uint16) + rng = np.random.default_rng(4) + f = normals(rng, n, 96, 145) # fp16 normals, subnormals, overflow and ties + f[: 1 << 12] = (h[: 1 << 12].view(np.float16).astype(np.float64) * (1 + 2.0 ** -11)).astype(F32) + hf, fh = nt.Buffer(dev, 4 * n), nt.Buffer(dev, 2 * n) + r = nt.Queue(dev).run([nt.Dispatch().pipeline(pso).buffer(0, nt.Buffer(dev, h.tobytes())) + .buffer(1, nt.Buffer(dev, f.tobytes())).buffer(2, hf).buffer(3, fh) + .grid(n // 256).threadgroup(256)]) + assert not r.error, r.error + got = np.frombuffer(hf.read(0, 4 * n), F32) + finite = np.isfinite(h.view(np.float16)) + assert np.array_equal(got[finite].view(np.uint32), emu.h2f(h)[finite].view(np.uint32)) # exact, fp16 subnormals too + assert np.array_equal(got[~finite], emu.h2f(h)[~finite], equal_nan=True) # infinities exact; NaN stays NaN + assert np.array_equal(np.frombuffer(fh.read(0, 2 * n), np.uint16), emu.half_bits(f)) # round to nearest even diff --git a/tests/kernels/test_basalt_pool.py b/tests/kernels/test_basalt_pool.py new file mode 100644 index 00000000..a34556a1 --- /dev/null +++ b/tests/kernels/test_basalt_pool.py @@ -0,0 +1,360 @@ +# SPDX-License-Identifier: MIT +# Copyright (c) 2026 Jesús Gulfo +# adapted from basalt (jesdga95/basalt) src/kernels/cpu/pool.cpp and include/basalt/kernels/cpu/pool.hpp @ +# b4c63b55754637f4c72ad53a0f791d425f71eb36 (MIT; third_party/NOTICE): the properties the pool's claim protocol and +# its park barriers are built to give. +"""``ExpertPool`` of ``runtime/src/basalt_pool.h``, the worker pool that runs basalt's CPU expert tier. + +**What this suite can and cannot pin.** Nothing bitwise depends on the pool: a job writes its own rows and the host +sums them in a fixed order, so the thread count, the placement and the order jobs are claimed in do not reach the +output (``docs/research/basalt-cpu-pool.md`` section 2). What the pool has to reproduce is its SYNCHRONISATION, and +getting that wrong does not give different numbers, it gives a run that hangs or computes a job twice. So this +suite asserts properties rather than values, and it asserts them under the schedules that break a wrong +implementation rather than under a quiet one. + +The property every case rests on: **each job of a phase runs exactly once**. ``count_phase`` has job j do +``out[j] += 1``, so after k phases every element is k, and a job claimed twice or dropped shows up as an element +that is not. + +Cases. **A**, one phase: A1 every job runs once, A2 the work is spread over the workers, A3 an empty phase, A4 a +phase with more jobs than workers. **B**, the claim protocol across batches, which is what the epoch in the batch +word exists for: B1 many phases back to back, B2 phases spaced so the workers sleep between them, B3 phases spaced +so some workers sleep and some do not, which is the schedule the header says "comes round constantly". **C**, the +pool's own guards: C1 the owner claim, C2 the batch-size refusal, C3 a stalled pool poisons itself and refuses +reuse, C4 a second concurrent driver is refused. **D**, shapes: D1 a single worker, D2 without the host working, D3 the phase timers. + +**The sleep boundary is the point.** A worker that went to sleep is still counted as parked when it wakes, so for a +moment after it has seen a new epoch the host believes it is idle. Group B spaces its phases around +``spin_before_sleep_ms`` so that moment keeps coming round. + +**What this suite does NOT catch, measured.** It was mutated to find out, and the answer is sobering: removing the +epoch test from ``claim``, removing either park barrier, removing both, and removing all three together each leave +every case passing, over 4,000 phases of 8 jobs [M]. The windows these protections cover are nanoseconds wide and +a trivial job never schedules into them. Two things follow. For the epoch test specifically the null result is +what the code predicts: the park barriers narrow the late-claim window without closing it (``worker`` re-reads the +epoch before it decrements ``parked_``), but a late claim lands on the next batch harmlessly, because the claim's +acquire of ``head_`` orders the batch description before it, the index compare-exchange hands out each job once, +and ``wait_done`` has seen every increment before the counter is reset +(``docs/research/basalt-cpu-pool.md`` section 1.1). The test is kept because this is a 1:1 port of basalt's +protocol. And a property test is the wrong instrument for the rest: ``tools/tsan/pool_tsan.cpp`` runs the same pool under ThreadSanitizer, which reads the +happens-before edges directly and found a real ordering defect this suite passed clean over (the batch description +was read before the claim that orders it). Weakening the written memory orders to ``relaxed`` is caught by neither +[M]; those rest on the transcription and the argument recorded with them, not on a test. +""" + +import multiprocessing +import queue +import threading +import time + +import numpy as np +import pytest + +from monolith.runtime import _native as _nt + +I32 = np.int32 + + +def pool(**kw): + """A pool with a short spin by default, so the sleep path is reachable inside a test's patience.""" + kw.setdefault("spin_before_sleep_ms", 2.0) + return _nt.ExpertPool(**kw) + + +def run_phase(p, n): + """One phase of n jobs. Returns (out, who, times).""" + out = np.zeros(n, I32) + who = np.full(n, -99, I32) + times = p.count_phase(out, who) + return out, who, times + + +# ---- A: one phase ------------------------------------------------------------------------------------------------ + +def test_a1_every_job_runs_exactly_once(): + """A1. The property the whole pool is built to give. A job claimed twice leaves a 2, a job dropped leaves a 0, + and either is a claim protocol that does not work.""" + p = pool() + out, who, _ = run_phase(p, 64) + assert list(out) == [1] * 64, f"{int((out != 1).sum())} of 64 jobs did not run exactly once" + assert (who >= -1).all() and (who < p.workers).all() + + +def test_a2_the_work_reaches_more_than_one_thread(): + """A2. A pool that ran every job on the host would pass A1. The jobs are claimed, not assigned, so which thread + takes which is not fixed; what is asserted is only that more than one took part, over enough jobs that a pool + distributing work at all cannot fail it.""" + p = pool(n_workers=4) + seen = set() + for _ in range(20): + _, who, _ = run_phase(p, 256) + seen.update(int(w) for w in who) + assert len(seen) > 1, f"every job ran on one thread, {seen}" + + +def test_a3_an_empty_phase(): + """A3. Zero jobs is a phase that publishes a batch nothing can claim. It must still cross both park barriers + and return, rather than waiting for a completion that cannot come.""" + p = pool() + out, _, _ = run_phase(p, 0) + assert len(out) == 0 + + +def test_a4_more_jobs_than_workers(): + """A4. The index field of the batch word is what hands out jobs, so a phase deeper than the worker count is the + case where it is actually used.""" + p = pool(n_workers=2) + out, _, _ = run_phase(p, 1000) + assert list(out) == [1] * 1000 + + +# ---- B: the claim protocol across batches -------------------------------------------------------------------- + +def test_b1_many_phases_back_to_back(): + """B1. Phases with no gap, so the workers never reach the sleep and the park barrier is the only thing keeping + one batch out of the next. The epoch in the batch word is what makes a late worker's claim fail.""" + p = pool() + n, phases = 48, 200 + out = np.zeros(n, I32) + who = np.full(n, -99, I32) + for _ in range(phases): + p.count_phase(out, who) + assert list(out) == [phases] * n, f"after {phases} phases the counts are not all {phases}" + + +def test_b2_phases_spaced_so_every_worker_sleeps(): + """B2. A gap longer than the spin, so every worker is inside the condition variable when the next batch is + published. This is the lost-wakeup path: the host bumps the epoch and then reads `sleepers_`, a worker + increments `sleepers_` and then reads the epoch, and both sides are seq_cst so one of them sees the other. A + port that weakened either side hangs here rather than returning a wrong number.""" + p = pool(spin_before_sleep_ms=1.0) + n, phases = 16, 40 + out = np.zeros(n, I32) + who = np.full(n, -99, I32) + for _ in range(phases): + time.sleep(0.004) # four times the spin, so the sleep is reached + p.count_phase(out, who) + assert list(out) == [phases] * n + + +def test_b3_phases_spaced_at_the_sleep_boundary(): + """B3. The schedule the header calls out: "tiny batches finish before a sleeper is awake, and that moment comes + round constantly". The gap straddles the spin, so on any given phase some workers are spinning and some are + inside the condition variable, which is the mix in which a late claim would be possible.""" + p = pool(spin_before_sleep_ms=1.0) + n, phases = 8, 300 + out = np.zeros(n, I32) + who = np.full(n, -99, I32) + for i in range(phases): + time.sleep(0.0004 + (i % 5) * 0.0004) # 0.4 to 2.0 ms, straddling the 1 ms spin + p.count_phase(out, who) + assert list(out) == [phases] * n, f"{int((out != phases).sum())} of {n} counts are wrong" + + +# ---- C: the pool's own guards ---------------------------------------------------------------------------------- + +def test_c1_one_owner_at_a_time(): + """C1. Two distinct host tasks could otherwise drive one pool and overlap their phases, which no barrier in the + pool protects against. The claim is a compare-exchange, as a task's runner claim is.""" + p = pool() + a, b = 0x1000, 0x2000 + assert p.claim_owner(a) + assert p.claim_owner(a) # the same owner may re-claim + assert not p.claim_owner(b) + p.release_owner(b) # a release by a non-owner changes nothing + assert not p.claim_owner(b) + p.release_owner(a) + assert p.claim_owner(b) + + +def test_c2_a_batch_too_large_is_refused(): + """C2. The batch word carries the job count in 16 bits, so a larger batch would overflow into the epoch. basalt + aborts here; this returns the refusal.""" + p = pool() + out = np.zeros(0x10000, I32) + who = np.zeros(0x10000, I32) + with pytest.raises(ValueError, match="0 to 65535"): + p.count_phase(out, who) + + +@pytest.mark.slow +def test_c3_a_stalled_pool_poisons_itself(): + """C3. A wait that sees no completion for kStall is a bug. basalt prints, releases the GPU waits and aborts; + this reports instead, and the pool is poisoned: its workers may still hold pointers into buffers the caller is + about to free, so it is never destroyed and never reused. + + The stall limit is 60 seconds, so this case costs the kernels tier about 70 of them. It carries the ``slow`` + marker for a run that wants to deselect it, and the tier does not: it runs, and it is the only case that + proves the limit is armed at all, which matters because the transcribed spin wraps its clock every 1.8 s if + armed as basalt arms it. + + ``host_works=False`` is the point of the shape: with the host working it drains the moment it has published, + so it can win the claim for the one job, sleep the 70 seconds inline and then find ``done`` already at 1. No + wait would stall and the case would pass or fail on which thread won. With the host not working only a worker + can claim, so the host always waits and always hits the limit.""" + p = pool(host_works=False) + ok, err = p.stall_phase(70.0) + assert not ok and "stalled" in err + assert p.poisoned + out, who = np.zeros(4, I32), np.zeros(4, I32) + with pytest.raises(ValueError, match="cannot be reused"): + p.count_phase(out, who) + globals().setdefault("_poisoned_pools", []).append(p) # never destroyed: a worker still holds its body + + +def test_c4_a_second_driver_is_refused(): + """C4. ``run_phase`` is not reentrant. A second driver that passes the park barrier before the first publishes + overwrites the batch description and resets ``done`` and ``head`` under it, so the first waits on a count the + second is filling and runs a body it did not publish. ``claim_owner`` answers a different question, which task + OWNS the pool, and an owner holds its claim across calls, so it is the wrong grain for a phase. + + Two Python threads reach ``run_phase`` concurrently, which is what this case does: ``count_phase`` and + ``stall_phase`` both release the GIL before calling it. The GIL serialises only the entry up to that release, + which makes the corrupting window (both drivers past the park barrier before either publishes) hard to hit + from Python: 400 simultaneous-entry trials did not hit it. ThreadSanitizer on two native threads names the + race at once (``tools/tsan/pool_tsan.cpp``). So the window is narrow here, not closed, and what this case + asserts is the refusal that makes a concurrent Python call safe.""" + p = pool(n_workers=3) + out, who = np.zeros(8, I32), np.full(8, -7, I32) + second = {} + + def drive_second(): + time.sleep(0.3) # the first driver is 0.3 s into a 2 s phase + try: + p.count_phase(out, who) + second["err"] = None + except ValueError as e: + second["err"] = str(e) + + t = threading.Thread(target=drive_second) + t.start() + ok, err = p.stall_phase(2.0) # 2 s is under kStall, so this finishes and does not poison + t.join() + assert ok, f"the first driver should finish its own phase: {err}" + assert second["err"] is not None, "the second driver ran a phase while the first held one" + assert "another thread" in second["err"], second["err"] + assert not p.poisoned + assert list(out) == [0] * 8, "the refused phase must not have run any job" + + +# ---- D: shapes -------------------------------------------------------------------------------------------------- + +def test_d1_a_single_worker(): + """D1. One worker and the host. The park barrier and the claim still have to work with nothing to race.""" + p = pool(n_workers=1) + assert p.workers == 1 + out, _, _ = run_phase(p, 100) + assert list(out) == [1] * 100 + + +def test_d2_without_the_host_working(): + """D2. basalt's host drains beside the workers unless --no-host-worker. With it off every job must still be + claimed, by a worker, and the host waits.""" + p = pool(n_workers=2, host_works=False) + assert not p.host_works + out, who, _ = run_phase(p, 200) + assert list(out) == [1] * 200 + assert (who >= 0).all(), "the host drained a job although host_works is off" + + +def test_d3_the_phase_timers(): + """D3. A slow pool poses one question, slow at the work or slow at the synchronisation, and only these answer + it. What is asserted is what the timers are: three non-negative wall-clock milliseconds that together account + for the phase, each measured around one of its three stages. Their ORDER is not a property - the first phase + after construction spends longer waiting for the workers to reach the park than it spends on the work, which + is exactly the kind of thing the timers exist to show.""" + p = pool() + t0 = time.perf_counter() + before, work, after = run_phase(p, 512)[2] + wall_ms = (time.perf_counter() - t0) * 1000.0 + for t in (before, work, after): + assert np.isfinite(t) and t >= 0.0 + total = before + work + after + assert total <= wall_ms + 1.0, f"the three timers total {total:.3f} ms over a {wall_ms:.3f} ms phase" + assert total >= wall_ms * 0.5, f"the three timers account for only {total:.3f} ms of a {wall_ms:.3f} ms phase" + + +def test_the_pool_refuses_a_mismatched_pair(): + p = pool() + with pytest.raises(ValueError, match="as many ints"): + p.count_phase(np.zeros(8, I32), np.zeros(7, I32)) + with pytest.raises(TypeError): + p.count_phase(np.zeros(8, np.int64), np.zeros(8, np.int64)) + + +def test_the_binding_refuses_what_the_equal_length_check_does_not_cover(): + """Equal lengths do not make two arrays distinct. The same array for both would let the worker-id write + replace the count, and a shifted view of one buffer would let two jobs write one element at once; neither is + a length error, and `.noconvert()` prevents a conversion copy rather than aliasing.""" + p = pool() + a = np.zeros(8, I32) + with pytest.raises(ValueError, match="share storage"): + p.count_phase(a, a) + b = np.zeros(9, I32) + with pytest.raises(ValueError, match="share storage"): + p.count_phase(b[:8], b[1:]) + p.count_phase(np.zeros(8, I32), np.zeros(8, I32)) # two distinct buffers are fine + + +def test_the_binding_refuses_an_unusable_spin(): + """The spin crosses into C++ as microseconds. A NaN, an infinity, or a value past the integer's range makes + that conversion undefined rather than merely wrong, so it is refused before it happens.""" + for bad in (float("nan"), float("inf"), -1.0, 1e18): + with pytest.raises(ValueError, match="finite"): + _nt.ExpertPool(n_workers=1, spin_before_sleep_ms=bad) + _nt.ExpertPool(n_workers=1, spin_before_sleep_ms=0.0) # zero is a pool that never spins + + +def test_many_pools_live_and_die(): + """Construction and teardown are their own risk: the destructor sets the stop flag and bumps the epoch so a + parked worker notices rather than sleeping through it, then joins. A worker that missed the bump would hang + the interpreter here rather than fail a test.""" + for _ in range(20): + p = pool(n_workers=3) + run_phase(p, 32) + del p + + +def _drive_from_a_thread(q): + """Run in a child process: a pool driven from a thread that did not construct it, reporting the counts back.""" + import numpy as _np + from monolith.runtime import _native as _n + + p = _n.ExpertPool(n_workers=0, host_works=True, spin_before_sleep_ms=2.0) + out = _np.zeros(64, _np.int32) + who = _np.full(64, -99, _np.int32) + err = [] + + def drive(): + try: + for _ in range(20): + p.count_phase(out, who) + except Exception as e: # noqa: BLE001 - carried back through the queue below + err.append(repr(e)) + + t = threading.Thread(target=drive) + t.start() + t.join() + q.put((list(out), err)) + + +def test_a_pool_driven_from_another_thread(): + """The pump thread is whatever Python thread called Engine.run and can differ between runs, so the pool must + work from a thread that did not construct it. + + In a child process, because the failure this guards against is a hang. A thread that never returns would + outlive `join(timeout=...)` in this process and keep the whole test run alive after the assertion failed; + a child can be terminated, so the deadline is real.""" + ctx = multiprocessing.get_context("spawn") + q = ctx.Queue() + proc = ctx.Process(target=_drive_from_a_thread, args=(q,)) + proc.start() + try: + counts, err = q.get(timeout=120) + except queue.Empty: + proc.terminate() + proc.join(10) + pytest.fail("the pool did not finish when driven from another thread") + proc.join(30) + assert not err, err + assert counts == [20] * 64 diff --git a/tests/kernels/test_basalt_q5k_head.py b/tests/kernels/test_basalt_q5k_head.py new file mode 100644 index 00000000..26c4af96 --- /dev/null +++ b/tests/kernels/test_basalt_q5k_head.py @@ -0,0 +1,406 @@ +# SPDX-License-Identifier: MIT +# Copyright (c) 2026 Jesús Gulfo +# adapted from basalt (jesdga95/basalt) src/kernels/q5k_head_parity.cpp @ b4c63b55754637f4c72ad53a0f791d425f71eb36 +# (MIT; third_party/NOTICE): its weights and activations, row counts, maps, planted rows and pass criteria. +"""basalt's Q5_K head on Metal (kernels/common/basalt_q5k_head.metal). + +q5k_head_parity, ported (basalt src/kernels/q5k_head_parity.cpp, ctest ``q5k_head_parity 20000 5``: 20,000 rows): +random Q5_K rows (random bytes, then d and dmin = fp16(|N(0, 1)| * 0.01), :33-43) and N(0, 1) activations quantized +by native_quantize_q8_1, n_in 2560. numpy's generator stands for basalt's mt19937 + normal_distribution: the same +distributions, other draws. The timing loops are not ported. +- The head against native_mmvq (basalt_mmvq.metal, Q5_K) bit for bit, 1 to 8 columns (:64-92); each column also bit + for bit the head's one-column call on it (column invariance, flash-next.md invariant 1). +- The contract's test (docs/design/flash-next.md, kernels without a reference test): mmvq_multi_parity.cpp:461's rule + at the head's shape, 2560 -> 248,320 rows, 8 columns, each bit for bit the head's one-column call on it and within + 1e-4 * max |ref| of the float64 product on the same bytes; the bitwise check against native_mmvq carried over.""" + +import struct + +import numpy as np +import pytest + +from monolith import kernels +from tests.kernels import basalt_emu as emu +from tests.kernels import basalt_gpu as gpu +from tests.kernels.test_basalt_mmvq import reference + +F32 = np.float32 +N_IN, ROWS, MT = 2560, 20000, 8 # basalt's n_in, ctest's row count, its 8 columns +QCOL = N_IN // 32 * 36 # q8_1 bytes a column + + +def weights(rows, rng, n_in=N_IN): + """q5k_head_parity.cpp:33-43: random bytes, then each block's d and dmin fp16(|N(0, 1)| * 0.01).""" + w = rng.integers(0, 256, (rows * n_in // 256, 176), dtype=np.uint8) + dm = (np.abs(rng.standard_normal((w.shape[0], 2))).astype(F32) * F32(0.01)).astype(np.float16) + w[:, :4] = dm.view(np.uint8).reshape(-1, 4) + return w.reshape(rows, -1) + + +def activations(ncols, rng): + """N(0, 1) columns quantized by native_quantize_q8_1 (:47-59).""" + return gpu.q8_1(rng.standard_normal(ncols * N_IN).astype(F32), "native") + + +def column(xq, j): + return xq[j * QCOL: (j + 1) * QCOL] + + +@pytest.fixture(scope="module") +def data(): + rng = np.random.default_rng(5) # basalt's seed, std::mt19937 rng(5) (:32) + w = weights(ROWS, rng) + return w, activations(MT, rng), rng + + +def bad_bits(a, b): + return int(np.count_nonzero(np.asarray(a, F32).view(np.uint32) != np.asarray(b, F32).view(np.uint32))) + + +def test_head_against_native_mmvq(data): + w, xq, _ = data + fail = diff = 0 + one = np.stack([gpu.q5k_head(w, column(xq, j), N_IN, ROWS, 1)[0] for j in range(MT)]) + for nc in range(1, MT + 1): + a = gpu.mmvq(13, w, xq[: nc * QCOL], N_IN, ROWS, nc, fill=0xFF) # basalt's pre-fills (:65-66) + b = gpu.q5k_head(w, xq[: nc * QCOL], N_IN, ROWS, nc, fill=0xEE) + bad = bad_bits(a, b) + # basalt: ``for (size_t i = 0; i < a.size(); ++i) bad += std::memcmp(&a[i], &b[i], 4) != 0;`` (:74) and + # ``if (bad) fail = 1;`` (:91) + fail |= bad != 0 + diff += bad_bits(b, one[:nc]) + assert np.all(np.isfinite(b)), nc + assert not fail and diff == 0, diff + + +def reference_rows(w, xc, rows, chunk=5000): + """reference(13, ...) by chunks of rows: its float64 intermediates take ~20 KB a row.""" + return np.concatenate([reference(13, w[r: r + chunk], xc, N_IN, min(chunk, rows - r)) + for r in range(0, rows, chunk)]) + + +def test_head_full_shape(): + """flash-next.md's test for q5k_head_mmvq: mmvq_multi_parity.cpp:461's rule at the head's shape, 2560 -> 248,320 + rows (basalt's test default, q5k_head_parity.cpp:28), 8 columns. Per column: ``diff``, the values differing from + the head's one-column call on it (basalt's one-column call against its two-column one, :429-430, :457), and + ``worst``, the one-column call's largest error against the float64 product on the same bytes, against ``scale``, + the largest |ref|. The bitwise check against native_mmvq carries over, one column and eight.""" + rows = 248320 + rng = np.random.default_rng(28) + w = weights(rows, rng) + xq = activations(MT, rng) + y = gpu.q5k_head(w, xq, N_IN, rows, MT, fill=0xEE) + assert bad_bits(gpu.mmvq(13, w, xq, N_IN, rows, MT, fill=0xFF), y) == 0 + for j in range(MT): + a = gpu.q5k_head(w, column(xq, j), N_IN, rows, 1)[0] + if j == 0: + assert bad_bits(gpu.mmvq(13, w, column(xq, 0), N_IN, rows, 1, fill=0xFF), a) == 0 + ref = reference_rows(w, column(xq, j), rows) + diff = bad_bits(a, y[j]) + worst, scale = np.max(np.abs(a.astype(np.float64) - ref)), np.max(np.abs(ref)) + # basalt: ``const bool ok = diff == 0 && worst <= 1e-4 * (scale + 1e-30);`` (mmvq_multi_parity.cpp:461); its + # std::max fold drops a NaN, so the non-finite values are counted + assert np.all(np.isfinite(a)) and diff == 0 and worst <= 1e-4 * (scale + 1e-30), (j, diff, worst, scale) + + +@pytest.mark.parametrize("n_in", [256, 2560, 16384]) +def test_head_shapes_and_grids(n_in): + """Other row lengths (q5k_head_supported's range: 1 to 64 blocks) and grids, each column against native_mmvq.""" + rng = np.random.default_rng(n_in) + rows = 333 + w = weights(rows, rng, n_in) + ncols = 1 if n_in == 16384 else 4 # basalt's 96 KiB staging rule allows 2 columns at 16384 + xq = gpu.q8_1(rng.standard_normal(ncols * n_in).astype(F32), "native") + a = gpu.mmvq(13, w, xq, n_in, rows, ncols) + for sm_count, per_sm in ((170, 2), (40, 1), (1, 1)): + b = gpu.q5k_head(w, xq, n_in, rows, ncols, sm_count=sm_count, per_sm=per_sm) + assert bad_bits(a, b) == 0, (sm_count, per_sm) + + +def test_launch_rules(): + """The builders refuse what basalt's API refuses or its int arithmetic cannot hold: n_out and n_rows are its ints + (q5k_head.cu:372-374, 412, 516-518), n_rows 0 included; n_cap past the 32-bit field; a grid whose int row loop + would step past INT_MAX.""" + assert kernels.basalt_q5k_head_grid(248320) == 340 and kernels.basalt_q5k_head_grid(2 ** 31 - 8 * 340) == 340 + for bad in [lambda: kernels.basalt_q5k_head_params(2560, 0), lambda: kernels.basalt_q5k_head_params(2560, 2 ** 31), + lambda: kernels.basalt_q5k_head_grid(2 ** 31 - 8 * 340 + 1), + lambda: kernels.basalt_q5k_proxy_params(100, n_rows=0), + lambda: kernels.basalt_q5k_proxy_params(100, n_rows=101), + lambda: kernels.basalt_q5k_proxy_params(2 ** 32 - 1, n_rows=2 ** 31), + lambda: kernels.basalt_q5k_proxy_params(2 ** 32, row0=0, n=1), + lambda: kernels.basalt_q5k_proxy_params(100, row0=50, n=51)]: + with pytest.raises(ValueError): + bad() + assert kernels.basalt_q5k_proxy_params(2 ** 32 - 1, row0=2 ** 32 - 2, n=1)[8:] == struct.pack(" a[best]`` scan and the sampler's + greedy rule, flash-next.md "Greedy pick") and the double softmax sum relative to it (:171-179).""" + rows = np.flatnonzero(mapped) + best = int(rows[np.argmax(a[rows])]) # np.argmax: the first maximum + s = float(np.sum(np.exp(a[rows].astype(np.float64) - np.float64(a[best])))) + return best, s + + +def test_top1(data): + """:93-146 at ctest's row counts ({20000, 106299, 40525, 1000}, the larger skipped above 20,000, :105-107), each of + 8 columns: the logits bit for bit against native_mmvq, the id against the host argmax over the GPU logits (basalt: + sample_greedy_top_prob on the GPU, sampler.cu:930, not on main), the probability against a host double softmax + over them (the comparison basalt's holes section makes, :171-185).""" + w, xq, _ = data + logit_bad = id_bad = nonfinite = 0 + max_rel = 0.0 + for rr in (ROWS, 106299, 40525, 1000): + if rr > ROWS: + continue + for col in range(MT): + xc = column(xq, col) + a = gpu.mmvq(13, w[:rr], xc, N_IN, rr, 1)[0] + b, b_id, b_p, _ = gpu.q5k_top1(w[:rr], xc, rr) + best, s = host_top(a, np.ones(rr, bool)) + logit_bad += bad_bits(a, b) + id_bad += b_id != best + nonfinite += int(not np.isfinite(b_p)) + int(np.count_nonzero(~np.isfinite(b))) + max_rel = max(max_rel, abs(float(b_p) - 1.0 / s) * s) + # basalt: ``if (logit_bad || id_bad || max_rel > 1e-5) fail = 1;`` (:145); its std::max fold (:123) drops a NaN, + # so the non-finite outputs are counted (flash-next.md) + assert logit_bad == 0 and id_bad == 0 and nonfinite == 0 and max_rel <= 1e-5, (logit_bad, id_bad, nonfinite, + max_rel) + + +def holes_map(rr): + """:157-158: every fifth row (i % 5 == 2) and the last 2048 rows without a token, the others id 3i + 7.""" + i = np.arange(rr) + return np.where((i % 5 == 2) | (i >= rr - 2048), -1, 3 * i + 7).astype(np.int32) + + +def test_top1_holes(data): + """:147-211 at min(rows, 106299) = 20,000 rows, 8 columns: masked rows -inf, the others bit for bit native_mmvq's; + the id against map[host argmax], the probability against the host double softmax; then the mask kernel after a + plain head the same way (:186-193).""" + w, xq, _ = data + rr = min(ROWS, 106299) + mp = holes_map(rr) + mapped = mp >= 0 + bad = 0 + max_rel = 0.0 + for col in range(MT): + xc = column(xq, col) + a = gpu.mmvq(13, w[:rr], xc, N_IN, rr, 1)[0] + b, b_id, b_p, _ = gpu.q5k_top1(w[:rr], xc, rr, mp) + bad += int(np.count_nonzero(~np.isneginf(b[~mapped]))) + bad_bits(a[mapped], b[mapped]) + best, s = host_top(a, mapped) + bad += b_id != mp[best] + max_rel = max(max_rel, abs(float(b_p) - 1.0 / s) * s) + c = gpu.q5k_head_masked(w[:rr], xc, N_IN, rr, mp) + bad += int(np.count_nonzero(~np.isneginf(c[~mapped]))) + bad_bits(a[mapped], c[mapped]) + # basalt's std::max fold (:185) drops a NaN: the non-finite outputs are counted (flash-next.md) + bad += int(not np.isfinite(b_p)) + int(np.count_nonzero(~np.isfinite(b[mapped]))) + bad += int(np.count_nonzero(~np.isfinite(c[mapped]))) + # basalt: ``if (bad || max_rel > 1e-5) fail = 1;`` (:210) + assert bad == 0 and max_rel <= 1e-5, (bad, max_rel) + + +@pytest.mark.parametrize("rr,grid", [(20000, {}), (1000, {}), (20000, {"sm_count": 40, "per_sm": 1}), + (5000, {"sm_count": 3, "per_sm": 1})]) +def test_top1_emulation_bit_for_bit(data, rr, grid): + """The partials, the id and the probability bit for bit against the numpy emulation of the take and merge + (basalt_emu.q5k_top1) on the kernel's logits, with the GPU's expf_ftz; with and without the holes map; at basalt's + grid and others (the probability's last bits follow the grid, mtp.cpp:1007-1008).""" + w, xq, _ = data + blocks = kernels.basalt_q5k_head_grid(rr, **grid) + for mp in (None, holes_map(rr)): + y, b_id, b_p, part = gpu.q5k_top1(w[:rr], column(xq, 3), rr, mp, **grid) + mapped = np.ones(rr, bool) if mp is None else mp >= 0 + e_part, e_row, e_p = emu.q5k_top1(y, mapped, blocks, gpu.expf_ftz) + assert bad_bits(part[:, 0], e_part[0]) == 0 and bad_bits(part[:, 2], e_part[2]) == 0 + assert np.array_equal(part[:, 1].view(np.int32), e_part[1].astype(np.int32)) + e_row = e_row if e_row < rr else 0 # no row taken (every row masked): row 0 (q5k_head.cu:330) + assert b_id == (e_row if mp is None else mp[e_row]) and bad_bits(b_p, e_p) == 0, (b_id, e_row, b_p, e_p) + + +def test_expf_ftz(): + """basalt_fp.metal's expf_ftz, whose GPU values the emulations above take for __expf, bit for bit against its + definition (q5k_head.md section 2): FMUL.FTZ by fl(log2 e) and the .ftz flush of the result on the host, only + fast::exp2 (MUFU.EX2's counterpart, with no bit-exact model) on the GPU. The arguments: the take's and the score's + range, the result's flush (x * log2 e below -126: x below -87.34), its underflow to 0 (below -103.3), its overflow + (above 88.72), -inf (the take's first row: m = -inf), zeros and subnormals (flushed).""" + log2e = F32(np.log2(np.e)) + assert log2e.view(np.uint32) == 0x3FB8AA3B # ptxas's FMUL.FTZ immediate 1.4426950216293334961 + x = np.concatenate([np.linspace(-30, 0, 4001, dtype=F32), np.linspace(-88, -86.5, 4001, dtype=F32), + np.linspace(-104.5, -102.5, 2001, dtype=F32), np.linspace(88, 89.5, 201, dtype=F32), + F32([-np.inf, 0.0, -0.0]), np.uint32([1, 0x007FFFFF, 0x80000001]).view(F32)]).astype(F32) + p = emu.mul_ftz(x, log2e) + src = kernels.PRELUDE + """ +kernel void ex2(device const float* p [[buffer(0)]], device float* e [[buffer(1)]], constant uint& n [[buffer(2)]], + uint i [[thread_position_in_grid]]) { + if (i < n) e[i] = fast::exp2(p[i]); +} +""" + e = gpu.run(gpu.pipeline(src, "ex2"), [p.tobytes(), 4 * p.size], np.uint32(p.size).tobytes(), 2, -(-p.size // 256), + 256)[1] + assert bad_bits(gpu.expf_ftz(x), emu.ftz(np.frombuffer(e, F32))) == 0 + + +# ---- the 2-bit proxy (q5k_head_parity.cpp:212-350) ----------------------------------------------------------------- + +@pytest.fixture(scope="module") +def proxy_rows(data): + """:215-235: min(rows, 41037) = 20,000 rows whose blocks' d and dmin are scaled by f = 3 / sd(column 0's logits), + so the logits spread 3: fp16(f32(d) * f).""" + w, xq, _ = data + rr = min(ROWS, 41037) + l0 = gpu.mmvq(13, w[:rr], column(xq, 0), N_IN, rr, 1)[0].astype(np.float64) + f = F32(3.0 / np.sqrt(np.mean(l0 * l0) - np.mean(l0) ** 2)) + blk = w[:rr].copy().reshape(rr * 10, 176) + dm = blk[:, :4].copy().view(np.float16).astype(F32) * f + blk[:, :4] = dm.astype(np.float16).view(np.uint8).reshape(-1, 4) + return blk.reshape(rr, 1760) + + +def test_proxy_pack_emulation_bit_for_bit(proxy_rows): + """q5k_proxy_pack byte for byte against the numpy emulation of nvcc's fit and packing (basalt_emu.q5k_proxy_pack; + q5k_head.md section 4), on basalt's rescaled rows with two planted blocks: one with zero scales (w = 0, so sh = 0 + and every level comes from a NaN, which F2I takes to 0) and one with d = 65504 (s past fp16's range, sh = inf); + into a copy with spare rows, n_cap = rows + 100 as basalt's test (:216).""" + rows = 640 + q5 = proxy_rows[:rows].copy() + blk = q5.reshape(rows * 10, 176) + blk[3, 4:16] = 0 # row 0, block 3: groups 24..31 have sc = m = 0 + blk[25, 0:2] = np.array([65504], np.float16).view(np.uint8) # row 2, block 5: d = 65504 + n_cap = rows + 100 + got = gpu.q5k_proxy_pack(q5, n_cap, [(0, rows)]) + assert np.array_equal(got, emu.q5k_proxy_pack(q5, 0, rows, n_cap)) + words = got[: emu.px_tiles(n_cap) * 40 * 32 * 16].view(np.uint32).reshape(-1, 40, 32, 4) + sc = got[emu.px_tiles(n_cap) * 40 * 32 * 16:].view(np.uint16).reshape(-1, 40, 32, 2) + assert np.all(words[0, 12:16, 0] == 0) and np.all(sc[0, 12:16, 0] == 0) # zero groups: levels 0, scale 0 + assert np.any(sc[0, 20:24, 2] == 0x7C00) # an infinite scale + + +def test_proxy_pack_incremental(proxy_rows): + """basalt's runtime packs the copy as rows arrive (mtp.cpp:680, 1446), its test in one call: two calls give the + one call's bytes, with n_cap = rows + 100 (629 tiles, not 625: the scales start where n_cap puts them).""" + rr = len(proxy_rows) + one = gpu.q5k_proxy_pack(proxy_rows, rr + 100, [(0, rr)]) + two = gpu.q5k_proxy_pack(proxy_rows, rr + 100, [(0, 7777), (7777, rr - 7777)]) + assert np.array_equal(one, two) + + +def proxy_map(rr): + """:250: rows i % 7 == 3 and the last 300 rows without a token, the others id 5i + 1.""" + i = np.arange(rr) + return np.where((i % 7 == 3) | (i >= rr - 300), -1, 5 * i + 1).astype(np.int32) + + +@pytest.fixture(scope="module") +def proxy_copy(proxy_rows): + """The copy of the rescaled rows with basalt's spare capacity (:216, :253).""" + n_cap = len(proxy_rows) + 100 + return gpu.q5k_proxy_pack(proxy_rows, n_cap, [(0, len(proxy_rows))]), n_cap + + +def test_proxy_score_emulation_bit_for_bit(proxy_copy, data): + """px::score_kernel's candidates and tile partials bit for bit against the numpy emulation + (basalt_emu.q5k_proxy_score, with the GPU's expf_ftz for __expf), at a row count that ends inside a tile (19,990: + a masked tail) with basalt's map (:250), on the first 40 tiles and the last 8.""" + proxy, n_cap = proxy_copy + rr = n_cap - 110 + mp = proxy_map(rr) + xc = column(data[1], 1) + cand, part = gpu.q5k_proxy_score(proxy, xc, rr, n_cap, mp) + t = kernels.basalt_q5k_proxy_tiles(rr) + tiles = np.r_[0:40, t - 8:t] + e_cand, e_part = emu.q5k_proxy_score(proxy, xc, rr, n_cap, mp, tiles, gpu.expf_ftz) + assert bad_bits(cand[tiles], e_cand) == 0 and bad_bits(part[tiles], e_part) == 0 + assert np.all(np.isneginf(cand[t - 1, :, 0])) # the last tile: rows 19,968.. masked (map's last 300 rows) + + +def dequant(row): + """A Q5_K row's values as basalt's test computes them on the host (:270-290): d * sc * q - dmin * m in float.""" + b = np.asarray(row, np.uint8).reshape(10, 176) + d, dmin = (b[:, :4].copy().view(np.float16).astype(F32)[:, k] for k in (0, 1)) + out = np.zeros((10, 8, 32), F32) + for j in range(8): + scl = b[:, 4:16].astype(np.int64) + if j < 4: + sci, mi = scl[:, j] & 63, scl[:, j + 4] & 63 + else: + sci = (scl[:, j + 4] & 0xF) | ((scl[:, j - 4] >> 6) << 4) + mi = (scl[:, j + 4] >> 4) | ((scl[:, j] >> 6) << 4) + qs = b[:, 48 + 32 * (j // 2): 80 + 32 * (j // 2)].astype(np.int64) + q = ((qs >> 4) if j & 1 else (qs & 15)) | (((b[:, 16:48].astype(np.int64) >> j) & 1) << 4) + out[:, j] = (d * sci.astype(F32))[:, None] * q.astype(F32) - (dmin * mi.astype(F32))[:, None] + return out.reshape(-1) + + +def trial_x(rng, q5, mp): + """:263-293: 0.8 N(0, 1) noise plus two planted rows among those with a token, the pick at 20 / |row|^2 and a + runner-up at (16 + 0..3) / |row|^2, as a head's logits have.""" + xh = (F32(0.8) * rng.standard_normal(N_IN).astype(F32)).astype(F32) + for pl in range(2): + r = int(rng.integers(len(mp))) + while mp[r] < 0: + r = int(rng.integers(len(mp))) + dq = dequant(q5[r]).astype(np.float64) + alpha = (20.0 if pl == 0 else 16.0 + int(rng.integers(4))) / float(np.sum(dq * dq)) + xh = (xh + (alpha * dq).astype(F32)).astype(F32) + return xh + + +def test_proxy_top1(proxy_copy, proxy_rows): + """:254-349: the two-stage argmax against the exact one, 400 trials on the rescaled rows with basalt's map; a miss + is a pick other than map[host argmax over native_mmvq's logits] (the first maximum, basalt's ``a[i] > a[best]``), + and for a hit |p * sum - 1| with the host double softmax sum. Each trial's id and probability are also checked bit + for bit against the numpy emulation of collect and pick (basalt_emu.q5k_proxy_final) on the score's own outputs + and native_mmvq's logits of the rescored rows.""" + proxy, n_cap = proxy_copy + rr = len(proxy_rows) + mp = proxy_map(rr) + rows = np.flatnonzero(mp >= 0) + rng = np.random.default_rng(349) + trials, miss, max_p_rel, emu_bad, nonfinite = 400, 0, 0.0, 0, 0 + for _ in range(trials): + xq1 = gpu.q8_1(trial_x(rng, proxy_rows, mp), "native") + a = gpu.mmvq(13, proxy_rows, xq1, N_IN, rr, 1)[0] + pid, p, cand, part = gpu.q5k_proxy_top1(proxy, proxy_rows, xq1, rr, n_cap, mp) + best = int(rows[np.argmax(a[rows])]) + if pid == mp[best]: + s = float(np.sum(np.exp(a[rows].astype(np.float64) - np.float64(a[best])))) + max_p_rel = max(max_p_rel, abs(float(p) * s - 1.0)) + else: + miss += 1 + nonfinite += int(not np.isfinite(p)) # basalt's std::max fold (:315) drops a NaN (flash-next.md) + e_id, e_p, _ = emu.q5k_proxy_final(cand, part, a, mp, gpu.expf_ftz) + emu_bad += e_id != pid or bad_bits(p, e_p) != 0 + # basalt: ``if (miss > trials / 50 || max_p_rel > 1.0) fail = 1;`` (:349) + assert miss <= trials // 50 and max_p_rel <= 1.0 and nonfinite == 0, (miss, max_p_rel, nonfinite) + assert emu_bad == 0, emu_bad + + +def test_proxy_top1_edges(proxy_copy, proxy_rows): + """Two cases basalt's test does not reach. Every row masked: collect's early exit, map[0] (0 when negative) with + probability 1 (head_proxy.cuh:193-196). A zero column: every approximate score is 0, so every candidate is within + kDelta and the list keeps 64 of them; the port's fixed order decides which, checked bit for bit against the + emulation.""" + proxy, n_cap = proxy_copy + rr = len(proxy_rows) + zero = gpu.q8_1(np.zeros(N_IN, F32), "native") + pid, p, _, _ = gpu.q5k_proxy_top1(proxy, proxy_rows, zero, rr, n_cap, np.full(rr, -1, np.int32)) + assert pid == 0 and p == 1.0 + mp = proxy_map(rr) + pid, p, cand, part = gpu.q5k_proxy_top1(proxy, proxy_rows, zero, rr, n_cap, mp) + e_id, e_p, listed = emu.q5k_proxy_final(cand, part, gpu.mmvq(13, proxy_rows, zero, N_IN, rr, 1)[0], mp, + gpu.expf_ftz) + assert len(listed) == 64 and pid == e_id == mp[0] and bad_bits(p, e_p) == 0, (pid, e_id, p, e_p) diff --git a/tests/kernels/test_basalt_q8_1.py b/tests/kernels/test_basalt_q8_1.py new file mode 100644 index 00000000..b8d2067b --- /dev/null +++ b/tests/kernels/test_basalt_q8_1.py @@ -0,0 +1,162 @@ +# SPDX-License-Identifier: MIT +# Copyright (c) 2026 Jesús Gulfo +# adapted from basalt (jesdga95/basalt) src/kernels/iq_multi_parity.cpp @ b4c63b55754637f4c72ad53a0f791d425f71eb36 +# (MIT; third_party/NOTICE): check_q8_1_finite's planted blocks, its host transcription and its pass criterion. +"""basalt's q8_1 activation quantizers on Metal (kernels/common/basalt_q8_1.metal). + +- ``check_q8_1_finite``, ported from basalt's iq_multi_parity.cpp:421-484: both quantizers on 3 rows of 2560 N(0, 1) + values with four planted blocks, against the host formula (d = amax / 127 in IEEE fp32, the butterfly's sum, + ``std::round(v[i] / d)``). Basalt's criterion, quoted: every finite block exact, or for ``native_quantize_q8_1`` + ``bool near = path == 1 && gs == os && std::abs((int) gd - (int) od) <= 1;`` (:465) with every code within one + (:466); overflowed blocks finite with codes in +-127, exactly three of them: ``g_fail += bad + (clamped != 3);`` + (:480). +- Bit for bit against the numpy emulation of what nvcc compiles (tests/kernels/basalt_emu.py, matvec.md sections 1-3), + on normal data and on planted edge blocks (zeros, subnormals, overflow, NaN, a scale that flushes); a NaN scale or + sum is sm_120's fp16 0x7fff (docs/research/basalt-nvcc/nan.md). +- How often the native sequence's quotient through the correctly rounded reciprocal, fl(xi * fl(1 / d)), differs from + the correctly rounded quotient fl(xi / d), and how often that changes a code (printed; run with -s).""" + +import numpy as np + +from tests.kernels import basalt_emu as emu +from tests.kernels import basalt_gpu as gpu + +F32 = np.float32 + + +def finite_case(): + n, rows = 2560, 3 + x = np.random.default_rng(18).standard_normal(rows * n).astype(F32) + x[5 * 32: 6 * 32] = 3000.0 # sum 96,000: overflowed + x[9 * 32: 10 * 32] = 0.5 + x[9 * 32 + 3] = -70000.0 # sum -69,984.5 + x[13 * 32: 14 * 32] = 2000.0 + np.arange(32, dtype=F32) # sum 64,496: finite, kept + x[n + 40] = 2.0e7 # amax / 127 overflowed too + return x + + +def host_formula(v): + """The test's host transcription (iq_multi_parity.cpp:437-458): od, os, the codes, and the finite flag.""" + amax = np.abs(v).max() + lane = v.copy() + for o in (16, 8, 4, 2, 1): + lane = lane + lane[np.arange(32) ^ o] + d, s = amax / F32(127.0), lane[0] + od, os = emu.half_bits(d)[()], emu.half_bits(s)[()] + with np.errstate(divide="ignore", invalid="ignore"): + q = np.zeros(32, F32) if amax == 0 else emu.roundf(v / d) + return od, os, q.astype(np.int8), (od & 0x7C00) != 0x7C00 and (os & 0x7C00) != 0x7C00, s + + +def test_check_q8_1_finite(): + x = finite_case() + for path, kind in ((0, "ieee"), (1, "native")): + got = gpu.q8_1(x, kind).reshape(-1, 36) + same = clamped = bad = 0 + for b in range(len(got)): + v = x[32 * b: 32 * b + 32] + od, os, want_q, finite_before, s = host_formula(v) + g = got[b] + gd, gs = int(g[0:2].view(np.uint16)[0]), int(g[2:4].view(np.uint16)[0]) + codes = g[4:].view(np.int8).astype(int) + if finite_before: + want = np.concatenate([np.array([od, os], np.uint16).view(np.uint8), want_q.view(np.uint8)]) + # basalt: ``bool near = path == 1 && gs == os && std::abs((int) gd - (int) od) <= 1;`` (:465), and + # every code within one (:466) + near = path == 1 and gs == os and abs(gd - int(od)) <= 1 and np.all(np.abs(codes - want_q) <= 1) + if np.array_equal(want, g) or near: + same += 1 + else: + bad += 1 + else: + fd, fs = emu.h2f(gd), emu.h2f(gs) + ok = np.isfinite(fd) and np.isfinite(fs) and fd > 0 and ( + gs == os if (os & 0x7C00) != 0x7C00 else abs(fs) == 65504.0 and (fs < 0) == (s < 0)) + ok = ok and codes.min() >= -127 and codes.max() <= 127 + clamped += ok + bad += not ok + # basalt: ``g_fail += bad + (clamped != 3);`` (:480) + assert bad == 0 and clamped == 3, (kind, same, clamped, bad) + assert same == len(got) - 3 + + +def edge_blocks(rng): + """Planted blocks: zeros, subnormals only, subnormals with tiny normals (an IEEE subnormal d), a normal amax whose + native d flushes, mixed signs at the subnormal boundary, overflow, NaN and infinities.""" + sub = lambda k: ((rng.integers(1, 1 << 23, k, dtype=np.uint32)) | (rng.integers(0, 2, k, dtype=np.uint32) << 31)).view(F32) + blocks = [np.zeros(32, F32), -np.zeros(32, F32), sub(32), sub(32) * F32(1.0)] + b = sub(32); b[7] = F32(3e-37); blocks.append(b) # amax normal, d subnormal + b = sub(32); b[0] = F32(2.0 ** -119); blocks.append(b) # d at the boundary + b = sub(32); b[0] = F32(127 * 2.0 ** -126); blocks.append(b) + b = np.full(32, F32(2.0 ** -126)); b[::2] *= -1; blocks.append(b) # sums that cancel exactly + b = sub(32); b[1] = F32(2.0 ** -100); blocks.append(b) # the IEEE emulation's threshold + b = rng.standard_normal(32).astype(F32) * F32(1e-38); blocks.append(b) # normals and subnormals mixed + b = rng.standard_normal(32).astype(F32); b[3] = np.nan; blocks.append(b) + b = rng.standard_normal(32).astype(F32); b[4] = np.inf; blocks.append(b) + blocks.append(np.full(32, np.nan, F32)) + b = rng.standard_normal(32).astype(F32) * F32(1e5); b[0] = F32(3e38); blocks.append(b) + return np.concatenate(blocks) + + +def test_quantizers_match_the_emulation_bit_for_bit(): + rng = np.random.default_rng(5) + x = np.concatenate([finite_case(), rng.standard_normal(1 << 16).astype(F32) * F32(3.0), + (rng.standard_normal(1 << 14) * np.exp(rng.uniform(-80, 80, 1 << 14))).astype(F32), + edge_blocks(rng)]) + nan_blocks = np.isnan(x.reshape(-1, 32)).any(axis=1) + for kind, emulate in (("native", emu.q8_1_native), ("ieee", emu.q8_1_ieee)): + got, want = gpu.q8_1(x, kind).reshape(-1, 36), emulate(x).reshape(-1, 36) + # every block bit for bit, a NaN half as sm_120's 0x7fff (nan.md): the NaN lane's block's sum, the all-NaN + # block's scale and sum + assert np.array_equal(got, want), (kind, np.flatnonzero(np.any(got != want, axis=1))[:8]) + assert np.count_nonzero(got[nan_blocks, :4].copy().view(np.uint16) == 0x7FFF) == 3, kind + + +def test_reciprocal_division_against_the_correctly_rounded_quotient(): + """Where nvcc compiles xi / d as MUFU.RCP then FMUL, the port multiplies by the correctly rounded reciprocal. + Count, on N(0, 1) activations, how often that product differs from the correctly rounded quotient that basalt's + host formula divides with, and how often a code changes; the port's codes are then the host's within one, as + check_q8_1_finite's near rule allows.""" + rng = np.random.default_rng(6) + v = rng.standard_normal((1 << 16, 32)).astype(F32) + amax = np.abs(v).max(axis=1) + d = emu.q8_1_finite(emu.mul_ftz(amax, emu.RCP127))[:, None] + via_rcp = emu.mul_ftz(v, emu.rcp_ftz(d)) + quotient = (v / d).astype(F32) + q_diff = np.count_nonzero(via_rcp.view(np.uint32) != quotient.view(np.uint32)) + c_diff = np.count_nonzero(emu.roundf(via_rcp) != emu.roundf(quotient)) + d_ieee = (amax / F32(127.0)).astype(F32) + d_diff = np.count_nonzero(d[:, 0].view(np.uint32) != d_ieee.view(np.uint32)) + print(f"\nq8_1 native division: {q_diff} of {v.size} quotients ({q_diff / v.size:.3%}) differ from fl(xi / d), " + f"{c_diff} codes ({c_diff / v.size:.4%}); d = fl(amax * fl(1/127)) differs from fl(amax / 127) in " + f"{d_diff} of {len(d_ieee)} blocks ({d_diff / len(d_ieee):.2%})") + assert np.all(np.abs(emu.roundf(via_rcp) - emu.roundf(quotient)) <= 1) + got = gpu.q8_1(v.reshape(-1), "native").reshape(-1, 36)[:, 4:].view(np.int8) + assert np.array_equal(got, emu.q8_1_codes(emu.roundf(via_rcp), amax)) + + +def test_swiglu_quantizer(): + """native_swiglu_quantize_q8_1: no basalt test covers it (pr-b-scope-basalt.md section 2.5). Its value is + __fmul_rn(__fdividef(g, __fadd_rn(1, __expf(-g))), up); MUFU.EX2 has no documented Metal counterpart, so the + exponential is taken from the GPU's fast::exp2 of the same product and every other step is checked bit for bit, + then the codes against the IEEE SiLU product with check_q8_1_finite's near rule.""" + rng = np.random.default_rng(7) + n = 2560 * 4 + g = (rng.standard_normal(n) * 4).astype(F32) + up = rng.standard_normal(n).astype(F32) + got = gpu.q8_1(g, "swiglu", up).reshape(-1, 36) + src = gpu.kernels.PRELUDE + gpu.kernels.template("basalt_fp.metal") + """ +kernel void ex(device const float* g [[buffer(0)]], device float* e [[buffer(1)]], constant uint& n [[buffer(2)]], + uint i [[thread_position_in_grid]]) { + if (i < n) e[i] = ftz(fast::exp2(mul_ftz(g[i], as_type(0xBFB8AA3Bu)))); +} +""" + e = np.frombuffer(gpu.run(gpu.pipeline(src, "ex"), [g.tobytes(), 4 * n], np.uint32(n).tobytes(), 2, + n // 256, 256)[1], F32) + xi = emu.mul_ftz(emu.mul_ftz(g, emu.rcp_ftz(emu.add_ftz(F32(1.0), e))), up) + assert np.array_equal(got.reshape(-1), emu.q8_1_native(xi)) + exact = np.exp2(emu.mul_ftz(g, np.uint32(0xBFB8AA3B).view(F32)).astype(np.float64)).astype(F32) + print(f"\nfast::exp2 differs from the correctly rounded exp2 on {np.count_nonzero(exact != e)} of {n} values") + silu = (g.astype(np.float64) / (1 + np.exp(-g.astype(np.float64))) * up).astype(F32) + host = emu.q8_1_ieee(silu).reshape(-1, 36) + assert np.all(np.abs(got[:, 4:].view(np.int8).astype(int) - host[:, 4:].view(np.int8)) <= 1) diff --git a/tests/kernels/test_basalt_s2_experts.py b/tests/kernels/test_basalt_s2_experts.py new file mode 100644 index 00000000..8d83fab3 --- /dev/null +++ b/tests/kernels/test_basalt_s2_experts.py @@ -0,0 +1,745 @@ +# SPDX-License-Identifier: MIT +# Copyright (c) 2026 Jesús Gulfo +# adapted from basalt (jesdga95/basalt) src/kernels/s2_expert_grouped_parity.cpp and src/kernels/quantize_act_parity.cpp +# @ b4c63b55754637f4c72ad53a0f791d425f71eb36 (MIT; third_party/NOTICE): their fixtures, plans, sentinels and pass +# criteria. +"""basalt's drafter experts on Metal (kernels/common/basalt_s2_experts.metal): moe_group_resident, +quantize_q8_0_scaled and moe_grouped_s2 (gate/up, SwiGLU, the intermediate's quantizer, down), with the IEEE helpers +they share (kernels/common/basalt_q8_1.metal) and the fp16 conversion (basalt_fp.metal's f16_bits). + +Fixtures follow basalt's tests; basalt draws them with std::mt19937 and std:: distributions, whose outputs are +implementation-defined, and these draw the same distributions with numpy. basalt's fixtures never make a subnormal (its +scales keep every product above 1e-6), so planted inputs exercise the IEEE paths, each with a negative control: the +same kernels with the plain Metal operation in place of each IEEE helper must differ on them.""" + +import struct + +import numpy as np +import pytest + +from monolith import kernels +from tests.contract import gguf_reference +from tests.kernels import basalt_emu as emu +from tests.kernels import basalt_gpu as gpu +from tests.kernels.test_basalt_iq_parity import quantize_q2_0 + +F32 = np.float32 +H, FF, K = kernels.S2_H, kernels.S2_FF, 10 +NC_GU, NC_D = H // 32, FF // 32 +XROW = NC_GU * kernels.Q8_0_BLOCK_BYTES # one token's activation row of block_q8_0 +O_D_CODES = 2 * FF * (H // 4) +O_GU_SCALES = O_D_CODES + H * (FF // 4) +O_D_SCALES = O_GU_SCALES + 2 * FF * (H // 64) * 2 + + +def gpu_eval(body, *arrays, out=1): + """A one-off kernel over n threads on basalt_q8_1_source's helpers: ``body`` computes ``r`` from ``a``, ``b``, ``c`` + (float inputs at index i); returns the float32 r.""" + names = "abc"[: len(arrays)] + args = "".join(f"device const float* {v}_ [[buffer({k})]], " for k, v in enumerate(names)) + loads = "".join(f"const float {v} = {v}_[i]; " for v in names) + src = kernels.basalt_q8_1_source() + f""" +kernel void ev({args}device float* r_ [[buffer({len(names)})]], constant uint& n [[buffer({len(names) + 1})]], + uint i [[thread_position_in_grid]]) {{ + if (i >= n) return; + {loads}float r; {body} + r_[i] = r; +}} +""" + arrays = [np.ascontiguousarray(a, F32).reshape(-1) for a in arrays] + n = arrays[0].size + res = gpu.run(gpu.pipeline(src, "ev"), [a.tobytes() for a in arrays] + [4 * n], np.uint32(n).tobytes(), + len(arrays) + 1, -(-n // 256), 256) + return np.frombuffer(res[len(arrays)], F32) + + +def same_bits(got, want): + return got.view(np.uint32) == np.asarray(want, F32).view(np.uint32) + + +# ---- the fp16 conversion: quantize_act_parity's fp16 half (quantize_act_parity.cpp:283-336) ------------------------- +# The file's Q8_0 half (run_case on quantize_q8_0, :70-130, :241-277) and Q8_K half (:337-401) are not ported: this +# path calls neither quantize_q8_0 nor quantize_q8_K; the drafter quantizes with quantize_q8_0_scaled (mtp.cpp:933; +# docs/design/flash-next.md), whose test below borrows the Q8_0 half's five distributions and byte criterion. + +def test_f16_bits_is_f16_from_f32(): + """basalt_fp.metal's f16_bits (Metal's half(), which q8_1_put and the quantizer share) against basalt's vectors, + quoted: ``if (got != c.want) {`` (quantize_act_parity.cpp:322); h2f(0x0001) == 2^-24, quoted: + ``if (!sub_ok) ++bad;`` (:335); and against the transcription of f16_from_f32 (tests/kernels/basalt_emu.py) on + the fp16 subnormal range, the 65504-65520 boundary, both overflow edges and random float32 patterns (a NaN's + payload is the GPU's).""" + cases = [(1e30, 0x7C00), (-1e30, 0xFC00), (65536.0, 0x7C00), (3.0e38, 0x7C00), (65504.0, 0x7BFF), + (65519.996, 0x7BFF), (65520.0, 0x7C00), (65536.0, 0x7C00), (5.9604645e-8, 0x0001), (1.0, 0x3C00), + (0.0, 0x0000)] + rng = np.random.default_rng(3) + sweep = np.concatenate([ + np.array([c for c, _ in cases], F32), + np.arange(0x33000000, 0x38800000, 97, dtype=np.uint32).view(F32), # 2^-25 .. 2^-14: fp16 subnormals + np.arange(0x477FE000, 0x47800100, dtype=np.uint32).view(F32), # 65504 .. 65536 + -np.arange(0x477FE000, 0x47800100, 7, dtype=np.uint32).view(F32), + np.uint32([1, 0x007FFFFF, 0x00800000, 0x80000001, 0x7F7FFFFF, 0xFF7FFFFF]).view(F32), + rng.integers(0, 2 ** 32, 1 << 20, dtype=np.uint64).astype(np.uint32).view(F32)]) + src = kernels.PRELUDE + kernels.template("basalt_fp.metal") + """ +kernel void f16(device const float* x [[buffer(0)]], device ushort* h [[buffer(1)]], device float* back [[buffer(2)]], + constant uint& n [[buffer(3)]], uint i [[thread_position_in_grid]]) { + if (i >= n) return; + h[i] = f16_bits(x[i]); + back[i] = h2f(ushort(i)); +} +""" + n = sweep.size + out = gpu.run(gpu.pipeline(src, "f16"), [sweep.tobytes(), 2 * n, 4 * n], np.uint32(n).tobytes(), 3, + -(-n // 256), 256) + got = np.frombuffer(out[1], np.uint16) + fp16_bad = sum(int(got[k]) != want for k, (_, want) in enumerate(cases)) + # basalt: if (got != c.want) { + assert fp16_bad == 0, [(c, hex(w), hex(int(got[k]))) for k, (c, w) in enumerate(cases)] + back = np.frombuffer(out[2], F32)[:65536] + assert back[1] == F32(5.9604645e-8) # basalt: sub_ok = (sub == 5.9604645e-8f) + with np.errstate(invalid="ignore"): + exact = np.arange(65536, dtype=np.uint32).astype(np.uint16).view(np.float16).astype(F32) + assert np.array_equal(back.view(np.uint32)[~np.isnan(exact)], exact.view(np.uint32)[~np.isnan(exact)]) + want = emu.f16_from_f32(sweep) + nan = np.isnan(sweep) + assert np.array_equal(got[~nan], want[~nan]), np.flatnonzero(got[~nan] != want[~nan])[:8] + assert np.all((got[nan] & 0x7C00) == 0x7C00) and np.all(got[nan] & 0x3FF) + print(f"\nf16_bits: {len(cases)} basalt vectors, {np.count_nonzero(~nan)} values bit for bit with f16_from_f32") + + +def test_builders_take_basalt_launches_only(): + """The builders refuse the shapes basalt cannot launch (CUDA's largest gridDim.x and .y: past them basalt's launch + fails and exits, and here a 32-bit threadgroup position or int(tg.y) would wrap) and take its largest: 65,535 + groups, 858,993,458 entries (2,147,483,645 SwiGLU and quantizer threadgroups), and quantizer block counts past 2^32 + (Q80Params.n_blocks is 64-bit, basalt's long long).""" + g = kernels.basalt_s2_grids(65535, 858_993_458) + assert g == {"gu": (40, 65535), "swiglu": 2_147_483_645, "quant": 2_147_483_645, "down": (40, 65535)} + assert struct.unpack(" 0) & (want_s < F32(2.0 ** -126))) + inf_inv = np.count_nonzero((want_s > 0) & np.isinf(F32(1.0) / want_s)) + assert sub > 100 and inf_inv > 10, (sub, inf_inv) + print(f"\nquantize_q8_0_scaled, {dist}: {x.size // 32} blocks byte for byte") + + +# ---- s2_expert_grouped_parity (s2_expert_grouped_parity.cpp:83-106, :149-260, :263-460) ------------------------------ +# Ported: section 4 (moe_grouped_s2, 8 tokens x 10 entries, a blob outside the arena), section 5 (moe_group_resident + +# moe_grouped_s2 at the drafter's shape), and the properties sections 2 and 3 check (a device count below the +# capacity; each entry reading its own token's row), on the grouped kernels. Left out, as this path does not run them: +# - the per-hit kernels (sections 1-3 and 6-8: moe_hit_grouped_s2, _dev, _multi) and the previous grouped kernels +# (OLD_GROUPED=1): the drafter calls moe_grouped_s2 only (mtp.cpp:934), and the contract compares each kernel with +# its own per-entry calls instead of a previous kernel (docs/design/flash-next.md); +# - the fp16-d runs (a null x_scales): they select quantize_q8_0 for the intermediate (s2_expert_grouped.cu:1112), +# and the drafter always passes its fp32 scales (it allocates hit_xs_, mtp.cpp:438); +# - the misaligned fallbacks (sections 6-8): new_grouped (s2_expert_grouped.cu:504-508) sends a misaligned x or +# scratch to the previous kernels; here 4-byte aligned x and scratch are a precondition the program binding +# enforces. + +BLOB = kernels.S2_BLOB_BYTES + + +def fill_blob(rng): + """fill_blob (:84-88): random code bytes, then fp16 scales of either sign with magnitude U[1e-3, 3e-2].""" + b = np.empty(BLOB, np.uint8) + b[:O_GU_SCALES] = rng.integers(0, 256, O_GU_SCALES) + n = (BLOB - O_GU_SCALES) // 2 + f = np.where(rng.integers(0, 2, n) == 1, F32(-1), F32(1)) * rng.uniform(1e-3, 3e-2, n).astype(F32) + b[O_GU_SCALES:] = emu.f16_from_f32(f).view(np.uint8) + return b + + +def fill_x(rng, n_tok): + """fill_x (:90-106): per 32-value chunk an fp32 scale U[2e-3, 5e-2] (and its fp16 as the block's d), 32 codes + uniform in [-127, 127], one chunk in 16 all 127 and one all -127 (saturated on purpose).""" + xs = rng.uniform(2e-3, 5e-2, n_tok * NC_GU).astype(F32) + blk = np.zeros((n_tok * NC_GU, 34), np.uint8) + blk[:, :2] = emu.f16_from_f32(xs).view(np.uint8).reshape(-1, 2) + mode = rng.integers(0, 16, len(blk)) + v = rng.integers(-127, 128, (len(blk), 32)) + v[mode == 0], v[mode == 1] = 127, -127 + blk[:, 2:] = v.astype(np.int8).view(np.uint8) + return blk.reshape(-1), xs + + +class Fixture: + """make_blobs(12) (:244-252) in one buffer, the last blob also alone in a second buffer (the test's mapped host + blob, :372-376: on this Mac every buffer is host memory; what carries over is a blob outside the arena), and 8 + tokens' activation rows with their fp32 scales.""" + + def __init__(self, seed=20260928, nb=12): + self.rng = np.random.default_rng(seed) + self.nb = nb + self.h = np.stack([fill_blob(self.rng) for _ in range(nb)]) + dev = gpu.device() + self.bufs = [gpu.nt.Buffer(dev, self.h.tobytes()), gpu.nt.Buffer(dev, self.h[nb - 1].tobytes())] + self.x, self.xs = fill_x(self.rng, 8) + + def blob(self, ref): + """The host bytes of a group's blob, ``ref`` = (buffer index, byte offset).""" + return self.h[self.nb - 1] if ref[0] == 1 else self.h[ref[1] // BLOB] + + +@pytest.fixture(scope="module") +def fx(): + return Fixture() + + +def groups_by_expert(slots): + """Hits to groups (one a distinct expert, first-appearance order, entries in hit order): (experts, grp_start, the + hits in entry order).""" + experts, members = [], {} + for h, s in enumerate(slots): + if s not in members: + experts.append(s) + members[s] = [] + members[s].append(h) + order = [h for s in experts for h in members[s]] + return experts, [int(v) for v in np.cumsum([0] + [len(members[s]) for s in experts])], order + + +def regions(e, cap): + """Entry e's slices of the scratch bytes: its gate (SwiGLU) row, up row, intermediate blocks and their scales.""" + sc = kernels.basalt_s2_scratch(cap) + blk = NC_D * kernels.Q8_0_BLOCK_BYTES + return [slice(4 * e * FF, 4 * (e + 1) * FF), slice(4 * (cap + e) * FF, 4 * (cap + e + 1) * FF), + slice(sc["hq"] + e * blk, sc["hq"] + (e + 1) * blk), + slice(sc["hs"] + 4 * e * NC_D, sc["hs"] + 4 * (e + 1) * NC_D)] + + +def per_entry(fx, grp, grp_start, n_groups, ent_tok, ent_dst, cap_groups, cap, n_rows, x, xs, src=None): + """Each entry of the plan alone (one group of one entry, the same capacities and entry arrays): the same kernels' + arithmetic one entry a call, the contract's comparand for basalt's previous kernels. Returns the output and scratch + the grouped call must write: entry e's row and scratch slices from call e, the rest (every capacity slot past the + plan, the padding) from the first call, after checking each call left every other output row at its sentinel.""" + out = np.full((n_rows, H), 0xA5A5A5A5, np.uint32) + scratch = None + for g in range(n_groups): + for e in range(grp_start[g], min(grp_start[g + 1], grp_start[g] + kernels.S2_GMAX)): + r = gpu.s2_experts(fx.bufs, [grp[g]], [e, e + 1], 1, ent_tok, ent_dst, x, xs, cap_groups, cap, n_rows, + src=src) + d = int(ent_dst[e]) + assert np.all(np.delete(r["out"], d, axis=0) == 0xA5A5A5A5), ("stray store", e) + out[d] = r["out"][d] + if scratch is None: + scratch = r["scratch"].copy() + for sl in regions(e, cap): + scratch[sl] = r["scratch"][sl] + return out, scratch + + +def row_ref(codes, scales, xq, xs): + """row_ref (:110-128) for rows ``codes`` (R, bytes) / fp16 ``scales`` (R, n / 64) against one activation row: + (ref, mag), sum_c dw * dx * sum_e (code_e - 1) * x_e in float64 and the sum of |terms|.""" + nk = codes.shape[1] // 8 + w = ((codes[:, np.arange(32 * nk) // 4].astype(np.int64) >> (2 * (np.arange(32 * nk) % 4))) & 3) - 1 + x = np.asarray(xq, np.uint8).reshape(nk, 34)[:, 2:].view(np.int8).astype(np.int64) + s = (w.reshape(-1, nk, 32) * x[None]).sum(axis=-1).astype(np.float64) + t = emu.h2f(scales).astype(np.float64)[:, np.arange(nk) // 2] * np.asarray(xs, np.float64)[None] * s + return t.sum(axis=1), np.abs(t).sum(axis=1) + + +def blob_parts(b): + """A blob's gate/up codes (1280 slots) and fp16 scale bits, its down codes and scale bits.""" + return (b[: O_D_CODES].reshape(2 * FF, H // 4), b[O_GU_SCALES: O_D_SCALES].view(np.uint16).reshape(2 * FF, H // 64), + b[O_D_CODES: O_GU_SCALES].reshape(H, FF // 4), b[O_D_SCALES:].view(np.uint16).reshape(H, FF // 64)) + + +def reference(fx, r, plan, cap, x, xs): + """reference (:200-235): every 7th up row of every entry against the activation row it read, every 13th down row + against the run's own intermediate; criterion, quoted: ``return std::isfinite(got) && std::fabs((double) got - ref) + <= 4e-5 * mag + 1e-30;`` (:131) and ``if (bad || checked == 0) ++g_fail;`` (:234). Gate rows are not referenced: + the SwiGLU overwrites them in place.""" + grp, grp_start, n_groups, ent_tok, ent_dst = plan + sc = kernels.basalt_s2_scratch(cap) + gu = r["scratch"][: 4 * 2 * cap * FF].view(F32) + hq, hs = r["scratch"][sc["hq"]:], r["scratch"][sc["hs"]: sc["hs"] + 4 * cap * NC_D].view(F32) + out = r["out"].view(F32) + checked = bad = 0 + worst = 0.0 + up_rows, d_rows = np.arange(0, FF, 7), np.arange(0, H, 13) + for g in range(n_groups): + cgu, sgu, cd, sd = blob_parts(fx.blob(grp[g])) + for e in range(grp_start[g], min(grp_start[g + 1], grp_start[g] + kernels.S2_GMAX)): + t = int(ent_tok[e]) + for (ref, mag), got in ( + (row_ref(cgu[2 * up_rows + 1], sgu[2 * up_rows + 1], x[t * XROW: (t + 1) * XROW], + xs[t * NC_GU: (t + 1) * NC_GU]), gu[(cap + e) * FF + up_rows]), + (row_ref(cd[d_rows], sd[d_rows], hq[e * NC_D * 34: (e + 1) * NC_D * 34], + hs[e * NC_D: (e + 1) * NC_D]), out[int(ent_dst[e]), d_rows])): + with np.errstate(invalid="ignore", over="ignore"): + ok = np.isfinite(got) & (np.abs(got.astype(np.float64) - ref) <= 4e-5 * mag + 1e-30) + rel = np.abs(got.astype(np.float64) - ref) / np.where(mag > 0, mag, np.inf) + checked += ok.size + bad += np.count_nonzero(~ok) + worst = max(worst, float(np.nanmax(rel))) + return checked, bad, worst + + +def emulation(fx, r, plan, cap, x, xs): + """Every stage bit for bit against tests/kernels/basalt_emu.py (s2_experts.md): each entry's up rows, its SwiGLU + row from the emulated gate rows (the exponential taken from the GPU's expf_neg), the intermediate's quantizer over + every capacity entry, and the down rows from the GPU's intermediate.""" + from tests.kernels.test_basalt_experts import gpu_expf_neg + grp, grp_start, n_groups, ent_tok, ent_dst = plan + sc = kernels.basalt_s2_scratch(cap) + s = r["scratch"] + gu = s[: 4 * 2 * cap * FF].view(F32) + for g in range(n_groups): + cgu, sgu, cd, sd = blob_parts(fx.blob(grp[g])) + ents = np.arange(grp_start[g], min(grp_start[g + 1], grp_start[g] + kernels.S2_GMAX)) + if not ents.size: + continue + toks = np.asarray(ent_tok)[ents] + xq = np.stack([x[t * XROW: (t + 1) * XROW] for t in toks]) + xr = np.stack([xs[t * NC_GU: (t + 1) * NC_GU] for t in toks]) + gate, up = emu.s2_dots(cgu[0::2], sgu[0::2], xq, xr), emu.s2_dots(cgu[1::2], sgu[1::2], xq, xr) + got_up = np.stack([gu[(cap + e) * FF: (cap + e + 1) * FF] for e in ents]) + assert np.array_equal(got_up.view(np.uint32), up.view(np.uint32)), ("up", g) + h = emu.s2_swiglu(gate, up, gpu_expf_neg(gate).reshape(gate.shape)) + got_h = np.stack([gu[e * FF: (e + 1) * FF] for e in ents]) + assert np.array_equal(got_h.view(np.uint32), h.view(np.uint32)), ("swiglu", g) + hq, hs = emu.q8_0_scaled(gu[: cap * FF]) + assert np.array_equal(s[sc["hq"]: sc["hq"] + hq.size], hq), "intermediate" + assert np.array_equal(s[sc["hs"]: sc["hs"] + 4 * hs.size], hs.view(np.uint8)), "intermediate scales" + blk = NC_D * 34 + for g in range(n_groups): + cgu, sgu, cd, sd = blob_parts(fx.blob(grp[g])) + ents = list(range(grp_start[g], min(grp_start[g + 1], grp_start[g] + kernels.S2_GMAX))) + if not ents: + continue + want = emu.s2_dots(cd, sd, np.stack([hq[e * blk: (e + 1) * blk] for e in ents]), + np.stack([hs[e * NC_D: (e + 1) * NC_D] for e in ents])) + for k, e in enumerate(ents): + assert np.array_equal(r["out"][int(ent_dst[e])], want[k].view(np.uint32)), ("down", e) + + +def check_call(name, fx, grp, grp_start, n_groups, ent_tok, ent_dst, cap_groups, cap, n_rows, resident=None, x=None, + xs=None): + """``twice`` (:149-191) with the contract's comparand: the grouped call from sentinel-filled buffers (out 0xA5, + scratch 0x5A, :153-154) against the per-entry calls, the output and the scratch (gate/up, the quantized + intermediate, its scales) byte for byte, quoted: ``diff_out += std::memcmp(&r[0].out[i], &r[1].out[i], 4) != 0;`` + (:175) and ``const bool ok = diff_out + diff_gu + diff_q8 + diff_hs == 0;`` (:182); then reference() and the + emulation. Returns the grouped run and its plan.""" + x, xs = (fx.x, fx.xs) if x is None else (x, xs) + r = gpu.s2_experts(fx.bufs, grp, grp_start, n_groups, ent_tok, ent_dst, x, xs, cap_groups, cap, n_rows, + resident=resident) + if resident is not None: # the device's plan, as basalt's test reads it back (:446) + n_groups, grp_start = int(r["n_groups"][0]), [int(v) for v in r["grp_start"]] + ent_tok, ent_dst = r["ent_tok"], r["ent_dst"] + grp = [(0, int(a) - fx.bufs[0].gpu_address) for a in r["grp_ptr"][:n_groups]] + plan = (grp, grp_start, n_groups, ent_tok, ent_dst) + want_out, want_s = per_entry(fx, *plan, cap_groups, cap, n_rows, x, xs) + sc = kernels.basalt_s2_scratch(cap) + diff_out = np.count_nonzero(r["out"] != want_out) + diff = r["scratch"] != want_s + diff_gu, diff_q8, diff_hs = (np.count_nonzero(diff[a:b]) for a, b in ((0, sc["hq"]), (sc["hq"], sc["hs"]), + (sc["hs"], sc["bytes"]))) + ok = diff_out + diff_gu + diff_q8 + diff_hs == 0 + assert ok, (name, diff_out, diff_gu, diff_q8, diff_hs) + checked, bad, worst = reference(fx, r, plan, cap, x, xs) + assert not (bad or checked == 0), (name, checked, bad, worst) # basalt: if (bad || checked == 0) ++g_fail; + emulation(fx, r, plan, cap, x, xs) + print(f"\n{name}: bitwise identical to {grp_start[n_groups] - grp_start[0]} per-entry calls; host reference: " + f"{checked} rows, {bad} outside tolerance, worst {worst:.2e} of sum|term|; emulation bit for bit") + return r, plan + + +def test_grouped_8_tokens(fx): + """Section 4 (:369-425): moe_grouped_s2 with 8 tokens x 10 entries in groups of 8, 1, 5, 2, 7, 3, 1, 6, 4, ..., + group 3 on the blob in its own buffer (the mapped host blob), the others blob gi % 11 of the arena, destinations a + shuffle of the 80 rows, each entry reading its own token's row (dst / 10), cap_groups = groups + 3 with the table + padded by group 0's address and the starts by the last. Only the fp32-scale run: a null x_scales (the fp16 d run) + selects quantize_q8_0, which the drafter never takes (it allocates hit_xs_, mtp.cpp:438).""" + n = 8 * K + sizes = [8, 1, 5, 2, 7, 3, 1, 6, 4, 8, 1, 2, 3, 4, 5, 6, 7, 1, 1, 5] + order = np.random.default_rng(4).permutation(n) + grp, gstart, edst = [], [0], [] + at = gi = 0 + while at < n: + sz = min(sizes[gi % 20], n - at) + grp.append((1, 0) if gi == 3 else (0, (gi % (fx.nb - 1)) * BLOB)) + edst += [int(o) for o in order[at: at + sz]] + at += sz + gstart.append(at) + gi += 1 + r, _ = check_call(f"moe_grouped_s2 ({gi} groups, fp32 scales)", fx, grp, gstart, gi, [d // K for d in edst], edst, + gi + 3, n, n) + assert np.count_nonzero(r["out"] == 0xA5A5A5A5) == 0 # every row written + + +def test_group_resident_drafter_shape(fx): + """Section 5 (:427-460): moe_group_resident then moe_grouped_s2 at the drafter layer's shape, 5 tokens x 10 routed + ids (distinct within a token, shared across tokens, from 12 experts resident at base + id * BLOB), cap_groups = + cap_entries = 50 (mtp.cpp:931-935); the plan read back from the device as basalt's test does, and checked against a + host transcription of group_resident_kernel (groups in first-appearance order, entries in routing order).""" + T, n, rng = 5, 5 * K, np.random.default_rng(5) + ids = np.concatenate([rng.permutation(fx.nb)[:K] for _ in range(T)]).astype(np.int32) + r, (grp, gstart, ng, etok, edst) = check_call("moe_group_resident + moe_grouped_s2 (fp32)", fx, None, None, 0, + None, None, n, n, n, resident=(ids, K, 0, 0)) + experts, want_start, order = groups_by_expert(list(ids)) + assert ng == len(experts) and gstart[: ng + 1] == want_start and r["n_groups"][1] == n + assert [o for _, o in grp] == [int(e) * BLOB for e in experts] + assert list(edst[:n]) == order and list(etok[:n]) == [i // K for i in order] + + +def test_verify_window_rows(fx): + """Section 3's verify window (:339-367) on the grouped kernels: 4 tokens x 10 routed entries, 29 hits (routing + order, each on a random blob), grouped by expert, each entry reading its own token's row (dst / 10); 40-entry + capacity and a device group count below cap_groups. basalt runs this section on the per-hit kernels + (moe_hit_grouped_s2_multi), which the drafter does not call; the property it checks, rows per token, is + moe_grouped_s2's ent_tok.""" + n, count, rng = 4 * K, 29, np.random.default_rng(3) + ent_ids = rng.permutation(n) + slot = rng.integers(0, fx.nb, n) + dst = np.sort(ent_ids[:count]) + experts, gstart, order = groups_by_expert([int(s) for s in slot[:count]]) + edst = [int(dst[h]) for h in order] + check_call("moe_grouped_s2 (4 tokens, 29 entries)", fx, [(0, s * BLOB) for s in experts], gstart, len(experts), + [d // K for d in edst], edst, n, n, n) + + +def test_device_count(fx): + """Section 2's device count (:304-337) on the grouped kernels: capacity 10, 7 entries counted (blob (7i + 1) mod 12, + destinations a shuffle of the 10 rows), one token; the group count on the device, below cap_groups; quoted: ``if + (touched) ++g_fail;`` (:336), the rows of the entries past the count keep the sentinel. basalt runs it on the + per-hit kernels (moe_hit_grouped_s2_dev), which the drafter does not call.""" + cap, count = 10, 7 + slot = [(i * 7 + 1) % fx.nb for i in range(cap)] + dst = np.random.default_rng(2).permutation(cap) + experts, gstart, order = groups_by_expert(slot[:count]) + edst = [int(dst[h]) for h in order] + [int(d) for d in dst[count:]] + r, _ = check_call("moe_grouped_s2 (count 7 of 10)", fx, [(0, s * BLOB) for s in experts], gstart, len(experts), + [0] * cap, edst, cap, cap, cap) + touched = np.count_nonzero(r["out"][dst[count:]] != 0xA5A5A5A5) + assert touched == 0, touched + + +def test_whole_expert_against_float64(): + """The contract's double-precision reference for the drafter expert (docs/design/flash-next.md): basalt checks + swiglu_kernel only by comparing a run of its old path with one of its new, both of which launch it + (s2_expert_grouped.cu:1108), and its float64 reference covers the up rows and the down rows from the run's own + intermediate (s2_expert_grouped_parity.cpp:200-235). Here the quantizer on fp32 activations, then + moe_grouped_s2 (gate/up, the SwiGLU, the intermediate's quantizer, down), against a float64 expert on the fp32 + activations, built as test_basalt_experts.py's test_whole_expert_against_float64 builds the routed expert's + (native_expert_parity.cpp:46-78, :387-402): 3 tokens of N(0, 1) values, row r's weights + 0.02 (0.5 + (r % 7) / 7) N(0, 1) quantized to Q2_0 (quantize_q2_0) and laid out as the drafter's blob, dequantized + on the host by ggml's dequantize_row_q2_0 (tests/contract/gguf_reference.py); g and u in double, + h = (float) (g / (1 + exp(-g)) * u) with numpy's exp (no device function), out = D h in double. Criterion, the + nearest basalt bound, quoted: ``const bool ok = ec < 3e-2 && eg < 3e-2 && std::isfinite(ec) && std::isfinite(eg);`` + (native_expert_parity.cpp:368), eg the relative L1 error (:38-42), on out and on the SwiGLU half against h.""" + nt, rng = 3, np.random.default_rng(17) + + def q2(rows, cols): + scale = (0.02 * (0.5 + (np.arange(rows) % 7) / 7.0)).astype(F32)[:, None] + return quantize_q2_0(scale * rng.standard_normal((rows, cols)).astype(F32)).reshape(rows, cols // 64, 18) + + G, U, D = q2(FF, H), q2(FF, H), q2(H, FF) + gu = np.stack([G, U], axis=1).reshape(2 * FF, H // 64, 18) # slot 2r gate row r, 2r + 1 up row r + blob = np.concatenate([gu[..., 2:].reshape(-1), D[..., 2:].reshape(-1), gu[..., :2].reshape(-1), + D[..., :2].reshape(-1)]) + assert blob.size == BLOB + Wg, Wu, Wd = (gguf_reference.dequantize(42, m.reshape(len(m), -1)).astype(np.float64) for m in (G, U, D)) + x = rng.standard_normal((nt, H)).astype(F32) + g, u = x.astype(np.float64) @ Wg.T, x.astype(np.float64) @ Wu.T + h = (g / (1.0 + np.exp(-g)) * u).astype(F32) + ref = (h.astype(np.float64) @ Wd.T).astype(F32) + xq, xs = gpu.q8_0_scaled(x.reshape(-1)) + r = gpu.s2_experts([gpu.nt.Buffer(gpu.device(), blob.tobytes())], [(0, 0)], [0, nt], 1, np.arange(nt), + np.arange(nt), xq, xs, 1, nt, nt) + got_h, got = r["scratch"][: 4 * nt * FF].view(F32).reshape(nt, FF), r["out"].view(F32) + rel = lambda a, b: np.abs(a.astype(np.float64) - b).sum() / (np.abs(b.astype(np.float64)).sum() + 1e-30) + eh, eg = rel(got_h, h), rel(got, ref) + print(f"\ndrafter expert Q2_0 {H} x {FF}, {nt} tokens against float64: SwiGLU rel {eh:.2e}, out rel {eg:.2e}") + # basalt: const bool ok = ec < 3e-2 && eg < 3e-2 && std::isfinite(ec) && std::isfinite(eg); + assert np.isfinite(eg) and eg < 3e-2 and np.isfinite(got).all(), eg + assert np.isfinite(eh) and eh < 3e-2 and np.isfinite(got_h).all(), eh + + +# ---- the IEEE helpers, bit for bit against numpy's IEEE float32 ------------------------------------------------------ + +def signed(rng, n, lo, hi): + """n float32 of random sign with log2 |x| uniform in [lo, hi) (subnormals by their bit patterns below -126).""" + v = rng.choice([-1.0, 1.0], n) * np.exp2(rng.uniform(lo, hi, n)) + sub = np.abs(v) < 2.0 ** -126 + v = v.astype(F32) + v[sub] = (np.sign(v[sub]) * rng.integers(1, 1 << 23, np.count_nonzero(sub)).astype(np.uint32).view(F32)).astype(F32) + return v + + +def helper_case(name, body, plain, want, *args, min_diff=10): + """The helper (``body``) bit for bit against numpy (``want``), NaN as NaN; the plain Metal operation (``plain``) + must differ from numpy on at least ``min_diff`` inputs, or the planted inputs would not test the helper.""" + got, raw = gpu_eval(body, *args), gpu_eval(plain, *args) + nan = np.isnan(want) + ok = (same_bits(got, want) & ~nan) | (np.isnan(got) & nan) + assert ok.all(), (name, np.flatnonzero(~ok)[:8], [a[np.flatnonzero(~ok)[:4]] for a in args]) + diff = np.count_nonzero(~((same_bits(raw, want) & ~nan) | (np.isnan(raw) & nan))) + assert diff >= min_diff, (name, diff) + return diff + + +def test_ieee_helpers(): + """basalt_q8_1.metal's ieee_div127, ieee_rcp, ieee_fma (an integer n) and ieee_div (b >= 1) bit for bit against + numpy's IEEE float32 (fma: tests/kernels/basalt_emu.py's fma32) on planted inputs: subnormal and tiny operands and + results, the 2^-126 boundary, cancellations to a subnormal sum, ties broken by a subnormal addend, overflow to + infinity, signed zeros, infinities and NaN; each with the plain Metal operation differing on them (the negative + control).""" + rng = np.random.default_rng(12) + n = 1 << 16 + with np.errstate(all="ignore"): + amax = np.abs(np.concatenate([signed(rng, n, -149, -90), np.uint32(np.arange(1, 4096)).view(F32), + F32([0.0, 2.0 ** -126, 2.0 ** -119, 2.0 ** -100, 1.0, 3e38, np.inf])])) + d127 = helper_case("ieee_div127", "r = ieee_div127(a);", "r = a / 127.0f;", amax / F32(127), amax) + s = np.abs(np.concatenate([signed(rng, n, -149, -95), F32([0.0, -0.0, 2.0 ** -149, 2.0 ** -128, 2.0 ** -127, + 2.0 ** -126, 2.0 ** -100, 1.0, 2.0 ** 120, + np.inf, np.nan])])) + s[-10] = -0.0 + rcp = helper_case("ieee_rcp", "r = ieee_rcp(a);", "r = 1.0f / a;", F32(1) / s, s) + # fma(a, n, c): a and c over every magnitude class, n an integer up to 2^13 (|s - hx| <= 8128) + a = np.concatenate([signed(rng, n, -149, -90), signed(rng, n, -100, 10), signed(rng, n, -149, -90), + signed(rng, n, -140, -95), signed(rng, 4096, 60, 120)]) + c = np.concatenate([signed(rng, n, -149, -90), signed(rng, n, -149, -100), signed(rng, n, -100, 70), + signed(rng, n, -149, -90), signed(rng, 4096, -149, -127)]) + k = rng.integers(-8128, 8129, a.size).astype(F32) + cancel = rng.integers(0, a.size, 8192) # c = -a * k + a few units: a subnormal sum + exact = -(a[cancel].astype(np.float64) * k[cancel]) + c[cancel] = (exact + rng.integers(-40, 40, 8192) * 2.0 ** -149).astype(F32) + tie_a = F32(1 + 2.0 ** -23) * np.exp2(rng.integers(-90, 60, 512)).astype(F32) # a * 3: a tie of fp32 + extra = [(tie_a, np.full(512, 3, F32), np.where(rng.random(512) < 0.5, F32(1), F32(-1)) + * np.uint32(rng.integers(1, 1 << 23, 512)).view(F32)), # broken by a subnormal c + (F32([0.0, -0.0, 0.0, 2.0 ** -90, np.inf, np.nan, 2.0 ** -110, 2.0 ** -110, 2.0 ** -110]), + F32([5, 3, 0, 0, 0, 2, 7, 7, 7]), + np.concatenate([np.uint32([3, 0x80000005, 9, 0x80000001]).view(F32), + F32([2.0 ** -140, 1.0, 2.0 ** 70, -(2.0 ** 63), np.inf])]))] + for ea, ek, ec in extra: + a, k, c = np.concatenate([a, ea]), np.concatenate([k, ek]), np.concatenate([c, ec]) + want = emu.fma32(a, k, c) + fma_diff = helper_case("ieee_fma", "r = ieee_fma(a, b, c);", "r = fma(a, b, c);", want, a, k, c) + sub = np.count_nonzero((want != 0) & (np.abs(want) < F32(2.0 ** -126))) + # a / b for b >= 1: the SwiGLU's quotient g / (1 + e) + g = np.concatenate([signed(rng, n, -149, -90), signed(rng, n, -100, 0), signed(rng, 4096, -20, 7), + F32([0.0, -0.0, np.inf, -np.inf, np.nan, 2.0 ** -100, -(2.0 ** -126)])]) + b = np.concatenate([np.exp2(rng.uniform(0, 1.5, n)), np.exp2(rng.uniform(0, 60, n)), + np.exp2(rng.uniform(0, 128, 4096)), F32([2.0, 1.0, np.inf, 3.0, 2.0, np.inf, np.nan])]) + b = b.astype(F32) + b[-13] = np.inf + div_diff = helper_case("ieee_div", "r = ieee_div(a, b);", "r = a / b;", g / b, g, b) + assert sub > 1000, sub + print(f"\nIEEE helpers bit for bit: ieee_div127 {amax.size} ({d127} differ from the plain division), ieee_rcp " + f"{s.size} ({rcp}), ieee_fma {a.size} ({fma_diff}; {sub} subnormal results), ieee_div {g.size} ({div_diff})") + + +def test_warp_sum_ieee(): + """warp_sum_ieee (basalt's warp_sum with IEEE adds) against the 32-lane butterfly of numpy's float32 adds, on lanes + holding subnormal, tiny and cancelling values; the plain butterfly (warp_sum) must differ on them.""" + rng = np.random.default_rng(13) + v = np.concatenate([signed(rng, 32 * 4096, -149, -95), signed(rng, 32 * 2048, -149, -60)]) + pair = rng.integers(0, v.size // 32, 2048) * 32 + v[pair + 1] = -v[pair] + np.uint32(rng.integers(1, 64, 2048)).view(F32) # cancelling neighbours + want = np.repeat(emu.butterfly(v.reshape(-1, 32), np.add), 32) + diff = helper_case("warp_sum_ieee", "r = warp_sum_ieee(a);", "r = warp_sum(a);", want, v) + print(f"\nwarp_sum_ieee: {v.size // 32} sums bit for bit ({diff} lanes differ with the plain butterfly)") + + +# ---- planted subnormals through the kernels, with the plain kernels as the negative control -------------------------- + +def plain_source(): + """The drafter kernels with each IEEE helper replaced by the plain Metal operation (what a port without them would + compute): the negative control the planted tests must catch.""" + body = kernels.template("basalt_s2_experts.metal") + for ieee, plain in (("ieee_fma(", "fma("), ("ieee_mul(", "mul_plain("), ("ieee_div(", "div_plain("), + ("ieee_div127(", "div127_plain("), ("ieee_rcp(", "rcp_plain("), + ("warp_sum_ieee(", "warp_sum(")): + body = body.replace(ieee, plain) + helpers = """ +static inline float mul_plain(float a, float b) { return a * b; } +static inline float div_plain(float a, float b) { return a / b; } +static inline float div127_plain(float a) { return a / 127.0f; } +static inline float rcp_plain(float a) { return 1.0f / a; } +""" + return (kernels.PRELUDE + kernels.template("basalt_fp.metal") + kernels.template("basalt_q8_1.metal") + helpers + + body) + + +def hw_nan_source(): + """The drafter kernels storing the hardware's NaN (0x7fc00000 on this GPU) instead of cuda_nan's 0x7fffffff: the + negative control of the NaN tests.""" + return (kernels.PRELUDE + kernels.template("basalt_fp.metal") + kernels.template("basalt_q8_1.metal") + + kernels.template("basalt_s2_experts.metal").replace("cuda_nan(", "(")) + + +def nan_bits(v): + """The bit patterns of the NaNs among float32 values ``v`` (given as uint32).""" + v = np.asarray(v).view(np.uint32).reshape(-1) + return v[(v & 0x7FFFFFFF) > 0x7F800000] + + +def test_quantizer_planted_negative_control(): + """The planted blocks of test_quantize_q8_0_scaled through the plain kernel: it must get bytes wrong that the IEEE + kernel gets right.""" + x = planted_blocks() + want_b, want_s = emu.q8_0_scaled(x) + blocks, scales = gpu.q8_0_scaled(x, src=plain_source()) + bad = np.count_nonzero(np.any(blocks.reshape(-1, 34) != want_b.reshape(-1, 34), axis=1) + | (scales.view(np.uint32) != want_s.view(np.uint32))) + assert bad > 50, bad + print(f"\nplain quantizer: {bad} of {x.size // 32} planted blocks wrong") + + +def test_planted_tiny_activations(fx): + """moe_grouped_s2 on activation rows whose fp32 scales are subnormal or tiny (the quantizer's s for rows of tiny + activations): products dw * dx, partial sums and butterfly sums below 2^-126, gate and up values whose SwiGLU + quotient and product are subnormal, an intermediate quantized on subnormal scales. Every stage bit for bit against + the emulation and the output and scratch against the per-entry calls; the plain kernels must differ.""" + rng = np.random.default_rng(14) + x, _ = fill_x(rng, 4) + xs = np.concatenate([signed(rng, NC_GU, -149, -100), np.abs(signed(rng, NC_GU, -78, -72)), + np.abs(signed(rng, NC_GU, -140, -60)), np.abs(signed(rng, NC_GU, -126, -110))]).astype(F32) + xs = np.abs(xs) + grp, gstart = [(0, 2 * BLOB), (1, 0), (0, 5 * BLOB)], [0, 4, 7, 10] + etok, edst = [0, 1, 2, 3, 3, 1, 0, 2, 0, 1], list(rng.permutation(10)) + r, plan = check_call("moe_grouped_s2 (planted tiny activation scales)", fx, grp, gstart, 3, etok, edst, 3, 10, 10, + x=x, xs=xs) + sc = kernels.basalt_s2_scratch(10) + gu = r["scratch"][: 4 * 2 * 10 * FF].view(F32) + hs = r["scratch"][sc["hs"]: sc["hs"] + 4 * 10 * NC_D].view(F32) + tiny = lambda v: np.count_nonzero((v != 0) & (np.abs(v) < F32(2.0 ** -126))) + with np.errstate(under="ignore"): + prods = sum(tiny(emu.h2f(blob_parts(fx.blob(grp[g]))[1])[:, np.arange(NC_GU) // 2][None] + * np.stack([xs[t * NC_GU: (t + 1) * NC_GU] for t in etok[gstart[g]: gstart[g + 1]]])[:, None]) + for g in range(3)) + counts = {"gate/up products": prods, "h": tiny(gu[: 10 * FF]), "h scales": tiny(hs)} + assert all(v > 20 for v in counts.values()), counts + p = gpu.s2_experts(fx.bufs, grp, gstart, 3, etok, edst, x, xs, 3, 10, 10, src=plain_source()) + wrong = {"out": np.count_nonzero(p["out"] != r["out"]), + "scratch": np.count_nonzero(p["scratch"][: sc["hq"]].view(np.uint32) + != r["scratch"][: sc["hq"]].view(np.uint32))} + assert wrong["out"] > 100 and wrong["scratch"] > 100, wrong + print(f"\nsubnormals in {counts}; the plain kernels differ in {wrong}") + + +def test_swiglu_planted(): + """basalt_s2_swiglu alone on planted gate and up values, bit for bit against the emulation (the exponential from + the GPU): gates tiny and subnormal (g / 2 subnormal), +-0, in [-91, -86] (the exponential overflows past -88.72 and + the quotient is -0) and up values making a subnormal product, large and non-finite gates; the plain kernel must + differ.""" + from tests.kernels.test_basalt_experts import gpu_expf_neg + rng = np.random.default_rng(15) + cap = 8 + n = cap * FF + g = np.concatenate([signed(rng, n // 4, -149, -90), rng.uniform(-91, -86, n // 4), + rng.standard_normal(n // 4) * 4, signed(rng, n // 4, -126, -60)]).astype(F32) + u = np.concatenate([rng.standard_normal(n // 4), signed(rng, n // 4, -60, -1), rng.standard_normal(n // 4), + signed(rng, n // 4, -90, -40)]).astype(F32) + g[:8] = [0.0, -0.0, np.inf, -np.inf, np.nan, 100.0, -100.0, 2.0 ** -149] + gu = np.concatenate([g, u]) + params = kernels.basalt_s2_params(cap) + + def run(src): + out = gpu.run(gpu.pipeline(src, "basalt_s2_swiglu"), [gu.tobytes()], params, 1, + -(-n // kernels.S2_THREADS), kernels.S2_THREADS) + return np.frombuffer(out[0], F32) + + got, plain, hw = run(kernels.basalt_s2_experts_source()), run(plain_source()), run(hw_nan_source()) + want = emu.s2_swiglu(g, u, gpu_expf_neg(g)) + nan = np.isnan(want) + assert np.array_equal(got[n:].view(np.uint32), u.view(np.uint32)) # the up half is read only + assert np.all((same_bits(got[:n], want) & ~nan) | (np.isnan(got[:n]) & nan)) + # a NaN stored as sm_120's 0x7fffffff (g = -inf makes a fresh one: -inf / inf); the hardware's differs + assert nan_bits(got[:n]).size >= 2 and np.all(nan_bits(got[:n]) == 0x7FFFFFFF), np.unique(nan_bits(got[:n])) + assert np.any(nan_bits(hw[:n]) != 0x7FFFFFFF) + diff = np.count_nonzero(~((same_bits(plain[:n], want) & ~nan) | (np.isnan(plain[:n]) & nan))) + sub = np.count_nonzero((want != 0) & (np.abs(want) < F32(2.0 ** -126))) + assert diff > 100 and sub > 100, (diff, sub) + print(f"\nSwiGLU planted: {n} values bit for bit, {sub} subnormal; the plain kernel differs on {diff}") + + +def test_nan_bit_pattern(fx): + """Every NaN the drafter kernels store is sm_120's canonical 0x7fffffff (s2_experts.md, NaN bit patterns), where + this GPU's fma, add and division give 0x7fc00000. Token 0's activation row holds an infinity: its block's s is + infinite and its codes 0, so each gate/up term fma(dw * inf, 0, acc) is NaN, and the SwiGLU of a NaN gate is NaN. + Token 1's holds a finite 3e38: gate and up values near 1e37 whose SwiGLU products overflow, an intermediate block + with an infinite s, and each down term fma(dw * inf, 0, acc) NaN. The same kernels storing the hardware's NaN must + differ.""" + rng = np.random.default_rng(16) + x = rng.standard_normal((2, H)).astype(F32) + x[0, 5], x[1, 5] = np.inf, F32(3e38) + xq, xs = gpu.q8_0_scaled(x.reshape(-1)) + + def stored(src): + r = gpu.s2_experts(fx.bufs, [(0, 0)], [0, 2], 1, [0, 1], [0, 1], xq, xs, 1, 2, 2, src=src) + gu = r["scratch"][: 4 * 2 * 2 * FF].view(np.uint32) + return {"up 0": gu[2 * FF: 3 * FF], "swiglu 0": gu[:FF], "gate/up": gu, "out 1": r["out"][1], "out": r["out"]} + + got, hw = stored(None), stored(hw_nan_source()) + pats = {k: (nan_bits(v).size, [hex(int(b)) for b in np.unique(nan_bits(v))]) for k, v in got.items()} + assert all(pats[k][0] for k in ("up 0", "swiglu 0", "out 1")), pats + assert all(np.all(nan_bits(v) == 0x7FFFFFFF) for v in got.values()), pats + assert any(np.any(nan_bits(hw[k]) != 0x7FFFFFFF) for k in ("gate/up", "out")) + print(f"\nNaN bit patterns stored: {pats}") diff --git a/tests/runtime/test_basalt_windows.py b/tests/runtime/test_basalt_windows.py new file mode 100644 index 00000000..f4f98024 --- /dev/null +++ b/tests/runtime/test_basalt_windows.py @@ -0,0 +1,113 @@ +"""A .basalt file's tensors read on the GPU through the windows the emitter plans for them (compiler/emit.py +``basalt_windows``): a toy kernel copies each bound tensor, byte by byte from its binding, into an arena buffer, and +every copy equals the file's bytes. The same in the copy test mode (one exact buffer per tensor, so shader validation +bounds each read by its tensor), and with two programs over different entry sets sharing one buffer dict. A window past +the end of its file is refused when it is mapped.""" + +import struct + +import pytest + +from monolith.compiler import emit_program +from monolith.compiler.emit import basalt_windows +from monolith.core import Graph +from monolith.formats.basalt_reader import BasaltFile +from monolith.packs.basalt import BasaltSource +from monolith.packs.packer import ALIGN +from monolith.runtime import BufferSpec, Engine, KernelSpec, OpSpec +from monolith.runtime import _native as nt +from tests.contract.test_basalt_windows import BOUND, PROFILE, plan, value, write + +COPY = """ +#include +using namespace metal; +struct CopyParams { uint n; uint pad0; uint pad1; uint pad2; }; +// one byte per thread: a tensor's size need not be a multiple of anything (Q3_K rows are 110 bytes) +kernel void copy_bytes(device const uchar* src [[buffer(0)]], device uchar* dst [[buffer(1)]], + constant CopyParams& p [[buffer(2)]], uint i [[thread_position_in_grid]]) { + if (i < p.n) dst[i] = src[i]; +} +""" + + +def copy_program(src, names, tag): + """The weights-only program ``emit_program`` gives for ``names``, plus one copy dispatch per tensor from its + binding into ``{tag}.``.""" + g = Graph("step") + for n in names: + value(g, src, n) + prog = emit_program(g, pack=src, profile=PROFILE, t=1, tail=None) + _, bound = basalt_windows(src, g.values.values()) + prog.kernels["copy"] = KernelSpec(COPY, "copy_bytes") + for i, n in enumerate(names): + nbytes = src.entries[n].nbytes + out, prm = f"{tag}.{i}", f"params.{tag}.{i}" + prog.buffers[out] = BufferSpec(nbytes, None, "arena") + prog.buffers[prm] = BufferSpec(16, struct.pack("<4I", nbytes, 0, 0, 0), "params") + prog.ops.append(OpSpec("copy", [(0, *bound[n]), (1, out, 0), (2, prm, 0)], (-(-nbytes // 256), 1, 1), + (256, 1, 1), True, name=f"copy {n}", meta={"writes": [1]})) + return prog, bound + + +def run_and_check(eng, src, names, tag, data): + assert eng.run(1).steps == 1 + for i, n in enumerate(names): + e = src.entries[n] + assert eng.read(f"{tag}.{i}", e.nbytes) == data[e.offset: e.offset + e.nbytes], n + + +@pytest.mark.parametrize("copy", [False, True], ids=["windows", "exact-copies"]) +def test_each_tensor_reads_its_file_bytes(tmp_path, copy): + path = write(tmp_path) + src = BasaltSource(path, copy=copy) + prog, bound = copy_program(src, BOUND, "out") + weights = {n: b for n, b in prog.buffers.items() if b.role == "weights"} + if copy: + assert all(b.file is None and b.nbytes == src.entries[n].nbytes and off == 0 + for n, (name, off) in bound.items() for b in [weights[name]]) + else: + assert len(weights) == 6 and all(b.file == src.path for b in weights.values()) + assert bound["gguf/b.weight"][1] == 4096 # a tensor that does not start its window's page + run_and_check(Engine(prog), src, BOUND, "out", path.read_bytes()) + + +def test_two_programs_share_one_buffer_dict(tmp_path): + """B binds a strict subset of A's entries. The window of e (and q3) has the same range in both, so B takes A's + buffer under the same name; b alone is a shorter range than A's first gguf window, so B maps a window of its own + under another name and never binds A's.""" + path = write(tmp_path) + src, data, dev = BasaltSource(path), path.read_bytes(), nt.Device() + names_a = ["gguf/a.weight", "gguf/b.weight", "gguf/c.weight", "gguf/e.weight", "gguf/q3.weight", "dense/n0.weight"] + names_b = ["gguf/b.weight", "gguf/e.weight"] + prog_a, bound_a = copy_program(src, names_a, "a") + prog_b, bound_b = copy_program(src, names_b, "b") + eng_a = Engine(prog_a, dev) + eng_b = Engine(prog_b, dev, buffers=dict(eng_a.buffers)) + win_a = {n for n, b in prog_a.buffers.items() if b.role == "weights"} + win_b = {n for n, b in prog_b.buffers.items() if b.role == "weights"} + assert win_a & win_b == {bound_a["gguf/e.weight"][0]} == {bound_b["gguf/e.weight"][0]} + (shared,) = win_a & win_b + assert eng_b.buffers[shared] is eng_a.buffers[shared] + assert bound_b["gguf/b.weight"][0] not in eng_a.buffers + assert eng_b.buffers[bound_b["gguf/b.weight"][0]] is not eng_a.buffers[bound_a["gguf/b.weight"][0]] + run_and_check(eng_a, src, names_a, "a", data) + run_and_check(eng_b, src, names_b, "b", data) + run_and_check(eng_a, src, names_a, "a", data) + + +def test_a_window_past_the_end_of_its_file_is_refused(tmp_path): + """A source whose ``path`` is shorter than the file its tables describe plans a window past ``path``'s end. Mapping + it is refused from the file's own size: touching a page past the end would kill the process with SIGBUS. A window + that ends exactly at the end of the file maps.""" + full = write(tmp_path) + mx = BasaltSource(full).entries["mtp/experts"].offset + short = tmp_path / "short.basalt" + short.write_bytes(full.read_bytes()[: mx + ALIGN]) # ends one page into mtp/experts + buffers, _ = plan(BasaltSource(short, BasaltFile(full)), "mtp/experts") + (w,) = buffers.values() + assert (w.file_offset, w.nbytes) == (mx, 3 * ALIGN) + dev = nt.Device() + with pytest.raises(RuntimeError, match=rf"mmap window \[{mx}, {mx + 3 * ALIGN}\) runs past the end of " + rf".*short\.basalt \({mx + ALIGN} bytes\)"): + nt.Buffer.from_file(dev, w.file, w.file_offset, w.nbytes) + assert nt.Buffer.from_file(dev, w.file, mx, ALIGN).read(0, 64) == full.read_bytes()[mx: mx + 64] diff --git a/tests/runtime/test_engine_limits.py b/tests/runtime/test_engine_limits.py new file mode 100644 index 00000000..50a647f2 --- /dev/null +++ b/tests/runtime/test_engine_limits.py @@ -0,0 +1,57 @@ +"""The Engine's pipeline checks: an op whose threadgroup exceeds its pipeline's ``max_threads_per_threadgroup`` is +refused when the program is instantiated, and so is a pipeline whose SIMD-group is not 32 lanes (every kernel's crews +and butterflies assume 32; basalt's warp is a SIMD-group).""" + +import numpy as np +import pytest + +from monolith.core.step_state import StepStateLayout +from monolith.runtime import BufferSpec, Engine, KernelSpec, OpSpec, Program +from monolith.runtime import _native as nt +from monolith.runtime import engine as engine_module + +LAYOUT = StepStateLayout() +CAPPED = """ +#include +using namespace metal; +[[max_total_threads_per_threadgroup(64)]] +kernel void capped(device uint* y [[buffer(0)]], uint i [[thread_position_in_grid]]) { y[i] = i + 1u; } +""" + + +def capped_program(threads): + """One dispatch of ``capped``, a kernel built to take at most 64 threads a threadgroup, with ``threads``.""" + return Program(kernels={"capped": KernelSpec(CAPPED, "capped")}, + buffers={"y": BufferSpec(4 * threads, None, "arena"), + "step_state": BufferSpec(LAYOUT.size, LAYOUT.pack({}), "step_state"), + "ring": BufferSpec(16 * 8, None, "ring")}, + ops=[OpSpec("capped", [(0, "y", 0)], (1, 1, 1), (threads, 1, 1), True, name="capped", + meta={"writes": [0]})], + ring_capacity=16, layout=LAYOUT) + + +def test_refuses_a_threadgroup_past_its_pipelines_limit(): + pso = nt.Pipeline(nt.Library(nt.Device(), CAPPED, {}), "capped") + assert (pso.max_threads_per_threadgroup, pso.thread_execution_width) == (64, 32) + eng = Engine(capped_program(64)) + assert eng.run(1).steps == 1 + assert np.array_equal(np.frombuffer(eng.read("y"), np.uint32), np.arange(1, 65)) + with pytest.raises(ValueError, match="op capped: a threadgroup of 128 threads; its pipeline takes at most 64"): + Engine(capped_program(128)) + + +def test_refuses_a_simd_group_of_other_than_32_lanes(monkeypatch): + """No Apple GPU reports another width, so the check meets a stand-in pipeline that reports 16 lanes.""" + real = engine_module.compile_pipelines + + class Narrow: + thread_execution_width = 16 + + def __init__(self, pso): + self.max_threads_per_threadgroup = pso.max_threads_per_threadgroup + + assert all(p.thread_execution_width == 32 for p in Engine(capped_program(64)).pipelines.values()) + monkeypatch.setattr(engine_module, "compile_pipelines", + lambda *a, **k: {n: Narrow(p) for n, p in real(*a, **k).items()}) + with pytest.raises(ValueError, match="kernel capped: SIMD-groups of 16 lanes; the kernels assume 32"): + Engine(capped_program(64)) diff --git a/third_party/ARM-OPTIMIZED-ROUTINES-LICENSE b/third_party/ARM-OPTIMIZED-ROUTINES-LICENSE new file mode 100644 index 00000000..20a4b771 --- /dev/null +++ b/third_party/ARM-OPTIMIZED-ROUTINES-LICENSE @@ -0,0 +1,249 @@ +MIT OR Apache-2.0 WITH LLVM-exception +===================================== + + +MIT License +----------- + +Copyright (c) 1999-2022, Arm Limited. + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. + + +Apache-2.0 WITH LLVM-exception +------------------------------ + + Apache License + Version 2.0, January 2004 + http://www.apache.org/licenses/ + + TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION + + 1. Definitions. + + "License" shall mean the terms and conditions for use, reproduction, + and distribution as defined by Sections 1 through 9 of this document. + + "Licensor" shall mean the copyright owner or entity authorized by + the copyright owner that is granting the License. + + "Legal Entity" shall mean the union of the acting entity and all + other entities that control, are controlled by, or are under common + control with that entity. For the purposes of this definition, + "control" means (i) the power, direct or indirect, to cause the + direction or management of such entity, whether by contract or + otherwise, or (ii) ownership of fifty percent (50%) or more of the + outstanding shares, or (iii) beneficial ownership of such entity. + + "You" (or "Your") shall mean an individual or Legal Entity + exercising permissions granted by this License. + + "Source" form shall mean the preferred form for making modifications, + including but not limited to software source code, documentation + source, and configuration files. + + "Object" form shall mean any form resulting from mechanical + transformation or translation of a Source form, including but + not limited to compiled object code, generated documentation, + and conversions to other media types. + + "Work" shall mean the work of authorship, whether in Source or + Object form, made available under the License, as indicated by a + copyright notice that is included in or attached to the work + (an example is provided in the Appendix below). + + "Derivative Works" shall mean any work, whether in Source or Object + form, that is based on (or derived from) the Work and for which the + editorial revisions, annotations, elaborations, or other modifications + represent, as a whole, an original work of authorship. For the purposes + of this License, Derivative Works shall not include works that remain + separable from, or merely link (or bind by name) to the interfaces of, + the Work and Derivative Works thereof. + + "Contribution" shall mean any work of authorship, including + the original version of the Work and any modifications or additions + to that Work or Derivative Works thereof, that is intentionally + submitted to Licensor for inclusion in the Work by the copyright owner + or by an individual or Legal Entity authorized to submit on behalf of + the copyright owner. For the purposes of this definition, "submitted" + means any form of electronic, verbal, or written communication sent + to the Licensor or its representatives, including but not limited to + communication on electronic mailing lists, source code control systems, + and issue tracking systems that are managed by, or on behalf of, the + Licensor for the purpose of discussing and improving the Work, but + excluding communication that is conspicuously marked or otherwise + designated in writing by the copyright owner as "Not a Contribution." + + "Contributor" shall mean Licensor and any individual or Legal Entity + on behalf of whom a Contribution has been received by Licensor and + subsequently incorporated within the Work. + + 2. Grant of Copyright License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + copyright license to reproduce, prepare Derivative Works of, + publicly display, publicly perform, sublicense, and distribute the + Work and such Derivative Works in Source or Object form. + + 3. Grant of Patent License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + (except as stated in this section) patent license to make, have made, + use, offer to sell, sell, import, and otherwise transfer the Work, + where such license applies only to those patent claims licensable + by such Contributor that are necessarily infringed by their + Contribution(s) alone or by combination of their Contribution(s) + with the Work to which such Contribution(s) was submitted. If You + institute patent litigation against any entity (including a + cross-claim or counterclaim in a lawsuit) alleging that the Work + or a Contribution incorporated within the Work constitutes direct + or contributory patent infringement, then any patent licenses + granted to You under this License for that Work shall terminate + as of the date such litigation is filed. + + 4. Redistribution. You may reproduce and distribute copies of the + Work or Derivative Works thereof in any medium, with or without + modifications, and in Source or Object form, provided that You + meet the following conditions: + + (a) You must give any other recipients of the Work or + Derivative Works a copy of this License; and + + (b) You must cause any modified files to carry prominent notices + stating that You changed the files; and + + (c) You must retain, in the Source form of any Derivative Works + that You distribute, all copyright, patent, trademark, and + attribution notices from the Source form of the Work, + excluding those notices that do not pertain to any part of + the Derivative Works; and + + (d) If the Work includes a "NOTICE" text file as part of its + distribution, then any Derivative Works that You distribute must + include a readable copy of the attribution notices contained + within such NOTICE file, excluding those notices that do not + pertain to any part of the Derivative Works, in at least one + of the following places: within a NOTICE text file distributed + as part of the Derivative Works; within the Source form or + documentation, if provided along with the Derivative Works; or, + within a display generated by the Derivative Works, if and + wherever such third-party notices normally appear. The contents + of the NOTICE file are for informational purposes only and + do not modify the License. You may add Your own attribution + notices within Derivative Works that You distribute, alongside + or as an addendum to the NOTICE text from the Work, provided + that such additional attribution notices cannot be construed + as modifying the License. + + You may add Your own copyright statement to Your modifications and + may provide additional or different license terms and conditions + for use, reproduction, or distribution of Your modifications, or + for any such Derivative Works as a whole, provided Your use, + reproduction, and distribution of the Work otherwise complies with + the conditions stated in this License. + + 5. Submission of Contributions. Unless You explicitly state otherwise, + any Contribution intentionally submitted for inclusion in the Work + by You to the Licensor shall be under the terms and conditions of + this License, without any additional terms or conditions. + Notwithstanding the above, nothing herein shall supersede or modify + the terms of any separate license agreement you may have executed + with Licensor regarding such Contributions. + + 6. Trademarks. This License does not grant permission to use the trade + names, trademarks, service marks, or product names of the Licensor, + except as required for reasonable and customary use in describing the + origin of the Work and reproducing the content of the NOTICE file. + + 7. Disclaimer of Warranty. Unless required by applicable law or + agreed to in writing, Licensor provides the Work (and each + Contributor provides its Contributions) on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or + implied, including, without limitation, any warranties or conditions + of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A + PARTICULAR PURPOSE. You are solely responsible for determining the + appropriateness of using or redistributing the Work and assume any + risks associated with Your exercise of permissions under this License. + + 8. Limitation of Liability. In no event and under no legal theory, + whether in tort (including negligence), contract, or otherwise, + unless required by applicable law (such as deliberate and grossly + negligent acts) or agreed to in writing, shall any Contributor be + liable to You for damages, including any direct, indirect, special, + incidental, or consequential damages of any character arising as a + result of this License or out of the use or inability to use the + Work (including but not limited to damages for loss of goodwill, + work stoppage, computer failure or malfunction, or any and all + other commercial damages or losses), even if such Contributor + has been advised of the possibility of such damages. + + 9. Accepting Warranty or Additional Liability. While redistributing + the Work or Derivative Works thereof, You may choose to offer, + and charge a fee for, acceptance of support, warranty, indemnity, + or other liability obligations and/or rights consistent with this + License. However, in accepting such obligations, You may act only + on Your own behalf and on Your sole responsibility, not on behalf + of any other Contributor, and only if You agree to indemnify, + defend, and hold each Contributor harmless for any liability + incurred by, or claims asserted against, such Contributor by reason + of your accepting any such warranty or additional liability. + + END OF TERMS AND CONDITIONS + + APPENDIX: How to apply the Apache License to your work. + + To apply the Apache License to your work, attach the following + boilerplate notice, with the fields enclosed by brackets "[]" + replaced with your own identifying information. (Don't include + the brackets!) The text should be enclosed in the appropriate + comment syntax for the file format. We also recommend that a + file or class name and description of purpose be included on the + same "printed page" as the copyright notice for easier + identification within third-party archives. + + Copyright [yyyy] [name of copyright owner] + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. + + +--- LLVM Exceptions to the Apache 2.0 License ---- + +As an exception, if, as a result of your compiling your source code, portions +of this Software are embedded into an Object form of such source code, you +may redistribute such embedded portions in such Object form without complying +with the conditions of Sections 4(a), 4(b) and 4(d) of the License. + +In addition, if you combine or link compiled forms of this Software with +software that is licensed under the GPLv2 ("Combined Software") and if a +court of competent jurisdiction determines that the patent provision (Section +3), the indemnity provision (Section 9) or other Section of the License +conflicts with the conditions of the GPLv2, you may retroactively and +prospectively choose to deem waived or otherwise exclude such Section(s) of +the License, but only in their entirety and only with respect to the Combined +Software. diff --git a/third_party/BASALT-LICENSE b/third_party/BASALT-LICENSE new file mode 100644 index 00000000..2edc883b --- /dev/null +++ b/third_party/BASALT-LICENSE @@ -0,0 +1,21 @@ +MIT License + +Copyright (c) 2026 Jesús Gulfo + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. diff --git a/third_party/GGML-LICENSE b/third_party/GGML-LICENSE new file mode 100644 index 00000000..e7dca554 --- /dev/null +++ b/third_party/GGML-LICENSE @@ -0,0 +1,21 @@ +MIT License + +Copyright (c) 2023-2026 The ggml authors + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. diff --git a/third_party/NOTICE b/third_party/NOTICE index a5f46f82..74b93cf8 100644 --- a/third_party/NOTICE +++ b/third_party/NOTICE @@ -72,6 +72,208 @@ Format: `` — adapted from / copied from `` `` @ output rows, extended for packed BF16 weights, fused normalization and epilogues. License: `third_party/MLX-LICENSE`. +## ggml / llama.cpp (ggml-org/llama.cpp @ `3cf03257f219afbe7334045ff7c6a06ac68c627d`, MIT) + +- `monolith/formats/gguf.py` — adapted from `ggml/src/ggml-common.h` and `ggml/src/ggml-quants.c` (MIT): the + `block_*` structs of Q2_0, Q4_0, Q5_0, Q8_0, Q3_K, Q4_K, Q5_K, Q6_K, IQ4_NL and IQ4_XS as numpy structured dtypes and + their `dequantize_row_*` / `get_scale_min_k4` rules re-implemented in numpy; the `kvalues_iq4nl` table copied; the + type ids of `ggml/include/ggml.h` (F32 and F16 included). License: `third_party/GGML-LICENSE`. +- `tests/contract/gguf_reference.py` — adapted from `gguf-py/gguf/quants.py` (MIT): the `dequantize_blocks` of BF16, + Q4_0, Q5_0, Q8_0, Q3_K, Q4_K (with `get_scale_min`), Q5_K, Q6_K, IQ4_NL and IQ4_XS, copied unchanged, and the block + sizes of `gguf-py/gguf/constants.py` `GGML_QUANT_SIZES`; its Q2_0 decode is a scalar port of + `ggml/src/ggml-quants.c` `dequantize_row_q2_0`. License: `third_party/GGML-LICENSE`; gguf-py's own `LICENSE` is the + same MIT text under "Copyright (c) 2023 Georgi Gerganov", which the file's header carries. +- `kernels/common/basalt_fp.metal` — through basalt's `src/kernels/cuda/native_mmvq.cu` (below), which adapts + `ggml/src/ggml-cuda/{quantize.cu,vecdotq.cuh,mmvq.cu,common.cuh}` and `ggml/src/ggml-common.h` (MIT): the warp sum + and max butterflies, the two-16-bit-load word read, the `__dp4a`, `__byte_perm`, `__vsubss4` and `__vsub4` + semantics and the IQ4 table lookup. License: `third_party/GGML-LICENSE`. +- `kernels/common/basalt_q8_1.metal` — through basalt's `native_mmvq.cu` and `iq_kernels.cu` (below), which adapt + `ggml/src/ggml-cuda/quantize.cu` (MIT): the q8_1 block and its quantization rule. License: `third_party/GGML-LICENSE`. +- `kernels/common/basalt_mmvq.metal` — through basalt's `src/kernels/cuda/native_mmvq.cu` (below), which adapts + `ggml/src/ggml-cuda/{vecdotq.cuh,mmvq.cu,common.cuh}` and `ggml/src/ggml-common.h` (MIT): the block structs, the + `vec_dot_*_q8_1` integer dot products and their scale arithmetic, and mmvq's thread-to-block mapping and cross-warp + reduction. License: `third_party/GGML-LICENSE`. +- `kernels/common/basalt_dequant.metal` — through basalt's `src/kernels/cuda/iq_kernels.cu` (below), which transcribes + `ggml/src/ggml-cuda/dequantize.cuh` and `convert.cu` and `ggml/src/ggml-common.h`'s `kvalues_iq4nl` (MIT): the + Q3_K, IQ4_NL and IQ4_XS dequantization rules and the IQ4 codebook. License: `third_party/GGML-LICENSE`. +- `kernels/common/basalt_experts.metal` — through basalt's `src/kernels/cuda/iq_kernels.cu` and `gu2.cuh` (below), + which transcribe `ggml/src/ggml-cuda/vecdotq.cuh`'s `vec_dot_q2_0_q8_1` and `ggml/src/ggml-cuda/quantize.cu` + (MIT): the Q2_0 times q8_1 dot product and the q8_1 rule. License: `third_party/GGML-LICENSE`. +- `kernels/common/basalt_dense_tc.metal` — through basalt's `src/kernels/cuda/dense_tc.cu` (below), which reads + `ggml/src/ggml-common.h`'s blocks (MIT): the Q2_0, Q3_K, Q4_K, Q5_K, Q6_K and IQ4_XS block layouts, their scale + unpacking and the IQ4 codebook. License: `third_party/GGML-LICENSE`. +- `kernels/common/basalt_mmvf.metal` — through basalt's `src/kernels/cuda/native_bf16.cu` (below), which adapts + `ggml/src/ggml-cuda/{mmvf.cu,common.cuh}` (MIT): the BF16 times fp32 MMVF kernel's pair accumulation and its warp + and block reductions; `monolith/kernels.py`'s `basalt_mmvf_block` transcribes its block-size rule. License: + `third_party/GGML-LICENSE`. +- `kernels/common/basalt_q5k_head.metal` — through basalt's `src/kernels/cuda/q5k_head.cu` (below), whose Q5_K dot + repeats `native_mmvq.cu`'s, an adaptation of `ggml/src/ggml-cuda/vecdotq.cuh` and `ggml/src/ggml-common.h` (MIT): the + Q5_K block layout, its scale unpacking and the `vec_dot_q5_K_q8_1` integer dot. License: `third_party/GGML-LICENSE`. +- `tests/kernels/basalt_emu.py` — through basalt (below): the `kvalues_iq4nl` table of `ggml/src/ggml-common.h`, + copied, `get_scale_min_k4` of `ggml/src/ggml-quants.c`, the q8_1 rule of `ggml/src/ggml-cuda/quantize.cu` and the + MMVF accumulation and reductions of `ggml/src/ggml-cuda/mmvf.cu`, re-implemented in numpy (MIT). License: + `third_party/GGML-LICENSE`. +- `runtime/src/basalt_cpu.h`, `runtime/src/basalt_cpu.cpp` and `tests/kernels/basalt_cpu_emu.py` — through basalt's + `src/kernels/cpu/expert.cpp` (below), which reads `ggml/src/ggml-common.h`'s `block_q2_0` and + `ggml/src/ggml-quants.c`'s `dequantize_row_q2_0` (MIT): the 18-byte block layout (an fp16 scale, then 64 codes two + bits each) and its code extraction `(qs[m / 4] >> 2 * (m % 4)) & 3`, re-implemented. The `- 1` that centres a code + reaches the result through basalt's own correction term, not through a dequantization. License: `third_party/GGML-LICENSE`. + +## Arm optimized-routines (ARM-software/optimized-routines, MIT OR Apache-2.0 WITH LLVM-exception; taken under MIT) + +- `runtime/src/basalt_cpu_expf.cpp` — adapted from `math/expf.c`, `math/exp2f_data.c`, `math/math_errf.c` and + `math/math_config.h` @ `f67e7daa5457646fad9f75580263dba654c988aa`: `expf`'s algorithm operation for operation, + the `exp2f_data` table, polynomial and constants for `EXP2F_TABLE_BITS = 5` copied, `xflowf`'s error returns and + the `asuint` / `asdouble` / `opt_barrier_float` helpers. glibc's generic `expf` is this same source + (`sysdeps/ieee754/flt-32/e_expf.c` since 2017), which is why basalt's CPU SwiGLU reaches it; the transcription + takes the MIT copy rather than glibc's LGPL one, and selects the build glibc makes (the `!TOINT_INTRINSICS` + branch, `WANT_ERRNO_UFLOW`). License: `third_party/ARM-OPTIMIZED-ROUTINES-LICENSE`. + +## basalt (jesdga95/basalt @ `b4c63b55754637f4c72ad53a0f791d425f71eb36`, MIT) + +- `monolith/formats/basalt_reader.py` — adapted from `tools/model_file.py` (MIT): the layout constants and the + `FileHeader` / `SectionEntry` structs of `include/basalt/core/model_format.hpp`; the parsers are written against the + checks of `src/core/model_file.cpp`, `src/core/weights.cpp`, `src/kernels/cpu/expert_layout.cpp` and + `src/core/mtp.cpp`. The test writer in `tests/contract/test_basalt_reader.py` follows `tools/model_file.py`'s + `ModelWriter`. `tests/contract/test_gguf_formats.py` compiles basalt's references only from a checkout the user points + `BASALT_SRC` at. License: `third_party/BASALT-LICENSE`. +- `kernels/common/basalt_fp.metal` — adapted from `src/kernels/cuda/native_mmvq.cu`, `src/kernels/cuda/iq_kernels.cu`, + `include/basalt/kernels/dp4a.hpp` and `include/basalt/kernels/q8_1_finite.hpp` (MIT): `warp_sum`, `warp_max`, + `load_int_b2`, the `DP4A` helper and the IQ4 table lookup (`native_mmvq.cu:441-457`), with the flush-to-zero and reciprocal helpers that write out the arithmetic nvcc + compiles for them (`docs/research/basalt-nvcc/matvec.md`); from `iq_kernels.cu`, `Split<42>`'s Q2_0 decode, the + IEEE-built `warp_sum` and the SwiGLU's `__expf(-g)` (`expf_neg`), in the arithmetic nvcc compiles for them + (`docs/research/basalt-nvcc/experts.md`); from `native_mmvq.cu:180-240` and `:897-937`, the Q5_K decode and dot + (`q5k_load`, `q5k_dot`) that `native_mmvq` and `src/kernels/cuda/q5k_head.cu` share, and from `q5k_head.cu`, a + fast-math file's `__expf` (`expf_ftz`; `docs/research/basalt-nvcc/q5k_head.md`). License: + `third_party/BASALT-LICENSE`. +- `kernels/common/basalt_q8_1.metal` — adapted from `src/kernels/cuda/native_mmvq.cu:146-177` (the native and SwiGLU + quantizers), `src/kernels/cuda/iq_kernels.cu:1880-1900` (the IEEE quantizer) and `include/basalt/kernels/q8_1_finite.hpp` + (MIT), written in the rounding sequence nvcc compiles for them. License: `third_party/BASALT-LICENSE`. +- `kernels/common/basalt_mmvq.metal` — adapted from `src/kernels/cuda/native_mmvq.cu:179-1172` (MIT): the + one-column `native_*_mmvq_kernel`s and `native_mmvq_multi_kernel` with the format traits' `load` / `apply` split, + for Q2_0, Q3_K, Q4_K, Q5_K, Q6_K, IQ4_XS, IQ4_NL, Q4_0, Q5_0 and Q8_0, in the exact and the upstream layouts, written + in the rounding sequence nvcc compiles for them (`docs/research/basalt-nvcc/matvec.md`). License: + `third_party/BASALT-LICENSE`. +- `kernels/common/basalt_dequant.metal` — adapted from `src/kernels/cuda/iq_kernels.cu:2012-2069` and `:2216-2220` + (MIT): `dq_iq4_nl`, `dq_q3_k`, `dq_iq4_xs` and `dq_q2_0` under `dequant_flat_kernel`, in the arithmetic nvcc + compiles for them (`docs/research/basalt-nvcc/dequant.md`). License: `third_party/BASALT-LICENSE`. +- `kernels/common/basalt_experts.metal` — adapted from `src/kernels/cuda/iq_kernels.cu:864-1014`, `:1087-1171`, + `:1648-1921` and `src/kernels/cuda/gu2.cuh:223-390` (MIT): `native_expert_grouped`'s Q2_0 kernels + (`native_gu2_kernel`, `native_gu_multi_kernel`, `swiglu_q8_1_entries_pdl_kernel`, `native_down_multi_kernel` with + `row_dot_multi` and `row_dot_20_sub16`), written in the rounding sequence nvcc compiles for them + (`docs/research/basalt-nvcc/experts.md`). License: `third_party/BASALT-LICENSE`. +- `kernels/common/basalt_s2_experts.metal` — adapted from `src/kernels/cuda/s2_expert_grouped.cu:34-46`, `:104-108`, + `:165-171`, `:215-279` and `:736-1083` and `src/kernels/cuda/quantize_act.cu:74-101` (MIT): the drafter's Q2_0 + experts (`group_resident_kernel`, `gu_grouped_t_kernel`, `swiglu_kernel`, `down_grouped_t_kernel` with + `load_x_chunk`, `stage_chunk`, `expand_codes` and `chunk_s`) and `quantize_q8_0_scaled_warp_kernel`, written in the + rounding sequence nvcc compiles for them (`docs/research/basalt-nvcc/s2_experts.md`). License: + `third_party/BASALT-LICENSE`. +- `kernels/common/basalt_q5k_head.metal` — adapted from `src/kernels/cuda/q5k_head.cu:19-496` and + `src/kernels/cuda/head_proxy.cuh:17-240` (MIT): `q5k_head_kernel` with `q5k_row_dev`, `q5k_head_top1_kernel` with + `Top` (its last-block merge as a second kernel), `mask_unmapped_kernel`, `q5k_proxy_pack_kernel` with `level`, + `fit_group` and `pack_group`, `px::score_kernel`, and `q5k_proxy_final_kernel` with `collect` and `pick`, written in + the rounding sequence nvcc compiles for them (`docs/research/basalt-nvcc/q5k_head.md`). License: + `third_party/BASALT-LICENSE`. +- `kernels/common/basalt_dense_tc.metal` — adapted from `src/kernels/cuda/dense_tc.cu:32-931` (MIT): `half_sb_terms` + for Q2_0, Q3_K, Q4_K, Q5_K, Q6_K and IQ4_XS with the `mma.sync` fragment layout, and the warps' chunks and warp-sum + trees of `dense_tc_one_kernel`, `dense_tc_tile_kernel`, `dense_tc_kernel` (KS 1 and 2) and `dense_tc_pair_kernel`, + written in the rounding sequence nvcc compiles for them (`docs/research/basalt-nvcc/dense_tc.md`). License: + `third_party/BASALT-LICENSE`. +- `kernels/common/basalt_mmvf.metal` — adapted from `src/kernels/cuda/native_bf16.cu:37-135` (MIT): + `bf16_f32_mmvf_kernel` and `bf16_f32_mmvf_multi_kernel` with `mmvf_warp_sum`, written in the rounding sequence nvcc + compiles for them (`docs/research/basalt-nvcc/bf16.md`); `monolith/kernels.py`'s `basalt_mmvf_block`, + `basalt_mmvf_macros` and `basalt_mmvf_cols` transcribe `mmvf_block_size` and the launchers' routing and checks + (`native_bf16.cu:124-203`). License: `third_party/BASALT-LICENSE`. +- `monolith/kernels.py` — adapted from `src/kernels/cuda/dense_tc.cu:35-42`, `:52-54`, `:698-702` and `:1017-1105` + (MIT): `Fmt::SB` (`DENSE_TC_SB`), and in `basalt_dense_tc_variant` the variant rule of `launch` with + `one_ok`, `one_row_stride` and `one_smem_bytes`; `dense_tc_supported` (`_dense_tc_check`) and + `dense_tc_pair_supported`'s shared-memory test (`basalt_dense_tc_pair_macros`); from + `src/kernels/cuda/s2_expert_grouped.cu:34-46`, `:554-562` and `:1085-1122` and + `src/kernels/cuda/quantize_act.cu:219-238`, the drafter experts' blob size, scratch layout (`basalt_s2_scratch`), + launch grids and checks. License: `third_party/BASALT-LICENSE`. +- `monolith/kernels.py` — adapted from `src/kernels/cuda/q5k_head.cu:337-386` and `:500-535` and + `src/kernels/cuda/head_proxy.cuh:17-28` (MIT): `q5k_head_supported` (`basalt_q5k_head_macros`), the head's and the + top-1's grid rule (`basalt_q5k_head_grid`), and the proxy's `tiles`, `bytes` and `scratch_bytes` + (`basalt_q5k_proxy_tiles`, `basalt_q5k_proxy_bytes`, `basalt_q5k_proxy_scratch_bytes`). License: + `third_party/BASALT-LICENSE`. +- `monolith/compiler/emit_basalt.py` — adapted from `src/kernels/cuda/native_mmvq.cu:1465-1475`, `:1490-1494`, + `:1549-1552` and `:1563-1568`, `src/kernels/cuda/dense_tc.cu:1077-1082` and `:1107-1113`, + `src/kernels/cuda/native_bf16.cu:139-171` and `src/kernels/cuda/iq_kernels.cu:2450-2455` (MIT): the launchers' + checks its handlers make at emit time (`validate_shape`'s whole 32-value blocks and 1 to 8 columns, + `validate_pointer`'s 4-byte alignment, `dense_tc`'s and `dense_tc_pair`'s pointer checks, the BF16 GEMVs' pointer + checks and their `ldy >= n_out` routing, the IEEE quantizer's unchecked column count); `monolith/kernels.py`'s + `basalt_q8_1_grid` and `basalt_mmvf_grid` transcribe the quantizers' and the BF16 GEMVs' grids + (`native_mmvq.cu:1556-1558`, `iq_kernels.cu:2453`, `native_bf16.cu:147-150`, `:174`). License: + `third_party/BASALT-LICENSE`. +- `tests/kernels/test_basalt_q5k_head.py` — adapted from `src/kernels/q5k_head_parity.cpp` (MIT): its weights and + activations, row counts, maps, rescaling, planted rows and trials, and the pass criteria. License: + `third_party/BASALT-LICENSE`. +- `tests/kernels/test_basalt_dense_tc.py` — adapted from `src/kernels/dense_tc_parity.cpp` (MIT): its cases and pairs + with their scale offsets and seeds, the T = 1..8 sweep, the 0xff output pre-fill and the pass criteria. License: + `third_party/BASALT-LICENSE`. +- `tests/kernels/test_basalt_mmvf.py` — adapted from `src/kernels/route_window_parity.cpp` (its projection half: the + shapes, widths, data distributions and criterion) and `src/kernels/ple_parity.cpp` (the native PLE value check: its + witness, float64 reference, `rel_l1`, `le`, `gt` and criterion) (MIT). License: `third_party/BASALT-LICENSE`. +- `tests/kernels/test_basalt_experts.py` — adapted from `src/kernels/iq_multi_parity.cpp` (`check_grouped`, + `check_mmvq`'s reference), `src/kernels/native_grouped_parity.cpp` and `src/kernels/native_expert_parity.cpp` (MIT): + their fixtures, plans, pre-fills and pass criteria. License: `third_party/BASALT-LICENSE`. +- `tests/kernels/test_basalt_s2_experts.py` — adapted from `src/kernels/s2_expert_grouped_parity.cpp` (its fixtures, + plans, sentinels, float64 reference and pass criteria) and `src/kernels/quantize_act_parity.cpp` (its five + distributions, the fp16 vectors and their criteria) (MIT). License: `third_party/BASALT-LICENSE`. +- `tests/kernels/test_basalt_iq_parity.py` — adapted from `tools/iq_fixture.py` and `tools/gguf_writer.py`'s + `quantize_q2_0` (MIT): `iq_parity`'s fixtures, byte for byte, and its pass criterion + (`src/kernels/iq_parity.cpp`). License: `third_party/BASALT-LICENSE`. +- `tests/kernels/test_basalt_mmvq.py` — adapted from `src/kernels/mmvq_multi_parity.cpp` (MIT): its cases with their + scale offsets, `sane_half`, the widths, seeds and Q8_0 geometries, `compare_q80`'s float64 reference and output + pre-fills, and the pass criteria. License: `third_party/BASALT-LICENSE`. +- `tests/kernels/test_basalt_q8_1.py` — adapted from `src/kernels/iq_multi_parity.cpp`'s `check_q8_1_finite` (MIT): the + planted blocks, the host transcription of the quantization formula and the pass criterion. License: + `third_party/BASALT-LICENSE`. +- `runtime/src/basalt_pool.h`, `runtime/src/basalt_pool.cpp` and `tests/kernels/test_basalt_pool.py` — adapted + from `include/basalt/kernels/cpu/pool.hpp` and `src/kernels/cpu/pool.cpp` (MIT): the CPU expert pool's + structure, its epoch-tagged claim protocol, its park and its phase barriers, with the memory orders as written. + License: `third_party/BASALT-LICENSE`. +- `runtime/src/basalt_cpu_expf.cpp`, `tests/kernels/test_basalt_cpu_expf.py` — adapted from + `src/kernels/cpu/pool.cpp:434` (MIT): the CPU expert pool's SwiGLU, `(g / (1.f + std::exp(-g))) * u`, in its + order of operations, which is the only arithmetic the pool itself performs. License: + `third_party/BASALT-LICENSE`. +- `tests/kernels/fixtures/swiglu_vectors.txt` — the recorded output of `src/kernels/cpu/pool.cpp:425-434` (MIT), + built as basalt builds it and run on x86-64: measured values, not source. License: + `third_party/BASALT-LICENSE`. +- `tests/kernels/test_basalt_platform.py` — the contraction check's pass criterion of + `src/kernels/elementwise_parity.cpp` (MIT). License: `third_party/BASALT-LICENSE`. +- `tests/kernels/basalt_emu.py` — adapted from `src/kernels/cuda/native_mmvq.cu`, `src/kernels/cuda/iq_kernels.cu`, + `src/kernels/cuda/native_bf16.cu`, `src/kernels/cuda/dense_tc.cu` and `include/basalt/kernels/q8_1_finite.hpp` + (MIT): the iteration traits, and in numpy the quantizers' and the `native_mmvq` kernels' arithmetic as nvcc + compiles it (`docs/research/basalt-nvcc/matvec.md`), the routed experts' (`q2_0_dots`: `iq_kernels.cu`'s + `row_dot_multi`; `swiglu_q8_1`: the SwiGLU and its IEEE quantizer; `docs/research/basalt-nvcc/experts.md`), the + BF16 GEMVs' (`mmvf`; `bf16_bits`: `include/basalt/kernels/bf16_bits.hpp`'s rounding; + `docs/research/basalt-nvcc/bf16.md`), `dense_tc`'s (`docs/research/basalt-nvcc/dense_tc.md`), the Q5_K head's + top-1 and 2-bit proxy (`src/kernels/cuda/q5k_head.cu`, `src/kernels/cuda/head_proxy.cuh`; + `docs/research/basalt-nvcc/q5k_head.md`) and the drafter experts' (`f16_from_f32`: + `include/basalt/kernels/f16_bits.hpp:36-65` transcribed; `q8_0_scaled`, `s2_dots`, `s2_swiglu`: + `src/kernels/cuda/quantize_act.cu` and `src/kernels/cuda/s2_expert_grouped.cu`; + `docs/research/basalt-nvcc/s2_experts.md`). License: `third_party/BASALT-LICENSE`. +- `runtime/src/basalt_cpu.h` and `runtime/src/basalt_cpu.cpp` — adapted from `src/kernels/cpu/expert.cpp:143-148`, + `:336-370` and `:503-556` and `include/basalt/kernels/cpu/expert.hpp:25-61` (MIT): the `ActQ` struct and the + geometry constants, `act_quant_q8_1`, and `q2_0_gguf_rows_multi` with `q2g_rows`, `q2g_row_multi` and + `unpack64_q2_0`, transcribed to ARM NEON operation for operation, with the lane-reduction trees of the AVX-512 + intrinsics' own headers. License: `third_party/BASALT-LICENSE`. +- `tests/kernels/basalt_cpu_emu.py` and `tests/kernels/test_basalt_cpu_q2.py` — adapted from + `src/kernels/cpu/expert.cpp:143-148`, `:336-370` and `:503-556` (MIT): the same two kernels re-implemented in numpy + as the AVX-512 semantics they are written in, and the shape of the per-token independence check of + `src/kernels/cpu/expert_multi_test.cpp:56-72`, which exercises a kernel off this pack's path: the pattern + transfers, not its code. License: `third_party/BASALT-LICENSE`. + +## Test data + +- `tests/contract/fixtures/basalt_pack.safetensors` — byte ranges (49 KB: the header and section table, three index + sections and a few weight rows) of `Qwen3.8-FN-GSQ-RCO-Q2_0.basalt` in `jesdga/Qwen3.8-Flash-Next-Basalt` @ + `2a6a758dc12f1d027d2d35b8964110df7e80f70b`, range-read by `tests/contract/fixtures/make_basalt_fixture.py`. The + pack's `meta` section names the weights' licence: Qwen Community License 1.0, copyright 2026 Qwen, quantized by ISTA + DASLab (the source GGUF's `general.license` field reads `apache-2.0`). License: `third_party/QWEN-COMMUNITY-LICENSE` + (basalt's `tools/convert/qwen-community-license-1.0.txt`, identical to the text in `meta`). + ## Original - `probes/` — original to this repository. diff --git a/third_party/QWEN-COMMUNITY-LICENSE b/third_party/QWEN-COMMUNITY-LICENSE new file mode 100644 index 00000000..9557a896 --- /dev/null +++ b/third_party/QWEN-COMMUNITY-LICENSE @@ -0,0 +1,16 @@ +Qwen Community License 1.0 + +Copyright (c) 2026 Qwen + +Permission is hereby granted, free of charge, to any person obtaining a copy of this software, including the model weights, parameters, configuration files, inference code and associated documentation files (collectively, the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, sell, deploy, host, fine-tune, and create derivative works from (collectively, "Use" or "Using") copies of the Software; and to permit persons to whom the Software is furnished to do so, subject to the following conditions: + +1. The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. If the Software (or any derivative works thereof) is Used for any of the licensee's commercial products or services that have more than 100,000,000 monthly active users or US$ 20,000,000 (or equivalent in other currencies) monthly revenue, respective model name must be prominently displayed on the user interface of such product or service; and, + +2. If the licensee or any of its affiliates conducts a Model as a Service or AI Work Assistant business, the licensee shall obtain a separate license from Qwen before Using the Software or its derivative works for any commercial purpose. The foregoing requirement shall not apply to the licensee's internal Use of the Software, provided that such Use does not make the Software, its outputs, or its underlying model capabilities available to any third party. + +"Model as a Service" means giving a third party access to language model inference or fine-tuning (e.g., via API or a hosted endpoint) in a manner that allows such third parties to exercise meaningful control over the inputs, parameters, or training data. This does not include the mere relaying of requests to models hosted by other third parties. +“AI Work Assistant” means an independent AI-powered product primarily designed for AI-assisted coding or office productivity (e.g., Qoder and QwenWork). It does not include: (a) a single-purpose AI tool (such as an AI translation tool); (b) an AI assistant primarily designed for a domain other than coding or office productivity (such as Taobao AI Shopping Assistant or AMap AI Chat); or (c) an AI assistant that is a feature of a product whose primary purpose is not AI-assisted coding or office productivity. + +THE SOFTWARE AND ANY OUTPUT AND RESULTS THEREFROM ARE PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL QWEN, ITS AFFILIATES OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. THE USE OF THE SOFTWARE MUST COMPLY WITH APPLICABLE LAWS AND REGULATIONS, AND MUST NOT INFRINGE THE INTELLECTUAL PROPERTY RIGHTS OF ANY THIRD PARTY. + +For any questions regarding this license, please contact model-business@notice.qwencloud.com. \ No newline at end of file diff --git a/tools/tsan/README.md b/tools/tsan/README.md new file mode 100644 index 00000000..e2247854 --- /dev/null +++ b/tools/tsan/README.md @@ -0,0 +1,30 @@ +# ThreadSanitizer drivers + +The CPU expert pool's correctness is synchronisation, not arithmetic, and a wrong synchronisation does not give +different numbers: it gives a run that hangs or computes a job twice. The Python suite +(`tests/kernels/test_basalt_pool.py`) asserts the pool's properties, but it cannot schedule itself into the +windows those properties protect. ThreadSanitizer can see the happens-before edges directly. + +```bash +clang++ -std=gnu++20 -O1 -g -fsanitize=thread -I runtime/src \ + tools/tsan/pool_tsan.cpp runtime/src/basalt_pool.cpp -o /tmp/pool_tsan && /tmp/pool_tsan +``` + +A clean run prints two `ok: ...` lines and nothing else. Run it after any change to +`runtime/src/basalt_pool.cpp`. + +The driver has two parts. The first drives one pool from one thread for 300 phases, republishing a fresh body each +phase, so a port that published the batch description after the epoch or read it before the acquire races there. +The second drives one pool from **two** threads, which the Python bindings and the pump thread both make reachable: +the bindings release the GIL and the host task runs on the pump. It reports how many phases were refused rather +than asserting a count, since whether the two overlap at all is the scheduler's business; the refusal itself is +asserted deterministically by `tests/kernels/test_basalt_pool.py` case C4. + +**What it caught.** The first draft of the pool read the batch description at the top of `drain`, before the claim +whose acquire is the only thing ordering it against the host's write. Every property test passed; ThreadSanitizer +named the file and line of both sides. + +**What it does not catch.** Weakening `publish`'s epoch bump, `begin_batch`'s head store or `drain`'s done +increment from their written orders to `relaxed` produces no warning here and no wrong result, over 300 phases of +16 jobs [M]. Those orders are transcribed from basalt with their arguments recorded in +`docs/research/basalt-cpu-pool.md` section 1.5, and nothing in this tree measures them. diff --git a/tools/tsan/pool_tsan.cpp b/tools/tsan/pool_tsan.cpp new file mode 100644 index 00000000..ebcf5cd2 --- /dev/null +++ b/tools/tsan/pool_tsan.cpp @@ -0,0 +1,61 @@ +// A ThreadSanitizer driver for the pool: no Python, no Metal. TSan finds the data race on the batch +// description and on `done_` directly, where a property test can only hope to schedule into the window. +#include "basalt_pool.h" +#include +#include +#include +#include +#include +#include +using namespace monolith::basalt_cpu; +int main() { + ExpertPool pool(8, true, std::chrono::microseconds{200}); + const int n = 16, phases = 300; + std::vector count((size_t) n, 0); + for (int k = 0; k < phases; ++k) { + std::string err; + // A fresh body each phase, so the plain `body_` pointer is genuinely republished: a port that + // published the description after the epoch, or read it before the acquire, races here. + std::vector mark((size_t) n, 0); + const bool ok = pool.run_phase(n, [&count, &mark](int job, int) { + count[(size_t) job] += 1; + mark[(size_t) job] = 1; + }, err, nullptr); + if (!ok) { + // _exit, not return: the pool's contract forbids destroying it once a stall has poisoned it, and a + // return here would unwind the automatic `pool` and join a worker that may never come back. + std::fprintf(stderr, "phase %d failed: %s\n", k, err.c_str()); + std::fflush(stderr); + _exit(2); + } + for (int j = 0; j < n; ++j) if (!mark[(size_t) j]) { std::fprintf(stderr, "job %d did not run\n", j); return 3; } + } + for (int j = 0; j < n; ++j) + if (count[(size_t) j] != phases) { std::fprintf(stderr, "job %d ran %d times, not %d\n", j, count[(size_t) j], phases); return 4; } + std::printf("ok: %d phases x %d jobs, each exactly once\n", phases, n); + + // Two drivers of one pool, which the Python bindings and the pump thread both make reachable: the bindings + // release the GIL and PoolTask runs on the pump. Before run_phase took its in-phase flag, TSan named the race + // on the batch description right here and neither driver was ever refused. The count is reported rather than + // asserted: whether the two overlap at all is the scheduler's business, and the refusal itself is asserted + // deterministically by tests/kernels/test_basalt_pool.py C4. + std::atomic refused{0}; + auto drive = [&pool, &refused, n]() { + for (int k = 0; k < 60; ++k) { + std::string err; + if (!pool.run_phase(n, [](int, int) {}, err, nullptr)) { + refused.fetch_add(1); + if (pool.poisoned()) { + std::fprintf(stderr, "two drivers poisoned the pool: %s\n", err.c_str()); + std::fflush(stderr); + _exit(5); + } + } + } + }; + std::thread ta(drive), tb(drive); + ta.join(); + tb.join(); + std::printf("ok: two drivers, 120 phases, %d refused\n", refused.load()); + return 0; +}