diff --git a/freetile/include/freetile/select_tree_lut.hpp b/freetile/include/freetile/select_tree_lut.hpp index 9d5eee5..4e305c6 100644 --- a/freetile/include/freetile/select_tree_lut.hpp +++ b/freetile/include/freetile/select_tree_lut.hpp @@ -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 #include #include @@ -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 index +// Generic 1..4-bit StableHLO select-tree LUT emitter on tensor +// 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& 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 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 diff --git a/freetile/include/freetile/tile_ir.hpp b/freetile/include/freetile/tile_ir.hpp index d174a0b..e07cc2e 100644 --- a/freetile/include/freetile/tile_ir.hpp +++ b/freetile/include/freetile/tile_ir.hpp @@ -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 { diff --git a/freetile/src/mosaic_emitter.cpp b/freetile/src/mosaic_emitter.cpp index 3eead46..0b978fe 100644 --- a/freetile/src/mosaic_emitter.cpp +++ b/freetile/src/mosaic_emitter.cpp @@ -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 " diff --git a/freetile/src/select_tree_lut.cpp b/freetile/src/select_tree_lut.cpp index 3a9c3b3..26af966 100644 --- a/freetile/src/select_tree_lut.cpp +++ b/freetile/src/select_tree_lut.cpp @@ -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(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((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( @@ -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"); @@ -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& 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(rows); + const uint64_t uc = static_cast(cols); + if (ur > std::numeric_limits::max() || uc > std::numeric_limits::max()) { + throw std::overflow_error("plan_codebook_dequant_op: dimension exceeds size_t"); + } + const size_t elems = checked_mul_size(static_cast(ur), static_cast(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& 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::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(d); if (ud > std::numeric_limits::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(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 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(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 up; for (size_t i = 0; i + 1 < level.size(); i += 2) { const std::string s = fresh(); @@ -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& 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; diff --git a/freetile/src/tile_ir.cpp b/freetile/src/tile_ir.cpp index 7461d9c..e570262 100644 --- a/freetile/src/tile_ir.cpp +++ b/freetile/src/tile_ir.cpp @@ -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) { @@ -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; @@ -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; @@ -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); diff --git a/freetile/tests/test_select_tree_lut.cpp b/freetile/tests/test_select_tree_lut.cpp index 4ae550a..a807b42 100644 --- a/freetile/tests/test_select_tree_lut.cpp +++ b/freetile/tests/test_select_tree_lut.cpp @@ -326,6 +326,72 @@ void test_tile_ir_planning() { } std::printf("[PASS] test_tile_ir_planning (v5e/v6e x 2304/3072/4096/6144)\n"); } +void test_packed_codebook4_and_portable_op() { + std::mt19937 rng(4343); + const uint16_t d = f32_to_fp16(0.025f); + for (auto cb : {freetile::Codebook4::NF4, freetile::Codebook4::FP4_E2M1, freetile::Codebook4::IQ4_NL}) { + for (uint32_t k : {0u, 1u, 17u, 32u, 257u, 2304u}) { + const size_t nb = k == 0u ? 1u : (static_cast(k - 1u) / 32u) + 1u; + std::vector raw(nb * sizeof(freetile::BlockCodebook4)); + for (auto& b : raw) b = static_cast(rng() & 0xFFu); + for (size_t i = 0; i < nb; ++i) write_u16_le(raw.data() + i * sizeof(freetile::BlockCodebook4), d); + std::vector a(k), b(k); + freetile::dequant_packed_codebook4_row(cb, raw.data(), k, a.data(), true); + freetile::dequant_packed_codebook4_row(cb, raw.data(), k, b.data(), false); + CHECK(vec_bit_exact_finite(a, b), "packed codebook4 dequant bit-exact"); + } + } + + // Generic 2-bit (3 selects) and 3-bit (7 selects) scalar sub-lookup StableHLO emission + // (composable primitive for future grid-codebook sub-tables such as IQ2_XXS/IQ3_XXS). + const float t2[4] = {-1.5f, -0.5f, 0.5f, 1.5f}; + const float t3[8] = {-3.5f, -2.5f, -1.5f, -0.5f, 0.5f, 1.5f, 2.5f, 3.5f}; + std::string out2, out3; + const std::string mlir2 = + freetile::emit_stablehlo_select_tree_lut("%arg0", {2304, 2304}, t2, 2u, "lut2", 0, &out2); + const std::string mlir3 = + freetile::emit_stablehlo_select_tree_lut("%arg0", {3072, 3072}, t3, 3u, "lut3", 0, &out3); + CHECK(!out2.empty() && freetile::count_mlir_ops(mlir2, "\"stablehlo.select\"") == 3 && + freetile::count_mlir_ops(mlir2, "stablehlo.gather") == 0, + "2-bit scalar sub-lookup emits 3 selects, 0 gather"); + CHECK(!out3.empty() && freetile::count_mlir_ops(mlir3, "\"stablehlo.select\"") == 7 && + freetile::count_mlir_ops(mlir3, "stablehlo.gather") == 0, + "3-bit scalar sub-lookup emits 7 selects, 0 gather"); + + // Portable FreeTile `codebook_dequant` semantic op across all 4 hardware targets + // and v5e 16 MiB VMEM gather-cliff boundary characterization (<= 5.31M vs >= 9.44M). + const auto op_v5e_cliff = freetile::plan_codebook_dequant_op( + freetile::QuantFormat::IQ4_XS, 2304, 2304, freetile::CodebookTargetBackend::CLOUD_TPU_SELECT_TREE); + CHECK(op_v5e_cliff.index_bits == 4u && op_v5e_cliff.select_ops == 15u && + op_v5e_cliff.v5e_gather_cliff_zone && + std::string(op_v5e_cliff.target_primitive) == "stablehlo.select_tree", + "2304x2304 IQ4_XS is inside v5e gather-cliff band"); + const auto op_v5e_above = freetile::plan_codebook_dequant_op( + freetile::QuantFormat::IQ4_XS, 3072, 3072, freetile::CodebookTargetBackend::CLOUD_TPU_SELECT_TREE); + CHECK(!op_v5e_above.v5e_gather_cliff_zone && op_v5e_above.weight_elements == 3072u * 3072u, + "3072x3072 IQ4_XS exceeds 5.31M v5e cliff band"); + + const auto op_sme2 = freetile::plan_codebook_dequant_op( + freetile::QuantFormat::IQ4_XS, 2304, 2304, freetile::CodebookTargetBackend::ARM_SME2_LUTI4); + CHECK(std::string(op_sme2.target_primitive) == "sme2.luti4" && + std::string(freetile::codebook_backend_name(op_sme2.backend)) == "arm_sme2_luti4", + "ARM SME2 lowers IQ4_XS to sme2.luti4"); + const auto op_hvx = freetile::plan_codebook_dequant_op( + freetile::QuantFormat::IQ4_NL, 4096, 4096, freetile::CodebookTargetBackend::QUALCOMM_HVX_VLUT); + CHECK(op_hvx.index_bits == 4u && op_hvx.select_ops == 15u && + std::string(op_hvx.target_primitive) == "hvx.vlut", + "Qualcomm HVX lowers IQ4_NL to hvx.vlut"); + const auto op_pvr = freetile::plan_codebook_dequant_op( + freetile::QuantFormat::NF4, 6144, 6144, freetile::CodebookTargetBackend::POWERVR_VOLCANIC_SELECT_TREE); + CHECK(std::string(op_pvr.target_primitive) == "volcanic.select_tree", + "PowerVR Volcanic lowers NF4 to volcanic.select_tree"); + + bool rejected = false; + try { (void)freetile::plan_codebook_dequant_op(freetile::QuantFormat::Q4_K, 2304, 2304); } + catch (const std::invalid_argument&) { rejected = true; } + CHECK(rejected, "non-codebook format rejected by plan_codebook_dequant_op"); + std::printf("[PASS] test_packed_codebook4_and_portable_op (packed NF4/FP4, 2/3-bit 3/7-select IR, 4 backends)\n"); +} } // namespace int main() { @@ -336,6 +402,7 @@ int main() { test_iq4xs_matmul_shapes(); test_stablehlo_emission_zero_gather(); test_tile_ir_planning(); + test_packed_codebook4_and_portable_op(); 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/ggml-cloudtpu.cpp b/llama-cpp-cloudtpu/ggml-cloudtpu.cpp index d439ec9..54ae59d 100644 --- a/llama-cpp-cloudtpu/ggml-cloudtpu.cpp +++ b/llama-cpp-cloudtpu/ggml-cloudtpu.cpp @@ -272,14 +272,15 @@ static bool is_dense_supported_type(enum ggml_type t) { } static bool is_quant_split_type(enum ggml_type t) { - return t == GGML_TYPE_Q8_0 || t == GGML_TYPE_Q4_0 || t == GGML_TYPE_Q4_K || t == GGML_TYPE_Q6_K; + return t == GGML_TYPE_Q8_0 || t == GGML_TYPE_Q4_0 || t == GGML_TYPE_Q4_K || t == GGML_TYPE_Q6_K || + t == GGML_TYPE_IQ4_XS || t == GGML_TYPE_IQ4_NL; } static int64_t quant_split_k_alignment(enum ggml_type t) { - if (t == GGML_TYPE_Q4_K || t == GGML_TYPE_Q6_K) { + if (t == GGML_TYPE_Q4_K || t == GGML_TYPE_Q6_K || t == GGML_TYPE_IQ4_XS) { return QK_K; } - if (t == GGML_TYPE_Q8_0 || t == GGML_TYPE_Q4_0) { + if (t == GGML_TYPE_Q8_0 || t == GGML_TYPE_Q4_0 || t == GGML_TYPE_IQ4_NL) { return QK8_0; } return 1; @@ -934,6 +935,22 @@ static Q4SlotPlan resolve_q4_slot_plan(enum ggml_type t, plan.q_dtype = cloudtpu::PjrtDType::U8; return plan; } + if (t == GGML_TYPE_IQ4_XS || t == GGML_TYPE_IQ4_NL) { + const int64_t k_align = (t == GGML_TYPE_IQ4_XS) ? QK_K : QK4_NL; + if ((K % k_align) != 0) { + return plan; + } + const int64_t n_local = (spmd_chips > 1 && sh == cloudtpu::TensorShardingKind::SHARD_N) ? (N / spmd_chips) : N; + plan.storage = (t == GGML_TYPE_IQ4_XS) ? cloudtpu::TensorStorageKind::IQ4_XS_LUT + : cloudtpu::TensorStorageKind::IQ4_NL_LUT; + plan.bitcast_target = cloudtpu::PjrtDType::U4; + if (q4_mode == CloudTpuQ4Mode::BITCAST && (n_local % 2) == 0) { + plan.q_dtype = cloudtpu::PjrtDType::U8; + } else { + plan.q_dtype = cloudtpu::PjrtDType::U4; + } + return plan; + } return plan; } @@ -1160,6 +1177,225 @@ static void pack_i4_to_q4_K(const uint8_t* qs_km, } } +static_assert(sizeof(block_iq4_nl) == 18, "block_iq4_nl must be 18 bytes"); +static_assert(sizeof(block_iq4_xs) == 136, "block_iq4_xs must be 136 bytes"); +static_assert(offsetof(block_iq4_nl, d) == 0 && offsetof(block_iq4_nl, qs) == 2, + "block_iq4_nl wire offsets mismatch"); +static_assert(offsetof(block_iq4_xs, d) == 0 && offsetof(block_iq4_xs, scales_h) == 2 && + offsetof(block_iq4_xs, scales_l) == 4 && offsetof(block_iq4_xs, qs) == 8, + "block_iq4_xs wire offsets mismatch"); + +static void unpack_iq4_nl_to_u4(const void* src_raw, + size_t B, + size_t N, + size_t nb, + bool packed_nibbles, + std::vector& out_qs, + std::vector& out_d_km) { + const auto* src = static_cast(src_raw); + out_d_km.resize(B * nb * N); + const size_t total_elems = B * nb * QK4_NL * N; + out_qs.assign(packed_nibbles ? cloudtpu::pjrt_dtype_nbytes(cloudtpu::PjrtDType::U4, total_elems) : total_elems, 0); + + for (size_t b = 0; b < B; ++b) { + for (size_t n = 0; n < N; ++n) { + const uint8_t* row = src + (b * N + n) * nb * sizeof(block_iq4_nl); + for (size_t blk = 0; blk < nb; ++blk) { + std::memcpy(&out_d_km[(b * nb + blk) * N + n], row + blk * sizeof(block_iq4_nl), sizeof(uint16_t)); + } + } + if (!packed_nibbles) { + for (size_t blk = 0; blk < nb; ++blk) { + for (size_t n = 0; n < N; ++n) { + const uint8_t* sq = src + (((b * N + n) * nb) + blk) * sizeof(block_iq4_nl) + 2; + for (size_t j = 0; j < QK4_NL / 2; ++j) { + const uint8_t byte = sq[j]; + out_qs[((b * nb + blk) * QK4_NL + j) * N + n] = byte & 0x0FU; + out_qs[((b * nb + blk) * QK4_NL + (j + 16)) * N + n] = byte >> 4; + } + } + } + } else if ((N & 1U) == 0U) { + const size_t n_half = N / 2; + for (size_t blk = 0; blk < nb; ++blk) { + for (size_t j = 0; j < QK4_NL / 2; ++j) { + uint8_t* dst_lo = out_qs.data() + (((b * nb + blk) * QK4_NL + j) * n_half); + uint8_t* dst_hi = out_qs.data() + (((b * nb + blk) * QK4_NL + (j + 16)) * n_half); + for (size_t nh = 0; nh < n_half; ++nh) { + const uint8_t b0 = src[(((b * N + (2 * nh + 0)) * nb) + blk) * sizeof(block_iq4_nl) + 2 + j]; + const uint8_t b1 = src[(((b * N + (2 * nh + 1)) * nb) + blk) * sizeof(block_iq4_nl) + 2 + j]; + dst_lo[nh] = static_cast((b0 & 0x0FU) | ((b1 & 0x0FU) << 4)); + dst_hi[nh] = static_cast(((b0 >> 4) & 0x0FU) | (((b1 >> 4) & 0x0FU) << 4)); + } + } + } + } else { + for (size_t blk = 0; blk < nb; ++blk) { + for (size_t n = 0; n < N; ++n) { + const uint8_t* sq = src + (((b * N + n) * nb) + blk) * sizeof(block_iq4_nl) + 2; + for (size_t j = 0; j < QK4_NL / 2; ++j) { + const uint8_t byte = sq[j]; + const size_t idx_lo = (((b * nb + blk) * QK4_NL + j) * N + n); + const size_t idx_hi = (((b * nb + blk) * QK4_NL + (j + 16)) * N + n); + write_nibble_4bit(out_qs.data(), idx_lo, byte & 0x0FU); + write_nibble_4bit(out_qs.data(), idx_hi, (byte >> 4) & 0x0FU); + } + } + } + } + } +} + +static void pack_u4_to_iq4_nl(const uint8_t* qs_km, + const uint16_t* d_km, + size_t B, + size_t N, + size_t nb, + bool packed_nibbles, + void* dst_raw) { + auto* dst = static_cast(dst_raw); + for (size_t b = 0; b < B; ++b) { + for (size_t n = 0; n < N; ++n) { + uint8_t* row = dst + (b * N + n) * nb * sizeof(block_iq4_nl); + for (size_t blk = 0; blk < nb; ++blk) { + uint8_t* blk_dst = row + blk * sizeof(block_iq4_nl); + std::memcpy(blk_dst, &d_km[(b * nb + blk) * N + n], sizeof(uint16_t)); + uint8_t* q = blk_dst + 2; + for (size_t j = 0; j < QK4_NL / 2; ++j) { + const size_t idx_lo = (((b * nb + blk) * QK4_NL + j) * N + n); + const size_t idx_hi = (((b * nb + blk) * QK4_NL + (j + 16)) * N + n); + const uint8_t lo = packed_nibbles ? read_nibble_4bit(qs_km, idx_lo) : (qs_km[idx_lo] & 0x0FU); + const uint8_t hi = packed_nibbles ? read_nibble_4bit(qs_km, idx_hi) : (qs_km[idx_hi] & 0x0FU); + q[j] = static_cast((lo & 0x0FU) | ((hi & 0x0FU) << 4)); + } + } + } + } +} + +// Canonical 136-byte / 256-weight IQ4_XS unpack into K-major U4 indices [B, K/32, 32, N] +// + per-subblock effective scales d_eff = d * (ls - 32) [B, K/32, N] (freetpu#43). +// Reads via byte offsets + memcpy to stay alignment-safe on arbitrary caller buffers. +static void unpack_iq4_xs_to_u4(const void* src_raw, + size_t B, + size_t N, + size_t nb_k, + bool packed_nibbles, + std::vector& out_qs, + std::vector& out_d_km) { + const auto* src = static_cast(src_raw); + const size_t nb32 = nb_k * 8; + out_d_km.resize(B * nb32 * N); + const size_t total_elems = B * nb32 * 32 * N; + out_qs.assign(packed_nibbles ? cloudtpu::pjrt_dtype_nbytes(cloudtpu::PjrtDType::U4, total_elems) : total_elems, 0); + + for (size_t b = 0; b < B; ++b) { + for (size_t n = 0; n < N; ++n) { + const uint8_t* row = src + (b * N + n) * nb_k * sizeof(block_iq4_xs); + for (size_t bk = 0; bk < nb_k; ++bk) { + const uint8_t* blk = row + bk * sizeof(block_iq4_xs); + uint16_t d16 = 0; + uint16_t scales_h = 0; + std::memcpy(&d16, blk + 0, sizeof(uint16_t)); + std::memcpy(&scales_h, blk + 2, sizeof(uint16_t)); + const uint8_t* scales_l = blk + 4; + const float d = cloudtpu::f16_to_f32(d16); + for (int ib = 0; ib < 8; ++ib) { + const int ls = ((scales_l[ib / 2] >> (4 * (ib & 1))) & 0x0F) | + (((scales_h >> (2 * ib)) & 3) << 4); + const float dl = d * static_cast(ls - 32); + const size_t sub = bk * 8 + static_cast(ib); + out_d_km[(b * nb32 + sub) * N + n] = dl; + } + } + } + if (!packed_nibbles) { + for (size_t bk = 0; bk < nb_k; ++bk) { + for (size_t n = 0; n < N; ++n) { + const uint8_t* sq = src + (((b * N + n) * nb_k) + bk) * sizeof(block_iq4_xs) + 8; + for (int ib = 0; ib < 8; ++ib) { + const size_t sub = bk * 8 + static_cast(ib); + const uint8_t* sub_qs = sq + ib * 16; + for (size_t j = 0; j < 16; ++j) { + const uint8_t byte = sub_qs[j]; + out_qs[((b * nb32 + sub) * 32 + j) * N + n] = byte & 0x0FU; + out_qs[((b * nb32 + sub) * 32 + (j + 16)) * N + n] = byte >> 4; + } + } + } + } + } else if ((N & 1U) == 0U) { + const size_t n_half = N / 2; + for (size_t bk = 0; bk < nb_k; ++bk) { + for (int ib = 0; ib < 8; ++ib) { + const size_t sub = bk * 8 + static_cast(ib); + for (size_t j = 0; j < 16; ++j) { + uint8_t* dst_lo = out_qs.data() + (((b * nb32 + sub) * 32 + j) * n_half); + uint8_t* dst_hi = out_qs.data() + (((b * nb32 + sub) * 32 + (j + 16)) * n_half); + for (size_t nh = 0; nh < n_half; ++nh) { + const uint8_t b0 = + src[(((b * N + (2 * nh + 0)) * nb_k) + bk) * sizeof(block_iq4_xs) + 8 + ib * 16 + j]; + const uint8_t b1 = + src[(((b * N + (2 * nh + 1)) * nb_k) + bk) * sizeof(block_iq4_xs) + 8 + ib * 16 + j]; + dst_lo[nh] = static_cast((b0 & 0x0FU) | ((b1 & 0x0FU) << 4)); + dst_hi[nh] = static_cast(((b0 >> 4) & 0x0FU) | (((b1 >> 4) & 0x0FU) << 4)); + } + } + } + } + } else { + for (size_t bk = 0; bk < nb_k; ++bk) { + for (size_t n = 0; n < N; ++n) { + const uint8_t* sq = src + (((b * N + n) * nb_k) + bk) * sizeof(block_iq4_xs) + 8; + for (int ib = 0; ib < 8; ++ib) { + const size_t sub = bk * 8 + static_cast(ib); + const uint8_t* sub_qs = sq + ib * 16; + for (size_t j = 0; j < 16; ++j) { + const uint8_t byte = sub_qs[j]; + const size_t idx_lo = (((b * nb32 + sub) * 32 + j) * N + n); + const size_t idx_hi = (((b * nb32 + sub) * 32 + (j + 16)) * N + n); + write_nibble_4bit(out_qs.data(), idx_lo, byte & 0x0FU); + write_nibble_4bit(out_qs.data(), idx_hi, (byte >> 4) & 0x0FU); + } + } + } + } + } + } +} + +static void pack_u4_to_iq4_xs(const uint8_t* qs_km, + const uint8_t* meta, + size_t B, + size_t N, + size_t nb_k, + bool packed_nibbles, + void* dst_raw) { + auto* dst = static_cast(dst_raw); + const size_t nb32 = nb_k * 8; + for (size_t b = 0; b < B; ++b) { + for (size_t n = 0; n < N; ++n) { + const size_t row_blk_base = (b * N + n) * nb_k; + for (size_t bk = 0; bk < nb_k; ++bk) { + const size_t bi = row_blk_base + bk; + uint8_t* blk_dst = dst + bi * sizeof(block_iq4_xs); + std::memcpy(blk_dst, meta + bi * 8, 8); + uint8_t* q = blk_dst + 8; + for (int ib = 0; ib < 8; ++ib) { + const size_t sub = bk * 8 + static_cast(ib); + for (size_t j = 0; j < 16; ++j) { + const size_t idx_lo = (((b * nb32 + sub) * 32 + j) * N + n); + const size_t idx_hi = (((b * nb32 + sub) * 32 + (j + 16)) * N + n); + const uint8_t lo = packed_nibbles ? read_nibble_4bit(qs_km, idx_lo) : (qs_km[idx_lo] & 0x0FU); + const uint8_t hi = packed_nibbles ? read_nibble_4bit(qs_km, idx_hi) : (qs_km[idx_hi] & 0x0FU); + q[ib * 16 + j] = static_cast((lo & 0x0FU) | ((hi & 0x0FU) << 4)); + } + } + } + } + } +} + static cloudtpu::TensorShardingKind choose_upload_sharding(const struct ggml_tensor* tensor, int spmd_chips, int spmd_min_rows, @@ -1194,7 +1430,8 @@ static cloudtpu::TensorShardingKind choose_upload_sharding(const struct ggml_ten // Packed U8 bitcast mode stores two rows per byte and requires an even per-chip N; // native S4/U4 mode transfers 1 host byte/element and supports arbitrary odd per-chip N. const bool is_q4_bitcast = - (tensor->type == GGML_TYPE_Q4_0 || tensor->type == GGML_TYPE_Q4_K) && + (tensor->type == GGML_TYPE_Q4_0 || tensor->type == GGML_TYPE_Q4_K || + tensor->type == GGML_TYPE_IQ4_XS || tensor->type == GGML_TYPE_IQ4_NL) && (q4_mode == CloudTpuQ4Mode::BITCAST); const int64_t n_align = is_q4_bitcast ? (static_cast(spmd_chips) * 2) : static_cast(spmd_chips); // Prefer SHARD_K for row-parallel FFN down projections and embedding tables (enables 1-collective @@ -1549,6 +1786,66 @@ static void upload_raw_tensor_to_slot(cloudtpu::PjrtRuntime& rt, {B3, B2, nb16, N}, q4_shard_ax); } slot.hbm_mins.clear(); + } else if (is_contig && tensor->type == GGML_TYPE_IQ4_NL && (K % QK4_NL) == 0) { + const size_t nb = static_cast(K / QK4_NL); + const Q4SlotPlan q4p = resolve_q4_slot_plan(tensor->type, K, N, spmd_chips, sh, q4_mode, q4k_u4); + slot.storage = q4p.storage; + slot.dtype = q4p.q_dtype; + slot.scale_dtype = cloudtpu::PjrtDType::F16; + slot.bitcast_target = cloudtpu::PjrtDType::U4; + std::vector qs_data; + std::vector d_km; + const bool packed_nibbles = (q4p.q_dtype == cloudtpu::PjrtDType::U8); + unpack_iq4_nl_to_u4(raw_data, B, static_cast(N), nb, + packed_nibbles, qs_data, d_km); + const std::vector qs_dims = packed_nibbles + ? std::vector{B3, B2, static_cast(nb), QK4_NL, N / 2} + : std::vector{B3, B2, static_cast(nb), QK4_NL, N}; + slot.hbm_primary = upload_sharded_part( + rt, device_index, spmd_chips, sh, qs_data.data(), q4p.q_dtype, qs_dims, q5_shard_ax); + slot.hbm_scales = upload_sharded_part( + rt, device_index, spmd_chips, sh, d_km.data(), cloudtpu::PjrtDType::F16, + {B3, B2, static_cast(nb), N}, q4_shard_ax); + slot.hbm_mins.clear(); + } else if (is_contig && tensor->type == GGML_TYPE_IQ4_XS && (K % QK_K) == 0) { + const size_t nb_k = static_cast(K / QK_K); + const int64_t nb32 = K / 32; + const size_t nrows = static_cast(B3 * B2 * N); + const size_t total_k_blocks = nrows * nb_k; + const auto* src_bytes = static_cast(raw_data); + slot.quant_meta.resize(total_k_blocks * 8); + for (size_t b = 0; b < total_k_blocks; ++b) { + std::memcpy(slot.quant_meta.data() + b * 8, src_bytes + b * sizeof(block_iq4_xs), 8); + } + const Q4SlotPlan q4p = resolve_q4_slot_plan(tensor->type, K, N, spmd_chips, sh, q4_mode, q4k_u4); + slot.storage = q4p.storage; + slot.dtype = q4p.q_dtype; + slot.bitcast_target = cloudtpu::PjrtDType::U4; + std::vector qs_data; + std::vector d_km_f32; + const bool packed_nibbles = (q4p.q_dtype == cloudtpu::PjrtDType::U8); + unpack_iq4_xs_to_u4(raw_data, B, static_cast(N), nb_k, packed_nibbles, qs_data, d_km_f32); + const std::vector qs_dims = packed_nibbles + ? std::vector{B3, B2, nb32, 32, N / 2} + : std::vector{B3, B2, nb32, 32, N}; + slot.hbm_primary = upload_sharded_part( + rt, device_index, spmd_chips, sh, qs_data.data(), q4p.q_dtype, qs_dims, q5_shard_ax); + if (q4k_bf16_scales) { + std::vector d_km_bf16(d_km_f32.size()); + for (size_t i = 0; i < d_km_f32.size(); ++i) { + d_km_bf16[i] = cloudtpu::f32_to_bf16(d_km_f32[i]); + } + slot.scale_dtype = cloudtpu::PjrtDType::BF16; + slot.hbm_scales = upload_sharded_part( + rt, device_index, spmd_chips, sh, d_km_bf16.data(), cloudtpu::PjrtDType::BF16, + {B3, B2, nb32, N}, q4_shard_ax); + } else { + slot.scale_dtype = cloudtpu::PjrtDType::F32; + slot.hbm_scales = upload_sharded_part( + rt, device_index, spmd_chips, sh, d_km_f32.data(), cloudtpu::PjrtDType::F32, + {B3, B2, nb32, N}, q4_shard_ax); + } + slot.hbm_mins.clear(); } else { const cloudtpu::PjrtDType pdt = ggml_type_to_pjrt(tensor->type); if (pdt != cloudtpu::PjrtDType::INVALID && is_contig) { @@ -1652,6 +1949,26 @@ static void download_slot_to_host(cloudtpu::PjrtRuntime& rt, download_sharded_part(rt, slot.sharding, slot.hbm_primary, qs_km.data(), qs_km.size(), q5_shard_ax); auto qs = transpose_minor_to_n(qs_km.data(), B, N, K); pack_split_to_q6_K(qs.data(), slot.quant_meta.data(), total_k_blocks, static_cast(dst_full)); + } else if (slot.storage == cloudtpu::TensorStorageKind::IQ4_NL_LUT) { + const size_t total_blocks = slot.hbm_scales[0]->num_elements() * shard_mul; + const size_t nb = K / QK4_NL; + const size_t total_elems = total_blocks * QK4_NL; + const bool packed_nibbles = (slot.dtype == cloudtpu::PjrtDType::U8); + std::vector qs_data( + packed_nibbles ? cloudtpu::pjrt_dtype_nbytes(cloudtpu::PjrtDType::U4, total_elems) : total_elems); + std::vector d_km(total_blocks); + download_sharded_part(rt, slot.sharding, slot.hbm_primary, qs_data.data(), qs_data.size(), q5_shard_ax); + download_sharded_part(rt, slot.sharding, slot.hbm_scales, d_km.data(), d_km.size() * sizeof(uint16_t), q4_shard_ax); + pack_u4_to_iq4_nl(qs_data.data(), d_km.data(), B, N, nb, packed_nibbles, dst_full); + } else if (slot.storage == cloudtpu::TensorStorageKind::IQ4_XS_LUT) { + const size_t total_sub = slot.hbm_scales[0]->num_elements() * shard_mul; + const size_t nb_k = K / QK_K; + const size_t total_elems = total_sub * 32; + const bool packed_nibbles = (slot.dtype == cloudtpu::PjrtDType::U8); + std::vector qs_data( + packed_nibbles ? cloudtpu::pjrt_dtype_nbytes(cloudtpu::PjrtDType::U4, total_elems) : total_elems); + download_sharded_part(rt, slot.sharding, slot.hbm_primary, qs_data.data(), qs_data.size(), q5_shard_ax); + pack_u4_to_iq4_xs(qs_data.data(), slot.quant_meta.data(), B, N, nb_k, packed_nibbles, dst_full); } else if (slot.hbm_token_axis >= 0 && slot.hbm_token_axis < 4 && slot.hbm_dims[slot.hbm_token_axis] > slot.dims[slot.hbm_token_axis] && slot.storage == cloudtpu::TensorStorageKind::DENSE) { @@ -1707,7 +2024,12 @@ static bool patch_view_into_root_slot_locked(cloudtpu::PjrtRuntime& rt, return false; } auto pit = bctx->slots.find(root_off); - if (pit == bctx->slots.end() || pit->second.nbytes != root_bytes) { + const bool root_matches_slot = + (pit != bctx->slots.end() && pit->second.nbytes == root_bytes && + pit->second.ggml_dt == root->type && + pit->second.dims[0] == root->ne[3] && pit->second.dims[1] == root->ne[2] && + pit->second.dims[2] == root->ne[1] && pit->second.dims[3] == root->ne[0]); + if (!root_matches_slot) { const cloudtpu::TensorShardingKind root_sh = choose_upload_sharding( root, bctx->spmd_chips, bctx->spmd_min_rows, /*allow_sharding=*/true, bctx->q4_mode); const size_t rel_new = (t_off - root_off) + offset; @@ -1741,6 +2063,11 @@ static bool patch_view_into_root_slot_locked(cloudtpu::PjrtRuntime& rt, CloudTpuTensorSlot& parent = bctx->slots[root_off]; parent.offset = root_off; parent.nbytes = root_bytes; + parent.ggml_dt = root->type; + parent.dims[0] = root->ne[3]; + parent.dims[1] = root->ne[2]; + parent.dims[2] = root->ne[1]; + parent.dims[3] = root->ne[0]; parent.sharding = root_sh; parent.hbm_primary.clear(); parent.hbm_scales.clear(); @@ -1924,6 +2251,11 @@ static void ggml_backend_cloudtpu_buffer_memset_tensor(ggml_backend_buffer_t buf CloudTpuTensorSlot& slot = bctx->slots[t_off]; slot.offset = t_off; slot.nbytes = t_bytes; + slot.ggml_dt = tensor->type; + slot.dims[0] = tensor->ne[3]; + slot.dims[1] = tensor->ne[2]; + slot.dims[2] = tensor->ne[1]; + slot.dims[3] = tensor->ne[0]; slot.sharding = choose_upload_sharding( tensor, bctx->spmd_chips, bctx->spmd_min_rows, /*allow_sharding=*/true, bctx->q4_mode); slot.hbm_primary.clear(); @@ -2004,6 +2336,11 @@ static void ggml_backend_cloudtpu_buffer_set_tensor(ggml_backend_buffer_t buffer CloudTpuTensorSlot& slot = bctx->slots[t_off]; slot.offset = t_off; slot.nbytes = t_bytes; + slot.ggml_dt = tensor->type; + slot.dims[0] = tensor->ne[3]; + slot.dims[1] = tensor->ne[2]; + slot.dims[2] = tensor->ne[1]; + slot.dims[3] = tensor->ne[0]; slot.sharding = choose_upload_sharding( tensor, bctx->spmd_chips, bctx->spmd_min_rows, /*allow_sharding=*/true, bctx->q4_mode); slot.hbm_primary.clear(); @@ -2303,15 +2640,19 @@ static size_t ggml_backend_cloudtpu_buffer_type_get_alloc_size(ggml_backend_buff const bool bf16_scales = (btc && btc->q4k_bf16_scales); size_t base_size = ggml_nbytes(tensor); const int64_t K = tensor->ne[0]; - if (K > 0 && (K % QK_K) == 0 && (tensor->type == GGML_TYPE_Q4_K || tensor->type == GGML_TYPE_Q6_K)) { + if (K > 0 && (K % QK_K) == 0 && + (tensor->type == GGML_TYPE_Q4_K || tensor->type == GGML_TYPE_Q6_K || tensor->type == GGML_TYPE_IQ4_XS)) { const size_t n_blocks = static_cast(K / QK_K) * static_cast(std::max(1, tensor->ne[1])) * static_cast(std::max(1, tensor->ne[2])) * static_cast(std::max(1, tensor->ne[3])); - // Split HBM representation expands Q4_K (128B u8 + 32B/16B d + 32B/16B m = 192B/160B/block) - // and Q6_K (256B s8 + 64B/32B d = 320B/288B/block) relative to packed GGML blocks. + // Split HBM representation expands Q4_K (128B u8 + 32B/16B d + 32B/16B m = 192B/160B/block), + // Q6_K (256B s8 + 64B/32B d = 320B/288B/block), and IQ4_XS (128B u4 + 32B/16B d_eff = 160B/144B/block). const size_t bytes_per_block = - (tensor->type == GGML_TYPE_Q4_K) ? (bf16_scales ? 160U : 192U) : (bf16_scales ? 288U : 320U); + (tensor->type == GGML_TYPE_Q4_K) + ? (bf16_scales ? 160U : 192U) + : ((tensor->type == GGML_TYPE_IQ4_XS) ? (bf16_scales ? 144U : 160U) + : (bf16_scales ? 288U : 320U)); if (n_blocks <= SIZE_MAX / bytes_per_block) { base_size = std::max(base_size, n_blocks * bytes_per_block); } @@ -2989,6 +3330,17 @@ static cloudtpu::TensorSpec tensor_to_spec(const struct ggml_tensor* t, } else if (t->type == GGML_TYPE_Q6_K) { ts.storage = cloudtpu::TensorStorageKind::Q6_K_SPLIT; ts.dtype = cloudtpu::PjrtDType::S8; + } else if (t->type == GGML_TYPE_IQ4_XS || t->type == GGML_TYPE_IQ4_NL) { + if (q4_plan && q4_plan->storage != cloudtpu::TensorStorageKind::DENSE) { + ts.storage = q4_plan->storage; + ts.dtype = q4_plan->q_dtype; + ts.bitcast_target = cloudtpu::PjrtDType::U4; + } else { + ts.storage = (t->type == GGML_TYPE_IQ4_XS) ? cloudtpu::TensorStorageKind::IQ4_XS_LUT + : cloudtpu::TensorStorageKind::IQ4_NL_LUT; + ts.dtype = cloudtpu::PjrtDType::U4; + ts.bitcast_target = cloudtpu::PjrtDType::U4; + } } else { ts.storage = cloudtpu::TensorStorageKind::DENSE; ts.dtype = ggml_type_to_pjrt(t->type); @@ -3030,7 +3382,8 @@ static Q4SlotPlan lookup_tensor_q4_plan(const struct ggml_tensor* t, cloudtpu::TensorShardingKind sh, CloudTpuQ4Mode default_q4_mode, bool default_q4k_u4) { - if (!t || (t->type != GGML_TYPE_Q4_0 && t->type != GGML_TYPE_Q4_K)) { + if (!t || (t->type != GGML_TYPE_Q4_0 && t->type != GGML_TYPE_Q4_K && + t->type != GGML_TYPE_IQ4_XS && t->type != GGML_TYPE_IQ4_NL)) { return {}; } if (t->buffer && is_cloudtpu_buffer(t->buffer)) { @@ -3078,7 +3431,7 @@ static cloudtpu::PjrtDType lookup_tensor_scale_dtype(const struct ggml_tensor* t if (!t || !is_quant_split_type(t->type)) { return cloudtpu::PjrtDType::INVALID; } - if (t->type == GGML_TYPE_Q8_0 || t->type == GGML_TYPE_Q4_0) { + if (t->type == GGML_TYPE_Q8_0 || t->type == GGML_TYPE_Q4_0 || t->type == GGML_TYPE_IQ4_NL) { return cloudtpu::PjrtDType::F16; } if (t->buffer && is_cloudtpu_buffer(t->buffer)) { @@ -3086,7 +3439,11 @@ static cloudtpu::PjrtDType lookup_tensor_scale_dtype(const struct ggml_tensor* t const size_t t_off = tensor_offset_in_buffer(bctx, t); std::lock_guard lock(bctx->mu); auto it = bctx->slots.find(t_off); - if (it != bctx->slots.end() && it->second.scale_dtype != cloudtpu::PjrtDType::INVALID) { + if (it != bctx->slots.end() && + it->second.ggml_dt == t->type && + it->second.dims[0] == t->ne[3] && it->second.dims[1] == t->ne[2] && + it->second.dims[2] == t->ne[1] && it->second.dims[3] == t->ne[0] && + it->second.scale_dtype != cloudtpu::PjrtDType::INVALID) { return it->second.scale_dtype; } return bctx->q4k_bf16_scales ? cloudtpu::PjrtDType::BF16 : cloudtpu::PjrtDType::F32; diff --git a/llama-cpp-cloudtpu/stablehlo_emitter.cpp b/llama-cpp-cloudtpu/stablehlo_emitter.cpp index 4947f70..ceeee47 100644 --- a/llama-cpp-cloudtpu/stablehlo_emitter.cpp +++ b/llama-cpp-cloudtpu/stablehlo_emitter.cpp @@ -635,6 +635,43 @@ SsaValue apply_fp8_scales(StableHloBuilder& b, return b.emit_binary("stablehlo.multiply", dot_f32, scale_b); } +// Canonical GGUF IQ4_NL / IQ4_XS 16-entry non-linear codebook (exact integer values in F32). +constexpr std::array kIq4NlTableF32 = { + -127.0f, -104.0f, -83.0f, -65.0f, -49.0f, -35.0f, -22.0f, -10.0f, + 1.0f, 13.0f, 25.0f, 38.0f, 53.0f, 69.0f, 89.0f, 113.0f, +}; + +// Branchless 4-bit select-tree LUT on an unsigned integer index tensor (freetpu#43): +// b0..b3 predicates, 16 splat leaves, 8->4->2->1 stablehlo.select levels (15 selects, 0 gather). +SsaValue select_tree_lut4_value(StableHloBuilder& b, const SsaValue& idx, + const std::array& table16) { + if (idx.dtype != PjrtDType::U32 && idx.dtype != PjrtDType::U8 && idx.dtype != PjrtDType::U4) { + throw std::invalid_argument("select_tree_lut4_value: idx dtype must be U32, U8, or U4"); + } + const SsaValue idx_u32 = (idx.dtype == PjrtDType::U32) ? idx : b.emit_convert(idx, PjrtDType::U32); + SsaValue zero = b.emit_const_splat_int(0, idx_u32.dims, PjrtDType::U32); + SsaValue one = b.emit_const_splat_int(1, idx_u32.dims, PjrtDType::U32); + std::vector pred; + for (int bit = 0; bit < 4; ++bit) { + SsaValue bits = idx_u32; + if (bit > 0) { + SsaValue shamt = b.emit_const_splat_int(bit, idx_u32.dims, PjrtDType::U32); + bits = b.emit_binary("stablehlo.shift_right_logical", idx_u32, 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_u32.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]; +} + // Dequantizes row-major [B3, B2, N_idx, NB, qs_blk] + [B3, B2, N_idx, NB] blocks (used by GET_ROWS // after gathering only the small selected subset of rows). SsaValue dequantize_row_major_blocks(StableHloBuilder& b, @@ -660,6 +697,16 @@ SsaValue dequantize_row_major_blocks(StableHloBuilder& b, SsaValue scaled = b.emit_binary("stablehlo.multiply", q_f, d_b); return b.emit_convert(b.emit_reshape(scaled, {B3, B2, N, K}), out_dt); } + if (storage == TensorStorageKind::IQ4_XS_LUT || storage == TensorStorageKind::IQ4_NL_LUT) { + const SsaValue qs_u = (qs.dtype == PjrtDType::U4 || qs.dtype == PjrtDType::U8 || qs.dtype == PjrtDType::U32) + ? qs + : b.emit_convert(qs, PjrtDType::U32); + SsaValue q_f = select_tree_lut4_value(b, qs_u, kIq4NlTableF32); + SsaValue d_c = b.emit_convert(d, calc_dt); + SsaValue d_b = b.emit_broadcast_in_dim(d_c, {0, 1, 2, 3}, blk_dims); + SsaValue scaled = b.emit_binary("stablehlo.multiply", q_f, d_b); + return b.emit_convert(b.emit_reshape(scaled, {B3, B2, N, K}), out_dt); + } if (storage == TensorStorageKind::Q4_0_I4 || storage == TensorStorageKind::Q4_K_I4) { SsaValue q_f = b.emit_convert(qs, calc_dt); if (storage == TensorStorageKind::Q4_0_I4 && effective_q_dt == PjrtDType::U4) { @@ -730,6 +777,8 @@ SsaValue materialize_q4_i4_nibbles(StableHloBuilder& b, // Q6_K_SPLIT: qs [B3, B2, NB, 16, N] S8, d [B3, B2, NB, N] F32/BF16 -> [B3, B2, NB, 16, N] // Q4_0_I4: qs [B3, B2, NB, 32, N] S4/U4, d [B3, B2, NB, N] F16 -> [B3, B2, NB, 32, N] // Q4_K_I4: qs [B3, B2, NB, 32, N] S4/U4, d/m [B3, B2, NB, N] F32/BF16 -> [B3, B2, NB, 32, N] +// IQ4_XS_LUT: qs [B3, B2, NB, 32, N] U4, d [B3, B2, NB, N] F32/BF16 -> [B3, B2, NB, 32, N] (15 selects, 0 gather) +// IQ4_NL_LUT: qs [B3, B2, NB, 32, N] U4, d [B3, B2, NB, N] F16 -> [B3, B2, NB, 32, N] (15 selects, 0 gather) SsaValue dequantize_k_major_blocks(StableHloBuilder& b, TensorStorageKind storage, const SsaValue& qs, @@ -744,6 +793,15 @@ SsaValue dequantize_k_major_blocks(StableHloBuilder& b, const int64_t blk_elems = (storage == TensorStorageKind::Q6_K_SPLIT) ? 16 : 32; const std::vector km_dims = {B3, B2, NB, blk_elems, N}; + if (storage == TensorStorageKind::IQ4_XS_LUT || storage == TensorStorageKind::IQ4_NL_LUT) { + SsaValue qs_u4 = materialize_q4_i4_nibbles(b, qs, PjrtDType::U4, N); + SsaValue q_f = select_tree_lut4_value(b, qs_u4, kIq4NlTableF32); + SsaValue d_c = b.emit_convert(d, PjrtDType::F32); + SsaValue d_b = b.emit_broadcast_in_dim(d_c, {0, 1, 2, 4}, km_dims); + SsaValue scaled = b.emit_binary("stablehlo.multiply", q_f, d_b); + return b.emit_convert(scaled, out_dt); + } + SsaValue qs_eff = qs; if (storage == TensorStorageKind::Q4_0_I4 || storage == TensorStorageKind::Q4_K_I4) { const PjrtDType target_4bit = (bitcast_target != PjrtDType::INVALID) ? bitcast_target : PjrtDType::S4; @@ -841,7 +899,8 @@ SsaValue dequantize_split_weight(StableHloBuilder& b, const int64_t K = NB * blk_elems; if (storage == TensorStorageKind::Q8_0_SPLIT || storage == TensorStorageKind::Q6_K_SPLIT || - storage == TensorStorageKind::Q4_0_I4 || storage == TensorStorageKind::Q4_K_I4) { + storage == TensorStorageKind::Q4_0_I4 || storage == TensorStorageKind::Q4_K_I4 || + storage == TensorStorageKind::IQ4_XS_LUT || storage == TensorStorageKind::IQ4_NL_LUT) { SsaValue km = dequantize_k_major_blocks(b, storage, qs, d, m_opt, bitcast_target, out_dt); SsaValue nm = b.emit_transpose(km, {0, 1, 4, 2, 3}); return b.emit_reshape(nm, {B3, B2, N, K}); @@ -975,37 +1034,6 @@ std::string build_canonical_cache_key(const std::string& mlir_text, return oss.str(); } -// Branchless 4-bit select-tree LUT on an unsigned integer 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) { - if (idx.dtype != PjrtDType::U32 && idx.dtype != PjrtDType::U8 && idx.dtype != PjrtDType::U4) { - throw std::invalid_argument("select_tree_lut4_value: idx dtype must be U32, U8, or U4"); - } - const SsaValue idx_u32 = (idx.dtype == PjrtDType::U32) ? idx : b.emit_convert(idx, PjrtDType::U32); - SsaValue zero = b.emit_const_splat_int(0, idx_u32.dims, PjrtDType::U32); - SsaValue one = b.emit_const_splat_int(1, idx_u32.dims, PjrtDType::U32); - std::vector pred; - for (int bit = 0; bit < 4; ++bit) { - SsaValue bits = idx_u32; - if (bit > 0) { - SsaValue shamt = b.emit_const_splat_int(bit, idx_u32.dims, PjrtDType::U32); - bits = b.emit_binary("stablehlo.shift_right_logical", idx_u32, 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_u32.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, @@ -1137,8 +1165,10 @@ EmittedProgram emit_stablehlo_program(const GraphProgramSpec& spec) { th.dense = builder.arg_val(arg_idx - 1); prog.input_bindings.push_back({in.id, 0, in.dtype, std::move(dims), alias_out >= 0}); } else { + const bool is_iq4_lut = + (in.storage == TensorStorageKind::IQ4_XS_LUT || in.storage == TensorStorageKind::IQ4_NL_LUT); const bool is_i4_storage = - (in.storage == TensorStorageKind::Q4_0_I4 || in.storage == TensorStorageKind::Q4_K_I4); + (in.storage == TensorStorageKind::Q4_0_I4 || in.storage == TensorStorageKind::Q4_K_I4 || is_iq4_lut); const int64_t blk_elems = (in.storage == TensorStorageKind::Q6_K_SPLIT) ? 16 : 32; if (K <= 0 || (K % blk_elems) != 0) { throw std::runtime_error("emit_stablehlo_program: quantized tensor K alignment error"); @@ -1154,18 +1184,22 @@ EmittedProgram emit_stablehlo_program(const GraphProgramSpec& spec) { qs_blk = 32; if (in.dtype == PjrtDType::U8) { if ((M_or_N % 2) != 0) { - throw std::runtime_error("emit_stablehlo_program: Q4_*_I4 bitcast mode requires even local N"); + throw std::runtime_error("emit_stablehlo_program: Q4/IQ4 bitcast mode requires even local N"); } q_dt = PjrtDType::U8; qs_n = M_or_N / 2; + if (is_iq4_lut) { + th.bitcast_target = PjrtDType::U4; + } } else { - q_dt = (in.dtype == PjrtDType::U4) ? PjrtDType::U4 : PjrtDType::S4; + q_dt = (is_iq4_lut || in.dtype == PjrtDType::U4) ? PjrtDType::U4 : PjrtDType::S4; } } const PjrtDType default_d_dt = (in.storage == TensorStorageKind::Q4_K_SPLIT || in.storage == TensorStorageKind::Q4_K_I4 || - in.storage == TensorStorageKind::Q6_K_SPLIT) + in.storage == TensorStorageKind::Q6_K_SPLIT || + in.storage == TensorStorageKind::IQ4_XS_LUT) ? PjrtDType::F32 : PjrtDType::F16; const PjrtDType d_dt = (in.scale_dtype != PjrtDType::INVALID) ? in.scale_dtype : default_d_dt; @@ -1402,6 +1436,8 @@ EmittedProgram emit_stablehlo_program(const GraphProgramSpec& spec) { x.dims[0] == 1 && x.dims[1] == 1 && m_orig >= 1 && m_orig < spec.mm_pad_m && (w_th.storage == TensorStorageKind::Q6_K_SPLIT || + w_th.storage == TensorStorageKind::IQ4_XS_LUT || + w_th.storage == TensorStorageKind::IQ4_NL_LUT || (is_q4_factored && spec.mm_pad_m <= 32)); SsaValue x_mm = x; if (apply_pad_m) { @@ -1415,7 +1451,9 @@ EmittedProgram emit_stablehlo_program(const GraphProgramSpec& spec) { if (emitted_freetile_mosaic) { // Collectives handled uniformly below (skipping apply_pad_m slice). } else if (w_th.storage == TensorStorageKind::Q8_0_SPLIT || - w_th.storage == TensorStorageKind::Q6_K_SPLIT) { + w_th.storage == TensorStorageKind::Q6_K_SPLIT || + w_th.storage == TensorStorageKind::IQ4_XS_LUT || + w_th.storage == TensorStorageKind::IQ4_NL_LUT) { SsaValue w_km = dequantize_k_major_blocks( builder, w_th.storage, w_th.q_qs, w_th.q_d, nullptr, w_th.bitcast_target, mm_dt); @@ -1432,9 +1470,17 @@ EmittedProgram emit_stablehlo_program(const GraphProgramSpec& spec) { apply_fp8_scales(builder, dot_f32, qx.scale_f32, &qw.scale_f32); local_out = builder.emit_convert(scaled_out, op.dst.dtype); } else { + // On Cloud TPU, F32 dot_general defaults to BF16 MXU operand rounding + // unless precision = [HIGHEST, HIGHEST] is requested; enforce HIGHEST + // on the F32 IQ4 select-tree path to preserve exact F32 parity. + const bool dot_high_precision = + op.high_precision || + ((w_th.storage == TensorStorageKind::IQ4_XS_LUT || + w_th.storage == TensorStorageKind::IQ4_NL_LUT) && + mm_dt == PjrtDType::F32); local_out = builder.emit_dot_general( x_blk, w_km, {0, 1}, {0, 1}, {3, 4}, {2, 3}, dot_out_dims, op.dst.dtype, - op.high_precision); + dot_high_precision); } } else if (is_q4_i4) { if (is_q4_factored) { @@ -1932,7 +1978,9 @@ EmittedProgram emit_stablehlo_program(const GraphProgramSpec& spec) { SsaValue g_qs; PjrtDType eff_q_dt = tbl.q_qs.dtype; if ((tbl.storage == TensorStorageKind::Q4_0_I4 || - tbl.storage == TensorStorageKind::Q4_K_I4) && + tbl.storage == TensorStorageKind::Q4_K_I4 || + tbl.storage == TensorStorageKind::IQ4_XS_LUT || + tbl.storage == TensorStorageKind::IQ4_NL_LUT) && tbl.q_qs.dtype == PjrtDType::U8) { // Packed bitcast U8 [..., 32, N_local/2]: gather byte (eff_idx1 >> 1), extract nibble (eff_idx1 & 1). SsaValue one = builder.emit_const_splat_int(1, idx_col_dims, PjrtDType::S32); diff --git a/llama-cpp-cloudtpu/stablehlo_emitter.hpp b/llama-cpp-cloudtpu/stablehlo_emitter.hpp index 4a424c4..e045c9c 100644 --- a/llama-cpp-cloudtpu/stablehlo_emitter.hpp +++ b/llama-cpp-cloudtpu/stablehlo_emitter.hpp @@ -17,6 +17,8 @@ enum class TensorStorageKind { Q6_K_SPLIT, // K-major N-minor: (qs: [B3, B2, K/16, 16, N] S8, d_eff: [B3, B2, K/16, N] F32/BF16) Q4_0_I4, // Single-read K-major: (qs: [B3, B2, K/32, 32, N] S4/U4 or [..., N/2] U8 bitcast, d: [B3, B2, K/32, N] F16) Q4_K_I4, // Single-read K-major: (qs: [B3, B2, K/32, 32, N] S4/U4 or [..., N/2] U8 bitcast, d_eff/m_eff: [B3, B2, K/32, N] F32/BF16) + IQ4_XS_LUT, // Branchless VREG select-tree LUT (freetpu#43): (qs: [B3, B2, K/32, 32, N] U4 or [..., N/2] U8 bitcast, d_eff: [B3, B2, K/32, N] F32/BF16) + IQ4_NL_LUT, // Branchless VREG select-tree LUT (freetpu#43): (qs: [B3, B2, K/32, 32, N] U4 or [..., N/2] U8 bitcast, d: [B3, B2, K/32, N] F16) }; enum class TensorShardingKind { diff --git a/llama-cpp-cloudtpu/tests/test_cloudtpu_host.cpp b/llama-cpp-cloudtpu/tests/test_cloudtpu_host.cpp index b576629..81de718 100644 --- a/llama-cpp-cloudtpu/tests/test_cloudtpu_host.cpp +++ b/llama-cpp-cloudtpu/tests/test_cloudtpu_host.cpp @@ -367,6 +367,300 @@ void test_select_tree_lut4_program(cloudtpu::PjrtRuntime& rt) { } } +void test_iq4xs_select_tree_matmul_and_get_rows(cloudtpu::PjrtRuntime& rt) { + const int fail_before = g_failures; + 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; + }; + + // 1) MLIR structural checks across non-power-of-2 MoE shapes (2304, 3072, 4096, 6144) + // for both decode (M=1, M=64) and prefill (M=128): 15 selects, 0 gather. + for (int64_t kn : {2304, 3072, 4096, 6144}) { + for (int64_t m : {1, 64, 128}) { + cloudtpu::GraphProgramSpec spec; + spec.bf16_matmul = (m != 1); + spec.mm_pad_m = 8; + cloudtpu::TensorSpec w{1, cloudtpu::PjrtDType::U4, cloudtpu::TensorStorageKind::IQ4_XS_LUT, {1, 1, kn, kn}}; + w.scale_dtype = cloudtpu::PjrtDType::F32; + cloudtpu::TensorSpec x{2, cloudtpu::PjrtDType::F32, cloudtpu::TensorStorageKind::DENSE, {1, 1, m, kn}}; + spec.inputs = {w, x}; + cloudtpu::OpNodeSpec op; + op.kind = cloudtpu::CloudOpKind::MUL_MAT; + op.src_ids = {1, 2}; + op.dst = {3, cloudtpu::PjrtDType::F32, cloudtpu::TensorStorageKind::DENSE, {1, 1, m, kn}}; + spec.ops = {op}; + spec.output_ids = {3}; + const auto prog = cloudtpu::emit_stablehlo_program(spec); + CHECK_TRUE(count(prog.mlir_text, "\"stablehlo.select\"") == 15, "IQ4_XS_LUT MUL_MAT emits 15 selects"); + CHECK_TRUE(count(prog.mlir_text, "stablehlo.gather") == 0, "IQ4_XS_LUT MUL_MAT emits 0 gather"); + CHECK_TRUE(prog.mlir_text.find("stablehlo.dot_general") != std::string::npos, + "IQ4_XS_LUT MUL_MAT emits dot_general"); + } + } + + // 2) End-to-end PJRT execution from canonical 136-byte / 256-weight IQ4_XS blocks: + // verify 0.0 bit-exact diff vs independent canonical IQ4_XS reference matmul (U4 & U8 bitcast) + // plus BF16 MXU pad8 parity and GET_ROWS bit-exact parity. + constexpr int64_t M = 4, K = 256, N = 16; + constexpr int64_t NB32 = K / 32; + struct RawIq4XsBlock { + uint16_t d; + uint16_t scales_h; + uint8_t scales_l[4]; + uint8_t qs[128]; + }; + static_assert(sizeof(RawIq4XsBlock) == 136, "canonical IQ4_XS block is 136 bytes"); + + std::vector blocks(static_cast(N)); + std::vector qs_u4(static_cast(NB32 * 32 * N)); + std::vector qs_bitcast(static_cast(NB32 * 32 * (N / 2))); + std::vector d_eff_km(static_cast(NB32 * N)); + std::vector w_ref(static_cast(N * K)); + + const uint16_t d_f16 = cloudtpu::f32_to_f16(0.015625f); // exact power of 2 in F16 + for (int64_t n = 0; n < N; ++n) { + auto& blk = blocks[static_cast(n)]; + blk.d = d_f16; + blk.scales_h = static_cast((0x5A3Cu + static_cast(n) * 0x1111u) & 0xFFFFu); + for (int i = 0; i < 4; ++i) { + blk.scales_l[i] = static_cast((n * 19 + i * 37 + 5) & 0xFFu); + } + for (int i = 0; i < 128; ++i) { + const uint8_t lo = static_cast((n * 7 + i) & 0x0Fu); + const uint8_t hi = static_cast((n * 11 + i * 3 + 5) & 0x0Fu); + blk.qs[i] = static_cast(lo | (hi << 4)); + } + const float d_f32 = cloudtpu::f16_to_f32(blk.d); + for (int64_t ib = 0; ib < 8; ++ib) { + const int ls = ((blk.scales_l[ib / 2] >> (4 * (ib & 1))) & 0x0F) | + (((blk.scales_h >> (2 * ib)) & 3) << 4); + const float dl = d_f32 * static_cast(ls - 32); + d_eff_km[static_cast(ib * N + n)] = dl; + for (int64_t j = 0; j < 16; ++j) { + const uint8_t byte = blk.qs[ib * 16 + j]; + const uint8_t lo = byte & 0x0Fu; + const uint8_t hi = byte >> 4; + qs_u4[static_cast((ib * 32 + j) * N + n)] = lo; + qs_u4[static_cast((ib * 32 + (j + 16)) * N + n)] = hi; + w_ref[static_cast(n * K + ib * 32 + j)] = dl * iq4[lo]; + w_ref[static_cast(n * K + ib * 32 + j + 16)] = dl * iq4[hi]; + } + } + } + for (int64_t ib = 0; ib < NB32; ++ib) { + for (int64_t j = 0; j < 32; ++j) { + for (int64_t nh = 0; nh < N / 2; ++nh) { + const uint8_t u0 = qs_u4[static_cast((ib * 32 + j) * N + (2 * nh + 0))]; + const uint8_t u1 = qs_u4[static_cast((ib * 32 + j) * N + (2 * nh + 1))]; + qs_bitcast[static_cast((ib * 32 + j) * (N / 2) + nh)] = + static_cast((u0 & 0x0Fu) | ((u1 & 0x0Fu) << 4)); + } + } + } + + std::vector x_host(static_cast(M * K)); + for (size_t i = 0; i < x_host.size(); ++i) { + // Exact dyadic floats to verify 0.0 bit-exact IEEE equality in F32 mode. + x_host[i] = static_cast((static_cast(i % 15) - 7)) * 0.125f; + } + std::vector c_ref(static_cast(M * N), 0.0f); + for (int64_t m = 0; m < M; ++m) { + for (int64_t n = 0; n < N; ++n) { + float acc = 0.0f; + for (int64_t k = 0; k < K; ++k) { + acc += x_host[static_cast(m * K + k)] * w_ref[static_cast(n * K + k)]; + } + c_ref[static_cast(m * N + n)] = acc; + } + } + + auto run_iq4xs_mm = [&](bool bitcast_u8, bool bf16_mxu, int64_t m_run, + const std::vector& x_in, std::vector* out) { + cloudtpu::GraphProgramSpec spec; + spec.bf16_matmul = bf16_mxu; + spec.mm_pad_m = 8; + cloudtpu::TensorSpec w{1, bitcast_u8 ? cloudtpu::PjrtDType::U8 : cloudtpu::PjrtDType::U4, + cloudtpu::TensorStorageKind::IQ4_XS_LUT, {1, 1, N, K}}; + w.scale_dtype = cloudtpu::PjrtDType::F32; + w.bitcast_target = cloudtpu::PjrtDType::U4; + cloudtpu::TensorSpec x{2, cloudtpu::PjrtDType::F32, cloudtpu::TensorStorageKind::DENSE, {1, 1, m_run, K}}; + spec.inputs = {w, x}; + cloudtpu::OpNodeSpec op; + op.kind = cloudtpu::CloudOpKind::MUL_MAT; + op.src_ids = {1, 2}; + op.dst = {3, cloudtpu::PjrtDType::F32, cloudtpu::TensorStorageKind::DENSE, {1, 1, m_run, N}}; + spec.ops = {op}; + spec.output_ids = {3}; + const auto prog = cloudtpu::emit_stablehlo_program(spec); + CHECK_TRUE(count(prog.mlir_text, "\"stablehlo.select\"") == 15, "IQ4_XS_LUT runtime emits 15 selects"); + CHECK_TRUE(count(prog.mlir_text, "stablehlo.gather") == 0, "IQ4_XS_LUT runtime emits 0 gather"); + if (!bf16_mxu) { + CHECK_TRUE(prog.mlir_text.find("HIGHEST") != std::string::npos, + "IQ4_XS_LUT F32 MUL_MAT requests HIGHEST dot precision"); + } + if (bf16_mxu && m_run < 8) { + CHECK_TRUE(prog.mlir_text.find("stablehlo.slice") != std::string::npos, + "IQ4_XS_LUT BF16 pad8 emits slice"); + } + auto b_qs = bitcast_u8 + ? rt.buffer_from_host(0, qs_bitcast.data(), cloudtpu::PjrtDType::U8, {1, 1, NB32, 32, N / 2}) + : rt.buffer_from_host(0, qs_u4.data(), cloudtpu::PjrtDType::U4, {1, 1, NB32, 32, N}); + auto b_d = rt.buffer_from_host(0, d_eff_km.data(), cloudtpu::PjrtDType::F32, {1, 1, NB32, N}); + auto b_x = rt.buffer_from_host(0, x_in.data(), cloudtpu::PjrtDType::F32, {1, 1, m_run, K}); + *out = run_emitted(rt, prog, {b_qs, b_d, b_x}); + }; + + auto bits_equal = [](float a, float b) { + uint32_t ba = 0, bb = 0; + std::memcpy(&ba, &a, sizeof(ba)); + std::memcpy(&bb, &b, sizeof(bb)); + return ba == bb; + }; + + // Exact F32 parity: native U4 and packed U8 bitcast both match canonical reference bit-exactly (0.0 diff). + std::vector got_u4, got_bc; + run_iq4xs_mm(false, false, M, x_host, &got_u4); + run_iq4xs_mm(true, false, M, x_host, &got_bc); + CHECK_TRUE(got_u4.size() == c_ref.size() && got_bc.size() == c_ref.size(), "IQ4_XS_LUT output size"); + for (size_t i = 0; i < c_ref.size(); ++i) { + CHECK_TRUE(bits_equal(got_u4[i], c_ref[i]), "IQ4_XS_LUT U4 F32 MUL_MAT IEEE bit-exact"); + CHECK_TRUE(bits_equal(got_bc[i], c_ref[i]), "IQ4_XS_LUT U8-bitcast F32 MUL_MAT IEEE bit-exact"); + } + + // BF16 MXU parity with M=1 pad8 decode. + std::vector x_m1(x_host.begin(), x_host.begin() + K); + std::vector ref_m1(c_ref.begin(), c_ref.begin() + N); + std::vector got_bf16; + run_iq4xs_mm(false, true, 1, x_m1, &got_bf16); + CHECK_TRUE(got_bf16.size() == ref_m1.size(), "IQ4_XS_LUT BF16 pad8 output size"); + double num = 0.0, den = 0.0; + for (size_t i = 0; i < ref_m1.size(); ++i) { + const double diff = static_cast(got_bf16[i]) - static_cast(ref_m1[i]); + num += diff * diff; + den += static_cast(ref_m1[i]) * static_cast(ref_m1[i]); + } + CHECK_TRUE((num / std::max(den, 1e-30)) < 5e-4, "IQ4_XS_LUT BF16 pad8 M=1 NMSE < 5e-4"); + + // 3) IQ4_XS_LUT GET_ROWS (both native U4 and U8 bitcast): bit-exact 0.0 diff vs w_ref. + const std::vector row_ids = {0, 3, 15, 7}; + for (bool bitcast_u8 : {false, true}) { + cloudtpu::GraphProgramSpec gspec; + cloudtpu::TensorSpec tbl{1, bitcast_u8 ? cloudtpu::PjrtDType::U8 : cloudtpu::PjrtDType::U4, + cloudtpu::TensorStorageKind::IQ4_XS_LUT, {1, 1, N, K}}; + tbl.scale_dtype = cloudtpu::PjrtDType::F32; + tbl.bitcast_target = cloudtpu::PjrtDType::U4; + cloudtpu::TensorSpec idx{2, cloudtpu::PjrtDType::S32, cloudtpu::TensorStorageKind::DENSE, + {1, 1, 1, static_cast(row_ids.size())}}; + gspec.inputs = {tbl, idx}; + cloudtpu::OpNodeSpec gop; + gop.kind = cloudtpu::CloudOpKind::GET_ROWS; + gop.src_ids = {1, 2}; + gop.dst = {3, cloudtpu::PjrtDType::F32, cloudtpu::TensorStorageKind::DENSE, + {1, 1, static_cast(row_ids.size()), K}}; + gspec.ops = {gop}; + gspec.output_ids = {3}; + const auto gprog = cloudtpu::emit_stablehlo_program(gspec); + CHECK_TRUE(count(gprog.mlir_text, "\"stablehlo.select\"") == 15, "IQ4_XS_LUT GET_ROWS emits 15 selects"); + auto b_qs = bitcast_u8 + ? rt.buffer_from_host(0, qs_bitcast.data(), cloudtpu::PjrtDType::U8, {1, 1, NB32, 32, N / 2}) + : rt.buffer_from_host(0, qs_u4.data(), cloudtpu::PjrtDType::U4, {1, 1, NB32, 32, N}); + auto b_d = rt.buffer_from_host(0, d_eff_km.data(), cloudtpu::PjrtDType::F32, {1, 1, NB32, N}); + auto b_i = rt.buffer_from_host(0, row_ids.data(), cloudtpu::PjrtDType::S32, + {1, 1, 1, static_cast(row_ids.size())}); + const std::vector got_rows = run_emitted(rt, gprog, {b_qs, b_d, b_i}); + for (size_t ri = 0; ri < row_ids.size(); ++ri) { + const int64_t r = row_ids[ri]; + for (int64_t k = 0; k < K; ++k) { + const float got_v = got_rows[ri * static_cast(K) + static_cast(k)]; + const float exp_v = w_ref[static_cast(r * K + k)]; + CHECK_TRUE(bits_equal(got_v, exp_v), "IQ4_XS_LUT GET_ROWS IEEE bit-exact"); + } + } + } + + // 4) IQ4_NL_LUT (F16 scales) MUL_MAT + GET_ROWS exact parity. + { + std::vector d_nl_f16(static_cast(NB32 * N), d_f16); + std::vector w_nl_ref(static_cast(N * K)); + std::vector c_nl_ref(static_cast(M * N), 0.0f); + const float d_val = cloudtpu::f16_to_f32(d_f16); + for (int64_t n = 0; n < N; ++n) { + for (int64_t ib = 0; ib < NB32; ++ib) { + for (int64_t j = 0; j < 32; ++j) { + const uint8_t q = qs_u4[static_cast((ib * 32 + j) * N + n)]; + w_nl_ref[static_cast(n * K + ib * 32 + j)] = d_val * iq4[q]; + } + } + } + for (int64_t m = 0; m < M; ++m) { + for (int64_t n = 0; n < N; ++n) { + float acc = 0.0f; + for (int64_t k = 0; k < K; ++k) { + acc += x_host[static_cast(m * K + k)] * w_nl_ref[static_cast(n * K + k)]; + } + c_nl_ref[static_cast(m * N + n)] = acc; + } + } + cloudtpu::GraphProgramSpec nlspec; + nlspec.bf16_matmul = false; + cloudtpu::TensorSpec w{1, cloudtpu::PjrtDType::U4, cloudtpu::TensorStorageKind::IQ4_NL_LUT, {1, 1, N, K}}; + cloudtpu::TensorSpec x{2, cloudtpu::PjrtDType::F32, cloudtpu::TensorStorageKind::DENSE, {1, 1, M, K}}; + nlspec.inputs = {w, x}; + cloudtpu::OpNodeSpec op; + op.kind = cloudtpu::CloudOpKind::MUL_MAT; + op.src_ids = {1, 2}; + op.dst = {3, cloudtpu::PjrtDType::F32, cloudtpu::TensorStorageKind::DENSE, {1, 1, M, N}}; + nlspec.ops = {op}; + nlspec.output_ids = {3}; + const auto nlprog = cloudtpu::emit_stablehlo_program(nlspec); + CHECK_TRUE(count(nlprog.mlir_text, "\"stablehlo.select\"") == 15, "IQ4_NL_LUT MUL_MAT emits 15 selects"); + CHECK_TRUE(count(nlprog.mlir_text, "stablehlo.gather") == 0, "IQ4_NL_LUT MUL_MAT emits 0 gather"); + CHECK_TRUE(nlprog.mlir_text.find("HIGHEST") != std::string::npos, + "IQ4_NL_LUT F32 MUL_MAT requests HIGHEST dot precision"); + auto b_qs = rt.buffer_from_host(0, qs_u4.data(), cloudtpu::PjrtDType::U4, {1, 1, NB32, 32, N}); + auto b_d = rt.buffer_from_host(0, d_nl_f16.data(), cloudtpu::PjrtDType::F16, {1, 1, NB32, N}); + auto b_x = rt.buffer_from_host(0, x_host.data(), cloudtpu::PjrtDType::F32, {1, 1, M, K}); + const std::vector got_nl = run_emitted(rt, nlprog, {b_qs, b_d, b_x}); + for (size_t i = 0; i < c_nl_ref.size(); ++i) { + CHECK_TRUE(bits_equal(got_nl[i], c_nl_ref[i]), "IQ4_NL_LUT U4 F32 MUL_MAT IEEE bit-exact"); + } + + cloudtpu::GraphProgramSpec nl_gspec; + cloudtpu::TensorSpec nl_tbl{1, cloudtpu::PjrtDType::U4, cloudtpu::TensorStorageKind::IQ4_NL_LUT, {1, 1, N, K}}; + cloudtpu::TensorSpec nl_idx{2, cloudtpu::PjrtDType::S32, cloudtpu::TensorStorageKind::DENSE, + {1, 1, 1, static_cast(row_ids.size())}}; + nl_gspec.inputs = {nl_tbl, nl_idx}; + cloudtpu::OpNodeSpec nl_gop; + nl_gop.kind = cloudtpu::CloudOpKind::GET_ROWS; + nl_gop.src_ids = {1, 2}; + nl_gop.dst = {3, cloudtpu::PjrtDType::F32, cloudtpu::TensorStorageKind::DENSE, + {1, 1, static_cast(row_ids.size()), K}}; + nl_gspec.ops = {nl_gop}; + nl_gspec.output_ids = {3}; + const auto nl_gprog = cloudtpu::emit_stablehlo_program(nl_gspec); + CHECK_TRUE(count(nl_gprog.mlir_text, "\"stablehlo.select\"") == 15, "IQ4_NL_LUT GET_ROWS emits 15 selects"); + auto b_i = rt.buffer_from_host(0, row_ids.data(), cloudtpu::PjrtDType::S32, + {1, 1, 1, static_cast(row_ids.size())}); + const std::vector got_nl_rows = run_emitted(rt, nl_gprog, {b_qs, b_d, b_i}); + for (size_t ri = 0; ri < row_ids.size(); ++ri) { + const int64_t r = row_ids[ri]; + for (int64_t k = 0; k < K; ++k) { + const float got_v = got_nl_rows[ri * static_cast(K) + static_cast(k)]; + const float exp_v = w_nl_ref[static_cast(r * K + k)]; + CHECK_TRUE(bits_equal(got_v, exp_v), "IQ4_NL_LUT GET_ROWS IEEE bit-exact"); + } + } + } + + if (g_failures == fail_before) { + std::printf(" [PASS] IQ4_XS_LUT & IQ4_NL_LUT StableHLO MUL_MAT + GET_ROWS (IEEE bit-exact, HIGHEST F32, 15 selects, 0 gather, 2304..6144)\n"); + } +} + void test_mul_mat_dense_and_quant(cloudtpu::PjrtRuntime& rt) { // 1) F32 x F32 with GQA batch ratio (src0 B2=1, src1 B2=2) constexpr int64_t M = 2, K = 32, N = 4; @@ -7589,6 +7883,7 @@ int main(int argc, char** argv) { test_half_bf16_conversions(); test_select_tree_lut4_program(rt); + test_iq4xs_select_tree_matmul_and_get_rows(rt); test_lru_cache_and_hbm_roundtrip(rt); test_multichip_device_assignment_and_eviction_lifetime(); test_mul_mat_dense_and_quant(rt); diff --git a/proof/cloud-tpu-iq4xs-select-tree/PROOF.md b/proof/cloud-tpu-iq4xs-select-tree/PROOF.md index 00cdaa6..7f5ee53 100644 --- a/proof/cloud-tpu-iq4xs-select-tree/PROOF.md +++ b/proof/cloud-tpu-iq4xs-select-tree/PROOF.md @@ -1,101 +1,68 @@ -# Proof: Phase-1 Branchless VREG IQ4_XS Select-Tree LUT (Refs #43) +# Proof: Phase-2 Branchless VREG IQ4_XS Select-Tree Kernel & Runtime Wiring (Refs #43) ## Scope & Issue Context -This PR delivers **Phase 1** for [freesilicon/freetpu#43](https://github.com/freesilicon/freetpu/issues/43) -(`Refs #43` — does **not** close `#43`): the host select-tree math, -GGUF `IQ4_XS`/`IQ4_NL` + sequential `NF4`/`FP4` decoders, standalone -StableHLO select-tree LUT emitters, TileIR codebook planning/Mosaic -refusal guard, and parity/sanitizer tests. Full `ggml-cloudtpu.cpp` runtime -GGUF ingestion/wiring, dispatch-amortized BF16 parity, bare-metal VFIO -`codebook_dequant`, and live Cloud TPU `v5e`/`v6e` silicon timing remain -open on `#43`. +This PR delivers **Phase 2** for [freesilicon/freetpu#43](https://github.com/freesilicon/freetpu/issues/43) +(`Refs #43` — does **not** close `#43`), building on the Phase-1 host math and +standalone select-tree primitives landed in `#46`. -Issue `#43` reports that on Cloud TPU `v5e-1`, XLA `gather`-based -4-bit codebook dequantization hits a compiler cliff tied to tensor size -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** -using a `uint8` + NF4 proxy on live `v5e-1` silicon. -Those timing numbers are the issue's baseline. **This PR makes no new -hardware timing claim**: its proof is host bit-exactness + StableHLO IR -text/Mock-PJRT verification + ready-to-run on-device PJRT correctness -and TPU bench entry commands (below). +What Phase 2 completes on host/Mock-PJRT + GGML runtime: +- **Cloud TPU `IQ4_XS_LUT` & `IQ4_NL_LUT` StableHLO lowering (`llama-cpp-cloudtpu/stablehlo_emitter.{hpp,cpp}`):** wires the 4-level branchless VREG select-tree LUT (`15` `stablehlo.select`, **`0` `stablehlo.gather`**) directly into `emit_stablehlo_program()` for `MUL_MAT` (`F32` exact with `precision = [HIGHEST, HIGHEST]`, `BF16` MXU + `mm_pad_m` small-batch decode padding, `FP8` MXU on `tpu7x`, SPMD `SHARD_N`/`SHARD_K`), `GET_ROWS`, and `CPY`, supporting both native `U4` and packed `U8` bitcast-to-`U4` HBM storage. +- **GGUF `GGML_TYPE_IQ4_XS` & `GGML_TYPE_IQ4_NL` runtime ingestion (`llama-cpp-cloudtpu/ggml-cloudtpu.cpp`):** alignment-safe byte-offset unpacking of canonical 136-byte/256-weight `block_iq4_xs` (split nibbles + 6-bit sub-scales `ls - 32` + `kvalues_iq4nl`) and 18-byte/32-weight `block_iq4_nl` into K-major N-minor HBM buffers, lossless readback via 8-byte header metadata, HBM allocation sizing, partial-upload slot shape/type recording for SPMD consistency, and `MUL_MAT`/`GET_ROWS` dispatch. +- **Portable FreeTile `codebook_dequant` semantic op & codebook extensibility (`freetile/`):** adds `CodebookDequantOp` / `plan_codebook_dequant_op()` across all 4 scalar 4-bit codebook formats (`IQ4_XS`, `IQ4_NL`, `NF4`, `FP4`) targeting Cloud TPU (`stablehlo.select_tree` with `v5e` 16 MiB VMEM gather-cliff characterization `<= 5.31M` vs `>= 9.44M` elements), ARM SME2 (`sme2.luti4`), Qualcomm HVX (`hvx.vlut`), and PowerVR Volcanic (`volcanic.select_tree`); adds generic 1..4-bit `emit_stablehlo_select_tree_lut()` (`3` / `7` / `15` selects, `0` gather — composable scalar sub-lookup primitive for future grid-codebook decoders such as `IQ2_XXS`/`IQ3_XXS`) and packed 18-byte/32-weight `BlockCodebook4` (`NF4`, `FP4_E2M1`, `IQ4_NL`) dequantization. +- **Gates 1–4 Reproducible Cloud TPU Benchmark Script (`tools/select_tree_lut.py --emit-jax-bench`):** clean-room script feeding canonical 136-byte `IQ4_XS` superblocks, asserting `0.0` parity (including an independent scalar row-0 decoder) before timing, sweeping `512^2..6144^2`, testing XLA gather footguns (`mode="promise_in_bounds"`, `int32`, flat 1D indices), and running dispatch-amortized `lax.fori_loop` `BF16` parity with `jax.lax.optimization_barrier` + lowered/compiled IR checks. -## What shipped +**This PR makes no new live-silicon timing claim.** Live Cloud TPU `v5e`/`v6e` +timing runs and bare-metal `/dev/vfio/0` (`MAPS_LIBTPU=0`) proof remain +human-gated follow-ups on `#43`. Scope boundaries, stated plainly: +- Standalone `test_cloudtpu_host` verifies `stablehlo_emitter` + Host Mock PJRT + directly (passing unpacked `U4`/`U8` indices and scales): the `2304 / 3072 / 4096 / 6144` + x `M=1,64,128` MLIR sweep verifies `IQ4_XS_LUT`, while executable IEEE bit-exact + `MUL_MAT` and `GET_ROWS` parity runs on `M=4, K=256, N=16` for both `IQ4_XS_LUT` + and `IQ4_NL_LUT`. +- GitHub CI's `llama.cpp b12608` overlay job compiles `ggml-cloudtpu.cpp` against + pinned `b12608` headers and runs `test-backend-ops` (`ADD`, `RMS_NORM`, `SCALE`); + end-to-end GGML `IQ4_XS`/`IQ4_NL` `test-backend-ops -o MUL_MAT` execution on + live Cloud TPU remains part of the human-gated silicon verification below. -| Piece | Location | -|---|---| -| Select-tree core (15 selects, 0 gather), IQ4_XS/IQ4_NL/NF4/FP4 tables, GGUF IQ4_XS/IQ4_NL + sequential NF4/FP4 decoders + 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()`, `LoweringTarget::STABLEHLO_SELECT_TREE`, U4 planner/validator path | `freetile/include/freetile/tile_ir.hpp`, `freetile/src/tile_ir.cpp` | -| Mosaic guard: codebook formats throw to refuse numeric `uitofp` dequant (requiring the StableHLO select-tree lowering instead) | `freetile/src/mosaic_emitter.cpp` | -| Cloud TPU StableHLO lowering: `emit_select_tree_lut4_program()` (complete module, builder-native `stablehlo.select`, `U32`/`U8`/`U4`) | `llama-cpp-cloudtpu/stablehlo_emitter.hpp`, `llama-cpp-cloudtpu/stablehlo_emitter.cpp` | -| Python/NumPy reference mirror + tests (produces no MLIR IR) | `tools/select_tree_lut.py`, `tools/test_select_tree_lut.py` | -| C++ bit-exact & PJRT execution 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 constant splat, -zero `stablehlo.gather` ops (VREG residency on TPU silicon remains to be -verified on `v5e`/`v6e` XLA compilation). 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 compare `use_select_tree=true` vs `false` with identical scale -arithmetic and float accumulation order, so bit-exact (`0.0` diff, matching -IEEE float bit patterns) holds by construction; the IQ4_XS decoder is -additionally verified in `test_select_tree_lut` against an independent inline -scalar decoder (`scalar_iq4_xs_ref`) on 14 sampled tail widths (`k=0..300`). +## Host-Verified Proof (Observed) | Check | Result | |---|---| -| Exhaustive 16-index tree vs table (IQ4_NL, IQ4_XS, NF4, FP4; f32 + i32 mask-blend) | bit-exact (incl. `-0.0f` sign bit) | -| IQ4_XS dequant, full weight matrices `2304², 3072², 4096², 6144²` (select-tree vs direct, every row) + 14 sampled tails `k=0..300` (vs direct & scalar ref) | `max_abs_diff = 0.0` (bit-exact) | -| IQ4_XS dequant+matmul `1x2304x2304` full; `64/128x2304x2304`, `128x3072x3072`, `128x4096x4096`, `64x6144x6144` at full K,N with M-tile 8 (CI speed) + tail matmul `k=0,1,31,257` | `max_abs_diff = 0.0` (bit-exact) | -| IQ4_NL (incl. 14 sampled tails `k=0..300`); NF4 & FP4 caller-supplied `scales32` + sequential nibbles (`dequant_codebook4_row`) | `max_abs_diff = 0.0` (bit-exact) | -| Emitted StableHLO (`emit_stablehlo_select_tree_lut4` snippet text check at `2304²` + SSA chaining; `emit_select_tree_lut4_program` text checks at `2304/3072/4096/6144` + Mock PJRT exec at `4x8`) | 15 `stablehlo.select`, **0 `stablehlo.gather`**; Mock PJRT exec bit-exact over `0..31` (`U32`/`U8`) and `0..15` repeated (`U4`) | -| FreeTile planning (`IQ4_XS` on `v5e`+`v6e` across `2304/3072/4096/6144`, `M=64`; `IQ4_NL`/`NF4`/`FP4` on `v6e`, `2304²`) | plans `STABLEHLO_SELECT_TREE` + U4 weights; Mosaic throws with select-tree diagnostic | -| ASan+UBSan (`-fno-sanitize-recover=all`) on the new C++ suite | clean | -| Repo suites: `cmake`/`make` `freetile` + `libopenbuenos` + `libopentpu` + `llama-cpp-cloudtpu` (mock) + Python tests | all pass | +| `freetile` C++17 suite (`test_select_tree_lut`, `test_freetile`, `test_splines_and_flash_attn`, `test_buenos_parity`, `test_freetile_twin`) | PASS (`0.0` bit-exact diff on `2304^2 / 3072^2 / 4096^2 / 6144^2`, packed `NF4`/`FP4`/`IQ4_NL`, 2/3-bit 3/7-select MLIR, 4 portable `codebook_dequant` backends, Mosaic refusal guard) | +| `freetile` ASan + UBSan (`-fsanitize=address,undefined -fno-sanitize-recover=all -Wall -Wextra -Wpedantic -Werror`) | PASS (`0` errors/warnings) | +| `llama-cpp-cloudtpu` Host + Mock PJRT (`test_cloudtpu_host`, `pjrt_runtime_guards_test`) | PASS (`IQ4_XS_LUT` MLIR `15` selects / `0` gather across `2304 / 3072 / 4096 / 6144` x `M=1,64,128`; `HIGHEST` F32 dot precision + IEEE bit-exact `MUL_MAT` & `GET_ROWS` parity on `M=4, K=256, N=16` for `IQ4_XS_LUT` `U4`/`U8`-bitcast and `IQ4_NL_LUT` `U4`; `BF16` `M=1` `pad8` `NMSE < 5e-4`) | +| `llama-cpp-cloudtpu` ASan + UBSan on `test_cloudtpu_host` | PASS (`0` errors) | +| Python syntax / CI suite (`tools/select_tree_lut.py`, `tools/test_select_tree_lut.py`) | `py_compile` + bench script `compile()` PASS locally; full NumPy suite runs in PR CI | +| GitHub CI (`llama.cpp b12608` overlay compile + `ADD`/`RMS_NORM`/`SCALE` + clean-room audit) | Runs on PR push in GitHub Actions | Reproduce (host, no TPU required): ```bash -cmake -S freetile -B build-freetile -DCMAKE_BUILD_TYPE=Release -cmake --build build-freetile && ctest --test-dir build-freetile --output-on-failure -clang++ -std=c++17 -O1 -g -fsanitize=address,undefined -fno-sanitize-recover=all -Wall -Wextra -Wpedantic -Werror -Ifreetile/include freetile/src/select_tree_lut.cpp freetile/src/tile_ir.cpp freetile/src/mosaic_emitter.cpp freetile/tests/test_select_tree_lut.cpp -o /tmp/test_select_tree_san && /tmp/test_select_tree_san -make -C libopenbuenos verify-header-host host test -python3 tools/select_tree_lut.py --self-test -python3 tools/test_select_tree_lut.py -v -# llama-cpp-cloudtpu host suite (CMake hosts): +make -C freetile test +clang++ -std=c++17 -O1 -g -fsanitize=address,undefined -fno-sanitize-recover=all \ + -Wall -Wextra -Wpedantic -Werror -Ifreetile/include \ + freetile/src/select_tree_lut.cpp freetile/src/tile_ir.cpp freetile/src/mosaic_emitter.cpp \ + freetile/tests/test_select_tree_lut.cpp -o /tmp/test_select_tree_san && /tmp/test_select_tree_san cmake -S llama-cpp-cloudtpu -B build-cloudtpu -DCMAKE_BUILD_TYPE=Release cmake --build build-cloudtpu && ctest --test-dir build-cloudtpu --output-on-failure +python3 tools/select_tree_lut.py --self-test +python3 tools/test_select_tree_lut.py -v ``` -Known scope limits, stated plainly: this PR delivers Phase 1 only (`Refs #43`); -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). Standalone StableHLO emitters (`emit_select_tree_lut4_program` -and snippet emitter) are verified via text assertions + Mock PJRT (`4x8` `U32`/`U8`/`U4`), -while `NF4`/`FP4` use sequential nibbles + caller-supplied `scales32` rather than -GGUF packed superblocks. Real XLA/StableHLO verifier (`stablehlo-opt`), GGUF `IQ4_XS` -tensor ingestion/wiring in `ggml-cloudtpu.cpp`, dispatch-amortized BF16 parity, -bare-metal VFIO `codebook_dequant`, and live Cloud TPU `v5e`/`v6e` silicon proof -remain open on `#43`. - -## Live Cloud TPU verification & bench entry points (not run by this PR) +## Remaining Human-Gated Silicon Proof (Open on #43) -On a Cloud TPU `v5e`/`v6e` VM with `libtpu.so`: +On an approved Cloud TPU `v5e` / `v6e` VM with `libtpu.so` (not run by this PR): ```bash -# 1. Correctness on silicon (runs test_select_tree_lut4_program on live PJRT): +# 1. Live PJRT correctness (runs test_select_tree_lut4_program + test_iq4xs_select_tree_matmul_and_get_rows): CLOUDTPU_MOCK=0 ./build-cloudtpu/test_cloudtpu_host -# 2. Existing repo TPU bench CLI / command printer (performs no timing itself): -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; report observed -# numbers with the exact libtpu/TPU build (do not reuse #43's v5e-1 211x -# baseline as this PR's result). + +# 2. 5-gate timing sweep (canonical 136 B IQ4_XS parity, VMEM cliff 512^2..6144^2, +# gather promise_in_bounds/int32/1D check, loop-carried lax.fori_loop BF16 parity): +python3 tools/select_tree_lut.py --emit-jax-bench > /tmp/tpu_iq4xs_bench.py +python3 /tmp/tpu_iq4xs_bench.py + +# 3. GGML backend-ops verification on live Cloud TPU: +CLOUDTPU_MOCK=0 ./build-cloudtpu-b12608/bin/test-backend-ops test -b CLOUDTPU -o MUL_MAT ``` diff --git a/tools/select_tree_lut.py b/tools/select_tree_lut.py index 488cf03..a857371 100644 --- a/tools/select_tree_lut.py +++ b/tools/select_tree_lut.py @@ -124,6 +124,194 @@ def iq4xs_dequant_matmul(a_mk, w_bytes, m, k, n, tree=True): return acc +V5E_GATHER_CLIFF_MAX_ELEMS = 5_310_000 # <= 5.31M elems hits v5e 16 MiB VMEM gather cliff + + +def dequant_packed_codebook4_row(name, block_bytes, k, tree=True): + """Dequantize packed 18-byte / 32-weight codebook blocks (IQ4_NL / NF4 / FP4_E2M1).""" + if name not in CODEBOOKS: + raise ValueError(f"unknown codebook {name!r}") + table = CODEBOOKS[name] + k = operator.index(k) + if k < 0: + raise ValueError("k must be non-negative") + out = np.zeros(k, dtype=np.float32) + if k == 0: + return out + nb = (k + 31) // 32 + need_bytes = nb * 18 + if len(block_bytes) < need_bytes: + raise ValueError(f"block_bytes too short: got {len(block_bytes)}, need {need_bytes}") + for b in range(nb): + blk = bytes(block_bytes[b * 18:(b + 1) * 18]) + d = np.float32(np.frombuffer(blk[0:2], dtype=" 16: + out[base + 16:base + want] = d * _lut(qs[:want - 16] >> 4, table, tree) + return out + + +def classify_v5e_cliff(k, n): + """Characterize whether weight matrix (N x K) falls inside v5e's 16 MiB VMEM gather-cliff band.""" + k, n = operator.index(k), operator.index(n) + if k <= 0 or n <= 0: + raise ValueError("k and n must be positive") + elems = k * n + return { + "k": k, + "n": n, + "elements": elems, + "f32_mib": round((elems * 4) / (1024 * 1024), 2), + "iq4_xs_mib": round((((k + 255) // 256) * 136 * n) / (1024 * 1024), 2), + "v5e_gather_cliff_zone": elems <= V5E_GATHER_CLIFF_MAX_ELEMS, + } + + +def format_jax_tpu_bench_script(): + """Return a clean-room Cloud TPU v5e/v6e JAX benchmark covering #43's Gates 1-4.""" + return '''#!/usr/bin/env python3 +"""Clean-room Cloud TPU v5e/v6e benchmark for freesilicon/freetpu#43 (Gates 1-4). + +Gates covered on live Cloud TPU silicon (do NOT run without approved TPU VM): + 1. VMEM-cliff size sweep: 512^2, 1024^2, 2048^2, 2304^2 (<=5.31M) vs 3072^2, 4096^2, 6144^2. + 2. XLA gather footgun check: default gather vs mode="promise_in_bounds" vs int32 vs flat 1D. + 3. True packed 136-byte/256-weight IQ4_XS (split nibbles + 6-bit sub-scales) bit-exact 0.0 parity. + 4. Dispatch-amortized BF16 parity inside lax.fori_loop with optimization_barrier + IR checks. +(Gate 5 bare-metal /dev/vfio/0 proof is run separately.) +""" +import time +import numpy as np +import jax +import jax.numpy as jnp + +KVALUES_IQ4NL = jnp.array( + [-127, -104, -83, -65, -49, -35, -22, -10, 1, 13, 25, 38, 53, 69, 89, 113], + dtype=jnp.float32, +) + +def make_canonical_iq4xs_blocks(n, k, seed=43): + """Synthesize canonical 136-byte/256-weight IQ4_XS blocks: shape [N, K/256, 136] uint8.""" + rng = np.random.default_rng(seed) + nsb = k // 256 + raw = rng.integers(0, 256, size=(n, nsb, 136), dtype=np.uint8) + d_f16 = np.frombuffer(np.float16(0.015625).tobytes(), dtype=np.uint8) + raw[:, :, 0:2] = d_f16 + return raw + +def unpack_iq4xs_blocks_jnp(raw_u8, lut_fn): + """Unpack canonical [N, K/256, 136] uint8 IQ4_XS blocks into [K, N] F32 via `lut_fn`.""" + n, nsb, _ = raw_u8.shape + d_u16 = raw_u8[:, :, 0].astype(jnp.uint16) | (raw_u8[:, :, 1].astype(jnp.uint16) << 8) + d_f32 = jax.lax.bitcast_convert_type(d_u16, jnp.float16).astype(jnp.float32) # [N, nsb] + sh = raw_u8[:, :, 2].astype(jnp.uint32) | (raw_u8[:, :, 3].astype(jnp.uint32) << 8) + sl = raw_u8[:, :, 4:8].astype(jnp.uint32) # [N, nsb, 4] + ib = jnp.arange(8, dtype=jnp.uint32) + sl_nib = (sl[:, :, ib // 2] >> (4 * (ib & 1))) & 0xF + sh_bits = (sh[:, :, None] >> (2 * ib)) & 3 + ls = (sl_nib | (sh_bits << 4)).astype(jnp.int32) - 32 # [N, nsb, 8] + dl = d_f32[:, :, None] * ls.astype(jnp.float32) # [N, nsb, 8] + + qs = raw_u8[:, :, 8:136].reshape(n, nsb, 8, 16) + lo = qs & 0xF + hi = qs >> 4 + nib = jnp.concatenate([lo, hi], axis=-1) # [N, nsb, 8, 32] + vals = lut_fn(nib) * dl[:, :, :, None] + return jnp.transpose(vals.reshape(n, nsb * 256), (1, 0)) # [K, N] + +def select_tree4_jnp(idx_u4): + u = idx_u4.astype(jnp.uint32) + b0 = (u & 1) != 0 + b1 = ((u >> 1) & 1) != 0 + b2 = ((u >> 2) & 1) != 0 + b3 = ((u >> 3) & 1) != 0 + lvl = [jnp.where(b0, KVALUES_IQ4NL[2 * i + 1], KVALUES_IQ4NL[2 * i]) for i in range(8)] + lvl = [jnp.where(b1, lvl[2 * i + 1], lvl[2 * i]) for i in range(4)] + lvl = [jnp.where(b2, lvl[2 * i + 1], lvl[2 * i]) for i in range(2)] + return jnp.where(b3, lvl[1], lvl[0]) + +def run_gate_sweep(iters=50): + print("Devices:", jax.devices()) + shapes = [ + (1, 2304, 2304), (64, 2304, 2304), (128, 2304, 2304), + (128, 512, 512), (128, 1024, 1024), (128, 2048, 2048), + (128, 3072, 3072), (128, 4096, 4096), (64, 6144, 6144), + ] + for m, k, n in shapes: + raw_np = make_canonical_iq4xs_blocks(n, k, seed=43 + k) + raw_jnp = jnp.asarray(raw_np) + x_bf16 = jnp.asarray(np.random.default_rng(7).standard_normal((m, k)).astype(np.float32) * 0.01, dtype=jnp.bfloat16) + + # Gate 3: verify bit-exact 0.0 diff against BOTH reference gather and an independent + # scalar NumPy 136-byte IQ4_XS decoder before timing. + w_tree_f32 = unpack_iq4xs_blocks_jnp(raw_jnp, select_tree4_jnp) + w_ref_f32 = unpack_iq4xs_blocks_jnp(raw_jnp, lambda q: KVALUES_IQ4NL[q.astype(jnp.int32)]) + max_diff = float(jnp.max(jnp.abs(w_tree_f32 - w_ref_f32))) + assert max_diff == 0.0, f"IQ4_XS LUT parity mismatch at {m}x{k}x{n}: {max_diff}" + # Independent scalar check on row 0 (catches nibble-order or subscale decode bugs). + row0 = np.asarray(raw_np[0]) + ref_row0 = np.empty(k, dtype=np.float32) + kvals_np = np.asarray(KVALUES_IQ4NL, dtype=np.float32) + for sb in range(k // 256): + blk = row0[sb] + d = float(np.frombuffer(blk[0:2].tobytes(), dtype="> (4 * (ib & 1))) & 0xF) | (((sh >> (2 * ib)) & 3) << 4) + dl = np.float32(d) * np.float32(ls - 32) + for j in range(16): + byte = int(qs[ib * 16 + j]) + ref_row0[sb * 256 + ib * 32 + j] = dl * kvals_np[byte & 0xF] + ref_row0[sb * 256 + ib * 32 + j + 16] = dl * kvals_np[byte >> 4] + assert np.array_equal(np.asarray(w_tree_f32[:, 0]), ref_row0), "scalar IQ4_XS row0 mismatch!" + w_bf16 = w_tree_f32.astype(jnp.bfloat16) + + def bench(fn, payload, expect_decode_in_loop=True): + # Thread loop-carried activation + optimization_barrier(w_in) so XLA cannot + # hoist either the packed weight LUT decode or the dot out of lax.fori_loop. + @jax.jit + def looped(x0, w_in): + def body(i, carry): + acc, x_cur, w_cur = carry + w_bar = jax.lax.optimization_barrier(w_cur) + y = fn(x_cur, w_bar) + x_next = x_cur + (y[:, :1] * jnp.bfloat16(1e-6)).astype(jnp.bfloat16) + return acc + y, x_next, w_bar + acc0 = jnp.zeros((m, n), jnp.float32) + acc_out, _, _ = jax.lax.fori_loop(0, iters, body, (acc0, x0, w_in)) + return acc_out + + lowered = looped.lower(x_bf16, payload) + lowered_txt = lowered.as_text() + assert "optimization_barrier" in lowered_txt, "Lowered IR missing optimization_barrier!" + compiled = lowered.compile() + hlo_txt = compiled.as_text() + assert "while" in hlo_txt, "XLA dropped timed while loop!" + if expect_decode_in_loop: + assert ("select" in hlo_txt or "gather" in hlo_txt or "fusion" in hlo_txt), "XLA dropped LUT decode!" + out = compiled(x_bf16, payload) + jax.block_until_ready(out) + t0 = time.perf_counter() + out = compiled(x_bf16, payload) + jax.block_until_ready(out) + return ((time.perf_counter() - t0) * 1e6) / iters + + t_tree = bench(lambda x, r: jnp.matmul(x, unpack_iq4xs_blocks_jnp(r, select_tree4_jnp).astype(jnp.bfloat16), preferred_element_type=jnp.float32), raw_jnp, True) + t_gather_def = bench(lambda x, r: jnp.matmul(x, unpack_iq4xs_blocks_jnp(r, lambda q: KVALUES_IQ4NL[q]).astype(jnp.bfloat16), preferred_element_type=jnp.float32), raw_jnp, True) + t_gather_pib = bench(lambda x, r: jnp.matmul(x, unpack_iq4xs_blocks_jnp(r, lambda q: KVALUES_IQ4NL.at[q.astype(jnp.int32).reshape(-1)].get(mode="promise_in_bounds").reshape(q.shape)).astype(jnp.bfloat16), preferred_element_type=jnp.float32), raw_jnp, True) + t_bf16 = bench(lambda x, w: jnp.matmul(x, w, preferred_element_type=jnp.float32), w_bf16, False) + print(f"M={m:3d} K={k:4d} N={n:4d} | max_diff={max_diff:.1f} | tree={t_tree:8.2f}us | gather={t_gather_def:9.2f}us | gather_pib_i32_1d={t_gather_pib:9.2f}us | bf16={t_bf16:8.2f}us") + +if __name__ == "__main__": + run_gate_sweep() +''' + + def count_selects(bits=4): if bits < 0 or bits >= 32: raise ValueError("bits out of range (0..31 for select count)") @@ -162,10 +350,16 @@ def main(argv=None): 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") + p.add_argument("--emit-jax-bench", action="store_true", + help="print the clean-room Cloud TPU Gates 1-4 JAX benchmark script") args = p.parse_args(argv) + if args.emit_jax_bench: + print(format_jax_tpu_bench_script(), end="") + return 0 if args.bench_harness: - print("On a Cloud TPU v5e/v6e VM (commands below run correctness/help; no timing yet):") + print("On a Cloud TPU v5e/v6e VM (human-gated silicon verification; no timing run on host):") print(" CLOUDTPU_MOCK=0 ./build-cloudtpu/test_cloudtpu_host") + print(" python3 tools/select_tree_lut.py --emit-jax-bench > /tmp/tpu_iq4xs_bench.py && python3 /tmp/tpu_iq4xs_bench.py") print(" python3 tools/colab_tpu_bench.py --help # existing TPU bench entry point") return 0 return _self_test() diff --git a/tools/test_select_tree_lut.py b/tools/test_select_tree_lut.py index 5a3f9b5..d4bcf8b 100644 --- a/tools/test_select_tree_lut.py +++ b/tools/test_select_tree_lut.py @@ -87,6 +87,34 @@ def test_tables(self): self.assertEqual(st.FP4_E2M1[7], np.float32(6.0)) self.assertEqual(st.FP4_E2M1[15], np.float32(-6.0)) + def test_packed_codebook4_and_cliff_bench(self): + rng = np.random.default_rng(43) + for name in ("iq4_nl", "nf4", "fp4_e2m1"): + for k in (0, 1, 17, 32, 257): + nb = 1 if k == 0 else (k + 31) // 32 + raw = bytearray(rng.integers(0, 256, size=nb * 18, dtype=np.uint8).tobytes()) + for off in range(0, len(raw), 18): + raw[off:off + 2] = np.float16(0.025).tobytes() + ya = st.dequant_packed_codebook4_row(name, bytes(raw), k, tree=True) + yb = st.dequant_packed_codebook4_row(name, bytes(raw), k, tree=False) + self.assertEqual(ya.shape, (k,)) + self.assertTrue(np.array_equal(ya, yb), (name, k)) + self.assertTrue(st.classify_v5e_cliff(2304, 2304)["v5e_gather_cliff_zone"]) + self.assertTrue(st.classify_v5e_cliff(2048, 2048)["v5e_gather_cliff_zone"]) + self.assertFalse(st.classify_v5e_cliff(3072, 3072)["v5e_gather_cliff_zone"]) + self.assertFalse(st.classify_v5e_cliff(6144, 6144)["v5e_gather_cliff_zone"]) + script = st.format_jax_tpu_bench_script() + compile(script, "", "exec") + self.assertIn("promise_in_bounds", script) + self.assertIn("lax.fori_loop", script) + self.assertIn("make_canonical_iq4xs_blocks", script) + self.assertIn("assert max_diff == 0.0", script) + self.assertIn("optimization_barrier", script) + self.assertIn("scalar IQ4_XS row0 mismatch", script) + self.assertIn("compiled.as_text()", script) + self.assertIn("2304", script) + self.assertIn("6144", script) + if __name__ == "__main__": unittest.main()