From 4aae74ed28dce65b72a848557e66223fbe65874d Mon Sep 17 00:00:00 2001 From: Lance Woodson <65194841+woodsonl@users.noreply.github.com> Date: Thu, 15 Oct 2026 19:41:04 -0500 Subject: [PATCH 01/74] Add the ggml block formats of GGUF files basalt's .basalt packs ship their weights as GGUF blocks, so porting a pack starts with formats that read them. monolith/formats/gguf.py registers Q2_0, Q4_0, Q5_0, Q8_0, Q3_K, Q4_K, Q5_K, Q6_K, IQ4_NL and IQ4_XS: each block is ggml-common.h's struct as a numpy structured dtype, unpack takes a tensor's GGUF rows, and dequantize is the oracle, written from ggml-quants.c's dequantize_row_* at llama.cpp 3cf03257. GGML_TYPES maps the GGUF type ids. 42 is GGML_TYPE_Q2_0 (64 values per block: an fp16 scale and 2-bit codes, value (code - 1) * d), the type of every routed expert in the official Q2_0 pack. BF16 rows go to the existing bf16 plugin. F32 and F16 decode by a dtype view, without a plugin: in a pack they are norms and conv taps, and "f32" already names the non-plugin checkpoint dtype. Every product in these decoders is exact in float32. The only rounding step is the subtraction in Q4_K and Q5_K, which an FMA rounds the same way, so the oracle does not depend on evaluation order or contraction. The tests compare the oracle byte for byte with llama.cpp's own numpy dequantizers (gguf-py quants.py at the same commit, vendored unchanged in tests/contract/gguf_reference.py) and with a scalar port of dequantize_row_q2_0, which gguf-py lacks. They use random blocks with finite scales plus edge scales (+-0, subnormals, the largest normal). With BASALT_SRC set, they also compile basalt's two CPU references and compare against them. pack, unpack_pack and msl_decode come with the Metal decode kernels. --- monolith/formats/__init__.py | 7 +- monolith/formats/gguf.py | 255 ++++++++++++++++++++++++ tests/contract/gguf_reference.py | 299 ++++++++++++++++++++++++++++ tests/contract/test_gguf_formats.py | 150 ++++++++++++++ third_party/GGML-LICENSE | 21 ++ third_party/NOTICE | 11 + 6 files changed, 740 insertions(+), 3 deletions(-) create mode 100644 monolith/formats/gguf.py create mode 100644 tests/contract/gguf_reference.py create mode 100644 tests/contract/test_gguf_formats.py create mode 100644 third_party/GGML-LICENSE diff --git a/monolith/formats/__init__.py b/monolith/formats/__init__.py index 3d6435ac..9152fbfc 100644 --- a/monolith/formats/__init__.py +++ b/monolith/formats/__init__.py @@ -1,11 +1,12 @@ """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``: ``q2_0``, +``q4_0``, ``q5_0``, ``q8_0``, ``q3_k`` … ``q6_k``, ``iq4_nl``, ``iq4_xs``; 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/gguf.py b/monolith/formats/gguf.py new file mode 100644 index 00000000..59c5ce7c --- /dev/null +++ b/monolith/formats/gguf.py @@ -0,0 +1,255 @@ +"""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``): 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 element types with an exact decode and no plugin: in a pack they +are norms, biases and convolution taps (auxiliary tensors, never a GEMV slab), and ``"f32"`` already names the +non-plugin float32 checkpoint dtype (checkpoint.py, pack_plan.py). + +``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), +} +ELEMENT_TYPES = {0: " 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") + if type_id in ELEMENT_TYPES: + return raw.view(ELEMENT_TYPES[type_id]).astype(np.float32).reshape(n, k) + 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(42, [("d", "> 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/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_gguf_formats.py b/tests/contract/test_gguf_formats.py new file mode 100644 index 00000000..408cc504 --- /dev/null +++ b/tests/contract/test_gguf_formats.py @@ -0,0 +1,150 @@ +"""The ggml block formats (monolith/formats/gguf.py) against an independent decode, byte for byte: llama.cpp's own +numpy dequantizers and a scalar port of ggml's Q2_0 (gguf_reference.py), on synthetic blocks (test_basalt_pack.py +repeats it on rows of the official pack). With BASALT_SRC set to a basalt checkout, also against basalt's compiled CPU +references: ggml's dequantize_row_* as basalt extracted them (src/kernels/cpu/ggml/ggml_quants.c) and basalt's own +transcriptions (include/basalt/artifact/dequant.hpp).""" + +import ctypes +import os +import shutil +import subprocess +from pathlib import Path + +import numpy as np +import pytest + +from monolith.formats import FORMATS, PackLayout +from monolith.formats.gguf import GGML_TYPES, ggml_dequantize, ggml_row_bytes +from tests.contract import gguf_reference as ref + +HALVES = {42: [0], 2: [0], 6: [0], 8: [0], 11: [108], 12: [0, 2], 13: [0, 2], 14: [208], 20: [0], 23: [0]} # fp16 fields +EDGES = np.array([0x0000, 0x8000, 0x0001, 0x03FF, 0x0400, 0x7BFF, 0xFBFF, 0x3C00, 0xBC00], np.uint16) # ±0, subnormals, normal min / max, ±1 + + +def synthetic(type_id, n, nb, seed): + """``n`` rows of ``nb`` random blocks: every code and scale pattern, with the fp16 scales kept finite (an Inf or + NaN scale decodes to an implementation's NaN, not to a value) and the edge cases on the first blocks.""" + _, block, size = GGML_TYPES[type_id] + raw = np.random.default_rng(seed).integers(0, 256, size=(n * nb, size), dtype=np.uint8) + for at in HALVES.get(type_id, ()): + h = np.ascontiguousarray(raw[:, at: at + 2]).view("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/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..74e5bc24 100644 --- a/third_party/NOTICE +++ b/third_party/NOTICE @@ -72,6 +72,17 @@ 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`. 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`. + ## Original - `probes/` — original to this repository. From a80b464cef25272303d394c07e5f349f90d7a7c4 Mon Sep 17 00:00:00 2001 From: Lance Woodson <65194841+woodsonl@users.noreply.github.com> Date: Thu, 15 Oct 2026 19:41:21 -0500 Subject: [PATCH 02/74] Add a reader for basalt's .basalt model file monolith/formats/basalt_reader.py reads the container basalt defines in include/basalt/core/model_format.hpp and writes with tools/model_file.py. It parses the 64 KiB header and its section table (sections at 2 MiB multiples, each with a SHA-256) and gives section access by name. It returns meta's GGUF tensors with absolute offsets, checked against their type and shape. It also parses dense.index v3, experts.layout v5 and mtp/dense.index. BasaltFile maps a path, or takes any buffer that has a length and slices to bytes, such as an HTTP range reader. The parsers refuse what basalt's own readers refuse, because a misparsed row is a wrong byte offset that still decodes to a plausible weight: - a header, version or section outside the file (model_file.cpp); - a dense row that is not 19 fields (weights.cpp); - a layout newer than v5, or layers that do not tile the experts section (expert_layout.cpp); - an MTP line that is not 6 fields (mtp.cpp). ExpertsLayout.matrices splits an expert blob into its gate, up and down GGUF rows the way basalt's native_fmt does, from the n_embd and n_ff the caller passes; the module names no model. --- monolith/formats/basalt_reader.py | 251 +++++++++++++++++++++++++++ tests/contract/test_basalt_reader.py | 118 +++++++++++++ third_party/NOTICE | 9 + 3 files changed, 378 insertions(+) create mode 100644 monolith/formats/basalt_reader.py create mode 100644 tests/contract/test_basalt_reader.py diff --git a/monolith/formats/basalt_reader.py b/monolith/formats/basalt_reader.py new file mode 100644 index 00000000..f02b2944 --- /dev/null +++ b/monolith/formats/basalt_reader.py @@ -0,0 +1,251 @@ +"""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/mtp.cpp) and +a few stricter ones: a section named twice, a ``dense.index`` whose header miscounts its rows, an ``mtp/dense.index`` +size that 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. +""" + +from __future__ import annotations + +import hashlib +import json +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 parse_dense_index(text: str) -> DenseIndex: + """``dense.index`` v3. A row that is not exactly 19 fields is refused, as basalt refuses it: a misparsed row is a + wrong byte offset that decodes to a plausible weight.""" + 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}") + rows.append(DenseRow(f[0], *(int(x) for x in f[1:]))) + 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)}") + 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 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.layers[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.layers[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, n_expert: Optional[int] = None) -> ExpertsLayout: + """``experts.layout`` up to v5; 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.""" + 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 layer.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}") + return ExpertsLayout(version, n_expert, at, tuple(layers[i] for i in range(len(layers)))) + + +def parse_mtp_dense_index(text: str) -> Tuple[MtpTensor, ...]: + """``mtp/dense.index``: six fields per line; the size of a known kind must match its rows and columns.""" + 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 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}") + 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") + ne, off, nbytes, type_id = tuple(int(x) for x in t["shape"]), int(t["offset"]), int(t["bytes"]), int(t["type_id"]) + if not 1 <= len(ne) <= 4 or off > g.nbytes or nbytes > g.nbytes - off: + raise ValueError(f"meta.tensors[{name!r}] is malformed or runs past the gguf section") + if type_id in GGML_TYPES and nbytes != ggml_row_bytes(type_id, ne[0]) * int(np.prod(ne[1:], dtype=np.int64)): + 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()) + + def experts_layout(self) -> ExpertsLayout: + return parse_experts_layout(self.read("experts.layout").decode()) + + def mtp_dense_index(self) -> Tuple[MtpTensor, ...]: + return parse_mtp_dense_index(self.read("mtp/dense.index").decode()) diff --git a/tests/contract/test_basalt_reader.py b/tests/contract/test_basalt_reader.py new file mode 100644 index 00000000..158f546f --- /dev/null +++ b/tests/contract/test_basalt_reader.py @@ -0,0 +1,118 @@ +"""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).""" + +import hashlib +import json + +import numpy as np +import pytest + +from monolith.formats.basalt_reader import (ENTRY, HEADER, HEADER_BYTES, MAGIC, 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], "` — adapted from / copied from `` `` @ 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`. +## basalt (jesdga95/basalt @ `b4c63b55754637f4c72ad53a0f791d425f71eb36`, MIT) + +- `monolith/formats/basalt_reader.py` — reads the `.basalt` layout of `include/basalt/core/model_format.hpp` and + `tools/model_file.py`, with the checks of `src/core/model_file.cpp`, `src/core/weights.cpp`, + `src/kernels/cpu/expert_layout.cpp` and `src/core/mtp.cpp`; written against them, no code copied. The test writer + in `tests/contract/test_basalt_reader.py` follows `tools/model_file.py`'s `ModelWriter` the same way, and + `tests/contract/test_gguf_formats.py` compiles basalt's references only from a checkout the user points + `BASALT_SRC` at; nothing of basalt is vendored. + ## Original - `probes/` — original to this repository. From aa4d28532ab67b609525173bed17a2ae563426ce Mon Sep 17 00:00:00 2001 From: Lance Woodson <65194841+woodsonl@users.noreply.github.com> Date: Thu, 15 Oct 2026 19:41:32 -0500 Subject: [PATCH 03/74] Test the formats and the reader on the official Q2_0 pack Synthetic blocks prove the decode rules; real bytes prove that the reader finds the right rows. The pack (jesdga/Qwen3.8-Flash-Next-Basalt, Qwen3.8-FN-GSQ-RCO-Q2_0.basalt at 2a6a758) is 64.9 GiB and is never downloaded. tests/contract/fixtures/make_basalt_fixture.py range-reads it through BasaltFile over HTTP and refuses any reply that is not a 206 of the exact length. It writes a 49 KB fixture: - the header and section table; - experts.layout, mtp/dense.index, and dense.index gzipped; - up to 1 KiB of the first and last rows of the first meta tensor of each ggml type; - the first and last gate, up and down rows of expert 0 in layer 0 and expert 511 in layer 47, located through experts.layout. test_basalt_pack.py checks the fixture three ways: - the three index sections hash to the table's SHA-256; - the dense pool, the 48 Q2_0 expert layers and the drafter index are consistent, and every fixture row lies where meta or the layout puts it; - the rows of all 13 types the pack uses decode byte for byte like the reference, with finite, plausible values. With BASALT_SRC set, the rows are also compared with basalt's compiled CPU references. The weights are Qwen's (Qwen Community License 1.0); third_party/NOTICE records the provenance. --- .../contract/fixtures/basalt_pack.safetensors | Bin 0 -> 49484 bytes .../contract/fixtures/make_basalt_fixture.py | 108 ++++++++++++++++++ tests/contract/test_basalt_pack.py | 89 +++++++++++++++ third_party/NOTICE | 8 ++ 4 files changed, 205 insertions(+) create mode 100644 tests/contract/fixtures/basalt_pack.safetensors create mode 100644 tests/contract/fixtures/make_basalt_fixture.py create mode 100644 tests/contract/test_basalt_pack.py diff --git a/tests/contract/fixtures/basalt_pack.safetensors b/tests/contract/fixtures/basalt_pack.safetensors new file mode 100644 index 0000000000000000000000000000000000000000..5202497dfac837fa320ed9edced936eb90923be1 GIT binary patch literal 49484 zcmcFr2UJtp)}{prpb|&|!3H6rC^)oGbaV(NfuJ}E)6ZaA8_W4W0`sL*7|WRS8j67clZ9zKHuJF-$1aV!RXHl zG?IPKqcQL{CQpfoKo(az1E7k+eVW+U;mTMzkeia3Ic`zz7jUjNeS0G}^WGJ@;j?c*Ep3A*3EMECwODI>rh-o638e}(t? zm*`)%eFWA+FB6|IgBt};P5$p9#oPajp)!K%;q9+?>p$VWBsC>DHRT`IFyKq_H;Uxp z9T51@cKLu8$4?xM>wm)a@$w7&LP(DwdUyu~`T2cf=LqiNCCe856Rx+H&lk4gD58gt zSCD_;e{fTlB!P?Lz(ooF9LGUl;&c?v!^bB`?}%P9_#m4DF8jLZ`08){*%lt1?csy- z)o&F&#&R$*MX+S?Hym*Ba&VepF$c_;#>@OFrnis3SI`$gN8mhs1A=^TAA|m$@TM(f zi}XwNbx=P&_n#R$iss=PsV9{N$sz%;>fJ(nNm_^|!i0k}X;qPGv%o8#pZ!13Yu;u7@1=I8D0#o-2k zfnMAIuY?bCxq^k@hk5_G$vn@{D5_`V?C(9PK5<^t5@94b6Da!;O5M%V- zCxN05294_QpF8cN9r3~Rkpd=8z!@2=zt4R1V$kak*wO1{f8258T|fPP7=1U5y)gB| z&Ghz-O#8ji85tDgiwp7z@be1%!|3HpQkNzE&d-QBzu#CNvP+hYOwi9BRhCb7?C;C6 zB>e*s9|#y(@R2!s7e_4rFrDP<^JQm7E3#3WMritg@E_v;225Rq1UQa z9wWE-D~lsl!xysIXSeqLh{w^j`3r}EBcJ}s-{^q9u;=gVqc;KeL`?Rpr2nrV1OP?PjJA9sOYPge?joy zn)@-yJ~-Upa7^`!({HvBgFo7Zqb~kQ@~8tNA~0&+e}Xs2$6H@)k4*iD<{&?RJpsNx zU#0mgCDUg%jBe@QmEcP>>rW>C17(Pn6pX*M_g^p__ywj%ef(#pM>58zOnc)3aNa@sjrwIl{;VMTj9>4M zwfI9S{X{YJ+58iVeSEz>7iCfYu(J%jh^ui~=*Bhs|e$>}LCBqNrrH^F2XnZx4KR+gaZpFu{ z{AH3q6AW*CvH7QZeMm~b^BSPHf0X1Ah0_Y9`KRBre(igrTvm6-cr_a=%a2(*{>+6TpNB0*w{!se-en|P8THg`;-v#2!)as90 zBV+!oC`OL=pHYj`$3&pFci@O{kJM*gfjHlhHo(Zhf7XaE82K@yBLVlfv5Wf>r=za@ zH?ixd7d5{RTkqp^_w|_l;sN+`Zbx_d-*M~nnKt}UZU42Nz~S_TqYutoA0@v2I2X>i;E@M}7R1WPM8eYutMK>Nn`8+TiV_&m}%y{sCXF zC%)E$`Hbri72)3`y8o_l)7Qj)UcUMwVua{G{VCW-uWA2AAO7CpkGcN)%8jg-iFtFs z;^v=p|BK>HzXbX;?xWwlUzCZDI+lO77C*oLKg-2uM1MtzN5t39|M%KWUBPrm<# z>EH9lr^bFv@jskEMmT0feZ|K=IsTxEUpR<(`v!ffc=PqqA5a3mQoQ|n5FKf?eod8q zNA>mhXdb=uh>Yr8`}0&k(yjVLmq+#C4*~l<<9$%#(FXOXEC=`o2I`srFQwyeto@kh zzt!dt(iaYT9~}IXMz-Ro zMCGe)d`zu3&MP1g=i@WNtp2sW2=Ezg zT7FVf{BF(%EA-7oaJ1_)ivQuGk*FEHT(;zoKH8sVf6VVl0$lai&dkTYrY8SCdaC!% z*Xs{Y^$nRX6{i1-r+*mzFZ>+QroZ>}f88u2tEl%a@OM9heDsy;7q-g(;^&`6f9&b# zj`_-x{{ArX&rtZNOY#?K_#-y;z<(<6e-**LdS&qP_5BdSqZj&f$$uZiejl}LM}k=Y z?DRt>_@Bf0cc1?VivK5%^)0W_P#*Evd-P$#=c)b6Yy6KM|6%#Zi~Kj+_M->R|34A^ zhl`^jJ$ez~{V!trAN~Eiu#R1YUbV{c!_O=X5%1*SZ%-QlZF@_4uq1*9y1^LQP|Y>H z9PihO!Vt~!@_akAsu0|bMmklWumi)w^;LtQXXBR2-a2xC(>)?SujWlq-a zu*G%|dx+7*1LH9iTD&!vF97IOyke@%DSVEGBIktX3uLiatOH;!OQ2rE3=k(09R{k| z;dI&*F*&Dnj!UFxDpLSZhoGPU;N}u&AzE1o7HtY35KbhKDFLLJ)TqZ6$PkEaI62KE zoUuV;K@hmg0HQ!eQo{kRH4`PTC3awPOAwb!_oJaE;dH0qAmWBZbtOQ2c_nf(xE zwN~vLQ$h-d(d1L`_{d;b6r%zYx`=553gZdXY8W$YGce&28YqH0qw>-QC;BWzWGg&> z`N0JcmNR8ox|oI{is)2pfR8~KAhu{|Z7Z|SkqeH=i1cyJZeDMiDR3{I9F&gb*fq zi1?5R2$%!HEx`~UuQ5ehtIe;L89Ds|-4#bP%9_M1E8SB|%EFouD?tPoxnZJV3CcPc zTA9m>U1%2WWt^du293wNtWiz~7m~hBTyP=>Ai`Qs%;k%(V)1YU6@e!oMnGwpc_2vG=e$3j z_l+rp5o%4brc&uy%xG*lwOED{^)e7h`|BH!nzDJd#5YmS16VZ4pz`&Egs?nxaA*nlHGVx(VXe07gQcX|s5^Bi z88Nt=Ru4zzx%tyWJZr`NOf`pNXo4(1S#JPv=#|ys!h)H(viT>srXZ^|J;9x~oUq~v zcp|8awBvs z31Dbspa5!zMXG&y(Wh-v83YD3%W#n0ipDpbeW8Lgg+C2S8sn-3hRTS0mC@ z9ITxROmhix3IJS4>$6UQ*;xySB`@dSG0{xGXh?LjH5)+!iK!Yn(V|8=+YhK+>BJC+ z9mq3a#=%_C!#a7UObgW@f@N9|#y05101QSBkv>>JjFy?wnE+&2O@+@uYBYNpl1t2n zFF@pn4XUe7Atn-IL9hhFx8?Uuj-FgYq7toGyju`!nguZIJNR&;Bh5)DB7|Rf-iwbX z*<5LNLt$Y6O_sy}xO4_+2!zQn@z`7z5s=Z$0ctF&96`t$WLMLz4b`OUHnKv_P>89t zr^;SU*zex6?wZccC5i!XSki2NXG|m<&kw*5hpdBLKu8SbJ9M^L!aBaGQ8?FeD>?o` zS$wkoG5Q*w8UEFpxt4_OW+8i3z}YHoJSxK34t^i$`qh9 zy;lQtatRY$gdmoI2_}F*Wu(E$=PtlQh}1}fQj@IZS-?~+otg>&a2i6ksFDj(OJD#7 zP|BiA^OA{9!mTyTI@&2=ZAjBKDnf@C!xe)esY4O5i8XyWX2Hi2WM|=E`iT+-_Hh=b z({O726d1rNqii9fkVup*#?K8O1^~hu7a%ON%_vNkqj8i+!elfRH9Q5NaRC~*L=95K zQ4Fw_3dB0m047jvg5?A!Dv4CfkOeVRp%yG>?#IaBE(i)D0Y;&rko$!+0tFL+o86pk z8c!%Iqf$%ovT_&nrEr&Mn|LsMKx&<(%lIXSpgxu33Q&zSn44lE90q7~s2Wbp#M_0G zV(4~+d}dIs&7yP0ckv*PjM}sHB zx8tVJ76P)lHPyhu#c-}MRnAt4S-DgoLM?_fJSW*W4dbbg=L!tvHWx$^oxE zgFsrSn#K0&ZN#!LI2rW!GdE}>W-Uv0MQae3LA7vf)};OOXygNrGplL`Osm{;XFiHV zoyej$jKPl$M6(S+iaR;XKwG@@boR`g*i+6Cgk7Y<3*us$3w$6}V^jUcIoe1@V>lxW z%_H3HS+ZMVL$xENnfJ^vLs){xJ4$+@hR&f`*+GYr``NQl11rMmpbex6197C{m*LCf zT@a?$E(Af>bC;6{Ry0|k^y#3Zn2MxoZedHP8W;>!UPWP=0A!7vIotUh7C}ZZ$QZ}a zstC};dg9NR1f?uw&KN-|)H<4Zn4S>f>&!XrIM)hpw^&mW85}^SAuc+n%aAYvk&3g5 zMpUS>QP3F}3o6_#k47dVc(2^O*ok&S&c)WUlzsq7ywPA(9Ajc_4MiJ*Sd0?E3dS<7 zG2-cGM5tOJ0>Xi>kB)ahNl%nhsyW{{t7!%R-e~wT*BXFb&qB`Lfu3=gm)}zbp&-^# z(J8QF$nM%@^$_z0VHhLSFu{iCK<|F1UvxG=r?crafGo2BfG`mzhA{(Wtu_;uK`F&> z3fZOrbD7D&hm`2I8UP{S()>#-(NZw?v0-)fti%*x*iLrAgENGoKFTIWom^0fSArt$dlnf#4yQ(8CoM} z=QFIW7Ogdhs0Oa9BY(2OL?X(8B8sX!7mx)X!gj8iQ9TVwEV&-8qnc<8dY|{Un1^Hf zIQmiL;j($2IjU4*;-XlzHcGCuO%(^T5XD9S7LSBr1V-@eU;@n$2!@nZSCpiZo%_A% zRR;8`2eh>L;b%6A5Z7ujC9}H_`2=~t7;ad~>~Cc|BWtL^C&S?E5Q#%c=InXyC!FjR zO(royXD!1iTQb{@NrzMmJVO$O*TdOtsuT=epQ%c$DHg1-PvqeH3ZjY+WT3jBGn|o1 z2lg^F7eOmJ9Jb3QC+s1He;{NM8G=tLN)}o@e z9Z`R4e`@AUqPz?!!4%*K*xNRdDsCiPsRcM11CVaW(lP)7TmzwjCNcuko=hCLQazV_ z%Qg^QWaANS21|wb6dc3gOW?p-U?CNl&4jCwEJBVt9)YL^{532wn~*|jV3)aK*<}p2 z{3Je2$}+S*Y=h#d)LOaWdYNha3C=b$6D*FX=GCNOie)F)4N-Atpc~rRrLn1mZy~kyxE?hjOBsLS&X0Cf1s0q~H>`3<4{j%8)It&MnelhNqZb z-UztwZwfrneb@0!md*FgfesVghn~ufi`iqiwYd)4=<7?wxGQDTSvrV`{FpOLX;WR2 z8wJIX2gr-GB!i2!S1yk!X6b5$t?-AtObCjS&+>Ova;b}fS8+LbgDL;?G$EI zi4>y_yOWm=#aD*c)D+vm`D!NT_Dwpxhd>cEQj~LoJ%XJr z2ckEXnlgOL5`YSH35zDLgt+C<;Y#K`ekzjs@0MleLhBa3U4JCWuef0z`_81t5a& zHo)YSQ)pY9G_V1O>$HRWiNQE+x!7ZY=k|>x>sZIUUua{l1DY%cqt1d!7%ep@2WA+h z4uO#yKvQgHLA9J8p9P-~>p&s_*~ks{8DPb=HMV&=Y7<50PwF>Bc4eJ(7EaU(kgwcB z*1OMzcieV|K-6?G8nC9_MiLCS+Lkk#Sx{$hCz>V}Ce|+|rTPlxzN{2;5(Y#>Q-Jx1 zYB^yin-%h#<5)y|4#X*2mv@aLnJBOUenlg8a>GC|zFw9kgm8r@Mh6CTG-nrKk$6oG zeTYWuyZ%N)nP^?&q+Od^1~?;_fJU|*dyOf!Wgrkx3Kx%s5Tm_v(eo3Zy&AV(f)a7y zC(LP_kU=$hiZzT)GxI=8wS)_vk)ii6L~MxxXdir%LnjlMavB1K#meb)G8MuB^c6cC zD1;q%Gaw?FWrhGCL*Z5W|NC7qWsQ&{*1S zZk!ftDS%{Y3B^PuBE`m800B&>Rq=71E{E`|Pe1|Vwlgm^YM-(uc5p_3xT2!efEUGfV- z%+0FKCD8y4$YEP7z(h;oL*+>_14n_dyU1pGaSkS;S)>C52q`fPi6Y2M>N;vV9CD;v zm{`2`0oG)U6k+YaCA?Z1_!x zU^P4;0Z5RJv2^CnJ=)%*iONP6vDTJjO=Fg5P-RdJ7fF<@hxW>_Fq+^v29Addh>`Gw zrB%%DabcIbGtp9EiN@U%LCqrpv0{Y8>81v03k(SaOn?(?PlIPE?enTl{MZbr?M4(+ zY;qk}w4J(oQ+5ql=81trog4`ScMyj-f}J3Ry2}`F9sQt*41_}bM4B@DFm?9qovXN1 zN4Ap%i?iKXWlH796jXXj4vMZM$P)OPj8djJClwkGUXshzuxjLEH0qWabPOVE*lw8n z8^k(aN;oB0^2F zu-HQ8O&73=$w$E;hBW3B6@dZclwz28l#x~+cw|Pf6Bz-*CTxnx#|F1KmD&o+gxqU(_UmP_%dk$}L@~>Z^%eq}M?6YJ1sixck9L z{P+jz1-I~XwMIk-NP{3Z&wV!iuv%^(U=U6g9?r^PbEeHA*+up?wrDEDJhW3)yzn9 z0BqZENXJ-6ESK@4+yUfLGXX223Lw`<0ZL+~Spybqb^-XaC-nEL3*)64;()58EM$;0 z=%)!c39o_1l1y_+AfXIT(|0`5FIj0wen5xG~ zv4I2FF(sZZCPwmvh8w1Uy1u_e!DN|%7#QD+;nkQD@g>f|f!=%wtSftGIU~av zxI+zYvZtleQN>6o6-POW=?6jxOlg9X7R3bs7rBf0w zj3_bGp{Y~?{v;b<6=7LoE+{jx=k&v7lk`<$F&#UJnvJ9)S$Gq8IWWK=*0f{jV{{zQ zq>V;}vH1Pr7Ea%}0ssV%!6N}0k_wkG5r{Er0hX#xk=uv?F*ymKMORM5x>52X1nUE3 z3q7eWa#M&?F*>!&^orDF!n!K4wWkI16zm5q6>ys{2Zktz7#5gnwblxaGmRhLuU_jO zwieUmL5Fs_})2V7Jz^D!lyvc`n(PDEa*bxn&j?L~O*%=f@^ZI57kYn?G{yI=x4 zv}|twD+5{>XK%G*T1QA3g>-Tc8E>tdYA|3ecP`d%zl!lPsyvKA^+<@&vR#8gvOh?U zWOmWA00c}bJ%}d0=JXk=7Uv6hw*#eVkL(YsaoJJB>N(4G0zrs75KguNFd>5ny5lK4 zK#CO-CsJ%oRT_{QLaoNjIfH-+5ujo5?atKk;XM|Rv~HR(Dj_^KV{o5(j-kpBb2x%f z45I~43PlyCqLq8{Q)e1fTpP?snWou;S)^L{L81i{2{QtqUOEh-A!<9?#Y|&&3I&Br zWClU=AttbpTB(esQX; zsZ<+g$Y{BvhV4vdQj@Afh!Qx8hMGjQsdY7?)aTr0+gPrDGb|`cqnFmYi$w>yMry~U z;_~2I+JWH97|c1NWm@d7#+4JX7B zxl|HSz=o|%aKw&{hq_nwmYa0a z5n~R*xslVb0L2E6h;^Jxq;1fIM|M_u)eHjzOW9fwhv#O3d~{QHPEB@BbtGJ48bUK$ zK;Zzt<=w}?o&E4-WHHeKpayl)^6WR)U>nJgNm(j27#uHhFJ9(61H&My#Z(9ossW>s zSUG@nQImx*;Q%5Afj>c_74AL0Zu#N#3x+qnCq4iafCD?M?$$3$zE}M(4L^o;}U4s|MR5XH$ z3mA>t$Z$IWWP?8-XfhKkH!Ty0b3)28#l_L)A+&NrK{N@+t;I|-A@T>>*CQ|OqN*Yd z8dMjZ&e#AY2z^7{DH3pCwxpncvzNLLZN2N&A3`^(-dK%UWInFirr#LHakwEinNO)g zSafeIbQTxP0pPZf@&F2yVN*QUa5GjANt4OR_8I}5DkF02Xnj@4lIyBxG*&Q&LdQ3k zQR$pXr>RrK*hvViqYR@eVN%Lp*Koq{AwOjhxF^=5-JEUKgdjFmv2D0EvBC&t2>y{2PiRkL%ah?2+OKqRk-qP5&U3MEigt#ju+AZ zp9M9MQ1n@VpvFh(1;kD_Y~Fzu9{$EAGE!6Rux&rDKg>i~Tv2(PO3355eDGReF=V?gwG_GK!6J`m!WE<=x$^tfheHz)? z#oZYMs4Ns9vYE@m$T%#Rs%sJ(3lIRjK4Yx{FXvHs9JnbGw(qj;r+qbBo9;c^0AOg^ zj9Wk#GptM`x{-dmdkV9g&f-{DgrQbw#Xka%l2-VxbnfP{;&+LK+szac@;gGA@=nD* zvP*mZlZp;*X+xbTf04pm+Dc|(qTl;u(tv!)8YO?Z44O<&Bhh`@$}TfXb#0k(ttp8! zzU#i(!kb}1s_S|rQDL|Y-vk}xBi1bPt6=Z9+er2H2b zA=%B{`TF042$eL;8|6QWPW=4NB5y|fihxxY8sD}lyH~z_P4k%PJ^yym-8tqAHPW)#s1662QL&B)4aQ z^UUx2Xq7A4&AX?!Do==s&8o6nG5f_Q#jWL)+OBI)a}MOwGV8|e`Z0W0w!;}uQx@#r zo!u{9Ki&O)`#4vlxR^6X3Y0F1(GL8CEWe(EUF?!QcwpD&W~h%>#=Mn1Z%VNP0JPj`|9|W;!5B27$_qPtd*+9&3`j0jrCZ;Vx3iizvpCA9I@yt&ttpMU&4J)*bHP z4uFs(PGA=o^49wGqo3Y4J$Sfp+qr2s2YGxTE?vByWXyBQOD~@NqIW7!okG{iUWgev zy~>@GbA`7>PozT1iu5&eY9g&>#x2hwOz+`#lnweXNn3~nc{>t{(o=hMZJh8u&OK1*U1flJD=*3yv+=wX-Vq?5Ko#@Jqa zsNQzzeoX@I{hrN=1-q4T?L43;!m;6?GtASRA=hVlrK*fZW>xwc(*6M zjajkF<;Q1pJ(otzvDjO#-I=($M^vz*Rdl0Z^Ui?s<4wJmy86w%^6ouvR_Rn1j{C3t zp{ufYMU0L<*G)omuiGq`xn*M783&av)H5OL#*b|?q>K#)-(>DLJ8z>se=n)>7fnm; zuiuYJ!9vWbc|>D_A#9f)n;$S)(?(%=M>uCkxl^vC>K`oD0R5SRX?5iV+^0%ty&|mT z;OUIzQIEJk%QI@k30bYm%_61f$D@2+@AY2!a9UoXDNW23##9~4lyq*;rQvdx{gl?9 z*xV1+cpI1f>UDVem8{u$)yp+$KIpu(GTal$8SBTF8f%_hyqoxbvQ@m~@zy&!S@YKY zW-1MlMiYnCr)q4Pr+2<{w!d>`N|$>ogm3l?<;cj34pefn5?3%PCDn%!D#tZ`7rIigf{sqg5M(pMomB0Cm$p^Lr6}BR zV1TR3M4xY%hoC{_uwJti+p0}Bc$FJ2rF74D&$=7D%l+_LFs7{khwu1-Wo-5s`3pUFukjPjS?#C08=cg^m zo+FY%=h%_MB|!}2(Ql7`M}O`ooB@_Y-{K%ih^XZsi`sZ zpcUQo!Z_(%E^Zb#DaQDQ53YR1%0jfa?$kuL)yLZ}>q&@S?C8{G+ z1{duuI^(d=zVcQ5mJMy)4()!iMN65CmAeY+Gk+>N?MIWDuBy-l|9sut(9{h6M7a6! z*;w_j@Asj|niALgL_iRI`?Onry~|E{>5u8Oj3;Kr_Vg)P>!XNA>JLlr2H)qke5+Yj4BQ;E#P3EvKbp%j*V}RlD2TkEUPUYkC>B?_%Ss_cz;;1D6_- zQ@OZ!uzlywXG$}Bb{iJgyC6;0*27dPithB44nLC!f^cDl(IUpw8M$s@u`HKcbu$?P z=r>FtX?Z%`(I1Gvmr1vh2;anXiYh%e?b0%p(Tq%9Y~D|K6)Wa5RI6^%TFn_dc%UGN zjBxypH;=6*(gmtFS5WCmLTN-mY>Hw3fyuVs@ja>Qo@==UYZ_t~WeQBkMw(3QfRs-2 zpE2W!nxFX_>6uqU%>iE0wT_tuZOSLw@Xg_qe$%I5Ss4v0mD-FlHDF42-N2~-MgO-e0#-6y)$PZ9p+6rA7)XmPg8p!~ zR8XJ2Z{;4k-_T<5m7#3cQ0uY5(?Xc}_gECR2SK+BWHAqKJ{O~{T~W1q*ZqOD93_ue zxg$;LvGs5zy?Z{PcxvaA@Z}ky(mJU^m$^ZuFqdSkXi=SmYV7*b^FqT?cQ|fs-R#~L znOk>NOq&iNCA|XJiv<}mbus>%i|1FQ4|8SG#=bKZ{->|IEN7B8E6R)Ojk9NE#J#vg z;w}HybWvhNXEm@Rd0xhCd+DOE-U#d4BD-+np{Hl2Yw92TB0rPcBqim}J$-lnTg@0; zHuWxJdD6VSF9&b9d6mCVRLhd`s$$RQ`Kyl2PhZuvWX>7t_=mSo9BZxQ&zeKs#=`N6 zYi}-xyvrkd~Y{tnFnVN%4)|ZXw&s%2$-8 z-B0S0$F)QSNa*RSBDN?z&ytKn&ZQYirpEbi(hedmGT|n14ib8Q!{c9;GA1dlSTAn-b!^*}@Lwzl| zDdzoqkt=)4-e)EI`a&&>>bojf?$|_Z+?z>eD!tVAydVcxZ?%nscHpuc#l5ShmW0i# z-)vV$zl>IP#9rkVT9%wWwg6tJFj7t3KlX*k z$S?38PTL_5Oz)^CjY*6m%>yUQ#%1iyI`o}I&x}qBiSo{rJlfH%^IW1Ew`ZtG(K!Y6 zTqY=qX-#ZV6|K(M>>RUTyU6&=mIWeqJnva=j)F*p=h;(#MEV;98!jvt&m2S6dD{@aWW2aiU zw01l&{?*{ofiuAdQ?KRkzudYj<(lC9QA=uEe!1V;V1Ff_^I&s>x2-Zws%#oKVCK+Hm_Df8eSrl%skzARa9`+FRS%cY;-~1rp`hIsgZlSLkY-4be&SA2`fx)XrQDmCS`fJg=2Eg`*~Vj5IrkgdndIbsfXTL?+1&RAJu)S%J_7|u80Q2 z!HZcFj29+vvG(l;k|F~Q*Q4tyCr*|#QDoiYw*OAVOB`pi1pZt<=Y8yJo4z>mz)^jD#{x zNU^9-6-BQ^+|sQaT!d=ItD1}+KJuhJ`Yp8j-kl4x98Zpk+HgGd{eomiXUAES9lakJ z8aPdQP<3tfgy^{XjqlDs@;>p+qiF}NotGNDyEFl3w_&(3k~HnI?eodwNcpo?KYO~_ z_VT6*+td489pU4G;IR+K8Cc`*HH|ZP)TMNJ-R83T;AQq$+lvb-Y)zU@Cj812!^d&f za3zuZs~10<9((s!&HXFZ@TIN}L&%d@&&B%=IK4|Wuylr9dhzYP3!5e^t`LakUjG&L zo14ue+fxr=7GuU;#>lRQkmlYYPJOTe<~;O$6LZ!(EbaSj`4x-O?~nT)>z(;)sqtjW zeffp4;ghabY&m_+`PcWxC*Hxnx4C3!ID8p;_fmxFs>tx_<)`;A+;6?qLH+*q<7F_S zL8C%`HS@bw#{I5NGgoDEzO|mWZua3vp2*th`R|@;<~q*8TkYiZqbFv0VBS23dpF%* zH~u&4cg)&w)%i-y>Qikm3RSZ7aJSjDPu9flcgorsA*eQZ{+;)R3G&$;j5z$Z2V)l9 zu)gb<_uVOj18Z(l>@6;CxgSyHfq6G})e>71wr^K}ks{gtm&Xs*8rnq6d`|N6vp=R< z{Jd$u*G5v|nB0J?%b}0Fq z-?AQKk3StZc}K~~_uePpDC|Vtr?agSP7EBHe>-LTq{GJhy@Xff*F9BZuUybbZ7*9J z^ebA&zB#pT>uQJTleRG|f1Ui;-r(W5_a`4a2V7iq;d_~7toEwA*DURO##S@hO~d6O zV;;?#VSm-G-n`y!!p#<;q>l} zy?D3c@9eGSMO?J*Onfx1jOu+CV^($7YNO@T#s|vrJFXxqe|Rdd$?bkNYw2YB3kjwn zlU6Q$dvX3mJ03ECC4AgT-8OdEWYX)&+cS-WUmHw!v3-*{>U6#$JldGjP00Uzpn23#700B@+Mjlg80mKFXP@Ss6BD@OA zkOOoC5o@*uFoGslg@bI1Y@=x$g0ch?K_fsz9nZ*}1T@ERYue5X1=?;xc7S8E3a>CS zG60;2^P-~MVi7=1B&K*GsZC2j0tjffxcyY26H1%il^XmMA4TPo&?$K8+}d+8dw|Zo zpzq3)D5Yv7@@bW>ixp*%o9EIc#>3XF=TPiw!T|!O4+WH2L^uS5AqmgZ(RN4`CDN$i zqys*lJjIa{xwS^zPbauIpcYZgxforXm_(?W|5SajmoV4J!OcW)qKm?rU2C%-T9yUH z%bdtsF&T*{!8&uBsiykoqE1T)bw|);t>leg*a=Ke-O20jNGo)0xi)VOWPOirXLD_3#o|^EtBfW>vvR$l zF|mP`w6b_`Y60A_Af-l~k zbv%|gca`n6yzn-YqQ;2&=BHbOcFBfCL#fcM8#Gpv0AY};KpEd1*^%(mu0^+Pi+T^Q z5XnmAOHve~b*H_$&SZ??^Z;i(v@5g)C(`Z+_~~t6q51C4x$B3@3#>Zq{OC^@g8u@C9A4q|Y)@>VXSdmW>!w@|R~PBfvB+m{Ad(wEHT z1+dnsBAYlQiLAV}6wH)2aGKXy2B_8qb`URzuHBLfW!?xVxoSDT;ozmZo_T|X%Os7ZiAjW_!oHSvSxepS76?Bhx}Y`E>&L2$-J;g=w9pJm zzDmT9N>d9963GuV#>P$t>kVoy2Nx&p(##rSSH`RoN19`dVE#V%^=L4 zs{v=OyJrd*MPq0yG8N4$HxO0Il*C<0$C99}b8Z}EJeSY0PCpu3fm7ZzEnHXbmQ3>B zlELWT%$pAC5WUd*A+0;KKT!aPe<*IJ-H!)6#-ef~SV)k`xs`){-NoBaIxx#pGazT0Dt9Je#0`W<)(ZM_`z;_4$WD~GrS z^lhqLx8>VgkCSX{1BS1^z6cvY46KHlJhFagbkW1Y<%nUW-=nhbErr>Sx=HC*bXW^Z z=jtPaTW6WgI34DO&{^HX3E30JxmgMJ zSqvR?YvkT)d12jt`?-0G{qC9*k8b{U_qWx1Jtw@U9)*$ucDSB~-ZY|MFZ-cKe_Ev+_&U`n2Qt4U+i|!{~E#N2hi;IkDa{ChM(`bclY^#iQhOA zc$k^OGJ9~$FJ_4GPg(9I7G^DX>~Uz<0}H$^Og)de4}1FV*`#Tf2HUfZ-x``+&&8QP zIcSaRZ$da7x27MzZ2+IWNj`DXDTQU9OT|0r{nO9R+ZnsOwO5>;FyZo~n*nWz)o0%M z8obAMKd>-66Ow(=)7@$2&EUPqYM`^6ZH)R4**!U6dGp?!0Eeshc0eaS{?+O?$aCkX zYW0qr@=@f*lNouLvgiZVA*e6 zaFcGqUWD7sn*7@1>I=+y!wJZ@520fww`%SBz4lrDZ0>P`%y&n7#}a+u^?jm zeG}$js5S^^`aJu)VXyb&hhNQxsvrNf#NL?DguSVI|Dd~Wjz#oO^wp$qk8OK!{~8+g zjnf(^5)XahIe>EXo_y_@(FM$IqY(EoZ!S!Luf9FOYi%#N^jnM5BqLjQ^vcs~A=jqd zRyF?CAO?M3+Fv}6L}cS0KbvuEg2j7>vERG}kjTE&zH=sap5HpZzqaTE`XLGotzX^z z>f+EliybFsKwrC{cDvrVV{v0{=atp3Em6YR$k5Ycw>`UJ3VrjvrSMgQb+)gA%JKS3 z+(B0q{B{3>qv!5Ez}>rW^}^Yk+up}oY@2p}{J_=Szco8VXFq<_HD*7|uL&qhi zy=7RW3-&%+sgxX;NywB14+5 zYmjFt1QMQ1(pjswCqKVj|EB&$mLxxa4RW9E?as5jRaoz^Ev?&;%s~fxMe9phy1svw zP@w-3+k@u4XB1ZF>Rx87UE2zT-66bc{4Kq$Jbia&yDBX+-@n4VLb8R)Q%}su0MZev zW|d@v{u8OZ0GyPbFOleJwUS2V zrbx=jy3P~iY{%mG?VRT_r zW3OU`3cM+A-;hy}k(VyHCE*n+^j&#rR=iyf@|9~;dPZyXyyRo|?g0C{?fH|pX7oN2 zq!CDIyu2~uAy1{$T=C7;^${7W@j;oy@w*!eP$D|7p}sq-A~j!>SD+e@t}GYp#CfUA z48AT@q2Se<3Nlm*VMa2E#rt+=eVRbJypR7>A2Mz7{=jmSbUx8<`nQU}HA-GZ!*n@E zRZx^EdjZ|qyJES0vAj|CQ(8vnp8f(iMJ_*mCQ8PUxl~9bE2@Nfhm_m9^T*q#i+I-- zOBx*N@)jX`GA@+#A(h9M`inAU7L7X^q^}}+)5H__lJpGAg3`2QqL?s6kx0JGUKg1z z8Q!C!*+}^EdPjBu&5T#KBOx}EZp-##D#p8h=xS*sXr3w^A+9;|jiPr1ReS-kyq@A{cl zs=;cqJ=X;`FNVWmb`5CDnRK0|fB{AfE=@8GYh2i%QkF&Mg(+mJrS(!-xKDVvSl*CI zJel=v%gkR+Eu7ObV~94V$>74vLw1|nAbaX(jIaD5Fqj0}Ud3VHc#FgLbR3J`hC|=p z0>p2*`e*@L=Lj5vib9*BAHnX!CLfZzr&c!)cVFo2b2v|l=G0)Y4^gb=R-G_ zo0RT$H8AU1b%`v`OSKjSTU;)TT<2_9pD@SeO}v*C@Z_PD53A-l;-*nrCZd9^Muh;rhqye~PST0{f(y69iKCL`+hwNZC>`80r9~Pi>l{(k;*L7{P5d-Bj z_U`RD(i`Euzj1nd*3RT6*HhgFyINEFyMn9-+S3edt;dbs`to6Yi8=DJCh`2(dDe)X z#H~HSgt4m*E>sI?R__8$E|2Nyo!Io)XjAB*38T;d#BP&e+Hcp>WbE^8!(R69sA~)? zu4tyLdg^3!eINey^{1BoKL?gAE=6cqgU766J$H4@IrX-r>EaN3rIX!_3U#qnq+3a= zp{)J}dNA!-$WEc)$gm41$lW2bL1msvlGbpKa>~mwpbaw;D67(LW^Uf@z916Zc0t?V zUdFK3GND~69N-IhxL(U5981~Tyyak)*M>&a3MaFoBj?UFE^6|mC67gq|K*9brBqt@ zQ~cPr%5T>JCd?UVgmg+umwKVd#y9ToHu!-G`6Gt z=OVaUCVuMc!_VFj3gup9HeI2gyEX{)znikHV5T%@k^XwQ_0*qTZ&gC-ZA}mMmpx!0( z+=Ew>^J*_Aqg5(dlp!-^aq_){d&U(G9F5IX;YOb=(v_*=t<$XJ6S8&MOY0>%^?<r9S4%o5~@WIpsex9Q9^TCu}u|Z&KvnPv1<*)S}vuJGp1@7HhRZ=lhr`rRpIQt)x!U;|8pY*U@ zxko(C@PxpxTUGEX>h|UGk(UhW_*oINzmBNC^;SPG(NCq;^a)O->MPW@FDTs2qASo3 zwN{$?m0nxOQlVWK!eEqTO~5bv$M!&M?n4O8=oZ?!s=ax6$)iZYCK6>dFf4 zx{1#m+n8?_HC4^E}{ug_X&DX%qf`rt8W z4c$IHZx3W@6Kc>+YcR8T|vCYOGAqSrL{;X9lgN{(+yOh0*P~T(= zAXfTw$o!XGOe&LaffIEvJUIE^YEcFfCZ(U*+y=YPZ=8MEk@HiKtlb^sYRB}o#BIaL zrfkbh&j_%Kdfl}t%9=)a)h+U#mgLW}-ZzAKiQUF5Jm4LON9Y9SW=oxnVlnG}xIb>oZg>=+Kqf7+H8UFS* zHv>C|FB@Sj53zls53%*9J}5_OChYu-=5%?r=B*`?u}xj(7-OP=Cm#1JWw}R*^d2qM z&u=1(HB<#+#GmsTwus+XXLhZnRSUQ6R2|Q-w>E7`Rlmb5xRR4|esBKQn%TkPV_%*o z$s=LSIkEerH}Buys;hqz?DzPlB&mxH-?l5m)X>hTGs2myAK#)Y*>iH|HR9vu=94NX z9)jNMa~i-j>Mg|~1sC$jyLc{W+E0W|_1?(Gz?}Bqc+ajNWTQ%?J%1Wywm+e{YctSy zzN&RS%Y9wJwZPKK{rJ!T8X{C8N!`^n$ZpFY-`nSH__jovClkj+=8%(6p}-W2d33|8 zlA20O1yhq`rlhrIDy<;noX9sjeRKL~D>&Cp-$UDN+xM_qXne7;qs?P$+raevrFTNj zUcv*x?squ@jx=|q8J|ASc`Z!mHP5g*;LO$&)Ph+UDd|8(P=0qp3NkpY_+o$Z z+Qb|Va2^QS9wj+i3`Hc9(GEy+w+p7qHDA4}>d<&w!1%QYFmS)kG69a)JkbTK>jaF&<7wo~Ks#9RxLFmTi6SbMLyUTIoY{#YT!@Fcaz0 zqCRk?e_T?e^-j)lfb@-o=S-gr_9zFl_Kw2i+7Mkx*@S8pib9S05S#j+$IYT@m}(^F zQ)LYS$+kubeJqxRf(-?soT%5!U03RsZ0|4a5nc=Jj<)sSdL~DuhF7HUbnLRv-FA~h zZ^%h58PT_N9$>`w4w>|=vAJMp`As*wHCuQ@SLk7kdKY`!=l-X6_k3K$5tzBtZA3%b z*e?r5&aTDVep06*Q|oId74&|lK(TSXDC*~x?1~nQ9fNlW2#-Mji3Hd3bs3@!P2#(n zac{D76z{wo%09iS{!=FJhNdJ|6j6YIp4oCyK>!_YYrRy=96f z@eE*w!jV2GF;p^yLY6_HfD9lHkhd5C4al1)5lIK604f7YZlOXnwon2T$V!9|G>a%h zoFiYi=t)ijg+MkELVQ6U15RKclz_SgFauN|3(61a3>YBdfj}S{f*?I;7?=k-5dOe4 zB-+vld7?DoRke^QP=&|>J|Q9jauhyLh+sh3p=5w=qynS^asj>2CgKBx1%(4Cz*8t6 z+J-iua^xUl0eTM|Am$Je2yCzsDuK)qT&O{S5+#W!g87kX@q$DEYk(5S2NK}D*CboS zrzG{DZurL%I&Jw3SR>Z}O(0wH9gq%9Lr;+B$QIxX!UTm;1_(-M6vYUPoL<5kfD3NXQwYL$w07Pz?|b2!VGYHXt7Q05f@&K3s7bq4If;y1~pe4Wo<{H(mEC~9#8wGrA7 z9@GfyBLwIGQXnn}2i1jegzi9Lz<|U6f(jLZiPk;I55SRZkS z*FXzI11&+C(04!zl?LQNuc3W}7(f7dBk=)hAQV{)@F0aDYD6+Z3S|twfKHIU$i$X& z=$j-y^b`s~2tzI?W$}7RGH?e`jKD%kphO`es0}DA$k-wc#Nz>>O!vo zWuUxe3!s1~kYz3NNF5*;PzRJH)q!!y6Tn8L!1_J_xDbMOYV2gSN>Oeu@EbtqEP`@DR)=WqR)P_cY4u~JP)`|%hAaPJBKq^Q8GNTkB zBXAT2pn9QBfDK+Ff=UD}BnhR?AtfLj=Ac=U5Hdi$2T))VIFGyuYN7-IW6&KeN3H{3 z06vsF$b*tX(Y8vX2mlX+5iDB+${DO{Mxv|`+Tdfz9P9vY!l%Oo>ME)i>5n1+yx-PU?lu&L|53l`d}Lz6SUwjlrMY&EdeE93DN;HL+nGr&=Zgc!~u&SEocE^1`NSx zsBb_PfCQePno%<-iq_Yl0BprasCxh*K!{2KMM1F^0>~KlwD({gSPuq)-LPlEu?0Rt z@k$_3{3r%66XvQG`iRN`Ex{#l2qXrnkUc1JFbLU#a02WhXK)3m0kJ>__^ca1O@cBg zS;!eB+L8{oBErA{fUZ>upplXWXHlF`7?_2$15LpJXa=xAy@m8a6969s!4$-mRuvQn zXo5EKf)3bldoL|ulj6i3m6eMma64z-7Tk7{Yz1^OTazzjBkL?}Y=IT!>a0aw8;L_10c zAOPDD_aO?@Gx$`GfGz>5AOWo1G?=0VXoPYAi&1Tebd(^93N?bthxMV2qJi*GNT?Z= zgSZMw!q)X_T?CiGXV62$9&`MBS03LExa6P_-a{q6C{D z1@JN`glYtopv#~qY91&@!LbKUK^~|Q&`=~7Y%?La2q00BU<~Zfi6}V~3c4gk z0lK0JCCVUcs0PkM!5|g*4f+n{06mf;&@(U?WJLNy!La?@QBNeVqi9hGAQ^QZGK0_M zV?a$x9^?aXp#<;VsL}RLc*58WjsxKyu(Y z(1coqDnN`t?AsU^WH2bfKz%;W9M@lS znSbrU2;&=YpAw$af%`CDX!?OAFntWTkDkwk=fA=L!u@_}j7?v-{{aR@c%BX(Ltl#n z!x#7(R=5>_K??>wcn-z`@!-Az3}~L(;p-0Jb+DWmm@wRf$F9M!2#>MD{1(FVRDZ3X zhsS8(xl1q(z%4!uuud>wz5?Mjf#NXq!Ruj}194<90&(FvwESpY!TQ6PgRe)^Wr6z^ zf5rk~eFZYZ{Z4ost#kBVFl~%uX^i$#cx)C1^coO`zxWCK4UcWX`@s8M=$IdFFT?Xw z@E9Z9U;9G~<3JkYb^+YyhUZ|tV4!)2>0x|>$IyLI7|^_V!Y$e!u%0e#t^l{NtuSEQ z&b@@!O2K`Y|3G>eV4Y#0eE@B{PcSVQZ_j|&Fu*ukr zi|k)5ObbKfHpcBxcpmK^q%b}X(?Rotwk2#2G|z!(|3K>t4PtOV4xW>TTQo1laGwZn z(Y&B_kO2d%qYHha`GD<(p$@kq@E8`{qW5Tk`!KD!BzP~h91<{~X@j>hSkmD!Snj~L zaC-yh4TAM&2=`&TT*!C@UWeupttYgMa2%j*64(Kc!F-}=T-YAAWqT_;hL+J7o)?1K zWf+Hbbm7}fa7zG>!TLe_!G#a1!Y!K5ZfT6UXqa!bZ^6ET=B@n=%m)(g--p+;!sBSY zp!bITa^W*(aSSC*u*ba|LI6 z9*&R9DpjQ%Z{76#?}R>b91-iuO#IqR{LWfAc!x~fk!jA&y4~4^Xi7#+_4{zr&E2zV zTXNzF-gcq#Rf2+5Y+9N*nJdl7-Wzw7^- z(xb<@#oXmM+I;Wnv$-bJ2jAL-v(^y%`4v-p_(lweVC|7Sy-fLI45BZ1Q8U#NZo|6|bw}4H9YL zoWDc;K3jG7W!~P=?s@6kzCOb?!e!XH$t*eY>e1+5pGuEzGl0{^OqX ziv_Bhls5aDosjGj&a-$I>KvzQx$g(C`57W;Gs<2Of4_1NBu3X$O(6O|KE`ZqL4U%~`ti zv0Rgeo=;G_Wxx09ei?K76UL=x0+UTOpW7WO61ah+L}Nqk0!mvsd=Q1mrAQ&t>cK57 zGHG+#F+wXF!eJa8m6+d`T;pX-ml)B4%2h3LSzwRc#(>9aW$%r1)8>~r)}7}2i!9>aW= zRr;|`-J87nVqMxt-*Z_tMTJk?6f$3k;(k(=TGO!8dp#yCFtpAmr(N}ZcUM|q<>@c8 z6=R>{j+{0&yepVbS8Z@RAJrQNeeA>$8jh03Bd2h~7GklBx2nJ0-L4%Jdp*JM;5CEs zdFPZQIeYz$zT3Mh{db{2Oi`th+JcvDfTs#?U?a#V7e76DXtJB_LTsg_p*Mf+v@Ea$La~H*%_>1tS0YtPK2H| zMNQMDbWqCN53Bx(83SO5o7Gt)@gK51>#MAcKbM%#Ot`k4b4b74e#Hfk2KUMM*iQ{= zTk~`u#kCZ@jW0jc_D4^qGV8Mx_Qq$Mr@fwFwX>?NBr8*rFsr>Az={6OagME7)ahvXX6GlIl1{v{8z~`y^UwTnCWRCgH*okPT!QH01B)13djyf#80VY$ zI1lR6)>=C_{TpsMXiN+TRDaMo)jlk`%X`yPO0MVB@f;HIhju0&eQzRD8ghsX4$r{ub0^Zz z>ZKz=kht6n{b&%oGQgWqU~{N4(3k<8j!x3K2ESdSc#YB)3v(XxAjZYD<|-SRoZH7w z59cMQU3O~yIb*A;+iv%ab)E)~$oLt4xFFjpX$a-9j8t>3M8Ef$q3{(N#`bF;77f}T z3i6kP5mQuNi*{X6=q>OU0VOFXd`TPk(7)|ap@812rgZ-U^D{W%k9Kph! zt2MFrdIUfJ68)9J<`!x#`FQFhqe|DpwnA}m_vMFteRCLJDVjLS$T67bzDcKg32u@S zx;kB!`GLQ=rN6HKkk#6EOXCln?`uELpv6cN=2}%5|jM9r*ZvekYR-MJZ zG8_&|t4L^%2$Cy@eIxbLal;m=Q`9b?0eGWs`&LfI32+>`@XL>XL@K1s9}A2X}jq7Pvu^tu(QViXQu(SJ@`E1gUc za?H48m?_mcfyI?qffEoolI!$~P2=&75KpMA;AQG9Kj}g8(9`U-{eF7dHuIMOBVyY- z5*zNG^k1C~SaNb^&l{|hi!f@^200xW$kZuByK%=~W&e8BK*e-J=;6`;(SZ|u1K zGM8gd+S%SeS#+Yq3g6XH#62^cJ_{miX9fe&*0r&=fUTg-FynNo1Ga?0(h|X7;T6ekeZ5;#ySHYkL)1dDHOZlFdC6 zneFL&hxbyX=MpP2DY~WBc8Yp}Mn{-5`8a!=i zX*|r44ukb<`k1B5H^w&!Q(4VL=)Vf2>d9srUCt@;lhv~M>Dou$5iGaJzmxgf{%A}5ciUs+T#%%|`a@aafXc_@D@&J|pG9gx zbVRy~Ma;D;8WeUXbuRbXF7f_Z{AcOK`#<;hd}L|y;J@4(O``pR&h-d`i&mvj1N&y# zVD%e}##t({;h&;E0`Wf|`%QZZr-*;Cw0?K7=wIG0o&x(X_+4^hLi?}7|3$yu2)+2S(;qfk zY8I|?+uaS+uM{eN6%(Iq@+^OxBQ{A#B~F)kwm8`K?}Y#Q%KE<#{}=e&#s2UG%Xsh` zu%pt!vB4`Kg|nfsSdr;TD1*P1p&{DfNH^|h>%wCIrV|LlD~TgCqG6m8*$tNwlLzr^pN_s0O@ zqtWuWUk$`8vOM69ReFJ2JIy0qAVrbC|8>lop}g+65^|MMi|f1Uad z`#Iz2{Sj#4;nyol{Xz9wo0W*LD3L7PXfnu(#1s{;bT_TU+hOzI=INhR|9nU9|NrNM z?HBvQpFQxRsp3n#xYTN~wWpdG!YrGm*fdLc@}YM%ozGL$>z;E7yT(6v{?ogV-_^p# z-TdPG`TO*Lf@7ic-KyV(`Y~$0jTV(Gw1r&nH)0#GVQxrA;l({QQrjC0Ddc^7>qGqC z3A(sGLOVUiC9+5sat#+sA}dNajuKbMB`2 zmJItGSV$lGJITNHcZVM>{r_lz`{HQ*=inDzkmf~3>z&WPPkt?sc~7-{&Gcx(`9x`4 zqL<=*Vh}?ZU)taIM?cW;?_>WR&T>)j_yqf2T!sjFq{J+c=#?__))>(=^Gk?46S`Gw zYGQnw#k`gdTjB4tnIkVw4-BmH3jePoi%m{z{#kitt{dd%y+yCCPBZ$>Z+)z{{h~B; z7MLU(gd=m`fU!uMs=R5O%fitTGiZM#;OXy`ar39=M~g+~XGePhZGK+oTiNDMPktA* zoo;g+3AUXctqht+4PG-FHXn!U*0$d(ZBNf1RO+669}hU+nr=Hk96k3tU49gB{{2Jn zS@+w3^T@r)$rY85iOJ=2fAD-awC#K`wC(Ijx{Zi{n@oH zHC^lVLFx1F8sphdPrk>RKRuj|4e(1Y&f79$KiZGoARqLRy0(48JUIyWz#Q+8(FJ+fXAIZc-j{BH2b=6pHj{Ol-2TBxmIU?!!O=T?B5 zx0^5S&e8ifW76kM{wXP&yPvasma4>tKE?WE0GI>jn**m$X*joCO{FZisWb~)5=K># zq<1Q*j?~x4OK+NnkIN!44D`W#M4d{p@~%JKVE5I!8oGjHj0oWT>{vSBu!b=|bfwSs zaLJ`oC9W-uQu=)VfO%_JFUW zlFh1bQ>cQ+F*vy*L7MutrAS^6VTIh2xCn|q_0jYms<^U7iObg21~;jHu0KJ&(Ecr2 zu6fBZsE$(#*B8Iw$cZ)=CvE=Q?r|^0ZGpKEioUp9Y^78`+@z8jLTjS+n*yj3(>r>F zUU%>T&3={Dx-QC6a<$-_m*Vi79uBwHV59-(`#T1#4Bu34a&V-sWKo#ksd{kQJ$`Q7 z_GkzZqAktuBvB6BdbLLSSROH&`IaL|cq+W;bvg8-C4nB&ImFy(30x6TmmTOvj2Z>`fw98fY>+x!h=}}ySV~S*dnGR0etuIVd1z7fxLd$?d!;6G4 z<2RVPbG{eU;>)`9UgG{8t4`itwjCZks{6HnGj_H-PcdH4_13K* zTP#yHz8$A`b@54jwwX^_jCao-=Plo4tzFfq9{!|SWx+^rsN<)2K$zaAE8vm1>Ee$V z{xafxoguTQ4jfJ|&gLf2<2v&9bvYD`-lV%cP4telkuk>H);+6rkR@!wTiia^qV{g1 z%}Y%?Fr$8?_~EZ(zIAByFfP*6!97a=gOZGDm~o24(m!i`u)KyPJjUsEV2P@i-I(E! zY=H}T<+Aq(UP4cv( z%TU>@+IXJDx+oJc%^=xLV(L>={@pN*v1@}X znoD%}CS-D01@DijbV}299*z}h4qX$h9IG;HGj9oQqVZhGe!TTzFU9uZI6f=2T)@aR z+EP=ygPL{Trmj1ByAW|OPQ)a2vKO6+WiI~{_0T}Bg~jmaxbZ7_wjSIq56U}t(UK15 zy8mu5Tcb0xRO@P#OcEIS0AyJhTB^Mjlf)5`(9obGl}&skLe!b^Mt{t=1NMZPe&J3R z%VPQ!FFR9Ad%L}33vmuSZ0mNkD|{vD+yq@(udojaL0D$VgZ8wS_5@0Bj%}#qBFaa~ z@GraSl@yk{Sy{J!75bw1K+}1qQ%0RE@s2vSU=d$DOOZ^1j$cGx#w9a#ghq-^P?+mg zc8UI!Mw(9{3hGOmaic7~_SS?Rt3!(S#Xl^Env`dFW|{SIvySb%B#bhs^iA&OK8OyU zXY!WlUyktp0IR`+BqQVPgwHGcYK}0I8En3y_n49I(Q^9<7P-8i;#-muud3nwj*zI3 zUF`FBHnY@wTatkl?dU(`9TCft=0_sYV1Uvv!kfJJYw4%qVW*k;qmY(iKfM@?pw-}t zj4?dzjK|blm4Oi{eLSSiNmJ1ujY0f5z2EO#2`Dk8?9#K#=iwlDatrgBk4-X%C|$1_NpQ#pWys5@7wJ$giqyJFdbfCM%O;F+_mouVjehP19-W%J ztwS%MH#TN>U>9Oq+|?0KSI5&3w8n{d^aa2Zrw6s1$zEDbUD}UhPrlE(WTdG4_)1w> zqx+TZ07HD!J9hjNW&8(UD`w2bf#f%H3?!*lVK*0}GN!b#+%drKD&>8L`s$|1&7Z`+ zIhHFQ%Bw%)^npqW!#HOZ)lH+`T=A*c)EKVWRFGGvzx&m#l~(~nW`EvH-SlHGl5j^L zFv5$iXwTQhwC0fwTJnsA`k8!>#cd7!$N4?Hs5JPOM|FMVnP}Oj6z2;}K6BdWMcOai zvY6Lzc>cr8NZ{M!=daYurn)FUncjV%-;gR_SE}}<)RQ!tLN51*Y}+FefxHs4L!uX) zI5oX$iu37l1Ea>o5sGSx32CGT_Z8{xo{(py$FbkK)^3yGNvyHNxo}tD4gNB47eilG z|DC(T9lzZhF?3I(Ih0iWDCR9UeLikF^4mX{Pa~ashEE$kK^ZT1qee~9r3(Rc=*Yfu zEyTy)(;QZ9dsiCuC_V1z#7kcIl)Q|*)&9<%-a=JjP)6kU4}%6#`IHP_Ci%42bu$H> zrTag6eIDB2vs5^YTIe}iwmhtnlE#Z>TSG^?`=Zhz9+EP?&rXV{)1~CA^rY^U&R5JK z2CNpe0|~^}q>MsuR^83CWshTV#lmG&esdNz)P|ho09G_#x);|r=;g^Hwv9ri79MyM z@9bW^P1?-;Bav99z_suxUv_EJJ8iv>5OIMCmGA-cUBMb%YT=^0?G%8SzK(2VR}48`PoR$52L zSQ^`eeCvywu42uiOU8IRly=bR(#wI&5Zb^h_7>}O;i0}tKQ2~>vsvn=4r7(#*;&R! zIu};wm5DlV^^6&iOrNx9N~l*j*423+(ZlmVyT|_9qB{rqLcOAEgoakq=-UtWOUv_0 zWJ>ChEJf?JDfq*H+ZS>I*Lye;6%XH3kl!LVjB!2Uq2VfeUPL1h)YE`sSomZrk$=zK zye*RBWrVNAB4z6R!m36ArVlV)>T9u3zn$~~Z~6-B%Y(PQCBhvcZ{}95aI^|DZqU|v zd|f}DgSueLUY8H#Rv2IUaZ8`W&+_JjZ`BEzAvO^`znNSKK)tAUIxUWoF&d?2QX-nX;Hr=28XTbmBcP|@0KCz-wKp%A_-Xz~Jo4;vh7%2G$F1OlF?!kk-us!zjDsNx&X4k>PE!&)l}DCz<6_?(%Rd~=w0)2@ zHkpm8su5U55DMySOn*a(%ZW%RY+tQyaQf+ZM@Y_=54WqQOzW`a(9gpKSC%Fmm15xk zPU_{u8(T!&;bH{zH!1t#j%#0Hn5B#=J-9ni;=MBaF;6kk=!uqIh;5(|Ye!Mg-k$4P z?(VUDf8B7QPabZh2r-&}z|>FPNU=89a3k7{ zF?Zbrj{d>CaPuRU7yCHFJW~`ibWWsu`!85reOX_uUdwPE zAhu^ttXWgy`bBV?G*~_B;fTpcgL=DF^9NeoK1CuqL4!>Frz-rs9JVj@!?$;njxNO) zB@70IHZj&VF5ZTZZTs;so9-f@kiBdPQ>(KL2_+0 z1z{$7BxgE%27Y@Is*4ZCH;Hv$D5Yg^knpM&$8pXCJCN?NlglQ`%A`ensPVCx9T5pl z5K%JIO%`Zad#$WC;H(QvHu5R_s4<%*;;K(={`UByQ+Zcs?DKi@NVx>B0xaIR;V%^{ zuOM)C)?s^Me|{P--nQ9Gl-&Ha*USpSO0#TBk|4s!Ud6yoVKrU1@DnT@@F>m+E~f z=^cV?m2Y~e@Z~tZFRr^pCaSs$tJKU)c$G)n>gALL_T3x5_h1#|w7&FuSIOV#6l0U+ z&ZV&`Q$S|qf5nhweemmz@EX+qj<}&=OVE7;Z?c z6e#QRGX?SFaUYf+B!oU5Y4l&7GbeMJqKgj>FHagNTD>)9?ax;`^IMYeARku4GJX7> zfMF!p{fJ`M7+Fyhg9wkGPVWO^wrO4khdq29);XGrkw@Kv>d_DAJMv|f1+bOpqkBSD zp6V%#>tg+Ml?;E_lpxIUL#$357TrWQxkHMgpB$fc#W3E9zwt(;ycLPFcB(R4EtE-V zkszzTotQSDO>H!z=|Jic&k@F7YvzX??6#INvBAe(s7Y=l*!lwN=hRc}f=Dy(EAKGEfLU%kd1>auC zUXv8N$0hDO|Ci{cOHRw_`+r2=eDC-u$v3g}T}%EW**8yfv1fvGWRu<4Yd;qiM?bGP z97NllG~S8QLY#%-_NTWfl&-&<0g>|waViE{_8%WQs$HU!1uO)!g zex1U2x79=6k?} zqiei!3#Ct7T7m*nPOU!rW@Y%4@x5hN8%P+Z;?z~7c;tC2OrG38Ht}7Z$mb;$OMmYl zV|g4&`AW4&2X`mw679sg+0Wfp86sEm%t$Wh6~}KKQY##?PHs(oy+s{q1wcK+X&+(@ zHY#fjIoOT`6q<^$%wFioYH=Ek^05RtWO1EQ4Hss{bJ9F4t{U~PgUwz3sGv9ajnbNu z`2*7tu@M}AXYRTm9#tar0Xd`w6ACSsa1lbL$mVL5-JeG@ggi z+*VTMTH5#gSf+OUAV(FW>H|+!#xpjn+4`FDc+R?oJO`rXmc~{$_F_TDfX{|Zv8MgN zD`M8jViDGK?|9Q!?D5G^Mqyo&+)FXHtFoq6_;9>0{GiMUGwWyhMLj8zB&%QRR_flB zBUT|V=WG;zniNGf`Hz5K`1#2UV(2O}A2Z}XfC?xyJG>r4C)UyLpA7m)>g8o@k*bo( zb=az9{vwg}n@%Ub5S`2@Rhq!>CAgvjr#pQs%O-7C{~j|-SaeqUyZ###X@NX>eG=r8 zRu4+4CmJbLhm8ox*=kFC@`x#{vBK`9?z0l&*=P@39C!5b71BmtYob5dYWe0o(0*@Z zn>hHpmp?`X?e~`6oM{~7vZ6Jt#zss_rqMl24@-rT<*j_OdEc^!ms{!H$}Hfog>*i% z{9;uhHL~I;E7csQ?H^kFBlvb{seA4kmtKpvXxUNfzsPN6K;?S6IN;s8ay4=>>!7Su zckybKkEvzNj9ZA_ZOY7!NS6q10;v^4D%TKC7L60WJT(McZNZsK_kr5+)s@;-s>%5} zl!i=CZtC23sKQhKQ#YM-oD}*At$O&nDs&7+=^Nu?PDd)=l)Gq5f%0@{uR^DhEd^g zv|Id%cK&~fc2_vsdCMMg5&RYH-~K(?c@2+P2G;Nkb?UjGopF{Y>0}W-YvER>RNn~o z{g{tZG#xb9H>%_fK3N`5o~&5jtOV&~tFScDp?+Lt7j?z?Xouv%2|g7vg!N&zF5Do`v+2gj~k}!nfhX>erpZgVfPRB zP%2u(-+brzgggsY%?{$eoltJT^}*K~ZtP+AB~}CZ$o!oAU=`e+!A$8Sru~_-F<|hN zgkJ7f=h+*?>Xh4S=5lS>^3wge9IDI%XV()@ec+|n5Uc9jg@+t?*HyVy5*HckFAXcs zN7yBBD<-NK_`5CF?V8?^Nh@E-(Ob^*(r!`9 zxuxk?;|S%0lFANn89vF52gLXG)No6rS_8vuZ!1BsGIB*zCkkKMx|(5DeOQL8!$)%tu7hAW&j>o#MR!d3 zt{@a__ZrHdkM+AAA9DXta{LqXj(^3xU(Q9$A3Xb?n8&8Fe4#Ox?{$`rPVvme^5gr7 zyr#hMZGY9Sh=*LilA~E790InVMU*^IjPmL$uQ6QrVdl=+o{4EhBO4OT#mY%vMW`uc zwKk2Iiw#w@r_(*32HA}cgguPOHL+Ix`X}DqPAg=X?jFF!O)J?XL*nC6RaH{Gf%u-6 zN5Wl_yP`a)d3BVu@>cY64C^0pNE?P$<=!;i&uA06sBKw|O$Z9UUh|u`pLYZ zTW1rus8_%xyX4YQnRkE1yIpeSQ5~b$)T!$0c$e;4C04Y3+8TUuOTm`sK0}3bgg8UmMZ6D}N{x`0E?k?Z(y0#0#7tsZGW8QT{d-MMVoapM{H_`7aF5u3aezfH`$+f>Su+?9wUcWm zmyw*Rpz}M8;cLQQHK(h%`#0#uvxxF4@o}_%F7y)eH;gYvy$Xny%UwXV2bMNDqT`>J zV+mJ3d}LP$kfYS@ee$eeiW}#TZd85ezb9}1iFha9`Pa=G-+({aZ!J7_KP~G8S~Vxc zv@IVfr#d&)aEcU3WxOUZXJtPVtQf%&{{@rnOs#@sApNLxXsP;fzSQcY^v+6Iy3_l~ ztgd>XxE;q~w{tD7l*Rz`oZ2FR)3#TJkb*Zq+-vBnEL%8Vo>Cr*+O^K|j8$~JE2XjH zRa|)cEeV7jY7J)__A_Da}&p4Ds) zqxnXum83K#Lzvd{BQx?4AAQcN@rb2#XYFyI>sd9P=V3>!c5vLoiCx!8h4oKOCnB-5 zFR-~Xb2KpQ(`w03?@SFW&XJ$D0j=7s)NXmoC9hHT_;zuMgVWM;9{gV(neo z@8^&BliU=~U;=P0U;bR*(g*UpwPPh7#-BG5_Ha(l(;8jUKKoPB;{BtfO(4KfNyE$p6xJ29Gz{r5P~0Ti5jfwd9w> ztL4v0QxMD&5j1#od$CN);T0LZT)q8l;ae&S}P#t}HaNEylR z^5V$3{Ny6TB}A6q04{2IdU3dxk4>q9Yxx-ci(39Q6}pypt^XtVumdS7L75EB>k53u zce=!iQVL5|xWmgA>^}b~gtz^7=oe{vdhp)=LMb63WSU=qP`%m)gX*IcFa^#6h{Aw_K0ytgAk& z&TfMj<)e$3d$$&dH!40(_G@78cz?6{ef6%)KVEMI%FSD>OyN&fB$4O#0 zHvqo?jg+}BYR9hG3RcJVPVDDXc&M?2-Qm(OyDxEglr074a_%IE#*lcec0>3aUBdf3 z)5{YFi8Rn9yxINcGuorHbxcy(bk9OKA92R6WAej_ncinFbf4|?Nw~PZnWC8E8BK&s zfyInj%%ug>#2?6NwRo1Gk%jsHd8pQV`y8RZnIH%zHoqZ!mucYsmnH;j~LGl7aePFTp^M3?6AI*~6UpcKc zrO?$h<$1?S|2DduOXR#Cv~hPi626n;$W+!@48QcK11@5Jr)GShO2qfrGUaNKkR0@i zdOoHWA97b1^BtzwMh-53OW^hPop26&VWL~Jc7venAG@RL_f8Hsj^hh&ABilz*w~1-SN_J>Seq<jpNiuFzWa_|X5PbKtK#b`o9F z@`-;GGh{}_+HVZ9YtiLeMbA{iYrcP!?~a5bnBG{0@Y$_sWx9K9JhxG)gEF%qM~HQr zd)~#4Gq5<=TCi52@Plt`IJ%4>Gom3RA~g6@#!80s>zaQT%+CHe4}VnUs&y;GHqVGv z#)^=yHhOV?TQ95}A%4$-H@HV~W;j9!zL94~r*pY@59sxu@?Fa+bHPr}M5$5&^@SA? z8q_1%J6t;Q`%U(zpLvLXP3W!-UR(-g^RKTzg~C0f3tTt6;YfGoi9tuY?grzM9j+|X zJ@NX>MPVkJj4O6}0li66Gxa+ZuuIEZt<;XD{8h-Y(z7(w?8?CfJzUBd&28ad7#+TI zF$^gAKI`Kc5u-f^$9g&|ai|TJ;=P~yG5YP_{kN&nCA>FV?Tr~RiV}>lpCvw(HB#x?PIJK{zy!_(^J;1-kD*!hz@mNL(Y8cl(cr_3)d}c!b9|SvJO?#Z!I_AgRPg#m)_oD?Ix;?%2v5r%toHQi0#&LqU-M1HT z^>dn9g3z&xj&@qj4!jp=1TN!g3^^kHQO4uy*E+2;gDf#(r|4k zxpRQ=(lBLL%{O7iEpimZ2r70R*a##P0a`(#Sy`6|95RtmMi(~af6M8i4qiqyJ8l!= z+RXcn{T2p!QBSLt$(l=<80rb!J3aqzIep$JjmXb!XD3f+v=!TpKRj_E_w(T$W35u0 z#fN!&67*aeVfIPyudwU)CB{+<-AP>EBDBY6p;VbsDto*bHmjt9k!$8^b}yM{LS*9| zem?iB^7NO@zl;l*j290CAF`Mp9o)e^zgo!7yg8qV5wW_FU#hLA_deYVi#tK%eJR=J z?C0wChS&7gyG5>?e_o9$nciHg5D*76{G+PIIxRvU3(LLh@Y*QX3%?Uqp!!KTFTYT@ z!TzSz^li7nAKGB9r_5z>6>Z#Y{X|mP%->-C&AUha*cp zZeC;3n`d41^}G{{7U37I2vbq1Zw6zew@IP%TPT(|y67RdVf4{$mD5l8dtjc2{rb1Scbc)-FCz+IZc1o2#?woPF z2Zj-MTkrVa=wPGN@unu|R(kxsx^w0gYo3{;e8k;1LSFB}pU5YDLhumpVIF!i?lj`rbyc1wFzLp!QTM0=G)8`4(NUX|nN z;^I}QkydM6|H5UW|rv{8iHshaiXS-%kRExH+#2g$6c4I`5~ zWjSAz9~V3xbEFw~W+bj58zE;qCpr*Tyke|so@W+$xD{&C``>Ycb$<-3TauV5s_;yE)&_7cSF@I*L>Q>Bx{}g{w0Rf{z|fJ z=v|kE$W+uDX2gd%=}cI=XG*Vzgt#Om6TU8s>nvXyX((o7G2vOY*xL0eRhluzt2Y=F zY~R+Pj5Hb78&-coa!J%TD|$3eh@E-wy-_($``d?f%_ovp^LF#9Z8G!?j#&ah^zB5c zSqp!Z-E&;ARoJTu5af-nFzO zq$O&HPtV_Fm*_|Bx`Rk>J+ErTpiDF#jnnaYbZWjJ>|46tlAE-H_$^6dkgy<@4sVzD@JJ`|QPY zg8ej@aXA;07`UYM!+W>f?RNHO?Klfq~RqWICT=yyICa+S?_ zrcrVUE24NtQFhv&t0w^!FO8b4ZsseW$$0o;X8p%QN6hA%f~%rWMB@5K z$rY&u-PVmsD=JRKoSWFLRgtdlT~`wD2RYJcp^2~7BPstYtHZ@&XQ;1>3ZaB?(z0TV zr^@S9^fWbkCM+6~2tC&Rmdh~8YNEMpl{j5cme5@Nx<;vCa@wk))lng*_Xk}Y7W&%A z(o)+NIfC-bo4G~4+*gY%3 zCZ{a52y37BSSuwxV*fg$;<)A&{yV0-a~Y{zC0`DgF`FBh8OvoHus&#M6W<&h0|d-X zG%QebT@zKf;8I_MzO{Z;EO8ZbkDqa&XvTe76~(=(_cv~v3^HC~0x4!E-ah~?a*SLu zixwVico=&4%uBv5`2LFCLL>o}XrePRTU)haG6=}XR@ zxj59Oc%`++`F@qmk9R%%L3gXHefP@b=E>uryLEoJa(vDVH&!w~>m#gZorg9qiswm! z=C<0})zr7^#Vp5bVKool&ba_5TGmy6eC!sH za~W2Q-Kcz9RmQ~Ad~2iadR9){k@t08rQA|kpRX&wCr5j-rFd2(>Dzy8FEE)<$!ZGq znmf%6YoA?w5JWE`H=d%C(`Wue0C%Zx!V6MsE#;*4Ij%L1oaY zc?Vw&$zPlTRX=S#zi;c7tRtop9GJpMkWD!7DE50@9{%Tr8fL~;@l@|P<5Sp>{DpUG zF^7_cJS{mz`2*Qyhn`L+)i$q_?K-0N?qEe>tz zZ`X4uF>aD__{=27z=O$KE3iukHO2o(s~&PF$(WQb^V&#E;&f~oPnY~D=xNn7@wpGqz1MRgS!!Hw_=i8;N+A6tYx@)1pF_dRujpR> ztdw#tM9se|`Vi%zbD{$)dhWArDp&VQSAS4);LO_LT(P<1&al$&3@bf)Sn1fP((~mq z8GZd~2Od`4!sEI15!R&OVo!71W{%|Oe47>Oynwora<{Vhpu?x7Vy2{8qo~5}uf|<{ zbM|nh!s1w)qg+z*CxhvB)66$d_P~d*cWM>Gv?r;z{?i=CUuLMq1qd@Vq7b_yi3<`Co{5e?OIPpb_OP0S`x4fD4{QgK<=_SZEGW(_GS4c&t zVqcEk6&ZE+>vfjrj$`b74wKA5(o=V_u1(CGa8)i5w6}lnVm#WoxEZ28k2{*>%KK*T#K<?w}3dKfyKamD9gOhrf>JC7Ki_cbeDs zVcG$uYL8ELeH)ZxX}Yz4j`>TuJll;ub(hCJ&IMQ!2)^#{9h_-bFqn5k-YoZETh+S0 zSlbtqrVZ3Dae2Kl=`O0c&$u9d)?j_dgW44V3L#>#iL(ak_nfs?Zdyj(!_7K3dn5bP z=bJwit#47fs-!Yz>u!9*AA7~?Gy;{9iM9aRzc+g?9Sn7PANb3Vp}aWp4Ah{H80xY$ z9I|QN;(^^YEvhN(2Pfls^tC;6b|mm5u43rY(v^k`I$<$K8P@gL0vTrimFBDBWc0s4I&0|nk|0%61 zc59@ROZ0g__`lVZ5_i^Cg8vU{#=O18e%<;r5{p~Rp|++Qk}+rAUcW{v@+fHQ0Th&o~JB*Y_;-|1CuPBE{_v{>AwR7z}gK_tDN+o*!a zJ*xD`P#< zjdmv=%+GR|Hm_$zR7iF4)_dSzF)b4xQV7+u#Ef(&Y z{&Jw)>(KrymnYBdnD<&!YFR_Pj|K6G?YXJ1PfuMxV|cWK&n@!(u@t-*ZS8qiG0IiFjU*PQ|NIy0ooKl6K|AnTkuT3AS@2R@}=lh5P;M{SyPz z!Q%6zT5Qen)PZd9sV=-VVCRApp0Yn)z<9W8l6iJ(fRpy4@b{ZmD=c$Zoz3%`(fd+6 z#4LaI!l@U-hdg(*efYFg$5wi#PUnva^K443h?m~f$Rn>0k+;$ol06)Q*nVW!E&TT= z$KmtG*D2|{QO*j%rfCzXJ1k;G*MiGGokl;8Kr=o~R zECNg*Dh6Q;;!Ma;fC>a502i1l5{&>C2&RHlDlQU^02v6Tqf`iIh{Pkn20~Djjx*@O z0l@-r#;QIR5G+6kLKzrB!%*RXU;#V?TOd$l;ecQPJ`e`eaR`)IC{I`b5QO0j3`aml zLeCsUh>qbX5v%awC_*4Zm_`-l?AOx^MP#h8=H7Y;|bR851$`29gCyVXu%<*#7-Nxp)x&@GZ8B8h} z20#vfp^`D24~{gr*^T22-i!Xlog?>+-tPw9nD=8kd3$-WodP)CUQAC;Ab5%0&57yd z?dK_Q;sQ7Ykpa5_<`9AdUV+T`%|QAW4me&uTLK7Y%;AWc&feQbV`8~L7#Y-Z%p>T= zAQz0rm-GMH=N2D9fP9a`@ezIrK@qKL)T3iSfEV*WL)8T{&B>h!epdp>eI!m1hv-Ov zM4?dvY`!F@9cpmV)Fjlo;eNxXe50Gm`p&x#QwvN z{Qpla&}D~5*f6yKj^lm(hFK^BMu_cagjqi|AIE~6Z2M>2jc@8=kb@k0@DDY z5@i-h+n?>>!XyMR{Kh 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/test_basalt_pack.py b/tests/contract/test_basalt_pack.py new file mode 100644 index 00000000..9bc77f63 --- /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()) + 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()) + 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()) + 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/third_party/NOTICE b/third_party/NOTICE index ffc40f5d..4878fd86 100644 --- a/third_party/NOTICE +++ b/third_party/NOTICE @@ -92,6 +92,14 @@ Format: `` — adapted from / copied from `` `` @ `tests/contract/test_gguf_formats.py` compiles basalt's references only from a checkout the user points `BASALT_SRC` at; nothing of basalt is vendored. +## 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 + weights are Qwen's under the Qwen Community License 1.0 (quantized by ISTA DASLab); the licence text is in the pack's + `meta` section. + ## Original - `probes/` — original to this repository. From 31514d83c68590d54e42c645004f9e48d0283ca6 Mon Sep 17 00:00:00 2001 From: Lance Woodson <65194841+woodsonl@users.noreply.github.com> Date: Thu, 15 Oct 2026 20:15:04 -0500 Subject: [PATCH 04/74] Register F32 and F16 as GGUF formats The port needs one registered format for each ggml type the Q2_0 pack uses. F32 (292 tensors in the pack) and F16 (one) were decoded by a dtype view outside the registry. They are now one-value block formats, f32 and f16, so ggml_dequantize sends every type through FORMATS. Registering "f32" changes no checkpoint path. pack_plan.bind_formats rewrites a checkpoint's "f32" to "bf16" before it resolves a format, and dequant.py and pack_plan.py skip "f32" groups by name. The synthetic F16 values now get the fp16 edge cases and stay finite, as the block scales do: random halves include NaNs, and a hardware conversion may quiet their bits. gguf.py also carries the ggml authors' MIT notice, since it copies the kvalues_iq4nl table. --- monolith/formats/__init__.py | 5 +++-- monolith/formats/gguf.py | 26 ++++++++++++++++++-------- tests/contract/test_gguf_formats.py | 11 +++++------ 3 files changed, 26 insertions(+), 16 deletions(-) diff --git a/monolith/formats/__init__.py b/monolith/formats/__init__.py index 9152fbfc..73c77530 100644 --- a/monolith/formats/__init__.py +++ b/monolith/formats/__init__.py @@ -1,8 +1,9 @@ """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``, -``int4_affine`` (the MLX / AWQ / GPTQ 4-bit groups) and the ggml block formats of GGUF files (``gguf``: ``q2_0``, -``q4_0``, ``q5_0``, ``q8_0``, ``q3_k`` … ``q6_k``, ``iq4_nl``, ``iq4_xs``; unpack and oracle only so far).""" +``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 diff --git a/monolith/formats/gguf.py b/monolith/formats/gguf.py index 59c5ce7c..c0fa039e 100644 --- a/monolith/formats/gguf.py +++ b/monolith/formats/gguf.py @@ -1,3 +1,5 @@ +# 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 @@ -13,11 +15,10 @@ 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``): 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 element types with an exact decode and no plugin: in a pack they -are norms, biases and convolution taps (auxiliary tensors, never a GEMV slab), and ``"f32"`` already names the -non-plugin float32 checkpoint dtype (checkpoint.py, pack_plan.py). +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. """ @@ -42,7 +43,6 @@ 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), } -ELEMENT_TYPES = {0: " np.ndarr 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") - if type_id in ELEMENT_TYPES: - return raw.view(ELEMENT_TYPES[type_id]).astype(np.float32).reshape(n, k) name = GGML_TYPES[type_id][0] fmt = FORMATS.get(name) weight = raw.view("> 2 (j % 4)) & 3) − 1, times d: the codes {0, 1, 2, 3} are {−1, 0, +1, +2}.""" diff --git a/tests/contract/test_gguf_formats.py b/tests/contract/test_gguf_formats.py index 408cc504..2606e4b1 100644 --- a/tests/contract/test_gguf_formats.py +++ b/tests/contract/test_gguf_formats.py @@ -17,13 +17,13 @@ from monolith.formats.gguf import GGML_TYPES, ggml_dequantize, ggml_row_bytes from tests.contract import gguf_reference as ref -HALVES = {42: [0], 2: [0], 6: [0], 8: [0], 11: [108], 12: [0, 2], 13: [0, 2], 14: [208], 20: [0], 23: [0]} # fp16 fields +HALVES = {1: [0], 42: [0], 2: [0], 6: [0], 8: [0], 11: [108], 12: [0, 2], 13: [0, 2], 14: [208], 20: [0], 23: [0]} # fp16 fields EDGES = np.array([0x0000, 0x8000, 0x0001, 0x03FF, 0x0400, 0x7BFF, 0xFBFF, 0x3C00, 0xBC00], np.uint16) # ±0, subnormals, normal min / max, ±1 def synthetic(type_id, n, nb, seed): - """``n`` rows of ``nb`` random blocks: every code and scale pattern, with the fp16 scales kept finite (an Inf or - NaN scale decodes to an implementation's NaN, not to a value) and the edge cases on the first blocks.""" + """``n`` rows of ``nb`` random blocks: every code and scale pattern, with the fp16 scales (and F16 values) kept + finite (an Inf or NaN decodes to an implementation's NaN, not to a value) and the edge cases on the first blocks.""" _, block, size = GGML_TYPES[type_id] raw = np.random.default_rng(seed).integers(0, 256, size=(n * nb, size), dtype=np.uint8) for at in HALVES.get(type_id, ()): @@ -38,10 +38,9 @@ def test_type_table_and_plugins(): assert GGML_TYPES[42] == ("q2_0", 64, 18) and FORMATS.get("q2_0").type_id == 42 # ggml.h: GGML_TYPE_Q2_0 = 42 for type_id, (name, block, size) in GGML_TYPES.items(): assert (block, size) == ref.SIZES[type_id], name - if name not in ("f32", "f16", "bf16"): - fmt = FORMATS.get(name) + fmt = FORMATS.get(name) # every type has a format plugin + if name != "bf16": # bf16: the existing [N, K] plugin assert fmt.type_id == type_id and fmt.layout.itemsize == size and fmt.bytes_per_weight == size / block - assert "f32" not in FORMATS and "f16" not in FORMATS # element types, no plugin assert ggml_row_bytes(13, 2560) == 1760 and ggml_row_bytes(42, 2560) == 720 with pytest.raises(ValueError): ggml_row_bytes(12, 100) # not whole blocks From f7d1c06a021cfb919dfe39f877d395d023b1a3fa Mon Sep 17 00:00:00 2001 From: Lance Woodson <65194841+woodsonl@users.noreply.github.com> Date: Thu, 15 Oct 2026 20:15:13 -0500 Subject: [PATCH 05/74] Record basalt's and Qwen's licences for the reader and the fixture basalt_reader.py takes its layout constants and header structs from basalt's tools/model_file.py, so it now carries basalt's MIT notice and an adapted-from line, and third_party/BASALT-LICENSE holds the licence. The fixture holds a few hundred rows of the pack's weights. The pack's meta section names the Qwen Community License 1.0, whose first condition asks every copy to keep its notice, so third_party/QWEN-COMMUNITY-LICENSE holds it: basalt's copy, identical to the text in meta. NOTICE also records gguf-py's own copyright line. The reader's docstring now lists every check where it is stricter than basalt. abbe033's message said basalt refuses a dense.index or mtp/dense.index row with extra fields. basalt's sscanf and istream parsers accept those rows; only this reader refuses them. --- monolith/formats/basalt_reader.py | 20 ++++++++++++++++---- third_party/BASALT-LICENSE | 21 +++++++++++++++++++++ third_party/NOTICE | 22 ++++++++++++---------- third_party/QWEN-COMMUNITY-LICENSE | 16 ++++++++++++++++ 4 files changed, 65 insertions(+), 14 deletions(-) create mode 100644 third_party/BASALT-LICENSE create mode 100644 third_party/QWEN-COMMUNITY-LICENSE diff --git a/monolith/formats/basalt_reader.py b/monolith/formats/basalt_reader.py index f02b2944..e6925cf4 100644 --- a/monolith/formats/basalt_reader.py +++ b/monolith/formats/basalt_reader.py @@ -1,8 +1,17 @@ +# 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/mtp.cpp) and -a few stricter ones: a section named twice, a ``dense.index`` whose header miscounts its rows, an ``mtp/dense.index`` -size that disagrees with its kind and shape. +readers make (src/core/model_file.cpp, src/core/weights.cpp, src/kernels/cpu/expert_layout.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`` 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 @@ -24,6 +33,9 @@ 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 @@ -91,7 +103,7 @@ def in_gguf(self) -> bool: def parse_dense_index(text: str) -> DenseIndex: - """``dense.index`` v3. A row that is not exactly 19 fields is refused, as basalt refuses it: a misparsed row is a + """``dense.index`` v3. 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.""" version = header = None rows: List[DenseRow] = [] 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/NOTICE b/third_party/NOTICE index 4878fd86..75fac725 100644 --- a/third_party/NOTICE +++ b/third_party/NOTICE @@ -77,28 +77,30 @@ Format: `` — adapted from / copied from `` `` @ - `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`. License: `third_party/GGML-LICENSE`. + 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`. + `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. ## basalt (jesdga95/basalt @ `b4c63b55754637f4c72ad53a0f791d425f71eb36`, MIT) -- `monolith/formats/basalt_reader.py` — reads the `.basalt` layout of `include/basalt/core/model_format.hpp` and - `tools/model_file.py`, with the checks of `src/core/model_file.cpp`, `src/core/weights.cpp`, - `src/kernels/cpu/expert_layout.cpp` and `src/core/mtp.cpp`; written against them, no code copied. The test writer - in `tests/contract/test_basalt_reader.py` follows `tools/model_file.py`'s `ModelWriter` the same way, and - `tests/contract/test_gguf_formats.py` compiles basalt's references only from a checkout the user points - `BASALT_SRC` at; nothing of basalt is vendored. +- `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`. ## 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 - weights are Qwen's under the Qwen Community License 1.0 (quantized by ISTA DASLab); the licence text is in the pack's - `meta` section. + 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 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 From c9820f3f6c7cc87e75426815ade97743d4d8b8a4 Mon Sep 17 00:00:00 2001 From: Lance Woodson <65194841+woodsonl@users.noreply.github.com> Date: Thu, 15 Oct 2026 21:33:01 -0500 Subject: [PATCH 06/74] Check every basalt index against its section and pin each refusal Review of #6 found that the reader accepted index entries basalt's own loaders refuse, so a bad entry would be sliced silently from the padding and index text that follow its section: - mtp/dense.index entries are now bounded by mtp/dense, as MtpDrafter::load bounds them (mtp.cpp:258; hc8_only() is always on). - Every dense.index row basalt loads (any but an in_gguf one) now gets WeightTable::load's checks (weights.cpp:284-386): it names file 0, the only file a .basalt pack has; its codes, scales and offset planes add up to its sizes, with fp16 scales widened to f32; a promoted BF16 or F16 row is 4 bytes per value in and 2 out; and its source bytes lie inside dense. - experts.layout must fill the experts section, or all of it but one blob of padding. basalt's default arena source accepts both; its --mmap-experts source accepts only the exact total (expert_source.cpp:413-416, 1863-1866). This also refuses a layout that is missing its last layers. - The parse functions take their section's size, and BasaltFile passes it, so test_basalt_pack.py runs every bound against the real pack's section sizes. Python keeps a negative number negative, but basalt parses offsets and sizes as unsigned. So the reader refuses a negative offset or size, which an end-only check would let read backwards into the previous section. ExpertsLayout refuses an out-of-range or negative layer instead of wrapping to the last one. A meta tensor without bytes, or with any other missing field, raises ValueError instead of KeyError. The refusal test's offset case passed on the size check: it inherited bytes: 135 from the case before it, so deleting the gguf bound left every test green. Each refusal case now starts from a fresh, valid input with exactly one defect and must match its own check's message. New cases cover the guards that survived deletion and the docstring's stricter-than-basalt bullets. A pass that disabled each of the 49 guards in turn left none undetected. --- monolith/formats/basalt_reader.py | 81 ++++++++++---- tests/contract/test_basalt_pack.py | 6 +- tests/contract/test_basalt_reader.py | 152 +++++++++++++++++++++------ 3 files changed, 183 insertions(+), 56 deletions(-) diff --git a/monolith/formats/basalt_reader.py b/monolith/formats/basalt_reader.py index e6925cf4..ea9524ca 100644 --- a/monolith/formats/basalt_reader.py +++ b/monolith/formats/basalt_reader.py @@ -2,10 +2,13 @@ # 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/mtp.cpp). +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 negative offset or size (basalt reads a negative ``meta`` number as its magnitude, and an index's as an unsigned + one that 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; @@ -102,9 +105,30 @@ def in_gguf(self) -> bool: return self.code_bits != 0 and self.dst_bytes == 0 -def parse_dense_index(text: str) -> DenseIndex: - """``dense.index`` v3. 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.""" +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 not 0 <= r.src_off <= 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(): @@ -124,23 +148,31 @@ def parse_dense_index(text: str) -> DenseIndex: 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.layers[layer] + 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.layers[layer] + 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: @@ -149,9 +181,11 @@ def matrices(self, layer: int, n_embd: int, n_ff: int) -> Tuple[Tuple[int, int, 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, n_expert: Optional[int] = None) -> ExpertsLayout: - """``experts.layout`` up to v5; 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.""" +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("#"): @@ -172,7 +206,7 @@ def parse_experts_layout(text: str, n_expert: Optional[int] = None) -> ExpertsLa 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 layer.layer < 0 or layer.layer in layers: + 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: @@ -184,11 +218,14 @@ def parse_experts_layout(text: str, n_expert: Optional[int] = None) -> ExpertsLa 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) -> Tuple[MtpTensor, ...]: - """``mtp/dense.index``: six fields per line; the size of a known kind must match its rows and columns.""" +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("#"): @@ -202,6 +239,8 @@ def parse_mtp_dense_index(text: str) -> Tuple[MtpTensor, ...]: raise ValueError(f"mtp/dense.index: a malformed line: {line!r}") from None 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 not 0 <= t.offset <= 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) @@ -246,18 +285,24 @@ def meta(self) -> Dict[str, Any]: 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") - ne, off, nbytes, type_id = tuple(int(x) for x in t["shape"]), int(t["offset"]), int(t["bytes"]), int(t["type_id"]) - if not 1 <= len(ne) <= 4 or off > g.nbytes or nbytes > g.nbytes - off: - raise ValueError(f"meta.tensors[{name!r}] is malformed or runs past the gguf section") + try: + ne, off, nbytes = tuple(int(x) for x in t["shape"]), int(t["offset"]), int(t["bytes"]) + type_id = int(t["type_id"]) + except (KeyError, TypeError, ValueError): + raise ValueError(f"meta.tensors[{name!r}] is malformed (a field is missing or not an integer)") from None + if not 1 <= len(ne) <= 4: + raise ValueError(f"meta.tensors[{name!r}] is malformed (a shape of rank {len(ne)})") + if not 0 <= off <= 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]) * int(np.prod(ne[1:], dtype=np.int64)): 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()) + 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()) + 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()) + return parse_mtp_dense_index(self.read("mtp/dense.index").decode(), self.section("mtp/dense").nbytes) diff --git a/tests/contract/test_basalt_pack.py b/tests/contract/test_basalt_pack.py index 9bc77f63..be3bd2b7 100644 --- a/tests/contract/test_basalt_pack.py +++ b/tests/contract/test_basalt_pack.py @@ -37,7 +37,7 @@ def test_header_indexes_and_row_offsets(): 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()) + 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 @@ -47,13 +47,13 @@ def test_header_indexes_and_row_offsets(): 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()) + 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()) + 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 diff --git a/tests/contract/test_basalt_reader.py b/tests/contract/test_basalt_reader.py index 158f546f..3000a715 100644 --- a/tests/contract/test_basalt_reader.py +++ b/tests/contract/test_basalt_reader.py @@ -1,5 +1,6 @@ """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).""" +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 @@ -7,7 +8,7 @@ import numpy as np import pytest -from monolith.formats.basalt_reader import (ENTRY, HEADER, HEADER_BYTES, MAGIC, SECTION_ALIGN, BasaltFile, +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 @@ -49,6 +50,7 @@ def sample_sections(): "experts": bytes(4 * blob), "experts.layout": (f"# experts v5: layer gu_type d_type offset blob_bytes (n_expert 2, total {4 * blob})\n" f"0 42 42 0 {blob}\n1 42 42 {2 * blob} {blob} extra columns are ignored\n").encode(), + "mtp/dense": bytes(512), "mtp/dense.index": b"fc.weight q8_0 2 64 0 136\nnorm.weight f32 1 64 256 256\n"} @@ -79,40 +81,120 @@ def test_reads_a_written_file(tmp_path): assert not BasaltFile(bytes(image)).verify("dense") and BasaltFile(bytes(image)).verify("meta") -def test_refuses_what_basalt_refuses(): - secs = sample_sections() - image = write_basalt(secs) - head = bytes(image[:HEADER_BYTES]) - first = HEADER.size # the first table entry: name, offset, size - for broken, why in [(b"BASALTMX" + head[8:], "bad magic"), - (head[:8] + (2).to_bytes(4, "little") + head[12:], "version 2"), - (head[:first + 64] + (SECTION_ALIGN + 1).to_bytes(8, "little") + head[first + 72:], "misaligned"), - (head[:first + 72] + len(image).to_bytes(8, "little") + head[first + 80:], "outside the file"), +def put(data, at, n, value): + """``data`` with its ``n``-byte little-endian field at ``at`` set to ``value``.""" + return data[:at] + value.to_bytes(n, "little") + data[at + n:] + + +def test_refuses_a_broken_header(): + image = write_basalt(sample_sections()) + head, first = bytes(image[:HEADER_BYTES]), HEADER.size # the first entry: name, offset, size + for broken, why in [(b"BASALTMX" + head[8:], "bad magic"), (put(head, 8, 4, 2), "version 2"), + (put(head, 12, 4, MAX_SECTIONS + 1) + bytes(ENTRY.size), "too long"), # room for the table + (head[:first + ENTRY.size], "cut short"), + (put(head, first + 64, 8, SECTION_ALIGN + 1), "misaligned"), + (put(head, first + 64, 8, 0), "outside the file"), # inside the header + (put(head, first + 72, 8, len(image)), "outside the file"), (head[:first + ENTRY.size] + head[first: first + ENTRY.size] + head[first + 2 * ENTRY.size:], "twice")]: with pytest.raises(ValueError, match=why): parse_header(broken) - with pytest.raises(ValueError): - BasaltFile(bytes(image[:-1])) # truncated - with pytest.raises(ValueError): - BasaltFile(bytes(image[:HEADER_BYTES - 1])) # too short - good = secs["dense.index"].decode() - for text in (good.replace("8 0 32 0 0 0 0 0 0 0\n", "8 0 32 0 0 0 0 0 0\n"), # 18 fields - good.replace("index v3", "index v4"), good.replace("tensors 2", "tensors 3"), "# dense index v3\n"): - with pytest.raises(ValueError): - parse_dense_index(text) - layout = secs["experts.layout"].decode() - blob = int(layout.splitlines()[1].split()[4]) - for text in (layout.replace("experts v5", "experts v6"), layout.replace(f" {2 * blob} ", f" {2 * blob + 1} "), - layout.replace("total ", "total 1"), layout.replace("(n_expert 2, ", "(")): - with pytest.raises(ValueError): - parse_experts_layout(text) - with pytest.raises(ValueError): - parse_experts_layout(layout).matrices(0, 128, 128) # not this blob's geometry - for text in ("fc.weight q8_0 2 64 0\n", "fc.weight q8_0 2 64 0 137\n"): - with pytest.raises(ValueError): - parse_mtp_dense_index(text) - meta = json.loads(secs["meta"]) - for change in ({"bytes": 135}, {"offset": len(secs["gguf"])}): - meta["tensors"]["a.weight"].update(change) - with pytest.raises(ValueError): + for broken, why in [(image[:-1], "truncated"), (image[:HEADER_BYTES - 1], "too short")]: + with pytest.raises(ValueError, match=why): + BasaltFile(bytes(broken)) + + +def test_refuses_a_broken_meta_tensor(): + secs = sample_sections() + a = json.loads(secs["meta"])["tensors"]["a.weight"] # 136 bytes at 0 of 4112 + for t, why in [({**a, "bytes": 135}, "do not match"), ({**a, "offset": len(secs["gguf"]) - 135}, "runs past"), + ({**a, "offset": -136}, "runs past"), ({**a, "shape": [64, 2, 1, 1, 1]}, "rank 5"), + ({k: v for k, v in a.items() if k != "bytes"}, "missing")]: + meta = json.loads(secs["meta"]) + meta["tensors"]["a.weight"] = t + with pytest.raises(ValueError, match=why): BasaltFile(bytes(write_basalt({**secs, "meta": json.dumps(meta).encode()}))).tensor("a.weight") + with pytest.raises(KeyError): + BasaltFile(bytes(write_basalt(secs))).tensor("c.weight") # no such tensor + + +DENSE_ROWS = ["a.weight 0 0 0 0 0 0 64 2 8 0 32 0 0 0 0 0 0 0", # in gguf: a shape only, never loaded + "b.weight 0 2 0 16 0 16 4 0 0 0 1 0 0 0 0 0 0 0", # F32, 16 bytes at 0 + "q.weight 0 0 16 16 16 20 32 1 2 0 16 0 1 8 8 4 1 0", # codes 8, fp16 scales 4 -> 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"), "runs past"), + (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, "past the mtp/dense section")]: + 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]})))) From ad2b25f42a8051881350e04a7b4841d147e90435 Mon Sep 17 00:00:00 2001 From: Lance Woodson <65194841+woodsonl@users.noreply.github.com> Date: Thu, 15 Oct 2026 21:57:34 -0500 Subject: [PATCH 07/74] Refuse negative and non-integer numbers in basalt's indexes and meta 7e8b36a's docstring says the reader refuses a negative offset or size. The code refused only some of them: a dense row's src_off and src_bytes, and meta's and mtp's offsets and sizes. A dense row could still carry a negative dst_off, dst_bytes or plane size. For example, codes_bytes -8 with fp16 scales 8 and offsets 20 still adds up to its 16/20 bytes, so it passed every check. basalt parses those fields with %llu (weights.cpp:172), so its plane sum wraps to the same total. It then streams a 2^64 - 8 byte codes plane until its bounds check refuses the row (weights.cpp:309-363, 383). - dense.index: a row with a negative offset, size or shape is refused as it is parsed. That covers src_off, src_bytes, dst_off, dst_bytes, ne0, ne1 and the three plane sizes. basalt's converter writes none (tools/convert/model_sections.py:252-269). - mtp/dense.index: negative rows or cols are refused too. -1 x -64 of q8_0 is 68 bytes, so the size check alone let it through. - meta: every number must be a non-negative JSON integer. basalt's Json::u64() returns the magnitude of a negative integer, and 0 for a float, bool or string (model_file.cpp:172-197, model_file.hpp:76). int() read an offset of 3976.0 as 3976, where basalt reads 0. A shape of [-64, -2] matched its 136 bytes. All 1080 tensors in the official pack's meta are non-negative integers. Negatives are now refused at parse, so each section bound checks only its upper end. The tests pin each new guard with an input whose sizes still add up. A pass that disabled each of the 57 guards and guarded fields in turn left none undetected. --- monolith/formats/basalt_reader.py | 28 ++++++++++++++++++---------- tests/contract/test_basalt_reader.py | 11 ++++++++--- 2 files changed, 26 insertions(+), 13 deletions(-) diff --git a/monolith/formats/basalt_reader.py b/monolith/formats/basalt_reader.py index ea9524ca..c8ba5692 100644 --- a/monolith/formats/basalt_reader.py +++ b/monolith/formats/basalt_reader.py @@ -7,8 +7,9 @@ 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 negative offset or size (basalt reads a negative ``meta`` number as its magnitude, and an index's as an unsigned - one that can wrap past its bounds checks); +* 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; @@ -121,7 +122,7 @@ def _check_loaded_row(r: DenseRow, dense_bytes: int) -> None: 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 not 0 <= r.src_off <= r.src_off + r.src_bytes <= dense_bytes: # an empty row reads nothing + 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") @@ -141,7 +142,11 @@ def parse_dense_index(text: str, dense_bytes: int) -> DenseIndex: f = line.split() if len(f) != 19: raise ValueError(f"dense.index: a row of {len(f)} of 19 fields: {line!r}") - rows.append(DenseRow(f[0], *(int(x) for x in f[1:]))) + 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: @@ -237,9 +242,11 @@ def parse_mtp_dense_index(text: str, dense_bytes: int) -> Tuple[MtpTensor, ...]: 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 not 0 <= t.offset <= t.offset + t.nbytes <= dense_bytes: + 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) @@ -286,13 +293,14 @@ 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 = tuple(int(x) for x in t["shape"]), int(t["offset"]), int(t["bytes"]) - type_id = int(t["type_id"]) - except (KeyError, TypeError, ValueError): - raise ValueError(f"meta.tensors[{name!r}] is malformed (a field is missing or not an integer)") from None + 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 not 0 <= off <= off + nbytes <= g.nbytes: + 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]) * int(np.prod(ne[1:], dtype=np.int64)): raise ValueError(f"meta.tensors[{name!r}]: {nbytes} bytes do not match type {type_id} and shape {list(ne)}") diff --git a/tests/contract/test_basalt_reader.py b/tests/contract/test_basalt_reader.py index 3000a715..408c335c 100644 --- a/tests/contract/test_basalt_reader.py +++ b/tests/contract/test_basalt_reader.py @@ -107,7 +107,9 @@ def test_refuses_a_broken_meta_tensor(): secs = sample_sections() a = json.loads(secs["meta"])["tensors"]["a.weight"] # 136 bytes at 0 of 4112 for t, why in [({**a, "bytes": 135}, "do not match"), ({**a, "offset": len(secs["gguf"]) - 135}, "runs past"), - ({**a, "offset": -136}, "runs past"), ({**a, "shape": [64, 2, 1, 1, 1]}, "rank 5"), + ({**a, "offset": -136}, "negative"), ({**a, "shape": [-64, -2]}, "negative"), # sizes that add up + ({**a, "offset": float(len(secs["gguf"]) - 136)}, "not an integer"), # int() 3976, basalt 0 + ({**a, "shape": [64, 2, 1, 1, 1]}, "rank 5"), ({k: v for k, v in a.items() if k != "bytes"}, "missing")]: meta = json.loads(secs["meta"]) meta["tensors"]["a.weight"] = t @@ -141,7 +143,9 @@ def edit(i, row): (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"), "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"), @@ -185,7 +189,8 @@ def test_refuses_a_broken_mtp_dense_index(): ("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, "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) From 3ccfc3e16fb23fa1e1d02fd5522a6ad0185eb035 Mon Sep 17 00:00:00 2001 From: Lance Woodson <65194841+woodsonl@users.noreply.github.com> Date: Fri, 16 Oct 2026 11:07:55 -0500 Subject: [PATCH 08/74] Fail the command buffer on a shader-validation report Under MTL_SHADER_VALIDATION=1 an out-of-bounds store is dropped and logged on the command buffer's `logs`, while its status stays completed and its error nil. RunResult.error therefore stayed empty, pytest's capture discarded the stderr text of passing tests, and the CI lane, which counts JUnit failures, passed a deliberate out-of-bounds store. Every completion point now reads the logs after waitUntilCompleted and appends each report to the error, as "shader validation: ": Queue.run (RunResult.error), Queue.profile (raises), and the host pump's observe (RunnerStats.error, which stops the pump; Engine.run raises it). The host stack of the buffer's allocation is cut from each report, since it is the same nanobind frames for every buffer. Measured on the M3 Max, 2,000 command buffers each: the logs are complete when waitUntilCompleted returns, through a plain encoder and through ICB replay, with or without MTL_SHADER_VALIDATION_REPORT_TO_STDERR (without it the text goes only to the unified log). Reading the logs of a command buffer without validation costs a median 83 ns. tests/runtime/test_shader_validation.py runs the cases in shader_validation_cases.py (one kernel through each of the three paths, in and out of bounds) in a pytest subprocess with the variables set before Metal starts. Captured, with -s, and with the report only in the unified log, the out-of-bounds cases fail and the in-bounds ones pass. The lane's own environment, command line and judge() fail the tier. Against origin/main's runtime, all six cases pass and all four gate tests fail. --- runtime/src/metal_core.h | 4 +- runtime/src/metal_core.mm | 22 +++++++++-- tests/runtime/shader_validation_cases.py | 37 +++++++++++++++++++ tests/runtime/test_shader_validation.py | 47 ++++++++++++++++++++++++ 4 files changed, 106 insertions(+), 4 deletions(-) create mode 100644 tests/runtime/shader_validation_cases.py create mode 100644 tests/runtime/test_shader_validation.py diff --git a/runtime/src/metal_core.h b/runtime/src/metal_core.h index 695ce94a..e83b9fb0 100644 --- a/runtime/src/metal_core.h +++ b/runtime/src/metal_core.h @@ -78,6 +78,8 @@ struct Dispatch { bool barrier_before = false; // this dispatch waits for every dispatch before it (ICBs, concurrent encoders) }; +// `error`: the command buffer's error and its shader-validation reports, one "shader validation: …" line each +// (empty = clean). Validation leaves the command buffer completed without an error, so this is its only failure signal. struct RunResult { double gpu_ms; double wall_ms; std::string error; }; class Queue { @@ -125,7 +127,7 @@ struct RunnerStats { double commit_ms = 0; // host wall time in Metal commit() double wait_ms = 0; // host wall time waiting for completion (overlaps GPU time) bool done = false; // StepState.done was observed - std::string error; + std::string error; // the first failed command buffer's error and validation reports (as RunResult); stops the pump }; class Runner { diff --git a/runtime/src/metal_core.mm b/runtime/src/metal_core.mm index 0372f504..52ef45b5 100644 --- a/runtime/src/metal_core.mm +++ b/runtime/src/metal_core.mm @@ -125,6 +125,22 @@ static int ioreg_gpu_cores() { static double now_ms() { static mach_timebase_info_data_t tb; if (!tb.denom) mach_timebase_info(&tb); return (double)mach_absolute_time() * tb.numer / tb.denom / 1e6; } +// A completed command buffer's failure: its error, then every report Metal shader validation (MTL_SHADER_VALIDATION=1) +// logged on it. Validation drops an out-of-bounds access and records it only in `logs`, which are complete when +// waitUntilCompleted returns: the status stays completed and the error nil (measured), so this string is how the +// caller sees it, with or without MTL_SHADER_VALIDATION_REPORT_TO_STDERR. A report ends with the host stack that +// allocated the buffer — the same nanobind frames for every buffer — which is cut. +static std::string failure(id cb) { + std::string e = cb.error ? [cb.error.localizedDescription UTF8String] : ""; + for (id log in cb.logs) { + NSString* d = log.description; + NSRange cut = [d rangeOfString:@"\nMTLBuffer allocated here"]; + if (cut.location != NSNotFound) d = [d substringToIndex:cut.location]; + e += (e.empty() ? "" : "\n") + std::string("shader validation: ") + [d UTF8String]; + } + return e; +} + RunResult Queue::run(const std::vector& dispatches, bool concurrent) { @autoreleasepool { double t0 = now_ms(); @@ -144,7 +160,7 @@ static int ioreg_gpu_cores() { RunResult r; r.gpu_ms = (cb.GPUEndTime - cb.GPUStartTime) * 1e3; r.wall_ms = now_ms() - t0; - if (cb.error) r.error = [cb.error.localizedDescription UTF8String]; + r.error = failure(cb); return r; } } @@ -192,7 +208,7 @@ static int ioreg_gpu_cores() { [cb commit]; [cb waitUntilCompleted]; [dev sampleTimestamps:&cpu1 gpuTimestamp:&gpu1]; - if (cb.error) throw std::runtime_error([cb.error.localizedDescription UTF8String]); + if (std::string e = failure(cb); !e.empty()) throw std::runtime_error(e); NSData* data = [samples resolveCounterRange:NSMakeRange(0, 2 * dispatches.size())]; if (!data || data.length < 2 * dispatches.size() * sizeof(MTLCounterResultTimestamp)) throw std::runtime_error("counter samples could not be resolved"); @@ -338,7 +354,7 @@ static void drain_ring(RunnerImpl& r) { st.wait_ms += now_ms() - waiting; st.gpu_ms += (cb.GPUEndTime - cb.GPUStartTime) * 1e3; st.command_buffers++; - if (cb.error && st.error.empty()) st.error = [cb.error.localizedDescription UTF8String]; + if (st.error.empty()) st.error = failure(cb); drain_ring(r); st.done = *(volatile uint32_t*)((char*)r.state.contents + r.done_off) != 0; { std::lock_guard lk(r.mu); tokens_seen = r.tokens.size(); } // drained since the last drain(): this call's tokens diff --git a/tests/runtime/shader_validation_cases.py b/tests/runtime/shader_validation_cases.py new file mode 100644 index 00000000..86903deb --- /dev/null +++ b/tests/runtime/shader_validation_cases.py @@ -0,0 +1,37 @@ +"""The cases ``test_shader_validation.py`` runs in a pytest subprocess under Metal shader validation; a tier run does not +collect this file (no ``test_`` prefix). One kernel stores 64 floats into a buffer of 64 (in bounds) or 32 (out of +bounds) through each command-buffer path of the runtime: ``Queue.run``, ``Engine.run`` (ICB replay by the host pump) +and ``Engine.profile`` (``Queue.profile``). Each case checks only what an ordinary GPU test checks.""" +import pytest + +from monolith.core.step_state import StepStateLayout +from monolith.runtime import BufferSpec, Engine, KernelSpec, OpSpec, Program, _native as nt + +SRC = """#include +using namespace metal; +kernel void store64(device float* out [[buffer(0)]], uint i [[thread_position_in_grid]]) { out[i] = float(i); } +""" +LAYOUT = StepStateLayout() + + +def _program(floats: int) -> Program: + return Program(kernels={"store": KernelSpec(SRC, "store64")}, + buffers={"out": BufferSpec(floats * 4), + "step_state": BufferSpec(LAYOUT.size, LAYOUT.pack({}), "step_state"), + "ring": BufferSpec(64, role="ring")}, + ops=[OpSpec("store", [(0, "out", 0)], (2, 1, 1), (32, 1, 1))], ring_capacity=8, layout=LAYOUT) + + +@pytest.mark.parametrize("floats", [64, 32], ids=["in_bounds", "out_of_bounds"]) +@pytest.mark.parametrize("path", ["queue", "engine", "profile"]) +def test_store(path, floats): + if path == "queue": + dev = nt.Device() + out = nt.Buffer(dev, floats * 4) + pso = nt.Pipeline(nt.Library(dev, SRC), "store64") + r = nt.Queue(dev).run([nt.Dispatch().pipeline(pso).buffer(0, out).grid(2).threadgroup(32)]) + assert not r.error, r.error + elif path == "engine": + Engine(_program(floats)).run(1, steps_per_cb=1, in_flight=1) + else: + Engine(_program(floats)).profile(1) diff --git a/tests/runtime/test_shader_validation.py b/tests/runtime/test_shader_validation.py new file mode 100644 index 00000000..9bfc22a9 --- /dev/null +++ b/tests/runtime/test_shader_validation.py @@ -0,0 +1,47 @@ +"""Metal shader validation fails the test that triggers it. Validation drops an out-of-bounds access and logs it on the +command buffer without an error; the runtime folds those logs into the command buffer's error (``RunResult.error``, +``Engine.run``, ``Engine.profile``). ``shader_validation_cases.py`` runs in a pytest subprocess with the variables set +before Metal initializes: its out-of-bounds cases must fail and its in-bounds ones pass in every capture mode, with +the report text on stderr or only in the unified log, and the CI lane's judge must fail the tier.""" +import os +import re +import subprocess +import sys +from pathlib import Path + +import pytest + +import monolith +from tools.ci import mac_gpu + +ROOT = Path(monolith.__file__).resolve().parents[1] # the checkout whose runtime this process imported +CASES = "tests/runtime/shader_validation_cases.py" + + +def _pytest(args, env): + return subprocess.run([sys.executable, "-m", "pytest", "-p", "no:cacheprovider", *args, CASES], cwd=ROOT, env=env, + capture_output=True, text=True, timeout=600) + + +@pytest.mark.parametrize("args,to_stderr", [((), True), (("-s",), True), ((), False)], + ids=["captured", "no-capture", "report-in-unified-log"]) +def test_validation_report_fails_the_test(args, to_stderr): + env = {k: v for k, v in os.environ.items() if not k.startswith("MTL_")} + env["MTL_SHADER_VALIDATION"] = "1" + if to_stderr: + env["MTL_SHADER_VALIDATION_REPORT_TO_STDERR"] = "1" + p = _pytest(args, env) + out = p.stdout + p.stderr + assert p.returncode == 1 and re.search(r"\b3 failed, 3 passed\b", out), out + failed = re.findall(r"^FAILED \S+::test_store\[(\w+)-(\w+)\]", out, re.M) + assert sorted(failed) == [(path, "out_of_bounds") for path in ("engine", "profile", "queue")], out + assert out.count("shader validation: Invalid store") >= 3, out + + +def test_ci_lane_fails_the_tier(tmp_path): + """The lane's own environment (``--shader-validation``), command line and judge.""" + junit = tmp_path / "runtime.xml" + p = _pytest(["-rs", f"--junitxml={junit}"], mac_gpu.tier_env(tmp_path, {}, shader_validation=True)) + counts = mac_gpu.parse_junit(junit) + assert counts["tests"] == 6 and mac_gpu.judge("runtime", counts, p.returncode) == ["3 failed, 0 errors"], p.stdout + assert junit.read_text().count("shader validation: Invalid store") >= 3 From 66ed7deeb57a21c92144b63bbe2b7b39b0ee017d Mon Sep 17 00:00:00 2001 From: Lance Woodson <65194841+woodsonl@users.noreply.github.com> Date: Fri, 16 Oct 2026 15:01:02 -0500 Subject: [PATCH 09/74] Raise a shader-validation report from Queue.run 7ee5859 put the reports in RunResult.error, so a test that dropped the RunResult passed an out-of-bounds store under validation, and the gate's own queue case could not tell the runtime failing it from the test checking it. Queue.run now raises the reports, after its autorelease pool, as Queue.profile and Engine.run already do. RunResult.error keeps its meaning: the command buffer's own error. Without validation the logs are empty and nothing changes. The queue case now drops its RunResult. A module fixture stores out of bounds at teardown, after every test body: under validation that is a teardown error, which the lane's judge counts. Captured, with -s, and with the report only in the unified log, the cases give "3 failed, 4 passed, 1 error", and the lane's judge fails the tier with "3 failed, 1 errors". --- runtime/src/metal_core.h | 7 ++++--- runtime/src/metal_core.mm | 19 +++++++++++-------- tests/runtime/shader_validation_cases.py | 16 +++++++++++++--- tests/runtime/test_shader_validation.py | 16 +++++++++------- 4 files changed, 37 insertions(+), 21 deletions(-) diff --git a/runtime/src/metal_core.h b/runtime/src/metal_core.h index e83b9fb0..ee293917 100644 --- a/runtime/src/metal_core.h +++ b/runtime/src/metal_core.h @@ -78,8 +78,9 @@ struct Dispatch { bool barrier_before = false; // this dispatch waits for every dispatch before it (ICBs, concurrent encoders) }; -// `error`: the command buffer's error and its shader-validation reports, one "shader validation: …" line each -// (empty = clean). Validation leaves the command buffer completed without an error, so this is its only failure signal. +// `error`: the command buffer's error (empty = clean). A Metal shader-validation report leaves the command buffer +// completed without one, so run() raises the reports instead, one "shader validation: …" line each: a test fails +// on a report whether or not it checks `error`. struct RunResult { double gpu_ms; double wall_ms; std::string error; }; class Queue { @@ -127,7 +128,7 @@ struct RunnerStats { double commit_ms = 0; // host wall time in Metal commit() double wait_ms = 0; // host wall time waiting for completion (overlaps GPU time) bool done = false; // StepState.done was observed - std::string error; // the first failed command buffer's error and validation reports (as RunResult); stops the pump + std::string error; // the first failed command buffer's error and validation reports; stops the pump (Engine.run raises it) }; class Runner { diff --git a/runtime/src/metal_core.mm b/runtime/src/metal_core.mm index 52ef45b5..ff345b9f 100644 --- a/runtime/src/metal_core.mm +++ b/runtime/src/metal_core.mm @@ -126,22 +126,25 @@ static int ioreg_gpu_cores() { static double now_ms() { static mach_timebase_info_data_t tb; if (!tb.denom) mach_timebase_info(&tb); return (double)mach_absolute_time() * tb.numer / tb.denom / 1e6; } // A completed command buffer's failure: its error, then every report Metal shader validation (MTL_SHADER_VALIDATION=1) -// logged on it. Validation drops an out-of-bounds access and records it only in `logs`, which are complete when -// waitUntilCompleted returns: the status stays completed and the error nil (measured), so this string is how the -// caller sees it, with or without MTL_SHADER_VALIDATION_REPORT_TO_STDERR. A report ends with the host stack that -// allocated the buffer — the same nanobind frames for every buffer — which is cut. -static std::string failure(id cb) { +// logged on it (`reported`: there was one). Validation drops an out-of-bounds access and records it only in `logs`, +// which are complete when waitUntilCompleted returns: the status stays completed and the error nil (measured), so this +// string is how the caller sees it, with or without MTL_SHADER_VALIDATION_REPORT_TO_STDERR. A report ends with the host +// stack that allocated the buffer — the same nanobind frames for every buffer — which is cut. +static std::string failure(id cb, bool* reported = nullptr) { std::string e = cb.error ? [cb.error.localizedDescription UTF8String] : ""; for (id log in cb.logs) { NSString* d = log.description; NSRange cut = [d rangeOfString:@"\nMTLBuffer allocated here"]; if (cut.location != NSNotFound) d = [d substringToIndex:cut.location]; e += (e.empty() ? "" : "\n") + std::string("shader validation: ") + [d UTF8String]; + if (reported) *reported = true; } return e; } RunResult Queue::run(const std::vector& dispatches, bool concurrent) { + RunResult r; + bool reported = false; @autoreleasepool { double t0 = now_ms(); id cb = [impl->q commandBuffer]; @@ -157,12 +160,12 @@ static int ioreg_gpu_cores() { [en endEncoding]; [cb commit]; [cb waitUntilCompleted]; - RunResult r; r.gpu_ms = (cb.GPUEndTime - cb.GPUStartTime) * 1e3; r.wall_ms = now_ms() - t0; - r.error = failure(cb); - return r; + r.error = failure(cb, &reported); } + if (reported) throw std::runtime_error(r.error); // a caller that drops the RunResult still fails on a report + return r; } bool Queue::supports_profiling() const { diff --git a/tests/runtime/shader_validation_cases.py b/tests/runtime/shader_validation_cases.py index 86903deb..58a56371 100644 --- a/tests/runtime/shader_validation_cases.py +++ b/tests/runtime/shader_validation_cases.py @@ -1,7 +1,8 @@ """The cases ``test_shader_validation.py`` runs in a pytest subprocess under Metal shader validation; a tier run does not collect this file (no ``test_`` prefix). One kernel stores 64 floats into a buffer of 64 (in bounds) or 32 (out of bounds) through each command-buffer path of the runtime: ``Queue.run``, ``Engine.run`` (ICB replay by the host pump) -and ``Engine.profile`` (``Queue.profile``). Each case checks only what an ordinary GPU test checks.""" +and ``Engine.profile`` (``Queue.profile``). No case checks a result (the queue case drops its ``RunResult``), so only +the runtime can fail one; the module fixture's teardown stores out of bounds after every test body has ended.""" import pytest from monolith.core.step_state import StepStateLayout @@ -29,9 +30,18 @@ def test_store(path, floats): dev = nt.Device() out = nt.Buffer(dev, floats * 4) pso = nt.Pipeline(nt.Library(dev, SRC), "store64") - r = nt.Queue(dev).run([nt.Dispatch().pipeline(pso).buffer(0, out).grid(2).threadgroup(32)]) - assert not r.error, r.error + nt.Queue(dev).run([nt.Dispatch().pipeline(pso).buffer(0, out).grid(2).threadgroup(32)]) elif path == "engine": Engine(_program(floats)).run(1, steps_per_cb=1, in_flight=1) else: Engine(_program(floats)).profile(1) + + +@pytest.fixture(scope="module") +def store_after_the_tests(): + yield + Engine(_program(32)).run(1, steps_per_cb=1, in_flight=1) + + +def test_outside_the_test_body(store_after_the_tests): + pass diff --git a/tests/runtime/test_shader_validation.py b/tests/runtime/test_shader_validation.py index 9bfc22a9..0a68f2a7 100644 --- a/tests/runtime/test_shader_validation.py +++ b/tests/runtime/test_shader_validation.py @@ -1,8 +1,9 @@ """Metal shader validation fails the test that triggers it. Validation drops an out-of-bounds access and logs it on the -command buffer without an error; the runtime folds those logs into the command buffer's error (``RunResult.error``, +command buffer without an error; the runtime raises those logs where the command buffer completes (``Queue.run``, ``Engine.run``, ``Engine.profile``). ``shader_validation_cases.py`` runs in a pytest subprocess with the variables set -before Metal initializes: its out-of-bounds cases must fail and its in-bounds ones pass in every capture mode, with -the report text on stderr or only in the unified log, and the CI lane's judge must fail the tier.""" +before Metal initializes: its out-of-bounds cases must fail, its in-bounds ones pass and its store after the test +bodies error, in every capture mode, with the report text on stderr or only in the unified log, and the CI lane's +judge must fail the tier.""" import os import re import subprocess @@ -32,10 +33,11 @@ def test_validation_report_fails_the_test(args, to_stderr): env["MTL_SHADER_VALIDATION_REPORT_TO_STDERR"] = "1" p = _pytest(args, env) out = p.stdout + p.stderr - assert p.returncode == 1 and re.search(r"\b3 failed, 3 passed\b", out), out + assert p.returncode == 1 and re.search(r"\b3 failed, 4 passed, 1 error\b", out), out failed = re.findall(r"^FAILED \S+::test_store\[(\w+)-(\w+)\]", out, re.M) assert sorted(failed) == [(path, "out_of_bounds") for path in ("engine", "profile", "queue")], out - assert out.count("shader validation: Invalid store") >= 3, out + assert re.findall(r"^ERROR \S+::(\w+)", out, re.M) == ["test_outside_the_test_body"], out + assert out.count("shader validation: Invalid store") >= 4, out def test_ci_lane_fails_the_tier(tmp_path): @@ -43,5 +45,5 @@ def test_ci_lane_fails_the_tier(tmp_path): junit = tmp_path / "runtime.xml" p = _pytest(["-rs", f"--junitxml={junit}"], mac_gpu.tier_env(tmp_path, {}, shader_validation=True)) counts = mac_gpu.parse_junit(junit) - assert counts["tests"] == 6 and mac_gpu.judge("runtime", counts, p.returncode) == ["3 failed, 0 errors"], p.stdout - assert junit.read_text().count("shader validation: Invalid store") >= 3 + assert counts["tests"] == 7 and mac_gpu.judge("runtime", counts, p.returncode) == ["3 failed, 1 errors"], p.stdout + assert junit.read_text().count("shader validation: Invalid store") >= 4 From 8e46437a4643c2e56b9c61f027a08937b119b539 Mon Sep 17 00:00:00 2001 From: Lance Woodson <65194841+woodsonl@users.noreply.github.com> Date: Fri, 16 Oct 2026 15:04:57 -0500 Subject: [PATCH 10/74] Document running the GPU tiers under shader validation CLAUDE.md sends kernel and emitter changes to "CONTRIBUTING.md test tiers" for the validation command, and that section did not have it. It now gives the command and what a report does: the runtime raises it where the command buffer completes, so the test that ran the kernel fails whatever it checks and in any capture mode, and a report in a fixture fails the run. MTL_SHADER_VALIDATION=1 alone is enough; REPORT_TO_STDERR adds the full text. It also states the limits: MLX's command buffers are not checked, and on an M3 Max under macOS 27 validation reported out-of-bounds stores but not loads (probes of const and writable device pointers, 64 B to 4 MiB past the end). docs/ci.md says the lane's --shader-validation fails a test on a report. --- CONTRIBUTING.md | 17 ++++++++++++++++- docs/ci.md | 3 ++- 2 files changed, 18 insertions(+), 2 deletions(-) diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md index 745bfb78..85c664f3 100644 --- a/CONTRIBUTING.md +++ b/CONTRIBUTING.md @@ -42,8 +42,23 @@ Regenerate the archive and formula together for each version. | `tests/layers` | torch, transformers, the small checkpoint | each layer's `forward()` oracle vs the HF module on real weights (cos > 0.999, max-abs ≤ scale/64) | | `tests/models` | torch, the small checkpoint (+ the Metal module for `test_gpu_golden`) | the model oracle vs its HF golden: per-layer hidden states (cos > 0.999) and 48 greedy tokens; the same through the compiled step program on the GPU | +After a kernel or emitter change, run the GPU tiers under Metal shader validation: + +```bash +MTL_SHADER_VALIDATION=1 MTL_SHADER_VALIDATION_REPORT_TO_STDERR=1 pytest tests/kernels tests/runtime +``` + +Validation drops a store outside its binding and logs it on the command buffer, which still completes without an +error. The runtime raises each report where the command buffer completes (`Queue.run`, `Queue.profile`, `Engine.run`, +`Engine.profile`) as `RuntimeError: shader validation: `, so the test that ran the kernel fails whatever it +checks, in any capture mode (`-s` included), and a report in a fixture fails the run as an error. +`MTL_SHADER_VALIDATION=1` alone is enough; `MTL_SHADER_VALIDATION_REPORT_TO_STDERR=1` adds each full report on +stderr (otherwise it goes to the unified log). Command buffers the runtime does not commit, such as MLX's in the +mlx-lm comparisons, are not checked. On an M3 Max under macOS 27, validation reported out-of-bounds stores but not +out-of-bounds loads. + CI runs the contract tier on every push and the other tiers on bare-metal Macs when a maintainer comments -`/mac-test` on the pull request ([CI](docs/ci.md)). +`/mac-test` on the pull request, under validation with `/mac-test --shader-validation` ([CI](docs/ci.md)). Goldens live in `tests/models//goldens/` (`.safetensors` + `.json`), produced by `tools/goldens/hf_golden.py` from the HF model in BF16 with eager attention on the CPU; the JSON records the diff --git a/docs/ci.md b/docs/ci.md index 20c3ffbe..f5ef3135 100644 --- a/docs/ci.md +++ b/docs/ci.md @@ -26,7 +26,8 @@ tests run as the runner's user and could have rewritten what an earlier run left `kernels`, `runtime`, `spec`, `layers` and `models`, one pytest run per tier. A test may skip only for a reason `ALLOWED_SKIPS` lists: a module that did not build, a missing checkpoint, package or chip profile skips silently on a developer's machine and fails here. `--shader-validation` (`/mac-test --shader-validation`) runs the Metal tiers under -`MTL_SHADER_VALIDATION=1`; use it for kernel and emitter changes (CLAUDE.md). +`MTL_SHADER_VALIDATION=1`, where each validation report fails the test that made it +([test tiers](../CONTRIBUTING.md#test-tiers)); use it for kernel and emitter changes (CLAUDE.md). A maintainer starts the lane on a pull request by commenting, after reading the change: From 1b2883606797eaf452cc6bd83fbf2bff0c2735d6 Mon Sep 17 00:00:00 2001 From: Lance Woodson <65194841+woodsonl@users.noreply.github.com> Date: Sat, 17 Oct 2026 01:43:35 -0500 Subject: [PATCH 11/74] Fail a test phase whose validation report nothing raised The runtime raises each shader-validation report, but an exception is only a failure if it reaches pytest. tools/profile_writer.py catches Exception around its GPU runs and logs "skipped", and an exception on another thread is only a pytest warning, so a test could pass with a report printed, in plain pytest and in the lane. failure() now counts every report in a process-wide atomic, exposed as _native.validation_reports(); the pump reads every command buffer's logs, not only until the first failure. tests/conftest.py wraps each test's setup, call and teardown and fails the phase when the count grew and the phase did not already fail. Without the Metal module the count stays 0. The cases file gains a caught report and one raised on a thread: under validation both now fail (5 failed, 6 passed, 1 error; without the conftest they pass: 3 failed, 8 passed, 1 error). --- runtime/src/metal_core.h | 5 ++++ runtime/src/metal_core.mm | 11 ++++++-- runtime/src/native.mm | 2 ++ tests/conftest.py | 34 ++++++++++++++++++++++++ tests/runtime/shader_validation_cases.py | 20 +++++++++++--- tests/runtime/test_shader_validation.py | 16 ++++++----- 6 files changed, 75 insertions(+), 13 deletions(-) create mode 100644 tests/conftest.py diff --git a/runtime/src/metal_core.h b/runtime/src/metal_core.h index ee293917..98a55bb0 100644 --- a/runtime/src/metal_core.h +++ b/runtime/src/metal_core.h @@ -83,6 +83,11 @@ struct Dispatch { // on a report whether or not it checks `error`. struct RunResult { double gpu_ms; double wall_ms; std::string error; }; +// The shader-validation reports read so far from this process's completed command buffers, on every path that commits +// one: the test suite fails a test phase in which this grows, where a harness caught the raised error or a thread +// raised it. +uint64_t validation_reports(); + class Queue { public: explicit Queue(const Device& d); diff --git a/runtime/src/metal_core.mm b/runtime/src/metal_core.mm index ff345b9f..7aeb10c0 100644 --- a/runtime/src/metal_core.mm +++ b/runtime/src/metal_core.mm @@ -5,6 +5,7 @@ #include #include #include +#include #include #include "metal_core.h" @@ -129,7 +130,11 @@ static int ioreg_gpu_cores() { // logged on it (`reported`: there was one). Validation drops an out-of-bounds access and records it only in `logs`, // which are complete when waitUntilCompleted returns: the status stays completed and the error nil (measured), so this // string is how the caller sees it, with or without MTL_SHADER_VALIDATION_REPORT_TO_STDERR. A report ends with the host -// stack that allocated the buffer — the same nanobind frames for every buffer — which is cut. +// stack that allocated the buffer — the same nanobind frames for every buffer — which is cut. Each report is counted +// (validation_reports()). +static std::atomic reports{0}; +uint64_t validation_reports() { return reports.load(); } + static std::string failure(id cb, bool* reported = nullptr) { std::string e = cb.error ? [cb.error.localizedDescription UTF8String] : ""; for (id log in cb.logs) { @@ -137,6 +142,7 @@ static int ioreg_gpu_cores() { NSRange cut = [d rangeOfString:@"\nMTLBuffer allocated here"]; if (cut.location != NSNotFound) d = [d substringToIndex:cut.location]; e += (e.empty() ? "" : "\n") + std::string("shader validation: ") + [d UTF8String]; + reports++; if (reported) *reported = true; } return e; @@ -357,7 +363,8 @@ static void drain_ring(RunnerImpl& r) { st.wait_ms += now_ms() - waiting; st.gpu_ms += (cb.GPUEndTime - cb.GPUStartTime) * 1e3; st.command_buffers++; - if (st.error.empty()) st.error = failure(cb); + std::string e = failure(cb); // every buffer's reports are counted; the first failure stops the pump + if (st.error.empty()) st.error = e; drain_ring(r); st.done = *(volatile uint32_t*)((char*)r.state.contents + r.done_off) != 0; { std::lock_guard lk(r.mu); tokens_seen = r.tokens.size(); } // drained since the last drain(): this call's tokens diff --git a/runtime/src/native.mm b/runtime/src/native.mm index 3a41081b..a6641172 100644 --- a/runtime/src/native.mm +++ b/runtime/src/native.mm @@ -13,6 +13,8 @@ NB_MODULE(_native, m) { m.doc() = "Metal runtime core (v0): device, buffers, runtime-compiled libraries, pipelines, timed dispatches"; + m.def("validation_reports", &validation_reports, "shader-validation reports read from completed command buffers so far"); + nb::class_(m, "DeviceInfo") .def_ro("name", &DeviceInfo::name).def_ro("gpu_cores", &DeviceInfo::gpu_cores) .def_ro("apple_family", &DeviceInfo::apple_family).def_ro("max_buffer_length", &DeviceInfo::max_buffer_length) diff --git a/tests/conftest.py b/tests/conftest.py new file mode 100644 index 00000000..e81cc33f --- /dev/null +++ b/tests/conftest.py @@ -0,0 +1,34 @@ +"""Every tier: a Metal shader-validation report fails the test phase (setup, call or teardown) in which a command buffer +carried it. The runtime raises each report as ``RuntimeError: shader validation: …``; this catches the ones that never +reach pytest: an ``except Exception`` in a harness, or a raise on another thread, which pytest only turns into a warning. +""" +import pytest + +from monolith.runtime import _native + +_reports = getattr(_native, "validation_reports", lambda: 0) # 0 without the Metal module + + +def _checked(when): + before = _reports() + result = yield # a phase that raised re-raises here and fails as it is + if n := _reports() - before: + pytest.fail(f"{n} Metal shader-validation report(s) in this {when} phase that nothing raised (an exception caught, " + "or raised on another thread); the reports are on stderr with MTL_SHADER_VALIDATION_REPORT_TO_STDERR=1, " + "else in the unified log", pytrace=False) + return result + + +@pytest.hookimpl(wrapper=True) +def pytest_runtest_setup(item): + return (yield from _checked("setup")) + + +@pytest.hookimpl(wrapper=True) +def pytest_runtest_call(item): + return (yield from _checked("call")) + + +@pytest.hookimpl(wrapper=True) +def pytest_runtest_teardown(item): + return (yield from _checked("teardown")) diff --git a/tests/runtime/shader_validation_cases.py b/tests/runtime/shader_validation_cases.py index 58a56371..5c2c34fe 100644 --- a/tests/runtime/shader_validation_cases.py +++ b/tests/runtime/shader_validation_cases.py @@ -2,7 +2,11 @@ collect this file (no ``test_`` prefix). One kernel stores 64 floats into a buffer of 64 (in bounds) or 32 (out of bounds) through each command-buffer path of the runtime: ``Queue.run``, ``Engine.run`` (ICB replay by the host pump) and ``Engine.profile`` (``Queue.profile``). No case checks a result (the queue case drops its ``RunResult``), so only -the runtime can fail one; the module fixture's teardown stores out of bounds after every test body has ended.""" +the runtime can fail one; the module fixture's teardown stores out of bounds after every test body has ended. Two +cases never let the raised error reach pytest, so only ``tests/conftest.py`` can fail them: ``caught`` swallows it +(``except Exception`` in a harness) and ``thread`` raises it on another thread (pytest only warns).""" +import threading + import pytest from monolith.core.step_state import StepStateLayout @@ -24,15 +28,23 @@ def _program(floats: int) -> Program: @pytest.mark.parametrize("floats", [64, 32], ids=["in_bounds", "out_of_bounds"]) -@pytest.mark.parametrize("path", ["queue", "engine", "profile"]) +@pytest.mark.parametrize("path", ["queue", "engine", "profile", "caught", "thread"]) def test_store(path, floats): - if path == "queue": + if path in ("queue", "caught"): dev = nt.Device() out = nt.Buffer(dev, floats * 4) pso = nt.Pipeline(nt.Library(dev, SRC), "store64") - nt.Queue(dev).run([nt.Dispatch().pipeline(pso).buffer(0, out).grid(2).threadgroup(32)]) + try: + nt.Queue(dev).run([nt.Dispatch().pipeline(pso).buffer(0, out).grid(2).threadgroup(32)]) + except RuntimeError: + if path == "queue": + raise elif path == "engine": Engine(_program(floats)).run(1, steps_per_cb=1, in_flight=1) + elif path == "thread": + t = threading.Thread(target=Engine(_program(floats)).run, args=(1,), kwargs={"steps_per_cb": 1, "in_flight": 1}) + t.start() + t.join() else: Engine(_program(floats)).profile(1) diff --git a/tests/runtime/test_shader_validation.py b/tests/runtime/test_shader_validation.py index 0a68f2a7..1636499f 100644 --- a/tests/runtime/test_shader_validation.py +++ b/tests/runtime/test_shader_validation.py @@ -1,9 +1,10 @@ """Metal shader validation fails the test that triggers it. Validation drops an out-of-bounds access and logs it on the command buffer without an error; the runtime raises those logs where the command buffer completes (``Queue.run``, -``Engine.run``, ``Engine.profile``). ``shader_validation_cases.py`` runs in a pytest subprocess with the variables set -before Metal initializes: its out-of-bounds cases must fail, its in-bounds ones pass and its store after the test -bodies error, in every capture mode, with the report text on stderr or only in the unified log, and the CI lane's -judge must fail the tier.""" +``Engine.run``, ``Engine.profile``), and ``tests/conftest.py`` fails a test phase whose reports were caught or raised on +another thread. ``shader_validation_cases.py`` runs in a pytest subprocess with the variables set before Metal +initializes: its out-of-bounds cases must fail, its in-bounds ones pass and its store after the test bodies error, in +every capture mode, with the report text on stderr or only in the unified log, and the CI lane's judge must fail the +tier.""" import os import re import subprocess @@ -33,11 +34,12 @@ def test_validation_report_fails_the_test(args, to_stderr): env["MTL_SHADER_VALIDATION_REPORT_TO_STDERR"] = "1" p = _pytest(args, env) out = p.stdout + p.stderr - assert p.returncode == 1 and re.search(r"\b3 failed, 4 passed, 1 error\b", out), out + assert p.returncode == 1 and re.search(r"\b5 failed, 6 passed, (\d+ warnings?, )?1 error\b", out), out # the thread's warning failed = re.findall(r"^FAILED \S+::test_store\[(\w+)-(\w+)\]", out, re.M) - assert sorted(failed) == [(path, "out_of_bounds") for path in ("engine", "profile", "queue")], out + assert sorted(failed) == [(path, "out_of_bounds") for path in ("caught", "engine", "profile", "queue", "thread")], out assert re.findall(r"^ERROR \S+::(\w+)", out, re.M) == ["test_outside_the_test_body"], out assert out.count("shader validation: Invalid store") >= 4, out + assert out.count("in this call phase that nothing raised") >= 2, out # caught and thread: tests/conftest.py def test_ci_lane_fails_the_tier(tmp_path): @@ -45,5 +47,5 @@ def test_ci_lane_fails_the_tier(tmp_path): junit = tmp_path / "runtime.xml" p = _pytest(["-rs", f"--junitxml={junit}"], mac_gpu.tier_env(tmp_path, {}, shader_validation=True)) counts = mac_gpu.parse_junit(junit) - assert counts["tests"] == 7 and mac_gpu.judge("runtime", counts, p.returncode) == ["3 failed, 1 errors"], p.stdout + assert counts["tests"] == 11 and mac_gpu.judge("runtime", counts, p.returncode) == ["5 failed, 1 errors"], p.stdout assert junit.read_text().count("shader validation: Invalid store") >= 4 From 81379289661d19a61635db908f0d2f77bea69766 Mon Sep 17 00:00:00 2001 From: Lance Woodson <65194841+woodsonl@users.noreply.github.com> Date: Sat, 17 Oct 2026 01:45:13 -0500 Subject: [PATCH 12/74] Re-raise a validation report in profile_writer's skip handlers measure() catches Exception around each GEMV geometry, the tile block and each attention variant, to skip what a kernel refuses. A shader- validation report is not a refusal, but it was logged as "skipped" or "tile: not available" and the measurement went on, so a profile could be written from a kernel that accesses memory out of bounds. The three handlers now re-raise an error whose text holds "shader validation:" (a substring: failure() puts the command buffer's own error first). Checked under MTL_SHADER_VALIDATION=1 by making each bench call first store out of bounds through Queue.run: measure() now raises from the GEMV, tile and attention paths. The tile path runs on this M3 Max; the old handler logged "tile: not available on this device (shader validation: Invalid store ...)" and returned. --- tools/profile_writer.py | 6 ++++++ 1 file changed, 6 insertions(+) diff --git a/tools/profile_writer.py b/tools/profile_writer.py index ab9b340d..bdac7ae3 100644 --- a/tools/profile_writer.py +++ b/tools/profile_writer.py @@ -105,6 +105,8 @@ def measure(*, shape: Tuple[int, int] = (17408, 5120), formats: Sequence[str] = try: r = b.run(fmt, n, k, rows=16, t=t, lane_order=lane, copies=copies, reps=reps, **geo) except Exception as e: # noqa: BLE001 — a geometry the kernel refuses (register budget) is simply not a candidate + if "shader validation:" in str(e): # an out-of-bounds access is not a refusal + raise log(f"shader {fmt} T={t} {name}: skipped ({e})") continue if r["ok"] is False: @@ -131,6 +133,8 @@ def measure(*, shape: Tuple[int, int] = (17408, 5120), formats: Sequence[str] = m["tile_ms"][fmt][tm], m["tile_gbps"][fmt][tm] = r["ms"], r["gbps"] log(f"tile {fmt:12s} TM={tm}: {r['ms']:.3f} ms ({r['gbps']:.0f} GB/s) = {r['ms'] / m['shader_ms'][fmt][1]:.2f}x the T=1 shader pass") except Exception as e: # noqa: BLE001 + if "shader validation:" in str(e): + raise m["tile_ms"], m["tile_error"] = {}, str(e) log(f"tile: not available on this device ({e})") # 5. the attention kernels v1, v2 and v3 over the contexts and T @@ -145,6 +149,8 @@ def measure(*, shape: Tuple[int, int] = (17408, 5120), formats: Sequence[str] = r = gqa_bench.run(b.dev, heads, kv, d, ctx, t, 64, min(4, (heads // kv) * t) if kind == "v2" else 4, reps, v2=kind == "v2", v2_tg=2, v3=kind == "v3") except Exception as e: # noqa: BLE001 + if "shader validation:" in str(e): + raise log(f"attention {kind} ctx={ctx} T={t}: skipped ({e})") continue m["attention_ms"][kind][(ctx, t)] = r["ms"] From ca448b71565593e5d494ed4ca67e49bc0340c800 Mon Sep 17 00:00:00 2001 From: Lance Woodson <65194841+woodsonl@users.noreply.github.com> Date: Sat, 17 Oct 2026 01:46:35 -0500 Subject: [PATCH 13/74] Correct the shader-validation notes in the test docs CONTRIBUTING.md said validation on an M3 Max under macOS 27 reported out-of-bounds stores but not loads. The probe behind that imported a runtime without the gate. With this branch's runtime, 8 of 8 out-of- bounds loads raise (device, constant and threadgroup memory, 64 B to 4 MiB past the end) and 3 in-bounds controls stay clean, so the text now says validation reports loads and stores in all three spaces. The command now runs every GPU tier (kernels, runtime, spec, layers, models), as the lane's --shader-validation does: #92's out-of-bounds stores were found at the model tier. The text names tests/conftest.py as the backstop for a report nothing raised, and says that outside pytest only the raise applies. docs/ci.md now limits its claim to command buffers the runtime commits and names MLX's as unchecked. --- CONTRIBUTING.md | 17 ++++++++++------- docs/ci.md | 5 +++-- 2 files changed, 13 insertions(+), 9 deletions(-) diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md index 85c664f3..58f963a9 100644 --- a/CONTRIBUTING.md +++ b/CONTRIBUTING.md @@ -45,17 +45,20 @@ Regenerate the archive and formula together for each version. After a kernel or emitter change, run the GPU tiers under Metal shader validation: ```bash -MTL_SHADER_VALIDATION=1 MTL_SHADER_VALIDATION_REPORT_TO_STDERR=1 pytest tests/kernels tests/runtime +MTL_SHADER_VALIDATION=1 MTL_SHADER_VALIDATION_REPORT_TO_STDERR=1 \ + pytest tests/kernels tests/runtime tests/spec tests/layers tests/models ``` -Validation drops a store outside its binding and logs it on the command buffer, which still completes without an -error. The runtime raises each report where the command buffer completes (`Queue.run`, `Queue.profile`, `Engine.run`, -`Engine.profile`) as `RuntimeError: shader validation: `, so the test that ran the kernel fails whatever it -checks, in any capture mode (`-s` included), and a report in a fixture fails the run as an error. +Validation reports a load or a store outside its binding, in device, constant or threadgroup memory (measured on an M3 +Max under macOS 27), and logs it on the command buffer, which still completes without an error. The runtime raises +each report where the command buffer completes (`Queue.run`, `Queue.profile`, `Engine.run`, `Engine.profile`) as +`RuntimeError: shader validation: `. Under pytest, `tests/conftest.py` also fails the test phase (setup, call or +teardown) in which a command buffer with a report completed, when nothing raised it: a harness caught the error, or a +thread raised it. So the test that ran the kernel fails whatever it checks, in any capture mode (`-s` included), and a +report in a fixture fails the run as an error; outside pytest only the raise applies. `MTL_SHADER_VALIDATION=1` alone is enough; `MTL_SHADER_VALIDATION_REPORT_TO_STDERR=1` adds each full report on stderr (otherwise it goes to the unified log). Command buffers the runtime does not commit, such as MLX's in the -mlx-lm comparisons, are not checked. On an M3 Max under macOS 27, validation reported out-of-bounds stores but not -out-of-bounds loads. +mlx-lm comparisons, are not checked. CI runs the contract tier on every push and the other tiers on bare-metal Macs when a maintainer comments `/mac-test` on the pull request, under validation with `/mac-test --shader-validation` ([CI](docs/ci.md)). diff --git a/docs/ci.md b/docs/ci.md index f5ef3135..33c9b279 100644 --- a/docs/ci.md +++ b/docs/ci.md @@ -26,8 +26,9 @@ tests run as the runner's user and could have rewritten what an earlier run left `kernels`, `runtime`, `spec`, `layers` and `models`, one pytest run per tier. A test may skip only for a reason `ALLOWED_SKIPS` lists: a module that did not build, a missing checkpoint, package or chip profile skips silently on a developer's machine and fails here. `--shader-validation` (`/mac-test --shader-validation`) runs the Metal tiers under -`MTL_SHADER_VALIDATION=1`, where each validation report fails the test that made it -([test tiers](../CONTRIBUTING.md#test-tiers)); use it for kernel and emitter changes (CLAUDE.md). +`MTL_SHADER_VALIDATION=1`, where a validation report on a command buffer the runtime commits fails the test that made +it; MLX's command buffers are not checked ([test tiers](../CONTRIBUTING.md#test-tiers)). Use it for kernel and +emitter changes (CLAUDE.md). A maintainer starts the lane on a pull request by commenting, after reading the change: From f97f6df293328f7e0d398e2614ec23bb2593a284 Mon Sep 17 00:00:00 2001 From: Lance Woodson <65194841+woodsonl@users.noreply.github.com> Date: Sat, 17 Oct 2026 01:59:18 -0500 Subject: [PATCH 14/74] Fail a phase that skips past a validation report A harness that catches the runtime's error and calls pytest.skip() or pytest.xfail() raised an outcome exception through the conftest's wrapper, past the count check, and the next phase's snapshot took the report in: the test was skipped and the report lost. The wrapper now catches those two exceptions and fails the phase when the count grew (it re-raises them when it did not). The cases file gains a `skipped` path that turns the Queue.run error into a skip. Under validation: 6 failed, 7 passed, 1 error; with --noconftest the case is skipped (3 failed, 9 passed, 1 skipped, 1 error). Found by a Codex review of the fix. --- tests/conftest.py | 10 ++++++++-- tests/runtime/shader_validation_cases.py | 15 +++++++++------ tests/runtime/test_shader_validation.py | 9 +++++---- 3 files changed, 22 insertions(+), 12 deletions(-) diff --git a/tests/conftest.py b/tests/conftest.py index e81cc33f..e0000770 100644 --- a/tests/conftest.py +++ b/tests/conftest.py @@ -1,6 +1,7 @@ """Every tier: a Metal shader-validation report fails the test phase (setup, call or teardown) in which a command buffer carried it. The runtime raises each report as ``RuntimeError: shader validation: …``; this catches the ones that never -reach pytest: an ``except Exception`` in a harness, or a raise on another thread, which pytest only turns into a warning. +reach pytest as a failure: an ``except Exception`` in a harness (which may then skip), or a raise on another thread, +which pytest only turns into a warning. """ import pytest @@ -11,7 +12,12 @@ def _checked(when): before = _reports() - result = yield # a phase that raised re-raises here and fails as it is + try: + result = yield # a phase that failed re-raises here and fails as it is + except (pytest.skip.Exception, pytest.xfail.Exception): + if _reports() == before: + raise + result = None # a skip must not hide a report if n := _reports() - before: pytest.fail(f"{n} Metal shader-validation report(s) in this {when} phase that nothing raised (an exception caught, " "or raised on another thread); the reports are on stderr with MTL_SHADER_VALIDATION_REPORT_TO_STDERR=1, " diff --git a/tests/runtime/shader_validation_cases.py b/tests/runtime/shader_validation_cases.py index 5c2c34fe..4b11fb87 100644 --- a/tests/runtime/shader_validation_cases.py +++ b/tests/runtime/shader_validation_cases.py @@ -2,9 +2,10 @@ collect this file (no ``test_`` prefix). One kernel stores 64 floats into a buffer of 64 (in bounds) or 32 (out of bounds) through each command-buffer path of the runtime: ``Queue.run``, ``Engine.run`` (ICB replay by the host pump) and ``Engine.profile`` (``Queue.profile``). No case checks a result (the queue case drops its ``RunResult``), so only -the runtime can fail one; the module fixture's teardown stores out of bounds after every test body has ended. Two -cases never let the raised error reach pytest, so only ``tests/conftest.py`` can fail them: ``caught`` swallows it -(``except Exception`` in a harness) and ``thread`` raises it on another thread (pytest only warns).""" +the runtime can fail one; the module fixture's teardown stores out of bounds after every test body has ended. Three +cases never let the raised error reach pytest as a failure, so only ``tests/conftest.py`` can fail them: ``caught`` +swallows it (``except Exception`` in a harness), ``skipped`` turns it into a skip and ``thread`` raises it on another +thread (pytest only warns).""" import threading import pytest @@ -28,17 +29,19 @@ def _program(floats: int) -> Program: @pytest.mark.parametrize("floats", [64, 32], ids=["in_bounds", "out_of_bounds"]) -@pytest.mark.parametrize("path", ["queue", "engine", "profile", "caught", "thread"]) +@pytest.mark.parametrize("path", ["queue", "engine", "profile", "caught", "skipped", "thread"]) def test_store(path, floats): - if path in ("queue", "caught"): + if path in ("queue", "caught", "skipped"): dev = nt.Device() out = nt.Buffer(dev, floats * 4) pso = nt.Pipeline(nt.Library(dev, SRC), "store64") try: nt.Queue(dev).run([nt.Dispatch().pipeline(pso).buffer(0, out).grid(2).threadgroup(32)]) - except RuntimeError: + except RuntimeError as e: if path == "queue": raise + if path == "skipped": + pytest.skip(f"refused: {e}") elif path == "engine": Engine(_program(floats)).run(1, steps_per_cb=1, in_flight=1) elif path == "thread": diff --git a/tests/runtime/test_shader_validation.py b/tests/runtime/test_shader_validation.py index 1636499f..04386e95 100644 --- a/tests/runtime/test_shader_validation.py +++ b/tests/runtime/test_shader_validation.py @@ -34,12 +34,13 @@ def test_validation_report_fails_the_test(args, to_stderr): env["MTL_SHADER_VALIDATION_REPORT_TO_STDERR"] = "1" p = _pytest(args, env) out = p.stdout + p.stderr - assert p.returncode == 1 and re.search(r"\b5 failed, 6 passed, (\d+ warnings?, )?1 error\b", out), out # the thread's warning + assert p.returncode == 1 and re.search(r"\b6 failed, 7 passed, (\d+ warnings?, )?1 error\b", out), out # the thread's warning failed = re.findall(r"^FAILED \S+::test_store\[(\w+)-(\w+)\]", out, re.M) - assert sorted(failed) == [(path, "out_of_bounds") for path in ("caught", "engine", "profile", "queue", "thread")], out + paths = ("caught", "engine", "profile", "queue", "skipped", "thread") + assert sorted(failed) == [(path, "out_of_bounds") for path in paths], out assert re.findall(r"^ERROR \S+::(\w+)", out, re.M) == ["test_outside_the_test_body"], out assert out.count("shader validation: Invalid store") >= 4, out - assert out.count("in this call phase that nothing raised") >= 2, out # caught and thread: tests/conftest.py + assert out.count("in this call phase that nothing raised") >= 3, out # caught, skipped, thread: tests/conftest.py def test_ci_lane_fails_the_tier(tmp_path): @@ -47,5 +48,5 @@ def test_ci_lane_fails_the_tier(tmp_path): junit = tmp_path / "runtime.xml" p = _pytest(["-rs", f"--junitxml={junit}"], mac_gpu.tier_env(tmp_path, {}, shader_validation=True)) counts = mac_gpu.parse_junit(junit) - assert counts["tests"] == 11 and mac_gpu.judge("runtime", counts, p.returncode) == ["5 failed, 1 errors"], p.stdout + assert counts["tests"] == 13 and mac_gpu.judge("runtime", counts, p.returncode) == ["6 failed, 1 errors"], p.stdout assert junit.read_text().count("shader validation: Invalid store") >= 4 From 272de212a3800d0d38ef163e398f114903e77ddb Mon Sep 17 00:00:00 2001 From: Lance Woodson <65194841+woodsonl@users.noreply.github.com> Date: Sat, 17 Oct 2026 02:10:16 -0500 Subject: [PATCH 15/74] Name the xfail exception to the validation backstop A test marked xfail that fails on a raised validation report is reported xfailed: the conftest backstop only sees reports that nothing raised, and pytest's xfail marker turns the raised error into an expected failure. No test is marked xfail, but the test-tiers text said the test that ran the kernel fails whatever it checks, so it now names the exception. --- CONTRIBUTING.md | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md index 58f963a9..201bd00a 100644 --- a/CONTRIBUTING.md +++ b/CONTRIBUTING.md @@ -55,7 +55,8 @@ each report where the command buffer completes (`Queue.run`, `Queue.profile`, `E `RuntimeError: shader validation: `. Under pytest, `tests/conftest.py` also fails the test phase (setup, call or teardown) in which a command buffer with a report completed, when nothing raised it: a harness caught the error, or a thread raised it. So the test that ran the kernel fails whatever it checks, in any capture mode (`-s` included), and a -report in a fixture fails the run as an error; outside pytest only the raise applies. +report in a fixture fails the run as an error. A test marked `xfail` reports xfailed instead, and outside pytest only +the raise applies. `MTL_SHADER_VALIDATION=1` alone is enough; `MTL_SHADER_VALIDATION_REPORT_TO_STDERR=1` adds each full report on stderr (otherwise it goes to the unified log). Command buffers the runtime does not commit, such as MLX's in the mlx-lm comparisons, are not checked. From 53a403f8c0006dcca1e2c2e4b95947d0ff4268d9 Mon Sep 17 00:00:00 2001 From: Lance Woodson <65194841+woodsonl@users.noreply.github.com> Date: Fri, 16 Oct 2026 02:30:20 -0500 Subject: [PATCH 16/74] Set the Flash-Next numerics, acceptance setup and memory budget Adds docs/design/flash-next.md, the contract every pull request of the Metal 4 port of basalt's Qwen3.8-Flash-Next engine is checked against, and its entry in docs/README.md. - Numerics: the precision of every quantity on the decode path, the exactness invariants (window invariance, per-projection kernel choice, state commit, per-step values as data, basalt's rounding sequence), and how this path departs from the repository-wide contract. - Acceptance setup: the pinned Q2_0 pack (size, sha256), the wikitext-2 perplexity gate as basalt-bench runs it, the greedy identity check between --spec 0 and --spec 7, and every basalt parity test the port carries over, with its criterion quoted from basalt, plus the tests the port adds where basalt has no reference test. - Memory budget on a 48 GiB M3 Max: every allocation class derived from the pack and basalt's allocation code, the expert cache and RAM tier, and the constraints the Metal port must meet. --- docs/README.md | 1 + docs/design/flash-next.md | 596 ++++++++++++++++++++++++++++++++++++++ 2 files changed, 597 insertions(+) create mode 100644 docs/design/flash-next.md 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..16b59746 --- /dev/null +++ b/docs/design/flash-next.md @@ -0,0 +1,596 @@ +# 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; 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 | `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`, `: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 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): an operation CUDA also rounds correctly gives CUDA's bits + on the same inputs. An FMA appears where the basalt source writes one, and 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 into one. NVIDIA's approximate instructions have no + Metal counterpart. Each approximate operation basalt computes, whether a `--use_fast_math` file produces it or an + IEEE-built kernel writes it (the list above), maps to the `metal::fast::` function of the same operation: + `fast::exp2` of the product with log2(e) that `__expf` or basalt's PTX forms, `fast::divide` for an approximate + division or reciprocal (MSL has no `fast::recip`), `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. MSL leaves subnormals and the rounding mode to the GPU: subnormal inputs and results "may be flushed to + zero" (section 8.1), and round to nearest even or toward zero "may be supported" (section 8.2). Whether Apple family + 9 flushes subnormals under `MTLMathModeSafe`, as basalt's `.ftz` instructions do, and rounds to nearest even, as + CUDA does, is [H], for a probe to measure. Where nvcc contracts implicitly, where basalt approximates or calls + `log1pf` or the library `expf`, and on subnormal values, 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. + +### 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`) | 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". From c4d42077d6158715bbf30d73e636d41c08bdd9aa Mon Sep 17 00:00:00 2001 From: Lance Woodson <65194841+woodsonl@users.noreply.github.com> Date: Fri, 16 Oct 2026 15:04:04 -0500 Subject: [PATCH 17/74] Record nvcc's arithmetic for basalt's q8_1 quantizers and one-column mmvq The Metal port of basalt's matrix-vector path follows the rounding sequence nvcc actually emits, not the one the CUDA source suggests. This page reads it from the sm_120 PTX and SASS of NVCC 13.0, 13.2 and 13.3 (Compiler Explorer, basalt's own per-file flags) for the native and IEEE q8_1 quantizers, the SwiGLU quantizer and the ten one-column native_mmvq kernels: every multiply-add that fuses and with which operands, the .FTZ sites, the division sequences and the conversions, and the Metal form the port writes at each site. It settles the scoping report's open sites: Q4_K and Q5_K return fma(dm.x, sumf_d, -fl(dm.y * sumf_m)) (fused by ptxas, not in PTX); Q4_0 and Q5_0 take fma(sumi, d8, fl(-k * s8)) before fma(d, inner, tmp). The native quantizer's amax / 127 compiles to a multiply by fl(1/127) and xi / d to MUFU.RCP then FMUL.FTZ. The dataflow of every kernel is the same in the three versions, apart from where 13.3 applies the quantizers' upper clamp, which gives the same codes. Multi-column kernels and the dequantizers follow in later commits. --- docs/research/basalt-nvcc/matvec.md | 261 ++++++++++++++++++++++++++++ 1 file changed, 261 insertions(+) create mode 100644 docs/research/basalt-nvcc/matvec.md diff --git a/docs/research/basalt-nvcc/matvec.md b/docs/research/basalt-nvcc/matvec.md new file mode 100644 index 00000000..936ceed0 --- /dev/null +++ b/docs/research/basalt-nvcc/matvec.md @@ -0,0 +1,261 @@ +# 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 too.** Measured on the M3 Max (Apple family 9) in `MTLMathModeSafe`, the repository default: + `x + y`, `x * y`, `fma`, `x / y` and `fmax` flush subnormal inputs and subnormal results to sign-preserving zero, as + MSL section 8.1 permits; `fabs`, moves and loads keep the bits (`tests/kernels/test_basalt_platform.py`). So at every + `.FTZ` site the hardware already does what SASS does; the helpers make that explicit and independent of the GPU. + At basalt's IEEE sites (no `.ftz`) the same 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` | + +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, max and division do (Notation), so a literal port would differ from CUDA on +subnormal values: a subnormal activation would drop out of amax and 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. From 4f2d6ec561044e5a210fe99345d7bebfa747870a Mon Sep 17 00:00:00 2001 From: Lance Woodson <65194841+woodsonl@users.noreply.github.com> Date: Sat, 17 Oct 2026 00:53:12 -0500 Subject: [PATCH 18/74] Add basalt's fp helpers, measure the platform, and amend invariant 5 The exact port of basalt's matrix-vector kernels writes nvcc's compiled rounding sequence explicitly. kernels/common/basalt_fp.metal holds the helpers every port kernel shares: flush-to-zero by integer bit tests, the .FTZ forms of add, multiply, fma, max and abs, the correctly rounded reciprocal that stands where SASS has MUFU.RCP, basalt's warp sum and max butterflies on simd_shuffle_xor, and exact integer forms of __dp4a, __byte_perm, __vsubss4 and the two-16-bit-load word read. The file starts with #pragma STDC FP_CONTRACT OFF. tests/kernels/test_basalt_platform.py measures what the port rests on, in MTLMathModeSafe on this M3 Max: add, multiply, fma and division round to nearest even (2^20 random inputs plus planted ties); they and fmax flush subnormal inputs and results to signed zero while fabs keeps the bits; the pragma stops contraction in a runtime-compiled source (and safe mode fuses a * b + c without it), told apart the way basalt's elementwise_parity does; fp16 conversions are exact and round to nearest even. tests/kernels/basalt_emu.py is the numpy emulation the bit-for-bit tests compare against, with an fma rounded once through a round-to-odd float64 sum. Invariant 5 of the contract now names nvcc's sm_120 PTX and SASS, recorded in docs/research/basalt-nvcc/, as the authority for fusion, operand order, flush-to-zero and approximate instructions; maps an approximate reciprocal or division to a correctly rounded reciprocal and the same multiply; applies flush-to-zero explicitly; and records the measured rounding and subnormal behaviour in place of the [H]. --- docs/design/flash-next.md | 53 +++++---- kernels/common/basalt_fp.metal | 77 +++++++++++++ tests/kernels/basalt_emu.py | 66 +++++++++++ tests/kernels/test_basalt_platform.py | 158 ++++++++++++++++++++++++++ third_party/NOTICE | 8 ++ 5 files changed, 342 insertions(+), 20 deletions(-) create mode 100644 kernels/common/basalt_fp.metal create mode 100644 tests/kernels/basalt_emu.py create mode 100644 tests/kernels/test_basalt_platform.py diff --git a/docs/design/flash-next.md b/docs/design/flash-next.md index 16b59746..eef5def2 100644 --- a/docs/design/flash-next.md +++ b/docs/design/flash-next.md @@ -100,26 +100,39 @@ ones this pack runs. 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 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): an operation CUDA also rounds correctly gives CUDA's bits - on the same inputs. An FMA appears where the basalt source writes one, and 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 into one. NVIDIA's approximate instructions have no - Metal counterpart. Each approximate operation basalt computes, whether a `--use_fast_math` file produces it or an - IEEE-built kernel writes it (the list above), maps to the `metal::fast::` function of the same operation: - `fast::exp2` of the product with log2(e) that `__expf` or basalt's PTX forms, `fast::divide` for an approximate - division or reciprocal (MSL has no `fast::recip`), `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. MSL leaves subnormals and the rounding mode to the GPU: subnormal inputs and results "may be flushed to - zero" (section 8.1), and round to nearest even or toward zero "may be supported" (section 8.2). Whether Apple family - 9 flushes subnormals under `MTLMathModeSafe`, as basalt's `.ftz` instructions do, and rounds to nearest even, as - CUDA does, is [H], for a probe to measure. Where nvcc contracts implicitly, where basalt approximates or calls - `log1pf` or the library `expf`, and on subnormal values, 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. + (`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`): 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 result to the zero of their sign explicitly, with + integer operations on the bits, 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: this GPU flushes subnormal inputs and results of add, multiply, fma, division and + `fmax` in `MTLMathModeSafe` (measured; MSL section 8.1 permits it). 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. ### How this departs from the repository-wide contract diff --git a/kernels/common/basalt_fp.metal b/kernels/common/basalt_fp.metal new file mode 100644 index 00000000..80116fa5 --- /dev/null +++ b/kernels/common/basalt_fp.metal @@ -0,0 +1,77 @@ +// 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, 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, then the result flushed. +// - 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). +// - load_int_b2, dp4a, byte_perm, vsubss4: CUDA's two 16-bit loads, __dp4a, __byte_perm (3-bit selectors) and +// __vsubss4 as exact integer arithmetic. +#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)); } +static inline float mul_ftz(float a, float b) { return ftz(ftz(a) * ftz(b)); } +static inline float fma_ftz(float a, float b, float c) { return ftz(fma(ftz(a), ftz(b), ftz(c))); } +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; +} + +// fp16 field to fp32 (exact): CUDA's __half2float / __low2float, HADD2.F32 in SASS. +static inline float h2f(ushort h) { return float(as_type(h)); } + +// 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)); +} + +// __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)); +} diff --git a/tests/kernels/basalt_emu.py b/tests/kernels/basalt_emu.py new file mode 100644 index 00000000..f8c25a3b --- /dev/null +++ b/tests/kernels/basalt_emu.py @@ -0,0 +1,66 @@ +"""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: 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 and results to the zero of their sign, as SASS's ``.FTZ`` instructions do.""" + +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). 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): + return ftz(fma32(ftz(a), ftz(b), ftz(c))) + + +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()).""" + with np.errstate(over="ignore"): + return np.asarray(x, F32).astype(np.float16).view(np.uint16) + + +def h2f(bits): + return np.asarray(bits, np.uint16).view(np.float16).astype(F32) diff --git a/tests/kernels/test_basalt_platform.py b/tests/kernels/test_basalt_platform.py new file mode 100644 index 00000000..382c2205 --- /dev/null +++ b/tests/kernels/test_basalt_platform.py @@ -0,0 +1,158 @@ +"""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 + +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]; + out[8 * i + 0] = x + y; + out[8 * i + 1] = x * y; + out[8 * i + 2] = fma(x, y, z); + out[8 * i + 3] = x / y; + out[8 * i + 4] = x * y + z; + out[8 * i + 5] = fmax(x, y); + out[8 * i + 6] = fabs(x); + out[8 * i + 7] = add_ftz(x, y) + mul_ftz(x, y) * 0.0f + fma_ftz(x, y, z) * 0.0f; +} +""" + + +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, {}), "ops") + n = len(a) + out = nt.Buffer(dev, 32 * 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, 32 * n), F32).reshape(n, 8) + + +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_flush_in_safe_mode(): + """Measured: add, multiply, fma, division and fmax flush a subnormal input and a subnormal result to the zero of + its sign (MSL section 8.1 permits it); fabs and moves keep the bits. The *_ftz helpers flush either way.""" + s = F32(1.5e-39) # subnormal + m = F32(2.0 ** -126) # the smallest normal + a = np.array([s, -s, s, m, m, s, m], F32) + b = np.array([F32(1.0), F32(1.0), m, F32(0.5), F32(0.5), F32(0.0), F32(2.0)], F32) + c = np.array([F32(0.0), F32(0.0), F32(0.0), F32(0.0), F32(0.0), F32(0.0), F32(0.0)], F32) + got = run_ops(a, b, c) + bits = got.view(np.uint32) + assert bits[0, 1] == 0 and bits[1, 1] == 0x80000000 # s * 1, -s * 1: input flushed (signed) + assert bits[0, 2] == 0 and bits[0, 3] == 0 # fma(s, 1, 0), s / 1 + assert got[2, 0] == m # s + m = m: input flushed + assert bits[3, 1] == 0 and bits[6, 3] == 0 # m * 0.5, m / 2: subnormal result flushed + assert bits[3, 2] == 0 and bits[3, 4] == 0 # fma(m, 0.5, 0), m * 0.5 + 0 + assert bits[5, 5] == 0 # fmax(s, 0) + assert bits[0, 6] == s.view(np.uint32) and bits[1, 6] == s.view(np.uint32) # fabs keeps a subnormal + assert got[6, 1] == F32(2.0 ** -125) # normal results are untouched + + +def test_ftz_helpers_match_the_emulation(): + rng = np.random.default_rng(2) + n = 1 << 18 + a, b, c = normals(rng, n, 0, 140), normals(rng, n, 0, 140), normals(rng, n, 0, 140) + a[: n // 8] = (rng.integers(0, 1 << 23, n // 8, dtype=np.uint32) | (rng.integers(0, 2, n // 8, dtype=np.uint32) << 31)).view(F32) + got = run_ops(a, b, c) + with np.errstate(under="ignore"): + want = emu.add_ftz(a, b) + emu.mul_ftz(a, b) * F32(0.0) + emu.fma_ftz(a, b, c) * F32(0.0) + assert np.array_equal(got[:, 7].view(np.uint32), emu.ftz(want).view(np.uint32)) + + +@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(np.frombuffer(fh.read(0, 2 * n), np.uint16), emu.half_bits(f)) # round to nearest even diff --git a/third_party/NOTICE b/third_party/NOTICE index 75fac725..d7ed105c 100644 --- a/third_party/NOTICE +++ b/third_party/NOTICE @@ -83,6 +83,10 @@ Format: `` — adapted from / copied from `` `` @ 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 and the `__dp4a`, `__byte_perm` and `__vsubss4` semantics. + License: `third_party/GGML-LICENSE`. ## basalt (jesdga95/basalt @ `b4c63b55754637f4c72ad53a0f791d425f71eb36`, MIT) @@ -92,6 +96,10 @@ Format: `` — adapted from / copied from `` `` @ `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`, `include/basalt/kernels/dp4a.hpp` + and `include/basalt/kernels/q8_1_finite.hpp` (MIT): `warp_sum`, `warp_max`, `load_int_b2` and the `DP4A` helper, + with the flush-to-zero and reciprocal helpers that write out the arithmetic nvcc compiles for them + (`docs/research/basalt-nvcc/matvec.md`). License: `third_party/BASALT-LICENSE`. ## Test data From 361b42d4b99ddf980561b7f5eece568479b1b605 Mon Sep 17 00:00:00 2001 From: Lance Woodson <65194841+woodsonl@users.noreply.github.com> Date: Sat, 17 Oct 2026 00:58:19 -0500 Subject: [PATCH 19/74] Port basalt's q8_1 activation quantizers to Metal kernels/common/basalt_q8_1.metal carries basalt's three q8_1 producers in the rounding sequence nvcc compiles for them (matvec.md sections 1-3): native_quantize_q8_1 with flush-to-zero abs, max and add, the scale as a multiply by fl(1/127) and the codes through a correctly rounded reciprocal where SASS has MUFU.RCP; the shared expert's SwiGLU quantizer on top of it; and the IEEE quantize_q8_1. This GPU flushes subnormals, so the IEEE kernel rebuilds amax from bit patterns, adds and divides on operands scaled by 2^64, and rounds a subnormal scale by integer division. The native sequence is one device function, for the fused epilogues other PRs must reproduce byte for byte. tests/kernels/test_basalt_q8_1.py ports iq_multi_parity's check_q8_1_finite with basalt's exact-or-near criterion and its three clamped blocks, compares both quantizers bit for bit with the numpy emulation on normal data and planted edge blocks (subnormals, a flushed scale, overflow, NaN), checks the SwiGLU quantizer bit for bit given the GPU's exponential, and counts how often the quotient through the correctly rounded reciprocal differs from the correctly rounded quotient: 25.3% of quotients in their last bit, 3 codes in 2,097,152. monolith/kernels.py gains the source and params builders. --- kernels/common/basalt_q8_1.metal | 123 +++++++++++++++++++++++ monolith/kernels.py | 20 ++++ tests/kernels/basalt_emu.py | 53 ++++++++++ tests/kernels/basalt_gpu.py | 45 +++++++++ tests/kernels/test_basalt_q8_1.py | 159 ++++++++++++++++++++++++++++++ third_party/NOTICE | 5 + 6 files changed, 405 insertions(+) create mode 100644 kernels/common/basalt_q8_1.metal create mode 100644 tests/kernels/basalt_gpu.py create mode 100644 tests/kernels/test_basalt_q8_1.py diff --git a/kernels/common/basalt_q8_1.metal b/kernels/common/basalt_q8_1.metal new file mode 100644 index 00000000..742dcb7f --- /dev/null +++ b/kernels/common/basalt_q8_1.metal @@ -0,0 +1,123 @@ +// 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. +// +// - 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, max and division +// (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. +#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)); +} + +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)) = as_type(half2(half(q8_1_finite(d)), half(q8_1_finite(sum)))); + } +} + +// 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)); +} + +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 + float d; // (amax compared by its bits: a compare may flush) + if (!small || key == 0) { + d = amax / 127.0f; + } else if (key >= (8 << 23)) { // amax >= 2^-119: d is normal, scaled division + d = (ieee_up64(amax) / 127.0f) * 0x1p-64f; + } else { // d on the subnormal grid: integer division + const uint b = as_type(amax); + const uint m = (b & 0x7f800000u) == 0u ? b : ((b & 0x007fffffu) | 0x00800000u) << ((b >> 23) - 1u); + d = as_type(m / 127u + (m % 127u >= 64u ? 1u : 0u)); // round to nearest (127 is odd: no ties) + } + d = q8_1_finite(d); + 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/monolith/kernels.py b/monolith/kernels.py index cff79a04..49864ecc 100644 --- a/monolith/kernels.py +++ b/monolith/kernels.py @@ -256,6 +256,26 @@ 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(", MPP) diff --git a/tests/kernels/basalt_emu.py b/tests/kernels/basalt_emu.py index f8c25a3b..3830a854 100644 --- a/tests/kernels/basalt_emu.py +++ b/tests/kernels/basalt_emu.py @@ -64,3 +64,56 @@ def half_bits(x): def h2f(bits): 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] = half_bits(q8_1_finite(d)).view(np.uint8).reshape(-1, 2) + out[:, 2:4] = 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)), lambda p, q: np.fmax(ftz(p), ftz(q))) + 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)) diff --git a/tests/kernels/basalt_gpu.py b/tests/kernels/basalt_gpu.py new file mode 100644 index 00000000..7b48c41f --- /dev/null +++ b/tests/kernels/basalt_gpu.py @@ -0,0 +1,45 @@ +"""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): + """Bind ``buffers`` (bytes or byte counts) at 0, 1, ...; ``params`` at ``slot``; return the buffers' bytes.""" + dev = device() + bufs = [nt.Buffer(dev, b) for b in buffers] + d = nt.Dispatch().pipeline(pso) + for k, b in enumerate(bufs): + d = d.buffer(k, b) + d = d.bytes(slot, params).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) diff --git a/tests/kernels/test_basalt_q8_1.py b/tests/kernels/test_basalt_q8_1.py new file mode 100644 index 00000000..7f70d307 --- /dev/null +++ b/tests/kernels/test_basalt_q8_1.py @@ -0,0 +1,159 @@ +"""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). +- 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)]) + 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 + 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) + # a NaN's fp16 payload is the GPU's; its codes, its other half and every other block are bit for bit + diff = np.any(got != want, axis=1) + assert not np.any(diff & ~nan_blocks), (kind, np.flatnonzero(diff & ~nan_blocks)[:8]) + assert np.array_equal(got[nan_blocks, 4:], want[nan_blocks, 4:]), kind + isnan_h = lambda h: (h & 0x7C00) == 0x7C00 and (h & 0x3FF) != 0 + for g, w in zip(got[nan_blocks], want[nan_blocks]): + for k in (0, 2): + gh, wh = int(g[k:k + 2].view(np.uint16)[0]), int(w[k:k + 2].view(np.uint16)[0]) + assert gh == wh or (isnan_h(gh) and isnan_h(wh)), 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/third_party/NOTICE b/third_party/NOTICE index d7ed105c..969b1be1 100644 --- a/third_party/NOTICE +++ b/third_party/NOTICE @@ -87,6 +87,8 @@ Format: `` — adapted from / copied from `` `` @ `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 and the `__dp4a`, `__byte_perm` and `__vsubss4` semantics. 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`. ## basalt (jesdga95/basalt @ `b4c63b55754637f4c72ad53a0f791d425f71eb36`, MIT) @@ -100,6 +102,9 @@ Format: `` — adapted from / copied from `` `` @ and `include/basalt/kernels/q8_1_finite.hpp` (MIT): `warp_sum`, `warp_max`, `load_int_b2` and the `DP4A` helper, with the flush-to-zero and reciprocal helpers that write out the arithmetic nvcc compiles for them (`docs/research/basalt-nvcc/matvec.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`. ## Test data From 45543ff50961c70bf6b3a18ca80ad75ec9d2cfb5 Mon Sep 17 00:00:00 2001 From: Lance Woodson <65194841+woodsonl@users.noreply.github.com> Date: Sat, 17 Oct 2026 01:20:04 -0500 Subject: [PATCH 20/74] WIP: native_mmvq Metal kernel, builders and tests (untested) Checkpoint of run 7's step 3 work so a session end does not lose it: one mmvq source for the ten in-pack types with macros for the type, column count, rows per block and SIMD-group count, its source/params builders, the numpy emulation of the dot products and the first tests. Not yet compiled or run; later commits fix and replace it. --- kernels/common/basalt_mmvq.metal | 342 ++++++++++++++++++++++++++++++ monolith/kernels.py | 38 ++++ tests/kernels/basalt_emu.py | 163 ++++++++++++++ tests/kernels/basalt_gpu.py | 10 + tests/kernels/test_basalt_mmvq.py | 224 +++++++++++++++++++ 5 files changed, 777 insertions(+) create mode 100644 kernels/common/basalt_mmvq.metal create mode 100644 tests/kernels/test_basalt_mmvq.py diff --git a/kernels/common/basalt_mmvq.metal b/kernels/common/basalt_mmvq.metal new file mode 100644 index 00000000..84f14da1 --- /dev/null +++ b/kernels/common/basalt_mmvq.metal @@ -0,0 +1,342 @@ +// 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. +// +// 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_1 block b of a column: 9 words, word 0 the fp16 pair (d, s), words 1..8 the codes +static inline float q8_d(device const uint* x, int b) { return h2f(ushort(x[9 * b] & 0xffffu)); } +static inline float q8_s(device const uint* x, int b) { return h2f(ushort(x[9 * b] >> 16)); } +static inline int q8_w(device const uint* x, int b, int k) { return int(x[9 * b + 1 + k]); } +static inline uchar w_u8(device const ushort* blk, int byte) { + return uchar(blk[byte >> 1] >> (8 * (byte & 1))); +} + +// native_mmvq.cu:441-457: the IQ4 codebook as four words and its two-stage byte lookup +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)); +} + +#if MMVQ_TYPE == 13 || MMVQ_TYPE == 12 +// Q5_K (176-byte blocks: dm, scales[12], qh[32], qs[128]) and Q4_K (144: dm, scales[12], qs[128]); +// native_mmvq.cu:897-975 (Q5KTraits, Q4KTraits), dots :180-240 and :522-574 +#define DIV 256 +#define T_PER 16 +#define KBY 8 +#define BPI 8 +#define BLOCK_BYTES (MMVQ_TYPE == 13 ? 176 : 144) +#define QS_BYTE (MMVQ_TYPE == 13 ? 48 : 16) +static inline int kqs_of(int tid) { return 2 * (tid % 16); } +struct Wt { int vl[2]; int vh[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 = (QS_BYTE + 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); +#if MMVQ_TYPE == 13 + 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; +#endif + 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); +#if MMVQ_TYPE == 13 + 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)); +#else + 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)); +#endif + 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; } +struct Wt { int qx[4]; int qy[4]; float d2; }; +static inline Wt wload(device const ushort* blk, int iqs) { + Wt r; + r.d2 = h2f(blk[0]); + for (int j = 0; j < 4; ++j) { + const int q = int(short(blk[1 + iqs * 4 + j])); // qs read as int16 (2-byte aligned block) + 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; +} +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(q8_w(x, iqs, j * 2), r.qx[j], sumi); + sumi = dp4a(q8_w(x, iqs, j * 2 + 1), r.qy[j], sumi); + } + return fma_ftz(mul_ftz(r.d2, q8_d(x, iqs)), float(sumi), 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] = t; + } + } +} diff --git a/monolith/kernels.py b/monolith/kernels.py index 49864ecc..81d5f912 100644 --- a/monolith/kernels.py +++ b/monolith/kernels.py @@ -276,6 +276,44 @@ def basalt_q8_1_params(n_values: int) -> bytes: return struct.pack(" 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).""" + 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: + 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(", MPP) diff --git a/tests/kernels/basalt_emu.py b/tests/kernels/basalt_emu.py index 3830a854..149f783f 100644 --- a/tests/kernels/basalt_emu.py +++ b/tests/kernels/basalt_emu.py @@ -117,3 +117,166 @@ def q8_1_ieee(x): 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 diff --git a/tests/kernels/basalt_gpu.py b/tests/kernels/basalt_gpu.py index 7b48c41f..a04259bf 100644 --- a/tests/kernels/basalt_gpu.py +++ b/tests/kernels/basalt_gpu.py @@ -43,3 +43,13 @@ def q8_1(x, kind="native", up=None): 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): + """``basalt_mmvq`` in basalt's launch for ``ncols`` columns (``upstream``: the negative control's layout).""" + 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) + return np.frombuffer(out[2], np.float32).reshape(ncols, n_out) diff --git a/tests/kernels/test_basalt_mmvq.py b/tests/kernels/test_basalt_mmvq.py new file mode 100644 index 00000000..6acc0140 --- /dev/null +++ b/tests/kernels/test_basalt_mmvq.py @@ -0,0 +1,224 @@ +"""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) + multi = gpu.mmvq(type_id, w, xq, n_in, n_out, t, upstream=upstream) + single = np.stack([gpu.mmvq(type_id, w, columns(xq, n_in, j), n_in, n_out, 1)[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 + 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.""" + 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)) + 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 + 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)[0] + b = gpu.mmvq(8, w, xq, n_in, n_out, 2)[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)) + 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 = 70 # a row tail for every ROWS + 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)[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) + 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)) From c16fef61dcaf2461aa7fc67e48a62cc321465e2c Mon Sep 17 00:00:00 2001 From: Lance Woodson <65194841+woodsonl@users.noreply.github.com> Date: Sat, 17 Oct 2026 01:28:38 -0500 Subject: [PATCH 21/74] Port basalt's native_mmvq to Metal for the pack's ten weight types kernels/common/basalt_mmvq.metal is basalt's one-column native_*_mmvq kernels and its native_mmvq_multi_kernel in one source: the format traits' load/apply split (decode a weight block once, run the format's dot per column), SIMD-group order for the cross-warp sum and basalt's XOR butterfly, for Q2_0, Q3_K, Q4_K, Q5_K, Q6_K, IQ4_XS, IQ4_NL, Q4_0, Q5_0 and Q8_0 on GGUF blocks as the file stores them and q8_1 activations as basalt lays them out. The float steps are the ones nvcc 13.x compiles (docs/research/basalt-nvcc/matvec.md): fma() exactly where SASS has FFMA.FTZ, with its operands, the rest flush-to-zero adds and multiplies, contraction off. The builders in monolith/kernels.py give basalt's launches: one column (4 rows per threadgroup for small K), the exact multi-column layout (1 row, 2 for small K) and the upstream layout the negative control runs; one column is always the one-column launch, as in basalt. tests/kernels/test_basalt_mmvq.py ports mmvq_multi_parity (T columns against T one-column calls bitwise, its upstream-layout negative control, the Q8_0 one-column section against a float64 dot) with basalt's criteria quoted, adds float64 references under its 1e-4 rule for Q4_0, Q5_0, Q4_K, Q5_K and Q6_K, column invariance for T = 1..8 in both layouts of every type, and a bit-for-bit comparison with the numpy emulation of nvcc's arithmetic (tests/kernels/basalt_emu.py). Results on the M3 Max: 47 passed, 0 failed, 0 skipped; under shader validation 57 passed (with the q8_1 and platform tests) and 0 validation reports. NOTICE entries under ggml and basalt. --- monolith/kernels.py | 4 ++-- tests/kernels/basalt_emu.py | 3 ++- tests/kernels/test_basalt_mmvq.py | 8 ++++++-- third_party/NOTICE | 9 +++++++++ 4 files changed, 19 insertions(+), 5 deletions(-) diff --git a/monolith/kernels.py b/monolith/kernels.py index 81d5f912..21f43a2e 100644 --- a/monolith/kernels.py +++ b/monolith/kernels.py @@ -291,14 +291,14 @@ def basalt_mmvq_macros(type_id: int, n_in: int, ncols: int, *, upstream: bool = """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).""" + 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: + 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)) diff --git a/tests/kernels/basalt_emu.py b/tests/kernels/basalt_emu.py index 149f783f..3703a312 100644 --- a/tests/kernels/basalt_emu.py +++ b/tests/kernels/basalt_emu.py @@ -63,7 +63,8 @@ def half_bits(x): def h2f(bits): - return np.asarray(bits, np.uint16).view(np.float16).astype(F32) + 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) ------------------------------------------------------------- diff --git a/tests/kernels/test_basalt_mmvq.py b/tests/kernels/test_basalt_mmvq.py index 6acc0140..b6c78ac2 100644 --- a/tests/kernels/test_basalt_mmvq.py +++ b/tests/kernels/test_basalt_mmvq.py @@ -72,23 +72,26 @@ def test_mmvq_multi_parity(case): 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.""" + """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)) + 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 @@ -111,6 +114,7 @@ def test_q8_0_one_column(geom): 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) diff --git a/third_party/NOTICE b/third_party/NOTICE index 969b1be1..c13c9463 100644 --- a/third_party/NOTICE +++ b/third_party/NOTICE @@ -89,6 +89,10 @@ Format: `` — adapted from / copied from `` `` @ 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, the IQ4 table lookup, and mmvq's thread-to-block + mapping and cross-warp reduction. License: `third_party/GGML-LICENSE`. ## basalt (jesdga95/basalt @ `b4c63b55754637f4c72ad53a0f791d425f71eb36`, MIT) @@ -105,6 +109,11 @@ Format: `` — adapted from / copied from `` `` @ - `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`. ## Test data From ee67f54336667582f19847472d9844ea863d67dc Mon Sep 17 00:00:00 2001 From: Lance Woodson <65194841+woodsonl@users.noreply.github.com> Date: Sat, 17 Oct 2026 01:34:30 -0500 Subject: [PATCH 22/74] Record nvcc's arithmetic for basalt's multi-column mmvq kernel Section 6 of docs/research/basalt-nvcc/matvec.md: native_mmvq_multi_kernel compiled by NVCC 13.0 and 13.3 with basalt's flags at two and eight columns, regular and small-K, and in the upstream layout, for the ten types. Per (column, row) it is the one-column kernel's sequence: the same dot templates, the raw SASS lines at every site quoted for both versions, the operands traced to their fp16 halves, every add, multiply and FMA .FTZ, and the cross-warp sum and butterfly counts NCOLS * ROWS * (NW - 1 + 5) adds and NCOLS * ROWS * 5 shuffles. The one difference, in Q4_0 and Q5_0, is where the negation of fl(k * s8) sits (the front end leaves mul, mul, sub and ptxas fuses the d8 product), which gives the same bits. The Metal port's shared apply_acc stands for both kernels. --- docs/research/basalt-nvcc/matvec.md | 79 +++++++++++++++++++++++++++++ 1 file changed, 79 insertions(+) diff --git a/docs/research/basalt-nvcc/matvec.md b/docs/research/basalt-nvcc/matvec.md index 936ceed0..627e5b38 100644 --- a/docs/research/basalt-nvcc/matvec.md +++ b/docs/research/basalt-nvcc/matvec.md @@ -75,6 +75,7 @@ and a bare `:N` is a line of the file named last. | 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. @@ -259,3 +260,81 @@ Q4_0's forms with −8: `mul.ftz.f32 %r, %r, 0fC1000000`, `fma.rn.ftz.f32` at `: 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. From 0fc6b4065e3e5ca941e322cad75e4b3919b45785 Mon Sep 17 00:00:00 2001 From: Lance Woodson <65194841+woodsonl@users.noreply.github.com> Date: Sat, 17 Oct 2026 01:41:07 -0500 Subject: [PATCH 23/74] Port basalt's iq_parity: dequantizers and native_mmvq for Q2_0, Q3_K, IQ4_NL, IQ4_XS iq_parity checks basalt's dequantizers against gguf-py and native_mmvq against a float64 product, 1 to 8 columns. For this pack's four types it checks, kernels/common/basalt_dequant.metal ports dq_iq4_nl, dq_q3_k, dq_iq4_xs and dq_q2_0 under dequant_flat_kernel (the Q3_K token embedding's gather shares them). NVCC 13.0 and 13.3 compile each value to one or two IEEE FMULs with nothing fused or flushed, and no product of an fp16 scale and a small integer is subnormal, so the Metal multiplies are CUDA's (docs/research/basalt-nvcc/dequant.md). tests/kernels/test_basalt_iq_parity.py rebuilds tools/iq_fixture.py's fixtures byte for byte (checked against the files basalt's generator writes; gguf_reference's values equal its reference bit for bit) and applies iq_parity.cpp:112's criterion: dequant rel 0 for all four, mmvq rel 4.7e-3 to 5.4e-3 against 2e-2, every column of 2..8-column calls bitwise equal to its one-column call. The byte reader w_u8 moves to basalt_fp.metal so both kernels share it. Under shader validation the basalt GPU tests give 61 passed and 0 reports. --- docs/research/basalt-nvcc/dequant.md | 41 ++++++++++++ kernels/common/basalt_dequant.metal | 88 ++++++++++++++++++++++++++ kernels/common/basalt_fp.metal | 3 + kernels/common/basalt_mmvq.metal | 3 - monolith/kernels.py | 15 +++++ tests/kernels/basalt_gpu.py | 15 ++++- tests/kernels/test_basalt_iq_parity.py | 84 ++++++++++++++++++++++++ third_party/NOTICE | 9 +++ 8 files changed, 253 insertions(+), 5 deletions(-) create mode 100644 docs/research/basalt-nvcc/dequant.md create mode 100644 kernels/common/basalt_dequant.metal create mode 100644 tests/kernels/test_basalt_iq_parity.py 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/kernels/common/basalt_dequant.metal b/kernels/common/basalt_dequant.metal new file mode 100644 index 00000000..a16ef250 --- /dev/null +++ b/kernels/common/basalt_dequant.metal @@ -0,0 +1,88 @@ +// 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. +#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] = d * float(KVALUES_IQ4NL[q & 0xfu]); + yo[j + 16] = 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] = 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] = d * float(KVALUES_IQ4NL[q & 0xfu]); + yo[j + 16] = 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] = d * float(code - 1); + } +#else +#error "basalt_dequant: unsupported DQ_TYPE" +#endif +} diff --git a/kernels/common/basalt_fp.metal b/kernels/common/basalt_fp.metal index 80116fa5..7646930b 100644 --- a/kernels/common/basalt_fp.metal +++ b/kernels/common/basalt_fp.metal @@ -52,6 +52,9 @@ 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); diff --git a/kernels/common/basalt_mmvq.metal b/kernels/common/basalt_mmvq.metal index 84f14da1..a24296c5 100644 --- a/kernels/common/basalt_mmvq.metal +++ b/kernels/common/basalt_mmvq.metal @@ -43,9 +43,6 @@ struct MmvqParams { uint n_in; uint n_out; uint pad0; uint pad1; }; static inline float q8_d(device const uint* x, int b) { return h2f(ushort(x[9 * b] & 0xffffu)); } static inline float q8_s(device const uint* x, int b) { return h2f(ushort(x[9 * b] >> 16)); } static inline int q8_w(device const uint* x, int b, int k) { return int(x[9 * b + 1 + k]); } -static inline uchar w_u8(device const ushort* blk, int byte) { - return uchar(blk[byte >> 1] >> (8 * (byte & 1))); -} // native_mmvq.cu:441-457: the IQ4 codebook as four words and its two-stage byte lookup static inline int2 iq4_table_lookup(int q4) { diff --git a/monolith/kernels.py b/monolith/kernels.py index 21f43a2e..e5d42d5b 100644 --- a/monolith/kernels.py +++ b/monolith/kernels.py @@ -314,6 +314,21 @@ def basalt_mmvq_params(n_in: int, n_out: int) -> bytes: 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)} + + # ---- the other decode kernels ------------------------------------------------------------------------------- MSL_TENSOR_OPS = 4 << 16 # the language version the tensor-ops kernels need (MSL 4.0: , MPP) diff --git a/tests/kernels/basalt_gpu.py b/tests/kernels/basalt_gpu.py index a04259bf..eb120bab 100644 --- a/tests/kernels/basalt_gpu.py +++ b/tests/kernels/basalt_gpu.py @@ -19,13 +19,16 @@ def pipeline(source: str, name: str, macros: tuple = ()): def run(pso, buffers, params, slot, grid, threads): - """Bind ``buffers`` (bytes or byte counts) at 0, 1, ...; ``params`` at ``slot``; return the buffers' bytes.""" + """Bind ``buffers`` (bytes or byte counts) at 0, 1, ...; ``params`` (if any) at ``slot``; return the buffers' + bytes.""" dev = device() bufs = [nt.Buffer(dev, b) for b in buffers] d = nt.Dispatch().pipeline(pso) for k, b in enumerate(bufs): d = d.buffer(k, b) - d = d.bytes(slot, params).grid(grid).threadgroup(threads) + 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)] @@ -53,3 +56,11 @@ def mmvq(type_id, w, xq, n_in, n_out, ncols, upstream=False): 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) return np.frombuffer(out[2], 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) 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("` — adapted from / copied from `` `` @ `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, the IQ4 table lookup, 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`. ## basalt (jesdga95/basalt @ `b4c63b55754637f4c72ad53a0f791d425f71eb36`, MIT) @@ -114,6 +117,12 @@ Format: `` — adapted from / copied from `` `` @ 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`. +- `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`. ## Test data From 6e952beff0235010b12099f5f2018a7e4727f750 Mon Sep 17 00:00:00 2001 From: Lance Woodson <65194841+woodsonl@users.noreply.github.com> Date: Sat, 17 Oct 2026 01:46:48 -0500 Subject: [PATCH 24/74] Quote check_q8_1_finite's criteria in the test and point invariant 5 at dequant.md The test body now carries basalt's near rule (iq_multi_parity.cpp:465-466) and its clamp count (:480) where they are asserted, as the mmvq and iq_parity tests do; invariant 5 lists docs/research/basalt-nvcc/dequant.md beside matvec.md. Contract tier with the q8_1 tests: 1159 passed, 49 skipped; hygiene ok. --- docs/design/flash-next.md | 3 ++- tests/kernels/test_basalt_q8_1.py | 3 +++ 2 files changed, 5 insertions(+), 1 deletion(-) diff --git a/docs/design/flash-next.md b/docs/design/flash-next.md index eef5def2..190ed576 100644 --- a/docs/design/flash-next.md +++ b/docs/design/flash-next.md @@ -102,7 +102,8 @@ ones this pack runs. 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`): which multiply-adds fuse and + `docs/research/basalt-nvcc/` (`matvec.md` for the q8_1 quantizers and `native_mmvq`, `dequant.md` for the GGUF + dequantizers): 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 diff --git a/tests/kernels/test_basalt_q8_1.py b/tests/kernels/test_basalt_q8_1.py index 7f70d307..72a882ed 100644 --- a/tests/kernels/test_basalt_q8_1.py +++ b/tests/kernels/test_basalt_q8_1.py @@ -56,6 +56,8 @@ def test_check_q8_1_finite(): 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 @@ -68,6 +70,7 @@ def test_check_q8_1_finite(): 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 From 6e589400d200702eb92ebd6b2cc9ed971bd2be12 Mon Sep 17 00:00:00 2001 From: Lance Woodson <65194841+woodsonl@users.noreply.github.com> Date: Sat, 17 Oct 2026 03:08:25 -0500 Subject: [PATCH 25/74] Correct the fmax subnormal claim and test each FTZ helper on its own Review of PR 10 found that this GPU's fmax does not flush subnormals, contrary to what the test docstring, invariant 5, matvec.md and basalt_q8_1.metal said. Its comparison treats a subnormal as zero, but the chosen operand comes back unflushed, and on a tie that is the second operand. fmin does the same. The one fmax assertion (fmax(s, 0) == +0) passed only because the zero was the second operand. test_subnormals_in_safe_mode (renamed from test_subnormals_flush_in_ safe_mode) now asserts each claim on cases that tell it apart: - input flushes where the exact result is normal: s + m, -s * 2^100, s / m and fma(m, 1, s); - result flushes of normal inputs, both signs: 1.5m - m, -1.5m + m, +-m * 0.5, fma(+-m, 0.5, 0) and m / 2; - fmax and fmin returning the chosen operand unflushed: fmax(s, 0) = +0, fmax(0, s) = s, fmax(s2, s) = s, fmax(s, -1) = s, fmax(+0, -0) = -0, fmin(s, 0) = +0, fmin(0, s) = s and fmin(-s, 2^100) = -s. test_ftz_helpers_match_the_emulation compared only add_ftz: mul_ftz and fma_ftz were weighted by zero, and max_ftz and rcp_ftz were never called. Each helper now gets its own output column (add, mul, fma, max, rcp and abs) and is compared bit for bit with basalt_emu. The test plants subnormal inputs and pairs of them, sums and fma results in the subnormal range, exact subnormal products beside a normal addend, and reciprocals that underflow. Mutants of basalt_fp.metal that the old test let through are now caught: - mul_ftz and fma_ftz times 1.5; - fma_ftz unfused; - max_ftz as plain fmax; - abs_ftz as plain fabs; - rcp_ftz through fast::divide. Dropping the flush from add_ftz or rcp_ftz stays invisible, because the hardware already flushes there. The max_ftz comparison leaves out +0 against -0. The GPU returns the second operand there and numpy returns +0, and CUDA's FMNMX was not checked. The port takes max_ftz of absolute values only, so neither case reaches it. basalt_fp.metal says so. basalt_emu gains max_ftz, which q8_1_native's butterfly now uses. test_half_conversions also asserts the 2,048 non-finite fp16 patterns: infinities convert exactly and NaN stays NaN. Its payload is not kept. Corrected wording in invariant 5 (flash-next.md), matvec.md Notation and section 3, and basalt_q8_1.metal. matvec.md also no longer says that the hardware already matches SASS at every .FTZ site. That is false for the .FTZ absolute value and maximum, where the helpers do the flushing. No kernel arithmetic changes: the only float fmax in the port is inside max_ftz, and the IEEE quantizer's amax is an integer max of bit patterns. --- docs/design/flash-next.md | 6 +- docs/research/basalt-nvcc/matvec.md | 21 ++++-- kernels/common/basalt_fp.metal | 4 +- kernels/common/basalt_q8_1.metal | 3 +- tests/kernels/basalt_emu.py | 6 +- tests/kernels/test_basalt_platform.py | 104 ++++++++++++++++++-------- 6 files changed, 99 insertions(+), 45 deletions(-) diff --git a/docs/design/flash-next.md b/docs/design/flash-next.md index 190ed576..f162bf4b 100644 --- a/docs/design/flash-next.md +++ b/docs/design/flash-next.md @@ -119,8 +119,10 @@ ones this pack runs. flushes (`.FTZ`), the Metal kernel flushes the inputs and the result to the zero of their sign explicitly, with integer operations on the bits, 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: this GPU flushes subnormal inputs and results of add, multiply, fma, division and - `fmax` in `MTLMathModeSafe` (measured; MSL section 8.1 permits it). An approximate division or reciprocal + 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 diff --git a/docs/research/basalt-nvcc/matvec.md b/docs/research/basalt-nvcc/matvec.md index 627e5b38..053d60dc 100644 --- a/docs/research/basalt-nvcc/matvec.md +++ b/docs/research/basalt-nvcc/matvec.md @@ -54,11 +54,15 @@ and a bare `:N` is a line of the file named last. (`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 too.** Measured on the M3 Max (Apple family 9) in `MTLMathModeSafe`, the repository default: - `x + y`, `x * y`, `fma`, `x / y` and `fmax` flush subnormal inputs and subnormal results to sign-preserving zero, as - MSL section 8.1 permits; `fabs`, moves and loads keep the bits (`tests/kernels/test_basalt_platform.py`). So at every - `.FTZ` site the hardware already does what SASS does; the helpers make that explicit and independent of the GPU. - At basalt's IEEE sites (no `.ftz`) the same flushing is a difference, treated in section 3. +- **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. `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, + multiplies and fmas, but not at the `.FTZ` absolute value and maximum (`abs.ftz` and the amax butterfly's + `FMNMX.FTZ`, section 1): the helpers flush explicitly, 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 @@ -147,9 +151,10 @@ Built with nvcc's defaults. `q8_1_store` runs the two butterflies in one loop (` | `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, max and division do (Notation), so a literal port would differ from CUDA on -subnormal values: a subnormal activation would drop out of amax and 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 +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 diff --git a/kernels/common/basalt_fp.metal b/kernels/common/basalt_fp.metal index 7646930b..ad7308f9 100644 --- a/kernels/common/basalt_fp.metal +++ b/kernels/common/basalt_fp.metal @@ -13,7 +13,9 @@ // - 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, then the result flushed. +// value: the operation on flushed inputs, correctly rounded, then the result flushed. 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 diff --git a/kernels/common/basalt_q8_1.metal b/kernels/common/basalt_q8_1.metal index 742dcb7f..b45b07fb 100644 --- a/kernels/common/basalt_q8_1.metal +++ b/kernels/common/basalt_q8_1.metal @@ -17,7 +17,8 @@ // - 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, max and division +// 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. diff --git a/tests/kernels/basalt_emu.py b/tests/kernels/basalt_emu.py index 3703a312..7a03b177 100644 --- a/tests/kernels/basalt_emu.py +++ b/tests/kernels/basalt_emu.py @@ -44,6 +44,10 @@ def fma_ftz(a, b, c): 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"): @@ -101,7 +105,7 @@ def q8_1_pack(d, s, codes): 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)), lambda p, q: np.fmax(ftz(p), ftz(q))) + 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"): diff --git a/tests/kernels/test_basalt_platform.py b/tests/kernels/test_basalt_platform.py index 382c2205..03957285 100644 --- a/tests/kernels/test_basalt_platform.py +++ b/tests/kernels/test_basalt_platform.py @@ -12,6 +12,7 @@ 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)]], @@ -19,14 +20,21 @@ 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]; - out[8 * i + 0] = x + y; - out[8 * i + 1] = x * y; - out[8 * i + 2] = fma(x, y, z); - out[8 * i + 3] = x / y; - out[8 * i + 4] = x * y + z; - out[8 * i + 5] = fmax(x, y); - out[8 * i + 6] = fabs(x); - out[8 * i + 7] = add_ftz(x, y) + mul_ftz(x, y) * 0.0f + fma_ftz(x, y, z) * 0.0f; + 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); } """ @@ -36,9 +44,9 @@ def run_ops(a, b, c, pragma=True): 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, {}), "ops") + pso = nt.Pipeline(nt.Library(dev, src, {"NCOL": str(NCOL)}), "ops") n = len(a) - out = nt.Buffer(dev, 32 * n) + 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): @@ -46,7 +54,7 @@ def run_ops(a, b, c, pragma=True): 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, 32 * n), F32).reshape(n, 8) + return np.frombuffer(out.read(0, 4 * NCOL * n), F32).reshape(n, NCOL) def normals(rng, n, lo=100, hi=154): @@ -83,35 +91,66 @@ def test_rounding_is_to_nearest_even(): assert np.count_nonzero((a + b).astype(np.float64) != a.astype(np.float64) + b) > n // 4 -def test_subnormals_flush_in_safe_mode(): - """Measured: add, multiply, fma, division and fmax flush a subnormal input and a subnormal result to the zero of - its sign (MSL section 8.1 permits it); fabs and moves keep the bits. The *_ftz helpers flush either way.""" - s = F32(1.5e-39) # subnormal +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. 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 - a = np.array([s, -s, s, m, m, s, m], F32) - b = np.array([F32(1.0), F32(1.0), m, F32(0.5), F32(0.5), F32(0.0), F32(2.0)], F32) - c = np.array([F32(0.0), F32(0.0), F32(0.0), F32(0.0), F32(0.0), F32(0.0), F32(0.0)], F32) - got = run_ops(a, b, c) + 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)], F32) + got = run_ops(rows[:, 0], rows[:, 1], rows[:, 2]) bits = got.view(np.uint32) - assert bits[0, 1] == 0 and bits[1, 1] == 0x80000000 # s * 1, -s * 1: input flushed (signed) - assert bits[0, 2] == 0 and bits[0, 3] == 0 # fma(s, 1, 0), s / 1 - assert got[2, 0] == m # s + m = m: input flushed - assert bits[3, 1] == 0 and bits[6, 3] == 0 # m * 0.5, m / 2: subnormal result flushed - assert bits[3, 2] == 0 and bits[3, 4] == 0 # fma(m, 0.5, 0), m * 0.5 + 0 - assert bits[5, 5] == 0 # fmax(s, 0) - assert bits[0, 6] == s.view(np.uint32) and bits[1, 6] == s.view(np.uint32) # fabs keeps a subnormal - assert got[6, 1] == F32(2.0 ** -125) # normal results are untouched + 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 + # 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), and reciprocals that underflow. On this GPU the + arithmetic flushes anyway (test_subnormals_in_safe_mode); fmax and fabs do not, so max_ftz and abs_ftz carry it.""" rng = np.random.default_rng(2) - n = 1 << 18 + 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[: n // 8] = (rng.integers(0, 1 << 23, n // 8, dtype=np.uint32) | (rng.integers(0, 2, n // 8, dtype=np.uint32) << 31)).view(F32) + 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 got = run_ops(a, b, c) - with np.errstate(under="ignore"): - want = emu.add_ftz(a, b) + emu.mul_ftz(a, b) * F32(0.0) + emu.fma_ftz(a, b, c) * F32(0.0) - assert np.array_equal(got[:, 7].view(np.uint32), emu.ftz(want).view(np.uint32)) + 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]) @@ -155,4 +194,5 @@ def test_half_conversions(): 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 From 0363d5ea8de54d5965ef399fea380803a20ff6bf Mon Sep 17 00:00:00 2001 From: Lance Woodson <65194841+woodsonl@users.noreply.github.com> Date: Sat, 17 Oct 2026 03:11:29 -0500 Subject: [PATCH 26/74] Pre-fill mmvq test outputs apart and give column invariance a 2-row tail The port of mmvq_multi_parity's Q8_0 one-column section dropped basalt's output pre-fills. Basalt fills the one-column output with 0xff and the two-column output with 0xfe (mmvq_multi_parity.cpp:426-427), so a row that neither call writes cannot pass `diff == 0` (:461). In the port, both outputs came from fresh allocations with identical bytes. basalt_gpu.run gains a fill byte for the buffers it allocates from a byte count, and mmvq passes it through. Fills used: - test_q8_0_one_column: basalt's 0xff and 0xfe. - test_mmvq_multi_parity, its negative control and test_column_invariance: multi side 0xff, single side 0xfe. These are a strengthening; basalt's main sweep does not pre-fill. 0xff on the multi side is NaN, so a row the control's layout leaves unwritten fails the non-finite check instead of counting as the control's power. Checked with a mutant whose store guard skips the last row: all four tests now catch it. Before, test_column_invariance passed it, because both sides read the same fresh bytes. test_column_invariance used n_out 70, which is even. The 2-row layouts (the multi-column small-K launch) therefore never had a partial last threadgroup, despite the comment "a row tail for every ROWS". n_out 71 leaves a tail for both 2 and 4 rows. The four basalt test files: 61 passed, 0 failed, 0 skipped. --- tests/kernels/basalt_gpu.py | 14 +++++++++----- tests/kernels/test_basalt_mmvq.py | 16 +++++++++------- 2 files changed, 18 insertions(+), 12 deletions(-) diff --git a/tests/kernels/basalt_gpu.py b/tests/kernels/basalt_gpu.py index eb120bab..181d9f17 100644 --- a/tests/kernels/basalt_gpu.py +++ b/tests/kernels/basalt_gpu.py @@ -18,11 +18,14 @@ 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): +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.""" + 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) @@ -48,13 +51,14 @@ def q8_1(x, kind="native", up=None): return np.frombuffer(out[-1], np.uint8) -def mmvq(type_id, w, xq, n_in, n_out, ncols, upstream=False): - """``basalt_mmvq`` in basalt's launch for ``ncols`` columns (``upstream``: the negative control's layout).""" +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) + 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) diff --git a/tests/kernels/test_basalt_mmvq.py b/tests/kernels/test_basalt_mmvq.py index b6c78ac2..7e65869b 100644 --- a/tests/kernels/test_basalt_mmvq.py +++ b/tests/kernels/test_basalt_mmvq.py @@ -59,8 +59,10 @@ 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) - multi = gpu.mmvq(type_id, w, xq, n_in, n_out, t, upstream=upstream) - single = np.stack([gpu.mmvq(type_id, w, columns(xq, n_in, j), n_in, n_out, 1)[0] for j in range(t)]) + # 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 @@ -109,8 +111,8 @@ def test_q8_0_one_column(geom): 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)[0] - b = gpu.mmvq(8, w, xq, n_in, n_out, 2)[0] + 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)) @@ -199,14 +201,14 @@ 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 = 70 # a row tail for every ROWS + 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)[0] for j in range(8)]) + 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) + 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) From 32a1762d9b9846e08152e0bed3ce5c2e1fde858e Mon Sep 17 00:00:00 2001 From: Lance Woodson <65194841+woodsonl@users.noreply.github.com> Date: Sat, 17 Oct 2026 03:11:52 -0500 Subject: [PATCH 27/74] Credit basalt and ggml in the test files that carry their code Review of PR 10 found four test files carrying basalt or ggml code with no licence header, provenance line or NOTICE entry, which CLAUDE.md and CONTRIBUTING.md:54-56 require. tools/ci/hygiene.py does not check provenance, so it passed anyway. Each file now gets the SPDX and copyright lines used on test_basalt_iq_parity.py, a provenance line "adapted from @ ", and a NOTICE entry: - test_basalt_mmvq.py ports mmvq_multi_parity.cpp: its cases with scale offsets, sane_half, widths, seeds and Q8_0 geometries, compare_q80's float64 reference, its output pre-fills and its pass criteria. - test_basalt_q8_1.py ports iq_multi_parity.cpp's check_q8_1_finite: the planted blocks, the host transcription and the pass criterion. - test_basalt_platform.py quotes and enforces elementwise_parity.cpp's contraction criterion. The same rule covers test_basalt_iq_parity.py's pass criterion. - basalt_emu.py has two sources. From basalt: the iteration traits and the quantizers' and kernels' arithmetic. From ggml, through basalt: kvalues_iq4nl, get_scale_min_k4 and the q8_1 rule. It is listed under both sections of NOTICE. Comments and NOTICE only; hygiene passes. --- tests/kernels/basalt_emu.py | 7 +++++++ tests/kernels/test_basalt_mmvq.py | 5 +++++ tests/kernels/test_basalt_platform.py | 4 ++++ tests/kernels/test_basalt_q8_1.py | 4 ++++ third_party/NOTICE | 15 +++++++++++++++ 5 files changed, 35 insertions(+) diff --git a/tests/kernels/basalt_emu.py b/tests/kernels/basalt_emu.py index 7a03b177..5b6a8331 100644 --- a/tests/kernels/basalt_emu.py +++ b/tests/kernels/basalt_emu.py @@ -1,3 +1,10 @@ +# 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 and +# include/basalt/kernels/q8_1_finite.hpp @ b4c63b55754637f4c72ad53a0f791d425f71eb36, which adapt ggml-org/llama.cpp +# ggml/src/ggml-common.h (kvalues_iq4nl), ggml/src/ggml-quants.c (get_scale_min_k4) and ggml/src/ggml-cuda/quantize.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: numpy's float32 add, multiply and divide do; ``fma32`` does by rounding the exact float64 sum to odd before the float32 cast. The diff --git a/tests/kernels/test_basalt_mmvq.py b/tests/kernels/test_basalt_mmvq.py index 7e65869b..bcde0a43 100644 --- a/tests/kernels/test_basalt_mmvq.py +++ b/tests/kernels/test_basalt_mmvq.py @@ -1,3 +1,8 @@ +# 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, diff --git a/tests/kernels/test_basalt_platform.py b/tests/kernels/test_basalt_platform.py index 03957285..403fcacb 100644 --- a/tests/kernels/test_basalt_platform.py +++ b/tests/kernels/test_basalt_platform.py @@ -1,3 +1,7 @@ +# 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 diff --git a/tests/kernels/test_basalt_q8_1.py b/tests/kernels/test_basalt_q8_1.py index 72a882ed..20f2b590 100644 --- a/tests/kernels/test_basalt_q8_1.py +++ b/tests/kernels/test_basalt_q8_1.py @@ -1,3 +1,7 @@ +# 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) diff --git a/third_party/NOTICE b/third_party/NOTICE index 7a894550..a188a075 100644 --- a/third_party/NOTICE +++ b/third_party/NOTICE @@ -96,6 +96,9 @@ Format: `` — adapted from / copied from `` `` @ - `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`. +- `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` and the q8_1 rule of `ggml/src/ggml-cuda/quantize.cu`, + re-implemented in numpy (MIT). License: `third_party/GGML-LICENSE`. ## basalt (jesdga95/basalt @ `b4c63b55754637f4c72ad53a0f791d425f71eb36`, MIT) @@ -123,6 +126,18 @@ Format: `` — adapted from / copied from `` `` @ - `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`. +- `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` 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`). License: + `third_party/BASALT-LICENSE`. ## Test data From 7c6ba4143c12bb12760e5adffbd134b9096b2019 Mon Sep 17 00:00:00 2001 From: Lance Woodson <65194841+woodsonl@users.noreply.github.com> Date: Sat, 17 Oct 2026 03:12:47 -0500 Subject: [PATCH 28/74] Rewrap matvec.md section 3's paragraph after the fmax correction The correction in f6dd07d left one line of the paragraph past the file's 120-column wrap. Whitespace only. --- docs/research/basalt-nvcc/matvec.md | 10 +++++----- 1 file changed, 5 insertions(+), 5 deletions(-) diff --git a/docs/research/basalt-nvcc/matvec.md b/docs/research/basalt-nvcc/matvec.md index 053d60dc..ecd57aee 100644 --- a/docs/research/basalt-nvcc/matvec.md +++ b/docs/research/basalt-nvcc/matvec.md @@ -154,11 +154,11 @@ Built with nvcc's defaults. `q8_1_store` runs the two butterflies in one loop (` 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. +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 From 14eb4b0f1d22c436dbf0d1f4ccf71a2080ce70f9 Mon Sep 17 00:00:00 2001 From: Lance Woodson <65194841+woodsonl@users.noreply.github.com> Date: Sat, 17 Oct 2026 03:49:22 -0500 Subject: [PATCH 29/74] Record nvcc's arithmetic for basalt's routed-expert kernels Add docs/research/basalt-nvcc/experts.md, the authority the Metal port of native_expert_grouped follows for the Q2_0 / Q2_0 experts (flash-next.md, invariant 5). It reads every rounding site of the gate/up kernels (native_gu2_kernel, native_gu_multi_kernel), the SwiGLU product with its IEEE q8_1 (swiglu_q8_1_entries_pdl_kernel) and the down kernel (native_down_multi_kernel, 16-lane and generic paths) from the sm_120 PTX and SASS of NVCC 13.0 and 13.3, compiled on Compiler Explorer with iq_kernels.cu's own flags (nvcc's IEEE defaults). The kernels carry no .FTZ. The page shows that no subnormal can reach the matrix-vector parts or the SwiGLU quotient (every value is a multiple of 2^-48, the quotient is at least 2.6e-37), so Metal's plain operations give the IEEE result there, and that the SwiGLU product can be subnormal, which the port emulates. --- docs/research/basalt-nvcc/experts.md | 186 +++++++++++++++++++++++++++ 1 file changed, 186 insertions(+) create mode 100644 docs/research/basalt-nvcc/experts.md diff --git a/docs/research/basalt-nvcc/experts.md b/docs/research/basalt-nvcc/experts.md new file mode 100644 index 00000000..a57142a8 --- /dev/null +++ b/docs/research/basalt-nvcc/experts.md @@ -0,0 +1,186 @@ +# 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). No instruction of these kernels carries +`.FTZ`: they are IEEE operations, 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 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 the same) | 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 the same templates. + +| 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` | `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) become byte offsets into one +buffer of blobs; the plan's other arrays, the scratch and the output keep basalt's layout. From 5a81cb385149a763c8a2aed59b2ccc4d2cc9c1b7 Mon Sep 17 00:00:00 2001 From: Lance Woodson <65194841+woodsonl@users.noreply.github.com> Date: Sat, 17 Oct 2026 07:44:52 -0500 Subject: [PATCH 30/74] Port basalt's Q2_0 routed-expert kernels to Metal kernels/common/basalt_experts.metal holds native_expert_grouped's three dispatches for Q2_0 gate/up and Q2_0 down, in the rounding sequence nvcc compiles for iq_kernels.cu (docs/research/basalt-nvcc/experts.md): - basalt_expert_gu: native_gu2_kernel (two rows a SIMD-group, n_embd 2560) or native_gu_multi_kernel (one row a SIMD-group), macro GU2; - basalt_expert_swiglu_q8_1: the SwiGLU product with the IEEE q8_1 store over the call's own entries; - basalt_expert_down: row_dot_20_sub16 on q8_1 rows staged in threadgroup memory at n_ff 640, else row_dot_multi, macro SUB16. The plan is basalt's, read on the device; grp_ptr becomes byte offsets into one buffer of blobs. fma() stands exactly at SASS's FFMA sites; the SwiGLU product, which can be subnormal, goes through a new ieee_mul (exact integer product of the significands), next to ieee_add. The Q2_0 decode, the q8_1 word readers, a plain warp_sum and the IEEE-build __expf move into basalt_fp.metal so native_mmvq and the experts share one copy; basalt_mmvq.metal now calls them. Builders in monolith/kernels.py follow basalt's launcher (gu2_usable, d_rows, gy). The first test builds every variant and checks a call writes finite rows and leaves the others untouched. NOTICE entries under ggml and basalt. --- kernels/common/basalt_experts.metal | 301 +++++++++++++++++++++++++++ kernels/common/basalt_fp.metal | 53 ++++- kernels/common/basalt_mmvq.metal | 27 +-- kernels/common/basalt_q8_1.metal | 32 +++ monolith/kernels.py | 61 ++++++ tests/kernels/basalt_gpu.py | 56 +++++ tests/kernels/test_basalt_experts.py | 52 +++++ third_party/NOTICE | 12 ++ 8 files changed, 568 insertions(+), 26 deletions(-) create mode 100644 kernels/common/basalt_experts.metal create mode 100644 tests/kernels/test_basalt_experts.py diff --git a/kernels/common/basalt_experts.metal b/kernels/common/basalt_experts.metal new file mode 100644 index 00000000..b15c32d7 --- /dev/null +++ b/kernels/common/basalt_experts.metal @@ -0,0 +1,301 @@ +// 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 grp_off[g] bytes into +// `blobs` (basalt's grp_ptr[g], a pointer, here an offset into one buffer of blobs) 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. +// +// - 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] = sA[c]; + if (lane == 2 * c + 1) dst[(e + c) * n_ff + r + 1] = sB[c]; + } + } +} +#endif + +kernel void basalt_expert_gu(device const ushort* blobs [[buffer(0)]], device const ulong* grp_off [[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 = blobs + (grp_off[g] + 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 = blobs + (grp_off[g] + 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] = 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] = 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] = 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 ushort* blobs [[buffer(0)]], device const ulong* grp_off [[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 = blobs + (grp_off[g] + 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] = 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] = 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] = 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 = blobs + (grp_off[g] + 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] = s[c]; + } + } + } +#endif +} diff --git a/kernels/common/basalt_fp.metal b/kernels/common/basalt_fp.metal index ad7308f9..17406eea 100644 --- a/kernels/common/basalt_fp.metal +++ b/kernels/common/basalt_fp.metal @@ -1,7 +1,8 @@ // 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, include/basalt/kernels/dp4a.hpp and -// include/basalt/kernels/q8_1_finite.hpp @ b4c63b55754637f4c72ad53a0f791d425f71eb36 (MIT; third_party/NOTICE), +// Adapted from basalt (jesdga95/basalt) 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 +// @ 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). // @@ -19,9 +20,13 @@ // - 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). +// 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: CUDA's two 16-bit loads, __dp4a, __byte_perm (3-bit selectors) and // __vsubss4 as exact integer arithmetic. +// - 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. #pragma STDC FP_CONTRACT OFF static inline float ftz(float x) { @@ -45,6 +50,16 @@ 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)); } // fp16 field to fp32 (exact): CUDA's __half2float / __low2float, HADD2.F32 in SASS. static inline float h2f(ushort h) { return float(as_type(h)); } @@ -80,3 +95,35 @@ 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)); } + +// 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; +} diff --git a/kernels/common/basalt_mmvq.metal b/kernels/common/basalt_mmvq.metal index a24296c5..ddc5fa46 100644 --- a/kernels/common/basalt_mmvq.metal +++ b/kernels/common/basalt_mmvq.metal @@ -39,10 +39,7 @@ struct MmvqParams { uint n_in; uint n_out; uint pad0; uint pad1; }; -// q8_1 block b of a column: 9 words, word 0 the fp16 pair (d, s), words 1..8 the codes -static inline float q8_d(device const uint* x, int b) { return h2f(ushort(x[9 * b] & 0xffffu)); } -static inline float q8_s(device const uint* x, int b) { return h2f(ushort(x[9 * b] >> 16)); } -static inline int q8_w(device const uint* x, int b, int k) { return int(x[9 * b + 1 + k]); } +// q8_d, q8_s, q8_w (a q8_1 block's scale, sum and code words) are basalt_fp.metal's. // native_mmvq.cu:441-457: the IQ4 codebook as four words and its two-stage byte lookup static inline int2 iq4_table_lookup(int q4) { @@ -124,26 +121,10 @@ static inline float apply_acc(float tmp, thread const Wt& r, device const uint* #define BPI 64 #define BLOCK_BYTES 18 static inline int kqs_of(int tid) { return tid % 2; } -struct Wt { int qx[4]; int qy[4]; float d2; }; -static inline Wt wload(device const ushort* blk, int iqs) { - Wt r; - r.d2 = h2f(blk[0]); - for (int j = 0; j < 4; ++j) { - const int q = int(short(blk[1 + iqs * 4 + j])); // qs read as int16 (2-byte aligned block) - 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; -} +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) { - int sumi = 0; - for (int j = 0; j < 4; ++j) { - sumi = dp4a(q8_w(x, iqs, j * 2), r.qx[j], sumi); - sumi = dp4a(q8_w(x, iqs, j * 2 + 1), r.qy[j], sumi); - } - return fma_ftz(mul_ftz(r.d2, q8_d(x, iqs)), float(sumi), tmp); // d2 * d8 * sumi into tmp += + 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 diff --git a/kernels/common/basalt_q8_1.metal b/kernels/common/basalt_q8_1.metal index b45b07fb..bfd241ad 100644 --- a/kernels/common/basalt_q8_1.metal +++ b/kernels/common/basalt_q8_1.metal @@ -92,6 +92,38 @@ static inline float ieee_add(float a, float b) { return ieee_down64(ieee_up64(a) + ieee_up64(b)); } +// a * b with IEEE subnormals, for finite a and b (CUDA's mul.rn.f32 in an IEEE-built kernel). Normal operands with a +// product of at least 2^-125 take the hardware's correctly rounded product; otherwise (a subnormal operand, which the +// hardware flushes, or a product it 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; // also inf and NaN + const uint sign = (ab ^ bb) & 0x80000000u; + if ((ea | ma) == 0u || (eb | mb) == 0u) 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 +} + 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; diff --git a/monolith/kernels.py b/monolith/kernels.py index e5d42d5b..8d1f5219 100644 --- a/monolith/kernels.py +++ b/monolith/kernels.py @@ -314,6 +314,67 @@ 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.""" + 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) + + DEQUANT_TYPES = (11, 20, 23, 42) # Q3_K, IQ4_NL, IQ4_XS, Q2_0: basalt's dequantizers for the types iq_parity checks diff --git a/tests/kernels/basalt_gpu.py b/tests/kernels/basalt_gpu.py index 181d9f17..769f3d97 100644 --- a/tests/kernels/basalt_gpu.py +++ b/tests/kernels/basalt_gpu.py @@ -62,6 +62,62 @@ def mmvq(type_id, w, xq, n_in, n_out, ncols, upstream=False, fill=None): 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): + """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, ``grp_off`` each group's byte offset into them (basalt's + grp_ptr); ``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()) + + b_blobs = nt.Buffer(dev, np.ascontiguousarray(blobs, np.uint8).tobytes()) + b_off = arr(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_blobs, b_off, b_start, b_ng, b_tok, b_xq, b_gate, b_up)): + d1 = d1.buffer(k, 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_blobs, b_off, b_start, b_ng, b_dst, b_hq, b_out)): + d3 = d3.buffer(k, 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 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", diff --git a/tests/kernels/test_basalt_experts.py b/tests/kernels/test_basalt_experts.py new file mode 100644 index 00000000..f072cbcb --- /dev/null +++ b/tests/kernels/test_basalt_experts.py @@ -0,0 +1,52 @@ +# 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:68-87, native_grouped_parity.cpp:73-99); 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.kernels import basalt_gpu as gpu + +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) diff --git a/third_party/NOTICE b/third_party/NOTICE index a188a075..356ce62d 100644 --- a/third_party/NOTICE +++ b/third_party/NOTICE @@ -96,6 +96,9 @@ Format: `` — adapted from / copied from `` `` @ - `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`. - `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` and the q8_1 rule of `ggml/src/ggml-cuda/quantize.cu`, re-implemented in numpy (MIT). License: `third_party/GGML-LICENSE`. @@ -123,6 +126,15 @@ Format: `` — adapted from / copied from `` `` @ - `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`). `basalt_fp.metal` also takes `Split<42>` and `warp_sum` from + `iq_kernels.cu`. 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_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`. From 17f0ec8041d99ca25bedc12c1313ded9b61f1547 Mon Sep 17 00:00:00 2001 From: Lance Woodson <65194841+woodsonl@users.noreply.github.com> Date: Sat, 17 Oct 2026 07:47:48 -0500 Subject: [PATCH 31/74] Port basalt's grouped-expert parity tests and emulate the experts basalt_emu.py gains q2_0_dots (row_dot_multi's order: lane k % 32 takes call k, fma(fl(d2 * d8), f(sumi), s) from +0, then the 32-lane butterfly) and swiglu_q8_1 (t, the IEEE quotient and product with subnormals, the IEEE quantizer), per experts.md. test_basalt_experts.py ports iq_multi_parity's check_grouped (9 groups of {1, 3, 4, 5, 0, 8, 2, 11, 1}, 8 tokens, spare grid rows and cap entries, NaN rows) and native_grouped_parity at 512 x 256 and, as its --gu2 run, 2560 x 640 (plans from entry 0 and 7, grid_groups 0..4 and cap + 3, stale scratch). Each comparison basalt makes between two of its own kernel variants becomes the grouped call against the same kernels one entry a call, every float compared; the two gate/up kernels and the two down trees are also compared with each other, and every stage of every call is checked bit for bit against the emulation, with the exponential taken from the GPU's expf_neg. --- tests/kernels/basalt_emu.py | 37 ++++++ tests/kernels/test_basalt_experts.py | 172 +++++++++++++++++++++++++++ 2 files changed, 209 insertions(+) diff --git a/tests/kernels/basalt_emu.py b/tests/kernels/basalt_emu.py index 5b6a8331..539e3845 100644 --- a/tests/kernels/basalt_emu.py +++ b/tests/kernels/basalt_emu.py @@ -292,3 +292,40 @@ def mmvq(type_id, w, xq, n_in, n_out, ncols, nw=4, row_chunk=64): 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) diff --git a/tests/kernels/test_basalt_experts.py b/tests/kernels/test_basalt_experts.py index f072cbcb..3babd4c1 100644 --- a/tests/kernels/test_basalt_experts.py +++ b/tests/kernels/test_basalt_experts.py @@ -16,6 +16,7 @@ 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 @@ -50,3 +51,174 @@ def test_every_variant_builds_and_runs(n_embd, n_ff): 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:117), + groups of ``sizes`` entries from entry ``base`` on, each group its own blob while there are enough (plan_sizes, + :163-191), 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.""" + 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) + out[d] = r["out"][d].view(np.uint32) + 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 (:248-275); 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 (:290-291) + 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:207-247, 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). 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) + ref = c.per_entry() + 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") From 5c0b0d026eeca35537a9e8f66359489afcd06682 Mon Sep 17 00:00:00 2001 From: Lance Woodson <65194841+woodsonl@users.noreply.github.com> Date: Sat, 17 Oct 2026 07:48:53 -0500 Subject: [PATCH 32/74] Test the SwiGLU product's IEEE subnormals on planted values test_ieee_mul_keeps_subnormals checks ieee_mul against numpy's IEEE float32 product on 65,610 pairs, 13,643 of them subnormal: the 2^-126 boundary, grid ties, products below half the smallest subnormal, signed zeros and subnormal operands. test_swiglu_q8_1_edges runs the SwiGLU + q8_1 dispatch alone on very negative gates with small up values (211 subnormal products), overflowing exponentials, large and zero gates and the GEMV's 2^-48 grid, bit for bit against the emulation, and checks it leaves the q8_1 blocks outside the call's entries untouched. --- tests/kernels/test_basalt_experts.py | 67 ++++++++++++++++++++++++++++ 1 file changed, 67 insertions(+) diff --git a/tests/kernels/test_basalt_experts.py b/tests/kernels/test_basalt_experts.py index 3babd4c1..825ec2ec 100644 --- a/tests/kernels/test_basalt_experts.py +++ b/tests/kernels/test_basalt_experts.py @@ -222,3 +222,70 @@ def test_native_grouped_parity(n_embd, n_ff): # 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 ------------------------------------------------------------------------ + +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, and normal products.""" + 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 * (k + 0.5) 2^-74: grid ties + 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))] + 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 ** -74), 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"): + want = pa * pb + sub = np.count_nonzero((np.abs(want) < F32(2.0 ** -126)) & (want != 0)) + assert np.array_equal(got.view(np.uint32), want.view(np.uint32)), np.flatnonzero(got.view(np.uint32) != want.view(np.uint32))[:8] + assert sub > 1000 # the subnormal path ran + print(f"\nieee_mul: {pa.size} products bit for bit, {sub} of them subnormal") + + +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. 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) + 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) + assert np.array_equal(hq[per: 5 * per], emu.swiglu_q8_1(g, up, gpu_expf_neg(g))) + with np.errstate(over="ignore", under="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") From bc4f122157025714ccfbd2ac1cf4692a49c67efc Mon Sep 17 00:00:00 2001 From: Lance Woodson <65194841+woodsonl@users.noreply.github.com> Date: Sat, 17 Oct 2026 07:49:39 -0500 Subject: [PATCH 33/74] Check the routed experts against float64 references test_stages_against_float64 holds each stage of check_grouped's call (gate and up on the tokens' q8_1 rows, down on the GPU's q8_1 of the SwiGLU product) to iq_multi_parity's check_mmvq bound, rel < 1e-2, over the GPU dequantizer's weights and the dequantized q8_1 rows (measured 6.7e-8). test_whole_expert_against_float64 is the contract's reference for native_expert_grouped: the whole expert on fp32 activations, built as native_expert_parity.cpp builds it, with its criterion eg < 3e-2 (measured 1.26e-2). Both cross-check the dequantizer against gguf-py's dequantize_row_q2_0. --- tests/kernels/test_basalt_experts.py | 82 ++++++++++++++++++++++++++++ 1 file changed, 82 insertions(+) diff --git a/tests/kernels/test_basalt_experts.py b/tests/kernels/test_basalt_experts.py index 825ec2ec..7ce31092 100644 --- a/tests/kernels/test_basalt_experts.py +++ b/tests/kernels/test_basalt_experts.py @@ -16,8 +16,10 @@ 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 @@ -289,3 +291,83 @@ def test_swiglu_q8_1_edges(): 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:100-110).""" + 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 = {} + 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 + 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() + rel[part] = num / (den + 1e-30) + # basalt: if (diff != 0 || !finite || !(rel < 1e-2)) { + assert finite and rel[part] < 1e-2, (part, rel[part]) + print("\nstages against float64: " + ", ".join(f"{k} rel {v:.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 by ggml's + dequantize_row_q2_0; 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 = (gpu.dequant(42, blob[o: o + n], rows * cols).reshape(rows, cols).astype(np.float64) + for o, n, rows, cols in ((0, lay["up_off"], n_ff, n_embd), (lay["up_off"], lay["up_off"], n_ff, n_embd), + (lay["down_off"], n_embd * lay["d_row"], n_embd, n_ff))) + 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 + raw = blob[: 64 * lay["gu_row"]].reshape(64, -1) + assert np.array_equal(G[:64].astype(F32), gguf_reference.dequantize(42, raw)) From f414a398e977f84510a0e88c60b34278ea77f2d0 Mon Sep 17 00:00:00 2001 From: Lance Woodson <65194841+woodsonl@users.noreply.github.com> Date: Sat, 17 Oct 2026 07:50:29 -0500 Subject: [PATCH 34/74] Point invariant 5 at experts.md and record the down kernel's DEP check flash-next.md's invariant 5 lists experts.md with matvec.md and dequant.md. experts.md states that 13.0 has the SwiGLU kernel's SASS lines as quoted, that native_down_multi_kernel<42, true> and <42, false> have identical template multisets in each version, and which tests check the page. --- docs/design/flash-next.md | 2 +- docs/research/basalt-nvcc/experts.md | 11 +++++++++-- 2 files changed, 10 insertions(+), 3 deletions(-) diff --git a/docs/design/flash-next.md b/docs/design/flash-next.md index f162bf4b..fcadd776 100644 --- a/docs/design/flash-next.md +++ b/docs/design/flash-next.md @@ -103,7 +103,7 @@ ones this pack runs. (`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): which multiply-adds fuse and + dequantizers, `experts.md` for the routed experts): 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 diff --git a/docs/research/basalt-nvcc/experts.md b/docs/research/basalt-nvcc/experts.md index a57142a8..8027c7fa 100644 --- a/docs/research/basalt-nvcc/experts.md +++ b/docs/research/basalt-nvcc/experts.md @@ -118,7 +118,7 @@ The value, quoted: `const float h = __fmul_rn(g / (1.0f + __expf(-g)), up[i]); q 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 the same) | Metal | +| 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` | @@ -150,7 +150,8 @@ Notes: 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 the same templates. +`<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 | |---|---|---|---|---|---| @@ -184,3 +185,9 @@ because no subnormal reaches them, except the SwiGLU product (`ieee_mul`) and th 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) become byte offsets into one buffer of blobs; 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 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. From 46aabb40ddd6754b2ab4c6a7ba19eb7c752c2757 Mon Sep 17 00:00:00 2001 From: Lance Woodson <65194841+woodsonl@users.noreply.github.com> Date: Sat, 17 Oct 2026 07:56:15 -0500 Subject: [PATCH 35/74] Compare gu2 with the one-row gate/up kernel in every --gu2 call basalt's native_grouped_parity --gu2 run checks native_gu2_kernel against v1, whose gate/up takes native_gu_multi_kernel. The 2560 x 640 port now takes its per-entry comparand on the one-row kernel too, so all 84 calls (both plan bases, every grid_groups, stale scratch) cross the kernel switch. test_stages_against_float64 also holds each entry, not only the call, to rel < 1e-2 (worst entry 7.45e-8). --- tests/kernels/test_basalt_experts.py | 19 ++++++++++++------- 1 file changed, 12 insertions(+), 7 deletions(-) diff --git a/tests/kernels/test_basalt_experts.py b/tests/kernels/test_basalt_experts.py index 7ce31092..84a85076 100644 --- a/tests/kernels/test_basalt_experts.py +++ b/tests/kernels/test_basalt_experts.py @@ -194,7 +194,8 @@ def test_native_grouped_parity(n_embd, n_ff): 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). Criteria, quoted: ``for (size_t i = 0; i < + 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.""" @@ -212,7 +213,8 @@ def test_native_grouped_parity(n_embd, n_ff): 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) - ref = c.per_entry() + # 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) @@ -311,10 +313,11 @@ def test_stages_against_float64(): c = grouped_case() r = c.run() blk = kernels.Q8_1_BLOCK_BYTES - rel = {} + 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: @@ -330,10 +333,12 @@ def test_stages_against_float64(): finite = finite and np.isfinite(y).all() num += np.abs(y - ref).sum() den += np.abs(ref).sum() - rel[part] = num / (den + 1e-30) - # basalt: if (diff != 0 || !finite || !(rel < 1e-2)) { - assert finite and rel[part] < 1e-2, (part, rel[part]) - print("\nstages against float64: " + ", ".join(f"{k} rel {v:.2e}" for k, v in rel.items())) + 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)) From 366b8bec7b154da67688c4f06c4270c1a2fb2895 Mon Sep 17 00:00:00 2001 From: Lance Woodson <65194841+woodsonl@users.noreply.github.com> Date: Sat, 17 Oct 2026 10:44:12 -0500 Subject: [PATCH 36/74] Give ieee_mul IEEE's result for infinities and NaN against zeros ieee_mul stands in for basalt's __fmul_rn (mul.rn.f32, SASS FMUL) in the SwiGLU product. A zero operand returned its signed zero before any check for exponent 255, so NaN * 0, inf * 0 and their mirrors came out as +-0 where CUDA gives NaN, and inf times a subnormal went through the integer rebuild. A NaN or inf fp16 scale in an expert's gate or up rows reaches it: basalt's down output is NaN, the port's was zeros. An operand with exponent 255 against a zero or a subnormal (the only case the hardware product cannot serve, since it flushes the subnormal) now returns CUDA's canonical NaN 0x7fffffff for a NaN or a zero operand and the signed infinity otherwise. test_ieee_mul_keeps_subnormals plants 0 * inf, NaN * 0, inf and NaN against subnormals, and its grid ties are now ties: the factor 2^-75 makes the products (k + 0.5) 2^-149 (the old 2^-74 gave odd multiples of 2^-149, all exact); the test counts 68 ties. test_swiglu_q8_1_edges plants five NaN products in one block and a whole block of inf * 0 inside the dispatched entries and compares their q8_1 bytes with the emulation, a NaN half as NaN (test_basalt_q8_1's convention). Both tests fail on the previous ieee_mul and pass on this one. --- kernels/common/basalt_q8_1.metal | 21 ++++++++----- tests/kernels/test_basalt_experts.py | 46 ++++++++++++++++++++-------- 2 files changed, 48 insertions(+), 19 deletions(-) diff --git a/kernels/common/basalt_q8_1.metal b/kernels/common/basalt_q8_1.metal index bfd241ad..1e1d27af 100644 --- a/kernels/common/basalt_q8_1.metal +++ b/kernels/common/basalt_q8_1.metal @@ -92,18 +92,25 @@ static inline float ieee_add(float a, float b) { return ieee_down64(ieee_up64(a) + ieee_up64(b)); } -// a * b with IEEE subnormals, for finite a and b (CUDA's mul.rn.f32 in an IEEE-built kernel). Normal operands with a -// product of at least 2^-125 take the hardware's correctly rounded product; otherwise (a subnormal operand, which the -// hardware flushes, or a product it 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). +// 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; // also inf and NaN + if (ea != 0u && eb != 0u && !(fabs(p) < 0x1p-125f)) return p; // p infinite or NaN included const uint sign = (ab ^ bb) & 0x80000000u; - if ((ea | ma) == 0u || (eb | mb) == 0u) return as_type(sign); + 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); diff --git a/tests/kernels/test_basalt_experts.py b/tests/kernels/test_basalt_experts.py index 84a85076..9bed2b20 100644 --- a/tests/kernels/test_basalt_experts.py +++ b/tests/kernels/test_basalt_experts.py @@ -233,19 +233,25 @@ def test_native_grouped_parity(n_embd, n_ff): 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, and normal products.""" + 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 * (k + 0.5) 2^-74: grid ties + 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))] + (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 ** -74), np.array([p[1] 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]]) { @@ -255,20 +261,26 @@ def test_ieee_mul_keeps_subnormals(): 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"): + 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)) - assert np.array_equal(got.view(np.uint32), want.view(np.uint32)), np.flatnonzero(got.view(np.uint32) != want.view(np.uint32))[:8] - assert sub > 1000 # the subnormal path ran - print(f"\nieee_mul: {pa.size} products bit for bit, {sub} of them subnormal") + 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. 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.""" + 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; a NaN's fp16 payload is the GPU's, 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), @@ -276,6 +288,10 @@ def test_swiglu_q8_1_edges(): 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 @@ -287,8 +303,14 @@ def test_swiglu_q8_1_edges(): 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) - assert np.array_equal(hq[per: 5 * per], emu.swiglu_q8_1(g, up, gpu_expf_neg(g))) - with np.errstate(over="ignore", under="ignore"): + 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 + assert np.array_equal(gh[~nan_h], wh[~nan_h]) and np.all((gh[nan_h] & 0x7C00) == 0x7C00) \ + and np.all(gh[nan_h] & 0x3FF), np.flatnonzero(np.any((gh != wh) & ~nan_h, 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 From f11c57b506c3da5f7edfe3dbbaf92be6c6336b5a Mon Sep 17 00:00:00 2001 From: Lance Woodson <65194841+woodsonl@users.noreply.github.com> Date: Sat, 17 Oct 2026 10:50:06 -0500 Subject: [PATCH 37/74] Build the whole-expert reference on the host codec and tighten per_entry test_whole_expert_against_float64 took its float64 weights from basalt_dequant_f32, which reads each block scale through basalt_fp.metal's h2f, the helper the kernel under test reads its scales through. The contract's reference for native_expert_grouped dequantizes Q2_0 by the host codec, as basalt builds G, U and D with ggml's to_float (native_expert_parity.cpp:56-61). G, U and D now come from tests/contract/gguf_reference.py's port of dequantize_row_q2_0, the decode tools/gguf_writer.py's dequantize_q2_0 mirrors, and the 64-row cross-check, which would now compare the codec with itself, is gone. The host and GPU matrices are bitwise equal for this blob, so eg is 1.26e-2 as before. per_entry kept only row ent_dst[e] of each single-entry call, so a stray store by the comparand to another row went unseen; basalt diffs the whole buffer (native_grouped_parity.cpp:226-234). Each call must now leave every other row as the 0xFF pattern. The basalt citations now point at the cited lines at b4c63b5: random_rows (iq_multi_parity.cpp:72-90, native_grouped_parity.cpp:73-98), the slot (:118), plan_sizes (:164-188), check() (:219-248), the pre-fills (:309-310), dequant_q8_1 (:99-109), and check_grouped's plan (:254-264, :321). test_basalt_experts.py under MTL_SHADER_VALIDATION=1: 9 passed, 0 failed, 0 skipped, no validation reports. --- tests/kernels/test_basalt_experts.py | 39 +++++++++++++++------------- 1 file changed, 21 insertions(+), 18 deletions(-) diff --git a/tests/kernels/test_basalt_experts.py b/tests/kernels/test_basalt_experts.py index 9bed2b20..ee1b24c7 100644 --- a/tests/kernels/test_basalt_experts.py +++ b/tests/kernels/test_basalt_experts.py @@ -7,7 +7,7 @@ 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:68-87, native_grouped_parity.cpp:73-99); token +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.""" @@ -58,9 +58,9 @@ def test_every_variant_builds_and_runs(n_embd, n_ff): # ---- 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:117), + """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, - :163-191), random tokens and scattered destinations (a permutation of the cap rows), and ``tokens`` q8_1 rows of + :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): @@ -95,13 +95,16 @@ def run(self, **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.""" + 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) - out[d] = r["out"][d].view(np.uint32) + 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): @@ -159,7 +162,7 @@ def check_against_emulation(c, r): 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 (:248-275); Q2_0 / Q2_0 at 2560 x 640 + 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] @@ -174,7 +177,7 @@ def test_check_grouped(): 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 (:290-291) + 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() @@ -186,7 +189,7 @@ def test_check_grouped(): check_against_emulation(c, r) -# ---- native_grouped_parity (native_grouped_parity.cpp:207-247, 513-532) ------------------------------------------ +# ---- 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): @@ -320,7 +323,7 @@ def test_swiglu_q8_1_edges(): # ---- float64 references ------------------------------------------------------------------------------------------ def dequant_q8_1(xq, n): - """q8_1 rows back to float64: d * code (iq_multi_parity.cpp:100-110).""" + """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) @@ -370,10 +373,12 @@ def test_whole_expert_against_float64(): 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 by ggml's - dequantize_row_q2_0; 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.""" + 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) @@ -383,9 +388,9 @@ def quant(rows, cols): 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 = (gpu.dequant(42, blob[o: o + n], rows * cols).reshape(rows, cols).astype(np.float64) - for o, n, rows, cols in ((0, lay["up_off"], n_ff, n_embd), (lay["up_off"], lay["up_off"], n_ff, n_embd), - (lay["down_off"], n_embd * lay["d_row"], 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) @@ -396,5 +401,3 @@ def quant(rows, cols): 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 - raw = blob[: 64 * lay["gu_row"]].reshape(64, -1) - assert np.array_equal(G[:64].astype(F32), gguf_reference.dequantize(42, raw)) From 11d14faabc3fcab5810461a050391cdc2f0fc810 Mon Sep 17 00:00:00 2001 From: Lance Woodson <65194841+woodsonl@users.noreply.github.com> Date: Sat, 17 Oct 2026 10:52:21 -0500 Subject: [PATCH 38/74] Correct experts.md's .FTZ sentence and down table; complete NOTICE experts.md said no instruction of these kernels carries .FTZ. The SASS dumps hold 32 .FTZ-flagged instructions each, all inside the four copies of div.rn.f32's slow-path subroutine __cuda_sm3x_div_rn_noftz_f32_slowpath (compares against infinity, the NaN-propagating add, and a negation and a compare on operands scaled into [1, 2)); the PTX has no .ftz. The page now says so; the quotient is div.rn.f32's, IEEE's, so the Metal mapping is unchanged. The down table's 13.0 call-t cell gains the FMUL R14, R14, R17 that forms d2 * d8 ahead of the FFMA (down16.nvcc130.sass:313). The SwiGLU notes and the test summary now cover ieee_mul's non-finite cases. NOTICE: basalt_fp.metal's own entry now names iq_kernels.cu for Split<42>'s Q2_0 decode, the IEEE-built warp_sum and expf_neg, instead of basalt_experts.metal's entry carrying that provenance; basalt_emu.py's entry covers q2_0_dots and swiglu_q8_1, the routed experts' arithmetic. --- docs/research/basalt-nvcc/experts.md | 23 ++++++++++++++--------- third_party/NOTICE | 18 ++++++++++-------- 2 files changed, 24 insertions(+), 17 deletions(-) diff --git a/docs/research/basalt-nvcc/experts.md b/docs/research/basalt-nvcc/experts.md index 8027c7fa..bb456822 100644 --- a/docs/research/basalt-nvcc/experts.md +++ b/docs/research/basalt-nvcc/experts.md @@ -39,8 +39,11 @@ and a bare `:N` is a line of the file named last. ## 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). No instruction of these kernels carries -`.FTZ`: they are IEEE operations, subnormals kept. +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 operands it has scaled into [1, 2). 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 @@ -57,8 +60,9 @@ says whether a subnormal can reach it: +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 the q8_1 quantizer after it is the IEEE one of `matvec.md` - section 3, which already emulates subnormal values. + 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 @@ -155,7 +159,7 @@ 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` | `FFMA R16, R14, R31, RZ` | `FMUL R14, R14, R17`; `FFMA R16, R14, R31, RZ` | `fma(d2 * d8, float(sumi), 0.0f)` | +| 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 | @@ -187,7 +191,8 @@ subnormals. The Q2_0 decode, the q8_1 word readers and `dp4a` are the device fun buffer of blobs; 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 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. +(`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/third_party/NOTICE b/third_party/NOTICE index 356ce62d..5941fb42 100644 --- a/third_party/NOTICE +++ b/third_party/NOTICE @@ -111,10 +111,12 @@ Format: `` — adapted from / copied from `` `` @ `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`, `include/basalt/kernels/dp4a.hpp` - and `include/basalt/kernels/q8_1_finite.hpp` (MIT): `warp_sum`, `warp_max`, `load_int_b2` and the `DP4A` helper, - with the flush-to-zero and reciprocal helpers that write out the arithmetic nvcc compiles for them - (`docs/research/basalt-nvcc/matvec.md`). 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` and the `DP4A` helper, 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`). 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`. @@ -130,8 +132,7 @@ Format: `` — adapted from / copied from `` `` @ `: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`). `basalt_fp.metal` also takes `Split<42>` and `warp_sum` from - `iq_kernels.cu`. License: `third_party/BASALT-LICENSE`. + (`docs/research/basalt-nvcc/experts.md`). 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`. @@ -148,8 +149,9 @@ Format: `` — adapted from / copied from `` `` @ `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` 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`). License: - `third_party/BASALT-LICENSE`. + `native_mmvq` kernels' arithmetic as nvcc compiles it (`docs/research/basalt-nvcc/matvec.md`) and 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`). License: `third_party/BASALT-LICENSE`. ## Test data From 5415ca8fe05c51d991625a0f655088f4bdd9be6f Mon Sep 17 00:00:00 2001 From: Lance Woodson <65194841+woodsonl@users.noreply.github.com> Date: Sat, 17 Oct 2026 10:57:05 -0500 Subject: [PATCH 39/74] Describe the division slow path's .FTZ compare precisely The compare among the slow path's .FTZ instructions (FSETP.NEU.FTZ on the FFMA.RP and FFMA.RM roundings) acts on the quotient of the two rebiased operands, which lies in (0.5, 2), not [1, 2). experts.md now says the negation and the compare act on values the subroutine has scaled away from the subnormal range, which holds for both. --- docs/research/basalt-nvcc/experts.md | 12 ++++++------ 1 file changed, 6 insertions(+), 6 deletions(-) diff --git a/docs/research/basalt-nvcc/experts.md b/docs/research/basalt-nvcc/experts.md index bb456822..6d2e4652 100644 --- a/docs/research/basalt-nvcc/experts.md +++ b/docs/research/basalt-nvcc/experts.md @@ -38,12 +38,12 @@ and a bare `:N` is a line of the file named last. ## 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 operands it has scaled into [1, 2). Its quotient is -`div.rn.f32`'s, IEEE's, so every float operation of these kernels is IEEE's, subnormals kept. +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 From cca8e180fc6495e78d0af82968a0a412d85896d1 Mon Sep 17 00:00:00 2001 From: Lance Woodson <65194841+woodsonl@users.noreply.github.com> Date: Sat, 17 Oct 2026 12:48:47 -0500 Subject: [PATCH 40/74] Hand the routed-expert kernels basalt's grp_ptr table basalt_expert_gu and basalt_expert_down read each group's blob through basalt's grp_ptr: buffer(1) is now a table of 64-bit GPU addresses (a struct holding a device pointer, one a group, each 2-byte aligned and inside a resident buffer), where it was byte offsets into one blobs buffer at buffer(0). The expert cache is 33,973,862,400 bytes, above maxBufferLength (30,150,672,384), so its slots span at least two buffers, which one-buffer offsets cannot reach. The arithmetic is unchanged. Dispatch.use(buffer) makes a buffer a kernel reaches only through a GPU address resident for that dispatch (useResource, read) in Queue.run and Queue.profile. The test harness builds the table from the blob buffers' GPU addresses and declares them; a new test moves a call's blobs into two separate buffers and gets the same bits. --- docs/research/basalt-nvcc/experts.md | 5 +++-- kernels/common/basalt_experts.metal | 20 +++++++++++--------- monolith/kernels.py | 3 ++- runtime/src/metal_core.h | 2 ++ runtime/src/metal_core.mm | 2 ++ runtime/src/native.mm | 4 +++- tests/kernels/basalt_gpu.py | 22 +++++++++++++++------- tests/kernels/test_basalt_experts.py | 25 +++++++++++++++++++++++++ 8 files changed, 63 insertions(+), 20 deletions(-) diff --git a/docs/research/basalt-nvcc/experts.md b/docs/research/basalt-nvcc/experts.md index 6d2e4652..6023f9f5 100644 --- a/docs/research/basalt-nvcc/experts.md +++ b/docs/research/basalt-nvcc/experts.md @@ -187,8 +187,9 @@ by n_embd as basalt's launcher does), `basalt_expert_swiglu_q8_1` and `basalt_ex 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) become byte offsets into one -buffer of blobs; the plan's other arrays, the scratch and the output keep basalt's layout. +(`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`), diff --git a/kernels/common/basalt_experts.metal b/kernels/common/basalt_experts.metal index b15c32d7..3d5dc491 100644 --- a/kernels/common/basalt_experts.metal +++ b/kernels/common/basalt_experts.metal @@ -8,9 +8,9 @@ // 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 grp_off[g] bytes into -// `blobs` (basalt's grp_ptr[g], a pointer, here an offset into one buffer of blobs) 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 +// 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). @@ -39,6 +39,8 @@ #endif #define GRP_NC 6 // entries a pass (iq_kernels.cu:1123) +struct GrpPtr { device const ushort* p; }; // one grp_ptr entry: a blob's 64-bit GPU address + 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) @@ -107,7 +109,7 @@ static inline void rows2(device const ushort* rowA, uint row_halves, int r, int } #endif -kernel void basalt_expert_gu(device const ushort* blobs [[buffer(0)]], device const ulong* grp_off [[buffer(1)]], +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)]], @@ -125,7 +127,7 @@ kernel void basalt_expert_gu(device const ushort* blobs [[buffer(0)]], device co 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 = blobs + (grp_off[g] + w_off) / 2; + 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; @@ -154,7 +156,7 @@ kernel void basalt_expert_gu(device const ushort* blobs [[buffer(0)]], device co 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 = blobs + (grp_off[g] + w_off) / 2; + 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); @@ -230,7 +232,7 @@ static inline void row_dot_20_sub16(device const ushort* row, threadgroup const } #endif -kernel void basalt_expert_down(device const ushort* blobs [[buffer(0)]], device const ulong* grp_off [[buffer(1)]], +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)]], @@ -246,7 +248,7 @@ kernel void basalt_expert_down(device const ushort* blobs [[buffer(0)]], device 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 = blobs + (grp_off[g] + w_off) / 2; + 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); @@ -283,7 +285,7 @@ kernel void basalt_expert_down(device const ushort* blobs [[buffer(0)]], device 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 = blobs + (grp_off[g] + w_off) / 2; + 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) { diff --git a/monolith/kernels.py b/monolith/kernels.py index 8d1f5219..cdf3f914 100644 --- a/monolith/kernels.py +++ b/monolith/kernels.py @@ -322,7 +322,8 @@ def basalt_mmvq_params(n_in: int, n_out: int) -> bytes: def basalt_experts_source() -> 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.""" + 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") 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..df02d623 100644 --- a/runtime/src/metal_core.mm +++ b/runtime/src/metal_core.mm @@ -135,6 +135,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 +187,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..026b2409 100644 --- a/runtime/src/native.mm +++ b/runtime/src/native.mm @@ -59,7 +59,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); diff --git a/tests/kernels/basalt_gpu.py b/tests/kernels/basalt_gpu.py index 769f3d97..2b8926bf 100644 --- a/tests/kernels/basalt_gpu.py +++ b/tests/kernels/basalt_gpu.py @@ -63,10 +63,12 @@ def mmvq(type_id, w, xq, n_in, n_out, ncols, upstream=False, fill=None): 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): + 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, ``grp_off`` each group's byte offset into them (basalt's - grp_ptr); ``grp_start`` (n_groups + 1 entries), ``ent_tok``, ``ent_dst`` and ``xq`` (q8_1 rows) as basalt's. The + 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 @@ -85,8 +87,10 @@ def arr(a, dt, n): # a plan array, zero-padde v[: len(a)] = a return nt.Buffer(dev, v.tobytes()) - b_blobs = nt.Buffer(dev, np.ascontiguousarray(blobs, np.uint8).tobytes()) - b_off = arr(grp_off, np.uint64, cap_groups) + 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) @@ -100,16 +104,20 @@ def arr(a, dt, n): # a plan array, zero-padde 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_blobs, b_off, b_start, b_ng, b_tok, b_xq, b_gate, b_up)): + 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_blobs, b_off, b_start, b_ng, b_dst, b_hq, b_out)): + 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 diff --git a/tests/kernels/test_basalt_experts.py b/tests/kernels/test_basalt_experts.py index ee1b24c7..c03806ae 100644 --- a/tests/kernels/test_basalt_experts.py +++ b/tests/kernels/test_basalt_experts.py @@ -233,6 +233,31 @@ def test_native_grouped_parity(n_embd, n_ff): # ---- 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 From 00c01b9ae39761b105fb54cfe8a55533e8865bcf Mon Sep 17 00:00:00 2001 From: Lance Woodson <65194841+woodsonl@users.noreply.github.com> Date: Sat, 17 Oct 2026 12:49:45 -0500 Subject: [PATCH 41/74] Rewrap the grp_ptr comments to the line width --- kernels/common/basalt_experts.metal | 7 ++++--- tests/kernels/basalt_gpu.py | 6 +++--- 2 files changed, 7 insertions(+), 6 deletions(-) diff --git a/kernels/common/basalt_experts.metal b/kernels/common/basalt_experts.metal index 3d5dc491..a081ddc8 100644 --- a/kernels/common/basalt_experts.metal +++ b/kernels/common/basalt_experts.metal @@ -10,9 +10,10 @@ // // 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). +// 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 diff --git a/tests/kernels/basalt_gpu.py b/tests/kernels/basalt_gpu.py index 2b8926bf..658a1adf 100644 --- a/tests/kernels/basalt_gpu.py +++ b/tests/kernels/basalt_gpu.py @@ -68,9 +68,9 @@ def experts(blobs, grp_off, grp_start, ent_tok, ent_dst, xq, n_embd, n_ff, n_out """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.""" + 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 From fb70ad2c68e54f0f9036c23e2599ce37ae265fb7 Mon Sep 17 00:00:00 2001 From: Lance Woodson <65194841+woodsonl@users.noreply.github.com> Date: Sat, 17 Oct 2026 11:22:46 -0500 Subject: [PATCH 42/74] Record the arithmetic nvcc compiles for basalt's BF16 GEMVs docs/research/basalt-nvcc/bf16.md reads bf16_gemv_fp32_mmvf, its multi-row kernel and the _cols launcher from NVCC 13.0, 13.2 and 13.3's sm_120 PTX and SASS (basalt's flags for native_bf16.cu, --use_fast_math included): two ordered FFMA.FTZ per bf16 pair, the FADD.FTZ XOR butterflies, the zeroed 32-slot block stage, and per token the one-row sequence in the multi kernel. It is the authority the Metal port of these kernels follows, so invariant 5 of flash-next.md now lists it with the other basalt-nvcc pages. --- docs/design/flash-next.md | 2 +- docs/research/basalt-nvcc/bf16.md | 162 ++++++++++++++++++++++++++++++ 2 files changed, 163 insertions(+), 1 deletion(-) create mode 100644 docs/research/basalt-nvcc/bf16.md diff --git a/docs/design/flash-next.md b/docs/design/flash-next.md index fcadd776..42d044a9 100644 --- a/docs/design/flash-next.md +++ b/docs/design/flash-next.md @@ -103,7 +103,7 @@ ones this pack runs. (`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): which multiply-adds fuse and + dequantizers, `experts.md` for the routed experts, `bf16.md` for the BF16 GEMVs): 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 diff --git a/docs/research/basalt-nvcc/bf16.md b/docs/research/basalt-nvcc/bf16.md new file mode 100644 index 00000000..ae85a591 --- /dev/null +++ b/docs/research/basalt-nvcc/bf16.md @@ -0,0 +1,162 @@ +# 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. `fma_ftz` and `add_ftz` flush explicitly, so the Metal kernel + does not depend on what the GPU does with subnormals (this one flushes them in arithmetic anyway: `matvec.md`, + Notation). +- **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 the unrolled loop bodies (15 pairs in the one-row kernel; 20 pair FMAs over 4 tokens per +multi iteration, plus the remainder loop), not a per-output count. + +## 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. From 1b20225e86f0b8a1d775e14eaa8038a00f995167 Mon Sep 17 00:00:00 2001 From: Lance Woodson <65194841+woodsonl@users.noreply.github.com> Date: Sat, 17 Oct 2026 11:26:48 -0500 Subject: [PATCH 43/74] Port basalt's BF16 GEMVs on fp32 activations to Metal kernels/common/basalt_mmvf.metal is one source for bf16_gemv_fp32_mmvf (NT 1) and its multi-row kernel (NT 4 or 8), in the sequence bf16.md reads from nvcc: per bf16 pair two ordered fma_ftz from +0, the warp_sum_ftz butterfly, and above 32 threads the zeroed 32-slot block stage. monolith/kernels.py gets the source, macro, params and _cols chunk builders, reproducing basalt's mmvf_block_size, its one-row routing (n_tok 1 with ldy >= n_out) and its checks. tests/kernels gets the single-kernel runners (one call, and _cols as offset-bound dispatches in one command buffer) and a numpy emulation of the sequence. Work in progress: the parity tests follow in the next commit. --- kernels/common/basalt_mmvf.metal | 69 ++++++++++++++++++++++++++++++++ monolith/kernels.py | 47 ++++++++++++++++++++++ tests/kernels/basalt_emu.py | 32 +++++++++++++++ tests/kernels/basalt_gpu.py | 34 ++++++++++++++++ 4 files changed, 182 insertions(+) create mode 100644 kernels/common/basalt_mmvf.metal diff --git a/kernels/common/basalt_mmvf.metal b/kernels/common/basalt_mmvf.metal new file mode 100644 index 00000000..e198ae62 --- /dev/null +++ b/kernels/common/basalt_mmvf.metal @@ -0,0 +1,69 @@ +// 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. +// +// 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] = acc[k]; +} diff --git a/monolith/kernels.py b/monolith/kernels.py index cdf3f914..b7d54b33 100644 --- a/monolith/kernels.py +++ b/monolith/kernels.py @@ -391,6 +391,53 @@ def basalt_dequant_macros(type_id: int) -> Dict[str, str]: return {"DQ_TYPE": str(type_id)} +# ---- basalt's BF16 GEMVs on fp32 activations (kernels/common/basalt_mmvf.metal; docs/research/basalt-nvcc/bf16.md) -- + +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_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)] + + # ---- the other decode kernels ------------------------------------------------------------------------------- MSL_TENSOR_OPS = 4 << 16 # the language version the tensor-ops kernels need (MSL 4.0: , MPP) diff --git a/tests/kernels/basalt_emu.py b/tests/kernels/basalt_emu.py index 539e3845..5a18c6e8 100644 --- a/tests/kernels/basalt_emu.py +++ b/tests/kernels/basalt_emu.py @@ -329,3 +329,35 @@ def swiglu_q8_1(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 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): + """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.""" + 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_ftz(wf[None, :, 2 * p], x[:, None, 2 * p], acc[..., p - p0]) + acc[..., p - p0] = fma_ftz(wf[None, :, 2 * p + 1], x[:, None, 2 * p + 1], a) + s = butterfly(acc.reshape(-1, 32), add_ftz).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_ftz).reshape(x.shape[0], n_out, 1) + return s[..., 0] diff --git a/tests/kernels/basalt_gpu.py b/tests/kernels/basalt_gpu.py index 658a1adf..d1bdf1eb 100644 --- a/tests/kernels/basalt_gpu.py +++ b/tests/kernels/basalt_gpu.py @@ -126,6 +126,40 @@ def arr(a, dt, n): # a plan array, zero-padde "hq": np.frombuffer(b_hq.read(0, b_hq.nbytes), np.uint8), "out": f32(b_out).reshape(n_out_rows, n_embd)} +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", From 44f1098df7ff1d5e62a8d5a93e272e1e6d552db6 Mon Sep 17 00:00:00 2001 From: Lance Woodson <65194841+woodsonl@users.noreply.github.com> Date: Sat, 17 Oct 2026 11:31:19 -0500 Subject: [PATCH 44/74] Port basalt's MMVF parity tests and check the kernel bit for bit tests/kernels/test_basalt_mmvf.py carries route_window_parity's projection half (2560 to 256 and 1, plus the contract's 2560 to 128 and 512, T = 2, 3, 4, 6, memcmp) and ple_parity's native PLE value check as a standalone float64 test for the one-row and multi kernels (le(rel, 2e-6), no non-finite, separation above 1e-5 from BF16-rounded activations). New: bitwise column invariance (multi at T = 1..8, _cols at 9 and 17, one row with ldy < n_out, strided rows with untouched gaps) at block sizes 32, 96 and 256; the kernel bit for bit against the numpy emulation of bf16.md at five block sizes; each .FTZ site planted to give +0. NOTICE, the emulation's header and the builders' section name native_bf16.cu and ggml's mmvf.cu. --- monolith/kernels.py | 3 + tests/kernels/basalt_emu.py | 9 +- tests/kernels/test_basalt_mmvf.py | 200 ++++++++++++++++++++++++++++++ third_party/NOTICE | 29 +++-- 4 files changed, 230 insertions(+), 11 deletions(-) create mode 100644 tests/kernels/test_basalt_mmvf.py diff --git a/monolith/kernels.py b/monolith/kernels.py index b7d54b33..7d6d3afb 100644 --- a/monolith/kernels.py +++ b/monolith/kernels.py @@ -392,6 +392,9 @@ def basalt_dequant_macros(type_id: int) -> Dict[str, str]: # ---- 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``).""" diff --git a/tests/kernels/basalt_emu.py b/tests/kernels/basalt_emu.py index 5a18c6e8..4a838199 100644 --- a/tests/kernels/basalt_emu.py +++ b/tests/kernels/basalt_emu.py @@ -1,10 +1,11 @@ # 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 and -# include/basalt/kernels/q8_1_finite.hpp @ b4c63b55754637f4c72ad53a0f791d425f71eb36, which adapt ggml-org/llama.cpp -# ggml/src/ggml-common.h (kvalues_iq4nl), ggml/src/ggml-quants.c (get_scale_min_k4) and ggml/src/ggml-cuda/quantize.cu -# @ 3cf03257f219afbe7334045ff7c6a06ac68c627d (MIT; third_party/NOTICE). +# adapted from basalt (jesdga95/basalt) src/kernels/cuda/native_mmvq.cu, src/kernels/cuda/iq_kernels.cu, +# src/kernels/cuda/native_bf16.cu and include/basalt/kernels/q8_1_finite.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: numpy's float32 add, multiply and divide do; ``fma32`` does by rounding the exact float64 sum to odd before the float32 cast. The diff --git a/tests/kernels/test_basalt_mmvf.py b/tests/kernels/test_basalt_mmvf.py new file mode 100644 index 00000000..3e5a8661 --- /dev/null +++ b/tests/kernels/test_basalt_mmvf.py @@ -0,0 +1,200 @@ +# SPDX-License-Identifier: MIT +# Copyright (c) 2026 Jesús Gulfo +# adapted from basalt (jesdga95/basalt) src/kernels/route_window_parity.cpp and src/kernels/ple_parity.cpp +# @ b4c63b55754637f4c72ad53a0f791d425f71eb36 (MIT; third_party/NOTICE): route_window_parity's projection half (its +# shapes, widths, data and criterion) and ple_parity's native PLE value check (its witness, float64 reference, rel_l1, +# le and gt, and criterion). +"""basalt's BF16 GEMVs on fp32 activations on Metal (kernels/common/basalt_mmvf.metal): bf16_gemv_fp32_mmvf (the +one-row kernel), bf16_gemv_fp32_mmvf_multi and bf16_gemv_fp32_mmvf_cols. + +- route_window_parity, its projection half (basalt src/kernels/route_window_parity.cpp:25-50): _cols at T = 2, 3, 4 + and 6 against T one-row calls at 2560 to 256 and 2560 to 1, weights bf16(N(0, 1) * 0.05) and N(0, 1) activations + (:29-35), criterion quoted: ``const bool same = std::memcmp(y1.data(), yn.data(), y1.size() * 4) == 0;`` (:48). The + contract's shapes for this path, 2560 to 128 and 2560 to 512 (docs/design/flash-next.md, "Per-kernel parity + tests"), run the same check. basalt draws from std::mt19937(7) through std::normal_distribution, 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.""" + +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 arithmetic gives a nonzero result: + a subnormal weight (row B), a subnormal activation (row x1), a subnormal product (row A times x0) and a block sum + whose last add is subnormal (row D times x2: 2^-125 from warp 0 plus -1.75 * 2^-126 from warp 1). This GPU's + arithmetic flushes subnormals itself (docs/research/basalt-nvcc/matvec.md, Notation), so the kernel passes here + without its explicit flushes too; the test pins CUDA's results, which the explicit flushes keep on any GPU.""" + 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 = x.astype(np.float64) @ weight_values(w).astype(np.float64).T + for k, r in [(0, 0), (0, 1), (2, 1), (1, 2), (1, 3), (2, 3)]: + assert bits(got)[k, r] == 0 and ieee[k, r] != 0, (k, r) + + +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/third_party/NOTICE b/third_party/NOTICE index 5941fb42..7c551c39 100644 --- a/third_party/NOTICE +++ b/third_party/NOTICE @@ -99,9 +99,14 @@ Format: `` — adapted from / copied from `` `` @ - `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_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`. - `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` and the q8_1 rule of `ggml/src/ggml-cuda/quantize.cu`, - re-implemented in numpy (MIT). License: `third_party/GGML-LICENSE`. + 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`. ## basalt (jesdga95/basalt @ `b4c63b55754637f4c72ad53a0f791d425f71eb36`, MIT) @@ -133,6 +138,14 @@ Format: `` — adapted from / copied from `` `` @ (`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_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`. +- `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`. @@ -147,11 +160,13 @@ Format: `` — adapted from / copied from `` `` @ `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` 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`) and 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`). 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` 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`) and the BF16 GEMVs' + (`mmvf`; `bf16_bits`: `include/basalt/kernels/bf16_bits.hpp`'s rounding; `docs/research/basalt-nvcc/bf16.md`). + License: `third_party/BASALT-LICENSE`. ## Test data From dd171e351453e67a32084d0149139e5e6eae7092 Mon Sep 17 00:00:00 2001 From: Lance Woodson <65194841+woodsonl@users.noreply.github.com> Date: Sat, 17 Oct 2026 11:32:35 -0500 Subject: [PATCH 45/74] State bf16.md's FFMA counts as the static counts they are The per-function table's FFMA.FTZ column counts the unrolled loop bodies; the sentence under it now says which copies make up the one-row and the four-token totals, read from the 13.2 SASS. --- docs/research/basalt-nvcc/bf16.md | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/docs/research/basalt-nvcc/bf16.md b/docs/research/basalt-nvcc/bf16.md index ae85a591..461a19fd 100644 --- a/docs/research/basalt-nvcc/bf16.md +++ b/docs/research/basalt-nvcc/bf16.md @@ -132,8 +132,8 @@ Instruction counts per function (13.0 = 13.2; 13.3 adds the diverged-warp copy o | `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 the unrolled loop bodies (15 pairs in the one-row kernel; 20 pair FMAs over 4 tokens per -multi iteration, plus the remainder loop), not a per-output count. +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`) From a44ca22a7152de04b9ebe4039d2642fb91b52ec4 Mon Sep 17 00:00:00 2001 From: Lance Woodson <65194841+woodsonl@users.noreply.github.com> Date: Sat, 17 Oct 2026 13:23:23 -0500 Subject: [PATCH 46/74] Round fma_ftz and mul_ftz up to 2^-126 where FFMA.FTZ does PTX defines fma.rn.ftz.f32 (and mul.rn.ftz.f32) as the exact result rounded to single precision, then a subnormal result flushed, so an exact value in [2^-126 - 2^-150, 2^-126) gives the smallest normal 2^-126. This GPU's fma and multiply flush on the exact value, before rounding, and return the zero of its sign there; the explicit ftz() wrappers never saw the rounded 2^-126. Review of #13 found it at the MMVF kernel's FMAs (R1: exact 2^-126 - 2^-151 gave +0, the emulation 0x00800000); a sweep of 2^20 fmas and 2^19 products around +-2^-126 found 40529 and 26053 such results. fma_ftz now checks a zero from nonzero flushed factors against the exact value, in integer units of 2^-150, and returns +-2^-126 when it rounds there; mul_ftz is fma_ftz(a, b, -0). Both now match the emulation on that sweep. The fix reaches every port kernel that includes basalt_fp.metal (mmvq, the q8_1 quantizers, the routed experts, mmvf). add_ftz is exact below 2^-126 and no float's reciprocal lies in the interval, so the other helpers are unchanged. --- kernels/common/basalt_fp.metal | 45 ++++++++++++++++++++++++++++++---- 1 file changed, 40 insertions(+), 5 deletions(-) diff --git a/kernels/common/basalt_fp.metal b/kernels/common/basalt_fp.metal index 17406eea..fddb0675 100644 --- a/kernels/common/basalt_fp.metal +++ b/kernels/common/basalt_fp.metal @@ -14,9 +14,15 @@ // - 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, then the result flushed. 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. +// 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 @@ -34,8 +40,37 @@ static inline float ftz(float 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)); } -static inline float mul_ftz(float a, float b) { return ftz(ftz(a) * ftz(b)); } -static inline float fma_ftz(float a, float b, float c) { return ftz(fma(ftz(a), ftz(b), ftz(c))); } + +// 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)); } From 7014be83f38bed674d8508940a333513c75b616c Mon Sep 17 00:00:00 2001 From: Lance Woodson <65194841+woodsonl@users.noreply.github.com> Date: Sat, 17 Oct 2026 13:28:19 -0500 Subject: [PATCH 47/74] Pin the rounding before the flush in the helper and MMVF tests The emulation already rounds to the float32 grid with its subnormals and flushes after, as PTX defines fma.rn.ftz.f32 and mul.rn.ftz.f32; its docstrings now say so, the tie 2^-126 - 2^-150 to 2^-126 included. - test_basalt_platform: test_subnormals_in_safe_mode records that this GPU's multiply and fma return +0 for an exact 2^-126 - 2^-151; the helper test plants products and fmas within 40 * 2^-152 of +-2^-126 (c zero, normal, or of either sign) and named cases: the tie, its neighbours, a 2^-252 product beside +-2^-126 and an exact cancellation, with their expected bits. - test_flush_to_zero: R1 at a pair's first FMA, the second FMA from a normal accumulator and its negative, and the tie, on the one-row and the multi kernel, all 0x00800000 (0x80800000). The IEEE guard is now the emulation without flushes (emu.mmvf(flush=False)) instead of a float64 product: the pairs (0, 1) and (1, 3) are zero in IEEE float32 too, so they are dropped, and the docstring names the pair that covers each .FTZ site. With the original one-line fma_ftz and mul_ftz, both test_ftz_helpers_match_the_emulation and test_flush_to_zero fail. --- tests/kernels/basalt_emu.py | 30 +++++++++++++------- tests/kernels/test_basalt_mmvf.py | 28 ++++++++++++------ tests/kernels/test_basalt_platform.py | 41 +++++++++++++++++++++++---- 3 files changed, 74 insertions(+), 25 deletions(-) diff --git a/tests/kernels/basalt_emu.py b/tests/kernels/basalt_emu.py index 4a838199..468d3106 100644 --- a/tests/kernels/basalt_emu.py +++ b/tests/kernels/basalt_emu.py @@ -7,9 +7,12 @@ # 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: 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 and results to the zero of their sign, as SASS's ``.FTZ`` instructions do.""" +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 @@ -24,8 +27,9 @@ def ftz(x): def fma32(a, b, c): - """a * b + c rounded once to float32 (to nearest even). 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 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 @@ -49,6 +53,7 @@ def mul_ftz(a, 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))) @@ -341,11 +346,14 @@ def bf16_bits(x): return ((b + ((b >> 16) & 1) + 0x7FFF) >> 16).astype(np.uint16) -def mmvf(w, x, block): +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.""" + 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) @@ -354,11 +362,11 @@ def mmvf(w, x, block): pairs = n_in // 2 for p0 in range(0, pairs, block): p = np.arange(p0, min(p0 + block, pairs)) - a = fma_ftz(wf[None, :, 2 * p], x[:, None, 2 * p], acc[..., p - p0]) - acc[..., p - p0] = fma_ftz(wf[None, :, 2 * p + 1], x[:, None, 2 * p + 1], a) - s = butterfly(acc.reshape(-1, 32), add_ftz).reshape(x.shape[0], n_out, block // 32) + 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_ftz).reshape(x.shape[0], n_out, 1) + s = butterfly(slots.reshape(-1, 32), add).reshape(x.shape[0], n_out, 1) return s[..., 0] diff --git a/tests/kernels/test_basalt_mmvf.py b/tests/kernels/test_basalt_mmvf.py index 3e5a8661..0a6b1594 100644 --- a/tests/kernels/test_basalt_mmvf.py +++ b/tests/kernels/test_basalt_mmvf.py @@ -28,7 +28,8 @@ 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.""" + 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 @@ -167,11 +168,15 @@ def p2(e): def test_flush_to_zero(): - """Each .FTZ site of bf16.md planted so that the flush gives +0 where IEEE arithmetic gives a nonzero result: - a subnormal weight (row B), a subnormal activation (row x1), a subnormal product (row A times x0) and a block sum - whose last add is subnormal (row D times x2: 2^-125 from warp 0 plus -1.75 * 2^-126 from warp 1). This GPU's - arithmetic flushes subnormals itself (docs/research/basalt-nvcc/matvec.md, Notation), so the kernel passes here - without its explicit flushes too; the test pins CUDA's results, which the explicit flushes keep on any GPU.""" + """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), @@ -184,9 +189,16 @@ def test_flush_to_zero(): 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 = x.astype(np.float64) @ weight_values(w).astype(np.float64).T - for k, r in [(0, 0), (0, 1), (2, 1), (1, 2), (1, 3), (2, 3)]: + 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(): diff --git a/tests/kernels/test_basalt_platform.py b/tests/kernels/test_basalt_platform.py index 403fcacb..a0bf9d43 100644 --- a/tests/kernels/test_basalt_platform.py +++ b/tests/kernels/test_basalt_platform.py @@ -98,13 +98,16 @@ def test_rounding_is_to_nearest_even(): 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. 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).""" + 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)], F32) + (-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 @@ -119,6 +122,8 @@ def test_subnormals_in_safe_mode(): 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 @@ -132,8 +137,11 @@ def test_subnormals_in_safe_mode(): 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), and reciprocals that underflow. On this GPU the - arithmetic flushes anyway (test_subnormals_in_safe_mode); fmax and fabs do not, so max_ftz and abs_ftz carry it.""" + 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) @@ -145,7 +153,28 @@ def test_ftz_helpers_match_the_emulation(): 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 From 6a25f702edac807461147e810b3c9d1cc2a5a457 Mon Sep 17 00:00:00 2001 From: Lance Woodson <65194841+woodsonl@users.noreply.github.com> Date: Sat, 17 Oct 2026 13:29:56 -0500 Subject: [PATCH 48/74] Correct the docs' claim that the GPU's flushing matches .FTZ bf16.md said the explicit flushes make the MMVF kernel independent of the GPU's subnormal handling, and matvec.md that the hardware does what SASS does at the .FTZ multiplies and fmas. Neither held: this GPU's multiply and fma flush on the exact value, so a result that rounds up to 2^-126 came back as zero. State PTX's rule (round to single precision, then flush a subnormal result), the measured hardware behaviour, and what fma_ftz and mul_ftz now do about it, in bf16.md, matvec.md's Notation and invariant 5 of flash-next.md. bf16.md also records that the rule rests on the PTX ISA's wording, not on a run on Blackwell. --- docs/design/flash-next.md | 10 ++++++---- docs/research/basalt-nvcc/bf16.md | 12 +++++++++--- docs/research/basalt-nvcc/matvec.md | 18 +++++++++++------- 3 files changed, 26 insertions(+), 14 deletions(-) diff --git a/docs/design/flash-next.md b/docs/design/flash-next.md index 42d044a9..ab0d4077 100644 --- a/docs/design/flash-next.md +++ b/docs/design/flash-next.md @@ -116,10 +116,12 @@ ones this pack runs. 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 result to the zero of their sign explicitly, with - integer operations on the bits, 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, + 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 diff --git a/docs/research/basalt-nvcc/bf16.md b/docs/research/basalt-nvcc/bf16.md index 461a19fd..06f0d0bb 100644 --- a/docs/research/basalt-nvcc/bf16.md +++ b/docs/research/basalt-nvcc/bf16.md @@ -86,9 +86,15 @@ Notes: 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. `fma_ftz` and `add_ftz` flush explicitly, so the Metal kernel - does not depend on what the GPU does with subnormals (this one flushes them in arithmetic anyway: `matvec.md`, - Notation). + 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 diff --git a/docs/research/basalt-nvcc/matvec.md b/docs/research/basalt-nvcc/matvec.md index ecd57aee..35b1235d 100644 --- a/docs/research/basalt-nvcc/matvec.md +++ b/docs/research/basalt-nvcc/matvec.md @@ -56,13 +56,17 @@ and a bare `:N` is a line of the file named last. 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. `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, - multiplies and fmas, but not at the `.FTZ` absolute value and maximum (`abs.ftz` and the amax butterfly's - `FMNMX.FTZ`, section 1): the helpers flush explicitly, 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. + 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 From 53638e591b2e36cc29b0364f9d25c48dd26afe5d Mon Sep 17 00:00:00 2001 From: Lance Woodson <65194841+woodsonl@users.noreply.github.com> Date: Sat, 17 Oct 2026 14:04:04 -0500 Subject: [PATCH 49/74] Port basalt's dense_tc window projections to Metal The net change of woodsonl/mlxstream#14 (its nine commits and its merge of the fork's main, which already carried the BF16 GEMVs this branch stacks on), as one commit: basalt's dense_tc and dense_tc_pair for Q2_0, Q3_K, Q4_K, Q5_K, Q6_K and IQ4_XS in each summation order its variant rule can pick, with the rule evaluated at basalt's 170 multiprocessors; the nvcc research page; the builders; the ported dense_tc_parity tests, a float64 reference per type and a bit-for-bit numpy emulation; and iq4_table_lookup and vsub4 moved into basalt_fp.metal for native_mmvq and dense_tc to share. --- docs/design/flash-next.md | 3 +- docs/research/basalt-nvcc/dense_tc.md | 226 +++++++++++ kernels/common/basalt_dense_tc.metal | 367 ++++++++++++++++++ kernels/common/basalt_fp.metal | 23 +- kernels/common/basalt_mmvq.metal | 16 +- monolith/kernels.py | 83 ++++ .../contract/test_basalt_dense_tc_variant.py | 33 ++ tests/kernels/basalt_emu.py | 129 +++++- tests/kernels/basalt_gpu.py | 47 +++ tests/kernels/test_basalt_dense_tc.py | 210 ++++++++++ third_party/NOTICE | 38 +- 11 files changed, 1145 insertions(+), 30 deletions(-) create mode 100644 docs/research/basalt-nvcc/dense_tc.md create mode 100644 kernels/common/basalt_dense_tc.metal create mode 100644 tests/contract/test_basalt_dense_tc_variant.py create mode 100644 tests/kernels/test_basalt_dense_tc.py diff --git a/docs/design/flash-next.md b/docs/design/flash-next.md index ab0d4077..87898d6b 100644 --- a/docs/design/flash-next.md +++ b/docs/design/flash-next.md @@ -103,7 +103,8 @@ ones this pack runs. (`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): which multiply-adds fuse and + dequantizers, `experts.md` for the routed experts, `bf16.md` for the BF16 GEMVs, `dense_tc.md` for the window + projections): 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 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/kernels/common/basalt_dense_tc.metal b/kernels/common/basalt_dense_tc.metal new file mode 100644 index 00000000..2511f4d8 --- /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. +// +// 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] = 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] = tree<1>(red + row * 8 + col); +} diff --git a/kernels/common/basalt_fp.metal b/kernels/common/basalt_fp.metal index fddb0675..95cd727a 100644 --- a/kernels/common/basalt_fp.metal +++ b/kernels/common/basalt_fp.metal @@ -29,8 +29,9 @@ // 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: CUDA's two 16-bit loads, __dp4a, __byte_perm (3-bit selectors) and -// __vsubss4 as exact integer arithmetic. +// - 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). // - 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. #pragma STDC FP_CONTRACT OFF @@ -131,6 +132,24 @@ static inline int vsubss4(int a, int b) { 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)); } diff --git a/kernels/common/basalt_mmvq.metal b/kernels/common/basalt_mmvq.metal index ddc5fa46..60739068 100644 --- a/kernels/common/basalt_mmvq.metal +++ b/kernels/common/basalt_mmvq.metal @@ -39,21 +39,7 @@ 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) are basalt_fp.metal's. - -// native_mmvq.cu:441-457: the IQ4 codebook as four words and its two-stage byte lookup -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_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 || MMVQ_TYPE == 12 // Q5_K (176-byte blocks: dm, scales[12], qh[32], qs[128]) and Q4_K (144: dm, scales[12], qs[128]); diff --git a/monolith/kernels.py b/monolith/kernels.py index 7d6d3afb..7b4df0f9 100644 --- a/monolith/kernels.py +++ b/monolith/kernels.py @@ -441,6 +441,89 @@ def basalt_mmvf_cols(ncols: int) -> List[Tuple[int, int]]: 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 + + # ---- the other decode kernels ------------------------------------------------------------------------------- MSL_TENSOR_OPS = 4 << 16 # the language version the tensor-ops kernels need (MSL 4.0: , MPP) 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/kernels/basalt_emu.py b/tests/kernels/basalt_emu.py index 468d3106..17c5059f 100644 --- a/tests/kernels/basalt_emu.py +++ b/tests/kernels/basalt_emu.py @@ -2,7 +2,7 @@ # 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 and include/basalt/kernels/q8_1_finite.hpp @ +# src/kernels/cuda/native_bf16.cu, src/kernels/cuda/dense_tc.cu and include/basalt/kernels/q8_1_finite.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). @@ -370,3 +370,130 @@ def mmvf(w, x, block, flush=True): 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() diff --git a/tests/kernels/basalt_gpu.py b/tests/kernels/basalt_gpu.py index d1bdf1eb..89e05f6d 100644 --- a/tests/kernels/basalt_gpu.py +++ b/tests/kernels/basalt_gpu.py @@ -166,3 +166,50 @@ def dequant(type_id, raw, n): 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()} 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/third_party/NOTICE b/third_party/NOTICE index 7c551c39..c70be754 100644 --- a/third_party/NOTICE +++ b/third_party/NOTICE @@ -85,20 +85,23 @@ Format: `` — adapted from / copied from `` `` @ 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 and the `__dp4a`, `__byte_perm` and `__vsubss4` semantics. - License: `third_party/GGML-LICENSE`. + 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, the IQ4 table lookup, and mmvq's thread-to-block - mapping and cross-warp reduction. License: `third_party/GGML-LICENSE`. + `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: @@ -118,7 +121,7 @@ Format: `` — adapted from / copied from `` `` @ `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` and the `DP4A` helper, with the flush-to-zero and reciprocal helpers that write out the arithmetic nvcc + `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`). License: `third_party/BASALT-LICENSE`. @@ -138,11 +141,23 @@ Format: `` — adapted from / copied from `` `` @ (`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_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`). 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`. @@ -161,12 +176,13 @@ Format: `` — adapted from / copied from `` `` @ - `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` 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`) and the BF16 GEMVs' - (`mmvf`; `bf16_bits`: `include/basalt/kernels/bf16_bits.hpp`'s rounding; `docs/research/basalt-nvcc/bf16.md`). - License: `third_party/BASALT-LICENSE`. + `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`) and `dense_tc`'s (`docs/research/basalt-nvcc/dense_tc.md`). License: + `third_party/BASALT-LICENSE`. ## Test data From fcf7b1caf419c5bac84319ef55eeb91872069d96 Mon Sep 17 00:00:00 2001 From: Lance Woodson <65194841+woodsonl@users.noreply.github.com> Date: Sat, 17 Oct 2026 16:27:12 -0500 Subject: [PATCH 50/74] Let a step pause for host work between GPU passes A step of the program can pause for CPU work between two of its GPU passes (HostPoint): the pass ending at a point's publish boundary signals an MTLSharedEvent, the host waits for it and runs the point's task, and only then commits the command buffer that starts at the point's wait boundary, so no command buffer ever waits on the host and a slow task cannot trip the GPU watchdog (probes/p16_host_handoff: a 5 s park is killed, 4.5 s survives). Host buffers come from the session by name and stay resident; ops declare buffers they reach through GPU addresses; Program.check_host_points rejects any op that races a task. This is woodsonl/mlxstream#15, squashed, on top of the upstream copies of the shader-validation gate (lithos-ai/lithos-metal#73) and the routed-expert grp_ptr table (lithos-ai/lithos-metal#77). It also records host points in docs/design/design.md and constraint 5 of docs/design/flash-next.md, and adds tools/bench/host_handoff.py, which measures the runtime's handoff: a median of 136 to 137 us of GPU idle time per handoff on a 40-core M3 Max. --- docs/design/design.md | 11 + docs/design/flash-next.md | 7 + monolith/compiler/barriers.py | 7 +- monolith/core/step_state.py | 2 +- monolith/runtime/__init__.py | 4 +- monolith/runtime/engine.py | 82 +- monolith/runtime/program.py | 71 +- probes/README.md | 1 + probes/p16_host_handoff.m | 265 +++++ probes/p16_host_handoff.metal | 14 + ...M3-Max_40c_macOS27.0.1_20261016-112112.txt | 15 + ...M3-Max_40c_macOS27.0.1_20261016-112242.txt | 21 + ...M3-Max_40c_macOS27.0.1_20261016-112417.txt | 19 + ...M3-Max_40c_macOS27.0.1_20261016-112747.txt | 21 + ...M3-Max_40c_macOS27.0.1_20261017-140635.txt | 26 + probes/run_all.sh | 2 +- runtime/src/metal_core.h | 48 +- runtime/src/metal_core.mm | 371 ++++++- runtime/src/native.mm | 106 +- tests/contract/test_barriers.py | 12 + tests/runtime/shader_validation_cases.py | 15 +- tests/runtime/test_host_steps.py | 931 ++++++++++++++++++ tests/runtime/test_shader_validation.py | 20 +- tools/bench/host_handoff.py | 80 ++ 24 files changed, 2100 insertions(+), 51 deletions(-) create mode 100644 probes/p16_host_handoff.m create mode 100644 probes/p16_host_handoff.metal create mode 100644 probes/results/Apple-M3-Max_40c_macOS27.0.1_20261016-112112.txt create mode 100644 probes/results/Apple-M3-Max_40c_macOS27.0.1_20261016-112242.txt create mode 100644 probes/results/Apple-M3-Max_40c_macOS27.0.1_20261016-112417.txt create mode 100644 probes/results/Apple-M3-Max_40c_macOS27.0.1_20261016-112747.txt create mode 100644 probes/results/Apple-M3-Max_40c_macOS27.0.1_20261017-140635.txt create mode 100644 tests/runtime/test_host_steps.py create mode 100644 tools/bench/host_handoff.py diff --git a/docs/design/design.md b/docs/design/design.md index b2ab081d..e526db3f 100644 --- a/docs/design/design.md +++ b/docs/design/design.md @@ -65,6 +65,7 @@ for the extension interface. | `KernelSpec` | Metal source, entry point, specialization macros, and language version | | `BufferSpec` | Size, initial data or mapped file range, and lifetime role | | `OpSpec` | Kernel, bindings, launch geometry, threadgroup storage, and dependency boundary | +| `HostPoint` | Host task inside a step: the boundary after which it starts, the boundary from which later operations wait for it, and the buffers it reads and writes | | `StepStateLayout` | Shared binary layout for GPU-resident generation control | | Backend identity | Backend ID and configuration digest associated with the compiled program | | Context capacity | Bound enforced before a step accesses persistent caches | @@ -73,6 +74,13 @@ The runtime replays a static operation sequence. Kernels use active-row counts a work within their compiled bounds. A later replay can return without doing work after the sequence has finished. The host submits bounded batches of work and reads output tokens. +A step can pause at a host point for CPU work. The pass before the point signals a shared event; the host +waits for the signal, runs the point's task, and then commits the command buffer that continues the step. +A committed command buffer therefore never waits on the host, so a slow task idles the GPU and cannot trip +the watchdog. A step's tasks run only when the program was live at the start of the step. A failed task, a +command-buffer error, or a timeout ends the run after every committed command buffer finishes, and sets +StepState error 4. + An ICB barrier orders dependent dispatches. The compiler may omit a boundary only after establishing that the relevant operations can run independently. Inside a megakernel, threadgroup barriers protect local scratch; cross-worker publication follows Metal's device-memory ordering rules. All spin loops and task @@ -91,6 +99,9 @@ Buffers have distinct ownership: - **Scratch:** temporary activations and partial results; storage may be reused after the last consumer. - **Parameters:** records owned by a particular program, including its shapes and binding offsets. - **Output ring:** tokens published by GPU control operations and consumed by the host. +- **Host buffers:** allocated by the session and bound by name (the expert cache, its slot table, staging rows); + they stay resident for every program that names them, because kernels can reach them through GPU addresses held + in other buffers. Programs within a session can share persistent buffers by name. Parameter records are program-specific. Scratch allocation must never alias live persistent state, acceptance logs, or output buffers. diff --git a/docs/design/flash-next.md b/docs/design/flash-next.md index fcadd776..9408f59c 100644 --- a/docs/design/flash-next.md +++ b/docs/design/flash-next.md @@ -610,3 +610,10 @@ Both acceptance runs pin it off, and with every expert resident no swap would ha 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]. diff --git a/monolith/compiler/barriers.py b/monolith/compiler/barriers.py index 939a596c..f47eaf8a 100644 --- a/monolith/compiler/barriers.py +++ b/monolith/compiler/barriers.py @@ -35,12 +35,7 @@ def place_barriers(program: Program, mode: str = "minimal") -> int: for o in ops: o.barrier_before = True return len(ops) - sets = [] # per op: (reads, writes) - for o in ops: - w_idx = o.meta.get("writes") - bound = {b[1] for b in o.bindings} - writes = bound if w_idx is None else {b[1] for b in o.bindings if b[0] in w_idx} - sets.append((bound - writes, writes)) + sets = [o.access() for o in ops] # per op: (reads, writes) def conflict(r, w, reads, writes): return bool(w & (reads | writes)) or bool(r & writes) diff --git a/monolith/core/step_state.py b/monolith/core/step_state.py index db7d304e..41af015c 100644 --- a/monolith/core/step_state.py +++ b/monolith/core/step_state.py @@ -54,7 +54,7 @@ def __init__(self, t_max: int = 8, gamma_max: int = 7) -> None: Field("checkpoint_index", DType.U32, doc="GDN/conv checkpoint slot to keep"), Field("drafter_ctx_len", DType.U32, doc="positions appended to the drafter's injected-context KV"), Field("done", DType.U32, doc="stop condition met; queued steps return at their first instruction"), - Field("error", DType.U32, doc="non-zero: 1 token ring overflow, 2 context capacity reached, 3 bounded mixer barrier timeout"), + Field("error", DType.U32, doc="non-zero: 1 token ring overflow, 2 context capacity reached, 3 bounded mixer barrier timeout, 4 a host step failed"), Field("ring_head", DType.U32, doc="token ring: next slot the GPU writes"), Field("ring_tail", DType.U32, doc="token ring: next slot the host reads (host-written)"), Field("prefill_left", DType.U32, doc="prompt chunks still to feed after this step; the advance emits a token only at 0"), diff --git a/monolith/runtime/__init__.py b/monolith/runtime/__init__.py index 5ec86f9d..336868c5 100644 --- a/monolith/runtime/__init__.py +++ b/monolith/runtime/__init__.py @@ -19,5 +19,5 @@ def is_available() -> bool: __all__ = ["is_available"] if _native is not None: from .engine import Engine, StepReport # noqa: E402,F401 - from .program import BufferSpec, KernelSpec, OpSpec, Program # noqa: E402,F401 - __all__ += ["Engine", "StepReport", "BufferSpec", "KernelSpec", "OpSpec", "Program"] + from .program import BufferSpec, HostPoint, KernelSpec, OpSpec, Program # noqa: E402,F401 + __all__ += ["Engine", "StepReport", "BufferSpec", "HostPoint", "KernelSpec", "OpSpec", "Program"] diff --git a/monolith/runtime/engine.py b/monolith/runtime/engine.py index aeb3df98..f9433926 100644 --- a/monolith/runtime/engine.py +++ b/monolith/runtime/engine.py @@ -2,8 +2,8 @@ from __future__ import annotations -from dataclasses import dataclass -from typing import Dict, List, Optional +from dataclasses import dataclass, field +from typing import Callable, Dict, List, Optional, Union from . import _native as nt from .program import Program @@ -21,6 +21,7 @@ class StepReport: encode_ms: float = 0.0 commit_ms: float = 0.0 wait_ms: float = 0.0 + handoff_gaps_ms: List[float] = field(default_factory=list) # GPU idle time at each host-point handoff @property def host_fraction(self) -> float: @@ -46,16 +47,28 @@ def compile_pipelines(program, device, *, fast_math=False, cache=None): class Engine: """``buffers`` lets several programs share device buffers by name (a prefill program at T = P and a decode - program at T = 1 over the same weights, states and StepState).""" + program at T = 1 over the same weights, states and StepState), and supplies every buffer of role "host".""" def __init__(self, program: Program, device: Optional[nt.Device] = None, buffers: Optional[Dict[str, nt.Buffer]] = None, - fast_math: bool = False, pipeline_cache: Optional[dict] = None) -> None: - """``fast_math``: compile the kernels with Metal's fast math mode (the default is the safe mode).""" + fast_math: bool = False, pipeline_cache: Optional[dict] = None, + host_tasks: Optional[Dict[str, Union["nt.HostTask", Callable[[int, int], None]]]] = None, + host_timeout_ms: int = 20000) -> None: + """``fast_math``: compile the kernels with Metal's fast math mode (the default is the safe mode). + ``host_tasks``: the task of each host point, by its task name: an ``nt.HostTask`` or a Python callable + ``fn(step, point)``. ``host_timeout_ms``: the longest a run waits for the GPU to reach a host point or finish a + command buffer.""" self.program = program self.fast_math = fast_math self.dev = device or nt.Device() self.buffers: Dict[str, nt.Buffer] = {} for name, spec in program.buffers.items(): + if spec.role == "host": # the session allocates it; the program binds it by name + if buffers is None or name not in buffers: + raise ValueError(f"host buffer {name}: the session allocates it and passes it in Engine(buffers=...)") + if buffers[name].nbytes < spec.nbytes: + raise ValueError(f"host buffer {name}: {buffers[name].nbytes} bytes, program needs {spec.nbytes}") + self.buffers[name] = buffers[name] + continue if buffers is not None and name in buffers and spec.role != "params" and buffers[name].nbytes >= spec.nbytes: self.buffers[name] = buffers[name] # shared (weights, states, StepState, ring, arena values) continue # never a params record: its bytes are this program's own @@ -74,6 +87,12 @@ def __init__(self, program: Program, device: Optional[nt.Device] = None, buffers buf = nt.Buffer(self.dev, spec.nbytes) buf.fill(0) self.buffers[name] = buf + for op in program.ops: + for name in [*op.meta.get("indirect_reads", ()), *op.meta.get("indirect_writes", ())]: + if name not in self.buffers: + raise ValueError(f"op {op.name or op.kernel}: reaches {name!r} through a GPU address, which is not a program buffer") + if program.host_points: + program.check_host_points(self._same_memory) self.pipelines = compile_pipelines(program, self.dev, fast_math=fast_math, cache=pipeline_cache) self.ops = [] for o in program.ops: @@ -82,34 +101,69 @@ def __init__(self, program: Program, device: Optional[nt.Device] = None, buffers d.buffer(index, self.buffers[bname], off) for index, length in o.threadgroup_memory: d.threadgroup_memory(index, length) + for name in o.meta.get("indirect_reads", ()): # Queue.run and Queue.profile declare these resident + d.use(self.buffers[name]) + for name in o.meta.get("indirect_writes", ()): + d.use(self.buffers[name], True) self.ops.append(d) self.icb = nt.Icb(self.dev, self.ops) lay = program.layout ring = self.buffers[program.ring] if ring.nbytes < program.ring_capacity * 8: raise ValueError("the token ring needs 8 bytes per slot: (sequence << 32) | token") - # Programs can retain unreferenced state buffers for session reuse. Only - # buffers actually bound by the ICB need a Metal residency declaration. + # Programs can retain unreferenced state buffers for session reuse. Only buffers the ICB binds, buffers its + # kernels reach through GPU addresses, and the session's host buffers need a Metal residency declaration. resources = {name: self.buffers[name] for op in program.ops for _, name, _ in op.bindings} + for op in program.ops: + for name in [*op.meta.get("indirect_reads", ()), *op.meta.get("indirect_writes", ())]: + resources[name] = self.buffers[name] + resources.update({name: self.buffers[name] for name, spec in program.buffers.items() if spec.role == "host"}) self.runner = nt.Runner(self.dev, self.icb, self.ops, list(resources.values()), self.buffers[program.step_state], lay.offset("done"), lay.offset("ring_head"), lay.offset("ring_tail"), ring, program.ring_capacity, [buffer for name, buffer in resources.items() if program.buffers[name].role in ('weights', 'params')]) + self.host_tasks = [] + if program.host_points: + for p in program.host_points: + task = (host_tasks or {}).get(p.task) + if task is None: + raise ValueError(f"host point {p.task!r}: no task supplied (Engine(host_tasks={{{p.task!r}: ...}}))") + self.host_tasks.append((p.publish, p.wait, task if isinstance(task, nt.HostTask) else nt.CallableTask(task))) + self.runner.set_host_points(self.host_tasks, lay.offset("error"), host_timeout_ms) + + def _same_memory(self, a: str, b: str) -> bool: + """Whether two buffer names reach overlapping memory (a session can pass one buffer under two names).""" + x, y = self.buffers[a], self.buffers[b] + return a == b or (x.gpu_address < y.gpu_address + y.nbytes and y.gpu_address < x.gpu_address + x.nbytes) def run(self, max_steps: int, *, steps_per_cb: int = 8, in_flight: int = 3, reencode: bool = False, max_tokens: int = 0) -> StepReport: """Replay up to ``max_steps`` steps (``max_tokens`` > 0: stop submitting once that many tokens arrived; the - queued buffers still complete, so a few more steps may run).""" + queued buffers still complete, so a few more steps may run). A failed run raises RuntimeError with the run's + StepReport, its tokens included, as ``report``; the exception a Python task raised is its cause, except that a + task's KeyboardInterrupt or SystemExit is raised as it was.""" st = self.runner.run(max_steps, steps_per_cb, in_flight, reencode, max_tokens) - if st.error: - raise RuntimeError(st.error) - if st.done and int(self.state()["error"]) == 3: - raise RuntimeError("Megakernel: bounded worker barrier timed out") - return StepReport(st.steps_submitted, st.command_buffers, st.gpu_ms, st.wall_ms, st.host_busy_ms, st.done, self.runner.drain(), - st.encode_ms, st.commit_ms, st.wait_ms) + report = StepReport(st.steps_submitted, st.command_buffers, st.gpu_ms, st.wall_ms, st.host_busy_ms, st.done, self.runner.drain(), + st.encode_ms, st.commit_ms, st.wait_ms, list(st.handoff_gaps_ms)) + code = int(self.state()["error"]) if st.done else 0 + message = st.error or {3: "Megakernel: bounded worker barrier timed out", + 4: "a host step failed in an earlier run; the program's state is unusable"}.get(code) + if not message: + return report + cause = None + if st.failed_task >= 0: # the failing task's own: an older one left elsewhere stays out + task = self.runner.host_tasks()[st.failed_task] + cause = task.take_exception() if isinstance(task, nt.CallableTask) else None + if cause is not None and not isinstance(cause, Exception): + raise cause # KeyboardInterrupt, SystemExit + error = RuntimeError(message) + error.report = report + raise error from cause def profile(self, steps: int = 3) -> List[List[Tuple[float, float]]]: """Per-dispatch GPU (start, end) ms for ``steps`` re-encoded steps (one encoder per op with timestamp counter samples, so the numbers carry encoder-boundary gaps the ICB replay does not have — use them for the shares and the per-op durations, not for the step total).""" + if self.program.host_points: + raise RuntimeError("profile() dispatches the ops without their tasks; a program with host points runs only through run()") q = nt.Queue(self.dev) return [q.profile(self.ops) for _ in range(steps)] diff --git a/monolith/runtime/program.py b/monolith/runtime/program.py index b1635d1b..fbd47833 100644 --- a/monolith/runtime/program.py +++ b/monolith/runtime/program.py @@ -7,7 +7,7 @@ import json from dataclasses import dataclass, field from pathlib import Path -from typing import Dict, List, Optional, Sequence, Tuple +from typing import Callable, Dict, List, Optional, Sequence, Set, Tuple from ..core.step_state import StepStateLayout @@ -24,7 +24,7 @@ class KernelSpec: class BufferSpec: nbytes: int init: Optional[bytes] = None # initial contents (zeros if None) - role: str = "arena" # "weights" | "state" | "arena" | "step_state" | "ring" | "params" + role: str = "arena" # "weights" | "state" | "arena" | "step_state" | "ring" | "params" | "host" file: Optional[str] = None # weights: a page-aligned window of this file, mapped without a copy file_offset: int = 0 @@ -40,6 +40,30 @@ class OpSpec: name: str = "" meta: Dict[str, object] = field(default_factory=dict) # informational: op kind, bytes streamed, layer … (JSON) + def access(self) -> Tuple[Set[str], Set[str]]: + """(reads, writes) as buffer names. ``meta["writes"]`` lists the binding slots the op writes; an op without it + writes every buffer it binds. ``meta["indirect_reads"]`` and ``meta["indirect_writes"]`` name buffers the op + reaches through GPU addresses held in another buffer rather than through a binding.""" + w_idx = self.meta.get("writes") + bound = {b[1] for b in self.bindings} + writes = bound if w_idx is None else {b[1] for b in self.bindings if b[0] in w_idx} + writes |= set(self.meta.get("indirect_writes", ())) + return (bound | set(self.meta.get("indirect_reads", ()))) - writes, writes + + +@dataclass +class HostPoint: + """CPU work inside a step (design: Runtime program). Boundary b sits before op b of the step. 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).""" + task: str # the name the session's task is supplied under (Engine(host_tasks=...)) + publish: int + wait: int + writes: List[str] = field(default_factory=list) + reads: List[str] = field(default_factory=list) + @dataclass class Program: @@ -53,6 +77,41 @@ class Program: context_capacity: int = 0 # positions a sequence may occupy (0 = unbounded): the serial ops stop the program (error 2) beyond it backend_id: str = "common" config_digest: str = "" + host_points: List[HostPoint] = field(default_factory=list) # in program order: publish boundaries never decrease + + def check_host_points(self, same: Optional[Callable[[str, str], bool]] = None) -> None: + """Raises ValueError unless every host point is well formed and its task cannot race the GPU: no op of + [publish, wait), which may run while the task runs, writes a buffer the task reads or writes, or reads a buffer + the task writes. ``same(a, b)`` says whether two buffer names reach the same memory; by default only equal + names do (the Engine compares GPU address ranges).""" + same = same or (lambda a, b: a == b) + n, prev = len(self.ops), 0 + for i, p in enumerate(self.host_points): + where = f"host point {i} ({p.task!r})" + if not p.task: + raise ValueError(f"host point {i}: needs a task name") + if not 0 <= p.publish <= p.wait <= n: + raise ValueError(f"{where}: need 0 <= publish ({p.publish}) <= wait ({p.wait}) <= {n}, the op count") + if p.publish < prev: + raise ValueError(f"{where}: publish boundaries must not decrease in program order") + prev = p.publish + for name in [*p.writes, *p.reads]: + if name not in self.buffers: + raise ValueError(f"{where}: unknown buffer {name!r}") + for name in p.writes: + if self.buffers[name].role in ("weights", "params"): + raise ValueError(f"{where}: writes {name!r}, a read-only {self.buffers[name].role} buffer") + for j in range(p.publish, p.wait): + reads, writes = self.ops[j].access() + op = f"op {j} ({self.ops[j].name or self.ops[j].kernel})" + for t in p.writes: + hit = next((b for b in sorted(reads | writes) if same(t, b)), None) + if hit is not None: + raise ValueError(f"{where}: {op} accesses {hit!r} while the task writes {t!r}") + for t in p.reads: + hit = next((b for b in sorted(writes) if same(t, b)), None) + if hit is not None: + raise ValueError(f"{where}: {op} writes {hit!r} while the task reads {t!r}") def to_json(self) -> str: d = {"version": 1, "step_state": self.step_state, "ring": self.ring, "ring_capacity": self.ring_capacity, @@ -63,7 +122,9 @@ def to_json(self) -> str: "buffers": {k: {"nbytes": v.nbytes, "role": v.role, "init_hex": v.init.hex() if v.init is not None else None, "file": v.file, "file_offset": v.file_offset} for k, v in self.buffers.items()}, "ops": [{"kernel": o.kernel, "bindings": o.bindings, "grid": o.grid, "threadgroup": o.threadgroup, - "barrier_before": o.barrier_before, "threadgroup_memory": o.threadgroup_memory, "name": o.name, "meta": o.meta} for o in self.ops]} + "barrier_before": o.barrier_before, "threadgroup_memory": o.threadgroup_memory, "name": o.name, "meta": o.meta} for o in self.ops], + "host_points": [{"task": h.task, "publish": h.publish, "wait": h.wait, "writes": h.writes, "reads": h.reads} + for h in self.host_points]} return json.dumps(d, indent=1) @classmethod @@ -79,7 +140,9 @@ def from_json(cls, text: str) -> "Program": [tuple(t) for t in o.get("threadgroup_memory", [])], o.get("name", ""), dict(o.get("meta", {}))) for o in d["ops"]], step_state=d["step_state"], ring=d["ring"], ring_capacity=d["ring_capacity"], context_capacity=int(d.get("context_capacity", 0)), layout=StepStateLayout(d["layout"]["t_max"], d["layout"]["gamma_max"]), - backend_id=d.get("backend_id", "common"), config_digest=d.get("config_digest", "")) + backend_id=d.get("backend_id", "common"), config_digest=d.get("config_digest", ""), + host_points=[HostPoint(h["task"], int(h["publish"]), int(h["wait"]), list(h.get("writes", [])), list(h.get("reads", []))) + for h in d.get("host_points", [])]) def save(self, path: str | Path) -> None: Path(path).write_text(self.to_json()) diff --git a/probes/README.md b/probes/README.md index 026d24e9..71d026ca 100644 --- a/probes/README.md +++ b/probes/README.md @@ -32,6 +32,7 @@ virtualized macOS (hosted CI runners): its paravirtual GPU does not schedule lik | `p13_decode_gemv` | real FP8-E4M3 and NVFP4 decode GEMV/GEMM (17408 × 5120, 16-byte loads, R-row blocks, T ∈ {1, 2, 4, 8}) in both block-lane-major lane orders, at the crew geometry and at conventional occupancy, checked against a CPU reference — the first half of plan M1. `./build/p13_decode_gemv check` compiles every variant without running | | `p14_tensor_ops` | M5 neural accelerators: `mpp::tensor_ops::matmul2d` from FP8/NVFP4 tiles dequantized into threadgroup memory (and from half weights directly), TM ∈ {8…64}, checked against a CPU reference; needs only the Command Line Tools. `./build/p14_tensor_ops check` compiles every variant | | `p15_frame_pacing` | on-screen frame pacing: a window presents one frame per vsync while compute command buffers of 8 / 16 / 33 / 66 / 133 ms (ALU-bound, then bus-bound) run back to back with 3 in flight; presented-time intervals, late frames, fps per buffer length. Needs the screen on and unlocked (it skips otherwise); opens a small floating window for ~70 s | +| `p16_host_handoff` | host handoffs between GPU passes through `MTLSharedEvent`, the host-step runtime's mechanism: GPU-to-CPU and CPU-to-GPU visibility over 1,000 steps with an in-buffer `encodeWaitForEvent` and with a second command buffer the CPU commits after its work; the GPU idle gap across one handoff (stage-boundary timestamps) for each, with the second command buffer encoded before and after the signal (a lower bound on the host-step runtime's handoff, which `tools/bench/host_handoff.py` measures), against a plain pass boundary; how long after a command buffer's status reads Completed its last signal is visible; whether a command buffer parked at an in-buffer wait for 2 to 6 s survives the GPU watchdog, after a pass and as its first command. `P16_PARKS=0` skips the parks (about 37 s; on the M3 Max every park of 5 s or more hits the watchdog) | Safety: an Apple9 GPU does not preempt a running dispatch and an Apple10 GPU does so only sometimes (`p6`), so every loop here is bounded and the longest single dispatch is ~1.5 s. Expect brief display stalls during `p3`/`p6`/`p6b`. Never add an unbounded spin to a probe. diff --git a/probes/p16_host_handoff.m b/probes/p16_host_handoff.m new file mode 100644 index 00000000..58405f50 --- /dev/null +++ b/probes/p16_host_handoff.m @@ -0,0 +1,265 @@ +#import +#import +#include +#include +#include "probe_common.h" +// Probe: host handoffs between GPU passes through MTLSharedEvent, the mechanism of the host-step runtime. A pass +// signals an event and the CPU observes it and does its work; the GPU work that needs the CPU's result either waits +// in the same command buffer for a second event the CPU signals (encodeWaitForEvent), or sits in a second command +// buffer the CPU commits once its work is done. Passes are ordered by one MTLFence (ICB-referenced resources made +// resident through a residency set are not hazard-tracked). +// 1. visibility: a GPU write before the signal is seen by the CPU once it observes the signal; a CPU write is seen +// by the GPU work after it (1,000 steps, ICB ranges): a. the in-buffer wait, two command buffers in flight; +// b. the second command buffer, committed after the CPU write +// 2. the GPU idle gap across one handoff with no CPU work (stage-boundary timestamps): the in-buffer wait with a +// spinning CPU and with waitUntilSignaledValue, the second command buffer encoded before the signal (the host +// only commits it) and encoded after it, and a plain pass boundary. Encoded after the signal is a lower bound on +// the host-step runtime's handoff, which also reads StepState, runs the task and encodes a whole segment of +// passes; tools/bench/host_handoff.py measures that handoff itself +// 3. a command buffer parked at an in-buffer wait after its first pass while the CPU sleeps 2 to 6 s: does it +// finish without an error (the GPU watchdog), and do another queue's command buffers keep completing meanwhile? +// 4. the same with the wait as the command buffer's first command (no pass has run before it) +// 5. a command buffer whose last command is a signal: how long after its status reads Completed is the signal +// visible to the CPU (the runtime's grace before it fails a point whose command buffer finished without it) +static double now_ms(void) { static mach_timebase_info_data_t tb; if (!tb.denom) mach_timebase_info(&tb); return (double)mach_absolute_time() * tb.numer / tb.denom / 1e6; } +static int cmp_d(const void* a, const void* b) { double x = *(const double*)a, y = *(const double*)b; return x < y ? -1 : x > y; } +static id pso(id d, id l, NSString* n, BOOL icb) { + NSError* e = nil; MTLComputePipelineDescriptor* pd = [MTLComputePipelineDescriptor new]; + pd.computeFunction = [l newFunctionWithName:n]; pd.supportIndirectCommandBuffers = icb; + id p = [d newComputePipelineStateWithDescriptor:pd options:0 reflection:nil error:&e]; + if (!p) { printf("PSO %s: %s\n", n.UTF8String, e.localizedDescription.UTF8String); exit(1); } + return p; +} +// bounded host wait for a GPU signal: spin (mode 0) or waitUntilSignaledValue (mode 1); 0 on timeout +static int host_wait(id ev, uint64_t v, int mode, double timeout_ms) { + if (mode == 1) return [ev waitUntilSignaledValue:v timeoutMS:(uint64_t)timeout_ms] ? 1 : 0; + double t0 = now_ms(); + while (ev.signaledValue < v) if (now_ms() - t0 > timeout_ms) return 0; + return 1; +} +// part 2's pass B: one small dispatch behind the fence, sampled at stage boundaries 2 and 3 +static void encode_pass_b(id cb, id sb, id fence, + id spin, id work) { + uint32_t one = 1; + MTLComputePassDescriptor* p2 = [MTLComputePassDescriptor computePassDescriptor]; + p2.sampleBufferAttachments[0].sampleBuffer = sb; p2.sampleBufferAttachments[0].startOfEncoderSampleIndex = 2; p2.sampleBufferAttachments[0].endOfEncoderSampleIndex = 3; + id en = [cb computeCommandEncoderWithDescriptor:p2]; + [en waitForFence:fence]; [en setComputePipelineState:spin]; [en setBuffer:work offset:0 atIndex:0]; [en setBytes:&one length:4 atIndex:1]; + [en dispatchThreadgroups:MTLSizeMake(1, 1, 1) threadsPerThreadgroup:MTLSizeMake(32, 1, 1)]; [en updateFence:fence]; [en endEncoding]; +} +int main() { @autoreleasepool { + id d = MTLCreateSystemDefaultDevice(); NSError* e = nil; + NSString* src = [NSString stringWithContentsOfFile:@"p16_host_handoff.metal" encoding:NSUTF8StringEncoding error:&e]; + id lib = [d newLibraryWithSource:src options:nil error:&e]; + if (!lib) { printf("compile: %s\n", e.localizedDescription.UTF8String); return 1; } + const int cores = gpu_cores(); + id bump = pso(d, lib, @"bump", YES), spin = pso(d, lib, @"spin_work", NO); + id a = [d newBufferWithLength:64 options:MTLResourceStorageModeShared]; + id logb = [d newBufferWithLength:4096 * 4 options:MTLResourceStorageModeShared]; + id work = [d newBufferWithLength:4096 options:MTLResourceStorageModeShared]; + memset(a.contents, 0, 64); memset(logb.contents, 0xff, 4096 * 4); memset(work.contents, 0, 4096); + MTLIndirectCommandBufferDescriptor* desc = [MTLIndirectCommandBufferDescriptor new]; + desc.commandTypes = MTLIndirectCommandTypeConcurrentDispatch; desc.inheritBuffers = NO; desc.inheritPipelineState = NO; + desc.maxKernelBufferBindCount = 2; + id icb = [d newIndirectCommandBufferWithDescriptor:desc maxCommandCount:3 options:0]; + for (int c = 0; c < 3; c++) { + id cmd = [icb indirectComputeCommandAtIndex:c]; + [cmd setComputePipelineState:bump]; [cmd setKernelBuffer:a offset:0 atIndex:0]; [cmd setKernelBuffer:logb offset:0 atIndex:1]; + [cmd concurrentDispatchThreadgroups:MTLSizeMake(1, 1, 1) threadsPerThreadgroup:MTLSizeMake(32, 1, 1)]; [cmd setBarrier]; + } + MTLResidencySetDescriptor* rd = [MTLResidencySetDescriptor new]; rd.initialCapacity = 8; + id rs = [d newResidencySetWithDescriptor:rd error:&e]; + [rs addAllocation:a]; [rs addAllocation:logb]; [rs addAllocation:work]; [rs commit]; [rs requestResidency]; + id q = [d newCommandQueue]; [q addResidencySet:rs]; + id gpu_ev = [d newSharedEvent], host_ev = [d newSharedEvent]; + id fence = [d newFence]; + uint64_t v = 0; + printf("gpu cores: %d\n", cores); + + // ---- 1. visibility, two command buffers in flight ----------------------------------------------------------- + { + const int N = 1000; int seen_bad = 0, log_bad = 0, timeouts = 0; BOOL fence_live = NO; + volatile uint32_t* av = (volatile uint32_t*)a.contents; + id inflight[2] = {nil, nil}; uint64_t vals[2] = {0, 0}; + for (int it = 0; it <= N; it++) { + if (it < N) { // encode step `it`: pass [0,1), signal, wait, pass [1,3) + id cb = [q commandBuffer]; + id en = [cb computeCommandEncoder]; + if (fence_live) [en waitForFence:fence]; + [en executeCommandsInBuffer:icb withRange:NSMakeRange(0, 1)]; [en updateFence:fence]; [en endEncoding]; fence_live = YES; + [cb encodeSignalEvent:gpu_ev value:v + 1]; [cb encodeWaitForEvent:host_ev value:v + 1]; + en = [cb computeCommandEncoder]; [en waitForFence:fence]; + [en executeCommandsInBuffer:icb withRange:NSMakeRange(1, 2)]; [en updateFence:fence]; [en endEncoding]; + [cb commit]; + inflight[it & 1] = cb; vals[it & 1] = ++v; + } + if (it >= 1) { // serve step it-1's host point, then retire its command buffer + int s = (it - 1) & 1; + if (!host_wait(gpu_ev, vals[s], 0, 2000)) { timeouts++; host_ev.signaledValue = v; break; } + if (av[0] != (uint32_t)(3 * (it - 1) + 1)) seen_bad++; // the first pass of step it-1 bumped a[0] + av[1] = 100000 + (it - 1); // the CPU write the step's next pass logs + host_ev.signaledValue = vals[s]; + [inflight[s] waitUntilCompleted]; + if (inflight[s].error) printf(" command buffer error: %s\n", inflight[s].error.localizedDescription.UTF8String); + if (((uint32_t*)logb.contents)[(3 * (it - 1) + 1) & 4095] != (uint32_t)(100000 + (it - 1))) log_bad++; + } + } + printf("1a. in-buffer wait, %d steps, 2 in flight: GPU->CPU misses %d, CPU->GPU misses %d, host timeouts %d\n", N, seen_bad, log_bad, timeouts); + } + { // 1b: a segment is [pass [1,3) of step it-1, pass [0,1) of step it, signal]; the CPU commits the next segment + // after it has checked the signalled step and written the word that step's [1,3) pass logs + const int N = 1000; int seen_bad = 0, log_bad = 0, timeouts = 0; + volatile uint32_t* av = (volatile uint32_t*)a.contents; + memset(a.contents, 0, 64); memset(logb.contents, 0xff, 4096 * 4); + id last = nil; + for (int it = 0; it <= N; it++) { + id cb = [q commandBuffer]; + id en = [cb computeCommandEncoder]; + [en waitForFence:fence]; + if (it > 0) { [en executeCommandsInBuffer:icb withRange:NSMakeRange(1, 2)]; [en updateFence:fence]; [en endEncoding]; + en = [cb computeCommandEncoder]; [en waitForFence:fence]; } + if (it < N) [en executeCommandsInBuffer:icb withRange:NSMakeRange(0, 1)]; + [en updateFence:fence]; [en endEncoding]; + if (it < N) [cb encodeSignalEvent:gpu_ev value:v + 1]; + [cb commit]; last = cb; + if (it == N) break; + v++; + if (!host_wait(gpu_ev, v, 0, 2000)) { timeouts++; break; } + if (av[0] != (uint32_t)(3 * it + 1)) seen_bad++; // step it's first pass bumped a[0] + av[1] = 200000 + it; // the word step it's [1,3) pass logs + } + [last waitUntilCompleted]; + if (last.error) printf(" command buffer error: %s\n", last.error.localizedDescription.UTF8String); + for (int it = 0; it < N; it++) if (((uint32_t*)logb.contents)[(3 * it + 1) & 4095] != (uint32_t)(200000 + it)) log_bad++; + printf("1b. second command buffer, %d steps: GPU->CPU misses %d, CPU->GPU misses %d, host timeouts %d\n", N, seen_bad, log_bad, timeouts); + } + + // ---- 2. GPU idle gap across a host round trip ---------------------------------------------------------------- + { + id ts = nil; + for (id cs in d.counterSets) if ([cs.name isEqualToString:MTLCommonCounterSetTimestamp]) ts = cs; + if (!ts || ![d supportsCounterSampling:MTLCounterSamplingPointAtStageBoundary]) { printf("2. skipped: no stage-boundary timestamps\n"); } + else { + MTLCounterSampleBufferDescriptor* sd = [MTLCounterSampleBufferDescriptor new]; + sd.counterSet = ts; sd.storageMode = MTLStorageModeShared; sd.sampleCount = 4; + id sb = [d newCounterSampleBufferWithDescriptor:sd error:&e]; + uint32_t busy = 20000; // pass A runs ~0.5 ms so the command buffer is executing when it signals + const char* names[5] = {"plain pass boundary (fence only)", "in-buffer wait, spinning CPU", "in-buffer wait, waitUntilSignaledValue", + "second buffer encoded before the signal", "second buffer encoded after the signal"}; + for (int round = 0; round < 2; round++) + for (int mode = -1; mode <= 3; mode++) { + const int N = 200; double gaps[200]; + MTLTimestamp c0, g0, c1, g1; [d sampleTimestamps:&c0 gpuTimestamp:&g0]; + for (int it = 0; it < N; it++) { + id cb = [q commandBuffer]; + MTLComputePassDescriptor* p1 = [MTLComputePassDescriptor computePassDescriptor]; + p1.sampleBufferAttachments[0].sampleBuffer = sb; p1.sampleBufferAttachments[0].startOfEncoderSampleIndex = 0; p1.sampleBufferAttachments[0].endOfEncoderSampleIndex = 1; + id en = [cb computeCommandEncoderWithDescriptor:p1]; + [en waitForFence:fence]; [en setComputePipelineState:spin]; [en setBuffer:work offset:0 atIndex:0]; [en setBytes:&busy length:4 atIndex:1]; + [en dispatchThreadgroups:MTLSizeMake(cores, 1, 1) threadsPerThreadgroup:MTLSizeMake(256, 1, 1)]; [en updateFence:fence]; [en endEncoding]; + if (mode == 0 || mode == 1) { [cb encodeSignalEvent:gpu_ev value:v + 1]; [cb encodeWaitForEvent:host_ev value:v + 1]; } + if (mode >= 2) [cb encodeSignalEvent:gpu_ev value:v + 1]; + if (mode == 2) { // the continuation is encoded before the signal; the host only commits it + id cb2 = [q commandBuffer]; + encode_pass_b(cb2, sb, fence, spin, work); + [cb commit]; v++; + if (!host_wait(gpu_ev, v, 0, 2000)) printf(" host wait timed out\n"); + [cb2 commit]; [cb2 waitUntilCompleted]; + } else if (mode == 3) { // the continuation is encoded once the signal is seen (the runtime's lower bound) + [cb commit]; v++; + if (!host_wait(gpu_ev, v, 0, 2000)) printf(" host wait timed out\n"); + id cb2 = [q commandBuffer]; + encode_pass_b(cb2, sb, fence, spin, work); + [cb2 commit]; [cb2 waitUntilCompleted]; + } else { + encode_pass_b(cb, sb, fence, spin, work); + [cb commit]; + if (mode >= 0) { + v++; + if (!host_wait(gpu_ev, v, mode, 2000)) { printf(" host wait timed out\n"); host_ev.signaledValue = v; } + host_ev.signaledValue = v; + } + } + [cb waitUntilCompleted]; + [d sampleTimestamps:&c1 gpuTimestamp:&g1]; + NSData* data = [sb resolveCounterRange:NSMakeRange(0, 4)]; + const MTLCounterResultTimestamp* r = (const MTLCounterResultTimestamp*)data.bytes; + double scale = (g1 > g0) ? (double)(c1 - c0) / (double)(g1 - g0) : 1.0; // ns per GPU tick + gaps[it] = (double)(r[2].timestamp - r[1].timestamp) * scale / 1e3; + } + qsort(gaps, N, sizeof(double), cmp_d); + printf("2. round %d, %-40s: GPU gap end of pass A -> start of pass B: min %.1f p10 %.1f median %.1f p90 %.1f max %.1f us\n", + round + 1, names[mode + 1], gaps[0], gaps[N / 10], gaps[N / 2], gaps[9 * N / 10], gaps[N - 1]); + } + } + } + + // ---- 5. the last signal of a command buffer whose status reads Completed -------------------------------------- + { + const int N = 2000; double lag[2000]; int missing = 0; + for (int it = 0; it < N; it++) { + id cb = [q commandBuffer]; + id en = [cb computeCommandEncoder]; + [en waitForFence:fence]; [en executeCommandsInBuffer:icb withRange:NSMakeRange(0, 1)]; [en updateFence:fence]; [en endEncoding]; + [cb encodeSignalEvent:gpu_ev value:v + 1]; + [cb commit]; v++; + const double t0 = now_ms(); + while (cb.status < MTLCommandBufferStatusCompleted && now_ms() - t0 < 2000) {} + const double tc = now_ms(); + while (gpu_ev.signaledValue < v && now_ms() - tc < 100) {} + lag[it] = (now_ms() - tc) * 1e3; + if (gpu_ev.signaledValue < v) missing++; + } + qsort(lag, N, sizeof(double), cmp_d); + printf("5. %d command buffers ending in a signal: the signal visible after the status reads Completed: min %.2f median %.2f " + "p99 %.2f max %.2f us; not within 100 ms: %d\n", N, lag[0], lag[N / 2], lag[99 * N / 100], lag[N - 1], missing); + } + + // ---- 3. and 4. a command buffer parked at a wait (P16_PARKS=0 skips these: ~37 s, deliberate GPU timeouts) ------ + if (!getenv("P16_PARKS") || atoi(getenv("P16_PARKS")) != 0) { + id other = [d newCommandQueue]; + // every case runs on a fresh queue: once a queue's buffer has hit the watchdog, Metal ignores that queue's later + // submissions (kIOGPUCommandBufferCallbackErrorSubmissionsIgnored), which would poison the next case + const double parks_s[8] = {2, 4, 4.5, 5, 5.5, 6, 4, 6}; + for (int k = 0; k < 8; k++) { + const int at_start = k >= 6; // part 4: the wait is the first command of the buffer + const double park = parks_s[k]; + id cq = [d newCommandQueue]; [cq addResidencySet:rs]; + id cb = [cq commandBuffer]; + id en; + if (!at_start) { + en = [cb computeCommandEncoder]; + [en executeCommandsInBuffer:icb withRange:NSMakeRange(0, 1)]; [en updateFence:fence]; [en endEncoding]; + [cb encodeSignalEvent:gpu_ev value:v + 1]; + } + [cb encodeWaitForEvent:host_ev value:v + 1]; + en = [cb computeCommandEncoder]; if (!at_start) [en waitForFence:fence]; + [en executeCommandsInBuffer:icb withRange:NSMakeRange(1, 2)]; [en updateFence:fence]; [en endEncoding]; + [cb commit]; v++; + int ok = at_start ? 1 : host_wait(gpu_ev, v, 1, 5000); + if (at_start) gpu_ev.signaledValue = v; // keep the GPU event's value in step with v + // while the command buffer is parked, another queue keeps submitting small command buffers + double t0 = now_ms(), worst = 0; int done_other = 0, err_other = 0; + while (now_ms() - t0 < park * 1e3) { + id o = [other commandBuffer]; + id oe = [o computeCommandEncoder]; + uint32_t n = 2000; + [oe setComputePipelineState:spin]; [oe setBuffer:work offset:0 atIndex:0]; [oe setBytes:&n length:4 atIndex:1]; + [oe dispatchThreadgroups:MTLSizeMake(1, 1, 1) threadsPerThreadgroup:MTLSizeMake(32, 1, 1)]; [oe endEncoding]; + double s0 = now_ms(); [o commit]; [o waitUntilCompleted]; double lat = now_ms() - s0; + if (lat > worst) worst = lat; + if (o.error) err_other++; else done_other++; + usleep(50000); + } + MTLCommandBufferStatus mid = cb.status; + double r0 = now_ms(); + host_ev.signaledValue = v; + [cb waitUntilCompleted]; + printf("%d. parked %4.1f s %s: publish seen %s; status while parked %d; finished %.2f ms after the host signal; error: %s; " + "GPU time %.0f ms; other queue: %d command buffers completed (%d errors), worst latency %.2f ms\n", + at_start ? 4 : 3, park, at_start ? "at the start" : "after a pass", ok ? "yes" : "NO", (int)mid, now_ms() - r0, + cb.error ? cb.error.localizedDescription.UTF8String : "none", (cb.GPUEndTime - cb.GPUStartTime) * 1e3, done_other, err_other, worst); + } + } +} +return 0; } diff --git a/probes/p16_host_handoff.metal b/probes/p16_host_handoff.metal new file mode 100644 index 00000000..8bd4ebcd --- /dev/null +++ b/probes/p16_host_handoff.metal @@ -0,0 +1,14 @@ +#include +using namespace metal; + +// One thread advances a counter and logs a host-written word: log[v] = a[1] where v is the counter before the bump. +kernel void bump(device uint* a [[buffer(0)]], device uint* log [[buffer(1)]], uint i [[thread_position_in_grid]]) { + if (i == 0) { uint v = a[0]; log[v & 4095u] = a[1]; a[0] = v + 1u; } +} + +// A bounded ALU loop: keeps the GPU busy for a controllable time. +kernel void spin_work(device float* a [[buffer(0)]], constant uint& n [[buffer(1)]], uint i [[thread_position_in_grid]]) { + float x = a[i & 1023u]; + for (uint k = 0; k < n; k++) x = fma(x, 1.0000001f, 1e-7f); + a[i & 1023u] = x; +} diff --git a/probes/results/Apple-M3-Max_40c_macOS27.0.1_20261016-112112.txt b/probes/results/Apple-M3-Max_40c_macOS27.0.1_20261016-112112.txt new file mode 100644 index 00000000..58d684a9 --- /dev/null +++ b/probes/results/Apple-M3-Max_40c_macOS27.0.1_20261016-112112.txt @@ -0,0 +1,15 @@ +# chip: Apple M3 Max gpu-cores: 40 ram: 48 GB +# os: macOS 27.0.1 (26A434) date: 2026-10-16T16:21:12Z on-battery: 0 + +################ p16_host_handoff ################ +gpu cores: 40 +1. visibility over 1000 steps, 2 in flight: GPU->CPU misses 0, CPU->GPU misses 0, host timeouts 0 +2. round 1, plain pass boundary (fence only) : GPU gap end of pass A -> start of pass B: min 0.4 p10 0.4 median 0.5 p90 0.5 max 0.8 us +2. round 1, host round trip, spinning host : GPU gap end of pass A -> start of pass B: min 58.8 p10 72.9 median 83.2 p90 141.5 max 402.1 us +2. round 1, host round trip, waitUntilSignaledValue : GPU gap end of pass A -> start of pass B: min 63.6 p10 87.6 median 104.8 p90 140.1 max 713.1 us +2. round 2, plain pass boundary (fence only) : GPU gap end of pass A -> start of pass B: min 0.4 p10 0.4 median 0.5 p90 0.5 max 32.8 us +2. round 2, host round trip, spinning host : GPU gap end of pass A -> start of pass B: min 45.1 p10 63.2 median 81.4 p90 146.5 max 492.5 us +2. round 2, host round trip, waitUntilSignaledValue : GPU gap end of pass A -> start of pass B: min 82.7 p10 104.0 median 125.0 p90 233.7 max 5909.5 us +3. parked 2 s: publish seen yes; status while parked 2; finished 0.30 ms after the host signal; error: none; other queue: 38 command buffers completed (0 errors), worst latency 0.61 ms +3. parked 10 s: publish seen yes; status while parked 5; finished 0.01 ms after the host signal; error: Caused GPU Timeout Error (00000002:kIOGPUCommandBufferCallbackErrorTimeout); other queue: 187 command buffers completed (0 errors), worst latency 1.95 ms +3. parked 25 s: publish seen yes; status while parked 5; finished 0.01 ms after the host signal; error: Caused GPU Timeout Error (00000002:kIOGPUCommandBufferCallbackErrorTimeout); other queue: 459 command buffers completed (0 errors), worst latency 18.88 ms diff --git a/probes/results/Apple-M3-Max_40c_macOS27.0.1_20261016-112242.txt b/probes/results/Apple-M3-Max_40c_macOS27.0.1_20261016-112242.txt new file mode 100644 index 00000000..86756db7 --- /dev/null +++ b/probes/results/Apple-M3-Max_40c_macOS27.0.1_20261016-112242.txt @@ -0,0 +1,21 @@ +# chip: Apple M3 Max gpu-cores: 40 ram: 48 GB +# os: macOS 27.0.1 (26A434) date: 2026-10-16T16:22:42Z on-battery: 0 + +################ p16_host_handoff ################ +gpu cores: 40 +1. visibility over 1000 steps, 2 in flight: GPU->CPU misses 0, CPU->GPU misses 0, host timeouts 0 +2. round 1, plain pass boundary (fence only) : GPU gap end of pass A -> start of pass B: min 0.4 p10 0.4 median 0.5 p90 0.5 max 0.8 us +2. round 1, host round trip, spinning host : GPU gap end of pass A -> start of pass B: min 53.6 p10 64.2 median 81.2 p90 160.7 max 349.6 us +2. round 1, host round trip, waitUntilSignaledValue : GPU gap end of pass A -> start of pass B: min 68.8 p10 83.0 median 97.5 p90 159.4 max 1810.5 us +2. round 2, plain pass boundary (fence only) : GPU gap end of pass A -> start of pass B: min 0.4 p10 0.4 median 0.5 p90 0.5 max 0.8 us +2. round 2, host round trip, spinning host : GPU gap end of pass A -> start of pass B: min 54.0 p10 61.7 median 79.1 p90 126.1 max 360.9 us +2. round 2, host round trip, waitUntilSignaledValue : GPU gap end of pass A -> start of pass B: min 91.0 p10 111.3 median 146.0 p90 1498.3 max 14012.2 us +3. parked 2 s after a pass: publish seen yes; status while parked 2; finished 0.20 ms after the host signal; error: none; other queue: 38 command buffers completed (0 errors), worst latency 0.73 ms +3. parked 3 s after a pass: publish seen yes; status while parked 2; finished 0.23 ms after the host signal; error: none; other queue: 57 command buffers completed (0 errors), worst latency 1.10 ms +3. parked 4 s after a pass: publish seen yes; status while parked 2; finished 0.25 ms after the host signal; error: none; other queue: 75 command buffers completed (0 errors), worst latency 3.89 ms +3. parked 5 s after a pass: publish seen yes; status while parked 5; finished 0.01 ms after the host signal; error: Caused GPU Timeout Error (00000002:kIOGPUCommandBufferCallbackErrorTimeout); other queue: 93 command buffers completed (0 errors), worst latency 8.30 ms +3. parked 6 s after a pass: publish seen yes; status while parked 5; finished 0.01 ms after the host signal; error: Caused GPU Timeout Error (00000002:kIOGPUCommandBufferCallbackErrorTimeout); other queue: 112 command buffers completed (0 errors), worst latency 3.15 ms +3. parked 8 s after a pass: publish seen NO; status while parked 5; finished 0.01 ms after the host signal; error: Ignored (for causing prior/excessive GPU errors) (00000004:kIOGPUCommandBufferCallbackErrorSubmissionsIgnored); other queue: 148 command buffers completed (0 errors), worst latency 11.71 ms +3. parked 10 s after a pass: publish seen NO; status while parked 5; finished 0.01 ms after the host signal; error: Ignored (for causing prior/excessive GPU errors) (00000004:kIOGPUCommandBufferCallbackErrorSubmissionsIgnored); other queue: 184 command buffers completed (0 errors), worst latency 13.49 ms +4. parked 3 s at the start: publish seen yes; status while parked 5; finished 0.01 ms after the host signal; error: Ignored (for causing prior/excessive GPU errors) (00000004:kIOGPUCommandBufferCallbackErrorSubmissionsIgnored); other queue: 56 command buffers completed (0 errors), worst latency 3.30 ms +4. parked 10 s at the start: publish seen yes; status while parked 5; finished 0.01 ms after the host signal; error: Ignored (for causing prior/excessive GPU errors) (00000004:kIOGPUCommandBufferCallbackErrorSubmissionsIgnored); other queue: 186 command buffers completed (0 errors), worst latency 8.10 ms diff --git a/probes/results/Apple-M3-Max_40c_macOS27.0.1_20261016-112417.txt b/probes/results/Apple-M3-Max_40c_macOS27.0.1_20261016-112417.txt new file mode 100644 index 00000000..84d32c0f --- /dev/null +++ b/probes/results/Apple-M3-Max_40c_macOS27.0.1_20261016-112417.txt @@ -0,0 +1,19 @@ +# chip: Apple M3 Max gpu-cores: 40 ram: 48 GB +# os: macOS 27.0.1 (26A434) date: 2026-10-16T16:24:17Z on-battery: 0 + +################ p16_host_handoff ################ +gpu cores: 40 +1. visibility over 1000 steps, 2 in flight: GPU->CPU misses 0, CPU->GPU misses 0, host timeouts 0 +2. round 1, plain pass boundary (fence only) : GPU gap end of pass A -> start of pass B: min 0.4 p10 0.5 median 0.5 p90 0.6 max 1.1 us +2. round 1, host round trip, spinning host : GPU gap end of pass A -> start of pass B: min 57.1 p10 77.9 median 89.9 p90 201.0 max 537.8 us +2. round 1, host round trip, waitUntilSignaledValue : GPU gap end of pass A -> start of pass B: min 52.9 p10 87.3 median 125.5 p90 255.5 max 529.9 us +2. round 2, plain pass boundary (fence only) : GPU gap end of pass A -> start of pass B: min 0.3 p10 0.4 median 0.5 p90 0.5 max 0.7 us +2. round 2, host round trip, spinning host : GPU gap end of pass A -> start of pass B: min 79.5 p10 100.0 median 214.1 p90 561.6 max 1174.2 us +2. round 2, host round trip, waitUntilSignaledValue : GPU gap end of pass A -> start of pass B: min 129.9 p10 178.4 median 517.2 p90 1803.2 max 6024.5 us +3. parked 2.0 s after a pass: publish seen yes; status while parked 2; finished 1.82 ms after the host signal; error: none; GPU time 2009 ms; other queue: 36 command buffers completed (0 errors), worst latency 7.91 ms +3. parked 4.0 s after a pass: publish seen yes; status while parked 2; finished 0.28 ms after the host signal; error: none; GPU time 4021 ms; other queue: 74 command buffers completed (0 errors), worst latency 1.69 ms +3. parked 4.5 s after a pass: publish seen yes; status while parked 2; finished 0.97 ms after the host signal; error: none; GPU time 4510 ms; other queue: 83 command buffers completed (0 errors), worst latency 2.72 ms +3. parked 6.0 s after a pass: publish seen yes; status while parked 5; finished 0.01 ms after the host signal; error: Caused GPU Timeout Error (00000002:kIOGPUCommandBufferCallbackErrorTimeout); GPU time 0 ms; other queue: 110 command buffers completed (0 errors), worst latency 12.24 ms +4. parked 4.0 s at the start: publish seen yes; status while parked 2; finished 0.33 ms after the host signal; error: none; GPU time 0 ms; other queue: 74 command buffers completed (0 errors), worst latency 3.78 ms +4. parked 6.0 s at the start: publish seen yes; status while parked 5; finished 0.01 ms after the host signal; error: Caused GPU Timeout Error (00000002:kIOGPUCommandBufferCallbackErrorTimeout); GPU time 0 ms; other queue: 112 command buffers completed (0 errors), worst latency 2.18 ms +4. parked 10.0 s at the start: publish seen yes; status while parked 5; finished 0.01 ms after the host signal; error: Caused GPU Timeout Error (00000002:kIOGPUCommandBufferCallbackErrorTimeout); GPU time 0 ms; other queue: 184 command buffers completed (0 errors), worst latency 7.22 ms diff --git a/probes/results/Apple-M3-Max_40c_macOS27.0.1_20261016-112747.txt b/probes/results/Apple-M3-Max_40c_macOS27.0.1_20261016-112747.txt new file mode 100644 index 00000000..20944046 --- /dev/null +++ b/probes/results/Apple-M3-Max_40c_macOS27.0.1_20261016-112747.txt @@ -0,0 +1,21 @@ +# chip: Apple M3 Max gpu-cores: 40 ram: 48 GB +# os: macOS 27.0.1 (26A434) date: 2026-10-16T16:27:47Z on-battery: 0 + +################ p16_host_handoff ################ +gpu cores: 40 +1a. in-buffer wait, 1000 steps, 2 in flight: GPU->CPU misses 0, CPU->GPU misses 0, host timeouts 0 +1b. second command buffer, 1000 steps: GPU->CPU misses 0, CPU->GPU misses 0, host timeouts 0 +2. round 1, plain pass boundary (fence only) : GPU gap end of pass A -> start of pass B: min 0.4 p10 0.4 median 0.5 p90 0.5 max 0.7 us +2. round 1, in-buffer wait, spinning CPU : GPU gap end of pass A -> start of pass B: min 57.3 p10 69.2 median 79.8 p90 289.5 max 905.4 us +2. round 1, in-buffer wait, waitUntilSignaledValue : GPU gap end of pass A -> start of pass B: min 78.9 p10 87.2 median 127.8 p90 466.8 max 852.1 us +2. round 1, second buffer committed after the signal: GPU gap end of pass A -> start of pass B: min 66.4 p10 83.9 median 90.3 p90 479.2 max 1290.3 us +2. round 2, plain pass boundary (fence only) : GPU gap end of pass A -> start of pass B: min 0.3 p10 0.4 median 0.5 p90 0.5 max 1.5 us +2. round 2, in-buffer wait, spinning CPU : GPU gap end of pass A -> start of pass B: min 57.0 p10 71.6 median 79.5 p90 397.3 max 1006.3 us +2. round 2, in-buffer wait, waitUntilSignaledValue : GPU gap end of pass A -> start of pass B: min 87.2 p10 121.7 median 126.8 p90 371.5 max 1008.5 us +2. round 2, second buffer committed after the signal: GPU gap end of pass A -> start of pass B: min 61.4 p10 82.5 median 86.4 p90 347.3 max 930.4 us +3. parked 2.0 s after a pass: publish seen yes; status while parked 2; finished 0.25 ms after the host signal; error: none; GPU time 2001 ms; other queue: 37 command buffers completed (0 errors), worst latency 1.72 ms +3. parked 4.0 s after a pass: publish seen yes; status while parked 2; finished 0.64 ms after the host signal; error: none; GPU time 4009 ms; other queue: 74 command buffers completed (0 errors), worst latency 2.24 ms +3. parked 4.5 s after a pass: publish seen yes; status while parked 2; finished 0.65 ms after the host signal; error: none; GPU time 4532 ms; other queue: 84 command buffers completed (0 errors), worst latency 2.35 ms +3. parked 6.0 s after a pass: publish seen yes; status while parked 5; finished 0.01 ms after the host signal; error: Caused GPU Timeout Error (00000002:kIOGPUCommandBufferCallbackErrorTimeout); GPU time 0 ms; other queue: 111 command buffers completed (0 errors), worst latency 2.46 ms +4. parked 4.0 s at the start: publish seen yes; status while parked 2; finished 0.33 ms after the host signal; error: none; GPU time 0 ms; other queue: 75 command buffers completed (0 errors), worst latency 2.94 ms +4. parked 6.0 s at the start: publish seen yes; status while parked 5; finished 0.01 ms after the host signal; error: Caused GPU Timeout Error (00000002:kIOGPUCommandBufferCallbackErrorTimeout); GPU time 0 ms; other queue: 112 command buffers completed (0 errors), worst latency 2.35 ms diff --git a/probes/results/Apple-M3-Max_40c_macOS27.0.1_20261017-140635.txt b/probes/results/Apple-M3-Max_40c_macOS27.0.1_20261017-140635.txt new file mode 100644 index 00000000..2ce06e06 --- /dev/null +++ b/probes/results/Apple-M3-Max_40c_macOS27.0.1_20261017-140635.txt @@ -0,0 +1,26 @@ +# chip: Apple M3 Max gpu-cores: 40 ram: 48 GB +# os: macOS 27.0.1 (26A434) date: 2026-10-17T19:06:35Z on-battery: 0 + +################ p16_host_handoff ################ +gpu cores: 40 +1a. in-buffer wait, 1000 steps, 2 in flight: GPU->CPU misses 0, CPU->GPU misses 0, host timeouts 0 +1b. second command buffer, 1000 steps: GPU->CPU misses 0, CPU->GPU misses 0, host timeouts 0 +2. round 1, plain pass boundary (fence only) : GPU gap end of pass A -> start of pass B: min 0.3 p10 0.4 median 0.5 p90 0.5 max 0.8 us +2. round 1, in-buffer wait, spinning CPU : GPU gap end of pass A -> start of pass B: min 44.3 p10 75.8 median 80.0 p90 241.2 max 988.5 us +2. round 1, in-buffer wait, waitUntilSignaledValue : GPU gap end of pass A -> start of pass B: min 66.9 p10 88.5 median 127.5 p90 365.4 max 1069.3 us +2. round 1, second buffer encoded before the signal : GPU gap end of pass A -> start of pass B: min 70.9 p10 84.2 median 89.3 p90 424.6 max 1224.5 us +2. round 1, second buffer encoded after the signal : GPU gap end of pass A -> start of pass B: min 82.6 p10 87.0 median 147.4 p90 919.8 max 7069.1 us +2. round 2, plain pass boundary (fence only) : GPU gap end of pass A -> start of pass B: min 0.3 p10 0.4 median 0.5 p90 0.5 max 428.2 us +2. round 2, in-buffer wait, spinning CPU : GPU gap end of pass A -> start of pass B: min 60.5 p10 79.2 median 125.8 p90 630.3 max 3548.0 us +2. round 2, in-buffer wait, waitUntilSignaledValue : GPU gap end of pass A -> start of pass B: min 87.5 p10 122.4 median 139.0 p90 464.6 max 5152.5 us +2. round 2, second buffer encoded before the signal : GPU gap end of pass A -> start of pass B: min 59.1 p10 84.1 median 91.8 p90 435.4 max 1283.7 us +2. round 2, second buffer encoded after the signal : GPU gap end of pass A -> start of pass B: min 77.9 p10 85.8 median 93.9 p90 465.0 max 5624.9 us +5. 2000 command buffers ending in a signal: the signal visible after the status reads Completed: min 0.00 median 0.04 p99 0.37 max 2.42 us; not within 100 ms: 0 +3. parked 2.0 s after a pass: publish seen yes; status while parked 2; finished 0.29 ms after the host signal; error: none; GPU time 2008 ms; other queue: 37 command buffers completed (0 errors), worst latency 1.43 ms +3. parked 4.0 s after a pass: publish seen yes; status while parked 2; finished 0.57 ms after the host signal; error: none; GPU time 4032 ms; other queue: 73 command buffers completed (0 errors), worst latency 11.52 ms +3. parked 4.5 s after a pass: publish seen yes; status while parked 2; finished 0.72 ms after the host signal; error: none; GPU time 4514 ms; other queue: 84 command buffers completed (0 errors), worst latency 4.99 ms +3. parked 5.0 s after a pass: publish seen yes; status while parked 5; finished 0.01 ms after the host signal; error: Caused GPU Timeout Error (00000002:kIOGPUCommandBufferCallbackErrorTimeout); GPU time 0 ms; other queue: 93 command buffers completed (0 errors), worst latency 12.46 ms +3. parked 5.5 s after a pass: publish seen yes; status while parked 5; finished 0.01 ms after the host signal; error: Caused GPU Timeout Error (00000002:kIOGPUCommandBufferCallbackErrorTimeout); GPU time 0 ms; other queue: 101 command buffers completed (0 errors), worst latency 20.36 ms +3. parked 6.0 s after a pass: publish seen yes; status while parked 5; finished 0.01 ms after the host signal; error: Caused GPU Timeout Error (00000002:kIOGPUCommandBufferCallbackErrorTimeout); GPU time 0 ms; other queue: 111 command buffers completed (0 errors), worst latency 6.50 ms +4. parked 4.0 s at the start: publish seen yes; status while parked 2; finished 1.51 ms after the host signal; error: none; GPU time 0 ms; other queue: 74 command buffers completed (0 errors), worst latency 3.63 ms +4. parked 6.0 s at the start: publish seen yes; status while parked 5; finished 0.01 ms after the host signal; error: Caused GPU Timeout Error (00000002:kIOGPUCommandBufferCallbackErrorTimeout); GPU time 0 ms; other queue: 110 command buffers completed (0 errors), worst latency 5.09 ms diff --git a/probes/run_all.sh b/probes/run_all.sh index cf098899..8f8cb426 100755 --- a/probes/run_all.sh +++ b/probes/run_all.sh @@ -12,7 +12,7 @@ set -uo pipefail cd "$(dirname "$0")" command -v clang >/dev/null || { echo "clang not found - install the Xcode Command Line Tools (see header)"; exit 1; } mkdir -p build results -ALL="p1_limits p2_sync p3_residency p4_core_model p5_bandwidth p5b_access_pattern p6_preemption p6b_interleave p7_dispatch_overhead p8_threadgroup_mem p9_clock_warp p10_claim_protocol p11_interop_overlap p12_stream_geometry p13_decode_gemv p14_tensor_ops p15_frame_pacing" +ALL="p1_limits p2_sync p3_residency p4_core_model p5_bandwidth p5b_access_pattern p6_preemption p6b_interleave p7_dispatch_overhead p8_threadgroup_mem p9_clock_warp p10_claim_protocol p11_interop_overlap p12_stream_geometry p13_decode_gemv p14_tensor_ops p15_frame_pacing p16_host_handoff" chip=$(sysctl -n machdep.cpu.brand_string 2>/dev/null | tr ' ' '-') cores=${GPU_CORES:-$(ioreg -l 2>/dev/null | awk -F'= ' '/"gpu-core-count"/{print $2; exit}')} out="results/${chip:-unknown}_${cores:-NA}c_macOS$(sw_vers -productVersion)_$(date +%Y%m%d-%H%M%S).txt" diff --git a/runtime/src/metal_core.h b/runtime/src/metal_core.h index 42df0ed3..6d560cda 100644 --- a/runtime/src/metal_core.h +++ b/runtime/src/metal_core.h @@ -67,6 +67,7 @@ class Pipeline { struct BufferBinding { uint32_t index; const Buffer* buffer; uint64_t offset; }; struct BytesBinding { uint32_t index; std::vector bytes; }; +struct BufferUse { const Buffer* buffer; bool write; }; struct Dispatch { const Pipeline* pipeline = nullptr; @@ -76,8 +77,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) + std::vector uses; // buffers the kernel reaches only through GPU addresses: Queue.run and + // Queue.profile make them resident for its dispatch (useResource) }; // `error`: the command buffer's error (empty = clean). A Metal shader-validation report leaves the command buffer @@ -125,6 +126,33 @@ class Icb { std::shared_ptr impl; }; +// Host steps: a step pauses for CPU work between two of its GPU passes. A running dispatch has no documented view of +// CPU writes, and the GPU watchdog kills a command buffer parked at an event wait for 5 s (probes/p16_host_handoff: +// 4.5 s survives), so the GPU never waits for the host: the pass that ends at a point's publish boundary signals an +// MTLSharedEvent, the host waits for the signal and runs the point's task, and only then commits the command buffer +// that starts at the point's wait boundary. A slow task idles the GPU; it cannot trip the watchdog. +struct HostCall { + uint64_t step; // the runner's absolute step index (it counts every step the runner has begun) + uint32_t point; // the host point's index in the program + void* step_state; // StepState. A task that reads it declares reads=["step_state"] on its point, so that no op + // running beside the task writes it (Program.check_host_points) +}; + +class HostTask { + public: + virtual ~HostTask() = default; + // Runs on the pump thread once the GPU completed the ops before the point's publish boundary; the ops from its wait + // boundary on are committed after it returns. Returns false with `error` set to stop the run. A task bounds its own + // duration (its I/O carries timeouts): the runner cannot interrupt it. + virtual bool run(const HostCall& call, std::string& error) = 0; +}; + +struct HostPoint { + uint32_t publish = 0; // boundary 0..n: the task starts once ops [0, publish) of the step completed (0: the previous step) + uint32_t wait = 0; // boundary publish..n: ops [wait, n) of the step need the task (n: the next step needs it) + std::shared_ptr task; +}; + struct RunnerStats { uint64_t steps_submitted = 0; uint64_t command_buffers = 0; @@ -136,6 +164,9 @@ struct RunnerStats { double wait_ms = 0; // host wall time waiting for completion (overlaps GPU time) bool done = false; // StepState.done was observed std::string error; // the first failed command buffer's error and validation reports; stops the pump (Engine.run raises it) + int32_t failed_task = -1; // the host point whose task failed the run (-1: none did) + std::vector handoff_gaps_ms; // per command buffer committed once a host point's task returned: its GPU start + // minus the GPU end of the one before it, the GPU's idle time at that handoff }; class Runner { @@ -154,7 +185,20 @@ class Runner { // same ops) instead of ICB replay. Blocks until done / max_steps; tokens are collected as buffers complete. // `max_tokens` > 0 stops submitting once that many tokens have been drained during this call (a speculative // program commits several tokens per step, so a step count over-runs); the buffers already queued still complete. + // With host points the command buffers are cut at the steps' boundaries and at the points' wait boundaries instead, + // so steps_per_cb and in_flight do not apply; a run always submits whole steps. A run drops the tokens an earlier run + // left undrained. One run() or set_host_points() at a time: a call while another runs, on another thread or from + // one of the runner's own host tasks, throws. RunnerStats run(uint32_t max_steps, uint32_t steps_per_cb, uint32_t in_flight, bool reencode, uint64_t max_tokens = 0); + // Switches run() to host steps. Points are in program order: 0 <= publish <= wait <= op count, publish boundaries + // never decrease. `error_offset`: StepState.error, set to 4 when a host step fails. `timeout_ms`: the longest run() + // waits for the GPU to reach a publish boundary or finish a command buffer; `spin_us`: how long such a wait spins + // before it blocks. + void set_host_points(std::vector points, uint32_t error_offset, uint32_t timeout_ms, uint32_t spin_us = 20000); + // The installed tasks, and their release: the bindings' garbage-collector support (a Python task's callable usually + // reaches the object that owns this runner). + std::vector> host_tasks() const; + void release_host_tasks(); // Tokens drained so far (in ring order); cleared by the call. std::vector drain(); std::shared_ptr impl; diff --git a/runtime/src/metal_core.mm b/runtime/src/metal_core.mm index bb2f97b1..724d94e6 100644 --- a/runtime/src/metal_core.mm +++ b/runtime/src/metal_core.mm @@ -6,7 +6,9 @@ #include #include #include +#include #include +#include #include "metal_core.h" namespace monolith { @@ -148,6 +150,8 @@ static int ioreg_gpu_cores() { return e; } +static MTLResourceUsage use_usage(const BufferUse& u) { return u.write ? (MTLResourceUsageRead | MTLResourceUsageWrite) : MTLResourceUsageRead; } + RunResult Queue::run(const std::vector& dispatches, bool concurrent) { RunResult r; bool reported = false; @@ -160,7 +164,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]; + for (auto& u : d.uses) [en useResource:u.buffer->impl->buf usage:use_usage(u)]; 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])]; } @@ -212,7 +216,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]; + for (auto& u : d.uses) [en useResource:u.buffer->impl->buf usage:use_usage(u)]; [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]; } @@ -280,6 +284,8 @@ static void encode_icb_command(id c, const Dispatch& Icb::~Icb() = default; size_t Icb::count() const { return impl->count; } +static constexpr uint32_t kDoneLog = 64; // steps of done snapshots kept; the GPU runs at most two steps ahead of the host + struct RunnerImpl { id dev; id q; std::shared_ptr icb; std::vector ops; @@ -289,10 +295,40 @@ static void encode_icb_command(id c, const Dispatch& id ring; uint32_t cap; uint32_t tail = 0; // next ring slot the host reads std::vector tokens; std::mutex mu; + std::atomic owner{}; // the thread inside run() or set_host_points(): one pump per runner bool resident = false; // the queue carries residency_set (replaces useResource) + // host steps (set_host_points) + std::vector points; + uint32_t error_off = 0, timeout_ms = 20000, spin_us = 20000; + std::vector pass_cuts; // boundaries that end a pass: 0, n and every interior publish or wait + std::vector cb_cuts; // boundaries that end a command buffer: 0, n and every interior wait + std::vector> pub_at, wait_at; // per boundary 0..n: the points that publish / wait there + std::vector pub_seg; // per boundary 1..n: the command buffer (index into cb_cuts) whose passes end there + id gpu_ev = nil; // the GPU signals V(step, point) after the pass ending at the publish boundary + id fence = nil; // orders every pass behind the one before it, across command buffers + bool fence_live = false; // a pass has updated the fence + id done_log = nil; // StepState.done copied at the end of each step, indexed by step % kDoneLog + uint64_t step_base = 0; // absolute index of the next step the runner begins + uint64_t event_base = 0; // step index at which gpu_ev was created (its values count from there) + bool drop = false; // test support: commit_segment leaves out the signal of (drop_step, drop_point) + uint64_t drop_step = 0; + uint32_t drop_point = 0; ~RunnerImpl() { if (resident) [q removeResidencySet:residency_set]; } }; +// Holds the runner for one call of run() or set_host_points(). A second call fails at once instead of waiting: run() +// releases the GIL, and a host task runs on the thread that holds the runner. +struct Hold { + std::atomic& owner; + Hold(std::atomic& o, const char* what) : owner(o) { + std::thread::id held{}; + if (!owner.compare_exchange_strong(held, std::this_thread::get_id())) + throw std::runtime_error(std::string(what) + (held == std::this_thread::get_id() ? ": called from one of the runner's own host tasks" + : ": already running on another thread")); + } + ~Hold() { owner.store(std::thread::id{}); } +}; + Runner::Runner(const Device& d, const Icb& icb, const std::vector& ops, std::vector resources, const Buffer& step_state, uint32_t done_offset, uint32_t ring_head_offset, uint32_t ring_tail_offset, const Buffer& ring, uint32_t ring_capacity, std::vector read_only_resources) @@ -351,9 +387,333 @@ static void drain_ring(RunnerImpl& r) { *(volatile uint32_t*)((char*)r.state.contents + r.tail_off) = r.tail; } +// --------------------------------------------------------------------------------------------------------------- +// Host steps. Op i of step s; boundary b of step s sits before op b, and boundary n of step s is boundary 0 of step +// s + 1. A command buffer covers the ops of one step between two consecutive cb_cuts; its passes end at pass_cuts, and +// the pass that ends at a publish boundary is followed by the signal of every point publishing there. Command buffers +// are committed in order, the one starting at boundary b only after every point waiting at b has been served, so a +// committed command buffer never waits on the host and every point's signal is committed before its turn to be served. + +void Runner::set_host_points(std::vector points, uint32_t error_offset, uint32_t timeout_ms, uint32_t spin_us) { + RunnerImpl& r = *impl; + std::vector old; // the replaced points die last, after the hold: a task's last reference may run Python, + // which may walk this runner's points (the collector) or call it + Hold hold(r.owner, "set_host_points"); + const uint32_t n = (uint32_t)r.ops.size(); + uint32_t prev = 0; + for (auto& p : points) { + if (!p.task) throw std::runtime_error("host point without a task"); + if (p.publish > p.wait || p.wait > n) throw std::runtime_error("host point: need 0 <= publish <= wait <= the op count"); + if (p.publish < prev) throw std::runtime_error("host points: publish boundaries must not decrease in program order"); + prev = p.publish; + } + if ((size_t)error_offset + 4 > r.state.length) throw std::runtime_error("host points: the error offset lies outside StepState"); + if (timeout_ms == 0) throw std::runtime_error("host points: timeout_ms must be at least 1"); + // Test support: LITHOS_HOST_STEPS_DROP_SIGNAL=:, two decimal numbers, leaves out that one signal (the + // step counts every step the runner begins), so a command buffer finishes without it. An empty value is unset. + bool drop = false; uint64_t drop_step = 0; uint32_t drop_point = 0; + if (const char* v = getenv("LITHOS_HOST_STEPS_DROP_SIGNAL"); v && *v) { + const std::string s(v); + const size_t colon = s.find(':'); + auto digits = [](const std::string& t) { // at most 19 digits: std::stoull cannot overflow + return !t.empty() && t.size() <= 19 && t.find_first_not_of("0123456789") == std::string::npos; + }; + if (colon == std::string::npos || !digits(s.substr(0, colon)) || !digits(s.substr(colon + 1))) + throw std::runtime_error("LITHOS_HOST_STEPS_DROP_SIGNAL: expected : in decimal digits, got '" + s + "'"); + const uint64_t k = std::stoull(s.substr(colon + 1)); + if (!points.empty() && k >= points.size()) + throw std::runtime_error("LITHOS_HOST_STEPS_DROP_SIGNAL: point " + std::to_string(k) + ", but the program has " + + std::to_string(points.size()) + " host points"); + drop = true; drop_step = std::stoull(s.substr(0, colon)); drop_point = (uint32_t)k; + } + old.swap(r.points); + r.points = std::move(points); + r.error_off = error_offset; r.timeout_ms = timeout_ms; r.spin_us = spin_us; + r.drop = drop; r.drop_step = drop_step; r.drop_point = drop_point; + r.pub_at.assign(n + 1, {}); r.wait_at.assign(n + 1, {}); + std::vector pass_cut(n + 1, false), cb_cut(n + 1, false); + pass_cut[0] = pass_cut[n] = cb_cut[0] = cb_cut[n] = true; + for (uint32_t k = 0; k < r.points.size(); k++) { + const HostPoint& p = r.points[k]; + r.pub_at[p.publish].push_back(k); + r.wait_at[p.wait].push_back(k); + pass_cut[p.publish] = pass_cut[p.wait] = cb_cut[p.wait] = true; + } + r.pass_cuts.clear(); r.cb_cuts.clear(); + for (uint32_t b = 0; b <= n; b++) { + if (pass_cut[b]) r.pass_cuts.push_back(b); + if (cb_cut[b]) r.cb_cuts.push_back(b); + } + r.pub_seg.assign(n + 1, 0); + for (uint32_t j = 0, b = 1; b <= n; b++) { + while (r.cb_cuts[j + 1] < b) j++; + r.pub_seg[b] = j; + } + r.gpu_ev = [r.dev newSharedEvent]; // a fresh event: its values count from the current step + r.event_base = r.step_base; + if (!r.fence) r.fence = [r.dev newFence]; + if (!r.done_log) r.done_log = [r.dev newBufferWithLength:kDoneLog * 4 options:MTLResourceStorageModeShared]; + if (!r.gpu_ev || !r.fence || !r.done_log) throw std::runtime_error("host points: newSharedEvent, newFence or newBuffer failed"); +} + +std::vector> Runner::host_tasks() const { + std::vector> out; + for (auto& p : impl->points) if (p.task) out.push_back(p.task); + return out; +} + +void Runner::release_host_tasks() { + std::vector> dying; // the points hold null tasks before any task's destructor runs Python + for (auto& p : impl->points) dying.push_back(std::move(p.task)); +} + +static uint64_t event_value(const RunnerImpl& r, uint64_t step, uint32_t point) { + return (step - r.event_base) * r.points.size() + point + 1; +} + +// One pass: ops [a, b) of a step, behind the fence of the pass before it (on any earlier command buffer). +static void encode_pass(RunnerImpl& r, id cb, uint32_t a, uint32_t b, bool reencode) { + id en = [cb computeCommandEncoder]; + if (r.fence_live) [en waitForFence:r.fence]; + if (!r.resident) // buffers a kernel reaches only through a GPU address are declared here too + for (size_t i = 0; i < r.resources.size(); i++) [en useResource:r.resources[i] usage:r.resource_usage[i]]; + if (reencode) { + for (uint32_t i = a; i < b; i++) { + const Dispatch& d = r.ops[i]; + [en setComputePipelineState:d.pipeline->impl->pso]; + for (auto& bb : d.buffers) [en setBuffer:bb.buffer->impl->buf offset:bb.offset atIndex:bb.index]; + for (auto& t : d.threadgroup_memory) [en setThreadgroupMemoryLength:t.second atIndex:t.first]; + [en dispatchThreadgroups:MTLSizeMake(d.grid[0], d.grid[1], d.grid[2]) threadsPerThreadgroup:MTLSizeMake(d.threadgroup[0], d.threadgroup[1], d.threadgroup[2])]; + } + } else { + [en executeCommandsInBuffer:r.icb->icb withRange:NSMakeRange(a, b - a)]; + } + [en updateFence:r.fence]; + [en endEncoding]; + r.fence_live = true; +} + +// Commits command buffer `seg` of `step`: its passes, each followed by the signals of the points publishing at its end. +// After the step's last pass, StepState.done is copied into done_log (whether the next step begins live), and the +// next step's points that publish at boundary 0 are signalled. +static id commit_segment(RunnerImpl& r, uint64_t step, uint32_t seg, bool reencode) { + const uint32_t n = (uint32_t)r.ops.size(), a = r.cb_cuts[seg], b = r.cb_cuts[seg + 1]; + id cb = [r.q commandBuffer]; + auto signal = [&](uint64_t s, uint32_t k) { + if (!r.drop || s != r.drop_step || k != r.drop_point) [cb encodeSignalEvent:r.gpu_ev value:event_value(r, s, k)]; + }; + uint32_t start = a; + for (uint32_t c : r.pass_cuts) { + if (c <= a) continue; + if (c > b) break; + encode_pass(r, cb, start, c, reencode); + if (c == n) { + id bl = [cb blitCommandEncoder]; + [bl waitForFence:r.fence]; + [bl copyFromBuffer:r.state sourceOffset:r.done_off toBuffer:r.done_log destinationOffset:(step % kDoneLog) * 4 size:4]; + [bl updateFence:r.fence]; + [bl endEncoding]; + } + for (uint32_t k : r.pub_at[c]) signal(step, k); + if (c == n) for (uint32_t k : r.pub_at[0]) signal(step + 1, k); + start = c; + } + [cb commit]; + return cb; +} + +static std::string cb_error(id cb) { + return std::string("command buffer failed: ") + (cb.error ? [cb.error.localizedDescription UTF8String] : "unknown error"); +} + +// Waits until the GPU signals `v`: the passes before the point's publish boundary completed and their writes are +// visible. `carrier` is the command buffer holding the signal (nil once it has been retired): if it finishes without +// the signal, the wait fails at once. Spins for spin_us, then blocks in 1 ms slices; fails after timeout_ms. +static bool wait_publish(const RunnerImpl& r, uint64_t v, id carrier, std::string& err) { + const double t0 = now_ms(); + for (uint32_t spins = 0; r.gpu_ev.signaledValue < v; spins++) { + if ((spins & 63) != 63) continue; + const bool finished = carrier == nil || carrier.status >= MTLCommandBufferStatusCompleted; + if (finished && ![r.gpu_ev waitUntilSignaledValue:v timeoutMS:10]) { // a finished buffer's signal lands at once + err = carrier != nil && carrier.status == MTLCommandBufferStatusError ? cb_error(carrier) + : "its command buffer finished without the signal"; + return false; + } + const double elapsed = now_ms() - t0; + if (elapsed > r.timeout_ms) { err = "the GPU did not reach the point within " + std::to_string(r.timeout_ms) + " ms"; return false; } + if (elapsed * 1e3 > r.spin_us) [r.gpu_ev waitUntilSignaledValue:v timeoutMS:1]; + } + // The event's value is read with a plain load: the host's later loads of what the GPU wrote must not run before it + std::atomic_thread_fence(std::memory_order_acquire); + return true; +} + +// Waits for a committed command buffer; it never waits on the host, so only its GPU work decides how long. +static bool wait_cb(const RunnerImpl& r, id cb, std::string& err) { + const double t0 = now_ms(); + while (cb.status < MTLCommandBufferStatusCompleted) { + const double elapsed = now_ms() - t0; + if (elapsed > r.timeout_ms) { err = "a command buffer did not complete within " + std::to_string(r.timeout_ms) + " ms"; return false; } + if (elapsed * 1e3 > r.spin_us) usleep(100); + } + std::atomic_thread_fence(std::memory_order_acquire); // as in wait_publish: the status is read with a plain load + return true; +} + +struct HostCb { id cb; uint64_t step; uint32_t seg; bool after_point; }; // after_point: committed once + // a host point's task returned + +static RunnerStats run_host_steps(RunnerImpl& r, uint32_t max_steps, bool reencode, uint64_t max_tokens) { + RunnerStats st; + std::string& err = st.error; + for (auto& p : r.points) + if (!p.task) { err = "host steps: a task has been released"; return st; } + const uint32_t n = (uint32_t)r.ops.size(), nseg = (uint32_t)r.cb_cuts.size() - 1, K = (uint32_t)r.points.size(); + const uint64_t S0 = r.step_base; + uint64_t S1 = S0 + max_steps; // steps [S0, S1) may begin; a stop lowers S1 to the steps begun + uint64_t begun = S0; // steps [S0, begun) have begun, and each runs to its end + uint64_t enc_step = S0; uint32_t enc_seg = 0; // the next command buffer to commit + uint64_t srv_step = S0; uint32_t srv_k = 0; // the next point to serve + bool stop = false; + std::deque pending; + const double t0 = now_ms(), c0 = cpu_ms_now(); + const bool done_at_start = *(volatile uint32_t*)((char*)r.state.contents + r.done_off) != 0; // nothing is in flight + // A step's tasks run when the program was live as the step began: done at the end of the previous step, from + // done_log. Reading StepState at the point itself would race an op that runs beside the task and sets done. + auto live = [&](uint64_t s) { + return s == S0 ? !done_at_start : ((volatile uint32_t*)r.done_log.contents)[(s - 1) % kDoneLog] == 0; + }; + auto served = [&](uint64_t s, uint32_t k) { return s < srv_step || (s == srv_step && k < srv_k); }; + auto may_begin = [&](uint64_t s) { // a step begins unless a stop came first + if (s < begun) return true; + if (stop || s >= S1) { S1 = begun; return false; } + begun = s + 1; + return true; + }; + auto observe_state = [&]() { // the GPU's writes so far are visible: drain, check the stops + drain_ring(r); + st.done = *(volatile uint32_t*)((char*)r.state.contents + r.done_off) != 0; + size_t seen; { std::lock_guard lk(r.mu); seen = r.tokens.size(); } + if (st.done || (max_tokens && seen >= max_tokens)) stop = true; + }; + double prev_end = 0; // GPU end of the command buffer retired last (0: none in this run) + auto retire = [&](bool block) { // retires completed command buffers, waiting for one if `block` + while (!pending.empty() && err.empty()) { + id cb = pending.front().cb; + if (cb.status < MTLCommandBufferStatusCompleted) { + if (!block) return; + const double w0 = now_ms(); + const bool ok = wait_cb(r, cb, err); + st.wait_ms += now_ms() - w0; + if (!ok) return; + } + [cb waitUntilCompleted]; // returns at once; the validation logs are complete only after it + st.gpu_ms += (cb.GPUEndTime - cb.GPUStartTime) * 1e3; + st.command_buffers++; + if (pending.front().after_point && prev_end > 0) st.handoff_gaps_ms.push_back((cb.GPUStartTime - prev_end) * 1e3); + prev_end = cb.GPUEndTime; + pending.pop_front(); + if (std::string e = failure(cb); !e.empty()) { err = e; return; } // its error or validation reports stop the run + block = false; + observe_state(); + } + }; + // Whatever stops the loop, a failed task, a timeout or an exception the pump itself meets, reaches the cleanup below + try { + for (;;) { + // commit every command buffer whose waits have all been served + while (err.empty() && enc_step < S1) { + const uint32_t a = r.cb_cuts[enc_seg]; + bool ready = true; + for (uint32_t k : r.wait_at[a]) ready = ready && served(enc_step, k); + if (a == 0 && enc_step > S0) for (uint32_t k : r.wait_at[n]) ready = ready && served(enc_step - 1, k); + if (!ready || (enc_seg == 0 && !may_begin(enc_step))) break; + const double e0 = now_ms(); + const bool after_point = !r.wait_at[a].empty() || (a == 0 && enc_step > S0 && !r.wait_at[n].empty()); + @autoreleasepool { pending.push_back({commit_segment(r, enc_step, enc_seg, reencode), enc_step, enc_seg, after_point}); } + st.encode_ms += now_ms() - e0; + if (++enc_seg == nseg) { enc_seg = 0; enc_step++; } + } + if (!err.empty()) break; + // serve the next point once its signal is committed; a point publishing at the run's first boundary needs none + if (srv_step < S1) { + const HostPoint& p = r.points[srv_k]; + const bool first = p.publish == 0 && srv_step == S0; + const bool committed = first || (p.publish == 0 ? enc_step >= srv_step + : srv_step < enc_step || (srv_step == enc_step && r.pub_seg[p.publish] < enc_seg)); + if (committed && may_begin(srv_step)) { + if (!first) { + const uint64_t cs = p.publish == 0 ? srv_step - 1 : srv_step; + const uint32_t cg = p.publish == 0 ? nseg - 1 : r.pub_seg[p.publish]; + id carrier = nil; + for (auto& h : pending) if (h.step == cs && h.seg == cg) carrier = h.cb; + const double w0 = now_ms(); + std::string werr; + const bool ok = wait_publish(r, event_value(r, srv_step, srv_k), carrier, werr); + st.wait_ms += now_ms() - w0; + if (!ok) { err = "host step " + std::to_string(srv_step) + ", point " + std::to_string(srv_k) + ": " + werr; break; } + } + observe_state(); + if (live(srv_step)) { // a step that began after the program finished does no host work + const HostCall call{srv_step, srv_k, r.state.contents}; + std::string terr; + bool ok = false; + try { ok = p.task->run(call, terr); } + catch (const std::exception& e) { terr = e.what(); } + catch (...) { terr = "the task threw an exception that is not a std::exception"; } // an int, an NSException + if (!ok) { + err = "host step " + std::to_string(srv_step) + ", point " + std::to_string(srv_k) + ": " + (terr.empty() ? "the task failed" : terr); + st.failed_task = (int32_t)srv_k; + break; + } + observe_state(); // a task may set done itself: then no later step begins + } + if (++srv_k == K) { srv_k = 0; srv_step++; } + retire(false); + continue; + } + } + if (pending.empty()) { // nothing committed is outstanding and nothing more can start + if (enc_step < S1 || srv_step < S1) err = "host steps: no command buffer in flight and no point to serve"; + break; + } + retire(true); + if (!err.empty()) break; + } + } catch (const std::exception& e) { + if (err.empty()) err = std::string("host steps: ") + e.what(); + } catch (...) { + if (err.empty()) err = "host steps: an exception that is not a std::exception"; + } + if (!err.empty()) { + // Committed command buffers never wait on the host and every kernel loop is bounded; the GPU watchdog ends a hung + // one. They finish before StepState is touched, so the failure leaves no GPU work behind. + for (auto& h : pending) { + [h.cb waitUntilCompleted]; + st.gpu_ms += (h.cb.GPUEndTime - h.cb.GPUStartTime) * 1e3; + st.command_buffers++; + failure(h.cb); // counts its validation reports; the run's error is the first failure's + } + pending.clear(); + volatile uint32_t* state = (volatile uint32_t*)r.state.contents; + state[r.done_off / 4] = 1; + if (state[r.error_off / 4] == 0) state[r.error_off / 4] = 4; + } + r.step_base = begun; + drain_ring(r); + st.done = *(volatile uint32_t*)((char*)r.state.contents + r.done_off) != 0; + st.steps_submitted = begun - S0; + st.wall_ms = now_ms() - t0; + st.host_busy_ms = cpu_ms_now() - c0; + return st; +} + RunnerStats Runner::run(uint32_t max_steps, uint32_t steps_per_cb, uint32_t in_flight, bool reencode, uint64_t max_tokens) { - impl->tail = *(volatile uint32_t*)((char*)impl->state.contents + impl->tail_off); // the ring tail lives in StepState: resume (or restart after a reset) from it RunnerImpl& r = *impl; + Hold hold(r.owner, "Runner.run"); + { std::lock_guard lk(r.mu); r.tokens.clear(); } // an earlier run's undrained tokens are not this run's + r.tail = *(volatile uint32_t*)((char*)r.state.contents + r.tail_off); // the ring tail lives in StepState: resume (or restart after a reset) from it + if (!r.points.empty()) return run_host_steps(r, max_steps, reencode, max_tokens); RunnerStats st; if (steps_per_cb == 0 || in_flight == 0) throw std::runtime_error("steps_per_cb and in_flight must be >= 1"); double t0 = now_ms(), c0 = cpu_ms_now(); @@ -377,6 +737,8 @@ static void drain_ring(RunnerImpl& r) { uint32_t n = std::min(steps_per_cb, max_steps - st.steps_submitted); id cb = [r.q commandBuffer]; id en = [cb computeCommandEncoder]; // serial: step s+1 starts after step s + if (!r.resident) // buffers a kernel reaches only through a GPU address are declared here too + for (size_t i = 0; i < r.resources.size(); i++) [en useResource:r.resources[i] usage:r.resource_usage[i]]; if (reencode) { for (uint32_t s = 0; s < n; s++) for (auto& d : r.ops) { @@ -386,8 +748,6 @@ static void drain_ring(RunnerImpl& r) { [en dispatchThreadgroups:MTLSizeMake(d.grid[0], d.grid[1], d.grid[2]) threadsPerThreadgroup:MTLSizeMake(d.threadgroup[0], d.threadgroup[1], d.threadgroup[2])]; } } else { - if (!r.resident) - for (size_t i = 0; i < r.resources.size(); i++) [en useResource:r.resources[i] usage:r.resource_usage[i]]; for (uint32_t s = 0; s < n; s++) [en executeCommandsInBuffer:r.icb->icb withRange:NSMakeRange(0, r.icb->count)]; } [en endEncoding]; @@ -401,6 +761,7 @@ static void drain_ring(RunnerImpl& r) { while (pending.size() >= in_flight) { observe(pending.front()); pending.pop_front(); } } while (!pending.empty()) { observe(pending.front()); pending.pop_front(); } + r.step_base += st.steps_submitted; // HostCall.step counts the steps of either pump st.wall_ms = now_ms() - t0; st.host_busy_ms = cpu_ms_now() - c0; return st; diff --git a/runtime/src/native.mm b/runtime/src/native.mm index ce0c14ae..28d36262 100644 --- a/runtime/src/native.mm +++ b/runtime/src/native.mm @@ -2,14 +2,94 @@ #include #include #include +#include #include +#include #include +#import +#include #include +#include +#include #include "metal_core.h" namespace nb = nanobind; using namespace monolith; +// A host task written in Python: fn(step, point). run() is called with the GIL released, so the call takes it; an +// exception fails the run with its message and stays on the task (take_exception) for the caller to raise. +struct CallableTask : HostTask { + nb::callable fn; + nb::object exception; + explicit CallableTask(nb::callable f) : fn(std::move(f)) {} + bool run(const HostCall& call, std::string& error) override { + nb::gil_scoped_acquire gil; + if (!fn.is_valid()) { error = "the task's callable has been released"; return false; } + try { + fn(call.step, call.point); + return true; + } catch (nb::python_error& e) { + error = e.what(); + exception = nb::borrow(e.value()); + return false; + } + } +}; + +// Test support: a C++ task that throws, at `step`, what a C++ task may throw besides a std::exception: an int, or an +// NSException (`objc`). +struct ThrowingTask : HostTask { + uint64_t step; + bool objc; + ThrowingTask(uint64_t s, bool o) : step(s), objc(o) {} + bool run(const HostCall& call, std::string&) override { + if (call.step == step) { + if (objc) [NSException raise:NSGenericException format:@"thrown at step %llu", (unsigned long long)step]; + throw 42; + } + return true; + } +}; + +// Garbage-collector support. A task's callable usually reaches the Engine that owns the Runner holding the task, a cycle +// through C++ references the collector cannot see unless these types report and break them. +static int callable_task_traverse(PyObject* self, visitproc visit, void* arg) { + Py_VISIT(Py_TYPE(self)); + if (!nb::inst_ready(self)) return 0; + CallableTask* task = nb::inst_ptr(self); + Py_VISIT(task->fn.ptr()); + Py_VISIT(task->exception.ptr()); // its traceback's frames usually reach the Engine too + return 0; +} +static int callable_task_clear(PyObject* self) { + if (!nb::inst_ready(self)) return 0; + CallableTask* task = nb::inst_ptr(self); + nb::callable fn = std::move(task->fn); // the task holds neither before they die + nb::object exception = std::move(task->exception); + return 0; +} +static int runner_traverse(PyObject* self, visitproc visit, void* arg) { + Py_VISIT(Py_TYPE(self)); + if (!nb::inst_ready(self)) return 0; + // A task handed in from Python is a shared_ptr whose deleter holds one reference to the Python object, per control + // block; a task made in C++ holds none. Visit exactly those references, without making a wrapper. + std::vector blocks; + for (auto& task : nb::inst_ptr(self)->host_tasks()) { + auto* owner = std::get_deleter(task); + if (!owner || std::find(blocks.begin(), blocks.end(), owner) != blocks.end()) continue; + blocks.push_back(owner); + Py_VISIT(owner->o); + } + return 0; +} +static int runner_clear(PyObject* self) { + if (!nb::inst_ready(self)) return 0; + nb::inst_ptr(self)->release_host_tasks(); + return 0; +} +static PyType_Slot callable_task_slots[] = {{Py_tp_traverse, (void*)callable_task_traverse}, {Py_tp_clear, (void*)callable_task_clear}, {0, nullptr}}; +static PyType_Slot runner_slots[] = {{Py_tp_traverse, (void*)runner_traverse}, {Py_tp_clear, (void*)runner_clear}, {0, nullptr}}; + NB_MODULE(_native, m) { m.doc() = "Metal runtime core (v0): device, buffers, runtime-compiled libraries, pipelines, timed dispatches"; @@ -62,8 +142,8 @@ .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("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>()); + .def("use", [](Dispatch& d, const Buffer& b, bool write) -> Dispatch& { d.uses.push_back({&b, write}); return d; }, + nb::arg("buffer"), nb::arg("write") = false, 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); @@ -78,13 +158,24 @@ .def(nb::init&>(), nb::arg("device"), nb::arg("ops"), nb::keep_alive<1, 3>()) .def_prop_ro("count", &Icb::count); + nb::class_(m, "HostTask"); // implemented in C++ (later tiers) or by CallableTask + nb::class_(m, "CallableTask", nb::type_slots(callable_task_slots)) + .def(nb::init(), nb::arg("fn")) + .def("take_exception", [](CallableTask& t) -> nb::object { + nb::object e = std::move(t.exception); + if (!e.is_valid()) return nb::none(); + return e; }, + "the exception the task's last failing call raised (None if none); the task no longer holds it"); + nb::class_(m, "_ThrowingTask").def(nb::init(), nb::arg("step"), nb::arg("objc") = false); + nb::class_(m, "RunnerStats") .def_ro("steps_submitted", &RunnerStats::steps_submitted).def_ro("command_buffers", &RunnerStats::command_buffers) .def_ro("gpu_ms", &RunnerStats::gpu_ms).def_ro("wall_ms", &RunnerStats::wall_ms).def_ro("host_busy_ms", &RunnerStats::host_busy_ms) .def_ro("encode_ms", &RunnerStats::encode_ms).def_ro("commit_ms", &RunnerStats::commit_ms).def_ro("wait_ms", &RunnerStats::wait_ms) - .def_ro("done", &RunnerStats::done).def_ro("error", &RunnerStats::error); + .def_ro("done", &RunnerStats::done).def_ro("error", &RunnerStats::error) + .def_ro("failed_task", &RunnerStats::failed_task).def_ro("handoff_gaps_ms", &RunnerStats::handoff_gaps_ms); - nb::class_(m, "Runner") + nb::class_(m, "Runner", nb::type_slots(runner_slots)) .def("__init__", [](Runner* self, const Device& d, const Icb& icb, const std::vector& ops, std::vector resources, const Buffer& state, uint32_t done_offset, uint32_t ring_head_offset, uint32_t ring_tail_offset, const Buffer& ring, uint32_t ring_capacity, std::vector read_only_resources) { @@ -95,5 +186,12 @@ nb::keep_alive<1, 3>(), nb::keep_alive<1, 4>(), nb::keep_alive<1, 5>(), nb::keep_alive<1, 6>(), nb::keep_alive<1, 10>()) .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("set_host_points", [](Runner& r, const std::vector>>& points, + uint32_t error_offset, uint32_t timeout_ms, uint32_t spin_us) { + std::vector pts; + for (auto& [publish, wait, task] : points) pts.push_back({publish, wait, task}); + r.set_host_points(std::move(pts), error_offset, timeout_ms, spin_us); }, + nb::arg("points"), nb::arg("error_offset"), nb::arg("timeout_ms") = 20000, nb::arg("spin_us") = 20000) + .def("host_tasks", &Runner::host_tasks, "the installed tasks, one per host point in program order") .def("drain", &Runner::drain); } diff --git a/tests/contract/test_barriers.py b/tests/contract/test_barriers.py index 90bfe5a9..ba91394d 100644 --- a/tests/contract/test_barriers.py +++ b/tests/contract/test_barriers.py @@ -58,6 +58,18 @@ def test_pass_on_a_hand_built_program(): prog2 = Program(kernels={"k": KernelSpec("", "k")}, buffers={}, ops=[_op("g", ["x", "o1"], writes=[1]), _op("h", ["x2", "x"], writes=[1])]) place_barriers(prog2) assert prog2.ops[0].barrier_before and prog2.ops[1].barrier_before + + +def test_access_through_gpu_addresses_orders_like_a_binding(): + """An op that writes a buffer through a GPU address (meta indirect_writes) makes the buffer's reader wait, and an op + that reads one through a GPU address (indirect_reads) waits for the group's writer of it.""" + ops = [_op("a", ["t", "o1"], writes=[1]), _op("b", ["h", "o2"], writes=[1]), + _op("c", ["x", "h2"], writes=[1]), _op("d", ["t2", "o3"], writes=[1])] + ops[0].meta["indirect_writes"] = ["h"] + ops[3].meta["indirect_reads"] = ["h2"] + prog = Program(kernels={"k": KernelSpec("", "k")}, buffers={}, ops=ops) + place_barriers(prog) + assert [o.barrier_before for o in prog.ops] == [True, True, False, True] # states updated in place: the same buffer read and written by consecutive ops prog3 = Program(kernels={"k": KernelSpec("", "k")}, buffers={}, ops=[_op("g", ["s"], writes=[0]), _op("h", ["s", "o"], writes=[1])]) place_barriers(prog3) diff --git a/tests/runtime/shader_validation_cases.py b/tests/runtime/shader_validation_cases.py index 4b11fb87..04e1da21 100644 --- a/tests/runtime/shader_validation_cases.py +++ b/tests/runtime/shader_validation_cases.py @@ -1,7 +1,7 @@ """The cases ``test_shader_validation.py`` runs in a pytest subprocess under Metal shader validation; a tier run does not collect this file (no ``test_`` prefix). One kernel stores 64 floats into a buffer of 64 (in bounds) or 32 (out of -bounds) through each command-buffer path of the runtime: ``Queue.run``, ``Engine.run`` (ICB replay by the host pump) -and ``Engine.profile`` (``Queue.profile``). No case checks a result (the queue case drops its ``RunResult``), so only +bounds) through each command-buffer path of the runtime: ``Queue.run``, ``Engine.run`` (ICB replay by the host pump, +with and without a host step) and ``Engine.profile`` (``Queue.profile``). No case checks a result (the queue case drops its ``RunResult``), so only the runtime can fail one; the module fixture's teardown stores out of bounds after every test body has ended. Three cases never let the raised error reach pytest as a failure, so only ``tests/conftest.py`` can fail them: ``caught`` swallows it (``except Exception`` in a harness), ``skipped`` turns it into a skip and ``thread`` raises it on another @@ -11,7 +11,7 @@ import pytest from monolith.core.step_state import StepStateLayout -from monolith.runtime import BufferSpec, Engine, KernelSpec, OpSpec, Program, _native as nt +from monolith.runtime import BufferSpec, Engine, HostPoint, KernelSpec, OpSpec, Program, _native as nt SRC = """#include using namespace metal; @@ -20,16 +20,17 @@ LAYOUT = StepStateLayout() -def _program(floats: int) -> Program: +def _program(floats: int, host: bool = False) -> Program: return Program(kernels={"store": KernelSpec(SRC, "store64")}, buffers={"out": BufferSpec(floats * 4), "step_state": BufferSpec(LAYOUT.size, LAYOUT.pack({}), "step_state"), "ring": BufferSpec(64, role="ring")}, - ops=[OpSpec("store", [(0, "out", 0)], (2, 1, 1), (32, 1, 1))], ring_capacity=8, layout=LAYOUT) + ops=[OpSpec("store", [(0, "out", 0)], (2, 1, 1), (32, 1, 1))], ring_capacity=8, layout=LAYOUT, + host_points=[HostPoint("noop", publish=1, wait=1)] if host else []) @pytest.mark.parametrize("floats", [64, 32], ids=["in_bounds", "out_of_bounds"]) -@pytest.mark.parametrize("path", ["queue", "engine", "profile", "caught", "skipped", "thread"]) +@pytest.mark.parametrize("path", ["queue", "engine", "host_steps", "profile", "caught", "skipped", "thread"]) def test_store(path, floats): if path in ("queue", "caught", "skipped"): dev = nt.Device() @@ -44,6 +45,8 @@ def test_store(path, floats): pytest.skip(f"refused: {e}") elif path == "engine": Engine(_program(floats)).run(1, steps_per_cb=1, in_flight=1) + elif path == "host_steps": + Engine(_program(floats, host=True), host_tasks={"noop": lambda step, point: None}).run(1) elif path == "thread": t = threading.Thread(target=Engine(_program(floats)).run, args=(1,), kwargs={"steps_per_cb": 1, "in_flight": 1}) t.start() diff --git a/tests/runtime/test_host_steps.py b/tests/runtime/test_host_steps.py new file mode 100644 index 00000000..840bc8ef --- /dev/null +++ b/tests/runtime/test_host_steps.py @@ -0,0 +1,931 @@ +"""Host steps: a step pauses for CPU work between two of its GPU passes (HostPoint). The GPU's writes before a point's +publish boundary reach the task, the task's writes reach the ops from the point's wait boundary on, a split step is +bitwise the unsplit step, failures and timeouts end the run with every command buffer finished, and a run submits whole +steps. Every test here runs clean under MTL_SHADER_VALIDATION=1.""" +import struct +import time + +import numpy as np +import pytest + +from monolith.core.step_state import StepStateLayout +from monolith.runtime import BufferSpec, Engine, HostPoint, KernelSpec, OpSpec, Program +from monolith.runtime import _native as nt + +LAYOUT = StepStateLayout(t_max=8, gamma_max=7) +M = 0xFFFFFFFF +W = 256 # words a step hands across a host point + +SRC = """ +#include +using namespace metal; +""" + LAYOUT.to_msl() + """ +struct Params { uint n_stop; uint ring_cap; uint width; uint pad; }; + +static uint mix(uint x, uint s) { return (x ^ 0x5bd1e995u) * 0x27d4eb2du + s; } +static bool emit(device StepState* st, constant Params& p, device ulong* ring, uint token) { + uint head = st->ring_head; + if (head - st->ring_tail >= p.ring_cap) { st->error = 1u; st->done = 1u; return false; } + ring[head % p.ring_cap] = (ulong(head + 1u) << 32) | ulong(token & 0x7fffffffu); + st->ring_head = head + 1u; + return true; +} +static void advance(device StepState* st, constant Params& p) { + uint s = st->step + 1u; + st->step = s; + st->position += 1u; + if (s >= p.n_stop || (st->stop_at != 0u && st->ring_head >= st->stop_at)) st->done = 1u; +} + +// the exchange program: produce -> (host or transform) -> consume +kernel void produce(device uint* x [[buffer(0)]], device const StepState* st [[buffer(1)]], constant Params& p [[buffer(2)]], + uint i [[thread_position_in_grid]]) { + if (st->done) return; + if (i < p.width) x[i] = (st->step + 1u) * 2654435761u + i * 40503u; +} +kernel void transform(device const uint* x [[buffer(0)]], device uint* staging [[buffer(1)]], device const StepState* st [[buffer(2)]], + constant Params& p [[buffer(3)]], uint i [[thread_position_in_grid]]) { + if (st->done) return; + if (i < p.width) staging[i] = mix(x[i], st->step); +} +kernel void consume(device const uint* staging [[buffer(0)]], device uint* acc [[buffer(1)]], device StepState* st [[buffer(2)]], + constant Params& p [[buffer(3)]], device ulong* ring [[buffer(4)]], uint i [[thread_position_in_grid]]) { + if (i != 0 || st->done) return; + uint a = acc[0]; + for (uint k = 0; k < p.width; k++) a = a * 31u + staging[k]; + acc[0] = a; + if (emit(st, p, ring, a)) advance(st, p); +} + +// a float chain whose middle op is independent of the first (barrier_before = false) +kernel void chain_a(device float* y [[buffer(0)]], device const StepState* st [[buffer(1)]], constant Params& p [[buffer(2)]], + uint i [[thread_position_in_grid]]) { + if (st->done) return; + if (i < p.width) y[i] = y[i] * 0.9993f + float(st->step + i) * 1.0e-3f; +} +kernel void chain_b(device float* z [[buffer(0)]], device const StepState* st [[buffer(1)]], constant Params& p [[buffer(2)]], + uint i [[thread_position_in_grid]]) { + if (st->done) return; + if (i < p.width) z[i] = z[i] * 1.0007f - float(i) * 1.0e-4f + 0.25f; +} +kernel void chain_c(device const float* y [[buffer(0)]], device const float* z [[buffer(1)]], device StepState* st [[buffer(2)]], + constant Params& p [[buffer(3)]], device ulong* ring [[buffer(4)]], uint i [[thread_position_in_grid]]) { + if (i != 0 || st->done) return; + float t = 0.0f; + for (uint k = 0; k < p.width; k++) t = t + y[k] * z[k]; + if (emit(st, p, ring, as_type(t))) advance(st, p); +} + +// speculative-style window: picks for T rows, then a commit of the kept rows the host chose +static uint next_token(uint v) { return (v * 1103515245u + 12345u) % 1000u; } +kernel void verify(device uint* picks [[buffer(0)]], device const StepState* st [[buffer(1)]], uint i [[thread_position_in_grid]]) { + if (i != 0 || st->done) return; + uint t_n = min(st->t_this_step, 4u); + for (uint t = 0; t < t_n; t++) picks[t] = next_token(t == 0 ? uint(st->anchor) : uint(st->pending_tokens[t])); +} +kernel void commit(device const uint* picks [[buffer(0)]], device const uint* keep [[buffer(1)]], device StepState* st [[buffer(2)]], + constant Params& p [[buffer(3)]], device ulong* ring [[buffer(4)]], uint i [[thread_position_in_grid]]) { + if (i != 0 || st->done) return; + uint n_keep = clamp(keep[0], 1u, min(st->t_this_step, 4u)); + for (uint t = 0; t < n_keep; t++) if (!emit(st, p, ring, picks[t])) return; + st->anchor = int(picks[n_keep - 1]); + st->accepted = n_keep - 1; + uint s = st->step + 1u; + st->step = s; + if (st->ring_head >= p.n_stop) st->done = 1u; +} + +// several points per step +kernel void s_a(device uint* a [[buffer(0)]], device const uint* h3 [[buffer(1)]], device const StepState* st [[buffer(2)]], + uint i [[thread_position_in_grid]]) { + if (i == 0 && !st->done) a[0] = h3[0] + (st->step + 1u) * 7u; +} +kernel void s_b(device uint* b [[buffer(0)]], device const StepState* st [[buffer(1)]], uint i [[thread_position_in_grid]]) { + if (i == 0 && !st->done) b[0] = (st->step + 1u) * 13u; +} +kernel void s_c(device uint* c [[buffer(0)]], device const uint* h1 [[buffer(1)]], device const uint* h2 [[buffer(2)]], + device const StepState* st [[buffer(3)]], uint i [[thread_position_in_grid]]) { + if (i == 0 && !st->done) c[0] = h1[0] * 3u + h2[0]; +} +kernel void s_adv(device const uint* c [[buffer(0)]], device StepState* st [[buffer(1)]], constant Params& p [[buffer(2)]], + device ulong* ring [[buffer(3)]], uint i [[thread_position_in_grid]]) { + if (i != 0 || st->done) return; + if (emit(st, p, ring, c[0])) advance(st, p); +} + +// a point that publishes at the step's start and is needed only by the second op (the n-gram rows' shape) +kernel void ng_first(device uint* l0 [[buffer(0)]], device const StepState* st [[buffer(1)]], uint i [[thread_position_in_grid]]) { + if (i == 0 && !st->done) l0[0] = (st->step + 1u) * 11u; +} +kernel void ng_second(device const uint* l0 [[buffer(0)]], device const uint* rows [[buffer(1)]], device uint* prev [[buffer(2)]], + device StepState* st [[buffer(3)]], constant Params& p [[buffer(4)]], device ulong* ring [[buffer(5)]], + uint i [[thread_position_in_grid]]) { + if (i != 0 || st->done) return; + uint out = l0[0] + rows[0]; + prev[0] = out; + if (emit(st, p, ring, out)) advance(st, p); +} + +// a bounded loop of a few hundred milliseconds before a publish boundary +kernel void slow(device float* sink [[buffer(0)]], device const StepState* st [[buffer(1)]], constant Params& p [[buffer(2)]], + uint i [[thread_position_in_grid]]) { + if (i != 0 || st->done) return; + float v = sink[0]; + for (uint k = 0; k < p.width; k++) v = fma(v, 1.0000001f, 1.0e-7f); + sink[0] = v; +} +kernel void tick(device StepState* st [[buffer(0)]], constant Params& p [[buffer(1)]], device ulong* ring [[buffer(2)]], + uint i [[thread_position_in_grid]]) { + if (i != 0 || st->done) return; + if (emit(st, p, ring, st->step)) advance(st, p); +} + +// a kernel that reaches two unbound buffers through GPU addresses the host wrote into a table +struct Ptr { device const uint* p; }; +kernel void gather(device const Ptr* table [[buffer(0)]], device uint* out [[buffer(1)]], device const StepState* st [[buffer(2)]], + constant Params& p [[buffer(3)]], uint i [[thread_position_in_grid]]) { + if (st->done) return; + if (i < p.width) out[i] = table[i & 1u].p[i >> 1] + st->step; +} +""" + +KERNELS = ("produce", "transform", "consume", "chain_a", "chain_b", "chain_c", "verify", "commit", "s_a", "s_b", "s_c", + "s_adv", "ng_first", "ng_second", "slow", "tick", "gather") + + +def _params(n_stop, ring_cap, width): + return BufferSpec(16, struct.pack("= n_stop and rep.tokens == chain + assert len(windows) == eng.state()["step"] < len(rep.tokens) # one window per committed step; several kept more than one row + assert {len(w) for w in windows} == {1, 2, 3, 4} + + +def _multi_program(n_stop): + host = {name: BufferSpec(16, role="host") for name in ("h1", "h2", "h3")} + buffers = {**_base_buffers(n_stop), **host, "a": BufferSpec(16), "b": BufferSpec(16), "c": BufferSpec(16)} + ops = [_op("s_a", [(0, "a", 0), (1, "h3", 0), (2, "step_state", 0)], [0]), + _op("s_b", [(0, "b", 0), (1, "step_state", 0)], [0]), + _op("s_c", [(0, "c", 0), (1, "h1", 0), (2, "h2", 0), (3, "step_state", 0)], [0]), + _op("s_adv", [(0, "c", 0), (1, "step_state", 0), (2, "params", 0), (3, "ring", 0)], [1, 3])] + points = [HostPoint("p1", 1, 2, writes=["h1"], reads=["a"]), # s_b runs beside the task + HostPoint("p2", 2, 2, writes=["h2"], reads=["b"]), # a sync point + HostPoint("p3", 3, 4, writes=["h3"], reads=["c"])] # s_adv runs beside it; the next step waits + return _program(buffers, ops, points) + + +def test_several_points_per_step_see_their_boundaries(): + dev = nt.Device() + h = {name: nt.Buffer(dev, 16) for name in ("h1", "h2", "h3")} + seen = {"p1": [], "p2": [], "p3": []} + eng = None + + def word(name): + return struct.unpack(" 0 # slow ran beside the task and finished first + st = eng.state() + assert st["done"] == 1 and st["error"] == 4 and st["step"] == 0 + + +@pytest.mark.parametrize("objc", [False, True], ids=["cpp", "objc"]) +def test_a_task_throwing_a_non_standard_exception_fails_the_run_cleanly(objc): + """A C++ task may throw what is not a std::exception (an int, an NSException): the run still waits for the GPU, + marks the program failed and counts the step, so the next run numbers its steps on.""" + steps = [] + buffers, ops = _slow_tick(100, 20_000_000) + eng = Engine(_program(buffers, ops, [HostPoint("rec", 0, 1), HostPoint("throw", 0, 1)]), + host_tasks={"rec": lambda s, k: steps.append(s), "throw": nt._ThrowingTask(3, objc)}) + with pytest.raises(RuntimeError, match="host step 3, point 1: the task threw"): + eng.run(10) + sink = _sink(eng) + time.sleep(0.5) + st = eng.state() + assert _sink(eng) == sink # step 3's slow op finished before run() returned + assert st["done"] == 1 and st["error"] == 4 and st["step"] == 3 and steps == [0, 1, 2, 3] + for field in ("done", "error"): + eng.buffers["step_state"].write(struct.pack(" 0 # the slow op before the point completed first + + +def test_a_command_buffer_that_finishes_without_its_signal_fails_at_once(monkeypatch): + """LITHOS_HOST_STEPS_DROP_SIGNAL leaves out one point's signal; the exchange program commits nothing later before + that point is served, so no higher signal masks it.""" + monkeypatch.setenv("LITHOS_HOST_STEPS_DROP_SIGNAL", "3:0") + ex = _Exchange() + eng = ex.engine(100, host_timeout_ms=10_000) + t0 = time.monotonic() + with pytest.raises(RuntimeError, match=r"host step 3, point 0: its command buffer finished without the signal"): + eng.run(10) + assert time.monotonic() - t0 < 1.0 and [c[0] for c in ex.calls] == [0, 1, 2] + st = eng.state() + assert st["done"] == 1 and st["error"] == 4 + + +@pytest.mark.parametrize("value", ["-1:0", "+3:0", " 3:0", "3:", ":0", "3:0x", "3:9", "123456789012345678901:0"]) +def test_a_malformed_drop_signal_is_refused(monkeypatch, value): + """The hook takes two decimal numbers and a point the program has; anything else fails instead of dropping nothing.""" + monkeypatch.setenv("LITHOS_HOST_STEPS_DROP_SIGNAL", value) + with pytest.raises(RuntimeError, match="LITHOS_HOST_STEPS_DROP_SIGNAL"): + _Exchange().engine(10) + + +def test_an_empty_drop_signal_is_unset(monkeypatch): + monkeypatch.setenv("LITHOS_HOST_STEPS_DROP_SIGNAL", "") + assert _Exchange().engine(10).run(3).steps == 3 + + +def test_a_failed_runs_tokens_leave_with_its_error(): + """The failed run's report rides on its error, so none of its tokens reach a later run (a session resets StepState + and the ring, then runs the next request on the same Engine).""" + calls = [] + + def watch(step, point): + calls.append(step) + if step == 3: + raise ValueError("stop at step 3") + + eng = Engine(_program(_base_buffers(100), [_tick()], [HostPoint("watch", 1, 1)]), host_tasks={"watch": watch}) + with pytest.raises(RuntimeError, match="stop at step 3") as failed: + eng.run(10) + assert failed.value.report.steps == 4 and failed.value.report.tokens == [0, 1, 2, 3] + for name, spec in eng.program.buffers.items(): # the session's reset + if spec.role in ("state", "step_state", "ring"): + eng.buffers[name].fill(0) + rep = eng.run(5, max_tokens=5) + assert rep.steps == 5 and rep.tokens == [0, 1, 2, 3, 4] and calls == list(range(9)) + + +@pytest.mark.parametrize("host_point", [True, False], ids=["host-steps", "plain"]) +def test_a_run_drops_tokens_an_earlier_run_left_undrained(host_point): + """A run interrupted before Engine.run drained it (a KeyboardInterrupt right after the pump returns), or a direct + Runner.run, leaves its tokens in the runner; the next run's report holds only its own.""" + points = [HostPoint("t", 1, 1)] if host_point else [] + eng = Engine(_program(_base_buffers(100), [_tick()], points), host_tasks={"t": lambda s, k: None}) + st = eng.runner.run(3, 1, 1, False, 0) + assert st.steps_submitted == 3 and not st.error + assert eng.run(2).tokens == [3, 4] + + +def test_a_task_exception_no_run_took_stays_out_of_later_errors(): + """A task raised in a run nothing took the exception from (a direct Runner.run here, or an Engine.run interrupted + before it did); a later run that fails for another reason carries no cause.""" + def watch(step, point): + if step == 2: + raise ValueError("stale, from the direct run") + + eng = Engine(_program(_base_buffers(100), [_tick()], [HostPoint("watch", 1, 1)]), host_tasks={"watch": watch}) + assert "stale, from the direct run" in eng.runner.run(5, 1, 1, False, 0).error + for field in ("done", "error"): + eng.buffers["step_state"].write(struct.pack("= step + 1: + break + time.sleep(0.001) + assert eng.state()["step"] >= step + 1 + + def p(step, point): + calls["p"].append(step) + + ops = [_op("s_b", [(0, "b", 0), (1, "step_state", 0)], [0]), _tick()] + eng = Engine(_program({**_base_buffers(5), "b": BufferSpec(16)}, ops, [HostPoint("q", 1, 2), HostPoint("p", 1, 2)]), + host_tasks={"q": q, "p": p}) + rep = eng.run(100) + assert rep.done and rep.steps == 5 and rep.tokens == list(range(5)) + assert calls == {"q": list(range(5)), "p": list(range(5))} + + +def test_a_second_concurrent_run_fails_at_once(): + import threading + entered, release = threading.Event(), threading.Event() + + def hold(step, point): + if step == 0: + entered.set() + assert release.wait(5.0) + + eng = Engine(_program(_base_buffers(10), [_tick()], [HostPoint("hold", 1, 1)]), host_tasks={"hold": hold}) + first = threading.Thread(target=eng.run, args=(3,)) + first.start() + try: + assert entered.wait(5.0) # the first run holds the runner + with pytest.raises(RuntimeError, match="Runner.run: already running on another thread"): + eng.run(1) + with pytest.raises(RuntimeError, match="set_host_points: already running on another thread"): + eng.runner.set_host_points([], LAYOUT.offset("error"), 1000) + finally: + release.set() + first.join(10.0) + assert not first.is_alive() and eng.state()["step"] == 3 + + +def test_a_task_that_calls_its_own_runner_is_refused(): + errors, eng = [], None + + def reenter(step, point): + if step == 1: + for call in (lambda: eng.run(1), lambda: eng.runner.set_host_points([], LAYOUT.offset("error"), 1000)): + with pytest.raises(RuntimeError) as refused: + call() + errors.append(str(refused.value)) + + eng = Engine(_program(_base_buffers(5), [_tick()], [HostPoint("reenter", 1, 1)]), host_tasks={"reenter": reenter}) + rep = eng.run(5) + assert rep.steps == 5 and rep.tokens == list(range(5)) + assert errors == ["Runner.run: called from one of the runner's own host tasks", + "set_host_points: called from one of the runner's own host tasks"] + + +def test_plain_runs_between_host_step_runs_keep_the_step_count(): + """HostCall.step counts every step the runner began, on either pump.""" + steps = [] + eng = Engine(_program(_base_buffers(1000), [_tick()], [HostPoint("watch", 1, 1)]), + host_tasks={"watch": lambda s, k: steps.append(s)}) + error = LAYOUT.offset("error") + eng.run(3) + eng.runner.set_host_points([], error, 1000) # the plain pump + eng.run(4, steps_per_cb=1, in_flight=1) + eng.runner.set_host_points(eng.host_tasks, error, 1000) + eng.run(2) + assert steps == [0, 1, 2, 7, 8] and eng.state()["step"] == 9 + + +def test_set_host_points_again_with_fewer_points_waits_for_the_gpu(): + """A new point list gets a new event: the old one already holds values the new numbering reaches early.""" + seen, eng = [], None + + def look(step, point): + seen.append((step, point, eng.state()["step"], _sink(eng))) + + buffers, ops = _slow_tick(1000, 1_000_000) + eng = Engine(_program(buffers, ops, [HostPoint("look", 1, 1, reads=["sink"]), HostPoint("look", 1, 1, reads=["sink"])]), + host_tasks={"look": look}) + assert eng.run(10).steps == 10 + eng.runner.set_host_points([(1, 1, nt.CallableTask(look))], LAYOUT.offset("error"), 20000) + seen.clear() + rep = eng.run(10) + assert rep.steps == 10 and rep.tokens == list(range(10, 20)) + assert [(s, k, st) for s, k, st, _ in seen] == [(s, 0, s) for s in range(10, 20)] + sinks = [v for *_, v in seen] + assert all(b > a for a, b in zip(sinks, sinks[1:])) # each task ran after its step's slow op + + +def test_handoff_gaps_measure_each_handoff(): + """One gap per handoff: the GPU idle time from the command buffer that ends at the point to the one after the task.""" + buffers, ops = _slow_tick(100, 1000) + eng = Engine(_program(buffers, ops, [HostPoint("t", 1, 1)]), host_tasks={"t": lambda s, k: None}) + gaps = eng.run(10).handoff_gaps_ms + assert len(gaps) == 10 and min(gaps) > 0 and max(gaps) < 1000 + assert Engine(_program(*_slow_tick(100, 1000))).run(10).handoff_gaps_ms == [] + + +def test_profile_refuses_a_program_with_host_points(): + with pytest.raises(RuntimeError, match="host points"): + _Exchange().engine(10).profile(1) # its ops would run without their tasks + + +def _validation_program(points, **overrides): + buffers = {**_base_buffers(10), "x": BufferSpec(W * 4), "acc": BufferSpec(16), "staging": BufferSpec(W * 4, role="host"), + "w": BufferSpec(16384, role="weights")} + buffers.update(overrides) + ops = [_op("produce", [(0, "x", 0), (1, "step_state", 0), (2, "params", 0)], [0], threads=W), + _op("consume", [(0, "staging", 0), (1, "acc", 0), (2, "step_state", 0), (3, "params", 0), (4, "ring", 0)], [1, 2, 4])] + return _program(buffers, ops, points) + + +@pytest.mark.parametrize("point, message", [ + (HostPoint("t", 2, 1), r"need 0 <= publish \(2\) <= wait \(1\)"), + (HostPoint("t", 0, 3), r"<= 2, the op count"), + (HostPoint("t", 0, 1, reads=["nope"]), "unknown buffer 'nope'"), + (HostPoint("t", 1, 1, writes=["w"]), "read-only weights buffer"), + (HostPoint("t", 0, 1, reads=["x"]), r"op 0 \(produce\) writes 'x' while the task reads 'x'"), + (HostPoint("t", 1, 2, writes=["staging"]), r"op 1 \(consume\) accesses 'staging' while the task writes 'staging'"), + (HostPoint("t", 0, 1, writes=["step_state"]), r"op 0 \(produce\) accesses 'step_state'"), +]) +def test_check_host_points_rejects(point, message): + with pytest.raises(ValueError, match=message): + _validation_program([point]).check_host_points() + + +@pytest.mark.parametrize("point, message", [ + (HostPoint("t", 0, 1, writes=["staging"]), r"op 0 \(produce\) accesses 'staging' while the task writes 'staging'"), + (HostPoint("t", 0, 1, reads=["acc"]), r"op 0 \(produce\) writes 'acc' while the task reads 'acc'"), +]) +def test_check_host_points_sees_what_ops_reach_through_gpu_addresses(point, message): + program = _validation_program([point]) + program.ops[0].meta.update(indirect_reads=["staging"], indirect_writes=["acc"]) + with pytest.raises(ValueError, match=message): + program.check_host_points() + + +def test_check_host_points_accepts_reads_of_what_the_window_only_reads_and_decreasing_publishes_fail(): + _validation_program([HostPoint("t", 0, 1, reads=["step_state"])]).check_host_points() + with pytest.raises(ValueError, match="must not decrease"): + _validation_program([HostPoint("t", 1, 1), HostPoint("u", 0, 2)]).check_host_points() + + +def test_engine_rejects_missing_tasks_host_buffers_and_aliases(): + dev = nt.Device() + staging = nt.Buffer(dev, W * 4) + program = _validation_program([HostPoint("t", 1, 1, writes=["staging"])]) + with pytest.raises(ValueError, match="no task supplied"): + Engine(program, dev, buffers={"staging": staging}) + with pytest.raises(ValueError, match="the session allocates it"): + Engine(program, dev, host_tasks={"t": lambda s, k: None}) + with pytest.raises(ValueError, match=f"{W * 4 - 4} bytes, program needs {W * 4}"): + Engine(program, dev, buffers={"staging": nt.Buffer(dev, W * 4 - 4)}, host_tasks={"t": lambda s, k: None}) + # the task writes staging while produce (in the window) writes x: one buffer passed under both names + aliased = _validation_program([HostPoint("t", 0, 1, writes=["staging"])]) + _validation_program([HostPoint("t", 0, 1, writes=["staging"])]).check_host_points() # distinct by name + with pytest.raises(ValueError, match=r"op 0 \(produce\) accesses 'x' while the task writes 'staging'"): + Engine(aliased, dev, buffers={"staging": staging, "x": staging}, host_tasks={"t": lambda s, k: None}) + + +@pytest.mark.parametrize("points", [[], [HostPoint("t", 0, 1, writes=["b"])]], ids=["plain", "host-steps"]) +def test_engine_rejects_an_unknown_indirect_buffer(points): + buffers = {**_base_buffers(3), "x": BufferSpec(W * 4), "b": BufferSpec(16)} + produce = OpSpec("produce", [(0, "x", 0), (1, "step_state", 0), (2, "params", 0)], (1, 1, 1), (W, 1, 1), True, + name="produce", meta={"writes": [0], "indirect_reads": ["nope"]}) + with pytest.raises(ValueError, match="reaches 'nope' through a GPU address, which is not a program buffer"): + Engine(_program(buffers, [produce, _tick()], points), host_tasks={"t": lambda s, k: None}) + + +@pytest.mark.parametrize("host_point", [True, False], ids=["host-steps", "plain"]) +@pytest.mark.parametrize("reencode", [False, True]) +@pytest.mark.parametrize("residency_set", ["1", "0"]) +def test_unbound_host_buffers_reached_through_gpu_addresses(monkeypatch, residency_set, reencode, host_point): + monkeypatch.setenv("LITHOS_RESIDENCY_SET", residency_set) + dev = nt.Device() + n = 512 + left = np.arange(n // 2, dtype=np.uint32) * 3 + 1 + right = np.arange(n // 2, dtype=np.uint32) * 5 + 2 + ha, hb = nt.Buffer(dev, left.tobytes()), nt.Buffer(dev, right.tobytes()) + table = nt.Buffer(dev, struct.pack("= 4, out assert out.count("in this call phase that nothing raised") >= 3, out # caught, skipped, thread: tests/conftest.py @@ -48,5 +53,8 @@ def test_ci_lane_fails_the_tier(tmp_path): junit = tmp_path / "runtime.xml" p = _pytest(["-rs", f"--junitxml={junit}"], mac_gpu.tier_env(tmp_path, {}, shader_validation=True)) counts = mac_gpu.parse_junit(junit) - assert counts["tests"] == 13 and mac_gpu.judge("runtime", counts, p.returncode) == ["6 failed, 1 errors"], p.stdout + assert counts["tests"] == 15 and mac_gpu.judge("runtime", counts, p.returncode) == ["7 failed, 1 errors"], p.stdout assert junit.read_text().count("shader validation: Invalid store") >= 4 + reasons = {re.search(r"\[(\w+)-out_of_bounds\]", case.get("name")).group(1): failure.get("message").split(":")[0] + for case in ET.parse(junit).iter("testcase") if (failure := case.find("failure")) is not None} + assert reasons == REASONS, junit.read_text() diff --git a/tools/bench/host_handoff.py b/tools/bench/host_handoff.py new file mode 100644 index 00000000..48564f01 --- /dev/null +++ b/tools/bench/host_handoff.py @@ -0,0 +1,80 @@ +"""GPU idle time per host handoff, as the host-step runtime makes it (RunnerStats.handoff_gaps_ms): for each command +buffer the pump commits once a host point's task returned, its GPU start minus the GPU end of the command buffer before +it. The program is one GPU-wide pass of about half a millisecond, one host point with a no-op Python task, and a tick. +Run without shader validation: + + python tools/bench/host_handoff.py --rounds 4 --steps 300 +""" +import argparse +import struct +import sys +from pathlib import Path + +import numpy as np + +sys.path.insert(0, str(Path(__file__).resolve().parents[2])) +from monolith.core.step_state import StepStateLayout # noqa: E402 +from monolith.runtime import BufferSpec, Engine, HostPoint, KernelSpec, OpSpec, Program # noqa: E402 +from monolith.runtime import _native as nt # noqa: E402 + +LAYOUT = StepStateLayout(t_max=8, gamma_max=7) +SRC = """ +#include +using namespace metal; +""" + LAYOUT.to_msl() + """ +struct Params { uint n_stop; uint ring_cap; uint iters; uint pad; }; +kernel void busy(device float* sink [[buffer(0)]], device const StepState* st [[buffer(1)]], constant Params& p [[buffer(2)]], + uint i [[thread_position_in_grid]]) { + if (st->done) return; + float v = float(i); + for (uint k = 0; k < p.iters; k++) v = fma(v, 1.0000001f, 1.0e-7f); + sink[i] = v; +} +kernel void tick(device StepState* st [[buffer(0)]], constant Params& p [[buffer(1)]], device ulong* ring [[buffer(2)]], + uint i [[thread_position_in_grid]]) { + if (i != 0 || st->done) return; + uint head = st->ring_head; + if (head - st->ring_tail >= p.ring_cap) { st->error = 1u; st->done = 1u; return; } + ring[head % p.ring_cap] = (ulong(head + 1u) << 32) | ulong(st->step & 0x7fffffffu); + st->ring_head = head + 1u; + st->step += 1u; + if (st->step >= p.n_stop) st->done = 1u; +} +""" + + +def engine(cores: int, iters: int) -> Engine: + threads = cores * 256 + buffers = {"step_state": BufferSpec(LAYOUT.size, LAYOUT.pack({}), "step_state"), + "params": BufferSpec(16, struct.pack(" None: + ap = argparse.ArgumentParser(description=__doc__.split("\n\n")[0]) + ap.add_argument("--rounds", type=int, default=4) + ap.add_argument("--steps", type=int, default=300, help="steps per round, after --warmup steps") + ap.add_argument("--warmup", type=int, default=20) + ap.add_argument("--iters", type=int, default=20000, help="loop iterations per thread of the pass before the point") + args = ap.parse_args() + cores = nt.Device().info().gpu_cores + eng = engine(cores, args.iters) + eng.run(args.warmup) + print(f"{cores}-core GPU; one host point after a {cores}x256-thread pass of {args.iters} iterations per thread") + for r in range(args.rounds): + rep = eng.run(args.steps) + gaps = np.array(rep.handoff_gaps_ms) * 1e3 + p10, p50, p90 = np.percentile(gaps, [10, 50, 90]) + print(f"round {r + 1}: {len(gaps)} handoffs, GPU idle per handoff: min {gaps.min():.1f} p10 {p10:.1f} " + f"median {p50:.1f} p90 {p90:.1f} max {gaps.max():.1f} us") + + +if __name__ == "__main__": + main() From 8d9b056ad59efad14d6cbf8aee7df31d1a559fc4 Mon Sep 17 00:00:00 2001 From: Lance Woodson <65194841+woodsonl@users.noreply.github.com> Date: Sat, 17 Oct 2026 16:51:01 -0500 Subject: [PATCH 51/74] Close the host-step findings of a Codex cross-check A read-only Codex review (GPT-6.1-Sol, maximum reasoning) of the merged host-step runtime reported ten findings; each holds against the code. - The pump records a command buffer before it commits it: if recording threw after the commit, the failure cleanup could miss GPU work in flight. encode_segment no longer commits; commit time is now counted in RunnerStats.commit_ms, which host steps left at zero. - Runner.run sets the ring tail under the token mutex, so a drain() on another thread cannot interleave with it and deliver a token twice. - max_tokens counts the tokens taken from the ring during the run; a task that called runner.drain() used to keep the count below it. - set_host_points builds the new schedule beside the old one and swaps it in, so an allocation failure leaves the runner as it was. - Engine.run holds an engine lock across the native run and the collection of its tokens and failing task, so a second thread cannot clear the first run's tokens in between; a call from another thread or from one of the engine's own tasks fails at once. - Engine.profile also refuses tasks installed directly on the runner. - A zero-step run reports an earlier host failure (StepState error 4). - check_host_points refuses a task write that reaches a weights or params buffer through another name. - A CallableTask's exception slot is its own: the comment states that a task serves one runner, which Engine guarantees by wrapping each callable in a task of its own. Each fix with a test fails without it on main: the five new tests and the updated concurrency tests. --- monolith/runtime/engine.py | 19 +++++++- monolith/runtime/program.py | 3 ++ runtime/src/metal_core.mm | 75 +++++++++++++++++++------------- runtime/src/native.mm | 3 +- tests/runtime/test_host_steps.py | 52 ++++++++++++++++++++-- 5 files changed, 115 insertions(+), 37 deletions(-) diff --git a/monolith/runtime/engine.py b/monolith/runtime/engine.py index f9433926..a8dc1134 100644 --- a/monolith/runtime/engine.py +++ b/monolith/runtime/engine.py @@ -2,6 +2,7 @@ from __future__ import annotations +import threading from dataclasses import dataclass, field from typing import Callable, Dict, List, Optional, Union @@ -58,6 +59,8 @@ def __init__(self, program: Program, device: Optional[nt.Device] = None, buffers ``fn(step, point)``. ``host_timeout_ms``: the longest a run waits for the GPU to reach a host point or finish a command buffer.""" self.program = program + self._run_lock = threading.Lock() # one run() at a time, its results collected included + self._run_thread: Optional[int] = None self.fast_math = fast_math self.dev = device or nt.Device() self.buffers: Dict[str, nt.Buffer] = {} @@ -140,10 +143,22 @@ def run(self, max_steps: int, *, steps_per_cb: int = 8, in_flight: int = 3, reen queued buffers still complete, so a few more steps may run). A failed run raises RuntimeError with the run's StepReport, its tokens included, as ``report``; the exception a Python task raised is its cause, except that a task's KeyboardInterrupt or SystemExit is raised as it was.""" + me = threading.get_ident() + if not self._run_lock.acquire(blocking=False): + raise RuntimeError("Engine.run: called from one of the engine's own host tasks" if self._run_thread == me + else "Engine.run: already running on another thread") + self._run_thread = me + try: + return self._run(max_steps, steps_per_cb, in_flight, reencode, max_tokens) + finally: + self._run_thread = None + self._run_lock.release() + + def _run(self, max_steps: int, steps_per_cb: int, in_flight: int, reencode: bool, max_tokens: int) -> StepReport: st = self.runner.run(max_steps, steps_per_cb, in_flight, reencode, max_tokens) report = StepReport(st.steps_submitted, st.command_buffers, st.gpu_ms, st.wall_ms, st.host_busy_ms, st.done, self.runner.drain(), st.encode_ms, st.commit_ms, st.wait_ms, list(st.handoff_gaps_ms)) - code = int(self.state()["error"]) if st.done else 0 + code = int(self.state()["error"]) if st.done or st.steps_submitted == 0 else 0 message = st.error or {3: "Megakernel: bounded worker barrier timed out", 4: "a host step failed in an earlier run; the program's state is unusable"}.get(code) if not message: @@ -162,7 +177,7 @@ def profile(self, steps: int = 3) -> List[List[Tuple[float, float]]]: """Per-dispatch GPU (start, end) ms for ``steps`` re-encoded steps (one encoder per op with timestamp counter samples, so the numbers carry encoder-boundary gaps the ICB replay does not have — use them for the shares and the per-op durations, not for the step total).""" - if self.program.host_points: + if self.program.host_points or self.runner.host_tasks(): raise RuntimeError("profile() dispatches the ops without their tasks; a program with host points runs only through run()") q = nt.Queue(self.dev) return [q.profile(self.ops) for _ in range(steps)] diff --git a/monolith/runtime/program.py b/monolith/runtime/program.py index fbd47833..5e64e37a 100644 --- a/monolith/runtime/program.py +++ b/monolith/runtime/program.py @@ -101,6 +101,9 @@ def check_host_points(self, same: Optional[Callable[[str, str], bool]] = None) - for name in p.writes: if self.buffers[name].role in ("weights", "params"): raise ValueError(f"{where}: writes {name!r}, a read-only {self.buffers[name].role} buffer") + hit = next((b for b, spec in self.buffers.items() if spec.role in ("weights", "params") and same(name, b)), None) + if hit is not None: + raise ValueError(f"{where}: writes {name!r}, which reaches the read-only {self.buffers[hit].role} buffer {hit!r}") for j in range(p.publish, p.wait): reads, writes = self.ops[j].access() op = f"op {j} ({self.ops[j].name or self.ops[j].kernel})" diff --git a/runtime/src/metal_core.mm b/runtime/src/metal_core.mm index 724d94e6..bd459141 100644 --- a/runtime/src/metal_core.mm +++ b/runtime/src/metal_core.mm @@ -295,6 +295,7 @@ static void encode_icb_command(id c, const Dispatch& id ring; uint32_t cap; uint32_t tail = 0; // next ring slot the host reads std::vector tokens; std::mutex mu; + uint64_t taken = 0; // tokens drained from the ring since the current run began (max_tokens) std::atomic owner{}; // the thread inside run() or set_host_points(): one pump per runner bool resident = false; // the queue carries residency_set (replaces useResource) // host steps (set_host_points) @@ -310,7 +311,7 @@ static void encode_icb_command(id c, const Dispatch& id done_log = nil; // StepState.done copied at the end of each step, indexed by step % kDoneLog uint64_t step_base = 0; // absolute index of the next step the runner begins uint64_t event_base = 0; // step index at which gpu_ev was created (its values count from there) - bool drop = false; // test support: commit_segment leaves out the signal of (drop_step, drop_point) + bool drop = false; // test support: encode_segment leaves out the signal of (drop_step, drop_point) uint64_t drop_step = 0; uint32_t drop_point = 0; ~RunnerImpl() { if (resident) [q removeResidencySet:residency_set]; } @@ -383,6 +384,7 @@ static void drain_ring(RunnerImpl& r) { if ((uint32_t)(v >> 32) != r.tail + 1) break; r.tokens.push_back((int32_t)(uint32_t)v); r.tail++; + r.taken++; } *(volatile uint32_t*)((char*)r.state.contents + r.tail_off) = r.tail; } @@ -426,34 +428,36 @@ static void drain_ring(RunnerImpl& r) { std::to_string(points.size()) + " host points"); drop = true; drop_step = std::stoull(s.substr(0, colon)); drop_point = (uint32_t)k; } - old.swap(r.points); - r.points = std::move(points); - r.error_off = error_offset; r.timeout_ms = timeout_ms; r.spin_us = spin_us; - r.drop = drop; r.drop_step = drop_step; r.drop_point = drop_point; - r.pub_at.assign(n + 1, {}); r.wait_at.assign(n + 1, {}); + // The new schedule is built beside the old one: a throw (an allocation failure) leaves the runner as it was + std::vector> pub_at(n + 1), wait_at(n + 1); std::vector pass_cut(n + 1, false), cb_cut(n + 1, false); pass_cut[0] = pass_cut[n] = cb_cut[0] = cb_cut[n] = true; - for (uint32_t k = 0; k < r.points.size(); k++) { - const HostPoint& p = r.points[k]; - r.pub_at[p.publish].push_back(k); - r.wait_at[p.wait].push_back(k); + for (uint32_t k = 0; k < points.size(); k++) { + const HostPoint& p = points[k]; + pub_at[p.publish].push_back(k); + wait_at[p.wait].push_back(k); pass_cut[p.publish] = pass_cut[p.wait] = cb_cut[p.wait] = true; } - r.pass_cuts.clear(); r.cb_cuts.clear(); + std::vector pass_cuts, cb_cuts; for (uint32_t b = 0; b <= n; b++) { - if (pass_cut[b]) r.pass_cuts.push_back(b); - if (cb_cut[b]) r.cb_cuts.push_back(b); + if (pass_cut[b]) pass_cuts.push_back(b); + if (cb_cut[b]) cb_cuts.push_back(b); } - r.pub_seg.assign(n + 1, 0); + std::vector pub_seg(n + 1, 0); for (uint32_t j = 0, b = 1; b <= n; b++) { - while (r.cb_cuts[j + 1] < b) j++; - r.pub_seg[b] = j; + while (cb_cuts[j + 1] < b) j++; + pub_seg[b] = j; } - r.gpu_ev = [r.dev newSharedEvent]; // a fresh event: its values count from the current step - r.event_base = r.step_base; + id gpu_ev = [r.dev newSharedEvent]; // a fresh event: its values count from the current step if (!r.fence) r.fence = [r.dev newFence]; if (!r.done_log) r.done_log = [r.dev newBufferWithLength:kDoneLog * 4 options:MTLResourceStorageModeShared]; - if (!r.gpu_ev || !r.fence || !r.done_log) throw std::runtime_error("host points: newSharedEvent, newFence or newBuffer failed"); + if (!gpu_ev || !r.fence || !r.done_log) throw std::runtime_error("host points: newSharedEvent, newFence or newBuffer failed"); + old.swap(r.points); // from here on nothing allocates or throws + r.points = std::move(points); + r.pub_at.swap(pub_at); r.wait_at.swap(wait_at); r.pass_cuts.swap(pass_cuts); r.cb_cuts.swap(cb_cuts); r.pub_seg.swap(pub_seg); + r.gpu_ev = gpu_ev; r.event_base = r.step_base; + r.error_off = error_offset; r.timeout_ms = timeout_ms; r.spin_us = spin_us; + r.drop = drop; r.drop_step = drop_step; r.drop_point = drop_point; } std::vector> Runner::host_tasks() const { @@ -493,10 +497,10 @@ static void encode_pass(RunnerImpl& r, id cb, uint32_t a, uint r.fence_live = true; } -// Commits command buffer `seg` of `step`: its passes, each followed by the signals of the points publishing at its end. -// After the step's last pass, StepState.done is copied into done_log (whether the next step begins live), and the -// next step's points that publish at boundary 0 are signalled. -static id commit_segment(RunnerImpl& r, uint64_t step, uint32_t seg, bool reencode) { +// Encodes command buffer `seg` of `step`, which the caller commits: its passes, each followed by the signals of the +// points publishing at its end. After the step's last pass, StepState.done is copied into done_log (whether the next +// step begins live), and the next step's points that publish at boundary 0 are signalled. +static id encode_segment(RunnerImpl& r, uint64_t step, uint32_t seg, bool reencode) { const uint32_t n = (uint32_t)r.ops.size(), a = r.cb_cuts[seg], b = r.cb_cuts[seg + 1]; id cb = [r.q commandBuffer]; auto signal = [&](uint64_t s, uint32_t k) { @@ -518,7 +522,6 @@ static void encode_pass(RunnerImpl& r, id cb, uint32_t a, uint if (c == n) for (uint32_t k : r.pub_at[0]) signal(step + 1, k); start = c; } - [cb commit]; return cb; } @@ -593,7 +596,7 @@ static RunnerStats run_host_steps(RunnerImpl& r, uint32_t max_steps, bool reenco auto observe_state = [&]() { // the GPU's writes so far are visible: drain, check the stops drain_ring(r); st.done = *(volatile uint32_t*)((char*)r.state.contents + r.done_off) != 0; - size_t seen; { std::lock_guard lk(r.mu); seen = r.tokens.size(); } + uint64_t seen; { std::lock_guard lk(r.mu); seen = r.taken; } // a task may drain() the tokens if (st.done || (max_tokens && seen >= max_tokens)) stop = true; }; double prev_end = 0; // GPU end of the command buffer retired last (0: none in this run) @@ -630,8 +633,14 @@ static RunnerStats run_host_steps(RunnerImpl& r, uint32_t max_steps, bool reenco if (!ready || (enc_seg == 0 && !may_begin(enc_step))) break; const double e0 = now_ms(); const bool after_point = !r.wait_at[a].empty() || (a == 0 && enc_step > S0 && !r.wait_at[n].empty()); - @autoreleasepool { pending.push_back({commit_segment(r, enc_step, enc_seg, reencode), enc_step, enc_seg, after_point}); } - st.encode_ms += now_ms() - e0; + @autoreleasepool { + id cb = encode_segment(r, enc_step, enc_seg, reencode); + pending.push_back({cb, enc_step, enc_seg, after_point}); // tracked before it is committed: the failure + const double c0 = now_ms(); // cleanup waits for every committed buffer + st.encode_ms += c0 - e0; + [cb commit]; + st.commit_ms += now_ms() - c0; + } if (++enc_seg == nseg) { enc_seg = 0; enc_step++; } } if (!err.empty()) break; @@ -711,14 +720,18 @@ static RunnerStats run_host_steps(RunnerImpl& r, uint32_t max_steps, bool reenco RunnerStats Runner::run(uint32_t max_steps, uint32_t steps_per_cb, uint32_t in_flight, bool reencode, uint64_t max_tokens) { RunnerImpl& r = *impl; Hold hold(r.owner, "Runner.run"); - { std::lock_guard lk(r.mu); r.tokens.clear(); } // an earlier run's undrained tokens are not this run's - r.tail = *(volatile uint32_t*)((char*)r.state.contents + r.tail_off); // the ring tail lives in StepState: resume (or restart after a reset) from it + { + std::lock_guard lk(r.mu); // drain() may run on another thread meanwhile + r.tokens.clear(); // an earlier run's undrained tokens are not this run's + r.taken = 0; + r.tail = *(volatile uint32_t*)((char*)r.state.contents + r.tail_off); // the ring tail lives in StepState: resume (or restart after a reset) from it + } if (!r.points.empty()) return run_host_steps(r, max_steps, reencode, max_tokens); RunnerStats st; if (steps_per_cb == 0 || in_flight == 0) throw std::runtime_error("steps_per_cb and in_flight must be >= 1"); double t0 = now_ms(), c0 = cpu_ms_now(); std::deque> pending; - size_t tokens_seen = 0; + uint64_t tokens_seen = 0; auto observe = [&](id cb) { double waiting = now_ms(); [cb waitUntilCompleted]; @@ -729,7 +742,7 @@ static RunnerStats run_host_steps(RunnerImpl& r, uint32_t max_steps, bool reenco if (st.error.empty()) st.error = e; drain_ring(r); st.done = *(volatile uint32_t*)((char*)r.state.contents + r.done_off) != 0; - { std::lock_guard lk(r.mu); tokens_seen = r.tokens.size(); } // drained since the last drain(): this call's tokens + { std::lock_guard lk(r.mu); tokens_seen = r.taken; } // this call's tokens, whoever drained them }; while (st.steps_submitted < max_steps && !st.done && st.error.empty() && (max_tokens == 0 || tokens_seen < max_tokens)) { @autoreleasepool { diff --git a/runtime/src/native.mm b/runtime/src/native.mm index 28d36262..1af2d919 100644 --- a/runtime/src/native.mm +++ b/runtime/src/native.mm @@ -17,7 +17,8 @@ using namespace monolith; // A host task written in Python: fn(step, point). run() is called with the GIL released, so the call takes it; an -// exception fails the run with its message and stays on the task (take_exception) for the caller to raise. +// exception fails the run with its message and stays on the task (take_exception) for the caller to raise. The slot is +// the task's own, so a task serves one runner: Engine wraps each callable in a CallableTask of its own. struct CallableTask : HostTask { nb::callable fn; nb::object exception; diff --git a/tests/runtime/test_host_steps.py b/tests/runtime/test_host_steps.py index 840bc8ef..bd443f6f 100644 --- a/tests/runtime/test_host_steps.py +++ b/tests/runtime/test_host_steps.py @@ -681,8 +681,10 @@ def hold(step, point): first.start() try: assert entered.wait(5.0) # the first run holds the runner - with pytest.raises(RuntimeError, match="Runner.run: already running on another thread"): + with pytest.raises(RuntimeError, match="Engine.run: already running on another thread"): eng.run(1) + with pytest.raises(RuntimeError, match="Runner.run: already running on another thread"): + eng.runner.run(1, 1, 1, False, 0) with pytest.raises(RuntimeError, match="set_host_points: already running on another thread"): eng.runner.set_host_points([], LAYOUT.offset("error"), 1000) finally: @@ -696,7 +698,8 @@ def test_a_task_that_calls_its_own_runner_is_refused(): def reenter(step, point): if step == 1: - for call in (lambda: eng.run(1), lambda: eng.runner.set_host_points([], LAYOUT.offset("error"), 1000)): + for call in (lambda: eng.run(1), lambda: eng.runner.run(1, 1, 1, False, 0), + lambda: eng.runner.set_host_points([], LAYOUT.offset("error"), 1000)): with pytest.raises(RuntimeError) as refused: call() errors.append(str(refused.value)) @@ -704,7 +707,8 @@ def reenter(step, point): eng = Engine(_program(_base_buffers(5), [_tick()], [HostPoint("reenter", 1, 1)]), host_tasks={"reenter": reenter}) rep = eng.run(5) assert rep.steps == 5 and rep.tokens == list(range(5)) - assert errors == ["Runner.run: called from one of the runner's own host tasks", + assert errors == ["Engine.run: called from one of the engine's own host tasks", + "Runner.run: called from one of the runner's own host tasks", "set_host_points: called from one of the runner's own host tasks"] @@ -756,6 +760,48 @@ def test_profile_refuses_a_program_with_host_points(): _Exchange().engine(10).profile(1) # its ops would run without their tasks +def test_profile_refuses_tasks_installed_on_the_runner(): + eng = Engine(_program(_base_buffers(10), [_tick()])) + eng.runner.set_host_points([(1, 1, nt.CallableTask(lambda s, k: None))], LAYOUT.offset("error"), 1000) + with pytest.raises(RuntimeError, match="host points"): + eng.profile(1) + + +def test_a_task_that_drains_does_not_defeat_max_tokens(): + """max_tokens counts the tokens taken from the ring during the run, also those a task drained itself.""" + drained, eng = [], None + + def take(step, point): + drained.extend(eng.runner.drain()) + + eng = Engine(_program(_base_buffers(100), [_tick()], [HostPoint("take", 1, 1)]), host_tasks={"take": take}) + rep = eng.run(50, max_tokens=2) + assert rep.steps <= 3 and drained + rep.tokens == list(range(rep.steps)) + + +def test_a_task_cannot_write_weights_through_an_alias(): + dev = nt.Device() + shared = nt.Buffer(dev, 16384) + program = _validation_program([HostPoint("t", 1, 1, writes=["staging"])]) + with pytest.raises(ValueError, match=r"writes 'staging', which reaches the read-only weights buffer 'w'"): + Engine(program, dev, buffers={"staging": shared, "w": shared}, host_tasks={"t": lambda s, k: None}) + + +def test_a_zero_step_run_reports_an_earlier_host_failure(): + ex = _Exchange(fail_at=2) + eng = ex.engine(100) + with pytest.raises(RuntimeError, match="task failed at step 2"): + eng.run(10) + eng.runner.set_host_points([], LAYOUT.offset("error"), 1000) # the plain pump + with pytest.raises(RuntimeError, match="a host step failed in an earlier run"): + eng.run(0) + + +def test_host_steps_report_commit_time(): + rep = _Exchange().engine(100).run(10) + assert rep.commit_ms > 0 and rep.encode_ms > 0 + + def _validation_program(points, **overrides): buffers = {**_base_buffers(10), "x": BufferSpec(W * 4), "acc": BufferSpec(16), "staging": BufferSpec(W * 4, role="host"), "w": BufferSpec(16384, role="weights")} From aedf0f417179d7047f85527be4a39ee2454a1b4a Mon Sep 17 00:00:00 2001 From: Lance Woodson <65194841+woodsonl@users.noreply.github.com> Date: Sat, 17 Oct 2026 16:59:44 -0500 Subject: [PATCH 52/74] Release Engine.run's claim when an interrupt lands just after it A second Codex review of the cross-check fixes found that a KeyboardInterrupt landing between the lock acquire and the try in Engine.run left the lock held, so every later run failed with "already running on another thread". run() now claims the engine inside its try (_claim, under a guard lock), and the finally releases only its own claim with attribute reads and a store, between which no interrupt can land. The new test interrupts run() right after the claim and fails with the claim moved back outside the try. --- monolith/runtime/engine.py | 25 ++++++++++++++++--------- tests/runtime/test_host_steps.py | 17 +++++++++++++++++ 2 files changed, 33 insertions(+), 9 deletions(-) diff --git a/monolith/runtime/engine.py b/monolith/runtime/engine.py index a8dc1134..9cd6c193 100644 --- a/monolith/runtime/engine.py +++ b/monolith/runtime/engine.py @@ -59,8 +59,8 @@ def __init__(self, program: Program, device: Optional[nt.Device] = None, buffers ``fn(step, point)``. ``host_timeout_ms``: the longest a run waits for the GPU to reach a host point or finish a command buffer.""" self.program = program - self._run_lock = threading.Lock() # one run() at a time, its results collected included - self._run_thread: Optional[int] = None + self._run_guard = threading.Lock() # makes run()'s check and claim one step + self._run_owner: Optional[tuple] = None # (thread, token) of the run() in progress, results included self.fast_math = fast_math self.dev = device or nt.Device() self.buffers: Dict[str, nt.Buffer] = {} @@ -143,16 +143,23 @@ def run(self, max_steps: int, *, steps_per_cb: int = 8, in_flight: int = 3, reen queued buffers still complete, so a few more steps may run). A failed run raises RuntimeError with the run's StepReport, its tokens included, as ``report``; the exception a Python task raised is its cause, except that a task's KeyboardInterrupt or SystemExit is raised as it was.""" - me = threading.get_ident() - if not self._run_lock.acquire(blocking=False): - raise RuntimeError("Engine.run: called from one of the engine's own host tasks" if self._run_thread == me - else "Engine.run: already running on another thread") - self._run_thread = me + token = (threading.get_ident(), object()) try: + self._claim(token) return self._run(max_steps, steps_per_cb, in_flight, reencode, max_tokens) finally: - self._run_thread = None - self._run_lock.release() + if self._run_owner is token: # reads and a store, no call: no interrupt lands between + self._run_owner = None + + def _claim(self, token: tuple) -> None: + """Claims the engine for one run(); a second run() fails at once. run() claims inside its try, so a + KeyboardInterrupt that lands just after the claim still releases it.""" + with self._run_guard: + owner = self._run_owner + if owner is not None: + raise RuntimeError("Engine.run: called from one of the engine's own host tasks" if owner[0] == token[0] + else "Engine.run: already running on another thread") + self._run_owner = token def _run(self, max_steps: int, steps_per_cb: int, in_flight: int, reencode: bool, max_tokens: int) -> StepReport: st = self.runner.run(max_steps, steps_per_cb, in_flight, reencode, max_tokens) diff --git a/tests/runtime/test_host_steps.py b/tests/runtime/test_host_steps.py index bd443f6f..c394632a 100644 --- a/tests/runtime/test_host_steps.py +++ b/tests/runtime/test_host_steps.py @@ -712,6 +712,23 @@ def reenter(step, point): "set_host_points: called from one of the runner's own host tasks"] +def test_an_interrupt_just_after_run_claims_the_engine_releases_it(): + """A KeyboardInterrupt can land after any call; one that lands as run() has just claimed the engine must not leave + every later run refused.""" + eng = Engine(_program(_base_buffers(10), [_tick()])) + claim = eng._claim + + def claim_then_interrupt(token): + claim(token) + raise KeyboardInterrupt + + eng._claim = claim_then_interrupt + with pytest.raises(KeyboardInterrupt): + eng.run(1) + del eng._claim + assert eng.run(1).steps == 1 + + def test_plain_runs_between_host_step_runs_keep_the_step_count(): """HostCall.step counts every step the runner began, on either pump.""" steps = [] From 6a71b4925c6702ca3690dba2f823651d16ba2cb8 Mon Sep 17 00:00:00 2001 From: Lance Woodson <65194841+woodsonl@users.noreply.github.com> Date: Sat, 17 Oct 2026 17:17:21 -0500 Subject: [PATCH 53/74] Take the engine's run claim in one atomic call A second Codex review found the lock the previous commit introduced still strandable: on Python 3.14 and later a `with` arms its release only after __enter__ returns, so a KeyboardInterrupt at that point left the guard held and every later run blocked, which is worse than the refusal it replaced. The claim is now one dict.setdefault, which tests and takes it in a single call, and run() makes that call inside its try. An interrupt lands only after a call returns, at a RESUME or at a backward jump, so a claim the call took is always released by run()'s finally, whose release is subscripts and an identity test with no call of its own (checked by disassembly on 3.13, 3.14 and 3.15). Two tests: one injects a KeyboardInterrupt at every point of run() and its claim where CPython can raise a pending signal and requires a later run to still complete; the other requires the claim to hold no context manager and the release to run no call. The first fails on the acquire-before-try version, the second on both earlier versions. --- monolith/runtime/engine.py | 24 ++++----- tests/runtime/test_host_steps.py | 86 +++++++++++++++++++++++++++----- 2 files changed, 85 insertions(+), 25 deletions(-) diff --git a/monolith/runtime/engine.py b/monolith/runtime/engine.py index 9cd6c193..926915a8 100644 --- a/monolith/runtime/engine.py +++ b/monolith/runtime/engine.py @@ -9,6 +9,8 @@ from . import _native as nt from .program import Program +_RUNNING = "running" # the key Engine._run_owner keeps a run's token under + @dataclass class StepReport: @@ -59,8 +61,7 @@ def __init__(self, program: Program, device: Optional[nt.Device] = None, buffers ``fn(step, point)``. ``host_timeout_ms``: the longest a run waits for the GPU to reach a host point or finish a command buffer.""" self.program = program - self._run_guard = threading.Lock() # makes run()'s check and claim one step - self._run_owner: Optional[tuple] = None # (thread, token) of the run() in progress, results included + self._run_owner: Dict[str, tuple] = {} # the token of the run() in progress, its results included self.fast_math = fast_math self.dev = device or nt.Device() self.buffers: Dict[str, nt.Buffer] = {} @@ -148,18 +149,17 @@ def run(self, max_steps: int, *, steps_per_cb: int = 8, in_flight: int = 3, reen self._claim(token) return self._run(max_steps, steps_per_cb, in_flight, reencode, max_tokens) finally: - if self._run_owner is token: # reads and a store, no call: no interrupt lands between - self._run_owner = None + if _RUNNING in self._run_owner and self._run_owner[_RUNNING] is token: # subscripts, no call: an + del self._run_owner[_RUNNING] # interrupt lands at neither def _claim(self, token: tuple) -> None: - """Claims the engine for one run(); a second run() fails at once. run() claims inside its try, so a - KeyboardInterrupt that lands just after the claim still releases it.""" - with self._run_guard: - owner = self._run_owner - if owner is not None: - raise RuntimeError("Engine.run: called from one of the engine's own host tasks" if owner[0] == token[0] - else "Engine.run: already running on another thread") - self._run_owner = token + """Claims the engine for one run(); a second run() fails at once. The claim is one dict.setdefault, which + tests and takes the claim in a single call, and run() makes it inside its try: an interrupt lands only after + a call returns, so a claim the call took is released by run()'s finally.""" + owner = self._run_owner.setdefault(_RUNNING, token) + if owner is not token: + raise RuntimeError("Engine.run: called from one of the engine's own host tasks" if owner[0] == token[0] + else "Engine.run: already running on another thread") def _run(self, max_steps: int, steps_per_cb: int, in_flight: int, reencode: bool, max_tokens: int) -> StepReport: st = self.runner.run(max_steps, steps_per_cb, in_flight, reencode, max_tokens) diff --git a/tests/runtime/test_host_steps.py b/tests/runtime/test_host_steps.py index c394632a..36c9a3b8 100644 --- a/tests/runtime/test_host_steps.py +++ b/tests/runtime/test_host_steps.py @@ -712,21 +712,81 @@ def reenter(step, point): "set_host_points: called from one of the runner's own host tasks"] -def test_an_interrupt_just_after_run_claims_the_engine_releases_it(): - """A KeyboardInterrupt can land after any call; one that lands as run() has just claimed the engine must not leave - every later run refused.""" - eng = Engine(_program(_base_buffers(10), [_tick()])) - claim = eng._claim +def _signal_points(fn): + """The offsets in ``fn`` where CPython can raise a pending signal's KeyboardInterrupt: the instruction after one + that calls (the CALL family, and ``BEFORE_WITH``, which calls ``__enter__``), and each ``RESUME``.""" + import dis + + code, prev, out = fn.__code__, None, [] + for ins in dis.get_instructions(code): + if ins.opname == "RESUME" or (prev is not None and (prev.opname.startswith("CALL") or prev.opname == "BEFORE_WITH")): + out.append((code, ins.offset)) + prev = ins + return out + + +def test_an_interrupt_at_any_signal_point_of_the_claim_leaves_the_engine_usable(): + """Ctrl-C during a run raises at the next point CPython checks for a signal. At every such point of run() and of + the claim it makes, the engine must stay claimable, so no interrupt leaves later runs refused or blocked.""" + import sys + import threading - def claim_then_interrupt(token): - claim(token) - raise KeyboardInterrupt + eng = Engine(_program(_base_buffers(1000), [_tick()])) + points = _signal_points(Engine.run) + _signal_points(Engine._claim) + assert len(points) >= 4 # the claim, the run, and the frames' entries - eng._claim = claim_then_interrupt - with pytest.raises(KeyboardInterrupt): - eng.run(1) - del eng._claim - assert eng.run(1).steps == 1 + for code, offset in points: + raised = [] + + def trace(frame, event, arg, code=code, offset=offset, raised=raised): + if frame.f_code is not code: + return None + + def step(frame, event, arg): + if event == "opcode" and frame.f_lasti == offset and not raised: + raised.append(offset) + raise KeyboardInterrupt + return step + + frame.f_trace_opcodes = True + return step + + sys.settrace(trace) + try: + eng.run(1) + except KeyboardInterrupt: + pass + finally: + sys.settrace(None) + + steps = [] + after = threading.Thread(target=lambda: steps.append(eng.run(1).steps)) + after.start() + after.join(10.0) + where = f"{code.co_name} at offset {offset}" + assert not after.is_alive(), f"a run after an interrupt in {where} blocked" + assert steps == [1], f"a run after an interrupt in {where} failed" + + +def test_an_interrupt_cannot_strand_the_claim(): + """CPython raises a pending signal after a call returns, at a RESUME and at a backward jump. The claim therefore + holds no lock across such a point, because a ``with`` arms its release only after ``__enter__`` returns on Python + 3.14 and later, and run()'s finally releases the claim without calling anything.""" + import dis + + WITH = ("BEFORE_WITH", "LOAD_SPECIAL") # the context-manager protocol, 3.13 and 3.14 + for fn in (Engine.run, getattr(Engine, "_claim", None)): + if fn is None: + continue + held = [i.opname for i in dis.get_instructions(fn) if i.opname in WITH] + assert not held, f"{fn.__name__} holds a context manager across its claim: {held}" + + ins = list(dis.get_instructions(Engine.run)) + release = [i for i in ins if i.opname in ("CONTAINS_OP", "IS_OP", "DELETE_SUBSCR")] + assert release, "run() no longer releases the claim by subscript" + lo, hi = min(i.offset for i in release), max(i.offset for i in release) + inside = [i.opname for i in ins if lo <= i.offset <= hi] + assert not [n for n in inside if n.startswith("CALL") or n in ("RESUME", "JUMP_BACKWARD") or n in WITH], inside def test_plain_runs_between_host_step_runs_keep_the_step_count(): From eab629be0ed072119c3ba3dc29596698e6d9635e Mon Sep 17 00:00:00 2001 From: Lance Woodson <65194841+woodsonl@users.noreply.github.com> Date: Sat, 17 Oct 2026 17:30:01 -0500 Subject: [PATCH 54/74] Interrupt the run with a real signal in the claim's test The opcode-injection sweep this replaces never injected anything: its trace function set f_trace_opcodes without activating the frame's tracing, so all nine of its injection points raised nothing and the test passed on a design that strands the claim. Its injection points were also the wrong ones: an exception raised at the instruction after a call is looked up at that instruction's offset, which for the last call of the try lies outside the protected interval, where the real post-call check still sits at the call. The test now asks the interpreter for the interrupt: it raises SIGINT inside the claim and inside the run, and the interpreter turns the flag into a KeyboardInterrupt at its own next check, which is where a Ctrl-C would arrive. The test requires the interrupt to propagate and a later run to complete, and it fails when the claim moves back outside the try. The disassembly test keeps the other half: it rejects a claim held under a context manager and a release that calls anything. --- tests/runtime/test_host_steps.py | 58 ++++++++++---------------------- 1 file changed, 17 insertions(+), 41 deletions(-) diff --git a/tests/runtime/test_host_steps.py b/tests/runtime/test_host_steps.py index 36c9a3b8..621d8db6 100644 --- a/tests/runtime/test_host_steps.py +++ b/tests/runtime/test_host_steps.py @@ -712,60 +712,36 @@ def reenter(step, point): "set_host_points: called from one of the runner's own host tasks"] -def _signal_points(fn): - """The offsets in ``fn`` where CPython can raise a pending signal's KeyboardInterrupt: the instruction after one - that calls (the CALL family, and ``BEFORE_WITH``, which calls ``__enter__``), and each ``RESUME``.""" - import dis - - code, prev, out = fn.__code__, None, [] - for ins in dis.get_instructions(code): - if ins.opname == "RESUME" or (prev is not None and (prev.opname.startswith("CALL") or prev.opname == "BEFORE_WITH")): - out.append((code, ins.offset)) - prev = ins - return out - - -def test_an_interrupt_at_any_signal_point_of_the_claim_leaves_the_engine_usable(): - """Ctrl-C during a run raises at the next point CPython checks for a signal. At every such point of run() and of - the claim it makes, the engine must stay claimable, so no interrupt leaves later runs refused or blocked.""" - import sys +def test_a_real_interrupt_during_a_run_leaves_the_engine_usable(): + """Ctrl-C sets a flag the interpreter turns into a KeyboardInterrupt at its next check, which is after the call + it arrives in returns. One arriving in the claim, and one arriving in the run itself, must each leave the engine + claimable, so no interrupt leaves later runs refused or blocked.""" + import signal import threading eng = Engine(_program(_base_buffers(1000), [_tick()])) - points = _signal_points(Engine.run) + _signal_points(Engine._claim) - assert len(points) >= 4 # the claim, the run, and the frames' entries - - for code, offset in points: - raised = [] - def trace(frame, event, arg, code=code, offset=offset, raised=raised): - if frame.f_code is not code: - return None + for name in ("_claim", "_run"): + inner = getattr(eng, name, None) or getattr(Engine, name).__get__(eng) - def step(frame, event, arg): - if event == "opcode" and frame.f_lasti == offset and not raised: - raised.append(offset) - raise KeyboardInterrupt - return step + def interrupt_after(*args, _inner=inner, **kw): + out = _inner(*args, **kw) + signal.raise_signal(signal.SIGINT) # the interpreter raises it at its next check + return out - frame.f_trace_opcodes = True - return step - - sys.settrace(trace) + setattr(eng, name, interrupt_after) try: - eng.run(1) - except KeyboardInterrupt: - pass + with pytest.raises(KeyboardInterrupt): + eng.run(1) finally: - sys.settrace(None) + delattr(eng, name) steps = [] after = threading.Thread(target=lambda: steps.append(eng.run(1).steps)) after.start() after.join(10.0) - where = f"{code.co_name} at offset {offset}" - assert not after.is_alive(), f"a run after an interrupt in {where} blocked" - assert steps == [1], f"a run after an interrupt in {where} failed" + assert not after.is_alive(), f"a run after an interrupt in {name} blocked" + assert steps == [1], f"a run after an interrupt in {name} failed" def test_an_interrupt_cannot_strand_the_claim(): From 089da106ffdac1d2551b5bb652b6302c9a434ded Mon Sep 17 00:00:00 2001 From: Lance Woodson <65194841+woodsonl@users.noreply.github.com> Date: Sat, 17 Oct 2026 17:41:48 -0500 Subject: [PATCH 55/74] Give the interrupt test its own SIGINT handler A detached run inherits SIGINT as SIG_IGN, and Python keeps an ignored signal ignored, so raise_signal did nothing and the test failed every run of the verification tiers while passing from a terminal. The test now installs the default handler for its own duration and restores the one it found, so it exercises the same path whatever launched pytest. --- tests/runtime/test_host_steps.py | 46 +++++++++++++++++--------------- 1 file changed, 25 insertions(+), 21 deletions(-) diff --git a/tests/runtime/test_host_steps.py b/tests/runtime/test_host_steps.py index 621d8db6..842403a1 100644 --- a/tests/runtime/test_host_steps.py +++ b/tests/runtime/test_host_steps.py @@ -720,28 +720,32 @@ def test_a_real_interrupt_during_a_run_leaves_the_engine_usable(): import threading eng = Engine(_program(_base_buffers(1000), [_tick()])) + outer = signal.signal(signal.SIGINT, signal.default_int_handler) # a detached or nohup'd run ignores SIGINT - for name in ("_claim", "_run"): - inner = getattr(eng, name, None) or getattr(Engine, name).__get__(eng) - - def interrupt_after(*args, _inner=inner, **kw): - out = _inner(*args, **kw) - signal.raise_signal(signal.SIGINT) # the interpreter raises it at its next check - return out - - setattr(eng, name, interrupt_after) - try: - with pytest.raises(KeyboardInterrupt): - eng.run(1) - finally: - delattr(eng, name) - - steps = [] - after = threading.Thread(target=lambda: steps.append(eng.run(1).steps)) - after.start() - after.join(10.0) - assert not after.is_alive(), f"a run after an interrupt in {name} blocked" - assert steps == [1], f"a run after an interrupt in {name} failed" + try: + for name in ("_claim", "_run"): + inner = getattr(eng, name, None) or getattr(Engine, name).__get__(eng) + + def interrupt_after(*args, _inner=inner, **kw): + out = _inner(*args, **kw) + signal.raise_signal(signal.SIGINT) # the interpreter raises it at its next check + return out + + setattr(eng, name, interrupt_after) + try: + with pytest.raises(KeyboardInterrupt): + eng.run(1) + finally: + delattr(eng, name) + + steps = [] + after = threading.Thread(target=lambda: steps.append(eng.run(1).steps)) + after.start() + after.join(10.0) + assert not after.is_alive(), f"a run after an interrupt in {name} blocked" + assert steps == [1], f"a run after an interrupt in {name} failed" + finally: + signal.signal(signal.SIGINT, outer) def test_an_interrupt_cannot_strand_the_claim(): From 1a4923eb7a4b86c1162dbc95063adc66d00c9002 Mon Sep 17 00:00:00 2001 From: Lance Woodson <65194841+woodsonl@users.noreply.github.com> Date: Sat, 17 Oct 2026 18:17:39 -0500 Subject: [PATCH 56/74] Let the runner hand back the tokens of its own run CodeRabbit found the claim's release still interruptible on Python 3.10, which the package supports and CI tests: 3.10 checks the eval breaker between ordinary opcodes, so a signal can land between the identity test and the delete. No pure-Python claim closes that, because the release itself is more than one instruction there. The claim is therefore gone. The runner already guards a run with an atomic hold a second thread cannot enter, so the pump now swaps the ring's tokens into its own RunnerStats before it returns, under that hold, and Engine.run reports those instead of draining afterwards. It also reads the task list before the run, so a reconfiguration cannot shift the index of the failing task under it. Both windows the claim was added for are closed by the runner's own hold, and no Python state is left for an interrupt to strand. Engine.run from another thread, and from one of the engine's own host tasks, now meets the runner's refusal rather than an engine-level one; the concurrency tests assert that, and that the held run still reports every token the refused caller could not take. A new test reads the tokens from the pump's stats and requires a later drain to find none. --- monolith/runtime/engine.py | 31 +++---------- runtime/src/metal_core.h | 2 + runtime/src/metal_core.mm | 2 + runtime/src/native.mm | 3 +- tests/runtime/test_host_steps.py | 75 +++++++------------------------- 5 files changed, 26 insertions(+), 87 deletions(-) diff --git a/monolith/runtime/engine.py b/monolith/runtime/engine.py index 926915a8..2c0197c8 100644 --- a/monolith/runtime/engine.py +++ b/monolith/runtime/engine.py @@ -2,15 +2,12 @@ from __future__ import annotations -import threading from dataclasses import dataclass, field from typing import Callable, Dict, List, Optional, Union from . import _native as nt from .program import Program -_RUNNING = "running" # the key Engine._run_owner keeps a run's token under - @dataclass class StepReport: @@ -61,7 +58,6 @@ def __init__(self, program: Program, device: Optional[nt.Device] = None, buffers ``fn(step, point)``. ``host_timeout_ms``: the longest a run waits for the GPU to reach a host point or finish a command buffer.""" self.program = program - self._run_owner: Dict[str, tuple] = {} # the token of the run() in progress, its results included self.fast_math = fast_math self.dev = device or nt.Device() self.buffers: Dict[str, nt.Buffer] = {} @@ -144,26 +140,9 @@ def run(self, max_steps: int, *, steps_per_cb: int = 8, in_flight: int = 3, reen queued buffers still complete, so a few more steps may run). A failed run raises RuntimeError with the run's StepReport, its tokens included, as ``report``; the exception a Python task raised is its cause, except that a task's KeyboardInterrupt or SystemExit is raised as it was.""" - token = (threading.get_ident(), object()) - try: - self._claim(token) - return self._run(max_steps, steps_per_cb, in_flight, reencode, max_tokens) - finally: - if _RUNNING in self._run_owner and self._run_owner[_RUNNING] is token: # subscripts, no call: an - del self._run_owner[_RUNNING] # interrupt lands at neither - - def _claim(self, token: tuple) -> None: - """Claims the engine for one run(); a second run() fails at once. The claim is one dict.setdefault, which - tests and takes the claim in a single call, and run() makes it inside its try: an interrupt lands only after - a call returns, so a claim the call took is released by run()'s finally.""" - owner = self._run_owner.setdefault(_RUNNING, token) - if owner is not token: - raise RuntimeError("Engine.run: called from one of the engine's own host tasks" if owner[0] == token[0] - else "Engine.run: already running on another thread") - - def _run(self, max_steps: int, steps_per_cb: int, in_flight: int, reencode: bool, max_tokens: int) -> StepReport: - st = self.runner.run(max_steps, steps_per_cb, in_flight, reencode, max_tokens) - report = StepReport(st.steps_submitted, st.command_buffers, st.gpu_ms, st.wall_ms, st.host_busy_ms, st.done, self.runner.drain(), + tasks = self.runner.host_tasks() # read before the run: a reconfiguration cannot shift the + st = self.runner.run(max_steps, steps_per_cb, in_flight, reencode, max_tokens) # index of the failing task + report = StepReport(st.steps_submitted, st.command_buffers, st.gpu_ms, st.wall_ms, st.host_busy_ms, st.done, list(st.tokens), st.encode_ms, st.commit_ms, st.wait_ms, list(st.handoff_gaps_ms)) code = int(self.state()["error"]) if st.done or st.steps_submitted == 0 else 0 message = st.error or {3: "Megakernel: bounded worker barrier timed out", @@ -171,8 +150,8 @@ def _run(self, max_steps: int, steps_per_cb: int, in_flight: int, reencode: bool if not message: return report cause = None - if st.failed_task >= 0: # the failing task's own: an older one left elsewhere stays out - task = self.runner.host_tasks()[st.failed_task] + if 0 <= st.failed_task < len(tasks): # the failing task's own: an older one left elsewhere stays out + task = tasks[st.failed_task] cause = task.take_exception() if isinstance(task, nt.CallableTask) else None if cause is not None and not isinstance(cause, Exception): raise cause # KeyboardInterrupt, SystemExit diff --git a/runtime/src/metal_core.h b/runtime/src/metal_core.h index 6d560cda..ccfad4ce 100644 --- a/runtime/src/metal_core.h +++ b/runtime/src/metal_core.h @@ -167,6 +167,8 @@ struct RunnerStats { int32_t failed_task = -1; // the host point whose task failed the run (-1: none did) std::vector handoff_gaps_ms; // per command buffer committed once a host point's task returned: its GPU start // minus the GPU end of the one before it, the GPU's idle time at that handoff + std::vector tokens; // the tokens the ring still held when the run ended, taken while the run still + // owned the runner: a run on another thread cannot take them first }; class Runner { diff --git a/runtime/src/metal_core.mm b/runtime/src/metal_core.mm index bd459141..a49c00aa 100644 --- a/runtime/src/metal_core.mm +++ b/runtime/src/metal_core.mm @@ -710,6 +710,7 @@ static RunnerStats run_host_steps(RunnerImpl& r, uint32_t max_steps, bool reenco } r.step_base = begun; drain_ring(r); + { std::lock_guard lk(r.mu); st.tokens.swap(r.tokens); } // this run's tokens, taken under its own hold st.done = *(volatile uint32_t*)((char*)r.state.contents + r.done_off) != 0; st.steps_submitted = begun - S0; st.wall_ms = now_ms() - t0; @@ -775,6 +776,7 @@ static RunnerStats run_host_steps(RunnerImpl& r, uint32_t max_steps, bool reenco } while (!pending.empty()) { observe(pending.front()); pending.pop_front(); } r.step_base += st.steps_submitted; // HostCall.step counts the steps of either pump + { std::lock_guard lk(r.mu); st.tokens.swap(r.tokens); } // this run's tokens, taken under its own hold st.wall_ms = now_ms() - t0; st.host_busy_ms = cpu_ms_now() - c0; return st; diff --git a/runtime/src/native.mm b/runtime/src/native.mm index 1af2d919..52f7551e 100644 --- a/runtime/src/native.mm +++ b/runtime/src/native.mm @@ -174,7 +174,8 @@ static int runner_clear(PyObject* self) { .def_ro("gpu_ms", &RunnerStats::gpu_ms).def_ro("wall_ms", &RunnerStats::wall_ms).def_ro("host_busy_ms", &RunnerStats::host_busy_ms) .def_ro("encode_ms", &RunnerStats::encode_ms).def_ro("commit_ms", &RunnerStats::commit_ms).def_ro("wait_ms", &RunnerStats::wait_ms) .def_ro("done", &RunnerStats::done).def_ro("error", &RunnerStats::error) - .def_ro("failed_task", &RunnerStats::failed_task).def_ro("handoff_gaps_ms", &RunnerStats::handoff_gaps_ms); + .def_ro("failed_task", &RunnerStats::failed_task).def_ro("handoff_gaps_ms", &RunnerStats::handoff_gaps_ms) + .def_ro("tokens", &RunnerStats::tokens); nb::class_(m, "Runner", nb::type_slots(runner_slots)) .def("__init__", [](Runner* self, const Device& d, const Icb& icb, const std::vector& ops, std::vector resources, diff --git a/tests/runtime/test_host_steps.py b/tests/runtime/test_host_steps.py index 842403a1..3fa174ce 100644 --- a/tests/runtime/test_host_steps.py +++ b/tests/runtime/test_host_steps.py @@ -677,20 +677,21 @@ def hold(step, point): assert release.wait(5.0) eng = Engine(_program(_base_buffers(10), [_tick()], [HostPoint("hold", 1, 1)]), host_tasks={"hold": hold}) - first = threading.Thread(target=eng.run, args=(3,)) + report = [] + first = threading.Thread(target=lambda: report.append(eng.run(3))) first.start() try: assert entered.wait(5.0) # the first run holds the runner - with pytest.raises(RuntimeError, match="Engine.run: already running on another thread"): - eng.run(1) - with pytest.raises(RuntimeError, match="Runner.run: already running on another thread"): - eng.runner.run(1, 1, 1, False, 0) + for call in (lambda: eng.run(1), lambda: eng.runner.run(1, 1, 1, False, 0)): + with pytest.raises(RuntimeError, match="Runner.run: already running on another thread"): + call() with pytest.raises(RuntimeError, match="set_host_points: already running on another thread"): eng.runner.set_host_points([], LAYOUT.offset("error"), 1000) finally: release.set() first.join(10.0) assert not first.is_alive() and eng.state()["step"] == 3 + assert report[0].tokens == list(range(3)) # the refused run took none of them def test_a_task_that_calls_its_own_runner_is_refused(): @@ -704,69 +705,23 @@ def reenter(step, point): call() errors.append(str(refused.value)) + eng = Engine(_program(_base_buffers(5), [_tick()], [HostPoint("reenter", 1, 1)]), host_tasks={"reenter": reenter}) rep = eng.run(5) assert rep.steps == 5 and rep.tokens == list(range(5)) - assert errors == ["Engine.run: called from one of the engine's own host tasks", + assert errors == ["Runner.run: called from one of the runner's own host tasks", "Runner.run: called from one of the runner's own host tasks", "set_host_points: called from one of the runner's own host tasks"] -def test_a_real_interrupt_during_a_run_leaves_the_engine_usable(): - """Ctrl-C sets a flag the interpreter turns into a KeyboardInterrupt at its next check, which is after the call - it arrives in returns. One arriving in the claim, and one arriving in the run itself, must each leave the engine - claimable, so no interrupt leaves later runs refused or blocked.""" - import signal - import threading - +def test_a_run_reports_the_tokens_it_took(): + """The run takes the ring's tokens while it still owns the runner, so a drain() afterwards finds none left and no + other caller can take them first.""" eng = Engine(_program(_base_buffers(1000), [_tick()])) - outer = signal.signal(signal.SIGINT, signal.default_int_handler) # a detached or nohup'd run ignores SIGINT - - try: - for name in ("_claim", "_run"): - inner = getattr(eng, name, None) or getattr(Engine, name).__get__(eng) - - def interrupt_after(*args, _inner=inner, **kw): - out = _inner(*args, **kw) - signal.raise_signal(signal.SIGINT) # the interpreter raises it at its next check - return out - - setattr(eng, name, interrupt_after) - try: - with pytest.raises(KeyboardInterrupt): - eng.run(1) - finally: - delattr(eng, name) - - steps = [] - after = threading.Thread(target=lambda: steps.append(eng.run(1).steps)) - after.start() - after.join(10.0) - assert not after.is_alive(), f"a run after an interrupt in {name} blocked" - assert steps == [1], f"a run after an interrupt in {name} failed" - finally: - signal.signal(signal.SIGINT, outer) - - -def test_an_interrupt_cannot_strand_the_claim(): - """CPython raises a pending signal after a call returns, at a RESUME and at a backward jump. The claim therefore - holds no lock across such a point, because a ``with`` arms its release only after ``__enter__`` returns on Python - 3.14 and later, and run()'s finally releases the claim without calling anything.""" - import dis - - WITH = ("BEFORE_WITH", "LOAD_SPECIAL") # the context-manager protocol, 3.13 and 3.14 - for fn in (Engine.run, getattr(Engine, "_claim", None)): - if fn is None: - continue - held = [i.opname for i in dis.get_instructions(fn) if i.opname in WITH] - assert not held, f"{fn.__name__} holds a context manager across its claim: {held}" - - ins = list(dis.get_instructions(Engine.run)) - release = [i for i in ins if i.opname in ("CONTAINS_OP", "IS_OP", "DELETE_SUBSCR")] - assert release, "run() no longer releases the claim by subscript" - lo, hi = min(i.offset for i in release), max(i.offset for i in release) - inside = [i.opname for i in ins if lo <= i.offset <= hi] - assert not [n for n in inside if n.startswith("CALL") or n in ("RESUME", "JUMP_BACKWARD") or n in WITH], inside + st = eng.runner.run(4, 8, 3, False, 0) # the pump's own stats, not Engine's report + assert list(st.tokens) == list(range(4)) + assert eng.runner.drain() == [] # the run left none behind to be taken later + assert eng.run(2).tokens == [4, 5] def test_plain_runs_between_host_step_runs_keep_the_step_count(): From 83461e580692b941ed0860b7e98c68353856740e Mon Sep 17 00:00:00 2001 From: Lance Woodson <65194841+woodsonl@users.noreply.github.com> Date: Sat, 17 Oct 2026 18:28:57 -0500 Subject: [PATCH 57/74] Close the two findings of the review of the handback A read-only Codex review of the previous commit found both of its new edges. The pump took the ring's tokens into its stats, which left drain() empty for the five benchmarks that still collect tokens that way (tools/bench/dspark_profile.py, dspark_round_latency.py, dspark_compare_packs.py, profile_spec_round.py). It copies them now: the stats carry the run's own tokens, read under the runner's hold, and drain() keeps handing the same tokens to a caller that takes them that way. The next run clears the list as it always did. Engine.run read the task list before the native call to keep a reconfiguration from shifting the failing task's index, but a reconfiguration between that read and the hold left the engine reporting the wrong task's exception. The stats now carry the failing task itself, so no index is resolved against a list that may have moved. --- monolith/runtime/engine.py | 9 ++++----- runtime/src/metal_core.h | 7 +++++-- runtime/src/metal_core.mm | 5 +++-- runtime/src/native.mm | 2 +- tests/runtime/test_host_steps.py | 8 ++++---- 5 files changed, 17 insertions(+), 14 deletions(-) diff --git a/monolith/runtime/engine.py b/monolith/runtime/engine.py index 2c0197c8..70a44b13 100644 --- a/monolith/runtime/engine.py +++ b/monolith/runtime/engine.py @@ -140,8 +140,7 @@ def run(self, max_steps: int, *, steps_per_cb: int = 8, in_flight: int = 3, reen queued buffers still complete, so a few more steps may run). A failed run raises RuntimeError with the run's StepReport, its tokens included, as ``report``; the exception a Python task raised is its cause, except that a task's KeyboardInterrupt or SystemExit is raised as it was.""" - tasks = self.runner.host_tasks() # read before the run: a reconfiguration cannot shift the - st = self.runner.run(max_steps, steps_per_cb, in_flight, reencode, max_tokens) # index of the failing task + st = self.runner.run(max_steps, steps_per_cb, in_flight, reencode, max_tokens) report = StepReport(st.steps_submitted, st.command_buffers, st.gpu_ms, st.wall_ms, st.host_busy_ms, st.done, list(st.tokens), st.encode_ms, st.commit_ms, st.wait_ms, list(st.handoff_gaps_ms)) code = int(self.state()["error"]) if st.done or st.steps_submitted == 0 else 0 @@ -150,9 +149,9 @@ def run(self, max_steps: int, *, steps_per_cb: int = 8, in_flight: int = 3, reen if not message: return report cause = None - if 0 <= st.failed_task < len(tasks): # the failing task's own: an older one left elsewhere stays out - task = tasks[st.failed_task] - cause = task.take_exception() if isinstance(task, nt.CallableTask) else None + task = st.failed # the failing task itself: an older one left elsewhere stays out + if isinstance(task, nt.CallableTask): + cause = task.take_exception() if cause is not None and not isinstance(cause, Exception): raise cause # KeyboardInterrupt, SystemExit error = RuntimeError(message) diff --git a/runtime/src/metal_core.h b/runtime/src/metal_core.h index ccfad4ce..d81e7b29 100644 --- a/runtime/src/metal_core.h +++ b/runtime/src/metal_core.h @@ -165,10 +165,13 @@ struct RunnerStats { bool done = false; // StepState.done was observed std::string error; // the first failed command buffer's error and validation reports; stops the pump (Engine.run raises it) int32_t failed_task = -1; // the host point whose task failed the run (-1: none did) + std::shared_ptr failed; // that point's task itself: the caller reads its exception without resolving + // the index against a list another thread may have replaced meanwhile std::vector handoff_gaps_ms; // per command buffer committed once a host point's task returned: its GPU start // minus the GPU end of the one before it, the GPU's idle time at that handoff - std::vector tokens; // the tokens the ring still held when the run ended, taken while the run still - // owned the runner: a run on another thread cannot take them first + std::vector tokens; // the tokens the ring held when the run ended, read while the run still owned + // the runner: a run on another thread cannot clear them first. drain() still + // hands the same tokens to a caller that takes them that way }; class Runner { diff --git a/runtime/src/metal_core.mm b/runtime/src/metal_core.mm index a49c00aa..a4fcfac5 100644 --- a/runtime/src/metal_core.mm +++ b/runtime/src/metal_core.mm @@ -673,6 +673,7 @@ static RunnerStats run_host_steps(RunnerImpl& r, uint32_t max_steps, bool reenco if (!ok) { err = "host step " + std::to_string(srv_step) + ", point " + std::to_string(srv_k) + ": " + (terr.empty() ? "the task failed" : terr); st.failed_task = (int32_t)srv_k; + st.failed = p.task; break; } observe_state(); // a task may set done itself: then no later step begins @@ -710,7 +711,7 @@ static RunnerStats run_host_steps(RunnerImpl& r, uint32_t max_steps, bool reenco } r.step_base = begun; drain_ring(r); - { std::lock_guard lk(r.mu); st.tokens.swap(r.tokens); } // this run's tokens, taken under its own hold + { std::lock_guard lk(r.mu); st.tokens = r.tokens; } // this run's tokens, read under its own hold st.done = *(volatile uint32_t*)((char*)r.state.contents + r.done_off) != 0; st.steps_submitted = begun - S0; st.wall_ms = now_ms() - t0; @@ -776,7 +777,7 @@ static RunnerStats run_host_steps(RunnerImpl& r, uint32_t max_steps, bool reenco } while (!pending.empty()) { observe(pending.front()); pending.pop_front(); } r.step_base += st.steps_submitted; // HostCall.step counts the steps of either pump - { std::lock_guard lk(r.mu); st.tokens.swap(r.tokens); } // this run's tokens, taken under its own hold + { std::lock_guard lk(r.mu); st.tokens = r.tokens; } // this run's tokens, read under its own hold st.wall_ms = now_ms() - t0; st.host_busy_ms = cpu_ms_now() - c0; return st; diff --git a/runtime/src/native.mm b/runtime/src/native.mm index 52f7551e..13d87272 100644 --- a/runtime/src/native.mm +++ b/runtime/src/native.mm @@ -174,7 +174,7 @@ static int runner_clear(PyObject* self) { .def_ro("gpu_ms", &RunnerStats::gpu_ms).def_ro("wall_ms", &RunnerStats::wall_ms).def_ro("host_busy_ms", &RunnerStats::host_busy_ms) .def_ro("encode_ms", &RunnerStats::encode_ms).def_ro("commit_ms", &RunnerStats::commit_ms).def_ro("wait_ms", &RunnerStats::wait_ms) .def_ro("done", &RunnerStats::done).def_ro("error", &RunnerStats::error) - .def_ro("failed_task", &RunnerStats::failed_task).def_ro("handoff_gaps_ms", &RunnerStats::handoff_gaps_ms) + .def_ro("failed_task", &RunnerStats::failed_task).def_ro("failed", &RunnerStats::failed).def_ro("handoff_gaps_ms", &RunnerStats::handoff_gaps_ms) .def_ro("tokens", &RunnerStats::tokens); nb::class_(m, "Runner", nb::type_slots(runner_slots)) diff --git a/tests/runtime/test_host_steps.py b/tests/runtime/test_host_steps.py index 3fa174ce..9f2059d5 100644 --- a/tests/runtime/test_host_steps.py +++ b/tests/runtime/test_host_steps.py @@ -715,13 +715,13 @@ def reenter(step, point): def test_a_run_reports_the_tokens_it_took(): - """The run takes the ring's tokens while it still owns the runner, so a drain() afterwards finds none left and no - other caller can take them first.""" + """The run reads the ring's tokens while it still owns the runner, so its own stats carry them whatever another + thread does next; drain() still hands the same tokens to a caller that takes them that way.""" eng = Engine(_program(_base_buffers(1000), [_tick()])) st = eng.runner.run(4, 8, 3, False, 0) # the pump's own stats, not Engine's report assert list(st.tokens) == list(range(4)) - assert eng.runner.drain() == [] # the run left none behind to be taken later - assert eng.run(2).tokens == [4, 5] + assert eng.runner.drain() == list(range(4)) # the ring's own view, for the callers of it + assert eng.run(2).tokens == [4, 5] # the next run starts from an empty list def test_plain_runs_between_host_step_runs_keep_the_step_count(): From 2b4a5aca971a12f9cc44027091781b28de57d242 Mon Sep 17 00:00:00 2001 From: Lance Woodson <65194841+woodsonl@users.noreply.github.com> Date: Sat, 17 Oct 2026 18:38:15 -0500 Subject: [PATCH 58/74] Say where a failing task's exception lives A review raised that a caller keeping raw RunnerStats after dropping the runner can have the task's exception collected out from under the retained task. Engine.run reads it inside the call that returns the stats; the field now says so. --- runtime/src/metal_core.h | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/runtime/src/metal_core.h b/runtime/src/metal_core.h index d81e7b29..d6e29698 100644 --- a/runtime/src/metal_core.h +++ b/runtime/src/metal_core.h @@ -166,7 +166,9 @@ struct RunnerStats { std::string error; // the first failed command buffer's error and validation reports; stops the pump (Engine.run raises it) int32_t failed_task = -1; // the host point whose task failed the run (-1: none did) std::shared_ptr failed; // that point's task itself: the caller reads its exception without resolving - // the index against a list another thread may have replaced meanwhile + // the index against a list another thread may have replaced meanwhile. A + // Python task's exception is the runner's to keep, so read it while the + // runner lives (Engine.run reads it inside the call that returns these stats) std::vector handoff_gaps_ms; // per command buffer committed once a host point's task returned: its GPU start // minus the GPU end of the one before it, the GPU's idle time at that handoff std::vector tokens; // the tokens the ring held when the run ended, read while the run still owned From 339192e4addbec9c24786da0e5537356e92b8f04 Mon Sep 17 00:00:00 2001 From: Lance Woodson <65194841+woodsonl@users.noreply.github.com> Date: Sat, 17 Oct 2026 18:55:35 -0500 Subject: [PATCH 59/74] Refuse a task a second runner already holds A task carries one exception slot, so the cross-check's ninth finding asked that a task serve one runner. That was a comment, and nothing enforced it: set_host_points took any shared task, so two runners could install one CallableTask and overwrite each other's cause before either caller read it. A task now records the runner holding it. set_host_points claims every task of the new schedule before it swaps that schedule in, gives back what it claimed if a later point refuses, and releases the tasks the replaced schedule no longer uses. A released runner and one that dies hand their tasks back, so the same task serves the next runner. Two tests: a second runner is refused while the first holds the task and takes it once that runner is gone, and a refused call leaves the runner with no points installed and the tasks it had claimed free. --- runtime/src/metal_core.h | 4 ++++ runtime/src/metal_core.mm | 28 +++++++++++++++++++++++++-- tests/runtime/test_host_steps.py | 33 ++++++++++++++++++++++++++++++++ 3 files changed, 63 insertions(+), 2 deletions(-) diff --git a/runtime/src/metal_core.h b/runtime/src/metal_core.h index d6e29698..8c6b3a37 100644 --- a/runtime/src/metal_core.h +++ b/runtime/src/metal_core.h @@ -5,6 +5,7 @@ #pragma once #include #include +#include #include #include #include @@ -145,6 +146,9 @@ class HostTask { // boundary on are committed after it returns. Returns false with `error` set to stop the run. A task bounds its own // duration (its I/O carries timeouts): the runner cannot interrupt it. virtual bool run(const HostCall& call, std::string& error) = 0; + // The runner the task is installed on. A task serves one runner, because what it carries out of a failed run (a + // Python task's exception) is one slot; set_host_points refuses a task another runner holds. + std::atomic owner{nullptr}; }; struct HostPoint { diff --git a/runtime/src/metal_core.mm b/runtime/src/metal_core.mm index a4fcfac5..d8f00a05 100644 --- a/runtime/src/metal_core.mm +++ b/runtime/src/metal_core.mm @@ -314,7 +314,10 @@ static void encode_icb_command(id c, const Dispatch& bool drop = false; // test support: encode_segment leaves out the signal of (drop_step, drop_point) uint64_t drop_step = 0; uint32_t drop_point = 0; - ~RunnerImpl() { if (resident) [q removeResidencySet:residency_set]; } + ~RunnerImpl() { + for (auto& p : points) if (p.task) p.task->owner.store(nullptr); // its tasks serve another runner again + if (resident) [q removeResidencySet:residency_set]; + } }; // Holds the runner for one call of run() or set_host_points(). A second call fails at once instead of waiting: run() @@ -452,12 +455,30 @@ static void drain_ring(RunnerImpl& r) { if (!r.fence) r.fence = [r.dev newFence]; if (!r.done_log) r.done_log = [r.dev newBufferWithLength:kDoneLog * 4 options:MTLResourceStorageModeShared]; if (!gpu_ev || !r.fence || !r.done_log) throw std::runtime_error("host points: newSharedEvent, newFence or newBuffer failed"); + std::vector claimed; // taken for this runner; given back if a later point refuses + try { + for (auto& p : points) { + const void* free_task = nullptr; + if (!p.task->owner.compare_exchange_strong(free_task, &r) && free_task != &r) + throw std::runtime_error("host points: this task is installed on another runner (a task serves one runner)"); + if (free_task == nullptr) claimed.push_back(p.task.get()); + } + } catch (...) { + for (auto* t : claimed) t->owner.store(nullptr); + throw; + } old.swap(r.points); // from here on nothing allocates or throws r.points = std::move(points); r.pub_at.swap(pub_at); r.wait_at.swap(wait_at); r.pass_cuts.swap(pass_cuts); r.cb_cuts.swap(cb_cuts); r.pub_seg.swap(pub_seg); r.gpu_ev = gpu_ev; r.event_base = r.step_base; r.error_off = error_offset; r.timeout_ms = timeout_ms; r.spin_us = spin_us; r.drop = drop; r.drop_step = drop_step; r.drop_point = drop_point; + for (auto& p : old) { // a task this runner no longer holds serves another again + if (!p.task) continue; + bool kept = false; + for (auto& q : r.points) kept = kept || q.task == p.task; + if (!kept) p.task->owner.store(nullptr); + } } std::vector> Runner::host_tasks() const { @@ -468,7 +489,10 @@ static void drain_ring(RunnerImpl& r) { void Runner::release_host_tasks() { std::vector> dying; // the points hold null tasks before any task's destructor runs Python - for (auto& p : impl->points) dying.push_back(std::move(p.task)); + for (auto& p : impl->points) { + if (p.task) p.task->owner.store(nullptr); // released: the task serves another runner again + dying.push_back(std::move(p.task)); + } } static uint64_t event_value(const RunnerImpl& r, uint64_t step, uint32_t point) { diff --git a/tests/runtime/test_host_steps.py b/tests/runtime/test_host_steps.py index 9f2059d5..0fe30dbb 100644 --- a/tests/runtime/test_host_steps.py +++ b/tests/runtime/test_host_steps.py @@ -714,6 +714,39 @@ def reenter(step, point): "set_host_points: called from one of the runner's own host tasks"] +def test_a_task_serves_one_runner(): + """A task carries one exception slot, so a second runner may not install it: the two runs would overwrite each + other's cause. The task is free again once the runner that held it is gone.""" + import gc + + task = nt.CallableTask(lambda step, point: None) + first = Engine(_program(_base_buffers(10), [_tick()])) + second = Engine(_program(_base_buffers(10), [_tick()])) + points = [(1, 1, task)] + first.runner.set_host_points(points, LAYOUT.offset("error"), 1000) + with pytest.raises(RuntimeError, match="this task is installed on another runner"): + second.runner.set_host_points(points, LAYOUT.offset("error"), 1000) + first.runner.set_host_points(points, LAYOUT.offset("error"), 1000) # the runner that holds it may reinstall it + del first + gc.collect() # the runner that held it is gone + second.runner.set_host_points(points, LAYOUT.offset("error"), 1000) # so the next runner takes it + assert second.run(3).steps == 3 + + +def test_a_refused_task_leaves_the_runner_as_it_was(): + """The refusal comes before the schedule is swapped in, and the points of the same call that were free before it + are free again.""" + free, held = nt.CallableTask(lambda step, point: None), nt.CallableTask(lambda step, point: None) + first = Engine(_program(_base_buffers(10), [_tick()])) + second = Engine(_program(_base_buffers(10), [_tick()])) + first.runner.set_host_points([(1, 1, held)], LAYOUT.offset("error"), 1000) + with pytest.raises(RuntimeError, match="this task is installed on another runner"): + second.runner.set_host_points([(1, 1, free), (1, 1, held)], LAYOUT.offset("error"), 1000) + assert second.runner.host_tasks() == [] # nothing was installed + second.runner.set_host_points([(1, 1, free)], LAYOUT.offset("error"), 1000) # and `free` was given back + assert second.run(2).steps == 2 + + def test_a_run_reports_the_tokens_it_took(): """The run reads the ring's tokens while it still owns the runner, so its own stats carry them whatever another thread does next; drain() still hands the same tokens to a caller that takes them that way.""" From 24670c1d182bd1497c1e11bbc6ebda41b5e95333 Mon Sep 17 00:00:00 2001 From: Lance Woodson <65194841+woodsonl@users.noreply.github.com> Date: Sat, 17 Oct 2026 19:05:08 -0500 Subject: [PATCH 60/74] Give a task back only while this runner still holds it A schedule may hold one task at several points, so replacing it ran the release once per point. The clears stored null unconditionally, so a runner that claimed the task between two of them lost it again. Every release is a compare-and-clear against the releasing runner now, in the schedule swap, in release_host_tasks and in the runner's destructor. The test installs one task at two points, replaces the schedule, lets a second runner claim it, and requires the first runner to be refused. --- runtime/src/metal_core.mm | 13 ++++++++++--- tests/runtime/test_host_steps.py | 14 ++++++++++++++ 2 files changed, 24 insertions(+), 3 deletions(-) diff --git a/runtime/src/metal_core.mm b/runtime/src/metal_core.mm index d8f00a05..ad71a121 100644 --- a/runtime/src/metal_core.mm +++ b/runtime/src/metal_core.mm @@ -286,6 +286,13 @@ static void encode_icb_command(id c, const Dispatch& static constexpr uint32_t kDoneLog = 64; // steps of done snapshots kept; the GPU runs at most two steps ahead of the host +// Gives a task back, unless another runner has claimed it since (a schedule may hold one task at several points, so +// this runs more than once for it). +static void release_task(HostTask& task, const void* owner) { + const void* held = owner; + task.owner.compare_exchange_strong(held, nullptr); +} + struct RunnerImpl { id dev; id q; std::shared_ptr icb; std::vector ops; @@ -315,7 +322,7 @@ static void encode_icb_command(id c, const Dispatch& uint64_t drop_step = 0; uint32_t drop_point = 0; ~RunnerImpl() { - for (auto& p : points) if (p.task) p.task->owner.store(nullptr); // its tasks serve another runner again + for (auto& p : points) if (p.task) release_task(*p.task, this); // its tasks serve another runner again if (resident) [q removeResidencySet:residency_set]; } }; @@ -477,7 +484,7 @@ static void drain_ring(RunnerImpl& r) { if (!p.task) continue; bool kept = false; for (auto& q : r.points) kept = kept || q.task == p.task; - if (!kept) p.task->owner.store(nullptr); + if (!kept) release_task(*p.task, &r); } } @@ -490,7 +497,7 @@ static void drain_ring(RunnerImpl& r) { void Runner::release_host_tasks() { std::vector> dying; // the points hold null tasks before any task's destructor runs Python for (auto& p : impl->points) { - if (p.task) p.task->owner.store(nullptr); // released: the task serves another runner again + if (p.task) release_task(*p.task, impl.get()); // released: the task serves another runner again dying.push_back(std::move(p.task)); } } diff --git a/tests/runtime/test_host_steps.py b/tests/runtime/test_host_steps.py index 0fe30dbb..3c93b3f3 100644 --- a/tests/runtime/test_host_steps.py +++ b/tests/runtime/test_host_steps.py @@ -733,6 +733,20 @@ def test_a_task_serves_one_runner(): assert second.run(3).steps == 3 +def test_a_task_at_two_points_is_released_once(): + """A schedule may hold one task at several points, so its release runs once per point; a release gives back only + what this runner still holds, or the second one would take the task from the runner that claimed it meanwhile.""" + task = nt.CallableTask(lambda step, point: None) + first = Engine(_program(_base_buffers(10), [_tick(), _tick()])) + second = Engine(_program(_base_buffers(10), [_tick()])) + first.runner.set_host_points([(1, 1, task), (2, 2, task)], LAYOUT.offset("error"), 1000) + first.runner.set_host_points([], LAYOUT.offset("error"), 1000) # both points release the one task + second.runner.set_host_points([(1, 1, task)], LAYOUT.offset("error"), 1000) + with pytest.raises(RuntimeError, match="this task is installed on another runner"): + first.runner.set_host_points([(1, 1, task)], LAYOUT.offset("error"), 1000) + assert second.run(2).steps == 2 + + def test_a_refused_task_leaves_the_runner_as_it_was(): """The refusal comes before the schedule is swapped in, and the points of the same call that were free before it are free again.""" From 89319f656ae88090f2f6a26cad4d6ce827bc6c03 Mon Sep 17 00:00:00 2001 From: Lance Woodson <65194841+woodsonl@users.noreply.github.com> Date: Sat, 17 Oct 2026 19:36:29 -0500 Subject: [PATCH 61/74] Port basalt's Q5_K head to Metal basalt's Q5_K output head (q5k_head.cu, head_proxy.cuh) as Metal kernels in kernels/common/basalt_q5k_head.metal, each output bit for bit the arithmetic nvcc compiles for sm_120: the head (1 to 8 columns), its unmapped-row mask, the top-1 with its cross-threadgroup merge as a second dispatch, and the 2-bit proxy's pack, score and final pass. The Q5_K decode and dot move into basalt_fp.metal, shared with native_mmvq. Offsets are 64-bit where basalt's are size_t or int64_t, and the builders refuse what basalt's API refuses. Research notes: docs/research/basalt-nvcc/q5k_head.md. The net change of woodsonl/mlxstream#17 (merge 0844a96). --- docs/research/basalt-nvcc/q5k_head.md | 260 ++++++++++++++++ kernels/common/basalt_fp.metal | 53 +++- kernels/common/basalt_mmvq.metal | 38 +-- kernels/common/basalt_q5k_head.metal | 421 ++++++++++++++++++++++++++ monolith/kernels.py | 83 +++++ tests/kernels/basalt_emu.py | 215 ++++++++++++- tests/kernels/basalt_gpu.py | 147 +++++++++ tests/kernels/test_basalt_q5k_head.py | 406 +++++++++++++++++++++++++ third_party/NOTICE | 27 +- 9 files changed, 1625 insertions(+), 25 deletions(-) create mode 100644 docs/research/basalt-nvcc/q5k_head.md create mode 100644 kernels/common/basalt_q5k_head.metal create mode 100644 tests/kernels/test_basalt_q5k_head.py 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/kernels/common/basalt_fp.metal b/kernels/common/basalt_fp.metal index 95cd727a..acbda279 100644 --- a/kernels/common/basalt_fp.metal +++ b/kernels/common/basalt_fp.metal @@ -1,7 +1,7 @@ // 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, -// include/basalt/kernels/dp4a.hpp and include/basalt/kernels/q8_1_finite.hpp +// 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). @@ -33,7 +33,9 @@ // __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). // - 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. +// 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) { @@ -96,6 +98,9 @@ static inline float warp_sum(float 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)); } @@ -181,3 +186,47 @@ template static inline int q2_0_sumi(thread const Q20W& r, P x, int } 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_mmvq.metal b/kernels/common/basalt_mmvq.metal index 60739068..67a248b4 100644 --- a/kernels/common/basalt_mmvq.metal +++ b/kernels/common/basalt_mmvq.metal @@ -41,28 +41,35 @@ 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 || MMVQ_TYPE == 12 -// Q5_K (176-byte blocks: dm, scales[12], qh[32], qs[128]) and Q4_K (144: dm, scales[12], qs[128]); -// native_mmvq.cu:897-975 (Q5KTraits, Q4KTraits), dots :180-240 and :522-574 +#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 (MMVQ_TYPE == 13 ? 176 : 144) -#define QS_BYTE (MMVQ_TYPE == 13 ? 48 : 16) +#define BLOCK_BYTES 144 static inline int kqs_of(int tid) { return 2 * (tid % 16); } -struct Wt { int vl[2]; int vh[2]; uchar sc[2]; uchar m[2]; float dmx, dmy; int bq8_offset; }; +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 = (QS_BYTE + 16 * r.bq8_offset + 4 * ((iqs / 2) % 4)) / 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); -#if MMVQ_TYPE == 13 - 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; -#endif 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]; @@ -81,17 +88,10 @@ static inline float apply_acc(float tmp, thread const Wt& r, device const uint* 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); -#if MMVQ_TYPE == 13 - 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)); -#else 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)); -#endif 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); } diff --git a/kernels/common/basalt_q5k_head.metal b/kernels/common/basalt_q5k_head.metal new file mode 100644 index 00000000..61ed427a --- /dev/null +++ b/kernels/common/basalt_q5k_head.metal @@ -0,0 +1,421 @@ +// 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. +#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)] = 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] = 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; + part[3 * tg + 1] = as_type(b.idx); + part[3 * tg + 2] = 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 = 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(m, 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(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/monolith/kernels.py b/monolith/kernels.py index 7b4df0f9..e01b204e 100644 --- a/monolith/kernels.py +++ b/monolith/kernels.py @@ -524,6 +524,89 @@ 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/tests/kernels/basalt_emu.py b/tests/kernels/basalt_emu.py index 17c5059f..0edd4d49 100644 --- a/tests/kernels/basalt_emu.py +++ b/tests/kernels/basalt_emu.py @@ -2,7 +2,8 @@ # 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 and include/basalt/kernels/q8_1_finite.hpp @ +# src/kernels/cuda/native_bf16.cu, src/kernels/cuda/dense_tc.cu, src/kernels/cuda/q5k_head.cu, +# src/kernels/cuda/head_proxy.cuh and include/basalt/kernels/q8_1_finite.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). @@ -497,3 +498,215 @@ def half_sb(acc, c, hb): 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 index 89e05f6d..79437700 100644 --- a/tests/kernels/basalt_gpu.py +++ b/tests/kernels/basalt_gpu.py @@ -213,3 +213,150 @@ def dense_tc_pair(type0, w0, n_out0, type1, w1, n_out1, xq, n_in, widths, fill=0 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/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/third_party/NOTICE b/third_party/NOTICE index c70be754..62526416 100644 --- a/third_party/NOTICE +++ b/third_party/NOTICE @@ -106,6 +106,9 @@ Format: `` — adapted from / copied from `` `` @ `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: @@ -124,7 +127,10 @@ Format: `` — adapted from / copied from `` `` @ `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`). License: `third_party/BASALT-LICENSE`. + (`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`. @@ -141,6 +147,12 @@ Format: `` — adapted from / copied from `` `` @ (`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_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`, @@ -155,6 +167,14 @@ Format: `` — adapted from / copied from `` `` @ (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`). 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`. +- `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`. @@ -181,8 +201,9 @@ Format: `` — adapted from / copied from `` `` @ 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`) and `dense_tc`'s (`docs/research/basalt-nvcc/dense_tc.md`). License: - `third_party/BASALT-LICENSE`. + `docs/research/basalt-nvcc/bf16.md`), `dense_tc`'s (`docs/research/basalt-nvcc/dense_tc.md`) and 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`). License: `third_party/BASALT-LICENSE`. ## Test data From da86cbec52c9dda9f2e01fb9ab16126808fe4d84 Mon Sep 17 00:00:00 2001 From: Lance Woodson <65194841+woodsonl@users.noreply.github.com> Date: Sat, 17 Oct 2026 19:36:41 -0500 Subject: [PATCH 62/74] Port basalt's drafter experts to Metal basalt's routed Q2_0 experts of the drafter (src/core/mtp.cpp:931-935) as Metal kernels in kernels/common/basalt_s2_experts.metal: moe_group_resident's plan, quantize_q8_0_scaled and moe_grouped_s2 (gate/up, SwiGLU, the intermediate's quantizer, down). Both CUDA files build with nvcc's IEEE defaults; this GPU flushes subnormals, so every rounding site a subnormal can reach goes through IEEE helpers in basalt_q8_1.metal, and a stored NaN is sm_120's canonical 0x7fffffff. Indices are 64-bit where basalt's are size_t or long long, and the builders refuse launches basalt cannot make. Research notes: docs/research/basalt-nvcc/s2_experts.md. The net change of woodsonl/mlxstream#18 (merge d151b0a). --- docs/research/basalt-nvcc/s2_experts.md | 219 +++++++ kernels/common/basalt_experts.metal | 2 - kernels/common/basalt_fp.metal | 9 + kernels/common/basalt_q8_1.metal | 98 +++- kernels/common/basalt_s2_experts.metal | 336 +++++++++++ monolith/kernels.py | 83 +++ tests/kernels/basalt_emu.py | 78 ++- tests/kernels/basalt_gpu.py | 86 +++ tests/kernels/test_basalt_s2_experts.py | 745 ++++++++++++++++++++++++ third_party/NOTICE | 21 +- 10 files changed, 1658 insertions(+), 19 deletions(-) create mode 100644 docs/research/basalt-nvcc/s2_experts.md create mode 100644 kernels/common/basalt_s2_experts.metal create mode 100644 tests/kernels/test_basalt_s2_experts.py diff --git a/docs/research/basalt-nvcc/s2_experts.md b/docs/research/basalt-nvcc/s2_experts.md new file mode 100644 index 00000000..95ca2211 --- /dev/null +++ b/docs/research/basalt-nvcc/s2_experts.md @@ -0,0 +1,219 @@ +# 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`, `basalt_q8_1.metal`) + 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_experts.metal b/kernels/common/basalt_experts.metal index a081ddc8..e3667156 100644 --- a/kernels/common/basalt_experts.metal +++ b/kernels/common/basalt_experts.metal @@ -40,8 +40,6 @@ #endif #define GRP_NC 6 // entries a pass (iq_kernels.cu:1123) -struct GrpPtr { device const ushort* p; }; // one grp_ptr entry: a blob's 64-bit GPU address - 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) diff --git a/kernels/common/basalt_fp.metal b/kernels/common/basalt_fp.metal index acbda279..51eaab1d 100644 --- a/kernels/common/basalt_fp.metal +++ b/kernels/common/basalt_fp.metal @@ -32,6 +32,7 @@ // - 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. // - 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. @@ -105,6 +106,14 @@ static inline float expf_ftz(float x) { return ftz(fast::exp2(mul_ftz(x, as_type // 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)); } + +// 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)); diff --git a/kernels/common/basalt_q8_1.metal b/kernels/common/basalt_q8_1.metal index 1e1d27af..51398550 100644 --- a/kernels/common/basalt_q8_1.metal +++ b/kernels/common/basalt_q8_1.metal @@ -21,7 +21,9 @@ // 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. +// 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 @@ -38,7 +40,8 @@ static inline char q8_1_code(float q) { 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)) = as_type(half2(half(q8_1_finite(d)), half(q8_1_finite(sum)))); + *(device uint*) (y + 36u * (i / 32u)) = + uint(f16_bits(q8_1_finite(d))) | (uint(f16_bits(q8_1_finite(sum))) << 16); } } @@ -131,6 +134,85 @@ static inline float ieee_mul(float a, float b) { 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; +} + +// x with a NaN as sm_120's: every FADD, FMUL, FFMA and div.rn.f32 that makes a NaN gives the canonical 0x7fffffff, +// where this GPU gives 0x7fc00000. A port kernel whose NaN can only come from such operations (or pass through them) +// applies it to the float it stores. +static inline float cuda_nan(float x) { + return (as_type(x) & 0x7fffffffu) > 0x7f800000u ? as_type(0x7fffffffu) : 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; @@ -140,17 +222,7 @@ static inline void q8_1_store_ieee(float xi, device uchar* y, uint i) { } 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 - float d; // (amax compared by its bits: a compare may flush) - if (!small || key == 0) { - d = amax / 127.0f; - } else if (key >= (8 << 23)) { // amax >= 2^-119: d is normal, scaled division - d = (ieee_up64(amax) / 127.0f) * 0x1p-64f; - } else { // d on the subnormal grid: integer division - const uint b = as_type(amax); - const uint m = (b & 0x7f800000u) == 0u ? b : ((b & 0x007fffffu) | 0x00800000u) << ((b >> 23) - 1u); - d = as_type(m / 127u + (m % 127u >= 64u ? 1u : 0u)); // round to nearest (127 is odd: no ties) - } - d = q8_1_finite(d); + 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); diff --git a/kernels/common/basalt_s2_experts.metal b/kernels/common/basalt_s2_experts.metal new file mode 100644 index 00000000..22c2afa1 --- /dev/null +++ b/kernels/common/basalt_s2_experts.metal @@ -0,0 +1,336 @@ +// 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 cuda_nan (this GPU's NaN is 0x7fc00000). +// +// 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/kernels.py b/monolith/kernels.py index e01b204e..5514d4fb 100644 --- a/monolith/kernels.py +++ b/monolith/kernels.py @@ -376,6 +376,89 @@ def basalt_expert_params(n_embd: int, n_ff: int) -> bytes: 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("> 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. diff --git a/tests/kernels/basalt_gpu.py b/tests/kernels/basalt_gpu.py index 79437700..6b3ea600 100644 --- a/tests/kernels/basalt_gpu.py +++ b/tests/kernels/basalt_gpu.py @@ -126,6 +126,92 @@ def arr(a, dt, n): # a plan array, zero-padde "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, 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/third_party/NOTICE b/third_party/NOTICE index 62526416..ce4fc8f1 100644 --- a/third_party/NOTICE +++ b/third_party/NOTICE @@ -147,6 +147,12 @@ Format: `` — adapted from / copied from `` `` @ (`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`, @@ -166,7 +172,10 @@ Format: `` — adapted from / copied from `` `` @ - `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`). License: `third_party/BASALT-LICENSE`. + `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` @@ -184,6 +193,9 @@ Format: `` — adapted from / copied from `` `` @ - `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`. @@ -201,9 +213,12 @@ Format: `` — adapted from / copied from `` `` @ 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`) and the Q5_K head's + `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`). License: `third_party/BASALT-LICENSE`. + `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`. ## Test data From 5fa02490ca0ffc4209fc00e073aba86d95860caa Mon Sep 17 00:00:00 2001 From: Lance Woodson <65194841+woodsonl@users.noreply.github.com> Date: Sat, 17 Oct 2026 21:57:46 -0500 Subject: [PATCH 63/74] Store sm_120's NaN encoding at every basalt port store On sm_120 every FADD, FMUL, FFMA, MUFU and division sequence that makes or passes a NaN stores the canonical 0x7fffffff, and __float2half stores 0x7fff; this GPU's arithmetic gives 0x7fc00000 and its half() 0x7e00. cuda_nan and cuda_nan_f16 in basalt_fp.metal rewrite a stored NaN to sm_120's bits and keep every other value's, and every port kernel applies them at the stores a NaN can reach (native_mmvq and the q8_1 quantizers, the dequantizers, the routed experts, the BF16 GEMVs, dense_tc, the Q5_K head, the drafter experts). docs/research/basalt-nvcc/nan.md records each store with its evidence; test_basalt_nan.py checks each against a control without the rewrite; invariant 5 of the port contract states the rule. The net change of woodsonl/mlxstream#20 (merge 0d7d491). --- docs/design/flash-next.md | 13 +- docs/research/basalt-nvcc/nan.md | 150 ++++++++++++ docs/research/basalt-nvcc/s2_experts.md | 5 +- kernels/common/basalt_dense_tc.metal | 6 +- kernels/common/basalt_dequant.metal | 15 +- kernels/common/basalt_experts.metal | 21 +- kernels/common/basalt_fp.metal | 14 ++ kernels/common/basalt_mmvf.metal | 5 +- kernels/common/basalt_mmvq.metal | 5 +- kernels/common/basalt_q5k_head.metal | 16 +- kernels/common/basalt_q8_1.metal | 15 +- kernels/common/basalt_s2_experts.metal | 3 +- tests/kernels/basalt_emu.py | 11 +- tests/kernels/test_basalt_experts.py | 6 +- tests/kernels/test_basalt_nan.py | 312 ++++++++++++++++++++++++ tests/kernels/test_basalt_q8_1.py | 16 +- 16 files changed, 551 insertions(+), 62 deletions(-) create mode 100644 docs/research/basalt-nvcc/nan.md create mode 100644 tests/kernels/test_basalt_nan.py diff --git a/docs/design/flash-next.md b/docs/design/flash-next.md index 87898d6b..f124100c 100644 --- a/docs/design/flash-next.md +++ b/docs/design/flash-next.md @@ -104,7 +104,8 @@ ones this pack runs. 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): which multiply-adds fuse and + 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): 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 @@ -138,7 +139,15 @@ ones this pack runs. `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. + 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 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/s2_experts.md b/docs/research/basalt-nvcc/s2_experts.md index 95ca2211..e447b49b 100644 --- a/docs/research/basalt-nvcc/s2_experts.md +++ b/docs/research/basalt-nvcc/s2_experts.md @@ -100,8 +100,9 @@ dx is the quantizer's fp32 s, any non-negative float. Site by site: - **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`, `basalt_q8_1.metal`) - and stores CUDA's bits. The quantizer stores no NaN: s never is one, and a NaN r gives code 0. + 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`) diff --git a/kernels/common/basalt_dense_tc.metal b/kernels/common/basalt_dense_tc.metal index 2511f4d8..4f397d1a 100644 --- a/kernels/common/basalt_dense_tc.metal +++ b/kernels/common/basalt_dense_tc.metal @@ -20,7 +20,7 @@ // 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. +// 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 @@ -341,7 +341,7 @@ kernel void basalt_dense_tc(device const uchar* w [[buffer(0)]], device const ui 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] = tree(red + row * 8 + col); + 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 @@ -363,5 +363,5 @@ kernel void basalt_dense_tc_pair(device const uchar* w0 [[buffer(0)]], device co 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] = tree<1>(red + row * 8 + col); + (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 index a16ef250..4d8905a1 100644 --- a/kernels/common/basalt_dequant.metal +++ b/kernels/common/basalt_dequant.metal @@ -14,7 +14,8 @@ // 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. +// 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 @@ -35,8 +36,8 @@ kernel void basalt_dequant_f32(device const ushort* vx [[buffer(0)]], device flo 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] = d * float(KVALUES_IQ4NL[q & 0xfu]); - yo[j + 16] = d * float(KVALUES_IQ4NL[q >> 4]); + 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 @@ -57,7 +58,7 @@ kernel void basalt_dequant_f32(device const ushort* vx [[buffer(0)]], device flo 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] = dl * float(q); + yo[l] = cuda_nan(dl * float(q)); } } #elif DQ_TYPE == 23 @@ -69,8 +70,8 @@ kernel void basalt_dequant_f32(device const ushort* vx [[buffer(0)]], device flo 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] = d * float(KVALUES_IQ4NL[q & 0xfu]); - yo[j + 16] = d * float(KVALUES_IQ4NL[q >> 4]); + 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) @@ -80,7 +81,7 @@ kernel void basalt_dequant_f32(device const ushort* vx [[buffer(0)]], device flo 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] = d * float(code - 1); + yy[b * 64 + i] = cuda_nan(d * float(code - 1)); } #else #error "basalt_dequant: unsupported DQ_TYPE" diff --git a/kernels/common/basalt_experts.metal b/kernels/common/basalt_experts.metal index e3667156..5f20575f 100644 --- a/kernels/common/basalt_experts.metal +++ b/kernels/common/basalt_experts.metal @@ -20,7 +20,8 @@ // 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. +// 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): @@ -101,8 +102,8 @@ static inline void rows2(device const ushort* rowA, uint row_halves, int r, int } sA[c] = warp_sum(sA[c]); sB[c] = warp_sum(sB[c]); - if (lane == 2 * c) dst[(e + c) * n_ff + r] = sA[c]; - if (lane == 2 * c + 1) dst[(e + c) * n_ff + r + 1] = 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]); } } } @@ -163,19 +164,19 @@ kernel void basalt_expert_gu(device const GrpPtr* grp_ptr [[buffer(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] = s1[0]; + 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] = s2[lane]; + 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] = s[c]; + if (c < n && int(lane) == c) dst[(e + c) * n_ff + r] = cuda_nan(s[c]); } } } @@ -261,19 +262,19 @@ kernel void basalt_expert_down(device const GrpPtr* grp_ptr [[buffer(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] = s1[0]; + 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] = t == 0 ? s2[0] : s2[1]; + 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] = s[c]; + if (c < n && t == c) out[ent_dst[e + c] * n_embd + r] = cuda_nan(s[c]); } } } @@ -294,7 +295,7 @@ kernel void basalt_expert_down(device const GrpPtr* grp_ptr [[buffer(1)]], 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] = s[c]; + if (c < n && int(lane) == c) out[ent_dst[e + c] * n_embd + r] = cuda_nan(s[c]); } } } diff --git a/kernels/common/basalt_fp.metal b/kernels/common/basalt_fp.metal index 51eaab1d..e9db9808 100644 --- a/kernels/common/basalt_fp.metal +++ b/kernels/common/basalt_fp.metal @@ -33,6 +33,9 @@ // __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. @@ -111,6 +114,17 @@ static inline float h2f(ushort h) { return float(as_type(h)); } // 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; }; diff --git a/kernels/common/basalt_mmvf.metal b/kernels/common/basalt_mmvf.metal index e198ae62..16cd3461 100644 --- a/kernels/common/basalt_mmvf.metal +++ b/kernels/common/basalt_mmvf.metal @@ -13,7 +13,8 @@ // 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. +// (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 @@ -65,5 +66,5 @@ kernel void basalt_mmvf(device const float2* x [[buffer(0)]], device const uint* #endif if (t == 0) for (uint k = 0; k < NT; ++k) - if (k < p.n_tok) y[ulong(k) * p.ldy + o] = acc[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 index 67a248b4..cd4ea74f 100644 --- a/kernels/common/basalt_mmvq.metal +++ b/kernels/common/basalt_mmvq.metal @@ -15,7 +15,8 @@ // 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. +// 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). @@ -300,7 +301,7 @@ kernel void basalt_mmvq(device const ushort* w [[buffer(0)]], device const uint* 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] = 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 index 61ed427a..98d2bac2 100644 --- a/kernels/common/basalt_q5k_head.metal +++ b/kernels/common/basalt_q5k_head.metal @@ -29,6 +29,7 @@ // 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 @@ -74,7 +75,7 @@ kernel void basalt_q5k_head(device const ushort* w [[buffer(0)]], device const u 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)] = t[j]; + for (int j = 0; j < NC; ++j) y[ulong(j) * ulong(n_out) + ulong(row)] = cuda_nan(t[j]); } } @@ -126,16 +127,16 @@ kernel void basalt_q5k_head_top1(device const ushort* w [[buffer(0)]], device co // 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] = t[0]; + 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; + 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] = b.s; + part[3 * tg + 2] = cuda_nan(b.s); } } @@ -158,7 +159,7 @@ kernel void basalt_q5k_head_top1_merge(device const float* part [[buffer(0)]], d 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 = rcp_ftz(b.s); + *out_prob = cuda_nan(rcp_ftz(b.s)); } } @@ -309,7 +310,7 @@ kernel void basalt_q5k_proxy_score(device const uint4* proxy [[buffer(0)]], devi 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(m, e); + 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; @@ -318,7 +319,8 @@ kernel void basalt_q5k_proxy_score(device const uint4* proxy [[buffer(0)]], devi 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(bv, as_type(int(tile) * 32 + bi)); + 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(); } } diff --git a/kernels/common/basalt_q8_1.metal b/kernels/common/basalt_q8_1.metal index 51398550..14a60c51 100644 --- a/kernels/common/basalt_q8_1.metal +++ b/kernels/common/basalt_q8_1.metal @@ -8,7 +8,8 @@ // 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. +// 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 @@ -37,11 +38,12 @@ 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(f16_bits(q8_1_finite(d))) | (uint(f16_bits(q8_1_finite(sum))) << 16); + *(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); } } @@ -206,13 +208,6 @@ static inline float warp_sum_ieee(float x) { return x; } -// x with a NaN as sm_120's: every FADD, FMUL, FFMA and div.rn.f32 that makes a NaN gives the canonical 0x7fffffff, -// where this GPU gives 0x7fc00000. A port kernel whose NaN can only come from such operations (or pass through them) -// applies it to the float it stores. -static inline float cuda_nan(float x) { - return (as_type(x) & 0x7fffffffu) > 0x7f800000u ? as_type(0x7fffffffu) : 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; diff --git a/kernels/common/basalt_s2_experts.metal b/kernels/common/basalt_s2_experts.metal index 22c2afa1..dee3e925 100644 --- a/kernels/common/basalt_s2_experts.metal +++ b/kernels/common/basalt_s2_experts.metal @@ -16,7 +16,8 @@ // 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 cuda_nan (this GPU's NaN is 0x7fc00000). +// 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) diff --git a/tests/kernels/basalt_emu.py b/tests/kernels/basalt_emu.py index 021c12fb..eea1feb7 100644 --- a/tests/kernels/basalt_emu.py +++ b/tests/kernels/basalt_emu.py @@ -76,11 +76,16 @@ def roundf(x): def half_bits(x): - """float32 to fp16 bits, round to nearest even (CUDA's __float2half, Metal's half()).""" + """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) @@ -111,8 +116,8 @@ def q8_1_codes(q, amax): def q8_1_pack(d, s, codes): out = np.zeros((len(d), 36), np.uint8) - out[:, 0:2] = half_bits(q8_1_finite(d)).view(np.uint8).reshape(-1, 2) - out[:, 2:4] = half_bits(q8_1_finite(s)).view(np.uint8).reshape(-1, 2) + 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) diff --git a/tests/kernels/test_basalt_experts.py b/tests/kernels/test_basalt_experts.py index c03806ae..8d990c41 100644 --- a/tests/kernels/test_basalt_experts.py +++ b/tests/kernels/test_basalt_experts.py @@ -307,7 +307,7 @@ def test_swiglu_q8_1_edges(): 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; a NaN's fp16 payload is the GPU's, as in test_basalt_q8_1). Entries [1, 5) of a 6-entry + 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 @@ -336,8 +336,8 @@ def test_swiglu_q8_1_edges(): 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 - assert np.array_equal(gh[~nan_h], wh[~nan_h]) and np.all((gh[nan_h] & 0x7C00) == 0x7C00) \ - and np.all(gh[nan_h] & 0x3FF), np.flatnonzero(np.any((gh != wh) & ~nan_h, axis=1)) + # 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))) 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_q8_1.py b/tests/kernels/test_basalt_q8_1.py index 20f2b590..b8d2067b 100644 --- a/tests/kernels/test_basalt_q8_1.py +++ b/tests/kernels/test_basalt_q8_1.py @@ -11,7 +11,8 @@ (: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). + 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).""" @@ -105,15 +106,10 @@ def test_quantizers_match_the_emulation_bit_for_bit(): 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) - # a NaN's fp16 payload is the GPU's; its codes, its other half and every other block are bit for bit - diff = np.any(got != want, axis=1) - assert not np.any(diff & ~nan_blocks), (kind, np.flatnonzero(diff & ~nan_blocks)[:8]) - assert np.array_equal(got[nan_blocks, 4:], want[nan_blocks, 4:]), kind - isnan_h = lambda h: (h & 0x7C00) == 0x7C00 and (h & 0x3FF) != 0 - for g, w in zip(got[nan_blocks], want[nan_blocks]): - for k in (0, 2): - gh, wh = int(g[k:k + 2].view(np.uint16)[0]), int(w[k:k + 2].view(np.uint16)[0]) - assert gh == wh or (isnan_h(gh) and isnan_h(wh)), kind + # 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(): From 54eb320b7e4bf26e059215351fa4c559fb8ca545 Mon Sep 17 00:00:00 2001 From: Lance Woodson <65194841+woodsonl@users.noreply.github.com> Date: Sun, 18 Oct 2026 05:57:13 -0500 Subject: [PATCH 64/74] Bind .basalt tensors through read-only windows of the file BasaltSource (monolith/packs/basalt.py) serves a .basalt file's tensors by IR name (gguf/, dense/, mtp/, whole sections), each an absolute byte range with its ggml type and shape, and refuses what basalt does not load as stored: dense rows it converts or serves from gguf, a slot its source bytes do not fill, the hyper-connection matrices its kernels read only through their 8-bit copies, types the format plugins lack, sizes a type and shape do not give. emit_program takes a source wherever it takes a pack: the basalt_windows planner maps only the pages the bound tensors touch, in page-aligned windows inside the file of at most WINDOW_BYTES each, named by a digest of (path, offset, size), and refuses a binding off a 16-byte boundary. PackFile programs are byte for byte unchanged. A file-backed buffer that runs past the end of its file is refused when it is mapped (an fstat guard in metal_core.mm) rather than faulting on first touch, and the reader's size check multiplies exactly. A copy test mode gives each tensor an exact buffer read from the same file. The net change of woodsonl/mlxstream#22 (merge e2e0bd5). --- monolith/compiler/emit.py | 79 ++++- monolith/formats/basalt_reader.py | 3 +- monolith/packs/basalt.py | 141 +++++++++ runtime/src/metal_core.mm | 12 + tests/contract/test_basalt_windows.py | 412 ++++++++++++++++++++++++++ tests/runtime/test_basalt_windows.py | 113 +++++++ 6 files changed, 752 insertions(+), 8 deletions(-) create mode 100644 monolith/packs/basalt.py create mode 100644 tests/contract/test_basalt_windows.py create mode 100644 tests/runtime/test_basalt_windows.py diff --git a/monolith/compiler/emit.py b/monolith/compiler/emit.py index 4387626b..727d7bf7 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,6 +34,7 @@ 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 @@ -47,7 +52,7 @@ @dataclass class _Ctx: program: Program - packs: List[PackFile] + packs: List[Union[PackFile, BasaltSource]] layout: StepStateLayout t: int n_sg: int @@ -214,11 +219,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"]: @@ -1368,7 +1433,7 @@ def _moe_combine(ctx: _Ctx, op: Op) -> None: @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 +1442,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 +1452,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/formats/basalt_reader.py b/monolith/formats/basalt_reader.py index c8ba5692..3fe4b3b7 100644 --- a/monolith/formats/basalt_reader.py +++ b/monolith/formats/basalt_reader.py @@ -44,6 +44,7 @@ import hashlib import json +import math import os import re import struct @@ -302,7 +303,7 @@ def tensor(self, name: str) -> GgufTensor: 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]) * int(np.prod(ne[1:], dtype=np.int64)): + 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) 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/runtime/src/metal_core.mm b/runtime/src/metal_core.mm index df02d623..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. 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=" +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] From 73051ab1a65504cfb2508d06408961dab234f930 Mon Sep 17 00:00:00 2001 From: Lance Woodson <65194841+woodsonl@users.noreply.github.com> Date: Sun, 18 Oct 2026 11:35:41 -0500 Subject: [PATCH 65/74] Emit basalt's single-dispatch GEMVs and q8_1 quantizers as ops monolith/ops/basalt.py registers one op kind per basalt host launcher (basalt_q8_1 with its native, swiglu and ieee quantizers, basalt_mmvq, basalt_dense_tc, basalt_dense_tc_pair, basalt_mmvf), so a compiled program can emit the merged Metal kernels over a .basalt file's weight windows; its docstring is the contract. monolith/compiler/emit_basalt.py holds their handlers, merged into emit.HANDLERS: each emits one dispatch whose macros, grid, threadgroup and params come only from monolith/kernels.py's builders (basalt_q8_1_grid and basalt_mmvf_grid are new), and checks at emit time basalt's launcher checks, pointer alignment at every binding, what basalt's call sites satisfy (contiguous output columns, the IEEE q8_1 rows read only by the routed experts and never through a view, a weight as shipped rows whose pack aux entry holds exactly its rows), and refuses a dynamic-T program. dense_tc keeps the summation order basalt's variant rule picks on its 170 multiprocessors. Engine now refuses a pipeline whose SIMD-groups are not 32 lanes and an op whose threadgroup exceeds its pipeline's max_threads_per_threadgroup, which would not run as encoded. Tests: tests/contract/test_basalt_ops.py (dispatches against the builders at T = 1 .. 8, dense_tc's order, each refusal with one defect), tests/kernels/test_basalt_ops_program.py (static programs at T = 1 .. 8 on the GPU, bitwise equal to the single-kernel harness and window invariant) and tests/runtime/test_engine_limits.py. The net change of woodsonl/mlxstream#23 (merge e7eb8b4). Its one conflict was engine.py's imports: the fork's carry field, Callable and Union for the host-step runtime, which this base lacks; this commit adds only #23's import math. --- monolith/compiler/emit.py | 3 +- monolith/compiler/emit_basalt.py | 176 ++++++++ monolith/kernels.py | 11 + monolith/ops/__init__.py | 2 +- monolith/ops/basalt.py | 54 +++ monolith/runtime/engine.py | 10 + tests/contract/test_basalt_ops.py | 499 +++++++++++++++++++++++ tests/kernels/test_basalt_ops_program.py | 156 +++++++ tests/runtime/test_engine_limits.py | 57 +++ third_party/NOTICE | 9 + 10 files changed, 975 insertions(+), 2 deletions(-) create mode 100644 monolith/compiler/emit_basalt.py create mode 100644 monolith/ops/basalt.py create mode 100644 tests/contract/test_basalt_ops.py create mode 100644 tests/kernels/test_basalt_ops_program.py create mode 100644 tests/runtime/test_engine_limits.py diff --git a/monolith/compiler/emit.py b/monolith/compiler/emit.py index 727d7bf7..9556db90 100644 --- a/monolith/compiler/emit.py +++ b/monolith/compiler/emit.py @@ -39,6 +39,7 @@ 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) @@ -1429,7 +1430,7 @@ 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") 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/kernels.py b/monolith/kernels.py index 5514d4fb..ed084a5e 100644 --- a/monolith/kernels.py +++ b/monolith/kernels.py @@ -276,6 +276,11 @@ def basalt_q8_1_params(n_values: int) -> bytes: 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), @@ -518,6 +523,12 @@ def basalt_mmvf_params(n_in: int, n_out: int, n_tok: int = 1, ldx: Optional[int] 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.""" 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/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/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/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/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/NOTICE b/third_party/NOTICE index ce4fc8f1..842e92ee 100644 --- a/third_party/NOTICE +++ b/third_party/NOTICE @@ -181,6 +181,15 @@ Format: `` — adapted from / copied from `` `` @ 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`. From 7141a06a2559ea1836cbb100f9dceb305f3002b4 Mon Sep 17 00:00:00 2001 From: Lance Woodson <65194841+woodsonl@users.noreply.github.com> Date: Sun, 18 Oct 2026 13:15:21 -0500 Subject: [PATCH 66/74] Port basalt's Q2_0 CPU expert kernels to ARM NEON The first piece of the expert tiers (OI-007): basalt's act_quant_q8_1 and q2_0_gguf_rows_multi, the arithmetic basalt runs on the CPU when the GPU expert cache misses, transcribed from AVX-512 to ARM NEON operation for operation in runtime/src/basalt_cpu.cpp, with basalt's ActQ, geometry constants and signatures in basalt_cpu.h. Where a literal transcription would give other bits, the port writes x86's: the float-to-int conversion returns the integer indefinite (-127 after the clamp) for a NaN, an infinity or an overflow where FCVTZS saturates; the horizontal sum and max trees are written out by hand in GCC's AVX-512 header order, MAXPS's operand order visible at every node; the file builds with -ffp-contract=off (runtime/CMakeLists.txt); and a row whose result is a NaN is recomputed lane by lane under x86's NaN rules. native.mm binds both kernels and checks dtype, rank, shape, contiguity and every bound (by division, which cannot wrap) before it releases the interpreter lock. Tests: tests/kernels/test_basalt_cpu_q2.py against the numpy AVX-512 reference tests/kernels/basalt_cpu_emu.py, x86 golden values and a float64 check through llama.cpp's dequantizer. docs/research/basalt-cpu-q2.md holds the research the transcription cites; the port contract (docs/design/flash-next.md) states the quantizer's rule and the CPU tier's bar; third_party/NOTICE gains three entries. The net change of woodsonl/mlxstream#21 (merge 9b255e0). Its one conflict was runtime/src/native.mm: the fork's includes and the declarations before NB_MODULE carry the host-step runtime (the Foundation import, , , , CallableTask and the host-task type slots), which this base lacks, so this commit adds only woodsonl/mlxstream#21's lines there. docs/design/flash-next.md merged clean and likewise gets only its two changed rows. The other seven files equal the fork's. --- docs/design/flash-next.md | 4 +- docs/research/basalt-cpu-q2.md | 283 +++++++++ runtime/CMakeLists.txt | 9 +- runtime/src/basalt_cpu.cpp | 393 ++++++++++++ runtime/src/basalt_cpu.h | 54 ++ runtime/src/native.mm | 76 +++ tests/kernels/basalt_cpu_emu.py | 220 +++++++ tests/kernels/test_basalt_cpu_q2.py | 924 ++++++++++++++++++++++++++++ third_party/NOTICE | 15 + 9 files changed, 1975 insertions(+), 3 deletions(-) create mode 100644 docs/research/basalt-cpu-q2.md create mode 100644 runtime/src/basalt_cpu.cpp create mode 100644 runtime/src/basalt_cpu.h create mode 100644 tests/kernels/basalt_cpu_emu.py create mode 100644 tests/kernels/test_basalt_cpu_q2.py diff --git a/docs/design/flash-next.md b/docs/design/flash-next.md index f124100c..1200f5cb 100644 --- a/docs/design/flash-next.md +++ b/docs/design/flash-next.md @@ -43,7 +43,7 @@ current code wherever the two differ. Paths under `runtime/` are this repository | 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; 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 | `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`, `:559`; `src/kernels/cpu/q2_avx2.cpp:37-62` | +| 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 | `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`, `: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` | @@ -446,7 +446,7 @@ same rule holds for any other ported kernel whose basalt tests end in a comparis | 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`) | 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`) | +| 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 | 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/runtime/CMakeLists.txt b/runtime/CMakeLists.txt index 1ec6f6ef..2e6b00a4 100644 --- a/runtime/CMakeLists.txt +++ b/runtime/CMakeLists.txt @@ -12,8 +12,15 @@ 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) 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. This file must never see -ffast-math, which is a different hazard: it substitutes +# FMAXNM for the kernel's 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. +set_source_files_properties(src/basalt_cpu.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..1ca4e09d --- /dev/null +++ b/runtime/src/basalt_cpu.cpp @@ -0,0 +1,393 @@ +// 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" + +#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 { + +/// 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 NaN PATH: x86's NaN rules, applied scalar and lane-exact ------------------------------------------------ +// +// Each helper selects the NaN by an explicit bit test, in the operand order of the instruction GCC emits at that +// site, and returns the indefinite for a NaN the operation itself created. No NEON NaN rule is consulted. + +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 and VSUBSS: SRC1's NaN if it has one, else SRC2's, each quieted ([S] Intel SDM Vol. 1 +/// Table 4-8; [M] ground-truth:134-136); a NaN the operation CREATES (inf * 0, inf - inf) 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); } + +/// 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; +} + +/// _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/native.mm b/runtime/src/native.mm index 026b2409..4531cb3c 100644 --- a/runtime/src/native.mm +++ b/runtime/src/native.mm @@ -1,15 +1,37 @@ // nanobind layer over metal_core: keeps Python free of Objective-C and the core free of Python. #include +#include #include #include #include #include +#include #include +#include +#include "basalt_cpu.h" #include "metal_core.h" namespace nb = nanobind; using namespace monolith; +// ---- basalt's two CPU Q2_0 kernels (basalt_cpu.h) ------------------------------------------------------------ +// Caller-owned numpy arrays, ActQ-shaped and C-contiguous: 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. +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); +} + NB_MODULE(_native, m) { m.doc() = "Metal runtime core (v0): device, buffers, runtime-compiled libraries, pipelines, timed dispatches"; @@ -94,4 +116,58 @@ .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"); } 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/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/third_party/NOTICE b/third_party/NOTICE index 842e92ee..d2fa11f1 100644 --- a/third_party/NOTICE +++ b/third_party/NOTICE @@ -113,6 +113,11 @@ Format: `` — adapted from / copied from `` `` @ 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`. ## basalt (jesdga95/basalt @ `b4c63b55754637f4c72ad53a0f791d425f71eb36`, MIT) @@ -228,6 +233,16 @@ Format: `` — adapted from / copied from `` `` @ `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 From bf9eec305e18d445824b8e895e7bc96f1116883a Mon Sep 17 00:00:00 2001 From: Lance Woodson <65194841+woodsonl@users.noreply.github.com> Date: Sun, 18 Oct 2026 20:07:52 -0500 Subject: [PATCH 67/74] Port basalt's CPU SwiGLU and glibc expf, held against its recorded x86 output The net change of woodsonl/mlxstream#24 (fork merge commit 50a6152), as one commit on the copy of woodsonl/mlxstream#21. The fork's native.mm also carries the host-step runtime, which this base lacks, so this commit keeps the base's lines there and adds exactly the PR's changed lines. --- docs/design/flash-next.md | 5 +- docs/research/basalt-cpu-expf.md | 128 + runtime/CMakeLists.txt | 14 +- runtime/src/basalt_cpu.cpp | 45 +- runtime/src/basalt_cpu_expf.cpp | 168 + runtime/src/basalt_cpu_expf.h | 26 + runtime/src/basalt_x86.h | 58 + runtime/src/native.mm | 68 +- tests/kernels/fixtures/expf_digests.txt | 4110 +++++++++++++++++++ tests/kernels/fixtures/swiglu_vectors.txt | 4235 ++++++++++++++++++++ tests/kernels/test_basalt_cpu_expf.py | 407 ++ third_party/ARM-OPTIMIZED-ROUTINES-LICENSE | 249 ++ third_party/NOTICE | 17 + 13 files changed, 9480 insertions(+), 50 deletions(-) create mode 100644 docs/research/basalt-cpu-expf.md create mode 100644 runtime/src/basalt_cpu_expf.cpp create mode 100644 runtime/src/basalt_cpu_expf.h create mode 100644 runtime/src/basalt_x86.h create mode 100644 tests/kernels/fixtures/expf_digests.txt create mode 100644 tests/kernels/fixtures/swiglu_vectors.txt create mode 100644 tests/kernels/test_basalt_cpu_expf.py create mode 100644 third_party/ARM-OPTIMIZED-ROUTINES-LICENSE diff --git a/docs/design/flash-next.md b/docs/design/flash-next.md index 1200f5cb..675cd0f4 100644 --- a/docs/design/flash-next.md +++ b/docs/design/flash-next.md @@ -43,7 +43,7 @@ current code wherever the two differ. Paths under `runtime/` are this repository | 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 | `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`, `:559`; `src/kernels/cpu/q2_avx2.cpp:37-62` | +| 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` | @@ -105,7 +105,8 @@ ones this pack runs. `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): which multiply-adds fuse and + 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 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/runtime/CMakeLists.txt b/runtime/CMakeLists.txt index 2e6b00a4..7a84058f 100644 --- a/runtime/CMakeLists.txt +++ b/runtime/CMakeLists.txt @@ -12,15 +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 src/basalt_cpu.cpp) +nanobind_add_module(_native NB_STATIC src/native.mm src/metal_core.mm src/basalt_cpu.cpp src/basalt_cpu_expf.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. This file must never see -ffast-math, which is a different hazard: it substitutes -# FMAXNM for the kernel's maxps selects [M], and FMAXNM returns the number where MAXPS returns its second operand, +# 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. -set_source_files_properties(src/basalt_cpu.cpp PROPERTIES COMPILE_FLAGS "-ffp-contract=off") +# +# 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 index 1ca4e09d..3b4e925d 100644 --- a/runtime/src/basalt_cpu.cpp +++ b/runtime/src/basalt_cpu.cpp @@ -116,6 +116,8 @@ // 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 @@ -129,6 +131,8 @@ 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 @@ -191,46 +195,7 @@ inline void group_scales(const uint8_t* row, int b0, int nb, float d[8]) { vst1q_f32(d + 4, vcvt_f32_f16(vreinterpret_f16_u16(vld1_u16(sc + 4)))); } -// ---- THE NaN PATH: x86's NaN rules, applied scalar and lane-exact ------------------------------------------------ -// -// Each helper selects the NaN by an explicit bit test, in the operand order of the instruction GCC emits at that -// site, and returns the indefinite for a NaN the operation itself created. No NEON NaN rule is consulted. - -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 and VSUBSS: SRC1's NaN if it has one, else SRC2's, each quieted ([S] Intel SDM Vol. 1 -/// Table 4-8; [M] ground-truth:134-136); a NaN the operation CREATES (inf * 0, inf - inf) 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); } - -/// 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; -} +// 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 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_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/native.mm b/runtime/src/native.mm index 4531cb3c..b646df04 100644 --- a/runtime/src/native.mm +++ b/runtime/src/native.mm @@ -9,15 +9,18 @@ #include #include #include "basalt_cpu.h" +#include "basalt_cpu_expf.h" #include "metal_core.h" namespace nb = nanobind; using namespace monolith; -// ---- basalt's two CPU Q2_0 kernels (basalt_cpu.h) ------------------------------------------------------------ -// Caller-owned numpy arrays, ActQ-shaped and C-contiguous: 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. +// ---- 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>; @@ -32,6 +35,14 @@ 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"; @@ -170,4 +181,53 @@ static void need(bool ok, const char* what) { }, 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. + 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/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/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/NOTICE b/third_party/NOTICE index d2fa11f1..807a6088 100644 --- a/third_party/NOTICE +++ b/third_party/NOTICE @@ -119,6 +119,16 @@ Format: `` — adapted from / copied from `` `` @ 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 @@ -219,6 +229,13 @@ Format: `` — adapted from / copied from `` `` @ - `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_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`, From 957b125c745ba4b83e634dd74078c60be7a182eb Mon Sep 17 00:00:00 2001 From: Lance Woodson <65194841+woodsonl@users.noreply.github.com> Date: Tue, 20 Oct 2026 15:03:59 -0500 Subject: [PATCH 68/74] Build basalt's int8 hyper-connection copies on the host The net change of woodsonl/mlxstream#28 (fork merge commit fa10916), as one commit on the copy of woodsonl/mlxstream#24. Five of its six files are byte-equal to the fork's merge; docs/design/flash-next.md carries the PR's changed lines and differs from the fork only where this base lacks the fork's later lines. --- docs/design/flash-next.md | 4 +- docs/research/basalt-nvcc/hc_fused.md | 510 ++++++++++++++++++++++++++ monolith/packs/basalt_hc8.py | 186 ++++++++++ tests/basalt_hc_ref.py | 100 +++++ tests/contract/test_basalt_hc8.py | 436 ++++++++++++++++++++++ third_party/NOTICE | 8 + 6 files changed, 1243 insertions(+), 1 deletion(-) create mode 100644 docs/research/basalt-nvcc/hc_fused.md create mode 100644 monolith/packs/basalt_hc8.py create mode 100644 tests/basalt_hc_ref.py create mode 100644 tests/contract/test_basalt_hc8.py diff --git a/docs/design/flash-next.md b/docs/design/flash-next.md index 675cd0f4..16340fa1 100644 --- a/docs/design/flash-next.md +++ b/docs/design/flash-next.md @@ -102,7 +102,8 @@ ones this pack runs. 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 + `docs/research/basalt-nvcc/` (`matvec.md` for the q8_1 quantizers and `native_mmvq`, `hc_fused.md` for the + hyper-connection read, its router and the int8 copies, `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 @@ -453,6 +454,7 @@ same rule holds for any other ported kernel whose basalt tests end in a comparis | `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 int8 hyper-connection copies, `hc8_quant_kernel` at load (`src/kernels/cuda/hc_fused.cu:1171-1197`; `src/program/generate.cpp:2319-2365`; `src/core/mtp.cpp:254-282`, `:488-503`) | `hc8_parity` prints the down copy's relative rms error (`src/kernels/hc8_parity.cpp:107-116`) and gates only reads of the copies | the codes and fp16 scales, made on the host (`monolith/packs/basalt_hc8.py`), byte for byte against a scalar transcription of `hc8_quant_kernel` (`tests/contract/test_basalt_hc8.py`): the contract's rule for quantizer codes, `if (g_blocks[i] != r_blocks[i]) ++byte_bad;` (`src/kernels/quantize_act_parity.cpp:100`) | | 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`) | diff --git a/docs/research/basalt-nvcc/hc_fused.md b/docs/research/basalt-nvcc/hc_fused.md new file mode 100644 index 00000000..e9f5ea9c --- /dev/null +++ b/docs/research/basalt-nvcc/hc_fused.md @@ -0,0 +1,510 @@ +# basalt's hyper-connection read as nvcc compiles it + +What NVIDIA's compiler emits at every rounding site of basalt's fused hyper-connection read (`hc_fused.cu`): the +load-time quantizer of the 8-bit copies (`hc8_quant_kernel`), and the items of the persistent `hc_fused_kernel`: the +down items (`cn_x`, `cn_dot`, `cn_lo`), the up items (`hc_up_pre`, `hc_up_main_mma8`) with the q8_1 rows they write +(`hc_q8_1_store_native`, `hc_up_q8`), the router items (`hc_router_rows`, `warp_sum16_ftz`, the IEEE `hc_q8_1_store`) +and the top-10 item (`hc_top10`), 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 `matvec.md` is for +the q8_1 quantizers and `bf16.md` for MMVF; `native_gr_postops.md` (not yet on main) covers the hyper-connection write. + +Basalt paths are relative to commit `b4c63b55754637f4c72ad53a0f791d425f71eb36`; `path:a-b` means lines a to b there, +and a bare `:N` is a line of `src/kernels/cuda/hc_fused.cu` unless another file was named last. + +## Method + +- **Sources.** `src/kernels/cuda/hc_fused.cu` with the quoted headers it includes (`include/basalt/core/diag.hpp`, + `include/basalt/kernels/hc_fused.hpp`, `pdl.hpp`, `q8_1_finite.hpp`), inlined recursively under `#line` + directives; system and CUDA headers stay `#include`s. Only basalt's public MIT source was sent. +- **Compiler.** Compiler Explorer's public API, `POST https://godbolt.org/api/compiler/nvcc130/compile` with + `"compilerOptions": {"produceDevice": true}` and `"filters": {}`: compiler id `nvcc130`, NVCC 13.0.0, version string + `Cuda compilation tools, release 13.0, V13.0.48`, which returns the PTX and the `SASS (sm_120)` listing. Compiled + October 18, 2026. Basalt requires CUDA 13 (`CMakeLists.txt:32-33`). +- **Flags.** `hc_fused.cu` joins the `kernels` target at `CMakeLists.txt:169` and is **not** in the `--use_fast_math` + list (`:185-202`), so it builds with nvcc's IEEE defaults (`-ftz=false -prec-div=true -prec-sqrt=true -fmad=true`). + Global settings: a Release build, `-O3 -DNDEBUG` (`:12-14`), `BASALT_VERSION` (`:7`), architecture 120 only + (`:3-5`, `:26-31`); basalt sets no `CMAKE_CUDA_FLAGS`, no `-lineinfo`, no `-fmad` or `-prec-*` option. The exact + `userArguments` sent: `-arch=sm_120 -lineinfo -O3 -DNDEBUG -DBASALT_VERSION="0.0.1"` (Compiler Explorer passed the + macro on as `-DBASALT_VERSION=0.0.1`; nothing in this translation unit reads it). `-arch=sm_120` is basalt's target + (`compute_120` PTX and `sm_120` SASS); `-lineinfo` attributes every PTX and SASS instruction to a basalt file and + line, which is how each site below is found. Compiler Explorer adds `-g -lineinfo --keep-device-functions -c + -keep` (the response's `compilationOptions`): `-g` is host debug information, and `--keep-device-functions` also + emits stand-alone copies of the external-linkage device functions (`q8_1_finite.hpp`'s three) beside the kernels, + which it leaves unchanged. +- **Translation units.** Compiler Explorer's SASS listing stops at about 5,000 lines (`[truncated; too many lines]`), + and the whole `hc_fused_kernel` is longer, so the kernel is compiled in units, each `hc_fused.cu` with the host part + (`:1110-1489`) blanked and a table that takes the address of one instantiation `hc_fused_kernel`. + Blanked lines stay empty, so every source line keeps its number. Unit `down` also blanks the calls of the up, top-10 + and router items (`:1001`, `:1023-1024`, `:1026-1027`, `:1035-1038`, `:1044-1046`, `:1061-1062`, `:1064-1068`); + unit `up` blanks the down items' calls (`:989-991`) and those of the top-10 and router items; unit `rt` blanks the + down and up items' calls (`:989-991`, `:1001`, `:1023-1024`, `:1026-1027`). Unit `quant` keeps `hc8_quant_kernel` + (`:1167-1197`) and `hc8_dequant_bf16_kernel` (`:1229-1244`) and blanks everything else after `:1109`. `T` = 1 for + every unit; `T` = 2, 5 and 8 for `down`, `up` and `rt`, and `T` = 3 for `down` and `rt` (section 9). + `DBG = true` (`kKernels[1]`, `:1111-1115`) is the bench's instantiation (`:213`): it adds the timestamp stores of + `stamp` (`:214-222`) and the phase markers `dbg[b * 16 + 15]`, no arithmetic, and is not recorded. +- **Unit check.** One more compile holds the whole kernel (`hc_fused_kernel<1, false>` and `hc8_quant_kernel`): its + SASS is truncated, its PTX complete. Per `hc_fused.cu` line and PTX floating-point opcode, the counts in the whole + kernel equal the sum of the counts in the units `down`, `up`, `rt` and `quant`, at every line; the one excess in the + units is `q8_1_finite.hpp:19`, three instructions per opcode, which is the stand-alone copy of `q8_1_finite.hpp` that + `--keep-device-functions` emits once per compile. So blanking the other items changes no item's arithmetic, and the + units' SASS stands for the kernel's. +- **Listings.** A row number (`up.sass.txt` rows 1899-1962) is the position, from 1, of an instruction in the `asm` + list of the response's `SASS (sm_120)` device, whose first entry is the kernel's label; every entry carries its + file and line. `down.sass.txt`, `up.sass.txt`, `rt.sass.txt` and `quant.sass.txt` name the units at T = 1 unless the + row names another T. The requests and responses are kept outside the repository; each unit's source is + `hc_fused.cu` at the commit with the lines above blanked, followed by the two closing braces of its namespaces and + the table `void* hc_nvcc_table[] = {(void*) basalt::kernels::hc_fused_kernel};` (for `quant`, the + addresses of `hc8_quant_kernel` and `hc8_dequant_bf16_kernel`), so this Method rebuilds every request. +- **Reading a site.** The PTX shows what the front end fused (`fma.rn.f32`), the division it chose (`div.rn.f32`, or + the source's own `div.approx.ftz.f32` and the `.ftz` instructions of the inline-asm helpers `:81-85`, `:271-305`) + and each conversion; the SASS shows what `ptxas` made of it. The tables cite the SASS, the ground truth. + +## Notation + +- `matvec.md`'s: 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); **.FTZ** (`.ftz`): subnormal inputs and results flushed to the zero of + their sign. "IEEE" marks an instruction without `.FTZ`: on sm_120 it reads and writes subnormals. +- Metal forms use `kernels/common/basalt_fp.metal`: `ftz`, `add_ftz`, `mul_ftz` (`fma_ftz(a, b, -0)`), `fma_ftz`, + `max_ftz`, `abs_ftz`, `rcp_ftz` (`ftz(1.0f / ftz(x))`, where SASS has `MUFU.RCP`), `warp_sum_ftz`, `warp_max_ftz`, + `warp_sum` (the plain-add butterfly), `expf_neg`, `expf_ftz`, `h2f`, `f16_bits`, `cuda_nan`, `cuda_nan_f16`; and + `kernels/common/basalt_q8_1.metal`: `q8_1_finite`, `q8_1_code`, `q8_1_put`, `q8_1_store_native`, `q8_1_store_ieee` + and the IEEE helpers `ieee_up64`, `ieee_add`, `ieee_mul`, `ieee_div`, `ieee_div127`, `ieee_rcp`, `ieee_fma`, + `warp_sum_ieee` (`ieee_add` and `ieee_mul` move to `basalt_ieee.metal` with the sampler unit). Every Metal source of + the port starts with `#pragma STDC FP_CONTRACT OFF`, so only an explicit `fma()` fuses. +- This GPU (M3 Max, `MTLMathModeSafe`) flushes its arithmetic, not its moves: `+`, `-`, `*`, `/`, `fma` read a + subnormal as zero and write a subnormal result as zero, compares read a subnormal as zero, `fmax`/`fmin` return the + chosen operand's original bits (`matvec.md`, Notation). At an IEEE site of this file a subnormal operand or result is + therefore a difference unless the row shows it cannot occur or cannot reach the output. + +## Summary + +| Function | Rounding sequence nvcc 13.0 emits (sm_120) | Metal | +|---|---|---| +| `hc8_quant_kernel` (section 1) | per 32 values amax = max(\|x\|) from 0 in order (`FMNMX`); s = h(fp16(amax / 127)) with `div.rn`; q = clamp(rint(x / s), −127, 127) with `div.rn`, 0 when s = 0; all IEEE | `fmax`, `/`, `half`, `rint`, `clamp`: CUDA's codes and scales (where Metal flushes a subnormal, the code or scale is 0 on both) | +| `cn_x` (section 2) | q = inj · −0.25 (exact); e = ex2(fl(q · L)) (the non-`.ftz` `ex2.approx`); g = 1 / fl(1 + e) (`rcp.rn`); gw = g + g; R' = fma(bo, gw, R) when `apply`; x = fl(R' · w); per slot q = fma(w, w, fma(z, z, fma(x, x, fl(y · y)))), sq = (+0 + q0) + q1, the XOR butterfly, the eight warps from +0; all IEEE | `expf_neg`, `ieee_div(1.0f, 1.0f + e)`, `ieee_add(g, g)`, `fma`, `ieee_mul`, `warp_sum` (`warp_sum_ieee`), `ieee_add` | +| `cn_dot`, `warp_sum16` (section 3) | int8 to fp32 exact; per chunk of eight d = fma chain from +0, w0.x to w1.w; acc = fma(h(sc), d, acc) per chunk, chunks ascending from +0; per value the XOR tree, 16 values per round; all IEEE | `float(char(b))`, `fma` (`ieee_fma` where x or a partial is below 2^-100), `warp_sum` per value | +| `cn_lo` (section 4) | rs = rsqrt(fl(s0 + s1) / 2560 + eps) (`div.rn`, the non-`.ftz` `MUFU.RSQ`); v = fma(rs_c, p_2c + p_2c+1, v) over c from +0; x = fl(v · 0.25); lo = x / (1 + ex2(fl(x · −L))) (`div.rn`); inject_out the same chain over `w_inject`'s rows; all IEEE | `ieee_add`, `/`, `fast::rsqrt`, `fma`, `ieee_mul`, `expf_neg`, `ieee_div` | +| `hc_up_pre` (section 5) | section 2's R' on the item's columns; px = fl(R' · w) | as section 2 | +| `hc_up_main_mma8` (section 5) | int8 to fp16 exact; hi = fp16(x), lo = fp16(x − h(hi)) (RNE); per scale group and half two `HMMA.16816.F32` (hi, lo), each chained through C over the group's two halves from 0; acc = fma(h(sc), gh + gl, acc) over groups from +0; g = fl(fl(px · rs) · rcp(1 + ex2(fl(acc · −L)))); mixed = fl(((((+0 + g0) + g1) + g2) + g3) · 0.25); all IEEE | `half`, a scalar sum per block (section 5), `fma`, `expf_neg`, `ieee_div`, `ieee_mul`, `ieee_add` | +| `hc_q8_1_store_native` (section 6) | `native_quantize_q8_1`'s sequence (`matvec.md` section 1) with \|x\|, max and sum IEEE: d = amax · fl(1/127) (`FMUL.FTZ`, the asm `div.approx.ftz` strength-reduced), code = clamp(roundf(xi · `MUFU.RCP`(d))) (`FMUL.FTZ`) | `q8_1_store_native` with `warp_sum_ieee` for the sum | +| `hc_q8_1_store` (section 6) | `quantize_q8_1_kernel`'s IEEE sequence (`matvec.md` section 3): `div.rn` for both divisions | `q8_1_store_ieee` unchanged | +| `hc_router_rows`, `warp_sum16_ftz` (section 7) | per (row, token) ten `FFMA.FTZ` from +0 over the pairs t + 256 j; per value the warp's XOR tree (`FADD.FTZ`), then the tree over the eight warp sums and 24 zeros: `bf16_f32_mmvf_multi_kernel<256, *>`'s value | `basalt_mmvf` (`BLOCK` 256): `fma_ftz`, `warp_sum_ftz` | +| `hc_top10` (section 8) | m = `max_ftz` chain from −inf, `warp_max_ftz`; e = ex2(fl(fl(v − m) · L)); sum `add_ftz` from +0, `warp_sum_ftz`; p = fl(e · `MUFU.RCP`(sum)), NaN to −FLT_MAX; the selection by (p descending, expert ascending), IEEE compares; weight = fl(top_v · `MUFU.RCP`(max(Σ, 2^-14))); every arithmetic instruction `.FTZ` | `max_ftz`, `warp_max_ftz`, `expf_ftz`, `add_ftz`, `warp_sum_ftz`, `rcp_ftz`, `mul_ftz`, the same compares and shuffles | + +**Flags and fusion.** The file's PTX carries `.ftz` only in its inline-asm helpers: the router's and the top-10's +`fma`, `add`, `sub`, `mul`, `max`, `ex2.approx` and `rcp.approx` (`:271-305`) and the native q8_1 rows' `div.approx` +(`:81-85`). Everything else is nvcc's IEEE default: subnormals kept, `div.rn.f32` and `rcp.rn.f32` correctly rounded +(a Newton step on `MUFU.RCP`, a slow-path subroutine for the extreme exponents), `ex2.approx.f32` and +`rsqrt.approx.f32` in their non-`.ftz` forms, which scale a subnormal argument or result around `MUFU.EX2` and +`MUFU.RSQ`. The front end contracts once, the sum of squares (`:446`); every other `fma` is the source's `fmaf` or an +asm `fma.rn.ftz`, and the divisions by HC = 4 (`:435` and `:616` with the sigmoid's negation, `:537`, `:717`) are +exact multiplies by ±0.25 in the PTX. Past the PTX `ptxas` fuses once, `hc8_quant_kernel`'s error sums (`:1188`, +which the port does not need), and strength-reduces once, the asm division by 127 in `hc_q8_1_store_native` (a +`FMUL.FTZ` by fl(1/127)), at every compiled T (section 9). + +**Exactness per output.** With the Metal forms above, each output given its inputs either has CUDA's bits or carries +an operation whose bits Metal does not reproduce: an approximate instruction, which the contract maps (invariant 5), +or the tensor-core sum. + +| Output | Given | CUDA's bits on Metal | Except through | +|---|---|---|---| +| the int8 copies' codes and scales | the BF16 matrices | yes | | +| `R_out` | R, `bo_prev`, `inj_prev` | without `apply` (a copy of R) | with `apply`, the stream gate's `MUFU.EX2` (`:341`) | +| `rs` | R' | no | `MUFU.RSQ` (`:526`) | +| `lo`, `inject_out` | R', `w_norm`, the down and inject copies | no | rs; for lo also the SiLU's `MUFU.EX2` (`:538`) | +| `mixed` | lo, rs, R', `w_norm`, the up copy | no | lo, rs, the `HMMA` block sums (section 5), the gate's `MUFU.EX2` (`:707`) | +| the q8_1 rows of the router read | `mixed` | yes (`q8_1_store_ieee`) | | +| the q8_1 rows of the other reads | `mixed` | where `MUFU.RCP(d)` is the correctly rounded reciprocal | `MUFU.RCP` (`:84`): a code can move by one at a .5 boundary (`matvec.md` section 1) | +| the logits | `mixed` | yes (`basalt_mmvf`) | | +| the probabilities | the logits | no | `MUFU.EX2` per logit (`:298`), `MUFU.RCP` of the sum (`:303`) | +| the ten ids | the probabilities | yes | | +| the ten weights | the probabilities, the ids | where `MUFU.RCP` of the normalizer is correctly rounded | `MUFU.RCP` (`:303`) | + +Inside the read, the dot products of the down items given R' and the sums of squares are CUDA's bits too, except at +the subnormal sites below, which feed only rs, lo, `inject_out`, `mixed` and the `R_out` of `apply`, outputs that +already carry an approximate instruction. Each Metal form is a per-token sequence that the window width and the +token's column do not change (section 9), so a port that keeps them meets the window checks of `hc_fused_parity` +(`src/kernels/hc_fused_parity.cpp:328`, `:356-361`) on every output. + +**Open gaps.** + +- The `HMMA` block sums (section 5). MSL has no instruction with their sum, and the PTX ISA leaves it unspecified. + The SASS fixes the operands, the chaining through C, the k positions and the scalar code around the blocks; which + scalar sum stands for each block, an fp32 `fma` chain in a fixed k order or a model of the sm_120 tensor core's + summation, is the contract's decision (invariant 5). +- A general IEEE fp32 `fma`. This GPU's `fma` flushes, and `basalt_q8_1.metal` has no IEEE fma with a non-integer + multiplier (`ieee_fma` takes an integer one). The sites are R' (`:443-444`, `:616`), the squares (`:446`), the scale + fma of the dot products (`:489`) and the rs chains (`:536`, `:550`); each differs from CUDA only where an operand, a + partial or the exact result is below 2^-126 in magnitude. The sampler unit's software binary64 (not yet on main) + gives the correctly rounded fp32 fma, `f32_from_f64(f64_fma_odd(...))` of the widened operands + (`kernels/common/basalt_f64.metal:16-19`), for a slow path taken only at such operands. +- The approximate instructions: `MUFU.EX2` (`:298`, `:341`, `:538`), `MUFU.RSQ` (`:526`) and the `MUFU.RCP` of + `rcp.approx.ftz` and `div.approx.ftz` (`:84`, `:303`) take the contract's mappings, `fast::exp2` of the same + product, `fast::rsqrt` and the correctly rounded reciprocal. Neither vendor documents those instructions' exact + results, so the port claims no CUDA bits through them, and their tests carry tolerances. + +**Two kinds of q8_1 row on decode.** Decode's first read of a layer, without the router, writes +`hc_q8_1_store_native`'s rows, and its second read, with the router, `hc_q8_1_store`'s IEEE rows (section 6); the +drafter's attention and mixer reads write native rows. The contract's no-reference row "The q8_1 rows the fused read +writes for the projections" (`docs/design/flash-next.md`) names only the native arithmetic (`hc_fused.cu:80-101`) and +`iq_multi_parity`'s rule for it, which accepts the scale within one fp16 step and each code within one (`near`, +`src/kernels/iq_multi_parity.cpp:465-466`). The router read's rows are `quantize_q8_1_kernel`'s arithmetic, which the +same test holds to the host formula bit for bit (`std::memcmp(want, g, 36) == 0`, `:467`, its path 0, +`quantize_q8_1_rows`, `:479`), so a test of the rows needs both rules. + +## 1. `hc8_quant_kernel` (`hc_fused.cu:1171-1197`) + +The load-time quantizer of the 8-bit copies, launched once per bf16 matrix by `hc8_make` (`:1210-1227`) with +`err = nullptr` (`:1224`). One thread per group of `G8` = 32 consecutive values (`:343`). IEEE-built: no `.FTZ` +anywhere in the kernel's arithmetic. + +| Site | basalt | SASS (13.0, `quant.sass.txt` rows 216-2080) | Metal | +|---|---|---|---| +| x | `:1178` `__uint_as_float((uint32_t) w[...] << 16)` | `IMAD.U32 R, R, 0x10000, RZ` (integer shift) | `as_type(uint(w) << 16)` (exact; bf16 subnormals stay subnormal bits) | +| amax | `:1179` `fmaxf(amax, fabsf(x[i]))`, i = 0..31 from `0.0f` | 32 × `FMNMX R, R, \|x\|, !PT` (max, no `.FTZ`), a chain in i order | `fmax(amax, fabs(x))` in the same order: Metal's compare reads a subnormal as zero, so it can pick a different operand only when no value of the group is normal, and then both scales below are +0; NaN is skipped by both | +| amax / 127 | `:1181` | `FCHK P0, amax, 127`; `FFMA q0 = amax·c + 0`; `FFMA r = q0·(−127) + amax`; `FFMA q = r·c + q0` with c = `UFFMA(UFFMA(r0, −127, 1), r0, r0)`, r0 = `0x3C010204` = fl(1/127); slow path `__cuda_sm3x_div_rn_noftz_f32_slowpath` when `FCHK` flags | `amax / 127.0f`: `div.rn.f32`, correctly rounded with subnormals; Metal's `/` is correctly rounded (measured) and flushes, which matters only for amax < 127·2^-126, where both scales are +0 | +| h, s | `:1181-1182` `__float2half_rn`, `__half2float` | `F2FP.F16.F32.PACK_AB R31, RZ, R31` (RNE); `HADD2.F32 R41, -RZ, R31.H0_H0` (exact) | `half(q)`, `float(h)`; the double rounding fp32 then fp16 is CUDA's too | +| s > 0 | `:1185` | `FSETP.GT.AND P2, PT, s, RZ` (hoisted out of the loop) | `s > 0.0f` (s is a half value, never an fp32 subnormal) | +| x / s | `:1185` | per value: `MUFU.RCP r0, s`; `FCHK P0, x, s`; `FFMA e = −s·r0 + 1`; `FFMA r1 = r0·e + r0`; `FFMA q0 = x·r1 + 0`; `FFMA rem = −s·q0 + x`; `FFMA q = r1·rem + q0`; the slow path when flagged | `x / s`: correctly rounded on both; a subnormal x (or quotient) is kept by CUDA and flushed by Metal, and rounds to a ±0 code on both | +| `rintf`, clamp | `:1185` `fminf(fmaxf(rintf(q), -127.0f), 127.0f)` | `FRND R, R` (round to nearest even); `FMNMX R, R, -127, !PT`; `FMNMX R, R, 127, PT` | `clamp(rint(q), -127.0f, 127.0f)`; `rint` rounds half to even (measured); a NaN q (x = ±inf with s = inf) becomes −127 on both (`fmaxf` returns the other operand) | +| code | `:1186` `(int8_t) v` | `F2I.TRUNC.NTZ R, R` | `char(v)` (v is an integer in [−127, 127]) | +| err sums | `:1187-1188` | `FFMA R45 = s·v − x`: the PTX keeps `v * s - x[i]` as `mul.f32` and `sub.f32` (no rounding modifier, 32 of each), and `ptxas` fuses each pair into one `FFMA`, the file's one fusion past the PTX; `F2F.F64.F32`, `DMUL`, `DFMA`; the butterfly `DADD` ×10 (`:1194`) | not ported: `hc8_make` passes `err = nullptr`; were it ported, e[1] uses fma(s, v, −x), not fl(fl(v·s) − x) | + +`hc8_dequant_bf16_kernel` (`:1229-1244`), which `hc8_dequant_bf16` (`:1328-1333`) launches for `hc8_parity` +(`src/kernels/hc8_parity.cpp:103-105`, `:325`) and for `Gemm::bf16_w` (`src/prefill/gemm.cu:136`, `:150`), the +prompt path's products on a matrix held only as its copy: `I2F.S8` / `I2FP.F32.S32` (exact), +`HADD2.F32 R8, -RZ, R8.H0_H0` (the scale), `FMUL R, s, f(v)` (no `.FTZ`), then `F2FP.BF16.F32.PACK_AB` (round to +nearest even). For a finite scale the product is 0 or at least 2^-24 in magnitude, never subnormal, so Metal's +`bfloat(s * float(v))` gives the same bits. An inf scale (absmax above 127 · 65504, codes 0) makes it 0 · inf = NaN, +`FMUL`'s 0x7fffffff (sm_120 [H]) and Metal's 0x7fc00000 (`nan.md`'s `mul.f32` row); `nan.md` has no row for a +NaN's BF16 conversion, so that group's stored BF16 is not claimed to be CUDA's. + +## 2. `cn_x` (`:415-460`) + +The down items' prologue (`:989`): the half-stream's x = R' · w_norm into shared memory, R' = R + bo_prev · gw when +`apply` (the previous half's write folded in), and for the first row group (`ss`) the half-stream's sum of R'^2 per +token. One thread holds float4 slot j = 0 (elements 4·tid) and, for tid < 64, slot j = 1 (4·(256 + tid)); the float4 +loads land in register quads, `R16..R19` = R (x, y, z, w), `R20..R23` = bo_prev, `R24..R27` = w_norm (rows 357-363). +No instruction carries `.FTZ` except the Newton step's internal negation. + +| Site | basalt | SASS (13.0, `down.sass.txt` rows 364-463) | Metal | +|---|---|---|---| +| inj / HC, negated | `:435` `a.inj_prev[k * HC + c] / (float) HC`, `:341` `-x` | `FMUL R49, R66, -0.25` (PTX `mul.f32 %f70, %f69, 0fBE800000`: the front end folds the division by 4 and the negation into one multiply, which is exact: x / 4 and x · 0.25 round the same real once, subnormal results included) | `q = inj * -0.25f`: a subnormal q (\|inj\| < 2^-124) is flushed by Metal, and e below is 1 on both | +| `__expf(-x)` | `:341` | `FMUL R49, R49, 1.4426950216293334961` (no `.FTZ`); `FSETP.GEU.AND P0, PT, R49, -126, PT`; `@!P0 FMUL R49, R49, 0.5`; `MUFU.EX2 R51, R49`; `@!P0 FMUL R51, R51, R51`: the non-ftz `ex2.approx.f32` (halve, `MUFU.EX2`, square below −126) | `e = expf_neg(inj * 0.25f)` (basalt_fp.metal:104, `fast::exp2` of fl(x · −L), the same bits as fl(q · L): rounding is symmetric in sign). Below −126 CUDA's e is subnormal and Metal's may be +0: 1 + e = 1 on both | +| `1.0f + e` | `:341` | `FADD R68, R51, 1` | `1.0f + e` (e ≥ +0) | +| `1.0f / (...)` | `:341` | `rcp.rn.f32`: the guard `IADD3 R51, R68, 0x1800000`; `LOP3.LUT R51, R51, 0x7f800000`; `ISETP.GT.U32.AND P0, PT, R51, 0x1ffffff`, then `MUFU.RCP R49, R68`; `FFMA R51, R68, R49, -1`; `FADD.FTZ R66, -R51, -RZ`; `FFMA R49, R49, R66, R49`, or `CALL __cuda_sm20_rcp_rn_f32_slowpath` for a biased exponent of 0, 253, 254 or 255: correctly rounded, subnormal results kept | `g = ieee_div(1.0f, 1.0f + e)` (basalt_q8_1.metal:181, for b ≥ 1, infinite or NaN). Metal's `1.0f / b` gives the same bits except for 1 + e in [2^126, 2^128), inj / HC in about (−88.72, −87.34], where CUDA's quotient is subnormal and Metal flushes it. Not `ieee_rcp`: it covers \|s\| ≤ 2^126 only | +| `2.0f * s` | `:435` | `FADD R49, R49, R49` (2 s as s + s, the same bits); `HFMA2 R49, -RZ, RZ, 0, 0` (gw = +0) when not `apply` | `gw = ieee_add(g, g)` (`g + g` unless g is subnormal) | +| R' | `:443-444` `fmaf(bb[k][j].x, gw, v.x)` ... | `@P1 FFMA R17, R49, R21, R17` ... (gw · bo + R, P1 = `apply`; not executed otherwise, so R is kept as is, −0 included) | `if (apply) v = fma(bo, gw, v)` (the product commutes). An IEEE FFMA: Metal's `fma` differs when bo, gw, R or the exact result is below 2^-126 in magnitude; the tree has no IEEE fma for a general multiplier (`ieee_fma` takes an integer one) | +| x | `:447` `v.x * g[j].x` ... | `FMUL R24, R24, R16`, `FMUL R25, R25, R17`, ... (R' · w_norm, IEEE) | `v * w` (`ieee_mul`, basalt_q8_1.metal:108, where a subnormal operand or product can occur) | +| squares | `:446` `sq += v.x * v.x + v.y * v.y + v.z * v.z + v.w * v.w` | slot 0: `FMUL R21, R17, R17` (y · y); `FFMA R21, R16, R16, R21` (x · x + it); `FFMA R16, R18, R18, R21` (z); `FFMA R16, R19, R19, R16` (w); `FADD R16, RZ, R16` (+0 + q). Slot 1 (tid < 64): the same four on `R12..R15`, then `FADD R16, R16, R15`. The front end contracted (PTX `mul.f32`, then `fma.rn.f32` ×3): the first product fused, the second rounded | `q = fma(v.w, v.w, fma(v.z, v.z, fma(v.x, v.x, v.y * v.y)))`; `sq = 0.0f + q0`, then `sq = sq + q1`. A subnormal square or partial (all four values below about 2^-63) differs | +| warp sum | `:450` `warp_sum(sq)` (`:319-323`) | `SHFL.BFLY PT, R5, R16, 0x10, 0x1f`; `FADD R5, R5, R16`; then 0x8, 0x4, 0x2, 0x1, each `SHFL.BFLY` then `FADD` (IEEE) | `warp_sum` (basalt_fp.metal:97, the same XOR order); `warp_sum_ieee` (basalt_q8_1.metal:206) where a subnormal partial can occur | +| cns | `:457` `s += part[tid * WARPS + w]` from `0.0f` | `FADD R12, RZ, R12` (0 + p0), then `FADD` ×7 in warp order p1..p7 (rows 456-463) | `s = 0.0f; for w in 0..7: s = s + part[w]` (`ieee_add` where a subnormal can occur) | + +The sum of squares of a half-stream is thus a fixed function of its 1280 values of R': per thread its one or two +contracted quads added onto +0 in slot order, per warp the XOR butterfly, then the eight warps in order from +0. The +partition is the thread's slots, not T: the per-T compiles repeat the sequence per token (section 9). + +## 3. `cn_dot` and `warp_sum16` (`:463-505`, `:328-339`) + +Warp w takes rows 4w..4w+3 of the item (w_down's 32 rows of a row group, or w_inject's 4); lane L takes the chunks +j = L + 32q, q = 0..4 ascending, of eight elements each (x0 = floats 0-3 of the chunk, x1 = floats 4-7, `:479-480`). +Per (row, token) the lane forms each chunk's eight-term dot product with `dot8ff` and adds it, scaled by the chunk's +group scale, into its accumulator; the 4T accumulators are then reduced over the warp 16 at a time. + +| Site | basalt | SASS (13.0, `down.sass.txt` rows 477-1145) | Metal | +|---|---|---|---| +| int8 to float | `:346-352` `i8x4_f`: `__byte_perm(u, 0x4B000000u, 0x765k)` less `8388736.0f` | `LOP3.LUT` (u = q ^ 0x80808080), `PRMT`, `FADD R, R, -8388736` per value (2^23 + (q + 128) − (2^23 + 128) = q, exact); `HFMA2 R20, -RZ, RZ, 14, 0` only materializes the constant 0x4B000000 | `float(char(b))` (exact; any exact conversion gives these bits) | +| scale | `:487` `h2f(...)` | `HADD2.F32 R10, -RZ, R5.H0_H0` (fp16 to fp32, exact) | `h2f` (basalt_fp.metal:110) | +| chunk dot | `:360-371` `dot8ff`: `acc = fmaf(w0.x, x0.x, acc)` ... from `0.0f`, w0.x..w0.w then w1.x..w1.w | `FFMA R22, R12, R21, RZ`; `FFMA R23, R13, R16, R22`; `FFMA R18, R14, R21, R23`; `FFMA R23, R15, R16, R18`; then x1's four (`FFMA R22, R4, R19, R23` ...): eight chained FFMA, the first adding +0 (rows 491-524 for the first chunk of row 0) | `d = fma(w0.x, x0.x, 0.0f); d = fma(w0.y, x0.y, d); ...` in the source order (the +0 addend makes a −0 first product +0). The weight is an integer, so `ieee_fma(x, w, d)` (basalt_q8_1.metal:167) is exact where an x or a partial may be below 2^-100 | +| accumulate | `:489` `acc[r * T + k] = fmaf(sc, dot8ff(...), acc[r * T + k])` from `0.0f` (`:472`) | 20 `FFMA` for T = 1 (4 rows × 5 chunks): q = 0 adds `RZ` (`FFMA R21, R6, R21, RZ`, row 648), q = 1..4 chain onto it (rows 664, 817, 926, 1079 for row 0) | `acc = fma(sc, d, acc)` per chunk, q ascending from `0.0f`: one scale fma per chunk of eight, not per group of 32. A general IEEE fma (sc ≥ 2^-24 or 0; d or acc below 2^-126) has no helper in the tree | +| reduction | `:497-498` `warp_sum16(v, lane)` (16 values per round, `v[i] = 0` past 4T) | per halving step o = 16, 8, 4, 2: `FSEL`/`SEL` pick keep and send on the lane bit (`!P4`, `!P3`, `!P2`, `!P1`), `SHFL.BFLY` by o, `FADD keep, received`; then `SHFL.BFLY ... 0x1` and `FADD R9, R8, R9` (row 1145). The padded slots compile to `MOV R17, RZ` / `CS2R R18, SRZ` and `FADD R17, RZ, R17` (0 + 0): a real partial only ever meets the same index's partial from the partner lane | `warp_sum` per value (basalt_fp.metal:97): each total is formed over warp_sum's pairs in warp_sum's tree, and a + b = b + a, so it has warp_sum's bits (`:324-327`); `warp_sum_ieee` where a subnormal partial can occur | +| store | `:500-502` lanes 2m, m < 4T: r = m / T, k = m − rT | `@P5 STG.E` of the final sum | `cnp[(k · 8 + hs) · 324 + row0 + 4w + r] = s` | + +For T = 1 the 4 values of the round are rows r = 0..3 of token 0; T = 2 fills 8 slots of one round and T = 8 two +rounds of 16 (row, token) pairs, and the per-value tree is the same (section 9), so a dot product depends neither on +T nor on the token's column of the window. + +## 4. `cn_lo` (`:506-555`) + +The up item's prologue (`hc_up_main_mma8`, `:658`): from the down items' dot products `cnp` and sums of squares +`cns` it forms each stream's rs, lo = SiLU(Σ_c rs_c · (dot_2c + dot_2c+1) / HC) and, for the item that writes the +read's outputs (`out`), rs, lo and inject_out. For T = 1 a thread takes lo rows idx = tid and, for tid < 64, +idx = tid + 256 (`NI` = 2, `:511`); threads tid < T · HC form one rs each (`:523-527`). Every arithmetic instruction +here comes from the source's own operators and `fmaf`: the PTX has `add.f32`, `div.rn.f32`, `rsqrt.approx.f32`, +`fma.rn.f32`, `mul.f32` and `ex2.approx.f32`, none with `.ftz`, and no contraction. + +| Site | basalt | SASS (13.0, `up.sass.txt` rows 731-891) | Metal | +|---|---|---|---| +| s | `:525` `ld(cns + k * CN_HS + 2 * c) + ld(cns + k * CN_HS + 2 * c + 1)` | `FADD R16, R17, R16` (row 742, IEEE) | `s = s0 + s1` (`ieee_add` where a half-stream's sum of squares can be subnormal, which needs every R' value of it below 2^-63) | +| s / N | `:526` `s / (float) N` | `div.rn.f32` by 2560: `UFFMA UR5, UR6, -UR5, 1` and `UFFMA UR5, UR5, UR6, 0.000390625...` refine r0 = `0x39cccccd` = fl(1/2560) to c = fma(fma(r0, −2560, 1), r0, r0) (rows 737-741); `FCHK P0, R16, 2560`; `FFMA R17 = s·c + 0`; `FFMA R8 = R17·(−2560) + s`; `FFMA R8 = R8·c + R17` (rows 743-746); `CALL __cuda_sm3x_div_rn_noftz_f32_slowpath` when `FCHK` flags (row 750). Correctly rounded, subnormal quotients kept | `s / 2560.0f`: Metal's division is correctly rounded (measured); it flushes a quotient below 2^-126, which the add below turns into eps on both | +| + eps | `:526` `+ a.eps` | `FADD R8, R8, UR5` (row 756, IEEE; eps = 1e-6f at every call, `src/core/verify.cpp:1135`, `:1147`, `include/basalt/kernels/hc_fused.hpp:37`) | `u = q + eps`: half an ulp of 1e-6 is 2^-44, so a quotient below 2^-126 leaves eps on both | +| `rsqrtf` | `:526` | `FSETP.GEU.AND P0, PT, \|R8\|, 1.175494350822287508e-38, PT`; `@!P0 FMUL R8, R8, 16777216`; `MUFU.RSQ R13, R8`; `@!P0 FMUL R13, R13, 4096` (rows 757-760): `rsqrt.approx.f32` without `.ftz` (a subnormal input scaled by 2^24 and the result by 2^12) | `rs = fast::rsqrt(u)` (`docs/design/flash-next.md`, invariant 5): u ≥ 1e-6 is normal, so only `MUFU.RSQ` acts. `MUFU.RSQ` is approximate and unspecified bit for bit, so the last bits may differ from CUDA's; the one helper at every site keeps invariant 1 | +| pair sums | `:536` `p[i][2 * c] + p[i][2 * c + 1]`, c = 0..3 | `FADD R39, R39, R38`; `FADD R37, R37, R36`; `FADD R34, R34, R35`; `FADD R33, R32, R33` (rows 768-771) | `p0 + p1` per c (`ieee_add` where a subnormal dot product can occur) | +| v | `:536` `v = fmaf(rs_s[k * HC + c], ..., v)` from `0.0f`, c ascending | `FFMA R16, R12, R39, RZ` (rs0 · pair0 + +0, rs from `LDS.128 R12`, row 775); `FFMA R37, R37, R13, R16`; `FFMA R34, R34, R14, R37`; `FFMA R16, R33, R15, R34` (rows 776-779) | `v = fma(rs0, q0, 0.0f); v = fma(rs1, q1, v); v = fma(rs2, q2, v); v = fma(rs3, q3, v)` (the +0 addend makes a −0 first product +0). rs is +0 or normal (at most 1000); a pair sum or partial below 2^-126 needs a general IEEE fma, which the tree does not have (`ieee_fma` takes an integer multiplier) | +| x | `:537` `v / (float) HC` | `FMUL R16, R16, 0.25` (row 780; PTX `mul.f32 %f159, %f158, 0f3E800000`: the division by 4 folded into a multiply, exact, the same real rounded once, subnormals included) | `x = v * 0.25f`; where \|v\| < 2^-124 CUDA's x is subnormal and Metal's ±0 (`ieee_mul(v, 0.25f)`) | +| `__expf(-x)` | `:538` | `FMUL R17, R16, -1.4426950216293334961` (no `.FTZ`); `FSETP.GEU.AND P0, PT, R17, -126, PT`; `@!P0 FMUL R17, R17, 0.5`; `MUFU.EX2 R22, R17`; `@!P0 FMUL R22, R22, R22` (rows 781-785): the non-ftz `ex2.approx.f32` | `e = expf_neg(x)` (basalt_fp.metal:104, as in section 2). Below −126 (x > 87.34) CUDA's e is subnormal and Metal's may be +0: 1 + e = 1 on both | +| `1.0f + e` | `:538` | `FADD R17, R22, 1` (row 786) | `b = 1.0f + e` (e ≥ +0) | +| `x / (...)` | `:538` | `MUFU.RCP R22, R17`; `FCHK P0, R16, R17`; `FFMA R23 = −b·r0 + 1`; `FFMA R23 = r0·R23 + r0`; `FFMA R22 = x·R23 + 0`; `FFMA R32 = −b·R22 + x`; `FFMA R23 = R23·R32 + R22` (rows 787-793); `CALL __cuda_sm3x_div_rn_noftz_f32_slowpath` when `FCHK` flags (row 796): `div.rn.f32`, correctly rounded, subnormal results kept | `l = ieee_div(x, b)` (basalt_q8_1.metal:181; b ≥ 1, infinite or NaN). The quotient is subnormal only for \|x\| < 2^-125: for x ≤ −88.72 the product x · −L reaches 128, e is +inf and l is −0 on both, and above that \|l\| ≈ \|x\| e^x stays above 2^-122 | +| lo stores | `:539-540` | `STS [R22], R23` (lo_s); `@!P2 STG.E desc[UR14][R16.64], R23` (`a.lo` when `out`) (rows 805-807) | `lo_s[k * ls + row] = l`; `if (out) lo[idx] = cuda_nan(l)` | +| second row | `:531-541` for i = 1 (idx = tid + 256 < 320) | rows 809-844: the same four `FADD`, four `FFMA` from `RZ`, `FMUL 0.25`, `ex2.approx` and `div.rn` (slow-path `CALL` row 836) | the same per idx | +| rs out | `:544` `a.rs[tid] = rs_s[tid]` | `LDS R13, [R114]`; `STG.E` (rows 852-859) | `rs[tid] = cuda_nan(rs_s[tid])` (a copy; a NaN in R' makes u and rs NaN, an infinite one gives rs = +0) | +| inject_out | `:547-552` `v = fmaf(rs_s[k * HC + c], cnp[2c][LR + r] + cnp[2c + 1][LR + r], v)` from `0.0f` | per c: `FADD` of the pair, then `FFMA R12, R12, R13, RZ` (rs0 · pair0 + +0); `FFMA R12, R17, R24, R12`; `FFMA R25, R25, R18, R12`; `FFMA R19, R28, R19, R25` (rows 883-890); `STG.E` (row 891) | as v: the pair sums, then the fma chain from `0.0f`, c ascending; `inject_out[tid] = cuda_nan(v)` | + +So each lo value is a fixed function of the eight half-stream dot products of its row and the four rs of its token, +each rs of the stream's two half-stream sums: the partition is the down items', which section 3 fixes per row, and T +only repeats the per-token sequence (section 9). + +## 5. The up items: `hc_up_pre` and `hc_up_main_mma8` + +An up item owns `nc` ≤ 32 columns of every stream (`up_slice`, `:563-566`). Before the down items finish it forms R' +and R' · w_norm of its columns (`hc_up_pre`, `:609-620`); then `cn_lo` (section 4), `hc_up_rout` (`:624-631`, R' to +`R_out`, a copy), the 8-bit up rows on the tensor cores (`:661-696`), the gate (`:698-708`) and the mean over the +streams into `mixed` (`:712-719`). In the tensor-core loop warp w owns row slots 16w..16w+15, lane (g, t4) = +(lane >> 2, lane & 3) holds token g's lo values 4t4..4t4+3 of each 16-value half (`:669`, `:683`), and each +mma_f16's output fragment holds (slot 16w + g, token 2t4), (16w + g, 2t4 + 1), (16w + g + 8, 2t4), (16w + g + 8, +2t4 + 1) in `acc[0..3]`. + +### `hc_up_pre` (`:609-620`) + +| Site | basalt | SASS (13.0, `up.sass.txt` rows 500-550) | Metal | +|---|---|---|---| +| inj / HC, negated | `:616` `a.inj_prev[k * HC + c] / (float) HC`, `:341` `-x` | `FMUL R32, R32, -0.25` (row 515) | as section 2: `inj * 0.25f` into `expf_neg` | +| `__expf(-x)` | `:341` | `FMUL R32, R32, 1.4426950216293334961`; `FSETP.GEU.AND P0, PT, R32, -126, PT`; `@!P0 FMUL R32, R32, 0.5`; `MUFU.EX2 R8, R32`; `@!P0 FMUL R8, R8, R8` (rows 516-520) | `e = expf_neg(inj * 0.25f)` (basalt_fp.metal:104) | +| `1.0f + e`, `1.0f / (...)` | `:341` | `FADD R31, R8, 1` (row 521); `rcp.rn.f32`: the guard `IADD3 R8, PT, PT, R31, 0x1800000, RZ`, `LOP3.LUT R8, R8, 0x7f800000, RZ, 0xc0, !PT`, `ISETP.GT.U32.AND P0, PT, R8, 0x1ffffff, PT` (rows 522-524), `CALL __cuda_sm20_rcp_rn_f32_slowpath` (row 528) or `MUFU.RCP R8, R31`; `FFMA R12, R31, R8, -1`; `FADD.FTZ R27, -R12, -RZ`; `FFMA R8, R8, R27, R8` (rows 531-534) | `g = ieee_div(1.0f, 1.0f + e)` (section 2) | +| `2.0f * s` | `:616` | `FADD R8, R8, R8` (row 538) | `gw = ieee_add(g, g)` | +| R' | `:616` `fmaf(a.bo_prev[...], 2.0f * s, rv)` when `a.apply` | `FFMA R25, R36, R8, R25` (row 539; bo · gw + R; skipped by the branch at row 500 when not `apply`, so R is kept as is) | `if (apply) rv = fma(bo, gw, rv)` (a general IEEE fma where an operand or the result is below 2^-126, as section 2) | +| rp, px | `:617-618` `u.rp[idx] = rv; u.px[idx] = rv * a.w_norm[i]` | `STS [R24], R25` (row 546); `FMUL R8, R26, R25` (row 549, IEEE) | `rp = rv`; `px = rv * w` (`ieee_mul` where a subnormal operand or product can occur) | + +These are section 2's instructions on the same inputs, so the R' an up item writes to `R_out` has the bits of the R' +the down items square and normalize. + +### `hc_up_main_mma8` (`:652-721`) + +| Site | basalt | SASS (13.0, `up.sass.txt`) | Metal | +|---|---|---|---| +| int8 to f16 | `:681-682` `i8x2_h2` (bytes 0, 1), `i8x2_h2` (bytes 2, 3) (`:354-359`) | `LOP3.LUT R41, R32, 0x80808080, RZ, 0x3c, !PT` (q ^ 0x80808080); `PRMT R12, R28, R13, 0x64646464` with selector 0x5140 or 0x7362 (each half 0x64 above the biased byte: 1024 + q + 128); `HADD2 R28, R12, -1152, -1152` (`__hsub2`, `cuda_fp16.hpp:2515`: 1152 + q − 1152 = q, every value an integer below 2048) (rows 985-1062) | `half(char(b))` per byte (exact) | +| x zeroed | `:684` `if (g >= T) x = make_float4(0.f, ...)` | `FSEL R51, R24, RZ, !P0` ×4 (rows 1002-1005) | `x = g < T ? x : 0.0f` | +| hi | `:643` `__floats2half2_rn(a, b)` | `F2FP.F16.F32.PACK_AB R16, R52, R51` (row 1016, `cuda_fp16.hpp:644`; round to nearest even, b in the high half) | `half(a)`, `half(b)`: round to nearest even (measured), a finite overflow to infinity on both, an fp32 subnormal to the zero of its sign on both | +| hf | `:644` `__half22float2(h)` | `HADD2.F32 R14, -RZ, R16.H0_H0`; `HADD2.F32 R15, -RZ, R16.H1_H1` (rows 1023, 1027; exact) | `float(h)` | +| residual | `:645` `a - hf.x`, `b - hf.y` | `FADD R51, R51, -R14`; `FADD R18, R52, -R15` (rows 1029, 1033, IEEE) | `a - float(h)`: exact for a finite hf (a multiple of a's ulp, below \|a\| in magnitude). It is subnormal only for a subnormal a, where CUDA's residual is a and its fp16 part the zero of a's sign, while Metal's flushed a − (−0) is +0 for a negative a: there the port takes `half(a)` | +| lo | `:645` `__floats2half2_rn(...)` | `F2FP.F16.F32.PACK_AB R16, R18, R51` (row 1047) | `half(r)` | +| the mma | `:688-689` `mma_f16(gh, af, h0, h1)`, `mma_f16(gl, af, l0, l1)` (`:637-641`: `mma.sync.aligned.m16n8k16.row.col.f32.f16.f16.f32`, D = A · B + C in place) | per group s, four `HMMA.16816.F32`: `HMMA.16816.F32 R52, R28, R52, RZ` (gh, half 0, C = `RZ`: the zero init `:678` folded), `HMMA.16816.F32 R28, R28, R16, RZ` (gl, half 0), `HMMA.16816.F32 R52, R20, R24, R52` (gh, half 1, C = gh), `HMMA.16816.F32 R28, R20, R12, R28` (gl, half 1) (rows 1048, 1060, 1089, 1105 for s = 0); 40 for T = 1 (10 groups × 2 halves × hi and lo) | MSL has no operation with HMMA's sum. Each output is C plus 16 exact products (an integer of at most 8 bits times an fp16 value: at most 19 significant bits); the mma's k positions 2t4, 2t4 + 1 hold the half's values 4t4, 4t4 + 1 and positions 2t4 + 8, 2t4 + 9 its values 4t4 + 2, 4t4 + 3 (`:632-636`). The PTX ISA leaves "the accumulation order, rounding and handling of subnormal inputs" unspecified: `HMMA.16816.F32` fixes the operands, the chaining through C and the k positions, not the sum. The Metal kernel keeps all three and forms each block's sum in scalar code; whether that sum is an fp32 `fma` chain in a fixed k order (C first, then the products), which can differ from CUDA in acc's last bits, or a model of the sm_120 tensor core's summation is the contract's decision (`docs/design/flash-next.md`, invariant 5) | +| group total | `:692-695` `acc[j] = fmaf(s0 or s1, gh[j] + gl[j], acc[j])` from `0.0f` (`:672`), groups s ascending; s0 = `h2f(sc0[s])` (row slot 16w + g), s1 = `h2f(sc1[s])` (slot 16w + g + 8) | `FADD R41, R52, R28` (gh + gl); `FFMA R41, R28, R41, RZ` (s · it + +0, group 0; rows 1603, 1615); then per group `FADD`, `FFMA ..., acc` as a dependent chain (rows 1603-1728 and on); for T = 1 20 `FADD` and 20 `FFMA` (acc[0] and acc[2]; acc[1] and acc[3] are token 2t4 + 1 ≥ T, dead) | `acc = fma(s, gh + gl, acc)` per group from `0.0f`. hi, lo and the products are multiples of 2^-24, and any rounding or truncation of a sum of them to 24 bits stays one, the scales too, so every operand here is 0 or a multiple of 2^-48: never subnormal, and Metal's `+` and `fma` give CUDA's bits | +| rs select | `:703-705` | `FSEL` chain (rows 1758-1764) | the stream's rs, selected (no arithmetic) | +| x | `:706` `u.px[idx] * rsc` | `FMUL R19, R15, R12` (row 1765, IEEE) | `ieee_mul(px, rs)` where the product can be subnormal | +| `sigmoidf_(acc[j])` | `:707`, `:341` | `FMUL R19, R35, -1.4426950216293334961` (no `.FTZ`); `FSETP.GEU.AND P0, PT, R19, -126, PT`; `@!P0 FMUL R19, R19, 0.5`; `MUFU.EX2 R8, R19`; `@!P0 FMUL R8, R8, R8`; `FADD R21, R8, 1` (rows 1746-1757); the `rcp.rn.f32` guard (rows 1760-1763), `CALL __cuda_sm20_rcp_rn_f32_slowpath` (row 1769) or `MUFU.RCP R8, R21`; `FFMA R12, R21, R8, -1`; `FADD.FTZ R15, -R12, -RZ`; `FFMA R8, R8, R15, R8` (rows 1772-1775) | `sg = ieee_div(1.0f, 1.0f + expf_neg(acc))` (section 2's sigmoid) | +| gate | `:707` `u.g[idx] = x * sigmoidf_(acc[j])` | `FMUL R8, R19, R8` (row 1779, IEEE) | `ieee_mul(x, sg)` where the product can be subnormal | +| mean | `:714-717` `s = 0.0f; s += u.g[(k * HC + c) * nc + col]`, c = 0..3; `s / (float) HC` | `FADD R25, RZ, R16` (+0 + g0); `FADD R25, R25, R28`; `FADD R25, R25, R26`; `FADD R25, R25, R30` (rows 1888-1894); `FMUL R35, R25, 0.25` (row 1896: the division by 4 as an exact multiply) | `s = 0.0f + g0; s = s + g1; s = s + g2; s = s + g3; m = s * 0.25f` (`ieee_add`, `ieee_mul(s, 0.25f)` where a subnormal can occur; the +0 start turns a −0 g0 into +0) | +| mixed | `:717` | `STG.E desc[UR14][R22.64], R35` (row 1897) | `mixed[...] = cuda_nan(m)` | +| the q8_1 row | `:718` `hc_q8_1_store_native(s / (float) HC, ...)` when `q8i` | the same R35 (rows 1899 on, section 6) | the same m | + +Each up output (row slot, token) is thus fixed by its row's 320 int8 values and 10 scales and the token's 320 lo +values: per group the two HMMA chains, their sum, the scale fma, groups ascending; nothing depends on T or on the +token's column, as the per-T compiles confirm (section 9). + +## 6. The q8_1 rows: `hc_q8_1_store_native`, `hc_q8_1_store`, `hc_up_q8` + +The read writes the q8_1 rows of `mixed` for the projections (`HcFusedArgs::xq`) in one of three places, chosen at +run time. With a router (`w_router`: decode's second read of a layer, before the experts, +`src/core/verify.cpp:1612-1616`) each router item quantizes its share of the `T · N / 32` blocks with the IEEE +`hc_q8_1_store` (`:1064-1067`: item r takes blocks r · nq / NRT to (r + 1) · nq / NRT, its warp w the blocks q0 + w, +q0 + w + 8, ...). Without one (decode's first read, before the mixer, `verify.cpp:1157-1159`; the drafter's attention +and mixer reads, `src/core/mtp.cpp:814-818`, `:988-992`), an up slice of 32 aligned columns quantizes its own blocks +in the epilogue (`up_q8_inline`, `:105-107`, `:718`), and any other slice counts its columns per block, the slice that +completes a block quantizing it for every token (`hc_up_q8`, `:116-138`), both with `hc_q8_1_store_native`. So decode +writes both kinds of row: `native_quantize_q8_1`'s arithmetic in the first read, `quantize_q8_1_kernel`'s IEEE +arithmetic in the second. The drafter's router read sets no `xq` (`mtp.cpp:908-913`). Block +q = k · N / 32 + j is token k's values 32j..32j + 31, and its row is a function of those 32 stored values alone +(`__ldcg` re-reads the stored bits, `LDG.E.STRONG.GPU`; the inline form takes the register `:717` stores), so which +item or warp quantizes it changes no bit: the port quantizes every block in a pass after the up items, a dispatch +boundary in place of the counters `g_hc_q8cnt` (`:111`) and the router items' wait (`:1057`). + +### `hc_q8_1_store_native` (`:86-101`) + +Not `native_quantize_q8_1`'s sequence (`matvec.md` section 1) site for site: this file is IEEE-built, so the abs, the +max and the add of the butterflies carry no `.FTZ`; only the two divisions, inline `div.approx.ftz.f32` (`:81-85`), +flush. + +| Site | basalt | SASS (inline at `:718`: `up.sass.txt` rows 1899-1962; in `hc_up_q8`: rows 2052-2114) | Metal | +|---|---|---|---| +| \|xi\| | `:87` `fabsf(xi)` | `FADD R26, \|R35\|, -RZ` (IEEE: a subnormal \|x\| is kept; it is the value sent at offset 16, and the lane's own \|x\| enters the first max as the operand modifier `\|R35\|`) | below | +| amax | `:90` `fmaxf(amax, __shfl_xor_sync(..., o))`, o = 16, 8, 4, 2, 1 | per o `SHFL.BFLY`, then `FMNMX R16, \|R35\|, R16, !PT` (own, received), no `.FTZ` | `warp_max_ftz(abs_ftz(xi))` as `q8_1_store_native` has it. CUDA's max orders subnormals exactly, but amax reaches only d, through an `FMUL.FTZ` that turns a subnormal amax into d = +0 either way, and the test below: when no value of the block is normal, CUDA's amax is subnormal or zero (test true; then each code is xi · +inf with xi flushed, NaN, code 0) and the flushed amax is +0 (test false, code 0), the same codes | +| sum | `:91` `sum += __shfl_xor_sync(..., o)` | per o `FADD R17, R35, R17` (own + received), IEEE; offset 1's add after the code store (row 1953 / 2105) | `warp_sum_ieee(xi)` (`basalt_q8_1.metal:206`, the same XOR order). Not `warp_sum_ftz`: a block of zeros and one negative subnormal value sums to that value on CUDA, which `__float2half` stores as −0 (0x8000), and to +0 flushed | +| d | `:93` `div_approx_ftz(amax, 127.0f)` | `FMUL.FTZ R24, R16, 0.0078740157186985015869` (row 1923 / 2077). The PTX keeps the asm's `div.approx.ftz.f32 %f, %f, 0f42FE0000`; `ptxas` turns the division by the constant into a multiply by fl(1/127) = `0x3C010204`, the file's one strength reduction past the PTX | `mul_ftz(amax, as_type(0x3C010204u))` | +| finite | `q8_1_finite.hpp:19` | `FSETP.GT.AND P1, PT, \|R24\|, 65504, PT`; `LOP3.LUT` (0xb8, copysign of 65504); `FSEL` | `q8_1_finite(d)` (d is +0 or normal, so the IEEE compare changes nothing) | +| amax ≠ 0 | `:95` | `FSETP.NEU.AND P2, PT, R16, RZ, PT` (row 1922 / 2076; true for a subnormal or NaN amax) | `amax == 0.0f ? 0 : ...` on the flushed amax (row amax) | +| xi / d | `:96` `div_approx_ftz(xi, d)` | `MUFU.RCP R24, R28`; `FMUL.FTZ R24, R35, R24` (rows 1936-1938 / 2089-2091) | `mul_ftz(xi, rcp_ftz(d))` (contract invariant 5). d = +0 (amax below about 127 · 2^-126) gives +inf: a normal xi codes ±127, a zero or subnormal one NaN, code 0, on both | +| `roundf` | `:96` | `LOP3.LUT` (copysign of 0.5), `FADD.RZ` (no `.FTZ`), `FRND.TRUNC` (rows 1939-1941 / 2092-2094) | `round(q)`: after the `FMUL.FTZ` q is zero, normal, infinite or NaN, so the IEEE add changes nothing; Metal's `round` breaks ties away from zero | +| clamp, int8 | `:97` | `FSETP.GT.AND P1, PT, v, 127`; `FMNMX.NAN R24, R25, -127, !PT`; `FSEL R27, R24, 127, !P1`; `F2I.TRUNC.NTZ` (rows 1942-1945 / 2095-2098); `STG.E.U8` | `q8_1_code(v)` (NaN to 0) | +| ds | `:100`, `q8_1_finite.hpp:29-31` | lane 0: `q8_1_finite` of d and of sum, `F2FP.F16.F32.PACK_AB R23, R23, R22` (d in the low half, sum in the high, round to nearest even); `STG.E` (rows 1955-1962 / 2107-2114) | `q8_1_put(y, i, code, d, sum)` (`basalt_q8_1.metal:42`; a NaN as 0x7fff) | + +So the Metal form is `q8_1_store_native` (`basalt_q8_1.metal:52`) with `warp_sum_ieee(xi)` in place of +`warp_sum_ftz(xi)`; every other site is the native quantizer's. The two instances compile to the same sequence; +rows 2994-3138 are their `BRA.DIV` fallbacks (the shuffles through `WARPSYNC.COLLECTIVE`), with the same operands. + +### `hc_q8_1_store` (`:68-78`, the router items) + +The IEEE quantizer of `quantize_q8_1_kernel` (`matvec.md` section 3), site for site; the port is +`q8_1_store_ieee` (`basalt_q8_1.metal:211`) unchanged. + +| Site | basalt | SASS (`rt.sass.txt` rows 1003-1104) | Metal (`q8_1_store_ieee`) | +|---|---|---|---| +| xi | `:1067` `__ldcg(a.mixed + q * 32 + lane)` | `LDG.E.STRONG.GPU R0` (row 1003) | `mixed[32q + lane]` | +| \|xi\|, amax, sum | `:69-74` | `FADD R28, \|R0\|, -RZ`; per o = 16..1 two `SHFL.BFLY`, `FMNMX R3, \|R0\|, R3, !PT`, `FADD R29, R0, R29` (rows 1008-1028, offset 1's add row 1036); IEEE | amax as the largest bit pattern of \|xi\| (a NaN dropped, as `fmaxf` drops it); the sum by `ieee_add` in the same XOR order | +| d | `:75` `amax / 127.0f` | `div.rn.f32`: `UFFMA UR5 = fma(r0, −127, 1)`, `UFFMA UR5 = fma(UR5, r0, r0)`, r0 = `0x3c010204`; `FCHK P0, R3, 127`; `FFMA R4 = amax · c + 0`; `FFMA R23 = R4 · (−127) + amax`; `FFMA R23 = R23 · c + R4` (rows 1030-1041); `CALL __cuda_sm3x_div_rn_noftz_f32_slowpath` when `FCHK` flags (row 1045) | `ieee_div127(amax)` (`basalt_q8_1.metal:142`), then `q8_1_finite` (rows 1051-1056) | +| amax == 0 | `q8_1_finite.hpp:24` | `FSETP.NEU.AND P2, PT, R3, RZ, PT` (row 1050) | `key != 0`, on the bits (a subnormal amax is nonzero, as on CUDA) | +| xi / d | `q8_1_finite.hpp:25` | `div.rn.f32`: `MUFU.RCP R4, R23`; `FCHK P0, R0, R23`; `FFMA R3 = −d · r + 1`; `FFMA R3 = r · R3 + r`; `FFMA R4 = xi · R3 + 0`; `FFMA R26 = −d · R4 + xi`; `FFMA R3 = R3 · R26 + R4` (rows 1058-1065); the slow path (row 1070) | `xi / d`, on both operands scaled by 2^64 where amax is below 2^-100 (`ieee_up64`) | +| `roundf`, clamp, int8 | `:25-26` | `HFMA2 R0, -RZ, RZ, 1.75, 0` (0.5 as fp32), `LOP3.LUT` (copysign), `FADD.RZ`, `FRND.TRUNC`; `FSETP.GT.AND`, `FMNMX.NAN`, `FSEL`, `F2I.TRUNC.NTZ` (rows 1075-1082); `STG.E.U8` (row 1093) | `q8_1_code(round(q))` | +| ds | `:77` | lane 0: `q8_1_finite` ×2, `F2FP.F16.F32.PACK_AB R3, R3, R0`, `STG.E` (rows 1095-1104) | `q8_1_put` | + +Rows 2036-2101 are the `BRA.DIV` fallback, with the same operands. + +### `hc_up_q8` (`:116-138`) + +No floating-point instruction of its own: the count `atomicAdd(&cnt[j], n)` (`:124`), `__threadfence()` +(`MEMBAR.SC.GPU`, row 1989), and per completed block j and token k one warp's +`hc_q8_1_store_native(__ldcg(a.mixed + q * 32 + lane), ...)`, q = k · N / 32 + j (`:132-136`; `LDG.E.STRONG.GPU`, +row 2052). The port's pass replaces it. + +## 7. `hc_router_rows` and `warp_sum16_ftz` (`:724-809`) + +Router item r (`:1049-1063`) takes the router rows e0 = r · NE / NRT to e1 = (r + 1) · NE / NRT (512 rows over +`NRT` = 81 items: 6 or 7 rows, `RT_MAX_ROWS` = 7, `:33`, `:38`, `:40`), bulk-copied as bf16 words into shared memory +(`wsm`, `:1052-1058`), and waits for every up item, so the `mixed` it reads (`__ldcg`, `LDG.E.64.STRONG.GPU`) is the +stored row. Per pass of `TG` = min(T, 4) tokens (`:745`) thread t loads the float2 pairs t + 256 j, j = 0..4 +(`PAIRS` = 5, `:744`), of each token's row and forms one chain per row slot e < 7 and token q; the 7 · TG chains are +reduced over the warp 16 at a time (`warp_sum16_ftz`), lane 2m of each warp stores value m's warp sum (m = e · TG + +q, `:778-786`), and warp 0 reduces the eight warp sums and 24 zeros with the same tree (`:789-805`). Every float +instruction is one of the file's inline-asm helpers, `fma_ftz` (`:273`, `fma.rn.ftz.f32`) and `add_ftz` (`:278`, +`add.ftz.f32`): the file is IEEE-built, but these sites are written in the flush-to-zero form of a `--use_fast_math` +build, the MMVF kernel's (`:723`, `:737-739`), and the SASS carries `.FTZ` on each. + +| Site | basalt | SASS (13.0, `rt.sass.txt` rows 595-978) | Metal | +|---|---|---|---| +| x | `:755` `__ldcg(...(a.mixed + (k0 + q) * N) + tid + THREADS * j)`, zero past T | `LDG.E.64.STRONG.GPU R4, desc[UR14][R40.64]`, then `+0x800`, `+0x1000`, `+0x1800`, `+0x2000` (rows 601-606: pairs t + 256 j) | `x[k * 1280 + t + 256 j]` as float2 | +| w | `:763` `e < ne ? ... : 0u`, `:769` `__uint_as_float(wr[j] << 16)`, `wr[j] & 0xffff0000u` | `@P1 LDS R3, [R33+UR4]` (row slot e at `+0x1400 · e`, predicated on e < ne; the register's `HFMA2 R3, -RZ, RZ, 0, 0` / `MOV` / `CS2R` zero otherwise); `IMAD.U32 R41, R3, 0x10000, RZ`; `LOP3.LUT R44, R3, 0xffff0000, RZ, 0xc0, !PT` (rows 613-626) | `as_type(word << 16)`, `as_type(word & 0xffff0000u)` (exact) | +| chain | `:766-772` `s = 0.0f; s = fma_ftz(w0, x[q][j].x, s); s = fma_ftz(w1, x[q][j].y, s);` j = 0..4 | per (row slot, token) 10 `FFMA.FTZ` chained from `RZ`, j ascending, w0 · x.x then w1 · x.y; row slot 0: `FFMA.FTZ R46, R4, R41, RZ`; `FFMA.FTZ R41, R5, R44, R46`; `FFMA.FTZ R44, R26, R44, R41`; `FFMA.FTZ R47, R27, R6, R44`; `FFMA.FTZ R44, R28, R44, R47`; `FFMA.FTZ R51, R29, R30, R44`; `FFMA.FTZ R52, R24, R50, R51`; `FFMA.FTZ R51, R25, R50, R52`; `FFMA.FTZ R52, R22, R52, R51`; `FFMA.FTZ R6, R23, R6, R52` (rows 636, 637, 640, 643, 648, 653, 664, 673, 700, 715). `ptxas` writes the activation first, as in `bf16.md`: the product commutes | `s = fma_ftz(w0, x.x, 0.0f); s = fma_ftz(w1, x.y, s); ...` in the same order (`fma_ftz`, basalt_fp.metal:73, with its rounding to ±2^-126; the +0 start makes a −0 first product +0). An absent row slot (weights +0) can give NaN for an infinite x; it is never stored and meets no other value in the trees | +| warp tree | `:784` `warp_sum16_ftz(v, lane)` (`:724-735`): for o = 16, 8, 4, 2 with n = 8, 4, 2, 1 values, keep = h ? v[j + n] : v[j], send the other, `v[j] = add_ftz(keep, __shfl_xor_sync(..., send, o))`; then `add_ftz(v[0], __shfl_xor_sync(..., v[0], 1))` | per step `SEL`/`FSEL` on the lane bit (P0..P3 = lane & 16, 8, 4, 2), `SHFL.BFLY` by 0x10, 0x8, 0x4, 0x2, `FADD.FTZ keep, received`; then `SHFL.BFLY PT, R4, R3, 0x1, 0x1f`; `FADD.FTZ R23, R3, R4` (rows 820-882). The padded values (`acc[i] = 0.0f` for i ≥ NV, `:777`) are `RZ` | `warp_sum_ftz(s)` per value (basalt_fp.metal:87): each value's total adds the same two partials at each step as `warp_sum_ftz`'s XOR tree on the 32 lanes' chains, and a + b = b + a (a NaN's payload aside), so it has `warp_sum_ftz`'s bits, as section 3's `warp_sum16` has `warp_sum`'s | +| partials | `:786` `if ((lane & 1) == 0 && m < NV) partials[m * WARPS + warp] = sum` | `@P4 STS [R8+0x8c00], R23` (row 883); `BAR.SYNC.DEFER_BLOCKING 0x0` (row 884) | `if (lane == 0) partials[k][sg] = s;` barrier | +| block tree | `:797` `v[i] = lane < WARPS && m < NV ? partials[m * WARPS + lane] : 0.0f`; `:799` `warp_sum16_ftz` | warp 0: `@!P4 LDS R3, [R12+UR4+0x8c00]` ... `+0x8cc0` (lanes < 8; value m at `+0x20 · m`), `MOV`/`CS2R` zeros on lanes ≥ 8 (rows 887-900); the same tree, `FADD.FTZ` (rows 901-963; `FADD.FTZ R25, RZ, R27` is a padded slot's 0 + 0) | `warp_sum_ftz(lane < 8 ? partials[k][lane] : 0.0f)`: the eight warp sums and 24 zeros, ((p0 + p4) + (p2 + p6)) + ((p1 + p5) + (p3 + p7)) after the +0 of the 16 and 8 steps, which turn a −0 into +0 (`bf16.md`, notes) | +| logits | `:801-803` lane 2m, m < NV, e < ne, k0 + q < T: `a.logits[(k0 + q) * NE + e0 + e] = sum`; `st_tagged(lg64 + ..., sum, tag)` | `STG.E desc[UR14][R22.64], R27` (row 977); `STG.E.64.STRONG.GPU desc[UR14][R24.64], R4` (row 978: the bits with the tag in the high word, `IADD.64`, `:235-237`) | `logits[k * 512 + e] = cuda_nan(s)`; the tagged copy is the persistent kernel's hand-off to the top-10 item (`:1045`) and becomes the dispatch boundary | + +So every logit is `bf16_f32_mmvf_multi_kernel<256, *>`'s value for its row and token, site for site: the ten +`FFMA.FTZ` of thread t's five pairs from +0, the warp's XOR tree, the tree over the eight warp sums and 24 zeros +(`bf16.md` section 1). The 16-value packing of `warp_sum16_ftz`, the passes of `TG` tokens and the item's share of +rows change which lane or pass forms a value, never its operations, so the port's router is `basalt_mmvf` +(`kernels/common/basalt_mmvf.metal`) with `BLOCK` 256 over the 512 rows of `w_router` and n_tok = T token rows +(`NT` ≥ T): the "MMVF router GEMV" `hc_fused_parity` prints its comparison against. Section 9 checks the chains and +trees at T = 2 and T = 8. + +## 8. `hc_top10` (`:816-916`) + +The top-10 item (`:1030-1047`): warp k < T takes token k's 512 logits (`NE`, `:33`), lane L the logits L + 32i, +i = 0..15, and writes the token's `KT` = 10 expert ids and weights (`:34`). It runs as `hc_top10_item`, a +`__noinline__` subroutine (`:918-924`; `rt.sass.txt` rows 2102-3161, called at row 507 for the dry run on +`L.t10_dummy`, `:1033-1040`, and at row 541 for the token, `:1044-1046`), so its operations and their dependencies +are the same for every T (section 9). The +softmax is the file's inline-asm helpers (`:271-316`), each with `.FTZ`; the selection is compares, integer counts and +shuffles. Every compare of the selection reads a probability `values[i]` after `:845`: the result of an `FMUL.FTZ` +(+0 or a positive normal value at most 1: e ≤ 1, and the warp sum is at least the maximum's e = 1) or −FLT_MAX in +place of a NaN. It is never subnormal and never NaN, so Metal's compares, which read a subnormal as zero, give CUDA's +predicates at every site, and no integer keys are needed. + +| Site | basalt | SASS (13.0, `rt.sass.txt`) | Metal | +|---|---|---|---| +| logits | `:820-830`: with the tag (`tg`, the read's path) 16 `ld_tagged_raw` (`:230-234`), re-read until each carries `tag` (`tagged_settle`, `:240-252`), the value the low word (`:826`); otherwise `__ldcg(logits + lane + i * 32)` | `LDG.E.64.STRONG.GPU R82, desc[UR8][R20.64]` to `+0xf00` (rows 2117-2156: `ld.relaxed.gpu.global.u64`, entries 8 bytes apart); the settle loop's `ISETP.NE.AND` of each high word against the tag (rows 2159 on); the plain path `LDG.E.STRONG.GPU` at `+0x80 · i` (rows 2261-2300) | `v = logits[k * 512 + lane + 32 * i]`: the router dispatch has stored them (section 7), so the tag and its re-read loop become the dispatch boundary; the bits are the router's `sum` | +| maximum | `:831-834` `maximum = -INFINITY; maximum = max_ftz(maximum, values[i])`, i ascending; `warp_max_ftz` (`:312-316`) | `FMNMX.FTZ R21, R82, -INF, !PT`, then 15 `FMNMX.FTZ` in i order (rows 2304-2322, `max.ftz.f32`, `:293`); per o = 0x10, ..., 0x1 `SHFL.BFLY`, `FMNMX.FTZ own, received, !PT` (rows 2325-2335) | `m = max_ftz(m, v)` from `-INFINITY`, i ascending; `warp_max_ftz(m)` (basalt_fp.metal:81, :91). A NaN logit is skipped on both (all NaN: m = −inf). Where `max_ftz`'s choice between +0 and −0 differs from `FMNMX.FTZ`'s, no output sees it: v − (±0) is v for a nonzero v and a zero for a zero v, and ex2 of a zero is 1 | +| `expf_fast(sub_ftz(v, m))` | `:838`, `:306` | `FADD.FTZ v, -m, v` (`sub.ftz.f32`, `:283`); `FMUL.FTZ t, v, 1.4426950216293334961` (`:288`; the constant `1.4426950216293335f` is 0x3FB8AA3B); `MUFU.EX2 e, t` (`:298`, the `.ftz` form: no range scaling) (rows 2336-2399) | `e = expf_ftz(add_ftz(v, -m))` (basalt_fp.metal:107, :49; contract invariant 5: `fast::exp2` of the same product) | +| sum | `:835`, `:839` `sum = add_ftz(sum, values[i])` from `0.0f` | `FADD.FTZ R26, RZ, R20` (+0 + e0), then e1..e15 chained in i order (rows 2362-2399, among the exponentials) | `s = add_ftz(s, e)` from `0.0f`, i ascending | +| reciprocal | `:841` `rcp_ftz(warp_sum_ftz(sum))` (`:307-311`) | per o = 0x10, ..., 0x1 `SHFL.BFLY`, `FADD.FTZ own, received` (rows 2400-2410); `MUFU.RCP R60, R60` (row 2411, `rcp.approx.ftz.f32`, `:303`) | `r = rcp_ftz(warp_sum_ftz(s))` (basalt_fp.metal:83, :87; `MUFU.RCP` as the correctly rounded reciprocal, contract invariant 5) | +| probabilities | `:843-846` `values[i] = mul_ftz(values[i], reciprocal); if (isnan(values[i])) values[i] = -FLT_MAX` | `FMUL.FTZ p, e, R60` (`:288`); `FSETP.NAN.AND P0, PT, \|p\|, \|p\|, PT` (`cmath:1176`); `FSEL p, p, -3.40282346638528859812e+38, !P0` (`:845`) (rows 2412-2510) | `p = mul_ftz(e, r); if (isnan(p)) p = -FLT_MAX;` (basalt_fp.metal:80). A NaN or +inf logit makes every p of the token NaN, so −FLT_MAX: the ties then fall to the lower expert numbers | +| lane maximum | `:851-855` `bv = values[0]; be = lane;` then `if (values[i] > bv) { bv = values[i]; be = lane + 32 * i; }`, i = 1..15 | per i `FSETP.GT.AND P, PT, p_i, bv, PT` (an IEEE compare), `FSEL bv`, `SEL be` (`IADD3 be, lane, 0x20 · i`) (rows 2428-2518) | the same strict `>` in i order: a tie keeps the lower expert | +| rank | `:857-863` for m = 0..31: `ov = __shfl_sync(bv, m)`, `oe = __shfl_sync(be, m)`, `rank += before(ov, oe, bv, be)`; `before` (`:849`): v > v2, or v == v2 and e < e2 | per m two `SHFL.IDX`; `ISETP.GE.AND P, PT, oe, be`; `FSETP.EQ.AND P, PT, bv, ov, !P`; `FSETP.LT.OR P, PT, bv, ov, P`; `@!P IADD3 rank, 1` (rows 2519-2742) | `simd_shuffle(bv, m)`, `simd_shuffle(be, m)` and the same `before`; the count is an integer, so its order is free | +| theta | `:864-867` `__ballot_sync(rank == KT - 1)`, `src = __ffs(at9) - 1`, `tv`, `te` by `__shfl_sync` from `src` | `VOTE.ANY R65, PT, !P0`; `BREV`; `FLO.U32.SH` (the lowest set lane); two `SHFL.IDX` (rows 2745-2750) | `src = ctz(simd_ballot(rank == 9))` (as an integer mask), two `simd_shuffle`. The 32 lane maxima are distinct (v, e) pairs, so exactly one lane has rank 9 | +| candidates | `:869-873` `if (!before(tv, te, values[i], lane + 32 * i)) mine \|= 1u << i`; `__popc` | per i `ISETP.GE.AND P, PT, te, e_i` with `FSETP.NEU`, `FSETP.GEU` of p_i against tv (rows 2753-2845: p_i ≥ tv, and p_i ≠ tv or te ≥ e_i); `POPC` (row 2856) | the same test per i (`!before(tv, te, p, e)`), `popcount(mine)` | +| compaction | `:874-888` inclusive prefix by `__shfl_up_sync` o = 1, 2, 4, 8, 16, `total` from lane 31; `cand[2 off] = bits, cand[2 off + 1] = e` | `SHFL.UP` by 0x1, 0x2, 0x4, 0x8, 0x10 (rows 2857-2873); `@P STS.64` of (p bits, e) per marked i in i order (rows 2882-2934); `SHFL.IDX ..., 0x1f` (total, row 2902) | `simd_shuffle_up` in the same steps (integer sums), the pairs into the warp's `CAND_WORDS` (`:943`) of threadgroup memory; `__syncwarp` (`:889`) is a `simdgroup_barrier(mem_flags::mem_threadgroup)` | +| ranking | `:892-900` for c = lane, lane + 32, ... < total: r = the number of d < total with `before(cand_d, cand_c)`; `if (r < KT) { top_v[r] = v; top_e[r] = e; }` | per d `FSETP.GT.AND P, PT, v_d, v, PT`, `@!P ISETP.GE.AND`, `@!P FSETP.EQ.AND` (rows 2965-3071, four candidates per `LDS.128`); `@!P0 STS [R53+0x1000]`, `[R53+0x1028]` for r ≤ 9 (rows 3075-3078) | the same loop (total ≤ 512, so both loops are bounded); ranks 0..9 are distinct, so each slot is written once | +| selected sum | `:904-907` `selected_sum = 0.0f`; for r = 0..9 `if ((top_e[r] & 31) == lane) selected_sum = add_ftz(selected_sum, top_v[r])` | `MOV R22, RZ`; `@!P3 FADD.FTZ R22, RZ, R23` (r = 0: +0 + top_v[0]), then `@!P FADD.FTZ R22, R22, top_v[r]` for r = 1..9 in rank order (rows 3098-3127) | `ss = add_ftz(ss, top_v[r])` from `0.0f`, r ascending, on the lane `top_e[r] & 31` | +| normalizer | `:910-911` `max_ftz(warp_sum_ftz(selected_sum), 6.103515625e-5f)`; `rcp_ftz` | per o = 0x10, ..., 0x1 `SHFL.BFLY`, `FADD.FTZ` (rows 3128-3143); `FMNMX.FTZ R27, R27, 6.103515625e-05, !PT` (row 3144: 2^-14); `MUFU.RCP R22, R27` (row 3145) | `inv = rcp_ftz(max_ftz(warp_sum_ftz(ss), 0x1p-14f))` (the two never tie at zero) | +| outputs | `:912-915` lane < 10: `ids[lane] = top_e[lane]`; `weights[lane] = mul_ftz(top_v[lane], inv)` | `FMUL.FTZ R3, R22, R23` (row 3154); `STG.E` of the id and the weight (rows 3159-3160) | `ids[k * 10 + lane] = top_e[lane]`; `weights[k * 10 + lane] = mul_ftz(top_v[lane], inv)` (never NaN: the selected values are finite, the normalizer at least 2^-14) | + +The selection is thus exact on Metal for given probabilities: every compare, count and shuffle is reproduced +operation for operation, and it orders by (probability descending, expert ascending), as `before` writes. Each step +from a logit to its probability is monotone non-decreasing in the logit (the subtraction of the shared maximum, the +product with L, the exponential, the product with the shared reciprocal, each rounded to nearest and flushed), so the +probabilities order the experts as their logits do, except where rounding makes two of them equal, and then the lower +expert wins. The port's probabilities differ from CUDA's only through the three approximate instructions, `MUFU.EX2` +per logit and the two `MUFU.RCP`, which the contract maps to `fast::exp2` and the correctly rounded reciprocal. +Assuming `fast::exp2` is monotone like `MUFU.EX2` (neither is measured here), the two selections can differ only at a +near-tie: two distinct logits whose probabilities round equal on one side and not on the other. `router_top10_parity` +checks the ids exactly (`src/kernels/router_top10_parity.cpp:86`) against a softmax in double precision with a stable +descending sort (`:35-60`), where distinct logits never tie, on 64 tokens of 512 logits: random normal, all equal, a +12-way exact tie and one dominant expert (`:126-146`). Equal logits give equal probabilities on every implementation +(the same operations on the same value), so the tie cases test only the index rule, which the port reproduces; the +random case passes for CUDA and the port alike unless a near-tie straddles a token's tenth place. The weights carry +the approximate instructions' last-bit differences; the rule's rel ≤ 1e-5 (`:90`) is 84 to 168 ulps. + +`route` (`src/kernels/cuda/native_router.cu:46-100`), the top-10 that runs where the fused read does not and that +`hc_fused_parity` prints its comparison against, is in the `--use_fast_math` list (`CMakeLists.txt:191`). Compiled the +same way (`nvcc130`, `-arch=sm_120 -lineinfo -O3 -DNDEBUG -DBASALT_VERSION="0.0.1" --use_fast_math`, one SASS listing +of 1,501 rows), its softmax and weights are the instructions `hc_top10` writes by hand, in the same order: a +`FMNMX.FTZ` chain from −inf over the 16 values, the warp maximum, per value `FADD.FTZ v, -m`, `FMUL.FTZ` by +1.4426950216293334961 and `MUFU.EX2`, the sum from `FADD.FTZ RZ, e0` in i order (`native_router.cu:58-67`; listing +rows 33-118), then the warp sum, `MUFU.RCP`, the products, the selected sum, the floor and the second `MUFU.RCP`: +`FMNMX.FTZ` 22, `FADD.FTZ` 52, `FMUL.FTZ` 33, `MUFU.EX2` 16 and `MUFU.RCP` 2, the counts of `hc_top10`'s main path and +tail (section 9). Only the operands of the subtraction (`FADD.FTZ v, -m` against `-m, v`) and of the weight's product +stand in the other order, inside commutative operations. Its selection is ten argmax passes (`:74-92`) with `.FTZ` +compares (`FSETP.GT.FTZ` 150, `FSETP.GEU.FTZ` and `FSETP.NEU.FTZ` 50 each) where `hc_top10` ranks candidates with +plain ones: on probabilities that are +0, positive normal or −FLT_MAX the flags agree, and both take the first ten +(p, e) pairs under `before`'s strict total order (basalt's comment, `hc_fused.cu:811-815`), so the port's top-10 serves +both call sites. + +## 9. Per-T check + +Basalt instantiates `hc_fused_kernel` for T = 1 to 8 (`kKernels`, `:1111-1115`) and launches the one for the +window's `a.T` (`:1456`). Sections 2-8 read T = 1; the units `down`, `up` and `rt` were compiled again at T = 2, 5 and +8, and `down` and `rt` at T = 3 (the same request with the table's instantiation changed), to check that a token's +sequence does not depend on T. Per site, the table counts the SASS instructions attributed to its lines at T = 1, 2 +and 8; a count follows the source's own loops (tokens, row slots, `cn_lo`'s rows per thread, rounds of 16 values), and +where the code is duplicated or rolled the copies were read. + +| Site | SASS at T = 1 / 2 / 8 | Reading | +|---|---|---| +| `cn_x`: R' (`:443-444`), squares (`:446`), x (`:447`) | `FFMA` 8 / 16 / 64; `FMUL` 2 / 8 / 32, `FFMA` 6 / 24 / 96, `FADD` 2 / 8 / 32; `FMUL` 8 / 32 / 128 | per token two slots of four values. At T ≥ 2 the loop is compiled twice, with and without `apply` (T = 1 predicates the R' `FFMA` instead), and every copy has section 2's pattern per slot: `FMUL` y·y, `FFMA` x·x + it, z, w, then `FADD` onto +0 (slot 0) and onto that sum (slot 1) (`down.sass.txt` rows 410-568 at T = 2) | +| `cn_x`: warp sum (`:321`), sigmoid (`:341`), `cns` (`:457`) | `FADD` 5 / 10 / 40; `MUFU.EX2` 1 / 2 / 8; `FADD` 8 / 8 / 8 | one butterfly and one gate per token; a thread sums one token's eight warp partials from +0 (rows 598-607 at T = 2) | +| `cn_dot`: int8 to float (`:348-351`) | `FADD` 40 / 40 / 40 per line | per weight, shared by the tokens | +| `cn_dot`: `dot8ff` (`:362-369`), scale (`:489`) | `FFMA` 20 / 40 / 160 per line, 20 / 40 / 160 chains from `RZ`; `FFMA` 20 / 40 / 160, 4 / 8 / 32 from `RZ` | 4 rows × 5 chunks × T chunk dots, each eight `FFMA` from +0; one accumulator per (row, token), chunks ascending | +| `warp_sum16` (`:335`, `:338`) | `FADD` 30 / 30 / 60; 1 / 1 / 3 | ⌈4T / 16⌉ rounds: one at T ≤ 4, two at T = 8, interleaved, each section 3's tree (`FSEL` keep and send on lane bits 16, 8, 4, 2, `SHFL.BFLY`, `FADD`, then offset 1) (rows 3086-3399 at T = 8; the counts include the `BRA.DIV` copies) | +| `cn_lo`: rs (`:525-526`) | `MUFU.RSQ` 1 / 1 / 1, `FCHK` 1 / 1 / 1 | threads tid < T · HC each form one rs | +| `cn_lo`: lo rows (`:536-538`), inject_out (`:550-551`) | `FADD` and `FFMA` 8 / 12 / 40; `FMUL` (÷ 4) 2 / 3 / 10; `MUFU.EX2` 2 / 3 / 10; `FFMA` 4 / 4 / 4 | ⌈320T / 256⌉ = 2, 3, 10 rows per thread, each four `FADD` and four `FFMA` from +0, the multiply by 0.25, ex2 and `div.rn` | +| `hc_up_main_mma8`: mma (`:640`), `split_f16` (`:645`) | `HMMA.16816.F32` 40 / 40 / 40, 20 / 20 / 20 with C = `RZ`; `FADD` 80 / 80 / 80 | one m16n8k16 per (group, half, hi or lo) covers tokens 0..7 in its n columns: T only changes which columns hold zeros (`:684`) | +| `hc_up_main_mma8`: group totals (`:692-695`), gate (`:706-707`), mean (`:716-717`) | `FADD` and `FFMA` 20 / 40 / 40, 2 / 4 / 4 from `RZ`; `FMUL` 2 / 4 / 4 per line; `FADD` 4 / 4 / 4, `FMUL` 1 / 1 / 1 | acc[1] and acc[3] (token 2t4 + 1) are dead at T = 1 and live from T = 2; at T = 8 the per-thread code is T = 2's | +| q8_1 rows (`:83-101`) | constant | the same per block at every T (inline and in `hc_up_q8`) | +| router chains (`:273`) | `FFMA.FTZ` 70 / 140 / 280, 7 / 14 / 28 from `RZ` | 7 row slots × TG tokens × 10, TG = min(T, 4) per pass (`:745`); at T = 8 the loop over the two passes (`:749`) is rolled | +| router trees (`:278`) | `FADD.FTZ` 46 / 47 / 94 | NV = 7 · TG values in ⌈NV / 16⌉ = 1, 1, 2 rounds (`:746-747`). At T = 1 the warp tree's first step adds 7 pairs, not 8 (`rt.sass.txt` rows 841-850): the eighth pair is two padded zeros on every lane, which `ptxas` folds to the +0 that add_ftz(+0, +0) gives, so no row slot's value loses an add | +| `hc_top10_item` | `FADD.FTZ` 89, `FMUL.FTZ` 65, `FMNMX.FTZ` 27, `MUFU.EX2` 32, `MUFU.RCP` 3 at each T; no `FFMA` | not a template on T: only register moves, constants and the schedule differ between the compiles. The counts hold the main path, the `BRA.DIV` copy of the softmax that a divergent warp takes at the warp maximum (`rt.sass.txt` rows 3162-3320 at T = 1: the shuffles under `WARPSYNC.COLLECTIVE`, then section 8's instructions in the same order, from the warp maximum to the probabilities) and the tail: `FADD.FTZ` 2 × (16 + 16 + 5) + 10 + 5, `FMUL.FTZ` 2 × 32 + 1, `FMNMX.FTZ` 16 + 2 × 5 + 1, `MUFU.EX2` 2 × 16; the three `MUFU.RCP` are the softmax reciprocal (row 2411), its copy (row 3306) and the normalizer's (row 3145) | + +`ptxas` fuses nothing beyond the PTX at any T: per line, the SASS `FFMA` count is the PTX's `fma` count plus the +Newton steps of the PTX's own `div.rn.f32` and `rcp.rn.f32`, and no PTX `mul` or `add` disappears. (The division and +reciprocal slow paths, `__cuda_sm3x_div_rn_noftz_f32_slowpath` and `__cuda_sm20_rcp_rn_f32_slowpath`, are subroutines +after the kernel, listed under `:178`. The one count that differs, two `div.rn.f32` and two `add.rz.f32` at +`q8_1_finite.hpp:25` in `rt` against one of each in SASS, is the stand-alone `.func q8_1_quant` that +`--keep-device-functions` adds to the PTX, which has no SASS in the listing.) Past the PTX the file has one fusion, +the error sums of `hc8_quant_kernel` (section 1), and one strength reduction, the division by 127 of +`hc_q8_1_store_native` (section 6), both independent of T. + +T = 3 and T = 5 add the partial structures: the router's TG = 3 (`FFMA.FTZ` 210, 21 chains from `RZ`) with its +21 values in two rounds (`FADD.FTZ` 91), and at T = 5 TG = 4 (`FFMA.FTZ` 280, 28 from `RZ`, `FADD.FTZ` 94) over two +passes, the second holding one token; `cn_dot`'s 12 values in one `warp_sum16` round at T = 3 and 20 in two at T = 5 +(`FADD` 30 and 60 at `:335`), with 60 and 100 chunk dots and 12 and 20 accumulators from `RZ`; `cn_x`'s two slots +per token in both copies (`FMUL` 12 and 20 at `:446`); at T = 5 ⌈1600 / 256⌉ = 7 lo rows per thread (`FADD` 28 at +`:536`), the 40 `HMMA` (20 with C = `RZ`) and four accumulators from `RZ`; and the top-10 subroutine's float +instructions, the same at all five T. + +So every count is the T = 1 count times the tokens, rows or rounds the source's loops give it, with one chain start +per token, and the sequences of sections 2-8 hold at every compiled T: no output depends on T or on the token's +column of the window (contract invariant 1), within the limits the sections name (the HMMA sum, the approximate +`MUFU` instructions). T = 4, 6 and 7 were not compiled; the compiled widths cover their structures: T = 4 has one +full `warp_sum16` round of 16 values in `cn_dot` and one router pass of 28 values in two rounds, and T = 6 and 7 have +two `cn_dot` rounds and a second router pass whose absent tokens load zeros (`:755`) and store nothing +(`:801-803`), as at T = 5. diff --git a/monolith/packs/basalt_hc8.py b/monolith/packs/basalt_hc8.py new file mode 100644 index 00000000..b92a8ed9 --- /dev/null +++ b/monolith/packs/basalt_hc8.py @@ -0,0 +1,186 @@ +# SPDX-License-Identifier: MIT +# Copyright (c) 2026 Jesús Gulfo +# adapted from basalt (jesdga95/basalt) src/kernels/cuda/hc_fused.cu:1171-1227 (hc8_quant_kernel, hc8_make), +# include/basalt/core/model_file.hpp:126-149 and src/core/model_file.cpp:438-485 (the BASALTH8 table), +# src/core/verify.cpp:566-581 and src/core/mtp.cpp:215-218, :488-503 (the copied matrices), src/core/verify.cpp:638-640 +# and src/core/mtp.cpp:516-521 (their order in hc8_dump's table) @ b4c63b55754637f4c72ad53a0f791d425f71eb36 (MIT; +# third_party/NOTICE). +"""Basalt's int8 copies of the hyper-connection matrices, made on the host. + +A copy of a BF16 matrix ``w [rows][cols]`` (``cols % 32 == 0``) is one block of bytes, the allocation ``hc8_make`` +fills (``src/kernels/cuda/hc_fused.cu:1210-1227``): the codes ``q [rows][cols]`` as int8, row-major, then the scales +``s [rows][srow]`` as f16, ``srow = (cols / 32 + 7) & ~7``. Scale ``j`` of row ``r`` covers ``w[r][32 j .. 32 j + 31]``: +``s = f16_rne(absmax / 127)`` and ``q = clamp(rint(w / s), -127, 127)``, every code of the group 0 where ``s`` is 0, and +the ``srow - cols / 32`` padding scales of each row are 0. ``hc8_quant_kernel`` (``hc_fused.cu:1171-1197``) computes it +in IEEE binary32: subnormals kept, both divisions correctly rounded, both roundings to nearest even. ``quantize`` is +that arithmetic in numpy, operation for operation; ``docs/research/basalt-nvcc/hc_fused.md`` section 1 records what +nvcc compiles it to. + +On one GPU basalt quantizes every hyper-connection down, up and injection matrix of the target and of the drafter at +load, from the BF16 bytes its model file stores (``src/program/generate.cpp:2233-2365``, ``src/core/mtp.cpp:254-282``, +``:488-503``). It holds the down and up matrices only as their copies, while the injections stay BF16 beside theirs +(``generate.cpp:2360``, ``mtp.cpp:215-218``). Every hyper-connection read then takes the copies (decode's fused read, +``src/kernels/cuda/hc_fused.cu:1430-1431``, and ``hc8_gr_read_multi``, ``src/kernels/cuda/hc8_gr.cu:250``, ``:279``) +except the target prompt path's injection product, which multiplies the BF16 matrix (``src/prefill/prefill.cpp:1572``; +``src/prefill/gemm.cu:136`` takes a copy only when it is ``owned``, the matrix's only form, as the down and up copies +are: ``hc_fused.cu:1274``, ``:1302``). The port makes the copies on the host, once per ``.basalt`` file: + +* Exact without a flush argument: the host CPU computes binary32 with subnormals kept, the kernel's own arithmetic, + where a Metal pass would flush them. +* No new runtime mechanism: the repository has no run-once setup program, and packs prepared on the host exist already. +* Memory: the GPU binds only the copies, never the target's 1,271,398,400 bytes of BF16 down and up matrices beside the + decode program. + +The copies pack is a :class:`~monolith.packs.packer.PackFile` directory. Its data file ``weights.pack`` is basalt's +``BASALTH8`` table as ``hc8_write`` lays it out (``include/basalt/core/model_file.hpp:126-149``, +``src/core/model_file.cpp:438-485``): a 16-byte header (``b"BASALTH8"``, version 1 and the entry count as ``uint32``), +160-byte entries (the name NUL-padded to 128 bytes; rows, cols, srow and 0 as ``uint32``; offset and bytes as +``uint64``), each copy's bytes at a 256-aligned offset with zero fill between, and the file zero-padded to a multiple +of 16384 bytes, because the runtime maps whole pages only. Its manifest lists two aux rows per copy, under basalt's +table name (``blk.L.hc_attn_down.weight`` and the like; ``mtp.`` then the tensor's name for the drafter's): +``hc8//q``, ``U8 [rows, cols]`` at the entry's offset, and ``hc8//s``, ``F16 [rows, srow]`` at that +offset plus ``rows * cols``. +""" + +from __future__ import annotations + +import json +import re +import struct +from collections import Counter, namedtuple +from pathlib import Path +from typing import Tuple + +import numpy as np + +from ..formats.basalt_reader import BasaltFile +from .packer import ALIGN, PackFile + +G8 = 32 # values per scale group (hc_fused.cu:343) +Hc8Entry = namedtuple("Hc8Entry", "name src offset rows cols") # offset: of the BF16 bytes, from the file's start +TARGET = re.compile(r"blk\.(\d+)\.hc_(attn|ffn)_(down|up|inject)\.weight") # hc8_tensors (verify.cpp:566-581) +OUTPUT = ("output_hc_down.weight", "output_hc_up.weight") # its last two (:578-579) +DRAFTER = tuple(p + m for p in ("attn_hyper_connection.", "mlp_hyper_connection.", "hyper_connection_mixer.") + for m in ("input_mix_weight_down.weight", "input_mix_weight_up.weight", "block_inject_weight.weight")) + + +def quantize(w: np.ndarray) -> Tuple[np.ndarray, np.ndarray]: + """The copy of the BF16 matrix whose bits are ``w`` (``uint16 [rows, cols]``): ``(q, s)``, ``q`` the codes' int8 + bit patterns as ``uint8 [rows, cols]`` and ``s`` the scales' f16 bits as ``uint16 [rows, srow]``, padding scales + 0, so that ``q.tobytes() + s.tobytes()`` is basalt's allocation. Raises ``ValueError`` unless ``w`` is a 2-D + ``uint16`` array with ``rows`` and ``cols`` positive, ``cols % 32 == 0`` and every weight finite. A finite weight + above ``127 * 65504`` is basalt's case too: its group's scale is inf and every code of the group 0.""" + if not (isinstance(w, np.ndarray) and w.dtype == np.uint16 and w.ndim == 2): + raise ValueError(f"quantize: the weights must be a 2-D uint16 array of BF16 bits, not " + f"{type(w).__name__} {getattr(w, 'dtype', '')} of shape {getattr(w, 'shape', '')}") + rows, cols = w.shape + if rows == 0 or cols == 0 or cols % G8: + raise ValueError(f"quantize: a {rows} x {cols} matrix; rows and cols must be positive and cols a multiple of " + f"{G8}, so that a group of {G8} never straddles a row") + bad = (w & 0x7F80) == 0x7F80 + if bad.any(): + r, c = np.argwhere(bad)[0] + raise ValueError(f"quantize: {int(bad.sum())} non-finite weights, the first at row {r}, column {c} " + f"(bits 0x{int(w[r, c]):04X}); a valid pack's hyper-connection matrices have none") + gpr = cols // G8 + x = (w.astype(np.uint32) << 16).view(np.float32).reshape(rows * gpr, G8) # :1178 the BF16 bits as fp32 + amax = np.abs(x).max(axis=1) # :1179 the fmaxf chain from 0: exact on finite weights + with np.errstate(over="ignore"): # above f16's range: inf, basalt's scale too + h = (amax / np.float32(127)).astype(np.float16) # :1181 div.rn.f32, cvt.rn.f16.f32 + s = h.astype(np.float32) # :1182 exact + with np.errstate(divide="ignore", invalid="ignore"): # s == 0: the quotients are unused + v = np.where(s[:, None] > 0, np.clip(np.rint(x / s[:, None]), -127, 127), 0) # :1185 div.rn, rni, max, min + q = v.astype(np.int8).view(np.uint8).reshape(rows, cols) # :1186 integral, in [-127, 127] + sc = np.zeros((rows, (gpr + 7) & ~7), np.uint16) # hc8_make's memset (:1223) + sc[:, :gpr] = h.view(np.uint16).reshape(rows, gpr) # :1183 + return q, sc + + +def copy_list(f: BasaltFile) -> Tuple[Hc8Entry, ...]: + """The matrices basalt copies on one GPU, in the order of the table ``hc8_dump`` writes + (``src/core/verify.cpp:619-645``), from the file's index sections alone (no weight byte is read). ``name`` is + basalt's table name, ``src`` the IR name of the BF16 row (for messages), ``offset`` its byte offset in the file, + ``rows`` x ``cols`` the copy's shape. The target's come first, in ``hc8_tensors``' order (``verify.cpp:566-581``, + ``:638-639``): per layer, ascending, ``blk.L.hc_attn_{down,up,inject}.weight`` then + ``blk.L.hc_ffn_{down,up,inject}.weight``, then ``output_hc_{down,up}.weight``, each a ``dense/`` row of ``ne1`` x + ``ne0`` (``generate.cpp:2326``, ``:2350``). Then the drafter's (``verify.cpp:640``), named ``"mtp." + name``: the + ``input_mix_weight_down``, ``input_mix_weight_up`` and ``block_inject_weight`` tensors of its attention's, MLP's and + final mixer's hyper-connections (``mtp.cpp:488-503``), in ``mtp/dense.index``'s line order, the order in which + ``hc8_keys`` lists them (``mtp.cpp:516-521``) and the load copies the down and up matrices (``:257-267``). A matrix + the file lacks is left out, as basalt's ``prepare_hc8`` leaves it (``verify.cpp:604``); a graph that reads its copy + is refused by ``emit_program``, where basalt's read ends the process (``hc_fused.cu:1442-1445``). + + Raises ``ValueError`` naming the row or cause for a file with an ``hc8`` section, a target row that is in ``gguf``, + not kind 4 (BF16 as stored) or not ``ne0 * ne1 * 2`` bytes, a drafter row not ``bf16`` of ``rows * cols * 2`` bytes, + a copied matrix that two rows of its index name (``BasaltSource`` refuses two entries of one name, + ``monolith/packs/basalt.py:106``; basalt would copy the first of two injections, ``mtp.cpp:189-193``, ``:495``, and + both of two down or up matrices, ``:257-267``), an empty matrix (``rows`` or ``cols`` 0, of which basalt makes no + copy: ``hc_fused.cu:1253``, ``:1270``), ``cols % 32 != 0``, and a table name of 128 bytes or more (``hc8_write``'s + limit, ``src/core/model_file.cpp:443``).""" + if "hc8" in f.sections: + raise ValueError("copy_list: the file has an 'hc8' section, a table of copies basalt would adopt as it stands: " + "this port builds its own copies from the BF16 rows and does not read a precomputed hc8 table") + out = [] + + def add(name, src, offset, rows, cols, why): + why = why or (f"{rows} x {cols}: an empty matrix" if not rows or not cols else + f"{rows} x {cols}: its columns are not whole groups of {G8}" if cols % G8 else + f"a table name of {len(name.encode())} bytes; hc8_write's hold at most 127" + if len(name.encode()) >= 128 else None) + if why: + raise ValueError(f"copy_list: {src}: {why}") + out.append(Hc8Entry(name, src, offset, rows, cols)) + + dense = f.dense_index().rows + rows, named, base = {r.name: r for r in dense}, Counter(r.name for r in dense), f.section("dense").offset + hc = sorted((int(m[1]), ("attn", "ffn").index(m[2]), ("down", "up", "inject").index(m[3]), n) + for n in rows if (m := TARGET.fullmatch(n))) + for n in [n for *_, n in hc] + [n for n in OUTPUT if n in rows]: + r = rows[n] + add(n, f"dense/{n}", base + r.src_off, r.ne1, r.ne0, + f"{named[n]} rows of dense.index are named {n!r}" if named[n] > 1 else + "its bytes are in gguf" if r.in_gguf else + f"kind {r.kind}, not 4 (BF16 as stored)" if r.kind != 4 else + f"{r.src_bytes} bytes, not {r.ne1} x {r.ne0} BF16" if r.src_bytes != r.ne0 * r.ne1 * 2 else None) + mtp, base = (f.mtp_dense_index(), f.section("mtp/dense").offset) \ + if "mtp/dense.index" in f.sections else ((), 0) # a file with no drafter + named = Counter(t.name for t in mtp) + for t in mtp: # the index's line order, hc8_keys' (mtp.cpp:516-521) + if t.name in DRAFTER: + add("mtp." + t.name, f"mtp/{t.name}", base + t.offset, t.rows, t.cols, + f"{named[t.name]} rows of mtp/dense.index are named {t.name!r}" if named[t.name] > 1 else + f"kind {t.kind!r}, not 'bf16'" if t.kind != "bf16" else + f"{t.nbytes} bytes, not {t.rows} x {t.cols} BF16" if t.nbytes != t.rows * t.cols * 2 else None) + return tuple(out) + + +def write_pack(f: BasaltFile, directory) -> PackFile: + """The copies pack of the ``.basalt`` file ``f``, written into the new directory ``directory`` (an existing one is + refused): every matrix of ``copy_list(f)`` read from its BF16 bytes and quantized, one at a time. ``weights.pack`` + is basalt's ``BASALTH8`` table as ``hc8_write`` lays it out (``src/core/model_file.cpp:438-485``), zero-padded to + a multiple of 16384 bytes; ``manifest.json``, written last, lists each copy's two aux rows (the module's + docstring). ``ValueError`` as ``copy_list`` and ``quantize`` raise it.""" + es = copy_list(f) + out = Path(directory) + out.mkdir(parents=True) # FileExistsError if it exists: a pack is never written over + table, aux, at = [], [], (16 + 160 * len(es) + 255) & ~255 # the first payload (:440) + for e in es: + srow, codes = (e.cols // G8 + 7) & ~7, e.rows * e.cols + nbytes = codes + e.rows * srow * 2 # :444 + table.append(struct.pack("<128sIIIIQQ", e.name.encode(), e.rows, e.cols, srow, 0, at, nbytes)) # :446-452 + aux += [dict(name=f"hc8/{e.name}/q", offset=at, nbytes=codes, dtype="U8", shape=[e.rows, e.cols]), + dict(name=f"hc8/{e.name}/s", offset=at + codes, nbytes=nbytes - codes, dtype="F16", + shape=[e.rows, srow])] + at = (at + nbytes + 255) & ~255 # :453 + with open(out / "weights.pack", "wb") as fh: + fh.write(struct.pack("<8sII", b"BASALTH8", 1, len(es)) + b"".join(table)) # :455-463 + for e, row in zip(es, aux[::2]): + fh.write(bytes(row["offset"] - fh.tell())) # the zero fill (:465-474) + w = np.frombuffer(f.data[e.offset: e.offset + 2 * e.rows * e.cols], np.uint16) # little-endian, as the host + q, s = quantize(w.reshape(e.rows, e.cols)) + fh.write(q.tobytes() + s.tobytes()) + size = -(-fh.tell() // ALIGN) * ALIGN # the runtime maps whole pages only; hc8_read reads only each entry + fh.write(bytes(size - fh.tell())) + (out / "manifest.json").write_text(json.dumps({"version": 2, "alignment": ALIGN, "pack": "weights.pack", + "nbytes": size, "slabs": [], "aux": aux}, indent=1)) + return PackFile(out) diff --git a/tests/basalt_hc_ref.py b/tests/basalt_hc_ref.py new file mode 100644 index 00000000..a688f0d1 --- /dev/null +++ b/tests/basalt_hc_ref.py @@ -0,0 +1,100 @@ +# SPDX-License-Identifier: MIT +# Copyright (c) 2026 Jesús Gulfo +# adapted from basalt (jesdga95/basalt) src/kernels/cuda/hc_fused.cu:1171-1197 (hc8_quant_kernel), +# src/core/model_file.cpp:487-513 (hc8_read) and src/kernels/hc8_parity.cpp:69-99 (hc8_parity's matrices) @ +# b4c63b55754637f4c72ad53a0f791d425f71eb36 (MIT; third_party/NOTICE). +"""Host references of basalt's hyper-connection unit for the port's tests: numpy only, no Metal, imported by every tier +like ``tests/moe_synth.py``. Each is a transcription of basalt's source written apart from the code it checks, so the +two cannot share a mistake. + +* ``hc8_quant_scalar``: ``hc8_quant_kernel``, one group and one value at a time, a numpy float32 or float16 scalar at + every step (the host keeps binary32 subnormals, as the IEEE-built kernel does); the independent side of + ``monolith.packs.basalt_hc8.quantize``. +* ``dequant_copy``: a copy's exact values, ``q * f16(s)`` in float64, the weights the int8 dot products multiply by. +* ``hc8_parity_matrices``: hc8_parity's down, up and injection matrices, drawn with numpy. +* ``hc8_read_table``: ``hc8_read``, basalt's reader of a ``BASALTH8`` table, its checks transcribed. +""" + +import struct +from pathlib import Path + +import numpy as np + +from monolith.formats.fp import f32_to_bf16 + + +def hc8_quant_scalar(w, gpr, srow): # hc8_quant_kernel, hc_fused.cu:1171-1197, G8 = 32 (:343) + """The copy of the BF16 bits ``w`` (any shape, flattened row-major; ``gpr`` scales per row, ``srow`` the row + stride of the scales): ``(q, sc)``, the codes as ``int8 [rows * cols]`` and the scales' f16 bits as + ``uint16 [rows * srow]``, padding scales 0.""" + w = np.asarray(w, np.uint16).reshape(-1) + groups = w.size // 32 + q = np.zeros(w.size, np.int8) + sc = np.zeros(groups // gpr * srow, np.uint16) # cudaMemset(c.s, 0, rows * srow * 2) (:1223) + for gi in range(groups): + x = [np.uint32(int(w[gi * 32 + i]) << 16).view(np.float32) for i in range(32)] # :1178 + amax = np.float32(0.0) + for i in range(32): + amax = np.fmax(amax, np.abs(x[i])) # :1179 fmaxf(amax, fabsf(x[i])) + with np.errstate(over="ignore"): # above f16's range the scale is inf, as cvt.rn.f16.f32 gives + h = np.float16(amax / np.float32(127.0)) # :1181 __float2half_rn(amax / 127.0f): div.rn, RNE + s = np.float32(h) # :1182 __half2float(h) + sc[gi // gpr * srow + gi % gpr] = h.view(np.uint16) # :1183 + for i in range(32): # :1185-1186 + v = np.fmin(np.fmax(np.rint(x[i] / s), np.float32(-127.0)), np.float32(127.0)) if s > 0 else np.float32(0.0) + q[gi * 32 + i] = np.int8(int(v)) + return q, sc + + +def dequant_copy(q, s, cols): + """The exact values of a copy: ``q * f16(s)`` in float64, ``[rows, cols]``, each scale broadcast over its group's 32 + columns. ``q`` holds the codes' int8 bit patterns (int8 or uint8, ``rows * cols`` of them), ``s`` the scales' f16 + bits or values (``uint16`` or ``float16``, ``[rows, srow]``). A code times a finite f16 scale has at most 18 + significant bits, so every such product is exact in double (an inf scale, a group whose absmax exceeds ``127 * + 65504``, has codes 0 and gives NaN): hc8_parity's "the copy's exact values in double", ``(double) q * (double) + f16f(s)`` (``src/kernels/hc8_parity.cpp:254-259``), without the BF16 rounding of its part 1's dequantized copies.""" + q = np.asarray(q).view(np.int8).reshape(-1, cols) + sc = np.asarray(s).view(np.float16).reshape(q.shape[0], -1).astype(np.float64) + return q.astype(np.float64) * sc[:, np.arange(cols) // 32] + + +def hc8_parity_matrices(seed=7): + """hc8_parity's three matrices as BF16 bits (``src/kernels/hc8_parity.cpp:69-99``): its shapes and distributions, + with numpy's normals in place of its ``mt19937(7)`` ones (drawn in its order, down, up, injection; the values are + numpy's, not basalt's): ``w_down [320][10240] = bf16(0.02 N)`` with the 64 outliers ``w_down[5 k][101 k] = + bf16(0.6)`` that set their groups' scales (``:84``), ``w_up [10240][320] = bf16(0.05 N)`` and ``w_inject [4][10240] + = bf16(0.02 N)``, each value the float32 product of the constant and an N(0, 1) draw (``0.02f * nd(rng)``), rounded + to nearest even on the bits (basalt's ``bf16``, ``:36-40``).""" + rng = np.random.default_rng(seed) + w_down, w_up, w_inject = (f32_to_bf16(np.float32(sc) * rng.standard_normal(shape, dtype=np.float32)) + for sc, shape in ((0.02, (320, 10240)), (0.05, (10240, 320)), (0.02, (4, 10240)))) + k = np.arange(64) + w_down[5 * k, 101 * k] = f32_to_bf16(np.float32([0.6])) + return w_down, w_up, w_inject + + +def hc8_read_table(path): # hc8_read, src/core/model_file.cpp:487-513 + """The ``BASALTH8`` table in the file ``path`` read as ``hc8_read`` reads it, with its checks: the magic and version + 1, at most 4096 entries, and each entry's ``bytes == rows * cols + rows * srow * 2`` (in uint64), its range inside + the file, ``cols % 32 == 0`` and ``srow >= cols / 32``; ``ValueError`` with basalt's message otherwise. + ``{name: (rows, cols, srow, offset, bytes, data)}`` in the table's order, ``data`` the entry's bytes, the name up + to its first NUL (``strnlen``); a later entry of a name replaces the earlier one, as in basalt's map.""" + data = Path(path).read_bytes() + if len(data) < 16: # read_range_at of the header (:490) + raise ValueError(f"short read from {path}") + magic, version, n = struct.unpack_from("<8sII", data) + if magic != b"BASALTH8" or version != 1: + raise ValueError(f"hc8: bad magic or version in {path}") + if n > 4096: + raise ValueError("hc8: implausible entry count") + if len(data) < 16 + 160 * n: # read_range_at of the entries (:495) + raise ValueError(f"short read from {path}") + out = {} + for i in range(n): + raw, rows, cols, srow, _, offset, nbytes = struct.unpack_from("<128sIIIIQQ", data, 16 + 160 * i) + name = raw.split(b"\0", 1)[0].decode() + want = (rows * cols + rows * srow * 2) % 2 ** 64 # :502, uint64_t + if nbytes != want or offset > len(data) or want > len(data) - offset or cols % 32 or srow < cols // 32: + raise ValueError(f"hc8: entry {name} is malformed") + out[name] = (rows, cols, srow, offset, nbytes, data[offset: offset + want]) + return out diff --git a/tests/contract/test_basalt_hc8.py b/tests/contract/test_basalt_hc8.py new file mode 100644 index 00000000..3b8ac42d --- /dev/null +++ b/tests/contract/test_basalt_hc8.py @@ -0,0 +1,436 @@ +# SPDX-License-Identifier: MIT +# Copyright (c) 2026 Jesús Gulfo +# adapted from basalt (jesdga95/basalt) src/kernels/cuda/hc_fused.cu:1171-1197 (hc8_quant_kernel), +# src/core/model_file.cpp:487-513 (hc8_read) and src/kernels/hc8_parity.cpp:69-99 (hc8_parity's matrices) @ +# b4c63b55754637f4c72ad53a0f791d425f71eb36 (MIT; third_party/NOTICE). +"""The int8 hyper-connection copies (``monolith/packs/basalt_hc8.py``), GPU-free and bit for bit. No basalt test gates +the copies' bits (hc8_parity prints the down copy's relative rms error and gates only what reads the copies), so every +test here is the port's own, under the contract's rule for quantizer codes: byte for byte (quantize_act_parity's ``if +(g_blocks[i] != r_blocks[i]) ++byte_bad;``). ``quantize`` is held against ``tests/basalt_hc_ref.py``'s scalar +transcription of ``hc8_quant_kernel``, written apart from it, and against groups whose scale and codes are worked out +by hand from basalt's arithmetic and written below. ``copy_list`` is held against basalt's own lists of the copied +matrices on the official pack's index sections, and against synthetic files with one defect each. ``write_pack``'s +table is read back through a transcription of ``hc8_read``'s checks, and as the ``PackFile`` the programs bind.""" + +import struct + +import numpy as np +import pytest + +from monolith.formats.basalt_reader import BasaltFile, DenseRow, MtpTensor +from monolith.formats.fp import bf16_to_f32, f32_to_bf16 +from monolith.packs.basalt import HC8 +from monolith.packs.basalt_hc8 import Hc8Entry, copy_list, quantize, write_pack +from monolith.packs.packer import PackFile +from tests.basalt_hc_ref import dequant_copy, hc8_parity_matrices, hc8_quant_scalar, hc8_read_table +from tests.contract.test_basalt_reader import write_basalt +from tests.contract.test_basalt_windows import real_source + + +def _differing_groups(w, q, s, q_ref, sc_ref, at=None): + """The groups whose codes or scale differ between ``quantize``'s ``(q, s)`` of the BF16 bits ``w [rows, cols]`` and + the scalar transcription's ``(q_ref, sc_ref)``: a message counting them and printing the first, ``""`` if none. + When ``w``'s rows are groups gathered from a matrix, ``at`` holds their rows and groups there, for the message.""" + rows, cols = w.shape + gpr = cols // 32 + q, q_ref = q.view(np.int8).reshape(rows, gpr, 32), q_ref.reshape(rows, gpr, 32) + s, sc_ref = s[:, :gpr], sc_ref.reshape(rows, -1)[:, :gpr] + bad = np.argwhere((q != q_ref).any(axis=2) | (s != sc_ref)) + if not len(bad): + return "" + r, j = bad[0] + where = f"row {r} group {j}" if at is None else f"row {at[0][r]} group {at[1][r]}" + return (f"{len(bad)} of {rows * gpr} groups differ; the first, {where} (BF16 " + f"{[hex(b) for b in w[r, 32 * j:32 * j + 32].tolist()]}): scale {int(s[r, j]):#06x} codes {q[r, j].tolist()}, " + f"the transcription's scale {int(sc_ref[r, j]):#06x} codes {q_ref[r, j].tolist()}") + + +def test_host_keeps_subnormals(): + """HC8-HOST: the host CPU computes binary32 with subnormals kept (macOS arm64 runs with FPCR.FZ clear), which is + hc8_quant_kernel's own IEEE arithmetic and what makes ``quantize`` exact without a flush argument.""" + assert (np.float32(2.0 ** -149) * np.float32(2) == np.float32(2.0 ** -148) + and (np.float32(2.0 ** -126) / np.float32(4)).view(np.uint32) == 0x00200000), \ + "HC8-HOST: np.float32(2.0 ** -149) * np.float32(2) == np.float32(2.0 ** -148) and " \ + "(np.float32(2.0 ** -126) / np.float32(4)).view(np.uint32) == 0x00200000: this host flushes binary32 subnormals" + + +def test_quantizer_equals_the_scalar_transcription(): + """HC8-VEC: a ``[64][4096]`` BF16 matrix (``gpr = srow = 128``) whose groups are each ``bf16(N(0, 1) * 2^E)`` with + their own exponent ``E`` drawn uniformly from -140..30, except that the last group of each row, 64 in all, is random + finite BF16 bit patterns: all-subnormal groups, f16-subnormal scales where the clamp binds, normal scales and scales + that overflow f16 to inf. ``quantize`` and ``hc8_quant_scalar`` give the same codes, scales and bytes.""" + rng = np.random.default_rng(9) + e = rng.integers(-140, 31, 64 * 128) + x = (rng.standard_normal((64 * 128, 32)) * np.exp2(e)[:, None]).astype(np.float32) + w = f32_to_bf16(x).reshape(64, 4096) + w[:, -32:] = (rng.integers(0, 2, (64, 32)) << 15) | (rng.integers(0, 0xFF, (64, 32)) << 7) | rng.integers(0, 0x80, (64, 32)) + q, s = quantize(w) + q_ref, sc_ref = hc8_quant_scalar(w, 128, 128) + assert not (bad := _differing_groups(w, q, s, q_ref, sc_ref)) and np.array_equal(q.view(np.int8).ravel(), q_ref) \ + and np.array_equal(s.ravel(), sc_ref) and q.tobytes() + s.tobytes() == q_ref.tobytes() + sc_ref.tobytes(), \ + f"HC8-VEC: np.array_equal(q, q_ref), np.array_equal(sc, sc_ref) and the bytes equal: {bad}" + + h, g = s.ravel(), w.reshape(-1, 32) # the input reaches every regime it is for + sub = ((h & 0x7C00) == 0) & (h != 0) + amax = np.abs((g.astype(np.uint32) << 16).view(np.float32)).max(axis=1).astype(np.float64) + regimes = {"all-subnormal groups": int((((g & 0x7F80) == 0).all(axis=1) & (g & 0x7FFF).any(axis=1)).sum()), + "the clamp binding at an f16-subnormal scale": + int((sub & (amax > 127.5 * h.view(np.float16).astype(np.float64))).sum()), + "normal scales": int((((h & 0x7C00) != 0) & ((h & 0x7C00) != 0x7C00)).sum()), + "inf scales": int((h == 0x7C00).sum())} + assert min(regimes.values()) > 0, f"HC8-VEC's input misses a regime: {regimes}" + + +# HC8-CASES: (case, the group's BF16 bits, zero after those listed; its scale's f16 bits; its codes, zero after those +# listed), worked out from hc8_quant_kernel's arithmetic: s = f16_rne(amax / 127), q = clamp(rint(w / s), -127, 127). +CASES = ( + ("all +0", [0x0000] * 32, 0x0000, []), + ("all -0", [0x8000] * 32, 0x0000, []), + ("all subnormal (amax / 127 far below 2^-25)", list(range(0x0001, 0x0021)), 0x0000, []), + ("all subnormal, negative", [0x8000 | b for b in range(0x0001, 0x0021)], 0x0000, []), + ("one normal among subnormals (scale 0.00787353515625)", [0x3F80] + list(range(0x0001, 0x0020)), 0x2008, [127]), + ("the clamp at an f16-subnormal scale (amax 178 x 2^-24: amax / 127 = 1.4016 x 2^-24, scale 2^-24, quotient 178)", + [0x3732], 0x0001, [127]), + ("quotient ties, to even (amax 127 x 2^-7, then k x 2^-7 for k = 0.5, 1.5, 2.5, 3.5, -2.5, -3.5, 126.5, and -0)", + [0x3F7E, 0x3B80, 0x3C40, 0x3CA0, 0x3CE0, 0xBCA0, 0xBCE0, 0x3F7D, 0x8000], 0x2000, [127, 0, 2, 2, 4, -2, -4, 126, 0]), + ("the f16 rounding tie (amax 3.7848949e-06: amax / 127 = 2^-25 exactly, between +0 and 2^-24, to even +0)", + [0x367E], 0x0000, []), + ("beside the tie (amax 3.7997961e-06: scale 2^-24, quotient 63.75)", [0x367F], 0x0001, [64]), + ("the division by the decoded scale (0.0119018555 / 0.0079345703125 = 1.5 exactly, to even 2; divided by amax / 127 " + "it would be 1.49982, code 1)", [0x3F81, 0x3C43], 0x2010, [127, 2]), + ("the largest finite scale (amax 8290304, scale 65280)", [0x4AFD, 0xCA7D] + [0x3F80] * 30, 0x7BF8, [127, -63]), + ("the scale overflows to inf (amax 8323072, the first BF16 amax with amax / 127 above f16's range: x / inf = +-0)", + [0x4AFE, 0xCA7E] + [0x3F80] * 30, 0x7C00, []), +) + + +def test_hand_computed_groups(): + """HC8-CASES: the groups of ``CASES`` (each one row of 32: ``gpr = 1``, ``srow = 8``); every positive BF16 ``amax`` + whose scale is a normal f16, alone in its group, has the code 127; and an up-shaped copy's layout. Both ``quantize`` + and ``hc8_quant_scalar``.""" + w = np.array([b + [0] * (32 - len(b)) for _, b, _, _ in CASES], np.uint16) + for who, (q, s) in (("quantize", quantize(w)), ("hc8_quant_scalar", hc8_quant_scalar(w, 1, 8))): + q, s = q.view(np.int8).reshape(len(CASES), 32), s.reshape(len(CASES), 8) + for (case, _, scale, codes), qi, si in zip(CASES, q, s): + assert si.tolist() == [scale] + [0] * 7 and qi.tolist() == codes + [0] * (32 - len(codes)), \ + f"HC8-CASES, {who}, {case}: scale bits {[hex(v) for v in si.tolist()]} codes {qi.tolist()}; " \ + f"the table's scale {scale:#06x} (padding slots 0) and codes {codes}, zero after" + + b = np.arange(0x0001, 0x7F80, dtype=np.uint16) # every positive finite BF16, the amax of a group + w = np.zeros((b.size, 32), np.uint16) + w[:, 0] = b + q, s = quantize(w) + normal = ((s[:, 0] & 0x7C00) != 0) & ((s[:, 0] & 0x7C00) != 0x7C00) + finite_from = (b.astype(np.uint32) << 16).view(np.float32) >= np.float32(127 * 2.0 ** -14) + assert normal.sum() == 3840 and np.array_equal(normal, finite_from & (s[:, 0] != 0x7C00)) \ + and (q[normal, 0].view(np.int8) == 127).all(), \ + f"HC8-CASES: the 3840 positive BF16 amax with a normal f16 scale (127 x 2^-14 <= amax, scale finite) each have " \ + f"the code 127: {int(normal.sum())} such amax, codes {sorted(set(q[normal, 0].view(np.int8).tolist()))}" + q_ref, sc_ref = hc8_quant_scalar(w[normal], 1, 8) + assert not (bad := _differing_groups(w[normal], q[normal], s[normal], q_ref, sc_ref)) \ + and np.array_equal(sc_ref.reshape(-1, 8), s[normal]), f"HC8-CASES, the 3840 amax through hc8_quant_scalar: {bad}" + + w = f32_to_bf16((np.random.default_rng(10).standard_normal((4, 320)) * 0.05).astype(np.float32)) + q, s = quantize(w) + q_ref, sc_ref = hc8_quant_scalar(w, 10, 16) + copy = q.tobytes() + s.tobytes() + scales = np.frombuffer(copy, "/q`` ``U8 [rows, cols]`` at the table + entry's offset and ``hc8//s`` ``F16 [rows, srow]`` at that offset plus ``rows * cols``, whose ``aux_array``s + are ``quantize``'s codes (as int8) and scales (as uint16 bits) bit for bit, and ``nbytes`` the file's size. The + port's own check: basalt's registry gate (``src/kernels/hc8_parity.cpp:101``) is the read's, family 6's.""" + pack, copies = hc8_pack + table = hc8_read_table(pack.dir / "weights.pack") + rows = [] + for name in copies: + r, c, sr, off, _, _ = table[name] + rows += [dict(name=f"hc8/{name}/q", offset=off, nbytes=r * c, dtype="U8", shape=[r, c]), + dict(name=f"hc8/{name}/s", offset=off + r * c, nbytes=r * sr * 2, dtype="F16", shape=[r, sr])] + size = (pack.dir / "weights.pack").stat().st_size + for who, pf in (("returned", pack), ("opened again", PackFile(pack.dir))): + m = pf.manifest + assert m == dict(version=2, alignment=16384, pack="weights.pack", nbytes=size, slabs=[], aux=rows), \ + f"HC8-PACK ({who}): version 2, alignment 16384, nbytes the file's {size}, no slabs, and the aux rows " \ + f"hc8//q U8 [rows, cols] at the entry's offset, hc8//s F16 [rows, srow] at that plus rows * " \ + f"cols: {dict(m, aux=m['aux'][:2])}, the first of {len(m['aux'])} aux rows" + bad = [] + for name, w in copies.items(): + q, s = quantize(w) + if not (np.array_equal(pf.aux_array(f"hc8/{name}/q").view(np.int8), q.view(np.int8)) + and np.array_equal(pf.aux_array(f"hc8/{name}/s").view(np.uint16), s)): + bad.append(name) + assert not bad, f"HC8-PACK ({who}): aux_array(f'hc8/{{name}}/q') viewed as int8 equals the codes and " \ + f"aux_array(f'hc8/{{name}}/s') viewed as uint16 the scales, bit for bit: {len(bad)} copies differ, the " \ + f"first {bad[:1]}" diff --git a/third_party/NOTICE b/third_party/NOTICE index 807a6088..ca9100e3 100644 --- a/third_party/NOTICE +++ b/third_party/NOTICE @@ -137,6 +137,14 @@ Format: `` — adapted from / copied from `` `` @ `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`. +- `monolith/packs/basalt_hc8.py` — adapted from `src/kernels/cuda/hc_fused.cu:1171-1227` (MIT): `hc8_quant_kernel`'s + arithmetic re-implemented in numpy and `hc8_make`'s layout; the `BASALTH8` table of + `include/basalt/core/model_file.hpp:126-149` as `hc8_write` writes it (`src/core/model_file.cpp:438-485`); the matrix + lists of `src/core/verify.cpp:566-581` and `src/core/mtp.cpp:215-218`, `:488-503`, in the order `hc8_dump` writes + them (`src/core/verify.cpp:638-640`, `src/core/mtp.cpp:516-521`). License: `third_party/BASALT-LICENSE`. +- `tests/basalt_hc_ref.py`, `tests/contract/test_basalt_hc8.py` — adapted from `src/kernels/cuda/hc_fused.cu:1171-1197`, + `src/core/model_file.cpp:487-513` and `src/kernels/hc8_parity.cpp:69-99` (MIT): a scalar transcription of + `hc8_quant_kernel`, `hc8_read`'s checks and hc8_parity's matrices. 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 From 27d7491ec502dd11c86d7f8beaea85c340cf3551 Mon Sep 17 00:00:00 2001 From: Lance Woodson <65194841+woodsonl@users.noreply.github.com> Date: Tue, 20 Oct 2026 17:20:05 -0500 Subject: [PATCH 69/74] Port basalt's group dequantizers to Metal: fp32, fp16 and BF16 stores, bit for bit The net change of woodsonl/mlxstream#29 (fork merge commit 9c83a1a), as one commit on woodsonl/basalt-hc-copies-upstream. --- docs/design/flash-next.md | 14 +- docs/research/basalt-nvcc/dequant_bf16.md | 181 ++++++++ kernels/common/basalt_dequant16.metal | 178 ++++++++ kernels/common/basalt_fp.metal | 26 +- monolith/kernels.py | 55 +++ .../test_basalt_dequant16_builders.py | 67 +++ tests/kernels/test_basalt_prompt_dequant.py | 430 ++++++++++++++++++ third_party/NOTICE | 23 +- 8 files changed, 964 insertions(+), 10 deletions(-) create mode 100644 docs/research/basalt-nvcc/dequant_bf16.md create mode 100644 kernels/common/basalt_dequant16.metal create mode 100644 tests/contract/test_basalt_dequant16_builders.py create mode 100644 tests/kernels/test_basalt_prompt_dequant.py diff --git a/docs/design/flash-next.md b/docs/design/flash-next.md index 16340fa1..57849526 100644 --- a/docs/design/flash-next.md +++ b/docs/design/flash-next.md @@ -103,11 +103,11 @@ ones this pack runs. (`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`, `hc_fused.md` for the - hyper-connection read, its router and the int8 copies, `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 + hyper-connection read, its router and the int8 copies, `dequant.md` for the GGUF dequantizers, `dequant_bf16.md` + for the prompt path's group 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 @@ -384,6 +384,7 @@ counters that must move, repeats that must be bitwise identical (`qsa_dec_attn_p | `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 | +| `elementwise_parity` (its `dequant_bf16` check, `:438-467`) | the BF16 dequantizer's NaN store and a finite block beside it | `if (!((q[(size_t) j] & 0x7FFFu) > 0x7F80u)) ++dq_wrong;` (`:459`); `if (wrong \|\| dq_wrong) ++bad;` (`:467`) | 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: @@ -405,7 +406,8 @@ These basalt tests do not run on this pack's path: - `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`). + `iq_embed_rows` (`src/kernels/cuda/iq_kernels.cu:2478-2483`). Its `dequant_bf16` check (`:438-467`) runs the prompt + path's dequantizer and is in the table above. - 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. diff --git a/docs/research/basalt-nvcc/dequant_bf16.md b/docs/research/basalt-nvcc/dequant_bf16.md new file mode 100644 index 00000000..443d170f --- /dev/null +++ b/docs/research/basalt-nvcc/dequant_bf16.md @@ -0,0 +1,181 @@ +# basalt's GGUF block dequantizers to fp16, BF16 and fp32 as nvcc compiles them + +What NVIDIA's compiler emits at every rounding site of `src/kernels/cuda/dequant_bf16.cu` (one thread per 32-value +group, GGUF blocks to fp16, BF16 or fp32), read from the sm_120 SASS, and the Metal form the port writes at each +site. The prompt path runs the fp16 entry, `dequant_f16`, ahead of every `Gemm::native` product +(`src/prefill/gemm.cu:169-185`); the BF16 and fp32 entries run only in tests. This page is the authority the Metal +kernel follows (`docs/design/flash-next.md`, invariant 5). + +Basalt paths are relative to commit `b4c63b55754637f4c72ad53a0f791d425f71eb36`; `path:a-b` means lines a to b there, +and a bare `:N` is a line of `src/kernels/cuda/dequant_bf16.cu` unless another file is named. + +## Method + +- **Date.** October 18, 2026. +- **Sources.** `src/kernels/cuda/dequant_bf16.cu` with the basalt headers it includes inlined under `#line` markers: + `include/basalt/kernels/dequant_bf16.hpp` and `include/basalt/kernels/iq_kernels.hpp`. System headers stay + `#include`s. Only basalt's public MIT source was sent. +- **Compiler.** Compiler Explorer's public API (`POST https://godbolt.org/api/compiler/nvcc130/compile`, + `produceDevice`): NVCC 13.0.0, `Cuda compilation tools, release 13.0, V13.0.48` (`Build + cuda_13.0.r13.0/compiler.36260728_0`). Both the PTX and the `SASS (sm_120)` listings were read. +- **Flags.** The file is in the `kernels` library's source list (`CMakeLists.txt:159`) and not in the + `--use_fast_math` list (`:186-202`); the project sets no `CMAKE_CUDA_FLAGS`, defaults to Release (`:12-14`) and + builds for compute capability 12.0 only (`:3-4`, `:26-31`). nvcc's defaults hold: `-ftz=false -prec-div=true + -prec-sqrt=true -fmad=true`. userArguments, exactly: `-arch=sm_120 -lineinfo -O3 -DNDEBUG + '-DBASALT_VERSION="0.0.1"'`. +- **Translation units.** The whole file's SASS passes Compiler Explorer's 5,000-line listing cap, so it was sent as + seven units, each the whole file with the line numbering kept, the host launcher (`:207-240`) and the public entries + (`:254-276`) blanked, and explicit instantiations of `dequant_kernel` appended: for each output type + T (fp16 `H16`, BF16 `uint16_t`, fp32 `float`) one unit with the vector store (`VEC = true`) for types 2, 6, 7, 8, + 20, 42 (Q4_0, Q5_0, Q5_1, Q8_0, IQ4_NL, Q2_0) and one for types 11, 12, 13, 14, 23 (Q3_K, Q4_K, Q5_K, Q6_K, + IQ4_XS), and a seventh with the scalar store (`VEC = false`) for fp16 and types 8, 13, 14, 23, the types + `dequant_f16_parity` runs through both stores. A kernel's code depends only on its own body and the device functions + it calls, so the split changes no instruction. Every listing is complete. +- **Reading.** Every float instruction of each instantiation was matched to its source line (from `-lineinfo`) and, + where an expression has several products or terms, to its operands through the registers of the full listing. + +## Summary + +- **Use.** The prompt path runs `dequant_f16` only, inside `Gemm::native` (`src/prefill/gemm.cu:178`, `:183`), for + every weight matrix of a native type it multiplies; the fp32 and BF16 entries run only in tests. Each call converts + a slice of a matrix's rows, so its arguments are the model's, not per-step values (invariant 4). +- **No approximate operation.** Each value is a product of an fp16 scale and small integers: `FMUL` (and `FFMA` for + Q4_K, Q5_K and Q5_1's `d1 * q - m1` and `q * d + m`), exact conversions (`HADD2.F32` for the fp16 scale, + `I2FP`/`I2F` for the integers), then the stored image: `F2FP.F16.F32.PACK_AB` for fp16, integer rounding for BF16, + nothing for fp32. No `.FTZ`, no `MUFU` but the index divisions'. +- **Exact by construction.** Every product is exact and none is subnormal, for every finite fp16 scale [M] (section 2), + so the fp32 values are d · P exactly, and Q4_K's, Q5_K's and Q5_1's one rounding is the same with or without the + contraction. Plain Metal arithmetic therefore gives CUDA's values bit for bit, with `fma()` where the SASS has `FFMA`. + The stored images follow section 1: `cuda_nan_f16(f16_bits(v))` for fp16, `f2bf(cuda_nan(v))` for BF16 (this + file's `f2bf` keeps a NaN a NaN, unlike `kernels.cu`'s `bf`), `cuda_nan(v)` for fp32. +- **Invariance.** One thread per 32-value group; a value depends only on its block's bytes, never on the slice, the + grid or the store form (`dequant_f16_parity` checks the vector and scalar stores bitwise). +- **Reuse.** `h2f`, `f16_bits`, `cuda_nan`, `cuda_nan_f16` (`kernels/common/basalt_fp.metal`). The IQ4_NL codebook + and the Q4_K and Q5_K scale unpacking are the port's own copies under basalt's names, `kv_iq4nl` and `scale_min_k4` + in `kernels/common/basalt_dequant16.metal`: `kernels/common/basalt_dequant.metal` defines its codebook beside + decode's kernel, whose `#error` refuses six of the ten types, so no other source includes it. For IQ4_NL, Q3_K, + IQ4_XS and Q2_0 the fp32 values equal `basalt_dequant.metal`'s (the same exact products of `iq_kernels.cu`'s + formulas); only the layout differs (one thread per 32-value group here, one threadgroup per 256-value superblock + there). + +## 1. Loads and output conversions + +`dequant_kernel` (`:170-188`) gives each thread one 32-value group: g = blockIdx.x · 256 + threadIdx.x +over rows · groups_per_row (`:173-174`), the row `row0 + g / groups_per_row` of the packed blocks, and the group's +32 outputs at `out + g * 32`. With `VEC` (the launcher's choice when `out` is 16-byte aligned, `:207-240`) the 32 +values are built in registers (`T tmp[32]`) and written as 16-byte stores (`:177-184`); without it `put` stores +each value. The values do not depend on the store: `dequant_f16_parity` checks the two forms bitwise (section 3). +Every group is independent, so no value depends on the slice (`row0`, `rows`) or the grid. The row and group indices +(`:175`, `g / groups_per_row` and `g % groups_per_row`) use the exact integer division of `__cuda_sm20_div_s64` +(`I2F.U64.RP`, `MUFU.RCP`, `F2I.U64.TRUNC`, its body charged to `:188`) and of its 32-bit fast path (`UI2F.U32.RP`, +`MUFU.RCP`, `F2I.FTZ.U32.TRUNC.NTZ`): index arithmetic, exact. + +| Line | Expression | SASS | Metal | +|---|---|---|---| +| `:17-19` | `h2f(p)`: `__half2float(__ushort_as_half((uint16_t) (p[0] \| (p[1] << 8))))` | two `LDG.E.U8.CONSTANT` and `IMAD h, hi, 0x100, lo`; `HADD2.F32 d, -RZ, h.H0_H0` (`cuda_fp16.hpp:708`): −0 + h, the exact fp16-to-fp32 conversion | `h2f(ushort(p[0] \| (p[1] << 8)))` (`basalt_fp.metal:115`): `float(as_type(h))`, exact, fp16 subnormals kept. A NaN scale's payload need not survive: every use of d is a multiply, whose NaN result is `cuda_nan`'s (below) | +| integer factors | `(float) (q - 1)`, `(float) (int8_t) b`, `(float) kv_iq4nl[..]`, `(float) sc`, … | `I2FP.F32.S32`, `I2FP.F32.U32`, `I2F.S8`, `I2F.S16`, `I2F.U16` | `float(n)`: exact, every factor is at most 128 in magnitude | +| `:30` | `put(H16*)`: `o[i].v = __half_as_ushort(__float2half_rn(v))` | `F2FP.F16.F32.PACK_AB h, b, a` (two values per instruction, `:184` with `VEC`; `F2FP.F16.F32.PACK_AB h, RZ, a`, `cuda_fp16.hpp:566`, without) | `cuda_nan_f16(f16_bits(v))` (`basalt_fp.metal`): round to nearest even, ±inf past 65504 (at 65520 and up), fp16 subnormals kept, a NaN as 0x7fff (`nan.md`) | +| `:20-27`, `:28` | `put(uint16_t*)`: `f2bf(v)` | `LOP3.LUT a, u, 0x7fffffff, RZ, 0xc0`; `ISETP.GT.U32.AND P, PT, a, 0x7f800000, PT`; NaN: `PRMT` (u >> 16) and `LOP3.LUT h, h, 0x40, RZ, 0xfc`; else `SHF.R.U32.HI t, RZ, 0x10, u`; `LOP3.LUT t, t, 0x1, RZ, 0xc0`; `IADD3 u, u, 0x7fff, t`; the high half | `f2bf(cuda_nan(v))`, a float argument as in basalt's signature (`:20`), then the same integer steps on its bits u: `(u & 0x7fffffffu) > 0x7f800000u ? ushort((u >> 16) \| 64u) : ushort((u + 0x7fffu + ((u >> 16) & 1u)) >> 16)`. v is a product, so CUDA's NaN is 0x7fffffff and its image 0x7fff; `cuda_nan` gives Metal the same, where this GPU's own NaN 0x7fc00000 would give 0x7fc0 | +| `:31` | `put(float*)`: `o[i] = v` | a plain store | `cuda_nan(v)` stored | + +Unlike `src/prefill/kernels.cu:31-35`'s `bf` (ported as `bf16_rne_nonan` in `kernels/common/basalt_fp.metal`), this +`f2bf` keeps a NaN a NaN (`:22-24`: "as in ggml_compute_fp32_to_bf16 and `bf16_from_f32`"), so the two files' BF16 +images of a NaN differ (0x7fff here, 0x8000 there); the port keeps both as basalt has them. + +## 2. Per-type arithmetic + +`group32` (`:41-166`) for each type. d, dmin, d_all and m are fp16 scales read by `h2f`; every other +factor is a small integer. This pack's projections use every type below but Q5_1 (`flash-next.md:218-219`; the +IQ-only types 16, 17, 18, 21, 22 and 29 go to `iq_dequant_f16` instead, `:259-267`, and this pack has none). + +| Type (id) | Lines | Value | SASS | Metal | +|---|---|---|---|---| +| Q2_0 (42): 64 values per 18-byte block | `:43-52` | `(float) (q - 1) * d`, q = `(b[2 + e / 4] >> ((e % 4) * 2)) & 3` (`:50-51`) | `IADD3 q, q, -0x1`; `I2FP.F32.S32 f, q`; `FMUL v, d, f` | `float(q - 1) * d` | +| Q4_0 (2) | `:53-59` | `(float) ((b[2 + j] & 0x0F) - 8) * d` (`:57`), the high nibbles for j + 16 (`:58`) | `I2FP.F32.S32`; `FMUL` | `float(n - 8) * d` | +| Q5_0 (6) | `:60-69` | `(float) (((b[6 + j] & 0x0F) \| xh0) - 16) * d` (`:67`), `xh1` for j + 16 (`:68`) | `I2FP.F32.S32`; `FMUL` | `float(n - 16) * d` | +| Q5_1 (7), not in this pack | `:70-80` | `(float) ((b[8 + j] & 15) \| xh0) * d + m` (`:78-79`) | `I2FP.F32.U32`; `FFMA v, d, f, m`: the front end contracts the expression | `fma(d, float(n), m)` | +| Q8_0 (8) | `:81-84` | `(float) (int8_t) b[2 + j] * d` (`:84`) | `I2F.S8`; `FMUL` | `float(char(b)) * d` | +| IQ4_NL (20) | `:85-91` | `d * (float) kv_iq4nl[b[2 + j] & 0xf]`, `[b[2 + j] >> 4]` (`:89-90`) | `I2F.S16` of the codebook entry; `FMUL` | `d * float(kv_iq4nl[i])` | +| Q3_K (11): 256 values per 110-byte block | `:92-113` | `dl = d_all * (float) (scales[is] - 32)` (`:111`); `dl * (float) ((int) ((q[t] >> shift) & 3) - ((hm[t] & m) ? 0 : 4))` (`:112`) | `I2FP.F32.S32`; `FMUL dl, d_all, s` (twice per group: t < 16 and t ≥ 16); `I2FP.F32.S32`; `FMUL v, dl, k` | `(d_all * float(s - 32)) * float(k)` | +| Q4_K (12): 144-byte blocks | `:114-122` | `d1 = d * (float) sc, m1 = dmin * (float) m` (`:120`); `d1 * (float) (hi ? (q[l] >> 4) : (q[l] & 0xF)) - m1` (`:122`) | `I2F.U16`; `FMUL d1`, `FMUL m1`; `I2F.U16`; `FFMA v, d1, f, -m1` | `fma(d1, float(n), -m1)` | +| Q5_K (13): 176-byte blocks | `:123-136` | as Q4_K (`:129`), the value `d1 * (float) (nib + ((qh[l] & u) ? 16 : 0)) - m1` (`:135`) | `I2F.U16`; two `FMUL`s; `I2FP.F32.U32`; `FFMA v, d1, f, -m1` | `fma(d1, float(n), -m1)` | +| Q6_K (14): 210-byte blocks | `:137-152` | `d * (float) sc[is + 2 * qu] * (float) (q - 32)` (`:151`) | `I2F.S8 s, sc`; `FMUL t, d, s`; `I2FP.F32.S32 f, q - 32`; `FMUL v, t, f`: left to right | `(d * float(sc)) * float(q - 32)` | +| IQ4_XS (23): 136-byte blocks | `:153-165` | `dl = d * (float) (ls - 32)` (`:159`); `dl * (float) kv_iq4nl[qs[j] & 0xf]`, `[qs[j] >> 4]` (`:162-163`) | `I2FP.F32.S32`; `FMUL dl`; `I2F.S16`; `FMUL v, dl, k` | `(d * float(ls - 32)) * float(kv_iq4nl[i])` | + +The Q4_K and Q5_K rows' `FFMA` is the fp16 and BF16 units' form at all 32 unrolled sites of `:122` and of `:135`; the +fp32 unit fuses one site of each line and keeps `FMUL p, d1, f` then `FADD v, -m1, p` at the other 31 (the PTX has +`mul.f32` and `sub.f32` at every site, so the fusion is ptxas's choice), which gives the same bits because d1 · q is +exact (below), so one `fma(d1, float(n), -m1)` serves all three outputs. + +**Every product is exact.** d has at most 11 significant bits and the integer factors at most 7 and 5 (Q6_K: +|sc| ≤ 128, |q − 32| ≤ 32; IQ4_XS: |ls − 32| ≤ 32, |kv| ≤ 127), so no product needs more than 23 bits. A host check +over every finite fp16 scale, subnormals and zeros included, and every factor product of each type +(`d · P` in binary64, compared with its binary32 rounding) confirms it [M]: every product is exact and none is +subnormal (the smallest nonzero one is 2^-24). The fp32 value is therefore d · P exactly, whatever the multiply order, +for every type but Q4_K, Q5_K and Q5_1, whose one rounding is the difference d1 · q − m1 (or the sum q · d + m): there +`FFMA` and a multiply followed by a subtraction give the same bits, since the product is exact; Metal writes `fma()` +where the SASS has `FFMA`, as the repository's ports do. These differences are multiples of 2^-24 too, so they are +zero or at least 2^-24: no fp32 subnormal occurs anywhere in this file, and this GPU's flushing changes no value. + +So plain Metal arithmetic gives CUDA's fp32 values bit for bit. What remains is the stored image (section 1): a NaN +(a NaN scale, or an infinite one times a zero factor) is CUDA's 0x7fffffff and becomes 0x7fff in fp16 and in BF16; +an infinite scale times a nonzero factor is ±inf; a finite value of at least 65520 in magnitude becomes ±inf in fp16. +The largest finite magnitude, 65504 · 4096, is far below fp32's range. + +The header of `kernels/common/basalt_dequant.metal` (`:16-17`), the port of the same formulas in `iq_kernels.cu` for +IQ4_NL, Q3_K, IQ4_XS and Q2_0, says "the products are not exact in general"; for those four types they are exact +too, by the check above. Its Metal form is unaffected: Metal's multiply is correctly rounded either way. + +## 3. Test coverage + +Four basalt tests call this file's entries directly. `dequant_f16_parity` and `dequant_bf16_test`, below, are not +registered with `ctest` and are run by hand. `elementwise_parity`, registered (`CMakeLists.txt:489-492`), checks +`dequant_bf16` on two Q8_0 blocks (`src/kernels/elementwise_parity.cpp:438-467`): with a NaN scale every BF16 value +must be a NaN, with scale 1 each must be ggml's BF16 of its integer. `q5_projection_parity` +(`src/kernels/q5_projection_parity.cpp`, built at `CMakeLists.txt:791-793`, run by hand on a real shard) checks +`dequant_f32` and `dequant_bf16` on Q5_1 only, which this pack does not use and the port refuses. The port runs the +first three in `tests/kernels/test_basalt_prompt_dequant.py`, `elementwise_parity`'s check verbatim. + +**`dequant_f16_parity`** (`src/kernels/dequant_f16_parity.cpp`, built at `CMakeLists.txt:515-517`). For IQ4_XS, +Q8_0, Q5_K and Q6_K (`:37-38`) on random blocks of 10240 × 2560 values (`:35`, `std::mt19937 rng(7)`, `:40`), with +every block's scale overwritten by the normal fp16 value `0.001f + (float) (rng() % 1000) * 1e-4f` (`:49`) and Q5_K's +dmin by 0.01 (`:51`), so that no NaN or infinite scale occurs. It counts three kinds of mismatch: + +``` + if (__half_as_ushort(__float2half_rn(f[(size_t) i])) != h[(size_t) i]) ++bad_f32; + if (h[(size_t) i] != h2[(size_t) i]) ++bad_scalar; +... + if (e > 1e-3 * std::fabs((double) v) + 1e-6) ++bad_cpu; +... + const bool ok = bad_f32 == 0 && bad_scalar == 0 && bad_cpu == 0; +``` + +(`:73`, `:74`, `:84`, `:98`): the fp16 output of the vector store against the fp32 path rounded to fp16, bitwise; the +same output through the scalar store (`out` misaligned by one element, `:64`), bitwise; and the first 64 rows (`:76`) against +the artifact's CPU dequantizers, within 10^-3 relative plus 10^-6. On Metal the first two hold by construction +(sections 1 and 2: the fp32 values are exact, and the store form changes none), and the port keeps both checks as +bit checks; the third needs a host reference of the four types, here `tests/contract/gguf_reference.py`'s float32 +values, bit for bit basalt's CPU dequantizers (`include/basalt/artifact/dequant.hpp`), compared in binary64 at +basalt's bound. The prompt path converts this pack's other six types too (Q2_0, Q3_K, Q4_K, IQ4_NL, Q4_0, Q5_0; +`flash-next.md:218-219`); the type list is the test's data, so the port runs the same three checks for all ten. + +**`dequant_bf16_test`** (`src/kernels/dequant_bf16_test.cpp`, `CMakeLists.txt:804-807`: "not a ctest: needs the full +model"). For each type `dequant_bf16_supported` accepts, the first four rows of the first two-dimensional tensor of +that type in the model's GGUF shards, against the artifact's CPU dequantizers: + +``` + const double tol = 1e-6 * std::fabs((double) ref[i]) + 1e-30; + if (e > tol) ++bad_f; +... + if (eh > std::ldexp(std::fabs((double) ref[i]), -8) + 1e-30) ++bad_h; +... + const bool ok = bad_f == 0 && bad_h == 0; +``` + +(`:91-92`, `:95`, `:99`): the fp32 path within 10^-6 relative (its header, `:6-7`: "the products are the reference's, +reordered at most") and the BF16 path within 2^-8 of the reference's magnitude. With every product exact (section 2) +the fp32 path equals any reference that forms the same products, whatever its order or contraction; only Q4_K's +and Q5_K's one rounding of d1 · q − m1 must be the reference's too, and it is the same rounding in either form. The +port runs these criteria on the committed pack fixture (`tests/contract/fixtures/basalt_pack.safetensors`), not on +the shards: the fixture's tensor of each of the ten types, rows 0 and n − 1, at most their first 1,024 bytes in whole +blocks (where basalt reads four whole rows); and on `dequant_f16_parity`'s blocks above. diff --git a/kernels/common/basalt_dequant16.metal b/kernels/common/basalt_dequant16.metal new file mode 100644 index 00000000..4a07f97c --- /dev/null +++ b/kernels/common/basalt_dequant16.metal @@ -0,0 +1,178 @@ +// Copyright (c) 2023-2026 The ggml authors (MIT) +// Copyright (c) 2026 Jesús Gulfo (MIT) +// Adapted from basalt (jesdga95/basalt) src/kernels/cuda/dequant_bf16.cu @ b4c63b55754637f4c72ad53a0f791d425f71eb36 +// (MIT; third_party/NOTICE), whose arithmetic transcribes ggml-org/llama.cpp ggml/src/ggml-quants.c +// (dequantize_row_q2_0/q4_0/q5_0/q8_0/q3_K/q4_K/q5_K/q6_K/iq4_nl/iq4_xs, dequant_bf16.cu:1-4) and +// ggml/src/ggml-common.h (kvalues_iq4nl) @ 3cf03257f219afbe7334045ff7c6a06ac68c627d (MIT; third_party/NOTICE). +// +// basalt's group dequantizer, dequant_kernel with group32 (:168-188, :40-166), as +// basalt_dequant_g32: one thread per 32-value group of a matrix's GGUF blocks, stored as fp32 (DQ_OUT 0, dequant_f32), +// fp16 bits (1, dequant_f16) or BF16 bits (2, dequant_bf16). DQ_TYPE: the ggml type id. Grid, bindings and params: +// monolith/kernels.py's basalt_dequant16_* builders. Needs basalt_fp.metal ahead of it. +// +// Numerics (docs/research/basalt-nvcc/dequant_bf16.md): for every finite fp16 scale, each product of a scale and the +// block's integers is exact and none is an fp32 subnormal [M] (the smallest nonzero value is 2^-24), so this GPU's +// flush never acts; the only fp32 rounding is Q4_K's and Q5_K's fma(d1, q, -m1); then one rounding into the output. +#pragma STDC FP_CONTRACT OFF + +struct DequantG32Params { long row_bytes; long row0; long rows; long groups_per_row; }; // :171-172, in order + +// h2f (:17-19): the little-endian fp16 field at p, any byte address, to fp32 (exact) +static inline float dq_h2f(device const uchar* p) { return h2f(ushort(p[0] | (p[1] << 8))); } + +constant char kv_iq4nl[16] = {-127, -104, -83, -65, -49, -35, -22, -10, 1, 13, 25, 38, 53, 69, 89, 113}; // :33 + +// :35-38: the 6-bit scale d and min m of group j (0..7) of a Q4_K or Q5_K block, from its 12 scale bytes at q +static inline void scale_min_k4(int j, device const uchar* q, thread int& d, thread int& m) { + if (j < 4) { d = q[j] & 63; m = q[j + 4] & 63; } + else { d = (q[j + 4] & 0xF) | ((q[j - 4] >> 6) << 4); m = (q[j + 4] >> 4) | ((q[j] >> 6) << 4); } +} + +// put (:28-31) by DQ_OUT. Every NaN here is a product on a NaN or infinite scale, sm_120's 0x7fffffff: the fp32 store +// takes cuda_nan, the BF16 store f2bf of it (0x7fff); __float2half_rn's NaN is cuda_nan_f16's 0x7fff. +#if DQ_OUT == 0 +typedef float DQ_T; +static inline void dq_put(device DQ_T* o, int i, float v) { o[i] = cuda_nan(v); } +#elif DQ_OUT == 1 +typedef ushort DQ_T; // basalt's H16 +static inline void dq_put(device DQ_T* o, int i, float v) { o[i] = cuda_nan_f16(f16_bits(v)); } +#elif DQ_OUT == 2 +typedef ushort DQ_T; // BF16 bits, basalt's uint16_t +static inline void dq_put(device DQ_T* o, int i, float v) { o[i] = f2bf(cuda_nan(v)); } +#else +#error "basalt_dequant16: unsupported DQ_OUT" +#endif + +// group32 (:40-166): the 32 values of group gi_in_row of the row whose blocks start at row_blocks, to out +static inline void dq_group32(device const uchar* row_blocks, int gi_in_row, device DQ_T* out) { +#if DQ_TYPE == 42 // Q2_0: 64 per block of 18 B (:43-52) + device const uchar* b = row_blocks + size_t(gi_in_row / 2) * 18; + const float d = dq_h2f(b); + const int e0 = (gi_in_row % 2) * 32; + for (int j = 0; j < 32; ++j) { + const int e = e0 + j; + const int q = (b[2 + e / 4] >> ((e % 4) * 2)) & 3; + dq_put(out, j, float(q - 1) * d); + } +#elif DQ_TYPE == 2 // Q4_0 (:53-59) + device const uchar* b = row_blocks + size_t(gi_in_row) * 18; + const float d = dq_h2f(b); + for (int j = 0; j < 16; ++j) { + dq_put(out, j, float((b[2 + j] & 0x0F) - 8) * d); + dq_put(out, j + 16, float((b[2 + j] >> 4) - 8) * d); + } +#elif DQ_TYPE == 6 // Q5_0 (:60-69) + device const uchar* b = row_blocks + size_t(gi_in_row) * 22; + const float d = dq_h2f(b); + const uint qh = uint(b[2]) | (uint(b[3]) << 8) | (uint(b[4]) << 16) | (uint(b[5]) << 24); + for (int j = 0; j < 16; ++j) { + const int xh0 = int(((qh >> j) << 4) & 0x10u); + const int xh1 = int((qh >> (j + 12)) & 0x10u); + dq_put(out, j, float(((b[6 + j] & 0x0F) | xh0) - 16) * d); + dq_put(out, j + 16, float(((b[6 + j] >> 4) | xh1) - 16) * d); + } +#elif DQ_TYPE == 8 // Q8_0 (:81-84) + device const uchar* b = row_blocks + size_t(gi_in_row) * 34; + const float d = dq_h2f(b); + for (int j = 0; j < 32; ++j) dq_put(out, j, float(char(b[2 + j])) * d); +#elif DQ_TYPE == 20 // IQ4_NL (:85-91) + device const uchar* b = row_blocks + size_t(gi_in_row) * 18; + const float d = dq_h2f(b); + for (int j = 0; j < 16; ++j) { + dq_put(out, j, d * float(kv_iq4nl[b[2 + j] & 0xf])); + dq_put(out, j + 16, d * float(kv_iq4nl[b[2 + j] >> 4])); + } +#elif DQ_TYPE == 11 // Q3_K: hmask[32] qs[64] scales[12] d (:92-113) + device const uchar* b = row_blocks + size_t(gi_in_row / 8) * 110; + const int gi = gi_in_row % 8, n = gi / 4, jj = gi % 4; + device const uchar* hm = b; + device const uchar* q = b + 32 + n * 32; + device const uchar* sc = b + 96; + const float d_all = dq_h2f(b + 108); + uint aux[4]; + for (int i = 0; i < 3; ++i) { // memcpy(aux, sc, 12): little-endian, any address + device const uchar* w = sc + 4 * i; + aux[i] = uint(w[0]) | (uint(w[1]) << 8) | (uint(w[2]) << 16) | (uint(w[3]) << 24); + } + const uint kmask1 = 0x03030303u, kmask2 = 0x0f0f0f0fu, tmp = aux[2]; + aux[2] = ((aux[0] >> 4) & kmask2) | (((tmp >> 4) & kmask1) << 4); + aux[3] = ((aux[1] >> 4) & kmask2) | (((tmp >> 6) & kmask1) << 4); + aux[0] = (aux[0] & kmask2) | (((tmp >> 0) & kmask1) << 4); + aux[1] = (aux[1] & kmask2) | (((tmp >> 2) & kmask1) << 4); + thread const char* scales = reinterpret_cast(aux); + const int shift = 2 * jj; + const uchar m = uchar(1u << (n * 4 + jj)); + for (int t = 0; t < 32; ++t) { + const int is = n * 8 + jj * 2 + (t >= 16 ? 1 : 0); + const float dl = d_all * float(scales[is] - 32); + dq_put(out, t, dl * float(int((q[t] >> shift) & 3) - ((hm[t] & m) ? 0 : 4))); + } +#elif DQ_TYPE == 12 // Q4_K: d dmin scales[12] qs[128] (:114-122) + device const uchar* b = row_blocks + size_t(gi_in_row / 8) * 144; + const int gi = gi_in_row % 8, j64 = gi / 2, hi = gi % 2; + const float d = dq_h2f(b), dmin = dq_h2f(b + 2); + int sc, m; + scale_min_k4(gi, b + 4, sc, m); + const float d1 = d * float(sc), m1 = dmin * float(m); + device const uchar* q = b + 16 + 32 * j64; + for (int l = 0; l < 32; ++l) dq_put(out, l, fma(d1, float(hi ? (q[l] >> 4) : (q[l] & 0xF)), -m1)); // FFMA +#elif DQ_TYPE == 13 // Q5_K: d dmin scales[12] qh[32] qs[128] (:123-136) + device const uchar* b = row_blocks + size_t(gi_in_row / 8) * 176; + const int gi = gi_in_row % 8, j64 = gi / 2, hi = gi % 2; + const float d = dq_h2f(b), dmin = dq_h2f(b + 2); + int sc, m; + scale_min_k4(gi, b + 4, sc, m); + const float d1 = d * float(sc), m1 = dmin * float(m); + device const uchar* qh = b + 16; + device const uchar* ql = b + 48 + 32 * j64; + const uchar u = uchar(1u << (2 * j64 + hi)); + for (int l = 0; l < 32; ++l) { + const int nib = hi ? (ql[l] >> 4) : (ql[l] & 0xF); + dq_put(out, l, fma(d1, float(nib + ((qh[l] & u) ? 16 : 0)), -m1)); // FFMA + } +#elif DQ_TYPE == 14 // Q6_K: ql[128] qh[64] scales[16] d (:137-152) + device const uchar* b = row_blocks + size_t(gi_in_row / 8) * 210; + const int gi = gi_in_row % 8, n = gi / 4, qu = gi % 4; + device const uchar* ql = b + 64 * n; + device const uchar* qh = b + 128 + 32 * n; + device const char* sc = reinterpret_cast(b + 192) + 8 * n; + const float d = dq_h2f(b + 208); + for (int l = 0; l < 32; ++l) { + const int is = l / 16; + int q; + if (qu == 0) q = (ql[l] & 0xF) | (((qh[l] >> 0) & 3) << 4); + else if (qu == 1) q = (ql[l + 32] & 0xF) | (((qh[l] >> 2) & 3) << 4); + else if (qu == 2) q = (ql[l] >> 4) | (((qh[l] >> 4) & 3) << 4); + else q = (ql[l + 32] >> 4) | (((qh[l] >> 6) & 3) << 4); + dq_put(out, l, d * float(sc[is + 2 * qu]) * float(q - 32)); // left to right + } +#elif DQ_TYPE == 23 // IQ4_XS: d scales_h scales_l[4] qs[128] (:153-164) + device const uchar* b = row_blocks + size_t(gi_in_row / 8) * 136; + const int ib = gi_in_row % 8; + const float d = dq_h2f(b); + const ushort scales_h = ushort(b[2] | (b[3] << 8)); + const int ls = ((b[4 + ib / 2] >> (4 * (ib % 2))) & 0xf) | (((scales_h >> (2 * ib)) & 3) << 4); + const float dl = d * float(ls - 32); + device const uchar* qs = b + 8 + 16 * ib; + for (int j = 0; j < 16; ++j) { + dq_put(out, j, dl * float(kv_iq4nl[qs[j] & 0xf])); + dq_put(out, j + 16, dl * float(kv_iq4nl[qs[j] >> 4])); + } +#else +// Q5_1 (7, :70-80) and the iq_only types (:251): no tensor of this pack has them; basalt_dequant16_macros refuses them +#error "basalt_dequant16: unsupported DQ_TYPE" +#endif +} + +// dequant_kernel (:170-188): thread g of rows * groups_per_row (256-thread threadgroups, +// :221-222) dequantizes group g % groups_per_row of row row0 + g / groups_per_row into out[32 g .. 32 g + 31]. The VEC +// form (:177-184) stores the same 32 values as 16-byte copies; it is not ported. +kernel void basalt_dequant_g32(device const uchar* blocks [[buffer(0)]], device DQ_T* out [[buffer(1)]], + constant DequantG32Params& p [[buffer(2)]], + uint tg [[threadgroup_position_in_grid]], uint tid [[thread_position_in_threadgroup]]) { + const long g = long(tg) * 256 + long(tid); // :173 + if (g >= p.rows * p.groups_per_row) return; // :174 + const long r = g / p.groups_per_row, gi = g % p.groups_per_row; // :175 + device const uchar* row = blocks + (p.row0 + r) * p.row_bytes; // :176 + dq_group32(row, int(gi), out + g * 32); // :186 +} diff --git a/kernels/common/basalt_fp.metal b/kernels/common/basalt_fp.metal index e9db9808..fd7cda0b 100644 --- a/kernels/common/basalt_fp.metal +++ b/kernels/common/basalt_fp.metal @@ -1,7 +1,8 @@ // 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 +// src/kernels/cuda/q5k_head.cu, src/kernels/cuda/dequant_bf16.cu, src/prefill/kernels.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). @@ -36,6 +37,10 @@ // - 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. +// - f2bf, bf16_rne_nonan: fp32 to BF16 bits by integer round to nearest even, with and without basalt's NaN case. +// f2bf (dequant_bf16.cu's) keeps a NaN a quiet NaN: the dequantizers' BF16 stores take it. bf16_rne_nonan +// (prefill/kernels.cu's bf) rounds a NaN's bits like any others: the prompt path's BF16 operand images take it. +// Both take the float, carrying sm_120's NaN (cuda_nan) as basalt's arithmetic leaves it. // - 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. @@ -125,6 +130,25 @@ static inline float cuda_nan(float x) { // 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; } +// basalt src/kernels/cuda/dequant_bf16.cu:20-27 `f2bf`, which follows ggml's ggml_compute_fp32_to_bf16 +// (ggml/src/ggml-impl.h): fp32 to BF16 bits, round to nearest even in integer arithmetic; a finite value at or above +// 0x7f7f8000 in magnitude carries into the infinity of its sign; an fp32 subnormal rounds by its bits (as_type keeps +// them); a NaN stays a NaN, its sign and top payload bits with the quiet bit set. A float parameter, as basalt's: a +// uint argument would be converted by value, not reinterpreted. +static inline ushort f2bf(float f) { + uint u = as_type(f); + if ((u & 0x7fffffffu) > 0x7f800000u) return ushort((u >> 16) | 64u); + u += 0x7fffu + ((u >> 16) & 1u); + return ushort(u >> 16); +} +// basalt src/prefill/kernels.cu:31-35 `bf`: f2bf without the NaN case, so a NaN's bits round like any others (32-bit +// wrap-around): sm_120's 0x7fffffff gives 0x8000 (-0), 0xffffffff 0x0000, 0x7f800001 0x7f80 (+inf), 0x7fc00000 0x7fc0. +static inline ushort bf16_rne_nonan(float f) { + uint u = as_type(f); + u += 0x7fffu + ((u >> 16) & 1u); + return ushort(u >> 16); +} + // 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; }; diff --git a/monolith/kernels.py b/monolith/kernels.py index ed084a5e..421333fe 100644 --- a/monolith/kernels.py +++ b/monolith/kernels.py @@ -11,6 +11,7 @@ from .formats import FORMATS from .formats.blm import PackInfo +from .formats.gguf import ggml_row_bytes from .backends.metal.context import current_backend from .resources import kernel_root @@ -701,6 +702,60 @@ def basalt_q5k_proxy_params(n_cap: int, *, row0: int = 0, n: int = 0, n_rows: Op return struct.pack(" str: + """basalt's ``dequant_kernel`` (dequant_bf16.cu:168-188) as ``basalt_dequant_g32``, one thread per 32-value group: + ``basalt_dequant16_grid`` threadgroups of 256 threads, 1-D. Bindings: 0 the matrix's blocks from its row 0, at + least (row0 + rows) * row bytes at any byte offset, of which rows [row0, row0 + rows) are read; 1 the output, + exactly rows * cols values, row-major (float for "f32", fp16 or BF16 bits for "f16" and "bf16"); 2 the + ``basalt_dequant16_params`` record.""" + return PRELUDE + template("basalt_fp.metal") + template("basalt_dequant16.metal") + + +def basalt_dequant16_macros(type_id: int, out: str) -> Dict[str, str]: + """``DQ_TYPE`` (the ggml type id) and ``DQ_OUT`` (``out``: "f32", "f16" or "bf16", as dequant_f32, dequant_f16 and + dequant_bf16 store). basalt also takes Q5_1 (dequant_bf16.cu:194) and hands the i-quant types of ``iq_only`` to + iq_kernels.cu (:251, :261-265, :270-274); no tensor of this pack has them, so a type outside ``DEQUANT16_TYPES`` + is refused.""" + if type_id not in DEQUANT16_TYPES: + raise ValueError(f"basalt_dequant16: unsupported ggml type {type_id}") + if out not in DEQUANT16_OUT: + raise ValueError(f"basalt_dequant16: unsupported output {out!r}") + return {"DQ_TYPE": str(type_id), "DQ_OUT": str(DEQUANT16_OUT[out])} + + +def basalt_dequant16_params(type_id: int, row0: int, rows: int, cols: int) -> bytes: + """``DequantG32Params`` (row bytes, row0, rows, groups per row: basalt's int64_t arguments, dequant_bf16.cu:171-172) + for rows [row0, row0 + rows) of ``cols`` values of type ``type_id``. Refused: a type ``basalt_dequant16_macros`` + refuses; basalt's cols not whole blocks and rows <= 0 (:210-214) and its failed launch (``basalt_dequant16_grid``); + row0 < 0, the port's own (a load before the binding).""" + if type_id not in DEQUANT16_TYPES: + raise ValueError(f"basalt_dequant16: unsupported ggml type {type_id}") + if rows <= 0 or row0 < 0: + raise ValueError(f"basalt_dequant16: rows must be positive and row0 non-negative, got {rows} and {row0}") + row_bytes = ggml_row_bytes(type_id, cols) + basalt_dequant16_grid(rows, cols) + return struct.pack(" Tuple[int, int]: + """(threadgroups, threads per threadgroup): ceil(rows * cols / 32 / 256) threadgroups of 256 (dequant_bf16.cu:216, + :221-222). A grid of no threadgroup or of more than ``CUDA_GRID_X`` is refused: basalt's launch fails on either + and it exits (:238-239).""" + grid = -(-(rows * (cols // 32)) // DEQUANT16_THREADS) + if not 0 < grid <= CUDA_GRID_X: + raise ValueError(f"basalt_dequant16: {rows} x {cols} values need {grid} threadgroups, outside 1..{CUDA_GRID_X}") + return grid, DEQUANT16_THREADS + + # ---- the other decode kernels ------------------------------------------------------------------------------- MSL_TENSOR_OPS = 4 << 16 # the language version the tensor-ops kernels need (MSL 4.0: , MPP) diff --git a/tests/contract/test_basalt_dequant16_builders.py b/tests/contract/test_basalt_dequant16_builders.py new file mode 100644 index 00000000..55178be6 --- /dev/null +++ b/tests/contract/test_basalt_dequant16_builders.py @@ -0,0 +1,67 @@ +# SPDX-License-Identifier: MIT +# Copyright (c) 2026 Jesús Gulfo +# adapted from basalt (jesdga95/basalt) src/kernels/cuda/dequant_bf16.cu:190-240 +# @ b4c63b55754637f4c72ad53a0f791d425f71eb36 (MIT; third_party/NOTICE): geometry's type table and launch's refusals +# and grid. +"""The builders of basalt's group dequantizers (monolith/kernels.py ``basalt_dequant16_*``, for +kernels/common/basalt_dequant16.metal), without the GPU: the ten types of this pack with basalt's block geometry, the +params record and grid basalt's launch computes, and every refusal, each input with one defect refused by that +defect's own check (its message). The kernel's tests are tests/kernels/test_basalt_prompt_dequant.py.""" + +import struct + +import pytest + +from monolith import kernels +from monolith.formats.gguf import GGML_TYPES + +# basalt's geometry (dequant_bf16.cu:190-205): ggml type -> (values, bytes) per block. Q5_1 (7) has no tensor here. +GEOMETRY = {2: (32, 18), 6: (32, 22), 7: (32, 24), 8: (32, 34), 20: (32, 18), 11: (256, 110), 12: (256, 144), + 13: (256, 176), 14: (256, 210), 23: (256, 136), 42: (64, 18)} + + +def test_types_and_geometry(): + assert sorted(kernels.DEQUANT16_TYPES) == sorted(set(GEOMETRY) - {7}) and len(kernels.DEQUANT16_TYPES) == 10 + for t in kernels.DEQUANT16_TYPES: + assert GGML_TYPES[t][1:] == GEOMETRY[t], t + + +@pytest.mark.parametrize("t", kernels.DEQUANT16_TYPES) +def test_params_are_basalts_arguments(t): + be, bb = GEOMETRY[t] + # dequant_bf16.cu:215: row_bytes = cols / be * bb, gpr = cols / 32, with row0 and rows as given + assert struct.unpack("= 0.001, so fixture E brings its zero); + at least 1,000 distinct values, counted on the first 64 rows.""" + t = request.param + raw = f_blocks[t] + blk = raw.reshape(-1, GGML_TYPES[t][2]) + for at in [D_AT.get(t, 0)] + [2] * (t in (12, 13)): + s = blk[:, at: at + 2].copy().view(np.float16) + assert np.isfinite(s).all() and (s != 0).all(), at + ref = reference(t, raw) + assert ref.min() < 0 < ref.max() and (t == 20 or (ref == 0).any()) + assert np.unique(ref[:64]).size >= 1000 + return t, raw, ref + + +# Fixture E's six blocks, appended to F's row 0: each F's first block of the type with its fp16 d (and Q4_K's and +# Q5_K's dmin where one is given, else F's 0x211f) set, as (block class, d, dmin). The overflow block's codes are +# EXTREME's; the last two blocks are class E-tiny (eng-review D25). +E_BLOCKS = (("nan", 0x7E00, None), ("inf", 0x7C00, None), ("overflow", 0x7BFF, None), ("-0", 0x8000, 0x0000), + ("2^-24", 0x0001, 0x0001), ("0x03ff", 0x03FF, 0x03FF)) + +# The overflow block's codes: (first byte, end, the bytes repeated over them) per type, every value 65504 times an +# integer of magnitude 2 or more, of both signs where the type has them, so every fp16 value overflows to +-inf and +# every fp32 and BF16 one stays finite (at most 65504 * 4096, dequant_bf16.md section 2). +EXTREME = { + 2: ((2, 18, (0x0F,)),), # Q4_0: nibbles 15 and 0: +7, -8 + 6: ((2, 6, (0xFF, 0xFF, 0, 0)), (6, 22, (0x0F,))), # Q5_0: qh bits 0-15, so codes 31 and 0: +15, -16 + 8: ((2, 34, (0x7F, 0x80)),), # Q8_0: +127, -128 + 11: ((0, 96, (0xFF, 0)), (96, 108, (0,))), # Q3_K: scales 0 (-32); q 3 with hmask, 0 without: -96, +128 + 12: ((4, 144, (0xFF,)),), # Q4_K: sc = m = 63, nibbles 15 (never negative: >= -m1) + 13: ((4, 176, (0xFF,)),), # Q5_K: sc = m = 63, codes 31 + 14: ((0, 192, (0xFF, 0)), (192, 208, (0x80,))), # Q6_K: scales -128, codes 63 and 0 (31, -32): -3968, +4096 + 20: ((2, 18, (0x0F,)),), # IQ4_NL: entries 113 and -127 + 23: ((2, 8, (0,)), (8, 136, (0x0F,))), # IQ4_XS: ls 0 (-32), entries 113 and -127: -3616, +4064 + 42: ((2, 18, (0xFF,)),), # Q2_0: codes 3: +2 (code 0's -1 stays finite: -65504) +} + + +@pytest.fixture(params=kernels.DEQUANT16_TYPES, ids=lambda t: GGML_TYPES[t][0]) +def e(request, f_blocks): + """Fixture E for one type (TG 3.4, 4.4; eng-review D25): one row, F's row 0 and then E_BLOCKS' six blocks, every + edge beside ordinary blocks. A NaN scale (every value NaN) and +inf (each value the infinity of its code's sign, a + zero code NaN) on F's codes; 65504 on EXTREME's codes (every fp16 value +-inf, every fp32 and BF16 one finite); -0 + on F's codes with Q4_K's and Q5_K's dmin +0 (fma(-0, n, -(+0)) is -0, where dmin -0 would give +0); class E-tiny, d + (and dmin) 2^-24 and 0x03ff, the largest fp16 subnormal: every fp32 value n * 2^-24 with |n| < 2^24, exact and + normal, the fp16 ones under 2^-14 fp16 subnormals. (type id, blocks [1, row bytes], each value's block class, host + values [1, n]).""" + t = request.param + _, be, bb = GGML_TYPES[t] + row = f_blocks[t][0] + at = D_AT.get(t, 0) + blocks = [row] + for name, d, dmin in E_BLOCKS: + b = row[:bb].copy() + b[at: at + 2] = np.array([d], " 1e-3 * std::fabs((double) v) + 1e-6) ++bad_cpu;``, and no non-finite output (a NaN's e compares false). + On Q4_0, Q5_0, Q3_K, Q4_K, IQ4_NL and Q2_0, which dequant_f16_parity does not draw: basalt's bound, extended beyond + its fixture (D5).""" + t, raw, ref = f + rows = min(ROWS, 64) + hv = run_dq(t, "f16", raw, ROWS, COLS)[: rows * COLS].view(np.float16).astype(np.float64) + v = ref[:rows].ravel().astype(np.float64) + bad_cpu = np.count_nonzero(np.abs(hv - v) > 1e-3 * np.abs(v) + 1e-6) + nonfinite = np.count_nonzero(~np.isfinite(hv)) + assert bad_cpu == 0 and nonfinite == 0, f"bad_cpu {bad_cpu}, non-finite {nonfinite}" + + +def test_f16_non_finite_scales(e): + """F16-E, added (TG 3.4; eng-review D25): fixture E through the fp16 store (dequant_f16) and the fp32 one, bit for + bit the twins (run_e): a NaN scale's values 0x7fff (0x7fffffff), an infinite one's +-0x7c00 or 0x7fff, the -0 + scale's 0x8000 (0x80000000); 65504 on extreme codes overflows every fp16 value to +-inf; class E-tiny holds a + nonzero fp16 subnormal, which the conversion keeps (plan R2). basalt's fixture avoids these scales (:45).""" + h, cls = run_e(e, "f16") + assert np.isin(h[cls == "overflow"], [0x7C00, 0xFC00]).all(), "a finite fp16 value from 65504 on extreme codes" + tiny = h[np.isin(cls, ["2^-24", "0x03ff"])] & 0x7FFF + assert ((tiny > 0) & (tiny < 0x400)).any(), "no nonzero fp16 subnormal in class E-tiny" + run_e(e, "f32") + + +def test_f32_against_the_cpu(p, f): + """B16-1 (dequant_bf16_test.cpp:90-92): the fp32 output (dequant_f32, :74) against the CPU dequantizer + (gguf_reference, bit for bit basalt's cpu_block, TG 4.1) in double, ``const double e = std::fabs((double) gf[i] - + ref[i]);`` ``const double tol = 1e-6 * std::fabs((double) ref[i]) + 1e-30;`` ``if (e > tol) ++bad_f;``, and no + non-finite output (a NaN's e compares false), on fixture P's tensor of the type and on fixture F. On F: basalt's + bound, extended beyond its fixture (D5).""" + t = f[0] + for name, raw, ref in (p[t], ("F",) + f[1:]): + gf = run_dq(t, "f32", raw, *ref.shape).view(np.float32).astype(np.float64) + v = ref.ravel().astype(np.float64) + bad_f = np.count_nonzero(np.abs(gf - v) > 1e-6 * np.abs(v) + 1e-30) + nonfinite = np.count_nonzero(~np.isfinite(gf)) + assert bad_f == 0 and nonfinite == 0, f"{name}: bad_f {bad_f}, non-finite {nonfinite}" + + +def test_bf16_within_the_bound(p, f): + """B16-2 (:94-95): the BF16 output (dequant_bf16, :75), widened by bf16_to_f32 (:40-45, ``(uint32_t) h << 16``), + against the CPU dequantizer in double, ``const double eh = std::fabs((double) bf16_to_f32(gh[i]) - ref[i]);`` + ``if (eh > std::ldexp(std::fabs((double) ref[i]), -8) + 1e-30) ++bad_h;``, and no non-finite output, on fixtures P + and F. On F: basalt's bound, extended beyond its fixture (D5).""" + t = f[0] + for name, raw, ref in (p[t], ("F",) + f[1:]): + gh = (run_dq(t, "bf16", raw, *ref.shape).astype(np.uint32) << 16).view(np.float32).astype(np.float64) + v = ref.ravel().astype(np.float64) + bad_h = np.count_nonzero(np.abs(gh - v) > np.ldexp(np.abs(v), -8) + 1e-30) + nonfinite = np.count_nonzero(~np.isfinite(gh)) + assert bad_h == 0 and nonfinite == 0, f"{name}: bad_h {bad_h}, non-finite {nonfinite}" + + +def test_outputs_bitwise(p, f): + """B16, added (TG 4.4): on fixtures P and F, the fp32 output bit for bit the host dequantizer's value and the BF16 + output its f2bf (``stored``: monolith.formats.fp.f32_to_bf16 of the cuda_nan'd value). B16-2's bound also passes a + tie broken away from zero and some truncations (TG 4.3); this pins f2bf's ties to even.""" + t = f[0] + for name, raw, ref in (p[t], ("F",) + f[1:]): + for out in ("f32", "bf16"): + bad = np.count_nonzero(run_dq(t, out, raw, *ref.shape) != stored(ref, out).ravel()) + assert bad == 0, f"{name} {out}: {bad} of {ref.size} values differ" + + +def test_pack_has_every_type(p): + """B16-3 (:97-100, :106-107): basalt gates each type it finds, ``const bool ok = bad_f == 0 && bad_h == 0;``, and + prints, ungated, how many types it checked, so a file without a type passes. The port's pack fixture is fixed, so + fixture P must hold every type of DEQUANT16_TYPES (TG 4.4), each from TG 4.2's tensor.""" + assert set(p) == set(kernels.DEQUANT16_TYPES) + assert {t: tensor for t, (tensor, _, _) in p.items()} == P_TENSORS + + +def test_bf16_non_finite_scales(e): + """B16, added (TG 4.4; eng-review D25): fixture E through the fp32 store (dequant_f32) and the BF16 one + (dequant_bf16), bit for bit the twins (run_e): a NaN scale's values 0x7fffffff and 0x7fff (f2bf of sm_120's NaN; + of this GPU's own NaN, 0x7fc00000, it would be 0x7fc0), an infinite one's signed infinities (0x7f800000, 0xff800000; + 0x7f80, 0xff80) or that NaN, the -0 scale's 0x80000000 and 0x8000; 65504 on extreme codes stays finite in both, and + class E-tiny's nonzero values, n * 2^-24, are normal in both. Of basalt's fixtures only elementwise_parity's + NaN-scale Q8_0 block (DQ-1) has one of these scales: dequant_bf16_test reads real tensors, and + dequant_f16_parity.cpp:45 gives every block a normal one.""" + run_e(e, "f32") + run_e(e, "bf16") + + +def test_bf16_nan_scale_stays_nan(): + """DQ-1: elementwise_parity's dequant_bf16 check (basalt src/kernels/elementwise_parity.cpp:438-467), its fixture + verbatim (:441-447): two Q8_0 blocks, the first with the fp16 NaN scale 0x7e00 and codes j - 16, the second with + scale 1.0 and codes 3 j - 50, dequantized as :453's ``dequant_bf16(8, db, 0, 2, 32, dq, nullptr)`` into exactly 64 + values. Its criteria verbatim, ``if (!((q[(size_t) j] & 0x7FFFu) > 0x7F80u)) ++dq_wrong;`` (:459) and ``if + (q[(size_t) (32 + j)] != ggml_bf16(vb)) ++dq_wrong;`` (:463; its ggml_bf16, :418-421, is basalt_emu.bf16_bits on + these finite values), gated as ``dq_wrong`` (:467; the gate's other count, ``wrong``, is f32_to_bf16_bulk's, + src/kernels/cuda/elementwise.cu:172, not ported here). Added, bitwise: the NaN row is all 0x7fff, f2bf of sm_120's + NaN (this GPU's own NaN, 0x7fc00000, would store 0x7fc0, which :459 accepts).""" + j = np.arange(32) + blk = np.zeros(2 * 34, np.uint8) + blk[0:2] = (0x00, 0x7E) # fp16 quiet NaN (:442) + blk[34:36] = (0x00, 0x3C) # fp16 1.0 (:443) + blk[2:34] = (j - 16).astype(np.int8).view(np.uint8) # :445 + blk[36:68] = (3 * j - 50).astype(np.int8).view(np.uint8) # :446 + q = run_dq(8, "bf16", blk, 2, 32) # :453 + dq_wrong = np.count_nonzero(~((q[:32] & 0x7FFF) > 0x7F80)) # :459, row 0: NaN scale -> NaN + dq_wrong += np.count_nonzero(q[32:] != emu.bf16_bits((3 * j - 50).astype(np.float32))) # :460-463, row 1 + assert dq_wrong == 0, f"dequant_bf16 {dq_wrong} of 64 wrong" + assert (q[:32] == 0x7FFF).all(), f"the NaN row stores {sorted({hex(v) for v in q[:32].tolist()})}, not 0x7fff" + + +@pytest.mark.parametrize("out", kernels.DEQUANT16_OUT) +def test_rows_do_not_depend_on_the_slice(f, out): + """DQ-2 (the plan's section 1 invariants): a row's values are a pure function of its blocks, whatever row0, row + count and grid select it, as basalt's slice branch relies on (src/prefill/gemm.cu:171-182: dequant_f16 of rows [r0, + r0 + n) from the whole weight's blocks). Fixture F's rows 0-63 dispatched whole, then rows [row0, row0 + rows) of + the same 64 rows' blocks for (0, 1), (1, 1), (5, 7) and (63, 1), each bit for bit its rows of the whole. Every + other test but DQ-3 (row0 2) dispatches from row 0.""" + t, raw, _ = f + whole = run_dq(t, out, raw[:64], 64, COLS) + for row0, rows in ((0, 1), (1, 1), (5, 7), (63, 1)): + got = run_dq(t, out, raw[:64], rows, COLS, row0=row0) + bad = np.count_nonzero(got != whole[row0 * COLS: (row0 + rows) * COLS]) + assert bad == 0, f"rows {row0}..{row0 + rows - 1}: {bad} of {got.size} values differ from the whole's" + + +@pytest.mark.parametrize("out", kernels.DEQUANT16_OUT) +def test_stores_stay_inside_the_output(f, out): + """DQ-3 (basalt_dequant_g32's bindings): rows 2-4 of a 5-row, 256-column matrix of fixture F's blocks, the blocks + buffer exactly 5 rows' bytes, the output bound between two guards of 64 values: 24 groups in one threadgroup of + 256, whose other 232 threads return at the kernel's bound (dequant_bf16.cu:174). Both guards keep every 0xFF byte + and the 768 values between them are bit for bit the twins. Under MTL_SHADER_VALIDATION=1 a read past the blocks or + a store past the output buffer is a report; a store into a guard is caught here.""" + t, raw, _ = f + _, be, bb = GGML_TYPES[t] + blk = raw.reshape(-1, bb)[: 5 * 256 // be].reshape(5, -1) + assert kernels.basalt_dequant16_grid(3, 256) == (1, 256) + got = run_dq(t, out, blk, 3, 256, row0=2, guard=64) + guards = np.concatenate([got[:64], got[-64:]]).view(np.uint8) + assert (guards == 0xFF).all(), f"{np.count_nonzero(guards != 0xFF)} guard bytes written" + bad = np.count_nonzero(got[64:-64] != stored(reference(t, blk[2:]), out).ravel()) + assert bad == 0, f"{bad} of {3 * 256} values differ from the twins" + + +BF16_PROBE = """ +kernel void bf16_helpers(device const uint* bits [[buffer(0)]], device ushort* rne [[buffer(1)]], + device ushort* nonan [[buffer(2)]], constant uint& n [[buffer(3)]], + uint i [[thread_position_in_grid]]) { + if (i >= n) return; + const float x = as_type(bits[i]); + rne[i] = f2bf(x); + nonan[i] = bf16_rne_nonan(x); +} +""" + + +def test_bf16_helpers_bitwise(): + """DQ-4: basalt_fp.metal's f2bf (basalt src/kernels/cuda/dequant_bf16.cu:20-27) and bf16_rne_nonan (basalt's bf, + src/prefill/kernels.cu:31-35), bit for bit, against monolith.formats.fp.f32_to_bf16 (f2bf's rounding with its NaN + case) and basalt_emu.bf16_bits (without it), on the edge patterns (signed zeros, the smallest and largest + subnormals, ties with bit 16 clear and set, the carry into inf, infinities, NaNs) and 2^20 random ones. Both take + a float: the probe passes as_type of each pattern, the twins the patterns viewed as float32.""" + edges = np.array([0x00000000, 0x80000000, 0x00000001, 0x80000001, 0x007fffff, 0x807fffff, 0x3f808000, 0x3f818000, + 0x7f7f7fff, 0x7f7f8000, 0x7f800000, 0xff800000, 0x7f800001, 0x7fc00000, 0x7fffffff, 0xffffffff, + 0xff810000], np.uint32) + bits = np.concatenate([edges, np.random.default_rng(7).integers(0, 1 << 32, 1 << 20, dtype=np.uint32)]) + n = bits.size + pso = gpu.pipeline(kernels.PRELUDE + kernels.template("basalt_fp.metal") + BF16_PROBE, "bf16_helpers") + out = gpu.run(pso, [bits.tobytes(), 2 * n, 2 * n], np.uint32(n).tobytes(), 3, -(-n // 256), 256, fill=0xFF) + rne, nonan = (np.frombuffer(b, np.uint16) for b in out[1:]) + x = bits.view(np.float32) + assert np.array_equal(rne, f32_to_bf16(x)) + assert np.array_equal(nonan, emu.bf16_bits(x)) + # basalt's rules where the two differ or carry: ties to even, the carry into inf, the NaN case f2bf alone has + for b, want_rne, want_nonan in [(0x3f808000, 0x3f80, 0x3f80), (0x3f818000, 0x3f82, 0x3f82), + (0x7f7f8000, 0x7f80, 0x7f80), (0x7f800001, 0x7fc0, 0x7f80), + (0x7fffffff, 0x7fff, 0x8000), (0xffffffff, 0xffff, 0x0000)]: + k = int(np.flatnonzero(bits == b)[0]) + assert (rne[k], nonan[k]) == (want_rne, want_nonan), hex(b) diff --git a/third_party/NOTICE b/third_party/NOTICE index ca9100e3..77f4c30f 100644 --- a/third_party/NOTICE +++ b/third_party/NOTICE @@ -86,7 +86,8 @@ Format: `` — adapted from / copied from `` `` @ - `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`. + semantics and the IQ4 table lookup, and, through `dequant_bf16.cu`'s `f2bf`, the BF16 rounding of + `ggml_compute_fp32_to_bf16`. 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 @@ -118,6 +119,10 @@ Format: `` — adapted from / copied from `` `` @ `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`. +- `kernels/common/basalt_dequant16.metal` — through basalt's `src/kernels/cuda/dequant_bf16.cu` (below), which + transcribes `ggml/src/ggml-quants.c`'s `dequantize_row_q2_0`, `_q4_0`, `_q5_0`, `_q8_0`, `_q3_K`, `_q4_K`, `_q5_K`, + `_q6_K`, `_iq4_nl`, `_iq4_xs` and `get_scale_min_k4`, and `ggml/src/ggml-common.h`'s `kvalues_iq4nl` (MIT): the + per-element dequantization rules of the ten types and the IQ4 codebook. License: `third_party/GGML-LICENSE`. ## Arm optimized-routines (ARM-software/optimized-routines, MIT OR Apache-2.0 WITH LLVM-exception; taken under MIT) @@ -152,8 +157,9 @@ Format: `` — adapted from / copied from `` `` @ 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`. + fast-math file's `__expf` (`expf_ftz`; `docs/research/basalt-nvcc/q5k_head.md`); and from + `src/kernels/cuda/dequant_bf16.cu:20-27` and `src/prefill/kernels.cu:31-35`, the BF16 roundings `f2bf` (with its NaN + case) and `bf` (`bf16_rne_nonan`, without). 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`. @@ -268,6 +274,17 @@ Format: `` — adapted from / copied from `` `` @ 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`. +- `kernels/common/basalt_dequant16.metal` — adapted from `src/kernels/cuda/dequant_bf16.cu:17-188` (MIT): + `dequant_kernel` with `group32` for Q4_0, Q5_0, Q8_0, Q3_K, Q4_K, Q5_K, Q6_K, IQ4_NL, IQ4_XS and Q2_0, `h2f`, the + three output conversions (`put`), `kv_iq4nl` and `scale_min_k4`, in the arithmetic nvcc compiles for them + (`docs/research/basalt-nvcc/dequant_bf16.md`). License: `third_party/BASALT-LICENSE`. +- `monolith/kernels.py` — adapted from `src/kernels/cuda/dequant_bf16.cu:190-240` (MIT): `geometry` and `launch`'s + refusals and grid, as `basalt_dequant16_params` and `basalt_dequant16_grid`. License: `third_party/BASALT-LICENSE`. +- `tests/kernels/test_basalt_prompt_dequant.py`, `tests/contract/test_basalt_dequant16_builders.py` — adapted from + `src/kernels/dequant_f16_parity.cpp:35-106`, `src/kernels/dequant_bf16_test.cpp:56-107` and + `src/kernels/elementwise_parity.cpp:438-472` (MIT): their fixtures (the `std::mt19937(7)` blocks with pinned + scales, the pack's tensors, the NaN-scale Q8_0 pair) and criteria, and `dequant_bf16.cu:190-205`'s type table. + License: `third_party/BASALT-LICENSE`. ## Test data From 48c6a2d1e005e7f9423abdacbd0496614681226b Mon Sep 17 00:00:00 2001 From: Lance Woodson <65194841+woodsonl@users.noreply.github.com> Date: Wed, 21 Oct 2026 13:29:01 -0500 Subject: [PATCH 70/74] Port basalt's hyper-connection write as basalt_gr_post The net change of woodsonl/mlxstream#30 (fork merge commit 5f67939), as one commit on the copy of woodsonl/mlxstream#28. Eleven of its fourteen files are byte-equal to the fork's merge. monolith/kernels.py and third_party/NOTICE carry exactly the PR's added and removed lines, and docs/design/flash-next.md its changed lines rewrapped; the three differ from the fork only where this base lacks the fork's later lines (the prompt path's group dequantizers, woodsonl/mlxstream#29). --- docs/design/flash-next.md | 12 +- docs/research/basalt-nvcc/hc_fused.md | 2 +- .../research/basalt-nvcc/native_gr_postops.md | 125 +++++++++++ kernels/common/basalt_gr_post.metal | 35 +++ monolith/compiler/emit_basalt.py | 39 +++- monolith/kernels.py | 25 +++ monolith/ops/basalt.py | 33 +-- tests/basalt_hc_ref.py | 73 +++++- tests/contract/test_basalt_hc_refs.py | 48 ++++ tests/contract/test_basalt_ops.py | 75 ++++++- tests/kernels/basalt_gpu.py | 29 +++ tests/kernels/test_basalt_gr_post.py | 211 ++++++++++++++++++ tests/kernels/test_basalt_ops_program.py | 21 +- third_party/NOTICE | 32 ++- 14 files changed, 718 insertions(+), 42 deletions(-) create mode 100644 docs/research/basalt-nvcc/native_gr_postops.md create mode 100644 kernels/common/basalt_gr_post.metal create mode 100644 tests/contract/test_basalt_hc_refs.py create mode 100644 tests/kernels/test_basalt_gr_post.py diff --git a/docs/design/flash-next.md b/docs/design/flash-next.md index 16340fa1..74b7b651 100644 --- a/docs/design/flash-next.md +++ b/docs/design/flash-next.md @@ -103,11 +103,11 @@ ones this pack runs. (`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`, `hc_fused.md` for the - hyper-connection read, its router and the int8 copies, `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 + hyper-connection read, its router and the int8 copies, `native_gr_postops.md` for the hyper-connection write, + `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 @@ -456,7 +456,7 @@ same rule holds for any other ported kernel whose basalt tests end in a comparis | 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 int8 hyper-connection copies, `hc8_quant_kernel` at load (`src/kernels/cuda/hc_fused.cu:1171-1197`; `src/program/generate.cpp:2319-2365`; `src/core/mtp.cpp:254-282`, `:488-503`) | `hc8_parity` prints the down copy's relative rms error (`src/kernels/hc8_parity.cpp:107-116`) and gates only reads of the copies | the codes and fp16 scales, made on the host (`monolith/packs/basalt_hc8.py`), byte for byte against a scalar transcription of `hc8_quant_kernel` (`tests/contract/test_basalt_hc8.py`): the contract's rule for quantizer codes, `if (g_blocks[i] != r_blocks[i]) ++byte_bad;` (`src/kernels/quantize_act_parity.cpp:100`) | | 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_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`) | the kernel bitwise against an emulation of its `.FTZ` sequence with the exponential taken from the GPU's own helper (`tests/kernels/test_basalt_gr_post.py`), and against a double-precision write with `gr_parity`'s two write rules on its fixtures, `const bool plain = worst_plain < 1e-6;` and `const bool streams_ok = worst_stream < 1e-6;` (`src/kernels/gr_parity.cpp:645`, `:689`). The term-relative rule holds for injections below about 80 in magnitude [M], beyond which the float32 rounding of `x * log2 e` that basalt shares dominates where `\|R\|` is small, so the extremes are held bitwise only | | `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 | diff --git a/docs/research/basalt-nvcc/hc_fused.md b/docs/research/basalt-nvcc/hc_fused.md index e9f5ea9c..19ec19a0 100644 --- a/docs/research/basalt-nvcc/hc_fused.md +++ b/docs/research/basalt-nvcc/hc_fused.md @@ -6,7 +6,7 @@ down items (`cn_x`, `cn_dot`, `cn_lo`), the up items (`hc_up_pre`, `hc_up_main_m (`hc_q8_1_store_native`, `hc_up_q8`), the router items (`hc_router_rows`, `warp_sum16_ftz`, the IEEE `hc_q8_1_store`) and the top-10 item (`hc_top10`), 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 `matvec.md` is for -the q8_1 quantizers and `bf16.md` for MMVF; `native_gr_postops.md` (not yet on main) covers the hyper-connection write. +the q8_1 quantizers and `bf16.md` for MMVF; `native_gr_postops.md` covers the hyper-connection write. Basalt paths are relative to commit `b4c63b55754637f4c72ad53a0f791d425f71eb36`; `path:a-b` means lines a to b there, and a bare `:N` is a line of `src/kernels/cuda/hc_fused.cu` unless another file was named last. diff --git a/docs/research/basalt-nvcc/native_gr_postops.md b/docs/research/basalt-nvcc/native_gr_postops.md new file mode 100644 index 00000000..d0491d17 --- /dev/null +++ b/docs/research/basalt-nvcc/native_gr_postops.md @@ -0,0 +1,125 @@ +# basalt's native GR post-operations as nvcc compiles them + +What NVIDIA's compiler emits at every rounding site of basalt's `native_gr_postops.cu`: `post`, the hyper-connection +write `native_gr_post` launches (`src/kernels/cuda/gr.cu:394-395`, `gr_write` when `native_mmvf` is set, the write +decode runs when it does not fold it into the next read), and the two kernels of the unfused read in the same file, +`down_silu` and `pre_gated` (`gr.cu:345`, `:349`), 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 kernel follows (`docs/design/flash-next.md`, invariant 5), +as `hc_fused.md` is for the fused read. + +Basalt paths are relative to commit `b4c63b55754637f4c72ad53a0f791d425f71eb36`; `path:a-b` means lines a to b there, +and a bare `:N` is a line of `src/kernels/cuda/native_gr_postops.cu` unless another file was named last. + +## Method + +- **Sources.** `src/kernels/cuda/native_gr_postops.cu` (115 lines, adapted from llama.cpp + `ggml/src/ggml-cuda/{dsv4-hc.cu,scale.cu,unary.cu,unary.cuh}` at 3cf03257, `:1-2`) with its one quoted header, + `include/basalt/kernels/native_gr_postops.hpp`, inlined under `#line` directives; the system and CUDA headers stay + `#include`s. Only basalt's public MIT source was sent. The file is compiled whole: its three kernels are referenced + by its own host launchers (`:91-114`), so no instantiation table is needed. +- **Compiler.** Compiler Explorer's public API, `POST https://godbolt.org/api/compiler/nvcc130/compile` with + `"compilerOptions": {"produceDevice": true}` and `"filters": {}`: compiler id `nvcc130`, NVCC 13.0.0, version string + `Cuda compilation tools, release 13.0, V13.0.48`, which returns the PTX and the `SASS (sm_120)` listing (complete: + 654 PTX and 722 SASS lines). Compiled October 18, 2026. Basalt requires CUDA 13 (`CMakeLists.txt:32-33`). +- **Flags.** The file belongs to the `kernels` library (`CMakeLists.txt:118`, `:137`) and is in the + `--use_fast_math` list (`:185-202`, the file at `:190`), so nvcc builds it with `-ftz=true -prec-div=false + -prec-sqrt=false -fmad=true` and maps `expf` to `__expf`. Global settings: a Release build, `-O3 -DNDEBUG` + (`:12-14`), `BASALT_VERSION` (`:7`), architecture 120 only (`:3-5`, `:26-31`); no `CMAKE_CUDA_FLAGS` and no + `-lineinfo`. The exact `userArguments` sent: `-arch=sm_120 -lineinfo -O3 -DNDEBUG -DBASALT_VERSION=\"0.0.1\" + --use_fast_math` (Compiler Explorer passed the macro on as `-DBASALT_VERSION="0.0.1"`; nothing in this translation + unit reads it). `-lineinfo` attributes every PTX and SASS instruction to a source line; Compiler Explorer adds + `-g -lineinfo --keep-device-functions -c -keep` (the response's `compilationOptions`), which changes no kernel. +- **Listings.** A row number (`native_gr_postops.sass.txt` rows 529-678) is the position, from 1, of an instruction + in the `asm` list of the response's `SASS (sm_120)` device; every entry carries its file and line, and each kernel + starts at its label (`pre_gated` at row 1, `pre_gated` at 265, `post` at 529, `down_silu` at 680). The + request and response are kept outside the repository; the Sources and Flags above rebuild the request. +- **Reading a site.** The PTX shows what the front end chose (`fma.rn.ftz.f32`, `ex2.approx.ftz.f32`, + `rcp.approx.ftz.f32`, `div.approx.ftz.f32`); the SASS shows what `ptxas` made of it, and the tables cite the SASS, + the ground truth. In this file the SASS follows the PTX one instruction for one: `ptxas` fuses nothing further, and + every float instruction carries `.FTZ`. + +## Notation + +`matvec.md`'s: fl(e), fma(a, b, c), **.FTZ** (subnormal inputs and results flushed to the zero of their sign). L = +`0x3FB8AA3B` = fl(log2 e) = 1.44269502; the SASS prints −L as `-1.4426950216293334961`. Metal forms use +`kernels/common/basalt_fp.metal`: `ftz`, `add_ftz`, `mul_ftz`, `fma_ftz`, `rcp_ftz` (where SASS has `MUFU.RCP`: +the correctly rounded 1 / x of the flushed input, flushed; contract invariant 5), `expf_ftz` (`__expf` in a +`--use_fast_math` file: `ftz(fast::exp2(mul_ftz(x, L)))`) and `cuda_nan` (sm_120's NaN at a store, `nan.md`). Every +Metal source starts with `#pragma STDC FP_CONTRACT OFF`. + +`expf_ftz(-a)` is the SASS's `FMUL.FTZ t, a, -L`: negation is exact and round-to-nearest-even is symmetric in sign, +so fl(−a · L) and fl(a · −L) have the same bits, flushed or not. + +## Summary + +| Kernel | Rounding sequence nvcc 13.0 emits (sm_120) | Metal | +|---|---|---| +| `post` (`:65-74`) | a = fma(inject[c], scale, +0); e = ex2(fl(a · −L)); g = rcp(1 + e); w = fma(g, 2, +0); out = fma(block_out[d], w, residual[i]); all `.FTZ` | `fma_ftz`, `expf_ftz(-a)`, `rcp_ftz(add_ftz(e, 1.0f))`, `fma_ftz(g, 2.0f, 0.0f)`, `cuda_nan(fma_ftz(...))` | +| `down_silu` (`:42-47`) | x = fma(lo, scale, +0); lo = x · rcp(1 + ex2(fl(x · −L))) (`div.approx.ftz`: `MUFU.RCP` then `FMUL.FTZ`) | `mul_ftz(x, rcp_ftz(add_ftz(expf_ftz(-x), 1.0f)))` | +| `pre_gated` (`:49-64`, layers) | per c in order: w = sigmoid(gate), gate = x · w (`FMUL.FTZ`), sum = fma(x, w, sum) from +0; mixed = scale · sum (`FMUL.FTZ`) | `mul_ftz` and `fma_ftz` in c order, `mul_ftz(scale, sum)` | +| `pre_gated` (head) | per c: gate = x · w; sum = product for c = 0, else sum + product (`FADD.FTZ`); mixed = fma(sum, scale, +0) | `add_ftz` in c order from the first product, `fma_ftz(sum, scale, 0.0f)` | + +The PTX of the three kernels holds no float instruction without `.ftz` (`fma.rn.ftz`, `mul.ftz`, `mul.rn.ftz`, +`add.ftz`, `ex2.approx.ftz`, `rcp.approx.ftz`, `div.approx.ftz`), and the SASS no `FFMA`, `FMUL` or `FADD` without +`.FTZ`. Counts: PTX 20 `fma.rn.ftz`, 33 `mul.ftz`, 30 `mul.rn.ftz`, 32 `add.ftz`, 15 `add.rn.ftz`, 32 +`ex2.approx.ftz`, 31 `rcp.approx.ftz`, 1 `div.approx.ftz`; SASS 20 `FFMA.FTZ`, 64 `FMUL.FTZ` (33 + 30 + the +division's), 47 `FADD.FTZ`, 32 `MUFU.EX2` and 34 `MUFU.RCP` (31, the division's, and two of `post`'s integer +division: rows 549 and 605). There is no implicit contraction site: every FMA is the source's `__fmaf_rn` (`:40`, +`:59`, `:73`), and the products `pre_gated` keeps beside its FMAs stay separate `FMUL.FTZ` instructions. The +only approximate operations are `MUFU.EX2` and `MUFU.RCP` (contract invariant 5: `fast::exp2` of the same product, +and the correctly rounded reciprocal, both flushed). + +## 1. `post` (`native_gr_post`, `:65-74`) + +`native_gr_post(residual, block_out, inject, output, n_embd, hc, stream)` (`:107-114`) launches +`blocks(n_embd · hc)` blocks of `THREADS` = 256 (`:35`, `:83`) with `scale = 1.0f / float(hc)`, computed by the host +code at launch (correctly rounded; 0.25 exactly for hc = 4). Thread i < n_embd · hc writes `output[i]`; `output` may be +`residual` (`:72`, `native_gr_postops.hpp:22-24`), which is why `residual` is read with a plain `ld.global.f32` +(`LDG.E`) and `inject`, `block_out` through the non-coherent path (`LDG.E.CONSTANT`). + +| Site | basalt | PTX | SASS (13.0, `native_gr_postops.sass.txt` rows 529-678) | Metal | +|---|---|---|---|---| +| indices | `:70` `c = int(i / n_embd), d = int(i % n_embd)` | `div.u32` (or `div.u64` when i or n_embd needs 64 bits) | `MUFU.RCP` of `UI2F.U32.RP` n_embd, `F2I.FTZ.U32.TRUNC.NTZ`, `IMAD.HI.U32` corrections (the integer-division idiom, exact); `__cuda_sm20_div_u64` otherwise | `t = i / row`, `c = (i % row) / n_embd`, `d = i % n_embd` in `uint`, `row = hc · n_embd` (`check_shape` bounds n_embd · hc by `INT_MAX`, `:79-82`; `basalt_gr_post_params` bounds T · hc · n_embd below 2^32) | +| SCALE(1/hc) | `:71`, `:40` `__fmaf_rn(scale, inject[c], 0.0f)` | `fma.rn.ftz.f32 %f3, %f1, %f2, 0f00000000` | `FFMA.FTZ R0, R0, UR4, RZ` (inject · scale + +0) | `a = fma_ftz(inject[c], scale, 0.0f)`: the +0 addend turns a −0 product into +0 (the comment `:37-38`), and `.FTZ` flushes a subnormal product | +| `expf(-a)` | `:36` (`__expf` under `--use_fast_math`) | `mul.ftz.f32 %f4, %f3, 0fBFB8AA3B`; `ex2.approx.ftz.f32 %f5, %f4` | `FMUL.FTZ R4, R0, -1.4426950216293334961`; `MUFU.EX2 R4, R4` (no range scaling: the `.ftz` form) | `e = expf_ftz(-a)` | +| `1 + e` | `:36` | `add.ftz.f32 %f6, %f5, 0f3F800000` | `FADD.FTZ R0, R4, 1` | `add_ftz(e, 1.0f)` | +| `1.0f / (...)` | `:36` | `rcp.approx.ftz.f32 %f7, %f6` | `MUFU.RCP R0, R0` | `g = rcp_ftz(add_ftz(e, 1.0f))` (1 / +inf = +0 on both) | +| SCALE(2) | `:71`, `:40` `__fmaf_rn(2.0f, g, 0.0f)` | `fma.rn.ftz.f32 %f8, %f7, 0f40000000, 0f00000000` | `FFMA.FTZ R5, R0, 2, RZ` | `w = fma_ftz(g, 2.0f, 0.0f)` (exact doubling: g lies in [+0, 1]) | +| the write | `:73` `__fmaf_rn(block_out[d], weight, residual[i])` | `fma.rn.ftz.f32 %f11, %f9, %f8, %f10` | `FFMA.FTZ R5, R5, R2, R8` (w · block_out[d] + residual[i]); `STG.E` | `output[i] = cuda_nan(fma_ftz(block_out[d], w, residual[i]))` | + +The port runs a window's T tokens in one dispatch, so its loads are `inject[t · hc + c]`, `block_out[t · n_embd + d]` +and `residual[i]`, and it computes `scale = 1.0f / float(hc)` in the kernel: a correctly rounded division in +MTLMathModeSafe, so the host's value. + +The weight depends only on `inject[c]`: every thread of stream c recomputes it, with the same bits, so the port may +compute it once per stream (threadgroup memory or a per-thread recomputation, either is exact). Nothing in `post` +reduces, so there is no order to reproduce: each output is one FMA of three loaded values. + +## 2. `down_silu` and `pre_gated` + +The unfused read (`gr_read` with `native_mmvf`, `gr.cu:336-349`) calls both; the decode path of this unit does not +(it runs `hc_fused_read`, `hc_fused.md`). Recorded because they share the file's flags and compile. + +### `down_silu` (`:42-47`) + +One thread per element of `lo` (`hc_lr` values), `scale = 1.0f / float(hc)` (`:94`). + +| Site | basalt | PTX | SASS (rows 680-722) | Metal | +|---|---|---|---|---| +| SCALE | `:45`, `:40` | `fma.rn.ftz.f32 %f3, %f1, %f2, 0f00000000` | `FFMA.FTZ R0, R0, UR6, RZ` | `x = fma_ftz(lo[i], scale, 0.0f)` | +| `expf(-x)`, `1 +` | `:46` | `mul.ftz.f32 %f4, %f3, 0fBFB8AA3B`; `ex2.approx.ftz.f32`; `add.ftz.f32 %f6, %f5, 0f3F800000` | `FMUL.FTZ R2, R0, -1.4426950216293334961`; `MUFU.EX2 R2, R2`; `FADD.FTZ R3, R2, 1` | `add_ftz(expf_ftz(-x), 1.0f)` | +| `x / (...)` | `:46` | `div.approx.ftz.f32 %f7, %f3, %f6` | `MUFU.RCP R3, R3`; `FMUL.FTZ R7, R0, R3` | `lo[i] = cuda_nan(mul_ftz(x, rcp_ftz(...)))` | + +### `pre_gated` (`:48-64`) + +One thread per column d < n_embd (`:51-52`); it walks the hc streams c = 0, 1, ... in order (`:54`, unrolled by 8 +with the remainder in blocks of 4, 2 and 1; the operations on `sum` keep the source's order). + +| Site | basalt | SASS (`` rows 1-264, `` rows 265-527) | Metal | +|---|---|---|---| +| `sigmoid(gate[i])` | `:56`, `:36` | `FMUL.FTZ t, g, -1.4426950216293334961`; `MUFU.EX2`; `FADD.FTZ e, t', 1`; `MUFU.RCP` | `w = rcp_ftz(add_ftz(expf_ftz(-g), 1.0f))` | +| `product` | `:57` `__fmul_rn(x, w)` | `FMUL.FTZ p, x, w` (`mul.rn.ftz.f32`) | `p = mul_ftz(x, w)`; `gate[i] = cuda_nan(p)` | +| `` sum | `:59` `sum = __fmaf_rn(x, w, sum)` from `0.0f` | `FFMA.FTZ s, x, w, s`, a chain in c order (beside the `FMUL.FTZ` of the product) | `sum = fma_ftz(x, w, sum)` from `0.0f` | +| `` sum | `:60` `c == 0 ? product : __fadd_rn(sum, product)` | `FADD.FTZ s, s, p` in c order; the first product taken as is (`@P0 FADD.FTZ` only past c = 0) | `sum = c == 0 ? p : add_ftz(sum, p)` (a −0 first product stays −0) | +| `` mixed | `:62` `scale * sum` | `FMUL.FTZ R11, R11, UR4` | `mixed[d] = cuda_nan(mul_ftz(sum, scale))` | +| `` mixed | `:63` `scale_zero_bias(sum, scale)` | `FFMA.FTZ R3, R0, UR4, RZ` | `mixed[d] = cuda_nan(fma_ftz(sum, scale, 0.0f))` | diff --git a/kernels/common/basalt_gr_post.metal b/kernels/common/basalt_gr_post.metal new file mode 100644 index 00000000..08c5fbd0 --- /dev/null +++ b/kernels/common/basalt_gr_post.metal @@ -0,0 +1,35 @@ +// Copyright (c) 2023-2026 The ggml authors (MIT) +// Copyright (c) 2026 Jesús Gulfo (MIT) +// Adapted from basalt (jesdga95/basalt) src/kernels/cuda/native_gr_postops.cu:35-41, :65-74, :107-114 @ +// b4c63b55754637f4c72ad53a0f791d425f71eb36 (MIT; third_party/NOTICE), which adapts ggml-org/llama.cpp +// ggml/src/ggml-cuda/{dsv4-hc.cu,scale.cu,unary.cu,unary.cuh} @ 3cf03257f219afbe7334045ff7c6a06ac68c627d (MIT; +// third_party/NOTICE), written in the rounding sequence nvcc compiles for it +// (docs/research/basalt-nvcc/native_gr_postops.md). +// +// basalt's hyper-connection write, native_gr_post, over T tokens at once: stream c of token t gets the weight +// w = 2 sigmoid(inject[t][c] / hc) and out[t][c][d] = fma(block_out[t][d], w, r[t][c][d]), in the sequence of +// native_gr_postops.md section 1. The file is --use_fast_math in basalt, so every operation is .FTZ, here through +// basalt_fp.metal's helpers (needed ahead of this file); MUFU.EX2 and MUFU.RCP, the two approximate operations, are +// expf_ftz and rcp_ftz (contract invariant 5), and a NaN is stored as sm_120's (cuda_nan). One thread per element in +// threadgroups of 256 (basalt's THREADS); the threads past the last element return before any load. Nothing is +// reduced and no thread reads another's values, so a token's bits depend neither on T nor on its row. out may be r's +// buffer (basalt's in-place call: each thread loads its own r[i] before it stores out[i], and no other thread loads +// r[i]); block_out and inject overlap neither. +#pragma STDC FP_CONTRACT OFF + +// p: n_embd, hc, T (the program's width), 0. n_embd * hc <= INT_MAX and T * hc * n_embd < 2^32 (basalt_gr_post_params), +// so the 32-bit indices are exact. +kernel void basalt_gr_post(device const float* r [[buffer(0)]], // residual [T][hc][n_embd] + device const float* block_out [[buffer(1)]], // [T][n_embd] + device const float* inject [[buffer(2)]], // [T][hc], the read's inject_out + device float* out [[buffer(3)]], // [T][hc][n_embd] + constant uint4& p [[buffer(4)]], + uint i [[thread_position_in_grid]]) { + const uint n_embd = p.x, hc = p.y, row = hc * n_embd; + if (i >= p.z * row) return; + const uint t = i / row, c = (i % row) / n_embd, d = i % n_embd; + const float x = fma_ftz(inject[t * hc + c], 1.0f / float(hc), 0.0f); // FFMA.FTZ R0, R0, UR4, RZ; UR4 = 1 / hc + const float g = rcp_ftz(add_ftz(expf_ftz(-x), 1.0f)); // FMUL.FTZ, MUFU.EX2, FADD.FTZ, MUFU.RCP + const float w = fma_ftz(g, 2.0f, 0.0f); // FFMA.FTZ R5, R0, 2, RZ + out[i] = cuda_nan(fma_ftz(block_out[t * n_embd + d], w, r[i])); // FFMA.FTZ R5, R5, R2, R8 +} diff --git a/monolith/compiler/emit_basalt.py b/monolith/compiler/emit_basalt.py index c5f7970d..1d325eb1 100644 --- a/monolith/compiler/emit_basalt.py +++ b/monolith/compiler/emit_basalt.py @@ -6,11 +6,12 @@ # 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). +# src/kernels/cuda/native_bf16.cu:139-171, src/kernels/cuda/iq_kernels.cu:2450-2455 and +# src/kernels/cuda/native_gr_postops.cu:75-82 @ b4c63b55754637f4c72ad53a0f791d425f71eb36 (MIT; third_party/NOTICE). from __future__ import annotations +import math from typing import TYPE_CHECKING, Dict, Sequence, Tuple from .. import kernels @@ -70,6 +71,17 @@ def _bind(ctx: _Ctx, op: Op, slot: int, v: Value, align: int) -> Tuple[int, str, return slot, buf, off +def _disjoint(ctx: _Ctx, op: Op, outs: Sequence[Value], ins: Sequence[Value]) -> None: + """Refuse an output whose bytes overlap another output's or an input's (the same buffer, intersecting byte ranges; + a view binds rows of its base's buffer). Two inputs may share bytes.""" + spans = [(*ctx.buf(v), math.prod(ctx.shape(v)) * v.dtype.itemsize, v.name) for v in (*outs, *ins)] + for i, (b0, o0, n0, v0) in enumerate(spans[:len(outs)]): + for b1, o1, n1, v1 in spans[i + 1:]: + if b0 == b1 and o0 < o1 + n1 and o1 < o0 + n0: + raise ValueError(f"{op.kind}: {v0!r} and {v1!r} overlap in {b0}; a store of this op would " + "land in bytes it reads or another of its outputs holds") + + def _q8_1(ctx: _Ctx, op: Op) -> None: kind = op.attrs.get("quantizer") if kind not in Q8_1_KERNELS: @@ -172,5 +184,26 @@ def _mmvf(ctx: _Ctx, op: Op) -> None: (grid, 1, 1), (threads, 1, 1), f"{op.kind}:{w.name}", writes=[2]) +def _gr_post(ctx: _Ctx, op: Op) -> None: + t = _columns(ctx, op) # no other T bound: native_gr_post takes any count + (r, block_out, inject), (r_out,) = op.inputs, op.outputs + n_embd, hc = ctx.shape(block_out)[-1], ctx.shape(inject)[-1] + record = kernels.basalt_gr_post_params(n_embd, hc, t) # check_shape's refusals, a dimension of 0 among them + _expect(ctx, op, r, (t, hc * n_embd), DType.F32, f"{hc} streams of the block output's {n_embd} values") + _expect(ctx, op, block_out, (t, n_embd), DType.F32, "the block output's columns") + _expect(ctx, op, inject, (t, hc), DType.F32, "one injection per stream of each column") + _expect(ctx, op, r_out, (t, hc * n_embd), DType.F32, "the residual's columns") + # basalt allows only output == residual (native_gr_postops.hpp:22-26): here a view of r over bytes r's other + # readers may still read, so that alias is refused too + _disjoint(ctx, op, (r_out,), (r, block_out, inject)) + k = ctx.kernel("basalt_gr_post", kernels.basalt_gr_post_source(), "basalt_gr_post", {}) + prm = ctx.params("basalt_gr_post", record) + grid, threads = kernels.basalt_gr_post_grid(n_embd, hc, t) + ctx.add(k, [_bind(ctx, op, 0, r, 4), _bind(ctx, op, 1, block_out, 4), _bind(ctx, op, 2, inject, 4), + _bind(ctx, op, 3, r_out, 4), (4, prm, 0)], (grid, 1, 1), (threads, 1, 1), + f"{op.kind}:{block_out.name}", writes=[3]) + + 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} + "basalt_dense_tc_pair": _dense_tc_pair, "basalt_mmvf": _mmvf, + "basalt_gr_post": _gr_post} diff --git a/monolith/kernels.py b/monolith/kernels.py index ed084a5e..485745f8 100644 --- a/monolith/kernels.py +++ b/monolith/kernels.py @@ -701,6 +701,31 @@ def basalt_q5k_proxy_params(n_cap: int, *, row0: int = 0, n: int = 0, n_rows: Op return struct.pack(" str: + """basalt's ``native_gr_post`` (``basalt_gr_post``): the hyper-connection write of T tokens' residual stacks.""" + return PRELUDE + template("basalt_fp.metal") + template("basalt_gr_post.metal") + + +def basalt_gr_post_params(n_embd: int, hc: int, t: int) -> bytes: + """``basalt_gr_post``'s record (n_embd, hc, T, 0): positive dimensions with n_embd * hc at most INT_MAX, basalt's + ``check_shape`` (native_gr_postops.cu:79-82), any T >= 1, and T * hc * n_embd below 2^32, the kernel's 32-bit + element index.""" + if n_embd < 1 or hc < 1 or t < 1 or n_embd * hc > 2 ** 31 - 1 or t * hc * n_embd >= 2 ** 32: + raise ValueError(f"basalt_gr_post: unsupported shape (n_embd {n_embd}, hc {hc}, T {t})") + return struct.pack(" Tuple[int, int]: + """(threadgroups, threads per threadgroup): one thread per element of the T rows, in threadgroups of 256 (basalt's + ``THREADS`` and ``blocks``, native_gr_postops.cu:35, :83).""" + return -(-t * hc * n_embd // 256), 256 + + # ---- the other decode kernels ------------------------------------------------------------------------------- MSL_TENSOR_OPS = 4 << 16 # the language version the tensor-ops kernels need (MSL 4.0: , MPP) diff --git a/monolith/ops/basalt.py b/monolith/ops/basalt.py index 638ff410..09e54a2e 100644 --- a/monolith/ops/basalt.py +++ b/monolith/ops/basalt.py @@ -1,7 +1,8 @@ -"""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. +"""basalt's single-dispatch GEMVs, q8_1 quantizers (OI-013) and hyper-connection write (OI-005; +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 @@ -31,16 +32,21 @@ * ``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. +* ``basalt_gr_post`` (``native_gr_post``): ``(r [T, hc * n_embd], block_out [T, n_embd], inject [T, hc] F32)`` → + ``r_out [T, hc * n_embd] F32``, ``r_out = r + block_out * 2 sigmoid(inject / hc)`` per stream in basalt's fast-math + rounding; n_embd and hc from ``block_out`` and ``inject``; any T >= 1 (the write has no width bound); ``r_out`` a + fresh value whose bytes overlap none of the inputs. -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. +Alignment, checked at every binding: 4 bytes for each q8_1, ``basalt_mmvq``, ``basalt_dense_tc`` and ``basalt_gr_post`` +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``), every pointer of ``native_gr_post`` +at 4 (``check_pointer``, ``native_gr_postops.cu:75-78``, called at ``:110``). 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 @@ -52,3 +58,4 @@ 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"))) +BASALT_GR_POST = register_op(OpDef("basalt_gr_post", OpClass.MAP, "rows").bind("*", KernelBinding("basalt_gr_post"))) diff --git a/tests/basalt_hc_ref.py b/tests/basalt_hc_ref.py index a688f0d1..8d2c61ba 100644 --- a/tests/basalt_hc_ref.py +++ b/tests/basalt_hc_ref.py @@ -1,8 +1,13 @@ # 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/hc_fused.cu:1171-1197 (hc8_quant_kernel), -# src/core/model_file.cpp:487-513 (hc8_read) and src/kernels/hc8_parity.cpp:69-99 (hc8_parity's matrices) @ -# b4c63b55754637f4c72ad53a0f791d425f71eb36 (MIT; third_party/NOTICE). +# src/core/model_file.cpp:487-513 (hc8_read), src/kernels/hc8_parity.cpp:69-99 (hc8_parity's matrices), +# src/kernels/gr_parity.cpp:136-156 (gr_parity's metrics), :433-454, :621-623, :675 (its write fixture), :679-688 +# (its double write) and src/kernels/cuda/native_gr_postops.cu:65-74 (native_gr_post's arithmetic) @ +# b4c63b55754637f4c72ad53a0f791d425f71eb36, the last of which adapts ggml-org/llama.cpp +# ggml/src/ggml-cuda/{dsv4-hc.cu,scale.cu,unary.cu,unary.cuh} @ 3cf03257f219afbe7334045ff7c6a06ac68c627d (MIT; +# third_party/NOTICE). """Host references of basalt's hyper-connection unit for the port's tests: numpy only, no Metal, imported by every tier like ``tests/moe_synth.py``. Each is a transcription of basalt's source written apart from the code it checks, so the two cannot share a mistake. @@ -13,6 +18,12 @@ * ``dequant_copy``: a copy's exact values, ``q * f16(s)`` in float64, the weights the int8 dot products multiply by. * ``hc8_parity_matrices``: hc8_parity's down, up and injection matrices, drawn with numpy. * ``hc8_read_table``: ``hc8_read``, basalt's reader of a ``BASALTH8`` table, its checks transcribed. +* ``gr_fixture``: gr_parity's write fixture, drawn with numpy, for any shape and window. +* ``gr_write_double``: gr_parity's double write, ``R + bo * 2 / (1 + exp(-inj / hc))`` in float64, with its block-output + term; ``rel_terms`` and ``rel_diff``: gr_parity's metrics (term-relative per element; normalised L1), in float64. +* ``gr_post_emulation``: ``native_gr_post`` as nvcc compiles it (docs/research/basalt-nvcc/native_gr_postops.md + section 1), every operation ``.FTZ`` through ``tests/kernels/basalt_emu.py``'s helpers, with the approximate + exponential the caller's; ``cuda_nan``: a stored NaN as sm_120's. """ import struct @@ -21,6 +32,9 @@ import numpy as np from monolith.formats.fp import f32_to_bf16 +from tests.kernels import basalt_emu as emu + +F32 = np.float32 def hc8_quant_scalar(w, gpr, srow): # hc8_quant_kernel, hc_fused.cu:1171-1197, G8 = 32 (:343) @@ -98,3 +112,58 @@ def hc8_read_table(path): # hc8_read, src/core/model_ raise ValueError(f"hc8: entry {name} is malformed") out[name] = (rows, cols, srow, offset, nbytes, data[offset: offset + want]) return out + + +def gr_fixture(n_embd=256, hc=4, T=1, inj_sd=0.0, seed=1234): # gr_parity.cpp:433-454, :621-623, :675 + """gr_parity's write fixture for ``T`` tokens, numpy's normals in place of its ``mt19937(1234)`` ones: the residual + ``R [T][hc][n_embd]`` N(0, 1) times ``4^c`` in stream c (its "STREAM SCALES 1, 4, 16, 64", ``:447-454``), + ``bo [T][n_embd]`` N(0, 1) (``:621-622``) and the injections ``inj [T][hc]``, ``inj_sd`` times N(0, 1) (0, its + ``zero_inj``, ``:623``; 3, ``gauss(rng) * 3.0f``, ``:675``), each a float32 product as basalt's.""" + rng = np.random.default_rng(seed) + R = rng.standard_normal((T, hc, n_embd), dtype=np.float32) + R *= (np.float32(4.0) ** np.arange(hc, dtype=np.float32))[None, :, None] + bo = rng.standard_normal((T, n_embd), dtype=np.float32) + inj = np.float32(inj_sd) * rng.standard_normal((T, hc), dtype=np.float32) + return R, bo, inj + + +def gr_write_double(R, bo, inj, hc): # gr_parity.cpp:679-688 + """gr_parity's double write of ``R [T][hc][n_embd]``, ``bo [T][n_embd]`` and ``inj [T][hc]``: ``(want, bo_w)``, + ``want = R + bo_w`` and the term ``bo_w = bo * w``, ``w = 2.0 / (1.0 + exp(-inj / hc))`` per stream (``:681``, + ``:684-686``), every operand float64. A zero injection gives ``w = 1`` exactly, so ``want = R + bo``.""" + w = 2.0 / (1.0 + np.exp(-np.asarray(inj, np.float64) / hc)) + bo_w = np.asarray(bo, np.float64)[:, None, :] * w[:, :, None] + return np.asarray(R, np.float64) + bo_w, bo_w + + +def rel_terms(want, got, term_a, term_b): # gr_parity.cpp:147-156, elementwise + """``|want - got| / (|term_a| + |term_b|)``, the denominator floored at 1e-30, with every argument converted to + float64 first, as basalt's ``double`` parameters are: a float32 denominator would round in binary32.""" + want, got, term_a, term_b = (np.asarray(v, np.float64) for v in (want, got, term_a, term_b)) + den = np.abs(term_a) + np.abs(term_b) + return np.abs(want - got) / np.where(den > 1e-30, den, 1e-30) + + +def rel_diff(a, b): # gr_parity.cpp:136-145 + """The normalised L1 difference ``sum |a - b| / sum |a|`` in float64, the denominator floored at 1e-30.""" + a, b = np.asarray(a, np.float64), np.asarray(b, np.float64) + d, mag = np.abs(a - b).sum(), np.abs(a).sum() + return d / (mag if mag > 1e-30 else 1e-30) + + +def gr_post_emulation(R, bo, inj, hc, exp_of): # native_gr_postops.cu:65-74, native_gr_postops.md section 1 + """``native_gr_post``'s output for the residuals ``R [T][hc][n_embd]``, block outputs ``bo [T][n_embd]`` and + injections ``inj [T][hc]``: ``x = fma(inj, 1 / hc, +0)``, ``w = fma(rcp(1 + exp_of(-x)), 2, +0)``, ``out = fma(w, + bo, R)``, all ``.FTZ``, a NaN as sm_120's. ``exp_of``: ``__expf`` (``MUFU.EX2``, no bit-exact host model), the + GPU's own ``expf_ftz`` in the tests, evaluated elementwise on the exact inputs.""" + with np.errstate(invalid="ignore", over="ignore"): # the planted infinities and NaNs + x = emu.fma_ftz(inj, F32(1) / F32(hc), F32(0)) + w = emu.fma_ftz(emu.rcp_ftz(emu.add_ftz(exp_of(-x), F32(1))), F32(2), F32(0)) + return cuda_nan(emu.fma_ftz(w[:, :, None], bo[:, None, :], R)) + + +def cuda_nan(x): # kernels/common/basalt_fp.metal's cuda_nan + """Every NaN of ``x`` as sm_120's 0x7fffffff (docs/research/basalt-nvcc/nan.md); every other value keeps its + bits.""" + u = np.ascontiguousarray(x, np.float32).view(np.uint32) + return np.where((u & 0x7FFFFFFF) > 0x7F800000, np.uint32(0x7FFFFFFF), u).view(np.float32) diff --git a/tests/contract/test_basalt_hc_refs.py b/tests/contract/test_basalt_hc_refs.py new file mode 100644 index 00000000..d1e6f03b --- /dev/null +++ b/tests/contract/test_basalt_hc_refs.py @@ -0,0 +1,48 @@ +"""The hyper-connection unit's own test code and kernel sources, GPU-free. + +- HF-COMPILE: each of the unit's kernel files, its comments removed, has ``#pragma STDC FP_CONTRACT OFF`` ahead of its + first function (docs/design/flash-next.md, invariant 5: "Each Metal source starts with ``#pragma STDC FP_CONTRACT + OFF``"), and no ``atomic`` (no threadgroup of a dispatch waits on or hands work to another, the property + hc_fused_parity's co-residency check establishes), no ``simd_sum``, ``simd_max``, ``simd_min`` or ``simd_prefix`` + (their reduction order is undocumented: every reduction is a shuffle loop in basalt's offset order), no ``fast::`` + or ``precise::`` (each approximate operation goes through its one shared helper, as basalt_fp.metal's, so kernels + basalt checks bitwise against each other stay bitwise equal) and no ``while`` (every GPU loop bounded: a ``for`` of + a fixed trip count). +- HREF-SELF: the host references of tests/basalt_hc_ref.py on inputs whose answers follow by hand from basalt's + formulas, since a misreading the kernel and its reference share would pass every comparison between them.""" + +import re +from pathlib import Path + +import numpy as np +import pytest + +from tests.basalt_hc_ref import gr_fixture, gr_write_double, rel_terms + +ROOT = Path(__file__).resolve().parents[2] +SOURCES = ("kernels/common/basalt_gr_post.metal",) # the unit's kernel files +PRAGMA = re.compile(r"^[ \t]*#pragma STDC FP_CONTRACT OFF[ \t]*$", re.M) +BANNED = ("atomic", "simd_sum", "simd_max", "simd_min", "simd_prefix", "fast::", "precise::", "while") + + +@pytest.mark.parametrize("path", SOURCES) +def test_kernel_sources_keep_the_port_rules(path): + code = re.sub(r"//[^\n]*|/\*.*?\*/", "", (ROOT / path).read_text(), flags=re.S) + pragma, body = PRAGMA.search(code), code.find("{") + assert pragma and pragma.start() < body, f"{path}: #pragma STDC FP_CONTRACT OFF does not precede its first function" + found = [word for word in BANNED if word in code] + assert not found, f"{path} uses {found}" + + +def test_references_on_known_values(): + # gr_write_double with a zero injection is R + bo exactly: its weight 2 / (1 + exp(-0 / hc)) is 1. + R, bo, inj = gr_fixture(inj_sd=0.0) + want, bo_w = gr_write_double(R, bo, inj, 4) + bo64 = np.broadcast_to(bo.astype(np.float64)[:, None, :], R.shape) + assert np.array_equal(bo_w, bo64) and np.array_equal(want, R.astype(np.float64) + bo64) + # rel_terms rounds nothing to binary32. On this float32 triple basalt's double rule gives 1.000000007e-6, a failure + # of `const bool plain = worst_plain < 1e-6;` (gr_parity.cpp:645); the denominator |R| + |bo| rounded in binary32 + # (1.875) would give 9.999999747e-7, a pass. + r, b, got = np.float32(0.9375), np.float32(-0.93749994), np.float32(1.9346046e-06) + rel = rel_terms(np.float64(r) + np.float64(b), got, r, b) + assert rel > 1e-6 and abs(rel - 1.000000007e-6) < 1e-15, rel diff --git a/tests/contract/test_basalt_ops.py b/tests/contract/test_basalt_ops.py index e8ab5bd8..608f15e9 100644 --- a/tests/contract/test_basalt_ops.py +++ b/tests/contract/test_basalt_ops.py @@ -4,6 +4,7 @@ defect refused by that defect's own check (its message). The GPU side is tests/kernels/test_basalt_ops_program.py.""" import json +import struct import numpy as np import pytest @@ -25,7 +26,7 @@ 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") +KINDS = ("basalt_q8_1", "basalt_mmvq", "basalt_mmvf", "basalt_dense_tc", "basalt_dense_tc_pair", "basalt_gr_post") Q8_1_FUNCTIONS = {"native": "native_quantize_q8_1", "swiglu": "native_swiglu_quantize_q8_1", "ieee": "quantize_q8_1"} QK = kernels.Q8_1_BLOCK_BYTES @@ -113,6 +114,16 @@ def gemv(g, kind, name, x, *ws, rows=T, widths=None): return ys +def gr_post(g, block_out, r=None, inject=None, width=10240): + """``basalt_gr_post`` of the residual ``r`` (default: an input ``r`` [T, 10240]), ``block_out`` [T, 2560] and the + injections ``inject`` (default: an input ``inject`` [T, 4]) into ``r_out`` [T, ``width``].""" + r = g.input("r", (T, 10240), F32) if r is None else r + inject = g.input("inject", (T, 4), F32) if inject is None else inject + y = g.value("r_out", (T, width), F32) + op(g, "basalt_gr_post", [r, block_out, inject], [y]) + return y + + def emit(g, src, t=1, packs=(), **kw): return emit_program(g, pack=[src, *packs], profile=PROFILE, t=t, tail=None, **kw) @@ -128,7 +139,7 @@ def spliced(source): 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.""" + their own, the hyper-connection write with the 2560-value input as its block output.""" 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} @@ -143,6 +154,7 @@ def all_ops(g, src): *[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)) + gr_post(g, xs[2560]) # ---- registration, and each dispatch against the builders ---------------------------------------------------------- @@ -158,12 +170,22 @@ def test_registered_and_covered(src): 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).""" + """The q8_1 and BF16 grid builders against the harness's own formulas (tests/kernels/basalt_gpu.py); the write's + against basalt's ``blocks`` of 256 threads over T tokens' elements (native_gr_postops.cu:83, :111), and its record + refused by each arm alone, ``check_shape``'s two (a dimension of 0, n_embd * hc past INT_MAX; :79-82) and the + port's 32-bit element bound (T * hc * n_embd at 2^32), and accepted at INT_MAX and at the last T below 2^32.""" 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)) + assert [kernels.basalt_gr_post_grid(n, 4, t) for n, t in ((2560, 1), (2560, 8), (100, 3))] == \ + [(40, 256), (320, 256), (5, 256)] + for n, hc, t in ((2560, 0, 1), (0, 4, 1), (2 ** 16, 2 ** 15, 1), (2 ** 20, 2 ** 10, 4)): + with pytest.raises(ValueError, match=rf"unsupported shape \(n_embd {n}, hc {hc}, T {t}\)"): + kernels.basalt_gr_post_params(n, hc, t) + for n, hc, t in ((2 ** 31 - 1, 1, 1), (2 ** 20, 2 ** 10, 3)): + assert kernels.basalt_gr_post_params(n, hc, t) == struct.pack(" 0.05 and rel_got < 0.05, "const bool visible = rel > 0.05 && rel_got < 0.05;" + + +@pytest.mark.parametrize("n_embd, T, inj_sd", [(256, 1, 3.0), (2560, 8, 3.0), (2560, 8, 2.0)], + ids=["S1-sd3", "S2-sd3", "S2-sd2"]) +def test_injection_weights_against_double(n_embd, T, inj_sd): + """HG-STREAM, gr_parity's nonzero-injection check (gr_parity.cpp:673-692): the double write (``gr_write_double``), + each element's error over its terms ``|R| + |bo w|``; the worst below 1e-6. The injections stay far inside the + rule's range, ``|inject| < 80`` (beyond it the float32 rounding of ``x log2 e`` that basalt shares dominates where + ``|R|`` is small; HG-EMU holds the extremes by bits).""" + R, bo, inj = ref.gr_fixture(n_embd, HC, T, inj_sd=inj_sd) + got = write(R, bo, inj, T, n_embd, in_place=False)[:T] + want, bo_w = ref.gr_write_double(R, bo, inj, HC) + worst_stream = ref.rel_terms(want, got, R, bo_w).max() + print(f"HG-STREAM n_embd {n_embd} T {T} inj_sd {inj_sd}: worst_stream {worst_stream:.3e} (max |inject| " + f"{np.abs(inj).max():.2f}), {n_nonfinite(got)} non-finite") + assert n_nonfinite(got) == 0, "a non-finite output" + assert worst_stream < 1e-6, "const bool streams_ok = worst_stream < 1e-6;" + + +def test_rows_of_a_window_equal_one_row_dispatches(): + """HG-WIN, the window rule (invariant 1) in ple_win_parity's call shape, one token row in place: for T = 1..8, row t + of the T-row dispatch has the bits of the one-row dispatch of token t alone (its rows copied to row 0 of fresh + buffers), and the 8-row dispatch of the reversed window (token k at row 7 - k) gives every token the forward one's + bits. Each dispatch's sentinels checked, and its output finite.""" + n_embd = 2560 + R, bo, inj = ref.gr_fixture(n_embd, HC, 8, inj_sd=3.0) + + def run(R, bo, inj, T): + got = write(R, bo, inj, T, n_embd)[:T] + assert n_nonfinite(got) == 0, f"a non-finite output in a {T}-row dispatch" + return got.view(U32) + + alone = [run(R[t:t + 1], bo[t:t + 1], inj[t:t + 1], 1)[0] for t in range(8)] + for T in range(1, 9): + got = run(R, bo, inj, T) + for t in range(T): + assert np.array_equal(got[t], alone[t]), f"row {t} of the {T}-row window differs from its one-row dispatch" + rev = run(R[::-1], bo[::-1], inj[::-1], 8) + for k in range(8): # got: the last window's, the forward 8-row dispatch + assert np.array_equal(rev[7 - k], got[k]), f"token {k} at row {7 - k} of the reversed window differs" diff --git a/tests/kernels/test_basalt_ops_program.py b/tests/kernels/test_basalt_ops_program.py index cb87b3da..ae1ca96e 100644 --- a/tests/kernels/test_basalt_ops_program.py +++ b/tests/kernels/test_basalt_ops_program.py @@ -2,13 +2,14 @@ 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. +down, the IEEE quantizer on its own, the hyper-connection write on the 2560-value input. 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 + program's own q8_1 rows (or activations) and the file's weights, the write against the harness's launch into a + separate output on the same residual, block output and injections. 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. @@ -145,6 +146,18 @@ def test_mmvf_is_the_harness(runs, name): assert np.array_equal(bits(y), bits(want)), t +def test_gr_post_is_the_harness(runs): + """The hyper-connection write's ``r_out`` at every width, bit for bit the harness's launch into a separate output + (the program's binding) on the program's own residual, block output (``x2560``) and injections, every value + finite.""" + x = runs["inputs"] + for t in WIDTHS: + got = np.frombuffer(runs["wide"][t]["r_out"], F32) + want = gpu.gr_post(x["r"][:t], x["x2560"][:t], x["inject"][:t], t, 2560, 4, in_place=False, fill=0xFE)[0] + assert np.array_equal(bits(got), bits(want[:t].ravel())), t + assert np.all(np.isfinite(got)), 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: diff --git a/third_party/NOTICE b/third_party/NOTICE index ca9100e3..97e2e993 100644 --- a/third_party/NOTICE +++ b/third_party/NOTICE @@ -89,6 +89,10 @@ Format: `` — adapted from / copied from `` `` @ 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_gr_post.metal` and `tests/basalt_hc_ref.py` — through basalt's + `src/kernels/cuda/native_gr_postops.cu` (below), which adapts + `ggml/src/ggml-cuda/{dsv4-hc.cu,scale.cu,unary.cu,unary.cuh}` (MIT): `native_gr_post`'s elementwise arithmetic, in + `tests/basalt_hc_ref.py` re-implemented in numpy (`gr_post_emulation`). 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 @@ -142,9 +146,12 @@ Format: `` — adapted from / copied from `` `` @ `include/basalt/core/model_file.hpp:126-149` as `hc8_write` writes it (`src/core/model_file.cpp:438-485`); the matrix lists of `src/core/verify.cpp:566-581` and `src/core/mtp.cpp:215-218`, `:488-503`, in the order `hc8_dump` writes them (`src/core/verify.cpp:638-640`, `src/core/mtp.cpp:516-521`). License: `third_party/BASALT-LICENSE`. -- `tests/basalt_hc_ref.py`, `tests/contract/test_basalt_hc8.py` — adapted from `src/kernels/cuda/hc_fused.cu:1171-1197`, - `src/core/model_file.cpp:487-513` and `src/kernels/hc8_parity.cpp:69-99` (MIT): a scalar transcription of - `hc8_quant_kernel`, `hc8_read`'s checks and hc8_parity's matrices. License: `third_party/BASALT-LICENSE`. +- `tests/basalt_hc_ref.py`, `tests/contract/test_basalt_hc8.py`, `tests/kernels/test_basalt_gr_post.py` — adapted from + `src/kernels/cuda/hc_fused.cu:1171-1197`, `src/core/model_file.cpp:487-513` and `src/kernels/hc8_parity.cpp:69-99` + (MIT): a scalar transcription of `hc8_quant_kernel`, `hc8_read`'s checks and hc8_parity's matrices; and from + `src/kernels/gr_parity.cpp:136-156`, `:433-454`, `:620-692` (MIT): the double write, its metrics, fixture and pass + criteria; and from `src/kernels/cuda/native_gr_postops.cu:65-74` (MIT): `native_gr_post`'s arithmetic as nvcc compiles + it (`gr_post_emulation`; `docs/research/basalt-nvcc/native_gr_postops.md`). 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 @@ -206,13 +213,15 @@ Format: `` — adapted from / copied from `` `` @ `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`. + `src/kernels/cuda/native_bf16.cu:139-171`, `src/kernels/cuda/iq_kernels.cu:2450-2455` and + `src/kernels/cuda/native_gr_postops.cu:75-82` (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, `native_gr_post`'s launcher checks (non-null four-byte aligned pointers, positive + bounded dimensions)); `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`), and its + `basalt_gr_post_params` and `basalt_gr_post_grid` transcribe `native_gr_post`'s `check_shape`, `THREADS` and `blocks` + (`native_gr_postops.cu:35`, `:79-83`). 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`. @@ -268,6 +277,9 @@ Format: `` — adapted from / copied from `` `` @ 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`. +- `kernels/common/basalt_gr_post.metal` — adapted from `src/kernels/cuda/native_gr_postops.cu:35-41`, `:65-74`, + `:107-114` (MIT): `native_gr_post`, written in the rounding sequence nvcc compiles for it + (`docs/research/basalt-nvcc/native_gr_postops.md`). License: `third_party/BASALT-LICENSE`. ## Test data From 44f83ea323b51e2ac78d9b134650ed703f901e69 Mon Sep 17 00:00:00 2001 From: Lance Woodson <65194841+woodsonl@users.noreply.github.com> Date: Wed, 21 Oct 2026 22:04:59 -0500 Subject: [PATCH 71/74] Port basalt's n-gram block decode path to Metal The net change of woodsonl/mlxstream#31 (fork merge commit 8a7e39f): the grouped RMSNorm and the n-gram block's gate, broadcast, convolution and history kernels, the basalt_ple_block and basalt_ple_commit op kinds with their emitter handlers, and ple_parity's block, key and value checks. --- docs/design/flash-next.md | 10 +- docs/research/basalt-nvcc/ple.md | 486 +++++++++++++ kernels/common/basalt_fp.metal | 16 +- kernels/common/basalt_gr_norm.metal | 54 ++ kernels/common/basalt_ple.metal | 133 ++++ monolith/compiler/emit_basalt.py | 154 +++- monolith/kernels.py | 78 ++ monolith/ops/__init__.py | 2 +- monolith/ops/basalt_ple.py | 95 +++ tests/basalt_ple_ref.py | 417 +++++++++++ .../contract/fixtures/basalt_ple.safetensors | Bin 0 -> 95344 bytes .../fixtures/make_basalt_ple_fixture.py | 81 +++ tests/contract/test_basalt_ple_ops.py | 606 ++++++++++++++++ tests/contract/test_basalt_ple_refs.py | 210 ++++++ tests/contract/test_ci_mac_lane.py | 21 + tests/kernels/basalt_emu.py | 93 ++- tests/kernels/basalt_ple_gpu.py | 277 +++++++ tests/kernels/test_basalt_mmvf.py | 29 +- tests/kernels/test_basalt_nan.py | 76 +- tests/kernels/test_basalt_platform.py | 92 ++- tests/kernels/test_basalt_ple.py | 674 ++++++++++++++++++ tests/kernels/test_basalt_ple_program.py | 361 ++++++++++ third_party/NOTICE | 61 +- tools/ci/mac_gpu.py | 15 +- 24 files changed, 4002 insertions(+), 39 deletions(-) create mode 100644 docs/research/basalt-nvcc/ple.md create mode 100644 kernels/common/basalt_gr_norm.metal create mode 100644 kernels/common/basalt_ple.metal create mode 100644 monolith/ops/basalt_ple.py create mode 100644 tests/basalt_ple_ref.py create mode 100644 tests/contract/fixtures/basalt_ple.safetensors create mode 100644 tests/contract/fixtures/make_basalt_ple_fixture.py create mode 100644 tests/contract/test_basalt_ple_ops.py create mode 100644 tests/contract/test_basalt_ple_refs.py create mode 100644 tests/kernels/basalt_ple_gpu.py create mode 100644 tests/kernels/test_basalt_ple.py create mode 100644 tests/kernels/test_basalt_ple_program.py diff --git a/docs/design/flash-next.md b/docs/design/flash-next.md index 74b7b651..2ea9114a 100644 --- a/docs/design/flash-next.md +++ b/docs/design/flash-next.md @@ -105,9 +105,10 @@ ones this pack runs. `docs/research/basalt-nvcc/` (`matvec.md` for the q8_1 quantizers and `native_mmvq`, `hc_fused.md` for the hyper-connection read, its router and the int8 copies, `native_gr_postops.md` for the hyper-connection write, `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 + `dense_tc.md` for the window projections, `q5k_head.md` for the Q5_K head, `s2_experts.md` for the drafter's experts, + `ple.md` for the n-gram block, `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 @@ -465,6 +466,9 @@ same rule holds for any other ported kernel whose basalt tests end in a comparis | 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`) | +| `native_gr_rms_norm_weighted`: the n-gram block's three grouped norms (`src/kernels/cuda/native_ple_postops.cu:352-353`, `:358`) | `ple_parity`'s norm check runs the legacy `gnorm_kernel`, because the test never calls `ple_set_native_postops` (`src/kernels/ple_parity.cpp:892-912`). `ple_win_parity` runs it only as the reference side (`src/kernels/ple_win_parity.cpp:109`), and `gr_parity` sees it only downstream of a GEMV (`src/kernels/gr_parity.cpp:535`, `:752`) | against a double-precision norm: `const bool wired = le(rel, 2e-6) && nonfinite(actual_result.data(), hcd) == 0;` (`src/kernels/ple_parity.cpp:910`); also bit for bit against a numpy emulation of `ple.md` | +| `native_ple_postops`: the n-gram gate, broadcast, convolution and residual, once per window row (`src/kernels/cuda/ple.cu:320-326`) | `ple_parity`'s block checks run the legacy chain (`src/kernels/ple_parity.cpp:740-783`), and `ple_win_parity` compares it with the window kernel (`src/kernels/ple_win_parity.cpp:109`) | per stage and per row, against a double-precision transcription of the block: `const bool ok = le(rel, 1e-4) && nf == 0;` (`src/kernels/ple_parity.cpp:1119`); also bit for bit against the numpy emulation | +| The n-gram history's per-row snapshot and the commit's restore: `copy_from_mapped` (`src/core/verify.cpp:1123`) and `copy_indexed` (`:2137`; `src/kernels/cuda/verify_kernels.cu:506-512`) | no test runs either on the history; `copy_from_mapped` only stages another test's input (`src/kernels/qsa_dec_fused_parity.cpp:113`) | byte for byte against the source bytes and the host's nine-row shift, for every window width and every kept count, the precedent being `if (ra != rb) {` (`src/kernels/dec_commit_parity.cpp:177`) | The ported `route_window_parity` also runs the shapes this path uses, 2560 to 128 and 2560 to 512. diff --git a/docs/research/basalt-nvcc/ple.md b/docs/research/basalt-nvcc/ple.md new file mode 100644 index 00000000..b79c789f --- /dev/null +++ b/docs/research/basalt-nvcc/ple.md @@ -0,0 +1,486 @@ +# basalt's n-gram block kernels as nvcc compiles them + +What NVIDIA's compiler emits at every rounding site of basalt's n-gram (per-layer embedding, PLE) block on the decode +path after its two projections, read from the sm_120 PTX and SASS, and the Metal form the port writes at each site: +the grouped RMSNorm `weighted_rms_norm` (`native_gr_norm.cu`), the three kernels of `native_ple_postops` +(`gate_kernel`, `broadcast_kernel`, `conv_residual_kernel`) and the history shift `history_advance_kernel` +(`ple.cu`). The two projections the block starts with, the key through `native_quantize_q8_1` and `native_mmvq` +type 42 and the value through `bf16_gemv_fp32_mmvf`, are in `matvec.md` and `bf16.md`. This page is the authority the +Metal kernels follow (`docs/design/flash-next.md`, invariant 5), as `matvec.md` and `bf16.md` are for theirs. + +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. The three files are `src/kernels/cuda/native_gr_norm.cu`, +`src/kernels/cuda/native_ple_postops.cu` and `src/kernels/cuda/ple.cu`. Compiled and read on October 18, 2026. + +## Method + +- **Sources.** The three files whole (102, 398 and 375 lines), each with the `include/basalt/kernels/` headers it + includes inlined recursively under `#line` directives, so the line table cites basalt's own lines: + `native_gr_norm.hpp` (`native_gr_norm.cu:25`); `native_ple_postops.hpp` (with the `ple.hpp` it includes), + `native_gr_norm.hpp`, `verify_kernels.hpp` and `ngram.hpp` (`native_ple_postops.cu:21-24`); `ple.hpp`, + `bf16_gemv.hpp`, `f16_bits.hpp`, `ngram.hpp`, `quantize_act.hpp`, `s2_gemv_q8.hpp`, `native_mmvq.hpp` and + `native_ple_postops.hpp` (`ple.cu:16-23`). System headers (``, ``, ``, ...) + stay includes. Only basalt's public MIT source was sent. +- **Compilers.** Compiler Explorer's public API (`POST https://godbolt.org/api/compiler//compile` with + `"produceDevice": true`), each response holding the PTX and the `SASS (sm_120)` listing: + - `nvcc130`: `Cuda compilation tools, release 13.0, V13.0.48`, `Build cuda_13.0.r13.0/compiler.36260728_0` + (built Wed Jul 16 2025). The tables quote this version. + - `nvcc133`: `Cuda compilation tools, release 13.3, V13.3.33`, `Build cuda_13.3.r13.3/compiler.37862127_0` + (built Fri Apr 24 2026). The check. + + The version strings are each compiler's own `--version` output through the same API. +- **Flags.** No CUDA flag reaches the three files but those below: there is no `CMAKE_CUDA_FLAGS` or + `CMAKE_CUDA_STANDARD` (the C++20 of `CMakeLists.txt:9` is the host compiler's), no `target_compile_options` on the + kernels library (`:118-169`), whose `warnings` options, inherited through `core` (`:97`, `:168`), are guarded by + `$` (`:44-48`), and no separable compilation; the one target with CUDA options of its own, + `mmq` (`:728`), sets them `PRIVATE`. So every file gets the Release flags `-O3 -DNDEBUG` (Release is the + default build type, `:12-14`), `-DBASALT_VERSION="0.0.1"` (`:6-7`) and the one target + `CMAKE_CUDA_ARCHITECTURES 120` (`:3-4`, `:26-31`), which CMake passes as + `--generate-code=arch=compute_120,code=[compute_120,sm_120]` and for which `-arch=sm_120` emits the same device + code. `CMakeLists.txt:185-202`, under the comment `# Match the pinned llama.cpp CUDA arithmetic contract for this + adapter only.` (`:185`), adds `--use_fast_math` to `native_gr_norm.cu` (`:187`) and `native_ple_postops.cu` + (`:195`). `ple.cu` is not in that list (it is at `:146` of the kernels library only) and builds with nvcc's IEEE + defaults: `-ftz=false -prec-div=true -prec-sqrt=true`, and `-fmad=true`. The exact `userArguments` sent: + + | File | `userArguments` | + |---|---| + | `native_gr_norm.cu`, `native_ple_postops.cu` | `-arch=sm_120 -O3 -DNDEBUG '-DBASALT_VERSION="0.0.1"' --use_fast_math` | + | `ple.cu` | `-arch=sm_120 -O3 -DNDEBUG '-DBASALT_VERSION="0.0.1"'` | + + Compiler Explorer prepends `-o /app/output.s -g -lineinfo --keep-device-functions -c -keep -keep-dir + -Xcompiler=-S --compiler-bindir /opt/compiler-explorer/gcc-14.1.0/bin`. `-lineinfo` gives the SASS its source lines; + `-g` is host debug information and does not change device code (a second run of each file with `-lineinfo` added + to `userArguments` gave the same SASS). The host assembly in the same response is gcc 14.1 for x86-64, which is + where section 7 reads the host constants. +- **Translation unit.** Each file whole, with nothing cut: every one of the six requests (three files, two versions) + returned code 0 and a complete SASS listing (13.0: 842, 1873 and 1687 instruction rows). The on-path functions + are `weighted_rms_norm<1024>` (the instantiation every n = 2560 row takes, section 1) and `<256>`, both + instantiated by the file's own launcher; `gate_kernel`, `broadcast_kernel` and `conv_residual_kernel`; and + `history_advance_kernel`. The other functions of the three files are off this path (section 7). +- **Version check.** 13.0 and 13.3 emit the same arithmetic in every on-path function. In `gate_kernel`, + `broadcast_kernel`, `conv_residual_kernel` and `history_advance_kernel` the float, conversion, shuffle, + shared-memory, barrier and global-memory instructions are the same in the same order, registers renamed (the one + textual difference: the line table cites `cuda_fp16.hpp:708` for the half-to-float conversion in 13.0 and `:688` + in 13.3). In `weighted_rms_norm<1024>` the same 114 instructions of those kinds appear in both, the same single FFMA + chain, the same butterflies and the same closing `FFMA.FTZ` and `MUFU.RSQ`; only the `I2FP.F32.S32` and `MUFU.RCP` + that build 1/n issue at a different slot relative to the `LDS`, which changes no value. Neither version emits + `bf16.md`'s diverged-warp copy of a butterfly: every butterfly function has 10 `SHFL.BFLY` in both. + +## Notation + +`matvec.md`'s: fl(e), fma(a, b, c), h(x) (fp16 to fp32, exact), f(n) (int32 to fp32, exact), `.FTZ`, and its account +of what this GPU's arithmetic flushes. The Metal helpers are those of `kernels/common/basalt_fp.metal`: `ftz`, +`add_ftz`, `fma_ftz`, `mul_ftz` (`fma_ftz(a, b, -0)`), `max_ftz`, `abs_ftz`, `rcp_ftz` (`ftz(1.0f / ftz(x))`), +`warp_sum_ftz`, `h2f`, `expf_ftz`, `rsqrtf_ftz` (`ftz(fast::rsqrt(ftz(x)))`), `sqrtf_ftz` (`ftz(fast::sqrt(ftz(x)))`) +and `cuda_nan`. Further: + +- L = fl(log2 e) = 0x3FB8AA3B. The SASS immediate `-1.4426950216293334961` is −L (0xBFB8AA3B), and `expf_ftz(x)` is + `ftz(fast::exp2(mul_ftz(x, L)))` (`basalt_fp.metal:116`). +- ex2(x), rsq(x), sq(x), rcp(x): the results of `MUFU.EX2`, `MUFU.RSQ`, `MUFU.SQRT` and `MUFU.RCP` (PTX + `ex2.approx.ftz.f32`, `rsqrt.approx.ftz.f32`, `sqrt.approx.ftz.f32`, `rcp.approx.ftz.f32`), approximations of 2^x, + 1/√x, √x and 1/x with subnormal inputs and results flushed. NVIDIA documents their error bounds, not their bits. +- ε = `NG_RMS_EPS` = 1e-6f (0x358637BD). `native_ple_postops.cu:36` is `constexpr int N = 2560, H = 4, D = N * H, + HISTORY = 9;`: the embedding width, the four hyper-connection streams, their D = 10240 channels and the history + depth. + +## Summary + +| Kernel | Rounding sequence nvcc 13.x emits (sm_120) | Metal | +|---|---|---| +| `weighted_rms_norm<1024>` (one 2560-wide row per block; three launches per token) | thread t: acc = fma(x_c, x_c, acc) for c = t, t + 1024, t + 2048 below 2560, from +0; butterfly 16, 8, 4, 2, 1 (`FADD.FTZ`); lane 0 of warp w stores `sums[w]`; every warp runs the butterfly over all 32 `sums`; scale = rsq(fma(sum, rcp(f(2560)), ε)): `partial / n_cols` becomes `MUFU.RCP` and its multiply fuses with the add of ε; y_c = fl(fl(scale·x_c)·γ_c) | `fma_ftz` chain; `warp_sum_ftz` twice; `rsqrtf_ftz(fma_ftz(sum, rcp_ftz(float(n_cols)), eps))`; `mul_ftz(mul_ftz(scale, x), g)` | +| `gate_kernel` (one stream per block, 512 threads) | thread t: p_j = fl(k_d·q_d) for d = t + 512 j below 2560; sums_j = fl(0 + p_j); sum = fl(…fl(fl(0 + sums_0) + sums_1)… + sums_7), sums_5..7 = 0; the two butterflies, lanes 16 to 31 adding 0 in the second; s = fma(scale, sum, +0); sign = (s > 0) − (s < 0), 0 for a NaN; mag = sq(max(\|s\|, 1e-6f)); g = rcp(fl(ex2(fl(fl(mag·sign)·(−L))) + 1)) | `mul_ftz`; `add_ftz` with the zero adds kept; `warp_sum_ftz` twice; `fma_ftz(scale, sum, 0.0f)`; `sqrtf_ftz(max_ftz(abs_ftz(s), 1e-6f))`; `rcp_ftz(add_ftz(1.0f, expf_ftz(-mul_ftz(sign, mag))))` | +| `broadcast_kernel` | gated_i = fl(v_(i mod N)·g_(i / N)) | `mul_ftz(value[i % N], gate[i / N])` | +| `conv_residual_kernel` | t_k = fl(x_k·h(w_k)), x_k = history[9c + 3k] for k < 3, x_3 = normalized[c]; sum = fl(fl(fl(t_0 + t_1) + t_2) + t_3); act = fl(sum·rcp(fl(ex2(fl(sum·(−L))) + 1))); result = fl(hidden + fl(gated + act)) | `h2f`, `mul_ftz`, `add_ftz` in the same order; `mul_ftz(sum, rcp_ftz(add_ftz(1.0f, expf_ftz(-sum))))` | +| `history_advance_kernel` (IEEE file) | none: nine 32-bit loads and nine 32-bit stores per channel | a copy of the bits | + +No float operation in the four fast-math functions lacks `.FTZ` (the `MUFU` operations carry it in the PTX; their SASS +prints no modifier), and nothing on the path goes through nvcc's IEEE division or square root: in both versions the PTX +of `native_gr_norm.cu` and `native_ple_postops.cu` has no unflagged `add`, `mul`, `fma` or `sub` `.f32`, no `div.rn` and +no `sqrt.rn`, and their SASS no unflagged `FADD`, `FMUL` or `FFMA` and no `FCHK`. The only conversions on the path are +exact: `I2FP.F32.S32` (n in the norm, the sign in the gate) and `HADD2.F32` (the fp16 convolution weights); there is no +`F2F` and no double-precision instruction. Three sites fuse: the norm's `partial += value * value` (contracted by the +front end, `-fmad=true`: the PTX already has `fma.rn.ftz.f32`), the norm's `partial / n_cols` with the following `+ +epsilon` (fused by `ptxas` alone, section 1) and the gate's explicit `__fmaf_rn`. Every other multiply and add rounds on +its own. A stored NaN is sm_120's 0x7fffffff, which `cuda_nan` writes at each store a NaN can reach (section 6). + +## 1. `weighted_rms_norm` (`native_gr_norm.cu:45-76`) + +The launcher `native_gr_rms_norm_weighted` (`:85-100`) runs `weighted_rms_norm<256>` when `n_cols < 1024` and +`weighted_rms_norm<1024>` otherwise, one block per row (section 7). The block's three norms +(`native_ple_postops.cu:352`, `:353`, `:358`) all pass n_cols = N = 2560 and n_rows = H = 4, so each is four blocks +of 1024 threads: block r normalizes row r of the 4 × 2560 input with row r of the 10240-entry weight (`input`, +`gamma` and `output` all advance by `blockIdx.x * n_cols`, `:50-53`). Thread t below 512 squares columns t, t + 1024 +and t + 2048; thread t from 512 up squares t and t + 1024. The SASS rows are `<1024>`'s; `<256>` has the same +sequence (below). + +| Site | basalt | PTX (13.0) | SASS (13.0) | Metal | +|---|---|---|---|---| +| sum of squares | `:54-58` `float partial = 0.0f;` then per column `partial += value * value;` | `fma.rn.ftz.f32 %f22, %f21, %f21, %f128` | `FFMA.FTZ R10, R21, R21, R10` (29 copies, one chain) | `partial = fma_ftz(v, v, partial)` from `0.0f` | +| warp sum | `:63`, `norm_warp_sum` (`:37-43`): `value += __shfl_xor_sync(0xffffffffu, value, offset, 32);`, offset 16, 8, 4, 2, 1 | `shfl.sync.bfly.b32 %r35\|%p10, %r34, 16, 31, -1`; `add.ftz.f32 %f80, %f130, %f79`; offsets 8, 4, 2, 1 likewise | `SHFL.BFLY PT, R9, R10, 0x10, 0x1f`; `FADD.FTZ R9, R9, R10`; ... ×5 | `warp_sum_ftz(partial)` | +| partial store | `:65` `if (lane == 0) sums[tid / 32] = partial;`; `:66` `__syncthreads();` | `st.shared.f32 [%r46], %f14` under `lane == 0`; `bar.sync 0` | `@!P0 STS [R9], R12`; `BAR.SYNC.DEFER_BLOCKING 0x0` | `if (lane == 0) sums[sg] = partial;` barrier | +| block sum | `:67-69` `partial = 0.0f; if (lane < BlockSize / 32) partial = sums[lane]; partial = norm_warp_sum(partial);` | `ld.shared.f32 %f86, [%r49]` (no guard: `lane < 32` always holds); 5 × (`shfl.sync.bfly`, `add.ftz.f32`) | `LDS R6, [R6]`; `SHFL.BFLY PT, R11, R6, 0x10, 0x1f`; `FADD.FTZ R11, R6, R11`; ... ×5, last `FADD.FTZ R9, R10, R9` | in every SIMD-group: `partial = warp_sum_ftz(sums[lane])` | +| mean | `:71` `const float mean = partial / n_cols;` | `cvt.rn.f32.s32 %f97, %r28`; `div.approx.ftz.f32 %f98, %f96, %f97` | `I2FP.F32.S32 R12, R0` (`R0` = n_cols, `c[0x0][0x398]`); `MUFU.RCP R6, R12` | `rcp_ftz(float(n_cols))` | +| scale | `:72` `const float scale = rsqrtf(mean + epsilon);` | `add.ftz.f32 %f99, %f16, %f98`; `rsqrt.approx.ftz.f32 %f15, %f99` | `FFMA.FTZ R6, R9, R6, UR4` (`UR4` = epsilon, `c[0x0][0x39c]`); `MUFU.RSQ R6, R6` | `rsqrtf_ftz(fma_ftz(partial, rcp_ftz(float(n_cols)), epsilon))` | +| output | `:74` `output[col] = scale * input[col] * gamma[col];` | `mul.ftz.f32 %f101, %f15, %f100`; `mul.ftz.f32 %f103, %f101, %f102` | `FMUL.FTZ R15, R6, R15`; `FMUL.FTZ R15, R15, R16` | `output[col] = cuda_nan(mul_ftz(mul_ftz(scale, input[col]), gamma[col]))` | + +Notes: + +- **The division fuses with the add of ε.** Under `--use_fast_math` the `/` of `:71` is `div.approx.ftz.f32`, which + the PTX ISA defines as a·(1/b): `ptxas` emits `MUFU.RCP` and a multiply. The add of `:72` is `add.ftz.f32` with no + rounding modifier, which the PTX ISA lets the code generator fuse with a multiply ("mul/add sequences with no + rounding modifiers may be optimized to use fused-multiply-add instructions"), and `ptxas` does: the multiply and the + add are one `FFMA.FTZ`, so the argument of `MUFU.RSQ` is fma(sum, rcp(f(n)), ε), rounded once. It is neither + fl(fl(sum·rcp(f(n))) + ε) nor the correctly rounded fl(sum/n) + ε, and the Metal form writes the fma. Both + instantiations and both versions do this; the front end does not (the PTX keeps the division and the add apart). +- **One chain per thread, in column order.** The squares loop is unrolled by 16, then 8, 4 and 1, which makes 29 + static `FFMA.FTZ` in one dependency chain (`R10`, then `R19`, `R18`, `R17`, `R16`, `R15`, back to `R10`), each + taking the previous result as its addend, from +0. Its first term is fma(x, x, +0), which `fma_ftz(v, v, 0.0f)` is. +- **Every warp repeats the block sum.** As the source's comment says (`:60-61`: "Pinned block_reduce: + every warp repeats the final XOR reduction. There is no warp-0-only broadcast or downward-shuffle tree."), all 32 + warps load `sums[lane]` and run the second butterfly, and every thread then computes the scale itself. At + BlockSize 1024 the 32 warps fill all 32 slots, so no zero enters; every thread ends with the same bits (both lanes of + a butterfly pair add the same two values, in either order). In `<256>` (off this path: it serves n_cols below 1024) + lanes 8 to 31 add +0 (`@!P1 LDS`, P1 = lane > 7; PTX `setp.gt.u32` and a `mov.f32` of 0); the rest of its sequence + is `<1024>`'s, instruction for instruction (`I2FP.F32.S32 R14, R0`; `MUFU.RCP R9, R14`; + `FFMA.FTZ R6, R6, R9, UR6`; `MUFU.RSQ`). +- **The butterfly's operand order.** The source adds the received value to its own; the SASS adds them in both + orders. Float addition is commutative (a NaN's payload aside, which `cuda_nan` settles), so `warp_sum_ftz` keeps the + source's order. +- **Flush to zero.** Every operation is `.FTZ`, and `fma_ftz` returns ±2^-126 where the exact fma rounds up to it + (`bf16.md`, section 1, the same rule). The squares cannot be negative and ε is normal, so the argument of `MUFU.RSQ` + is at least ε. +- **The two approximations.** `MUFU.RCP` of 2560.0: `rcp_ftz(2560.0f)` is the correctly rounded 0x39CCCCCD, and + `ptxas` folds `rcp.approx` of the same constant to exactly that value in the prompt path's copy of this norm + (section 7), so the port gives CUDA's bits wherever the hardware returns the value `ptxas` folds to ([H]: no + Blackwell GPU here). `MUFU.RSQ` becomes `fast::rsqrt` (invariant 5); its last bits can differ from CUDA's. + +| Count per instantiation (13.0 = 13.3) | `FFMA.FTZ` | `FADD.FTZ` | `FMUL.FTZ` | `I2FP.F32.S32` | `MUFU.RCP` | `MUFU.RSQ` | `SHFL.BFLY` | `STS` / `LDS` / `BAR` | +|---|---|---|---|---|---|---|---|---| +| `weighted_rms_norm<1024>`, `<256>` | 30 (29 at `:57`, 1 at `:72`) | 10 | 58 (`:74`, 29 × 2) | 1 | 1 | 1 | 10 | 1 / 1 / 1 | + +## 2. `gate_kernel` (`native_ple_postops.cu:41-67`) + +`native_ple_postops.cu:355` launches it as `gate_kernel<<>>`: block g (one per hyper-connection +stream, g < 4) reduces the 2560 products of row g of the normalized key and the normalized query, and thread 0 +stores the stream's gate. Thread t multiplies columns t + 512 j for j < 5; for j = 5 to 7 the column is past N and the +product is the source's literal 0. The kernel's comment (`:42-43`): "SUM_ROWS selects 512 threads for four rows on the +target GPU. Preserve its eight partial lanes and materialized MUL rounding (never a dot FMA)." + +| Site | basalt | PTX (13.0) | SASS (13.0) | Metal | +|---|---|---|---|---| +| products | `:47` `const int d = threadIdx.x + j * 512;` `:48` `const float p = d < N ? __fmul_rn(key[blockIdx.x * N + d], query[blockIdx.x * N + d]) : 0.0f;` | `mul.rn.ftz.f32 %f1, %f13, %f14` (j = 0; j = 1 to 3 likewise, unguarded); j = 4 under `setp.gt.u32 %p1, %r1, 511`; nothing for j = 5 to 7 | `FMUL.FTZ R0, R0, R11`, `FMUL.FTZ R12, R12, R15`, `FMUL.FTZ R16, R16, R19`, `FMUL.FTZ R8, R8, R21`, `@!P0 FMUL.FTZ R3, R6, R3` (`P0`: `ISETP.GT.U32.AND P0, PT, R5, 0x1ff, PT`, t > 511) | `p = d < N ? mul_ftz(key[g * N + d], query[g * N + d]) : 0.0f` | +| eight partials | `:44` `float sums[8] = {};` `:49` `sums[j] += p;` | `add.ftz.f32 %f24, %f1, 0f00000000` (p + 0), one per j < 5 | `FADD.FTZ R0, RZ, R0`, `FADD.FTZ R11, RZ, R12`, `FADD.FTZ R9, RZ, R16`, `FADD.FTZ R8, RZ, R8`; j = 4: `HFMA2 R0, -RZ, RZ, 0, 0` then `@!P0 FADD.FTZ R0, RZ, R3` | `sums[j] = add_ftz(sums[j], p)` from `0.0f` | +| thread sum | `:51` `float sum = 0;` `:53` `for (int j = 0; j < 8; ++j) sum += sums[j];` | `add.ftz.f32 %f25, %f24, 0f00000000`; `add.ftz.f32 %f27, %f25, %f26`; ...; `add.ftz.f32 %f32, %f31, %f65` (+ sums_4); three `add.ftz.f32 ..., 0f00000000` | `FADD.FTZ R0, RZ, R0`; `FADD.FTZ R0, R0, R11`; `FADD.FTZ R9, R0, R9`; `FADD.FTZ R9, R9, R8`; `FADD.FTZ R0, R9, R0`; `FADD.FTZ R0, RZ, R0` ×3 | `sum = add_ftz(sum, sums[j])` for j = 0 to 7, from `0.0f` | +| warp sum | `:55` `sum = warp_sum(sum);`, `warp_sum` (`:37-40`): `for (int offset = 16; offset; offset >>= 1) x += __shfl_xor_sync(0xffffffffu, x, offset);` | `shfl.sync.bfly.b32 %r10\|%p2, %r9, 16, 31, -1`; `add.ftz.f32 %f37, %f35, %f36`; offsets 8, 4, 2, 1 likewise | `SHFL.BFLY PT, R3, R0, 0x10, 0x1f`; `FADD.FTZ R3, R0, R3`; ... ×5 | `warp_sum_ftz(sum)` | +| partial store | `:54` `__shared__ float partials[32];` `:57` `if (!lane) partials[threadIdx.x / 32] = sum;` `:58` `__syncthreads();` | `st.shared.f32 [%r21], %f7` under `setp.ne.s32 %p7, %r4, 0`; `bar.sync 0` | `@!P0 STS [R0], R9`; `BAR.SYNC.DEFER_BLOCKING 0x0` | `if (lane == 0) partials[sg] = sum;` barrier | +| block sum | `:59` `sum = lane < 16 ? partials[lane] : 0.0f;` `:60` `sum = warp_sum(sum);` | `setp.gt.u32 %p8, %r4, 15`; `ld.shared.f32 %f66, [%r24]` (0 for lanes 16 to 31); 5 × (`shfl.sync.bfly`, `add.ftz.f32`) | `MOV R2, RZ`; `@!P1 LDS R2, [R8]` (`P1`: lane > 15); `SHFL.BFLY PT, R3, R2, 0x10, 0x1f`; `FADD.FTZ R3, R3, R2`; ... ×5, the last `FADD.FTZ R0, R10, R5` | `sum = warp_sum_ftz(lane < 16 ? partials[lane] : 0.0f)` | +| scale | `:61` `if (threadIdx.x == 0) {` `:62` `const float s = __fmaf_rn(scale, sum, 0.0f); // ggml SCALE's zero bias` | `fma.rn.ftz.f32 %f55, %f11, %f10, 0f00000000` | `FFMA.FTZ R0, R0, UR6, RZ` (`UR6` = scale, `LDCU UR6, c[0x0][0x398]`) | `s = fma_ftz(scale, sum, 0.0f)` | +| magnitude | `:63` `const float mag = sqrtf(fmaxf(fabsf(s), 1e-6f));` | `abs.ftz.f32 %f56, %f55`; `max.ftz.f32 %f57, %f56, 0f358637BD`; `sqrt.approx.ftz.f32 %f58, %f57` | `FMNMX.FTZ R0, \|R0\|, 9.9999999747524270788e-07, !PT`; `MUFU.SQRT R0, R0` | `mag = sqrtf_ftz(max_ftz(abs_ftz(s), 1e-6f))` | +| sign | `:64` `const float sign = float((s > 0.0f) - (s < 0.0f));` | `setp.gt.ftz.f32 %p15, %f55, 0f00000000`; `selp.u32 %r35, 1, 0, %p15`; `setp.lt.ftz.f32 %p16, %f55, 0f00000000`; `selp.s32 %r36, -1, 0, %p16`; `add.s32 %r37, %r36, %r35`; `cvt.rn.f32.s32 %f59, %r37` | `FSETP.GT.FTZ.AND P0, PT, R0, RZ, PT`; `FSETP.GEU.FTZ.AND P1, PT, R0, RZ, PT`; `MOV R3, RZ`; `SEL R2, RZ, 0x1, !P0`; `@!P0 IADD3 R3, PT, PT, RZ, -0x1, RZ`; `@P1 IADD3 R3, PT, PT, R2, RZ, RZ`; `I2FP.F32.S32 R3, R3` | `sign = float((s > 0.0f) - (s < 0.0f))` | +| gate | `:65` `gate[blockIdx.x] = 1.0f / (1.0f + expf(-__fmul_rn(sign, mag)));` | `mul.rn.ftz.f32 %f60, %f59, %f58`; `mul.ftz.f32 %f61, %f60, 0fBFB8AA3B`; `ex2.approx.ftz.f32 %f62, %f61`; `add.ftz.f32 %f63, %f62, 0f3F800000`; `rcp.approx.ftz.f32 %f64, %f63`; `st.global.f32 [%rd23], %f64` | `FMUL.FTZ R3, R0, R3`; `FMUL.FTZ R6, R3, -1.4426950216293334961`; `MUFU.EX2 R6, R6`; `FADD.FTZ R7, R6, 1`; `MUFU.RCP R7, R7`; `STG.E desc[UR4][R4.64], R7` | `gate[g] = rcp_ftz(add_ftz(1.0f, expf_ftz(-mul_ftz(sign, mag))))` | + +Notes: + +- **No dot-product FMA.** Every product is `__fmul_rn`, which PTX keeps as `mul.rn.ftz.f32`: a multiply with a + rounding modifier is never fused, so each product rounds before it is added, as the comment at `:43` demands and as + `docs/design/flash-next.md` records for this kernel. The one fused operation is the explicit `__fmaf_rn` of `:62`. +- **The zero adds stay.** `sums[j] += p` adds p to the +0 of `:44`, and the thread's sum adds `sums[5..7]`, which are + the literal 0. nvcc keeps all of these as `add.ftz` of 0 because x + 0 is not x for x = −0. Their only effect is + to turn a −0 product into +0. The thread's sum starts from +0, so it is never −0 with or without them, and the gate + of s = ±0 is 0.5 either way. The Metal writes the source's two loops, zero adds included, so it needs no argument + about them. +- **The summation order.** Thread t's sum is fl(…fl(fl(fl(0 + s_0) + s_1) + s_2)… + s_7) with s_j = fl(0 + p_j); the + first butterfly runs in each of the 16 warps; lane 0 of warp w stores `partials[w]`; then every warp runs the + second butterfly over `partials[0..15]` with lanes 16 to 31 contributing +0, and only thread 0 uses its result. + The order is fixed by the 512-thread block: the Metal kernel runs 4 threadgroups of 512 threads (16 SIMD-groups) + and reads only `partials[0..15]` (basalt declares 32 entries and writes 16). Only SIMD-group 0 needs the second + butterfly; running it in all 16, as CUDA does, gives the same value. `SHFL.BFLY` adds the received value on either + side (`FADD.FTZ R3, R0, R3` in the first butterfly, `FADD.FTZ R3, R3, R2` in the second); float addition is + commutative, so `warp_sum_ftz`'s single order gives the same bits. +- **The scale.** `__fmaf_rn(scale, sum, 0.0f)` is an FFMA with a +0 addend: one rounding of scale·sum, a −0 product + becomes +0, and a result that rounds to a subnormal is flushed to the zero of its sign. `fma_ftz(scale, sum, 0.0f)` is + that instruction, including the exact-value check at 2^-126 (`basalt_fp.metal:65-81`); `mul_ftz` would differ on the + sign of a zero only. The scale is the host's constant 1/√2560 (section 7). +- **The sign.** The SASS computes `(s > 0) - (s < 0)` as `FSETP.GT` and `FSETP.GEU` (greater, or equal, or unordered) + with selects: 1 for s > 0, −1 for s < 0, and 0 for s = ±0 and for a NaN, since both of C's comparisons are false on + a NaN. Metal's comparisons give the same three cases, and s, an `FFMA.FTZ` result, is never subnormal. +- **The gate is never NaN.** For a NaN s the sign is 0 and `fmaxf` returns its other operand (`FMNMX` and Metal's + `fmax` both return the number when one operand is NaN), so mag = sq(1e-6f), sign·mag = +0, and the gate is + rcp(1 + ex2(−0)) = rcp(2) = 0.5 on both. The gate store therefore needs no `cuda_nan`. An infinite s needs a sum of + products above 2^128 / scale; for it CUDA gives 1 (s = +∞) and 0 (s = −∞). +- **The exponential and the reciprocal.** `expf` under `--use_fast_math` is `ex2.approx.ftz` of x·L, and the front end + folds the negation of `-__fmul_rn(sign, mag)` into the constant: the SASS multiplies by −L. `expf_ftz(-m)` computes + `mul_ftz(-m, L)`, which has the bits of fl(m·(−L)) because rounding to nearest even and the flush are symmetric in + sign, so the Metal form matches the SASS without a second helper. `1.0f / x` is `rcp.approx.ftz.f32`, one + `MUFU.RCP` and no multiply (section 6); `rcp_ftz` stands for it (invariant 5). + +| Count (13.0 = 13.3) | `FMUL.FTZ` | `FADD.FTZ` | `FFMA.FTZ` | `FMNMX.FTZ` | `FSETP` | `I2FP.F32.S32` | `MUFU.SQRT` | `MUFU.EX2` | `MUFU.RCP` | `SHFL.BFLY` | `STS` / `LDS` / `BAR` | +|---|---|---|---|---|---|---|---|---|---|---|---| +| `gate_kernel` | 7 (5 at `:48`, 2 at `:65`) | 24 (5 at `:49`, 8 at `:53`, 10 in the butterflies, 1 at `:65`) | 1 (`:62`) | 1 | 2 (`.GT.FTZ`, `.GEU.FTZ`) | 1 | 1 | 1 | 1 | 10 | 1 / 1 / 1 | + +## 3. `broadcast_kernel` (`native_ple_postops.cu:68-71`) + +`native_ple_postops.cu:356` launches it as `broadcast_kernel<<>>`: 40 blocks of 256 threads, one +thread per channel i of the D = 10240 hyper-connection channels. Channel i of stream i / N takes the projected value's +entry i mod N times that stream's gate. + +| Site | basalt | PTX (13.0) | SASS (13.0) | Metal | +|---|---|---|---|---| +| index | `:69` `const int i = blockIdx.x * blockDim.x + threadIdx.x;` `:70` `if (i < D)` | `mad.lo.s32 %r1, %r2, %r3, %r4`; `setp.gt.s32 %p1, %r1, 10239` | `IMAD R9, R9, UR4, R0`; `ISETP.GT.AND P0, PT, R9, 0x27ff, PT`; `@P0 EXIT` | `if (i < D)` | +| stream and column | `i / N`, `i % N` | `mul.hi.s32 %r5, %r1, 1717986919`; `shr.u32 %r6, %r5, 31`; `shr.s32 %r7, %r5, 10`; `add.s32 %r8, %r7, %r6`; `mul.lo.s32 %r9, %r8, 2560`; `sub.s32 %r10, %r1, %r9` | `IMAD.HI R0, R9, 0x66666667, RZ`; `SHF.R.U32.HI R7, RZ, 0x1f, R0`; `LEA.HI.SX32 R7, R0, R7, 0x16`; `IMAD R11, R7, -0xa00, R9` | `i / N`, `i % N` (exact integer arithmetic) | +| product | `:70` `gated[i] = __fmul_rn(value[i % N], gate[i / N]);` | `mul.rn.ftz.f32 %f3, %f1, %f2`; `st.global.f32 [%rd12], %f3` | `FMUL.FTZ R9, R2, R5`; `STG.E desc[UR4][R6.64], R9` | `gated[i] = cuda_nan(mul_ftz(value[i % N], gate[i / N]))` | + +Notes: + +- **One rounding per channel.** The product is the whole arithmetic: fl(v·g) with both operands and the result + flushed. The index arithmetic is the compiler's exact division by the constant 2560 (multiply-high by 0x66666667, + shift by 10, add the sign bit), the same quotient and remainder as Metal's integer `/` and `%`. +- **NaN.** The gate is never NaN (section 2), but a NaN value or an infinite value times a zero gate gives a NaN, so + the store applies `cuda_nan`. `gated` feeds the third norm and the residual add of section 4. +- **Geometry.** The kernel is elementwise: any Metal grid that covers the 10240 channels once gives the same bits. + +| Count (13.0 = 13.3) | `FMUL.FTZ` | other float | +|---|---|---| +| `broadcast_kernel` | 1 | none | + +## 4. `conv_residual_kernel` (`native_ple_postops.cu:72-89`) + +`native_ple_postops.cu:359` launches it as `conv_residual_kernel<<>>`: one thread per channel c of +the 10240. The history is channel-major, nine floats per channel (`history[c * HISTORY + r]`, row 8 the newest), so +before this token's advance (section 5) rows 0, 3 and 6 hold the normalized rows of tokens t − 9, t − 6 and t − 3, and +the fourth tap is this token's `normalized[c]`, the third norm's output: kernel 4, dilation 3, causal. The weights +are fp16 bits, four per channel. + +| Site | basalt | PTX (13.0) | SASS (13.0) | Metal | +|---|---|---|---|---| +| index | `:75` `const int c = blockIdx.x * blockDim.x + threadIdx.x;` `:76` `if (c >= D) return;` | `mad.lo.s32 %r1, %r2, %r3, %r4`; `setp.gt.s32 %p1, %r1, 10239` | `IMAD R0, R0, UR4, R3`; `ISETP.GT.AND P0, PT, R0, 0x27ff, PT`; `@P0 EXIT` | `if (c >= D) return;` | +| taps | `:80` `const float x = k == 3 ? normalized[c] : history[c * HISTORY + 3 * k];` `:81` `const float w = __half2float(__ushort_as_half(weights[c * 4 + k]));` | `ld.global.f32 %f5, [%rd18]` (`+12`, `+24` for k = 1, 2); `ld.global.f32 %f13, [%rd16]` (k = 3); `ld.global.u16 %rs1, [%rd20]` (`+2`, `+4`, `+6`); `cvt.f32.f16 %f1, %rs1` (`cuda_fp16.hpp:708`) | `LDG.E R8, desc[UR4][R4.64]`, `R4.64+0xc`, `R4.64+0x18`; `LDG.E R2, desc[UR4][R2.64]`; `LDG.E.U16 R9, desc[UR4][R6.64]`, `+0x2`, `+0x4`, `+0x6`; `HADD2.F32 R9, -RZ, R9.H0_H0` (×4) | `x = k == 3 ? normalized[c] : history[c * HISTORY + 3 * k]`; `w = h2f(weights[c * 4 + k])` | +| terms and sum | `:77` `float sum = 0;` `:82` `const float term = __fmul_rn(x, w);` `:83` `sum = k == 0 ? term : __fadd_rn(sum, term);` | `mul.rn.ftz.f32 %f6, %f5, %f1`; `mul.rn.ftz.f32 %f8, %f7, %f2`; `add.rn.ftz.f32 %f9, %f6, %f8`; `mul.rn.ftz.f32 %f11, %f10, %f3`; `add.rn.ftz.f32 %f12, %f9, %f11`; `mul.rn.ftz.f32 %f14, %f13, %f4`; `add.rn.ftz.f32 %f15, %f12, %f14` | `FMUL.FTZ R8, R8, R9`; `FMUL.FTZ R11, R10, R11`; `FADD.FTZ R8, R8, R11`; `FMUL.FTZ R13, R12, R13`; `FMUL.FTZ R9, R2, R9`; `FADD.FTZ R8, R8, R13`; `FADD.FTZ R8, R8, R9` | `term = mul_ftz(x, w)`; `sum = k == 0 ? term : add_ftz(sum, term)` | +| SiLU | `:85` `const float activation = sum / (1.0f + expf(-sum));` `:86` `conv[c] = activation;` | `mul.ftz.f32 %f16, %f15, 0fBFB8AA3B`; `ex2.approx.ftz.f32 %f17, %f16`; `add.ftz.f32 %f18, %f17, 0f3F800000`; `div.approx.ftz.f32 %f19, %f15, %f18`; `st.global.f32 [%rd21], %f19` | `FMUL.FTZ R9, R8, -1.4426950216293334961`; `MUFU.EX2 R9, R9`; `FADD.FTZ R10, R9, 1`; `MUFU.RCP R11, R10`; `FMUL.FTZ R11, R8, R11`; `STG.E desc[UR4][R2.64], R11` | `act = mul_ftz(sum, rcp_ftz(add_ftz(1.0f, expf_ftz(-sum))))`; `conv[c] = cuda_nan(act)` | +| residual | `:88` `result[c] = __fadd_rn(hidden[c], __fadd_rn(gated[c], activation));` | `add.rn.ftz.f32 %f22, %f21, %f19`; `add.rn.ftz.f32 %f23, %f20, %f22`; `st.global.f32 [%rd24], %f23` | `FADD.FTZ R13, R11, R6` (`R6` = `gated[c]`); `FADD.FTZ R13, R4, R13` (`R4` = `hidden[c]`); `STG.E desc[UR4][R8.64], R13` | `result[c] = cuda_nan(add_ftz(hidden[c], add_ftz(gated[c], act)))` | + +Notes: + +- **No FMA anywhere.** Every multiply and add of the convolution and the residual is `__fmul_rn` or `__fadd_rn`, kept + as `mul.rn.ftz` and `add.rn.ftz`, which are never fused. The sum is fl(fl(fl(t_0 + t_1) + t_2) + t_3) in k order, + starting from the first term itself (the `0` of `:77` is never added). The SASS line table attributes the three adds + of `:83` to `:82`. +- **The fp16 weights.** `HADD2.F32 R, -RZ, R.H0_H0` converts the low fp16 half to fp32 exactly (h(x)), fp16 + subnormals and signed zeros included; `h2f` is that conversion. +- **The SiLU's division.** `sum / (1.0f + expf(-sum))` is `div.approx.ftz.f32` under `--use_fast_math`: `MUFU.RCP` of + the denominator, then `FMUL.FTZ` by sum (section 6). The PTX folds the negation of `-sum` into the constant (×(−L)), + which `expf_ftz(-sum)` matches bit for bit (section 2). The product is followed by `__fadd_rn`, which cannot fuse, + so the activation is materialized as stored. +- **A flushed reciprocal.** For a finite sum below about −87.34 the denominator 1 + e^(−sum) is at least 2^126, its + reciprocal is subnormal (or 0 once e^(−sum) overflows), the `.FTZ` makes it +0, and the activation is −0 where the + quotient is a tiny negative number; for sum = −∞ it is −∞·0 = NaN. `rcp_ftz` reproduces both. Where 1 + ex2 lands + within an ulp of 2^126 the boundary follows the last bit of `MUFU.EX2`, which `fast::exp2` need not share. +- **NaN.** A NaN tap or weight, or sum = −∞, makes the activation NaN, and a NaN or opposite infinities in `hidden`, + `gated` or the activation make the result NaN; both stores apply `cuda_nan`. +- **Aliasing.** `result` may be `hidden` (`:346` exempts exactly that pair; `ple.cu` passes the residual row as both, + section 7). Each thread reads `hidden[c]` before it stores `result[c]`, and no other thread touches channel c, so the + Metal kernel binds the same buffer twice and reads before it writes. + +| Count (13.0 = 13.3) | `FMUL.FTZ` | `FADD.FTZ` | `HADD2.F32` | `MUFU.EX2` | `MUFU.RCP` | `FFMA` | stores | +|---|---|---|---|---|---|---|---| +| `conv_residual_kernel` | 6 (4 at `:82`, 2 at `:85`) | 6 (3 at `:83`, 1 at `:85`, 2 at `:88`) | 4 | 1 | 1 | 0 | 2 (`conv`, `result`) | + +## 5. `history_advance_kernel` (`ple.cu:46-52`) + +`ple_history_advance` (`ple.cu:204-212`) checks both pointers and that the history (9 × 10240 floats) and +`normalized` (10240 floats) do not overlap (`:207-209`, `overlap` at `:40-44`), then launches +`history_advance_kernel<<<(NG_HC_DIM + THREADS - 1) / THREADS, THREADS, 0, (cudaStream_t) stream>>>(hist, normalized);` +(`:210`) with `THREADS = 256` (`:36`): 40 blocks of 256 threads, one thread per channel. `ple.cu` is the IEEE-built +file, but this kernel performs no float arithmetic. + +| Site | basalt | PTX (13.0) | SASS (13.0) | Metal | +|---|---|---|---|---| +| index | `:46` `__global__ void history_advance_kernel(float* __restrict__ history, const float* __restrict__ normalized) {` `:47` `const int channel = blockIdx.x * blockDim.x + threadIdx.x;` `:48` `if (channel >= NG_HC_DIM) return;` | `mad.lo.s32 %r1, %r2, %r3, %r4`; `setp.gt.s32 %p1, %r1, 10239` | `IMAD R7, R7, UR4, R0`; `ISETP.GT.AND P0, PT, R7, 0x27ff, PT`; `@P0 EXIT` | `if (c >= NG_HC_DIM) return;` | +| column | `:49` `float* column = history + (size_t) channel * NG_HIST;` | `mul.wide.s32 %rd5, %r1, 36` | `IMAD.WIDE R2, R7, 0x24, R2` | `column = history + c * NG_HIST` | +| shift | `:50` `for (int row = 0; row + 1 < NG_HIST; ++row) column[row] = column[row + 1];` | `ld.global.f32 %f1, [%rd6+4]`; `st.global.f32 [%rd6], %f1`; ... to `ld.global.f32 %f8, [%rd6+32]`; `st.global.f32 [%rd6+28], %f8` | `LDG.E R7, desc[UR4][R2.64+0x4]` ... `LDG.E R21, desc[UR4][R2.64+0x20]` (rows 1 to 8, all loaded first); `STG.E desc[UR4][R2.64], R7` ... `STG.E desc[UR4][R2.64+0x1c], R21` | the same loop | +| newest row | `:51` `column[NG_HIST - 1] = normalized[channel];` | `ld.global.nc.f32 %f9, [%rd8]`; `st.global.f32 [%rd6+32], %f9` | `LDG.E.CONSTANT R5, desc[UR4][R4.64]`; `STG.E desc[UR4][R2.64+0x20], R5` (stored before the shifted rows) | `column[NG_HIST - 1] = normalized[c]` | + +Notes: + +- **Bits, not values.** The kernel is nine 32-bit loads and nine 32-bit stores per channel and no float instruction, + so the file's IEEE build (no `.ftz`) changes nothing here: subnormals and NaN payloads move unchanged, as a Metal + float load and store (a register move) also keep them. No IEEE emulation is needed on this path: `ple.cu` + contributes no arithmetic to it (section 7). +- **Order.** The PTX keeps the source's load-store order; `ptxas` hoists all nine loads ahead of the stores, which the + two `__restrict__` qualifiers and the launcher's overlap check make legal. Each thread owns one 36-byte column, so + the source's loop (each row read before it is overwritten) gives the same result as the hoisted order. +- **What the history holds.** `normalized` here is the third norm's output, exported from the block's scratch + (section 7), so row 8 is this token's normalized row, the fourth tap of the next token's convolution. + +| Count (13.0 = 13.3) | float instructions | `LDG.E` | `LDG.E.CONSTANT` | `STG.E` | +|---|---|---|---|---| +| `history_advance_kernel` | 0 | 8 | 1 | 9 | + +## 6. The fast-math idioms + +`--use_fast_math` implies `--ftz=true --prec-div=false --prec-sqrt=false --fmad=true` and maps `expf` to `__expf`. +In the two fast-math files it gives each library call and each division one fixed instruction sequence, the same in +13.0 and 13.3: + +| Source | PTX | SASS (sm_120) | Sites | Metal | +|---|---|---|---|---| +| `sqrtf(x)` | `sqrt.approx.ftz.f32` | `MUFU.SQRT` alone: no `MUFU.RSQ` and multiply, no fix-up | gate `:63` | `sqrtf_ftz(x)` | +| `rsqrtf(x)` | `rsqrt.approx.ftz.f32` | `MUFU.RSQ` alone | norm `:72` | `rsqrtf_ftz(x)` | +| `expf(-x)` | `mul.ftz.f32 t, x, 0fBFB8AA3B`; `ex2.approx.ftz.f32 e, t` | `FMUL.FTZ t, x, -1.4426950216293334961`; `MUFU.EX2 e, t` | gate `:65`, conv `:85` | `expf_ftz(-x)` | +| `a / b` | `div.approx.ftz.f32 d, a, b` | `MUFU.RCP r, b`; `FMUL.FTZ d, a, r` | conv `:85` | `mul_ftz(a, rcp_ftz(b))` | +| `a / b`, then `+ c` | `div.approx.ftz.f32 q, a, b`; `add.ftz.f32 d, c, q` | `MUFU.RCP r, b`; `FFMA.FTZ d, a, r, c` | norm `:71-72` | `fma_ftz(a, rcp_ftz(b), c)` | +| `1.0f / x` | `rcp.approx.ftz.f32 d, x` | `MUFU.RCP d, x` alone | gate `:65` | `rcp_ftz(x)` | + +Notes: + +- **`sqrtf` is `MUFU.SQRT`.** sm_120 has a square-root unit operation, and `sqrt.approx.ftz.f32` compiles to it + directly; it is not the reciprocal square root followed by a multiply. Invariant 5 maps it to `fast::sqrt`, the + `metal::fast` function of the same operation. +- **`expf` is one multiply and `MUFU.EX2`.** `__expf(x)` is `ex2.approx.ftz` of fl(x·L) with no range reduction and no + correction term; both on-path calls take a negated argument, and the front end folds the negation into the constant + (0fBFB8AA3B = −L). Rounding to nearest even and the flush are symmetric in sign, so `expf_ftz(-x)`, which computes + `mul_ftz(-x, L)` = fl((−x)·L), has exactly the bits of the SASS multiply fl(x·(−L)). The multiply is `mul.ftz.f32` + without `.rn` and so could fuse with an add it fed; in both sites it feeds `ex2`. The library `expf` of an IEEE file + (a different, longer sequence that the contract maps to `metal::precise::exp`) does not occur on this path. +- **Every division is a reciprocal.** `div.approx.f32` is defined by the PTX ISA as a·(1/b), and `ptxas` emits exactly + that: `MUFU.RCP` of the divisor and an `FMUL.FTZ`. The multiply carries no rounding modifier, so where an add without + one consumes the quotient (norm `:72`) `ptxas` fuses them into an `FFMA.FTZ`. `1.0f / x` skips the multiply. None of + these has an `FCHK` or a slow path: both fast-math files compile to no `FCHK` at all, and their PTX has no `div.rn` + and no `sqrt.rn`. For a divisor of magnitude above 2^126 the flushed reciprocal is 0 (the PTX ISA documents 0 for + `div.approx.f32` there, and NaN for an infinite dividend), which `rcp_ftz` also gives. +- **The approximations.** NVIDIA documents error bounds for `MUFU.SQRT`, `MUFU.RSQ`, `MUFU.EX2` and `MUFU.RCP`, not + their bits. Invariant 5 maps each to `fast::sqrt`, `fast::rsqrt`, `fast::exp2` and the correctly rounded reciprocal, + so the norm's scale, the gate and the SiLU can differ from CUDA in the last bits while every rounding around them is + CUDA's. The one approximation with a constant argument, `MUFU.RCP` of 2560.0 in the norm, is discussed in section 1 + and section 7. +- **NaN.** Every `FADD`, `FMUL`, `FFMA`, `MUFU.RCP` and `MUFU.EX2` that makes or passes a NaN gives sm_120's canonical + 0x7fffffff, where this GPU gives 0x7fc00000 (`nan.md`), so each store a NaN can reach applies `cuda_nan`: the norm's + output (a NaN in the row or in γ, or an infinity, whose square makes the scale rsq(+∞) = +0 and its own column ∞·0), + `gated` (section 3), `conv` and `result` (section 4). The gate cannot be NaN (section 2), and the history advance + moves bits that already carry CUDA's NaN (section 5). The NaN behavior inside the kernels that decides values is + shared: a NaN compares false, `fmaxf` and Metal's `fmax` return the number, and the gate's sign of a NaN is 0. The + infinity cases (rsq(+∞) = +0, ex2(−∞) = +0, ex2(+∞) = +∞, sq(+∞) = +∞) rest on the `metal::fast` functions + returning the limits there, which they do on this GPU [M] + (`tests/kernels/test_basalt_platform.py::test_fast_limits_at_infinity`). + +## 7. Launches, host constants and the code off this path + +Per verify-window row, `verify.cpp:1105-1124` calls `ple_block` (`ple.cu:228-356`) with the row's residual as both +`hidden` and the result (`po.result = Rt(t)`), then `ple_history_advance(hist, normalized, cs)` (`:1118`), then +snapshots the history (`copy_from_mapped(hist_snap_ + t * HS, hist, HS, cs)`, `:1123`); the commit restores the kept +row's snapshot with `copy_indexed` (`verify.cpp:2137`). The snapshot, the restore and `ple_block`'s exports +(`cudaMemcpyAsync` device to device, `ple.cu:341-350`) copy bytes. On this pack's branch (`native_key` and +`native_postops`; `generate.cpp:2419` sets the latter) `ple_block` does no float arithmetic on the host: it carves its +scratch (`ple.cu:282-292`), projects the key (`native_quantize_q8_1` and `native_mmvq`, `:299-301`) and the value +(`bf16_gemv_fp32_mmvf`, `:312-313`), and calls `native_ple_postops(d_key,hidden,d_value,hist_rows,w,buffers,stream)` +(`:325`) with `NativePlePostopsBuffers buffers{d_query,d_norm,d_gate,d_gated,d_norm,d_conv,out.result};` (`:324`). The +block's launches, in stream order: + +| # | Launch | Grid × threads | Arithmetic arguments | +|---|---|---|---| +| 1 | `native_gr_rms_norm_weighted(projected_key,w.norm_key,b.key,N,H,NG_RMS_EPS,stream);` (`native_ple_postops.cu:352`) → `weighted_rms_norm<1024>` | 4 × 1024 | n_cols = 2560 (`I2FP` and `MUFU.RCP` on the device), ε = 0x358637BD | +| 2 | `native_gr_rms_norm_weighted(hidden,w.norm_query,b.query,N,H,NG_RMS_EPS,stream);` (`:353`) | 4 × 1024 | as 1 | +| 3 | `gate_kernel<<>>(b.key,b.query,b.gate,1.0f / std::sqrt(float(N)));` (`:355`) | 4 × 512 | scale = 0x3CA1E89B | +| 4 | `broadcast_kernel<<>>(value,b.gate,b.gated);` (`:356`) | 40 × 256 | none | +| 5 | `native_gr_rms_norm_weighted(b.gated,w.norm_conv,b.normalized,N,H,NG_RMS_EPS,stream);` (`:358`) | 4 × 1024 | as 1 | +| 6 | `conv_residual_kernel<<>>(history,b.normalized,w.conv1d_f16,hidden,b.gated,b.conv,b.result);` (`:359`) | 40 × 256 | none | +| 7 | `history_advance_kernel<<<(NG_HC_DIM + THREADS - 1) / THREADS, THREADS, 0, (cudaStream_t) stream>>>(hist, normalized);` (`ple.cu:210`) | 40 × 256 | none | + +Notes: + +- **The two host constants.** The host compiler folds the gate's `1.0f / std::sqrt(float(N))`: Compiler Explorer's + host assembly (gcc 14.1) holds `.LC27: .long 1017243803`, 0x3CA1E89B = 0.019764235, loaded by + `movss .LC27(%rip), %xmm0` for both gate launches of the file. It is the correctly rounded reciprocal of the correctly + rounded √2560 (0x424A62C2), so any IEEE host computes the same bits. `NG_RMS_EPS` is `.LC24: .long 897988541`, + 0x358637BD, at `:352`, `:353` and `:358`. Both are model constants, not per-step values, so invariant 4 allows them + in a params record or in the kernel source; the port uses these two bit patterns. +- **The buffers alias by design.** `b.query` and `b.normalized` are both `d_norm` ("temporary query storage can be + reused for normalized gated values after the gate consumes it", `ple.cu:322-323`), and `b.result` is `hidden`; the + span checks allow exactly these two pairs (`native_ple_postops.cu:344-351`). The third norm overwrites the normalized + query, so the Metal program must order launch 5 after launch 3 (a barrier, as the CUDA stream's order gives), and + `normalized` reaches the history through the export of `d_norm` (`ple.cu:347-348`). +- **The launcher's checks.** `native_gr_rms_norm_weighted` (`native_gr_norm.cu:85-100`) refuses n_cols ≤ 0, + n_rows ≤ 0 and a negative or non-finite ε, requires non-null 4-byte-aligned pointers, and picks + `weighted_rms_norm<256>` for n_cols below 1024, `<1024>` otherwise, one block per row. + `native_ple_postops` (`:336-351`) refuses a null stream, validates each span and the overlaps above. + +### Off this path + +- **`native_gr_norm.cu`.** Only `weighted_rms_norm<256>` (section 1, the same sequence). +- **`native_ple_postops.cu`.** The window kernels (`post_sigmoid` `:162`, `win_rms_scale` `:164-185`, + `ple_win_rows_dev`/`ple_win_rows_kernel` `:193-267`, `ple_win_conv_dev`/`ple_win_conv_kernel`/`ple_win_conv_seg` + `:269-315`, launched by `native_ple_window` `:363-380`) serve the window branch (`verify.cpp:1091-1103`), which + `verify.cpp:1058-1066` takes only with a BF16 key (`ss.ple.w.key_bf16 != nullptr`), never with this pack's Q2_0 key. + The batch kernels are the prompt path's (next subsection). +- **`ple.cu`.** The legacy IEEE chain (`block_sum` `:74-87`, `gnorm_kernel` `:92-109`, `gate_kernel(int, float)` + `:115-127`, `bcast_kernel` `:130-135`, `conv_kernel` `:147-163`, `add3_kernel` `:166-170`), `bf16_gemv_kernel` + `:175-183` and `to_bf16_kernel` `:185-188` run only while `native_postops` or `native_bf16` is false (their defaults, + `ple.cu:37-38`), which `generate.cpp` never allows for this pack; `src/kernels/ple_parity.cpp` never calls + `ple_set_native_postops`, so its block checks run that chain, not `native_ple_postops`. Every IEEE-only instruction of + the three files is in it: the 35 `F2F.F64.F32`/`F2F.F32.F64`, the one `FCHK` (`conv_kernel`), `F2I`/`I2F.RP` + (`bcast_kernel`), the `DADD`/`DFMA`/`DMUL` (`bf16_gemv_kernel`, `gate_kernel(int, float)`, `gnorm_kernel`) and the + slow paths `__cuda_sm3x_div_rn_noftz_f32_slowpath`, `__cuda_sm20_rcp_rn_f32_slowpath` (2), + `__cuda_sm20_sqrt_rn_f32_slowpath` (2) and `__cuda_sm20_div_rn_f64_full`. None is reached on this path, which + therefore needs no IEEE emulation. + +### The prompt path's batch kernels + +`native_ple_postops_batch` (`native_ple_postops.cu:382-397`, called at `src/prefill/prefill.cpp:1540`) runs the same +block over T prompt tokens at once: `rms_rep_kernel<<>>` three times (rows = T·H), the same +`gate_kernel<<>>`, `broadcast_batch_kernel` and `conv_residual_batch_kernel` over +`(T·D + 255) / 256` blocks of 256, and `history_batch_kernel<<>>`. The four batch kernels compile +to the same instructions in the same order in 13.0 and 13.3: + +| Kernel | SASS (13.0 = 13.3) | Against the decode kernel | +|---|---|---| +| `rms_rep_kernel` (`:97-121`) | `FFMA.FTZ R6, R11, R11, R6` in a loop over t, t + 1024, t + 2048 (not unrolled: one static copy); the two butterflies (`:94`), `@!P0 STS`, `BAR.SYNC.DEFER_BLOCKING 0x0`, `LDS R12, [R12]`; `HFMA2 R6, -RZ, RZ, 0.724609375, -19.203125`; `FFMA.FTZ R15, R15, R6, 9.9999999747524270788e-07`; `MUFU.RSQ R15, R15`; `FMUL.FTZ R8, R15, R8`; `FMUL.FTZ R9, R8, R9` | the same chain, butterflies and products; `gamma += size_t(blockIdx.x % H) * N`. N is a compile-time constant, so `partial / N` is `div.approx.ftz.f32` by `0f45200000` and `ptxas` evaluates its reciprocal at compile time: the `HFMA2` packs the halves 0x39CC and 0xCCCD, R6 = 0x39CCCCCD, the correctly rounded 1/2560. ε is an immediate | +| `gate_kernel` | the decode's function | rows = T·H blocks | +| `broadcast_batch_kernel` (`:122-127`) | `FMUL.FTZ R3, R6, R9` | `gated[i] = __fmul_rn(value[t * N + d % N], gate[t * H + d / N]);` | +| `conv_residual_batch_kernel` (`:129-145`) | 4 `HADD2.F32`; 4 `FMUL.FTZ` and 3 `FADD.FTZ` in k order; `FMUL.FTZ R0, R5, -1.4426950216293334961`; `MUFU.EX2`; `FADD.FTZ R4, R0, 1`; `MUFU.RCP R4, R4`; `FMUL.FTZ R5, R5, R4`; `FADD.FTZ R5, R5, R12` (+ `gated`); `FADD.FTZ R5, R14, R5` (`hidden` +) | the decode's sequence. Tap k reads token p = t − 9 + 3k: the chunk's normalized row p, or history row 9 + p when p < 0; no `conv` store; `hidden` updated in place | +| `history_batch_kernel` (`:147-158`) | no float instruction | row r becomes normalized row T − 9 + r, or history row T + r when T − 9 + r < 0 | + +So a prompt token gets the decode's arithmetic in every operation but one: the norm's reciprocal of 2560 is +`ptxas`'s folded 0x39CCCCCD in the batch and `MUFU.RCP` at run time in the decode. The exact 1/2560 lies 0.8 ulp above +0x39CCCCCC, so a reciprocal within the PTX ISA's 1-ulp bound returns 0x39CCCCCC or 0x39CCCCCD; basalt's two paths agree +bit for bit if the GPU returns ptxas's value ([H]: no Blackwell GPU here to check). The port's `rcp_ftz(2560.0f)` is +0x39CCCCCD on both paths, so its prompt and decode norms agree by construction, as invariant 1 requires. + +## 8. Metal + +The Metal kernels of this block are `kernels/common/basalt_gr_norm.metal` (the norm) and +`kernels/common/basalt_ple.metal` (the gate, the broadcast, the convolution and residual, and the history's advance, +snapshot and restore). Each source starts with `#pragma STDC FP_CONTRACT OFF` and +`kernels/common/basalt_fp.metal`, and writes every site in the form the tables above give it; a thread's index is +t = 32 · sg + lane, so its columns, its SIMD-group and its threadgroup slot are basalt's whatever order Metal gives the +SIMD-groups. + +- **The norm** (section 1): one threadgroup of 1024 threads per 2560-wide row, `threadgroup float sums[32]`, the + `fma_ftz` chain over columns t, t + 1024, t + 2048 from `0.0f`, `warp_sum_ftz` for both butterflies (the second in + every SIMD-group, over all 32 slots), `rsqrtf_ftz(fma_ftz(partial, rcp_ftz(float(n_cols)), eps))` and + `cuda_nan(mul_ftz(mul_ftz(scale, input[col]), gamma[col]))`. The threadgroup size fixes the reduction order, so the + pipeline must accept 1024 threads per threadgroup (`maxTotalThreadsPerThreadgroup`, checked when it is built). The + same kernel, with gamma row r mod 4, is the prompt path's `rms_rep_kernel` (section 7). +- **The gate** (section 2): one threadgroup of 512 threads (16 SIMD-groups) per stream, the source's two eight-slot + loops with `mul_ftz` and `add_ftz`, zero adds included, `warp_sum_ftz` twice with lanes 16 to 31 reading 0, and + thread 0's `fma_ftz(scale, sum, 0.0f)`, `sqrtf_ftz(max_ftz(abs_ftz(s), 1e-6f))`, + `float((s > 0.0f) - (s < 0.0f))` and `rcp_ftz(add_ftz(1.0f, expf_ftz(-mul_ftz(sign, mag))))`. The gate store needs + no `cuda_nan`. +- **The broadcast, the convolution and residual, the history advance** (sections 3 to 5): one thread per channel, + any grid that covers the 10240 channels (T · 10240 for the batch kernels); `cuda_nan` at the `gated`, `conv` and + `result` stores; the history advance copies bits. +- **Helpers.** The two square roots go through `rsqrtf_ftz` and `sqrtf_ftz` (`basalt_fp.metal`), which flush around + `metal::fast::rsqrt` and `metal::fast::sqrt` as `rsqrt.approx.ftz.f32` and `sqrt.approx.ftz.f32` do (invariant 5). + Their arguments are at least 1e-6 and their results normal, so on this path the flushes never change a value. Every + other site uses an existing helper. +- **Order and state.** The seven launches of section 7 run in that order, each behind a barrier on its predecessor + (the two first norms are independent of each other). No kernel takes a per-step value: the rows, the history and the + outputs are buffers, and n_cols, ε and the gate's scale are model constants (invariant 4). The history advance + writes the window's working history; the snapshot and the commit's restore (section 7) belong to the program. +- **Tests.** `ple_parity`'s block checks run the legacy chain of section 7, so no basalt test compares these kernels + bitwise with a reference, and the contract's rule for kernels without a gated reference test applies. The bitwise + oracle, R-emu, is `basalt_emu.gr_norm` and `basalt_emu.ple_gate`, `ple_broadcast` and `ple_conv` + (`tests/kernels/basalt_emu.py`), a numpy emulation of sections 1 to 4: it takes the values of `rsqrtf_ftz`, + `sqrtf_ftz` and `expf_ftz` from the GPU, as `basalt_emu.py` does for `expf_neg` (`:339-342`: "MUFU.EX2 and + fast::exp2 have no bit-exact host model"), and reproduces every other rounding, the flushes, the reduction orders and + `rcp_ftz` bit for bit. `test_grouped_norm_bitwise_emu` and `test_postops_bitwise_emu` + (`tests/kernels/test_basalt_ple.py`) compare the kernels with it bit for bit. diff --git a/kernels/common/basalt_fp.metal b/kernels/common/basalt_fp.metal index e9db9808..c8f828f7 100644 --- a/kernels/common/basalt_fp.metal +++ b/kernels/common/basalt_fp.metal @@ -1,7 +1,8 @@ // 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 +// src/kernels/cuda/q5k_head.cu, src/kernels/cuda/native_gr_norm.cu, src/kernels/cuda/native_ple_postops.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). @@ -40,6 +41,9 @@ // 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). +// - rsqrtf_ftz, sqrtf_ftz: rsqrtf(x) and sqrtf(x) in a --use_fast_math file, rsqrt.approx.ftz.f32 and +// sqrt.approx.ftz.f32 (MUFU.RSQ and MUFU.SQRT with .ftz): fast::rsqrt and fast::sqrt of the flushed input, the +// result flushed (docs/research/basalt-nvcc/ple.md sections 1-2). #pragma STDC FP_CONTRACT OFF static inline float ftz(float x) { @@ -253,3 +257,13 @@ static inline float q5k_dot(thread const Q5KW& r, device const uint* x, int iqs) } return fma_ftz(r.dmx, sumf_d, -mul_ftz(r.dmy, sumf_m)); } + +// The square roots of a --use_fast_math file (docs/research/basalt-nvcc/ple.md sections 1, 2 and 6): nvcc compiles +// rsqrtf (the grouped RMSNorm's scale, native_gr_norm.cu:72) to rsqrt.approx.ftz.f32, MUFU.RSQ alone, and sqrtf (the +// n-gram gate's magnitude, native_ple_postops.cu:63) to sqrt.approx.ftz.f32, MUFU.SQRT alone, not a reciprocal square +// root and a multiply. NVIDIA documents their error bounds, not their bits, so the contract (invariant 5) maps each +// to the metal::fast function of the same operation, whose last bits can differ from CUDA's; one helper serves each +// operation at every site. The flushes are .ftz's, on the input and on the result, for any operand; on the n-gram +// path the operands are at least 1e-6 and the results normal, so there they never change a value. +static inline float rsqrtf_ftz(float x) { return ftz(fast::rsqrt(ftz(x))); } +static inline float sqrtf_ftz(float x) { return ftz(fast::sqrt(ftz(x))); } diff --git a/kernels/common/basalt_gr_norm.metal b/kernels/common/basalt_gr_norm.metal new file mode 100644 index 00000000..74b7da6f --- /dev/null +++ b/kernels/common/basalt_gr_norm.metal @@ -0,0 +1,54 @@ +// Copyright (c) 2023-2026 The ggml authors (MIT) +// Copyright (c) 2026 Jesús Gulfo (MIT) +// Adapted from basalt (jesdga95/basalt) src/kernels/cuda/native_gr_norm.cu:37-100 +// @ b4c63b55754637f4c72ad53a0f791d425f71eb36 (MIT; third_party/NOTICE), which adapts ggml-org/llama.cpp +// ggml/src/ggml-cuda/{norm.cu,common.cuh} @ 3cf03257f219afbe7334045ff7c6a06ac68c627d (MIT; third_party/NOTICE). +// +// basalt's grouped RMSNorm, native_gr_rms_norm_weighted (weighted_rms_norm): row r of x (n_cols floats) +// becomes y[c] = (scale * x[c]) * gamma[c], scale = rsqrtf(sum of the row's squares / n_cols + eps), with row +// r % gamma_rows of gamma (gamma_rows = n_rows is basalt's gamma += row_offset; the n-gram block's three norms pass +// 4 rows of 2560 with 4 gamma rows). Needs basalt_fp.metal ahead of it. +// +// Thread t = 32 * sg + lane is basalt's threadIdx.x, so its columns and its slot do not depend on how Metal orders the +// SIMD-groups: it squares columns t, t + NORM_BLOCK, ... in order, fma(v, v, partial) from +0; each SIMD-group reduces +// with basalt's XOR butterfly; lane 0 of each stores its sum into slot sg; after the barrier every SIMD-group (not only +// the first) loads the slots (lane < NORM_BLOCK / 32; +0 above) and runs the butterfly again, so every thread holds +// the same sum and computes the scale itself: rsqrtf(fma(sum, 1 / n_cols, eps)), the division fused with the add as +// ptxas fuses it. Every float step is .FTZ (fma_ftz, add_ftz, mul_ftz, rcp_ftz for MUFU.RCP, rsqrtf_ftz for +// MUFU.RSQ); a NaN is stored as sm_120's (cuda_nan; docs/research/basalt-nvcc/nan.md). +// +// Macros: NORM_BLOCK threads per threadgroup, basalt's choice of 256 below 1024 columns and 1024 from there +// (native_gr_norm.cu:93-96; monolith/kernels.py's basalt_gr_norm_macros). The block size fixes the reduction order, +// so the pipeline must accept NORM_BLOCK threads. Grid: n_rows threadgroups of NORM_BLOCK threads. +// +// The rounding sequence nvcc compiles for this kernel: docs/research/basalt-nvcc/ple.md +#pragma STDC FP_CONTRACT OFF + +#ifndef NORM_BLOCK +#define NORM_BLOCK 1024 +#endif + +struct GrNormParams { uint n_cols; uint gamma_rows; uint eps_bits; uint pad; }; + +kernel void basalt_gr_norm(device const float* x [[buffer(0)]], device const float* gamma [[buffer(1)]], + device float* y [[buffer(2)]], constant GrNormParams& p [[buffer(3)]], + uint r [[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 + device const float* in = x + ulong(r) * p.n_cols; + device const float* g = gamma + ulong(r % p.gamma_rows) * p.n_cols; + device float* out = y + ulong(r) * p.n_cols; + float partial = 0.0f; + for (uint c = t; c < p.n_cols; c += NORM_BLOCK) { + const float v = in[c]; + partial = fma_ftz(v, v, partial); + } + threadgroup float sums[32]; + partial = warp_sum_ftz(partial); + if (lane == 0) sums[sg] = partial; + threadgroup_barrier(mem_flags::mem_threadgroup); + partial = lane < NORM_BLOCK / 32 ? sums[lane] : 0.0f; + partial = warp_sum_ftz(partial); + const float scale = rsqrtf_ftz(fma_ftz(partial, rcp_ftz(float(p.n_cols)), as_type(p.eps_bits))); + for (uint c = t; c < p.n_cols; c += NORM_BLOCK) out[c] = cuda_nan(mul_ftz(mul_ftz(scale, in[c]), g[c])); +} diff --git a/kernels/common/basalt_ple.metal b/kernels/common/basalt_ple.metal new file mode 100644 index 00000000..f4a25042 --- /dev/null +++ b/kernels/common/basalt_ple.metal @@ -0,0 +1,133 @@ +// Copyright (c) 2023-2026 The ggml authors (MIT) +// Copyright (c) 2026 Jesús Gulfo (MIT) +// Adapted from basalt (jesdga95/basalt) src/kernels/cuda/native_ple_postops.cu:37-89, src/kernels/cuda/ple.cu:46-52, +// src/kernels/cuda/elementwise.cu:222-227 and src/kernels/cuda/verify_kernels.cu:506-512 +// @ b4c63b55754637f4c72ad53a0f791d425f71eb36 (MIT; third_party/NOTICE); native_ple_postops.cu's arithmetic adapts +// ggml-org/llama.cpp ggml/src/ggml-cuda/{reduce_rows.cuh,sumrows.cu,unary.cu} @ +// 3cf03257f219afbe7334045ff7c6a06ac68c627d (MIT; third_party/NOTICE). +// +// basalt's n-gram (PLE) block after its projections, one token (native_ple_postops), between its grouped norms +// (basalt_gr_norm.metal): the gate, the broadcast and the causal convolution with its SiLU and residual; then the +// history's three moves in a verify window: the advance after each row, the snapshot after it and the commit's +// restore. The constants are basalt's (native_ple_postops.cu:36; include/basalt/kernels/ngram.hpp:30-41): N the stream +// width, H the hyper-connection streams, D = H * N their channels, HIST the history's rows, HS = HIST * D its words +// (src/core/verify.cpp:939), SNAP_SLOTS the snapshots, one per row of the largest window (kVerifyMaxT, +// include/basalt/kernels/verify_kernels.hpp:21). Needs basalt_fp.metal ahead of it. +// +// - basalt_ple_gate (gate_kernel): threadgroup b of 512 threads reduces stream b's N products of the normalized key +// and query. Thread t = 32 * sg + lane (basalt's threadIdx.x) adds product t + 512 j into partial j from +0, then the +// eight partials in order into a sum from +0 (the zero adds kept: +0 + -0 is +0); basalt's XOR butterfly per +// SIMD-group; lane 0 of each stores its sum into slot sg; after the barrier every SIMD-group runs the butterfly over +// the 16 slots, lanes 16 to 31 adding +0; thread 0 scales the sum (an fma with a +0 addend), clamps its magnitude at +// 1e-6f, takes its square root, signs it ((s > 0) - (s < 0): 0 for +-0 and a NaN) and stores the sigmoid +// 1 / (1 + expf(-y)), which is never NaN. The scale is the host's 1.0f / std::sqrt(float(N)) (params). +// - basalt_ple_broadcast (broadcast_kernel): channel i of stream i / N is value[i % N] times gate[i / N]. +// - basalt_ple_conv (conv_residual_kernel): channel c's taps are history rows 0, 3 and 6 (the history is +// channel-major, row r of channel c at c * HIST + r, row 8 the newest) and this token's normalized[c], each times its +// fp16 weight taps[c * 4 + k], summed in k order from the first term; then the SiLU sum / (1 + expf(-sum)), stored +// as conv, and result = hidden + (gated + activation). The history is only read; result may be bound onto hidden +// (each thread reads its hidden[c] before it stores result[c]). +// - basalt_ple_advance (history_advance_kernel; verify.cpp:1118): channel c's HIST words drop row 0 and take +// normalized[c] as row 8, in place, each row read before it is overwritten (no other thread touches the column, and +// normalized lies outside the history: the emitter refuses an alias, as ple_history_advance does, ple.cu:207-209). +// - basalt_ple_snapshot (copy_from_mapped_kernel; verify.cpp:1123): the history's HS words into one snapshot slot, +// bound at the slot (slot r after row r), as 16-byte words in basalt's grid-stride order. +// - basalt_ple_restore (copy_indexed_kernel; verify.cpp:2137): the history from snapshot slot index[1], the commit +// record's word 1 (n_keep - 1, basalt's commit_ + 1), which every thread reads at run time. A negative index copies +// nothing (basalt's); an index past the last slot restores the last one (the port's bound: basalt has none on the +// device, and its host refuses an n_keep outside 1 to the window's rows, verify.cpp:2732). +// The moves do no arithmetic (their files are IEEE-built, and no rounding rule applies to a move): every binding is +// words (uint, uint4), so every bit pattern, subnormals and NaN payloads included, moves unchanged. +// +// Every float step is .FTZ: mul_ftz and add_ftz for basalt's __fmul_rn and __fadd_rn (never fused), fma_ftz for the +// explicit __fmaf_rn, max_ftz and abs_ftz for fmaxf and fabsf, and for the fast-math library calls sqrtf_ftz +// (MUFU.SQRT), expf_ftz (MUFU.EX2 of the product with log2 e; expf_ftz(-x) has the bits of the SASS product with +// -log2 e) and rcp_ftz (MUFU.RCP; a / b is mul_ftz(a, rcp_ftz(b))). A NaN is stored as sm_120's (cuda_nan; +// docs/research/basalt-nvcc/nan.md) at the gated, conv and result stores. +// +// Grids: the gate H threadgroups of 512 threads (one per stream), the broadcast, the convolution and the advance +// D / 256 threadgroups of 256 threads, the snapshot and the restore 64 threadgroups of 256 threads in grid-stride +// loops of two and six passes (monolith/kernels.py's PLE_GRIDS). The gate's block size fixes its reduction order, so +// its pipeline must accept 512 threads. +// +// The rounding sequence nvcc compiles for these kernels: docs/research/basalt-nvcc/ple.md +#pragma STDC FP_CONTRACT OFF + +constant constexpr uint N = 2560u; +constant constexpr uint H = 4u; +constant constexpr uint D = N * H; +constant constexpr uint HIST = 9u; +constant constexpr uint HS = HIST * D; +constant constexpr uint SNAP_SLOTS = 8u; + +struct PleGateParams { uint scale_bits; uint pad[3]; }; + +kernel void basalt_ple_gate(device const float* key [[buffer(0)]], device const float* query [[buffer(1)]], + device float* gate [[buffer(2)]], constant PleGateParams& gp [[buffer(3)]], + uint b [[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 + float sums[8] = {0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f}; + for (uint j = 0; j < 8u; ++j) { + const uint d = t + j * 512u; + const float p = d < N ? mul_ftz(key[b * N + d], query[b * N + d]) : 0.0f; + sums[j] = add_ftz(sums[j], p); + } + float sum = 0.0f; + for (uint j = 0; j < 8u; ++j) sum = add_ftz(sum, sums[j]); + threadgroup float partials[16]; + sum = warp_sum_ftz(sum); + if (lane == 0) partials[sg] = sum; + threadgroup_barrier(mem_flags::mem_threadgroup); + sum = lane < 16 ? partials[lane] : 0.0f; + sum = warp_sum_ftz(sum); + if (t == 0) { + const float s = fma_ftz(as_type(gp.scale_bits), sum, 0.0f); // ggml SCALE's zero bias + const float mag = sqrtf_ftz(max_ftz(abs_ftz(s), 1e-6f)); + const float sign = float((s > 0.0f) - (s < 0.0f)); + gate[b] = rcp_ftz(add_ftz(1.0f, expf_ftz(-mul_ftz(sign, mag)))); + } +} + +kernel void basalt_ple_broadcast(device const float* value [[buffer(0)]], device const float* gate [[buffer(1)]], + device float* gated [[buffer(2)]], uint i [[thread_position_in_grid]]) { + if (i < D) gated[i] = cuda_nan(mul_ftz(value[i % N], gate[i / N])); +} + +kernel void basalt_ple_conv(device const float* history [[buffer(0)]], device const float* normalized [[buffer(1)]], + device const ushort* taps [[buffer(2)]], device const float* hidden [[buffer(3)]], + device const float* gated [[buffer(4)]], device float* conv [[buffer(5)]], + device float* result [[buffer(6)]], uint c [[thread_position_in_grid]]) { + if (c >= D) return; + float sum = 0.0f; + for (uint k = 0; k < 4u; ++k) { + const float x = k == 3u ? normalized[c] : history[c * HIST + 3u * k]; + const float term = mul_ftz(x, h2f(taps[c * 4u + k])); + sum = k == 0u ? term : add_ftz(sum, term); + } + const float act = mul_ftz(sum, rcp_ftz(add_ftz(1.0f, expf_ftz(-sum)))); + conv[c] = cuda_nan(act); + result[c] = cuda_nan(add_ftz(hidden[c], add_ftz(gated[c], act))); +} + +kernel void basalt_ple_advance(device uint* history [[buffer(0)]], device const uint* normalized [[buffer(1)]], + uint c [[thread_position_in_grid]]) { + if (c >= D) return; + device uint* column = history + c * HIST; + for (uint row = 0; row + 1u < HIST; ++row) column[row] = column[row + 1u]; + column[HIST - 1u] = normalized[c]; +} + +kernel void basalt_ple_snapshot(device uint4* dst [[buffer(0)]], device const uint4* src [[buffer(1)]], + uint i0 [[thread_position_in_grid]], uint n [[threads_per_grid]]) { + for (uint i = i0; i < HS / 4u; i += n) dst[i] = src[i]; +} + +kernel void basalt_ple_restore(device uint* dst [[buffer(0)]], device const uint* src [[buffer(1)]], + device const int* index [[buffer(2)]], uint i0 [[thread_position_in_grid]], + uint n [[threads_per_grid]]) { + int idx = index[1]; + if (idx < 0) return; + idx = min(idx, int(SNAP_SLOTS) - 1); + for (uint i = i0; i < HS; i += n) dst[i] = src[uint(idx) * HS + i]; +} diff --git a/monolith/compiler/emit_basalt.py b/monolith/compiler/emit_basalt.py index 1d325eb1..50a22826 100644 --- a/monolith/compiler/emit_basalt.py +++ b/monolith/compiler/emit_basalt.py @@ -1,13 +1,20 @@ """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). +emits one dispatch, except ``basalt_ple_block``, which emits basalt's per-row chain, 11 dispatches a row +(``monolith/ops/basalt_ple.py``), 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, src/kernels/cuda/iq_kernels.cu:2450-2455 and -# src/kernels/cuda/native_gr_postops.cu:75-82 @ b4c63b55754637f4c72ad53a0f791d425f71eb36 (MIT; third_party/NOTICE). +# src/kernels/cuda/native_gr_postops.cu:75-82; the n-gram block's launches, +# their order and its refusals from src/kernels/cuda/ple.cu:204-212 and :228-356, +# src/kernels/cuda/native_ple_postops.cu:317-361, src/kernels/cuda/native_gr_norm.cu:78-100, +# src/kernels/cuda/elementwise.cu:277-287, src/kernels/cuda/verify_kernels.cu:1086-1090 and +# src/core/verify.cpp:1105-1124 and :2137, and the key's arm from src/core/native_dense.cpp:95-102 and +# src/core/weights.cpp:129-148 @ b4c63b55754637f4c72ad53a0f791d425f71eb36 (MIT; third_party/NOTICE). from __future__ import annotations @@ -18,6 +25,7 @@ from ..core.dtypes import DType from ..core.ir import Op, Value from ..formats.gguf import GGML_TYPES, ggml_row_bytes +from ..packs.basalt import BasaltSource if TYPE_CHECKING: from .emit import _Ctx @@ -204,6 +212,142 @@ def _gr_post(ctx: _Ctx, op: Op) -> None: f"{op.kind}:{block_out.name}", writes=[3]) +def _ple_block(ctx: _Ctx, op: Op) -> None: + """The verify loop's per-row chain (verify.cpp:1105-1124) on rows 0 .. T - 1: ``ple_block``'s native branch + (ple.cu:298-326), then the history's advance and its snapshot into slot r. The quantizer, the key and the value + are main's kernels at one column, built and launched as ``_q8_1``, ``_mmvq`` and ``_mmvf`` launch them for a + one-column graph; every row reuses one set of scratch buffers, as basalt reuses its workspace (ple.cu:282-292), + and the barrier pass orders the reuse.""" + n, d, h, hist_rows, slots = kernels.PLE_N, kernels.PLE_D, kernels.PLE_H, kernels.PLE_HIST, kernels.PLE_SNAP_SLOTS + t = _columns(ctx, op) + if t > slots: + raise ValueError(f"{op.kind}: {t} rows; basalt's windows run 1 to {slots} rows (verify.cpp:685-688), one " + "snapshot slot each") + (rows, hidden, w_key, w_value, n_key, n_query, n_conv, taps, hist, snap), (result, normalized) = (op.inputs, + op.outputs) + # the key as type 42 only: basalt's other native key types (ple.cu:231-235) wait for a pack that needs them + for w, ty, shape, what in ((w_key, "q2_0", (d, n), "the key"), (w_value, "bf16", (n, n), "the value")): + _, n_out, n_in = _weight(ctx, op, w, (GGML_IDS[ty],)) + if (n_out, n_in) != shape: + raise ValueError(f"{op.kind}: {what} {w.name!r} is {ty} {[n_out, n_in]}, not {list(shape)}") + # the key's arm as basalt picks it from the dense.index of the file that holds it (keep_unquantized_ple_key, + # native_dense.cpp:95-102): no index fails the load (index_code_bits cannot open it, weights.cpp:129-132); a row + # of code_bits 0 serves the key from that unquantized row, an arm the port does not build; no row (-1) or a + # shape-only row keeps the gguf tensor + key = w_key.name.split("/", 1)[-1] + for pk in ctx.packs: + if not isinstance(pk, BasaltSource) or w_key.name not in pk.entries: + continue + if "dense.index" not in pk.file.sections: + raise ValueError(f"{op.kind}: {pk.path} holds {w_key.name!r} but no dense.index, so basalt cannot tell " + "which arm serves the key and refuses to load (index_code_bits cannot open the index)") + if any(r.name == key and r.code_bits == 0 for r in pk.file.dense_index().rows): + raise ValueError(f"{op.kind}: the dense.index holds {key!r} unquantized (code_bits 0), so basalt serves " + f"the key from that row, an arm this port does not build, not from {w_key.name!r}") + for v, shape, why in ((rows, (t, n), "the window's gathered rows"), (hidden, (t, d), "the window's hidden rows"), + (result, (t, d), "the block's output rows"), (normalized, (t, d), "the conv norm's rows")): + _expect(ctx, op, v, shape, DType.F32, why) + for v in (n_key, n_query, n_conv): + _expect(ctx, op, v, (d,), DType.F32, "a grouped norm's weights") + _expect(ctx, op, taps, (d, 4), DType.F16, "the convolution's four taps a channel, k + 4c") + if snap is hist: + raise ValueError(f"{op.kind}: {hist.name!r} is both the history and its snapshots") + for v, shape, what in ((hist, (d, hist_rows), "the history"), (snap, (slots, d, hist_rows), "the snapshots")): + if not v.is_state: + raise ValueError(f"{op.kind}: {v.name!r} ({what}) is not a state") + if v.name not in op.attrs.get("updates", ()): + raise ValueError(f"{op.kind}: {v.name!r} ({what}) is not in updates; the window writes it in place") + _expect(ctx, op, v, shape, DType.F32, what) + # each value bound once, at the slot whose kernel sets its alignment (postops.cu:337-343): the rows at the BF16 + # GEMV's float2 reads, the taps at halves, the history and its snapshots at the snapshot's 16-byte words + # (elementwise.cu:277-286); every row stride is a multiple of 16 bytes, so the rows keep it + at = {v.name: _bind(ctx, op, slot, v, align)[1:] for v, slot, align in ( + (rows, 0, 8), (w_key, 0, 4), (w_value, 1, 4), (n_key, 1, 4), (hidden, 0, 4), (n_query, 1, 4), + (normalized, 2, 4), (n_conv, 1, 4), (hist, 1, 16), (taps, 2, 2), (result, 6, 4), (snap, 0, 16))} + owner: Dict[str, str] = {} + for v in (rows, hidden, result, normalized, hist, snap): + buf = at[v.name][0] + if buf in owner: # basalt's two aliases do not arise: result is out of place, query == normalized ours + raise ValueError(f"{op.kind}: {v.name!r} and {owner[buf]!r} bind one buffer ({buf}); the rows, the " + "hidden rows, the outputs, the history and the snapshots are buffers of their own") + owner[buf] = v.name + mq, mf = kernels.basalt_mmvq_macros(GGML_IDS["q2_0"], n, 1), kernels.basalt_mmvf_macros(n, n, 1) + mn, ple = kernels.basalt_gr_norm_macros(n), kernels.basalt_ple_source() + k = {"q8_1": ctx.kernel("basalt_q8_1", kernels.basalt_q8_1_source(), Q8_1_KERNELS["native"], {}), + "key": ctx.kernel("basalt_mmvq", kernels.basalt_mmvq_source(), "basalt_mmvq", mq), + "value": ctx.kernel("basalt_mmvf", kernels.basalt_mmvf_source(), "basalt_mmvf", mf), + "norm": ctx.kernel("basalt_gr_norm", kernels.basalt_gr_norm_source(), "basalt_gr_norm", mn), + **{s: ctx.kernel("basalt_ple", ple, f"basalt_ple_{s}", {}) + for s in ("gate", "broadcast", "conv", "advance", "snapshot")}} + prm = {"q8_1": ctx.params("basalt_q8_1", kernels.basalt_q8_1_params(n)), + "key": ctx.params("basalt_mmvq", kernels.basalt_mmvq_params(n, d)), + "value": ctx.params("basalt_mmvf", kernels.basalt_mmvf_params(n, n, 1)), + "norm": ctx.params("basalt_gr_norm", kernels.basalt_gr_norm_params(n, h, kernels.PLE_RMS_EPS)), + "gate": ctx.params("basalt_ple_gate", kernels.basalt_ple_gate_params())} + grid = {"q8_1": kernels.basalt_q8_1_grid(n), "key": kernels.basalt_mmvq_grid(mq, d), + "value": kernels.basalt_mmvf_grid(mf, n), "norm": kernels.basalt_gr_norm_grid(h, mn), **kernels.PLE_GRIDS} + ws = {s: (ctx.scratch(f"ple.{s}", nbytes), 0) for s, nbytes in ( + ("q8_1", n // 32 * kernels.Q8_1_BLOCK_BYTES), ("key", 4 * d), ("key_norm", 4 * d), ("value", 4 * n), + ("gate", 4 * h), ("gated", 4 * d), ("conv", 4 * d))} + + def row(v: Value, r: int, nbytes: int) -> Tuple[str, int]: + buf, off = at[v.name] + return buf, off + r * nbytes + + for r in range(t): + x, hr, nr = row(rows, r, 4 * n), row(hidden, r, 4 * d), row(normalized, r, 4 * d) + chain = ( # (stage, kernel, slots 0, 1, ..., writes): ple.cu:298-326, verify.cpp:1118, :1123 + ("q8_1", "q8_1", [x, ws["q8_1"]], [1]), + ("key", "key", [at[w_key.name], ws["q8_1"], ws["key"]], [2]), + ("value", "value", [x, at[w_value.name], ws["value"]], [2]), + ("norm_key", "norm", [ws["key"], at[n_key.name], ws["key_norm"]], [2]), + ("norm_query", "norm", [hr, at[n_query.name], nr], [2]), + ("gate", "gate", [ws["key_norm"], nr, ws["gate"]], [2]), + ("broadcast", "broadcast", [ws["value"], ws["gate"], ws["gated"]], [2]), + ("norm_conv", "norm", [ws["gated"], at[n_conv.name], nr], [2]), + ("conv", "conv", [at[hist.name], nr, at[taps.name], hr, ws["gated"], ws["conv"], row(result, r, 4 * d)], + [5, 6]), + ("advance", "advance", [at[hist.name], nr], [0]), + ("snapshot", "snapshot", [row(snap, r, 4 * hist_rows * d), at[hist.name]], [0])) + for stage, kind, slot_bufs, writes in chain: + bindings = [(i, *b) for i, b in enumerate(slot_bufs)] + if kind in prm: + bindings.append((len(slot_bufs), prm[kind], 0)) + groups, threads = grid[kind] + ctx.add(k[kind], bindings, (groups, 1, 1), (threads, 1, 1), f"{op.kind}:{r}:{stage}", writes=writes) + + +def _ple_commit(ctx: _Ctx, op: Op) -> None: + """The commit's restore (verify.cpp:2137): basalt's ``copy_indexed`` of snapshot ``commit[1]`` (n_keep - 1) into + the history, one dispatch. The kernel reads the record's word at run time and nothing of the program's width, so + a commit program compiled at any width restores after every window.""" + d, hist_rows, slots = kernels.PLE_D, kernels.PLE_HIST, kernels.PLE_SNAP_SLOTS + _columns(ctx, op) + hist, snap, record = op.inputs + if snap is hist: + raise ValueError(f"{op.kind}: {hist.name!r} is both the history and its snapshots") + updates = op.attrs.get("updates", ()) + for v, shape, what, written in ((hist, (d, hist_rows), "the history", True), + (snap, (slots, d, hist_rows), "the snapshots", False)): + if not v.is_state: + raise ValueError(f"{op.kind}: {v.name!r} ({what}) is not a state") + if (v.name in updates) != written: + why = "not in updates; the commit restores it in place" if written else "in updates; it only reads them" + raise ValueError(f"{op.kind}: {v.name!r} ({what}) is {why}") + _expect(ctx, op, v, shape, DType.F32, what) + if not record.is_input or record.dtype != DType.I32 or math.prod(ctx.shape(record)) < 2: + raise ValueError(f"{op.kind}: {record.name!r} ({record.dtype} {list(ctx.shape(record))}) is not the commit " + "record, an i32 graph input of at least 2 words (word 1 is n_keep - 1)") + bindings = [_bind(ctx, op, 0, hist, 16), _bind(ctx, op, 1, snap, 16), _bind(ctx, op, 2, record, 4)] + if bindings[2][1] == ctx.program.step_state: + raise ValueError(f"{op.kind}: {record.name!r} names a StepState field; the commit record is a host-written " + "input buffer of its own, never StepState") + k = ctx.kernel("basalt_ple", kernels.basalt_ple_source(), "basalt_ple_restore", {}) + groups, threads = kernels.PLE_GRIDS["restore"] + ctx.add(k, bindings, (groups, 1, 1), (threads, 1, 1), f"{op.kind}:restore", writes=[0]) + + 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, - "basalt_gr_post": _gr_post} + "basalt_gr_post": _gr_post, "basalt_ple_block": _ple_block, + "basalt_ple_commit": _ple_commit} diff --git a/monolith/kernels.py b/monolith/kernels.py index 485745f8..2861b859 100644 --- a/monolith/kernels.py +++ b/monolith/kernels.py @@ -726,6 +726,84 @@ def basalt_gr_post_grid(n_embd: int, hc: int, t: int) -> Tuple[int, int]: return -(-t * hc * n_embd // 256), 256 +# ---- basalt's grouped RMSNorm (kernels/common/basalt_gr_norm.metal; docs/research/basalt-nvcc/ple.md) ---- +# The launch rules below are adapted from basalt (jesdga95/basalt) src/kernels/cuda/native_gr_norm.cu:85-100 @ +# b4c63b55754637f4c72ad53a0f791d425f71eb36 (MIT; third_party/NOTICE). + +def basalt_gr_norm_source() -> str: + """basalt's ``native_gr_rms_norm_weighted``, ``weighted_rms_norm<256>`` and ``<1024>`` (``basalt_gr_norm``).""" + return PRELUDE + template("basalt_fp.metal") + template("basalt_gr_norm.metal") + + +def basalt_gr_norm_macros(n_cols: int) -> Dict[str, str]: + """basalt's block choice (native_gr_norm.cu:93-96): 256 threads below 1024 columns, 1024 from there.""" + return {"NORM_BLOCK": "1024" if n_cols >= 1024 else "256"} + + +def basalt_gr_norm_params(n_cols: int, gamma_rows: int, eps: float) -> bytes: + """``GrNormParams``: n_cols, gamma_rows (row r is normalized with gamma row r % gamma_rows) and eps as float32 + bits. basalt's refusals (native_gr_norm.cu:87), eps taken as its float: n_cols outside its int's 1..INT_MAX (which + also keeps the column loop's counter from wrapping), or eps not finite or below 0; and a gamma_rows below 1.""" + import numpy as np + + with np.errstate(over="ignore"): + e = np.float32(eps) + if not 0 < n_cols < 2 ** 31 or gamma_rows <= 0 or not np.isfinite(e) or e < 0: + raise ValueError(f"basalt_gr_norm: require 1 <= n_cols <= INT_MAX, gamma_rows >= 1 and a finite eps >= 0 " + f"(n_cols {n_cols}, gamma_rows {gamma_rows}, eps {eps})") + return struct.pack("<4I", n_cols, gamma_rows, int(e.view(np.uint32)), 0) + + +def basalt_gr_norm_grid(n_rows: int, macros: Mapping[str, str]) -> Tuple[int, int]: + """(threadgroups, threads per threadgroup): one threadgroup of NORM_BLOCK threads per row; basalt refuses + n_rows below 1 (native_gr_norm.cu:87).""" + if n_rows <= 0: + raise ValueError(f"basalt_gr_norm: n_rows must be positive, got {n_rows}") + return n_rows, int(macros["NORM_BLOCK"]) + + +# ---- basalt's n-gram block (kernels/common/basalt_ple.metal; docs/research/basalt-nvcc/ple.md) ---- +# The launch rules and constants below are adapted from basalt (jesdga95/basalt) +# src/kernels/cuda/native_ple_postops.cu:36, :352-359, src/kernels/cuda/ple.cu:36, :210, +# src/kernels/cuda/elementwise.cu:277-287, src/kernels/cuda/verify_kernels.cu:1086-1090, +# include/basalt/kernels/ngram.hpp:30-41 and include/basalt/kernels/verify_kernels.hpp:21 @ +# b4c63b55754637f4c72ad53a0f791d425f71eb36 (MIT; third_party/NOTICE). + +PLE_N = 2560 # a hyper-connection stream's width (NG_N_EMBD) +PLE_H = 4 # the hyper-connection streams (NG_HC) +PLE_D = 10240 # their channels, PLE_H * PLE_N (NG_HC_DIM) +PLE_HIST = 9 # the history's rows (NG_HIST) +PLE_SNAP_SLOTS = 8 # the per-row snapshots: a verify window's most rows (kVerifyMaxT) +PLE_RMS_EPS = 1e-6 # the three grouped norms' eps (NG_RMS_EPS) + +PLE_GRIDS = { # entry (basalt_ple_) -> (threadgroups, threads), basalt's launches + "gate": (4, 512), # native_ple_postops.cu:355: gate_kernel<<>>, one block per stream + "broadcast": (40, 256), # native_ple_postops.cu:356: broadcast_kernel<<>> + "conv": (40, 256), # native_ple_postops.cu:359: conv_residual_kernel<<>> + "advance": (40, 256), # ple.cu:210: (NG_HC_DIM + THREADS - 1) / THREADS blocks of THREADS = 256 (:36) + "snapshot": (64, 256), # elementwise.cu:284-285: min(ceil(n4 / 256), 64) blocks of 256, n4 = 23,040 float4s + "restore": (64, 256), # verify_kernels.cu:1087-1088: min(ceil(n / 256), 64) blocks of 256, n = 92,160 +} + + +def basalt_ple_source() -> str: + """basalt's ``gate_kernel`` (``basalt_ple_gate``), ``broadcast_kernel`` (``basalt_ple_broadcast``), + ``conv_residual_kernel`` (``basalt_ple_conv``), ``history_advance_kernel`` (``basalt_ple_advance``), + ``copy_from_mapped_kernel`` as the history's snapshot (``basalt_ple_snapshot``) and ``copy_indexed_kernel`` as the + commit's restore (``basalt_ple_restore``).""" + return PRELUDE + template("basalt_fp.metal") + template("basalt_ple.metal") + + +def basalt_ple_gate_params() -> bytes: + """``PleGateParams``: the gate's scale as float32 bits, basalt's host constant ``1.0f / std::sqrt(float(N))`` + (native_ple_postops.cu:355; host code, which --use_fast_math leaves IEEE), 0x3CA1E89B.""" + import numpy as np + + bits = int((np.float32(1) / np.sqrt(np.float32(PLE_N))).view(np.uint32)) + assert bits == 0x3CA1E89B, hex(bits) + return struct.pack("<4I", bits, 0, 0, 0) + + # ---- the other decode kernels ------------------------------------------------------------------------------- MSL_TENSOR_OPS = 4 << 16 # the language version the tensor-ops kernels need (MSL 4.0: , MPP) diff --git a/monolith/ops/__init__.py b/monolith/ops/__init__.py index ea38d2f8..53730799 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, basalt, draft, embed, gdn, gemv, moe, norm, sample # noqa: F401 (registration) +from . import attention, basalt, basalt_ple, draft, embed, gdn, gemv, moe, norm, sample # noqa: F401 (registration) __all__ = ["OPS", "CostModel", "KernelBinding", "OpDef", "register_op"] diff --git a/monolith/ops/basalt_ple.py b/monolith/ops/basalt_ple.py new file mode 100644 index 00000000..d4bebf24 --- /dev/null +++ b/monolith/ops/basalt_ple.py @@ -0,0 +1,95 @@ +"""basalt's n-gram block on the decode path (docs/design/flash-next.md; docs/research/basalt-nvcc/ple.md): the pack's +per-row chain, basalt's verify loop for a window (``src/core/verify.cpp:1105-1124``) with ``ple_block``'s native branch +(``src/kernels/cuda/ple.cu:228-356``), and the commit's restore of the history (``verify.cpp:2137``). The emitter +(``compiler/emit_basalt.py``) composes main's ``native_quantize_q8_1``, ``basalt_mmvq`` and ``basalt_mmvf`` kernels, +built by their own builders at one column, with the grouped RMSNorm (``kernels/common/basalt_gr_norm.metal``) and the +block's kernels (``kernels/common/basalt_ple.metal``); every macro, grid, threadgroup and params record comes from +``monolith/kernels.py``'s builders, never from the profile's crew or core count. + +* ``basalt_ple_block``: inputs ``(rows [T, 2560] F32, hidden [T, 10240] F32, w_key, w_value, norm_key, norm_query, + norm_conv, conv1d, hist, snap)`` → outputs ``(result [T, 10240] F32, normalized [T, 10240] F32)``, attr + ``updates=[hist, snap]``. + - ``rows``: the window's gathered table rows, written by the host. ``hidden``: the hyper-connection rows + (``gr_write``'s, run for every row before this op), the query norm's input and the residual. + - ``w_key``: a weight as shipped, ggml type 42 (``q2_0``) ``[10240, 2560]``, the pack's + ``gguf/blk.1.ple_key.weight``. + ``w_value``: a constant BF16 ``[2560, 2560]``. ``norm_key``, ``norm_query``, ``norm_conv``: constants F32 + ``[10240]``. ``conv1d``: a constant F16 ``[10240, 4]``, channel c's tap k at ``k + 4c``. + - ``hist``: the session's history, a state F32 ``[10240, 9]``, channel c's nine rows at ``c * 9 + r``, oldest first. + ``snap``: the window's snapshots, a state F32 ``[8, 10240, 9]`` of that layout, slot r the history after row r; it + is the same size in every width's program and in the commit's, so the programs share it by name. + - ``result``: row t's block output, out of place: ``hidden`` plus the gated value plus the convolution. + ``normalized``: row t's conv-norm output, the row the history appends. +* Rows. The program for a T-row window runs rows 0 to T - 1 and no other, as basalt's capture loop does + (``verify.cpp:1105``), and each row is the one-row call: row r of a T-row window is exactly a one-row window's row + (invariant 1). Row r reads ``rows[r]``, ``hidden[r]`` and the history after row r - 1; it writes ``result[r]`` and + ``normalized[r]``, advances ``hist`` in place, then copies it into ``snap[r]``. A window never restores ``hist``: + only ``basalt_ple_commit`` does (invariant 3, flash-next.md). Eleven dispatches a row, named + ``basalt_ple_block::``, in this order: + + == ========== ======================== ==================================================================== + # stage kernel reads → writes (``ple.*`` the block's scratch, which every row reuses) + == ========== ======================== ==================================================================== + 1 q8_1 native_quantize_q8_1 ``rows[r]`` → ``ple.q8_1`` + 2 key basalt_mmvq (type 42) ``w_key``, ``ple.q8_1`` → ``ple.key`` + 3 value basalt_mmvf ``rows[r]``, ``w_value`` → ``ple.value`` + 4 norm_key basalt_gr_norm ``ple.key``, ``norm_key`` → ``ple.key_norm`` + 5 norm_query basalt_gr_norm ``hidden[r]``, ``norm_query`` → ``normalized[r]`` + 6 gate basalt_ple_gate ``ple.key_norm``, ``normalized[r]`` → ``ple.gate`` + 7 broadcast basalt_ple_broadcast ``ple.value``, ``ple.gate`` → ``ple.gated`` + 8 norm_conv basalt_gr_norm ``ple.gated``, ``norm_conv`` → ``normalized[r]`` + 9 conv basalt_ple_conv ``hist``, ``normalized[r]``, ``conv1d``, ``hidden[r]``, ``ple.gated`` + → ``ple.conv``, ``result[r]`` + 10 advance basalt_ple_advance ``hist``, ``normalized[r]`` → ``hist`` + 11 snapshot basalt_ple_snapshot ``hist`` → ``snap[r]`` + == ========== ======================== ==================================================================== + + Stages 4 to 8 are ``ple_block``'s own binding (``ple.cu:320-326``): the query norm writes ``normalized[r]`` and the + conv norm overwrites it once the gate has read it, basalt's permitted query == normalized alias + (``src/kernels/cuda/native_ple_postops.cu:344-351``). +* ``basalt_ple_commit``: inputs ``(hist, snap, commit)`` → one placeholder output ``[1] U32`` that binds no slot (as + ``lower_round``'s commit does), attr ``updates=[hist]``. ``commit`` is the window's commit record, the named I32 + graph input of 2 + 8 words in basalt's layout (word 0 n_keep, word 1 n_keep - 1, word 2 + t row t's position or -1), + host-written between the window and the commit program, never a params record. One dispatch, + ``basalt_ple_commit:restore`` (``basalt_ple_restore``), copies snapshot ``commit[1]`` into ``hist``, basalt's + ``copy_indexed`` (``verify.cpp:2137``; ``src/kernels/cuda/verify_kernels.cu:506-512``). Word 1 below 0 copies + nothing (basalt's), which leaves ``hist`` as the window left it, advanced by all T rows; word 1 above 7 restores + slot 7 (the GDN commit's ``min(n_keep, MT)``); no error code. Neither branch fires for an n_keep basalt's host + allows, and neither gives a meaningful state: the host refuses ``n_keep < 1 || n_keep > T`` (``verify.cpp:2732``), + and that refusal is the guard. The dispatch does not depend on the program's width, so one commit program compiled + at width 8 can hold it beside the other commits. It binds no StepState. + +Programs. basalt captures one graph per window width (T = 1 .. 8) and bakes T into every launch, so the block compiles +one static program per width; the programs share the weight windows, ``hist`` and ``snap`` by name. The per-step +values (the rows, the hidden rows, the commit record) live in buffers; the params records hold only shapes, the +norms' eps and the gate's scale (invariant 4). + +Refused with a reason, before anything is encoded: + +* ``basalt_ple_block``: a dynamic-T program; T above 8 (basalt's window limit, ``verify.cpp:685-688``, and the + snapshot slots); a key that is not an unpacked type-42 ``[10240, 2560]`` weight, a BF16 or dense-section key among + them (basalt's other native key types, ``ple.cu:231-235``, wait for a pack that needs them); a key whose ``.basalt`` + file has no ``dense.index`` (basalt cannot tell which arm serves it and refuses to load) or a ``dense.index`` row for + it that is unquantized (code_bits 0, which basalt serves from that row instead, an arm the port does not build; + ``src/core/native_dense.cpp:95-102``), where no row, or a shape-only one, keeps the gguf tensor; a value that is + not BF16 ``[2560, 2560]``; ``rows``, ``hidden``, ``result`` or ``normalized`` not of its shape above; a norm that + is not F32 ``[10240]``, or taps that are not F16 ``[10240, 4]``; ``hist`` or ``snap`` not a state of its shape or + missing from ``updates``, or ``snap`` the same value as ``hist``; a misaligned binding; two of ``rows``, + ``hidden``, ``result``, ``normalized``, ``hist`` and ``snap`` in one buffer (basalt's two permitted aliases do not + arise here: ``result`` is a value of its own, and query == normalized is the emitter's own binding). +* ``basalt_ple_commit``: a dynamic-T program; ``hist`` not a state F32 ``[10240, 9]`` in ``updates``; ``snap`` not a + state F32 ``[8, 10240, 9]``, or in ``updates``, or the same value as ``hist``; ``commit`` not an I32 graph input of + at least 2 words, or one named after a StepState field (which binds StepState); a misaligned binding. + +Alignment, checked at every binding: 8 bytes for ``rows`` (the BF16 GEMV reads it as float2), 2 for ``conv1d``, 16 +for ``hist`` and ``snap`` (the snapshot's float4 copy), 4 for every other binding (basalt's spans, +``native_ple_postops.cu:337-343``, ``src/kernels/cuda/elementwise.cu:277-286``). +""" + +from ..core.ir import OpClass +from .registry import KernelBinding, OpDef, register_op + +BASALT_PLE_BLOCK = register_op(OpDef("basalt_ple_block", OpClass.MAP, "rows") + .bind("*", KernelBinding("basalt_ple_block"))) +BASALT_PLE_COMMIT = register_op(OpDef("basalt_ple_commit", OpClass.MAP, "rows") + .bind("*", KernelBinding("basalt_ple_commit"))) diff --git a/tests/basalt_ple_ref.py b/tests/basalt_ple_ref.py new file mode 100644 index 00000000..2627af14 --- /dev/null +++ b/tests/basalt_ple_ref.py @@ -0,0 +1,417 @@ +# SPDX-License-Identifier: MIT +# Copyright (c) 2026 Jesús Gulfo +# adapted from basalt (jesdga95/basalt) src/kernels/ple_parity.cpp, src/kernels/ple_win_parity.cpp, src/core/verify.cpp +# @ b4c63b55754637f4c72ad53a0f791d425f71eb36 (MIT; third_party/NOTICE): ple_parity's metric helpers (le, gt, +# nonfinite and rel_l1, :41-77), the seven stages its block check compares (:751-759), its host grouped norm +# (:899-904) and its host f32 reference block with the history slide (:1046-1102, :1127-1131); ple_win_parity's +# fixture scales (:48-56); ple_parity's capture loader rules (:135-164: a file missing or of the wrong size fails); +# verify.cpp's commit record and its count refusal (:2732-2737). +"""The n-gram (PLE) block's host references, numpy only (no Metal import), imported as ``from tests.basalt_ple_ref +import ...``. + +- ``le``, ``gt``, ``nonfinite`` and ``rel_l1``: ple_parity's NaN-safe metric helpers (ple_parity.cpp:41-77). + ``rel_l1(a, b)`` takes the reference first and returns ``(rel, mag, nf)``: rel = sum |a - b| / sum |a| (the sum + floored at 1e-30) in float64, NaN when any pair has a non-finite entry; mag = mean |a| (the finite pairs' sum over + the length); nf = the count of non-finite pairs. +- R-struct (``r_struct``, spec T§6.2): the block in float64, from the graph comment (basalt + include/basalt/kernels/ple.hpp:3-13), not from basalt's host f32 reference. The Q2_0 key is decoded by + tests/contract/gguf_reference.py's ``q2_0``; BF16, F16 and F32 are widened, exactly. For every row it returns the + capture's seven slices (ple_parity.cpp:171-172: the normed key, value, gate, gated, normalized, conv_out and result), + the history after the row and the gate's argument s. The window is one pad, P = [history | normalized rows], read + at rows t, t + 3, t + 6 and t + 9 (ple.hpp's ``padded[hist + t - (kern - 1 - k) * dil]``), so the 12 rows run from + one initial history. ``r_contract`` (R-contract) is R-struct entered after the projections, fed a raw key and value. + ``STAGES`` names the seven slices. +- R-f32 (``r_f32``): basalt's own host f32 reference block (ple_parity.cpp:1046-1102), transcribed, every row in order + from ``fx.hist`` with its own slide between rows (:1127-1131). It shares only the weights with R-struct: it works on + basalt's flat buffers (the history row-fastest, row r of channel c at r + 9 c; conv1d at [k + 4 c]; the taps read + rows 0, 3 and 6 and the new normalized row), rounds to f32 wherever the C++ does (an x86-64 SSE2 build: no FMA, no + flush), adds each float64 sum in the C++ loop's order (a product of two f32 is exact) and takes std::exp's float + overload as exp in float64 rounded once to f32. It returns a ``Ref`` of float32 arrays, ``hist`` the slid history + after each row in R-struct's (row, channel) order. +- The host norm (``host_norm``): ple_parity.cpp:899-904, the grouped norm C8 holds the GPU's against, which is R-f32's + ``gnorm`` (:1046-1059) operation for operation: per stream, the f32 squares summed in float64 in column order, the + mean rounded to f32, scale = 1.0f / sqrtf(mean + 1e-6f), then (x * scale) * w, all in f32. +- H-ORACLE (``h_oracle``, spec T§7.1): the history a commit of ``n_keep`` rows of a window run from ``hist`` leaves, + the last nine rows of [hist rows 0..8 | the window's normalized rows 0..n_keep - 1], in basalt's layout (row r of + channel c at c * 9 + r). It only moves words, so it holds bit for bit on the GPU's own rows, NaN payloads included; + it refuses an ``n_keep`` outside 1..T (form (a)'s no-op leaves the history advanced by all T rows, not as it was). +- ``commit_record(n_keep, t, pos0)``: the commit record, the host-written int32 graph input of 2 + T_MAX words, for a + window of ``t`` rows at positions pos0, pos0 + 1, ..., as basalt's host writes it (verify.cpp:2735-2737): n_keep, + n_keep - 1 (the snapshot the n-gram commit restores), then pos0 + r for each row r < n_keep of the T_MAX and -1 for + the rest. It raises ValueError unless 1 <= n_keep <= t, basalt's refusal (verify.cpp:2732). +- The synthetic fixture (``synthetic``, spec T§6.3), ``Fixture``: the weights in the encodings the GPU reads (the key + as type-42 rows, the value as BF16 bits, the conv kernel as F16 in ggml's flat [k + 4 i]) and float32 activations; + the history is logical, row r oldest first (its row-fastest buffer layout, hist[r + 9 c], is the harness's). + Seeds: ``default_rng(SYNTHETIC_SEED)`` draws, in order, the key's codes (uniform bytes: four uniform 2-bit codes + each) and its d = f16(0.02 * U(0.5, 1.5)) per 64-weight block, w_nk, w_nq and w_nc = f32(1 + 0.1 * N(0,1)) (in that + order), conv1d = f16(0.3 * N(0,1)), emb = f32(0.2 * N(0,1)) (12 x 2560), the history f32(N(0,1)) (9 x 10240) and + hidden's unit draw z (12 x 10240); the value is bf16(0.05 * N(0,1)) from ``default_rng(VALUE_SEED)``, the + first (2560, 2560) draw, bit for bit test_ple_value_float64's weights (tests/kernels/test_basalt_mmvf.py). hidden = + f32(sigma_h * z), with sigma_h by T§6.3's rule 3: R-struct with the unit-scale hidden f32(z), then sigma_h = mean + |gated + conv_out| / mean |f32(z)|. ``SYNTHETIC_SEED`` = 54 is the first seed from 0 for which property 2 holds + (seeds 0-53 put some |s[c]| below 0.1). +- The real weights (spec T§5): ``TENSORS`` places blk.1's six PLE tensors in the pack (make_basalt_fixture.py's pinned + file; absolute offsets) and ``RANGES`` the two byte ranges that hold them, one per name space. ``committed()`` reads + ``FIXTURE``, the committed slices (key row 0, the first 1024 B of the five dense rows and of their GGUF twins, all of + the dense conv1d) with the writer's record of where each lies; ``full_ranges()`` reads the two full ranges from + $BASALT_PLE_FIXTURE (tests/contract/fixtures/make_basalt_ple_fixture.py --full DIR fetches them): unset, the caller + skips with a reason naming the variable; set, a file missing or of the wrong size fails (ple_parity's L1-L4, spec + T§1.1). ``real_tensors()`` cuts the full ranges at TENSORS' offsets. ``real`` is T§6.3's real fixture: the key as + the session binds it (gguf, type 42), the value, the three norms and conv1d from their dense rows, and + ``_with_activations(default_rng(REAL_SEED), 0.0158, ...)``: emb = f32(0.0158 * N(0,1)), the history f32(N(0,1)) and + hidden by rule 3. ``REAL_SEED`` = 279 is the first seed from 0 for which property 2 holds (seeds 0-278 put some + |s[c]| below 0.1). +- ``check_fixture``: the four properties every generator asserts on R-struct before it returns (T§6.3): + 1. hidden is nonzero (every row's every stream: with hidden = 0, s = 0 and gate = 0.5, the key is never observed); + 2. min over rows and streams of |s[c]| >= 0.1; + 3. the block's share of result, sum |gated + conv_out| / sum |result|, is at least 0.3 on every row; + 4. T = 12 rows from one initial history: each row's normalized row enters the history the next rows read.""" + +import functools +import json +import os +from pathlib import Path +from typing import NamedTuple + +import numpy as np + +from monolith.formats.safetensors_reader import read_header +from tests.contract.gguf_reference import q2_0 +from tests.kernels.basalt_emu import bf16_bits + +F32, F64 = np.float32, np.float64 +N, H = 2560, 4 # NG_N_EMBD, NG_HC (basalt include/basalt/kernels/ngram.hpp:30-41) +D = H * N # NG_HC_DIM: a [D] vector is stream-major, element (c, d) at c * N + d +KERN, DIL = 4, 3 # PLE_CONV_KERNEL, NGRAM_SIZE +HIST = (KERN - 1) * DIL # NG_HIST: 9 history rows, oldest first +ROWS = 12 # T§6.1: every block-level comparison runs 12 rows from one initial history +T_MAX = 8 # kVerifyMaxT (include/basalt/kernels/verify_kernels.hpp:21): a window's most rows +EPS = float(F32(1e-6)) # NG_RMS_EPS as float64(float32(1e-6)): the norms' eps and the gate's clamp +KEY_BLOCK = 18 # a type-42 (Q2_0) block: the f16 d, then 16 bytes of 2-bit codes, for 64 weights +SYNTHETIC_SEED = 54 # the first seed from 0 for which property 2 holds: min |s| 0.1251, min row share 0.628 +VALUE_SEED = 790 # test_ple_value_float64's +REAL_SEED = 279 # the first seed from 0 for which property 2 holds: min |s| 0.1219, min row share 0.562 + + +class PackTensor(NamedTuple): + type_id: int # ggml type + ne: tuple # ggml order, fastest first + nbytes: int + gguf: int # the GGUF tensor's absolute offset in the pack + kind: int # its dense.index row's kind: 5 F16, 2 F32, 4 BF16 as stored, 0 shape-only + dense: int | None # that row's absolute offset (dense base + src_off); None: shape-only, the bytes are in gguf + + +TENSORS = { # spec T§5's table in file order; the shapes are ngram.hpp:30-41's + "blk.1.ple_conv1d.weight": PackTensor(1, (KERN, D), 81920, 36325965824, 5, 90852224), + "blk.1.ple_key.weight": PackTensor(42, (N, D), 7372800, 36326047744, 0, None), + "blk.1.ple_norm_conv.weight": PackTensor(0, (D,), 40960, 36333420544, 2, 90934144), + "blk.1.ple_norm_key.weight": PackTensor(0, (D,), 40960, 36333461504, 2, 90975104), + "blk.1.ple_norm_query.weight": PackTensor(0, (D,), 40960, 36333502464, 2, 91016064), + "blk.1.ple_value.weight": PackTensor(30, (N, N), 13107200, 36333543424, 4, 91057024), +} +RANGES = { # T§5: each name space's tensors lie in one range, (file under $BASALT_PLE_FIXTURE, absolute offset, bytes) + "gguf": ("gguf_blk1_ple.bin", 36325965824, 20684800), + "dense": ("dense_blk1_ple.bin", 90852224, 13312000), +} +FIXTURE = Path(__file__).parent / "contract" / "fixtures" / "basalt_ple.safetensors" + + +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 nonfinite(a): + """ple_parity.cpp:52-57: how many entries of ``a`` are not finite.""" + return int(np.count_nonzero(~np.isfinite(a))) + + +def rel_l1(a, b): + """ple_parity.cpp:64-77, ``a`` the reference: (rel, mag, nf) as the module docstring says.""" + a, b = np.asarray(a, F64).ravel(), np.asarray(b, F64).ravel() + ok = np.isfinite(a) & np.isfinite(b) + nf = int(np.count_nonzero(~ok)) + m = np.abs(a[ok]).sum() + mag = m / (a.size or 1) + if nf: + return np.nan, mag, nf + return np.abs(a - b).sum() / (m if m > 1e-30 else 1e-30), mag, 0 + + +class Fixture(NamedTuple): + key: np.ndarray # uint8 (D, 720): W_key's type-42 rows, row o = W_key[o, :] in 40 blocks of 64 + value: np.ndarray # uint16 (N, N): W_value's BF16 bits, row-major + w_nk: np.ndarray # float32 (D,): the key norm's gamma + w_nq: np.ndarray # float32 (D,): the query norm's + w_nc: np.ndarray # float32 (D,): the conv input norm's + conv1d: np.ndarray # float16 (KERN * D,): ggml's flat [k + 4 i] + emb: np.ndarray # float32 (ROWS, N): the gathered n-gram rows + hist: np.ndarray # float32 (HIST, D): the initial history, row r oldest first + hidden: np.ndarray # float32 (ROWS, D): the residual stack + + +class Ref(NamedTuple): + key: np.ndarray # (T, D): gnorm(W_key @ emb, w_nk) + value: np.ndarray # (T, N): W_value @ emb + gate: np.ndarray # (T, H) + gated: np.ndarray # (T, D) + normalized: np.ndarray # (T, D): gnorm(gated, w_nc), the conv input + conv_out: np.ndarray # (T, D): SiLU(conv) + result: np.ndarray # (T, D): hidden + gated + conv_out + hist: np.ndarray # (T, HIST, D): the history after row t, P[t + 1 .. t + 9] + s: np.ndarray # (T, H): the gate's argument + + +STAGES = Ref._fields[:7] # the capture's seven slices, in its order (ple_parity.cpp:171-172) + + +@functools.lru_cache(maxsize=2) +def _key_weights(key): + """W_key (D, N) in float32 as gguf_reference.q2_0 decodes ``key``, the bytes of the type-42 rows. The decode is a + scalar loop of about 10 s, so it is cached per key, read-only.""" + w = q2_0(np.frombuffer(key, np.uint8).reshape(-1, KEY_BLOCK)).reshape(D, N) + w.flags.writeable = False + return w + + +def bf16_values(bits): + """BF16 bits widened to float32, exactly.""" + return (np.asarray(bits, np.uint16).astype(np.uint32) << 16).view(F32) + + +def gnorm(x, w): + """T§6.2's grouped norm over each of the H streams of N, in float64: + x[c, d] / sqrt(mean_d(x[c, :]^2) + eps) * w[c, d].""" + x = np.asarray(x, F64).reshape(-1, H, N) + y = x / np.sqrt(np.mean(x * x, axis=2, keepdims=True) + EPS) * np.asarray(w, F64).reshape(H, N) + return y.reshape(-1, D) + + +def sigmoid(x): + return 1 / (1 + np.exp(-x)) + + +def silu(x): + return x / (1 + np.exp(-x)) + + +def taps(conv1d): + """w_conv[i, k] = conv1d flat [k + 4 i] (ggml's ne = (kern, hc_dim)), float64.""" + return np.asarray(conv1d, F64).reshape(D, KERN) + + +def conv(P, w): + """conv[t, i] = sum_{k=0..3} w[i, k] * P[t + 3k, i] over the padded rows P = [history | normalized rows], tap 0 the + furthest back (ple.hpp's ``padded[hist + t - (kern - 1 - k) * dil]``).""" + t = len(P) - HIST + return sum(w[:, k] * P[DIL * k:DIL * k + t] for k in range(KERN)) + + +def r_contract(fx, key_raw, value): + """R-struct after the projections: ``key_raw`` (T, D) and ``value`` (T, N) are given (the GPU's, or R-struct's own), + every other input is ``fx``'s, and the T rows run from ``fx.hist``.""" + t = len(key_raw) + key = gnorm(key_raw, fx.w_nk) + query = gnorm(fx.hidden, fx.w_nq) + value = np.asarray(value, F64).reshape(t, N) + s = (key * query).reshape(t, H, N).sum(axis=2) / np.sqrt(N) + gate = sigmoid(np.sign(s) * np.sqrt(np.maximum(np.abs(s), EPS))) # sign(0) = 0 + gated = (value[:, None, :] * gate[:, :, None]).reshape(t, D) + normalized = gnorm(gated, fx.w_nc) + P = np.concatenate([np.asarray(fx.hist, F64), normalized]) + conv_out = silu(conv(P, taps(fx.conv1d))) + result = np.asarray(fx.hidden, F64) + gated + conv_out + hist = np.stack([P[r + 1:r + 1 + HIST] for r in range(t)]) + return Ref(key, value, gate, gated, normalized, conv_out, result, hist, s) + + +def r_struct(fx): + """T§6.2's R-struct of ``fx``, every row.""" + emb = np.asarray(fx.emb, F64) + key_raw = emb @ _key_weights(fx.key.tobytes()).astype(F64).T + value = emb @ bf16_values(fx.value).astype(F64).T + return r_contract(fx, key_raw, value) + + +def host_norm(x, w): + """ple_parity.cpp:899-904 (C8's host norm) and R-f32's ``gnorm`` (:1046-1059), one arithmetic: per stream of N, + the f32 squares widened and summed in float64 in column order, the mean rounded to f32, scale = 1.0f / + sqrtf(mean + 1e-6f), then (x * scale) * w, all in f32. ``x`` (..., D); float32, x's shape.""" + x = np.asarray(x, F32) + xs = x.reshape(-1, H, N) + total = np.cumsum((xs * xs).astype(F64), axis=2)[..., -1:] # `sum += double(v * v)`, in order + scale = F32(1) / np.sqrt((total / N).astype(F32) + F32(EPS)) + return (xs * scale * np.asarray(w, F32).reshape(H, N)).reshape(x.shape) + + +def _dot_in_order(w, x): + """a[t, o] = the C++ loop's ``a += (double) w[o * n + i] * (double) x[i]`` for i = 0..n-1 in order, float64 (rows + of x, rows of w). A product of two f32 is exact in float64, so the order of the adds is all there is to match.""" + wt = np.ascontiguousarray(np.asarray(w, F32).T) + x = np.asarray(x, F64) + a = np.zeros((len(x), wt.shape[1])) + for i, col in enumerate(wt): + a += np.multiply.outer(x[:, i], col) + return a + + +def _expf(x): + """std::exp's float overload as exp in float64 rounded once to f32, the correctly rounded value. glibc's expf, + basalt's on Linux, errs by at most 0.502 ulp (runtime/src/basalt_cpu_expf.cpp:106-107): one ulp apart at most.""" + return np.exp(np.asarray(x, F64)).astype(F32) + + +def r_f32(fx): + """R-f32, basalt's host f32 reference block (ple_parity.cpp:1046-1102), every row of ``fx`` in order with its + slide between rows (:1127-1131), on the module docstring's terms.""" + k_raw = _dot_in_order(_key_weights(fx.key.tobytes()), fx.emb).astype(F32) # :1066-1070, before the loop: + v_raw = _dot_in_order(bf16_values(fx.value).reshape(N, N), fx.emb).astype(F32) # :1073-1077, no history in them + hist = np.asarray(fx.hist, F32).T.flatten() # hist_ref = cap.hist: row r of channel c at r + 9 c + w_conv = np.asarray(fx.conv1d, F32) # cap.w_conv[k + 4 c] + i = np.arange(D) + rows = [] + for t in range(len(fx.emb)): + hid = np.asarray(fx.hidden[t], F32) + key = host_norm(k_raw[t], fx.w_nk) # :1071 + query = host_norm(hid, fx.w_nq) # :1072 + a = np.cumsum((key.astype(F64) * query.astype(F64)).reshape(H, N), axis=1)[:, -1] + s = a.astype(F32) / np.sqrt(F32(N)) # :1082 + mag = np.sqrt(np.fmax(np.abs(s), F32(1e-6))) + sgn = np.where(s > 0, F32(1), np.where(s < 0, F32(-1), F32(0))) + gate = F32(1) / (F32(1) + _expf(-(sgn * mag))) + gated = v_raw[t][i % N] * gate[i // N] # :1087-1088 + normalized = host_norm(gated, fx.w_nc) # :1089 + acc = np.zeros(D, F32) + for kk in range(KERN): # :1090-1101 + row = HIST - (KERN - 1 - kk) * DIL + vv = normalized if row == HIST else hist[row::HIST] # hist_ref[row + 9 c] + acc = acc + w_conv[kk::KERN] * vv # w_conv[kk + 4 c] + conv_out = acc / (F32(1) + _expf(-acc)) + result = hid + gated + conv_out # :1102 + h = hist.reshape(D, HIST) # :1127-1131, in place + h[:, :-1] = h[:, 1:] + h[:, -1] = normalized + rows.append((key, v_raw[t], gate, gated, normalized, conv_out, result, h.T.copy(), s)) + return Ref(*map(np.stack, zip(*rows))) + + +def h_oracle(hist, normalized, n_keep): + """H-ORACLE (spec T§7.1) on the module docstring's terms: ``hist`` (D, 9) or flat and the returned history in + basalt's layout, ``normalized`` (T, D), both float32 as the GPU stores them.""" + hist, normalized = np.asarray(hist, F32), np.asarray(normalized, F32) + if not 1 <= n_keep <= len(normalized): + raise ValueError(f"H-ORACLE keeps 1 to {len(normalized)} rows, not {n_keep}") + seq = np.concatenate([hist.reshape(D, HIST), normalized[:n_keep].T], axis=1) + return np.ascontiguousarray(seq[:, -HIST:]).reshape(hist.shape) + + +def commit_record(n_keep, t, pos0): + """The commit record of a window of ``t`` rows at positions pos0, pos0 + 1, ..., on the module docstring's + terms.""" + if n_keep < 1 or n_keep > t: # verify.cpp:2732 + raise ValueError(f"verify: commit count out of range: n_keep {n_keep} for a window of {t} rows") + return np.array([n_keep, n_keep - 1] + [pos0 + r if r < n_keep else -1 for r in range(T_MAX)], np.int32) + + +def check_fixture(fx, ref): + """T§6.3's four properties of a fixture, asserted on its R-struct ``ref``; returns min |s| and the smallest row + share, for the log.""" + chained = (fx.emb.shape == (ROWS, N) and fx.hidden.shape == (ROWS, D) and fx.hist.shape == (HIST, D) + and ref.hist.shape == (ROWS, HIST, D) and (ref.hist[0, :-1] == fx.hist[1:]).all() + and (ref.hist[:, -1] == ref.normalized).all() and (ref.hist[-1] == ref.normalized[ROWS - HIST:]).all()) + assert chained, ("T§6.3 property 4, \"T = 12 rows from one initial history\": the fixture has 12 rows and one " + "9-row history, and each row's normalized row enters the history the next rows read") + zero = int(np.count_nonzero(~(np.abs(fx.hidden.reshape(ROWS, H, N)).max(axis=2) > 0))) + assert zero == 0, (f"T§6.3 property 1, \"hidden is nonzero\": {zero} of {ROWS * H} row streams are zero (with " + "hidden = 0, query = 0, s = 0 and gate = 0.5 exactly, so the key is never observed)") + min_s = float(np.abs(ref.s).min()) + assert min_s >= 0.1, f"T§6.3 property 2, \"min over rows and streams of |s[c]| ≥ 0.1\": {min_s!r}" + share = np.abs(ref.gated + ref.conv_out).sum(axis=1) / np.abs(ref.result).sum(axis=1) + assert (share >= 0.3).all(), ("T§6.3 property 3, \"The block's share of result is at least 0.3. The share is " + f"Σ|gated + conv_out| / Σ|result| per row\": {np.round(share, 4).tolist()}") + return min_s, float(share.min()) + + +def _with_activations(rng, emb_scale, **weights): + """The fixture of ``weights`` with T§6.3's activations from ``rng``: emb = f32(emb_scale * N(0,1)), the history + f32(N(0,1)), hidden = f32(sigma_h * z) by rule 3; its four properties asserted.""" + emb = (emb_scale * rng.standard_normal((ROWS, N))).astype(F32) + hist = rng.standard_normal((HIST, D)).astype(F32) + z = rng.standard_normal((ROWS, D)) + fx = Fixture(emb=emb, hist=hist, hidden=z.astype(F32), **weights) + ref = r_struct(fx) + sigma = np.abs(ref.gated + ref.conv_out).mean() / np.abs(fx.hidden.astype(F64)).mean() + fx = fx._replace(hidden=(sigma * z).astype(F32)) + check_fixture(fx, r_struct(fx)) + return fx + + +def synthetic(seed=SYNTHETIC_SEED): + """T§6.3's synthetic fixture, drawn as the module docstring says.""" + rng = np.random.default_rng(seed) + blocks = N // 64 + codes = rng.integers(0, 256, (D, blocks, 16), dtype=np.uint8) + d = (0.02 * rng.uniform(0.5, 1.5, (D, blocks))).astype(np.float16) + key = np.concatenate([d.view(np.uint8).reshape(D, blocks, 2), codes], axis=2).reshape(D, blocks * KEY_BLOCK) + value = bf16_bits(np.random.default_rng(VALUE_SEED).standard_normal((N, N)).astype(F32) * F32(0.05)) + w_nk, w_nq, w_nc = ((1 + 0.1 * rng.standard_normal(D)).astype(F32) for _ in range(3)) + conv1d = (0.3 * rng.standard_normal(KERN * D)).astype(np.float16) + return _with_activations(rng, 0.2, key=key, value=value, w_nk=w_nk, w_nq=w_nq, w_nc=w_nc, conv1d=conv1d) + + +def committed(): + """``FIXTURE``'s committed slices, ``{key: bytes}``, and the writer's metadata (``entries``: each slice's tensor and + name space, where the pack's tables put it and how many of its bytes are kept).""" + infos, meta = read_header(FIXTURE) + data = FIXTURE.read_bytes() + return {k: data[i.start:i.end] for k, i in infos.items()}, json.loads(meta["fixture"]) + + +def full_ranges(): + """The two full ranges from $BASALT_PLE_FIXTURE, ``{name space: bytes}``. Unset, the caller skips with a reason that + names the variable; set, a file missing or of the wrong size fails.""" + import pytest # imported here: make_basalt_ple_fixture.py imports this module and needs no pytest + + root = os.environ.get("BASALT_PLE_FIXTURE") + if not root: + pytest.skip("set BASALT_PLE_FIXTURE to the directory `make_basalt_ple_fixture.py --full DIR` filled with the " + "n-gram block's two real-weight ranges") + out = {} + for space, (name, _, size) in RANGES.items(): + path = Path(root) / name + got = path.stat().st_size if path.is_file() else None + if got != size: + pytest.fail(f"$BASALT_PLE_FIXTURE/{name} is {'missing' if got is None else f'{got} bytes'}, not {size} " + "bytes: fetch it again with make_basalt_ple_fixture.py --full DIR") + out[space] = path.read_bytes() + return out + + +def real_tensors(): + """``TENSORS`` cut from the full ranges: ``{"gguf/": bytes}`` for all six, ``{"dense/": bytes}`` for + the five with a dense row.""" + ranges, out = full_ranges(), {} + for name, t in TENSORS.items(): + for space, at in (("gguf", t.gguf), ("dense", t.dense)): + if at is not None: + at -= RANGES[space][1] + out[f"{space}/{name}"] = ranges[space][at:at + t.nbytes] + return out + + +def real(seed=REAL_SEED): + """T§6.3's real fixture, as the module docstring says.""" + w = real_tensors() + + def dense(name, dtype): + return np.frombuffer(w[f"dense/blk.1.ple_{name}.weight"], dtype) + + key = np.frombuffer(w["gguf/blk.1.ple_key.weight"], np.uint8).reshape(D, -1) + return _with_activations(np.random.default_rng(seed), 0.0158, key=key, + value=dense("value", np.uint16).reshape(N, N), w_nk=dense("norm_key", F32), + w_nq=dense("norm_query", F32), w_nc=dense("norm_conv", F32), + conv1d=dense("conv1d", np.float16)) diff --git a/tests/contract/fixtures/basalt_ple.safetensors b/tests/contract/fixtures/basalt_ple.safetensors new file mode 100644 index 0000000000000000000000000000000000000000..ab7c38fc63baea6b8823b2f37936691a32fdc6d8 GIT binary patch literal 95344 zcmb@uU5w;dmLA5c>Z)R8MrPiKAR}&MR`1enStg*~75ksP@B?8B5+4>4Wy=6ztuUNb z_bf*{nxSWUS6oSJu)C_On3?f&BZ5Dd3`R8#uVBK~10ncEtA<3E<)c=L@P znBTnn&EJ&Y`tWV(Z@u}(N8kM9o8S1}x4!j*k3abV{IT@rSAX%l@Hbx@_q*Tw{@?v_ z@IPtjx1_h<{qd2%9QRH6?GN95_iz2Q(SP&f-}zGxemCr!@;e{CFaOlR|I^?4`1^m_ z;qL~1Q-1fu58wVt!~ga-zw=uk|0!SmZp=63_ocVqzZ>~Ce&e^k^>c6KPg(D~G2fIw zklvMk!pJ|vN`LT^;^WKlVAK!Z|4F0%SwrM**f(YQ1NqAk`PyQ9Irz`;-alnI?nZr6 z{!o^_jF6u+_Mas{?#6xdLrH$;%K-V>=zoUz_;ScMKYUAm@5}i3#y9@%$De%j%QO3p zyQBTBZ`+^z*7xrY_docxH@^R|^}Szv<5z@Vd*knX{DY5vn7{N_Kej*lrGNjMKltW%KKZpb-h@wm|Ks2O_7A@Oz3+bYowvXF{x?5(PyXm{ zzxDRF-ug&-`-6|({^*_eeqH|X{deDbOZwABt#5zl?rfBPHKFaP?FJn8P!-}v?4`Q+mt+e0NTmug%mQ}!tAW3^h<^muzIut@{Mdr2{EBe5<98$d;CsLI{lERg*Sh=m zSD*R>aO`{E|7y&if|5V{Ai(4|zWvdcBi;@7-7kmwn=tg<0{|@H&%Q#+yN|r{{yT5K z_u>2R$zMJD-^}hyocrB3g&&>D*P--}nafu&`L)S>`Td`BHoy7p?|wOz_x|LmK#;xn z_S-+hJifLi|KDN!qx%8K@$+uS*N3`GSwGy1ci;Yz8NB@-AjD7IkN2f_KllI=0W9CY z*^dw2`QU9?lD@VhUz^F-f$NXX=T8$~KY7F-nbwy}^urMQDe?8rJMX?Nz4x{Gyeob9 z{?}*o_4xY95C7wi%byrwKV`@t2HB5p(U+5XQ~3IM`B3`sop;~*87A|Sw&v^M@yAW& zPdfQu&gAO@{@fe${#)-!e>Bj3=8gIKv;Vls{A~O3VYL z`B5bM3ZL(O{_%AA&O7hD3yAhdx8|*P-jX0+{7H!R<8Sb1+L)g(+zEdSKW zeE6319`Ki+GLygcyKnsN?^frGH|)E;;W|NzZ69;;KApCd%*l;L3+hsLEZ#Qzdagy4 z#~gFq2fC*u4n=`AWkMBeIGeUfdhMLM#HOixsnV7FPgKIQjfi&xC~lP+ohb5=pJ()jn&BY`Wu(8sm5cJe{ROvZB5b( zCFy+oROhs$^adWC6;$+wnY?e$&4oKAxQ(1qJ^34-X-9G{PEb^Z^itw7lubH}aLG9r z^_4LZE~HUPa?*L0FNR7`EDD;PTYD+cVg+CO-muP`~yfDId@42C{6K8TH zti?TDuyIdaRC3xu+jKiR%a2-M&5K1kX2$7_|t8RLnO?a8x#;v9qr&6$Q>zkk`lN_B^N-i%Qs z`yJ6o*&{6+_-fbB^Qitj;{>idt@#e6i!@Pi#^;dtwo`%LXP1Hc1lAu|cq#L_i zbf`}?k4|iAU^S4YO_VK!2X>tL?bz~IY6b3v_Sksp?Bysurcre)cg)1_l%4*1i3MyP z#jsnJXT&FK_gT8NV|9|#hI1n(U}t18?4;XnR#Wxp+!P+ORE{Q9x5}7}nTvnI6!YeQ zIf=7h7KwE(p!&iN(z!wHM;da@Bp%O%k-O8!r6+sB*!E#AGm~T2XlfqZ9W#TSjmw?m zOWQu86O+p?)QH)T1@k;Vu;};i*$eTYhsH%dlPL}?zFs=MvXMRYLJRCgPTiH9R9w%c zla#V&=A@pLkuqiYep~nouDt$?3G8)G$h7%FSXW!L6GArVX7(se=%Z#&)-8t?a>)2n zm`*dCPUXPyaw;vgCqnGZ2TCXIREcY%28EBe*=t#pMJ-oNi~yZlW3+cY(>KO$tP^>Y zEpxB;TtA;sk5YA~Ojx2{IEluW4{0QLI%ei{+fB;oKl@aS2$yrcmvNG3oK(<%7f-uS~)o>Mh!9M47|epOrH-tq4Z)OiFY(k<7O7m1TV)6B@~L zb8LhKWoF_y#c3p8{PSo3&1V&<&V(r-*p56X0(?O!4oTFnTx#O<(%xn+`>SMCVgf@QT9(tk0^aUD|&ESjF;rh8kn+1KI zFaGepL`1CdO_UQQYBDZa{s8l@=P zvtwha)8Z(v%1EEFAp>z@BP~ox7Zhh5CF3G8!(r!8{IY}nl+Ostc*rJGx>sXV*e$}ir1S@lBA9gEoOK7vt7S^*WDY@LWLg~QF4bQw} z4!SR5>~#mmmpL*;uy18(tg>xQTUPYyi3sRhojN`|`>Y82C*`aPh6~HrD8|AGOPxdR z%QJ0^cd}2Yo#f}(Yhgd6)9hOC#aMbMQF;ovJvGMZYB;EY;whmU8w-=*b0HQ zsP^?x!F?nx(ZV=156eXx3BF59-o9v`XVf@PcU2@)bM~Cke?j!p%RF`hl?)+@RIetz zU+wLY_DVicA(q|P^?vn!ev@9Ogiwalf_{^8tv7@Q%_)iNBSB5^0Q_#x@U8;4=5CO6M1cpt*G!R?q+hFhx$Z&Mvv*Vn967f@VuCHYjY=afTVLH zMzF`mYPiVv?7rabFYK}6=96yQUh1L#Kt3=5ot1kzF1)|*C?hva!(x{qCzO{KDMxgt zM&_#Bh!e8SW-R_!_sD+mfs-84mFBZSLI1CN<{n|=FtGYr5lDeK?mdas1BtL9V2Gbj ziKpM1;|{l>acLyod3_w8R|$r(j6YT<93~1$_Qch0O#>jm(RB;9%lN5$+(d``*Zi?TgGpv z8ZqMXLgm%4UNB3C6nqx;INe%P%jUu^*cUou%4k`VPx)Gc}oO^?hcK`dQ7Il1kVFuR0+%{vA z9|C(a1o;y31LvIKP(Z?_+B(Z(gC{1DHl=R??ulz>ZFB#pBTblBI>wtmz;Ur$K4>qS zqzvq>y&`+zrdn6DiiDut$zgtd7o~vZzH+bI{f%c`;4ax~0rts6=1$}+U*TAyP0C~# z)g1OA7hSOnH7R4XW08D;5@sXbGNgz_PkngDjD%_Z!a*G}P~jElS!`f@F3lAmM>=3_ z8{x}t+{~o0Jk6%kb1i9+Gy{ecNSMLtXLXp*vyHlNj>?(C_3F(7+BFKjk{s-C*k6S1`l6v4V{!X22x*d^oeC3hD}br0(;hJ?kcPT6xV>08ZEM z>RX4y(|%ut$|GPiNgt340e1nu1rGWmkJzm~ves%)j-_+ws-^7~zi@eDqCR1X!S!E| zX$dh`MRugkyW2W;ZVj%RNnCQji-n~XIi3~fz*Cu{kfK*bn!iSt8c!f*@-Xwl!ZfDKZ344{oN$KY@ zZ&Qi<+5=~wM+W0;j7P3lE*RgqkdEElh}5;2bR%Jc=WJ9E#9P#i<%P4?T;;%UfTx#a zMd4Y4tHe2WP_cu!<-4$$(|vX-ZRDvN0cuXmy?!u|1iUmqRGcwk*TW$t^^E;2jZjo# z6liO8N_Xi@i{)G8fj}XjECiZSDd`XTMA&PP*PRJH??>If+KO8gqlr2raE^-&Ga4QZ zaXA*l((8|PKs@<|QYNYh@gc`-%SE{|JuN6##l#Gyn|dQ}1#0l}xF4r`h6qPU!;LyJvBXEY`^_DUk@p;m{B7itXFA8Nstpn`s`KCsM#hVyv&= z%*66Rjq5A-M2PDx;LZ!xW1zaVd_>&$7#IwnZq&k#- zaiT1$r4v@y@s+?O#cAoO=nG}d)Yn(0gBc|mATIC>H|a} zFZ#mK;vq(2eQ7R%QQhik!}nZ%)g|Uegp5WG?T(3s%Q|wy24&MSE)MD5Mt3Wq@XQ3g z68Lg0UAc$$68|F9a9NA}XOi1fvWQNv4-f+AqeS599gVs(4b%~gs;EMc380o!Cd0UzH8{KKuFOXk z#(UsLkHw>Vq3-Qad)h+XM|^zDXF7!}8C$sb32_cR=PU+bvrylMHDr{GW45VBe0cU1 zWUH8+n>!ZXOWrxSMmc5g&fwmTrM1PkYx__Va&AV>(OP7?dYi71rxE+2j4@Wvv$6wjNmJ<*eHq0H{)qq*u*Tx8eMZdeL45tx`X zX%^j;woC&CxN!zmYL1yiUu!eVXDGAGLd%m6=3d;9*|2Vda>@b@nw**d0)(2c_<7g? z2hXR%jlQjK>`^wJxn)Pt8LE+@QV{uBr!^>VCrwyJ9aNtBZC9iL7tE=$OZoMYzfPL9i&jcDYqoGml1 zV?6FIm<#LJ&GZ!^T4dliA6VGl7{GtT9qdy8-{aF`b6y|N9si#fxAesjh`i{R7oBI0 z?L`^LiTc18GrSmfk-ZiI_CRh}ispSnNz0Q!z3%2DE_vDe=rh8xkqZ3AOz<-ic#IoV zGcoB-;N)L8SL#e#$Xs(UFO^Hkj>)#9 z<&2I~j(yecDV%;WN*7Rlat&=<{Zx*I$OXQ{aCz{1pR%sKV>|(?95bztE^Q}l_A9HspR@c)wa7+%HfTs~N5ZqNs1WD|qeC(4aIt++gFlIn@L2hD}_Q$2F` zT?~5B18t{yJ+C8W)x^S8F%r&{y*8FXf9+#=pHcQ;^1_X9sdzYYX6BfQyU3hokL^Gs z!=izDpRhXCQ4tJLhqXmNZDV6vJ%_)K)Ym0YX{uLfie^rvB{nua;h=1#xp}Vo<)J+& zN9C2C4%hv-a|D3%dr*IvHBE8)nW)O(8r{O69eZD+8fQoxO4CHXO}nE<+6ek zgHZ}A4spIAz%E%&eo)QLSMrV-D?tWIS4Fak5D33#{a*f`m;Z&du#j@DC!#OxmDlt{ z=YhGei%9XILRwo#2D=M(+Z^6~&;pz9V);R_EMoRhK}D5E?ia@1o;7zGWaRGHTTJsS zodS+|E$@>5nZethcEH23U4dIFkF0}09jslJk&J7P#aWVtFhf{BjYCr%P=bBd2L^9` zk>e&XJPY2#Sqel>Bwq9^;zVdHaUEi}GFRhvoJLyM^Gf7w@_7dt&^XxC-c=Lnm_xoH z6XlSd&;|0DR|E;uj^sf*?yuF0Y^OfXBWvG3sr}B&Km#(Mf_I1$OP7w9p9~50D}we8 z)qsx(vA%u&tX(^-nOK+k%HF3`S>Qzl`bEuY!2E|-)^xxfJ0#sknCe{b>rexCGZuc; zJhXWWYPghDIdo9gbgc0>)<7St?<>hLb4Mr=jzWM=q~{9NIe7$ld-zo*_xf=bE$S{&>ZUf}tcDSf5tER$jS-di|HvV@9u?F%>PPyjI=aN>>#;&ULR2tX1WjH=sIfFlnGqArNg(p^uP49tSR=@ zW9pk;`#hx%aZ$IHW4wjj5cKhPoNSgt{b;U@hxN#zDPT>C%>(F+t`JqUCDK-!vI#@F zCkh1yF@_AaQoY>!Zym&y$sc^i(1rjfe~JA5iJ0J6J}F}H7xS?=FW_?u=ndp4o5)Y~ zkoEDNLUaii|?I63JlxslF+kDil}4r+b#%)ISJV(1de*Ha1lQwk@0Y-|y8YtQvakBo^ifx7zO z_zJ3G3CmCDL^||y>l`o07ES6G@(lE4&)qg0p=PA>bs*BpPe|C_FNb{prNpF#+SF`b70=c;D#6YR$eJbcq;U_EZ%g7r3C+1 z!i?*u5+|)ys!fIa)s#f(*7b&41x|a$s+b;}N7h*6hq&?RYtkuX4e*E{+i4eWA_RD+L~Z1r<45R;0k|mK7&9vzLVMQwPQ+a5^NPYg zEWCRIa1kA}PsuBjEY7eJnnWBMhis-r-7SV6;;Zu9<$AtP9P;MVB4k}UxbUil6BZ*2uHdcrU zI<=0l@2r{wGX^$3Yonf(o_G(G^Xig8Y?23ffyU0*+DPMSf6J(}Cj#JSwj!t?C7=4* z7=`KvM}R$E#k#vxLT}k`x9@dx$h09kziVL7BU!#@$YF*mV}N4_QvcI`rFY z=y)(u_o6&WIn4DpHnymKXxVaMpQ(xK8bt75m-g+Yyvh<#dx8@5JkVCx4QJENuZe!1 zMb@fE$}IK!$Hi2cIibGB6LjAClru)cRE|xkh;+9*;J}&YyK=AYx^s4yZ78Qu^RqT2 z8|q7_oN8ATG;LrqenUh~KDaK~q*#Q#?We_koV2tE%5}OQPE>4dFt9jn+;5o!T1v5v z9NNqf*OOx3%-TTrnP3<>XF2H7bmoq;3mKT2!J1JMF^Ep(u}N7rdxVJvpQ|6C#gLen zExfUksAm@Rz1gS;>vQ|m97{NxRf{fk&mAmm%>=5IE%RyRGoX*<1n_rNk2>FsM9M`hKdlcer4zP z)nCOjxZ_k`fqGPmm_-@4d=)CI{;YagLAS9;8epsy?}QE1d?u;EJy2ZQJ91RU3Y>A! z2XP;^REgy;4A76Y2_5Tu{78xHUFJDkm)DY%*#-T72f(>@X5jS z%n_bD2Mu~O-I!UKGdwl;D$tOQew$Gb4%b5Wl);2cxBAuy5yhugWN`)LyKatSlXoxZ zR7m>ADyY*bsHjX>KhbvXRE@GrbC>P9OVMki%o8UC@NWWrG<$zSadL z#S@n}p>r+8IaC8}Wboyzy{Px>xtx?2rUx7=XeZ>AaL}jZ1RsWV&*P^yC;niKSwE&L?Kp7m3|$Fxmtd^j$gsEURCmQhzsfH2Ux50Ox(B?~C|=cm zJ1-&=;XC~q*nED$cqDR93g~3WelgByvjpDw0CRNRhO*}@nuiAWKi#7j5+}b>VBd+a zB?jkW$V+?6hio^^kA~NhcAH0yr*ge(c+91_8m2->P|N)*rim<%fs+JLbivL*Puiqo zJ(8#S7IGQz{wy+Y`%S%ZykGxx@HE~^Qs}jcyqstwZDB-dqR!2jJ7bYD0v zCv?#Vxi5W2=N9z&|2Id4exi8WM#OJp!Ou6uS7UuGPh7tAr9hkZp22HtV~&8Kku{|a zZNut}g352j^;7gzz0{tP2{Sf{GH!Y8c32YXUTGHwbc3~9buO>FqcCYV!b;`~UprBK z8TxtU%33&{F+NJZ_a+A+rl*VkmH(k3cAd#olh zsO&5jXzb*>VyRx+W93Oc8fbN)BB)lj!UgDlvnEn0ovEMS@%r5V)zA8EIj)logT{Vc zFY{%8z~uhzBUgUPRH6q>nP&#HVu`Kte|4VY@($IcODJ(Q*;e_ zQl!V(Q@{-HA#|(+8ecJI7xGmJIsoAjXKt%o_5mL22|~t{UDLbH2xOD~Xi(UJE5Nl` ziPf-6^s#Z9PTH`2O{XbzJ+i3^8bGryr>rmY{jnY4oej9oKnGuW4199#-nXG15_#*T z9F!q?m@e4yU7aU!r4RcS*N+CSJ!S#JF%z;@;iUDC(gU8MTYUEaIKl<%86k;n&bX}j z4!R2Jg+i>Ta{-$}HtBD*RW`Lx$-I79U_`5Ji_q9i+-c)mH`$T~-hBi3K+mbubna}d zX?>zUbPoMQ+~_Vkm=kF)g<_0f_Jlsi zg`OA}eGJuXqQ@fmmbAoqJ)KLJeL{Kjr8wzAdE3n3$y6j1bV+fp`PIS(FMu>1_8Af) z^E3-H-i9oqtcx{tc9F7Gkr4>Ex|Kj5f!&YOt$3u6w{_@qKtzKEV;&_B>Ucz;4__U~ ztRu#(;K65bKwSN#_idN*0`w`(konx4sWbZ;y;cX>PEO=4#ZB0GBByzP;4#GQS-G`* ziqvJpn-hKCjJuf?>5J0KFBRYq4fqhGP@k$k<9D$_+J$>oB*y3V%yI8I+1?_k`h)RU2lh1ax& z8&@ZwojyzxvXDU;)_{$qv*JvQo7WHmmJ*7@^sSd#T#gX17%4#$b!#oM!*KI|FlmTs zwM=Igcq=rNPr4mBNT`~MJ_#y{aK3@_wzMbaLWqo+3Y~;D$hiEGJR^z7qfs6eeEmr0 z`q%0Z&L*dCv`FUYn9PQgYFwQe%OR1jtc@6mapyyKp0%z8O!xtCl=3hOLV_lsKH^Z^ zf)j@BO&($Mse8p-wxq%}@4iyzkbf8T7cNphSH}4f^LXB^Ysi7wxW{gydi18`Owgd& zg*omii>(XGlaA<08V!C5{Vn^n2~c7_mX<8Z!h-8oz|0b;jyQ*c=JvwgvBci196KeO znwIApPr=Ecdw36ZG`08r4A3<|vjH?XyiNoC7I9hxuDyl6x~mmjo}u}*HpOSKa_916 z=5=dqBxq%AMO+>Fz(FcUK;h5a4%`Hw>AM55UiEwRNx9N!KQ>W=3u?SxPn|=Rp!1Bg z!7&3F8=&rr zH_FmRRigUYvLO9|opQEoBRI?kdR_Zx9Zc{~zU=v4unE4!prUaAmb^`W5( z)KNX0Lz`1y0JE7^*TYuix~TkA^Ygj5W;o%(i1WR@QP5m(7{#sf!ct#WM_a5A%M<^XbSpQGwXa5x;qNB ztN=ZPW(+(c5wERd29es%bzrh?ByZU*nYn&C1GUAk4i1udz^TKqaG>6kHa%}XYM=B$ zj@yag_q4rM;FL>|IahCuk)0r~2IavF$$s!1md4$Z1#QNPoxL7t6h-p0cAENPoI@{1 zn-fe9E!6@xMj;Bc368tKm?+>LY_YPpJjj!w`=|pQE5Ejv^cwmhegz$oJaQ7_N&9&k z4cq#&EXF8VoZxOjpdVicF|ztXK7+ zrvg@wl~dLhGv%GMrPuj^tl6EmC;&gTwKEcqc0^_=^jES;`4Y!y+l<6p zbxW?@Gr}sf40L0((69BqIIAXvcYN{F-)Hb;vo?r@_0af2=d_3BwUsp6e3zX=bezkx z{IsEfoHJ!+9hzx-)d3HE^PU_!S4Bk6WzSv@UcI-euym4!7_9KH11#$TGJ;Aq8oY|9 zuR2mfeFNSl4yxoJi!y@15j4cbIp}PB0jo*3%njPWPClgx6m?je0iiFp5AAs z@}#5YQpCnt8kwZSj$iHm*{Awk_3A^ulpeNA!vlT=x|aj}6#>(^j^Ol-)2*DC;8NU4yR3OSi@}Jr+B2e#aR4z+5S#CR9Py$bmnyo^w`^ine2I((_Wp zf?hW8PI6a$w*(YZPh7a5(HaZzdG72Oyi`zik*FLi3j#WL1=>^z{&JbezDnw#48DKQ z8Pf+6bmmw<-{Cdqxxi>UXRXg0iucev@yzFHFz53a-%@*Us_f~sL6 zAbE?%_PG*kSULg*`_khSYQ!Syz_rHiUGNomOJl2sLd?b@)YF*9v<`=(FwUX>qrOC3 z#S5Gfi4$g1dlq%5w4L2!B7M?E;9ZMqjzVm+K66p7zsnR)Y{HJo-j155B5fd&%PsZA zr!Ht*I>~4j)ce%Ki|!!a>JM$m&oUOS>oraA$Uwqf-5d2M{TWG8KfAC$ceeO*eI-Mm zLU^9@4&OlMI0vL{;~^|i?z^w@$MPs2S6k?%xEl1`?QIq0o*Gd!OsTI>@di)ySs7z+ zU>j2je6|kP0xy)N+8CqUWjMoUF-^)*!{g;2JflR|i5!9`L&RKJF?2VkHqN)oL<2=4 z+ZhvqA12L#UAW5uV$gj)_-d#u3?xq)Ufri-eOJF`y=pEo{X3s3&@a{^90CsC&jQtl zT)j=6*)wBA_fTna^uUBDk&-sa5HL-@Ck1$riI3uXEL{V8ipmKSW}_B-XvzU}%_My& z-NKs1-ByZf@bL<#%-Drp$5ScNZ*4fg(&u=KJ+w11+Ovm&w4glTn9jOIx0e!~E1pzS zAt-_r`uha@v#f_+w%}VTUxJ@0Xpsgd-8%etpE;Dm{y84zMbPt$s0RlL#O#&G|MSlZ zj(FWfzAUDNC-K?^@{C*e3>0E;XH_25$kMu*4V;wm_ZK($nfF&C6Lo*Y~;0hG^W3E#Uc*D|iLm$WTBRHGB~iyWs%Lnr|0%B24fk z1-&EV2<`d$pajfIgX_Qt*^II$ax5n8u7OjNp1Ir3%VOa^nM*wWLWTaO9YUUky9{L9 zQDsKA6{mu)uegwQ^j15;(-w3DA#lB7r%i32UJnZv`uUix7wsbr>sR_!3hqjLUhG(? zkkCV$T3=){hbu9r`3_t&bH~qit;c}!W8w~jCLAL=V5q>8?qT!99HW0L-^(v0j@fIG z_bdxxPkeiecXgD_vV9Y%y9OLB8nF)O#sx>N7}em>|2~rfBT>9|((JMzpRkb{F|Qj7 zJU65C?nV%SJs6iX_oPsU-k}X~=*|uJ*>o%5am|^KSgVfjHtDVczlC;Qa+N!b$ZJMY zpW|C{2Iu%p^*a~VYp-zT31rD}dfKvSRBf_d0q3UU`mM3e5^bgIJ1(R0Od(>F(|(<8 zyIngXX9O7h0Qv~x%ZU-vB@S6nj^T3~HL@wWY7g4HfGR@+41{&RHUfEW@4HJa{2iwN z9he;#7wu>1UI!*A?i?-~151s%6XcbkS66#*JJ5EdKDH+I#-t2nxnd(;=Tz~{n+Cdn z^+dU^!~+i+%p{|YPqE-xTjb|)4gGADONl$PlLF_MS!m#M>@KNqf)mVzezusPP5#V| zq@%D0tOb80ey;NF>nd=(<}{s~$AUMT&l1N(@)$BaEqD1&hWeci@A{|Z0r}cB;%m0rm5@Q1MBgc(elbyv*h_=d3G1hO zbt}N#8Fo}nvWVFZfa4w1Lv*RbO&!+FH{c*S6ri&Hd!MPE87O#&4NtmAgDPkv8?>hk zw9vr=&hiAteXR$*rj1oBM%68e9a^2ZJO=ijuiBSz+k!LCnq?KL2QeaZ481yyD`tdt z3+=hd^${TbM%d{`^&-866*#tBF;@cXRnC=@A^3yO%rku_J}i7tb+`s_0~5;2PmH8T z#AD`cQ1ird5b)+ng(YTBu70OuRq5|A!A`Plx*uvR6#H&|Rpze5)pspMi6y@h~|1 z0psJ8A8@;o67ZAF3h)8t7tn?0SkO1}P@p(A33O;4OZ#SygEX}Kip}QPZ5qJ&2~2P+ z2ppm|-(HxwdPL`dvl9*Oc#v%szWJHE(T_<9Mk~$*+Unyfy(#K2hu?eJp{n% z_rk5T>9*#9nE+0))j@$fLCOdn{zt~#tG8mD-n8@FHxJDSvhWFah3=Y7^c#F5R)SN)|M*%M*e@iN6*Wy%6~5>HvLTnf+&r&Dz! z0m~>oHFT0+{?wcR+EXoJ_Wfh`3p#F2#H|nw(03FAGA6qenJbqsiQyw&cu{iwz68Ak zpI57V(gwv!SsAC|TA0d?JugV{`IfI~BO%JHNSM;tr+Dj$k<0KtE3g7pj>!z7p9>HkP(JS9`$!N7>1S z$%p_>km5v!dx=mHjBy~}>p1W!0V+wr??t%1gO}F2KFC{bmV(#p5ATatEJjfY&TR(z z28i@8j0p+~&ISeF+CfzT_dN#4dm3v!2fjoA1(22q3-n9}ZO-+@aphI9HA2vRs1Id8 z;XhclEjy(&k6B*j)Ypuoe5qY&V+QW_w4AcI!%6Vn6(#H7UUa1q^*WtF8`$VRxFCon1qZp`!ctv8KlYnx}fn3!`I%j<& zGT}yn1inLbJ4^rxf@#ei{MidGy8f6{q;bi_6_h6a7}BF2h%`d1#FG5-yn-;X%G2}SvXfF zhtF-U@}bUK>a&4pa2m`BA|(P9f;YF6mW0`9ewVPGpgskiw-4pgpMuu#)9B&E`!LzXY$6!4keh^I_EtVOPWm`1WYoYwo? z(>Y+T6VrpZ0+)plc9?zYuIr408F=-?y}KvBO;HnKsOs^Bs%E17Ozkid=Bm%9}II|Chh_< z8hDa{_eULc9k$J573yE-$X+#(dZRAcsTdLu zL&u8+{n(u5caEk<3T;*_bh_=4eIM}mF;qXmGpu=y1Yd*OZ_NapO;m?F$raS7rsrHJ z)QF0c_6)RpDz5vjhDof3?OeJdo-~tYWjJ`&xy0FH_s^SW)!u;42!g(rxKLt!Ah+nFDK+_Qh-UwwzlN^9&&VWQ z)se>2L$xzN^LF7$ebAjVfsV6?`Yke-1@tu?RA4x*aBfr3YILNY<6Y0&+w!E?48Y8t zz#7}seuBr^tfAUST-GCSCTxUt1~KGJ)VrQ&?4B8Lhnr5EojbQ?+0OFhjd%r`-^zsh z6e-p2RMYDe?t^F>d}G4B8h31Z1Eqkq0?ue1*e_MCgFCi#hAE--94}bT@duAUmpM=D zjf)tXg6~tHG!ROZSl_$I&|LH2+S zNxC6(0_fRnE9x$rNS=4#Hqk?6FT%Z`_9bXPd^)1>^H1Bbzp!HUroGij&o!<9&Jh}Z z|6bv>aerWOduwtua#0rdV_-ac8~*)*0iIec^qcbd#-}1^LXcN@_#J9^^Mt$4>``Lx zvvC3Z#(E_nai=9D$U@*)A$rQrhIw}oaJj4>L%i|slXNLjimgQldZKaO!Y%765aI6W zFdsZ)gRg5etaECPKXJ-f462*Kua4@1`VwV5XK6sTG=pI>tfVPQ+>nWS4kr*7z{uIG0^mTgOP6TgQ%l^z^SN0OY_sOc{;pT(}@z>6Vy}JeX0XUxU(TzGUn+`sG&c1LWHgWE{@V<}? zoHSE+S}e`vTkX%QX|a|$W{xSoF8zGhc+``?n*u)Jop@i^r*S#e3FtXV4)@fJ^9FoK zt|w1qzzI1`1L2*=ro;B1sI7s3odm?0<|V^m#L z-Kwf}&^lC=`taKt@3E~A2Xrw6T?|2SOi&UNlwb#4Og19h7h>ZJ5u30`oRFt{^A~?p z-AhaQ-uHc;=Y8H+hmRiSm>cx1^F{h#@XkZdCt)2H--hIPKpWLCr5%`j5a^2bp7{>&!bb-#9$R+v3RGxuG$%o-yA^f64!4 z@3a0MxlSnVJ+3@bpjW8CHOZwR1eU1IQ>yuIg#~{2=VLk zqs|)=L7w)AcN*W;eShVI*>V1@d}@W6$nMDlc%mrX%dee%wo)d^xPFXwA^L`4n2ryh z4;^)3Kh_`J4!c*NEBe68$hCV@)SzE`AC!|oiWUSOMi&Y#`>6~i-U=&l7e-(g(nm%7 z@mm$lnYnki66+}ZkPZ+LD>X15oKN|q30IAIszBdQ zUO8j^o)MG}WW;_8U+H7^q5c$}D)6N`pA?QI;iLJ{1=lJ@#^y_5KhUn^sOZB(wN1zIm>sg;Dm+0~DgBUO*N?-)*Nf>Ge?vZLBj~92 zz-ym_feg$GpWeOmAYs2ki)jJCfnOL7csR3uHJsJb4hn)AUaHo%*Uo-6^rr$?K=P zT9mr}NeR8xk=n=fqZ1)U#TxmfK|e450F4fey0|wM;oiaK4r5`D4-eXh_EzV9@!b5- z@Hx(5%)_O2s`L6jBo?}bsKq<~R@pzrkISnY^P{u|G8b{4x7L=uso(|3`~IU5$vb^4 zp?By5S}u_Ct-Lqky{(a{vsLyyi=-_J zeJ}W+t;kM_fDb437jn-(&G>fhj+%Y&DU~n}^Eo;7h&l@vVUNj;b`q(>U z-6#9(qk8QV^wU1nBW+T>1nyW<>?Ap0r#?fd57;#~jCF=X2gw zc1_~j!KicRpdv~>9f3{g>U;}HHp$w%a`)uyPdB+~Q5z=kZs~^}8 zUPs>nkG+;ZBPU`HQoePz%7ZS-_t}GnEmp2*jg&3>z`)0(eTq5dKJKUYEVf*cUh-(4 zBAYB&_*1pL&K^(^?8j!zLTB+G(w%uyjgpTzQ=fu?`%>A5ktJzx9u(h_rydwwOB&{$ z8|c6KBE()H<)b^QwhVmn)hH7);E}5D49%7I$n2|kWRlBB_lQYSI>Y2#d#W&TfWWK*ZJ__8a z)Aa_>Qz_697YinBw!o61IhRJ&waiNM_$cee8+A^46|eV0nhzL)c%_FM12bkd)%Vp> z7ixNd-c=9VsX3O%%{7@x#OyUMlX(IB7Y$vi4*Z*tZ)kjM51hcD>1mE_U$tB>t&T0a zR2syS!yTd8M{5xG45|;pQ8>zIehGFemed?1cXjV@UUfXq;A&dGV!40UcWKs(cyp9e zXipnWu;>2r&o7H{PBBFinLP6)vnkf`oh9c(c5zrUGga`HIdQ1GVb~hK=U}Tsyh*4z zRPH5SomWI2%53_j{!$~Bm{N1?JWcvj?WVj%7shp(Uo3;ELv$ zd=o9%{_k9}vycxqEuYeAZ!8%xr)eOEG4E36s#zM#;=J5NWA#*ilir%Q9=?BrdH-S( zQgq$>&}pc=(1yTOH1ArtWA%B_RW`vOI}0y^kvy(x87BMSw4vU6^3i&16#v14^T4CU zR^h#qk~&L&$ZiyB1@ewe5~?0KBab9B+7)0E?}Gw$NBeHxF|VCoNS#&7DkGo99Y4&6IsHrDe%}hl z+`i6E(t$B&G1=#g3z{q>(&9X6TbVVbivIHpiDL#i4FY9s3|bm5lTP@~pPRj6eK=AS z?bts0#S5FZ{D0x=gr)h3`|=?A^!pd`F*ZJ(ha;u;uP>TiyKzKw6wzp72aXuiP>^|6 zENJt-;DUZm4=;VOUE0)%e9WJcGj`aXVTC&z*5d+4u5YaGTGIf&NYt z1Ip}>e>t7T@S~R_ol3lSX9)6)SplPR1r3S*@WU6`Su=p2FHB|$Z@zVx`80dJyL0E- zVDA@*TLZnq5;I%PGvf;9hw7`OFLhPwFObzn7X6*)_N}>%XBshwiD*!!%P#G$GMBm~ z;xeL8Qg$8}(tr=f5zfE0aDrOI_vMY{pFXpv47!~$;>_x?FN$6`D>wRkpC{B@DcuP7 zB_!w$;y$KhpSQV+s$l^~r$_PkHq1tvMS=G6=Wh?^YL9E z(v5Rxkc=wW1XT;o)FU=0kENN^3s)`9Z5f0lJd$bpTe5te{c1pAZZ8&7Od_jmvL>P`P7;l13y(2dbg%du#ds`8HLB>OGkh6sQIh zSP|l*4Wk>Ds=z%B@_>e3fU?qN;49tq2)}>Ju9I~_Q;~U3glZZeGuK)#pzX^j$b*W? z!|cQ${tT?+UU^LZp&Tj#%bB#eR=MCNp+2XI5~=VxrF57?REJ-ydWyHOTDHTGjxXGv z+Bc@Uc;I5h5xiW)dl}5Ep4*8+Z5DBv@L&4gto=?7uTDKmBk}-t{Ri&Jf9DrHYibhp zr0Lu9h6G#oYwZ%`!4e)sZxmBkR8PtQ z^7+6g!8>`Xb4n=plNlpQy|zPUHnei`MWpyWqvwSsRo{8o+ThIC2h{VE^6cvi^+SLu zu}V<)YA-)80_!LoFmtn`?XX8`{7eQBl>rpNT0d4m3Oxp(Krz&UA7 z6e_VAhnz`mQO2C7O!Hn#oRLedRSW-)G|PzBDMt8rZrfgSQ_*Z#i7Mis6^iFYx1ED~ z_YRYc8cS7V`WF4$w=!vt+;jc!9T4Qqo#am)<*CB?dscL(@Ln$DNqbhUqAr8H$n=w2 zW*^R)l>yyQo(H0ijWj9sh(weZ32jf*ZG!W85TysFBU6S{VLevqVHMud=VYGTxOZ|7 z*V{8LOAhDYrTJ39^J6wjpT+%-kLy>~Tl=R0;-={!-<~)-BlM{|VDA3$h<(Ms*#8iThtPoPFkrK}QluFAyOuA(LN zgZuWp-hFwY%>U`d0h=b0b9tBw4&vV2X1Bp>d8XdRLd74byYTxOpU`I5^qRLV#oZKC z;?n9k-Rr0F*CDn$xFn$bGiksgZ-oPCqOM8`jv}O-M{{(|J=CK>eCadzY2ErH6j{n} zE^v-R6S4WEO3a%Yez|5<(dN47#mN8o^Ida8zK(C58>QdSXk@+xrl-m#VVjpF)ffJP z=@jP;ymIMFpE{vDuyJ3YE{X>}ow^TY_b|r&TiK#cO3Hk4KIl=P_*@oN$PXd1Ux@mi zi{_oRuin6;CL;G>)uR1S?36dwNjibjH^rHH>2da1He?6-T|`}MztFgFuG~nY5;&w4 z?1{e*rkNOt@+I)@%EUffkJ@*2XyEzjg99>ON!_kPoMATo)|atw2l(OQAXKQ2_0k(- zQ_~L)Y&Ep_oc`ly%}VB6%7SwqglPVo&&a)tc<@g0TWc%NfG)7-OG7;*B9VY|h92}4 zpT@ldHjARph{myeo4?UJX4m0s%A6#3>8PZw*t;~2WBQLSqRSqY2qI} z59a!-|LdaY6}0BCu@CW~V;gaU__mHcOhz*^QwWc1-ka$Ibz=nT%!H$#{9g7)VL!X` zItg`=uR;=^TT)D9QqxR?4#KlE;&c)Y0!m25NsE?}8)@Bi{ka4lj~Y+&eg^+`KF#_y z@U=?AokHTLdbHG`Py3WCnt|V|X|!x_*}i+mzF@;-+|b}vdPQ)5L@#;q}t~(Is%)k+F1v=P-S8R|)K_9VfRfv8nVB z4TDW|CSxWpeWA=U;U|6$yj~3Cy)9U@SVUv3ADn5E=vIDbQFhmoh=lXQAQ2b=^?Orc z$|*s;k9p)gYL7Jd9X$$EcfyWx3NGDw!iPmC9JCXMO5KQKo|RPYGLO=`^vv8Pp)|zv zAPKMX8O;Ru1WvhGKJwsSJkWeu@&W!l9a&;5gf!~@>f7JEaOU`y&+8YcuY5Ub1CNG_ z5J;q;(q6eP5HC6UHsK%yPEh)FkEMqo;?$uuRk{D2sqp=RjB3;V>P&U1;aIh-?e zKWibU*;ePxZAlw=K-r%5Wjk_2U9@R6R`ETM_dC8Aj0$SLEO`y*N;+0wL?Yq_ ze_)P`eIfX`PUWS)^X4k%n`Ok8hAD@<=i$B@eP(P<8|cpl&btk@Gs1Z=Ix%O9CN=ZmV zLpfj`g$$HgA_UmHYSQ{O+}z(~zSiFTXFfa7X5>Bys-ZbE@7ouL4Ld7uO`+x@>h%fc z#oW1xJ*!XkOj)L()Q`XQ1m#KJnp+58M zNCPj=c@_89!Y%|I`CH+1Afud4{4jJk)_HuA50Kf;C1R||IG~4j`K><2?{DND;gz}8 zFF1GX&<0bc`m1nySVFhocynjZtbfiF=e~q`irtqI+ysZdO0)OU1{HYLvNHI9L%qGV zNtOqybXC?yp7%ES%>j9r`Ot3bQ}gSb3yF_Bn_q-0c2c39L(t`=*}vsm+j2=}@z%t<7s2e@#1&acVh0LEn%hnd>&R9O$2U4ZPtjqq^MKJS)Cy!N0 z!=8c->N4^RBeI-N89o_2@nvAneu#Rb_I~4;vZ&6Z4I`+x;mq9U1pP7S5kGq_^WZCC zd>pN$uT+t&{CgF63H3;b=wW1hK}HAJJ9gGA@6Q~zy?f#lt-yrYAg0W~BJ8nG7cbmU z1%9jg-o8ejinlD%(G34^^p0e%woWhzLha~bEp zPbm}n-DFc!Y2z${wMLzRNgUqC=OkhnkhwNVH}$yq0jjH{cN;|}@vDk&>3@Gg#NzI7 z4t=_BfNzk6BRWDs5#4v$@IVue?AxJshCCu*MvykV!~H)@PE9_)a>2j7p2au7Mbe22 zMIAT}dmji<@%Q6RCK_jlPWD#e%sF$LE+fPtdEI=WNt$Ai!{C7YZLI#9QMr^J*mjur z*?EJGJA-ozt~W9!&?ENl`1dXh-~nx;arV@?b;h39PL)^nl_oaSz433ftv6Q|#j6`uEPM8M)t+`(ap4kjHNG=gcssfBW1IvlD;*cb7(wz18L(P(+J( zPq5pY@CLQJm;w>nsI=69v8!TR%m-*@lqAw$yvkQw;tk6wTuk0bh{ zx5c1@{$=*nl}pG>4%(i9dK2;roI?%uI_kI?MbirN+zdgU-aA9GHD@VTys}T4dHz1_ z7vS68Htwb4!yE4vrmTC&b0>dvk#gFUtPS+LiwyJ*S@773XJ*-g+1k*f*bNx3 zlu&zJ0BMIad1GLzw4%WmExhj}imu!j3GknOYaJ(jW@ZTm?+Y0<@9VMgMKX0BlePPW z7Ma&Em`Dp;8;$G``IBuPWx-LjzTAas4z*(ah&)W(Ubi#nI zc_JM;?#d5HpB*1)Jqbj1+x|de3m^cIDgRY+pprDwmg7$)Z#$|9z09dW-ow_#qMp){Wz4lm%flD+M6mc_mbdG zOOC}p?}XOxq=g5as2*uI?ApNRsDs18pUD%OcYEMfA)*%eFg`I(bmX<*Dhf>=@zswe zhx_(R6>d0tfI8m`M&V=i{bC_sf|sBkwI>Yn!Y`h?g8HI4H%2PwBM(E@T^gJ*mlx3@ znyA!#_oEk$pw6A4cV`U=O_$ZyB{}uCGWr?Tl!&=!mu;9r@7FLN*gM z`ol{P`6F;XAy%MJu+d(E+u_)Y2B$a z_vk&Nt#$hI%Lw@+rMjRXa!@b$114ZR`lHKy9Uqtxy3berT{$N&z?5P%uwSoC!i_pdw)aj5!dJwU_xo;5Sv)z0(>Ha z0+dtxnt3I^4d>1>+Gaxq^(VOZaX*_Asc+-o%U}8L{b4h+-s{*TQBh-)tc@{n!Y1Xb z1v{7D$$<^NroA(IHt<6RwSEM?d1n7l%Zr6rHco zVL-ecfqml*8ulg>4)5zJRKZ0Boe8-Z`~)~@js6rL(y9}Utd&LOt76E47b`1^bS}W> zMS0{3`V{X)S$glZdBwWxkTvH9V~NQiKQmcprEtKDc%PN=VAJyp9}W%RQq&K-ug}7+ zF=|G@IYUFVhtS)X`E|X_p|gbG=PnIKK^OJ)>wME*S;KY~PV|NHO8VuBcNl8~+;$Rk z$r3!_L-I-bWGi*YpG2q+F&B)DQ)6naYfQG6Z<7A%A{JWcDgNF-zfGH%*Z{3jWt^Q> zr_Pzi8=~5A=wU2zhfy)DcllCh3))PGSRVOr$cec(P=5pA*DuU&NsaD*x9w3-Ib{XroxGxk57lzrHJ&1eAEVNpE#Y7~d z<@HaWWyGEZ0m0ld>Pxp+>p?I>^&4pDleS^ZIl_}(D38ijNPq1u*uFq!?ya{h40_*LhMR87o-{A6rq~p?+esMGpL%;f9wJ<4t&yfSI~f?&Vy} z7w8`}q`>DGVf-pZ9h0CRxg@2(JYSK<+zQA5c8#;1(t@FS^ticCT zNR^v*<&H!8>x?eweem+0F-%7V`dRMfL8xfi^Ps0nGj@}ogvir>bx9^3r_6Bw9^)hC zO^zyS_p>S9im*{mpf8_5mFJpSvt;jd(WL$`zOgwQ=kBo8fWPE!d?#JHbLZ&4Vh%j; z%#aAWP{zeeu;)Q}?t(StK}?%>TF*rsxMIXbIR92(AF|i=dAKx17j?Ym%0bxAr)A#} zoEzv-Ty^9Q-D!4JL7!4-JNU=GAxblAshk*>!92&?kDN>7zaC4HJ83Rq7U)ke44Mc2 zN`K<{U3Dej`OxJJFcO27{4X)u$ebp8J1EyK)vgoZ=LB^_>cqg)bua9df;v;!|AlcD z(VKz~MFoACLX@z}2)N)y!lhdU_2qY-H+^-ko+$6D9?thp?Wap;hCLVq8{f;u2I_{> zW-+hfJODq94AfioQ%+doj@t7K)zl;{O~d`$0(GJ6>mB1NrAjBq97GBp2c8f%wB+4zhj<{;Ev;o--|O)T4Y*pSwM)*NoViF6F5E>^D$pfXp&#+~vLoUL=Q1M|#pX zclI(ERa2b#lM=Wk-#C-c7ZME_meen8YAvHM+9)%`nEUddDf%GdJd34>f#lLCG=UT09s1gbmP>JwF815h7#mkK1j+ zwbS%gT1UtBtQPD$b^%;0$lRY?f}e^(#GaO4NrRjy`1|Gd@Ips@XxMn|;{LRosP}V5 zI=9vlJl59v7npl0C7e&*r9hvXc~)#$hA6AN*P zK3&h?l(~xOdTnpx^I7;v2qiuJimbAE{lZy1=~`YlXNzG2y_|W_`0|Z2%DEcn#ohvq za;S@Zyt07zfI0>ycoojdskSS=F~NHyF`(f-hI78A|La90cpUK4z}xv;GSvfR?SOw3 zqzNP9Oj+!?BIutayMM)GxZlmd?`W?Q^abKIb3(wM)R6<-xZFdhl;p3%<8m4Ik)MVN z7hHLBG6@z5`r2v;<>3|L82hoTtEc>qyor9YB*^1>1YKrqy!Qz~U!fj*eG_#fz~20n z{`|#%dJ#*|rMUlrDe%3_2f0@P533#HRtIl(cSR?|o=z!b$--|@58`11JYjShI1^cX zPJEqn(cC98-ms$0vUluIe}(hgjc)XwJvYA1PNPNk`_XN=%Tec}mDh`|$=nl5^nd&( zUekle@GKcH%Ww=Fv4c*8dh{EY=4~)4z_aabxX*stZcX6nmKsC9C*kh_Esu){@b@!s zp|R04eTamX$P_4e8+XAQ1@ku9r1Txr-m$Md=oH$5=>ji^23PSGRTs`K5M#eEOyfR#KF8%Gxdhfb8l_Uy^Z-y8~IaHj8C); zes5%SRrD=QvFR(|D{`N`I`9g0un~tL4E^bgoT%WbW-lgs2R|43F5LK3-m*Bs33Tf4 zCBeBd`c6OTMO5u(3wIMvah^}Ue1<&0*O;c(XVJ@ibM7Nvw#yUftINXwf1V5PvUv_$@;(nONIoH0)#B8SxE%Zw*?7eWO z?8qL~zWjR@kHaG_v~%QH(%7uo2^zo4TJWuE1{!X>E7!Ewc9 z;OS&tU=x;t{F!qS`Z@lv?Z=`5AB}o%qHf68qo5I!DghgsB6K2N8~C9&XWlVju>QQ} z7|s$=zlHtV`lvpamN67e7j-A;20V03R^^HTc*?yQ__q~hBoF%l@%z2JNZzHTNa@QD1~^3;A) zhteAV_RI*y7xH`iJVch3ZkU<93j1-#pTlYYtr9_DTgB_T@6Z2Z#vZ1~%TDhXZ{2YV z-LvV%cn<#39jKyA_4h7+0PeCea~e$u^#_?)jKMEo>fLG`K&N6zh5DGCIL8*^)FdS) zh`sOScq>Q3=hR+QS3csOY>Fd8$Z6UM-W9-;{>I?FcLn?=CFjBargBNo9E8+*4_zC6 zK=ZyL^(1&h#_m93fOoFjuJu&^@0z<%bf(NG7}|nt7p7Yy7Jt=)`l7f zKGwsz-H~~Nt#Foaz|D^V59d9{zR z$;8|U&6+4t=(kh5*RiTfHgm&X2AULdYsm8<4jnOV?xJn%WFfhU@Py4F{T zg3qZphZA|^f2nj5^2BrY&)XggoL>YD-mDzY{g+BN6HM@8^4gO0X~mV~slVUs(xp2| z(f`d~X`_nf#O}HsooY+zrXuM)zKw?!;?xY3g)~lR{XW?NY0&h(9%T{pgA{vlGU&Wo zZ}Ikke5a9`Ggjf;xY0Rhi|guFlD}nR)J4HSoQ3H6m%HX{`;56Z!Ru3~l!x%3)VNOO zwuU|$?=u1T_E>#1g=AX4hF|)1_VwY8C4T~4mW1{?!F2?owmPuj-N*LW5_}r+Wv>zn zYH`KF!}a~^3oA7C`kY<-Z@#rYoc}9E3k=}!f=e++g?^Xl?GF?0jXkPKh`Q{E(x@2w z$otGz1s~UgVjFX)k3$J+4ZhcgCCZw4>Z9!oUZG5{=p~!>{6HLRf+6#IX)bCWeO;)M zDf;+DSZ|fL!92VVPduE91hbd+xH@y8FS*FeN$)UpPjVW)HQraZ_P@}2&`~EXbQmQ# zK(B)D@JQnt==^_uQE(;vr}oemP54f7f*u|E#&4fRSEx&vQ&sW34FUz>G?CS-cK`80 zJFhX{rH>f&Bg>n5sn4^Mh|NbO&WX&aeP!nE@|DrA&J-RlVDzW8!QmtVzB9mDz#P!O zP`1XZJ#Sx0V%?Kx9@sM!H(EaWU+5#ufh}0P*E&N#HsTV_q;Q|@WwwI;AuqC58vXOP z(QUD?&OH7=)Dik^9NYP2#;3tG?j!2O;W{85@*1)&FOO~dv$uyUl_XTTXD7}Wcy1Rx zN)PTgzwp!5;)O?n-TT29zyF|}ny1BA{E`XhGwXN-b7ug@*?4RrB974{(doq*;KF){Y?%q0vDEJ%YD3ylu^ z`8q=fKnIU>uqie8+8anBGiGMiq}gexQ^80YGGmw4+i1Z6S31iuj839y(8+}O7W{Ih zVRJ%7dv6o$KsTo*u|rqHxqpb(3h|~EOSlI4(+CapHPaajz8In&`oNhL>I$M=3cw#U z(ylY$bL+Gn{n#(QWRG>=n(F)jRWP5FlpWQ0{|0cQR7&|<BFsQ@c8cHtmzxfd=WR%LtJ;XUVz*i1tjksW+ zw<`rWJ2=WoK0*E7n}c#6PqRDarnvOx(MM&g^5OTYeug&zB$Romhy{OQK z^H6t8Y*?y)(5!|`PBi3Q4-+&8nh4&pbz;o4jkh@<9%HV+KL2n^r2N#C(rG!kdJ9B9 zbJoTv!}sHJ%r4I+cD0t zr42r-l4`8`Lc4*EbDMRoZgp;p&Kfg1@Cn0pCYiu5>?A?F7JPQXPE?90-Xs(C>@W!7 zH}dB?e1|E{t>inbKZ35bQx{1;Klg9TI|coQc#J(E3k`2rwl+YlwAvbCI5OeiQpPN? zX2!ire3E=&4^6yDwWf{~?t)1+l}{YZ;y33~7{VW%(ULWY$K$?j+x{U8fk&%55B}I_ z8IG6<_y%;G>KXK95(bKYIG6S~KgZ#@)OAKraVXswYqP7(^LzclexJ+jhTXOJd;YMw zKKF6`8~4V7A3Pp}@SW7iH&0uqq(6uR1(U%x<`&Qu>PfUX(z(w}Nwa>rAz@6@uJ+jW z+0TFX!q|ip;Knr*I176o0?j#t5;{zFTMz|$EZeuh7u7w!uc*`Hlld{eQNJwv$bt{% z8GBcN0b8`;OZZ8EKe+V0%sJ2xa}q&s369v6@}8XqclxS??s`~j=>Nmti?^qTp`y5B zc1#39)u=p3{$TUh?bw zd3c`fP0pQ2c;7NRO19A7H(8iL&nAngW9*t4GpzB3XKmiDq=oX#r}=G)3=sjJ>UfV4 zo(JbFwBSJV8})rS%%LMHCyb<=HN3%PuWG9G|LTR0yj9<(oXpjDUL_~pLRa1yc=uOJ zn-wxNcu=z_NJ0wAih1ZSQ|v}4CoK3s3!b9f1wU|>*`k1+YFtS--rAp=8`2AbALWU* z)JMVhNZ$w~@E@Biux|!q12 zuly7^TMi}Bpj8i12K-k**H3WHJ>o7}QcR^MS2><@vpI}e)RpL1?`HkrCo1PInk9JD zqJHO|)@RbAjmyhMEB{$x0BIo>Uf3^6yl z?o}X!XX0~zPmoswJY5C&s(8lk52(is$u|XO(D1RqPO0!qtH*An=ZN=V`s!CMtT)yZ z>*v%r3W@qw&pt0U5uc+^6W(V$d!c-lzg3obFQu{gYtIQE!Vi@S!GxXp#0|1Ra}M{x zra>Gjd_HuMmo*{B_jhN%@-|pRh!=3BmA<#8#WK0g17{vTy+1Mle+1h*pdKlqa(sC5 zc@F>XMZHwc<6*vP#}&1{>){Qd_V<+sa;0w4X(Qli!!O|AX~hBX&d?vb_wpMZQ$f)e z?)MMyr#!(x8Y!1+}A%(}S<=Ef&iO2D7e#r9dXFz4yO zSUbR%zv-L2BK$qR73?GQYe(+dAIsm!mqS1f%29tQ&Wr{{YXF*praGQ9D5|dQqRVg56VY2nB0lOD2U6(hCDI zqwYRGA{&=R3w9H}kLUm7SquhJfsa@?p$Sd#wCzp-pMJ_G_q^caVR`(p@bsSw z6zAXTmSZS^m?HvjhkujZc_J$k_?7CTYG~4b!Vv7N^%be_^bRb}{h&rg^C@=t4JG7V zw;#V%j&Sb#DpwQW2%xiiQJ(vv#V0E=GelqVhRyWU7~iCt+C0IzV`sMLi*n@sF|fl<=1`xA`py#VsXRQ~m^_~UJEf!Uaej}=9pE}w%+{J1zz?b51u`X37P1@m8+%Bw(J`2(56ZrI(y_Mw z4*UW>-fA21*135D|NK+F+y4!t^$@o=$({f106(tUGmtm3n*@qq3V&fV@W6YE6{ahn zWzZWPy!SGv2d?JTz(-%R>J@xNo8a%BJMT;Ml~QuR^UFhf>4-J-6PGJ)^fR5ey9M%+ zE(Q-0@-!gj?50heUY}o z(jz+Nqu|iN{q~L`QUEXKz!8aH;QH~&@4T-Y=o`kweS;Z?rA!p`k(hTj$*2uok$IX+ z63i3yOwdOlY)X)SuHvE0c~pDRj93xpfHNceL85>0R_~gqYxb&HGS~XdlB9e8i~PIZ zYag@CS?qBx>TF1D#yMi~?;HK6I^4n^RZV2EoMK~!=#i8{9d&U`R5lk_Iakr?`h9mdQZ3(I~L%_ z!5ha}-lZD!9uxOZ?UQB71=PHawr)S2m)PZ9Uvq~M#t$E)_{cb}ndE#tfB>3m%(oDFV^55blk5DE@xW;ezmaqC%!}^W@Jy|ual)K9gyeAv9v116!S00Zoqr$J8j|g@Z2U& z$66`W#kA{_-l7epy@5E-Hs-n-Nl$Z#=$t<38#yXNeQqCxH|02lj-&6}0C@fOa4Q3^ z0NWCBm7TYwz9M*@XBPy@n2LOy3kLd|f5x<|{?er-rZ&pQ>>K9296Z$*22)JdwTXE$ zeJ5?5H_x1S z3hW7EpXzhh2M(^`dn(5fWiNwag8P=St<;J#=6dxDW|F}l;E^A_jpodgb6kvc$ps8&D;u(J+*Rg!krlQ1d3M&E2bt z(|SI&_*5)!+&3+{h{(jKQ^g>dIPm?I9qUe>ha65NXDjv1zkOly(KNt(w1M+mujQeK z^QH>wRW>m(KU44w>Wh6Fo#GsxrK9|^L_X0LfA&n~(=&zGH#+K+vA0Egm%NF_?uzBI zZ_q>D)+39?VYRn8k6L3!2zJid&z_S&e`TIqn4a)SK&vq6$BV-`5v339Df5lBE;tY8 zSSTh4gm58Qv~<35Ns{9`HbPBe6Yi}j7S(%*%^dC`N8cmQ@E zDZuN>QstgLCk?gG7Tvk>1>Wc+THjR1h0qMpKkNY^@BBZ^2pRl0j6MIwGb1eN6-=O$VG52kHo1tDcxX%BH z0p5K)x-2BZd1Uu7t(ACqJCBO$HV6Z+l~k0p@iw-o?*`KU}fbEQOb6koO7rNzsE6hU-sHYSE(3zz}Ni$SAPx649O+%X%!| z*_an1`+Shhg5$UkEsjbPCmXJW5kIR<}y-LBb3`}^(*N5tkKu43`Xrru;eah2Ax4Cpg2K=L0L_;#iTioEQ(PpNYZ8YGH>TTRjCK0Vy z2RQv>s*?Q347@4X#>BgZF3_nb?4UZc`^Bh+-$UZ$JE>b>UgDoI6_=uKo3S#B=estz zRP<;d{P40G#x%xsSj|<`e!v!lPB|sm_*LDqn2&R>l#xEmy4FHNAD1CHHvh9z{W{nf z$PcO5!e0ixY+LZyfN`#b$@{BI*NH>h{3_|_OTQ=dytTGUG)8*LN(wBD1k4WDS(v)92%c+T$Zpka-M#AL^Qdpt2`e3bnZaACB69eFzml+-IiPr&fjnYq z*s=TU%9kCt z6NpdsL?2cp#hf5>>Ie<}PnZBcZ1Auf=7!~f!$)z@jEiZoBnt_BJA955yd>Y`c)wIS zD!aDcR z_uv(wu`v2I_F4D>vy^6!j1sz0{e~#WQRB|=V64TCoNyU!auUl;GTb8Og?o!ps zbB-RGL5vF{hVr0?dJv|W5q2@iP#Dn^gP0j?G42QLYbx%)6pGl2%g)qvmm3+n+j37~ zgsBICi$;c_M`jEbLmNa>7{L@q9?C{;3ga*P;k=xaXJ>51ukZi9wbr*5)G`0Z_s$gV zYrdY?OZ&UpLP7jk{6<2>c{>H%3=yP5Y43mJ$Z)_eb@8|nD=zIf;mUy3eaCk&>zMqho39bD3CiE?049G7w#RaUqPL7zEr>! z!GZoxc`63{K>Nnv(4YjpOxXd12zXtMjC7 z3Vovo$$|&nTs;vMLf8EU&L=Rf?U#-R&ct2~d(6?j4Ch2#!rQ!vzNycZ3l-*z5|UPJ z&;3I@!!r}!k6*kIJ>kN7U(z9E1n{0div1N~!{^1I+=^h&6+s@6@?}O!4?Of6_yiAS zs6QG~+=O=Dlc(^Ou~3hC(y(S#==V$5@Pf|;e&wIfU%8HvjPUoIYYCKq{CCU#e+~M) z81xD4qDI>H$R+WTh0WgR8*B#89aH(=@&Y=fK{q4vJ<e|&xEC`r z^m7h|M0?P67<|MN@A0$&XD8_!n3`F+Cw(cwJlBp8%+G+QQRD?Im zq|zllIL{~Y-{MCpxQJRq2lNGqBxvb3i}}pk2WCbZ}2j zX!H&8l^I^9UlUaIEI?nHf%=WSus_eSJ(+}aKt^MPD(LgkEJpb2Ca6~}Z+sz~Yea>V zZ~j9<9%XR<@{BlhVc!^s!boGA?{LcaVA2)!!rp&Nd2w`-7K*& zza)X}%CY&4fOOc1%wS$sMke$fLXSVz83*u&kgY+Vq|gp>mQc6n8qBTAdvb=rVFBj# zbv=w2V)FGY;8R@;bCZW%dzKm9QK?BYx4l3TfsK1jU z_>>*^dp-L?yvjw5N>}kk^uC<@=H7t$40`xIe@T4LMk%Ku@k<-fa~1lM`m@S=__-f4 z0LL=EbcTS~&5if%@$Uknn7)rMWEvy+eYzvy{f)mXvds`CjQ8ZCer_n3=gt(^6SUtK zTzw(4#Fy#0dn(aTKd=PIJG{p(3I4a_R|-=P!y(**14K7S{t9m6fL~hwtr&<*L7RYM ziOc**_=+D|4?5uVzkDD&ZXf#P?hoEH@Hv|vrXwx_JcjQWaQ}*|-gA)l6<`|Y`Mms^ z2ogU7 z9A+9C@MS8adAK+5S%NJ3^XEdC9~W^3Y4rGs3+F7R(*-=EuVO$CO162gTx+n&OJ4AFJy$sl z{t9Wgg!k6I%tjfbz+4y3oIwoyjoOz_VSe(-UOC7?|3P+ht^pjup#Skv@>O+bjT*Qo zi9s}Opk538=uUz;KpKe19YQ}sSI5>${U+;)uqgug9v60smGnJxnvnGg^rfWpNHEYZ z!#+61?$^pPzmL!KuYg^E5IcW;6vOioRx%H`M&E)>5AiGQZQJ`>UT~JZQMdIzAJ-=i^mEyy zTvo7$R)GJn1^1}{>|}hQe^K`dR)g=~yx=|HEJgTRA@?=-2U+w$@ntz5TZ4 z;OB#%OnPcUza^faK;o?LIx~&cpuU7_5i6bu`|>2O2hn%UfSlug1bXquB_dF{i@*;=2LO!b< z@+*R!!Ty~4c^_e6&e1o<$7UvuiD1f3urD6kQt!JL+Q2J3zq;+W>) zJ+~HU(m?+aqGW8oU6E=cG<^gDB^K;4M@?S%yQBj9_`kz}CTbbhU|oj?qSrkB{Fwh(qL?WsO(?;8ZGLbs zTjcg@aAM2pG%!|h_BQU!9mXRJ^G(Sr*8-pl3nF<{7#Eze>LqaGuGAH8_?a}~ms<3% z?u9{#%U!(+--KR#BdidHbN@;Ve{>`>8mF<}fsu30ua-K)Vfyn-we8TM66CgVvY5ApT~$K)jPGA5o8 zV_^W@=2RT0$0_Gbq!)MW?ukD$|IGXo_0MBZ>xqej_YN2L6ztq+;1Qtqtgdp!gX)(U)!W!N z*2P=|m+a^aEztscPPorA&{Va)2#%f79Bz+Ixgr@0DVO@8*qE$@G5Ep?;4d9+%_rO= zCN^m2T1r?p8*uMLBv#mXp)itfv4Hc<>~q-E22ah{=ee2Ig65+kZ}wf%9YqEpn(|KZxs& zlX%5(xlhM6mIHiStkdqhBYdz>6o9gyR{(uaj&imb@-x8Fz6Ixd&Z87kqx5y!Ctfk9 zpqnH6nmmd7GETOz_lLv>cl+-M_}-^_nB#=Dx#*zZ0OH_%)(v0&dQTe^D1uw?W|qSTrXtotGF{8w+XIMPCkd z_`NmSyeF676Y45Ui%M?DjrPO`i6;cfhGc49Us#`calwX+aARQaNYKL&Z);Zk(17>0 zve9P}?EjHhF18=VvleoeYS5=U*9PeH+BLyx;1^=j;aUFdymjWq294yA4(Z9wO6x|w zN+4(P(gcjiLrel zI2ItU!&$eWoE3-7%U?bG=DuDFOXbwPYPbAW+z^pN*PWK*&)ZGQ{`3yBB{nv)=R^_* zQxAnk$PXc@DZUh!C7cXmE6z2zv6`2^1NW%vx!}>tduX6uxkF+Z(&iT4bw-<~unkrL zFC!kLlbn+vCoo>hf!&jW;*7onL`noz@H$c<#or?wAoIOtkx68>K{IT0W;;PF8k=VR@)>e*{PY%gQR@=Ro3Taa5}UXb8xoqEmy zv7%>#exbgxmS|*Lx?BZmvg(U{le-o;EL8h={nIxDmHPIq>Z!g0zU(<5g5*`r%S(sk zFCx&*7~l~Sz9DAzF!?rA`!A7#9!5v-?i=l2!4NT;|gj z(MK+O^ClkM-vJ^7-q{7C?u&sN6j!l?Czpj3!ApYLP8-|gZqUGn=;iw@Cvy1@C8X_a}jon6nGB= z$ZWE)HXvE$U4v5^{<*}kcgOq0b&R7EWoW!abn>X7;?<(b^BOVVMqt}**#9paWl(I<1?tI=$0D-fsvMB7;`+C5vL!if9_1&( ztHB|ggp?HiV1TMX8Q`r%%Cl?&=K#0B0Ex@c#}kc8;FHE){>)#;LuZ|%>ZT0xt{4DQ z>8WcIX9t5*K(SVZ&|CJUXLTEas|6Z0gZKCNNLeY{iq1Ic5nq>(o?(!pXD|l%3`ws^ zw}cD}<4~~hT-N5Txe~@YBy~570^=p#gJx*pKthwU6g$eP2szU{&o7D>lQF?Jx?1bL zhKpx7kC!!@ue2L?C^I~=;OF#?b2c2BJq1#}v}>0$;pQ?R&(Y`_zIsE_a!&`$7|&wJ z>#aSFQCA{3z5Nn=w@UPRx|uylUi@vm6q%nLHv!)_Ade1jGZYU5Px{u(aTkb_!ZIis zhe3O&65s)kZt4NdX`s=P2EY4YK<V?sD}ZldYO!`V8^VqyR%rVs?Pedu zxg(gpa8j}24!s2&?U)y=Wj&OiiJeMoIKI?xOiza#w(7?1H~2RX{6T?Rf$tJr!bX$o z0^O(xaMi{CaR=|%D)e|xSn_>-44xts>1vQgulwyr@zt$9D>2cFt~3h2RXFupJ$IP! z67OB`Sxu4r$>17KUngr7@JFJX9>{^nX7|=RZBWzBCJ*DMxC6b)z?jJEc;T{9AAyoa zd&O?GfSvPO;%vB0a-6bUl==m@y7k&dNn9>NWY@PWquHl44aF@r*NjPBbkX}uW-7xN{ zD-BsY2WM`IlaJLf>_#sU!jPuW_UfTJ7GRU2VpU&o`Kfp+fj_Sdc}&I77$|*vn|@F! z5)j3DCVsFMkk}B&FMoUoszh2Qi>Wxn_`h1#E7FH`>rWS2i)EDq0MhnXlDA zJ%M@_Buj0>(_$D?{CzlUxSSN%ySog0^fCCSXaYZqskHBm@_EZSSo{bmBUW&Ef$0XE zUr0gji-0iJthS0bL{FxQpakSc+ND7_aF^P_f<7%mREbr;FGJa%835z(m!>O(sG;axf}c;Q|HJs5_0oLt(p z7L=a0C>SG9NA^ZvfRZ^Ne0%C_@K6NiO}uG(=1QY@I$48~&npk)2oFk_8Tdg(CuFfJ zK13^nY8hn-Z(7g%4$n9j8UycdC}Ux5yr!orID#eK=Lzk1?&`3f2v~vppjw9K`f;<@ zA9Kw6(LSB#moDRORUFOAsX0=?eNlLxL z;OsY$3?lbsq{6OV)^B>SD}P9Ur4y-k|Eo9gP+uBXe|{t^s}uK7b0}!1#y;JOklpBd z4y&=w=R8VEWXk}5vO(pYj`NAz%OKq=qsXB?RDJO#o|d%h2{*reAdtIBd6kaA&#PJ& zbmmoTbs54ojQNOe6WUrRZ1&QCZ-By8u#ML~wX=*=-y~g7G~n;0d5e#>5!}fnNMxc0B0wCq)*Kc<-7>;b-j-1cB^}4&mt{aN4j4< zW>@eh&d9Zb3no3T7v@1YHzCiK*vc+UEs$qi(dL?eYJ)gX&&id1;jVL5ev5r`p0Asw z@>G%TIq?!7>J`7S8C8(6O+v-#lAux{X=7)R(zHAa4|>p^C|(2=qXMQuha57(5B>Z= z;?@&hlq=HDAW^R1%o!N~^6?$91I$XN4TXt&k-uqqH$bqNS_2DGarmS-(Xlyj)=?<1 z(X%*>8F`p8@hIQ9Ui|3#;x?jn(6y6mm>J$;I=L-oP$eefs}&F%)i?QaA)M!+(15*O z*ceq7#oA__C+X5e_301qfBOdR_K~`R-`4#b;`y!tO-aPH>*`uYb%-HJzD;EA`_U*MlV%qcvx=h+PjzIgdkxQyr*BAE+Y(M5}7poeb% zH*Wy{x=}_2Z3M<7Sv3T|jTT1FI?Y)G`8`)oK6Ypx`q%8NJ-|#k{ErFk24M-5Uaqgx zDd3s{u(C4X8||wK$ZIrf1nJa)IkTix+8FA+^a2lCR+`I)g07bQdCFnfUyhb?NZy;I z#lYF<3G4FFc&87{IXTM%0^Hg`LHdHnRX18dP7>_-$t(F)eXI0%I(sF1aD!0=Om}Wj zc=DLQ|ItxAm0s~Q4UH~z`<@ILP8N8WC6G`UeM0xmrtI2V*o~dK^Wvs>#z?xiAgBHF z{R2)0o0uvn1bIkVKVj3EISgSwR=y2e_;Y)M4~VsJ`^LcOuz9QYh)?EP34}q;XXnj% z>%X}}khEg3%0d`5A8Ie+Ypjj3r*`uP_s&!PtnI3vvEl>y)nT-S1iQx6coK--%08>`(5*r2lrW8thP5f%D%)=KR_;Tw^K7>mr z5ReWTbAV)d#6Q+?yxQXB5eT$TlxC(joQfIW0;maHvww?+2MIOk3apOGJy=0zx82nW6qrDDKF^Bt* zoil7ad!E2_P=nqu+wlv5sss6xvVt1e(XRCmgd3gbgJMKnRVVqrS&A&&pYOCY7dxaB zs?eo_@((;kbJ+aNFYy^nG#lw-ye6ORA@Qx`yritY=&P{J^zR7qK%7-4?7gvW7v_ZM zH#aarU#3^>O>#l<c>z-B*rLHY#D>pAQCiLdW|^hTnz zZuO2|n?dB|`xK@mm$LR2B~!>tAdRB(@mq8-afX|&I*j= zoBQ=q_$I*!5)jiZ|AGQEH1~2}r=<@SZkd8hsC=K{x+g$VTsAd<`4c`GeI4qDc`b(K zCfTP^>k(K8tbGmcek5=dPM{8@V|QCXCK$03KV?k1GO@aa-WGJg^2DB_p~ED+KuTL} zCG48B5VF7WojA;ccwNm6M2rcl`rF>#?HUK`rI{B?sAbrCZpY0UdkQc;>LDH%3!YKW zEhMd5PQJ-M>;5+i<{<^ByjJ$clZ~1o@k-2emxP|s`s~(ERbfM$frHGK-@Yk8Ar=CE zQg9m9t_|#pJP4cW+hM*F0yTpN9NuIpY z57Kc244^a;7A81LI|u9DnkqB_TgpE^0UU0bQ>5??6I}1cjQv&Su>Tba5^<8Axx*uMg*q3g!fmZT}VBLetQ6Y z1QT-xEgkd~R9-i{ZeE3t75ug)4!hDS|3bnE;5W8Vp=Rxj1U5s$BJyIP>1Q;;Ke(%& z#rNCVQb~fXu*^ZaWq!pDezYOhh6Zn`3y3Aj43mw0Zm?{itvi=sKc#8)!$y$lMk|{8nBS z8_=sjAFA|1Ko8VT5-PBbn)(8yOsTAbip%UG>Ki<|=DX&YU|?5vOw#tTu(wBWi;X1s z?qJH}OzI~`1o%`akm;&{eiz*;)0m2RlCpvQjVY5O7VV(wXfI;mcq44m?{tn2LS$XbkB+bQtBtz~!STQD*+X>&+`UiGw(ri=8v_?UOiV%6AxA{dK48yU z<}>9SccD*Nhg>v^vF+MdBwKOK%-k6RaT77+0WE4s?kvY7>>ngU$Oq+kHXGxE30qZo z1@rQWb1p38SJ&qkfH+)6BY^|P}en<9G3Jt74fzz&d;X5&Cyf{cdNsytbc_!prwj+%+E|gw2Q7K}Jp!ZI?@!Xmd zRPu&+C)0+nomzW@{_dR(d6ZE{Tgwar?;c~Borj@-!+G4RE{vhVMvQhUq4NQ4s@X_`vFF%zLCR;?p9HC$8)B2TsiZMB9aQTRV z8>%kFdx<4@gH62p^WSjOQaaY&W-jss%BIwph~fJ}AZ@J;(Ki;LWu2)M@A0(3L@Vn& zADbc3$;aZW{^-83JmvalZ&H@TWR$oLoM`7;CDfnT%O8kt^^{&H7tIC`s*Q1oIp~s4 z!(lVb0=cW*)H5N>AfqxFn!Xl*>UXW2NgK&CKndla zR=++5c8pRE(#)h0TffAvOkv1`hx?jQ=SdJzI$55JpE)7SyU`)>WyqtIHYsdZBs6Sq zOvOOFufpW4UNnJl+067OV`}m4nfL*Ev9NryJm)0}CCGJ3>1LOE80)@Gw}Wt1vrX8t zB{(DSk%`h73Awn%vqXn0ImFc0cVW-DN!FR)&W&x|GiUiDfzUeI5?r%SAWte?CWp{d z7HAUzy7AKov8N9TuYF0!5ij6kio4{MHK+k;G#)BAwb_X08y~tnq=xd+1qPPf0Dr{F z9Pp7#{oDwmfebf0+E@QVW?C{|W>B-#pcv!VhSeX{v-H;eoTN5TX9Q```rscr&AAE) zCV!>PBwu8bn_}ghrR!*?y~$AN3Q%2>04DWyJd8bw`sqIE$y^YDf{lG0kU<&%9zGO4JL%6%*nU*}l9l^^?@pwI zchOjI8!T*p|A<6lU|yCSrkxXh=gczZm-j8O6J= zW~?g449K2)9=XIGY7kfA__idQt~gI_!O6kl9lYsc&8&uUeOVlf%6#Kw}#hM{Q{PaFWiey}@Pk5Hz@i3tbX} zKbphD(}wmzU@_xPvK!&Ko@i%8&zU8&cqHEBn|f40&bU2-`F_$~f(C#`eG^i_-rPxS zc%@LpIs(tEc%`0WHh%qsV@$$HKZx)R5P@*3Peag8XTU8c!wPu6iq+=odGZP<@hWGd z1K+JWe{%1_MH zRh#75`qRI^LxG5)zhpE&T*3Pb8J+)?6TP~y^{3--B=q@{#R zJ>p^$JJPav>jvsB_7+Z#o3|qL!8U2~XsmRK1qmt7O8Bc|v@N-0#3L&d zC~X#=2-o!@xo{b4r%=|~3O?f?VIWTv;C3n^?CA$Ha4+mh2Kn}A@SA%#wCK;%r4q)S!n5YltLh`1oe)E! zQ$6LZFifWKyVCAWa$2mUG5W|ux~H-gsGQmflU)TYhldf{eFG`$n z#is2EW3r#z=v=%gP=2F=ZZAAT*D@~!>Qxikbj(4w+mR^|as!Q(;7X)QY2V2xi&r_| zt5M>|!}iehYERy@I|S%+5#*4I8`B2pI$L0$q@W#{B=}oRd8oKK@K1=!R@n%9#ihWB zvwun?YZK}$S{R(>r+4LoT$kV`3; z{pdLQcET8w$}`r^R64Im*=re;OM=q<`dFFEkXvif1vqG9dWD_(|9p#`yz5;Pp&RVAKgrJCuR{!IjwJHz1FU*skwJXnL zk7r{zPa^ycG9r)k9w4_j`O@y|6y`Lh>JuN@SJJabcF^o)kKnXVZe~pn}}!XkCW!#$b~rf{vwKTj2K#75TF0l`tpP zVGNq1lFhh?$*Aa!FhfY9ZL9*%5J5F3J`voHkK$gkCx?j6fuD>i1JqLq%&02LSoiXe z9l|qM^-7<{z(2uh9y{O+p{|WL0^m$4YAH`2ur2owJNIG1^VKYM=z}W&s znVyE+cWx-Lh*b{Bs`0f8ehXdFu`*K+8fSK3HVXgdh+N0M@DXi7*5VQlbp>Au>z&P7 zOLKu)JZs_izyd#Pdhs#fL^yGcjd2NQdz%eP$QQQ(*@@O>UkOq_^h(lot!@Im3bBZn z@w!4#b><>4G&PA=@{P;Et#V%O3Q7S7eSHhhyeE(b(quq~Xx8ee@}MHD9Z1>DG5MB%Rl8}A?8%23W8cMk_>UdbkB`Y654;p!346!a zJ?N-DsotJNR zBWND>BW!SGkVoM%;>BgQP(5ue&Lz4SxYz&cKJmg+^YF7b&L;E3b+aY{%grx;_rCGX ziF0es(lMS^I04=V`fk|D(LEQTuw25l2TqJ4DZ$&`j7ZWQLZ=)M1NB8;>z@+*j|ie) zbQKm*L{K>XPvC~#P@rq=>EJN0LM}+u&zLwM(fyryT-=1X3d*PAMt(-L66m+kK~i>5 z9#_vY*^Z-wFoAo!r-0{(Hnu2!KRA*H{0u#5D|t<@!026|r)Wi@=&4*OeuSH$jbfVE zn-2ye;f4-hno)|{y&6r;HyaKw{{mDlE+L?Ozz${cwlnSEPf zNk$wxH~g;NYX|g4VxYY(Pa}?;w~uMZJvfVcopHrlVJt*4>h_utAh{83m1P^qnBM`K zu}B~D{og0_b9>Pq95M>vX1;WKe{fvGb1?&gg8qqe2g1(o;*|vKIL|nH9^P)zm3IcK zqkjP1E4dH{)J85yiwO7^fUS-`lxv+)-S>k^$<)6(M=c-V}6c7 z72|+vOuR~Hf{_Ddsh%jK1QNSou7Ew$IFw#;s#&!G5sgC{9$M^JaD}lSvhVnsvk+6jdzFAryDzCV9nDG4TBjL5^ z#6!VrUUU>e1uu69nY4kWgZUww$Fr8J=Fowz>~~+h(XiOJVWyNuA|%0Jy6LNI7?Lo3 z5+efK-9?69M1Tnh{bCja#`JfN8VtH;TIhzu9MGuH6X))Q=C`161AX60r0`jNV>5^r zp5seQ!SDW3yeRkjyqwk0?>n%sAp5e11EQ;5YOBFrI80s>P}yh89N}4g!cUSu!cfoL zWS~+uEi?KhF>kOnwzrQ*w%?rdIAK6dIEQ*RBwWY0U)(#r@?G!6f|_82D@^1;VfZbO*19UWPTusdvt;fIsA1<)x?X zuE6akpPOB2pf6KW1f96}tk0EQh4q2dYhGhU>k=5=Z*b>!*_Ka-79v@9s}C_KC-Tb- z(t`@RpmMJbDn|BlKp#^C_~w#$7JL_UWED(^Wthx=-?80dm#hfj@yMMx%{<}~?=sLi zRTs`dzt6$PAPIDrVC`{vRd&?A&^KP2ndO%Q`}Ti#R4Vjj(CIle@uIvMYj}2^b#R9! zyx+Aif(lM`wH2BROvowkLdcCL8HGcm8txktrsrrZ-q~BIB1mER7qjnB5t+UK4hBAH zdbgZ5UT|k0)L{b36k?y^gc441C*uDQI+u#Iflo5r?3SQgV1mhaCE%GB5)bvz9A$wW z2ow=SWVTJ#xcj4fG2|C+R{`um@X}EPd{`Kmt~s}^HQ?FFwfzw$a2C3~Wk_adQ; zF}ch^M;0z$oZlV`>^~t0z`Z~Ta2^BirM~9)>mwyJU-f5aoq<+9o5N3kDz*u{zlN9k z4*JPaO1Y6VfY~8vLLOY)+KF|UG9jI>)K?Ky8Tw1fwK#nddnWAAnV?59fUnj#)d!sU zv%k$bI-s$>R2ONe&w=qM|Xu9Si(Qn*#}) zsy)YUyKKB{kZ-e5$;qo$Fj$*TUE+Xx@I>8o{huC@oI9?setfS?$YF6K;t<%7^qm9f zD+Ya)Ff2bHZ1WaEP?7Z!2`55d%CAb_^-5oXz6b^3X>pSe`KJ^mH%T8VEtS4tNR!8` za7$41QR)FsNn;FkXfMyJu{qQZ_G!$7zH+6}poE$8ukN6@P{>$_VUxmM5w{ulL&t`m zqwYFmsW0r!iA?c~wNExe5W)RitgvT;^2bHO@_U4Ha34ud0X>2X9lF@dMjb%HqZR)zgPX>EZn zO{T~#3W<~7JVXOBC|BkOf^*;5eWQapd6f5yGmFwT5ufqdg?=S>eg-*>#kTM>s_l`R za6n$-7y`P&C~GyuC+@lezLgkAr1L>}sTb~BY1D2ts4h?=)(NUkv16HEWwpKiA}IGtXLCN zepw)0m2>MTL9iE@1u}pcg<#+}vx{B6I}`0-ZFIOe*l?k>57J z=jyN82*E~q!kbKm<#oIjS@{{Jyge{Z8+j#sB7K!qXmxM*nm$j3->KnVB9QXJ1Nv`s z@hrP2S=B99@ZDhgs99N*j+|M&M)MT*#v@QkE3?>FT?4)&X_@a-uUQ!{!Y7_>PULMI z5--9=TN1Z8ATLx;JfL+$$E|Ib}A%umr;Lm3q^%Em@I`@;v} zN?v3^ysUUYmj?~v7aB@j1@JxTceL-eV)QjhCv&LJ2mK@ll~=fqL491ztt%Dq9@MG% zV&!yX*z3@z3NMcATTo*yN|>k0XCiFLW*35=p%BD;8fI|P@&gb2C@~;zd8YIdMknE% z`l9b%3TqWM9n?KPmKkDf9x}FG6n6yh(#}iaAwFD?EX*mF4oc3$p4^L}4%#4zGamV2 z4EU)t4M)u^4gSep1UPy8xocwNLDlEkj3In;TLETYVDxHwfI71BtA6bE&{(+5&+QrX zT5AyrQ+aIf$z=?P4Ibp6uS}VCEssp9oe8`dWL^XNA$SP5?MC~yjRmBw;rW8^5uUnX zI1Ev|EV_Sr1a-JyUB_$FyzxS}&yjspD>RCVi+oHt4e=*kn^M zfhDR9%AI)p<2yVcz9noNV7rNrVh?*N4xwI{OOq65IR`VpPhPnTXJrqCkHri8Cfj0_ zY|T*j+K&|RCvQ^5ewVFVNDKmA!n0Pj>+XmrdF7z|#rBF9GKfB@a|}9qyei*<29ZgE zn`3ea$TM4g-UFEObQSQkWRd!1kWaE@wEw|_>yvIWROpIC^ZMO?d8GBLaSl9#1$iL2 z>(Z#B_46?A04D_Zcnc^a`rLn>rkG#zyK34jFfDDHnRKcL%4^$Iu;T*$+4=n=hgDyq zbCDyxmNiEFMLI`^UmS;A#>k-bRc99HM@Z0Ss!a320jAMeguN#t z^S*H%vofhow4peOy5WMjELqJ687klYV|qXD(%Nc34bus`Q1x_HB>!%Uk!NSUPXe#zjB5$EbkpSn1+7 z59(D!26rhA_XWy8*Bk}a#005u?H+N^(f@Z84%CSqVAtk~ox!*P8mP3@RZvbz zf)47_ro&&VwC%wh@P*OK9U=$;FVa@wGT9Nd&Q-Mff<_vy9^@VJe|hBkBDfjyqaQw$ zp}NLv=S4cSkg8(Livz*t2u?d~^xRVw5r^zt9h75}Cp>=IF2X}PH!1ru+wu$1YfsUu zdgh+d8{A;2GowE-6Zq`uQ zlb!HFWUOn9<%hB-?yQaR;I2UT9}sRBWTdi!-W7J;e{j^odzu}}xyx!@4Y(DH0wiQ& zQt5fLvM-9>tz(UwZTTd3GT<%JWrI`K*x3xGEG!>dNWAiSG88`= zxS7}p_H8%`DKMw$A$=kP3+k}gPXVRV**a)J1K$ho=|1%6%l)G{J%l1@N)B+R+Q&H!{cqm!@&1~v7vy~Z|A z>Bu;c;Nq&lahpY~8C(iXraVdHtCI>$}#xt055WZ|@$+-au8!l|R zRsHZvKW!Lvulxsj$LSIy{>A|HW;4-lw2N#bP|ddWs~`c*oCY0i8kC2;XY`S8j))Dh z;0MyJa?!jrO!!(-#vosji~_id){CF=aXwRffZOxgqwqFb7fY?z!1rB&o~2ltm+A)s zw`bNMT_?Tt(b^Wr=pq4qNk~_)$yKw~R(Gp&YYlfaJQv{8!<2!lv=tu7zzxz-`l5`J zc^l?bNNeXRZ&M05O`$6^gdS>=gz_{)Dbitouw4JI4^VqQ=x^&DaU*#t)sp&5q;>Z3 z0dWrS8rmRv6)~oqXZ{m-OrdmH?EZ5?rOLnpe$K)oc)DfF96D-XQt5)s=hi!(PDZ4M zu96pHmH63J!u`L516qv&RAzXPUh0FKaysoqV+iP%K7RLp5}v(=FH1L|rC* z>x%}y1(~g{g&?QJCzV1=i`8c0$A-}Y15gLdWRsRjAuY>fHPF(!v;%b`zDPlHX}?uo z+C@CqxbT@++H1*GUxjge-he{8rs3xRo}8=+`X4%ED0P1NCOMZ60?9u^C$Mt{Dpppq zuLi%kYrHTBhi*U)>orf}h0%#ZZCTC|THTdM7{!eBQ9Fmel*PBU-}v^Jzv|t8*4eoS z9k%dtGTz64gOFY5C^vYediYhJ2|>FmE@KvPI_%Y_fFkD0va59DUd5?^5-F7Oq%(l; zEu|Gf>T4-T9!Br@;}kZ3 z;MeF?zsq{blDJf1TOb2m7|yN71Gh%9zjGvzP&q)!o_Xa)pYyok^0V}<=^H2wi$%_3 zhNPuV44sbhs;-HCePOWGm}Ic$UaE{c{e>fi|NKbqLuU|1fe1cQO3%UdNFAE*2v8ZB z4Ekh&-bvk*R|*q$LD34lmdV>l3W*@yL{sI;-s=bLp#G5=l&njIzBt!C;HGxXw4H@> z_^Hr?$)0eKd&0B|l!J-nF^R$v>L8@M{KstN%yJs^zhOKhePW-TYbVALuvZ9fg^u%L z-B+MDPf_|t1%C^Nb^| zC1lgX2Wyx;slDRhg6lS7@MU~rL&A6l9$}$Ruv)0Ti2QGljH~Da5fnXf+j?j%uR_=i zRhYsDhqiMWhXef(zd#oe=$8t%=l_e-z7jqW5YP4~nizi8QP%Z@XJohi|0#Nxkjb$& zO-xyp7k&BNPDDtGBZU-k;*x(0+yh#8K$yX3(F-klA!cE;Xp9zP5T+MeG)8zas4BCn z^xYNrqlox2^|$+<)^s;UE2BlzXweJJ#%R&l0(&9MV8k#BEsTjpWBg{-F01m3FQjwc z%kw_Z^8!CIVE*p2v5NYTB_13ZJ*fD+)FTZzGd8aQxBbuFu($u_bN=*S{$$>V&)KC4 z`?8^Pykx|1>qimK@(nmf6(6gQ+GVmSzR+j?xAb&gxe>ZdWO8G1j8Ggk&^h~?a^+q# z1M;GcjREe%?LV1Y?XJ2dd-El{`nw;{{%?YU`^TT)d0n$ZuNTGaQwqp^6Kj1F)!(a% zp8A}=ZGeYqMC|*5vX>V4=Y~Q8{+wZidljocb$9xag`WdZeL#cm%lG}9%!4_u zHo!`GqA>$|bNt_Ok&S-+DZ4I}4p~oSn8qdQ_|0dgr@s7ukO}m?*{?3jK2*!UWL(jY zXmUf@YFX0;>gVi|0Uo@;YLD&^KV#@ap?+W4z)sXZvJc*Uc7eF=jfxoHp&Ecf6_*I2 zXdVH#@X~*;-j^`zXt&9|v8AtQ1Nq~sJv!jGa1JZbiz28p&QyC}Uu)M^oUsrc2mWh! zmm>S#5wtLkO3)nv#?G^lQJ_Ztg}qH~R8Ww+v9~gwf)D?ivEw#8{fzi}uki-2eQsc` z9fH%T_R54huLaQ8!36yb=N+vgA>RhCYBA0j`E(CGdrf+Fw(`QL-=x8#8yn;Z72zS54`wSfbUUbs&g_+l6@{-yRlgx$Q! zMR0>R>JFmzZ2*ii<1N%4SJn~#;(siAtmHmw&&5M_>R#$7yR^5}jeQ+lXFGf!J!elP z=*F~lwzQUbNiS;17u^+1&^VW}g94mHb%{hQ)p<2WkiEM5=C{+EKmQ?GTSvVIm56{3 zCZ|PY-NyF&8k}s;0^r!dr1MVc^%dq+P1Vqd_<0AR{^=zN8b z)niB1zhyqLA$qBvi(@;mub|(I!<&{T$W@9Pyw?TibG5M}=)ThI^b7Wm88Uz_8_VX@3E8%|0o3rp`=0rP=vLh}gFr~G z81$dslqcuC$&zRAB<{HnRTM~CFB%wvxpmg*owfC3W>8!?TNSkKkrZ6yhiXYk%lwnF|uzw~#>x(VCpe83yTm0U{k zW%rVCB`vo8HFNKe^!sFJ34nCo`YQr`8~eS>-zF#H*Onu{sz-x!`sK5JY9J;h5AN5$ zVps%ccpD)Ve84gZrhZHH5m1eXbg6OB53KNAunmUHI|3VtnAZfjax4vBHSnv+qmZhh z3EmW_hp*u7LH^V@=eK{!z#aXKe57~eHG2*KZ-V*Q))+!w1iq>98y3=U%tH(M-mLe3 z2knj1OUE`>y#F^px~FbiF2e^TMoT!kFq=qjwLW>Qx&QVjyz-H=Os{;%$J)LEJ*@xC zUKcC&&H{lOUx85ZSTjSa<-ba_BHM|Kf z0&EwDssMdw|MAE2Azfv6);;81Y7g3hKBUKDW58Y(^HJxmU+E@=J}=_x$Kn;RA#kov zKZHM)n`ntg4xn!S>O4-bE5LM8>3kKgjmZAK<9Q2F8wYH-`G12zw2(Xe;~xkOZ;W02 z*1&)D+1o*tBl^&vF;@ZTyR~a?fO}fs7qmY5dcH<|GWK+%6QHo!xB3VH_D9@WS6rue9y>}3t{6%GFz#$TEP<6tAGN7wAhyN}k%$~anE z?V7m`e#tL@uk==x>=$FGg3l3tApPhg`8)*_H_AYKNpwm(fFKQv3(u3&xddWJ=nHk_dOo1 zpsu+9{F##9eDF{z)-CdQy3!yHLic*D!q)Z{lmqFh{sn&K=6vwL(}TT+IZ5BYz{uIN z%N8aRCFgQFIBjJTjnmr*@L=X+`@+Edm|Z#CfBlmdqidC`pHsd-1axJ13|ZsKzQreR zt8WOUM{-3jicJRk0t*?pz#CuLSbs=%`8&#o&+4H7rUR&)POxtSrf$}E+`r$lg@Ry; z77cS5Lly4!g9CoaV9sUl-6!LMfXdXlZdkm{e$8IAAYU24J~ZAXD{?4a$iTZ{C^KN! zP)SG{L<66LH+@k)u{$dUJnC)6n{xDy8JJNT!;I~QtPRQDHkU@|@99MZ|5V@6tG@nZ z%Sq(j>u>2W;Pi_qEN{Y~WL1uRbiTlo{!nwwnxgarY^nvfCH*4UWkR&h;YKB#{u}}~ zfVm^@vtG+Ny)63UpL~3d{*M5#`d+i6?;G&^2Q+w9FUb**=NA>`RQmHD|JZOy*7_Mw zp6z3B*}OO_8{rkE&eDNwouLSD3~#CS^nSVvq6#?U-HY|!1>IY8DsJ?*a4#Sq{qyJa z1+Vg(a${d>iFzIKDqHuArPKeb9|MRO8kh8~uPID2qf1Xg?-4i>LLIh&{+?G4^rsd* z{$$79gHP2%{;d(p8^EArkHU2Bs-m`l1P>XU*D5;S)htBN_YBm6>XivRN$tx2&L6me+6{0a$iuzl!jJIY zy|X~^VQn-%1zrr`ZaBYe9;1^ES>;ayh%q10t#Mrs%icUl-scmGZyykAo>25pKS9SA zc|HF!xQFg%l|u#BCS~aT!d#w@O^>Xt6?;k_;J9rJ;DaMTiXySvZhov;oo8757O$;I z*+*YW_(Z6t*X1L9&DQ_bn{d#E&XvIxZ;=AeZBu?^uK%AOom+@ma`$WV9%9=md34w3 zWwVZu!v&A$xL^w|y?3~L>w%tDk9CgTgdCuZVRx-9btSsgUT`npxGQylK}o@2=GP3d zd<6XCZe7vr2Ce_?n-u=uakE+paGdZ-P6y|oUNjAw8E zo@oz+&m;dX?_=;ssC(7U3(t}NYXBN$`$@Zrz&8f<@^w9|!Z50DJec>G$o>_bvq5> zbKFMdk;Sn0n>Wcj#vC)ldR*~2OrjW43+UHW(#MYEY>jn0RHa)RFMLey zqB-U)Z14O#9ak_9F)+oo=nDBPqjqes5p6|FvgBrNZ^M=TWWpkH8F0B-(AbR1^nAw9GkfvzH zjv!yZw!pW5zDrET>0QX@n2wAcex^b?bz=5}hxh;t1n^>MXC-F96)HV6;FHc$OE6!s z(9mSsie%Z0+)1@naW+B=!s~l&t4>PX@qnp(>NYa?N=0Muoxxj@J#DZF>iUSPH}$Ge z^66Pp`BqH63Fvo=oIRXIR&ed_@ejeUh@&pV)F(6B1!t9;6Cl3V6CH?{zywnIZg zn^Z7woN4*lTzMihO+F@yv0A)=5s+M?l)r$=*HNI zq647vi*RGo4xTb!VJXNftnFIYMJSWi359KtndCNEn-6N`f; z>jFE1-yinaL!2f7?Em(kU2q>tK>Zj@J1!WQyQHUL3;+3NmSnNI@kDQC_cEnZa%@8v zqOU*~beqU{M4mj_oczl?&aQxYFbZeqjoPXRaNW=^^Jo$#iBZZ z%3+Db@|hjA3!5e~OjRdn*!J0*aF$5Agoo9*26qz3ZluOo)^IY`#P-MU?>*!~fuL^g zyc*w}uVq{-ko`DqVtgUD-j9|D6DU#T=)#E8o4@d2+s> z!!umIY<1cl4JmI7t(!j7>qM_7``ODTdIkeH<#m#|AmOY#fOu$I^Cw7D=olEp7)o zAKo*->C^Y{X9PzTIDFP)IL{or)gIGIKuh56|*@rwx9+~2^ztaLdX}4wx8qV zmulv2&QCD)o-@4mBg-2LUv@_f&wes@&IY={A4_mGK_^Ozo&h(zCPn`YvoUL};TD`n zneq7#^xs8)NPg$?wg_0PoPX4hbPxAgBAg@P=@~n6wo^&7N4G8Z7B;Xot#LDliEY2T z&q#3y;wWssoq6<}eh9w8WCr@+M(!?LiR{CZzJ%;6oPjs(3wUF`LchrBVKP-kENGi< z*1Y^$8GX zzTFhl^UlWgN?lM2Rb-T4ci(|}**!u3hI}~j!SJ7c_60N!KUn=7;-1YzRDM@a(L~#! z6HKn82)nqRs@!?}kDt{A1NWGY@)^1gp>db}*f(#t6exA7%=^i+F#>0Dp&vdE>TyPkUN$IafV5p=E}U8$ zt>?wfw8YE_Klmr(q(0?>{|V||sgv`W7901JQ(rx~1oi_v)kZWjRvBU8_ociqhg%zF z0p~fh)npO1~MCLkQ}Z zWbRPomgTjiM(UEp1nNr=D8bLemC?xkY7aE76uJc+xrcUCoQf~iN|QXCZ_L=}bu(j| z+*A@XZ>4tc0RC=qSRgX~>Vmqm*)DFNlVKi`Wi}~> z{tDroU|<@P*H-pE!p+>7z%xYP^Ntp92jOJ-y@r}YXNMOKcs7;r+%nOi)iH-T5xgI+ zmCN<>LHVtPi;nCks{U9!QnqYh(^f zrTYr!i>ezHdI{#J-=b^6HT{4(tB@lL_tv})u(fbRI?;cx5(8U&C$|qloSsUlS`_>8 znBrV!2L*JH^iwV5E6N43KF}zI+inRBmyGS-r2-l{CsQ$hbFMR*j#bLSzl0V%oN#I_ zBGH%s^o^z@M;|sV1z*Fx!P9%luN-K)A3g9La&7~uQjEA2Y(AegM~8+ZpZKql;2ixE zRC!`FRHwB-MRVm$g9z&Qfh#+sNP&#KC?zc84dlltIQm1o@8ED7otUx8;bphc`TC-` zISbl^#2Kiynwhy_6(o`=6~n8bpAhGUE*+69TE3+!AI_^=9V)G8kW%Yeld{?W_9g=r zHM6je?Y=>1lV7o83o|pqmQW$Jr|`axJLH0XC5x;>LV|t^3Ri7rZ_#rC)4qt;1#O#8 zSmbUAbtmkYCGC)mD%iqO0iRx-m;-g4Lp_qkE#Hk3nCK?F@!AXvdLG!|2dr)BTAS7V z1ZQ9A+7X;2T}Dcou&tOaOV7|9QYi21@$Xp0VxS3Gt4*9 zFqqn6J8m{U-@dBA(@;StMgTX{rY_Pz$=%3|Yyy4`c*K|Voy$3kws!`#CL?MB5p1rV zvzWw=Y<~HVKO>RpMMo7ri4|D_*#`1zu<#@_&~bf4ca~U5Hk>L9o*~H`5VKwM&UiJz zx!kADq2h~82l!|Ez8soyE{9PTc`r=tZ-Sw-%;)E!sRU{++pBO_O75p{fN*zfEkfQM zq)JKPTVj=~K_3|Q@yLR@-`W%Yyop4z&!hCz?ct2X_^3%54NioZBbF~@f1Ym(WDV)e z`q`uYl|I$h0Y^njg8^hu*^>2Gg$YO(<+}=48kXco^gsb?ro$TEhBm|Zb|1_7{C{~< z2zcMYXLK9m;5@nOCT@3U=qaoV!gY&w0~4MNGY|ef^EcMt>a-J*;W?^j<%orPEm#SFTdJQ)zFfynO->K}}e@hKH7!M&~~o}$7Ysf5@|8@&H=vFT|C zM{&kb51tI%P4s@KoR`USy&|uOCSz|CNeuLv=1}AEVGhp2mZWms1T=ZqkjEye^nuCv zN=BUd0bK8Bcudt%6dhkT>2`YHXI@AX@2*pUiXpcc&Fd+NiSLxYe45`g`QH8lI$##$sd zru_Fm;<PFyT)r07UO0z3MFtFS!cYuPN;|rbka36h+}u?Pr~_xZl8)PpbV{~q z1bOBV$#!H7&ofmHK>w%Ct+>5qhW6H58nnGKKuw)L01tp6x=-Mrh|Au8z?L zy@q1`B>!kn|J4uHvK1qmCGGF^B-*2$dXJa+BI-otc zZ{zcmDkq0>N0%+^!3+u9#-6#(Pu>tK=WBS+$Lw9X^*)@F@>u+fi&OVLOB?-3RD)* z&)2t2kGXRu2pBGSbA}z7SgGLe0j3R+)KyrBFwF;#E2Z-(m0X#eAb#D#)7e$K>ahZE zK>`jia2f?0dPQ}r^`Xlh<}uW0$i7w;ZLfohDBLG~1Kj%neN;S{%bH0hoZpvnI}b+Q zw&YrZvAHjI*(~d^HxTzGxopVg6`h)#C3jMOVwMcB6)d7YMe9rqrstRQJ8SQZSUEif z+ZG4W)n_^mNxe$pzx$(-cce-t^9(!-oxU@#sdKDG8thldb{eoG6WHG3jNngtXAaJ! z621g+cFjaXUg&kwx;$`Jy~DL*Ra<~7WekEB^g^h%w8HL zpo!w`TGoyOqZI0_@_U7WE5#e&p#^iUXo$wPh>p`sTj|e`tQ8FXg72dP95F zZ5qO08%OVwG1*s}0-wjsZ8p>-R?$XhgcK~{t;Sc-w}(enNq=C8i}MTgn|<((=B|^O zS6A);$qi?ino{_#R5ajh)=PINpL$2k4K93JT}^R09Jc z6IGgvery73s+yvKhP${_8e~c72~R!TZi{0%&rWRYA`>w3NJ_`aUv|{QE$N4$)`DLt_DMuj1vvD?U#8dS zt2zlz=oXN*g|#tZ@_{B9@Vv25E1D2+=-Qcfu)_qwrqW!p$B}G})pfSEb{>g%7du0! z=YdaULWs$X-Dpd+G=L`S)_%@kiq1c+&3Csh4`*+f4 zD1lc1_U6T!5zkO>CVfopi)s`;1$+Z~FN4cBwBHf)wdniQOUMZ76UCf@%dmfK%6O4|a}Uj?y@F>4wQsZw zIr5whJkmgf)fF;kE-Pd$lUcU4md;}#SwkBpO+j2%&43*V$I?X|I8i|ysC^|I< zYZB6M1DOosQysN{ZRy~JR&8pS)kbhX1MvF-g!49;IcqJ(G?nunrm8?=e^@+eVhXrw z0aYwr1U+x)QJvJUXoq-m@__+i0>*7fj&j~dv5(E`aF@^9jnM;CaPG&oNJWj9kkzz{ zn$)1{Xs%Pz3>%z=wPKDi4j%RS`I(Vyjv>Xj_8U&}BNKZtKec)WR&VV+0pv`Lt$ic5 zQiJ>pqj&zTfelVM)CovRAg|Z5LsO{(PuK()aN*2@X=i>wf^!XM(NSAGF;pz++W=;g zBNp^4g{&TJ>X7W%q5s4LvxL)r={72*A6<+v`Q-IoP?*B`2Trt$3X%fH@NXHlNBH11 z8F_Pa*ioNzrp`8d0S439*<{eyN3-Ms!@Y6I?|y0y6^9qTQ1sGGjjcreeU-Sc2B;Ls zQvkeW=gyF{*J2q)fM3lGo`QR@HrFulO>j8ZWuF4ZLkR4)%b1g9QEf{I$I zj@hj{s;8Rh0scZ^4v@n>-bBHBUBZK0v7$h<@%MQr88Z8HRzTOwa_Y?Al+XG1h=`jP zgQ_^Y()y~{{E}bkBC|J?`XZ5`H--09UWbbF?Tmev$m)UJTCx?pqTUMz?7kfp{rrjY zbm~I(s79<(E~_UrV6c8;_cXB_YsY+ta6JY-!C2p%CG$}OW|_Yw%Afo|SNYCZLlzsH zNh#Bnw{?j9*#g#bd1^7{+}(N7?5bCGTh8#X6X3 z*x}VtGAqD|EXC0&rz+LtcIs0=pEu^*8Nr)9f)DEl=$_j~L#q2!lwSco$vzm4r`0h#tcQKOKc?Mcd_whWh6=rDSe34uNcVLO94)6pp zmyW|17Usy!JYf^g`q&aXasf}r3+oWRbbTzHsdY>@Sgs{a(B$A#@-_XKZrj*}-EQp8 zALDzdOCy+5V5lti;n?r9fKNh4GC+Gru@=>iuHciWk&y9>7%1cdEhDa;Bs+#TFEb?s z4mg~lU(LP&s%d{>D;@R)Z%T$~%zo7g{@y7JgGo9-v40UxGXXk~M|BQadhWXuZ(j-&oEU>)D_RiObb<7Xup)T=n)nDHn7F+>7XNWTdbHVnbl{#$ZNPtW$Bx8EaVkfp=Rhq@{ zd9&o+dJM!&t`+Nm$LRt=S5RR*|Ia_v9D8Gb^FWit9M6;N$LzM6F5TIV|SW;ySqTPU;*z8Ne~~Bn;|PmYP$F-7n!f zoHsqlVsi6|aQUqVzeOGShgu}Z1Q>c%%#KZ%?)YLUN8ol(U-VN3U0F0TryArfZ)bip zC>})kJTQR80+Z`;4*sR>hyh3L8tb3drpXZf!559S%jxZ%%nU9J=>!jscQzD;c_L% z#zsfxx&uZ)x78IiRT)4_N9v~r5IK0;pX#9}7;-nKz%XM+?lhzYc0|}f(sy@AIFo9P zxCG|z1=dh{%`W_3H8?Mo0%v06!)bGmga&J70@dOOzUM5v@nZkcrS?wc{ZS~A=Lno1 z=``UnoXK$A%I?M$g1HKBseEJ4$`cmTy(N>w8MFxDq+`XP8xZ9Tr!^94HjxY7zj0<* zY{64Ff_+iWy}Dts7Tdj4swU^yIAN~D%qCHaJ(;FT@eDW~)L0ELG}CFat+?i2;G@4X z;t)1FtC-?64oLL`{DTq9g*RP{cJ{QO(Tfc@Ia;29=blgPRk?;fXR0Um*Wg>8(3f_r zzN#k{FxC$IxFBcjBe9<45_x2#a&O}FiHNm=Hi$pR-d+W*4OGmi5zRve7_xVO`16z# zMmb9f@SUQ&GD;|!=KF#MPv#^WX>dY(#U2)Yi{Y?by3q)G@-xoZlIICrJsy-G)l#AZsUlv#+lq=e^`QdN{K^Y{B$x4QMcpI zh(XalIGjgaOkqlgK<{P6&6=GqlmU2t+3dDpw`k zHqh~xGnS^$wP+GnhE8Ft!Thnl4;3`i!NW)2g!58Nu3RBqMDNePSrXvXz;CiwZvPy$ zo20J-8sx%$&1OO|WP0q*R3+z`oj(U`Wa$7tlZ+ZTcP`ZF6!7|JQw!D@NhvjY^&uao zlRPHRs!~r4>`)tUkOGk#54hUrOBVirhEE5r$neeF;T%x6+H+SaFuC!k-7?ubaq`W3 zd%ng?2F|xPf{eW&f+a!)zO8=fRvqvKR5I#CYpL%73Npo0z6UJy5COllN+m&DN|7& zG)sv1x9IltlOuK`ROM0v@Qy{A9u$#=;)pBpFZPNtsePur~%U!W!WG zGsJ*?(HVZnd}?rMjCF|A$tVI%l70-aGr%wQHse~M27V0XiPBtYQ}sooI;E!s zI$;g?KYr+b(8P+UFEmad59RxuW0tLiX#u!C{!~jQf(k@*f&UBr0EyxXJ5Qu%iYcqD z9pJS<=0d^52ah8|vZml)+Bcyd(XaGdz+a|pKX@=u0Pg~#6_b zDC|}HR`5p=ush-RKWQ=H>aD#XN;|Y(!mW=($Y>?$`Wf)mU_KSAA2lBCCvGIPx1tRC z(@eH!P)F}|*gLN8!k+cZd7cA@#}g>*mot|Bcif0J;8u8sd5?4Ni0a6a&R?TG@HIK$ z`9fxDwt3V0F} z_(s*t0=7jyu*d#D1=dobv^>ihcSL6yWR$EP_jRW&nRM zm%S+?SUvCOQnmo+IlogUAgkP`?}};0=hWRt-yk=F#~?&3K%UP7Ixz%Oq)*J)85M|K z2Eb42t|KY>Mb#O8WY!hT_1Y-pnPoD?qxJv{!3TJXf+{s@ zT`X}mw5HCgk{#>;e<{a*|AWQlyA&o%?mPuADFb3jfJ&-~czli%?DOGQXCFM$2gpYd z4Zr`~0_NO|pplL;Q2BIIT|$7tv`V0)qhz8IvNDDc0d{pS+yjQAn0*%J{*+K0ZlG#g zK=zOE*XnBqrycHO99*;;Ds0Sue-O<>2%DHakk2T;_mpn@wN=NFb z9YrF<>Cd*DUL_lM)Smob^1VAOr*6OAm3JPOUI(#HYrws|QMsu{HSne&hroQ2f*vS3 zhCQ7cz^k^DPBQz^!g%{O2sgk#0ffbg)oJ>qi|nm?Sw%)jg$8)-7$%`E%sUNE2YyPo zw7^xU+S)@MDjKLeqy)G?K6C@7T&&PkgL$Zq!x?j@#)yM?2+ZqUV48ck-KxOsoZS?c z>4sULXLf^n?5jh=*yvX?A6RMj(3}S!Ss}%UoW&H7RxJCM|M*k-qVFr1ni%5}_D1B_ z)e6b_5ufz0(KGxV*hSUF7&gc=JA*V^L&o=n=(OY#p&61sifoY~6|lEqB05cW-m&;7-u{bPg^7G#a+!^sBvgVqfk=7F3u4 z@VEUVe8%WZ7`ast^wBz(Y;*Ac*MWgZ#|gNGFrhcnSLKBL*2RHb+?@eecX0)sR1UsF zl+@tnmk1%8KU1!#-FF3bkNK1bObP4T{NRkfPg;U$aT8wTdrH_I7ZfO&bW1YKS+Y+R z^M%>LT>n&n2G3I9EOPqcJFb|C31@vWMF*G_(FFR|ubN~l3G8`yK*wKg3C!ErqrYuv zH7a3F*j(qk5EJAL%3I@=@HHqtD8-{(IzO7gSNlJIpuah!Iq9zyVx2zfMh;Gu@Eg<~ zf|ek_1)PC5cL5Ffho4L-8>#SQFd)5Q&lOdut3V064S^5D4uM}yTG-rG^q{_{*#}jq zX6D%JL3X)ylP7x%8Cw~4IPDf){icSznQDE#3=gQ|IQ8W=VNDUMBW;S z#S_Aqx27#PgF<#+q=RHYX}C;Z%0VMC3up6(AcPG?(G}b4WG!iq;Z-ArGjb2AO29ko zID#Dp8VP#Y(b{UWNcfIl`!goCpXsoZZ8)#tI3bL{zL;`Atb->ro3m2yf_2VQsB^j> zI;=0EebuuzmZjV3V2EZ2V)icCEcWt-9Ft%yF!Mn zvhc33*vaQb&YwX$iRRV7=(Pg|kS_0-4;j#jl-PbKAx9N_zSWQA2mumjEu1~~+1Rza zbm@-V&3TbsslagYCv;@KP?!@z&jvoQ=BU8lmvm?@3}7)K=p*&L)zcMb+=&|OR3s2r z@|~(U3dDiSWZ3@R*jSIOQV)%naAXe3K{&vBALjUe=nvg1AL@2S41dLA`x5$$CA-#^ z>`=Q3Wx|6~``GykvMfv44iDy9=v-~mQ_Fm~t0Q?d7+n~Ae44yx>PIWl(8 zCoArV8RfFRaIr^?feyF0+9BXoouM9ts%{=o2KM8HC#WY;^U5CdI07{<#x>}htLIWN zL5XQT`Xl`8?-;0anp62LKbQ#<7n@8BfXA+@f;}G5s#owzl@et zDE7dRn&|H_Z0%;o!S+A?VC~&0{?bJn?tuSX4K%2KvhXa^tpR&SzGIZ;Cw6Z_Ee)Tw z34rOP&V4bV1u|opYJs{*{SHoBA^s=8_Ey_ivc2 zO5jp7P_YKr{=)6IKeDj}e^m#6+m=gZTR6Wfr_l|wYOV@Wy-T+l0M>CVMo6lP9VD2z0^Z`|iMre+qA~ti3i{KtVn+BUWJVy8|MB`a>i_-ktcpFF&X< zooYREL@vmb1$4X_xpPqB3@tAB+QA&Cq1~tU+K`=rHC1DKh{Ja3<6(mN~ZL;{8a7y1p-eMJYZoD9CXp6?il`PYy&QtWKswnQ2<)T zj;dm=lsy#`qAGkJP*z+s3cj{5rBtRT_LL9HZ|E)(GQhK~TMg#>(X{D1I1-_zj!DlR zc(6ZJlYnW55KdQ)7|K*KemftkStLi0EzOz5F+F@@p|>w@yn{XVV1tg%r{e^s8V*ih z$+fj&l|mp7)t4rM{&O5aU!K0UC|DK|B^D~g=1|O|q5f12iDCgy#i!lSr7e%&<wcbx90aa4?GPz(fLg3hTXK`G0hRdlw-K!lpHhZzX-x(F>&Ic7slNYx@+lt zB(ROt5HUQtT4Io+kVW&7aQd*FxP9oyaiK78!;!VKi4UKyLvNG-zbAUs6{Bw*^40?3vr}2W}n8$oz&fDLB zCk5Y6-Dtpd%KAk7`_D-n4!V)C{oY^T2yhUnS4*gURJoj5VzD#<2?rbyaP4}ofo_NF z*`6V^r~FzI(}@bRft0AC0lu}}RT?M50yQ&yv?G-wMek+c=nY*i)Gf&qBIVleH!yed z04vWy6~pr3(D>N~y^${`JOh128-JhPblYkj0+*+gl0&!m2;D@ou~$j)T1(B+kPHe~ zTkOg#>l_$xKnQlueTDHT0F@j}i$S-6a4ADxzs}()HnIgA9t7X{-vTXoP^}9{BZ4v0&z>Bv#*b@rpv6ceS-MK=J%b5*0jUo9wp#^9$ z&TE%OlFJg}@@G(O5D9bV2)+rRv)y-nI?RD`;0HKTBsbW34NuLhz6-=kq>>7JMON{` zWFI{+3u}?h7(kN@j_~C*@WHtd=JD#H?B$Tjv>B1BtNhBHhGKF=GIWuEcZNvY=rH~E zNA)7xormfJ@FYpGDPw<3UUe}XkiC9PIb$DC9jcc|u7GdXY+dM!Bkb= zxb3OziS?qwuBh|D%!><29kKHiewuzb-yk@(#*Mkig-CYZ(+TC#!H@#LGOck4`vvVj zoY>8I);zU`?CLzFwEJotQQ!QC0B1JfO($2L;EV~+!~}4O4BW-NeKetv2Mo|RRPdYw zm^8IClVF|zSnC;4(4TkD-p&`oSt@JP0gg6%(mC@P^2)C@DDgt25($P#A{Z-c>wF;x zmP54ZX%I(g&j$Pos<9ukjlWYR8x-u!?QEI1fi+1iDF2bYDuE^$~V|ZKmCxm92d?X(4aJ z3=+L;mfg9kZ3f@n~dt<{c5-GTh zKqmpH^9y?)oK$eEB9|86vlT{BqQDHIm)v?2k1|6ll&?0`s3&&E^j7=gikPIFdhL#( zl8~@?9@{gMHsCF+O;y;TWV8 zKZeWY?f{FA0d|)f>qs3=XIro%S7tGcZtTQo`0R^dMY6}P_zXEw4tH`=sFcfx*ttr6 z52C7ES4sYgQkM#AtG5R|-LKz!{ko_7z1Q6izQcJnyVhMzbNU!&!LUo4Wv!OM9htIU z;LX)(x3dt_*gV%?Nz5@A_nfl=*7G##Iy2lvZXI)P5iej3bBGesWbH)PCpSgw7M40L=v?^O`Ypk zbT5Ou_H=iD)hywnl5#(sC@1*zVs}cwJ>I>5%P&V2A0NpD^Zq8Ud55c=YM$%)Fk7f3 zcr7sWrQs38MND0G6=L=Yv)Y0GkhaKG2fEG=%0@W3qjPmf%LQ0n-q7nzm|biJnV^Y% zygc@etE`6mEHgnSkPSI?Ddc#Y&?CzDmgR!OgjrPdF3yWGIl(OjdA}SO;6{e$w*-~r>haP)SObYeSPfj>6DWjt%wWr&J0cxPvd-r zK`_T@e6OMIRHu{;rmVwruEVRPEMho*?kn?a@i6o%~5Teey9(6^`5I>jn7O;bcTgGfR#Pafn zz;|m2=qZ&NQ|bgW(d;@~W!E}BtlMj?9XUR~&eRI9_iE!D`yHlGPfX-b_B=*Rht{E` zat%B;Juz)vp2S0;b@Shr9Q@8rQ`}`LRq)r&xVAU9>A`YQj^yk zQr+drA?DX4%{6QL`@w8Qk9T1&NUt)p0_U3Qszcnbz;9?+k>-N7&P-#U$3$;3ALL_s zjq|G*hq+S1uUs{p>#T7>EtsE1tz5F)#CM{#A%rC8mdpwGM@3ozPLn4S@CS4)aS>Ov z0Dr@@doaUrX;=)+=wN3T=TM}fXL0=O8Xrwhrs2~m^XXclo(T^do#kPLtwGO>S<-+@ z#xvn=ITNv?yibMykTRFY-RZfS@?4^vXA_wJq_Hl{28XjQ++dWeVwFQy{Z$oqF?=7f ze}s=_8!gy)?KAKQXvnyK3a8K%&2v)Jfxl0)#z$Gq4LRP0v(lMhQ}25jtfzaiWP=SS z$zLfb=;=royOOh2h0BNdvx88M&&~{vCql{@Ho^o3Q$h$HX3(-0u%fZqn5NtjXe$vKWy_!E) zWa>>#jy?XY5zxsm2In^zI0gI{N;lk^a^ki-4?lMF>u8_NR9o=`t1dy`79RwplQQUS zae7_QUHJOw8|h#tEW0q)d?9%*!Mc_lj*AznO2hGRb5h8~IaK2uPOE18jpQFDwp-A8|X)@?aP-lXqW4s;fhJ@^}-hj`$SpSP&dMv zc?mWwMR(1aA*~FJX~hZ18WS<*T(!=f_M&onCx zmxp&pW;%iWW-KSy80<$gd|7CgbKKCcLX*{x4y!IL#~M*}Qm8bG_B4A%CNu~^Pl$T$ zpv&9ZA>-7V!fbP^a9UlF8(NgDCH+h+zoX?gr}ME~mEjoAa7L>rkpAZLn2j!Hd@}TP znx2FIUEa@(Nzfy?O2(ABD$M40CLwS4ln2os{0^HHfotO4sh+pz;zGuBCp?TMvG14XnwTeM zV)6=$o$#(WANcYXtng?KC3X5JIS2uZfym7D=h3LY(Rs*X0n)w2vKD^ zueXBQ68xmjN;>-6jDE_6lfV*j#=};fdVyDWz}FCTXK`9z2Kz2rm!{E1V5<ZAJTj7j(caPpi~qn;T4U!1W+s1CJEQ zpLKXyGrUa?ALk`ucK7vWgR1qxBVsFsGwnJMiwt5f zGsz<3&tW}~U1M;Ll}mSd6Yy6S*cRv10Yhxb9sb~L|DMgz=-hGW-S@Y#S&E`Jiz^6vX={M;Q{ABYX*Hmqy;Oc4xb9wlCact z_h$w>Wp0L%Vm4FK^--qv)3Z!7lBrk9zPmYY!r^EKmag6rx=T?uBw>79cLG>h=h zE@0ojP;syiQjHFv^BB;1MX;kbgUK_j&Q{YArPOao4I?7} z8BJ7Vv~nI6i$3qbOU!ju0`^k}eIw5^#SHE*faRi`e?5>Ax!kaiJ)C;N*a#nMZLCFYe z@aD?<*a+-7W%HC2>dms6#1e44I@S|J`Sz_AjSEOoFeLke>^)3(bt zgS?&#Wx{;C>*aAWl!Viqvfg~OhyA)e_}?}w{gQDKquopb-XXAOv%Fsjw#pLrZ7NY4 z^JdwX(R0`*3SLzbni(7Vhc#izoWpolHO}?nduwh;OTC~LZbI{5LvP*Ek#pK~cUG}i zbWX-@C>Q*~oKUYafc{T|JZkkmuSBxNLd3vKEz#)H*rRIxe5A)WSE04>Ni*_F&fD{A zK{KFw9QYZwV6{klg{{d5w1H)PMwsE(ZB>SMQ!?<#6-vmc4kwt10{e;_&O>flchi@c z;9>=gAt(8rMi080#3~3P^&r8$N4w$(L#74rn+qUjUerRCsqh1$`M?8XA?evuYiUT&IF%$aVuivQ3wvz z_ii9qRF2-=f|&4---!udiQpmd_aO~+QhkIw@z*9k5l)nc(g_aXOyvk3@<_yg%8RlR zU=waU+Jnl`Z^C_4p714j#Ahl?c_{#v@o}V49Untp;7Bysw;@Km5p5FHNpOfJz+edf z-@TN63C9t>fW-j!5v`Q>b_7ZT>=7QomEbYJ!3I3#_uh$#h7oPZs}L;&lW;>mhMsRm zpghE5k{g0c^buUpLhV5H6P`BZL#*sU3_9rjh#thujd%ur3g{$wL=%I&%smL8iP?>G z!V7`gi0GGy9(qUVfRRNzNr*={QdzpeR*q~{IE0xDH z;Y;)wpFlcd`aR+a!KHdB4`^Ws7T!}CdbWw~cX>eXiC*xOV2t44H`PB%r+TSAiV07G zL2wB^<)=E4cT|pIf=~GosD1@)LwQE+0~w*RL=z9$VfG;)jd(@)N(7(e2WceN%)NO2 z9fb65ru8YjM|+NVPWb*d!d|3NpQ5%Sep4IanRys7(RdwVwEd_Kl7TFOgx`c8+SI-Y z?+GUIjmi@4gcI^Az$5VohyhPQ+Vay#7f>H?8u9y*Y$-P&9c@T7G9uy!5g->fbnx^9+fBfpf7V`H`70bbnuqyCAx_wqJ<$I z;CUq5gg%(xMmSTx8<3Cq0s2R2;2EV+If6;NQ@{t}t&u}I(L}rkPQ)Ju{9uUJXx|YX zs6(PQ06&QLls1wj;5y1nvO#T1{J$PCct|)?|7VbQ#7BY)I1G*Vln!_#CkkYMLEAEr zP3l8bCj)+MeHOn#gK|Ft@$eE~Y^sy;fp&sB;uG?KnsKCQNN)!CYhl&CK;0d` zIqGB7781rF>RbP(`#;I$d({8Ai&5(~>uu|!;`OQP7xr2SQNrKxg_jmSD7LNB;-6XH zO*K=0+vdf;Z-2mgdGqasmQ_uCy!{ucYsKT%FWcX4|5jVG9ci`|9)E^-&2Pfd#ZQ=e>q*!p8jvlMHG^`V7drQWp0c5M}pY(~Xz zq+SxwSk;AX))wnJtK1&jwOd?H&0V}s{7vig;E7@u=rUqCB{-eGK=CN@t5r-@hS1&ihr{Cs^t@BE}pWEh|!B*6}RuY(|SadtrxAo zOZ{~!kb2p=V0jk8?Y-7=>UlAhdQ7~-T1mYvPFOdIkBNEfsJPwoEeum16;E!?Zf;l~ zu|jRXsEXU#0r8-CQf!O=RQ#G412wnf|63`|`lKQiGSU`*#4~et@gjSUQAU)zvbWcsQ81;6Pu>^pBBuN zBVMo~?I%+YFI24kBAfbI`(o;|)^AupS>UW2+sE69)P(g#>!a;wHt!OD+Dd(&$@ zE{>;OY5%2ord*HcH^uUPvQ zK4@{)XRSc$bo=UE->_Z~ZShR%ed6DVThMab#H{!!t7#?Mle?}FZR_(Nem%9{YKofp z&6J+{PU=3fB!1cQh<|0JFK$?i)|Z6aMXP;_rMF}4ZSB9X{+XCfS>pGsKNDXwkBbZ9 zIq~Q1+uHv*^=kWTqFa2a{q58f<~6As#2>Z4V*SzPhf<%muCZoBC-u)oDfM+LY;C5d zK>dfs4QqF5(h8-NcE5e?zqlKBd#Ce`|PsY*L3npRER1DP!> zoU{J8Jz@Qa%@uI&s`gv$SK6)3C&Wj@tHh1=;f0ThSBT+V-?viMmDWqv8`e|pQ`Ys? z&&B5!rmR!e&DL7#SE;|W#1tdeEgNnBMX}SquxVJgS~cqxu_FGhI3-5KE5+XwZ(5iT zpRiQ%7gkcdTl{S?Cc4{e;;Gb@U3+#tE0z}g;#=Yg>l5Nu@k^|Y-JZ##h32q&y3#q;ew)+?Kx33%(S_E)p2QZ=|jh4Tul##9ehT5VC*OWu&82Bf$W3k=|ry4#BETe4B_I6UjZ{#iBH^rY9*6RssQV9yQ11&uqa>%v*H znkg2_t|bXKqq7ah(`ARNO1(91R{~67Tv2h`8UIh)h^Znem+ zb>Sza;{=W@m#)J8R)>c1%0k1yO%(aE3%V+GQhr}HqO1yaW5cL-HtZ7PfySr>BdO+tpwu zzsi^aXN~hFy|`}=_ZahRcd}450`RBXF0;yb(#QGvohojnvdaQ)uPIbOi$CXeEwfX( zHMInb!P!>BE-95{5xX!wId5w+U1wIbAalI6=3>9Qr4UT4Wop^UmS51hYTnmfQYzAl zP)<+Eu&}pu^{fD2hym`$f!=aF=jp=7S(;*egQ8iHuv>dD&QuG_15KN9p5vE0MYaS_ z$140ab{gyYc4t*v?s?guP-7~|nlaVnj4Alwm7yT2n#S>cM! zt<8F~-t%@m+3M}{N0;{hV*dfpe0A@g^Cx%AZhhta&SO{K^5xvYmp|95+#9;X?Rz4A zU@W)r{#oYxZ~e{}vIdO8|7HHs_>n`IeeU~w`yMzDyvy_AtLLlRq{HgKIpX}ZCi970A^Tjl`H+%TlzTLR_$Oq5AQNQ8T+gE3Dx$ntO^V@FU z>zzOJ;7!phPduFTA1s%jELL6{#$#;d;JmZn_|$&amOJWO<)ib(YY#n8-m_l$=Hh|d z<`21F+j8NNJug3STh4vIC-c?ETL3TlZ&Qc;AA1e*T;Lwa*=X zNUmIeOqn`-;FdGzA6`ZWfN-cL!t6pZ4YM$QQ+fZZw{(itx8siBD7Piv^VFFjK_t>KTp zlZVz@qq3BapwOC-^aNCv*3w8D{ib{3#tnv@^S<*j3eU|bM z^jVkn*=WE2i~1~*q09R0OZ^VtIMR=kK1+HJ^;tGxzeoD4|84)jtj|WfUb1Ih)@Ng! jA>B2;Bh>#d>$AZR^#9BH?92M>%lhog`t1Kl_1XUe>BkSX literal 0 HcmV?d00001 diff --git a/tests/contract/fixtures/make_basalt_ple_fixture.py b/tests/contract/fixtures/make_basalt_ple_fixture.py new file mode 100644 index 00000000..47e3c6b9 --- /dev/null +++ b/tests/contract/fixtures/make_basalt_ple_fixture.py @@ -0,0 +1,81 @@ +"""Write ``basalt_ple.safetensors``, the committed real-weight slices of the n-gram (PLE) block's tests +(tests/basalt_ple_ref.py), or fetch the block's two full byte ranges, by HTTP range reads of the official pack at +make_basalt_fixture.py's pinned revision (the 65 GB file is never downloaded): + + python tests/contract/fixtures/make_basalt_ple_fixture.py # basalt_ple.safetensors + python tests/contract/fixtures/make_basalt_ple_fixture.py --full DIR # the two full ranges, into DIR + +The pack's own tables (``meta``, ``dense.index``) locate blk.1's six PLE tensors, refused unless they lie where +tests/basalt_ple_ref.py's TENSORS (spec T§5) says. The slices are key row 0 (one Q2_0 row, 720 B), the first +``ROW_BYTES`` of the five dense rows and of their GGUF twins, and the whole dense conv1d; the metadata records where the +tables put each. ``--full DIR`` writes each name space's range of RANGES, the six GGUF tensors and the five dense rows, +for $BASALT_PLE_FIXTURE. +""" + +import argparse +import json +import sys +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 BasaltFile # noqa: E402 +from monolith.formats.gguf import ggml_row_bytes # noqa: E402 +from monolith.formats.safetensors_reader import write_safetensors # noqa: E402 +from tests.basalt_ple_ref import FIXTURE, RANGES, TENSORS # noqa: E402 +from tests.contract.fixtures.make_basalt_fixture import FILE, REPO, REVISION, URL, HttpRange # noqa: E402 + +ROW_BYTES = 1024 # the head kept of each dense row and of its GGUF twin +KEY, CONV = "blk.1.ple_key.weight", "blk.1.ple_conv1d.weight" + + +def locate(f: BasaltFile) -> list: + """Each TENSORS entry as the pack's tables give it, ``(key, absolute offset, bytes kept, record)`` per slice.""" + rows, base = {r.name: r for r in f.dense_index().rows}, f.section("dense").offset + found = [] + for name, want in TENSORS.items(): + g, r = f.tensor(name), rows[name] + dense = None if r.in_gguf else base + r.src_off + got = (g.type_id, tuple(g.ne), g.nbytes, g.offset, r.kind, dense) + row_ok = dense is None or ((r.ne0, r.ne1), r.src_bytes) == ((want.ne + (0,))[:2], want.nbytes) + if got != tuple(want) or not row_ok: + raise SystemExit(f"{name}: the pack's tables put it at {got} (dense row ne {r.ne0} {r.ne1}, {r.src_bytes} " + f"bytes), TENSORS at {tuple(want)}") + keep = ggml_row_bytes(g.type_id, g.ne[0]) if name == KEY else ROW_BYTES + found.append((f"gguf/{name}", g.offset, keep, dict(source="gguf", tensor=name, type_id=g.type_id, + ne=list(g.ne), offset=g.offset, bytes=g.nbytes))) + if dense is not None: + found.append((f"dense/{name}", dense, r.src_bytes if name == CONV else ROW_BYTES, + dict(source="dense", tensor=name, kind=r.kind, ne=[r.ne0, r.ne1], offset=dense, + bytes=r.src_bytes))) + return found + + +def main(argv=None) -> int: + ap = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter) + ap.add_argument("--full", type=Path, metavar="DIR", help="fetch the two full ranges into DIR instead") + args = ap.parse_args(argv) + f = BasaltFile(HttpRange(URL)) + found = locate(f) + if args.full: + args.full.mkdir(parents=True, exist_ok=True) + for name, start, size in RANGES.values(): + path = args.full / name + path.write_bytes(f.data[start:start + size]) + if path.stat().st_size != size: + raise SystemExit(f"{path}: {path.stat().st_size} bytes, not {size}") + print(f"wrote {path} ({size} bytes)") + return 0 + slices = {key: f.data[at:at + keep] for key, at, keep, _ in found} + meta = {"repo": REPO, "revision": REVISION, "file": FILE, "file_bytes": f.file_bytes, + "entries": [dict(key=key, kept=keep, **rec) for key, _, keep, rec in found]} + write_safetensors(FIXTURE, {k: ("U8", np.frombuffer(v, np.uint8)) for k, v in slices.items()}, + {"fixture": json.dumps(meta)}) + print(f"wrote {FIXTURE} ({FIXTURE.stat().st_size} bytes): {len(slices)} slices") + return 0 + + +if __name__ == "__main__": + raise SystemExit(main()) diff --git a/tests/contract/test_basalt_ple_ops.py b/tests/contract/test_basalt_ple_ops.py new file mode 100644 index 00000000..f9fd8afa --- /dev/null +++ b/tests/contract/test_basalt_ple_ops.py @@ -0,0 +1,606 @@ +# SPDX-License-Identifier: MIT +# Copyright (c) 2026 Jesús Gulfo +# adapted from basalt (jesdga95/basalt) tests/core/native_dense_ple_key_test.cpp and src/kernels/ple_parity.cpp +# @ b4c63b55754637f4c72ad53a0f791d425f71eb36 (MIT; third_party/NOTICE): native_dense_ple_key_test's key rows (:62-78) +# and its three cases (:116-171: a BF16 key row, a shape-only one, the index's edge cases) as the key's binding, and +# ple_parity's prelaunch refusals (:215-220, :715-739, :869-891) as the emitter's. +"""basalt's n-gram block on the decode path (monolith/ops/basalt_ple.py) as compiler/emit_basalt.py emits it: the window +op ``basalt_ple_block`` and the commit op ``basalt_ple_commit``, over the pack's six tensors declared as the op contract +gives them, from a synthetic .basalt file that holds them under the pack's names and types (``write_file``). The GPU +side is tests/kernels/test_basalt_ple_program.py. + +- REG ``test_registered_and_covered``: both kinds are ``OpClass.MAP``, each bound to the kernel of its own name, and + the coverage guard passes on the window graph and on the commit graph. +- DISP ``test_dispatches_are_the_builders``: at T = 1 .. 8 the window is 11 T dispatches in the plan's order + (``STAGES``), each with its builder's kernel, grid, threads and params record (the records' fields pinned, + ``LAUNCHES``), its slots and ``writes=``, row r's row bindings at r times their row bytes; no StepState. The commit + is one dispatch, ``basalt_ple_restore`` over the history, the snapshots and the record, no params record and no + StepState, the same at every width as at 8. +- X-PROJ ``test_projections_are_main_ops``: every row's q8_1, key and value dispatches are what main's handlers emit for + a one-column graph on the same tensors, the row's input at r times its row bytes. +- BUF ``test_buffers``: ``hist`` and ``snap`` are states of one size at every width and in the commit's program, the + row I/O T rows, the seven scratch buffers of the plan's sizes, and the six named values in buffers of their own; the + record ``commit`` is a 40-byte host-written buffer of the commit's program only. +- BAR ``test_barriers``: every two dispatches in conflict at buffer granularity, write-after-read included, have a + barrier between them. +- X-REF ``test_refusals``: one case for each refusal of both kinds (``REFUSALS``): a valid op, then the same op with + exactly one defect, refused by that defect's own check (its message). No graph reaches the others, so they have no + case: a misaligned ``hist``, ``snap`` or commit record (states and inputs bind at byte 0 of their own buffers, a + StepState field at a whole word), ``hist`` or ``snap`` sharing a buffer (a state cannot be viewed), and basalt's + overlap (H2) and scratch cases (C2, C7): the emitter binds the history and owns the scratch buffers. +- X-BIND-1 ``test_key_binds_gguf_type42``: the key's shape-only dense row is refused (its bytes are in gguf), and the + block's key binds ``gguf/blk.1.ple_key.weight`` as type 42 ``[10240, 2560]`` at the tensor's bytes, on the + synthetic file and on the pack's own dense.index (its row 46) with the key's gguf record. +- X-BIND-2 ``test_bf16_key_row_is_refused``: with a BF16 dense key row, the gguf key is refused (basalt serves the key + from that row) and so is the row as the key (the port builds no BF16 key arm). +- X-BIND-3 ``test_missing_key_is_refused``: no key in either name space, or a key from a file with no dense.index, + fails naming the key; a dense.index without the key's row keeps the gguf key.""" + +import json +import math +import re +import struct + +import pytest + +from monolith import kernels +from monolith.compiler.coverage import check_coverage +from monolith.compiler.emit import basalt_windows +from monolith.compiler.emit_basalt import GGML_IDS +from monolith.core import DType, Graph +from monolith.core.ir import OpClass +from monolith.core.shapes import T +from monolith.formats.gguf import ggml_row_bytes +from monolith.ops import OPS +from monolith.packs.basalt import BasaltSource +from tests.basalt_ple_ref import D, HIST, KERN, N, T_MAX, TENSORS, committed +from tests.contract.test_basalt_ops import emit, gemv, op, pack, q8_1, spliced, weight +from tests.contract.test_basalt_reader import write_basalt +from tests.contract.test_basalt_windows import PROFILE, real_source + +F32 = DType.F32 +KEY, VALUE, TAPS = "gguf/blk.1.ple_key.weight", "dense/blk.1.ple_value.weight", "dense/blk.1.ple_conv1d.weight" +NORMS = tuple(f"dense/blk.1.ple_norm_{n}.weight" for n in ("key", "query", "conv")) +DENSE_KEY = "dense/blk.1.ple_key.weight" + + +def write_file(path, data, key_row="shape", index=True): + """A .basalt file holding the pack's six n-gram tensors as the pack ships them (tests.basalt_ple_ref.TENSORS; the + pack's dense.index rows 45-50): all six in the gguf section with their ggml types, and in dense.index the key's + shape-only row and the other five as dense rows of their kinds (5 F16, 2 F32, 4 BF16) of the same bytes, each + tensor at the next multiple of 64 of its section. ``data`` maps each tensor's name to its bytes; a tensor without + them is in neither section. The key's other forms (X-BIND): ``key_row="bf16"`` writes its row as zero BF16 bytes of + its shape (kind 4, code_bits 0, basalt's unquantized key row: native_dense_ple_key_test.cpp:62-78), ``None`` no + row; ``index=False`` writes no dense.index.""" + gguf, tensors, dense, rows = bytearray(), {}, bytearray(), [] + for name, t in TENSORS.items(): + ne0, ne1 = (*t.ne, 0)[:2] + blob = data.get(name) + if blob is not None: + assert len(blob) == t.nbytes, name + gguf += bytes(-len(gguf) % 64) + tensors[name] = {"type_id": t.type_id, "shape": list(t.ne), "offset": len(gguf), "bytes": t.nbytes} + gguf += blob + kind = t.kind + if t.dense is None: # the key: its bytes are in gguf + if key_row == "shape": # and a shape only in dense.index + rows.append(f"{name} 0 0 0 0 {len(dense)} 0 {ne0} {ne1} 8 0 32 0 0 0 0 0 0 0") + if key_row != "bf16": + continue + kind, blob = 4, bytes(2 * ne0 * ne1) + if blob is None: + continue + dense += bytes(-len(dense) % 64) + at = len(dense) + rows.append(f"{name} 0 {kind} {at} {len(blob)} {at} {len(blob)} {ne0} {ne1} 0 0 1 0 0 0 0 0 0 0") + dense += blob + meta = {"format": "basalt", "version": 1, "tensors": tensors} + sections = {"meta": json.dumps(meta).encode(), "gguf": bytes(gguf), "dense": bytes(dense)} + if index: + sections["dense.index"] = (f"# dense index v3\n# align 64 pool {len(dense)} tensors {len(rows)}\n" + + "\n".join(rows) + "\n").encode() + path.write_bytes(write_basalt(sections)) + return path + + +def zeros(): + """The six tensors as zero bytes (the planner and the emitter never read them).""" + return {name: bytes(t.nbytes) for name, t in TENSORS.items()} + + +@pytest.fixture(scope="module") +def src(tmp_path_factory): + return BasaltSource(write_file(tmp_path_factory.mktemp("ple") / "ple.basalt", zeros())) + + +# ---- graph builders ---------------------------------------------------------------------------------------------- + +SPECS = { # role: (graph method, name, shape, dtype or format), each value as the op contract declares it + "rows": ("input", "ngram.rows", (T, N), F32), "hidden": ("input", "ngram.hidden", (T, D), F32), + "key": ("weight", KEY, (D, N), "q2_0"), "value": ("const", VALUE, (N, N), DType.BF16), + **{f"norm_{n}": ("const", name, (D,), F32) for n, name in zip(("key", "query", "conv"), NORMS)}, + "taps": ("const", TAPS, (D, KERN), DType.F16), + "hist": ("state", "ngram.hist", (D, HIST), F32), "snap": ("state", "ngram.snap", (T_MAX, D, HIST), F32), + "result": ("value", "ngram.result", (T, D), F32), "normalized": ("value", "ngram.normalized", (T, D), F32), + "commit": ("input", "commit", (2 + T_MAX,), DType.I32), +} +BLOCK_IN = ("rows", "hidden", "key", "value", "norm_key", "norm_query", "norm_conv", "taps", "hist", "snap") + + +def declare(g, role, **change): + """``role``'s value as ``SPECS`` declares it, with ``change``'s ``method``, ``name``, ``shape`` or ``dtype``.""" + spec = dict(zip(("method", "name", "shape", "dtype"), SPECS[role]), **change) + return getattr(g, spec["method"])(spec["name"], spec["shape"], spec["dtype"]) + + +def block(g, **over): + """The window: ``basalt_ple_block`` over the T rows of ``ngram.rows`` and ``ngram.hidden``, with the key, the + value, the three norms and the taps declared as they bind (``gguf/`` a weight, ``dense/`` a constant), and + ``hist`` and ``snap`` one size in every program, the windows' and the commit's, so they are shared by name. + ``over`` replaces a role's value or the ``updates`` (the refusals).""" + ins = [over[r] if r in over else declare(g, r) for r in BLOCK_IN] + outs = [over[r] if r in over else declare(g, r) for r in ("result", "normalized")] + return op(g, "basalt_ple_block", ins, outs, updates=over.get("updates", [ins[8].name, ins[9].name])) + + +def commit(g, **over): + """The commit: ``basalt_ple_commit`` restores ``hist`` from the snapshot that word 1 of the record ``commit`` + names, into a placeholder output; ``over`` as ``block``'s.""" + ins = [over[r] if r in over else declare(g, r) for r in ("hist", "snap", "commit")] + return op(g, "basalt_ple_commit", ins, [g.value("ngram.commit", (1,), DType.U32)], + updates=over.get("updates", [ins[0].name])) + + +def window(src, t): + """The window's graph and its program at T = t.""" + g = Graph("step") + block(g) + return g, emit(g, src, t) + + +def commit_program(src, t): + """The commit's program at T = t.""" + g = Graph("step") + commit(g) + return emit(g, src, t) + + +# ---- registration ------------------------------------------------------------------------------------------------ + +def test_registered_and_covered(): + for build in (block, commit): + g = Graph("step") + kind = build(g).kind + od = OPS.get(kind) + assert od.klass == OpClass.MAP and od.binding_for(PROFILE.key).kernel == kind + assert [o.kind for o in g.ops] == [kind] + check_coverage(g, PROFILE) + + +# ---- the window's dispatches ------------------------------------------------------------------------------------- + +STAGES = [ # the plan's eleven dispatches a row (§3): stage, function, the values in slots 0, 1, ..., writes= + ("q8_1", "native_quantize_q8_1", ("rows", "ple.q8_1"), [1]), + ("key", "basalt_mmvq", (KEY, "ple.q8_1", "ple.key"), [2]), + ("value", "basalt_mmvf", ("rows", VALUE, "ple.value"), [2]), + ("norm_key", "basalt_gr_norm", ("ple.key", NORMS[0], "ple.key_norm"), [2]), + ("norm_query", "basalt_gr_norm", ("hidden", NORMS[1], "normalized"), [2]), + ("gate", "basalt_ple_gate", ("ple.key_norm", "normalized", "ple.gate"), [2]), + ("broadcast", "basalt_ple_broadcast", ("ple.value", "ple.gate", "ple.gated"), [2]), + ("norm_conv", "basalt_gr_norm", ("ple.gated", NORMS[2], "normalized"), [2]), + ("conv", "basalt_ple_conv", ("hist", "normalized", TAPS, "hidden", "ple.gated", "ple.conv", "result"), [5, 6]), + ("advance", "basalt_ple_advance", ("hist", "normalized"), [0]), + ("snapshot", "basalt_ple_snapshot", ("snap", "hist"), [0]), +] +LAUNCHES = { # the plan's launches at every width (§3): macros, (threadgroups, threads), params fields or None + "native_quantize_q8_1": ({}, (10, 256), ("<4I", (2560, 0, 0, 0))), + "basalt_mmvq": ({"MMVQ_TYPE": "42", "NCOLS": "1", "ROWS": "4", "NW": "4"}, (2560, 128), + ("<4I", (2560, 10240, 0, 0))), + "basalt_mmvf": ({"BLOCK": "256", "NT": "1"}, (2560, 256), ("<8I", (2560, 2560, 1, 2560, 2560, 0, 0, 0))), + "basalt_gr_norm": ({"NORM_BLOCK": "1024"}, (4, 1024), ("<4I", (2560, 4, 0x358637BD, 0))), # eps f32(1e-6) + "basalt_ple_gate": ({}, (4, 512), ("<4I", (0x3CA1E89B, 0, 0, 0))), # 1 / sqrt(2560) + "basalt_ple_broadcast": ({}, (40, 256), None), + "basalt_ple_conv": ({}, (40, 256), None), + "basalt_ple_advance": ({}, (40, 256), None), + "basalt_ple_snapshot": ({}, (64, 256), None), + "basalt_ple_restore": ({}, (64, 256), None), # the commit's +} +ROW_BYTES = {"rows": 10240, "hidden": 40960, "result": 40960, "normalized": 40960, "snap": 368640} +SCRATCH = {"ple.q8_1": 2880, "ple.key": 40960, "ple.key_norm": 40960, "ple.value": 10240, "ple.gate": 16, + "ple.gated": 40960, "ple.conv": 40960} +OWN = ("rows", "hidden", "result", "normalized", "hist", "snap") # the values that must not share a buffer + + +def builders(): + """Each kernel's (source, macros, (threadgroups, threads), params record or None) from monolith/kernels.py's + builders: the quantizer, the key and the value at one column whatever the width, the norms over 4 rows.""" + mq, mf = kernels.basalt_mmvq_macros(42, N, 1), kernels.basalt_mmvf_macros(N, N, 1) + mn, ple = kernels.basalt_gr_norm_macros(N), kernels.basalt_ple_source() + return { + "native_quantize_q8_1": (kernels.basalt_q8_1_source(), {}, kernels.basalt_q8_1_grid(N), + kernels.basalt_q8_1_params(N)), + "basalt_mmvq": (kernels.basalt_mmvq_source(), mq, kernels.basalt_mmvq_grid(mq, D), + kernels.basalt_mmvq_params(N, D)), + "basalt_mmvf": (kernels.basalt_mmvf_source(), mf, kernels.basalt_mmvf_grid(mf, N), + kernels.basalt_mmvf_params(N, N, 1)), + "basalt_gr_norm": (kernels.basalt_gr_norm_source(), mn, kernels.basalt_gr_norm_grid(4, mn), + kernels.basalt_gr_norm_params(N, 4, kernels.PLE_RMS_EPS)), + "basalt_ple_gate": (ple, {}, kernels.PLE_GRIDS["gate"], kernels.basalt_ple_gate_params()), + **{f"basalt_ple_{s}": (ple, {}, kernels.PLE_GRIDS[s], None) + for s in ("broadcast", "conv", "advance", "snapshot", "restore")}, + } + + +def rows_of(prog, t): + """``(r, STAGES entry)`` of each dispatch in order, after checking the names: 11 T, row by row in STAGES' order.""" + assert [o.name for o in prog.ops] == [f"basalt_ple_block:{r}:{s[0]}" for r in range(t) for s in STAGES] + return [(r, s) for r in range(t) for s in STAGES] + + +def scratch_of(prog, t): + """The program's scratch buffers by role: ``ws.T.ple..`` as ``ple.``.""" + return {"ple." + b.split(".")[3]: b for b in prog.buffers if b.startswith(f"ws.T{t}.ple.")} + + +@pytest.mark.parametrize("t", range(1, 9)) +def test_dispatches_are_the_builders(src, t): + """DISP, the window: 11 T dispatches in STAGES' order, each with its builder's kernel (function, macros, source), + grid, threads and params record (made once: five records, nine pipelines), the builders' values the plan's + (``LAUNCHES``, the records' fields by struct.unpack_from), each slot bound to its value (a weight at its window, a + scratch buffer at 0, row r of a row binding at r times its row bytes), the plan's ``writes=``; no StepState and + no threadgroup memory. The commit: one dispatch, ``basalt_ple_restore`` (one pipeline, no params record) bound to + hist, snap and the record at byte 0, writing hist, the same op and pipeline at every width as at 8.""" + g, prog = window(src, t) + _, bound = basalt_windows(src, g.values.values(), t) + built = builders() + assert set(built) == set(LAUNCHES) + for fn, (macros, grid, fields) in LAUNCHES.items(): + _, m, gr, prm = built[fn] + assert (m, gr, prm is None) == (macros, grid, fields is None), fn + assert fields is None or struct.unpack_from(fields[0], prm) == fields[1], fn + scratch = scratch_of(prog, t) + + def at(v, r): + return (scratch[v], 0) if v in scratch else bound[v] if v in bound else (f"ngram.{v}", r * ROW_BYTES.get(v, 0)) + + for o, (r, (stage, fn, values, writes)) in zip(prog.ops, rows_of(prog, t)): + source, macros, (groups, threads), prm = built[fn] + k = prog.kernels[o.kernel] + assert (k.function, k.macros, k.source) == (fn, macros, spliced(source)), o.name + assert (o.grid, o.threadgroup, o.threadgroup_memory) == ((groups, 1, 1), (threads, 1, 1), []), o.name + want = [(i, *at(v, r)) for i, v in enumerate(values)] + if prm is not None: + slot, record, off = o.bindings[-1] + assert (slot, off, prog.buffers[record].role, prog.buffers[record].init) == (len(values), 0, "params", + prm), o.name + want.append(o.bindings[-1]) + assert o.bindings == want, o.name + assert o.meta["writes"] == writes, o.name + assert prog.step_state not in {b for o in prog.ops for _, b, _ in o.bindings} + assert sum(b.role == "params" for b in prog.buffers.values()) == 5 and len(prog.kernels) == 9 + c, c8 = commit_program(src, t), commit_program(src, 8) # the commit: one dispatch + (o,), (o8,) = c.ops, c8.ops + source, macros, (groups, threads), _ = built["basalt_ple_restore"] + k = c.kernels[o.kernel] + assert (o.name, k.function, k.macros, k.source) == ("basalt_ple_commit:restore", "basalt_ple_restore", macros, + spliced(source)) + assert (o.grid, o.threadgroup, o.threadgroup_memory) == ((groups, 1, 1), (threads, 1, 1), []) + assert o.bindings == [(0, "ngram.hist", 0), (1, "ngram.snap", 0), (2, "commit", 0)] and o.meta["writes"] == [0] + assert len(c.kernels) == 1 and not any(b.role == "params" for b in c.buffers.values()) + assert (o, k) == (o8, c8.kernels[o8.kernel]) # the same at every width + + +@pytest.mark.parametrize("t", range(1, 9)) +def test_projections_are_main_ops(src, t): + """X-PROJ: every row's q8_1, key and value dispatches are the dispatches main's ``_q8_1``, ``_mmvq`` and ``_mmvf`` + emit for a one-column graph of the same three ops on the same tensors (basalt's per-row call): the same pipeline + (its key, source, macros and function), grid, threads, written slots and params bytes, each weight at the same + bytes of the file, the row's input at r times its row bytes where main binds row 0, every other slot a buffer of + the same role and size at 0.""" + _, prog = window(src, t) + g = Graph("step") + x = g.input("ngram.rows", (T, N), F32) + gemv(g, "basalt_mmvq", "key", q8_1(g, "xq", [x]), weight(g, KEY, src)) + gemv(g, "basalt_mmvf", "value", x, weight(g, VALUE, src)) + main = emit(g, src, 1) + mains = dict(zip(("q8_1", "key", "value"), main.ops)) + assert [o.name.split(":")[0] for o in main.ops] == ["basalt_q8_1", "basalt_mmvq", "basalt_mmvf"] + + def reaches(p, b, off): # a binding as what it reads or writes: a window's bytes of the file, or a buffer + spec = p.buffers[b] + return (spec.role, spec.file, spec.file_offset + off) if spec.role == "weights" else (spec.role, spec.nbytes, + spec.init, off) + + ops = {o.name: o for o in prog.ops} + for r in range(t): + for stage, m in mains.items(): + o = ops[f"basalt_ple_block:{r}:{stage}"] + assert (o.kernel, prog.kernels[o.kernel]) == (m.kernel, main.kernels[m.kernel]), o.name + assert (o.grid, o.threadgroup, o.threadgroup_memory, o.meta["writes"]) == ( + m.grid, m.threadgroup, m.threadgroup_memory, m.meta["writes"]), o.name + assert [i for i, _, _ in o.bindings] == [i for i, _, _ in m.bindings], o.name + for (_, b, off), (_, mb, moff) in zip(o.bindings, m.bindings): + if mb == "ngram.rows": + assert (b, off) == (mb, moff + 4 * N * r), o.name + else: + assert reaches(prog, b, off) == reaches(main, mb, moff), (o.name, b, mb) + + +@pytest.mark.parametrize("t", range(1, 9)) +def test_buffers(src, t): + """BUF, the window: ``hist`` (368,640 B) and ``snap`` (2,949,120 B) are states of one size at every width, so the + programs share them by name; the rows are T rows of 10,240 B and the hidden rows and the outputs T rows of 40,960 B, + host- or GPU-written arenas; the scratch is the plan's seven buffers at its sizes, one each, which every row reuses; + and rows, hidden, result, normalized, hist and snap are bound to six buffers of their own. The commit's program + holds hist and snap at the window's sizes, and the record ``commit`` as a 40-byte host-written arena that no window + program has.""" + _, prog = window(src, t) + sizes = {n: (b.role, b.nbytes) for n, b in prog.buffers.items()} + assert {v: sizes[f"ngram.{v}"] for v in OWN} == { + "rows": ("arena", t * 10240), "hidden": ("arena", t * 40960), "result": ("arena", t * 40960), + "normalized": ("arena", t * 40960), "hist": ("state", 368640), "snap": ("state", 2949120)} + assert {v: sizes[b] for v, b in scratch_of(prog, t).items()} == {v: ("arena", n) for v, n in SCRATCH.items()} + assert len([b for b in prog.buffers if b.startswith("ws.")]) == len(SCRATCH) + bound = {v: set() for v in OWN} + for o, (_, (_, _, values, _)) in zip(prog.ops, rows_of(prog, t)): + for (_, b, _), v in zip(o.bindings, values): + if v in bound: + bound[v].add(b) + assert all(len(b) == 1 for b in bound.values()) and len(set().union(*bound.values())) == len(OWN), bound + c = commit_program(src, t) # the commit's program: the same states, and the record its own + assert {n: (b.role, b.nbytes) for n, b in c.buffers.items() if n in ("ngram.hist", "ngram.snap", "commit")} == { + "ngram.hist": sizes["ngram.hist"], "ngram.snap": sizes["ngram.snap"], "commit": ("arena", 40)} + assert "commit" not in prog.buffers + + +@pytest.mark.parametrize("t", range(1, 9)) +def test_barriers(src, t): + """BAR: two dispatches conflict when one writes a buffer the other reads or writes (buffer granularity, the reads + and writes the plan's ``writes=`` give each dispatch's bindings), write-after-read included; every such pair has a + barrier between them, on the later one or on a dispatch between them (a barrier makes its dispatch, and every one + after it, wait for every one before it: monolith/compiler/barriers.py).""" + _, prog = window(src, t) + access = [] + for o, (_, (_, _, _, writes)) in zip(prog.ops, rows_of(prog, t)): + w = {b for i, b, _ in o.bindings if i in writes} + access.append(({b for _, b, _ in o.bindings} - w, w)) + last, war = -1, 0 # the latest barrier at or before dispatch j + for j, (rj, wj) in enumerate(access): + last = j if prog.ops[j].barrier_before else last + for i, (ri, wi) in enumerate(access[:j]): + if wj & (ri | wi) or rj & wi: + assert last > i, (prog.ops[i].name, prog.ops[j].name) + war += not (wj & wi or rj & wi) # only a write after a read + assert prog.ops[0].barrier_before and war, war + + +# ---- the refusals (X-REF) ---------------------------------------------------------------------------------------- + +def nbytes(v): + """A pack entry's bytes for ``v``: a weight's rows as stored, a constant's values.""" + if v.is_weight: + return v.shape[0] * ggml_row_bytes(GGML_IDS[v.format], v.shape[1]) + return math.prod(v.shape) * v.dtype.itemsize + + +def _dynamic(build): + def case(g, src, bad, tmp): + build(g) + return {"dynamic_t": bad} + return case + + +def _bad(build, make): + """``build`` (``block`` or ``commit``) with the values or ``updates`` ``make(g)`` gives, in the bad case only.""" + def case(g, src, bad, tmp): + build(g, **(make(g) if bad else {})) + return {} + return case + + +def _entry(build, role, at, slab=(False, False), **change): + """``build`` with ``role`` declared as ``p`` (its ``SPECS`` declaration with ``change``), read from a pack entry of + exactly its bytes at byte ``at[bad]`` (test_basalt_ops.pack: the only route to a misaligned binding), a + block-lane-major slab where ``slab[bad]``; where ``at[bad]`` is None, ``role`` as ``SPECS`` declares it.""" + def case(g, src, bad, tmp): + if at[bad] is None: + build(g) + return {} + v = declare(g, role, name="p", **change) + build(g, **{role: v}) + return {"packs": [pack(tmp, {"p": (at[bad], nbytes(v))}, slab=slab[bad])]} + return case + + +def _nine_rows(g, src, bad, tmp): + """The window's four row values at 9 static rows, or at basalt's most, 8.""" + block(g, **{r: declare(g, r, shape=(9 if bad else 8, SPECS[r][2][1])) + for r in ("rows", "hidden", "result", "normalized")}) + return {} + + +def _views(g): + """``result`` and ``normalized`` as two views of one value.""" + base = g.value("ngram.out", (4, D), F32) + return {"result": g.view("ngram.result", base, 0, 2), "normalized": g.view("ngram.normalized", base, 2, 2)} + + +def _one_pack(g, src, bad, tmp): + """``rows`` and ``hidden`` read from pack entries ``p`` and ``q``, of one pack (one window) or of a pack each.""" + block(g, rows=declare(g, "rows", method="const", name="p", shape=(2, N)), + hidden=declare(g, "hidden", method="const", name="q", shape=(2, D))) + entries = {"p": (0, 2 * N * 4), "q": (2 * N * 4, 2 * D * 4)} + if bad: + return {"packs": [pack(tmp, entries)]} + return {"packs": [pack(tmp.with_name(f"{tmp.name}.{n}"), {n: e}) for n, e in entries.items()]} + + +B, C = "basalt_ple_block: ", "basalt_ple_commit: " +DYNAMIC = ("basalt's kernels take the window's width as a compiled count, one static program per width; a dynamic-T " + "program cannot run them") +REFUSALS = [ # (id, build, the reason's regex): monolith/ops/basalt_ple.py's refusals of both kinds, in its order + ("window dynamic-T", _dynamic(block), B + DYNAMIC), + ("window of 9 rows", _nine_rows, B + r"9 rows; basalt's windows run 1 to 8 rows \(verify\.cpp:685-688\)"), + ("key Q3_K (C7's type 11)", _entry(block, "key", (None, 0), dtype="q3_k"), + B + r"the weight 'p' \(q3_k \[10240, 2560\]\) is not a weight or constant \[n_out, n_in\] of ggml type \['q2_0'\]"), + ("key of 2560 rows", _entry(block, "key", (None, 0), shape=(N, N)), + B + r"the key 'p' is q2_0 \[2560, 2560\], not \[10240, 2560\]"), + ("key a block-lane-major slab", _entry(block, "key", (0, 0), (False, True)), + B + r"the weight 'p' is a block-lane-major pack slab, not rows as stored"), + ("value Q2_0 (the key's matrix)", _bad(block, lambda g: dict.fromkeys(("key", "value"), declare(g, "key"))), + B + r"the weight 'gguf/blk\.1\.ple_key\.weight' \(q2_0 \[10240, 2560\]\) is not a weight or constant \[n_out, " + r"n_in\] of ggml type \['bf16'\]"), + ("value of 64 columns", _entry(block, "value", (None, 0), shape=(N, 64)), + B + r"the value 'p' is bf16 \[2560, 64\], not \[2560, 2560\]"), + *[(f"{r} 32 values wider", _bad(block, lambda g, r=r: {r: declare(g, r, shape=(T, SPECS[r][2][1] + 32))}), + B + rf"'ngram\.{r}' is f32 \[2, {w + 32}\], not f32 \[2, {w}\] \({why}\)") + for r, w, why in (("rows", N, "the window's gathered rows"), ("hidden", D, "the window's hidden rows"), + ("result", D, "the block's output rows"), ("normalized", D, "the conv norm's rows"))], + ("norm F16", _entry(block, "norm_query", (None, 0), dtype=DType.F16), + B + r"'p' is f16 \[10240\], not f32 \[10240\] \(a grouped norm's weights\)"), + ("taps F32", _entry(block, "taps", (None, 0), dtype=F32), + B + r"'p' is f32 \[10240, 4\], not f16 \[10240, 4\] \(the convolution's four taps a channel, k \+ 4c\)"), + ("history an input", _bad(block, lambda g: {"hist": declare(g, "hist", method="input"), "updates": ["ngram.snap"]}), + B + r"'ngram\.hist' \(the history\) is not a state"), + ("history of 10 rows", _bad(block, lambda g: {"hist": declare(g, "hist", shape=(D, HIST + 1))}), + B + r"'ngram\.hist' is f32 \[10240, 10\], not f32 \[10240, 9\] \(the history\)"), + ("snapshots of 7 slots", _bad(block, lambda g: {"snap": declare(g, "snap", shape=(T_MAX - 1, D, HIST))}), + B + r"'ngram\.snap' is f32 \[7, 10240, 9\], not f32 \[8, 10240, 9\] \(the snapshots\)"), + ("history not in updates", _bad(block, lambda g: {"updates": ["ngram.snap"]}), + B + r"'ngram\.hist' \(the history\) is not in updates; the window writes it in place"), + ("snapshots not in updates", _bad(block, lambda g: {"updates": ["ngram.hist"]}), + B + r"'ngram\.snap' \(the snapshots\) is not in updates; the window writes it in place"), + ("snapshots the history", _bad(block, lambda g: dict.fromkeys(("hist", "snap"), declare(g, "hist"))), + B + r"'ngram\.hist' is both the history and its snapshots"), + ("rows off 8 bytes", _entry(block, "rows", (8, 4), method="const", shape=(2, N)), + B + r"'p' binds at byte 4 of pack\.0; slot 0 needs 8-byte alignment"), + ("hidden off 4 bytes", _entry(block, "hidden", (4, 2), method="const", shape=(2, D)), + B + r"'p' binds at byte 2 of pack\.0; slot 0 needs 4-byte alignment"), + ("norm off 4 bytes", _entry(block, "norm_conv", (4, 2)), + B + r"'p' binds at byte 2 of pack\.0; slot 1 needs 4-byte alignment"), + ("taps off 2 bytes", _entry(block, "taps", (2, 1)), + B + r"'p' binds at byte 1 of pack\.0; slot 2 needs 2-byte alignment"), + ("result and normalized in one buffer", _bad(block, _views), + B + r"'ngram\.normalized' and 'ngram\.result' bind one buffer \(ngram\.out\)"), + ("rows and hidden in one buffer", _one_pack, B + r"'q' and 'p' bind one buffer \(pack\.0\)"), + ("commit dynamic-T", _dynamic(commit), C + DYNAMIC), + ("commit history an input", _bad(commit, lambda g: {"hist": declare(g, "hist", method="input"), "updates": []}), + C + r"'ngram\.hist' \(the history\) is not a state"), + ("commit history of 10 rows", _bad(commit, lambda g: {"hist": declare(g, "hist", shape=(D, HIST + 1))}), + C + r"'ngram\.hist' is f32 \[10240, 10\], not f32 \[10240, 9\] \(the history\)"), + ("commit history not in updates", _bad(commit, lambda g: {"updates": []}), + C + r"'ngram\.hist' \(the history\) is not in updates; the commit restores it in place"), + ("commit snapshots an input", _bad(commit, lambda g: {"snap": declare(g, "snap", method="input")}), + C + r"'ngram\.snap' \(the snapshots\) is not a state"), + ("commit snapshots of 7 slots", _bad(commit, lambda g: {"snap": declare(g, "snap", shape=(T_MAX - 1, D, HIST))}), + C + r"'ngram\.snap' is f32 \[7, 10240, 9\], not f32 \[8, 10240, 9\] \(the snapshots\)"), + ("commit snapshots in updates", _bad(commit, lambda g: {"updates": ["ngram.hist", "ngram.snap"]}), + C + r"'ngram\.snap' \(the snapshots\) is in updates; it only reads them"), + ("commit snapshots the history", _bad(commit, lambda g: dict.fromkeys(("hist", "snap"), declare(g, "hist"))), + C + r"'ngram\.hist' is both the history and its snapshots"), + ("commit record F32", _bad(commit, lambda g: {"commit": declare(g, "commit", dtype=F32)}), + C + r"'commit' \(f32 \[10\]\) is not the commit record, an i32 graph input of at least 2 words"), + ("commit record of 1 word", _bad(commit, lambda g: {"commit": declare(g, "commit", shape=(1,))}), + C + r"'commit' \(i32 \[1\]\) is not the commit record, an i32 graph input of at least 2 words"), + ("commit record a constant", _entry(commit, "commit", (None, 0), method="const"), + C + r"'p' \(i32 \[10\]\) is not the commit record, an i32 graph input of at least 2 words"), + ("commit record a StepState field", + _bad(commit, lambda g: {"commit": declare(g, "commit", name="tokens", shape=(T_MAX,))}), + C + r"'tokens' names a StepState field; the commit record is a host-written input buffer of its own"), +] + + +@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): + """X-REF: each case emits as a valid op, then with its one defect is refused before anything is encoded, with its + reason (``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) + + +# ---- the key's binding (X-BIND) ---------------------------------------------------------------------------------- + +def key_slot(prog): + """``(file, absolute offset)`` that row 0's key dispatch reads its weight at.""" + (o,) = [o for o in prog.ops if o.name == "basalt_ple_block:0:key"] + _, b, off = o.bindings[0] + return prog.buffers[b].file, prog.buffers[b].file_offset + off + + +def test_key_binds_gguf_type42(src): + """X-BIND-1 (native_dense_ple_key_test.cpp:145-158: with a shape-only key row the key stays the source tensor, + served natively): the key's shape-only dense row is refused, its bytes being in gguf, and the block's key binds + ``gguf/blk.1.ple_key.weight``, type 42 ``[10240, 2560]``, at the tensor's bytes. On the synthetic file, and on the + pack's own dense.index (tests/contract/fixtures/basalt_pack.safetensors; the key's row, 46 of the table: kind 0, no + bytes, code_bits 8) with the key's gguf record (basalt_ple.safetensors), at its offset in the pack.""" + real, fixture = real_source() + rec = next(e for e in committed()[1]["entries"] if e["key"] == KEY) + f = real.file + f.meta()["tensors"][rec["tensor"]] = {"type_id": rec["type_id"], "shape": rec["ne"], "bytes": rec["bytes"], + "offset": rec["offset"] - f.section("gguf").offset} # into the cached meta + real = BasaltSource(fixture["file"], f) + rows = [r for r in f.dense_index().rows if r.name == rec["tensor"]] + assert [(r.kind, r.src_bytes, r.dst_bytes, r.ne0, r.ne1, r.code_bits, r.in_gguf) for r in rows] == [ + (0, 0, 0, N, D, 8, True)] + for s, at in ((src, src.file.tensor("blk.1.ple_key.weight").offset), (real, TENSORS["blk.1.ple_key.weight"].gguf)): + assert s.refused[DENSE_KEY] == f"its bytes are in gguf: bind {KEY}" + e = s.bind(KEY, "q2_0", (D, N)) + assert (e.type_id, e.shape, e.offset, e.nbytes) == (42, (D, N), at, TENSORS["blk.1.ple_key.weight"].nbytes) + assert key_slot(window(s, 1)[1]) == (s.path, at) + g = Graph("step") + block(g, key=g.const(DENSE_KEY, (D, N), DType.BF16)) + with pytest.raises(ValueError, match=re.escape(f"{DENSE_KEY!r} cannot be bound: its bytes are in gguf: bind " + f"{KEY}")): + emit(g, s, 1) + + +def test_bf16_key_row_is_refused(tmp_path): + """X-BIND-2 (native_dense_ple_key_test.cpp:116-143: with a BF16 key row basalt keeps the key in its arena as that + row and attaches no native key): with the key's dense row BF16 (kind 4, code_bits 0), basalt serves the key from + the row, an arm this port does not build, so the block refuses the gguf key, and refuses the row itself as the key + (BF16 where the key's arm takes type 42).""" + s = BasaltSource(write_file(tmp_path / "bf16.basalt", zeros(), key_row="bf16")) + assert (s.entries[DENSE_KEY].type_id, s.entries[DENSE_KEY].shape) == (30, (D, N)) and KEY in s.entries + for over, why in (({}, r"the dense\.index holds 'blk\.1\.ple_key\.weight' unquantized \(code_bits 0\), so basalt " + r"serves the key from that row, an arm this port does not build"), + ({"key": (DENSE_KEY, DType.BF16)}, r"the weight 'dense/blk\.1\.ple_key\.weight' \(bf16 \[10240, " + r"2560\]\) is not a weight or constant \[n_out, n_in\] of " + r"ggml type \['q2_0'\]")): + g = Graph("step") + block(g, **{r: g.const(name, (D, N), dt) for r, (name, dt) in over.items()}) + with pytest.raises(ValueError, match=B + why): + emit(g, s, 1) + + +def test_missing_key_is_refused(src, tmp_path): + """X-BIND-3 (native_dense_ple_key_test.cpp:160-171, index_code_bits's edge cases): a file with no key in either + name space fails the binding naming the key, declared either way; a key from a file with no dense.index is + refused, as basalt's load fails when it cannot open the index (:166-167; src/core/weights.cpp:129-132), here with + the other five bound from their gguf twins, which emit from the file that has one; and a dense.index without the + key's row is no refusal: the row's code bits are -1 (:164-165), so the key stays the gguf tensor.""" + none = BasaltSource(write_file(tmp_path / "none.basalt", {n: b for n, b in zeros().items() + if n != "blk.1.ple_key.weight"}, key_row=None)) + for name, method, dt in ((KEY, "weight", "q2_0"), (DENSE_KEY, "const", DType.BF16)): + g = Graph("step") + block(g, key=declare(g, "key", method=method, name=name, dtype=dt)) + with pytest.raises(KeyError, match=re.escape(f"the pack has no entry for {name!r}")): + emit(g, none, 1) + + def twins(s): # the five from the gguf section + g = Graph("step") + block(g, **{r: declare(g, r, name=SPECS[r][1].replace("dense/", "gguf/")) for r in BLOCK_IN[3:8]}) + return emit(g, s, 1) + + assert key_slot(twins(src)) == (src.path, src.file.tensor("blk.1.ple_key.weight").offset) + no_index = BasaltSource(write_file(tmp_path / "no_index.basalt", zeros(), index=False)) + with pytest.raises(ValueError, match=B + re.escape(f"{no_index.path} holds {KEY!r} but no dense.index")): + twins(no_index) + no_row = BasaltSource(write_file(tmp_path / "no_row.basalt", zeros(), key_row=None)) + assert key_slot(window(no_row, 1)[1]) == (no_row.path, no_row.file.tensor("blk.1.ple_key.weight").offset) diff --git a/tests/contract/test_basalt_ple_refs.py b/tests/contract/test_basalt_ple_refs.py new file mode 100644 index 00000000..37dc9d80 --- /dev/null +++ b/tests/contract/test_basalt_ple_refs.py @@ -0,0 +1,210 @@ +# SPDX-License-Identifier: MIT +# Copyright (c) 2026 Jesús Gulfo +# adapted from basalt (jesdga95/basalt) src/kernels/ple_parity.cpp, src/kernels/ple_win_parity.cpp, src/core/verify.cpp +# @ b4c63b55754637f4c72ad53a0f791d425f71eb36 (MIT; third_party/NOTICE): ple_parity's checks on its block oracle (the +# conv input and the conv tap order, :984-1025) and on its host f32 reference (:1104-1123), and their pass criteria; +# the fixture's properties (spec T§6.3); the capture loader's and the preflight's checks (:135-164, :273-283, +# :563-614) as the real-weight fixture's (spec T§1.1); verify.cpp's commit count refusal and record (:2732-2737). +"""Host-only checks of the n-gram block's references (tests/basalt_ple_ref.py) and of its real-weight fixture; no GPU. +The block-level checks run 12 rows from one initial history through R-struct (spec T§6.1). + +- FX.2 ``test_fixture_properties``: the synthetic fixture's four properties (T§6.3: hidden nonzero, min |s| >= 0.1, the + block's share of result >= 0.3 on every row, 12 rows from one history), and the same seed gives the same bytes. +- FX.1 ``test_real_fixture_extents`` (ple_parity's L1-L4, P3, P4, C0, C0b and C0d, spec T§1.1). ``[committed]``: the + committed slices come from the pinned file, and its six tensors sit at T§5's offsets with T§5's types, sizes and + ngram.hpp:30-41's shapes, as the pack's own tables gave them to make_basalt_ple_fixture.py; the loader skips with a + reason naming BASALT_PLE_FIXTURE when the variable is unset, and fails on a range file missing or of the wrong size. + ``[full]``: the two full ranges have their sizes, the tensors cut from them T§5's sizes, and the committed slices + are their heads. +- X-W ``test_dense_rows_equal_gguf`` (spec T§8): each of the five dense rows equals its GGUF tensor byte for byte, + ``[committed]`` on the first 1024 B, ``[full]`` whole. +- C13 ``test_conv_input_is_normalized_not_gated`` (ple_parity.cpp:984-989): on every row, convolving gated instead of + normalized would be visible, criterion quoted: ``if (!(rel_norm_gated > 0.05)) ++bad;`` (:988). +- C14 ``test_tap_order_rivals_are_visible`` (:992-1025): on every row, R-struct's conv_out against the reversed taps + (basalt's rival, P[t + 3 (3 - k)]) and against the transposed kernel (conv1d read as flat [k * 10240 + i], the bug + of basalt's first reference, :1012-1016), each with ``if (!gt(rel, 0.05)) ++bad;`` (:1024); on the synthetic taps + ``[synthetic]``, on the pack's committed conv1d over the synthetic fixture's rows and history ``[committed]``, and on + R-struct of the real fixture ``[full]``. +- C15 ``test_host_f32_matches_float64_graph`` (ple_parity.cpp:1027-1137): R-f32, basalt's host f32 block transcribed + with its own slide, against R-struct on every stage of every row, criterion quoted: ``const bool ok = le(rel, 1e-4) + && nf == 0;`` (:1119), rel = rel_l1(R-struct, R-f32); on the synthetic fixture ``[synthetic]`` and the real one + ``[full]``. Every stage R-f32 returns is float32, and its slid history after each row is H-ORACLE (spec T§7.1) of + its own normalized rows, byte for byte. +- X-COMMIT's host half ``test_commit_record_refuses`` (spec T§8): the host refuses n_keep < 1 and n_keep > T, as + ``if (n_keep < 1 || n_keep > last_t_)`` does (verify.cpp:2732), and the record's words for n_keep = 1..T are the ones + verify.cpp:2735-2737 writes. + +The ``[full]`` cases read $BASALT_PLE_FIXTURE (make_basalt_ple_fixture.py --full DIR fetches it) and skip when it is +unset.""" + +import numpy as np +import pytest + +from tests.basalt_ple_ref import (D, DIL, KERN, KEY_BLOCK, N, RANGES, ROWS, STAGES, T_MAX, TENSORS, Fixture, Ref, + check_fixture, commit_record, committed, conv, full_ranges, gt, h_oracle, le, r_f32, + r_struct, real, real_tensors, rel_l1, silu, synthetic, taps) +from tests.contract.fixtures.make_basalt_fixture import FILE, REPO, REVISION + +CONV1D = "blk.1.ple_conv1d.weight" + + +@pytest.fixture(scope="module") +def synth(): + fx = synthetic() + return fx, r_struct(fx) + + +@pytest.fixture(scope="module") +def full(): + fx = real() + return fx, r_struct(fx) + + +def test_fixture_properties(synth): + fx, ref = synth + min_s, share = check_fixture(fx, ref) # the four properties, each asserted with T§6.3's words + again = synthetic() + differ = [name for name, a, b in zip(Fixture._fields, fx, again) + if (a.dtype, a.shape, a.tobytes()) != (b.dtype, b.shape, b.tobytes())] + assert not differ, f"FX.2, \"the same seed gives the same bytes\": two calls differ in {differ}" + print(f"synthetic fixture: min |s| {min_s:.4f}, min row share {share:.4f}") + + +@pytest.mark.parametrize("form", ["committed", "full"]) +def test_real_fixture_extents(form, tmp_path, monkeypatch): + slices, meta = committed() + if form == "full": + ranges, cut = full_ranges(), real_tensors() + sizes = {space: len(data) for space, data in ranges.items()} + assert sizes == {space: size for space, (_, _, size) in RANGES.items()}, ( + "L3, `if (file_size(in_path) != in_bytes || file_size(out_path) != out_bytes) { std::fclose(fi); return " + f"false; }}` (ple_parity.cpp:153-154), here T§5's two ranges: {sizes}") + wrong = {k: len(v) for k, v in cut.items() if len(v) != TENSORS[k.split("/", 1)[1]].nbytes} + assert len(cut) == 11 and not wrong, f"P3, the ranges cover T§5's tensors at their sizes: {wrong}" + heads = [k for k, v in slices.items() if cut[k][:len(v)] != v] + assert not heads, f"FX.1, the committed slices are the heads of the full ranges' tensors; these differ: {heads}" + return + + pinned = (meta["repo"], meta["revision"], meta["file"], meta["file_bytes"]) + assert pinned == (REPO, REVISION, FILE, 69685970297), f"FX.1, the slices come from the pinned file: {pinned}" + want = {} # T§5's table, and the writer's rule for what it keeps of each tensor + for name, t in TENSORS.items(): + want[f"gguf/{name}"] = dict(source="gguf", tensor=name, type_id=t.type_id, ne=list(t.ne), offset=t.gguf, + bytes=t.nbytes, kept=N // 64 * KEY_BLOCK if t.type_id == 42 else 1024) + if t.dense is not None: + want[f"dense/{name}"] = dict(source="dense", tensor=name, kind=t.kind, ne=list((t.ne + (0,))[:2]), + offset=t.dense, bytes=t.nbytes, kept=t.nbytes if name == CONV1D else 1024) + got = {e["key"]: {k: v for k, v in e.items() if k != "key"} for e in meta["entries"]} + differ = sorted(k for k in want.keys() | got.keys() if want.get(k) != got.get(k)) + assert not differ, ( + "L2 and C0b, `if (c.n_embd != k::NG_N_EMBD || c.hc != k::NG_HC || c.nt <= 0 || c.nt > 64 || c.kern != " + "k::PLE_CONV_KERNEL || c.dil != k::NGRAM_SIZE || c.eps != k::NG_RMS_EPS) { std::fclose(fi); return false; }` " + "(ple_parity.cpp:144-146), here the committed tensors' types, shapes, offsets and sizes as the pack's tables " + f"gave them, against T§5's: {[(k, got.get(k), want.get(k)) for k in differ]}") + lengths = {k: len(v) for k, v in slices.items()} + assert lengths == {k: e["kept"] for k, e in want.items()}, f"FX.1, each slice is what the writer kept: {lengths}" + + # The loader: C0's skip, L1's missing file, C0d's short range, L3's exact size, on files in tmp_path. + monkeypatch.delenv("BASALT_PLE_FIXTURE", raising=False) + with pytest.raises(pytest.skip.Exception, match=r"BASALT_PLE_FIXTURE.*make_basalt_ple_fixture\.py --full DIR"): + full_ranges() + monkeypatch.setenv("BASALT_PLE_FIXTURE", str(tmp_path)) + with pytest.raises(pytest.fail.Exception, match="gguf_blk1_ple.bin is missing"): + full_ranges() # L1, `if (!fi) return false;` (ple_parity.cpp:137) + for name, _, size in RANGES.values(): + with open(tmp_path / name, "wb") as f: + f.truncate(size - 1 if name.startswith("gguf") else size + 1) + # C0d, `if (key_codes.empty() || raw_scales.empty() || raw_value.empty()) {` (ple_parity.cpp:593): a short range + with pytest.raises(pytest.fail.Exception, match="gguf_blk1_ple.bin is 20684799 bytes, not 20684800"): + full_ranges() + with open(tmp_path / RANGES["gguf"][0], "wb") as f: + f.truncate(RANGES["gguf"][2]) + with pytest.raises(pytest.fail.Exception, match="dense_blk1_ple.bin is 13312001 bytes, not 13312000"): + full_ranges() # L3, `!= in_bytes` (:153) + with open(tmp_path / RANGES["dense"][0], "wb") as f: + f.truncate(RANGES["dense"][2]) + assert {k: len(v) for k, v in real_tensors().items()} == {k: e["bytes"] for k, e in want.items()} + + +@pytest.mark.parametrize("form", ["committed", "full"]) +def test_dense_rows_equal_gguf(form): + got, head = (committed()[0], 1024) if form == "committed" else (real_tensors(), None) + names = [name for name, t in TENSORS.items() if t.dense is not None] + differ = [name for name in names if got[f"dense/{name}"][:head] != got[f"gguf/{name}"][:head]] + criterion = ("the first 1024 B of each dense row equal the first 1024 B of the matching GGUF tensor" + if head else "each whole dense row equals its whole GGUF tensor") + assert len(names) == 5 and not differ, f"X-W, \"{criterion}\" (spec T§8): these differ: {differ}" + + +def test_conv_input_is_normalized_not_gated(synth): + _, ref = synth + rels = [rel_l1(ref.gated[t], ref.normalized[t])[0] for t in range(ROWS)] + bad = sum(not (rel > 0.05) for rel in rels) + assert bad == 0, ("`if (!(rel_norm_gated > 0.05)) ++bad;` (ple_parity.cpp:988), rel_norm_gated = " + f"rel_l1(gated, normalized): {bad} of {ROWS} rows fail; per row {np.round(rels, 4).tolist()}") + + +@pytest.mark.parametrize("form", ["synthetic", "committed", "full"]) +def test_tap_order_rivals_are_visible(form, synth, request): + fx, ref = request.getfixturevalue("full") if form == "full" else synth + if form == "committed": # the pack's own taps; normalized does not depend on them + fx = fx._replace(conv1d=np.frombuffer(committed()[0][f"dense/{CONV1D}"], np.float16)) + ref = r_struct(fx) + P = np.concatenate([fx.hist, ref.normalized]) # R-struct's padded rows: [history | normalized rows] + w = taps(fx.conv1d) + rivals = { # each as basalt accumulates its rival, tap kk = 0..3 in order + # basalt's rival (:1003-1016): tap kk reads row (K - 1 - kk) * dil, 9, 6, 3, 0; the source reads 0, 3, 6, 9 + "reversed taps, P[t + 3 (3 - k)]": sum(w[:, k] * P[DIL * (KERN - 1 - k):][:ROWS] for k in range(KERN)), + "transposed kernel, conv1d flat [k * 10240 + i]": conv(P, np.asarray(fx.conv1d, np.float64).reshape(KERN, D).T), + } + bad = {} + for name, rival in rivals.items(): + out = silu(rival) + rels = [rel_l1(ref.conv_out[t], out[t])[0] for t in range(ROWS)] + bad[name] = (sum(not gt(rel, 0.05) for rel in rels), np.round(rels, 4).tolist()) + assert all(n == 0 for n, _ in bad.values()), \ + f"`if (!gt(rel, 0.05)) ++bad;` (ple_parity.cpp:1024), rel = rel_l1(conv_out, rival) per row: {bad}" + + +@pytest.mark.parametrize("form", ["synthetic", "full"]) +def test_host_f32_matches_float64_graph(form, synth, request): + fx, want = request.getfixturevalue("full") if form == "full" else synth + got = r_f32(fx) + wide = [name for name in Ref._fields if getattr(got, name).dtype != np.float32] + assert not wide, f"R-f32 is basalt's host f32 block, every stage float32; these are not: {wide}" + rels, bad = {}, [] + for stage in STAGES: + for t in range(ROWS): + rel, _, nf = rel_l1(getattr(want, stage)[t], getattr(got, stage)[t]) + rels.setdefault(stage, []).append(rel) + if not (le(rel, 1e-4) and nf == 0): + bad.append((stage, t, rel, nf)) + print(f"host f32 reference [{form}], worst rel over {ROWS} rows: " + + ", ".join(f"{stage} {max(r):.3e}" for stage, r in rels.items())) + assert not bad, ("`const bool ok = le(rel, 1e-4) && nf == 0;` (ple_parity.cpp:1119), rel = rel_l1(R-struct, " + f"R-f32) per stage and row; these (stage, row, rel, nf) fail: {bad}") + start = fx.hist.T.ravel() # basalt's layout, row r of channel c at c * 9 + r + moved = [n for n in range(1, ROWS + 1) + if h_oracle(start, got.normalized, n).tobytes() != got.hist[n - 1].T.tobytes()] + assert not moved, ("H-ORACLE (spec T§7.1), \"the last nine rows of the host sequence [H rows 0..8 | the GPU's " + "normalized rows 0..`n_keep` − 1], compared byte for byte in basalt's layout (row r, channel c " + "at `c * 9 + r`)\", against R-f32's slide (ple_parity.cpp:1127-1131) over its own normalized " + f"rows: these n_keep differ: {moved}") + + +def test_commit_record_refuses(): + words = commit_record(3, 5, 100) + assert words.dtype == np.int32 and words.tolist() == [3, 2, 100, 101, 102, -1, -1, -1, -1, -1], words + for t in range(1, T_MAX + 1): + for n_keep in (-1, 0, t + 1): + # The host refuses n_keep < 1 and n_keep > T before any write, as `if (n_keep < 1 || n_keep > last_t_)` + # does (verify.cpp:2732): `{ err = "verify: commit count out of range"; return false; }` + with pytest.raises(ValueError, match="commit count out of range"): + commit_record(n_keep, t, 4096) + for n_keep in range(1, t + 1): + words = commit_record(n_keep, t, 4096) + want = [n_keep, n_keep - 1] + [4096 + r for r in range(n_keep)] + [-1] * (T_MAX - n_keep) + assert words.dtype == np.int32 and words.tolist() == want, ( + "`h_commit_[0] = n_keep; h_commit_[1] = n_keep - 1; for (int t = 0; t < max_t_; ++t) h_commit_[2 + t] " + f"= t < n_keep ? (int32_t) (last_pos0_ + t) : -1;` (verify.cpp:2735-2737), T = {t}, n_keep = {n_keep}: " + f"{words.tolist()} ({words.dtype}), not {want}") diff --git a/tests/contract/test_ci_mac_lane.py b/tests/contract/test_ci_mac_lane.py index 4f4e842b..b69e6302 100644 --- a/tests/contract/test_ci_mac_lane.py +++ b/tests/contract/test_ci_mac_lane.py @@ -1,5 +1,7 @@ """The self-hosted Mac lane: the skip audit of tools/ci/mac_gpu.py and the commit statuses of tools/ci/ci_status.py.""" +import types + from tools.ci import ci_status, mac_gpu @@ -83,3 +85,22 @@ def test_fresh_dir_never_follows_or_keeps_what_a_test_left(tmp_path): assert mac_gpu.fresh_dir(root, "venv").is_dir() assert (outside / "keep.txt").read_bytes() == b"precious" + +def test_lane_environment_names_the_ple_fixture(tmp_path, monkeypatch): + py, log = tmp_path / "venv" / "bin" / "python", [] + monkeypatch.delenv("GITHUB_STEP_SUMMARY", raising=False) + monkeypatch.setattr(mac_gpu.platform, "system", lambda: "Darwin") + monkeypatch.setattr(mac_gpu.platform, "machine", lambda: "arm64") + monkeypatch.setattr(mac_gpu.shutil, "disk_usage", lambda path: types.SimpleNamespace(free=10**12)) + monkeypatch.setattr(mac_gpu, "chip_name", lambda: "test") + monkeypatch.setattr(mac_gpu, "prepare_venv", lambda root, repo, python: py) + monkeypatch.setattr(mac_gpu, "run", lambda cmd, **kw: log.append(cmd)) + monkeypatch.setattr(mac_gpu, "run_tier", lambda tier, py, repo, env, report, timeout: log.append(env) or + {"tier": tier, "tests": 1, "failures": 0, "errors": 0, "skipped": 0, "wall_s": 0.0, + "problems": []}) + # a contract-only run: the contract tier reads the fixture too, and provisions nothing else + assert mac_gpu.main(["--root", str(tmp_path), "--tiers", "contract", "--report-dir", str(tmp_path / "report")]) == 0 + fixture = tmp_path / "fixtures" / "ple" + writer = str(mac_gpu.ROOT / "tests" / "contract" / "fixtures" / "make_basalt_ple_fixture.py") + assert log[0] == [str(py), writer, "--full", str(fixture)] and fixture.is_dir() # fetched before the tier + assert len(log) == 2 and log[1]["BASALT_PLE_FIXTURE"] == str(fixture) diff --git a/tests/kernels/basalt_emu.py b/tests/kernels/basalt_emu.py index eea1feb7..36fd6229 100644 --- a/tests/kernels/basalt_emu.py +++ b/tests/kernels/basalt_emu.py @@ -4,10 +4,12 @@ # 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, +# src/kernels/cuda/native_gr_norm.cu, src/kernels/cuda/native_ple_postops.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). +# ggml/src/ggml-quants.c (get_scale_min_k4), ggml/src/ggml-cuda/quantize.cu, ggml/src/ggml-cuda/mmvf.cu, +# ggml/src/ggml-cuda/norm.cu (the RMSNorm), ggml/src/ggml-cuda/reduce_rows.cuh (the row sum) and +# ggml/src/ggml-cuda/unary.cu (the SiLU) @ 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 @@ -791,3 +793,90 @@ def q5k_proxy_final(cand, part, exact, map_, expf): 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 + + +# ---- the n-gram block's grouped RMSNorm (docs/research/basalt-nvcc/ple.md section 1) -------------------------------- +# native_gr_norm.cu builds with --use_fast_math: every FMA, add and multiply is .FTZ. + +def gr_norm(x, gamma, n_rows, n_cols, gamma_rows, eps, rsqrt): + """weighted_rms_norm (native_gr_rms_norm_weighted) as ple.md section 1 records it, on ``n_rows`` rows of + ``n_cols`` float32 values ``x``, row r with row r % ``gamma_rows`` of ``gamma``; block = 256 below 1024 columns, + else 1024 (native_gr_norm.cu:93-96). Thread t squares columns t, t + block, ... in order, fma(v, v, acc) from +0; + the XOR butterfly per warp; every warp's butterfly over the 32 slots (the block / 32 warp sums, then +0s); scale = + rsq(fma(sum, rcp(f(n_cols)), eps)); y = fl(fl(scale * x) * gamma), all .FTZ, with the correctly rounded reciprocal + in place of MUFU.RCP. ``rsqrt`` evaluates the kernel's rsqrtf_ftz (MUFU.RSQ and fast::rsqrt have no bit-exact host + model). Returns (n_rows, n_cols) float32.""" + block = 1024 if n_cols >= 1024 else 256 + x = np.asarray(x, F32).reshape(n_rows, n_cols) + g = np.asarray(gamma, F32).reshape(gamma_rows, n_cols)[np.arange(n_rows) % gamma_rows] + acc = np.zeros((n_rows, block), F32) + for c0 in range(0, n_cols, block): + c = np.arange(c0, min(c0 + block, n_cols)) + acc[:, c - c0] = fma_ftz(x[:, c], x[:, c], acc[:, c - c0]) + slots = np.zeros((n_rows, 32), F32) + slots[:, : block // 32] = butterfly(acc.reshape(-1, 32), add_ftz).reshape(n_rows, block // 32) + total = butterfly(slots, add_ftz) + scale = np.asarray(rsqrt(fma_ftz(total, rcp_ftz(F32(n_cols)), F32(eps))), F32) + return mul_ftz(mul_ftz(scale[:, None], x), g) + + +# ---- the n-gram block's gate, broadcast and convolution (docs/research/basalt-nvcc/ple.md sections 2-4) ------------- +# native_ple_postops.cu builds with --use_fast_math: every multiply, add and FMA is .FTZ. + +PLE_N = 2560 # native_ple_postops.cu:36's N: a hyper-connection stream's width + + +def cuda_nan(x): + """A NaN as sm_120 stores it, 0x7fffffff; every other value keeps its bits (docs/research/basalt-nvcc/nan.md).""" + b = np.asarray(x, F32).view(np.uint32) + return np.where((b & 0x7FFFFFFF) > 0x7F800000, np.uint32(0x7FFFFFFF), b).astype(np.uint32).view(F32) + + +def ple_gate(key, query, scale, sqrt, expf): + """gate_kernel as ple.md section 2 records it, one 512-thread block per row of PLE_N normalized key and query + values: thread t's products fl(k_d q_d) for d = t + 512 j, j < 8 (+0 past the row), each added to +0; its eight + partials added in order to +0; the XOR butterfly in each of the 16 warps, then over their 16 sums and 16 zeros; + s = fma(scale, sum, +0); sign = (s > 0) - (s < 0), 0 for +-0 and a NaN; mag = sq(max(|s|, 1e-6f)); + gate = rcp(fl(ex2(fl(fl(mag sign) (-L))) + 1)); all .FTZ, with the correctly rounded reciprocal in place of + MUFU.RCP. ``sqrt`` and ``expf`` evaluate the kernel's sqrtf_ftz and expf_ftz (MUFU.SQRT, MUFU.EX2 and their + metal::fast counterparts have no bit-exact host model). Returns (rows,) float32.""" + k, q = (np.asarray(a, F32).reshape(-1, PLE_N) for a in (key, query)) + rows = len(k) + p = np.zeros((rows, 8 * 512), F32) # column t + 512 j: thread t's product j + p[:, :PLE_N] = mul_ftz(k, q) + sums = add_ftz(F32(0.0), p.reshape(rows, 8, 512)) + acc = np.zeros((rows, 512), F32) + for j in range(8): + acc = add_ftz(acc, sums[:, j]) + slots = np.zeros((rows, 32), F32) + slots[:, :16] = butterfly(acc.reshape(-1, 32), add_ftz).reshape(rows, 16) + s = fma_ftz(F32(scale), butterfly(slots, add_ftz), F32(0.0)) + with np.errstate(invalid="ignore"): + sign = np.where(s > 0, F32(1.0), np.where(s < 0, F32(-1.0), F32(0.0))) + mag = np.asarray(sqrt(max_ftz(ftz(np.abs(s)), F32(1e-6))), F32) + return rcp_ftz(add_ftz(F32(1.0), np.asarray(expf(-mul_ftz(sign, mag)), F32))) + + +def ple_broadcast(value, gate): + """broadcast_kernel (ple.md section 3): gated[i] = fl(value[i % N] gate[i / N]), .FTZ, N = len(value), stored as + sm_120 stores a NaN. Returns (len(gate) * N,) float32.""" + v, g = np.asarray(value, F32).ravel(), np.asarray(gate, F32).ravel() + return cuda_nan(mul_ftz(v[None, :], g[:, None]).ravel()) + + +def ple_conv(hist, normalized, taps, hidden, gated, expf): + """conv_residual_kernel (ple.md section 4), per channel c: the terms t_k = fl(x_k h(w_k)) of history rows 0, 3 and + 6 (``hist`` in basalt's layout, row r of channel c at c * 9 + r) and of normalized[c], the fp16 taps ``taps`` + (float16 or their bits, at [k + 4 c]) widened exactly; sum = fl(fl(fl(t_0 + t_1) + t_2) + t_3); + act = fl(sum rcp(fl(ex2(fl(sum (-L))) + 1))); result = fl(hidden + fl(gated + act)); all .FTZ, with the correctly + rounded reciprocal in place of MUFU.RCP, and conv (act) and result stored as sm_120 stores a NaN. ``expf`` + evaluates the kernel's expf_ftz. Returns (conv, result), float32.""" + h = np.asarray(hist, F32).reshape(-1, 9) + w = h2f(np.ascontiguousarray(taps).view(np.uint16)).reshape(-1, 4) + x = (h[:, 0], h[:, 3], h[:, 6], np.asarray(normalized, F32).ravel()) + s = mul_ftz(x[0], w[:, 0]) + for k in (1, 2, 3): + s = add_ftz(s, mul_ftz(x[k], w[:, k])) + act = mul_ftz(s, rcp_ftz(add_ftz(F32(1.0), np.asarray(expf(-s), F32)))) + result = add_ftz(np.asarray(hidden, F32).ravel(), add_ftz(np.asarray(gated, F32).ravel(), act)) + return cuda_nan(act), cuda_nan(result) diff --git a/tests/kernels/basalt_ple_gpu.py b/tests/kernels/basalt_ple_gpu.py new file mode 100644 index 00000000..8c4f90fc --- /dev/null +++ b/tests/kernels/basalt_ple_gpu.py @@ -0,0 +1,277 @@ +"""Single-kernel runs of the n-gram block's Metal port (kernels/common/basalt_gr_norm.metal and basalt_ple.metal) for +the GPU tests, on tests/kernels/basalt_gpu.py's device, pipelines and runs: one wrapper per entry, every output +starting as 0xFF bytes, and GPU probes of the basalt_fp.metal helpers whose values the numpy emulation +(tests/kernels/basalt_emu.py) takes from the GPU. The history's moves (advance, snapshot, restore) run on words, each +binding between GUARD bytes of 0xA5 (basalt's guards, ple_parity.cpp:178-190). ``chain`` runs the whole block, row by +row, as the window op dispatches it: main's q8_1, mmvq and mmvf, then the block's kernels.""" + +import numpy as np + +from monolith import kernels +from monolith.runtime import _native as nt +from tests.kernels import basalt_gpu as gpu + +GUARD = 64 # bytes of 0xA5 on both sides of a guarded binding (16 floats) +HS = kernels.PLE_HIST * kernels.PLE_D # a history's words + + +def gr_norm(x, gamma, n_rows, n_cols, gamma_rows, eps): + """``basalt_gr_norm`` in basalt's launch (``basalt_gr_norm_macros``): ``n_rows`` rows of ``n_cols`` float32 values + ``x``, row r with row r % ``gamma_rows`` of ``gamma``, into an output that starts as 0xFF bytes; (n_rows, n_cols) + float32. The block size fixes the reduction order, so the pipeline must take a threadgroup of that size.""" + macros = kernels.basalt_gr_norm_macros(n_cols) + pso = gpu.pipeline(kernels.basalt_gr_norm_source(), "basalt_gr_norm", tuple(sorted(macros.items()))) + grid, threads = kernels.basalt_gr_norm_grid(n_rows, macros) + assert pso.max_threads_per_threadgroup >= threads, (pso.max_threads_per_threadgroup, threads) + ins = [np.ascontiguousarray(a, np.float32).tobytes() for a in (x, gamma)] + out = gpu.run(pso, ins + [4 * n_rows * n_cols], kernels.basalt_gr_norm_params(n_cols, gamma_rows, eps), 3, grid, + threads, 0xFF) + return np.frombuffer(out[2], np.float32).reshape(n_rows, n_cols) + + +def gate(key, query): + """``basalt_ple_gate`` in basalt's launch (``PLE_GRIDS["gate"]``: one threadgroup of 512 threads per stream) on the + PLE_H rows of PLE_N normalized key and query values, into gates that start as 0xFF bytes; (PLE_H,) float32. The + block size fixes the reduction order, so the pipeline must take a threadgroup of that size.""" + pso = gpu.pipeline(kernels.basalt_ple_source(), "basalt_ple_gate") + grid, threads = kernels.PLE_GRIDS["gate"] + assert pso.max_threads_per_threadgroup >= threads, (pso.max_threads_per_threadgroup, threads) + ins = [np.ascontiguousarray(a, np.float32).reshape(grid * kernels.PLE_N).tobytes() for a in (key, query)] + out = gpu.run(pso, ins + [4 * grid], kernels.basalt_ple_gate_params(), 3, grid, threads, 0xFF) + return np.frombuffer(out[2], np.float32) + + +def broadcast(value, gate): + """``basalt_ple_broadcast`` in basalt's launch: the PLE_N values times each of the PLE_H gates, into a PLE_D output + that starts as 0xFF bytes; float32.""" + pso = gpu.pipeline(kernels.basalt_ple_source(), "basalt_ple_broadcast") + ins = [np.ascontiguousarray(value, np.float32).reshape(kernels.PLE_N).tobytes(), + np.ascontiguousarray(gate, np.float32).reshape(kernels.PLE_H).tobytes()] + out = gpu.run(pso, ins + [4 * kernels.PLE_D], None, None, *kernels.PLE_GRIDS["broadcast"], 0xFF) + return np.frombuffer(out[2], np.float32) + + +def conv(hist, normalized, taps, hidden, gated): + """``basalt_ple_conv`` in basalt's launch: ``hist`` the history in basalt's layout (row r of channel c at + c * 9 + r), ``taps`` the fp16 kernel (float16 or its bits) at [k + 4 c], ``normalized``, ``hidden`` and ``gated`` + PLE_D values each; conv and result start as 0xFF bytes. Returns (conv, result), PLE_D float32 each.""" + pso = gpu.pipeline(kernels.basalt_ple_source(), "basalt_ple_conv") + d = kernels.PLE_D + + def f32(a, n): + return np.ascontiguousarray(a, np.float32).reshape(n).tobytes() + + ins = [f32(hist, kernels.PLE_HIST * d), f32(normalized, d), + np.ascontiguousarray(taps).view(np.uint16).reshape(4 * d).tobytes(), f32(hidden, d), f32(gated, d)] + out = gpu.run(pso, ins + [4 * d, 4 * d], None, None, *kernels.PLE_GRIDS["conv"], 0xFF) + return np.frombuffer(out[5], np.float32), np.frombuffer(out[6], np.float32) + + +def _words(a, n): + """``a``, 4-byte elements (float32, uint32 or int32), as rows of ``n`` uint32 words with its bits.""" + a = np.ascontiguousarray(a) + assert a.dtype.itemsize == 4, a.dtype + return a.view(np.uint32).reshape(-1, n) + + +def _guarded(payload): + """A buffer holding the bytes ``payload`` between GUARD bytes of 0xA5 on both sides (ple_parity.cpp:183-190).""" + b = nt.Buffer(gpu.device(), len(payload) + 2 * GUARD) + assert b.nbytes == len(payload) + 2 * GUARD, (b.nbytes, len(payload)) + b.fill(0xA5) + b.write(payload, GUARD) + return b + + +def _payload(b): + """A guarded buffer's payload as uint32 words, and whether both guards still hold 0xA5 (ple_parity.cpp:221-227).""" + raw = b.read(0, b.nbytes) + return np.frombuffer(raw[GUARD:-GUARD], np.uint32), raw[:GUARD] + raw[-GUARD:] == b"\xa5" * (2 * GUARD) + + +def _launch(pso, bindings, grid, params=None): + """A dispatch of ``pso`` in ``grid`` = (threadgroups, threads), binding k at ``bindings[k]`` = (buffer, byte + offset) and ``params`` (if any) at the slot after them.""" + d = nt.Dispatch().pipeline(pso) + for k, (b, offset) in enumerate(bindings): + d = d.buffer(k, b, offset) + if params is not None: + d = d.bytes(len(bindings), params) + return d.grid(grid[0]).threadgroup(grid[1]) + + +def _dispatch(name, bindings, params=None): + """``basalt_ple_`` in basalt's launch (``PLE_GRIDS[name]``), binding k at ``bindings[k]`` = (buffer, byte + offset).""" + return _launch(gpu.pipeline(kernels.basalt_ple_source(), f"basalt_ple_{name}"), bindings, kernels.PLE_GRIDS[name], + params) + + +def _submit(q, *ds): + """``ds`` in order, in one command buffer.""" + r = q.run(list(ds)) + assert not r.error, r.error + + +def advance(hist, normalized): + """``basalt_ple_advance`` on the history ``hist`` (HS words in basalt's layout, row r of channel c at c * 9 + r), + once per row of ``normalized`` (rows of PLE_D words): one dispatch, built once as basalt captures its advance + (ple_parity.cpp:195-198) and run once per row after the row is written into its normalized buffer (:206-207). + Returns the history after each run, (rows, HS) uint32, and whether every guard byte is intact.""" + rows = _words(normalized, kernels.PLE_D) + bh, bn = _guarded(_words(hist, HS).tobytes()), _guarded(bytes(4 * kernels.PLE_D)) + d, q, out = _dispatch("advance", [(bh, GUARD), (bn, GUARD)]), nt.Queue(gpu.device()), [] + for row in rows: + bn.write(row.tobytes(), GUARD) + _submit(q, d) + out.append(_payload(bh)[0]) + return np.array(out), _payload(bh)[1] and _payload(bn)[1] + + +def snapshot(hist, slot): + """``basalt_ple_snapshot``: the history ``hist`` (HS words) into slot ``slot`` of PLE_SNAP_SLOTS snapshots of HS + words, bound at the slot as the program binds it. The snapshots start as 0xA5 bytes, the slot as 0xFF bytes. + Returns the snapshots after the run, (PLE_SNAP_SLOTS, HS) uint32, and whether every guard byte is intact.""" + bs = _guarded(b"\xa5" * (4 * HS * kernels.PLE_SNAP_SLOTS)) + bs.write(b"\xff" * (4 * HS), GUARD + 4 * HS * slot) + bh = _guarded(_words(hist, HS).tobytes()) + _submit(nt.Queue(gpu.device()), _dispatch("snapshot", [(bs, GUARD + 4 * HS * slot), (bh, GUARD)])) + return _payload(bs)[0].reshape(kernels.PLE_SNAP_SLOTS, HS), _payload(bs)[1] and _payload(bh)[1] + + +def restore(hist, snap, commit): + """``basalt_ple_restore``: the history ``hist`` (HS words) from the PLE_SNAP_SLOTS snapshots ``snap`` (HS words + each) by the commit record ``commit`` (int32 words, of which the kernel reads word 1). Returns the history after + the run, HS uint32, and whether every guard byte is intact.""" + snap = _words(snap, HS) + assert snap.shape[0] == kernels.PLE_SNAP_SLOTS, snap.shape + bh, bs = _guarded(_words(hist, HS).tobytes()), _guarded(snap.tobytes()) + bc = _guarded(np.ascontiguousarray(commit, np.int32).tobytes()) + _submit(nt.Queue(gpu.device()), _dispatch("restore", [(bh, GUARD), (bs, GUARD), (bc, GUARD)])) + return _payload(bh)[0], _payload(bh)[1] and _payload(bs)[1] and _payload(bc)[1] + + +SCRATCH = { # the window op's per-row scratch (plan §3), bytes: q8_1, raw key, key norm, value, gate, gated, conv + "q8_1": kernels.PLE_N // 32 * kernels.Q8_1_BLOCK_BYTES, "key": 4 * kernels.PLE_D, "key_norm": 4 * kernels.PLE_D, + "value": 4 * kernels.PLE_N, "gate": 4 * kernels.PLE_H, "gated": 4 * kernels.PLE_D, "conv": 4 * kernels.PLE_D, +} + + +def chain(rows, hidden, hist, w, n=None, guard=False, split_query=False, inplace=False): + """basalt's per-row n-gram block (verify.cpp:1105-1124: ple_block's native branch, ple.cu:298-326, then the + history's advance and snapshot, :1118, :1123) as the window op's eleven dispatches a row (plan §3), on rows 0 to + ``n`` - 1 (default: all) of the gathered rows ``rows`` (R, PLE_N) and the hidden rows ``hidden`` (R, PLE_D), from + the history ``hist`` (HS values in basalt's layout, row r of channel c at c * 9 + r), with ``w``'s weights + (tests.basalt_ple_ref.Fixture's key, value, w_nk, w_nq, w_nc and conv1d). A row is one command buffer: + native_quantize_q8_1, basalt_mmvq (type 42) and basalt_mmvf at one column, with the pipelines, grids and params + basalt_gpu.q8_1, mmvq and mmvf launch them with; the key norm; the query norm into normalized row r; the gate; the + broadcast; the conv norm over normalized row r (basalt binds the two norms to one buffer, ple.cu:320-326); the + convolution into conv and result row r; the advance of the history; its snapshot into slot r. Rows bind at r times + their row bytes, as the program binds them, and every row shares the scratch, as basalt shares its workspace + (ple.cu:282-292). Every output starts as 0xFF bytes, the scratch again before each row. Returns a dict: per row + run, the scratch after it (``q8_1`` uint8, ``key`` the raw key, ``key_norm``, ``value``, ``gate``, ``gated``, + ``conv``) and ``hist``, the history after it, (n, ...) each; ``normalized``, ``result`` and ``snap`` (R snapshot + slots), all R rows (rows from n on as they started). The values are float32. + + ``guard``: every binding (inputs, weights, history, outputs and scratch) lies between GUARD bytes of 0xA5 and binds + after its head guard (basalt's guards, ple_parity.cpp:183-190), and ``guards`` maps each buffer's name to whether + both its guards still hold 0xA5. ``split_query``: the query norm writes its own buffer (``query``, scratch), which + the gate reads, in place of normalized row r (basalt's permitted alias query == normalized undone, + native_ple_postops.cu:344-351). ``inplace``: result binds onto hidden (basalt's in-place alias, ple_parity.cpp:957, + verify.cpp:1105-1124), and ``result`` is read back from the hidden buffer.""" + N, D, H = kernels.PLE_N, kernels.PLE_D, kernels.PLE_H + rows, hidden = _words(rows, N), _words(hidden, D) + n = len(rows) if n is None else n + assert len(hidden) == len(rows) and 1 <= n <= len(rows), (rows.shape, hidden.shape, n) + key = np.ascontiguousarray(w.key).view(np.uint8).reshape(D, -1) + assert key.shape[1] == N // 64 * 18, key.shape # type-42 rows: 40 blocks of 18 B + mq, mf = kernels.basalt_mmvq_macros(42, N, 1), kernels.basalt_mmvf_macros(N, N, 1) + nm = kernels.basalt_gr_norm_macros(N) + q81 = gpu.pipeline(kernels.basalt_q8_1_source(), "native_quantize_q8_1") + mmvq = gpu.pipeline(kernels.basalt_mmvq_source(), "basalt_mmvq", tuple(sorted(mq.items()))) + mmvf = gpu.pipeline(kernels.basalt_mmvf_source(), "basalt_mmvf", tuple(sorted(mf.items()))) + norm = gpu.pipeline(kernels.basalt_gr_norm_source(), "basalt_gr_norm", tuple(sorted(nm.items()))) + grids = (kernels.basalt_q8_1_grid(N), kernels.basalt_mmvq_grid(mq, D), kernels.basalt_mmvf_grid(mf, N), + kernels.basalt_gr_norm_grid(H, nm)) + assert grids == ((10, 256), (2560, 128), (2560, 256), (4, 1024)), grids # plan §3's one-column launches + gate_pso = gpu.pipeline(kernels.basalt_ple_source(), "basalt_ple_gate") + for pso, threads in ((norm, grids[3][1]), (gate_pso, kernels.PLE_GRIDS["gate"][1])): + assert pso.max_threads_per_threadgroup >= threads, (pso.max_threads_per_threadgroup, threads) + r_all, pad = len(rows), GUARD if guard else 0 + scratch = {**SCRATCH, **({"query": 4 * D} if split_query else {})} + data = { # each binding's bytes, or its size for one that starts as 0xFF bytes + "rows": rows.tobytes(), "hidden": hidden.tobytes(), "hist": _words(hist, HS).tobytes(), + **{k: _words(getattr(w, k), D).tobytes() for k in ("w_nk", "w_nq", "w_nc")}, "w_key": key.tobytes(), + "w_value": np.ascontiguousarray(w.value).view(np.uint16).reshape(N * N).tobytes(), + "taps": np.ascontiguousarray(w.conv1d).view(np.uint16).reshape(4 * D).tobytes(), + "normalized": 4 * r_all * D, "snap": 4 * r_all * HS, **({} if inplace else {"result": 4 * r_all * D}), + **scratch} + data = {k: b"\xff" * v if isinstance(v, int) else v for k, v in data.items()} + b = {k: _guarded(v) if guard else nt.Buffer(gpu.device(), v) for k, v in data.items()} + if inplace: + b["result"] = b["hidden"] + + def at(k, offset=0): + return b[k], pad + offset + + def payload(k): + return b[k].read(pad, b[k].nbytes - 2 * pad) + + s = {k: at(k) for k in scratch} + q81_p, mmvq_p, mmvf_p = (kernels.basalt_q8_1_params(N), kernels.basalt_mmvq_params(N, D), + kernels.basalt_mmvf_params(N, N, 1)) + norm_p, gate_p = kernels.basalt_gr_norm_params(N, H, kernels.PLE_RMS_EPS), kernels.basalt_ple_gate_params() + q, out = nt.Queue(gpu.device()), {k: [] for k in (*scratch, "hist")} + for r in range(n): + for k in scratch: + b[k].write(data[k], pad) + x, h = at("rows", 4 * N * r), at("hidden", 4 * D * r) + nr, res = at("normalized", 4 * D * r), at("result", 4 * D * r) + qr = s["query"] if split_query else nr + _submit(q, + _launch(q81, [x, s["q8_1"]], grids[0], q81_p), # ple.cu:298-299 + _launch(mmvq, [at("w_key"), s["q8_1"], s["key"]], grids[1], mmvq_p), # :300-301 + _launch(mmvf, [x, at("w_value"), s["value"]], grids[2], mmvf_p), # :312-313 + _launch(norm, [s["key"], at("w_nk"), s["key_norm"]], grids[3], norm_p), # postops.cu:352 + _launch(norm, [h, at("w_nq"), qr], grids[3], norm_p), # :353 + _dispatch("gate", [s["key_norm"], qr, s["gate"]], gate_p), # :355 + _dispatch("broadcast", [s["value"], s["gate"], s["gated"]]), # :356 + _launch(norm, [s["gated"], at("w_nc"), nr], grids[3], norm_p), # :358 + _dispatch("conv", [at("hist"), nr, at("taps"), h, s["gated"], s["conv"], res]), # :359 + _dispatch("advance", [at("hist"), nr]), # verify.cpp:1118 + _dispatch("snapshot", [at("snap", 4 * HS * r), at("hist")])) # :1123 + for k in out: + out[k].append(payload(k)) + got = {k: np.frombuffer(b"".join(v), np.uint8 if k == "q8_1" else np.float32).reshape(n, -1) + for k, v in out.items()} + for k in ("normalized", "result", "snap"): + got[k] = np.frombuffer(payload(k), np.float32).reshape(r_all, -1) + if guard: + got["guards"] = {k: _payload(v)[1] for k, v in b.items()} + return got + + +def _helper(name, x): + """basalt_fp.metal's float helper ``name`` on the GPU, elementwise (basalt_gpu.expf_ftz's pattern).""" + src = kernels.PRELUDE + kernels.template("basalt_fp.metal") + f""" +kernel void probe(device const float* x [[buffer(0)]], device float* y [[buffer(1)]], constant uint& n [[buffer(2)]], + uint i [[thread_position_in_grid]]) {{ + if (i < n) y[i] = {name}(x[i]); +}} +""" + x = np.ascontiguousarray(x, np.float32) + flat = x.reshape(-1) + out = gpu.run(gpu.pipeline(src, "probe"), [flat.tobytes(), 4 * flat.size], np.uint32(flat.size).tobytes(), 2, + -(-flat.size // 256), 256, 0xFF) + return np.frombuffer(out[1], np.float32).reshape(x.shape) + + +def rsqrtf_ftz(x): + """basalt_fp.metal's rsqrtf_ftz (``rsqrtf`` in a fast-math file) on the GPU, elementwise: the values the norm + uses.""" + return _helper("rsqrtf_ftz", x) + + +def sqrtf_ftz(x): + """basalt_fp.metal's sqrtf_ftz (``sqrtf`` in a fast-math file) on the GPU, elementwise: the values the gate uses.""" + return _helper("sqrtf_ftz", x) diff --git a/tests/kernels/test_basalt_mmvf.py b/tests/kernels/test_basalt_mmvf.py index 0a6b1594..5d44bc49 100644 --- a/tests/kernels/test_basalt_mmvf.py +++ b/tests/kernels/test_basalt_mmvf.py @@ -18,10 +18,12 @@ 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. + fixture's ple_value, and the test runs only with PLE_FIXTURE_DIR; here it runs on two: [synthetic], + route_window_parity's bf16(N(0, 1) * 0.05), and [real], the pack's dense blk.1.ple_value.weight + (tests/basalt_ple_ref.py's ``real()``, from the ranges under $BASALT_PLE_FIXTURE: unset, the case skips with a reason + naming the variable; set, a file missing or of the wrong size fails). 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 @@ -35,6 +37,7 @@ import pytest from monolith import kernels +from tests.basalt_ple_ref import real from tests.kernels import basalt_emu as emu from tests.kernels import basalt_gpu as gpu @@ -92,30 +95,32 @@ def gt(x, t): return bool(np.isfinite(x) and x > t) # ple_parity.cpp:49 -def test_ple_value_float64(): +@pytest.mark.parametrize("name", ["synthetic", "real"]) +def test_ple_value_float64(name): nd = 2560 rng = np.random.default_rng(790) - w = bf16_weights(rng, nd, nd) + w = bf16_weights(rng, nd, nd) if name == "synthetic" else real().value 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): + def check(native, x, row): 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) + assert le(rel, 2e-6) and nf == 0 and gt(separation, 1e-5), ( + "`const bool correct = le(rel, 2e-6) && nf == 0 && gt(separation, 1e-5);` (ple_parity.cpp:815), " + f"{name} weights, {row}: rel {rel!r}, non-finite {nf}, separation {separation!r}") return rel - rels = [check(gpu.mmvf(w, witness, nd, nd, fill=0xFE), witness)] + rels = [check(gpu.mmvf(w, witness, nd, nd, fill=0xFE), witness, "the one-row kernel")] 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}") + rels += [check(y[k], x[k], f"the multi kernel at T = {t}, row {k}") for k in range(t)] + print(f"ple value rel_l1 [{name}]: max {max(rels):.3e}") @pytest.mark.parametrize("n_in", [2560, 64, 130], ids=["block256", "block32", "block96"]) diff --git a/tests/kernels/test_basalt_nan.py b/tests/kernels/test_basalt_nan.py index 668c7d76..3d8e59c4 100644 --- a/tests/kernels/test_basalt_nan.py +++ b/tests/kernels/test_basalt_nan.py @@ -6,22 +6,29 @@ 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).""" +other value has the same bits. The drafter experts' stores have their own tests (test_basalt_s2_experts.py). The +n-gram block's (basalt_gr_norm.metal, basalt_ple.metal) plant a quiet NaN in one input and also require that it reaches +exactly the values it must (the non-finite count) and that every other value keeps the bits of the run without it.""" import numpy as np import pytest from monolith import kernels +from tests.basalt_ple_ref import D, EPS, H, HIST, N, ROWS, nonfinite from tests.kernels import basalt_emu as emu from tests.kernels import basalt_gpu as gpu +from tests.kernels import basalt_ple_gpu as ple_gpu from tests.kernels.test_basalt_experts import Call from tests.kernels.test_basalt_mmvq import SCALES, weights +from tests.kernels.test_basalt_ple import block 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 +QNAN = 0x7FC00000 # the quiet NaN planted in the n-gram block's inputs 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") + "basalt_mmvf_source", "basalt_dense_tc_source", "basalt_q5k_head_source", "basalt_gr_norm_source", + "basalt_ple_source") @pytest.fixture @@ -310,3 +317,68 @@ def test_q5k_proxy_score(hw): at = np.zeros_like(cand, bool) at[1, 0, 0] = True check(cand, ccand, at) + + +# ---- the n-gram block ---------------------------------------------------------------------------------------------- + +def exactly(got, ctl, clean, at): + """``check``, then the comparison helper's non-finite count over ``got`` (``nonfinite``, ple_parity.cpp:52-57) + equal to the size of ``at``, and every value outside ``at`` with the bits of the run without the NaN, ``clean``. + Returns the count.""" + n = check(got, ctl, at) + assert nonfinite(got) == n, ( + "X-NF (spec T§8), \"The comparison helper's non-finite count over result must equal the size of that set\": " + f"{nonfinite(got)} non-finite values, {n} reached") + g, c = (np.ascontiguousarray(a, F32).view(np.uint32) for a in (got, clean)) + assert np.array_equal(g[~at], c[~at]), "a value the NaN does not reach changed its bits" + return n + + +@pytest.mark.parametrize("row", [0, 4, 8]) +def test_ple_conv(hw, row): + """The 12-row chain (basalt_ple_gpu.chain) on the synthetic fixture with history element (channel i, row ``row``) + a quiet NaN: only basalt_ple_conv reads the history, and row t's taps read rows t, t + 3 and t + 6 of the initial + history though it advances in place, so the NaN reaches exactly conv[t][i] and result[t][i] for t in {row, + row - 3, row - 6} ∩ [0, 12) (plan §4.8: "each count equals that set's size, and those values are 0x7fffffff").""" + fx, _, clean = block("synthetic") + i = 2 * N + 777 # a channel of stream 2 + hist = np.ascontiguousarray(fx.hist.T).ravel() # a copy: row r of channel c at c * 9 + r + hist.view(np.uint32)[i * HIST + row] = QNAN + run = lambda: ple_gpu.chain(fx.emb, fx.hidden, hist, fx) + got, ctl = run(), hw(run) + reached = [t for t in (row, row - 3, row - 6) if 0 <= t < ROWS] + at = np.zeros((ROWS, D), bool) + at[reached, i] = True + for k in ("conv", "result"): + assert exactly(got[k], ctl[k], clean[k], at) == len(reached), ( + f"plan §4.8, \"each count equals that set's size\": {k}, t in {reached}") + + +def test_ple_norm(hw): + """basalt_gr_norm at the block's call (4 groups of 2560, 4 gamma rows, eps f32(1e-6)) with element 1234 of group 2 + a quiet NaN: the group's sum and scale are NaN, so it reaches exactly that group's 2560 outputs, and every other + group keeps its bits.""" + rng = np.random.default_rng(10) + x, w = rng.standard_normal((H, N)).astype(F32), (1 + 0.1 * rng.standard_normal(D)).astype(F32) + clean = ple_gpu.gr_norm(x, w, H, N, H, EPS) + x.view(np.uint32)[2, 1234] = QNAN + run = lambda: ple_gpu.gr_norm(x, w, H, N, H, EPS) + got, ctl = run(), hw(run) + at = np.zeros((H, N), bool) + at[2] = True + assert exactly(got, ctl, clean, at) == N, ( + "plan §4.8, \"It reaches exactly that group's 2560 outputs; every other group keeps its bits.\"") + + +def test_ple_broadcast(hw): + """basalt_ple_broadcast with value[1234] a quiet NaN: it reaches exactly gated[s][1234] for the four streams s.""" + rng = np.random.default_rng(11) + value, gate = rng.standard_normal(N).astype(F32), rng.uniform(0.1, 0.9, H).astype(F32) + clean = ple_gpu.broadcast(value, gate).reshape(H, N) + value.view(np.uint32)[1234] = QNAN + run = lambda: ple_gpu.broadcast(value, gate).reshape(H, N) + got, ctl = run(), hw(run) + at = np.zeros((H, N), bool) + at[:, 1234] = True + assert exactly(got, ctl, clean, at) == H, ( + "plan §4.8, \"It reaches exactly `gated[s][j]` for the four streams s.\"") diff --git a/tests/kernels/test_basalt_platform.py b/tests/kernels/test_basalt_platform.py index a0bf9d43..ae7f659a 100644 --- a/tests/kernels/test_basalt_platform.py +++ b/tests/kernels/test_basalt_platform.py @@ -3,10 +3,11 @@ # 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).""" +fp32 add, multiply, fma and division round to nearest even; how they and the compares treat subnormals; the +``metal::fast`` limits at infinity; 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 @@ -229,3 +230,86 @@ def test_half_conversions(): 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 + + +def test_compares_read_subnormals_as_zero(): + """Measured: ``<``, ``>`` and ``==`` read a subnormal operand as the zero of its sign, so two subnormals, or a + subnormal and a zero, compare equal; NaN is unordered and -0 equals +0, as IEEE says. The model is IEEE's compare + of the flushed operands, on every row. That is CUDA's setp with .ftz, so a --use_fast_math file's compares are + ported as plain ones (the n-gram gate's sign, src/kernels/cuda/native_ple_postops.cu:64: setp.gt.ftz and + setp.lt.ftz; docs/research/basalt-nvcc/ple.md section 2); setp without .ftz orders subnormals exactly.""" + dev = nt.Device() + src = kernels.PRELUDE + kernels.template("basalt_fp.metal") + """ +kernel void cmp(device const float* a [[buffer(0)]], device const float* b [[buffer(1)]], + device uint* out [[buffer(2)]], constant uint& n [[buffer(3)]], uint i [[thread_position_in_grid]]) { + if (i >= n) return; + const float x = a[i], y = b[i]; + out[i] = uint(x < y) | (uint(x > y) << 1) | (uint(x == y) << 2); +} +""" + pso = nt.Pipeline(nt.Library(dev, src, {}), "cmp") + s, s2, m = 1.5e-39, 3e-39, 2.0 ** -126 # subnormals s < s2; the smallest normal + nan, inf = np.nan, np.inf + planted = np.array([(s, 0), (0, s), (s, s2), (-s, 0), (s, -s), (-s, -0.0), (s2, -s2), (m, s), (s, m), (m, 0), + (0, -0.0), (nan, nan), (nan, s), (s, nan), (inf, s), (-inf, -s)], F32) + rng = np.random.default_rng(5) + n = 1 << 16 + low = lambda: normals(rng, n, 0, 3) # subnormals (or zeros) and the two lowest binades + a = np.r_[planted[:, 0], low(), rng.integers(0, 1 << 32, n, dtype=np.uint64).astype(np.uint32).view(F32)] + b = np.r_[planted[:, 1], low(), rng.integers(0, 1 << 32, n, dtype=np.uint64).astype(np.uint32).view(F32)] + out = nt.Buffer(dev, 4 * len(a)) + d = nt.Dispatch().pipeline(pso).buffer(0, nt.Buffer(dev, a.tobytes())).buffer(1, nt.Buffer(dev, b.tobytes())) + d = d.buffer(2, out).bytes(3, np.uint32(len(a)).tobytes()).grid(-(-len(a) // 256)).threadgroup(256) + r = nt.Queue(dev).run([d]) + assert not r.error, r.error + got = np.frombuffer(out.read(0, 4 * len(a)), np.uint32) + code = lambda x, y: (x < y).astype(np.uint32) | ((x > y).astype(np.uint32) << 1) | ((x == y).astype(np.uint32) << 2) + lt, gt, eq = 1, 2, 4 + # the planted rows: subnormals are zeros of their sign to the compare; NaN unordered; -0 == +0; normals ordered + assert got[: len(planted)].tolist() == [eq, eq, eq, eq, eq, eq, eq, gt, lt, gt, eq, 0, 0, 0, gt, lt] + assert np.array_equal(got, code(emu.ftz(a), emu.ftz(b))) + assert np.count_nonzero(got != code(a, b)) > n // 16 # IEEE's compare of the same bits differs on many rows + + +def test_fast_limits_at_infinity(): + """Measured: the ``metal::fast`` functions invariant 5 maps MUFU.RSQ, MUFU.SQRT and MUFU.EX2 to return those + instructions' limits at infinity (docs/research/basalt-nvcc/ple.md section 6): rsqrt(+inf) = +0, sqrt(+inf) = +inf, + exp2(+inf) = +inf and exp2(-inf) = +0. Beyond the float range exp2 gives the limits as well: exp2(x) = +inf for + every x >= 128, and ftz(exp2(x)) = +0 for every x <= -150. The norm's scale of an infinite row, the gate of an + infinite s and the SiLU whose -acc * log2(e) leaves the float range rest on them. Checked bit for bit on every float + of [128, 129) and of (-151, -150], 2^16 random floats of each sign and every exponent from 2^7 to 2^127, the largest + finite floats and the infinities.""" + dev = nt.Device() + src = kernels.PRELUDE + kernels.template("basalt_fp.metal") + """ +kernel void lim(device const float* a [[buffer(0)]], device float* out [[buffer(1)]], constant uint& n [[buffer(2)]], + uint i [[thread_position_in_grid]]) { + if (i >= n) return; + const float x = a[i]; + device float* o = out + 4 * i; + o[0] = fast::rsqrt(x); + o[1] = fast::sqrt(x); + o[2] = fast::exp2(x); + o[3] = ftz(fast::exp2(x)); +} +""" + pso = nt.Pipeline(nt.Library(dev, src, {}), "lim") + rng = np.random.default_rng(6) + big = np.finfo(F32).max + edge = np.arange(0x43000000, 0x43010000, dtype=np.uint32).view(F32) # [128, 129) + edge_neg = np.arange(0xC3160000, 0xC3170000, dtype=np.uint32).view(F32) # (-151, -150] + far = np.abs(normals(rng, 1 << 16, 134, 255)) # [128, 2^128) + x = np.r_[np.array([np.inf, -np.inf, big, -big], F32), edge, edge_neg, far, -far] + n = len(x) + out = nt.Buffer(dev, 16 * n) + d = nt.Dispatch().pipeline(pso).buffer(0, nt.Buffer(dev, x.tobytes())).buffer(1, out) + d = d.bytes(2, np.uint32(n).tobytes()).grid(-(-n // 256)).threadgroup(256) + r = nt.Queue(dev).run([d]) + assert not r.error, r.error + bits = np.frombuffer(out.read(0, 16 * n), np.uint32).reshape(n, 4) + pos0, inf = 0x00000000, 0x7F800000 + over, under = x >= 128, x <= -150 + assert x[4] == 128 and x[4 + len(edge)] == -150 and min(np.count_nonzero(over), np.count_nonzero(under)) > 1 << 16 + assert bits[0, 0] == pos0 and bits[0, 1] == inf # rsqrt(+inf) = +0, sqrt(+inf) = +inf + assert bits[0, 2] == inf and bits[1, 2] == pos0 # exp2(+inf) = +inf, exp2(-inf) = +0 + assert np.all(bits[over, 2] == inf) # exp2(x) = +inf for x >= 128 + assert np.all(bits[under, 3] == pos0) # ftz(exp2(x)) = +0 for x <= -150 diff --git a/tests/kernels/test_basalt_ple.py b/tests/kernels/test_basalt_ple.py new file mode 100644 index 00000000..cfc90cf6 --- /dev/null +++ b/tests/kernels/test_basalt_ple.py @@ -0,0 +1,674 @@ +# SPDX-License-Identifier: MIT +# Copyright (c) 2026 Jesús Gulfo +# adapted from basalt (jesdga95/basalt) src/kernels/ple_parity.cpp, src/kernels/ple_win_parity.cpp and +# src/kernels/gr_parity.cpp @ b4c63b55754637f4c72ad53a0f791d425f71eb36 (MIT; third_party/NOTICE): ple_parity's history +# regression with its guards (:177-228), key-row check (:617-637), block check with its seven stages and its log line +# (:740-783), native key projection check with its host norm, metric and pass criterion (:892-912) and its guards +# (:930-937), separate-exports and in-place result check with its log line (:949-969), host reference check's +# per-stage pass criterion and log line (:1114-1122) and conv cancellation metric (:1139-1165), ple_win_parity's +# projected-form input scales (:47-55), and gr_parity's scalar activation contract's degenerate norm input and the +# exactness it relies on (:167-236). +"""The n-gram (PLE) block's Metal port on the GPU, kernel by kernel (kernels/common/basalt_gr_norm.metal and +basalt_ple.metal) and as the per-row chain (``basalt_ple_gpu.chain``: main's q8_1, mmvq and mmvf, then those kernels, +row by row, as the window op dispatches them). Each norm call runs at its call sites' shape, 4 rows of 2560 with 4 +gamma rows and eps = f32(1e-6) (native_ple_postops.cu:352-353, :358), unless stated. + +- T-NORM ``test_grouped_norm_float64`` (spec T§7.2): basalt_gr_norm against R-struct's float64 ``gnorm`` + (tests/basalt_ple_ref.py), criterion quoted: + ``const bool wired = le(rel, 2e-6) && nonfinite(actual_result.data(), hcd) == 0;`` (ple_parity.cpp:910), rel = + rel_l1(reference, GPU) over one call's 4 x 2560 outputs and the non-finite count over the norm's own output (basalt + counted it over the block's result). The calls: N(0, σ) rows for σ in {1e-3, 1e-2, 1, 1e2} (at 1e-3 the mean square + is about eps) and a zero row, whose output is 0, each with weights f32(1 + 0.1 N(0, 1)); and "the GPU's raw key, + hidden and the GPU's gated rows from the 12-row C3 fixtures, synthetic and real" (``C3_NORMS``), one call per row + at each of the norm's call sites: the chain's raw key with w_nk, the fixture's hidden with w_nq and the chain's + gated row with w_nc (``block``). +- T-NORM ``test_grouped_norm_bitwise_emu``: bit for bit against R-emu, ``basalt_emu.gr_norm`` (the rounding sequence of + docs/research/basalt-nvcc/ple.md section 1) with the GPU's rsqrtf_ftz (MUFU.RSQ and fast::rsqrt have no bit-exact + host model), on the calls above plus a row whose squares all lie below 2^-126, each of which .FTZ turns into +0; and + on G1a, gr_parity's degenerate input (gr_parity.cpp:169-201: GrShapes{2, 1, 2}, so one row of 2 columns and the + 256-thread block; R = 1, eps = 0, gamma in {1.0f, 1.00390625f}). There, "At R=1 and eps=0, xn=gamma exactly" + (:169), which basalt's exact checks rely on (:233-236): the scale is rsqrtf(1) and the output equals gamma bit for + bit, provided the GPU's fast::rsqrt(1.0f) is exactly 1.0f. A failure there is a departure from basalt, to record, + not to tune away. +- T-POST ``test_postops_bitwise_emu`` (spec T§7.3): native_ple_postops (native_ple_postops.cu:352-359) one token at a + time, launch by launch (the key and query norms, basalt_ple_gate, basalt_ple_broadcast, the conv norm and + basalt_ple_conv), each launch bit for bit against R-emu (``basalt_emu.gr_norm``, ``ple_gate``, ``ple_broadcast`` and + ``ple_conv``: ple.md sections 1-4, with the GPU's rsqrtf_ftz, sqrtf_ftz and expf_ftz evaluated on the emulation's + own arguments) fed the GPU's outputs of the launches before it, so that each comparison is its own kernel's: T§7.3 + "compares all six stages of every row of every fixture above with R-emu, byte for byte" (the query norm is compared + too). The fixtures: T§7.3's three 12-row fixtures, each row in order from the GPU's history before it + (``postops_rows``): the projected form at W1's scales (``projected``), its history the initial one, then each row's + GPU normalized row shifted in; C3's fixtures' GPU projections, synthetic and real, each row's raw key and value the + chain's (``block``) and its history the initial one, then the chain's snapshot of the row before; and T§7.3's + edge cases. The gate's are streams of a direct basalt_ple_gate call + (``GATE_EDGES``): s = +0 and s = -0 (sign 0, so the gate is exactly the sigmoid of 0, 0.5), 0 < |s| < 1e-6 (the + clamp: the same gate as |s| = 1e-6f), |s| = 1e-6f, and |s| = 2e4 (the sigmoid saturates at 1, and at 0 where + fast::exp2 overflows). The others are the projected form's first row with inputs planted (``EDGE_ROWS``): a SiLU + whose fast::exp2 overflows (act = acc * rcp(inf) = -0), subnormal key, value, hidden and history inputs (read as + zero under the flush) beside fp16-subnormal taps (widened exactly), and gated products below 2^-126 (flushed). +- T-POST ``test_postops_float64`` (spec T§7.3): those three 12-row fixtures' GPU stages, row by row, against + R-contract (``r_contract``) fed the row's own inputs, the raw key, the value, hidden and the GPU's history before + the row, so that "each row's comparison therefore isolates that row's arithmetic" (propagation across rows is C3's), + criterion quoted: ``const bool ok = le(rel, 1e-4) && nf == 0;`` (ple_parity.cpp:1119), rel and nf = + rel_l1(R-contract, GPU) per row and stage, on the six stages key (normed), gate, gated, normalized, conv_out and + result (the value is an input), logged in :1120-1121's format; and "Each fixture asserts min |s[c]| ≥ 0.1 on + R-contract". +- H1, T-HIST ``test_history_advance_12_steps`` (spec T§7.4): ple_parity's history regression (ple_parity.cpp:177-214) + as written, on basalt_ple_advance: the initial history ``expected[c * rows + r] = -float(c * 16 + r + 1)`` + (row-fastest) and 12 tokens of ``normalized[c] = float((token + 1) * 1000000 + c)``, one dispatch built once and run + once per token (basalt captures its advance once and replays it, :195-207), each run followed by the host shift + (:203-204) and the criterion, quoted: ``if (std::memcmp(actual.data(), expected.data(), count * sizeof(float)) != 0) + {`` (:210), then ``++bad;`` (:212). Its refusals (H2) are the emitter's, its guards (H3) X-GUARD's. +- X-H ``test_history_moves_bits`` (spec T§8): H1's run with fp32 subnormals (0x00000001, 0x807fffff), -0.0, +-inf, a + quiet NaN with a payload (0x7fc00001) and a signalling NaN (0x7f800001) planted in every token's normalized row, as + words, so that they pass through every history row: "every pattern survives the history's moves bit for bit + (memcmp, as H1)", the advance, then basalt_ple_snapshot of the GPU's histories, then basalt_ple_restore from the + GPU's snapshots into a history that differs from each of them at every word. +- T-COPY ``test_snapshot_copy_exact`` and ``test_commit_restore_exact`` (spec T§7.5), byte for byte (the precedent + ``if (ra != rb) {``, dec_commit_parity.cpp:177), every guard byte intact: the snapshot into each slot equals its + source and leaves the other slots' 0xA5; the restore by the commit record's word 1 (``commit_record``: every + (T, n_keep) with n_keep - 1 = word 1 has the same record, so words 0 to 7 cover T = 1..8 and n_keep = 1..T) equals + that slot, a negative word leaves the history unchanged, and a word above 7 restores slot 7 (the port's bound, plan + D5). The words are slot-tagged random words (``copy_words``), so that a missed, stray or misplaced store shows. +- C8 ``test_key_projection_into_grouped_norm`` (ple_parity.cpp:892-912, spec T§6.4), on every row of C3's fixtures + (basalt runs two): the raw key of basalt's native_q2_0_f32, native_quantize_q8_1 then native_mmvq type 42 at one + column (basalt_gpu.q8_1 and mmvq), is the chain's own bit for bit, and so are its q8_1 image and its value + (basalt_gpu.mmvf): the chain composes main's kernels. Then the chain's key norm against the host norm of that raw + key (:899-904, ``host_norm``), criterion quoted: + ``const bool wired = le(rel, 2e-6) && nonfinite(actual_result.data(), hcd) == 0;`` (:910), rel = rel_l1(host norm, + GPU key norm), the non-finite count over the row's result. +- C3 ``test_block_vs_float64_graph[synthetic]``, ``[real]`` (ple_parity.cpp:740-783, spec T§6.4): the chain over + T§6.3's fixtures, 12 rows from one initial history (the key's Q8_1 rounding the only contract between them), against + R-struct, rel = rel_l1(R-struct, GPU) per row and stage (the capture's seven slices), criterion quoted: + ``if (last && !le(rel, 1e-2)) ++bad;`` (:782), on result. The other six stages are logged in :771-772's format, + with the row's block share (T§6.3 rule 3) and C16's metric (:1139-1165), never gated: the conv_out error against + its terms' magnitude, sum |R-struct - GPU| / sum_c sum_k |w v| and sum |R-struct| / sum_c sum_k |w v|, the terms + w v from R-struct's taps and padded rows. Every stage's non-finite count must be 0 (spec T§8, X-NF rule 1). +- C1 ``test_real_key_row0_decodes_like_ggml`` (ple_parity.cpp:617-637, spec T§6.4), real weights only: the committed + row 0 of the key (720 B of type-42 blocks) decoded by basalt_dequant_f32 (basalt_gpu.dequant) against ggml's + dequantize_row_q2_0 of the same bytes (tests/contract/gguf_reference.py's ``q2_0``), criterion quoted: + ``if (!le(worst, 0.0) || nf) ++bad;`` (:636), worst the NaN-safe largest |GPU - ggml| and nf the non-finite pairs; + the decoded row finite with 1e-4 < rms < 10 (weights, not padding: tests/contract/test_basalt_pack.py's + ``test_real_rows_match_the_reference``); and row 0 of the key the real fixture binds (gguf/blk.1.ple_key.weight, cut + from its full range at T§5's offset) equal to the committed slice, byte for byte. +- X-INPLACE ``test_compact_build_equals_full_exports`` (ple_parity.cpp:949-969, spec T§8), on C3's fixtures, every row: + the chain as the handler binds it (``block``) against two other bindings of the same 12 rows, criterion quoted: + ``const bool equal = std::memcmp(compact_norm.data(), dev_norm.data(), hcd * sizeof(float)) == 0 && + std::memcmp(compact_result.data(), dev_res.data(), hcd * sizeof(float)) == 0;`` (:963-964), then + ``if (!equal) ++bad;`` (:966), with :965's log line. (1) Query and normalized as one buffer against two buffers + (``split_query``): gate, gated, normalized and result equal. (2) Result bound onto hidden, basalt's in-place alias + (``inplace``), against out of place: normalized and result equal. The conv store is kept (plan D3), so there is no + compact build to compare. +- X-GUARD ``test_store_bounds_guards`` (H3, ple_parity.cpp:221-228; C10, :930-937; spec T§8): the chain's guard run + (``basalt_ple_gpu.chain(..., guard=True)``: every binding of every kernel, the rows, hidden, weights, history, + snapshots, outputs and scratch, between 64 B of 0xA5) of a T-row window, T = 1..8, of the synthetic fixture over + buffers of T_MAX rows and slots, as the T = 8 program's row I/O and its snapshots, then the commit's restore of + n_keep = 1 into the window's history (``basalt_ple_gpu.restore``, its three bindings guarded too). Criteria quoted: + ``if (!guard_ok(history_storage, count) || !guard_ok(norm_storage, channels)) ++bad;`` (:228) and + ``if (!std::all_of(ends.begin(), ends.end(), [](uint8_t x) { return x == 0xa5; })) ++bad;`` (:936), for every + buffer; "rows from T to T_MAX − 1 of every multi-row output still hold their sentinel" (T§8), 0xFF in normalized, + result and the snapshots; and rows below T equal the exact-size run's (``block``) byte for byte, so the guards and + offsets change nothing else. The exact-size half is every test's validated pass (plan §4.9).""" + +import functools + +import numpy as np +import pytest + +from monolith import kernels +from tests.basalt_ple_ref import (D, DIL, EPS, H, HIST, KERN, KEY_BLOCK, N, ROWS, STAGES, T_MAX, Fixture, + commit_record, committed, gnorm, h_oracle, host_norm, le, nonfinite, r_contract, + r_struct, real, real_tensors, rel_l1, synthetic, taps) +from tests.contract.gguf_reference import q2_0 +from tests.kernels import basalt_emu as emu +from tests.kernels import basalt_gpu as gpu +from tests.kernels import basalt_ple_gpu as ple_gpu + +F32, F64 = np.float32, np.float64 +SIGMAS = (1e-3, 1e-2, 1.0, 1e2) +NORM_SEED = 910 # default_rng(NORM_SEED) draws, in order: each σ's row then its weights, the zero row's weights, + # then the tiny row and its weights +TINY = "squares below 2^-126" + + +def norm_calls(): + """The standalone norm calls, ``{id: (x, w)}``, each a D-vector (4 rows of 2560) with its own weights: spec T§7.2's + N(0, σ) rows and zero row, then the tiny row, f32(N(0, 1) 2^-70): normal values whose squares all lie below + 2^-126 (asserted).""" + rng = np.random.default_rng(NORM_SEED) + + def weights(): + return (1 + 0.1 * rng.standard_normal(D)).astype(F32) + + calls = {} + for s in SIGMAS: + x = (s * rng.standard_normal(D)).astype(F32) + calls[f"sigma={s:g}"] = x, weights() + calls["zero"] = np.zeros(D, F32), weights() + tiny = (rng.standard_normal(D) * 2.0 ** -70).astype(F32) + normal, small = (np.abs(tiny) >= 2.0 ** -126).all(), (np.square(tiny.astype(F64)) < 2.0 ** -127).all() + assert normal and small, "the tiny row: normal values, squares below 2^-127" + calls[TINY] = tiny, weights() + return calls + + +CALLS = norm_calls() +# G1a: (x, gamma, n_rows, n_cols, gamma_rows, eps) for gr_parity's n_embd = 2, hc = 1 norm at R = 1, eps = 0 +G1A = {f"G1a gamma={g}": (np.ones(2, F32), np.full(2, g, F32), 1, 2, 1, 0.0) for g in (1.0, 1.00390625)} +BITWISE = {**{k: (x, w, H, N, H, EPS) for k, (x, w) in CALLS.items()}, **G1A} +C3_NORMS = { # call: (C3's fixture, the norm's call site), one call per row of the fixture (spec T§7.2) + f"{name} {site}": (name, site) for name in ("synthetic", "real") for site in ("raw key", "hidden", "gated")} + + +def bits(a): + return np.ascontiguousarray(a, F32).view(np.uint32) + + +def norm_rows(call): + """``C3_NORMS[call]``'s 12 norm calls, ``[(x, w)]``: the rows of C3's fixture (``block``) at the call site, the + chain's raw key with w_nk (the key norm's), the fixture's hidden with w_nq (the query norm's) or the chain's gated + row with w_nc (the conv norm's).""" + name, site = C3_NORMS[call] + fx, _, out = block(name) + x, w = {"raw key": (out["key"], fx.w_nk), "hidden": (fx.hidden, fx.w_nq), "gated": (out["gated"], fx.w_nc)}[site] + return [(row, w) for row in x] + + +@pytest.mark.parametrize("call", [k for k in CALLS if k != TINY] + list(C3_NORMS)) +def test_grouped_norm_float64(call): + calls, bad = [CALLS[call]] if call in CALLS else norm_rows(call), [] + for i, (x, w) in enumerate(calls): + actual = ple_gpu.gr_norm(x, w, H, N, H, EPS) + rel = rel_l1(gnorm(x, w), actual)[0] + nf = nonfinite(actual) + print(f"grouped norm [{call}]{f' row {i}' if call in C3_NORMS else ''}: rel {rel:.3e}, nf {nf}") + if not (le(rel, 2e-6) and nf == 0): + bad.append((i, float(rel), nf)) + assert not bad, ( + "`const bool wired = le(rel, 2e-6) && nonfinite(actual_result.data(), hcd) == 0;` (ple_parity.cpp:910), rel = " + "rel_l1(R-struct's gnorm, the GPU) over the call's 4 x 2560 outputs, nf over the norm's output: (call, rel, " + f"nf) {bad}") + if call == "zero": + assert (actual == 0).all(), f"spec T§7.2, a zero row: \"the output is 0\": {actual[actual != 0][:8]}" + + +@pytest.mark.parametrize("call", list(BITWISE) + list(C3_NORMS)) +def test_grouped_norm_bitwise_emu(call): + calls = [BITWISE[call]] if call in BITWISE else [(x, w, H, N, H, EPS) for x, w in norm_rows(call)] + for i, (x, w, *shape) in enumerate(calls): + got = ple_gpu.gr_norm(x, w, *shape) + want = emu.gr_norm(x, w, *shape, ple_gpu.rsqrtf_ftz) + diff = np.flatnonzero(bits(got) != bits(want)) + assert diff.size == 0, ( + f"T-NORM, bit for bit against basalt_emu.gr_norm (ple.md section 1): call {i}: {diff.size} of {got.size} " + f"outputs differ; first at {diff[:4].tolist()}: GPU {[hex(v) for v in bits(got).ravel()[diff[:4]]]}, " + f"R-emu {[hex(v) for v in bits(want).ravel()[diff[:4]]]}") + if call in G1A: + one = hex(bits(ple_gpu.rsqrtf_ftz(np.ones(1, F32)))[0]) + out, gamma = [hex(v) for v in bits(got).ravel()], [hex(v) for v in bits(w)] + print(f"{call}: output {out}, gamma {gamma}, the GPU's rsqrtf_ftz(1.0f) {one}") + assert out == gamma, ( + f"G1a, \"At R=1 and eps=0, xn=gamma exactly\" (gr_parity.cpp:169): output {out} != gamma {gamma} with the " + f"GPU's rsqrtf_ftz(1.0f) = {one}; a departure from basalt (gr_parity.cpp:233-236), to record, not to tune " + "away (spec T§7.2)") + + +# ---- T-POST: native_ple_postops kernel by kernel against R-emu, row by row against R-contract (spec T§7.3) --------- +PROJECTED_SEED = 4 # default_rng(PROJECTED_SEED) draws, in W1's order without its hyper-connection inputs + # (ple_win_parity.cpp:50-55): conv1d, hidden's unit draw z, the raw keys, the values, the + # history, then w_nk, w_nq and w_nc; the first seed from 0 for which min |s| >= 0.1 holds + # (min |s| 0.174) +EDGE_SEED = 1119 # default_rng(EDGE_SEED) draws the planted inputs of the edge row being built +SCALE = np.frombuffer(kernels.basalt_ple_gate_params(), F32)[0] # the gate's scale as the kernel reads it, 0x3CA1E89B +CLAMP_P = np.uint32(0x38543784).view(F32) # fl(SCALE * CLAMP_P) is 1e-6f, the clamp (asserted) +GATE_EDGES = { # stream: (key[0], query[0]), every other entry 0, so the stream's sum is fl(key[0] * query[0]) exactly + "s = +0": (0.0, 1.0), + "s = -0": (-2.0 ** -61, 2.0 ** -61), # fl(SCALE * -2^-122) is subnormal: .FTZ makes s -0 + "0 < s < 1e-6": (2.0 ** -20, 1.0), + "-1e-6 < s < 0": (-2.0 ** -20, 1.0), + "s = 1e-6f": (CLAMP_P, 1.0), + "s = -1e-6f": (-CLAMP_P, 1.0), + "s = 2e4": (2.0 ** 10, 2.0 ** 10), # mag 144: ex2(-208) is +0 and the gate rcp(1) = 1 + "s = -2e4": (-2.0 ** 10, 2.0 ** 10), # ex2(+208) overflows: the gate is rcp(inf) = +0 +} +# The SiLU row's sums, channel c = 0, 1, ...: -acc * log2(e) passes 128 below acc = -88.72 (fast::exp2 overflows) +# and 1 + ex2 passes 2^126 below -87.34 (the reciprocal flushes); either way act = acc * +0 = -0. +SILU_ACC = (-np.inf, -3e38, -1e4, -100.0, -89.0, -88.75, -88.7, -88.5, -88.0, -87.5, -87.0, -80.0, -20.0, 20.0, 80.0, + 88.0, 89.0, 100.0, 3e38, np.inf) +EDGE_ROWS = ("SiLU exp2 overflow", "subnormal inputs", "gated below 2^-126") + + +@functools.lru_cache(maxsize=1) +def projected(): + """T§7.3's projected form at W1's scales (ple_win_parity.cpp:47-55): per row a raw key f32(0.2 N(0,1)) (D values) + and a value f32(0.5 N(0,1)) (N), the initial history f32(N(0,1)) (9 x D, row r oldest first), the three norms' + f32(1 + 0.1 N(0,1)) and conv1d f16(0.3 N(0,1)); hidden = f32(sigma_h z) by T§6.3's rule 3 (R-contract with the + unit hidden f32(z), then sigma_h = mean |gated + conv_out| / mean |f32(z)|). Asserts T§7.3's min |s| >= 0.1 on + R-contract. Returns (fx, key, value): a basalt_ple_ref Fixture without key, value and emb (the projections are + inputs here), the raw keys (12, D) and the values (12, N).""" + rng = np.random.default_rng(PROJECTED_SEED) + conv1d = (0.3 * rng.standard_normal(KERN * D)).astype(np.float16) + z = rng.standard_normal((ROWS, D)) + key = (0.2 * rng.standard_normal((ROWS, D))).astype(F32) + value = (0.5 * rng.standard_normal((ROWS, N))).astype(F32) + hist = rng.standard_normal((HIST, D)).astype(F32) + w_nk, w_nq, w_nc = ((1 + 0.1 * rng.standard_normal(D)).astype(F32) for _ in range(3)) + fx = Fixture(key=None, value=None, w_nk=w_nk, w_nq=w_nq, w_nc=w_nc, conv1d=conv1d, emb=None, hist=hist, + hidden=z.astype(F32)) + ref = r_contract(fx, key, value) + sigma = np.abs(ref.gated + ref.conv_out).mean() / np.abs(fx.hidden.astype(F64)).mean() + fx = fx._replace(hidden=(sigma * z).astype(F32)) + min_s = float(np.abs(r_contract(fx, key, value).s).min()) + assert min_s >= 0.1, f"T§7.3, \"Each fixture asserts min |s[c]| ≥ 0.1 on R-contract\": {min_s!r}" + return fx, key, value + + +def postops_row(key, value, hidden, hist, fx): + """One token of native_ple_postops (native_ple_postops.cu:352-359) on the GPU, launch by launch, with ``fx``'s + norms and conv1d, and R-emu on the same inputs, each emulated launch fed the GPU's outputs of the launches before + it: ``{stage: (GPU, R-emu)}`` for the key norm, the query norm, the gate, the broadcast (gated), the conv norm + (normalized), and the convolution's conv_out and result. ``hist`` is in basalt's layout (row r of channel c at + c * 9 + r).""" + def norm(x, w): + return ple_gpu.gr_norm(x, w, H, N, H, EPS).ravel(), emu.gr_norm(x, w, H, N, H, EPS, ple_gpu.rsqrtf_ftz).ravel() + + out = {"key": norm(key, fx.w_nk), "query": norm(hidden, fx.w_nq)} + k, q = out["key"][0], out["query"][0] + out["gate"] = ple_gpu.gate(k, q), emu.ple_gate(k, q, SCALE, ple_gpu.sqrtf_ftz, gpu.expf_ftz) + out["gated"] = ple_gpu.broadcast(value, out["gate"][0]), emu.ple_broadcast(value, out["gate"][0]) + gated = out["gated"][0] + out["normalized"] = norm(gated, fx.w_nc) + nm = out["normalized"][0] + got = ple_gpu.conv(hist, nm, fx.conv1d, hidden, gated) + out["conv_out"], out["result"] = zip(got, emu.ple_conv(hist, nm, fx.conv1d, hidden, gated, gpu.expf_ftz)) + return out + + +POSTOPS_ROWS = ("projected", "synthetic", "real") # T§7.3's 12-row fixtures: the projected form, C3's two + + +@functools.lru_cache(maxsize=None) +def postops_rows(name): + """T§7.3's 12-row fixture ``name`` on ``postops_row``, its rows in order, each from the GPU's history before it, + once per process: (fx, rows), row t = (inputs, stages), the row's inputs (raw key, value, hidden, history) and + postops_row's stages. The projected form's raw keys and values are its own, its history the initial one, then + each row's GPU normalized row shifted in (basalt's advance moves words, so the host's shift, H-ORACLE's, has its + bits). C3's fixtures' raw keys and values, synthetic and real, are the chain's projections of the row (``block``), + their history the initial one, then "the GPU's snapshot of row t − 1", the chain's.""" + if name == "projected": + (fx, key, value), snap = projected(), None + else: + fx, _, out = block(name) + key, value, snap = out["key"], out["value"], out["snap"] + hist, rows = np.ascontiguousarray(fx.hist.T).ravel(), [] + for t in range(ROWS): + inputs = key[t], value[t], fx.hidden[t], hist + rows.append((inputs, postops_row(*inputs, fx))) + hist = h_oracle(hist, rows[-1][1]["normalized"][0][None], 1) if snap is None else snap[t] + return fx, rows + + +def postops_stages(name): + """``postops_rows(name)``'s stages, row by row.""" + return [stages for _, stages in postops_rows(name)[1]] + + +def edge_row(case): + """The projected form's first row, from the initial history, with ``case``'s inputs planted (``EDGE_ROWS``).""" + fx, key, value = projected() + rng = np.random.default_rng(EDGE_SEED) + k, v, h, taps = key[0].copy(), value[0].copy(), fx.hidden[0].copy(), fx.conv1d.copy() + hist = np.ascontiguousarray(fx.hist.T).ravel() # a copy + if case == "SiLU exp2 overflow": # channel c's taps (1, 0, 0, 0): its sum is history row 0 + c = np.arange(len(SILU_ACC)) + taps.reshape(D, KERN)[c] = (1.0, 0.0, 0.0, 0.0) + hist.reshape(D, HIST)[c, 0] = SILU_ACC + elif case == "subnormal inputs": # every 7th input a float32 subnormal, every 5th tap an + for a in (k, v, h, hist): # fp16 subnormal, of either sign + n = a[::7].size + a[::7] = (rng.integers(1, 1 << 23, n, dtype=np.uint32) | rng.integers(0, 2, n, dtype=np.uint32) << 31 + ).view(F32) + n = taps[::5].size + taps[::5] = (rng.integers(1, 1 << 10, n, dtype=np.uint16) | rng.integers(0, 2, n, dtype=np.uint16) << 15 + ).view(np.float16) + elif case == "gated below 2^-126": # |value| in [2^-126, 2^-123), so |value * gate| + # straddles 2^-126 + v = (rng.choice((-1.0, 1.0), N) * rng.uniform(1, 8, N) * 2.0 ** -126).astype(F32) + return [postops_row(k, v, h, hist, fx._replace(conv1d=taps))] + + +def gate_edges(): + """``GATE_EDGES``' streams through basalt_ple_gate, H streams a call (basalt's launch), and R-emu's ple_gate.""" + keys, queries = np.zeros((len(GATE_EDGES), N), F32), np.zeros((len(GATE_EDGES), N), F32) + keys[:, 0], queries[:, 0] = np.array(list(GATE_EDGES.values()), F32).T + return [{"gate": (ple_gpu.gate(keys[i:i + H], queries[i:i + H]), + emu.ple_gate(keys[i:i + H], queries[i:i + H], SCALE, ple_gpu.sqrtf_ftz, gpu.expf_ftz))} + for i in range(0, len(GATE_EDGES), H)] + + +POSTOPS = {**{name: functools.partial(postops_stages, name) for name in POSTOPS_ROWS}, "gate edges": gate_edges, + **{case: functools.partial(edge_row, case) for case in EDGE_ROWS}} + + +@pytest.mark.parametrize("case", list(POSTOPS)) +def test_postops_bitwise_emu(case): + rows = POSTOPS[case]() + for t, stages in enumerate(rows): + for stage, (got, want) in stages.items(): + diff = np.flatnonzero(bits(got) != bits(want)) + assert diff.size == 0, ( + "T-POST, \"compares all six stages of every row of every fixture above with R-emu, byte for byte\" " + f"(spec T§7.3): {case}, row {t}, {stage}: {diff.size} of {got.size} values differ; first at " + f"{diff[:4].tolist()}: GPU {[hex(v) for v in bits(got)[diff[:4]]]}, " + f"R-emu {[hex(v) for v in bits(want)[diff[:4]]]}") + if case == "gate edges": + assert F32(SCALE * CLAMP_P) == F32(1e-6), "the clamp stream's s = fl(SCALE * CLAMP_P) must be 1e-6f" + g = dict(zip(GATE_EDGES, (int(b) for b in bits(np.concatenate([r["gate"][0] for r in rows]))))) + print("gate edges:", {name: hex(b) for name, b in g.items()}) + assert g["s = +0"] == g["s = -0"] == 0x3F000000, ( + f"T§7.3, s = +0 and -0: \"sign 0, gate exactly the sigmoid of 0\": {hex(g['s = +0'])}, {hex(g['s = -0'])}") + assert g["0 < s < 1e-6"] == g["s = 1e-6f"] and g["-1e-6 < s < 0"] == g["s = -1e-6f"], ( + "T§7.3, 0 < |s| < 1e-6: the clamp gives the gate of |s| = 1e-6f, sign for sign") + assert g["s = 2e4"] == 0x3F800000 and g["s = -2e4"] == 0, ( + "T§7.3, large |s|: the sigmoid saturates at 1, and at +0 where fast::exp2 overflows: " + f"{hex(g['s = 2e4'])}, {hex(g['s = -2e4'])}") + elif case == "SiLU exp2 overflow": + acc = np.array(SILU_ACC) + act = bits(rows[0]["conv_out"][0][:len(acc)]) + under = np.isfinite(acc) & (acc <= -87.5) + assert (act[under] == 0x80000000).all(), ( + "T§7.3, \"the SiLU where -acc · log2(e) overflows fast::exp2, so acc / inf\" (and where 1 + ex2 passes " + f"2^126, so the reciprocal flushes): act = -0 for acc {acc[under].tolist()}: " + f"{[hex(b) for b in act[under]]}") + elif case == "gated below 2^-126": + flushed = int(np.count_nonzero(rows[0]["gated"][0] == 0)) + assert 0 < flushed < D, ( + f"T§7.3, gated products below 2^-126 are flushed and the others kept: {flushed} of {D} are 0") + + +POST_STAGES = tuple(s for s in STAGES if s != "value") # T§7.3's six stages: the value is an input + + +@pytest.mark.parametrize("name", POSTOPS_ROWS) +def test_postops_float64(name): + fx, rows = postops_rows(name) + bad, min_s = [], np.inf + for t, ((key, value, hidden, hist), stages) in enumerate(rows): + ref = r_contract(fx._replace(hist=hist.reshape(D, HIST).T, hidden=hidden[None]), key[None], value[None]) + min_s = min(min_s, float(np.abs(ref.s).min())) + for stage in POST_STAGES: + rel, _, nf = rel_l1(getattr(ref, stage)[0], stages[stage][0]) + ok = le(rel, 1e-4) and nf == 0 + print(f" postops [{name}] against R-contract, token {t} {stage:<12} rel {rel:.3e} (non-finite {nf})" + f"{'' if ok else ' *** FAIL ***'}") + if not ok: + bad.append((t, stage, float(rel), nf)) + assert min_s >= 0.1, f"T§7.3, \"Each fixture asserts min |s[c]| ≥ 0.1 on R-contract\": {name}: {min_s!r}" + assert not bad, ( + "`const bool ok = le(rel, 1e-4) && nf == 0;` (ple_parity.cpp:1119), then `if (!ok) ++bad;` (:1122), rel and " + "nf = rel_l1(R-contract, the GPU) per row and stage, R-contract fed the row's raw key, value, hidden and the " + f"GPU's history before the row (spec T§7.3): {name}: (row, stage, rel, non-finite) {bad}") + + +# ---- T-HIST, X-H and T-COPY: the history's moves (spec T§7.4-7.5, T§8) --------------------------------------------- +HS = HIST * D # a history's words +TOKENS = 12 # ple_parity.cpp:200 +PATTERNS = np.array([0x00000001, 0x807FFFFF, 0x80000000, 0x7F800000, 0xFF800000, 0x7FC00001, 0x7F800001], np.uint32) +PLANT = 37 # X-H plants PATTERNS, in turn, at every PLANT-th channel from the token's index +COPY_SEED = 177 # default_rng(COPY_SEED) draws T-COPY's random words + + +def h1_fixture(): + """H1's fixture as words (ple_parity.cpp:181-182, :200-202): the initial history + ``expected[c * rows + r] = -float(c * 16 + r + 1)`` and the 12 tokens' normalized rows, + ``normalized[c] = float((token + 1) * 1000000 + c); // distinct exactly represented integers``.""" + c, r = np.meshgrid(np.arange(D), np.arange(HIST), indexing="ij") + hist = bits((-(c * 16 + r + 1)).astype(F32)).ravel() + normalized = bits(((np.arange(TOKENS)[:, None] + 1) * 1000000 + np.arange(D)).astype(F32)) + return hist, normalized + + +def host_shift(expected, normalized): + """ple_parity.cpp:203-204 for every channel, on words: rows 1 to 8 move to rows 0 to 7, and ``normalized`` enters + row 8.""" + e = expected.reshape(D, HIST).copy() + e[:, :-1] = expected.reshape(D, HIST)[:, 1:] + e[:, -1] = normalized + return e.ravel() + + +def test_history_advance_12_steps(): + hist, normalized = h1_fixture() + actual = ple_gpu.advance(hist, normalized)[0] + expected, bad = hist, [] + for token in range(TOKENS): + expected = host_shift(expected, normalized[token]) + if actual[token].tobytes() != expected.tobytes(): + bad.append(token) + assert not bad, ( + "H1, `if (std::memcmp(actual.data(), expected.data(), count * sizeof(float)) != 0) {` (ple_parity.cpp:210), " + f"then `++bad;` (:212): history advance mismatch after token {bad}") + + +def test_history_moves_bits(): + hist, normalized = h1_fixture() + for token in range(TOKENS): + planted = np.arange(token, D, PLANT) + normalized[token, planted] = PATTERNS[np.arange(planted.size) % PATTERNS.size] + expected = [hist] + for token in range(TOKENS): + expected.append(host_shift(expected[-1], normalized[token])) + expected = expected[1:] # expected[t]: the history after token t + first = TOKENS - T_MAX # slot s takes the history after token first + s + last = expected[-1].reshape(D, HIST) + assert all(np.isin(PATTERNS, last[:, r]).all() for r in range(HIST)), "X-H: every pattern in every history row" + assert all((hist != expected[first + s]).all() for s in range(T_MAX)), ( + "X-H: the restore's target history differs from every slot at every word") + advanced = ple_gpu.advance(hist, normalized)[0] + bad = [f"advance after token {t}" for t in range(TOKENS) if advanced[t].tobytes() != expected[t].tobytes()] + slots = np.empty((T_MAX, HS), np.uint32) + for s in range(T_MAX): + slots[s] = ple_gpu.snapshot(advanced[first + s], s)[0][s] + if slots[s].tobytes() != expected[first + s].tobytes(): + bad.append(f"snapshot into slot {s}") + for s in range(T_MAX): + if ple_gpu.restore(hist, slots, commit_record(s + 1, T_MAX, 0))[0].tobytes() != expected[first + s].tobytes(): + bad.append(f"restore of slot {s}") + assert not bad, ( + "X-H, \"every pattern survives the history's moves bit for bit (memcmp, as H1). Under forms (a)/(b) the moves " + f"are the advance, the snapshot and the commit restore\" (spec T§8): mismatches at {bad}") + + +@functools.lru_cache(maxsize=1) +def copy_words(): + """T-COPY's words, (T_MAX + 1, HS) uint32: row s is ``w ^ (s << 24)`` for one draw ``w`` of HS random words + (default_rng(COPY_SEED)), rows 0 to 7 the snapshots and row 8 the history. Each row differs from every other at + every word, and no word is a fill of the harness (0xFFFFFFFF, 0xA5A5A5A5; asserted), so that a missed, stray or + misplaced store shows.""" + w = np.random.default_rng(COPY_SEED).integers(0, 2 ** 32, HS, dtype=np.uint32) + words = w[None] ^ (np.arange(T_MAX + 1, dtype=np.uint32)[:, None] << np.uint32(24)) + assert not np.isin(words, np.array([0xFFFFFFFF, 0xA5A5A5A5], np.uint32)).any(), "T-COPY: a fill word in the data" + return words + + +@pytest.mark.parametrize("slot", range(T_MAX)) +def test_snapshot_copy_exact(slot): + src = copy_words()[T_MAX] + snaps, guards = ple_gpu.snapshot(src, slot) + equal = snaps[slot].tobytes() == src.tobytes() + changed = [s for s in range(T_MAX) if s != slot and (snaps[s] != 0xA5A5A5A5).any()] + assert equal and not changed and guards, ( + "T-COPY, \"for every row t of a T-row window, snapshot t equals the history after row t, byte for byte; the " + "snapshot rows from T to T_MAX − 1 still hold their sentinel; the guard bytes around the buffer are " + "untouched\" (spec T§7.5; `if (ra != rb) {`, dec_commit_parity.cpp:177): " + f"slot {slot} equals its source: {equal}; other slots changed: {changed}; guards intact: {guards}") + + +RESTORES = { # case: (the record's word 1, the slot the history must then equal, None: unchanged) + **{f"word 1 = {i}": (i, i) for i in range(T_MAX)}, + **{f"word 1 = {i}": (i, None) for i in (-1, -5)}, + **{f"word 1 = {i}": (i, T_MAX - 1) for i in (T_MAX, 100)}, +} + + +@pytest.mark.parametrize("case", list(RESTORES)) +def test_commit_restore_exact(case): + word1, slot = RESTORES[case] + words = copy_words() + if 0 <= word1 < T_MAX: + commit = commit_record(word1 + 1, T_MAX, 0) # the window's record (verify.cpp:2735-2737) + else: # a record the host refuses (verify.cpp:2732); word 0 names + commit = commit_record(3, T_MAX, 0) # slot 3, so that a read of word 0 shows + commit[1] = word1 + got, guards = ple_gpu.restore(words[T_MAX], words[:T_MAX], commit) + want = words[T_MAX] if slot is None else words[slot] + equal = got.tobytes() == want.tobytes() + assert equal and guards, ( + "T-COPY, \"the history after the restore equals snapshot n_keep − 1 byte for byte; with index −1 the history " + "is unchanged; ... guard bytes are untouched\" (spec T§7.5), and word 1 above 7 restores slot 7 (plan D5): " + f"record {commit.tolist()}, the history equals {'itself' if slot is None else f'slot {slot}'}: {equal}; " + f"guards intact: {guards}") + + +# ---- C8, C3 (with C16) and C1: the block on the per-row chain (spec T§6.4) ----------------------------------------- +KEY = "gguf/blk.1.ple_key.weight" +FIXTURES = {"synthetic": synthetic, "real": real} +STAGE_OUT = { # R-struct's slice: the chain's output for it, and basalt's name for the stage (ple_parity.cpp:752-758) + "key": ("key_norm", "key (grouped_norm of ple_key @ emb)"), + "value": ("value", "value (ple_value @ emb, BF16)"), + "gate": ("gate", "gate (signed sqrt, sigmoid)"), + "gated": ("gated", "gated (value broadcast * gate)"), + "normalized": ("normalized", "normalized (grouped_norm(gated, ple_norm_conv))"), + "conv_out": ("conv", "conv_out (dilated conv, then SiLU)"), + "result": ("result", "result (hidden + gated + conv)"), +} + + +@functools.lru_cache(maxsize=None) +def block(name): + """C3's fixture ``name`` (spec T§6.3: 12 rows from one initial history), its R-struct, and the chain's run of its + 12 rows (``basalt_ple_gpu.chain``), once per process: (fx, ref, out).""" + fx = FIXTURES[name]() + out = ple_gpu.chain(fx.emb, fx.hidden, np.ascontiguousarray(fx.hist.T).ravel(), fx) + return fx, r_struct(fx), out + + +@pytest.mark.parametrize("name", list(FIXTURES)) +def test_key_projection_into_grouped_norm(name): + fx, _, out = block(name) + differ, bad = [], [] + for t in range(ROWS): + xq = gpu.q8_1(fx.emb[t]) # native_q2_0_f32 (ple_parity.cpp:896) + raw = gpu.mmvq(42, fx.key, xq, N, D, 1)[0] + main = {"q8_1": xq, "key": raw, "value": gpu.mmvf(fx.value, fx.emb[t], N, N)} + differ += [(t, k) for k, a in main.items() if a.tobytes() != out[k][t].tobytes()] + rel = rel_l1(host_norm(raw, fx.w_nk), out["key_norm"][t])[0] + wired = le(rel, 2e-6) and nonfinite(out["result"][t]) == 0 + print(f" native PLE key projection->existing norm input {t}: {'pass' if wired else 'FAIL'} (rel {rel:.3e})") + if not wired: + bad.append((t, rel, nonfinite(out["result"][t]))) + assert not differ, ( + "C8's raw key is basalt's native_q2_0_f32 (native_quantize_q8_1, then native_mmvq type 42; basalt_gpu.q8_1 and " + "mmvq), and the chain's q8_1 image, raw key and value (basalt_gpu.mmvf) must be main's kernels' own, bit for " + f"bit: (row, output) {differ} differ") + assert not bad, ( + "`const bool wired = le(rel, 2e-6) && nonfinite(actual_result.data(), hcd) == 0;` (ple_parity.cpp:910), then " + "`if (!wired) ++bad;` (:912), rel = rel_l1(the host norm of the raw key (:899-904), the chain's key norm), the " + f"non-finite count over the row's result: (row, rel, non-finite) {bad}") + + +@pytest.mark.parametrize("name", list(FIXTURES)) +def test_block_vs_float64_graph(name): + fx, ref, out = block(name) + P = np.concatenate([np.asarray(fx.hist, F64), ref.normalized]) # R-struct's padded rows (spec T§6.2) + w = taps(fx.conv1d) + rels, over, nf_all = {stage: [] for stage in STAGES}, [], [] + for t in range(ROWS): + for stage in STAGES: + got, label = STAGE_OUT[stage] + rel, mag, nf = rel_l1(getattr(ref, stage)[t], out[got][t]) + last = stage == "result" + print(f" token {t} {label:<46} rel {rel:.3e} (mean |ref| {mag:.4f}, non-finite {nf})" + f"{' *** over 1e-2 ***' if last and not le(rel, 1e-2) else ''}") + rels[stage].append(rel) + if last and not le(rel, 1e-2): + over.append((t, rel)) + if nf: + nf_all.append((t, stage, nf)) + share = np.abs(ref.gated[t] + ref.conv_out[t]).sum() / np.abs(ref.result[t]).sum() + terms = sum(np.abs(w[:, k] * P[t + DIL * k]) for k in range(KERN)).sum() + num, res = np.abs(ref.conv_out[t] - out["conv"][t]).sum(), np.abs(ref.conv_out[t]).sum() + print(f" token {t} block share {share:.4f}; conv_out against the TERM magnitude, not the result: rel " + f"{num / terms:.3e} (|result|/|terms| = {res / terms:.4f})") + print(f"C3 [{name}]: worst rel per stage", {stage: f"{np.max(v):.3e}" for stage, v in rels.items()}) + assert not over and not nf_all, ( + "`if (last && !le(rel, 1e-2)) ++bad;` (ple_parity.cpp:782), rel = rel_l1(R-struct, the chain) on result: " + f"(row, rel) {over}; and spec T§8, X-NF rule 1, \"Every comparison in sections 6-8 counts non-finite outputs " + "in every stage, including the six that C3 only prints. With finite fixtures the count must be 0.\": (row, " + f"stage, non-finite) {nf_all}") + + +def test_real_key_row0_decodes_like_ggml(): + row0 = np.frombuffer(committed()[0][KEY], np.uint8) + v = gpu.dequant(42, row0, N) + want = q2_0(row0.reshape(-1, KEY_BLOCK)).ravel() + ok = np.isfinite(v) & np.isfinite(want) + nf = int(np.count_nonzero(~ok)) + diff = np.abs(v[ok].astype(F64) - want[ok].astype(F64)) + worst = float(diff.max()) if diff.size else 0.0 # NaN-safe: the non-finite pairs are nf's + rms = float(np.sqrt(np.mean(v.astype(F64) ** 2))) + same = le(worst, 0.0) and nf == 0 + print(f" {'ple_key row 0: the GPU decode == ggml dequantize_row_q2_0':<46} {'yes' if same else '*** NO ***'} " + f"(worst |d| {worst:.3e}, non-finite {nf}); rms {rms:.4e}") + assert same, f"`if (!le(worst, 0.0) || nf) ++bad;` (ple_parity.cpp:636): worst |d| {worst!r}, non-finite {nf}" + assert np.isfinite(v).all() and 1e-4 < rms < 10, ( + f"spec T§6.4, C1: the row is finite with 1e-4 < rms < 10 (weights, not padding): rms {rms!r}") + bound = real_tensors()[KEY][:row0.size] + assert bound == row0.tobytes(), ( + f"spec T§6.4, C1: \"the bound key's row 0 equals the committed slice byte for byte\": {KEY} row 0 differs at " + f"bytes {np.flatnonzero(np.frombuffer(bound, np.uint8) != row0)[:8].tolist()}") + + +# ---- X-INPLACE and X-GUARD: the chain's aliases and its stores' bounds (spec T§8) ---------------------------------- +def differ(a, b, keys, rows): + """The (output, row) pairs of ``keys`` over ``rows`` where the chain runs ``a`` and ``b`` differ, byte for byte.""" + return [(k, t) for k in keys for t in rows if a[k][t].tobytes() != b[k][t].tobytes()] + + +@pytest.mark.parametrize("name", list(FIXTURES)) +def test_compact_build_equals_full_exports(name): + fx, _, shared = block(name) + args = fx.emb, fx.hidden, np.ascontiguousarray(fx.hist.T).ravel(), fx + split = differ(shared, ple_gpu.chain(*args, split_query=True), ("gate", "gated", "normalized", "result"), + range(ROWS)) + inplace = differ(shared, ple_gpu.chain(*args, inplace=True), ("normalized", "result"), range(ROWS)) + equal = not split and not inplace + print(f" PLE separate exports and in-place hidden result: {'byte-identical' if equal else 'FAIL'}") + assert equal, ( + "C12, `const bool equal = std::memcmp(compact_norm.data(), dev_norm.data(), hcd * sizeof(float)) == 0 && " + "std::memcmp(compact_result.data(), dev_res.data(), hcd * sizeof(float)) == 0;` (ple_parity.cpp:963-964), " + "then `if (!equal) ++bad;` (:966), on every row: (1) query and normalized bound as one buffer (the handler's " + f"binding) against two buffers, (output, row) {split} differ; (2) result bound onto hidden (basalt's in-place " + f"alias) against out of place, (output, row) {inplace} differ") + + +@pytest.mark.parametrize("t", range(1, T_MAX + 1)) +def test_store_bounds_guards(t): + fx, _, clean = block("synthetic") + out = ple_gpu.chain(fx.emb[:T_MAX], fx.hidden[:T_MAX], np.ascontiguousarray(fx.hist.T).ravel(), fx, t, + guard=True) + broken = [k for k, kept in out["guards"].items() if not kept] + touched = [(k, r) for k in ("normalized", "result", "snap") for r in range(t, T_MAX) + if (bits(out[k][r]) != 0xFFFFFFFF).any()] + wrong = differ(out, clean, (*ple_gpu.SCRATCH, "hist", "normalized", "result", "snap"), range(t)) + restored, kept = ple_gpu.restore(out["hist"][-1], out["snap"], commit_record(1, t, 0)) + if not kept: + broken.append("restore: hist, snap or commit") + if restored.tobytes() != out["snap"][0].tobytes(): + wrong.append(("restore", 0)) + assert not broken and not touched and not wrong, ( + "X-GUARD (spec T§8), H3's `if (!guard_ok(history_storage, count) || !guard_ok(norm_storage, channels)) " + "++bad;` (ple_parity.cpp:228) and C10's `if (!std::all_of(ends.begin(), ends.end(), [](uint8_t x) { return x " + "== 0xa5; })) ++bad;` (:936) on every binding: guards broken on {broken}; \"rows from T to T_MAX − 1 of every " + f"multi-row output still hold their sentinel\": (output, row) {touched} were written; rows below T equal the " + f"exact-size run's, and the restore of n_keep = 1 equals slot 0: (output, row) {wrong} differ (T = {t})") diff --git a/tests/kernels/test_basalt_ple_program.py b/tests/kernels/test_basalt_ple_program.py new file mode 100644 index 00000000..58d8dad5 --- /dev/null +++ b/tests/kernels/test_basalt_ple_program.py @@ -0,0 +1,361 @@ +# SPDX-License-Identifier: MIT +# Copyright (c) 2026 Jesús Gulfo +# adapted from basalt (jesdga95/basalt) src/kernels/ple_win_parity.cpp and src/kernels/ple_parity.cpp +# @ b4c63b55754637f4c72ad53a0f791d425f71eb36 (MIT; third_party/NOTICE): ple_win_parity's window against the verify +# window's per-row chain (:71-116: for T = 1..8 from one reset, the result rows, the history and the snapshots compared +# value by value, its criterion and its log line, :96-109), ple_parity's guard byte 0xa5 (:186-187) as the snapshots' +# sentinel, and its graph replay checks' criteria, the captured graph's replay (:819-834, :829) and the replays after +# re-uploaded rows (:913-927, :924). +"""basalt's n-gram block on the decode path in compiled programs on the GPU: the window op ``basalt_ple_block`` in one +static program per width, T = 1 .. 8 (basalt captures one graph per width), and the commit op ``basalt_ple_commit`` in +a program of its own at t = 8, every program emitted with ``tail=None`` (spec G§3.3: the stock tail moves +``position``), from the hand-built graph of tests/contract/test_basalt_ple_ops.py (``window``, ``commit_program``): +the inputs ``ngram.rows`` and ``ngram.hidden``, the pack's six tensors bound from a BasaltSource over a .basalt file +that holds them under the pack's names and types (``write_file``), the states ``ngram.hist`` and ``ngram.snap``, and +the commit's record ``commit``. The file holds spec T§6.3's fixtures' weights, synthetic and real (tests.basalt_ple_ref +``synthetic`` and ``real``, the real ones cut from $BASALT_PLE_FIXTURE's ranges), and the runs take the fixture's +activations: rows 0 .. 7 of its gathered rows (emb) and hidden rows, and its history H0 in basalt's layout (row r of +channel c at c * 9 + r). + +- The engines share by name (plan §3): the T = 8 window's engine is built first and holds every buffer the others + share, the weight windows, ``ngram.hist``, ``ngram.snap``, the row I/O (``ngram.rows``, ``ngram.hidden``, + ``ngram.result``, ``ngram.normalized``: the T = 8 program's are the largest), StepState and the ring; every other + width's engine and the commit's take ``buffers=`` from it, and each name they hold in common is its buffer + (asserted). They keep their own params records and scratch (the names carry the width) and, the commit's, the + record. One encoding per program, replayed: between runs only buffers change, and each run's outputs are read + before the next run. +- A window run (``run_window``) writes all T_MAX rows of rows and hidden and, unless it continues from the history the + last run left, a history; the snapshots start as 0xa5 bytes (but in X-COMMIT's stale-row check), result and + normalized as 0xFF bytes. A commit run (``run_commit``) writes its record (``commit_record``) first, the record's + zero-filled arena would restore slot 0, and the history when it starts from one. +- X-WIN ``test_window_rows_equal_one_row_calls`` (spec T§8; W1, ple_win_parity.cpp:96-116): for T = 1..8 the T-row + window from H0, its input rows at or past T NaN (``sentinel``), gives R_T[t] (result) and N_T[t] (normalized), and + its commit with each n_keep in 1..T the committed history C_T[n_keep]; the one-row windows from H0, row t at row 0 + and NaN in rows 1..7, each committed with n_keep = 1 and continuing from the history the commit left, give R_1[t], + N_1[t] and C_1[t], the history after the commit of row t. Criteria: "for every T in 1..8 and every t < T: R_T[t] == + R_1[t], N_T[t] == N_1[t] and C_T[t + 1] == C_1[t]", byte for byte, W1's ``fail += d0 + d1 + d2 != 0;`` (:109) with + its log line; "The outputs of rows below T must equal the clean-input run bit for bit, which catches a kernel that + reads past T": the window over the fixture's own rows T..7 gives the same result, normalized and snapshot rows below + T and the same history after it; and X-NF rule 1, "With finite fixtures the count must be 0", over the output rows + below T and the committed histories. +- X-SNAP ``test_snapshots_are_history_after_each_row`` (spec T§8; W1's snapshot comparison and verify.cpp:1123), on + the windows of X-WIN, for every T and t < T: "rows 0..7 of snapshot t equal rows 1..8 of snapshot t − 1, byte for + byte (rows 1..8 of the initial history when t = 0)", "row 8 of snapshot t equals row t's normalized output, byte for + byte", and "snapshot rows T..T_MAX − 1 still hold their 0xa5 sentinel". +- X-COMMIT ``test_commit_restores_each_n_keep`` (spec T§8; no basalt test runs the restore, verify.cpp:2137): on X-WIN's + windows and their commits of each n_keep in 1..T, "the committed history equals H-ORACLE (7.1) for that n_keep: the + last nine rows of [H0 rows 0..8 | the window's normalized rows 0..n_keep − 1]", "it also equals snapshot + n_keep − 1" and "it equals C_1[n_keep − 1], the history after n_keep one-row windows (X-WIN)". For each (T, n_keep) + the window and its commit again, then "A following window from that state gives results equal to a fresh run from + the same state": the T = 8 window over the fixture's rows 4..11 from the history the commit left, against the same + window from the committed history written. "Stale rows are never read": a T = 8 window committed with n_keep = 8, + then a T = 2 window over rows 4..11 with the snapshots as the wider window left them, committed with n_keep = 2, + gives the T = 2 window's H-ORACLE history; the stale slots 2..7 are there, the T = 2 window rewrote slot 1 and the + stale slot 2 differs from that history (asserted). The no-op values, from H0 written between a T = 8 window and its + commit (H0 and the window's eight snapshots pairwise differ, asserted), with K's records (n_keep = 3's, word 1 + replaced: word 0 names another slot, so that a read of word 0 shows): word 1 = −1 leaves the history unchanged, + basalt's ``if (idx < 0) return;`` (verify_kernels.cu:506-512), and word 1 = 8 restores slot 7 (plan D5). The host's + refusal is CPU-only (tests/contract/test_basalt_ple_refs.py ``test_commit_record_refuses``). +- X-REP ``test_repeat_and_replay_bitwise`` (spec T§8; C5 and C9, ple_parity.cpp:829 and :924): for T = 1..8 the window + over the fixture's rows 0..7 from H0 and its commit of n_keep = 1. "three replays of one encoding on the same inputs + give identical result rows, normalized rows ..., snapshots ... and committed history"; "a replay equals a run of a + freshly encoded program on the same inputs", the same programs encoded again (a new Engine: a new indirect command + buffer and new params records, over the session's buffers); "a replay after new emb and hidden values are written + reads the new values, and equals a fresh run on them", the fixture's rows 4..11, whose result rows differ from the + first inputs' (asserted). +- X-TIER ``test_program_equals_kernel_chain`` (plan §4.7): "the program's 12 rows (a window of 8, commit 8, a window of + 4) equal §4.5's 12-row kernel chain byte for byte: result, normalized and the history after each row", the chain + ``basalt_ple_gpu.chain`` over the fixture's 12 rows from H0, as test_basalt_ple.py's ``block`` runs it; a program + row's history is its snapshot (X-SNAP), and the histories after each window and after the commit are compared too. +- Each of them counts the non-finite values of the outputs it compares, X-NF rule 1: "With finite fixtures the count + must be 0".""" + +import itertools + +import numpy as np +import pytest + +from monolith.packs.basalt import BasaltSource +from monolith.runtime import Engine +from tests.basalt_ple_ref import D, HIST, ROWS, T_MAX, commit_record, h_oracle, nonfinite, real, synthetic +from tests.contract.test_basalt_ple_ops import commit_program, window, write_file +from tests.kernels import basalt_gpu as gpu +from tests.kernels import basalt_ple_gpu as ple_gpu + +F32 = np.float32 +WIDTHS = range(1, T_MAX + 1) +HS = HIST * D # a history's words +FIXTURES = {"synthetic": synthetic, "real": real} +WEIGHTS = { # each tensor of the pack (blk.1.ple_.weight) and the fixture's field that holds its bytes + "conv1d": "conv1d", "key": "key", "norm_conv": "w_nc", "norm_key": "w_nk", "norm_query": "w_nq", "value": "value"} +SNAP_FILL = 0xA5A5A5A5 # a snapshot word no run has written +PIPELINES = {} # one pipeline cache for every engine of the module + + +@pytest.fixture(scope="module", params=list(FIXTURES)) +def session(request, tmp_path_factory): + """The fixture ``request.param`` and the engines of its eight window programs and its commit program, sharing by + name as the module docstring says: (fx, engines), ``engines[t]`` the T = t window's, ``engines["commit"]``.""" + fx = FIXTURES[request.param]() + data = {f"blk.1.ple_{name}.weight": getattr(fx, field).tobytes() for name, field in WEIGHTS.items()} + src = BasaltSource(write_file(tmp_path_factory.mktemp("ple") / "ple.basalt", data)) + progs = {t: window(src, t)[1] for t in WIDTHS} + progs["commit"] = commit_program(src, T_MAX) + dev = gpu.device() + engines = {T_MAX: Engine(progs[T_MAX], dev, pipeline_cache=PIPELINES)} + shared = engines[T_MAX].buffers + for k in (*WIDTHS[:-1], "commit"): + engines[k] = Engine(progs[k], dev, buffers=shared, pipeline_cache=PIPELINES) + own = [(k, n) for k, e in engines.items() for n in e.buffers + if n in shared and e.program.buffers[n].role != "params" and e.buffers[n] is not shared[n]] + common = set(engines["commit"].buffers) & set(shared) + assert not own and {"ngram.hist", "ngram.snap"} <= common and "commit" not in shared, ( + "plan §3: every engine takes the T = 8 engine's buffer for each name both hold, params records aside; " + f"(engine, name) {own} hold their own; the commit's program holds {sorted(common)} of them") + return fx, engines + + +def words(eng, name, n): + """``eng``'s buffer ``name``, all of it, as rows of ``n`` uint32 words.""" + return np.frombuffer(eng.read(name), np.uint32).reshape(-1, n) + + +def run_window(engines, t, rows, hidden, hist=None, fill=True): + """One replay of the T = ``t`` window over ``rows`` (T_MAX, N) and ``hidden`` (T_MAX, D), all T_MAX rows of each + written, from the history ``hist`` (HS words in basalt's layout, float32 or the uint32 words a run returns, written + as its bytes; None: the history the last run left), the snapshots first 0xa5 bytes (``fill`` False: as the last run + left them), result and normalized 0xFF bytes. Returns its ``result`` and ``normalized`` (T_MAX rows of D words), + its snapshots ``snap`` (T_MAX slots of HS words) and ``hist`` after it (HS words), uint32.""" + eng = engines[t] + b = eng.buffers + b["ngram.rows"].write(np.ascontiguousarray(rows, F32).tobytes(), 0) + b["ngram.hidden"].write(np.ascontiguousarray(hidden, F32).tobytes(), 0) + if hist is not None: + b["ngram.hist"].write(np.ascontiguousarray(hist).tobytes(), 0) + if fill: + b["ngram.snap"].fill(0xA5) + b["ngram.result"].fill(0xFF) + b["ngram.normalized"].fill(0xFF) + assert eng.run(1, steps_per_cb=1, in_flight=1).steps == 1 + return {"result": words(eng, "ngram.result", D), "normalized": words(eng, "ngram.normalized", D), + "snap": words(eng, "ngram.snap", HS), "hist": words(eng, "ngram.hist", HS)[0]} + + +def run_commit(engines, record, hist=None): + """One replay of the commit, its record ``record`` (int32 words) written first, from the history ``hist`` (as + ``run_window``'s). Returns the history after it, HS uint32 words.""" + eng = engines["commit"] + eng.buffers["commit"].write(np.asarray(record, np.int32).tobytes(), 0) + if hist is not None: + eng.buffers["ngram.hist"].write(np.ascontiguousarray(hist).tobytes(), 0) + assert eng.run(1, steps_per_cb=1, in_flight=1).steps == 1 + return words(eng, "ngram.hist", HS)[0] + + +def sentinel(a, t): + """T_MAX rows, float32: the first ``t`` rows of ``a``, then NaN (spec T§8's sentinel input rows).""" + out = np.full((T_MAX, *np.shape(a)[1:]), np.nan, F32) + out[:t] = a[:t] + return out + + +@pytest.fixture(scope="module") +def runs(session): + """X-WIN's runs, in the module docstring's order, each read before the next: ``wide[T]`` the sentinel window, + ``committed[T][n_keep - 1]`` its commit's C_T[n_keep], ``clean[T]`` the window over the fixture's rows; ``ones[t]`` + the one-row window of row t and ``chain[t]`` its commit's C_1[t]; ``h0`` the initial history (HS float32).""" + fx, engines = session + h0 = np.ascontiguousarray(fx.hist.T, F32).ravel() + wide, committed, clean = {}, {}, {} + for t in WIDTHS: + wide[t] = run_window(engines, t, sentinel(fx.emb, t), sentinel(fx.hidden, t), h0) + committed[t] = [run_commit(engines, commit_record(n, t, 0)) for n in range(1, t + 1)] + clean[t] = run_window(engines, t, fx.emb[:T_MAX], fx.hidden[:T_MAX], h0) + ones, chain = [], [] + for t in range(T_MAX): + rows, hidden = sentinel(fx.emb, 1), sentinel(fx.hidden, 1) + rows[0], hidden[0] = fx.emb[t], fx.hidden[t] + ones.append(run_window(engines, 1, rows, hidden, h0 if t == 0 else None)) + chain.append(run_commit(engines, commit_record(1, 1, t))) + return {"h0": h0, "wide": wide, "committed": committed, "clean": clean, "ones": ones, "chain": chain} + + +def test_window_rows_equal_one_row_calls(runs): + ones, chain = runs["ones"], runs["chain"] + fail, diffs, past, nf = 0, {}, [], [] + for t in WIDTHS: + w, c, ct = runs["wide"][t], runs["clean"][t], runs["committed"][t] + d0 = sum(int(np.count_nonzero(w["result"][r] != ones[r]["result"][0])) for r in range(t)) + d1 = sum(int(np.count_nonzero(w["normalized"][r] != ones[r]["normalized"][0])) for r in range(t)) + d2 = sum(int(np.count_nonzero(ct[r] != chain[r])) for r in range(t)) # C_T[r + 1] against C_1[r] + print(f"T={t} result {d0} normalized {d1} history {d2} differing values{' DIFF' if d0 + d1 + d2 else ''}") + fail += d0 + d1 + d2 != 0 + if d0 + d1 + d2: + diffs[t] = (d0, d1, d2) + past += [(t, k) for k in ("result", "normalized", "snap") if not np.array_equal(w[k][:t], c[k][:t])] + past += [(t, "hist")] if not np.array_equal(w["hist"], c["hist"]) else [] + for k, a in (("result", w["result"][:t]), ("normalized", w["normalized"][:t]), ("history", np.array(ct))): + if n := nonfinite(a.view(F32)): + nf.append((t, k, n)) + assert not fail, ( + "X-WIN (spec T§8), \"for every T in 1..8 and every t < T: R_T[t] == R_1[t], N_T[t] == N_1[t] and C_T[t + 1] == " + "C_1[t]\", byte for byte, W1's `fail += d0 + d1 + d2 != 0;` (ple_win_parity.cpp:109): differing values " + f"(result, normalized, history) at T {diffs}") + assert not past, ( + "X-WIN (spec T§8), \"The outputs of rows below T must equal the clean-input run bit for bit, which catches a " + "kernel that reads past T\": with NaN in input rows T..7, (T, output) " + f"{past} differ from the window over the fixture's rows") + assert not nf, ( + "X-NF rule 1 (spec T§8), \"With finite fixtures the count must be 0\": (T, output, non-finite values) " + f"{nf} in the output rows below T and the committed histories") + + +def test_snapshots_are_history_after_each_row(runs): + h0 = runs["h0"].view(np.uint32).reshape(D, HIST) + shifted, entered, kept = [], [], [] + for t in WIDTHS: + w = runs["wide"][t] + snap = w["snap"].reshape(T_MAX, D, HIST) # row r of channel c at [slot, c, r] + for r in range(t): + prev = h0 if r == 0 else snap[r - 1] + if not np.array_equal(snap[r][:, :HIST - 1], prev[:, 1:]): + shifted.append((t, r)) + if not np.array_equal(snap[r][:, HIST - 1], w["normalized"][r]): + entered.append((t, r)) + kept += [(t, r) for r in range(t, T_MAX) if (w["snap"][r] != SNAP_FILL).any()] + assert not shifted and not entered and not kept, ( + "X-SNAP (spec T§8): \"rows 0..7 of snapshot t equal rows 1..8 of snapshot t − 1, byte for byte (rows 1..8 of " + f"the initial history when t = 0)\": (T, t) {shifted} differ; \"row 8 of snapshot t equals row t's normalized " + f"output, byte for byte\": (T, t) {entered} differ; \"snapshot rows T..T_MAX − 1 still hold their 0xa5 " + f"sentinel\": (T, slot) {kept} were written") + + +def test_commit_restores_each_n_keep(session, runs): + fx, engines = session + h0, wide, committed, chain = runs["h0"], runs["wide"], runs["committed"], runs["chain"] + nxt = fx.emb[ROWS - T_MAX:], fx.hidden[ROWS - T_MAX:] # other inputs: the fixture's rows 4..11 + oracle, slot, seq, follow, nf = [], [], [], [], [] + for t in WIDTHS: + for n in range(1, t + 1): + c = committed[t][n - 1] + oracle += [(t, n)] if not np.array_equal( + c, h_oracle(h0, wide[t]["normalized"][:t].view(F32), n).view(np.uint32)) else [] + slot += [(t, n)] if not np.array_equal(c, wide[t]["snap"][n - 1]) else [] + seq += [(t, n)] if not np.array_equal(c, chain[n - 1]) else [] + run_window(engines, t, sentinel(fx.emb, t), sentinel(fx.hidden, t), h0) # X-WIN's window again + run_commit(engines, commit_record(n, t, 0)) + after = run_window(engines, T_MAX, *nxt) # the following window, from the state left + fresh = run_window(engines, T_MAX, *nxt, c) # the same window from that state, written + follow += [(t, n, k) for k in after if not np.array_equal(after[k], fresh[k])] + for k, a in (("committed history", c), *after.items()): + if m := nonfinite(a.view(F32)): + nf.append((t, n, k, m)) + assert not oracle and not slot and not seq, ( + "X-COMMIT (spec T§8), \"After the window and its commit, the committed history equals H-ORACLE (7.1) for that " + "n_keep: the last nine rows of [H0 rows 0..8 | the window's normalized rows 0..n_keep − 1]\": (T, n_keep) " + f"{oracle} differ; \"Under forms (a)/(b) it also equals snapshot n_keep − 1\": {slot} differ; \"Under every " + f"form it equals C_1[n_keep − 1], the history after n_keep one-row windows (X-WIN)\": {seq} differ") + assert not follow, ( + "X-COMMIT (spec T§8), \"A following window from that state gives results equal to a fresh run from the same " + "state\": the T = 8 window over the fixture's rows 4..11 from the history the commit left against the same " + f"window from the committed history written: (T, n_keep, output) {follow} differ") + + rows, hidden = fx.emb[:T_MAX], fx.hidden[:T_MAX] + w8 = run_window(engines, T_MAX, rows, hidden, h0) + c8 = run_commit(engines, commit_record(T_MAX, T_MAX, 0)) + w2 = run_window(engines, 2, *nxt, fill=False) # from c8, its snapshots as the T = 8 window left them + c2 = run_commit(engines, commit_record(2, 2, 0)) + want = h_oracle(c8.view(F32), w2["normalized"][:2].view(F32), 2).view(np.uint32) + present = {"slots 2..7 hold the T = 8 window's": np.array_equal(w2["snap"][2:], w8["snap"][2:]), + "the T = 2 window rewrote slot 1": not np.array_equal(w2["snap"][1], w8["snap"][1]), + "the stale slot 2 differs from the oracle": not np.array_equal(w8["snap"][2], want)} + assert all(present.values()) and np.array_equal(c2, want), ( + "X-COMMIT (spec T§8), \"Stale rows are never read. Run a T = 8 window committed with n_keep = 8, then a T = 2 " + "window on different inputs committed with n_keep = 2. The result is the T = 2 window's H-ORACLE history. Rows " + "2..7 left over from the wider window (... snapshots under forms (a)/(b)) must not reach it\": the commit " + f"gives the T = 2 window's H-ORACLE history: {np.array_equal(c2, want)}; the stale rows present: {present}") + nf += [("stale", 2, "committed history", m)] if (m := nonfinite(c2.view(F32))) else [] + + w = run_window(engines, T_MAX, rows, hidden, h0) + h0w = h0.view(np.uint32) + distinct = all(not np.array_equal(a, b) for a, b in itertools.combinations([h0w, *w["snap"]], 2)) + noop = {} + for word1, want in ((-1, h0w), (T_MAX, w["snap"][T_MAX - 1])): + record = commit_record(3, T_MAX, 0) # word 0 names slot 3, so that a read of word 0 shows + record[1] = word1 + noop[word1] = np.array_equal(run_commit(engines, record, h0), want) # from H0, which no slot holds + assert distinct and all(noop.values()), ( + "X-COMMIT (spec T§8), \"The no-op values copy nothing and leave the committed history unchanged\": word 1 = " + "−1 (basalt's `if (idx < 0) return;`, verify_kernels.cu:506-512) leaves the history H0 unchanged, and word " + f"1 = 8 restores slot 7 (plan D5, \"Word 1 > 7 restores slot 7\"): {noop} (word 1: equal); H0 and the T = 8 " + f"window's eight snapshots pairwise differ: {distinct}") + assert not nf, ( + "X-NF rule 1 (spec T§8), \"With finite fixtures the count must be 0\": (T, n_keep, output, non-finite values) " + f"{nf} in the committed histories and the following windows' outputs") + + +def test_repeat_and_replay_bitwise(session): + fx, engines = session + h0 = np.ascontiguousarray(fx.hist.T, F32).ravel() + shared = engines[T_MAX].buffers # the same programs encoded again, over the same buffers + fresh = {k: Engine(e.program, gpu.device(), buffers=shared, pipeline_cache=PIPELINES) for k, e in engines.items()} + first, new = (fx.emb[:T_MAX], fx.hidden[:T_MAX]), (fx.emb[ROWS - T_MAX:], fx.hidden[ROWS - T_MAX:]) + + def replay(engs, t, inputs): + """The T = ``t`` window of ``engs`` over ``inputs`` from H0 and its commit of n_keep = 1: the window's outputs + and the ``committed`` history.""" + out = run_window(engs, t, *inputs, h0) + return {**out, "committed": run_commit(engs, commit_record(1, t, 0))} + + same, encoded, reread, ignored, nf = [], [], [], [], [] + for t in WIDTHS: + reps = [replay(engines, t, first) for _ in range(3)] + again = replay(engines, t, new) + a, b = replay(fresh, t, first), replay(fresh, t, new) + same += [(t, k) for k in reps[0] if not all(np.array_equal(r[k], reps[0][k]) for r in reps[1:])] + encoded += [(t, k) for k in a if not np.array_equal(reps[0][k], a[k])] + reread += [(t, k) for k in b if not np.array_equal(again[k], b[k])] + ignored += [t] if np.array_equal(again["result"][:t], reps[0]["result"][:t]) else [] + for name, out in (("rows 0..7", reps[0]), ("rows 4..11", again)): + for k, x in (("result", out["result"][:t]), ("normalized", out["normalized"][:t]), + ("committed history", out["committed"])): + if m := nonfinite(x.view(F32)): + nf.append((t, name, k, m)) + assert not same and not encoded, ( + "X-REP (spec T§8; C5's `const bool captured = std::memcmp(native_result.data(), replay.data(), hcd * " + "sizeof(float)) == 0;`, ple_parity.cpp:829), \"three replays of one encoding on the same inputs give identical " + "result rows, normalized rows (W under form (c)), snapshots (forms (a)/(b)) and committed history\": (T, " + f"output) {same} differ; \"a replay equals a run of a freshly encoded program on the same inputs\": {encoded} " + "differ") + assert not reread and not ignored, ( + "X-REP (spec T§8; C9's `if (std::memcmp(actual_result.data(), replay.data(), hcd * 4) != 0) ++bad;`, " + "ple_parity.cpp:924), \"a replay after new emb and hidden values are written reads the new values, and equals " + f"a fresh run on them\": (T, output) {reread} differ from the fresh encoding's run on the fixture's rows " + f"4..11; at T {ignored} the replay's result rows equal the first inputs'") + assert not nf, ( + "X-NF rule 1 (spec T§8), \"With finite fixtures the count must be 0\": (T, inputs, output, non-finite values) " + f"{nf}") + + +def test_program_equals_kernel_chain(session): + fx, engines = session + h0 = np.ascontiguousarray(fx.hist.T, F32).ravel() + ref = {k: v.view(np.uint32) for k, v in ple_gpu.chain(fx.emb, fx.hidden, h0, fx).items() + if k in ("result", "normalized", "hist")} # plan §4.5's 12-row chain, as K's ``block`` runs it + t2 = ROWS - T_MAX + a = run_window(engines, T_MAX, fx.emb[:T_MAX], fx.hidden[:T_MAX], h0) + c = run_commit(engines, commit_record(T_MAX, T_MAX, 0)) + b = run_window(engines, t2, sentinel(fx.emb[T_MAX:], t2), sentinel(fx.hidden[T_MAX:], t2)) + got = {"result": np.concatenate([a["result"], b["result"][:t2]]), + "normalized": np.concatenate([a["normalized"], b["normalized"][:t2]]), + "hist": np.concatenate([a["snap"], b["snap"][:t2]])} # snapshot t: the history after row t (X-SNAP) + rows = {k: [r for r in range(ROWS) if not np.array_equal(got[k][r], ref[k][r])] for k in got} + ends = {"the 8-row window's": (a["hist"], T_MAX - 1), "its commit's": (c, T_MAX - 1), + "the 4-row window's": (b["hist"], ROWS - 1)} + ends = [k for k, (h, r) in ends.items() if not np.array_equal(h, ref["hist"][r])] + nf = {k: m for k, v in got.items() if (m := nonfinite(v.view(F32)))} + assert not any(rows.values()) and not ends and not nf, ( + "X-TIER (plan §4.7), \"the program's 12 rows (a window of 8, commit 8, a window of 4) equal §4.5's 12-row " + "kernel chain byte for byte: result, normalized and the history after each row\": (output: rows) " + f"{ {k: v for k, v in rows.items() if v} } differ; the histories after {ends} differ from the chain's after " + f"the same row; X-NF rule 1 (spec T§8), \"With finite fixtures the count must be 0\": {nf}") diff --git a/third_party/NOTICE b/third_party/NOTICE index 97e2e993..55121b4b 100644 --- a/third_party/NOTICE +++ b/third_party/NOTICE @@ -113,10 +113,17 @@ Format: `` — adapted from / copied from `` `` @ - `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`. +- `kernels/common/basalt_gr_norm.metal` — through basalt's `src/kernels/cuda/native_gr_norm.cu` (below), which adapts + `ggml/src/ggml-cuda/{norm.cu,common.cuh}` (MIT): the weighted RMSNorm's per-thread squares and its warp and block + reductions. License: `third_party/GGML-LICENSE`. +- `kernels/common/basalt_ple.metal` — through basalt's `src/kernels/cuda/native_ple_postops.cu` (below), which adapts + `ggml/src/ggml-cuda/{reduce_rows.cuh,sumrows.cu,unary.cu}` (MIT): the gate's 512-thread row sum with its eight + partial lanes, and the SiLU. 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`. + copied, `get_scale_min_k4` of `ggml/src/ggml-quants.c`, the q8_1 rule of `ggml/src/ggml-cuda/quantize.cu`, the + MMVF accumulation and reductions of `ggml/src/ggml-cuda/mmvf.cu`, the RMSNorm of `ggml/src/ggml-cuda/norm.cu`, the + row sum of `ggml/src/ggml-cuda/reduce_rows.cuh` and the SiLU of `ggml/src/ggml-cuda/unary.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 @@ -159,7 +166,9 @@ Format: `` — adapted from / copied from `` `` @ 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: + fast-math file's `__expf` (`expf_ftz`; `docs/research/basalt-nvcc/q5k_head.md`); and from + `src/kernels/cuda/native_gr_norm.cu:72` and `src/kernels/cuda/native_ple_postops.cu:63`, `rsqrtf` and `sqrtf` as nvcc + compiles them in a fast-math file (`rsqrtf_ftz`, `sqrtf_ftz`; `docs/research/basalt-nvcc/ple.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` @@ -199,6 +208,15 @@ Format: `` — adapted from / copied from `` `` @ 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`. +- `kernels/common/basalt_gr_norm.metal` — adapted from `src/kernels/cuda/native_gr_norm.cu:37-100` (MIT): + `norm_warp_sum`, `weighted_rms_norm` and `native_gr_rms_norm_weighted`'s block choice, written in the rounding + sequence nvcc compiles for them (`docs/research/basalt-nvcc/ple.md`). License: `third_party/BASALT-LICENSE`. +- `kernels/common/basalt_ple.metal` — adapted from `src/kernels/cuda/native_ple_postops.cu:37-89`, + `src/kernels/cuda/ple.cu:46-52`, `src/kernels/cuda/elementwise.cu:222-227` and + `src/kernels/cuda/verify_kernels.cu:506-512` (MIT): `gate_kernel`, `broadcast_kernel` and `conv_residual_kernel`, + written in the rounding sequence nvcc compiles for them (`docs/research/basalt-nvcc/ple.md`); `history_advance_kernel` + and `copy_from_mapped_kernel`, word for word; and `copy_indexed_kernel` with the port's bound: an index past the last + snapshot slot restores slot 7, where basalt's kernel has none. 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 @@ -211,6 +229,12 @@ Format: `` — adapted from / copied from `` `` @ 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/kernels.py` — adapted from `src/kernels/cuda/native_gr_norm.cu:85-100`, + `src/kernels/cuda/native_ple_postops.cu:36` and `:352-359`, `src/kernels/cuda/ple.cu:36` and `:210`, + `src/kernels/cuda/elementwise.cu:277-287`, `src/kernels/cuda/verify_kernels.cu:1086-1090`, + `include/basalt/kernels/ngram.hpp:30-41` and `include/basalt/kernels/verify_kernels.hpp:21` (MIT): the n-gram + block's constants and launch grids, the norm's block choice and argument checks, and the gate's host scale. 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`, `src/kernels/cuda/iq_kernels.cu:2450-2455` and @@ -221,7 +245,14 @@ Format: `` — adapted from / copied from `` `` @ bounded dimensions)); `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`), and its `basalt_gr_post_params` and `basalt_gr_post_grid` transcribe `native_gr_post`'s `check_shape`, `THREADS` and `blocks` - (`native_gr_postops.cu:35`, `:79-83`). License: `third_party/BASALT-LICENSE`. + (`native_gr_postops.cu:35`, `:79-83`); `ple_block`'s native branch and refusals (`src/kernels/cuda/ple.cu:228-356`), + `native_ple_postops`'s span and alias checks (`src/kernels/cuda/native_ple_postops.cu:317-361`), + `ple_history_advance`'s (`ple.cu:204-212`) and the verify loop's per-row order and commit restore + (`src/core/verify.cpp:1105-1124`, `:2137`), with the norm's, the snapshot's and the restore's launcher checks + (`src/kernels/cuda/native_gr_norm.cu:78-100`, `src/kernels/cuda/elementwise.cu:277-287`, + `src/kernels/cuda/verify_kernels.cu:1086-1090`) and the key's binding (`keep_unquantized_ple_key`, + `src/core/native_dense.cpp:95-102`; `index_code_bits`, `src/core/weights.cpp:129-148`). 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`. @@ -246,6 +277,15 @@ Format: `` — adapted from / copied from `` `` @ - `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`. +- `tests/basalt_ple_ref.py`, `tests/contract/test_basalt_ple_refs.py`, `tests/kernels/test_basalt_ple.py` and + `tests/kernels/test_basalt_ple_program.py` — adapted from `src/kernels/ple_parity.cpp` and + `src/kernels/ple_win_parity.cpp` (MIT): their history regression, block, key and host-reference checks, fixtures, + guards and pass criteria, and the per-row chain comparison; with the commit record and its count refusal of + `src/core/verify.cpp:2732-2737` and the degenerate norm input of `src/kernels/gr_parity.cpp:167-236`. License: + `third_party/BASALT-LICENSE`. +- `tests/contract/test_basalt_ple_ops.py` — adapted from `tests/core/native_dense_ple_key_test.cpp` (its key rows and + three cases, as the key's binding) and `src/kernels/ple_parity.cpp` (its prelaunch refusals, as the emitter's) (MIT). + 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: @@ -263,10 +303,12 @@ Format: `` — adapted from / copied from `` `` @ 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`: + `docs/research/basalt-nvcc/q5k_head.md`), 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`. + `docs/research/basalt-nvcc/s2_experts.md`) and the n-gram block's norm, gate, broadcast and convolution (`gr_norm`, + `ple_gate`, `ple_broadcast`, `ple_conv`: `src/kernels/cuda/native_gr_norm.cu`, + `src/kernels/cuda/native_ple_postops.cu`; `docs/research/basalt-nvcc/ple.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 @@ -289,6 +331,11 @@ Format: `` — adapted from / copied from `` `` @ 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`). +- `tests/contract/fixtures/basalt_ple.safetensors` — byte ranges (95 KB: the n-gram block's slices of layer 1, key + row 0, the first 1024 bytes of the five dense rows and of their GGUF twins, and the whole convolution weight) of the + same `Qwen3.8-FN-GSQ-RCO-Q2_0.basalt` in `jesdga/Qwen3.8-Flash-Next-Basalt` @ + `2a6a758dc12f1d027d2d35b8964110df7e80f70b`, range-read by `tests/contract/fixtures/make_basalt_ple_fixture.py`. + License: `third_party/QWEN-COMMUNITY-LICENSE`, as above. ## Original diff --git a/tools/ci/mac_gpu.py b/tools/ci/mac_gpu.py index 64e14116..0959536d 100644 --- a/tools/ci/mac_gpu.py +++ b/tools/ci/mac_gpu.py @@ -8,8 +8,10 @@ module), the oracle and serving extras and mlx-lm. The module must import (``monolith.runtime.is_available()``). 2. The pinned checkpoints under ``/models`` (``tools/ci/provision.py``, every file re-hashed), exported as ``$MONOLITH_MODELS``, and the pinned reference implementations checked out afresh under ``/references`` - (``REFERENCES``). The tests run as the runner's user and can write all of these, so a run trusts nothing an earlier - run left behind except files whose hashes it checks. + (``REFERENCES``); for every tier, the n-gram block's two real-weight byte ranges fetched afresh under + ``/fixtures/ple`` (``tests/contract/fixtures/make_basalt_ple_fixture.py --full``), exported as + ``$BASALT_PLE_FIXTURE``. The tests run as the runner's user and can write all of these, so a run trusts nothing an + earlier run left behind except files whose hashes it checks. 3. One pytest run per tier, each writing JUnit XML. Every tier but the contract tier runs inside ``$LITHOS_CI_GPU_WRAPPER`` when the runner sets one: a command prefix that serializes GPU work on a shared machine. 4. The skip audit. A test may skip only for a reason ``ALLOWED_SKIPS`` lists (the chip lacks a feature, a case the @@ -112,6 +114,14 @@ def fetch_references(root: Path) -> Dict[str, str]: return env +def fetch_ple_fixture(root: Path, py: Path, repo: Path) -> Dict[str, str]: + """Fetch the n-gram block's two real-weight byte ranges afresh under ``/fixtures/ple`` with the checkout's + writer (the last run's tests could write to the last copy); returns the environment pointing at them.""" + path = fresh_dir(root, "fixtures/ple") + run([str(py), str(repo / "tests/contract/fixtures/make_basalt_ple_fixture.py"), "--full", str(path)]) + return {"BASALT_PLE_FIXTURE": str(path)} + + def tier_env(models: Path, references: Dict[str, str], shader_validation: bool) -> Dict[str, str]: env = {k: v for k, v in os.environ.items() if k not in ("HF_TOKEN", "HUGGING_FACE_HUB_TOKEN")} env.update(MONOLITH_MODELS=str(models), HF_HUB_OFFLINE="1", HF_HUB_DISABLE_TELEMETRY="1", @@ -236,6 +246,7 @@ def main(argv: List[str] | None = None) -> int: # --rehash: the last run's tests could rewrite a file and its verification record alike run([str(py), str(repo / "tools/ci/provision.py"), "--dest", str(models), "--rehash"]) references = fetch_references(args.root) + references.update(fetch_ple_fixture(args.root, py, repo)) # every tier reads it, the contract tier too env = tier_env(models, references, args.shader_validation) for tier in tiers: result["tiers"].append(run_tier(tier, py, repo, env, report, args.tier_timeout)) From edb309f39d0ca4e3ac71ed0cabc38a08e98a9512 Mon Sep 17 00:00:00 2001 From: Lance Woodson <65194841+woodsonl@users.noreply.github.com> Date: Thu, 22 Oct 2026 00:40:13 -0500 Subject: [PATCH 72/74] Port basalt's prompt-path GEMMs and 16-bit conversions to Metal The net change of woodsonl/mlxstream#32 (fork merge commit 6fac383): Gemm::bf16 and Gemm::native as basalt_prompt_gemm, one fixed fp32 fma chain per output, and to_f16 and to_bf16 as basalt_prompt_convert, with the prompt family's plumbing (PROMPT_ROWS, prompt_rows, the op and handler modules, the test harness) and its tests. Applied on #91's branch; flash-next.md, monolith/kernels.py, tests/kernels/basalt_emu.py and third_party/NOTICE keep only this PR's own lines where the fork also carries the hyper-connection write and the n-gram block (#93, #98). --- docs/design/flash-next.md | 28 +- docs/research/basalt-nvcc/dequant_bf16.md | 4 +- docs/research/basalt-nvcc/prefill_kernels.md | 892 +++++++++++++++++++ kernels/common/basalt_prompt_gemm.metal | 135 +++ monolith/compiler/emit.py | 3 +- monolith/compiler/emit_basalt_prompt.py | 124 +++ monolith/kernels.py | 60 ++ monolith/ops/__init__.py | 2 + monolith/ops/basalt_prompt.py | 43 + tests/contract/test_basalt_prompt_ops.py | 332 +++++++ tests/kernels/basalt_emu.py | 66 +- tests/kernels/basalt_prompt_gpu.py | 89 ++ tests/kernels/test_basalt_prompt_gemm.py | 459 ++++++++++ tests/kernels/test_basalt_prompt_program.py | 104 +++ third_party/NOTICE | 15 +- 15 files changed, 2340 insertions(+), 16 deletions(-) create mode 100644 docs/research/basalt-nvcc/prefill_kernels.md create mode 100644 kernels/common/basalt_prompt_gemm.metal create mode 100644 monolith/compiler/emit_basalt_prompt.py create mode 100644 monolith/ops/basalt_prompt.py create mode 100644 tests/contract/test_basalt_prompt_ops.py create mode 100644 tests/kernels/basalt_prompt_gpu.py create mode 100644 tests/kernels/test_basalt_prompt_gemm.py create mode 100644 tests/kernels/test_basalt_prompt_program.py diff --git a/docs/design/flash-next.md b/docs/design/flash-next.md index 57849526..bd00907f 100644 --- a/docs/design/flash-next.md +++ b/docs/design/flash-next.md @@ -81,6 +81,19 @@ The prompt path's own kernels, `src/prefill/kernels.cu`, build the same way (`CM `rsqrtf` and `log1pf` too (for example `src/prefill/kernels.cu:39`, `:74`, `:214`); the prompt path's port lists the ones this pack runs. +- `src/prefill/gemm.cu`, the prompt path's fp16 and BF16 products, has no device code: each product is one + `cublasGemmEx` (`gemm.cu:122-132`, `:158-167`), so cuBLAS picks the kernel, the summation order and the subnormal + handling. basalt fixes the 16-bit operand types, the fp32 output and compute type (`CUDA_R_32F`, + `CUBLAS_COMPUTE_32F`, `CUBLAS_GEMM_DEFAULT`), alpha 1 and beta 0 (the default, `include/basalt/prefill/gemm.hpp:35`, + `:43`, `:47`; no prompt-path call passes another); every FP16 product, and every BF16 product in fp32's normal range, + is exact in fp32; the order, the in-MMA rounding and the handling of smaller BF16 products are cuBLAS's and the + hardware's. The port computes each output as one fp32 `fma` chain from +0 in increasing k + (`kernels/common/basalt_prompt_gemm.metal`), which, as Metal's `fma` does, reads subnormal BF16 operands as zero and + flushes every partial sum whose exact value is below 2^-126 (a lone product included): that order is the port's, + not basalt code, so invariant 5's subnormal emulation does not apply (decided 2026-10-19 for the partial sums; for + the operands, 2026-10-20). Widened FP16 operands, their fp32 products and the partial sums are never subnormal in + fp32: nonzero operands are multiples of 2^-24, nonzero products and partial sums multiples of 2^-48. + ### Exactness invariants 1. **Window invariance.** "Token t's argmax is what plain greedy decode would produce after token t, BIT FOR BIT" @@ -103,11 +116,12 @@ ones this pack runs. (`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`, `hc_fused.md` for the - hyper-connection read, its router and the int8 copies, `dequant.md` for the GGUF dequantizers, `dequant_bf16.md` - for the prompt path's group 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 + hyper-connection read, its router and the int8 copies, `dequant.md` for the GGUF dequantizers, `dequant_bf16.md` for + the prompt path's group dequantizers, `prefill_kernels.md` for the prompt path's element-wise kernels and + conversions, `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 @@ -467,6 +481,10 @@ same rule holds for any other ported kernel whose basalt tests end in a comparis | 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`) | +| `Gemm::bf16`, the BF16 x BF16 product: the PLE value product and every BF16 projection without an int8 copy (`src/prefill/gemm.cu:122-132`; `src/prefill/prefill.cpp:1538`, `:1707`, and through `Gemm::bf16_w`'s fall-through, `gemm.cu:155`, at `prefill.cpp:1572`, `:1587`-`:1588`, `:1608`-`:1609`, `:1698`) | `hc8_parity` part 2 runs `Gemm::bf16` through `Gemm::bf16_w`, directly on a BF16 matrix (`src/kernels/hc8_parity.cpp:244`; `src/prefill/gemm.cu:155`) and on the BF16 image of an int8 copy (`hc8_parity.cpp:245-246`; `gemm.cu:151`), and gates only the copy's product against double (`hc8_parity.cpp:269`, on 256 sampled outputs, `:253-262`), at hc8's shapes | `hc8_parity`'s own gate on `Gemm::bf16`'s product, `expect(ex.rel() < 5e-3, "the product against the copy in double");` (`hc8_parity.cpp:269`), applied at this pack's plain-BF16 shapes on every output against float64; the chain bit for bit against its numpy twin; row, column, slice and repeat invariance bit for bit | +| `Gemm::native`, a GGUF matrix dequantized into an FP16 image and multiplied by `Gemm::f16` (`src/prefill/gemm.cu:169-185`, `:158-167`; `src/prefill/prefill.cpp:1191` for every quantized projection, `:1535` for the PLE key) | no test runs `Gemm::native`; `prefill_mmq_kq_test` runs `Gemm::f16` in its FP16 expert path, off this pack (`tests/cuda/prefill_mmq_kq_test.cpp:241`, `:244`), and prints that path's error against double without a bound (`:370`, `:373`; only a non-finite output fails, `:269`); `dequant_f16_parity` checks only the first stage, the FP16 image (`src/kernels/dequant_f16_parity.cpp:73`, `:98`) | borrowed (nearest bound; no basalt test gates `Gemm::native`'s or `Gemm::f16`'s product against a reference): `expect(ex.rel() < 5e-3, "the product against the copy in double");` (`hc8_parity.cpp:269`) on every output against float64 on the exact dequantized values, so the FP16 image's rounding counts; the two stages bit for bit equal to the FP16 chain on the image; repeat invariance bit for bit | +| `to_f16`, the PLE key operand for a quantized key matrix (`src/prefill/kernels.cu:818-821`, `hf` `:40`, launcher `:846-850`; `src/prefill/prefill.cpp:1534`) | no test runs `to_f16_kernel`; the nearest check, `dequant_f16_parity`'s store against `__float2half_rn` of the fp32 value (`src/kernels/dequant_f16_parity.cpp:73`), is the same rounding, bitwise | bit for bit against `emu.cuda_half_bits` on every special value (G9-F16) | +| `to_bf16`, the PLE value operand (`src/prefill/kernels.cu:826-833`, `bf` `:31-35`, launcher `:856-860`; `src/prefill/prefill.cpp:1531`, `:1536`) | no test runs `to_bf16_kernel` or `bf`; `bf16_bits_test` checks `bf16_from_f32` bitwise over every fp32 pattern against ggml's rule (`src/kernels/bf16_bits_test.cpp:47`) and, on every non-NaN input, against `previous_bf16` (`:57`), whose `u = (u + ((u >> 16) & 1u) + 0x7FFFu) & 0xFFFF0000u;` (`:30`) is `bf`'s arithmetic; on a NaN, `bf` keeps the carry that `bf16_from_f32` replaced | bit for bit against `emu.bf16_bits` on every special value, NaNs included (G9-BF16) | The ported `route_window_parity` also runs the shapes this path uses, 2560 to 128 and 2560 to 512. diff --git a/docs/research/basalt-nvcc/dequant_bf16.md b/docs/research/basalt-nvcc/dequant_bf16.md index 443d170f..85e2679e 100644 --- a/docs/research/basalt-nvcc/dequant_bf16.md +++ b/docs/research/basalt-nvcc/dequant_bf16.md @@ -85,7 +85,7 @@ images of a NaN differ (0x7fff here, 0x8000 there); the port keeps both as basal ## 2. Per-type arithmetic `group32` (`:41-166`) for each type. d, dmin, d_all and m are fp16 scales read by `h2f`; every other -factor is a small integer. This pack's projections use every type below but Q5_1 (`flash-next.md:218-219`; the +factor is a small integer. This pack's projections use every type below but Q5_1 (`flash-next.md`, "The model file"; the IQ-only types 16, 17, 18, 21, 22 and 29 go to `iq_dequant_f16` instead, `:259-267`, and this pack has none). | Type (id) | Lines | Value | SASS | Metal | @@ -157,7 +157,7 @@ the artifact's CPU dequantizers, within 10^-3 relative plus 10^-6. On Metal the bit checks; the third needs a host reference of the four types, here `tests/contract/gguf_reference.py`'s float32 values, bit for bit basalt's CPU dequantizers (`include/basalt/artifact/dequant.hpp`), compared in binary64 at basalt's bound. The prompt path converts this pack's other six types too (Q2_0, Q3_K, Q4_K, IQ4_NL, Q4_0, Q5_0; -`flash-next.md:218-219`); the type list is the test's data, so the port runs the same three checks for all ten. +`flash-next.md`, "The model file"); the type list is the test's data, so the port runs the same three checks for all ten. **`dequant_bf16_test`** (`src/kernels/dequant_bf16_test.cpp`, `CMakeLists.txt:804-807`: "not a ctest: needs the full model"). For each type `dequant_bf16_supported` accepts, the first four rows of the first two-dimensional tensor of diff --git a/docs/research/basalt-nvcc/prefill_kernels.md b/docs/research/basalt-nvcc/prefill_kernels.md new file mode 100644 index 00000000..85d4bee1 --- /dev/null +++ b/docs/research/basalt-nvcc/prefill_kernels.md @@ -0,0 +1,892 @@ +# basalt's prompt-path element-wise and recurrence kernels as nvcc compiles them + +What NVIDIA's compiler emits at every rounding site of the kernels in basalt's `src/prefill/kernels.cu` (the +element-wise, normalization, GDN, routing and KV-append kernels of batched prompt processing), read from the sm_120 +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, and its note that the prompt path's port lists the approximate operations +this pack runs: `flash-next.md:80-82`). + +Basalt paths are relative to commit `b4c63b55754637f4c72ad53a0f791d425f71eb36`; `path:a-b` means lines a to b there, +and a bare `:N` is a line of `src/prefill/kernels.cu` unless another file is named. + +## Method + +- **Date.** October 18, 2026. +- **Sources.** `src/prefill/kernels.cu` with the basalt headers it includes, inlined recursively under `#line` + markers: `include/basalt/prefill/kernels.hpp`, `include/basalt/kernels/kv_stream.hpp`, `qsa.hpp`, + `qsa_decode_attn.hpp`, `rope_scaling.hpp`, `mrope.hpp` and `router_top10.hpp`. System headers stay `#include`s. + Only basalt's public MIT source was sent. +- **`src/prefill/gemm.cu` has no device code.** It has no `__global__`, `__device__`, `__shared__` or `<<<`. `Gemm::bf16` + (`gemm.cu:122-132`) and `Gemm::f16` (`:158-167`) are one `cublasGemmEx` each (`CUBLAS_COMPUTE_32F`, + `CUBLAS_GEMM_DEFAULT`, the handle in `CUBLAS_DEFAULT_MATH`, `:80`, `:110`), so their arithmetic is cuBLAS's kernel + choice. `Gemm::native` (`:169-185`) runs `dequant_f16` (`dequant_bf16.md`) and then `Gemm::f16`. `Gemm::bf16_w` + (`:134-156`) runs `hc8_dequant_bf16` (`src/kernels/cuda/hc_fused.cu`, the hc lane's record) and then `Gemm::bf16`. + This page therefore has no `gemm.cu` section. +- **Compiler.** Compiler Explorer's public API (`POST https://godbolt.org/api/compiler/nvcc130/compile`, + `produceDevice`): NVCC 13.0.0, `Cuda compilation tools, release 13.0, V13.0.48` (`Build + cuda_13.0.r13.0/compiler.36260728_0`). Both the PTX and the `SASS (sm_120)` listings were read. 13.1 to 13.3 were + not run, since 13.0 compiled every unit. +- **Flags.** `kernels.cu` is compiled into the `prefill` static library (`CMakeLists.txt:285`), which has no + per-source or per-target CUDA options. The project sets no `CMAKE_CUDA_FLAGS`; it adds only `BASALT_VERSION` + (`:7`), defaults the build type to Release (`:12-14`) and builds for compute capability 12.0 only (`:3-4`, + `:26-31`). `kernels.cu` is not in the `--use_fast_math` list (`:185-202`), and `mmq`'s `-use_fast_math` is + `PRIVATE` to that target (`:728`). nvcc's defaults therefore hold: `-ftz=false -prec-div=true -prec-sqrt=true + -fmad=true`, which gives IEEE subnormals, correctly rounded division and square root, and `a * b + c` contracted to + one `FFMA`. userArguments, exactly: `-arch=sm_120 -lineinfo -O3 -DNDEBUG '-DBASALT_VERSION="0.0.1"'` (`-lineinfo` + only attaches source lines). +- **Translation units.** The whole file's SASS passes Compiler Explorer's 5,000-line listing cap, so the file was sent + as ten units. Each unit is the whole file with the line numbering kept: every kernel outside the unit and every + host function (`:463-478`, `:587-606`, `:837-937`, `:944-964`, `:977-1033`) is replaced by blank lines, and + explicit instantiations of the unit's templates are appended. The units are: + - `hc1`: `gr_norm`, `gr_norm_rs`, `gr_mix_r`, `gr_silu`. + - `hc2`: `gr_write_norm_rs`, `gr_mix`, `gr_write`, `gr_broadcast`. + - `gdn_small`: `gdn_gates`, `gdn_conv`, `gdn_conv_tiled`, `gdn_conv_hist`, `gdn_l2`, `gdn_out_norm`. + - `gdn_wl`, `gdn_kh`, `gdn_cp`: one recurrence kernel each. + - `route16`: `route_kernel<16>`. + - `moe`: `blob_dequant_kernel` and ``, `swiglu_il`, `swiglu_pair`, `gather_rows16`, `moe_combine`, + `route_count`, `copy_i32`, `copy_f4`. + - `rope`: `rope_kernel` and ``. + - `qsa`: `rms_rows`, `split_q`, `gate_attn`, `kv_append`, `to_f16`, `round_f16`, `to_bf16`. + + A kernel's code depends only on its own body and the device functions it calls, so the split changes no + instruction. Every listing is complete (no `[truncated]` marker). +- **Shapes are compile-time constants.** `constexpr int N = 2560, HC = 4, D = N * HC, LR = 320; constexpr int S = + 128, HK = 16, HV = 48, C = 10240;` (`:18-19`). They are this pack's hidden size, hyper-connection count, GDN state + size and heads. nvcc folds them, so `/ (float) HC` is a multiply by 0.25 and `/ (float) N` is a division by the + constant 2560. The port takes the same values from the model's dimensions as compile-time constants, never as + per-step values (invariant 4 concerns only per-step values). +- **Reading.** Every float instruction of each on-path kernel was matched to its source line (from `-lineinfo`) and, + where an expression has several products or terms, to its operands through the registers of the full listing. + +## Notation and the shared sequences + +As in `matvec.md`: fl(e) rounds once to fp32, to nearest even; fma(a, b, c) rounds a·b + c once. PTX `.ftz` appears +only in the inlined CUDA math library (`ex2.approx.ftz.f32` inside `expf`, `rcp.approx.ftz.f32` inside `powf`, +the RoPE angle's; sections 3 and 4). Basalt's own expressions compile without `.ftz`, so they keep IEEE subnormals, +and the Metal kernel follows invariant 5 at each site: `ieee_*` emulation where a subnormal can occur, plain Metal +arithmetic where the site's argument shows none can. + +Left out of every table: + +- `HFMA2 Rx, -RZ, RZ, a, b`: a constant load. It is fma(-0, 0, (a, b)), which packs two fp16 immediates into a + register. +- The index arithmetic of `__cuda_sm20_div_u16`, `__cuda_sm20_div_u64` and `__cuda_sm20_div_s64` (`I2F`, `FMUL.RZ`, + `MUFU.RCP`, `F2I`): integer divisions of indices, exact. +- The `.FTZ` compares and adds inside the slow-path subroutines `__cuda_sm3x_div_rn_noftz_f32_slowpath` and + `__cuda_sm20_rcp_rn_f32_slowpath`. They compare against infinity, propagate a NaN operand, or act on operands the + routine has already scaled away from the subnormal range. Their result is `div.rn.f32`'s or `rcp.rn.f32`'s, which + is IEEE's. + +The sequences shared by many sites: + +- **E(x), the IEEE file's `__expf(x)`.** PTX `mul.f32 t, x, 0f3FB8AA3B` (`0fBFB8AA3B` for `__expf(-x)`: the front end + folds the negation into the constant), then `ex2.approx.f32`. SASS: + `FMUL t, x, -1.4426950216293334961`; `FSETP.GEU.AND P0, PT, t, -126, PT`; `@!P0 FMUL t, t, 0.5`; `MUFU.EX2 e, t`; + `@!P0 FMUL e, e, e`. That is ex2.approx of fl(x·log2 e) with subnormal outputs kept: below −126 the argument is + halved and the result squared, so e is subnormal for t in about [−149, −126) and +0 below. The product t never + matters on its own: a subnormal t, or a flushed one, gives e = 1. Metal writes `expf_ieee(x)` at every site, since + one helper serves each operation at every site (`flash-next.md`, invariant 5): the product `ieee_mul(x, log2 e)`, + halved below −126, through `fast::exp2` (the contract's mapping), and there squared by `ieee_mul(e, e)`, so + subnormal outputs are kept; `__expf(-g)` is `expf_ieee(sign_flip(g))`, the same product since flipping the sign bit + negates exactly. Where e is used itself (`gdn_gates`, section 2) the kept subnormal matters; where e only feeds + `1.0f + e` (sigm, `gr_silu`, the SwiGLU) a subnormal e is absorbed (1 + e rounds to 1, as 1 + 0 does). +- **sigm(x) = `1.0f / (1.0f + __expf(-x))` (`:39`).** E(−x); `FADD t, e, 1`; then `rcp.rn.f32` (the front end turns + `1.0f / t` into the IEEE reciprocal): a range test `IADD3 u, t, 0x1800000`; `LOP3.LUT u, u, 0x7f800000, RZ, 0xc0`; + `ISETP.GT.U32.AND P0, PT, u, 0x1ffffff` (the exponent field plus 3, modulo 256, above 3), then the fast path + `MUFU.RCP r, t`; `FFMA d, t, r, -1`; `FADD.FTZ d, -d, -RZ`; `FFMA r, r, d, r`, else + `__cuda_sm20_rcp_rn_f32_slowpath` (t ≥ 2^126, infinite or NaN). The result is the correctly rounded 1/t, IEEE's. + t ≥ 1, so 1/t ≤ 1, but 1/t is subnormal for t > 2^126, which is x below about −87.3 (e ≥ 2^126 once + −x·log2 e ≥ 126); below about −88.7, e and t are +inf and sigm is +0. Metal's `1.0f / t` flushes that subnormal, + so Metal writes `ieee_div(1.0f, 1.0f + expf_ieee(sign_flip(x)))` (main's `ieee_div`, `basalt_q8_1.metal:181`, for + a divisor of at least 1: rcp.rn(t) is div.rn(1, t)). Each section follows a subnormal sigm into the operation that + uses it. +- **Q(a, b), IEEE `a / b`.** PTX `div.rn.f32`. SASS: `MUFU.RCP r, b`; `FCHK P0, a, b`; `FFMA d, -b, r, 1`; + `FFMA r, r, d, r`; `FFMA q, a, r, RZ`; `FFMA d, -b, q, a`; `FFMA q, r, d, q`, with `@P0` calling + `__cuda_sm3x_div_rn_noftz_f32_slowpath`. The quotient is correctly rounded and keeps subnormals. Metal: `a / b` + where no operand or quotient can be subnormal; where one can, `ieee_div(a, b)` (divisor at least 1) or the general + IEEE division (`ieee_div_any(a, b)` on `origin/woodsonl/basalt-sampler`). +- **Division by the constant N = 2560.** The reciprocal is refined from the immediate 0x39CCCCCD (loaded as `HFMA2 + R7, -RZ, RZ, 0.724609375, -19.203125`): `FFMA r0, R7, -2560, 1` (shown as `FFMA R4, R7, -R4, 1`) and `FFMA r, r0, + R7, 0.00039062500582076609135`. Then `FCHK P0, a, 2560`; `FFMA q, a, r, RZ`; `FFMA d, q, -2560, a`; `FFMA q, r, d, + q`. This is the same correctly rounded `div.rn.f32`. Metal: `a / 2560.0f`. +- **`/ (float) HC` (HC = 4).** `FMUL x, x, 0.25`. This is exact unless the product falls below 2^-126, where IEEE keeps + the subnormal. Metal: `x * 0.25f`, with a subnormal result possible only where the section says so. +- **rsqrtf(x).** PTX `rsqrt.approx.f32`. SASS: `FSETP.GEU.AND P0, PT, |x|, 1.175494350822287508e-38, PT`; `@!P0 FMUL x, + x, 16777216`; `MUFU.RSQ r, x`; `@!P0 FMUL r, r, 4096`. A subnormal argument is scaled by 2^24 and the result by + 2^12. Metal: `fast::rsqrt(x)` (invariant 5). Every on-path argument is at least eps or at least the constant S, + so the wrapper never fires. +- **hf(f) = `__half_as_ushort(__float2half_rn(f))` (`:40`).** PTX `cvt.rn.f16.f32`. SASS: `F2FP.F16.F32.PACK_AB d, + RZ, f` (or `F2F.F16.F32`). The conversion rounds to nearest even, overflows to infinity, keeps fp16 subnormals and + rounds an fp32 subnormal to the zero of its sign, since every fp32 subnormal is below half of fp16's smallest + subnormal 2^-24. It stores a NaN as 0x7fff (`nan.md`). Metal: `cuda_nan_f16(f16_bits(f))` (`basalt_fp.metal`), + which gives the same bits for every input. +- **bf(f) (`:31-35`).** Integer operations only on the bits (`u += 0x7fffu + ((u >> 16) & 1u)`, then the high + half): round to nearest even with no NaN case, so a NaN's low payload carries into the exponent and the sign. + sm_120's arithmetic gives every NaN it makes or passes as 0x7fffffff (`nan.md`), which bf turns into 0x8000, the + BF16 −0: in basalt a NaN activation's BF16 image is −0, and so is its bf_lo image (below). This GPU's arithmetic + NaN is 0x7fc00000, which bf would turn into the NaN 0x7fc0. Metal: the same integer expression on + `as_type(f)`, applied to `cuda_nan(f)` where f is the result of arithmetic, and to the raw bits where f is + only loaded (`to_bf16`, section 5). +- **bf_lo(f, hi) (`:38`).** `FADD r, f, -h` with h = `__uint_as_float((uint32_t) hi << 16)`, then bf(r). h is f + rounded to BF16, so f − h is a multiple of f's fp32 ulp (or of 2^-149) of magnitude at most half a BF16 ulp: the + difference is exact, normal or subnormal. It is subnormal for every f below 2^-118 that is not a BF16 value and for + some f below 2^-102, and f itself may be subnormal; CUDA keeps both, while Metal's `-` reads and writes them as + zero. For a NaN f, h is −0 (bf's 0x8000) and f − h is CUDA's 0x7fffffff, so the low image is 0x8000 too. Metal: + `bf(cuda_nan(ieee_add(f, -h)))` with f the value already passed through `cuda_nan` (`ieee_add`, + `basalt_q8_1.metal:95`, is exact here: the difference is representable). +- **warp_sum (`:21-25`).** `SHFL.BFLY` and `FADD` with offsets 16, 8, 4, 2, 1; v = fl(v + shfl). Metal: `warp_sum` + (`basalt_fp.metal:102`), or `warp_sum_ieee` (`basalt_q8_1.metal:206`) where a subnormal sum can occur. +- **block_sum (`:46-58`).** warp_sum in every warp; warp w's sum to `sh[w]`; warp 0 sums `sh[0..nw)` (zeros past nw) + with warp_sum again, and `sh[0]` is broadcast. Metal: the same two butterflies through threadgroup memory, with a + barrier at each `__syncthreads`. + +## Summary + +- **On the path** (this pack, `src/prefill/prefill.cpp`): the hyper-connection kernels `gr_broadcast`, `gr_norm_rs`, + `gr_silu`, `gr_mix_r`, `gr_write_norm_rs`, `gr_write` (section 1); `gdn_gates`, `gdn_conv` or + `gdn_conv_tiled` with `gdn_conv_hist`, `gdn_l2`, `gdn_rec_wl`, `gdn_out_norm` (section 2); `route_kernel<16>`, + `route_count`, `swiglu_pair`, `moe_combine` (section 3); `rms_rows`, `rope_kernel`, `split_q`, `gate_attn`, + `kv_append`'s fp16 branch (section 4); `to_f16`, `to_bf16` without `ylo`, `copy_i32` (section 5). Section 6 + records `gdn_rec_parity`'s reference kernel, section 7 the kernels that do not run. `gemm.cu` has no device code. +- **The approximate operations this pack's prompt path runs in `kernels.cu`** (the list `flash-next.md:80-82` asks + for); everything else is a correctly rounded fp32 operation, an exact sequence, or integer arithmetic: + 1. `__expf` (`ex2.approx.f32`: `MUFU.EX2` with the −126 scaling, Notation's E(x)) in sigm and the SiLU and SwiGLU + terms of sections 1 to 3, in `gdn_gates` (`:214`) and in the decay of `gdn_rec_wl` (`:551`). Metal: + `expf_ieee` at every site, `expf_ieee(sign_flip(x))` for `__expf(-x)`. + 2. `rsqrtf` (`rsqrt.approx.f32`, `MUFU.RSQ`) in `gr_norm_rs`, `gr_write_norm_rs`, `gdn_l2`, `gdn_out_norm` and + `rms_rows`. Metal: `fast::rsqrt`; no argument reaches the subnormal wrapper. + 3. The library `expf`, libdevice's `__nv_expf` inlined, whose one approximate step is `ex2.approx.ftz.f32`, in + `route_kernel` (`:642`) and `gate_attn` (`:770`). Metal: the contract's `precise::exp` + (`flash-next.md:153`), or `nv_expf`, every other step transcribed, proposed in section 3 for the owner. + 4. `powf`, libdevice's `__nv_powf` inlined, whose one approximate step is `rcp.approx.ftz.f32`, in `rope` (`:751`). + Metal: `nv_powf` with `1.0f / x` there; for this pack's theta_scale no result depends on that reciprocal's last + bits [M] (section 4). + + `log1pf` (`gdn_gates`), `cosf` and `sinf` (`rope`) compile to sequences of correctly rounded operations with no + approximate instruction, and every `/` and `1.0f / x` to IEEE's correctly rounded quotient (a `MUFU.RCP` seed + refined to the exact rounding); the port transcribes the first three (`log1pf_cuda`, `nv_cosf`, `nv_sinf`) and + uses Metal's `/` or the IEEE helpers for the rest. +- **Subnormals.** The file is built without `-ftz`, and its data are arbitrary fp32 values, so nearly every product, + sum and quotient can be subnormal: the tables use `ieee_mul`, `ieee_add`, `warp_sum_ieee`, `ieee_div` (main), a + general `ieee_fma_any` and `ieee_div_any`, and every fp32 store of an arithmetic result writes `cuda_nan(x)`. + Plain Metal arithmetic stands only where a section shows that no subnormal can change a bit. +- **Helpers main lacks.** `ieee_fma_any` (general IEEE fma), `ieee_div_any` (`origin/woodsonl/basalt-sampler`), + `expf_ieee` with `sign_flip`, `log1pf_cuda`, `nv_expf`, `nv_powf`, `nv_cosf` and `nv_sinf` (with the sampler + branch's `f64_round`, `f64_mul` and `f32_from_f64` for the Payne-Hanek path), and the sampler branch's float keys + `okey`, `f_gt`, `fmaxf_bits`. One shared copy each, beside the existing `ieee_*` and libdevice helpers. +- **Invariance.** No kernel's output for a token depends on the chunk length T or on the token's place in the chunk + (each section's note); T, `pos0`, the element counts and the page table are per-step values the port reads from the + step's state or a buffer (invariant 4). The prompt path's routing weights, rotated keys and GDN row sums are not + decode's: decode runs other kernels (`hc_top10`, the fast-math `native_rope.cu`, `dec_gdn_rec`), so the two paths + need not share bits, and the port keeps them separate as basalt does. + +## 1. Hyper-connection kernels + +The residual `R` holds HC = 4 streams of N = 2560 fp32 values per token (`T × HC × N`). On this pack's prompt path +(`src/prefill/prefill.cpp`) the kernels are `gr_broadcast` (`prefill.cpp:1311`), `gr_norm_rs` (`:1567`, and the +drafter's KV rows at `:1015`), `gr_silu` (`:1570`), `gr_mix_r` (`:1573`), and at a block's end `gr_write_norm_rs` +(`:2376`) or `gr_write` (`:2379`). `gr_norm` and `gr_mix` have no caller outside `kernels.cu` (section 7). + +**Where a subnormal can occur.** R, the block outputs `bo`, the norm weights `w`, the gate logits `g`, `inj` and +`lo` are arbitrary fp32 data. An element below 2^-63 in magnitude has a subnormal square; a partial sum of squares +of such elements is subnormal; `r · rs · w` is subnormal for small enough `r` (rs is at most eps^-1/2 ≈ 1000); +sigm(x) is subnormal for x below about −87.3 (Notation), so `x · sigm` and the fma chains can be; the residual update +`fma(bo, sc, r)` can produce or read one. CUDA keeps all of these and the BF16, fp16 and fp32 images carry them, so +every product and sum below uses an IEEE helper: `ieee_mul`, `ieee_add` and `warp_sum_ieee` (main), `ieee_div` for +a divisor of at least 1 (main), and a general IEEE fma, here `ieee_fma_any(a, b, c)` (main's `ieee_fma` takes only +an integer multiplier, `basalt_q8_1.metal:167`; the prompt path's GDN plan defines the general one). With them every +product, sum and conversion gives CUDA's bits for every input; only `rsqrtf` and `__expf` follow the contract's +approximate mappings. Every fp32 store of an arithmetic result (`rs_out`, `mixed`, `R`) writes `cuda_nan(x)`. + +### `gr_norm_rs_kernel` (`:85-102`) + +Grid `T·HC` threadgroups of 256 threads (`:864`), one row `(t, c)` each; thread `tid` handles `d = tid + 256k`, +k = 0..9 in order. Outputs `rs_out[row]`, the BF16 image `xn16` and, when non-null, its low part `xn16_lo`. + +| Line | Expression | SASS | Metal | +|---|---|---|---| +| `:93` | `ss += r[d] * r[d]` | `FFMA ss, r, r, RZ` for k = 0 (ss = +0 folded), then `FFMA ss, r, r, ss`, k ascending | `ss = ieee_fma_any(r, r, ss)` from `ss = 0.0f`, k ascending | +| `:94` | `block_sum(ss, sh)` | `SHFL.BFLY` and `FADD` at offsets 16, 8, 4, 2, 1 (`:23`); warp 0 repeats them over `sh[0..8)` and 24 zeros | block_sum (Notation) with `warp_sum_ieee` | +| `:94` | `/ (float) N + eps` | the constant-2560 division (Notation); `FADD q, q, UR4` | `q = s / 2560.0f; q + eps`: plain operations are exact here, since a quotient below 2^-126 (s below 2^-114.7) gives fl(q + eps) = eps in both (eps = `EPS` = 1e-6f, `prefill.cpp:57`) | +| `:94` | `rsqrtf(·)` | the rsqrtf sequence; the argument is at least eps, so the scaling never fires | `fast::rsqrt(q + eps)` | +| `:97` | `r[d] * rs * w[c * N + d]` | `FMUL a, rs, r`; `FMUL v, a, w` (left to right; the multiply commutes) | `ieee_mul(ieee_mul(r, rs), w)` | +| `:98` | `bf(v)` | integer operations | bf on `as_type(cuda_nan(v))` | +| `:100` | `bf_lo(v, h)` | `FADD d, v, -h` (`:38`) | `bf(cuda_nan(ieee_add(v, -h)))` | + +### `gr_mix_r_kernel` (`:103-124`) + +`blocks_for(T·N)` threadgroups of 256 (`:874`), one output `i = t·N + d` per thread. The loop over c is unrolled. + +| Line | Expression | SASS | Metal | +|---|---|---|---| +| `:113` | `R[j] * rs[t * HC + c] * w[c * N + d]` | `FMUL a, R, rs`; `FMUL x, a, w` | `ieee_mul(ieee_mul(R, rs), w)`: gr_norm_rs's `v`, bit for bit, as the source's comment says | +| `:39` | `sigm(g[j])` | E(−g), `FADD t, e, 1`, rcp.rn (Notation) | `ieee_div(1.0f, 1.0f + expf_ieee(sign_flip(g)))` | +| `:114` | `s = fmaf(x, sigm(g[j]), s)` | c = 0: `FFMA s, x, sig, RZ`; c = 1, 2, 3: `FFMA s, x, sig, s` | `s = ieee_fma_any(x, sig, s)` from `s = 0.0f`, c ascending. fma(x, sig, +0) is not fl(x·sig) for a −0 product: (−0) + (+0) is +0, so the literal chain from `0.0f` is required | +| `:116` | `s /= (float) HC` | `FMUL s, s, 0.25` | `ieee_mul(s, 0.25f)` (inexact only for a subnormal result) | +| `:117` | `mixed[i] = s` | `STG` | `cuda_nan(s)` | +| `:119-120` | `bf(s)`, `bf_lo(s, h)` | integer operations; `FADD d, s, -h` | as `gr_norm_rs` `:98`, `:100` | +| `:122` | `hf(s)` | `F2FP.F16.F32.PACK_AB h, RZ, s` (`cuda_fp16.hpp:566`) | `cuda_nan_f16(f16_bits(s))` | + +### `gr_silu_kernel` (`:161-170`) + +`blocks_for(T·LR)` threadgroups of 256 (`:885`), LR = 320, one element per thread. + +| Line | Expression | SASS | Metal | +|---|---|---|---| +| `:165` | `lo[i] / (float) HC` | `FMUL x, lo, 0.25` | `ieee_mul(lo, 0.25f)` | +| `:166` | `__expf(-x)` | E(−x) | `expf_ieee(sign_flip(x))`: a subnormal e is absorbed by `1 + e` | +| `:166` | `1.0f + e` | `FADD t, e, 1` | `1.0f + e` (t ≥ 1, or +inf for x below about −88.72) | +| `:166` | `x / t` | Q(x, t), slow path `__cuda_sm3x_div_rn_noftz_f32_slowpath` | `ieee_div(x, t)`. v is subnormal only for x below about 2^-125 in magnitude (v ≈ x/2); for x below −88.72, t = +inf and v = −0; between, \|v\| ≥ 2.6e-37 | +| `:167`, `:169` | `bf(v)`, `bf_lo(v, h)` | integer operations; `FADD d, v, -h` | as `gr_norm_rs` `:98`, `:100` | + +### `gr_write_norm_rs_kernel` (`:129-160`) + +Grid `T·HC` threadgroups of 256 (`:880`, `__launch_bounds__(256)`): `gr_write` on one row `(t, c)` fused with +`gr_norm_rs`'s reduction. The source's comment (`:125-127`) promises that rs and the BF16 image are the bits the two +separate kernels give: the same mapping (stride 256, k = 0..9) and the same block_sum. The port keeps this +invariance; the residual row stays in registers (`v[GRW_PER]`, `GRW_PER = 10`, `:128`). + +| Line | Expression | SASS | Metal | +|---|---|---|---| +| `:139` | `__expf(-(inj[..] / (float) HC))` | `FMUL a, inj, -0.25` (the quotient and E's negation folded into one multiply); `FMUL u, a, 1.4426950216293334961`; E's tail | `expf_ieee(sign_flip(inj * 0.25f))`: fl(fl(−0.25·inj)·log2 e) = −fl(fl(0.25·inj)·log2 e), the same product; a subnormal quotient gives e = 1 either way | +| `:39` | `1.0f / (1.0f + e)` | `FADD t, e, 1`; rcp.rn | `ieee_div(1.0f, t)` | +| `:139` | `2.0f * sig` | `FADD sc, sig, sig` | `ieee_add(sig, sig)`, exact (sig is subnormal for `inj` below about −349) | +| `:145` | `fmaf(bo[t * N + d], sc, r[d])` | `FFMA x, sc, bo, r` | `ieee_fma_any(bo, sc, r)`; `r[d]` stores `cuda_nan(x)` | +| `:148` | `ss += x * x` | `FFMA ss, x, x, RZ` (k = 0), then `FFMA ss, x, x, ss` | as `gr_norm_rs` `:93` | +| `:150` | `rsqrtf(block_sum(ss, sh) / (float) N + eps)` | as `gr_norm_rs` `:94` | as `gr_norm_rs` `:94` | +| `:155` | `v[k] * rs * w[c * N + d]` | `FMUL a, v, rs`; `FMUL x, a, w` | `ieee_mul(ieee_mul(v, rs), w)` | +| `:156`, `:158` | `bf(x)`, `bf_lo(x, h)` | integer operations; `FADD d, x, -h` | as `gr_norm_rs` `:98`, `:100` | + +### `gr_write_kernel` (`:192-198`) + +`blocks_for(T·D)` threadgroups of 256, one residual element per thread. + +| Line | Expression | SASS | Metal | +|---|---|---|---| +| `:197` | `sigm(inj[..] / (float) HC)` | `FMUL a, inj, -0.25`; `FMUL u, a, 1.4426950216293334961`; E's tail; `FADD t, e, 1`; rcp.rn (slow path at `:198`) | as `gr_write_norm_rs` `:139`, `:39` | +| `:197` | `2.0f * sig` | `FADD sc, sig, sig` | `ieee_add(sig, sig)` | +| `:197` | `fmaf(bo[t * N + d], sc, R[i])` | `FFMA x, bo, sc, R` | `ieee_fma_any(bo, sc, R)`, stored as `cuda_nan(x)`: the bits `gr_write_norm_rs` stores | + +### `gr_broadcast_kernel` (`:199-204`) + +`R[i] = e[t * N + d]`: a load and a store, no float instruction. The Metal kernel copies 32-bit words as `uint`, +which keeps subnormal and NaN bits. + +## 2. GDN kernels + +On this pack's prompt path each GDN layer runs `gdn_gates` (`prefill.cpp:1589`), then `gdn_conv` (`prefill.cpp:1590`: +`gdn_conv_kernel` for a chunk of at most `CONV_TILE` = 64 tokens, else `gdn_conv_tiled_kernel` and +`gdn_conv_hist_kernel`; then always `gdn_l2_kernel`, `:905-915`), then `gdn_recurrence` (`prefill.cpp:1591`: +`gdn_rec_wl_kernel`, then `gdn_out_norm_kernel`, `:916-928`). `gdn_warp_ok` (`:587-606`) selects the warp kernel on +a card that holds all 128 of its threadgroups (`HK · GDN_WNCB`) at once, as basalt's 170-SM RTX 5090 does +(`dense_tc.md:193-195`); +`gdn_rec_kh_kernel` and `gdn_rec_cols_pipe_kernel` are the fallbacks and `gdn_rec_parity`'s references (section 6). +Both `eps` arguments are `EPS` = 1e-6f (`prefill.cpp:57`, `:1590-1591`). + +**Chunk invariance.** A token's outputs do not depend on the chunk length T or on where a chunk boundary falls: the +recurrence walks the chunk's tokens in order with the state in fp32 and stores it as fp32 at the end, the tiled and +untiled convolutions evaluate the same expression on the same operands (`:232-234`, and the SASS below) with the +history holding raw inputs, and the gates, the L2 norm and the output norm work per token. The port keeps this. +The recurrence's row sums run in `gdn_rec_wl_kernel`'s own order, which is not the order of the other two prompt +kernels (`:484`); the port reproduces this order for the prompt path. + +**Where a subnormal can occur.** `ab`, `dt`, `ssm_a`, `qkv`, the conv weights, the state, `z` and `gamma` are +arbitrary fp32 data. `__expf(v)` is subnormal for v in about [−103.3, −87.3), and two sites use it directly: +`log1pf(__expf(v))` returns it (below), and the decay g = `__expf(gate)` multiplies the state. Those two sites +therefore need `expf_ieee` (Notation, E(x)), which every other `__expf` site calls too; where e only feeds `1 + e`, +a subnormal e is absorbed. sigm can be subnormal (beta, the output gate), and every product and sum of the +convolution, the norms and the recurrence can be. As in section 1, every product and sum uses an IEEE helper, and +every fp32 store of an arithmetic result writes `cuda_nan(x)`. + +### `gdn_gates_kernel` (`:207-216`) + +`blocks_for(T·HV)` threadgroups of 256 (`:902`), one (t, h) per thread, HV = 48. Each token's `ab` row holds the +48 alpha logits, then the 48 beta logits (`prefill.cpp:1587-1588`). + +| Line | Expression | SASS | Metal | +|---|---|---|---| +| `:213` | `ab[..] + dt[h]` | `FADD v, ab, dt` | `ab + dt`. A subnormal operand changes v only where \|v\| < 2^-101, and there e = 1 on both, so plain addition gives CUDA's gate | +| `:214` | `v > 20.0f` | `FSETP.GT.AND P0, PT, v, 20, PT`; branch | `v > 20.0f`: a NaN v takes the `log1pf` branch | +| `:214` | `__expf(v)` | E(v): `FMUL t, v, 1.4426950216293334961`, the −126 test, `MUFU.EX2`, the squaring | `expf_ieee(v)`: log1pf returns a subnormal e itself | +| `:214` | `log1pf(e)` | the CUDA library sequence, inlined (below) | `log1pf_cuda(e)` | +| `:214` | `(·) * ssm_a[h]` | `FMUL gate, ssm_a, r` (also for the `v > 20` branch, r = v) | `ieee_mul(r, ssm_a)`, stored as `cuda_nan(·)` | +| `:215` | `sigm(ab[..])` | E(−x), `FADD t, e, 1`, rcp.rn (slow path at `:216`) | `ieee_div(1.0f, 1.0f + expf_ieee(sign_flip(x)))`, stored as `cuda_nan(·)` | + +The inlined `log1pf(e)` (unit `gdn_small`, SASS offsets 784-1184; the PTX constants in brackets). `bits(x)` is the +fp32 bit pattern, and the integer steps act on 32-bit words: + +``` +u = FADD.RZ e, 1 // e + 1 rounded toward zero +k = (bits(u) - 0x3f400000) & 0xff800000 // IADD3, LOP3.LUT +m = float_from_bits(bits(e) - k) // e · 2^-(k >> 23) +s4 = float_from_bits(0x40800000 - k) // 4 · 2^-(k >> 23) +fk = I2FP.F32.S32(k) * 1.1920928955078125e-07 // (k >> 23) as a float, exact +t = FADD m, FFMA(s4, 0.25, -1) // [0x3E800000] +p = FFMA t, -0.045348..., 0.10546888411045074463 // [0xBD39BF78, 0x3DD80012] +p = FFMA t, p, c for c = -0.13229703903198242188, 0.14491446316242218018, -0.16641564667224884033, + 0.19988867640495300293, -0.25000196695327758789, 0.33333510160446166992, -0.5 + // [0xBE0778E0, 0x3E146475, 0xBE2A68DD, 0x3E4CAF9E, 0xBE800042, 0x3EAAAAE6, 0xBF000000] +q = FMUL t, p +r = FFMA t, q, t +r = FFMA fk, 0.69314718246459960938, r // [0x3F317218] +if bits(e) >= 0x7f800000 (unsigned): // +inf, NaN or a negative e + if (int) bits(e) > (int) 0xbf800000: r = FFMA e, +inf, +inf + r = (e != 0) ? r : -0 +``` + +Here e ≥ 0 or NaN, and e ≤ e^20 on this branch, so the last lines matter only for a NaN e, which gives a NaN r. For a +subnormal or zero e, CUDA's sequence returns e itself: u = 1, k = 0, s4·0.25 − 1 = 0, t = e, r = fma(t, q, t) = t, +fk = 0. Metal's flushing arithmetic would return 0 instead. Metal: `log1pf_cuda(e)` transcribes the sequence, with +`fma()` at every `FFMA`, the integer steps on `as_type`, an early `return e` for a zero exponent field, and +`FADD.RZ` emulated, since MSL has no rounding-mode control. For e ≥ 0 that is fl(e + 1), moved one ulp toward zero +where the exact two-sum error of e + 1 is negative. + +### `gdn_conv_kernel` (`:218-231`) and `gdn_conv_tiled_kernel` (`:236-252`) + +`gdn_conv_kernel`: C/128 = 80 threadgroups of 128 threads (`:907`), one channel per thread, walking the chunk +(T ≤ 64) and carrying the three-tap history in registers. `gdn_conv_tiled_kernel`: `dim3(C/128, ⌈T/64⌉)` threadgroups +of 128 (`:909-910`), one (channel, 64-token tile) per thread, reading the tile's three predecessors from the chunk or +the history (`:243`); then `gdn_conv_hist_kernel` (`:254-263`, loads and stores only, `:911`) writes the chunk's +last three inputs as the new history. C = 10240 channels (q and k: 2·HK·S, then v: HV·S). + +| Line | Expression | SASS | Metal | +|---|---|---|---| +| `:226`, `:248` | `v0 * w0 + v1 * w1 + v2 * w2 + x * w3` | `FMUL p, w1, v1`; `FFMA s, w0, v0, p`; `FFMA s, w2, v2, s`; `FFMA s, w3, x, s`, in both kernels and every unrolled token (the tiled kernel's operands traced to its loads of `w` at +0, +4, +8, +0xc and of the taps) | `ieee_fma_any(w3, x, ieee_fma_any(w2, v2, ieee_fma_any(w0, v0, ieee_mul(w1, v1))))`. The front end contracts `a·b + c·d` to fma(a, b, fl(c·d)), so the second product is the rounded one | +| `:227`, `:249` | `__expf(-s)` | E(−s) | `expf_ieee(sign_flip(s))`: e only feeds `1 + e` | +| `:227`, `:249` | `1.0f + e` | `FADD t, e, 1` | `1.0f + e` (t ≥ 1, or +inf for s below about −88.72) | +| `:227`, `:249` | `s / t` | Q(s, t) | `ieee_div(s, t)`, stored as `cuda_nan(·)` | + +The history moves (`:228`, `:230`, `:262`) are copies: the Metal kernel moves the 32-bit words, which keeps subnormal +and NaN bits. + +### `gdn_l2_kernel` (`:264-276`) + +`dim3(2·HK, T)` threadgroups of S = 128 threads (`:913`): one (token, q or k head) per threadgroup, one element per +thread, normalized in place. + +| Line | Expression | SASS | Metal | +|---|---|---|---| +| `:270` | `warp_sum(v * v)` | `FMUL a, v, v`; warp_sum's five `FADD`s (`:23`) | `warp_sum_ieee(ieee_mul(v, v))` | +| `:274` | `part[0] + part[1] + part[2] + part[3]` | `LDS.128`; `FADD a, p0, p1`; `FADD a, a, p2`; `FADD a, a, p3` | `ieee_add(ieee_add(ieee_add(p0, p1), p2), p3)` | +| `:275` | `rsqrtf(ss + eps)` | `FADD a, ss, eps`; the rsqrtf sequence | `fast::rsqrt(ss + eps)`. Plain addition is exact here: a subnormal ss gives eps on both | +| `:275` | `v * rs` | `FMUL x, v, rs` | `ieee_mul(v, rs)`, stored as `cuda_nan(·)` | + +### `gdn_rec_wl_kernel` (`:486-585`) + +HK·GDN_WNCB = 128 threadgroups of GDN_WC·8 = 128 threads (`:485`, `:920`). Threadgroup (qh, cb) owns key head qh, +its VPK = 3 value heads qh + j·HK and the 16 value columns from cb·16. Thread `tid` (SIMD-group w = tid >> 5, lane l) +holds column c = 4w + (l >> 3) and, with rg = l & 7, the 16 state rows 4·rg + 32·m + e (m, e < 4) of each value +head: `s[3][16]` in registers, loaded and stored as fp32 (`:506`, `:584`). The tokens run in order, staged 16 at a +time into threadgroup memory by `cp.async` (copies only). Per token: + +| Line | Expression | SASS | Metal | +|---|---|---|---| +| `:551` | `g[j] = __expf(sg[..][j])` | E(x) with the positive constant | `expf_ieee(gate)`: g multiplies the state and is subnormal for a gate in about [−103.3, −87.3) | +| `:555` | `kv[j] = fmaf(s[j][r], kc[r], kv[j])`, r = 0..15 from `kv[j] = 0.0f` | `FFMA kv, kc, s, RZ` (r = 0), then `FFMA kv, kc, s, kv`, r ascending | `kv = ieee_fma_any(s, kc, kv)` from `0.0f`, r ascending | +| `:559` | `kv[j] += __shfl_xor_sync(.., kv[j], x)`, x = 1, 2, 4 | `SHFL.BFLY`; `FADD` | `kv = ieee_add(kv, simd_shuffle_xor(kv, x))`, x = 1, 2, 4. The eight row-group lanes end with the same bits | +| `:561` | `(sv[..][c] - g[j] * kv[j]) * sb[..][j]` | `FFMA d, -g, kv, v`; `FMUL d, d, beta`: ptxas contracts the subtraction into the fma | `ieee_mul(ieee_fma_any(-g, kv, v), beta)` | +| `:566` | `s[j][r] = fmaf(g[j], s[j][r], kc[r] * delta[j])` | `FMUL kd, kc, delta`; `FFMA s, g, s, kd` | `s = ieee_fma_any(g, s, ieee_mul(kc, delta))` | +| `:567` | `o[j] = fmaf(s[j][r], qc[r], o[j])`, r = 0..15 from `o[j] = 0.0f` | `FFMA o, s, qc, RZ` (r = 0), then `FFMA o, s, qc, o`, each after its row's `:566` | `o = ieee_fma_any(s, qc, o)` from `0.0f`, r ascending, with the updated s | +| `:572` | `o[j] += __shfl_xor_sync(.., o[j], x)`, x = 1, 2, 4 | `SHFL.BFLY`; `FADD` | as `:559` | +| `:575` | `o * rsqrtf((float) S)` | `FMUL y, o, 0.08838834613561630249`: nvcc folds `rsqrtf(128.0f)` to 0x3DB504F3, the correctly rounded 2^-3.5 | `ieee_mul(o, as_type(0x3DB504F3u))`, the literal and not `fast::rsqrt(128.0f)`; stored as `cuda_nan(·)` by the lanes with rg = j < 3 | + +### `gdn_out_norm_kernel` (`:609-623`) + +`dim3(T, HV)` threadgroups of S = 128 (`:925`), one (token, value head) per threadgroup and one column per thread. +It writes the fp16 copy `y16` that the output projection reads. + +| Line | Expression | SASS | Metal | +|---|---|---|---| +| `:617` | `warp_sum(oc * oc)` | `FMUL a, oc, oc`; warp_sum | `warp_sum_ieee(ieee_mul(oc, oc))` | +| `:620` | `wsum[0] + wsum[1] + wsum[2] + wsum[3]` | `LDS.128`; three `FADD`s, left to right | as `gdn_l2` `:274` | +| `:621` | `ss / (float) S + eps` | `FFMA a, ss, 0.0078125, eps`: the division by 128 becomes a multiply by 2^-7 (the same rounded quotient for every ss), contracted with the addition | `fma(ss, 0.0078125f, eps)`. Plain fma is exact here: a subnormal ss or product gives eps on both | +| `:621` | `rsqrtf(·)` | the rsqrtf sequence | `fast::rsqrt(·)` | +| `:621` | `oc * rs * gamma[col] * sigm(z[..])` | `FMUL a, oc, rs`; `FMUL a, a, gamma`; sigm (E(−z), `FADD t, e, 1`, rcp.rn, slow path at `:623`); `FMUL v, a, sig` | `ieee_mul(ieee_mul(ieee_mul(oc, rs), gamma), ieee_div(1.0f, 1.0f + expf_ieee(sign_flip(z))))` | +| `:622` | `hf(v)` | `F2FP.F16.F32.PACK_AB h, RZ, v` | `cuda_nan_f16(f16_bits(v))` | + +## 3. Routing and expert combine + +Each MoE layer of this pack's prompt path computes the router logits (`bf16_proj`, `prefill.cpp:1698`), runs +`route` (`prefill.cpp:1699`) and `route_count` (`prefill.cpp:1700`, only while the expert histogram is on), then the +shared expert: its gate and up projections (`prefill.cpp:1702-1703`), `swiglu_pair` (`prefill.cpp:1704`, T rows of +640) and its down projection (`prefill.cpp:1705`), all three on `Gemm::native`, and its gate logit `sg`, one BF16 +column (`prefill.cpp:1707`). After the routed experts, `moe_combine` (`prefill.cpp:2361`) sums their rows `Dm` with +the shared expert's output; its result `bo` feeds `gr_write_norm_rs` or `gr_write` (section 1). `route` (`:929-937`) launches `route_kernel<16>` for `n_expert == 512`, this pack's count +(`flash-next.md:228`); `route_kernel<8>` (256 experts) and `basalt::kernels::router_top10` (any other count) do not +run here (section 7). The decode step's router is a different kernel (`hc_top10`, the hc lane's), so a token's +expert weights from the prompt path and from decode need not share bits. + +**Chunk invariance.** A token's outputs do not depend on T or on its place in the chunk: `route_kernel` gives each +token one warp (`(T + 7) / 8` threadgroups of 256, `:931`), `swiglu_pair` and `moe_combine` compute one element per +thread, and `route_count` adds integers, whose sum does not depend on the order of the atomic adds. The port keeps +one SIMD-group per token with basalt's lane layout (lane l holds the logits l + 32·i, i < 16, `:635`), because the +sums and the tie rule below depend on it. + +**Where a subnormal can occur.** The logits, `Dm`, `shared`, `sg`, `g` and `u` are arbitrary fp32 data. In +`route_kernel` the softmax term e = expf(d), d = v − mx ≤ 0, is subnormal for d in about (−103.97, −87.34) and +0 +below, so the probabilities, the lanes' sums, the selected sums and the stored quotients can be subnormal too. In +`moe_combine` the routing weights `w` and every partial sum can be, and so can sigm (Notation). The sites below use +the IEEE helpers, and every compare that orders probabilities runs on integer keys: `okey`, `f_gt` and +`fmaxf_bits` (`origin/woodsonl/basalt-sampler:kernels/common/basalt_sampler.metal:37`, `:43`, `:48`), with −0 and +0 +equal. + +**The library `expf` (`:642`).** This file is built without fast math, so `expf` is libdevice's `__nv_expf`, +inlined. PTX: + +``` +sub.f32 d, v, mx; +fma.rn.f32 t, d, 0f3BBB989D, 0f3F000000; // log2(e)/252, 0.5 +cvt.sat.f32.f32 t, t; +fma.rm.f32 j, t, 0f437C0000, 0f4B400001; // 252, 12582913 = 1.5 * 2^23 + 1 +add.f32 n, j, 0fCB40007F; // -12583039 +neg.f32 n, n; +fma.rn.f32 f, d, 0f3FB8AA3B, n; // log2(e) +fma.rn.f32 f, d, 0f32A57060, f; // log2(e)'s low part, 1.925963033500011079e-08 +shl.b32 s, j, 23; +ex2.approx.ftz.f32 x, f; +mul.f32 e, x, s; +``` + +SASS: `FADD d, v, -mx`; `FFMA.SAT t, d, R3, 0.5` (R3 = 0x3BBB989D; the `cvt.sat` folded into the fma); +`FFMA.RM j, t, R2, 12582913` (R2 = 252); `FADD n, j, -12583039`; `FFMA f, d, 1.4426950216293334961, -n`; +`FFMA f, d, 1.925963033500011079e-08, f`; `MUFU.EX2 x, f` (no −126 wrapper: `.ftz`); an integer shift for s; +`FMUL e, s, x`. With k = ⌊252·t⌋ (exact, from the round-down fma), j = 12582913 + k, n = k − 126 and +s = 2^(k−126), a normal power of two (the shift keeps j's low 9 bits, k + 1). For d ≤ 0, k ≤ 126 and f is in about [0, 1) +except when t saturates at 0 (d below about −87.34), where k = 0 and f = d·log2 e + 126 < 0. For d > 0 (`gate_attn` +passes −q, of either sign) t saturates at 1 above about 87.34, where k = 252 and s = 2^126; f = d·log2 e − 126 grows +with d, every fma step stays normal, and from about 88.72 the scale multiply overflows to +inf on both machines +(`ex2.approx.ftz` and `fast::exp2` themselves return +inf once f reaches 128). + +Metal: the contract maps the library `expf` to `metal::precise::exp` (`flash-next.md:153`); this page proposes +`nv_expf(d)`, a transcription, for the owner's decision (the paragraph after the code): + +``` +float t = saturate(fma(d, as_type(0x3BBB989Du), 0.5f)); +float k = floor(t * 252.0f); +if (fma(t, 252.0f, -k) < 0.0f) k -= 1.0f; // fma.rm: t * 252 rounded up to an integer +float f = fma(d, as_type(0x3FB8AA3Bu), 126.0f - k); +f = fma(d, as_type(0x32A57060u), f); +float e = ieee_mul(fast::exp2(f), as_type(uint(k + 1.0f) << 23)); +``` + +`126.0f − k` is −n exactly. The fp32 steps are plain Metal arithmetic: a subnormal d gives t = 0.5, k = 126, f +tiny and e = 1 on both machines, and for k ≠ 126 the fma results are far from the subnormal range (|f| ≥ 2^-48 when +nonzero). `ex2.approx.ftz` maps to `fast::exp2` (invariant 5); both flush a subnormal input and output, and the +output is subnormal only for f < −126, d below about −174.7, where e is +0 anyway. The scale multiply is the one +step that writes a subnormal (k = 0, f < 0), so it is `ieee_mul`. A NaN d gives a NaN e. The contract's table +maps the library `expf` to `metal::precise::exp` (`flash-next.md:153`), which is a different function: +`precise::exp` is not `__nv_expf`'s sequence, and the bits then differ wherever the two round differently. +`nv_expf` reproduces every operation but `ex2.approx`, which follows the contract's own mapping; it extends the +owner's libdevice decision (`origin/woodsonl/basalt-sampler:kernels/common/basalt_libdevice.metal` transcribes only +`__nv_exp` and `__nv_logf`), so it needs the owner's sign-off. The deciding fact: that decision covers library functions +without a correctly rounded Metal counterpart, and Metal does not document its `exp` as correctly rounded (the MSL +specification gives its math functions ulp bounds). Until the owner decides, the contract's `precise::exp` stands. +`gate_attn_kernel` (section 4) inlines the same function. The elementwise spec (`spec-kernels-elem.md`) and the hc lane's router spec (§9 Q1) raise the same +question. + +### `route_kernel<16>` (`:626-664`) + +| Line | Expression | SASS | Metal | +|---|---|---|---| +| `:635` | `v[i] = lg[lane + i * 32]`, i = 0..15 | 16 `LDG`s | the same loads, one SIMD-group per token | +| `:638` | `mx = fmaxf(mx, v[i])` from `-INFINITY`, i ascending | `FMNMX mx, v0, -INF, !PT`, then `FMNMX` with v1..v15 in order | `fmaxf_bits(mx, v[i])`: the other operand for a NaN, the larger by key. mx is never NaN (−inf if every logit is) | +| `:639` | `warp_max`: `v = fmaxf(v, __shfl_xor_sync(.., v, o))`, o = 16..1 (`:26-30`) | `SHFL.BFLY`; `FMNMX` | `fmaxf_bits(v, simd_shuffle_xor(v, o))`, o = 16, 8, 4, 2, 1 | +| `:642` | `v[i] = expf(v[i] - mx)` | `FADD d, v, -mx`, then the sequence above | `nv_expf(v - mx)` as proposed (the contract: `precise::exp`, pending the owner; above); plain `-`: a d that Metal reads differently is so small that e = 1 on both | +| `:642` | `sum += v[i]` from `0.0f`, i ascending | `FADD sum, RZ, e0` (0 + e0), then `FADD` with e1..e15 in order | `sum = ieee_add(sum, e)` from `0.0f`, i ascending | +| `:643` | `1.0f / warp_sum(sum)` | warp_sum; rcp.rn (sigm's fast path, slow path `__cuda_sm20_rcp_rn_f32_slowpath`) | `1.0f / warp_sum_ieee(sum)`. For finite logits the sum is in [1, 512] (the maximum's e is exactly 1), so the reciprocal is normal and Metal's `/` gives its bits; a NaN sum gives NaN | +| `:645` | `v[i] *= rcp; if (isnan(v[i])) v[i] = -FLT_MAX;` | `FMUL v, e, rcp`; `FSETP.NAN.AND P, PT, \|v\|, \|v\|, PT`; `FSEL v, v, -3.40282346638528859812e+38, !P` | `v = ieee_mul(e, rcp); v = isnan(v) ? -FLT_MAX : v` | +| `:651` | `if (v[i] > best) { best = v[i]; ex = lane + i * 32; }` from `best = v[0]`, `ex = lane` | 15 × (`FSETP.GT.AND P, v[i], best`; `FSEL`; `SEL`), i = 1..15 | `f_gt(v[i], best)`: strict, so a tie keeps the smaller expert id | +| `:654-656` | `ob = shfl_xor(best, m)`, `oi = shfl_xor(ex, m)`, m = 16..1; `if (ob > best \|\| (ob == best && oi < ex))` | `SHFL.BFLY` ×2; `FSETP.GEU.AND P1, best, ob`; `@P1 ISETP.GE.AND P2, oi, ex`; `@P1 FSETP.EQ.AND P0, best, ob, !P2` (P0 starts true); `FSEL`; `SEL` | `f_gt(ob, best) \|\| (okey(ob) == okey(best) && oi < ex)` on `simd_shuffle_xor`, m = 16, 8, 4, 2, 1. No NaN can reach it (`:645`), so the key equality is CUDA's `==`. Every lane ends with the same (best, ex) | +| `:658` | `if ((ex & 31) == lane) { v[ex / 32] = -INFINITY; selected_sum += best; }` | predicated `MOV v[k], 0xff800000`; `FADD ss, RZ, best` at the first rank, then `FADD` | the same, `selected_sum = ieee_add(selected_sum, best)` from `0.0f`, ranks in order | +| `:659`, `:660` | `ids[t * 10 + rank] = ex` (lane 0); `if (rank == lane) selected = best;` | `STG`; `FSEL` | the same | +| `:662` | `fmaxf(warp_sum(selected_sum), 6.103515625e-5f)` | warp_sum; `FMNMX ss, ss, 6.103515625e-05, !PT` | `max(warp_sum_ieee(selected_sum), 6.103515625e-5f)`. The sum is never NaN (no +inf can enter it), and a subnormal sum loses to the floor 2^-14 under either compare, so plain `max` returns CUDA's bits. For finite logits the sum is at least the top probability, 1/512 or more, and the floor binds only on the NaN path | +| `:663` | `wout[t * 10 + lane] = selected / selected_sum` (lanes 0..9) | Q(a, b) with `FCHK`, slow path `__cuda_sm3x_div_rn_noftz_f32_slowpath` | `ieee_div_any(selected, selected_sum)` (`basalt_sampler.metal:70`): the divisor is in [2^-14, 10], so main's `ieee_div` (divisor at least 1) does not cover it, and a subnormal numerator can give a normal quotient. No NaN reaches the store: on the NaN path every probability is −FLT_MAX, the ids are the ten smallest and the weights −inf | + +### `swiglu_pair_kernel` (`:698-704`) + +One element per thread over n · 640 values (n = T rows; `blocks_for(n * 640)` threadgroups of 256, `:962`). g and u +are the shared expert's gate and up projections (fp32, `Gemm::native`); the stored fp16 is its down projection's +operand. + +| Line | Expression | SASS | Metal | +|---|---|---|---| +| `:702` | `a = g[i]` | `LDG` | the same | +| `:703` | `__expf(-a)` | E(−a): `FMUL t, a, -1.4426950216293334961`; `FSETP.GEU.AND P0, PT, t, -126, PT`; `@!P0 FMUL t, t, 0.5`; `MUFU.EX2 e, t`; `@!P0 FMUL e, e, e` | `expf_ieee(sign_flip(a))`: e only feeds `1.0f + e` (Notation) | +| `:703` | `1.0f + e` | `FADD den, e, 1` | `1.0f + e`: den is at least 1, +inf for a below about −88.7, NaN for a NaN a | +| `:703` | `a / den` | Q(a, den): `MUFU.RCP`; `FCHK P0, a, den`; five `FFMA`s; `@P0` `__cuda_sm3x_div_rn_noftz_f32_slowpath` | `ieee_div(a, den)` (`basalt_q8_1.metal:181`, divisor at least 1): the quotient is subnormal for \|a\| below 2^-125 (den = 2 there) and a subnormal a must not read as zero | +| `:703` | `... * u[i]` | `FMUL p, u, q` | `ieee_mul(q, u)`: a subnormal q times an infinite u is ±inf in CUDA (clamped to ±65504 next) but 0 · inf = NaN in Metal, and times a finite u above 2^100 it can reach fp16's range. A product below 2^-126 from normal operands rounds to an fp16 zero of the same sign either way | +| `:44` | hf_sat: `isnan(f) ? f : fminf(fmaxf(f, -65504.0f), 65504.0f)` | `FSETP.NAN.AND P0, PT, \|p\|, \|p\|, PT` (`cmath:1176`); `FMNMX m, p, -65504, !PT` (max); `@!P0 FMNMX p, m, 65504, PT` (min) | `isnan(p) ? p : min(max(p, -65504.0f), 65504.0f)`: both bounds are normal, so Metal's `max` and `min` choose as CUDA's do and return a subnormal p with its bits | +| `:40`, `:703` | `h16[i] = hf(...)` | `F2FP.F16.F32.PACK_AB d, RZ, p` (`cuda_fp16.hpp:566`) | `cuda_nan_f16(f16_bits(p))`: a NaN stores 0x7fff; no infinity reaches the conversion | + +`swiglu_il_kernel` (`:691-697`) compiles to the same sequence on interleaved rows; this pack does not run it +(section 7). + +### `moe_combine_kernel` (`:713-723`) + +One element per thread over T · N (`blocks_for(T * N)` threadgroups of 256, `:997`). `Dm` holds the routed experts' +down-projection rows (fp32), `slot[t * 10 + k]` the row of token t's rank-k expert, `w` the weights `route` wrote, +`shared` the shared expert's output and `sg` its gate logit. + +| Line | Expression | SASS | Metal | +|---|---|---|---| +| `:719`, `:721` | `s = fmaf(w[t * 10 + k], Dm[(int64_t) slot[t * 10 + k] * N + d], s)`, k = 0..9 from `s = 0.0f` | `FFMA s, w0, D0, RZ`, then nine `FFMA s, w, D, s`: one dependent chain, k ascending | `s = ieee_fma_any(w, D, s)` from `s = 0.0f`, k ascending (rank order, as `route` stored it). w can be subnormal (section intro), and so can the products and partial sums; fma(w0, D0, +0) is +0 for a zero product of either sign, so the first term is the fma too | +| `:722` | `sigm(sg[t])` | E(−sg); `FADD t, e, 1`; rcp.rn (`MUFU.RCP r, t`; `FFMA d, t, r, -1`; `FADD.FTZ d, -d, -RZ`; `FFMA r, r, d, r`; slow path `__cuda_sm20_rcp_rn_f32_slowpath`) | `ieee_div(1.0f, 1.0f + expf_ieee(sign_flip(sg)))` (Notation): subnormal for sg below about −87.3, +0 below about −88.7 | +| `:722` | `bo[i] = s + shared[i] * sigm(sg[t])` | `FFMA bo, shared, sig, s`: ptxas contracts the expression into one fma | `ieee_fma_any(shared, sig, s)`, one rounding (a subnormal sig times a large `shared` is a normal product); `bo` stores `cuda_nan(x)` | + +### `route_count_kernel` (`:938-943`) + +No float arithmetic: a grid-stride loop over the n = T · 10 expert ids, `if (e >= 0 && e < n_expert) +atomicAdd(hist + e, 1u);` (`:941`), on min(64, ⌈n / 256⌉) threadgroups of 256 (`:945`). Its SASS has only the exact +integer divisions of the loop's trip count (`I2F.U32.RP`, `MUFU.RCP`, `F2I.FTZ.U32.TRUNC.NTZ` at `:941`, +`__cuda_sm20_div_u64` at `:943`; Notation) and `HFMA2` constant loads of the increment (`device_atomic_functions.hpp:112`). +Metal: the same range test and `atomic_fetch_add_explicit(hist + e, 1u, memory_order_relaxed)` on a `device +atomic_uint`, in a grid-stride loop bounded by n. The counts do not depend on the order of the adds; +`prefill_route_count_test` (`tests/cuda/prefill_route_count_test.cpp:38`) checks them exactly. + +In all four kernels T (and n = T · 10) is a chunk's row count, a per-step value: the port reads it from the step's +state, never from a kernel argument or a params record (invariant 4). + +## 4. Attention-side kernels + +The prompt path's QSA layers (`prefill.cpp:1599-1687`) run `rms_rows` on the key rows (`:1610`, T · 2 rows of 256), +the query rows (`:1642`, T · 24 rows of 256) and the indexer's query rows (`:1645`, T · 4 rows of 128), each followed +by `rope` (`:1611`, `:1643`, `:1646`); `kv_append` (`:1636-1638`) writes the rotated keys and the values into the +fp16 pools, `split_q` (`:1641`) separates the queries from their gate half, and `gate_attn` (`:1687`) gates the +attention output into the fp16 operand of the output projection. The drafter's KV rows run `rms_rows` and `rope` too +(`prefill.cpp:1005`, `:1009`, `:1022-1023`). The decode path's norms, RoPE and KV append are different kernels (the +qsa lane's: `native_rope.cu`, built with `--use_fast_math`), so the prompt path's rotated keys need not share bits +with decode's; basalt says so itself (`include/basalt/kernels/mrope.hpp:29-31`: without a table "the prompt path +(precise libm) and decode (fast-math) disagree with each other"). The port keeps the two separate, as basalt does. + +**Chunk invariance.** `rms_rows` gives each row one threadgroup of 256 threads (`:1002`), and the row's sum order +depends only on that layout; `rope` gives each (token, head) row one SIMD-group of 32, one thread per pair (`:1017-1023`); +the others compute one element per thread. No output depends on T or on the row's place in the chunk. The row counts +(T · 2, T · 24, T · 4) and `pos0` are per-step values (invariant 4); the widths, `ld` and the RoPE constants are the +model's. + +### `rms_rows_kernel` (`:726-734`) + +cols is 256 or 128 on the QSA layers and the drafter's widths (2560, 10240, its head size) at `prefill.cpp:1005-1022`; +`eps` is `EPS = 1e-6f` (`prefill.cpp:57`). The row is normalized in place. + +| Line | Expression | SASS | Metal | +|---|---|---|---| +| `:730` | `ss += r[c] * r[c]`, c = tid, tid + 256, … from `ss = 0.0f` | `FFMA ss, r, r, ss` (contracted; unrolled by four, then a remainder loop) | `ss = ieee_fma_any(r, r, ss)` from `0.0f`, c ascending: a square below 2^-126 and the partial sums are kept | +| `:731` | `block_sum(ss, sh)` | Notation (`FADD` butterflies, `kernels.cu:23`) | the same two butterflies with `warp_sum_ieee` | +| `:731` | `/ (float) cols` | `I2F.S64 c, cols` (exact); Q(sum, c): `MUFU.RCP`, `FCHK`, five `FFMA`s, slow path | `ieee_div(sum, float(cols))` (divisor at least 1): the quotient can be subnormal | +| `:731` | `+ eps` | `FADD x, q, eps` | `q + eps`: a subnormal q leaves eps unchanged on both machines | +| `:731` | `rsqrtf(x)` | Notation's sequence (`FSETP.GEU`, `@!P0 FMUL`, `MUFU.RSQ`, `@!P0 FMUL`) | `fast::rsqrt(x)` (invariant 5); x is at least eps, so the subnormal wrapper never fires | +| `:732` | `__syncthreads()` | `BAR.SYNC` | `threadgroup_barrier(mem_flags::mem_threadgroup)` (every thread has read `sh[0]` before the row is rewritten) | +| `:733` | `r[c] = s * r[c] * w[c]` | `FMUL t, s, r`; `FMUL t, t, w`: (s · r) · w | `cuda_nan(ieee_mul(ieee_mul(s, r), w))`: s is at most eps^-1/2 = 1000, so a small r gives a subnormal product | + +### `rope_kernel` (`:738-758`) + +One SIMD-group of 32 threads per (token, head) row (`T * heads` threadgroups, `:1017-1023`); thread `pair` rotates +elements `pair` and `pair + 32` of the head (NEOX halves of the first 64 values). `rope_kernel` never runs: +`rope_table_for` returns no table (`src/kernels/cuda/native_rope.cu:99`), so the host always launches ``. The +host computes `theta_scale = powf((float) freq_base, -2.0f / 64.0f)` (`:1013`, host libm; the qsa lane's record has +0x3F1AB32B for base 1e7), and `kernel_args(64)` gives this pack's `None` scaling freq_scale = 1, ext_factor = 0 and +attn_factor (the kernel's `mscale`) = 1 (`include/basalt/kernels/rope_scaling.hpp:54-60`, `:107-109`). `mrope_table()` +is null for text (`native_rope.cu:81`; only the vision path sets it), so the position is `pos0 + t` +(`mrope.hpp:48-50`). The file is built without fast math, so `powf`, `cosf` and `sinf` are libdevice's accurate +functions, inlined; their only approximate instruction is `rcp.approx.ftz.f32` inside `powf`. + +| Line | Expression | SASS | Metal | +|---|---|---|---| +| `:751` | `(float) mrope_pos(mtab, (int) (pos0 + t), pair)` | `I2FP.F32.S32` | `float(pos)`, exact below 2^24 | +| `:751` | `powf(theta_scale, (float) pair)` | `__nv_powf` inlined (below): `FADD`, `FMUL` and `FFMA` steps, one `MUFU.RCP`, `FRND`, `F2I.NTZ`, the result scaled through two exponent-field multiplies; `x == 1` or `pair == 0` gives 1 | `nv_powf(theta_scale, float(pair))`, the transcription below, `MUFU.RCP` as `1.0f / x` (invariant 5) | +| `:751` | `(float) pos * powf(...)` | `FMUL te, pow, posf` | `pow * posf`: both normal (or a zero position) | +| `rope_scaling.hpp:153` | `theta = freq_scale * theta_extrap` | `FMUL th, te, freq_scale` | `te`: freq_scale is 1 and the product is exact | +| `rope_scaling.hpp:155-160` | the YaRN correction | a compare of ext_factor with 0 and a branch around it (the ramp's division, a `logf`) | not ported: ext_factor is 0 under `None`, the only scaling the port accepts | +| `rope_scaling.hpp:161` | `cos_out = cosf(theta) * mscale` | `__nv_cosf` inlined (below): `FMUL` by 2/π, `F2I.NTZ`, three `FFMA` reductions, the polynomial in `FFMA`s; Payne-Hanek for \|θ\| ≥ 105615 (`I2F.F64.S64`, `DMUL`, `F2F.F32.F64`); then `FMUL c, cosv, mscale` | `nv_cosf(theta)`; mscale is 1 (exact: cos and sin are never subnormal here) | +| `rope_scaling.hpp:162` | `sin_out = sinf(theta) * mscale` | `__nv_sinf`, the same reduction with the sine's quadrant; `FMUL s, sinv, mscale` | `nv_sinf(theta)` | +| `:755` | `a = p[pair], b = p[pair + 32]` | two `LDG` | the same | +| `:756` | `p[pair] = a * c - b * s` | `FMUL t, s, b`; `FFMA x, c, a, -t`: ptxas fuses a · c and rounds b · s | `cuda_nan(ieee_fma_any(c, a, -ieee_mul(s, b)))` | +| `:757` | `p[pair + 32] = a * s + b * c` | `FMUL t, s, a`; `FFMA x, c, b, t` (the front end's own `fma.rn.f32`) | `cuda_nan(ieee_fma_any(c, b, ieee_mul(s, a)))` | + +The rows a and b are `rms_rows`' outputs, arbitrary fp32 data, hence the IEEE helpers in the rotation; θ, c and s are +normal or zero for every position (θ ≥ theta_scale^31 · pos, about 1.6 · 10^-7 for pos ≥ 1 at base 10^7), so the +angle's own steps are plain Metal arithmetic. + +**`nv_powf` (`:751`).** libdevice's `__nv_powf` as nvcc inlines it; the SASS keeps the PTX's operations one for one +(ptxas contracts nothing further). For the RoPE's arguments, x = theta_scale a normal float in (2^-4.9, 1] (any base +from just above 1 to about 10^47) and y = 0..31, the function's other branches (a subnormal x scaled by 2^24, a NaN, +zero, infinite or negative x, |y · log2 x| above 152) cannot run, so the port leaves them out and refuses a +theta_scale outside that range: + +```metal +// x = theta_scale, a normal float in (2^-4.9, 1]; y = 0, 1, ..., 31 +static inline float nv_powf(float x, float y) { + if (y == 0.0f || x == 1.0f) return 1.0f; + const int ex = (as_type(x) - 0x3F3504F3) & int(0xFF800000u); + const float m = as_type(as_type(x) - ex); // in [2^-1/2, 2^1/2) + const float e = fma(float(ex), 0x1p-23f, 0.0f); // the exponent, exact + const float m1 = m + -1.0f, rc = 1.0f / (m + 1.0f); // rcp.approx.ftz.f32 (invariant 5) + const float u = (m1 + m1) * rc, uu = u * u; + float d = m1 - u; + d = d + d; + const float ul = rc * fma(-u, m1, d); + float p = fma(uu, as_type(0x3A2C32E4u), as_type(0x3B52E7DBu)); + p = fma(p, uu, as_type(0x3C93BB73u)); + p = fma(p, uu, as_type(0x3DF6384Fu)); + p = p * uu; + const float l2e = as_type(0x3FB8AA3Bu), h = fma(u, l2e, e); + float t = e - h; + t = fma(u, l2e, t); + t = fma(ul, l2e, t); + t = fma(u, as_type(0x32A55E34u), t); + t = fma(p * 3.0f, ul, t); + t = fma(p, u, t); + const float lh = h + t, ll = t - (lh - h); // log2(x) = lh + ll + const float yh = lh * y, yl = fma(ll, y, fma(lh, y, -yh)); + const float n = rint(yh), f = (yh - n) + yl; + float q = fma(f, as_type(0x391FCB8Eu), as_type(0x3AAF85EDu)); + q = fma(q, f, as_type(0x3C1D9856u)); + q = fma(q, f, as_type(0x3D6357BBu)); + q = fma(q, f, as_type(0x3E75FDECu)); + q = fma(q, f, as_type(0x3F317218u)); + q = fma(q, f, 1.0f); // 2^f + const uint b = n > 0.0f ? 0u : 0x83000000u; // 2^n as 2^127 or 2^-123 times 2^(n -+ ...) + return (q * as_type(b + 0x7F000000u)) * as_type((uint(int(n)) << 23) - b); +} +``` + +Every intermediate stays normal for these arguments (the first scale gives q · 2^-123 at worst), so the plain +statements give the PTX's roundings; only the reciprocal differs in kind. An exact binary32 emulation of this sequence +(each fma rounded once) at theta_scale = 0x3F1AB32B [M] gives every pair the same result whether the reciprocal is +the correctly rounded one or one or two units in the last place off, within 0.58 ulp of the exact power: there, +`1.0f / x` reproduces CUDA's bits whatever `MUFU.RCP` returns in its last bit. The 32 values, pairs 0 to 31, are a +test vector for the port: `3F800000 3F1AB32B 3EBAF81A 3E61F835 3E088D77 3DA50956 3D47763E 3CF11175 3C91AD38 +3C301051 3BD4CA14 3B80967D 3B1B690C 3ABBD3EB 3A6301E0 3A092E01 39A5CB5E 394860BF 38F22CE1 3892587D 3830DF50 37D5C43F +37812DAA 371C1FC2 36BCB0BF 36640CC4 3609CF49 35A68E4A 35494C54 34F34999 3493048C 3431AF42`. Since the inputs are +model constants, the 32 values could equally be computed once at load time by the same transcription. + +**`nv_cosf`, `nv_sinf` (`rope_scaling.hpp:161-162`).** libdevice's accurate sine and cosine: θ = j · π/2 + r with +π/2 in three parts, then the sine or cosine polynomial of quadrant q = j (sine) or j + 1 (cosine). No approximate +instruction; every step is a correctly rounded fp32 operation, and r is far from the subnormal range, so the +transcription is exact: + +```metal +// 2/pi's bits for the Payne-Hanek reduction (__cudart_i2opi_f, least significant word first) +constant uint I2OPI[6] = {0x3C439041u, 0xDB629599u, 0xF534DDC0u, 0xFC2757D1u, 0x4E441529u, 0xA2F9836Eu}; + +// cvt.rn.f64.s64 of n < 2^63 (basalt_f64.metal's f64_round: the value m * 2^(e - 1085), m's leading bit at 62) +static inline ulong f64_from_u63(ulong n) { + if (n == 0) return 0; + const uint s = clz(n) - 1; + return f64_round(0, 1085 - int(s), n << s); +} + +// |x| >= 105615, finite: the reduction in integers, then one binary64 multiply by pi/2 * 2^-64 +static inline float nv_trig_slow(float x, thread int& j) { + const uint ix = as_type(x), m = (ix << 8) | 0x80000000u; + uint w[7]; + ulong c = 0; + for (uint i = 0; i < 6; ++i) { // bounded: six words + const ulong p = ulong(I2OPI[i]) * m + c; + w[i] = uint(p); + c = p >> 32; + } + w[6] = uint(c); + const uint e = ix >> 23, sh = e & 31u, k = ((e & 224u) - 128u) >> 5; // k = 0..3 here + uint hi = w[6 - k], lo = w[5 - k]; + if (sh != 0u) { + hi = (hi << sh) | (lo >> (32u - sh)); + lo = (lo << sh) | (w[4 - k] >> (32u - sh)); + } + const uint f = (hi << 2) | (lo >> 30), s = (f >> 31) != 0u ? 0xFFFFFFFFu : 0u; // shr.s32 f, 31 + const uint q = (hi >> 30) + (f >> 31); + j = int(ix) < 0 ? -int(q) : int(q); + const ulong n = (ulong(f ^ s) << 32) | ulong((lo << 2) ^ s); + const float r = as_type(f32_from_f64(f64_mul(f64_from_u63(n), 0x3BF921FB54442D19ul))); + return int(f ^ ix) < 0 ? -r : r; +} + +// add = 0: sinf; add = 1: cosf +static inline float nv_trig(float x, int add) { + int j; + float r; + if (fabs(x) < 105615.0f) { + j = int(rint(x * as_type(0x3F22F983u))); // FMUL by 2/pi, F2I (nearest even) + const float jf = float(j); + r = fma(jf, as_type(0xBFC90FDAu), x); + r = fma(jf, as_type(0xB3A22168u), r); + r = fma(jf, as_type(0xA7C234C5u), r); + } else { + r = nv_trig_slow(x, j); + } + const int q = j + add; + const bool cq = (q & 1) != 0; // the cosine's polynomial + const float r2 = r * r, p = cq ? 1.0f : r, t = fma(r2, p, 0.0f); + float k = cq ? fma(r2, as_type(0x37CBAC00u), as_type(0xBAB607EDu)) : as_type(0xB94D4153u); + k = fma(k, r2, cq ? as_type(0x3D2AAABBu) : as_type(0x3C0885E4u)); + k = fma(k, r2, cq ? as_type(0xBEFFFFFFu) : as_type(0xBE2AAAA8u)); + const float v = fma(k, t, p); + return (q & 2) != 0 ? 0.0f - v : v; // sub.f32 from +0: a zero stays +0 +} +``` + +The PTX's own case for an infinite θ (r = θ · 0, j = 0) is left out: θ is at most 2^24 here. The slow path runs only +for θ of at least 105615, which pair 0 reaches at position 105615 (θ = pos there) and pair 1 at about 174770; it needs +`f64_round`, `f64_mul` and `f32_from_f64` from the soft binary64 (`origin/woodsonl/basalt-sampler: +kernels/common/basalt_f64.metal:48`, `:234`, `:112`): CUDA rounds the 63-bit integer to binary64, the product to +binary64 and that to binary32, and only the same three roundings give its bits. + +### `split_q_kernel` (`:759-764`) + +A copy with no float instruction: `q[i] = qf[t * 24 * 512 + h * 512 + d]` (`:763`) takes the first 256 values of +each head's 512 (the query half; `gate_attn` reads the other half), one element per thread over T · 6144 values +(`blocks_for(T * 24 * 256)`, `:1027`). The SASS is the index arithmetic (multiplies by the constant reciprocals of +6144 and 256), one `LDG` and one `STG`. Metal: the same copy, bounded by T · 6144 with T read from the step's state. + +### `gate_attn_kernel` (`:765-771`) + +One element per thread over T · 6144 values (`:1031`). `a` is the attention output (fp32, `qsa_decode_attn_batch`, +`prefill.cpp:1682`, the attention lane's kernel) and the gate is the second half of the head's 512 query values. The +stored fp16 is the output projection's operand. This is a library `expf` again (the file has no fast math), the same +inlined `__nv_expf` as `route_kernel`'s (section 3) applied to −q; the front end folds the negation into the +constants, and ptxas fuses `__nv_expf`'s last multiply with the `1.0f +`. + +| Line | Expression | SASS | Metal | +|---|---|---|---| +| `:770` | `expf(-q)`, q = `qf[t * 24 * 512 + h * 512 + 256 + d]` | `FFMA.SAT t, q, -R9, 0.5` (R9 = 0x3BBB989D); `FFMA.RM j, t, R11, 12582913` (R11 = 252); `FADD n, j, -12583039`; `IMAD.SHL.U32 s, j, 0x800000`; `FFMA f, q, -1.4426950216293334961, -n`; `FFMA f, q, -1.925963033500011079e-08, f`; `MUFU.EX2 x, f` | `e = nv_expf(-q)` as proposed (the contract: `precise::exp`, pending the owner; section 3): fma(q, −c, 0.5) and fma(−q, c, 0.5) are the same exact value, so the folded negation changes no bit | +| `:770` | `1.0f + e` | `FFMA den, s, x, 1`: the scale multiply s · x and the add in one rounding | `1.0f + e`. s is a power of two, so s · x is exact whenever it is normal and `nv_expf` returns it unrounded; when it is below 2^-126, 1 + it rounds to 1 whichever way it was formed. A product above `FLT_MAX` is +inf on both. So the fused and the unfused forms give the same den, at least 1 | +| `:770` | `1.0f / den` | rcp.rn: the range test `IADD3`, `LOP3.LUT`, `ISETP.GT.U32`; `MUFU.RCP r, den`; `FFMA d, den, r, -1`; `FADD.FTZ d, -d, -RZ`; `FFMA r, r, d, r`; else `__cuda_sm20_rcp_rn_f32_slowpath` | `ieee_div(1.0f, den)` (`basalt_q8_1.metal:181`, divisor at least 1): r is subnormal for den above 2^126, q below about −87.3, and +0 once den is +inf | +| `:770` | `a[i] * r` | `FMUL p, a, r` | `ieee_mul(a, r)`: a subnormal r times an infinite a is ±inf in CUDA (stored as fp16 ±inf) but 0 · inf = NaN in Metal. For a finite a (an attention output, at most 65504 in magnitude when V is finite) and any subnormal operand, the product is below 2^-110 and rounds to the fp16 zero of its sign either way | +| `:40`, `:770` | `o16[i] = hf(p)` | `F2FP.F16.F32.PACK_AB d, RZ, p` (`cuda_fp16.hpp:566`) | `cuda_nan_f16(f16_bits(p))` (Notation); no clamp here, so a product beyond fp16's range stores ±inf | + +A NaN gate gives a NaN e (`FFMA.SAT` sends the NaN to 0, but f is NaN), a NaN den, r and p, and the store 0x7fff. + +### `kv_append_kernel` (`:775-817`), the fp16 branch + +One threadgroup of 64 threads per (token, KV head, 64-value group, K or V) (`dim3(T, 2, 8)`, `:841`); thread d +converts one value. The contract keeps fp16 KV fully resident (`flash-next.md:434-435`): the call passes the fp16 +pools whenever `kv_int8` is off (`prefill.cpp:1636-1638`), and the host copy (`host`) and the prompt path's staging +pool (`stage`) belong to KV streaming, outside the contract. The int8 branch (`:795-816`) does not run on this pack +(section 7). + +| Line | Expression | SASS | Metal | +|---|---|---|---| +| `:783` | `x = (is_v ? V : K)[t * 512 + kvh * 256 + d]` | `LDG` | the same; K is `rope`'s output, V the value projection's | +| `:784-786` | `pos = pos0 + t`; `page = table[pos / page_size]`; `row = (page * 2 + kvh) * page_size + pos % page_size` | integer only: `__cuda_sm20_div_s64` and the `I2F.U32.RP`, `MUFU.RCP`, `F2I.FTZ.U32.TRUNC.NTZ` of its 32-bit fast path (Notation) | the same integer arithmetic; pos0 and T are per-step values read from the step's state, the page table a buffer (invariant 4) | +| `:789` | `h = hf(x)` | `F2FP.F16.F32.PACK_AB h, RZ, x` (`cuda_fp16.hpp:566`) | `cuda_nan_f16(f16_bits(x))`: round to nearest even, overflow to ±inf, fp16 subnormals kept, an fp32 subnormal to the zero of its sign, a NaN to 0x7fff (`nan.md`) | +| `:790` | `if (page >= 0) (is_v ? v_pool : k_pool)[row * 256 + d] = h` | `STG.E.U16` | the same store; a negative page (a block not resident) writes nothing, and every store stays inside the pool's binding | + +The rows written here are the pool rows decode's attention reads, so `hf`'s bits are the format's: the qsa lane's +decode append (`kv_append_step`, `f16_from_f32`, `flash-next.md:376`) writes the same fp16 encoding of its own +keys, which are computed by a different kernel (section intro). + +## 5. Conversions and copies + +Three kernels of this section run on this pack's prompt path: `to_f16` and `to_bf16` on the per-layer embedding rows +(`prefill.cpp:1531`, `:1534`, `:1536`: BF16 for a BF16 key projection and for the value projection, fp16 for a +native-quantized key projection) and on the drafter's normalized rows when its projections are not int8 +(`prefill.cpp:1007`, `:1011`, `if (!q8)`), and `copy_i32` around the host's grouping of the routed (token, rank) +pairs by expert (`prefill.cpp:1793`, `:1919-1920`, `:2004`, when the group buffer is mapped host memory). `to_f16` +and `to_bf16` run min(⌈n / 256⌉, 4096) threadgroups of 256 in a grid-stride loop (`:846-860`), `copy_i32` +min(⌈n / 256⌉, 256) (`:984-988`); each element is independent, so no output depends on n, the grid or the chunk. +n is a per-step count (T rows times a width), read from the step's state (invariant 4). + +### `to_f16_kernel` (`:818-821`) + +| Line | Expression | SASS | Metal | +|---|---|---|---| +| `:820` | `y[i] = hf(x[i])` | `LDG`; `F2FP.F16.F32.PACK_AB d, RZ, x` (`cuda_fp16.hpp:566`, unrolled by four); `STG.E.U16` | `cuda_nan_f16(f16_bits(x))` (Notation): a NaN of any payload stores 0x7fff | + +The loop's trip count uses the integer division of Notation (`I2F.U32.RP`, `MUFU.RCP`, `F2I.FTZ.U32.TRUNC.NTZ`, +`:819`), which is exact. Metal: one thread per element, `i < prompt_rows(st) * n` (the chunk's rows times the +width), with no loop; each element is independent, so the geometry changes no bit. + +### `to_bf16_kernel` (`:826-833`) + +| Line | Expression | SASS | Metal | +|---|---|---|---| +| `:829` | `h = bf(x[i])` | `LDG`; `SHF.R.U32.HI t, RZ, 0x10, u`; `LOP3.LUT t, t, 0x1, RZ, 0xc0`; `IADD3 u, u, 0x7fff, t`; `SHF.R.U32.HI h, RZ, 0x10, u` (`:33-34`) | `bf16_rne_nonan(x)` (`basalt_fp.metal`), bf's integer steps on the loaded bits, no `cuda_nan`: x is only loaded, so its bits are its producer's (a NaN stored by a ported kernel already carries `cuda_nan`'s 0x7fffffff, whose image is 0x8000) | +| `:830` | `y[i] = h` | `STG.E.U16` | the same | +| `:831` | `if (ylo) ylo[i] = bf_lo(x[i], h)` | a second copy of the loop: `FADD r, x, -h32` (`:38`), then bf(r) | not run: every prompt-path call passes no `ylo` (the default `nullptr`, `include/basalt/prefill/kernels.hpp:96`); bf_lo is on the path inside the hyper-connection kernels (section 1), where Notation gives its Metal form | + +nvcc compiles the loop twice, with and without the `ylo` store, and picks one at run time; the `ylo == nullptr` +loop has no float instruction at all, so the BF16 image is integer arithmetic on the bits, which Metal reproduces +exactly. + +### `copy_i32_kernel` (`:966-969`) + +`dst[i] = src[i]` in a grid-stride loop: no float instruction but the exact trip-count division. The copies move the +routing ids (`route`'s output) into the mapped group buffer and the host-made slot, source and bound arrays back to +device buffers, where the expert GEMMs read them; without a mapped buffer basalt uses `cudaMemcpyAsync` instead +(`prefill.cpp:1794`). The host grouping and the expert tiers belong to the host-step runtime lane: on unified +memory the port can read and write one shared buffer, and whether these copies remain is that lane's decision (the +copied integers are the same either way). If they remain, Metal: the same copy, bounded by n. + +## 6. Test-only kernels: the GDN recurrence references of `gdn_rec_parity` + +`gdn_rec_parity` (`src/prefill/gdn_rec_parity.cu`, its own target with nvcc's defaults: `CMakeLists.txt:409-411`) +carries verbatim copies of the three recurrence kernels (`gdn_rec_cols_pipe_kernel` at `:56`, `gdn_rec_kh_kernel` +at `:136`, `gdn_rec_wl_kernel` at `:236`; header comment `:3-10`). Its gate for the prompt path's kernel is +`check_warp` (`:574-591`): `gdn_rec_wl_kernel` against `gdn_rec_kh_kernel` from the same state, both the output +columns and the state after the chunk, within + +``` + 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; +``` + +(`:585-586`), where `close_to` (`:559-573`) gives the relative RMS sqrt(Σd² / Σref²) and max|d| / max|ref| in +double, any non-finite value failing, and the wl output starts as the NaN sentinel 0xffffffff (`:580`). Its other +checks compare `gdn_rec_kh_kernel` with `gdn_rec_cols_pipe_kernel` bit for bit; both are fallbacks this pack's +prompt path does not run (section 2). The header (`:8-9`) still calls the warp kernel opt-in, but `kernels.cu` +selects it whenever `gdn_warp_ok` holds (`:919`). + +The gate's reference is therefore `gdn_rec_kh_kernel`. The port of the gate needs a test-only Metal copy of it (the +1:1 choice, recommended) or another reference within fp32 rounding of it; the records below make the copy exact. +The SASS was read from the `kernels.cu` copy (unit `gdn_kh`); the test's copies are line for line the same as +`kernels.cu`'s (`:136-228` and `:56-111` there), compiled with the same flags. + +### `gdn_rec_kh_kernel` (`:364-456`, the test's `:136-228`) + +HK · NCB = 64 threadgroups of (CB, RG) = (32, 4) threads (`:920`). Threadgroup (qh, cb) owns key head qh, its +VPK = 3 value heads qh + j·HK and the 32 columns from cb·32; thread (c, rg) holds column col = cb·32 + c and the +RPG = 32 consecutive state rows rg·32 + r of each of the three heads (`s[3][32]`). Inputs are staged eight tokens at a +time by `cp.async` (copies only). Per token: + +| Line | Expression | SASS | Metal | +|---|---|---|---| +| `:420` | `g[j] = __expf(sg[bb][i][j])` | E(x) with the positive constant, three times: `FMUL t, x, 1.4426950216293334961`; `FSETP.GEU.AND P, PT, t, -126, PT`; `@!P FMUL t, t, 0.5`; `MUFU.EX2 e, t`; `@!P FMUL e, e, e` | `expf_ieee(gate)`, as `gdn_rec_wl_kernel` `:551` | +| `:424` | `kv[j] = fmaf(s[j][r], kc[r], kv[j])`, r = 0..31 outer, j inner, from `kv[j] = 0.0f` | `FFMA kv, kc, s, RZ` at r = 0, then `FFMA kv, kc, s, kv`: three chains, r ascending | `kv = ieee_fma_any(s, kc, kv)` from `0.0f`, r ascending | +| `:430` | `rkv[j][0][c] + rkv[j][1][c] + rkv[j][2][c] + rkv[j][3][c]` | three `FADD`s, left to right | `ieee_add(ieee_add(ieee_add(p0, p1), p2), p3)` | +| `:431` | `(sv[bb][i][j][c] - g[j] * kv_col) * sb[bb][i][j]` | `FFMA d, g, -kv_col, v`; `FMUL d, d, beta` | `ieee_mul(ieee_fma_any(-g, kv_col, v), beta)` | +| `:438` | `s[j][r] = fmaf(g[j], s[j][r], kc[r] * delta[j])` | `FMUL kd, kc, delta`; `FFMA s, g, s, kd` | `s = ieee_fma_any(g, s, ieee_mul(kc, delta))` | +| `:439` | `o[j] = fmaf(s[j][r], qr, o[j])`, r = 0..31 from `o[j] = 0.0f` | `FFMA o, s, qr, RZ` at r = 0, then `FFMA o, s, qr, o`, each after its row's `:438` | `o = ieee_fma_any(s, qr, o)` from `0.0f`, r ascending, with the updated s | +| `:447` | `(ro[rg][0][c] + ro[rg][1][c] + ro[rg][2][c] + ro[rg][3][c]) * rsqrtf((float) S)` (row group rg < 3 writes head rg) | three `FADD`s, left to right; `FMUL y, sum, 0.08838834613561630249` (`rsqrtf(128.0f)` folded to 0x3DB504F3) | `ieee_mul(sum, as_type(0x3DB504F3u))`, stored as `cuda_nan(·)` | + +The kernel differs from `gdn_rec_wl_kernel` only in the order of each column's row sums: 32 rows in one thread, +then the four row groups left to right, against wl's 16-row chains and the xor butterfly over 1, 2 and 4. The state +update and the output use the same expressions. + +### `gdn_rec_cols_pipe_kernel` (`:284-339`, the test's `:56-111`) + +HV · NCB = 192 threadgroups, one value head each; per column the same operations in the same order as +`gdn_rec_kh_kernel` (`:318`, `:321`, `:324`, `:325`, `:329`, `:330`, `:335` match `:420`, `:424`, `:430`, `:431`, +`:438`, `:439`, `:447` instruction for instruction), the test's bit check. One difference in the listing changes no +bit: `__expf` of the head's gate runs on the uniform datapath (`UFMUL`, `UFSETP.GEU.AND`, `@!UP0 UFMUL`), the same +IEEE single-precision operations. The gate (`:585-586`) does not use this kernel, so the port needs it only to port +the bit checks too. + +## 7. Kernels this pack does not run + +These kernels of `kernels.cu` compile (all were in the units above), but this pack's prompt path does not launch +them. The port leaves them out; a later pack that needs one adds it with its own record. + +| Kernel | Lines | Why it does not run | What it computes | +|---|---|---|---| +| `gr_norm_kernel`, `gr_mix_kernel` | `:66-82`, `:171-191` | no caller outside `kernels.cu` (section 1) | `gr_norm_rs`'s and `gr_mix_r`'s arithmetic without the stored norm factor | +| `gdn_rec_kh_kernel`, `gdn_rec_cols_pipe_kernel` | `:364-456`, `:284-339` | `gdn_warp_ok` selects `gdn_rec_wl_kernel` (`:919`, section 2) | the same recurrence with other row-sum orders; section 6 records them as `gdn_rec_parity`'s reference | +| `route_kernel<8>`, `basalt::kernels::router_top10` | `:626-664`, `include/basalt/kernels/router_top10.hpp` | `route` launches `<16>` for 512 experts (`:929-937`) | the router for 256 experts and for any other count | +| `blob_dequant_kernel`, `` | `:666-690` | the FP16 expert path only (`prefill.cpp:2275`), taken where a layer does not use MMQ (`use_mmq`, `prefill.cpp:1716`). `mmq_plan` (`prefill.cpp:617-637`) gives every layer of a Q2_0 pack MMQ wherever the MMQ kernels are built and fit ("the Q2_0 pack always", `:604`), so this pack's routed experts run MMQ or, on a streamed chunk, the fused int8 path (`fused_layout`, `:643-645`), never the FP16 path | the 2-bit expert blob to fp16 or BF16, `(float) (((c >> (2 * k)) & 3) - 1) * d` | +| `swiglu_il_kernel` | `:691-697` | the same FP16 expert path (`prefill.cpp:2280`) | section 3's SwiGLU on interleaved gate and up rows | +| `gather_rows16_kernel` | `:705-712` | the same path, the `else` of `use_mmq` (`prefill.cpp:2009-2010`) | a copy of fp16 rows by index | +| `rope_kernel` | `:738-758` | `rope_table_for` returns no table (`src/kernels/cuda/native_rope.cu:99`; section 4) | the RoPE angle from a table instead of `powf`, `cosf` and `sinf` | +| `kv_append_kernel`'s int8 branch | `:795-816` | the contract keeps fp16 KV (`flash-next.md:434-435`; section 4) | `fabsf`, an `fmaxf` butterfly over 64 values, `hf(amax / 127.0f)`, `__float2int_rn(x / sf)` clamped to ±127 | +| `to_bf16_kernel`'s `ylo` loop | `:831` | no prompt-path call passes `ylo` (section 5) | bf_lo of each element | +| `round_f16_kernel` | `:822-825` | no caller outside `kernels.cu` (declared at `include/basalt/prefill/kernels.hpp:98`) | `__half2float(__float2half_rn(x))` | +| `copy_f4_kernel` (`copy_f32_wide`, `:977-983`) | `:972-975` | no caller outside `kernels.cu` (declared at `kernels.hpp:67`) | a float4 copy | diff --git a/kernels/common/basalt_prompt_gemm.metal b/kernels/common/basalt_prompt_gemm.metal new file mode 100644 index 00000000..59d2aeb1 --- /dev/null +++ b/kernels/common/basalt_prompt_gemm.metal @@ -0,0 +1,135 @@ +// Copyright (c) 2026 Jesús Gulfo (MIT) +// Adapted from basalt (jesdga95/basalt) src/prefill/gemm.cu:122-185 and src/prefill/kernels.cu:31-40, :818-860 +// @ b4c63b55754637f4c72ad53a0f791d425f71eb36 (MIT; third_party/NOTICE). +// +// basalt's prompt-path products: Gemm::bf16 (gemm.cu:122-132), BF16 x BF16, and Gemm::native's second stage, Gemm::f16 +// (:158-167) on the FP16 image of a GGUF matrix (:169-185), FP16 x FP16. Each is one cublasGemmEx with an fp32 output +// and compute type, alpha 1 and beta 0; gemm.cu has no device code (docs/research/basalt-nvcc/prefill_kernels.md, +// Method), so cuBLAS picks the summation order and this port fixes its own: every output is one fp32 fma chain from +// +0 in increasing k, +// +// acc = 0; for k in 0 .. K - 1: acc = fma(x[t][k], w[n][k], acc); y[t][n] = cuda_nan(acc) +// +// on the operands widened exactly (h2f; a BF16 field as the high half of a float). Metal's fma reads a subnormal BF16 +// operand as the zero of its sign and flushes a partial sum whose exact value is below 2^-126 (a lone product +// included): the order is the port's, not basalt code. Widened FP16 operands, their fp32 products and the partial sums +// are never subnormal in fp32 (nonzero ones are multiples of 2^-24 and 2^-48). A NaN is stored as sm_120's 0x7fffffff +// (cuda_nan). Each output's bits depend only on its x row, its w row and K: not on the chunk's rows, the tile or the +// slice that computes it. +// +// basalt_prompt_gemm: x [B][K] (bf16 or fp16 bits), w [N][K] (the same type; a BF16 tensor in place or the FP16 +// image), y [B][N] floats. Rows come from StepState through prompt_rows (monolith/kernels.py's PROMPT_ROWS, ahead of +// this file with basalt_fp.metal and the StepState struct): R = prompt_rows(st). A threadgroup computes a 64 x 64 tile +// of y, rows row0 + 64 * gy and columns col0 + 64 * gx onward (row0 and col0 are the slice's, from its params record): +// 256 threads, each 4 x 4 outputs (rows 4 tr + i, columns 4 tc + j), K in steps of 16 staged as floats in one 8,192 B +// threadgroup array (quads of 4 rows as float4, their slots XOR-swizzled by kk), the next step's 16-bit operands +// loaded into registers while this step's fmas run: the speed a dispatch needs to stay under 1 ms at K 10240 (C4), +// with every output's chain unchanged. A tile at or past R returns before its first barrier; loads past R or N stage +// zeros (never read past x's B rows or w's N rows); a thread none of whose outputs is stored skips its fmas but meets +// every barrier; stores need t < R and n < N. Grid: (ceil(ncols / 64), nrows / 64) threadgroups of 256 per slice. +// K % 16 == 0. +// +// basalt_prompt_convert: to_f16 (kernels.cu:818-821, hf :40) at CV_BF16 0 and to_bf16 without ylo (:826-833, bf +// :31-35) at CV_BF16 1, x [B][n] floats to y [B][n] fp16 or bf16 bits. One thread per element of the chunk's rows, +// i < prompt_rows(st) * n (basalt's launchers, :846-850 and :856-860, run a grid-stride loop of +// min(ceil(count / 256), 4096) blocks of 256 over the element count; every element is independent, so the geometry +// changes no bit). +// hf is __float2half_rn: round to nearest even, a finite overflow to inf, fp16 subnormals kept, an fp32 subnormal to +// the zero of its sign, every NaN to sm_120's 0x7fff (f16_bits, then cuda_nan_f16). bf is integer arithmetic on the +// loaded bits (bf16_rne_nonan): round to nearest even, a finite value from 0x7f7f8000 in magnitude to inf, an fp32 +// subnormal rounded by its bits (a load and as_type keep them), and no NaN case, so a NaN's bits round like any +// others, with 32-bit wrap-around: sm_120's 0x7fffffff gives 0x8000 (-0), 0xffffffff 0x0000, 0x7fc00000 0x7fc0. x +// is only loaded, so it keeps its producer's NaN (a ported kernel stores cuda_nan's) and takes no cuda_nan here. +// Grid: ceil(B * n / 256) threadgroups of 256. +// +// Macros: GEMM_BF16 (1: BF16 operands, 0: FP16), CV_BF16 (0: to_f16, 1: to_bf16), and PROMPT_ROWS' T_SRC, ROWS_MAX +// and T_STATIC_ROWS. +#pragma STDC FP_CONTRACT OFF + +#ifndef GEMM_BF16 +#define GEMM_BF16 0 +#endif +#ifndef CV_BF16 +#define CV_BF16 0 +#endif + +// ponytail: one geometry for every shape (a 64 x 64 tile, 4 x 4 outputs per thread, K steps of 16, one single-buffered +// threadgroup array beside a register prefetch); a per-shape geometry macro, gated unchanged by GM-EMU and GM-ROWS +// (tests/kernels/test_basalt_prompt_gemm.py), when prompt speed is measured to matter. +#define PG_TILE 64u +#define PG_BK 16u + +struct PromptGemmParams { uint n, k, row0, col0; }; + +static inline float pg_widen(ushort b) { +#if GEMM_BF16 + return as_type(uint(b) << 16); +#else + return h2f(b); +#endif +} + +kernel void basalt_prompt_gemm(device const ushort* x [[buffer(0)]], device const ushort* w [[buffer(1)]], + device float* y [[buffer(2)]], constant PromptGemmParams& p [[buffer(3)]], + device const StepState* st [[buffer(15)]], + uint2 tg [[threadgroup_position_in_grid]], uint tid [[thread_index_in_threadgroup]]) { + // [0][kk][q ^ kk]: x[t0 + 4q + 0..3][k0 + kk]; [1][kk][q ^ kk]: w[n0 + 4q + 0..3][k0 + kk] (8,192 B) + threadgroup float4 s[2][PG_BK][PG_TILE / 4u]; + const uint t0 = p.row0 + PG_TILE * tg.y, n0 = p.col0 + PG_TILE * tg.x; + const uint R = prompt_rows(st); + if (st->done || t0 >= R) return; // the whole threadgroup, before any barrier + const uint tr = tid % 16u, tc = tid / 16u; // outputs: rows t0 + 4 tr + i, columns n0 + 4 tc + j + const uint sq = tid / 16u, skk = tid % 16u; // staging: quad sq (rows or columns 4 sq + c) at kk = skk + const bool live = t0 + 4u * tr < R && n0 + 4u * tc < p.n; // else none of the thread's 16 outputs is stored + device const ushort* xs[4]; + device const ushort* ws[4]; + bool xin[4], win[4]; + for (uint c = 0; c < 4u; ++c) { // a row past R or N stages 0 and points at row 0 (in bounds) + const uint t = t0 + 4u * sq + c, n = n0 + 4u * sq + c; + xin[c] = t < R; win[c] = n < p.n; + xs[c] = x + ulong(xin[c] ? t : 0u) * p.k + skk; + ws[c] = w + ulong(win[c] ? n : 0u) * p.k + skk; + } + ushort rx[4], rw[4]; // the step's 16-bit operands, loaded a step ahead + for (uint c = 0; c < 4u; ++c) { rx[c] = xin[c] ? xs[c][0] : ushort(0); rw[c] = win[c] ? ws[c][0] : ushort(0); } + float acc[4][4]; + for (uint i = 0; i < 4u; ++i) + for (uint j = 0; j < 4u; ++j) acc[i][j] = 0.0f; + for (uint k0 = 0; k0 < p.k; k0 += PG_BK) { + s[0][skk][sq ^ skk] = float4(pg_widen(rx[0]), pg_widen(rx[1]), pg_widen(rx[2]), pg_widen(rx[3])); + s[1][skk][sq ^ skk] = float4(pg_widen(rw[0]), pg_widen(rw[1]), pg_widen(rw[2]), pg_widen(rw[3])); + threadgroup_barrier(mem_flags::mem_threadgroup); + const uint k1 = k0 + PG_BK; + if (k1 < p.k) + for (uint c = 0; c < 4u; ++c) { rx[c] = xin[c] ? xs[c][k1] : ushort(0); rw[c] = win[c] ? ws[c][k1] : ushort(0); } + if (live) + for (uint k2 = 0; k2 < PG_BK; k2 += 4u) { // kk = k2 + u increasing: every chain sees k in order + float4 a[4], b[4]; + for (uint u = 0; u < 4u; ++u) { a[u] = s[0][k2 + u][tr ^ (k2 + u)]; b[u] = s[1][k2 + u][tc ^ (k2 + u)]; } + for (uint u = 0; u < 4u; ++u) + for (uint i = 0; i < 4u; ++i) + for (uint j = 0; j < 4u; ++j) acc[i][j] = fma(a[u][i], b[u][j], acc[i][j]); + } + threadgroup_barrier(mem_flags::mem_threadgroup); // every thread has read the step before the next store + } + for (uint i = 0; i < 4u; ++i) { + const uint t = t0 + 4u * tr + i; + for (uint j = 0; j < 4u; ++j) { + const uint n = n0 + 4u * tc + j; + if (t < R && n < p.n) y[ulong(t) * p.n + n] = cuda_nan(acc[i][j]); + } + } +} + +struct PromptConvertParams { uint n; }; + +kernel void basalt_prompt_convert(device const float* x [[buffer(0)]], device ushort* y [[buffer(1)]], + constant PromptConvertParams& p [[buffer(2)]], + device const StepState* st [[buffer(15)]], uint i [[thread_position_in_grid]]) { + if (st->done || i >= prompt_rows(st) * p.n) return; +#if CV_BF16 + y[i] = bf16_rne_nonan(x[i]); +#else + y[i] = cuda_nan_f16(f16_bits(x[i])); +#endif +} diff --git a/monolith/compiler/emit.py b/monolith/compiler/emit.py index 9556db90..9a71b4dc 100644 --- a/monolith/compiler/emit.py +++ b/monolith/compiler/emit.py @@ -40,6 +40,7 @@ from .barriers import place_barriers from .coverage import check_coverage from .emit_basalt import BASALT_HANDLERS +from .emit_basalt_prompt import BASALT_PROMPT_HANDLERS from .passes import DEFAULT_PASSES WINDOW_BYTES = 2 << 30 # pack windows: ICB bind offsets are 32-bit (design §5.1) @@ -1430,7 +1431,7 @@ 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, **BASALT_HANDLERS} + "accept_scan": _accept_scan, **BASALT_HANDLERS, **BASALT_PROMPT_HANDLERS} @dispatch("emit") diff --git a/monolith/compiler/emit_basalt_prompt.py b/monolith/compiler/emit_basalt_prompt.py new file mode 100644 index 00000000..2222b395 --- /dev/null +++ b/monolith/compiler/emit_basalt_prompt.py @@ -0,0 +1,124 @@ +# SPDX-License-Identifier: MIT +# Copyright (c) 2026 Jesús Gulfo +# adapted from basalt (jesdga95/basalt) src/prefill/prefill.cpp:1188-1199 @ b4c63b55754637f4c72ad53a0f791d425f71eb36 +# (MIT; third_party/NOTICE). +"""The emitter's handlers for basalt's prompt path (``monolith/ops/basalt_prompt.py``), merged into ``emit.HANDLERS``. +Every dispatch binds StepState at slot 15 and reads the chunk's rows only through ``prompt_rows(st)`` +(``kernels.PROMPT_ROWS``; ``Gemm::native``'s dequantization reads none), in the dynamic-T prompt program and in a +static one. Its sources, params and the GEMM's slices come from ``monolith/kernels.py``'s builders, as do the +dequantization's ``DQ_TYPE``, ``DQ_OUT``, grid and threadgroup; the row macros come from ``prompt_rows``, and +``GEMM_BF16``, ``CV_BF16`` and the products' and conversions' grids and threadgroups from the handlers. A params +record holds geometry, never a row count, a position or a pointer (invariant 4). The weight checks are +``native_proj``'s and ``bf16_proj``'s (``prefill.cpp:1188-1199``): the entry must agree with the weight.""" + +from __future__ import annotations + +from dataclasses import replace +from typing import TYPE_CHECKING, Dict, Optional, Sequence, Tuple + +from .. import kernels +from ..core.dtypes import DType +from ..core.ir import Op, Value +from ..core.shapes import T +from .emit_basalt import GGML_IDS, _bind, _expect, _weight + +if TYPE_CHECKING: + from .emit import _Ctx + +GEMM_ENTRIES = ("bf16", "native") # hc8 adds "bf16_w" + + +def prompt_rows(ctx: _Ctx, op: Op, rows_from: Optional[Value] = None, + same_rows: Sequence[Value] = ()) -> Tuple[int, Dict[str, str]]: + """``(B, macros)`` of a prompt dispatch: B, the compiled rows of ``op``'s first output (of ``rows_from`` instead, for + an op whose only output is a placeholder), by ``ctx.rows_of``'s rule, and the macros ``prompt_rows(st)`` reads: + STEP_STATE 1, ROWS_MAX B, and T_SRC 0 for T rows in a dynamic-T program, T_SRC 2 with T_STATIC_ROWS B for a static + row count and in a static program (``rows_of`` reports T rows as source 0 there too, but its advance resets + t_this_step to 1). Rows from any other StepState field are refused, as is a value of ``same_rows`` (an input the + kernel reads row for row) whose rows are not the output's, the same count from the same source. Every prompt + dispatch lists ``(15, ctx.program.step_state, 0)`` itself: ``ctx.add`` appends it in a dynamic-T program only.""" + from .emit import ROW_SOURCE, STATIC_ROWS # emit imports this module: resolved at call time + v = op.outputs[0] if rows_from is None else rows_from + rows, src = ctx.rows_of(replace(op, outputs=[v])) + if src not in (ROW_SOURCE[T], STATIC_ROWS): + raise ValueError(f"{op.kind}: {v.name!r} has the rows {v.shape[0]} (T_SRC {src}); a prompt kernel's rows are " + "the chunk's (T, t_this_step) or a static count") + for u in same_rows: + if ctx.rows_of(replace(op, outputs=[u])) != (rows, src): + raise ValueError(f"{op.kind}: {u.name!r} has the rows {u.shape[0]} and {v.name!r} {v.shape[0]}; a prompt " + "kernel reads and writes the same rows, from one source") + src = src if ctx.dynamic_t else STATIC_ROWS + macros = {"STEP_STATE": "1", "T_SRC": str(src), "ROWS_MAX": f"{rows}u"} + if src == STATIC_ROWS: + macros["T_STATIC_ROWS"] = f"{rows}u" + return rows, macros + + +def _gemm(ctx: _Ctx, op: Op) -> None: + """``Gemm::bf16`` (``gemm.cu:122-132``): the product on the BF16 tensor in place. ``Gemm::native`` (``:169-185``): + ``dequant_f16`` of the whole matrix (dequant's ``basalt_dequant_g32`` at ``DQ_OUT 1``) into the program's one FP16 + scratch, grown to its largest image (basalt slices only a matrix past its 32M-value scratch, none on this pack; + each output reads only its own image row, so the bits are the same), then ``Gemm::f16``'s product on that image. + The dequantization lists the scratch in ``writes``: the barrier pass orders it after the products that read the + previous op's image and before its own, and ``reuse_arenas`` may pack the scratch.""" + entry = op.attrs.get("entry") + if entry not in GEMM_ENTRIES: + raise ValueError(f"basalt_prompt_gemm: attr entry must be one of {GEMM_ENTRIES}, got {entry!r}") + (x, w), (y,) = op.inputs, op.outputs + rows, macros = prompt_rows(ctx, op, same_rows=(x,)) + native = entry == "native" + tid, n, k = _weight(ctx, op, w, kernels.DEQUANT16_TYPES if native else (GGML_IDS["bf16"],)) + _expect(ctx, op, x, (rows, k), DType.F16 if native else DType.BF16, + f"Gemm::{entry}'s {'FP16' if native else 'BF16'} rows of the weight's width") + _expect(ctx, op, y, (rows, n), DType.F32, "contiguous columns of the weight's rows") + if not native: + return _product(ctx, op, _bind(ctx, op, 1, w, 2), True, rows, n, k, macros) + img = (1, ctx.scratch("prompt_gemm_f16", 2 * n * k, shared=True), 0) # the dequantization's out, the products' w + # ponytail: one dequantization dispatch per matrix. On this Mac (M3 Max) a Q6_K matrix of 10240 or 12288 x 2560 + # takes 1.42-1.70 ms, over a dispatch's 1 ms, and would need two row0 halves; no Q6_K tensor of this pack has that + # shape (its longest, 2560 x 6144, 0.85 ms; every other type at most 0.84 ms at its shapes here). + kern = ctx.kernel("basalt_dequant16", kernels.basalt_dequant16_source(), "basalt_dequant_g32", + kernels.basalt_dequant16_macros(tid, "f16")) + prm = ctx.params("basalt_dequant16", kernels.basalt_dequant16_params(tid, 0, n, k)) + grid, threads = kernels.basalt_dequant16_grid(n, k) + ctx.add(kern, [_bind(ctx, op, 0, w, 1), img, (2, prm, 0), (15, ctx.program.step_state, 0)], (grid, 1, 1), + (threads, 1, 1), f"{op.kind}:dequant_f16:{w.name}", writes=[1]) + _product(ctx, op, img, False, rows, n, k, macros) + + +def _product(ctx: _Ctx, op: Op, w: Tuple[int, str, int], bf16: bool, rows: int, n: int, k: int, + macros: Dict[str, str]) -> None: + """The product (``Gemm::bf16``'s, ``gemm.cu:122-132``, or ``Gemm::f16``'s, ``:158-167``) of x, ``op``'s first + input, by the 16-bit rows ``w`` binds at slot 1 (a BF16 tensor in place, or a scratch's image) into y, its first + output: one dispatch per static slice of ``kernels.basalt_prompt_gemm_slices(B, N, K)``, each with its own params + record, every slice writing y.""" + slices = kernels.basalt_prompt_gemm_slices(rows, n, k) # refuses k % 16 + kern = ctx.kernel("basalt_prompt_gemm", kernels.basalt_prompt_gemm_source(), "basalt_prompt_gemm", + {**macros, "GEMM_BF16": str(int(bf16))}) + bindings = [_bind(ctx, op, 0, op.inputs[0], 2), w, _bind(ctx, op, 2, op.outputs[0], 4)] + for row0, nrows, col0, ncols in slices: + prm = ctx.params("basalt_prompt_gemm", kernels.basalt_prompt_gemm_params(n, k, row0, col0)) + ctx.add(kern, bindings + [(3, prm, 0), (15, ctx.program.step_state, 0)], (-(-ncols // 64), -(-nrows // 64), 1), + (256, 1, 1), f"{op.kind}:{op.attrs['entry']}:{op.inputs[1].name}", writes=[2]) + + +def _convert(ctx: _Ctx, op: Op) -> None: + """``to_f16`` (``kernels.cu:818-821``) or ``to_bf16`` without ``ylo`` (``:826-833``), as the output's dtype + says: one thread per element of the bound's rows.""" + (x,), (y,) = op.inputs, op.outputs + rows, macros = prompt_rows(ctx, op, same_rows=(x,)) + n = ctx.shape(x)[-1] + _expect(ctx, op, x, (rows, n), DType.F32, "the converted rows") + if y.dtype not in (DType.F16, DType.BF16): + raise ValueError(f"basalt_prompt_convert: {y.name!r} is {y.dtype}; the output is F16 (to_f16) or BF16 (to_bf16)") + bf16 = y.dtype == DType.BF16 + _expect(ctx, op, y, (rows, n), y.dtype, "the input's rows, converted") + kern = ctx.kernel("basalt_prompt_gemm", kernels.basalt_prompt_gemm_source(), "basalt_prompt_convert", + {**macros, "CV_BF16": str(int(bf16))}) + prm = ctx.params("basalt_prompt_convert", kernels.basalt_prompt_convert_params(n)) + ctx.add(kern, [_bind(ctx, op, 0, x, 4), _bind(ctx, op, 1, y, 2), (2, prm, 0), (15, ctx.program.step_state, 0)], + (-(-rows * n // 256), 1, 1), (256, 1, 1), f"{op.kind}:{'to_bf16' if bf16 else 'to_f16'}:{x.name}", + writes=[1]) + + +BASALT_PROMPT_HANDLERS: Dict[str, object] = {"basalt_prompt_gemm": _gemm, "basalt_prompt_convert": _convert} diff --git a/monolith/kernels.py b/monolith/kernels.py index 421333fe..6eb1f89b 100644 --- a/monolith/kernels.py +++ b/monolith/kernels.py @@ -756,6 +756,66 @@ def basalt_dequant16_grid(rows: int, cols: int) -> Tuple[int, int]: return grid, DEQUANT16_THREADS +# ---- basalt's prompt path: the GEMM and the 16-bit conversions (kernels/common/basalt_prompt_gemm.metal; docs/research/basalt-nvcc/prefill_kernels.md) ---- + +# The rows every prompt-path kernel reads (invariant 4): StepState.t_this_step clamped to the compiled bound ROWS_MAX in +# a dynamic-T program (T_SRC 0), the compiled count T_STATIC_ROWS in a static one (T_SRC 2), whose advance resets +# t_this_step to 1. A builder places it after its PRELUDE-led prefix, behind which the emitter splices the StepState +# struct, and before its kernels. The row macros are uint literals ("64u"): MSL's min(uint, int) is ambiguous. +PROMPT_ROWS = """ +inline uint prompt_rows(device const StepState* st) { // invariant 4: the chunk's rows are StepState data +#if T_SRC == 2 + return T_STATIC_ROWS; // a static program's compiled count +#else + return min(st->t_this_step, ROWS_MAX); // ROWS_MAX: the program's bound, the buffers' rows +#endif +} +""" + + +def basalt_prompt_gemm_source() -> str: + """basalt's ``Gemm::bf16`` product and ``Gemm::native``'s FP16 product (``basalt_prompt_gemm``), and the + conversions ``to_f16`` and ``to_bf16`` (``basalt_prompt_convert``).""" + return PRELUDE + template("basalt_fp.metal") + PROMPT_ROWS + template("basalt_prompt_gemm.metal") + + +# The padded multiply-adds a product dispatch may run, measured on 2026-10-20 on an Apple M3 Max (40 GPU cores, macOS +# 27.0.1): whole products at B 256 with at least 40 threadgroups ran 769-2456 G MAC/s (three runs, each the least of 5 +# at a warm clock; one run alone gave 1 << 29); the slowest, FP16 640 x 2560 (one threadgroup per core) at 769, times +# 0.5 ms, rounded down to a power of two. +PROMPT_GEMM_MACS = 1 << 28 + + +def basalt_prompt_gemm_slices(rows: int, n: int, k: int) -> List[Tuple[int, int, int, int]]: + """The static slices ``(row0, nrows, col0, ncols)`` of a product at bound ``rows`` (B) with ``n`` outputs over + ``k``, each its own dispatch and params record, covering [0, Bp) x [0, n) once, Bp = 64 * ceil(B / 64). A slice + runs its tiles' 64 * ceil(nrows / 64) * 64 * ceil(ncols / 64) * k multiply-adds. Columns: CB = min(n, max(64, c)), + c the largest multiple of 64 with Bp * c * k <= PROMPT_GEMM_MACS (0 if none). Rows: Bp when c >= 64, else + RB = min(Bp, max(64, r)), r the largest multiple of 64 with r * 64 * k <= PROMPT_GEMM_MACS. So every slice is + within the budget or one tile, every row slice is a multiple of 64 tall and every column slice but the last (which + ends at n) a multiple of 64 wide: a slice's grid covers its block and no other. Slices change no bit (each output's + chain is the same in any slice).""" + if k <= 0 or k % 16: + raise ValueError(f"basalt_prompt_gemm: k must be a positive multiple of 16, got {k}") + if rows < 1 or n < 1: + raise ValueError(f"basalt_prompt_gemm: need at least one row and one output, got {rows} rows, {n} outputs") + bp = 64 * -(-rows // 64) + c = PROMPT_GEMM_MACS // (bp * k) // 64 * 64 + cb = min(n, max(64, c)) + rb = bp if c >= 64 else min(bp, max(64, PROMPT_GEMM_MACS // (64 * k) // 64 * 64)) + return [(r0, min(rb, bp - r0), c0, min(cb, n - c0)) for r0 in range(0, bp, rb) for c0 in range(0, n, cb)] + + +def basalt_prompt_gemm_params(n: int, k: int, row0: int, col0: int) -> bytes: + """``PromptGemmParams``: the product's n and k, the slice's first row and first column.""" + return struct.pack("<4I", n, k, row0, col0) + + +def basalt_prompt_convert_params(n: int) -> bytes: + """``PromptConvertParams``: the row width n (the conversion runs the chunk's rows times n elements).""" + return struct.pack(", MPP) diff --git a/monolith/ops/__init__.py b/monolith/ops/__init__.py index ea38d2f8..7aa0d3db 100644 --- a/monolith/ops/__init__.py +++ b/monolith/ops/__init__.py @@ -7,4 +7,6 @@ from .registry import OPS, CostModel, KernelBinding, OpDef, register_op from . import attention, basalt, draft, embed, gdn, gemv, moe, norm, sample # noqa: F401 (registration) +from . import basalt_prompt # noqa: F401 (registration: basalt's prompt path, ops/basalt_prompt.py) + __all__ = ["OPS", "CostModel", "KernelBinding", "OpDef", "register_op"] diff --git a/monolith/ops/basalt_prompt.py b/monolith/ops/basalt_prompt.py new file mode 100644 index 00000000..bc86be6d --- /dev/null +++ b/monolith/ops/basalt_prompt.py @@ -0,0 +1,43 @@ +"""basalt's prompt path (docs/design/flash-next.md): one op kind per distinct signature of the kernels a prompt chunk +runs, ``basalt_prompt_``, each lowered by ``compiler/emit_basalt_prompt.py`` to the dispatches of +``kernels/common/basalt_*.metal``, with the sources and params records of ``monolith/kernels.py``'s builders. +Each prompt PR appends its kinds here, with a bullet below. + +Values. Activations are row-major ``[T, n]``, a token's row after the one before. A weight is the tensor as shipped, +``[N, K]`` (N outputs over K inputs): 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 (as ``ops/basalt.py`` says). + +Rows. T, the first output's rows, is the chunk's row count: ``StepState.t_this_step`` clamped to the compiled bound B +in the dynamic-T prompt program (``kernels.PROMPT_ROWS``; every grid is encoded at B and a threadgroup past the chunk's +rows returns before its first barrier), the compiled count in a static one. Rows never come from an attr or a params +record (invariant 4). Outputs are exactly ``[T, N]``: no ``ldy`` and no ``beta``. No prompt-path call passes a nonzero +``beta``. The only ``ldy`` other than N, 96, is passed by the GDN layer's ``ssm_alpha`` and ``ssm_beta`` products of +48 outputs into one ``ab`` buffer (``src/prefill/prefill.cpp:1587``-``:1588``); the port gives them two ops with +``[T, 48]`` outputs. + +Programs. The dynamic-T prompt program at bound B (one per session; every chunk, the short last one included, runs +through it) and static programs (the tests') are both accepted; every dispatch binds StepState at slot 15 in both. + +* ``basalt_prompt_gemm``, attr ``entry`` (``Gemm::``, ``src/prefill/gemm.cu:122-185``): ``"bf16"``: ``(x [T, K] + BF16, w [N, K] BF16)`` → ``y [T, N] F32``; ``"native"``: ``(x [T, K] F16, w [N, K]`` GGUF blocks of one of the ten + ggml types ``Gemm::native`` meets on this pack ``)`` → ``y [T, N] F32``, through one FP16 image of ``w`` per op. + ``hc8`` adds ``"bf16_w"``. The entry must agree with ``w`` (a BF16 tensor for ``bf16``, GGUF blocks for + ``native``, as ``native_proj`` and ``bf16_proj`` require, ``src/prefill/prefill.cpp:1188-1199``); a mismatch is + refused. K is a multiple of 16. Each output is one fp32 ``fma`` chain from +0 in increasing k, so its bits depend + only on its x row, its w row and K: never on the chunk's rows, the row's place in the chunk or the static slice + that computes it (basalt's cuBLAS call promises none of these). +* ``basalt_prompt_convert`` (``to_f16`` / ``to_bf16``, ``src/prefill/kernels.cu:818-833``): ``(x [T, n] F32)`` → + ``y [T, n]`` F16 (``to_f16``) or BF16 (``to_bf16``); the output dtype picks the kernel. Element-local, so a row's + bits never depend on the chunk. + +Alignment, checked at every binding: 2 bytes for 16-bit values, 4 for F32 ones. +""" + +from ..core.ir import OpClass +from .registry import KernelBinding, OpDef, register_op + +BASALT_PROMPT_GEMM = register_op(OpDef("basalt_prompt_gemm", OpClass.MAP, "rows") + .bind("*", KernelBinding("basalt_prompt_gemm"))) +BASALT_PROMPT_CONVERT = register_op(OpDef("basalt_prompt_convert", OpClass.MAP, "rows") + .bind("*", KernelBinding("basalt_prompt_convert"))) diff --git a/tests/contract/test_basalt_prompt_ops.py b/tests/contract/test_basalt_prompt_ops.py new file mode 100644 index 00000000..6b4e345a --- /dev/null +++ b/tests/contract/test_basalt_prompt_ops.py @@ -0,0 +1,332 @@ +"""basalt's prompt-path op kinds (monolith/ops/basalt_prompt.py) as compiler/emit_basalt_prompt.py emits them over the +synthetic .basalt file of test_basalt_ops.py: both kinds registered and covered; every dispatch equal to kernels.py's +builders and the handlers' rules (function, macros, source, grid, threadgroup, params, written slot), with StepState at +slot 15 and the row macros of the program's form (prompt_rows); no per-step value in a params record (invariant 4); +the GEMM's static slices tiling every product once; Gemm::native's dequantization into the program's one FP16 scratch +ordered ahead of its products and behind the previous op's; 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_prompt_program.py.""" + +import struct + +import numpy as np +import pytest + +from monolith import kernels +from monolith.compiler.coverage import check_coverage +from monolith.compiler.emit import _Ctx, basalt_windows +from monolith.compiler.emit_basalt_prompt import prompt_rows +from monolith.core import DType, Graph +from monolith.core.ir import OpClass +from monolith.core.shapes import N_INJ, T +from monolith.core.step_state import StepStateLayout +from monolith.formats.gguf import ggml_row_bytes +from monolith.ops import OPS +from monolith.runtime.program import Program +from tests.contract.test_basalt_ops import emit, op, pack, src, weight # noqa: F401 (src: the .basalt file fixture) +from tests.contract.test_basalt_windows import PROFILE + +F32, F16, BF16 = DType.F32, DType.F16, DType.BF16 +KINDS = ("basalt_prompt_gemm", "basalt_prompt_convert") +LAYOUT = StepStateLayout(t_max=128) +TILE_K2560 = 64 * 64 * 2560 # one 64 x 64 tile's multiply-adds at K 2560: a budget that slices rows and columns + +# The products basalt_prompt_gemm runs on this pack, (N, K) (spec-kernels-gemm.md section 3; prefill.cpp lines): +# :1569 and :1571 the hc down and up (Gemm::bf16 on the copies' BF16 images, hc8's entry), :1572 the inject, :1585 and +# :1535 qkv and the PLE key, :1586 the GDN gate, :1587-1588 alpha and beta, :1592 and :1688 ssm_out and attn_output, +# :1605-1606, :1609 and :1698 at 512 x 2560, :1607 attn_q, :1608 the indexer's k, :1702-1703 the shared expert's gate and +# up, :1705 its down, :1707 its scalar gate, :1538 the PLE value; and N 4 and 72 at K 2560 (column tiles cut short). +PRODUCTS = ((320, 10240), (10240, 320), (4, 10240), (10240, 2560), (6144, 2560), (48, 2560), (2560, 6144), (512, 2560), + (12288, 2560), (128, 2560), (640, 2560), (2560, 640), (1, 2560), (2560, 2560), (4, 2560), (72, 2560)) + + +def prompt_graph(g, src, rows=T): + """Both kinds at ``rows`` rows: to_f16 and to_bf16 of x [rows, 2560] F32 (the PLE's key and value operands of one + row, prefill.cpp:1534, :1536), and Gemm::bf16 of xb [rows, 2560] BF16 by the file's two BF16 matrices (128 outputs: + two column tiles; 1 output: one partial tile).""" + x = g.input("x", (rows, 2560), F32) + op(g, "basalt_prompt_convert", [x], [g.value("x16", (rows, 2560), F16)]) + op(g, "basalt_prompt_convert", [x], [g.value("xbf16", (rows, 2560), BF16)]) + xb = g.input("xb", (rows, 2560), BF16) + for name in ("mmvf.q", "mmvf.gate"): + w = weight(g, f"dense/{name}", src) + op(g, "basalt_prompt_gemm", [xb, w], [g.value(f"y.{name}", (rows, w.shape[0]), F32)], entry="bf16") + + +def row_macros(rows, static): + """The macros prompt_rows(st) reads: T_SRC 0 in a dynamic-T program, 2 with the count for a static one.""" + m = {"STEP_STATE": "1", "T_SRC": "2" if static else "0", "ROWS_MAX": f"{rows}u"} + return {**m, "T_STATIC_ROWS": f"{rows}u"} if static else m + + +def record(prog, o): + """The params record a dispatch binds (its one buffer of role params).""" + (prm,) = [prog.buffers[b] for _, b, _ in o.bindings if prog.buffers[b].role == "params"] + return prm.init + + +# ---- 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") + prompt_graph(g, src) + assert {o.kind for o in g.ops} == set(KINDS) + check_coverage(g, PROFILE) + + +# (dynamic-T program, the values' rows, the program's t): T rows in a dynamic program read t_this_step; a static count +# in a dynamic program and every row count of a static one (T included: rows_of reports it as source 0 there too, and a +# static program's advance resets t_this_step to 1) compile T_SRC 2. +FORMS = [(True, T, 128), (True, 17, 128), (False, T, 17), (False, 5, 17)] + + +@pytest.mark.parametrize("dynamic, rows, t", FORMS, ids=["dynamic", "dynamic-static-rows", "static", "static-rows"]) +def test_dispatches_bind_step_state(src, monkeypatch, dynamic, rows, t): + """Every dispatch of both kinds is the builders' (source, params, slices) and the handler's (grid, threadgroup, + macros) and binds (15, step_state, 0) once, with STEP_STATE 1, ROWS_MAX the compiled rows B and T_SRC 0 (dynamic-T, + T rows) or T_SRC 2 with T_STATIC_ROWS B. Under a budget of one tile the products split into static slices, one + dispatch each in basalt_prompt_gemm_slices' order, each with its own record (row0, col0) and the grid of its block; + each conversion is one dispatch over the bound's elements, its output's dtype choosing CV_BF16.""" + monkeypatch.setattr(kernels, "PROMPT_GEMM_MACS", TILE_K2560) + g = Graph("step") + prompt_graph(g, src, rows) + prog = emit(g, src, t, dynamic_t=dynamic, layout=LAYOUT) + _, bound = basalt_windows(src, g.values.values(), t) + b = t if rows is T else rows + macros = row_macros(b, not dynamic or rows is not T) + source = kernels.basalt_prompt_gemm_source().replace(kernels.PRELUDE, kernels.PRELUDE + LAYOUT.to_msl() + "\n", 1) + # per dispatch: (function, its macro, the value slots, params, grid, label, written slots) + want = [("basalt_prompt_convert", {"CV_BF16": cv}, [(0, "x", 0), (1, y, 0)], + kernels.basalt_prompt_convert_params(2560), (-(-b * 2560 // 256), 1, 1), f"basalt_prompt_convert:{name}:x", [1]) + for cv, y, name in (("0", "x16", "to_f16"), ("1", "xbf16", "to_bf16"))] + for name in ("mmvf.q", "mmvf.gate"): + n = src.entries[f"dense/{name}"].shape[0] + values = [(0, "xb", 0), (1, *bound[f"dense/{name}"]), (2, f"y.{name}", 0)] + want += [("basalt_prompt_gemm", {"GEMM_BF16": "1"}, values, kernels.basalt_prompt_gemm_params(n, 2560, row0, col0), + (-(-ncols // 64), nrows // 64, 1), f"basalt_prompt_gemm:bf16:dense/{name}", [2]) + for row0, nrows, col0, ncols in kernels.basalt_prompt_gemm_slices(b, n, 2560)] + assert [w[5] for w in want].count("basalt_prompt_gemm:bf16:dense/mmvf.q") == (4 if b > 64 else 2) # sliced + assert len(prog.ops) == len(want) + for o, (fn, macro, values, params, grid, label, writes) in zip(prog.ops, want): + k = prog.kernels[o.kernel] + assert (k.function, k.macros, k.source) == (fn, {**macros, **macro}, source), label + assert (o.name, o.grid, o.threadgroup, o.threadgroup_memory, o.meta["writes"]) == ( + label, grid, (256, 1, 1), [], writes) + slot, prm, off = o.bindings[len(values)] + assert o.bindings == values + [(slot, prm, off), (15, prog.step_state, 0)], label + assert (slot, off, prog.buffers[prm].role, prog.buffers[prm].init) == (len(values), 0, "params", params), label + + +@pytest.mark.parametrize("dynamic, rows, t", FORMS, ids=["dynamic", "dynamic-static-rows", "static", "static-rows"]) +def test_native_orders_its_stages(src, monkeypatch, dynamic, rows, t): + """Gemm::native (gemm.cu:169-185): dequant_f16 of the whole matrix into the scratch, then Gemm::f16's product on + it. Two native ops in a row, the smaller image first (Q6_K 35 x 2560, then Q4_K 70 x 2560), each product sliced + under a budget of one tile: every dispatch is the builders' and the handler's and binds (15, step_state, 0); each + op's dequantization (dequant's builders, DQ_OUT 1) comes first and writes the scratch at slot 1, and its slices + (GEMM_BF16 0) read the scratch at slot 1; both ops bind the program's one ws.T{t}.prompt_gemm_f16.shared, sized to + the larger image. The barrier pass (compiler/barriers.py's conflict rule) puts each op's products behind its + dequantization (read after write) and the second dequantization behind the first op's products (write after read), + so no product reads another op's image.""" + monkeypatch.setattr(kernels, "PROMPT_GEMM_MACS", TILE_K2560) + names = ("gguf/pair.14.23.0", "gguf/mmvq.12") + g = Graph("step") + x = g.input("x16", (rows, 2560), F16) + for name in names: + w = weight(g, name, src) + op(g, "basalt_prompt_gemm", [x, w], [g.value(f"y.{name}", (rows, w.shape[0]), F32)], entry="native") + prog = emit(g, src, t, dynamic_t=dynamic, layout=LAYOUT) + _, bound = basalt_windows(src, g.values.values(), t) + b = t if rows is T else rows + scratch = f"ws.T{t}.prompt_gemm_f16.shared" + dq_source, gemm_source = (s.replace(kernels.PRELUDE, kernels.PRELUDE + LAYOUT.to_msl() + "\n", 1) + for s in (kernels.basalt_dequant16_source(), kernels.basalt_prompt_gemm_source())) + # per dispatch: (function, macros, source, the value slots, params, grid, threadgroup, label, written slots) + want, images = [], [] + for name in names: + tid, (n, k) = src.entries[name].type_id, src.entries[name].shape + images.append(2 * n * k) + grid, threads = kernels.basalt_dequant16_grid(n, k) + dq = kernels.basalt_dequant16_macros(tid, "f16") # it reads no rows; STEP_STATE is _Ctx.kernel's (dynamic-T) + want.append(("basalt_dequant_g32", {**dq, "STEP_STATE": "1"} if dynamic else dq, + dq_source, [(0, *bound[name]), (1, scratch, 0)], + kernels.basalt_dequant16_params(tid, 0, n, k), (grid, 1, 1), (threads, 1, 1), + f"basalt_prompt_gemm:dequant_f16:{name}", [1])) + want += [("basalt_prompt_gemm", {**row_macros(b, not dynamic or rows is not T), "GEMM_BF16": "0"}, + gemm_source, [(0, "x16", 0), (1, scratch, 0), (2, f"y.{name}", 0)], + kernels.basalt_prompt_gemm_params(n, k, row0, col0), (-(-ncols // 64), nrows // 64, 1), (256, 1, 1), + f"basalt_prompt_gemm:native:{name}", [2]) + for row0, nrows, col0, ncols in kernels.basalt_prompt_gemm_slices(b, n, k)] + labels = [w[7] for w in want] + assert labels.count(f"basalt_prompt_gemm:native:{names[1]}") == (4 if b > 64 else 2) # sliced + assert len(prog.ops) == len(want) + for o, (fn, macros, source, values, params, grid, threads, label, writes) in zip(prog.ops, want): + k = prog.kernels[o.kernel] + assert (k.function, k.macros, k.source) == (fn, macros, source), label + assert (o.name, o.grid, o.threadgroup, o.threadgroup_memory, o.meta["writes"]) == ( + label, grid, threads, [], writes) + slot, prm, off = o.bindings[len(values)] + assert o.bindings == values + [(slot, prm, off), (15, prog.step_state, 0)], label + assert (slot, off, prog.buffers[prm].role, prog.buffers[prm].init) == (len(values), 0, "params", params), label + assert images[0] < images[1] and [n for n in prog.buffers if "prompt_gemm_f16" in n] == [scratch] + assert (prog.buffers[scratch].nbytes, prog.buffers[scratch].role) == (images[1], "arena") + second = labels.index(f"basalt_prompt_gemm:dequant_f16:{names[1]}") + assert prog.ops[second].barrier_before, ( + "the second dequantization waits for the first op's products (write after read)") + assert prog.ops[1].barrier_before and prog.ops[second + 1].barrier_before, ( + "each op's products wait for its dequantization (read after write)") + + +def test_rows_from_reads_its_value(src): + """prompt_rows' ``rows_from``: an op whose only output is a placeholder takes its rows from the value it names (the + same rule as an output's), and without it from that output, a static count.""" + g = Graph("step") + k = g.input("k", (T, 2560), F32) + placeholder = g.value("ph", (1,), DType.U32) + o = op(g, "basalt_prompt_convert", [k], [placeholder]) + for dynamic, want in ((True, row_macros(64, False)), (False, row_macros(64, True))): + ctx = _Ctx(Program(kernels={}, buffers={}, ops=[], layout=LAYOUT), [src], LAYOUT, 64, 1, 256, dynamic_t=dynamic) + assert prompt_rows(ctx, o, rows_from=k) == (64, want) + assert prompt_rows(ctx, o) == (1, row_macros(1, True)) + + +def test_per_step_values_stay_out_of_params(src, monkeypatch): + """Invariant 4: the program compiled at bound B serves every chunk, so its records hold geometry only. Two emissions + give byte-identical records and macros; every product record is exactly (n, k, row0, col0), its slice's 64-row and + 64-column origin, every conversion record exactly (n,): no row count, position or pointer.""" + monkeypatch.setattr(kernels, "PROMPT_GEMM_MACS", TILE_K2560) + progs = [] + for _ in range(2): + g = Graph("step") + prompt_graph(g, src) + progs.append(emit(g, src, 128, dynamic_t=True, layout=LAYOUT)) + a, b = ([(record(p, o), p.kernels[o.kernel].macros) for o in p.ops] for p in progs) + assert a == b + origins = {(n, row0, col0) for n in (128, 1) for row0, _, col0, _ in kernels.basalt_prompt_gemm_slices(128, n, 2560)} + seen = set() + for o in progs[0].ops: + rec = record(progs[0], o) + if o.name.startswith("basalt_prompt_convert:"): + assert struct.unpack(" 0 and row0 + nrows <= bp, (n, k, row0, nrows) + assert col0 % 64 == 0 and ncols > 0 and col0 + ncols <= n, (n, k, col0, ncols) + assert ncols % 64 == 0 or col0 + ncols == n, (n, k, col0, ncols) + assert nrows * 64 * -(-ncols // 64) * k <= macs or (nrows == 64 and ncols <= 64), (n, k, row0, col0) + cover[row0:row0 + nrows, col0:col0 + ncols] += 1 + assert (cover == 1).all(), (n, k) + widths = {ncols for _, _, _, ncols in slices} + if budget == "tile-": # single tiles, each over the budget + assert len(slices) == bp // 64 * -(-n // 64) and widths <= set(range(1, 65)), (n, k) + if budget == "c0" and bp > 64: # rows sliced: Bp - 64 rows, then 64 + assert sorted({nrows for _, nrows, _, _ in slices}) == [64, bp - 64], (n, k) + if budget == "cN": + assert widths == {n} and len(slices) == 1, (n, k) + + +# ---- refusals: each case's valid input emits, and the same input with its one defect is refused by its own check --- + +def gemm(g, src, entry="bf16", w="dense/mmvf.q", x_dtype=BF16, y_dtype=F32, y_extra=0, rows=T, x_rows=None): + """``basalt_prompt_gemm`` of x [x_rows (default rows), K] by ``w`` into y [rows, N + y_extra].""" + wv = weight(g, w, src) + x = g.input("x", (rows if x_rows is None else x_rows, wv.shape[1]), x_dtype) + op(g, "basalt_prompt_gemm", [x, wv], [g.value("y", (rows, wv.shape[0] + y_extra), y_dtype)], entry=entry) + + +def convert(g, x_dtype=F32, y_dtype=F16, y_extra=0, y_rows=T): + """``basalt_prompt_convert`` of x [T, 64] into y [y_rows, 64 + y_extra].""" + x = g.input("x", (T, 64), x_dtype) + op(g, "basalt_prompt_convert", [x], [g.value("y", (y_rows, 64 + y_extra), y_dtype)]) + + +def _gemm(**defect): + def build(g, src, bad, tmp): + gemm(g, src, **(defect if bad else {})) + return {} + return build + + +def _native(**defect): + """A valid Gemm::native, F16 rows by gguf/mmvq.12 (Q4_K), and the same with ``defect``.""" + def build(g, src, bad, tmp): + gemm(g, src, **{"entry": "native", "w": "gguf/mmvq.12", "x_dtype": F16, **(defect if bad else {})}) + return {} + return build + + +def _convert(**defect): + def build(g, src, bad, tmp): + convert(g, **(defect if bad else {})) + return {} + return build + + +def _k16(g, src, bad, tmp): + """A BF16 matrix of 4 rows over K 40 (valid: 48) from a pack entry at byte 16.""" + k = 40 if bad else 48 + w = g.const("p", (4, k), BF16) + op(g, "basalt_prompt_gemm", [g.input("x", (T, k), BF16), w], [g.value("y", (T, 4), F32)], entry="bf16") + return {"packs": [pack(tmp, {"p": (16, 4 * k * 2)})]} + + +def _f16_blocks(g, src, bad, tmp): + """Gemm::native of a pack's 4 GGUF rows over K 64 at byte 16: Q8_0 (valid), or F16, a ggml type outside the ten + (basalt's dequant_f16 exits on it: dequant_bf16.cu:203, :210-213).""" + w = g.weight("p", (4, 64), "f16" if bad else "q8_0") + op(g, "basalt_prompt_gemm", [g.input("x", (T, 64), F16), w], [g.value("y", (T, 4), F32)], entry="native") + return {"packs": [pack(tmp, {"p": (16, 4 * ggml_row_bytes(8, 64))})]} + + +TEN = r"of ggml type \['iq4_nl', 'iq4_xs', 'q2_0', 'q3_k', 'q4_0', 'q4_k', 'q5_0', 'q5_k', 'q6_k', 'q8_0'\]" +REFUSALS = [ + ("entry outside bf16 and native", _gemm(entry="f16"), r"attr entry must be one of \('bf16', 'native'\), got 'f16'"), + ("bf16 entry on GGUF blocks", _gemm(w="gguf/mmvq.12"), r"is not a weight or constant .* of ggml type \['bf16'\]"), + ("native entry on a BF16 matrix", _gemm(entry="native"), r"'dense/mmvf.q' \(bf16 \[128, 2560\]\) is not .* " + TEN), + ("native on F16 blocks", _f16_blocks, r"'p' \(f16 \[4, 64\]\) is not .* " + TEN), + ("bf16 entry on F16 rows", _gemm(x_dtype=F16), r"'x' is f16 \[2, 2560\], not bf16 \[2, 2560\]"), + ("native entry on BF16 rows", _native(x_dtype=BF16), r"'x' is bf16 \[2, 2560\], not f16 \[2, 2560\]"), + ("product output not F32", _gemm(y_dtype=F16), r"'y' is f16 \[2, 128\], not f32 \[2, 128\]"), + ("product output wider than the weight's rows", _gemm(y_extra=1), r"'y' is f32 \[2, 129\], not f32 \[2, 128\]"), + ("K not a multiple of 16", _k16, "k must be a positive multiple of 16, got 40"), + ("rows from n_inject", _gemm(rows=N_INJ), r"'y' has the rows n_inject \(T_SRC 1\)"), + ("product rows from two sources", _gemm(rows=2, x_rows=T), r"'x' has the rows T and 'y' 2; a prompt kernel reads"), + ("convert to F32", _convert(y_dtype=F32), r"'y' is f32; the output is F16 \(to_f16\) or BF16 \(to_bf16\)"), + ("convert of F16 rows", _convert(x_dtype=F16), r"'x' is f16 \[2, 64\], not f32 \[2, 64\]"), + ("convert output of another width", _convert(y_extra=1), r"'y' is f16 \[2, 65\], not f16 \[2, 64\]"), + ("convert rows from two sources", _convert(y_rows=2), r"'x' has the rows T and 'y' 2; a prompt kernel reads"), +] + + +@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) diff --git a/tests/kernels/basalt_emu.py b/tests/kernels/basalt_emu.py index eea1feb7..a6f5c2a7 100644 --- a/tests/kernels/basalt_emu.py +++ b/tests/kernels/basalt_emu.py @@ -4,7 +4,7 @@ # 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 @ +# include/basalt/kernels/q8_1_finite.hpp, include/basalt/kernels/f16_bits.hpp and src/kernels/hc8_parity.cpp @ # 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). @@ -28,10 +28,8 @@ def ftz(x): 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).""" +def _fma64_odd(a, b, c): + """a * b + c of float32 inputs as a float64 rounded to odd, fma32's and fma_metal's common step.""" a, b, c = (np.asarray(v, F32).astype(np.float64) for v in (a, b, c)) s = a * b t = s + c @@ -39,9 +37,27 @@ def fma32(a, b, c): 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) + return np.where(bump, np.nextafter(t, np.where(err > 0, np.inf, -np.inf)), t) + + +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).""" with np.errstate(over="ignore"): - return t.astype(F32) + return _fma64_odd(a, b, c).astype(F32) + + +def fma_metal(a, b, c): + """This GPU's fma in MTLMathModeSafe as test_subnormals_in_safe_mode measures it (basalt_fp.metal's header): a + subnormal input reads as the zero of its sign, an exact result below 2^-126 in magnitude flushes to the zero of + its sign before rounding, and every other result is fma32's on the flushed inputs. So an exact 2^-126 - 2^-150 + gives 0 here and 2^-126 in fma_ftz (.ftz flushes the rounded result). The test is on _fma64_odd's value, which is + below 2^-126 exactly when the exact result is: rounding to odd never reaches 2^-126, an even significand, from + below.""" + t = _fma64_odd(ftz(a), ftz(b), ftz(c)) + with np.errstate(over="ignore"): + return np.where(np.abs(t) < 2.0 ** -126, np.copysign(0.0, t), t).astype(F32) def add_ftz(a, b): @@ -791,3 +807,39 @@ def q5k_proxy_final(cand, part, exact, map_, expf): 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 +# ---- the prompt path's products (kernels/common/basalt_prompt_gemm.metal) ------------------------------------------- +# Gemm::bf16's product and Gemm::native's (Gemm::f16 on the FP16 image) are cuBLAS calls (src/prefill/gemm.cu:122-132, +# :158-185), which fix no summation order; the port's is one fp32 fma chain per output, from +0 in increasing k. + +def gemm_chain(xb, wb, bf16, flush=True): + """basalt_prompt_gemm's outputs as bits, uint32 (R, N), for 16-bit operand bits ``xb`` (R, K) and ``wb`` (N, K), + BF16 if ``bf16`` else FP16: acc = fma_metal(x[t][k], w[n][k], acc) from +0 in increasing k, so subnormal BF16 + operands read as zero and every partial sum whose exact value is below 2^-126 flushes; a NaN stored as sm_120's + 0x7fffffff (cuda_nan). ``flush=False``: the same fold on fma32, an IEEE chain that keeps subnormals.""" + widen = (lambda b: (np.asarray(b, np.uint16).astype(np.uint32) << 16).view(F32)) if bf16 else h2f + xf, wf = widen(xb), widen(wb) + fma = fma_metal if flush else fma32 + acc = np.zeros((xf.shape[0], wf.shape[0]), F32) + for k in range(xf.shape[1]): + acc = fma(xf[:, k, None], wf[None, :, k], acc) + return np.where(np.isnan(acc), np.uint32(0x7FFFFFFF), acc.view(np.uint32)) + + +def rel_norm(y, ref): + """The GEMM gate's metric: src/kernels/hc8_parity.cpp:57-61's Err folded over every element of the float32 values + ``y`` (Err::add's a) against ``ref`` (its b), as part 2 feeds it (``ex.add(y1[t * ldy + n], (float) ref);``, + :261): ``ref`` cast to float32, |y - ref| in float32 widened to float64, each fold std::max's (a NaN never replaces + the running value, which starts at 0, so callers count non-finite outputs themselves), then rel(): + + struct Err { + double abs = 0, ref = 0; + void add(float a, float b) { abs = std::max(abs, (double) std::fabs(a - b)); ref = std::max(ref, (double) std::fabs(b)); } + double rel() const { return ref > 0 ? abs / ref : abs; } + }; + """ + with np.errstate(over="ignore", invalid="ignore"): + b = np.asarray(ref).astype(F32) + d = np.abs(np.asarray(y, F32) - b).astype(np.float64) + e = np.fmax.reduce(d.ravel(), initial=0.0) + r = np.fmax.reduce(np.abs(b).astype(np.float64).ravel(), initial=0.0) + return float(e / r) if r > 0 else float(e) diff --git a/tests/kernels/basalt_prompt_gpu.py b/tests/kernels/basalt_prompt_gpu.py new file mode 100644 index 00000000..4f5189c5 --- /dev/null +++ b/tests/kernels/basalt_prompt_gpu.py @@ -0,0 +1,89 @@ +"""Single-kernel runs of basalt's prompt path (kernels/common/basalt_prompt_*.metal) for the GPU tests. Every prompt +kernel reads its rows from StepState at slot 15 (monolith/kernels.py's PROMPT_ROWS), so ``run_rows`` is +basalt_gpu.run with a StepState record bound there. A source compiles as the emitter registers it (the StepState +struct spliced in after the prelude) with the dynamic-T program's row macros: STEP_STATE 1, T_SRC 0 and ROWS_MAX the +compiled bound B; the static form (T_SRC 2) is the contract and program tiers' concern.""" + +import numpy as np + +from monolith import kernels +from monolith.core.step_state import StepStateLayout +from monolith.formats.gguf import ggml_row_bytes +from monolith.runtime import _native as nt +from tests.contract.test_basalt_ops import spliced +from tests.kernels.basalt_gpu import device, pipeline, run + + +def prompt_pipeline(source, name, B, macros=()): + """Kernel ``name`` of ``source`` as a dynamic-T program at bound ``B`` compiles it, with ``macros`` beside.""" + m = {"STEP_STATE": "1", "T_SRC": "0", "ROWS_MAX": f"{B}u", **dict(macros)} + return pipeline(spliced(source), name, tuple(sorted(m.items()))) + + +def run_rows(pso, buffers, params, slot, grid, threads, rows, position, fill=None, done=0): + """basalt_gpu.run with a StepState record (the layout ``spliced`` gives the source; ``t_this_step`` = ``rows``, + ``position``, ``done``) bound at slot 15 and returned last. ``grid`` (threadgroups) and ``threads`` are 3-tuples.""" + dev = device() + state = StepStateLayout().pack({"t_this_step": rows, "position": position, "done": done}) + srcs = [*buffers, state] + bufs = [nt.Buffer(dev, b) for b in srcs] + 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[:-1]): + d = d.buffer(k, b) + d = d.buffer(15, bufs[-1]) + if params is not None: + d = d.bytes(slot, params) + r = nt.Queue(dev).run([d.grid(*grid).threadgroup(*threads)]) + 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, srcs)] + + +def prompt_gemm(xb, wb, *, bf16, B, rows=None, slices=None, fill=0xFF, done=0): + """basalt_prompt_gemm: ``Gemm::bf16``'s product (``bf16``) or ``Gemm::native``'s FP16 product of the 16-bit bits + ``xb`` [B, K] and ``wb`` [N, K] (gemm.cu:122-132, :158-185), compiled at bound ``B`` and run with ``rows`` (default + B) and ``done`` in StepState: one run_rows per slice ``(row0, nrows, col0, ncols)`` into one y of exactly B * N + floats whose bytes start as ``fill``. ``slices`` default to the handler's rule, kernels.basalt_prompt_gemm_slices(B, + N, K). Returns y's bits, uint32 [B, N].""" + xb, wb = np.ascontiguousarray(xb, np.uint16), np.ascontiguousarray(wb, np.uint16) + (nx, k), (n, kw) = xb.shape, wb.shape + assert nx == B and kw == k, f"x {xb.shape} and w {wb.shape} at bound {B}" + pso = prompt_pipeline(kernels.basalt_prompt_gemm_source(), "basalt_prompt_gemm", B, {"GEMM_BF16": str(int(bf16))}) + y = bytes([fill]) * (4 * B * n) + for row0, nrows, col0, ncols in kernels.basalt_prompt_gemm_slices(B, n, k) if slices is None else slices: + y = run_rows(pso, [xb.tobytes(), wb.tobytes(), y], kernels.basalt_prompt_gemm_params(n, k, row0, col0), 3, + (-(-ncols // 64), -(-nrows // 64), 1), (256, 1, 1), B if rows is None else rows, 0, done=done)[2] + return np.frombuffer(y, np.uint32).reshape(B, n) + + +def native(type_id, blocks, xb, *, B, rows=None, fill=0xFF): + """``Gemm::native`` (gemm.cu:169-185) of the fp16 bits ``xb`` [B, K] by the GGUF rows ``blocks`` [N, row bytes] of + type ``type_id``: basalt_dequant_g32 at DQ_OUT 1 (dequant_f16, through the dequantizer's builders) over all N rows + into an fp16 image of exactly N * K halves, then prompt_gemm's FP16 product on that image (rows and y as there). + The image's and y's bytes start as ``fill``. Two runs here; the program's two dispatches in one command buffer are + the program tier's. Returns (y's bits uint32 [B, N], the image's bits uint16 [N, K]).""" + blocks = np.ascontiguousarray(blocks, np.uint8) + n, k = len(blocks), np.shape(xb)[1] + assert blocks.shape[1] == ggml_row_bytes(type_id, k), f"blocks {blocks.shape} of type {type_id} at K {k}" + pso = pipeline(kernels.basalt_dequant16_source(), "basalt_dequant_g32", + tuple(kernels.basalt_dequant16_macros(type_id, "f16").items())) + image = run(pso, [blocks.tobytes(), 2 * n * k], kernels.basalt_dequant16_params(type_id, 0, n, k), 2, + *kernels.basalt_dequant16_grid(n, k), fill)[1] + image = np.frombuffer(image, np.uint16).reshape(n, k) + return prompt_gemm(xb, image, bf16=False, B=B, rows=rows, fill=fill), image + + +def convert(x, *, bf16, B, rows, fill=0xFF): + """basalt_prompt_convert: ``to_bf16`` (``bf16``) or ``to_f16`` of the floats ``x`` [B, n] (kernels.cu:818-833), + compiled at bound ``B`` and run with ``rows`` in StepState, one thread per element, into one y of exactly B * n + halves whose bytes start as ``fill``. ``x``'s bits reach the kernel as they are (NaN payloads included). Returns + y's bits, uint16 [B, n].""" + x = np.ascontiguousarray(x) + assert x.dtype == np.float32 and x.ndim == 2 and len(x) == B, f"x {x.dtype} {x.shape} at bound {B}" + n = x.shape[1] + pso = prompt_pipeline(kernels.basalt_prompt_gemm_source(), "basalt_prompt_convert", B, {"CV_BF16": str(int(bf16))}) + y = run_rows(pso, [x.tobytes(), 2 * B * n], kernels.basalt_prompt_convert_params(n), 2, (-(-B * n // 256), 1, 1), + (256, 1, 1), rows, 0, fill=fill)[1] + return np.frombuffer(y, np.uint16).reshape(B, n) diff --git a/tests/kernels/test_basalt_prompt_gemm.py b/tests/kernels/test_basalt_prompt_gemm.py new file mode 100644 index 00000000..62845964 --- /dev/null +++ b/tests/kernels/test_basalt_prompt_gemm.py @@ -0,0 +1,459 @@ +# SPDX-License-Identifier: MIT +# Copyright (c) 2026 Jesús Gulfo +# adapted from basalt (jesdga95/basalt) src/kernels/hc8_parity.cpp @ b4c63b55754637f4c72ad53a0f791d425f71eb36 +# (MIT; third_party/NOTICE): the GEMM gate's bound and its use of Err (:253-262, :269). +"""basalt's prompt-path products on Metal (kernels/common/basalt_prompt_gemm.metal). Gemm::bf16's product and +Gemm::native's (Gemm::f16 on the dequantized FP16 image) are cuBLAS calls (src/prefill/gemm.cu:122-132, :158-185) that +fix no summation order; the port computes each output as one fp32 fma chain from +0 in increasing k, and +``emu.gemm_chain`` is its numpy twin on this GPU's fma (``emu.fma_metal``). + +- GM-TWIN (host only): the twin flushes where test_subnormals_in_safe_mode measures this GPU's fma flushing + (tests/kernels/test_basalt_platform.py:114-126), on the planted BF16 cases ``PLANTED``, against the same fold on + ``emu.fma32``, an IEEE chain. +- GM-EMU: the kernel bit for bit against the twin at 1, 17 and 64 rows of a 64-row bound (a partial row tile), N 1, 4, + 48 and 72 (partial column tiles), K 320 and 640, BF16 operands (+-0 or magnitudes in [2^-20, 2^10]) and FP16 ones + (activations N(0, 1), weights 0.02 N(0, 1)); the rows at and past the chunk's keep the 0xFF fill. A NaN at x[3][7] + or w[5][9] gives 0x7fffffff in its row or its column only. ``PLANTED`` on the GPU: the flushed partial sums ((a), + (b)) and the subnormal operands read as zero ((c)) give the twin's bits, where the IEEE fold gives others. +- GM-REF: the product (the handler's slices) against float64 on the same operand bits, ``emu.rel_norm`` + (hc8_parity.cpp:57-61's Err) over every output under hc8_parity.cpp:269's 5e-3, and no output non-finite, at the + pack's BF16 shapes (Gemm::bf16's own gate, which hc8_parity applies at hc8's shapes) and FP16 ones (Gemm::native's + second stage: the nearest bound, as no basalt test gates Gemm::f16's product against a reference; + prefill_mmq_kq_test.cpp:241, :244 run it off this pack, its error printed, not gated), 1, 17 and 512 rows + (attn_q's 12288 outputs at 1 and 17), activations N(0, 1) and weights 0.02 N(0, 1); and Gemm::native end to end + (``gpu.native``: the fp16 image, then its product) at 37 rows, Q2_0 (512, 2560), Q4_K (640, 2560) and the ten GGUF + types at (64, 2560), against float64 on the exact dequantized weights (gguf_reference.dequantize), so the image's + rounding counts. + +basalt promises no invariance (cuBLAS picks the kernel per product, hc8_parity.cpp:263); the chain gives each by +construction, and these gates keep it bit for bit against one whole-product dispatch (``whole``): +- GM-ROWS (row invariance), BF16 (48, 2560) and FP16 (2560, 640): rows 0, 63, 64, 255 and 511 each alone, the first + 63, 65, 17 and 37 rows at those bounds, the 512 rows permuted, row 5 at row 300 of fresh rows, explicit row slices of + 64 and of 192 rows give the same rows as B 512; FP16 (2560, 6144) at B 512 in the handler's slices (more than one). +- GM-STEP (the rows are StepState data, invariant 4): compiled at B 512 and run with t_this_step 1, 17, 65, 511, 512 + and 600 (prompt_rows clamps to B), the rows below min(r, B) are the B 512 rows and the rest keep 0xFF, every row at + done 1; at B 37 and t_this_step 600 only the clamp keeps the row tile's loads and stores inside x and y. +- GM-COLS (column invariance), BF16 (512, 2560) (48 columns hold neither n 65 at 37 nor a 192-column slice) and FP16 + (2560, 640), 37 rows: the w rows [r0, r0 + n) alone (n 1, 63, 65 at r0 0 and 37), the w rows permuted, explicit + column slices of 64 and of 192 give the whole product's columns. +- GM-REPEAT (determinism), FP16 (6144, 2560) at B 512 in the handler's slices: y prefilled 0x00, then 0xFF, on one + pipeline, then on a freshly compiled one, every run the same bits; native Q4_K (640, 2560) at B 37, the fp16 image + and y prefilled 0x00, then 0xFF, the same image and y. + +Gemm::native composes two stages (gemm.cu:169-185: dequant_f16 into the scratch, then Gemm::f16's product on it): +- GM-COMP: ``gpu.native`` for each of the ten GGUF types at (64, 2560), 37 rows, bitwise equal to the FP16 product on + the host's fp16 image of the same blocks, emu.cuda_half_bits(gguf_reference.dequantize(t, blocks)). + +The conversion to_f16 (src/prefill/kernels.cu:818-821, hf :40: __float2half_rn), the PLE key's operand +(prefill.cpp:1534), has no basalt test; the nearest check, dequant_f16_parity.cpp:73's store against __float2half_rn of +the fp32 value, is bitwise, and so is this one: +- G9-F16: n 100 a row at 37 rows of a 64-row bound, ``F16_SPECIALS`` (+-0, fp32 subnormals, 65504, the overflow tie + 65520 and the float below it, +-inf, three NaNs, the fp16-subnormal ties) among fp32 normals from 2^-30 to 2^20, + bit for bit against emu.cuda_half_bits; the elements past 37 * n keep the 0xFF fill. + +The conversion to_bf16 without ylo (src/prefill/kernels.cu:826-833, bf :31-35), the PLE value's operand +(prefill.cpp:1536), has no basalt test either; bf16_bits_test checks bf16_from_f32 against previous_bf16, whose +arithmetic is bf's, on the non-NaN inputs only (bf16_bits_test.cpp:30, :57). This one is bitwise on NaNs too: +- G9-BF16: G9-F16's elements with ``BF16_SPECIALS`` (G9-F16's specials, the low half's carry, the largest float to + inf, the fp32 subnormal 0x00018000 kept as 0x0002, a tie that stays even, the NaNs 0x7fffffff and 0xffffffff that + wrap to zeros), bit for bit against emu.bf16_bits; the elements past 37 * n keep the 0xFF fill.""" + +import itertools + +import numpy as np +import pytest + +from monolith import kernels +from monolith.formats.fp import bf16_to_f32 +from monolith.formats.gguf import GGML_TYPES +from tests.contract import gguf_reference +from tests.kernels import basalt_emu as emu +from tests.kernels import basalt_gpu +from tests.kernels import basalt_prompt_gpu as gpu +from tests.kernels.test_basalt_mmvq import weights + +F32 = np.float32 +FILL = 0xFFFFFFFF # a y word no dispatch wrote (prompt_gemm's 0xFF bytes) +CUDA_NAN = 0x7FFFFFFF + + +def bf16_rows(*rows): + """BF16 bits (len(rows), 16): each row's values, then zeros; every value must be a BF16 value (asserted).""" + v = np.zeros((len(rows), 16), F32) + for i, r in enumerate(rows): + v[i, :len(r)] = r + b = emu.bf16_bits(v) + assert np.array_equal(b.astype(np.uint32) << 16, v.view(np.uint32)), "a planted operand is not a BF16 value" + return b + + +# GM-EMU's planted BF16 cases, where the chain flushes a subnormal partial sum ((a), (b)) or reads a subnormal operand +# as zero ((c)), as (x [R, 16], w [N, 16], the twin's bits [R, N], the bits of the same fold on fma32). (a) the partial +# sum 2^-127 is subnormal. (b) the exact sum 2^-126 - 2^-150, the tie IEEE rounds up to 2^-126. (c) a subnormal +# operand, x[0][0] = 2^-127 (0x0040) and w[1][0] = 2^-133 (0x0001), times a normal one gives a normal exact product at +# (0, 0) and (1, 1), 2^-117 and 2^-123. +PLANTED = { + "a": (bf16_rows([1, -1, 1]), bf16_rows([2.0 ** -120, 2.0 ** -120 - 2.0 ** -127, 2.0 ** -126]), + [[0x00800000]], [[0x00C00000]]), + "b": (bf16_rows([1, 2.0 ** -75, 3 * 2.0 ** -75, 1]), bf16_rows([2.0 ** -126, 2.0 ** -74, -2.0 ** -75, 2.0 ** -126]), + [[0x00800000]], [[0x01000000]]), + "c": (bf16_rows([2.0 ** -127, 1], [2.0 ** 10, 1]), bf16_rows([2.0 ** 10, 2.0 ** -126], [2.0 ** -133, 2.0 ** -126]), + [[0x00800000, 0x00800000], [0x49800000, 0x00800000]], # (1, 0): 2^20 + 2^-126 rounds to 2^20 + [[0x05004000, 0x00800000], [0x49800000, 0x02100000]]), # 2^-117 + 2^-126 and 2^-123 + 2^-126 kept +} + + +def test_twin_flushes_as_measured(): + """GM-TWIN: each planted case through emu.gemm_chain and through the same fold on emu.fma32 (flush=False).""" + for case, (xb, wb, twin, ieee) in PLANTED.items(): + got, chain = emu.gemm_chain(xb, wb, True), emu.gemm_chain(xb, wb, True, flush=False) + assert np.array_equal(got, twin) and np.array_equal(chain, ieee), ( + "port: the twin gives 0x00800000 for (a) and (b), where the fma32 chain gives 0x00c00000 and 0x01000000, " + "and 0x00800000 at (c)'s (0, 0) and (1, 1), where it gives 0x05004000 and 0x02100000 (the flush " + "test_subnormals_in_safe_mode measures, tests/kernels/test_basalt_platform.py:114-126); " + f"({case}): twin {[hex(v) for v in got.ravel()]}, fma32 chain {[hex(v) for v in chain.ravel()]}") + + +def operands(rng, bf16, rows, n, k): + """GM-EMU's operand bits, x [rows, k] and w [n, k]. BF16: about one in eight +-0, the rest a random sign times + 2^u, u uniform in [-20, 10], rounded to BF16 (every nonzero magnitude in [2^-20, 2^10], and zeros drawn: asserted). + FP16: activations N(0, 1) and weights 0.02 N(0, 1), rounded to fp16.""" + if not bf16: + return (emu.half_bits(rng.standard_normal((rows, k)).astype(F32)), + emu.half_bits(F32(0.02) * rng.standard_normal((n, k)).astype(F32))) + + def draw(shape): + v = np.exp2(rng.uniform(-20.0, 10.0, shape)).astype(F32) * rng.choice(F32([-1.0, 1.0]), shape) + b = emu.bf16_bits(np.where(rng.random(shape) < 0.125, v * F32(0.0), v)) + mag = np.abs((b.astype(np.uint32) << 16).view(F32)) + assert (mag == 0).any() and ((mag == 0) | ((mag >= 2.0 ** -20) & (mag <= 2.0 ** 10))).all(), \ + "a BF16 operand is neither 0 nor of magnitude in [2^-20, 2^10], or no zero was drawn" + return b + + return draw((rows, k)), draw((n, k)) + + +@pytest.mark.parametrize("bf16", [True, False], ids=["bf16", "fp16"]) +def test_product_emulates_the_order(bf16): + """GM-EMU: every (N, K) at 1, 17 and 64 rows of a 64-row bound; then the NaN cases at 17 rows, N 72, K 320; then, + for BF16, PLANTED at a bound of its own rows.""" + order = ("bitwise equal to emu.gemm_chain, one fp32 fma chain per output from +0 in increasing k (fully specified, " + "CPU-reproducible)") + rng = np.random.default_rng(29 if bf16 else 31) + for n, k in itertools.product((1, 4, 48, 72), (320, 640)): + xb, wb = operands(rng, bf16, 64, n, k) + want = emu.gemm_chain(xb, wb, bf16) + assert np.isfinite(want.view(F32)).all() and np.count_nonzero(want), f"a vacuous fixture (N {n}, K {k})" + for r in (1, 17, 64): + y = gpu.prompt_gemm(xb, wb, bf16=bf16, B=64, rows=r) + assert (np.array_equal(y[:r], want[:r]) and np.isfinite(y[:r].view(F32)).all() + and (y[r:] == FILL).all()), ( + f"port: {order}; the rows at and past R keep 0xFF (rows {r} of 64, N {n}, K {k}): " + f"{np.count_nonzero(y[:r] != want[:r])} outputs differ, {np.count_nonzero(~np.isfinite(y[:r].view(F32)))} " + f"not finite, {np.count_nonzero(y[r:] != FILL)} past R written") + + xb, wb = operands(rng, bf16, 64, 72, 320) + nans = {"x": (3, 7, 0x7FC1 if bf16 else 0x7E01), "w": (5, 9, 0xFF81 if bf16 else 0xFC01)} # quiet +, signaling - + for where, (i, j, bits) in nans.items(): + a, b = xb.copy(), wb.copy() + (a if where == "x" else b)[i, j] = bits + with np.errstate(invalid="ignore"): # numpy's cast of a signaling NaN (emu.h2f's case) + want = emu.gemm_chain(a, b, bf16) + y = gpu.prompt_gemm(a, b, bf16=bf16, B=64, rows=17) + hit = np.zeros((17, 72), bool) + if where == "x": + hit[i, :] = True + else: + hit[:, i] = True + assert (np.array_equal(y[:17], want[:17]) and np.array_equal(y[:17] == CUDA_NAN, hit) + and np.isfinite(y[:17][~hit].view(F32)).all() and (y[17:] == FILL).all()), ( + f"port: a NaN operand gives 0x7fffffff in its row (column) only, every output {order} (a NaN at " + f"{where}[{i}][{j}], {bits:#06x}): {np.count_nonzero(y[:17] != want[:17])} outputs differ from the twin, " + f"0x7fffffff at {np.argwhere(y[:17] == CUDA_NAN).tolist()[:4]}...") + + if bf16: + for case, (xb, wb, twin, ieee) in PLANTED.items(): + y = gpu.prompt_gemm(xb, wb, bf16=True, B=len(xb)) + assert (np.array_equal(y, twin) and np.array_equal(emu.gemm_chain(xb, wb, True), twin) + and np.array_equal(emu.gemm_chain(xb, wb, True, flush=False), ieee) + and not np.array_equal(twin, ieee)), ( + "port: (a) and (b) give 0x00800000 on the GPU and in the twin, where an IEEE chain gives 0x00c00000 and " + "0x01000000; (c) gives 0x00800000 at (0, 0) and (1, 1) on the GPU and in the twin, where a chain that " + "keeps subnormal operands (emu.fma32's) gives 2^-117 + 2^-126 (0x05004000) and 2^-123 + 2^-126 " + f"(0x02100000); ({case}): GPU {[hex(v) for v in y.ravel()]}, twin {[hex(v) for v in np.ravel(twin)]}") + + +# GM-REF's rows (TG 7.4: the pack's shapes, KG 3) as (BF16 operands, N, K, B). BF16, Gemm::bf16's product: the shared +# expert's gate (prefill.cpp:1707), ssm_alpha and ssm_beta (:1587-1588), indexer k (:1608), indexer q and the router +# (:1609, :1698), the PLE value (:1538), hc inject (:1572). FP16, Gemm::native's second stage (Gemm::f16's product): +# the shared expert's gate and up (:1702-1703), its down (:1705), ssm_out and attn_output (:1592, :1688), attn_gate +# (:1586), attn_q (:1607; at B 1 and 17 only). +REF_BF16 = ((1, 2560), (48, 2560), (128, 2560), (512, 2560), (2560, 2560), (4, 10240)) +REF_FP16 = ((640, 2560), (2560, 640), (2560, 6144), (6144, 2560), (12288, 2560)) +# Gemm::native end to end (the dequantization into the fp16 image, then the FP16 product), as (GGUF type, N, K) at +# B 37: Q2_0 (the pack's routed and dense type) at attn_k's shape (:1605), Q4_K at the shared expert's gate (:1702), +# and every type the dequantizer takes at one shape. The GGUF type is None on the rows above. +REF_NATIVE = ((42, 512, 2560), (12, 640, 2560)) + tuple((t, 64, 2560) for t in kernels.DEQUANT16_TYPES) +REF_ROWS = [(bf16, None, n, k, b) for bf16, shapes in ((True, REF_BF16), (False, REF_FP16)) for n, k in shapes + for b in ((1, 17) if (n, k) == (12288, 2560) else (1, 17, 512))] +REF_ROWS += [(False, t, n, k, 37) for t, n, k in REF_NATIVE] +REF_GATE = { # the bound's standing per entry (ER-D5's label) with hc8_parity.cpp:269's criterion + True: "hc8_parity.cpp:269, Gemm::bf16's gate at this pack's plain-BF16 shapes: " + 'expect(ex.rel() < 5e-3, "the product against the copy in double");', + False: "nearest bound; no basalt test gates Gemm::native's or Gemm::f16's product against a reference: " + 'hc8_parity.cpp:269 expect(ex.rel() < 5e-3, "the product against the copy in double");', +} + + +@pytest.mark.parametrize("bf16, t, n, k, B", REF_ROWS, + ids=[f"{'bf16' if b else 'fp16' if t is None else GGML_TYPES[t][0]}-{n}x{k}-B{B}" + for b, t, n, k, B in REF_ROWS]) +def test_product_against_double(bf16, t, n, k, B): + """GM-REF: y against x64 @ w64.T on the operands' exact values, emu.rel_norm over all B x N outputs (basalt + samples 256, hc8_parity.cpp:253-262). A native row (GGUF type ``t``) runs gpu.native on test_basalt_mmvq's + ``weights`` blocks, and its w64 is their exact dequantized values (gguf_reference.dequantize), so the fp16 image's + rounding counts against the bound. The fixture keeps every operand at most 2^10 and every nonzero BF16 one at + least 2^-40 (TG 7.1: nothing overflows, no partial sum is subnormal). Prints the measured value.""" + rng = np.random.default_rng((n, k, B) if t is None else (t, n, k, B)) + to16, widen = (emu.bf16_bits, bf16_to_f32) if bf16 else (emu.half_bits, emu.h2f) + xb = to16(rng.standard_normal((B, k)).astype(F32)) + if t is None: + wb = to16(F32(0.02) * rng.standard_normal((n, k)).astype(F32)) + w64 = widen(wb).astype(np.float64) + else: + blocks = weights(t, k, n, rng) + w64 = gguf_reference.dequantize(t, blocks).astype(np.float64) + x64 = widen(xb).astype(np.float64) + for v in (x64, w64): + mag = np.abs(v) + assert mag.max() <= 2.0 ** 10 and (not bf16 or mag[mag > 0].min(initial=np.inf) >= 2.0 ** -40), \ + "an operand above 2^10 in magnitude (or not finite), or a nonzero BF16 operand below 2^-40" + ref = x64 @ w64.T + assert np.abs(ref).max() > 0, "a vacuous reference: every output 0" + y = (gpu.prompt_gemm(xb, wb, bf16=bf16, B=B) if t is None else gpu.native(t, blocks, xb, B=B)[0]).view(F32) + bad, rel = np.count_nonzero(~np.isfinite(y)), emu.rel_norm(y, ref) + tag = "bf16" if bf16 else "fp16" if t is None else f"native {GGML_TYPES[t][0]}" + print(f"GM-REF {tag} N {n} K {k} B {B}: rel_norm {rel:.3e}") + assert bad == 0 and rel < 5e-3, ( + f"{REF_GATE[bf16]} ({tag} N {n}, K {k}, B {B}): rel_norm {rel:.3e}, {bad} not finite") + + +def whole(xb, wb, bf16): + """The reference of the invariance gates: the product as one dispatch over every row and column (never the + handler's slices), asserted live: every output finite (so no 0xFF word) and one nonzero.""" + B, n = len(xb), len(wb) + y = gpu.prompt_gemm(xb, wb, bf16=bf16, B=B, slices=[(0, B, 0, n)]) + assert np.isfinite(y.view(F32)).all() and np.count_nonzero(y), f"a vacuous reference (B {B}, N {n})" + return y + + +def differ(y, want): + """How the outputs ``y`` miss ``want``, for an assert message: those that differ, those not finite.""" + return f"{np.count_nonzero(y != want)} outputs differ, {np.count_nonzero(~np.isfinite(y.view(F32)))} not finite" + + +# GM-ROWS' and GM-STEP's shapes (N, K): BF16 ssm_alpha and ssm_beta (prefill.cpp:1587-1588), FP16 the shared expert's +# down (:1705). +ROW_SHAPES = {True: (48, 2560), False: (2560, 640)} +ROWS = ("port: every row bitwise equal to the same row of one whole-product dispatch at B 512 (row invariance: an " + "output depends only on its x row, its w row and K)") + + +@pytest.mark.parametrize("bf16", [True, False], ids=["bf16", "fp16"]) +def test_rows_do_not_depend_on_the_batch(bf16): + """GM-ROWS: each run's rows against the same rows of the whole product at B 512 (equal to a live reference, so + finite); for FP16 also (2560, 6144) at B 512 in the handler's own slices, more than one, against its whole + product.""" + (n, k), tag = ROW_SHAPES[bf16], "bf16" if bf16 else "fp16" + rng = np.random.default_rng(43 if bf16 else 47) + xb, wb = operands(rng, bf16, 512, n, k) + ref, perm = whole(xb, wb, bf16), rng.permutation(512) + runs = [(f"row {i} alone", xb[i:i + 1], None, ref[i:i + 1]) for i in (0, 63, 64, 255, 511)] + runs += [(f"the first {b} rows at B {b}", xb[:b], None, ref[:b]) for b in (63, 65, 17, 37)] + runs += [("the 512 rows permuted", xb[perm], None, ref[perm])] + runs += [(f"row slices of {rb}", xb, [(r0, min(rb, 512 - r0), 0, n) for r0 in range(0, 512, rb)], ref) + for rb in (64, 192)] + for what, x, slices, want in runs: + y = gpu.prompt_gemm(x, wb, bf16=bf16, B=len(x), slices=slices) + assert np.array_equal(y, want), f"{ROWS} ({what}; {tag} N {n} K {k}): {differ(y, want)}" + + fresh = operands(rng, bf16, 512, 1, k)[0] + fresh[300] = xb[5] + assert np.delete((fresh != xb).any(axis=1), 300).all(), "a fresh row equals the batch's row" + y = gpu.prompt_gemm(fresh, wb, bf16=bf16, B=512) + assert np.array_equal(y[300], ref[5]) and np.isfinite(y.view(F32)).all(), ( + f"{ROWS} (row 5 at row 300 of fresh rows; {tag} N {n} K {k}): {differ(y[300], ref[5])} in row 300, " + f"{np.count_nonzero(~np.isfinite(y.view(F32)))} not finite in the run") + + if not bf16: # F7: a product the handler's own rule slices + x7, w7 = operands(rng, False, 512, 2560, 6144) + assert len(kernels.basalt_prompt_gemm_slices(512, 2560, 6144)) > 1, "FP16 (2560, 6144) at B 512 is one slice" + want, y = whole(x7, w7, False), gpu.prompt_gemm(x7, w7, bf16=False, B=512) + assert np.array_equal(y, want), f"{ROWS} (FP16 N 2560 K 6144 in the handler's slices): {differ(y, want)}" + + +@pytest.mark.parametrize("bf16", [True, False], ids=["bf16", "fp16"]) +def test_rows_from_step_state(bf16): + """GM-STEP: compiled at B 512 and run with t_this_step 1, 17, 65, 511, 512 and 600, then done 1 at 511; and the + first 37 rows compiled at B 37 with t_this_step 600, where the row tile reaches row 63 (at B 512 the grid ends at + row 511) and only prompt_rows' clamp keeps its loads and stores inside x and y.""" + (n, k), tag = ROW_SHAPES[bf16], "bf16" if bf16 else "fp16" + rng = np.random.default_rng(53 if bf16 else 59) + xb, wb = operands(rng, bf16, 512, n, k) + ref = whole(xb, wb, bf16) + for B, r, done in [(512, r, 0) for r in (1, 17, 65, 511, 512, 600)] + [(512, 511, 1), (37, 600, 0)]: + y = gpu.prompt_gemm(xb[:B], wb, bf16=bf16, B=B, rows=r, done=done) + m = 0 if done else min(r, B) + assert np.array_equal(y[:m], ref[:m]) and (y[m:] == FILL).all(), ( + "port: rows < min(r, B) equal the B 512 rows bitwise; rows >= r, and every row at done 1, keep 0xFF (the " + f"rows are StepState data, the program the same) (B {B}, t_this_step {r}, done {done}; {tag} N {n} K {k}): " + f"{differ(y[:m], ref[:m])} below row {m}, {np.count_nonzero(y[m:] != FILL)} at or past it written") + + +# GM-COLS' shapes (N, K): BF16 indexer q and the router (prefill.cpp:1609, :1698), as GM-ROWS' 48 columns hold neither +# n 65 at r0 37 nor a slice of 192; FP16 the shared expert's down (:1705). +COL_SHAPES = {True: (512, 2560), False: (2560, 640)} + + +@pytest.mark.parametrize("bf16", [True, False], ids=["bf16", "fp16"]) +def test_columns_do_not_depend_on_the_matrix_rows(bf16): + """GM-COLS at 37 rows (a partial row tile): the w rows [r0, r0 + n) as their own matrix, the w rows permuted, and + explicit column slices of 64 and of 192, against the matching columns of the whole product.""" + (n, k), tag, B = COL_SHAPES[bf16], "bf16" if bf16 else "fp16", 37 + rng = np.random.default_rng(61 if bf16 else 67) + xb, wb = operands(rng, bf16, B, n, k) + full, perm = whole(xb, wb, bf16), rng.permutation(n) + runs = [(f"w rows [{r0}, {r0 + c}) alone", wb[r0:r0 + c], None, full[:, r0:r0 + c]) + for r0 in (0, 37) for c in (1, 63, 65)] + runs += [("the w rows permuted", wb[perm], None, full[:, perm])] + runs += [(f"column slices of {cb}", wb, [(0, B, c0, min(cb, n - c0)) for c0 in range(0, n, cb)], full) + for cb in (64, 192)] + for what, w, slices, want in runs: + y = gpu.prompt_gemm(xb, w, bf16=bf16, B=B, slices=slices) + assert np.array_equal(y, want), ( + "port: bitwise equal to the matching columns of the full product, computed as one dispatch (column " + f"invariance: an output depends only on its x row, its w row and K) ({what}; {tag} N {n} K {k}, B {B}): " + f"{differ(y, want)}") + + +def test_repeats_are_bit_identical(): + """GM-REPEAT (FP16): FP16 (6144, 2560) at B 512 in the handler's slices, into a y prefilled 0x00, then 0xFF, on one + pipeline, then into 0xFF on a freshly compiled one (basalt_gpu.pipeline's cache cleared). (native): Q4_K (640, + 2560) at B 37 through gpu.native, the fp16 image and y prefilled 0x00, then 0xFF.""" + rng = np.random.default_rng(71) + xb, wb = operands(rng, False, 512, 6144, 2560) + key = (kernels.basalt_prompt_gemm_source(), "basalt_prompt_gemm", 512, {"GEMM_BF16": "0"}) + pso = gpu.prompt_pipeline(*key) + runs = [gpu.prompt_gemm(xb, wb, bf16=False, B=512, fill=f) for f in (0x00, 0xFF)] + assert gpu.prompt_pipeline(*key) is pso, "the second run compiled a pipeline of its own" + basalt_gpu.pipeline.cache_clear() + runs.append(gpu.prompt_gemm(xb, wb, bf16=False, B=512)) + assert gpu.prompt_pipeline(*key) is not pso, "the third run reused the first pipeline" + assert np.isfinite(runs[0].view(F32)).all() and np.count_nonzero(runs[0]), "a vacuous first run" + for i, y in enumerate(runs[1:], 2): + assert np.array_equal(y, runs[0]), ( + "port: every run bitwise identical (deterministic: no atomics, no split of K, no dependence on scheduling " + f"or on y's prior bytes) (run {i} against run 1; fp16 N 6144 K 2560, B 512): {differ(y, runs[0])}") + + blocks, x16 = weights(12, 2560, 640, rng), emu.half_bits(rng.standard_normal((37, 2560)).astype(F32)) + (y, image), (again, image2) = (gpu.native(12, blocks, x16, B=37, fill=f) for f in (0x00, 0xFF)) + assert (np.isfinite(y.view(F32)).all() and np.count_nonzero(y) and np.isfinite(emu.h2f(image)).all() + and np.count_nonzero(image)), "a vacuous first native run" + assert np.array_equal(again, y) and np.array_equal(image2, image), ( + "port: every run bitwise identical (deterministic: no atomics, no split of K, no dependence on scheduling " + "or on the image's or y's prior bytes) (the run into 0xFF against the run into 0x00; native q4_k N 640 K " + f"2560, B 37): {differ(again, y)}, {np.count_nonzero(image2 != image)} image halves differ") + + +@pytest.mark.parametrize("t", kernels.DEQUANT16_TYPES, ids=lambda t: GGML_TYPES[t][0]) +def test_two_stage_product_is_the_product_on_the_image(t): + """GM-COMP: gpu.native (basalt_dequant_g32 at DQ_OUT 1, then the product at GEMM_BF16 0) of fp16 activations by + test_basalt_mmvq's ``weights`` blocks (random bytes, every fp16 scale field a normal of magnitude in [2^-10, + 2^-5)) of GGUF type ``t`` at (64, 2560), B 37, against the FP16 product on the host's image of the same blocks, + emu.cuda_half_bits(gguf_reference.dequantize(t, blocks)) (asserted live: finite, one output nonzero). Both sides + run the one product kernel at one (N, K, B), so equality needs GM-REPEAT's determinism alone.""" + n, k, B = 64, 2560, 37 + rng = np.random.default_rng((83, t)) + blocks, xb = weights(t, k, n, rng), emu.half_bits(rng.standard_normal((B, k)).astype(F32)) + host = emu.cuda_half_bits(gguf_reference.dequantize(t, blocks)) + want = gpu.prompt_gemm(xb, host, bf16=False, B=B) + assert np.isfinite(want.view(F32)).all() and np.count_nonzero(want), "a vacuous reference" + y, image = gpu.native(t, blocks, xb, B=B) + assert np.array_equal(y, want), ( + "port: native (dequant at DQ_OUT 1, then GEMM_BF16 0) bitwise equal to the FP16 product on " + f"emu.cuda_half_bits(gguf_reference.dequantize(t, blocks)) ({GGML_TYPES[t][0]} N {n} K {k}, B {B}): " + f"{differ(y, want)}; {np.count_nonzero(image != host)} image halves differ from the host's") + + +# G9-F16's specials, float32 bits: to_f16's fp16 bits (__float2half_rn). +-0; the fp32 subnormals 0x00000001 and +# 0x807fffff, below half of fp16's least subnormal (a signed zero whether or not read as zero); 65504, the largest +# fp16; 0x477fefff, the float below the tie 65520; 65520 (65504's last bit is odd: inf); +-inf; the NaNs 0x7fc00000, +# 0xffffffff and the signaling 0x7f800001, each sm_120's 0x7fff; the fp16-subnormal ties 2^-25 (to 0, where ties away +# from zero would give 2^-24) and 3 * 2^-25 (to 2 * 2^-24). +F16_SPECIALS = { + 0x00000000: 0x0000, 0x80000000: 0x8000, 0x00000001: 0x0000, 0x807FFFFF: 0x8000, 0x477FE000: 0x7BFF, + 0x477FEFFF: 0x7BFF, 0x477FF000: 0x7C00, 0x7F800000: 0x7C00, 0xFF800000: 0xFC00, 0x7FC00000: 0x7FFF, + 0xFFFFFFFF: 0x7FFF, 0x7F800001: 0x7FFF, 0x33000000: 0x0000, 0x33C00000: 0x0002, +} + + +def test_to_f16_is_the_conversion(): + """G9-F16: to_f16 of n 100 floats a row at 37 rows of a 64-row bound, into a y prefilled 0xFF. F16_SPECIALS, + written as bits, start row 0, end row 36 (the last converted elements) and start row 37; every other element is + an fp32 normal of magnitude 2^u, u uniform in [-30, 20] (to 0, to fp16 subnormals and normals, past 65520 to + inf).""" + B, R, n = 64, 37, 100 + rng = np.random.default_rng(73) + x = (np.exp2(rng.uniform(-30.0, 20.0, (B, n))) * rng.choice([-1.0, 1.0], (B, n))).astype(F32) + bits, sp = x.reshape(-1).view(np.uint32), np.array(list(F16_SPECIALS), np.uint32) + for at in (0, R * n - len(sp), R * n): + bits[at:at + len(sp)] = sp + with np.errstate(invalid="ignore"): # numpy's cast of a signaling NaN + want, twin = emu.cuda_half_bits(x), emu.cuda_half_bits(sp.view(F32)) + assert np.array_equal(twin, list(F16_SPECIALS.values())) and np.isin(sp, bits[:R * n]).all(), \ + "a special is not among the converted elements, or the twin misses its fp16 bits" + y = gpu.convert(x, bf16=False, B=B, rows=R) + miss = np.argwhere(y[:R] != want[:R]) + assert np.array_equal(y[:R], want[:R]) and (y[R:] == 0xFFFF).all(), ( + "port: bitwise equal to emu.cuda_half_bits (__float2half_rn: round to nearest even, every NaN to sm_120's " + "0x7fff); elements past R*n keep 0xFFFF. The nearest basalt check (dequant_f16_parity.cpp:73, the store " + f"against the rounded fp32 value) is bitwise too (R {R} of B {B}, n {n}): {len(miss)} elements differ, as " + f"(x, y, want) {[(hex(bits[i * n + j]), hex(y[i, j]), hex(want[i, j])) for i, j in miss[:4]]}; " + f"{np.count_nonzero(y[R:] != 0xFFFF)} past R*n written") + + +# G9-BF16's specials, float32 bits: to_bf16's bf16 bits (bf, kernels.cu:31-35: u += 0x7fff + ((u >> 16) & 1) in 32 +# bits, then the high half; no NaN case). G9-F16's (F16_SPECIALS), where 0x807fffff rounds by its bits to -2^-126 +# (0x8080) and 65504 up to 65536; then 0x3f80ffff (the low half's carry), 0x7f7fffff (the largest float, to inf), the +# fp32 subnormal 0x00018000 (kept: a load keeps its bits; the tie with bit 16 set, to the even 0x0002), the tie +# 0x3f808000 with bit 16 clear (stays 0x3f80: to even, not away from zero), and the NaNs: sm_120's 0x7fffffff wraps +# to 0x8000 (-0), 0xffffffff to 0x0000 (+0), the signaling 0x7f800001 to +inf (0x7f80); 0x7fc00000 stays 0x7fc0. +BF16_SPECIALS = { + 0x00000000: 0x0000, 0x80000000: 0x8000, 0x00000001: 0x0000, 0x807FFFFF: 0x8080, 0x477FE000: 0x4780, + 0x477FEFFF: 0x4780, 0x477FF000: 0x4780, 0x7F800000: 0x7F80, 0xFF800000: 0xFF80, 0x7FC00000: 0x7FC0, + 0xFFFFFFFF: 0x0000, 0x7F800001: 0x7F80, 0x33000000: 0x3300, 0x33C00000: 0x33C0, + 0x3F80FFFF: 0x3F81, 0x7F7FFFFF: 0x7F80, 0x00018000: 0x0002, 0x3F808000: 0x3F80, 0x7FFFFFFF: 0x8000, +} + + +def test_to_bf16_is_the_rounding(): + """G9-BF16: to_bf16 of n 100 floats a row at 37 rows of a 64-row bound, into a y prefilled 0xFF: G9-F16's + elements (its seed and normals, the specials at its three places) with BF16_SPECIALS for F16_SPECIALS.""" + B, R, n = 64, 37, 100 + rng = np.random.default_rng(73) + x = (np.exp2(rng.uniform(-30.0, 20.0, (B, n))) * rng.choice([-1.0, 1.0], (B, n))).astype(F32) + bits, sp = x.reshape(-1).view(np.uint32), np.array(list(BF16_SPECIALS), np.uint32) + for at in (0, R * n - len(sp), R * n): + bits[at:at + len(sp)] = sp + want, twin = emu.bf16_bits(x), emu.bf16_bits(sp.view(F32)) + assert set(F16_SPECIALS) < set(BF16_SPECIALS) and np.array_equal(twin, list(BF16_SPECIALS.values())) \ + and np.isin(sp, bits[:R * n]).all(), \ + "G9-F16's specials are not all here, a special is not among the converted elements, or the twin misses its bits" + y = gpu.convert(x, bf16=True, B=B, rows=R) + miss = np.argwhere(y[:R] != want[:R]) + assert np.array_equal(y[:R], want[:R]) and (y[R:] == 0xFFFF).all(), ( + "port: bitwise equal to emu.bf16_bits (bf's integer round to nearest even with no NaN case: its uint64 sum cut " + "to 16 bits is bf's 32-bit wrap, so 0x7fffffff -> 0x8000, 0xffffffff -> 0x0000); elements past R*n keep " + f"0xFFFF (R {R} of B {B}, n {n}): {len(miss)} elements differ, as (x, y, want) " + f"{[(hex(bits[i * n + j]), hex(y[i, j]), hex(want[i, j])) for i, j in miss[:4]]}; " + f"{np.count_nonzero(y[R:] != 0xFFFF)} past R*n written") diff --git a/tests/kernels/test_basalt_prompt_program.py b/tests/kernels/test_basalt_prompt_program.py new file mode 100644 index 00000000..7b04c7ed --- /dev/null +++ b/tests/kernels/test_basalt_prompt_program.py @@ -0,0 +1,104 @@ +"""basalt's prompt-path op kinds (monolith/ops/basalt_prompt.py) in compiled programs on the GPU. A session compiles +the dynamic-T prompt program once, at its chunk bound B, and replays it for every chunk with StepState.t_this_step set +to the chunk's rows (monolith/generate.py:604); this tier runs the handlers' dispatches (compiler/emit_basalt_prompt.py) +that way, through Engine, over a synthetic .basalt file (tests/contract/test_basalt_ops.py ``write_file``), and checks +what the single-kernel tier (tests/kernels/test_basalt_prompt_gemm.py) cannot see: that the handlers bind what the +kernels read, and that a program's rows are StepState data (dynamic-T) or its compiled count (static). Each prompt +kind joins ``graph``. + +- GM-PROG: Gemm::bf16 (src/prefill/gemm.cu:122-132) of BF16 rows by dense/a, 48 BF16 rows over 2560 inputs + (ssm_alpha's shape, src/prefill/prefill.cpp:1587), Gemm::native (:169-185) of FP16 rows by gguf/b, Q2_0 256 x + 2560, then gguf/c, Q4_K 64 x 2560, whose dequantizations share the program's one FP16 scratch, and to_f16 and + to_bf16 (src/prefill/kernels.cu:818-833) of F32 rows of 2560 (the PLE batch's, prefill.cpp:1531-1536), in + dynamic-T programs at B 64 and B 128 on one StepState layout (t_max 128), each replayed at t_this_step 1, 17 and + 64, and in a static program at T 17, replayed at t_this_step 1 (what the advance leaves after a step, + kernels/common/advance.metal:34, so a static program that read its rows from StepState would compute one). Each + replay runs twice, into outputs prefilled 0xFF before each run: the rows below the chunk's are the single-kernel + helpers' (tests/kernels/basalt_prompt_gpu.py ``prompt_gemm``, ``native`` and ``convert``) on the same bytes, one + whole run of the 128 rows at B 128 each, so both bounds and the static program give the same rows, and gguf/b's + show that gguf/c's dequantization did not overwrite the scratch while gguf/b's products read it; the rest keep the + fill; and the second run gives the first's bits. 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 + (gguf/b and gguf/c share a page).""" + +import numpy as np +import pytest + +from monolith.core import DType, Graph +from monolith.core.shapes import T +from monolith.core.step_state import StepStateLayout +from monolith.packs.basalt import BasaltSource +from monolith.runtime import Engine +from tests.contract.test_basalt_ops import emit, op, weight, write_file +from tests.kernels import basalt_emu as emu +from tests.kernels import basalt_prompt_gpu as gpu +from tests.kernels.test_basalt_mmvf import bf16_weights +from tests.kernels.test_basalt_mmvq import weights + +F32 = np.float32 +LAYOUT = StepStateLayout(t_max=128) # the session's one layout: every program compiles against it +N, K = 48, 2560 # dense/a +GGUF = {"b": (42, 256), "c": (12, 64)} # gguf/: (ggml type, rows) over K: Q2_0, Q4_K +CONVERTS = {"f16": DType.F16, "bf16": DType.BF16} # y.: to_f16, to_bf16 of xf [T, K] F32 + + +def graph(g, src): + """The prompt kinds over the file: Gemm::bf16 of xb [T, K] by dense/a into y.a [T, N], Gemm::native of x16 + [T, K] by gguf/b and gguf/c into y.b and y.c, and to_f16 and to_bf16 of xf [T, K] into y.f16 and y.bf16.""" + xb = g.input("xb", (T, K), DType.BF16) + op(g, "basalt_prompt_gemm", [xb, weight(g, "dense/a", src)], [g.value("y.a", (T, N), DType.F32)], entry="bf16") + x16 = g.input("x16", (T, K), DType.F16) + for name, (_, n) in GGUF.items(): + op(g, "basalt_prompt_gemm", [x16, weight(g, f"gguf/{name}", src)], [g.value(f"y.{name}", (T, n), DType.F32)], + entry="native") + xf = g.input("xf", (T, K), DType.F32) + for name, dtype in CONVERTS.items(): + op(g, "basalt_prompt_convert", [xf], [g.value(f"y.{name}", (T, K), dtype)]) + + +@pytest.mark.parametrize("copy", [False, True], ids=["windows", "exact-copies"]) +def test_prompt_gemm_in_a_program(tmp_path, copy): + """GM-PROG: (t, dynamic-T, [(t_this_step, the rows computed)]) per program, against one whole product of the 128 + rows at B 128 per weight (each asserted live: finite, one output nonzero) and one conversion of xf's 128 rows at + B 128 per 16-bit dtype (each asserted live: every element written, one nonzero).""" + rng = np.random.default_rng(79) + wb = bf16_weights(rng, N, K) + xb = emu.bf16_bits(rng.standard_normal((128, K)).astype(F32)) + blocks = {name: weights(tid, K, n, rng) for name, (tid, n) in GGUF.items()} + x16 = emu.half_bits(rng.standard_normal((128, K)).astype(F32)) + xf = rng.standard_normal((128, K)).astype(F32) + gguf = {name: (tid, n, K, blocks[name].tobytes()) for name, (tid, n) in GGUF.items()} + src = BasaltSource(write_file(tmp_path / "prompt.basalt", gguf, {"a": (N, K, wb.tobytes())}), copy=copy) + ref = {"a": gpu.prompt_gemm(xb, wb, bf16=True, B=128), # y.: the rows of 's product + **{name: gpu.native(tid, blocks[name], x16, B=128)[0] for name, (tid, _) in GGUF.items()}} + for name, want in ref.items(): + assert np.isfinite(want.view(F32)).all() and np.count_nonzero(want), f"a vacuous reference (y.{name})" + for name in CONVERTS: # y.: xf's rows converted + ref[name] = gpu.convert(xf, bf16=name == "bf16", B=128, rows=128) + assert (ref[name] != 0xFFFF).all() and np.count_nonzero(ref[name]), f"a vacuous reference (y.{name})" + programs = [(b, True, [(r, r) for r in (1, 17, 64)]) for b in (64, 128)] + [(17, False, [(1, 17)])] + for t, dynamic, replays in programs: + g = Graph("step") + graph(g, src) + eng = Engine(emit(g, src, t, dynamic_t=dynamic, layout=LAYOUT), gpu.device()) + eng.buffers["xb"].write(xb[:t].tobytes(), 0) + eng.buffers["x16"].write(x16[:t].tobytes(), 0) + eng.buffers["xf"].write(xf[:t].tobytes(), 0) + for r, m in replays: + eng.buffers[eng.program.step_state].write(LAYOUT.pack({"t_this_step": r}), 0) + runs = [] + for _ in range(2): + for name in ref: + eng.buffers[f"y.{name}"].fill(0xFF) + assert eng.run(1, steps_per_cb=1, in_flight=1).steps == 1 + runs.append({name: np.frombuffer(eng.read(f"y.{name}"), want.dtype).reshape(t, -1) + for name, want in ref.items()}) + for name, want in ref.items(): + y, again, fill = runs[0][name], runs[1][name], np.iinfo(want.dtype).max # the 0xFF prefill's word + assert np.array_equal(y[:m], want[:m]) and (y[m:] == fill).all() and np.array_equal(again, y), ( + "port: rows < r bitwise equal to the kernel-tier helpers' rows, rows >= r keep 0xFF, a second " + "replay identical, both bounds and the static program (at r 17) giving the same rows " + f"({'dynamic-T at B' if dynamic else 'static at T'} {t}, t_this_step {r}, y.{name}, " + f"{'exact copies' if copy else 'windows'}): {np.count_nonzero(y[:m] != want[:m])} outputs below " + f"row {m} differ from the helper's, {np.count_nonzero(y[m:] != fill)} at or past it written, " + f"{np.count_nonzero(again != y)} differ in the second run") diff --git a/third_party/NOTICE b/third_party/NOTICE index 77f4c30f..c81a7a37 100644 --- a/third_party/NOTICE +++ b/third_party/NOTICE @@ -263,7 +263,9 @@ Format: `` — adapted from / copied from `` `` @ `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`. + `docs/research/basalt-nvcc/s2_experts.md`); and `rel_norm`, the GEMM gate's metric, `Err` of + `src/kernels/hc8_parity.cpp:57-61` in its float32 form (`gemm_chain`, `fma_metal` and `_fma64_odd` beside it are + the port's order and this GPU's measured `fma`, not basalt's). 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 @@ -285,6 +287,17 @@ Format: `` — adapted from / copied from `` `` @ `src/kernels/elementwise_parity.cpp:438-472` (MIT): their fixtures (the `std::mt19937(7)` blocks with pinned scales, the pack's tensors, the NaN-scale Q8_0 pair) and criteria, and `dequant_bf16.cu:190-205`'s type table. License: `third_party/BASALT-LICENSE`. +- `kernels/common/basalt_prompt_gemm.metal` — adapted from `src/prefill/gemm.cu:122-185` and + `src/prefill/kernels.cu:31-40` and `:818-833` (MIT): `Gemm::bf16`'s and `Gemm::native`'s products as one + fixed-order fma chain per output (the order is this port's: cuBLAS fixes none, + `docs/research/basalt-nvcc/prefill_kernels.md`), and `to_f16` and `to_bf16` with `hf` and `bf`. License: + `third_party/BASALT-LICENSE`. +- `monolith/compiler/emit_basalt_prompt.py` — adapted from `src/prefill/prefill.cpp:1188-1199` (MIT): `native_proj`'s + and `bf16_proj`'s weight checks, as the refusals at emit time of an `entry` its weight contradicts. License: + `third_party/BASALT-LICENSE`. +- `tests/kernels/test_basalt_prompt_gemm.py` — adapted from `src/kernels/hc8_parity.cpp:253-262` and `:269` (MIT): the + GEMM gate's bound, `expect(ex.rel() < 5e-3, "the product against the copy in double");`, and its use of `Err` + over the product against double. License: `third_party/BASALT-LICENSE`. ## Test data From f3476e3b2f59d659a57968b29a17254457c2a898 Mon Sep 17 00:00:00 2001 From: Lance Woodson <65194841+woodsonl@users.noreply.github.com> Date: Sat, 24 Oct 2026 14:44:33 -0500 Subject: [PATCH 73/74] Emit basalt's Q5_K head, top-1 and proxy top-1 as ops monolith/ops/basalt.py registers one op kind per basalt host launcher of the Q5_K head: basalt_q5k_head (q5k_head_mmvq, then q5k_head_mask_unmapped on each column when a map is given), basalt_q5k_top1 (the partials, then the merge) and basalt_q5k_proxy_top1 (the 2-bit score, then the final). Its docstring is their contract. monolith/compiler/emit_basalt.py emits them in basalt's launch order, with macros, grids, threadgroups, params and scratch sizes from monolith/kernels.py's builders only. basalt_q5k_mask_grid and basalt_q5k_top1_part_bytes are new. Each follow-up dispatch declares what the dispatch before it wrote, so the barrier pass orders it. The handlers make basalt's launcher checks at emit time, plus the port's alignment rule. Graph.input(..., host=True) declares an input whose buffer the session allocates and passes to every program that binds it: the drafter's gathered head rows, their map and the 2-bit copy, one allocation for every tier and width. emit_program gives it role "host" at exactly the value's bytes, which Engine requires the session to supply. It refuses a host input named after a StepState field or one of the program's own buffers, since one name cannot hold both. The accept and confidence logs are assigned rather than set by default, so that check sees them. Tests: tests/contract/test_basalt_q5k_ops.py (dispatches against the builders at T = 1 .. 8, barriers, scratch sizes, and 62 refusals with one defect each). tests/kernels/test_basalt_q5k_ops_program.py runs static programs on the GPU over a .basalt file and over the session's host buffers, bit for bit equal to the single-kernel harness. The net change of woodsonl/mlxstream#26 (merge 15d65e4). It applies without a conflict on this base, which merges #99's, #98's and #82's branches. All eight files are byte-equal to the fork's merge. --- monolith/compiler/emit.py | 28 +- monolith/compiler/emit_basalt.py | 151 +++++- monolith/core/ir.py | 10 +- monolith/kernels.py | 14 +- monolith/ops/basalt.py | 54 +- tests/contract/test_basalt_q5k_ops.py | 541 +++++++++++++++++++ tests/kernels/test_basalt_q5k_ops_program.py | 334 ++++++++++++ third_party/NOTICE | 34 +- 8 files changed, 1134 insertions(+), 32 deletions(-) create mode 100644 tests/contract/test_basalt_q5k_ops.py create mode 100644 tests/kernels/test_basalt_q5k_ops_program.py diff --git a/monolith/compiler/emit.py b/monolith/compiler/emit.py index 9a71b4dc..d9afaf75 100644 --- a/monolith/compiler/emit.py +++ b/monolith/compiler/emit.py @@ -1345,7 +1345,8 @@ def _verify_select(ctx: _Ctx, op: Op) -> None: mode, thr = 0, (float(op.attrs.get("threshold", 0.0)) if conf is not None else 0.0) prm = ctx.params("verify_select", kernels.select_params(gamma, thr, ctx.t, mode=mode, cost=cost, log_cap=kernels.ACCEPT_LOG_CAP, ctx_cap=ctx.ctx_cap_target, lm=bool(op.attrs.get("lm")))) - ctx.program.buffers.setdefault(CONF_LOG, BufferSpec(kernels.ACCEPT_LOG_CAP * kernels.CONF_LOG_WIDTH * 4, None, "arena")) + # assigned, not setdefault: a host input of this name loses its spec to the log, and emit_program refuses it + ctx.program.buffers[CONF_LOG] = BufferSpec(kernels.ACCEPT_LOG_CAP * kernels.CONF_LOG_WIDTH * 4, None, "arena") cb = ctx.buf(conf) if conf is not None else (ctx.scratch("verify_select.conf", gamma * 4), 0) ctx.add(k, [(0, *ctx.buf(drafts)), (1, *cb), (2, ctx.program.step_state, 0), (3, prm, 0), (4, CONF_LOG, 0)], (1, 1, 1), (32, 1, 1), op.kind, writes=[2, 4]) @@ -1356,7 +1357,8 @@ def _accept_scan(ctx: _Ctx, op: Op) -> None: k = ctx.kernel("spec_ops", _spec_ops(ctx), "accept_scan", kernels.eos_macros(ctx.eos)) prm = ctx.params("accept_scan", kernels.accept_params(ctx.ring_capacity, ctx.eos, kernels.ACCEPT_LOG_CAP, ctx_cap=ctx.ctx_cap, lm=bool(op.attrs.get("lm")))) - ctx.program.buffers.setdefault(ACCEPT_LOG, BufferSpec(kernels.ACCEPT_LOG_CAP * 4, None, "arena")) + # assigned, not setdefault: a host input of this name loses its spec to the log, and emit_program refuses it + ctx.program.buffers[ACCEPT_LOG] = BufferSpec(kernels.ACCEPT_LOG_CAP * 4, None, "arena") ctx.add(k, [(0, *ctx.buf(token)), (1, ctx.program.step_state, 0), (2, ctx.program.ring, 0), (3, prm, 0), (4, ACCEPT_LOG, 0)], (1, 1, 1), (32, 1, 1), op.kind, writes=[1, 2, 4]) @@ -1469,6 +1471,7 @@ def emit_program(g: Graph, *, pack: Union[PackFile, BasaltSource, Sequence[Union ctx.ctx_cap_target, ctx.ctx_cap = _context_capacity(ctx, g) program.context_capacity = ctx.ctx_cap hoisted = {op.attrs["stat_value"]: ctx.slab_info(op.inputs[1].name).n_blocks for op in g.ops if op.kind == "gemv" and op.attrs.get("stat_value")} + host: Dict[str, BufferSpec] = {} # host input -> its own spec (checked after the tail) for v in g.values.values(): if v.is_view: continue # rows of its base's buffer @@ -1476,7 +1479,16 @@ def emit_program(g: Graph, *, pack: Union[PackFile, BasaltSource, Sequence[Union program.buffers[v.name] = BufferSpec(_value_bytes(v, t), None, "state") elif v.is_input: fld = "pending_tokens" if v.name == "tokens" else v.name - if fld not in layout.offsets: # not StepState-backed: a host-written arena buffer + if v.is_host and fld in layout.offsets: # _Ctx.buf would bind the field, not the session's + raise ValueError(f"emit_program: the host input {v.name!r} is named after StepState's {fld!r}; a host " + "input binds the session's buffer of its name") + if v.is_host and (v.name in (program.step_state, program.ring) or v.name in program.buffers): # the windows so far + own = {program.step_state: "StepState", program.ring: "token ring"}.get(v.name, "weights window") + raise ValueError(f"emit_program: the host input {v.name!r} is named after the program's {own}; a host " + "input binds the session's buffer of its name") + if v.is_host: # the session's buffer: the value's bytes exactly + program.buffers[v.name] = host[v.name] = BufferSpec(_value_bytes(v, t), None, "host") + elif fld not in layout.offsets: # not StepState-backed: a host-written arena buffer program.buffers[v.name] = BufferSpec(max(_value_bytes(v, t), 16), None, "arena") elif not v.is_source: nbytes = _value_bytes(v, t) @@ -1513,6 +1525,16 @@ def emit_program(g: Graph, *, pack: Union[PackFile, BasaltSource, Sequence[Union writes=[1, 2]) elif tail is not None: raise ValueError(f"emit_program: unknown tail {tail!r}") + # a buffer added after the input loop under a host input's name (a params record, a scratch arena, a log, StepState, + # the ring) replaced its spec, and the ops bind that buffer in place of the session's + for name, own in host.items(): + spec = program.buffers[name] + if spec is not own: + what = {ACCEPT_LOG: "accept log", CONF_LOG: "confidence log"}.get(name) or { + "params": "params record", "arena": "scratch arena", "weights": "weights window", "step_state": "StepState", + "ring": "token ring"}.get(spec.role, f"{spec.role} buffer") + raise ValueError(f"emit_program: the program's {what} took the name of the host input {name!r}; a host input " + "binds the session's buffer of its name") # an arena value no dispatch binds is not allocated: the graph allots the attention's partial workspaces for the # two-dispatch kernels, and with v3 (core and merge in one) nothing reads or writes them — the 8B's part_o alone # is 8 MiB per layer at a 32K context diff --git a/monolith/compiler/emit_basalt.py b/monolith/compiler/emit_basalt.py index 50a22826..9131fd25 100644 --- a/monolith/compiler/emit_basalt.py +++ b/monolith/compiler/emit_basalt.py @@ -1,15 +1,17 @@ """The emitter's handlers for basalt's ops (``monolith/ops/basalt.py``), merged into ``emit.HANDLERS``. Each handler -emits one dispatch, except ``basalt_ple_block``, which emits basalt's per-row chain, 11 dispatches a row -(``monolith/ops/basalt_ple.py``), 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). +emits basalt's launches in its order (one dispatch, except the Q5_K head's second dispatches after it and +``basalt_ple_block``'s per-row chain, 11 dispatches a row, ``monolith/ops/basalt_ple.py``) with the macros, grid, +threadgroup, params and scratch sizes 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). A follow-up dispatch reads +what the one before it wrote, which ``writes`` declares, so the barrier pass orders it. """ # 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, src/kernels/cuda/iq_kernels.cu:2450-2455 and -# src/kernels/cuda/native_gr_postops.cu:75-82; the n-gram block's launches, +# src/kernels/cuda/native_bf16.cu:139-171, src/kernels/cuda/iq_kernels.cu:2450-2455, +# src/kernels/cuda/native_gr_postops.cu:75-82 and src/kernels/cuda/q5k_head.cu:372-374, :406-408, :411-412 and +# :516-518, and the Q5_K head's per-column mask from src/core/mtp.cpp:1024-1025; the n-gram block's launches, # their order and its refusals from src/kernels/cuda/ple.cu:204-212 and :228-356, # src/kernels/cuda/native_ple_postops.cu:317-361, src/kernels/cuda/native_gr_norm.cu:78-100, # src/kernels/cuda/elementwise.cu:277-287, src/kernels/cuda/verify_kernels.cu:1086-1090 and @@ -347,7 +349,140 @@ def _ple_commit(ctx: _Ctx, op: Op) -> None: ctx.add(k, bindings, (groups, 1, 1), (threads, 1, 1), f"{op.kind}:restore", writes=[0]) +# ---- the Q5_K head (kernels/common/basalt_q5k_head.metal) ----------------------------------------------------------- + +Q5_K = GGML_IDS["q5_k"] +Q5K_BLOCK = GGML_TYPES[Q5_K][2] # bytes of a 256-value block +TOP1_N_IN = 2560 # the top-1s' rows: q5k_head_top1 refuses others, the 2-bit copy holds 40 words + + +def _q5k_rows(ctx: _Ctx, op: Op, w: Value, n: int) -> int: + """n_in of the Q5_K rows ``w`` an op reads the first ``n`` of: a ``q5_k`` weight ``[rows, n_in]`` (a ``.basalt`` + tensor, the verify head's ``output.weight``) or a host input ``U8 [rows, n_in / 256 * 176]``, the rows as stored + (the drafter's gathered head rows, which the session writes at load and at every flush). basalt passes such a + pointer with a row count: its tier 0 reads the leading n_tier1_ of the gathered rows (mtp.cpp:1006, :1016-1021).""" + if w.is_input: + shape = ctx.shape(w) + if not w.is_host: + raise ValueError(f"{op.kind}: {w.name!r} is an input each program allocates; Q5_K rows that are no file " + "tensor are the session's gathered head rows, a host input") + if w.dtype != DType.U8 or len(shape) != 2 or shape[1] % Q5K_BLOCK: # no blocks: each op refuses n_in 0 + raise ValueError(f"{op.kind}: the host rows {w.name!r} are {w.dtype} {list(shape)}, not u8 [rows, whole " + f"{Q5K_BLOCK}-byte Q5_K blocks] (the rows as stored)") + rows, n_in = shape[0], shape[1] // Q5K_BLOCK * 256 + else: + _, rows, n_in = _weight(ctx, op, w, (Q5_K,)) + if rows < n: + raise ValueError(f"{op.kind}: {w.name!r} holds {rows} rows; the op reads {n}") + return n_in + + +def _map(ctx: _Ctx, op: Op, m: Value, n: int) -> None: + """The map: an id per row read, negative for a row that holds no token (basalt's ``dvocab_``).""" + shape = ctx.shape(m) + if m.dtype != DType.I32 or len(shape) != 1 or shape[0] < n: + raise ValueError(f"{op.kind}: the map {m.name!r} is {m.dtype} {list(shape)}; it maps the {n} rows read, " + f"i32 [>= {n}]") + + +def _q5k_head(ctx: _Ctx, op: Op) -> None: + t = _columns(ctx, op) + xq, w, *mp = op.inputs + (y,) = op.outputs + if len(mp) > 1: + raise ValueError(f"basalt_q5k_head: {len(op.inputs)} inputs; it takes (xq, rows[, map])") + n_out = ctx.shape(y)[-1] + n_in = _q5k_rows(ctx, op, w, n_out) + if mp: + _map(ctx, op, mp[0], n_out) + macros = kernels.basalt_q5k_head_macros(n_in, t) # q5k_head_supported (q5k_head.cu:412) + _expect(ctx, op, xq, (t, n_in // 32 * kernels.Q8_1_BLOCK_BYTES), DType.U8, "q8_1 rows of the rows' width") + _expect(ctx, op, y, (t, n_out), DType.F32, "contiguous columns of the logits") + src = kernels.basalt_q5k_head_source() + prm = ctx.params("basalt_q5k_head", kernels.basalt_q5k_head_params(n_in, n_out)) + head = [_bind(ctx, op, 0, w, 2), _bind(ctx, op, 1, xq, 4), _bind(ctx, op, 2, y, 4), (3, prm, 0)] + ctx.add(ctx.kernel("basalt_q5k_head", src, "basalt_q5k_head", macros), head, + (kernels.basalt_q5k_head_grid(n_out), 1, 1), (kernels.Q5K_HEAD_THREADS, 1, 1), f"{op.kind}:{w.name}", + writes=[2]) + if mp: # basalt masks each column's logits (mtp.cpp:1024-1025) + km = ctx.kernel("basalt_q5k_head", src, "basalt_q5k_head_mask_unmapped", macros) + grid, threads = kernels.basalt_q5k_mask_grid(n_out) + _, yb, yo = head[2] + for j in range(t): + ctx.add(km, [(0, yb, yo + 4 * n_out * j), _bind(ctx, op, 1, mp[0], 4), (2, prm, 0)], (grid, 1, 1), + (threads, 1, 1), f"{op.kind}.mask:{w.name}", writes=[0]) + + +def _q5k_top1(ctx: _Ctx, op: Op) -> None: + _columns(ctx, op) + xq, w, *mp = op.inputs + y, tok, prob = op.outputs + if len(mp) > 1: + raise ValueError(f"basalt_q5k_top1: {len(op.inputs)} inputs; it takes (xq, rows[, map])") + n_out = ctx.shape(y)[-1] + n_in = _q5k_rows(ctx, op, w, n_out) + if n_in != TOP1_N_IN: # q5k_head.cu:374 + raise ValueError(f"basalt_q5k_top1: rows of {n_in} values; q5k_head_top1 takes {TOP1_N_IN}") + if mp: + _map(ctx, op, mp[0], n_out) + _expect(ctx, op, xq, (1, TOP1_N_IN // 32 * kernels.Q8_1_BLOCK_BYTES), DType.U8, + "one q8_1 column: basalt runs the top-1 at T = 1, mtp.cpp:1016") + _expect(ctx, op, y, (1, n_out), DType.F32, "the logits of one column") + _expect(ctx, op, tok, (1,), DType.I32, "the best row's id") + _expect(ctx, op, prob, (1,), DType.F32, "its probability") + src, macros = kernels.basalt_q5k_head_source(), kernels.basalt_q5k_head_macros(TOP1_N_IN, 1) + grid = kernels.basalt_q5k_head_grid(n_out) # once: the merge combines this many partials in basalt's order + prm = ctx.params("basalt_q5k_top1", kernels.basalt_q5k_head_params(TOP1_N_IN, n_out, bool(mp), grid)) + part = ctx.scratch("basalt_q5k_top1.part", kernels.basalt_q5k_top1_part_bytes(grid)) + _, mb, mo = _bind(ctx, op, 3, mp[0], 4) if mp else (3, ctx.scratch("basalt_q5k_top1.no_map", 4), 0) + ctx.add(ctx.kernel("basalt_q5k_head", src, "basalt_q5k_head_top1", macros), + [_bind(ctx, op, 0, w, 2), _bind(ctx, op, 1, xq, 4), _bind(ctx, op, 2, y, 4), (3, mb, mo), (4, part, 0), + (5, prm, 0)], (grid, 1, 1), (kernels.Q5K_HEAD_THREADS, 1, 1), f"{op.kind}:{w.name}", writes=[2, 4]) + ctx.add(ctx.kernel("basalt_q5k_head", src, "basalt_q5k_head_top1_merge", macros), + [(0, part, 0), (1, mb, mo), _bind(ctx, op, 2, tok, 4), _bind(ctx, op, 3, prob, 4), (4, prm, 0)], + (1, 1, 1), (kernels.Q5K_HEAD_THREADS, 1, 1), f"{op.kind}.merge:{w.name}", writes=[2, 3]) + + +def _q5k_proxy_top1(ctx: _Ctx, op: Op) -> None: + _columns(ctx, op) + xq, proxy, rows, *mp = op.inputs + tok, prob = op.outputs + if len(mp) != 1: # q5k_head.cu:518 refuses a call without the map + raise ValueError(f"basalt_q5k_proxy_top1: {len(op.inputs)} inputs; it takes (xq, proxy, rows, map), and basalt " + "refuses it without the map") + n_rows, n_cap = op.attrs.get("n_rows"), op.attrs.get("n_cap") + if not (isinstance(n_rows, int) and isinstance(n_cap, int)): + raise ValueError(f"basalt_q5k_proxy_top1: attrs n_rows and n_cap must be ints, got {n_rows!r} and {n_cap!r}") + params = kernels.basalt_q5k_proxy_params(n_cap, n_rows=n_rows) # 1 <= n_rows <= n_cap (q5k_head.cu:518) + if not proxy.is_host: + raise ValueError(f"basalt_q5k_proxy_top1: the 2-bit copy {proxy.name!r} is not a host input; the session packs " + "it at load and at every flush") + _expect(ctx, op, proxy, (kernels.basalt_q5k_proxy_bytes(n_cap),), DType.U8, "the 2-bit copy of n_cap rows") + n_in = _q5k_rows(ctx, op, rows, n_rows) + if n_in != TOP1_N_IN: + raise ValueError(f"basalt_q5k_proxy_top1: rows of {n_in} values; the 2-bit copy holds rows of {TOP1_N_IN}") + _map(ctx, op, mp[0], n_rows) + _expect(ctx, op, xq, (1, TOP1_N_IN // 32 * kernels.Q8_1_BLOCK_BYTES), DType.U8, + "one q8_1 column: basalt runs the top-1 at T = 1, mtp.cpp:1009") + _expect(ctx, op, tok, (1,), DType.I32, "the best row's id") + _expect(ctx, op, prob, (1,), DType.F32, "its probability") + src = kernels.basalt_q5k_head_source() + prm = ctx.params("basalt_q5k_proxy_top1", params) + scratch = ctx.scratch("basalt_q5k_proxy.scratch", kernels.basalt_q5k_proxy_scratch_bytes(n_cap)) + xb, (_, mb, mo) = _bind(ctx, op, 1, xq, 4), _bind(ctx, op, 2, mp[0], 4) + ctx.add(ctx.kernel("basalt_q5k_head", src, "basalt_q5k_proxy_score", {}), + [_bind(ctx, op, 0, proxy, 16), xb, (2, mb, mo), (3, scratch, 0), (4, prm, 0)], + (kernels.basalt_q5k_proxy_tiles(n_rows), 1, 1), (kernels.PX_THREADS_SCORE, 1, 1), + f"{op.kind}:{proxy.name}", writes=[3]) + ctx.add(ctx.kernel("basalt_q5k_head", src, "basalt_q5k_proxy_final", {}), + [_bind(ctx, op, 0, rows, 2), xb, (2, mb, mo), (3, scratch, 0), _bind(ctx, op, 4, tok, 4), + _bind(ctx, op, 5, prob, 4), (6, prm, 0)], (1, 1, 1), (kernels.PX_THREADS_FINAL, 1, 1), + f"{op.kind}.final:{rows.name}", writes=[4, 5]) + + 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, "basalt_gr_post": _gr_post, "basalt_ple_block": _ple_block, - "basalt_ple_commit": _ple_commit} + "basalt_ple_commit": _ple_commit, + "basalt_q5k_head": _q5k_head, "basalt_q5k_top1": _q5k_top1, + "basalt_q5k_proxy_top1": _q5k_proxy_top1} diff --git a/monolith/core/ir.py b/monolith/core/ir.py index d60d6045..00b1706a 100644 --- a/monolith/core/ir.py +++ b/monolith/core/ir.py @@ -52,6 +52,7 @@ class Value: producer: Optional["Op"] = None consumers: List["Op"] = field(default_factory=list) is_input: bool = False + is_host: bool = False # an input the session allocates and passes to every program that binds it (role "host") is_weight: bool = False is_state: bool = False # persistent per-sequence buffer (KV cache, recurrent state): read and updated in place is_const: bool = False # a constant table or aux tensor from the pack (RoPE tables, norm weights, A_log …) @@ -125,9 +126,16 @@ def value(self, name: str, shape: Sequence[Dim], dtype: DType, *, format: Option self.symbols.update(d for d in v.shape if isinstance(d, Sym)) return v - def input(self, name: str, shape: Sequence[Dim], dtype: DType) -> Value: + def input(self, name: str, shape: Sequence[Dim], dtype: DType, *, host: bool = False) -> Value: + """A value the host writes before a step. ``host``: the session allocates its buffer (at least the value's + bytes) and passes the same one to every program that binds it (data it derives and updates outside the + programs, such as a drafter's gathered head rows); the emitter refuses one named after a StepState field, + which an input of that name binds, or after one of the program's own buffers (StepState, the token ring, a + weights window, a params record, a scratch arena, the accept or confidence log). Otherwise each program + allocates its own.""" v = self.value(name, shape, dtype, scoped=False) v.is_input = True + v.is_host = host return v def weight(self, name: str, shape: Sequence[int], format: str) -> Value: diff --git a/monolith/kernels.py b/monolith/kernels.py index 8147a504..7b07d2af 100644 --- a/monolith/kernels.py +++ b/monolith/kernels.py @@ -620,7 +620,7 @@ def basalt_dense_tc_pair_grid(n_out0: int, n_out1: int) -> Tuple[int, int]: # ---- 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 +# adapted from basalt (jesdga95/basalt) src/kernels/cuda/q5k_head.cu:337-386, :406-408, :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 @@ -670,6 +670,18 @@ def basalt_q5k_head_params(n_in: int, n_out: int, has_map: bool = False, n_block return struct.pack(" Tuple[int, int]: + """``q5k_head_mask_unmapped``'s launch (q5k_head.cu:406-408): ceil(n_out / 256) threadgroups of 256, a row each.""" + return -(-n_out // 256), 256 + + +def basalt_q5k_top1_part_bytes(grid: int) -> int: + """The top-1's partials, which its merge reads: (max, row, sum) per threadgroup of ``grid``, 12 bytes each. basalt + keeps them in ``q5k_head_top1_scratch_bytes()`` (q5k_head.cu:370), room for 4096 and its counter; the port's merge + is a dispatch of its own and needs no counter.""" + return 12 * grid + + # basalt's 2-bit proxy of the head's rows (head_proxy.cuh:17-28; q5k_head.cu:500-535) PX_THREADS_PACK = 128 # q5k_proxy_pack: one thread per 32-weight group PX_THREADS_SCORE = 128 # px::score_kernel: four SIMD-groups per tile of 32 rows diff --git a/monolith/ops/basalt.py b/monolith/ops/basalt.py index 09e54a2e..1ef76b86 100644 --- a/monolith/ops/basalt.py +++ b/monolith/ops/basalt.py @@ -1,8 +1,9 @@ -"""basalt's single-dispatch GEMVs, q8_1 quantizers (OI-013) and hyper-connection write (OI-005; -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. +"""basalt's GEMVs, q8_1 quantizers, Q5_K head (OI-013) and hyper-connection write (OI-005; docs/design/flash-next.md): +one op kind per basalt host launcher, whose kernels and grids follow from the shape alone, as the launcher picks them. +Each op is the launcher's dispatches of merged kernels (``kernels/common/basalt_*.metal``) in its order: one for a +GEMV, a quantizer or the hyper-connection write, two or more for the Q5_K head's (below); the emitter +(``compiler/emit_basalt.py``) takes their macros, grids, threadgroups, params and scratch sizes 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 @@ -47,6 +48,43 @@ at 4 (``check_pointer``, ``native_gr_postops.cu:75-78``, called at ``:110``). 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. + +The Q5_K head (``q5k_head.cu``). Its rows are Q5_K rows as stored: a ``q5_k`` weight ``[rows, n_in]`` (a ``.basalt`` +tensor: the verify head's ``output.weight``) or a host input ``u8 [rows, n_in / 256 * 176]`` (``Graph.input(..., +host=True)``: the drafter's head rows, gathered for its draft vocabulary). An op reads the first n_out (n_rows) of them, +as basalt passes a pointer and a row count: its draft head's tier 0 reads the leading ``n_tier1_`` of the gathered +rows, tier 1 all of them (``mtp.cpp:1006``). A map is an i32 value of at least that many ids, negative for a row that +holds no token (basalt's ``dvocab_``). The session rewrites the map with the rows (at load, at every flush, and at a +request's start), so it passes it as a host input as well; the kernels read it alike from any buffer, so an op does +not require that. + +* ``basalt_q5k_head`` (``q5k_head_mmvq``): ``(xq [T, n_in / 32 * 36], rows[, map])`` → ``y [T, n_out] F32``, the + logits of rows 0 .. n_out - 1, n_out the output's width; n_in a multiple of 256 of at most 64 blocks and T 1 .. 8 + (``q5k_head_supported``). With a map, ``q5k_head_mask_unmapped`` follows on each column, as basalt masks the draft + head's logits (``mtp.cpp:1024-1025``): a row whose id is negative becomes -inf. basalt masks only when the draft + vocabulary has context rows (``n_xcap_ > 0``), whose ids are its only negative ones, so a lowering passes the head + the map exactly then. +* ``basalt_q5k_top1`` (``q5k_head_top1``): ``(xq [1, 2880], rows[, map])`` → ``(y [1, n_out] F32, id [1] I32, + prob [1] F32)``: n_in 2560 and one column, as basalt calls it (``q5k_head.cu:374``; ``mtp.cpp:1016``). The first + dispatch writes the logits and each threadgroup's partials, the merge the best row (its id through the map) and its + probability. Both take the grid basalt's rule gives on its 170 multiprocessors (``basalt_q5k_head_grid``), the + merge as its partial count: the probability sums in that order. Without a map a dummy buffer fills the map's slot. +* ``basalt_q5k_proxy_top1`` (``q5k_proxy_top1``), attrs ``n_rows`` and ``n_cap``: ``(xq [1, 2880], proxy, rows, map)`` + → ``(id [1] I32, prob [1] F32)``: the score over the first n_rows rows (1 <= n_rows <= n_cap) of the 2-bit copy, a + host input ``u8 [q5k_proxy_bytes(n_cap)]``, then the final dispatch, which rescores the candidates on the Q5_K rows. + n_in 2560 and one column (``mtp.cpp:1009-1014``); the map is required, as basalt's launcher requires it + (``q5k_head.cu:518``). + +The 2-bit copy's pack (``q5k_proxy_pack``) is no op: basalt runs it outside its graphs, at load over the copy's rows +and again at every flush over the context rows just gathered (``mtp.cpp:680``, ``:1439-1452``). The session issues it +as a direct dispatch and lets it complete before it submits a program that scores the copy; ``gather_rows``, the +id-map copy and ``begin_request``'s reset are the session's too. basalt captures the draft head per tier and width +(``round_exec_[tier][T]``), so each tier is a program of its own at each width, its n_out or n_rows compiled in, every +one binding the same host buffers. A follow-up dispatch (each mask, the merge, the final) reads what the dispatch +before it wrote, which its ``writes`` record declares, so the barrier pass gives it ``barrier_before``. + +Alignment, the port's own (basalt's head launchers check only for null pointers): 2 bytes for the Q5_K rows (16-bit +loads), 16 for the 2-bit copy (read as uint4), 4 for every other binding. """ from ..core.ir import OpClass @@ -59,3 +97,9 @@ BASALT_DENSE_TC_PAIR = register_op(OpDef("basalt_dense_tc_pair", OpClass.MAP, "rows") .bind("*", KernelBinding("basalt_dense_tc_pair"))) BASALT_GR_POST = register_op(OpDef("basalt_gr_post", OpClass.MAP, "rows").bind("*", KernelBinding("basalt_gr_post"))) +BASALT_Q5K_HEAD = register_op(OpDef("basalt_q5k_head", OpClass.MAP, "rows") # basalt_q5k_head (+ mask_unmapped) + .bind("*", KernelBinding("basalt_q5k_head"))) +BASALT_Q5K_TOP1 = register_op(OpDef("basalt_q5k_top1", OpClass.REDUCE, "rows") # basalt_q5k_head_top1 + _merge + .bind("*", KernelBinding("basalt_q5k_top1"))) +BASALT_Q5K_PROXY_TOP1 = register_op(OpDef("basalt_q5k_proxy_top1", OpClass.REDUCE, "rows") # proxy_score + _final + .bind("*", KernelBinding("basalt_q5k_proxy_top1"))) diff --git a/tests/contract/test_basalt_q5k_ops.py b/tests/contract/test_basalt_q5k_ops.py new file mode 100644 index 00000000..b17b6967 --- /dev/null +++ b/tests/contract/test_basalt_q5k_ops.py @@ -0,0 +1,541 @@ +"""basalt's Q5_K head ops (monolith/ops/basalt.py: ``basalt_q5k_head``, ``basalt_q5k_top1``, ``basalt_q5k_proxy_top1``) +as compiler/emit_basalt.py emits them over a synthetic .basalt file and the session's host inputs: every dispatch +(function, macros, grid, threadgroup, bindings, params and written slots) against monolith/kernels.py's builders, the +follow-up dispatches behind their barriers in the finished program, the merge's partial count and the scratch sizes, +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_q5k_ops_program.py.""" + +import struct + +import pytest + +from monolith import kernels +from monolith.compiler.coverage import check_coverage +from monolith.compiler.emit import ACCEPT_LOG, CONF_LOG, basalt_windows +from monolith.core import DType, Graph +from monolith.core.ir import BlockDomain, OpClass +from monolith.core.shapes import T +from monolith.formats.gguf import ggml_row_bytes +from monolith.ops import OPS +from monolith.packs.basalt import BasaltSource +from tests.contract.test_basalt_ops import PROFILE, emit, op, pack, spliced, weight, write_file + +F32, I32, U8 = DType.F32, DType.I32, DType.U8 +KINDS = ("basalt_q5k_head", "basalt_q5k_top1", "basalt_q5k_proxy_top1") +QCOL, ROW = 2880, 1760 # bytes of a 2560-value q8_1 column and of a 2560-value Q5_K row +N_VOCAB, N_DVOCAB, N_CAP = 4000, 3600, 3064 # the head's rows; the gathered rows (tier 1); the copy's (tier 0) +GGUF = {"head": (13, N_VOCAB, 2560), "head2048": (13, 64, 2048), "q4k": (12, 64, 2560)} +FOLLOW_UPS = ("basalt_q5k_head_mask_unmapped", "basalt_q5k_head_top1_merge", "basalt_q5k_proxy_final") + + +@pytest.fixture(scope="module") +def src(tmp_path_factory): + """The tensors as zeros (the emitter never reads them), and a BF16 row the file's dense index needs.""" + gguf = {n: (t, o, i, bytes(o * ggml_row_bytes(t, i))) for n, (t, o, i) in GGUF.items()} + return BasaltSource(write_file(tmp_path_factory.mktemp("q5k") / "q5k.basalt", gguf, {"pad": (1, 64, bytes(128))})) + + +# ---- graph builders (the GPU test uses them too) ------------------------------------------------------------------- + +def draft_inputs(g, rows=N_DVOCAB, cap=N_CAP): + """The session's host inputs: the gathered head rows, their map and the 2-bit copy of the first ``cap`` rows.""" + return (g.input("dhead", (rows, ROW), U8, host=True), g.input("dvocab", (rows,), I32, host=True), + g.input("proxy", (kernels.basalt_q5k_proxy_bytes(cap),), U8, host=True)) + + +def head(g, name, xq, rows, *mp, width=None, dtype=F32): + """``basalt_q5k_head`` of the q8_1 columns ``xq`` by the first ``width`` (default: all) of ``rows``.""" + y = g.value(name, (xq.shape[0], rows.shape[0] if width is None else width), dtype) + op(g, "basalt_q5k_head", [xq, rows, *mp], [y]) + return y + + +def top1(g, name, x1, rows, *mp, width=None, dtypes=(F32, I32, F32)): + """``basalt_q5k_top1`` of the q8_1 column ``x1``: ``name.y`` (the logits of one column), ``name.id``, ``name.p``.""" + shapes = ((1, rows.shape[0] if width is None else width), (1,), (1,)) + outs = [g.value(f"{name}.{s}", sh, dt) for s, sh, dt in zip(("y", "id", "p"), shapes, dtypes)] + op(g, "basalt_q5k_top1", [x1, rows, *mp], outs) + return outs + + +def proxy_top1(g, name, x1, proxy, rows, *mp, n_rows=N_CAP, n_cap=N_CAP, dtypes=(I32, F32)): + """``basalt_q5k_proxy_top1`` over the first ``n_rows`` rows of the copy ``proxy`` (``n_cap`` rows).""" + outs = [g.value(f"{name}.{s}", (1,), dt) for s, dt in zip(("id", "p"), dtypes)] + attrs = {k: v for k, v in (("n_rows", n_rows), ("n_cap", n_cap)) if v is not None} + op(g, "basalt_q5k_proxy_top1", [x1, proxy, rows, *mp], outs, **attrs) + return outs + + +def all_ops(g, src): + """Every kind as basalt calls it: the verify head over the file's output rows (T columns); the draft head over the + first N_CAP gathered rows with the map (tier 0's width, masked); the top-1 over the file's rows without a map and + over the gathered rows with it; the proxy top-1 over the copy of the first N_CAP rows (tier 0).""" + xq, x1 = g.input("xq", (T, QCOL), U8), g.input("x1", (1, QCOL), U8) + w = weight(g, "gguf/head", src) + rows, mp, proxy = draft_inputs(g) + head(g, "y.head", xq, w) + head(g, "y.masked", xq, rows, mp, width=N_CAP) + top1(g, "top1", x1, w) + top1(g, "top1m", x1, rows, mp) + proxy_top1(g, "proxy", x1, proxy, rows, mp) + + +# ---- registration, each dispatch against the builders, barriers, partial counts, scratch ----------------------------- + +def test_registered_and_covered(src): + for kind, klass in zip(KINDS, (OpClass.MAP, OpClass.REDUCE, OpClass.REDUCE)): + od = OPS.get(kind) + assert od.klass == klass 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 described(prog): + """Each dispatch as (function, macros, grid, threadgroup, bindings, written slots), a params record or workspace + named by its first appearance (``params``, ``ws``), and what those hold: a record's bytes, a workspace's + size. Every kernel is the Q5_K head's source.""" + tags = {} + + def bind(slot, name, off): + spec = prog.buffers[name] + if spec.role == "params" or name.startswith("ws."): + name = tags.setdefault(name, f"{'params' if spec.role == 'params' else 'ws'}{len(tags)}") + return slot, name, off + + ops = [] + for o in prog.ops: + k = prog.kernels[o.kernel] + assert k.source == spliced(kernels.basalt_q5k_head_source()) and o.threadgroup_memory == [], o.name + ops.append((k.function, k.macros, o.grid, o.threadgroup, [bind(*b) for b in o.bindings], o.meta["writes"])) + held = {tag: prog.buffers[n].init if prog.buffers[n].role == "params" else prog.buffers[n].nbytes + for n, tag in tags.items()} + return ops, held + + +@pytest.mark.parametrize("t", range(1, 9)) +def test_dispatches_are_the_builders(src, t): + """``all_ops`` at T = t: basalt's launches in its order, each with the builders' macros, grid, threadgroup and + params; the file's rows bound at the window and offset the planner gives them, the session's at 0 of their own + buffers; the masked head's mask once per column, at that column's logits; one params record per op, shared by its + dispatches, and one partials workspace between the top-1 and its merge, which a dummy buffer joins in the map's slot + when there is no map; no StepState and no threadgroup memory.""" + g = Graph("step") + all_ops(g, src) + ops, held = described(emit(g, src, t)) + w = basalt_windows(src, g.values.values(), t)[1]["gguf/head"] + nc, n1, tg = {"NC": str(t)}, {"NC": "1"}, (kernels.Q5K_HEAD_THREADS, 1, 1) + gv, gc, gd = (kernels.basalt_q5k_head_grid(n) for n in (N_VOCAB, N_CAP, N_DVOCAB)) + mg, mt = kernels.basalt_q5k_mask_grid(N_CAP) + assert ops == [ + ("basalt_q5k_head", nc, (gv, 1, 1), tg, [(0, *w), (1, "xq", 0), (2, "y.head", 0), (3, "params0", 0)], [2]), + ("basalt_q5k_head", nc, (gc, 1, 1), tg, [(0, "dhead", 0), (1, "xq", 0), (2, "y.masked", 0), + (3, "params1", 0)], [2]), + *[("basalt_q5k_head_mask_unmapped", nc, (mg, 1, 1), (mt, 1, 1), + [(0, "y.masked", 4 * N_CAP * j), (1, "dvocab", 0), (2, "params1", 0)], [0]) for j in range(t)], + ("basalt_q5k_head_top1", n1, (gv, 1, 1), tg, [(0, *w), (1, "x1", 0), (2, "top1.y", 0), (3, "ws2", 0), + (4, "ws3", 0), (5, "params4", 0)], [2, 4]), + ("basalt_q5k_head_top1_merge", n1, (1, 1, 1), tg, [(0, "ws3", 0), (1, "ws2", 0), (2, "top1.id", 0), + (3, "top1.p", 0), (4, "params4", 0)], [2, 3]), + ("basalt_q5k_head_top1", n1, (gd, 1, 1), tg, [(0, "dhead", 0), (1, "x1", 0), (2, "top1m.y", 0), + (3, "dvocab", 0), (4, "ws5", 0), (5, "params6", 0)], [2, 4]), + ("basalt_q5k_head_top1_merge", n1, (1, 1, 1), tg, [(0, "ws5", 0), (1, "dvocab", 0), (2, "top1m.id", 0), + (3, "top1m.p", 0), (4, "params6", 0)], [2, 3]), + ("basalt_q5k_proxy_score", {}, (kernels.basalt_q5k_proxy_tiles(N_CAP), 1, 1), (kernels.PX_THREADS_SCORE, 1, 1), + [(0, "proxy", 0), (1, "x1", 0), (2, "dvocab", 0), (3, "ws7", 0), (4, "params8", 0)], [3]), + ("basalt_q5k_proxy_final", {}, (1, 1, 1), (kernels.PX_THREADS_FINAL, 1, 1), + [(0, "dhead", 0), (1, "x1", 0), (2, "dvocab", 0), (3, "ws7", 0), (4, "proxy.id", 0), (5, "proxy.p", 0), + (6, "params8", 0)], [4, 5])] + assert held == {"params0": kernels.basalt_q5k_head_params(2560, N_VOCAB), + "params1": kernels.basalt_q5k_head_params(2560, N_CAP), + "ws2": 16, # the dummy map: 4 bytes, the floor 16 + "ws3": kernels.basalt_q5k_top1_part_bytes(gv), + "params4": kernels.basalt_q5k_head_params(2560, N_VOCAB, False, gv), + "ws5": kernels.basalt_q5k_top1_part_bytes(gd), + "params6": kernels.basalt_q5k_head_params(2560, N_DVOCAB, True, gd), + "ws7": kernels.basalt_q5k_proxy_scratch_bytes(N_CAP), + "params8": kernels.basalt_q5k_proxy_params(N_CAP, n_rows=N_CAP)} + + +def test_host_inputs_are_the_sessions(src): + """The gathered rows, their map and the 2-bit copy are host buffers (the session allocates them and passes the same + ones to every program); an input not declared host stays the program's own.""" + g = Graph("step") + all_ops(g, src) + prog = emit(g, src, 1) + assert {n: prog.buffers[n].role for n in ("dhead", "dvocab", "proxy", "xq", "x1")} == { + "dhead": "host", "dvocab": "host", "proxy": "host", "xq": "arena", "x1": "arena"} + assert prog.buffers["proxy"].nbytes == kernels.basalt_q5k_proxy_bytes(N_CAP) + + +def test_host_inputs_are_sized_exactly(src): + """A host buffer is its value's bytes, a one-id map 4 (basalt allocates ``map.size() * 4``, mtp.cpp:656), so Engine + takes the session's exact allocation; the program's own buffers keep their 16-byte floor.""" + g = Graph("step") + x1, (rows, mp, proxy) = g.input("x1", (1, QCOL), U8), draft_inputs(g, rows=1, cap=1) + proxy_top1(g, "p", x1, proxy, rows, mp, n_rows=1, n_cap=1) + prog = emit(g, src, 1) + assert {n: prog.buffers[n].nbytes for n in ("dhead", "dvocab", "proxy", "p.id")} == { + "dhead": ROW, "dvocab": 4, "proxy": kernels.basalt_q5k_proxy_bytes(1), "p.id": 16} + + +@pytest.mark.parametrize("t", (1, 3, 8)) +def test_follow_ups_wait_for_their_first_dispatch(src, t): + """In the finished program (place_barriers, then the backend's finalize) under ``barriers="minimal"``, each mask, + merge and final carries ``barrier_before``: it reads what the dispatch before it wrote. The first dispatches here + read only host buffers, inputs and windows, so the pass lets the second and later ones run beside the first.""" + g = Graph("step") + all_ops(g, src) + prog = emit(g, src, t, barriers="minimal") + fn = [prog.kernels[o.kernel].function for o in prog.ops] + assert fn.count("basalt_q5k_head_mask_unmapped") == t + assert [o.barrier_before for o, f in zip(prog.ops, fn) if f in FOLLOW_UPS] == [True] * (t + 3) + assert [o.barrier_before for o, f in zip(prog.ops, fn) if f not in FOLLOW_UPS] == [True, False, False, False, + False] + + +@pytest.mark.parametrize("width", [N_VOCAB, 2720, 1000, 8]) +def test_merge_counts_the_first_grid(src, width): + """The merge's params give n_blocks = the first dispatch's grid, which is basalt's rule at its 170 multiprocessors: + the cap of 340 threadgroups from 2,720 rows, fewer below (125 at 1,000, one at 8); with and without the map.""" + g = Graph("step") + x1, w = g.input("x1", (1, QCOL), U8), weight(g, "gguf/head", src) + rows, mp, _ = draft_inputs(g, rows=N_VOCAB) + top1(g, "a", x1, w, width=width) + top1(g, "b", x1, rows, mp, width=width) + prog = emit(g, src, 1) + firsts = [o for o in prog.ops if prog.kernels[o.kernel].function == "basalt_q5k_head_top1"] + merges = [o for o in prog.ops if prog.kernels[o.kernel].function == "basalt_q5k_head_top1_merge"] + assert len(firsts) == len(merges) == 2 + want = kernels.basalt_q5k_head_grid(width) + assert want == {N_VOCAB: 340, 2720: 340, 1000: 125, 8: 1}[width] + for first, merge in zip(firsts, merges): + n_in, n_out, has_map, n_blocks = struct.unpack(" 16 + assert prog.buffers[score.bindings[3][1]].nbytes == kernels.basalt_q5k_proxy_scratch_bytes(n_cap) > 16 + assert score.grid == (kernels.basalt_q5k_proxy_tiles(n_rows), 1, 1) + + +# ---- refusals: each case's valid input emits, and the same input with its one defect is refused by its own check --- + +def _dynamic(kind): + def build(g, src, bad, tmp): + x1, w = g.input("x1", (1, QCOL), U8), weight(g, "gguf/head", src) + rows, mp, proxy = draft_inputs(g) + {"basalt_q5k_head": lambda: head(g, "y", x1, w), "basalt_q5k_top1": lambda: top1(g, "y", x1, w), + "basalt_q5k_proxy_top1": lambda: proxy_top1(g, "y", x1, proxy, rows, mp)}[kind]() + return {"dynamic_t": bad} + return build + + +def _arity(kind): + """An extra input: a second map.""" + def build(g, src, bad, tmp): + x1, (rows, mp, proxy) = g.input("x1", (1, QCOL), U8), draft_inputs(g) + extra = [g.input("map2", (N_DVOCAB,), I32, host=True)] if bad else [] + {"basalt_q5k_head": lambda: head(g, "y", x1, rows, mp, *extra), + "basalt_q5k_top1": lambda: top1(g, "y", x1, rows, mp, *extra), + "basalt_q5k_proxy_top1": lambda: proxy_top1(g, "y", x1, proxy, rows, mp, *extra)}[kind]() + return {} + return build + + +def _rows_type(g, src, bad, tmp): + head(g, "y", g.input("x1", (1, QCOL), U8), weight(g, "gguf/q4k" if bad else "gguf/head", src), width=64) + return {} + + +def _rows_not_host(g, src, bad, tmp): + head(g, "y", g.input("x1", (1, QCOL), U8), g.input("dhead", (64, ROW), U8, host=not bad)) + return {} + + +def _host_rows(name="dhead", shape=(64, ROW), dtype=U8): + """The head over host rows ``dhead`` u8 [64, ROW], or (bad) the given name, shape or dtype.""" + def build(g, src, bad, tmp): + rows = g.input(name if bad else "dhead", shape if bad else (64, ROW), dtype if bad else U8, host=True) + head(g, "y", g.input("x1", (1, QCOL), U8), rows) + return {} + return build + + +def _host_rows_window(g, src, bad, tmp): + """The verify head over the file's rows beside the head over host rows ``dhead``, or (bad) host rows named after the + window the file's rows bind.""" + x1, w = g.input("x1", (1, QCOL), U8), weight(g, "gguf/head", src) + head(g, "y.v", x1, w) + rows = g.input(basalt_windows(src, [w])[1]["gguf/head"][0] if bad else "dhead", (64, ROW), U8, host=True) + head(g, "y", x1, rows) + return {} + + +def _top1_host_rows(name): + """The top-1 over host rows ``dhead`` and their map, or (bad) host rows named ``name``.""" + def build(g, src, bad, tmp): + rows = g.input(name if bad else "dhead", (64, ROW), U8, host=True) + top1(g, "y", g.input("x1", (1, QCOL), U8), rows, g.input("dvocab", (64,), I32, host=True)) + return {} + return build + + +def _host_rows_log(kind, log): + """The head over host rows ``dhead`` beside the round's ``kind`` (the accept scan, the verify select), which writes + the log ``log``, or (bad) host rows named ``log``.""" + def build(g, src, bad, tmp): + head(g, "y", g.input("x1", (1, QCOL), U8), g.input(log if bad else "dhead", (64, ROW), U8, host=True)) + g.op(kind, [g.input("ids", (1,), I32)], [g.value("out", (1,), DType.U32)], domain=BlockDomain("span", 1), + klass=OpClass.SERIAL, **({"gamma": 1} if kind == "verify_select" else {})) + return {} + return build + + +def _rows_held(kind): + """The op reads one row more than the rows hold (the head and the top-1: their logits' width; the proxy: n_rows, + within a copy that has room for it).""" + def build(g, src, bad, tmp): + x1, (rows, mp, proxy) = g.input("x1", (1, QCOL), U8), draft_inputs(g, cap=N_DVOCAB + 1) + n = N_DVOCAB + 1 if bad else N_DVOCAB + mp = g.input("map_long", (N_DVOCAB + 1,), I32, host=True) + {"basalt_q5k_head": lambda: head(g, "y", x1, rows, mp, width=n), + "basalt_q5k_top1": lambda: top1(g, "y", x1, rows, mp, width=n), + "basalt_q5k_proxy_top1": lambda: proxy_top1(g, "y", x1, proxy, rows, mp, n_rows=n, + n_cap=N_DVOCAB + 1)}[kind]() + return {} + return build + + +def _head_shape(good, bad): + """The head of ``good`` = (columns, blocks a row) over host rows of that width, or of ``bad``: q5k_head_supported's + rule (1 to 64 blocks, 1 to 8 columns, their staging within 96 KiB). Static counts, as the default t_max (8) allows + no T past 8.""" + def build(g, src, is_bad, tmp): + cols, blocks = bad if is_bad else good + head(g, "y", g.input("xq", (cols, blocks * 8 * kernels.Q8_1_BLOCK_BYTES), U8), + g.input("dhead", (64, blocks * 176), U8, host=True)) + return {} + return build + + +def _head_xq_width(g, src, bad, tmp): + head(g, "y", g.input("xq", (T, 2304 if bad else 2304 + 576), U8), weight(g, "gguf/head", src)) + return {} + + +def _head_logits(g, src, bad, tmp): + head(g, "y", g.input("xq", (T, QCOL), U8), weight(g, "gguf/head", src), dtype=DType.BF16 if bad else F32) + return {} + + +def _map_short(kind): + def build(g, src, bad, tmp): + x1, rows = g.input("x1", (1, QCOL), U8), g.input("dhead", (N_CAP, ROW), U8, host=True) + proxy = g.input("proxy", (kernels.basalt_q5k_proxy_bytes(N_CAP),), U8, host=True) + mp = g.input("dvocab", (N_CAP - 1 if bad else N_CAP,), I32, host=True) + {"basalt_q5k_head": lambda: head(g, "y", x1, rows, mp), + "basalt_q5k_top1": lambda: top1(g, "y", x1, rows, mp), + "basalt_q5k_proxy_top1": lambda: proxy_top1(g, "y", x1, proxy, rows, mp)}[kind]() + return {} + return build + + +def _head_map(shape=(N_DVOCAB,), dtype=I32): + """The head with the map i32 [N_DVOCAB], or (bad) of the given shape or dtype.""" + def build(g, src, bad, tmp): + mp = g.input("dvocab", shape if bad else (N_DVOCAB,), dtype if bad else I32, host=True) + head(g, "y", g.input("x1", (1, QCOL), U8), g.input("dhead", (N_DVOCAB, ROW), U8, host=True), mp) + return {} + return build + + +def _top1_n_in(kind): + """Rows of 2,048 values (a valid head shape) for the top-1s, which take 2,560 only.""" + def build(g, src, bad, tmp): + x1 = g.input("x1", (1, 2048 // 32 * 36 if bad else QCOL), U8) + if kind == "basalt_q5k_top1": + top1(g, "y", x1, weight(g, "gguf/head2048" if bad else "gguf/head", src), width=64) + else: + _, mp, proxy = draft_inputs(g, cap=64) + rows = g.input("rows", (64, 1408 if bad else ROW), U8, host=True) + proxy_top1(g, "y", x1, proxy, rows, mp, n_rows=64, n_cap=64) + return {} + return build + + +def _one_column(kind): + def build(g, src, bad, tmp): + x = g.input("x", (2 if bad else 1, QCOL), U8) + rows, mp, proxy = draft_inputs(g) + if kind == "basalt_q5k_top1": + top1(g, "y", x, weight(g, "gguf/head", src)) + else: + proxy_top1(g, "y", x, proxy, rows, mp) + return {} + return build + + +def _out_dtype(kind, which): + """Output ``which`` (0 the logits, 1 the id, 2 the probability; the proxy's: 1 and 2) of another dtype.""" + def build(g, src, bad, tmp): + x1, (rows, mp, proxy) = g.input("x1", (1, QCOL), U8), draft_inputs(g) + dts = [F32, I32, F32] + if bad: + dts[which] = {0: DType.BF16, 1: DType.U32, 2: DType.BF16}[which] + if kind == "basalt_q5k_top1": + top1(g, "y", x1, rows, mp, dtypes=dts) + else: + proxy_top1(g, "y", x1, proxy, rows, mp, dtypes=dts[1:]) + return {} + return build + + +def _proxy_map(g, src, bad, tmp): + x1, (rows, mp, proxy) = g.input("x1", (1, QCOL), U8), draft_inputs(g) + proxy_top1(g, "y", x1, proxy, rows, *([] if bad else [mp])) + return {} + + +def _proxy_attrs(attr): + def build(g, src, bad, tmp): + x1, (rows, mp, proxy) = g.input("x1", (1, QCOL), U8), draft_inputs(g) + proxy_top1(g, "y", x1, proxy, rows, mp, **{attr: None if bad else N_CAP}) + return {} + return build + + +def _proxy_rows_past_cap(g, src, bad, tmp): + """n_rows one past the copy's n_cap (the copy itself sized for n_cap: its size check holds).""" + x1, (rows, mp, proxy) = g.input("x1", (1, QCOL), U8), draft_inputs(g, cap=N_CAP - 1) + proxy_top1(g, "y", x1, proxy, rows, mp, n_rows=N_CAP if bad else N_CAP - 1, n_cap=N_CAP - 1) + return {} + + +def _proxy_not_host(g, src, bad, tmp): + x1, (rows, mp, _) = g.input("x1", (1, QCOL), U8), draft_inputs(g) + proxy = g.input("proxy2", (kernels.basalt_q5k_proxy_bytes(N_CAP),), U8, host=not bad) + proxy_top1(g, "y", x1, proxy, rows, mp) + return {} + + +def _proxy_size(g, src, bad, tmp): + """A copy of n_cap + 32 rows' bytes: one tile more, which would move the scales the kernels read.""" + x1, (rows, mp, _) = g.input("x1", (1, QCOL), U8), draft_inputs(g) + proxy = g.input("proxy2", (kernels.basalt_q5k_proxy_bytes(N_CAP + 32 if bad else N_CAP),), U8, host=True) + proxy_top1(g, "y", x1, proxy, rows, mp) + return {} + + +def _from_pack(kind, value, offset=16, extra=0): + """``kind`` over 64 rows (the proxy: n_rows = n_cap = 64) with the map, its ``value`` (``rows``: a q5_k weight; + ``xq``: the q8_1 column; ``map``) a pack entry at byte 16 holding exactly its bytes (valid), or at byte ``offset`` + holding ``extra`` bytes more; the other values the program's and the session's inputs.""" + def build(g, src, bad, tmp): + v, nbytes = {"rows": lambda: (g.weight("p", (64, 2560), "q5_k"), 64 * ROW), + "xq": lambda: (g.const("p", (1, QCOL), U8), QCOL), + "map": lambda: (g.const("p", (64,), I32), 4 * 64)}[value]() + x1 = v if value == "xq" else g.input("x1", (1, QCOL), U8) + rows = v if value == "rows" else g.input("dhead", (64, ROW), U8, host=True) + mp = v if value == "map" else g.input("dvocab", (64,), I32, host=True) + if kind == "basalt_q5k_proxy_top1": + proxy = g.input("proxy", (kernels.basalt_q5k_proxy_bytes(64),), U8, host=True) + proxy_top1(g, "y", x1, proxy, rows, mp, n_rows=64, n_cap=64) + else: + (head if kind == "basalt_q5k_head" else top1)(g, "y", x1, rows, mp) + return {"packs": [pack(tmp, {"p": (offset, nbytes + extra) if bad else (16, nbytes)})]} + return build + + +REFUSALS = [ + *[(f"dynamic-T {k}", _dynamic(k), "a dynamic-T program cannot run them") for k in KINDS], + *[(f"{k} with a second map", _arity(k), r"4 inputs; it takes \(xq, rows\[, map\]\)") for k in KINDS[:2]], + ("proxy top-1 with a second map", _arity("basalt_q5k_proxy_top1"), + r"5 inputs; it takes \(xq, proxy, rows, map\)"), + ("head on Q4_K rows", _rows_type, r"of ggml type \['q5_k'\]"), + ("head rows an input the program allocates", _rows_not_host, "is an input each program allocates"), + ("head host rows not whole Q5_K blocks", _host_rows(shape=(64, ROW - 60)), + r"u8 \[64, 1700\], not u8 \[rows, whole 176-byte"), + ("head host rows not u8", _host_rows(dtype=F32), r"'dhead' are f32 \[64, 1760\], not u8 \[rows, whole 176-byte"), + ("head host rows of rank 3", _host_rows(shape=(64, ROW, 2)), + r"'dhead' are u8 \[64, 1760, 2\], not u8 \[rows, whole 176-byte"), + ("head host rows of no blocks", _host_rows(shape=(64, 0)), r"unsupported shape \(n_in 0, ncols 1\)"), + *[(f"head host rows named after StepState's {f}", _host_rows(name=n), + f"the host input '{n}' is named after StepState's '{f}'") + for n, f in (("draft_tokens", "draft_tokens"), ("tokens", "pending_tokens"))], + *[(f"head host rows named after the program's {n}", _host_rows(name=n), + f"the host input '{n}' is named after the program's {own}; a host input binds") + for n, own in (("step_state", "StepState"), ("ring", "token ring"))], + ("head host rows named after the verify head's window", _host_rows_window, + r"the host input 'basalt\.[0-9a-f]{16}' is named after the program's weights window; a host input binds"), + ("head host rows named after the head's params record", _host_rows(name="params.S2.basalt_q5k_head.0"), + r"the program's params record took the name of the host input 'params\.S2\.basalt_q5k_head\.0'; a host input " + "binds"), + ("top-1 host rows named after its partials' scratch arena", _top1_host_rows("ws.T2.basalt_q5k_top1.part.1"), + r"the program's scratch arena took the name of the host input 'ws\.T2\.basalt_q5k_top1\.part\.1'; a host input " + "binds"), + *[(f"head host rows named after the {what}", _host_rows_log(k, log), + f"the program's {what} took the name of the host input '{log}'; a host input binds") + for k, log, what in (("accept_scan", ACCEPT_LOG, "accept log"), ("verify_select", CONF_LOG, "confidence log"))], + *[(f"{k} reads a row past its rows", _rows_held(k), f"'dhead' holds {N_DVOCAB} rows; the op reads {N_DVOCAB + 1}") + for k in KINDS], + ("head of 9 columns", _head_shape((8, 10), (9, 10)), r"unsupported shape \(n_in 2560, ncols 9\)"), + ("head of no columns", _head_shape((1, 10), (0, 10)), r"unsupported shape \(n_in 2560, ncols 0\)"), + ("head rows of 65 blocks", _head_shape((1, 64), (1, 65)), r"unsupported shape \(n_in 16640, ncols 1\)"), + ("head of 3 columns of 64 blocks", _head_shape((2, 64), (3, 64)), r"unsupported shape \(n_in 16384, ncols 3\)"), + ("head q8_1 rows of another width", _head_xq_width, r"not u8 \[2, 2880\] \(q8_1 rows of the rows' width\)"), + ("head logits not F32", _head_logits, r"not f32 \[2, 4000\] \(contiguous columns of the logits\)"), + *[(f"{k} map a row short", _map_short(k), rf"\[{N_CAP - 1}\]; it maps the {N_CAP} rows read") for k in KINDS], + ("head map not I32", _head_map(dtype=DType.U32), r"the map 'dvocab' is u32"), + ("head map of rank 2", _head_map(shape=(N_DVOCAB, 2)), rf"the map 'dvocab' is i32 \[{N_DVOCAB}, 2\]"), + ("top-1 on rows of 2048", _top1_n_in("basalt_q5k_top1"), "rows of 2048 values; q5k_head_top1 takes 2560"), + ("proxy top-1 on rows of 2048", _top1_n_in("basalt_q5k_proxy_top1"), + "rows of 2048 values; the 2-bit copy holds rows of 2560"), + *[(f"{k} of two columns", _one_column(k), r"not u8 \[1, 2880\] \(one q8_1 column") for k in KINDS[1:]], + ("top-1 logits not F32", _out_dtype("basalt_q5k_top1", 0), r"\(the logits of one column\)"), + *[(f"{k} id not I32", _out_dtype(k, 1), r"\(the best row's id\)") for k in KINDS[1:]], + *[(f"{k} probability not F32", _out_dtype(k, 2), r"\(its probability\)") for k in KINDS[1:]], + ("proxy top-1 without the map", _proxy_map, r"3 inputs; .* basalt refuses it without the map"), + ("proxy top-1 without n_rows", _proxy_attrs("n_rows"), f"must be ints, got None and {N_CAP}"), + ("proxy top-1 without n_cap", _proxy_attrs("n_cap"), f"must be ints, got {N_CAP} and None"), + ("proxy top-1 n_rows past n_cap", _proxy_rows_past_cap, + rf"rows out of range \(row0 0, n 0, n_rows {N_CAP}, n_cap {N_CAP - 1}\)"), + ("proxy top-1 copy not a host input", _proxy_not_host, "the 2-bit copy 'proxy2' is not a host input"), + ("proxy top-1 copy of another size", _proxy_size, r"\(the 2-bit copy of n_cap rows\)"), + *[(f"{k} rows off 2 bytes", _from_pack(k, "rows", 1), "'p' binds at byte 1 of .*; slot 0 needs 2-byte alignment") + for k in KINDS], + *[(f"{k} q8_1 column off 4 bytes", _from_pack(k, "xq", 2), "'p' binds at byte 2 of .*; slot 1 needs 4-byte") + for k in KINDS], + *[(f"{k} map off 4 bytes", _from_pack(k, "map", 2), f"'p' binds at byte 2 of .*; slot {s} needs 4-byte") + for k, s in zip(KINDS, (1, 3, 2))], # the mask's slot, the top-1's, the score's + *[(f"{k} rows entry a row short", _from_pack(k, "rows", extra=-ROW), + r"'p' is 112640 bytes of q5_k \[64, 2560\], but its pack entry holds 110880") for k in KINDS], +] + + +@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) diff --git a/tests/kernels/test_basalt_q5k_ops_program.py b/tests/kernels/test_basalt_q5k_ops_program.py new file mode 100644 index 00000000..9456d2d9 --- /dev/null +++ b/tests/kernels/test_basalt_q5k_ops_program.py @@ -0,0 +1,334 @@ +# 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): the rows' rescaling and the planted row (centered here; basalt plants it uncentered). +"""basalt's Q5_K head ops (monolith/ops/basalt.py) in compiled static programs on the GPU, as basalt captures them: the +verify head (``q5k_head_mmvq`` over ``output.weight``, T columns, no map) in one program per width T = 1 .. 8, and a +drafter's head, one program per draft-head tier and width (``round_exec_[tier][T]``, mtp.cpp:1516; ``mtp.cpp:1006-1025`` +picks the launches): at T = 1 the proxy top-1 over the 2-bit copy of the first n_tier1 rows (tier 0) or the top-1 with +the map over every gathered row (tier 1), above T = 1 the head over the tier's rows and the mask on each column; and the +top-1 over ``output.weight`` without a map (a drafter with no draft vocabulary). The file is bound through its windows +and through exact per-tensor copies; the gathered rows, their map and the 2-bit copy are the session's host buffers, one +allocation every draft program binds. + +Synthetic Q5_K rows at n_in 2560 (q5k_head_parity's rows, rescaled so that the logits spread 3, as its proxy test does) +and q8_1 columns, each a noise vector plus one planted row, centered and lifted so that its logit stands above every +other row's (by 11 or more in these columns; uncentered, the rows' common mean lifts every logit with it): the row of a +token the draft vocabulary lacks until a flush brings it in. + +- Each output bitwise equal to the merged single-kernel harness (tests/kernels/basalt_gpu.py) on the same bytes: the + logits, the id, the probability and the top-1's partials; the proxy top-1's id and probability with the score's + candidates and tile partials; the masked head's columns against the harness's head and mask on each column. The + program's outputs and scratch start as 0xff bytes, the harness's as 0xee. +- The session's flush (``ctx_flush``, mtp.cpp:1439-1452): the planted tokens' rows gathered into the next context + rows, the 2-bit copy packed over them by the harness's direct pack dispatch (row0 > 0) on top of the load's pack, + their ids written into the map. Every draft program scored again equals the harness on the new bytes, its pick + moves to the planted token, and the copy equals a pack of the new rows at load. +- Window invariance at program level (docs/design/flash-next.md invariant 1): column j of the T-wide verify head bit + for bit the 1-wide program on column j alone. +- A draft vocabulary of one row on session buffers of exactly its bytes, the map's 4 among them. +- Each program run twice gives identical bits.""" + +import numpy as np +import pytest + +from monolith import kernels +from monolith.compiler import emit_program +from monolith.core import Graph +from monolith.core.shapes import T +from monolith.packs.basalt import BasaltSource +from monolith.runtime import Engine +from tests.contract.test_basalt_ops import PROFILE, weight, write_file +from tests.contract.test_basalt_q5k_ops import QCOL, ROW, U8, draft_inputs, head, proxy_top1, top1 +from tests.kernels import basalt_gpu as gpu +from tests.kernels import test_basalt_q5k_head as q5k + +F32 = np.float32 +N_IN, N_VOCAB = 2560, 6000 +N_BASE, N_XCAP, N_ADD = 3000, 64, 300 # the draft vocabulary: base ids, context rows, added ids +N_CAP, N_DVOCAB = N_BASE + N_XCAP, N_BASE + N_XCAP + N_ADD # tier 0's rows (n_tier1_), tier 1's (n_dvocab_) +WIDTHS = range(1, 9) +PIPELINES = {} # one pipeline cache for every engine of the module + + +@pytest.fixture(scope="module") +def data(): + """The head's rows, the draft vocabulary's map (base ids, the context rows' -1, added ids: mtp.cpp:647-653), the + flush's tokens (outside the vocabulary) and 8 q8_1 columns, column j planted with the row of token j % 4: its + values less their mean at 60 / |row - mean|^2 (q5k_head_parity.cpp:263-293 plants 20 / |row|^2).""" + rng = np.random.default_rng(2560) + w = q5k.weights(N_VOCAB, rng) + l0 = gpu.mmvq(13, w, gpu.q8_1(rng.standard_normal(N_IN).astype(F32), "native"), N_IN, N_VOCAB, 1)[0] + f = F32(3.0 / np.std(l0.astype(np.float64))) # q5k_head_parity.cpp:215-235: the logits spread 3 + blk = w.reshape(-1, 176) + blk[:, :4] = (blk[:, :4].copy().view(np.float16).astype(F32) * f).astype(np.float16).view(np.uint8).reshape(-1, 4) + ids = rng.permutation(N_VOCAB) + dvocab = np.concatenate([np.sort(ids[:N_BASE]), np.full(N_XCAP, -1), np.sort(ids[N_BASE: N_BASE + N_ADD])]) + tokens = ids[N_BASE + N_ADD: N_BASE + N_ADD + 4] + cols = [] + for j in range(8): + dq = q5k.dequant(w[tokens[j % 4]]).astype(np.float64) + dq -= dq.mean() + noise = F32(0.8) * rng.standard_normal(N_IN).astype(F32) + cols.append((noise + (60.0 / np.sum(dq * dq) * dq).astype(F32)).astype(F32)) + return {"w": w, "dvocab": dvocab.astype(np.int32), "tokens": tokens, + "xq": gpu.q8_1(np.concatenate(cols), "native")} + + +def run(eng, inputs, read, fill): + """One step of ``eng`` on ``inputs``, after every buffer of ``read`` ({name: bytes}) is filled with ``fill``.""" + for name, b in inputs.items(): + eng.buffers[name].write(b, 0) + for name in read: + eng.buffers[name].fill(fill) + assert eng.run(1, steps_per_cb=1, in_flight=1).steps == 1 + return {name: eng.read(name, nb) for name, nb in read.items()} + + +def runs_twice(eng, inputs, read): + """Two runs, outputs and scratch starting as 0xff and then 0x5a: (the first's bytes, the second's).""" + return run(eng, inputs, read, 0xFF), run(eng, inputs, read, 0x5A) + + +def workspace(prog, function, slot): + """(buffer, size) a dispatch of ``function`` binds at ``slot``: the top-1's partials or the proxy's scratch, read + whole (the contract tier checks the sizes against the builders).""" + o = next(o for o in prog.ops if prog.kernels[o.kernel].function == function) + name = o.bindings[[b[0] for b in o.bindings].index(slot)][1] + return name, prog.buffers[name].nbytes + + +# ---- the verify head and the plain top-1, over the file ------------------------------------------------------------- + +@pytest.fixture(scope="module", params=[False, True], ids=["windows", "exact-copies"]) +def file_runs(request, data, tmp_path_factory): + """``output.weight`` in a .basalt file; the verify head at each width and the top-1 without a map, each run twice.""" + w = data["w"] + path = write_file(tmp_path_factory.mktemp("q5k") / "head.basalt", {"output.weight": (13, N_VOCAB, N_IN, w.tobytes())}, + {"pad": (1, 64, bytes(128))}) + src = BasaltSource(path, copy=request.param) + progs = {} + for t in WIDTHS: + g = Graph("step") + head(g, "y", g.input("xq", (T, QCOL), U8), weight(g, "gguf/output.weight", src)) + progs[t] = emit_program(g, pack=src, profile=PROFILE, t=t, tail=None) + g = Graph("step") + top1(g, "t", g.input("x1", (1, QCOL), U8), weight(g, "gguf/output.weight", src)) + progs["top1"] = emit_program(g, pack=src, profile=PROFILE, t=1, tail=None) + dev = gpu.device() + shared, engines, out = {}, {}, {} + for key, prog in progs.items(): + engines[key] = Engine(prog, dev, buffers=shared, pipeline_cache=PIPELINES) + shared.update({n: b for n, b in engines[key].buffers.items() if prog.buffers[n].role == "weights"}) + xq = data["xq"] + for t in WIDTHS: + out[t] = runs_twice(engines[t], {"xq": xq[: t * QCOL].tobytes()}, {"y": 4 * t * N_VOCAB}) + ones = [run(engines[1], {"xq": xq[j * QCOL: (j + 1) * QCOL].tobytes()}, {"y": 4 * N_VOCAB}, 0xFF)["y"] + for j in range(8)] + part, part_bytes = workspace(progs["top1"], "basalt_q5k_head_top1", 4) + out["top1"] = runs_twice(engines["top1"], {"x1": xq[:QCOL].tobytes()}, + {"t.y": 4 * N_VOCAB, "t.id": 4, "t.p": 4, part: part_bytes}) + return {"src": src, "progs": progs, "engines": engines, "out": out, "ones": ones, "part": part} + + +def test_verify_head_is_the_harness(data, file_runs): + """The verify head (basalt's ``q5k_head_mmvq`` over ``output.weight``, verify.cpp:1935-1936): each width's logits + bit for bit the harness's launch for T columns.""" + w, xq = data["w"], data["xq"] + for t in WIDTHS: + y = np.frombuffer(file_runs["out"][t][0]["y"], F32).reshape(t, N_VOCAB) + assert y.tobytes() == gpu.q5k_head(w, xq[: t * QCOL], N_IN, N_VOCAB, t).tobytes(), t + assert np.all(np.isfinite(y)) and np.argmax(y[0]) == data["tokens"][0], t + + +def test_verify_head_window_invariance(file_runs): + """Window invariance at program level (docs/design/flash-next.md invariant 1): column j of each width's logits bit + for bit the 1-wide program's on column j alone, every logit finite.""" + for t in WIDTHS: + y = file_runs["out"][t][0]["y"] + assert np.all(np.isfinite(np.frombuffer(y, F32))), t + for j in range(t): + assert y[4 * N_VOCAB * j: 4 * N_VOCAB * (j + 1)] == file_runs["ones"][j], (t, j) + + +def test_top1_without_a_map_is_the_harness(data, file_runs): + """The top-1 over output.weight without a map: logits, id, probability and the partials, bit for bit.""" + got = file_runs["out"]["top1"][0] + y, tid, p, part = gpu.q5k_top1(data["w"], data["xq"][:QCOL], N_VOCAB) + assert (got["t.y"], got["t.p"], got[file_runs["part"]]) == (y.tobytes(), p.tobytes(), part.tobytes()) + assert np.frombuffer(got["t.id"], np.int32)[0] == tid == data["tokens"][0] + + +def test_file_programs_run_twice_alike(file_runs): + for key, (first, second) in file_runs["out"].items(): + assert first == second, key + + +# ---- the draft head: one program per tier and width over the session's host buffers ---------------------------------- + +def draft_program(tier, t): + """Tier 0 reads the first N_CAP gathered rows (the proxy top-1 at T = 1), tier 1 all of them (the top-1 with the + map); above T = 1 both run the head over their rows and mask each column (mtp.cpp:1006-1025).""" + g = Graph("step") + rows, mp, proxy = draft_inputs(g, rows=N_DVOCAB, cap=N_CAP) + if t == 1: + x1 = g.input("x1", (1, QCOL), U8) + if tier == 0: + proxy_top1(g, "p", x1, proxy, rows, mp, n_rows=N_CAP, n_cap=N_CAP) + else: + top1(g, "t", x1, rows, mp) + else: + head(g, "y", g.input("xq", (T, QCOL), U8), rows, mp, width=(N_CAP, N_DVOCAB)[tier]) + return emit_program(g, pack=[], profile=PROFILE, t=t, tail=None) + + +def draft_reads(prog, tier, t): + """{buffer: bytes} a draft program's run reads: its outputs and the scratch its second dispatch reads.""" + if t > 1: + return {"y": 4 * t * (N_CAP, N_DVOCAB)[tier]} + if tier == 0: + return dict([("p.id", 4), ("p.p", 4), workspace(prog, "basalt_q5k_proxy_score", 3)]) + return dict([("t.y", 4 * N_DVOCAB), ("t.id", 4), ("t.p", 4), workspace(prog, "basalt_q5k_head_top1", 4)]) + + +@pytest.fixture(scope="module") +def draft_runs(data): + """The session: its host buffers after the load (the gather with the context rows reading the first base id's row, + the copy packed over its N_CAP rows, mtp.cpp:657-680), every draft program run twice; then its flush (the four + tokens' rows into context rows N_BASE .., the pack over them at row0 = N_BASE, their ids into the map) and every + program run twice again. Returns the programs, engines, buffers and each state's bytes and outputs.""" + w, dvocab = data["w"], data["dvocab"].copy() + dhead = w[np.where(dvocab < 0, dvocab[0], dvocab)] + proxy = gpu.q5k_proxy_pack(dhead, N_CAP, [(0, N_CAP)]) + dev = gpu.device() + session = {"dhead": gpu.nt.Buffer(dev, dhead.tobytes()), "dvocab": gpu.nt.Buffer(dev, dvocab.tobytes()), + "proxy": gpu.nt.Buffer(dev, proxy.tobytes())} + progs = {(tier, t): draft_program(tier, t) for tier in (0, 1) for t in WIDTHS} + engines = {k: Engine(p, dev, buffers=session, pipeline_cache=PIPELINES) for k, p in progs.items()} + xq = data["xq"] + + def score(): + out = {} + for (tier, t), eng in engines.items(): + inputs = {"x1" if t == 1 else "xq": xq[: t * QCOL].tobytes()} + out[tier, t] = runs_twice(eng, inputs, draft_reads(progs[tier, t], tier, t)) + return out + + states = {"load": {"dhead": dhead.copy(), "dvocab": dvocab.copy(), "proxy": proxy, "out": score()}} + at, k = N_BASE, len(data["tokens"]) # xbase_ + n_xused_: the first free context row + dhead[at: at + k] = w[data["tokens"]] # gather_rows (the session's) + session["dhead"].write(dhead[at: at + k].tobytes(), at * ROW) + proxy = gpu.q5k_proxy_pack(dhead, N_CAP, [(at, k)], proxy=proxy) # q5k_proxy_pack(dhead_, at, n, ...) + session["proxy"].write(proxy.tobytes(), 0) + dvocab[at: at + k] = data["tokens"] # the id map's copy + session["dvocab"].write(dvocab[at: at + k].tobytes(), 4 * at) + states["flush"] = {"dhead": dhead, "dvocab": dvocab, "proxy": proxy, "out": score()} + return {"progs": progs, "engines": engines, "session": session, "states": states} + + +@pytest.mark.parametrize("state", ["load", "flush"]) +def test_proxy_top1_is_the_harness(data, draft_runs, state): + """Tier 0 at T = 1: the id, the probability, the score's candidates and tile partials bit for bit the harness's + q5k_proxy_top1 on the state's copy, rows and map. The load's pick is a base row; the flush's is the token.""" + s = draft_runs["states"][state] + got = s["out"][0, 1][0] + tid, p, cand, part = gpu.q5k_proxy_top1(s["proxy"], s["dhead"], data["xq"][:QCOL], N_CAP, N_CAP, s["dvocab"]) + scratch = got[workspace(draft_runs["progs"][0, 1], "basalt_q5k_proxy_score", 3)[0]] + t = kernels.basalt_q5k_proxy_tiles(N_CAP) # n_rows = n_cap: the candidates, then the tiles' partials + assert (scratch[: 32 * t], scratch[32 * t: 40 * t]) == (cand.tobytes(), part.tobytes()) + assert np.frombuffer(got["p.id"], np.int32)[0] == tid and got["p.p"] == p.tobytes() + assert (tid == data["tokens"][0]) == (state == "flush") and tid in s["dvocab"][:N_CAP] + + +@pytest.mark.parametrize("state", ["load", "flush"]) +def test_top1_with_the_map_is_the_harness(data, draft_runs, state): + """Tier 1 at T = 1: the logits (masked rows -inf), the id through the map, the probability and the partials bit for + bit the harness's q5k_head_top1 on the state's rows and map. The flush's pick is the token.""" + s = draft_runs["states"][state] + got = s["out"][1, 1][0] + y, tid, p, part = gpu.q5k_top1(s["dhead"], data["xq"][:QCOL], N_DVOCAB, s["dvocab"]) + part_name = workspace(draft_runs["progs"][1, 1], "basalt_q5k_head_top1", 4)[0] + assert (got["t.y"], got["t.p"], got[part_name]) == (y.tobytes(), p.tobytes(), part.tobytes()) + assert np.frombuffer(got["t.id"], np.int32)[0] == tid + assert np.all(np.isneginf(y[s["dvocab"] < 0])) and np.all(np.isfinite(y[s["dvocab"] >= 0])) + assert (tid == data["tokens"][0]) == (state == "flush") + + +@pytest.mark.parametrize("state", ["load", "flush"]) +@pytest.mark.parametrize("tier", [0, 1]) +def test_masked_head_is_the_harness(data, draft_runs, tier, state): + """Each tier above T = 1: column j of the T-wide masked head bit for bit the harness's head and mask on column j + over the tier's rows (basalt masks each column in turn, mtp.cpp:1024-1025); after the flush column j's best row is + the context row of the token planted in it.""" + s, nv = draft_runs["states"][state], (N_CAP, N_DVOCAB)[tier] + want = [gpu.q5k_head_masked(s["dhead"], data["xq"][j * QCOL: (j + 1) * QCOL], N_IN, nv, s["dvocab"]) + for j in range(8)] + for t in WIDTHS[1:]: + y = np.frombuffer(s["out"][tier, t][0]["y"], F32).reshape(t, nv) + for j in range(t): + assert y[j].tobytes() == want[j].tobytes(), (t, j) + if state == "flush": + assert np.argmax(y[j]) == N_BASE + j % 4, (t, j) + + +def test_the_flush_packs_what_a_load_would(draft_runs): + """The copy after the load's pack and the flush's pack over the appended rows equals one pack of the new rows (the + session's two direct dispatches give a load's bytes), and the session's buffers hold what the harness wrote.""" + s, session = draft_runs["states"]["flush"], draft_runs["session"] + assert np.array_equal(s["proxy"], gpu.q5k_proxy_pack(s["dhead"], N_CAP, [(0, N_CAP)])) + for name in ("dhead", "dvocab", "proxy"): + assert session[name].read(0, session[name].nbytes) == np.ascontiguousarray(s[name]).tobytes(), name + + +def test_draft_programs_share_the_sessions_buffers(draft_runs): + """Every tier's program at every width binds the session's one allocation of each host buffer, and a program is + refused without them (the session allocates them: Engine).""" + for key, eng in draft_runs["engines"].items(): + assert all(eng.buffers[n] is b for n, b in draft_runs["session"].items()), key + with pytest.raises(ValueError, match="host buffer dhead: the session allocates it"): + Engine(draft_runs["progs"][0, 1], gpu.device(), pipeline_cache=PIPELINES) + + +def test_draft_programs_run_twice_alike(draft_runs): + for state, s in draft_runs["states"].items(): + for key, (first, second) in s["out"].items(): + assert first == second, (state, key) + + +def test_one_row_on_exact_session_buffers(data): + """A draft vocabulary of one row on session buffers of exactly its bytes (rows 1,760, map 4, copy + q5k_proxy_bytes(1)), as basalt allocates them (mtp.cpp:656-657, :676-678): Engine takes them, and the proxy + top-1, the top-1 with the map and the masked head at T = 2 are bit for bit the harness's. Shader validation bounds + each read by its buffer, so a read past the one id is a report.""" + w1, mp, xq = data["w"][:1], np.array([7], np.int32), data["xq"] + proxy = gpu.q5k_proxy_pack(w1, 1, [(0, 1)]) + dev = gpu.device() + session = {"dhead": gpu.nt.Buffer(dev, w1.tobytes()), "dvocab": gpu.nt.Buffer(dev, mp.tobytes()), + "proxy": gpu.nt.Buffer(dev, proxy.tobytes())} + assert [b.nbytes for b in session.values()] == [ROW, 4, kernels.basalt_q5k_proxy_bytes(1)] + progs = {} + for kind, t in (("proxy", 1), ("top1", 1), ("head", 2)): + g = Graph("step") + rows, m, cp = draft_inputs(g, rows=1, cap=1) + x = g.input("x1", (1, QCOL), U8) if t == 1 else g.input("xq", (T, QCOL), U8) + {"proxy": lambda: proxy_top1(g, "p", x, cp, rows, m, n_rows=1, n_cap=1), + "top1": lambda: top1(g, "t", x, rows, m), "head": lambda: head(g, "y", x, rows, m)}[kind]() + progs[kind] = emit_program(g, pack=[], profile=PROFILE, t=t, tail=None) + eng = {k: Engine(p, dev, buffers=session, pipeline_cache=PIPELINES) for k, p in progs.items()} + x1 = {"x1": xq[:QCOL].tobytes()} + + scratch = workspace(progs["proxy"], "basalt_q5k_proxy_score", 3) + got = run(eng["proxy"], x1, dict([("p.id", 4), ("p.p", 4), scratch]), 0xFF) + tid, p, cand, part = gpu.q5k_proxy_top1(proxy, w1, xq[:QCOL], 1, 1, mp) + assert (got[scratch[0]][:32], got[scratch[0]][32:40]) == (cand.tobytes(), part.tobytes()) # one tile + assert np.frombuffer(got["p.id"], np.int32)[0] == tid == 7 and got["p.p"] == p.tobytes() + + part_ws = workspace(progs["top1"], "basalt_q5k_head_top1", 4) + got = run(eng["top1"], x1, dict([("t.y", 4), ("t.id", 4), ("t.p", 4), part_ws]), 0xFF) + y, tid, p, part = gpu.q5k_top1(w1, xq[:QCOL], 1, mp) + assert (got["t.y"], got["t.p"], got[part_ws[0]][: part.nbytes]) == (y.tobytes(), p.tobytes(), part.tobytes()) + assert np.frombuffer(got["t.id"], np.int32)[0] == tid == 7 + + got = run(eng["head"], {"xq": xq[: 2 * QCOL].tobytes()}, {"y": 8}, 0xFF) + want = [gpu.q5k_head_masked(w1, xq[j * QCOL: (j + 1) * QCOL], N_IN, 1, mp) for j in range(2)] + assert got["y"] == b"".join(a.tobytes() for a in want) diff --git a/third_party/NOTICE b/third_party/NOTICE index 85e8cfb7..ec8e1ec7 100644 --- a/third_party/NOTICE +++ b/third_party/NOTICE @@ -230,11 +230,11 @@ Format: `` — adapted from / copied 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 +- `monolith/kernels.py` — adapted from `src/kernels/cuda/q5k_head.cu:337-386`, `:406-408` 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`. + top-1's grid rule (`basalt_q5k_head_grid`), the top-1's partials (`basalt_q5k_top1_part_bytes`), the mask's launch + (`basalt_q5k_mask_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/kernels.py` — adapted from `src/kernels/cuda/native_gr_norm.cu:85-100`, `src/kernels/cuda/native_ple_postops.cu:36` and `:352-359`, `src/kernels/cuda/ple.cu:36` and `:210`, `src/kernels/cuda/elementwise.cu:277-287`, `src/kernels/cuda/verify_kernels.cu:1086-1090`, @@ -243,25 +243,31 @@ Format: `` — adapted from / copied from `` `` @ `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`, `src/kernels/cuda/iq_kernels.cu:2450-2455` and - `src/kernels/cuda/native_gr_postops.cu:75-82` (MIT): the launchers' checks its handlers make at emit time + `src/kernels/cuda/native_bf16.cu:139-171`, `src/kernels/cuda/iq_kernels.cu:2450-2455`, + `src/kernels/cuda/native_gr_postops.cu:75-82`, `src/kernels/cuda/q5k_head.cu:372-374`, `:406-408`, `:411-412` and + `:516-518` and `src/core/mtp.cpp:1024-1025` (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, `native_gr_post`'s launcher checks (non-null four-byte aligned pointers, positive - bounded dimensions)); `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`), and its - `basalt_gr_post_params` and `basalt_gr_post_grid` transcribe `native_gr_post`'s `check_shape`, `THREADS` and `blocks` - (`native_gr_postops.cu:35`, `:79-83`); `ple_block`'s native branch and refusals (`src/kernels/cuda/ple.cu:228-356`), - `native_ple_postops`'s span and alias checks (`src/kernels/cuda/native_ple_postops.cu:317-361`), - `ple_history_advance`'s (`ple.cu:204-212`) and the verify loop's per-row order and commit restore - (`src/core/verify.cpp:1105-1124`, `:2137`), with the norm's, the snapshot's and the restore's launcher checks - (`src/kernels/cuda/native_gr_norm.cu:78-100`, `src/kernels/cuda/elementwise.cu:277-287`, + bounded dimensions), the Q5_K head's shape rule, the top-1's 2,560 inputs, the proxy top-1's row range and required + map) and the Q5_K head's launch sequence (the per-column mask of `src/core/mtp.cpp:1024-1025`, the top-1's grid shared + by its two dispatches); `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`), and + its `basalt_gr_post_params` and `basalt_gr_post_grid` transcribe `native_gr_post`'s `check_shape`, `THREADS` and + `blocks` (`native_gr_postops.cu:35`, `:79-83`); `ple_block`'s native branch and refusals + (`src/kernels/cuda/ple.cu:228-356`), `native_ple_postops`'s span and alias checks + (`src/kernels/cuda/native_ple_postops.cu:317-361`), `ple_history_advance`'s (`ple.cu:204-212`) and the verify loop's + per-row order and commit restore (`src/core/verify.cpp:1105-1124`, `:2137`), with the norm's, the snapshot's and the + restore's launcher checks (`src/kernels/cuda/native_gr_norm.cu:78-100`, `src/kernels/cuda/elementwise.cu:277-287`, `src/kernels/cuda/verify_kernels.cu:1086-1090`) and the key's binding (`keep_unquantized_ple_key`, `src/core/native_dense.cpp:95-102`; `index_code_bits`, `src/core/weights.cpp:129-148`). 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_q5k_ops_program.py` — adapted from `src/kernels/q5k_head_parity.cpp` (MIT): the rows' + rescaling and the planted row (centered in this test; basalt plants it uncentered). 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`. From fcbd8003fdc540fdc6ff8e0267d18fcb433de14d Mon Sep 17 00:00:00 2001 From: Lance Woodson <65194841+woodsonl@users.noreply.github.com> Date: Sat, 24 Oct 2026 15:51:33 -0500 Subject: [PATCH 74/74] Transcribe libdevice's math functions in the port contract The net change of woodsonl/mlxstream#35 (fork merge commit 143c09a): the port contract's invariant 5 transcribes libdevice's exp, logf, expf, powf, cosf, sinf and log1pf from the PTX nvcc inlines, each approximate step in them mapped as the invariant maps it, in place of the library expf's metal::precise::exp; prefill_kernels.md and ple.md record the choice. --- docs/design/flash-next.md | 12 ++++----- docs/research/basalt-nvcc/ple.md | 2 +- docs/research/basalt-nvcc/prefill_kernels.md | 27 ++++++++------------ 3 files changed, 18 insertions(+), 23 deletions(-) diff --git a/docs/design/flash-next.md b/docs/design/flash-next.md index 3c97e294..78d71011 100644 --- a/docs/design/flash-next.md +++ b/docs/design/flash-next.md @@ -150,12 +150,12 @@ ones this pack runs. 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 + basalt's PTX forms, `fast::rsqrt` for `rsqrtf` (Table 8.2). libdevice's `exp`, `logf`, `expf`, `powf`, `cosf`, + `sinf` and `log1pf` are transcribed from the PTX nvcc inlines, each approximate step in them mapped as above. 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 and where basalt approximates an exponential or a square root (`ex2.approx`, + `rsqrtf`), 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 diff --git a/docs/research/basalt-nvcc/ple.md b/docs/research/basalt-nvcc/ple.md index b79c789f..7a9e6e0a 100644 --- a/docs/research/basalt-nvcc/ple.md +++ b/docs/research/basalt-nvcc/ple.md @@ -341,7 +341,7 @@ Notes: (0fBFB8AA3B = −L). Rounding to nearest even and the flush are symmetric in sign, so `expf_ftz(-x)`, which computes `mul_ftz(-x, L)` = fl((−x)·L), has exactly the bits of the SASS multiply fl(x·(−L)). The multiply is `mul.ftz.f32` without `.rn` and so could fuse with an add it fed; in both sites it feeds `ex2`. The library `expf` of an IEEE file - (a different, longer sequence that the contract maps to `metal::precise::exp`) does not occur on this path. + (a different, longer sequence, which the contract transcribes as `nv_expf`) does not occur on this path. - **Every division is a reciprocal.** `div.approx.f32` is defined by the PTX ISA as a·(1/b), and `ptxas` emits exactly that: `MUFU.RCP` of the divisor and an `FMUL.FTZ`. The multiply carries no rounding modifier, so where an add without one consumes the quotient (norm `:72`) `ptxas` fuses them into an `FFMA.FTZ`. `1.0f / x` skips the multiply. None of diff --git a/docs/research/basalt-nvcc/prefill_kernels.md b/docs/research/basalt-nvcc/prefill_kernels.md index 85d4bee1..8e00549a 100644 --- a/docs/research/basalt-nvcc/prefill_kernels.md +++ b/docs/research/basalt-nvcc/prefill_kernels.md @@ -156,8 +156,8 @@ The sequences shared by many sites: 2. `rsqrtf` (`rsqrt.approx.f32`, `MUFU.RSQ`) in `gr_norm_rs`, `gr_write_norm_rs`, `gdn_l2`, `gdn_out_norm` and `rms_rows`. Metal: `fast::rsqrt`; no argument reaches the subnormal wrapper. 3. The library `expf`, libdevice's `__nv_expf` inlined, whose one approximate step is `ex2.approx.ftz.f32`, in - `route_kernel` (`:642`) and `gate_attn` (`:770`). Metal: the contract's `precise::exp` - (`flash-next.md:153`), or `nv_expf`, every other step transcribed, proposed in section 3 for the owner. + `route_kernel` (`:642`) and `gate_attn` (`:770`). Metal: `nv_expf`, every other step transcribed + (`flash-next.md:153-154`; section 3). 4. `powf`, libdevice's `__nv_powf` inlined, whose one approximate step is `rcp.approx.ftz.f32`, in `rope` (`:751`). Metal: `nv_powf` with `1.0f / x` there; for this pack's theta_scale no result depends on that reciprocal's last bits [M] (section 4). @@ -457,8 +457,7 @@ passes −q, of either sign) t saturates at 1 above about 87.34, where k = 252 a with d, every fma step stays normal, and from about 88.72 the scale multiply overflows to +inf on both machines (`ex2.approx.ftz` and `fast::exp2` themselves return +inf once f reaches 128). -Metal: the contract maps the library `expf` to `metal::precise::exp` (`flash-next.md:153`); this page proposes -`nv_expf(d)`, a transcription, for the owner's decision (the paragraph after the code): +Metal: `nv_expf(d)`, the transcription the contract asks for (`flash-next.md:153-154`), explained after the code: ``` float t = saturate(fma(d, as_type(0x3BBB989Du), 0.5f)); @@ -473,16 +472,12 @@ float e = ieee_mul(fast::exp2(f), as_type(uint(k + 1.0f) << 23)); tiny and e = 1 on both machines, and for k ≠ 126 the fma results are far from the subnormal range (|f| ≥ 2^-48 when nonzero). `ex2.approx.ftz` maps to `fast::exp2` (invariant 5); both flush a subnormal input and output, and the output is subnormal only for f < −126, d below about −174.7, where e is +0 anyway. The scale multiply is the one -step that writes a subnormal (k = 0, f < 0), so it is `ieee_mul`. A NaN d gives a NaN e. The contract's table -maps the library `expf` to `metal::precise::exp` (`flash-next.md:153`), which is a different function: -`precise::exp` is not `__nv_expf`'s sequence, and the bits then differ wherever the two round differently. -`nv_expf` reproduces every operation but `ex2.approx`, which follows the contract's own mapping; it extends the -owner's libdevice decision (`origin/woodsonl/basalt-sampler:kernels/common/basalt_libdevice.metal` transcribes only -`__nv_exp` and `__nv_logf`), so it needs the owner's sign-off. The deciding fact: that decision covers library functions -without a correctly rounded Metal counterpart, and Metal does not document its `exp` as correctly rounded (the MSL -specification gives its math functions ulp bounds). Until the owner decides, the contract's `precise::exp` stands. -`gate_attn_kernel` (section 4) inlines the same function. The elementwise spec (`spec-kernels-elem.md`) and the hc lane's router spec (§9 Q1) raise the same -question. +step that writes a subnormal (k = 0, f < 0), so it is `ieee_mul`. A NaN d gives a NaN e. `nv_expf` reproduces +every operation but `ex2.approx`, which follows the contract's own mapping. The owner chose the transcription on +October 24, 2026, for this function and for `powf`, `cosf`, `sinf` and `log1pf`, as for the sampler's `exp` and +`logf`: Metal's `precise::exp` is a different function, and its bits differ from `__nv_expf`'s wherever the two +round differently. `gate_attn_kernel` (section 4) inlines the same function. The same choice answers the question +the elementwise spec (`spec-kernels-elem.md`) and the hc lane's router spec (§9 Q1) raise. ### `route_kernel<16>` (`:626-664`) @@ -491,7 +486,7 @@ question. | `:635` | `v[i] = lg[lane + i * 32]`, i = 0..15 | 16 `LDG`s | the same loads, one SIMD-group per token | | `:638` | `mx = fmaxf(mx, v[i])` from `-INFINITY`, i ascending | `FMNMX mx, v0, -INF, !PT`, then `FMNMX` with v1..v15 in order | `fmaxf_bits(mx, v[i])`: the other operand for a NaN, the larger by key. mx is never NaN (−inf if every logit is) | | `:639` | `warp_max`: `v = fmaxf(v, __shfl_xor_sync(.., v, o))`, o = 16..1 (`:26-30`) | `SHFL.BFLY`; `FMNMX` | `fmaxf_bits(v, simd_shuffle_xor(v, o))`, o = 16, 8, 4, 2, 1 | -| `:642` | `v[i] = expf(v[i] - mx)` | `FADD d, v, -mx`, then the sequence above | `nv_expf(v - mx)` as proposed (the contract: `precise::exp`, pending the owner; above); plain `-`: a d that Metal reads differently is so small that e = 1 on both | +| `:642` | `v[i] = expf(v[i] - mx)` | `FADD d, v, -mx`, then the sequence above | `nv_expf(v - mx)` (above); plain `-`: a d that Metal reads differently is so small that e = 1 on both | | `:642` | `sum += v[i]` from `0.0f`, i ascending | `FADD sum, RZ, e0` (0 + e0), then `FADD` with e1..e15 in order | `sum = ieee_add(sum, e)` from `0.0f`, i ascending | | `:643` | `1.0f / warp_sum(sum)` | warp_sum; rcp.rn (sigm's fast path, slow path `__cuda_sm20_rcp_rn_f32_slowpath`) | `1.0f / warp_sum_ieee(sum)`. For finite logits the sum is in [1, 512] (the maximum's e is exactly 1), so the reciprocal is normal and Metal's `/` gives its bits; a NaN sum gives NaN | | `:645` | `v[i] *= rcp; if (isnan(v[i])) v[i] = -FLT_MAX;` | `FMUL v, e, rcp`; `FSETP.NAN.AND P, PT, \|v\|, \|v\|, PT`; `FSEL v, v, -3.40282346638528859812e+38, !P` | `v = ieee_mul(e, rcp); v = isnan(v) ? -FLT_MAX : v` | @@ -749,7 +744,7 @@ constants, and ptxas fuses `__nv_expf`'s last multiply with the `1.0f +`. | Line | Expression | SASS | Metal | |---|---|---|---| -| `:770` | `expf(-q)`, q = `qf[t * 24 * 512 + h * 512 + 256 + d]` | `FFMA.SAT t, q, -R9, 0.5` (R9 = 0x3BBB989D); `FFMA.RM j, t, R11, 12582913` (R11 = 252); `FADD n, j, -12583039`; `IMAD.SHL.U32 s, j, 0x800000`; `FFMA f, q, -1.4426950216293334961, -n`; `FFMA f, q, -1.925963033500011079e-08, f`; `MUFU.EX2 x, f` | `e = nv_expf(-q)` as proposed (the contract: `precise::exp`, pending the owner; section 3): fma(q, −c, 0.5) and fma(−q, c, 0.5) are the same exact value, so the folded negation changes no bit | +| `:770` | `expf(-q)`, q = `qf[t * 24 * 512 + h * 512 + 256 + d]` | `FFMA.SAT t, q, -R9, 0.5` (R9 = 0x3BBB989D); `FFMA.RM j, t, R11, 12582913` (R11 = 252); `FADD n, j, -12583039`; `IMAD.SHL.U32 s, j, 0x800000`; `FFMA f, q, -1.4426950216293334961, -n`; `FFMA f, q, -1.925963033500011079e-08, f`; `MUFU.EX2 x, f` | `e = nv_expf(-q)` (section 3): fma(q, −c, 0.5) and fma(−q, c, 0.5) are the same exact value, so the folded negation changes no bit | | `:770` | `1.0f + e` | `FFMA den, s, x, 1`: the scale multiply s · x and the add in one rounding | `1.0f + e`. s is a power of two, so s · x is exact whenever it is normal and `nv_expf` returns it unrounded; when it is below 2^-126, 1 + it rounds to 1 whichever way it was formed. A product above `FLT_MAX` is +inf on both. So the fused and the unfused forms give the same den, at least 1 | | `:770` | `1.0f / den` | rcp.rn: the range test `IADD3`, `LOP3.LUT`, `ISETP.GT.U32`; `MUFU.RCP r, den`; `FFMA d, den, r, -1`; `FADD.FTZ d, -d, -RZ`; `FFMA r, r, d, r`; else `__cuda_sm20_rcp_rn_f32_slowpath` | `ieee_div(1.0f, den)` (`basalt_q8_1.metal:181`, divisor at least 1): r is subnormal for den above 2^126, q below about −87.3, and +0 once den is +inf | | `:770` | `a[i] * r` | `FMUL p, a, r` | `ieee_mul(a, r)`: a subnormal r times an infinite a is ±inf in CUDA (stored as fp16 ±inf) but 0 · inf = NaN in Metal. For a finite a (an attention output, at most 65504 in magnitude when V is finite) and any subnormal operand, the product is below 2^-110 and rounds to the fp16 zero of its sign either way |