Skip to content

armgit / uzu

Public Imported from GitHub
0

A high-performance inference engine for AI models

generic forward pass state (#159)

uuuvn4a6a017ed4de
diff --git a/crates/uzu/src/array.rs b/crates/uzu/src/array.rs
index c2ec9ba13..07524801f 100644
--- a/crates/uzu/src/array.rs
+++ b/crates/uzu/src/array.rs
@@ -229,22 +229,28 @@ impl<B: Backend> Array<B> {
}
}
+// Array extends RefCell to have .view on RefCell<Array> (aka ArrayCell)
+
+pub type ArrayCell<B> = RefCell<Array<B>>;
+
pub trait ArrayCellExt<B: Backend> {
fn view(
&self,
shape: &[usize],
- ) -> RefCell<Array<B>>;
+ ) -> ArrayCell<B>;
}
-impl<B: Backend> ArrayCellExt<B> for RefCell<Array<B>> {
+impl<B: Backend> ArrayCellExt<B> for ArrayCell<B> {
fn view(
&self,
shape: &[usize],
- ) -> RefCell<Array<B>> {
+ ) -> ArrayCell<B> {
RefCell::new(self.borrow().view(shape))
}
}
+// Array extends Context with helper functions to create arrays from context
+
pub trait ArrayContextExt {
type Backend: Backend;
diff --git a/crates/uzu/src/backends/metal/classifier_context.rs b/crates/uzu/src/backends/metal/classifier_context.rs
index 593d70497..01bcef66b 100644
--- a/crates/uzu/src/backends/metal/classifier_context.rs
+++ b/crates/uzu/src/backends/metal/classifier_context.rs
@@ -2,7 +2,7 @@ use crate::backends::metal::Metal;
use std::{cell::RefCell, fs::File, io::BufReader, path::Path, rc::Rc};
use super::{
- KernelDataType, MTLCommandBuffer, MTLCommandQueue, MTLContext, ModelShape,
+ KernelDataType, MTLCommandBuffer, MTLCommandQueue, MTLContext,
ProtocolObject, Retained,
compilation_parameters::CompilationConfig,
encodable_block::{
@@ -10,9 +10,7 @@ use super::{
Pooling, Rope,
transformer_layer::{embed_block, linear_block},
},
- forward_pass::{
- ArrayId, EncodableBlock, RopeType, ScratchBuffers, SharedBuffers,
- },
+ forward_pass::{ArrayId, EncodableBlock, RopeType},
kernel::dsl::SigmoidMetalKernel,
};
use crate::{
@@ -22,6 +20,10 @@ use crate::{
metal::error::ClassifierError,
},
config::{ClassifierModelConfig, ModelMetadata},
+ forward_pass::{
+ model_shape::ModelShape, scratch_buffers::ScratchBuffers,
+ state::SharedBuffers,
+ },
parameters::ParameterLoader,
session::types::Error,
};
@@ -30,8 +32,8 @@ pub struct ClassifierContext {
pub mtl_context: Rc<MTLContext>,
pub command_buffer: Retained<ProtocolObject<dyn MTLCommandBuffer>>,
- pub shared_buffers: Rc<RefCell<SharedBuffers>>,
- pub scratch_buffers: ScratchBuffers<MTLContext>,
+ pub shared_buffers: Rc<RefCell<SharedBuffers<Metal>>>,
+ pub scratch_buffers: ScratchBuffers<Metal>,
pub model_config: ClassifierModelConfig,
pub model_shape: ModelShape,
@@ -93,7 +95,7 @@ impl ClassifierContext {
let root_loader_view = loader.tree();
let shared_buffers = Rc::new(RefCell::new(SharedBuffers::new(
- &context,
+ context.as_ref(),
&decoder_config,
&model_shape,
)));
diff --git a/crates/uzu/src/backends/metal/encodable_block/decoder.rs b/crates/uzu/src/backends/metal/encodable_block/decoder.rs
index a24b15f66..4f14bc79b 100644
--- a/crates/uzu/src/backends/metal/encodable_block/decoder.rs
+++ b/crates/uzu/src/backends/metal/encodable_block/decoder.rs
@@ -10,12 +10,13 @@ use crate::{
DataType, DecoderConfig,
backends::metal::{
KernelDataType, MTLCommandBuffer, MTLComputeCommandEncoder, MTLContext,
- ModelShape, ProtocolObject, Retained,
+ ProtocolObject, Retained,
compilation_parameters::CompilationConfig,
encodable_block::transformer_layer::{embed_block, readout_block},
forward_pass::{ArrayId, ForwardPassState, RopeType},
},
config::{DecoderLayerType, MixerConfig},
+ forward_pass::model_shape::ModelShape,
parameters::ParameterTree,
};
diff --git a/crates/uzu/src/backends/metal/forward_pass/cache_layers.rs b/crates/uzu/src/backends/metal/forward_pass/cache_layers.rs
index 6a5a2096e..baaf49075 100644
--- a/crates/uzu/src/backends/metal/forward_pass/cache_layers.rs
+++ b/crates/uzu/src/backends/metal/forward_pass/cache_layers.rs
@@ -6,7 +6,6 @@ use super::{
AttentionBiasUpdate, INVALID_POSITION, KVCacheLayer, KVCacheLayerState,
KVSlice,
},
- model_shape::ModelShape,
short_conv_layer::ShortConvLayer,
ssm_layer::SSMLayer,
};
@@ -16,6 +15,7 @@ use crate::{
MTLCommandBuffer, ProtocolObject, Retained, kernel::KVCacheUpdate,
},
config::DecoderLayerType,
+ forward_pass::model_shape::ModelShape,
};
#[derive(Debug)]
diff --git a/crates/uzu/src/backends/metal/forward_pass/mod.rs b/crates/uzu/src/backends/metal/forward_pass/mod.rs
index 4451eaeb2..c4f610d07 100644
--- a/crates/uzu/src/backends/metal/forward_pass/mod.rs
+++ b/crates/uzu/src/backends/metal/forward_pass/mod.rs
@@ -1,8 +1,6 @@
pub mod cache_layers;
mod encoder_resolver;
pub mod kv_cache_layer;
-mod model_shape;
-mod scratch_buffers;
pub mod short_conv_layer;
pub mod ssm_layer;
pub mod state;
@@ -14,15 +12,12 @@ pub use encoder_resolver::EncoderResolver;
pub use kv_cache_layer::{
AttentionBiasUpdate, INVALID_POSITION, KVCacheLayer, KVCacheLayerState,
};
-pub use model_shape::ModelShape;
-pub use scratch_buffers::ScratchBuffers;
pub use short_conv_layer::ShortConvLayer;
pub use ssm_layer::SSMLayer;
+pub use crate::forward_pass::state::{ArrayId, HashMapId, RopeType};
pub use state::{
- ArrayCell, ArrayId, ClassifierModeState, CommonAuxBuffers, ForwardPassMode,
- ForwardPassState, HashMapId, LanguageModelGeneratorAuxBuffers,
- LanguageModelGeneratorModeState, MoeExpertWeights, RopeBuffers, RopeType,
- SharedBuffers,
+ ArrayCell, ClassifierModeState, ForwardPassMode, ForwardPassState,
+ LanguageModelGeneratorModeState,
};
pub use super::encodable_block::{EncodableBlock, EncodingParameters};
diff --git a/crates/uzu/src/backends/metal/forward_pass/state/mod.rs b/crates/uzu/src/backends/metal/forward_pass/state/mod.rs
index 91e55dd34..c2d61f065 100644
--- a/crates/uzu/src/backends/metal/forward_pass/state/mod.rs
+++ b/crates/uzu/src/backends/metal/forward_pass/state/mod.rs
@@ -1,28 +1,14 @@
-mod array_id;
-mod common_aux_buffers;
-mod hash_map_id;
-mod language_model_generator_aux_buffers;
mod mode;
-mod rope_buffers;
-mod rope_type;
-mod shared_buffers;
use std::{cell::RefCell, collections::HashMap, rc::Rc};
-pub use array_id::ArrayId;
-pub use common_aux_buffers::CommonAuxBuffers;
-pub use hash_map_id::HashMapId;
-pub use language_model_generator_aux_buffers::LanguageModelGeneratorAuxBuffers;
pub use mode::{
ClassifierModeState, ForwardPassMode, LanguageModelGeneratorModeState,
};
-pub use rope_buffers::RopeBuffers;
-pub use rope_type::RopeType;
-pub use shared_buffers::{MoeExpertWeights, SharedBuffers};
+use super::cache_layers::CacheLayers;
#[cfg(feature = "tracing")]
use super::traces::ActivationTrace;
-use super::{ModelShape, ScratchBuffers, cache_layers::CacheLayers};
use crate::{
DataType, DecoderConfig,
array::ArrayCellExt,
@@ -30,10 +16,18 @@ use crate::{
common::Context,
metal::{
MTLBlitCommandEncoder, MTLBuffer, MTLCommandBuffer,
- MTLCommandEncoder, MTLContext, MetalArray, ProtocolObject,
+ MTLCommandEncoder, MTLContext, Metal, MetalArray, ProtocolObject,
Retained,
},
},
+ forward_pass::{
+ model_shape::ModelShape,
+ scratch_buffers::ScratchBuffers,
+ state::{
+ ArrayId, CommonAuxBuffers, HashMapId,
+ LanguageModelGeneratorAuxBuffers, RopeType, SharedBuffers,
+ },
+ },
session::parameter::SamplingMethod,
utils::attention::fill_attention_bias,
};
@@ -46,9 +40,9 @@ pub struct ForwardPassState {
token_positions: ArrayCell,
token_bitmask: Option<ArrayCell>,
attention_bias: HashMap<Option<usize>, ArrayCell>,
- pub shared_buffers: Rc<RefCell<SharedBuffers>>,
- common_aux: CommonAuxBuffers,
- llm_aux: Option<LanguageModelGeneratorAuxBuffers>,
+ pub shared_buffers: Rc<RefCell<SharedBuffers<Metal>>>,
+ common_aux: CommonAuxBuffers<Metal>,
+ llm_aux: Option<LanguageModelGeneratorAuxBuffers<Metal>>,
mode: ForwardPassMode,
}
@@ -58,7 +52,7 @@ impl ForwardPassState {
// ========================================================================
fn init_token_ids(
- scratch: &ScratchBuffers<MTLContext>,
+ scratch: &ScratchBuffers<Metal>,
token_ids: &[u64],
) -> ArrayCell {
let suffix_length = token_ids.len();
@@ -68,7 +62,7 @@ impl ForwardPassState {
}
fn init_token_positions(
- scratch: &ScratchBuffers<MTLContext>,
+ scratch: &ScratchBuffers<Metal>,
token_positions: &[usize],
) -> ArrayCell {
let suffix_length = token_positions.len();
@@ -91,9 +85,9 @@ impl ForwardPassState {
context: Rc<MTLContext>,
decoder_config: &DecoderConfig,
model_shape: &ModelShape,
- scratch: &ScratchBuffers<MTLContext>,
+ scratch: &ScratchBuffers<Metal>,
cache_layers: Rc<RefCell<CacheLayers>>,
- shared_buffers: Rc<RefCell<SharedBuffers>>,
+ shared_buffers: Rc<RefCell<SharedBuffers<Metal>>>,
token_ids: &[u64],
token_positions: &[usize],
token_bitmask: Option<&[u32]>,
@@ -238,7 +232,7 @@ impl ForwardPassState {
}
fn init_llm_attention_bias(
- scratch: &ScratchBuffers<MTLContext>,
+ scratch: &ScratchBuffers<Metal>,
cache_layers: &Rc<RefCell<CacheLayers>>,
suffix_length: usize,
token_positions: &[usize],
@@ -287,8 +281,8 @@ impl ForwardPassState {
pub fn new_classifier(
context: Rc<MTLContext>,
model_shape: &ModelShape,
- scratch: &ScratchBuffers<MTLContext>,
- shared_buffers: Rc<RefCell<SharedBuffers>>,
+ scratch: &ScratchBuffers<Metal>,
+ shared_buffers: Rc<RefCell<SharedBuffers<Metal>>>,
token_ids: &[u64],
token_positions: &[usize],
bidirectional_attention: bool,
@@ -338,7 +332,7 @@ impl ForwardPassState {
}
fn init_classifier_attention_bias(
- scratch: &ScratchBuffers<MTLContext>,
+ scratch: &ScratchBuffers<Metal>,
suffix_length: usize,
bidirectional_attention: bool,
) -> HashMap<Option<usize>, ArrayCell> {
diff --git a/crates/uzu/src/backends/metal/forward_pass/traces.rs b/crates/uzu/src/backends/metal/forward_pass/traces.rs
index 0bd3a7ddf..6ab3c8e04 100644
--- a/crates/uzu/src/backends/metal/forward_pass/traces.rs
+++ b/crates/uzu/src/backends/metal/forward_pass/traces.rs
@@ -3,7 +3,8 @@ use std::{cell::RefCell, rc::Rc};
use crate::{
DataType,
array::ArrayContextExt,
- backends::metal::{MTLContext, MetalArray, ModelShape},
+ backends::metal::{MTLContext, MetalArray},
+ forward_pass::model_shape::ModelShape,
};
type ArrayCell = RefCell<MetalArray>;
diff --git a/crates/uzu/src/backends/metal/language_model_generator_context.rs b/crates/uzu/src/backends/metal/language_model_generator_context.rs
index a90bc5051..37e15d9ab 100644
--- a/crates/uzu/src/backends/metal/language_model_generator_context.rs
+++ b/crates/uzu/src/backends/metal/language_model_generator_context.rs
@@ -8,10 +8,7 @@ use std::{
use super::{
CacheLayers, Decoder, KVCacheUpdate, KernelDataType, MTLContext, Metal,
- ModelShape,
- compilation_parameters::CompilationConfig,
- forward_pass::{ScratchBuffers, SharedBuffers},
- kernel::TokenCopyKernel,
+ compilation_parameters::CompilationConfig, kernel::TokenCopyKernel,
};
use crate::{
DataType,
@@ -25,6 +22,10 @@ use crate::{
},
config::{DecoderConfig, LanguageModelConfig, ModelMetadata},
encodable_block::Sampling,
+ forward_pass::{
+ model_shape::ModelShape, scratch_buffers::ScratchBuffers,
+ state::SharedBuffers,
+ },
language_model::rng::PRng,
parameters::ParameterLoader,
session::{
@@ -136,8 +137,8 @@ pub struct LanguageModelGeneratorContext {
pub command_buffer: Retained<ProtocolObject<dyn MTLCommandBuffer>>,
pub cache_layers: Rc<RefCell<CacheLayers>>,
- pub shared_buffers: Rc<RefCell<SharedBuffers>>,
- pub scratch_buffers: ScratchBuffers<MTLContext>,
+ pub shared_buffers: Rc<RefCell<SharedBuffers<Metal>>>,
+ pub scratch_buffers: ScratchBuffers<Metal>,
pub model_config: LanguageModelConfig,
pub decoder_config: Rc<DecoderConfig>,
@@ -211,7 +212,7 @@ impl LanguageModelGeneratorContext {
let root_loader_view = loader.tree();
let shared_buffers = Rc::new(RefCell::new(SharedBuffers::new(
- &context,
+ context.as_ref(),
&decoder_config,
&model_shape,
)));
diff --git a/crates/uzu/src/backends/metal/mod.rs b/crates/uzu/src/backends/metal/mod.rs
index f4c45e5ca..019247024 100644
--- a/crates/uzu/src/backends/metal/mod.rs
+++ b/crates/uzu/src/backends/metal/mod.rs
@@ -23,7 +23,7 @@ pub use context::{
};
pub use encodable_block::Decoder;
pub use error::MTLError;
-pub use forward_pass::{CacheLayers, ForwardPassState, ModelShape};
+pub use forward_pass::{CacheLayers, ForwardPassState};
pub use kernel::{
KVCacheUpdate, KernelDataType, RopeKernel, dsl::MetalKernels,
};
diff --git a/crates/uzu/src/forward_pass/mod.rs b/crates/uzu/src/forward_pass/mod.rs
new file mode 100644
index 000000000..4dc2d5634
--- /dev/null
+++ b/crates/uzu/src/forward_pass/mod.rs
@@ -0,0 +1,3 @@
+pub mod model_shape;
+pub mod scratch_buffers;
+pub mod state;
diff --git a/crates/uzu/src/backends/metal/forward_pass/model_shape.rs b/crates/uzu/src/forward_pass/model_shape.rs
similarity index 100%
rename from crates/uzu/src/backends/metal/forward_pass/model_shape.rs
rename to crates/uzu/src/forward_pass/model_shape.rs
diff --git a/crates/uzu/src/backends/metal/forward_pass/scratch_buffers.rs b/crates/uzu/src/forward_pass/scratch_buffers.rs
similarity index 51%
rename from crates/uzu/src/backends/metal/forward_pass/scratch_buffers.rs
rename to crates/uzu/src/forward_pass/scratch_buffers.rs
index ed7b8cc11..af1ab7279 100644
--- a/crates/uzu/src/backends/metal/forward_pass/scratch_buffers.rs
+++ b/crates/uzu/src/forward_pass/scratch_buffers.rs
@@ -1,78 +1,77 @@
-use std::{cell::RefCell, collections::HashMap};
+use std::{
+ cell::RefCell,
+ collections::{HashMap, HashSet},
+};
-use super::model_shape::ModelShape;
use crate::{
DataType,
- array::ArrayContextExt,
- backends::common::Context,
+ array::{ArrayCell, ArrayContextExt},
+ backends::common::Backend,
config::{DecoderConfig, MLPConfig},
+ forward_pass::model_shape::ModelShape,
};
-type Array<C> = RefCell<crate::array::Array<<C as Context>::Backend>>;
-
-pub struct ScratchBuffers<C: Context> {
+pub struct ScratchBuffers<B: Backend> {
// 1-D
- pub token_ids: Array<C>,
- pub token_positions: Array<C>,
- pub token_bitmask: Array<C>,
- pub token_seeds: Array<C>,
- pub sampling_output: Array<C>,
+ pub token_ids: ArrayCell<B>,
+ pub token_positions: ArrayCell<B>,
+ pub token_bitmask: ArrayCell<B>,
+ pub token_seeds: ArrayCell<B>,
+ pub sampling_output: ArrayCell<B>,
// 2-D
- pub attention_window_size_to_bias: HashMap<Option<usize>, Array<C>>,
- pub logits: Array<C>,
- pub main: Array<C>,
- pub shortcut: Array<C>,
- pub qkv: Array<C>,
- pub attention_output: Array<C>,
- pub mlp_fused_up: Array<C>,
- pub mlp_hidden: Array<C>,
- pub ssm_inproj: Option<Array<C>>,
- pub ssm_packed: Option<Array<C>>,
- pub ssm_conv_padded: Option<Array<C>>,
- pub short_conv_padded: Option<Array<C>>,
- pub ssm_x: Option<Array<C>>,
- pub ssm_b: Option<Array<C>>,
- pub ssm_c: Option<Array<C>>,
- pub ssm_dt: Option<Array<C>>,
- pub ssm_z: Option<Array<C>>,
+ pub attention_window_size_to_bias: HashMap<Option<usize>, ArrayCell<B>>,
+ pub logits: ArrayCell<B>,
+ pub main: ArrayCell<B>,
+ pub shortcut: ArrayCell<B>,
+ pub qkv: ArrayCell<B>,
+ pub attention_output: ArrayCell<B>,
+ pub mlp_fused_up: ArrayCell<B>,
+ pub mlp_hidden: ArrayCell<B>,
+ pub ssm_inproj: Option<ArrayCell<B>>,
+ pub ssm_packed: Option<ArrayCell<B>>,
+ pub ssm_conv_padded: Option<ArrayCell<B>>,
+ pub short_conv_padded: Option<ArrayCell<B>>,
+ pub ssm_x: Option<ArrayCell<B>>,
+ pub ssm_b: Option<ArrayCell<B>>,
+ pub ssm_c: Option<ArrayCell<B>>,
+ pub ssm_dt: Option<ArrayCell<B>>,
+ pub ssm_z: Option<ArrayCell<B>>,
// 3-D
- pub rotated_queries: Array<C>,
- pub rotated_keys: Array<C>,
- pub extracted_values: Array<C>,
+ pub rotated_queries: ArrayCell<B>,
+ pub rotated_keys: ArrayCell<B>,
+ pub extracted_values: ArrayCell<B>,
// 2-pass attention intermediate buffers
- pub attention_partials: Array<C>, // [num_heads * max_suffix_len * total_blocks_count * head_dim]
- pub attention_sums: Array<C>, // [num_heads * max_suffix_len * total_blocks_count]
- pub attention_maxs: Array<C>, // [num_heads * max_suffix_len * total_blocks_count]
+ pub attention_partials: ArrayCell<B>, // [num_heads * max_suffix_len * total_blocks_count * head_dim]
+ pub attention_sums: ArrayCell<B>, // [num_heads * max_suffix_len * total_blocks_count]
+ pub attention_maxs: ArrayCell<B>, // [num_heads * max_suffix_len * total_blocks_count]
- pub moe_topk_ids: Option<Array<C>>,
- pub moe_topk_probs: Option<Array<C>>,
- pub moe_offsets: Option<Array<C>>,
- pub moe_sumk: Option<Array<C>>,
- pub moe_bucketed_token_ids: Option<Array<C>>,
- pub moe_bucketed_probs: Option<Array<C>>,
- pub moe_x_perm: Option<Array<C>>,
- pub moe_tok2row: Option<Array<C>>,
- pub moe_y_partial: Option<Array<C>>,
- pub moe_hidden: Option<Array<C>>,
- pub moe_two_pass_row_expert_map: Option<Array<C>>,
- pub moe_tile_counts: Option<Array<C>>,
- pub moe_tile_offsets: Option<Array<C>>,
- pub moe_tile_map: Option<Array<C>>,
- pub moe_total_tiles: Option<Array<C>>,
- pub moe_dispatch_args: Option<Array<C>>,
- pub moe_scatter_partials: Option<Array<C>>,
- pub moe_scatter_block_bases: Option<Array<C>>,
- pub moe_block_alloc: Option<Array<C>>,
+ pub moe_topk_ids: Option<ArrayCell<B>>,
+ pub moe_topk_probs: Option<ArrayCell<B>>,
+ pub moe_offsets: Option<ArrayCell<B>>,
+ pub moe_sumk: Option<ArrayCell<B>>,
+ pub moe_bucketed_token_ids: Option<ArrayCell<B>>,
+ pub moe_bucketed_probs: Option<ArrayCell<B>>,
+ pub moe_x_perm: Option<ArrayCell<B>>,
+ pub moe_tok2row: Option<ArrayCell<B>>,
+ pub moe_y_partial: Option<ArrayCell<B>>,
+ pub moe_hidden: Option<ArrayCell<B>>,
+ pub moe_two_pass_row_expert_map: Option<ArrayCell<B>>,
+ pub moe_tile_counts: Option<ArrayCell<B>>,
+ pub moe_tile_offsets: Option<ArrayCell<B>>,
+ pub moe_tile_map: Option<ArrayCell<B>>,
+ pub moe_total_tiles: Option<ArrayCell<B>>,
+ pub moe_dispatch_args: Option<ArrayCell<B>>,
+ pub moe_scatter_partials: Option<ArrayCell<B>>,
+ pub moe_scatter_block_bases: Option<ArrayCell<B>>,
+ pub moe_block_alloc: Option<ArrayCell<B>>,
}
-impl<C: Context> ScratchBuffers<C> {
- // TODO: use device arrays instead of MTLBuffers
- /// Allocate the buffers with `StorageModeShared` so that they are CPU-accessible as well.
+impl<B: Backend> ScratchBuffers<B> {
pub fn new(
- context: &C,
+ context: &B::Context,
decoder_config: &DecoderConfig,
model_shape: &ModelShape,
max_prefix_len: usize,
@@ -80,7 +79,7 @@ impl<C: Context> ScratchBuffers<C> {
) -> Self {
// Helper closure for allocation
let alloc =
- |shape: &[usize], dtype: DataType, label: &str| -> Array<C> {
+ |shape: &[usize], dtype: DataType, label: &str| -> ArrayCell<B> {
let array = context.create_array(
shape,
dtype,
@@ -91,8 +90,6 @@ impl<C: Context> ScratchBuffers<C> {
let act_ty = model_shape.activation_data_type();
- let partials_shape =
- model_shape.attention_partials_shape(max_suffix_len);
let sums_maxs_shape = model_shape.attention_sums_shape(max_suffix_len);
let moe = match &decoder_config.layer_config.mlp_config {
MLPConfig::MixtureOfExperts(moe) => Some(moe),
@@ -100,7 +97,6 @@ impl<C: Context> ScratchBuffers<C> {
};
let moe_max_routed =
moe.map(|moe| max_suffix_len * moe.num_experts_per_token);
- let moe_mixture_size = moe.map(|moe| moe.mixture_size);
let moe_scatter_entries = moe.map(|moe| {
let num_blocks = ((max_suffix_len + 255) / 256).max(1);
let num_tiles = ((moe.mixture_size + 512 - 1) / 512).max(1);
@@ -128,40 +124,26 @@ impl<C: Context> ScratchBuffers<C> {
),
// 2-D
- attention_window_size_to_bias: {
- // Collect unique window sizes across all layers
- let unique_window_sizes: std::collections::HashSet<
- Option<usize>,
- > = model_shape
- .sliding_window_length_per_layer
- .iter()
- .copied()
- .collect();
-
- // Create one buffer per unique window size
- unique_window_sizes
- .into_iter()
- .map(|window_size| {
- (window_size, {
- let label = match window_size {
- Some(window_size) => format!(
- "attention_bias_for_window_size_{window_size}"
- ),
- None => "attention_bias_for_window_size_none".to_string(),
- };
- alloc(
- &[
- max_suffix_len,
- max_suffix_len + max_prefix_len,
- ],
- act_ty,
- label
- .as_str(),
- )
- })
- })
- .collect::<HashMap<Option<usize>, Array<C>>>()
- },
+ attention_window_size_to_bias: model_shape
+ .sliding_window_length_per_layer
+ .iter()
+ .copied()
+ .collect::<HashSet<_>>()
+ .into_iter()
+ .map(|window_size| {
+ let label = match window_size {
+ Some(ws) => {
+ format!("attention_bias_for_window_size_{ws}")
+ },
+ None => {
+ "attention_bias_for_window_size_none".to_string()
+ },
+ };
+ let shape =
+ [max_suffix_len, max_suffix_len + max_prefix_len];
+ (window_size, alloc(&shape, act_ty, &label))
+ })
+ .collect(),
logits: alloc(
&model_shape.logits_shape(max_suffix_len),
act_ty,
@@ -238,7 +220,7 @@ impl<C: Context> ScratchBuffers<C> {
),
attention_partials: alloc(
- &partials_shape,
+ &model_shape.attention_partials_shape(max_suffix_len),
act_ty,
"attention_partials",
),
@@ -246,54 +228,79 @@ impl<C: Context> ScratchBuffers<C> {
attention_maxs: alloc(&sums_maxs_shape, act_ty, "attention_maxs"),
moe_topk_ids: moe.map(|moe| {
- let shape = model_shape.moe_topk_ids_shape(
- max_suffix_len,
- moe.num_experts_per_token,
- );
- alloc(&shape, DataType::U32, "moe_topk_ids")
+ alloc(
+ &model_shape.moe_topk_ids_shape(
+ max_suffix_len,
+ moe.num_experts_per_token,
+ ),
+ DataType::U32,
+ "moe_topk_ids",
+ )
}),
moe_topk_probs: moe.map(|moe| {
- let shape = model_shape.moe_topk_probs_shape(
- max_suffix_len,
- moe.num_experts_per_token,
- );
- alloc(&shape, act_ty, "moe_topk_probs")
+ alloc(
+ &model_shape.moe_topk_probs_shape(
+ max_suffix_len,
+ moe.num_experts_per_token,
+ ),
+ act_ty,
+ "moe_topk_probs",
+ )
}),
- moe_offsets: moe_mixture_size.map(|mixture_size| {
- let shape = model_shape.moe_offsets_shape(mixture_size);
- alloc(&shape, DataType::U32, "moe_offsets")
+ moe_offsets: moe.map(|moe| {
+ alloc(
+ &model_shape.moe_offsets_shape(moe.mixture_size),
+ DataType::U32,
+ "moe_offsets",
+ )
}),
moe_sumk: moe.map(|_| {
- let shape = model_shape.moe_sumk_shape();
- alloc(&shape, DataType::U32, "moe_sumk")
+ alloc(&model_shape.moe_sumk_shape(), DataType::U32, "moe_sumk")
}),
moe_bucketed_token_ids: moe_max_routed.map(|max_routed| {
- let shape =
- model_shape.moe_bucketed_token_ids_shape(max_routed);
- alloc(&shape, DataType::U32, "moe_bucketed_token_ids")
+ alloc(
+ &model_shape.moe_bucketed_token_ids_shape(max_routed),
+ DataType::U32,
+ "moe_bucketed_token_ids",
+ )
}),
moe_bucketed_probs: moe_max_routed.map(|max_routed| {
- let shape = model_shape.moe_bucketed_probs_shape(max_routed);
- alloc(&shape, act_ty, "moe_bucketed_probs")
+ alloc(
+ &model_shape.moe_bucketed_probs_shape(max_routed),
+ act_ty,
+ "moe_bucketed_probs",
+ )
}),
moe_x_perm: moe_max_routed.map(|max_routed| {
- let shape = model_shape.moe_x_perm_shape(max_routed);
- alloc(&shape, DataType::F16, "moe_x_perm")
+ alloc(
+ &model_shape.moe_x_perm_shape(max_routed),
+ DataType::F16,
+ "moe_x_perm",
+ )
}),
moe_tok2row: moe.map(|moe| {
- let shape = model_shape.moe_tok2row_shape(
- max_suffix_len,
- moe.num_experts_per_token,
- );
- alloc(&shape, DataType::I32, "moe_tok2row")
+ alloc(
+ &model_shape.moe_tok2row_shape(
+ max_suffix_len,
+ moe.num_experts_per_token,
+ ),
+ DataType::I32,
+ "moe_tok2row",
+ )
}),
moe_y_partial: moe_max_routed.map(|max_routed| {
- let shape = model_shape.moe_y_partial_shape(max_routed);
- alloc(&shape, DataType::F16, "moe_y_partial")
+ alloc(
+ &model_shape.moe_y_partial_shape(max_routed),
+ DataType::F16,
+ "moe_y_partial",
+ )
}),
moe_hidden: moe_max_routed.map(|max_routed| {
- let shape = model_shape.moe_hidden_shape(max_routed);
- alloc(&shape, DataType::F32, "moe_hidden")
+ alloc(
+ &model_shape.moe_hidden_shape(max_routed),
+ DataType::F32,
+ "moe_hidden",
+ )
}),
moe_two_pass_row_expert_map: moe_max_routed.map(|max_routed| {
alloc(
@@ -302,25 +309,40 @@ impl<C: Context> ScratchBuffers<C> {
"moe_two_pass_row_expert_map",
)
}),
- moe_tile_counts: moe_mixture_size.map(|mixture_size| {
- let shape = model_shape.moe_counts_shape(mixture_size);
- alloc(&shape, DataType::U32, "moe_tile_counts")
+ moe_tile_counts: moe.map(|moe| {
+ alloc(
+ &model_shape.moe_counts_shape(moe.mixture_size),
+ DataType::U32,
+ "moe_tile_counts",
+ )
}),
- moe_tile_offsets: moe_mixture_size.map(|mixture_size| {
- let shape = model_shape.moe_offsets_shape(mixture_size);
- alloc(&shape, DataType::U32, "moe_tile_offsets")
+ moe_tile_offsets: moe.map(|moe| {
+ alloc(
+ &model_shape.moe_offsets_shape(moe.mixture_size),
+ DataType::U32,
+ "moe_tile_offsets",
+ )
}),
moe_tile_map: moe_max_routed.map(|max_routed| {
- let shape = model_shape.moe_tile_map_shape(max_routed);
- alloc(&shape, DataType::U32, "moe_tile_map")
+ alloc(
+ &model_shape.moe_tile_map_shape(max_routed),
+ DataType::U32,
+ "moe_tile_map",
+ )
}),
moe_total_tiles: moe.map(|_| {
- let shape = model_shape.moe_total_tiles_shape();
- alloc(&shape, DataType::U32, "moe_total_tiles")
+ alloc(
+ &model_shape.moe_total_tiles_shape(),
+ DataType::U32,
+ "moe_total_tiles",
+ )
}),
moe_dispatch_args: moe.map(|_| {
- let shape = model_shape.moe_dispatch_args_shape();
- alloc(&shape, DataType::U32, "moe_dispatch_args")
+ alloc(
+ &model_shape.moe_dispatch_args_shape(),
+ DataType::U32,
+ "moe_dispatch_args",
+ )
}),
moe_scatter_partials: moe_scatter_entries.map(|entries| {
alloc(&[entries], DataType::U32, "moe_scatter_partials")
diff --git a/crates/uzu/src/backends/metal/forward_pass/state/array_id.rs b/crates/uzu/src/forward_pass/state/array_id.rs
similarity index 100%
rename from crates/uzu/src/backends/metal/forward_pass/state/array_id.rs
rename to crates/uzu/src/forward_pass/state/array_id.rs
diff --git a/crates/uzu/src/backends/metal/forward_pass/state/common_aux_buffers.rs b/crates/uzu/src/forward_pass/state/common_aux_buffers.rs
similarity index 72%
rename from crates/uzu/src/backends/metal/forward_pass/state/common_aux_buffers.rs
rename to crates/uzu/src/forward_pass/state/common_aux_buffers.rs
index e5d516905..f0ccedb7d 100644
--- a/crates/uzu/src/backends/metal/forward_pass/state/common_aux_buffers.rs
+++ b/crates/uzu/src/forward_pass/state/common_aux_buffers.rs
@@ -1,32 +1,28 @@
-use std::cell::RefCell;
-
-use super::super::{ModelShape, ScratchBuffers};
use crate::{
- array::ArrayCellExt,
- backends::metal::{MTLContext, MetalArray},
+ array::{ArrayCell, ArrayCellExt},
+ backends::common::Backend,
+ forward_pass::{model_shape::ModelShape, scratch_buffers::ScratchBuffers},
};
-type ArrayCell = RefCell<MetalArray>;
-
-pub struct CommonAuxBuffers {
+pub struct CommonAuxBuffers<B: Backend> {
pub suffix_length: usize,
- pub main: ArrayCell,
- pub shortcut: ArrayCell,
- pub qkv: ArrayCell,
- pub attention_output: ArrayCell,
- pub mlp_fused_up: ArrayCell,
- pub mlp_hidden: ArrayCell,
- pub rotated_queries: ArrayCell,
- pub rotated_keys: ArrayCell,
- pub extracted_values: ArrayCell,
- pub attention_partials: ArrayCell,
- pub attention_sums: ArrayCell,
- pub attention_maxs: ArrayCell,
+ pub main: ArrayCell<B>,
+ pub shortcut: ArrayCell<B>,
+ pub qkv: ArrayCell<B>,
+ pub attention_output: ArrayCell<B>,
+ pub mlp_fused_up: ArrayCell<B>,
+ pub mlp_hidden: ArrayCell<B>,
+ pub rotated_queries: ArrayCell<B>,
+ pub rotated_keys: ArrayCell<B>,
+ pub extracted_values: ArrayCell<B>,
+ pub attention_partials: ArrayCell<B>,
+ pub attention_sums: ArrayCell<B>,
+ pub attention_maxs: ArrayCell<B>,
}
-impl CommonAuxBuffers {
+impl<B: Backend> CommonAuxBuffers<B> {
pub fn new(
- scratch: &ScratchBuffers<MTLContext>,
+ scratch: &ScratchBuffers<B>,
model_shape: &ModelShape,
suffix_length: usize,
) -> Self {
diff --git a/crates/uzu/src/backends/metal/forward_pass/state/hash_map_id.rs b/crates/uzu/src/forward_pass/state/hash_map_id.rs
similarity index 100%
rename from crates/uzu/src/backends/metal/forward_pass/state/hash_map_id.rs
rename to crates/uzu/src/forward_pass/state/hash_map_id.rs
diff --git a/crates/uzu/src/backends/metal/forward_pass/state/language_model_generator_aux_buffers.rs b/crates/uzu/src/forward_pass/state/language_model_generator_aux_buffers.rs
similarity index 58%
rename from crates/uzu/src/backends/metal/forward_pass/state/language_model_generator_aux_buffers.rs
rename to crates/uzu/src/forward_pass/state/language_model_generator_aux_buffers.rs
index 46dc4186c..27bfedd02 100644
--- a/crates/uzu/src/backends/metal/forward_pass/state/language_model_generator_aux_buffers.rs
+++ b/crates/uzu/src/forward_pass/state/language_model_generator_aux_buffers.rs
@@ -1,50 +1,46 @@
-use std::cell::RefCell;
-
-use super::super::{ModelShape, ScratchBuffers};
use crate::{
DecoderConfig,
- array::ArrayCellExt,
- backends::metal::{MTLContext, MetalArray},
+ array::{ArrayCell, ArrayCellExt},
+ backends::common::Backend,
config::MLPConfig,
+ forward_pass::{model_shape::ModelShape, scratch_buffers::ScratchBuffers},
};
-type ArrayCell = RefCell<MetalArray>;
-
-pub struct LanguageModelGeneratorAuxBuffers {
- pub ssm_inproj: Option<ArrayCell>,
- pub ssm_packed: Option<ArrayCell>,
- pub ssm_conv_padded: Option<ArrayCell>,
- pub short_conv_padded: Option<ArrayCell>,
- pub ssm_x: Option<ArrayCell>,
- pub ssm_b: Option<ArrayCell>,
- pub ssm_c: Option<ArrayCell>,
- pub ssm_dt: Option<ArrayCell>,
- pub ssm_z: Option<ArrayCell>,
+pub struct LanguageModelGeneratorAuxBuffers<B: Backend> {
+ pub ssm_inproj: Option<ArrayCell<B>>,
+ pub ssm_packed: Option<ArrayCell<B>>,
+ pub ssm_conv_padded: Option<ArrayCell<B>>,
+ pub short_conv_padded: Option<ArrayCell<B>>,
+ pub ssm_x: Option<ArrayCell<B>>,
+ pub ssm_b: Option<ArrayCell<B>>,
+ pub ssm_c: Option<ArrayCell<B>>,
+ pub ssm_dt: Option<ArrayCell<B>>,
+ pub ssm_z: Option<ArrayCell<B>>,
// MoE buffers
- pub moe_topk_ids: Option<ArrayCell>,
- pub moe_topk_probs: Option<ArrayCell>,
- pub moe_offsets: Option<ArrayCell>,
- pub moe_sumk: Option<ArrayCell>,
- pub moe_bucketed_token_ids: Option<ArrayCell>,
- pub moe_bucketed_probs: Option<ArrayCell>,
- pub moe_x_perm: Option<ArrayCell>,
- pub moe_tok2row: Option<ArrayCell>,
- pub moe_y_partial: Option<ArrayCell>,
- pub moe_hidden: Option<ArrayCell>,
- pub moe_two_pass_row_expert_map: Option<ArrayCell>,
- pub moe_tile_counts: Option<ArrayCell>,
- pub moe_tile_offsets: Option<ArrayCell>,
- pub moe_tile_map: Option<ArrayCell>,
- pub moe_total_tiles: Option<ArrayCell>,
- pub moe_dispatch_args: Option<ArrayCell>,
- pub moe_scatter_partials: Option<ArrayCell>,
- pub moe_scatter_block_bases: Option<ArrayCell>,
- pub moe_block_alloc: Option<ArrayCell>,
+ pub moe_topk_ids: Option<ArrayCell<B>>,
+ pub moe_topk_probs: Option<ArrayCell<B>>,
+ pub moe_offsets: Option<ArrayCell<B>>,
+ pub moe_sumk: Option<ArrayCell<B>>,
+ pub moe_bucketed_token_ids: Option<ArrayCell<B>>,
+ pub moe_bucketed_probs: Option<ArrayCell<B>>,
+ pub moe_x_perm: Option<ArrayCell<B>>,
+ pub moe_tok2row: Option<ArrayCell<B>>,
+ pub moe_y_partial: Option<ArrayCell<B>>,
+ pub moe_hidden: Option<ArrayCell<B>>,
+ pub moe_two_pass_row_expert_map: Option<ArrayCell<B>>,
+ pub moe_tile_counts: Option<ArrayCell<B>>,
+ pub moe_tile_offsets: Option<ArrayCell<B>>,
+ pub moe_tile_map: Option<ArrayCell<B>>,
+ pub moe_total_tiles: Option<ArrayCell<B>>,
+ pub moe_dispatch_args: Option<ArrayCell<B>>,
+ pub moe_scatter_partials: Option<ArrayCell<B>>,
+ pub moe_scatter_block_bases: Option<ArrayCell<B>>,
+ pub moe_block_alloc: Option<ArrayCell<B>>,
}
-impl LanguageModelGeneratorAuxBuffers {
+impl<B: Backend> LanguageModelGeneratorAuxBuffers<B> {
pub fn new(
- scratch: &ScratchBuffers<MTLContext>,
+ scratch: &ScratchBuffers<B>,
decoder_config: &DecoderConfig,
model_shape: &ModelShape,
suffix_length: usize,
@@ -53,14 +49,14 @@ impl LanguageModelGeneratorAuxBuffers {
MLPConfig::MixtureOfExperts(moe) => Some(moe),
_ => None,
};
- let num_experts_per_token = moe.map(|moe| moe.num_experts_per_token);
- let mixture_size = moe.map(|moe| moe.mixture_size);
- let max_routed = num_experts_per_token.map(|k| suffix_length * k);
+ let max_routed =
+ moe.map(|moe| suffix_length * moe.num_experts_per_token);
let num_blocks = suffix_length.div_ceil(256).max(1);
- let scatter_entries =
- mixture_size.map(|e| num_blocks * e.div_ceil(512).max(1) * 512);
+ let scatter_entries = moe.map(|moe| {
+ num_blocks * moe.mixture_size.div_ceil(512).max(1) * 512
+ });
let block_alloc_entries =
- mixture_size.map(|e| num_blocks * e.div_ceil(512).max(1));
+ moe.map(|moe| num_blocks * moe.mixture_size.div_ceil(512).max(1));
Self {
ssm_inproj: scratch
@@ -108,21 +104,27 @@ impl LanguageModelGeneratorAuxBuffers {
.as_ref()
.zip(model_shape.ssm_z_shape(suffix_length))
.map(|(buf, shape)| buf.view(&shape)),
- moe_topk_ids: num_experts_per_token
- .zip(scratch.moe_topk_ids.as_ref())
- .map(|(k, buf)| {
- buf.view(&model_shape.moe_topk_ids_shape(suffix_length, k))
- }),
- moe_topk_probs: num_experts_per_token
- .zip(scratch.moe_topk_probs.as_ref())
- .map(|(k, buf)| {
- buf.view(
- &model_shape.moe_topk_probs_shape(suffix_length, k),
- )
- }),
- moe_offsets: mixture_size
- .zip(scratch.moe_offsets.as_ref())
- .map(|(e, buf)| buf.view(&model_shape.moe_offsets_shape(e))),
+ moe_topk_ids: moe.zip(scratch.moe_topk_ids.as_ref()).map(
+ |(moe, buf)| {
+ buf.view(&model_shape.moe_topk_ids_shape(
+ suffix_length,
+ moe.num_experts_per_token,
+ ))
+ },
+ ),
+ moe_topk_probs: moe.zip(scratch.moe_topk_probs.as_ref()).map(
+ |(moe, buf)| {
+ buf.view(&model_shape.moe_topk_probs_shape(
+ suffix_length,
+ moe.num_experts_per_token,
+ ))
+ },
+ ),
+ moe_offsets: moe.zip(scratch.moe_offsets.as_ref()).map(
+ |(moe, buf)| {
+ buf.view(&model_shape.moe_offsets_shape(moe.mixture_size))
+ },
+ ),
moe_sumk: moe
.and(scratch.moe_sumk.as_ref())
.map(|buf| buf.view(&model_shape.moe_sumk_shape())),
@@ -143,11 +145,14 @@ impl LanguageModelGeneratorAuxBuffers {
buf.view(&model_shape.moe_x_perm_shape(max_routed))
},
),
- moe_tok2row: num_experts_per_token
- .zip(scratch.moe_tok2row.as_ref())
- .map(|(k, buf)| {
- buf.view(&model_shape.moe_tok2row_shape(suffix_length, k))
- }),
+ moe_tok2row: moe.zip(scratch.moe_tok2row.as_ref()).map(
+ |(moe, buf)| {
+ buf.view(&model_shape.moe_tok2row_shape(
+ suffix_length,
+ moe.num_experts_per_token,
+ ))
+ },
+ ),
moe_y_partial: max_routed.zip(scratch.moe_y_partial.as_ref()).map(
|(max_routed, buf)| {
buf.view(&model_shape.moe_y_partial_shape(max_routed))
@@ -161,12 +166,16 @@ impl LanguageModelGeneratorAuxBuffers {
moe_two_pass_row_expert_map: max_routed
.zip(scratch.moe_two_pass_row_expert_map.as_ref())
.map(|(max_routed, buf)| buf.view(&[max_routed])),
- moe_tile_counts: mixture_size
- .zip(scratch.moe_tile_counts.as_ref())
- .map(|(e, buf)| buf.view(&model_shape.moe_counts_shape(e))),
- moe_tile_offsets: mixture_size
- .zip(scratch.moe_tile_offsets.as_ref())
- .map(|(e, buf)| buf.view(&model_shape.moe_offsets_shape(e))),
+ moe_tile_counts: moe.zip(scratch.moe_tile_counts.as_ref()).map(
+ |(moe, buf)| {
+ buf.view(&model_shape.moe_counts_shape(moe.mixture_size))
+ },
+ ),
+ moe_tile_offsets: moe.zip(scratch.moe_tile_offsets.as_ref()).map(
+ |(moe, buf)| {
+ buf.view(&model_shape.moe_offsets_shape(moe.mixture_size))
+ },
+ ),
moe_tile_map: max_routed.zip(scratch.moe_tile_map.as_ref()).map(
|(max_routed, buf)| {
buf.view(&model_shape.moe_tile_map_shape(max_routed))
diff --git a/crates/uzu/src/forward_pass/state/mod.rs b/crates/uzu/src/forward_pass/state/mod.rs
new file mode 100644
index 000000000..b211f2955
--- /dev/null
+++ b/crates/uzu/src/forward_pass/state/mod.rs
@@ -0,0 +1,17 @@
+mod array_id;
+mod hash_map_id;
+mod rope_type;
+
+mod common_aux_buffers;
+mod language_model_generator_aux_buffers;
+mod rope_buffers;
+mod shared_buffers;
+
+pub use array_id::ArrayId;
+pub use hash_map_id::HashMapId;
+pub use rope_type::RopeType;
+
+pub use common_aux_buffers::CommonAuxBuffers;
+pub use language_model_generator_aux_buffers::LanguageModelGeneratorAuxBuffers;
+pub use rope_buffers::RopeBuffers;
+pub use shared_buffers::{MoeExpertWeights, SharedBuffers};
diff --git a/crates/uzu/src/backends/metal/forward_pass/state/rope_buffers.rs b/crates/uzu/src/forward_pass/state/rope_buffers.rs
similarity index 80%
rename from crates/uzu/src/backends/metal/forward_pass/state/rope_buffers.rs
rename to crates/uzu/src/forward_pass/state/rope_buffers.rs
index efe1ce8a9..d21a65db2 100644
--- a/crates/uzu/src/backends/metal/forward_pass/state/rope_buffers.rs
+++ b/crates/uzu/src/forward_pass/state/rope_buffers.rs
@@ -1,24 +1,22 @@
use std::cell::RefCell;
-use super::super::ModelShape;
use crate::{
- array::ArrayContextExt,
- backends::metal::{MTLContext, MetalArray},
+ array::{ArrayCell, ArrayContextExt},
+ backends::common::Backend,
+ forward_pass::model_shape::ModelShape,
parameters::ParameterTree,
};
-type ArrayCell = RefCell<MetalArray>;
-
-pub struct RopeBuffers {
+pub struct RopeBuffers<B: Backend> {
/// [rope_max_sequence_length, head_dim]
- pub cosines: ArrayCell,
+ pub cosines: ArrayCell<B>,
/// [rope_max_sequence_length, head_dim]
- pub sines: ArrayCell,
+ pub sines: ArrayCell<B>,
}
-impl RopeBuffers {
+impl<B: Backend> RopeBuffers<B> {
pub fn new(
- context: &MTLContext,
+ context: &B::Context,
model_shape: &ModelShape,
) -> Self {
let rotated_queries_shape = model_shape.rotated_queries_shape(1);
@@ -41,7 +39,7 @@ impl RopeBuffers {
pub fn update_data(
&mut self,
- parameter_tree: &ParameterTree<MTLContext>,
+ parameter_tree: &ParameterTree<B::Context>,
rope_name: &str,
) {
let Ok(rope_tree) = parameter_tree.subtree(rope_name) else {
diff --git a/crates/uzu/src/backends/metal/forward_pass/state/rope_type.rs b/crates/uzu/src/forward_pass/state/rope_type.rs
similarity index 100%
rename from crates/uzu/src/backends/metal/forward_pass/state/rope_type.rs
rename to crates/uzu/src/forward_pass/state/rope_type.rs
diff --git a/crates/uzu/src/backends/metal/forward_pass/state/shared_buffers.rs b/crates/uzu/src/forward_pass/state/shared_buffers.rs
similarity index 58%
rename from crates/uzu/src/backends/metal/forward_pass/state/shared_buffers.rs
rename to crates/uzu/src/forward_pass/state/shared_buffers.rs
index 9327de281..c8040d93e 100644
--- a/crates/uzu/src/backends/metal/forward_pass/state/shared_buffers.rs
+++ b/crates/uzu/src/forward_pass/state/shared_buffers.rs
@@ -2,78 +2,68 @@ use std::cell::RefCell;
use half::{bf16, f16};
-use super::{super::ModelShape, RopeBuffers};
use crate::{
DataType,
- array::ArrayContextExt,
- backends::metal::{MTLContext, MetalArray},
+ array::{ArrayCell, ArrayContextExt},
+ backends::common::Backend,
+ config::{DecoderConfig, MLPConfig},
+ forward_pass::model_shape::ModelShape,
parameters::ParameterTree,
};
-type ArrayCell = RefCell<MetalArray>;
+use super::RopeBuffers;
-pub struct MoeExpertWeights {
- pub w1: ArrayCell,
- pub w2: ArrayCell,
- pub w3: ArrayCell,
+pub struct MoeExpertWeights<B: Backend> {
+ pub w1: ArrayCell<B>,
+ pub w2: ArrayCell<B>,
+ pub w3: ArrayCell<B>,
}
-pub struct SharedBuffers {
- pub global_rope: Option<RopeBuffers>,
- pub local_rope: Option<RopeBuffers>,
- pub moe_expert_weights: Option<Vec<MoeExpertWeights>>,
- pub attention_sinks: Option<Vec<ArrayCell>>,
+pub struct SharedBuffers<B: Backend> {
+ pub global_rope: Option<RopeBuffers<B>>,
+ pub local_rope: Option<RopeBuffers<B>>,
+ pub moe_expert_weights: Option<Vec<MoeExpertWeights<B>>>,
+ pub attention_sinks: Option<Vec<ArrayCell<B>>>,
}
-impl SharedBuffers {
+impl<B: Backend> SharedBuffers<B> {
pub fn new(
- context: &MTLContext,
- decoder_config: &crate::config::DecoderConfig,
+ context: &B::Context,
+ decoder_config: &DecoderConfig,
model_shape: &ModelShape,
) -> Self {
- let global_rope = if decoder_config.global_rope_config.is_some() {
- Some(RopeBuffers::new(context, model_shape))
- } else {
- None
- };
+ let global_rope = decoder_config
+ .global_rope_config
+ .is_some()
+ .then(|| RopeBuffers::new(context, model_shape));
- let local_rope = if decoder_config.local_rope_config.is_some() {
- Some(RopeBuffers::new(context, model_shape))
- } else {
- None
- };
+ let local_rope = decoder_config
+ .local_rope_config
+ .is_some()
+ .then(|| RopeBuffers::new(context, model_shape));
- let moe_expert_weights = if matches!(
+ let moe_expert_weights = matches!(
decoder_config.layer_config.mlp_config,
- crate::config::MLPConfig::MixtureOfExperts(_)
- ) {
- Some(Vec::new())
- } else {
- None
- };
+ MLPConfig::MixtureOfExperts(_)
+ )
+ .then(Vec::new);
- let attention_sinks = if let Some(attention_config) =
- decoder_config.layer_config.attention_config()
- {
- if attention_config.has_sinks {
+ let attention_sinks = decoder_config
+ .layer_config
+ .attention_config()
+ .is_some_and(|c| c.has_sinks)
+ .then(|| {
let num_heads = decoder_config.num_heads;
- Some(
- (0..decoder_config.num_layers)
- .map(|_| {
- RefCell::new(context.create_array_uninitialized(
- &[num_heads],
- DataType::F32,
- "shared_buffers_attention_sinks",
- ))
- })
- .collect(),
- )
- } else {
- None
- }
- } else {
- None
- };
+ (0..decoder_config.num_layers)
+ .map(|_| {
+ RefCell::new(context.create_array_uninitialized(
+ &[num_heads],
+ DataType::F32,
+ "shared_buffers_attention_sinks",
+ ))
+ })
+ .collect()
+ });
Self {
global_rope,
@@ -85,7 +75,7 @@ impl SharedBuffers {
pub fn update_data(
&mut self,
- parameter_tree: &ParameterTree<MTLContext>,
+ parameter_tree: &ParameterTree<B::Context>,
) {
let transformer_tree = parameter_tree
.subtree("transformer")
diff --git a/crates/uzu/src/lib.rs b/crates/uzu/src/lib.rs
index e8d43ecfb..4adb560e6 100644
--- a/crates/uzu/src/lib.rs
+++ b/crates/uzu/src/lib.rs
@@ -4,6 +4,7 @@ pub mod classifier;
pub mod config;
pub mod data_type;
pub mod encodable_block;
+pub mod forward_pass;
pub mod language_model;
pub mod parameters;
pub mod prelude;
diff --git a/crates/uzu/src/tracer/trace_validator.rs b/crates/uzu/src/tracer/trace_validator.rs
index 188cc3b1a..ca5307270 100644
--- a/crates/uzu/src/tracer/trace_validator.rs
+++ b/crates/uzu/src/tracer/trace_validator.rs
@@ -22,12 +22,13 @@ use crate::{
MTLCommandQueue, MTLContext, MetalArray,
forward_pass::{
ArrayId, EncodableBlock, EncodingParameters, ForwardPassState,
- ScratchBuffers, traces::ActivationTrace,
+ traces::ActivationTrace,
},
},
classifier::Classifier,
config::ModelMetadata,
encodable_block::Sampling,
+ forward_pass::scratch_buffers::ScratchBuffers,
language_model::{
LanguageModelGeneratorContext,
sampler::{ArgmaxSampler, LogitsSampler},
@@ -1003,7 +1004,7 @@ impl TraceValidator {
let decoder_config = &context.decoder_config;
context.scratch_buffers = ScratchBuffers::new(
- &context.mtl_context,
+ context.mtl_context.as_ref(),
decoder_config,
&context.model_shape,
resolved_prefix_length,