Skip to content

armgit / uzu

Public Imported from GitHub
0

A high-performance inference engine for AI models

Small cleanups (part 1) (#949)

uuuvnb73162db5c95
diff --git a/crates/uzu-engine/src/backends/common/gpu_types/gemm.rs b/crates/uzu-engine/src/backends/common/gpu_types/gemm.rs
index 5800a8bee..ddf160c8d 100644
--- a/crates/uzu-engine/src/backends/common/gpu_types/gemm.rs
+++ b/crates/uzu-engine/src/backends/common/gpu_types/gemm.rs
@@ -22,10 +22,9 @@ bitflags! {
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub struct GemmDTransform: u32 {
const SCALE = 1 << 0;
- const ACCUMULATE = 1 << 1;
- const BIAS = 1 << 2;
- const RHT = 1 << 3;
- const SOFT_CAP = 1 << 4;
+ const BIAS = 1 << 1;
+ const RHT = 1 << 2;
+ const SOFT_CAP = 1 << 3;
}
}
diff --git a/crates/uzu-engine/src/backends/common/kernel/matmul/d_ops.rs b/crates/uzu-engine/src/backends/common/kernel/matmul/d_ops.rs
index 9bccbc4d5..7a300a96a 100644
--- a/crates/uzu-engine/src/backends/common/kernel/matmul/d_ops.rs
+++ b/crates/uzu-engine/src/backends/common/kernel/matmul/d_ops.rs
@@ -2,7 +2,6 @@ use crate::backends::common::{Backend, gpu_types::gemm::GemmDTransform};
pub struct MatmulDOps<'a, B: Backend> {
pub ab_scale: f32,
- pub accumulate: bool,
pub bias: Option<&'a B::GlobalBuffer>,
pub rht_factors: Option<&'a B::GlobalBuffer>,
pub soft_cap: Option<f32>,
@@ -12,7 +11,6 @@ impl<'a, B: Backend> MatmulDOps<'a, B> {
pub fn none() -> Self {
Self {
ab_scale: 1.0,
- accumulate: false,
bias: None,
rht_factors: None,
soft_cap: None,
@@ -24,9 +22,6 @@ impl<'a, B: Backend> MatmulDOps<'a, B> {
if self.ab_scale != 1.0 {
m |= GemmDTransform::SCALE;
}
- if self.accumulate {
- m |= GemmDTransform::ACCUMULATE;
- }
if self.bias.is_some() {
m |= GemmDTransform::BIAS;
}
@@ -49,11 +44,6 @@ impl<'a, B: Backend> MatmulDOps<'a, B> {
} else {
self.ab_scale
},
- accumulate: if bits.contains(GemmDTransform::ACCUMULATE) {
- false
- } else {
- self.accumulate
- },
bias: if bits.contains(GemmDTransform::BIAS) {
None
} else {
diff --git a/crates/uzu-engine/src/backends/cpu/kernel/matmul/kernel.rs b/crates/uzu-engine/src/backends/cpu/kernel/matmul/kernel.rs
index 0e72889e0..08d5c623d 100644
--- a/crates/uzu-engine/src/backends/cpu/kernel/matmul/kernel.rs
+++ b/crates/uzu-engine/src/backends/cpu/kernel/matmul/kernel.rs
@@ -81,7 +81,6 @@ impl MatmulKernel for MatmulCpuKernel {
} = arguments;
let (mut d, ops) = output.into_contiguous(n, "CpuMatmul")?;
let output_scale = ops.ab_scale;
- let accumulate = ops.accumulate;
let bias_buffer = ops.bias;
let post_rht = ops.rht_factors;
let soft_cap = ops.soft_cap;
@@ -264,9 +263,6 @@ impl MatmulKernel for MatmulCpuKernel {
let output_index = row * n_u + col;
let mut value = output_scale * accumulator;
- if accumulate {
- value += read_f32(d_ptr.as_ptr(), output_data_type, output_index);
- }
if !bias_after_rht && let Some(bias) = bias_ptr {
value += read_f32(bias.as_ptr(), weights_data_type, col);
}
diff --git a/crates/uzu-engine/src/backends/metal/kernel/attention/attention_gemm.metal b/crates/uzu-engine/src/backends/metal/kernel/attention/attention_gemm.metal
index 0cdfb142d..23a3dc938 100644
--- a/crates/uzu-engine/src/backends/metal/kernel/attention/attention_gemm.metal
+++ b/crates/uzu-engine/src/backends/metal/kernel/attention/attention_gemm.metal
@@ -160,7 +160,7 @@ KERNEL(AttentionGemm)(
} else {
query_loader.load_unsafe();
}
- query_loader.apply_inplace_op(TransformScale<T>(static_cast<T>(params.scale * M_LOG2E_F)));
+ query_loader.apply_inplace_op(::TransformScale<T>(static_cast<T>(params.scale * M_LOG2E_F)));
threadgroup_barrier(mem_flags::mem_threadgroup);
}
diff --git a/crates/uzu-engine/src/backends/metal/kernel/generated/gemm.h b/crates/uzu-engine/src/backends/metal/kernel/generated/gemm.h
index 1a7b47409..6a2af05cb 100644
--- a/crates/uzu-engine/src/backends/metal/kernel/generated/gemm.h
+++ b/crates/uzu-engine/src/backends/metal/kernel/generated/gemm.h
@@ -22,10 +22,9 @@ struct GemmDTransform {
constexpr GemmDTransform() thread : raw_value(0) {}
constexpr GemmDTransform(uint32_t __dsl_v) thread : raw_value(__dsl_v) {}
static constant constexpr uint32_t SCALE = 1 << 0;
- static constant constexpr uint32_t ACCUMULATE = 1 << 1;
- static constant constexpr uint32_t BIAS = 1 << 2;
- static constant constexpr uint32_t RHT = 1 << 3;
- static constant constexpr uint32_t SOFT_CAP = 1 << 4;
+ static constant constexpr uint32_t BIAS = 1 << 1;
+ static constant constexpr uint32_t RHT = 1 << 2;
+ static constant constexpr uint32_t SOFT_CAP = 1 << 3;
constexpr bool contains(uint32_t flag) const thread { return (raw_value & flag) != 0; }
constexpr bool contains(uint32_t flag) const constant { return (raw_value & flag) != 0; }
constexpr uint32_t bits() const thread { return raw_value; }
diff --git a/crates/uzu-engine/src/backends/metal/kernel/matmul/common/defines.h b/crates/uzu-engine/src/backends/metal/kernel/matmul/common/defines.h
index 93691392c..28c6667bf 100644
--- a/crates/uzu-engine/src/backends/metal/kernel/matmul/common/defines.h
+++ b/crates/uzu-engine/src/backends/metal/kernel/matmul/common/defines.h
@@ -33,27 +33,16 @@ using PointerElementType = typename PointerElementTypeImpl<T>::type;
template <typename OutputType, typename InputType>
struct TransformNone {
- TransformNone(float = 1.0f, float = 0.0f) {}
-
static METAL_FUNC OutputType apply(InputType x) { return static_cast<OutputType>(x); }
- METAL_FUNC OutputType apply(InputType x, OutputType) const { return static_cast<OutputType>(x); }
};
template <typename OutputType, typename InputType>
-struct TransformScaleAccumulate {
+struct TransformScale {
const float alpha;
- const float beta;
-
- TransformScaleAccumulate(float alpha, float beta) : alpha(alpha), beta(beta) {}
- static METAL_FUNC OutputType apply(InputType x) { return static_cast<OutputType>(x); }
+ TransformScale(float alpha) : alpha(alpha) {}
- METAL_FUNC OutputType apply(InputType x, OutputType c) const {
- return static_cast<OutputType>(
- x * static_cast<InputType>(alpha) +
- (beta != 0.0f ? (static_cast<OutputType>(beta) * c) : static_cast<OutputType>(0.0))
- );
- }
+ METAL_FUNC OutputType apply(InputType x) const { return static_cast<OutputType>(x * static_cast<InputType>(alpha)); }
};
} // namespace matmul
diff --git a/crates/uzu-engine/src/backends/metal/kernel/matmul/common/threadgroup_tile.h b/crates/uzu-engine/src/backends/metal/kernel/matmul/common/threadgroup_tile.h
index 8c688560a..9a3a0876e 100644
--- a/crates/uzu-engine/src/backends/metal/kernel/matmul/common/threadgroup_tile.h
+++ b/crates/uzu-engine/src/backends/metal/kernel/matmul/common/threadgroup_tile.h
@@ -128,27 +128,8 @@ struct ThreadgroupTile {
}
template <typename EpilogueOp>
- METAL_FUNC void apply_epilogue(const device DT* C, const int ld_c, const int cstride_c, thread const EpilogueOp& op) {
- const device DT* c_ptr = C + simdgroup_row_offset * ld_c + simdgroup_col_offset * cstride_c;
- for_each_output([&](ushort row_offset, ushort col_offset, ushort k, thread AccumulatorType& v) {
- v = op.apply(v, static_cast<AccumulatorType>(c_ptr[row_offset * ld_c + col_offset * cstride_c + k]));
- });
- }
-
- template <typename EpilogueOp>
- METAL_FUNC void apply_epilogue_safe(
- const device DT* C,
- const int ld_c,
- const int cstride_c,
- short2 tile_dimensions,
- thread const EpilogueOp& op
- ) {
- const device DT* c_ptr = C + simdgroup_row_offset * ld_c + simdgroup_col_offset * cstride_c;
- tile_dimensions -= short2(simdgroup_col_offset, simdgroup_row_offset);
- for_each_output([&](ushort row_offset, ushort col_offset, ushort k, thread AccumulatorType& v) {
- if (row_offset < tile_dimensions.y && col_offset + k < tile_dimensions.x)
- v = op.apply(v, static_cast<AccumulatorType>(c_ptr[row_offset * ld_c + col_offset * cstride_c + k]));
- });
+ METAL_FUNC void apply_epilogue(thread const EpilogueOp& op) {
+ c_fragment.map([&](AccumulatorType value) { return op.apply(value); });
}
METAL_FUNC void apply_bias(const device BT* bias) {
diff --git a/crates/uzu-engine/src/backends/metal/kernel/matmul/gemm/common/mxu_mma_core.h b/crates/uzu-engine/src/backends/metal/kernel/matmul/gemm/common/mxu_mma_core.h
index d89dba965..6b7133841 100644
--- a/crates/uzu-engine/src/backends/metal/kernel/matmul/gemm/common/mxu_mma_core.h
+++ b/crates/uzu-engine/src/backends/metal/kernel/matmul/gemm/common/mxu_mma_core.h
@@ -125,7 +125,6 @@ struct MxuMmaCore {
};
const bool apply_scale = output_transform.contains(GemmDTransform::SCALE);
- const bool apply_accumulate = output_transform.contains(GemmDTransform::ACCUMULATE);
const bool apply_bias = output_transform.contains(GemmDTransform::BIAS);
const bool apply_rht = output_transform.contains(GemmDTransform::RHT);
@@ -177,18 +176,6 @@ struct MxuMmaCore {
accumulator_tile.map([&](auto value) { return value * scale; });
}
- if (apply_accumulate) {
- uzu::matmul::Fragment<OutputElementType, TILES_M, TILES_N, uzu::matmul::MxuFragmentOps<>>
- existing_output;
- auto output_src = uzu::matmul::fragment_source(d_simdgroup, int(params->leading_dimension_d));
- if constexpr (!(aligned_m.value && aligned_n.value)) {
- output_src = output_src.bounded(simdgroup_limit_m, simdgroup_limit_n);
- }
- existing_output.load_from(thread_context.simd_lane_id, output_src);
- thread OutputElementType* existing_data = existing_output.elements();
- accumulator_tile.map([&](auto value) { return value + AccumulatorType(*(existing_data++)); });
- }
-
if (apply_bias && !apply_rht) {
accumulator_tile.map_coords(thread_context.simd_lane_id, [&](short, short col, auto value) {
if constexpr (aligned_n.value) {
diff --git a/crates/uzu-engine/src/backends/metal/kernel/matmul/gemm/common/simdgroup_mma_core.h b/crates/uzu-engine/src/backends/metal/kernel/matmul/gemm/common/simdgroup_mma_core.h
index e790b6181..1c5fb6e2e 100644
--- a/crates/uzu-engine/src/backends/metal/kernel/matmul/gemm/common/simdgroup_mma_core.h
+++ b/crates/uzu-engine/src/backends/metal/kernel/matmul/gemm/common/simdgroup_mma_core.h
@@ -139,7 +139,7 @@ struct SimdgroupMmaCore {
const thread ushort& tile_block_rows,
const thread ushort& tile_block_cols,
const bool needs_epilogue,
- const thread uzu::matmul::TransformScaleAccumulate<float, float>& epilogue,
+ const thread uzu::matmul::TransformScale<float, float>& epilogue,
const device RightElementType* bias_block,
const bool needs_bias,
const device int32_t* rht_factors_block,
@@ -147,19 +147,15 @@ struct SimdgroupMmaCore {
const thread ThreadContext& thread_context
) {
constexpr GemmAlignment gemm_alignment{GEMM_ALIGNMENT_RAW};
+ if (needs_epilogue) {
+ accumulator.apply_epilogue(epilogue);
+ }
if constexpr (gemm_alignment.contains(GemmAlignment::M) && gemm_alignment.contains(GemmAlignment::N)) {
- if (needs_epilogue) {
- accumulator.apply_epilogue(d, params->leading_dimension_d, 1, epilogue);
- }
if (needs_bias && !needs_rht) {
accumulator.apply_bias(bias_block);
}
accumulator.store_result(d, params->leading_dimension_d);
} else {
- if (needs_epilogue) {
- accumulator
- .apply_epilogue_safe(d, params->leading_dimension_d, 1, short2(tile_block_cols, tile_block_rows), epilogue);
- }
if (needs_bias && !needs_rht) {
accumulator.apply_bias_safe(bias_block, short2(tile_block_cols, tile_block_rows));
}
@@ -228,13 +224,9 @@ struct SimdgroupMmaCore {
const ushort leftover_block_depth = params->K - params->aligned_inner_iterations * THREADGROUP_BLOCK_K;
const bool needs_scale = output_transform.contains(GemmDTransform::SCALE);
- const bool needs_accumulate = output_transform.contains(GemmDTransform::ACCUMULATE);
const bool needs_bias = output_transform.contains(GemmDTransform::BIAS);
const bool needs_rht = output_transform.contains(GemmDTransform::RHT);
- const bool needs_epilogue = needs_scale || needs_accumulate;
- const float alpha = needs_scale ? params->ab_scale : 1.0f;
- const float beta = needs_accumulate ? 1.0f : 0.0f;
- uzu::matmul::TransformScaleAccumulate<float, float> epilogue(alpha, beta);
+ uzu::matmul::TransformScale<float, float> epilogue(params->ab_scale);
const device RightElementType* bias_block = output_bias + block_col;
const device int32_t* rht_factors_block = rht_factors + block_col;
@@ -267,7 +259,7 @@ struct SimdgroupMmaCore {
params,
tile_block_rows,
tile_block_cols,
- needs_epilogue,
+ needs_scale,
epilogue,
bias_block,
needs_bias,
diff --git a/crates/uzu-engine/src/backends/metal/kernel/matmul/gemm/gemm_split_k_reduce.metal b/crates/uzu-engine/src/backends/metal/kernel/matmul/gemm/gemm_split_k_reduce.metal
index 553259e9d..baaffa05e 100644
--- a/crates/uzu-engine/src/backends/metal/kernel/matmul/gemm/gemm_split_k_reduce.metal
+++ b/crates/uzu-engine/src/backends/metal/kernel/matmul/gemm/gemm_split_k_reduce.metal
@@ -48,9 +48,6 @@ KERNEL(GemmSplitKReduce)(
if (output_transform.contains(GemmDTransform::SCALE)) {
accumulator *= output_scale;
}
- if (output_transform.contains(GemmDTransform::ACCUMULATE)) {
- accumulator += float4(output_vectors[vector_index]);
- }
if (output_transform.contains(GemmDTransform::BIAS)) {
const uint column = (vector_index * 4u) % column_count;
accumulator += float4(*reinterpret_cast<const device vec<T, 4>*>(output_bias + column));
diff --git a/crates/uzu-engine/src/backends/metal/kernel/matmul/gemm/kernel.rs b/crates/uzu-engine/src/backends/metal/kernel/matmul/gemm/kernel.rs
index 158082bbf..684ae1c35 100644
--- a/crates/uzu-engine/src/backends/metal/kernel/matmul/gemm/kernel.rs
+++ b/crates/uzu-engine/src/backends/metal/kernel/matmul/gemm/kernel.rs
@@ -166,16 +166,6 @@ impl GemmKernel {
.validate_engine(plan.engine)
.map_err(|error| MetalError::KernelDispatchFailed(Box::new(error)))?;
- if !matches!(arguments.b, MatmulB::FullPrecision { .. })
- && arguments.output.ops.mask().contains(GemmDTransform::ACCUMULATE)
- {
- return Err(MatmulError::UnsupportedDOp {
- bit: GemmDTransform::ACCUMULATE,
- path: "QuantGemm",
- }
- .into());
- }
-
match arguments.b {
MatmulB::FullPrecision {
b: weights,
@@ -481,8 +471,7 @@ impl GemmKernel {
debug_assert_eq!(elem % 4, 0, "split-K reduce requires M*N divisible by 4");
let group_count = ((elem as u32) / 4).div_ceil(256);
- let reduce_transform =
- output_transform.intersection(GemmDTransform::SCALE | GemmDTransform::ACCUMULATE | GemmDTransform::BIAS);
+ let reduce_transform = output_transform.intersection(GemmDTransform::SCALE | GemmDTransform::BIAS);
let bias_arg = if reduce_transform.contains(GemmDTransform::BIAS) {
output_bias
} else {
diff --git a/crates/uzu-engine/src/backends/metal/kernel/matmul/gemv/common/epilogue.h b/crates/uzu-engine/src/backends/metal/kernel/matmul/gemv/common/epilogue.h
index 0bc642579..042dcced7 100644
--- a/crates/uzu-engine/src/backends/metal/kernel/matmul/gemv/common/epilogue.h
+++ b/crates/uzu-engine/src/backends/metal/kernel/matmul/gemv/common/epilogue.h
@@ -82,33 +82,22 @@ private:
if (!OutputTile<Tile, FULL_TILE>::row_in_range(global_row, params.out_vec_size)) {
return;
}
- if (tile.clamped && params.output_transform.contains(GemmDTransform::ACCUMULATE)) {
- return;
- }
if constexpr (STAGE_HADAMARD) {
shared_results[I * Tile::OUTPUT_ROWS + tile.local_row + R] =
- transform<false>(result[I][R], output + R, global_row, ops, params);
+ transform<false>(result[I][R], global_row, ops, params);
} else {
- output[R] = static_cast<DT>(transform<true>(result[I][R], output + R, global_row, ops, params));
+ output[R] = static_cast<DT>(transform<true>(result[I][R], global_row, ops, params));
}
});
});
}
template <bool APPLY_BIAS>
- static METAL_FUNC U transform(
- U value,
- const device DT* output,
- uint global_row,
- const thread GemvOperands<AT, BT, DT>& ops,
- const thread GemvParams& params
- ) {
+ static METAL_FUNC U
+ transform(U value, uint global_row, const thread GemvOperands<AT, BT, DT>& ops, const thread GemvParams& params) {
if (params.output_transform.contains(GemmDTransform::SCALE)) {
value *= params.ab_scale;
}
- if (params.output_transform.contains(GemmDTransform::ACCUMULATE)) {
- value += static_cast<U>(*output);
- }
if constexpr (APPLY_BIAS) {
if (params.output_transform.contains(GemmDTransform::BIAS)) {
value += static_cast<U>(ops.output_bias[global_row]);
diff --git a/crates/uzu-engine/src/backends/metal/kernel/matmul/gemv/common/tile.h b/crates/uzu-engine/src/backends/metal/kernel/matmul/gemv/common/tile.h
index d980352e9..aa969d239 100644
--- a/crates/uzu-engine/src/backends/metal/kernel/matmul/gemv/common/tile.h
+++ b/crates/uzu-engine/src/backends/metal/kernel/matmul/gemv/common/tile.h
@@ -69,7 +69,6 @@ struct OutputTile {
uint local_row;
uint row0;
bool writer;
- bool clamped;
static METAL_FUNC OutputTile
make(uint output_tile_idx, uint input_tile_idx, uint simd_group, uint simd_lane, uint out_vec_size) {
@@ -90,7 +89,6 @@ struct OutputTile {
tile.local_row = local_row;
tile.row0 = FULL_TILE ? unclamped : min(unclamped, last);
tile.writer = Tile::K_SPLIT == 1 || k_slice == 0;
- tile.clamped = !FULL_TILE && unclamped > last;
return tile;
}
diff --git a/crates/uzu-engine/src/backends/metal/kernel/matmul/gemv/kernel.rs b/crates/uzu-engine/src/backends/metal/kernel/matmul/gemv/kernel.rs
index ff949980c..a69d487f2 100644
--- a/crates/uzu-engine/src/backends/metal/kernel/matmul/gemv/kernel.rs
+++ b/crates/uzu-engine/src/backends/metal/kernel/matmul/gemv/kernel.rs
@@ -99,9 +99,6 @@ impl GemvSpecialization {
return None;
}
let output_transform = output_transform_for_tile(shape, tile)?;
- if shape.d_transform.contains(GemmDTransform::ACCUMULATE) && !shape.n.is_multiple_of(32) {
- return None;
- }
let bits = shape.b_bits.unwrap_or(0);
if !is_quant {
let mixed_precision = weights_data_type == DataType::F32
diff --git a/crates/uzu-engine/src/config/weight_matrix/hybrid_spec.rs b/crates/uzu-engine/src/config/weight_matrix/hybrid_spec.rs
index 8e578529e..332eda59c 100644
--- a/crates/uzu-engine/src/config/weight_matrix/hybrid_spec.rs
+++ b/crates/uzu-engine/src/config/weight_matrix/hybrid_spec.rs
@@ -1,6 +1,6 @@
use uzu_engine_macros::uzu_config;
-use crate::config::weight_matrix::AnyWeightMatrixSpec;
+use crate::{config::weight_matrix::AnyWeightMatrixSpec, utils::strict_serde::Unsupported};
#[uzu_config]
#[serde(rename_all = "snake_case")]
@@ -13,7 +13,7 @@ pub enum IncoherenceProcessingMode {
#[uzu_config(super::WeightMatrixSpec)]
pub struct HybridSpec {
pub quantization_spec: Box<AnyWeightMatrixSpec>,
- pub adapter_spec: Option<Box<AnyWeightMatrixSpec>>,
+ pub adapter_spec: Option<Unsupported>,
pub incoherence_block_size: Option<u32>,
pub incoherence_processing_mode: IncoherenceProcessingMode,
}
diff --git a/crates/uzu-engine/src/config/weight_matrix/low_rank_spec.rs b/crates/uzu-engine/src/config/weight_matrix/low_rank_spec.rs
deleted file mode 100644
index 9ac41a646..000000000
--- a/crates/uzu-engine/src/config/weight_matrix/low_rank_spec.rs
+++ /dev/null
@@ -1,6 +0,0 @@
-use uzu_engine_macros::uzu_config;
-
-#[uzu_config(super::WeightMatrixSpec)]
-pub struct LowRankSpec {
- pub rank: u32,
-}
diff --git a/crates/uzu-engine/src/config/weight_matrix/mod.rs b/crates/uzu-engine/src/config/weight_matrix/mod.rs
index 3f8b789a8..bf70fa20b 100644
--- a/crates/uzu-engine/src/config/weight_matrix/mod.rs
+++ b/crates/uzu-engine/src/config/weight_matrix/mod.rs
@@ -4,7 +4,6 @@ pub mod d4s4_spec;
pub mod full_precision_spec;
pub mod hybrid_spec;
pub mod int_spec;
-pub mod low_rank_spec;
pub mod mlx_spec;
#[uzu_config]
@@ -16,7 +15,6 @@ pub enum Layout {
#[uzu_config_abstract(
full_precision_spec::FullPrecisionSpec,
- low_rank_spec::LowRankSpec,
hybrid_spec::HybridSpec,
int_spec::IntSpec,
mlx_spec::MLXSpec,
diff --git a/crates/uzu-engine/src/encodable_block/classifier.rs b/crates/uzu-engine/src/encodable_block/classifier.rs
index fc24277d2..05fa33cad 100644
--- a/crates/uzu-engine/src/encodable_block/classifier.rs
+++ b/crates/uzu-engine/src/encodable_block/classifier.rs
@@ -46,37 +46,37 @@ pub struct Classifier<B: Backend> {
impl<B: Backend> Classifier<B> {
pub fn new(
- context: &B::Context,
+ data_type: DataType,
config: &ClassifierConfig,
parameter_tree: &ParameterTree<B>,
- data_type: DataType,
+ context: &B::Context,
) -> Result<Self, ClassifierError<B>> {
let (embedding, _) = Embedding::new(
- context,
config.vocab_size,
config.transformer_config.model_dim,
+ data_type,
&config.embedding_config,
&parameter_tree.subtree("embedding"),
- data_type,
+ context,
)?;
let embedding_norm = Normalization::new(
config.transformer_config.model_dim,
+ data_type,
None,
ShortcutMode::None,
PostLayerScalar::None,
- data_type,
&config.embedding_norm_config,
&parameter_tree.subtree("embedding_norm"),
context,
)?;
let transformer = Transformer::new(
- context,
- None,
data_type,
+ None,
&config.transformer_config,
&parameter_tree.subtree("transformer"),
+ context,
)?;
if config.classifier_pooling != PoolingType::Mean {
diff --git a/crates/uzu-engine/src/encodable_block/decoder.rs b/crates/uzu-engine/src/encodable_block/decoder.rs
index 5c7dfcfc2..e3a3242aa 100644
--- a/crates/uzu-engine/src/encodable_block/decoder.rs
+++ b/crates/uzu-engine/src/encodable_block/decoder.rs
@@ -50,18 +50,18 @@ impl<B: Backend> Decoder<B> {
}
pub fn new(
- context: &B::Context,
+ data_type: DataType,
config: &DecoderConfig,
parameter_tree: &ParameterTree<B>,
- data_type: DataType,
+ context: &B::Context,
) -> Result<Self, DecoderError<B>> {
let (embedding, readout_input_hadamard_factors) = Embedding::new(
- context,
config.vocab_size,
config.transformer_config.model_dim,
+ data_type,
&config.embedding_config,
&parameter_tree.subtree("embedding"),
- data_type,
+ context,
)?;
let embedding_norm = config
@@ -70,10 +70,10 @@ impl<B: Backend> Decoder<B> {
.map(|norm_config| {
Normalization::new(
config.transformer_config.model_dim,
+ data_type,
None,
ShortcutMode::None,
PostLayerScalar::None,
- data_type,
norm_config,
&parameter_tree.subtree("embedding_norm"),
context,
@@ -88,22 +88,22 @@ impl<B: Backend> Decoder<B> {
"per-layer embedding num_layers must match transformer layer count"
);
Some(PerLayerEmbedding::new(
- context,
- ple_config,
config.transformer_config.model_dim,
data_type,
+ ple_config,
&parameter_tree.subtree("per_layer_embedding"),
+ context,
)?)
} else {
None
};
let transformer = Transformer::new(
- context,
- readout_input_hadamard_factors,
data_type,
+ readout_input_hadamard_factors,
&config.transformer_config,
&parameter_tree.subtree("transformer"),
+ context,
)?;
Ok(Self {
@@ -180,8 +180,8 @@ impl<B: Backend> Decoder<B> {
let logits = if let Some(output_range) = output_range {
let output = transformer_output.output.as_ref().expect("decoder output range requires transformer output");
Some(self.embedding.encode_readout(
- output_range.end - output_range.start,
output,
+ output_range.end - output_range.start,
self.embedding.vocab_size(),
None::<&B::ScratchBuffer>,
true,
diff --git a/crates/uzu-engine/src/encodable_block/dflash.rs b/crates/uzu-engine/src/encodable_block/dflash.rs
index 67d38fd36..e2a749989 100644
--- a/crates/uzu-engine/src/encodable_block/dflash.rs
+++ b/crates/uzu-engine/src/encodable_block/dflash.rs
@@ -20,7 +20,7 @@ use crate::{
ATTENTION_SUFFIX_CAPACITY, Attention, AttentionNewError, AttentionState, rope::PrecalculatedRoPE,
},
},
- mlp::MlpBlockError,
+ mlp::MlpBlockNewError,
normalization::{Normalization, NormalizationNewError, PostLayerScalar, ShortcutMode},
transformer_layer::{TransformerLayer, TransformerLayerError},
},
@@ -68,7 +68,7 @@ pub enum DFlashNewError<B: Backend> {
#[error("Normalization error: {0}")]
Normalization(#[from] NormalizationNewError<B>),
#[error("MLP error: {0}")]
- Mlp(#[from] MlpBlockError<B>),
+ Mlp(#[from] MlpBlockNewError<B>),
#[error("Attention error: {0}")]
Attention(#[from] AttentionNewError<B>),
#[error("Transformer layer error: {0}")]
@@ -89,27 +89,27 @@ pub enum DFlashEncodeError<B: Backend> {
impl<B: Backend> DFlash<B> {
pub fn new(
- context: &B::Context,
+ data_type: DataType,
config: &DFlashDraftConfig,
parameter_tree: &ParameterTree<B>,
- data_type: DataType,
+ context: &B::Context,
) -> Result<Self, DFlashNewError<B>> {
let mask_token_id = config.mask_token_id as u32;
assert!(config.block_size <= ATTENTION_SUFFIX_CAPACITY, "DFlash block_size exceeds attention suffix capacity");
let target_feature_projection = <dyn Linear<B>>::new(
config.model_dim * config.target_layer_ids.len() as u32,
- [config.model_dim],
- false,
- context,
+ config.model_dim,
data_type,
+ false,
&parameter_tree.subtree("context_projection"),
+ context,
)?;
let projected_feature_norm = Normalization::new(
config.model_dim,
+ data_type,
None,
ShortcutMode::None,
PostLayerScalar::None,
- data_type,
&config.context_norm_config,
&parameter_tree.subtree("context_norm"),
context,
@@ -123,11 +123,11 @@ impl<B: Backend> DFlash<B> {
let num_layers = config.layer_configs.len() as u32;
let state_kv_projection = <dyn Linear<B>>::new(
config.model_dim,
- [num_layers * layer_kv_dim],
- false,
- context,
+ num_layers * layer_kv_dim,
data_type,
+ false,
&parameter_tree.subtree("state_kv_projection"),
+ context,
)?;
let layers = config
.layer_configs
@@ -135,23 +135,23 @@ impl<B: Backend> DFlash<B> {
.zip(0u32..)
.map(|(layer_config, index)| {
TransformerLayer::new(
- context,
config.model_dim,
config.hidden_dim,
num_layers,
- layer_config,
index,
- &layers_tree.subtree(&index.to_string()),
data_type,
+ layer_config,
+ &layers_tree.subtree(&index.to_string()),
+ context,
)
})
.collect::<Result<Box<[_]>, TransformerLayerError<B>>>()?;
let output_norm = Normalization::new(
config.model_dim,
+ data_type,
None,
ShortcutMode::Add,
PostLayerScalar::None,
- data_type,
&config.output_norm_config,
&parameter_tree.subtree("output_norm"),
context,
@@ -198,9 +198,9 @@ impl<B: Backend> DFlash<B> {
pub fn encode_accept(
&self,
- state: &mut DFlashState<B>,
target_features: impl ExactSizeIterator<Item = impl BufferRef<Backend = B>>,
accepted_indices: &[u32],
+ state: &mut DFlashState<B>,
command_buffer: &mut <B::CommandBuffer as CommandBuffer>::Encoding,
) -> Result<(), B::Error> {
if accepted_indices.is_empty() {
@@ -279,10 +279,10 @@ impl<B: Backend> DFlash<B> {
pub fn encode_draft(
&self,
- state: &mut DFlashState<B>,
- target_output_token: u32,
target_embedding: &Embedding<B>,
+ target_output_token: u32,
batch_size: u32,
+ state: &mut DFlashState<B>,
command_buffer: &mut <B::CommandBuffer as CommandBuffer>::Encoding,
) -> Result<DFlashOutput<B>, DFlashEncodeError<B>> {
let command_buffer = &mut *command_buffer.debug_group("dflash draft");
@@ -338,8 +338,8 @@ impl<B: Backend> DFlash<B> {
command_buffer.allocate_scratch(lookahead_rows.iter().len()).map_err(DFlashEncodeError::Backend)?;
command_buffer.encode_copy(draft_hidden.subrange(lookahead_rows), &mut lookahead_hidden);
let logits = target_embedding.encode_readout(
- batch_size - 1,
&lookahead_hidden,
+ batch_size - 1,
target_embedding.vocab_size(),
None::<&B::ScratchBuffer>,
false,
diff --git a/crates/uzu-engine/src/encodable_block/embedding.rs b/crates/uzu-engine/src/encodable_block/embedding.rs
index d64fa10a2..88b293a90 100644
--- a/crates/uzu-engine/src/encodable_block/embedding.rs
+++ b/crates/uzu-engine/src/encodable_block/embedding.rs
@@ -69,17 +69,17 @@ impl<B: Backend> Embedding<B> {
}
pub fn new(
- context: &B::Context,
vocab_size: u32,
model_dim: u32,
+ data_type: DataType,
config: &AnyEmbeddingConfig,
parameter_tree: &ParameterTree<B>,
- data_type: DataType,
+ context: &B::Context,
) -> Result<(Self, Option<B::GlobalBuffer>), EmbeddingError<B>> {
let (tying, readout_input_hadamard_factors) = match config {
AnyEmbeddingConfig::TiedEmbeddingConfig(_) => {
let embedding_tree = parameter_tree.subtree("embedding");
- let table = EmbeddingTable::load(context, &embedding_tree, vocab_size, model_dim, data_type)?;
+ let table = EmbeddingTable::load(vocab_size, model_dim, data_type, &embedding_tree, context)?;
if table.as_matrix().is_none() {
return Err(EmbeddingError::UnsupportedConfiguration("tied embeddings need a matrix table".into()));
}
@@ -101,16 +101,16 @@ impl<B: Backend> Embedding<B> {
AnyEmbeddingConfig::UntiedEmbeddingConfig(_) => {
let input_embedding_tree = parameter_tree.subtree("input_embedding");
let input_table =
- EmbeddingTable::load(context, &input_embedding_tree, vocab_size, model_dim, data_type)?;
+ EmbeddingTable::load(vocab_size, model_dim, data_type, &input_embedding_tree, context)?;
let output_embedding_tree = parameter_tree.subtree("output_embedding");
let output_embedding_spec = output_embedding_tree.metadata("spec")?;
let output = UntiedReadout::load(
- context,
- &output_embedding_tree,
- output_embedding_spec,
vocab_size,
model_dim,
data_type,
+ output_embedding_spec,
+ &output_embedding_tree,
+ context,
)?;
(
EmbeddingTying::Untied {
@@ -178,8 +178,8 @@ impl<B: Backend> Embedding<B> {
pub fn encode_readout(
&self,
- batch_dim: u32,
input_buffer: impl BufferRef<Backend = B>,
+ batch_dim: u32,
output_dim: u32,
gather_indices: Option<impl BufferRef<Backend = B>>,
apply_logit_transform: bool,
diff --git a/crates/uzu-engine/src/encodable_block/embedding_table.rs b/crates/uzu-engine/src/encodable_block/embedding_table.rs
index 7dae6806a..5d9f67598 100644
--- a/crates/uzu-engine/src/encodable_block/embedding_table.rs
+++ b/crates/uzu-engine/src/encodable_block/embedding_table.rs
@@ -90,11 +90,11 @@ pub struct EmbeddingTable<B: Backend> {
impl<B: Backend> EmbeddingTable<B> {
pub fn load(
- context: &B::Context,
- tree: &ParameterTree<B>,
vocab_size: u32,
embedding_dim: u32,
data_type: DataType,
+ tree: &ParameterTree<B>,
+ context: &B::Context,
) -> Result<Self, EmbeddingTableError<B>> {
if !matches!(data_type, DataType::F32 | DataType::BF16) {
return Err(EmbeddingTableError::UnsupportedConfiguration(format!(
@@ -102,7 +102,7 @@ impl<B: Backend> EmbeddingTable<B> {
)));
}
let load_matrix = |tree: &ParameterTree<B>, spec| {
- WeightMatrix::load(tree, spec, Layout::InputOutput, embedding_dim, vocab_size, data_type)
+ WeightMatrix::load(embedding_dim, vocab_size, data_type, spec, Layout::InputOutput, tree)
};
let (storage, output_hadamard_factors) = match tree.metadata::<AnyWeightMatrixSpec>("spec")? {
AnyWeightMatrixSpec::D4S4Spec(spec) => {
@@ -111,7 +111,6 @@ impl<B: Backend> EmbeddingTable<B> {
},
AnyWeightMatrixSpec::HybridSpec(HybridSpec {
quantization_spec,
- adapter_spec: None,
incoherence_block_size: Some(HADAMARD_TRANSFORM_BLOCK_SIZE),
incoherence_processing_mode: IncoherenceProcessingMode::Output,
..
diff --git a/crates/uzu-engine/src/encodable_block/linear/input_rht.rs b/crates/uzu-engine/src/encodable_block/linear/input_rht.rs
index 2c82b4d93..47ad13a45 100644
--- a/crates/uzu-engine/src/encodable_block/linear/input_rht.rs
+++ b/crates/uzu-engine/src/encodable_block/linear/input_rht.rs
@@ -17,10 +17,10 @@ pub(super) struct InputRht<B: Backend> {
impl<B: Backend> InputRht<B> {
pub(super) fn new(
- context: &B::Context,
data_type: DataType,
preparation: LinearInputPreparation<B>,
in_place: bool,
+ context: &B::Context,
) -> Result<Self, B::Error> {
let LinearInputPreparation {
rht_signs,
diff --git a/crates/uzu-engine/src/encodable_block/linear/matmul.rs b/crates/uzu-engine/src/encodable_block/linear/matmul.rs
index b1fcce5dd..4f619f2df 100644
--- a/crates/uzu-engine/src/encodable_block/linear/matmul.rs
+++ b/crates/uzu-engine/src/encodable_block/linear/matmul.rs
@@ -66,16 +66,16 @@ impl<B: Backend> LinearMatmul<B> {
/// Loads a linear over any parsed spec — full precision, MLX or Int. Hybrid
/// compositions live in the wrappers, not here.
pub fn load(
- context: &B::Context,
- spec: AnyWeightMatrixSpec,
input_dim: u32,
output_dim: u32,
weights_data_type: DataType,
input_data_type: DataType,
output_data_type: DataType,
+ spec: AnyWeightMatrixSpec,
+ output_hadamard_factors: Option<B::GlobalBuffer>,
weights_tree: &ParameterTree<B>,
bias_tree: Option<&ParameterTree<B>>,
- output_hadamard_factors: Option<B::GlobalBuffer>,
+ context: &B::Context,
) -> Result<Self, LinearMatmulError<B>> {
for data_type in [weights_data_type, input_data_type, output_data_type] {
if !matches!(data_type, DataType::BF16 | DataType::F32) {
@@ -84,7 +84,7 @@ impl<B: Backend> LinearMatmul<B> {
}
let matrix =
- WeightMatrix::load(weights_tree, spec, Layout::OutputInput, output_dim, input_dim, weights_data_type)?;
+ WeightMatrix::load(output_dim, input_dim, weights_data_type, spec, Layout::OutputInput, weights_tree)?;
if output_hadamard_factors.is_some() && matrix.quantization().is_none() {
return Err(LinearMatmulError::UnsupportedConfiguration(
"fused output-hadamard factors require quantized weights".into(),
@@ -184,23 +184,6 @@ impl<B: Backend> LinearMatmul<B> {
}
impl<B: Backend> Linear<B> for LinearMatmul<B> {
- fn encode(
- &self,
- input: B::ScratchBuffer,
- batch_dim: u32,
- command_buffer: &mut <B::CommandBuffer as CommandBuffer>::Encoding,
- ) -> Result<B::ScratchBuffer, B::Error> {
- self.encode_with_a(
- MatmulA::FullPrecision {
- values: &input,
- offset: 0,
- },
- batch_dim,
- None::<Gather<&B::ScratchBuffer>>,
- command_buffer,
- )
- }
-
fn encode_input(
&self,
input: LinearInput<B>,
diff --git a/crates/uzu-engine/src/encodable_block/linear/mod.rs b/crates/uzu-engine/src/encodable_block/linear/mod.rs
index 78dfdfb93..7d42396b9 100644
--- a/crates/uzu-engine/src/encodable_block/linear/mod.rs
+++ b/crates/uzu-engine/src/encodable_block/linear/mod.rs
@@ -3,12 +3,10 @@ use thiserror::Error;
mod input_rht;
mod matmul;
-mod qlora_wrapper;
mod rht_wrapper;
mod untied_readout;
pub use matmul::{LinearMatmul, LinearMatmulError};
-pub use qlora_wrapper::{QLoRALinearWrapper, QLoRALinearWrapperError};
pub use rht_wrapper::{RHTLinearWrapper, RHTLinearWrapperError};
pub use untied_readout::UntiedReadout;
@@ -35,23 +33,16 @@ pub trait Linear<B: Backend>: Send + Sync {
input: B::ScratchBuffer,
batch_dim: u32,
command_buffer: &mut <B::CommandBuffer as CommandBuffer>::Encoding,
- ) -> Result<B::ScratchBuffer, B::Error>;
+ ) -> Result<B::ScratchBuffer, B::Error> {
+ self.encode_input(LinearInput::FullPrecision(input), batch_dim, command_buffer)
+ }
fn encode_input(
&self,
input: LinearInput<B>,
batch_dim: u32,
command_buffer: &mut <B::CommandBuffer as CommandBuffer>::Encoding,
- ) -> Result<B::ScratchBuffer, B::Error> {
- match input {
- LinearInput::FullPrecision(input) => self.encode(input, batch_dim, command_buffer),
- LinearInput::Int8Symmetric {
- ..
- } => {
- panic!("linear does not support pre-quantized activations")
- },
- }
- }
+ ) -> Result<B::ScratchBuffer, B::Error>;
fn select_activation_format(
&self,
@@ -111,8 +102,6 @@ pub struct LinearInputPreparation<B: Backend> {
pub enum LinearBlockError<B: Backend> {
#[error("LinearMatmul error: {0}")]
LinearMatmulError(#[from] LinearMatmulError<B>),
- #[error("QLoRALinearWrapper error: {0}")]
- QLoRALinearWrapperError(#[from] QLoRALinearWrapperError<B>),
#[error("RHTLinearWrapper error: {0}")]
RHTLinearWrapperError(#[from] RHTLinearWrapperError<B>),
#[error("Parameter loading error: {0}")]
@@ -124,15 +113,14 @@ pub enum LinearBlockError<B: Backend> {
impl<B: Backend> dyn Linear<B> {
pub fn new_mixed_precision(
input_dimension: u32,
- output_dimensions: impl AsRef<[u32]>,
- has_biases: bool,
- context: &B::Context,
+ 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<Box<dyn Linear<B>>, LinearBlockError<B>> {
- let output_dimension_sum: u32 = output_dimensions.as_ref().iter().sum();
let weights_tree = parameter_tree.subtree("weights");
let spec = weights_tree.metadata::<AnyWeightMatrixSpec>("spec")?;
match spec {
@@ -140,175 +128,146 @@ impl<B: Backend> dyn Linear<B> {
| AnyWeightMatrixSpec::MLXSpec(_)
| AnyWeightMatrixSpec::IntSpec(_)) => {
let block = LinearMatmul::load(
- context,
- spec,
input_dimension,
- output_dimension_sum,
+ output_dimension,
weights_data_type,
input_data_type,
output_data_type,
+ spec,
+ None,
&weights_tree,
has_biases.then_some(parameter_tree),
- None,
+ context,
)?;
Ok(Box::new(block))
},
AnyWeightMatrixSpec::HybridSpec(HybridSpec {
- adapter_spec: None,
incoherence_block_size: Some(block_size),
incoherence_processing_mode: IncoherenceProcessingMode::InputOutput,
..
}) if block_size == HADAMARD_TRANSFORM_BLOCK_SIZE => Ok(Box::new(RHTLinearWrapper::new(
- context,
input_dimension,
- output_dimension_sum,
- has_biases,
+ output_dimension,
weights_data_type,
input_data_type,
output_data_type,
+ has_biases,
parameter_tree,
+ context,
)?)),
- AnyWeightMatrixSpec::HybridSpec(HybridSpec {
- quantization_spec,
- adapter_spec: Some(adapter_spec),
- incoherence_block_size,
- incoherence_processing_mode,
- ..
- }) => {
- assert!(!has_biases, "QLoRA linear with biases is not supported");
- let adapter_spec = *adapter_spec;
- let AnyWeightMatrixSpec::LowRankSpec(adapter_spec) = adapter_spec else {
- return Err(LinearBlockError::UnsupportedConfiguration(format!("{adapter_spec:?}")));
- };
- Ok(Box::new(QLoRALinearWrapper::new(
- context,
- *quantization_spec,
- adapter_spec,
- incoherence_block_size,
- incoherence_processing_mode,
- input_dimension,
- output_dimension_sum,
- weights_data_type,
- input_data_type,
- output_data_type,
- &weights_tree,
- )?))
- },
spec => Err(LinearBlockError::UnsupportedConfiguration(format!("{spec:?}"))),
}
}
pub fn new(
input_dimension: u32,
- output_dimensions: impl AsRef<[u32]>,
- has_biases: bool,
- context: &B::Context,
+ output_dimension: u32,
data_type: DataType,
+ has_biases: bool,
parameter_tree: &ParameterTree<B>,
+ context: &B::Context,
) -> Result<Box<dyn Linear<B>>, LinearBlockError<B>> {
Self::new_mixed_precision(
input_dimension,
- output_dimensions,
- has_biases,
- context,
+ output_dimension,
data_type,
data_type,
data_type,
+ has_biases,
parameter_tree,
+ context,
)
}
pub fn new_with_input_rht_mixed_precision(
input_dimension: u32,
- output_dimensions: impl AsRef<[u32]>,
- has_biases: bool,
- context: &B::Context,
+ 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<(Box<dyn Linear<B>>, Option<B::GlobalBuffer>), LinearBlockError<B>> {
- let output_dimension_sum: u32 = output_dimensions.as_ref().iter().sum();
if let Some(linear) = RHTLinearWrapper::try_new_with_input_preparation(
- context,
input_dimension,
- output_dimension_sum,
- has_biases,
+ output_dimension,
weights_data_type,
input_data_type,
output_data_type,
+ has_biases,
false,
parameter_tree,
+ context,
)? {
return Ok((linear.0, linear.1.map(|preparation| preparation.rht_signs)));
}
let linear = Self::new_mixed_precision(
input_dimension,
- output_dimensions,
- has_biases,
- context,
+ output_dimension,
weights_data_type,
input_data_type,
output_data_type,
+ has_biases,
parameter_tree,
+ context,
)?;
Ok((linear, None))
}
pub fn new_for_fused_input(
input_dimension: u32,
- output_dimensions: impl AsRef<[u32]>,
- has_biases: bool,
- context: &B::Context,
+ output_dimension: u32,
data_type: DataType,
+ has_biases: bool,
parameter_tree: &ParameterTree<B>,
+ context: &B::Context,
) -> Result<(Box<dyn Linear<B>>, Option<LinearInputPreparation<B>>), LinearBlockError<B>> {
- let output_dimension_sum: u32 = output_dimensions.as_ref().iter().sum();
if let Some(linear) = RHTLinearWrapper::try_new_with_input_preparation(
- context,
input_dimension,
- output_dimension_sum,
- has_biases,
+ output_dimension,
data_type,
data_type,
data_type,
+ has_biases,
true,
parameter_tree,
+ context,
)? {
return Ok(linear);
}
let linear = Self::new_mixed_precision(
input_dimension,
- output_dimensions,
- has_biases,
- context,
+ output_dimension,
data_type,
data_type,
data_type,
+ has_biases,
parameter_tree,
+ context,
)?;
Ok((linear, None))
}
pub fn new_with_input_rht(
input_dimension: u32,
- output_dimensions: impl AsRef<[u32]>,
- has_biases: bool,
- context: &B::Context,
+ output_dimension: u32,
data_type: DataType,
+ has_biases: bool,
parameter_tree: &ParameterTree<B>,
+ context: &B::Context,
) -> Result<(Box<dyn Linear<B>>, Option<B::GlobalBuffer>), LinearBlockError<B>> {
Self::new_with_input_rht_mixed_precision(
input_dimension,
- output_dimensions,
- has_biases,
- context,
+ output_dimension,
data_type,
data_type,
data_type,
+ has_biases,
parameter_tree,
+ context,
)
}
}
diff --git a/crates/uzu-engine/src/encodable_block/linear/qlora_wrapper.rs b/crates/uzu-engine/src/encodable_block/linear/qlora_wrapper.rs
deleted file mode 100644
index a98d5599f..000000000
--- a/crates/uzu-engine/src/encodable_block/linear/qlora_wrapper.rs
+++ /dev/null
@@ -1,266 +0,0 @@
-use derive_more::Debug;
-use parking_lot::Mutex;
-use thiserror::Error;
-
-use crate::{
- backends::common::{
- Backend, CommandBuffer, CommandBufferEncoding,
- gpu_types::HADAMARD_TRANSFORM_BLOCK_SIZE,
- kernel::{
- ActivationTransform, Kernels,
- matmul::{MatmulA, MatmulArguments, MatmulB, MatmulDOps, MatmulKernel, MatmulOutput},
- },
- },
- config::weight_matrix::{AnyWeightMatrixSpec, hybrid_spec::IncoherenceProcessingMode, low_rank_spec::LowRankSpec},
- data_type::DataType,
- encodable_block::{
- linear::{Linear, LinearMatmul, LinearMatmulError},
- weight_matrix::{WeightMatrixError, parse_spec},
- },
- parameters::{ParameterLoaderError, ParameterTree},
-};
-
-#[derive(Debug, Error)]
-pub enum QLoRALinearWrapperError<B: Backend> {
- #[error("LinearMatmul error: {0}")]
- LinearMatmulError(#[from] LinearMatmulError<B>),
- #[error("Weight matrix error: {0}")]
- WeightMatrix(#[from] WeightMatrixError<B>),
- #[error("Parameter loader error: {0}")]
- ParameterLoaderError(#[from] ParameterLoaderError<B>),
- #[error("Backend error: {0}")]
- BackendError(#[source] B::Error),
- #[error("Unsupported QLoRA linear configuration: {0}")]
- UnsupportedConfiguration(String),
-}
-
-pub struct QLoRALinearWrapper<B: Backend> {
- base_linear: LinearMatmul<B>,
- input_hadamard: Option<(ActivationTransform<B>, B::GlobalBuffer)>,
- output_hadamard: Option<(ActivationTransform<B>, B::GlobalBuffer)>,
- adapter_down_kernel: Mutex<<B::Kernels as Kernels>::MatmulKernel>,
- adapter_up_kernel: Mutex<<B::Kernels as Kernels>::MatmulKernel>,
- adapter_down: B::GlobalBuffer,
- adapter_up: B::GlobalBuffer,
- input_dim: u32,
- output_dim: u32,
- lora_rank: u32,
- weights_data_type: DataType,
- input_data_type: DataType,
-}
-
-impl<B: Backend> QLoRALinearWrapper<B> {
- pub fn new(
- context: &B::Context,
- quantization_spec: AnyWeightMatrixSpec,
- adapter_spec: LowRankSpec,
- incoherence_block_size: Option<u32>,
- incoherence_processing_mode: IncoherenceProcessingMode,
- input_dim: u32,
- output_dim: u32,
- weights_data_type: DataType,
- input_data_type: DataType,
- output_data_type: DataType,
- weights_tree: &ParameterTree<B>,
- ) -> Result<Self, QLoRALinearWrapperError<B>> {
- let use_incoherence_signs = match (incoherence_block_size, incoherence_processing_mode) {
- (None, _) => false,
- (Some(block_size), IncoherenceProcessingMode::InputOutput)
- if block_size == HADAMARD_TRANSFORM_BLOCK_SIZE =>
- {
- true
- },
- (incoherence_block_size, incoherence_processing_mode) => {
- return Err(QLoRALinearWrapperError::UnsupportedConfiguration(format!(
- "incoherence block_size={incoherence_block_size:?}, processing_mode={incoherence_processing_mode:?}"
- )));
- },
- };
-
- let quantized_tree = weights_tree.subtree("quantized");
- let parsed = parse_spec::<B>(&quantization_spec)?;
- let Some(_) = parsed.quantization else {
- return Err(QLoRALinearWrapperError::UnsupportedConfiguration(
- "QLoRA requires a quantized base spec".into(),
- ));
- };
- let base_linear = LinearMatmul::load(
- context,
- quantization_spec,
- input_dim,
- output_dim,
- weights_data_type,
- input_data_type,
- output_data_type,
- &quantized_tree,
- None,
- None,
- )?;
-
- let (input_hadamard, output_hadamard) = if use_incoherence_signs {
- let input_factors = weights_tree
- .leaf("incoherence_signs.input_signs")?
- .validate(&[input_dim], DataType::I32)?
- .read_buffer()?;
- let output_factors = weights_tree
- .leaf("incoherence_signs.output_signs")?
- .validate(&[output_dim], DataType::I32)?
- .read_buffer()?;
- (
- Some((
- ActivationTransform::input_rht(context, input_data_type, false)
- .map_err(QLoRALinearWrapperError::BackendError)?,
- input_factors,
- )),
- Some((
- ActivationTransform::output_rht(context, output_data_type, None, true)
- .map_err(QLoRALinearWrapperError::BackendError)?,
- output_factors,
- )),
- )
- } else {
- (None, None)
- };
-
- let adapter_down_kernel = Mutex::new(
- <<B::Kernels as Kernels>::MatmulKernel as MatmulKernel>::new(
- context,
- weights_data_type,
- input_data_type,
- weights_data_type,
- )
- .map_err(QLoRALinearWrapperError::BackendError)?,
- );
- let adapter_up_kernel = Mutex::new(
- <<B::Kernels as Kernels>::MatmulKernel as MatmulKernel>::new(
- context,
- weights_data_type,
- weights_data_type,
- output_data_type,
- )
- .map_err(QLoRALinearWrapperError::BackendError)?,
- );
-
- let adapter_down = weights_tree
- .leaf("adapter.down_projection")?
- .validate(&[adapter_spec.rank, input_dim], weights_data_type)?
- .read_buffer()?;
-
- let adapter_up = weights_tree
- .leaf("adapter.up_projection")?
- .validate(&[output_dim, adapter_spec.rank], weights_data_type)?
- .read_buffer()?;
-
- Ok(Self {
- base_linear,
- input_hadamard,
- output_hadamard,
- adapter_down_kernel,
- adapter_up_kernel,
- adapter_down,
- adapter_up,
- input_dim,
- output_dim,
- lora_rank: adapter_spec.rank,
- weights_data_type,
- input_data_type,
- })
- }
-}
-
-impl<B: Backend> Linear<B> for QLoRALinearWrapper<B> {
- fn encode(
- &self,
- input: B::ScratchBuffer,
- batch_dim: u32,
- command_buffer: &mut <B::CommandBuffer as CommandBuffer>::Encoding,
- ) -> Result<B::ScratchBuffer, B::Error> {
- let command_buffer = &mut *command_buffer.debug_group("linear (qlora)");
-
- let mut intermediate =
- command_buffer.allocate_scratch_for_shape(&[batch_dim, self.lora_rank], self.weights_data_type)?;
-
- {
- let mut adapter_kernel = self.adapter_down_kernel.lock();
- adapter_kernel.encode(
- MatmulArguments {
- a: MatmulA::FullPrecision {
- values: &input,
- offset: 0,
- },
- b: MatmulB::FullPrecision {
- b: &self.adapter_down,
- },
- b_leading_dimension: None,
- b_transpose: true,
- output: MatmulOutput::new(&mut intermediate, MatmulDOps::none()),
- gather_indices: None::<&B::ScratchBuffer>,
- m: batch_dim,
- n: self.lora_rank,
- k: self.input_dim,
- },
- command_buffer,
- )?;
- }
-
- let base_input = if let Some((input_hadamard_kernel, input_factors)) = &self.input_hadamard {
- let mut base_input =
- command_buffer.allocate_scratch_for_shape(&[batch_dim, self.input_dim], self.input_data_type)?;
- input_hadamard_kernel.encode_fp(
- &input,
- &mut base_input,
- input_factors,
- batch_dim,
- self.input_dim,
- command_buffer,
- );
- base_input
- } else {
- input
- };
-
- let mut output = self.base_linear.encode(base_input, batch_dim, command_buffer)?;
-
- {
- let mut adapter_kernel = self.adapter_up_kernel.lock();
- adapter_kernel.encode(
- MatmulArguments {
- a: MatmulA::FullPrecision {
- values: &intermediate,
- offset: 0,
- },
- b: MatmulB::FullPrecision {
- b: &self.adapter_up,
- },
- b_leading_dimension: None,
- b_transpose: true,
- output: MatmulOutput::new(
- &mut output,
- MatmulDOps {
- accumulate: true,
- ..MatmulDOps::none()
- },
- ),
- gather_indices: None::<&B::ScratchBuffer>,
- m: batch_dim,
- n: self.output_dim,
- k: self.lora_rank,
- },
- command_buffer,
- )?;
- }
-
- if let Some((output_hadamard_kernel, output_factors)) = &self.output_hadamard {
- output_hadamard_kernel.encode_fp_in_place(
- &mut output,
- output_factors,
- None,
- batch_dim,
- self.output_dim,
- command_buffer,
- );
- }
-
- Ok(output)
- }
-}
diff --git a/crates/uzu-engine/src/encodable_block/linear/rht_wrapper.rs b/crates/uzu-engine/src/encodable_block/linear/rht_wrapper.rs
index 4135fe01a..a1e0d5a55 100644
--- a/crates/uzu-engine/src/encodable_block/linear/rht_wrapper.rs
+++ b/crates/uzu-engine/src/encodable_block/linear/rht_wrapper.rs
@@ -35,7 +35,6 @@ fn has_input_output_rht(spec: &AnyWeightMatrixSpec) -> bool {
matches!(
spec,
AnyWeightMatrixSpec::HybridSpec(HybridSpec {
- adapter_spec: None,
incoherence_block_size: Some(block_size),
incoherence_processing_mode: IncoherenceProcessingMode::InputOutput,
..
@@ -45,14 +44,14 @@ fn has_input_output_rht(spec: &AnyWeightMatrixSpec) -> bool {
impl<B: Backend> RHTLinearWrapper<B> {
pub(super) fn new(
- context: &B::Context,
input_dimension: u32,
output_dimension: u32,
- has_biases: bool,
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 weights_tree = parameter_tree.subtree("weights");
let spec = weights_tree.metadata::<AnyWeightMatrixSpec>("spec")?;
@@ -61,37 +60,37 @@ impl<B: Backend> RHTLinearWrapper<B> {
}
let (rht_signs, mut inner_linear) = Self::load_inner_with_output_rht(
- context,
input_dimension,
output_dimension,
- has_biases,
+ weights_data_type,
input_data_type,
output_data_type,
- weights_data_type,
+ has_biases,
parameter_tree,
+ context,
)?;
let activation_quantization = inner_linear.prepare_a8(context);
Self::build_self_contained(
- context,
input_data_type,
LinearInputPreparation {
rht_signs,
activation_quantization,
},
inner_linear,
+ context,
)
}
pub(super) fn try_new_with_input_preparation(
- context: &B::Context,
input_dimension: u32,
output_dimension: u32,
- has_biases: bool,
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")?;
@@ -100,21 +99,21 @@ impl<B: Backend> RHTLinearWrapper<B> {
}
let (rht_signs, mut inner_linear) = Self::load_inner_with_output_rht(
- context,
input_dimension,
output_dimension,
- has_biases,
+ weights_data_type,
input_data_type,
output_data_type,
- weights_data_type,
+ has_biases,
parameter_tree,
+ context,
)?;
let input_preparation = LinearInputPreparation {
rht_signs,
activation_quantization: inner_linear.prepare_a8(context),
};
if input_preparation.activation_quantization.is_some() && !allow_prequantized_activation {
- let wrapper = Self::build_self_contained(context, input_data_type, input_preparation, inner_linear)?;
+ 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))))
@@ -122,14 +121,14 @@ impl<B: Backend> RHTLinearWrapper<B> {
}
fn load_inner_with_output_rht(
- context: &B::Context,
input_dimension: u32,
output_dimension: u32,
- has_biases: bool,
+ weights_data_type: DataType,
input_data_type: DataType,
output_data_type: DataType,
- weights_data_type: DataType,
+ has_biases: bool,
parameter_tree: &ParameterTree<B>,
+ context: &B::Context,
) -> Result<(B::GlobalBuffer, LinearMatmul<B>), RHTLinearWrapperError<B>> {
let weights_tree = parameter_tree.subtree("weights");
let quantized_weights_tree = weights_tree.subtree("quantized");
@@ -143,27 +142,27 @@ impl<B: Backend> RHTLinearWrapper<B> {
.validate(&[output_dimension], DataType::I32)?
.read_buffer()?;
let inner_linear = LinearMatmul::load(
- context,
- quantization_spec,
input_dimension,
output_dimension,
weights_data_type,
input_data_type,
output_data_type,
+ quantization_spec,
+ Some(output_factors),
&quantized_weights_tree,
has_biases.then_some(parameter_tree),
- Some(output_factors),
+ context,
)?;
Ok((rht_signs, inner_linear))
}
fn build_self_contained(
- context: &B::Context,
input_data_type: DataType,
input_preparation: LinearInputPreparation<B>,
inner_linear: LinearMatmul<B>,
+ context: &B::Context,
) -> Result<Self, RHTLinearWrapperError<B>> {
- let input_rht = InputRht::new(context, input_data_type, input_preparation, true)
+ let input_rht = InputRht::new(input_data_type, input_preparation, true, context)
.map_err(RHTLinearWrapperError::BackendError)?;
Ok(Self {
@@ -174,15 +173,6 @@ impl<B: Backend> RHTLinearWrapper<B> {
}
impl<B: Backend> Linear<B> for RHTLinearWrapper<B> {
- fn encode(
- &self,
- input: B::ScratchBuffer,
- batch_dim: u32,
- command_buffer: &mut <B::CommandBuffer as CommandBuffer>::Encoding,
- ) -> Result<B::ScratchBuffer, B::Error> {
- self.encode_input(LinearInput::FullPrecision(input), batch_dim, command_buffer)
- }
-
fn encode_input(
&self,
input: LinearInput<B>,
diff --git a/crates/uzu-engine/src/encodable_block/linear/untied_readout.rs b/crates/uzu-engine/src/encodable_block/linear/untied_readout.rs
index a993ff14e..12d6e565d 100644
--- a/crates/uzu-engine/src/encodable_block/linear/untied_readout.rs
+++ b/crates/uzu-engine/src/encodable_block/linear/untied_readout.rs
@@ -22,16 +22,15 @@ pub struct UntiedReadout<B: Backend> {
impl<B: Backend> UntiedReadout<B> {
pub fn load(
- context: &B::Context,
- tree: &ParameterTree<B>,
- spec: AnyWeightMatrixSpec,
vocab_size: u32,
model_dim: u32,
data_type: DataType,
+ spec: AnyWeightMatrixSpec,
+ tree: &ParameterTree<B>,
+ context: &B::Context,
) -> Result<Self, LinearMatmulError<B>> {
let AnyWeightMatrixSpec::HybridSpec(HybridSpec {
quantization_spec,
- adapter_spec: None,
incoherence_block_size: Some(HADAMARD_TRANSFORM_BLOCK_SIZE),
incoherence_processing_mode: IncoherenceProcessingMode::Input,
..
@@ -39,23 +38,23 @@ impl<B: Backend> UntiedReadout<B> {
else {
return Ok(Self {
linear: LinearMatmul::load(
- context, spec, model_dim, vocab_size, data_type, data_type, data_type, tree, None, None,
+ model_dim, vocab_size, data_type, data_type, data_type, spec, None, tree, None, context,
)?,
input_rht: None,
});
};
let mut linear = LinearMatmul::load(
- context,
- *quantization_spec,
model_dim,
vocab_size,
data_type,
data_type,
data_type,
- &tree.subtree("quantized"),
+ *quantization_spec,
None,
+ &tree.subtree("quantized"),
None,
+ context,
)?;
let rht_signs = tree
.subtree("incoherence_signs")
@@ -66,7 +65,7 @@ impl<B: Backend> UntiedReadout<B> {
rht_signs,
activation_quantization: linear.prepare_a8(context),
};
- let input_rht = InputRht::new(context, data_type, preparation, /* in_place */ false)
+ let input_rht = InputRht::new(data_type, preparation, /* in_place */ false, context)
.map_err(LinearMatmulError::BackendError)?;
Ok(Self {
diff --git a/crates/uzu-engine/src/encodable_block/mixer/attention/mod.rs b/crates/uzu-engine/src/encodable_block/mixer/attention/mod.rs
index f3a63c1c6..63a68fec6 100644
--- a/crates/uzu-engine/src/encodable_block/mixer/attention/mod.rs
+++ b/crates/uzu-engine/src/encodable_block/mixer/attention/mod.rs
@@ -96,11 +96,11 @@ impl<B: Backend> Attention<B> {
};
let (projection, in_projection_input_hadamard_factors) = <dyn Linear<B>>::new_with_input_rht(
hidden_dim,
- [projection_dim],
- config.has_qkvg_biases,
- context,
+ projection_dim,
data_type,
+ config.has_qkvg_biases,
&projection_tree,
+ context,
)?;
let query_norm_config = config.query_norm_config.clone();
@@ -110,16 +110,16 @@ impl<B: Backend> Attention<B> {
let qkv_norm = (query_norm_config.is_some() || key_norm_config.is_some() || value_norm_config.is_some())
.then(|| {
QKVNorm::new(
- context,
+ config.num_heads,
+ num_kv_heads.unwrap_or(0), // TODO: should take option
+ projection_dim,
+ config.head_dim,
data_type,
query_norm_config,
key_norm_config,
value_norm_config,
parameter_tree,
- config.num_heads,
- num_kv_heads.unwrap_or(0), // TODO: should take option
- projection_dim,
- config.head_dim,
+ context,
)
})
.transpose()?;
@@ -160,11 +160,11 @@ impl<B: Backend> Attention<B> {
let out_projection = <dyn Linear<B>>::new(
q_dim,
- [hidden_dim],
- config.has_out_biases,
- context,
+ hidden_dim,
data_type,
+ config.has_out_biases,
&parameter_tree.subtree("out_projection"),
+ context,
)?;
Ok((
diff --git a/crates/uzu-engine/src/encodable_block/mixer/attention/qkv_norm.rs b/crates/uzu-engine/src/encodable_block/mixer/attention/qkv_norm.rs
index 02beb5503..9a9a1fbde 100644
--- a/crates/uzu-engine/src/encodable_block/mixer/attention/qkv_norm.rs
+++ b/crates/uzu-engine/src/encodable_block/mixer/attention/qkv_norm.rs
@@ -37,16 +37,16 @@ pub struct QKVNorm<B: Backend> {
impl<B: Backend> QKVNorm<B> {
pub fn new(
- context: &B::Context,
+ num_q_heads: u32,
+ num_kv_heads: u32,
+ projection_row_stride: u32,
+ head_dim: u32,
intermediate_data_type: DataType,
query_config: Option<NormalizationConfig>,
key_config: Option<NormalizationConfig>,
value_config: Option<NormalizationConfig>,
parameter_tree: &ParameterTree<B>,
- num_q_heads: u32,
- num_kv_heads: u32,
- projection_row_stride: u32,
- head_dim: u32,
+ context: &B::Context,
) -> Result<Self, QKVNormError<B>> {
let query = query_config
.map(|cfg| {
diff --git a/crates/uzu-engine/src/encodable_block/mixer/delta_net.rs b/crates/uzu-engine/src/encodable_block/mixer/delta_net.rs
index 8ac89be55..46f4c81ec 100644
--- a/crates/uzu-engine/src/encodable_block/mixer/delta_net.rs
+++ b/crates/uzu-engine/src/encodable_block/mixer/delta_net.rs
@@ -192,13 +192,13 @@ impl<B: Backend> DeltaNet<B> {
let (in_projection, in_projection_input_hadamard_factors) =
<dyn Linear<B>>::new_with_input_rht_mixed_precision(
hidden_dim,
- [total_proj_dim],
- false,
- context,
+ total_proj_dim,
outer_data_type,
outer_data_type,
outer_data_type,
+ false,
&parameter_tree.subtree("in_proj"),
+ context,
)?;
let conv_config = &config.conv_config;
@@ -282,13 +282,13 @@ impl<B: Backend> DeltaNet<B> {
let out_projection = <dyn Linear<B>>::new_mixed_precision(
value_dim,
- [hidden_dim],
- false,
- context,
+ hidden_dim,
outer_data_type,
outer_data_type,
outer_data_type,
+ false,
&parameter_tree.subtree("out_proj"),
+ context,
)?;
Ok((
diff --git a/crates/uzu-engine/src/encodable_block/mixer/mamba2.rs b/crates/uzu-engine/src/encodable_block/mixer/mamba2.rs
index 753113be2..038109caa 100644
--- a/crates/uzu-engine/src/encodable_block/mixer/mamba2.rs
+++ b/crates/uzu-engine/src/encodable_block/mixer/mamba2.rs
@@ -115,13 +115,13 @@ impl<B: Backend> Mamba2<B> {
let (in_projection, in_projection_input_hadamard_factors) =
<dyn Linear<B>>::new_with_input_rht_mixed_precision(
hidden_dim,
- [conv_dim, inner_dim, num_heads],
- config.has_in_biases,
- context,
+ conv_dim + inner_dim + num_heads,
outer_data_type,
outer_data_type,
INNER_DATA_TYPE,
+ config.has_in_biases,
&parameter_tree.subtree("in_projection"),
+ context,
)?;
let gate_bias = parameter_tree.leaf("gate_bias")?.validate(&[inner_dim], INNER_DATA_TYPE)?.read_buffer()?;
@@ -166,13 +166,13 @@ impl<B: Backend> Mamba2<B> {
let out_projection = <dyn Linear<B>>::new_mixed_precision(
inner_dim,
- [hidden_dim],
- config.has_out_biases,
- context,
+ hidden_dim,
outer_data_type,
INNER_DATA_TYPE,
outer_data_type,
+ config.has_out_biases,
&parameter_tree.subtree("out_projection"),
+ context,
)?;
Ok((
diff --git a/crates/uzu-engine/src/encodable_block/mixer/mod.rs b/crates/uzu-engine/src/encodable_block/mixer/mod.rs
index 5e0c30d66..d4250ce14 100644
--- a/crates/uzu-engine/src/encodable_block/mixer/mod.rs
+++ b/crates/uzu-engine/src/encodable_block/mixer/mod.rs
@@ -85,7 +85,7 @@ impl<B: Backend> dyn Mixer<B> {
pub fn new(
hidden_dim: u32,
data_type: DataType,
- rope_config: Option<&AnyRoPEConfig>,
+ rope_config: Option<&AnyRoPEConfig>, // TODO: this shouldn't exist
config: &AnyTokenMixerConfig,
parameter_tree: &ParameterTree<B>,
context: &B::Context,
diff --git a/crates/uzu-engine/src/encodable_block/mixer/short_conv.rs b/crates/uzu-engine/src/encodable_block/mixer/short_conv.rs
index 040b8cc4a..7bc2dd839 100644
--- a/crates/uzu-engine/src/encodable_block/mixer/short_conv.rs
+++ b/crates/uzu-engine/src/encodable_block/mixer/short_conv.rs
@@ -118,20 +118,20 @@ impl<B: Backend> ShortConv<B> {
let (in_projection, in_projection_input_hadamard_factors) = <dyn Linear<B>>::new_with_input_rht(
hidden_dim,
- [hidden_dim * 3],
- false,
- context,
+ hidden_dim * 3,
data_type,
+ false,
&parameter_tree.subtree("in_projection"),
+ context,
)?;
let out_projection = <dyn Linear<B>>::new(
hidden_dim,
- [hidden_dim],
- false,
- context,
+ hidden_dim,
data_type,
+ false,
&parameter_tree.subtree("out_projection"),
+ context,
)?;
let conv_tree = parameter_tree.subtree("conv");
@@ -245,8 +245,8 @@ impl<B: Backend> ShortConv<B> {
fn encode_trie_conv(
&self,
in_projected: impl BufferRef<Backend = B>,
- batch_dim: u32,
token_parents: impl BufferRef<Backend = B>,
+ batch_dim: u32,
state: &mut ShortConvState<B>,
command_buffer: &mut <B::CommandBuffer as CommandBuffer>::Encoding,
) -> Result<(B::ScratchBuffer, B::ScratchBuffer), B::Error> {
@@ -335,7 +335,7 @@ impl<B: Backend> Mixer<B> for ShortConv<B> {
} else {
let token_parents = command_buffer.allocate_constant_from_slice(batch_dim.parents())?;
let (conv_output, conv_states) =
- self.encode_trie_conv(&in_projected, batch_dim.size(), &token_parents, state, command_buffer)?;
+ self.encode_trie_conv(&in_projected, &token_parents, batch_dim.size(), state, command_buffer)?;
state.suffix_state = Some(ShortConvStateSuffixStatus::Trie {
conv_states,
});
diff --git a/crates/uzu-engine/src/encodable_block/mlp/dense.rs b/crates/uzu-engine/src/encodable_block/mlp/dense.rs
index a6a021470..31ecba34d 100644
--- a/crates/uzu-engine/src/encodable_block/mlp/dense.rs
+++ b/crates/uzu-engine/src/encodable_block/mlp/dense.rs
@@ -1,11 +1,17 @@
//! MLP block encodable.
+use derive_more::Debug;
+use thiserror::Error;
+
use crate::{
backends::common::{Backend, CommandBuffer, CommandBufferEncoding},
+ config::mlp::dense_mlp::DenseMLPConfig,
+ data_type::DataType,
encodable_block::{
- linear::Linear,
+ linear::{Linear, LinearBlockError},
mlp::{Mlp, gate_act_mul::MlpGateActMulEncodable},
},
+ parameters::ParameterTree,
};
pub struct DenseMlp<B: Backend> {
@@ -14,17 +20,60 @@ pub struct DenseMlp<B: Backend> {
down: Box<dyn Linear<B>>,
}
+#[derive(Debug, Error)]
+pub enum DenseMlpNewError<B: Backend> {
+ #[error("Backend error: {0}")]
+ Backend(#[source] B::Error),
+ #[error("Linear error: {0}")]
+ Linear(#[from] LinearBlockError<B>),
+}
+
impl<B: Backend> DenseMlp<B> {
pub fn new(
- up: Box<dyn Linear<B>>,
- gate: MlpGateActMulEncodable<B>,
- down: Box<dyn Linear<B>>,
- ) -> Self {
- Self {
- up,
- gate,
- down,
- }
+ model_dimension: u32,
+ hidden_dimension: u32,
+ data_type: DataType,
+ config: &DenseMLPConfig,
+ parameter_tree: &ParameterTree<B>,
+ context: &B::Context,
+ ) -> Result<(Self, Option<B::GlobalBuffer>), DenseMlpNewError<B>> {
+ let (up, up_input_hadamard_factors) = <dyn Linear<B>>::new_with_input_rht(
+ model_dimension,
+ 2 * hidden_dimension,
+ data_type,
+ config.has_up_biases,
+ &parameter_tree.subtree("up_projection"),
+ context,
+ )?;
+
+ let (down, down_input_preparation) = <dyn Linear<B>>::new_for_fused_input(
+ hidden_dimension,
+ model_dimension,
+ data_type,
+ config.has_down_biases,
+ &parameter_tree.subtree("down_projection"),
+ context,
+ )?;
+
+ let gate = MlpGateActMulEncodable::new(
+ hidden_dimension,
+ data_type,
+ config.activation.clone(),
+ config.gate_clipping,
+ config.up_clipping,
+ down_input_preparation,
+ context,
+ )
+ .map_err(DenseMlpNewError::Backend)?;
+
+ Ok((
+ Self {
+ up,
+ gate,
+ down,
+ },
+ up_input_hadamard_factors,
+ ))
}
}
@@ -39,7 +88,7 @@ impl<B: Backend> Mlp<B> for DenseMlp<B> {
let fused_up = self.up.encode(input, batch_dim, command_buffer)?;
let act_format = self.down.select_activation_format(batch_dim, command_buffer.context());
- let down_input = self.gate.encode_for_linear(command_buffer, &fused_up, batch_dim, act_format)?;
+ let down_input = self.gate.encode_for_linear(&fused_up, batch_dim, act_format, command_buffer)?;
let output = self.down.encode_input(down_input, batch_dim, command_buffer)?;
Ok(output)
diff --git a/crates/uzu-engine/src/encodable_block/mlp/gate_act_mul.rs b/crates/uzu-engine/src/encodable_block/mlp/gate_act_mul.rs
index 9ffeb4f3d..1e96ba139 100644
--- a/crates/uzu-engine/src/encodable_block/mlp/gate_act_mul.rs
+++ b/crates/uzu-engine/src/encodable_block/mlp/gate_act_mul.rs
@@ -21,13 +21,13 @@ pub struct MlpGateActMulEncodable<B: Backend> {
impl<B: Backend> MlpGateActMulEncodable<B> {
pub fn new(
- context: &B::Context,
+ hidden_dim: u32,
data_type: DataType,
activation: AnyActivation,
gate_clipping: ClippingBounds,
value_clipping: ClippingBounds,
- hidden_dim: u32,
input_preparation: Option<LinearInputPreparation<B>>,
+ context: &B::Context,
) -> Result<Self, B::Error> {
let (hadamard_factors, activation_quantization) = input_preparation
.map_or((None, None), |preparation| (Some(preparation.rht_signs), preparation.activation_quantization));
@@ -53,10 +53,10 @@ impl<B: Backend> MlpGateActMulEncodable<B> {
pub fn encode_for_linear(
&self,
- command_buffer: &mut <B::CommandBuffer as CommandBuffer>::Encoding,
fused_up: impl BufferRef<Backend = B>,
batch_dim: u32,
act_format: ActivationFormat,
+ command_buffer: &mut <B::CommandBuffer as CommandBuffer>::Encoding,
) -> Result<LinearInput<B>, B::Error> {
if self.activation.act_type() == ActivationType::IDENTITY {
panic!("Identity activation is not supported for kernel")
diff --git a/crates/uzu-engine/src/encodable_block/mlp/mod.rs b/crates/uzu-engine/src/encodable_block/mlp/mod.rs
index 5ae64a74e..988a178e2 100644
--- a/crates/uzu-engine/src/encodable_block/mlp/mod.rs
+++ b/crates/uzu-engine/src/encodable_block/mlp/mod.rs
@@ -1,16 +1,14 @@
mod dense;
mod gate_act_mul;
-pub use dense::DenseMlp;
use derive_more::Debug;
-use gate_act_mul::MlpGateActMulEncodable;
use thiserror::Error;
use crate::{
backends::common::{Backend, CommandBuffer},
config::mlp::AnyMLPConfig,
data_type::DataType,
- encodable_block::linear::{Linear, LinearBlockError},
+ encodable_block::mlp::dense::{DenseMlp, DenseMlpNewError},
parameters::ParameterTree,
};
@@ -24,58 +22,30 @@ pub trait Mlp<B: Backend>: Send + Sync {
}
#[derive(Debug, Error)]
-pub enum MlpBlockError<B: Backend> {
- #[error("Backend error: {0}")]
- BackendError(#[source] B::Error),
- #[error("Linear block error: {0}")]
- LinearBlockError(#[from] LinearBlockError<B>),
+pub enum MlpBlockNewError<B: Backend> {
+ #[error("Dense MLP error: {0}")]
+ Dense(#[from] DenseMlpNewError<B>),
#[error("Mixture of experts is not supported")]
UnsupportedMixtureOfExperts,
}
impl<B: Backend> dyn Mlp<B> {
pub fn new(
- config: &AnyMLPConfig,
model_dimension: u32,
hidden_dimension: u32,
- context: &B::Context,
- parameter_tree: &ParameterTree<B>,
data_type: DataType,
- ) -> Result<(Box<dyn Mlp<B>>, Option<B::GlobalBuffer>), MlpBlockError<B>> {
+ config: &AnyMLPConfig,
+ parameter_tree: &ParameterTree<B>,
+ context: &B::Context,
+ ) -> Result<(Box<dyn Mlp<B>>, Option<B::GlobalBuffer>), MlpBlockNewError<B>> {
match config {
- AnyMLPConfig::DenseMLPConfig(dense_config) => {
- let (up_projection, up_input_hadamard_factors) = <dyn Linear<B>>::new_with_input_rht(
- model_dimension,
- [2 * hidden_dimension],
- dense_config.has_up_biases,
- context,
- data_type,
- &parameter_tree.subtree("up_projection"),
- )?;
-
- let (down_projection, down_input_preparation) = <dyn Linear<B>>::new_for_fused_input(
- hidden_dimension,
- [model_dimension],
- dense_config.has_down_biases,
- context,
- data_type,
- &parameter_tree.subtree("down_projection"),
- )?;
-
- let gate = MlpGateActMulEncodable::new(
- context,
- data_type,
- dense_config.activation.clone(),
- dense_config.gate_clipping,
- dense_config.up_clipping,
- hidden_dimension,
- down_input_preparation,
- )
- .map_err(MlpBlockError::BackendError)?;
+ AnyMLPConfig::DenseMLPConfig(config) => {
+ let (dense, up_input_hadamard_factors) =
+ DenseMlp::new(model_dimension, hidden_dimension, data_type, config, parameter_tree, context)?;
- Ok((Box::new(DenseMlp::new(up_projection, gate, down_projection)), up_input_hadamard_factors))
+ Ok((Box::new(dense), up_input_hadamard_factors))
},
- AnyMLPConfig::MixtureOfExpertsConfig(_) => Err(MlpBlockError::UnsupportedMixtureOfExperts),
+ AnyMLPConfig::MixtureOfExpertsConfig(_) => Err(MlpBlockNewError::UnsupportedMixtureOfExperts),
}
}
}
diff --git a/crates/uzu-engine/src/encodable_block/mod.rs b/crates/uzu-engine/src/encodable_block/mod.rs
index 9f6c79366..bc4e3c9a3 100644
--- a/crates/uzu-engine/src/encodable_block/mod.rs
+++ b/crates/uzu-engine/src/encodable_block/mod.rs
@@ -1,3 +1,9 @@
+//! Encodable blocks follow the argument order used by [`mixer`]:
+//! - Constructors: dimensions, data types, configuration and other construction inputs,
+//! parameter trees, then the backend context.
+//! - Encode methods: operands, dimensions and operation options, explicit state,
+//! then the command buffer. Method receivers always come first.
+
pub mod batch_topology;
pub mod classifier;
pub mod convolution;
diff --git a/crates/uzu-engine/src/encodable_block/normalization.rs b/crates/uzu-engine/src/encodable_block/normalization.rs
index 1a1ec09d7..90c5fd109 100644
--- a/crates/uzu-engine/src/encodable_block/normalization.rs
+++ b/crates/uzu-engine/src/encodable_block/normalization.rs
@@ -51,10 +51,10 @@ pub struct Normalization<B: Backend> {
impl<B: Backend> Normalization<B> {
pub fn new(
element_count: u32,
+ data_type: DataType,
hadamard_factors: Option<B::GlobalBuffer>,
shortcut_mode: ShortcutMode,
post_layer_scalar: PostLayerScalar,
- data_type: DataType,
config: &NormalizationConfig,
parameter_tree: &ParameterTree<B>,
context: &B::Context,
diff --git a/crates/uzu-engine/src/encodable_block/per_layer_embedding.rs b/crates/uzu-engine/src/encodable_block/per_layer_embedding.rs
index 6f5ab40d1..c95f24cbe 100644
--- a/crates/uzu-engine/src/encodable_block/per_layer_embedding.rs
+++ b/crates/uzu-engine/src/encodable_block/per_layer_embedding.rs
@@ -45,29 +45,29 @@ pub struct PerLayerEmbedding<B: Backend> {
impl<B: Backend> PerLayerEmbedding<B> {
pub fn new(
- context: &B::Context,
- config: &PLEModelConfig,
model_dim: u32,
data_type: DataType,
+ config: &PLEModelConfig,
parameter_tree: &ParameterTree<B>,
+ context: &B::Context,
) -> Result<Self, PerLayerEmbeddingError<B>> {
let total_ple_dim = config.num_layers * config.ple_dim;
let token_embedding = EmbeddingTable::load(
- context,
- &parameter_tree.subtree("token_embedding"),
config.ple_vocab_size,
total_ple_dim,
data_type,
+ &parameter_tree.subtree("token_embedding"),
+ context,
)?;
let model_projection = <dyn Linear<B>>::new(
model_dim,
- [total_ple_dim],
- false,
- context,
+ total_ple_dim,
data_type,
+ false,
&parameter_tree.subtree("model_projection"),
+ context,
)?;
let scale_squared = config.model_projection_scale * config.model_projection_scale;
@@ -78,10 +78,10 @@ impl<B: Backend> PerLayerEmbedding<B> {
};
let projection_norm = Normalization::new(
config.ple_dim,
+ data_type,
None,
ShortcutMode::None,
PostLayerScalar::ScaleOutput(config.input_scale),
- data_type,
&projection_norm_config,
&parameter_tree.subtree("projection_norm"),
context,
@@ -171,36 +171,36 @@ pub struct PerLayerEmbeddingProjection<B: Backend> {
impl<B: Backend> PerLayerEmbeddingProjection<B> {
pub fn new(
- context: &B::Context,
- config: &PLELayerConfig,
model_dim: u32,
num_layers: u32,
- post_layer_scalar: f32,
data_type: DataType,
+ post_layer_scalar: f32,
+ config: &PLELayerConfig,
parameter_tree: &ParameterTree<B>,
+ context: &B::Context,
) -> Result<Self, PerLayerEmbeddingError<B>> {
let gate = <dyn Linear<B>>::new(
model_dim,
- [config.ple_dim],
- false,
- context,
+ config.ple_dim,
data_type,
+ false,
&parameter_tree.subtree("gate"),
+ context,
)?;
let projection = <dyn Linear<B>>::new(
config.ple_dim,
- [model_dim],
- false,
- context,
+ model_dim,
data_type,
+ false,
&parameter_tree.subtree("projection"),
+ context,
)?;
let norm = Normalization::new(
model_dim,
+ data_type,
None,
ShortcutMode::None,
PostLayerScalar::None,
- data_type,
&config.norm_config,
&parameter_tree.subtree("norm"),
context,
@@ -236,10 +236,10 @@ impl<B: Backend> PerLayerEmbeddingProjection<B> {
pub fn encode(
&self,
- layer_index: u32,
per_layer_input: impl BufferRef<Backend = B>,
mut outputs: impl BufferMut<Backend = B>,
hidden: impl BufferRef<Backend = B>,
+ layer_index: u32,
batch_dim: u32,
command_buffer: &mut <B::CommandBuffer as CommandBuffer>::Encoding,
) -> Result<(), B::Error> {
diff --git a/crates/uzu-engine/src/encodable_block/prediction_head.rs b/crates/uzu-engine/src/encodable_block/prediction_head.rs
index 0ebb99779..913ac5997 100644
--- a/crates/uzu-engine/src/encodable_block/prediction_head.rs
+++ b/crates/uzu-engine/src/encodable_block/prediction_head.rs
@@ -46,11 +46,11 @@ impl<B: Backend> PredictionHead<B> {
) -> Result<Self, PredictionHeadError<B>> {
let dense_projection = <dyn Linear<B>>::new(
hidden_dim,
- [hidden_dim],
- config.use_dense_bias,
- context,
+ hidden_dim,
data_type,
+ config.use_dense_bias,
&parameter_tree.subtree("dense"),
+ context,
)?;
let activation = config.activation.act_type();
@@ -59,23 +59,17 @@ impl<B: Backend> PredictionHead<B> {
let normalization = Normalization::new(
hidden_dim,
+ data_type,
None,
ShortcutMode::None,
PostLayerScalar::None,
- data_type,
&config.normalization_config,
&parameter_tree.subtree("norm"),
context,
)?;
- let readout = <dyn Linear<B>>::new(
- hidden_dim,
- [num_labels],
- true,
- context,
- data_type,
- &parameter_tree.subtree("readout"),
- )?;
+ let readout =
+ <dyn Linear<B>>::new(hidden_dim, num_labels, data_type, true, &parameter_tree.subtree("readout"), context)?;
Ok(Self {
hidden_dim,
diff --git a/crates/uzu-engine/src/encodable_block/sampling/mod.rs b/crates/uzu-engine/src/encodable_block/sampling/mod.rs
index 1d2a1e29a..5e607226d 100644
--- a/crates/uzu-engine/src/encodable_block/sampling/mod.rs
+++ b/crates/uzu-engine/src/encodable_block/sampling/mod.rs
@@ -31,8 +31,8 @@ pub struct Sampling<B: Backend> {
impl<B: Backend> Sampling<B> {
pub fn new(
- data_type: DataType,
vocab_size: u32,
+ data_type: DataType,
) -> Self {
Self {
vocab_size,
@@ -87,9 +87,9 @@ impl<B: Backend> Sampling<B> {
bitmask: Option<impl BufferRef<Backend = B>>,
context_ring: Option<impl BufferRef<Backend = B>>,
token_ids: Option<impl BufferRef<Backend = B>>,
- sampling_method: &SamplingMethod,
batch_dim: &BatchTopology,
sampling_range: Range<u32>,
+ sampling_method: &SamplingMethod,
command_buffer: &mut <B::CommandBuffer as CommandBuffer>::Encoding,
) -> Result<B::GlobalBuffer, B::Error> {
let command_buffer = &mut *command_buffer.debug_group("sampling");
diff --git a/crates/uzu-engine/src/encodable_block/transformer.rs b/crates/uzu-engine/src/encodable_block/transformer.rs
index 8cdcdb62b..b541d3be9 100644
--- a/crates/uzu-engine/src/encodable_block/transformer.rs
+++ b/crates/uzu-engine/src/encodable_block/transformer.rs
@@ -100,11 +100,11 @@ pub struct Transformer<B: Backend> {
impl<B: Backend> Transformer<B> {
pub fn new(
- context: &B::Context,
- output_norm_hadamard_factors: Option<B::GlobalBuffer>,
data_type: DataType,
+ output_norm_hadamard_factors: Option<B::GlobalBuffer>,
transformer_config: &TransformerConfig,
parameter_tree: &ParameterTree<B>,
+ context: &B::Context,
) -> Result<Self, TransformerNewError<B>> {
let mut ropes: Vec<AnyRoPEConfig> = Vec::new();
@@ -124,14 +124,14 @@ impl<B: Backend> Transformer<B> {
});
let layer = TransformerLayer::new(
- context,
transformer_config.model_dim,
transformer_config.hidden_dim,
num_layers,
- layer_config,
layer_index,
- &layer_loader,
data_type,
+ layer_config,
+ &layer_loader,
+ context,
)?;
Ok((layer, rope))
@@ -140,10 +140,10 @@ impl<B: Backend> Transformer<B> {
let output_norm = Normalization::new(
transformer_config.model_dim,
+ data_type,
output_norm_hadamard_factors,
ShortcutMode::Add,
PostLayerScalar::None,
- data_type,
&transformer_config.output_norm_config,
&parameter_tree.subtree("output_norm"),
context,
diff --git a/crates/uzu-engine/src/encodable_block/transformer_layer.rs b/crates/uzu-engine/src/encodable_block/transformer_layer.rs
index 654d9be9b..928cf5e90 100644
--- a/crates/uzu-engine/src/encodable_block/transformer_layer.rs
+++ b/crates/uzu-engine/src/encodable_block/transformer_layer.rs
@@ -12,7 +12,7 @@ use crate::{
convolution::{ConvolutionNewError, SeparableCausalConv},
linear::{Linear, LinearBlockError},
mixer::{Mixer, MixerNewError, MixerState, attention::rope::PrecalculatedRoPE},
- mlp::{Mlp, MlpBlockError},
+ mlp::{Mlp, MlpBlockNewError},
normalization::{Normalization, NormalizationNewError, PostLayerScalar, ShortcutMode},
per_layer_embedding::PerLayerEmbeddingProjection,
},
@@ -29,7 +29,7 @@ pub enum TransformerLayerError<B: Backend> {
#[error("Mixer error: {0}")]
Mixer(#[from] MixerNewError<B>),
#[error("MLP error: {0}")]
- MlpBlock(#[from] MlpBlockError<B>),
+ MlpBlock(#[from] MlpBlockNewError<B>),
#[error("Normalization error: {0}")]
Normalization(#[from] NormalizationNewError<B>),
#[error("Convolution error: {0}")]
@@ -71,12 +71,12 @@ pub struct TransformerLayer<B: Backend> {
impl<B: Backend> TransformerLayerConv<B> {
fn new(
- context: &B::Context,
model_dim: u32,
- config: &TransformerLayerConvConfig,
- parameter_tree: &ParameterTree<B>,
data_type: DataType,
input_hadamard_factors: Option<B::GlobalBuffer>,
+ config: &TransformerLayerConvConfig,
+ parameter_tree: &ParameterTree<B>,
+ context: &B::Context,
) -> Result<Self, TransformerLayerError<B>> {
let pre_conv = SeparableCausalConv::new(
model_dim,
@@ -101,11 +101,11 @@ impl<B: Backend> TransformerLayerConv<B> {
let projection_dim = coefficient_count * 2;
let kernel_projection = <dyn Linear<B>>::new(
model_dim,
- [projection_dim],
- false,
- context,
+ projection_dim,
data_type,
+ false,
&parameter_tree.subtree("kernel_projection"),
+ context,
)?;
let input_rht = input_hadamard_factors
@@ -166,14 +166,14 @@ impl<B: Backend> TransformerLayerConv<B> {
impl<B: Backend> TransformerLayer<B> {
pub fn new(
- context: &B::Context,
model_dim: u32,
hidden_dim: u32,
num_layers: u32,
- layer_config: &TransformerLayerConfig,
layer_index: u32,
- parameter_tree: &ParameterTree<B>,
data_type: DataType,
+ layer_config: &TransformerLayerConfig,
+ parameter_tree: &ParameterTree<B>,
+ context: &B::Context,
) -> Result<Self, TransformerLayerError<B>> {
let post_layer_scalar = if layer_config.has_post_layer_scalar {
if layer_config.post_mlp_norm_config.is_none() {
@@ -212,12 +212,12 @@ impl<B: Backend> TransformerLayer<B> {
let (mixer_conv, mixer_hadamard_factors) = match &layer_config.mixer_conv_config {
Some(config) => (
Some(TransformerLayerConv::new(
- context,
model_dim,
- config,
- &parameter_tree.subtree("mixer_conv"),
data_type,
mixer_hadamard_factors,
+ config,
+ &parameter_tree.subtree("mixer_conv"),
+ context,
)?),
None,
),
@@ -227,6 +227,7 @@ impl<B: Backend> TransformerLayer<B> {
let pre_mixer_norm = if let Some(pre_mixer_norm_config) = &layer_config.pre_mixer_norm_config {
Some(Normalization::new(
model_dim,
+ data_type,
mixer_hadamard_factors,
if layer_index > 0 {
ShortcutMode::Add
@@ -234,7 +235,6 @@ impl<B: Backend> TransformerLayer<B> {
ShortcutMode::Copy
},
PostLayerScalar::None,
- data_type,
pre_mixer_norm_config,
&parameter_tree.subtree("pre_mixer_norm"),
context,
@@ -249,10 +249,10 @@ impl<B: Backend> TransformerLayer<B> {
let post_mixer_norm = if let Some(norm_config) = &layer_config.post_mixer_norm_config {
Some(Normalization::new(
model_dim,
+ data_type,
None,
ShortcutMode::None,
PostLayerScalar::None,
- data_type,
norm_config,
&parameter_tree.subtree("post_mixer_norm"),
context,
@@ -262,23 +262,23 @@ impl<B: Backend> TransformerLayer<B> {
};
let (mlp, mlp_input_hadamard_factors) = <dyn Mlp<B>>::new(
- &layer_config.mlp_config,
model_dim,
layer_config.hidden_dim.unwrap_or(hidden_dim),
- context,
- &parameter_tree.subtree("mlp"),
data_type,
+ &layer_config.mlp_config,
+ &parameter_tree.subtree("mlp"),
+ context,
)?;
let (mlp_conv, mlp_input_hadamard_factors) = match &layer_config.mlp_conv_config {
Some(config) => (
Some(TransformerLayerConv::new(
- context,
model_dim,
- config,
- &parameter_tree.subtree("mlp_conv"),
data_type,
mlp_input_hadamard_factors,
+ config,
+ &parameter_tree.subtree("mlp_conv"),
+ context,
)?),
None,
),
@@ -287,10 +287,10 @@ impl<B: Backend> TransformerLayer<B> {
let pre_mlp_norm = Normalization::new(
model_dim,
+ data_type,
mlp_input_hadamard_factors,
ShortcutMode::Add,
residual_sum_scalar,
- data_type,
&layer_config.pre_mlp_norm_config,
&parameter_tree.subtree("pre_mlp_norm"),
context,
@@ -299,10 +299,10 @@ impl<B: Backend> TransformerLayer<B> {
let post_mlp_norm = if let Some(norm_config) = &layer_config.post_mlp_norm_config {
Some(Normalization::new(
model_dim,
+ data_type,
None,
ShortcutMode::None,
output_scalar,
- data_type,
norm_config,
&parameter_tree.subtree("post_mlp_norm"),
context,
@@ -314,13 +314,13 @@ impl<B: Backend> TransformerLayer<B> {
let ple_projection = layer_config.ple_config.as_ref().map(|ple_config| {
let ple_loader = parameter_tree.subtree("ple");
PerLayerEmbeddingProjection::new(
- context,
- ple_config,
model_dim,
num_layers,
- post_layer_scalar.unwrap_or(1.0),
data_type,
+ post_layer_scalar.unwrap_or(1.0),
+ ple_config,
&ple_loader,
+ context,
)
.expect("Failed to create per-layer embedding projection")
});
@@ -408,10 +408,10 @@ impl<B: Backend> TransformerLayer<B> {
if let Some(ple_projection) = &self.ple_projection {
let per_layer_inputs = per_layer_inputs.expect("per-layer inputs required for PLE layer");
ple_projection.encode(
- self.layer_index,
per_layer_inputs,
shortcut,
&hidden,
+ self.layer_index,
batch_dim.size(),
command_buffer,
)?;
diff --git a/crates/uzu-engine/src/encodable_block/weaver.rs b/crates/uzu-engine/src/encodable_block/weaver.rs
index 9df512a47..2569a872e 100644
--- a/crates/uzu-engine/src/encodable_block/weaver.rs
+++ b/crates/uzu-engine/src/encodable_block/weaver.rs
@@ -19,7 +19,7 @@ use crate::{
embedding::{Embedding, EmbeddingError},
linear::{Linear, LinearBlockError},
mixer::attention::{KVCacheView, rope::PrecalculatedRoPE},
- mlp::MlpBlockError,
+ mlp::MlpBlockNewError,
normalization::{Normalization, NormalizationNewError, PostLayerScalar, ShortcutMode},
weaver_layer::{PreparedPrefixAttention, WeaverLayer},
},
@@ -135,7 +135,7 @@ pub enum WeaverNewError<B: Backend> {
#[error("linear error: {0}")]
Linear(#[from] LinearBlockError<B>),
#[error("mlp error: {0}")]
- Mlp(#[from] MlpBlockError<B>),
+ Mlp(#[from] MlpBlockNewError<B>),
#[error("normalization error: {0}")]
Normalization(#[from] NormalizationNewError<B>),
#[error("backend error: {0}")]
@@ -170,10 +170,10 @@ pub enum WeaverEncodeError<B: Backend> {
impl<B: Backend> Weaver<B> {
pub fn new(
- context: &B::Context,
- config: &WeaverConfig,
vocab_size: u32,
+ config: &WeaverConfig,
parameter_tree: &ParameterTree<B>,
+ context: &B::Context,
) -> Result<Self, WeaverNewError<B>> {
if config.num_layers == 0 {
return Err(WeaverNewError::InvalidLayerCount);
@@ -199,61 +199,61 @@ impl<B: Backend> Weaver<B> {
}
let token_embedding_norm = Normalization::new(
config.target_embedding_dim,
+ DATA_TYPE,
None,
ShortcutMode::None,
PostLayerScalar::None,
- DATA_TYPE,
&config.norm_config,
&parameter_tree.subtree("embedding_norm"),
context,
)?;
let hidden_state_norm = Normalization::new(
config.target_model_dim,
+ DATA_TYPE,
None,
ShortcutMode::None,
PostLayerScalar::None,
- DATA_TYPE,
&config.norm_config,
&parameter_tree.subtree("hidden_state_norm"),
context,
)?;
let token_embedding_projection = <dyn Linear<B>>::new(
config.target_embedding_dim,
- [config.model_dim],
- true,
- context,
+ config.model_dim,
DATA_TYPE,
+ true,
&parameter_tree.subtree("embedding_projection"),
+ context,
)?;
let layer_parameters = parameter_tree.subtree("blocks");
let layers = (0..config.num_layers)
- .map(|index| WeaverLayer::new(context, config, index > 0, &layer_parameters.subtree(&index.to_string())))
+ .map(|index| WeaverLayer::new(index > 0, config, &layer_parameters.subtree(&index.to_string()), context))
.collect::<Result<Box<[_]>, WeaverNewError<B>>>()?;
let readout_norm = Normalization::new(
config.model_dim,
+ DATA_TYPE,
None,
ShortcutMode::Add,
PostLayerScalar::None,
- DATA_TYPE,
&config.norm_config,
&parameter_tree.subtree("output_norm"),
context,
)?;
let hidden_state_projection = <dyn Linear<B>>::new(
config.target_model_dim,
- [config.model_dim],
- true,
- context,
+ config.model_dim,
DATA_TYPE,
+ true,
&parameter_tree.subtree("hidden_state_projection"),
+ context,
)?;
let readout_query_projection = <dyn Linear<B>>::new(
config.model_dim,
- [config.target_model_dim],
- false,
- context,
+ config.target_model_dim,
DATA_TYPE,
+ false,
&parameter_tree.subtree("query_projection"),
+ context,
)?;
let top_k =
<B::Kernels as Kernels>::RadixTopKSmall::new(context, vocab_size).map_err(WeaverNewError::Backend)?;
@@ -478,8 +478,8 @@ impl<B: Backend> Weaver<B> {
.encode(normalized_output, batch_node_count, command_buffer)
.map_err(WeaverEncodeError::Backend)?;
let logit_residuals = target_embedding.encode_readout(
- batch_node_count,
&query,
+ batch_node_count,
self.candidate_pool_size,
Some(batch_candidate_ids),
false,
diff --git a/crates/uzu-engine/src/encodable_block/weaver_layer.rs b/crates/uzu-engine/src/encodable_block/weaver_layer.rs
index 691cdf286..a71d6d5ac 100644
--- a/crates/uzu-engine/src/encodable_block/weaver_layer.rs
+++ b/crates/uzu-engine/src/encodable_block/weaver_layer.rs
@@ -42,10 +42,10 @@ pub struct WeaverLayer<B: Backend> {
impl<B: Backend> WeaverLayer<B> {
pub fn new(
- context: &B::Context,
- config: &WeaverConfig,
add_to_residual: bool,
+ config: &WeaverConfig,
parameter_tree: &ParameterTree<B>,
+ context: &B::Context,
) -> Result<Self, WeaverNewError<B>> {
let WeaverConfig {
model_dim,
@@ -60,19 +60,19 @@ impl<B: Backend> WeaverLayer<B> {
let attention_scale = 1.0 / (head_dim as f32).sqrt();
let qkv_projection = <dyn Linear<B>>::new(
model_dim,
- [3 * model_dim],
- false,
- context,
+ 3 * model_dim,
DATA_TYPE,
+ false,
&parameter_tree.subtree("qkv_projection"),
+ context,
)?;
let out_projection = <dyn Linear<B>>::new(
model_dim,
- [model_dim],
- false,
- context,
+ model_dim,
DATA_TYPE,
+ false,
&parameter_tree.subtree("out_projection"),
+ context,
)?;
let prefix_attention = <B::Kernels as Kernels>::AttentionKernel::new(
context,
@@ -95,6 +95,7 @@ impl<B: Backend> WeaverLayer<B> {
.map_err(WeaverNewError::Backend)?;
let pre_attention_norm = Normalization::new(
model_dim,
+ DATA_TYPE,
None,
if add_to_residual {
ShortcutMode::Add
@@ -102,17 +103,16 @@ impl<B: Backend> WeaverLayer<B> {
ShortcutMode::Copy
},
PostLayerScalar::None,
- DATA_TYPE,
norm_config,
&parameter_tree.subtree("pre_attention_norm"),
context,
)?;
let pre_mlp_norm = Normalization::new(
model_dim,
+ DATA_TYPE,
None,
ShortcutMode::Add,
PostLayerScalar::None,
- DATA_TYPE,
norm_config,
&parameter_tree.subtree("pre_mlp_norm"),
context,
@@ -124,7 +124,7 @@ impl<B: Backend> WeaverLayer<B> {
true,
));
let (mlp, up_input_hadamard_factors) =
- <dyn Mlp<B>>::new(&mlp_config, model_dim, hidden_dim, context, &parameter_tree.subtree("mlp"), DATA_TYPE)?;
+ <dyn Mlp<B>>::new(model_dim, hidden_dim, DATA_TYPE, &mlp_config, &parameter_tree.subtree("mlp"), context)?;
assert!(up_input_hadamard_factors.is_none(), "Weaver MLP does not support input Hadamard factors");
let ancestor_attention = <B::Kernels as Kernels>::AncestorAttentionKernel::new(context, head_dim, num_heads)
.map_err(WeaverNewError::Backend)?;
diff --git a/crates/uzu-engine/src/encodable_block/weight_matrix.rs b/crates/uzu-engine/src/encodable_block/weight_matrix.rs
index e0e4be876..1b5515e87 100644
--- a/crates/uzu-engine/src/encodable_block/weight_matrix.rs
+++ b/crates/uzu-engine/src/encodable_block/weight_matrix.rs
@@ -95,12 +95,12 @@ pub struct WeightMatrix<B: Backend> {
impl<B: Backend> WeightMatrix<B> {
pub fn load(
- tree: &ParameterTree<B>,
- spec: AnyWeightMatrixSpec,
- required_layout: Layout,
output_dim: u32,
input_dim: u32,
data_type: DataType,
+ spec: AnyWeightMatrixSpec,
+ required_layout: Layout,
+ tree: &ParameterTree<B>,
) -> Result<Self, WeightMatrixError<B>> {
let ParsedWeightSpec {
layout,
diff --git a/crates/uzu-engine/src/engine/classifier_model.rs b/crates/uzu-engine/src/engine/classifier_model.rs
index d92e350e7..3c9832faa 100644
--- a/crates/uzu-engine/src/engine/classifier_model.rs
+++ b/crates/uzu-engine/src/engine/classifier_model.rs
@@ -66,10 +66,10 @@ impl<B: Backend> Engine<B> {
let weight_loader = ParameterLoader::new(&weights_file, context.as_ref())?;
let classifier = ClassifierEncodable::new(
- context.as_ref(),
+ data_type,
&config.classifier_config,
&weight_loader.tree().subtree("classifier"),
- data_type,
+ context.as_ref(),
)?;
let output_labels = if let Some(output_labels) = config.classifier_config.output_labels {
diff --git a/crates/uzu-engine/src/engine/language_model/mod.rs b/crates/uzu-engine/src/engine/language_model/mod.rs
index 168ba1aa6..4e051ee1f 100644
--- a/crates/uzu-engine/src/engine/language_model/mod.rs
+++ b/crates/uzu-engine/src/engine/language_model/mod.rs
@@ -77,10 +77,10 @@ impl<B: Backend> Engine<B> {
let data_type = DataType::BF16;
let decoder = Decoder::new(
- self.context.as_ref(),
+ data_type,
&config.decoder_config,
&weight_loader.tree().subtree("decoder"),
- data_type,
+ self.context.as_ref(),
)?;
assert!(
@@ -94,7 +94,7 @@ impl<B: Backend> Engine<B> {
.transpose()?
.flatten();
- let sampling = Sampling::new(data_type, config.decoder_config.vocab_size);
+ let sampling = Sampling::new(config.decoder_config.vocab_size, data_type);
let context_ring_update = <B::Kernels as Kernels>::ContextRingUpdateKernel::new(&self.context)
.map_err(EngineLoadLanguageModelError::Backend)?;
diff --git a/crates/uzu-engine/src/engine/language_model/stream/stream.rs b/crates/uzu-engine/src/engine/language_model/stream/stream.rs
index f5a74c487..593db5397 100644
--- a/crates/uzu-engine/src/engine/language_model/stream/stream.rs
+++ b/crates/uzu-engine/src/engine/language_model/stream/stream.rs
@@ -299,9 +299,9 @@ impl<'a, B: Backend> LanguageModelStream<'a, B> {
bitmask.as_ref(),
context_ring.as_ref(),
Some(&token_ids),
- &options.sampling_method,
&batch_dim,
(sampled_row..sampled_row + 1).into(),
+ &options.sampling_method,
&mut command_buffer,
)
.map_err(LanguageModelStreamError::Backend)?,
@@ -704,9 +704,9 @@ impl<'a, B: Backend> LanguageModelStream<'a, B> {
bitmask.as_ref(),
self.context_ring.as_ref(),
Some(token_ids),
- &self.options.sampling_method,
&batch_dim,
(0..batch_dim.size()).into(),
+ &self.options.sampling_method,
&mut command_buffer,
)
.map_err(LanguageModelStreamError::Backend)?;
diff --git a/crates/uzu-engine/src/speculators/dflash_tfm.rs b/crates/uzu-engine/src/speculators/dflash_tfm.rs
index 7a37d05e3..afeaf8139 100644
--- a/crates/uzu-engine/src/speculators/dflash_tfm.rs
+++ b/crates/uzu-engine/src/speculators/dflash_tfm.rs
@@ -122,23 +122,23 @@ impl<B: Backend> DFlashTfmSpeculator<B> {
let weight_loader = ParameterLoader::new(&weights_file, &*context)?;
let speculator_tree = weight_loader.tree().subtree("speculator");
- let dflash = DFlash::new(&*context, &config.draft_config, &speculator_tree.subtree("draft_model"), data_type)?;
+ let dflash = DFlash::new(data_type, &config.draft_config, &speculator_tree.subtree("draft_model"), &*context)?;
let weaver = config
.weaver_config
.as_ref()
.map(|weaver_config| {
Weaver::new(
- &*context,
- weaver_config,
config.draft_config.vocab_size,
+ weaver_config,
&speculator_tree.subtree("weaver"),
+ &*context,
)
})
.transpose()?;
weight_loader.tree().assert_all_tensors_validated()?;
- let sampling = Sampling::new(data_type, config.draft_config.vocab_size);
+ let sampling = Sampling::new(config.draft_config.vocab_size, data_type);
Ok(Some(Self {
context,
@@ -168,7 +168,7 @@ impl<B: Backend> DFlashTfmSpeculator<B> {
accepted_indices: &[u32],
command_buffer: &mut <B::CommandBuffer as CommandBuffer>::Encoding,
) -> Result<(), B::Error> {
- self.dflash.encode_accept(state, target_features, accepted_indices, command_buffer)
+ self.dflash.encode_accept(target_features, accepted_indices, state, command_buffer)
}
pub fn make_shape(
@@ -255,10 +255,10 @@ impl<B: Backend> DFlashTfmSpeculator<B> {
child_indices: vec![1],
});
let dflash_output = self.dflash.encode_draft(
- state,
- target_output_token,
target_embedding,
+ target_output_token,
dflash_depth,
+ state,
&mut command_buffer,
)?;
let topology_nodes = (0..chain_length)
@@ -277,9 +277,9 @@ impl<B: Backend> DFlashTfmSpeculator<B> {
None::<&B::ConstantBuffer>,
None::<&B::GlobalBuffer>,
None::<&B::ConstantBuffer>,
- &SamplingMethod::Greedy,
&batch_topology,
(0..chain_length).into(),
+ &SamplingMethod::Greedy,
&mut command_buffer,
)
.map_err(DFlashTreeError::Backend)?;
@@ -331,10 +331,10 @@ impl<B: Backend> DFlashTfmSpeculator<B> {
)));
}
let dflash_output = self.dflash.encode_draft(
- state,
- target_output_token,
target_embedding,
+ target_output_token,
dflash_depth,
+ state,
&mut command_buffer,
)?;
let depth_seeds = (0..weaver.max_depth())
diff --git a/crates/uzu-engine/unit/backends/common/kernel/matmul/dispatch_paths_test.rs b/crates/uzu-engine/unit/backends/common/kernel/matmul/dispatch_paths_test.rs
index ffb867b61..f785ecb0e 100644
--- a/crates/uzu-engine/unit/backends/common/kernel/matmul/dispatch_paths_test.rs
+++ b/crates/uzu-engine/unit/backends/common/kernel/matmul/dispatch_paths_test.rs
@@ -73,15 +73,10 @@ fn run_matrix<T: ArrayElement + Float + Debug + Display>(
#[rstest]
#[test_attr(uzu_test)]
-#[case::base(1.0, false)]
-#[case::ab_scale(0.5, false)]
-#[case::accumulate(1.0, true)]
-#[case::scale_and_accumulate(0.5, true)]
-fn matches_cpu_reference_bf16(
- #[case] ab_scale: f32,
- #[case] accumulate: bool,
-) {
- run_matrix::<bf16>(|shape| Case::new(shape).with_ab_scale(ab_scale).with_accumulate(accumulate), 1.0);
+#[case::base(1.0)]
+#[case::ab_scale(0.5)]
+fn matches_cpu_reference_bf16(#[case] ab_scale: f32) {
+ run_matrix::<bf16>(|shape| Case::new(shape).with_ab_scale(ab_scale), 1.0);
}
#[uzu_test]
@@ -176,14 +171,9 @@ fn gemv_fp_output_transforms_bf16() {
bf16::data_type(),
)
.expect("MatmulKernel");
- // Small m routes to GEMV; n % 32 == 0 keeps RHT/accumulate in the GEMV path.
+ // Small m routes to GEMV; n % 32 == 0 keeps RHT in the GEMV path.
let shape = Shape::new(2, 256, 64);
- let cases = [
- Case::new(shape).with_bias(true).with_rht(true),
- Case::new(shape).with_accumulate(true),
- Case::new(shape).with_accumulate(true).with_bias(true),
- Case::new(shape).with_ab_scale(2.0).with_rht(true),
- ];
+ let cases = [Case::new(shape).with_bias(true).with_rht(true), Case::new(shape).with_ab_scale(2.0).with_rht(true)];
for case in cases {
check_case::<bf16>(&context, &mut kernel, None, case, 1.0);
}
diff --git a/crates/uzu-engine/unit/backends/common/kernel/matmul/quant_dispatch_test.rs b/crates/uzu-engine/unit/backends/common/kernel/matmul/quant_dispatch_test.rs
index 24a903df2..66b9ae8ee 100644
--- a/crates/uzu-engine/unit/backends/common/kernel/matmul/quant_dispatch_test.rs
+++ b/crates/uzu-engine/unit/backends/common/kernel/matmul/quant_dispatch_test.rs
@@ -1,9 +1,6 @@
#![cfg(backend = "metal")]
-use std::{
- error::Error,
- fmt::{Debug, Display},
-};
+use std::fmt::{Debug, Display};
use QuantParamsLayout::{GroupOutput, OutputGroup};
use QuantizationMethod::{ScaleBias, ScaleZeroPoint};
@@ -17,14 +14,11 @@ use crate::{
backends::{
common::{
Backend, CommandBufferEncoding, CommandBufferExecutable, CommandBufferPending, Context,
- gpu_types::{QuantizationMethod, QuantizationMode, gemm::GemmDTransform},
+ gpu_types::{QuantizationMethod, QuantizationMode},
kernel::{
Kernels,
activation_transform::ACTIVATION_SCALE_GROUP_SIZE,
- matmul::{
- MatmulDOps, MatmulError, MatmulKernel, MatmulOutput, QuantParams, QuantParamsLayout,
- QuantParamsStrides,
- },
+ matmul::{MatmulDOps, MatmulKernel, MatmulOutput, QuantParams, QuantParamsLayout, QuantParamsStrides},
},
},
cpu::Cpu,
@@ -410,44 +404,6 @@ fn cpu_group_major_quantized_gemm_matches_row_major() {
}
}
-#[uzu_test]
-fn quant_gemm_accumulate_returns_unsupported_dop() {
- let context = MetalContext::new().expect("Metal context");
- let input = QuantInput::<bf16>::new(64, 256, 64, 32, 4, QuantizationMethod::ScaleBias, 0);
- let mut buffers = QuantBuffers::<Metal, bf16>::allocate(&context, &input);
- let mut matmul = <<Metal as Backend>::Kernels as Kernels>::MatmulKernel::new(
- &context,
- bf16::data_type(),
- bf16::data_type(),
- bf16::data_type(),
- )
- .expect("MatmulMetalKernel");
-
- let mut command_buffer = context.create_command_buffer(None, None).unwrap();
- let mut args = quant_arguments(&mut buffers, &input);
- args.output.ops = MatmulDOps {
- accumulate: true,
- ..MatmulDOps::none()
- };
- let result = matmul.encode(args, &mut command_buffer);
-
- let err = result.expect_err("expected error");
- let matmul = err
- .source()
- .and_then(|source| source.downcast_ref::<MatmulError<Metal>>())
- .expect("expected a MatmulError source");
- assert!(
- matches!(
- matmul,
- MatmulError::UnsupportedDOp {
- bit: GemmDTransform::ACCUMULATE,
- ..
- }
- ),
- "got {matmul:?}"
- );
-}
-
#[rstest]
#[test_attr(uzu_test)]
#[case::output_group_single_group_gs64(OutputGroup, 64, 64, 64, 4, ScaleZeroPoint, 64)]
diff --git a/crates/uzu-engine/unit/backends/metal/kernel/matmul/gemv/policy_test.rs b/crates/uzu-engine/unit/backends/metal/kernel/matmul/gemv/policy_test.rs
index 8e2264b52..c4109b892 100644
--- a/crates/uzu-engine/unit/backends/metal/kernel/matmul/gemv/policy_test.rs
+++ b/crates/uzu-engine/unit/backends/metal/kernel/matmul/gemv/policy_test.rs
@@ -162,7 +162,7 @@ fn block_unaligned_quantized_k_stays_on_gemv() {
}
#[uzu_test]
-fn specialization_preserves_quantized_route_and_accumulate_tail() {
+fn specialization_preserves_quantized_route() {
let select = |n, transform| {
super::super::kernel::GemvSpecialization::select_shape(
&quant_shape(4, n, transform),
@@ -175,7 +175,7 @@ fn specialization_preserves_quantized_route_and_accumulate_tail() {
};
let clean = select(8192, GemmDTransform::empty()).expect("quantized specialization");
assert!(clean.output_row_tile() > DEFAULT_RESULTS_PER_SIMDGROUP);
- assert_eq!(select(8192 + clean.output_row_tile() / 2, GemmDTransform::ACCUMULATE), None);
+ assert!(select(8192 + clean.output_row_tile() / 2, GemmDTransform::empty()).is_some());
}
#[uzu_test]
diff --git a/crates/uzu-engine/unit/common/matmul/harness.rs b/crates/uzu-engine/unit/common/matmul/harness.rs
index c729c08f3..0c137bf46 100644
--- a/crates/uzu-engine/unit/common/matmul/harness.rs
+++ b/crates/uzu-engine/unit/common/matmul/harness.rs
@@ -28,7 +28,6 @@ pub type TestDispatch = Option<GemmEngine>;
pub struct Case {
pub shape: Shape,
pub ab_scale: f32,
- pub accumulate: bool,
pub b_transpose: bool,
pub enable_rht: bool,
pub enable_bias: bool,
@@ -39,7 +38,6 @@ impl Case {
Self {
shape,
ab_scale: 1.0,
- accumulate: false,
b_transpose: true,
enable_rht: false,
enable_bias: false,
@@ -54,14 +52,6 @@ impl Case {
self
}
- pub const fn with_accumulate(
- mut self,
- accumulate: bool,
- ) -> Self {
- self.accumulate = accumulate;
- self
- }
-
pub const fn with_rht(
mut self,
enable_rht: bool,
@@ -82,7 +72,6 @@ impl Case {
pub struct Input<T: ArrayElement + Float> {
pub a: Box<[T]>,
pub b: Box<[T]>,
- pub d_prefill: Option<Box<[T]>>,
pub rht_factors: Option<Box<[i32]>>,
pub bias: Option<Box<[T]>>,
pub case: Case,
@@ -96,9 +85,6 @@ pub fn deterministic_input<T: ArrayElement + Float>(case: Case) -> Input<T> {
} = case.shape;
let a: Vec<T> = (0..m * k).map(|i| T::from(((i % 13) as f32) * 0.1 - 0.6).unwrap()).collect();
let b: Vec<T> = (0..n * k).map(|i| T::from(((i % 17) as f32) * 0.1 - 0.8).unwrap()).collect();
- let d_prefill = case.accumulate.then(|| {
- (0..m * n).map(|i| T::from(((i % 7) as f32) * 0.03 - 0.09).unwrap()).collect::<Vec<_>>().into_boxed_slice()
- });
let rht_factors = (case.enable_rht && n % 32 == 0).then(|| {
(0..n)
.map(|i| {
@@ -117,7 +103,6 @@ pub fn deterministic_input<T: ArrayElement + Float>(case: Case) -> Input<T> {
Input {
a: a.into_boxed_slice(),
b: b.into_boxed_slice(),
- d_prefill,
rht_factors,
bias,
case,
@@ -141,17 +126,13 @@ fn run<B: Backend, T: ArrayElement + Float>(
} = input.case.shape;
let b_buffer = create_buffer_with_data::<B, T>(context, &input.b);
let a_buffer = create_buffer_with_data::<B, T>(context, &input.a);
- let mut d_buffer = if let Some(ref prefill) = input.d_prefill {
- create_buffer_with_data::<B, T>(context, prefill)
- } else {
- context.create_buffer(m as usize * n as usize * std::mem::size_of::<T>()).expect("create d buffer")
- };
+ let mut d_buffer =
+ context.create_buffer(m as usize * n as usize * std::mem::size_of::<T>()).expect("create d buffer");
let rht_buffer = input.rht_factors.as_ref().map(|factors| create_buffer_with_data::<B, i32>(context, factors));
let bias_buffer = input.bias.as_ref().map(|bias| create_buffer_with_data::<B, T>(context, bias));
let d_transform = MatmulDOps::<'_, B> {
ab_scale: input.case.ab_scale,
- accumulate: input.case.accumulate,
bias: bias_buffer.as_ref(),
rht_factors: rht_buffer.as_ref(),
soft_cap: None,
diff --git a/crates/uzu-engine/unit/encodable_block/sampling_test.rs b/crates/uzu-engine/unit/encodable_block/sampling_test.rs
index f00b7bfff..c6af3b91e 100644
--- a/crates/uzu-engine/unit/encodable_block/sampling_test.rs
+++ b/crates/uzu-engine/unit/encodable_block/sampling_test.rs
@@ -44,7 +44,7 @@ fn do_sampling_backend<B: Backend, T: ArrayElement + Float>(
method: &SamplingMethod,
batch_size: u32,
) -> Result<SamplingTestResults, TestCaseError> {
- let sampling = Sampling::<B>::new(T::data_type(), vocab_size as u32);
+ let sampling = Sampling::<B>::new(vocab_size as u32, T::data_type());
let mut command_buffer = context.create_command_buffer(None, None).unwrap();
let logits_buffer = command_buffer.allocate_constant_from_slice(logits).unwrap();
@@ -67,9 +67,9 @@ fn do_sampling_backend<B: Backend, T: ArrayElement + Float>(
bitmask_buffer.as_ref(),
None::<&B::GlobalBuffer>, // TODO
None::<&B::ConstantBuffer>, // TODO
- method,
&batch_topology,
(0..batch_size).into(),
+ method,
&mut command_buffer,
)
.unwrap();