diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 94ff0ff6..16dfc77a 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -95,6 +95,8 @@ jobs: python3 tools/verify_fusion_lut.py python3 tools/verify_chained_fusion.py python3 tools/verify_patch_proof.py + python3 tools/select_tree_lut.py --self-test + python3 tools/test_select_tree_lut.py -v python3 tools/colab_tpu_bench.py --self-test python3 tools/h100_fast_kernels.py --self-test python3 tools/test_h100_fast_kernels.py -v diff --git a/freetile/CMakeLists.txt b/freetile/CMakeLists.txt index 4179fda2..8d74cf1c 100644 --- a/freetile/CMakeLists.txt +++ b/freetile/CMakeLists.txt @@ -7,6 +7,7 @@ set(CMAKE_CXX_EXTENSIONS OFF) add_library(freetile STATIC src/tile_ir.cpp + src/select_tree_lut.cpp src/mosaic_emitter.cpp src/buenos_emitter.cpp src/buenos_splines.cpp @@ -32,6 +33,13 @@ target_compile_options(test_splines_and_flash_attn PRIVATE -Wall -Wextra -Wpedantic -Werror -fno-exceptions -fno-rtti) add_test(NAME freetile_splines_flash_attn_tests COMMAND test_splines_and_flash_attn) +add_executable(test_select_tree_lut + tests/test_select_tree_lut.cpp +) +target_link_libraries(test_select_tree_lut PRIVATE freetile) +target_compile_options(test_select_tree_lut PRIVATE -Wall -Wextra -Wpedantic -Werror) +add_test(NAME freetile_select_tree_lut_tests COMMAND test_select_tree_lut) + option(FREETILE_BUILD_BUENOS_PARITY_TEST "Build bit-exact parity test against sibling libopenbuenos" ON) option(FREETILE_BUILD_DIGITAL_TWIN "Build freetile-twin digital twin library, CLI, and tests" ON) diff --git a/freetile/Makefile b/freetile/Makefile index 4f1507ce..437586c2 100644 --- a/freetile/Makefile +++ b/freetile/Makefile @@ -23,6 +23,7 @@ LDFLAGS := -lm -lpthread CORE_SRCS := \ $(THIS_DIR)/src/tile_ir.cpp \ + $(THIS_DIR)/src/select_tree_lut.cpp \ $(THIS_DIR)/src/mosaic_emitter.cpp \ $(THIS_DIR)/src/buenos_emitter.cpp \ $(THIS_DIR)/src/buenos_splines.cpp \ @@ -31,6 +32,7 @@ CORE_SRCS := \ CORE_HDRS := \ $(THIS_DIR)/include/freetile/tile_ir.hpp \ + $(THIS_DIR)/include/freetile/select_tree_lut.hpp \ $(THIS_DIR)/include/freetile/mosaic_emitter.hpp \ $(THIS_DIR)/include/freetile/buenos_emitter.hpp \ $(THIS_DIR)/include/freetile/buenos_splines.hpp \ @@ -53,13 +55,14 @@ TEST_FREETILE := $(BUILD_DIR)/test_freetile TEST_SPLINES := $(BUILD_DIR)/test_splines_and_flash_attn TEST_PARITY := $(BUILD_DIR)/test_buenos_parity TEST_TWIN := $(BUILD_DIR)/test_freetile_twin +TEST_SELECT_TREE := $(BUILD_DIR)/test_select_tree_lut .PHONY: all host twin test verify-header clean openbuenos-host all: host host: $(FREETILE_LIB) $(FREETILE_TWIN_LIB) $(TWIN_CLI) $(ROOT_TWIN_CLI) \ - $(TEST_FREETILE) $(TEST_SPLINES) $(TEST_PARITY) $(TEST_TWIN) + $(TEST_FREETILE) $(TEST_SPLINES) $(TEST_PARITY) $(TEST_TWIN) $(TEST_SELECT_TREE) twin: $(TWIN_CLI) $(ROOT_TWIN_CLI) @@ -109,15 +112,20 @@ $(TEST_TWIN): $(THIS_DIR)/tests/test_freetile_twin.cpp $(TWIN_HDR) $(FREETILE_TW @mkdir -p $(dir $@) $(HOST_CXX) $(CXXFLAGS_NOEXC) $< $(FREETILE_TWIN_LIB) $(FREETILE_LIB) $(OB_LIB) -o $@ $(LDFLAGS) +$(TEST_SELECT_TREE): $(THIS_DIR)/tests/test_select_tree_lut.cpp $(FREETILE_LIB) $(CORE_HDRS) + @mkdir -p $(dir $@) + $(HOST_CXX) $(CXXFLAGS_BASE) $< $(FREETILE_LIB) -o $@ $(LDFLAGS) + verify-header: $(TWIN_HDR) $(HOST_CC) -x c -std=c11 -fsyntax-only -Wall -Wextra -Wpedantic -Werror $< $(HOST_CXX) -x c++ -std=c++17 -fsyntax-only -Wall -Wextra -Wpedantic -Werror $< -test: verify-header $(TEST_FREETILE) $(TEST_SPLINES) $(TEST_PARITY) $(TEST_TWIN) $(ROOT_TWIN_CLI) +test: verify-header $(TEST_FREETILE) $(TEST_SPLINES) $(TEST_PARITY) $(TEST_TWIN) $(TEST_SELECT_TREE) $(ROOT_TWIN_CLI) $(TEST_FREETILE) $(TEST_SPLINES) $(TEST_PARITY) $(TEST_TWIN) + $(TEST_SELECT_TREE) clean: rm -rf $(THIS_DIR)/build $(ROOT_TWIN_CLI) diff --git a/freetile/README.md b/freetile/README.md index afbde891..3657889a 100644 --- a/freetile/README.md +++ b/freetile/README.md @@ -9,6 +9,8 @@ - `ChipTarget` / `TargetProfile` (`V5E`, `V6E`, `TPU7X`, `BUENOS_A0`) - `TileGrid`, `SramTile`, `DmaPrefetch`, `QuantFormat` (`NONE`, `Q4_K`, `Q6_K`, `Q4_0`, `Q8_0`), `EpilogueActivation` (`NONE`, `RELU`, `RELU6`, `SILU`, `GELU`), `TileMatmul`, `TileKernel` - `TilePlannerConfig` & `TileScheduleHookFn` extension seam allowing external runtime/tuning layers to override `(bm, bn, bk)` schedules with zero fork. +- **Branchless VREG Select-Tree LUT (`include/freetile/select_tree_lut.hpp`, freetpu#43):** + - Replaces dynamic-gather 4-bit codebook lookup with a 4-level branchless select tree (8→4→2→1 = 15 selects, zero `gather`) for `IQ4_XS`/`IQ4_NL` (`kvalues_iq4nl`), `NF4`, and `FP4` (E2M1); 2/3-bit tables truncate the same tree (3/7 selects). New `QuantFormat::IQ4_XS/IQ4_NL/NF4/FP4` plan as U4 on `V5E`/`V6E` for non-power-of-2 MoE shapes (`2304`, `3072`, `4096`, `6144`), lower through StableHLO (`llama-cpp-cloudtpu` `emit_select_tree_lut4_program`), and are refused by the Mosaic uitofp path. Host-verified `0.0` max abs diff vs reference dequant+matmul (see `../proof/cloud-tpu-iq4xs-select-tree/PROOF.md`); no live-silicon timing is claimed by the host proof. - **Cloud TPU Mosaic Lowering (`include/freetile/mosaic_emitter.hpp`):** - Lowers `TileKernel` descriptors directly to `stable_mosaic.*` MLIR (`stable_mosaic.version = 17`) with RFC 4648 base64 encoding (`serialization_format = 1`) for `stablehlo.custom_call @tpu_custom_call`. - Integrated into `llama-cpp-cloudtpu` behind `CLOUDTPU_FREETILE_MOSAIC=1`, with automatic runtime fallback to pure StableHLO (`Q4_K_I4`, `Q6_K_SPLIT`, `Q4_0_I4`, `Q8_0_SPLIT`) if compilation or dialect version fails. diff --git a/freetile/include/freetile/select_tree_lut.hpp b/freetile/include/freetile/select_tree_lut.hpp new file mode 100644 index 00000000..fd2b7b91 --- /dev/null +++ b/freetile/include/freetile/select_tree_lut.hpp @@ -0,0 +1,137 @@ +#pragma once +// SPDX-License-Identifier: Apache-2.0 +// Branchless VREG select-tree LUT for 4-bit codebooks (freesilicon/freetpu#43). +// +// On Cloud TPU v5e/v6e, lowering a 16-entry codebook lookup as a dynamic +// memory `gather` hits a compiler cliff on non-power-of-2 MoE shapes +// (e.g. 2304x2304). This module replaces the gather with a 4-level +// branchless select tree over the 4 index bits: +// +// level 0 (b0): 8 selects s_i = select(b0, T[2i+1], T[2i]) +// level 1 (b1): 4 selects +// level 2 (b2): 2 selects +// level 3 (b3): 1 select -> T[idx] +// +// 15 selects total, zero dynamic gather, all operands are VREG-resident +// constants. The host reference below, the StableHLO emission, and the +// Python mirror (tools/select_tree_lut.py) implement the identical tree, +// so dequantization is bit-exact (0.0 max abs diff) vs direct table +// indexing by construction: every select picks a verbatim table entry. +// +// Narrower codebooks compose on the same primitive: a 2-bit table needs +// levels {b0,b1} (3 selects) and a 3-bit table levels {b0,b1,b2} +// (7 selects) — see select_tree_f32(). Grid codebooks (IQ2_XXS/IQ3_XXS +// style) apply the primitive per scalar sub-lookup. + +#include +#include +#include +#include +#include + +namespace freetile { + +enum class Codebook4 { + IQ4_NL = 0, // GGUF IQ4_NL (also the IQ4_XS table) + IQ4_XS = 1, // GGUF IQ4_XS (identical 16-entry table to IQ4_NL) + NF4 = 2, // NormalFloat4 (QLoRA) + FP4_E2M1 = 3 // OCP FP4 E2M1, nibble = sign(1) exp(2) mantissa(1) +}; + +const char* codebook4_name(Codebook4 cb); + +// 16-entry table as exact float values. IQ4 entries are the int8 +// kvalues_iq4nl codebook widened to float (exact for |v| <= 127). +const std::array& codebook4_table_f32(Codebook4 cb); +extern const std::array kValuesIq4Nl; + +// --- Core branchless select tree (host scalar reference) ------------------ + +// Mask blend on integers: branchless by construction (no data-dependent +// branch, no indexed load). +constexpr int32_t select_i32(uint32_t bit, int32_t on_true, int32_t on_false) { + const int32_t mask = -static_cast(bit & 1u); + return (on_true & mask) | (on_false & ~mask); +} +constexpr float select_f32(uint32_t bit, float on_true, float on_false) { + return (bit & 1u) ? on_true : on_false; // lowers to a single select/csel +} + +// 4-bit select tree: 8 -> 4 -> 2 -> 1 selects. `idx` is masked to 4 bits. +constexpr float select_tree4_f32(uint32_t idx, const float* table16) { + const uint32_t b0 = (idx >> 0) & 1u, b1 = (idx >> 1) & 1u; + const uint32_t b2 = (idx >> 2) & 1u, b3 = (idx >> 3) & 1u; + const float l0[8] = {select_f32(b0, table16[1], table16[0]), select_f32(b0, table16[3], table16[2]), + select_f32(b0, table16[5], table16[4]), select_f32(b0, table16[7], table16[6]), + select_f32(b0, table16[9], table16[8]), select_f32(b0, table16[11], table16[10]), + select_f32(b0, table16[13], table16[12]), select_f32(b0, table16[15], table16[14])}; + const float l1[4] = {select_f32(b1, l0[1], l0[0]), select_f32(b1, l0[3], l0[2]), + select_f32(b1, l0[5], l0[4]), select_f32(b1, l0[7], l0[6])}; + const float l2[2] = {select_f32(b2, l1[1], l1[0]), select_f32(b2, l1[3], l1[2])}; + return select_f32(b3, l2[1], l2[0]); +} + +constexpr int32_t select_tree4_i32(uint32_t idx, const int32_t* table16) { + const uint32_t b0 = (idx >> 0) & 1u, b1 = (idx >> 1) & 1u; + const uint32_t b2 = (idx >> 2) & 1u, b3 = (idx >> 3) & 1u; + const int32_t l0[8] = {select_i32(b0, table16[1], table16[0]), select_i32(b0, table16[3], table16[2]), + select_i32(b0, table16[5], table16[4]), select_i32(b0, table16[7], table16[6]), + select_i32(b0, table16[9], table16[8]), select_i32(b0, table16[11], table16[10]), + select_i32(b0, table16[13], table16[12]), select_i32(b0, table16[15], table16[14])}; + const int32_t l1[4] = {select_i32(b1, l0[1], l0[0]), select_i32(b1, l0[3], l0[2]), + select_i32(b1, l0[5], l0[4]), select_i32(b1, l0[7], l0[6])}; + const int32_t l2[2] = {select_i32(b2, l1[1], l1[0]), select_i32(b2, l1[3], l1[2])}; + return select_i32(b3, l2[1], l2[0]); +} + +// Generic 1..4-bit tree over `table[0..2^bits)`. This is how 2/3-bit +// codebooks (IQ2/IQ3-style scalar sub-lookups) compose: same levels, +// truncated at `bits` (3 / 7 selects instead of 15). +float select_tree_f32(uint32_t idx, const float* table, uint32_t bits); + +// Number of select ops in a `bits`-wide tree: 2^bits - 1. +// Hardened against shift UB for bits >= 32: saturates to UINT32_MAX. +constexpr uint32_t select_tree_select_count(uint32_t bits) { + return bits >= 32u ? 0xFFFFFFFFu + : static_cast((1ULL << bits) - 1ULL); +} + +// --- GGUF block layouts (byte-identical to libopenbuenos) ----------------- +#pragma pack(push, 1) +struct BlockIq4Nl { uint16_t d; uint8_t qs[16]; }; // 18 B / 32 +struct BlockIq4Xs { uint16_t d; uint16_t scales_h; uint8_t scales_l[4]; uint8_t qs[128]; }; // 136 B / 256 +#pragma pack(pop) +static_assert(sizeof(BlockIq4Nl) == 18u, "BlockIq4Nl must be 18 bytes"); +static_assert(sizeof(BlockIq4Xs) == 136u, "BlockIq4Xs must be 136 bytes"); + +float fp16_to_f32(uint16_t h); + +// Dequantizers. `use_select_tree=true` resolves every nibble through the +// branchless tree; `false` is the direct-index reference. Both paths apply +// identical scale arithmetic, so outputs are bit-identical. +void dequant_iq4_nl_row(const void* blocks, uint32_t k, float* out, bool use_select_tree); +void dequant_iq4_xs_row(const void* blocks, uint32_t k, float* out, bool use_select_tree); + +// Sequential nibble-packed NF4/FP4 row: byte i holds elements 2i (low +// nibble) and 2i+1 (high nibble); one float scale per 32 elements. +void dequant_codebook4_row(Codebook4 cb, const uint8_t* nibbles, const float* scales32, + uint32_t k, float* out, bool use_select_tree); + +// C[MxN] = A[MxK] @ dequant(W)^T with W as N IQ4_XS rows of width K. +// Accumulation is float, k-ascending, identical in both paths. +void iq4xs_dequant_matmul(const float* a_mk, const void* w_blocks_nk, float* c_mn, + uint32_t m, uint32_t k, uint32_t n, bool use_select_tree); + +// --- IR emission ----------------------------------------------------------- +// Emits the select tree as StableHLO MLIR ops on tensor index +// SSA value `idx_ssa` (e.g. "%arg0"), returning the MLIR text. The result +// SSA name is written to *out_ssa. Contains exactly 15 stablehlo.select +// ops and zero gather ops. SSA numbering starts at `ssa_start`. +std::string emit_stablehlo_select_tree_lut4(const std::string& idx_ssa, + const std::vector& dims, Codebook4 cb, + int ssa_start, std::string* out_ssa); + +// Counts `"stablehlo.select"` / gather ops in emitted MLIR (test/CI helper). +size_t count_mlir_ops(const std::string& mlir, const std::string& needle); + +} // namespace freetile diff --git a/freetile/include/freetile/tile_ir.hpp b/freetile/include/freetile/tile_ir.hpp index 5d05be2f..96a426f4 100644 --- a/freetile/include/freetile/tile_ir.hpp +++ b/freetile/include/freetile/tile_ir.hpp @@ -62,11 +62,18 @@ enum class QuantFormat { Q6_K, Q4_0, Q8_0, + IQ4_XS, // 16-entry codebook, branchless select-tree LUT (freetpu#43) + IQ4_NL, // 16-entry codebook, branchless select-tree LUT + NF4, // 16-entry NormalFloat4 codebook, select-tree LUT + FP4, // 16-entry OCP FP4 E2M1 codebook, select-tree LUT }; const char* quant_format_name(QuantFormat fmt); int64_t quant_block_size(QuantFormat fmt); bool quant_has_min(QuantFormat fmt); +// True for 4-bit codebook formats lowered via the branchless VREG +// select-tree LUT instead of a dynamic gather (see select_tree_lut.hpp). +bool quant_is_codebook4(QuantFormat fmt); enum class MemorySpace { HBM = 0, diff --git a/freetile/src/mosaic_emitter.cpp b/freetile/src/mosaic_emitter.cpp index 2c1f9671..3eead46c 100644 --- a/freetile/src/mosaic_emitter.cpp +++ b/freetile/src/mosaic_emitter.cpp @@ -165,6 +165,14 @@ MosaicEmitResult emit_mosaic_kernel(const TileKernel& kernel, int64_t mosaic_ver throw std::runtime_error(std::string("emit_mosaic_kernel: target ") + prof.name + " does not support Mosaic tpu_custom_call"); } + if (quant_is_codebook4(kernel.matmul.quant)) { + // Codebook indices must resolve through the branchless select-tree + // LUT (select_tree_lut.hpp / StableHLO path), never a numeric + // uitofp + scale, which would dequantize to wrong values. + throw std::runtime_error( + "emit_mosaic_kernel: codebook quant format requires the StableHLO " + "select-tree LUT lowering (freetpu#43), not Mosaic uitofp dequant"); + } if (kernel.matmul.activation != EpilogueActivation::NONE) { throw std::runtime_error(std::string("emit_mosaic_kernel: fused epilogue activation ") + epilogue_activation_name(kernel.matmul.activation) + diff --git a/freetile/src/select_tree_lut.cpp b/freetile/src/select_tree_lut.cpp new file mode 100644 index 00000000..b1f4cb3c --- /dev/null +++ b/freetile/src/select_tree_lut.cpp @@ -0,0 +1,302 @@ +// SPDX-License-Identifier: Apache-2.0 +#include "freetile/select_tree_lut.hpp" + +#include +#include +#include +#include +#include + +namespace freetile { + +const std::array kValuesIq4Nl = {-127, -104, -83, -65, -49, -35, -22, -10, + 1, 13, 25, 38, 53, 69, 89, 113}; + +namespace { +std::array iq4_table() { + std::array t{}; + for (size_t i = 0; i < 16; ++i) t[i] = static_cast(kValuesIq4Nl[i]); + return t; +} +const std::array kIq4 = iq4_table(); +// NormalFloat4 codebook (Dettmers et al., QLoRA), float32 values. +const std::array kNf4 = { + -1.0f, -0.6961928009986877f, -0.5250730514526367f, -0.39491748809814453f, + -0.28444138169288635f, -0.18477343022823334f, -0.09105003625154495f, 0.0f, + 0.07958029955618668f, 0.16093020141124725f, 0.24611230194568634f, 0.33791524171829224f, + 0.44070982933044434f, 0.5626170039176941f, 0.7229568362236023f, 1.0f}; +// OCP FP4 E2M1: nibble bits [sign|exp1 exp0|mantissa]. +const std::array kFp4 = {0.0f, 0.5f, 1.0f, 1.5f, 2.0f, 3.0f, 4.0f, 6.0f, + -0.0f, -0.5f, -1.0f, -1.5f, -2.0f, -3.0f, -4.0f, -6.0f}; + +uint16_t load_u16(const void* p) { uint16_t v; std::memcpy(&v, p, 2); return v; } +inline float lut4(uint32_t idx, const float* t, bool tree) { + return tree ? select_tree4_f32(idx & 0xFu, t) : t[idx & 0xFu]; +} +std::ostringstream classic_stream() { std::ostringstream o; o.imbue(std::locale::classic()); return o; } +std::string f32_literal(float v) { + auto o = classic_stream(); + o << std::scientific << std::setprecision(8) << v; + return o.str(); +} +std::string tensor_type(const std::vector& dims, const char* elem) { + auto o = classic_stream(); + o << "tensor<"; + for (int64_t d : dims) o << d << "x"; + o << elem << ">"; + return o.str(); +} +} // namespace + +const char* codebook4_name(Codebook4 cb) { + switch (cb) { + case Codebook4::IQ4_NL: return "iq4_nl"; + case Codebook4::IQ4_XS: return "iq4_xs"; + case Codebook4::NF4: return "nf4"; + case Codebook4::FP4_E2M1: return "fp4_e2m1"; + } + return "unknown"; +} + +const std::array& codebook4_table_f32(Codebook4 cb) { + switch (cb) { + case Codebook4::IQ4_NL: + case Codebook4::IQ4_XS: return kIq4; + case Codebook4::NF4: return kNf4; + case Codebook4::FP4_E2M1: return kFp4; + } + return kIq4; +} + +float select_tree_f32(uint32_t idx, const float* table, uint32_t bits) { + if (bits == 0 || bits > 4) throw std::invalid_argument("select_tree_f32: bits must be 1..4"); + float level[16]; + const uint32_t n = 1u << bits; + for (uint32_t i = 0; i < n; ++i) level[i] = table[i]; + uint32_t count = n; + for (uint32_t b = 0; b < bits; ++b) { + const uint32_t bit = (idx >> b) & 1u; + count /= 2; + for (uint32_t i = 0; i < count; ++i) + level[i] = select_f32(bit, level[2 * i + 1], level[2 * i]); + } + return level[0]; +} + +float fp16_to_f32(uint16_t h) { + const uint32_t sign = (h >> 15) & 1u, exp = (h >> 10) & 0x1Fu, frac = h & 0x3FFu; + uint32_t bits; + if (exp == 0) { + if (frac == 0) { bits = sign << 31; } + else { // subnormal: normalize + uint32_t f = frac; int e = -14; + while ((f & 0x400u) == 0) { f <<= 1; --e; } + bits = (sign << 31) | (static_cast(e + 127) << 23) | ((f & 0x3FFu) << 13); + } + } else if (exp == 0x1Fu) { + bits = (sign << 31) | (0xFFu << 23) | (frac << 13); + } else { + bits = (sign << 31) | ((exp - 15 + 127) << 23) | (frac << 13); + } + float out; std::memcpy(&out, &bits, 4); return out; +} + +void dequant_iq4_nl_row(const void* blocks, uint32_t k, float* out, bool tree) { + if (!blocks || !out) throw std::invalid_argument("dequant_iq4_nl_row: null pointer"); + if (k == 0) return; + const auto* blks = static_cast(blocks); + const float* t = codebook4_table_f32(Codebook4::IQ4_NL).data(); + const uint32_t nb_full = k / 32; + const uint32_t rem = k % 32; + for (uint32_t b = 0; b < nb_full; ++b) { + const float d = fp16_to_f32(load_u16(&blks[b].d)); + float* y = out + b * 32; + for (uint32_t j = 0; j < 16; ++j) { + const uint8_t byte = blks[b].qs[j]; + y[j] = d * lut4(byte & 0xFu, t, tree); + y[j + 16] = d * lut4(byte >> 4, t, tree); + } + } + if (rem) { + const uint32_t b = nb_full; + const float d = fp16_to_f32(load_u16(&blks[b].d)); + float* y = out + b * 32; + const uint32_t take = rem < 16 ? rem : 16; + for (uint32_t j = 0; j < take; ++j) { + const uint8_t byte = blks[b].qs[j]; + y[j] = d * lut4(byte & 0xFu, t, tree); + } + if (rem > 16) { + const uint32_t hi = rem - 16; + for (uint32_t j = 0; j < hi; ++j) { + const uint8_t byte = blks[b].qs[j]; + y[16 + j] = d * lut4(byte >> 4, t, tree); + } + } + } +} + +void dequant_iq4_xs_row(const void* blocks, uint32_t k, float* out, bool tree) { + if (!blocks || !out) throw std::invalid_argument("dequant_iq4_xs_row: null pointer"); + if (k == 0) return; + const auto* blks = static_cast(blocks); + const float* t = codebook4_table_f32(Codebook4::IQ4_XS).data(); + const uint32_t nsb_full = k / 256; + const uint32_t rem256 = k % 256; + for (uint32_t sb = 0; sb < nsb_full; ++sb) { + const BlockIq4Xs& blk = blks[sb]; + const float d = fp16_to_f32(load_u16(&blk.d)); + const uint16_t scales_h = load_u16(&blk.scales_h); + const uint8_t* qs = blk.qs; + float* y = out + sb * 256; + for (uint32_t ib = 0; ib < 8; ++ib) { + const int32_t ls = static_cast( + ((blk.scales_l[ib / 2] >> (4u * (ib & 1u))) & 0x0Fu) | + (((scales_h >> (2u * ib)) & 3u) << 4)); + const float dl = d * static_cast(ls - 32); + for (uint32_t j = 0; j < 16; ++j) { + const uint8_t byte = qs[j]; + y[j] = dl * lut4(byte & 0xFu, t, tree); + y[j + 16] = dl * lut4(byte >> 4, t, tree); + } + y += 32; qs += 16; + } + } + if (rem256) { + const uint32_t sb = nsb_full; + const BlockIq4Xs& blk = blks[sb]; + const float d = fp16_to_f32(load_u16(&blk.d)); + const uint16_t scales_h = load_u16(&blk.scales_h); + const uint8_t* qs = blk.qs; + float* y = out + sb * 256; + for (uint32_t ib = 0; ib < 8; ++ib) { + const uint32_t base = ib * 32; + if (base >= rem256) break; + const uint32_t want = rem256 - base < 32 ? rem256 - base : 32; + const int32_t ls = static_cast( + ((blk.scales_l[ib / 2] >> (4u * (ib & 1u))) & 0x0Fu) | + (((scales_h >> (2u * ib)) & 3u) << 4)); + const float dl = d * static_cast(ls - 32); + const uint8_t* qib = qs + ib * 16; + if (want <= 16) { + for (uint32_t j = 0; j < want; ++j) { + const uint8_t byte = qib[j]; + y[j] = dl * lut4(byte & 0xFu, t, tree); + } + } else { + for (uint32_t j = 0; j < 16; ++j) { + const uint8_t byte = qib[j]; + y[j] = dl * lut4(byte & 0xFu, t, tree); + } + const uint32_t hi = want - 16; + for (uint32_t j = 0; j < hi; ++j) { + const uint8_t byte = qib[j]; + y[16 + j] = dl * lut4(byte >> 4, t, tree); + } + } + y += 32; + } + } +} + +void dequant_codebook4_row(Codebook4 cb, const uint8_t* nibbles, const float* scales32, + uint32_t k, float* out, bool tree) { + if (!nibbles || !scales32 || !out) throw std::invalid_argument("dequant_codebook4_row: null pointer"); + if (k == 0) return; + const float* t = codebook4_table_f32(cb).data(); + for (uint32_t i = 0; i < k; ++i) { + const uint8_t byte = nibbles[i / 2]; + const uint32_t idx = (i & 1u) ? (byte >> 4) : (byte & 0xFu); + out[i] = scales32[i / 32] * lut4(idx, t, tree); + } +} + +void iq4xs_dequant_matmul(const float* a_mk, const void* w_blocks_nk, float* c_mn, + uint32_t m, uint32_t k, uint32_t n, bool tree) { + if (!a_mk || !w_blocks_nk || !c_mn) throw std::invalid_argument("iq4xs_dequant_matmul: null pointer"); + if (m == 0 || n == 0 || k == 0) return; + if (k % 256 != 0) { + // Allow non-multiple K but require correct ceil row stride; partial tails are + // handled by dequant_iq4_xs_row. This keeps the byte layout ceil(K/256)*136. + } + const size_t nsb = (static_cast(k) + 255u) / 256u; + const size_t row_bytes = nsb * sizeof(BlockIq4Xs); + std::vector wrow(k); + for (uint32_t ni = 0; ni < n; ++ni) { + dequant_iq4_xs_row(static_cast(w_blocks_nk) + ni * row_bytes, k, + wrow.data(), tree); + for (uint32_t mi = 0; mi < m; ++mi) { + const float* a = a_mk + static_cast(mi) * k; + float acc = 0.0f; + for (uint32_t ki = 0; ki < k; ++ki) acc += a[ki] * wrow[ki]; + c_mn[static_cast(mi) * n + ni] = acc; + } + } +} + +std::string emit_stablehlo_select_tree_lut4(const std::string& idx_ssa, + const std::vector& dims, Codebook4 cb, + int ssa_start, std::string* out_ssa) { + if (dims.empty()) throw std::invalid_argument("emit_stablehlo_select_tree_lut4: dims empty"); + for (int64_t d : dims) + if (d <= 0) throw std::invalid_argument("emit_stablehlo_select_tree_lut4: dims must be positive"); + const std::string ui32_t = tensor_type(dims, "ui32"); + const std::string pred_t = tensor_type(dims, "i1"); + const std::string f32_t = tensor_type(dims, "f32"); + auto body = classic_stream(); + int next = ssa_start; + auto fresh = [&]() { return "%sel" + std::to_string(next++); }; + body << " // freetpu#43 branchless VREG select-tree LUT (" << codebook4_name(cb) + << "): 15 selects, 0 gather\n"; + // Bit predicates b0..b3 = ((idx >> b) & 1) != 0. + std::string pred[4]; + const std::string zero = fresh(); + body << " " << zero << " = stablehlo.constant dense<0> : " << ui32_t << "\n"; + for (int b = 0; b < 4; ++b) { + std::string bits = idx_ssa; + if (b > 0) { + const std::string sh = fresh(), shamt = fresh(); + body << " " << shamt << " = stablehlo.constant dense<" << b << "> : " << ui32_t << "\n"; + body << " " << sh << " = stablehlo.shift_right_logical " << idx_ssa << ", " << shamt + << " : " << ui32_t << "\n"; + bits = sh; + } + const std::string one = fresh(), bitv = fresh(); + body << " " << one << " = stablehlo.constant dense<1> : " << ui32_t << "\n"; + body << " " << bitv << " = stablehlo.and " << bits << ", " << one << " : " << ui32_t << "\n"; + pred[b] = fresh(); + body << " " << pred[b] << " = stablehlo.compare NE, " << bitv << ", " << zero + << ", UNSIGNED : (" << ui32_t << ", " << ui32_t << ") -> " << pred_t << "\n"; + } + // Leaves: 16 splat constants, then 8->4->2->1 selects. + const auto& table = codebook4_table_f32(cb); + std::vector level; + for (int i = 0; i < 16; ++i) { + const std::string c = fresh(); + body << " " << c << " = stablehlo.constant dense<" << f32_literal(table[static_cast(i)]) + << "> : " << f32_t << "\n"; + level.push_back(c); + } + for (int b = 0; b < 4; ++b) { + std::vector up; + for (size_t i = 0; i + 1 < level.size(); i += 2) { + const std::string s = fresh(); + body << " " << s << " = \"stablehlo.select\"(" << pred[b] << ", " << level[i + 1] + << ", " << level[i] << ") : (" << pred_t << ", " << f32_t << ", " << f32_t + << ") -> " << f32_t << "\n"; + up.push_back(s); + } + level = std::move(up); + } + if (out_ssa) *out_ssa = level[0]; + return body.str(); +} + +size_t count_mlir_ops(const std::string& mlir, const std::string& needle) { + if (needle.empty()) return 0; + size_t count = 0, pos = 0; + while ((pos = mlir.find(needle, pos)) != std::string::npos) { ++count; pos += needle.size(); } + return count; +} + +} // namespace freetile diff --git a/freetile/src/tile_ir.cpp b/freetile/src/tile_ir.cpp index 09848cd3..a22f15e0 100644 --- a/freetile/src/tile_ir.cpp +++ b/freetile/src/tile_ir.cpp @@ -209,6 +209,10 @@ const char* quant_format_name(QuantFormat fmt) { case QuantFormat::Q6_K: return "q6_k"; case QuantFormat::Q4_0: return "q4_0"; case QuantFormat::Q8_0: return "q8_0"; + case QuantFormat::IQ4_XS: return "iq4_xs"; + case QuantFormat::IQ4_NL: return "iq4_nl"; + case QuantFormat::NF4: return "nf4"; + case QuantFormat::FP4: return "fp4"; default: return "unknown"; } } @@ -218,7 +222,13 @@ int64_t quant_block_size(QuantFormat fmt) { case QuantFormat::NONE: return 1; case QuantFormat::Q4_K: case QuantFormat::Q4_0: - case QuantFormat::Q8_0: return 32; + case QuantFormat::Q8_0: + // Codebook formats: one effective scale per 32 weights (IQ4_XS + // 256-superblock = 8x32 sub-blocks with pre-folded scales). + case QuantFormat::IQ4_XS: + case QuantFormat::IQ4_NL: + case QuantFormat::NF4: + case QuantFormat::FP4: return 32; case QuantFormat::Q6_K: return 16; default: return 0; } @@ -228,6 +238,11 @@ bool quant_has_min(QuantFormat fmt) { return fmt == QuantFormat::Q4_K; } +bool quant_is_codebook4(QuantFormat fmt) { + return fmt == QuantFormat::IQ4_XS || fmt == QuantFormat::IQ4_NL || + fmt == QuantFormat::NF4 || fmt == QuantFormat::FP4; +} + const char* memory_space_name(MemorySpace space) { switch (space) { case MemorySpace::HBM: return "hbm"; @@ -385,9 +400,11 @@ bool TileKernel::validate(std::string* err) const { return fail(err, "Quantized TileMatmul scale_dtype must be BF16 or F32"); } const DType expected_w_dt = - (matmul.quant == QuantFormat::Q4_K || matmul.quant == QuantFormat::Q4_0) - ? (matmul.unsigned_q4 ? DType::U4 : DType::S4) - : DType::S8; + quant_is_codebook4(matmul.quant) + ? DType::U4 // codebook indices are unsigned 4-bit + : (matmul.quant == QuantFormat::Q4_K || matmul.quant == QuantFormat::Q4_0) + ? (matmul.unsigned_q4 ? DType::U4 : DType::S4) + : DType::S8; if (matmul.weight_dtype != expected_w_dt) { return fail(err, "Quantized TileMatmul weight_dtype does not match QuantFormat/unsigned_q4"); } @@ -573,7 +590,9 @@ bool plan_quant_matmul_kernel(ChipTarget target, } DType w_dt = DType::BF16; - if (fmt == QuantFormat::Q4_K || fmt == QuantFormat::Q4_0) { + if (quant_is_codebook4(fmt)) { + w_dt = DType::U4; // unsigned codebook indices -> select-tree LUT + } else if (fmt == QuantFormat::Q4_K || fmt == QuantFormat::Q4_0) { w_dt = unsigned_q4 ? DType::U4 : DType::S4; } else if (fmt == QuantFormat::Q6_K || fmt == QuantFormat::Q8_0) { w_dt = DType::S8; diff --git a/freetile/tests/test_select_tree_lut.cpp b/freetile/tests/test_select_tree_lut.cpp new file mode 100644 index 00000000..29b30a41 --- /dev/null +++ b/freetile/tests/test_select_tree_lut.cpp @@ -0,0 +1,212 @@ +// Bit-exact (0.0 max abs diff) parity tests for the branchless VREG +// 4-bit select-tree LUT (freetpu#43): select-tree vs direct-index +// reference IQ4_XS/IQ4_NL dequant + matmul, NF4/FP4 codebooks, +// 2/3-bit composition, FreeTile planning on non-power-of-2 MoE shapes, +// and zero-gather StableHLO emission. +#include "freetile/mosaic_emitter.hpp" +#include "freetile/select_tree_lut.hpp" +#include "freetile/tile_ir.hpp" + +#include +#include +#include +#include +#include +#include +#include +#include +#include + +namespace { +int g_fail = 0; +#define CHECK(cond, msg) \ + do { \ + if (!(cond)) { \ + std::fprintf(stderr, "FAIL [%s:%d]: %s\n", __FILE__, __LINE__, msg); \ + ++g_fail; \ + return; \ + } \ + } while (0) + +uint16_t f32_to_fp16(float f) { // round-to-nearest-even, test data only + uint32_t x; std::memcpy(&x, &f, 4); + const uint32_t sign = (x >> 16) & 0x8000u; + int exp = static_cast((x >> 23) & 0xFFu) - 112; + uint32_t frac = x & 0x7FFFFFu; + if (exp <= 0) return static_cast(sign); + if (exp >= 31) return static_cast(sign | 0x7C00u); + uint32_t half = sign | (static_cast(exp) << 10) | (frac >> 13); + if ((frac & 0x1FFFu) > 0x1000u || ((frac & 0x1FFFu) == 0x1000u && (half & 1u))) ++half; + return static_cast(half); +} + +std::vector make_iq4xs_weights(uint32_t n, uint32_t k, uint32_t seed) { + std::mt19937 rng(seed); + std::vector raw(static_cast(n) * (k / 256) * sizeof(freetile::BlockIq4Xs)); + for (auto& b : raw) b = static_cast(rng() & 0xFFu); + // Force finite, non-denormal scales: d = 0.01f in every superblock. + auto* blks = reinterpret_cast(raw.data()); + const uint16_t d = f32_to_fp16(0.01f); + for (size_t i = 0; i < raw.size() / sizeof(freetile::BlockIq4Xs); ++i) + std::memcpy(&blks[i].d, &d, 2); + return raw; +} + +double max_abs_diff(const std::vector& a, const std::vector& b) { + double m = 0.0; + for (size_t i = 0; i < a.size(); ++i) m = std::max(m, std::fabs(static_cast(a[i] - b[i]))); + return m; +} + +void test_scalar_tree_exhaustive() { + for (auto cb : {freetile::Codebook4::IQ4_NL, freetile::Codebook4::IQ4_XS, + freetile::Codebook4::NF4, freetile::Codebook4::FP4_E2M1}) { + const auto& t = freetile::codebook4_table_f32(cb); + for (uint32_t idx = 0; idx < 16; ++idx) { + CHECK(freetile::select_tree4_f32(idx, t.data()) == t[idx], "select_tree4_f32 exhaustive"); + CHECK(freetile::select_tree_f32(idx, t.data(), 4) == t[idx], "select_tree_f32 bits=4"); + } + } + int32_t ti[16]; + for (int i = 0; i < 16; ++i) ti[i] = freetile::kValuesIq4Nl[static_cast(i)]; + for (uint32_t idx = 0; idx < 16; ++idx) + CHECK(freetile::select_tree4_i32(idx, ti) == ti[idx], "select_tree4_i32 exhaustive"); + CHECK(freetile::select_tree_select_count(4) == 15, "4-bit tree = 15 selects"); + CHECK(freetile::select_tree_select_count(3) == 7, "3-bit tree = 7 selects"); + CHECK(freetile::select_tree_select_count(2) == 3, "2-bit tree = 3 selects"); + // 2/3-bit composition on the same primitive (IQ2/IQ3-style sub-lookups). + const float t2[4] = {-1.5f, -0.5f, 0.25f, 2.0f}; + const float t3[8] = {-3.f, -2.f, -1.f, -0.125f, 0.125f, 1.f, 2.f, 3.f}; + for (uint32_t i = 0; i < 4; ++i) CHECK(freetile::select_tree_f32(i, t2, 2) == t2[i], "2-bit tree"); + for (uint32_t i = 0; i < 8; ++i) CHECK(freetile::select_tree_f32(i, t3, 3) == t3[i], "3-bit tree"); + bool threw = false; + try { (void)freetile::select_tree_f32(0, t2, 5); } catch (const std::invalid_argument&) { threw = true; } + CHECK(threw, "bits=5 rejected"); + std::printf("[PASS] test_scalar_tree_exhaustive\n"); +} + +void test_codebook_tables() { + const auto& iq = freetile::codebook4_table_f32(freetile::Codebook4::IQ4_XS); + CHECK(iq[0] == -127.0f && iq[7] == -10.0f && iq[8] == 1.0f && iq[15] == 113.0f, "IQ4 table values"); + CHECK(freetile::codebook4_table_f32(freetile::Codebook4::IQ4_NL) == iq, "IQ4_NL == IQ4_XS table"); + const auto& nf = freetile::codebook4_table_f32(freetile::Codebook4::NF4); + CHECK(nf[0] == -1.0f && nf[7] == 0.0f && nf[15] == 1.0f, "NF4 endpoints/zero"); + for (int i = 1; i < 16; ++i) CHECK(nf[static_cast(i)] > nf[static_cast(i - 1)], "NF4 monotonic"); + const auto& fp = freetile::codebook4_table_f32(freetile::Codebook4::FP4_E2M1); + CHECK(fp[0] == 0.0f && fp[1] == 0.5f && fp[6] == 4.0f && fp[7] == 6.0f && fp[15] == -6.0f, "FP4 E2M1 values"); + std::printf("[PASS] test_codebook_tables\n"); +} + +void test_dequant_bit_exact() { + std::mt19937 rng(1234); + // IQ4_NL rows. + { + std::vector raw(64 * sizeof(freetile::BlockIq4Nl)); + for (auto& b : raw) b = static_cast(rng() & 0xFFu); + auto* blks = reinterpret_cast(raw.data()); + const uint16_t d = f32_to_fp16(0.02f); + for (int i = 0; i < 64; ++i) std::memcpy(&blks[i].d, &d, 2); + std::vector a(2048), b(2048); + freetile::dequant_iq4_nl_row(raw.data(), 2048, a.data(), true); + freetile::dequant_iq4_nl_row(raw.data(), 2048, b.data(), false); + CHECK(max_abs_diff(a, b) == 0.0, "IQ4_NL dequant 0.0 diff"); + } + // NF4 + FP4 rows. + for (auto cb : {freetile::Codebook4::NF4, freetile::Codebook4::FP4_E2M1}) { + std::vector nib(1024); + for (auto& x : nib) x = static_cast(rng() & 0xFFu); + std::vector scales(64, 0.05f), a(2048), b(2048); + freetile::dequant_codebook4_row(cb, nib.data(), scales.data(), 2048, a.data(), true); + freetile::dequant_codebook4_row(cb, nib.data(), scales.data(), 2048, b.data(), false); + CHECK(max_abs_diff(a, b) == 0.0, "NF4/FP4 dequant 0.0 diff"); + } + std::printf("[PASS] test_dequant_bit_exact (IQ4_NL/NF4/FP4)\n"); +} + +void test_iq4xs_matmul_shapes() { + // Issue shapes (M x K x N). Full dequant parity over every weight of + // every shape; matmul parity at full K,N with M capped at 8 for CI + // speed, except 1x2304x2304 which runs fully. K,N are never capped. + struct Shape { uint32_t m, k, n; }; + const Shape shapes[] = {{1, 2304, 2304}, {64, 2304, 2304}, {128, 2304, 2304}, + {128, 3072, 3072}, {128, 4096, 4096}, {64, 6144, 6144}}; + for (const Shape& s : shapes) { + auto w = make_iq4xs_weights(s.n, s.k, 42 + s.k); + const size_t row_bytes = static_cast(s.k / 256) * sizeof(freetile::BlockIq4Xs); + std::vector wa(s.k), wb(s.k); + for (uint32_t r = 0; r < s.n; ++r) { + freetile::dequant_iq4_xs_row(w.data() + r * row_bytes, s.k, wa.data(), true); + freetile::dequant_iq4_xs_row(w.data() + r * row_bytes, s.k, wb.data(), false); + CHECK(max_abs_diff(wa, wb) == 0.0, "IQ4_XS full-shape dequant 0.0 diff"); + } + const uint32_t mm = std::min(s.m, 8); + std::mt19937 rng(7); + std::vector a(static_cast(mm) * s.k); + for (auto& v : a) v = static_cast(static_cast(rng() % 2001) - 1000) * 0.001f; + std::vector ca(static_cast(mm) * s.n), cb(static_cast(mm) * s.n); + freetile::iq4xs_dequant_matmul(a.data(), w.data(), ca.data(), mm, s.k, s.n, true); + freetile::iq4xs_dequant_matmul(a.data(), w.data(), cb.data(), mm, s.k, s.n, false); + CHECK(max_abs_diff(ca, cb) == 0.0, "IQ4_XS dequant+matmul 0.0 diff"); + std::printf(" shape M=%u K=%u N=%u (matmul M_tile=%u): max_abs_diff=0.0\n", s.m, s.k, s.n, mm); + } + std::printf("[PASS] test_iq4xs_matmul_shapes (6 MoE shapes, 0.0 diff)\n"); +} + +void test_stablehlo_emission_zero_gather() { + for (auto cb : {freetile::Codebook4::IQ4_XS, freetile::Codebook4::NF4, freetile::Codebook4::FP4_E2M1}) { + std::string out; + const std::string mlir = freetile::emit_stablehlo_select_tree_lut4("%arg0", {2304, 2304}, cb, 0, &out); + CHECK(!out.empty(), "emission returns SSA"); + CHECK(freetile::count_mlir_ops(mlir, "\"stablehlo.select\"") == 15, "exactly 15 selects"); + CHECK(freetile::count_mlir_ops(mlir, "stablehlo.gather") == 0, "zero gather ops"); + CHECK(freetile::count_mlir_ops(mlir, "\"stablehlo.gather\"") == 0, "zero quoted gather ops"); + CHECK(mlir.find("tensor<2304x2304xui32>") != std::string::npos, "2304x2304 ui32 type"); + CHECK(mlir.find("tensor<2304x2304xf32>") != std::string::npos, "2304x2304 f32 type"); + } + bool threw = false; + try { (void)freetile::emit_stablehlo_select_tree_lut4("%a", {}, freetile::Codebook4::IQ4_XS, 0, nullptr); } + catch (const std::invalid_argument&) { threw = true; } + CHECK(threw, "empty dims rejected"); + std::printf("[PASS] test_stablehlo_emission_zero_gather\n"); +} + +void test_tile_ir_planning() { + CHECK(std::string(freetile::quant_format_name(freetile::QuantFormat::IQ4_XS)) == "iq4_xs", "name iq4_xs"); + CHECK(freetile::quant_is_codebook4(freetile::QuantFormat::IQ4_XS), "IQ4_XS is codebook4"); + CHECK(freetile::quant_is_codebook4(freetile::QuantFormat::NF4), "NF4 is codebook4"); + CHECK(!freetile::quant_is_codebook4(freetile::QuantFormat::Q4_K), "Q4_K not codebook4"); + CHECK(freetile::quant_block_size(freetile::QuantFormat::IQ4_XS) == 32, "IQ4_XS block 32"); + // Non-power-of-2 MoE shapes plan cleanly on v5e and v6e (M<=64 planner scope). + for (auto target : {freetile::ChipTarget::V5E, freetile::ChipTarget::V6E}) { + for (int64_t kn : {2304, 3072, 4096, 6144}) { + freetile::TileKernel kern; std::string reason; + const bool ok = freetile::plan_quant_matmul_kernel( + target, 64, kn, kn, freetile::QuantFormat::IQ4_XS, + freetile::DType::BF16, freetile::DType::F32, true, &kern, &reason); + CHECK(ok, ("IQ4_XS plan failed: " + reason).c_str()); + CHECK(kern.matmul.weight_dtype == freetile::DType::U4, "codebook weight dtype U4"); + CHECK(kern.name.find("iq4_xs") != std::string::npos, "kernel name carries iq4_xs"); + // Mosaic must refuse codebook formats (StableHLO tree is the path). + bool threw = false; + try { (void)freetile::emit_mosaic_kernel(kern); } + catch (const std::runtime_error& e) { + threw = std::string(e.what()).find("select-tree") != std::string::npos; + } + CHECK(threw, "mosaic refuses codebook format with select-tree diagnostic"); + } + } + std::printf("[PASS] test_tile_ir_planning (v5e/v6e x 2304/3072/4096/6144)\n"); +} +} // namespace + +int main() { + test_scalar_tree_exhaustive(); + test_codebook_tables(); + test_dequant_bit_exact(); + test_iq4xs_matmul_shapes(); + test_stablehlo_emission_zero_gather(); + test_tile_ir_planning(); + if (g_fail != 0) { std::printf("FAILED (%d)\n", g_fail); return 1; } + std::printf("ALL PASSED (select-tree LUT, 0 failures)\n"); + return 0; +} diff --git a/llama-cpp-cloudtpu/stablehlo_emitter.cpp b/llama-cpp-cloudtpu/stablehlo_emitter.cpp index e78f0f51..bc26b3ab 100644 --- a/llama-cpp-cloudtpu/stablehlo_emitter.cpp +++ b/llama-cpp-cloudtpu/stablehlo_emitter.cpp @@ -975,8 +975,46 @@ std::string build_canonical_cache_key(const std::string& mlir_text, return oss.str(); } +// Branchless 4-bit select-tree LUT on a ui32 index tensor (freetpu#43): +// b0..b3 predicates, 16 splat leaves, 8->4->2->1 stablehlo.select levels. +SsaValue select_tree_lut4_value(StableHloBuilder& b, const SsaValue& idx, + const std::array& table16) { + SsaValue zero = b.emit_const_splat_int(0, idx.dims, PjrtDType::U32); + SsaValue one = b.emit_const_splat_int(1, idx.dims, PjrtDType::U32); + std::vector pred; + for (int bit = 0; bit < 4; ++bit) { + SsaValue bits = idx; + if (bit > 0) { + SsaValue shamt = b.emit_const_splat_int(bit, idx.dims, PjrtDType::U32); + bits = b.emit_binary("stablehlo.shift_right_logical", idx, shamt); + } + SsaValue bitv = b.emit_binary("stablehlo.and", bits, one); + pred.push_back(b.emit_compare("NE", bitv, zero)); + } + std::vector level; + for (float v : table16) level.push_back(b.emit_const_splat_f32(v, idx.dims, PjrtDType::F32)); + for (int bit = 0; bit < 4; ++bit) { + std::vector up; + for (size_t i = 0; i + 1 < level.size(); i += 2) + up.push_back(b.emit_select(pred[static_cast(bit)], level[i + 1], level[i])); + level = std::move(up); + } + return level[0]; +} + } // namespace +std::string emit_select_tree_lut4_program(const std::vector& dims, + const std::array& table16) { + if (dims.empty()) throw std::invalid_argument("emit_select_tree_lut4_program: dims empty"); + for (int64_t d : dims) + if (d <= 0) throw std::invalid_argument("emit_select_tree_lut4_program: dims must be positive"); + StableHloBuilder b; + b.add_arg("%arg0", PjrtDType::U32, dims); + SsaValue out = select_tree_lut4_value(b, b.arg_val(0), table16); + return b.finish({out}); +} + std::string format_sdy_mesh_op(int32_t num_chips, int32_t d2d_group_size, const std::vector& device_ids) { diff --git a/llama-cpp-cloudtpu/stablehlo_emitter.hpp b/llama-cpp-cloudtpu/stablehlo_emitter.hpp index 9202dfb1..528a5575 100644 --- a/llama-cpp-cloudtpu/stablehlo_emitter.hpp +++ b/llama-cpp-cloudtpu/stablehlo_emitter.hpp @@ -2,6 +2,7 @@ #include "pjrt_runtime.hpp" +#include #include #include #include @@ -163,6 +164,15 @@ EmittedProgram emit_stablehlo_program(const GraphProgramSpec& spec); // Convenience helpers for unit tests / single-op lowering. std::string format_mlir_tensor_type(PjrtDType dtype, const std::vector& dims); +// Branchless VREG select-tree LUT program (freetpu#43): emits a complete +// StableHLO module `@main(%arg0: tensor) -> tensor` +// resolving each 4-bit index through a 4-level select tree over `table16` +// (15 stablehlo.select ops, zero stablehlo.gather). This is the Cloud TPU +// lowering for IQ4_XS/IQ4_NL/NF4/FP4 codebook dequantization on +// non-power-of-2 MoE shapes where XLA gather hits a compiler cliff. +std::string emit_select_tree_lut4_program(const std::vector& dims, + const std::array& table16); + // ========================================================================= // Continuous Batching Padded Buckets & Safe Dataflow Token-Axis Propagation // ========================================================================= diff --git a/llama-cpp-cloudtpu/tests/test_cloudtpu_host.cpp b/llama-cpp-cloudtpu/tests/test_cloudtpu_host.cpp index c8204fdf..56808d0e 100644 --- a/llama-cpp-cloudtpu/tests/test_cloudtpu_host.cpp +++ b/llama-cpp-cloudtpu/tests/test_cloudtpu_host.cpp @@ -57,6 +57,32 @@ void check_vec_close(const std::vector& got, } } +void test_select_tree_lut4_program() { + // freetpu#43: branchless VREG select-tree LUT. 15 selects, zero gather, + // on non-power-of-2 MoE shapes for the IQ4_XS codebook. + const std::array iq4 = {-127.f, -104.f, -83.f, -65.f, -49.f, -35.f, -22.f, -10.f, + 1.f, 13.f, 25.f, 38.f, 53.f, 69.f, 89.f, 113.f}; + auto count = [](const std::string& s, const char* needle) { + size_t c = 0, p = 0; + while ((p = s.find(needle, p)) != std::string::npos) { ++c; p += std::strlen(needle); } + return c; + }; + for (int64_t kn : {2304, 3072, 4096, 6144}) { + const std::string mlir = cloudtpu::emit_select_tree_lut4_program({kn, kn}, iq4); + CHECK_TRUE(count(mlir, "\"stablehlo.select\"") == 15, "select-tree emits exactly 15 selects"); + CHECK_TRUE(count(mlir, "stablehlo.gather") == 0, "select-tree emits zero gather"); + CHECK_TRUE(mlir.find("func.func public @main") != std::string::npos, "select-tree module @main"); + CHECK_TRUE(mlir.find("xui32") != std::string::npos, "select-tree ui32 index tensor"); + CHECK_TRUE(mlir.find("-1.27000000e+02") != std::string::npos, "IQ4 leaf -127 present"); + CHECK_TRUE(mlir.find("1.13000000e+02") != std::string::npos, "IQ4 leaf 113 present"); + } + bool threw = false; + try { (void)cloudtpu::emit_select_tree_lut4_program({}, iq4); } + catch (const std::invalid_argument&) { threw = true; } + CHECK_TRUE(threw, "select-tree rejects empty dims"); + std::printf(" [PASS] StableHLO select-tree LUT4 (15 selects, 0 gather, 2304/3072/4096/6144)\n"); +} + void test_compile_options_proto() { cloudtpu::PjrtCompileOptions o1; const std::string p1 = cloudtpu::encode_compile_options_proto(o1); @@ -7460,6 +7486,7 @@ int main(int argc, char** argv) { } test_compile_options_proto(); + test_select_tree_lut4_program(); test_half_bf16_conversions(); test_lru_cache_and_hbm_roundtrip(rt); diff --git a/proof/cloud-tpu-iq4xs-select-tree/PROOF.md b/proof/cloud-tpu-iq4xs-select-tree/PROOF.md new file mode 100644 index 00000000..0e3f9c7a --- /dev/null +++ b/proof/cloud-tpu-iq4xs-select-tree/PROOF.md @@ -0,0 +1,84 @@ +# Proof: Branchless VREG IQ4_XS Select-Tree LUT (freesilicon/freetpu#43) + +## Issue context (quoted baseline, not this PR's measurement) + +Issue #43 reports that on Cloud TPU `v5e`/`v6e`, XLA `gather`-based +4-bit codebook dequantization hits a compiler cliff on non-power-of-2 +MoE shapes (e.g. `2304x2304`), and that a branchless VREG select-tree +LUT measured **211x vs XLA gather, faster than BF16** on live silicon. +Those timing numbers are the issue's baseline. **This PR makes no new +hardware timing claim**: its proof is host bit-exactness + static IR +verification + a ready-to-run on-device benchmark command (below). + +## What shipped + +| Piece | Location | +|---|---| +| Select-tree core (15 selects, 0 gather), IQ4_XS/IQ4_NL/NF4/FP4 tables, GGUF block dequant + matmul, StableHLO snippet emitter | `freetile/include/freetile/select_tree_lut.hpp`, `freetile/src/select_tree_lut.cpp` | +| FreeTile IR wiring: `QuantFormat::IQ4_XS/IQ4_NL/NF4/FP4`, `quant_is_codebook4()`, U4 planner/validator path | `freetile/include/freetile/tile_ir.hpp`, `freetile/src/tile_ir.cpp` | +| Mosaic guard: codebook formats refuse numeric uitofp dequant and route to the StableHLO select-tree | `freetile/src/mosaic_emitter.cpp` | +| Cloud TPU StableHLO lowering: `emit_select_tree_lut4_program()` (complete module, builder-native `stablehlo.select`) | `llama-cpp-cloudtpu/stablehlo_emitter.hpp`, `llama-cpp-cloudtpu/stablehlo_emitter.cpp` | +| Python/NumPy mirror + tests | `tools/select_tree_lut.py`, `tools/test_select_tree_lut.py` | +| C++ bit-exact tests | `freetile/tests/test_select_tree_lut.cpp`, `llama-cpp-cloudtpu/tests/test_cloudtpu_host.cpp` (`test_select_tree_lut4_program`) | + +Algorithm: for index bits `b0..b3`, level 0 computes +`s_i = select(b0, T[2i+1], T[2i])` (8 selects), then 4, 2, 1 selects +on `b1`, `b2`, `b3` — 15 selects total, every leaf a VREG constant, +zero dynamic memory gather. 2/3-bit codebooks truncate the same tree +(3 / 7 selects, `select_tree_f32(idx, table, bits)`); grid codebooks +(IQ2/IQ3-style) apply the primitive per scalar sub-lookup. + +## Host-verified proof (this PR, observed) + +All diffs are select-tree vs direct-index reference with identical +scale arithmetic and float accumulation order, so `0.0` is exact, and +the IQ4_XS dequantizer was additionally cross-checked `0.0` against +the independent `libopenbuenos` scalar reference +(`ob::quant::dequant_row_scalar_f32`, `K=2304`). + +| Check | Result | +|---|---| +| Exhaustive 16-index tree vs table (IQ4_NL, IQ4_XS, NF4, FP4; f32 + i32 mask-blend) | exact | +| IQ4_XS dequant, full weight matrices `2304², 3072², 4096², 6144²` (every row) | `max_abs_diff = 0.0` | +| IQ4_XS dequant+matmul `1x2304x2304` full; `64/128x2304x2304`, `128x3072x3072`, `128x4096x4096`, `64x6144x6144` at full K,N with M-tile 8 (CI speed) | `max_abs_diff = 0.0` | +| IQ4_NL, NF4, FP4 dequant rows | `max_abs_diff = 0.0` | +| Emitted StableHLO (both emitters, `2304/3072/4096/6144`) | exactly 15 `stablehlo.select`, **0 `stablehlo.gather`** | +| FreeTile planning `IQ4_XS` on v5e+v6e, K=N in {2304, 3072, 4096, 6144}, M=64 | plans; U4 weights; Mosaic refuses with select-tree diagnostic | +| ASan+UBSan (`-fno-sanitize-recover=all`) on the new C++ suite | clean | +| Repo suites: `make -C freetile test`, `make -C libopenbuenos verify-header-host host test`, `make -C libopentpu verify-header-host host test`, cloudtpu host test (mock), Python tests | all pass | + +Reproduce (host, no TPU required): + +```bash +make -C freetile test # includes test_select_tree_lut +python3 tools/select_tree_lut.py --self-test +python3 tools/test_select_tree_lut.py -v +# llama-cpp-cloudtpu host suite (CMake hosts): +cmake -S llama-cpp-cloudtpu -B build-cloudtpu -DCMAKE_BUILD_TYPE=Release +cmake --build build-cloudtpu && ctest --test-dir build-cloudtpu --output-on-failure +``` + +Known scope limits, stated plainly: the FreeTile planner's existing +`M <= 64` small-batch scope is unchanged (the host dequant+matmul +reference covers any M; the `128x...` shapes are verified at M-tile 8 +with full K and N). The select-tree is wired as the StableHLO +codebook lowering (`emit_select_tree_lut4_program` + snippet emitter); +GGUF `IQ4_XS` tensor ingestion in `ggml-cloudtpu.cpp` (new storage +kind) remains follow-up work and is not claimed here. + +## Live Cloud TPU benchmark (ready to run, not run by this PR) + +On a Cloud TPU `v5e`/`v6e` VM with `libtpu.so`: + +```bash +# 1. Correctness on silicon (same host suite, live PJRT): +CLOUDTPU_MOCK=0 ./build-cloudtpu/test_cloudtpu_host +# 2. Timing harness entry points already in this repo: +python3 tools/colab_tpu_bench.py --help +python3 tools/select_tree_lut.py --bench-harness +# Compare: select-tree StableHLO (this PR) vs a gather-based LUT vs BF16 +# dense at 1x2304x2304, 128x2304x2304, 128x4096x4096; expect the issue's +# qualitative result (gather cliff removed). Report observed numbers +# with the exact libtpu/TPU build; do not reuse the issue's 211x figure +# as this PR's result. +``` diff --git a/tools/select_tree_lut.py b/tools/select_tree_lut.py new file mode 100644 index 00000000..6a7c8db1 --- /dev/null +++ b/tools/select_tree_lut.py @@ -0,0 +1,169 @@ +#!/usr/bin/env python3 +"""Branchless VREG 4-bit select-tree LUT (freesilicon/freetpu#43). + +Clean-room NumPy mirror of freetile/select_tree_lut: resolves 4-bit +codebook indices (IQ4_XS/IQ4_NL, NF4, FP4 E2M1) through a 4-level +branchless select tree (8->4->2->1 np.where) instead of a dynamic +gather (`table[idx]`), plus GGUF IQ4_XS block dequant + matmul. +Bit-exact (0.0 max abs diff) vs direct-index reference by construction. + +Usage: + python3 tools/select_tree_lut.py --self-test + python3 tools/select_tree_lut.py --bench-harness # prints Cloud TPU bench command +""" +import argparse +import struct +import sys + +import numpy as np + +KVALUES_IQ4NL = np.array( + [-127, -104, -83, -65, -49, -35, -22, -10, 1, 13, 25, 38, 53, 69, 89, 113], + dtype=np.float32, +) +NF4 = np.array( + [-1.0, -0.6961928009986877, -0.5250730514526367, -0.39491748809814453, + -0.28444138169288635, -0.18477343022823334, -0.09105003625154495, 0.0, + 0.07958029955618668, 0.16093020141124725, 0.24611230194568634, 0.33791524171829224, + 0.44070982933044434, 0.5626170039176941, 0.7229568362236023, 1.0], + dtype=np.float32, +) +FP4_E2M1 = np.array( + [0.0, 0.5, 1.0, 1.5, 2.0, 3.0, 4.0, 6.0, -0.0, -0.5, -1.0, -1.5, -2.0, -3.0, -4.0, -6.0], + dtype=np.float32, +) +CODEBOOKS = {"iq4_nl": KVALUES_IQ4NL, "iq4_xs": KVALUES_IQ4NL, "nf4": NF4, "fp4_e2m1": FP4_E2M1} + + +def select_tree4(idx, table): + """Branchless 4-bit select tree: 8->4->2->1 selects, zero gather.""" + idx = np.asarray(idx) + t = [np.full(idx.shape, v, dtype=np.float32) if idx.shape else np.float32(v) for v in table] + level = t + for b in range(4): + bit = ((idx >> b) & 1).astype(bool) + level = [np.where(bit, level[2 * i + 1], level[2 * i]) for i in range(len(level) // 2)] + return level[0] + + +def select_tree(idx, table, bits): + """Generic 1..4-bit tree; 2/3-bit codebooks truncate the same levels.""" + if not 1 <= bits <= 4: + raise ValueError("bits must be 1..4") + idx = np.asarray(idx) + level = [np.full(idx.shape, float(table[i]), dtype=np.float32) for i in range(1 << bits)] + for b in range(bits): + bit = ((idx >> b) & 1).astype(bool) + level = [np.where(bit, level[2 * i + 1], level[2 * i]) for i in range(len(level) // 2)] + return level[0] + + +def _lut(idx, table, tree): + return select_tree4(idx, table) if tree else table[np.asarray(idx) & 0xF] + + +def dequant_iq4_xs_row(block_bytes, k, tree=True): + """Dequantize one IQ4_XS row of width k (136 B per 256 weights). + + Handles non-multiple k tails (partial super-block) so every output is + written; k may be any value, trailing partial super-block uses the + same scale decoding and only the first k%256 values are produced. + """ + out = np.zeros(k, dtype=np.float32) + nsb_full = k // 256 + rem = k % 256 + for sb in range(nsb_full): + blk = block_bytes[sb * 136:(sb + 1) * 136] + d = float(np.frombuffer(blk[0:2], dtype=np.float16)[0]) + scales_h = struct.unpack_from("> (4 * (ib & 1))) & 0xF) | (((scales_h >> (2 * ib)) & 3) << 4) + dl = np.float32(d) * np.float32(ls - 32) + chunk = qs[ib * 16:(ib + 1) * 16] + base = sb * 256 + ib * 32 + out[base:base + 16] = dl * _lut(chunk & 0xF, KVALUES_IQ4NL, tree) + out[base + 16:base + 32] = dl * _lut(chunk >> 4, KVALUES_IQ4NL, tree) + if rem: + sb = nsb_full + blk = block_bytes[sb * 136:(sb + 1) * 136] + d = float(np.frombuffer(blk[0:2], dtype=np.float16)[0]) + scales_h = struct.unpack_from("= rem: + break + want = min(32, rem - base) + ls = ((scales_l[ib // 2] >> (4 * (ib & 1))) & 0xF) | (((scales_h >> (2 * ib)) & 3) << 4) + dl = np.float32(d) * np.float32(ls - 32) + chunk = qs[ib * 16:(ib + 1) * 16] + out_base = sb * 256 + base + if want <= 16: + out[out_base:out_base + want] = dl * _lut(chunk[:want] & 0xF, KVALUES_IQ4NL, tree) + else: + out[out_base:out_base + 16] = dl * _lut(chunk & 0xF, KVALUES_IQ4NL, tree) + out[out_base + 16:out_base + want] = dl * _lut(chunk[:want - 16] >> 4, KVALUES_IQ4NL, tree) + return out + + +def iq4xs_dequant_matmul(a_mk, w_bytes, m, k, n, tree=True): + """C[MxN] = A[MxK] @ dequant(W)^T, W = N IQ4_XS rows. Float32 accum.""" + row_bytes = ((k + 255) // 256) * 136 + w = np.empty((n, k), dtype=np.float32) + for r in range(n): + w[r] = dequant_iq4_xs_row(w_bytes[r * row_bytes:(r + 1) * row_bytes], k, tree) + return (np.asarray(a_mk, dtype=np.float32).reshape(m, k) @ w.T).astype(np.float32) + + +def count_selects(bits=4): + if bits < 0 or bits >= 32: + raise ValueError("bits out of range (0..31 for select count)") + if bits == 0: + return 0 + return (1 << bits) - 1 + + +def _self_test(): + rng = np.random.default_rng(43) + for name, table in CODEBOOKS.items(): + idx = np.arange(16, dtype=np.uint32) + assert np.array_equal(select_tree4(idx, table), table), name + big = rng.integers(0, 16, size=(2304, 256), dtype=np.uint32) + diff = np.max(np.abs(select_tree4(big, table) - table[big])) + assert diff == 0.0, (name, diff) + for bits in (2, 3): + tab = rng.standard_normal(1 << bits).astype(np.float32) + idx = np.arange(1 << bits, dtype=np.uint32) + assert np.array_equal(select_tree(idx, tab, bits), tab), bits + # IQ4_XS dequant + matmul parity on a tiled MoE sub-shape. + k, n, m = 2304, 256, 8 + raw = bytearray(rng.integers(0, 256, size=n * (k // 256) * 136, dtype=np.uint8).tobytes()) + for off in range(0, len(raw), 136): + raw[off:off + 2] = np.float16(0.01).tobytes() + a = rng.standard_normal((m, k)).astype(np.float32) * 0.01 + ca = iq4xs_dequant_matmul(a, bytes(raw), m, k, n, tree=True) + cb = iq4xs_dequant_matmul(a, bytes(raw), m, k, n, tree=False) + assert np.max(np.abs(ca - cb)) == 0.0 + print("select_tree_lut self-test PASSED (0.0 max abs diff, 15 selects, 0 gather)") + return 0 + + +def main(argv=None): + p = argparse.ArgumentParser(description=__doc__.splitlines()[0]) + p.add_argument("--self-test", action="store_true", help="run host bit-exact parity self-test") + p.add_argument("--bench-harness", action="store_true", + help="print the ready-to-run Cloud TPU v5e/v6e benchmark command") + args = p.parse_args(argv) + if args.bench_harness: + print("On a Cloud TPU v5e/v6e VM (host proof here is bit-exactness only):") + print(" CLOUDTPU_MOCK=0 ./llama-cpp-cloudtpu/build/test_cloudtpu_host") + print(" python3 tools/colab_tpu_bench.py --help # existing TPU bench entry point") + return 0 + return _self_test() + + +if __name__ == "__main__": + sys.exit(main()) diff --git a/tools/test_select_tree_lut.py b/tools/test_select_tree_lut.py new file mode 100644 index 00000000..1ca92274 --- /dev/null +++ b/tools/test_select_tree_lut.py @@ -0,0 +1,59 @@ +#!/usr/bin/env python3 +"""Bit-exact (0.0 diff) parity tests for tools/select_tree_lut.py (freetpu#43).""" +import os +import sys +import unittest + +import numpy as np + +sys.path.insert(0, os.path.dirname(os.path.abspath(__file__))) +import select_tree_lut as st # noqa: E402 + + +class TestSelectTree(unittest.TestCase): + def test_exhaustive_all_codebooks(self): + for name, table in st.CODEBOOKS.items(): + idx = np.arange(16, dtype=np.uint32) + self.assertTrue(np.array_equal(st.select_tree4(idx, table), table), name) + + def test_large_non_pow2_shape_zero_diff(self): + rng = np.random.default_rng(1) + for name in ("iq4_xs", "nf4", "fp4_e2m1"): + table = st.CODEBOOKS[name] + idx = rng.integers(0, 16, size=(2304, 2304), dtype=np.uint32) + diff = float(np.max(np.abs(st.select_tree4(idx, table) - table[idx]))) + self.assertEqual(diff, 0.0, name) + + def test_2_3_bit_composition(self): + t2 = np.array([-1.5, -0.5, 0.25, 2.0], dtype=np.float32) + t3 = np.linspace(-3, 3, 8).astype(np.float32) + self.assertTrue(np.array_equal(st.select_tree(np.arange(4, dtype=np.uint32), t2, 2), t2)) + self.assertTrue(np.array_equal(st.select_tree(np.arange(8, dtype=np.uint32), t3, 3), t3)) + with self.assertRaises(ValueError): + st.select_tree(np.arange(4, dtype=np.uint32), t2, 5) + + def test_select_counts(self): + self.assertEqual((st.count_selects(2), st.count_selects(3), st.count_selects(4)), (3, 7, 15)) + + def test_iq4xs_dequant_matmul_shapes(self): + rng = np.random.default_rng(7) + # Tiled N for Python CI speed; full-shape verification is in the C++ suite. + for (m, k, n) in [(1, 2304, 512), (8, 3072, 512), (8, 4096, 256), (8, 6144, 128)]: + raw = bytearray(rng.integers(0, 256, size=n * (k // 256) * 136, dtype=np.uint8).tobytes()) + for off in range(0, len(raw), 136): + raw[off:off + 2] = np.float16(0.01).tobytes() + a = (rng.standard_normal((m, k)) * 0.01).astype(np.float32) + ca = st.iq4xs_dequant_matmul(a, bytes(raw), m, k, n, tree=True) + cb = st.iq4xs_dequant_matmul(a, bytes(raw), m, k, n, tree=False) + self.assertEqual(float(np.max(np.abs(ca - cb))), 0.0, (m, k, n)) + + def test_tables(self): + self.assertEqual(st.KVALUES_IQ4NL[0], np.float32(-127)) + self.assertEqual(st.KVALUES_IQ4NL[15], np.float32(113)) + self.assertEqual(st.NF4[7], np.float32(0.0)) + self.assertEqual(st.FP4_E2M1[7], np.float32(6.0)) + self.assertEqual(st.FP4_E2M1[15], np.float32(-6.0)) + + +if __name__ == "__main__": + unittest.main()