Skip to content

armgit / uzu

Public Imported from GitHub
0

A high-performance inference engine for AI models

Embedding unification and support trellis D4S4 embedding (#876)

CCYeh4d880766f5a4
diff --git a/crates/uzu-engine/src/backends/common/gpu_types/d4s4.rs b/crates/uzu-engine/src/backends/common/gpu_types/d4s4.rs
new file mode 100644
index 000000000..0903bcbb9
--- /dev/null
+++ b/crates/uzu-engine/src/backends/common/gpu_types/d4s4.rs
@@ -0,0 +1,7 @@
+//! Fixed layout of the D4S4 embedding format (lalamo's `LatticeSpec` with kind `d4`).
+
+pub const VALUES_PER_CODE: u32 = 4;
+pub const CODEBOOK_SIZE: u32 = 256;
+pub const COLUMNS_PER_LADDER_SCALE: u32 = 64;
+pub const COLUMNS_PER_LADDER_INDEX_BYTE: u32 = 2 * COLUMNS_PER_LADDER_SCALE;
+pub const LADDER_SIZE: u32 = 16;
diff --git a/crates/uzu-engine/src/backends/common/gpu_types/embedding.rs b/crates/uzu-engine/src/backends/common/gpu_types/embedding.rs
new file mode 100644
index 000000000..71bfe4e15
--- /dev/null
+++ b/crates/uzu-engine/src/backends/common/gpu_types/embedding.rs
@@ -0,0 +1,8 @@
+/// Storage format used by the input embedding lookup kernel.
+#[repr(C)]
+#[derive(Debug, Copy, Clone, PartialEq, Eq, Hash)]
+pub enum EmbeddingTableKind {
+ Dense = 0,
+ Quantized = 1,
+ D4S4 = 2,
+}
diff --git a/crates/uzu-engine/src/backends/common/gpu_types/mod.rs b/crates/uzu-engine/src/backends/common/gpu_types/mod.rs
index 5c1089585..a8184e988 100644
--- a/crates/uzu-engine/src/backends/common/gpu_types/mod.rs
+++ b/crates/uzu-engine/src/backends/common/gpu_types/mod.rs
@@ -6,6 +6,8 @@
pub mod activation_transform;
pub mod activation_type;
pub mod attention;
+pub mod d4s4;
+pub mod embedding;
pub mod gated_act_mul;
pub mod gemm;
pub mod hadamard_order;
@@ -20,6 +22,7 @@ pub mod weaver;
pub use activation_transform::*;
pub use activation_type::*;
pub use attention::*;
+pub use embedding::*;
pub use gated_act_mul::*;
pub use hadamard_order::*;
pub use kv_cache_update::*;
diff --git a/crates/uzu-engine/src/backends/cpu/kernel/embedding/full_precision_embedding.rs b/crates/uzu-engine/src/backends/cpu/kernel/embedding/full_precision_embedding.rs
deleted file mode 100644
index 8b1da99e1..000000000
--- a/crates/uzu-engine/src/backends/cpu/kernel/embedding/full_precision_embedding.rs
+++ /dev/null
@@ -1,32 +0,0 @@
-use half::{bf16, f16};
-use num_traits::Float;
-use uzu_engine_macros::kernel;
-
-use crate::array::ArrayElement;
-
-#[kernel(FullPrecisionEmbeddingLookup)]
-#[variants(T, f32, f16, bf16)]
-pub fn full_precision_embedding_lookup<T: ArrayElement + Float>(
- token_ids: *const u32,
- weights: *const T,
- output: *mut T,
- batch_size: u32,
- vocab_size: u32,
- model_dim: u32,
- input_scale: f32,
-) {
- for batch_idx in 0..batch_size {
- let token_id = unsafe { *token_ids.add(batch_idx as usize) };
- for dim_idx in 0..model_dim {
- let output_idx = (batch_idx * model_dim + dim_idx) as usize;
- if token_id >= vocab_size {
- unsafe { *output.add(output_idx) = T::zero() };
- } else {
- unsafe {
- let weights_idx = token_id as usize * model_dim as usize + dim_idx as usize;
- *output.add(output_idx) = *weights.add(weights_idx) * T::from(input_scale).unwrap();
- };
- }
- }
- }
-}
diff --git a/crates/uzu-engine/src/backends/cpu/kernel/embedding/input_embedding_lookup.rs b/crates/uzu-engine/src/backends/cpu/kernel/embedding/input_embedding_lookup.rs
new file mode 100644
index 000000000..73a32ca4f
--- /dev/null
+++ b/crates/uzu-engine/src/backends/cpu/kernel/embedding/input_embedding_lookup.rs
@@ -0,0 +1,151 @@
+use half::{bf16, f16};
+use num_traits::Float;
+use uzu_engine_macros::kernel;
+
+use crate::{
+ array::ArrayElement,
+ backends::{
+ common::gpu_types::{
+ EmbeddingTableKind, HADAMARD_TRANSFORM_BLOCK_SIZE, QuantizationMethod, QuantizationMode, d4s4,
+ },
+ cpu::kernel::activation_transform::hadamard_transform,
+ },
+};
+
+#[kernel(InputEmbeddingLookup)]
+#[variants(T, f32, bf16)]
+pub fn input_embedding_lookup<T: ArrayElement + Float>(
+ token_ids: *const u32,
+ values: *const u8,
+ #[optional(table_kind != EmbeddingTableKind::Dense)] scales: Option<*const T>,
+ #[optional(quantization_method == QuantizationMethod::ScaleZeroPoint)] zero_points: Option<*const u8>,
+ #[optional(quantization_method == QuantizationMethod::ScaleBias)] biases: Option<*const T>,
+ #[optional(use_hadamard)] hadamard_factors: Option<*const i32>,
+ #[optional(table_kind == EmbeddingTableKind::D4S4)] ladder_indices: Option<*const u8>,
+ #[optional(table_kind == EmbeddingTableKind::D4S4)] ladder: Option<*const f16>,
+ #[optional(table_kind == EmbeddingTableKind::D4S4)] codebook: Option<*const i8>,
+ output: *mut T,
+ batch_size: u32,
+ vocab_size: u32,
+ model_dim: u32,
+ input_scale: f32,
+ #[specialize] table_kind: EmbeddingTableKind,
+ #[specialize]
+ #[optional(table_kind == EmbeddingTableKind::Quantized)]
+ group_size: Option<u32>,
+ #[specialize]
+ #[optional(table_kind == EmbeddingTableKind::Quantized)]
+ quantization_mode: Option<QuantizationMode>,
+ #[specialize]
+ #[optional(table_kind == EmbeddingTableKind::Quantized)]
+ quantization_method: Option<QuantizationMethod>,
+ #[specialize] use_hadamard: bool,
+) {
+ let factors = if use_hadamard {
+ hadamard_factors
+ } else {
+ None
+ };
+ let dim = model_dim as usize;
+ let quantization =
+ if let (Some(group_size), Some(mode), Some(method)) = (group_size, quantization_mode, quantization_method) {
+ let num_groups = dim.div_ceil(group_size as usize);
+ let weights_stride = dim / mode.packing_divisor() as usize;
+ Some((group_size, mode, method, num_groups, weights_stride))
+ } else {
+ None
+ };
+ let dense_scale = T::from(input_scale).unwrap();
+ for batch in 0..batch_size as usize {
+ let row = unsafe { std::slice::from_raw_parts_mut(output.add(batch * dim), dim) };
+ let token = unsafe { *token_ids.add(batch) };
+ if token >= vocab_size {
+ row.fill(T::zero());
+ continue;
+ }
+ let token = token as usize;
+ let load = |column: usize| -> f32 {
+ match table_kind {
+ EmbeddingTableKind::Dense => unsafe {
+ (*(values as *const T).add(token * dim + column) * dense_scale).to_f32().unwrap()
+ },
+ EmbeddingTableKind::Quantized => {
+ let (group_size, quantization_mode, quantization_method, num_groups, weights_stride) =
+ quantization.expect("quantization settings");
+ let scales = scales.expect("quantized lookup requires scales");
+ let group = column / group_size as usize;
+ let index = token * num_groups + group;
+ let scale = unsafe { (*scales.add(index)).to_f32().unwrap() };
+ let offset = token * weights_stride;
+ let code = match quantization_mode {
+ QuantizationMode::U4 => read_u4(values, 2 * offset + column) as f32,
+ QuantizationMode::I8 => (unsafe { *(values as *const i8).add(offset + column) }) as f32,
+ QuantizationMode::U8 => (unsafe { *values.add(offset + column) }) as f32,
+ };
+ let bias = match quantization_method {
+ QuantizationMethod::ScaleBias => unsafe {
+ (*biases.expect("quantized lookup requires biases").add(index)).to_f32().unwrap()
+ },
+ QuantizationMethod::ScaleZeroPoint => {
+ let zero_points = zero_points.expect("quantized lookup requires zero points");
+ let zero_point = if quantization_mode == QuantizationMode::U4 {
+ read_u4(zero_points, 2 * token * num_groups.div_ceil(2) + group)
+ } else {
+ unsafe { *zero_points.add(index) }
+ };
+ -scale * zero_point as f32
+ },
+ QuantizationMethod::ScaleSymmetric => {
+ let midpoint = if quantization_mode == QuantizationMode::U4 {
+ 8.0
+ } else {
+ 128.0
+ };
+ -scale * midpoint
+ },
+ };
+ // Ordinary quantization rounds to T before the transform.
+ T::from((scale * code + bias) * input_scale).unwrap().to_f32().unwrap()
+ },
+ EmbeddingTableKind::D4S4 => {
+ let row_scales = scales.expect("D4S4 lookup requires row scales");
+ let ladder_indices = ladder_indices.expect("D4S4 lookup requires ladder indices");
+ let ladder = ladder.expect("D4S4 lookup requires a ladder");
+ let codebook = codebook.expect("D4S4 lookup requires a codebook");
+ let values_per_code = d4s4::VALUES_PER_CODE as usize;
+ let columns_per_scale = d4s4::COLUMNS_PER_LADDER_SCALE as usize;
+ let ladder_index =
+ read_u4(ladder_indices, token * (dim / columns_per_scale) + column / columns_per_scale);
+ let code =
+ unsafe { *values.add(token * (dim / values_per_code) + column / values_per_code) } as usize;
+ let point = unsafe { *codebook.add(values_per_code * code + column % values_per_code) };
+ let row_scale = unsafe { (*row_scales.add(token)).to_f32().unwrap() };
+ let step = unsafe { (*ladder.add(ladder_index as usize)).to_f32() };
+ row_scale * step * point as f32 * input_scale
+ },
+ }
+ };
+ if let Some(factors) = factors {
+ for block_start in (0..row.len()).step_by(HADAMARD_TRANSFORM_BLOCK_SIZE as usize) {
+ let mut block: [f32; HADAMARD_TRANSFORM_BLOCK_SIZE as usize] =
+ std::array::from_fn(|lane| load(block_start + lane));
+ hadamard_transform(&mut block);
+ for (lane, value) in block.into_iter().enumerate() {
+ row[block_start + lane] =
+ T::from(value * unsafe { *factors.add(block_start + lane) } as f32).unwrap();
+ }
+ }
+ } else {
+ for (column, value) in row.iter_mut().enumerate() {
+ *value = T::from(load(column)).unwrap();
+ }
+ }
+ }
+}
+
+fn read_u4(
+ values: *const u8,
+ nibble: usize,
+) -> u8 {
+ (unsafe { *values.add(nibble / 2) } >> (4 * (nibble % 2))) & 15
+}
diff --git a/crates/uzu-engine/src/backends/cpu/kernel/embedding/mod.rs b/crates/uzu-engine/src/backends/cpu/kernel/embedding/mod.rs
index 93f7cf1f0..6c296c960 100644
--- a/crates/uzu-engine/src/backends/cpu/kernel/embedding/mod.rs
+++ b/crates/uzu-engine/src/backends/cpu/kernel/embedding/mod.rs
@@ -1,2 +1 @@
-pub mod full_precision_embedding;
-pub mod quant_embedding;
+pub mod input_embedding_lookup;
diff --git a/crates/uzu-engine/src/backends/cpu/kernel/embedding/quant_embedding.rs b/crates/uzu-engine/src/backends/cpu/kernel/embedding/quant_embedding.rs
deleted file mode 100644
index 8a99ab825..000000000
--- a/crates/uzu-engine/src/backends/cpu/kernel/embedding/quant_embedding.rs
+++ /dev/null
@@ -1,131 +0,0 @@
-use half::{bf16, f16};
-use num_traits::Float;
-use uzu_engine_macros::kernel;
-
-use crate::{
- array::ArrayElement,
- backends::{
- common::gpu_types::{HADAMARD_TRANSFORM_BLOCK_SIZE, QuantizationMethod, QuantizationMode},
- cpu::kernel::activation_transform::hadamard_transform,
- },
- data_type::DataType,
-};
-
-#[kernel(QuantizedEmbeddingLookup)]
-#[variants(T, f32, f16, bf16)]
-pub fn quantized_embedding_lookup<T: ArrayElement + Float>(
- token_ids: *const u32,
- weights: *const u8,
- scales: *const T,
- #[optional(quantization_method == QuantizationMethod::ScaleZeroPoint)] zero_points: Option<*const u8>,
- #[optional(quantization_method == QuantizationMethod::ScaleBias)] biases: Option<*const T>,
- output: *mut T,
- #[optional(use_hadamard)] output_hadamard_factors: Option<*const i32>,
- batch_size: u32,
- vocab_size: u32,
- model_dim: u32,
- input_scale: f32,
- #[specialize] group_size: u32,
- #[specialize] quantization_mode: QuantizationMode,
- #[specialize] quantization_method: QuantizationMethod,
- #[specialize] use_hadamard: bool,
-) {
- assert_eq!(output_hadamard_factors.is_some(), use_hadamard);
- assert!(!use_hadamard || model_dim.is_multiple_of(HADAMARD_TRANSFORM_BLOCK_SIZE));
-
- let packing_divisor = quantization_mode.packing_divisor();
- let weights_stride = model_dim / packing_divisor;
- let num_groups = model_dim.div_ceil(group_size);
- let zero_points_stride = match quantization_mode {
- QuantizationMode::U4 => num_groups.div_ceil(2),
- QuantizationMode::I8 | QuantizationMode::U8 => num_groups,
- };
-
- unsafe {
- for batch_idx in 0..batch_size {
- let token_id = *token_ids.add(batch_idx as usize);
-
- for dim_idx in 0..model_dim {
- let out_idx = (batch_idx * model_dim + dim_idx) as usize;
-
- if token_id >= vocab_size {
- *output.add(out_idx) = T::zero();
- continue;
- }
-
- let group_idx = dim_idx / group_size;
- let scale = *scales.add((token_id * num_groups + group_idx) as usize);
-
- let quantized_value: i32 = match quantization_mode {
- QuantizationMode::U4 => {
- let byte_idx = (token_id * weights_stride + dim_idx / 2) as usize;
- let packed = *weights.add(byte_idx);
- if (dim_idx & 1) == 0 {
- (packed & 0x0F) as i32
- } else {
- ((packed >> 4) & 0x0F) as i32
- }
- },
- QuantizationMode::I8 => {
- let elem_idx = (token_id * weights_stride + dim_idx) as usize;
- let weights_i8 = weights as *const i8;
- *weights_i8.add(elem_idx) as i32
- },
- QuantizationMode::U8 => {
- let elem_idx = (token_id * weights_stride + dim_idx) as usize;
- *weights.add(elem_idx) as i32
- },
- };
-
- let bias = match quantization_method {
- QuantizationMethod::ScaleBias => biases
- .expect("ScaleBias quantized embedding requires biases")
- .add((token_id * num_groups + group_idx) as usize)
- .read()
- .to_f32()
- .unwrap(),
- QuantizationMethod::ScaleZeroPoint => {
- let zero_points = zero_points.expect("ScaleZeroPoint quantized embedding requires zero_points");
- let zero_point = match quantization_mode {
- QuantizationMode::U4 => {
- let byte_idx = (token_id * zero_points_stride + group_idx / 2) as usize;
- let packed = *zero_points.add(byte_idx);
- if (group_idx & 1) == 0 {
- packed & 0x0F
- } else {
- (packed >> 4) & 0x0F
- }
- },
- QuantizationMode::I8 | QuantizationMode::U8 => {
- *zero_points.add((token_id * zero_points_stride + group_idx) as usize)
- },
- };
- -scale.to_f32().unwrap() * zero_point as f32
- },
- QuantizationMethod::ScaleSymmetric => {
- let midpoint = 1 << (DataType::from(quantization_mode).size_in_bits() - 1);
- -scale.to_f32().unwrap() * midpoint as f32
- },
- };
-
- let out_f = scale.to_f32().unwrap() * quantized_value as f32 + bias;
- let out_f = out_f * input_scale;
- *output.add(out_idx) = T::from(out_f).unwrap();
- }
-
- // Output RHT like the Metal kernel: round to T, transform each block, then apply the factors
- if let Some(factors) = output_hadamard_factors {
- let row =
- std::slice::from_raw_parts_mut(output.add((batch_idx * model_dim) as usize), model_dim as usize);
- for block_start in (0..model_dim as usize).step_by(HADAMARD_TRANSFORM_BLOCK_SIZE as usize) {
- let mut block = std::array::from_fn(|lane| row[block_start + lane].to_f32().unwrap());
- hadamard_transform(&mut block);
- for (lane, value) in block.into_iter().enumerate() {
- let factor = *factors.add(block_start + lane) as f32;
- row[block_start + lane] = T::from(value * factor).unwrap();
- }
- }
- }
- }
- }
-}
diff --git a/crates/uzu-engine/src/backends/metal/kernel/common/packed.h b/crates/uzu-engine/src/backends/metal/kernel/common/packed.h
new file mode 100644
index 000000000..603294e72
--- /dev/null
+++ b/crates/uzu-engine/src/backends/metal/kernel/common/packed.h
@@ -0,0 +1,18 @@
+#pragma once
+
+#include <metal_stdlib>
+
+namespace uzu {
+
+template <uint BITS>
+inline uint read_packed(uchar packed, uint index) {
+ static_assert(BITS == 2 || BITS == 4, "Only 2-bit and 4-bit packed values are supported");
+ return (uint(packed) >> (BITS * (index % (8u / BITS)))) & ((1u << BITS) - 1u);
+}
+
+template <uint BITS>
+inline uint read_packed(const device uchar* packed, uint index) {
+ return read_packed<BITS>(packed[index / (8u / BITS)], index);
+}
+
+} // namespace uzu
diff --git a/crates/uzu-engine/src/backends/metal/kernel/embedding/full_precision_embedding.metal b/crates/uzu-engine/src/backends/metal/kernel/embedding/full_precision_embedding.metal
deleted file mode 100644
index 4baaf37e3..000000000
--- a/crates/uzu-engine/src/backends/metal/kernel/embedding/full_precision_embedding.metal
+++ /dev/null
@@ -1,29 +0,0 @@
-#include <metal_stdlib>
-#include "../common/dsl.h"
-
-#define BLOCK_SIZE 256
-
-template <typename T>
-VARIANTS(T, float, half, bfloat)
-PUBLIC KERNEL(FullPrecisionEmbeddingLookup) (
- const device uint32_t* token_ids, // [batch_size]
- const device T* weights, // [vocab_size, model_dim]
- device T* output, // [batch_size, model_dim]
- constant uint32_t& batch_size,
- constant uint32_t& vocab_size,
- constant uint32_t& model_dim,
- constant float& input_scale,
- uint dim_idx AXIS(model_dim, BLOCK_SIZE),
- uint batch_idx AXIS(batch_size, 1)
-) {
- const uint32_t token_id = token_ids[batch_idx];
- const uint output_idx = batch_idx * model_dim + dim_idx;
-
- if (token_id >= vocab_size) {
- output[output_idx] = T(0);
- return;
- }
-
- T value = weights[token_id * model_dim + dim_idx];
- output[output_idx] = value * T(input_scale);
-}
diff --git a/crates/uzu-engine/src/backends/metal/kernel/embedding/input_embedding_lookup.metal b/crates/uzu-engine/src/backends/metal/kernel/embedding/input_embedding_lookup.metal
new file mode 100644
index 000000000..74787568c
--- /dev/null
+++ b/crates/uzu-engine/src/backends/metal/kernel/embedding/input_embedding_lookup.metal
@@ -0,0 +1,94 @@
+#include <metal_stdlib>
+#include "../common/dsl.h"
+#include "../common/packed.h"
+#include "../generated/d4s4.h"
+#include "../generated/embedding.h"
+#include "../generated/quantization_method.h"
+#include "../hadamard_transform/hadamard_transform.h"
+#include "quantization.h"
+
+using namespace metal;
+using namespace uzu::embedding;
+using namespace uzu::quantization_method;
+using uzu::read_packed;
+
+template <typename T>
+VARIANTS(T, float, bfloat)
+PUBLIC KERNEL(InputEmbeddingLookup)(
+ const device uint* token_ids,
+ const device uchar* values,
+ const device T* scales OPTIONAL(table_kind != EmbeddingTableKind::Dense),
+ const device uchar* zero_points OPTIONAL(table_kind == EmbeddingTableKind::Quantized && quantization_method == QuantizationMethod::ScaleZeroPoint),
+ const device T* biases OPTIONAL(table_kind == EmbeddingTableKind::Quantized && quantization_method == QuantizationMethod::ScaleBias),
+ const device int* hadamard_factors OPTIONAL(use_hadamard),
+ const device uchar* ladder_indices OPTIONAL(table_kind == EmbeddingTableKind::D4S4),
+ const device half* ladder OPTIONAL(table_kind == EmbeddingTableKind::D4S4),
+ const device char4* codebook OPTIONAL(table_kind == EmbeddingTableKind::D4S4),
+ device T* output,
+ constant uint& batch_size,
+ constant uint& vocab_size,
+ constant uint& model_dim,
+ constant float& input_scale,
+ const EmbeddingTableKind table_kind SPECIALIZE,
+ const uint group_size SPECIALIZE_IF(table_kind == EmbeddingTableKind::Quantized),
+ const uzu::quantization::QuantizationMode quantization_mode SPECIALIZE_IF(table_kind == EmbeddingTableKind::Quantized),
+ const QuantizationMethod quantization_method SPECIALIZE_IF(table_kind == EmbeddingTableKind::Quantized),
+ const bool use_hadamard SPECIALIZE,
+ const uint dim_idx AXIS(model_dim, 256),
+ const uint batch_idx AXIS(batch_size, 1)
+) {
+ const uint output_idx = batch_idx * model_dim + dim_idx;
+ const uint token_id = token_ids[batch_idx];
+ if (token_id >= vocab_size) {
+ output[output_idx] = T(0);
+ return;
+ }
+
+ float loaded;
+ if (table_kind == EmbeddingTableKind::Dense) {
+ loaded = float(reinterpret_cast<const device T*>(values)[token_id * model_dim + dim_idx] * T(input_scale));
+ } else if (table_kind == EmbeddingTableKind::Quantized) {
+ const bool is_u4 = quantization_mode == uzu::quantization::QuantizationMode::U4;
+ const uint group_idx = dim_idx / group_size;
+ const uint num_groups = (model_dim + group_size - 1) / group_size;
+ const uint scale_idx = token_id * num_groups + group_idx;
+ const float scale = float(scales[scale_idx]);
+ const uint row = token_id * (is_u4 ? model_dim / 2 : model_dim);
+ float code;
+ if (is_u4) {
+ code = float(read_packed<4>(values, 2 * row + dim_idx));
+ } else if (quantization_mode == uzu::quantization::QuantizationMode::I8) {
+ code = float(reinterpret_cast<const device char*>(values)[row + dim_idx]);
+ } else {
+ code = float(values[row + dim_idx]);
+ }
+ float bias;
+ if (quantization_method == QuantizationMethod::ScaleBias) {
+ bias = float(biases[scale_idx]);
+ } else if (quantization_method == QuantizationMethod::ScaleZeroPoint) {
+ const uint zero_point = is_u4 ? read_packed<4>(zero_points, 2 * token_id * ((num_groups + 1) / 2) + group_idx)
+ : zero_points[scale_idx];
+ bias = -scale * float(zero_point);
+ } else {
+ bias = -scale * (is_u4 ? 8.0f : 128.0f);
+ }
+ loaded = float(T((scale * code + bias) * input_scale));
+ } else {
+ const uint ladder_index = read_packed<4>(
+ ladder_indices,
+ token_id * (model_dim / uzu::d4s4::COLUMNS_PER_LADDER_SCALE) + dim_idx / uzu::d4s4::COLUMNS_PER_LADDER_SCALE
+ );
+ const char4 point =
+ codebook[values[token_id * (model_dim / uzu::d4s4::VALUES_PER_CODE) + dim_idx / uzu::d4s4::VALUES_PER_CODE]];
+ loaded = float(scales[token_id]) * float(ladder[ladder_index]) *
+ float(point[dim_idx % uzu::d4s4::VALUES_PER_CODE]) * input_scale;
+ }
+ if (use_hadamard) {
+ loaded = simdgroup_output_random_hadamard_transform(
+ static_cast<ushort>(dim_idx % METAL_SIMD_SIZE),
+ loaded,
+ hadamard_factors[dim_idx]
+ );
+ }
+ output[output_idx] = T(loaded);
+}
diff --git a/crates/uzu-engine/src/backends/metal/kernel/embedding/quant_embedding.metal b/crates/uzu-engine/src/backends/metal/kernel/embedding/quant_embedding.metal
deleted file mode 100644
index c3998a8eb..000000000
--- a/crates/uzu-engine/src/backends/metal/kernel/embedding/quant_embedding.metal
+++ /dev/null
@@ -1,100 +0,0 @@
-#include <metal_stdlib>
-#include "../common/dsl.h"
-#include "../generated/quantization_method.h"
-#include "../hadamard_transform/hadamard_transform.h"
-#include "quantization.h"
-
-using namespace uzu::quantization_method;
-using namespace uzu::quantization;
-
-template <typename T>
-VARIANTS(T, float, half, bfloat)
-PUBLIC KERNEL(QuantizedEmbeddingLookup) (
- const device uint32_t* token_ids, // [batch_size]
- const device uint8_t* weights, // [vocab_size, model_dim/packing_divisor] packed
- const device T* scales, // [vocab_size, num_groups]
- const device uint8_t* zero_points OPTIONAL(quantization_method == QuantizationMethod::ScaleZeroPoint),
- const device T* biases OPTIONAL(quantization_method == QuantizationMethod::ScaleBias),
- device T* output, // [batch_size, model_dim]
- const device int32_t* output_hadamard_factors OPTIONAL(use_hadamard),
- constant uint32_t& batch_size,
- constant uint32_t& vocab_size,
- constant uint32_t& model_dim,
- constant float& input_scale,
- const uint32_t group_size SPECIALIZE,
- const QuantizationMode quantization_mode SPECIALIZE,
- const QuantizationMethod quantization_method SPECIALIZE,
- const bool use_hadamard SPECIALIZE,
- const uint dim_idx AXIS(model_dim, 32),
- const uint batch_idx AXIS(batch_size, 1)
-) {
- const uint thread_position_in_grid = batch_idx * model_dim + dim_idx;
- const uint32_t token_id = token_ids[batch_idx];
- if (token_id >= vocab_size) {
- output[thread_position_in_grid] = T(0);
- return;
- }
-
- const uint group_idx = dim_idx / group_size;
- const uint num_groups = (model_dim + group_size - 1) / group_size;
- const uint zp_stride = quantization_mode == QuantizationMode::U4 ? (num_groups + 1) / 2 : num_groups;
-
- const T scale = scales[token_id * num_groups + group_idx];
-
- const uint packing_divisor = quantization_mode == QuantizationMode::U4 ? 2 : 1;
- const uint weights_stride = model_dim / packing_divisor;
-
- int quantized_value = 0;
- switch (quantization_mode) {
- case QuantizationMode::U4: {
- const uint byte_idx = token_id * weights_stride + (dim_idx / 2);
- const uint8_t packed = weights[byte_idx];
- if ((dim_idx & 1) == 0) {
- quantized_value = int(packed & 0x0F);
- } else {
- quantized_value = int((packed >> 4) & 0x0F);
- }
- break;
- };
- case QuantizationMode::I8: {
- const uint elem_idx = token_id * weights_stride + dim_idx;
- const device int8_t* weights_i8 = reinterpret_cast<const device int8_t*>(weights);
- quantized_value = int(weights_i8[elem_idx]);
- break;
- };
- case QuantizationMode::U8: {
- const uint elem_idx = token_id * weights_stride + dim_idx;
- quantized_value = int(weights[elem_idx]);
- break;
- };
- }
-
- float bias = 0.0f;
- if (quantization_method == QuantizationMethod::ScaleBias) {
- bias = float(biases[token_id * num_groups + group_idx]);
- } else if (quantization_method == QuantizationMethod::ScaleZeroPoint) {
- uint zero_point = 0;
- if (quantization_mode == QuantizationMode::U4) {
- const uint8_t packed = zero_points[token_id * zp_stride + group_idx / 2];
- zero_point = (group_idx & 1) == 0 ? (packed & 0x0F) : ((packed >> 4) & 0x0F);
- } else {
- zero_point = zero_points[token_id * zp_stride + group_idx];
- }
- bias = -float(scale) * float(zero_point);
- } else {
- const uint midpoint = quantization_mode == QuantizationMode::U4 ? 8 : 128;
- bias = -float(scale) * float(midpoint);
- }
-
- float out_f = float(scale) * float(quantized_value) + bias;
- out_f *= input_scale;
- T out = T(out_f);
- if (use_hadamard) {
- out = simdgroup_output_random_hadamard_transform(
- static_cast<ushort>(dim_idx % METAL_SIMD_SIZE),
- out,
- output_hadamard_factors[dim_idx]
- );
- }
- output[thread_position_in_grid] = out;
-}
diff --git a/crates/uzu-engine/src/backends/metal/kernel/generated/d4s4.h b/crates/uzu-engine/src/backends/metal/kernel/generated/d4s4.h
new file mode 100644
index 000000000..d90b54974
--- /dev/null
+++ b/crates/uzu-engine/src/backends/metal/kernel/generated/d4s4.h
@@ -0,0 +1,17 @@
+// Auto-generated from gpu_types/d4s4 - do not edit manually
+#pragma once
+
+#include <metal_stdlib>
+using namespace metal;
+
+namespace uzu::d4s4 {
+static constant constexpr uint32_t VALUES_PER_CODE = 4;
+
+static constant constexpr uint32_t CODEBOOK_SIZE = 256;
+
+static constant constexpr uint32_t COLUMNS_PER_LADDER_SCALE = 64;
+
+static constant constexpr uint32_t COLUMNS_PER_LADDER_INDEX_BYTE = 2 * COLUMNS_PER_LADDER_SCALE;
+
+static constant constexpr uint32_t LADDER_SIZE = 16;
+} // namespace uzu::d4s4
diff --git a/crates/uzu-engine/src/backends/metal/kernel/generated/embedding.h b/crates/uzu-engine/src/backends/metal/kernel/generated/embedding.h
new file mode 100644
index 000000000..23e103ec3
--- /dev/null
+++ b/crates/uzu-engine/src/backends/metal/kernel/generated/embedding.h
@@ -0,0 +1,13 @@
+// Auto-generated from gpu_types/embedding - do not edit manually
+#pragma once
+
+#include <metal_stdlib>
+using namespace metal;
+
+namespace uzu::embedding {
+enum class EmbeddingTableKind : uint32_t {
+ Dense = 0,
+ Quantized = 1,
+ D4S4 = 2,
+};
+} // namespace uzu::embedding
diff --git a/crates/uzu-engine/src/backends/metal/kernel/matmul/common/quant_unpack.h b/crates/uzu-engine/src/backends/metal/kernel/matmul/common/quant_unpack.h
index f160b3fb2..759bf3e09 100644
--- a/crates/uzu-engine/src/backends/metal/kernel/matmul/common/quant_unpack.h
+++ b/crates/uzu-engine/src/backends/metal/kernel/matmul/common/quant_unpack.h
@@ -3,6 +3,7 @@
#include <metal_stdlib>
#include "../../common/defines.h"
+#include "../../common/packed.h"
using namespace metal;
@@ -59,7 +60,7 @@ template <ushort BITS>
METAL_FUNC uint decode_zero_point(uint8_t packed, uint group_index) {
static_assert(BITS == 4 || BITS == 8, "Only int4 and int8 zero points supported");
if constexpr (BITS == 4) {
- return (uint(packed) >> ((group_index & 1u) * 4u)) & 0x0Fu;
+ return read_packed<4>(packed, group_index);
} else {
return uint(packed);
}
@@ -67,8 +68,11 @@ METAL_FUNC uint decode_zero_point(uint8_t packed, uint group_index) {
template <ushort BITS>
METAL_FUNC uint decode_zero_point(const device uint8_t* zero_points_row, uint group_index) {
- const uint byte_index = BITS == 4 ? group_index >> 1 : group_index;
- return decode_zero_point<BITS>(zero_points_row[byte_index], group_index);
+ if constexpr (BITS == 4) {
+ return read_packed<4>(zero_points_row, group_index);
+ } else {
+ return decode_zero_point<BITS>(zero_points_row[group_index], group_index);
+ }
}
UZU_CONST ushort W4_BITS = 4;
diff --git a/crates/uzu-engine/src/config/weight_matrix/d4s4_spec.rs b/crates/uzu-engine/src/config/weight_matrix/d4s4_spec.rs
new file mode 100644
index 000000000..e46926df0
--- /dev/null
+++ b/crates/uzu-engine/src/config/weight_matrix/d4s4_spec.rs
@@ -0,0 +1,9 @@
+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.
+#[uzu_config(super::WeightMatrixSpec)]
+pub struct D4S4Spec {
+ pub layout: Layout,
+}
diff --git a/crates/uzu-engine/src/config/weight_matrix/mod.rs b/crates/uzu-engine/src/config/weight_matrix/mod.rs
index 5f10ee506..3f8b789a8 100644
--- a/crates/uzu-engine/src/config/weight_matrix/mod.rs
+++ b/crates/uzu-engine/src/config/weight_matrix/mod.rs
@@ -1,5 +1,6 @@
use uzu_engine_macros::{uzu_config, uzu_config_abstract};
+pub mod d4s4_spec;
pub mod full_precision_spec;
pub mod hybrid_spec;
pub mod int_spec;
@@ -18,6 +19,7 @@ pub enum Layout {
low_rank_spec::LowRankSpec,
hybrid_spec::HybridSpec,
int_spec::IntSpec,
- mlx_spec::MLXSpec
+ mlx_spec::MLXSpec,
+ d4s4_spec::D4S4Spec
)]
pub struct WeightMatrixSpec;
diff --git a/crates/uzu-engine/src/encodable_block/embedding.rs b/crates/uzu-engine/src/encodable_block/embedding.rs
index 2f57c2b42..3ed2ccabf 100644
--- a/crates/uzu-engine/src/encodable_block/embedding.rs
+++ b/crates/uzu-engine/src/encodable_block/embedding.rs
@@ -5,24 +5,16 @@ use thiserror::Error;
use crate::{
backends::common::{
Backend, BufferRef, CommandBuffer, CommandBufferEncoding, Kernels,
- gpu_types::HADAMARD_TRANSFORM_BLOCK_SIZE,
kernel::{
LogitTransformKernel,
matmul::{MatmulA, MatmulArguments, MatmulDOps, MatmulKernel},
},
},
- config::{
- embedding::AnyEmbeddingConfig,
- weight_matrix::{
- AnyWeightMatrixSpec,
- hybrid_spec::{HybridSpec, IncoherenceProcessingMode},
- },
- },
+ config::{embedding::AnyEmbeddingConfig, weight_matrix::AnyWeightMatrixSpec},
data_type::DataType,
encodable_block::{
- embedding_table::{EmbeddingTable, EmbeddingTableError},
+ embedding_table::{EmbeddingTable, EmbeddingTableError, read_output_signs},
linear::{Gather, LinearMatmulError, UntiedReadout},
- weight_matrix::WeightMatrixError,
},
parameters::{ParameterLoaderError, ParameterTree},
};
@@ -37,8 +29,6 @@ pub enum EmbeddingError<B: Backend> {
UnsupportedConfiguration(String),
#[error("Embedding table error: {0}")]
EmbeddingTable(#[from] EmbeddingTableError<B>),
- #[error("Weight matrix error: {0}")]
- WeightMatrix(#[from] WeightMatrixError<B>),
#[error(transparent)]
LinearMatmul(#[from] LinearMatmulError<B>),
}
@@ -89,116 +79,31 @@ impl<B: Backend> Embedding<B> {
let (tying, readout_input_hadamard_factors) = match config {
AnyEmbeddingConfig::TiedEmbeddingConfig(_) => {
let embedding_tree = parameter_tree.subtree("embedding");
- let embedding_spec = embedding_tree.metadata::<AnyWeightMatrixSpec>("spec")?;
-
- let (tying, readout_input_hadamard_factors) = match embedding_spec {
- spec @ (AnyWeightMatrixSpec::FullPrecisionSpec(_)
- | AnyWeightMatrixSpec::MLXSpec(_)
- | AnyWeightMatrixSpec::IntSpec(_)) => {
- let table = EmbeddingTable::load_with_spec(
- context,
- &embedding_tree,
- vocab_size,
- model_dim,
- data_type,
- spec,
- None,
- )?;
-
- (
- EmbeddingTying::Tied {
- table,
- readout: readout_kernel(context, data_type)?,
- },
- None,
- )
- },
- AnyWeightMatrixSpec::HybridSpec(HybridSpec {
- quantization_spec,
- adapter_spec: None,
- incoherence_block_size: Some(block_size),
- incoherence_processing_mode: IncoherenceProcessingMode::Output,
- ..
- }) if block_size == HADAMARD_TRANSFORM_BLOCK_SIZE => {
- let incoherence_signs_tree = embedding_tree.subtree("incoherence_signs");
- let output_hadamard_factors = Some(
- incoherence_signs_tree
- .leaf("output_signs")?
- .validate(&[model_dim], DataType::I32)?
- .read_buffer()?,
- );
- let readout_input_hadamard_factors = Some(
- incoherence_signs_tree
- .leaf("output_signs")?
- .validate(&[model_dim], DataType::I32)?
- .read_buffer()?,
- );
-
- let table = EmbeddingTable::load_with_spec(
- context,
- &embedding_tree.subtree("quantized"),
- vocab_size,
- model_dim,
- data_type,
- *quantization_spec,
- output_hadamard_factors,
- )?;
- (
- EmbeddingTying::Tied {
- table,
- readout: readout_kernel(context, data_type)?,
- },
- readout_input_hadamard_factors,
- )
+ let table = EmbeddingTable::load(context, &embedding_tree, vocab_size, model_dim, data_type)?;
+ if table.as_matrix().is_none() {
+ return Err(EmbeddingError::UnsupportedConfiguration("tied embeddings need a matrix table".into()));
+ }
+ // The output norm fuses the readout's input rotation, so it needs its own copy of the factors.
+ let readout_input_hadamard_factors =
+ if let AnyWeightMatrixSpec::HybridSpec(_) = embedding_tree.metadata("spec")? {
+ Some(read_output_signs(&embedding_tree, model_dim)?)
+ } else {
+ None
+ };
+ (
+ EmbeddingTying::Tied {
+ table,
+ readout: readout_kernel(context, data_type)?,
},
- spec => return Err(EmbeddingError::UnsupportedConfiguration(format!("{spec:?}"))),
- };
-
- (tying, readout_input_hadamard_factors)
+ readout_input_hadamard_factors,
+ )
},
AnyEmbeddingConfig::UntiedEmbeddingConfig(_) => {
let input_embedding_tree = parameter_tree.subtree("input_embedding");
- let input_embedding_spec = input_embedding_tree.metadata::<AnyWeightMatrixSpec>("spec")?;
-
- let input_table = match input_embedding_spec {
- AnyWeightMatrixSpec::HybridSpec(HybridSpec {
- quantization_spec,
- adapter_spec: None,
- incoherence_block_size: Some(block_size),
- incoherence_processing_mode: IncoherenceProcessingMode::Output,
- ..
- }) if block_size == HADAMARD_TRANSFORM_BLOCK_SIZE => {
- let output_hadamard_factors = Some(
- input_embedding_tree
- .subtree("incoherence_signs")
- .leaf("output_signs")?
- .validate(&[model_dim], DataType::I32)?
- .read_buffer()?,
- );
- EmbeddingTable::load_with_spec(
- context,
- &input_embedding_tree.subtree("quantized"),
- vocab_size,
- model_dim,
- data_type,
- *quantization_spec,
- output_hadamard_factors,
- )?
- },
- spec => EmbeddingTable::load_with_spec(
- context,
- &input_embedding_tree,
- vocab_size,
- model_dim,
- data_type,
- spec,
- None,
- )?,
- };
-
+ let input_table =
+ EmbeddingTable::load(context, &input_embedding_tree, vocab_size, model_dim, data_type)?;
let output_embedding_tree = parameter_tree.subtree("output_embedding");
- let output_embedding_spec = output_embedding_tree.metadata::<AnyWeightMatrixSpec>("spec")?;
-
+ let output_embedding_spec = output_embedding_tree.metadata("spec")?;
let output = UntiedReadout::load(
context,
&output_embedding_tree,
@@ -207,7 +112,6 @@ impl<B: Backend> Embedding<B> {
model_dim,
data_type,
)?;
-
(
EmbeddingTying::Untied {
input_table,
@@ -311,7 +215,7 @@ impl<B: Backend> Embedding<B> {
values: input_buffer,
offset: 0,
},
- b: table.matrix().matmul_b(),
+ b: table.as_matrix().expect("tied embedding tables are matrices").matmul_b(),
b_leading_dimension: None,
b_transpose: true,
d: &mut output,
diff --git a/crates/uzu-engine/src/encodable_block/embedding_table.rs b/crates/uzu-engine/src/encodable_block/embedding_table.rs
index 9c4158518..7dae6806a 100644
--- a/crates/uzu-engine/src/encodable_block/embedding_table.rs
+++ b/crates/uzu-engine/src/encodable_block/embedding_table.rs
@@ -4,14 +4,21 @@ use thiserror::Error;
use crate::{
backends::common::{
Backend, BufferMut, BufferRef, CommandBuffer, Kernels,
- kernel::{FullPrecisionEmbeddingLookupKernel, QuantizedEmbeddingLookupKernel},
+ gpu_types::{EmbeddingTableKind, HADAMARD_TRANSFORM_BLOCK_SIZE, d4s4},
+ kernel::InputEmbeddingLookupKernel,
+ },
+ config::weight_matrix::{
+ AnyWeightMatrixSpec, Layout,
+ d4s4_spec::D4S4Spec,
+ hybrid_spec::{HybridSpec, IncoherenceProcessingMode},
},
- config::weight_matrix::{AnyWeightMatrixSpec, Layout},
data_type::DataType,
encodable_block::weight_matrix::{WeightMatrix, WeightMatrixError},
parameters::{ParameterLoaderError, ParameterTree},
};
+type LookupKernel<B> = <<B as Backend>::Kernels as Kernels>::InputEmbeddingLookupKernel;
+
#[derive(Debug, Error)]
pub enum EmbeddingTableError<B: Backend> {
#[error("Backend error: {0}")]
@@ -24,15 +31,59 @@ pub enum EmbeddingTableError<B: Backend> {
UnsupportedConfiguration(String),
}
-enum LookupKernel<B: Backend> {
- FullPrecision(<B::Kernels as Kernels>::FullPrecisionEmbeddingLookupKernel),
- Quantized(<B::Kernels as Kernels>::QuantizedEmbeddingLookupKernel),
+/// Lookup-only D4S4 table: one codebook entry per 4 columns and a ladder scale per 64 columns.
+struct D4S4Table<B: Backend> {
+ codes: B::GlobalBuffer,
+ row_scales: B::GlobalBuffer,
+ ladder_indices: B::GlobalBuffer,
+ ladder: B::GlobalBuffer,
+ codebook: B::GlobalBuffer,
+}
+
+enum Storage<B: Backend> {
+ Matrix(WeightMatrix<B>),
+ D4S4(D4S4Table<B>),
+}
+
+struct LookupBindings<'a, B: Backend> {
+ values: &'a B::GlobalBuffer,
+ scales: Option<&'a B::GlobalBuffer>,
+ zero_points: Option<&'a B::GlobalBuffer>,
+ biases: Option<&'a B::GlobalBuffer>,
+ ladder_indices: Option<&'a B::GlobalBuffer>,
+ ladder: Option<&'a B::GlobalBuffer>,
+ codebook: Option<&'a B::GlobalBuffer>,
+}
+
+impl<B: Backend> Storage<B> {
+ fn lookup_bindings(&self) -> LookupBindings<'_, B> {
+ match self {
+ Self::Matrix(matrix) => LookupBindings {
+ values: matrix.values(),
+ scales: matrix.scales(),
+ zero_points: matrix.zero_points(),
+ biases: matrix.biases(),
+ ladder_indices: None,
+ ladder: None,
+ codebook: None,
+ },
+ Self::D4S4(table) => LookupBindings {
+ values: &table.codes,
+ scales: Some(&table.row_scales),
+ zero_points: None,
+ biases: None,
+ ladder_indices: Some(&table.ladder_indices),
+ ladder: Some(&table.ladder),
+ codebook: Some(&table.codebook),
+ },
+ }
+ }
}
pub struct EmbeddingTable<B: Backend> {
- matrix: WeightMatrix<B>,
- lookup: LookupKernel<B>,
+ storage: Storage<B>,
output_hadamard_factors: Option<B::GlobalBuffer>,
+ lookup: LookupKernel<B>,
vocab_size: u32,
embedding_dim: u32,
}
@@ -45,55 +96,74 @@ impl<B: Backend> EmbeddingTable<B> {
embedding_dim: u32,
data_type: DataType,
) -> Result<Self, EmbeddingTableError<B>> {
- let spec = tree.metadata::<AnyWeightMatrixSpec>("spec")?;
- Self::load_with_spec(context, tree, vocab_size, embedding_dim, data_type, spec, None)
- }
-
- pub fn load_with_spec(
- context: &B::Context,
- tree: &ParameterTree<B>,
- vocab_size: u32,
- embedding_dim: u32,
- data_type: DataType,
- spec: AnyWeightMatrixSpec,
- output_hadamard_factors: Option<B::GlobalBuffer>,
- ) -> Result<Self, EmbeddingTableError<B>> {
- let matrix = WeightMatrix::load(tree, spec, Layout::InputOutput, embedding_dim, vocab_size, data_type)?;
- if output_hadamard_factors.is_some() && matrix.quantization().is_none() {
- return Err(EmbeddingTableError::UnsupportedConfiguration(
- "output-hadamard factors require a quantized table".into(),
- ));
+ if !matches!(data_type, DataType::F32 | DataType::BF16) {
+ return Err(EmbeddingTableError::UnsupportedConfiguration(format!(
+ "input embedding lookup does not support {data_type:?}"
+ )));
}
+ let load_matrix = |tree: &ParameterTree<B>, spec| {
+ WeightMatrix::load(tree, spec, Layout::InputOutput, embedding_dim, vocab_size, data_type)
+ };
+ let (storage, output_hadamard_factors) = match tree.metadata::<AnyWeightMatrixSpec>("spec")? {
+ AnyWeightMatrixSpec::D4S4Spec(spec) => {
+ let (table, factors) = load_d4s4(tree, vocab_size, embedding_dim, data_type, spec)?;
+ (Storage::D4S4(table), Some(factors))
+ },
+ AnyWeightMatrixSpec::HybridSpec(HybridSpec {
+ quantization_spec,
+ adapter_spec: None,
+ incoherence_block_size: Some(HADAMARD_TRANSFORM_BLOCK_SIZE),
+ incoherence_processing_mode: IncoherenceProcessingMode::Output,
+ ..
+ }) if embedding_dim.is_multiple_of(HADAMARD_TRANSFORM_BLOCK_SIZE) => {
+ let matrix = load_matrix(&tree.subtree("quantized"), *quantization_spec)?;
+ 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)?))
+ },
+ spec @ AnyWeightMatrixSpec::HybridSpec(_) => {
+ return Err(EmbeddingTableError::UnsupportedConfiguration(format!(
+ "{spec:?} with embedding dim {embedding_dim}"
+ )));
+ },
+ spec => (Storage::Matrix(load_matrix(tree, spec)?), None),
+ };
- let lookup = match matrix.quantization() {
- None => LookupKernel::FullPrecision(
- <B::Kernels as Kernels>::FullPrecisionEmbeddingLookupKernel::new(context, data_type)
- .map_err(EmbeddingTableError::BackendError)?,
- ),
- Some(info) => LookupKernel::Quantized(
- <B::Kernels as Kernels>::QuantizedEmbeddingLookupKernel::new(
- context,
- data_type,
- info.group_size,
- info.mode,
- info.method,
- output_hadamard_factors.is_some(),
- )
- .map_err(EmbeddingTableError::BackendError)?,
- ),
+ 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)
+ }
+ },
};
+ let group_size = quantization.map(|info| info.group_size);
+ let mode = quantization.map(|info| info.mode);
+ let method = quantization.map(|info| info.method);
+ 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)?;
Ok(Self {
- matrix,
- lookup,
+ storage,
output_hadamard_factors,
+ lookup,
vocab_size,
embedding_dim,
})
}
- pub fn matrix(&self) -> &WeightMatrix<B> {
- &self.matrix
+ /// The matrix used by tied readout; D4S4 tables support lookup only.
+ pub fn as_matrix(&self) -> Option<&WeightMatrix<B>> {
+ match &self.storage {
+ Storage::Matrix(matrix) => Some(matrix),
+ Storage::D4S4(_) => None,
+ }
}
/// Gathers one row per token id into `output`, scaling by `scale`.
@@ -105,31 +175,59 @@ impl<B: Backend> EmbeddingTable<B> {
scale: f32,
command_buffer: &mut <B::CommandBuffer as CommandBuffer>::Encoding,
) {
- match &self.lookup {
- LookupKernel::FullPrecision(kernel) => kernel.encode(
- token_ids,
- self.matrix.values(),
- output,
- batch_dim,
- self.vocab_size,
- self.embedding_dim,
- scale,
- command_buffer,
- ),
- LookupKernel::Quantized(kernel) => kernel.encode(
- token_ids,
- self.matrix.values(),
- self.matrix.scales().expect("quantized lookup requires scales"),
- self.matrix.zero_points(),
- self.matrix.biases(),
- output,
- self.output_hadamard_factors.as_ref(),
- batch_dim,
- self.vocab_size,
- self.embedding_dim,
- scale,
- command_buffer,
- ),
- }
+ let bindings = self.storage.lookup_bindings();
+ self.lookup.encode(
+ token_ids,
+ bindings.values,
+ bindings.scales,
+ bindings.zero_points,
+ bindings.biases,
+ self.output_hadamard_factors.as_ref(),
+ bindings.ladder_indices,
+ bindings.ladder,
+ bindings.codebook,
+ output,
+ batch_dim,
+ self.vocab_size,
+ self.embedding_dim,
+ scale,
+ command_buffer,
+ );
}
}
+
+fn load_d4s4<B: Backend>(
+ tree: &ParameterTree<B>,
+ vocab_size: u32,
+ embedding_dim: u32,
+ data_type: DataType,
+ spec: D4S4Spec,
+) -> Result<(D4S4Table<B>, B::GlobalBuffer), EmbeddingTableError<B>> {
+ if spec.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}"
+ )));
+ }
+ let read = |name: &str, shape: &[u32], data_type| tree.leaf(name)?.validate(shape, data_type)?.read_buffer();
+ let table = D4S4Table {
+ codes: read("codes", &[vocab_size, embedding_dim / d4s4::VALUES_PER_CODE], DataType::U8)?,
+ row_scales: read("row_scales", &[vocab_size], data_type)?,
+ ladder_indices: read(
+ "ladder_indices",
+ &[vocab_size, embedding_dim / d4s4::COLUMNS_PER_LADDER_INDEX_BYTE],
+ DataType::U8,
+ )?,
+ ladder: read("ladder", &[d4s4::LADDER_SIZE], DataType::F16)?,
+ codebook: read("table", &[d4s4::CODEBOOK_SIZE, d4s4::VALUES_PER_CODE], DataType::I8)?,
+ };
+ let factors = read("output_hadamard_factors", &[embedding_dim], DataType::I32)?;
+ Ok((table, factors))
+}
+
+pub(super) fn read_output_signs<B: Backend>(
+ tree: &ParameterTree<B>,
+ embedding_dim: u32,
+) -> Result<B::GlobalBuffer, EmbeddingTableError<B>> {
+ let signs = tree.subtree("incoherence_signs");
+ Ok(signs.leaf("output_signs")?.validate(&[embedding_dim], DataType::I32)?.read_buffer()?)
+}
diff --git a/crates/uzu-engine/unit/backends/common/kernel/embedding/full_precision_embedding_test.rs b/crates/uzu-engine/unit/backends/common/kernel/embedding/full_precision_embedding_test.rs
deleted file mode 100644
index 02b21c6d8..000000000
--- a/crates/uzu-engine/unit/backends/common/kernel/embedding/full_precision_embedding_test.rs
+++ /dev/null
@@ -1,102 +0,0 @@
-use std::fmt::Debug;
-
-use half::{bf16, f16};
-use num_traits::Float;
-use uzu_engine_macros::uzu_test;
-
-use crate::{
- array::ArrayElement,
- backends::common::{
- Backend, CommandBufferEncoding, CommandBufferExecutable, CommandBufferPending, Context, Kernels,
- kernel::FullPrecisionEmbeddingLookupKernel,
- },
- tests::helpers::{buffer_to_vec, create_buffer, create_buffer_with_data, for_each_backend},
-};
-
-struct Input<T: ArrayElement + Float> {
- token_ids: Box<[u32]>,
- weights: Box<[T]>,
- batch_size: usize,
- vocab_size: usize,
- model_dim: usize,
- input_scale: f32,
-}
-
-fn get_test_data<T: ArrayElement + Float>() -> (Input<T>, Vec<T>) {
- let vocab_size = 11;
- let model_dim = 513;
- let batch_size = 7;
- let input_scale = 2.0_f32;
-
- let token_ids: Box<[u32]> = Box::new([3, 7, 1, 10, 0, 5, 8]);
- let weights: Vec<T> =
- (0..vocab_size * model_dim).map(|i| T::from((i as f32).sin() * 30.0f32).unwrap()).collect::<Vec<_>>();
- let mut expected: Vec<T> = Vec::with_capacity(batch_size * model_dim);
- for &tid in token_ids.iter() {
- let row_start = tid as usize * model_dim;
- for j in 0..model_dim {
- expected.push(weights[row_start + j] * T::from(input_scale).unwrap());
- }
- }
-
- let input = Input {
- token_ids,
- weights: weights.iter().map(|&v| T::from(v).unwrap()).collect(),
- batch_size,
- vocab_size,
- model_dim,
- input_scale,
- };
-
- (input, expected)
-}
-
-fn get_output<T: ArrayElement + Float, B: Backend>(input: &Input<T>) -> Vec<T> {
- let context = B::Context::new().expect("Failed to create Context");
-
- let kernel =
- <<B as Backend>::Kernels as Kernels>::FullPrecisionEmbeddingLookupKernel::new(&context, T::data_type())
- .expect("Failed to create FullPrecisionEmbeddingLookupKernel");
-
- let token_ids_buffer = create_buffer_with_data::<B, u32>(&context, &input.token_ids);
- let weights_buffer = create_buffer_with_data::<B, T>(&context, &input.weights);
- let mut output = create_buffer::<B, T>(&context, input.batch_size * input.model_dim);
-
- let mut command_buffer = context.create_command_buffer(None, None).expect("Failed to get command buffer");
- kernel.encode(
- &token_ids_buffer,
- &weights_buffer,
- &mut output,
- input.batch_size as u32,
- input.vocab_size as u32,
- input.model_dim as u32,
- input.input_scale,
- &mut command_buffer,
- );
- command_buffer.end_encoding().submit().wait_until_completed().unwrap();
-
- buffer_to_vec(&output)
-}
-
-fn test<T: ArrayElement + Float + Debug>() {
- let (input, expected) = get_test_data::<T>();
- for_each_backend!(|B| {
- let output = get_output::<T, B>(&input);
- assert_eq!(output, expected, "Results are not equals for backend {}", std::any::type_name::<B>());
- });
-}
-
-#[uzu_test]
-fn test_f32() {
- test::<f32>()
-}
-
-#[uzu_test]
-fn test_f16() {
- test::<f16>()
-}
-
-#[uzu_test]
-fn test_bf16() {
- test::<bf16>()
-}
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.rs
new file mode 100644
index 000000000..db2b3feef
--- /dev/null
+++ b/crates/uzu-engine/unit/backends/common/kernel/embedding/input_embedding_lookup_test.rs
@@ -0,0 +1,187 @@
+use std::fmt::Display;
+
+use half::{bf16, f16};
+use num_traits::Float;
+use rstest::rstest;
+use uzu_engine_macros::uzu_test;
+
+use crate::{
+ array::ArrayElement,
+ backends::{
+ common::{
+ Backend, Context, Kernels,
+ gpu_types::{
+ EmbeddingTableKind::{self, D4S4, Dense, Quantized},
+ QuantizationMethod::{self, ScaleBias, ScaleSymmetric, ScaleZeroPoint},
+ QuantizationMode::{self, I8, U4, U8},
+ d4s4,
+ },
+ kernel::InputEmbeddingLookupKernel,
+ },
+ cpu::Cpu,
+ },
+ tests::{
+ assert::assert_eq_float,
+ helpers::{
+ buffer_to_vec, create_buffer, create_buffer_with_data, for_each_non_cpu_backend, submit_command_buffer,
+ },
+ },
+};
+
+const VOCAB_SIZE: u32 = 4;
+const MODEL_DIM: u32 = 128;
+const TOKEN_IDS: [u32; 3] = [0, 2, VOCAB_SIZE];
+
+type Quantization = (QuantizationMode, QuantizationMethod, u32);
+
+fn pattern(
+ len: u32,
+ seed: u32,
+) -> Vec<u8> {
+ (0..len).map(|index| (index * seed + 9) as u8).collect()
+}
+
+fn floats<T: ArrayElement + Float>(
+ len: u32,
+ value: impl Fn(u32) -> f32,
+) -> Vec<T> {
+ (0..len).map(|index| T::from(value(index)).unwrap()).collect()
+}
+
+fn lookup<B: Backend, T: ArrayElement + Float>(
+ table_kind: EmbeddingTableKind,
+ quantization: Option<Quantization>,
+ use_hadamard: bool,
+) -> Vec<T> {
+ let context = <B as Backend>::Context::new().unwrap();
+ let context = context.as_ref();
+ let bytes = |data: &[u8]| create_buffer_with_data::<B, u8>(context, data);
+ let (mut scales, mut zero_points, mut biases) = (None, None, None);
+ let (mut ladder_indices, mut ladder, mut codebook) = (None, None, None);
+ let values = match table_kind {
+ Dense => {
+ bytes(bytemuck::cast_slice(&floats::<T>(VOCAB_SIZE * MODEL_DIM, |index| (index as f32 * 0.37).sin() * 3.0)))
+ },
+ Quantized => {
+ let (mode, method, group_size) = quantization.expect("quantization settings");
+ let groups = MODEL_DIM.div_ceil(group_size);
+ let group_values =
+ |value: fn(u32) -> f32| create_buffer_with_data::<B, T>(context, &floats(VOCAB_SIZE * groups, value));
+ scales = Some(group_values(|index| 0.02 + (index % 5) as f32 * 0.01));
+ if method == ScaleBias {
+ biases = Some(group_values(|index| -0.1 + index as f32 * 0.03));
+ } else if method == ScaleZeroPoint {
+ zero_points = Some(bytes(&pattern(VOCAB_SIZE * groups.div_ceil(mode.packing_divisor()), 53)));
+ }
+ bytes(&pattern(VOCAB_SIZE * MODEL_DIM / mode.packing_divisor(), 37))
+ },
+ D4S4 => {
+ let row_scales = floats::<T>(VOCAB_SIZE, |row| 0.02 + row as f32 * 0.01);
+ let steps: Vec<f16> =
+ (0..d4s4::LADDER_SIZE).map(|index| f16::from_f32(2f32.powf(index as f32 / 2.0 - 5.5))).collect();
+ let points: Vec<i8> =
+ (0..d4s4::CODEBOOK_SIZE * d4s4::VALUES_PER_CODE).map(|index| (index % 9) as i8 - 4).collect();
+ scales = Some(create_buffer_with_data::<B, T>(context, &row_scales));
+ ladder_indices = Some(bytes(&pattern(VOCAB_SIZE * MODEL_DIM / d4s4::COLUMNS_PER_LADDER_INDEX_BYTE, 5)));
+ ladder = Some(create_buffer_with_data::<B, f16>(context, &steps));
+ codebook = Some(create_buffer_with_data::<B, i8>(context, &points));
+ bytes(&pattern(VOCAB_SIZE * MODEL_DIM / d4s4::VALUES_PER_CODE, 37))
+ },
+ };
+ let hadamard_factors = if use_hadamard {
+ let signs: Vec<i32> = (0..MODEL_DIM)
+ .map(|index| {
+ if index % 3 == 0 {
+ -1
+ } else {
+ 1
+ }
+ })
+ .collect();
+ Some(create_buffer_with_data::<B, i32>(context, &signs))
+ } else {
+ None
+ };
+
+ let (mode, method, group_size) = quantization
+ .map_or((None, None, None), |(mode, method, group_size)| (Some(mode), Some(method), Some(group_size)));
+ let kernel = <<B as Backend>::Kernels as Kernels>::InputEmbeddingLookupKernel::new(
+ context,
+ T::data_type(),
+ table_kind,
+ group_size,
+ mode,
+ method,
+ use_hadamard,
+ )
+ .unwrap();
+ let token_ids = create_buffer_with_data::<B, u32>(context, &TOKEN_IDS);
+ let mut output = create_buffer::<B, T>(context, TOKEN_IDS.len() * MODEL_DIM as usize);
+ let mut command_buffer = context.create_command_buffer(None, None).unwrap();
+ kernel.encode(
+ &token_ids,
+ &values,
+ scales.as_ref(),
+ zero_points.as_ref(),
+ biases.as_ref(),
+ hadamard_factors.as_ref(),
+ ladder_indices.as_ref(),
+ ladder.as_ref(),
+ codebook.as_ref(),
+ &mut output,
+ TOKEN_IDS.len() as u32,
+ VOCAB_SIZE,
+ MODEL_DIM,
+ 1.5,
+ &mut command_buffer,
+ );
+ submit_command_buffer(command_buffer);
+ buffer_to_vec::<B, T>(&output)
+}
+
+fn check<T: ArrayElement + Float + Display>(
+ table_kind: EmbeddingTableKind,
+ quantization: Option<Quantization>,
+ use_hadamard: bool,
+) {
+ let expected = lookup::<Cpu, T>(table_kind, quantization, use_hadamard);
+ let in_vocab = 2 * MODEL_DIM as usize;
+ assert!(expected[..in_vocab].iter().any(|value| *value != T::zero()), "in-vocab rows are empty");
+ assert!(expected[in_vocab..].iter().all(|value| *value == T::zero()), "out-of-vocab row is not zero");
+ for_each_non_cpu_backend!(|B| {
+ let actual = lookup::<B, T>(table_kind, quantization, use_hadamard);
+ assert_eq_float(&expected, &actual, 0.02, std::any::type_name::<B>());
+ });
+}
+
+#[rstest]
+#[test_attr(uzu_test)]
+#[case::dense(Dense, None, false)]
+#[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)]
+#[case::u8_bias(Quantized, Some((U8, ScaleBias, 32)), false)]
+#[case::u8_zero_point(Quantized, Some((U8, ScaleZeroPoint, 32)), false)]
+#[case::u8_symmetric(Quantized, Some((U8, ScaleSymmetric, 32)), false)]
+#[case::i8_symmetric(Quantized, Some((I8, ScaleSymmetric, 32)), false)]
+#[case::u4_bias_hadamard(Quantized, Some((U4, ScaleBias, 32)), true)]
+#[case::d4s4(D4S4, None, true)]
+fn input_embedding_lookup_bf16(
+ #[case] table_kind: EmbeddingTableKind,
+ #[case] quantization: Option<Quantization>,
+ #[case] use_hadamard: bool,
+) {
+ check::<bf16>(table_kind, quantization, use_hadamard);
+}
+
+#[rstest]
+#[test_attr(uzu_test)]
+#[case::dense(Dense, None, false)]
+#[case::u4_bias(Quantized, Some((U4, ScaleBias, 32)), false)]
+fn input_embedding_lookup_f32(
+ #[case] table_kind: EmbeddingTableKind,
+ #[case] quantization: Option<Quantization>,
+ #[case] use_hadamard: bool,
+) {
+ check::<f32>(table_kind, quantization, use_hadamard);
+}
diff --git a/crates/uzu-engine/unit/backends/common/kernel/embedding/mod.rs b/crates/uzu-engine/unit/backends/common/kernel/embedding/mod.rs
index dd406a5cd..79bce669c 100644
--- a/crates/uzu-engine/unit/backends/common/kernel/embedding/mod.rs
+++ b/crates/uzu-engine/unit/backends/common/kernel/embedding/mod.rs
@@ -1,2 +1 @@
-mod full_precision_embedding_test;
-mod quant_embedding_test;
+mod input_embedding_lookup_test;
diff --git a/crates/uzu-engine/unit/backends/common/kernel/embedding/quant_embedding_test.rs b/crates/uzu-engine/unit/backends/common/kernel/embedding/quant_embedding_test.rs
deleted file mode 100644
index 19bcc4ee9..000000000
--- a/crates/uzu-engine/unit/backends/common/kernel/embedding/quant_embedding_test.rs
+++ /dev/null
@@ -1,478 +0,0 @@
-use std::fmt::{Debug, Display};
-
-use half::{bf16, f16};
-use num_traits::Float;
-use uzu_engine_macros::uzu_test;
-
-use crate::{
- array::ArrayElement,
- backends::{
- common::{
- Backend, CommandBufferEncoding, CommandBufferExecutable, CommandBufferPending, Context, Kernels,
- gpu_types::{QuantizationMethod, QuantizationMode},
- kernel::{ActivationTransform, QuantizedEmbeddingLookupKernel},
- },
- cpu::Cpu,
- },
- data_type::DataType,
- tests::{
- assert::assert_eq_float,
- helpers::{buffer_to_vec, create_buffer, create_buffer_with_data, for_each_backend, for_each_non_cpu_backend},
- },
-};
-
-struct Input<T: ArrayElement + Float> {
- token_ids: Box<[u32]>,
- weights: Box<[u8]>,
- scales: Box<[T]>,
- zero_points: Option<Box<[u8]>>,
- biases: Option<Box<[T]>>,
- batch_size: u32,
- vocab_size: u32,
- model_dim: u32,
- input_scale: f32,
- group_size: u32,
- quant_mode: QuantizationMode,
- quant_method: QuantizationMethod,
-}
-
-fn get_test_data<T: ArrayElement + Float>(quant_mode: QuantizationMode) -> (Input<T>, Vec<T>) {
- let batch_size = 3u32;
- let vocab_size = 8u32;
- let model_dim = 64u32;
- let group_size = 32u32;
- let input_scale = 1.5f32;
-
- let token_ids: Box<[u32]> = Box::new([2, 5, 0]);
-
- let packing_divisor = quant_mode.packing_divisor();
- let weights_stride = model_dim / packing_divisor;
- let weights: Vec<u8> = (0..vocab_size as usize * weights_stride as usize)
- .map(|i| ((i % 16) as u8) | ((((i + 3) % 16) as u8) * 16))
- .collect();
-
- let num_groups = model_dim.div_ceil(group_size);
- let scales: Vec<T> = (0..vocab_size as usize * num_groups as usize)
- .map(|i| T::from(0.5 + (i as f32 * 0.1).sin() * 0.3).unwrap())
- .collect();
- let biases: Vec<T> = (0..vocab_size as usize * num_groups as usize)
- .map(|i| T::from((i as f32 * 0.2).cos() * 0.1).unwrap())
- .collect();
-
- let input = Input {
- token_ids,
- weights: weights.into_boxed_slice(),
- scales: scales.into_boxed_slice(),
- zero_points: None,
- biases: Some(biases.into_boxed_slice()),
- batch_size,
- vocab_size,
- model_dim,
- input_scale,
- group_size,
- quant_mode,
- quant_method: QuantizationMethod::ScaleBias,
- };
-
- let expected = get_output::<T, Cpu>(&input);
- (input, expected)
-}
-
-fn get_test_data_zero_point_group16<T: ArrayElement + Float>() -> (Input<T>, Vec<T>) {
- let batch_size = 3u32;
- let vocab_size = 8u32;
- let model_dim = 64u32;
- let group_size = 16u32;
- let input_scale = 1.5f32;
- let quant_mode = QuantizationMode::U4;
-
- let token_ids: Box<[u32]> = Box::new([2, 5, 0]);
-
- let packing_divisor = quant_mode.packing_divisor();
- let weights_stride = model_dim / packing_divisor;
- let weights: Vec<u8> = (0..vocab_size as usize * weights_stride as usize)
- .map(|i| ((i % 16) as u8) | ((((i + 3) % 16) as u8) * 16))
- .collect();
-
- let num_groups = model_dim.div_ceil(group_size);
- let scales: Vec<T> = (0..vocab_size as usize * num_groups as usize)
- .map(|i| T::from(0.5 + (i as f32 * 0.1).sin() * 0.3).unwrap())
- .collect();
- let zero_point_stride = num_groups.div_ceil(packing_divisor);
- let zero_points: Vec<u8> = (0..vocab_size as usize * zero_point_stride as usize)
- .map(|i| ((i % 16) as u8) | ((((i + 5) % 16) as u8) * 16))
- .collect();
-
- let input = Input {
- token_ids,
- weights: weights.into_boxed_slice(),
- scales: scales.into_boxed_slice(),
- zero_points: Some(zero_points.into_boxed_slice()),
- biases: None,
- batch_size,
- vocab_size,
- model_dim,
- input_scale,
- group_size,
- quant_mode,
- quant_method: QuantizationMethod::ScaleZeroPoint,
- };
-
- let expected = get_output::<T, Cpu>(&input);
- (input, expected)
-}
-
-fn get_test_data_symmetric_u8<T: ArrayElement + Float>() -> (Input<T>, Vec<T>) {
- let batch_size = 3u32;
- let vocab_size = 8u32;
- let model_dim = 64u32;
- let group_size = 32u32;
- let input_scale = 1.5f32;
- let quant_mode = QuantizationMode::U8;
-
- let token_ids: Box<[u32]> = Box::new([2, 5, 0]);
-
- let weights: Vec<u8> =
- (0..vocab_size as usize * model_dim as usize).map(|i| ((i * 37 + 11) & 0xFF) as u8).collect();
-
- let num_groups = model_dim.div_ceil(group_size);
- let scales: Vec<T> = (0..vocab_size as usize * num_groups as usize)
- .map(|i| T::from(0.5 + (i as f32 * 0.1).sin() * 0.3).unwrap())
- .collect();
-
- let input = Input {
- token_ids,
- weights: weights.into_boxed_slice(),
- scales: scales.into_boxed_slice(),
- zero_points: None,
- biases: None,
- batch_size,
- vocab_size,
- model_dim,
- input_scale,
- group_size,
- quant_mode,
- quant_method: QuantizationMethod::ScaleSymmetric,
- };
-
- let expected = get_output::<T, Cpu>(&input);
- (input, expected)
-}
-
-fn get_test_data_oob<T: ArrayElement + Float>() -> (Input<T>, Vec<T>) {
- let batch_size = 2u32;
- let vocab_size = 4u32;
- let model_dim = 32u32;
- let group_size = 32u32;
- let input_scale = 1.0f32;
-
- // token_id 1 is valid, token_id 10 is out of bounds
- let token_ids: Box<[u32]> = Box::new([1, 10]);
-
- let weights: Vec<u8> = (0..vocab_size as usize * model_dim as usize).map(|i| (i % 200) as u8).collect();
-
- let num_groups = model_dim.div_ceil(group_size);
- let scales: Vec<T> =
- (0..vocab_size as usize * num_groups as usize).map(|i| T::from(0.5 + i as f32 * 0.1).unwrap()).collect();
- let biases: Vec<T> =
- (0..vocab_size as usize * num_groups as usize).map(|i| T::from(i as f32 * 0.01).unwrap()).collect();
-
- let input = Input {
- token_ids,
- weights: weights.into_boxed_slice(),
- scales: scales.into_boxed_slice(),
- zero_points: None,
- biases: Some(biases.into_boxed_slice()),
- batch_size,
- vocab_size,
- model_dim,
- input_scale,
- group_size,
- quant_mode: QuantizationMode::U8,
- quant_method: QuantizationMethod::ScaleBias,
- };
-
- let expected = get_output::<T, Cpu>(&input);
- (input, expected)
-}
-
-fn get_output<T: ArrayElement + Float, B: Backend>(input: &Input<T>) -> Vec<T> {
- get_output_with_hadamard::<T, B>(input, None)
-}
-
-fn get_output_with_hadamard<T: ArrayElement + Float, B: Backend>(
- input: &Input<T>,
- hadamard_factors: Option<&[i32]>,
-) -> Vec<T> {
- let context = B::Context::new().expect("Failed to create Context");
-
- let kernel = <<B as Backend>::Kernels as Kernels>::QuantizedEmbeddingLookupKernel::new(
- &context,
- T::data_type(),
- input.group_size,
- input.quant_mode,
- input.quant_method,
- hadamard_factors.is_some(),
- )
- .expect("Failed to create QuantizedEmbeddingLookupKernel");
-
- let token_ids_buffer = create_buffer_with_data::<B, u32>(&context, &input.token_ids);
- let weights_buffer = create_buffer_with_data::<B, u8>(&context, &input.weights);
- let scales_buffer = create_buffer_with_data::<B, T>(&context, &input.scales);
- let zero_points_buffer =
- input.zero_points.as_ref().map(|zero_points| create_buffer_with_data::<B, u8>(&context, zero_points));
- let biases_buffer = input.biases.as_ref().map(|biases| create_buffer_with_data::<B, T>(&context, biases));
- let hadamard_factors_buffer =
- hadamard_factors.map(|hadamard_factors| create_buffer_with_data::<B, i32>(&context, hadamard_factors));
- let mut output = create_buffer::<B, T>(&context, input.batch_size as usize * input.model_dim as usize);
-
- let mut command_buffer = context.create_command_buffer(None, None).expect("Failed to create command buffer");
- kernel.encode(
- &token_ids_buffer,
- &weights_buffer,
- &scales_buffer,
- zero_points_buffer.as_ref(),
- biases_buffer.as_ref(),
- &mut output,
- hadamard_factors_buffer.as_ref(),
- input.batch_size,
- input.vocab_size,
- input.model_dim,
- input.input_scale,
- &mut command_buffer,
- );
- command_buffer.end_encoding().submit().wait_until_completed().unwrap();
-
- buffer_to_vec(&output)
-}
-
-fn test_zero_point_group16<T: ArrayElement + Float + Debug + Display>() {
- let eps = if matches!(T::data_type(), DataType::F16 | DataType::BF16) {
- 0.5f32
- } else {
- 1e-4
- };
- let (input, expected) = get_test_data_zero_point_group16::<T>();
- for_each_non_cpu_backend!(|B| {
- let output = get_output::<T, B>(&input);
- assert_eq_float::<T>(
- &expected,
- &output,
- eps,
- &format!(
- "QuantizedEmbeddingLookup ScaleZeroPoint group16 test failed for backend {}",
- std::any::type_name::<B>()
- ),
- );
- });
-}
-
-fn test_symmetric_u8<T: ArrayElement + Float + Debug + Display>() {
- let eps = if matches!(T::data_type(), DataType::F16 | DataType::BF16) {
- 0.5f32
- } else {
- 1e-4
- };
- let (input, expected) = get_test_data_symmetric_u8::<T>();
- for_each_non_cpu_backend!(|B| {
- let output = get_output::<T, B>(&input);
- assert_eq_float::<T>(
- &expected,
- &output,
- eps,
- &format!("QuantizedEmbeddingLookup ScaleSymmetric test failed for backend {}", std::any::type_name::<B>()),
- );
- });
-}
-
-#[cfg(backend = "metal")]
-fn test_zero_point_group16_hadamard_constructor<T: ArrayElement + Float + Debug + Display>() {
- use crate::backends::metal::Metal;
-
- let context = <Metal as Backend>::Context::new().expect("Metal context");
- <<Metal as Backend>::Kernels as Kernels>::QuantizedEmbeddingLookupKernel::new(
- &context,
- T::data_type(),
- 16,
- QuantizationMode::U4,
- QuantizationMethod::ScaleZeroPoint,
- true,
- )
- .expect("QuantizedEmbeddingLookupKernel group16 zero-point hadamard");
-}
-
-// The fused transform has to match the plain lookup followed by the standalone output RHT
-fn test_zero_point_group16_hadamard<T: ArrayElement + Float + Debug + Display>() {
- let eps = if matches!(T::data_type(), DataType::F16 | DataType::BF16) {
- 0.5f32
- } else {
- 1e-4
- };
- let (input, plain) = get_test_data_zero_point_group16::<T>();
- let hadamard_factors: Vec<i32> = (0..input.model_dim)
- .map(|index| {
- if index % 3 == 0 {
- -1
- } else {
- 1
- }
- })
- .collect();
-
- let context = <Cpu as Backend>::Context::new().expect("Failed to create Context");
- let output_rht = ActivationTransform::<Cpu>::output_rht(context.as_ref(), T::data_type(), None, false)
- .expect("Failed to create ActivationTransform");
- let plain_buffer = create_buffer_with_data::<Cpu, T>(&context, &plain);
- let hadamard_factors_buffer = create_buffer_with_data::<Cpu, i32>(&context, &hadamard_factors);
- let mut expected_buffer = create_buffer::<Cpu, T>(&context, plain.len());
- let mut command_buffer = context.create_command_buffer(None, None).expect("Failed to create command buffer");
- output_rht.encode_fp(
- &plain_buffer,
- &mut expected_buffer,
- &hadamard_factors_buffer,
- input.batch_size,
- input.model_dim,
- &mut command_buffer,
- );
- command_buffer.end_encoding().submit().wait_until_completed().unwrap();
- let expected = buffer_to_vec::<Cpu, T>(&expected_buffer);
-
- for_each_backend!(|B| {
- let output = get_output_with_hadamard::<T, B>(&input, Some(&hadamard_factors));
- assert_eq_float::<T>(
- &expected,
- &output,
- eps,
- &format!(
- "QuantizedEmbeddingLookup ScaleZeroPoint group16 hadamard test failed for backend {}",
- std::any::type_name::<B>()
- ),
- );
- });
-}
-
-fn test_quant_mode<T: ArrayElement + Float + Debug + Display>(quant_mode: QuantizationMode) {
- let eps = if matches!(T::data_type(), DataType::F16 | DataType::BF16) {
- 0.5f32
- } else {
- 1e-4
- };
- let (input, expected) = get_test_data::<T>(quant_mode);
- for_each_non_cpu_backend!(|B| {
- let output = get_output::<T, B>(&input);
- assert_eq_float::<T>(
- &expected,
- &output,
- eps,
- &format!("QuantizedEmbeddingLookup {quant_mode:?} test failed for backend {}", std::any::type_name::<B>()),
- );
- });
-}
-
-fn test_oob<T: ArrayElement + Float + Debug + Display>() {
- let eps = if matches!(T::data_type(), DataType::F16 | DataType::BF16) {
- 0.5f32
- } else {
- 1e-4
- };
- let (input, expected) = get_test_data_oob::<T>();
- for_each_non_cpu_backend!(|B| {
- let output = get_output::<T, B>(&input);
- assert_eq_float::<T>(
- &expected,
- &output,
- eps,
- &format!("QuantizedEmbeddingLookup OOB test failed for backend {}", std::any::type_name::<B>()),
- );
- });
-}
-
-// UINT4 tests
-#[uzu_test]
-fn test_uint4_f32() {
- test_quant_mode::<f32>(QuantizationMode::U4);
-}
-
-#[uzu_test]
-fn test_uint4_f16() {
- test_quant_mode::<f16>(QuantizationMode::U4);
-}
-
-#[uzu_test]
-fn test_uint4_bf16() {
- test_quant_mode::<bf16>(QuantizationMode::U4);
-}
-
-#[uzu_test]
-fn test_uint4_zero_point_group16_bf16() {
- test_zero_point_group16::<bf16>();
-}
-
-#[cfg(backend = "metal")]
-#[uzu_test]
-fn test_uint4_zero_point_group16_hadamard_bf16_constructor() {
- test_zero_point_group16_hadamard_constructor::<bf16>();
-}
-
-#[uzu_test]
-fn test_uint4_zero_point_group16_hadamard_f32() {
- test_zero_point_group16_hadamard::<f32>();
-}
-
-#[uzu_test]
-fn test_uint4_zero_point_group16_hadamard_bf16() {
- test_zero_point_group16_hadamard::<bf16>();
-}
-
-// INT8 tests
-#[uzu_test]
-fn test_int8_f32() {
- test_quant_mode::<f32>(QuantizationMode::I8);
-}
-
-#[uzu_test]
-fn test_int8_f16() {
- test_quant_mode::<f16>(QuantizationMode::I8);
-}
-
-#[uzu_test]
-fn test_int8_bf16() {
- test_quant_mode::<bf16>(QuantizationMode::I8);
-}
-
-// UINT8 tests
-#[uzu_test]
-fn test_uint8_f32() {
- test_quant_mode::<f32>(QuantizationMode::U8);
-}
-
-#[uzu_test]
-fn test_uint8_f16() {
- test_quant_mode::<f16>(QuantizationMode::U8);
-}
-
-#[uzu_test]
-fn test_uint8_bf16() {
- test_quant_mode::<bf16>(QuantizationMode::U8);
-}
-
-#[uzu_test]
-fn test_uint8_symmetric_bf16() {
- test_symmetric_u8::<bf16>();
-}
-
-// OOB tests
-#[uzu_test]
-fn test_oob_f32() {
- test_oob::<f32>();
-}
-
-#[uzu_test]
-fn test_oob_f16() {
- test_oob::<f16>();
-}
-
-#[uzu_test]
-fn test_oob_bf16() {
- test_oob::<bf16>();
-}