Skip to content

armgit / uzu

Public Imported from GitHub
0

A high-performance inference engine for AI models

Array labels (#80)

Aleksei Savin87935129a01b
diff --git a/crates/uzu/src/backends/cpu/common.rs b/crates/uzu/src/backends/cpu/common.rs
index c23cf7cc7..b160f8c21 100644
--- a/crates/uzu/src/backends/cpu/common.rs
+++ b/crates/uzu/src/backends/cpu/common.rs
@@ -5,13 +5,20 @@ pub struct CPUArray {
buffer: Box<[u8]>,
shape: Box<[usize]>,
data_type: DataType,
+ label: String,
}
impl Array for CPUArray {
+ type BackendBuffer = Box<[u8]>;
+
fn shape(&self) -> &[usize] {
&self.shape
}
+ fn label(&self) -> String {
+ self.label.clone()
+ }
+
fn data_type(&self) -> DataType {
self.data_type
}
@@ -23,6 +30,10 @@ impl Array for CPUArray {
fn buffer_mut(&mut self) -> &mut [u8] {
&mut self.buffer
}
+
+ fn backend_buffer(&self) -> &Box<[u8]> {
+ &self.buffer
+ }
}
impl CPUArray {
@@ -30,6 +41,7 @@ impl CPUArray {
pub fn new(
shape: &[usize],
data_type: DataType,
+ label: String,
) -> Self {
let buffer_size_bytes = array_size_in_bytes(shape, data_type);
let buffer =
@@ -38,6 +50,7 @@ impl CPUArray {
buffer,
shape: shape.into(),
data_type,
+ label,
}
}
}
@@ -57,7 +70,8 @@ impl DeviceContext for CPUContext {
&self,
shape: &[usize],
data_type: DataType,
+ label: String,
) -> CPUArray {
- CPUArray::new(shape, data_type)
+ CPUArray::new(shape, data_type, label)
}
}
diff --git a/crates/uzu/src/backends/metal/array.rs b/crates/uzu/src/backends/metal/array.rs
index 555a70906..b8252b472 100644
--- a/crates/uzu/src/backends/metal/array.rs
+++ b/crates/uzu/src/backends/metal/array.rs
@@ -14,6 +14,8 @@ pub struct MetalArray {
}
impl Array for MetalArray {
+ type BackendBuffer = MTLBuffer;
+
fn shape(&self) -> &[usize] {
&self.shape
}
@@ -22,6 +24,10 @@ impl Array for MetalArray {
self.data_type
}
+ fn label(&self) -> String {
+ self.buffer.label().to_string()
+ }
+
fn buffer(&self) -> &[u8] {
unsafe {
std::slice::from_raw_parts(
@@ -39,6 +45,10 @@ impl Array for MetalArray {
)
}
}
+
+ fn backend_buffer(&self) -> &MTLBuffer {
+ &self.buffer
+ }
}
impl MetalArray {
diff --git a/crates/uzu/src/backends/metal/classifier_context.rs b/crates/uzu/src/backends/metal/classifier_context.rs
index d3909de1d..3ab7ddcff 100644
--- a/crates/uzu/src/backends/metal/classifier_context.rs
+++ b/crates/uzu/src/backends/metal/classifier_context.rs
@@ -28,7 +28,7 @@ pub struct ClassifierContext {
pub command_buffer: CommandBuffer,
pub shared_buffers: Rc<RefCell<SharedBuffers>>,
- pub scratch_buffers: ScratchBuffers,
+ pub scratch_buffers: ScratchBuffers<Rc<MTLContext>>,
pub model_config: ClassifierModelConfig,
pub model_shape: ModelShape,
diff --git a/crates/uzu/src/backends/metal/context.rs b/crates/uzu/src/backends/metal/context.rs
index d1eb88618..02d4a04f7 100644
--- a/crates/uzu/src/backends/metal/context.rs
+++ b/crates/uzu/src/backends/metal/context.rs
@@ -271,6 +271,7 @@ impl DeviceContext for MTLContext {
&self,
shape: &[usize],
data_type: DataType,
+ label: String,
) -> MetalArray {
unsafe {
let buffer_size_bytes = array_size_in_bytes(shape, data_type);
@@ -279,6 +280,7 @@ impl DeviceContext for MTLContext {
buffer_size_bytes as u64,
metal::MTLResourceOptions::StorageModeShared,
);
+ buffer.set_label(label.as_str());
MetalArray::new(buffer, shape, data_type)
}
}
@@ -291,7 +293,8 @@ impl DeviceContext for Rc<MTLContext> {
&self,
shape: &[usize],
data_type: DataType,
+ label: String,
) -> MetalArray {
- unsafe { (**self).array_uninitialized(shape, data_type) }
+ unsafe { (**self).array_uninitialized(shape, data_type, label) }
}
}
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 ff63d40f0..dcf1ad0d0 100644
--- a/crates/uzu/src/backends/metal/forward_pass/cache_layers.rs
+++ b/crates/uzu/src/backends/metal/forward_pass/cache_layers.rs
@@ -31,6 +31,15 @@ pub enum CacheLayerSlice {
ShortConv,
}
+const ARRAY_TRANSFORMER_KEYS_LABEL: &str = "cache_layers_transformer_keys";
+const ARRAY_TRANSFORMER_VALUES_LABEL: &str = "cache_layers_transformer_values";
+const ARRAY_STATE_SPACE_CONV_STATE_LABEL: &str =
+ "cache_layers_state_space_conv_state";
+const ARRAY_STATE_SPACE_SSM_STATE_LABEL: &str =
+ "cache_layers_state_space_ssm_state";
+const ARRAY_SHORT_CONV_CONV_STATE_LABEL: &str =
+ "cache_layers_short_conv_conv_state";
+
impl CacheLayer {
pub fn as_transformer(&self) -> Option<&KVCacheLayer> {
match self {
@@ -98,95 +107,111 @@ impl CacheLayers {
.kv_cache_layer_shapes(max_prefix_length, max_suffix_length)
.collect();
- let data: Box<[CacheLayer]> =
- model_shape
- .layer_types()
- .iter()
- .enumerate()
- .map(|(layer_idx, layer_type)| match layer_type {
- DecoderLayerType::Transformer => {
- let shape = kv_shapes[layer_idx];
- let window_length = model_shape
- .sliding_window_length_per_layer[layer_idx]
- .filter(|&window_size| {
- window_size < total_context_length
- });
-
- let state = if let Some(w) = window_length {
- KVCacheLayerState::Windowed {
- ring_offset: 0,
- ring_length: 0,
- window_length: w,
- }
- } else {
+ let data: Box<[CacheLayer]> = model_shape
+ .layer_types()
+ .iter()
+ .enumerate()
+ .map(|(layer_index, layer_type)| match layer_type {
+ DecoderLayerType::Transformer => {
+ let shape = kv_shapes[layer_index];
+ let window_length = model_shape
+ .sliding_window_length_per_layer[layer_index]
+ .filter(|&window_size| {
+ window_size < total_context_length
+ });
+
+ let state = if let Some(w) = window_length {
+ KVCacheLayerState::Windowed {
+ ring_offset: 0,
+ ring_length: 0,
+ window_length: w,
+ }
+ } else {
+ KVCacheLayerState::Full {
+ prefix_len: 0,
+ }
+ };
+
+ CacheLayer::Transformer(KVCacheLayer {
+ state: state.clone(),
+ keys: RefCell::new(context.array(
+ &shape,
+ model_shape.kv_cache_data_type(),
+ format!(
+ "{ARRAY_TRANSFORMER_KEYS_LABEL}_{layer_index}"
+ ),
+ )),
+ values: RefCell::new(context.array(
+ &shape,
+ model_shape.kv_cache_data_type(),
+ format!(
+ "{ARRAY_TRANSFORMER_VALUES_LABEL}_{layer_index}"
+ ),
+ )),
+ prefix_token_positions: match &state {
KVCacheLayerState::Full {
- prefix_len: 0,
- }
- };
-
- CacheLayer::Transformer(KVCacheLayer {
- state: state.clone(),
- keys: RefCell::new(context.array(
- &shape,
- model_shape.kv_cache_data_type(),
- )),
- values: RefCell::new(context.array(
- &shape,
- model_shape.kv_cache_data_type(),
- )),
- prefix_token_positions: match &state {
- KVCacheLayerState::Full {
- ..
- } => Vec::with_capacity(max_prefix_length),
- KVCacheLayerState::Windowed {
- window_length,
- ..
- } => (0..*window_length)
- .map(|_| INVALID_POSITION)
- .collect(),
- },
- max_suffix_length,
- })
- },
- DecoderLayerType::StateSpace {
- conv_dim,
- kernel_size,
- state_dim,
- num_heads,
- head_dim,
- ..
- } => {
- let conv_shape =
- [*conv_dim, kernel_size.saturating_sub(1)];
- let ssm_shape = [*num_heads, *head_dim, *state_dim];
- let dtype = model_shape.activation_data_type();
-
- CacheLayer::StateSpace(SSMLayer {
- conv_state: RefCell::new(
- context.array(&conv_shape, dtype),
+ ..
+ } => Vec::with_capacity(max_prefix_length),
+ KVCacheLayerState::Windowed {
+ window_length,
+ ..
+ } => (0..*window_length)
+ .map(|_| INVALID_POSITION)
+ .collect(),
+ },
+ max_suffix_length,
+ })
+ },
+ DecoderLayerType::StateSpace {
+ conv_dim,
+ kernel_size,
+ state_dim,
+ num_heads,
+ head_dim,
+ ..
+ } => {
+ let conv_shape = [*conv_dim, kernel_size.saturating_sub(1)];
+ let ssm_shape = [*num_heads, *head_dim, *state_dim];
+ let dtype = model_shape.activation_data_type();
+
+ CacheLayer::StateSpace(SSMLayer {
+ conv_state: RefCell::new(context.array(
+ &conv_shape,
+ dtype,
+ format!(
+ "{ARRAY_STATE_SPACE_CONV_STATE_LABEL}_{layer_index}"
),
- ssm_state: RefCell::new(
- context.array(&ssm_shape, dtype),
+ )),
+ ssm_state: RefCell::new(context.array(
+ &ssm_shape,
+ dtype,
+ format!(
+ "{ARRAY_STATE_SPACE_SSM_STATE_LABEL}_{layer_index}"
),
- })
- },
- DecoderLayerType::ShortConv {
- kernel_size,
- } => {
- let conv_shape = [
- model_shape.model_dim(),
- kernel_size.saturating_sub(1),
- ];
- let dtype = model_shape.activation_data_type();
-
- CacheLayer::ShortConv(ShortConvLayer {
- conv_state: RefCell::new(
- context.array(&conv_shape, dtype),
+ )),
+ })
+ },
+ DecoderLayerType::ShortConv {
+ kernel_size,
+ } => {
+ let conv_shape = [
+ model_shape.model_dim(),
+ kernel_size.saturating_sub(1),
+ ];
+ let dtype = model_shape.activation_data_type();
+
+ CacheLayer::ShortConv(ShortConvLayer {
+ conv_state: RefCell::new(context.array(
+ &conv_shape,
+ dtype,
+ format!(
+ "{ARRAY_SHORT_CONV_CONV_STATE_LABEL}_{layer_index}"
),
- })
- },
- })
- .collect();
+ )),
+ })
+ },
+ })
+ .collect();
Self {
max_suffix_length,
@@ -363,7 +388,8 @@ impl CacheLayers {
let data: Box<[CacheLayer]> = self
.data
.iter()
- .map(|layer| match layer {
+ .enumerate()
+ .map(|(layer_index, layer)| match layer {
CacheLayer::Transformer(layer) => {
let shape = layer.keys.borrow().shape().to_vec();
let num_groups = shape[0];
@@ -377,8 +403,18 @@ impl CacheLayers {
}
let new_shape = [num_groups, new_total_len, head_dim];
- let mut new_keys = context.array(&new_shape, dtype);
- let mut new_values = context.array(&new_shape, dtype);
+ let mut new_keys = context.array(
+ &new_shape,
+ dtype,
+ format!("{ARRAY_TRANSFORMER_KEYS_LABEL}_{layer_index}"),
+ );
+ let mut new_values = context.array(
+ &new_shape,
+ dtype,
+ format!(
+ "{ARRAY_TRANSFORMER_VALUES_LABEL}_{layer_index}"
+ ),
+ );
if copy_rows > 0 {
{
@@ -404,7 +440,13 @@ impl CacheLayers {
CacheLayer::StateSpace(layer) => {
let conv_shape = layer.conv_state.borrow().shape().to_vec();
let conv_dtype = layer.conv_state.borrow().data_type();
- let mut new_conv = context.array(&conv_shape, conv_dtype);
+ let mut new_conv = context.array(
+ &conv_shape,
+ conv_dtype,
+ format!(
+ "{ARRAY_STATE_SPACE_CONV_STATE_LABEL}_{layer_index}"
+ ),
+ );
{
let conv_src = layer.conv_state.borrow();
new_conv.copy_from_array(&conv_src);
@@ -412,7 +454,13 @@ impl CacheLayers {
let ssm_shape = layer.ssm_state.borrow().shape().to_vec();
let ssm_dtype = layer.ssm_state.borrow().data_type();
- let mut new_ssm = context.array(&ssm_shape, ssm_dtype);
+ let mut new_ssm = context.array(
+ &ssm_shape,
+ ssm_dtype,
+ format!(
+ "{ARRAY_STATE_SPACE_SSM_STATE_LABEL}_{layer_index}"
+ ),
+ );
{
let ssm_src = layer.ssm_state.borrow();
new_ssm.copy_from_array(&ssm_src);
@@ -426,7 +474,13 @@ impl CacheLayers {
CacheLayer::ShortConv(layer) => {
let conv_shape = layer.conv_state.borrow().shape().to_vec();
let conv_dtype = layer.conv_state.borrow().data_type();
- let mut new_conv = context.array(&conv_shape, conv_dtype);
+ let mut new_conv = context.array(
+ &conv_shape,
+ conv_dtype,
+ format!(
+ "{ARRAY_SHORT_CONV_CONV_STATE_LABEL}_{layer_index}"
+ ),
+ );
{
let conv_src = layer.conv_state.borrow();
new_conv.copy_from_array(&conv_src);
diff --git a/crates/uzu/src/backends/metal/forward_pass/kv_cache_layer.rs b/crates/uzu/src/backends/metal/forward_pass/kv_cache_layer.rs
index 4b3b4c641..ace3d39c9 100644
--- a/crates/uzu/src/backends/metal/forward_pass/kv_cache_layer.rs
+++ b/crates/uzu/src/backends/metal/forward_pass/kv_cache_layer.rs
@@ -387,8 +387,16 @@ impl KVCacheLayer {
let dtype = keys.data_type();
let slice_shape = [num_groups, len, head_dim];
- let mut slice_keys = context.array(&slice_shape, dtype);
- let mut slice_values = context.array(&slice_shape, dtype);
+ let mut slice_keys = context.array(
+ &slice_shape,
+ dtype,
+ String::from("kv_cache_layer_slice_keys"),
+ );
+ let mut slice_values = context.array(
+ &slice_shape,
+ dtype,
+ String::from("kv_cache_layer_slice_values"),
+ );
let slots: Vec<usize> = (range.start..range.end)
.enumerate()
diff --git a/crates/uzu/src/backends/metal/forward_pass/scratch_buffers.rs b/crates/uzu/src/backends/metal/forward_pass/scratch_buffers.rs
index 27b132a11..170206407 100644
--- a/crates/uzu/src/backends/metal/forward_pass/scratch_buffers.rs
+++ b/crates/uzu/src/backends/metal/forward_pass/scratch_buffers.rs
@@ -1,90 +1,89 @@
-use std::collections::HashMap;
+use std::{cell::RefCell, collections::HashMap};
-use metal::Buffer as MTLBuffer;
-
-use super::{super::MTLContext, model_shape::ModelShape};
+use super::model_shape::ModelShape;
use crate::{
- DataType,
- array::array_size_in_bytes,
+ DataType, DeviceContext,
config::{DecoderConfig, MLPConfig},
};
-#[derive(Debug)]
-pub struct ScratchBuffers {
+type Array<Context> = RefCell<<Context as DeviceContext>::DeviceArray>;
+
+pub struct ScratchBuffers<Context: DeviceContext> {
// 1-D
- pub token_ids: MTLBuffer,
- pub token_positions: MTLBuffer,
- pub token_bitmask: MTLBuffer,
- pub token_seeds: MTLBuffer,
- pub sampling_output: MTLBuffer,
+ pub token_ids: Array<Context>,
+ pub token_positions: Array<Context>,
+ pub token_bitmask: Array<Context>,
+ pub token_seeds: Array<Context>,
+ pub sampling_output: Array<Context>,
// 2-D
- pub attention_window_size_to_bias: HashMap<Option<usize>, MTLBuffer>,
- pub logits: MTLBuffer,
- pub main: MTLBuffer,
- pub shortcut: MTLBuffer,
- pub qkv: MTLBuffer,
- pub attention_output: MTLBuffer,
- pub mlp_fused_up: MTLBuffer,
- pub mlp_hidden: MTLBuffer,
- pub ssm_inproj: Option<MTLBuffer>,
- pub ssm_packed: Option<MTLBuffer>,
- pub ssm_conv_padded: Option<MTLBuffer>,
- pub short_conv_padded: Option<MTLBuffer>,
- pub ssm_x: Option<MTLBuffer>,
- pub ssm_b: Option<MTLBuffer>,
- pub ssm_c: Option<MTLBuffer>,
- pub ssm_dt: Option<MTLBuffer>,
- pub ssm_z: Option<MTLBuffer>,
+ pub attention_window_size_to_bias: HashMap<Option<usize>, Array<Context>>,
+ pub logits: Array<Context>,
+ pub main: Array<Context>,
+ pub shortcut: Array<Context>,
+ pub qkv: Array<Context>,
+ pub attention_output: Array<Context>,
+ pub mlp_fused_up: Array<Context>,
+ pub mlp_hidden: Array<Context>,
+ pub ssm_inproj: Option<Array<Context>>,
+ pub ssm_packed: Option<Array<Context>>,
+ pub ssm_conv_padded: Option<Array<Context>>,
+ pub short_conv_padded: Option<Array<Context>>,
+ pub ssm_x: Option<Array<Context>>,
+ pub ssm_b: Option<Array<Context>>,
+ pub ssm_c: Option<Array<Context>>,
+ pub ssm_dt: Option<Array<Context>>,
+ pub ssm_z: Option<Array<Context>>,
// 3-D
- pub rotated_queries: MTLBuffer,
- pub rotated_keys: MTLBuffer,
- pub extracted_values: MTLBuffer,
+ pub rotated_queries: Array<Context>,
+ pub rotated_keys: Array<Context>,
+ pub extracted_values: Array<Context>,
// 2-pass attention intermediate buffers
- pub attention_partials: MTLBuffer, // [num_heads * max_suffix_len * total_blocks_count * head_dim]
- pub attention_sums: MTLBuffer, // [num_heads * max_suffix_len * total_blocks_count]
- pub attention_maxs: MTLBuffer, // [num_heads * max_suffix_len * total_blocks_count]
+ pub attention_partials: Array<Context>, // [num_heads * max_suffix_len * total_blocks_count * head_dim]
+ pub attention_sums: Array<Context>, // [num_heads * max_suffix_len * total_blocks_count]
+ pub attention_maxs: Array<Context>, // [num_heads * max_suffix_len * total_blocks_count]
- pub moe_topk_ids: Option<MTLBuffer>,
- pub moe_topk_probs: Option<MTLBuffer>,
- pub moe_offsets: Option<MTLBuffer>,
- pub moe_sumk: Option<MTLBuffer>,
- pub moe_bucketed_token_ids: Option<MTLBuffer>,
- pub moe_bucketed_probs: Option<MTLBuffer>,
- pub moe_x_perm: Option<MTLBuffer>,
- pub moe_tok2row: Option<MTLBuffer>,
- pub moe_y_partial: Option<MTLBuffer>,
- pub moe_hidden: Option<MTLBuffer>,
- pub moe_two_pass_row_expert_map: Option<MTLBuffer>,
- pub moe_tile_counts: Option<MTLBuffer>,
- pub moe_tile_offsets: Option<MTLBuffer>,
- pub moe_tile_map: Option<MTLBuffer>,
- pub moe_total_tiles: Option<MTLBuffer>,
- pub moe_dispatch_args: Option<MTLBuffer>,
- pub moe_scatter_partials: Option<MTLBuffer>,
- pub moe_scatter_block_bases: Option<MTLBuffer>,
- pub moe_block_alloc: Option<MTLBuffer>,
+ pub moe_topk_ids: Option<Array<Context>>,
+ pub moe_topk_probs: Option<Array<Context>>,
+ pub moe_offsets: Option<Array<Context>>,
+ pub moe_sumk: Option<Array<Context>>,
+ pub moe_bucketed_token_ids: Option<Array<Context>>,
+ pub moe_bucketed_probs: Option<Array<Context>>,
+ pub moe_x_perm: Option<Array<Context>>,
+ pub moe_tok2row: Option<Array<Context>>,
+ pub moe_y_partial: Option<Array<Context>>,
+ pub moe_hidden: Option<Array<Context>>,
+ pub moe_two_pass_row_expert_map: Option<Array<Context>>,
+ pub moe_tile_counts: Option<Array<Context>>,
+ pub moe_tile_offsets: Option<Array<Context>>,
+ pub moe_tile_map: Option<Array<Context>>,
+ pub moe_total_tiles: Option<Array<Context>>,
+ pub moe_dispatch_args: Option<Array<Context>>,
+ pub moe_scatter_partials: Option<Array<Context>>,
+ pub moe_scatter_block_bases: Option<Array<Context>>,
+ pub moe_block_alloc: Option<Array<Context>>,
}
-impl ScratchBuffers {
+impl<Context: DeviceContext> ScratchBuffers<Context> {
// TODO: use device arrays instead of MTLBuffers
/// Allocate the buffers with `StorageModeShared` so that they are CPU-accessible as well.
pub fn new(
- context: &MTLContext,
+ context: &Context,
decoder_config: &DecoderConfig,
model_shape: &ModelShape,
max_prefix_len: usize,
max_suffix_len: usize,
) -> Self {
// Helper closure for allocation
- let alloc = |shape: &[usize], dtype: DataType| -> MTLBuffer {
- let bytes = array_size_in_bytes(shape, dtype);
- context.device.new_buffer(
- bytes as u64,
- metal::MTLResourceOptions::StorageModeShared,
- )
+ let alloc = |shape: &[usize],
+ dtype: DataType,
+ label: &str|
+ -> Array<Context> {
+ let array =
+ context.array(shape, dtype, format!("scratch_buffers_{label}"));
+ RefCell::new(array)
};
let act_ty = model_shape.activation_data_type();
@@ -95,14 +94,23 @@ impl ScratchBuffers {
Self {
// 1-D
- token_ids: alloc(&[max_suffix_len], DataType::U64),
- token_positions: alloc(&[max_suffix_len], DataType::I32),
+ token_ids: alloc(&[max_suffix_len], DataType::U64, "token_ids"),
+ token_positions: alloc(
+ &[max_suffix_len],
+ DataType::I32,
+ "token_positions",
+ ),
token_bitmask: alloc(
&model_shape.bitmask_shape(max_suffix_len),
DataType::U32,
+ "token_bitmask",
+ ),
+ token_seeds: alloc(&[max_suffix_len], DataType::U64, "token_seeds"),
+ sampling_output: alloc(
+ &[max_suffix_len],
+ DataType::U32,
+ "sampling_output",
),
- token_seeds: alloc(&[max_suffix_len], DataType::U64),
- sampling_output: alloc(&[max_suffix_len], DataType::U32),
// 2-D
attention_window_size_to_bias: {
@@ -119,79 +127,108 @@ impl ScratchBuffers {
unique_window_sizes
.into_iter()
.map(|window_size| {
- (
- 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>, MTLBuffer>>()
+ .collect::<HashMap<Option<usize>, Array<Context>>>()
},
- logits: alloc(&model_shape.logits_shape(max_suffix_len), act_ty),
- main: alloc(&model_shape.main_shape(max_suffix_len), act_ty),
- shortcut: alloc(&model_shape.main_shape(max_suffix_len), act_ty),
- qkv: alloc(&model_shape.qkv_shape(max_suffix_len), act_ty),
+ logits: alloc(
+ &model_shape.logits_shape(max_suffix_len),
+ act_ty,
+ "logits",
+ ),
+ main: alloc(
+ &model_shape.main_shape(max_suffix_len),
+ act_ty,
+ "main",
+ ),
+ shortcut: alloc(
+ &model_shape.main_shape(max_suffix_len),
+ act_ty,
+ "shortcut",
+ ),
+ qkv: alloc(&model_shape.qkv_shape(max_suffix_len), act_ty, "qkv"),
attention_output: alloc(
&model_shape.attention_output_shape(max_suffix_len),
act_ty,
+ "attention_output",
),
mlp_fused_up: alloc(
&model_shape.mlp_fused_up_shape(max_suffix_len),
act_ty,
+ "mlp_fused_up",
),
mlp_hidden: alloc(
&model_shape.mlp_hidden_shape(max_suffix_len),
act_ty,
+ "mlp_hidden",
),
ssm_inproj: model_shape
.ssm_inproj_shape(max_suffix_len)
- .map(|shape| alloc(&shape, act_ty)),
+ .map(|shape| alloc(&shape, act_ty, "ssm_inproj")),
ssm_packed: model_shape
.ssm_packed_shape(max_suffix_len)
- .map(|shape| alloc(&shape, act_ty)),
+ .map(|shape| alloc(&shape, act_ty, "ssm_packed")),
ssm_conv_padded: model_shape
.ssm_conv_padded_shape(max_suffix_len)
- .map(|shape| alloc(&shape, act_ty)),
+ .map(|shape| alloc(&shape, act_ty, "ssm_conv_padded")),
short_conv_padded: model_shape
.short_conv_padded_shape(max_suffix_len)
- .map(|shape| alloc(&shape, act_ty)),
+ .map(|shape| alloc(&shape, act_ty, "short_conv_padded")),
ssm_x: model_shape
.ssm_x_shape(max_suffix_len)
- .map(|shape| alloc(&shape, act_ty)),
+ .map(|shape| alloc(&shape, act_ty, "ssm_x")),
ssm_b: model_shape
.ssm_bc_shape(max_suffix_len)
- .map(|shape| alloc(&shape, act_ty)),
+ .map(|shape| alloc(&shape, act_ty, "ssm_b")),
ssm_c: model_shape
.ssm_bc_shape(max_suffix_len)
- .map(|shape| alloc(&shape, act_ty)),
+ .map(|shape| alloc(&shape, act_ty, "ssm_c")),
ssm_dt: model_shape
.ssm_dt_shape(max_suffix_len)
- .map(|shape| alloc(&shape, act_ty)),
+ .map(|shape| alloc(&shape, act_ty, "ssm_dt")),
ssm_z: model_shape
.ssm_z_shape(max_suffix_len)
- .map(|shape| alloc(&shape, act_ty)),
+ .map(|shape| alloc(&shape, act_ty, "ssm_z")),
// 3-D
rotated_queries: alloc(
&model_shape.rotated_queries_shape(max_suffix_len),
act_ty,
+ "rotated_queries",
),
rotated_keys: alloc(
&model_shape.rotated_keys_shape(max_suffix_len),
act_ty,
+ "rotated_keys",
),
extracted_values: alloc(
&model_shape.extracted_values_shape(max_suffix_len),
act_ty,
+ "extracted_values",
),
- attention_partials: alloc(&partials_shape, act_ty),
- attention_sums: alloc(&sums_maxs_shape, act_ty),
- attention_maxs: alloc(&sums_maxs_shape, act_ty),
+ attention_partials: alloc(
+ &partials_shape,
+ act_ty,
+ "attention_partials",
+ ),
+ attention_sums: alloc(&sums_maxs_shape, act_ty, "attention_sums"),
+ attention_maxs: alloc(&sums_maxs_shape, act_ty, "attention_maxs"),
moe_topk_ids: match &decoder_config.layer_config.mlp_config {
MLPConfig::MixtureOfExperts(moe) => {
@@ -199,7 +236,7 @@ impl ScratchBuffers {
max_suffix_len,
moe.num_experts_per_token,
);
- Some(alloc(&shape, DataType::U32))
+ Some(alloc(&shape, DataType::U32, "moe_topk_ids"))
},
_ => None,
},
@@ -209,21 +246,21 @@ impl ScratchBuffers {
max_suffix_len,
moe.num_experts_per_token,
);
- Some(alloc(&shape, act_ty))
+ Some(alloc(&shape, act_ty, "moe_topk_probs"))
},
_ => None,
},
moe_offsets: match &decoder_config.layer_config.mlp_config {
MLPConfig::MixtureOfExperts(moe) => {
let shape = model_shape.moe_offsets_shape(moe.mixture_size);
- Some(alloc(&shape, DataType::U32))
+ Some(alloc(&shape, DataType::U32, "moe_offsets"))
},
_ => None,
},
moe_sumk: match &decoder_config.layer_config.mlp_config {
MLPConfig::MixtureOfExperts(_) => {
let shape = model_shape.moe_sumk_shape();
- Some(alloc(&shape, DataType::U32))
+ Some(alloc(&shape, DataType::U32, "moe_sumk"))
},
_ => None,
},
@@ -235,7 +272,7 @@ impl ScratchBuffers {
let max_routed = max_suffix_len * moe.num_experts_per_token;
let shape =
model_shape.moe_bucketed_token_ids_shape(max_routed);
- Some(alloc(&shape, DataType::U32))
+ Some(alloc(&shape, DataType::U32, "moe_bucketed_token_ids"))
},
_ => None,
},
@@ -244,7 +281,7 @@ impl ScratchBuffers {
let max_routed = max_suffix_len * moe.num_experts_per_token;
let shape =
model_shape.moe_bucketed_probs_shape(max_routed);
- Some(alloc(&shape, act_ty))
+ Some(alloc(&shape, act_ty, "moe_bucketed_probs"))
},
_ => None,
},
@@ -252,7 +289,7 @@ impl ScratchBuffers {
MLPConfig::MixtureOfExperts(moe) => {
let max_routed = max_suffix_len * moe.num_experts_per_token;
let shape = model_shape.moe_x_perm_shape(max_routed);
- Some(alloc(&shape, DataType::F16))
+ Some(alloc(&shape, DataType::F16, "moe_x_perm"))
},
_ => None,
},
@@ -262,7 +299,7 @@ impl ScratchBuffers {
max_suffix_len,
moe.num_experts_per_token,
);
- Some(alloc(&shape, DataType::I32))
+ Some(alloc(&shape, DataType::I32, "moe_tok2row"))
},
_ => None,
},
@@ -270,7 +307,7 @@ impl ScratchBuffers {
MLPConfig::MixtureOfExperts(moe) => {
let max_routed = max_suffix_len * moe.num_experts_per_token;
let shape = model_shape.moe_y_partial_shape(max_routed);
- Some(alloc(&shape, DataType::F16))
+ Some(alloc(&shape, DataType::F16, "moe_y_partial"))
},
_ => None,
},
@@ -278,7 +315,7 @@ impl ScratchBuffers {
MLPConfig::MixtureOfExperts(moe) => {
let max_routed = max_suffix_len * moe.num_experts_per_token;
let shape = model_shape.moe_hidden_shape(max_routed);
- Some(alloc(&shape, DataType::F32))
+ Some(alloc(&shape, DataType::F32, "moe_hidden"))
},
_ => None,
},
@@ -288,21 +325,25 @@ impl ScratchBuffers {
{
MLPConfig::MixtureOfExperts(moe) => {
let max_routed = max_suffix_len * moe.num_experts_per_token;
- Some(alloc(&[max_routed], DataType::U32))
+ Some(alloc(
+ &[max_routed],
+ DataType::U32,
+ "moe_two_pass_row_expert_map",
+ ))
},
_ => None,
},
moe_tile_counts: match &decoder_config.layer_config.mlp_config {
MLPConfig::MixtureOfExperts(moe) => {
let shape = model_shape.moe_counts_shape(moe.mixture_size);
- Some(alloc(&shape, DataType::U32))
+ Some(alloc(&shape, DataType::U32, "moe_tile_counts"))
},
_ => None,
},
moe_tile_offsets: match &decoder_config.layer_config.mlp_config {
MLPConfig::MixtureOfExperts(moe) => {
let shape = model_shape.moe_offsets_shape(moe.mixture_size);
- Some(alloc(&shape, DataType::U32))
+ Some(alloc(&shape, DataType::U32, "moe_tile_offsets"))
},
_ => None,
},
@@ -310,21 +351,21 @@ impl ScratchBuffers {
MLPConfig::MixtureOfExperts(moe) => {
let max_routed = max_suffix_len * moe.num_experts_per_token;
let shape = model_shape.moe_tile_map_shape(max_routed);
- Some(alloc(&shape, DataType::U32))
+ Some(alloc(&shape, DataType::U32, "moe_tile_map"))
},
_ => None,
},
moe_total_tiles: match &decoder_config.layer_config.mlp_config {
MLPConfig::MixtureOfExperts(_) => {
let shape = model_shape.moe_total_tiles_shape();
- Some(alloc(&shape, DataType::U32))
+ Some(alloc(&shape, DataType::U32, "moe_total_tiles"))
},
_ => None,
},
moe_dispatch_args: match &decoder_config.layer_config.mlp_config {
MLPConfig::MixtureOfExperts(_) => {
let shape = model_shape.moe_dispatch_args_shape();
- Some(alloc(&shape, DataType::U32))
+ Some(alloc(&shape, DataType::U32, "moe_dispatch_args"))
},
_ => None,
},
@@ -334,10 +375,10 @@ impl ScratchBuffers {
let num_blocks = ((max_suffix_len + 255) / 256).max(1);
let num_tiles = ((moe.mixture_size + 512 - 1) / 512).max(1);
let entries = num_blocks * num_tiles * 512;
- let bytes = (entries * std::mem::size_of::<u32>()) as u64;
- Some(context.device.new_buffer(
- bytes,
- metal::MTLResourceOptions::StorageModeShared,
+ Some(alloc(
+ &[entries],
+ DataType::U32,
+ "moe_scatter_partials",
))
},
_ => None,
@@ -350,10 +391,10 @@ impl ScratchBuffers {
let num_blocks = ((max_suffix_len + 255) / 256).max(1);
let num_tiles = ((moe.mixture_size + 512 - 1) / 512).max(1);
let entries = num_blocks * num_tiles * 512;
- let bytes = (entries * std::mem::size_of::<u32>()) as u64;
- Some(context.device.new_buffer(
- bytes,
- metal::MTLResourceOptions::StorageModeShared,
+ Some(alloc(
+ &[entries],
+ DataType::U32,
+ "moe_scatter_block_bases",
))
},
_ => None,
@@ -363,11 +404,7 @@ impl ScratchBuffers {
let num_blocks = ((max_suffix_len + 255) / 256).max(1);
let num_tiles = ((moe.mixture_size + 512 - 1) / 512).max(1);
let entries = num_blocks * num_tiles * 512;
- let bytes = (entries * std::mem::size_of::<u32>()) as u64;
- Some(context.device.new_buffer(
- bytes,
- metal::MTLResourceOptions::StorageModeShared,
- ))
+ Some(alloc(&[entries], DataType::U32, "moe_block_alloc"))
},
_ => None,
},
diff --git a/crates/uzu/src/backends/metal/forward_pass/state/common_aux_buffers.rs b/crates/uzu/src/backends/metal/forward_pass/state/common_aux_buffers.rs
index ee1412742..936c1e336 100644
--- a/crates/uzu/src/backends/metal/forward_pass/state/common_aux_buffers.rs
+++ b/crates/uzu/src/backends/metal/forward_pass/state/common_aux_buffers.rs
@@ -1,7 +1,10 @@
-use std::cell::RefCell;
+use std::{cell::RefCell, rc::Rc};
use super::super::{ModelShape, ScratchBuffers};
-use crate::backends::metal::MetalArray;
+use crate::{
+ Array,
+ backends::metal::{MTLContext, MetalArray},
+};
type ArrayCell = RefCell<MetalArray>;
@@ -23,7 +26,7 @@ pub struct CommonAuxBuffers {
impl CommonAuxBuffers {
pub fn new(
- scratch: &ScratchBuffers,
+ scratch: &ScratchBuffers<Rc<MTLContext>>,
model_shape: &ModelShape,
suffix_length: usize,
) -> Self {
@@ -32,62 +35,66 @@ impl CommonAuxBuffers {
Self {
suffix_length,
main: RefCell::new(MetalArray::new(
- scratch.main.clone(),
+ scratch.main.borrow().backend_buffer().clone(),
&model_shape.main_shape(suffix_length),
act_dtype,
)),
shortcut: RefCell::new(MetalArray::new(
- scratch.shortcut.clone(),
+ scratch.shortcut.borrow().backend_buffer().clone(),
&model_shape.main_shape(suffix_length),
act_dtype,
)),
qkv: RefCell::new(MetalArray::new(
- scratch.qkv.clone(),
+ scratch.qkv.borrow().backend_buffer().clone(),
&model_shape.qkv_shape(suffix_length),
act_dtype,
)),
attention_output: RefCell::new(MetalArray::new(
- scratch.attention_output.clone(),
+ scratch.attention_output.borrow().backend_buffer().clone(),
&model_shape.attention_output_shape(suffix_length),
act_dtype,
)),
mlp_fused_up: RefCell::new(MetalArray::new(
- scratch.mlp_fused_up.clone(),
+ scratch.mlp_fused_up.borrow().backend_buffer().clone(),
&model_shape.mlp_fused_up_shape(suffix_length),
act_dtype,
)),
mlp_hidden: RefCell::new(MetalArray::new(
- scratch.mlp_hidden.clone(),
+ scratch.mlp_hidden.borrow().backend_buffer().clone(),
&model_shape.mlp_hidden_shape(suffix_length),
act_dtype,
)),
rotated_queries: RefCell::new(MetalArray::new(
- scratch.rotated_queries.clone(),
+ scratch.rotated_queries.borrow().backend_buffer().clone(),
&model_shape.rotated_queries_shape(suffix_length),
act_dtype,
)),
rotated_keys: RefCell::new(MetalArray::new(
- scratch.rotated_keys.clone(),
+ scratch.rotated_keys.borrow().backend_buffer().clone(),
&model_shape.rotated_keys_shape(suffix_length),
act_dtype,
)),
extracted_values: RefCell::new(MetalArray::new(
- scratch.extracted_values.clone(),
+ scratch.extracted_values.borrow().backend_buffer().clone(),
&model_shape.extracted_values_shape(suffix_length),
act_dtype,
)),
attention_partials: RefCell::new(MetalArray::new(
- scratch.attention_partials.clone(),
+ scratch
+ .attention_partials
+ .borrow()
+ .backend_buffer()
+ .clone(),
&model_shape.attention_partials_shape(suffix_length),
act_dtype,
)),
attention_sums: RefCell::new(MetalArray::new(
- scratch.attention_sums.clone(),
+ scratch.attention_sums.borrow().backend_buffer().clone(),
&model_shape.attention_sums_shape(suffix_length),
act_dtype,
)),
attention_maxs: RefCell::new(MetalArray::new(
- scratch.attention_maxs.clone(),
+ scratch.attention_maxs.borrow().backend_buffer().clone(),
&model_shape.attention_maxs_shape(suffix_length),
act_dtype,
)),
diff --git a/crates/uzu/src/backends/metal/forward_pass/state/embeddings_buffers.rs b/crates/uzu/src/backends/metal/forward_pass/state/embeddings_buffers.rs
index 67c01be9f..14c49022b 100644
--- a/crates/uzu/src/backends/metal/forward_pass/state/embeddings_buffers.rs
+++ b/crates/uzu/src/backends/metal/forward_pass/state/embeddings_buffers.rs
@@ -60,6 +60,31 @@ impl EmbeddingsBuffers {
embeddings_config: &EmbeddingConfig,
model_shape: &ModelShape,
) -> Self {
+ let array_label = |config: &EmbeddingConfig, name: &str| -> String {
+ let prefix = "embeddings_buffers";
+ let config_name = match config {
+ EmbeddingConfig::Tied {
+ ..
+ } => "tied",
+ EmbeddingConfig::Untied {
+ ..
+ } => "untied",
+ EmbeddingConfig::QuantizedTied {
+ ..
+ } => "quantized_tied",
+ EmbeddingConfig::MLXQuantizedTied {
+ ..
+ } => "mlx_quantized_tied",
+ EmbeddingConfig::MLXSemiQuantizedUntied {
+ ..
+ } => "mlx_semi_quantized_untied",
+ EmbeddingConfig::MLXQuantizedUntied {
+ ..
+ } => "mlx_quantized_untied",
+ };
+ format!("{prefix}_{config_name}_{name}")
+ };
+
unsafe {
match embeddings_config {
EmbeddingConfig::Tied {
@@ -69,6 +94,7 @@ impl EmbeddingsBuffers {
weights: RefCell::new(context.array_uninitialized(
&model_shape.embeddings_input_shape(),
model_shape.activation_data_type(),
+ array_label(embeddings_config, "weights"),
)),
},
EmbeddingConfig::Untied {
@@ -78,10 +104,12 @@ impl EmbeddingsBuffers {
input_weights: RefCell::new(context.array_uninitialized(
&model_shape.embeddings_input_shape(),
model_shape.activation_data_type(),
+ array_label(embeddings_config, "input_weights"),
)),
output_weights: RefCell::new(context.array_uninitialized(
&model_shape.embeddings_output_shape(),
model_shape.activation_data_type(),
+ array_label(embeddings_config, "output_weights"),
)),
},
EmbeddingConfig::QuantizedTied {
@@ -100,11 +128,13 @@ impl EmbeddingsBuffers {
.packing_divisor(),
],
embedding_quantization_mode.storage_type(),
+ array_label(embeddings_config, "weights"),
),
),
scales: RefCell::new(context.array_uninitialized(
&model_shape.quantized_embeddings_scales_shape(),
model_shape.activation_data_type(),
+ array_label(embeddings_config, "scales"),
)),
}
},
@@ -126,11 +156,13 @@ impl EmbeddingsBuffers {
.packing_divisor(),
],
embedding_quantization_mode.storage_type(),
+ array_label(embeddings_config, "weights"),
),
),
scales: RefCell::new(context.array_uninitialized(
&[vocab_size, num_groups],
model_shape.activation_data_type(),
+ array_label(embeddings_config, "scales"),
)),
}
},
@@ -147,6 +179,7 @@ impl EmbeddingsBuffers {
context.array_uninitialized(
&model_shape.embeddings_input_shape(),
model_shape.activation_data_type(),
+ array_label(embeddings_config, "input_weights"),
),
),
packed_output_weights: RefCell::new(
@@ -158,18 +191,24 @@ impl EmbeddingsBuffers {
.packing_divisor(),
],
embedding_quantization_mode.storage_type(),
+ array_label(
+ embeddings_config,
+ "packed_output_weights",
+ ),
),
),
output_scales: RefCell::new(
context.array_uninitialized(
&[vocab_size, num_groups],
model_shape.activation_data_type(),
+ array_label(embeddings_config, "output_scales"),
),
),
output_biases: RefCell::new(
context.array_uninitialized(
&[vocab_size, num_groups],
model_shape.activation_data_type(),
+ array_label(embeddings_config, "output_biases"),
),
),
}
@@ -188,36 +227,48 @@ impl EmbeddingsBuffers {
context.array_uninitialized(
&[vocab_size, model_dim / pack],
embedding_quantization_mode.storage_type(),
+ array_label(
+ embeddings_config,
+ "packed_input_weights",
+ ),
),
),
input_scales: RefCell::new(
context.array_uninitialized(
&[vocab_size, num_groups],
model_shape.activation_data_type(),
+ array_label(embeddings_config, "input_scales"),
),
),
input_biases: RefCell::new(
context.array_uninitialized(
&[vocab_size, num_groups],
model_shape.activation_data_type(),
+ array_label(embeddings_config, "input_biases"),
),
),
packed_output_weights: RefCell::new(
context.array_uninitialized(
&[vocab_size, model_dim / pack],
embedding_quantization_mode.storage_type(),
+ array_label(
+ embeddings_config,
+ "packed_output_weights",
+ ),
),
),
output_scales: RefCell::new(
context.array_uninitialized(
&[vocab_size, num_groups],
model_shape.activation_data_type(),
+ array_label(embeddings_config, "output_scales"),
),
),
output_biases: RefCell::new(
context.array_uninitialized(
&[vocab_size, num_groups],
model_shape.activation_data_type(),
+ array_label(embeddings_config, "output_biases"),
),
),
}
diff --git a/crates/uzu/src/backends/metal/forward_pass/state/language_model_generator_aux_buffers.rs b/crates/uzu/src/backends/metal/forward_pass/state/language_model_generator_aux_buffers.rs
index cce6e48cb..dd1ca4a7d 100644
--- a/crates/uzu/src/backends/metal/forward_pass/state/language_model_generator_aux_buffers.rs
+++ b/crates/uzu/src/backends/metal/forward_pass/state/language_model_generator_aux_buffers.rs
@@ -1,8 +1,10 @@
-use std::cell::RefCell;
+use std::{cell::RefCell, rc::Rc};
use super::super::{ModelShape, ScratchBuffers};
use crate::{
- DataType, DecoderConfig, backends::metal::MetalArray, config::MLPConfig,
+ Array, DataType, DecoderConfig,
+ backends::metal::{MTLContext, MetalArray},
+ config::MLPConfig,
};
type ArrayCell = RefCell<MetalArray>;
@@ -41,7 +43,7 @@ pub struct LanguageModelGeneratorAuxBuffers {
impl LanguageModelGeneratorAuxBuffers {
pub fn new(
- scratch: &ScratchBuffers,
+ scratch: &ScratchBuffers<Rc<MTLContext>>,
decoder_config: &DecoderConfig,
model_shape: &ModelShape,
suffix_length: usize,
@@ -54,88 +56,124 @@ impl LanguageModelGeneratorAuxBuffers {
scratch.ssm_inproj.as_ref(),
model_shape.ssm_inproj_shape(suffix_length),
) {
- (Some(buf), Some(shape)) => Some(RefCell::new(
- MetalArray::new(buf.clone(), &shape, act_dtype),
- )),
+ (Some(buf), Some(shape)) => {
+ Some(RefCell::new(MetalArray::new(
+ buf.borrow().backend_buffer().clone(),
+ &shape,
+ act_dtype,
+ )))
+ },
_ => None,
},
ssm_packed: match (
scratch.ssm_packed.as_ref(),
model_shape.ssm_packed_shape(suffix_length),
) {
- (Some(buf), Some(shape)) => Some(RefCell::new(
- MetalArray::new(buf.clone(), &shape, act_dtype),
- )),
+ (Some(buf), Some(shape)) => {
+ Some(RefCell::new(MetalArray::new(
+ buf.borrow().backend_buffer().clone(),
+ &shape,
+ act_dtype,
+ )))
+ },
_ => None,
},
ssm_conv_padded: match (
scratch.ssm_conv_padded.as_ref(),
model_shape.ssm_conv_padded_shape(suffix_length),
) {
- (Some(buf), Some(shape)) => Some(RefCell::new(
- MetalArray::new(buf.clone(), &shape, act_dtype),
- )),
+ (Some(buf), Some(shape)) => {
+ Some(RefCell::new(MetalArray::new(
+ buf.borrow().backend_buffer().clone(),
+ &shape,
+ act_dtype,
+ )))
+ },
_ => None,
},
short_conv_padded: match (
scratch.short_conv_padded.as_ref(),
model_shape.short_conv_padded_shape(suffix_length),
) {
- (Some(buf), Some(shape)) => Some(RefCell::new(
- MetalArray::new(buf.clone(), &shape, act_dtype),
- )),
+ (Some(buf), Some(shape)) => {
+ Some(RefCell::new(MetalArray::new(
+ buf.borrow().backend_buffer().clone(),
+ &shape,
+ act_dtype,
+ )))
+ },
_ => None,
},
ssm_x: match (
scratch.ssm_x.as_ref(),
model_shape.ssm_x_shape(suffix_length),
) {
- (Some(buf), Some(shape)) => Some(RefCell::new(
- MetalArray::new(buf.clone(), &shape, act_dtype),
- )),
+ (Some(buf), Some(shape)) => {
+ Some(RefCell::new(MetalArray::new(
+ buf.borrow().backend_buffer().clone(),
+ &shape,
+ act_dtype,
+ )))
+ },
_ => None,
},
ssm_b: match (
scratch.ssm_b.as_ref(),
model_shape.ssm_bc_shape(suffix_length),
) {
- (Some(buf), Some(shape)) => Some(RefCell::new(
- MetalArray::new(buf.clone(), &shape, act_dtype),
- )),
+ (Some(buf), Some(shape)) => {
+ Some(RefCell::new(MetalArray::new(
+ buf.borrow().backend_buffer().clone(),
+ &shape,
+ act_dtype,
+ )))
+ },
_ => None,
},
ssm_c: match (
scratch.ssm_c.as_ref(),
model_shape.ssm_bc_shape(suffix_length),
) {
- (Some(buf), Some(shape)) => Some(RefCell::new(
- MetalArray::new(buf.clone(), &shape, act_dtype),
- )),
+ (Some(buf), Some(shape)) => {
+ Some(RefCell::new(MetalArray::new(
+ buf.borrow().backend_buffer().clone(),
+ &shape,
+ act_dtype,
+ )))
+ },
_ => None,
},
ssm_dt: match (
scratch.ssm_dt.as_ref(),
model_shape.ssm_dt_shape(suffix_length),
) {
- (Some(buf), Some(shape)) => Some(RefCell::new(
- MetalArray::new(buf.clone(), &shape, act_dtype),
- )),
+ (Some(buf), Some(shape)) => {
+ Some(RefCell::new(MetalArray::new(
+ buf.borrow().backend_buffer().clone(),
+ &shape,
+ act_dtype,
+ )))
+ },
_ => None,
},
ssm_z: match (
scratch.ssm_z.as_ref(),
model_shape.ssm_z_shape(suffix_length),
) {
- (Some(buf), Some(shape)) => Some(RefCell::new(
- MetalArray::new(buf.clone(), &shape, act_dtype),
- )),
+ (Some(buf), Some(shape)) => {
+ Some(RefCell::new(MetalArray::new(
+ buf.borrow().backend_buffer().clone(),
+ &shape,
+ act_dtype,
+ )))
+ },
_ => None,
},
moe_topk_ids: match &decoder_config.layer_config.mlp_config {
MLPConfig::MixtureOfExperts(moe) => {
scratch.moe_topk_ids.as_ref().map(|buf| {
RefCell::new(MetalArray::new(
- buf.clone(),
+ buf.borrow().backend_buffer().clone(),
&model_shape.moe_topk_ids_shape(
suffix_length,
moe.num_experts_per_token,
@@ -150,7 +188,7 @@ impl LanguageModelGeneratorAuxBuffers {
MLPConfig::MixtureOfExperts(moe) => {
scratch.moe_topk_probs.as_ref().map(|buf| {
RefCell::new(MetalArray::new(
- buf.clone(),
+ buf.borrow().backend_buffer().clone(),
&model_shape.moe_topk_probs_shape(
suffix_length,
moe.num_experts_per_token,
@@ -165,7 +203,7 @@ impl LanguageModelGeneratorAuxBuffers {
MLPConfig::MixtureOfExperts(moe) => {
scratch.moe_offsets.as_ref().map(|buf| {
RefCell::new(MetalArray::new(
- buf.clone(),
+ buf.borrow().backend_buffer().clone(),
&model_shape
.moe_offsets_shape(moe.mixture_size),
DataType::U32,
@@ -178,7 +216,7 @@ impl LanguageModelGeneratorAuxBuffers {
MLPConfig::MixtureOfExperts(_) => {
scratch.moe_sumk.as_ref().map(|buf| {
RefCell::new(MetalArray::new(
- buf.clone(),
+ buf.borrow().backend_buffer().clone(),
&model_shape.moe_sumk_shape(),
DataType::U32,
))
@@ -195,7 +233,7 @@ impl LanguageModelGeneratorAuxBuffers {
suffix_length * moe.num_experts_per_token;
scratch.moe_bucketed_token_ids.as_ref().map(|buf| {
RefCell::new(MetalArray::new(
- buf.clone(),
+ buf.borrow().backend_buffer().clone(),
&model_shape
.moe_bucketed_token_ids_shape(max_routed),
DataType::U32,
@@ -213,7 +251,7 @@ impl LanguageModelGeneratorAuxBuffers {
suffix_length * moe.num_experts_per_token;
scratch.moe_bucketed_probs.as_ref().map(|buf| {
RefCell::new(MetalArray::new(
- buf.clone(),
+ buf.borrow().backend_buffer().clone(),
&model_shape
.moe_bucketed_probs_shape(max_routed),
act_dtype,
@@ -228,7 +266,7 @@ impl LanguageModelGeneratorAuxBuffers {
suffix_length * moe.num_experts_per_token;
scratch.moe_x_perm.as_ref().map(|buf| {
RefCell::new(MetalArray::new(
- buf.clone(),
+ buf.borrow().backend_buffer().clone(),
&model_shape.moe_x_perm_shape(max_routed),
DataType::F16,
))
@@ -240,7 +278,7 @@ impl LanguageModelGeneratorAuxBuffers {
MLPConfig::MixtureOfExperts(moe) => {
scratch.moe_tok2row.as_ref().map(|buf| {
RefCell::new(MetalArray::new(
- buf.clone(),
+ buf.borrow().backend_buffer().clone(),
&model_shape.moe_tok2row_shape(
suffix_length,
moe.num_experts_per_token,
@@ -257,7 +295,7 @@ impl LanguageModelGeneratorAuxBuffers {
suffix_length * moe.num_experts_per_token;
scratch.moe_y_partial.as_ref().map(|buf| {
RefCell::new(MetalArray::new(
- buf.clone(),
+ buf.borrow().backend_buffer().clone(),
&model_shape.moe_y_partial_shape(max_routed),
DataType::F16,
))
@@ -271,7 +309,7 @@ impl LanguageModelGeneratorAuxBuffers {
suffix_length * moe.num_experts_per_token;
scratch.moe_hidden.as_ref().map(|buf| {
RefCell::new(MetalArray::new(
- buf.clone(),
+ buf.borrow().backend_buffer().clone(),
&model_shape.moe_hidden_shape(max_routed),
DataType::F32,
))
@@ -289,7 +327,7 @@ impl LanguageModelGeneratorAuxBuffers {
scratch.moe_two_pass_row_expert_map.as_ref().map(
|buf| {
RefCell::new(MetalArray::new(
- buf.clone(),
+ buf.borrow().backend_buffer().clone(),
&[max_routed],
DataType::U32,
))
@@ -302,7 +340,7 @@ impl LanguageModelGeneratorAuxBuffers {
MLPConfig::MixtureOfExperts(moe) => {
scratch.moe_tile_counts.as_ref().map(|buf| {
RefCell::new(MetalArray::new(
- buf.clone(),
+ buf.borrow().backend_buffer().clone(),
&model_shape.moe_counts_shape(moe.mixture_size),
DataType::U32,
))
@@ -315,7 +353,7 @@ impl LanguageModelGeneratorAuxBuffers {
MLPConfig::MixtureOfExperts(moe) => {
scratch.moe_tile_offsets.as_ref().map(|buf| {
RefCell::new(MetalArray::new(
- buf.clone(),
+ buf.borrow().backend_buffer().clone(),
&model_shape
.moe_offsets_shape(moe.mixture_size),
DataType::U32,
@@ -330,7 +368,7 @@ impl LanguageModelGeneratorAuxBuffers {
suffix_length * moe.num_experts_per_token;
scratch.moe_tile_map.as_ref().map(|buf| {
RefCell::new(MetalArray::new(
- buf.clone(),
+ buf.borrow().backend_buffer().clone(),
&model_shape.moe_tile_map_shape(max_routed),
DataType::U32,
))
@@ -342,7 +380,7 @@ impl LanguageModelGeneratorAuxBuffers {
MLPConfig::MixtureOfExperts(_) => {
scratch.moe_total_tiles.as_ref().map(|buf| {
RefCell::new(MetalArray::new(
- buf.clone(),
+ buf.borrow().backend_buffer().clone(),
&model_shape.moe_total_tiles_shape(),
DataType::U32,
))
@@ -355,7 +393,7 @@ impl LanguageModelGeneratorAuxBuffers {
MLPConfig::MixtureOfExperts(_) => {
scratch.moe_dispatch_args.as_ref().map(|buf| {
RefCell::new(MetalArray::new(
- buf.clone(),
+ buf.borrow().backend_buffer().clone(),
&model_shape.moe_dispatch_args_shape(),
DataType::U32,
))
@@ -375,7 +413,7 @@ impl LanguageModelGeneratorAuxBuffers {
((moe.mixture_size + 512 - 1) / 512).max(1);
let entries = num_blocks * num_tiles * 512;
RefCell::new(MetalArray::new(
- buf.clone(),
+ buf.borrow().backend_buffer().clone(),
&[entries],
DataType::U32,
))
@@ -395,7 +433,7 @@ impl LanguageModelGeneratorAuxBuffers {
((moe.mixture_size + 512 - 1) / 512).max(1);
let entries = num_blocks * num_tiles * 512;
RefCell::new(MetalArray::new(
- buf.clone(),
+ buf.borrow().backend_buffer().clone(),
&[entries],
DataType::U32,
))
@@ -412,7 +450,7 @@ impl LanguageModelGeneratorAuxBuffers {
((moe.mixture_size + 512 - 1) / 512).max(1);
let entries = num_blocks * num_tiles;
RefCell::new(MetalArray::new(
- buf.clone(),
+ buf.borrow().backend_buffer().clone(),
&[entries],
DataType::U32,
))
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 7888e5452..eb484bfd0 100644
--- a/crates/uzu/src/backends/metal/forward_pass/state/mod.rs
+++ b/crates/uzu/src/backends/metal/forward_pass/state/mod.rs
@@ -52,13 +52,13 @@ impl ForwardPassState {
fn init_token_ids(
context: &MTLContext,
- scratch: &ScratchBuffers,
+ scratch: &ScratchBuffers<Rc<MTLContext>>,
token_ids: &[u64],
) -> ArrayCell {
let suffix_length = token_ids.len();
let mut token_ids_array = unsafe {
MetalArray::new(
- scratch.token_ids.clone(),
+ scratch.token_ids.borrow().backend_buffer().clone(),
&[suffix_length],
DataType::U64,
)
@@ -69,13 +69,13 @@ impl ForwardPassState {
fn init_token_positions(
context: &MTLContext,
- scratch: &ScratchBuffers,
+ scratch: &ScratchBuffers<Rc<MTLContext>>,
token_positions: &[usize],
) -> ArrayCell {
let suffix_length = token_positions.len();
let mut token_positions_array = unsafe {
MetalArray::new(
- scratch.token_positions.clone(),
+ scratch.token_positions.borrow().backend_buffer().clone(),
&[suffix_length],
DataType::I32,
)
@@ -98,7 +98,7 @@ impl ForwardPassState {
context: Rc<MTLContext>,
decoder_config: &DecoderConfig,
model_shape: &ModelShape,
- scratch: &ScratchBuffers,
+ scratch: &ScratchBuffers<Rc<MTLContext>>,
cache_layers: Rc<RefCell<CacheLayers>>,
shared_buffers: Rc<RefCell<SharedBuffers>>,
token_ids: &[u64],
@@ -130,7 +130,7 @@ impl ForwardPassState {
let token_ids_cell = if skip_token_ids_copy {
RefCell::new(unsafe {
MetalArray::new(
- scratch.token_ids.clone(),
+ scratch.token_ids.borrow().backend_buffer().clone(),
&[suffix_length],
DataType::U64,
)
@@ -160,7 +160,7 @@ impl ForwardPassState {
let bitmask_shape = model_shape.bitmask_shape(suffix_length);
let mut bitmask_array = unsafe {
MetalArray::new(
- scratch.token_bitmask.clone(),
+ scratch.token_bitmask.borrow().backend_buffer().clone(),
&bitmask_shape,
DataType::U32,
)
@@ -186,7 +186,7 @@ impl ForwardPassState {
} else {
let mut token_seeds_array = unsafe {
MetalArray::new(
- scratch.token_seeds.clone(),
+ scratch.token_seeds.borrow().backend_buffer().clone(),
&[suffix_length],
DataType::U64,
)
@@ -198,7 +198,7 @@ impl ForwardPassState {
// Logits
let logits_cell = RefCell::new(unsafe {
MetalArray::new(
- scratch.logits.clone(),
+ scratch.logits.borrow().backend_buffer().clone(),
&model_shape.logits_shape(suffix_length),
model_shape.activation_data_type(),
)
@@ -207,7 +207,7 @@ impl ForwardPassState {
// Sampling output
let sampling_output = Some(RefCell::new(unsafe {
MetalArray::new(
- scratch.sampling_output.clone(),
+ scratch.sampling_output.borrow().backend_buffer().clone(),
&[suffix_length],
DataType::U32,
)
@@ -277,7 +277,7 @@ impl ForwardPassState {
fn init_llm_attention_bias(
context: &MTLContext,
- scratch: &ScratchBuffers,
+ scratch: &ScratchBuffers<Rc<MTLContext>>,
cache_layers: &Rc<RefCell<CacheLayers>>,
suffix_length: usize,
act_dtype: DataType,
@@ -297,7 +297,7 @@ impl ForwardPassState {
[suffix_length, suffix_length + prefix_length];
let array = unsafe {
MetalArray::new(
- buffer.clone(),
+ buffer.borrow().backend_buffer().clone(),
&attention_bias_shape,
act_dtype,
)
@@ -334,7 +334,7 @@ impl ForwardPassState {
pub fn new_classifier(
context: Rc<MTLContext>,
model_shape: &ModelShape,
- scratch: &ScratchBuffers,
+ scratch: &ScratchBuffers<Rc<MTLContext>>,
shared_buffers: Rc<RefCell<SharedBuffers>>,
token_ids: &[u64],
token_positions: &[usize],
@@ -389,7 +389,7 @@ impl ForwardPassState {
fn init_classifier_attention_bias(
context: &MTLContext,
- scratch: &ScratchBuffers,
+ scratch: &ScratchBuffers<Rc<MTLContext>>,
suffix_length: usize,
act_dtype: DataType,
bidirectional_attention: bool,
@@ -402,7 +402,7 @@ impl ForwardPassState {
let attention_bias_shape = [suffix_length, suffix_length];
let array = unsafe {
MetalArray::new(
- buffer.clone(),
+ buffer.borrow().backend_buffer().clone(),
&attention_bias_shape,
act_dtype,
)
diff --git a/crates/uzu/src/backends/metal/forward_pass/state/rope_buffers.rs b/crates/uzu/src/backends/metal/forward_pass/state/rope_buffers.rs
index 469089911..88af4784e 100644
--- a/crates/uzu/src/backends/metal/forward_pass/state/rope_buffers.rs
+++ b/crates/uzu/src/backends/metal/forward_pass/state/rope_buffers.rs
@@ -30,10 +30,12 @@ impl RopeBuffers {
cosines: RefCell::new(context.array_uninitialized(
&[rope_max_sequence_length, head_dim],
model_shape.activation_data_type(),
+ String::from("rope_buffers_cosines"),
)),
sines: RefCell::new(context.array_uninitialized(
&[rope_max_sequence_length, head_dim],
model_shape.activation_data_type(),
+ String::from("rope_buffers_sines"),
)),
}
}
diff --git a/crates/uzu/src/backends/metal/forward_pass/state/shared_buffers.rs b/crates/uzu/src/backends/metal/forward_pass/state/shared_buffers.rs
index 6c9cfa81d..c3d974aa7 100644
--- a/crates/uzu/src/backends/metal/forward_pass/state/shared_buffers.rs
+++ b/crates/uzu/src/backends/metal/forward_pass/state/shared_buffers.rs
@@ -69,6 +69,7 @@ impl SharedBuffers {
RefCell::new(context.array_uninitialized(
&[num_heads],
DataType::F32,
+ String::from("shared_buffers_attention_sinks"),
))
})
.collect(),
diff --git a/crates/uzu/src/backends/metal/forward_pass/traces.rs b/crates/uzu/src/backends/metal/forward_pass/traces.rs
index 9035cf2d7..123c504a0 100644
--- a/crates/uzu/src/backends/metal/forward_pass/traces.rs
+++ b/crates/uzu/src/backends/metal/forward_pass/traces.rs
@@ -30,38 +30,47 @@ impl LayerActivationTrace {
inputs: RefCell::new(context.array_uninitialized(
&model_shape.main_shape(suffix_length),
model_shape.activation_data_type(),
+ String::from("layer_activation_trace_inputs"),
)),
pre_attention_norm: RefCell::new(context.array_uninitialized(
&model_shape.main_shape(suffix_length),
model_shape.activation_data_type(),
+ String::from("layer_activation_trace_pre_attention_norm"),
)),
attention: RefCell::new(context.array_uninitialized(
&model_shape.main_shape(suffix_length),
model_shape.activation_data_type(),
+ String::from("layer_activation_trace_attention"),
)),
post_attention_norm: RefCell::new(context.array_uninitialized(
&model_shape.main_shape(suffix_length),
model_shape.activation_data_type(),
+ String::from("layer_activation_trace_post_attention_norm"),
)),
mlp_inputs: RefCell::new(context.array_uninitialized(
&model_shape.main_shape(suffix_length),
model_shape.activation_data_type(),
+ String::from("layer_activation_trace_mlp_inputs"),
)),
pre_mlp_norm: RefCell::new(context.array_uninitialized(
&model_shape.main_shape(suffix_length),
model_shape.activation_data_type(),
+ String::from("layer_activation_trace_pre_mlp_norm"),
)),
mlp: RefCell::new(context.array_uninitialized(
&model_shape.main_shape(suffix_length),
model_shape.activation_data_type(),
+ String::from("layer_activation_trace_mlp"),
)),
post_mlp_norm: RefCell::new(context.array_uninitialized(
&model_shape.main_shape(suffix_length),
model_shape.activation_data_type(),
+ String::from("layer_activation_trace_post_mlp_norm"),
)),
outputs: RefCell::new(context.array_uninitialized(
&model_shape.main_shape(suffix_length),
model_shape.activation_data_type(),
+ String::from("layer_activation_trace_outputs"),
)),
}
}
@@ -98,11 +107,13 @@ impl ActivationTrace {
output_norm: RefCell::new(context.array_uninitialized(
&model_shape.main_shape(suffix_length),
model_shape.activation_data_type(),
+ String::from("activation_trace_output_norm"),
)),
output_pooling: None,
logits: RefCell::new(context.array_uninitialized(
&model_shape.logits_shape(suffix_length),
model_shape.activation_data_type(),
+ String::from("activation_trace_logits"),
)),
}
}
@@ -130,22 +141,26 @@ impl ActivationTrace {
context.array_uninitialized(
&model_shape.main_shape(suffix_length),
model_shape.activation_data_type(),
+ String::from("activation_trace_embedding_norm"),
),
)),
layer_results,
output_norm: RefCell::new(context.array_uninitialized(
&model_shape.main_shape(suffix_length),
model_shape.activation_data_type(),
+ String::from("activation_trace_output_norm"),
)),
output_pooling: Some(RefCell::new(
context.array_uninitialized(
&[1, model_dim],
model_shape.activation_data_type(),
+ String::from("activation_trace_output_pooling"),
),
)),
logits: RefCell::new(context.array_uninitialized(
&[1, num_labels],
model_shape.activation_data_type(),
+ String::from("activation_trace_logits"),
)),
}
}
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 74d5feee3..421b1851a 100644
--- a/crates/uzu/src/backends/metal/language_model_generator_context.rs
+++ b/crates/uzu/src/backends/metal/language_model_generator_context.rs
@@ -133,7 +133,7 @@ pub struct LanguageModelGeneratorContext {
pub cache_layers: Rc<RefCell<CacheLayers>>,
pub shared_buffers: Rc<RefCell<SharedBuffers>>,
- pub scratch_buffers: ScratchBuffers,
+ pub scratch_buffers: ScratchBuffers<Rc<MTLContext>>,
pub model_config: LanguageModelConfig,
pub decoder_config: Rc<DecoderConfig>,
diff --git a/crates/uzu/src/device/array.rs b/crates/uzu/src/device/array.rs
index 851f3f337..48b45a053 100644
--- a/crates/uzu/src/device/array.rs
+++ b/crates/uzu/src/device/array.rs
@@ -35,6 +35,8 @@ pub fn array_size_in_bytes(
// Backend-agnostic n-dimensional array type.
pub trait Array {
+ type BackendBuffer;
+
fn shape(&self) -> &[usize];
fn num_elements(&self) -> usize {
@@ -43,12 +45,16 @@ pub trait Array {
fn data_type(&self) -> DataType;
+ fn label(&self) -> String;
+
/// Returns a reference to the device buffer containing the array's data.
fn buffer(&self) -> &[u8];
/// Returns a mutable reference to the device buffer containing the array's data.
fn buffer_mut(&mut self) -> &mut [u8];
+ fn backend_buffer(&self) -> &Self::BackendBuffer;
+
/// Returns the size of the array in memory.
fn size_in_bytes(&self) -> usize {
array_size_in_bytes(self.shape(), self.data_type())
diff --git a/crates/uzu/src/device/device_context.rs b/crates/uzu/src/device/device_context.rs
index 2b39e3273..983c993dd 100644
--- a/crates/uzu/src/device/device_context.rs
+++ b/crates/uzu/src/device/device_context.rs
@@ -27,6 +27,7 @@ pub trait DeviceContext {
&self,
shape: &[usize],
data_type: DataType,
+ label: String,
) -> Self::DeviceArray;
/// Allocate a new array with the given shape and data type.
@@ -35,9 +36,10 @@ pub trait DeviceContext {
&self,
shape: &[usize],
data_type: DataType,
+ label: String,
) -> Self::DeviceArray {
unsafe {
- let mut result = self.array_uninitialized(shape, data_type);
+ let mut result = self.array_uninitialized(shape, data_type, label);
fill_zeroes(result.buffer_mut());
result
}
@@ -47,10 +49,11 @@ pub trait DeviceContext {
fn array_from_view<T: ArrayElement, D: Dimension>(
&self,
view: ArrayView<T, D>,
+ label: String,
) -> Self::DeviceArray {
unsafe {
let mut result =
- self.array_uninitialized(view.shape(), T::data_type());
+ self.array_uninitialized(view.shape(), T::data_type(), label);
let result_buffer = result.as_slice_mut().unwrap();
// If the view data is contiguous, copy it directly, otherwise .
@@ -73,10 +76,12 @@ pub trait DeviceContext {
>(
&self,
shape: &[usize; D],
+ label: String,
mut f: F,
) -> Self::DeviceArray {
unsafe {
- let mut result = self.array_uninitialized(shape, T::data_type());
+ let mut result =
+ self.array_uninitialized(shape, T::data_type(), label);
for (slice_index, value) in
result.as_slice_mut().unwrap().iter_mut().enumerate()
{
@@ -91,9 +96,11 @@ pub trait DeviceContext {
&self,
shape: &[usize],
elem: T,
+ label: String,
) -> Self::DeviceArray {
unsafe {
- let mut result = self.array_uninitialized(shape, T::data_type());
+ let mut result =
+ self.array_uninitialized(shape, T::data_type(), label);
result.as_slice_mut().unwrap().fill(elem);
result
}
@@ -103,8 +110,9 @@ pub trait DeviceContext {
fn scalar<T: ArrayElement>(
&self,
value: T,
+ label: String,
) -> Self::DeviceArray {
- self.array_from_elem(&[], value)
+ self.array_from_elem(&[], value, label)
}
/// Allocate a new array for an attention bias (also sometimes referred to as "attention mask").
@@ -120,35 +128,44 @@ pub trait DeviceContext {
F: FnMut(usize, usize) -> bool,
{
let shape = [suffix_length, suffix_length + prefix_length];
+ let label = String::from("attention_bias");
match data_type {
- DataType::F16 => self.array_from_shape_fn(&shape, |[row, col]| {
- if should_be_neg_inf(*row, *col) {
- f16::NEG_INFINITY
- } else {
- f16::zero()
- }
- }),
- DataType::BF16 => self.array_from_shape_fn(&shape, |[row, col]| {
- if should_be_neg_inf(*row, *col) {
- bf16::NEG_INFINITY
- } else {
- bf16::zero()
- }
- }),
- DataType::F32 => self.array_from_shape_fn(&shape, |[row, col]| {
- if should_be_neg_inf(*row, *col) {
- f32::NEG_INFINITY
- } else {
- f32::zero()
- }
- }),
- DataType::F64 => self.array_from_shape_fn(&shape, |[row, col]| {
- if should_be_neg_inf(*row, *col) {
- f64::NEG_INFINITY
- } else {
- f64::zero()
- }
- }),
+ DataType::F16 => {
+ self.array_from_shape_fn(&shape, label, |[row, col]| {
+ if should_be_neg_inf(*row, *col) {
+ f16::NEG_INFINITY
+ } else {
+ f16::zero()
+ }
+ })
+ },
+ DataType::BF16 => {
+ self.array_from_shape_fn(&shape, label, |[row, col]| {
+ if should_be_neg_inf(*row, *col) {
+ bf16::NEG_INFINITY
+ } else {
+ bf16::zero()
+ }
+ })
+ },
+ DataType::F32 => {
+ self.array_from_shape_fn(&shape, label, |[row, col]| {
+ if should_be_neg_inf(*row, *col) {
+ f32::NEG_INFINITY
+ } else {
+ f32::zero()
+ }
+ })
+ },
+ DataType::F64 => {
+ self.array_from_shape_fn(&shape, label, |[row, col]| {
+ if should_be_neg_inf(*row, *col) {
+ f64::NEG_INFINITY
+ } else {
+ f64::zero()
+ }
+ })
+ },
_ => {
panic!(
"Attention bias can only be of a floating-point type, but requested {:?}",
diff --git a/crates/uzu/src/language_model/language_model_generator.rs b/crates/uzu/src/language_model/language_model_generator.rs
index 19529515f..1a7b00a44 100644
--- a/crates/uzu/src/language_model/language_model_generator.rs
+++ b/crates/uzu/src/language_model/language_model_generator.rs
@@ -432,8 +432,13 @@ impl LanguageModelGenerator {
&self.context.scratch_buffers.attention_window_size_to_bias
{
unsafe {
- let ptr = mask_buffer.contents() as *mut u8;
- std::ptr::write_bytes(ptr, 0, mask_buffer.length() as usize);
+ let ptr =
+ mask_buffer.borrow().backend_buffer().contents() as *mut u8;
+ std::ptr::write_bytes(
+ ptr,
+ 0,
+ mask_buffer.borrow().backend_buffer().length() as usize,
+ );
}
}
@@ -568,7 +573,13 @@ impl LanguageModelGenerator {
.expect("sampling_output must exist after sampling encode");
let sampling_output_buffer =
unsafe { sampling_output.borrow_mut().mtl_buffer().clone() };
- let token_ids_buffer = self.context.scratch_buffers.token_ids.clone();
+ let token_ids_buffer = self
+ .context
+ .scratch_buffers
+ .token_ids
+ .borrow()
+ .backend_buffer()
+ .clone();
let encoder = root_command_buffer.new_compute_command_encoder();
self.context.token_copy.encode_to_token_ids(
@@ -616,7 +627,7 @@ impl LanguageModelGenerator {
if update.unmask_col >= 0 || update.mask_col >= 0 {
mask_update.encode(
encoder,
- mask_buffer,
+ mask_buffer.borrow().backend_buffer(),
update.unmask_col,
update.mask_col,
);
diff --git a/crates/uzu/src/parameters/loader.rs b/crates/uzu/src/parameters/loader.rs
index c7eb51dff..428c570c9 100644
--- a/crates/uzu/src/parameters/loader.rs
+++ b/crates/uzu/src/parameters/loader.rs
@@ -100,8 +100,13 @@ where
.get(key)
.ok_or(ParameterLoaderError::KeyNotFound(key.to_string()))?;
let (offset, size) = (metadata_entry.offset, metadata_entry.size);
- let mut array =
- self.context.array(&metadata_entry.shape, metadata_entry.data_type);
+ let array_key = key.replace(".", "_");
+ let array_label = format!("parameter_loader_{array_key}");
+ let mut array = self.context.array(
+ &metadata_entry.shape,
+ metadata_entry.data_type,
+ array_label,
+ );
let expected_size = array.size_in_bytes();
if expected_size != size {
return Err(ParameterLoaderError::SizeMismatch {