A high-performance inference engine for AI models
Support Trellis model (#899)
CCYeh158162140250
diff --git a/crates/uzu-engine/src/backends/common/gpu_types/quantization.rs b/crates/uzu-engine/src/backends/common/gpu_types/quantization.rsindex d51b53b7c..6a4b33d92 100644--- a/crates/uzu-engine/src/backends/common/gpu_types/quantization.rs+++ b/crates/uzu-engine/src/backends/common/gpu_types/quantization.rs@@ -18,6 +18,15 @@ pub enum QuantizationMode {}impl QuantizationMode {+ pub fn from_unsigned_bits(bits: u32) -> Option<Self> {+ match bits {+ 2 => Some(Self::U2),+ 4 => Some(Self::U4),+ 8 => Some(Self::U8),+ _ => None,+ }+ }+pub fn packing_divisor(&self) -> u32 {let bits = DataType::from(*self).size_in_bits() as u32;assert_eq!(8 % bits, 0, "QuantizationMode bit width ({bits}) must divide 8 evenly");diff --git a/crates/uzu-engine/src/backends/common/gpu_types/trellis.rs b/crates/uzu-engine/src/backends/common/gpu_types/trellis.rsindex f2d7282fb..101f710b3 100644--- a/crates/uzu-engine/src/backends/common/gpu_types/trellis.rs+++ b/crates/uzu-engine/src/backends/common/gpu_types/trellis.rs@@ -1 +1,14 @@+use uzu_engine_macros::uzu_config;+pub const COLUMN_GROUP_COUNT: u32 = 4;+pub const MAX_DIMENSION: u32 = 20480;+pub const MIN_HADAMARD_SIZE: u32 = 512;+pub const MAX_HADAMARD_SIZE: u32 = 4096;++#[repr(C)]+#[derive(Copy)]+#[uzu_config]+pub struct TrellisCodebook {+ pub scale: f32,+ pub offsets: [f32; 4],+}diff --git a/crates/uzu-engine/src/backends/common/kernel/matmul/matmul_b.rs b/crates/uzu-engine/src/backends/common/kernel/matmul/matmul_b.rsindex d214d16d6..ff9c6e8db 100644--- a/crates/uzu-engine/src/backends/common/kernel/matmul/matmul_b.rs+++ b/crates/uzu-engine/src/backends/common/kernel/matmul/matmul_b.rs@@ -2,7 +2,7 @@ use super::{QuantParams, QuantParamsLayout, WeightsLayout};use crate::{backends::common::{BufferRef,- gpu_types::{gemm::GemmBPrologueKind, quantization::QuantizationMode},+ gpu_types::{gemm::GemmBPrologueKind, quantization::QuantizationMode, trellis::TrellisCodebook},},data_type::DataType,};@@ -39,7 +39,7 @@ pub enum MatmulB<TB: BufferRef> {Trellis {codes: TB,row_scales: TB,- codebook: TB,+ codebook: TrellisCodebook,format: TrellisFormat,},}diff --git a/crates/uzu-engine/src/backends/common/kernel/matmul/mod.rs b/crates/uzu-engine/src/backends/common/kernel/matmul/mod.rsindex 6bf75391f..1f83364b2 100644--- a/crates/uzu-engine/src/backends/common/kernel/matmul/mod.rs+++ b/crates/uzu-engine/src/backends/common/kernel/matmul/mod.rs@@ -10,9 +10,7 @@ pub use arguments::MatmulArguments;pub use d_ops::MatmulDOps;pub use kernel::MatmulKernel;pub use matmul_a::{Int8CodeLayout, MatmulA, packed_half_bytes};-#[cfg(backend = "metal")]-pub use matmul_b::TrellisFormat;-pub use matmul_b::{MatmulB, QuantizedB, QuantizedCorrection};+pub use matmul_b::{MatmulB, QuantizedB, QuantizedCorrection, TrellisFormat};pub use output::MatmulOutput;#[cfg(any(backend = "cpu", backend = "metal"))] // TODO: webgpupub use output::MatmulOutputError;diff --git a/crates/uzu-engine/src/backends/common/kernel/mod.rs b/crates/uzu-engine/src/backends/common/kernel/mod.rsindex 626d7a35c..2b08a50cd 100644--- a/crates/uzu-engine/src/backends/common/kernel/mod.rs+++ b/crates/uzu-engine/src/backends/common/kernel/mod.rs@@ -11,7 +11,6 @@ pub mod gated_act_mul;pub mod kv_layout;pub mod matmul;pub mod radix_top_k_small;-#[cfg(any(backend = "cpu", test))]mod trellis;pub use activation_transform::{ActivationQuantization, ActivationTransform};@@ -19,7 +18,6 @@ pub use attention::{AttentionArguments, AttentionInput, AttentionKernel, Attentipub use gated_act_mul::{GatedActMul, GatedActMulSettings};pub use matmul::ActivationFormat;-#[cfg(any(backend = "cpu", test))]pub use crate::backends::common::kernel::trellis::mixing_dimension;include!(concat!(env!("OUT_DIR"), "/traits.rs"));diff --git a/crates/uzu-engine/src/backends/cpu/kernel/activation_transform/trellis.rs b/crates/uzu-engine/src/backends/cpu/kernel/activation_transform/trellis.rsindex 3c76110cd..fc239ca12 100644--- a/crates/uzu-engine/src/backends/cpu/kernel/activation_transform/trellis.rs+++ b/crates/uzu-engine/src/backends/cpu/kernel/activation_transform/trellis.rs@@ -6,7 +6,7 @@ use crate::backends::common::{gpu_types::trellis::COLUMN_GROUP_COUNT, kernel::mifn rotate_token(input: &[bf16],- rht_factors: &[f32],+ rht_factors: &[i32],mixing: &[f32],mixing_dimension: usize,) -> Vec<f32> {@@ -18,7 +18,7 @@ fn rotate_token(.map(|hadamard_index| {(0..mixing_dimension).fold(0.0f32, |accumulated, mixing_index| {let column = hadamard_index * mixing_dimension + mixing_index;- (input[column].to_f32() * rht_factors[column])+ (input[column].to_f32() * rht_factors[column] as f32).mul_add(mixing[output_mixing_index * mixing_dimension + mixing_index], accumulated)})})@@ -34,7 +34,7 @@ fn rotate_token(#[kernel(TrellisTransform)]pub fn trellis_transform(input: *const bf16,- rht_factors: *const f32,+ rht_factors: *const i32,mixing: *const f32,activations: *mut i8,column_group_sums: *mut f32,diff --git a/crates/uzu-engine/src/backends/cpu/kernel/matmul/kernel.rs b/crates/uzu-engine/src/backends/cpu/kernel/matmul/kernel.rsindex 1f7bdae3f..31692c6b9 100644--- a/crates/uzu-engine/src/backends/cpu/kernel/matmul/kernel.rs+++ b/crates/uzu-engine/src/backends/cpu/kernel/matmul/kernel.rs@@ -113,7 +113,7 @@ impl MatmulKernel for MatmulCpuKernel {offset,} => {let (values, range) = values.parts();- let byte_offset = range.start + offset * self.input_data_type.size_in_bytes();+ let byte_offset = range.start + offset;AData::FullPrecision(SendPtr(values.cpu_address().as_ptr().cast::<u8>().cast_const().wrapping_byte_add(byte_offset),))diff --git a/crates/uzu-engine/src/backends/metal/kernel/activation_transform/trellis.metal b/crates/uzu-engine/src/backends/metal/kernel/activation_transform/trellis.metalindex 8184fdacf..78bb03e62 100644--- a/crates/uzu-engine/src/backends/metal/kernel/activation_transform/trellis.metal+++ b/crates/uzu-engine/src/backends/metal/kernel/activation_transform/trellis.metal@@ -27,12 +27,11 @@ static METAL_FUNC uint hadamard_index_before_transpose(ushort lane, ushort simdgreturn METAL_SIMD_SIZE * (simdgroup + SIMDGROUPS_PER_THREADGROUP * value_index) + lane;}-// Supported limits; arrays are sized for them.-UZU_CONST uint MAX_DIMENSION = 20480;-UZU_CONST uint MIN_HADAMARD_SIZE = 512;-UZU_CONST uint MAX_HADAMARD_SIZE = 4096;-UZU_CONST uint MAX_COLUMNS_PER_PASS = 4;+using trellis::MAX_DIMENSION;+using trellis::MAX_HADAMARD_SIZE;+using trellis::MIN_HADAMARD_SIZE;+UZU_CONST uint MAX_COLUMNS_PER_PASS = 4;UZU_CONST uint MAX_MIXING_DIMENSION = MAX_DIMENSION / MIN_HADAMARD_SIZE;UZU_CONST uint MAX_VALUES_PER_THREAD = MAX_HADAMARD_SIZE / THREADS_PER_THREADGROUP;UZU_CONST uint MAX_PRIVATE_VALUES = MAX_DIMENSION / THREADS_PER_THREADGROUP;@@ -175,7 +174,7 @@ static METAL_FUNC void rotate_columns(PUBLIC KERNEL(TrellisTransform)(device const bfloat* input,- device const float* rht_factors,+ device const int32_t* rht_factors,device const float* mixing,device int8_t* activations,device float4* column_group_sums,@@ -205,11 +204,11 @@ PUBLIC KERNEL(TrellisTransform)(const uint hadamard_index = hadamard_index_before_transpose(lane, simdgroup, value_index);const uint first_column = hadamard_index * layout.mixing_dimension;const device bfloat* token_input = input + token * dimension + first_column;- const device float* token_factors = rht_factors + first_column;+ const device int32_t* token_factors = rht_factors + first_column;METAL_PRAGMA_UNROLLfor (uint mixing_index = 0; mixing_index < layout.mixing_dimension; ++mixing_index) {sign_flipped_input[value_index * layout.mixing_dimension + mixing_index] =- float(token_input[mixing_index]) * token_factors[mixing_index];+ float(token_input[mixing_index]) * float(token_factors[mixing_index]);}}threadgroup_barrier(mem_flags::mem_threadgroup);diff --git a/crates/uzu-engine/src/backends/metal/kernel/generated/trellis.h b/crates/uzu-engine/src/backends/metal/kernel/generated/trellis.hindex 029ee080e..ff7d3d3a7 100644--- a/crates/uzu-engine/src/backends/metal/kernel/generated/trellis.h+++ b/crates/uzu-engine/src/backends/metal/kernel/generated/trellis.h@@ -6,4 +6,15 @@ using namespace metal;namespace uzu::trellis {static constant constexpr uint32_t COLUMN_GROUP_COUNT = 4;++static constant constexpr uint32_t MAX_DIMENSION = 20480;++static constant constexpr uint32_t MIN_HADAMARD_SIZE = 512;++static constant constexpr uint32_t MAX_HADAMARD_SIZE = 4096;++typedef struct {+ float scale;+ float offsets[4];+} TrellisCodebook;} // namespace uzu::trellisdiff --git a/crates/uzu-engine/src/backends/metal/kernel/matmul/gemm/gemm.metal b/crates/uzu-engine/src/backends/metal/kernel/matmul/gemm/gemm.metalindex d2e7434cd..cd5837965 100644--- a/crates/uzu-engine/src/backends/metal/kernel/matmul/gemm/gemm.metal+++ b/crates/uzu-engine/src/backends/metal/kernel/matmul/gemm/gemm.metal@@ -96,7 +96,9 @@ CONSTRAINT((B_PROLOGUE == GemmBPrologueKind::FullPrecision) == (BITS == 0))CONSTRAINT((BITS == 0) == (BLOCK_K == 0))CONSTRAINT((BITS == 2) == (BLOCK_K == 128))CONSTRAINT(B_PROLOGUE != GemmBPrologueKind::ScaleZeroPointDequant || BITS == 4)-CONSTRAINT(B_PROLOGUE != GemmBPrologueKind::ScaleSymmetricDequant || BITS == 8)+CONSTRAINT(+ B_PROLOGUE != GemmBPrologueKind::ScaleSymmetricDequant || BITS == 8 ||+ (A_PROLOGUE == GemmAPrologueKind::Int8Symmetric && BLOCK_K == 64 && DT == "bfloat"))CONSTRAINT(B_PROLOGUE != GemmBPrologueKind::ScaleBiasDequant || BITS == 2 || BITS == 4)CONSTRAINT((BITS != 2 || A_IS_INT8 ||diff --git a/crates/uzu-engine/src/backends/metal/kernel/matmul/gemm/gemm_trellis.metal b/crates/uzu-engine/src/backends/metal/kernel/matmul/gemm/gemm_trellis.metalindex 2383d9fd6..be356c995 100644--- a/crates/uzu-engine/src/backends/metal/kernel/matmul/gemm/gemm_trellis.metal+++ b/crates/uzu-engine/src/backends/metal/kernel/matmul/gemm/gemm_trellis.metal@@ -1,4 +1,5 @@#include "../../common/dsl.h"+#include "../../generated/trellis.h"#include "../../common/defines.h"#include "../../common/thread_context.h"#include "../generated/gemm.h"@@ -12,6 +13,7 @@using namespace metal;using namespace uzu::gemm;+using uzu::trellis::TrellisCodebook;#define REDUCE_THREADS 256#define REDUCE_VECTOR_WIDTH 4@@ -24,7 +26,7 @@ using namespace uzu::gemm;namespace {struct TrellisEpilogue {- const device float* scale_and_offsets;+ TrellisCodebook codebook;const device float4* group_sums;const device float* activation_scales;const device float* row_scales;@@ -36,9 +38,8 @@ struct TrellisEpilogue {const int level_dot =biased_dot - int(trellis::WEIGHT_BIAS) * int(group_sum.x + group_sum.y + group_sum.z + group_sum.w);const float activation_scale = activation_scales[token];- const float4 offsets =- float4(scale_and_offsets[1], scale_and_offsets[2], scale_and_offsets[3], scale_and_offsets[4]);- const float dot = float(level_dot) * scale_and_offsets[0] + metal::dot(group_sum, offsets);+ const float4 offsets = float4(codebook.offsets[0], codebook.offsets[1], codebook.offsets[2], codebook.offsets[3]);+ const float dot = float(level_dot) * codebook.scale + metal::dot(group_sum, offsets);output[token * output_row_stride + row] = bfloat(dot * row_scales[row] * activation_scale);}};@@ -96,7 +97,7 @@ KERNEL(GemmTrellis)(const device float* activation_scales,const device uint8_t* codes,const device float* row_scales,- const device float* scale_and_offsets,+ const constant TrellisCodebook& codebook,device bfloat* output,const constant uzu::matmul::GemmParams* params,threadgroup half stage[TRELLIS_STAGE_ELEMENTS],@@ -140,14 +141,8 @@ KERNEL(GemmTrellis)(const bool write_split_k_partials = params->aligned_inner_iterations * trellis::K_STEP < params->K;const size_t partial_sum_offset = size_t(group_z) * params->M * params->N;- const TrellisEpilogue epilogue{- scale_and_offsets,- column_group_sums,- activation_scales,- row_scales,- output,- params->leading_dimension_d- };+ const TrellisEpilogue+ epilogue{codebook, column_group_sums, activation_scales, row_scales, output, params->leading_dimension_d};const auto store = [&](const uint token, const uint row, const int value) {if (token < params->M && row < params->N) {if (write_split_k_partials) {@@ -303,7 +298,7 @@ KERNEL(GemmTrellisReduce)(const device float4* column_group_sums,const device float* activation_scales,const device float* row_scales,- const device float* scale_and_offsets,+ const constant TrellisCodebook& codebook,device bfloat* output,const constant uint& token_count,const constant uint& row_count,@@ -323,8 +318,7 @@ KERNEL(GemmTrellisReduce)(}const uint token = token_row_group / row_groups;const uint first_row = token_row_group % row_groups * REDUCE_VECTOR_WIDTH;- const TrellisEpilogue- epilogue{scale_and_offsets, column_group_sums, activation_scales, row_scales, output, output_stride};+ const TrellisEpilogue epilogue{codebook, column_group_sums, activation_scales, row_scales, output, output_stride};for (uint index = 0u; index < REDUCE_VECTOR_WIDTH; ++index) {epilogue.store(partial_sum[index], token, first_row + index);}diff --git a/crates/uzu-engine/src/backends/metal/kernel/matmul/gemm/gemm_trellis_decode.metal b/crates/uzu-engine/src/backends/metal/kernel/matmul/gemm/gemm_trellis_decode.metalindex aa779d936..14a72d9f2 100644--- a/crates/uzu-engine/src/backends/metal/kernel/matmul/gemm/gemm_trellis_decode.metal+++ b/crates/uzu-engine/src/backends/metal/kernel/matmul/gemm/gemm_trellis_decode.metal@@ -1,9 +1,11 @@#include "../../common/dsl.h"+#include "../../generated/trellis.h"#include "../common/quant_unpack.h"#include "common/quantized/trellis.h"using namespace metal;using namespace uzu::gemm;+using uzu::trellis::TrellisCodebook;#define SIMDGROUPS 8#define ROWS_PER_SIMDGROUP 4@@ -18,7 +20,7 @@ KERNEL(GemmTrellisDecode)(const device float* activation_scales,const device uint8_t* codes,const device float* row_scales,- const device float* scale_and_offsets,+ const constant TrellisCodebook& codebook,device bfloat* output,const constant uint& k,const constant uint& n,@@ -86,7 +88,7 @@ KERNEL(GemmTrellisDecode)(}}- const float4 offsets = float4(scale_and_offsets[1], scale_and_offsets[2], scale_and_offsets[3], scale_and_offsets[4]);+ const float4 offsets = float4(codebook.offsets[0], codebook.offsets[1], codebook.offsets[2], codebook.offsets[3]);METAL_PRAGMA_UNROLLfor (uint token = 0; token < MAX_BATCH; ++token) {if (token < batch) {@@ -96,7 +98,7 @@ KERNEL(GemmTrellisDecode)(const float level_dot = float(simd_sum(int(sums[token][row])));if (lane == 0 && first_row + row < n) {output[token * output_stride + first_row + row] = bfloat(- (level_dot * scale_and_offsets[0] + offsets_dot) * row_scales[first_row + row] * activation_scales[token]+ (level_dot * codebook.scale + offsets_dot) * row_scales[first_row + row] * activation_scales[token]);}}diff --git a/crates/uzu-engine/src/backends/metal/kernel/matmul/gemv/gemv.metal b/crates/uzu-engine/src/backends/metal/kernel/matmul/gemv/gemv.metalindex 682282502..701f6784a 100644--- a/crates/uzu-engine/src/backends/metal/kernel/matmul/gemv/gemv.metal+++ b/crates/uzu-engine/src/backends/metal/kernel/matmul/gemv/gemv.metal@@ -69,7 +69,8 @@ CONSTRAINT(((B_PROLOGUE == GemmBPrologueKind::ScaleBiasDequant ||B_PROLOGUE == GemmBPrologueKind::ScaleZeroPointDequant) &&BITS == 4 && BLOCK_K != 0) ||- (B_PROLOGUE == GemmBPrologueKind::ScaleSymmetricDequant && BITS == 8 && BLOCK_K != 0) ||+ (B_PROLOGUE == GemmBPrologueKind::ScaleSymmetricDequant && BLOCK_K != 0 &&+ (BITS == 8 || (BITS == 4 && INPUT_ROW_TILE == 1 && BLOCK_K == 64 && AT == "bfloat" && DT == "bfloat"))) ||(B_PROLOGUE == GemmBPrologueKind::ScaleBiasDequant && BITS == 2 && GEMV_QUANTIZED_ROW_TILE))CONSTRAINT((BITS == 2) == (BLOCK_K == 128))CONSTRAINT(INPUT_ROW_TILE == 1 || GEMV_BATCHED_INPUT)diff --git a/crates/uzu-engine/src/backends/slang/kernel/generated/trellis.slang b/crates/uzu-engine/src/backends/slang/kernel/generated/trellis.slangindex 33a6cd1f1..bc3d637d4 100644--- a/crates/uzu-engine/src/backends/slang/kernel/generated/trellis.slang+++ b/crates/uzu-engine/src/backends/slang/kernel/generated/trellis.slang@@ -1 +1,12 @@-static const uint COLUMN_GROUP_COUNT = 4;\ No newline at end of file+static const uint COLUMN_GROUP_COUNT = 4;++static const uint MAX_DIMENSION = 20480;++static const uint MIN_HADAMARD_SIZE = 512;++static const uint MAX_HADAMARD_SIZE = 4096;++struct TrellisCodebook {+ float scale;+ float offsets[4];+};\ No newline at end of filediff --git a/crates/uzu-engine/src/config/weight_matrix/d4s4_spec.rs b/crates/uzu-engine/src/config/weight_matrix/d4s4_spec.rsindex e46926df0..52e5f61b8 100644--- a/crates/uzu-engine/src/config/weight_matrix/d4s4_spec.rs+++ b/crates/uzu-engine/src/config/weight_matrix/d4s4_spec.rs@@ -2,8 +2,14 @@ use uzu_engine_macros::uzu_config;use crate::config::weight_matrix::Layout;-/// Lookup-only embedding table: one D4 lattice code per 4 columns and a ladder scale per 64 columns.+/// Lookup-only D4S4 table: one D4 lattice code per 4 columns and a ladder scale per 64 columns.#[uzu_config(super::WeightMatrixSpec)]pub struct D4S4Spec {pub layout: Layout,}++#[uzu_config(super::WeightMatrixSpec)]+pub struct LatticeSpec {+ pub kind: monostate::MustBe!("d4"),+ pub layout: Layout,+}diff --git a/crates/uzu-engine/src/config/weight_matrix/hybrid_spec.rs b/crates/uzu-engine/src/config/weight_matrix/hybrid_spec.rsindex 631c9056b..58ffa71c0 100644--- a/crates/uzu-engine/src/config/weight_matrix/hybrid_spec.rs+++ b/crates/uzu-engine/src/config/weight_matrix/hybrid_spec.rs@@ -1,4 +1,4 @@-use uzu_engine_macros::uzu_config;+use uzu_engine_macros::{uzu_config, uzu_config_abstract};use crate::{config::weight_matrix::AnyWeightMatrixSpec, utils::strict_serde::Unsupported};@@ -10,17 +10,23 @@ pub enum IncoherenceProcessingMode {InputOutput,}-#[uzu_config]+#[uzu_config_abstract(HadamardSpec, KroneckerSpec)]+pub struct IncoherenceProcessorSpec;++#[uzu_config(self::IncoherenceProcessorSpec)]pub struct HadamardSpec {- #[serde(rename = "type")]- ty: monostate::MustBe!("HadamardSpec"),pub block_size: u32,pub processing_mode: IncoherenceProcessingMode,}+#[uzu_config(self::IncoherenceProcessorSpec)]+pub struct KroneckerSpec {+ pub processing_mode: IncoherenceProcessingMode,+}+#[uzu_config(super::WeightMatrixSpec)]pub struct HybridSpec {pub quantization_spec: Box<AnyWeightMatrixSpec>,pub adapter_spec: Option<Unsupported>,- pub incoherence_spec: Option<HadamardSpec>,+ pub incoherence_spec: Option<AnyIncoherenceProcessorSpec>,}diff --git a/crates/uzu-engine/src/config/weight_matrix/mod.rs b/crates/uzu-engine/src/config/weight_matrix/mod.rsindex bf70fa20b..17de5fb22 100644--- a/crates/uzu-engine/src/config/weight_matrix/mod.rs+++ b/crates/uzu-engine/src/config/weight_matrix/mod.rs@@ -5,6 +5,8 @@ pub mod full_precision_spec;pub mod hybrid_spec;pub mod int_spec;pub mod mlx_spec;+pub mod output_stack;+pub mod qtip_gaussian;#[uzu_config]#[serde(rename_all = "snake_case")]@@ -18,6 +20,9 @@ pub enum Layout {hybrid_spec::HybridSpec,int_spec::IntSpec,mlx_spec::MLXSpec,- d4s4_spec::D4S4Spec+ d4s4_spec::D4S4Spec,+ d4s4_spec::LatticeSpec,+ qtip_gaussian::QtipGaussianSpec,+ output_stack::OutputStackSpec)]pub struct WeightMatrixSpec;diff --git a/crates/uzu-engine/src/config/weight_matrix/output_stack.rs b/crates/uzu-engine/src/config/weight_matrix/output_stack.rsnew file mode 100644index 000000000..f5ac905ea--- /dev/null+++ b/crates/uzu-engine/src/config/weight_matrix/output_stack.rs@@ -0,0 +1,14 @@+use uzu_engine_macros::uzu_config;++use super::AnyWeightMatrixSpec;++#[uzu_config(super::WeightMatrixSpec)]+pub struct OutputStackSpec {+ pub parts: Box<[OutputStackPart]>,+}++#[uzu_config]+pub struct OutputStackPart {+ pub rows: u32,+ pub spec: AnyWeightMatrixSpec,+}diff --git a/crates/uzu-engine/src/config/weight_matrix/qtip_gaussian.rs b/crates/uzu-engine/src/config/weight_matrix/qtip_gaussian.rsnew file mode 100644index 000000000..a8e015a9b--- /dev/null+++ b/crates/uzu-engine/src/config/weight_matrix/qtip_gaussian.rs@@ -0,0 +1,14 @@+use uzu_engine_macros::uzu_config;++use super::Layout;+use crate::backends::common::gpu_types::trellis::TrellisCodebook;++#[uzu_config(super::WeightMatrixSpec)]+pub struct QtipGaussianSpec {+ pub vector_width: u32,+ pub transition_bits: u32,+ pub restart_columns: u32,+ pub codebook: TrellisCodebook,+ pub layout: Layout,+ pub tape: monostate::MustBe!(2u64),+}diff --git a/crates/uzu-engine/src/encodable_block/embedding_table.rs b/crates/uzu-engine/src/encodable_block/embedding_table.rsindex ef662893c..a4facdb06 100644--- a/crates/uzu-engine/src/encodable_block/embedding_table.rs+++ b/crates/uzu-engine/src/encodable_block/embedding_table.rs@@ -4,13 +4,18 @@ use thiserror::Error;use crate::{backends::common::{Backend, BufferMut, BufferRef, CommandBuffer, Kernels,- gpu_types::{d4s4, embedding::EmbeddingTableKind, hadamard_order::HADAMARD_TRANSFORM_BLOCK_SIZE},- kernel::InputEmbeddingLookupKernel,+ gpu_types::{+ d4s4, embedding::EmbeddingTableKind, hadamard_order::HADAMARD_TRANSFORM_BLOCK_SIZE,+ quantization_method::QuantizationMethod,+ },+ kernel::{+ InputEmbeddingLookupKernel,+ matmul::{MatmulB, QuantizedCorrection},+ },},config::weight_matrix::{AnyWeightMatrixSpec, Layout,- d4s4_spec::D4S4Spec,- hybrid_spec::{HadamardSpec, HybridSpec, IncoherenceProcessingMode},+ hybrid_spec::{AnyIncoherenceProcessorSpec, HadamardSpec, HybridSpec, IncoherenceProcessingMode},},data_type::DataType,encodable_block::weight_matrix::{WeightMatrix, WeightMatrixError},@@ -107,26 +112,40 @@ impl<B: Backend> EmbeddingTable<B> {let spec = tree.metadata::<AnyWeightMatrixSpec>("spec")?;let (storage, output_hadamard_factors) = match spec {AnyWeightMatrixSpec::D4S4Spec(spec) => {- let (table, factors) = load_d4s4(tree, vocab_size, embedding_dim, data_type, spec).await?;+ let table = load_d4s4(tree, vocab_size, embedding_dim, data_type, spec.layout).await?;+ let factors = tree.read_buffer("output_hadamard_factors", &[embedding_dim], DataType::I32).await?;(Storage::D4S4(table), Some(factors))},+ AnyWeightMatrixSpec::LatticeSpec(spec) => {+ let table = load_d4s4(tree, vocab_size, embedding_dim, data_type, spec.layout).await?;+ (Storage::D4S4(table), None)+ },AnyWeightMatrixSpec::HybridSpec(HybridSpec {quantization_spec,incoherence_spec:- Some(HadamardSpec {+ Some(AnyIncoherenceProcessorSpec::HadamardSpec(HadamardSpec {block_size: HADAMARD_TRANSFORM_BLOCK_SIZE,processing_mode: IncoherenceProcessingMode::Output,..- }),+ })),..}) if embedding_dim.is_multiple_of(HADAMARD_TRANSFORM_BLOCK_SIZE) => {- let matrix = load_matrix(&tree.subtree("quantized"), *quantization_spec).await?;- if matrix.quantization().is_none() {- return Err(EmbeddingTableError::UnsupportedConfiguration(- "output-Hadamard factors require a quantized table".into(),- ));- }- (Storage::Matrix(matrix), Some(read_output_signs(tree, embedding_dim).await?))+ let storage = match *quantization_spec {+ AnyWeightMatrixSpec::LatticeSpec(spec) => Storage::D4S4(+ load_d4s4(&tree.subtree("quantized"), vocab_size, embedding_dim, data_type, spec.layout)+ .await?,+ ),+ spec => {+ let matrix = load_matrix(&tree.subtree("quantized"), spec).await?;+ if matrix.matmul_b().quantized().is_none() {+ return Err(EmbeddingTableError::UnsupportedConfiguration(+ "output-Hadamard factors require a quantized table".into(),+ ));+ }+ Storage::Matrix(matrix)+ },+ };+ (storage, Some(read_output_signs(tree, embedding_dim).await?))},spec @ AnyWeightMatrixSpec::HybridSpec(_) => {return Err(EmbeddingTableError::UnsupportedConfiguration(format!(@@ -138,17 +157,18 @@ impl<B: Backend> EmbeddingTable<B> {let (table_kind, quantization) = match &storage {Storage::D4S4(_) => (EmbeddingTableKind::D4S4, None),- Storage::Matrix(matrix) => {- if let Some(info) = matrix.quantization() {- (EmbeddingTableKind::Quantized, Some(info))- } else {- (EmbeddingTableKind::Dense, None)- }+ Storage::Matrix(matrix) => match matrix.matmul_b() {+ MatmulB::Quantized(quantized) => (EmbeddingTableKind::Quantized, Some(quantized)),+ _ => (EmbeddingTableKind::Dense, None),},};- let group_size = quantization.map(|info| info.group_size);- let mode = quantization.map(|info| info.mode);- let method = quantization.map(|info| info.method);+ let group_size = quantization.as_ref().map(|quantized| quantized.group_size);+ let mode = quantization.as_ref().map(|quantized| quantized.mode);+ let method = quantization.as_ref().map(|quantized| match quantized.correction {+ QuantizedCorrection::Symmetric => QuantizationMethod::ScaleSymmetric,+ QuantizedCorrection::Biases(_) => QuantizationMethod::ScaleBias,+ QuantizedCorrection::ZeroPoints(_) => QuantizationMethod::ScaleZeroPoint,+ });let use_hadamard = output_hadamard_factors.is_some();let lookup = LookupKernel::<B>::new(context, data_type, table_kind, group_size, mode, method, use_hadamard).map_err(EmbeddingTableError::BackendError)?;@@ -205,11 +225,11 @@ async fn load_d4s4<B: Backend>(vocab_size: u32,embedding_dim: u32,data_type: DataType,- spec: D4S4Spec,-) -> Result<(D4S4Table<B>, B::GlobalGpuBuffer), EmbeddingTableError<B>> {- if spec.layout != Layout::InputOutput || !embedding_dim.is_multiple_of(d4s4::COLUMNS_PER_LADDER_INDEX_BYTE) {+ layout: Layout,+) -> Result<D4S4Table<B>, EmbeddingTableError<B>> {+ if layout != Layout::InputOutput || !embedding_dim.is_multiple_of(d4s4::COLUMNS_PER_LADDER_INDEX_BYTE) {return Err(EmbeddingTableError::UnsupportedConfiguration(format!(- "{spec:?} with {data_type:?} and embedding dim {embedding_dim}"+ "{layout:?} with {data_type:?} and embedding dim {embedding_dim}")));}let read = async |name: &str, shape: &[u32], data_type| tree.read_buffer(name, shape, data_type).await;@@ -227,8 +247,7 @@ async fn load_d4s4<B: Backend>(ladder,codebook,};- let factors = read("output_hadamard_factors", &[embedding_dim], DataType::I32).await?;- Ok((table, factors))+ Ok(table)}pub(super) async fn read_output_signs<B: Backend>(diff --git a/crates/uzu-engine/src/encodable_block/linear/input_rht.rs b/crates/uzu-engine/src/encodable_block/linear/input_rht.rsindex 286380555..31572a4d1 100644--- a/crates/uzu-engine/src/encodable_block/linear/input_rht.rs+++ b/crates/uzu-engine/src/encodable_block/linear/input_rht.rs@@ -3,7 +3,7 @@ use std::mem::size_of;use super::{LinearInput, LinearInputPreparation};use crate::{backends::common::{- Backend, Buffer, BufferRef, CommandBuffer, CommandBufferEncoding,+ Backend, Buffer, BufferMut, BufferRef, CommandBuffer, CommandBufferEncoding,kernel::{ActivationTransform,matmul::{ActivationFormat, MatmulA, packed_half_bytes},@@ -12,7 +12,7 @@ use crate::{data_type::DataType,};-pub(super) struct InputRht<B: Backend> {+pub struct InputRht<B: Backend> {rht_signs: B::GlobalGpuBuffer,rht: ActivationTransform<B>,quantizer: Option<ActivationTransform<B>>,@@ -104,17 +104,28 @@ impl<B: Backend> InputRht<B> {pub(super) fn prepare_in_place(&self,mut input: B::ScratchBuffer,+ offset: usize,batch_dim: u32,format: ActivationFormat,command_buffer: &mut <B::CommandBuffer as CommandBuffer>::Encoding,) -> Result<LinearInput<B>, B::Error> {if self.quantizer.as_ref().is_some_and(|kernel| kernel.format() == format) {- return self.prepare(&input, batch_dim, format, command_buffer);+ return self.prepare((&input).subrange(offset..), batch_dim, format, command_buffer);}let input_dim = self.input_dim();- self.rht.encode_fp_in_place(&mut input, &self.rht_signs, None, batch_dim, input_dim, command_buffer);- Ok(MatmulA::full_precision(input))+ self.rht.encode_fp_in_place(+ (&mut input).subrange_mut(offset..),+ &self.rht_signs,+ None,+ batch_dim,+ input_dim,+ command_buffer,+ );+ Ok(MatmulA::FullPrecision {+ values: input,+ offset,+ })}fn input_dim(&self) -> u32 {diff --git a/crates/uzu-engine/src/encodable_block/linear/matmul.rs b/crates/uzu-engine/src/encodable_block/linear/matmul.rsindex fee4187a9..cd3d9f085 100644--- a/crates/uzu-engine/src/encodable_block/linear/matmul.rs+++ b/crates/uzu-engine/src/encodable_block/linear/matmul.rs@@ -4,7 +4,7 @@ use thiserror::Error;use crate::{backends::common::{- Backend, BufferRef, CommandBuffer, CommandBufferEncoding,+ Backend, BufferMut, BufferRef, CommandBuffer, CommandBufferEncoding,kernel::{Kernels,matmul::{@@ -68,6 +68,10 @@ async fn load_biases<B: Backend>(}impl<B: Backend> LinearMatmul<B> {+ pub(super) fn output_dim(&self) -> u32 {+ self.output_dim+ }+pub async fn load(input_dim: u32,output_dim: u32,@@ -89,7 +93,7 @@ impl<B: Backend> LinearMatmul<B> {let matrix =WeightMatrix::load(output_dim, input_dim, weights_data_type, spec, Layout::OutputInput, weights_tree).await?;- if output_hadamard_factors.is_some() && matrix.quantization().is_none() {+ if output_hadamard_factors.is_some() && matrix.matmul_b().quantized().is_none() {return Err(LinearMatmulError::UnsupportedConfiguration("fused output-hadamard factors require quantized weights".into(),));@@ -139,6 +143,48 @@ impl<B: Backend> LinearMatmul<B> {let mut output = command_buffer.allocate_scratch_for_shape(&[batch_dim, output_dim], self.output_data_type).map_err(LinearEncodeError::Backend)?;+ self.encode_output(+ a,+ batch_dim,+ output_dim,+ gather_indices,+ MatmulOutput::new(&mut output, self.d_ops()),+ command_buffer,+ )?;++ Ok(output)+ }++ pub(super) fn encode_columns(+ &self,+ a: MatmulA<impl BufferRef<Backend = B>>,+ batch_dim: u32,+ output: &mut B::ScratchBuffer,+ column: u32,+ row_stride: u32,+ command_buffer: &mut <B::CommandBuffer as CommandBuffer>::Encoding,+ ) -> Result<(), LinearEncodeError<B>> {+ let element = self.output_data_type.size_in_bytes();+ if !self.matmul_b().is_trellis() {+ unreachable!("TODO: support strided output in ordinary GEMM/GEMV");+ }+ let output = MatmulOutput {+ values: output.subrange_mut(column as usize * element..),+ row_stride: Some(row_stride),+ ops: self.d_ops(),+ };+ self.encode_output(a, batch_dim, self.output_dim, None::<&B::ScratchBuffer>, output, command_buffer)+ }++ fn encode_output(+ &self,+ a: MatmulA<impl BufferRef<Backend = B>>,+ batch_dim: u32,+ output_dim: u32,+ gather_indices: Option<impl BufferRef<Backend = B>>,+ output: MatmulOutput<'_, B, impl BufferMut<Backend = B>>,+ command_buffer: &mut <B::CommandBuffer as CommandBuffer>::Encoding,+ ) -> Result<(), LinearEncodeError<B>> {self.kernel.lock().encode(@@ -147,7 +193,7 @@ impl<B: Backend> LinearMatmul<B> {b: self.matmul_b(),b_leading_dimension: None,b_transpose: true,- output: MatmulOutput::new(&mut output, self.d_ops()),+ output,gather_indices,m: batch_dim,n: output_dim,@@ -155,9 +201,7 @@ impl<B: Backend> LinearMatmul<B> {},command_buffer,)- .map_err(LinearEncodeError::Matmul)?;-- Ok(output)+ .map_err(LinearEncodeError::Matmul)}fn matmul_shape(diff --git a/crates/uzu-engine/src/encodable_block/linear/mod.rs b/crates/uzu-engine/src/encodable_block/linear/mod.rsindex bfd717f50..6fc02e4e3 100644--- a/crates/uzu-engine/src/encodable_block/linear/mod.rs+++ b/crates/uzu-engine/src/encodable_block/linear/mod.rs@@ -1,25 +1,26 @@use derive_more::Debug;use thiserror::Error;+use self::transformed_linear::InputPreparationMode;+mod input_rht;mod matmul;-mod rht_wrapper;+mod transformed_linear;mod untied_readout;pub use matmul::{LinearMatmul, LinearMatmulError};-pub use rht_wrapper::{RHTLinearWrapper, RHTLinearWrapperError};+pub use transformed_linear::TransformedLinear;pub use untied_readout::UntiedReadout;use crate::{backends::common::{Backend, CommandBuffer, Kernels,- gpu_types::hadamard_order::HADAMARD_TRANSFORM_BLOCK_SIZE,- kernel::matmul::{ActivationFormat, MatmulA, MatmulKernel},- },- config::weight_matrix::{- AnyWeightMatrixSpec,- hybrid_spec::{HadamardSpec, HybridSpec, IncoherenceProcessingMode},+ kernel::{+ ActivationFormat,+ matmul::{MatmulA, MatmulKernel},+ },},+ config::weight_matrix::AnyWeightMatrixSpec,data_type::DataType,safetensors::{ParameterLoaderError, ParameterTree},};@@ -70,8 +71,8 @@ pub struct LinearInputPreparation<B: Backend> {pub enum LinearBlockError<B: Backend> {#[error("LinearMatmul error: {0}")]LinearMatmulError(#[from] LinearMatmulError<B>),- #[error("RHTLinearWrapper error: {0}")]- RHTLinearWrapperError(#[from] RHTLinearWrapperError<B>),+ #[error("Backend error: {0}")]+ Backend(#[source] B::Error),#[error("Parameter loading error: {0}")]ParameterError(#[from] ParameterLoaderError<B>),#[error("Unsupported linear configuration: {0}")]@@ -95,7 +96,7 @@ impl<B: Backend> dyn Linear<B> {spec @ (AnyWeightMatrixSpec::FullPrecisionSpec(_)| AnyWeightMatrixSpec::MLXSpec(_)| AnyWeightMatrixSpec::IntSpec(_)) => {- let block = LinearMatmul::load(+ let matrix = LinearMatmul::load(input_dimension,output_dimension,weights_data_type,@@ -108,29 +109,24 @@ impl<B: Backend> dyn Linear<B> {context,).await?;- Ok(Box::new(block))+ Ok(Box::new(matrix))},- AnyWeightMatrixSpec::HybridSpec(HybridSpec {- incoherence_spec:- Some(HadamardSpec {- block_size: HADAMARD_TRANSFORM_BLOCK_SIZE,- processing_mode: IncoherenceProcessingMode::InputOutput,- ..- }),- ..- }) => Ok(Box::new(- RHTLinearWrapper::new(+ AnyWeightMatrixSpec::HybridSpec(spec) => {+ let (linear, _) = TransformedLinear::load(input_dimension,output_dimension,weights_data_type,input_data_type,output_data_type,- has_biases,- parameter_tree,+ has_biases.then_some(parameter_tree),+ spec,+ &weights_tree,+ InputPreparationMode::InLinear,context,)- .await?,- )),+ .await?;+ Ok(linear)+ },spec => Err(LinearBlockError::UnsupportedConfiguration(format!("{spec:?}"))),}}@@ -166,7 +162,7 @@ impl<B: Backend> dyn Linear<B> {parameter_tree: &ParameterTree<'_, B>,context: &B::Context,) -> Result<(Box<dyn Linear<B>>, Option<B::GlobalGpuBuffer>), LinearBlockError<B>> {- if let Some(linear) = RHTLinearWrapper::try_new_with_input_preparation(+ let (linear, preparation) = Self::new_with_input_preparation(input_dimension,output_dimension,weights_data_type,@@ -177,23 +173,8 @@ impl<B: Backend> dyn Linear<B> {parameter_tree,context,)- .await?- {- return Ok((linear.0, linear.1.map(|preparation| preparation.rht_signs)));- }-- let linear = Self::new_mixed_precision(- input_dimension,- output_dimension,- weights_data_type,- input_data_type,- output_data_type,- has_biases,- parameter_tree,- context,- ).await?;- Ok((linear, None))+ Ok((linear, preparation.map(|preparation| preparation.rht_signs)))}pub async fn new_for_fused_input(@@ -204,7 +185,7 @@ impl<B: Backend> dyn Linear<B> {parameter_tree: &ParameterTree<'_, B>,context: &B::Context,) -> Result<(Box<dyn Linear<B>>, Option<LinearInputPreparation<B>>), LinearBlockError<B>> {- if let Some(linear) = RHTLinearWrapper::try_new_with_input_preparation(+ Self::new_with_input_preparation(input_dimension,output_dimension,data_type,@@ -215,23 +196,7 @@ impl<B: Backend> dyn Linear<B> {parameter_tree,context,)- .await?- {- return Ok(linear);- }-- let linear = Self::new_mixed_precision(- input_dimension,- output_dimension,- data_type,- data_type,- data_type,- has_biases,- parameter_tree,- context,- )- .await?;- Ok((linear, None))+ .await}pub async fn new_with_input_rht(@@ -254,4 +219,52 @@ impl<B: Backend> dyn Linear<B> {).await}++ async fn new_with_input_preparation(+ input_dimension: u32,+ output_dimension: u32,+ weights_data_type: DataType,+ input_data_type: DataType,+ output_data_type: DataType,+ has_biases: bool,+ allow_quantized_activations: bool,+ parameter_tree: &ParameterTree<'_, B>,+ context: &B::Context,+ ) -> Result<(Box<dyn Linear<B>>, Option<LinearInputPreparation<B>>), LinearBlockError<B>> {+ let weights_tree = parameter_tree.subtree("weights");+ let spec = weights_tree.metadata::<AnyWeightMatrixSpec>("spec")?;+ match spec {+ AnyWeightMatrixSpec::HybridSpec(spec) => {+ TransformedLinear::load(+ input_dimension,+ output_dimension,+ weights_data_type,+ input_data_type,+ output_data_type,+ has_biases.then_some(parameter_tree),+ spec,+ &weights_tree,+ InputPreparationMode::AllowExternal {+ allow_quantized_activations,+ },+ context,+ )+ .await+ },+ _ => {+ let linear = Self::new_mixed_precision(+ input_dimension,+ output_dimension,+ weights_data_type,+ input_data_type,+ output_data_type,+ has_biases,+ parameter_tree,+ context,+ )+ .await?;+ Ok((linear, None))+ },+ }+ }}diff --git a/crates/uzu-engine/src/encodable_block/linear/rht_wrapper.rs b/crates/uzu-engine/src/encodable_block/linear/rht_wrapper.rsdeleted file mode 100644index a3d5392a8..000000000--- a/crates/uzu-engine/src/encodable_block/linear/rht_wrapper.rs+++ /dev/null@@ -1,241 +0,0 @@-use derive_more::Debug;-use thiserror::Error;--use crate::{- backends::common::{- Backend, CommandBuffer, CommandBufferEncoding,- gpu_types::hadamard_order::HADAMARD_TRANSFORM_BLOCK_SIZE,- kernel::{ActivationFormat, matmul::MatmulA},- },- config::weight_matrix::{- AnyWeightMatrixSpec,- hybrid_spec::{HadamardSpec, HybridSpec, IncoherenceProcessingMode},- },- data_type::DataType,- encodable_block::linear::{- Linear, LinearEncodeError, LinearInput, LinearInputPreparation, LinearMatmul, LinearMatmulError,- input_rht::InputRht,- },- safetensors::{ParameterLoaderError, ParameterTree},-};--#[derive(Debug, Error)]-pub enum RHTLinearWrapperError<B: Backend> {- #[error("Inner linear error: {0}")]- InnerLinearError(#[from] LinearMatmulError<B>),- #[error("Parameter loading error: {0}")]- ParameterError(#[from] ParameterLoaderError<B>),- #[error("Backend error: {0}")]- BackendError(#[source] B::Error),- #[error("Unsupported RHT linear configuration: {0}")]- UnsupportedConfiguration(String),-}--pub struct RHTLinearWrapper<B: Backend> {- input_rht: InputRht<B>,- inner_linear: LinearMatmul<B>,-}--fn has_input_output_rht(spec: &AnyWeightMatrixSpec) -> bool {- matches!(- spec,- AnyWeightMatrixSpec::HybridSpec(HybridSpec {- incoherence_spec: Some(HadamardSpec {- block_size: HADAMARD_TRANSFORM_BLOCK_SIZE,- processing_mode: IncoherenceProcessingMode::InputOutput,- ..- }),- ..- })- )-}--impl<B: Backend> RHTLinearWrapper<B> {- pub(super) async fn new(- input_dimension: u32,- output_dimension: u32,- weights_data_type: DataType,- input_data_type: DataType,- output_data_type: DataType,- has_biases: bool,- parameter_tree: &ParameterTree<'_, B>,- context: &B::Context,- ) -> Result<Self, RHTLinearWrapperError<B>> {- let (rht_signs, inner_linear, activation_format) = Self::load_inner(- input_dimension,- output_dimension,- weights_data_type,- input_data_type,- output_data_type,- has_biases,- true,- parameter_tree,- context,- )- .await?;- Self::build_self_contained(- input_data_type,- LinearInputPreparation {- rht_signs,- activation_format,- },- inner_linear,- context,- )- }-- pub async fn new_with_rotated_output(- input_dimension: u32,- output_dimension: u32,- data_type: DataType,- parameter_tree: &ParameterTree<'_, B>,- context: &B::Context,- ) -> Result<Self, RHTLinearWrapperError<B>> {- let (rht_signs, inner_linear, activation_format) = Self::load_inner(- input_dimension,- output_dimension,- data_type,- data_type,- data_type,- false,- false,- parameter_tree,- context,- )- .await?;- Self::build_self_contained(- data_type,- LinearInputPreparation {- rht_signs,- activation_format,- },- inner_linear,- context,- )- }-- pub(super) async fn try_new_with_input_preparation(- input_dimension: u32,- output_dimension: u32,- weights_data_type: DataType,- input_data_type: DataType,- output_data_type: DataType,- has_biases: bool,- allow_prequantized_activation: bool,- parameter_tree: &ParameterTree<'_, B>,- context: &B::Context,- ) -> Result<Option<(Box<dyn Linear<B>>, Option<LinearInputPreparation<B>>)>, RHTLinearWrapperError<B>> {- let weights_tree = parameter_tree.subtree("weights");- let spec = weights_tree.metadata::<AnyWeightMatrixSpec>("spec")?;- if !has_input_output_rht(&spec) {- return Ok(None);- }-- let (rht_signs, inner_linear, activation_format) = Self::load_inner(- input_dimension,- output_dimension,- weights_data_type,- input_data_type,- output_data_type,- has_biases,- true,- parameter_tree,- context,- )- .await?;- let input_preparation = LinearInputPreparation {- rht_signs,- activation_format,- };- if input_preparation.activation_format != ActivationFormat::Bf16 && !allow_prequantized_activation {- let wrapper = Self::build_self_contained(input_data_type, input_preparation, inner_linear, context)?;- Ok(Some((Box::new(wrapper), None)))- } else {- Ok(Some((Box::new(inner_linear), Some(input_preparation))))- }- }-- async fn load_inner(- input_dimension: u32,- output_dimension: u32,- weights_data_type: DataType,- input_data_type: DataType,- output_data_type: DataType,- has_biases: bool,- restore_output_basis: bool,- parameter_tree: &ParameterTree<'_, B>,- context: &B::Context,- ) -> Result<(B::GlobalGpuBuffer, LinearMatmul<B>, ActivationFormat), RHTLinearWrapperError<B>> {- let weights_tree = parameter_tree.subtree("weights");- let spec = weights_tree.metadata::<AnyWeightMatrixSpec>("spec")?;- if !has_input_output_rht(&spec) {- return Err(RHTLinearWrapperError::UnsupportedConfiguration(format!("{spec:?}")));- }- let quantized_weights_tree = weights_tree.subtree("quantized");- let quantization_spec = quantized_weights_tree.metadata::<AnyWeightMatrixSpec>("spec")?;- let rht_signs =- weights_tree.read_buffer("incoherence_signs.input_signs", &[input_dimension], DataType::I32).await?;- let output_factors = if restore_output_basis {- Some(weights_tree.read_buffer("incoherence_signs.output_signs", &[output_dimension], DataType::I32).await?)- } else {- weights_tree.ignore("incoherence_signs.output_signs", &[output_dimension], DataType::I32)?;- None- };- let mut inner_linear = LinearMatmul::load(- input_dimension,- output_dimension,- weights_data_type,- input_data_type,- output_data_type,- quantization_spec,- output_factors,- &quantized_weights_tree,- has_biases.then_some(parameter_tree),- context,- )- .await?;- let activation_format =- inner_linear.prepare_activation(context).map_err(RHTLinearWrapperError::BackendError)?;- Ok((rht_signs, inner_linear, activation_format))- }-- fn build_self_contained(- input_data_type: DataType,- input_preparation: LinearInputPreparation<B>,- inner_linear: LinearMatmul<B>,- context: &B::Context,- ) -> Result<Self, RHTLinearWrapperError<B>> {- let input_rht = InputRht::new(input_data_type, input_preparation, true, context)- .map_err(RHTLinearWrapperError::BackendError)?;-- Ok(Self {- input_rht,- inner_linear,- })- }-}--impl<B: Backend> Linear<B> for RHTLinearWrapper<B> {- fn encode_input(- &self,- input: LinearInput<B>,- batch_dim: u32,- command_buffer: &mut <B::CommandBuffer as CommandBuffer>::Encoding,- ) -> Result<B::ScratchBuffer, LinearEncodeError<B>> {- let input = match input {- MatmulA::FullPrecision {- values: input,- ..- } => input,- input => return self.inner_linear.encode_input(input, batch_dim, command_buffer),- };- let command_buffer = &mut *command_buffer.debug_group("linear (rht)");-- let format = self.inner_linear.select_activation_format(batch_dim, None, command_buffer.context());- let input = self- .input_rht- .prepare_in_place(input, batch_dim, format, command_buffer)- .map_err(LinearEncodeError::Backend)?;- self.inner_linear.encode_input(input, batch_dim, command_buffer)- }-}diff --git a/crates/uzu-engine/src/encodable_block/linear/transformed_linear.rs b/crates/uzu-engine/src/encodable_block/linear/transformed_linear.rsnew file mode 100644index 000000000..5cc5ff407--- /dev/null+++ b/crates/uzu-engine/src/encodable_block/linear/transformed_linear.rs@@ -0,0 +1,372 @@+use crate::{+ backends::common::{+ Backend, BufferRef, CommandBuffer, CommandBufferEncoding, Kernels,+ gpu_types::{+ hadamard_order::HADAMARD_TRANSFORM_BLOCK_SIZE,+ trellis::{COLUMN_GROUP_COUNT, MAX_DIMENSION, MAX_HADAMARD_SIZE, MIN_HADAMARD_SIZE},+ },+ kernel::{ActivationFormat, TrellisTransformKernel, matmul::MatmulA, mixing_dimension},+ },+ config::weight_matrix::{+ AnyWeightMatrixSpec,+ hybrid_spec::{+ AnyIncoherenceProcessorSpec, HadamardSpec, HybridSpec,+ IncoherenceProcessingMode::{Input, InputOutput},+ },+ },+ data_type::DataType,+ encodable_block::linear::{+ Linear, LinearBlockError, LinearEncodeError, LinearInput, LinearInputPreparation, LinearMatmul,+ input_rht::InputRht,+ },+ safetensors::ParameterTree,+};++pub enum TransformedLinear<B: Backend> {+ Hadamard {+ input_rht: InputRht<B>,+ matrix: LinearMatmul<B>,+ },+ Kronecker {+ kernel: <B::Kernels as Kernels>::TrellisTransformKernel,+ signs: B::GlobalGpuBuffer,+ orthogonal_factor: B::GlobalGpuBuffer,+ matrices: Box<[LinearMatmul<B>]>,+ input_dimension: u32,+ output_dimension: u32,+ },+}++pub(super) enum InputPreparationMode {+ InLinear,+ AllowExternal {+ allow_quantized_activations: bool,+ },+}++impl<B: Backend> TransformedLinear<B> {+ pub(super) async fn load(+ input_dimension: u32,+ output_dimension: u32,+ weights_data_type: DataType,+ input_data_type: DataType,+ output_data_type: DataType,+ bias_tree: Option<&ParameterTree<'_, B>>,+ spec: HybridSpec,+ weights_tree: &ParameterTree<'_, B>,+ input_preparation_mode: InputPreparationMode,+ context: &B::Context,+ ) -> Result<(Box<dyn Linear<B>>, Option<LinearInputPreparation<B>>), LinearBlockError<B>> {+ match spec.incoherence_spec {+ Some(AnyIncoherenceProcessorSpec::HadamardSpec(hadamard))+ if matches!(hadamard.processing_mode, Input | InputOutput) =>+ {+ let (preparation, matrix) = Self::load_hadamard(+ input_dimension,+ output_dimension,+ weights_data_type,+ input_data_type,+ output_data_type,+ hadamard,+ *spec.quantization_spec,+ true,+ weights_tree,+ bias_tree,+ context,+ )+ .await?;+ let use_external_preparation = match input_preparation_mode {+ InputPreparationMode::InLinear => false,+ InputPreparationMode::AllowExternal {+ allow_quantized_activations,+ } => preparation.activation_format == ActivationFormat::Bf16 || allow_quantized_activations,+ };+ if use_external_preparation {+ Ok((Box::new(matrix), Some(preparation)))+ } else {+ let linear = Self::build_self_contained(input_data_type, preparation, matrix, context)?;+ Ok((Box::new(linear), None))+ }+ },+ Some(AnyIncoherenceProcessorSpec::KroneckerSpec(kronecker)) if kronecker.processing_mode == Input => {+ let linear = Self::load_kronecker(+ input_dimension,+ output_dimension,+ weights_data_type,+ input_data_type,+ output_data_type,+ bias_tree,+ *spec.quantization_spec,+ weights_tree,+ context,+ )+ .await?;+ Ok((Box::new(linear), None))+ },+ spec => Err(LinearBlockError::UnsupportedConfiguration(format!("{spec:?}"))),+ }+ }++ async fn load_kronecker(+ input_dimension: u32,+ output_dimension: u32,+ weights_data_type: DataType,+ input_data_type: DataType,+ output_data_type: DataType,+ bias_tree: Option<&ParameterTree<'_, B>>,+ spec: AnyWeightMatrixSpec,+ weights_tree: &ParameterTree<'_, B>,+ context: &B::Context,+ ) -> Result<Self, LinearBlockError<B>> {+ if bias_tree.is_some() {+ return Err(LinearBlockError::UnsupportedConfiguration("Kronecker linear biases".into()));+ }+ if [weights_data_type, input_data_type, output_data_type] != [DataType::BF16; 3] {+ return Err(LinearBlockError::UnsupportedConfiguration("Kronecker linears require BF16".into()));+ }+ let hadamard_size = input_dimension.isolate_lowest_one();+ if !(MIN_HADAMARD_SIZE..=MAX_HADAMARD_SIZE).contains(&hadamard_size) || input_dimension > MAX_DIMENSION {+ return Err(LinearBlockError::UnsupportedConfiguration(format!(+ "Kronecker rotation over {input_dimension} columns"+ )));+ }+ let kernel = <B::Kernels as Kernels>::TrellisTransformKernel::new(context, input_dimension)+ .map_err(LinearBlockError::Backend)?;+ let signs = weights_tree.read_buffer("incoherence_signs.signs", &[input_dimension], DataType::I32).await?;+ let mixing_dimension = mixing_dimension(input_dimension);+ let orthogonal_factor = weights_tree+ .read_buffer("incoherence_signs.orthogonal_factor", &[mixing_dimension, mixing_dimension], DataType::F32)+ .await?;+ let load_matrix = async |rows, spec, tree: &ParameterTree<'_, B>| {+ if !matches!(spec, AnyWeightMatrixSpec::QtipGaussianSpec(_)) {+ return Err(LinearBlockError::UnsupportedConfiguration("expected Trellis weights".into()));+ }+ LinearMatmul::load(+ input_dimension,+ rows,+ DataType::BF16,+ DataType::BF16,+ DataType::BF16,+ spec,+ None,+ tree,+ None,+ context,+ )+ .await+ .map_err(LinearBlockError::from)+ };+ let matrices = match spec {+ AnyWeightMatrixSpec::OutputStackSpec(spec) => {+ let mut matrices = Vec::with_capacity(spec.parts.len());+ for (index, part) in spec.parts.into_vec().into_iter().enumerate() {+ let part_tree = weights_tree.subtree(&format!("quantized.parts.{index}"));+ matrices.push(load_matrix(part.rows, part.spec, &part_tree).await?);+ }+ matrices.into_boxed_slice()+ },+ spec => {+ Box::new([load_matrix(output_dimension, spec, &weights_tree.subtree("quantized")).await?]) as Box<[_]>+ },+ };+ Ok(Self::Kronecker {+ kernel,+ signs,+ orthogonal_factor,+ matrices,+ input_dimension,+ output_dimension,+ })+ }++ pub async fn new_with_rotated_output(+ input_dimension: u32,+ output_dimension: u32,+ data_type: DataType,+ parameter_tree: &ParameterTree<'_, B>,+ context: &B::Context,+ ) -> Result<Self, LinearBlockError<B>> {+ let weights_tree = parameter_tree.subtree("weights");+ let spec = weights_tree.metadata::<AnyWeightMatrixSpec>("spec")?;+ let (hadamard, quantization_spec) = match spec {+ AnyWeightMatrixSpec::HybridSpec(HybridSpec {+ incoherence_spec: Some(AnyIncoherenceProcessorSpec::HadamardSpec(hadamard)),+ quantization_spec,+ ..+ }) if hadamard.processing_mode == InputOutput => (hadamard, *quantization_spec),+ _ => {+ return Err(LinearBlockError::UnsupportedConfiguration(+ "expected input-output Hadamard transform".into(),+ ));+ },+ };+ let (preparation, matrix) = Self::load_hadamard(+ input_dimension,+ output_dimension,+ data_type,+ data_type,+ data_type,+ hadamard,+ quantization_spec,+ false,+ &weights_tree,+ None,+ context,+ )+ .await?;+ Self::build_self_contained(data_type, preparation, matrix, context)+ }++ async fn load_hadamard(+ input_dimension: u32,+ output_dimension: u32,+ weights_data_type: DataType,+ input_data_type: DataType,+ output_data_type: DataType,+ spec: HadamardSpec,+ quantization_spec: AnyWeightMatrixSpec,+ restore_output_basis: bool,+ weights_tree: &ParameterTree<'_, B>,+ bias_tree: Option<&ParameterTree<'_, B>>,+ context: &B::Context,+ ) -> Result<(LinearInputPreparation<B>, LinearMatmul<B>), LinearBlockError<B>> {+ if spec.block_size != HADAMARD_TRANSFORM_BLOCK_SIZE {+ return Err(LinearBlockError::UnsupportedConfiguration(format!("Hadamard block size {}", spec.block_size)));+ }+ let has_output_transform = spec.processing_mode == InputOutput;+ let rht_signs =+ weights_tree.read_buffer("incoherence_signs.input_signs", &[input_dimension], DataType::I32).await?;+ let output_factors = if has_output_transform && restore_output_basis {+ Some(weights_tree.read_buffer("incoherence_signs.output_signs", &[output_dimension], DataType::I32).await?)+ } else {+ if has_output_transform {+ weights_tree.ignore("incoherence_signs.output_signs", &[output_dimension], DataType::I32)?;+ }+ None+ };+ let mut inner_linear = LinearMatmul::load(+ input_dimension,+ output_dimension,+ weights_data_type,+ input_data_type,+ output_data_type,+ quantization_spec,+ output_factors,+ &weights_tree.subtree("quantized"),+ bias_tree,+ context,+ )+ .await?;+ let activation_format = inner_linear.prepare_activation(context).map_err(LinearBlockError::Backend)?;+ Ok((+ LinearInputPreparation {+ rht_signs,+ activation_format,+ },+ inner_linear,+ ))+ }++ fn build_self_contained(+ input_data_type: DataType,+ input_preparation: LinearInputPreparation<B>,+ inner_linear: LinearMatmul<B>,+ context: &B::Context,+ ) -> Result<Self, LinearBlockError<B>> {+ let input_rht =+ InputRht::new(input_data_type, input_preparation, true, context).map_err(LinearBlockError::Backend)?;++ Ok(Self::Hadamard {+ input_rht,+ matrix: inner_linear,+ })+ }+}++impl<B: Backend> Linear<B> for TransformedLinear<B> {+ fn encode_input(+ &self,+ input: LinearInput<B>,+ batch_dim: u32,+ command_buffer: &mut <B::CommandBuffer as CommandBuffer>::Encoding,+ ) -> Result<B::ScratchBuffer, LinearEncodeError<B>> {+ let command_buffer = &mut *command_buffer.debug_group("linear (transformed)");+ match self {+ Self::Hadamard {+ input_rht,+ matrix,+ } => {+ let input = match input {+ MatmulA::FullPrecision {+ values,+ offset,+ } => {+ let format = matrix.select_activation_format(batch_dim, None, command_buffer.context());+ input_rht+ .prepare_in_place(values, offset, batch_dim, format, command_buffer)+ .map_err(LinearEncodeError::Backend)?+ },+ prepared => prepared,+ };+ matrix.encode_input(input, batch_dim, command_buffer)+ },+ Self::Kronecker {+ kernel,+ signs,+ orthogonal_factor,+ matrices,+ input_dimension,+ output_dimension,+ } => {+ let input = match input {+ MatmulA::FullPrecision {+ values: input,+ offset,+ } => {+ let mut values = command_buffer+ .allocate_scratch_for_shape(&[batch_dim, *input_dimension], DataType::I8)+ .map_err(LinearEncodeError::Backend)?;+ let mut column_group_sums = command_buffer+ .allocate_scratch_for_shape(&[batch_dim, COLUMN_GROUP_COUNT], DataType::F32)+ .map_err(LinearEncodeError::Backend)?;+ let mut scales = command_buffer+ .allocate_scratch_for_shape(&[batch_dim], DataType::F32)+ .map_err(LinearEncodeError::Backend)?;+ kernel.encode(+ (&input).subrange(offset..),+ signs,+ orthogonal_factor,+ &mut values,+ &mut column_group_sums,+ &mut scales,+ batch_dim,+ command_buffer,+ );+ MatmulA::Trellis {+ values,+ column_group_sums,+ scales,+ }+ },+ prepared => prepared,+ };+ let mut output = command_buffer+ .allocate_scratch_for_shape(&[batch_dim, *output_dimension], DataType::BF16)+ .map_err(LinearEncodeError::Backend)?;+ let mut column = 0;+ for matrix in matrices {+ matrix.encode_columns(+ input.as_ref(),+ batch_dim,+ &mut output,+ column,+ *output_dimension,+ command_buffer,+ )?;+ column += matrix.output_dim();+ }+ Ok(output)+ },+ }+ }+}diff --git a/crates/uzu-engine/src/encodable_block/linear/untied_readout.rs b/crates/uzu-engine/src/encodable_block/linear/untied_readout.rsindex ff90d7cf7..cb14132a2 100644--- a/crates/uzu-engine/src/encodable_block/linear/untied_readout.rs+++ b/crates/uzu-engine/src/encodable_block/linear/untied_readout.rs@@ -6,7 +6,7 @@ use crate::{},config::weight_matrix::{AnyWeightMatrixSpec,- hybrid_spec::{HadamardSpec, HybridSpec, IncoherenceProcessingMode},+ hybrid_spec::{AnyIncoherenceProcessorSpec, HadamardSpec, HybridSpec, IncoherenceProcessingMode},},data_type::DataType,encodable_block::linear::{@@ -32,11 +32,11 @@ impl<B: Backend> UntiedReadout<B> {let AnyWeightMatrixSpec::HybridSpec(HybridSpec {quantization_spec,incoherence_spec:- Some(HadamardSpec {+ Some(AnyIncoherenceProcessorSpec::HadamardSpec(HadamardSpec {block_size: HADAMARD_TRANSFORM_BLOCK_SIZE,processing_mode: IncoherenceProcessingMode::Input,..- }),+ })),..}) = specelse {diff --git a/crates/uzu-engine/src/encodable_block/weaver.rs b/crates/uzu-engine/src/encodable_block/weaver.rsindex 8c3ad5391..12788c80b 100644--- a/crates/uzu-engine/src/encodable_block/weaver.rs+++ b/crates/uzu-engine/src/encodable_block/weaver.rs@@ -20,7 +20,7 @@ use crate::{encodable_block::{confidence_head::{ConfidenceHead, ConfidenceHeadError, ConfidenceHeadStep},embedding::{Embedding, EmbeddingError},- linear::{Linear, LinearBlockError, LinearEncodeError, RHTLinearWrapper},+ linear::{Linear, LinearBlockError, LinearEncodeError, TransformedLinear},mixer::attention::{KVCache, KVCacheView, rope::PrecalculatedRoPE},mlp::{MlpBlockNewError, MlpEncodeError},normalization::{Normalization, NormalizationNewError, PostLayerScalar, ShortcutMode},@@ -295,15 +295,14 @@ impl<B: Backend> Weaver<B> {// NOTE: We assume the query projection's output Hadamard signs match the tied// readout's input signs, so its output can stay in the readout's rotated basis.Box::new(- RHTLinearWrapper::new_with_rotated_output(+ TransformedLinear::new_with_rotated_output(config.model_dim,config.target_model_dim,DATA_TYPE,&query_projection_tree,context,)- .await- .map_err(LinearBlockError::from)?,+ .await?,)} else {<dyn Linear<B>>::new(diff --git a/crates/uzu-engine/src/encodable_block/weight_matrix.rs b/crates/uzu-engine/src/encodable_block/weight_matrix.rsindex 9bbe22fd5..b9e343ba0 100644--- a/crates/uzu-engine/src/encodable_block/weight_matrix.rs+++ b/crates/uzu-engine/src/encodable_block/weight_matrix.rs@@ -4,8 +4,12 @@ use thiserror::Error;use crate::{backends::common::{Backend,- gpu_types::{quantization::QuantizationMode, quantization_method::QuantizationMethod},- kernel::matmul::{MatmulB, QuantParams, QuantParamsLayout, QuantizedB, QuantizedCorrection, WeightsLayout},+ gpu_types::{+ quantization::QuantizationMode, quantization_method::QuantizationMethod, trellis::TrellisCodebook,+ },+ kernel::matmul::{+ MatmulB, QuantParams, QuantParamsLayout, QuantizedB, QuantizedCorrection, TrellisFormat, WeightsLayout,+ },},config::weight_matrix::{AnyWeightMatrixSpec, Layout},data_type::DataType,@@ -20,79 +24,27 @@ pub enum WeightMatrixError<B: Backend> {UnsupportedConfiguration(String),}-#[derive(Clone, Copy)]-pub struct QuantizationInfo {- pub mode: QuantizationMode,- pub method: QuantizationMethod,- pub group_size: u32,-}--pub struct ParsedWeightSpec {- pub layout: Layout,- pub quantization: Option<QuantizationInfo>,-}--pub fn parse_spec<B: Backend>(spec: &AnyWeightMatrixSpec) -> Result<ParsedWeightSpec, WeightMatrixError<B>> {- let (layout, quantized) = match spec {- AnyWeightMatrixSpec::FullPrecisionSpec(spec) => (spec.layout.clone(), None),- AnyWeightMatrixSpec::MLXSpec(spec) => {- (spec.layout.clone(), Some((spec.bits, spec.group_size, QuantizationMethod::ScaleBias)))- },- AnyWeightMatrixSpec::IntSpec(spec) => (- spec.layout.clone(),- Some((- spec.bits,- spec.group_size,- if spec.is_symmetric {- QuantizationMethod::ScaleSymmetric- } else {- QuantizationMethod::ScaleZeroPoint- },- )),- ),- spec => return Err(WeightMatrixError::UnsupportedConfiguration(format!("{spec:?}"))),- };- let quantization = match quantized {- None => None,- Some((bits, group_size, method)) => {- let mode = match bits {- 2 => QuantizationMode::U2,- 4 => QuantizationMode::U4,- 8 => QuantizationMode::U8,- _ => {- return Err(WeightMatrixError::UnsupportedConfiguration(format!(- "{method} bits={bits}, group_size={group_size}"- )));- },- };- if group_size == 0 {- return Err(WeightMatrixError::UnsupportedConfiguration("group size must be non-zero".into()));- }- Some(QuantizationInfo {- mode,- method,- group_size,- })- },- };- Ok(ParsedWeightSpec {- layout,- quantization,- })-}--struct Quantized<B: Backend> {- scales: B::GlobalGpuBuffer,- correction: QuantizedCorrection<B::GlobalGpuBuffer>,- params: QuantParams,- info: QuantizationInfo,- signed_codes: bool,- weights_layout: WeightsLayout<B>,-}-pub struct WeightMatrix<B: Backend> {values: B::GlobalGpuBuffer,- quantized: Option<Quantized<B>>,+ encoding: WeightEncoding<B>,+}++enum WeightEncoding<B: Backend> {+ Dense,+ Quantized {+ scales: B::GlobalGpuBuffer,+ correction: QuantizedCorrection<B::GlobalGpuBuffer>,+ params: QuantParams,+ mode: QuantizationMode,+ group_size: u32,+ signed_codes: bool,+ weights_layout: WeightsLayout<B>,+ },+ Trellis {+ row_scales: B::GlobalGpuBuffer,+ codebook: TrellisCodebook,+ format: TrellisFormat,+ },}impl<B: Backend> WeightMatrix<B> {@@ -104,69 +56,105 @@ impl<B: Backend> WeightMatrix<B> {required_layout: Layout,tree: &ParameterTree<'_, B>,) -> Result<Self, WeightMatrixError<B>> {- let ParsedWeightSpec {- layout,- quantization: quantization_info,- } = parse_spec(&spec)?;+ let (layout, quantized) = match spec {+ AnyWeightMatrixSpec::FullPrecisionSpec(spec) => (spec.layout, None),+ AnyWeightMatrixSpec::MLXSpec(spec) => {+ (spec.layout, Some((spec.bits, spec.group_size, QuantizationMethod::ScaleBias)))+ },+ AnyWeightMatrixSpec::IntSpec(spec) => (+ spec.layout,+ Some((+ spec.bits,+ spec.group_size,+ if spec.is_symmetric {+ QuantizationMethod::ScaleSymmetric+ } else {+ QuantizationMethod::ScaleZeroPoint+ },+ )),+ ),+ AnyWeightMatrixSpec::QtipGaussianSpec(spec) => {+ if spec.layout != Layout::OutputInput || required_layout != Layout::OutputInput {+ return Err(WeightMatrixError::UnsupportedConfiguration(format!(+ "Trellis requires OutputInput layout, got stored={:?}, requested={required_layout:?}",+ spec.layout+ )));+ }+ let format = TrellisFormat {+ vector_width: spec.vector_width,+ transition_bits: spec.transition_bits,+ restart_columns: (spec.restart_columns != 0).then_some(spec.restart_columns),+ };+ let code_shape = [output_dim, format.code_row_bytes(input_dim)];+ let values = tree.read_buffer("codes", &code_shape, DataType::U8).await?;+ let row_scales = tree.read_buffer("scales", &[output_dim], DataType::F32).await?;+ return Ok(Self {+ values,+ encoding: WeightEncoding::Trellis {+ row_scales,+ codebook: spec.codebook,+ format,+ },+ });+ },+ spec => return Err(WeightMatrixError::UnsupportedConfiguration(format!("{spec:?}"))),+ };if layout != required_layout {return Err(WeightMatrixError::UnsupportedConfiguration(format!("expected {required_layout:?} weight layout, got {layout:?}")));}- let (rows, columns) = physical_shape(&layout, output_dim, input_dim);+ let (rows, columns) = match layout {+ Layout::OutputInput => (output_dim, input_dim),+ Layout::InputOutput => (input_dim, output_dim),+ };- let Some(info) = quantization_info else {+ let Some((bits, group_size, method)) = quantized else {let values = tree.read_buffer("weights", &[rows, columns], data_type).await?;return Ok(Self {values,- quantized: None,+ encoding: WeightEncoding::Dense,});};+ let mode = QuantizationMode::from_unsigned_bits(bits).ok_or_else(|| {+ WeightMatrixError::UnsupportedConfiguration(format!("{method} bits={bits}, group_size={group_size}"))+ })?;// Parameters swap the weight axes once K is grouped: output-input stores [G, N], input-output stores [N, G].let params_layout = match layout {Layout::OutputInput => QuantParamsLayout::GroupOutput,Layout::InputOutput => QuantParamsLayout::OutputGroup,};- let group_size = info.group_size;- let packing_divisor = info.mode.packing_divisor();- let storage_data_type = info.mode.storage_type();+ let packing_divisor = mode.packing_divisor();if !columns.is_multiple_of(packing_divisor) {return Err(WeightMatrixError::UnsupportedConfiguration(format!("stored columns {columns} are not divisible by packing divisor {packing_divisor}")));}- let groups = columns.div_ceil(group_size);-- let values = tree.read_buffer("weights", &[rows, columns / packing_divisor], storage_data_type).await?;- let params = QuantParams::new(params_layout, rows, groups);- let load_plane = async |name: &str,- shape: [u32; 2],- storage_type: DataType|- -> Result<B::GlobalGpuBuffer, WeightMatrixError<B>> {- Ok(tree.read_buffer(name, &shape, storage_type).await?)- };- let scales = load_plane("scales", params.scale_shape(), data_type).await?;- let correction = match info.method {+ let values = tree.read_buffer("weights", &[rows, columns / packing_divisor], mode.storage_type()).await?;+ let params = QuantParams::new(params_layout, rows, columns.div_ceil(group_size));+ let scales = tree.read_buffer("scales", ¶ms.scale_shape(), data_type).await?;+ let correction = match method {QuantizationMethod::ScaleBias => {- QuantizedCorrection::Biases(load_plane("biases", params.scale_shape(), data_type).await?)+ QuantizedCorrection::Biases(tree.read_buffer("biases", ¶ms.scale_shape(), data_type).await?)},QuantizationMethod::ScaleZeroPoint => QuantizedCorrection::ZeroPoints(- load_plane("zero_points", params.zero_point_shape(info.mode), info.mode.storage_type()).await?,+ tree.read_buffer("zero_points", ¶ms.zero_point_shape(mode), mode.storage_type()).await?,),QuantizationMethod::ScaleSymmetric => QuantizedCorrection::Symmetric,};Ok(Self {values,- quantized: Some(Quantized {+ encoding: WeightEncoding::Quantized {scales,correction,params,- info,+ mode,+ group_size,signed_codes: false,weights_layout: Default::default(),- }),+ },})}@@ -174,64 +162,70 @@ impl<B: Backend> WeightMatrix<B> {&self.values}- pub fn quantization(&self) -> Option<QuantizationInfo> {- self.quantized.as_ref().map(|quantized| quantized.info)- }-pub fn scales(&self) -> Option<&B::GlobalGpuBuffer> {- self.quantized.as_ref().map(|quantized| &quantized.scales)+ self.matmul_b().quantized().map(|quantized| quantized.scales)}pub fn zero_points(&self) -> Option<&B::GlobalGpuBuffer> {- self.quantized.as_ref()?.correction.zero_points()+ self.matmul_b().quantized()?.zero_points()}pub fn biases(&self) -> Option<&B::GlobalGpuBuffer> {- self.quantized.as_ref()?.correction.biases()+ self.matmul_b().quantized()?.biases()}pub fn matmul_b(&self) -> MatmulB<&B::GlobalGpuBuffer> {- let Some(quantized) = self.quantized.as_ref() else {- return MatmulB::FullPrecision {+ match &self.encoding {+ WeightEncoding::Dense => MatmulB::FullPrecision {b: &self.values,- };- };- let mode = quantized.info.mode;- let group_size = quantized.info.group_size;- let signed_codes = quantized.signed_codes;- MatmulB::Quantized(QuantizedB {- codes: &self.values,- scales: &quantized.scales,- correction: quantized.correction.as_ref(),- params: quantized.params,- mode,- group_size,- signed_codes,- weights_layout: quantized.weights_layout,- })+ },+ WeightEncoding::Quantized {+ scales,+ correction,+ params,+ mode,+ group_size,+ signed_codes,+ weights_layout,+ } => MatmulB::Quantized(QuantizedB {+ codes: &self.values,+ scales,+ correction: correction.as_ref(),+ params: *params,+ mode: *mode,+ group_size: *group_size,+ signed_codes: *signed_codes,+ weights_layout: *weights_layout,+ }),+ WeightEncoding::Trellis {+ row_scales,+ codebook,+ format,+ } => MatmulB::Trellis {+ codes: &self.values,+ row_scales,+ codebook: *codebook,+ format: *format,+ },+ }}pub fn optimize_weights_layout<E>(&mut self,optimize: impl FnOnce(&mut B::GlobalGpuBuffer) -> Result<(WeightsLayout<B>, bool), E>,) -> Result<(), E> {- let Some(quantized) =- self.quantized.as_mut().filter(|quantized| quantized.weights_layout == WeightsLayout::<B>::default())+ let WeightEncoding::Quantized {+ weights_layout,+ signed_codes,+ ..+ } = &mut self.encodingelse {return Ok(());};- (quantized.weights_layout, quantized.signed_codes) = optimize(&mut self.values)?;+ if *weights_layout != WeightsLayout::<B>::default() {+ return Ok(());+ }+ (*weights_layout, *signed_codes) = optimize(&mut self.values)?;Ok(())}}--fn physical_shape(- layout: &Layout,- output_dim: u32,- input_dim: u32,-) -> (u32, u32) {- match layout {- Layout::OutputInput => (output_dim, input_dim),- Layout::InputOutput => (input_dim, output_dim),- }-}diff --git a/crates/uzu-engine/src/utils/strict_serde.rs b/crates/uzu-engine/src/utils/strict_serde.rsindex 969bf246d..dd0217a5e 100644--- a/crates/uzu-engine/src/utils/strict_serde.rs+++ b/crates/uzu-engine/src/utils/strict_serde.rs@@ -29,8 +29,10 @@ impl_strict!(impl<'de, T: DeserializeStrict<'de>> DeserializeStrict<'de> for Box<T> {}impl<'de, T: DeserializeStrict<'de>> DeserializeStrict<'de> for Box<[T]> {}impl<'de, T: DeserializeStrict<'de>> DeserializeStrict<'de> for Option<T> {}+impl<'de, T: DeserializeStrict<'de>, const N: usize> DeserializeStrict<'de> for [T; N] where [T; N]: Deserialize<'de> {}impl<'de, A: DeserializeStrict<'de>, B: DeserializeStrict<'de>> DeserializeStrict<'de> for (A, B) {}impl<'de, const V: bool> DeserializeStrict<'de> for MustBeBool<V> {}+impl<'de, const V: u64> DeserializeStrict<'de> for monostate::MustBeU64<V> {}impl<'de, V: ConstStr> DeserializeStrict<'de> for MustBeStr<V> {}pub fn required<'de, D: Deserializer<'de>, T: DeserializeStrict<'de>>(deserializer: D) -> Result<T, D::Error> {diff --git a/crates/uzu-engine/unit/backends/common/kernel/embedding/input_embedding_lookup_test.rs b/crates/uzu-engine/unit/backends/common/kernel/embedding/input_embedding_lookup_test.rsindex 646c1c559..15d932644 100644--- a/crates/uzu-engine/unit/backends/common/kernel/embedding/input_embedding_lookup_test.rs+++ b/crates/uzu-engine/unit/backends/common/kernel/embedding/input_embedding_lookup_test.rs@@ -158,6 +158,7 @@ fn check<T: DataTypeRepr + Float + Display>(#[rstest]#[test_attr(uzu_test)]#[case::dense(Dense, None, false)]+#[case::dense_hadamard(Dense, None, true)]#[case::u4_bias(Quantized, Some((U4, ScaleBias, 32)), false)]#[case::u4_zero_point_odd_group(Quantized, Some((U4, ScaleZeroPoint, 48)), false)]#[case::u4_symmetric(Quantized, Some((U4, ScaleSymmetric, 32)), false)]@@ -178,6 +179,7 @@ fn input_embedding_lookup_bf16(#[rstest]#[test_attr(uzu_test)]#[case::dense(Dense, None, false)]+#[case::dense_hadamard(Dense, None, true)]#[case::u4_bias(Quantized, Some((U4, ScaleBias, 32)), false)]fn input_embedding_lookup_f32(#[case] table_kind: EmbeddingTableKind,diff --git a/crates/uzu-engine/unit/backends/common/kernel/trellis_test.rs b/crates/uzu-engine/unit/backends/common/kernel/trellis_test.rsindex 19ffc199a..dbb2a7c63 100644--- a/crates/uzu-engine/unit/backends/common/kernel/trellis_test.rs+++ b/crates/uzu-engine/unit/backends/common/kernel/trellis_test.rs@@ -26,9 +26,9 @@ fn random_transform_data(rng: &mut SmallRng,columns: u32,batch: u32,-) -> (Vec<f32>, Vec<f32>, Vec<bf16>) {+) -> (Vec<i32>, Vec<f32>, Vec<bf16>) {let mixing_dimension = mixing_dimension(columns);- let rht_factors = (0..columns).map(|_| [1.0, -1.0][rng.random_range(0..2)]).collect();+ let rht_factors = (0..columns).map(|_| [1, -1][rng.random_range(0..2)]).collect();let mixing = (0..mixing_dimension * mixing_dimension).map(|_| rng.random_range(-MIXING_ENTRY_BOUND..MIXING_ENTRY_BOUND)).collect();@@ -41,7 +41,7 @@ fn random_transform_data(fn run<B: Backend>(columns: u32,batch: u32,- rht_factors: &[f32],+ rht_factors: &[i32],mixing: &[f32],input: &[bf16],) -> (Vec<i8>, Vec<f32>, Vec<f32>) {@@ -51,7 +51,7 @@ fn run<B: Backend>(let mut command_buffer = context.create_command_buffer(None, None).expect("command buffer");// kept alive until the command buffer has run: the CPU backend reads them at submit timelet input = create_buffer_with_data::<B, bf16>(context.as_ref(), input);- let rht_factors = create_buffer_with_data::<B, f32>(context.as_ref(), rht_factors);+ let rht_factors = create_buffer_with_data::<B, i32>(context.as_ref(), rht_factors);let mixing = create_buffer_with_data::<B, f32>(context.as_ref(), mixing);let mut activations = create_buffer::<B, i8>(context.as_ref(), (batch * columns) as usize);let mut column_group_sums = create_buffer::<B, f32>(context.as_ref(), COLUMN_GROUP_COUNT as usize * batch as usize);diff --git a/crates/uzu-engine/unit/backends/metal/kernel/matmul/quant_dispatch_test.rs b/crates/uzu-engine/unit/backends/metal/kernel/matmul/quant_dispatch_test.rsindex f56aae1f8..6dd4eb23a 100644--- a/crates/uzu-engine/unit/backends/metal/kernel/matmul/quant_dispatch_test.rs+++ b/crates/uzu-engine/unit/backends/metal/kernel/matmul/quant_dispatch_test.rs@@ -231,6 +231,7 @@ fn parity_bf16_8bit_splitk(#[case::m1_gs64_4bit_mlx(1, 256, 64, 64, 4, QuantizationMethod::ScaleBias)]#[case::m1_gs32_4bit_zp(1, 256, 64, 32, 4, QuantizationMethod::ScaleZeroPoint)]#[case::m1_gs64_8bit_sym(1, 256, 64, 64, 8, QuantizationMethod::ScaleSymmetric)]+#[case::w4_symmetric_g64(1, 256, 64, 64, 4, QuantizationMethod::ScaleSymmetric)]#[case::m2_gs32_4bit_mlx(2, 256, 64, 32, 4, QuantizationMethod::ScaleBias)]#[case::m4_gs32_4bit_zp(4, 256, 64, 32, 4, QuantizationMethod::ScaleZeroPoint)]#[case::m8_gs32_4bit_zp(8, 256, 64, 32, 4, QuantizationMethod::ScaleZeroPoint)]@@ -462,6 +463,7 @@ fn mxu_quant_parity_bf16(#[rstest]#[test_attr(uzu_test)]#[case::sym_w8_gs64(16u32, 256u32, 128u32, 64u32, 8u32, QuantizationMethod::ScaleSymmetric)]+#[case::w4_symmetric_g64(16u32, 256u32, 128u32, 64u32, 4u32, QuantizationMethod::ScaleSymmetric)]#[case::bias_w4_gs32(16u32, 256u32, 128u32, 32u32, 4u32, QuantizationMethod::ScaleBias)]#[case::zp_w4_gs32(16u32, 256u32, 128u32, 32u32, 4u32, QuantizationMethod::ScaleZeroPoint)]#[case::m1_bias_w4_gs64(1u32, 256u32, 128u32, 64u32, 4u32, QuantizationMethod::ScaleBias)]diff --git a/crates/uzu-engine/unit/backends/metal/kernel/matmul/trellis_gemm_test.rs b/crates/uzu-engine/unit/backends/metal/kernel/matmul/trellis_gemm_test.rsindex a5f2a78d4..3a9b67a6f 100644--- a/crates/uzu-engine/unit/backends/metal/kernel/matmul/trellis_gemm_test.rs+++ b/crates/uzu-engine/unit/backends/metal/kernel/matmul/trellis_gemm_test.rs@@ -7,6 +7,7 @@ use crate::{backends::{common::{Backend, Context, Kernels,+ gpu_types::trellis::TrellisCodebook,kernel::matmul::{MatmulA, MatmulArguments, MatmulB, MatmulDOps, MatmulKernel, MatmulOutput, MatmulShape, TrellisFormat,},@@ -93,7 +94,10 @@ fn decode_level(type MetalBuffer = <Metal as Backend>::GlobalGpuBuffer;type MetalMatmul = <<Metal as Backend>::Kernels as Kernels>::MatmulKernel;-const CODEBOOK: [f32; 5] = [0.0123, 0.3, -0.25, 0.125, -0.0625];+const CODEBOOK: TrellisCodebook = TrellisCodebook {+ scale: 0.0123,+ offsets: [0.3, -0.25, 0.125, -0.0625],+};const PADDING: usize = 24;const SENTINEL: u16 = 0x7F7F;const RELATIVE_TOLERANCE: f32 = 1e-2;@@ -154,7 +158,6 @@ fn run_projection(let activation_scales = create_buffer_with_data::<Metal, f32>(context, &activation_scales_host);let codes = create_buffer_with_data::<Metal, u8>(context, &stored);let row_scales_buffer = create_buffer_with_data::<Metal, f32>(context, &row_scales);- let codebook = create_buffer_with_data::<Metal, f32>(context, &CODEBOOK);let mut output = create_buffer_with_data::<Metal, u16>(context, &vec![SENTINEL; m * (n + PADDING)]);let arguments = MatmulArguments {a: MatmulA::Trellis {@@ -165,7 +168,7 @@ fn run_projection(b: MatmulB::Trellis {codes: &codes,row_scales: &row_scales_buffer,- codebook: &codebook,+ codebook: CODEBOOK,format,},b_leading_dimension: None,@@ -215,9 +218,10 @@ fn run_projection(let level_dot: i32 = levels.iter().zip(row_values).map(|(&level, &value)| level * i32::from(value)).sum();let sums = &group_sums_host[token * 4..token * 4 + 4];// A non-dyadic offset exposes rounding differences in the GPU dot.- let offsets_dot =- (((sums[0] * CODEBOOK[1]) + sums[1] * CODEBOOK[2]) + sums[2] * CODEBOOK[3]) + sums[3] * CODEBOOK[4];- let dot = (level_dot as f32).mul_add(CODEBOOK[0], offsets_dot);+ let offsets_dot = (((sums[0] * CODEBOOK.offsets[0]) + sums[1] * CODEBOOK.offsets[1])+ + sums[2] * CODEBOOK.offsets[2])+ + sums[3] * CODEBOOK.offsets[3];+ let dot = (level_dot as f32).mul_add(CODEBOOK.scale, offsets_dot);let want = bf16::from_f32(dot * row_scales[row] * activation_scales_host[token]).to_f32();let got = bf16::from_bits(got).to_f32();assert!(