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
61 changes: 60 additions & 1 deletion freetile/include/freetile/select_tree_lut.hpp
Original file line number Diff line number Diff line change
Expand Up @@ -23,6 +23,8 @@
// (7 selects) — see select_tree_f32(). Grid codebooks (IQ2_XXS/IQ3_XXS
// style) apply the primitive per scalar sub-lookup.

#include "freetile/tile_ir.hpp"

#include <array>
#include <cstddef>
#include <cstdint>
Expand Down Expand Up @@ -118,13 +120,70 @@ void dequant_iq4_xs_row(const void* blocks, uint32_t k, float* out, bool use_sel
void dequant_codebook4_row(Codebook4 cb, const uint8_t* nibbles, const float* scales32,
uint32_t k, float* out, bool use_select_tree);

// Packed 18-byte / 32-weight codebook block (FP16 scale `d` + 16 split-nibble
// bytes, wire-compatible with BlockIq4Nl and packed NF4/FP4/BOF4 layouts).
using BlockCodebook4 = BlockIq4Nl;
void dequant_packed_codebook4_row(Codebook4 cb, const void* blocks, 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);

// --- Portable FreeTile `codebook_dequant` semantic IR op (freetpu#43) ------
// Exposes one backend-neutral codebook dequantization descriptor that lowers
// across Cloud TPU (branchless VREG select-tree), ARM SME2 (LUTI4), Qualcomm
// HVX (vlut), and PowerVR Volcanic compute (register select-tree).
enum class CodebookTargetBackend {
CLOUD_TPU_SELECT_TREE = 0,
ARM_SME2_LUTI4,
QUALCOMM_HVX_VLUT,
POWERVR_VOLCANIC_SELECT_TREE,
};

const char* codebook_backend_name(CodebookTargetBackend backend);

// Cloud TPU v5e 16 MiB VMEM gather-cliff threshold characterized in #43:
// weight tensors with <= 5.31M elements (e.g. 512^2, 1024^2, 2048^2, 2304^2)
// hit the severe XLA gather cliff, whereas >= 9.44M (3072^2+) cross the 16 MiB
// VMEM boundary and lower differently. Select-tree eliminates gather across all sizes.
constexpr size_t kV5eGatherCliffMaxElems = 5310000u;

struct CodebookDequantOp {
QuantFormat format = QuantFormat::IQ4_XS;
uint32_t index_bits = 4u;
uint32_t select_ops = 15u;
int64_t block_size = 32;
int64_t rows = 0;
int64_t cols = 0;
CodebookTargetBackend backend = CodebookTargetBackend::CLOUD_TPU_SELECT_TREE;
const char* target_primitive = "stablehlo.select_tree";
size_t weight_elements = 0;
size_t vmem_f32_bytes = 0;
bool v5e_gather_cliff_zone = false;
};

CodebookDequantOp plan_codebook_dequant_op(QuantFormat fmt,
int64_t rows,
int64_t cols,
CodebookTargetBackend backend = CodebookTargetBackend::CLOUD_TPU_SELECT_TREE);

// --- IR emission -----------------------------------------------------------
// Emits the select tree as StableHLO MLIR ops on tensor<dims x ui32> index
// Generic 1..4-bit StableHLO select-tree LUT emitter on tensor<dims x ui32>
// index SSA value `idx_ssa` over `table[0..2^bits)`. Emits exactly (2^bits - 1)
// stablehlo.select ops (3 for 2-bit IQ2_XXS, 7 for 3-bit IQ3_XXS, 15 for 4-bit
// IQ4_XS/IQ4_NL/NF4/FP4) and zero stablehlo.gather ops.
std::string emit_stablehlo_select_tree_lut(const std::string& idx_ssa,
const std::vector<int64_t>& dims,
const float* table,
uint32_t bits,
const char* label,
int ssa_start,
std::string* out_ssa,
int* next_ssa = nullptr);

// Emits the 4-bit 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, and if `next_ssa` is non-null, the next
// unused SSA index is written to *next_ssa so callers can chain snippets in
Expand Down
18 changes: 12 additions & 6 deletions freetile/include/freetile/tile_ir.hpp
Original file line number Diff line number Diff line change
Expand Up @@ -63,17 +63,23 @@ 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
IQ4_XS, // 16-entry codebook, branchless 4-bit select-tree LUT (freetpu#43)
IQ4_NL, // 16-entry codebook, branchless 4-bit select-tree LUT
NF4, // 16-entry NormalFloat4 codebook, 4-bit select-tree LUT
FP4, // 16-entry OCP FP4 E2M1 codebook, 4-bit 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).
// Index bit-width for scalar codebook quant formats (4 for IQ4_XS/IQ4_NL/NF4/FP4,
// 0 for affine/dense formats). Narrower 2/3-bit scalar sub-lookups compose via
// select_tree_f32() / emit_stablehlo_select_tree_lut() (see select_tree_lut.hpp).
uint32_t quant_codebook_bits(QuantFormat fmt);
// True for any scalar codebook format lowered via branchless select-tree LUT.
bool quant_is_codebook(QuantFormat fmt);
// True for 4-bit codebook formats lowered via the 15-select VREG select-tree LUT
// instead of a dynamic gather (see select_tree_lut.hpp).
bool quant_is_codebook4(QuantFormat fmt);

enum class MemorySpace {
Expand Down
4 changes: 2 additions & 2 deletions freetile/src/mosaic_emitter.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -165,9 +165,9 @@ 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)) {
if (quant_is_codebook(kernel.matmul.quant)) {
// Codebook indices must resolve through the branchless select-tree
// LUT (select_tree_lut.hpp / StableHLO path), never a numeric
// LUT (codebook_dequant / 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 "
Expand Down
139 changes: 111 additions & 28 deletions freetile/src/select_tree_lut.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -137,14 +137,15 @@ float fp16_to_f32(uint16_t h) {
float out; std::memcpy(&out, &bits, 4); return out;
}

void dequant_iq4_nl_row(const void* blocks, uint32_t k, float* out, bool tree) {
void dequant_packed_codebook4_row(Codebook4 cb, const void* blocks, uint32_t k,
float* out, bool tree) {
if (k == 0) return;
if (!blocks || !out) throw std::invalid_argument("dequant_iq4_nl_row: null pointer");
if (!blocks || !out) throw std::invalid_argument("dequant_packed_codebook4_row: null pointer");
const auto* raw = static_cast<const uint8_t*>(blocks);
const float* t = codebook4_table_f32(Codebook4::IQ4_NL).data();
const float* t = codebook4_table_f32(cb).data();
const size_t nb = static_cast<size_t>((k - 1u) / 32u) + 1u;
for (size_t b = 0; b < nb; ++b) {
const uint8_t* blk = raw + b * sizeof(BlockIq4Nl);
const uint8_t* blk = raw + b * sizeof(BlockCodebook4);
const float d = fp16_to_f32(load_u16_le(blk));
const size_t base = b * 32u;
const uint32_t want = static_cast<uint32_t>(
Expand All @@ -153,6 +154,10 @@ void dequant_iq4_nl_row(const void* blocks, uint32_t k, float* out, bool tree) {
}
}

void dequant_iq4_nl_row(const void* blocks, uint32_t k, float* out, bool tree) {
dequant_packed_codebook4_row(Codebook4::IQ4_NL, blocks, k, out, tree);
}

void dequant_iq4_xs_row(const void* blocks, uint32_t k, float* out, bool tree) {
if (k == 0) return;
if (!blocks || !out) throw std::invalid_argument("dequant_iq4_xs_row: null pointer");
Expand Down Expand Up @@ -230,65 +235,134 @@ void iq4xs_dequant_matmul(const float* a_mk, const void* w_blocks_nk, float* c_m
}
}

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,
int* next_ssa) {
if (idx_ssa.empty()) throw std::invalid_argument("emit_stablehlo_select_tree_lut4: idx_ssa empty");
const char* codebook_backend_name(CodebookTargetBackend backend) {
switch (backend) {
case CodebookTargetBackend::CLOUD_TPU_SELECT_TREE: return "cloud_tpu_select_tree";
case CodebookTargetBackend::ARM_SME2_LUTI4: return "arm_sme2_luti4";
case CodebookTargetBackend::QUALCOMM_HVX_VLUT: return "qualcomm_hvx_vlut";
case CodebookTargetBackend::POWERVR_VOLCANIC_SELECT_TREE: return "powervr_volcanic_select_tree";
}
return "unknown";
}

CodebookDequantOp plan_codebook_dequant_op(QuantFormat fmt,
int64_t rows,
int64_t cols,
CodebookTargetBackend backend) {
const uint32_t bits = quant_codebook_bits(fmt);
if (bits == 0u) {
throw std::invalid_argument("plan_codebook_dequant_op: format is not a codebook quant");
}
if (rows <= 0 || cols <= 0) {
throw std::invalid_argument("plan_codebook_dequant_op: rows and cols must be positive");
}
const uint64_t ur = static_cast<uint64_t>(rows);
const uint64_t uc = static_cast<uint64_t>(cols);
if (ur > std::numeric_limits<size_t>::max() || uc > std::numeric_limits<size_t>::max()) {
throw std::overflow_error("plan_codebook_dequant_op: dimension exceeds size_t");
}
const size_t elems = checked_mul_size(static_cast<size_t>(ur), static_cast<size_t>(uc),
"plan_codebook_dequant_op: weight_elements overflow");
const size_t f32_bytes = checked_mul_size(elems, sizeof(float),
"plan_codebook_dequant_op: vmem_f32_bytes overflow");
CodebookDequantOp op;
op.format = fmt;
op.index_bits = bits;
op.select_ops = select_tree_select_count(bits);
op.block_size = quant_block_size(fmt);
op.rows = rows;
op.cols = cols;
op.backend = backend;
switch (backend) {
case CodebookTargetBackend::CLOUD_TPU_SELECT_TREE:
op.target_primitive = "stablehlo.select_tree";
break;
case CodebookTargetBackend::ARM_SME2_LUTI4:
op.target_primitive = (bits <= 2u) ? "sme2.luti2" : "sme2.luti4";
break;
case CodebookTargetBackend::QUALCOMM_HVX_VLUT:
op.target_primitive = "hvx.vlut";
break;
case CodebookTargetBackend::POWERVR_VOLCANIC_SELECT_TREE:
op.target_primitive = "volcanic.select_tree";
break;
}
op.weight_elements = elems;
op.vmem_f32_bytes = f32_bytes;
op.v5e_gather_cliff_zone = (elems <= kV5eGatherCliffMaxElems);
return op;
}

std::string emit_stablehlo_select_tree_lut(const std::string& idx_ssa,
const std::vector<int64_t>& dims,
const float* table,
uint32_t bits,
const char* label,
int ssa_start,
std::string* out_ssa,
int* next_ssa) {
if (idx_ssa.empty()) throw std::invalid_argument("emit_stablehlo_select_tree_lut: idx_ssa empty");
if (!table) throw std::invalid_argument("emit_stablehlo_select_tree_lut: table null");
if (bits == 0u || bits > 4u) {
throw std::invalid_argument("emit_stablehlo_select_tree_lut: bits must be 1..4");
}
if (ssa_start < 0 || ssa_start > std::numeric_limits<int>::max() - 64) {
throw std::invalid_argument("emit_stablehlo_select_tree_lut4: ssa_start out of range");
throw std::invalid_argument("emit_stablehlo_select_tree_lut: ssa_start out of range");
}
if (dims.empty()) throw std::invalid_argument("emit_stablehlo_select_tree_lut4: dims empty");
if (dims.empty()) throw std::invalid_argument("emit_stablehlo_select_tree_lut: dims empty");
size_t elems = 1;
for (int64_t d : dims) {
if (d <= 0) throw std::invalid_argument("emit_stablehlo_select_tree_lut4: dims must be positive");
if (d <= 0) throw std::invalid_argument("emit_stablehlo_select_tree_lut: dims must be positive");
const uint64_t ud = static_cast<uint64_t>(d);
if (ud > std::numeric_limits<size_t>::max()) {
throw std::overflow_error("emit_stablehlo_select_tree_lut4: dimension exceeds size_t");
throw std::overflow_error("emit_stablehlo_select_tree_lut: dimension exceeds size_t");
}
elems = checked_mul_size(elems, static_cast<size_t>(ud),
"emit_stablehlo_select_tree_lut4: element count overflow");
"emit_stablehlo_select_tree_lut: element count overflow");
}
(void)checked_mul_size(elems, sizeof(float), "emit_stablehlo_select_tree_lut4: byte extent overflow");
(void)checked_mul_size(elems, sizeof(float), "emit_stablehlo_select_tree_lut: byte extent overflow");
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.
const uint32_t n_entries = 1u << bits;
const uint32_t n_selects = select_tree_select_count(bits);
body << " // freetpu#43 branchless VREG select-tree LUT ("
<< (label ? label : "custom") << ", " << bits << "-bit): "
<< n_selects << " selects, 0 gather\n";
// Bit predicates b0..b_{bits-1} = ((idx >> b) & 1) != 0.
std::string pred[4];
const std::string zero = fresh();
const std::string one = fresh();
body << " " << zero << " = stablehlo.constant dense<0> : " << ui32_t << "\n";
body << " " << one << " = stablehlo.constant dense<1> : " << ui32_t << "\n";
for (int b = 0; b < 4; ++b) {
std::string bits = idx_ssa;
if (b > 0) {
for (uint32_t b = 0; b < bits; ++b) {
std::string shifted = idx_ssa;
if (b > 0u) {
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;
shifted = sh;
}
const std::string bitv = fresh();
body << " " << bitv << " = stablehlo.and " << bits << ", " << one << " : " << ui32_t << "\n";
body << " " << bitv << " = stablehlo.and " << shifted << ", " << 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);
// Leaves: 2^bits splat constants, then binary reduction of selects.
std::vector<std::string> level;
for (int i = 0; i < 16; ++i) {
level.reserve(n_entries);
for (uint32_t i = 0; i < n_entries; ++i) {
const std::string c = fresh();
body << " " << c << " = stablehlo.constant dense<" << f32_literal(table[static_cast<size_t>(i)])
body << " " << c << " = stablehlo.constant dense<" << f32_literal(table[i])
<< "> : " << f32_t << "\n";
level.push_back(c);
}
for (int b = 0; b < 4; ++b) {
for (uint32_t b = 0; b < bits; ++b) {
std::vector<std::string> up;
for (size_t i = 0; i + 1 < level.size(); i += 2) {
const std::string s = fresh();
Expand All @@ -304,6 +378,15 @@ std::string emit_stablehlo_select_tree_lut4(const std::string& idx_ssa,
return body.str();
}

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,
int* next_ssa) {
const auto& table = codebook4_table_f32(cb);
return emit_stablehlo_select_tree_lut(idx_ssa, dims, table.data(), 4u,
codebook4_name(cb), ssa_start, out_ssa, next_ssa);
}

size_t count_mlir_ops(const std::string& mlir, const std::string& needle) {
if (needle.empty()) return 0;
size_t count = 0, pos = 0;
Expand Down
25 changes: 19 additions & 6 deletions freetile/src/tile_ir.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -238,9 +238,22 @@ bool quant_has_min(QuantFormat fmt) {
return fmt == QuantFormat::Q4_K;
}

uint32_t quant_codebook_bits(QuantFormat fmt) {
switch (fmt) {
case QuantFormat::IQ4_XS:
case QuantFormat::IQ4_NL:
case QuantFormat::NF4:
case QuantFormat::FP4: return 4u;
default: return 0u;
}
}

bool quant_is_codebook(QuantFormat fmt) {
return quant_codebook_bits(fmt) > 0u;
}

bool quant_is_codebook4(QuantFormat fmt) {
return fmt == QuantFormat::IQ4_XS || fmt == QuantFormat::IQ4_NL ||
fmt == QuantFormat::NF4 || fmt == QuantFormat::FP4;
return quant_codebook_bits(fmt) == 4u;
}

const char* memory_space_name(MemorySpace space) {
Expand Down Expand Up @@ -400,8 +413,8 @@ bool TileKernel::validate(std::string* err) const {
return fail(err, "Quantized TileMatmul scale_dtype must be BF16 or F32");
}
const DType expected_w_dt =
quant_is_codebook4(matmul.quant)
? DType::U4 // codebook indices are unsigned 4-bit
quant_is_codebook(matmul.quant)
? DType::U4 // codebook indices are unsigned <= 4-bit (packed in U4 lanes)
: (matmul.quant == QuantFormat::Q4_K || matmul.quant == QuantFormat::Q4_0)
? (matmul.unsigned_q4 ? DType::U4 : DType::S4)
: DType::S8;
Expand Down Expand Up @@ -590,7 +603,7 @@ bool plan_quant_matmul_kernel(ChipTarget target,
}

DType w_dt = DType::BF16;
if (quant_is_codebook4(fmt)) {
if (quant_is_codebook(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;
Expand Down Expand Up @@ -631,7 +644,7 @@ bool plan_quant_matmul_kernel(ChipTarget target,
cand.target = target;
cand.preferred_lowering = (target == ChipTarget::BUENOS_A0)
? LoweringTarget::OPENBUENOS_DGC0_HOOK
: (quant_is_codebook4(fmt)
: (quant_is_codebook(fmt)
? LoweringTarget::STABLEHLO_SELECT_TREE
: LoweringTarget::MOSAIC_TPU_CUSTOM_CALL);

Expand Down
Loading
Loading