Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 2 additions & 0 deletions .github/workflows/ci.yml
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
8 changes: 8 additions & 0 deletions freetile/CMakeLists.txt
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand All @@ -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)

Expand Down
12 changes: 10 additions & 2 deletions freetile/Makefile
Original file line number Diff line number Diff line change
Expand Up @@ -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 \
Expand All @@ -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 \
Expand All @@ -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)

Expand Down Expand Up @@ -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)
2 changes: 2 additions & 0 deletions freetile/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -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.
Expand Down
137 changes: 137 additions & 0 deletions freetile/include/freetile/select_tree_lut.hpp
Original file line number Diff line number Diff line change
@@ -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 <array>
#include <cstddef>
#include <cstdint>
#include <string>
#include <vector>

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<float, 16>& codebook4_table_f32(Codebook4 cb);
extern const std::array<int8_t, 16> 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<int32_t>(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<uint32_t>((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<dims x ui32> 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<int64_t>& 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
7 changes: 7 additions & 0 deletions freetile/include/freetile/tile_ir.hpp
Original file line number Diff line number Diff line change
Expand Up @@ -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,
Expand Down
8 changes: 8 additions & 0 deletions freetile/src/mosaic_emitter.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -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) +
Expand Down
Loading
Loading