A high-performance inference engine for AI models
Big refactor (metal4 gone out of control) (#796)
uuuvn2f0737834475
diff --git a/Cargo.lock b/Cargo.lockindex 5e02f9c35..c1779491e 100644--- a/Cargo.lock+++ b/Cargo.lock@@ -3689,9 +3689,9 @@ dependencies = [[[package]]name = "mtl-rs"-version = "0.2.0"+version = "0.2.2"source = "registry+https://github.com/rust-lang/crates.io-index"-checksum = "bf8b377d6cc3233c580332bf4aba1c3c1b93d72dadf5af30bc1b7414c39fccb8"+checksum = "d9f1de2bca596db925db758d497cbf9cb394a2981933319b3777510097e1d360"dependencies = ["bitflags 2.13.0","block2",diff --git a/Cargo.toml b/Cargo.tomlindex 9eb0be1b9..d9fe0467e 100644--- a/Cargo.toml+++ b/Cargo.toml@@ -76,7 +76,7 @@ objc2-foundation = "0.3.2"objc2-core-foundation = "0.3.2"objc2-io-kit = { version = "0.3.2", default-features = false, features = ["libc", "ps"] }obfstr = "0.4.4"-metal = { package = "mtl-rs", version = "0.2.0" }+metal = { package = "mtl-rs", version = "0.2.2" }block2 = "0.6"bytemuck = "1.23"bytesize = "2"diff --git a/crates/uzu-engine/Cargo.toml b/crates/uzu-engine/Cargo.tomlindex 3d4b20c7d..4c0133843 100644--- a/crates/uzu-engine/Cargo.toml+++ b/crates/uzu-engine/Cargo.toml@@ -20,10 +20,12 @@ cpu = [] # TODO: move libm heremetal = ["dep:rayon","dep:clang-ast",+ "dep:depfile","dep:tempfile","dep:serde_json","dep:objc2","dep:obfstr",+ "dep:blake3","dep:xxhash-rust","dep:metal",]@@ -33,10 +35,8 @@ grammar = ["dep:xgrammar", "dep:schemars"][build-dependencies]anyhow.workspace = truewalkdir.workspace = true-depfile.workspace = truederive_more.workspace = trueserde.workspace = true-blake3.workspace = truequote.workspace = trueproc-macro2.workspace = truesyn.workspace = true@@ -47,8 +47,10 @@ rhai.workspace = true[target.'cfg(any(target_os = "macos", target_os = "ios", target_os = "tvos", target_os = "visionos"))'.build-dependencies]rayon = { workspace = true, optional = true }clang-ast = { workspace = true, optional = true }+depfile = { workspace = true, optional = true }tempfile = { workspace = true, optional = true }serde_json = { workspace = true, features = ["unbounded_depth"], optional = true }+blake3 = { workspace = true, optional = true }xxhash-rust = { workspace = true, features = ["xxh3"], optional = true }[dependencies]diff --git a/crates/uzu-engine/build/common/enum_paths.rs b/crates/uzu-engine/build/common/enum_paths.rsindex 4dc54a9f2..e641b6c06 100644--- a/crates/uzu-engine/build/common/enum_paths.rs+++ b/crates/uzu-engine/build/common/enum_paths.rs@@ -14,7 +14,6 @@ pub enum GpuTypeKind {#[derive(Clone)]struct GpuTypeEntry {path: GpuTypePath,- #[allow(dead_code)]kind: GpuTypeKind,}diff --git a/crates/uzu-engine/build/common/traitgen.rs b/crates/uzu-engine/build/common/traitgen.rsindex 69af15127..06d3e3a53 100644--- a/crates/uzu-engine/build/common/traitgen.rs+++ b/crates/uzu-engine/build/common/traitgen.rs@@ -2,9 +2,9 @@ use std::{collections::HashMap, env, path::PathBuf};use anyhow::{Context, bail};use itertools::Itertools;-use proc_macro2::{Span, TokenStream};+use proc_macro2::TokenStream;use quote::{format_ident, quote};-use syn::{Lifetime, Type};+use syn::Type;use crate::common::{codegen::write_tokens,@@ -29,30 +29,24 @@ pub fn traitgen(kernel: &Kernel) -> (TokenStream, TokenStream) {quote! { #name: #ty }});- let (encode_lifetime_generics, mut args) = kernel+ let mut args = kernel.arguments.iter().map(|a| {let name = format_ident!("{}", a.name.as_ref());- let (lifetime_generic, mut ty) = match &a.ty {- KernelArgumentType::Buffer(access) => {- let buffer_lifetime = Lifetime::new(&format!("'{}", a.name.as_ref()), Span::call_site());- (- Some(quote! { #buffer_lifetime }),- match access {- KernelBufferAccess::Read => {- quote! { impl crate::backends::common::BufferArg<#buffer_lifetime, Self::Backend> }- },- KernelBufferAccess::ReadWrite => {- quote! { impl crate::backends::common::BufferArgMut<#buffer_lifetime, Self::Backend> }- },- },- )+ let mut ty = match &a.ty {+ KernelArgumentType::Buffer(access) => match access {+ KernelBufferAccess::Read => {+ quote! { impl crate::backends::common::BufferRef<Backend = Self::Backend> }+ },+ KernelBufferAccess::ReadWrite => {+ quote! { impl crate::backends::common::BufferMut<Backend = Self::Backend> }+ },},KernelArgumentType::Constant(ty) => {let ty: Type = syn::parse_str(ty.as_ref()).unwrap();- (None, quote! { #ty })+ quote! { #ty }},};@@ -60,13 +54,11 @@ pub fn traitgen(kernel: &Kernel) -> (TokenStream, TokenStream) {ty = quote! { Option<#ty> };}- (lifetime_generic, quote! { #name: #ty })+ quote! { #name: #ty }})- .collect::<(Vec<_>, Vec<_>)>();+ .collect::<Vec<_>>();- let mut encode_generics = encode_lifetime_generics.into_iter().flatten().collect::<Vec<_>>();- encode_generics.push(quote! { 'encoder });- args.push(quote! { encoder: &'encoder mut crate::backends::common::Encoder<Self::Backend> });+ args.push(quote! { command_buffer: &mut <<Self::Backend as crate::backends::common::Backend>::CommandBuffer as crate::backends::common::CommandBuffer>::Encoding });let kernel_trait = quote! {#[allow(clippy::style, clippy::complexity, clippy::perf)]@@ -76,7 +68,7 @@ pub fn traitgen(kernel: &Kernel) -> (TokenStream, TokenStream) {#[allow(non_snake_case)]fn new(context: &<Self::Backend as crate::backends::common::Backend>::Context #(, #params)*) -> Result<Self, <Self::Backend as crate::backends::common::Backend>::Error>;- fn encode<#(#encode_generics),*>(&self, #(#args),*);+ fn encode(&self, #(#args),*);}};diff --git a/crates/uzu-engine/build/cpu/compiler.rs b/crates/uzu-engine/build/cpu/compiler.rsindex 76717d283..0ee5dde47 100644--- a/crates/uzu-engine/build/cpu/compiler.rs+++ b/crates/uzu-engine/build/cpu/compiler.rs@@ -2,11 +2,11 @@ use std::{collections::HashMap, env, fs, path::PathBuf};use anyhow::{Context, bail};use itertools::Itertools;-use proc_macro2::{Span, TokenStream};+use proc_macro2::TokenStream;use quote::{ToTokens, format_ident, quote};use syn::{- Expr, FnArg, GenericArgument, GenericParam, Ident, Item, ItemFn, Lifetime, PathArguments, Type,- punctuated::Punctuated, token::Comma,+ Expr, FnArg, GenericArgument, GenericParam, Ident, Item, ItemFn, PathArguments, Type, punctuated::Punctuated,+ token::Comma,};use walkdir::WalkDir;@@ -362,29 +362,23 @@ impl CpuCompiler {}).collect::<anyhow::Result<_>>()?;- let (encode_lifetimes, mut encode_args_defs): (Vec<_>, Vec<_>) = kernel_arguments+ let mut encode_args_defs: Vec<_> = kernel_arguments.iter().map(|argument| {let argument_ident: Ident = syn::parse_str(argument.name.as_ref()).context("cannot parse ident")?;- let (lifetime, mut ty) = match &argument.ty {- KernelArgumentType::Buffer(access) => {- let buffer_lifetime = Lifetime::new(&format!("'{}", argument.name.as_ref()), Span::call_site());- (- Some(quote! { #buffer_lifetime }),- match access {- KernelBufferAccess::Read => {- quote! { impl crate::backends::common::BufferArg<#buffer_lifetime, crate::backends::cpu::Cpu> }- },- KernelBufferAccess::ReadWrite => {- quote! { impl crate::backends::common::BufferArgMut<#buffer_lifetime, crate::backends::cpu::Cpu> }- },- },- )+ let mut ty = match &argument.ty {+ KernelArgumentType::Buffer(access) => match access {+ KernelBufferAccess::Read => {+ quote! { impl crate::backends::common::BufferRef<Backend = crate::backends::cpu::Cpu> }+ },+ KernelBufferAccess::ReadWrite => {+ quote! { impl crate::backends::common::BufferMut<Backend = crate::backends::cpu::Cpu> }+ },},KernelArgumentType::Constant(ty) => {let ty: Type = syn::parse_str(ty.as_ref()).context("cannot parse type")?;- (None, quote! { #ty })+ quote! { #ty }},};@@ -392,10 +386,9 @@ impl CpuCompiler {ty = quote! { Option<#ty> };}- Ok((lifetime, quote! { #argument_ident: #ty }))+ Ok(quote! { #argument_ident: #ty })}).collect::<anyhow::Result<_>>()?;- let mut encode_lifetimes = encode_lifetimes.into_iter().flatten().collect::<Vec<_>>();let argument_copies = function_arguments.iter()@@ -405,11 +398,11 @@ impl CpuCompiler {FunctionArgumentType::Buffer(access) => {let (buffer_ptr, buffer_ptr_wrapper) = match access {KernelBufferAccess::Read => (- quote! { (&*__dsl_buffer.downcast().get()).as_ptr() },+ quote! { crate::backends::cpu::buffer::CpuBufferExt::cpu_address(__dsl_buffer).as_ptr().cast::<u8>().cast_const() },quote! { crate::utils::pointers::SendPtr },),KernelBufferAccess::ReadWrite => (- quote! { (&mut *__dsl_buffer.downcast().get()).as_mut_ptr() },+ quote! { crate::backends::cpu::buffer::CpuBufferExt::cpu_address(__dsl_buffer).as_ptr().cast::<u8>() },quote! { crate::utils::pointers::SendPtrMut },),};@@ -417,17 +410,17 @@ impl CpuCompiler {if argument.conditional.is_some() {Some(quote! {let #argument_ident = #argument_ident.map(|__dsl_buffer_impl| unsafe {- let (__dsl_buffer, __dsl_offset, _) = __dsl_buffer_impl.into_parts();+ let (__dsl_buffer, __dsl_range) = __dsl_buffer_impl.parts();- #buffer_ptr_wrapper(#buffer_ptr.byte_add(__dsl_offset))+ #buffer_ptr_wrapper(#buffer_ptr.byte_add(__dsl_range.start))});})} else {Some(quote! {let #argument_ident = unsafe {- let (__dsl_buffer, __dsl_offset, _) = #argument_ident.into_parts();+ let (__dsl_buffer, __dsl_range) = #argument_ident.parts();- #buffer_ptr_wrapper(#buffer_ptr.byte_add(__dsl_offset))+ #buffer_ptr_wrapper(#buffer_ptr.byte_add(__dsl_range.start))};})}@@ -480,7 +473,7 @@ impl CpuCompiler {});quote! {- encoder.as_command_buffer_mut().push_command(move || #monomorphized_function(#function_call_args_joined));+ command_buffer.push_command(move || #monomorphized_function(#function_call_args_joined));}};@@ -578,9 +571,8 @@ impl CpuCompiler {make_encode(quote! {})};- encode_lifetimes.push(quote! { 'encoder });encode_args_defs- .push(quote! { encoder: &'encoder mut crate::backends::common::Encoder<crate::backends::cpu::Cpu> });+ .push(quote! { command_buffer: &mut <<crate::backends::cpu::Cpu as crate::backends::common::Backend>::CommandBuffer as crate::backends::common::CommandBuffer>::Encoding });let tokens = quote! {#[allow(non_snake_case)]@@ -598,7 +590,7 @@ impl CpuCompiler {})}- fn encode<#(#encode_lifetimes),*>(&self, #(#encode_args_defs),*) {+ fn encode(&self, #(#encode_args_defs),*) {#(#argument_copies)*#encode_body}diff --git a/crates/uzu-engine/build/metal/bindgen/arguments.rs b/crates/uzu-engine/build/metal/bindgen/arguments.rsindex 13e2d891f..052470d82 100644--- a/crates/uzu-engine/build/metal/bindgen/arguments.rs+++ b/crates/uzu-engine/build/metal/bindgen/arguments.rs@@ -1,19 +1,19 @@-use anyhow::{Context, Result};-use proc_macro2::{Span, TokenStream};+use anyhow::{Context, Result, ensure};+use proc_macro2::TokenStream;use quote::{format_ident, quote};-use syn::{Expr, Ident, Lifetime, Type};+use syn::{Expr, Ident, Type};-use super::{- super::{+use crate::{+ common::enum_paths::EnumPaths,+ metal::{ast::{MetalArgument, MetalArgumentType, MetalBufferAccess, MetalConstantType, MetalGroupsType, MetalKernelInfo,shared_element_byte_size,},+ bindgen::host_expression_rewriter::HostExpressionRewriter,enum_path_rewrite::rewrite_for_rust,},- host_expression_rewriter::HostExpressionRewriter,};-use crate::common::enum_paths::EnumPaths;pub enum ArgumentEmission {Buffer(BufferArgument),@@ -26,7 +26,6 @@ pub struct BufferArgument {name: Ident,buffer_index: usize,access: MetalBufferAccess,- lifetime: Lifetime,condition: Option<ArgumentCondition>,}@@ -101,6 +100,8 @@ pub fn parse(}}+ ensure!(next_buffer_index <= 31, "requires {next_buffer_index} buffer slots; maximum is 31");+Ok(emissions)}@@ -138,13 +139,11 @@ fn parse_buffer_argument(enum_paths: &EnumPaths,) -> Result<BufferArgument> {let name = format_ident!("{}", argument.name.as_ref());- let lifetime = Lifetime::new(&format!("'{}", argument.name.as_ref()), Span::call_site());let condition = parse_argument_condition(argument, enum_paths)?;Ok(BufferArgument {name,buffer_index,access,- lifetime,condition,})}@@ -219,38 +218,69 @@ impl ArgumentEmission {ArgumentEmission::Constant(constant) => Some(emit_constant_argument_definition(constant)),ArgumentEmission::Shared(_) => None,ArgumentEmission::IndirectDispatch(_) => Some(quote! {- __dsl_indirect_dispatch_buffer: impl crate::backends::common::BufferArg<- '__dsl_indirect_dispatch_buffer, crate::backends::metal::Metal- >+ __dsl_indirect_dispatch_buffer: impl crate::backends::common::BufferRef<Backend = crate::backends::metal::Metal>}),}}- pub fn encode_lifetime(&self) -> Option<TokenStream> {- match self {- ArgumentEmission::Buffer(buffer) => {- let lifetime = &buffer.lifetime;- Some(quote! { #lifetime })- },- ArgumentEmission::IndirectDispatch(_) => Some(quote! { '__dsl_indirect_dispatch_buffer }),- ArgumentEmission::Constant(_) | ArgumentEmission::Shared(_) => None,- }- }-pub fn encode_deconstruct(&self) -> Option<TokenStream> {match self {ArgumentEmission::Buffer(buffer) => {let name = &buffer.name;Some(if buffer.condition.is_some() {- quote! { let #name = #name.map(|#name| #name.into_parts()); }+ quote! { let #name = #name.map(|#name| #name.parts()); }} else {- quote! { let #name = #name.into_parts(); }+ quote! { let #name = #name.parts(); }})},ArgumentEmission::IndirectDispatch(_) => Some(quote! {- let __dsl_indirect_dispatch_buffer = __dsl_indirect_dispatch_buffer.into_parts();+ let __dsl_indirect_dispatch_buffer = __dsl_indirect_dispatch_buffer.parts();}),- ArgumentEmission::Constant(_) | ArgumentEmission::Shared(_) => None,+ ArgumentEmission::Constant(constant) => {+ let constant_name = &constant.name;+ let buffer_name = format_ident!("__dsl_argument_buffer_{}", constant_name);+ let parts_name = format_ident!("__dsl_argument_buffer_parts_{}", constant_name);+ let (buffer_size, buffer_copy) = match &constant.shape {+ ConstantShape::Scalar(ty) => (+ quote! { std::mem::size_of::<#ty>() },+ quote! { #buffer_name.copyin(unsafe { std::slice::from_raw_parts((&raw const #constant_name) as *const u8, std::mem::size_of::<#ty>()) }); },+ ),+ ConstantShape::UnsizedSlice(ty) => (+ quote! { std::mem::size_of_val::<[#ty]>(#constant_name).max(std::mem::size_of::<#ty>()) },+ quote! {+ if !#constant_name.is_empty() {+ #buffer_name.copyin(unsafe { std::slice::from_raw_parts(#constant_name.as_ptr() as *const u8, std::mem::size_of_val::<[#ty]>(#constant_name)) });+ }+ },+ ),+ ConstantShape::SizedArray {+ element_type,+ size,+ } => (+ quote! { std::mem::size_of::<[#element_type; #size]>() },+ quote! { #buffer_name.copyin(unsafe { std::slice::from_raw_parts(#constant_name.as_ptr() as *const u8, std::mem::size_of::<[#element_type; #size]>()) }); },+ ),+ };+ Some(if constant.condition.is_none() {+ quote! {+ let mut #buffer_name = command_buffer.allocate_constant(#buffer_size).unwrap();+ #buffer_copy+ let #parts_name = #buffer_name.parts();+ }+ } else {+ quote! {+ let mut #buffer_name;+ let #parts_name = if let Some(#constant_name) = #constant_name {+ #buffer_name = command_buffer.allocate_constant(#buffer_size).unwrap();+ #buffer_copy+ Some(#buffer_name.parts())+ } else {+ None+ };+ }+ })+ },+ ArgumentEmission::Shared(_) => None,}}@@ -258,23 +288,24 @@ impl ArgumentEmission {match self {ArgumentEmission::Buffer(buffer) => Some(emit_buffer_access(buffer)),ArgumentEmission::IndirectDispatch(_) => Some(quote! {- Some(crate::backends::common::Access {+ Some(crate::backends::metal::command_buffer::Access {range: __dsl_indirect_dispatch_buffer.0.gpu_address_subrange(- (__dsl_indirect_dispatch_buffer.1)..(__dsl_indirect_dispatch_buffer.1 + 12),+ ((__dsl_indirect_dispatch_buffer.1.start)..(__dsl_indirect_dispatch_buffer.1.start + 12)).into(),),- flags: crate::backends::common::AccessFlags::compute_read(),+ write: false,})}),- ArgumentEmission::Constant(_) | ArgumentEmission::Shared(_) => None,+ ArgumentEmission::Constant(constant) => Some(emit_constant_access(constant)),+ ArgumentEmission::Shared(_) => None,}}- pub fn encode_set(&self) -> TokenStream {+ pub fn encode_set(&self) -> Option<TokenStream> {match self {- ArgumentEmission::Buffer(buffer) => emit_buffer_set(buffer),- ArgumentEmission::Constant(constant) => emit_constant_set(constant),- ArgumentEmission::Shared(shared) => emit_shared_set(shared),- ArgumentEmission::IndirectDispatch(_) => quote! {},+ ArgumentEmission::Buffer(buffer) => Some(emit_buffer_set(buffer)),+ ArgumentEmission::Constant(constant) => Some(emit_constant_set(constant)),+ ArgumentEmission::Shared(shared) => Some(emit_shared_set(shared)),+ ArgumentEmission::IndirectDispatch(_) => None,}}@@ -290,12 +321,14 @@ impl ArgumentEmission {fn emit_buffer_argument_definition(buffer: &BufferArgument) -> TokenStream {let name = &buffer.name;- let lifetime = &buffer.lifetime;- let trait_path = match buffer.access {- MetalBufferAccess::Read => quote! { crate::backends::common::BufferArg },- MetalBufferAccess::ReadWrite => quote! { crate::backends::common::BufferArgMut },+ let buffer_argument_type = match buffer.access {+ MetalBufferAccess::Read => quote! {+ impl crate::backends::common::BufferRef<Backend = crate::backends::metal::Metal>+ },+ MetalBufferAccess::ReadWrite => quote! {+ impl crate::backends::common::BufferMut<Backend = crate::backends::metal::Metal>+ },};- let buffer_argument_type = quote! { impl #trait_path<#lifetime, crate::backends::metal::Metal> };if buffer.condition.is_some() {quote! { #name: Option<#buffer_argument_type> }} else {@@ -322,16 +355,11 @@ fn emit_constant_argument_definition(constant: &ConstantArgument) -> TokenStreamfn emit_buffer_access(buffer: &BufferArgument) -> TokenStream {let name = &buffer.name;- let compute_write = matches!(buffer.access, MetalBufferAccess::ReadWrite);+ let write = matches!(buffer.access, MetalBufferAccess::ReadWrite);let access_expression = quote! {- crate::backends::common::Access {- range: #name.0.gpu_address_subrange((#name.1)..(#name.1 + #name.2)),- flags: crate::backends::common::AccessFlags {- compute_read: true,- compute_write: #compute_write,- copy_read: false,- copy_write: false,- },+ crate::backends::metal::command_buffer::Access {+ range: #name.0.gpu_address_subrange(#name.1),+ write: #write,}};if buffer.condition.is_some() {@@ -341,11 +369,26 @@ fn emit_buffer_access(buffer: &BufferArgument) -> TokenStream {}}+fn emit_constant_access(constant: &ConstantArgument) -> TokenStream {+ let parts_name = format_ident!("__dsl_argument_buffer_parts_{}", constant.name);+ let access_expression = quote! {+ crate::backends::metal::command_buffer::Access {+ range: #parts_name.0.gpu_address_subrange(#parts_name.1),+ write: false,+ }+ };+ if constant.condition.is_some() {+ quote! { #parts_name.as_ref().map(|#parts_name| #access_expression) }+ } else {+ quote! { Some(#access_expression) }+ }+}+fn emit_buffer_set(buffer: &BufferArgument) -> TokenStream {let name = &buffer.name;let buffer_index = buffer.buffer_index;let unconditional_set = quote! {- compute_encoder.set_buffer(Some(#name.0.downcast()), #name.1, #buffer_index);+ command_buffer.argument_table.set_address_at_index(#name.0.gpu_address() + #name.1.start as u64, #buffer_index);};match &buffer.condition {Some(condition) => {@@ -362,23 +405,17 @@ fn emit_buffer_set(buffer: &BufferArgument) -> TokenStream {}fn emit_constant_set(constant: &ConstantArgument) -> TokenStream {- let name = &constant.name;+ let parts_name = format_ident!("__dsl_argument_buffer_parts_{}", constant.name);let buffer_index = constant.buffer_index;- let unconditional_set = match &constant.shape {- ConstantShape::Scalar(_) => quote! { compute_encoder.set_value(&#name, #buffer_index); },- ConstantShape::UnsizedSlice(_)- | ConstantShape::SizedArray {- ..- } => {- quote! { compute_encoder.set_slice(#name, #buffer_index); }- },+ let unconditional_set = quote! {+ command_buffer.argument_table.set_address_at_index(#parts_name.0.gpu_address() + #parts_name.1.start as u64, #buffer_index);};match &constant.condition {Some(condition) => {let field_name = &condition.field_name;quote! {- assert!(#name.is_some() == self.#field_name);- if let Some(#name) = #name {+ assert!(#parts_name.is_some() == self.#field_name);+ if let Some(#parts_name) = #parts_name {#unconditional_set}}@@ -393,7 +430,7 @@ fn emit_shared_set(shared: &SharedArgument) -> TokenStream {let length_expression = &shared.length_expression;quote! {if self.#field_name {- compute_encoder.set_threadgroup_memory_length(#length_expression, #threadgroup_index);+ command_buffer.compute_encoder.set_threadgroup_memory_length_at_index(#length_expression, #threadgroup_index);}}}@@ -405,7 +442,7 @@ pub fn encode_accesses_call(arguments: &[ArgumentEmission]) -> TokenStream {quote! {}} else {quote! {- encoder.access(&[#(#access_expressions),*].into_iter().flatten().collect::<Vec<_>>());+ command_buffer.access(&[#(#access_expressions),*].into_iter().flatten().collect::<Vec<_>>());}}}diff --git a/crates/uzu-engine/build/metal/bindgen/dispatch.rs b/crates/uzu-engine/build/metal/bindgen/dispatch.rsindex 2f99bf4ea..9bc434a66 100644--- a/crates/uzu-engine/build/metal/bindgen/dispatch.rs+++ b/crates/uzu-engine/build/metal/bindgen/dispatch.rs@@ -65,7 +65,7 @@ fn build_axis_dispatch(let (threads, threads_per_group): (Vec<TokenStream>, Vec<TokenStream>) = axis_pairs.into_iter().unzip();let dispatch_code = quote! {- compute_encoder.dispatch_threads(+ command_buffer.compute_encoder.dispatch_threads_threads_per_threadgroup(MTLSize::new(#((#threads) as usize, )*),MTLSize::new(#((#threads_per_group) as usize, )*),);@@ -84,9 +84,8 @@ fn build_indirect_dispatch(threads.extend(repeat_n(quote! { 1 }, 3 - threads.len()));let dispatch_code = quote! {- compute_encoder.dispatch_threadgroups_indirect(- __dsl_indirect_dispatch_buffer.0.downcast(),- __dsl_indirect_dispatch_buffer.1,+ command_buffer.compute_encoder.dispatch_threadgroups_with_indirect_buffer_threads_per_threadgroup(+ __dsl_indirect_dispatch_buffer.0.gpu_address() + __dsl_indirect_dispatch_buffer.1.start as u64,MTLSize::new(#((#threads) as usize, )*),);};@@ -114,7 +113,7 @@ fn build_direct_dispatch(groups.extend(repeat_n(quote! { 1 }, 3 - groups.len()));let dispatch_code = quote! {- compute_encoder.dispatch_threadgroups(+ command_buffer.compute_encoder.dispatch_threadgroups_threads_per_threadgroup(MTLSize::new(#((#groups) as usize, )*),MTLSize::new(#((#threads) as usize, )*),);diff --git a/crates/uzu-engine/build/metal/bindgen/mod.rs b/crates/uzu-engine/build/metal/bindgen/mod.rsindex 1633fbd0e..fd6d8120b 100644--- a/crates/uzu-engine/build/metal/bindgen/mod.rs+++ b/crates/uzu-engine/build/metal/bindgen/mod.rs@@ -9,9 +9,12 @@ use anyhow::Result;use proc_macro2::TokenStream;use quote::{format_ident, quote};-use self::host_expression_rewriter::HostExpressionRewriter;-use super::{ast::MetalKernelInfo, wrapper::SpecializeBaseIndices};-use crate::common::{enum_paths::EnumPaths, kernel::Kernel, mangling::dynamic_mangle};+use crate::{+ common::{enum_paths::EnumPaths, kernel::Kernel, mangling::dynamic_mangle},+ metal::{+ ast::MetalKernelInfo, bindgen::host_expression_rewriter::HostExpressionRewriter, wrapper::SpecializeBaseIndices,+ },+};pub fn bindgen(kernel: &MetalKernelInfo,@@ -42,11 +45,10 @@ pub fn bindgen(argument_emissions.iter().filter_map(|argument| argument.struct_initializer()).collect();let mut encode_argument_definitions: Vec<TokenStream> =argument_emissions.iter().filter_map(|argument| argument.encode_argument_definition()).collect();- let mut encode_lifetimes: Vec<TokenStream> =- argument_emissions.iter().filter_map(|argument| argument.encode_lifetime()).collect();let encode_deconstructs: Vec<TokenStream> =argument_emissions.iter().filter_map(|argument| argument.encode_deconstruct()).collect();- let encode_set_calls: Vec<TokenStream> = argument_emissions.iter().map(|argument| argument.encode_set()).collect();+ let encode_set_calls: Vec<TokenStream> =+ argument_emissions.iter().filter_map(|argument| argument.encode_set()).collect();let encode_accesses_call = arguments::encode_accesses_call(&argument_emissions);let variant_struct_fields: Vec<TokenStream> =@@ -81,9 +83,8 @@ pub fn bindgen(let associate_backend = &trait_wiring.associate_backend;let method_visibility = &trait_wiring.method_visibility;- encode_lifetimes.push(quote! { 'encoder });encode_argument_definitions.push(quote! {- encoder: &'encoder mut crate::backends::common::Encoder<crate::backends::metal::Metal>+ command_buffer: &mut <<crate::backends::metal::Metal as crate::backends::common::Backend>::CommandBuffer as crate::backends::common::CommandBuffer>::Encoding});let kernel_tokens = quote! {@@ -114,19 +115,18 @@ pub fn bindgen(})}- #method_visibility fn encode<#(#encode_lifetimes),*>(+ #method_visibility fn encode(&self,#(#encode_argument_definitions),*) {#empty_dispatch_guards- encoder.push_debug_group(#kernel_name);+ command_buffer.push_debug_group(#kernel_name);#(#encode_deconstructs)*#encode_accesses_call- let compute_encoder = encoder.as_command_buffer_mut().ensure_compute();- compute_encoder.set_compute_pipeline_state(&self.pipeline);+ command_buffer.compute_encoder.set_compute_pipeline_state(&self.pipeline);#(#encode_set_calls)*#dispatch_code- encoder.pop_debug_group();+ command_buffer.pop_debug_group();}}};@@ -153,15 +153,18 @@ pub fn bindgen_global(kernels: &[(impl AsRef<std::path::Path>, &[Kernel])]) -> R});let tokens = quote! {- use metal::{MTLComputeCommandEncoder, MTLComputePipelineState, MTLFunctionConstantValues, MTLSize};+ use metal::{+ MTL4ArgumentTable, MTL4ComputeCommandEncoder, MTLComputePipelineState, MTLFunctionConstantValues,+ MTLSize,+ };use objc2::{rc::Retained, runtime::ProtocolObject};- use crate::backends::common::BufferGpuAddressRangeExt;- use crate::backends::metal::{- context::MetalContext,- error::MetalError,- metal_extensions::{- ComputeEncoderSetValue, FunctionConstantValuesSetValue, MetalDataTypeExt,+ use crate::backends::{+ common::{BufferRef, CommandBufferEncoding, BufferMut},+ metal::{+ context::MetalContext,+ error::MetalError,+ metal_extensions::{FunctionConstantValuesSetValue, MetalDataTypeExt},},};diff --git a/crates/uzu-engine/src/backends/common/allocator/allocator.rs b/crates/uzu-engine/src/backends/common/allocator/allocator.rsdeleted file mode 100644index 8c23c2419..000000000--- a/crates/uzu-engine/src/backends/common/allocator/allocator.rs+++ /dev/null@@ -1,261 +0,0 @@-use std::{- ops::Range,- sync::{- Arc, Weak,- atomic::{AtomicUsize, Ordering},- },-};--use bytemuck::{AnyBitPattern, NoUninit};-use parking_lot::Mutex;--use crate::backends::common::{- AsBufferRangeMut, AsBufferRangeRef, Backend, Buffer, BufferRangeMut, BufferRangeRef, Context, DenseBuffer,- allocator::{RangeAllocationType, RangeAllocator},-};--pub struct Allocation<B: Backend> {- allocator: Arc<Allocator<B>>,- buffer: Arc<B::DenseBuffer>,- range: Range<usize>,- allocation_type: RangeAllocationType,-}--impl<B: Backend> Allocation<B> {- pub fn size(&self) -> usize {- self.range.len()- }-- pub fn as_slice_mut<T: NoUninit + AnyBitPattern>(&mut self) -> &mut [T] {- let base = self.buffer.cpu_ptr().cast::<u8>().as_ptr();- let bytes = unsafe { std::slice::from_raw_parts_mut(base.add(self.range.start), self.range.len()) };- bytemuck::cast_slice_mut(bytes)- }-- pub fn copyin<T: NoUninit + AnyBitPattern>(- &mut self,- data: &[T],- ) {- self.as_slice_mut().copy_from_slice(data);- }-- pub fn as_slice<T: AnyBitPattern>(&self) -> &[T] {- let base = self.buffer.cpu_ptr().cast::<u8>().as_ptr();- let bytes = unsafe { std::slice::from_raw_parts(base.add(self.range.start), self.range.len()) };- bytemuck::cast_slice(bytes)- }-- pub fn copyout<T: AnyBitPattern>(&self) -> Vec<T> {- self.as_slice().to_vec()- }-}--impl<B: Backend> AsBufferRangeRef for Allocation<B> {- type Buffer = B::DenseBuffer;-- fn as_buffer_range_ref<'a>(&'a self) -> BufferRangeRef<'a, B::DenseBuffer> {- BufferRangeRef::new(self.buffer.as_ref(), self.range.clone())- }-}--impl<B: Backend> AsBufferRangeMut for Allocation<B> {- fn as_buffer_range_mut<'a>(&'a mut self) -> BufferRangeMut<'a, B::DenseBuffer> {- // SAFETY: allocator algorithm (hopefully if there is no bugs) guarantees no two overlapping live allocations can exist (which is the contract of BufferRangeMut)- unsafe { BufferRangeMut::new_shared(self.buffer.as_ref(), self.range.clone()) }- }-}--impl<B: Backend> Drop for Allocation<B> {- fn drop(&mut self) {- self.allocator.free(self)- }-}--pub struct AllocationPool<B: Backend> {- reusable: bool,- allocator: Arc<Allocator<B>>,- pool_number: usize,-}--impl<B: Backend> Drop for AllocationPool<B> {- fn drop(&mut self) {- self.allocator.free_pool(self)- }-}--pub enum AllocationType<'a, B: Backend> {- Global,- Pooled {- pool: &'a AllocationPool<B>,- cpu_available: bool,- },-}--struct AllocatorBuffer<B: Backend> {- buffer: Arc<B::DenseBuffer>,- range_allocator: RangeAllocator,-}--pub struct Allocator<B: Backend> {- context: Weak<B::Context>,- allocator_buffers: Mutex<Vec<AllocatorBuffer<B>>>,- next_pool_number: AtomicUsize,- peak_memory_usage: AtomicUsize,-}--impl<B: Backend> Allocator<B> {- pub fn new(context: Weak<B::Context>) -> Arc<Self> {- Arc::new(Self {- context,- allocator_buffers: Mutex::new(Vec::new()),- next_pool_number: AtomicUsize::new(0),- peak_memory_usage: AtomicUsize::new(0),- })- }-- pub fn allocate(- self: &Arc<Self>,- size: usize,- allocation_type: AllocationType<B>,- ) -> Result<Allocation<B>, B::Error> {- assert!(size > 0, "allocation size must be greater than 0");- let alignment =- usize::clamp(size.next_power_of_two(), B::MIN_ALLOCATION_ALIGNMENT, B::MAX_ALLOCATION_ALIGNMENT);- let allocation_type = match allocation_type {- AllocationType::Global => RangeAllocationType::Global,- AllocationType::Pooled {- pool,- cpu_available,- } => RangeAllocationType::Pooled {- pool: pool.pool_number,- can_alias_before: !cpu_available,- can_alias_after: !(cpu_available && pool.reusable),- },- };-- let mut allocator_buffers = self.allocator_buffers.lock();-- let found = allocator_buffers.iter_mut().enumerate().find_map(|(allocator_buffer_index, allocator_buffer)| {- let range = allocator_buffer.range_allocator.allocate_range_aligned(size, alignment, allocation_type)?;-- Some((allocator_buffer_index, allocator_buffer.buffer.clone(), range))- });-- let (buffer, range) = if let Some((allocator_buffer_index, buffer, range)) = found {- Self::restore_buffer_order(&mut allocator_buffers, allocator_buffer_index);-- (buffer, range)- } else {- let new_allocator_buffer_size = usize::max(size, B::ALLOCATION_GRANULARITY);-- let mut allocator_buffer = AllocatorBuffer::<B> {- buffer: Arc::new(self.context.upgrade().unwrap().create_buffer(new_allocator_buffer_size)?), // Upgrade can never fail- range_allocator: RangeAllocator::new(0..new_allocator_buffer_size),- };-- let buffer = allocator_buffer.buffer.clone();- let range =- allocator_buffer.range_allocator.allocate_range_aligned(size, alignment, allocation_type).unwrap(); // Can never fail-- allocator_buffers.push(allocator_buffer);- let allocator_buffer_index = allocator_buffers.len() - 1;- Self::restore_buffer_order(&mut allocator_buffers, allocator_buffer_index);-- self.peak_memory_usage.store(- allocator_buffers.iter().map(|allocator_buffer| allocator_buffer.buffer.size()).sum(),- Ordering::Relaxed,- );-- (buffer, range)- };-- Ok(Allocation {- allocator: self.clone(),- buffer,- range,- allocation_type,- })- }-- pub fn create_pool(- self: &Arc<Self>,- reusable: bool,- ) -> AllocationPool<B> {- let pool_number = self.next_pool_number.fetch_add(1, Ordering::Relaxed);-- AllocationPool {- reusable,- allocator: self.clone(),- pool_number,- }- }-- pub fn peak_memory_usage(&self) -> usize {- self.peak_memory_usage.load(Ordering::Relaxed)- }-- // TODO: Maybe hysteresis in free/free_pool?-- fn free(- self: &Arc<Self>,- allocation: &Allocation<B>,- ) {- let mut allocator_buffers = self.allocator_buffers.lock();-- let allocator_buffer_index = allocator_buffers- .iter()- .position(|allocator_buffer| Arc::ptr_eq(&allocator_buffer.buffer, &allocation.buffer))- .unwrap(); // Can never fail-- allocator_buffers[allocator_buffer_index]- .range_allocator- .free_range(allocation.range.clone(), allocation.allocation_type);-- if allocator_buffers[allocator_buffer_index].range_allocator.is_empty() {- allocator_buffers.remove(allocator_buffer_index);- } else {- Self::restore_buffer_order(&mut allocator_buffers, allocator_buffer_index);- }- }-- fn free_pool(- self: &Arc<Self>,- pool: &AllocationPool<B>,- ) {- let mut allocator_buffers = self.allocator_buffers.lock();-- allocator_buffers.retain_mut(|allocation_buffer| {- allocation_buffer.range_allocator.free_pool(pool.pool_number);- !allocation_buffer.range_allocator.is_empty()- });-- if allocator_buffers.len() > 1 {- allocator_buffers.sort_by_key(|allocator_buffer| allocator_buffer.range_allocator.total_available());- }- }-- fn restore_buffer_order(- allocator_buffers: &mut [AllocatorBuffer<B>],- mut index: usize,- ) {- while index > 0- && allocator_buffers[index].range_allocator.total_available()- < allocator_buffers[index - 1].range_allocator.total_available()- {- allocator_buffers.swap(index, index - 1);- index -= 1;- }-- while index + 1 < allocator_buffers.len()- && allocator_buffers[index].range_allocator.total_available()- > allocator_buffers[index + 1].range_allocator.total_available()- {- allocator_buffers.swap(index, index + 1);- index += 1;- }- }-}--#[cfg(all(test, backend = "metal"))]-#[path = "../../../../unit/backends/common/allocator/allocator.rs"]-mod tests;diff --git a/crates/uzu-engine/src/backends/common/allocator/block.rs b/crates/uzu-engine/src/backends/common/allocator/block.rsnew file mode 100644index 000000000..cc0806fcb--- /dev/null+++ b/crates/uzu-engine/src/backends/common/allocator/block.rs@@ -0,0 +1,72 @@+use std::{collections::HashMap, mem::ManuallyDrop, range::Range, sync::Arc};++use parking_lot::Mutex;++// TODO: this is a stub, real block allocator should suballocate from large pages++pub struct BlockAllocator<T> {+ min_page_size: usize,+ cache: Mutex<HashMap<usize, Vec<T>>>,+}++impl<T> BlockAllocator<T> {+ pub fn new(min_page_size: usize) -> Arc<Self> {+ Arc::new(Self {+ min_page_size,+ cache: Mutex::new(HashMap::new()),+ })+ }++ pub fn allocate<E>(+ self: &Arc<Self>,+ size: usize,+ upstream: impl FnOnce(usize) -> Result<T, E>,+ ) -> Result<BlockAllocation<T>, E> {+ assert!(size > 0);++ let page = if let mut cache_locked = self.cache.lock()+ && let Some(cache_entries) = cache_locked.get_mut(&size.max(self.min_page_size))+ && let Some(cache_entry) = cache_entries.pop()+ {+ cache_entry+ } else {+ upstream(size.max(self.min_page_size))?+ };++ Ok(BlockAllocation {+ allocator: self.clone(),+ page: ManuallyDrop::new(page),+ range: (0..size).into(),+ })+ }++ fn free(+ self: &Arc<Self>,+ page: T,+ range: Range<usize>,+ ) {+ self.cache.lock().entry(range.iter().len().max(self.min_page_size)).or_default().push(page);+ }+}++pub struct BlockAllocation<T> {+ allocator: Arc<BlockAllocator<T>>,+ page: ManuallyDrop<T>,+ range: Range<usize>,+}++impl<T> BlockAllocation<T> {+ pub fn page(&self) -> &T {+ &self.page+ }++ pub fn range(&self) -> Range<usize> {+ self.range+ }+}++impl<T> Drop for BlockAllocation<T> {+ fn drop(&mut self) {+ self.allocator.free(unsafe { ManuallyDrop::take(&mut self.page) }, self.range);+ }+}diff --git a/crates/uzu-engine/src/backends/common/allocator/bump.rs b/crates/uzu-engine/src/backends/common/allocator/bump.rsnew file mode 100644index 000000000..77abe7dec--- /dev/null+++ b/crates/uzu-engine/src/backends/common/allocator/bump.rs@@ -0,0 +1,75 @@+use std::{range::Range, sync::Arc};++struct BumpAllocatorPage<T> {+ page: Arc<T>,+ size: usize,+ offset: usize,+}++pub struct BumpAllocator<T> {+ min_page_size: usize,+ pages: Vec<BumpAllocatorPage<T>>,+}++impl<T> BumpAllocator<T> {+ pub fn new(min_page_size: usize) -> Self {+ Self {+ min_page_size,+ pages: Vec::new(),+ }+ }++ pub fn allocate<E>(+ &mut self,+ size: usize,+ upstream: impl FnOnce(usize) -> Result<T, E>,+ ) -> Result<BumpAllocation<T>, E> {+ assert!(size > 0);++ let alignment = usize::min(size, 64).next_power_of_two();++ if let Some(page) = self.pages.last_mut()+ && let page_offset_aligned = page.offset.next_multiple_of(alignment)+ && page_offset_aligned + size <= page.size+ {+ let allocation = BumpAllocation {+ page: page.page.clone(),+ range: (page_offset_aligned..page_offset_aligned + size).into(),+ };+ page.offset = page_offset_aligned + size;+ return Ok(allocation);+ }++ let new_page_size = usize::max(size, self.min_page_size);+ let new_page = Arc::new(upstream(new_page_size)?);+ self.pages.push(BumpAllocatorPage {+ page: new_page.clone(),+ size: new_page_size,+ offset: size,+ });++ Ok(BumpAllocation {+ page: new_page,+ range: (0..size).into(),+ })+ }++ pub fn is_done(&self) -> bool {+ self.pages.iter().all(|page| Arc::strong_count(&page.page) == 1)+ }+}++pub struct BumpAllocation<T> {+ page: Arc<T>,+ range: Range<usize>,+}++impl<T> BumpAllocation<T> {+ pub fn page(&self) -> &T {+ &self.page+ }++ pub fn range(&self) -> Range<usize> {+ self.range+ }+}diff --git a/crates/uzu-engine/src/backends/common/allocator/mod.rs b/crates/uzu-engine/src/backends/common/allocator/mod.rsindex c6e4a183c..783dd0817 100644--- a/crates/uzu-engine/src/backends/common/allocator/mod.rs+++ b/crates/uzu-engine/src/backends/common/allocator/mod.rs@@ -1,5 +1,4 @@-mod allocator;-mod range_allocator;--pub use allocator::{Allocation, AllocationPool, AllocationType, Allocator};-use range_allocator::{AllocationType as RangeAllocationType, RangeAllocator};+#[cfg(backend = "metal")]+pub mod block;+pub mod bump;+pub mod pool;diff --git a/crates/uzu-engine/src/backends/common/allocator/pool.rs b/crates/uzu-engine/src/backends/common/allocator/pool.rsnew file mode 100644index 000000000..65e7d0ec1--- /dev/null+++ b/crates/uzu-engine/src/backends/common/allocator/pool.rs@@ -0,0 +1,65 @@+use std::{collections::VecDeque, mem::ManuallyDrop, range::Range, sync::Arc};++use parking_lot::Mutex;++pub struct PoolAllocator<T> {+ pages: [Mutex<VecDeque<T>>; 32],+}++impl<T> PoolAllocator<T> {+ pub fn new() -> Arc<Self> {+ Arc::new(Self {+ pages: Default::default(),+ })+ }++ pub fn allocate<E>(+ self: &Arc<Self>,+ size: usize,+ upstream: impl FnOnce(usize) -> Result<T, E>,+ ) -> Result<PoolAllocation<T>, E> {+ assert!(size > 0 && size <= 2 * 1024 * 1024 * 1024);++ let page = if let Some(page) = self.pages[(size - 1).bit_width() as usize].lock().pop_front() {+ page+ } else {+ upstream(size.next_power_of_two())?+ };++ Ok(PoolAllocation {+ allocator: self.clone(),+ page: ManuallyDrop::new(page),+ range: (0..size).into(),+ })+ }++ fn alias(+ self: &Arc<Self>,+ page: T,+ range: Range<usize>,+ ) {+ self.pages[(range.iter().len() - 1).bit_width() as usize].lock().push_back(page);+ }+}++pub struct PoolAllocation<T> {+ allocator: Arc<PoolAllocator<T>>,+ page: ManuallyDrop<T>,+ range: Range<usize>,+}++impl<T> PoolAllocation<T> {+ pub fn page(&self) -> &T {+ &self.page+ }++ pub fn range(&self) -> Range<usize> {+ self.range+ }+}++impl<T> Drop for PoolAllocation<T> {+ fn drop(&mut self) {+ self.allocator.alias(unsafe { ManuallyDrop::take(&mut self.page) }, self.range);+ }+}diff --git a/crates/uzu-engine/src/backends/common/allocator/range_allocator.rs b/crates/uzu-engine/src/backends/common/allocator/range_allocator.rsdeleted file mode 100644index 76a982bb3..000000000--- a/crates/uzu-engine/src/backends/common/allocator/range_allocator.rs+++ /dev/null@@ -1,302 +0,0 @@-use std::{- collections::{BTreeMap, BTreeSet},- ops::Range,-};--#[derive(PartialEq, Eq, Clone, Copy)]-pub enum AllocationType {- Global,- Pooled {- pool: usize,- can_alias_before: bool,- can_alias_after: bool,- },-}--#[derive(Default)]-struct AvailableRanges {- by_start: BTreeMap<usize, usize>,- by_len: BTreeSet<(usize, usize, usize)>,- total_len: usize,-}--#[derive(Clone, Copy)]-struct AvailableRangeFit {- available_start: usize,- available_end: usize,- allocated_start: usize,- allocated_end: usize,-}--impl AvailableRangeFit {- fn available_key(self) -> (usize, usize) {- (self.available_end - self.available_start, self.available_start)- }-- fn allocated_range(self) -> Range<usize> {- self.allocated_start..self.allocated_end- }-- fn allocated_len(self) -> usize {- self.allocated_end - self.allocated_start- }-}--impl AvailableRanges {- fn new(range: Range<usize>) -> Self {- let mut available_ranges = Self::default();- available_ranges.insert(range);- available_ranges- }-- fn total_len(&self) -> usize {- self.total_len- }-- fn insert(- &mut self,- mut range: Range<usize>,- ) {- if range.is_empty() {- return;- }-- if let Some((&start, &end)) = self.by_start.range(..=range.start).next_back()- && end >= range.start- {- self.remove_entry(start, end);- range.start = usize::min(range.start, start);- range.end = usize::max(range.end, end);- }-- while let Some((&start, &end)) = self.by_start.range(range.start..).next() {- if start > range.end {- break;- }-- self.remove_entry(start, end);- range.end = usize::max(range.end, end);- }-- self.insert_entry(range.start, range.end);- }-- fn remove_fit(- &mut self,- fit: AvailableRangeFit,- ) -> Range<usize> {- self.remove_entry(fit.available_start, fit.available_end);-- if fit.available_start < fit.allocated_start {- self.insert_entry(fit.available_start, fit.allocated_start);- }-- if fit.allocated_end < fit.available_end {- self.insert_entry(fit.allocated_end, fit.available_end);- }-- fit.allocated_range()- }-- fn best_fit(- &self,- size: usize,- alignment: usize,- ) -> Option<AvailableRangeFit> {- for &(range_len, range_start, range_end) in self.by_len.range((size, 0, 0)..) {- let allocated_start = range_start.next_multiple_of(alignment);-- if range_end.saturating_sub(allocated_start) >= size {- debug_assert_eq!(range_end - range_start, range_len);-- return Some(AvailableRangeFit {- available_start: range_start,- available_end: range_end,- allocated_start,- allocated_end: allocated_start + size,- });- }- }-- None- }-- fn into_ranges(self) -> impl Iterator<Item = Range<usize>> {- self.by_start.into_iter().map(|(start, end)| start..end)- }-- fn insert_entry(- &mut self,- start: usize,- end: usize,- ) {- debug_assert!(start < end);-- let len = end - start;- let old_end = self.by_start.insert(start, end);- debug_assert!(old_end.is_none());-- self.by_len.insert((len, start, end));- self.total_len += len;- }-- fn remove_entry(- &mut self,- start: usize,- end: usize,- ) {- let len = end - start;-- assert_eq!(self.by_start.remove(&start), Some(end));- assert!(self.by_len.remove(&(len, start, end)));- self.total_len -= len;- }-}--pub struct RangeAllocator {- full_len: usize,- free_ranges: AvailableRanges,- aliasable_ranges_by_pool: Vec<AvailableRanges>,- pool_ranges_by_pool: Vec<AvailableRanges>,- pool_live_allocations: Vec<usize>,- total_available: usize,-}--impl RangeAllocator {- pub fn new(full_range: Range<usize>) -> Self {- let full_len = full_range.len();-- Self {- full_len,- free_ranges: AvailableRanges::new(full_range),- aliasable_ranges_by_pool: Vec::new(),- pool_ranges_by_pool: Vec::new(),- pool_live_allocations: Vec::new(),- total_available: full_len,- }- }-- pub fn allocate_range_aligned(- &mut self,- size: usize,- alignment: usize,- allocation_type: AllocationType,- ) -> Option<Range<usize>> {- let aliasable_pool = match allocation_type {- AllocationType::Pooled {- pool,- can_alias_before: true,- can_alias_after: _,- } => Some(pool),- _ => None,- };-- let free_candidate = self.free_ranges.best_fit(size, alignment);- let aliasable_candidate = aliasable_pool.and_then(|pool| {- self.aliasable_ranges_by_pool.get(pool).and_then(|ranges| ranges.best_fit(size, alignment))- });-- let (selected_aliasable_pool, fit) = match (free_candidate, aliasable_candidate) {- (None, None) => return None,- (Some(fit), None) => (None, fit),- (None, Some(fit)) => (aliasable_pool, fit),- (Some(free_fit), Some(aliasable_fit)) if aliasable_fit.available_key() < free_fit.available_key() => {- (aliasable_pool, aliasable_fit)- },- (Some(fit), Some(_)) => (None, fit),- };-- let allocated_range = if let Some(pool) = selected_aliasable_pool {- self.aliasable_ranges_by_pool[pool].remove_fit(fit)- } else {- self.free_ranges.remove_fit(fit)- };- self.total_available -= fit.allocated_len();-- match allocation_type {- AllocationType::Global => {},- AllocationType::Pooled {- pool,- can_alias_before: _,- can_alias_after: _,- } => {- self.ensure_pool(pool);- self.pool_live_allocations[pool] += 1;-- if selected_aliasable_pool.is_none() {- self.pool_ranges_by_pool[pool].insert(allocated_range.clone());- }- },- };-- Some(allocated_range)- }-- pub fn free_range(- &mut self,- range: Range<usize>,- allocation_type: AllocationType,- ) {- match allocation_type {- AllocationType::Global => {- self.free_ranges.insert(range.clone());- self.total_available += range.len();- },- AllocationType::Pooled {- pool,- can_alias_before: _,- can_alias_after,- } => {- self.pool_live_allocations[pool] -= 1;-- if can_alias_after {- self.aliasable_ranges_by_pool[pool].insert(range.clone());- self.total_available += range.len();- }- },- };- }-- pub fn free_pool(- &mut self,- pool: usize,- ) {- if let Some(live_allocations) = self.pool_live_allocations.get(pool) {- assert_eq!(*live_allocations, 0, "attempted to free a pool that has live allocations");- }-- if let Some(aliasable_ranges) = self.aliasable_ranges_by_pool.get_mut(pool) {- self.total_available -= aliasable_ranges.total_len();- *aliasable_ranges = AvailableRanges::default();- }-- let Some(pool_ranges) = self.pool_ranges_by_pool.get_mut(pool) else {- return;- };- let pool_ranges = std::mem::take(pool_ranges);-- for pool_range in pool_ranges.into_ranges() {- self.free_ranges.insert(pool_range.clone());- self.total_available += pool_range.len();- }- }-- pub fn total_available(&self) -> usize {- self.total_available- }-- pub fn is_empty(&self) -> bool {- self.free_ranges.total_len() == self.full_len- }-- fn ensure_pool(- &mut self,- pool: usize,- ) {- let pool_len = pool + 1;-- self.aliasable_ranges_by_pool.resize_with(pool_len, AvailableRanges::default);- self.pool_ranges_by_pool.resize_with(pool_len, AvailableRanges::default);- self.pool_live_allocations.resize(pool_len, 0);- }-}diff --git a/crates/uzu-engine/src/backends/common/backend.rs b/crates/uzu-engine/src/backends/common/backend.rsindex f29bfc6b1..6bb45917e 100644--- a/crates/uzu-engine/src/backends/common/backend.rs+++ b/crates/uzu-engine/src/backends/common/backend.rs@@ -1,18 +1,17 @@use std::{error::Error, fmt::Debug};-use super::{CommandBuffer, Context, DenseBuffer, Kernels, SparseBuffer};+use super::{CommandBuffer, ConstantBuffer, Context, GlobalBuffer, Kernels, ScratchBuffer, SparseBuffer};pub trait Backend: Debug + Clone + Send + Sync + 'static {type Context: Context<Backend = Self>;type CommandBuffer: CommandBuffer<Backend = Self>;- type DenseBuffer: DenseBuffer<Backend = Self>;+ type GlobalBuffer: GlobalBuffer<Backend = Self>;+ type ConstantBuffer: ConstantBuffer<Backend = Self>;+ type ScratchBuffer: ScratchBuffer<Backend = Self>;type SparseBuffer: SparseBuffer<Backend = Self>;+ type AllocationPool: Send + Sync;type Kernels: Kernels<Backend = Self>;type Error: Error + Debug;const NAME: &'static str;- const MIN_ALLOCATION_ALIGNMENT: usize;- const MAX_ALLOCATION_ALIGNMENT: usize;- const ALLOCATION_GRANULARITY: usize;- const MAX_INLINE_BYTES: usize;}diff --git a/crates/uzu-engine/src/backends/common/buffer/arg.rs b/crates/uzu-engine/src/backends/common/buffer/arg.rsdeleted file mode 100644index 5c383d800..000000000--- a/crates/uzu-engine/src/backends/common/buffer/arg.rs+++ /dev/null@@ -1,59 +0,0 @@-use crate::backends::common::{AsBufferRangeMut, AsBufferRangeRef, Backend, Buffer, BufferRangeMut};--// TODO: This whole thing is horrible and should be unified with AsBufferRangeRef-pub trait BufferArg<'a, B: Backend>: Copy {- fn into_parts(self) -> (&'a dyn Buffer<Backend = B>, usize, usize);-}--impl<'a, B: Backend, T: AsBufferRangeRef<Buffer: Buffer<Backend = B>>> BufferArg<'a, B> for &'a T {- fn into_parts(self) -> (&'a dyn Buffer<Backend = B>, usize, usize) {- let buffer_range = self.as_buffer_range_ref();- let (buffer, range) = (buffer_range.buffer(), buffer_range.range());- (buffer, range.start, range.end - range.start)- }-}--impl<'a, B: Backend> BufferArg<'a, B> for &'a dyn Buffer<Backend = B> {- fn into_parts(self) -> (&'a dyn Buffer<Backend = B>, usize, usize) {- (self, 0, self.size())- }-}--impl<'a, B: Backend, T: BufferArg<'a, B>> BufferArg<'a, B> for (T, usize) {- fn into_parts(self) -> (&'a dyn Buffer<Backend = B>, usize, usize) {- let (buffer, offset, length) = self.0.into_parts();- (buffer, offset + self.1, length - self.1)- }-}--pub trait BufferArgMut<'a, B: Backend> {- fn into_parts(self) -> (&'a dyn Buffer<Backend = B>, usize, usize);-}--impl<'a, B: Backend, Buf: Buffer<Backend = B>> BufferArgMut<'a, B> for BufferRangeMut<'a, Buf> {- fn into_parts(self) -> (&'a dyn Buffer<Backend = B>, usize, usize) {- let (buffer, range) = (self.buffer(), self.range());- (buffer, range.start, range.len())- }-}--impl<'a, B: Backend, T: AsBufferRangeMut<Buffer: Buffer<Backend = B>>> BufferArgMut<'a, B> for &'a mut T {- fn into_parts(self) -> (&'a dyn Buffer<Backend = B>, usize, usize) {- let buffer_range = self.as_buffer_range_mut();- let (buffer, range) = (buffer_range.buffer(), buffer_range.range());- (buffer, range.start, range.end - range.start)- }-}--impl<'a, B: Backend> BufferArgMut<'a, B> for &'a mut dyn Buffer<Backend = B> {- fn into_parts(self) -> (&'a dyn Buffer<Backend = B>, usize, usize) {- (self, 0, self.size())- }-}--impl<'a, B: Backend, T: BufferArgMut<'a, B>> BufferArgMut<'a, B> for (T, usize) {- fn into_parts(self) -> (&'a dyn Buffer<Backend = B>, usize, usize) {- let (buffer, offset, length) = self.0.into_parts();- (buffer, offset + self.1, length - self.1)- }-}diff --git a/crates/uzu-engine/src/backends/common/buffer/constant.rs b/crates/uzu-engine/src/backends/common/buffer/constant.rsnew file mode 100644index 000000000..294f94088--- /dev/null+++ b/crates/uzu-engine/src/backends/common/buffer/constant.rs@@ -0,0 +1,3 @@+use crate::backends::common::{Backend, BufferCpuAccessible};++pub trait ConstantBuffer: BufferCpuAccessible<Backend: Backend<ConstantBuffer = Self>> {}diff --git a/crates/uzu-engine/src/backends/common/buffer/cpu_accessible.rs b/crates/uzu-engine/src/backends/common/buffer/cpu_accessible.rsnew file mode 100644index 000000000..297093484--- /dev/null+++ b/crates/uzu-engine/src/backends/common/buffer/cpu_accessible.rs@@ -0,0 +1,7 @@+use std::{os::raw::c_void, ptr::NonNull};++use crate::backends::common::Buffer;++pub trait BufferCpuAccessible: Buffer {+ fn cpu_ptr(&self) -> NonNull<c_void>;+}diff --git a/crates/uzu-engine/src/backends/common/buffer/dense.rs b/crates/uzu-engine/src/backends/common/buffer/dense.rsdeleted file mode 100644index c6be7a0ae..000000000--- a/crates/uzu-engine/src/backends/common/buffer/dense.rs+++ /dev/null@@ -1,7 +0,0 @@-use std::{os::raw::c_void, ptr::NonNull};--use crate::backends::common::{Backend, Buffer};--pub trait DenseBuffer: Buffer<Backend: Backend<DenseBuffer = Self>> {- fn cpu_ptr(&self) -> NonNull<c_void>;-}diff --git a/crates/uzu-engine/src/backends/common/buffer/global.rs b/crates/uzu-engine/src/backends/common/buffer/global.rsnew file mode 100644index 000000000..2f2981f1f--- /dev/null+++ b/crates/uzu-engine/src/backends/common/buffer/global.rs@@ -0,0 +1,3 @@+use crate::backends::common::{Backend, BufferCpuAccessible};++pub trait GlobalBuffer: BufferCpuAccessible<Backend: Backend<GlobalBuffer = Self>> {}diff --git a/crates/uzu-engine/src/backends/common/buffer/mod.rs b/crates/uzu-engine/src/backends/common/buffer/mod.rsindex b9e2fd07c..afcadb840 100644--- a/crates/uzu-engine/src/backends/common/buffer/mod.rs+++ b/crates/uzu-engine/src/backends/common/buffer/mod.rs@@ -1,44 +1,57 @@-use std::{any::Any, fmt::Debug, ops::Range};+use std::{any::Any, fmt::Debug, range::Range};-use crate::backends::common::{AsBufferRangeMut, AsBufferRangeRef, Backend, BufferRangeMut, BufferRangeRef};+use crate::backends::common::{Backend, BufferMut, BufferRef};-pub mod dense;+pub mod constant;+pub mod cpu_accessible;+pub mod global;+pub mod scratch;pub mod sparse;-pub mod arg;-pub mod range;+pub mod reference;-pub trait Buffer: Any + Debug + Send + Sync {+pub trait Buffer: Any + Debug + Send + Sync + Unpin {type Backend: Backend;- fn gpu_ptr(&self) -> usize;-fn size(&self) -> usize;}-impl<B: Buffer> AsBufferRangeRef for B {+impl<B: Buffer + ?Sized> BufferRef for &B {+ type Backend = B::Backend;type Buffer = B;- fn as_buffer_range_ref(&self) -> BufferRangeRef<'_, B> {- BufferRangeRef::new(self, 0..self.size())+ fn size(&self) -> usize {+ Buffer::size(*self)}-}-impl<B: Buffer> AsBufferRangeMut for B {- fn as_buffer_range_mut(&mut self) -> BufferRangeMut<'_, B> {- BufferRangeMut::new_exclusive(self, 0..self.size())+ fn parts<'a>(self) -> (&'a B, Range<usize>)+ where+ Self: 'a,+ {+ (self, (0..self.size()).into())}}-pub trait BufferGpuAddressRangeExt: Buffer {- fn gpu_address_subrange(- &self,- subrange: Range<usize>,- ) -> Range<usize> {- assert!(subrange.end <= self.size(), "subrange overflow: subrange={:?} length={}", subrange, self.size());+impl<B: Buffer + ?Sized> BufferMut for &mut B {+ type Backend = B::Backend;+ type Buffer = B;- (self.gpu_ptr() + subrange.start)..(self.gpu_ptr() + subrange.end)+ fn size(&self) -> usize {+ Buffer::size(&**self)+ }++ fn parts<'a>(self) -> (&'a B, Range<usize>)+ where+ Self: 'a,+ {+ (self, (0..self.size()).into())+ }++ fn reborrow(&mut self) -> impl BufferMut<Backend = Self::Backend, Buffer = B> {+ &mut **self}-}-impl<B: Buffer + ?Sized> BufferGpuAddressRangeExt for B {}+ fn as_ref(&self) -> impl BufferRef<Backend = Self::Backend, Buffer = B> {+ &**self+ }+}diff --git a/crates/uzu-engine/src/backends/common/buffer/range.rs b/crates/uzu-engine/src/backends/common/buffer/range.rsdeleted file mode 100644index 5887811b3..000000000--- a/crates/uzu-engine/src/backends/common/buffer/range.rs+++ /dev/null@@ -1,126 +0,0 @@-// NOTE: we treat the buffer as the entire buffer,-// but we also give a "safe" way to get the ref to the whole buffer from a range,-// this is a fundamental limitation of the current design,-// but we can nicely fix this after migration to allocations--use std::ops::Range;--use crate::backends::common::Buffer;--pub struct BufferRangeRef<'a, B: Buffer> {- buffer: &'a B,- range: Range<usize>,-}--impl<'a, B: Buffer> BufferRangeRef<'a, B> {- pub fn new(- buffer: &'a B,- range: Range<usize>,- ) -> Self {- Self {- buffer,- range,- }- }-- pub fn buffer(&self) -> &'a B {- self.buffer- }-- pub fn range(&self) -> Range<usize> {- self.range.clone()- }-- pub fn subrange(- self,- range: Range<usize>,- ) -> Self {- Self {- buffer: self.buffer,- range: subrange(self.range, range),- }- }-}--pub trait AsBufferRangeRef {- type Buffer: Buffer;-- fn as_buffer_range_ref(&self) -> BufferRangeRef<'_, Self::Buffer>;-}--pub struct BufferRangeMut<'a, B: Buffer> {- buffer: &'a B,- range: Range<usize>,-}--impl<'a, B: Buffer> BufferRangeMut<'a, B> {- pub fn new_exclusive(- buffer: &'a mut B,- range: Range<usize>,- ) -> Self {- Self {- buffer,- range,- }- }-- pub unsafe fn new_shared(- buffer: &'a B,- range: Range<usize>,- ) -> Self {- Self {- buffer,- range,- }- }-- pub fn split_at(- self,- byte_offset: usize,- ) -> (Self, Self) {- assert!(byte_offset <= self.range.len(), "split offset exceeds buffer range size");- let split = self.range.start + byte_offset;- let buffer = self.buffer;-- (- Self {- buffer,- range: self.range.start..split,- },- Self {- buffer,- range: split..self.range.end,- },- )- }-- pub fn buffer(&self) -> &'a B {- self.buffer- }-- pub fn range(&self) -> Range<usize> {- self.range.clone()- }-- pub fn subrange(- self,- range: Range<usize>,- ) -> Self {- Self {- buffer: self.buffer,- range: subrange(self.range, range),- }- }-}--pub trait AsBufferRangeMut: AsBufferRangeRef {- fn as_buffer_range_mut(&mut self) -> BufferRangeMut<'_, Self::Buffer>;-}--fn subrange(- buffer_range: Range<usize>,- subrange: Range<usize>,-) -> Range<usize> {- assert!(subrange.end <= buffer_range.len(), "buffer subrange exceeds range");- buffer_range.start + subrange.start..buffer_range.start + subrange.end-}diff --git a/crates/uzu-engine/src/backends/common/buffer/reference.rs b/crates/uzu-engine/src/backends/common/buffer/reference.rsnew file mode 100644index 000000000..8affca261--- /dev/null+++ b/crates/uzu-engine/src/backends/common/buffer/reference.rs@@ -0,0 +1,205 @@+use std::{+ ops::{Bound, RangeBounds},+ range::Range,+};++use bytemuck::{AnyBitPattern, NoUninit};++use crate::backends::common::{Backend, Buffer, BufferCpuAccessible};++// TODO: revisit as_slice/copy bounds and remove horrible unsafe metal kernel argument copyin hack+// TODO: also I'm not a big fan of this implementation. The implementation can be clean when BufferRef is on T+// TODO: but then &(impl BufferRef + ?Sized) everywhere it's used is much worse than a slightly messy trait system++pub trait BufferRef: Copy {+ type Backend: Backend;+ type Buffer: Buffer<Backend = Self::Backend> + ?Sized;++ fn size(&self) -> usize;++ fn parts<'a>(self) -> (&'a Self::Buffer, Range<usize>)+ where+ Self: 'a;++ fn as_slice<'a, T: AnyBitPattern>(self) -> &'a [T]+ where+ Self::Buffer: BufferCpuAccessible,+ Self: 'a,+ {+ let (buffer, range) = self.parts();+ let bytes = unsafe {+ std::slice::from_raw_parts(buffer.cpu_ptr().as_ptr().cast::<u8>().add(range.start), range.iter().len())+ };+ bytemuck::cast_slice(bytes)+ }++ fn copyout<T: AnyBitPattern>(self) -> Vec<T>+ where+ Self::Buffer: BufferCpuAccessible,+ {+ self.as_slice().to_vec()+ }++ fn subrange<'a>(+ self,+ range: impl RangeBounds<usize>,+ ) -> Subbuffer<'a, Self::Buffer, false>+ where+ Self: 'a,+ {+ let (buffer, buffer_range) = self.parts();+ Subbuffer {+ buffer,+ range: subrange(buffer_range, range),+ }+ }+}++pub trait BufferMut: Sized {+ type Backend: Backend;+ type Buffer: Buffer<Backend = Self::Backend> + ?Sized;++ fn size(&self) -> usize;++ fn parts<'a>(self) -> (&'a Self::Buffer, Range<usize>)+ where+ Self: 'a;++ fn reborrow(&mut self) -> impl BufferMut<Backend = Self::Backend, Buffer = Self::Buffer>;++ fn as_ref(&self) -> impl BufferRef<Backend = Self::Backend, Buffer = Self::Buffer>;++ #[expect(clippy::wrong_self_convention)]+ fn as_slice_mut<'a, T: NoUninit + AnyBitPattern>(self) -> &'a mut [T]+ where+ Self::Buffer: BufferCpuAccessible,+ Self: 'a,+ {+ let (buffer, range) = self.parts();+ let bytes = unsafe {+ std::slice::from_raw_parts_mut(buffer.cpu_ptr().as_ptr().cast::<u8>().add(range.start), range.iter().len())+ };+ bytemuck::cast_slice_mut(bytes)+ }++ fn copyin(+ self,+ data: &[impl NoUninit + AnyBitPattern],+ ) where+ Self::Buffer: BufferCpuAccessible,+ {+ self.as_slice_mut().copy_from_slice(data);+ }++ fn subrange_mut<'a>(+ self,+ range: impl RangeBounds<usize>,+ ) -> Subbuffer<'a, Self::Buffer, true>+ where+ Self: 'a,+ {+ let (buffer, buffer_range) = self.parts();+ Subbuffer {+ buffer,+ range: subrange(buffer_range, range),+ }+ }++ fn split_at<'a>(+ self,+ byte_offset: usize,+ ) -> (Subbuffer<'a, Self::Buffer, true>, Subbuffer<'a, Self::Buffer, true>)+ where+ Self: 'a,+ {+ let (buffer, range) = self.parts();+ assert!(byte_offset <= range.iter().len(), "split offset exceeds buffer range size");+ let split = range.start + byte_offset;+ (+ Subbuffer {+ buffer,+ range: (range.start..split).into(),+ },+ Subbuffer {+ buffer,+ range: (split..range.end).into(),+ },+ )+ }+}++pub struct Subbuffer<'a, B: Buffer + ?Sized, const MUTABLE: bool> {+ buffer: &'a B,+ range: Range<usize>,+}++impl<B: Buffer + ?Sized> Clone for Subbuffer<'_, B, false> {+ fn clone(&self) -> Self {+ *self+ }+}+impl<B: Buffer + ?Sized> Copy for Subbuffer<'_, B, false> {}++impl<B: Buffer + ?Sized> BufferRef for Subbuffer<'_, B, false> {+ type Backend = B::Backend;+ type Buffer = B;++ fn size(&self) -> usize {+ self.range.iter().len()+ }++ fn parts<'a>(self) -> (&'a B, Range<usize>)+ where+ Self: 'a,+ {+ (self.buffer, self.range)+ }+}++impl<B: Buffer + ?Sized> BufferMut for Subbuffer<'_, B, true> {+ type Backend = B::Backend;+ type Buffer = B;++ fn size(&self) -> usize {+ self.range.iter().len()+ }++ fn parts<'a>(self) -> (&'a B, Range<usize>)+ where+ Self: 'a,+ {+ (self.buffer, self.range)+ }++ fn reborrow(&mut self) -> impl BufferMut<Backend = Self::Backend, Buffer = B> {+ Subbuffer::<_, true> {+ buffer: self.buffer,+ range: self.range,+ }+ }++ fn as_ref(&self) -> impl BufferRef<Backend = Self::Backend, Buffer = B> {+ Subbuffer::<_, false> {+ buffer: self.buffer,+ range: self.range,+ }+ }+}++pub fn subrange(+ buffer_range: Range<usize>,+ subrange: impl RangeBounds<usize>,+) -> Range<usize> {+ let start = match subrange.start_bound() {+ Bound::Included(&start) => start,+ Bound::Excluded(&start) => start.checked_add(1).expect("subrange start overflow"),+ Bound::Unbounded => 0,+ };+ let end = match subrange.end_bound() {+ Bound::Included(&end) => end.checked_add(1).expect("subrange end overflow"),+ Bound::Excluded(&end) => end,+ Bound::Unbounded => buffer_range.iter().len(),+ };+ assert!(start <= end && end <= buffer_range.iter().len(), "invalid subrange");+ (buffer_range.start + start..buffer_range.start + end).into()+}diff --git a/crates/uzu-engine/src/backends/common/buffer/scratch.rs b/crates/uzu-engine/src/backends/common/buffer/scratch.rsnew file mode 100644index 000000000..e417e3b38--- /dev/null+++ b/crates/uzu-engine/src/backends/common/buffer/scratch.rs@@ -0,0 +1,3 @@+use crate::backends::common::{Backend, Buffer};++pub trait ScratchBuffer: Buffer<Backend: Backend<ScratchBuffer = Self>> {}diff --git a/crates/uzu-engine/src/backends/common/buffer/sparse.rs b/crates/uzu-engine/src/backends/common/buffer/sparse.rsindex 5b522c1bc..c82b8765a 100644--- a/crates/uzu-engine/src/backends/common/buffer/sparse.rs+++ b/crates/uzu-engine/src/backends/common/buffer/sparse.rs@@ -1,4 +1,4 @@-use std::ops::Range;+use std::range::Range;use crate::backends::common::{Backend, Buffer};@@ -6,22 +6,18 @@ pub trait SparseBuffer: Buffer<Backend: Backend<SparseBuffer = Self>> {fn map(&mut self,context: &<Self::Backend as Backend>::Context,- pages: &Range<usize>,+ pages: impl Into<Range<usize>>,) -> Result<(), <Self::Backend as Backend>::Error>;fn unmap(&mut self,context: &<Self::Backend as Backend>::Context,- pages: &Range<usize>,+ pages: impl Into<Range<usize>>,) -> Result<(), <Self::Backend as Backend>::Error>;fn page_size_bytes(&self) -> usize;-}-pub trait SparseBufferExt: SparseBuffer {fn total_pages(&self) -> usize {self.size() / self.page_size_bytes()}}--impl<B: SparseBuffer> SparseBufferExt for B {}diff --git a/crates/uzu-engine/src/backends/common/command_buffer.rs b/crates/uzu-engine/src/backends/common/command_buffer.rsindex e9ba90c48..0377b6a70 100644--- a/crates/uzu-engine/src/backends/common/command_buffer.rs+++ b/crates/uzu-engine/src/backends/common/command_buffer.rs@@ -1,96 +1,78 @@-use std::time::Duration;+use std::{mem::size_of_val, time::Duration};-use super::{Backend, Buffer, BufferRangeMut, BufferRangeRef};+use bytemuck::{AnyBitPattern, NoUninit};++use crate::{+ array::size_for_shape,+ backends::common::{Backend, BufferMut, BufferRef},+ data_type::DataType,+};pub trait CommandBuffer {type Backend: Backend<CommandBuffer = Self>;- type Initial: CommandBufferInitial<CommandBuffer = Self>;type Encoding: CommandBufferEncoding<CommandBuffer = Self>;type Executable: CommandBufferExecutable<CommandBuffer = Self>;type Pending: CommandBufferPending<CommandBuffer = Self>;type Completed: CommandBufferCompleted<CommandBuffer = Self>;}-pub trait CommandBufferInitial: Send {- type CommandBuffer: CommandBuffer<Initial = Self>;+pub trait CommandBufferEncoding {+ type CommandBuffer: CommandBuffer<Encoding = Self>;- fn start_encoding(self) -> <Self::CommandBuffer as CommandBuffer>::Encoding;-}+ fn context(&self) -> &<<Self::CommandBuffer as CommandBuffer>::Backend as Backend>::Context;-#[derive(Debug, Clone, PartialEq)]-pub struct AccessFlags {- pub compute_read: bool,- pub compute_write: bool,- pub copy_read: bool,- pub copy_write: bool,-}+ fn allocate_constant(+ &mut self,+ size: usize,+ ) -> Result<+ <<Self::CommandBuffer as CommandBuffer>::Backend as Backend>::ConstantBuffer,+ <<Self::CommandBuffer as CommandBuffer>::Backend as Backend>::Error,+ >;-impl AccessFlags {- pub fn empty() -> Self {- Self {- compute_read: false,- compute_write: false,- copy_read: false,- copy_write: false,- }+ fn allocate_constant_from_slice(+ &mut self,+ data: &[impl NoUninit + AnyBitPattern],+ ) -> Result<+ <<Self::CommandBuffer as CommandBuffer>::Backend as Backend>::ConstantBuffer,+ <<Self::CommandBuffer as CommandBuffer>::Backend as Backend>::Error,+ > {+ let mut buffer = self.allocate_constant(size_of_val(data))?;+ buffer.copyin(data);+ Ok(buffer)}- pub fn with_compute_read(mut self) -> Self {- self.compute_read = true;- self- }- pub fn with_compute_write(mut self) -> Self {- self.compute_write = true;- self- }- pub fn with_copy_read(mut self) -> Self {- self.copy_read = true;- self- }- pub fn with_copy_write(mut self) -> Self {- self.copy_write = true;- self- }+ fn allocate_scratch(+ &mut self,+ size: usize,+ ) -> Result<+ <<Self::CommandBuffer as CommandBuffer>::Backend as Backend>::ScratchBuffer,+ <<Self::CommandBuffer as CommandBuffer>::Backend as Backend>::Error,+ >;- pub fn compute_read() -> Self {- Self::empty().with_compute_read()- }- pub fn compute_write() -> Self {- Self::empty().with_compute_write()- }- pub fn copy_read() -> Self {- Self::empty().with_copy_read()- }- pub fn copy_write() -> Self {- Self::empty().with_copy_write()+ fn allocate_scratch_for_shape(+ &mut self,+ shape: &[u32],+ data_type: DataType,+ ) -> Result<+ <<Self::CommandBuffer as CommandBuffer>::Backend as Backend>::ScratchBuffer,+ <<Self::CommandBuffer as CommandBuffer>::Backend as Backend>::Error,+ > {+ self.allocate_scratch(size_for_shape(shape, data_type))}-}-pub trait CommandBufferEncoding {- type CommandBuffer: CommandBuffer<Encoding = Self>;-- fn encode_copy<- Src: Buffer<Backend = <Self::CommandBuffer as CommandBuffer>::Backend>,- Dst: Buffer<Backend = <Self::CommandBuffer as CommandBuffer>::Backend>,- >(+ fn encode_copy(&mut self,- src: BufferRangeRef<Src>,- dst: BufferRangeMut<Dst>,+ src: impl BufferRef<Backend = <Self::CommandBuffer as CommandBuffer>::Backend>,+ dst: impl BufferMut<Backend = <Self::CommandBuffer as CommandBuffer>::Backend>,);- fn encode_fill<Dst: Buffer<Backend = <Self::CommandBuffer as CommandBuffer>::Backend>>(+ fn encode_fill(&mut self,- dst: BufferRangeMut<Dst>,+ dst: impl BufferMut<Backend = <Self::CommandBuffer as CommandBuffer>::Backend>,value: u8,);- fn encode_barrier(- &mut self,- after: AccessFlags,- before: AccessFlags,- );-fn push_debug_group(&mut self,name: &str,diff --git a/crates/uzu-engine/src/backends/common/context.rs b/crates/uzu-engine/src/backends/common/context.rsindex bfdde01da..0b07354ba 100644--- a/crates/uzu-engine/src/backends/common/context.rs+++ b/crates/uzu-engine/src/backends/common/context.rs@@ -1,6 +1,6 @@use std::{path::Path, sync::Arc};-use crate::backends::common::{Allocation, AllocationPool, AllocationType, Backend, CommandBuffer, DeviceCapabilities};+use crate::backends::common::{Backend, CommandBuffer, DeviceCapabilities};pub trait Context: Sized + Send + Sync {type Backend: Backend<Context = Self>;@@ -12,29 +12,21 @@ pub trait Context: Sized + Send + Sync {fn create_command_buffer(&self,name: Option<&str>,- ) -> Result<<<Self::Backend as Backend>::CommandBuffer as CommandBuffer>::Initial, <Self::Backend as Backend>::Error>;+ allocation_pool: Option<Arc<<Self::Backend as Backend>::AllocationPool>>,+ ) -> Result<<<Self::Backend as Backend>::CommandBuffer as CommandBuffer>::Encoding, <Self::Backend as Backend>::Error>;fn create_buffer(&self,size: usize,- ) -> Result<<Self::Backend as Backend>::DenseBuffer, <Self::Backend as Backend>::Error>;-- fn create_allocation(- &self,- size: usize,- allocation_type: AllocationType<Self::Backend>,- ) -> Result<Allocation<Self::Backend>, <Self::Backend as Backend>::Error>;-- fn create_allocation_pool(- &self,- reusable: bool,- ) -> AllocationPool<Self::Backend>;+ ) -> Result<<Self::Backend as Backend>::GlobalBuffer, <Self::Backend as Backend>::Error>;fn create_sparse_buffer(&self,capacity: usize,) -> Result<<Self::Backend as Backend>::SparseBuffer, <Self::Backend as Backend>::Error>;+ fn create_allocation_pool(&self) -> Arc<<Self::Backend as Backend>::AllocationPool>;+fn peak_memory_usage(&self) -> Option<usize>;fn enable_capture();diff --git a/crates/uzu-engine/src/backends/common/encoder.rs b/crates/uzu-engine/src/backends/common/encoder.rsdeleted file mode 100644index 987a37c9c..000000000--- a/crates/uzu-engine/src/backends/common/encoder.rs+++ /dev/null@@ -1,248 +0,0 @@-use std::{- mem::size_of_val,- ops::{Bound, Range, RangeBounds},- sync::Arc,- time::Duration,-};--use bytemuck::{AnyBitPattern, NoUninit};--use crate::{- array::size_for_shape,- backends::common::{- AccessFlags, Allocation, AllocationPool, AllocationType, AsBufferRangeMut, AsBufferRangeRef, Backend, Buffer,- BufferGpuAddressRangeExt, CommandBuffer, CommandBufferCompleted, CommandBufferEncoding,- CommandBufferExecutable, CommandBufferInitial, CommandBufferPending, Context,- hazard_tracker::{Access, HazardTracker},- },- data_type::DataType,-};--fn resolve_copy_range(- range: impl RangeBounds<usize>,- allocation_len: usize,- label: &str,-) -> Range<usize> {- let start = match range.start_bound() {- Bound::Included(&value) => value,- Bound::Excluded(&value) => value.checked_add(1).expect("copy range start overflow"),- Bound::Unbounded => 0,- };- let end = match range.end_bound() {- Bound::Included(&value) => value.checked_add(1).expect("copy range end overflow"),- Bound::Excluded(&value) => value,- Bound::Unbounded => allocation_len,- };- assert!(start <= end, "{label} copy range start exceeds end");- assert!(end <= allocation_len, "{label} copy range exceeds allocation");- start..end-}--pub struct Encoder<'encoding, B: Backend> {- context: &'encoding B::Context,- command_buffer: <B::CommandBuffer as CommandBuffer>::Encoding,- allocation_pool: Arc<AllocationPool<B>>,- hazard_tracker: HazardTracker,-}--impl<'encoding, B: Backend> Encoder<'encoding, B> {- pub fn new(context: &'encoding B::Context) -> Result<Self, B::Error> {- Self::new_with_name(context, None)- }-- pub fn new_with_name(- context: &'encoding B::Context,- name: Option<&str>,- ) -> Result<Self, B::Error> {- Self::new_with_pool_name(context, Arc::new(context.create_allocation_pool(false)), name)- }-- pub fn new_with_pool_name(- context: &'encoding B::Context,- allocation_pool: Arc<AllocationPool<B>>,- name: Option<&str>,- ) -> Result<Self, B::Error> {- let command_buffer = context.create_command_buffer(name)?.start_encoding();- let hazard_tracker = HazardTracker::new();-- Ok(Self {- context,- command_buffer,- allocation_pool,- hazard_tracker,- })- }-- // This is valid on both cpu and gpu timelines- pub fn allocate_constant(- &mut self,- size: usize,- ) -> Result<Allocation<B>, B::Error> {- self.context.create_allocation(- size,- AllocationType::Pooled {- pool: &self.allocation_pool,- cpu_available: true,- },- )- }-- pub fn allocate_constant_for_shape(- &mut self,- shape: &[u32],- data_type: DataType,- ) -> Result<Allocation<B>, B::Error> {- self.allocate_constant(size_for_shape(shape, data_type))- }-- pub fn allocate_constant_from_slice<T: NoUninit + AnyBitPattern>(- &mut self,- data: &[T],- ) -> Result<Allocation<B>, B::Error> {- let mut allocation = self.allocate_constant(size_of_val(data))?;- allocation.copyin(data);- Ok(allocation)- }-- // This is valid on gpu timeline only- pub fn allocate_scratch(- &mut self,- size: usize,- ) -> Result<Allocation<B>, B::Error> {- self.context.create_allocation(- size,- AllocationType::Pooled {- pool: &self.allocation_pool,- cpu_available: false,- },- )- }-- pub fn allocate_scratch_for_shape(- &mut self,- shape: &[u32],- data_type: DataType,- ) -> Result<Allocation<B>, B::Error> {- self.allocate_scratch(size_for_shape(shape, data_type))- }-- pub fn encode_copy<- Src: AsBufferRangeRef<Buffer: Buffer<Backend = B>>,- Dst: AsBufferRangeMut<Buffer: Buffer<Backend = B>>,- >(- &mut self,- src: &Src,- src_range: impl RangeBounds<usize>,- dst: &mut Dst,- dst_range: impl RangeBounds<usize>,- ) {- let src_buffer_range = src.as_buffer_range_ref();- let dst_buffer_range = dst.as_buffer_range_mut();- let src_range = resolve_copy_range(src_range, src_buffer_range.range().len(), "source");- let dst_range = resolve_copy_range(dst_range, dst_buffer_range.range().len(), "destination");- let byte_len = src_range.len();- assert_eq!(byte_len, dst_range.len(), "copy range lengths must match");- assert!(byte_len > 0, "zero-sized copies are not allowed");- let src_buffer_range = src_buffer_range.subrange(src_range);- let dst_buffer_range = dst_buffer_range.subrange(dst_range);- self.access(&[- Access {- range: src_buffer_range.buffer().gpu_address_subrange(src_buffer_range.range()),- flags: AccessFlags::copy_read(),- },- Access {- range: dst_buffer_range.buffer().gpu_address_subrange(dst_buffer_range.range()),- flags: AccessFlags::copy_write(),- },- ]);- self.command_buffer.encode_copy(src_buffer_range, dst_buffer_range);- }-- pub fn encode_fill<Dst: AsBufferRangeMut<Buffer: Buffer<Backend = B>>>(- &mut self,- dst: &mut Dst,- value: u8,- ) {- let dst_buffer_range = dst.as_buffer_range_mut();- assert!(!dst_buffer_range.range().is_empty(), "zero-sized fills are not allowed");- self.access(&[Access {- range: dst_buffer_range.buffer().gpu_address_subrange(dst_buffer_range.range()),- flags: AccessFlags::copy_write(),- }]);- self.command_buffer.encode_fill(dst_buffer_range, value);- }-- pub fn push_debug_group(- &mut self,- name: &str,- ) {- self.command_buffer.push_debug_group(name);- }-- pub fn pop_debug_group(&mut self) {- self.command_buffer.pop_debug_group();- }-- pub fn access(- &mut self,- accesses: &[Access],- ) {- if let Some((after, before)) = self.hazard_tracker.access(accesses) {- self.command_buffer.encode_barrier(after, before);- }- }-- pub fn as_command_buffer_mut(&mut self) -> &mut <B::CommandBuffer as CommandBuffer>::Encoding {- &mut self.command_buffer- }-- pub fn context(&self) -> &'encoding B::Context {- self.context- }-- pub fn end_encoding(self) -> Executable<B> {- Executable {- command_buffer: self.command_buffer.end_encoding(),- allocation_pool: self.allocation_pool,- }- }-}--pub struct Executable<B: Backend> {- command_buffer: <B::CommandBuffer as CommandBuffer>::Executable,- allocation_pool: Arc<AllocationPool<B>>,-}--impl<B: Backend> Executable<B> {- pub fn submit(self) -> Pending<B> {- Pending {- command_buffer: self.command_buffer.submit(),- allocation_pool: self.allocation_pool,- }- }-}--pub struct Pending<B: Backend> {- command_buffer: <B::CommandBuffer as CommandBuffer>::Pending,- allocation_pool: Arc<AllocationPool<B>>,-}--impl<B: Backend> Pending<B> {- pub fn wait_until_completed(self) -> Result<Completed<B>, B::Error> {- Ok(Completed {- command_buffer: self.command_buffer.wait_until_completed()?,- _allocation_pool: self.allocation_pool,- })- }-}--pub struct Completed<B: Backend> {- command_buffer: <B::CommandBuffer as CommandBuffer>::Completed,- _allocation_pool: Arc<AllocationPool<B>>,-}--impl<B: Backend> Completed<B> {- pub fn gpu_execution_time(&self) -> Duration {- self.command_buffer.gpu_execution_time()- }-}diff --git a/crates/uzu-engine/src/backends/common/hazard_tracker.rs b/crates/uzu-engine/src/backends/common/hazard_tracker.rsdeleted file mode 100644index 419ffe162..000000000--- a/crates/uzu-engine/src/backends/common/hazard_tracker.rs+++ /dev/null@@ -1,98 +0,0 @@-use std::ops::Range;--use rangemap::RangeSet;--use crate::backends::common::AccessFlags;--#[derive(Debug, Clone)]-pub struct Access {- pub range: Range<usize>,- pub flags: AccessFlags,-}--pub struct HazardTracker {- compute_reads: RangeSet<usize>,- compute_writes: RangeSet<usize>,- copy_reads: RangeSet<usize>,- copy_writes: RangeSet<usize>,-}--impl HazardTracker {- pub fn new() -> Self {- Self {- compute_reads: RangeSet::new(),- compute_writes: RangeSet::new(),- copy_reads: RangeSet::new(),- copy_writes: RangeSet::new(),- }- }-- #[must_use]- pub fn access(- &mut self,- accesses: &[Access],- ) -> Option<(AccessFlags, AccessFlags)> {- let mut after = AccessFlags::empty();- let mut before = AccessFlags::empty();-- // Get existing hazards (before the barrier, aka barrier after this)- for access in accesses {- // Any access should wait for earlier overlapping writes to complete (RAW/WAW)- if access.flags.compute_read- || access.flags.compute_write- || access.flags.copy_read- || access.flags.copy_write- {- if self.compute_writes.overlaps(&access.range) {- after.compute_write = true;- self.compute_writes.clear();- }- if self.copy_writes.overlaps(&access.range) {- after.copy_write = true;- self.copy_writes.clear();- }- }- // Write accesses also must wait for previous reads to complete (WAR)- if access.flags.compute_write || access.flags.copy_write {- if self.compute_reads.overlaps(&access.range) {- after.compute_read = true;- self.compute_reads.clear();- }- if self.copy_reads.overlaps(&access.range) {- after.copy_read = true;- self.copy_reads.clear();- }- }- }-- // Track new ones (after the barrier, aka barrier before this)- for access in accesses {- if access.flags.compute_read {- before.compute_read = true;- self.compute_reads.insert(access.range.clone());- }- if access.flags.compute_write {- before.compute_write = true;- self.compute_writes.insert(access.range.clone());- }- if access.flags.copy_read {- before.copy_read = true;- self.copy_reads.insert(access.range.clone());- }- if access.flags.copy_write {- before.copy_write = true;- self.copy_writes.insert(access.range.clone());- }- }-- if after.compute_read || after.compute_write || after.copy_read || after.copy_write {- Some((after, before))- } else {- None- }- }-}--#[cfg(test)]-#[path = "../../../unit/backends/common/hazard_tracker_test.rs"]-mod tests;diff --git a/crates/uzu-engine/src/backends/common/kernel/activation_transform.rs b/crates/uzu-engine/src/backends/common/kernel/activation_transform.rsindex 7a9199051..07dc5b311 100644--- a/crates/uzu-engine/src/backends/common/kernel/activation_transform.rs+++ b/crates/uzu-engine/src/backends/common/kernel/activation_transform.rs@@ -1,6 +1,6 @@use crate::{backends::common::{- Allocation, Backend, Encoder, Kernels,+ Backend, BufferMut, BufferRef, CommandBuffer, Kernels,gpu_types::{ActivationTransformOp, HADAMARD_TRANSFORM_BLOCK_SIZE},kernel::{ActivationTransformKernel, matmul::Int8CodeLayout},},@@ -136,64 +136,64 @@ impl<B: Backend> ActivationTransform<B> {/// `input` and `output` must be distinct buffers.pub fn encode_fp(&self,- input: &Allocation<B>,- output: &mut Allocation<B>,- rht_factors: &Allocation<B>,+ input: impl BufferRef<Backend = B>,+ output: impl BufferMut<Backend = B>,+ rht_factors: impl BufferRef<Backend = B>,batch_size: u32,element_count: u32,- encoder: &mut Encoder<B>,+ command_buffer: &mut <B::CommandBuffer as CommandBuffer>::Encoding,) {assert!(self.quantization.is_none() && !self.in_place && !self.has_bias);assert_row_width(element_count);self.kernel.encode(Some(input),Some(output),- None::<&Allocation<B>>,- None::<&mut Allocation<B>>,- None::<&mut Allocation<B>>,- None::<&mut Allocation<B>>,+ None::<&B::GlobalBuffer>,+ None::<&mut B::ScratchBuffer>,+ None::<&mut B::ScratchBuffer>,+ None::<&mut B::ScratchBuffer>,rht_factors,batch_size,element_count,- encoder,+ command_buffer,);}pub fn encode_fp_in_place(&self,- data: &mut Allocation<B>,- rht_factors: &Allocation<B>,- bias: Option<&Allocation<B>>,+ data: impl BufferMut<Backend = B>,+ rht_factors: impl BufferRef<Backend = B>,+ bias: Option<&B::GlobalBuffer>,batch_size: u32,element_count: u32,- encoder: &mut Encoder<B>,+ command_buffer: &mut <B::CommandBuffer as CommandBuffer>::Encoding,) {assert!(self.quantization.is_none() && self.in_place && self.has_bias == bias.is_some());assert_row_width(element_count);self.kernel.encode(- None::<&Allocation<B>>,+ None::<&B::ScratchBuffer>,Some(data),bias,- None::<&mut Allocation<B>>,- None::<&mut Allocation<B>>,- None::<&mut Allocation<B>>,+ None::<&mut B::ScratchBuffer>,+ None::<&mut B::ScratchBuffer>,+ None::<&mut B::ScratchBuffer>,rht_factors,batch_size,element_count,- encoder,+ command_buffer,);}pub fn encode_quantize(&self,- input: &Allocation<B>,- q_out: &mut Allocation<B>,- scales_out: &mut Allocation<B>,- group_sums_out: Option<&mut Allocation<B>>,- rht_factors: &Allocation<B>,+ input: impl BufferRef<Backend = B>,+ q_out: impl BufferMut<Backend = B>,+ scales_out: impl BufferMut<Backend = B>,+ group_sums_out: Option<impl BufferMut<Backend = B>>,+ rht_factors: impl BufferRef<Backend = B>,batch_size: u32,element_count: u32,- encoder: &mut Encoder<B>,+ command_buffer: &mut <B::CommandBuffer as CommandBuffer>::Encoding,) {let quantization = self.quantization.expect("quantized activation transform required");assert_row_width(element_count);@@ -207,15 +207,15 @@ impl<B: Backend> ActivationTransform<B> {}self.kernel.encode(Some(input),- None::<&mut Allocation<B>>,- None::<&Allocation<B>>,+ None::<&mut B::ScratchBuffer>,+ None::<&B::GlobalBuffer>,Some(q_out),Some(scales_out),group_sums_out,rht_factors,batch_size,element_count,- encoder,+ command_buffer,);}}diff --git a/crates/uzu-engine/src/backends/common/kernel/attention.rs b/crates/uzu-engine/src/backends/common/kernel/attention.rsindex 6311c8a29..1ca7225d9 100644--- a/crates/uzu-engine/src/backends/common/kernel/attention.rs+++ b/crates/uzu-engine/src/backends/common/kernel/attention.rs@@ -1,5 +1,5 @@use crate::{- backends::common::{Allocation, Backend, BufferArg, Encoder, Kernels},+ backends::common::{Backend, BufferRef, CommandBuffer, Kernels},data_type::DataType,encodable_block::mixer::attention::KVCacheView,};@@ -12,14 +12,18 @@ pub trait AttentionKernel: Sized + Send + Sync {config: AttentionKernelConfig,) -> Result<Self, <Self::Backend as Backend>::Error>;- fn encode<'a, KT, VT>(+ fn encode(&self,- arguments: AttentionArguments<'a, Self::Backend, KT, VT>,- encoder: &mut Encoder<Self::Backend>,- ) -> Result<Allocation<Self::Backend>, <Self::Backend as Backend>::Error>- where- KT: BufferArg<'a, Self::Backend>,- VT: BufferArg<'a, Self::Backend>;+ arguments: AttentionArguments<+ '_,+ Self::Backend,+ impl BufferRef<Backend = Self::Backend>,+ impl BufferRef<Backend = Self::Backend>,+ impl BufferRef<Backend = Self::Backend>,+ impl BufferRef<Backend = Self::Backend>,+ >,+ command_buffer: &mut <<Self::Backend as Backend>::CommandBuffer as CommandBuffer>::Encoding,+ ) -> Result<<Self::Backend as Backend>::ScratchBuffer, <Self::Backend as Backend>::Error>;}#[derive(Clone, Copy)]@@ -35,12 +39,19 @@ pub struct AttentionKernelConfig {pub data_type: DataType,}-pub struct AttentionArguments<'a, B: Backend, KT: BufferArg<'a, B>, VT: BufferArg<'a, B>> {- pub queries: &'a Allocation<B>,+pub struct AttentionArguments<+ 'a,+ B: Backend,+ QT: BufferRef<Backend = B>,+ TT: BufferRef<Backend = B>,+ KT: BufferRef<Backend = B>,+ VT: BufferRef<Backend = B>,+> {+ pub queries: QT,pub keys: KT,pub values: VT,pub suffix_length: u32,- pub trie: Option<&'a Allocation<B>>,- pub sinks: Option<&'a Allocation<B>>,+ pub trie: Option<TT>,+ pub sinks: Option<&'a B::GlobalBuffer>,pub cache: KVCacheView,}diff --git a/crates/uzu-engine/src/backends/common/kernel/delta_net_chunked_prefill.rs b/crates/uzu-engine/src/backends/common/kernel/delta_net_chunked_prefill.rsindex c303c6be2..5a396f962 100644--- a/crates/uzu-engine/src/backends/common/kernel/delta_net_chunked_prefill.rs+++ b/crates/uzu-engine/src/backends/common/kernel/delta_net_chunked_prefill.rs@@ -1,14 +1,14 @@use crate::{- backends::common::{Allocation, Backend, Encoder, Kernels, kernel::Unsupported},+ backends::common::{Backend, CommandBuffer, Kernels, kernel::Unsupported},data_type::DataType,};pub struct DeltaNetChunkedPrefillArgs<'a, B: Backend> {- pub in_projected: &'a Allocation<B>,- pub a_log: &'a Allocation<B>,- pub dt_bias: &'a Allocation<B>,- pub ssm_state: &'a mut Allocation<B>,- pub delta_output: &'a mut Allocation<B>,+ pub in_projected: &'a B::ScratchBuffer,+ pub a_log: &'a B::GlobalBuffer,+ pub dt_bias: &'a B::GlobalBuffer,+ pub ssm_state: &'a mut B::GlobalBuffer,+ pub delta_output: &'a mut B::ScratchBuffer,pub num_heads: u32,pub num_groups: u32,pub value_head_dim: u32,@@ -34,7 +34,7 @@ pub trait DeltaNetChunkedPrefill: Sized + Send + Sync {fn encode(&self,args: DeltaNetChunkedPrefillArgs<'_, Self::Backend>,- encoder: &mut Encoder<Self::Backend>,+ command_buffer: &mut <<Self::Backend as Backend>::CommandBuffer as CommandBuffer>::Encoding,) -> Result<(), <Self::Backend as Backend>::Error>;}@@ -59,7 +59,7 @@ impl<B: Backend<Kernels: Kernels<DeltaNetChunkedPrefill = Unsupported<B>>>> Deltfn encode(&self,_args: DeltaNetChunkedPrefillArgs<'_, B>,- _encoder: &mut Encoder<B>,+ _command_buffer: &mut <B::CommandBuffer as CommandBuffer>::Encoding,) -> Result<(), B::Error> {match self.never {}}diff --git a/crates/uzu-engine/src/backends/common/kernel/delta_net_tree_verify.rs b/crates/uzu-engine/src/backends/common/kernel/delta_net_tree_verify.rsindex e33a569d8..c4113d1d3 100644--- a/crates/uzu-engine/src/backends/common/kernel/delta_net_tree_verify.rs+++ b/crates/uzu-engine/src/backends/common/kernel/delta_net_tree_verify.rs@@ -1,5 +1,5 @@use crate::{- backends::common::{Allocation, Backend, Encoder, Kernels, kernel::Unsupported},+ backends::common::{Backend, CommandBuffer, Kernels, kernel::Unsupported},encodable_block::mixer::delta_net::tree_verify::{TreeVerifyEncodeArguments, TreeVerifyNewArguments},};@@ -16,8 +16,8 @@ pub trait DeltaNetTreeVerify: Sized + Send + Sync {fn encode(&self,arguments: TreeVerifyEncodeArguments<'_, Self::Backend>,- encoder: &mut Encoder<Self::Backend>,- ) -> Result<Allocation<Self::Backend>, <Self::Backend as Backend>::Error>;+ command_buffer: &mut <<Self::Backend as Backend>::CommandBuffer as CommandBuffer>::Encoding,+ ) -> Result<<Self::Backend as Backend>::ScratchBuffer, <Self::Backend as Backend>::Error>;}impl<B: Backend<Kernels: Kernels<DeltaNetTreeVerify = Unsupported<B>>>> DeltaNetTreeVerify for Unsupported<B> {@@ -37,8 +37,8 @@ impl<B: Backend<Kernels: Kernels<DeltaNetTreeVerify = Unsupported<B>>>> DeltaNetfn encode(&self,_arguments: TreeVerifyEncodeArguments<'_, B>,- _encoder: &mut Encoder<B>,- ) -> Result<Allocation<B>, B::Error> {+ _command_buffer: &mut <B::CommandBuffer as CommandBuffer>::Encoding,+ ) -> Result<B::ScratchBuffer, B::Error> {unreachable!("unsupported DeltaNet tree verifier cannot encode")}}diff --git a/crates/uzu-engine/src/backends/common/kernel/gated_act_mul.rs b/crates/uzu-engine/src/backends/common/kernel/gated_act_mul.rsindex 16f531686..170f60a48 100644--- a/crates/uzu-engine/src/backends/common/kernel/gated_act_mul.rs+++ b/crates/uzu-engine/src/backends/common/kernel/gated_act_mul.rs@@ -2,7 +2,7 @@ use bitflags::bitflags;use crate::{backends::common::{- Allocation, Backend, Encoder, Kernels,+ Backend, BufferMut, BufferRef, CommandBuffer, Kernels,gpu_types::{ActivationType, GatedActMulOp, HADAMARD_TRANSFORM_BLOCK_SIZE},kernel::{ActivationQuantization, GatedActMulKernel},},@@ -100,16 +100,16 @@ impl<B: Backend> GatedActMul<B> {pub fn encode_fp(&self,- act_operand: &Allocation<B>,- value_operand: Option<&Allocation<B>>,- output: &mut Allocation<B>,- hadamard_factors: Option<&Allocation<B>>,+ act_operand: impl BufferRef<Backend = B>,+ value_operand: Option<impl BufferRef<Backend = B>>,+ output: impl BufferMut<Backend = B>,+ hadamard_factors: Option<impl BufferRef<Backend = B>>,gated_dim: u32,batch_dim: u32,value_offset: u32,value_row_stride: u32,act_type: ActivationType,- encoder: &mut Encoder<B>,+ command_buffer: &mut <B::CommandBuffer as CommandBuffer>::Encoding,) {assert!(self.quantization.is_none());assert_eq!(self.options.contains(GatedActMulOptions::INTERLEAVED), value_operand.is_none());@@ -124,9 +124,9 @@ impl<B: Backend> GatedActMul<B> {act_operand,value_operand,Some(output),- None::<&mut Allocation<B>>,- None::<&mut Allocation<B>>,- None::<&mut Allocation<B>>,+ None::<&mut B::ScratchBuffer>,+ None::<&mut B::ScratchBuffer>,+ None::<&mut B::ScratchBuffer>,hadamard_factors,gated_dim,batch_dim,@@ -138,21 +138,21 @@ impl<B: Backend> GatedActMul<B> {gate_clip_max,value_clip_min,value_clip_max,- encoder,+ command_buffer,);}pub fn encode_quantized(&self,- act_operand: &Allocation<B>,- values: &mut Allocation<B>,- scales: &mut Allocation<B>,- group_sums: Option<&mut Allocation<B>>,- hadamard_factors: &Allocation<B>,+ act_operand: impl BufferRef<Backend = B>,+ values: impl BufferMut<Backend = B>,+ scales: impl BufferMut<Backend = B>,+ group_sums: Option<impl BufferMut<Backend = B>>,+ hadamard_factors: impl BufferRef<Backend = B>,gated_dim: u32,batch_dim: u32,act_type: ActivationType,- encoder: &mut Encoder<B>,+ command_buffer: &mut <B::CommandBuffer as CommandBuffer>::Encoding,) {let quantization = self.quantization.expect("quantized gated activation required");assert!(self.options.contains(GatedActMulOptions::INTERLEAVED));@@ -167,8 +167,8 @@ impl<B: Backend> GatedActMul<B> {let (value_clip_min, value_clip_max) = self.settings.value_clipping.into_pair().unzip();self.kernel.encode(act_operand,- None::<&Allocation<B>>,- None::<&mut Allocation<B>>,+ None::<&B::ScratchBuffer>,+ None::<&mut B::ScratchBuffer>,Some(values),Some(scales),group_sums,@@ -183,7 +183,7 @@ impl<B: Backend> GatedActMul<B> {gate_clip_max,value_clip_min,value_clip_max,- encoder,+ command_buffer,);}}diff --git a/crates/uzu-engine/src/backends/common/kernel/matmul/arguments.rs b/crates/uzu-engine/src/backends/common/kernel/matmul/arguments.rsindex 1de408fa2..305dad425 100644--- a/crates/uzu-engine/src/backends/common/kernel/matmul/arguments.rs+++ b/crates/uzu-engine/src/backends/common/kernel/matmul/arguments.rs@@ -1,14 +1,21 @@use super::{d_ops::MatmulDOps, matmul_a::MatmulA, matmul_b::MatmulB};-use crate::backends::common::{Allocation, Backend, BufferArg};+use crate::backends::common::{Backend, BufferMut, BufferRef};-pub struct MatmulArguments<'a, 'b, 'd, B: Backend, TB: BufferArg<'b, B> = &'b Allocation<B>> {- pub a: MatmulA<'a, B>,- pub b: MatmulB<'b, B, TB>,+pub struct MatmulArguments<+ 'd,+ B: Backend,+ TA: BufferRef<Backend = B>,+ TB: BufferRef<Backend = B>,+ TD: BufferMut<Backend = B>,+ TI: BufferRef<Backend = B>,+> {+ pub a: MatmulA<TA>,+ pub b: MatmulB<TB>,pub b_leading_dimension: Option<u32>,pub b_transpose: bool,- pub d: &'d mut Allocation<B>,+ pub d: TD,pub d_transform: MatmulDOps<'d, B>,- pub gather_indices: Option<&'a Allocation<B>>,+ pub gather_indices: Option<TI>,pub m: u32,pub n: u32,pub k: u32,diff --git a/crates/uzu-engine/src/backends/common/kernel/matmul/d_ops.rs b/crates/uzu-engine/src/backends/common/kernel/matmul/d_ops.rsindex 55448769e..9bccbc4d5 100644--- a/crates/uzu-engine/src/backends/common/kernel/matmul/d_ops.rs+++ b/crates/uzu-engine/src/backends/common/kernel/matmul/d_ops.rs@@ -1,10 +1,10 @@-use crate::backends::common::{Allocation, Backend, gpu_types::gemm::GemmDTransform};+use crate::backends::common::{Backend, gpu_types::gemm::GemmDTransform};pub struct MatmulDOps<'a, B: Backend> {pub ab_scale: f32,pub accumulate: bool,- pub bias: Option<&'a Allocation<B>>,- pub rht_factors: Option<&'a Allocation<B>>,+ pub bias: Option<&'a B::GlobalBuffer>,+ pub rht_factors: Option<&'a B::GlobalBuffer>,pub soft_cap: Option<f32>,}diff --git a/crates/uzu-engine/src/backends/common/kernel/matmul/kernel.rs b/crates/uzu-engine/src/backends/common/kernel/matmul/kernel.rsindex 8fe1982ac..217cb7ca3 100644--- a/crates/uzu-engine/src/backends/common/kernel/matmul/kernel.rs+++ b/crates/uzu-engine/src/backends/common/kernel/matmul/kernel.rs@@ -1,6 +1,6 @@use crate::{backends::common::{- Backend, BufferArg, Encoder, Kernels,+ Backend, BufferMut, BufferRef, CommandBuffer, Kernels,kernel::{ActivationQuantization,matmul::{@@ -22,10 +22,17 @@ pub trait MatmulKernel: Sized + Send + Sync {output_data_type: DataType,) -> Result<Self, <Self::Backend as Backend>::Error>;- fn encode<'a, 'b, 'd, TB: BufferArg<'b, Self::Backend>>(+ fn encode(&mut self,- arguments: MatmulArguments<'a, 'b, 'd, Self::Backend, TB>,- encoder: &mut Encoder<Self::Backend>,+ arguments: MatmulArguments<+ '_,+ Self::Backend,+ impl BufferRef<Backend = Self::Backend>,+ impl BufferRef<Backend = Self::Backend>,+ impl BufferMut<Backend = Self::Backend>,+ impl BufferRef<Backend = Self::Backend>,+ >,+ command_buffer: &mut <<Self::Backend as Backend>::CommandBuffer as CommandBuffer>::Encoding,) -> Result<(), <Self::Backend as Backend>::Error>;fn select_activation_quantization(diff --git a/crates/uzu-engine/src/backends/common/kernel/matmul/matmul_a.rs b/crates/uzu-engine/src/backends/common/kernel/matmul/matmul_a.rsindex d93c02b0e..8e0849676 100644--- a/crates/uzu-engine/src/backends/common/kernel/matmul/matmul_a.rs+++ b/crates/uzu-engine/src/backends/common/kernel/matmul/matmul_a.rs@@ -1,6 +1,6 @@use std::mem::size_of;-use crate::backends::common::{Allocation, Backend, gpu_types::gemm::GemmAPrologueKind};+use crate::backends::common::{BufferRef, gpu_types::gemm::GemmAPrologueKind};#[derive(Clone, Copy, PartialEq)]pub enum Int8CodeLayout {@@ -46,21 +46,21 @@ impl Int8CodeLayout {}}-pub enum MatmulA<'a, B: Backend> {+pub enum MatmulA<T: BufferRef> {FullPrecision {- values: &'a Allocation<B>,+ values: T,offset: usize,},Int8Symmetric {- values: &'a Allocation<B>,- scales: &'a Allocation<B>,- group_sums: Option<&'a Allocation<B>>,+ values: T,+ scales: T,+ group_sums: Option<T>,scale_group_size: u32,code_layout: Int8CodeLayout,},}-impl<'a, B: Backend> MatmulA<'a, B> {+impl<T: BufferRef> MatmulA<T> {pub fn prologue_kind(&self) -> GemmAPrologueKind {match self {Self::FullPrecision {diff --git a/crates/uzu-engine/src/backends/common/kernel/matmul/matmul_b.rs b/crates/uzu-engine/src/backends/common/kernel/matmul/matmul_b.rsindex 6d772b29a..24bb89d24 100644--- a/crates/uzu-engine/src/backends/common/kernel/matmul/matmul_b.rs+++ b/crates/uzu-engine/src/backends/common/kernel/matmul/matmul_b.rs@@ -1,23 +1,23 @@use super::{QuantParams, QuantParamsLayout};use crate::{backends::common::{- Allocation, Backend, BufferArg,+ BufferRef,gpu_types::{QuantizationMode, gemm::GemmBPrologueKind},},data_type::DataType,};-pub enum MatmulB<'a, B: Backend, TB: BufferArg<'a, B> = &'a Allocation<B>> {+pub enum MatmulB<TB: BufferRef> {FullPrecision {b: TB,},- Quantized(QuantizedB<'a, B>),+ Quantized(QuantizedB<TB>),}-pub struct QuantizedB<'a, B: Backend> {- pub codes: &'a Allocation<B>,- pub scales: &'a Allocation<B>,- pub correction: QuantizedCorrection<&'a Allocation<B>>,+pub struct QuantizedB<TB: BufferRef> {+ pub codes: TB,+ pub scales: TB,+ pub correction: QuantizedCorrection<TB>,pub params: QuantParams,pub mode: QuantizationMode,pub group_size: u32,@@ -55,7 +55,7 @@ impl<T> QuantizedCorrection<T> {}}-impl<'a, B: Backend> QuantizedB<'a, B> {+impl<TB: BufferRef> QuantizedB<TB> {pub fn bits(&self) -> u32 {DataType::from(self.mode).size_in_bits() as u32}@@ -68,11 +68,11 @@ impl<'a, B: Backend> QuantizedB<'a, B> {}}- pub fn biases(&self) -> Option<&'a Allocation<B>> {+ pub fn biases(&self) -> Option<TB> {self.correction.biases().copied()}- pub fn zero_points(&self) -> Option<&'a Allocation<B>> {+ pub fn zero_points(&self) -> Option<TB> {self.correction.zero_points().copied()}@@ -81,8 +81,8 @@ impl<'a, B: Backend> QuantizedB<'a, B> {}}-impl<'a, B: Backend, TB: BufferArg<'a, B>> MatmulB<'a, B, TB> {- pub fn quantized(&self) -> Option<&QuantizedB<'a, B>> {+impl<TB: BufferRef> MatmulB<TB> {+ pub fn quantized(&self) -> Option<&QuantizedB<TB>> {match self {Self::FullPrecision {..diff --git a/crates/uzu-engine/src/backends/common/kernel/matmul/routing.rs b/crates/uzu-engine/src/backends/common/kernel/matmul/routing.rsindex 640d77644..658efa276 100644--- a/crates/uzu-engine/src/backends/common/kernel/matmul/routing.rs+++ b/crates/uzu-engine/src/backends/common/kernel/matmul/routing.rs@@ -1,6 +1,6 @@use super::{MatmulA, MatmulArguments, QuantParamsLayout};use crate::backends::common::{- Backend, BufferArg,+ Backend, BufferMut, BufferRef,gpu_types::gemm::{GemmBPrologueKind, GemmDTransform},};@@ -28,8 +28,15 @@ pub struct MatmulShape {}impl MatmulShape {- pub fn from_arguments<'a, 'b, 'd, B: Backend, TB: BufferArg<'b, B>>(- arguments: &MatmulArguments<'a, 'b, 'd, B, TB>+ pub fn from_arguments<B: Backend>(+ arguments: &MatmulArguments<+ '_,+ B,+ impl BufferRef<Backend = B>,+ impl BufferRef<Backend = B>,+ impl BufferMut<Backend = B>,+ impl BufferRef<Backend = B>,+ >) -> Self {Self {m: arguments.m,diff --git a/crates/uzu-engine/src/backends/common/kernel/radix_top_k_small.rs b/crates/uzu-engine/src/backends/common/kernel/radix_top_k_small.rsindex 07045138b..ace5351ce 100644--- a/crates/uzu-engine/src/backends/common/kernel/radix_top_k_small.rs+++ b/crates/uzu-engine/src/backends/common/kernel/radix_top_k_small.rs@@ -1,4 +1,4 @@-use crate::backends::common::{Allocation, Backend, Encoder, Kernels};+use crate::backends::common::{Backend, BufferMut, BufferRef, CommandBuffer, Kernels};pub const MAX_K: u32 = 512;@@ -12,11 +12,11 @@ pub trait RadixTopKSmall: Sized + Send + Sync {fn encode(&self,- input: &Allocation<Self::Backend>,- output_ids: &mut Allocation<Self::Backend>,- output_scores: &mut Allocation<Self::Backend>,+ input: impl BufferRef<Backend = Self::Backend>,+ output_ids: impl BufferMut<Backend = Self::Backend>,+ output_scores: impl BufferMut<Backend = Self::Backend>,rows: u32,k: u32,- encoder: &mut Encoder<Self::Backend>,+ command_buffer: &mut <<Self::Backend as Backend>::CommandBuffer as CommandBuffer>::Encoding,) -> Result<(), <Self::Backend as Backend>::Error>;}diff --git a/crates/uzu-engine/src/backends/common/mod.rs b/crates/uzu-engine/src/backends/common/mod.rsindex d3b57f26d..a07c947d6 100644--- a/crates/uzu-engine/src/backends/common/mod.rs+++ b/crates/uzu-engine/src/backends/common/mod.rs@@ -1,29 +1,25 @@-mod allocator;+pub(super) mod allocator;mod backend;mod buffer;mod command_buffer;mod context;mod device_capabilities;-mod encoder;pub mod gpu_types;-mod hazard_tracker;pub mod kernel;-pub use allocator::{Allocation, AllocationPool, AllocationType, Allocator};pub use backend::Backend;pub use buffer::{- Buffer, BufferGpuAddressRangeExt,- arg::{BufferArg, BufferArgMut},- dense::DenseBuffer,- range::{AsBufferRangeMut, AsBufferRangeRef, BufferRangeMut, BufferRangeRef},- sparse::{SparseBuffer, SparseBufferExt},+ Buffer,+ constant::ConstantBuffer,+ cpu_accessible::BufferCpuAccessible,+ global::GlobalBuffer,+ reference::{BufferMut, BufferRef, Subbuffer},+ scratch::ScratchBuffer,+ sparse::SparseBuffer,};pub use command_buffer::{- AccessFlags, CommandBuffer, CommandBufferCompleted, CommandBufferEncoding, CommandBufferExecutable,- CommandBufferInitial, CommandBufferPending,+ CommandBuffer, CommandBufferCompleted, CommandBufferEncoding, CommandBufferExecutable, CommandBufferPending,};pub use context::Context;pub use device_capabilities::DeviceCapabilities;-pub use encoder::{Completed, Encoder, Executable, Pending};-pub use hazard_tracker::Access;pub use kernel::Kernels;diff --git a/crates/uzu-engine/src/backends/cpu/backend.rs b/crates/uzu-engine/src/backends/cpu/backend.rsindex b039f13f3..22ed5b72e 100644--- a/crates/uzu-engine/src/backends/cpu/backend.rs+++ b/crates/uzu-engine/src/backends/cpu/backend.rs@@ -1,8 +1,19 @@-use super::{- command_buffer::CpuCommandBuffer, context::CpuContext, dense_buffer::CpuBuffer, error::CpuError,- kernel::CpuKernels, sparse::CpuSparseBuffer,+use crate::backends::{+ common::{+ Backend,+ allocator::{+ bump::BumpAllocation,+ pool::{PoolAllocation, PoolAllocator},+ },+ },+ cpu::{+ buffer::{dense::CpuBuffer, sparse::CpuSparseBuffer},+ command_buffer::CpuCommandBuffer,+ context::CpuContext,+ error::CpuError,+ kernel::CpuKernels,+ },};-use crate::backends::common::Backend;#[derive(Debug, Clone)]pub struct Cpu;@@ -10,14 +21,13 @@ pub struct Cpu;impl Backend for Cpu {type Context = CpuContext;type CommandBuffer = CpuCommandBuffer;- type DenseBuffer = CpuBuffer;+ type GlobalBuffer = CpuBuffer;+ type ConstantBuffer = BumpAllocation<Self::GlobalBuffer>;+ type ScratchBuffer = PoolAllocation<Self::GlobalBuffer>;type SparseBuffer = CpuSparseBuffer;+ type AllocationPool = PoolAllocator<Self::GlobalBuffer>;type Kernels = CpuKernels;type Error = CpuError;const NAME: &'static str = "cpu";- const MIN_ALLOCATION_ALIGNMENT: usize = 4;- const MAX_ALLOCATION_ALIGNMENT: usize = 64;- const ALLOCATION_GRANULARITY: usize = 8 * 1024 * 1024;- const MAX_INLINE_BYTES: usize = usize::MAX;}diff --git a/crates/uzu-engine/src/backends/cpu/buffer.rs b/crates/uzu-engine/src/backends/cpu/buffer.rsdeleted file mode 100644index ff19e3008..000000000--- a/crates/uzu-engine/src/backends/cpu/buffer.rs+++ /dev/null@@ -1,17 +0,0 @@-use std::any::Any;--use crate::backends::{- common::{Backend, Buffer},- cpu::{Cpu, dense_buffer::CpuBuffer},-};--impl dyn Buffer<Backend = Cpu> {- pub fn downcast(&self) -> &CpuBuffer {- let buffer = self as &dyn Any;- if let Some(buffer) = buffer.downcast_ref::<<Cpu as Backend>::DenseBuffer>() {- buffer- } else {- unreachable!("Unsupported Cpu buffer type")- }- }-}diff --git a/crates/uzu-engine/src/backends/cpu/buffer/constant.rs b/crates/uzu-engine/src/backends/cpu/buffer/constant.rsnew file mode 100644index 000000000..f91ead2f3--- /dev/null+++ b/crates/uzu-engine/src/backends/cpu/buffer/constant.rs@@ -0,0 +1,34 @@+use std::{fmt::Debug, os::raw::c_void, ptr::NonNull};++use crate::backends::{+ common::{Backend, Buffer, BufferCpuAccessible, ConstantBuffer, allocator::bump::BumpAllocation},+ cpu::Cpu,+};++impl Buffer for BumpAllocation<<Cpu as Backend>::GlobalBuffer> {+ type Backend = Cpu;++ fn size(&self) -> usize {+ self.range().iter().len()+ }+}++impl BufferCpuAccessible for BumpAllocation<<Cpu as Backend>::GlobalBuffer> {+ fn cpu_ptr(&self) -> NonNull<c_void> {+ unsafe { self.page().cpu_ptr().byte_add(self.range().start) }+ }+}++impl ConstantBuffer for BumpAllocation<<Cpu as Backend>::GlobalBuffer> {}++impl Debug for BumpAllocation<<Cpu as Backend>::GlobalBuffer> {+ fn fmt(+ &self,+ f: &mut std::fmt::Formatter<'_>,+ ) -> std::fmt::Result {+ f.debug_struct("BumpAllocation<Cpu::GlobalBuffer>")+ .field("page", &self.page())+ .field("range", &self.range())+ .finish_non_exhaustive()+ }+}diff --git a/crates/uzu-engine/src/backends/cpu/buffer/dense.rs b/crates/uzu-engine/src/backends/cpu/buffer/dense.rsnew file mode 100644index 000000000..0ba3445ed--- /dev/null+++ b/crates/uzu-engine/src/backends/cpu/buffer/dense.rs@@ -0,0 +1,54 @@+use std::{+ alloc::{Layout, alloc, dealloc, handle_alloc_error},+ os::raw::c_void,+ ptr::NonNull,+};++use crate::backends::{+ common::{Buffer, BufferCpuAccessible, GlobalBuffer},+ cpu::Cpu,+};++#[derive(Debug)]+pub struct CpuBuffer {+ ptr: NonNull<c_void>,+ layout: Layout,+}++impl CpuBuffer {+ pub(in crate::backends::cpu) fn new(size: usize) -> Self {+ assert!(size > 0, "CPU buffer size must be nonzero");+ let layout = Layout::from_size_align(size, 64).expect("invalid CPU buffer layout");+ let ptr = NonNull::new(unsafe { alloc(layout) }).unwrap_or_else(|| handle_alloc_error(layout)).cast();+ Self {+ ptr,+ layout,+ }+ }+}++// The allocation has a stable address; callers synchronize access through buffer borrows and command buffers.+unsafe impl Send for CpuBuffer {}+unsafe impl Sync for CpuBuffer {}++impl Drop for CpuBuffer {+ fn drop(&mut self) {+ unsafe { dealloc(self.ptr.as_ptr().cast(), self.layout) };+ }+}++impl Buffer for CpuBuffer {+ type Backend = Cpu;++ fn size(&self) -> usize {+ self.layout.size()+ }+}++impl BufferCpuAccessible for CpuBuffer {+ fn cpu_ptr(&self) -> NonNull<c_void> {+ self.ptr+ }+}++impl GlobalBuffer for CpuBuffer {}diff --git a/crates/uzu-engine/src/backends/cpu/buffer/mod.rs b/crates/uzu-engine/src/backends/cpu/buffer/mod.rsnew file mode 100644index 000000000..a462662fa--- /dev/null+++ b/crates/uzu-engine/src/backends/cpu/buffer/mod.rs@@ -0,0 +1,30 @@+use std::{os::raw::c_void, ptr::NonNull};++use crate::{+ backends::{+ common::{Backend, Buffer, BufferCpuAccessible},+ cpu::Cpu,+ },+ utils::downcast::downcast_ref,+};++pub mod constant;+pub mod dense;+pub mod scratch;+pub mod sparse;++pub(super) trait CpuBufferExt: Buffer<Backend = Cpu> {+ fn cpu_address(&self) -> NonNull<c_void> {+ if let Some(buffer) = downcast_ref::<<Cpu as Backend>::GlobalBuffer>(self) {+ buffer.cpu_ptr()+ } else if let Some(buffer) = downcast_ref::<<Cpu as Backend>::ConstantBuffer>(self) {+ buffer.cpu_ptr()+ } else if let Some(buffer) = downcast_ref::<<Cpu as Backend>::ScratchBuffer>(self) {+ buffer.cpu_ptr()+ } else {+ unreachable!("Unsupported Cpu buffer type")+ }+ }+}++impl<T: Buffer<Backend = Cpu> + ?Sized> CpuBufferExt for T {}diff --git a/crates/uzu-engine/src/backends/cpu/buffer/scratch.rs b/crates/uzu-engine/src/backends/cpu/buffer/scratch.rsnew file mode 100644index 000000000..1592d6391--- /dev/null+++ b/crates/uzu-engine/src/backends/cpu/buffer/scratch.rs@@ -0,0 +1,34 @@+use std::{fmt::Debug, os::raw::c_void, ptr::NonNull};++use crate::backends::{+ common::{Backend, Buffer, BufferCpuAccessible, ScratchBuffer, allocator::pool::PoolAllocation},+ cpu::Cpu,+};++impl Buffer for PoolAllocation<<Cpu as Backend>::GlobalBuffer> {+ type Backend = Cpu;++ fn size(&self) -> usize {+ self.range().iter().len()+ }+}++impl BufferCpuAccessible for PoolAllocation<<Cpu as Backend>::GlobalBuffer> {+ fn cpu_ptr(&self) -> NonNull<c_void> {+ unsafe { self.page().cpu_ptr().byte_add(self.range().start) }+ }+}++impl ScratchBuffer for PoolAllocation<<Cpu as Backend>::GlobalBuffer> {}++impl Debug for PoolAllocation<<Cpu as Backend>::GlobalBuffer> {+ fn fmt(+ &self,+ f: &mut std::fmt::Formatter<'_>,+ ) -> std::fmt::Result {+ f.debug_struct("PoolAllocation<Cpu::GlobalBuffer>")+ .field("page", &self.page())+ .field("range", &self.range())+ .finish_non_exhaustive()+ }+}diff --git a/crates/uzu-engine/src/backends/cpu/sparse/mod.rs b/crates/uzu-engine/src/backends/cpu/buffer/sparse/mod.rssimilarity index 100%rename from crates/uzu-engine/src/backends/cpu/sparse/mod.rsrename to crates/uzu-engine/src/backends/cpu/buffer/sparse/mod.rsdiff --git a/crates/uzu-engine/src/backends/cpu/sparse/sparse_buffer.rs b/crates/uzu-engine/src/backends/cpu/buffer/sparse/sparse_buffer.rssimilarity index 83%rename from crates/uzu-engine/src/backends/cpu/sparse/sparse_buffer.rsrename to crates/uzu-engine/src/backends/cpu/buffer/sparse/sparse_buffer.rsindex 5b0a4da9e..ef9e0c75d 100644--- a/crates/uzu-engine/src/backends/cpu/sparse/sparse_buffer.rs+++ b/crates/uzu-engine/src/backends/cpu/buffer/sparse/sparse_buffer.rs@@ -1,4 +1,4 @@-use std::ops::Range;+use std::range::Range;use crate::backends::{common::{Backend, Buffer, SparseBuffer},@@ -11,10 +11,6 @@ pub struct CpuSparseBuffer {}impl Buffer for CpuSparseBuffer {type Backend = Cpu;- fn gpu_ptr(&self) -> usize {- todo!()- }-fn size(&self) -> usize {todo!()}@@ -24,7 +20,7 @@ impl SparseBuffer for CpuSparseBuffer {fn map(&mut self,_context: &<Self::Backend as Backend>::Context,- _pages: &Range<usize>,+ _pages: impl Into<Range<usize>>,) -> Result<(), <Self::Backend as Backend>::Error> {todo!()}@@ -32,7 +28,7 @@ impl SparseBuffer for CpuSparseBuffer {fn unmap(&mut self,_context: &<Self::Backend as Backend>::Context,- _pages: &Range<usize>,+ _pages: impl Into<Range<usize>>,) -> Result<(), <Self::Backend as Backend>::Error> {todo!()}diff --git a/crates/uzu-engine/src/backends/cpu/command_buffer.rs b/crates/uzu-engine/src/backends/cpu/command_buffer.rsindex f04581dd9..62ba458aa 100644--- a/crates/uzu-engine/src/backends/cpu/command_buffer.rs+++ b/crates/uzu-engine/src/backends/cpu/command_buffer.rs@@ -1,15 +1,20 @@use std::{- sync::mpsc,+ sync::{Arc, mpsc},time::{Duration, Instant},};use crate::{backends::{common::{- AccessFlags, Buffer, BufferRangeMut, BufferRangeRef, CommandBuffer, CommandBufferCompleted,- CommandBufferEncoding, CommandBufferExecutable, CommandBufferInitial, CommandBufferPending,+ Backend, BufferMut, BufferRef, CommandBuffer, CommandBufferCompleted, CommandBufferEncoding,+ CommandBufferExecutable, CommandBufferPending, allocator::bump::BumpAllocator,+ },+ cpu::{+ Cpu,+ buffer::{CpuBufferExt, dense::CpuBuffer},+ context::CpuContext,+ error::CpuError,},- cpu::{Cpu, error::CpuError},},utils::pointers::{SendPtr, SendPtrMut},};@@ -19,44 +24,33 @@ pub struct CpuCommandBuffer;impl CommandBuffer for CpuCommandBuffer {type Backend = Cpu;- type Initial = CpuCommandBufferInitial;type Encoding = CpuCommandBufferEncoding;type Executable = CpuCommandBufferExecutable;type Pending = CpuCommandBufferPending;type Completed = CpuCommandBufferCompleted;}-pub struct CpuCommandBufferInitial {- command_queue: mpsc::Sender<Box<dyn FnOnce() + Send>>,-}--impl CpuCommandBufferInitial {- pub fn new(command_queue: mpsc::Sender<Box<dyn FnOnce() + Send>>) -> CpuCommandBufferInitial {- CpuCommandBufferInitial {- command_queue,- }- }+pub struct CpuCommandBufferEncoding {+ commands: Vec<Box<dyn FnOnce() + Send>>,+ constant_allocator: BumpAllocator<<Cpu as Backend>::GlobalBuffer>,+ allocation_pool: Arc<<Cpu as Backend>::AllocationPool>,+ context: Arc<CpuContext>,}-impl CommandBufferInitial for CpuCommandBufferInitial {- type CommandBuffer = CpuCommandBuffer;-- fn start_encoding(self) -> CpuCommandBufferEncoding {+impl CpuCommandBufferEncoding {+ pub fn new(+ constant_allocator: BumpAllocator<<Cpu as Backend>::GlobalBuffer>,+ allocation_pool: Arc<<Cpu as Backend>::AllocationPool>,+ context: Arc<CpuContext>,+ ) -> CpuCommandBufferEncoding {CpuCommandBufferEncoding {- command_queue: self.command_queue,commands: Vec::new(),- completion_handlers: Vec::new(),+ constant_allocator,+ allocation_pool,+ context,}}-}--pub struct CpuCommandBufferEncoding {- command_queue: mpsc::Sender<Box<dyn FnOnce() + Send>>,- commands: Vec<Box<dyn FnOnce() + Send>>,- completion_handlers: Vec<Box<dyn FnOnce(Result<&CpuCommandBufferCompleted, CpuError>) + Send + 'static>>,-}-impl CpuCommandBufferEncoding {pub fn push_command(&mut self,command: impl FnOnce() + Send + 'static,@@ -68,48 +62,54 @@ impl CpuCommandBufferEncoding {impl CommandBufferEncoding for CpuCommandBufferEncoding {type CommandBuffer = CpuCommandBuffer;- fn encode_copy<Src: Buffer<Backend = Cpu>, Dst: Buffer<Backend = Cpu>>(+ fn context(&self) -> &CpuContext {+ &self.context+ }++ fn allocate_constant(&mut self,- src: BufferRangeRef<Src>,- dst: BufferRangeMut<Dst>,- ) {- let src_range = src.range();- let dst_range = dst.range();- assert_eq!(src_range.len(), dst_range.len());+ size: usize,+ ) -> Result<<Cpu as Backend>::ConstantBuffer, CpuError> {+ self.constant_allocator.allocate(size, |size| Ok(CpuBuffer::new(size)))+ }- let src_buffer = (src.buffer() as &dyn Buffer<Backend = Cpu>).downcast();- let src_ptr = SendPtr(unsafe { (&*src_buffer.get()).as_ptr().add(src_range.start) });+ fn allocate_scratch(+ &mut self,+ size: usize,+ ) -> Result<<Cpu as Backend>::ScratchBuffer, CpuError> {+ self.allocation_pool.allocate(size, |size| Ok(CpuBuffer::new(size)))+ }++ fn encode_copy(+ &mut self,+ src: impl BufferRef<Backend = Cpu>,+ dst: impl BufferMut<Backend = Cpu>,+ ) {+ let (src, src_range) = src.parts();+ let (dst, dst_range) = dst.parts();+ assert_eq!(src_range.iter().len(), dst_range.iter().len());- let dst_buffer = (dst.buffer() as &dyn Buffer<Backend = Cpu>).downcast();- let dst_ptr = SendPtrMut(unsafe { (&mut *dst_buffer.get()).as_mut_ptr().add(dst_range.start) });+ let src_ptr = SendPtr(unsafe { src.cpu_address().as_ptr().cast::<u8>().add(src_range.start) });+ let dst_ptr = SendPtrMut(unsafe { dst.cpu_address().as_ptr().cast::<u8>().add(dst_range.start) });self.push_command(move || unsafe {- std::ptr::copy(src_ptr.as_ptr(), dst_ptr.as_ptr(), src_range.len());+ std::ptr::copy(src_ptr.as_ptr(), dst_ptr.as_ptr(), src_range.iter().len());});}- fn encode_fill<Dst: Buffer<Backend = Cpu>>(+ fn encode_fill(&mut self,- dst: BufferRangeMut<Dst>,+ dst: impl BufferMut<Backend = Cpu>,value: u8,) {- let range = dst.range();- let size = range.end - range.start;- let dst = SendPtrMut(unsafe {- (&mut *(dst.buffer() as &dyn Buffer<Backend = Cpu>).downcast().get()).as_mut_ptr().add(range.start)- });+ let (dst, range) = dst.parts();+ let size = range.iter().len();+ let dst = SendPtrMut(unsafe { dst.cpu_address().as_ptr().cast::<u8>().add(range.start) });self.push_command(move || unsafe {dst.as_ptr().write_bytes(value, size);});}- fn encode_barrier(- &mut self,- _after: AccessFlags,- _before: AccessFlags,- ) {- }-fn push_debug_group(&mut self,_name: &str,@@ -119,18 +119,21 @@ impl CommandBufferEncoding for CpuCommandBufferEncoding {fn pop_debug_group(&mut self) {}fn end_encoding(self) -> CpuCommandBufferExecutable {+ assert!(self.constant_allocator.is_done(), "attempted to end encoding while constants are still alive");CpuCommandBufferExecutable {- command_queue: self.command_queue,commands: self.commands,- completion_handlers: self.completion_handlers,+ constant_allocator: self.constant_allocator,+ allocation_pool: self.allocation_pool,+ context: self.context,}}}pub struct CpuCommandBufferExecutable {- command_queue: mpsc::Sender<Box<dyn FnOnce() + Send>>,commands: Vec<Box<dyn FnOnce() + Send>>,- completion_handlers: Vec<Box<dyn FnOnce(Result<&CpuCommandBufferCompleted, CpuError>) + Send + 'static>>,+ constant_allocator: BumpAllocator<<Cpu as Backend>::GlobalBuffer>,+ allocation_pool: Arc<<Cpu as Backend>::AllocationPool>,+ context: Arc<CpuContext>,}impl CommandBufferExecutable for CpuCommandBufferExecutable {@@ -138,8 +141,10 @@ impl CommandBufferExecutable for CpuCommandBufferExecutable {fn submit(self) -> CpuCommandBufferPending {let (return_sender, return_receiver) = mpsc::channel();+ let allocation_pool = self.allocation_pool.clone();- self.command_queue+ self.context+ .command_queue.send(Box::new(move || {let start = Instant::now();@@ -151,24 +156,24 @@ impl CommandBufferExecutable for CpuCommandBufferExecutable {let completed = CpuCommandBufferCompleted {gpu_execution_time,+ _allocation_pool: self.allocation_pool,};- for handler in self.completion_handlers {- handler(Ok(&completed))- }-let _ = return_sender.send(completed);+ drop(self.constant_allocator);})).unwrap();CpuCommandBufferPending {return_receiver,+ _allocation_pool: allocation_pool,}}}pub struct CpuCommandBufferPending {return_receiver: mpsc::Receiver<CpuCommandBufferCompleted>,+ _allocation_pool: Arc<<Cpu as Backend>::AllocationPool>,}impl CommandBufferPending for CpuCommandBufferPending {@@ -181,6 +186,7 @@ impl CommandBufferPending for CpuCommandBufferPending {pub struct CpuCommandBufferCompleted {gpu_execution_time: Duration,+ _allocation_pool: Arc<<Cpu as Backend>::AllocationPool>,}impl CommandBufferCompleted for CpuCommandBufferCompleted {diff --git a/crates/uzu-engine/src/backends/cpu/context.rs b/crates/uzu-engine/src/backends/cpu/context.rsindex 6519d6512..9f923ece7 100644--- a/crates/uzu-engine/src/backends/cpu/context.rs+++ b/crates/uzu-engine/src/backends/cpu/context.rs@@ -1,17 +1,20 @@use std::{path::Path,- sync::{Arc, mpsc},+ sync::{Arc, Weak, mpsc},thread,};use crate::backends::{- common::{Allocation, AllocationPool, AllocationType, Allocator, Backend, Context, DeviceCapabilities},- cpu::{Cpu, command_buffer::CpuCommandBufferInitial, dense_buffer::CpuBuffer, error::CpuError},+ common::{+ Backend, Context, DeviceCapabilities,+ allocator::{bump::BumpAllocator, pool::PoolAllocator},+ },+ cpu::{Cpu, buffer::dense::CpuBuffer, command_buffer::CpuCommandBufferEncoding, error::CpuError},};pub struct CpuContext {- allocator: Arc<Allocator<Cpu>>,- command_queue: mpsc::Sender<Box<dyn FnOnce() + Send>>,+ pub(super) command_queue: mpsc::Sender<Box<dyn FnOnce() + Send>>,+ weak_self: Weak<CpuContext>,}impl Context for CpuContext {@@ -27,8 +30,8 @@ impl Context for CpuContext {});Ok(Arc::new_cyclic(|weak_self| CpuContext {- allocator: Allocator::new(weak_self.clone()),command_queue: command_queue_sender,+ weak_self: weak_self.clone(),}))}@@ -36,33 +39,21 @@ impl Context for CpuContext {None}- fn create_buffer(+ fn create_command_buffer(&self,- size: usize,- ) -> Result<CpuBuffer, CpuError> {- Ok(CpuBuffer::new(size))+ _name: Option<&str>,+ allocation_pool: Option<Arc<<Cpu as Backend>::AllocationPool>>,+ ) -> Result<CpuCommandBufferEncoding, CpuError> {+ let constant_allocator = BumpAllocator::new(256 * 1024);+ let allocation_pool = allocation_pool.unwrap_or_else(|| self.create_allocation_pool());+ Ok(CpuCommandBufferEncoding::new(constant_allocator, allocation_pool, self.weak_self.upgrade().unwrap()))}- fn create_allocation(+ fn create_buffer(&self,size: usize,- allocation_type: AllocationType<Cpu>,- ) -> Result<Allocation<Cpu>, CpuError> {- self.allocator.allocate(size, allocation_type)- }-- fn create_allocation_pool(- &self,- reusable: bool,- ) -> AllocationPool<Cpu> {- self.allocator.create_pool(reusable)- }-- fn create_command_buffer(- &self,- _name: Option<&str>,- ) -> Result<CpuCommandBufferInitial, CpuError> {- Ok(CpuCommandBufferInitial::new(self.command_queue.clone()))+ ) -> Result<<Cpu as Backend>::GlobalBuffer, CpuError> {+ Ok(CpuBuffer::new(size))}fn create_sparse_buffer(@@ -72,6 +63,10 @@ impl Context for CpuContext {Err(CpuError::NotSupported)}+ fn create_allocation_pool(&self) -> Arc<<Cpu as Backend>::AllocationPool> {+ PoolAllocator::new()+ }+fn peak_memory_usage(&self) -> Option<usize> {None}diff --git a/crates/uzu-engine/src/backends/cpu/dense_buffer.rs b/crates/uzu-engine/src/backends/cpu/dense_buffer.rsdeleted file mode 100644index 3c4154c5d..000000000--- a/crates/uzu-engine/src/backends/cpu/dense_buffer.rs+++ /dev/null@@ -1,42 +0,0 @@-use std::{cell::UnsafeCell, os::raw::c_void, pin::Pin, ptr::NonNull};--use super::Cpu;-use crate::backends::common::{Buffer, DenseBuffer};--#[derive(Debug)]-pub struct CpuBuffer(pub(crate) UnsafeCell<Pin<Box<[u8]>>>);--/// SAFETY: contents are accessed through raw pointers with manual-/// synchronization (command submission order, explicit submit/wait).-/// `Send`/`Sync` assert the buffer can be moved and owned across-/// threads, not that individual accesses are race-free.-unsafe impl Send for CpuBuffer {}-unsafe impl Sync for CpuBuffer {}--impl CpuBuffer {- pub fn new(size: usize) -> Self {- Self(UnsafeCell::new(Pin::new(vec![0; size].into_boxed_slice())))- }-- pub(crate) fn get(&self) -> *mut Pin<Box<[u8]>> {- self.0.get()- }-}--impl Buffer for CpuBuffer {- type Backend = Cpu;-- fn gpu_ptr(&self) -> usize {- unsafe { &*self.0.get() }.as_ptr().addr()- }-- fn size(&self) -> usize {- unsafe { &*self.0.get() }.len()- }-}--impl DenseBuffer for CpuBuffer {- fn cpu_ptr(&self) -> NonNull<c_void> {- unsafe { NonNull::new_unchecked((&*self.0.get()).as_ptr() as *mut c_void) }- }-}diff --git a/crates/uzu-engine/src/backends/cpu/kernel/attention/attention_prepare.rs b/crates/uzu-engine/src/backends/cpu/kernel/attention/attention_prepare.rsindex 8c1ab4d7f..be16009fd 100644--- a/crates/uzu-engine/src/backends/cpu/kernel/attention/attention_prepare.rs+++ b/crates/uzu-engine/src/backends/cpu/kernel/attention/attention_prepare.rs@@ -4,10 +4,10 @@ use uzu_engine_macros::kernel;use crate::array::ArrayElement;-fn apply_rope<ElementT: ArrayElement + Float, RopeT: ArrayElement + Float>(+fn apply_rope<ElementT: ArrayElement + Float>(head: *const ElementT,- cosines: *const RopeT,- sines: *const RopeT,+ cosines: *const (impl ArrayElement + Float),+ sines: *const (impl ArrayElement + Float),batch_idx: usize,head_dim_idx: usize,rope_dim: usize,diff --git a/crates/uzu-engine/src/backends/cpu/kernel/attention/mod.rs b/crates/uzu-engine/src/backends/cpu/kernel/attention/mod.rsindex dc9d18668..18ad128b4 100644--- a/crates/uzu-engine/src/backends/cpu/kernel/attention/mod.rs+++ b/crates/uzu-engine/src/backends/cpu/kernel/attention/mod.rs@@ -1,3 +1,5 @@+use crate::backends::common::Backend;+pub mod ancestor_attention;pub mod attention_prepare;pub mod attention_single_pass;@@ -9,10 +11,10 @@ mod mask;use crate::backends::{common::{- Allocation, BufferArg, Encoder,+ BufferRef, CommandBufferEncoding,kernel::{AttentionArguments, AttentionKernel, AttentionKernelConfig, AttentionSinglePassKernel},},- cpu::{Cpu, context::CpuContext, error::CpuError},+ cpu::{Cpu, command_buffer::CpuCommandBufferEncoding, context::CpuContext, error::CpuError},};pub struct AttentionCpuKernel {@@ -31,23 +33,26 @@ impl AttentionKernel for AttentionCpuKernel {})}- fn encode<'a, KT, VT>(+ fn encode(&self,- arguments: AttentionArguments<'a, Cpu, KT, VT>,- encoder: &mut Encoder<Cpu>,- ) -> Result<Allocation<Cpu>, CpuError>- where- KT: BufferArg<'a, Cpu>,- VT: BufferArg<'a, Cpu>,- {+ arguments: AttentionArguments<+ '_,+ Cpu,+ impl BufferRef<Backend = Cpu>,+ impl BufferRef<Backend = Cpu>,+ impl BufferRef<Backend = Cpu>,+ impl BufferRef<Backend = Cpu>,+ >,+ command_buffer: &mut CpuCommandBufferEncoding,+ ) -> Result<<Cpu as Backend>::ScratchBuffer, CpuError> {let config = self.config;- let mut output = encoder.allocate_constant_for_shape(+ let mut output = command_buffer.allocate_scratch_for_shape(&[arguments.suffix_length, config.num_q_heads, config.head_dim],config.data_type,)?;let single_pass = <attention_single_pass::AttentionSinglePassCpuKernel as AttentionSinglePassKernel>::new(- encoder.context(),+ command_buffer.context(),config.data_type,config.head_dim,config.has_sinks,@@ -56,7 +61,7 @@ impl AttentionKernel for AttentionCpuKernel {arguments.trie.is_some(),config.sliding_window_size.is_some(),)?;- encoder.push_debug_group("attention core");+ command_buffer.push_debug_group("attention core");single_pass.encode(arguments.queries,arguments.keys,@@ -75,9 +80,9 @@ impl AttentionKernel for AttentionCpuKernel {arguments.sinks,config.num_q_heads,arguments.suffix_length,- encoder,+ command_buffer,);- encoder.pop_debug_group();+ command_buffer.pop_debug_group();Ok(output)}}diff --git a/crates/uzu-engine/src/backends/cpu/kernel/matmul/kernel.rs b/crates/uzu-engine/src/backends/cpu/kernel/matmul/kernel.rsindex 7670be9c8..5273d789b 100644--- a/crates/uzu-engine/src/backends/cpu/kernel/matmul/kernel.rs+++ b/crates/uzu-engine/src/backends/cpu/kernel/matmul/kernel.rs@@ -2,14 +2,16 @@ use super::reference::{WeightData, read_f32, write_f32};use crate::{backends::{common::{- Allocation, AsBufferRangeMut, AsBufferRangeRef, Backend, BufferArg, Encoder, Kernels,+ Backend, BufferCpuAccessible, BufferMut, BufferRef, Kernels,gpu_types::QuantizationMode,kernel::{ActivationTransform, TensorAddBiasKernel,matmul::{Int8CodeLayout, MatmulA, MatmulArguments, MatmulError, MatmulKernel},},},- cpu::{Cpu, context::CpuContext, error::CpuError},+ cpu::{+ Cpu, buffer::CpuBufferExt, command_buffer::CpuCommandBufferEncoding, context::CpuContext, error::CpuError,+ },},data_type::DataType,utils::pointers::{SendPtr, SendPtrMut},@@ -53,14 +55,21 @@ impl MatmulKernel for MatmulCpuKernel {})}- fn encode<'a, 'b, 'd, TB: BufferArg<'b, Cpu>>(+ fn encode(&mut self,- arguments: MatmulArguments<'a, 'b, 'd, Cpu, TB>,- encoder: &mut Encoder<Cpu>,+ arguments: MatmulArguments<+ '_,+ Cpu,+ impl BufferRef<Backend = Cpu>,+ impl BufferRef<Backend = Cpu>,+ impl BufferMut<Backend = Cpu>,+ impl BufferRef<Backend = Cpu>,+ >,+ command_buffer: &mut CpuCommandBufferEncoding,) -> Result<(), CpuError> {let output_scale = arguments.d_transform.ab_scale;let accumulate = arguments.d_transform.accumulate;- let bias_alloc = arguments.d_transform.bias;+ let bias_buffer = arguments.d_transform.bias;let post_rht = arguments.d_transform.rht_factors;let soft_cap = arguments.d_transform.soft_cap;@@ -69,7 +78,7 @@ impl MatmulKernel for MatmulCpuKernel {b,b_leading_dimension,b_transpose,- d,+ mut d,m,n,k,@@ -99,9 +108,11 @@ impl MatmulKernel for MatmulCpuKernel {values,offset,} => {- let range = values.as_buffer_range_ref();- let byte_offset = range.range().start + offset * input_data_type.size_in_bytes();- AData::FullPrecision(SendPtr(unsafe { &*range.buffer().get() }.as_ptr().wrapping_byte_add(byte_offset)))+ let (values, range) = values.parts();+ let byte_offset = range.start + offset * input_data_type.size_in_bytes();+ AData::FullPrecision(SendPtr(+ values.cpu_address().as_ptr().cast::<u8>().cast_const().wrapping_byte_add(byte_offset),+ ))},MatmulA::Int8Symmetric {values,@@ -122,37 +133,31 @@ impl MatmulKernel for MatmulCpuKernel {}.into());}- let values_range = values.as_buffer_range_ref();- let scales_range = scales.as_buffer_range_ref();+ let (values, values_range) = values.parts();+ let (scales, scales_range) = scales.parts();AData::Int8 {values: SendPtr(- unsafe { &*values_range.buffer().get() }.as_ptr().wrapping_byte_add(values_range.range().start),+ values.cpu_address().as_ptr().cast::<u8>().cast_const().wrapping_byte_add(values_range.start),),scales: SendPtr(- unsafe { &*scales_range.buffer().get() }.as_ptr().wrapping_byte_add(scales_range.range().start),+ scales.cpu_address().as_ptr().cast::<u8>().cast_const().wrapping_byte_add(scales_range.start),),group_size: a_group_size as usize,code_layout,}},};- let bias_ptr = bias_alloc.map(|bias| {- let r = bias.as_buffer_range_ref();- SendPtr(unsafe { &*r.buffer().get() }.as_ptr().wrapping_byte_add(r.range().start))- });+ let bias_ptr = bias_buffer.map(|bias| SendPtr(bias.cpu_ptr().as_ptr().cast::<u8>().cast_const()));let gather_ptr = gather_indices.map(|indices| {- let r = indices.as_buffer_range_ref();- SendPtr(unsafe { &*r.buffer().get() }.as_ptr().wrapping_byte_add(r.range().start) as *const u32)- });- let d_buffer_range = d.as_buffer_range_mut();- let d_ptr = SendPtrMut(unsafe {- (&*d_buffer_range.buffer().get()).as_ptr().wrapping_byte_add(d_buffer_range.range().start) as *mut u8+ let (indices, range) = indices.parts();+ SendPtr(indices.cpu_address().as_ptr().cast::<u32>().cast_const().wrapping_byte_add(range.start))});+ let (d_buffer, d_range) = d.reborrow().parts();+ let d_ptr = SendPtrMut(d_buffer.cpu_address().as_ptr().cast::<u8>().wrapping_byte_add(d_range.start));let weight_data = WeightData::from_b(b, b_leading_dimension, b_transpose, k_u, n_u)?;let bias_after_rht = post_rht.is_some();- let command_buffer = encoder.as_command_buffer_mut();command_buffer.push_command(move || {unsafe {for row in 0..m_u {@@ -267,10 +272,17 @@ impl MatmulKernel for MatmulCpuKernel {});if let Some(factors) = post_rht {- self.output_rht.encode_fp_in_place(&mut *d, factors, None, m, n, encoder);- if let Some(bias) = bias_alloc {+ self.output_rht.encode_fp_in_place(d.reborrow(), factors, None, m, n, command_buffer);+ if let Some(bias) = bias_buffer {let output_length = m.checked_mul(n).expect("matmul output length must fit in u32");- self.bias_add.encode(None::<&Allocation<Cpu>>, bias, &mut *d, n, output_length, encoder);+ self.bias_add.encode(+ None::<&<Cpu as Backend>::ScratchBuffer>,+ bias,+ d,+ n,+ output_length,+ command_buffer,+ );}}diff --git a/crates/uzu-engine/src/backends/cpu/kernel/matmul/reference.rs b/crates/uzu-engine/src/backends/cpu/kernel/matmul/reference.rsindex 0ce2f5ac0..e6674ab1f 100644--- a/crates/uzu-engine/src/backends/cpu/kernel/matmul/reference.rs+++ b/crates/uzu-engine/src/backends/cpu/kernel/matmul/reference.rs@@ -3,10 +3,10 @@ use half::{bf16, f16};use crate::{backends::{common::{- AsBufferRangeRef, BufferArg,+ BufferRef,kernel::matmul::{MatmulB, MatmulError, QuantParamsStrides},},- cpu::Cpu,+ cpu::{Cpu, buffer::CpuBufferExt},},data_type::DataType,utils::pointers::SendPtr,@@ -31,17 +31,17 @@ pub(super) enum WeightData {}impl WeightData {- pub(super) fn from_b<'a, TB: BufferArg<'a, Cpu>>(- b: MatmulB<'a, Cpu, TB>,+ pub(super) fn from_b(+ b: MatmulB<impl BufferRef<Backend = Cpu>>,b_leading_dimension: Option<u32>,b_transpose: bool,k: usize,n: usize,) -> Result<Self, MatmulError<Cpu>> {- let alloc_ptr = |a: &crate::backends::common::Allocation<Cpu>| {- let r = a.as_buffer_range_ref();- SendPtr(unsafe { &*r.buffer().get() }.as_ptr().wrapping_byte_add(r.range().start))- };+ fn buffer_ptr(view: impl BufferRef<Backend = Cpu>) -> SendPtr<u8> {+ let (buffer, range) = view.parts();+ SendPtr(buffer.cpu_address().as_ptr().cast::<u8>().cast_const().wrapping_byte_add(range.start))+ }match b {MatmulB::FullPrecision {b: weights,@@ -51,18 +51,17 @@ impl WeightData {} else {n});- let (buffer, byte_off, _) = weights.into_parts();Ok(WeightData::FullPrecision {- ptr: SendPtr(unsafe { &*buffer.downcast().get() }.as_ptr().wrapping_byte_add(byte_off)),+ ptr: buffer_ptr(weights),leading_dimension,transpose: b_transpose,})},MatmulB::Quantized(quantized) => Ok(WeightData::Quantized {- weights: alloc_ptr(quantized.codes),- scales: alloc_ptr(quantized.scales),- zero_points: quantized.zero_points().map(|values| (alloc_ptr(values), quantized.zero_point_strides())),- biases: quantized.biases().map(alloc_ptr),+ weights: buffer_ptr(quantized.codes),+ scales: buffer_ptr(quantized.scales),+ zero_points: quantized.zero_points().map(|values| (buffer_ptr(values), quantized.zero_point_strides())),+ biases: quantized.biases().map(buffer_ptr),scale_strides: quantized.params.scale_strides(),bits: quantized.bits() as usize,group_size: quantized.group_size as usize,diff --git a/crates/uzu-engine/src/backends/cpu/kernel/mod.rs b/crates/uzu-engine/src/backends/cpu/kernel/mod.rsindex a1a3f0467..8a079aeba 100644--- a/crates/uzu-engine/src/backends/cpu/kernel/mod.rs+++ b/crates/uzu-engine/src/backends/cpu/kernel/mod.rs@@ -22,8 +22,6 @@ mod softmax;mod ssm;mod tensor_add_bias;mod tensor_add_scale;-mod tensor_add_swap;-mod tensor_copy;mod weaver;include!(concat!(env!("OUT_DIR"), "/cpu.rs"));diff --git a/crates/uzu-engine/src/backends/cpu/kernel/radix_top_k_small.rs b/crates/uzu-engine/src/backends/cpu/kernel/radix_top_k_small.rsindex be9089f4c..c8e226395 100644--- a/crates/uzu-engine/src/backends/cpu/kernel/radix_top_k_small.rs+++ b/crates/uzu-engine/src/backends/cpu/kernel/radix_top_k_small.rs@@ -3,10 +3,12 @@ use half::bf16;use crate::{backends::{common::{- Allocation, AsBufferRangeMut, AsBufferRangeRef, Encoder,+ BufferMut, BufferRef,kernel::radix_top_k_small::{MAX_K, RadixTopKSmall},},- cpu::{Cpu, context::CpuContext, error::CpuError},+ cpu::{+ Cpu, buffer::CpuBufferExt, command_buffer::CpuCommandBufferEncoding, context::CpuContext, error::CpuError,+ },},utils::pointers::{SendPtr, SendPtrMut},};@@ -30,28 +32,27 @@ impl RadixTopKSmall for CpuRadixTopKSmall {fn encode(&self,- input: &Allocation<Cpu>,- output_ids: &mut Allocation<Cpu>,- output_scores: &mut Allocation<Cpu>,+ input: impl BufferRef<Backend = Cpu>,+ output_ids: impl BufferMut<Backend = Cpu>,+ output_scores: impl BufferMut<Backend = Cpu>,rows: u32,k: u32,- encoder: &mut Encoder<Cpu>,+ command_buffer: &mut CpuCommandBufferEncoding,) -> Result<(), CpuError> {let rows = rows as usize;let columns = self.columns;let k = k as usize;assert!(rows > 0 && k > 0 && k <= MAX_K as usize && k <= columns);- let input = input.as_buffer_range_ref();- let input = SendPtr(unsafe { (&*input.buffer().get()).as_ptr().add(input.range().start).cast::<bf16>() });- let output_ids = output_ids.as_buffer_range_mut();- let output_ids = SendPtrMut(unsafe {- (&mut *output_ids.buffer().get()).as_mut_ptr().add(output_ids.range().start).cast::<u32>()- });- let output_scores = output_scores.as_buffer_range_mut();- let output_scores = SendPtrMut(unsafe {- (&mut *output_scores.buffer().get()).as_mut_ptr().add(output_scores.range().start).cast::<f32>()- });- encoder.as_command_buffer_mut().push_command(move || {+ let (input, input_range) = input.parts();+ let (output_ids, output_ids_range) = output_ids.parts();+ let (output_scores, output_scores_range) = output_scores.parts();+ let input =+ SendPtr(input.cpu_address().as_ptr().cast::<bf16>().cast_const().wrapping_byte_add(input_range.start));+ let output_ids =+ SendPtrMut(output_ids.cpu_address().as_ptr().cast::<u32>().wrapping_byte_add(output_ids_range.start));+ let output_scores =+ SendPtrMut(output_scores.cpu_address().as_ptr().cast::<f32>().wrapping_byte_add(output_scores_range.start));+ command_buffer.push_command(move || {let output_ids = unsafe { std::slice::from_raw_parts_mut(output_ids.as_ptr(), rows * k) };let output_scores = unsafe { std::slice::from_raw_parts_mut(output_scores.as_ptr(), rows * k) };let values = unsafe { std::slice::from_raw_parts(input.as_ptr(), rows * columns) }diff --git a/crates/uzu-engine/src/backends/cpu/kernel/sampling/repetition_penalty.rs b/crates/uzu-engine/src/backends/cpu/kernel/sampling/repetition_penalty.rsindex c406e4e16..1d9f059bf 100644--- a/crates/uzu-engine/src/backends/cpu/kernel/sampling/repetition_penalty.rs+++ b/crates/uzu-engine/src/backends/cpu/kernel/sampling/repetition_penalty.rs@@ -17,9 +17,9 @@ pub fn repetition_penalty<T: ArrayElement + Float + NumCast>(sampling_start: u32,sampling_length: u32,) {- fn apply<T: ArrayElement + Float + NumCast>(- original_logits: *const T,- logits_copy: *mut T,+ fn apply(+ original_logits: *const (impl ArrayElement + Float),+ logits_copy: *mut (impl ArrayElement + Float),vocab_size: usize,sample_index: usize,token_id: usize,diff --git a/crates/uzu-engine/src/backends/cpu/kernel/tensor_add_swap/mod.rs b/crates/uzu-engine/src/backends/cpu/kernel/tensor_add_swap/mod.rsdeleted file mode 100644index a429b0db3..000000000--- a/crates/uzu-engine/src/backends/cpu/kernel/tensor_add_swap/mod.rs+++ /dev/null@@ -1 +0,0 @@-pub mod tensor_add_swap;diff --git a/crates/uzu-engine/src/backends/cpu/kernel/tensor_add_swap/tensor_add_swap.rs b/crates/uzu-engine/src/backends/cpu/kernel/tensor_add_swap/tensor_add_swap.rsdeleted file mode 100644index df0954921..000000000--- a/crates/uzu-engine/src/backends/cpu/kernel/tensor_add_swap/tensor_add_swap.rs+++ /dev/null@@ -1,21 +0,0 @@-use half::{bf16, f16};-use num_traits::Float;-use uzu_engine_macros::kernel;--use crate::array::ArrayElement;--#[kernel(TensorAddSwap)]-#[variants(T, f32, f16, bf16)]-pub fn tensor_add_swap<T: ArrayElement + Float>(- skip_buffer: *mut T,- main_buffer: *mut T,- length: u32,-) {- unsafe {- for i in 0..length {- let result = *skip_buffer.add(i as usize) + *main_buffer.add(i as usize);- *skip_buffer.add(i as usize) = result;- *main_buffer.add(i as usize) = result;- }- }-}diff --git a/crates/uzu-engine/src/backends/cpu/kernel/tensor_copy/mod.rs b/crates/uzu-engine/src/backends/cpu/kernel/tensor_copy/mod.rsdeleted file mode 100644index a61a2ebd2..000000000--- a/crates/uzu-engine/src/backends/cpu/kernel/tensor_copy/mod.rs+++ /dev/null@@ -1 +0,0 @@-pub mod tensor_copy;diff --git a/crates/uzu-engine/src/backends/cpu/kernel/tensor_copy/tensor_copy.rs b/crates/uzu-engine/src/backends/cpu/kernel/tensor_copy/tensor_copy.rsdeleted file mode 100644index e46e9bf72..000000000--- a/crates/uzu-engine/src/backends/cpu/kernel/tensor_copy/tensor_copy.rs+++ /dev/null@@ -1,19 +0,0 @@-use half::{bf16, f16};-use num_traits::Float;-use uzu_engine_macros::kernel;--use crate::array::ArrayElement;--#[kernel(TensorCopy)]-#[variants(T, f32, f16, bf16)]-pub fn tensor_copy<T: ArrayElement + Float>(- src_buffer: *const T,- dst_buffer: *mut T,- length: u32,-) {- unsafe {- for i in 0usize..(length as usize) {- *dst_buffer.add(i) = *src_buffer.add(i);- }- }-}diff --git a/crates/uzu-engine/src/backends/cpu/kernel/weaver/weaver_frontier_select.rs b/crates/uzu-engine/src/backends/cpu/kernel/weaver/weaver_frontier_select.rsindex 4b9fc95a6..6ddf5760e 100644--- a/crates/uzu-engine/src/backends/cpu/kernel/weaver/weaver_frontier_select.rs+++ b/crates/uzu-engine/src/backends/cpu/kernel/weaver/weaver_frontier_select.rs@@ -1,3 +1,5 @@+use std::range::Range;+use uzu_engine_macros::kernel;use crate::backends::common::gpu_types::weaver::{@@ -135,9 +137,10 @@ pub fn weaver_frontier_select(node_valid[node] = u32::from(real && expandable);if (depth as usize) < candidate_depth_count {- let source = depth as usize * candidates_per_depth..(depth as usize + 1) * candidates_per_depth;- let destination = node * candidates_per_depth..(node + 1) * candidates_per_depth;- node_candidate_ids[destination.clone()].copy_from_slice(&candidate_pool_ids[source.clone()]);+ let source =+ Range::from(depth as usize * candidates_per_depth..(depth as usize + 1) * candidates_per_depth);+ let destination = Range::from(node * candidates_per_depth..(node + 1) * candidates_per_depth);+ node_candidate_ids[destination].copy_from_slice(&candidate_pool_ids[source]);node_candidate_logits[destination].copy_from_slice(&candidate_pool_logits[source]);}}diff --git a/crates/uzu-engine/src/backends/cpu/mod.rs b/crates/uzu-engine/src/backends/cpu/mod.rsindex 5628b5d28..f569a2da4 100644--- a/crates/uzu-engine/src/backends/cpu/mod.rs+++ b/crates/uzu-engine/src/backends/cpu/mod.rs@@ -2,9 +2,7 @@ mod backend;mod buffer;mod command_buffer;mod context;-mod dense_buffer;mod error;-pub(crate) mod kernel;-mod sparse;+pub(crate) mod kernel; // TODO: This should not be pub!!!pub use backend::Cpu;diff --git a/crates/uzu-engine/src/backends/metal/backend.rs b/crates/uzu-engine/src/backends/metal/backend.rsindex a394a7c1a..fa2936be7 100644--- a/crates/uzu-engine/src/backends/metal/backend.rs+++ b/crates/uzu-engine/src/backends/metal/backend.rs@@ -1,8 +1,20 @@-use metal::MTLBuffer;-use objc2::{rc::Retained, runtime::ProtocolObject};--use super::{command_buffer::MetalCommandBuffer, context::MetalContext, error::MetalError, kernel::MetalKernels};-use crate::backends::{common::Backend, metal::sparse::MetalSparseBuffer};+use crate::backends::{+ common::{+ Backend,+ allocator::{+ block::BlockAllocation,+ bump::BumpAllocation,+ pool::{PoolAllocation, PoolAllocator},+ },+ },+ metal::{+ buffer::{dense::MetalDenseBuffer, sparse::MetalSparseBuffer},+ command_buffer::MetalCommandBuffer,+ context::MetalContext,+ error::MetalError,+ kernel::MetalKernels,+ },+};#[derive(Debug, Clone)]pub struct Metal;@@ -10,16 +22,13 @@ pub struct Metal;impl Backend for Metal {type Context = MetalContext;type CommandBuffer = MetalCommandBuffer;- type DenseBuffer = Retained<ProtocolObject<dyn MTLBuffer>>;+ type GlobalBuffer = BlockAllocation<MetalDenseBuffer>;+ type ConstantBuffer = BumpAllocation<Self::GlobalBuffer>;+ type ScratchBuffer = PoolAllocation<Self::GlobalBuffer>;type SparseBuffer = MetalSparseBuffer;+ type AllocationPool = PoolAllocator<Self::GlobalBuffer>;type Kernels = MetalKernels;type Error = MetalError;const NAME: &'static str = "metal";- const MIN_ALLOCATION_ALIGNMENT: usize = 4;- const MAX_ALLOCATION_ALIGNMENT: usize = 64;- const ALLOCATION_GRANULARITY: usize = 8 * 1024 * 1024;- // Metal's set_bytes supports up to 4KB per bound value.- // https://developer.apple.com/documentation/metal/mtlcomputecommandencoder/setbytes(_:length:index:)?language=objc- const MAX_INLINE_BYTES: usize = 4096;}diff --git a/crates/uzu-engine/src/backends/metal/buffer.rs b/crates/uzu-engine/src/backends/metal/buffer.rsdeleted file mode 100644index d7af99e38..000000000--- a/crates/uzu-engine/src/backends/metal/buffer.rs+++ /dev/null@@ -1,22 +0,0 @@-use std::any::Any;--use metal::MTLBuffer;-use objc2::{rc::Retained, runtime::ProtocolObject};--use crate::backends::{- common::{Backend, Buffer},- metal::{Metal, sparse::MetalSparseBuffer},-};--impl dyn Buffer<Backend = Metal> {- pub fn downcast(&self) -> &Retained<ProtocolObject<dyn MTLBuffer>> {- let buffer = self as &dyn Any;- if let Some(buffer) = buffer.downcast_ref::<<Metal as Backend>::DenseBuffer>() {- buffer- } else if let Some(buffer) = buffer.downcast_ref::<MetalSparseBuffer>() {- buffer.mtl_buffer()- } else {- unreachable!("Unsupported Metal buffer type")- }- }-}diff --git a/crates/uzu-engine/src/backends/metal/buffer/constant.rs b/crates/uzu-engine/src/backends/metal/buffer/constant.rsnew file mode 100644index 000000000..f2a19cfe6--- /dev/null+++ b/crates/uzu-engine/src/backends/metal/buffer/constant.rs@@ -0,0 +1,34 @@+use std::{fmt::Debug, os::raw::c_void, ptr::NonNull};++use crate::backends::{+ common::{Backend, Buffer, BufferCpuAccessible, ConstantBuffer, allocator::bump::BumpAllocation},+ metal::Metal,+};++impl Buffer for BumpAllocation<<Metal as Backend>::GlobalBuffer> {+ type Backend = Metal;++ fn size(&self) -> usize {+ self.range().iter().len()+ }+}++impl BufferCpuAccessible for BumpAllocation<<Metal as Backend>::GlobalBuffer> {+ fn cpu_ptr(&self) -> NonNull<c_void> {+ unsafe { self.page().cpu_ptr().byte_add(self.range().start) }+ }+}++impl ConstantBuffer for BumpAllocation<<Metal as Backend>::GlobalBuffer> {}++impl Debug for BumpAllocation<<Metal as Backend>::GlobalBuffer> {+ fn fmt(+ &self,+ f: &mut std::fmt::Formatter<'_>,+ ) -> std::fmt::Result {+ f.debug_struct("BumpAllocation<Metal::GlobalBuffer>")+ .field("page", &self.page())+ .field("range", &self.range())+ .finish_non_exhaustive()+ }+}diff --git a/crates/uzu-engine/src/backends/metal/buffer/dense.rs b/crates/uzu-engine/src/backends/metal/buffer/dense.rsnew file mode 100644index 000000000..83fc24161--- /dev/null+++ b/crates/uzu-engine/src/backends/metal/buffer/dense.rs@@ -0,0 +1,52 @@+use std::sync::Arc;++use metal::{MTLBuffer, MTLDeviceExt, MTLResidencySet, MTLResourceOptions};+use objc2::{rc::Retained, runtime::ProtocolObject};+use parking_lot::Mutex;++use crate::backends::metal::{MetalContext, error::MetalError};++#[derive(Debug)]+pub struct MetalDenseBuffer {+ buffer: Retained<ProtocolObject<dyn MTLBuffer>>,+ residency_set: Arc<Mutex<Retained<ProtocolObject<dyn MTLResidencySet>>>>,+}++impl MetalDenseBuffer {+ pub(in crate::backends::metal) fn new(+ context: &MetalContext,+ size: usize,+ ) -> Result<Self, MetalError> {+ let buffer = context+ .device+ .new_buffer(size, MTLResourceOptions::STORAGE_MODE_SHARED)+ .ok_or(MetalError::CannotCreateBuffer)?;++ let residency_set = context.residency_set.clone();++ let residency_set_locked = residency_set.lock();+ residency_set_locked.add_allocation(buffer.as_ref());+ residency_set_locked.commit();+ residency_set_locked.request_residency();+ drop(residency_set_locked);++ context.update_peak_memory_usage();++ Ok(Self {+ buffer,+ residency_set,+ })+ }++ pub(super) fn mtl_buffer(&self) -> &Retained<ProtocolObject<dyn MTLBuffer>> {+ &self.buffer+ }+}++impl Drop for MetalDenseBuffer {+ fn drop(&mut self) {+ let residency_set_locked = self.residency_set.lock();+ residency_set_locked.remove_allocation(self.buffer.as_ref());+ residency_set_locked.commit();+ }+}diff --git a/crates/uzu-engine/src/backends/metal/buffer/global.rs b/crates/uzu-engine/src/backends/metal/buffer/global.rsnew file mode 100644index 000000000..25c4d3d8c--- /dev/null+++ b/crates/uzu-engine/src/backends/metal/buffer/global.rs@@ -0,0 +1,36 @@+use std::{fmt::Debug, os::raw::c_void, ptr::NonNull};++use metal::MTLBuffer;++use crate::backends::{+ common::{Buffer, BufferCpuAccessible, GlobalBuffer, allocator::block::BlockAllocation},+ metal::{Metal, buffer::dense::MetalDenseBuffer},+};++impl Buffer for BlockAllocation<MetalDenseBuffer> {+ type Backend = Metal;++ fn size(&self) -> usize {+ self.range().iter().len()+ }+}++impl BufferCpuAccessible for BlockAllocation<MetalDenseBuffer> {+ fn cpu_ptr(&self) -> NonNull<c_void> {+ unsafe { self.page().mtl_buffer().contents().byte_add(self.range().start) }+ }+}++impl GlobalBuffer for BlockAllocation<MetalDenseBuffer> {}++impl Debug for BlockAllocation<MetalDenseBuffer> {+ fn fmt(+ &self,+ f: &mut std::fmt::Formatter<'_>,+ ) -> std::fmt::Result {+ f.debug_struct("BlockAllocation<MetalDenseBuffer>")+ .field("page", &self.page())+ .field("range", &self.range())+ .finish_non_exhaustive()+ }+}diff --git a/crates/uzu-engine/src/backends/metal/buffer/mod.rs b/crates/uzu-engine/src/backends/metal/buffer/mod.rsnew file mode 100644index 000000000..b6b9ef5de--- /dev/null+++ b/crates/uzu-engine/src/backends/metal/buffer/mod.rs@@ -0,0 +1,52 @@+use std::range::Range;++use metal::MTLBuffer;+use objc2::{rc::Retained, runtime::ProtocolObject};++use crate::{+ backends::{+ common::{Backend, Buffer},+ metal::Metal,+ },+ utils::downcast::downcast_ref,+};++pub mod constant;+pub mod dense;+pub mod global;+pub mod scratch;+pub mod sparse;++pub(super) trait MetalBufferExt: Buffer<Backend = Metal> {+ fn downcast(&self) -> (&Retained<ProtocolObject<dyn MTLBuffer>>, usize) {+ if let Some(buffer) = downcast_ref::<<Metal as Backend>::GlobalBuffer>(self) {+ (buffer.page().mtl_buffer(), buffer.range().start)+ } else if let Some(buffer) = downcast_ref::<<Metal as Backend>::ConstantBuffer>(self) {+ let (page, offset) = buffer.page().downcast();+ (page, offset + buffer.range().start)+ } else if let Some(buffer) = downcast_ref::<<Metal as Backend>::ScratchBuffer>(self) {+ let (page, offset) = buffer.page().downcast();+ (page, offset + buffer.range().start)+ } else if let Some(buffer) = downcast_ref::<<Metal as Backend>::SparseBuffer>(self) {+ (buffer.mtl_buffer(), 0)+ } else {+ unreachable!()+ }+ }++ fn gpu_address(&self) -> u64 {+ let (buffer, offset) = self.downcast();+ buffer.gpu_address() + offset as u64+ }++ fn gpu_address_subrange(+ &self,+ subrange: Range<usize>,+ ) -> Range<u64> {+ assert!(subrange.end <= self.size(), "subrange overflow: subrange={:?} length={}", subrange, self.size());+ let buffer_pointer = self.gpu_address();+ ((buffer_pointer + subrange.start as u64)..(buffer_pointer + subrange.end as u64)).into()+ }+}++impl<T: Buffer<Backend = Metal> + ?Sized> MetalBufferExt for T {}diff --git a/crates/uzu-engine/src/backends/metal/buffer/scratch.rs b/crates/uzu-engine/src/backends/metal/buffer/scratch.rsnew file mode 100644index 000000000..fd5af39b8--- /dev/null+++ b/crates/uzu-engine/src/backends/metal/buffer/scratch.rs@@ -0,0 +1,34 @@+use std::{fmt::Debug, os::raw::c_void, ptr::NonNull};++use crate::backends::{+ common::{Backend, Buffer, BufferCpuAccessible, ScratchBuffer, allocator::pool::PoolAllocation},+ metal::Metal,+};++impl Buffer for PoolAllocation<<Metal as Backend>::GlobalBuffer> {+ type Backend = Metal;++ fn size(&self) -> usize {+ self.range().iter().len()+ }+}++impl BufferCpuAccessible for PoolAllocation<<Metal as Backend>::GlobalBuffer> {+ fn cpu_ptr(&self) -> NonNull<c_void> {+ unsafe { self.page().cpu_ptr().byte_add(self.range().start) }+ }+}++impl ScratchBuffer for PoolAllocation<<Metal as Backend>::GlobalBuffer> {}++impl Debug for PoolAllocation<<Metal as Backend>::GlobalBuffer> {+ fn fmt(+ &self,+ f: &mut std::fmt::Formatter<'_>,+ ) -> std::fmt::Result {+ f.debug_struct("PoolAllocation<Metal::GlobalBuffer>")+ .field("page", &self.page())+ .field("range", &self.range())+ .finish_non_exhaustive()+ }+}diff --git a/crates/uzu-engine/src/backends/metal/sparse/mod.rs b/crates/uzu-engine/src/backends/metal/buffer/sparse/mod.rssimilarity index 100%rename from crates/uzu-engine/src/backends/metal/sparse/mod.rsrename to crates/uzu-engine/src/backends/metal/buffer/sparse/mod.rsdiff --git a/crates/uzu-engine/src/backends/metal/sparse/sparse_buffer.rs b/crates/uzu-engine/src/backends/metal/buffer/sparse/sparse_buffer.rssimilarity index 69%rename from crates/uzu-engine/src/backends/metal/sparse/sparse_buffer.rsrename to crates/uzu-engine/src/backends/metal/buffer/sparse/sparse_buffer.rsindex 6776a0ff1..6ee040bf7 100644--- a/crates/uzu-engine/src/backends/metal/sparse/sparse_buffer.rs+++ b/crates/uzu-engine/src/backends/metal/buffer/sparse/sparse_buffer.rs@@ -1,18 +1,19 @@use std::{cmp::{max, min},fmt::Debug,- ops::Range,+ range::Range,sync::Arc,};-use metal::{MTLBuffer, MTLDeviceExt, MTLResourceOptions, MTLSparsePageSize};+use metal::{MTLBuffer, MTLDeviceExt, MTLResidencySet, MTLResourceOptions, MTLSparsePageSize};use objc2::{rc::Retained, runtime::ProtocolObject};use rangemap::RangeSet;use crate::backends::{- common::{Backend, Buffer, SparseBuffer, SparseBufferExt},+ common::{Backend, Buffer, SparseBuffer},metal::{- Metal, MetalContext, error::MetalError, metal_extensions::SparsePageSizeExt, sparse::MetalSparseMappingOpsBatch,+ Metal, MetalContext, buffer::sparse::MetalSparseMappingOpsBatch, error::MetalError,+ metal_extensions::SparsePageSizeExt,},};@@ -39,6 +40,12 @@ impl MetalSparseBuffer {).ok_or(MetalError::SparseBufferAlloc(aligned_capacity))?;+ let residency_set_locked = context.residency_set.lock();+ residency_set_locked.add_allocation(buffer.as_ref());+ residency_set_locked.commit();+ residency_set_locked.request_residency();+ drop(residency_set_locked);+Ok(Self {buffer,mapped_pages: RangeSet::new(),@@ -67,19 +74,18 @@ impl Debug for MetalSparseBuffer {impl Drop for MetalSparseBuffer {fn drop(&mut self) {let context = self.context.clone();- self.unmap(&context, &(0..self.total_pages())).expect("Failed to unmap");+ self.unmap(&context, 0..self.total_pages()).expect("Failed to unmap");+ let residency_set_locked = context.residency_set.lock();+ residency_set_locked.remove_allocation(self.buffer.as_ref());+ residency_set_locked.commit();}}impl Buffer for MetalSparseBuffer {type Backend = Metal;- fn gpu_ptr(&self) -> usize {- self.buffer.gpu_ptr()- }-fn size(&self) -> usize {- self.buffer.size()+ self.buffer.length()}}@@ -87,19 +93,20 @@ impl SparseBuffer for MetalSparseBuffer {fn map(&mut self,context: &<Self::Backend as Backend>::Context,- pages: &Range<usize>,+ pages: impl Into<Range<usize>>,) -> Result<(), <Self::Backend as Backend>::Error> {+ let pages = pages.into();if pages.is_empty() {return Ok(());}// prepare operationslet mut all_batches: Vec<MetalSparseMappingOpsBatch> = Vec::new();- let gaps = self.mapped_pages.gaps(pages).collect::<Vec<_>>();- let pages_to_map = gaps.iter().map(|gap| gap.len()).sum();+ let gaps = self.mapped_pages.gaps(&pages.into()).map(Range::from).collect::<Vec<_>>();+ let pages_to_map = gaps.iter().map(|gap| gap.iter().len()).sum();context.sparse_heap_pool().ensure_enough_free_pages(context, pages_to_map)?;- for gap in gaps.iter() {+ for &gap in &gaps {let mut pool = context.sparse_heap_pool();let operations = pool.create_map_operations(context, &self.buffer, gap)?;pool.apply_map_operations(&operations);@@ -109,7 +116,7 @@ impl SparseBuffer for MetalSparseBuffer {// execute operationscontext.sparse_update_mappings(&all_batches);for gap in gaps {- self.mapped_pages.insert(gap)+ self.mapped_pages.insert(gap.into())}Ok(())@@ -118,8 +125,9 @@ impl SparseBuffer for MetalSparseBuffer {fn unmap(&mut self,context: &<Self::Backend as Backend>::Context,- pages: &Range<usize>,+ pages: impl Into<Range<usize>>,) -> Result<(), <Self::Backend as Backend>::Error> {+ let pages = pages.into();if pages.is_empty() {return Ok(());}@@ -128,10 +136,10 @@ impl SparseBuffer for MetalSparseBuffer {let mut all_batches: Vec<MetalSparseMappingOpsBatch> = Vec::new();let mapped_ranges = self.mapped_pages- .overlapping(pages)- .map(|range| max(range.start, pages.start)..min(range.end, pages.end))+ .overlapping(&pages.into())+ .map(|range| Range::from(max(range.start, pages.start)..min(range.end, pages.end))).collect::<Vec<_>>();- for mapped_range in mapped_ranges.iter() {+ for &mapped_range in &mapped_ranges {let batches = context.sparse_heap_pool().create_unmap_operations(&self.buffer, mapped_range);context.sparse_heap_pool().apply_map_operations(&batches);all_batches.extend(batches);@@ -140,7 +148,7 @@ impl SparseBuffer for MetalSparseBuffer {// execute operationscontext.sparse_update_mappings(&all_batches);for mapped_range in mapped_ranges {- self.mapped_pages.remove(mapped_range)+ self.mapped_pages.remove(mapped_range.into())}Ok(())@@ -152,5 +160,5 @@ impl SparseBuffer for MetalSparseBuffer {}#[cfg(test)]-#[path = "../../../../unit/backends/metal/sparse/sparse_buffer_test.rs"]+#[path = "../../../../../unit/backends/metal/sparse/sparse_buffer_test.rs"]mod tests;diff --git a/crates/uzu-engine/src/backends/metal/sparse/sparse_heap.rs b/crates/uzu-engine/src/backends/metal/buffer/sparse/sparse_heap.rssimilarity index 78%rename from crates/uzu-engine/src/backends/metal/sparse/sparse_heap.rsrename to crates/uzu-engine/src/backends/metal/buffer/sparse/sparse_heap.rsindex 85436a7ea..496311334 100644--- a/crates/uzu-engine/src/backends/metal/sparse/sparse_heap.rs+++ b/crates/uzu-engine/src/backends/metal/buffer/sparse/sparse_heap.rs@@ -1,4 +1,4 @@-use std::{collections::HashMap, ops::Range};+use std::{collections::HashMap, range::Range};use metal::{MTLBuffer, MTLDeviceExt, MTLHeap, MTLHeapDescriptor, MTLHeapType, MTLSparsePageSize, MTLSparseTextureMappingMode,@@ -9,9 +9,9 @@ use rangemap::{RangeMap, RangeSet};use crate::backends::metal::{MetalContext,+ buffer::sparse::{MetalSparseMappingOpsBatch, sparse_utils::MetalSparseHeapBufferMapping},error::MetalError,metal_extensions::SparsePageSizeExt,- sparse::{MetalSparseMappingOpsBatch, sparse_utils::MetalSparseHeapBufferMapping},};pub(crate) struct MetalSparseHeap {@@ -57,8 +57,8 @@ impl MetalSparseHeap {&self.heap}- pub fn free_pages(&self) -> &RangeSet<usize> {- &self.free_pages+ pub fn free_pages(&self) -> impl Iterator<Item = Range<usize>> + '_ {+ self.free_pages.iter().map(|range| (range.start..range.end).into())}/// Iterates `(heap_range, mapping)` pairs that belong to a single buffer.@@ -69,7 +69,8 @@ impl MetalSparseHeap {self.buffer_mappings.get(&buffer_address).into_iter()- .flat_map(|m| m.iter().map(|(r, mapping)| (r.clone(), mapping)))+ .flat_map(|m| m.iter())+ .map(|(range, mapping)| ((range.start..range.end).into(), mapping))}pub fn is_empty(&self) -> bool {@@ -83,15 +84,15 @@ impl MetalSparseHeap {let buffer_address = ops.buffer.gpu_address();let entry = self.buffer_mappings.entry(buffer_address).or_default();for mtl_op in ops.mtl_operations.iter() {- let heap_range = mtl_op.heap_offset..(mtl_op.heap_offset + mtl_op.buffer_range().len());+ let buffer_range = Range::from(mtl_op.buffer_range());+ let heap_range = Range::from(mtl_op.heap_offset..mtl_op.heap_offset + buffer_range.iter().len());if mtl_op.mode == MTLSparseTextureMappingMode::Map {- let buffer_range = mtl_op.buffer_range();let buffer_mapping = MetalSparseHeapBufferMapping::new(mtl_op.heap_offset, buffer_range.start);- entry.insert(heap_range.clone(), buffer_mapping);- self.free_pages.remove(heap_range);+ entry.insert(heap_range.into(), buffer_mapping);+ self.free_pages.remove(heap_range.into());} else {- entry.remove(heap_range.clone());- self.free_pages.insert(heap_range);+ entry.remove(heap_range.into());+ self.free_pages.insert(heap_range.into());}}diff --git a/crates/uzu-engine/src/backends/metal/sparse/sparse_heap_pool.rs b/crates/uzu-engine/src/backends/metal/buffer/sparse/sparse_heap_pool.rssimilarity index 90%rename from crates/uzu-engine/src/backends/metal/sparse/sparse_heap_pool.rsrename to crates/uzu-engine/src/backends/metal/buffer/sparse/sparse_heap_pool.rsindex ff6b25487..2a0cd1c02 100644--- a/crates/uzu-engine/src/backends/metal/sparse/sparse_heap_pool.rs+++ b/crates/uzu-engine/src/backends/metal/buffer/sparse/sparse_heap_pool.rs@@ -1,6 +1,6 @@use std::{cmp::{max, min},- ops::Range,+ range::Range,sync::Arc,};@@ -10,9 +10,9 @@ use parking_lot::Mutex;use crate::backends::metal::{MetalContext,+ buffer::sparse::{MetalSparseMappingOpsBatch, sparse_heap::MetalSparseHeap},error::MetalError,metal_extensions::SparsePageSizeExt,- sparse::{MetalSparseMappingOpsBatch, sparse_heap::MetalSparseHeap},};pub struct MetalSparseHeapPool {@@ -40,8 +40,8 @@ impl MetalSparseHeapPool {) -> Result<(), MetalError> {let mut pages_to_alloc = pages;for heap in self.heaps.iter() {- for free_pages_range in heap.lock().free_pages().iter() {- pages_to_alloc -= min(free_pages_range.len(), pages_to_alloc);+ for free_pages_range in heap.lock().free_pages() {+ pages_to_alloc -= min(free_pages_range.iter().len(), pages_to_alloc);}}if pages_to_alloc == 0 {@@ -62,16 +62,16 @@ impl MetalSparseHeapPool {&mut self,context: &MetalContext,buffer: &Retained<ProtocolObject<dyn MTLBuffer>>,- buffer_pages: &Range<usize>,+ buffer_pages: Range<usize>,) -> Result<Vec<MetalSparseMappingOpsBatch>, MetalError> {- self.ensure_enough_free_pages(context, buffer_pages.len())?;+ self.ensure_enough_free_pages(context, buffer_pages.iter().len())?;- let mut pages_to_map = buffer_pages.clone();+ let mut pages_to_map = buffer_pages;let mut batches: Vec<MetalSparseMappingOpsBatch> = Vec::new();for heap in self.heaps.iter() {let mut heap_mtl_operations: Vec<MTL4UpdateSparseBufferMappingOperation> = Vec::new();- for heap_free_pages_range in heap.lock().free_pages().iter() {- let map_pages_count = min(heap_free_pages_range.len(), pages_to_map.len());+ for heap_free_pages_range in heap.lock().free_pages() {+ let map_pages_count = min(heap_free_pages_range.iter().len(), pages_to_map.iter().len());if map_pages_count == 0 {break;}@@ -102,7 +102,7 @@ impl MetalSparseHeapPool {pub fn create_unmap_operations(&self,buffer: &Retained<ProtocolObject<dyn MTLBuffer>>,- buffer_pages: &Range<usize>,+ buffer_pages: Range<usize>,) -> Vec<MetalSparseMappingOpsBatch> {let mut batches: Vec<MetalSparseMappingOpsBatch> = Vec::new();@@ -111,7 +111,7 @@ impl MetalSparseHeapPool {let mut heap_mtl_operations: Vec<MTL4UpdateSparseBufferMappingOperation> = Vec::new();for (heap_range, mapping) in heap.lock().mappings_for(buffer_address) {- let mapped_buffer_pages = mapping.buffer_pages_for(&heap_range);+ let mapped_buffer_pages = mapping.buffer_pages_for(heap_range);let unmap_start_page = max(buffer_pages.start, mapped_buffer_pages.start);let unmap_end_page = min(buffer_pages.end, mapped_buffer_pages.end);if unmap_start_page < unmap_end_page {@@ -174,5 +174,5 @@ impl MetalSparseHeapPool {}#[cfg(test)]-#[path = "../../../../unit/backends/metal/sparse/sparse_heap_pool_test.rs"]+#[path = "../../../../../unit/backends/metal/sparse/sparse_heap_pool_test.rs"]mod tests;diff --git a/crates/uzu-engine/src/backends/metal/sparse/sparse_utils.rs b/crates/uzu-engine/src/backends/metal/buffer/sparse/sparse_utils.rssimilarity index 87%rename from crates/uzu-engine/src/backends/metal/sparse/sparse_utils.rsrename to crates/uzu-engine/src/backends/metal/buffer/sparse/sparse_utils.rsindex 370fdbe8d..e1154aeed 100644--- a/crates/uzu-engine/src/backends/metal/sparse/sparse_utils.rs+++ b/crates/uzu-engine/src/backends/metal/buffer/sparse/sparse_utils.rs@@ -1,10 +1,10 @@-use std::{ops::Range, sync::Arc};+use std::{range::Range, sync::Arc};use metal::{MTL4UpdateSparseBufferMappingOperation, MTLBuffer};use objc2::{rc::Retained, runtime::ProtocolObject};use parking_lot::Mutex;-use crate::backends::metal::sparse::sparse_heap::MetalSparseHeap;+use crate::backends::metal::buffer::sparse::sparse_heap::MetalSparseHeap;#[derive(Clone, PartialEq)]pub(crate) struct MetalSparseHeapBufferMapping {@@ -28,11 +28,11 @@ impl MetalSparseHeapBufferMapping {pub fn buffer_pages_for(&self,- heap_range: &Range<usize>,+ heap_range: Range<usize>,) -> Range<usize> {let start = self.buffer_page_anchor + (heap_range.start - self.heap_page_anchor);let end = self.buffer_page_anchor + (heap_range.end - self.heap_page_anchor);- start..end+ (start..end).into()}}diff --git a/crates/uzu-engine/src/backends/metal/command_buffer.rs b/crates/uzu-engine/src/backends/metal/command_buffer.rsindex 6f393e899..194b581db 100644--- a/crates/uzu-engine/src/backends/metal/command_buffer.rs+++ b/crates/uzu-engine/src/backends/metal/command_buffer.rs@@ -1,253 +1,249 @@use std::{- iter::{chain, once},- sync::{Arc, LazyLock},+ range::Range,+ sync::{Arc, mpsc},time::Duration,};-use itertools::Itertools;use metal::{- MTLBlitCommandEncoder, MTLBlitCommandEncoderExt, MTLCommandBuffer, MTLCommandBufferExt, MTLCommandBufferStatus,- MTLCommandEncoder, MTLCommandEncoderExt, MTLCommandQueue, MTLComputeCommandEncoder,+ MTL4ArgumentTable, MTL4ArgumentTableDescriptor, MTL4CommandAllocator, MTL4CommandBuffer, MTL4CommandBufferExt,+ MTL4CommandEncoder, MTL4CommandEncoderExt, MTL4CommandQueueExt, MTL4CommitFeedback, MTL4CommitFeedbackExt,+ MTL4CommitFeedbackHandler, MTL4CommitOptions, MTL4ComputeCommandEncoder, MTL4ComputeCommandEncoderExt,+ MTL4VisibilityOptions, MTLDeviceExt, MTLStages,};use objc2::{rc::Retained, runtime::ProtocolObject};+use rangemap::RangeSet;use crate::backends::{common::{- AccessFlags, Buffer, BufferRangeMut, BufferRangeRef, CommandBuffer, CommandBufferCompleted,- CommandBufferEncoding, CommandBufferExecutable, CommandBufferInitial, CommandBufferPending,+ Backend, BufferMut, BufferRef, CommandBuffer, CommandBufferCompleted, CommandBufferEncoding,+ CommandBufferExecutable, CommandBufferPending, Context, allocator::bump::BumpAllocator,},- metal::{Metal, MetalContext, error::MetalError},+ metal::{Metal, MetalContext, buffer::MetalBufferExt, error::MetalError},};-static DEBUG_ENCODER_LABELS: LazyLock<bool> = LazyLock::new(|| std::env::var("UZU_METAL_DEBUG_ENCODER_LABELS").is_ok());-pub struct MetalCommandBuffer;impl CommandBuffer for MetalCommandBuffer {type Backend = Metal;- type Initial = MetalCommandBufferInitial;type Encoding = MetalCommandBufferEncoding;type Executable = MetalCommandBufferExecutable;type Pending = MetalCommandBufferPending;type Completed = MetalCommandBufferCompleted;}-pub struct MetalCommandBufferInitial {- command_buffer: Retained<ProtocolObject<dyn MTLCommandBuffer>>,- context: Arc<MetalContext>,-}--impl MetalCommandBufferInitial {- pub fn new(- command_buffer: Retained<ProtocolObject<dyn MTLCommandBuffer>>,- context: Arc<MetalContext>,- ) -> Self {- Self {- command_buffer,- context,- }- }-}--impl CommandBufferInitial for MetalCommandBufferInitial {- type CommandBuffer = MetalCommandBuffer;-- fn start_encoding(self) -> MetalCommandBufferEncoding {- MetalCommandBufferEncoding {- command_buffer: self.command_buffer,- encoding_state: MetalCommandBufferEncodingEncodingState::None,- debug_group_stack: vec![],- context: self.context,- }- }-}--enum MetalCommandBufferEncodingEncodingState {- None,- Compute(Retained<ProtocolObject<dyn MTLComputeCommandEncoder>>),- Blit(Retained<ProtocolObject<dyn MTLBlitCommandEncoder>>),+pub(super) struct Access {+ pub(super) range: Range<u64>,+ pub(super) write: bool,}pub struct MetalCommandBufferEncoding {- command_buffer: Retained<ProtocolObject<dyn MTLCommandBuffer>>,- encoding_state: MetalCommandBufferEncodingEncodingState,- debug_group_stack: Vec<String>,- context: Arc<MetalContext>,+ command_allocator: Retained<ProtocolObject<dyn MTL4CommandAllocator>>,+ command_buffer: Retained<ProtocolObject<dyn MTL4CommandBuffer>>,+ pub(super) compute_encoder: Retained<ProtocolObject<dyn MTL4ComputeCommandEncoder>>,+ pub(super) argument_table: Retained<ProtocolObject<dyn MTL4ArgumentTable>>,+ reads: RangeSet<u64>,+ writes: RangeSet<u64>,+ constant_allocator: Option<BumpAllocator<<Metal as Backend>::GlobalBuffer>>,+ allocation_pool: Arc<<Metal as Backend>::AllocationPool>,+ pub(super) context: Arc<MetalContext>,}impl MetalCommandBufferEncoding {- fn ensure_none(&mut self) {- let encoder: &ProtocolObject<dyn MTLCommandEncoder> = match &self.encoding_state {- MetalCommandBufferEncodingEncodingState::None => return,- MetalCommandBufferEncodingEncodingState::Compute(compute_encoder) => compute_encoder.as_ref(),- MetalCommandBufferEncodingEncodingState::Blit(blit_encoder) => blit_encoder.as_ref(),+ pub fn new(+ context: Arc<MetalContext>,+ name: Option<&str>,+ allocation_pool: Option<Arc<<Metal as Backend>::AllocationPool>>,+ ) -> Result<Self, MetalError> {+ let (command_allocator, command_buffer) = if let mut command_buffer_cache = context.command_buffer_cache.lock()+ && let Some(command_buffer_cached) = command_buffer_cache.pop()+ {+ command_buffer_cached.command_allocator.reset();+ (command_buffer_cached.command_allocator, command_buffer_cached.command_buffer)+ } else {+ (+ context.device.new_command_allocator().ok_or(MetalError::CannotCreateCommandBuffer)?,+ context.device.new_mtl4_command_buffer().ok_or(MetalError::CannotCreateCommandBuffer)?,+ )};- for _ in &self.debug_group_stack {- encoder.pop_debug_group();- }+ command_buffer.set_label(name);- encoder.end_encoding();+ command_buffer.begin_command_buffer_with_allocator(&command_allocator);- self.encoding_state = MetalCommandBufferEncodingEncodingState::None;- }+ let compute_encoder = command_buffer.compute_command_encoder().unwrap();- pub(super) fn ensure_compute(&mut self) -> &mut Retained<ProtocolObject<dyn MTLComputeCommandEncoder>> {- if !matches!(self.encoding_state, MetalCommandBufferEncodingEncodingState::Compute(_)) {- self.ensure_none();- let compute_encoder =- self.command_buffer.compute_command_encoder().expect("Failed to create compute command encoder");- self.ensure_common(compute_encoder.as_ref());- self.encoding_state = MetalCommandBufferEncodingEncodingState::Compute(compute_encoder);- }+ compute_encoder.barrier_after_queue_stages_before_stages_visibility_options(+ MTLStages::Dispatch | MTLStages::Blit | MTLStages::ResourceState,+ MTLStages::Dispatch | MTLStages::Blit,+ MTL4VisibilityOptions::Device,+ );- let MetalCommandBufferEncodingEncodingState::Compute(compute_encoder) = &mut self.encoding_state else {- unreachable!()- };- compute_encoder- }+ let argument_table_descriptor = MTL4ArgumentTableDescriptor::new();+ argument_table_descriptor.set_max_buffer_bind_count(31);+ let argument_table = context+ .device+ .new_argument_table_with_descriptor(&argument_table_descriptor)+ .map_err(|error| MetalError::CannotCreateArgumentTable(error.to_string()))?;+ compute_encoder.set_argument_table(Some(&argument_table));- fn ensure_blit(&mut self) -> &mut Retained<ProtocolObject<dyn MTLBlitCommandEncoder>> {- if !matches!(self.encoding_state, MetalCommandBufferEncodingEncodingState::Blit(_)) {- self.ensure_none();- let blit_encoder =- self.command_buffer.blit_command_encoder().expect("Failed to create blit command encoder");- self.ensure_common(blit_encoder.as_ref());- self.encoding_state = MetalCommandBufferEncodingEncodingState::Blit(blit_encoder);- }+ let constant_allocator = BumpAllocator::new(256 * 1024);- let MetalCommandBufferEncodingEncodingState::Blit(blit_encoder) = &mut self.encoding_state else {- unreachable!()- };- blit_encoder+ let allocation_pool = allocation_pool.unwrap_or_else(|| context.create_allocation_pool());++ Ok(Self {+ command_allocator,+ command_buffer,+ compute_encoder,+ argument_table,+ reads: RangeSet::new(),+ writes: RangeSet::new(),+ constant_allocator: Some(constant_allocator),+ allocation_pool,+ context,+ })}- fn ensure_common(- &self,- encoder: &ProtocolObject<dyn MTLCommandEncoder>,+ pub(super) fn access(+ &mut self,+ accesses: &[Access],) {- let command_buffer_label = self.command_buffer.label();- let label = if *DEBUG_ENCODER_LABELS && (command_buffer_label.is_some() || !self.debug_group_stack.is_empty()) {- Some(- chain(- once(command_buffer_label.as_deref()),- self.debug_group_stack.iter().map(|label| Some(label.as_str())),- )- .flatten()- .join("."),- )- } else {- command_buffer_label- };- if label.is_some() {- encoder.set_label(label.as_deref());+ // TODO: more fine grained barriers+ if accesses.iter().any(|access| {+ self.writes.overlaps(&access.range.into()) || (access.write && self.reads.overlaps(&access.range.into()))+ }) {+ self.compute_encoder.barrier_after_encoder_stages_before_encoder_stages_visibility_options(+ MTLStages::Dispatch | MTLStages::Blit,+ MTLStages::Dispatch | MTLStages::Blit,+ MTL4VisibilityOptions::Device,+ );+ self.reads.clear();+ self.writes.clear();}- for debug_group in &self.debug_group_stack {- encoder.push_debug_group(debug_group);- }- }-}-impl Drop for MetalCommandBufferEncoding {- fn drop(&mut self) {- self.ensure_none();+ for access in accesses {+ if access.write {+ self.writes.insert(access.range.into());+ } else {+ self.reads.insert(access.range.into());+ }+ }}}impl CommandBufferEncoding for MetalCommandBufferEncoding {type CommandBuffer = MetalCommandBuffer;- fn encode_copy<Src: Buffer<Backend = Metal>, Dst: Buffer<Backend = Metal>>(+ fn context(&self) -> &MetalContext {+ &self.context+ }++ fn allocate_constant(+ &mut self,+ size: usize,+ ) -> Result<<Metal as Backend>::ConstantBuffer, MetalError> {+ self.constant_allocator.as_mut().unwrap().allocate(size, |size| self.context.create_buffer(size))+ }++ fn allocate_scratch(&mut self,- src: BufferRangeRef<Src>,- dst: BufferRangeMut<Dst>,+ size: usize,+ ) -> Result<<Metal as Backend>::ScratchBuffer, MetalError> {+ self.allocation_pool.allocate(size, |size| self.context.create_buffer(size))+ }++ fn encode_copy(+ &mut self,+ src: impl BufferRef<Backend = Metal>,+ dst: impl BufferMut<Backend = Metal>,) {- let src_range = src.range();- let dst_range = dst.range();- assert_eq!(src_range.len(), dst_range.len());-- self.ensure_blit().copy_buffer_to_buffer(- (src.buffer() as &dyn Buffer<Backend = Metal>).downcast(),- src_range.start,- (dst.buffer() as &dyn Buffer<Backend = Metal>).downcast(),- dst_range.start,- src_range.len(),+ let (src, src_range) = src.parts();+ let (dst, dst_range) = dst.parts();+ assert_eq!(src_range.iter().len(), dst_range.iter().len());++ self.access(&[+ Access {+ range: src.gpu_address_subrange(src_range),+ write: false,+ },+ Access {+ range: dst.gpu_address_subrange(dst_range),+ write: true,+ },+ ]);++ let (src_buffer, src_offset) = src.downcast();+ let (dst_buffer, dst_offset) = dst.downcast();+ self.compute_encoder.copy_from_buffer_source_offset_to_buffer_destination_offset_size(+ src_buffer,+ src_offset + src_range.start,+ dst_buffer,+ dst_offset + dst_range.start,+ src_range.iter().len(),);}- fn encode_fill<Dst: Buffer<Backend = Metal>>(+ fn encode_fill(&mut self,- dst: BufferRangeMut<Dst>,+ dst: impl BufferMut<Backend = Metal>,value: u8,) {- let range = dst.range();+ let (dst, range) = dst.parts();assert!(range.end > range.start);assert!(range.start.is_multiple_of(4) && range.end.is_multiple_of(4));- self.ensure_blit().fill_buffer_range_value(- (dst.buffer() as &dyn Buffer<Backend = Metal>).downcast(),- range,- value,- );- }+ self.access(&[Access {+ range: dst.gpu_address_subrange(range),+ write: true,+ }]);- fn encode_barrier(- &mut self,- _after: AccessFlags,- _before: AccessFlags,- ) {+ let (buffer, offset) = dst.downcast();+ self.compute_encoder.fill_buffer_range_value(buffer, offset + range.start..offset + range.end, value);}+ // TODO: maybe port previous debug command_buffer labelsfn push_debug_group(&mut self,name: &str,) {- if *DEBUG_ENCODER_LABELS {- self.ensure_none();- }-- self.debug_group_stack.push(name.to_string());-- match &self.encoding_state {- MetalCommandBufferEncodingEncodingState::None => (),- MetalCommandBufferEncodingEncodingState::Compute(compute_encoder) => compute_encoder.push_debug_group(name),- MetalCommandBufferEncodingEncodingState::Blit(blit_encoder) => {- let encoder: &ProtocolObject<dyn MTLCommandEncoder> = blit_encoder.as_ref();- encoder.push_debug_group(name);- },- }+ ProtocolObject::<dyn MTL4CommandEncoder>::push_debug_group(self.compute_encoder.as_ref(), name);}fn pop_debug_group(&mut self) {- if *DEBUG_ENCODER_LABELS {- self.ensure_none();- }-- self.debug_group_stack.pop().expect("debug group stack underflow");-- match &self.encoding_state {- MetalCommandBufferEncodingEncodingState::None => (),- MetalCommandBufferEncodingEncodingState::Compute(compute_encoder) => compute_encoder.pop_debug_group(),- MetalCommandBufferEncodingEncodingState::Blit(blit_encoder) => {- let encoder: &ProtocolObject<dyn MTLCommandEncoder> = blit_encoder.as_ref();- encoder.pop_debug_group();- },- }+ self.compute_encoder.pop_debug_group();}fn end_encoding(mut self) -> <Self::CommandBuffer as CommandBuffer>::Executable {- self.ensure_none();+ let constant_allocator = self.constant_allocator.take().unwrap();+ assert!(constant_allocator.is_done(), "attempted to end encoding while constants are still alive");MetalCommandBufferExecutable {+ command_allocator: self.command_allocator.clone(),command_buffer: self.command_buffer.clone(),+ constant_allocator,+ allocation_pool: self.allocation_pool.clone(),context: self.context.clone(),}}}+impl Drop for MetalCommandBufferEncoding {+ fn drop(&mut self) {+ self.compute_encoder.barrier_after_stages_before_queue_stages_visibility_options(+ MTLStages::Dispatch | MTLStages::Blit,+ MTLStages::Dispatch | MTLStages::Blit | MTLStages::ResourceState,+ MTL4VisibilityOptions::Device,+ );+ self.compute_encoder.end_encoding();+ self.command_buffer.end_command_buffer();+ }+}+pub struct MetalCommandBufferExecutable {- command_buffer: Retained<ProtocolObject<dyn MTLCommandBuffer>>,+ command_allocator: Retained<ProtocolObject<dyn MTL4CommandAllocator>>,+ command_buffer: Retained<ProtocolObject<dyn MTL4CommandBuffer>>,+ constant_allocator: BumpAllocator<<Metal as Backend>::GlobalBuffer>,+ allocation_pool: Arc<<Metal as Backend>::AllocationPool>,context: Arc<MetalContext>,}@@ -255,66 +251,73 @@ impl CommandBufferExecutable for MetalCommandBufferExecutable {type CommandBuffer = MetalCommandBuffer;fn submit(self) -> MetalCommandBufferPending {- let cmd_queue = self.command_buffer.command_queue();- let wait_value = self.context.timeline_get_and_increment();-- {- let cmd_buffer = cmd_queue.command_buffer().expect("Failed to create command buffer");- cmd_buffer.set_label(Some("sync (wait)"));- cmd_buffer.encode_wait_for_event_value(self.context.timeline_event(), wait_value);- cmd_buffer.commit();- }-- self.command_buffer.commit();+ let (sender, receiver) = mpsc::channel();++ let command_allocator = self.command_allocator.clone();+ let command_buffer = self.command_buffer.clone();+ let context_clone = self.context.clone();++ let constant_allocator = self.constant_allocator;+ let allocation_pool = self.allocation_pool.clone();+ let feedback_handler = move |feedback: &ProtocolObject<dyn MTL4CommitFeedback>| {+ let message = if let Some(error) = feedback.error() {+ Err(error.to_string())+ } else {+ Ok(Duration::from_secs_f64(feedback.gpu_end_time() - feedback.gpu_start_time()))+ };+ let _ = sender.send(message);+ context_clone.command_buffer_cache.lock().push(MetalCommandBufferCache {+ command_allocator: command_allocator.clone(),+ command_buffer: command_buffer.clone(),+ });+ let _keep_alive = (&constant_allocator, &allocation_pool);+ };- {- let cmd_buffer = cmd_queue.command_buffer().expect("Failed to create command buffer");- cmd_buffer.set_label(Some("sync (signal)"));- cmd_buffer.encode_signal_event_value(self.context.timeline_event(), wait_value + 1);- cmd_buffer.commit();- }+ let options = MTL4CommitOptions::new();+ options.add_feedback_handler(&MTL4CommitFeedbackHandler::new(feedback_handler));+ self.context.command_queue.commit_with_options(&[&self.command_buffer], &options);MetalCommandBufferPending {- command_buffer: self.command_buffer,+ allocation_pool: self.allocation_pool,+ receiver,}}}pub struct MetalCommandBufferPending {- command_buffer: Retained<ProtocolObject<dyn MTLCommandBuffer>>,+ allocation_pool: Arc<<Metal as Backend>::AllocationPool>,+ receiver: mpsc::Receiver<Result<Duration, String>>,}impl CommandBufferPending for MetalCommandBufferPending {type CommandBuffer = MetalCommandBuffer;fn wait_until_completed(self) -> Result<MetalCommandBufferCompleted, MetalError> {- self.command_buffer.wait_until_completed();-- match (self.command_buffer.status(), self.command_buffer.error()) {- (MTLCommandBufferStatus::Completed, None) => (),- (status, Some(nserror)) => {- return Err(MetalError::CommandBufferExecutionFailed(format!("{status:?}: {nserror:?}")));- },- (status, None) => return Err(MetalError::CommandBufferExecutionFailed(format!("{status:?}"))),- }-Ok(MetalCommandBufferCompleted {- command_buffer: self.command_buffer,+ gpu_execution_time: self+ .receiver+ .recv()+ .map_err(MetalError::CommandBufferWait)?+ .map_err(MetalError::CommandBufferExecution)?,+ _allocation_pool: self.allocation_pool,})}}pub struct MetalCommandBufferCompleted {- command_buffer: Retained<ProtocolObject<dyn MTLCommandBuffer>>,+ gpu_execution_time: Duration,+ _allocation_pool: Arc<<Metal as Backend>::AllocationPool>,}impl CommandBufferCompleted for MetalCommandBufferCompleted {type CommandBuffer = MetalCommandBuffer;fn gpu_execution_time(&self) -> Duration {- // They're always present, https://developer.apple.com/documentation/metal/mtlcommandbuffer/gpustarttime?language=objc- let start = self.command_buffer.gpu_start_time();- let end = self.command_buffer.gpu_end_time();- Duration::from_secs_f64(end - start)+ self.gpu_execution_time}}++pub struct MetalCommandBufferCache {+ command_allocator: Retained<ProtocolObject<dyn MTL4CommandAllocator>>,+ command_buffer: Retained<ProtocolObject<dyn MTL4CommandBuffer>>,+}diff --git a/crates/uzu-engine/src/backends/metal/context.rs b/crates/uzu-engine/src/backends/metal/context.rsindex 99765d566..1736faf99 100644--- a/crates/uzu-engine/src/backends/metal/context.rs+++ b/crates/uzu-engine/src/backends/metal/context.rs@@ -3,31 +3,33 @@ use std::{path::Path,sync::{Arc, Weak,- atomic::{AtomicU64, AtomicUsize, Ordering},+ atomic::{AtomicUsize, Ordering},},};-#[cfg(test)]-use metal::MTLSharedEvent;use metal::{- MTL4CommandQueue, MTL4CommandQueueExt, MTLBuffer, MTLCaptureDescriptor, MTLCaptureDestination, MTLCaptureManager,- MTLCaptureTarget, MTLCommandBufferExt, MTLCommandQueue, MTLCommandQueueExt, MTLComputePipelineState, MTLDevice,- MTLDeviceExt, MTLEvent, MTLFunctionConstantValues, MTLGPUFamily, MTLLibrary, MTLResourceOptions, MTLSparsePageSize,+ MTL4CommandQueue, MTL4CommandQueueExt, MTLCaptureDescriptor, MTLCaptureDestination, MTLCaptureManager,+ MTLCaptureTarget, MTLComputePipelineState, MTLDevice, MTLDeviceExt, MTLFunctionConstantValues, MTLGPUFamily,+ MTLLibrary, MTLResidencySet, MTLResidencySetDescriptor, MTLSparsePageSize,};use objc2::{rc::Retained, runtime::ProtocolObject};use parking_lot::{Mutex, MutexGuard};-use super::{- Metal,- error::MetalError,- metal_extensions::{DeviceExt, LibraryPipelineExtensions},-};use crate::backends::{- common::{Allocation, AllocationPool, AllocationType, Allocator, Backend, Context, DeviceCapabilities},+ common::{+ Backend, Context, DeviceCapabilities,+ allocator::{block::BlockAllocator, pool::PoolAllocator},+ },metal::{- command_buffer::MetalCommandBufferInitial,+ Metal,+ buffer::{+ dense::MetalDenseBuffer,+ sparse::{MetalSparseBuffer, MetalSparseHeapPool, MetalSparseMappingOpsBatch},+ },+ command_buffer::{MetalCommandBufferCache, MetalCommandBufferEncoding},decompression,- sparse::{MetalSparseBuffer, MetalSparseHeapPool, MetalSparseMappingOpsBatch},+ error::MetalError,+ metal_extensions::{DeviceExt, LibraryPipelineExtensions},},};@@ -39,18 +41,15 @@ pub struct MetalContext {pub apple_gpu_family: MTLGPUFamily,pub supports_mxu: bool,pub device_name: String,- pub command_queue: Retained<ProtocolObject<dyn MTLCommandQueue>>,- pub command_queue4: Retained<ProtocolObject<dyn MTL4CommandQueue>>,- timeline_event: Retained<ProtocolObject<dyn MTLEvent>>,- timeline_value: AtomicU64,- allocator: Arc<Allocator<Metal>>,+ pub(super) residency_set: Arc<Mutex<Retained<ProtocolObject<dyn MTLResidencySet>>>>,+ pub command_queue: Retained<ProtocolObject<dyn MTL4CommandQueue>>,+ pub(super) block_allocator: Arc<BlockAllocator<MetalDenseBuffer>>,peak_memory_usage: AtomicUsize,+ pub(super) command_buffer_cache: Mutex<Vec<MetalCommandBufferCache>>,library_cache: Mutex<HashMap<usize, Retained<ProtocolObject<dyn MTLLibrary>>>>,pipeline_cache: Mutex<HashMap<String, Retained<ProtocolObject<dyn MTLComputePipelineState>>>>,sparse_heap_pool: Mutex<MetalSparseHeapPool>,weak_self: Weak<MetalContext>,- #[cfg(test)]- timeline_shared_event: Retained<ProtocolObject<dyn MTLSharedEvent>>,}impl MetalContext {@@ -86,7 +85,7 @@ impl MetalContext {Ok(library)}- pub fn compute_pipeline_state(+ pub(super) fn compute_pipeline_state(&self,library_data: &'static [u8],library_compressed: bool,@@ -113,28 +112,9 @@ impl MetalContext {&self,mappings: &[MetalSparseMappingOpsBatch],) {- if mappings.is_empty() {- return;- }-- let wait_value = self.timeline_get_and_increment();- self.command_queue4.wait_for_event_value(&self.timeline_event, wait_value);for op in mappings {- self.command_queue4.update_buffer_mappings(&op.buffer, Some(op.heap.lock().heap()), &op.mtl_operations);+ self.command_queue.update_buffer_mappings(&op.buffer, Some(op.heap.lock().heap()), &op.mtl_operations);}- self.command_queue4.signal_event_value(&self.timeline_event, wait_value + 1);-- // This line prevent tests from freezing, showing pink screen and shutting down computer- #[cfg(test)]- self.timeline_shared_event.wait_until_signaled_value_timeout_ms(wait_value, 10);- }-- pub(super) fn timeline_get_and_increment(&self) -> u64 {- self.timeline_value.fetch_add(1, Ordering::Release)- }-- pub(super) fn timeline_event(&self) -> &ProtocolObject<dyn MTLEvent> {- &self.timeline_event}}@@ -142,43 +122,42 @@ impl Context for MetalContext {type Backend = Metal;fn new() -> Result<Arc<Self>, MetalError> {- let device: Retained<ProtocolObject<dyn MTLDevice>> =- <dyn MTLDevice>::system_default().ok_or(MetalError::CannotOpenDevice)?;+ let device = <dyn MTLDevice>::system_default().ok_or(MetalError::CannotOpenDevice)?;let device_name = device.name();let gpu_core_count = device.gpu_core_count();let apple_gpu_family = device.newest_supported_apple_gpu_family();let supports_mxu = device.supports_mxu();- let command_queue =- device.new_command_queue_with_max_command_buffer_count(1024).ok_or(MetalError::CannotCreateCommandQueue)?;+ let residency_set_descriptor = MTLResidencySetDescriptor::new();+ residency_set_descriptor.set_initial_capacity(1024);+ let residency_set = device+ .new_residency_set_with_descriptor(&residency_set_descriptor)+ .map_err(|nserror| MetalError::CannotCreateResidencySet(nserror.to_string()))?;++ let command_queue = device.new_mtl4_command_queue().ok_or(MetalError::CannotCreateCommandQueue)?;+ command_queue.add_residency_set(&residency_set);- let command_queue4 = device.new_mtl4_command_queue().ok_or(MetalError::CannotCreateCommandQueueMtl4)?;+ let block_allocator = BlockAllocator::new(16 * 1024);let page_size = MTLSparsePageSize::KB256;- let heap_capacity = Metal::ALLOCATION_GRANULARITY;+ let heap_capacity = 8 * 1024 * 1024;let sparse_pool = MetalSparseHeapPool::new(page_size, heap_capacity);- let timeline_event = device.new_event().ok_or(MetalError::CannotCreateEvent)?;- #[cfg(test)]- let timeline_shared_event = device.new_shared_event().ok_or(MetalError::CannotCreateEvent)?;- Ok(Arc::new_cyclic(|weak_self| Self {+ Ok(Arc::new_cyclic(|weak_self: &Weak<Self>| Self {device,gpu_core_count,apple_gpu_family,supports_mxu,device_name,+ residency_set: Arc::new(Mutex::new(residency_set)),command_queue,- command_queue4,- timeline_event,- timeline_value: AtomicU64::new(0),- allocator: Allocator::new(weak_self.clone()),+ block_allocator,peak_memory_usage: AtomicUsize::new(0),+ command_buffer_cache: Mutex::new(Vec::with_capacity(32)),library_cache: Mutex::new(HashMap::new()),pipeline_cache: Mutex::new(HashMap::new()),sparse_heap_pool: Mutex::new(sparse_pool),weak_self: weak_self.clone(),- #[cfg(test)]- timeline_shared_event,}))}@@ -186,43 +165,19 @@ impl Context for MetalContext {Some(&self.device_name)}- fn create_buffer(+ fn create_command_buffer(&self,- size: usize,- ) -> Result<Retained<ProtocolObject<dyn MTLBuffer>>, MetalError> {- let buffer = self- .device- .new_buffer(size, MTLResourceOptions::STORAGE_MODE_SHARED)- .ok_or(MetalError::CannotCreateBuffer)?;-- self.update_peak_memory_usage();-- Ok(buffer)+ name: Option<&str>,+ allocation_pool: Option<Arc<<Metal as Backend>::AllocationPool>>,+ ) -> Result<MetalCommandBufferEncoding, MetalError> {+ MetalCommandBufferEncoding::new(self.weak_self.upgrade().unwrap(), name, allocation_pool)}- fn create_allocation(+ fn create_buffer(&self,size: usize,- allocation_type: AllocationType<Metal>,- ) -> Result<Allocation<Metal>, MetalError> {- self.allocator.allocate(size, allocation_type)- }-- fn create_allocation_pool(- &self,- reusable: bool,- ) -> AllocationPool<Metal> {- self.allocator.create_pool(reusable)- }-- fn create_command_buffer(- &self,- name: Option<&str>,- ) -> Result<MetalCommandBufferInitial, MetalError> {- let command_buffer = self.command_queue.command_buffer().ok_or(MetalError::CannotCreateCommandBuffer)?;- command_buffer.set_label(name);- let context = self.weak_self.upgrade().unwrap(); // never fails- Ok(MetalCommandBufferInitial::new(command_buffer, context))+ ) -> Result<<Metal as Backend>::GlobalBuffer, MetalError> {+ self.block_allocator.allocate(size, |size| MetalDenseBuffer::new(&self.weak_self.upgrade().unwrap(), size))}fn create_sparse_buffer(@@ -234,6 +189,10 @@ impl Context for MetalContext {MetalSparseBuffer::new(context, capacity, sparse_page_size)}+ fn create_allocation_pool(&self) -> Arc<<Metal as Backend>::AllocationPool> {+ PoolAllocator::new()+ }+fn peak_memory_usage(&self) -> Option<usize> {Some(self.peak_memory_usage.load(Ordering::Relaxed))}@@ -248,16 +207,12 @@ impl Context for MetalContext {&self,trace_path: &Path,) -> Result<(), <Self::Backend as Backend>::Error> {- let capture_manager = MTLCaptureManager::shared_capture_manager();let capture_descriptor = MTLCaptureDescriptor::new();capture_descriptor.set_destination(MTLCaptureDestination::GPUTraceDocument);capture_descriptor.set_output_path(Some(&trace_path.with_added_extension("gputrace")));+ capture_descriptor.set_capture_object(Some(&MTLCaptureTarget::Device(self.device.clone())));- self.command_queue.set_label(Some("uzu_command_queue"));- let capture_target = MTLCaptureTarget::CommandQueue(self.command_queue.clone());- capture_descriptor.set_capture_object(Some(&capture_target));-- capture_manager+ MTLCaptureManager::shared_capture_manager().start_capture_with_descriptor(&capture_descriptor).map_err(|error| MetalError::CannotStartGpuCapture(error.to_string()))?;diff --git a/crates/uzu-engine/src/backends/metal/dense_buffer.rs b/crates/uzu-engine/src/backends/metal/dense_buffer.rsdeleted file mode 100644index 761821331..000000000--- a/crates/uzu-engine/src/backends/metal/dense_buffer.rs+++ /dev/null@@ -1,25 +0,0 @@-use std::{os::raw::c_void, ptr::NonNull};--use metal::MTLBuffer;-use objc2::{rc::Retained, runtime::ProtocolObject};--use super::Metal;-use crate::backends::common::{Buffer, DenseBuffer};--impl Buffer for Retained<ProtocolObject<dyn MTLBuffer>> {- type Backend = Metal;-- fn gpu_ptr(&self) -> usize {- self.gpu_address() as usize- }-- fn size(&self) -> usize {- self.length()- }-}--impl DenseBuffer for Retained<ProtocolObject<dyn MTLBuffer>> {- fn cpu_ptr(&self) -> NonNull<c_void> {- self.contents()- }-}diff --git a/crates/uzu-engine/src/backends/metal/error.rs b/crates/uzu-engine/src/backends/metal/error.rsindex 0b508ce03..ca4b89fe8 100644--- a/crates/uzu-engine/src/backends/metal/error.rs+++ b/crates/uzu-engine/src/backends/metal/error.rs@@ -1,4 +1,4 @@-use std::error::Error as StdError;+use std::{error::Error as StdError, sync::mpsc::RecvError};use thiserror::Error;@@ -11,22 +11,24 @@ use crate::backends::{pub enum MetalError {#[error("Cannot open device")]CannotOpenDevice,+ #[error("Cannot create residency set: {0}")]+ CannotCreateResidencySet(String),#[error("Cannot start gpu capture {0}")]CannotStartGpuCapture(String),#[error("Cannot create library: {0}")]CannotCreateLibrary(String),#[error("Cannot create command queue")]CannotCreateCommandQueue,- #[error("Cannot create command Metal 4 queue")]- CannotCreateCommandQueueMtl4,#[error("Cannot create buffer")]CannotCreateBuffer,#[error("Cannot create command buffer")]CannotCreateCommandBuffer,+ #[error("Cannot create argument table: {0}")]+ CannotCreateArgumentTable(String),+ #[error("Error waiting for command buffer: {0}")]+ CommandBufferWait(RecvError),#[error("Command buffer execution failed: {0}")]- CommandBufferExecutionFailed(String),- #[error("Cannot create event")]- CannotCreateEvent,+ CommandBufferExecution(String),#[error("Cannot create function: {0}")]CannotCreateFunction(String),#[error("Cannot create pipeline state for {function_name}: {error}")]diff --git a/crates/uzu-engine/src/backends/metal/kernel/attention/fallback.rs b/crates/uzu-engine/src/backends/metal/kernel/attention/fallback.rsindex 589d67806..dec62f708 100644--- a/crates/uzu-engine/src/backends/metal/kernel/attention/fallback.rs+++ b/crates/uzu-engine/src/backends/metal/kernel/attention/fallback.rs@@ -3,7 +3,7 @@ use parking_lot::Mutex;use crate::{backends::{common::{- Allocation, BufferArg, Encoder, Kernels,+ Backend, BufferRef, CommandBufferEncoding, Kernels,kernel::{AttentionArguments, AttentionKernelConfig, SoftmaxKernel,matmul::{MatmulA, MatmulArguments, MatmulB, MatmulDOps, MatmulKernel},@@ -11,6 +11,7 @@ use crate::{},metal::{Metal,+ command_buffer::MetalCommandBufferEncoding,context::MetalContext,error::MetalError,kernel::{@@ -79,11 +80,18 @@ impl AttentionFallback {})}- pub fn encode<'a, KT: BufferArg<'a, Metal>, VT: BufferArg<'a, Metal>>(+ pub fn encode(&self,- arguments: AttentionArguments<'a, Metal, KT, VT>,- encoder: &mut Encoder<Metal>,- ) -> Result<Allocation<Metal>, MetalError> {+ arguments: AttentionArguments<+ '_,+ Metal,+ impl BufferRef<Backend = Metal>,+ impl BufferRef<Backend = Metal>,+ impl BufferRef<Backend = Metal>,+ impl BufferRef<Backend = Metal>,+ >,+ command_buffer: &mut MetalCommandBufferEncoding,+ ) -> Result<<Metal as Backend>::ScratchBuffer, MetalError> {assert!(arguments.trie.is_none(), "fallback does not support trie");let suffix_length = arguments.suffix_length;let sequence_length = arguments.cache.prefix_len() + suffix_length;@@ -92,12 +100,12 @@ impl AttentionFallback {let dt_bytes = self.data_type.size_in_bytes();let head_dim_bytes = self.head_dim as usize * dt_bytes;let group_rows = (gqa_factor * suffix_length) as usize;- let mut output =- encoder.allocate_constant_for_shape(&[suffix_length, self.num_q_heads, self.head_dim], self.data_type)?;- let mut scores =- encoder.allocate_scratch_for_shape(&[self.num_q_heads, suffix_length, sequence_length], self.data_type)?;- let mut group_scores =- encoder.allocate_scratch_for_shape(&[gqa_factor * suffix_length, sequence_length], self.data_type)?;+ let mut output = command_buffer+ .allocate_scratch_for_shape(&[suffix_length, self.num_q_heads, self.head_dim], self.data_type)?;+ let mut scores = command_buffer+ .allocate_scratch_for_shape(&[self.num_q_heads, suffix_length, sequence_length], self.data_type)?;+ let mut group_scores = command_buffer+ .allocate_scratch_for_shape(&[gqa_factor * suffix_length, sequence_length], self.data_type)?;for group_index in 0..self.num_groups {self.matmul.lock().encode(@@ -107,7 +115,7 @@ impl AttentionFallback {offset: group_index as usize * group_rows * head_dim_bytes,},b: MatmulB::FullPrecision {- b: (arguments.keys, group_index as usize * head_dim_bytes),+ b: arguments.keys.subrange(group_index as usize * head_dim_bytes..),},b_leading_dimension: Some(self.num_groups * self.head_dim),b_transpose: true,@@ -116,31 +124,38 @@ impl AttentionFallback {ab_scale: scale,..MatmulDOps::none()},- gather_indices: None,+ gather_indices: None::<&<Metal as Backend>::ScratchBuffer>,m: gqa_factor * suffix_length,n: sequence_length,k: self.head_dim,},- encoder,+ command_buffer,)?;self.scatter_scores.encode(&group_scores,&mut scores,arguments.cache.ring_params(),- None::<&Allocation<Metal>>,+ None::<&<Metal as Backend>::ConstantBuffer>,self.sliding_window_size,group_index,gqa_factor,sequence_length,suffix_length,gqa_factor * suffix_length * sequence_length,- encoder,+ command_buffer,);}- self.softmax.encode(&mut scores, arguments.sinks, sequence_length, self.num_q_heads, suffix_length, encoder);+ self.softmax.encode(+ &mut scores,+ arguments.sinks,+ sequence_length,+ self.num_q_heads,+ suffix_length,+ command_buffer,+ );let mut group_output =- encoder.allocate_scratch_for_shape(&[gqa_factor * suffix_length, self.head_dim], self.data_type)?;+ command_buffer.allocate_scratch_for_shape(&[gqa_factor * suffix_length, self.head_dim], self.data_type)?;for group_index in 0..self.num_groups {self.matmul.lock().encode(MatmulArguments {@@ -149,18 +164,18 @@ impl AttentionFallback {offset: group_index as usize * group_rows * sequence_length as usize * dt_bytes,},b: MatmulB::FullPrecision {- b: (arguments.values, group_index as usize * head_dim_bytes),+ b: arguments.values.subrange(group_index as usize * head_dim_bytes..),},b_leading_dimension: Some(self.num_groups * self.head_dim),b_transpose: false,d: &mut group_output,d_transform: MatmulDOps::none(),- gather_indices: None,+ gather_indices: None::<&<Metal as Backend>::ScratchBuffer>,m: gqa_factor * suffix_length,n: self.head_dim,k: sequence_length,},- encoder,+ command_buffer,)?;self.scatter_values.encode(&group_output,@@ -171,7 +186,7 @@ impl AttentionFallback {self.num_q_heads,self.head_dim,gqa_factor * suffix_length * self.head_dim,- encoder,+ command_buffer,);}Ok(output)diff --git a/crates/uzu-engine/src/backends/metal/kernel/attention/gemm.rs b/crates/uzu-engine/src/backends/metal/kernel/attention/gemm.rsindex cecf5fe2b..d8e93eb1a 100644--- a/crates/uzu-engine/src/backends/metal/kernel/attention/gemm.rs+++ b/crates/uzu-engine/src/backends/metal/kernel/attention/gemm.rs@@ -5,11 +5,14 @@ use parking_lot::{MappedMutexGuard, Mutex, MutexGuard};use crate::{backends::{common::{- Allocation, BufferArg, Encoder,+ Backend, BufferRef, CommandBufferEncoding,gpu_types::AttnParams,kernel::{AttentionArguments, AttentionKernelConfig},},- metal::{Metal, context::MetalContext, error::MetalError, kernel::AttentionGemmMetalKernel},+ metal::{+ Metal, command_buffer::MetalCommandBufferEncoding, context::MetalContext, error::MetalError,+ kernel::AttentionGemmMetalKernel,+ },},data_type::DataType,};@@ -108,18 +111,25 @@ impl AttentionGemm {Ok(MutexGuard::map(kernels, |kernels| kernels.get_mut(&key).expect("kernel was just initialized")))}- pub fn encode<'a, KT: BufferArg<'a, Metal>, VT: BufferArg<'a, Metal>>(+ pub fn encode(&self,- arguments: AttentionArguments<'a, Metal, KT, VT>,- encoder: &mut Encoder<Metal>,- ) -> Result<Allocation<Metal>, MetalError> {- let mut output = encoder- .allocate_constant_for_shape(&[arguments.suffix_length, self.num_q_heads, self.head_dim], self.data_type)?;+ arguments: AttentionArguments<+ '_,+ Metal,+ impl BufferRef<Backend = Metal>,+ impl BufferRef<Backend = Metal>,+ impl BufferRef<Backend = Metal>,+ impl BufferRef<Backend = Metal>,+ >,+ command_buffer: &mut MetalCommandBufferEncoding,+ ) -> Result<<Metal as Backend>::ScratchBuffer, MetalError> {+ let mut output = command_buffer+ .allocate_scratch_for_shape(&[arguments.suffix_length, self.num_q_heads, self.head_dim], self.data_type)?;let use_mxu = arguments.suffix_length >= 64&& matches!(self.data_type, DataType::BF16)&& matches!(self.head_dim, 64 | 128)- && encoder.context().supports_mxu;+ && command_buffer.context().supports_mxu;let (bq, bk) = if use_mxu {(64, 32)} else {@@ -151,7 +161,7 @@ impl AttentionGemm {align_k: params.k_rem == 0,is_trie: arguments.trie.is_some(),};- let kernel = self.get_or_create(encoder.context(), key)?;+ let kernel = self.get_or_create(command_buffer.context(), key)?;kernel.encode(arguments.queries,arguments.keys,@@ -164,7 +174,7 @@ impl AttentionGemm {arguments.sinks,self.num_q_heads,arguments.suffix_length,- encoder,+ command_buffer,);Ok(output)}diff --git a/crates/uzu-engine/src/backends/metal/kernel/attention/gemm_grouped/mod.rs b/crates/uzu-engine/src/backends/metal/kernel/attention/gemm_grouped/mod.rsindex 01fd9b0e7..bd3697228 100644--- a/crates/uzu-engine/src/backends/metal/kernel/attention/gemm_grouped/mod.rs+++ b/crates/uzu-engine/src/backends/metal/kernel/attention/gemm_grouped/mod.rs@@ -3,12 +3,13 @@ use parking_lot::{MappedMutexGuard, Mutex, MutexGuard};use crate::{backends::{common::{- Allocation, BufferArg, BufferArgMut, Encoder,+ Backend, BufferMut, BufferRef, CommandBufferEncoding,gpu_types::AttnParams,kernel::{AttentionArguments, AttentionKernelConfig},},metal::{Metal,+ command_buffer::MetalCommandBufferEncoding,context::MetalContext,error::MetalError,kernel::{AttentionGemmGroupedCombineMetalKernel, AttentionGemmGroupedMetalKernel},@@ -78,19 +79,18 @@ impl AttentionGemmGroupedMetal {})}- #[allow(clippy::too_many_arguments)]- fn encode<'q, 'k, 'v, 'o, 't>(+ fn encode(&self,- queries: impl BufferArg<'q, Metal>,- keys: impl BufferArg<'k, Metal>,- values: impl BufferArg<'v, Metal>,- output: impl BufferArgMut<'o, Metal>,- trie: Option<impl BufferArg<'t, Metal>>,+ queries: impl BufferRef<Backend = Metal>,+ keys: impl BufferRef<Backend = Metal>,+ values: impl BufferRef<Backend = Metal>,+ output: impl BufferMut<Backend = Metal>,+ trie: Option<impl BufferRef<Backend = Metal>>,suffix_length: u32,kv_length: u32,q_replicas: u32,num_splits: u32,- encoder: &mut Encoder<Metal>,+ command_buffer: &mut MetalCommandBufferEncoding,) -> Result<(), MetalError> {let params = self.params(suffix_length, kv_length);let grouped_rows = self.num_q_heads / self.num_groups * suffix_length;@@ -105,30 +105,30 @@ impl AttentionGemmGroupedMetal {keys,values,Some(output),- None::<&mut Allocation<Metal>>,- None::<&mut Allocation<Metal>>,- None::<&mut Allocation<Metal>>,+ None::<&mut <Metal as Backend>::ScratchBuffer>,+ None::<&mut <Metal as Backend>::ScratchBuffer>,+ None::<&mut <Metal as Backend>::ScratchBuffer>,trie,params,m_tiles,self.num_groups,q_replicas,1,- encoder,+ command_buffer,);return Ok(());}let partial_rows = q_replicas * self.num_groups * m_tiles * num_splits * self.block_rows;- let mut partials = encoder.allocate_scratch_for_shape(&[partial_rows, self.head_dim], DataType::F32)?;- let mut partial_maxs = encoder.allocate_scratch_for_shape(&[partial_rows], DataType::F32)?;- let mut partial_sums = encoder.allocate_scratch_for_shape(&[partial_rows], DataType::F32)?;+ let mut partials = command_buffer.allocate_scratch_for_shape(&[partial_rows, self.head_dim], DataType::F32)?;+ let mut partial_maxs = command_buffer.allocate_scratch_for_shape(&[partial_rows], DataType::F32)?;+ let mut partial_sums = command_buffer.allocate_scratch_for_shape(&[partial_rows], DataType::F32)?;self.split_kernel.encode(queries,keys,values,- None::<&mut Allocation<Metal>>,+ None::<&mut <Metal as Backend>::ScratchBuffer>,Some(&mut partials),Some(&mut partial_maxs),Some(&mut partial_sums),@@ -138,7 +138,7 @@ impl AttentionGemmGroupedMetal {self.num_groups,q_replicas,num_splits,- encoder,+ command_buffer,);self.combine.encode(@@ -153,7 +153,7 @@ impl AttentionGemmGroupedMetal {self.num_groups,q_replicas,num_splits,- encoder,+ command_buffer,);Ok(())}@@ -248,21 +248,28 @@ impl AttentionGemmGrouped {policy::should_encode(self.head_dim, mask, suffix_length, kv_length)}- pub fn encode<'a, KT: BufferArg<'a, Metal>, VT: BufferArg<'a, Metal>>(+ pub fn encode(&self,mask: MaskKind,- arguments: AttentionArguments<'a, Metal, KT, VT>,- encoder: &mut Encoder<Metal>,- ) -> Result<Allocation<Metal>, MetalError> {+ arguments: AttentionArguments<+ '_,+ Metal,+ impl BufferRef<Backend = Metal>,+ impl BufferRef<Backend = Metal>,+ impl BufferRef<Backend = Metal>,+ impl BufferRef<Backend = Metal>,+ >,+ command_buffer: &mut MetalCommandBufferEncoding,+ ) -> Result<<Metal as Backend>::ScratchBuffer, MetalError> {let suffix_length = arguments.suffix_length;assert!(arguments.cache.ring_params().is_none(), "ring KV cache is unsupported");assert!(arguments.sinks.is_none(), "attention sinks are unsupported");let kv_length = arguments.cache.prefix_len() + suffix_length;- let mut output =- encoder.allocate_constant_for_shape(&[suffix_length, self.num_q_heads, self.head_dim], DataType::BF16)?;- let gpu_core_count = encoder.context().gpu_core_count;- let core = self.get_or_create(encoder.context(), mask)?;+ let mut output = command_buffer+ .allocate_scratch_for_shape(&[suffix_length, self.num_q_heads, self.head_dim], DataType::BF16)?;+ let gpu_core_count = command_buffer.context().gpu_core_count;+ let core = self.get_or_create(command_buffer.context(), mask)?;let num_splits = choose_splits(SplitGeometry {head_dim: core.head_dim,@@ -285,7 +292,7 @@ impl AttentionGemmGrouped {kv_length,1,num_splits,- encoder,+ command_buffer,)?;Ok(output)}diff --git a/crates/uzu-engine/src/backends/metal/kernel/attention/mod.rs b/crates/uzu-engine/src/backends/metal/kernel/attention/mod.rsindex 452afdf94..5bbafd69e 100644--- a/crates/uzu-engine/src/backends/metal/kernel/attention/mod.rs+++ b/crates/uzu-engine/src/backends/metal/kernel/attention/mod.rs@@ -1,3 +1,5 @@+use crate::backends::common::Backend;+mod fallback;mod gemm;mod gemm_grouped;@@ -6,10 +8,10 @@ mod two_pass;use crate::backends::{common::{- Allocation, BufferArg, Encoder,+ BufferRef, CommandBufferEncoding,kernel::{AttentionArguments, AttentionKernel, AttentionKernelConfig},},- metal::{Metal, context::MetalContext, error::MetalError},+ metal::{Metal, command_buffer::MetalCommandBufferEncoding, context::MetalContext, error::MetalError},};#[derive(Clone, Copy, Debug, PartialEq, Eq)]@@ -79,32 +81,38 @@ impl AttentionKernel for AttentionMetalKernel {})}- fn encode<'a, KT, VT>(+ fn encode(&self,- arguments: AttentionArguments<'a, Metal, KT, VT>,- encoder: &mut Encoder<Metal>,- ) -> Result<Allocation<Metal>, MetalError>- where- KT: BufferArg<'a, Metal>,- VT: BufferArg<'a, Metal>,- {- encoder.push_debug_group("attention core");- let result = self.encode_impl(arguments, encoder);- encoder.pop_debug_group();+ arguments: AttentionArguments<+ '_,+ Metal,+ impl BufferRef<Backend = Metal>,+ impl BufferRef<Backend = Metal>,+ impl BufferRef<Backend = Metal>,+ impl BufferRef<Backend = Metal>,+ >,+ command_buffer: &mut MetalCommandBufferEncoding,+ ) -> Result<<Metal as Backend>::ScratchBuffer, MetalError> {+ command_buffer.push_debug_group("attention core");+ let result = self.encode_impl(arguments, command_buffer);+ command_buffer.pop_debug_group();result}}impl AttentionMetalKernel {- fn encode_impl<'a, KT, VT>(+ fn encode_impl(&self,- arguments: AttentionArguments<'a, Metal, KT, VT>,- encoder: &mut Encoder<Metal>,- ) -> Result<Allocation<Metal>, MetalError>- where- KT: BufferArg<'a, Metal>,- VT: BufferArg<'a, Metal>,- {+ arguments: AttentionArguments<+ '_,+ Metal,+ impl BufferRef<Backend = Metal>,+ impl BufferRef<Backend = Metal>,+ impl BufferRef<Backend = Metal>,+ impl BufferRef<Backend = Metal>,+ >,+ command_buffer: &mut MetalCommandBufferEncoding,+ ) -> Result<<Metal as Backend>::ScratchBuffer, MetalError> {let suffix_length = arguments.suffix_length;let kv_length = arguments.cache.prefix_len() + suffix_length;let is_trie = arguments.trie.is_some();@@ -116,36 +124,36 @@ impl AttentionMetalKernel {&& let Some(grouped) = &self.grouped{if grouped.should_encode(mask, suffix_length, kv_length) {- return grouped.encode(mask, arguments, encoder);+ return grouped.encode(mask, arguments, command_buffer);}// These measured sibling exceptions apply only when the// grouped core was built for this layer.if self.head_dim == 256 && (1..=16).contains(&suffix_length) && kv_length > D256_SINGLE_PASS_KV_THRESHOLD {- return self.single_pass.encode(arguments, encoder);+ return self.single_pass.encode(arguments, command_buffer);}if (self.head_dim == 256 && (9..=16).contains(&suffix_length))|| (self.head_dim == 128&& (9..=16).contains(&suffix_length)&& kv_length > D128_SHORT_KV_GEMM_THRESHOLD){- return self.two_pass.encode(arguments, encoder);+ return self.two_pass.encode(arguments, command_buffer);}}if suffix_length > 8 {if let Some(gemm) = &self.gemm {- return gemm.encode(arguments, encoder);+ return gemm.encode(arguments, command_buffer);}if !is_trie && let Some(fallback) = &self.fallback {- return fallback.encode(arguments, encoder);+ return fallback.encode(arguments, command_buffer);}}if kv_length > SINGLE_PASS_KV_THRESHOLD {- self.two_pass.encode(arguments, encoder)+ self.two_pass.encode(arguments, command_buffer)} else {- self.single_pass.encode(arguments, encoder)+ self.single_pass.encode(arguments, command_buffer)}}}diff --git a/crates/uzu-engine/src/backends/metal/kernel/attention/single_pass.rs b/crates/uzu-engine/src/backends/metal/kernel/attention/single_pass.rsindex ae72c18c5..aa034a94a 100644--- a/crates/uzu-engine/src/backends/metal/kernel/attention/single_pass.rs+++ b/crates/uzu-engine/src/backends/metal/kernel/attention/single_pass.rs@@ -4,10 +4,13 @@ use parking_lot::{MappedMutexGuard, Mutex, MutexGuard};use crate::backends::{common::{- Allocation, BufferArg, Encoder,+ Backend, BufferRef, CommandBufferEncoding,kernel::{AttentionArguments, AttentionKernelConfig, AttentionSinglePassKernel},},- metal::{Metal, context::MetalContext, error::MetalError, kernel::AttentionSinglePassMetalKernel},+ metal::{+ Metal, command_buffer::MetalCommandBufferEncoding, context::MetalContext, error::MetalError,+ kernel::AttentionSinglePassMetalKernel,+ },};pub struct AttentionSinglePass {@@ -45,17 +48,24 @@ impl AttentionSinglePass {Ok(MutexGuard::map(kernels, |kernels| kernels.get_mut(&is_trie).expect("kernel was just initialized")))}- pub fn encode<'a, KT: BufferArg<'a, Metal>, VT: BufferArg<'a, Metal>>(+ pub fn encode(&self,- arguments: AttentionArguments<'a, Metal, KT, VT>,- encoder: &mut Encoder<Metal>,- ) -> Result<Allocation<Metal>, MetalError> {+ arguments: AttentionArguments<+ '_,+ Metal,+ impl BufferRef<Backend = Metal>,+ impl BufferRef<Backend = Metal>,+ impl BufferRef<Backend = Metal>,+ impl BufferRef<Backend = Metal>,+ >,+ command_buffer: &mut MetalCommandBufferEncoding,+ ) -> Result<<Metal as Backend>::ScratchBuffer, MetalError> {let config = self.config;- let mut output = encoder.allocate_constant_for_shape(+ let mut output = command_buffer.allocate_scratch_for_shape(&[arguments.suffix_length, config.num_q_heads, config.head_dim],config.data_type,)?;- let kernel = self.get_or_create(encoder.context(), arguments.trie.is_some())?;+ let kernel = self.get_or_create(command_buffer.context(), arguments.trie.is_some())?;kernel.encode(arguments.queries,arguments.keys,@@ -74,7 +84,7 @@ impl AttentionSinglePass {arguments.sinks,config.num_q_heads,arguments.suffix_length,- encoder,+ command_buffer,);Ok(output)}diff --git a/crates/uzu-engine/src/backends/metal/kernel/attention/two_pass.rs b/crates/uzu-engine/src/backends/metal/kernel/attention/two_pass.rsindex 111a5bda2..8a7f93c64 100644--- a/crates/uzu-engine/src/backends/metal/kernel/attention/two_pass.rs+++ b/crates/uzu-engine/src/backends/metal/kernel/attention/two_pass.rs@@ -5,11 +5,12 @@ use parking_lot::{MappedMutexGuard, Mutex, MutexGuard};use crate::{backends::{common::{- Allocation, BufferArg, Encoder,+ Backend, BufferRef, CommandBufferEncoding,kernel::{AttentionArguments, AttentionKernelConfig},},metal::{Metal,+ command_buffer::MetalCommandBufferEncoding,context::MetalContext,error::MetalError,kernel::{AttentionTwoPass1MetalKernel, AttentionTwoPass2MetalKernel},@@ -68,25 +69,32 @@ impl AttentionTwoPass {Ok(MutexGuard::map(second, |second| second.as_mut().expect("pass was just initialized")))}- pub fn encode<'a, KT: BufferArg<'a, Metal>, VT: BufferArg<'a, Metal>>(+ pub fn encode(&self,- arguments: AttentionArguments<'a, Metal, KT, VT>,- encoder: &mut Encoder<Metal>,- ) -> Result<Allocation<Metal>, MetalError> {+ arguments: AttentionArguments<+ '_,+ Metal,+ impl BufferRef<Backend = Metal>,+ impl BufferRef<Backend = Metal>,+ impl BufferRef<Backend = Metal>,+ impl BufferRef<Backend = Metal>,+ >,+ command_buffer: &mut MetalCommandBufferEncoding,+ ) -> Result<<Metal as Backend>::ScratchBuffer, MetalError> {let config = self.config;- let mut partials = encoder.allocate_scratch_for_shape(+ let mut partials = command_buffer.allocate_scratch_for_shape(&[arguments.suffix_length, config.num_q_heads, PARTIAL_BLOCKS, config.head_dim],PARTIAL_DATA_TYPE,)?;- let mut sums = encoder.allocate_scratch_for_shape(+ let mut sums = command_buffer.allocate_scratch_for_shape(&[arguments.suffix_length, config.num_q_heads, PARTIAL_BLOCKS],PARTIAL_DATA_TYPE,)?;- let mut maxs = encoder.allocate_scratch_for_shape(+ let mut maxs = command_buffer.allocate_scratch_for_shape(&[arguments.suffix_length, config.num_q_heads, PARTIAL_BLOCKS],PARTIAL_DATA_TYPE,)?;- let first = self.get_or_create(encoder.context(), arguments.trie.is_some())?;+ let first = self.get_or_create(command_buffer.context(), arguments.trie.is_some())?;first.encode(arguments.queries,arguments.keys,@@ -107,14 +115,22 @@ impl AttentionTwoPass {arguments.trie,config.sliding_window_size,arguments.sinks,- encoder,+ command_buffer,);- let mut output = encoder.allocate_constant_for_shape(+ let mut output = command_buffer.allocate_scratch_for_shape(&[arguments.suffix_length, config.num_q_heads, config.head_dim],config.data_type,)?;- let second = self.get_or_create_second(encoder.context())?;- second.encode(&partials, &sums, &maxs, &mut output, config.num_q_heads, arguments.suffix_length, encoder);+ let second = self.get_or_create_second(command_buffer.context())?;+ second.encode(+ &partials,+ &sums,+ &maxs,+ &mut output,+ config.num_q_heads,+ arguments.suffix_length,+ command_buffer,+ );Ok(output)}}diff --git a/crates/uzu-engine/src/backends/metal/kernel/gdn/chunked/mod.rs b/crates/uzu-engine/src/backends/metal/kernel/gdn/chunked/mod.rsindex c71e1cbcd..ec585d3e4 100644--- a/crates/uzu-engine/src/backends/metal/kernel/gdn/chunked/mod.rs+++ b/crates/uzu-engine/src/backends/metal/kernel/gdn/chunked/mod.rs@@ -5,13 +5,13 @@ use super::super::{use crate::{backends::{common::{- Backend, Encoder,+ Backend, CommandBufferEncoding,kernel::{DeltaNetPrefillPrepKernel,delta_net_chunked_prefill::{DeltaNetChunkedPrefill, DeltaNetChunkedPrefillArgs},},},- metal::{Metal, MetalContext},+ metal::{Metal, MetalContext, command_buffer::MetalCommandBufferEncoding},},data_type::DataType,};@@ -90,31 +90,32 @@ impl DeltaNetChunkedPrefill for MetalDeltaNetChunkedPrefill {fn encode(&self,args: DeltaNetChunkedPrefillArgs<'_, Metal>,- encoder: &mut Encoder<Metal>,+ command_buffer: &mut MetalCommandBufferEncoding,) -> Result<(), <Metal as Backend>::Error> {let suffix_len = args.suffix_len;let num_chunks = suffix_len.div_ceil(CHUNK_SIZE);let num_blocks = CHUNK_SIZE.div_ceil(BLOCK_SIZE);let num_col_pairs = num_blocks.div_ceil(2);- let mut q_norm = encoder.allocate_scratch_for_shape(&[suffix_len, args.key_dim], INNER_DATA_TYPE)?;- let mut k_norm = encoder.allocate_scratch_for_shape(&[suffix_len, args.key_dim], INNER_DATA_TYPE)?;- let mut beta = encoder.allocate_scratch_for_shape(&[suffix_len, args.num_heads], INNER_DATA_TYPE)?;- let mut log_decay = encoder.allocate_scratch_for_shape(&[suffix_len, args.num_heads], INNER_DATA_TYPE)?;- let mut g = encoder.allocate_scratch_for_shape(&[suffix_len, args.num_heads], INNER_DATA_TYPE)?;- let mut kk = encoder+ let mut q_norm = command_buffer.allocate_scratch_for_shape(&[suffix_len, args.key_dim], INNER_DATA_TYPE)?;+ let mut k_norm = command_buffer.allocate_scratch_for_shape(&[suffix_len, args.key_dim], INNER_DATA_TYPE)?;+ let mut beta = command_buffer.allocate_scratch_for_shape(&[suffix_len, args.num_heads], INNER_DATA_TYPE)?;+ let mut log_decay =+ command_buffer.allocate_scratch_for_shape(&[suffix_len, args.num_heads], INNER_DATA_TYPE)?;+ let mut g = command_buffer.allocate_scratch_for_shape(&[suffix_len, args.num_heads], INNER_DATA_TYPE)?;+ let mut kk = command_buffer.allocate_scratch_for_shape(&[num_chunks, args.num_groups, CHUNK_SIZE, CHUNK_SIZE], INNER_DATA_TYPE)?;- let mut qk = encoder+ let mut qk = command_buffer.allocate_scratch_for_shape(&[num_chunks, args.num_heads, CHUNK_SIZE, CHUNK_SIZE], INNER_DATA_TYPE)?;- let mut a_packed = encoder.allocate_scratch_for_shape(+ let mut a_packed = command_buffer.allocate_scratch_for_shape(&[num_chunks, args.num_heads, num_blocks, num_col_pairs, BLOCK_SIZE, 2 * BLOCK_SIZE],INNER_DATA_TYPE,)?;- let mut a_inv = encoder.allocate_scratch_for_shape(+ let mut a_inv = command_buffer.allocate_scratch_for_shape(&[num_chunks, args.num_heads, num_blocks, BLOCK_SIZE, BLOCK_SIZE],INNER_DATA_TYPE,)?;- let mut t_mat = encoder+ let mut t_mat = command_buffer.allocate_scratch_for_shape(&[num_chunks, args.num_heads, CHUNK_SIZE, CHUNK_SIZE], DataType::BF16)?;self.prep.encode(@@ -123,7 +124,7 @@ impl DeltaNetChunkedPrefill for MetalDeltaNetChunkedPrefill {args.dt_bias,&mut q_norm,&mut k_norm,- None::<&mut crate::backends::common::Allocation<Metal>>,+ None::<&mut <Metal as Backend>::ScratchBuffer>,&mut beta,&mut log_decay,args.num_heads,@@ -131,9 +132,9 @@ impl DeltaNetChunkedPrefill for MetalDeltaNetChunkedPrefill {args.key_dim,args.value_dim,suffix_len,- encoder,+ command_buffer,);- self.cumsum.encode(&log_decay, &mut g, args.num_heads, suffix_len, encoder);+ self.cumsum.encode(&log_decay, &mut g, args.num_heads, suffix_len, command_buffer);self.gram.encode(&q_norm,&k_norm,@@ -144,7 +145,7 @@ impl DeltaNetChunkedPrefill for MetalDeltaNetChunkedPrefill {args.num_groups,args.key_dim,suffix_len,- encoder,+ command_buffer,);self.a_diag_inv.encode(&kk,@@ -155,9 +156,9 @@ impl DeltaNetChunkedPrefill for MetalDeltaNetChunkedPrefill {args.num_heads,args.num_groups,suffix_len,- encoder,+ command_buffer,);- self.causal_inv.encode(&a_packed, &a_inv, &mut t_mat, args.num_heads, suffix_len, encoder);+ self.causal_inv.encode(&a_packed, &a_inv, &mut t_mat, args.num_heads, suffix_len, command_buffer);self.output_and_state.encode(&q_norm,&k_norm,@@ -174,7 +175,7 @@ impl DeltaNetChunkedPrefill for MetalDeltaNetChunkedPrefill {args.key_dim,args.value_dim,suffix_len,- encoder,+ command_buffer,);Ok(())}diff --git a/crates/uzu-engine/src/backends/metal/kernel/gdn/tree_verify.rs b/crates/uzu-engine/src/backends/metal/kernel/gdn/tree_verify.rsindex 44f7044ca..34807d306 100644--- a/crates/uzu-engine/src/backends/metal/kernel/gdn/tree_verify.rs+++ b/crates/uzu-engine/src/backends/metal/kernel/gdn/tree_verify.rs@@ -3,13 +3,16 @@ use metal::MTLGPUFamily;use crate::{backends::{common::{- Allocation, Encoder, Kernels,+ Backend, CommandBufferEncoding, Kernels,kernel::{BuildTreeGramKernel, BuildTreeOutKernel, BuildTreePrefixKernel, TreeUpdateSolveKernel,delta_net_tree_verify::DeltaNetTreeVerify,},},- metal::{Metal, MetalContext, context::LARGE_MIN_GPU_CORES, error::MetalError, kernel::MetalKernels},+ metal::{+ Metal, MetalContext, command_buffer::MetalCommandBufferEncoding, context::LARGE_MIN_GPU_CORES,+ error::MetalError, kernel::MetalKernels,+ },},data_type::DataType,encodable_block::mixer::delta_net::tree_verify::{TreeVerifyEncodeArguments, TreeVerifyNewArguments},@@ -93,23 +96,23 @@ impl DeltaNetTreeVerify for MetalDeltaNetTreeVerify {fn encode(&self,arguments: TreeVerifyEncodeArguments<'_, Metal>,- encoder: &mut Encoder<Metal>,- ) -> Result<Allocation<Metal>, MetalError> {+ command_buffer: &mut MetalCommandBufferEncoding,+ ) -> Result<<Metal as Backend>::ScratchBuffer, MetalError> {let layout = Layout::new(arguments.tree_size, &self.arguments);- let mut h0_indices = encoder.allocate_constant(DataType::I32.size_in_bytes())?;- h0_indices.copyin(&[0i32]);+ let mut h0_indices = command_buffer.allocate_scratch(DataType::I32.size_in_bytes())?;+ command_buffer.encode_fill(&mut h0_indices, 0);let mut prefix =- encoder.allocate_scratch_for_shape(&[layout.tree_size, layout.num_v_heads], INNER_DATA_TYPE)?;- let mut a_packed = encoder.allocate_scratch_for_shape(&layout.a_packed_shape(), INNER_DATA_TYPE)?;- let mut qkd = encoder+ command_buffer.allocate_scratch_for_shape(&[layout.tree_size, layout.num_v_heads], INNER_DATA_TYPE)?;+ let mut a_packed = command_buffer.allocate_scratch_for_shape(&layout.a_packed_shape(), INNER_DATA_TYPE)?;+ let mut qkd = command_buffer.allocate_scratch_for_shape(&[layout.num_v_heads, layout.tree_size, layout.tree_size], INNER_DATA_TYPE)?;- let mut a_inverse = encoder.allocate_scratch_for_shape(&layout.a_inverse_shape(), INNER_DATA_TYPE)?;- let mut kh0 = encoder+ let mut a_inverse = command_buffer.allocate_scratch_for_shape(&layout.a_inverse_shape(), INNER_DATA_TYPE)?;+ let mut kh0 = command_buffer.allocate_scratch_for_shape(&[layout.tree_size, layout.num_v_heads, layout.head_v_dim], INNER_DATA_TYPE)?;- let mut u = encoder+ let mut u = command_buffer.allocate_scratch_for_shape(&[layout.num_v_heads, layout.tree_size, layout.head_v_dim], INNER_DATA_TYPE)?;- let mut output = encoder.allocate_scratch_for_shape(+ let mut output = command_buffer.allocate_scratch_for_shape(&[layout.tree_size, layout.num_v_heads, layout.head_v_dim],self.arguments.data_type,)?;@@ -121,7 +124,7 @@ impl DeltaNetTreeVerify for MetalDeltaNetTreeVerify {1,arguments.tree_size,self.arguments.num_v_heads,- encoder,+ command_buffer,);self.gram.encode(arguments.q,@@ -142,7 +145,7 @@ impl DeltaNetTreeVerify for MetalDeltaNetTreeVerify {self.arguments.num_v_heads,self.arguments.head_k_dim,self.arguments.head_v_dim,- encoder,+ command_buffer,);self.solve.encode(Some(&kh0),@@ -157,7 +160,7 @@ impl DeltaNetTreeVerify for MetalDeltaNetTreeVerify {arguments.tree_size,self.arguments.num_v_heads,self.arguments.head_v_dim,- encoder,+ command_buffer,);self.out.encode(arguments.q,@@ -174,7 +177,7 @@ impl DeltaNetTreeVerify for MetalDeltaNetTreeVerify {self.arguments.num_v_heads,self.arguments.head_k_dim,self.arguments.head_v_dim,- encoder,+ command_buffer,);Ok(output)}diff --git a/crates/uzu-engine/src/backends/metal/kernel/matmul/gemm/kernel.rs b/crates/uzu-engine/src/backends/metal/kernel/matmul/gemm/kernel.rsindex 78cad2172..0854876ad 100644--- a/crates/uzu-engine/src/backends/metal/kernel/matmul/gemm/kernel.rs+++ b/crates/uzu-engine/src/backends/metal/kernel/matmul/gemm/kernel.rs@@ -9,7 +9,7 @@ use super::{use crate::{backends::{common::{- Allocation, BufferArg, Encoder,+ Backend, BufferMut, BufferRef, CommandBufferEncoding,gpu_types::{GemmParams,gemm::{GemmAPrologueKind, GemmAlignment, GemmBPrologueKind, GemmDTransform},@@ -21,6 +21,7 @@ use crate::{},metal::{Metal,+ command_buffer::MetalCommandBufferEncoding,context::MetalContext,error::MetalError,kernel::{GemmMetalKernel, GemmSplitKReduceMetalKernel},@@ -122,15 +123,22 @@ impl GemmKernel {.map_err(|error| MetalError::KernelDispatchFailed(Box::new(error)))}- pub fn encode_plan<'a, 'b, 'd, TB: BufferArg<'b, Metal>>(+ pub fn encode_plan(&mut self,- arguments: MatmulArguments<'a, 'b, 'd, Metal, TB>,+ arguments: MatmulArguments<+ '_,+ Metal,+ impl BufferRef<Backend = Metal>,+ impl BufferRef<Backend = Metal>,+ impl BufferMut<Backend = Metal>,+ impl BufferRef<Backend = Metal>,+ >,plan: GemmPlan,output_work: &MatmulOutputWork,- encoder: &mut Encoder<Metal>,+ command_buffer: &mut MetalCommandBufferEncoding,) -> Result<(), MetalError> {let shape = MatmulShape::from_arguments(&arguments);- self.problem(shape, encoder.context())+ self.problem(shape, command_buffer.context()).validate_engine(plan.engine).map_err(|error| MetalError::KernelDispatchFailed(Box::new(error)))?;@@ -154,7 +162,7 @@ impl GemmKernel {match b {MatmulB::FullPrecision {b: weights,- } => self.encode_weights(a, weights, None, d, d_transform, shape, plan, output_work, encoder),+ } => self.encode_weights(a, weights, None, d, d_transform, shape, plan, output_work, command_buffer),MatmulB::Quantized(quantized) => self.encode_weights(a,quantized.codes,@@ -164,22 +172,22 @@ impl GemmKernel {shape,plan,output_work,- encoder,+ command_buffer,),}}- fn encode_weights<'a, 'b, 'd, WB: BufferArg<'b, Metal>>(+ fn encode_weights<WB: BufferRef<Backend = Metal>>(&mut self,- a: MatmulA<'a, Metal>,+ a: MatmulA<impl BufferRef<Backend = Metal>>,weights: WB,- quantized: Option<QuantizedB<'b, Metal>>,- d: &mut Allocation<Metal>,- d_transform: MatmulDOps<'d, Metal>,+ quantized: Option<QuantizedB<WB>>,+ mut d: impl BufferMut<Backend = Metal>,+ d_transform: MatmulDOps<'_, Metal>,shape: MatmulShape,plan: GemmPlan,output_work: &MatmulOutputWork,- encoder: &mut Encoder<Metal>,+ command_buffer: &mut MetalCommandBufferEncoding,) -> Result<(), MetalError> {let (m, n, k) = (shape.m, shape.n, shape.k);let ab_scale = d_transform.ab_scale;@@ -218,7 +226,7 @@ impl GemmKernel {MatmulA::FullPrecision {values,offset,- } => (Some((*values, *offset)), None, None, None, None),+ } => (Some(values.subrange(*offset..)), None, None, None, None),MatmulA::Int8Symmetric {values,scales: activation_scales,@@ -251,7 +259,7 @@ impl GemmKernel {scales,biases,zero_points,- &mut *d,+ d.reborrow(),ab_scale,scale_strides,zero_point_strides,@@ -259,10 +267,10 @@ impl GemmKernel {plan,output_transform,output_bias,- encoder,+ command_buffer,)?;if let Some(factors) = rht_factors {- output_work.apply(&mut *d, factors, bias_after_rht, m, n, encoder);+ output_work.apply(d.reborrow(), factors, bias_after_rht, m, n, command_buffer);}return Ok(());}@@ -305,11 +313,11 @@ impl GemmKernel {a_prologue,a_group_size,)?;- let kernel = self.get_or_create(encoder.context(), specialization)?;+ let kernel = self.get_or_create(command_buffer.context(), specialization)?;kernel.encode(a_full_precision,weights,- &mut *d,+ d.reborrow(),scales,biases,zero_points,@@ -322,35 +330,35 @@ impl GemmKernel {group_count_x,group_count_y,1,- encoder,+ command_buffer,);Ok(())}- fn encode_split_k<'a, 'b, WB: BufferArg<'b, Metal>>(+ fn encode_split_k(&mut self,- a: MatmulA<'a, Metal>,- weights: WB,- scales: Option<&Allocation<Metal>>,- biases: Option<&Allocation<Metal>>,- zero_points: Option<&Allocation<Metal>>,- d: &mut Allocation<Metal>,+ a: MatmulA<impl BufferRef<Backend = Metal>>,+ weights: impl BufferRef<Backend = Metal>,+ scales: Option<impl BufferRef<Backend = Metal>>,+ biases: Option<impl BufferRef<Backend = Metal>>,+ zero_points: Option<impl BufferRef<Backend = Metal>>,+ mut d: impl BufferMut<Backend = Metal>,ab_scale: f32,scale_strides: QuantParamsStrides,zero_point_strides: QuantParamsStrides,shape: MatmulShape,plan: GemmPlan,output_transform: GemmDTransform,- output_bias: Option<&Allocation<Metal>>,- encoder: &mut Encoder<Metal>,+ output_bias: Option<impl BufferRef<Backend = Metal>>,+ command_buffer: &mut MetalCommandBufferEncoding,) -> Result<(), MetalError> {let (m, n, k) = (shape.m, shape.n, shape.k);let (a_full_precision, a_int8, a_scales, a_group_sums, a_prologue, a_group_size) = match a {MatmulA::FullPrecision {values,offset,- } => (Some((values, offset)), None, None, None, GemmAPrologueKind::FullPrecision, None),+ } => (Some(values.subrange(offset..)), None, None, None, GemmAPrologueKind::FullPrecision, None),MatmulA::Int8Symmetric {values,scales,@@ -381,10 +389,10 @@ impl GemmKernel {let elem = (m as usize) * (n as usize);let slice_bytes = elem * self.output_data_type.size_in_bytes();- let mut temp = encoder.allocate_scratch(split_k as usize * slice_bytes)?;+ let mut temp = command_buffer.allocate_scratch(split_k as usize * slice_bytes)?;let mut params = gemm_params(shape, plan, 1.0, scale_strides, zero_point_strides);params.aligned_inner_iterations = kp / k_step;- let part_kernel = self.get_or_create(encoder.context(), part_spec)?;+ let part_kernel = self.get_or_create(command_buffer.context(), part_spec)?;part_kernel.encode(a_full_precision,weights,@@ -392,8 +400,8 @@ impl GemmKernel {scales,biases,zero_points,- None::<&Allocation<Metal>>,- None::<&Allocation<Metal>>,+ None::<&<Metal as Backend>::GlobalBuffer>,+ None::<&<Metal as Backend>::GlobalBuffer>,a_int8,a_scales,a_group_sums,@@ -401,7 +409,7 @@ impl GemmKernel {base_gx,base_gy,split_k,- encoder,+ command_buffer,);debug_assert_eq!(elem % 4, 0, "split-K reduce requires M*N divisible by 4");@@ -418,8 +426,8 @@ impl GemmKernel {} else {None};- let reduce = self.get_or_create_split_k_reduce(encoder.context(), reduce_transform)?;- reduce.encode((&temp, 0usize), &mut *d, bias_arg, elem as u32, split_k, group_count, n, scale_arg, encoder);+ let reduce = self.get_or_create_split_k_reduce(command_buffer.context(), reduce_transform)?;+ reduce.encode(&temp, d.reborrow(), bias_arg, elem as u32, split_k, group_count, n, scale_arg, command_buffer);Ok(())}diff --git a/crates/uzu-engine/src/backends/metal/kernel/matmul/gemv/kernel.rs b/crates/uzu-engine/src/backends/metal/kernel/matmul/gemv/kernel.rsindex 2845c4bdb..1e44c109a 100644--- a/crates/uzu-engine/src/backends/metal/kernel/matmul/gemv/kernel.rs+++ b/crates/uzu-engine/src/backends/metal/kernel/matmul/gemv/kernel.rs@@ -7,13 +7,17 @@ use super::{use crate::{backends::{common::{+ CommandBufferEncoding,gpu_types::{HADAMARD_TRANSFORM_BLOCK_SIZE,gemm::{GemmBPrologueKind, GemmDTransform},},kernel::matmul::{MatmulB, MatmulShape},},- metal::{context::MetalContext, error::MetalError, kernel::GemvMetalKernel},+ metal::{+ command_buffer::MetalCommandBufferEncoding, context::MetalContext, error::MetalError,+ kernel::GemvMetalKernel,+ },},data_type::DataType,};@@ -209,7 +213,7 @@ use std::collections::{HashMap, hash_map::Entry};use crate::backends::{common::{- BufferArg, Encoder,+ BufferMut, BufferRef,kernel::matmul::{MatmulA, MatmulArguments, MatmulError},},metal::Metal,@@ -253,12 +257,19 @@ impl GemvKernel {}}- pub fn encode<'a, 'b, 'd, TB: BufferArg<'b, Metal>>(+ pub fn encode(&mut self,- arguments: MatmulArguments<'a, 'b, 'd, Metal, TB>,+ arguments: MatmulArguments<+ '_,+ Metal,+ impl BufferRef<Backend = Metal>,+ impl BufferRef<Backend = Metal>,+ impl BufferMut<Backend = Metal>,+ impl BufferRef<Backend = Metal>,+ >,specialization: GemvSpecialization,output_work: &MatmulOutputWork,- encoder: &mut Encoder<Metal>,+ command_buffer: &mut MetalCommandBufferEncoding,) -> Result<(), MatmulError<Metal>> {let ab_scale = arguments.d_transform.ab_scale;let output_bias = arguments.d_transform.bias;@@ -274,7 +285,7 @@ impl GemvKernel {let MatmulArguments {a,b,- d,+ mut d,m,n,k,@@ -292,54 +303,71 @@ impl GemvKernel {});};- let (weights, scales, biases, zero_points, scale_strides, zero_point_strides) = match b {- MatmulB::FullPrecision {- b: weights,- } => {- let (buffer, offset, _) = weights.into_parts();- ((buffer, offset), None, None, None, Default::default(), Default::default())- },- MatmulB::Quantized(quantized) => {- let (buffer, offset, _) = quantized.codes.into_parts();- let zero_points = quantized.zero_points();+ let a = a.subrange(a_offset..);+ let (scales, biases, zero_points, scale_strides, zero_point_strides) =+ b.quantized().map_or((None, None, None, Default::default(), Default::default()), |quantized| {(- (buffer, offset),Some(quantized.scales),quantized.biases(),- zero_points,+ quantized.zero_points(),quantized.params.scale_strides(),quantized.zero_point_strides(),)- },- };+ });let output_group_count = n.div_ceil(specialization.output_row_tile());- let context = encoder.context();+ let context = command_buffer.context();let pipeline = self.get_or_create(context, specialization)?;- pipeline.encode(- weights,- scales,- zero_points,- biases,- (a, a_offset),- &mut *d,- gemv_bias,- gemv_rht_factors,- gather_indices,- k,- n,- m,- ab_scale,- output_group_count,- scale_strides.output_stride,- scale_strides.group_stride,- zero_point_strides.output_stride,- zero_point_strides.group_stride,- soft_cap,- encoder,- );+ match b {+ MatmulB::FullPrecision {+ b: weights,+ } => pipeline.encode(+ weights,+ scales,+ zero_points,+ biases,+ a,+ d.reborrow(),+ gemv_bias,+ gemv_rht_factors,+ gather_indices,+ k,+ n,+ m,+ ab_scale,+ output_group_count,+ scale_strides.output_stride,+ scale_strides.group_stride,+ zero_point_strides.output_stride,+ zero_point_strides.group_stride,+ soft_cap,+ command_buffer,+ ),+ MatmulB::Quantized(quantized) => pipeline.encode(+ quantized.codes,+ scales,+ zero_points,+ biases,+ a,+ d.reborrow(),+ gemv_bias,+ gemv_rht_factors,+ gather_indices,+ k,+ n,+ m,+ ab_scale,+ output_group_count,+ scale_strides.output_stride,+ scale_strides.group_stride,+ zero_point_strides.output_stride,+ zero_point_strides.group_stride,+ soft_cap,+ command_buffer,+ ),+ }if let Some(factors) = deferred_factors {- output_work.apply(&mut *d, factors, output_bias, m, n, encoder);+ output_work.apply(d, factors, output_bias, m, n, command_buffer);}Ok(())diff --git a/crates/uzu-engine/src/backends/metal/kernel/matmul/mod.rs b/crates/uzu-engine/src/backends/metal/kernel/matmul/mod.rsindex 9857dba89..b6e8fddda 100644--- a/crates/uzu-engine/src/backends/metal/kernel/matmul/mod.rs+++ b/crates/uzu-engine/src/backends/metal/kernel/matmul/mod.rs@@ -13,7 +13,7 @@ use self::{use crate::{backends::{common::{- Allocation, BufferArg, Encoder,+ Backend, BufferMut, BufferRef, CommandBufferEncoding,gpu_types::gemm::{GemmBPrologueKind, GemmTiling},kernel::{ActivationQuantization, ActivationTransform,@@ -24,7 +24,7 @@ use crate::{},},},- metal::{Metal, context::MetalContext, error::MetalError},+ metal::{Metal, command_buffer::MetalCommandBufferEncoding, context::MetalContext, error::MetalError},},data_type::DataType,};@@ -67,19 +67,19 @@ impl MatmulOutputWork {fn apply(&self,- output: &mut Allocation<Metal>,- factors: &Allocation<Metal>,- bias: Option<&Allocation<Metal>>,+ output: impl BufferMut<Backend = Metal>,+ factors: impl BufferRef<Backend = Metal>,+ bias: Option<&<Metal as Backend>::GlobalBuffer>,m: u32,n: u32,- encoder: &mut Encoder<Metal>,+ command_buffer: &mut MetalCommandBufferEncoding,) {let transform = if bias.is_some() {&self.output_rht_with_bias} else {&self.output_rht};- transform.encode_fp_in_place(output, factors, bias, m, n, encoder);+ transform.encode_fp_in_place(output, factors, bias, m, n, command_buffer);}}@@ -261,15 +261,22 @@ impl MatmulKernel for MatmulMetalKernel {}}- fn encode<'a, 'b, 'd, TB: BufferArg<'b, Metal>>(+ fn encode(&mut self,- arguments: MatmulArguments<'a, 'b, 'd, Metal, TB>,- encoder: &mut Encoder<Metal>,+ arguments: MatmulArguments<+ '_,+ Metal,+ impl BufferRef<Backend = Metal>,+ impl BufferRef<Backend = Metal>,+ impl BufferMut<Backend = Metal>,+ impl BufferRef<Backend = Metal>,+ >,+ command_buffer: &mut MetalCommandBufferEncoding,) -> Result<(), MetalError> {let shape = MatmulShape::from_arguments(&arguments);- let plan = match self.select_dispatch(&shape, encoder.context()) {+ let plan = match self.select_dispatch(&shape, command_buffer.context()) {MatmulDispatch::Gemv(gemv) => {- return self.gemv.encode(arguments, gemv, &self.output_work, encoder).map_err(MetalError::from);+ return self.gemv.encode(arguments, gemv, &self.output_work, command_buffer).map_err(MetalError::from);},MatmulDispatch::Gemm(plan) => plan,};@@ -284,20 +291,27 @@ impl MatmulKernel for MatmulMetalKernel {.into(),));}- self.gemm.encode_plan(arguments, plan, &self.output_work, encoder)+ self.gemm.encode_plan(arguments, plan, &self.output_work, command_buffer)}}#[cfg(test)]impl MatmulMetalKernel {- pub fn encode_with_gemm_engine<'a, 'b, 'd, TB: BufferArg<'b, Metal>>(+ pub fn encode_with_gemm_engine(&mut self,- arguments: MatmulArguments<'a, 'b, 'd, Metal, TB>,+ arguments: MatmulArguments<+ '_,+ Metal,+ impl BufferRef<Backend = Metal>,+ impl BufferRef<Backend = Metal>,+ impl BufferMut<Backend = Metal>,+ impl BufferRef<Backend = Metal>,+ >,engine: gemm::GemmEngine,- encoder: &mut Encoder<Metal>,+ command_buffer: &mut MetalCommandBufferEncoding,) -> Result<(), MetalError> {let shape = MatmulShape::from_arguments(&arguments);- let plan = self.gemm.select_plan_for_engine(&shape, engine, encoder.context())?;- self.gemm.encode_plan(arguments, plan, &self.output_work, encoder)+ let plan = self.gemm.select_plan_for_engine(&shape, engine, command_buffer.context())?;+ self.gemm.encode_plan(arguments, plan, &self.output_work, command_buffer)}}diff --git a/crates/uzu-engine/src/backends/metal/kernel/mod.rs b/crates/uzu-engine/src/backends/metal/kernel/mod.rsindex 7c2cf7a05..9c0d00097 100644--- a/crates/uzu-engine/src/backends/metal/kernel/mod.rs+++ b/crates/uzu-engine/src/backends/metal/kernel/mod.rs@@ -2,11 +2,18 @@ use crate::backends::{common::{Kernels,gpu_types::{+ HADAMARD_TRANSFORM_BLOCK_SIZE,gemm::{gemm_tiling_simdgroups_per_column, gemm_tiling_simdgroups_per_row},weaver::{FRONTIER_SELECT_THREADS, TOP_CHILDREN_THREADS},},},- metal::Metal,+ metal::{Metal, buffer::MetalBufferExt},+};++const METAL_SIMD_SIZE: u32 = 32;++const _: () = {+ assert!(HADAMARD_TRANSFORM_BLOCK_SIZE == METAL_SIMD_SIZE);};mod attention;diff --git a/crates/uzu-engine/src/backends/metal/kernel/radix_top_k_small.rs b/crates/uzu-engine/src/backends/metal/kernel/radix_top_k_small.rsindex 5d21a696f..a49ec1410 100644--- a/crates/uzu-engine/src/backends/metal/kernel/radix_top_k_small.rs+++ b/crates/uzu-engine/src/backends/metal/kernel/radix_top_k_small.rs@@ -3,10 +3,10 @@ use std::mem::size_of;use super::{RadixTopKSmallCollectMetalKernel, RadixTopKSmallPassMetalKernel};use crate::backends::{common::{- Allocation, Encoder,+ BufferMut, BufferRef, CommandBufferEncoding,kernel::radix_top_k_small::{MAX_K, RadixTopKSmall},},- metal::{Metal, context::MetalContext, error::MetalError},+ metal::{Metal, command_buffer::MetalCommandBufferEncoding, context::MetalContext, error::MetalError},};const DEFAULT_PARTITIONS: u32 = 4;@@ -55,27 +55,27 @@ impl RadixTopKSmall for MetalRadixTopKSmall {fn encode(&self,- input: &Allocation<Metal>,- output_ids: &mut Allocation<Metal>,- output_scores: &mut Allocation<Metal>,+ input: impl BufferRef<Backend = Metal>,+ output_ids: impl BufferMut<Backend = Metal>,+ output_scores: impl BufferMut<Backend = Metal>,rows: u32,k: u32,- encoder: &mut Encoder<Metal>,+ command_buffer: &mut MetalCommandBufferEncoding,) -> Result<(), MetalError> {assert!(rows > 0 && k > 0 && k <= MAX_K && k <= self.columns);let rows = rows as usize;let mut histograms =- encoder.allocate_scratch(rows * self.partitions as usize * RADIX_BUCKETS * size_of::<u32>())?;- let mut prefixes = encoder.allocate_scratch(rows * size_of::<u64>())?;- let mut masks = encoder.allocate_scratch(rows * size_of::<u64>())?;- let mut ranks = encoder.allocate_scratch(rows * size_of::<u32>())?;- let mut counts = encoder.allocate_scratch(rows * size_of::<u32>())?;- let mut done = encoder.allocate_scratch(rows * size_of::<u32>())?;- let mut keys = encoder.allocate_scratch(rows * k as usize * size_of::<u64>())?;- encoder.encode_fill(&mut prefixes, 0);- encoder.encode_fill(&mut masks, 0);- encoder.encode_fill(&mut counts, 0);- encoder.encode_fill(&mut done, 0);+ command_buffer.allocate_scratch(rows * self.partitions as usize * RADIX_BUCKETS * size_of::<u32>())?;+ let mut prefixes = command_buffer.allocate_scratch(rows * size_of::<u64>())?;+ let mut masks = command_buffer.allocate_scratch(rows * size_of::<u64>())?;+ let mut ranks = command_buffer.allocate_scratch(rows * size_of::<u32>())?;+ let mut counts = command_buffer.allocate_scratch(rows * size_of::<u32>())?;+ let mut done = command_buffer.allocate_scratch(rows * size_of::<u32>())?;+ let mut keys = command_buffer.allocate_scratch(rows * k as usize * size_of::<u64>())?;+ command_buffer.encode_fill(&mut prefixes, 0);+ command_buffer.encode_fill(&mut masks, 0);+ command_buffer.encode_fill(&mut counts, 0);+ command_buffer.encode_fill(&mut done, 0);for pass in 0..self.passes {self.pass.encode(@@ -88,7 +88,7 @@ impl RadixTopKSmall for MetalRadixTopKSmall {rows as u32,k,pass,- encoder,+ command_buffer,);}self.collect.encode(@@ -101,7 +101,7 @@ impl RadixTopKSmall for MetalRadixTopKSmall {&mut keys,rows as u32,k,- encoder,+ command_buffer,);Ok(())}diff --git a/crates/uzu-engine/src/backends/metal/kernel/tensor_add_swap/tensor_add_swap.metal b/crates/uzu-engine/src/backends/metal/kernel/tensor_add_swap/tensor_add_swap.metaldeleted file mode 100644index 7675efb0b..000000000--- a/crates/uzu-engine/src/backends/metal/kernel/tensor_add_swap/tensor_add_swap.metal+++ /dev/null@@ -1,18 +0,0 @@-#include <metal_stdlib>-#include "../common/dsl.h"--template <typename T>-VARIANTS(T, float, half, bfloat)-PUBLIC KERNEL(TensorAddSwap)(- device T* skip_buffer,- device T* main_buffer,- constant uint& length,- const uint position AXIS(length, 256)-) {- T skip_value = skip_buffer[position];- T main_value = main_buffer[position];- T result = main_value + skip_value;-- main_buffer[position] = result;- skip_buffer[position] = result;-}\ No newline at end of filediff --git a/crates/uzu-engine/src/backends/metal/kernel/tensor_copy/tensor_copy.metal b/crates/uzu-engine/src/backends/metal/kernel/tensor_copy/tensor_copy.metaldeleted file mode 100644index 7c6a35f79..000000000--- a/crates/uzu-engine/src/backends/metal/kernel/tensor_copy/tensor_copy.metal+++ /dev/null@@ -1,13 +0,0 @@-#include <metal_stdlib>-#include "../common/dsl.h"--template <typename T>-VARIANTS(T, float, half, bfloat)-PUBLIC KERNEL(TensorCopy)(- const device T* src_buffer,- device T* dst_buffer,- constant uint& length,- const uint position AXIS(length, 256)-) {- dst_buffer[position] = src_buffer[position];-}\ No newline at end of filediff --git a/crates/uzu-engine/src/backends/metal/metal_extensions/compute_command_encoder_extensions_set_value.rs b/crates/uzu-engine/src/backends/metal/metal_extensions/compute_command_encoder_extensions_set_value.rsdeleted file mode 100644index 8794f48d2..000000000--- a/crates/uzu-engine/src/backends/metal/metal_extensions/compute_command_encoder_extensions_set_value.rs+++ /dev/null@@ -1,41 +0,0 @@-use std::{ffi::c_void, mem::size_of, ptr::NonNull};--use metal::MTLComputeCommandEncoder;-use objc2::runtime::ProtocolObject;--/// Extension trait providing ergonomic `set_value` methods for compute command encoders.-pub trait ComputeEncoderSetValue {- /// Sets a value at the specified buffer index.- fn set_value<T>(- &self,- value: &T,- index: usize,- );-- /// Sets a slice of values at the specified buffer index.- fn set_slice<T>(- &self,- slice: &[T],- index: usize,- );-}--impl ComputeEncoderSetValue for ProtocolObject<dyn MTLComputeCommandEncoder> {- fn set_value<T>(- &self,- value: &T,- index: usize,- ) {- let ptr = NonNull::new(value as *const T as *mut c_void).expect("value pointer should never be null");- self.set_bytes(ptr, size_of::<T>(), index);- }-- fn set_slice<T>(- &self,- slice: &[T],- index: usize,- ) {- let ptr = NonNull::new(slice.as_ptr() as *mut c_void).expect("slice pointer should never be null");- self.set_bytes(ptr, size_of_val(slice), index);- }-}diff --git a/crates/uzu-engine/src/backends/metal/metal_extensions/device_extensions.rs b/crates/uzu-engine/src/backends/metal/metal_extensions/device_extensions.rsindex 02bd38d86..931420981 100644--- a/crates/uzu-engine/src/backends/metal/metal_extensions/device_extensions.rs+++ b/crates/uzu-engine/src/backends/metal/metal_extensions/device_extensions.rs@@ -18,12 +18,12 @@ use super::GpuFamilyExt;// would succeed.//// The caller must verify with `respondsToSelector:` first.-unsafe fn raw_msg_send<T: Message + ?Sized, R>(- obj: &T,+unsafe fn raw_msg_send<R>(+ obj: &(impl Message + ?Sized),sel: Sel,) -> R {- let object_pointer: *const T = obj;- let send: unsafe extern "C" fn(*const T, Sel) -> R = unsafe { transmute(objc_msgSend as *const ()) };+ let object_pointer = std::ptr::from_ref(obj);+ let send: unsafe extern "C" fn(*const _, Sel) -> R = unsafe { transmute(objc_msgSend as *const ()) };unsafe { send(object_pointer, sel) }}@@ -40,14 +40,11 @@ fn register_selector(name: &str) -> Sel {// class check so the send also works on the `CaptureMTLDevice` forwarding proxy// (where a typed `msg_send!` would panic) — this is why the typed `mtl-rs`// accessors are not used here.-fn optional_selector_value<T, R>(- device: &T,+fn optional_selector_value<R>(+ device: &(impl Message + NSObjectProtocol),name: &str,fallback: R,-) -> R-where- T: Message + NSObjectProtocol,-{+) -> R {let selector = register_selector(name);if device.respondsToSelector(selector) {unsafe { raw_msg_send(device, selector) }diff --git a/crates/uzu-engine/src/backends/metal/metal_extensions/mod.rs b/crates/uzu-engine/src/backends/metal/metal_extensions/mod.rsindex 67889fcfb..88e550683 100644--- a/crates/uzu-engine/src/backends/metal/metal_extensions/mod.rs+++ b/crates/uzu-engine/src/backends/metal/metal_extensions/mod.rs@@ -1,4 +1,3 @@-mod compute_command_encoder_extensions_set_value;mod data_type;mod device_extensions;mod function_constant_values_extensions_set_value;@@ -6,7 +5,6 @@ mod gpu_family_extensions;mod library_extensions_pipeline;mod sparse_page_size_extensions;-pub use compute_command_encoder_extensions_set_value::ComputeEncoderSetValue;pub use data_type::MetalDataTypeExt;pub use device_extensions::DeviceExt;pub use function_constant_values_extensions_set_value::FunctionConstantValuesSetValue;diff --git a/crates/uzu-engine/src/backends/metal/mod.rs b/crates/uzu-engine/src/backends/metal/mod.rsindex 65d1610e4..98d646a2e 100644--- a/crates/uzu-engine/src/backends/metal/mod.rs+++ b/crates/uzu-engine/src/backends/metal/mod.rs@@ -3,21 +3,11 @@ mod buffer;mod command_buffer;mod context;mod decompression;-mod dense_buffer;mod error;mod kernel;mod metal_extensions;-mod sparse;--use crate::backends::common::gpu_types::HADAMARD_TRANSFORM_BLOCK_SIZE;--const METAL_SIMD_SIZE: u32 = 32;--const _: () = {- assert!(HADAMARD_TRANSFORM_BLOCK_SIZE == METAL_SIMD_SIZE);-};pub use backend::Metal;-pub use context::MetalContext;+pub use context::MetalContext; // TODO: This should be removed#[cfg(test)]pub use kernel::matmul::gemm::GemmEngine;diff --git a/crates/uzu-engine/src/encodable_block/classifier.rs b/crates/uzu-engine/src/encodable_block/classifier.rsindex 2f5ee208d..df7f2958e 100644--- a/crates/uzu-engine/src/encodable_block/classifier.rs+++ b/crates/uzu-engine/src/encodable_block/classifier.rs@@ -1,7 +1,10 @@use thiserror::Error;use crate::{- backends::common::{Allocation, Backend, Encoder, Kernels, gpu_types::trie::TrieNode, kernel::PoolingMeanKernel},+ backends::common::{+ Backend, BufferRef, CommandBuffer, CommandBufferEncoding, Kernels, gpu_types::trie::TrieNode,+ kernel::PoolingMeanKernel,+ },config::classifier::{ClassifierConfig, PoolingType},data_type::DataType,encodable_block::{@@ -110,16 +113,18 @@ impl<B: Backend> Classifier<B> {pub fn encode(&self,- token_ids: &Allocation<B>,+ token_ids: impl BufferRef<Backend = B>,batch_dim: u32,- encoder: &mut Encoder<B>,- ) -> Result<Allocation<B>, ClassifierError<B>> {- encoder.push_debug_group("classifier");+ command_buffer: &mut <B::CommandBuffer as CommandBuffer>::Encoding,+ ) -> Result<B::ScratchBuffer, ClassifierError<B>> {+ command_buffer.push_debug_group("classifier");- let embedded = self.embedding.encode_lookup(token_ids, batch_dim, encoder)?;+ let embedded = self.embedding.encode_lookup(token_ids, batch_dim, command_buffer)?;- let hidden =- self.embedding_norm.encode(&embedded, 0, batch_dim, None, encoder).map_err(ClassifierError::Backend)?;+ let hidden = self+ .embedding_norm+ .encode(&embedded, 0, batch_dim, None::<&mut B::ScratchBuffer>, command_buffer)+ .map_err(ClassifierError::Backend)?;let nodes = (0..batch_dim).map(|index| TrieNode {@@ -130,18 +135,27 @@ impl<B: Backend> Classifier<B> {.collect::<Box<[TrieNode]>>();let hidden = self.transformer- .encode(hidden, None, &BatchTopology::new(&nodes, true), Some(0..batch_dim), None, None, encoder)+ .encode(+ hidden,+ None::<&B::ScratchBuffer>,+ &BatchTopology::new(&nodes, true),+ Some((0..batch_dim).into()),+ None,+ None,+ command_buffer,+ ).map_err(ClassifierError::Backend)?.output.unwrap();- let mut pooled =- encoder.allocate_scratch_for_shape(&[self.hidden_dim], self.data_type).map_err(ClassifierError::Backend)?;- self.pooling.encode(&hidden, &mut pooled, batch_dim, self.hidden_dim, 1, encoder);+ let mut pooled = command_buffer+ .allocate_scratch_for_shape(&[self.hidden_dim], self.data_type)+ .map_err(ClassifierError::Backend)?;+ self.pooling.encode(&hidden, &mut pooled, batch_dim, self.hidden_dim, 1, command_buffer);- let logits = self.prediction_head.encode(pooled, 1, encoder).map_err(ClassifierError::Backend)?;+ let logits = self.prediction_head.encode(pooled, 1, command_buffer).map_err(ClassifierError::Backend)?;- encoder.pop_debug_group();+ command_buffer.pop_debug_group();Ok(logits)}diff --git a/crates/uzu-engine/src/encodable_block/convolution.rs b/crates/uzu-engine/src/encodable_block/convolution.rsindex 437bee19d..59fe3f5fb 100644--- a/crates/uzu-engine/src/encodable_block/convolution.rs+++ b/crates/uzu-engine/src/encodable_block/convolution.rs@@ -3,7 +3,7 @@ use thiserror::Error;use crate::{array::size_for_shape,backends::common::{- Allocation, Backend, Encoder,+ Backend, BufferRef, CommandBuffer, CommandBufferEncoding,kernel::{Kernels, SeparableCausalConvKernel},},config::token_mixer::convolutions::SeparableCausalConvConfig,@@ -22,8 +22,8 @@ pub enum ConvolutionNewError<B: Backend> {pub struct SeparableCausalConv<B: Backend> {model_dim: u32,data_type: DataType,- weights: Allocation<B>,- biases: Option<Allocation<B>>,+ weights: B::GlobalBuffer,+ biases: Option<B::GlobalBuffer>,kernel: <B::Kernels as Kernels>::SeparableCausalConvKernel,}@@ -43,11 +43,11 @@ impl<B: Backend> SeparableCausalConv<B> {assert_eq!(data_type, DataType::BF16, "SeparableCausalConv only supports BF16");let weights =- parameter_tree.leaf("weights")?.validate(&[model_dim, kernel_size], DataType::BF16)?.read_allocation()?;+ parameter_tree.leaf("weights")?.validate(&[model_dim, kernel_size], DataType::BF16)?.read_buffer()?;let biases = config.has_biases- .then(|| parameter_tree.leaf("biases")?.validate(&[model_dim], DataType::BF16)?.read_allocation())+ .then(|| parameter_tree.leaf("biases")?.validate(&[model_dim], DataType::BF16)?.read_buffer()).transpose()?;let kernel = <B::Kernels as Kernels>::SeparableCausalConvKernel::new(@@ -71,29 +71,30 @@ impl<B: Backend> SeparableCausalConv<B> {pub fn encode(&self,- input: &Allocation<B>,- coefficient_deltas: &Allocation<B>,+ input: impl BufferRef<Backend = B>,+ coefficient_deltas: impl BufferRef<Backend = B>,coefficient_row_stride: u32,coefficient_column_offset: u32,sequence_length: u32,- encoder: &mut Encoder<B>,- ) -> Result<Allocation<B>, B::Error> {- encoder.push_debug_group("SeparableCausalConv");+ command_buffer: &mut <B::CommandBuffer as CommandBuffer>::Encoding,+ ) -> Result<B::ScratchBuffer, B::Error> {+ command_buffer.push_debug_group("SeparableCausalConv");- let mut output = encoder.allocate_scratch_for_shape(&[sequence_length, self.model_dim], self.data_type)?;+ let mut output =+ command_buffer.allocate_scratch_for_shape(&[sequence_length, self.model_dim], self.data_type)?;let coefficients_offset_bytes = size_for_shape(&[coefficient_column_offset], self.data_type);self.kernel.encode(input,- (coefficient_deltas, coefficients_offset_bytes),+ coefficient_deltas.subrange(coefficients_offset_bytes..),&self.weights,self.biases.as_ref(),&mut output,sequence_length,coefficient_row_stride,- encoder,+ command_buffer,);- encoder.pop_debug_group();+ command_buffer.pop_debug_group();Ok(output)}}diff --git a/crates/uzu-engine/src/encodable_block/decoder.rs b/crates/uzu-engine/src/encodable_block/decoder.rsindex ca3c22849..1bdfe1f9e 100644--- a/crates/uzu-engine/src/encodable_block/decoder.rs+++ b/crates/uzu-engine/src/encodable_block/decoder.rs@@ -1,9 +1,9 @@-use std::ops::Range;+use std::range::Range;use thiserror::Error;use crate::{- backends::common::{Allocation, Backend, Encoder},+ backends::common::{Backend, BufferRef, CommandBuffer, CommandBufferEncoding},config::decoder::DecoderConfig,data_type::DataType,encodable_block::{@@ -38,11 +38,9 @@ pub struct Decoder<B: Backend> {}pub struct DecoderEncodeOutput<B: Backend> {- pub logits: Option<Allocation<B>>,- #[allow(dead_code)]- pub hidden_features: Option<Box<[Allocation<B>]>>,- #[allow(dead_code)]- pub final_hidden: Option<Allocation<B>>,+ pub logits: Option<B::ScratchBuffer>,+ pub hidden_features: Option<Box<[B::ScratchBuffer]>>,+ pub final_hidden: Option<B::ScratchBuffer>,}impl<B: Backend> Decoder<B> {@@ -137,18 +135,20 @@ impl<B: Backend> Decoder<B> {pub fn encode(&self,- token_ids: &Allocation<B>,+ token_ids: impl BufferRef<Backend = B>,batch_dim: &BatchTopology,output_range: Option<Range<u32>>,hidden_feature_layer_indices: Option<&[u32]>,state: &mut TransformerState<B>,- encoder: &mut Encoder<B>,+ command_buffer: &mut <B::CommandBuffer as CommandBuffer>::Encoding,) -> Result<DecoderEncodeOutput<B>, DecoderError<B>> {- encoder.push_debug_group("decoder");+ command_buffer.push_debug_group("decoder");- let embedded = self.embedding.encode_lookup(token_ids, batch_dim.size(), encoder)?;+ let embedded = self.embedding.encode_lookup(token_ids, batch_dim.size(), command_buffer)?;let embedded = if let Some(embedding_norm) = &self.embedding_norm {- embedding_norm.encode(&embedded, 0, batch_dim.size(), None, encoder).map_err(DecoderError::Backend)?+ embedding_norm+ .encode(&embedded, 0, batch_dim.size(), None::<&mut B::ScratchBuffer>, command_buffer)+ .map_err(DecoderError::Backend)?} else {embedded};@@ -156,7 +156,7 @@ impl<B: Backend> Decoder<B> {let per_layer_inputs = if let Some(per_layer_embedding) = &self.per_layer_embedding {Some(per_layer_embedding- .encode(token_ids, &embedded, batch_dim.size(), encoder)+ .encode(token_ids, &embedded, batch_dim.size(), command_buffer).map_err(DecoderError::Backend)?,)} else {@@ -169,10 +169,10 @@ impl<B: Backend> Decoder<B> {embedded,per_layer_inputs.as_ref(),batch_dim,- output_range.clone(),+ output_range,hidden_feature_layer_indices,Some(state),- encoder,+ command_buffer,).map_err(DecoderError::Backend)?;@@ -182,9 +182,9 @@ impl<B: Backend> Decoder<B> {output_range.end - output_range.start,output,self.embedding.vocab_size(),- None,+ None::<&B::ScratchBuffer>,true,- encoder,+ command_buffer,)?)} else {None@@ -195,7 +195,7 @@ impl<B: Backend> Decoder<B> {transformer_output.output};- encoder.pop_debug_group();+ command_buffer.pop_debug_group();Ok(DecoderEncodeOutput {logits,diff --git a/crates/uzu-engine/src/encodable_block/dflash.rs b/crates/uzu-engine/src/encodable_block/dflash.rsindex 59f268cec..30b18eee8 100644--- a/crates/uzu-engine/src/encodable_block/dflash.rs+++ b/crates/uzu-engine/src/encodable_block/dflash.rs@@ -1,10 +1,12 @@-use std::any::Any;+use std::{any::Any, range::Range};use thiserror::Error;use crate::{array::size_for_shape,- backends::common::{Allocation, Backend, Encoder, gpu_types::trie::TrieNode},+ backends::common::{+ Backend, Buffer, BufferMut, BufferRef, CommandBuffer, CommandBufferEncoding, gpu_types::trie::TrieNode,+ },config::{dflash::DFlashDraftConfig, rope::AnyRoPEConfig, token_mixer::AnyTokenMixerConfig},data_type::DataType,encodable_block::{@@ -54,8 +56,8 @@ pub struct DFlash<B: Backend> {}pub struct DFlashOutput<B: Backend> {- pub draft_hidden: Allocation<B>,- pub logits: Allocation<B>,+ pub draft_hidden: B::ScratchBuffer,+ pub logits: B::ScratchBuffer,}#[derive(Debug, Error)]@@ -196,78 +198,82 @@ impl<B: Backend> DFlash<B> {pub fn encode_accept(&self,state: &mut DFlashState<B>,- target_features: &[Allocation<B>],+ target_features: impl ExactSizeIterator<Item = impl BufferRef<Backend = B>>,accepted_indices: &[u32],- encoder: &mut Encoder<B>,+ command_buffer: &mut <B::CommandBuffer as CommandBuffer>::Encoding,) -> Result<(), B::Error> {if accepted_indices.is_empty() {return Ok(());}- encoder.push_debug_group("dflash accept");+ command_buffer.push_debug_group("dflash accept");let num_tokens = accepted_indices.len() as u32;let captured_layer_count = self.target_feature_input_dim / self.model_dim;assert_eq!(target_features.len() as u32, captured_layer_count);let layer_feature_bytes = size_for_shape(&[self.model_dim], self.data_type);- assert!(target_features.iter().all(|features| features.size() % layer_feature_bytes == 0));let context_length = state.context_length + num_tokens;assert!(context_length <= state.context_capacity, "DFlash state capacity exceeded");assert!(context_length <= self.max_context_length, "DFlash context exceeds configured RoPE capacity");let mut packed_target_features =- encoder.allocate_scratch_for_shape(&[num_tokens, self.target_feature_input_dim], self.data_type)?;- for (layer_index, features) in target_features.iter().enumerate() {+ command_buffer.allocate_scratch_for_shape(&[num_tokens, self.target_feature_input_dim], self.data_type)?;+ for (layer_index, features) in target_features.enumerate() {+ assert!(features.size() % layer_feature_bytes == 0);for (token_index, &accepted_index) in accepted_indices.iter().enumerate() {let source_start = accepted_index as usize * layer_feature_bytes;assert!(source_start + layer_feature_bytes <= features.size(), "accepted index out of feature bounds");- let destination_start = (token_index * target_features.len() + layer_index) * layer_feature_bytes;- encoder.encode_copy(- features,- source_start..source_start + layer_feature_bytes,- &mut packed_target_features,- destination_start..destination_start + layer_feature_bytes,+ let destination_start =+ (token_index * captured_layer_count as usize + layer_index) * layer_feature_bytes;+ command_buffer.encode_copy(+ features.subrange(source_start..source_start + layer_feature_bytes),+ packed_target_features.subrange_mut(destination_start..destination_start + layer_feature_bytes),);}}- let projected_features = self.target_feature_projection.encode(packed_target_features, num_tokens, encoder)?;- let normalized_features =- self.projected_feature_norm.encode(&projected_features, 0, num_tokens, None, encoder)?;+ let projected_features =+ self.target_feature_projection.encode(packed_target_features, num_tokens, command_buffer)?;+ let normalized_features = self.projected_feature_norm.encode(+ &projected_features,+ 0,+ num_tokens,+ None::<&mut B::ScratchBuffer>,+ command_buffer,+ )?;let token_positions = (state.context_length..state.context_length + num_tokens).collect::<Box<[_]>>();- let rope = PrecalculatedRoPE::precalculate(&self.rope_config, &token_positions, encoder)?;+ let rope = PrecalculatedRoPE::precalculate(&self.rope_config, &token_positions, command_buffer)?;- let projected_kv = self.state_kv_projection.encode(normalized_features, num_tokens, encoder)?;+ let projected_kv = self.state_kv_projection.encode(normalized_features, num_tokens, command_buffer)?;let layer_kv_bytes = size_for_shape(&[self.layer_kv_dim], self.data_type);- let kv_chunk = |chunk_index: usize| chunk_index * layer_kv_bytes..(chunk_index + 1) * layer_kv_bytes;+ let kv_chunk =+ |chunk_index: usize| Range::from(chunk_index * layer_kv_bytes..(chunk_index + 1) * layer_kv_bytes);let mut layer_key_values = (0..self.layers.len())- .map(|_| encoder.allocate_scratch(num_tokens as usize * layer_kv_bytes))+ .map(|_| command_buffer.allocate_scratch(num_tokens as usize * layer_kv_bytes)).collect::<Result<Box<[_]>, _>>()?;for (layer_index, key_value) in layer_key_values.iter_mut().enumerate() {for token_index in 0..num_tokens as usize {- encoder.encode_copy(- &projected_kv,- kv_chunk(token_index * self.layers.len() + layer_index),- key_value,- kv_chunk(token_index),+ command_buffer.encode_copy(+ projected_kv.subrange(kv_chunk(token_index * self.layers.len() + layer_index)),+ key_value.subrange_mut(kv_chunk(token_index)),);}}- for ((layer, mixer_state), key_value) in+ for ((layer, mixer_state), mut key_value) inself.layers.iter().zip(state.layer_states.iter_mut()).zip(layer_key_values){- mixer_state.prepare(state.context_length, num_tokens, encoder.context())?;+ mixer_state.prepare(state.context_length, num_tokens, command_buffer.context())?;let attention = (layer.mixer.as_ref() as &dyn Any).downcast_ref::<Attention<B>>().expect("DFlash draft layers must use attention mixers");let attention_state = (mixer_state.as_mut() as &mut dyn Any).downcast_mut::<AttentionState<B>>().expect("DFlash draft layer states must be attention states");- attention.append_projected_kv(key_value, &rope, num_tokens, attention_state, encoder)?;+ attention.append_projected_kv(&mut key_value, &rope, num_tokens, attention_state, command_buffer)?;}state.context_length += num_tokens;- encoder.pop_debug_group();+ command_buffer.pop_debug_group();Ok(())}@@ -278,9 +284,9 @@ impl<B: Backend> DFlash<B> {target_output_token: u32,target_embedding: &Embedding<B>,batch_size: u32,- encoder: &mut Encoder<B>,+ command_buffer: &mut <B::CommandBuffer as CommandBuffer>::Encoding,) -> Result<DFlashOutput<B>, DFlashEncodeError<B>> {- encoder.push_debug_group("dflash draft");+ command_buffer.push_debug_group("dflash draft");assert!(batch_size >= 2 && batch_size <= self.block_size, "batch size exceeds DFlash block size");assert!(@@ -290,9 +296,9 @@ impl<B: Backend> DFlash<B> {let mut tokens = vec![self.mask_token_id; batch_size as usize];tokens[0] = target_output_token;- let token_ids = encoder.allocate_constant_from_slice(&tokens).map_err(DFlashEncodeError::Backend)?;+ let token_ids = command_buffer.allocate_constant_from_slice(&tokens).map_err(DFlashEncodeError::Backend)?;- let token_embeddings = target_embedding.encode_lookup(&token_ids, batch_size, encoder)?;+ let token_embeddings = target_embedding.encode_lookup(&token_ids, batch_size, command_buffer)?;let nodes = (0..batch_size).map(|index| TrieNode {@@ -303,47 +309,47 @@ impl<B: Backend> DFlash<B> {.collect::<Box<[_]>>();let batch_topology = BatchTopology::new(&nodes, true);let token_positions = (state.context_length..state.context_length + batch_size).collect::<Box<[_]>>();- let rope = PrecalculatedRoPE::precalculate(&self.rope_config, &token_positions, encoder)+ let rope = PrecalculatedRoPE::precalculate(&self.rope_config, &token_positions, command_buffer).map_err(DFlashEncodeError::Backend)?;let mut hidden = token_embeddings;- let mut residual = encoder.allocate_scratch(hidden.size()).map_err(DFlashEncodeError::Backend)?;+ let mut residual = command_buffer.allocate_scratch(hidden.size()).map_err(DFlashEncodeError::Backend)?;for (layer, mixer_state) in self.layers.iter().zip(state.layer_states.iter_mut()) {mixer_state- .prepare(state.context_length, batch_size, encoder.context())+ .prepare(state.context_length, batch_size, command_buffer.context()).map_err(DFlashEncodeError::Backend)?;hidden = layer.encode(hidden,&mut residual,- None,+ None::<&B::ScratchBuffer>,Some(&rope),&batch_topology,Some(MaybeMut::Mut(mixer_state.as_mut())),- encoder,+ command_buffer,).map_err(DFlashEncodeError::Backend)?;}let draft_hidden = self.output_norm- .encode(&hidden, 0, batch_size, Some(&mut residual), encoder)+ .encode(&hidden, 0, batch_size, Some(&mut residual), command_buffer).map_err(DFlashEncodeError::Backend)?;let row_bytes = size_for_shape(&[target_embedding.model_dim()], DataType::BF16);- let lookahead_rows = row_bytes..batch_size as usize * row_bytes;+ let lookahead_rows = Range::from(row_bytes..batch_size as usize * row_bytes);let mut lookahead_hidden =- encoder.allocate_scratch(lookahead_rows.len()).map_err(DFlashEncodeError::Backend)?;- encoder.encode_copy(&draft_hidden, lookahead_rows, &mut lookahead_hidden, ..);+ command_buffer.allocate_scratch(lookahead_rows.iter().len()).map_err(DFlashEncodeError::Backend)?;+ command_buffer.encode_copy(draft_hidden.subrange(lookahead_rows), &mut lookahead_hidden);let logits = target_embedding.encode_readout(batch_size - 1,&lookahead_hidden,target_embedding.vocab_size(),- None,+ None::<&B::ScratchBuffer>,false,- encoder,+ command_buffer,)?;- encoder.pop_debug_group();+ command_buffer.pop_debug_group();Ok(DFlashOutput {draft_hidden,diff --git a/crates/uzu-engine/src/encodable_block/embedding.rs b/crates/uzu-engine/src/encodable_block/embedding.rsindex 265d9e137..4320242d6 100644--- a/crates/uzu-engine/src/encodable_block/embedding.rs+++ b/crates/uzu-engine/src/encodable_block/embedding.rs@@ -3,7 +3,7 @@ use thiserror::Error;use crate::{backends::common::{- Allocation, Backend, Encoder, Kernels,+ Backend, BufferRef, CommandBuffer, CommandBufferEncoding, Kernels,gpu_types::HADAMARD_TRANSFORM_BLOCK_SIZE,kernel::{LogitTransformKernel,@@ -84,7 +84,7 @@ impl<B: Backend> Embedding<B> {config: &AnyEmbeddingConfig,parameter_tree: &ParameterTree<B>,data_type: DataType,- ) -> Result<(Self, Option<Allocation<B>>), EmbeddingError<B>> {+ ) -> Result<(Self, Option<B::GlobalBuffer>), EmbeddingError<B>> {let (tying, readout_input_hadamard_factors) = match config {AnyEmbeddingConfig::TiedEmbeddingConfig(_) => {let embedding_tree = parameter_tree.subtree("embedding");@@ -124,13 +124,13 @@ impl<B: Backend> Embedding<B> {incoherence_signs_tree.leaf("output_signs")?.validate(&[model_dim], DataType::I32)?- .read_allocation()?,+ .read_buffer()?,);let readout_input_hadamard_factors = Some(incoherence_signs_tree.leaf("output_signs")?.validate(&[model_dim], DataType::I32)?- .read_allocation()?,+ .read_buffer()?,);let table = EmbeddingTable::load_with_spec(@@ -172,7 +172,7 @@ impl<B: Backend> Embedding<B> {.subtree("incoherence_signs").leaf("output_signs")?.validate(&[model_dim], DataType::I32)?- .read_allocation()?,+ .read_buffer()?,);EmbeddingTable::load_with_spec(context,@@ -248,13 +248,13 @@ impl<B: Backend> Embedding<B> {pub fn encode_lookup(&self,- token_ids: &Allocation<B>,+ token_ids: impl BufferRef<Backend = B>,batch_dim: u32,- encoder: &mut Encoder<B>,- ) -> Result<Allocation<B>, EmbeddingError<B>> {- encoder.push_debug_group("embedding lookup");+ command_buffer: &mut <B::CommandBuffer as CommandBuffer>::Encoding,+ ) -> Result<B::ScratchBuffer, EmbeddingError<B>> {+ command_buffer.push_debug_group("embedding lookup");- let mut output = encoder+ let mut output = command_buffer.allocate_scratch_for_shape(&[batch_dim, self.model_dim], self.data_type).map_err(EmbeddingError::BackendError)?;@@ -268,9 +268,9 @@ impl<B: Backend> Embedding<B> {..} => input_table,};- table.encode_lookup(token_ids, &mut output, batch_dim, self.input_scale, encoder);+ table.encode_lookup(token_ids, &mut output, batch_dim, self.input_scale, command_buffer);- encoder.pop_debug_group();+ command_buffer.pop_debug_group();Ok(output)}@@ -278,16 +278,16 @@ impl<B: Backend> Embedding<B> {pub fn encode_readout(&self,batch_dim: u32,- input_allocation: &Allocation<B>,+ input_buffer: impl BufferRef<Backend = B>,output_dim: u32,- gather_indices: Option<&Allocation<B>>,+ gather_indices: Option<impl BufferRef<Backend = B>>,apply_logit_transform: bool,- encoder: &mut Encoder<B>,- ) -> Result<Allocation<B>, EmbeddingError<B>> {- encoder.push_debug_group("embedding readout");+ command_buffer: &mut <B::CommandBuffer as CommandBuffer>::Encoding,+ ) -> Result<B::ScratchBuffer, EmbeddingError<B>> {+ command_buffer.push_debug_group("embedding readout");assert!(batch_dim > 0 && output_dim > 0, "Embedding readout requires non-empty dimensions");- let mut output_allocation = match &self.tying {+ let mut output_buffer = match &self.tying {EmbeddingTying::Untied {output,..@@ -296,18 +296,18 @@ impl<B: Backend> Embedding<B> {indices,output_dim,});- output.encode(input_allocation, batch_dim, gather, encoder).map_err(EmbeddingError::BackendError)?+ output.encode(input_buffer, batch_dim, gather, command_buffer).map_err(EmbeddingError::BackendError)?},EmbeddingTying::Tied {table,readout,} => {- let mut output = encoder+ let mut output = command_buffer.allocate_scratch_for_shape(&[batch_dim, output_dim], self.data_type).map_err(EmbeddingError::BackendError)?;let arguments = MatmulArguments {a: MatmulA::FullPrecision {- values: input_allocation,+ values: input_buffer,offset: 0,},b: table.matrix().matmul_b(),@@ -320,7 +320,7 @@ impl<B: Backend> Embedding<B> {n: output_dim,k: self.model_dim,};- readout.lock().encode(arguments, encoder).map_err(EmbeddingError::BackendError)?;+ readout.lock().encode(arguments, command_buffer).map_err(EmbeddingError::BackendError)?;output},};@@ -328,17 +328,17 @@ impl<B: Backend> Embedding<B> {if apply_logit_transform && let Some(logit_transform) = &self.logit_transform {let length = batch_dim * output_dim;logit_transform.kernel.encode(- &mut output_allocation,+ &mut output_buffer,length,logit_transform.scale,logit_transform.soft_cap.unwrap_or(0.0),- encoder,+ command_buffer,);}- encoder.pop_debug_group();+ command_buffer.pop_debug_group();- Ok(output_allocation)+ Ok(output_buffer)}}fn readout_kernel<B: Backend>(diff --git a/crates/uzu-engine/src/encodable_block/embedding_table.rs b/crates/uzu-engine/src/encodable_block/embedding_table.rsindex 250a1e70c..7972d178f 100644--- a/crates/uzu-engine/src/encodable_block/embedding_table.rs+++ b/crates/uzu-engine/src/encodable_block/embedding_table.rs@@ -2,7 +2,7 @@ use thiserror::Error;use crate::{backends::common::{- Allocation, Backend, Encoder, Kernels,+ Backend, BufferMut, BufferRef, CommandBuffer, Kernels,kernel::{FullPrecisionEmbeddingLookupKernel, QuantizedEmbeddingLookupKernel},},config::weight_matrix::{AnyWeightMatrixSpec, Layout},@@ -31,7 +31,7 @@ enum LookupKernel<B: Backend> {pub struct EmbeddingTable<B: Backend> {matrix: WeightMatrix<B>,lookup: LookupKernel<B>,- output_hadamard_factors: Option<Allocation<B>>,+ output_hadamard_factors: Option<B::GlobalBuffer>,vocab_size: u32,embedding_dim: u32,}@@ -55,7 +55,7 @@ impl<B: Backend> EmbeddingTable<B> {embedding_dim: u32,data_type: DataType,spec: AnyWeightMatrixSpec,- output_hadamard_factors: Option<Allocation<B>>,+ output_hadamard_factors: Option<B::GlobalBuffer>,) -> Result<Self, EmbeddingTableError<B>> {let matrix = WeightMatrix::load(tree, spec, Layout::InputOutput, embedding_dim, vocab_size, data_type)?;if output_hadamard_factors.is_some() && matrix.quantization().is_none() {@@ -98,11 +98,11 @@ impl<B: Backend> EmbeddingTable<B> {/// Gathers one row per token id into `output`, scaling by `scale`.pub fn encode_lookup(&self,- token_ids: &Allocation<B>,- output: &mut Allocation<B>,+ token_ids: impl BufferRef<Backend = B>,+ output: impl BufferMut<Backend = B>,batch_dim: u32,scale: f32,- encoder: &mut Encoder<B>,+ command_buffer: &mut <B::CommandBuffer as CommandBuffer>::Encoding,) {match &self.lookup {LookupKernel::FullPrecision(kernel) => kernel.encode(@@ -113,7 +113,7 @@ impl<B: Backend> EmbeddingTable<B> {self.vocab_size,self.embedding_dim,scale,- encoder,+ command_buffer,),LookupKernel::Quantized(kernel) => kernel.encode(token_ids,@@ -127,7 +127,7 @@ impl<B: Backend> EmbeddingTable<B> {self.vocab_size,self.embedding_dim,scale,- encoder,+ command_buffer,),}}diff --git a/crates/uzu-engine/src/encodable_block/linear/input_rht.rs b/crates/uzu-engine/src/encodable_block/linear/input_rht.rsindex 93788b823..2c82b4d93 100644--- a/crates/uzu-engine/src/encodable_block/linear/input_rht.rs+++ b/crates/uzu-engine/src/encodable_block/linear/input_rht.rs@@ -2,16 +2,15 @@ use std::mem::size_of;use super::{LinearInput, LinearInputPreparation};use crate::{- array::size_for_shape,backends::common::{- Allocation, Backend, Encoder,+ Backend, Buffer, BufferRef, CommandBuffer, CommandBufferEncoding,kernel::{ActivationTransform, matmul::ActivationFormat},},data_type::DataType,};pub(super) struct InputRht<B: Backend> {- rht_signs: Allocation<B>,+ rht_signs: B::GlobalBuffer,rht: ActivationTransform<B>,quantizer: Option<ActivationTransform<B>>,}@@ -41,23 +40,23 @@ impl<B: Backend> InputRht<B> {pub(super) fn prepare(&self,- input: &Allocation<B>,+ input: impl BufferRef<Backend = B>,batch_dim: u32,format: ActivationFormat,- encoder: &mut Encoder<B>,+ command_buffer: &mut <B::CommandBuffer as CommandBuffer>::Encoding,) -> Result<LinearInput<B>, B::Error> {if format == ActivationFormat::Int8&& let Some(quantizer) = &self.quantizer{let input_dim = self.input_dim();let groups_per_row = input_dim.div_ceil(quantizer.scale_group_size());- let mut values = encoder.allocate_scratch(size_for_shape(&[batch_dim, input_dim], DataType::I8))?;- let mut scales = encoder.allocate_scratch(size_for_shape(&[batch_dim, groups_per_row], DataType::F32))?;+ let mut values = command_buffer.allocate_scratch_for_shape(&[batch_dim, input_dim], DataType::I8)?;+ let mut scales = command_buffer.allocate_scratch_for_shape(&[batch_dim, groups_per_row], DataType::F32)?;let mut group_sums = quantizer.sum_group_size().map(|group_size| {- encoder- .allocate_scratch(size_for_shape(&[batch_dim, input_dim.div_ceil(group_size)], DataType::I32))+ command_buffer+ .allocate_scratch_for_shape(&[batch_dim, input_dim.div_ceil(group_size)], DataType::I32)}).transpose()?;quantizer.encode_quantize(@@ -68,7 +67,7 @@ impl<B: Backend> InputRht<B> {&self.rht_signs,batch_dim,input_dim,- encoder,+ command_buffer,);return Ok(LinearInput::Int8Symmetric {@@ -81,24 +80,24 @@ impl<B: Backend> InputRht<B> {}let input_dim = self.input_dim();- let mut transformed = encoder.allocate_scratch(input.size())?;- self.rht.encode_fp(input, &mut transformed, &self.rht_signs, batch_dim, input_dim, encoder);+ let mut transformed = command_buffer.allocate_scratch(input.size())?;+ self.rht.encode_fp(input, &mut transformed, &self.rht_signs, batch_dim, input_dim, command_buffer);Ok(LinearInput::FullPrecision(transformed))}pub(super) fn prepare_in_place(&self,- mut input: Allocation<B>,+ mut input: B::ScratchBuffer,batch_dim: u32,format: ActivationFormat,- encoder: &mut Encoder<B>,+ command_buffer: &mut <B::CommandBuffer as CommandBuffer>::Encoding,) -> Result<LinearInput<B>, B::Error> {if format == ActivationFormat::Int8 && self.quantizer.is_some() {- return self.prepare(&input, batch_dim, format, encoder);+ return self.prepare(&input, batch_dim, format, command_buffer);}let input_dim = self.input_dim();- self.rht.encode_fp_in_place(&mut input, &self.rht_signs, None, batch_dim, input_dim, encoder);+ self.rht.encode_fp_in_place(&mut input, &self.rht_signs, None, batch_dim, input_dim, command_buffer);Ok(LinearInput::FullPrecision(input))}diff --git a/crates/uzu-engine/src/encodable_block/linear/matmul.rs b/crates/uzu-engine/src/encodable_block/linear/matmul.rsindex 59d1a8683..7d4927dd7 100644--- a/crates/uzu-engine/src/encodable_block/linear/matmul.rs+++ b/crates/uzu-engine/src/encodable_block/linear/matmul.rs@@ -2,9 +2,8 @@ use parking_lot::Mutex;use thiserror::Error;use crate::{- array::size_for_shape,backends::common::{- Allocation, Backend, Encoder,+ Backend, BufferRef, CommandBuffer, CommandBufferEncoding,kernel::{ActivationQuantization, Kernels,matmul::{ActivationFormat, MatmulA, MatmulArguments, MatmulB, MatmulDOps, MatmulKernel, MatmulShape},@@ -36,8 +35,8 @@ pub enum LinearMatmulError<B: Backend> {pub struct LinearMatmul<B: Backend> {kernel: Mutex<<B::Kernels as Kernels>::MatmulKernel>,matrix: WeightMatrix<B>,- biases: Option<Allocation<B>>,- output_hadamard_factors: Option<Allocation<B>>,+ biases: Option<B::GlobalBuffer>,+ output_hadamard_factors: Option<B::GlobalBuffer>,input_dim: u32,output_dim: u32,output_data_type: DataType,@@ -48,14 +47,14 @@ fn load_biases<B: Backend>(output_data_type: DataType,output_dim: u32,parameter_tree: Option<&ParameterTree<B>>,-) -> Result<Option<Allocation<B>>, LinearMatmulError<B>> {+) -> Result<Option<B::GlobalBuffer>, LinearMatmulError<B>> {if parameter_tree.is_some() && weights_data_type != output_data_type {return Err(LinearMatmulError::UnsupportedConfiguration(format!("mixed precision linear with biases is not supported: weights={weights_data_type:?}, output={output_data_type:?}",)));}Ok(parameter_tree- .map(|tree| tree.leaf("biases")?.validate(&[output_dim], weights_data_type)?.read_allocation())+ .map(|tree| tree.leaf("biases")?.validate(&[output_dim], weights_data_type)?.read_buffer()).transpose()?)}@@ -72,7 +71,7 @@ impl<B: Backend> LinearMatmul<B> {output_data_type: DataType,weights_tree: &ParameterTree<B>,bias_tree: Option<&ParameterTree<B>>,- output_hadamard_factors: Option<Allocation<B>>,+ output_hadamard_factors: Option<B::GlobalBuffer>,) -> Result<Self, LinearMatmulError<B>> {for data_type in [weights_data_type, input_data_type, output_data_type] {if !matches!(data_type, DataType::BF16 | DataType::F32) {@@ -117,14 +116,14 @@ impl<B: Backend> LinearMatmul<B> {pub(super) fn encode_with_a(&self,- a: MatmulA<'_, B>,+ a: MatmulA<impl BufferRef<Backend = B>>,batch_dim: u32,- gather: Option<Gather<'_, B>>,- encoder: &mut Encoder<B>,- ) -> Result<Allocation<B>, B::Error> {+ gather: Option<Gather<impl BufferRef<Backend = B>>>,+ command_buffer: &mut <B::CommandBuffer as CommandBuffer>::Encoding,+ ) -> Result<B::ScratchBuffer, B::Error> {let (output_dim, gather_indices) =gather.map_or((self.output_dim, None), |gather| (gather.output_dim, Some(gather.indices)));- let mut output = encoder.allocate_scratch(size_for_shape(&[batch_dim, output_dim], self.output_data_type))?;+ let mut output = command_buffer.allocate_scratch_for_shape(&[batch_dim, output_dim], self.output_data_type)?;self.kernel.lock().encode(MatmulArguments {a,@@ -138,7 +137,7 @@ impl<B: Backend> LinearMatmul<B> {n: output_dim,k: self.input_dim,},- encoder,+ command_buffer,)?;Ok(output)@@ -167,7 +166,7 @@ impl<B: Backend> LinearMatmul<B> {}}- fn matmul_b(&self) -> MatmulB<'_, B> {+ fn matmul_b(&self) -> MatmulB<&B::GlobalBuffer> {self.matrix.matmul_b()}@@ -183,11 +182,11 @@ impl<B: Backend> LinearMatmul<B> {impl<B: Backend> Linear<B> for LinearMatmul<B> {fn encode(&self,- input: Allocation<B>,+ input: B::ScratchBuffer,batch_dim: u32,- encoder: &mut Encoder<B>,- ) -> Result<Allocation<B>, B::Error> {- encoder.push_debug_group("matmul");+ command_buffer: &mut <B::CommandBuffer as CommandBuffer>::Encoding,+ ) -> Result<B::ScratchBuffer, B::Error> {+ command_buffer.push_debug_group("matmul");let output = self.encode_with_a(MatmulA::FullPrecision {@@ -195,11 +194,11 @@ impl<B: Backend> Linear<B> for LinearMatmul<B> {offset: 0,},batch_dim,- None,- encoder,+ None::<Gather<&B::ScratchBuffer>>,+ command_buffer,)?;- encoder.pop_debug_group();+ command_buffer.pop_debug_group();Ok(output)}@@ -208,9 +207,9 @@ impl<B: Backend> Linear<B> for LinearMatmul<B> {&self,input: LinearInput<B>,batch_dim: u32,- encoder: &mut Encoder<B>,- ) -> Result<Allocation<B>, B::Error> {- self.encode_with_a(input.as_matmul_a(), batch_dim, None, encoder)+ command_buffer: &mut <B::CommandBuffer as CommandBuffer>::Encoding,+ ) -> Result<B::ScratchBuffer, B::Error> {+ self.encode_with_a(input.as_matmul_a(), batch_dim, None::<Gather<&B::ScratchBuffer>>, command_buffer)}fn select_activation_format(diff --git a/crates/uzu-engine/src/encodable_block/linear/mod.rs b/crates/uzu-engine/src/encodable_block/linear/mod.rsindex ef0a8dcb7..0cc7d1684 100644--- a/crates/uzu-engine/src/encodable_block/linear/mod.rs+++ b/crates/uzu-engine/src/encodable_block/linear/mod.rs@@ -13,7 +13,7 @@ pub use untied_readout::UntiedReadout;use crate::{backends::common::{- Allocation, Backend, Encoder,+ Backend, BufferRef, CommandBuffer,gpu_types::HADAMARD_TRANSFORM_BLOCK_SIZE,kernel::{ActivationQuantization,@@ -31,19 +31,19 @@ use crate::{pub trait Linear<B: Backend>: Send + Sync {fn encode(&self,- input: Allocation<B>,+ input: B::ScratchBuffer,batch_dim: u32,- encoder: &mut Encoder<B>,- ) -> Result<Allocation<B>, B::Error>;+ command_buffer: &mut <B::CommandBuffer as CommandBuffer>::Encoding,+ ) -> Result<B::ScratchBuffer, B::Error>;fn encode_input(&self,input: LinearInput<B>,batch_dim: u32,- encoder: &mut Encoder<B>,- ) -> Result<Allocation<B>, B::Error> {+ command_buffer: &mut <B::CommandBuffer as CommandBuffer>::Encoding,+ ) -> Result<B::ScratchBuffer, B::Error> {match input {- LinearInput::FullPrecision(input) => self.encode(input, batch_dim, encoder),+ LinearInput::FullPrecision(input) => self.encode(input, batch_dim, command_buffer),LinearInput::Int8Symmetric {..} => {@@ -62,23 +62,23 @@ pub trait Linear<B: Backend>: Send + Sync {}pub enum LinearInput<B: Backend> {- FullPrecision(Allocation<B>),+ FullPrecision(B::ScratchBuffer),Int8Symmetric {- values: Allocation<B>,- scales: Allocation<B>,- group_sums: Option<Allocation<B>>,+ values: B::ScratchBuffer,+ scales: B::ScratchBuffer,+ group_sums: Option<B::ScratchBuffer>,scale_group_size: u32,code_layout: Int8CodeLayout,},}-pub struct Gather<'a, B: Backend> {- pub indices: &'a Allocation<B>,+pub struct Gather<T: BufferRef> {+ pub indices: T,pub output_dim: u32,}impl<B: Backend> LinearInput<B> {- fn as_matmul_a(&self) -> MatmulA<'_, B> {+ fn as_matmul_a(&self) -> MatmulA<&B::ScratchBuffer> {match self {Self::FullPrecision(values) => MatmulA::FullPrecision {values,@@ -102,7 +102,7 @@ impl<B: Backend> LinearInput<B> {}pub struct LinearInputPreparation<B: Backend> {- pub rht_signs: Allocation<B>,+ pub rht_signs: B::GlobalBuffer,pub activation_quantization: Option<ActivationQuantization>,}@@ -121,9 +121,9 @@ pub enum LinearBlockError<B: Backend> {}impl<B: Backend> dyn Linear<B> {- pub fn new_mixed_precision<const N: usize>(+ pub fn new_mixed_precision(input_dimension: u32,- output_dimensions: [u32; N],+ output_dimensions: impl AsRef<[u32]>,has_biases: bool,context: &B::Context,weights_data_type: DataType,@@ -131,7 +131,7 @@ impl<B: Backend> dyn Linear<B> {output_data_type: DataType,parameter_tree: &ParameterTree<B>,) -> Result<Box<dyn Linear<B>>, LinearBlockError<B>> {- let output_dimension_sum: u32 = output_dimensions.iter().sum();+ let output_dimension_sum: u32 = output_dimensions.as_ref().iter().sum();let weights_tree = parameter_tree.subtree("weights");let spec = weights_tree.metadata::<AnyWeightMatrixSpec>("spec")?;match spec {@@ -197,9 +197,9 @@ impl<B: Backend> dyn Linear<B> {}}- pub fn new<const N: usize>(+ pub fn new(input_dimension: u32,- output_dimensions: [u32; N],+ output_dimensions: impl AsRef<[u32]>,has_biases: bool,context: &B::Context,data_type: DataType,@@ -217,17 +217,17 @@ impl<B: Backend> dyn Linear<B> {)}- pub fn new_with_input_rht_mixed_precision<const N: usize>(+ pub fn new_with_input_rht_mixed_precision(input_dimension: u32,- output_dimensions: [u32; N],+ output_dimensions: impl AsRef<[u32]>,has_biases: bool,context: &B::Context,weights_data_type: DataType,input_data_type: DataType,output_data_type: DataType,parameter_tree: &ParameterTree<B>,- ) -> Result<(Box<dyn Linear<B>>, Option<Allocation<B>>), LinearBlockError<B>> {- let output_dimension_sum: u32 = output_dimensions.iter().sum();+ ) -> Result<(Box<dyn Linear<B>>, Option<B::GlobalBuffer>), LinearBlockError<B>> {+ let output_dimension_sum: u32 = output_dimensions.as_ref().iter().sum();if let Some(linear) = RHTLinearWrapper::try_new_with_input_preparation(context,input_dimension,@@ -255,15 +255,15 @@ impl<B: Backend> dyn Linear<B> {Ok((linear, None))}- pub fn new_for_fused_input<const N: usize>(+ pub fn new_for_fused_input(input_dimension: u32,- output_dimensions: [u32; N],+ output_dimensions: impl AsRef<[u32]>,has_biases: bool,context: &B::Context,data_type: DataType,parameter_tree: &ParameterTree<B>,) -> Result<(Box<dyn Linear<B>>, Option<LinearInputPreparation<B>>), LinearBlockError<B>> {- let output_dimension_sum: u32 = output_dimensions.iter().sum();+ let output_dimension_sum: u32 = output_dimensions.as_ref().iter().sum();if let Some(linear) = RHTLinearWrapper::try_new_with_input_preparation(context,input_dimension,@@ -291,14 +291,14 @@ impl<B: Backend> dyn Linear<B> {Ok((linear, None))}- pub fn new_with_input_rht<const N: usize>(+ pub fn new_with_input_rht(input_dimension: u32,- output_dimensions: [u32; N],+ output_dimensions: impl AsRef<[u32]>,has_biases: bool,context: &B::Context,data_type: DataType,parameter_tree: &ParameterTree<B>,- ) -> Result<(Box<dyn Linear<B>>, Option<Allocation<B>>), LinearBlockError<B>> {+ ) -> Result<(Box<dyn Linear<B>>, Option<B::GlobalBuffer>), LinearBlockError<B>> {Self::new_with_input_rht_mixed_precision(input_dimension,output_dimensions,diff --git a/crates/uzu-engine/src/encodable_block/linear/qlora_wrapper.rs b/crates/uzu-engine/src/encodable_block/linear/qlora_wrapper.rsindex 68401e24d..1da4b631e 100644--- a/crates/uzu-engine/src/encodable_block/linear/qlora_wrapper.rs+++ b/crates/uzu-engine/src/encodable_block/linear/qlora_wrapper.rs@@ -3,7 +3,7 @@ use thiserror::Error;use crate::{backends::common::{- Allocation, Backend, Encoder,+ Backend, CommandBuffer, CommandBufferEncoding,gpu_types::HADAMARD_TRANSFORM_BLOCK_SIZE,kernel::{ActivationTransform, Kernels,@@ -35,12 +35,12 @@ pub enum QLoRALinearWrapperError<B: Backend> {pub struct QLoRALinearWrapper<B: Backend> {base_linear: LinearMatmul<B>,- input_hadamard: Option<(ActivationTransform<B>, Allocation<B>)>,- output_hadamard: Option<(ActivationTransform<B>, Allocation<B>)>,+ input_hadamard: Option<(ActivationTransform<B>, B::GlobalBuffer)>,+ output_hadamard: Option<(ActivationTransform<B>, B::GlobalBuffer)>,adapter_down_kernel: Mutex<<B::Kernels as Kernels>::MatmulKernel>,adapter_up_kernel: Mutex<<B::Kernels as Kernels>::MatmulKernel>,- adapter_down: Allocation<B>,- adapter_up: Allocation<B>,+ adapter_down: B::GlobalBuffer,+ adapter_up: B::GlobalBuffer,input_dim: u32,output_dim: u32,lora_rank: u32,@@ -100,11 +100,11 @@ impl<B: Backend> QLoRALinearWrapper<B> {let input_factors = weights_tree.leaf("incoherence_signs.input_signs")?.validate(&[input_dim], DataType::I32)?- .read_allocation()?;+ .read_buffer()?;let output_factors = weights_tree.leaf("incoherence_signs.output_signs")?.validate(&[output_dim], DataType::I32)?- .read_allocation()?;+ .read_buffer()?;(Some((ActivationTransform::input_rht(context, input_data_type, false)@@ -143,12 +143,12 @@ impl<B: Backend> QLoRALinearWrapper<B> {let adapter_down = weights_tree.leaf("adapter.down_projection")?.validate(&[adapter_spec.rank, input_dim], weights_data_type)?- .read_allocation()?;+ .read_buffer()?;let adapter_up = weights_tree.leaf("adapter.up_projection")?.validate(&[output_dim, adapter_spec.rank], weights_data_type)?- .read_allocation()?;+ .read_buffer()?;Ok(Self {base_linear,@@ -170,14 +170,14 @@ impl<B: Backend> QLoRALinearWrapper<B> {impl<B: Backend> Linear<B> for QLoRALinearWrapper<B> {fn encode(&self,- input: Allocation<B>,+ input: B::ScratchBuffer,batch_dim: u32,- encoder: &mut Encoder<B>,- ) -> Result<Allocation<B>, B::Error> {- encoder.push_debug_group("linear (qlora)");+ command_buffer: &mut <B::CommandBuffer as CommandBuffer>::Encoding,+ ) -> Result<B::ScratchBuffer, B::Error> {+ command_buffer.push_debug_group("linear (qlora)");let mut intermediate =- encoder.allocate_scratch_for_shape(&[batch_dim, self.lora_rank], self.weights_data_type)?;+ command_buffer.allocate_scratch_for_shape(&[batch_dim, self.lora_rank], self.weights_data_type)?;{let mut adapter_kernel = self.adapter_down_kernel.lock();@@ -194,25 +194,32 @@ impl<B: Backend> Linear<B> for QLoRALinearWrapper<B> {b_transpose: true,d: &mut intermediate,d_transform: MatmulDOps::none(),- gather_indices: None,+ gather_indices: None::<&B::ScratchBuffer>,m: batch_dim,n: self.lora_rank,k: self.input_dim,},- encoder,+ command_buffer,)?;}let base_input = if let Some((input_hadamard_kernel, input_factors)) = &self.input_hadamard {let mut base_input =- encoder.allocate_scratch_for_shape(&[batch_dim, self.input_dim], self.input_data_type)?;- input_hadamard_kernel.encode_fp(&input, &mut base_input, input_factors, batch_dim, self.input_dim, encoder);+ command_buffer.allocate_scratch_for_shape(&[batch_dim, self.input_dim], self.input_data_type)?;+ input_hadamard_kernel.encode_fp(+ &input,+ &mut base_input,+ input_factors,+ batch_dim,+ self.input_dim,+ command_buffer,+ );base_input} else {input};- let mut output = self.base_linear.encode(base_input, batch_dim, encoder)?;+ let mut output = self.base_linear.encode(base_input, batch_dim, command_buffer)?;{let mut adapter_kernel = self.adapter_up_kernel.lock();@@ -232,12 +239,12 @@ impl<B: Backend> Linear<B> for QLoRALinearWrapper<B> {accumulate: true,..MatmulDOps::none()},- gather_indices: None,+ gather_indices: None::<&B::ScratchBuffer>,m: batch_dim,n: self.output_dim,k: self.lora_rank,},- encoder,+ command_buffer,)?;}@@ -248,11 +255,11 @@ impl<B: Backend> Linear<B> for QLoRALinearWrapper<B> {None,batch_dim,self.output_dim,- encoder,+ command_buffer,);}- encoder.pop_debug_group();+ command_buffer.pop_debug_group();Ok(output)}diff --git a/crates/uzu-engine/src/encodable_block/linear/rht_wrapper.rs b/crates/uzu-engine/src/encodable_block/linear/rht_wrapper.rsindex 54e9d6c2a..91842627b 100644--- a/crates/uzu-engine/src/encodable_block/linear/rht_wrapper.rs+++ b/crates/uzu-engine/src/encodable_block/linear/rht_wrapper.rs@@ -1,7 +1,7 @@use thiserror::Error;use crate::{- backends::common::{Allocation, Backend, Encoder, gpu_types::HADAMARD_TRANSFORM_BLOCK_SIZE},+ backends::common::{Backend, CommandBuffer, CommandBufferEncoding, gpu_types::HADAMARD_TRANSFORM_BLOCK_SIZE},config::weight_matrix::{AnyWeightMatrixSpec,hybrid_spec::{HybridSpec, IncoherenceProcessingMode},@@ -129,18 +129,18 @@ impl<B: Backend> RHTLinearWrapper<B> {output_data_type: DataType,weights_data_type: DataType,parameter_tree: &ParameterTree<B>,- ) -> Result<(Allocation<B>, LinearMatmul<B>), RHTLinearWrapperError<B>> {+ ) -> Result<(B::GlobalBuffer, LinearMatmul<B>), RHTLinearWrapperError<B>> {let weights_tree = parameter_tree.subtree("weights");let quantized_weights_tree = weights_tree.subtree("quantized");let quantization_spec = quantized_weights_tree.metadata::<AnyWeightMatrixSpec>("spec")?;let rht_signs = weights_tree.leaf("incoherence_signs.input_signs")?.validate(&[input_dimension], DataType::I32)?- .read_allocation()?;+ .read_buffer()?;let output_factors = weights_tree.leaf("incoherence_signs.output_signs")?.validate(&[output_dimension], DataType::I32)?- .read_allocation()?;+ .read_buffer()?;let inner_linear = LinearMatmul::load(context,quantization_spec,@@ -175,34 +175,39 @@ impl<B: Backend> RHTLinearWrapper<B> {impl<B: Backend> Linear<B> for RHTLinearWrapper<B> {fn encode(&self,- input: Allocation<B>,+ input: B::ScratchBuffer,batch_dim: u32,- encoder: &mut Encoder<B>,- ) -> Result<Allocation<B>, B::Error> {- self.encode_input(LinearInput::FullPrecision(input), batch_dim, encoder)+ command_buffer: &mut <B::CommandBuffer as CommandBuffer>::Encoding,+ ) -> Result<B::ScratchBuffer, B::Error> {+ self.encode_input(LinearInput::FullPrecision(input), batch_dim, command_buffer)}fn encode_input(&self,input: LinearInput<B>,batch_dim: u32,- encoder: &mut Encoder<B>,- ) -> Result<Allocation<B>, B::Error> {- encoder.push_debug_group("linear (rht)");+ command_buffer: &mut <B::CommandBuffer as CommandBuffer>::Encoding,+ ) -> Result<B::ScratchBuffer, B::Error> {+ command_buffer.push_debug_group("linear (rht)");let input = match input {LinearInput::FullPrecision(input) => input,input => {- let output = self.inner_linear.encode_input(input, batch_dim, encoder);- encoder.pop_debug_group();+ let output = self.inner_linear.encode_input(input, batch_dim, command_buffer);+ command_buffer.pop_debug_group();return output;},};- let format = self.inner_linear.select_activation_format(batch_dim, encoder.context());- let input = self.input_rht.prepare_in_place(input, batch_dim, format, encoder)?;- let output = self.inner_linear.encode_with_a(input.as_matmul_a(), batch_dim, None, encoder)?;+ let format = self.inner_linear.select_activation_format(batch_dim, command_buffer.context());+ let input = self.input_rht.prepare_in_place(input, batch_dim, format, command_buffer)?;+ let output = self.inner_linear.encode_with_a(+ input.as_matmul_a(),+ batch_dim,+ None::<super::Gather<&B::ScratchBuffer>>,+ command_buffer,+ )?;- encoder.pop_debug_group();+ command_buffer.pop_debug_group();Ok(output)}}diff --git a/crates/uzu-engine/src/encodable_block/linear/untied_readout.rs b/crates/uzu-engine/src/encodable_block/linear/untied_readout.rsindex 04400eeb2..a993ff14e 100644--- a/crates/uzu-engine/src/encodable_block/linear/untied_readout.rs+++ b/crates/uzu-engine/src/encodable_block/linear/untied_readout.rs@@ -1,6 +1,6 @@use crate::{backends::common::{- Allocation, Backend, Encoder,+ Backend, BufferRef, CommandBuffer, CommandBufferEncoding,gpu_types::HADAMARD_TRANSFORM_BLOCK_SIZE,kernel::matmul::{ActivationFormat, MatmulA},},@@ -61,7 +61,7 @@ impl<B: Backend> UntiedReadout<B> {.subtree("incoherence_signs").leaf("input_signs")?.validate(&[model_dim], DataType::I32)?- .read_allocation()?;+ .read_buffer()?;let preparation = LinearInputPreparation {rht_signs,activation_quantization: linear.prepare_a8(context),@@ -77,25 +77,25 @@ impl<B: Backend> UntiedReadout<B> {pub fn encode(&self,- input: &Allocation<B>,+ input: impl BufferRef<Backend = B>,batch_dim: u32,- gather: Option<Gather<'_, B>>,- encoder: &mut Encoder<B>,- ) -> Result<Allocation<B>, B::Error> {+ gather: Option<Gather<impl BufferRef<Backend = B>>>,+ command_buffer: &mut <B::CommandBuffer as CommandBuffer>::Encoding,+ ) -> Result<B::ScratchBuffer, B::Error> {let Some(input_rht) = &self.input_rht else {let a = MatmulA::FullPrecision {values: input,offset: 0,};- return self.linear.encode_with_a(a, batch_dim, gather, encoder);+ return self.linear.encode_with_a(a, batch_dim, gather, command_buffer);};let format = if gather.is_some() {ActivationFormat::Bf16} else {- self.linear.select_activation_format(batch_dim, encoder.context())+ self.linear.select_activation_format(batch_dim, command_buffer.context())};- let input = input_rht.prepare(input, batch_dim, format, encoder)?;- self.linear.encode_with_a(input.as_matmul_a(), batch_dim, gather, encoder)+ let input = input_rht.prepare(input, batch_dim, format, command_buffer)?;+ self.linear.encode_with_a(input.as_matmul_a(), batch_dim, gather, command_buffer)}}diff --git a/crates/uzu-engine/src/encodable_block/mixer/attention/mod.rs b/crates/uzu-engine/src/encodable_block/mixer/attention/mod.rsindex 64f199928..6d5eea1d9 100644--- a/crates/uzu-engine/src/encodable_block/mixer/attention/mod.rs+++ b/crates/uzu-engine/src/encodable_block/mixer/attention/mod.rs@@ -2,7 +2,7 @@ use thiserror::Error;use crate::{backends::common::{- Allocation, Backend, Encoder, Kernels,+ Backend, CommandBuffer, CommandBufferEncoding, Kernels,kernel::{AttentionKernel, AttentionKernelConfig, AttentionPrepareKernel, SigmoidGateKernel},},config::{rope::AnyRoPEConfig, token_mixer::attention::AttentionConfig},@@ -41,7 +41,7 @@ pub struct Attention<B: Backend> {projection_dim: u32,projection: LinearProjection<B>,prepare: <B::Kernels as Kernels>::AttentionPrepareKernel,- sinks: Option<Allocation<B>>,+ sinks: Option<B::GlobalBuffer>,kernel: <B::Kernels as Kernels>::AttentionKernel,gate_kernel: Option<<B::Kernels as Kernels>::SigmoidGateKernel>,out_projection: Box<dyn Linear<B>>,@@ -67,7 +67,7 @@ impl<B: Backend> Attention<B> {config: &AttentionConfig,parameter_tree: &ParameterTree<B>,context: &B::Context,- ) -> Result<(Self, Option<Allocation<B>>), AttentionNewError<B>> {+ ) -> Result<(Self, Option<B::GlobalBuffer>), AttentionNewError<B>> {let is_kv_sharing = config.is_kv_sharing;let head_dim = config.head_dim;@@ -133,7 +133,7 @@ impl<B: Backend> Attention<B> {.map_err(AttentionNewError::Backend)?;let sinks = config.has_sinks- .then(|| parameter_tree.leaf("sinks")?.validate(&[num_q_heads], data_type)?.read_allocation())+ .then(|| parameter_tree.leaf("sinks")?.validate(&[num_q_heads], data_type)?.read_buffer()).transpose()?;assert!(sliding_window_size.is_none_or(|size| size > 0), "zero sliding window size");@@ -214,21 +214,21 @@ impl<B: Backend> Mixer<B> for Attention<B> {fn encode(&self,- hidden: Allocation<B>,+ hidden: B::ScratchBuffer,precalculated_rope: Option<&PrecalculatedRoPE<B>>,batch_dim: &BatchTopology,state: Option<MaybeMut<dyn MixerState<B>>>,- encoder: &mut Encoder<B>,- ) -> Result<Allocation<B>, B::Error> {- encoder.push_debug_group("attention");+ command_buffer: &mut <B::CommandBuffer as CommandBuffer>::Encoding,+ ) -> Result<B::ScratchBuffer, B::Error> {+ command_buffer.push_debug_group("attention");assert_eq!(precalculated_rope.is_some(), self.max_rope_length.is_some(), "precalculated rope mismatch");let state =state.map(|state| state.downcast::<AttentionState<B>>().expect("incorrect type of attention state"));- let output = self.attend(hidden, precalculated_rope, batch_dim, state, encoder)?;+ let output = self.attend(hidden, precalculated_rope, batch_dim, state, command_buffer)?;- encoder.pop_debug_group();+ command_buffer.pop_debug_group();Ok(output)}diff --git a/crates/uzu-engine/src/encodable_block/mixer/attention/mode.rs b/crates/uzu-engine/src/encodable_block/mixer/attention/mode.rsindex f03843486..75b337ac1 100644--- a/crates/uzu-engine/src/encodable_block/mixer/attention/mode.rs+++ b/crates/uzu-engine/src/encodable_block/mixer/attention/mode.rs@@ -1,7 +1,6 @@use crate::{backends::common::{- Allocation, Backend, BufferArgMut, Encoder,- gpu_types::trie::TrieNode,+ Backend, BufferMut, BufferRef, CommandBuffer, CommandBufferEncoding,kernel::{AttentionArguments, AttentionKernel, AttentionPrepareKernel, SigmoidGateKernel},},encodable_block::{@@ -23,13 +22,13 @@ pub(super) struct LinearProjection<B: Backend> {impl<B: Backend> LinearProjection<B> {fn project(&self,- hidden: Allocation<B>,+ hidden: B::ScratchBuffer,batch_dim: u32,- encoder: &mut Encoder<B>,- ) -> Result<Allocation<B>, B::Error> {- let mut projected = self.lin.encode(hidden, batch_dim, encoder)?;+ command_buffer: &mut <B::CommandBuffer as CommandBuffer>::Encoding,+ ) -> Result<B::ScratchBuffer, B::Error> {+ let mut projected = self.lin.encode(hidden, batch_dim, command_buffer)?;if let Some(norm) = &self.norm {- norm.encode(&mut projected, batch_dim, encoder)?;+ norm.encode(&mut projected, batch_dim, command_buffer)?;}Ok(projected)}@@ -38,13 +37,13 @@ impl<B: Backend> LinearProjection<B> {impl<B: Backend> Attention<B> {pub(super) fn attend(&self,- hidden: Allocation<B>,+ hidden: B::ScratchBuffer,precalculated_rope: Option<&PrecalculatedRoPE<B>>,batch_dim: &BatchTopology,state: Option<MaybeMut<AttentionState<B>>>,- encoder: &mut Encoder<B>,- ) -> Result<Allocation<B>, B::Error> {- let qkvg = self.projection.project(hidden, batch_dim.size(), encoder)?;+ command_buffer: &mut <B::CommandBuffer as CommandBuffer>::Encoding,+ ) -> Result<B::ScratchBuffer, B::Error> {+ let qkvg = self.projection.project(hidden, batch_dim.size(), command_buffer)?;let mut attention_output = match state {Some(MaybeMut::Mut(state)) => {@@ -57,14 +56,14 @@ impl<B: Backend> Attention<B> {self.num_q_heads,precalculated_rope,batch_dim.size(),- encoder,+ command_buffer,)?;- self.run_core(&queries, batch_dim, state, encoder)?+ self.run_core(&queries, batch_dim, state, command_buffer)?},Some(MaybeMut::Const(state)) => {// KV sharing: QKVG contains queries and an optional gate only.- let queries = self.prepare_queries(&qkvg, precalculated_rope, batch_dim.size(), encoder)?;- self.run_core(&queries, batch_dim, state, encoder)?+ let queries = self.prepare_queries(&qkvg, precalculated_rope, batch_dim.size(), command_buffer)?;+ self.run_core(&queries, batch_dim, state, command_buffer)?},None => {let Some(num_kv_heads) = self.num_kv_heads else {@@ -72,9 +71,9 @@ impl<B: Backend> Attention<B> {};assert!(batch_dim.is_flat(), "stateless attention doesn't support trie");- let mut keys = encoder+ let mut keys = command_buffer.allocate_scratch_for_shape(&[batch_dim.size(), num_kv_heads, self.head_dim], self.data_type)?;- let mut values = encoder+ let mut values = command_buffer.allocate_scratch_for_shape(&[batch_dim.size(), num_kv_heads, self.head_dim], self.data_type)?;let queries = self.prepare_kv_and_queries(@@ -85,7 +84,7 @@ impl<B: Backend> Attention<B> {self.num_q_heads,precalculated_rope,batch_dim.size(),- encoder,+ command_buffer,)?;let cache = self.ring_capacity.map_or_else(|| KVCacheView::full(0), |_| KVCacheView::ring(0, 0));@@ -96,11 +95,11 @@ impl<B: Backend> Attention<B> {keys: &keys,values: &values,suffix_length: batch_dim.size(),- trie: None,+ trie: None::<&B::ConstantBuffer>,sinks: self.sinks.as_ref(),cache,},- encoder,+ command_buffer,)?},};@@ -109,56 +108,54 @@ impl<B: Backend> Attention<B> {let gate_dim = self.num_q_heads * self.head_dim;let gate_offset = self.projection_dim - gate_dim;gate_kernel.encode(- (&qkvg, gate_offset as usize * self.data_type.size_in_bytes()),+ qkvg.subrange(gate_offset as usize * self.data_type.size_in_bytes()..),&mut attention_output,gate_dim,batch_dim.size(),self.projection_dim,- encoder,+ command_buffer,);}- self.out_projection.encode(attention_output, batch_dim.size(), encoder)+ self.out_projection.encode(attention_output, batch_dim.size(), command_buffer)}pub fn append_projected_kv(&self,- mut key_value: Allocation<B>,+ mut key_value: impl BufferMut<Backend = B>,precalculated_rope: &PrecalculatedRoPE<B>,batch_dim: u32,state: &mut AttentionState<B>,- encoder: &mut Encoder<B>,+ command_buffer: &mut <B::CommandBuffer as CommandBuffer>::Encoding,) -> Result<(), B::Error> {if let Some(norm) = &self.projection.norm {- norm.encode_key_value(&mut key_value, batch_dim, encoder)?;+ norm.encode_key_value(key_value.reborrow(), batch_dim, command_buffer)?;}let prefix_len = state.view().prefix_len();self.prepare_kv_and_queries(- &key_value,+ key_value.as_ref(),state.keys.as_mut(),state.values.as_mut(),prefix_len,0,Some(precalculated_rope),batch_dim,- encoder,+ command_buffer,)?;- state.encode_accept(&(0..batch_dim).collect::<Box<[u32]>>(), encoder)?;+ state.encode_accept(&(0..batch_dim).collect::<Box<[u32]>>(), command_buffer)?;Ok(())}fn run_core(&self,- queries: &Allocation<B>,+ queries: impl BufferRef<Backend = B>,batch_dim: &BatchTopology,state: &AttentionState<B>,- encoder: &mut Encoder<B>,- ) -> Result<Allocation<B>, B::Error> {+ command_buffer: &mut <B::CommandBuffer as CommandBuffer>::Encoding,+ ) -> Result<B::ScratchBuffer, B::Error> {let trie = if batch_dim.is_flat() {None} else {- let mut trie = encoder.allocate_constant(batch_dim.size() as usize * size_of::<TrieNode>())?;- trie.copyin(batch_dim.nodes());- Some(trie)+ Some(command_buffer.allocate_constant_from_slice(batch_dim.nodes())?)};self.kernel.encode(@@ -171,21 +168,21 @@ impl<B: Backend> Attention<B> {sinks: self.sinks.as_ref(),cache: state.view(),},- encoder,+ command_buffer,)}- fn prepare_kv_and_queries<'keys, 'values>(+ fn prepare_kv_and_queries(&self,- input: &Allocation<B>,- keys: impl BufferArgMut<'keys, B>,- values: impl BufferArgMut<'values, B>,+ input: impl BufferRef<Backend = B>,+ keys: impl BufferMut<Backend = B>,+ values: impl BufferMut<Backend = B>,kv_token_offset: u32,num_q_heads: u32,precalculated_rope: Option<&PrecalculatedRoPE<B>>,batch_dim: u32,- encoder: &mut Encoder<B>,- ) -> Result<Allocation<B>, B::Error> {+ command_buffer: &mut <B::CommandBuffer as CommandBuffer>::Encoding,+ ) -> Result<B::ScratchBuffer, B::Error> {let num_kv_heads = self.num_kv_heads.expect("KV prepare requires KV heads");// Appended KV is tightly packed; attention projections may have a trailing gate segment.let input_row_stride = if num_q_heads == 0 {@@ -194,9 +191,9 @@ impl<B: Backend> Attention<B> {self.projection_dim};let mut queries = if num_q_heads == 0 {- encoder.allocate_scratch(self.data_type.size_in_bytes())?+ command_buffer.allocate_scratch(self.data_type.size_in_bytes())?} else {- encoder.allocate_scratch_for_shape(&[self.num_q_heads, batch_dim, self.head_dim], self.data_type)?+ command_buffer.allocate_scratch_for_shape(&[self.num_q_heads, batch_dim, self.head_dim], self.data_type)?};self.prepare.encode(input,@@ -212,25 +209,25 @@ impl<B: Backend> Attention<B> {Some(kv_token_offset),input_row_stride,batch_dim,- encoder,+ command_buffer,);Ok(queries)}fn prepare_queries(&self,- qkvg: &Allocation<B>,+ qkvg: impl BufferRef<Backend = B>,precalculated_rope: Option<&PrecalculatedRoPE<B>>,batch_dim: u32,- encoder: &mut Encoder<B>,- ) -> Result<Allocation<B>, B::Error> {+ command_buffer: &mut <B::CommandBuffer as CommandBuffer>::Encoding,+ ) -> Result<B::ScratchBuffer, B::Error> {let mut queries =- encoder.allocate_scratch_for_shape(&[self.num_q_heads, batch_dim, self.head_dim], self.data_type)?;+ command_buffer.allocate_scratch_for_shape(&[self.num_q_heads, batch_dim, self.head_dim], self.data_type)?;self.prepare.encode(qkvg,&mut queries,- None::<&mut Allocation<B>>,- None::<&mut Allocation<B>>,+ None::<&mut B::ScratchBuffer>,+ None::<&mut B::ScratchBuffer>,precalculated_rope.map(|rope| &rope.cosines),precalculated_rope.map(|rope| &rope.sines),self.num_q_heads,@@ -240,7 +237,7 @@ impl<B: Backend> Attention<B> {None,self.projection_dim,batch_dim,- encoder,+ command_buffer,);Ok(queries)}diff --git a/crates/uzu-engine/src/encodable_block/mixer/attention/qkv_norm.rs b/crates/uzu-engine/src/encodable_block/mixer/attention/qkv_norm.rsindex 81392f72a..0f762f19f 100644--- a/crates/uzu-engine/src/encodable_block/mixer/attention/qkv_norm.rs+++ b/crates/uzu-engine/src/encodable_block/mixer/attention/qkv_norm.rs@@ -2,7 +2,7 @@ use thiserror::Error;use crate::{backends::common::{- Allocation, Backend, Encoder,+ Backend, BufferMut, CommandBuffer, CommandBufferEncoding,kernel::{Kernels, QKVNormKernel},},config::normalization::{NormalizationConfig, UpcastMode},@@ -20,7 +20,7 @@ pub enum QKVNormError<B: Backend> {struct Head<B: Backend> {kernel: <B::Kernels as Kernels>::QKVNormKernel,- scales: Option<Allocation<B>>,+ scales: Option<B::GlobalBuffer>,config: NormalizationConfig,}@@ -97,7 +97,7 @@ impl<B: Backend> QKVNorm<B> {.expect("scaled norm requires parameter tree").leaf("scales")?.validate(&[head_dim], DataType::F32)?- .read_allocation()?,+ .read_buffer()?,)} else {None@@ -121,29 +121,29 @@ impl<B: Backend> QKVNorm<B> {pub fn encode(&self,- qkvg: &mut Allocation<B>,+ qkvg: impl BufferMut<Backend = B>,batch_dim: u32,- encoder: &mut Encoder<B>,+ command_buffer: &mut <B::CommandBuffer as CommandBuffer>::Encoding,) -> Result<(), B::Error> {- self.encode_packed(qkvg, batch_dim, self.num_q_heads, self.projection_row_stride, encoder)+ self.encode_packed(qkvg, batch_dim, self.num_q_heads, self.projection_row_stride, command_buffer)}pub fn encode_key_value(&self,- key_value: &mut Allocation<B>,+ key_value: impl BufferMut<Backend = B>,batch_dim: u32,- encoder: &mut Encoder<B>,+ command_buffer: &mut <B::CommandBuffer as CommandBuffer>::Encoding,) -> Result<(), B::Error> {- self.encode_packed(key_value, batch_dim, 0, 2 * self.num_kv_heads * self.head_dim, encoder)+ self.encode_packed(key_value, batch_dim, 0, 2 * self.num_kv_heads * self.head_dim, command_buffer)}fn encode_packed(&self,- buffer: &mut Allocation<B>,+ mut buffer: impl BufferMut<Backend = B>,batch_dim: u32,q_heads: u32,input_row_stride: u32,- encoder: &mut Encoder<B>,+ command_buffer: &mut <B::CommandBuffer as CommandBuffer>::Encoding,) -> Result<(), B::Error> {let packed_row_width = (q_heads + 2 * self.num_kv_heads) * self.head_dim;assert!(@@ -151,7 +151,7 @@ impl<B: Backend> QKVNorm<B> {"QKV norm input row stride ({input_row_stride}) is smaller than its packed row width ({packed_row_width})");- encoder.push_debug_group("qkv norm");+ command_buffer.push_debug_group("qkv norm");let kv = self.num_kv_heads;let heads = [(&self.query, 0, q_heads), (&self.key, q_heads, kv), (&self.value, q_heads + kv, kv)];@@ -163,9 +163,9 @@ impl<B: Backend> QKVNorm<B> {continue;}head.kernel.encode(- None::<&Allocation<B>>,+ None::<&B::ScratchBuffer>,head.scales.as_ref(),- &mut *buffer,+ buffer.reborrow(),batch_dim,input_row_stride,self.head_dim,@@ -174,11 +174,11 @@ impl<B: Backend> QKVNorm<B> {head_offset,head_count,head.config.upcast_mode == UpcastMode::FullLayer,- encoder,+ command_buffer,);}- encoder.pop_debug_group();+ command_buffer.pop_debug_group();Ok(())}diff --git a/crates/uzu-engine/src/encodable_block/mixer/attention/rope.rs b/crates/uzu-engine/src/encodable_block/mixer/attention/rope.rsindex 97009a5b1..fe220d6db 100644--- a/crates/uzu-engine/src/encodable_block/mixer/attention/rope.rs+++ b/crates/uzu-engine/src/encodable_block/mixer/attention/rope.rs@@ -1,11 +1,11 @@use crate::{- backends::common::{Allocation, Backend, Encoder},+ backends::common::{Backend, CommandBuffer, CommandBufferEncoding},config::rope::AnyRoPEConfig,};pub struct PrecalculatedRoPE<B: Backend> {- pub cosines: Allocation<B>,- pub sines: Allocation<B>,+ pub cosines: B::ConstantBuffer,+ pub sines: B::ConstantBuffer,pub dim: u32,}@@ -13,7 +13,7 @@ impl<B: Backend> PrecalculatedRoPE<B> {pub fn precalculate(rope_config: &AnyRoPEConfig,token_positions: &[u32],- encoder: &mut Encoder<B>,+ command_buffer: &mut <B::CommandBuffer as CommandBuffer>::Encoding,) -> Result<Self, B::Error> {let head_dim = *rope_config.head_dim();assert!(head_dim > 0 && head_dim.is_multiple_of(2), "RoPE head_dim must be positive and even");@@ -101,14 +101,9 @@ impl<B: Backend> PrecalculatedRoPE<B> {}}- let mut sines_allocation = encoder.allocate_constant(sines.len() * std::mem::size_of::<f32>())?;- sines_allocation.copyin(sines.as_ref());- let mut cosines_allocation = encoder.allocate_constant(cosines.len() * std::mem::size_of::<f32>())?;- cosines_allocation.copyin(cosines.as_ref());-Ok(Self {- cosines: cosines_allocation,- sines: sines_allocation,+ cosines: command_buffer.allocate_constant_from_slice(&cosines)?,+ sines: command_buffer.allocate_constant_from_slice(&sines)?,dim: *rope_config.head_dim(),})}diff --git a/crates/uzu-engine/src/encodable_block/mixer/attention/state.rs b/crates/uzu-engine/src/encodable_block/mixer/attention/state.rsindex 646a190b4..9cef8b8e8 100644--- a/crates/uzu-engine/src/encodable_block/mixer/attention/state.rs+++ b/crates/uzu-engine/src/encodable_block/mixer/attention/state.rs@@ -3,7 +3,7 @@ use std::any::Any;use crate::{array::size_for_shape,backends::common::{- Backend, Buffer, Context, DeviceCapabilities, Encoder, Kernels, SparseBuffer,+ Backend, Buffer, CommandBuffer, Context, DeviceCapabilities, Kernels, SparseBuffer,gpu_types::{Copy, ring::RingParams},kernel::KVCacheUpdateKernel,},@@ -253,7 +253,7 @@ impl<B: Backend> MixerState<B> for AttentionState<B> {let buffer_end_page = bytes_required.div_ceil(buffer_page_size);if buffer_end_page > buffer_start_page {- buffer.map(context, &(buffer_start_page..buffer_end_page))?;+ buffer.map(context, buffer_start_page..buffer_end_page)?;}}@@ -265,18 +265,18 @@ impl<B: Backend> MixerState<B> for AttentionState<B> {fn encode_accept(&mut self,accepted_indices: &[u32],- encoder: &mut Encoder<B>,+ command_buffer: &mut <B::CommandBuffer as CommandBuffer>::Encoding,) -> Result<(), B::Error> {let copies = self.cache.accept(accepted_indices);- for copies_chunk in copies.chunks(B::MAX_INLINE_BYTES / size_of::<Copy>()) {+ if !copies.is_empty() {self.kv_cache_update.encode(self.keys.as_mut(),self.values.as_mut(),- copies_chunk,- copies_chunk.len() as u32,+ &copies,+ copies.len() as u32,self.element_dim,- encoder,+ command_buffer,);}diff --git a/crates/uzu-engine/src/encodable_block/mixer/delta_net.rs b/crates/uzu-engine/src/encodable_block/mixer/delta_net.rsindex a69aa54c6..04750b0e7 100644--- a/crates/uzu-engine/src/encodable_block/mixer/delta_net.rs+++ b/crates/uzu-engine/src/encodable_block/mixer/delta_net.rs@@ -3,7 +3,8 @@ use thiserror::Error;use crate::{array::size_for_shape,backends::common::{- Allocation, AllocationType, Backend, Context, Encoder, Kernels,+ Backend, Buffer, BufferRef, CommandBuffer, CommandBufferEncoding, CommandBufferExecutable,+ CommandBufferPending, Context, Kernels,kernel::{Conv1dPackKernel, ConvTreeScanKernel, DeltaNetConvScanKernel, DeltaNetConvUpdateKernel,DeltaNetNormGateKernel, DeltaNetPrefillKernel, DeltaNetPrefillPrepKernel, DeltaNetUpdateKernel,@@ -36,18 +37,18 @@ enum DeltaNetSuffixStatus<B: Backend> {suffix_length: u32,},Tree {- conv_states: Allocation<B>,- k: Allocation<B>,- v: Allocation<B>,- log_decay: Allocation<B>,- beta: Allocation<B>,+ conv_states: B::ScratchBuffer,+ k: B::ScratchBuffer,+ v: B::ScratchBuffer,+ log_decay: B::ScratchBuffer,+ beta: B::ScratchBuffer,parents: Box<[i32]>,},}pub struct DeltaNetState<B: Backend> {- conv_state: Allocation<B>,- ssm_state: Allocation<B>,+ conv_state: B::GlobalBuffer,+ ssm_state: B::GlobalBuffer,suffix_status: Option<DeltaNetSuffixStatus<B>>,state_advance: <B::Kernels as Kernels>::StateAdvanceKernel,}@@ -65,7 +66,7 @@ impl<B: Backend> MixerState<B> for DeltaNetState<B> {fn encode_accept(&mut self,accepted_indices: &[u32],- encoder: &mut Encoder<B>,+ command_buffer: &mut <B::CommandBuffer as CommandBuffer>::Encoding,) -> Result<(), B::Error> {let suffix_status = self.suffix_status.take().expect("delta net state has no suffix to accept");let accepted_index = *accepted_indices.last().expect("delta net state attempted to accept zero indices");@@ -90,14 +91,12 @@ impl<B: Backend> MixerState<B> for DeltaNetState<B> {let conv_state_size = self.conv_state.size();let accepted_offset = accepted_index as usize * conv_state_size;- encoder.encode_copy(- &conv_states,- accepted_offset..accepted_offset + conv_state_size,+ command_buffer.encode_copy(+ conv_states.subrange(accepted_offset..accepted_offset + conv_state_size),&mut self.conv_state,- ..,);- let accepted_indices_buffer = encoder.allocate_constant_from_slice(accepted_indices)?;+ let accepted_indices_buffer = command_buffer.allocate_constant_from_slice(accepted_indices)?;self.state_advance.encode(&k,&v,@@ -106,7 +105,7 @@ impl<B: Backend> MixerState<B> for DeltaNetState<B> {&accepted_indices_buffer,&mut self.ssm_state,accepted_indices.len() as u32,- encoder,+ command_buffer,);},}@@ -126,15 +125,15 @@ pub struct DeltaNet<B: Backend> {kernel_size: u32,outer_data_type: DataType,in_projection: Box<dyn Linear<B>>,- conv_weight: Allocation<B>,- conv_bias: Option<Allocation<B>>,+ conv_weight: B::GlobalBuffer,+ conv_bias: Option<B::GlobalBuffer>,conv_update: <B::Kernels as Kernels>::DeltaNetConvUpdateKernel,conv_pack: <B::Kernels as Kernels>::Conv1dPackKernel,conv_scan: <B::Kernels as Kernels>::DeltaNetConvScanKernel,conv_tree_scan: <B::Kernels as Kernels>::ConvTreeScanKernel,- a_log: Allocation<B>,- dt_bias: Allocation<B>,- norm_weight: Allocation<B>,+ a_log: B::GlobalBuffer,+ dt_bias: B::GlobalBuffer,+ norm_weight: B::GlobalBuffer,norm_epsilon: f32,delta_net_update: <B::Kernels as Kernels>::DeltaNetUpdateKernel,delta_net_prefill_prep: <B::Kernels as Kernels>::DeltaNetPrefillPrepKernel,@@ -165,7 +164,7 @@ impl<B: Backend> DeltaNet<B> {config: &DeltaNetConfig,parameter_tree: &ParameterTree<B>,context: &B::Context,- ) -> Result<(Self, Option<Allocation<B>>), DeltaNetNewError<B>> {+ ) -> Result<(Self, Option<B::GlobalBuffer>), DeltaNetNewError<B>> {if config.kernel_size < 2 {return Err(DeltaNetNewError::UnsupportedConfiguration(format!("kernel_size must be >= 2, got {}",@@ -206,9 +205,9 @@ impl<B: Backend> DeltaNet<B> {let conv_tree = parameter_tree.subtree("conv");let conv_weight =- conv_tree.leaf("weights")?.validate(&[conv_dim, config.kernel_size], INNER_DATA_TYPE)?.read_allocation()?;+ conv_tree.leaf("weights")?.validate(&[conv_dim, config.kernel_size], INNER_DATA_TYPE)?.read_buffer()?;let conv_bias = if conv_config.has_biases {- Some(conv_tree.leaf("biases")?.validate(&[conv_dim], INNER_DATA_TYPE)?.read_allocation()?)+ Some(conv_tree.leaf("biases")?.validate(&[conv_dim], INNER_DATA_TYPE)?.read_buffer()?)} else {None};@@ -228,13 +227,10 @@ impl<B: Backend> DeltaNet<B> {).map_err(DeltaNetNewError::Backend)?;- let a_log = parameter_tree.leaf("a_log")?.validate(&[config.num_heads], INNER_DATA_TYPE)?.read_allocation()?;- let dt_bias =- parameter_tree.leaf("dt_bias")?.validate(&[config.num_heads], INNER_DATA_TYPE)?.read_allocation()?;- let norm_weight = parameter_tree- .leaf("norm.scales")?- .validate(&[config.value_head_dim], INNER_DATA_TYPE)?- .read_allocation()?;+ let a_log = parameter_tree.leaf("a_log")?.validate(&[config.num_heads], INNER_DATA_TYPE)?.read_buffer()?;+ let dt_bias = parameter_tree.leaf("dt_bias")?.validate(&[config.num_heads], INNER_DATA_TYPE)?.read_buffer()?;+ let norm_weight =+ parameter_tree.leaf("norm.scales")?.validate(&[config.value_head_dim], INNER_DATA_TYPE)?.read_buffer()?;let norm_epsilon = config.norm_config.epsilon;let delta_net_update =<B::Kernels as Kernels>::DeltaNetUpdateKernel::new(context, outer_data_type, config.head_dim)@@ -333,29 +329,29 @@ impl<B: Backend> DeltaNet<B> {fn encode_tree_verify(&self,- in_projected: Allocation<B>,+ in_projected: impl BufferRef<Backend = B>,batch_dim: &BatchTopology,state: &mut DeltaNetState<B>,- encoder: &mut Encoder<B>,- ) -> Result<Allocation<B>, B::Error> {+ command_buffer: &mut <B::CommandBuffer as CommandBuffer>::Encoding,+ ) -> Result<B::ScratchBuffer, B::Error> {let tree_verify = self.tree_verify.as_ref().expect("DeltaNet tree verification is unsupported");let tree_size = batch_dim.size();- let parents = encoder.allocate_constant_from_slice(batch_dim.parents())?;- let trie = encoder.allocate_constant_from_slice(batch_dim.nodes())?;+ let parents = command_buffer.allocate_constant_from_slice(batch_dim.parents())?;+ let trie = command_buffer.allocate_constant_from_slice(batch_dim.nodes())?;- let mut conv_states =- encoder.allocate_scratch_for_shape(&[tree_size, self.conv_dim, self.kernel_size - 1], INNER_DATA_TYPE)?;- let mut k = encoder.allocate_scratch_for_shape(&[tree_size, self.key_dim], self.outer_data_type)?;- let mut v = encoder.allocate_scratch_for_shape(&[tree_size, self.value_dim], self.outer_data_type)?;- let mut beta = encoder.allocate_scratch_for_shape(&[tree_size, self.num_heads], INNER_DATA_TYPE)?;- let mut log_decay = encoder.allocate_scratch_for_shape(&[tree_size, self.num_heads], INNER_DATA_TYPE)?;+ let mut conv_states = command_buffer+ .allocate_scratch_for_shape(&[tree_size, self.conv_dim, self.kernel_size - 1], INNER_DATA_TYPE)?;+ let mut k = command_buffer.allocate_scratch_for_shape(&[tree_size, self.key_dim], self.outer_data_type)?;+ let mut v = command_buffer.allocate_scratch_for_shape(&[tree_size, self.value_dim], self.outer_data_type)?;+ let mut beta = command_buffer.allocate_scratch_for_shape(&[tree_size, self.num_heads], INNER_DATA_TYPE)?;+ let mut log_decay = command_buffer.allocate_scratch_for_shape(&[tree_size, self.num_heads], INNER_DATA_TYPE)?;let mut tree_projected =- encoder.allocate_scratch_for_shape(&[tree_size, self.total_proj_dim], self.outer_data_type)?;- let mut q = encoder.allocate_scratch_for_shape(&[tree_size, self.key_dim], self.outer_data_type)?;+ command_buffer.allocate_scratch_for_shape(&[tree_size, self.total_proj_dim], self.outer_data_type)?;+ let mut q = command_buffer.allocate_scratch_for_shape(&[tree_size, self.key_dim], self.outer_data_type)?;self.conv_tree_scan.encode(- &in_projected,+ in_projected,&self.conv_weight,self.conv_bias.as_ref(),&state.conv_state,@@ -365,7 +361,7 @@ impl<B: Backend> DeltaNet<B> {tree_size,self.total_proj_dim,self.conv_dim,- encoder,+ command_buffer,);self.delta_net_tree_prep.encode(@@ -382,7 +378,7 @@ impl<B: Backend> DeltaNet<B> {self.key_dim,self.value_dim,tree_size,- encoder,+ command_buffer,);let mut delta_output = tree_verify.encode(@@ -396,7 +392,7 @@ impl<B: Backend> DeltaNet<B> {h0: &state.ssm_state,tree_size,},- encoder,+ command_buffer,)?;self.delta_net_norm_gate.encode(&mut delta_output,@@ -409,10 +405,10 @@ impl<B: Backend> DeltaNet<B> {self.total_proj_dim,self.norm_epsilon,tree_size,- encoder,+ command_buffer,);- let output = self.out_projection.encode(delta_output, tree_size, encoder)?;+ let output = self.out_projection.encode(delta_output, tree_size, command_buffer)?;state.suffix_status = Some(DeltaNetSuffixStatus::Tree {conv_states,k,@@ -439,20 +435,16 @@ impl<B: Backend> Mixer<B> for DeltaNet<B> {_max_context_length: Option<u32>,context: &B::Context,) -> Result<Box<dyn MixerState<B>>, B::Error> {- let mut conv_state = context.create_allocation(- size_for_shape(&[self.conv_dim, self.kernel_size - 1], INNER_DATA_TYPE),- AllocationType::Global,- )?;+ let mut conv_state =+ context.create_buffer(size_for_shape(&[self.conv_dim, self.kernel_size - 1], INNER_DATA_TYPE))?;- let mut ssm_state = context.create_allocation(- size_for_shape(&[self.num_heads, self.value_head_dim, self.head_dim], INNER_DATA_TYPE),- AllocationType::Global,- )?;+ let mut ssm_state = context+ .create_buffer(size_for_shape(&[self.num_heads, self.value_head_dim, self.head_dim], INNER_DATA_TYPE))?;- let mut zero_encoder = Encoder::<B>::new(context)?;- zero_encoder.encode_fill(&mut conv_state, 0);- zero_encoder.encode_fill(&mut ssm_state, 0);- zero_encoder.end_encoding().submit().wait_until_completed()?;+ let mut zero_command_buffer = context.create_command_buffer(None, None)?;+ zero_command_buffer.encode_fill(&mut conv_state, 0);+ zero_command_buffer.encode_fill(&mut ssm_state, 0);+ zero_command_buffer.end_encoding().submit().wait_until_completed()?;let state_advance = <B::Kernels as Kernels>::StateAdvanceKernel::new(context,@@ -472,13 +464,13 @@ impl<B: Backend> Mixer<B> for DeltaNet<B> {fn encode(&self,- hidden: Allocation<B>,+ hidden: B::ScratchBuffer,precalculated_rope: Option<&PrecalculatedRoPE<B>>,batch_dim: &BatchTopology,state: Option<MaybeMut<dyn MixerState<B>>>,- encoder: &mut Encoder<B>,- ) -> Result<Allocation<B>, B::Error> {- encoder.push_debug_group("delta net");+ command_buffer: &mut <B::CommandBuffer as CommandBuffer>::Encoding,+ ) -> Result<B::ScratchBuffer, B::Error> {+ command_buffer.push_debug_group("delta net");assert!(precalculated_rope.is_none(), "unexpected rope for delta net mixer");@@ -490,18 +482,18 @@ impl<B: Backend> Mixer<B> for DeltaNet<B> {assert!(state.suffix_status.is_none(), "delta net called with state with an unaccepted suffix");- let mut in_projected = self.in_projection.encode(hidden, batch_dim.size(), encoder)?;+ let mut in_projected = self.in_projection.encode(hidden, batch_dim.size(), command_buffer)?;if !batch_dim.full_accept() {- let output = self.encode_tree_verify(in_projected, batch_dim, state, encoder)?;+ let output = self.encode_tree_verify(&in_projected, batch_dim, state, command_buffer)?;- encoder.pop_debug_group();+ command_buffer.pop_debug_group();return Ok(output);}let mut delta_output =- encoder.allocate_scratch_for_shape(&[batch_dim.size(), self.value_dim], self.outer_data_type)?;+ command_buffer.allocate_scratch_for_shape(&[batch_dim.size(), self.value_dim], self.outer_data_type)?;if batch_dim.size() == 1 {self.conv_update.encode(&self.conv_weight,@@ -511,7 +503,7 @@ impl<B: Backend> Mixer<B> for DeltaNet<B> {self.kernel_size,self.conv_dim,self.kernel_size - 1,- encoder,+ command_buffer,);self.delta_net_update.encode(@@ -527,10 +519,10 @@ impl<B: Backend> Mixer<B> for DeltaNet<B> {self.key_dim,self.value_dim,self.norm_epsilon,- encoder,+ command_buffer,);} else {- let mut padded = encoder.allocate_scratch_for_shape(+ let mut padded = command_buffer.allocate_scratch_for_shape(&[batch_dim.size() + self.kernel_size - 1, self.total_proj_dim],INNER_DATA_TYPE,)?;@@ -542,7 +534,7 @@ impl<B: Backend> Mixer<B> for DeltaNet<B> {self.total_proj_dim,batch_dim.size(),self.conv_dim,- encoder,+ command_buffer,);self.conv_scan.encode(&padded,@@ -556,7 +548,7 @@ impl<B: Backend> Mixer<B> for DeltaNet<B> {self.kernel_size - 1,self.conv_dim,self.total_proj_dim,- encoder,+ command_buffer,);if let Some(chunked) = self.chunked.as_ref().filter(|chunked| chunked.should_use(batch_dim.size())) {chunked.encode(@@ -573,24 +565,24 @@ impl<B: Backend> Mixer<B> for DeltaNet<B> {value_dim: self.value_dim,suffix_len: batch_dim.size(),},- encoder,+ command_buffer,)?;} else {let mut prep_q_norm =- encoder.allocate_scratch_for_shape(&[batch_dim.size(), self.key_dim], INNER_DATA_TYPE)?;+ command_buffer.allocate_scratch_for_shape(&[batch_dim.size(), self.key_dim], INNER_DATA_TYPE)?;let mut prep_k_norm =- encoder.allocate_scratch_for_shape(&[batch_dim.size(), self.key_dim], INNER_DATA_TYPE)?;+ command_buffer.allocate_scratch_for_shape(&[batch_dim.size(), self.key_dim], INNER_DATA_TYPE)?;let mut prep_beta =- encoder.allocate_scratch_for_shape(&[batch_dim.size(), self.num_heads], INNER_DATA_TYPE)?;+ command_buffer.allocate_scratch_for_shape(&[batch_dim.size(), self.num_heads], INNER_DATA_TYPE)?;let mut prep_decay =- encoder.allocate_scratch_for_shape(&[batch_dim.size(), self.num_heads], INNER_DATA_TYPE)?;+ command_buffer.allocate_scratch_for_shape(&[batch_dim.size(), self.num_heads], INNER_DATA_TYPE)?;self.delta_net_prefill_prep.encode(&in_projected,&self.a_log,&self.dt_bias,&mut prep_q_norm,&mut prep_k_norm,- None::<&mut Allocation<B>>,+ None::<&mut B::ScratchBuffer>,&mut prep_beta,&mut prep_decay,self.num_heads,@@ -598,7 +590,7 @@ impl<B: Backend> Mixer<B> for DeltaNet<B> {self.key_dim,self.value_dim,batch_dim.size(),- encoder,+ command_buffer,);self.delta_net_prefill.encode(&prep_q_norm,@@ -615,7 +607,7 @@ impl<B: Backend> Mixer<B> for DeltaNet<B> {self.value_dim,batch_dim.size(),self.value_head_dim.div_ceil(16),- encoder,+ command_buffer,);}self.delta_net_norm_gate.encode(@@ -629,7 +621,7 @@ impl<B: Backend> Mixer<B> for DeltaNet<B> {self.total_proj_dim,self.norm_epsilon,batch_dim.size(),- encoder,+ command_buffer,);}@@ -637,9 +629,9 @@ impl<B: Backend> Mixer<B> for DeltaNet<B> {suffix_length: batch_dim.size(),});- let output = self.out_projection.encode(delta_output, batch_dim.size(), encoder)?;+ let output = self.out_projection.encode(delta_output, batch_dim.size(), command_buffer)?;- encoder.pop_debug_group();+ command_buffer.pop_debug_group();Ok(output)}diff --git a/crates/uzu-engine/src/encodable_block/mixer/delta_net/tree_verify.rs b/crates/uzu-engine/src/encodable_block/mixer/delta_net/tree_verify.rsindex b021ec5ec..223aceff9 100644--- a/crates/uzu-engine/src/encodable_block/mixer/delta_net/tree_verify.rs+++ b/crates/uzu-engine/src/encodable_block/mixer/delta_net/tree_verify.rs@@ -1,7 +1,4 @@-use crate::{- backends::common::{Allocation, Backend},- data_type::DataType,-};+use crate::{backends::common::Backend, data_type::DataType};#[derive(Clone, Copy)]pub struct TreeVerifyNewArguments {@@ -14,13 +11,13 @@ pub struct TreeVerifyNewArguments {#[derive(Clone, Copy)]pub struct TreeVerifyEncodeArguments<'a, B: Backend> {- pub q: &'a Allocation<B>,- pub k: &'a Allocation<B>,- pub v: &'a Allocation<B>,- pub trie: &'a Allocation<B>,- pub log_decay: &'a Allocation<B>,- pub beta: &'a Allocation<B>,- pub h0: &'a Allocation<B>,+ pub q: &'a B::ScratchBuffer,+ pub k: &'a B::ScratchBuffer,+ pub v: &'a B::ScratchBuffer,+ pub trie: &'a B::ConstantBuffer,+ pub log_decay: &'a B::ScratchBuffer,+ pub beta: &'a B::ScratchBuffer,+ pub h0: &'a B::GlobalBuffer,pub tree_size: u32,}diff --git a/crates/uzu-engine/src/encodable_block/mixer/mamba2.rs b/crates/uzu-engine/src/encodable_block/mixer/mamba2.rsindex a8c79cab1..a59c4a90c 100644--- a/crates/uzu-engine/src/encodable_block/mixer/mamba2.rs+++ b/crates/uzu-engine/src/encodable_block/mixer/mamba2.rs@@ -3,7 +3,7 @@ use thiserror::Error;use crate::{array::size_for_shape,backends::common::{- Allocation, AllocationType, Backend, Context, Encoder, Kernels,+ Backend, CommandBuffer, CommandBufferEncoding, CommandBufferExecutable, CommandBufferPending, Context, Kernels,gpu_types::ActivationType,kernel::{Conv1dDecodeKernel, Conv1dPackKernel, Conv1dScanKernel, SSDPrefill64Kernel, SSDPrefillKernel,@@ -24,8 +24,8 @@ use crate::{const INNER_DATA_TYPE: DataType = DataType::F32;pub struct Mamba2State<B: Backend> {- conv_state: Allocation<B>,- ssm_state: Allocation<B>,+ conv_state: B::GlobalBuffer,+ ssm_state: B::GlobalBuffer,suffix_length: Option<u32>,}@@ -42,7 +42,7 @@ impl<B: Backend> MixerState<B> for Mamba2State<B> {fn encode_accept(&mut self,accepted_indices: &[u32],- _encoder: &mut Encoder<B>,+ _command_buffer: &mut <B::CommandBuffer as CommandBuffer>::Encoding,) -> Result<(), <B as Backend>::Error> {assert!(self.suffix_length.take() == Some(*accepted_indices.last().unwrap() + 1));Ok(())@@ -64,14 +64,14 @@ pub struct Mamba2<B: Backend> {conv_dim: u32,activation_type: ActivationType,in_projection: Box<dyn Linear<B>>,- gate_bias: Allocation<B>,+ gate_bias: B::GlobalBuffer,split_inproj: <B::Kernels as Kernels>::SplitInProjKernel,- conv_weight: Allocation<B>,- conv_bias: Option<Allocation<B>>,+ conv_weight: B::GlobalBuffer,+ conv_bias: Option<B::GlobalBuffer>,conv_decode: <B::Kernels as Kernels>::Conv1dDecodeKernel,conv_pack: <B::Kernels as Kernels>::Conv1dPackKernel,conv_scan: <B::Kernels as Kernels>::Conv1dScanKernel,- skip_connection_weight: Allocation<B>,+ skip_connection_weight: B::GlobalBuffer,ssd_update: <B::Kernels as Kernels>::SSDUpdateKernel,ssd_prefill: Mamba2SSDPrefillVariant<B>,out_projection: Box<dyn Linear<B>>,@@ -96,7 +96,7 @@ impl<B: Backend> Mamba2<B> {config: &Mamba2Config,parameter_tree: &ParameterTree<B>,context: &B::Context,- ) -> Result<(Self, Option<Allocation<B>>), Mamba2NewError<B>> {+ ) -> Result<(Self, Option<B::GlobalBuffer>), Mamba2NewError<B>> {let kernel_size = config.kernel_size;let num_heads = config.num_heads;let num_groups = config.num_groups;@@ -124,7 +124,7 @@ impl<B: Backend> Mamba2<B> {¶meter_tree.subtree("in_projection"),)?;- let gate_bias = parameter_tree.leaf("gate_bias")?.validate(&[inner_dim], INNER_DATA_TYPE)?.read_allocation()?;+ let gate_bias = parameter_tree.leaf("gate_bias")?.validate(&[inner_dim], INNER_DATA_TYPE)?.read_buffer()?;let split_inproj = <B::Kernels as Kernels>::SplitInProjKernel::new(context, INNER_DATA_TYPE).map_err(Mamba2NewError::Backend)?;@@ -132,9 +132,9 @@ impl<B: Backend> Mamba2<B> {let conv_tree = parameter_tree.subtree("conv");let conv_weight =- conv_tree.leaf("weights")?.validate(&[conv_dim, kernel_size], INNER_DATA_TYPE)?.read_allocation()?;+ conv_tree.leaf("weights")?.validate(&[conv_dim, kernel_size], INNER_DATA_TYPE)?.read_buffer()?;let conv_bias = if conv_config.has_biases {- Some(conv_tree.leaf("biases")?.validate(&[conv_dim], INNER_DATA_TYPE)?.read_allocation()?)+ Some(conv_tree.leaf("biases")?.validate(&[conv_dim], INNER_DATA_TYPE)?.read_buffer()?)} else {None};@@ -147,10 +147,8 @@ impl<B: Backend> Mamba2<B> {<B::Kernels as Kernels>::Conv1dScanKernel::new(context, INNER_DATA_TYPE, conv_config.has_biases).map_err(Mamba2NewError::Backend)?;- let skip_connection_weight = parameter_tree- .leaf("skip_connection_weight")?- .validate(&[num_heads], INNER_DATA_TYPE)?- .read_allocation()?;+ let skip_connection_weight =+ parameter_tree.leaf("skip_connection_weight")?.validate(&[num_heads], INNER_DATA_TYPE)?.read_buffer()?;let ssd_update = <B::Kernels as Kernels>::SSDUpdateKernel::new(context, INNER_DATA_TYPE, true).map_err(Mamba2NewError::Backend)?;@@ -219,20 +217,16 @@ impl<B: Backend> Mixer<B> for Mamba2<B> {_max_context_length: Option<u32>,context: &B::Context,) -> Result<Box<dyn MixerState<B>>, B::Error> {- let mut conv_state = context.create_allocation(- size_for_shape(&[self.conv_dim, self.kernel_size - 1], INNER_DATA_TYPE),- AllocationType::Global,- )?;+ let mut conv_state =+ context.create_buffer(size_for_shape(&[self.conv_dim, self.kernel_size - 1], INNER_DATA_TYPE))?;- let mut ssm_state = context.create_allocation(- size_for_shape(&[self.num_heads, self.head_dim, self.state_dim], INNER_DATA_TYPE),- AllocationType::Global,- )?;+ let mut ssm_state =+ context.create_buffer(size_for_shape(&[self.num_heads, self.head_dim, self.state_dim], INNER_DATA_TYPE))?;- let mut zero_encoder = Encoder::<B>::new(context)?;- zero_encoder.encode_fill(&mut conv_state, 0);- zero_encoder.encode_fill(&mut ssm_state, 0);- zero_encoder.end_encoding().submit().wait_until_completed()?;+ let mut zero_command_buffer = context.create_command_buffer(None, None)?;+ zero_command_buffer.encode_fill(&mut conv_state, 0);+ zero_command_buffer.encode_fill(&mut ssm_state, 0);+ zero_command_buffer.end_encoding().submit().wait_until_completed()?;Ok(Box::new(Mamba2State {conv_state,@@ -243,13 +237,13 @@ impl<B: Backend> Mixer<B> for Mamba2<B> {fn encode(&self,- hidden: Allocation<B>,+ hidden: B::ScratchBuffer,precalculated_rope: Option<&PrecalculatedRoPE<B>>,batch_dim: &BatchTopology,state: Option<MaybeMut<dyn MixerState<B>>>,- encoder: &mut Encoder<B>,- ) -> Result<Allocation<B>, B::Error> {- encoder.push_debug_group("mamba2");+ command_buffer: &mut <B::CommandBuffer as CommandBuffer>::Encoding,+ ) -> Result<B::ScratchBuffer, B::Error> {+ command_buffer.push_debug_group("mamba2");assert!(precalculated_rope.is_none(), "unexpected rope for mamba2 mixer");@@ -265,13 +259,14 @@ impl<B: Backend> Mixer<B> for Mamba2<B> {assert!(state.suffix_length.is_none(), "mamba2 called with state with unaccepted tokens");- let in_projected = self.in_projection.encode(hidden, batch_dim.size(), encoder)?;+ let in_projected = self.in_projection.encode(hidden, batch_dim.size(), command_buffer)?;let mut conv_inputs =- encoder.allocate_scratch_for_shape(&[batch_dim.size(), self.conv_dim], INNER_DATA_TYPE)?;- let mut gate =- encoder.allocate_scratch_for_shape(&[batch_dim.size(), self.num_heads, self.head_dim], INNER_DATA_TYPE)?;- let mut time_step = encoder.allocate_scratch_for_shape(&[batch_dim.size(), self.num_heads], INNER_DATA_TYPE)?;+ command_buffer.allocate_scratch_for_shape(&[batch_dim.size(), self.conv_dim], INNER_DATA_TYPE)?;+ let mut gate = command_buffer+ .allocate_scratch_for_shape(&[batch_dim.size(), self.num_heads, self.head_dim], INNER_DATA_TYPE)?;+ let mut time_step =+ command_buffer.allocate_scratch_for_shape(&[batch_dim.size(), self.num_heads], INNER_DATA_TYPE)?;self.split_inproj.encode(&in_projected,&mut conv_inputs,@@ -283,14 +278,14 @@ impl<B: Backend> Mixer<B> for Mamba2<B> {self.conv_dim,self.inner_dim,self.num_heads,- encoder,+ command_buffer,);- let mut conv_x =- encoder.allocate_scratch_for_shape(&[batch_dim.size(), self.num_heads, self.head_dim], INNER_DATA_TYPE)?;- let mut state_b = encoder+ let mut conv_x = command_buffer+ .allocate_scratch_for_shape(&[batch_dim.size(), self.num_heads, self.head_dim], INNER_DATA_TYPE)?;+ let mut state_b = command_buffer.allocate_scratch_for_shape(&[batch_dim.size(), self.num_groups, self.state_dim], INNER_DATA_TYPE)?;- let mut state_c = encoder+ let mut state_c = command_buffer.allocate_scratch_for_shape(&[batch_dim.size(), self.num_groups, self.state_dim], INNER_DATA_TYPE)?;let state_stride = self.kernel_size - 1;if batch_dim.size() == 1 {@@ -298,7 +293,7 @@ impl<B: Backend> Mixer<B> for Mamba2<B> {&conv_inputs,&self.conv_weight,self.conv_bias.as_ref(),- None::<&Allocation<B>>,+ None::<&B::GlobalBuffer>,&mut conv_x,&mut state_b,&mut state_c,@@ -311,10 +306,10 @@ impl<B: Backend> Mixer<B> for Mamba2<B> {self.inner_dim,self.num_groups * self.state_dim,self.activation_type,- encoder,+ command_buffer,);} else {- let mut padded = encoder+ let mut padded = command_buffer.allocate_scratch_for_shape(&[batch_dim.size() + state_stride, self.conv_dim], INNER_DATA_TYPE)?;self.conv_pack.encode(&state.conv_state,@@ -324,7 +319,7 @@ impl<B: Backend> Mixer<B> for Mamba2<B> {self.conv_dim,batch_dim.size(),self.conv_dim,- encoder,+ command_buffer,);self.conv_scan.encode(&padded,@@ -342,12 +337,12 @@ impl<B: Backend> Mixer<B> for Mamba2<B> {self.inner_dim,self.num_groups * self.state_dim,self.activation_type,- encoder,+ command_buffer,);}let mut ssd_output =- encoder.allocate_scratch_for_shape(&[batch_dim.size(), self.inner_dim], INNER_DATA_TYPE)?;+ command_buffer.allocate_scratch_for_shape(&[batch_dim.size(), self.inner_dim], INNER_DATA_TYPE)?;let x_strides = [self.num_heads * self.head_dim, self.head_dim, 1];let dt_strides = [self.num_heads, 1];let cb_strides = [self.num_groups * self.state_dim, self.state_dim, 1];@@ -362,7 +357,7 @@ impl<B: Backend> Mixer<B> for Mamba2<B> {&state_c,&self.skip_connection_weight,&gate,- None::<&Allocation<B>>,+ None::<&B::GlobalBuffer>,&mut ssd_output,&mut state.ssm_state,group_size,@@ -374,7 +369,7 @@ impl<B: Backend> Mixer<B> for Mamba2<B> {batch_dim.size(),self.num_heads,self.head_dim,- encoder,+ command_buffer,);} else {let state_strides = [self.head_dim * self.state_dim, self.state_dim, 1];@@ -397,7 +392,7 @@ impl<B: Backend> Mixer<B> for Mamba2<B> {&state_strides,self.num_heads,self.head_dim,- encoder,+ command_buffer,),Mamba2SSDPrefillVariant::Special64(ssd_prefill) => ssd_prefill.encode(&conv_x,@@ -417,16 +412,16 @@ impl<B: Backend> Mixer<B> for Mamba2<B> {&state_strides,self.num_heads,self.head_dim,- encoder,+ command_buffer,),}}state.suffix_length = Some(batch_dim.size());- let output = self.out_projection.encode(ssd_output, batch_dim.size(), encoder)?;+ let output = self.out_projection.encode(ssd_output, batch_dim.size(), command_buffer)?;- encoder.pop_debug_group();+ command_buffer.pop_debug_group();Ok(output)}diff --git a/crates/uzu-engine/src/encodable_block/mixer/mod.rs b/crates/uzu-engine/src/encodable_block/mixer/mod.rsindex e38911c01..a7a2dc9fe 100644--- a/crates/uzu-engine/src/encodable_block/mixer/mod.rs+++ b/crates/uzu-engine/src/encodable_block/mixer/mod.rs@@ -3,7 +3,7 @@ use std::any::Any;use thiserror::Error;use crate::{- backends::common::{Allocation, Backend, Encoder},+ backends::common::{Backend, CommandBuffer},config::{rope::AnyRoPEConfig, token_mixer::AnyTokenMixerConfig},data_type::DataType,encodable_block::{@@ -35,7 +35,7 @@ pub trait MixerState<B: Backend>: Any + Send {fn encode_accept(&mut self,accepted_indices: &[u32],- encoder: &mut Encoder<B>,+ command_buffer: &mut <B::CommandBuffer as CommandBuffer>::Encoding,) -> Result<(), B::Error>;}@@ -61,12 +61,12 @@ pub trait Mixer<B: Backend>: Any + Send + Sync {fn encode(&self,- hidden: Allocation<B>,+ hidden: B::ScratchBuffer,precalculated_rope: Option<&PrecalculatedRoPE<B>>,batch_dim: &BatchTopology,state: Option<MaybeMut<dyn MixerState<B>>>,- encoder: &mut Encoder<B>,- ) -> Result<Allocation<B>, B::Error>;+ command_buffer: &mut <B::CommandBuffer as CommandBuffer>::Encoding,+ ) -> Result<B::ScratchBuffer, B::Error>;}#[derive(Debug, Error)]@@ -89,7 +89,7 @@ impl<B: Backend> dyn Mixer<B> {config: &AnyTokenMixerConfig,parameter_tree: &ParameterTree<B>,context: &B::Context,- ) -> Result<(Box<dyn Mixer<B>>, Option<Allocation<B>>), MixerNewError<B>> {+ ) -> Result<(Box<dyn Mixer<B>>, Option<B::GlobalBuffer>), MixerNewError<B>> {match config {AnyTokenMixerConfig::AttentionConfig(config) => {let (attention, in_projection_input_hadamard_factors) =diff --git a/crates/uzu-engine/src/encodable_block/mixer/short_conv.rs b/crates/uzu-engine/src/encodable_block/mixer/short_conv.rsindex 4e7fd4b9f..e67eb8660 100644--- a/crates/uzu-engine/src/encodable_block/mixer/short_conv.rs+++ b/crates/uzu-engine/src/encodable_block/mixer/short_conv.rs@@ -3,7 +3,8 @@ use thiserror::Error;use crate::{array::size_for_shape,backends::common::{- Allocation, AllocationType, Backend, Context, Encoder, Kernels,+ Backend, Buffer, BufferRef, CommandBuffer, CommandBufferEncoding, CommandBufferExecutable,+ CommandBufferPending, Context, Kernels,kernel::{ShortConvDecodeKernel, ShortConvPackKernel, ShortConvPrefillKernel, ShortConvTrieKernel},},config::token_mixer::short_conv::ShortConvConfig,@@ -22,12 +23,12 @@ enum ShortConvStateSuffixStatus<B: Backend> {suffix_length: u32,},Trie {- conv_states: Allocation<B>,+ conv_states: B::ScratchBuffer,},}pub struct ShortConvState<B: Backend> {- conv_state: Allocation<B>,+ conv_state: B::GlobalBuffer,suffix_state: Option<ShortConvStateSuffixStatus<B>>,}@@ -44,7 +45,7 @@ impl<B: Backend> MixerState<B> for ShortConvState<B> {fn encode_accept(&mut self,accepted_indices: &[u32],- encoder: &mut Encoder<B>,+ command_buffer: &mut <B::CommandBuffer as CommandBuffer>::Encoding,) -> Result<(), B::Error> {let suffix_state_type =self.suffix_state.take().expect("Called short conv state encode accept on a state with nothing to accept");@@ -63,11 +64,9 @@ impl<B: Backend> MixerState<B> for ShortConvState<B> {} => {let conv_state_size = self.conv_state.size();let accepted_offset = accepted_index as usize * conv_state_size;- encoder.encode_copy(- &conv_states,- accepted_offset..accepted_offset + conv_state_size,+ command_buffer.encode_copy(+ conv_states.subrange(accepted_offset..accepted_offset + conv_state_size),&mut self.conv_state,- ..,);Ok(())},@@ -85,8 +84,8 @@ pub struct ShortConv<B: Backend> {short_conv_prefill: <B::Kernels as Kernels>::ShortConvPrefillKernel,short_conv_decode: <B::Kernels as Kernels>::ShortConvDecodeKernel,short_conv_trie: <B::Kernels as Kernels>::ShortConvTrieKernel,- conv_weight: Allocation<B>,- conv_bias: Option<Allocation<B>>,+ conv_weight: B::GlobalBuffer,+ conv_bias: Option<B::GlobalBuffer>,}#[derive(Debug, Error)]@@ -108,7 +107,7 @@ impl<B: Backend> ShortConv<B> {config: &ShortConvConfig,parameter_tree: &ParameterTree<B>,context: &B::Context,- ) -> Result<(Self, Option<Allocation<B>>), ShortConvNewError<B>> {+ ) -> Result<(Self, Option<B::GlobalBuffer>), ShortConvNewError<B>> {let kernel_size = config.kernel_size;if kernel_size < 2 {return Err(ShortConvNewError::UnsupportedConfiguration(format!(@@ -139,11 +138,11 @@ impl<B: Backend> ShortConv<B> {let conv_data_type = DataType::F32;let conv_weight =- conv_tree.leaf("weights")?.validate(&[hidden_dim, kernel_size], conv_data_type)?.read_allocation()?;+ conv_tree.leaf("weights")?.validate(&[hidden_dim, kernel_size], conv_data_type)?.read_buffer()?;let has_bias = config.conv_config.has_biases;let conv_bias = if has_bias {- Some(conv_tree.leaf("biases")?.validate(&[hidden_dim], conv_data_type)?.read_allocation()?)+ Some(conv_tree.leaf("biases")?.validate(&[hidden_dim], conv_data_type)?.read_buffer()?)} else {None};@@ -180,16 +179,16 @@ impl<B: Backend> ShortConv<B> {fn encode_decode_conv(&self,- in_projected: &Allocation<B>,+ in_projected: impl BufferRef<Backend = B>,state: &mut ShortConvState<B>,- encoder: &mut Encoder<B>,- ) -> Result<Allocation<B>, B::Error> {- let mut conv_output = encoder.allocate_scratch_for_shape(&[self.hidden_dim], self.data_type)?;+ command_buffer: &mut <B::CommandBuffer as CommandBuffer>::Encoding,+ ) -> Result<B::ScratchBuffer, B::Error> {+ let mut conv_output = command_buffer.allocate_scratch_for_shape(&[self.hidden_dim], self.data_type)?;self.short_conv_decode.encode(in_projected,&self.conv_weight,self.conv_bias.as_ref(),- None::<&Allocation<B>>,+ None::<&B::GlobalBuffer>,&mut conv_output,&mut state.conv_state,1,@@ -197,22 +196,22 @@ impl<B: Backend> ShortConv<B> {self.hidden_dim * 3,self.kernel_size - 1,self.hidden_dim,- encoder,+ command_buffer,);Ok(conv_output)}fn encode_prefill_conv(&self,- in_projected: &Allocation<B>,+ in_projected: impl BufferRef<Backend = B>,batch_dim: u32,state: &mut ShortConvState<B>,- encoder: &mut Encoder<B>,- ) -> Result<Allocation<B>, B::Error> {+ command_buffer: &mut <B::CommandBuffer as CommandBuffer>::Encoding,+ ) -> Result<B::ScratchBuffer, B::Error> {let state_stride = self.kernel_size - 1;let padded_rows = state_stride + batch_dim;- let mut padded = encoder.allocate_scratch_for_shape(&[padded_rows, self.hidden_dim], self.data_type)?;+ let mut padded = command_buffer.allocate_scratch_for_shape(&[padded_rows, self.hidden_dim], self.data_type)?;self.short_conv_pack.encode(&state.conv_state,in_projected,@@ -221,10 +220,11 @@ impl<B: Backend> ShortConv<B> {batch_dim,self.hidden_dim * 3,self.hidden_dim,- encoder,+ command_buffer,);- let mut conv_output = encoder.allocate_scratch_for_shape(&[batch_dim, self.hidden_dim], self.data_type)?;+ let mut conv_output =+ command_buffer.allocate_scratch_for_shape(&[batch_dim, self.hidden_dim], self.data_type)?;self.short_conv_prefill.encode(&padded,in_projected,@@ -237,22 +237,23 @@ impl<B: Backend> ShortConv<B> {self.hidden_dim * 3,state_stride,self.hidden_dim,- encoder,+ command_buffer,);Ok(conv_output)}fn encode_trie_conv(&self,- in_projected: &Allocation<B>,+ in_projected: impl BufferRef<Backend = B>,batch_dim: u32,- token_parents: &Allocation<B>,+ token_parents: impl BufferRef<Backend = B>,state: &mut ShortConvState<B>,- encoder: &mut Encoder<B>,- ) -> Result<(Allocation<B>, Allocation<B>), B::Error> {- let mut conv_output = encoder.allocate_scratch_for_shape(&[batch_dim, self.hidden_dim], self.data_type)?;- let mut conv_states =- encoder.allocate_scratch_for_shape(&[batch_dim, self.kernel_size - 1, self.hidden_dim], self.data_type)?;+ command_buffer: &mut <B::CommandBuffer as CommandBuffer>::Encoding,+ ) -> Result<(B::ScratchBuffer, B::ScratchBuffer), B::Error> {+ let mut conv_output =+ command_buffer.allocate_scratch_for_shape(&[batch_dim, self.hidden_dim], self.data_type)?;+ let mut conv_states = command_buffer+ .allocate_scratch_for_shape(&[batch_dim, self.kernel_size - 1, self.hidden_dim], self.data_type)?;self.short_conv_trie.encode(in_projected,&self.conv_weight,@@ -266,7 +267,7 @@ impl<B: Backend> ShortConv<B> {self.hidden_dim * 3,self.kernel_size - 1,self.hidden_dim,- encoder,+ command_buffer,);Ok((conv_output, conv_states))}@@ -286,21 +287,17 @@ impl<B: Backend> Mixer<B> for ShortConv<B> {_max_context_length: Option<u32>,context: &B::Context,) -> Result<Box<dyn MixerState<B>>, B::Error> {- let mut conv_state = context.create_allocation(- size_for_shape(&[self.kernel_size - 1, self.hidden_dim], self.data_type),- AllocationType::Global,- )?;+ let mut conv_state =+ context.create_buffer(size_for_shape(&[self.kernel_size - 1, self.hidden_dim], self.data_type))?;let suffix_capacity = 1024; // TODO: remove hardcoded suffix capacity- let mut suffix_state = context.create_allocation(- size_for_shape(&[suffix_capacity, self.kernel_size - 1, self.hidden_dim], self.data_type),- AllocationType::Global,- )?;+ let mut suffix_state = context+ .create_buffer(size_for_shape(&[suffix_capacity, self.kernel_size - 1, self.hidden_dim], self.data_type))?;- let mut zero_encoder = Encoder::<B>::new(context)?;- zero_encoder.encode_fill(&mut conv_state, 0);- zero_encoder.encode_fill(&mut suffix_state, 0);- zero_encoder.end_encoding().submit().wait_until_completed()?;+ let mut zero_command_buffer = context.create_command_buffer(None, None)?;+ zero_command_buffer.encode_fill(&mut conv_state, 0);+ zero_command_buffer.encode_fill(&mut suffix_state, 0);+ zero_command_buffer.end_encoding().submit().wait_until_completed()?;Ok(Box::new(ShortConvState {conv_state,@@ -310,13 +307,13 @@ impl<B: Backend> Mixer<B> for ShortConv<B> {fn encode(&self,- hidden: Allocation<B>,+ hidden: B::ScratchBuffer,precalculated_rope: Option<&PrecalculatedRoPE<B>>,batch_dim: &BatchTopology,state: Option<MaybeMut<dyn MixerState<B>>>,- encoder: &mut Encoder<B>,- ) -> Result<Allocation<B>, B::Error> {- encoder.push_debug_group("short conv");+ command_buffer: &mut <B::CommandBuffer as CommandBuffer>::Encoding,+ ) -> Result<B::ScratchBuffer, B::Error> {+ command_buffer.push_debug_group("short conv");assert!(precalculated_rope.is_none(), "unexpected rope for short conv mixer");@@ -328,31 +325,31 @@ impl<B: Backend> Mixer<B> for ShortConv<B> {assert!(state.suffix_state.is_none(), "short conv called with state with unaccepted tokens");- let in_projected = self.in_projection.encode(hidden, batch_dim.size(), encoder)?;+ let in_projected = self.in_projection.encode(hidden, batch_dim.size(), command_buffer)?;let conv_output = if batch_dim.full_accept() {let conv_output = if batch_dim.size() == 1 {- self.encode_decode_conv(&in_projected, state, encoder)?+ self.encode_decode_conv(&in_projected, state, command_buffer)?} else {- self.encode_prefill_conv(&in_projected, batch_dim.size(), state, encoder)?+ self.encode_prefill_conv(&in_projected, batch_dim.size(), state, command_buffer)?};state.suffix_state = Some(ShortConvStateSuffixStatus::Flat {suffix_length: batch_dim.size(),});conv_output} else {- let token_parents = encoder.allocate_constant_from_slice(batch_dim.parents())?;+ let token_parents = command_buffer.allocate_constant_from_slice(batch_dim.parents())?;let (conv_output, conv_states) =- self.encode_trie_conv(&in_projected, batch_dim.size(), &token_parents, state, encoder)?;+ self.encode_trie_conv(&in_projected, batch_dim.size(), &token_parents, state, command_buffer)?;state.suffix_state = Some(ShortConvStateSuffixStatus::Trie {conv_states,});conv_output};- let output = self.out_projection.encode(conv_output, batch_dim.size(), encoder)?;+ let output = self.out_projection.encode(conv_output, batch_dim.size(), command_buffer)?;- encoder.pop_debug_group();+ command_buffer.pop_debug_group();Ok(output)}diff --git a/crates/uzu-engine/src/encodable_block/mlp/dense.rs b/crates/uzu-engine/src/encodable_block/mlp/dense.rsindex 4ae3e82cf..a0881dee7 100644--- a/crates/uzu-engine/src/encodable_block/mlp/dense.rs+++ b/crates/uzu-engine/src/encodable_block/mlp/dense.rs@@ -1,7 +1,7 @@//! MLP block encodable.use crate::{- backends::common::{Allocation, Backend, Encoder},+ backends::common::{Backend, CommandBuffer, CommandBufferEncoding},encodable_block::{linear::Linear,mlp::{Mlp, gate_act_mul::MlpGateActMulEncodable},@@ -31,18 +31,18 @@ impl<B: Backend> DenseMlp<B> {impl<B: Backend> Mlp<B> for DenseMlp<B> {fn encode(&self,- input: Allocation<B>,+ input: B::ScratchBuffer,batch_dim: u32,- encoder: &mut Encoder<B>,- ) -> Result<Allocation<B>, B::Error> {- encoder.push_debug_group("mlp (dense)");+ command_buffer: &mut <B::CommandBuffer as CommandBuffer>::Encoding,+ ) -> Result<B::ScratchBuffer, B::Error> {+ command_buffer.push_debug_group("mlp (dense)");- let fused_up = self.up.encode(input, batch_dim, encoder)?;- let act_format = self.down.select_activation_format(batch_dim, encoder.context());- let down_input = self.gate.encode_for_linear(encoder, &fused_up, batch_dim, act_format)?;- let output = self.down.encode_input(down_input, batch_dim, encoder)?;+ let fused_up = self.up.encode(input, batch_dim, command_buffer)?;+ let act_format = self.down.select_activation_format(batch_dim, command_buffer.context());+ let down_input = self.gate.encode_for_linear(command_buffer, &fused_up, batch_dim, act_format)?;+ let output = self.down.encode_input(down_input, batch_dim, command_buffer)?;- encoder.pop_debug_group();+ command_buffer.pop_debug_group();Ok(output)}diff --git a/crates/uzu-engine/src/encodable_block/mlp/gate_act_mul.rs b/crates/uzu-engine/src/encodable_block/mlp/gate_act_mul.rsindex a65853970..4eab50d2f 100644--- a/crates/uzu-engine/src/encodable_block/mlp/gate_act_mul.rs+++ b/crates/uzu-engine/src/encodable_block/mlp/gate_act_mul.rs@@ -1,7 +1,6 @@use crate::{- array::size_for_shape,backends::common::{- Allocation, Backend, Encoder,+ Backend, BufferRef, CommandBuffer, CommandBufferEncoding,gpu_types::ActivationType,kernel::{ActivationQuantization, GatedActMul, GatedActMulSettings, matmul::ActivationFormat},},@@ -15,7 +14,7 @@ pub struct MlpGateActMulEncodable<B: Backend> {activation: AnyActivation,hidden_dim: u32,data_type: DataType,- hadamard_factors: Option<Allocation<B>>,+ hadamard_factors: Option<B::GlobalBuffer>,activation_quantization: Option<ActivationQuantization>,quantized_kernel: Option<GatedActMul<B>>,}@@ -54,12 +53,12 @@ impl<B: Backend> MlpGateActMulEncodable<B> {pub fn encode_for_linear(&self,- encoder: &mut Encoder<B>,- fused_up: &Allocation<B>,+ command_buffer: &mut <B::CommandBuffer as CommandBuffer>::Encoding,+ fused_up: impl BufferRef<Backend = B>,batch_dim: u32,act_format: ActivationFormat,) -> Result<LinearInput<B>, B::Error> {- encoder.push_debug_group("gate act mul");+ command_buffer.push_debug_group("gate act mul");if self.activation.act_type() == ActivationType::IDENTITY {panic!("Identity activation is not supported for kernel")@@ -68,18 +67,16 @@ impl<B: Backend> MlpGateActMulEncodable<B> {&& let Some(quantization) = self.activation_quantization{let kernel = self.quantized_kernel.as_ref().expect("INT8 input requires a quantized gate kernel");- let mut values = encoder.allocate_scratch(size_for_shape(&[batch_dim, self.hidden_dim], DataType::I8))?;- let mut scales = encoder.allocate_scratch(size_for_shape(+ let mut values = command_buffer.allocate_scratch_for_shape(&[batch_dim, self.hidden_dim], DataType::I8)?;+ let mut scales = command_buffer.allocate_scratch_for_shape(&[batch_dim, self.hidden_dim.div_ceil(quantization.scale_group_size())],DataType::F32,- ))?;+ )?;let mut group_sums = quantization.sum_group_size().map(|group_size| {- encoder.allocate_scratch(size_for_shape(- &[batch_dim, self.hidden_dim.div_ceil(group_size)],- DataType::I32,- ))+ command_buffer+ .allocate_scratch_for_shape(&[batch_dim, self.hidden_dim.div_ceil(group_size)], DataType::I32)}).transpose()?;kernel.encode_quantized(@@ -91,7 +88,7 @@ impl<B: Backend> MlpGateActMulEncodable<B> {self.hidden_dim,batch_dim,self.activation.act_type(),- encoder,+ command_buffer,);LinearInput::Int8Symmetric {values,@@ -101,10 +98,11 @@ impl<B: Backend> MlpGateActMulEncodable<B> {code_layout: quantization.code_layout(),}} else {- let mut hidden = encoder.allocate_scratch(size_for_shape(&[batch_dim, self.hidden_dim], self.data_type))?;+ let mut hidden =+ command_buffer.allocate_scratch_for_shape(&[batch_dim, self.hidden_dim], self.data_type)?;self.fp_kernel.encode_fp(fused_up,- None,+ None::<&B::ScratchBuffer>,&mut hidden,self.hadamard_factors.as_ref(),self.hidden_dim,@@ -112,12 +110,12 @@ impl<B: Backend> MlpGateActMulEncodable<B> {0,0,self.activation.act_type(),- encoder,+ command_buffer,);LinearInput::FullPrecision(hidden)};- encoder.pop_debug_group();+ command_buffer.pop_debug_group();Ok(input)}diff --git a/crates/uzu-engine/src/encodable_block/mlp/mod.rs b/crates/uzu-engine/src/encodable_block/mlp/mod.rsindex 614961941..80273d940 100644--- a/crates/uzu-engine/src/encodable_block/mlp/mod.rs+++ b/crates/uzu-engine/src/encodable_block/mlp/mod.rs@@ -8,7 +8,7 @@ pub use moe::{MoeBlock, MoeBlockError};use thiserror::Error;use crate::{- backends::common::{Allocation, Backend, Encoder},+ backends::common::{Backend, CommandBuffer},config::mlp::AnyMLPConfig,data_type::DataType,encodable_block::linear::{Linear, LinearBlockError},@@ -18,10 +18,10 @@ use crate::{pub trait Mlp<B: Backend>: Send + Sync {fn encode(&self,- input: Allocation<B>,+ input: B::ScratchBuffer,batch_dim: u32,- encoder: &mut Encoder<B>,- ) -> Result<Allocation<B>, B::Error>;+ command_buffer: &mut <B::CommandBuffer as CommandBuffer>::Encoding,+ ) -> Result<B::ScratchBuffer, B::Error>;}#[derive(Debug, Error)]@@ -42,7 +42,7 @@ impl<B: Backend> dyn Mlp<B> {context: &B::Context,parameter_tree: &ParameterTree<B>,data_type: DataType,- ) -> Result<(Box<dyn Mlp<B>>, Option<Allocation<B>>), MlpBlockError<B>> {+ ) -> Result<(Box<dyn Mlp<B>>, Option<B::GlobalBuffer>), MlpBlockError<B>> {match config {AnyMLPConfig::DenseMLPConfig(dense_config) => {let (up_projection, up_input_hadamard_factors) = <dyn Linear<B>>::new_with_input_rht(diff --git a/crates/uzu-engine/src/encodable_block/mlp/moe/experts_two_pass_decode.rs b/crates/uzu-engine/src/encodable_block/mlp/moe/experts_two_pass_decode.rsindex e1ff9e4f7..9fec0879b 100644--- a/crates/uzu-engine/src/encodable_block/mlp/moe/experts_two_pass_decode.rs+++ b/crates/uzu-engine/src/encodable_block/mlp/moe/experts_two_pass_decode.rs@@ -1,6 +1,6 @@use crate::{backends::common::{- Allocation, Backend, Encoder,+ Backend, BufferRef, CommandBuffer, CommandBufferEncoding,kernel::{Kernels, MoeExpertsDecodeDownFused2DKernel, MoeExpertsDecodePassAKernel, MoePassABuildRowMapKernel,MoePassABuildTileMapKernel, MoePassATileCountsKernel, MoePassATileScanKernel,@@ -42,29 +42,34 @@ impl<B: Backend> MoeExpertsTwoPassDecodeBlock<B> {pub fn encode(&self,- args: MoeExpertsTwoPassArguments<B>,- encoder: &mut Encoder<B>,- ) -> Result<Allocation<B>, B::Error> {+ args: MoeExpertsTwoPassArguments<+ impl BufferRef<Backend = B>,+ impl BufferRef<Backend = B>,+ impl BufferRef<Backend = B>,+ >,+ command_buffer: &mut <B::CommandBuffer as CommandBuffer>::Encoding,+ ) -> Result<B::ScratchBuffer, B::Error> {const BLOCK_M: u32 = 4;let h_blocks = args.d_ff.div_ceil(BLOCK_M);- let mut tile_counts = encoder.allocate_scratch_for_shape(&[args.num_routed_experts], DataType::U32)?;- self.counts.encode(args.expert_offsets, &mut tile_counts, args.num_routed_experts, h_blocks, encoder);+ let mut tile_counts = command_buffer.allocate_scratch_for_shape(&[args.num_routed_experts], DataType::U32)?;+ self.counts.encode(args.expert_offsets, &mut tile_counts, args.num_routed_experts, h_blocks, command_buffer);- let mut tile_offsets = encoder.allocate_scratch_for_shape(&[args.num_routed_experts + 1], DataType::U32)?;- let mut total_tiles = encoder.allocate_scratch_for_shape(&[1], DataType::U32)?;- self.scan.encode(&tile_counts, &mut tile_offsets, &mut total_tiles, args.num_routed_experts, encoder);+ let mut tile_offsets =+ command_buffer.allocate_scratch_for_shape(&[args.num_routed_experts + 1], DataType::U32)?;+ let mut total_tiles = command_buffer.allocate_scratch_for_shape(&[1], DataType::U32)?;+ self.scan.encode(&tile_counts, &mut tile_offsets, &mut total_tiles, args.num_routed_experts, command_buffer);- let mut row_expert_map = encoder.allocate_scratch_for_shape(&[args.total_rows], DataType::U32)?;+ let mut row_expert_map = command_buffer.allocate_scratch_for_shape(&[args.total_rows], DataType::U32)?;self.row_map.encode(args.expert_offsets,&mut row_expert_map,args.total_rows,args.num_routed_experts,- encoder,+ command_buffer,);- let mut tile_map = encoder.allocate_scratch_for_shape(&[args.total_rows, h_blocks, 3], DataType::U32)?;+ let mut tile_map = command_buffer.allocate_scratch_for_shape(&[args.total_rows, h_blocks, 3], DataType::U32)?;self.build_map.encode(args.expert_offsets,&tile_offsets,@@ -72,13 +77,13 @@ impl<B: Backend> MoeExpertsTwoPassDecodeBlock<B> {&mut tile_map,args.total_rows,h_blocks,- encoder,+ command_buffer,);- let mut dispatch_args = encoder.allocate_scratch_for_shape(&[3], DataType::U32)?;- self.dispatch.encode(&total_tiles, &mut dispatch_args, 1, encoder);+ let mut dispatch_args = command_buffer.allocate_scratch_for_shape(&[3], DataType::U32)?;+ self.dispatch.encode(&total_tiles, &mut dispatch_args, 1, command_buffer);- let mut hidden = encoder.allocate_scratch_for_shape(&[args.total_rows, args.d_ff], DataType::F32)?;+ let mut hidden = command_buffer.allocate_scratch_for_shape(&[args.total_rows, args.d_ff], DataType::F32)?;self.pass_a_indirect.encode(args.x_perm,@@ -96,10 +101,10 @@ impl<B: Backend> MoeExpertsTwoPassDecodeBlock<B> {args.silu_alpha,&tile_map,&dispatch_args,- encoder,+ command_buffer,);- let mut output = encoder.allocate_scratch_for_shape(&[args.total_rows, args.d_model], self.data_type)?;+ let mut output = command_buffer.allocate_scratch_for_shape(&[args.total_rows, args.d_model], self.data_type)?;self.fused_down.encode(&hidden,&row_expert_map,@@ -110,7 +115,7 @@ impl<B: Backend> MoeExpertsTwoPassDecodeBlock<B> {args.d_model,args.d_ff,args.num_routed_experts,- encoder,+ command_buffer,);Ok(output)diff --git a/crates/uzu-engine/src/encodable_block/mlp/moe/experts_two_pass_prefill.rs b/crates/uzu-engine/src/encodable_block/mlp/moe/experts_two_pass_prefill.rsindex f53249825..37a05cedb 100644--- a/crates/uzu-engine/src/encodable_block/mlp/moe/experts_two_pass_prefill.rs+++ b/crates/uzu-engine/src/encodable_block/mlp/moe/experts_two_pass_prefill.rs@@ -1,6 +1,6 @@use crate::{backends::common::{- Allocation, Backend, Encoder, Kernels,+ Backend, BufferRef, CommandBuffer, CommandBufferEncoding, Kernels,kernel::{MoeBuildTileMapKernel, MoeExpertsPrefillPassAKernel, MoeExpertsPrefillPassBKernel, MoeTileCountsKernel,MoeTileScanKernel, MoeWriteDispatchArgsKernel,@@ -38,34 +38,39 @@ impl<B: Backend> MoeExpertsTwoPassPrefillBlock<B> {pub fn encode(&self,- args: MoeExpertsTwoPassArguments<B>,- encoder: &mut Encoder<B>,- ) -> Result<Allocation<B>, B::Error> {- let mut tile_counts = encoder.allocate_scratch_for_shape(&[args.num_routed_experts], DataType::U32)?;- self.counts.encode(args.expert_offsets, &mut tile_counts, args.num_routed_experts, encoder);+ args: MoeExpertsTwoPassArguments<+ impl BufferRef<Backend = B>,+ impl BufferRef<Backend = B>,+ impl BufferRef<Backend = B>,+ >,+ command_buffer: &mut <B::CommandBuffer as CommandBuffer>::Encoding,+ ) -> Result<B::ScratchBuffer, B::Error> {+ let mut tile_counts = command_buffer.allocate_scratch_for_shape(&[args.num_routed_experts], DataType::U32)?;+ self.counts.encode(args.expert_offsets, &mut tile_counts, args.num_routed_experts, command_buffer);- let mut tile_offsets = encoder.allocate_scratch_for_shape(&[args.num_routed_experts + 1], DataType::U32)?;- let mut total_tiles = encoder.allocate_scratch_for_shape(&[8], DataType::U32)?;- self.scan.encode(&tile_counts, &mut tile_offsets, &mut total_tiles, args.num_routed_experts, encoder);+ let mut tile_offsets =+ command_buffer.allocate_scratch_for_shape(&[args.num_routed_experts + 1], DataType::U32)?;+ let mut total_tiles = command_buffer.allocate_scratch_for_shape(&[8], DataType::U32)?;+ self.scan.encode(&tile_counts, &mut tile_offsets, &mut total_tiles, args.num_routed_experts, command_buffer);- let mut tile_map = encoder.allocate_scratch_for_shape(&[args.total_rows, 3], DataType::U32)?;+ let mut tile_map = command_buffer.allocate_scratch_for_shape(&[args.total_rows, 3], DataType::U32)?;self.build.encode(args.expert_offsets,&tile_offsets,&tile_counts,&mut tile_map,args.num_routed_experts,- encoder,+ command_buffer,);const COL_TILE_FF: u32 = 32; // Must match PASSA_BN in kernellet n_tiles_ff = args.d_ff.div_ceil(COL_TILE_FF);- let mut pass_a_dispatch_args = encoder.allocate_scratch_for_shape(&[3], DataType::U32)?;- self.dispatch.encode(&total_tiles, &mut pass_a_dispatch_args, n_tiles_ff, encoder);+ let mut pass_a_dispatch_args = command_buffer.allocate_scratch_for_shape(&[3], DataType::U32)?;+ self.dispatch.encode(&total_tiles, &mut pass_a_dispatch_args, n_tiles_ff, command_buffer);- let mut hidden = encoder.allocate_scratch_for_shape(&[args.total_rows, args.d_ff], DataType::F32)?;- encoder.encode_fill(&mut hidden, 0);+ let mut hidden = command_buffer.allocate_scratch_for_shape(&[args.total_rows, args.d_ff], DataType::F32)?;+ command_buffer.encode_fill(&mut hidden, 0);self.pass_a_indirect.encode(args.x_perm,@@ -83,16 +88,16 @@ impl<B: Backend> MoeExpertsTwoPassPrefillBlock<B> {args.silu_alpha,&tile_map,&pass_a_dispatch_args,- encoder,+ command_buffer,);const COL_TILE_MODEL: u32 = 64;let n_tiles_model = args.d_model.div_ceil(COL_TILE_MODEL);- let mut pass_b_dispatch_args = encoder.allocate_scratch_for_shape(&[3], DataType::U32)?;- self.dispatch.encode(&total_tiles, &mut pass_b_dispatch_args, n_tiles_model, encoder);+ let mut pass_b_dispatch_args = command_buffer.allocate_scratch_for_shape(&[3], DataType::U32)?;+ self.dispatch.encode(&total_tiles, &mut pass_b_dispatch_args, n_tiles_model, command_buffer);- let mut output = encoder.allocate_scratch_for_shape(&[args.total_rows, args.d_model], self.data_type)?;+ let mut output = command_buffer.allocate_scratch_for_shape(&[args.total_rows, args.d_model], self.data_type)?;self.pass_b_indirect.encode(&hidden,args.expert_offsets,@@ -104,19 +109,23 @@ impl<B: Backend> MoeExpertsTwoPassPrefillBlock<B> {args.num_routed_experts,&tile_map,&pass_b_dispatch_args,- encoder,+ command_buffer,);Ok(output)}}-pub struct MoeExpertsTwoPassArguments<'a, B: Backend> {- pub x_perm: &'a Allocation<B>,- pub expert_offsets: &'a Allocation<B>,- pub w13_all: &'a Allocation<B>,- pub w2_all: &'a Allocation<B>,- pub up_biases: &'a Allocation<B>,- pub down_biases: &'a Allocation<B>,+pub struct MoeExpertsTwoPassArguments<+ X: BufferRef,+ O: BufferRef<Backend = X::Backend>,+ W: BufferRef<Backend = X::Backend>,+> {+ pub x_perm: X,+ pub expert_offsets: O,+ pub w13_all: W,+ pub w2_all: W,+ pub up_biases: W,+ pub down_biases: W,pub total_rows: u32,pub d_model: u32,pub d_ff: u32,diff --git a/crates/uzu-engine/src/encodable_block/mlp/moe/gather.rs b/crates/uzu-engine/src/encodable_block/mlp/moe/gather.rsindex 85f1a0b3a..7fadae4d6 100644--- a/crates/uzu-engine/src/encodable_block/mlp/moe/gather.rs+++ b/crates/uzu-engine/src/encodable_block/mlp/moe/gather.rs@@ -1,6 +1,6 @@use crate::{backends::common::{- Allocation, Backend, Encoder, Kernels,+ Backend, BufferRef, CommandBuffer, CommandBufferEncoding, Kernels,kernel::{MoeGatherXPerm1DKernel, MoeGatherXPerm2DKernel},},data_type::DataType,@@ -33,25 +33,39 @@ impl<B: Backend> MoeGather<B> {pub fn encode(&self,- input: &Allocation<B>,- bucketed_ids: &Allocation<B>,- sumk: &Allocation<B>,+ input: impl BufferRef<Backend = B>,+ bucketed_ids: impl BufferRef<Backend = B>,+ sumk: impl BufferRef<Backend = B>,batch_dim: u32,num_active_experts: u32,d_model: u32,- encoder: &mut Encoder<B>,- ) -> Result<Allocation<B>, B::Error> {+ command_buffer: &mut <B::CommandBuffer as CommandBuffer>::Encoding,+ ) -> Result<B::ScratchBuffer, B::Error> {let mut x_perm =- encoder.allocate_scratch_for_shape(&[batch_dim, num_active_experts, d_model], self.data_type)?;- encoder.encode_fill(&mut x_perm, 0);+ command_buffer.allocate_scratch_for_shape(&[batch_dim, num_active_experts, d_model], self.data_type)?;+ command_buffer.encode_fill(&mut x_perm, 0);match &self.variant {- MoeGatherVariant::OneD(kernel) => {- kernel.encode(input, bucketed_ids, &mut x_perm, sumk, d_model, batch_dim, num_active_experts, encoder)- },- MoeGatherVariant::TwoD(kernel) => {- kernel.encode(input, bucketed_ids, &mut x_perm, sumk, d_model, batch_dim, num_active_experts, encoder)- },+ MoeGatherVariant::OneD(kernel) => kernel.encode(+ input,+ bucketed_ids,+ &mut x_perm,+ sumk,+ d_model,+ batch_dim,+ num_active_experts,+ command_buffer,+ ),+ MoeGatherVariant::TwoD(kernel) => kernel.encode(+ input,+ bucketed_ids,+ &mut x_perm,+ sumk,+ d_model,+ batch_dim,+ num_active_experts,+ command_buffer,+ ),};Ok(x_perm)diff --git a/crates/uzu-engine/src/encodable_block/mlp/moe/mod.rs b/crates/uzu-engine/src/encodable_block/mlp/moe/mod.rsindex a4bd46741..d58419ddd 100644--- a/crates/uzu-engine/src/encodable_block/mlp/moe/mod.rs+++ b/crates/uzu-engine/src/encodable_block/mlp/moe/mod.rs@@ -11,7 +11,7 @@ use thiserror::Error;use crate::{backends::common::{- Allocation, Backend, Encoder, Kernels,+ Backend, CommandBuffer, CommandBufferEncoding, Kernels,gpu_types::{ActivationType,router_topk::{ROUTER_TOPK_MAX_EXPERTS, ROUTER_TOPK_MAX_MODEL_DIM, ROUTER_TOPK_MAX_SELECTED_EXPERTS},@@ -39,13 +39,13 @@ pub struct MoeBlock<B: Backend> {experts_two_pass_decode_block: MoeExpertsTwoPassDecodeBlock<B>,experts_two_pass_prefill_block: MoeExpertsTwoPassPrefillBlock<B>,finalize_kernel: <B::Kernels as Kernels>::MoeFinalizeKernel,- router_weights: Allocation<B>,- router_biases: Allocation<B>,+ router_weights: B::GlobalBuffer,+ router_biases: B::GlobalBuffer,router_renorm: bool,- w13: Allocation<B>,- w2: Allocation<B>,- up_biases: Allocation<B>,- down_biases: Allocation<B>,+ w13: B::GlobalBuffer,+ w2: B::GlobalBuffer,+ up_biases: B::GlobalBuffer,+ down_biases: B::GlobalBuffer,model_dim: u32,hidden_dim: u32,num_routed_experts: u32,@@ -135,9 +135,9 @@ impl<B: Backend> MoeBlock<B> {let router_weights = router_weights_tree.leaf("weights")?.validate(&[moe_config.num_routed_experts, model_dim], data_type)?- .read_allocation()?;+ .read_buffer()?;let router_biases =- router_tree.leaf("biases")?.validate(&[moe_config.num_routed_experts], data_type)?.read_allocation()?;+ router_tree.leaf("biases")?.validate(&[moe_config.num_routed_experts], data_type)?.read_buffer()?;let experts_tree = parameter_tree.subtree("experts");let up_tree = experts_tree.subtree("up_projection");@@ -148,19 +148,19 @@ impl<B: Backend> MoeBlock<B> {let w13 = up_weights_tree.leaf("weights")?.validate(&[moe_config.num_routed_experts, moe_config.expert_hidden_dim * 2, model_dim], data_type)?- .read_allocation()?;+ .read_buffer()?;let w2 = down_weights_tree.leaf("weights")?.validate(&[moe_config.num_routed_experts, model_dim, moe_config.expert_hidden_dim], data_type)?- .read_allocation()?;+ .read_buffer()?;let up_biases = up_tree.leaf("biases")?.validate(&[moe_config.num_routed_experts, moe_config.expert_hidden_dim * 2], data_type)?- .read_allocation()?;+ .read_buffer()?;let down_biases = down_tree.leaf("biases")?.validate(&[moe_config.num_routed_experts, model_dim], data_type)?- .read_allocation()?;+ .read_buffer()?;let router_topk_kernel =<B::Kernels as Kernels>::MoeRouterTopKKernel::new(context, data_type, true, false, false, false, false)@@ -218,28 +218,29 @@ impl<B: Backend> MoeBlock<B> {impl<B: Backend> Mlp<B> for MoeBlock<B> {fn encode(&self,- input: Allocation<B>,+ input: B::ScratchBuffer,batch_dim: u32,- encoder: &mut Encoder<B>,- ) -> Result<Allocation<B>, B::Error> {- encoder.push_debug_group("mlp (moe)");+ command_buffer: &mut <B::CommandBuffer as CommandBuffer>::Encoding,+ ) -> Result<B::ScratchBuffer, B::Error> {+ command_buffer.push_debug_group("mlp (moe)");let total_rows = batch_dim * self.num_active_experts;let num_blocks = batch_dim.div_ceil(256);let num_tiles = self.num_routed_experts.div_ceil(512);- let mut topk_ids = encoder.allocate_scratch_for_shape(&[batch_dim, self.num_active_experts], DataType::I32)?;+ let mut topk_ids =+ command_buffer.allocate_scratch_for_shape(&[batch_dim, self.num_active_experts], DataType::I32)?;let mut topk_probs =- encoder.allocate_scratch_for_shape(&[batch_dim, self.num_active_experts], self.data_type)?;+ command_buffer.allocate_scratch_for_shape(&[batch_dim, self.num_active_experts], self.data_type)?;- encoder.encode_fill(&mut topk_ids, 0xFF);+ command_buffer.encode_fill(&mut topk_ids, 0xFF);self.router_topk_kernel.encode(&input,&self.router_weights,Some(&self.router_biases),- None::<&Allocation<B>>,- None::<&Allocation<B>>,+ None::<&B::GlobalBuffer>,+ None::<&B::GlobalBuffer>,&mut topk_ids,&mut topk_probs,batch_dim,@@ -249,13 +250,13 @@ impl<B: Backend> Mlp<B> for MoeBlock<B> {self.router_renorm,None::<f32>,None::<f32>,- encoder,+ command_buffer,);- let mut offsets = encoder.allocate_scratch_for_shape(&[self.num_routed_experts + 1], DataType::U32)?;- let mut sumk = encoder.allocate_scratch_for_shape(&[1], DataType::U32)?;+ let mut offsets = command_buffer.allocate_scratch_for_shape(&[self.num_routed_experts + 1], DataType::U32)?;+ let mut sumk = command_buffer.allocate_scratch_for_shape(&[1], DataType::U32)?;let scatter_entries = num_blocks * num_tiles * 512;- let mut partials = encoder.allocate_scratch_for_shape(&[scatter_entries], DataType::U32)?;+ let mut partials = command_buffer.allocate_scratch_for_shape(&[scatter_entries], DataType::U32)?;self.counts_offsets_kernel.encode(&topk_ids,&mut offsets,@@ -264,16 +265,16 @@ impl<B: Backend> Mlp<B> for MoeBlock<B> {batch_dim,self.num_routed_experts,self.num_active_experts,- encoder,+ command_buffer,);- let mut block_bases = encoder.allocate_scratch_for_shape(&[scatter_entries], DataType::U32)?;- let mut block_alloc = encoder.allocate_scratch_for_shape(&[scatter_entries], DataType::U32)?;- let mut bucketed_ids = encoder.allocate_scratch_for_shape(&[total_rows], DataType::I32)?;- let mut bucketed_probs = encoder.allocate_scratch_for_shape(&[total_rows], self.data_type)?;- let mut tok2row = encoder.allocate_scratch_for_shape(&[total_rows], DataType::I32)?;+ let mut block_bases = command_buffer.allocate_scratch_for_shape(&[scatter_entries], DataType::U32)?;+ let mut block_alloc = command_buffer.allocate_scratch_for_shape(&[scatter_entries], DataType::U32)?;+ let mut bucketed_ids = command_buffer.allocate_scratch_for_shape(&[total_rows], DataType::I32)?;+ let mut bucketed_probs = command_buffer.allocate_scratch_for_shape(&[total_rows], self.data_type)?;+ let mut tok2row = command_buffer.allocate_scratch_for_shape(&[total_rows], DataType::I32)?;- encoder.encode_fill(&mut tok2row, 0xFF);+ command_buffer.encode_fill(&mut tok2row, 0xFF);self.scatter_bases_kernel.encode(&partials,@@ -283,7 +284,7 @@ impl<B: Backend> Mlp<B> for MoeBlock<B> {num_blocks,num_tiles,0u32,- encoder,+ command_buffer,);self.scatter_map_kernel.encode(&topk_ids,@@ -299,7 +300,7 @@ impl<B: Backend> Mlp<B> for MoeBlock<B> {num_blocks,num_tiles,&mut tok2row,- encoder,+ command_buffer,);let x_perm = self.gather.encode(@@ -309,7 +310,7 @@ impl<B: Backend> Mlp<B> for MoeBlock<B> {batch_dim,self.num_active_experts,self.model_dim,- encoder,+ command_buffer,)?;let args = MoeExpertsTwoPassArguments {@@ -331,12 +332,12 @@ impl<B: Backend> Mlp<B> for MoeBlock<B> {};let y_partial = if batch_dim == 1 {- self.experts_two_pass_decode_block.encode(args, encoder)?+ self.experts_two_pass_decode_block.encode(args, command_buffer)?} else {- self.experts_two_pass_prefill_block.encode(args, encoder)?+ self.experts_two_pass_prefill_block.encode(args, command_buffer)?};- let mut output = encoder.allocate_scratch_for_shape(&[batch_dim, self.model_dim], self.data_type)?;+ let mut output = command_buffer.allocate_scratch_for_shape(&[batch_dim, self.model_dim], self.data_type)?;self.finalize_kernel.encode(&tok2row,&topk_probs,@@ -345,10 +346,10 @@ impl<B: Backend> Mlp<B> for MoeBlock<B> {batch_dim,self.model_dim,self.num_active_experts,- encoder,+ command_buffer,);- encoder.pop_debug_group();+ command_buffer.pop_debug_group();Ok(output)}diff --git a/crates/uzu-engine/src/encodable_block/normalization.rs b/crates/uzu-engine/src/encodable_block/normalization.rsindex 24e1a2e93..abf315741 100644--- a/crates/uzu-engine/src/encodable_block/normalization.rs+++ b/crates/uzu-engine/src/encodable_block/normalization.rs@@ -3,7 +3,7 @@ use thiserror::Error;use crate::{array::size_for_shape,backends::common::{- Allocation, Backend, Encoder,+ Backend, BufferMut, BufferRef, CommandBuffer, CommandBufferEncoding,kernel::{Kernels, NormalizationKernel},},config::normalization::{NormalizationConfig, UpcastMode},@@ -38,10 +38,10 @@ pub enum NormalizationNewError<B: Backend> {pub struct Normalization<B: Backend> {epsilon: f32,scale_offset: Option<f32>,- scales: Option<Allocation<B>>,- biases: Option<Allocation<B>>,+ scales: Option<B::GlobalBuffer>,+ biases: Option<B::GlobalBuffer>,element_count: u32,- hadamard_factors: Option<Allocation<B>>,+ hadamard_factors: Option<B::GlobalBuffer>,post_layer_scalar_value: f32,data_type: DataType,kernel: <B::Kernels as Kernels>::NormalizationKernel,@@ -50,7 +50,7 @@ pub struct Normalization<B: Backend> {impl<B: Backend> Normalization<B> {pub fn new(element_count: u32,- hadamard_factors: Option<Allocation<B>>,+ hadamard_factors: Option<B::GlobalBuffer>,shortcut_mode: ShortcutMode,post_layer_scalar: PostLayerScalar,data_type: DataType,@@ -66,11 +66,11 @@ impl<B: Backend> Normalization<B> {let scales = config.has_scale- .then(|| parameter_tree.leaf("scales")?.validate(&[element_count], DataType::F32)?.read_allocation())+ .then(|| parameter_tree.leaf("scales")?.validate(&[element_count], DataType::F32)?.read_buffer()).transpose()?;let biases = config.has_biases- .then(|| parameter_tree.leaf("biases")?.validate(&[element_count], DataType::F32)?.read_allocation())+ .then(|| parameter_tree.leaf("biases")?.validate(&[element_count], DataType::F32)?.read_buffer()).transpose()?;let (scale_residual_sum, scale_output, post_layer_scalar_value) = match post_layer_scalar {@@ -113,20 +113,20 @@ impl<B: Backend> Normalization<B> {pub fn encode(&self,- input: &Allocation<B>,+ input: impl BufferRef<Backend = B>,row_offset: u32,row_count: u32,- shortcut: Option<&mut Allocation<B>>,- encoder: &mut Encoder<B>,- ) -> Result<Allocation<B>, B::Error> {- encoder.push_debug_group("normalization");+ shortcut: Option<impl BufferMut<Backend = B>>,+ command_buffer: &mut <B::CommandBuffer as CommandBuffer>::Encoding,+ ) -> Result<B::ScratchBuffer, B::Error> {+ command_buffer.push_debug_group("normalization");let row_size = size_for_shape(&[self.element_count], self.data_type);let row_offset_bytes = row_offset as usize * row_size;- let shortcut = shortcut.map(|shortcut| (shortcut, row_offset_bytes));- let mut output = encoder.allocate_scratch_for_shape(&[row_count, self.element_count], self.data_type)?;+ let shortcut = shortcut.map(|shortcut| shortcut.subrange_mut(row_offset_bytes..));+ let mut output = command_buffer.allocate_scratch_for_shape(&[row_count, self.element_count], self.data_type)?;self.kernel.encode(- Some((input, row_offset_bytes)),+ Some(input.subrange(row_offset_bytes..)),self.scales.as_ref(),self.biases.as_ref(),&mut output,@@ -137,10 +137,10 @@ impl<B: Backend> Normalization<B> {self.epsilon,self.scale_offset.unwrap_or(0.0),self.post_layer_scalar_value,- encoder,+ command_buffer,);- encoder.pop_debug_group();+ command_buffer.pop_debug_group();Ok(output)}diff --git a/crates/uzu-engine/src/encodable_block/per_layer_embedding.rs b/crates/uzu-engine/src/encodable_block/per_layer_embedding.rsindex 74b4b36ec..7db1ba244 100644--- a/crates/uzu-engine/src/encodable_block/per_layer_embedding.rs+++ b/crates/uzu-engine/src/encodable_block/per_layer_embedding.rs@@ -1,9 +1,8 @@use thiserror::Error;use crate::{- array::size_for_shape,backends::common::{- Allocation, Backend, Encoder,+ Backend, BufferMut, BufferRef, CommandBuffer, CommandBufferEncoding,kernel::{GatedActMul, GatedActMulSettings, Kernels, TensorAddBiasKernel, TensorAddScaleKernel},},config::{@@ -105,29 +104,41 @@ impl<B: Backend> PerLayerEmbedding<B> {pub fn encode(&self,- token_ids: &Allocation<B>,- inner_features: &Allocation<B>,+ token_ids: impl BufferRef<Backend = B>,+ inner_features: impl BufferRef<Backend = B>,batch_dim: u32,- encoder: &mut Encoder<B>,- ) -> Result<Allocation<B>, B::Error> {- encoder.push_debug_group("per layer embedding");+ command_buffer: &mut <B::CommandBuffer as CommandBuffer>::Encoding,+ ) -> Result<B::ScratchBuffer, B::Error> {+ command_buffer.push_debug_group("per layer embedding");let total_ple_dim = self.num_layers * self.ple_dim;let total_rows = batch_dim * self.num_layers;let total_elements = batch_dim * total_ple_dim;- let mut token_ple = encoder.allocate_scratch(size_for_shape(&[batch_dim, total_ple_dim], self.data_type))?;- self.token_embedding.encode_lookup(token_ids, &mut token_ple, batch_dim, self.fused_token_scale, encoder);+ let mut token_ple = command_buffer.allocate_scratch_for_shape(&[batch_dim, total_ple_dim], self.data_type)?;+ self.token_embedding.encode_lookup(+ token_ids,+ &mut token_ple,+ batch_dim,+ self.fused_token_scale,+ command_buffer,+ );let mut model_projection_input =- encoder.allocate_scratch(size_for_shape(&[batch_dim, self.model_dim], self.data_type))?;- encoder.encode_copy(inner_features, .., &mut model_projection_input, ..);- let model_projected = self.model_projection.encode(model_projection_input, batch_dim, encoder)?;+ command_buffer.allocate_scratch_for_shape(&[batch_dim, self.model_dim], self.data_type)?;+ command_buffer.encode_copy(inner_features, &mut model_projection_input);+ let model_projected = self.model_projection.encode(model_projection_input, batch_dim, command_buffer)?;- let model_normed = self.projection_norm.encode(&model_projected, 0, total_rows, None, encoder)?;+ let model_normed = self.projection_norm.encode(+ &model_projected,+ 0,+ total_rows,+ None::<&mut B::ScratchBuffer>,+ command_buffer,+ )?;let mut per_layer_inputs =- encoder.allocate_scratch(size_for_shape(&[batch_dim, self.num_layers, self.ple_dim], self.data_type))?;+ command_buffer.allocate_scratch_for_shape(&[batch_dim, self.num_layers, self.ple_dim], self.data_type)?;self.add_scale.encode(Some(&token_ple),&model_normed,@@ -135,10 +146,10 @@ impl<B: Backend> PerLayerEmbedding<B> {total_elements,total_elements,1.0,- encoder,+ command_buffer,);- encoder.pop_debug_group();+ command_buffer.pop_debug_group();Ok(per_layer_inputs)}@@ -227,50 +238,57 @@ impl<B: Backend> PerLayerEmbeddingProjection<B> {pub fn encode(&self,layer_index: u32,- per_layer_input: &Allocation<B>,- outputs: &mut Allocation<B>,- hidden: &Allocation<B>,+ per_layer_input: impl BufferRef<Backend = B>,+ mut outputs: impl BufferMut<Backend = B>,+ hidden: impl BufferRef<Backend = B>,batch_dim: u32,- encoder: &mut Encoder<B>,+ command_buffer: &mut <B::CommandBuffer as CommandBuffer>::Encoding,) -> Result<(), B::Error> {- encoder.push_debug_group("per layer embedding projection");+ command_buffer.push_debug_group("per layer embedding projection");let length = batch_dim * self.model_dim;- self.residual_finalize.encode(None::<&Allocation<B>>, hidden, &mut *outputs, length, length, encoder);+ self.residual_finalize.encode(+ None::<&B::ScratchBuffer>,+ hidden,+ outputs.reborrow(),+ length,+ length,+ command_buffer,+ );- let mut gate_input = encoder.allocate_scratch(size_for_shape(&[batch_dim, self.model_dim], self.data_type))?;- encoder.encode_copy(outputs, .., &mut gate_input, ..);- let gate_out = self.gate.encode(gate_input, batch_dim, encoder)?;+ let mut gate_input = command_buffer.allocate_scratch_for_shape(&[batch_dim, self.model_dim], self.data_type)?;+ command_buffer.encode_copy(outputs.as_ref(), &mut gate_input);+ let gate_out = self.gate.encode(gate_input, batch_dim, command_buffer)?;- let mut activated = encoder.allocate_scratch(size_for_shape(&[batch_dim, self.ple_dim], self.data_type))?;+ let mut activated = command_buffer.allocate_scratch_for_shape(&[batch_dim, self.ple_dim], self.data_type)?;self.gate_act_mul.encode_fp(&gate_out,Some(per_layer_input),&mut activated,- None,+ None::<&B::GlobalBuffer>,self.ple_dim,batch_dim,layer_index * self.ple_dim,self.num_layers * self.ple_dim,self.activation.act_type(),- encoder,+ command_buffer,);- let projected = self.projection.encode(activated, batch_dim, encoder)?;- let normed = self.norm.encode(&projected, 0, batch_dim, None, encoder)?;+ let projected = self.projection.encode(activated, batch_dim, command_buffer)?;+ let normed = self.norm.encode(&projected, 0, batch_dim, None::<&mut B::ScratchBuffer>, command_buffer)?;self.residual_combine.encode(- None::<&Allocation<B>>,+ None::<&B::ScratchBuffer>,&normed,- &mut *outputs,+ outputs,length,length,self.post_layer_scalar,- encoder,+ command_buffer,);- encoder.pop_debug_group();+ command_buffer.pop_debug_group();Ok(())}diff --git a/crates/uzu-engine/src/encodable_block/prediction_head.rs b/crates/uzu-engine/src/encodable_block/prediction_head.rsindex d79daad53..5fe4c2d32 100644--- a/crates/uzu-engine/src/encodable_block/prediction_head.rs+++ b/crates/uzu-engine/src/encodable_block/prediction_head.rs@@ -2,7 +2,7 @@ use thiserror::Error;use crate::{backends::common::{- Allocation, Backend, Encoder,+ Backend, CommandBuffer, CommandBufferEncoding,gpu_types::ActivationType,kernel::{ActivationKernel, Kernels},},@@ -88,18 +88,25 @@ impl<B: Backend> PredictionHead<B> {pub fn encode(&self,- input: Allocation<B>,+ input: B::ScratchBuffer,batch_dim: u32,- encoder: &mut Encoder<B>,- ) -> Result<Allocation<B>, B::Error> {- encoder.push_debug_group("prediction head");+ command_buffer: &mut <B::CommandBuffer as CommandBuffer>::Encoding,+ ) -> Result<B::ScratchBuffer, B::Error> {+ command_buffer.push_debug_group("prediction head");- let mut hidden = self.dense_projection.encode(input, batch_dim, encoder)?;- self.activation_kernel.encode(None::<&Allocation<B>>, &mut hidden, self.hidden_dim, self.activation, encoder);- let normalized = self.normalization.encode(&hidden, 0, batch_dim, None, encoder)?;- let logits = self.readout.encode(normalized, batch_dim, encoder)?;+ let mut hidden = self.dense_projection.encode(input, batch_dim, command_buffer)?;+ self.activation_kernel.encode(+ None::<&B::ScratchBuffer>,+ &mut hidden,+ self.hidden_dim,+ self.activation,+ command_buffer,+ );+ let normalized =+ self.normalization.encode(&hidden, 0, batch_dim, None::<&mut B::ScratchBuffer>, command_buffer)?;+ let logits = self.readout.encode(normalized, batch_dim, command_buffer)?;- encoder.pop_debug_group();+ command_buffer.pop_debug_group();Ok(logits)}diff --git a/crates/uzu-engine/src/encodable_block/sampling/mod.rs b/crates/uzu-engine/src/encodable_block/sampling/mod.rsindex 41ad00a15..1142bd587 100644--- a/crates/uzu-engine/src/encodable_block/sampling/mod.rs+++ b/crates/uzu-engine/src/encodable_block/sampling/mod.rs@@ -1,15 +1,15 @@use std::{collections::{HashMap, hash_map::Entry},mem::size_of,- ops::Range,+ range::Range,};use parking_lot::Mutex;use crate::{backends::common::{- Allocation, AllocationType, AsBufferRangeRef, Backend, Context, Encoder, Kernels,- kernel::{RepetitionPenaltyKernel, TensorCopyKernel, UnifiedSamplingKernel},+ Backend, Buffer, BufferMut, BufferRef, CommandBuffer, CommandBufferEncoding, Context, Kernels,+ kernel::{RepetitionPenaltyKernel, UnifiedSamplingKernel},},data_type::DataType,encodable_block::batch_topology::BatchTopology,@@ -82,17 +82,17 @@ struct UnifiedSamplingKey {impl<B: Backend> Sampling<B> {pub fn encode(&self,- logits: &Allocation<B>,- seeds: Option<&Allocation<B>>,- bitmask: Option<&Allocation<B>>,- context_ring: Option<&Allocation<B>>,- token_ids: Option<&Allocation<B>>,+ logits: impl BufferRef<Backend = B, Buffer: Sized>,+ seeds: Option<impl BufferRef<Backend = B>>,+ bitmask: Option<impl BufferRef<Backend = B>>,+ context_ring: Option<impl BufferRef<Backend = B>>,+ token_ids: Option<impl BufferRef<Backend = B>>,sampling_method: &SamplingMethod,batch_dim: &BatchTopology,sampling_range: Range<u32>,- encoder: &mut Encoder<B>,- ) -> Result<Allocation<B>, B::Error> {- encoder.push_debug_group("sampling");+ command_buffer: &mut <B::CommandBuffer as CommandBuffer>::Encoding,+ ) -> Result<B::GlobalBuffer, B::Error> {+ command_buffer.push_debug_group("sampling");let sampling_length = sampling_range.end - sampling_range.start;@@ -126,12 +126,12 @@ impl<B: Backend> Sampling<B> {let suffix_repetition_length =suffix_repetition_length.expect("suffix_repetition_length is required for repetition_penalty");- let mut logits_copy = encoder.allocate_scratch(logits.as_buffer_range_ref().range().len())?;- let tensor_copy = <B::Kernels as Kernels>::TensorCopyKernel::new(encoder.context(), self.data_type)?;- tensor_copy.encode(logits, &mut logits_copy, self.vocab_size * sampling_length, encoder);+ let mut logits_copy = command_buffer.allocate_scratch(logits.size())?;+ let copy_size = self.vocab_size as usize * sampling_length as usize * self.data_type.size_in_bytes();+ command_buffer.encode_copy(logits.subrange(..copy_size), logits_copy.subrange_mut(..copy_size));let repetition_penalty_kernel =- <B::Kernels as Kernels>::RepetitionPenaltyKernel::new(encoder.context(), self.data_type)?;+ <B::Kernels as Kernels>::RepetitionPenaltyKernel::new(command_buffer.context(), self.data_type)?;repetition_penalty_kernel.encode(logits,&mut logits_copy,@@ -142,13 +142,19 @@ impl<B: Backend> Sampling<B> {self.vocab_size,sampling_range.start,sampling_length,- encoder,+ command_buffer,);Some(logits_copy)} else {None};- let logits = penalized_logits.as_ref().unwrap_or(logits);+ let logits = match &penalized_logits {+ Some(logits) => (logits as &dyn Buffer<Backend = B>).subrange(..),+ None => {+ let (buffer, range) = logits.parts();+ (buffer as &dyn Buffer<Backend = B>).subrange(range)+ },+ };let mut unified_kernels = self.unified_kernels.lock();let entry = unified_kernels.entry(key);@@ -158,7 +164,7 @@ impl<B: Backend> Sampling<B> {let key = vacant.key();let kernel = <B::Kernels as Kernels>::UnifiedSamplingKernel::new(- encoder.context(),+ command_buffer.context(),self.data_type,key.is_stochastic,key.has_bitmask,@@ -172,8 +178,7 @@ impl<B: Backend> Sampling<B> {},};- let mut output =- encoder.context().create_allocation(sampling_length as usize * size_of::<u32>(), AllocationType::Global)?;+ let mut output = command_buffer.context().create_buffer(sampling_length as usize * size_of::<u32>())?;kernel.encode(logits,@@ -186,10 +191,10 @@ impl<B: Backend> Sampling<B> {min_p,self.vocab_size,sampling_length,- encoder,+ command_buffer,);- encoder.pop_debug_group();+ command_buffer.pop_debug_group();Ok(output)}diff --git a/crates/uzu-engine/src/encodable_block/transformer.rs b/crates/uzu-engine/src/encodable_block/transformer.rsindex d02a9432d..4a107cc1f 100644--- a/crates/uzu-engine/src/encodable_block/transformer.rs+++ b/crates/uzu-engine/src/encodable_block/transformer.rs@@ -1,9 +1,11 @@-use std::ops::Range;+use std::range::Range;use thiserror::Error;use crate::{- backends::common::{Allocation, Backend, Encoder, Kernels, kernel::TensorAddScaleKernel},+ backends::common::{+ Backend, Buffer, BufferRef, CommandBuffer, CommandBufferEncoding, Kernels, kernel::TensorAddScaleKernel,+ },config::{rope::AnyRoPEConfig, transformer::TransformerConfig},data_type::DataType,encodable_block::{@@ -27,8 +29,8 @@ pub struct TransformerState<B: Backend> {}pub struct TransformerEncodeOutput<B: Backend> {- pub output: Option<Allocation<B>>,- pub hidden_features: Option<Box<[Allocation<B>]>>,+ pub output: Option<B::ScratchBuffer>,+ pub hidden_features: Option<Box<[B::ScratchBuffer]>>,}impl<B: Backend> TransformerState<B> {@@ -56,21 +58,21 @@ impl<B: Backend> TransformerState<B> {pub fn encode_accept(&mut self,accepted_indices: &[u32],- encoder: &mut Encoder<B>,+ command_buffer: &mut <B::CommandBuffer as CommandBuffer>::Encoding,) -> Result<(), B::Error> {- encoder.push_debug_group("transformer accept");+ command_buffer.push_debug_group("transformer accept");for layer_state in &mut self.layer_states {let TransformerLayerStateType::Owned(layer_state) = layer_state else {continue;};- layer_state.encode_accept(accepted_indices, encoder)?;+ layer_state.encode_accept(accepted_indices, command_buffer)?;}self.context_length += accepted_indices.len() as u32;- encoder.pop_debug_group();+ command_buffer.pop_debug_group();Ok(())}@@ -97,7 +99,7 @@ pub struct Transformer<B: Backend> {impl<B: Backend> Transformer<B> {pub fn new(context: &B::Context,- output_norm_hadamard_factors: Option<Allocation<B>>,+ output_norm_hadamard_factors: Option<B::GlobalBuffer>,data_type: DataType,transformer_config: &TransformerConfig,parameter_tree: &ParameterTree<B>,@@ -159,14 +161,14 @@ impl<B: Backend> Transformer<B> {fn capture_residual(&self,- shortcut: &Allocation<B>,- hidden: &Allocation<B>,+ shortcut: impl BufferRef<Backend = B>,+ hidden: impl BufferRef<Backend = B>,batch_size: u32,- encoder: &mut Encoder<B>,- ) -> Result<Allocation<B>, B::Error> {- let mut output = encoder.allocate_scratch(hidden.size())?;+ command_buffer: &mut <B::CommandBuffer as CommandBuffer>::Encoding,+ ) -> Result<B::ScratchBuffer, B::Error> {+ let mut output = command_buffer.allocate_scratch(hidden.size())?;let elements = batch_size * self.model_dim;- self.residual_add.encode(Some(shortcut), hidden, &mut output, elements, elements, 1.0, encoder);+ self.residual_add.encode(Some(shortcut), hidden, &mut output, elements, elements, 1.0, command_buffer);Ok(output)}@@ -225,13 +227,13 @@ impl<B: Backend> Transformer<B> {pub fn encode(&self,- input: Allocation<B>,- per_layer_inputs: Option<&Allocation<B>>,+ input: B::ScratchBuffer,+ per_layer_inputs: Option<impl BufferRef<Backend = B>>,batch_dim: &BatchTopology,output_range: Option<Range<u32>>,hidden_feature_layer_indices: Option<&[u32]>,mut state: Option<&mut TransformerState<B>>,- encoder: &mut Encoder<B>,+ command_buffer: &mut <B::CommandBuffer as CommandBuffer>::Encoding,) -> Result<TransformerEncodeOutput<B>, B::Error> {let mut hidden = input;let layer_count = if output_range.is_none() && hidden_feature_layer_indices.is_none() {@@ -240,7 +242,7 @@ impl<B: Backend> Transformer<B> {self.layers.len()};- let mut shortcut = encoder.allocate_scratch(hidden.size())?;+ let mut shortcut = command_buffer.allocate_scratch(hidden.size())?;let mut hidden_features =hidden_feature_layer_indices.map(|indices| (0..indices.len()).map(|_| None).collect::<Vec<_>>());@@ -250,7 +252,7 @@ impl<B: Backend> Transformer<B> {let precalculated_ropes = self.ropes.iter()- .map(|rope_config| PrecalculatedRoPE::precalculate(rope_config, &token_positions, encoder))+ .map(|rope_config| PrecalculatedRoPE::precalculate(rope_config, &token_positions, command_buffer)).collect::<Result<Box<[_]>, B::Error>>()?;for (layer, layer_rope_index) in self.layers.iter().take(layer_count) {@@ -279,13 +281,13 @@ impl<B: Backend> Transformer<B> {precalculated_rope,batch_dim,layer_state,- encoder,+ command_buffer,)?;if let (Some(hidden_features), Some(indices)) = (&mut hidden_features, hidden_feature_layer_indices) {for (feature_index, &layer_index) in indices.iter().enumerate() {if layer_index == layer.layer_index {- let feature = self.capture_residual(&shortcut, &hidden, batch_dim.size(), encoder)?;+ let feature = self.capture_residual(&shortcut, &hidden, batch_dim.size(), command_buffer)?;hidden_features[feature_index] = Some(feature);}}@@ -319,7 +321,7 @@ impl<B: Backend> Transformer<B> {output_range.start,output_range.end - output_range.start,Some(&mut shortcut),- encoder,+ command_buffer,)?;Ok(TransformerEncodeOutput {diff --git a/crates/uzu-engine/src/encodable_block/transformer_layer.rs b/crates/uzu-engine/src/encodable_block/transformer_layer.rsindex 6294394c1..d9d31634d 100644--- a/crates/uzu-engine/src/encodable_block/transformer_layer.rs+++ b/crates/uzu-engine/src/encodable_block/transformer_layer.rs@@ -1,7 +1,9 @@use thiserror::Error;use crate::{- backends::common::{Allocation, Backend, Encoder, kernel::ActivationTransform},+ backends::common::{+ Backend, BufferMut, BufferRef, CommandBuffer, CommandBufferEncoding, kernel::ActivationTransform,+ },config::transformer_layer::{TransformerLayerConfig, TransformerLayerConvConfig},data_type::DataType,encodable_block::{@@ -46,7 +48,7 @@ struct TransformerLayerConv<B: Backend> {pre_conv: SeparableCausalConv<B>,kernel_projection: Box<dyn Linear<B>>,post_conv: SeparableCausalConv<B>,- input_rht: Option<(ActivationTransform<B>, Allocation<B>)>,+ input_rht: Option<(ActivationTransform<B>, B::GlobalBuffer)>,coefficient_count: u32,}@@ -73,7 +75,7 @@ impl<B: Backend> TransformerLayerConv<B> {config: &TransformerLayerConvConfig,parameter_tree: &ParameterTree<B>,data_type: DataType,- input_hadamard_factors: Option<Allocation<B>>,+ input_hadamard_factors: Option<B::GlobalBuffer>,) -> Result<Self, TransformerLayerError<B>> {let pre_conv = SeparableCausalConv::new(model_dim,@@ -122,35 +124,41 @@ impl<B: Backend> TransformerLayerConv<B> {fn encode_pre_convolution(&self,- input: &Allocation<B>,+ input: impl BufferRef<Backend = B>,sequence_length: u32,- encoder: &mut Encoder<B>,- ) -> Result<(Allocation<B>, Allocation<B>), B::Error> {- let mut projection_input = encoder.allocate_scratch(input.size())?;- encoder.encode_copy(input, .., &mut projection_input, ..);- let coefficients = self.kernel_projection.encode(projection_input, sequence_length, encoder)?;- let mut output =- self.pre_conv.encode(input, &coefficients, 2 * self.coefficient_count, 0, sequence_length, encoder)?;+ command_buffer: &mut <B::CommandBuffer as CommandBuffer>::Encoding,+ ) -> Result<(B::ScratchBuffer, B::ScratchBuffer), B::Error> {+ let mut projection_input = command_buffer.allocate_scratch(input.size())?;+ command_buffer.encode_copy(input, &mut projection_input);+ let coefficients = self.kernel_projection.encode(projection_input, sequence_length, command_buffer)?;+ let mut output = self.pre_conv.encode(+ input,+ &coefficients,+ 2 * self.coefficient_count,+ 0,+ sequence_length,+ command_buffer,+ )?;if let Some((transform, factors)) = &self.input_rht {- transform.encode_fp_in_place(&mut output, factors, None, sequence_length, self.model_dim, encoder);+ transform.encode_fp_in_place(&mut output, factors, None, sequence_length, self.model_dim, command_buffer);}Ok((output, coefficients))}fn encode_post_convolution(&self,- input: &Allocation<B>,- coefficients: &Allocation<B>,+ input: impl BufferRef<Backend = B>,+ coefficients: impl BufferRef<Backend = B>,sequence_length: u32,- encoder: &mut Encoder<B>,- ) -> Result<Allocation<B>, B::Error> {+ command_buffer: &mut <B::CommandBuffer as CommandBuffer>::Encoding,+ ) -> Result<B::ScratchBuffer, B::Error> {self.post_conv.encode(input,coefficients,2 * self.coefficient_count,self.coefficient_count,sequence_length,- encoder,+ command_buffer,)}}@@ -333,26 +341,27 @@ impl<B: Backend> TransformerLayer<B> {pub fn encode(&self,- input: Allocation<B>,- shortcut: &mut Allocation<B>,- per_layer_inputs: Option<&Allocation<B>>,+ input: B::ScratchBuffer,+ mut shortcut: impl BufferMut<Backend = B>,+ per_layer_inputs: Option<impl BufferRef<Backend = B>>,precalculated_rope: Option<&PrecalculatedRoPE<B>>,batch_dim: &BatchTopology,state: Option<MaybeMut<dyn MixerState<B>>>,- encoder: &mut Encoder<B>,- ) -> Result<Allocation<B>, B::Error> {- encoder.push_debug_group(&format!("transformer layer {}", self.layer_index));+ command_buffer: &mut <B::CommandBuffer as CommandBuffer>::Encoding,+ ) -> Result<B::ScratchBuffer, B::Error> {+ command_buffer.push_debug_group(&format!("transformer layer {}", self.layer_index));let mut hidden = if let Some(pre_mixer_norm) = &self.pre_mixer_norm {- pre_mixer_norm.encode(&input, 0, batch_dim.size(), Some(shortcut), encoder)?+ pre_mixer_norm.encode(&input, 0, batch_dim.size(), Some(shortcut.reborrow()), command_buffer)?} else {assert!(self.layer_index == 0);- encoder.encode_copy(&input, .., shortcut, ..);+ command_buffer.encode_copy(&input, shortcut.reborrow());input};let mixer_coefficients = if let Some(convolution) = &self.mixer_conv {- let (output, coefficients) = convolution.encode_pre_convolution(&hidden, batch_dim.size(), encoder)?;+ let (output, coefficients) =+ convolution.encode_pre_convolution(&hidden, batch_dim.size(), command_buffer)?;hidden = output;Some(coefficients)} else {@@ -360,45 +369,55 @@ impl<B: Backend> TransformerLayer<B> {};// TODO: In prefill outside of sampling suffix in last layer part of mixer (ie out projection) and everything after is dead code- hidden = self.mixer.encode(hidden, precalculated_rope, batch_dim, state, encoder)?;+ hidden = self.mixer.encode(hidden, precalculated_rope, batch_dim, state, command_buffer)?;if let Some(coefficients) = mixer_coefficients {let convolution = self.mixer_conv.as_ref().expect("mixer convolution required");- hidden = convolution.encode_post_convolution(&hidden, &coefficients, batch_dim.size(), encoder)?;+ hidden = convolution.encode_post_convolution(&hidden, &coefficients, batch_dim.size(), command_buffer)?;}if let Some(post_mixer_norm) = &self.post_mixer_norm {- hidden = post_mixer_norm.encode(&hidden, 0, batch_dim.size(), None, encoder)?;+ hidden =+ post_mixer_norm.encode(&hidden, 0, batch_dim.size(), None::<&mut B::ScratchBuffer>, command_buffer)?;}- hidden = self.pre_mlp_norm.encode(&hidden, 0, batch_dim.size(), Some(shortcut), encoder)?;+ hidden = self.pre_mlp_norm.encode(&hidden, 0, batch_dim.size(), Some(shortcut.reborrow()), command_buffer)?;let mlp_coefficients = if let Some(convolution) = &self.mlp_conv {- let (output, coefficients) = convolution.encode_pre_convolution(&hidden, batch_dim.size(), encoder)?;+ let (output, coefficients) =+ convolution.encode_pre_convolution(&hidden, batch_dim.size(), command_buffer)?;hidden = output;Some(coefficients)} else {None};- hidden = self.mlp.encode(hidden, batch_dim.size(), encoder)?;+ hidden = self.mlp.encode(hidden, batch_dim.size(), command_buffer)?;if let Some(coefficients) = mlp_coefficients {let convolution = self.mlp_conv.as_ref().expect("mlp convolution required");- hidden = convolution.encode_post_convolution(&hidden, &coefficients, batch_dim.size(), encoder)?;+ hidden = convolution.encode_post_convolution(&hidden, &coefficients, batch_dim.size(), command_buffer)?;}if let Some(post_mlp_norm) = &self.post_mlp_norm {- hidden = post_mlp_norm.encode(&hidden, 0, batch_dim.size(), None, encoder)?;+ hidden =+ post_mlp_norm.encode(&hidden, 0, batch_dim.size(), None::<&mut B::ScratchBuffer>, command_buffer)?;}if let Some(ple_projection) = &self.ple_projection {let per_layer_inputs = per_layer_inputs.expect("per-layer inputs required for PLE layer");- ple_projection.encode(self.layer_index, per_layer_inputs, shortcut, &hidden, batch_dim.size(), encoder)?;- encoder.encode_fill(&mut hidden, 0);+ ple_projection.encode(+ self.layer_index,+ per_layer_inputs,+ shortcut,+ &hidden,+ batch_dim.size(),+ command_buffer,+ )?;+ command_buffer.encode_fill(&mut hidden, 0);}- encoder.pop_debug_group();+ command_buffer.pop_debug_group();Ok(hidden)}diff --git a/crates/uzu-engine/src/encodable_block/weaver.rs b/crates/uzu-engine/src/encodable_block/weaver.rsindex 479c704d9..027ede941 100644--- a/crates/uzu-engine/src/encodable_block/weaver.rs+++ b/crates/uzu-engine/src/encodable_block/weaver.rs@@ -3,10 +3,9 @@ use thiserror::Error;use crate::{array::size_for_shape,backends::common::{- Allocation, Backend, Encoder, Kernels,+ Backend, Buffer, BufferMut, BufferRef, CommandBuffer, CommandBufferEncoding, Context, Kernels,gpu_types::weaver::{- CANDIDATES_MAX, FRONTIER_MAX_SLOTS, FRONTIER_MAX_WIDTH, FRONTIER_NO_WINNER, FrontierIdx, MetadataIdx,- TreeIdx,+ CANDIDATES_MAX, FRONTIER_MAX_SLOTS, FRONTIER_MAX_WIDTH, FrontierIdx, MetadataIdx, TreeIdx,},kernel::{AncestorAttentionKernel, AttentionArguments, AttentionKernel, WeaverFrontierInsertChildrenKernel,@@ -46,8 +45,8 @@ impl WeaverTreeShape {}pub struct EncodedWeaverTree<B: Backend> {- packed_tree: Allocation<B>,- frontier: Allocation<B>,+ packed_tree: B::GlobalBuffer,+ frontier: B::GlobalBuffer,}pub struct ProposalNode {@@ -293,42 +292,42 @@ impl<B: Backend> Weaver<B> {fn encode_prefix(&self,- target_hidden: &Allocation<B>,- draft_hidden: &Allocation<B>,+ target_hidden: impl BufferRef<Backend = B>,+ draft_hidden: impl BufferRef<Backend = B>,rope: &PrecalculatedRoPE<B>,depth: u32,- encoder: &mut Encoder<B>,- ) -> Result<Vec<Allocation<B>>, WeaverEncodeError<B>> {- encoder.push_debug_group("weaver prefix");+ command_buffer: &mut <B::CommandBuffer as CommandBuffer>::Encoding,+ ) -> Result<Vec<B::ScratchBuffer>, WeaverEncodeError<B>> {+ command_buffer.push_debug_group("weaver prefix");let hidden_row_bytes = size_for_shape(&[self.target_model_dim], DATA_TYPE);- let mut prefix_hidden = encoder- .allocate_scratch(size_for_shape(&[depth, self.target_model_dim], DATA_TYPE))+ let mut prefix_hidden = command_buffer+ .allocate_scratch_for_shape(&[depth, self.target_model_dim], DATA_TYPE).map_err(WeaverEncodeError::Backend)?;- encoder.encode_copy(target_hidden, 0..hidden_row_bytes, &mut prefix_hidden, 0..hidden_row_bytes);- encoder.encode_copy(- draft_hidden,- hidden_row_bytes..depth as usize * hidden_row_bytes,- &mut prefix_hidden,- hidden_row_bytes..depth as usize * hidden_row_bytes,+ command_buffer+ .encode_copy(target_hidden.subrange(..hidden_row_bytes), prefix_hidden.subrange_mut(..hidden_row_bytes));+ command_buffer.encode_copy(+ draft_hidden.subrange(hidden_row_bytes..depth as usize * hidden_row_bytes),+ prefix_hidden.subrange_mut(hidden_row_bytes..),);let normalized_prefix = self.hidden_state_norm- .encode(&prefix_hidden, 0, depth, None, encoder)+ .encode(&prefix_hidden, 0, depth, None::<&mut B::ScratchBuffer>, command_buffer).map_err(WeaverEncodeError::Backend)?;let mut residual_input = self.hidden_state_projection- .encode(normalized_prefix, depth, encoder)+ .encode(normalized_prefix, depth, command_buffer).map_err(WeaverEncodeError::Backend)?;let (last_layer, preceding_layers) = self.layers.split_last().expect("Weaver must have at least one layer");- let mut residual_state = encoder.allocate_scratch(residual_input.size()).map_err(WeaverEncodeError::Backend)?;+ let mut residual_state =+ command_buffer.allocate_scratch(residual_input.size()).map_err(WeaverEncodeError::Backend)?;let mut prefix_kv_layers = Vec::with_capacity(self.layers.len());for layer in preceding_layers {let PreparedPrefixAttention {queries,kv_cache,} = layer- .encode_prefix_attention(&residual_input, &mut residual_state, rope, depth, encoder)+ .encode_prefix_attention(&residual_input, &mut residual_state, rope, depth, command_buffer).map_err(WeaverEncodeError::Backend)?;let cache = KVCacheView::full(0);let kv_plane_bytes = size_for_shape(&[depth, self.model_dim], DATA_TYPE);@@ -338,54 +337,54 @@ impl<B: Backend> Weaver<B> {AttentionArguments {queries: &queries,keys: &kv_cache,- values: (&kv_cache, kv_plane_bytes),+ values: kv_cache.subrange(kv_plane_bytes..),suffix_length: depth,- trie: None,+ trie: None::<&B::ConstantBuffer>,sinks: None,cache,},- encoder,+ command_buffer,).map_err(WeaverEncodeError::Backend)?;residual_input = layer- .encode_post_attention(attention_output, &mut residual_state, depth, encoder)+ .encode_post_attention(attention_output, &mut residual_state, depth, command_buffer).map_err(WeaverEncodeError::Backend)?;prefix_kv_layers.push(kv_cache);}prefix_kv_layers.push(last_layer- .encode_prefix_attention(&residual_input, &mut residual_state, rope, depth, encoder)+ .encode_prefix_attention(&residual_input, &mut residual_state, rope, depth, command_buffer).map_err(WeaverEncodeError::Backend)?.kv_cache,);- encoder.pop_debug_group();+ command_buffer.pop_debug_group();Ok(prefix_kv_layers)}- fn encode_step(+ fn encode_step<Ids: BufferRef<Backend = B>, Logits: BufferRef<Backend = B>>(&self,target_embedding: &Embedding<B>,- prefix_kv_layers: &[Allocation<B>],+ mut prefix_kv_layers: impl Iterator<Item = impl BufferRef<Backend = B>>,rope: &PrecalculatedRoPE<B>,- node_kv_layers: &mut [Allocation<B>],- packed_tree: &mut Allocation<B>,- frontier: &mut Allocation<B>,- slot_ancestors: &mut Allocation<B>,- node_token_ids: &mut Allocation<B>,- node_metadata: &mut Allocation<B>,- node_ancestor_indices: &mut Allocation<B>,- node_valid: &mut Allocation<B>,- node_candidate_ids: &mut Allocation<B>,- node_candidate_logits: &mut Allocation<B>,- depth_seeds_buffer: &Allocation<B>,- candidate_ids: &Allocation<B>,- candidate_logits: &Allocation<B>,+ mut node_kv_layers: impl Iterator<Item = impl BufferMut<Backend = B>>,+ mut packed_tree: impl BufferMut<Backend = B>,+ mut frontier: impl BufferMut<Backend = B>,+ slot_ancestors: impl BufferMut<Backend = B>,+ mut node_token_ids: impl BufferMut<Backend = B>,+ mut node_metadata: impl BufferMut<Backend = B>,+ mut node_ancestor_indices: impl BufferMut<Backend = B>,+ mut node_valid: impl BufferMut<Backend = B>,+ mut node_candidate_ids: impl BufferMut<Backend = B, Buffer = Ids::Buffer>,+ mut node_candidate_logits: impl BufferMut<Backend = B, Buffer = Logits::Buffer>,+ depth_seeds_buffer: impl BufferRef<Backend = B>,+ candidate_ids: Ids,+ candidate_logits: Logits,shape: &WeaverTreeShape,batch_node_count: u32,batch_start_slot: u32,- encoder: &mut Encoder<B>,+ command_buffer: &mut <B::CommandBuffer as CommandBuffer>::Encoding,) -> Result<(), WeaverEncodeError<B>> {let tree_slot_count = shape.slot_count();let ancestor_stride = self.max_depth;@@ -393,17 +392,17 @@ impl<B: Backend> Weaver<B> {if batch_start_slot > 0 {self.frontier_select.encode(- &mut *frontier,- &mut *packed_tree,- &mut *slot_ancestors,- &mut *node_token_ids,- &mut *node_metadata,- &mut *node_ancestor_indices,- &mut *node_valid,+ frontier.reborrow(),+ packed_tree.reborrow(),+ slot_ancestors,+ node_token_ids.reborrow(),+ node_metadata.reborrow(),+ node_ancestor_indices.reborrow(),+ node_valid.reborrow(),candidate_ids,candidate_logits,- &mut *node_candidate_ids,- &mut *node_candidate_logits,+ node_candidate_ids.reborrow(),+ node_candidate_logits.reborrow(),frontier_capacity,tree_slot_count,batch_node_count,@@ -413,50 +412,53 @@ impl<B: Backend> Weaver<B> {shape.max_depth - 1,shape.dflash_depth - 1,self.candidate_pool_size,- encoder,+ command_buffer,);}let (batch_candidate_ids, batch_candidate_logits) = if batch_start_slot == 0 {- (candidate_ids, candidate_logits)+ (candidate_ids.subrange(..), candidate_logits.subrange(..))} else {- (&*node_candidate_ids, &*node_candidate_logits)+ (node_candidate_ids.as_ref().subrange(..), node_candidate_logits.as_ref().subrange(..))};// Node expansion: embed the batch's tokens, run every layer against// the prefix KV and each node's ancestors, then pick its children.- let token_embedding = target_embedding.encode_lookup(&*node_token_ids, batch_node_count, encoder)?;+ let token_embedding =+ target_embedding.encode_lookup(node_token_ids.as_ref(), batch_node_count, command_buffer)?;let normalized_embedding = self.token_embedding_norm- .encode(&token_embedding, 0, batch_node_count, None, encoder)+ .encode(&token_embedding, 0, batch_node_count, None::<&mut B::ScratchBuffer>, command_buffer).map_err(WeaverEncodeError::Backend)?;let mut residual_input = self.token_embedding_projection- .encode(normalized_embedding, batch_node_count, encoder)+ .encode(normalized_embedding, batch_node_count, command_buffer).map_err(WeaverEncodeError::Backend)?;- let mut residual_state = encoder.allocate_scratch(residual_input.size()).map_err(WeaverEncodeError::Backend)?;+ let mut residual_state =+ command_buffer.allocate_scratch(residual_input.size()).map_err(WeaverEncodeError::Backend)?;+ let node_metadata = node_metadata.as_ref();let metadata_field_bytes = size_for_shape(&[batch_node_count], DataType::U32);- for (layer_index, layer) in self.layers.iter().enumerate() {+ for layer in &self.layers {let attention_input = layer.pre_attention_norm- .encode(&residual_input, 0, batch_node_count, Some(&mut residual_state), encoder)+ .encode(&residual_input, 0, batch_node_count, Some(&mut residual_state), command_buffer).map_err(WeaverEncodeError::Backend)?;let current_qkv = layer.qkv_projection- .encode(attention_input, batch_node_count, encoder)+ .encode(attention_input, batch_node_count, command_buffer).map_err(WeaverEncodeError::Backend)?;- let mut attention_output = encoder- .allocate_scratch(size_for_shape(&[batch_node_count, self.model_dim], DATA_TYPE))+ let mut attention_output = command_buffer+ .allocate_scratch_for_shape(&[batch_node_count, self.model_dim], DATA_TYPE).map_err(WeaverEncodeError::Backend)?;layer.ancestor_attention.encode(- &prefix_kv_layers[layer_index],- &mut node_kv_layers[layer_index],+ prefix_kv_layers.next().expect("missing prefix KV layer"),+ node_kv_layers.next().expect("missing node KV layer"),¤t_qkv,&rope.cosines,&rope.sines,- &*node_metadata,- &*node_ancestor_indices,- (&*node_metadata, MetadataIdx::AncestorCount as usize * metadata_field_bytes),- (&*node_metadata, MetadataIdx::TreeSlot as usize * metadata_field_bytes),+ node_metadata,+ node_ancestor_indices.as_ref(),+ node_metadata.subrange(MetadataIdx::AncestorCount as usize * metadata_field_bytes..),+ node_metadata.subrange(MetadataIdx::TreeSlot as usize * metadata_field_bytes..),&mut attention_output,batch_node_count,shape.dflash_depth,@@ -464,20 +466,20 @@ impl<B: Backend> Weaver<B> {tree_slot_count,layer.max_depth,layer.attention_scale,- encoder,+ command_buffer,);residual_input = layer- .encode_post_attention(attention_output, &mut residual_state, batch_node_count, encoder)+ .encode_post_attention(attention_output, &mut residual_state, batch_node_count, command_buffer).map_err(WeaverEncodeError::Backend)?;}let normalized_output = self.readout_norm- .encode(&residual_input, 0, batch_node_count, Some(&mut residual_state), encoder)+ .encode(&residual_input, 0, batch_node_count, Some(&mut residual_state), command_buffer).map_err(WeaverEncodeError::Backend)?;let query = self.readout_query_projection- .encode(normalized_output, batch_node_count, encoder)+ .encode(normalized_output, batch_node_count, command_buffer).map_err(WeaverEncodeError::Backend)?;let logit_residuals = target_embedding.encode_readout(batch_node_count,@@ -485,17 +487,17 @@ impl<B: Backend> Weaver<B> {self.candidate_pool_size,Some(batch_candidate_ids),false,- encoder,+ command_buffer,)?;- let mut child_token_ids = encoder- .allocate_scratch(size_for_shape(&[batch_node_count, shape.expand_width], DataType::U32))+ let mut child_token_ids = command_buffer+ .allocate_scratch_for_shape(&[batch_node_count, shape.expand_width], DataType::U32).map_err(WeaverEncodeError::Backend)?;- let mut child_logprobs = encoder- .allocate_scratch(size_for_shape(&[batch_node_count, shape.expand_width], DataType::F32))+ let mut child_logprobs = command_buffer+ .allocate_scratch_for_shape(&[batch_node_count, shape.expand_width], DataType::F32).map_err(WeaverEncodeError::Backend)?;let mut child_prune_logprobs = shape.prune_noise_scale- .map(|_| encoder.allocate_scratch(size_for_shape(&[batch_node_count, shape.expand_width], DataType::F32)))+ .map(|_| command_buffer.allocate_scratch_for_shape(&[batch_node_count, shape.expand_width], DataType::F32)).transpose().map_err(WeaverEncodeError::Backend)?;let top_children = if shape.prune_noise_scale.is_some() {@@ -508,7 +510,7 @@ impl<B: Backend> Weaver<B> {batch_candidate_logits,batch_candidate_ids,depth_seeds_buffer,- &*node_metadata,+ node_metadata,&mut child_token_ids,&mut child_logprobs,child_prune_logprobs.as_mut(),@@ -517,14 +519,14 @@ impl<B: Backend> Weaver<B> {shape.expand_width,target_embedding.vocab_size(),shape.prune_noise_scale,- encoder,+ command_buffer,);// The edge lane feeds only final pruning; without prune noise it keeps the model logprobs.self.frontier_insert_children.encode(- &*packed_tree,- &*node_metadata,- &*node_valid,+ packed_tree.as_ref(),+ node_metadata,+ node_valid.as_ref(),&child_token_ids,&child_logprobs,child_prune_logprobs.as_ref().unwrap_or(&child_logprobs),@@ -533,7 +535,7 @@ impl<B: Backend> Weaver<B> {tree_slot_count,batch_node_count,shape.expand_width,- encoder,+ command_buffer,);Ok(())@@ -541,16 +543,16 @@ impl<B: Backend> Weaver<B> {pub fn encode_tree(&self,- target_hidden: &Allocation<B>,- draft_hidden: &Allocation<B>,+ target_hidden: impl BufferRef<Backend = B>,+ draft_hidden: impl BufferRef<Backend = B>,target_embedding: &Embedding<B>,- logits: &Allocation<B>,+ logits: impl BufferRef<Backend = B>,depth_seeds: &[u64],root_token_id: u32,shape: WeaverTreeShape,- encoder: &mut Encoder<B>,+ command_buffer: &mut <B::CommandBuffer as CommandBuffer>::Encoding,) -> Result<EncodedWeaverTree<B>, WeaverEncodeError<B>> {- encoder.push_debug_group("weaver tree");+ command_buffer.push_debug_group("weaver tree");let tree_slot_count = shape.slot_count();let ancestor_stride = self.max_depth;@@ -580,11 +582,11 @@ impl<B: Backend> Weaver<B> {logits.size() >= size_for_shape(&[pool_depth_count, vocab_size], DATA_TYPE),"draft logits do not cover the lookahead rows");- let mut candidate_ids = encoder- .allocate_scratch(size_for_shape(&[pool_depth_count, self.candidate_pool_size], DataType::U32))+ let mut candidate_ids = command_buffer+ .allocate_scratch_for_shape(&[pool_depth_count, self.candidate_pool_size], DataType::U32).map_err(WeaverEncodeError::Backend)?;- let mut candidate_logits = encoder- .allocate_scratch(size_for_shape(&[pool_depth_count, self.candidate_pool_size], DataType::F32))+ let mut candidate_logits = command_buffer+ .allocate_scratch_for_shape(&[pool_depth_count, self.candidate_pool_size], DataType::F32).map_err(WeaverEncodeError::Backend)?;self.top_k.encode(@@ -593,63 +595,79 @@ impl<B: Backend> Weaver<B> {&mut candidate_logits,pool_depth_count,self.candidate_pool_size,- encoder,+ command_buffer,).map_err(WeaverEncodeError::Backend)?;let rope_positions = (0..=self.max_depth).collect::<Box<[_]>>();- let rope = PrecalculatedRoPE::precalculate(&self.rope_config, &rope_positions, encoder)+ let rope = PrecalculatedRoPE::precalculate(&self.rope_config, &rope_positions, command_buffer).map_err(WeaverEncodeError::Backend)?;- let prefix_kv_layers = self.encode_prefix(target_hidden, draft_hidden, &rope, shape.dflash_depth, encoder)?;+ let prefix_kv_layers =+ self.encode_prefix(target_hidden, draft_hidden, &rope, shape.dflash_depth, command_buffer)?;// Per-layer KV cache for tree nodes, one slot per packed-tree slot.let node_kv_size = size_for_shape(&[2, tree_slot_count, self.model_dim], DATA_TYPE);let mut node_kv_layers = (0..self.layers.len())- .map(|_| encoder.allocate_scratch(node_kv_size))+ .map(|_| command_buffer.allocate_scratch(node_kv_size)).collect::<Result<Vec<_>, _>>().map_err(WeaverEncodeError::Backend)?;- let tree_slots = tree_slot_count as usize;- let round_nodes = shape.expand_per_round as usize;-- let mut tree_init = vec![0u32; TreeIdx::COUNT * tree_slots];- for slot in 0..tree_slots {- tree_init[TreeIdx::ParentSlot as usize * tree_slots + slot] = FRONTIER_NO_WINNER;- }- tree_init[TreeIdx::TokenId as usize * tree_slots] = root_token_id;- tree_init[TreeIdx::Valid as usize * tree_slots] = 1;+ let root =+ command_buffer.allocate_constant_from_slice(&[root_token_id, 1u32]).map_err(WeaverEncodeError::Backend)?;+ let word_bytes = DataType::U32.size_in_bytes();+ let tree_field_bytes = size_for_shape(&[tree_slot_count], DataType::U32);+ let mut packed_tree =+ command_buffer.allocate_scratch(TreeIdx::COUNT * tree_field_bytes).map_err(WeaverEncodeError::Backend)?;+ command_buffer.encode_fill(&mut packed_tree, 0);+ let parent_offset = TreeIdx::ParentSlot as usize * tree_field_bytes;+ command_buffer.encode_fill(+ packed_tree.subrange_mut(parent_offset..parent_offset + tree_field_bytes),+ 0xff, // FRONTIER_NO_WINNER+ );+ command_buffer.encode_copy(root.subrange(..word_bytes), packed_tree.subrange_mut(..word_bytes));+ let valid_offset = TreeIdx::Valid as usize * tree_field_bytes;+ command_buffer.encode_copy(+ root.subrange(word_bytes..),+ packed_tree.subrange_mut(valid_offset..valid_offset + word_bytes),+ );- let mut packed_tree = encoder.allocate_constant_from_slice(&tree_init).map_err(WeaverEncodeError::Backend)?;- let mut frontier = encoder- .allocate_constant_from_slice(&vec![0u32; FrontierIdx::COUNT * frontier_capacity as usize])+ let mut frontier = command_buffer+ .allocate_scratch_for_shape(&[FrontierIdx::COUNT as u32, frontier_capacity], DataType::U32)+ .map_err(WeaverEncodeError::Backend)?;+ command_buffer.encode_fill(&mut frontier, 0);+ let mut slot_ancestors = command_buffer+ .allocate_scratch_for_shape(&[tree_slot_count, ancestor_stride], DataType::U32).map_err(WeaverEncodeError::Backend)?;- let mut slot_ancestors = encoder- .allocate_constant_from_slice(&vec![0u32; tree_slots * ancestor_stride as usize])++ let mut node_token_ids = command_buffer+ .allocate_scratch_for_shape(&[shape.expand_per_round], DataType::U32).map_err(WeaverEncodeError::Backend)?;+ command_buffer.encode_fill(&mut node_token_ids, 0);+ command_buffer.encode_copy(root.subrange(..word_bytes), node_token_ids.subrange_mut(..word_bytes));- let mut initial_node_token_ids = vec![0u32; round_nodes];- initial_node_token_ids[0] = root_token_id;- let mut initial_node_valid = vec![0u32; round_nodes];- initial_node_valid[0] = 1;- let mut node_token_ids =- encoder.allocate_constant_from_slice(&initial_node_token_ids).map_err(WeaverEncodeError::Backend)?;- let mut node_metadata = encoder- .allocate_constant_from_slice(&vec![0u32; MetadataIdx::COUNT * round_nodes])+ let mut node_metadata = command_buffer+ .allocate_scratch_for_shape(&[MetadataIdx::COUNT as u32, shape.expand_per_round], DataType::U32)+ .map_err(WeaverEncodeError::Backend)?;+ command_buffer.encode_fill(&mut node_metadata, 0);+ let mut node_ancestor_indices = command_buffer+ .allocate_scratch_for_shape(&[shape.expand_per_round, ancestor_stride], DataType::U32).map_err(WeaverEncodeError::Backend)?;- let mut node_ancestor_indices = encoder- .allocate_constant_from_slice(&vec![0u32; round_nodes * ancestor_stride as usize])+ command_buffer.encode_fill(&mut node_ancestor_indices, 0);+ let mut node_valid = command_buffer+ .allocate_scratch_for_shape(&[shape.expand_per_round], DataType::U32).map_err(WeaverEncodeError::Backend)?;- let mut node_valid =- encoder.allocate_constant_from_slice(&initial_node_valid).map_err(WeaverEncodeError::Backend)?;- let mut node_candidate_ids = encoder- .allocate_constant_from_slice(&vec![0u32; (shape.expand_per_round * self.candidate_pool_size) as usize])+ command_buffer.encode_fill(&mut node_valid, 0);+ command_buffer.encode_copy(root.subrange(word_bytes..), node_valid.subrange_mut(..word_bytes));++ let mut node_candidate_ids = command_buffer+ .allocate_scratch_for_shape(&[shape.expand_per_round, self.candidate_pool_size], DataType::U32).map_err(WeaverEncodeError::Backend)?;- let mut node_candidate_logits = encoder- .allocate_constant_from_slice(&vec![0.0f32; (shape.expand_per_round * self.candidate_pool_size) as usize])+ let mut node_candidate_logits = command_buffer+ .allocate_scratch_for_shape(&[shape.expand_per_round, self.candidate_pool_size], DataType::F32).map_err(WeaverEncodeError::Backend)?;let depth_seeds_buffer =- encoder.allocate_constant_from_slice(depth_seeds).map_err(WeaverEncodeError::Backend)?;+ command_buffer.allocate_constant_from_slice(depth_seeds).map_err(WeaverEncodeError::Backend)?;let mut batch_start_slot = 0;for round in 0..shape.rounds {@@ -658,12 +676,12 @@ impl<B: Backend> Weaver<B> {} else {shape.expand_per_round};- encoder.push_debug_group("weaver step");+ command_buffer.push_debug_group("weaver step");self.encode_step(target_embedding,- &prefix_kv_layers,+ prefix_kv_layers.iter(),&rope,- &mut node_kv_layers,+ node_kv_layers.iter_mut(),&mut packed_tree,&mut frontier,&mut slot_ancestors,@@ -679,17 +697,24 @@ impl<B: Backend> Weaver<B> {&shape,batch_node_count,batch_start_slot,- encoder,+ command_buffer,)?;- encoder.pop_debug_group();+ command_buffer.pop_debug_group();batch_start_slot += batch_node_count;}- encoder.pop_debug_group();+ command_buffer.pop_debug_group();++ let mut packed_tree_readback =+ command_buffer.context().create_buffer(packed_tree.size()).map_err(WeaverEncodeError::Backend)?;+ command_buffer.encode_copy(&packed_tree, &mut packed_tree_readback);+ let mut frontier_readback =+ command_buffer.context().create_buffer(frontier.size()).map_err(WeaverEncodeError::Backend)?;+ command_buffer.encode_copy(&frontier, &mut frontier_readback);Ok(EncodedWeaverTree {- packed_tree,- frontier,+ packed_tree: packed_tree_readback,+ frontier: frontier_readback,})}}diff --git a/crates/uzu-engine/src/encodable_block/weaver_layer.rs b/crates/uzu-engine/src/encodable_block/weaver_layer.rsindex b9a484775..2b9080e6b 100644--- a/crates/uzu-engine/src/encodable_block/weaver_layer.rs+++ b/crates/uzu-engine/src/encodable_block/weaver_layer.rs@@ -1,7 +1,7 @@use crate::{array::size_for_shape,backends::common::{- Allocation, AsBufferRangeMut, Backend, Encoder, Kernels,+ Backend, BufferMut, BufferRef, CommandBuffer, CommandBufferEncoding, Kernels,kernel::{AncestorAttentionKernel, AttentionKernel, AttentionKernelConfig, AttentionPrepareKernel},},config::{@@ -20,8 +20,8 @@ use crate::{};pub struct PreparedPrefixAttention<B: Backend> {- pub queries: Allocation<B>,- pub kv_cache: Allocation<B>,+ pub queries: B::ScratchBuffer,+ pub kv_cache: B::ScratchBuffer,}pub struct WeaverLayer<B: Backend> {@@ -146,20 +146,20 @@ impl<B: Backend> WeaverLayer<B> {pub fn encode_prefix_attention(&self,- residual_input: &Allocation<B>,- residual_state: &mut Allocation<B>,+ residual_input: impl BufferRef<Backend = B>,+ residual_state: impl BufferMut<Backend = B>,rope: &PrecalculatedRoPE<B>,token_count: u32,- encoder: &mut Encoder<B>,+ command_buffer: &mut <B::CommandBuffer as CommandBuffer>::Encoding,) -> Result<PreparedPrefixAttention<B>, B::Error> {let attention_input =- self.pre_attention_norm.encode(residual_input, 0, token_count, Some(residual_state), encoder)?;- let qkv = self.qkv_projection.encode(attention_input, token_count, encoder)?;+ self.pre_attention_norm.encode(residual_input, 0, token_count, Some(residual_state), command_buffer)?;+ let qkv = self.qkv_projection.encode(attention_input, token_count, command_buffer)?;let mut queries =- encoder.allocate_scratch_for_shape(&[self.num_heads, token_count, self.head_dim], DATA_TYPE)?;+ command_buffer.allocate_scratch_for_shape(&[self.num_heads, token_count, self.head_dim], DATA_TYPE)?;let kv_plane_bytes = size_for_shape(&[token_count, self.model_dim], DATA_TYPE);- let mut kv_cache = encoder.allocate_scratch_for_shape(&[2, token_count, self.model_dim], DATA_TYPE)?;- let (keys, values) = kv_cache.as_buffer_range_mut().split_at(kv_plane_bytes);+ let mut kv_cache = command_buffer.allocate_scratch_for_shape(&[2, token_count, self.model_dim], DATA_TYPE)?;+ let (keys, values) = kv_cache.split_at(kv_plane_bytes);self.attention_prepare.encode(&qkv,&mut queries,@@ -174,7 +174,7 @@ impl<B: Backend> WeaverLayer<B> {Some(0),3 * self.model_dim,token_count,- encoder,+ command_buffer,);Ok(PreparedPrefixAttention {queries,@@ -184,14 +184,14 @@ impl<B: Backend> WeaverLayer<B> {pub fn encode_post_attention(&self,- attention_output: Allocation<B>,- residual_state: &mut Allocation<B>,+ attention_output: B::ScratchBuffer,+ residual_state: impl BufferMut<Backend = B>,token_count: u32,- encoder: &mut Encoder<B>,- ) -> Result<Allocation<B>, B::Error> {- let projected_attention = self.out_projection.encode(attention_output, token_count, encoder)?;+ command_buffer: &mut <B::CommandBuffer as CommandBuffer>::Encoding,+ ) -> Result<B::ScratchBuffer, B::Error> {+ let projected_attention = self.out_projection.encode(attention_output, token_count, command_buffer)?;let mlp_input =- self.pre_mlp_norm.encode(&projected_attention, 0, token_count, Some(residual_state), encoder)?;- self.mlp.encode(mlp_input, token_count, encoder)+ self.pre_mlp_norm.encode(&projected_attention, 0, token_count, Some(residual_state), command_buffer)?;+ self.mlp.encode(mlp_input, token_count, command_buffer)}}diff --git a/crates/uzu-engine/src/encodable_block/weight_matrix.rs b/crates/uzu-engine/src/encodable_block/weight_matrix.rsindex 90b3e084c..05e3e075d 100644--- a/crates/uzu-engine/src/encodable_block/weight_matrix.rs+++ b/crates/uzu-engine/src/encodable_block/weight_matrix.rs@@ -2,7 +2,7 @@ use thiserror::Error;use crate::{backends::common::{- Allocation, Backend,+ Backend, BufferCpuAccessible, BufferMut,gpu_types::{QuantizationMethod, QuantizationMode},kernel::matmul::{MatmulB, QuantParams, QuantParamsLayout, QuantizedB, QuantizedCorrection},},@@ -80,15 +80,15 @@ pub fn parse_spec<B: Backend>(spec: &AnyWeightMatrixSpec) -> Result<ParsedWeight}struct Quantized<B: Backend> {- scales: Allocation<B>,- correction: QuantizedCorrection<Allocation<B>>,+ scales: B::GlobalBuffer,+ correction: QuantizedCorrection<B::GlobalBuffer>,params: QuantParams,info: QuantizationInfo,signed_codes: bool,}pub struct WeightMatrix<B: Backend> {- values: Allocation<B>,+ values: B::GlobalBuffer,quantized: Option<Quantized<B>>,}@@ -113,7 +113,7 @@ impl<B: Backend> WeightMatrix<B> {let (rows, columns) = physical_shape(&layout, output_dim, input_dim);let Some(info) = quantization_info else {- let values = tree.leaf("weights")?.validate(&[rows, columns], data_type)?.read_allocation()?;+ let values = tree.leaf("weights")?.validate(&[rows, columns], data_type)?.read_buffer()?;return Ok(Self {values,quantized: None,@@ -136,11 +136,11 @@ impl<B: Backend> WeightMatrix<B> {let groups = columns.div_ceil(group_size);let values =- tree.leaf("weights")?.validate(&[rows, columns / packing_divisor], storage_data_type)?.read_allocation()?;+ tree.leaf("weights")?.validate(&[rows, columns / packing_divisor], storage_data_type)?.read_buffer()?;let params = QuantParams::new(params_layout, rows, groups);let load_plane =- |name: &str, shape: [u32; 2], storage_type: DataType| -> Result<Allocation<B>, WeightMatrixError<B>> {- Ok(tree.leaf(name)?.validate(&shape, storage_type)?.read_allocation()?)+ |name: &str, shape: [u32; 2], storage_type: DataType| -> Result<B::GlobalBuffer, WeightMatrixError<B>> {+ Ok(tree.leaf(name)?.validate(&shape, storage_type)?.read_buffer()?)};let scales = load_plane("scales", params.scale_shape(), data_type)?;let correction = match info.method {@@ -167,7 +167,7 @@ impl<B: Backend> WeightMatrix<B> {})}- pub fn values(&self) -> &Allocation<B> {+ pub fn values(&self) -> &B::GlobalBuffer {&self.values}@@ -175,19 +175,19 @@ impl<B: Backend> WeightMatrix<B> {self.quantized.as_ref().map(|quantized| quantized.info)}- pub fn scales(&self) -> Option<&Allocation<B>> {+ pub fn scales(&self) -> Option<&B::GlobalBuffer> {self.quantized.as_ref().map(|quantized| &quantized.scales)}- pub fn zero_points(&self) -> Option<&Allocation<B>> {+ pub fn zero_points(&self) -> Option<&B::GlobalBuffer> {self.quantized.as_ref()?.correction.zero_points()}- pub fn biases(&self) -> Option<&Allocation<B>> {+ pub fn biases(&self) -> Option<&B::GlobalBuffer> {self.quantized.as_ref()?.correction.biases()}- pub fn matmul_b(&self) -> MatmulB<'_, B> {+ pub fn matmul_b(&self) -> MatmulB<&B::GlobalBuffer> {let Some(quantized) = self.quantized.as_ref() else {return MatmulB::FullPrecision {b: &self.values,@@ -222,7 +222,7 @@ impl<B: Backend> WeightMatrix<B> {impl<B: Backend> Quantized<B> {fn prepare_a8_storage(&mut self,- values: &mut Allocation<B>,+ values: impl BufferMut<Buffer: BufferCpuAccessible>,) -> bool {if self.params.layout() != QuantParamsLayout::GroupOutput {return false;diff --git a/crates/uzu-engine/src/engine/classifier_model.rs b/crates/uzu-engine/src/engine/classifier_model.rsindex cd629b4a9..c2ae0dd6a 100644--- a/crates/uzu-engine/src/engine/classifier_model.rs+++ b/crates/uzu-engine/src/engine/classifier_model.rs@@ -16,7 +16,9 @@ use thiserror::Error;use tokenizers::Tokenizer;use crate::{- backends::common::{AllocationType, Backend, Context, Encoder},+ backends::common::{+ Backend, BufferRef, CommandBufferEncoding, CommandBufferExecutable, CommandBufferPending, Context,+ },config::{model::classifier_model::ClassifierModelConfig, token_codec::AnyTokenCodecConfig},data_type::DataType,encodable_block::classifier::{Classifier as ClassifierEncodable, ClassifierError as ClassifierEncodableError},@@ -142,26 +144,26 @@ impl<B: Backend> ClassifierModel<B> {return Err(ClassifierModelClassifyError::ContextOverflow);}- let mut encoder = Encoder::<B>::new(&self.context).map_err(ClassifierModelClassifyError::Backend)?;+ let mut command_buffer =+ self.context.create_command_buffer(None, None).map_err(ClassifierModelClassifyError::Backend)?;- let mut token_ids = encoder- .allocate_constant(input.len() * DataType::U32.size_in_bytes())+ let token_ids = command_buffer+ .allocate_constant_from_slice(&input.iter().map(|token_id| *token_id as u32).collect::<Box<[u32]>>()).map_err(ClassifierModelClassifyError::Backend)?;- token_ids.copyin(&input.iter().map(|token_id| *token_id as u32).collect::<Box<[u32]>>());- let logits = self.classifier.encode(&token_ids, input.len() as u32, &mut encoder)?;+ let logits = self.classifier.encode(&token_ids, input.len() as u32, &mut command_buffer)?;let mut output_buffer = self.context- .create_allocation(self.output_labels.len() * self.data_type.size_in_bytes(), AllocationType::Global)+ .create_buffer(self.output_labels.len() * self.data_type.size_in_bytes()).map_err(ClassifierModelClassifyError::Backend)?;- encoder.encode_copy(&logits, .., &mut output_buffer, ..);+ command_buffer.encode_copy(&logits, &mut output_buffer);drop(logits);drop(token_ids);- encoder.end_encoding().submit().wait_until_completed().map_err(ClassifierModelClassifyError::Backend)?;+ command_buffer.end_encoding().submit().wait_until_completed().map_err(ClassifierModelClassifyError::Backend)?;assert!(self.data_type == DataType::BF16);diff --git a/crates/uzu-engine/src/engine/language_model/mod.rs b/crates/uzu-engine/src/engine/language_model/mod.rsindex 20a78574a..ee1f1fa8b 100644--- a/crates/uzu-engine/src/engine/language_model/mod.rs+++ b/crates/uzu-engine/src/engine/language_model/mod.rs@@ -32,8 +32,6 @@ pub struct LanguageModel<B: Backend> {sampling: Sampling<B>,context_ring_update: <B::Kernels as Kernels>::ContextRingUpdateKernel,generation_config: GenerationConfig,- /// The literal text the model emits between its reasoning and its final- /// answer (e.g. "</think>"); None when the model does not separate them.end_of_thinking_tag: Option<String>,tokenizer: Arc<Tokenizer>,#[cfg(grammar)]diff --git a/crates/uzu-engine/src/engine/language_model/stream/stream.rs b/crates/uzu-engine/src/engine/language_model/stream/stream.rsindex 18216ab7e..0e76c3f68 100644--- a/crates/uzu-engine/src/engine/language_model/stream/stream.rs+++ b/crates/uzu-engine/src/engine/language_model/stream/stream.rs@@ -1,6 +1,7 @@use std::{iter::{once, repeat_n},mem::replace,+ range::Range,sync::Arc,};@@ -11,8 +12,8 @@ use crate::engine::language_model::grammar::Grammar;use crate::{array::size_for_shape,backends::common::{- Allocation, AllocationPool, AllocationType, Backend, Context, Encoder, Pending,- gpu_types::trie::TrieNode as GpuTrieNode, kernel::ContextRingUpdateKernel,+ Backend, Buffer, BufferMut, BufferRef, CommandBuffer, CommandBufferEncoding, CommandBufferExecutable,+ CommandBufferPending, Context, gpu_types::trie::TrieNode as GpuTrieNode, kernel::ContextRingUpdateKernel,},data_type::DataType,encodable_block::{batch_topology::BatchTopology, sampling::SamplingMethod},@@ -30,7 +31,7 @@ use crate::{enum ForwardPassChaining<B: Backend> {Constant {token: u64,- output_norm: Option<Allocation<B>>,+ output_norm: Option<B::ScratchBuffer>,},InFlight(DecodingStatePending<B>),}@@ -40,7 +41,7 @@ impl<B: Backend> ForwardPassChaining<B> {&'a mut self,tokens: &mut Vec<u64>,#[cfg(grammar)] grammar: Option<&mut Grammar>,- ) -> Result<(u64, Option<&'a Allocation<B>>), LanguageModelStreamError<B>> {+ ) -> Result<(u64, Option<&'a B::ScratchBuffer>), LanguageModelStreamError<B>> {match self {Self::Constant {token,@@ -90,12 +91,12 @@ impl<B: Backend> ForwardPassChaining<B> {struct DecodingStatePending<B: Backend> {input_trie: TrieNode,full_accept: bool,- pending: Box<[Pending<B>]>,+ pending: Box<[<B::CommandBuffer as CommandBuffer>::Pending]>,capture_span: Option<CaptureSpan<B>>,- hidden_features: Option<Box<[Allocation<B>]>>,- output_norm: Option<Allocation<B>>,- output_tokens: Arc<Allocation<B>>,- _input_token_source: Option<Arc<Allocation<B>>>,+ hidden_features: Option<Box<[B::ScratchBuffer]>>,+ output_norm: Option<B::ScratchBuffer>,+ output_tokens: Arc<B::GlobalBuffer>,+ _input_token_source: Option<Arc<B::GlobalBuffer>>,}enum DecodingState<B: Backend> {@@ -106,8 +107,8 @@ enum DecodingState<B: Backend> {Accepting {full: Box<[(usize, u64, u64)]>,num_accepted: usize,- hidden_features: Option<Box<[Allocation<B>]>>,- output_norm: Option<(Allocation<B>, usize)>,+ hidden_features: Option<Box<[B::ScratchBuffer]>>,+ output_norm: Option<(B::ScratchBuffer, usize)>,capture_span: Option<CaptureSpan<B>>,},Halted,@@ -131,8 +132,8 @@ pub struct LanguageModelStream<'a, B: Backend> {model: &'a LanguageModel<B>,model_state: &'a mut LanguageModelState<B>,options: LanguageModelStreamOptions,- allocation_pool: Arc<AllocationPool<B>>,- context_ring: Option<Allocation<B>>,+ allocation_pool: Arc<B::AllocationPool>,+ context_ring: Option<B::GlobalBuffer>,decoding_state: DecodingState<B>,metrics: TokenStreamMetrics,}@@ -165,35 +166,34 @@ impl<'a, B: Backend> LanguageModelStream<'a, B> {None};- let allocation_pool = Arc::new(model.engine.context.create_allocation_pool(false));+ let allocation_pool = model.engine.context.create_allocation_pool();- let mut context_ring =- if let Some(suffix_repetition_length) = options.sampling_method.suffix_repetition_length() {- let mut context_ring = model- .engine- .context- .create_allocation(- size_for_shape(&[2 + suffix_repetition_length], DataType::U32),- AllocationType::Global,- )- .map_err(LanguageModelStreamError::Backend)?;+ let mut context_ring = if let Some(suffix_repetition_length) =+ options.sampling_method.suffix_repetition_length()+ {+ let mut context_ring = model+ .engine+ .context+ .create_buffer(size_for_shape(&[2 + suffix_repetition_length], DataType::U32))+ .map_err(LanguageModelStreamError::Backend)?;- let state_tokens_range = model_state.tokens.len().saturating_sub(suffix_repetition_length as usize)- ..model_state.tokens.len();+ let state_tokens_range = Range::from(+ model_state.tokens.len().saturating_sub(suffix_repetition_length as usize)..model_state.tokens.len(),+ );- context_ring.copyin(- &once(0) // offset- .chain(once(state_tokens_range.len() as u64)) // length- .chain(model_state.tokens[state_tokens_range.clone()].iter().copied()) // tokens- .chain(repeat_n(0, suffix_repetition_length as usize - state_tokens_range.len())) // pad if not full- .map(|x| x as u32)- .collect::<Box<[_]>>(),- );+ context_ring.copyin(+ &once(0) // offset+ .chain(once(state_tokens_range.iter().len() as u64)) // length+ .chain(model_state.tokens[state_tokens_range].iter().copied()) // tokens+ .chain(repeat_n(0, suffix_repetition_length as usize - state_tokens_range.iter().len())) // pad if not full+ .map(|x| x as u32)+ .collect::<Box<[_]>>(),+ );- Some(context_ring)- } else {- None- };+ Some(context_ring)+ } else {+ None+ };let mut metrics = TokenStreamMetrics::default();@@ -213,9 +213,11 @@ impl<'a, B: Backend> LanguageModelStream<'a, B> {).map_err(LanguageModelStreamError::Backend)?;- let mut encoder =- Encoder::<B>::new_with_pool_name(&model.engine.context, allocation_pool.clone(), Some("prefill"))- .map_err(LanguageModelStreamError::Backend)?;+ let mut command_buffer = model+ .engine+ .context+ .create_command_buffer(Some("prefill"), Some(allocation_pool.clone()))+ .map_err(LanguageModelStreamError::Backend)?;let mut output_tokens = None;let mut output_norm = None;@@ -234,10 +236,11 @@ impl<'a, B: Backend> LanguageModelStream<'a, B> {let input_trie = TrieNode::flat(model_state.tokens.len(), input_chunk, &model_state.prng);let input_flat_trie = input_trie.linearize();- let mut token_ids = encoder- .allocate_constant(input_chunk.len() * DataType::U32.size_in_bytes())+ let token_ids = command_buffer+ .allocate_constant_from_slice(+ &input_chunk.iter().map(|token_id| *token_id as u32).collect::<Box<[u32]>>(),+ ).map_err(LanguageModelStreamError::Backend)?;- token_ids.copyin(&input_chunk.iter().map(|token_id| *token_id as u32).collect::<Box<[u32]>>());let input_flat_trie_nodes = input_flat_trie.token_subtrie_ranges().collect::<Box<[GpuTrieNode]>>();let batch_dim = BatchTopology::new(&input_flat_trie_nodes, true);@@ -245,10 +248,10 @@ impl<'a, B: Backend> LanguageModelStream<'a, B> {let decoder_output = model.decoder.encode(&token_ids,&batch_dim,- sample_last.then(|| input_chunk.len() as u32 - 1..input_chunk.len() as u32),+ sample_last.then(|| (input_chunk.len() as u32 - 1..input_chunk.len() as u32).into()),hidden_feature_layer_indices,&mut model_state.transformer_state,- &mut encoder,+ &mut command_buffer,)?;let logits = decoder_output.logits;@@ -256,20 +259,20 @@ impl<'a, B: Backend> LanguageModelStream<'a, B> {let logits = logits.unwrap();let seeds = if matches!(options.sampling_method, SamplingMethod::Stochastic { .. }) {- let mut seeds = encoder- .allocate_constant(DataType::U64.size_in_bytes())- .map_err(LanguageModelStreamError::Backend)?;- seeds.copyin(&[model_state- .prng- .derive((model_state.tokens.len() + input_chunk.len() - 1) as u64)]);- Some(seeds)+ Some(+ command_buffer+ .allocate_constant_from_slice(&[model_state+ .prng+ .derive((model_state.tokens.len() + input_chunk.len() - 1) as u64)])+ .map_err(LanguageModelStreamError::Backend)?,+ )} else {None};#[cfg(grammar)]let bitmask = if let Some(grammar) = options.grammar.as_mut() {- let mut bitmask = encoder+ let mut bitmask = command_buffer.allocate_constant(model.vocab_size.div_ceil(DataType::U32.size_in_bits()) * DataType::U32.size_in_bytes(),)@@ -284,7 +287,7 @@ impl<'a, B: Backend> LanguageModelStream<'a, B> {None};#[cfg(not(grammar))]- let bitmask = None;+ let bitmask = None::<B::ConstantBuffer>;output_norm = decoder_output.final_hidden;let sampled_row = batch_dim.size() - 1;@@ -299,8 +302,8 @@ impl<'a, B: Backend> LanguageModelStream<'a, B> {Some(&token_ids),&options.sampling_method,&batch_dim,- sampled_row..sampled_row + 1,- &mut encoder,+ (sampled_row..sampled_row + 1).into(),+ &mut command_buffer,).map_err(LanguageModelStreamError::Backend)?,);@@ -308,7 +311,7 @@ impl<'a, B: Backend> LanguageModelStream<'a, B> {model_state.transformer_state- .encode_accept(&(0..input_chunk.len() as u32).collect::<Box<[u32]>>(), &mut encoder)+ .encode_accept(&(0..input_chunk.len() as u32).collect::<Box<[u32]>>(), &mut command_buffer).map_err(LanguageModelStreamError::Backend)?;if let Some(speculator) = model.speculator.as_ref() {@@ -316,9 +319,9 @@ impl<'a, B: Backend> LanguageModelStream<'a, B> {speculator.encode_accept(speculator_state,- decoder_output.hidden_features.as_ref().unwrap(),+ decoder_output.hidden_features.as_ref().unwrap().iter(),&(0..input_chunk.len() as u32).collect::<Box<[u32]>>(),- &mut encoder,+ &mut command_buffer,).map_err(LanguageModelStreamError::Backend)?;}@@ -329,14 +332,14 @@ impl<'a, B: Backend> LanguageModelStream<'a, B> {context_ring.as_mut().unwrap(),suffix_repetition_length,input_chunk.len() as u32,- &mut encoder,+ &mut command_buffer,);}model_state.tokens.extend(input_chunk);}- let pending = Box::new([encoder.end_encoding().submit()]);+ let pending = Box::new([command_buffer.end_encoding().submit()]);metrics.num_prefill_forward_passes += 1;metrics.num_tokens_prefilled += input.len();@@ -372,163 +375,164 @@ impl<'a, B: Backend> LanguageModelStream<'a, B> {}fn generate(&mut self) -> Result<Option<u64>, LanguageModelStreamError<B>> {- let (mut prev_output, mut encoder): (ForwardPassChaining<B>, Option<Encoder<B>>) =- match replace(&mut self.decoding_state, DecodingState::Invalid) {- DecodingState::Seeded {- seed_token,- } => {- self.model_state.tokens.push(seed_token);- #[cfg(grammar)]- if let Some(grammar) = self.options.grammar.as_mut() {- let _ = grammar.accept_token(seed_token); // TODO: this should not be ignored- }+ let (mut prev_output, mut command_buffer): (+ ForwardPassChaining<B>,+ Option<<B::CommandBuffer as CommandBuffer>::Encoding>,+ ) = match replace(&mut self.decoding_state, DecodingState::Invalid) {+ DecodingState::Seeded {+ seed_token,+ } => {+ self.model_state.tokens.push(seed_token);+ #[cfg(grammar)]+ if let Some(grammar) = self.options.grammar.as_mut() {+ let _ = grammar.accept_token(seed_token); // TODO: this should not be ignored+ }+ self.metrics.num_tokens_returned += 1;+ (+ ForwardPassChaining::Constant {+ token: seed_token,+ output_norm: None,+ },+ None,+ )+ },+ DecodingState::ForwardPassPending(forward_pass_pending) => {+ if forward_pass_pending.full_accept {self.metrics.num_tokens_returned += 1;- (- ForwardPassChaining::Constant {- token: seed_token,- output_norm: None,- },- None,- )- },- DecodingState::ForwardPassPending(forward_pass_pending) => {- if forward_pass_pending.full_accept {- self.metrics.num_tokens_returned += 1;- (ForwardPassChaining::InFlight(forward_pass_pending), None)- } else {- for pending in forward_pass_pending.pending {- pending.wait_until_completed().map_err(LanguageModelStreamError::Backend)?;- }- let sampled_tokens = forward_pass_pending- .output_tokens- .as_slice::<u32>()- .iter()- .map(|x| *x as u64)- .collect::<Box<[u64]>>();- let flat_trie = forward_pass_pending.input_trie.linearize();- let full = flat_trie.accept(- &sampled_tokens,- #[cfg(grammar)]- self.options.grammar.as_mut(),- )?;- let output_norm = forward_pass_pending.output_norm.map(|norm| {- let row_bytes = norm.size() / flat_trie.len();- (norm, row_bytes)- });- self.metrics.num_tokens_accepted += full.len();- self.decoding_state = DecodingState::Accepting {- full,- num_accepted: 0,- hidden_features: forward_pass_pending.hidden_features,- output_norm,- capture_span: forward_pass_pending.capture_span,- };- return self.generate();+ (ForwardPassChaining::InFlight(forward_pass_pending), None)+ } else {+ for pending in forward_pass_pending.pending {+ pending.wait_until_completed().map_err(LanguageModelStreamError::Backend)?;}- },- DecodingState::Accepting {- full,- num_accepted,- hidden_features,- output_norm,- capture_span,- } => {- let output_token_id = full[num_accepted].2;+ let sampled_tokens = forward_pass_pending+ .output_tokens+ .as_slice::<u32>()+ .iter()+ .map(|x| *x as u64)+ .collect::<Box<[u64]>>();+ let flat_trie = forward_pass_pending.input_trie.linearize();+ let full = flat_trie.accept(+ &sampled_tokens,+ #[cfg(grammar)]+ self.options.grammar.as_mut(),+ )?;+ let output_norm = forward_pass_pending.output_norm.map(|norm| {+ let row_bytes = norm.size() / flat_trie.len();+ (norm, row_bytes)+ });+ self.metrics.num_tokens_accepted += full.len();+ self.decoding_state = DecodingState::Accepting {+ full,+ num_accepted: 0,+ hidden_features: forward_pass_pending.hidden_features,+ output_norm,+ capture_span: forward_pass_pending.capture_span,+ };+ return self.generate();+ }+ },+ DecodingState::Accepting {+ full,+ num_accepted,+ hidden_features,+ output_norm,+ capture_span,+ } => {+ let output_token_id = full[num_accepted].2;- self.metrics.num_tokens_returned += 1;+ self.metrics.num_tokens_returned += 1;- if num_accepted < full.len() - 1 {- self.decoding_state = DecodingState::Accepting {- full,- num_accepted: num_accepted + 1,- hidden_features,- output_norm,- capture_span,- };- return Ok(Some(output_token_id));- } else {- let accepted_token_indicies = full.iter().map(|(i, _, _)| *i as u32).collect::<Box<[u32]>>();- let accepted_input_token_ids = full.iter().map(|(_, t, _)| *t).collect::<Box<[u64]>>();- let accepted_output_token_ids = full.iter().map(|(_, _, t)| *t).collect::<Box<[u64]>>();- let mut encoder = Encoder::<B>::new_with_pool_name(- &self.model.engine.context,- self.allocation_pool.clone(),- Some("decode"),- )+ if num_accepted < full.len() - 1 {+ self.decoding_state = DecodingState::Accepting {+ full,+ num_accepted: num_accepted + 1,+ hidden_features,+ output_norm,+ capture_span,+ };+ return Ok(Some(output_token_id));+ } else {+ let accepted_token_indicies = full.iter().map(|(i, _, _)| *i as u32).collect::<Box<[u32]>>();+ let accepted_input_token_ids = full.iter().map(|(_, t, _)| *t).collect::<Box<[u64]>>();+ let accepted_output_token_ids = full.iter().map(|(_, _, t)| *t).collect::<Box<[u64]>>();+ let mut command_buffer = self+ .model+ .engine+ .context+ .create_command_buffer(Some("decode"), Some(self.allocation_pool.clone()))+ .map_err(LanguageModelStreamError::Backend)?;+ self.model_state+ .transformer_state+ .encode_accept(&accepted_token_indicies, &mut command_buffer).map_err(LanguageModelStreamError::Backend)?;- self.model_state- .transformer_state- .encode_accept(&accepted_token_indicies, &mut encoder)+ if let Some(speculator) = self.model.speculator.as_ref() {+ speculator+ .encode_accept(+ self.model_state.speculator_state.as_mut().unwrap(),+ hidden_features.as_ref().unwrap().iter(),+ &accepted_token_indicies,+ &mut command_buffer,+ ).map_err(LanguageModelStreamError::Backend)?;- if let Some(speculator) = self.model.speculator.as_ref() {- speculator- .encode_accept(- self.model_state.speculator_state.as_mut().unwrap(),- hidden_features.as_deref().unwrap(),- &accepted_token_indicies,- &mut encoder,- )- .map_err(LanguageModelStreamError::Backend)?;- }- let output_norm = if let Some((final_hidden, row_bytes)) = output_norm {- let row = full.last().unwrap().0;- let mut norm =- encoder.allocate_scratch(row_bytes).map_err(LanguageModelStreamError::Backend)?;- encoder.encode_copy(&final_hidden, row * row_bytes..(row + 1) * row_bytes, &mut norm, ..);- Some(norm)- } else {- None- };- if let Some(suffix_repetition_length) = self.options.sampling_method.suffix_repetition_length()- {- encoder.push_debug_group("update repetition penalty ring");- let mut accepted_input_token_ids_const = encoder- .allocate_constant(full.len() * DataType::U32.size_in_bytes())- .map_err(LanguageModelStreamError::Backend)?;- accepted_input_token_ids_const.copyin(+ }+ let output_norm = if let Some((final_hidden, row_bytes)) = output_norm {+ let row = full.last().unwrap().0;+ let mut norm =+ command_buffer.allocate_scratch(row_bytes).map_err(LanguageModelStreamError::Backend)?;+ command_buffer+ .encode_copy(final_hidden.subrange(row * row_bytes..(row + 1) * row_bytes), &mut norm);+ Some(norm)+ } else {+ None+ };+ if let Some(suffix_repetition_length) = self.options.sampling_method.suffix_repetition_length() {+ command_buffer.push_debug_group("update repetition penalty ring");+ let accepted_input_token_ids_const = command_buffer+ .allocate_constant_from_slice(&accepted_input_token_ids.iter().map(|token_id| *token_id as u32).collect::<Box<[u32]>>(),- );- self.model.context_ring_update.encode(- &accepted_input_token_ids_const,- self.context_ring.as_mut().unwrap(),- suffix_repetition_length,- full.len() as u32,- &mut encoder,- );- encoder.pop_debug_group();- }- if let Some(capture_span) = capture_span {- encoder- .end_encoding()- .submit()- .wait_until_completed()- .map_err(LanguageModelStreamError::Backend)?;-- drop(capture_span);-- encoder = Encoder::<B>::new_with_pool_name(- &self.model.engine.context,- self.allocation_pool.clone(),- Some("decode"),).map_err(LanguageModelStreamError::Backend)?;- }- self.model_state.tokens.extend(accepted_output_token_ids);- (- ForwardPassChaining::Constant {- token: output_token_id,- output_norm,- },- Some(encoder),- )+ self.model.context_ring_update.encode(+ &accepted_input_token_ids_const,+ self.context_ring.as_mut().unwrap(),+ suffix_repetition_length,+ full.len() as u32,+ &mut command_buffer,+ );+ command_buffer.pop_debug_group();}- },- DecodingState::Halted => return Ok(None),- DecodingState::Invalid => unreachable!(),- };+ if let Some(capture_span) = capture_span {+ command_buffer+ .end_encoding()+ .submit()+ .wait_until_completed()+ .map_err(LanguageModelStreamError::Backend)?;++ drop(capture_span);++ command_buffer = self+ .model+ .engine+ .context+ .create_command_buffer(Some("decode"), Some(self.allocation_pool.clone()))+ .map_err(LanguageModelStreamError::Backend)?;+ }+ self.model_state.tokens.extend(accepted_output_token_ids);+ (+ ForwardPassChaining::Constant {+ token: output_token_id,+ output_norm,+ },+ Some(command_buffer),+ )+ }+ },+ DecodingState::Halted => return Ok(None),+ DecodingState::Invalid => unreachable!(),+ };let context_length = self.model_state.transformer_state.context_length();@@ -569,8 +573,8 @@ impl<'a, B: Backend> LanguageModelStream<'a, B> {#[cfg(grammar)]self.options.grammar.as_mut(),)? {- if let Some(accept_encoder) = encoder.take() {- pending.push(accept_encoder.end_encoding().submit());+ if let Some(accept_command_buffer) = command_buffer.take() {+ pending.push(accept_command_buffer.end_encoding().submit());}let trie = speculator.propose_tree(self.model_state.speculator_state.as_mut().unwrap(),@@ -598,27 +602,36 @@ impl<'a, B: Backend> LanguageModelStream<'a, B> {};let input_flat_trie = input_trie.linearize();- if let Some(accept_encoder) = encoder.take() {- pending.push(accept_encoder.end_encoding().submit());+ if let Some(accept_command_buffer) = command_buffer.take() {+ pending.push(accept_command_buffer.end_encoding().submit());}- self.allocation_pool = Arc::new(self.model.engine.context.create_allocation_pool(false));+ self.allocation_pool = self.model.engine.context.create_allocation_pool();- let mut encoder =- Encoder::<B>::new_with_pool_name(&self.model.engine.context, self.allocation_pool.clone(), Some("decode"))- .map_err(LanguageModelStreamError::Backend)?;+ let mut command_buffer = self+ .model+ .engine+ .context+ .create_command_buffer(Some("decode"), Some(self.allocation_pool.clone()))+ .map_err(LanguageModelStreamError::Backend)?;- let token_ids = if let Some(chain_copy) = chain_copy.as_deref() {- let mut token_ids =- encoder.allocate_scratch(DataType::U32.size_in_bytes()).map_err(LanguageModelStreamError::Backend)?;- encoder.encode_copy(chain_copy, .., &mut token_ids, ..);- token_ids- } else {- let mut token_ids = encoder- .allocate_constant(input_flat_trie.len() * DataType::U32.size_in_bytes())+ let scratch_token_ids;+ let mut constant_token_ids = None;+ let token_ids: &dyn Buffer<Backend = B> = if let Some(chain_copy) = chain_copy.as_deref() {+ let mut token_ids = command_buffer+ .allocate_scratch(DataType::U32.size_in_bytes()).map_err(LanguageModelStreamError::Backend)?;- token_ids.copyin(&input_flat_trie.token_ids().map(|token_id| token_id as u32).collect::<Box<[u32]>>());- token_ids+ command_buffer.encode_copy(chain_copy, &mut token_ids);+ scratch_token_ids = token_ids;+ &scratch_token_ids+ } else {+ constant_token_ids.insert(+ command_buffer+ .allocate_constant_from_slice(+ &input_flat_trie.token_ids().map(|token_id| token_id as u32).collect::<Box<[u32]>>(),+ )+ .map_err(LanguageModelStreamError::Backend)?,+ )};let input_flat_trie_nodes = input_flat_trie.token_subtrie_ranges().collect::<Box<[GpuTrieNode]>>();@@ -633,28 +646,28 @@ impl<'a, B: Backend> LanguageModelStream<'a, B> {self.model.speculator.as_ref().map(|speculator| speculator.hidden_feature_layer_indices());let decoder_output = self.model.decoder.encode(- &token_ids,+ token_ids,&batch_dim,- Some(0..batch_dim.size()),+ Some((0..batch_dim.size()).into()),hidden_feature_layer_indices,&mut self.model_state.transformer_state,- &mut encoder,+ &mut command_buffer,)?;let logits = decoder_output.logits.unwrap();#[cfg(grammar)]- let (bitmask, mut encoder) = if let Some(grammar) = self.options.grammar.as_mut() {+ let (bitmask, mut command_buffer) = if let Some(grammar) = self.options.grammar.as_mut() {if chain_copy.is_some() {- pending.push(encoder.end_encoding().submit());+ pending.push(command_buffer.end_encoding().submit());- let mut encoder = Encoder::<B>::new_with_pool_name(- &self.model.engine.context,- self.allocation_pool.clone(),- Some("decode"),- )- .map_err(LanguageModelStreamError::Backend)?;+ let mut command_buffer = self+ .model+ .engine+ .context+ .create_command_buffer(Some("decode"), Some(self.allocation_pool.clone()))+ .map_err(LanguageModelStreamError::Backend)?;- let mut bitmask = encoder+ let mut bitmask = command_buffer.allocate_constant(self.model.vocab_size.div_ceil(DataType::U32.size_in_bits()) * DataType::U32.size_in_bytes(),)@@ -662,12 +675,12 @@ impl<'a, B: Backend> LanguageModelStream<'a, B> {prev_output.resolve(&mut self.model_state.tokens, Some(grammar))?;if grammar.next_bitmask(bitmask.as_slice_mut()) {- (Some(bitmask), encoder)+ (Some(bitmask), command_buffer)} else {- (None, encoder)+ (None, command_buffer)}} else {- let mut bitmasks = encoder+ let mut bitmasks = command_buffer.allocate_constant(input_flat_trie.len()* self.model.vocab_size.div_ceil(DataType::U32.size_in_bits())@@ -676,23 +689,23 @@ impl<'a, B: Backend> LanguageModelStream<'a, B> {.map_err(LanguageModelStreamError::Backend)?;if input_flat_trie.fill_bitmasks(bitmasks.as_slice_mut(), self.model.vocab_size, grammar) {- (Some(bitmasks), encoder)+ (Some(bitmasks), command_buffer)} else {- (None, encoder)+ (None, command_buffer)}}} else {- (None, encoder)+ (None, command_buffer)};#[cfg(not(grammar))]- let bitmask = None;+ let bitmask = None::<B::ConstantBuffer>;let seeds = if matches!(self.options.sampling_method, SamplingMethod::Stochastic { .. }) {- let mut seeds = encoder- .allocate_constant(input_flat_trie.len() * DataType::U64.size_in_bytes())- .map_err(LanguageModelStreamError::Backend)?;- seeds.copyin(&input_flat_trie.token_seeds().collect::<Box<[u64]>>());- Some(seeds)+ Some(+ command_buffer+ .allocate_constant_from_slice(&input_flat_trie.token_seeds().collect::<Box<[u64]>>())+ .map_err(LanguageModelStreamError::Backend)?,+ )} else {None};@@ -705,11 +718,11 @@ impl<'a, B: Backend> LanguageModelStream<'a, B> {seeds.as_ref(),bitmask.as_ref(),self.context_ring.as_ref(),- Some(&token_ids),+ Some(token_ids),&self.options.sampling_method,&batch_dim,- 0..batch_dim.size(),- &mut encoder,+ (0..batch_dim.size()).into(),+ &mut command_buffer,).map_err(LanguageModelStreamError::Backend)?;@@ -720,7 +733,7 @@ impl<'a, B: Backend> LanguageModelStream<'a, B> {if full_accept {self.model_state.transformer_state- .encode_accept(&(0..batch_dim.size()).collect::<Box<[u32]>>(), &mut encoder)+ .encode_accept(&(0..batch_dim.size()).collect::<Box<[u32]>>(), &mut command_buffer).map_err(LanguageModelStreamError::Backend)?;if let Some(speculator) = self.model.speculator.as_ref() {@@ -728,27 +741,26 @@ impl<'a, B: Backend> LanguageModelStream<'a, B> {speculator.encode_accept(speculator_state,- decoder_output.hidden_features.as_ref().unwrap(),+ decoder_output.hidden_features.as_ref().unwrap().iter(),&(0..batch_dim.size()).collect::<Box<[u32]>>(),- &mut encoder,+ &mut command_buffer,).map_err(LanguageModelStreamError::Backend)?;}if let Some(suffix_repetition_length) = self.options.sampling_method.suffix_repetition_length() {self.model.context_ring_update.encode(- &token_ids,+ token_ids,self.context_ring.as_mut().unwrap(),suffix_repetition_length,batch_dim.size(),- &mut encoder,+ &mut command_buffer,);}}- drop(token_ids);-- pending.push(encoder.end_encoding().submit());+ drop(constant_token_ids);+ pending.push(command_buffer.end_encoding().submit());self.metrics.num_decode_forward_passes += 1;self.metrics.num_tokens_proposed += input_flat_trie.len();@@ -807,24 +819,24 @@ impl<'a, B: Backend> Drop for LanguageModelStream<'a, B> {}if !in_flight.full_accept {- let mut encoder = Encoder::<B>::new_with_pool_name(- &self.model.engine.context,- self.allocation_pool.clone(),- Some("drop accept"),- )- .unwrap();- self.model_state.transformer_state.encode_accept(&[0], &mut encoder).unwrap();+ let mut command_buffer = self+ .model+ .engine+ .context+ .create_command_buffer(Some("drop accept"), Some(self.allocation_pool.clone()))+ .unwrap();+ self.model_state.transformer_state.encode_accept(&[0], &mut command_buffer).unwrap();if let Some(speculator) = self.model.speculator.as_ref() {speculator.encode_accept(self.model_state.speculator_state.as_mut().unwrap(),- in_flight.hidden_features.as_deref().unwrap(),+ in_flight.hidden_features.as_ref().unwrap().iter(),&[0],- &mut encoder,+ &mut command_buffer,).unwrap();}- encoder.end_encoding().submit().wait_until_completed().unwrap();+ command_buffer.end_encoding().submit().wait_until_completed().unwrap();}Some(in_flight.output_tokens.as_slice::<u32>()[0] as u64)@@ -838,26 +850,29 @@ impl<'a, B: Backend> Drop for LanguageModelStream<'a, B> {} => {assert!(num_accepted > 0 && num_accepted < full.len());- let mut encoder = Encoder::<B>::new_with_pool_name(- &self.model.engine.context,- self.allocation_pool.clone(),- Some("drop accept"),- )- .unwrap();+ let mut command_buffer = self+ .model+ .engine+ .context+ .create_command_buffer(Some("drop accept"), Some(self.allocation_pool.clone()))+ .unwrap();let accepted_token_indicies =full.iter().take(num_accepted + 1).map(|(i, _, _)| *i as u32).collect::<Box<[u32]>>();- self.model_state.transformer_state.encode_accept(&accepted_token_indicies, &mut encoder).unwrap();+ self.model_state+ .transformer_state+ .encode_accept(&accepted_token_indicies, &mut command_buffer)+ .unwrap();if let Some(speculator) = self.model.speculator.as_ref() {speculator.encode_accept(self.model_state.speculator_state.as_mut().unwrap(),- hidden_features.as_deref().unwrap(),+ hidden_features.as_ref().unwrap().iter(),&accepted_token_indicies,- &mut encoder,+ &mut command_buffer,).unwrap();}- encoder.end_encoding().submit().wait_until_completed().unwrap();+ command_buffer.end_encoding().submit().wait_until_completed().unwrap();drop(capture_span);diff --git a/crates/uzu-engine/src/parameters/loader.rs b/crates/uzu-engine/src/parameters/loader.rsindex 4de6a3190..4c6a54e8d 100644--- a/crates/uzu-engine/src/parameters/loader.rs+++ b/crates/uzu-engine/src/parameters/loader.rs@@ -14,7 +14,7 @@ use super::{};use crate::{array::{ArrayElement, size_for_shape},- backends::common::{Allocation, AllocationType, Backend, Context},+ backends::common::{Backend, BufferMut, Context},data_type::DataType,utils::strict_serde::DeserializeStrictOwned,};@@ -133,14 +133,11 @@ impl<'a, 'leaf, B: Backend> ParameterLeaf<'a, 'leaf, B, true> {Ok(data.into_boxed_slice())}- pub fn read_allocation(&self) -> Result<Allocation<B>, ParameterLoaderError<B>> {- let mut allocation = self- .loader- .context- .create_allocation(self.metadata.size, AllocationType::Global)- .map_err(ParameterLoaderError::BackendError)?;- self.loader.file.read_exact_at(allocation.as_slice_mut(), self.metadata.offset as u64)?;- Ok(allocation)+ pub fn read_buffer(&self) -> Result<B::GlobalBuffer, ParameterLoaderError<B>> {+ let mut buffer =+ self.loader.context.create_buffer(self.metadata.size).map_err(ParameterLoaderError::BackendError)?;+ self.loader.file.read_exact_at(buffer.as_slice_mut::<u8>(), self.metadata.offset as u64)?;+ Ok(buffer)}}diff --git a/crates/uzu-engine/src/speculators/dflash_tfm.rs b/crates/uzu-engine/src/speculators/dflash_tfm.rsindex 49bf3aa72..a836ac1d3 100644--- a/crates/uzu-engine/src/speculators/dflash_tfm.rs+++ b/crates/uzu-engine/src/speculators/dflash_tfm.rs@@ -14,7 +14,8 @@ pub use crate::encodable_block::dflash::DFlashState;use crate::engine::language_model::grammar::Grammar;use crate::{backends::common::{- Allocation, AllocationPool, Backend, Context, Encoder, gpu_types::trie::TrieNode as GpuTrieNode,+ Backend, BufferRef, CommandBuffer, CommandBufferEncoding, CommandBufferExecutable, CommandBufferPending,+ Context, gpu_types::trie::TrieNode as GpuTrieNode,},config::speculator::{AnySpeculatorConfig, dflash::DFlashSpeculatorConfig, model::SpeculatorModelConfig},data_type::DataType,@@ -162,11 +163,11 @@ impl<B: Backend> DFlashTfmSpeculator<B> {pub fn encode_accept(&self,state: &mut DFlashState<B>,- target_features: &[Allocation<B>],+ target_features: impl ExactSizeIterator<Item = impl BufferRef<Backend = B>>,accepted_indices: &[u32],- encoder: &mut Encoder<B>,+ command_buffer: &mut <B::CommandBuffer as CommandBuffer>::Encoding,) -> Result<(), B::Error> {- self.dflash.encode_accept(state, target_features, accepted_indices, encoder)+ self.dflash.encode_accept(state, target_features, accepted_indices, command_buffer)}pub fn make_shape(@@ -208,13 +209,13 @@ impl<B: Backend> DFlashTfmSpeculator<B> {pub fn propose_tree(&self,state: &mut DFlashState<B>,- target_output_norm: &Allocation<B>,+ target_output_norm: impl BufferRef<Backend = B>,target_output_token: u32,target_embedding: &Embedding<B>,shape: DFlashTfmTreeShape,#[cfg(grammar)] grammar: Option<&mut Grammar>,prng: &PRng,- allocation_pool: Arc<AllocationPool<B>>,+ allocation_pool: Arc<B::AllocationPool>,) -> Result<TrieNode, DFlashTreeError<B>> {assert!(shape.tree_budget >= 2, "tree budget needs at least a root and one draft token");@@ -228,7 +229,9 @@ impl<B: Backend> DFlashTfmSpeculator<B> {let root_position = state.context_length();- let mut encoder = Encoder::new_with_pool_name(&*self.context, allocation_pool, Some("speculator propose"))+ let mut command_buffer = self+ .context+ .create_command_buffer(Some("speculator propose"), Some(allocation_pool)).map_err(DFlashTreeError::Backend)?;let nodes = match shape.construction_method {@@ -254,7 +257,7 @@ impl<B: Backend> DFlashTfmSpeculator<B> {target_output_token,target_embedding,dflash_depth,- &mut encoder,+ &mut command_buffer,)?;let topology_nodes = (0..chain_length).map(|index| GpuTrieNode {@@ -268,18 +271,18 @@ impl<B: Backend> DFlashTfmSpeculator<B> {.sampling.encode(&dflash_output.logits,- None,- None,- None,- None,+ None::<&B::ConstantBuffer>,+ None::<&B::ConstantBuffer>,+ None::<&B::GlobalBuffer>,+ None::<&B::ConstantBuffer>,&SamplingMethod::Greedy,&batch_topology,- 0..chain_length,- &mut encoder,+ (0..chain_length).into(),+ &mut command_buffer,).map_err(DFlashTreeError::Backend)?;let completed =- encoder.end_encoding().submit().wait_until_completed().map_err(DFlashTreeError::Backend)?;+ command_buffer.end_encoding().submit().wait_until_completed().map_err(DFlashTreeError::Backend)?;let tokens = sampled.copyout::<u32>();drop(completed);nodes.extend(tokens.into_iter().zip(1u32..).map(|(token_id, depth)| ProposalNode {@@ -330,7 +333,7 @@ impl<B: Backend> DFlashTfmSpeculator<B> {target_output_token,target_embedding,dflash_depth,- &mut encoder,+ &mut command_buffer,)?;let depth_seeds = (0..weaver.max_depth()).map(|depth| prng.derive(root_position as u64 + depth as u64))@@ -351,10 +354,10 @@ impl<B: Backend> DFlashTfmSpeculator<B> {expand_width,prune_noise_scale: prune_sigma.map(f32::recip),},- &mut encoder,+ &mut command_buffer,)?;let completed =- encoder.end_encoding().submit().wait_until_completed().map_err(DFlashTreeError::Backend)?;+ command_buffer.end_encoding().submit().wait_until_completed().map_err(DFlashTreeError::Backend)?;let nodes = tree.read_nodes();drop(completed);nodesdiff --git a/crates/uzu-engine/src/utils/downcast.rs b/crates/uzu-engine/src/utils/downcast.rsnew file mode 100644index 000000000..11fbc0441--- /dev/null+++ b/crates/uzu-engine/src/utils/downcast.rs@@ -0,0 +1,10 @@+use std::any::{Any, TypeId};++#[inline]+pub fn downcast_ref<U: Any>(value: &(impl Any + ?Sized)) -> Option<&U> {+ if Any::type_id(value) == TypeId::of::<U>() {+ Some(unsafe { &*std::ptr::from_ref(value).cast::<U>() })+ } else {+ None+ }+}diff --git a/crates/uzu-engine/src/utils/mod.rs b/crates/uzu-engine/src/utils/mod.rsindex 400fdec78..11e88e2c5 100644--- a/crates/uzu-engine/src/utils/mod.rs+++ b/crates/uzu-engine/src/utils/mod.rs@@ -1,4 +1,5 @@pub mod dispatch_dtype;+pub mod downcast;pub mod maybe_mut;#[cfg(backend = "cpu")]pub mod pointers;diff --git a/crates/uzu-engine/unit/backends/common/allocator/allocator.rs b/crates/uzu-engine/unit/backends/common/allocator/allocator.rsdeleted file mode 100644index 2f20530da..000000000--- a/crates/uzu-engine/unit/backends/common/allocator/allocator.rs+++ /dev/null@@ -1,147 +0,0 @@-use std::{- collections::{HashMap, hash_map::Entry},- fs::File,- io::BufReader,- sync::Arc,- time::Instant,-};--use serde::{Deserialize, Serialize};-use uzu_engine_macros::uzu_test;--use crate::backends::{- common::{- Allocation, AllocationPool, AllocationType, Allocator, AsBufferRangeMut, AsBufferRangeRef, Backend,- BufferArgMut, Context,- },- metal::Metal,-};--#[derive(Serialize, Deserialize)]-struct TraceEvent {- allocator_id: usize,- event_type: TraceEventType,-}--#[derive(Serialize, Deserialize)]-pub enum TraceEventAllocationType {- Global,- Pooled {- pool_id: usize,- cpu_available: bool,- },-}--#[derive(Serialize, Deserialize)]-enum TraceEventType {- Create,- CreatePool {- reusable: bool,- pool_id: usize,- },- Allocate {- size: usize,- allocation_type: TraceEventAllocationType,- allocation_id: usize,- },- Free {- allocation_id: usize,- },- FreePool {- pool_id: usize,- },-}--#[uzu_test]-#[ignore]-fn bench_allocator_generation_trace() {- let file = BufReader::with_capacity(1 << 20, File::open("/tmp/allocator_trace.jsonl").unwrap());- let events: Vec<TraceEvent> = serde_json::Deserializer::from_reader(file)- .into_iter::<TraceEvent>()- .map(|r| r.expect("malformed trace event"))- .collect();-- let context = <<Metal as Backend>::Context as Context>::new().unwrap();-- let mut allocators: HashMap<usize, Arc<Allocator<Metal>>> = HashMap::new();- let mut pools: HashMap<(usize, usize), AllocationPool<Metal>> = HashMap::new();- let mut allocations: HashMap<(usize, usize), Allocation<Metal>> = HashMap::new();-- let start = Instant::now();-- for event in events {- match event.event_type {- TraceEventType::Create => {- let Entry::Vacant(vacant) = allocators.entry(event.allocator_id) else {- panic!("Duplicate allocator id: {}", event.allocator_id);- };-- vacant.insert(Allocator::new(Arc::downgrade(&context)));- },- TraceEventType::CreatePool {- reusable,- pool_id,- } => {- let Entry::Vacant(vacant) = pools.entry((event.allocator_id, pool_id)) else {- panic!("Duplicate pool id {} in allocator {}", pool_id, event.allocator_id);- };-- vacant.insert(allocators[&event.allocator_id].create_pool(reusable));- },- TraceEventType::Allocate {- size,- allocation_type,- allocation_id,- } => {- let Entry::Vacant(vacant) = allocations.entry((event.allocator_id, allocation_id)) else {- panic!("Duplicate allocation id {} in allocator {}", allocation_id, event.allocator_id);- };-- let allocation_type = match allocation_type {- TraceEventAllocationType::Global => AllocationType::Global,- TraceEventAllocationType::Pooled {- pool_id,- cpu_available,- } => AllocationType::Pooled {- pool: &pools[&(event.allocator_id, pool_id)],- cpu_available,- },- };-- vacant.insert(allocators[&event.allocator_id].allocate(size, allocation_type).unwrap());- },- TraceEventType::Free {- allocation_id,- } => {- allocations.remove(&(event.allocator_id, allocation_id)).unwrap();- },- TraceEventType::FreePool {- pool_id,- } => {- pools.remove(&(event.allocator_id, pool_id)).unwrap();- },- }- }-- let elapsed = start.elapsed();-- eprintln!();- eprintln!("--------------------");- eprintln!("Cpu time: {} ms", elapsed.as_millis());- eprintln!("--------------------");-}--#[uzu_test]-#[ignore]-fn allocation_split_at_mut_returns_disjoint_buffer_arguments() {- let context = <<Metal as Backend>::Context as Context>::new().unwrap();- let mut allocation = context.create_allocation(64, AllocationType::Global).unwrap();- let allocation_range = allocation.as_buffer_range_ref().range();-- let (head, tail) = allocation.as_buffer_range_mut().split_at(24);- let (_, head_offset, head_length) = BufferArgMut::<'_, Metal>::into_parts(head);- let (_, tail_offset, tail_length) = BufferArgMut::<'_, Metal>::into_parts(tail);-- assert_eq!((head_offset, head_length), (allocation_range.start, 24));- assert_eq!((tail_offset, tail_length), (allocation_range.start + 24, 40));-}diff --git a/crates/uzu-engine/unit/backends/common/hazard_tracker_test.rs b/crates/uzu-engine/unit/backends/common/hazard_tracker_test.rsdeleted file mode 100644index 8a5312722..000000000--- a/crates/uzu-engine/unit/backends/common/hazard_tracker_test.rs+++ /dev/null@@ -1,48 +0,0 @@-use uzu_engine_macros::uzu_test;--use super::*;--#[uzu_test]-fn test_hazard_tracker_simple_compute_sequence() {- let mut ht = HazardTracker::new();-- // RAR is fine (many readers don't interfere with each other)- for _ in 0..123 {- assert_eq!(- ht.access(&[Access {- range: 0..16,- flags: AccessFlags::compute_read()- }]),- None- );- }-- // WAR causes barrier after reads before writes (to ensure that the reads are done before writes can rewrite the data)- assert_eq!(- ht.access(&[Access {- range: 0..16,- flags: AccessFlags::compute_write()- }]),- Some((AccessFlags::compute_read(), AccessFlags::compute_write()))- );-- // WAW causes barrier after writes before writes (to ensure the last write wins)- for _ in 0..123 {- assert_eq!(- ht.access(&[Access {- range: 0..16,- flags: AccessFlags::compute_write()- }]),- Some((AccessFlags::compute_write(), AccessFlags::compute_write()))- );- }-- // RAW causes barrier after writes before reads (to ensure that writes wrote the data before reads read it)- assert_eq!(- ht.access(&[Access {- range: 0..16,- flags: AccessFlags::compute_read()- }]),- Some((AccessFlags::compute_write(), AccessFlags::compute_read()))- );-}diff --git a/crates/uzu-engine/unit/backends/common/kernel/activation_test.rs b/crates/uzu-engine/unit/backends/common/kernel/activation_test.rsindex d18182b42..9d940407d 100644--- a/crates/uzu-engine/unit/backends/common/kernel/activation_test.rs+++ b/crates/uzu-engine/unit/backends/common/kernel/activation_test.rs@@ -7,13 +7,16 @@ use uzu_engine_macros::uzu_test;use crate::{array::ArrayElement,backends::{- common::{Allocation, Backend, Context, Encoder, Kernels, gpu_types::ActivationType, kernel::ActivationKernel},+ common::{+ Backend, CommandBufferEncoding, CommandBufferExecutable, CommandBufferPending, Context, Kernels,+ gpu_types::ActivationType, kernel::ActivationKernel,+ },cpu::Cpu,},data_type::DataType,tests::{assert::assert_eq_float,- helpers::{alloc_allocation, alloc_allocation_with_data, allocation_to_vec, for_each_non_cpu_backend},+ helpers::{buffer_to_vec, create_buffer, create_buffer_with_data, for_each_non_cpu_backend},},};@@ -40,18 +43,18 @@ fn get_output<T: ArrayElement + Float, B: Backend>(input: &Input<T>) -> Vec<T> {let n = input.data.len();if input.in_place {- let mut output_allocation = alloc_allocation_with_data::<B, T>(&context, &input.data);- let mut encoder = Encoder::new(context.as_ref()).expect("Failed to get encoder");- kernel.encode(None::<&Allocation<B>>, &mut output_allocation, n as u32, input.act_type, &mut encoder);- encoder.end_encoding().submit().wait_until_completed().unwrap();- allocation_to_vec::<B, T>(&output_allocation)+ let mut output_buffer = create_buffer_with_data::<B, T>(&context, &input.data);+ let mut command_buffer = context.create_command_buffer(None, None).expect("Failed to get command buffer");+ kernel.encode(None::<&B::GlobalBuffer>, &mut output_buffer, n as u32, input.act_type, &mut command_buffer);+ command_buffer.end_encoding().submit().wait_until_completed().unwrap();+ buffer_to_vec::<B, T>(&output_buffer)} else {- let input_allocation = alloc_allocation_with_data::<B, T>(&context, &input.data);- let mut output_allocation = alloc_allocation::<B, T>(&context, n);- let mut encoder = Encoder::new(context.as_ref()).expect("Failed to get encoder");- kernel.encode(Some(&input_allocation), &mut output_allocation, n as u32, input.act_type, &mut encoder);- encoder.end_encoding().submit().wait_until_completed().unwrap();- allocation_to_vec::<B, T>(&output_allocation)+ let input_buffer = create_buffer_with_data::<B, T>(&context, &input.data);+ let mut output_buffer = create_buffer::<B, T>(&context, n);+ let mut command_buffer = context.create_command_buffer(None, None).expect("Failed to get command buffer");+ kernel.encode(Some(&input_buffer), &mut output_buffer, n as u32, input.act_type, &mut command_buffer);+ command_buffer.end_encoding().submit().wait_until_completed().unwrap();+ buffer_to_vec::<B, T>(&output_buffer)}}diff --git a/crates/uzu-engine/unit/backends/common/kernel/activation_transform_test.rs b/crates/uzu-engine/unit/backends/common/kernel/activation_transform_test.rsindex 0c0aad447..f56d0836c 100644--- a/crates/uzu-engine/unit/backends/common/kernel/activation_transform_test.rs+++ b/crates/uzu-engine/unit/backends/common/kernel/activation_transform_test.rs@@ -8,12 +8,12 @@ use crate::{array::ArrayElement,backends::{common::{- Backend, Context, Encoder, gpu_types::HADAMARD_TRANSFORM_BLOCK_SIZE as BLOCK_SIZE,- kernel::ActivationTransform,+ Backend, CommandBufferEncoding, CommandBufferExecutable, CommandBufferPending, Context,+ gpu_types::HADAMARD_TRANSFORM_BLOCK_SIZE as BLOCK_SIZE, kernel::ActivationTransform,},cpu::Cpu,},- tests::helpers::{alloc_allocation, alloc_allocation_with_data, allocation_to_vec, for_each_backend},+ tests::helpers::{buffer_to_vec, create_buffer, create_buffer_with_data, for_each_backend},};#[derive(Clone, Copy, Debug)]@@ -38,21 +38,21 @@ fn run<T: ArrayElement + Float + Debug, B: Backend>(}.expect("activation transform");- let mut input = alloc_allocation_with_data::<B, T>(context.as_ref(), data);- let mut output = alloc_allocation::<B, T>(context.as_ref(), data.len());- let factors = alloc_allocation_with_data::<B, i32>(context.as_ref(), factors);+ let mut input = create_buffer_with_data::<B, T>(context.as_ref(), data);+ let mut output = create_buffer::<B, T>(context.as_ref(), data.len());+ let factors = create_buffer_with_data::<B, i32>(context.as_ref(), factors);let batch_count = (data.len() / channel_count) as u32;- let mut encoder = Encoder::new(context.as_ref()).expect("encoder");+ let mut command_buffer = context.create_command_buffer(None, None).expect("command buffer");if in_place {- kernel.encode_fp_in_place(&mut input, &factors, None, batch_count, channel_count as u32, &mut encoder);+ kernel.encode_fp_in_place(&mut input, &factors, None, batch_count, channel_count as u32, &mut command_buffer);} else {- kernel.encode_fp(&input, &mut output, &factors, batch_count, channel_count as u32, &mut encoder);+ kernel.encode_fp(&input, &mut output, &factors, batch_count, channel_count as u32, &mut command_buffer);}- encoder.end_encoding().submit().wait_until_completed().unwrap();+ command_buffer.end_encoding().submit().wait_until_completed().unwrap();if !in_place {- assert_eq!(allocation_to_vec::<B, T>(&input), data);+ assert_eq!(buffer_to_vec::<B, T>(&input), data);}- allocation_to_vec(if in_place {+ buffer_to_vec(if in_place {&input} else {&output@@ -129,20 +129,21 @@ fn output_rht_fused_bias_matches_separate_mixed_dtype() {.enumerate().map(|(i, value)| bf16::from_f32(value.to_f32() + bias_data[i % channels])).collect();- let mut fused = alloc_allocation_with_data::<B, bf16>(context.as_ref(), &data);- let bias = alloc_allocation_with_data::<B, f32>(context.as_ref(), &bias_data);- let factors = alloc_allocation_with_data::<B, i32>(context.as_ref(), &factors_data);+ let mut fused = create_buffer_with_data::<B, bf16>(context.as_ref(), &data);+ let bias = create_buffer_with_data::<B, f32>(context.as_ref(), &bias_data);+ let factors = create_buffer_with_data::<B, i32>(context.as_ref(), &factors_data);- let mut encoder = Encoder::new(context.as_ref()).expect("encoder");- ActivationTransform::output_rht(context.as_ref(), bf16::data_type(), Some(f32::data_type()), true)+ let mut command_buffer = context.create_command_buffer(None, None).expect("command buffer");+ ActivationTransform::<B>::output_rht(context.as_ref(), bf16::data_type(), Some(f32::data_type()), true).expect("fused transform")- .encode_fp_in_place(&mut fused, &factors, Some(&bias), 2, channels as u32, &mut encoder);- encoder.end_encoding().submit().wait_until_completed().unwrap();- assert_eq!(allocation_to_vec::<B, bf16>(&fused), expected);+ .encode_fp_in_place(&mut fused, &factors, Some(&bias), 2, channels as u32, &mut command_buffer);+ command_buffer.end_encoding().submit().wait_until_completed().unwrap();+ assert_eq!(buffer_to_vec::<B, bf16>(&fused), expected);});}mod quantize {+use rand::{RngExt, SeedableRng, rngs::SmallRng};use uzu_engine_macros::uzu_test;@@ -150,13 +151,13 @@ mod quantize {use crate::{backends::{common::{- Backend, Context, Encoder,+ Backend, CommandBufferEncoding, CommandBufferExecutable, CommandBufferPending, Context,kernel::{ActivationQuantization, ActivationTransform, matmul::Int8CodeLayout},},cpu::Cpu,},data_type::DataType,- tests::helpers::{alloc_allocation, alloc_allocation_with_data, allocation_to_vec, for_each_backend},+ tests::helpers::{buffer_to_vec, create_buffer, create_buffer_with_data, for_each_backend},};fn run<B: Backend>(@@ -172,13 +173,13 @@ mod quantize {let scale_groups = columns / scale_group_size;let sum_groups = sum_group_size.map_or(0, |group_size| columns / group_size);let context = B::Context::new().expect("context");- let input = alloc_allocation_with_data::<B, f32>(context.as_ref(), input_data);- let factors = alloc_allocation_with_data::<B, i32>(context.as_ref(), factors_data);- let mut values = alloc_allocation::<B, i8>(context.as_ref(), (rows * columns) as usize);- let mut scales = alloc_allocation::<B, f32>(context.as_ref(), (rows * scale_groups) as usize);+ let input = create_buffer_with_data::<B, f32>(context.as_ref(), input_data);+ let factors = create_buffer_with_data::<B, i32>(context.as_ref(), factors_data);+ let mut values = create_buffer::<B, i8>(context.as_ref(), (rows * columns) as usize);+ let mut scales = create_buffer::<B, f32>(context.as_ref(), (rows * scale_groups) as usize);let mut group_sums =- emit_group_sums.then(|| alloc_allocation::<B, i32>(context.as_ref(), (rows * sum_groups) as usize));- let kernel = ActivationTransform::quantize(+ emit_group_sums.then(|| create_buffer::<B, i32>(context.as_ref(), (rows * sum_groups) as usize));+ let kernel = ActivationTransform::<B>::quantize(context.as_ref(),DataType::F32,ActivationQuantization::new(@@ -190,7 +191,7 @@ mod quantize {.expect("supported activation quantization"),).expect("quantize transform");- let mut encoder = Encoder::<B>::new(context.as_ref()).expect("encoder");+ let mut command_buffer = context.as_ref().create_command_buffer(None, None).expect("command buffer");kernel.encode_quantize(&input,&mut values,@@ -199,11 +200,11 @@ mod quantize {&factors,rows,columns,- &mut encoder,+ &mut command_buffer,);- encoder.end_encoding().submit().wait_until_completed().unwrap();+ command_buffer.end_encoding().submit().wait_until_completed().unwrap();- (allocation_to_vec(&values), allocation_to_vec(&scales), group_sums.as_ref().map(allocation_to_vec))+ (buffer_to_vec(&values), buffer_to_vec(&scales), group_sums.as_ref().map(buffer_to_vec))}fn check_quantize(diff --git a/crates/uzu-engine/unit/backends/common/kernel/attention/ancestor_attention_test.rs b/crates/uzu-engine/unit/backends/common/kernel/attention/ancestor_attention_test.rsindex 704ab57c3..e7090f98f 100644--- a/crates/uzu-engine/unit/backends/common/kernel/attention/ancestor_attention_test.rs+++ b/crates/uzu-engine/unit/backends/common/kernel/attention/ancestor_attention_test.rs@@ -8,14 +8,15 @@ use uzu_engine_macros::uzu_test;use crate::{backends::{common::{- Allocation, Backend, Encoder, Kernels, gpu_types::weaver::MetadataIdx, kernel::AncestorAttentionKernel,+ Backend, CommandBufferCompleted, CommandBufferEncoding, CommandBufferExecutable, CommandBufferPending,+ Context, Kernels, gpu_types::weaver::MetadataIdx, kernel::AncestorAttentionKernel,},cpu::Cpu,metal::Metal,},tests::{assert::assert_eq_float,- helpers::{alloc_allocation, alloc_allocation_with_data, allocation_to_vec, create_context},+ helpers::{buffer_to_vec, create_buffer, create_buffer_with_data, create_context},},};@@ -26,16 +27,16 @@ const MAX_DEPTH: u32 = 8;struct Runner<B: Backend> {context: Arc<B::Context>,kernel: <B::Kernels as Kernels>::AncestorAttentionKernel,- prefix_kv: Allocation<B>,- node_kv: Allocation<B>,- current_qkv: Allocation<B>,- cosines: Allocation<B>,- sines: Allocation<B>,- node_metadata: Allocation<B>,- ancestor_indices: Allocation<B>,- ancestor_counts: Allocation<B>,- node_indices: Allocation<B>,- output: Allocation<B>,+ prefix_kv: B::GlobalBuffer,+ node_kv: B::GlobalBuffer,+ current_qkv: B::GlobalBuffer,+ cosines: B::GlobalBuffer,+ sines: B::GlobalBuffer,+ node_metadata: B::GlobalBuffer,+ ancestor_indices: B::GlobalBuffer,+ ancestor_counts: B::GlobalBuffer,+ node_indices: B::GlobalBuffer,+ output: B::GlobalBuffer,rows: u32,prefix_length: u32,ancestor_stride: u32,@@ -92,16 +93,16 @@ impl<B: Backend> Runner<B> {<B::Kernels as Kernels>::AncestorAttentionKernel::new(context.as_ref(), HEAD_DIM as u32, NUM_HEADS).unwrap();Self {- prefix_kv: alloc_allocation_with_data::<B, bf16>(&context, &values(prefix_length * kv_width, 0)),- node_kv: alloc_allocation_with_data::<B, bf16>(&context, &values(nodes * kv_width, 11)),- current_qkv: alloc_allocation_with_data::<B, bf16>(&context, &values(rows * qkv_width, 29)),- cosines: alloc_allocation_with_data::<B, f32>(&context, &cosines),- sines: alloc_allocation_with_data::<B, f32>(&context, &sines),- node_metadata: alloc_allocation_with_data::<B, u32>(&context, &node_metadata),- ancestor_indices: alloc_allocation_with_data::<B, u32>(&context, &ancestor_indices),- ancestor_counts: alloc_allocation_with_data::<B, u32>(&context, &ancestor_counts),- node_indices: alloc_allocation_with_data::<B, u32>(&context, &node_indices),- output: alloc_allocation::<B, bf16>(&context, rows * NUM_HEADS as usize * HEAD_DIM),+ prefix_kv: create_buffer_with_data::<B, bf16>(&context, &values(prefix_length * kv_width, 0)),+ node_kv: create_buffer_with_data::<B, bf16>(&context, &values(nodes * kv_width, 11)),+ current_qkv: create_buffer_with_data::<B, bf16>(&context, &values(rows * qkv_width, 29)),+ cosines: create_buffer_with_data::<B, f32>(&context, &cosines),+ sines: create_buffer_with_data::<B, f32>(&context, &sines),+ node_metadata: create_buffer_with_data::<B, u32>(&context, &node_metadata),+ ancestor_indices: create_buffer_with_data::<B, u32>(&context, &ancestor_indices),+ ancestor_counts: create_buffer_with_data::<B, u32>(&context, &ancestor_counts),+ node_indices: create_buffer_with_data::<B, u32>(&context, &node_indices),+ output: create_buffer::<B, bf16>(&context, rows * NUM_HEADS as usize * HEAD_DIM),context,kernel,rows: rows as u32,@@ -115,7 +116,7 @@ impl<B: Backend> Runner<B> {&mut self,repetitions: u32,) -> Duration {- let mut encoder = Encoder::new(self.context.as_ref()).unwrap();+ let mut command_buffer = self.context.create_command_buffer(None, None).unwrap();for _ in 0..repetitions {self.kernel.encode(&self.prefix_kv,@@ -134,10 +135,10 @@ impl<B: Backend> Runner<B> {self.node_capacity,MAX_DEPTH,1.0 / (HEAD_DIM as f32).sqrt(),- &mut encoder,+ &mut command_buffer,);}- encoder.end_encoding().submit().wait_until_completed().unwrap().gpu_execution_time()+ command_buffer.end_encoding().submit().wait_until_completed().unwrap().gpu_execution_time()}}@@ -145,13 +146,13 @@ impl<B: Backend> Runner<B> {fn ancestor_attention_matches_cpu() {let mut cpu = Runner::<Cpu>::new(4, 5, 3, 16);cpu.encode(1);- let expected_output = allocation_to_vec::<Cpu, bf16>(&cpu.output);- let expected_node_kv = allocation_to_vec::<Cpu, bf16>(&cpu.node_kv);+ let expected_output = buffer_to_vec::<Cpu, bf16>(&cpu.output);+ let expected_node_kv = buffer_to_vec::<Cpu, bf16>(&cpu.node_kv);let mut metal = Runner::<Metal>::new(4, 5, 3, 16);metal.encode(1);- let actual_output = allocation_to_vec::<Metal, bf16>(&metal.output);- let actual_node_kv = allocation_to_vec::<Metal, bf16>(&metal.node_kv);+ let actual_output = buffer_to_vec::<Metal, bf16>(&metal.output);+ let actual_node_kv = buffer_to_vec::<Metal, bf16>(&metal.node_kv);assert_eq_float(&expected_output, &actual_output, 0.02, "AncestorAttention output");assert_eq!(actual_node_kv, expected_node_kv);diff --git a/crates/uzu-engine/unit/backends/common/kernel/attention/attention_prepare_test.rs b/crates/uzu-engine/unit/backends/common/kernel/attention/attention_prepare_test.rsindex ea27e944c..1f1bd14ff 100644--- a/crates/uzu-engine/unit/backends/common/kernel/attention/attention_prepare_test.rs+++ b/crates/uzu-engine/unit/backends/common/kernel/attention/attention_prepare_test.rs@@ -3,11 +3,14 @@ use uzu_engine_macros::uzu_test;use crate::{backends::{- common::{Allocation, Backend, Context, Encoder, Kernels, kernel::AttentionPrepareKernel},+ common::{+ Backend, CommandBufferEncoding, CommandBufferExecutable, CommandBufferPending, Context, Kernels,+ kernel::AttentionPrepareKernel,+ },cpu::Cpu,},data_type::DataType,- tests::helpers::{alloc_allocation, alloc_allocation_with_data, allocation_to_vec, for_each_non_cpu_backend},+ tests::helpers::{buffer_to_vec, create_buffer, create_buffer_with_data, for_each_non_cpu_backend},};struct Output {@@ -31,19 +34,19 @@ fn run<B: Backend>() -> Output {18.0, 111.0, 112.0, 113.0, 114.0,].map(bf16::from_f32);- let qkvg = alloc_allocation_with_data::<B, bf16>(&context, &qkvg);- let mut queries = alloc_allocation::<B, bf16>(&context, 8);- let mut keys = alloc_allocation::<B, bf16>(&context, 4);- let mut values = alloc_allocation::<B, bf16>(&context, 4);- let mut encoder = Encoder::new(context.as_ref()).expect("Failed to create encoder");+ let qkvg = create_buffer_with_data::<B, bf16>(&context, &qkvg);+ let mut queries = create_buffer::<B, bf16>(&context, 8);+ let mut keys = create_buffer::<B, bf16>(&context, 4);+ let mut values = create_buffer::<B, bf16>(&context, 4);+ let mut command_buffer = context.create_command_buffer(None, None).expect("Failed to create command buffer");kernel.encode(&qkvg,&mut queries,Some(&mut keys),Some(&mut values),- None::<&Allocation<B>>,- None::<&Allocation<B>>,+ None::<&B::GlobalBuffer>,+ None::<&B::GlobalBuffer>,2,Some(1),2,@@ -51,14 +54,14 @@ fn run<B: Backend>() -> Output {Some(0),12,2,- &mut encoder,+ &mut command_buffer,);- encoder.end_encoding().submit().wait_until_completed().expect("Failed to wait command buffer");+ command_buffer.end_encoding().submit().wait_until_completed().expect("Failed to wait command buffer");Output {- queries: allocation_to_vec(&queries),- keys: allocation_to_vec(&keys),- values: allocation_to_vec(&values),+ queries: buffer_to_vec(&queries),+ keys: buffer_to_vec(&keys),+ values: buffer_to_vec(&values),}}@@ -87,17 +90,17 @@ fn run_query_only<B: Backend>() -> Vec<bf16> {.expect("Failed to create AttentionPrepareKernel");let qg = [1.0, 2.0, 3.0, 4.0, 101.0, 102.0, 103.0, 104.0, 11.0, 12.0, 13.0, 14.0, 111.0, 112.0, 113.0, 114.0].map(bf16::from_f32);- let qg = alloc_allocation_with_data::<B, bf16>(&context, &qg);- let mut queries = alloc_allocation::<B, bf16>(&context, 8);- let mut encoder = Encoder::new(context.as_ref()).expect("Failed to create encoder");+ let qg = create_buffer_with_data::<B, bf16>(&context, &qg);+ let mut queries = create_buffer::<B, bf16>(&context, 8);+ let mut command_buffer = context.create_command_buffer(None, None).expect("Failed to create command buffer");kernel.encode(&qg,&mut queries,- None::<&mut Allocation<B>>,- None::<&mut Allocation<B>>,- None::<&Allocation<B>>,- None::<&Allocation<B>>,+ None::<&mut B::GlobalBuffer>,+ None::<&mut B::GlobalBuffer>,+ None::<&B::GlobalBuffer>,+ None::<&B::GlobalBuffer>,2,None,2,@@ -105,11 +108,11 @@ fn run_query_only<B: Backend>() -> Vec<bf16> {None,8,2,- &mut encoder,+ &mut command_buffer,);- encoder.end_encoding().submit().wait_until_completed().expect("Failed to wait command buffer");+ command_buffer.end_encoding().submit().wait_until_completed().expect("Failed to wait command buffer");- allocation_to_vec(&queries)+ buffer_to_vec(&queries)}#[uzu_test]diff --git a/crates/uzu-engine/unit/backends/common/kernel/attention/kv_cache_update_test.rs b/crates/uzu-engine/unit/backends/common/kernel/attention/kv_cache_update_test.rsindex 1e5ee58f2..6af44a666 100644--- a/crates/uzu-engine/unit/backends/common/kernel/attention/kv_cache_update_test.rs+++ b/crates/uzu-engine/unit/backends/common/kernel/attention/kv_cache_update_test.rs@@ -9,12 +9,15 @@ use uzu_engine_macros::uzu_test;use crate::{array::ArrayElement,backends::{- common::{Backend, Context, Encoder, Kernels, gpu_types::Copy, kernel::KVCacheUpdateKernel},+ common::{+ Backend, CommandBufferEncoding, CommandBufferExecutable, CommandBufferPending, Context, Kernels,+ gpu_types::Copy, kernel::KVCacheUpdateKernel,+ },cpu::Cpu,},tests::{assert::assert_eq_float,- helpers::{alloc_allocation_with_data, allocation_to_vec, for_each_non_cpu_backend},+ helpers::{buffer_to_vec, create_buffer_with_data, for_each_non_cpu_backend},},};#[cfg(backend = "metal")]@@ -50,14 +53,21 @@ fn get_output<T: ArrayElement + Float, B: Backend>(input: &Input<T>) -> (Vec<T>,let kernel = <<B as Backend>::Kernels as Kernels>::KVCacheUpdateKernel::new(&context, T::data_type()).expect("Failed to create KVCacheUpdateKernel");- let mut keys = alloc_allocation_with_data::<B, T>(&context, &input.keys);- let mut values = alloc_allocation_with_data::<B, T>(&context, &input.values);-- let mut encoder = Encoder::new(context.as_ref()).expect("Failed to get encoder");- kernel.encode(&mut keys, &mut values, &input.copies, input.copies.len() as u32, input.element_dim, &mut encoder);- encoder.end_encoding().submit().wait_until_completed().unwrap();-- (allocation_to_vec(&keys), allocation_to_vec(&values))+ let mut keys = create_buffer_with_data::<B, T>(&context, &input.keys);+ let mut values = create_buffer_with_data::<B, T>(&context, &input.values);++ let mut command_buffer = context.create_command_buffer(None, None).expect("Failed to get command buffer");+ kernel.encode(+ &mut keys,+ &mut values,+ &input.copies,+ input.copies.len() as u32,+ input.element_dim,+ &mut command_buffer,+ );+ command_buffer.end_encoding().submit().wait_until_completed().unwrap();++ (buffer_to_vec(&keys), buffer_to_vec(&values))}/// Single copy between two different positions.@@ -348,9 +358,16 @@ fn test_sparse_random_pattern_f32() {let mut key_buffer = sparse_buffer_create_with::<Metal, f32>(&context, key_data.as_slice().unwrap());let mut value_buffer = sparse_buffer_create_with::<Metal, f32>(&context, value_data.as_slice().unwrap());- let mut encoder = Encoder::<Metal>::new(&context).unwrap();- kernel.encode(&mut key_buffer, &mut value_buffer, &copies, copies.len() as u32, element_dim as u32, &mut encoder);- encoder.end_encoding().submit().wait_until_completed().unwrap();+ let mut command_buffer = context.create_command_buffer(None, None).unwrap();+ kernel.encode(+ &mut key_buffer,+ &mut value_buffer,+ &copies,+ copies.len() as u32,+ element_dim as u32,+ &mut command_buffer,+ );+ command_buffer.end_encoding().submit().wait_until_completed().unwrap();let elements_count = seq_len * num_heads * head_dim;let key_values: Vec<f32> = sparse_buffer_read_vec::<Metal, f32>(&context, &key_buffer, elements_count);diff --git a/crates/uzu-engine/unit/backends/common/kernel/attention/qkv_norm_test.rs b/crates/uzu-engine/unit/backends/common/kernel/attention/qkv_norm_test.rsindex 9b9cd02f5..0b5ef4e9a 100644--- a/crates/uzu-engine/unit/backends/common/kernel/attention/qkv_norm_test.rs+++ b/crates/uzu-engine/unit/backends/common/kernel/attention/qkv_norm_test.rs@@ -7,13 +7,16 @@ use uzu_engine_macros::uzu_test;use crate::{array::ArrayElement,backends::{- common::{Allocation, Backend, Context, Encoder, Kernels, kernel::QKVNormKernel},+ common::{+ Backend, CommandBufferEncoding, CommandBufferExecutable, CommandBufferPending, Context, Kernels,+ kernel::QKVNormKernel,+ },cpu::Cpu,},data_type::DataType,tests::{assert::assert_eq_float,- helpers::{alloc_allocation_with_data, allocation_to_vec, for_each_non_cpu_backend},+ helpers::{buffer_to_vec, create_buffer_with_data, for_each_non_cpu_backend},},};@@ -133,12 +136,12 @@ fn get_output<).expect("Failed to create QKVNormKernel");- let mut qkvg = alloc_allocation_with_data::<B, OutputT>(&context, &input.qkvg);- let scales = input.has_scales.then(|| alloc_allocation_with_data::<B, ScaleT>(&context, &input.scales));+ let mut qkvg = create_buffer_with_data::<B, OutputT>(&context, &input.qkvg);+ let scales = input.has_scales.then(|| create_buffer_with_data::<B, ScaleT>(&context, &input.scales));- let mut encoder = Encoder::new(context.as_ref()).expect("Failed to create encoder");+ let mut command_buffer = context.create_command_buffer(None, None).expect("Failed to create command buffer");kernel.encode(- None::<&Allocation<B>>,+ None::<&B::GlobalBuffer>,scales.as_ref(),&mut qkvg,input.batch_size,@@ -149,11 +152,11 @@ fn get_output<input.head_offset,input.head_count,input.full_layer,- &mut encoder,+ &mut command_buffer,);- encoder.end_encoding().submit().wait_until_completed().expect("Failed to wait command buffer");+ command_buffer.end_encoding().submit().wait_until_completed().expect("Failed to wait command buffer");- allocation_to_vec(&qkvg)+ buffer_to_vec(&qkvg)}fn test_internal<diff --git a/crates/uzu-engine/unit/backends/common/kernel/attention/sigmoid_gate_test.rs b/crates/uzu-engine/unit/backends/common/kernel/attention/sigmoid_gate_test.rsindex 6f5524def..0a8b121e1 100644--- a/crates/uzu-engine/unit/backends/common/kernel/attention/sigmoid_gate_test.rs+++ b/crates/uzu-engine/unit/backends/common/kernel/attention/sigmoid_gate_test.rs@@ -7,10 +7,13 @@ use uzu_engine_macros::uzu_test;use crate::{array::ArrayElement,backends::{- common::{Backend, Context, Encoder, Kernels, kernel::SigmoidGateKernel},+ common::{+ Backend, BufferRef, CommandBufferEncoding, CommandBufferExecutable, CommandBufferPending, Context, Kernels,+ kernel::SigmoidGateKernel,+ },cpu::Cpu,},- tests::helpers::{alloc_allocation_with_data, allocation_to_vec, for_each_non_cpu_backend},+ tests::helpers::{buffer_to_vec, create_buffer_with_data, for_each_non_cpu_backend},};struct Config {@@ -29,24 +32,25 @@ fn get_output<T: ArrayElement + Float, B: Backend>(let kernel = <<B as Backend>::Kernels as Kernels>::SigmoidGateKernel::new(&context, T::data_type()).expect("Failed to create SigmoidGateKernel");- let qkvg = alloc_allocation_with_data::<B, T>(&context, qkvg_data);- let mut output = alloc_allocation_with_data::<B, T>(&context, output_data);+ let qkvg = create_buffer_with_data::<B, T>(&context, qkvg_data);+ let mut output = create_buffer_with_data::<B, T>(&context, output_data);- let mut encoder = Encoder::new(context.as_ref()).expect("Failed to create encoder");+ let mut command_buffer =+ context.as_ref().create_command_buffer(None, None).expect("Failed to create command buffer");let gate_dim = config.num_heads * config.head_dim;let gate_offset = (config.num_heads + 2 * config.num_kv_heads) * config.head_dim;let qkvg_dim = gate_offset + gate_dim;kernel.encode(- (&qkvg, gate_offset as usize * size_of::<T>()),+ qkvg.subrange(gate_offset as usize * size_of::<T>()..),&mut output,gate_dim,config.suffix_length,qkvg_dim,- &mut encoder,+ &mut command_buffer,);- encoder.end_encoding().submit().wait_until_completed().unwrap();+ command_buffer.end_encoding().submit().wait_until_completed().unwrap();- allocation_to_vec(&output)+ buffer_to_vec(&output)}fn run_test<T: ArrayElement + Float + Debug>(config: &Config) {diff --git a/crates/uzu-engine/unit/backends/common/kernel/embedding/full_precision_embedding_test.rs b/crates/uzu-engine/unit/backends/common/kernel/embedding/full_precision_embedding_test.rsindex 8d913de64..02b21c6d8 100644--- a/crates/uzu-engine/unit/backends/common/kernel/embedding/full_precision_embedding_test.rs+++ b/crates/uzu-engine/unit/backends/common/kernel/embedding/full_precision_embedding_test.rs@@ -6,8 +6,11 @@ use uzu_engine_macros::uzu_test;use crate::{array::ArrayElement,- backends::common::{Backend, Context, Encoder, Kernels, kernel::FullPrecisionEmbeddingLookupKernel},- tests::helpers::{alloc_allocation, alloc_allocation_with_data, allocation_to_vec, for_each_backend},+ backends::common::{+ Backend, CommandBufferEncoding, CommandBufferExecutable, CommandBufferPending, Context, Kernels,+ kernel::FullPrecisionEmbeddingLookupKernel,+ },+ tests::helpers::{buffer_to_vec, create_buffer, create_buffer_with_data, for_each_backend},};struct Input<T: ArrayElement + Float> {@@ -55,24 +58,24 @@ fn get_output<T: ArrayElement + Float, B: Backend>(input: &Input<T>) -> Vec<T> {<<B as Backend>::Kernels as Kernels>::FullPrecisionEmbeddingLookupKernel::new(&context, T::data_type()).expect("Failed to create FullPrecisionEmbeddingLookupKernel");- let token_ids_allocation = alloc_allocation_with_data::<B, u32>(&context, &input.token_ids);- let weights_allocation = alloc_allocation_with_data::<B, T>(&context, &input.weights);- let mut output = alloc_allocation::<B, T>(&context, input.batch_size * input.model_dim);+ let token_ids_buffer = create_buffer_with_data::<B, u32>(&context, &input.token_ids);+ let weights_buffer = create_buffer_with_data::<B, T>(&context, &input.weights);+ let mut output = create_buffer::<B, T>(&context, input.batch_size * input.model_dim);- let mut encoder = Encoder::new(context.as_ref()).expect("Failed to get encoder");+ let mut command_buffer = context.create_command_buffer(None, None).expect("Failed to get command buffer");kernel.encode(- &token_ids_allocation,- &weights_allocation,+ &token_ids_buffer,+ &weights_buffer,&mut output,input.batch_size as u32,input.vocab_size as u32,input.model_dim as u32,input.input_scale,- &mut encoder,+ &mut command_buffer,);- encoder.end_encoding().submit().wait_until_completed().unwrap();+ command_buffer.end_encoding().submit().wait_until_completed().unwrap();- allocation_to_vec(&output)+ buffer_to_vec(&output)}fn test<T: ArrayElement + Float + Debug>() {diff --git a/crates/uzu-engine/unit/backends/common/kernel/embedding/quant_embedding_test.rs b/crates/uzu-engine/unit/backends/common/kernel/embedding/quant_embedding_test.rsindex 0949aa88e..19bcc4ee9 100644--- a/crates/uzu-engine/unit/backends/common/kernel/embedding/quant_embedding_test.rs+++ b/crates/uzu-engine/unit/backends/common/kernel/embedding/quant_embedding_test.rs@@ -8,7 +8,7 @@ use crate::{array::ArrayElement,backends::{common::{- Backend, Context, Encoder, Kernels,+ Backend, CommandBufferEncoding, CommandBufferExecutable, CommandBufferPending, Context, Kernels,gpu_types::{QuantizationMethod, QuantizationMode},kernel::{ActivationTransform, QuantizedEmbeddingLookupKernel},},@@ -17,9 +17,7 @@ use crate::{data_type::DataType,tests::{assert::assert_eq_float,- helpers::{- alloc_allocation, alloc_allocation_with_data, allocation_to_vec, for_each_backend, for_each_non_cpu_backend,- },+ helpers::{buffer_to_vec, create_buffer, create_buffer_with_data, for_each_backend, for_each_non_cpu_backend},},};@@ -218,34 +216,34 @@ fn get_output_with_hadamard<T: ArrayElement + Float, B: Backend>().expect("Failed to create QuantizedEmbeddingLookupKernel");- let token_ids_allocation = alloc_allocation_with_data::<B, u32>(&context, &input.token_ids);- let weights_allocation = alloc_allocation_with_data::<B, u8>(&context, &input.weights);- let scales_allocation = alloc_allocation_with_data::<B, T>(&context, &input.scales);- let zero_points_allocation =- input.zero_points.as_ref().map(|zero_points| alloc_allocation_with_data::<B, u8>(&context, zero_points));- let biases_allocation = input.biases.as_ref().map(|biases| alloc_allocation_with_data::<B, T>(&context, biases));- let hadamard_factors_allocation =- hadamard_factors.map(|hadamard_factors| alloc_allocation_with_data::<B, i32>(&context, hadamard_factors));- let mut output = alloc_allocation::<B, T>(&context, input.batch_size as usize * input.model_dim as usize);-- let mut encoder = Encoder::new(context.as_ref()).expect("Failed to create encoder");+ let token_ids_buffer = create_buffer_with_data::<B, u32>(&context, &input.token_ids);+ let weights_buffer = create_buffer_with_data::<B, u8>(&context, &input.weights);+ let scales_buffer = create_buffer_with_data::<B, T>(&context, &input.scales);+ let zero_points_buffer =+ input.zero_points.as_ref().map(|zero_points| create_buffer_with_data::<B, u8>(&context, zero_points));+ let biases_buffer = input.biases.as_ref().map(|biases| create_buffer_with_data::<B, T>(&context, biases));+ let hadamard_factors_buffer =+ hadamard_factors.map(|hadamard_factors| create_buffer_with_data::<B, i32>(&context, hadamard_factors));+ let mut output = create_buffer::<B, T>(&context, input.batch_size as usize * input.model_dim as usize);++ let mut command_buffer = context.create_command_buffer(None, None).expect("Failed to create command buffer");kernel.encode(- &token_ids_allocation,- &weights_allocation,- &scales_allocation,- zero_points_allocation.as_ref(),- biases_allocation.as_ref(),+ &token_ids_buffer,+ &weights_buffer,+ &scales_buffer,+ zero_points_buffer.as_ref(),+ biases_buffer.as_ref(),&mut output,- hadamard_factors_allocation.as_ref(),+ hadamard_factors_buffer.as_ref(),input.batch_size,input.vocab_size,input.model_dim,input.input_scale,- &mut encoder,+ &mut command_buffer,);- encoder.end_encoding().submit().wait_until_completed().unwrap();+ command_buffer.end_encoding().submit().wait_until_completed().unwrap();- allocation_to_vec(&output)+ buffer_to_vec(&output)}fn test_zero_point_group16<T: ArrayElement + Float + Debug + Display>() {@@ -324,20 +322,20 @@ fn test_zero_point_group16_hadamard<T: ArrayElement + Float + Debug + Display>()let context = <Cpu as Backend>::Context::new().expect("Failed to create Context");let output_rht = ActivationTransform::<Cpu>::output_rht(context.as_ref(), T::data_type(), None, false).expect("Failed to create ActivationTransform");- let plain_allocation = alloc_allocation_with_data::<Cpu, T>(&context, &plain);- let hadamard_factors_allocation = alloc_allocation_with_data::<Cpu, i32>(&context, &hadamard_factors);- let mut expected_allocation = alloc_allocation::<Cpu, T>(&context, plain.len());- let mut encoder = Encoder::new(context.as_ref()).expect("Failed to create encoder");+ let plain_buffer = create_buffer_with_data::<Cpu, T>(&context, &plain);+ let hadamard_factors_buffer = create_buffer_with_data::<Cpu, i32>(&context, &hadamard_factors);+ let mut expected_buffer = create_buffer::<Cpu, T>(&context, plain.len());+ let mut command_buffer = context.create_command_buffer(None, None).expect("Failed to create command buffer");output_rht.encode_fp(- &plain_allocation,- &mut expected_allocation,- &hadamard_factors_allocation,+ &plain_buffer,+ &mut expected_buffer,+ &hadamard_factors_buffer,input.batch_size,input.model_dim,- &mut encoder,+ &mut command_buffer,);- encoder.end_encoding().submit().wait_until_completed().unwrap();- let expected = allocation_to_vec::<Cpu, T>(&expected_allocation);+ command_buffer.end_encoding().submit().wait_until_completed().unwrap();+ let expected = buffer_to_vec::<Cpu, T>(&expected_buffer);for_each_backend!(|B| {let output = get_output_with_hadamard::<T, B>(&input, Some(&hadamard_factors));diff --git a/crates/uzu-engine/unit/backends/common/kernel/gated_act_mul_test.rs b/crates/uzu-engine/unit/backends/common/kernel/gated_act_mul_test.rsindex 51ba335e1..26e5a68d2 100644--- a/crates/uzu-engine/unit/backends/common/kernel/gated_act_mul_test.rs+++ b/crates/uzu-engine/unit/backends/common/kernel/gated_act_mul_test.rs@@ -8,7 +8,7 @@ use crate::{array::ArrayElement,backends::{common::{- Allocation, Backend, Context, Encoder,+ Backend, CommandBufferEncoding, CommandBufferExecutable, CommandBufferPending, Context,gpu_types::ActivationType,kernel::{ActivationQuantization, GatedActMul, GatedActMulSettings, matmul::Int8CodeLayout},},@@ -18,9 +18,7 @@ use crate::{data_type::DataType,tests::{assert::assert_eq_float,- helpers::{- alloc_allocation, alloc_allocation_with_data, allocation_to_vec, for_each_backend, for_each_non_cpu_backend,- },+ helpers::{buffer_to_vec, create_buffer, create_buffer_with_data, for_each_backend, for_each_non_cpu_backend},},};@@ -60,14 +58,14 @@ fn run_interleaved<T: ArrayElement + Float, B: Backend>(let fused_length = (input.batch_dim * 2 * input.gated_dim) as usize;let output_length = (input.batch_dim * input.gated_dim) as usize;- let fused_up = alloc_allocation_with_data::<B, T>(&context, &input.fused_up[..fused_length]);- let hadamard_factors = alloc_allocation_with_data::<B, i32>(&context, &input.hadamard_factors);- let mut output = alloc_allocation::<B, T>(&context, output_length);+ let fused_up = create_buffer_with_data::<B, T>(&context, &input.fused_up[..fused_length]);+ let hadamard_factors = create_buffer_with_data::<B, i32>(&context, &input.hadamard_factors);+ let mut output = create_buffer::<B, T>(&context, output_length);- let mut encoder = Encoder::new(context.as_ref()).expect("create encoder");+ let mut command_buffer = context.create_command_buffer(None, None).expect("create command buffer");kernel.encode_fp(&fused_up,- None::<&Allocation<B>>,+ None::<&<B as Backend>::GlobalBuffer>,&mut output,use_hadamard.then_some(&hadamard_factors),input.gated_dim,@@ -75,11 +73,11 @@ fn run_interleaved<T: ArrayElement + Float, B: Backend>(0,0,input.act_type,- &mut encoder,+ &mut command_buffer,);- encoder.end_encoding().submit().wait_until_completed().unwrap();+ command_buffer.end_encoding().submit().wait_until_completed().unwrap();- allocation_to_vec::<B, T>(&output)+ buffer_to_vec::<B, T>(&output)}fn interleaved_test<T: ArrayElement + Float + Debug + Display>(act_type: ActivationType) {@@ -120,10 +118,10 @@ fn test_gated_act_mul_interleaved_silu_bf16() {fn run_nibble_grouped_quantized<B: Backend>(input: &InterleavedInput<bf16>) -> Vec<i8> {let context = B::Context::new().expect("create context");- let act_operand = alloc_allocation_with_data::<B, bf16>(&context, &input.fused_up);- let factors = alloc_allocation_with_data::<B, i32>(&context, &input.hadamard_factors);- let mut values = alloc_allocation::<B, i8>(&context, (input.batch_dim * input.gated_dim) as usize);- let mut scales = alloc_allocation::<B, f32>(&context, (input.batch_dim * input.gated_dim / 128) as usize);+ let act_operand = create_buffer_with_data::<B, bf16>(&context, &input.fused_up);+ let factors = create_buffer_with_data::<B, i32>(&context, &input.hadamard_factors);+ let mut values = create_buffer::<B, i8>(&context, (input.batch_dim * input.gated_dim) as usize);+ let mut scales = create_buffer::<B, f32>(&context, (input.batch_dim * input.gated_dim / 128) as usize);let kernel = GatedActMul::<B>::quantized(&context,DataType::BF16,@@ -132,20 +130,20 @@ fn run_nibble_grouped_quantized<B: Backend>(input: &InterleavedInput<bf16>) -> VGatedActMulSettings::default(),).expect("create quantized GatedActMul");- let mut encoder = Encoder::<B>::new(&context).expect("create encoder");+ let mut command_buffer = context.create_command_buffer(None, None).expect("create command buffer");kernel.encode_quantized(&act_operand,&mut values,&mut scales,- None,+ None::<&mut B::GlobalBuffer>,&factors,input.gated_dim,input.batch_dim,input.act_type,- &mut encoder,+ &mut command_buffer,);- encoder.end_encoding().submit().wait_until_completed().unwrap();- allocation_to_vec(&values)+ command_buffer.end_encoding().submit().wait_until_completed().unwrap();+ buffer_to_vec(&values)}#[uzu_test]@@ -211,26 +209,26 @@ fn run_separate<T: ArrayElement + Float, B: Backend>(input: &SeparateInput<T>) -GatedActMul::<B>::full_precision(&context, T::data_type(), false, false, GatedActMulSettings::default()).expect("create GatedActMul");- let gate_out = alloc_allocation_with_data::<B, T>(&context, &input.gate_out);- let per_layer_input = alloc_allocation_with_data::<B, T>(&context, &input.per_layer_input);- let mut output = alloc_allocation::<B, T>(&context, (input.batch_dim * input.gated_dim) as usize);+ let gate_out = create_buffer_with_data::<B, T>(&context, &input.gate_out);+ let per_layer_input = create_buffer_with_data::<B, T>(&context, &input.per_layer_input);+ let mut output = create_buffer::<B, T>(&context, (input.batch_dim * input.gated_dim) as usize);- let mut encoder = Encoder::new(context.as_ref()).expect("create encoder");+ let mut command_buffer = context.create_command_buffer(None, None).expect("create command buffer");kernel.encode_fp(&gate_out,Some(&per_layer_input),&mut output,- None,+ None::<&B::GlobalBuffer>,input.gated_dim,input.batch_dim,input.value_offset,input.value_row_stride,input.act_type,- &mut encoder,+ &mut command_buffer,);- encoder.end_encoding().submit().wait_until_completed().unwrap();+ command_buffer.end_encoding().submit().wait_until_completed().unwrap();- allocation_to_vec::<B, T>(&output)+ buffer_to_vec::<B, T>(&output)}fn separate_test<T: ArrayElement + Float + Debug>() {@@ -288,24 +286,24 @@ fn transformed_interleaved_test<T: ArrayElement + Float + Debug + Display>(let context = <B as Backend>::Context::new().expect("create context");let kernel = GatedActMul::<B>::full_precision(&context, T::data_type(), true, false, settings).expect("create transformed GatedActMul");- let fused_up = alloc_allocation_with_data::<B, T>(&context, &fused_up);- let mut output = alloc_allocation::<B, T>(&context, GATED_DIM as usize);- let mut encoder = Encoder::new(context.as_ref()).expect("create encoder");+ let fused_up = create_buffer_with_data::<B, T>(&context, &fused_up);+ let mut output = create_buffer::<B, T>(&context, GATED_DIM as usize);+ let mut command_buffer = context.create_command_buffer(None, None).expect("create command buffer");kernel.encode_fp(&fused_up,- None::<&Allocation<B>>,+ None::<&<B as Backend>::GlobalBuffer>,&mut output,- None::<&Allocation<B>>,+ None::<&<B as Backend>::GlobalBuffer>,GATED_DIM,1,0,0,ActivationType::SILU,- &mut encoder,+ &mut command_buffer,);- encoder.end_encoding().submit().wait_until_completed().unwrap();+ command_buffer.end_encoding().submit().wait_until_completed().unwrap();- let output = allocation_to_vec::<B, T>(&output);+ let output = buffer_to_vec::<B, T>(&output);assert_eq_float(&expected,&output,diff --git a/crates/uzu-engine/unit/backends/common/kernel/gdn/delta_net_test.rs b/crates/uzu-engine/unit/backends/common/kernel/gdn/delta_net_test.rsindex 0f25cca06..573cc6eca 100644--- a/crates/uzu-engine/unit/backends/common/kernel/gdn/delta_net_test.rs+++ b/crates/uzu-engine/unit/backends/common/kernel/gdn/delta_net_test.rs@@ -5,13 +5,13 @@ use crate::{array::ArrayElement,backends::{common::{- Backend, Context, Encoder, Kernels,+ Backend, CommandBufferEncoding, CommandBufferExecutable, CommandBufferPending, Context, Kernels,kernel::{DeltaNetNormGateKernel, DeltaNetPrefillKernel, DeltaNetPrefillPrepKernel, DeltaNetUpdateKernel},},cpu::Cpu,},data_type::DataType,- tests::helpers::{alloc_allocation, alloc_allocation_with_data, allocation_to_vec, for_each_backend},+ tests::helpers::{buffer_to_vec, create_buffer, create_buffer_with_data, for_each_backend},};#[cfg(backend = "metal")]use crate::{@@ -19,7 +19,7 @@ use crate::{common::kernel::{Conv1dPackKernel, DeltaNetConvScanKernel, DeltaNetConvUpdateKernel},metal::Metal,},- tests::helpers::allocation_prefix_to_vec,+ tests::helpers::buffer_prefix_to_vec,};#[cfg(backend = "metal")]@@ -34,29 +34,29 @@ fn run_conv_update<B: Backend>() -> (Vec<f32>, Vec<f32>) {let context = B::Context::new().expect("Failed to create context");- let w_array = alloc_allocation_with_data::<B, f32>(&context, w);- let b_array = alloc_allocation_with_data::<B, f32>(&context, b);- let mut in_out = alloc_allocation_with_data::<B, f32>(&context, in_proj);- let mut state_allocation = alloc_allocation_with_data::<B, f32>(&context, state);+ let w_array = create_buffer_with_data::<B, f32>(&context, w);+ let b_array = create_buffer_with_data::<B, f32>(&context, b);+ let mut in_out = create_buffer_with_data::<B, f32>(&context, in_proj);+ let mut state_buffer = create_buffer_with_data::<B, f32>(&context, state);let kernel = <<B as Backend>::Kernels as Kernels>::DeltaNetConvUpdateKernel::new(&context, DataType::F32, true).expect("Failed to create kernel");- let mut encoder = Encoder::new(context.as_ref()).expect("Failed to create encoder");+ let mut command_buffer = context.create_command_buffer(None, None).expect("Failed to create command buffer");kernel.encode(&w_array,Some(&b_array),&mut in_out,- &mut state_allocation,+ &mut state_buffer,kernel_size,conv_dim,state_stride,- &mut encoder,+ &mut command_buffer,);- encoder.end_encoding().submit().wait_until_completed().unwrap();+ command_buffer.end_encoding().submit().wait_until_completed().unwrap();- let out = allocation_prefix_to_vec::<B, f32>(&in_out, conv_dim as usize);- let new_state = allocation_to_vec::<B, f32>(&state_allocation);+ let out = buffer_prefix_to_vec::<B, f32>(&in_out, conv_dim as usize);+ let new_state = buffer_to_vec::<B, f32>(&state_buffer);(out, new_state)}@@ -75,23 +75,23 @@ fn run_delta_net_update<B: Backend, T: ArrayElement>() -> (Vec<f32>, Vec<f32>) {let context = B::Context::new().expect("Failed to create context");- let in_proj_array = alloc_allocation_with_data::<B, T>(&context, in_proj);- let a_log_array = alloc_allocation_with_data::<B, f32>(&context, a_log);- let dt_bias_array = alloc_allocation_with_data::<B, f32>(&context, dt_bias);- let norm_weight_array = alloc_allocation_with_data::<B, f32>(&context, norm_weight);- let mut state_allocation = alloc_allocation_with_data::<B, f32>(&context, state);- let mut out = alloc_allocation::<B, T>(&context, value_dim as usize);+ let in_proj_array = create_buffer_with_data::<B, T>(&context, in_proj);+ let a_log_array = create_buffer_with_data::<B, f32>(&context, a_log);+ let dt_bias_array = create_buffer_with_data::<B, f32>(&context, dt_bias);+ let norm_weight_array = create_buffer_with_data::<B, f32>(&context, norm_weight);+ let mut state_buffer = create_buffer_with_data::<B, f32>(&context, state);+ let mut out = create_buffer::<B, T>(&context, value_dim as usize);let kernel = <<B as Backend>::Kernels as Kernels>::DeltaNetUpdateKernel::new(&context, T::data_type(), head_k_dim).expect("Failed to create kernel");- let mut encoder = Encoder::new(context.as_ref()).expect("Failed to create encoder");+ let mut command_buffer = context.create_command_buffer(None, None).expect("Failed to create command buffer");kernel.encode(&in_proj_array,&a_log_array,&dt_bias_array,&norm_weight_array,- &mut state_allocation,+ &mut state_buffer,&mut out,num_v_heads,num_k_heads,@@ -99,12 +99,12 @@ fn run_delta_net_update<B: Backend, T: ArrayElement>(key_dim,value_dim,1e-6f32,- &mut encoder,+ &mut command_buffer,);- encoder.end_encoding().submit().wait_until_completed().unwrap();+ command_buffer.end_encoding().submit().wait_until_completed().unwrap();- let out = allocation_to_vec::<B, T>(&out).into_iter().map(|value| value.to_f32().expect("output to f32")).collect();- let new_state = allocation_to_vec::<B, f32>(&state_allocation);+ let out = buffer_to_vec::<B, T>(&out).into_iter().map(|value| value.to_f32().expect("output to f32")).collect();+ let new_state = buffer_to_vec::<B, f32>(&state_buffer);(out, new_state)}@@ -189,14 +189,14 @@ fn test_delta_net_conv_scan() {// Test: Conv1dPack + DeltaNetConvScan on Metallet context = <Metal as Backend>::Context::new().expect("context");- let state_array = alloc_allocation_with_data::<Metal, f32>(&context, &init_state);- let mut in_proj_array = alloc_allocation_with_data::<Metal, bf16>(&context, &in_proj);- let w_array = alloc_allocation_with_data::<Metal, f32>(&context, &w);- let b_array = alloc_allocation_with_data::<Metal, f32>(&context, &b);+ let state_array = create_buffer_with_data::<Metal, f32>(&context, &init_state);+ let mut in_proj_array = create_buffer_with_data::<Metal, bf16>(&context, &in_proj);+ let w_array = create_buffer_with_data::<Metal, f32>(&context, &w);+ let b_array = create_buffer_with_data::<Metal, f32>(&context, &b);let padded_len = (tap_count + suffix_len) * total_proj_dim;- let mut padded_array = alloc_allocation::<Metal, f32>(&context, padded_len);- let mut state_out_array = alloc_allocation::<Metal, f32>(&context, conv_dim * tap_count);+ let mut padded_array = create_buffer::<Metal, f32>(&context, padded_len);+ let mut state_out_array = create_buffer::<Metal, f32>(&context, conv_dim * tap_count);let pack_kernel =<<Metal as Backend>::Kernels as Kernels>::Conv1dPackKernel::new(&context, DataType::F32, DataType::BF16)@@ -205,7 +205,7 @@ fn test_delta_net_conv_scan() {<<Metal as Backend>::Kernels as Kernels>::DeltaNetConvScanKernel::new(&context, DataType::BF16, true).expect("scan");- let mut encoder = Encoder::new(context.as_ref()).expect("Failed to create encoder");+ let mut command_buffer = context.create_command_buffer(None, None).expect("Failed to create command buffer");pack_kernel.encode(&state_array,&in_proj_array,@@ -214,7 +214,7 @@ fn test_delta_net_conv_scan() {total_proj_dim as u32,suffix_len as u32,conv_dim as u32,- &mut encoder,+ &mut command_buffer,);scan_kernel.encode(&padded_array,@@ -228,18 +228,18 @@ fn test_delta_net_conv_scan() {tap_count as u32,conv_dim as u32,total_proj_dim as u32,- &mut encoder,+ &mut command_buffer,);- encoder.end_encoding().submit().wait_until_completed().unwrap();+ command_buffer.end_encoding().submit().wait_until_completed().unwrap();- let in_proj_result: Vec<bf16> = allocation_to_vec(&in_proj_array);+ let in_proj_result: Vec<bf16> = buffer_to_vec(&in_proj_array);let in_proj_result: Vec<f32> = in_proj_result.into_iter().map(f32::from).collect();let mut scan_outputs = vec![0.0f32; suffix_len * conv_dim];for t in 0..suffix_len {scan_outputs[t * conv_dim..(t + 1) * conv_dim].copy_from_slice(&in_proj_result[t * total_proj_dim..t * total_proj_dim + conv_dim]);}- let scan_state: Vec<f32> = allocation_to_vec(&state_out_array);+ let scan_state: Vec<f32> = buffer_to_vec(&state_out_array);assert_close(&ref_outputs, &scan_outputs, 1e-4, 1e-3, "ConvScan output");assert_close(&ref_state, &scan_state, 1e-5, 1e-4, "ConvScan state");@@ -337,17 +337,17 @@ fn run_prefill_with_norm_gate_typed<B: Backend, T: ArrayElement>(let num_dv_groups = head_v_dim.div_ceil(16) as u32;let context = <B as Backend>::Context::new().expect("context");- let in_proj_array = alloc_allocation_with_data::<B, T>(&context, in_proj);- let a_log_array = alloc_allocation_with_data::<B, f32>(&context, a_log);- let dt_bias_array = alloc_allocation_with_data::<B, f32>(&context, dt_bias);- let norm_weight_array = alloc_allocation_with_data::<B, f32>(&context, norm_weight);- let mut state_array = alloc_allocation_with_data::<B, f32>(&context, state);- let mut out_array = alloc_allocation::<B, T>(&context, suffix_len * value_dim);- let mut q_norm_array = alloc_allocation::<B, f32>(&context, suffix_len * key_dim);- let mut k_norm_array = alloc_allocation::<B, f32>(&context, suffix_len * key_dim);-- let mut beta_array = alloc_allocation::<B, f32>(&context, suffix_len * num_v_heads);- let mut decay_array = alloc_allocation::<B, f32>(&context, suffix_len * num_v_heads);+ let in_proj_array = create_buffer_with_data::<B, T>(&context, in_proj);+ let a_log_array = create_buffer_with_data::<B, f32>(&context, a_log);+ let dt_bias_array = create_buffer_with_data::<B, f32>(&context, dt_bias);+ let norm_weight_array = create_buffer_with_data::<B, f32>(&context, norm_weight);+ let mut state_array = create_buffer_with_data::<B, f32>(&context, state);+ let mut out_array = create_buffer::<B, T>(&context, suffix_len * value_dim);+ let mut q_norm_array = create_buffer::<B, f32>(&context, suffix_len * key_dim);+ let mut k_norm_array = create_buffer::<B, f32>(&context, suffix_len * key_dim);++ let mut beta_array = create_buffer::<B, f32>(&context, suffix_len * num_v_heads);+ let mut decay_array = create_buffer::<B, f32>(&context, suffix_len * num_v_heads);let prep_k = <<B as Backend>::Kernels as Kernels>::DeltaNetPrefillPrepKernel::new(&context,@@ -363,14 +363,14 @@ fn run_prefill_with_norm_gate_typed<B: Backend, T: ArrayElement>(.unwrap();let norm_k = <<B as Backend>::Kernels as Kernels>::DeltaNetNormGateKernel::new(&context, T::data_type()).unwrap();- let mut encoder = Encoder::new(context.as_ref()).expect("Failed to create encoder");+ let mut command_buffer = context.create_command_buffer(None, None).expect("Failed to create command buffer");prep_k.encode(&in_proj_array,&a_log_array,&dt_bias_array,&mut q_norm_array,&mut k_norm_array,- None::<&mut crate::backends::common::Allocation<B>>,+ None::<&mut B::GlobalBuffer>,&mut beta_array,&mut decay_array,num_v_heads as u32,@@ -378,7 +378,7 @@ fn run_prefill_with_norm_gate_typed<B: Backend, T: ArrayElement>(key_dim as u32,value_dim as u32,suffix_len as u32,- &mut encoder,+ &mut command_buffer,);prefill_k.encode(&q_norm_array,@@ -395,7 +395,7 @@ fn run_prefill_with_norm_gate_typed<B: Backend, T: ArrayElement>(value_dim as u32,suffix_len as u32,num_dv_groups,- &mut encoder,+ &mut command_buffer,);norm_k.encode(&mut out_array,@@ -408,13 +408,13 @@ fn run_prefill_with_norm_gate_typed<B: Backend, T: ArrayElement>(total_proj_dim as u32,1e-6f32,suffix_len as u32,- &mut encoder,+ &mut command_buffer,);- encoder.end_encoding().submit().wait_until_completed().unwrap();+ command_buffer.end_encoding().submit().wait_until_completed().unwrap();- let out: Vec<T> = allocation_to_vec(&out_array);+ let out: Vec<T> = buffer_to_vec(&out_array);let out = out.into_iter().map(|value| value.to_f32().expect("output to f32")).collect();- let state = allocation_to_vec(&state_array);+ let state = buffer_to_vec(&state_array);(out, state)}@@ -523,14 +523,14 @@ fn test_delta_net_prefill_prep() {// CPU reference via Kernels traitlet cpu_ctx = <Cpu as Backend>::Context::new().expect("cpu context");- let cpu_in_proj = alloc_allocation_with_data::<Cpu, bf16>(&cpu_ctx, &in_proj);- let cpu_a_log = alloc_allocation_with_data::<Cpu, f32>(&cpu_ctx, &a_log);- let cpu_dt_bias = alloc_allocation_with_data::<Cpu, f32>(&cpu_ctx, &dt_bias);- let mut cpu_q = alloc_allocation::<Cpu, bf16>(&cpu_ctx, suffix_len * key_dim);- let mut cpu_k = alloc_allocation::<Cpu, bf16>(&cpu_ctx, suffix_len * key_dim);- let mut cpu_v = alloc_allocation::<Cpu, bf16>(&cpu_ctx, suffix_len * value_dim);- let mut cpu_beta = alloc_allocation::<Cpu, f32>(&cpu_ctx, suffix_len * num_v_heads);- let mut cpu_decay = alloc_allocation::<Cpu, f32>(&cpu_ctx, suffix_len * num_v_heads);+ let cpu_in_proj = create_buffer_with_data::<Cpu, bf16>(&cpu_ctx, &in_proj);+ let cpu_a_log = create_buffer_with_data::<Cpu, f32>(&cpu_ctx, &a_log);+ let cpu_dt_bias = create_buffer_with_data::<Cpu, f32>(&cpu_ctx, &dt_bias);+ let mut cpu_q = create_buffer::<Cpu, bf16>(&cpu_ctx, suffix_len * key_dim);+ let mut cpu_k = create_buffer::<Cpu, bf16>(&cpu_ctx, suffix_len * key_dim);+ let mut cpu_v = create_buffer::<Cpu, bf16>(&cpu_ctx, suffix_len * value_dim);+ let mut cpu_beta = create_buffer::<Cpu, f32>(&cpu_ctx, suffix_len * num_v_heads);+ let mut cpu_decay = create_buffer::<Cpu, f32>(&cpu_ctx, suffix_len * num_v_heads);let cpu_prep = <<Cpu as Backend>::Kernels as Kernels>::DeltaNetPrefillPrepKernel::new(&cpu_ctx,@@ -541,7 +541,7 @@ fn test_delta_net_prefill_prep() {true,).unwrap();- let mut cpu_enc = Encoder::new(cpu_ctx.as_ref()).expect("encoder");+ let mut cpu_enc = cpu_ctx.create_command_buffer(None, None).expect("command buffer");cpu_prep.encode(&cpu_in_proj,&cpu_a_log,@@ -560,11 +560,11 @@ fn test_delta_net_prefill_prep() {);cpu_enc.end_encoding().submit().wait_until_completed().unwrap();- let ref_q = allocation_to_vec::<Cpu, bf16>(&cpu_q).into_iter().map(f32::from).collect::<Vec<_>>();- let ref_k = allocation_to_vec::<Cpu, bf16>(&cpu_k).into_iter().map(f32::from).collect::<Vec<_>>();- let ref_v: Vec<bf16> = allocation_to_vec(&cpu_v);- let ref_beta: Vec<f32> = allocation_to_vec(&cpu_beta);- let ref_decay: Vec<f32> = allocation_to_vec(&cpu_decay);+ let ref_q = buffer_to_vec::<Cpu, bf16>(&cpu_q).into_iter().map(f32::from).collect::<Vec<_>>();+ let ref_k = buffer_to_vec::<Cpu, bf16>(&cpu_k).into_iter().map(f32::from).collect::<Vec<_>>();+ let ref_v: Vec<bf16> = buffer_to_vec(&cpu_v);+ let ref_beta: Vec<f32> = buffer_to_vec(&cpu_beta);+ let ref_decay: Vec<f32> = buffer_to_vec(&cpu_decay);let expected_v = in_proj.chunks_exact(total_proj_dim).flat_map(|row| row[2 * key_dim..2 * key_dim + value_dim].iter().copied())@@ -573,15 +573,15 @@ fn test_delta_net_prefill_prep() {// Metallet context = <Metal as Backend>::Context::new().expect("context");- let in_proj_array = alloc_allocation_with_data::<Metal, bf16>(&context, &in_proj);- let a_log_array = alloc_allocation_with_data::<Metal, f32>(&context, &a_log);- let dt_bias_array = alloc_allocation_with_data::<Metal, f32>(&context, &dt_bias);- let mut q_norm_array = alloc_allocation::<Metal, bf16>(&context, suffix_len * key_dim);- let mut k_norm_array = alloc_allocation::<Metal, bf16>(&context, suffix_len * key_dim);- let mut compact_v_array = alloc_allocation::<Metal, bf16>(&context, suffix_len * value_dim);+ let in_proj_array = create_buffer_with_data::<Metal, bf16>(&context, &in_proj);+ let a_log_array = create_buffer_with_data::<Metal, f32>(&context, &a_log);+ let dt_bias_array = create_buffer_with_data::<Metal, f32>(&context, &dt_bias);+ let mut q_norm_array = create_buffer::<Metal, bf16>(&context, suffix_len * key_dim);+ let mut k_norm_array = create_buffer::<Metal, bf16>(&context, suffix_len * key_dim);+ let mut compact_v_array = create_buffer::<Metal, bf16>(&context, suffix_len * value_dim);- let mut beta_array = alloc_allocation::<Metal, f32>(&context, suffix_len * num_v_heads);- let mut decay_array = alloc_allocation::<Metal, f32>(&context, suffix_len * num_v_heads);+ let mut beta_array = create_buffer::<Metal, f32>(&context, suffix_len * num_v_heads);+ let mut decay_array = create_buffer::<Metal, f32>(&context, suffix_len * num_v_heads);let prep_k = <<Metal as Backend>::Kernels as Kernels>::DeltaNetPrefillPrepKernel::new(&context,@@ -593,7 +593,7 @@ fn test_delta_net_prefill_prep() {).unwrap();- let mut encoder = Encoder::new(context.as_ref()).expect("encoder");+ let mut command_buffer = context.create_command_buffer(None, None).expect("command buffer");prep_k.encode(&in_proj_array,&a_log_array,@@ -608,15 +608,15 @@ fn test_delta_net_prefill_prep() {key_dim as u32,value_dim as u32,suffix_len as u32,- &mut encoder,+ &mut command_buffer,);- encoder.end_encoding().submit().wait_until_completed().unwrap();+ command_buffer.end_encoding().submit().wait_until_completed().unwrap();- let gpu_q = allocation_to_vec::<Metal, bf16>(&q_norm_array).into_iter().map(f32::from).collect::<Vec<_>>();- let gpu_k = allocation_to_vec::<Metal, bf16>(&k_norm_array).into_iter().map(f32::from).collect::<Vec<_>>();- let gpu_v: Vec<bf16> = allocation_to_vec(&compact_v_array);- let gpu_beta: Vec<f32> = allocation_to_vec(&beta_array);- let gpu_decay: Vec<f32> = allocation_to_vec(&decay_array);+ let gpu_q = buffer_to_vec::<Metal, bf16>(&q_norm_array).into_iter().map(f32::from).collect::<Vec<_>>();+ let gpu_k = buffer_to_vec::<Metal, bf16>(&k_norm_array).into_iter().map(f32::from).collect::<Vec<_>>();+ let gpu_v: Vec<bf16> = buffer_to_vec(&compact_v_array);+ let gpu_beta: Vec<f32> = buffer_to_vec(&beta_array);+ let gpu_decay: Vec<f32> = buffer_to_vec(&decay_array);assert_close(&gpu_q, &ref_q, 1e-4, 1e-3, "prep q_norm");assert_close(&gpu_k, &ref_k, 1e-4, 1e-3, "prep k_norm");@@ -649,16 +649,16 @@ fn bench_delta_net_prefill() {let norm_weight: Vec<f32> = (0..head_v_dim).map(|i| 0.9 + (i as f32) * 0.001).collect();let context = <Metal as Backend>::Context::new().expect("context");- let in_proj_array = alloc_allocation_with_data::<Metal, f32>(&context, &in_proj);- let a_log_array = alloc_allocation_with_data::<Metal, f32>(&context, &a_log);- let dt_bias_array = alloc_allocation_with_data::<Metal, f32>(&context, &dt_bias);- let norm_weight_array = alloc_allocation_with_data::<Metal, f32>(&context, &norm_weight);- let mut out_array = alloc_allocation::<Metal, f32>(&context, suffix_len * value_dim);- let mut q_norm_array = alloc_allocation::<Metal, f32>(&context, suffix_len * key_dim);- let mut k_norm_array = alloc_allocation::<Metal, f32>(&context, suffix_len * key_dim);+ let in_proj_array = create_buffer_with_data::<Metal, f32>(&context, &in_proj);+ let a_log_array = create_buffer_with_data::<Metal, f32>(&context, &a_log);+ let dt_bias_array = create_buffer_with_data::<Metal, f32>(&context, &dt_bias);+ let norm_weight_array = create_buffer_with_data::<Metal, f32>(&context, &norm_weight);+ let mut out_array = create_buffer::<Metal, f32>(&context, suffix_len * value_dim);+ let mut q_norm_array = create_buffer::<Metal, f32>(&context, suffix_len * key_dim);+ let mut k_norm_array = create_buffer::<Metal, f32>(&context, suffix_len * key_dim);- let mut beta_array = alloc_allocation::<Metal, f32>(&context, suffix_len * num_v_heads);- let mut decay_array = alloc_allocation::<Metal, f32>(&context, suffix_len * num_v_heads);+ let mut beta_array = create_buffer::<Metal, f32>(&context, suffix_len * num_v_heads);+ let mut decay_array = create_buffer::<Metal, f32>(&context, suffix_len * num_v_heads);let num_dv_groups = head_v_dim.div_ceil(16) as u32;@@ -687,14 +687,14 @@ fn bench_delta_net_prefill() {eprintln!(" state_size={state_size} ({:.2} MB)", state_size as f64 * 4.0 / 1024.0 / 1024.0);let prep_result = run_perf_with_warmup("prep_only", 5, 50, || {- let mut encoder = Encoder::new(context.as_ref()).expect("encoder");+ let mut command_buffer = context.create_command_buffer(None, None).expect("command buffer");prep_k.encode(&in_proj_array,&a_log_array,&dt_bias_array,&mut q_norm_array,&mut k_norm_array,- None::<&mut crate::backends::common::Allocation<Metal>>,+ None::<&mut <Metal as Backend>::GlobalBuffer>,&mut beta_array,&mut decay_array,num_v_heads as u32,@@ -702,25 +702,25 @@ fn bench_delta_net_prefill() {key_dim as u32,value_dim as u32,suffix_len as u32,- &mut encoder,+ &mut command_buffer,);- encoder.end_encoding().submit().wait_until_completed().unwrap();+ command_buffer.end_encoding().submit().wait_until_completed().unwrap();});prep_result.print();// Benchmark prep + prefill + norm_gate (production path)- let mut state_array = alloc_allocation::<Metal, f32>(&context, state_size);+ let mut state_array = create_buffer::<Metal, f32>(&context, state_size);let prefill_result = run_perf_with_warmup("prep+prefill+norm_gate", 5, 50, || {- let mut encoder = Encoder::new(context.as_ref()).expect("encoder");- encoder.encode_fill(&mut state_array, 0);+ let mut command_buffer = context.create_command_buffer(None, None).expect("command buffer");+ command_buffer.encode_fill(&mut state_array, 0);prep_k.encode(&in_proj_array,&a_log_array,&dt_bias_array,&mut q_norm_array,&mut k_norm_array,- None::<&mut crate::backends::common::Allocation<Metal>>,+ None::<&mut <Metal as Backend>::GlobalBuffer>,&mut beta_array,&mut decay_array,num_v_heads as u32,@@ -728,7 +728,7 @@ fn bench_delta_net_prefill() {key_dim as u32,value_dim as u32,suffix_len as u32,- &mut encoder,+ &mut command_buffer,);prefill_k.encode(&q_norm_array,@@ -745,7 +745,7 @@ fn bench_delta_net_prefill() {value_dim as u32,suffix_len as u32,num_dv_groups,- &mut encoder,+ &mut command_buffer,);norm_k.encode(&mut out_array,@@ -758,9 +758,9 @@ fn bench_delta_net_prefill() {total_proj_dim as u32,1e-6f32,suffix_len as u32,- &mut encoder,+ &mut command_buffer,);- encoder.end_encoding().submit().wait_until_completed().unwrap();+ command_buffer.end_encoding().submit().wait_until_completed().unwrap();});prefill_result.print();}diff --git a/crates/uzu-engine/unit/backends/common/kernel/gdn/tree_verify/conv_scan_test.rs b/crates/uzu-engine/unit/backends/common/kernel/gdn/tree_verify/conv_scan_test.rsindex d42c9c5ac..5ee8ebc6c 100644--- a/crates/uzu-engine/unit/backends/common/kernel/gdn/tree_verify/conv_scan_test.rs+++ b/crates/uzu-engine/unit/backends/common/kernel/gdn/tree_verify/conv_scan_test.rs@@ -1,3 +1,4 @@+use std::range::Range;#[cfg(backend = "metal")]use std::{mem::size_of, time::Duration};@@ -11,18 +12,21 @@ use uzu_engine_macros::uzu_test;#[cfg(backend = "metal")]use crate::{- backends::{common::Allocation, metal::Metal},+ backends::metal::Metal,tests::{cold_pool::ColdPool, matmul::iter_encode_loop_named},};use crate::{backends::{- common::{Backend, Context, Encoder, Kernels, kernel::ConvTreeScanKernel},+ common::{+ Backend, CommandBufferEncoding, CommandBufferExecutable, CommandBufferPending, Context, Kernels,+ kernel::ConvTreeScanKernel,+ },cpu::Cpu,},data_type::DataType,tests::{assert::assert_eq_float,- helpers::{alloc_allocation, alloc_allocation_with_data, allocation_to_vec, for_each_non_cpu_backend},+ helpers::{buffer_to_vec, create_buffer, create_buffer_with_data, for_each_non_cpu_backend},},};@@ -73,15 +77,15 @@ fn run<B: Backend>(let bias = (0..CONV_DIM).map(|i| i as f32 * 0.003 - 0.04).collect::<Vec<_>>();let base_state = (0..CONV_DIM * STATE_STRIDE).map(|i| (i % 13) as f32 * 0.01 - 0.05).collect::<Vec<_>>();- let input = alloc_allocation_with_data::<B, f32>(&context, &input);- let weights = alloc_allocation_with_data::<B, f32>(&context, &weights);- let bias = alloc_allocation_with_data::<B, f32>(&context, &bias);- let base_state_buffer = alloc_allocation_with_data::<B, f32>(&context, &base_state);- let parents = alloc_allocation_with_data::<B, i32>(&context, &parents(tree_size, shape));- let mut output = alloc_allocation::<B, f32>(&context, tree_size * TOTAL_PROJ_DIM);- let mut suffix_state = alloc_allocation::<B, f32>(&context, tree_size * CONV_DIM * STATE_STRIDE);+ let input = create_buffer_with_data::<B, f32>(&context, &input);+ let weights = create_buffer_with_data::<B, f32>(&context, &weights);+ let bias = create_buffer_with_data::<B, f32>(&context, &bias);+ let base_state_buffer = create_buffer_with_data::<B, f32>(&context, &base_state);+ let parents = create_buffer_with_data::<B, i32>(&context, &parents(tree_size, shape));+ let mut output = create_buffer::<B, f32>(&context, tree_size * TOTAL_PROJ_DIM);+ let mut suffix_state = create_buffer::<B, f32>(&context, tree_size * CONV_DIM * STATE_STRIDE);- let mut encoder = Encoder::new(context.as_ref()).expect("encoder");+ let mut command_buffer = context.create_command_buffer(None, None).expect("command buffer");kernel.encode(&input,&weights,@@ -93,16 +97,11 @@ fn run<B: Backend>(tree_size as u32,TOTAL_PROJ_DIM as u32,CONV_DIM as u32,- &mut encoder,+ &mut command_buffer,);- encoder.end_encoding().submit().wait_until_completed().unwrap();- assert_eq_float(- &base_state,- &allocation_to_vec(&base_state_buffer),- 0.0,- &format!("base state {shape} T={tree_size}"),- );- (allocation_to_vec(&output), allocation_to_vec(&suffix_state))+ command_buffer.end_encoding().submit().wait_until_completed().unwrap();+ assert_eq_float(&base_state, &buffer_to_vec(&base_state_buffer), 0.0, &format!("base state {shape} T={tree_size}"));+ (buffer_to_vec(&output), buffer_to_vec(&suffix_state))}#[uzu_test]@@ -121,17 +120,17 @@ fn test_conv_tree_scan() {let baseline = run::<Cpu>(49, "binary", false);let perturbed = run::<Cpu>(49, "binary", true);- let output = 2 * TOTAL_PROJ_DIM..3 * TOTAL_PROJ_DIM;- let state = 2 * CONV_DIM * STATE_STRIDE..3 * CONV_DIM * STATE_STRIDE;- assert_eq_float(&baseline.0[output.clone()], &perturbed.0[output], 0.0, "sibling output");- assert_eq_float(&baseline.1[state.clone()], &perturbed.1[state], 0.0, "sibling state");+ let output = Range::from(2 * TOTAL_PROJ_DIM..3 * TOTAL_PROJ_DIM);+ let state = Range::from(2 * CONV_DIM * STATE_STRIDE..3 * CONV_DIM * STATE_STRIDE);+ assert_eq_float(&baseline.0[output], &perturbed.0[output], 0.0, "sibling output");+ assert_eq_float(&baseline.1[state], &perturbed.1[state], 0.0, "sibling state");}#[cfg(backend = "metal")]struct Buffers {- input: Allocation<Metal>,- output: Allocation<Metal>,- suffix_state: Allocation<Metal>,+ input: <Metal as Backend>::GlobalBuffer,+ output: <Metal as Backend>::GlobalBuffer,+ suffix_state: <Metal as Backend>::GlobalBuffer,}#[cfg(backend = "metal")]@@ -149,38 +148,43 @@ fn bench_conv_tree_scan(c: &mut Criterion) {true,).expect("kernel");- let weights = alloc_allocation_with_data::<Metal, f32>(&context, &vec![0.01; BENCH_CONV_DIM * KERNEL_SIZE]);- let bias = alloc_allocation_with_data::<Metal, f32>(&context, &vec![0.0; BENCH_CONV_DIM]);- let base_state = alloc_allocation_with_data::<Metal, f32>(&context, &vec![0.0; BENCH_CONV_DIM * STATE_STRIDE]);+ let weights = create_buffer_with_data::<Metal, f32>(&context, &vec![0.01; BENCH_CONV_DIM * KERNEL_SIZE]);+ let bias = create_buffer_with_data::<Metal, f32>(&context, &vec![0.0; BENCH_CONV_DIM]);+ let base_state = create_buffer_with_data::<Metal, f32>(&context, &vec![0.0; BENCH_CONV_DIM * STATE_STRIDE]);let mut group = c.benchmark_group(BENCHMARK);group.sample_size(30).warm_up_time(Duration::from_millis(300)).measurement_time(Duration::from_secs(1));for tree_size in [49usize, 64, 128] {- let parents = alloc_allocation_with_data::<Metal, i32>(&context, &parents(tree_size, "binary"));+ let parents = create_buffer_with_data::<Metal, i32>(&context, &parents(tree_size, "binary"));let input_len = tree_size * BENCH_TOTAL_PROJ_DIM;let state_len = tree_size * BENCH_CONV_DIM * STATE_STRIDE;let mut buffers = ColdPool::new(2 * input_len * size_of::<bf16>() + state_len * size_of::<f32>(), || Buffers {- input: alloc_allocation_with_data::<Metal, bf16>(&context, &vec![bf16::from_f32(0.1); input_len]),- output: alloc_allocation::<Metal, bf16>(&context, input_len),- suffix_state: alloc_allocation::<Metal, f32>(&context, state_len),+ input: create_buffer_with_data::<Metal, bf16>(&context, &vec![bf16::from_f32(0.1); input_len]),+ output: create_buffer::<Metal, bf16>(&context, input_len),+ suffix_state: create_buffer::<Metal, f32>(&context, state_len),});group.bench_function(format!("T{tree_size}"), |bencher| {- iter_encode_loop_named::<Metal, _>(&context, bencher, &format!("{BENCHMARK}/T{tree_size}"), |encoder| {- let buffers = buffers.next_mut();- kernel.encode(- &buffers.input,- &weights,- Some(&bias),- &base_state,- &parents,- &mut buffers.output,- &mut buffers.suffix_state,- tree_size as u32,- BENCH_TOTAL_PROJ_DIM as u32,- BENCH_CONV_DIM as u32,- encoder,- );- });+ iter_encode_loop_named::<Metal, _>(+ &context,+ bencher,+ &format!("{BENCHMARK}/T{tree_size}"),+ |command_buffer| {+ let buffers = buffers.next_mut();+ kernel.encode(+ &buffers.input,+ &weights,+ Some(&bias),+ &base_state,+ &parents,+ &mut buffers.output,+ &mut buffers.suffix_state,+ tree_size as u32,+ BENCH_TOTAL_PROJ_DIM as u32,+ BENCH_CONV_DIM as u32,+ command_buffer,+ );+ },+ );});}}diff --git a/crates/uzu-engine/unit/backends/common/kernel/gdn/tree_verify/out_bench.rs b/crates/uzu-engine/unit/backends/common/kernel/gdn/tree_verify/out_bench.rsindex 54c6a5679..3a542dbed 100644--- a/crates/uzu-engine/unit/backends/common/kernel/gdn/tree_verify/out_bench.rs+++ b/crates/uzu-engine/unit/backends/common/kernel/gdn/tree_verify/out_bench.rs@@ -10,11 +10,11 @@ use uzu_engine_macros::uzu_bench;use crate::{array::ArrayElement,backends::{- common::{Allocation, Backend, Context, Kernels, kernel::BuildTreeOutKernel},+ common::{Backend, Context, Kernels, kernel::BuildTreeOutKernel},metal::Metal,},tests::{- helpers::{alloc_allocation, alloc_allocation_with_data},+ helpers::{create_buffer, create_buffer_with_data},matmul::iter_encode_loop_named,},};@@ -36,13 +36,13 @@ const BUILD_TREE_OUT_PATHS: &[(&str, bool, bool, usize)] = &[];struct TreeOutBuffers {- q: Allocation<Metal>,- prefix: Allocation<Metal>,- qkd: Allocation<Metal>,- u: Allocation<Metal>,- h0: Allocation<Metal>,- h0_indices: Allocation<Metal>,- o: Allocation<Metal>,+ q: <Metal as Backend>::GlobalBuffer,+ prefix: <Metal as Backend>::GlobalBuffer,+ qkd: <Metal as Backend>::GlobalBuffer,+ u: <Metal as Backend>::GlobalBuffer,+ h0: <Metal as Backend>::GlobalBuffer,+ h0_indices: <Metal as Backend>::GlobalBuffer,+ o: <Metal as Backend>::GlobalBuffer,}fn make_buffers<T: ArrayElement + Float>(@@ -65,13 +65,13 @@ fn make_buffers<T: ArrayElement + Float>(let h0_indices = (0..batch_size as i32).collect::<Vec<_>>();TreeOutBuffers {- q: alloc_allocation_with_data::<Metal, T>(context, &q),- prefix: alloc_allocation_with_data::<Metal, f32>(context, &prefix),- qkd: alloc_allocation_with_data::<Metal, f32>(context, &qkd),- u: alloc_allocation_with_data::<Metal, f32>(context, &u),- h0: alloc_allocation_with_data::<Metal, f32>(context, &h0),- h0_indices: alloc_allocation_with_data::<Metal, i32>(context, &h0_indices),- o: alloc_allocation::<Metal, T>(context, uv_len),+ q: create_buffer_with_data::<Metal, T>(context, &q),+ prefix: create_buffer_with_data::<Metal, f32>(context, &prefix),+ qkd: create_buffer_with_data::<Metal, f32>(context, &qkd),+ u: create_buffer_with_data::<Metal, f32>(context, &u),+ h0: create_buffer_with_data::<Metal, f32>(context, &h0),+ h0_indices: create_buffer_with_data::<Metal, i32>(context, &h0_indices),+ o: create_buffer::<Metal, T>(context, uv_len),}}@@ -116,7 +116,7 @@ fn bench_build_tree_out_type<T: ArrayElement + Float>().expect("BuildTreeOutKernel");group.bench_function(benchmark_id, |bencher| {- iter_encode_loop_named::<Metal, _>(context, bencher, &benchmark_path, |encoder| {+ iter_encode_loop_named::<Metal, _>(context, bencher, &benchmark_path, |command_buffer| {kernel.encode(&buffers.q,&buffers.prefix,@@ -132,7 +132,7 @@ fn bench_build_tree_out_type<T: ArrayElement + Float>(VALUE_HEADS as u32,HEAD_K_DIM as u32,HEAD_V_DIM as u32,- encoder,+ command_buffer,);});});diff --git a/crates/uzu-engine/unit/backends/common/kernel/gdn/tree_verify/out_test.rs b/crates/uzu-engine/unit/backends/common/kernel/gdn/tree_verify/out_test.rsindex 75889593f..195c4e117 100644--- a/crates/uzu-engine/unit/backends/common/kernel/gdn/tree_verify/out_test.rs+++ b/crates/uzu-engine/unit/backends/common/kernel/gdn/tree_verify/out_test.rs@@ -7,13 +7,16 @@ use uzu_engine_macros::uzu_test;use crate::{array::ArrayElement,backends::{- common::{Backend, Context, Encoder, Kernels, kernel::BuildTreeOutKernel},+ common::{+ Backend, CommandBufferEncoding, CommandBufferExecutable, CommandBufferPending, Context, Kernels,+ kernel::BuildTreeOutKernel,+ },cpu::Cpu,metal::Metal,},tests::{assert::assert_eq_float,- helpers::{alloc_allocation, alloc_allocation_with_data, allocation_to_vec, for_each_non_cpu_backend},+ helpers::{buffer_to_vec, create_buffer, create_buffer_with_data, for_each_non_cpu_backend},},};@@ -87,16 +90,16 @@ fn run_build_tree_out<B: Backend, T: ArrayElement + Float>(use_h0,).expect("BuildTreeOutKernel");- let q = alloc_allocation_with_data::<B, T>(&context, &inputs.q);- let prefix = alloc_allocation_with_data::<B, f32>(&context, &inputs.prefix);- let qkd = alloc_allocation_with_data::<B, f32>(&context, &inputs.qkd);- let u = alloc_allocation_with_data::<B, f32>(&context, &inputs.u);- let h0 = use_h0.then(|| alloc_allocation_with_data::<B, f32>(&context, &inputs.h0));- let h0_indices = use_h0.then(|| alloc_allocation_with_data::<B, i32>(&context, &inputs.h0_indices));+ let q = create_buffer_with_data::<B, T>(&context, &inputs.q);+ let prefix = create_buffer_with_data::<B, f32>(&context, &inputs.prefix);+ let qkd = create_buffer_with_data::<B, f32>(&context, &inputs.qkd);+ let u = create_buffer_with_data::<B, f32>(&context, &inputs.u);+ let h0 = use_h0.then(|| create_buffer_with_data::<B, f32>(&context, &inputs.h0));+ let h0_indices = use_h0.then(|| create_buffer_with_data::<B, i32>(&context, &inputs.h0_indices));let mut o =- alloc_allocation::<B, T>(&context, shape.batch_size * shape.tree_size * shape.value_heads * shape.head_v_dim);+ create_buffer::<B, T>(&context, shape.batch_size * shape.tree_size * shape.value_heads * shape.head_v_dim);- let mut encoder = Encoder::new(context.as_ref()).expect("Failed to create encoder");+ let mut command_buffer = context.create_command_buffer(None, None).expect("Failed to create command buffer");kernel.encode(&q,&prefix,@@ -112,10 +115,10 @@ fn run_build_tree_out<B: Backend, T: ArrayElement + Float>(shape.value_heads as u32,shape.head_k_dim as u32,shape.head_v_dim as u32,- &mut encoder,+ &mut command_buffer,);- encoder.end_encoding().submit().wait_until_completed().unwrap();- allocation_to_vec(&o)+ command_buffer.end_encoding().submit().wait_until_completed().unwrap();+ buffer_to_vec(&o)}fn check_shape<T: ArrayElement + Float + std::fmt::Display>(diff --git a/crates/uzu-engine/unit/backends/common/kernel/gdn/tree_verify/prefix_bench.rs b/crates/uzu-engine/unit/backends/common/kernel/gdn/tree_verify/prefix_bench.rsindex d77037895..6dc0edd79 100644--- a/crates/uzu-engine/unit/backends/common/kernel/gdn/tree_verify/prefix_bench.rs+++ b/crates/uzu-engine/unit/backends/common/kernel/gdn/tree_verify/prefix_bench.rs@@ -7,21 +7,21 @@ use uzu_engine_macros::uzu_bench;use crate::{backends::{- common::{Allocation, Backend, Kernels, kernel::BuildTreePrefixKernel},+ common::{Backend, Kernels, kernel::BuildTreePrefixKernel},metal::Metal,},tests::{cold_pool::ColdPool,- helpers::{alloc_allocation, alloc_allocation_with_data},+ helpers::{create_buffer, create_buffer_with_data},matmul::iter_encode_loop_named,util::type_short_name,},};struct TreePrefixBuffers {- trie: Allocation<Metal>,- log_decay: Allocation<Metal>,- prefix: Allocation<Metal>,+ trie: <Metal as Backend>::GlobalBuffer,+ log_decay: <Metal as Backend>::GlobalBuffer,+ prefix: <Metal as Backend>::GlobalBuffer,}#[uzu_bench]@@ -39,9 +39,9 @@ fn bench_build_tree_prefix(c: &mut Criterion) {let log_decay = (0..len).map(|i| -0.001 - (i as f32 * 0.017).sin().abs() * 0.1).collect::<Vec<_>>();let bytes_per_copy = trie.len() * size_of::<u32>() + len * size_of::<f32>() * 2;let mut buffers = ColdPool::new(bytes_per_copy, || TreePrefixBuffers {- trie: alloc_allocation_with_data::<Metal, u32>(&context, &trie),- log_decay: alloc_allocation_with_data::<Metal, f32>(&context, &log_decay),- prefix: alloc_allocation::<Metal, f32>(&context, len),+ trie: create_buffer_with_data::<Metal, u32>(&context, &trie),+ log_decay: create_buffer_with_data::<Metal, f32>(&context, &log_decay),+ prefix: create_buffer::<Metal, f32>(&context, len),});group.throughput(Throughput::Elements((len * tree_size) as u64));@@ -50,7 +50,7 @@ fn bench_build_tree_prefix(c: &mut Criterion) {"{}/Kernel/GDNTreeVerify/BuildTreePrefix/B1_T{tree_size}_HV{value_heads}",type_short_name::<Metal>());- iter_encode_loop_named::<Metal, _>(&context, bencher, &benchmark_path, |encoder| {+ iter_encode_loop_named::<Metal, _>(&context, bencher, &benchmark_path, |command_buffer| {let buffers = buffers.next_mut();kernel.encode(&buffers.trie,@@ -59,7 +59,7 @@ fn bench_build_tree_prefix(c: &mut Criterion) {batch_size as u32,tree_size as u32,value_heads as u32,- encoder,+ command_buffer,);});});diff --git a/crates/uzu-engine/unit/backends/common/kernel/gdn/tree_verify/prefix_test.rs b/crates/uzu-engine/unit/backends/common/kernel/gdn/tree_verify/prefix_test.rsindex 3288f91ce..e5e2e1301 100644--- a/crates/uzu-engine/unit/backends/common/kernel/gdn/tree_verify/prefix_test.rs+++ b/crates/uzu-engine/unit/backends/common/kernel/gdn/tree_verify/prefix_test.rs@@ -4,12 +4,15 @@ use uzu_engine_macros::uzu_test;use crate::{backends::{- common::{Backend, Context, Encoder, Kernels, kernel::BuildTreePrefixKernel},+ common::{+ Backend, CommandBufferEncoding, CommandBufferExecutable, CommandBufferPending, Context, Kernels,+ kernel::BuildTreePrefixKernel,+ },cpu::Cpu,},tests::{assert::assert_eq_float,- helpers::{alloc_allocation, alloc_allocation_with_data, allocation_to_vec, for_each_non_cpu_backend},+ helpers::{buffer_to_vec, create_buffer, create_buffer_with_data, for_each_non_cpu_backend},},};@@ -18,14 +21,14 @@ fn run<B: Backend>(tree_size: usize) -> Vec<f32> {let context = B::Context::new().unwrap();let trie = (0..tree_size as u32).flat_map(|node| [node, tree_size as u32 - 1, node]).collect::<Vec<_>>();let log_decay = (0..tree_size * HEADS).map(|i| -0.001 - i as f32 * 0.0001).collect::<Vec<_>>();- let trie = alloc_allocation_with_data::<B, u32>(&context, &trie);- let log_decay = alloc_allocation_with_data::<B, f32>(&context, &log_decay);- let mut prefix = alloc_allocation::<B, f32>(&context, tree_size * HEADS);+ let trie = create_buffer_with_data::<B, u32>(&context, &trie);+ let log_decay = create_buffer_with_data::<B, f32>(&context, &log_decay);+ let mut prefix = create_buffer::<B, f32>(&context, tree_size * HEADS);let kernel = <B::Kernels as Kernels>::BuildTreePrefixKernel::new(&context).unwrap();- let mut encoder = Encoder::new(context.as_ref()).unwrap();- kernel.encode(&trie, &log_decay, &mut prefix, 1, tree_size as u32, HEADS as u32, &mut encoder);- encoder.end_encoding().submit().wait_until_completed().unwrap();- allocation_to_vec(&prefix)+ let mut command_buffer = context.create_command_buffer(None, None).unwrap();+ kernel.encode(&trie, &log_decay, &mut prefix, 1, tree_size as u32, HEADS as u32, &mut command_buffer);+ command_buffer.end_encoding().submit().wait_until_completed().unwrap();+ buffer_to_vec(&prefix)}#[uzu_test]diff --git a/crates/uzu-engine/unit/backends/common/kernel/gdn/tree_verify/state_advance_test.rs b/crates/uzu-engine/unit/backends/common/kernel/gdn/tree_verify/state_advance_test.rsindex 58eb71e40..b6e37ef4c 100644--- a/crates/uzu-engine/unit/backends/common/kernel/gdn/tree_verify/state_advance_test.rs+++ b/crates/uzu-engine/unit/backends/common/kernel/gdn/tree_verify/state_advance_test.rs@@ -12,19 +12,22 @@ use uzu_engine_macros::uzu_test;use crate::{array::ArrayElement,backends::{- common::{Backend, Context, Encoder, Kernels, kernel::StateAdvanceKernel},+ common::{+ Backend, CommandBufferEncoding, CommandBufferExecutable, CommandBufferPending, Context, Kernels,+ kernel::StateAdvanceKernel,+ },cpu::Cpu,},tests::{assert::assert_eq_float,- helpers::{alloc_allocation_with_data, allocation_to_vec, for_each_non_cpu_backend},+ helpers::{buffer_to_vec, create_buffer_with_data, for_each_non_cpu_backend},},};#[cfg(backend = "metal")]use crate::{backends::metal::Metal,data_type::DataType,- tests::{cold_pool::ColdPool, helpers::allocation_size_bytes, matmul::iter_encode_loop_named},+ tests::{cold_pool::ColdPool, helpers::buffer_size_bytes, matmul::iter_encode_loop_named},};const TREE_SIZE: usize = 128;@@ -53,15 +56,15 @@ fn run<B: Backend, T: ArrayElement + Float>(accepted_indices: &[u32]) -> Vec<f32let beta = (0..scalar_len).map(|i| 0.2 + (i % 5) as f32 * 0.03).collect::<Vec<_>>();let initial_state = (0..state_len).map(|i| (i % 23) as f32 * 0.001 - 0.011).collect::<Vec<_>>();- let k_norm = alloc_allocation_with_data::<B, T>(&context, &k_norm);- let v = alloc_allocation_with_data::<B, T>(&context, &v);- let log_decay = alloc_allocation_with_data::<B, f32>(&context, &log_decay);- let beta = alloc_allocation_with_data::<B, f32>(&context, &beta);+ let k_norm = create_buffer_with_data::<B, T>(&context, &k_norm);+ let v = create_buffer_with_data::<B, T>(&context, &v);+ let log_decay = create_buffer_with_data::<B, f32>(&context, &log_decay);+ let beta = create_buffer_with_data::<B, f32>(&context, &beta);let accepted_len = accepted_indices.len();- let accepted_indices = alloc_allocation_with_data::<B, u32>(&context, accepted_indices);- let mut committed_state = alloc_allocation_with_data::<B, f32>(&context, &initial_state);+ let accepted_indices = create_buffer_with_data::<B, u32>(&context, accepted_indices);+ let mut committed_state = create_buffer_with_data::<B, f32>(&context, &initial_state);- let mut encoder = Encoder::new(context.as_ref()).expect("encoder");+ let mut command_buffer = context.create_command_buffer(None, None).expect("command buffer");kernel.encode(&k_norm,&v,@@ -70,10 +73,10 @@ fn run<B: Backend, T: ArrayElement + Float>(accepted_indices: &[u32]) -> Vec<f32&accepted_indices,&mut committed_state,accepted_len as u32,- &mut encoder,+ &mut command_buffer,);- encoder.end_encoding().submit().wait_until_completed().unwrap();- allocation_to_vec(&committed_state)+ command_buffer.end_encoding().submit().wait_until_completed().unwrap();+ buffer_to_vec(&committed_state)}#[uzu_test]@@ -102,38 +105,43 @@ fn bench_state_advance(c: &mut Criterion) {NUM_K_HEADS as u32,).expect("kernel");- let k_norm = alloc_allocation_with_data::<Metal, bf16>(+ let k_norm = create_buffer_with_data::<Metal, bf16>(&context,&vec![bf16::from_f32(0.001); TREE_SIZE * NUM_K_HEADS * HEAD_DIM],);- let v = alloc_allocation_with_data::<Metal, bf16>(+ let v = create_buffer_with_data::<Metal, bf16>(&context,&vec![bf16::from_f32(0.01); TREE_SIZE * NUM_V_HEADS * HEAD_DIM],);- let log_decay = alloc_allocation_with_data::<Metal, f32>(&context, &vec![-0.01; TREE_SIZE * NUM_V_HEADS]);- let beta = alloc_allocation_with_data::<Metal, f32>(&context, &vec![0.2; TREE_SIZE * NUM_V_HEADS]);+ let log_decay = create_buffer_with_data::<Metal, f32>(&context, &vec![-0.01; TREE_SIZE * NUM_V_HEADS]);+ let beta = create_buffer_with_data::<Metal, f32>(&context, &vec![0.2; TREE_SIZE * NUM_V_HEADS]);let initial_state = vec![0.01; NUM_V_HEADS * HEAD_DIM * HEAD_DIM];let mut group = c.benchmark_group(BENCHMARK);group.sample_size(30).warm_up_time(Duration::from_millis(300)).measurement_time(Duration::from_secs(1));for accepted_len in [1usize, 4, 8, 16] {- let accepted_indices = alloc_allocation_with_data::<Metal, u32>(&context, &PATH[..accepted_len]);- let mut committed_states = ColdPool::new(allocation_size_bytes::<f32>(initial_state.len()), || {- alloc_allocation_with_data::<Metal, f32>(&context, &initial_state)+ let accepted_indices = create_buffer_with_data::<Metal, u32>(&context, &PATH[..accepted_len]);+ let mut committed_states = ColdPool::new(buffer_size_bytes::<f32>(initial_state.len()), || {+ create_buffer_with_data::<Metal, f32>(&context, &initial_state)});group.bench_function(format!("L{accepted_len}"), |bencher| {- iter_encode_loop_named::<Metal, _>(&context, bencher, &format!("{BENCHMARK}/L{accepted_len}"), |encoder| {- kernel.encode(- &k_norm,- &v,- &log_decay,- &beta,- &accepted_indices,- committed_states.next_mut(),- accepted_len as u32,- encoder,- );- });+ iter_encode_loop_named::<Metal, _>(+ &context,+ bencher,+ &format!("{BENCHMARK}/L{accepted_len}"),+ |command_buffer| {+ kernel.encode(+ &k_norm,+ &v,+ &log_decay,+ &beta,+ &accepted_indices,+ committed_states.next_mut(),+ accepted_len as u32,+ command_buffer,+ );+ },+ );});}}diff --git a/crates/uzu-engine/unit/backends/common/kernel/gdn/tree_verify/tree_gram_bench.rs b/crates/uzu-engine/unit/backends/common/kernel/gdn/tree_verify/tree_gram_bench.rsindex d4461df34..99fc7e66c 100644--- a/crates/uzu-engine/unit/backends/common/kernel/gdn/tree_verify/tree_gram_bench.rs+++ b/crates/uzu-engine/unit/backends/common/kernel/gdn/tree_verify/tree_gram_bench.rs@@ -8,13 +8,13 @@ use uzu_engine_macros::uzu_bench;use crate::{backends::{- common::{Allocation, Backend, Context, Kernels, kernel::BuildTreeGramKernel},+ common::{Backend, Context, Kernels, kernel::BuildTreeGramKernel},metal::Metal,},data_type::DataType,tests::{cold_pool::ColdPool,- helpers::{alloc_allocation, alloc_allocation_with_data},+ helpers::{create_buffer, create_buffer_with_data},matmul::iter_encode_loop_named,},};@@ -27,17 +27,17 @@ const TREE_SIZES: &[usize] = &[32, 33, 49, 64, 128, 256, 512];const BATCH_SIZES: &[usize] = &[1, 2, 4, 8];struct TreeGramBuffers {- q: Allocation<Metal>,- k: Allocation<Metal>,- trie: Allocation<Metal>,- prefix: Allocation<Metal>,- beta: Allocation<Metal>,- h0: Allocation<Metal>,- h0_idx: Allocation<Metal>,- a_packed: Allocation<Metal>,- qkd: Allocation<Metal>,- a_inv: Allocation<Metal>,- kh0: Allocation<Metal>,+ q: <Metal as Backend>::GlobalBuffer,+ k: <Metal as Backend>::GlobalBuffer,+ trie: <Metal as Backend>::GlobalBuffer,+ prefix: <Metal as Backend>::GlobalBuffer,+ beta: <Metal as Backend>::GlobalBuffer,+ h0: <Metal as Backend>::GlobalBuffer,+ h0_idx: <Metal as Backend>::GlobalBuffer,+ a_packed: <Metal as Backend>::GlobalBuffer,+ qkd: <Metal as Backend>::GlobalBuffer,+ a_inv: <Metal as Backend>::GlobalBuffer,+ kh0: <Metal as Backend>::GlobalBuffer,}fn reranker_like_trie(@@ -109,17 +109,17 @@ fn make_buffers(let scale = (HEAD_K_DIM as f32).sqrt().recip();(TreeGramBuffers {- q: alloc_allocation_with_data::<Metal, bf16>(context, &q),- k: alloc_allocation_with_data::<Metal, bf16>(context, &k),- trie: alloc_allocation_with_data::<Metal, u32>(context, &trie),- prefix: alloc_allocation_with_data::<Metal, f32>(context, &prefix),- beta: alloc_allocation_with_data::<Metal, f32>(context, &beta),- h0: alloc_allocation_with_data::<Metal, f32>(context, &h0),- h0_idx: alloc_allocation_with_data::<Metal, i32>(context, &h0_idx),- a_packed: alloc_allocation::<Metal, f32>(context, a_len),- qkd: alloc_allocation::<Metal, f32>(context, out_len),- a_inv: alloc_allocation::<Metal, f32>(context, a_inv_len),- kh0: alloc_allocation::<Metal, f32>(context, kh0_len),+ q: create_buffer_with_data::<Metal, bf16>(context, &q),+ k: create_buffer_with_data::<Metal, bf16>(context, &k),+ trie: create_buffer_with_data::<Metal, u32>(context, &trie),+ prefix: create_buffer_with_data::<Metal, f32>(context, &prefix),+ beta: create_buffer_with_data::<Metal, f32>(context, &beta),+ h0: create_buffer_with_data::<Metal, f32>(context, &h0),+ h0_idx: create_buffer_with_data::<Metal, i32>(context, &h0_idx),+ a_packed: create_buffer::<Metal, f32>(context, a_len),+ qkd: create_buffer::<Metal, f32>(context, out_len),+ a_inv: create_buffer::<Metal, f32>(context, a_inv_len),+ kh0: create_buffer::<Metal, f32>(context, kh0_len),},scale,)@@ -178,7 +178,7 @@ fn bench_build_tree_gram(c: &mut Criterion) {make_buffers(&context, batch_size, tree_size).0});group.bench_function(benchmark_id, |bencher| {- iter_encode_loop_named::<Metal, _>(context.as_ref(), bencher, &benchmark_path, |encoder| {+ iter_encode_loop_named::<Metal, _>(context.as_ref(), bencher, &benchmark_path, |command_buffer| {let buffers = buffers.next_mut();kernel.encode(&buffers.q,@@ -199,7 +199,7 @@ fn bench_build_tree_gram(c: &mut Criterion) {VALUE_HEADS as u32,HEAD_K_DIM as u32,HEAD_V_DIM as u32,- encoder,+ command_buffer,);});});diff --git a/crates/uzu-engine/unit/backends/common/kernel/gdn/tree_verify/tree_gram_test.rs b/crates/uzu-engine/unit/backends/common/kernel/gdn/tree_verify/tree_gram_test.rsindex 6359fed74..b38e7602c 100644--- a/crates/uzu-engine/unit/backends/common/kernel/gdn/tree_verify/tree_gram_test.rs+++ b/crates/uzu-engine/unit/backends/common/kernel/gdn/tree_verify/tree_gram_test.rs@@ -7,14 +7,17 @@ use uzu_engine_macros::uzu_test;use crate::{array::ArrayElement,backends::{- common::{Backend, Context, Encoder, Kernels, kernel::BuildTreeGramKernel},+ common::{+ Backend, CommandBufferEncoding, CommandBufferExecutable, CommandBufferPending, Context, Kernels,+ kernel::BuildTreeGramKernel,+ },cpu::Cpu,metal::Metal,},data_type::DataType,tests::{assert::assert_eq_float,- helpers::{alloc_allocation, alloc_allocation_with_data, allocation_to_vec, for_each_non_cpu_backend},+ helpers::{buffer_to_vec, create_buffer, create_buffer_with_data, for_each_non_cpu_backend},},};@@ -75,23 +78,23 @@ fn get_output<B: Backend, T: ArrayElement + Float>(let a_len = BATCH_SIZE * VALUE_HEADS * num_blocks * num_blocks.div_ceil(2) * 16 * 32;let a_inv_len = BATCH_SIZE * VALUE_HEADS * num_blocks * 16 * 16;let kh0_len = BATCH_SIZE * tree_size * VALUE_HEADS * HEAD_V_DIM;- let q = alloc_allocation_with_data::<B, T>(&context, q);- let k = alloc_allocation_with_data::<B, T>(&context, k);- let trie = alloc_allocation_with_data::<B, u32>(&context, trie);- let prefix = alloc_allocation_with_data::<B, f32>(&context, prefix);- let beta = alloc_allocation_with_data::<B, f32>(&context, beta);- let h0 = alloc_allocation_with_data::<B, f32>(&context, h0);- let h0_idx = alloc_allocation_with_data::<B, i32>(&context, h0_idx);+ let q = create_buffer_with_data::<B, T>(&context, q);+ let k = create_buffer_with_data::<B, T>(&context, k);+ let trie = create_buffer_with_data::<B, u32>(&context, trie);+ let prefix = create_buffer_with_data::<B, f32>(&context, prefix);+ let beta = create_buffer_with_data::<B, f32>(&context, beta);+ let h0 = create_buffer_with_data::<B, f32>(&context, h0);+ let h0_idx = create_buffer_with_data::<B, i32>(&context, h0_idx);// The GPU only writes packed-A tiles touching the block lower triangle;// zero-init so CPU and GPU buffers stay comparable elsewhere.- let mut a_packed = alloc_allocation_with_data::<B, f32>(&context, &vec![0.0f32; a_len]);- let mut qkd = alloc_allocation::<B, f32>(&context, output_len);- let mut a_inv = alloc_allocation::<B, f32>(&context, a_inv_len);+ let mut a_packed = create_buffer_with_data::<B, f32>(&context, &vec![0.0f32; a_len]);+ let mut qkd = create_buffer::<B, f32>(&context, output_len);+ let mut a_inv = create_buffer::<B, f32>(&context, a_inv_len);// kh0 is only written for batches with h0_idx >= 0; zero-init so CPU and GPU// outputs stay comparable on the skipped batch.- let mut kh0 = alloc_allocation_with_data::<B, f32>(&context, &vec![0.0f32; kh0_len]);+ let mut kh0 = create_buffer_with_data::<B, f32>(&context, &vec![0.0f32; kh0_len]);- let mut encoder = Encoder::new(context.as_ref()).expect("Failed to create encoder");+ let mut command_buffer = context.create_command_buffer(None, None).expect("Failed to create command buffer");kernel.encode(&q,&k,@@ -111,11 +114,11 @@ fn get_output<B: Backend, T: ArrayElement + Float>(VALUE_HEADS as u32,HEAD_K_DIM as u32,HEAD_V_DIM as u32,- &mut encoder,+ &mut command_buffer,);- encoder.end_encoding().submit().wait_until_completed().unwrap();+ command_buffer.end_encoding().submit().wait_until_completed().unwrap();- (allocation_to_vec(&a_packed), allocation_to_vec(&qkd), allocation_to_vec(&a_inv), allocation_to_vec(&kh0))+ (buffer_to_vec(&a_packed), buffer_to_vec(&qkd), buffer_to_vec(&a_inv), buffer_to_vec(&kh0))}fn check_type<T: ArrayElement + Float>(diff --git a/crates/uzu-engine/unit/backends/common/kernel/gdn/tree_verify/tree_update_solve_bench.rs b/crates/uzu-engine/unit/backends/common/kernel/gdn/tree_verify/tree_update_solve_bench.rsindex 3fef30f46..ac165afe3 100644--- a/crates/uzu-engine/unit/backends/common/kernel/gdn/tree_verify/tree_update_solve_bench.rs+++ b/crates/uzu-engine/unit/backends/common/kernel/gdn/tree_verify/tree_update_solve_bench.rs@@ -8,13 +8,13 @@ use uzu_engine_macros::uzu_bench;use crate::{backends::{- common::{Allocation, Backend, Context, Encoder, Kernels, kernel::TreeUpdateSolveKernel},+ common::{Backend, CommandBuffer, Context, Kernels, kernel::TreeUpdateSolveKernel},metal::Metal,},data_type::DataType,tests::{cold_pool::ColdPool,- helpers::{alloc_allocation, alloc_allocation_with_data},+ helpers::{create_buffer, create_buffer_with_data},matmul::iter_encode_loop_named,},};@@ -53,14 +53,14 @@ const BENCH_SHAPES: &[(usize, usize)] = &[];struct TreeUpdateSolveBuffers {- kh0: Allocation<Metal>,- v: Allocation<Metal>,- prefix: Allocation<Metal>,- beta: Allocation<Metal>,- a: Allocation<Metal>,- a_inv: Allocation<Metal>,- h0_idx: Allocation<Metal>,- u: Allocation<Metal>,+ kh0: <Metal as Backend>::GlobalBuffer,+ v: <Metal as Backend>::GlobalBuffer,+ prefix: <Metal as Backend>::GlobalBuffer,+ beta: <Metal as Backend>::GlobalBuffer,+ a: <Metal as Backend>::GlobalBuffer,+ a_inv: <Metal as Backend>::GlobalBuffer,+ h0_idx: <Metal as Backend>::GlobalBuffer,+ u: <Metal as Backend>::GlobalBuffer,}fn matrix_value(@@ -128,7 +128,7 @@ fn make_buffers(}}).collect::<Vec<_>>();- let a = alloc_allocation_with_data::<Metal, f32>(context, &a_f32);+ let a = create_buffer_with_data::<Metal, f32>(context, &a_f32);let inv_len = batch_size * NUM_V_HEADS * tree_size.div_ceil(BT) * BT * BT;let a_inv = (0..inv_len).map(|i| {@@ -142,14 +142,14 @@ fn make_buffers(let h0_idx = (0..batch_size).map(|i| i as i32).collect::<Vec<_>>();TreeUpdateSolveBuffers {- kh0: alloc_allocation_with_data::<Metal, f32>(context, &kh0),- v: alloc_allocation_with_data::<Metal, bf16>(context, &v),- prefix: alloc_allocation_with_data::<Metal, f32>(context, &prefix),- beta: alloc_allocation_with_data::<Metal, f32>(context, &beta),+ kh0: create_buffer_with_data::<Metal, f32>(context, &kh0),+ v: create_buffer_with_data::<Metal, bf16>(context, &v),+ prefix: create_buffer_with_data::<Metal, f32>(context, &prefix),+ beta: create_buffer_with_data::<Metal, f32>(context, &beta),a,- a_inv: alloc_allocation_with_data::<Metal, f32>(context, &a_inv),- h0_idx: alloc_allocation_with_data::<Metal, i32>(context, &h0_idx),- u: alloc_allocation::<Metal, f32>(context, u_len),+ a_inv: create_buffer_with_data::<Metal, f32>(context, &a_inv),+ h0_idx: create_buffer_with_data::<Metal, i32>(context, &h0_idx),+ u: create_buffer::<Metal, f32>(context, u_len),}}@@ -196,9 +196,9 @@ fn bench_tree_update_solve(c: &mut Criterion) {group.throughput(Throughput::Elements((batch_size * tree_size * NUM_V_HEADS * HEAD_V_DIM) as u64));group.bench_function(benchmark_id, |bencher| {- iter_encode_loop_named::<Metal, _>(context.as_ref(), bencher, &benchmark_path, |encoder| {+ iter_encode_loop_named::<Metal, _>(context.as_ref(), bencher, &benchmark_path, |command_buffer| {let buffers = buffers.next_mut();- encode(&kernel, buffers, batch_size, tree_size, encoder);+ encode(&kernel, buffers, batch_size, tree_size, command_buffer);});});}@@ -212,7 +212,7 @@ fn encode(buffers: &mut TreeUpdateSolveBuffers,batch_size: usize,tree_size: usize,- encoder: &mut Encoder<Metal>,+ command_buffer: &mut <<Metal as Backend>::CommandBuffer as CommandBuffer>::Encoding,) {kernel.encode(Some(&buffers.kh0),@@ -227,6 +227,6 @@ fn encode(tree_size as u32,NUM_V_HEADS as u32,HEAD_V_DIM as u32,- encoder,+ command_buffer,);}diff --git a/crates/uzu-engine/unit/backends/common/kernel/gdn/tree_verify/tree_update_solve_test.rs b/crates/uzu-engine/unit/backends/common/kernel/gdn/tree_verify/tree_update_solve_test.rsindex c3d55312d..c340afd7a 100644--- a/crates/uzu-engine/unit/backends/common/kernel/gdn/tree_verify/tree_update_solve_test.rs+++ b/crates/uzu-engine/unit/backends/common/kernel/gdn/tree_verify/tree_update_solve_test.rs@@ -6,13 +6,16 @@ use uzu_engine_macros::uzu_test;use crate::{array::ArrayElement,backends::{- common::{Backend, Context, Encoder, Kernels, kernel::TreeUpdateSolveKernel},+ common::{+ Backend, CommandBufferEncoding, CommandBufferExecutable, CommandBufferPending, Context, Kernels,+ kernel::TreeUpdateSolveKernel,+ },cpu::Cpu,},data_type::DataType,tests::{assert::assert_eq_float,- helpers::{alloc_allocation, alloc_allocation_with_data, allocation_to_vec, for_each_non_cpu_backend},+ helpers::{buffer_to_vec, create_buffer, create_buffer_with_data, for_each_non_cpu_backend},},};@@ -152,16 +155,16 @@ fn run_case<B: Backend, T: ArrayElement + Copy>((0..batch_size).map(|batch| batch as i32).collect::<Vec<_>>()};- let kh0 = alloc_allocation_with_data::<B, f32>(&context, &kh0);- let v = alloc_allocation_with_data::<B, T>(&context, &v);- let prefix = alloc_allocation_with_data::<B, f32>(&context, &prefix);- let beta = alloc_allocation_with_data::<B, f32>(&context, &beta);- let a = alloc_allocation_with_data::<B, f32>(&context, &a_f32);- let a_inv = alloc_allocation_with_data::<B, f32>(&context, &a_inv);- let h0_idx = alloc_allocation_with_data::<B, i32>(&context, &h0_idx);- let mut u = alloc_allocation::<B, f32>(&context, u_len);+ let kh0 = create_buffer_with_data::<B, f32>(&context, &kh0);+ let v = create_buffer_with_data::<B, T>(&context, &v);+ let prefix = create_buffer_with_data::<B, f32>(&context, &prefix);+ let beta = create_buffer_with_data::<B, f32>(&context, &beta);+ let a = create_buffer_with_data::<B, f32>(&context, &a_f32);+ let a_inv = create_buffer_with_data::<B, f32>(&context, &a_inv);+ let h0_idx = create_buffer_with_data::<B, i32>(&context, &h0_idx);+ let mut u = create_buffer::<B, f32>(&context, u_len);- let mut encoder = Encoder::new(context.as_ref()).expect("encoder");+ let mut command_buffer = context.create_command_buffer(None, None).expect("command buffer");kernel.encode(use_h0.then_some(&kh0),&v,@@ -175,11 +178,11 @@ fn run_case<B: Backend, T: ArrayElement + Copy>(case.tree_size,case.num_v_heads,case.head_v_dim,- &mut encoder,+ &mut command_buffer,);- encoder.end_encoding().submit().wait_until_completed().unwrap();+ command_buffer.end_encoding().submit().wait_until_completed().unwrap();- allocation_to_vec(&u)+ buffer_to_vec(&u)}#[uzu_test]diff --git a/crates/uzu-engine/unit/backends/common/kernel/logit_transform_test.rs b/crates/uzu-engine/unit/backends/common/kernel/logit_transform_test.rsindex 8e196a627..519858c70 100644--- a/crates/uzu-engine/unit/backends/common/kernel/logit_transform_test.rs+++ b/crates/uzu-engine/unit/backends/common/kernel/logit_transform_test.rs@@ -7,13 +7,16 @@ use uzu_engine_macros::uzu_test;use crate::{array::ArrayElement,backends::{- common::{Backend, Context, Encoder, Kernels, kernel::LogitTransformKernel},+ common::{+ Backend, CommandBufferEncoding, CommandBufferExecutable, CommandBufferPending, Context, Kernels,+ kernel::LogitTransformKernel,+ },cpu::Cpu,},data_type::DataType,tests::{assert::assert_eq_float,- helpers::{alloc_allocation_with_data, allocation_to_vec, for_each_non_cpu_backend},+ helpers::{buffer_to_vec, create_buffer_with_data, for_each_non_cpu_backend},},};@@ -27,12 +30,12 @@ fn get_output<T: ArrayElement + Float, B: Backend>(<<B as Backend>::Kernels as Kernels>::LogitTransformKernel::new(&context, T::data_type(), soft_cap.is_some()).expect("Failed to create LogitTransformKernel");- let mut logits_allocation = alloc_allocation_with_data::<B, T>(&context, logits);- let mut encoder = Encoder::new(context.as_ref()).expect("Failed to create encoder");- kernel.encode(&mut logits_allocation, logits.len() as u32, scale, soft_cap.unwrap_or(0.0), &mut encoder);- encoder.end_encoding().submit().wait_until_completed().unwrap();+ let mut logits_buffer = create_buffer_with_data::<B, T>(&context, logits);+ let mut command_buffer = context.create_command_buffer(None, None).expect("Failed to create command buffer");+ kernel.encode(&mut logits_buffer, logits.len() as u32, scale, soft_cap.unwrap_or(0.0), &mut command_buffer);+ command_buffer.end_encoding().submit().wait_until_completed().unwrap();- allocation_to_vec::<B, T>(&logits_allocation)+ buffer_to_vec::<B, T>(&logits_buffer)}fn test_logit_transform<T: ArrayElement + Float + Display>(diff --git a/crates/uzu-engine/unit/backends/common/kernel/matmul/a8w_bench.rs b/crates/uzu-engine/unit/backends/common/kernel/matmul/a8w_bench.rsindex c8b0d9c12..962552ffc 100644--- a/crates/uzu-engine/unit/backends/common/kernel/matmul/a8w_bench.rs+++ b/crates/uzu-engine/unit/backends/common/kernel/matmul/a8w_bench.rs@@ -9,7 +9,7 @@ use uzu_engine_macros::uzu_bench;use crate::{backends::{common::{- Allocation, Backend, Encoder,+ Backend, BufferMut, CommandBuffer, CommandBufferEncoding,gpu_types::{HADAMARD_TRANSFORM_BLOCK_SIZE, QuantizationMethod, QuantizationMode},kernel::{ActivationQuantization, ActivationTransform, Kernels,@@ -24,7 +24,7 @@ use crate::{},data_type::DataType,tests::{- helpers::{alloc_allocation, alloc_allocation_with_data},+ helpers::{create_buffer, create_buffer_with_data},matmul::{QuantInput, iter_encode_loop_named, qwen3_layer_shapes, transpose_metadata},util::{shared_metal_context, type_short_name},},@@ -50,16 +50,16 @@ impl BenchPath {}struct BenchmarkData {- unsigned_weights: Allocation<Metal>,- a8_weights: Allocation<Metal>,- weight_scales: Allocation<Metal>,+ unsigned_weights: <Metal as Backend>::GlobalBuffer,+ a8_weights: <Metal as Backend>::GlobalBuffer,+ weight_scales: <Metal as Backend>::GlobalBuffer,/// The `[G, N]` scale plane the A8 MXU route reads.- group_major_weight_scales: Allocation<Metal>,- activations: Allocation<Metal>,- rht_factors: Allocation<Metal>,- a_working: Allocation<Metal>,- a_int8: Allocation<Metal>,- a_scales: Allocation<Metal>,+ group_major_weight_scales: <Metal as Backend>::GlobalBuffer,+ activations: <Metal as Backend>::GlobalBuffer,+ rht_factors: <Metal as Backend>::GlobalBuffer,+ a_working: <Metal as Backend>::GlobalBuffer,+ a_int8: <Metal as Backend>::GlobalBuffer,+ a_scales: <Metal as Backend>::GlobalBuffer,m: u32,k: u32,n: u32,@@ -80,13 +80,13 @@ impl BenchmarkData {let input = QuantInput::<bf16>::new(m, k, n, group_size, bits, QuantizationMethod::ScaleSymmetric, seed);let input = input.with_prepared_a(ACTIVATION_SCALE_GROUP_SIZE, None);- let unsigned_weights = alloc_allocation_with_data::<Metal, u32>(context, &input.w_packed);+ let unsigned_weights = create_buffer_with_data::<Metal, u32>(context, &input.w_packed);let a8_weights = input.weights_for_upload();- let a8_weights = alloc_allocation_with_data::<Metal, u32>(context, &a8_weights);- let weight_scales = alloc_allocation_with_data::<Metal, bf16>(context, &input.scales);- let mut group_major_weight_scales = alloc_allocation_with_data::<Metal, bf16>(context, &input.scales);+ let a8_weights = create_buffer_with_data::<Metal, u32>(context, &a8_weights);+ let weight_scales = create_buffer_with_data::<Metal, bf16>(context, &input.scales);+ let mut group_major_weight_scales = create_buffer_with_data::<Metal, bf16>(context, &input.scales);transpose_metadata(group_major_weight_scales.as_slice_mut(), n, k.div_ceil(group_size), 16);- let activations = alloc_allocation_with_data::<Metal, bf16>(context, &input.x);+ let activations = create_buffer_with_data::<Metal, bf16>(context, &input.x);let rht: Vec<i32> = (0..k).map(|index| {if index % 3 == 0 {@@ -96,7 +96,7 @@ impl BenchmarkData {}}).collect();- let rht_factors = alloc_allocation_with_data::<Metal, i32>(context, &rht);+ let rht_factors = create_buffer_with_data::<Metal, i32>(context, &rht);let groups = k / group_size;Self {@@ -106,9 +106,9 @@ impl BenchmarkData {group_major_weight_scales,activations,rht_factors,- a_working: alloc_allocation::<Metal, bf16>(context, (m * k) as usize),- a_int8: alloc_allocation::<Metal, i8>(context, (m * k) as usize),- a_scales: alloc_allocation::<Metal, f32>(context, (m * groups) as usize),+ a_working: create_buffer::<Metal, bf16>(context, (m * k) as usize),+ a_int8: create_buffer::<Metal, i8>(context, (m * k) as usize),+ a_scales: create_buffer::<Metal, f32>(context, (m * groups) as usize),m,k,n,@@ -121,10 +121,17 @@ impl BenchmarkData {}}- fn bf16_arguments<'a>(+ fn bf16_arguments<'a, D: BufferMut<Backend = Metal>>(&'a self,- output: &'a mut Allocation<Metal>,- ) -> MatmulArguments<'a, 'a, 'a, Metal, &'a Allocation<Metal>> {+ output: D,+ ) -> MatmulArguments<+ 'a,+ Metal,+ &'a <Metal as Backend>::GlobalBuffer,+ &'a <Metal as Backend>::GlobalBuffer,+ D,+ &'a <Metal as Backend>::GlobalBuffer,+ > {MatmulArguments {a: MatmulA::FullPrecision {values: &self.a_working,@@ -151,15 +158,14 @@ impl BenchmarkData {}}-#[allow(clippy::too_many_arguments)]fn encode_step(path: BenchPath,data: &mut BenchmarkData,- output: &mut Allocation<Metal>,+ output: impl BufferMut<Backend = Metal>,prepare: &ActivationTransform<Metal>,hadamard: &ActivationTransform<Metal>,matmul: &mut MetalMatmul,- encoder: &mut Encoder<Metal>,+ command_buffer: &mut <<Metal as Backend>::CommandBuffer as CommandBuffer>::Encoding,) {match path {BenchPath::A8GemmMxu => {@@ -167,52 +173,57 @@ fn encode_step(&data.activations,&mut data.a_int8,&mut data.a_scales,- None::<&mut Allocation<Metal>>,+ None::<&mut <Metal as Backend>::GlobalBuffer>,&data.rht_factors,data.m,data.k,- encoder,+ command_buffer,);- let args: MatmulArguments<'_, '_, '_, Metal, &Allocation<Metal>> = MatmulArguments {- a: MatmulA::Int8Symmetric {- values: &data.a_int8,- scales: &data.a_scales,- group_sums: None,- scale_group_size: 128,- code_layout: Int8CodeLayout::for_right_bits(DataType::from(data.mode).size_in_bits() as u32)- .expect("W4/W8 benchmark"),- },- b: MatmulB::Quantized(QuantizedB {- codes: &data.a8_weights,- scales: &data.group_major_weight_scales,- correction: QuantizedCorrection::Symmetric,- params: QuantParams::new(QuantParamsLayout::GroupOutput, data.n, data.k.div_ceil(data.group_size)),- mode: data.mode,- group_size: data.group_size,- signed_codes: !matches!(data.mode, QuantizationMode::U4),- }),- b_leading_dimension: None,- b_transpose: true,- d: output,- d_transform: MatmulDOps::none(),- gather_indices: None,- m: data.m,- n: data.n,- k: data.k,- };- matmul.encode_with_gemm_engine(args, GemmEngine::Mxu, encoder).expect("a8 gemm mxu encode");+ let args =+ MatmulArguments::<Metal, _, &<Metal as Backend>::GlobalBuffer, _, &<Metal as Backend>::GlobalBuffer> {+ a: MatmulA::Int8Symmetric {+ values: &data.a_int8,+ scales: &data.a_scales,+ group_sums: None,+ scale_group_size: 128,+ code_layout: Int8CodeLayout::for_right_bits(DataType::from(data.mode).size_in_bits() as u32)+ .expect("W4/W8 benchmark"),+ },+ b: MatmulB::Quantized(QuantizedB {+ codes: &data.a8_weights,+ scales: &data.group_major_weight_scales,+ correction: QuantizedCorrection::Symmetric,+ params: QuantParams::new(+ QuantParamsLayout::GroupOutput,+ data.n,+ data.k.div_ceil(data.group_size),+ ),+ mode: data.mode,+ group_size: data.group_size,+ signed_codes: !matches!(data.mode, QuantizationMode::U4),+ }),+ b_leading_dimension: None,+ b_transpose: true,+ d: output,+ d_transform: MatmulDOps::none(),+ gather_indices: None,+ m: data.m,+ n: data.n,+ k: data.k,+ };+ matmul.encode_with_gemm_engine(args, GemmEngine::Mxu, command_buffer).expect("a8 gemm mxu encode");},BenchPath::Bf16GemmMxu => {- encoder.encode_copy(&data.activations, .., &mut data.a_working, ..);- hadamard.encode_fp_in_place(&mut data.a_working, &data.rht_factors, None, data.m, data.k, encoder);+ command_buffer.encode_copy(&data.activations, &mut data.a_working);+ hadamard.encode_fp_in_place(&mut data.a_working, &data.rht_factors, None, data.m, data.k, command_buffer);let args = data.bf16_arguments(output);- matmul.encode_with_gemm_engine(args, GemmEngine::Mxu, encoder).expect("bf16 gemm mxu encode");+ matmul.encode_with_gemm_engine(args, GemmEngine::Mxu, command_buffer).expect("bf16 gemm mxu encode");},BenchPath::Bf16Routed => {- encoder.encode_copy(&data.activations, .., &mut data.a_working, ..);- hadamard.encode_fp_in_place(&mut data.a_working, &data.rht_factors, None, data.m, data.k, encoder);+ command_buffer.encode_copy(&data.activations, &mut data.a_working);+ hadamard.encode_fp_in_place(&mut data.a_working, &data.rht_factors, None, data.m, data.k, command_buffer);let args = data.bf16_arguments(output);- matmul.encode(args, encoder).expect("routed bf16 matmul encode");+ matmul.encode(args, command_buffer).expect("routed bf16 matmul encode");},}}@@ -242,7 +253,7 @@ fn bench_bits(HADAMARD_TRANSFORM_BLOCK_SIZE,0xA8_00 ^ u64::from(bits) ^ k as u64 ^ n as u64,);- let mut output = alloc_allocation::<Metal, bf16>(context, (m * n) as usize);+ let mut output = create_buffer::<Metal, bf16>(context, (m * n) as usize);let shape_label = format!("{layer}_m{m}_k{k}_n{n}");let paths = [BenchPath::A8GemmMxu, BenchPath::Bf16GemmMxu, BenchPath::Bf16Routed];@@ -252,8 +263,8 @@ fn bench_bits(group.bench_function(BenchmarkId::new(path.label(), &shape_label), |bench| {let benchmark_path =format!("{}/Kernel/A8W/w{bits}/{}/{shape_label}", type_short_name::<Metal>(), path.label());- iter_encode_loop_named::<Metal, _>(context, bench, &benchmark_path, |encoder| {- encode_step(path, &mut data, &mut output, prepare, hadamard, &mut matmul, encoder);+ iter_encode_loop_named::<Metal, _>(context, bench, &benchmark_path, |command_buffer| {+ encode_step(path, &mut data, &mut output, prepare, hadamard, &mut matmul, command_buffer);});});}diff --git a/crates/uzu-engine/unit/backends/common/kernel/matmul/gemm_bench.rs b/crates/uzu-engine/unit/backends/common/kernel/matmul/gemm_bench.rsindex 66fe353b9..551730e75 100644--- a/crates/uzu-engine/unit/backends/common/kernel/matmul/gemm_bench.rs+++ b/crates/uzu-engine/unit/backends/common/kernel/matmul/gemm_bench.rs@@ -17,7 +17,7 @@ use crate::{metal::{GemmEngine, Metal},},tests::{- helpers::alloc_allocation,+ helpers::create_buffer,matmul::{bench_fp_gemm_shapes, iter_encode_loop},util::type_short_name,},@@ -45,12 +45,12 @@ fn bench_gemm(c: &mut Criterion) {for shape in bench_fp_gemm_shapes() {let (m, k, n) = (shape.m, shape.k, shape.n);- let a = alloc_allocation::<Metal, bf16>(&context, m as usize * k as usize);- let b_weights = alloc_allocation::<Metal, bf16>(&context, n as usize * k as usize);- let mut d = alloc_allocation::<Metal, bf16>(&context, m as usize * n as usize);+ let a = create_buffer::<Metal, bf16>(&context, m as usize * k as usize);+ let b_weights = create_buffer::<Metal, bf16>(&context, n as usize * k as usize);+ let mut d = create_buffer::<Metal, bf16>(&context, m as usize * n as usize);group.throughput(Throughput::Elements(2 * u64::from(m) * u64::from(k) * u64::from(n)));group.bench_function(BenchmarkId::new("BF16", shape.to_string()), |b| {- iter_encode_loop::<Metal, _>(&context, b, |encoder| {+ iter_encode_loop::<Metal, _>(&context, b, |command_buffer| {kernel.encode_with_gemm_engine(MatmulArguments {@@ -65,13 +65,13 @@ fn bench_gemm(c: &mut Criterion) {b_transpose: true,d: &mut d,d_transform: MatmulDOps::none(),- gather_indices: None,+ gather_indices: None::<&<Metal as Backend>::GlobalBuffer>,m,n,k,},engine,- encoder,+ command_buffer,).expect("encode_plan failed");});diff --git a/crates/uzu-engine/unit/backends/common/kernel/matmul/gemv_test.rs b/crates/uzu-engine/unit/backends/common/kernel/matmul/gemv_test.rsindex 3f6154796..2ef96a40b 100644--- a/crates/uzu-engine/unit/backends/common/kernel/matmul/gemv_test.rs+++ b/crates/uzu-engine/unit/backends/common/kernel/matmul/gemv_test.rs@@ -9,7 +9,7 @@ use crate::{array::ArrayElement,backends::{common::{- Allocation, Backend, Context, Encoder,+ Backend, BufferRef, CommandBufferEncoding, CommandBufferExecutable, CommandBufferPending, Context,gpu_types::QuantizationMethod,kernel::{Kernels,@@ -20,7 +20,7 @@ use crate::{},tests::{assert::assert_eq_float,- helpers::{alloc_allocation, alloc_allocation_with_data, allocation_to_vec, for_each_non_cpu_backend},+ helpers::{buffer_to_vec, create_buffer, create_buffer_with_data, for_each_non_cpu_backend},matmul::{QuantBuffers, QuantInput},},};@@ -63,21 +63,21 @@ fn get_test_data<T: ArrayElement + Float>(}// Encode one GEMV (dense, or a per-row B-row gather when `gather_indices` is set) and copy out.-fn run_gemv<'a, B: Backend, T: ArrayElement + Float>(+fn run_gemv<B: Backend, T: ArrayElement + Float>(context: &B::Context,- a: &'a Allocation<B>,- b: MatmulB<'a, B>,- gather_indices: Option<&'a Allocation<B>>,+ a: impl BufferRef<Backend = B>,+ b: MatmulB<impl BufferRef<Backend = B>>,+ gather_indices: Option<impl BufferRef<Backend = B>>,m: usize,n_out: usize,k: usize,soft_cap: Option<f32>,) -> Vec<T> {- let mut d = alloc_allocation::<B, T>(context, m * n_out);+ let mut d = create_buffer::<B, T>(context, m * n_out);let mut kernel =<B::Kernels as Kernels>::MatmulKernel::new(context, T::data_type(), T::data_type(), T::data_type()).expect("MatmulKernel");- let mut encoder = Encoder::new(context).expect("encoder");+ let mut command_buffer = context.create_command_buffer(None, None).expect("command buffer");kernel.encode(MatmulArguments {@@ -98,18 +98,18 @@ fn run_gemv<'a, B: Backend, T: ArrayElement + Float>(n: n_out as u32,k: k as u32,},- &mut encoder,+ &mut command_buffer,).expect("encode failed");- encoder.end_encoding().submit().wait_until_completed().unwrap();- allocation_to_vec::<B, T>(&d)+ command_buffer.end_encoding().submit().wait_until_completed().unwrap();+ buffer_to_vec::<B, T>(&d)}fn get_output<T: ArrayElement + Float, B: Backend>(input: &Input<T>) -> Vec<T> {let context = B::Context::new().expect("Failed to create Context");- let a = alloc_allocation_with_data::<B, T>(&context, &input.a);- let weights = alloc_allocation_with_data::<B, T>(&context, &input.b);- let ids = input.ids.as_ref().map(|ids| alloc_allocation_with_data::<B, u32>(&context, ids));+ let a = create_buffer_with_data::<B, T>(&context, &input.a);+ let weights = create_buffer_with_data::<B, T>(&context, &input.b);+ let ids = input.ids.as_ref().map(|ids| create_buffer_with_data::<B, u32>(&context, ids));run_gemv::<B, T>(&context,&a,@@ -172,7 +172,7 @@ fn group_major_gemv_bf16(&context,&buffers.x,buffers.matmul_b(&input),- None,+ None::<&<Metal as Backend>::GlobalBuffer>,1,input.n as usize,input.k as usize,@@ -270,10 +270,10 @@ fn quant_gather_case(check_gather!(m, vocab, ids, ids_per_row, eps, |B| {let context = <B as Backend>::Context::new().expect("context");let buffers = QuantBuffers::<B, bf16>::allocate(&context, &input);- let ids_alloc = alloc_allocation_with_data::<B, u32>(&context, &ids);+ let ids_alloc = create_buffer_with_data::<B, u32>(&context, &ids);let b = || buffers.matmul_b(&input);(- run_gemv::<B, bf16>(&context, &buffers.x, b(), None, m, vocab, k, None),+ run_gemv::<B, bf16>(&context, &buffers.x, b(), None::<&<B as Backend>::GlobalBuffer>, m, vocab, k, None),run_gemv::<B, bf16>(&context, &buffers.x, b(), Some(&ids_alloc), m, ids_per_row, k, None),)});diff --git a/crates/uzu-engine/unit/backends/common/kernel/matmul/quant_dispatch_test.rs b/crates/uzu-engine/unit/backends/common/kernel/matmul/quant_dispatch_test.rsindex a1c2daf04..728ba43de 100644--- a/crates/uzu-engine/unit/backends/common/kernel/matmul/quant_dispatch_test.rs+++ b/crates/uzu-engine/unit/backends/common/kernel/matmul/quant_dispatch_test.rs@@ -16,7 +16,7 @@ use crate::{array::ArrayElement,backends::{common::{- Backend, Context, Encoder,+ Backend, CommandBufferEncoding, CommandBufferExecutable, CommandBufferPending, Context,gpu_types::{QuantizationMethod, QuantizationMode, gemm::GemmDTransform},kernel::{Kernels,@@ -28,7 +28,7 @@ use crate::{metal::{GemmEngine, Metal, MetalContext},},tests::{- helpers::allocation_to_vec,+ helpers::buffer_to_vec,matmul::{QuantBuffers, QuantInput,harness::TestDispatch,@@ -196,7 +196,7 @@ fn parity_bf16_gs32_4bit_mlx_with_bias() {let bias_t: Vec<bf16> = bias_f32.iter().map(|&v| bf16::from_f32(v)).collect();let mut buffers = QuantBuffers::<Metal, bf16>::allocate(&context, &input);- let bias_pp_buf = crate::tests::helpers::alloc_allocation_with_data::<Metal, bf16>(&context, &bias_t);+ let bias_pp_buf = crate::tests::helpers::create_buffer_with_data::<Metal, bf16>(&context, &bias_t);let mut matmul = <<Metal as Backend>::Kernels as Kernels>::MatmulKernel::new(&context,bf16::data_type(),@@ -205,15 +205,15 @@ fn parity_bf16_gs32_4bit_mlx_with_bias() {).expect("MatmulMetalKernel");- let mut encoder = Encoder::<Metal>::new(&context).expect("encoder");+ let mut command_buffer = context.create_command_buffer(None, None).unwrap();let mut args = quant_arguments(&mut buffers, &input);args.d_transform = MatmulDOps {bias: Some(&bias_pp_buf),..MatmulDOps::none()};- matmul.encode_with_gemm_engine(args, GemmEngine::Simdgroup, &mut encoder).expect("encode quant with bias");- encoder.end_encoding().submit().wait_until_completed().unwrap();- let actual = allocation_to_vec::<Metal, bf16>(&buffers.y);+ matmul.encode_with_gemm_engine(args, GemmEngine::Simdgroup, &mut command_buffer).expect("encode quant with bias");+ command_buffer.end_encoding().submit().wait_until_completed().unwrap();+ let actual = buffer_to_vec::<Metal, bf16>(&buffers.y);let mut reference = run_quant_cpu::<bf16>(&input);for i in 0..(input.m as usize) {@@ -246,7 +246,7 @@ fn parity_bf16_gemv_qmv_fused_scale_bias() {.collect();let mut buffers = QuantBuffers::<Metal, bf16>::allocate(&context, &input);- let bias_buf = crate::tests::helpers::alloc_allocation_with_data::<Metal, bf16>(&context, &bias_t);+ let bias_buf = crate::tests::helpers::create_buffer_with_data::<Metal, bf16>(&context, &bias_t);let mut matmul = <<Metal as Backend>::Kernels as Kernels>::MatmulKernel::new(&context,bf16::data_type(),@@ -255,16 +255,16 @@ fn parity_bf16_gemv_qmv_fused_scale_bias() {).expect("MatmulMetalKernel");- let mut encoder = Encoder::<Metal>::new(&context).expect("encoder");+ let mut command_buffer = context.create_command_buffer(None, None).unwrap();let mut args = quant_arguments(&mut buffers, &input);args.d_transform = MatmulDOps {ab_scale: scale,bias: Some(&bias_buf),..MatmulDOps::none()};- matmul.encode(args, &mut encoder).expect("encode quant gemv with scale+bias");- encoder.end_encoding().submit().wait_until_completed().unwrap();- let actual = allocation_to_vec::<Metal, bf16>(&buffers.y);+ matmul.encode(args, &mut command_buffer).expect("encode quant gemv with scale+bias");+ command_buffer.end_encoding().submit().wait_until_completed().unwrap();+ let actual = buffer_to_vec::<Metal, bf16>(&buffers.y);assert_parity::<bf16>("gemv_qmv_scale_bias", &reference, &actual, 0.05, 0.4);}@@ -351,8 +351,8 @@ fn parity_bf16_quant_rht(// CPU reference applies the RHT through the CPU matmul kernel.let cpu_context = <Cpu as Backend>::Context::new().expect("Cpu context");let mut cpu_buffers = QuantBuffers::<Cpu, bf16>::allocate(&cpu_context, &input);- let cpu_rht = crate::tests::helpers::alloc_allocation_with_data::<Cpu, i32>(&cpu_context, &rht);- let cpu_bias = crate::tests::helpers::alloc_allocation_with_data::<Cpu, bf16>(&cpu_context, &bias_t);+ let cpu_rht = crate::tests::helpers::create_buffer_with_data::<Cpu, i32>(&cpu_context, &rht);+ let cpu_bias = crate::tests::helpers::create_buffer_with_data::<Cpu, bf16>(&cpu_context, &bias_t);let mut cpu_matmul = <<Cpu as Backend>::Kernels as Kernels>::MatmulKernel::new(&cpu_context,bf16::data_type(),@@ -360,20 +360,20 @@ fn parity_bf16_quant_rht(bf16::data_type(),).expect("MatmulCpuKernel");- let mut cpu_encoder = Encoder::<Cpu>::new(&cpu_context).expect("cpu encoder");+ let mut cpu_command_buffer = cpu_context.create_command_buffer(None, None).expect("cpu command buffer");let mut cpu_args = quant_arguments(&mut cpu_buffers, &input);cpu_args.d_transform = MatmulDOps {bias: with_bias.then_some(&cpu_bias),rht_factors: Some(&cpu_rht),..MatmulDOps::none()};- cpu_matmul.encode(cpu_args, &mut cpu_encoder).expect("cpu encode quant+rht");- cpu_encoder.end_encoding().submit().wait_until_completed().unwrap();- let reference = allocation_to_vec::<Cpu, bf16>(&cpu_buffers.y);+ cpu_matmul.encode(cpu_args, &mut cpu_command_buffer).expect("cpu encode quant+rht");+ cpu_command_buffer.end_encoding().submit().wait_until_completed().unwrap();+ let reference = buffer_to_vec::<Cpu, bf16>(&cpu_buffers.y);let mut buffers = QuantBuffers::<Metal, bf16>::allocate(&context, &input);- let metal_rht = crate::tests::helpers::alloc_allocation_with_data::<Metal, i32>(&context, &rht);- let metal_bias = crate::tests::helpers::alloc_allocation_with_data::<Metal, bf16>(&context, &bias_t);+ let metal_rht = crate::tests::helpers::create_buffer_with_data::<Metal, i32>(&context, &rht);+ let metal_bias = crate::tests::helpers::create_buffer_with_data::<Metal, bf16>(&context, &bias_t);let mut matmul = <<Metal as Backend>::Kernels as Kernels>::MatmulKernel::new(&context,bf16::data_type(),@@ -381,16 +381,16 @@ fn parity_bf16_quant_rht(bf16::data_type(),).expect("MatmulMetalKernel");- let mut encoder = Encoder::<Metal>::new(&context).expect("encoder");+ let mut command_buffer = context.create_command_buffer(None, None).unwrap();let mut args = quant_arguments(&mut buffers, &input);args.d_transform = MatmulDOps {bias: with_bias.then_some(&metal_bias),rht_factors: Some(&metal_rht),..MatmulDOps::none()};- matmul.encode(args, &mut encoder).expect("encode quant matmul with rht");- encoder.end_encoding().submit().wait_until_completed().unwrap();- let actual = allocation_to_vec::<Metal, bf16>(&buffers.y);+ matmul.encode(args, &mut command_buffer).expect("encode quant matmul with rht");+ command_buffer.end_encoding().submit().wait_until_completed().unwrap();+ let actual = buffer_to_vec::<Metal, bf16>(&buffers.y);assert_parity::<bf16>(if with_bias {@@ -432,13 +432,13 @@ fn quant_gemm_accumulate_returns_unsupported_dop() {).expect("MatmulMetalKernel");- let mut encoder = Encoder::<Metal>::new(&context).expect("encoder");+ let mut command_buffer = context.create_command_buffer(None, None).unwrap();let mut args = quant_arguments(&mut buffers, &input);args.d_transform = MatmulDOps {accumulate: true,..MatmulDOps::none()};- let result = matmul.encode(args, &mut encoder);+ let result = matmul.encode(args, &mut command_buffer);let err = result.expect_err("expected error");let matmul = err@@ -495,12 +495,12 @@ fn quant_gemm_parameter_layout_prefix_matches_cpu(continue;}let mut buffers = QuantBuffers::<Metal, bf16>::allocate(&context, &input);- let mut encoder = Encoder::<Metal>::new(&context).expect("encoder");+ let mut command_buffer = context.create_command_buffer(None, None).expect("command buffer");let mut args = quant_arguments(&mut buffers, &input);args.n = logical_n;- matmul.encode_with_gemm_engine(args, engine, &mut encoder).unwrap();- encoder.end_encoding().submit().wait_until_completed().unwrap();- let actual = allocation_to_vec::<Metal, bf16>(&buffers.y);+ matmul.encode_with_gemm_engine(args, engine, &mut command_buffer).unwrap();+ command_buffer.end_encoding().submit().wait_until_completed().unwrap();+ let actual = buffer_to_vec::<Metal, bf16>(&buffers.y);let expected: Vec<_> = reference.chunks_exact(input.n as usize).flat_map(|row| row[..logical_n as usize].iter().copied())@@ -716,7 +716,7 @@ fn a8w_mxu_output_bias_parity_bf16(let mut cpu_buffers = QuantBuffers::<Cpu, bf16>::allocate(&cpu_context, &reference_input);let cpu_output_hadamard_factors = output_hadamard_factors.as_ref()- .map(|factors| crate::tests::helpers::alloc_allocation_with_data::<Cpu, i32>(&cpu_context, factors));+ .map(|factors| crate::tests::helpers::create_buffer_with_data::<Cpu, i32>(&cpu_context, factors));let mut cpu_matmul = <<Cpu as Backend>::Kernels as Kernels>::MatmulKernel::new(&cpu_context,bf16::data_type(),@@ -724,15 +724,15 @@ fn a8w_mxu_output_bias_parity_bf16(bf16::data_type(),).expect("CPU matmul kernel");- let mut cpu_encoder = Encoder::<Cpu>::new(&cpu_context).expect("CPU encoder");+ let mut cpu_command_buffer = cpu_context.create_command_buffer(None, None).expect("CPU command buffer");let mut cpu_arguments = quant_arguments(&mut cpu_buffers, &reference_input);cpu_arguments.d_transform = MatmulDOps {rht_factors: cpu_output_hadamard_factors.as_ref(),..MatmulDOps::none()};- cpu_matmul.encode(cpu_arguments, &mut cpu_encoder).expect("CPU A8W matmul");- cpu_encoder.end_encoding().submit().wait_until_completed().unwrap();- let mut reference = allocation_to_vec::<Cpu, bf16>(&cpu_buffers.y);+ cpu_matmul.encode(cpu_arguments, &mut cpu_command_buffer).expect("CPU A8W matmul");+ cpu_command_buffer.end_encoding().submit().wait_until_completed().unwrap();+ let mut reference = buffer_to_vec::<Cpu, bf16>(&cpu_buffers.y);for row in reference.chunks_exact_mut(n as usize) {for (value, bias) in row.iter_mut().zip(&output_bias) {*value = bf16::from_f32(value.to_f32() + bias.to_f32());@@ -740,10 +740,10 @@ fn a8w_mxu_output_bias_parity_bf16(}let mut metal_buffers = QuantBuffers::<Metal, bf16>::allocate(&context, &input);- let metal_output_bias = crate::tests::helpers::alloc_allocation_with_data::<Metal, bf16>(&context, &output_bias);+ let metal_output_bias = crate::tests::helpers::create_buffer_with_data::<Metal, bf16>(&context, &output_bias);let metal_output_hadamard_factors = output_hadamard_factors.as_ref()- .map(|factors| crate::tests::helpers::alloc_allocation_with_data::<Metal, i32>(&context, factors));+ .map(|factors| crate::tests::helpers::create_buffer_with_data::<Metal, i32>(&context, factors));let mut metal_matmul = <<Metal as Backend>::Kernels as Kernels>::MatmulKernel::new(&context,bf16::data_type(),@@ -751,7 +751,7 @@ fn a8w_mxu_output_bias_parity_bf16(bf16::data_type(),).expect("Metal matmul kernel");- let mut metal_encoder = Encoder::<Metal>::new(&context).expect("Metal encoder");+ let mut metal_command_buffer = context.create_command_buffer(None, None).unwrap();let mut metal_arguments = quant_arguments(&mut metal_buffers, &input);metal_arguments.d_transform = MatmulDOps {bias: Some(&metal_output_bias),@@ -759,10 +759,10 @@ fn a8w_mxu_output_bias_parity_bf16(..MatmulDOps::none()};metal_matmul- .encode_with_gemm_engine(metal_arguments, GemmEngine::Mxu, &mut metal_encoder)+ .encode_with_gemm_engine(metal_arguments, GemmEngine::Mxu, &mut metal_command_buffer).expect("Metal A8W MXU matmul with output bias");- metal_encoder.end_encoding().submit().wait_until_completed().unwrap();- let actual = allocation_to_vec::<Metal, bf16>(&metal_buffers.y);+ metal_command_buffer.end_encoding().submit().wait_until_completed().unwrap();+ let actual = buffer_to_vec::<Metal, bf16>(&metal_buffers.y);assert_parity::<bf16>(&format!("A8W{bits} MXU output bias, output Hadamard={with_output_hadamard}"),@@ -777,14 +777,14 @@ fn run_widened_f32<B: Backend>(context: &B::Context,input: &QuantInput<bf16>,) -> Vec<f32> {- use crate::{backends::common::kernel::matmul::MatmulA, data_type::DataType, tests::helpers::alloc_allocation};+ use crate::{backends::common::kernel::matmul::MatmulA, data_type::DataType, tests::helpers::create_buffer};let buffers = QuantBuffers::<B, bf16>::allocate(context, input);- let mut y = alloc_allocation::<B, f32>(context, (input.m as usize) * (input.n as usize));+ let mut y = create_buffer::<B, f32>(context, (input.m as usize) * (input.n as usize));let mut matmul =<<B as Backend>::Kernels as Kernels>::MatmulKernel::new(context, DataType::BF16, DataType::BF16, DataType::F32).expect("MatmulKernel widened");let b = buffers.matmul_b(input);- let mut encoder = Encoder::<B>::new(context).expect("encoder");+ let mut command_buffer = context.create_command_buffer(None, None).expect("command buffer");matmul.encode(crate::backends::common::kernel::matmul::MatmulArguments {@@ -797,16 +797,16 @@ fn run_widened_f32<B: Backend>(b_transpose: true,d: &mut y,d_transform: MatmulDOps::none(),- gather_indices: None,+ gather_indices: None::<&B::GlobalBuffer>,m: input.m,n: input.n,k: input.k,},- &mut encoder,+ &mut command_buffer,).expect("widened encode failed");- encoder.end_encoding().submit().wait_until_completed().unwrap();- allocation_to_vec::<B, f32>(&y)+ command_buffer.end_encoding().submit().wait_until_completed().unwrap();+ buffer_to_vec::<B, f32>(&y)}#[rstest]diff --git a/crates/uzu-engine/unit/backends/common/kernel/matmul/quant_gemm_bench.rs b/crates/uzu-engine/unit/backends/common/kernel/matmul/quant_gemm_bench.rsindex 70ae2fd96..ae0605033 100644--- a/crates/uzu-engine/unit/backends/common/kernel/matmul/quant_gemm_bench.rs+++ b/crates/uzu-engine/unit/backends/common/kernel/matmul/quant_gemm_bench.rs@@ -57,9 +57,9 @@ fn bench_unified_quant_typed<T: ArrayElement + Float>());group.throughput(Throughput::Elements((m * n * k) as u64));group.bench_function(BenchmarkId::from_parameter(shape.to_string()), |b| {- iter_encode_loop::<Metal, _>(context, b, |encoder| {+ iter_encode_loop::<Metal, _>(context, b, |command_buffer| {matmul- .encode_with_gemm_engine(quant_arguments(&mut buffers, &input), engine, encoder)+ .encode_with_gemm_engine(quant_arguments(&mut buffers, &input), engine, command_buffer).expect("encode unified quant matmul");});});diff --git a/crates/uzu-engine/unit/backends/common/kernel/matmul/quant_gemv_bench.rs b/crates/uzu-engine/unit/backends/common/kernel/matmul/quant_gemv_bench.rsindex 952c8a713..79be8b9d2 100644--- a/crates/uzu-engine/unit/backends/common/kernel/matmul/quant_gemv_bench.rs+++ b/crates/uzu-engine/unit/backends/common/kernel/matmul/quant_gemv_bench.rs@@ -45,9 +45,9 @@ fn bench_gemv_typed<B: Backend, T: ArrayElement + Float>(group.throughput(Throughput::Elements((m * n * k) as u64));group.bench_function(BenchmarkId::from_parameter(shape.to_string()), |b| {let benchmark_path = format!("{group_path}/{shape}");- iter_encode_loop_named::<B, _>(context, b, &benchmark_path, |encoder| {+ iter_encode_loop_named::<B, _>(context, b, &benchmark_path, |command_buffer| {let args = quant_arguments(buffers.next_mut(), &input);- matmul.encode(args, encoder).expect("encode failed");+ matmul.encode(args, command_buffer).expect("encode failed");});});}diff --git a/crates/uzu-engine/unit/backends/common/kernel/matmul/qwen3_bench.rs b/crates/uzu-engine/unit/backends/common/kernel/matmul/qwen3_bench.rsindex 0075a036d..ddd0f9873 100644--- a/crates/uzu-engine/unit/backends/common/kernel/matmul/qwen3_bench.rs+++ b/crates/uzu-engine/unit/backends/common/kernel/matmul/qwen3_bench.rs@@ -46,8 +46,8 @@ fn bench_qwen3_layers_typed<T: ArrayElement + Float>(group.throughput(Throughput::Elements((m * n * k) as u64));group.bench_function(BenchmarkId::from_parameter(format!("{layer}_{shape}")), |b| {- iter_encode_loop::<Metal, _>(context, b, |encoder| {- matmul.encode(quant_arguments(buffers.next_mut(), &input), encoder).expect("encode qwen3 layer");+ iter_encode_loop::<Metal, _>(context, b, |command_buffer| {+ matmul.encode(quant_arguments(buffers.next_mut(), &input), command_buffer).expect("encode qwen3 layer");});});}diff --git a/crates/uzu-engine/unit/backends/common/kernel/mod.rs b/crates/uzu-engine/unit/backends/common/kernel/mod.rsindex 6194246f5..ad865edc5 100644--- a/crates/uzu-engine/unit/backends/common/kernel/mod.rs+++ b/crates/uzu-engine/unit/backends/common/kernel/mod.rs@@ -15,6 +15,4 @@ mod short_conv;mod ssm;mod tensor_add_bias_test;mod tensor_add_scale_test;-mod tensor_add_swap_test;-mod tensor_copy_test;mod weaver;diff --git a/crates/uzu-engine/unit/backends/common/kernel/moe/moe_counts_offsets_fused_test.rs b/crates/uzu-engine/unit/backends/common/kernel/moe/moe_counts_offsets_fused_test.rsindex b82fc8885..a459958aa 100644--- a/crates/uzu-engine/unit/backends/common/kernel/moe/moe_counts_offsets_fused_test.rs+++ b/crates/uzu-engine/unit/backends/common/kernel/moe/moe_counts_offsets_fused_test.rs@@ -3,11 +3,14 @@ use uzu_engine_macros::uzu_test;use crate::{backends::{- common::{Backend, Context, Encoder, Kernels, kernel::MoeCountsOffsetsFusedKernel},+ common::{+ Backend, CommandBufferEncoding, CommandBufferExecutable, CommandBufferPending, Context, Kernels,+ kernel::MoeCountsOffsetsFusedKernel,+ },cpu::Cpu,},tests::helpers::{- alloc_allocation, alloc_allocation_with_data, allocation_prefix_to_vec, allocation_to_vec, for_each_backend,+ buffer_prefix_to_vec, buffer_to_vec, create_buffer, create_buffer_with_data, for_each_backend,for_each_non_cpu_backend,},};@@ -40,32 +43,32 @@ fn get_output<B: Backend>(.expect("Failed to create MoeCountsOffsetsFusedKernel");let topk_ids_len = (t * k).max(1);- let topk_ids_allocation = if topk_ids.is_empty() {- alloc_allocation::<B, i32>(&context, topk_ids_len)+ let topk_ids_buffer = if topk_ids.is_empty() {+ create_buffer::<B, i32>(&context, topk_ids_len)} else {- alloc_allocation_with_data::<B, i32>(&context, topk_ids)+ create_buffer_with_data::<B, i32>(&context, topk_ids)};- let mut offsets = alloc_allocation::<B, u32>(&context, e + 1);- let mut sum_k = alloc_allocation::<B, u32>(&context, 1);+ let mut offsets = create_buffer::<B, u32>(&context, e + 1);+ let mut sum_k = create_buffer::<B, u32>(&context, 1);let num_tiles = e.div_ceil(512).max(1);- let mut partials = alloc_allocation::<B, u32>(&context, num_tiles * 512);+ let mut partials = create_buffer::<B, u32>(&context, num_tiles * 512);- let mut encoder = Encoder::new(context.as_ref()).expect("Failed to create encoder");+ let mut command_buffer = context.create_command_buffer(None, None).expect("Failed to create command buffer");kernel.encode(- &topk_ids_allocation,+ &topk_ids_buffer,&mut offsets,&mut sum_k,&mut partials,t as u32,e as u32,k as u32,- &mut encoder,+ &mut command_buffer,);- encoder.end_encoding().submit().wait_until_completed().unwrap();+ command_buffer.end_encoding().submit().wait_until_completed().unwrap();- let offsets = allocation_to_vec::<B, u32>(&offsets);- let sum_k = allocation_to_vec::<B, u32>(&sum_k)[0];- let partials = allocation_prefix_to_vec::<B, u32>(&partials, e);+ let offsets = buffer_to_vec::<B, u32>(&offsets);+ let sum_k = buffer_to_vec::<B, u32>(&sum_k)[0];+ let partials = buffer_prefix_to_vec::<B, u32>(&partials, e);(offsets, sum_k, partials)}diff --git a/crates/uzu-engine/unit/backends/common/kernel/moe/moe_finalize_test.rs b/crates/uzu-engine/unit/backends/common/kernel/moe/moe_finalize_test.rsindex df7c75efc..4ecb80859 100644--- a/crates/uzu-engine/unit/backends/common/kernel/moe/moe_finalize_test.rs+++ b/crates/uzu-engine/unit/backends/common/kernel/moe/moe_finalize_test.rs@@ -6,15 +6,16 @@ use uzu_engine_macros::uzu_test;use crate::{array::ArrayElement,backends::{- common::{Backend, Encoder, Kernels, kernel::MoeFinalizeKernel},+ common::{+ Backend, CommandBufferEncoding, CommandBufferExecutable, CommandBufferPending, Context, Kernels,+ kernel::MoeFinalizeKernel,+ },cpu::Cpu,},data_type::DataType,tests::{assert::assert_eq_float,- helpers::{- alloc_allocation, alloc_allocation_with_data, allocation_to_vec, create_context, for_each_non_cpu_backend,- },+ helpers::{buffer_to_vec, create_buffer, create_buffer_with_data, create_context, for_each_non_cpu_backend},},};@@ -29,13 +30,13 @@ struct Input<T: ArrayElement + Float> {fn get_output<B: Backend, T: ArrayElement + Float>(input: &Input<T>) -> Vec<T> {let context = create_context::<B>();- let tok2row = alloc_allocation_with_data::<B, i32>(&context, &input.tok2row);- let probs = alloc_allocation_with_data::<B, T>(&context, &input.probs);- let y_partial = alloc_allocation_with_data::<B, T>(&context, &input.y_partial);- let mut y_out = alloc_allocation::<B, T>(&context, input.t * input.d_model);+ let tok2row = create_buffer_with_data::<B, i32>(&context, &input.tok2row);+ let probs = create_buffer_with_data::<B, T>(&context, &input.probs);+ let y_partial = create_buffer_with_data::<B, T>(&context, &input.y_partial);+ let mut y_out = create_buffer::<B, T>(&context, input.t * input.d_model);let finalize = <B::Kernels as Kernels>::MoeFinalizeKernel::new(&context, DataType::BF16).expect("finalize kernel");- let mut encoder = Encoder::new(context.as_ref()).expect("Failed to create encoder");+ let mut command_buffer = context.create_command_buffer(None, None).expect("Failed to create command buffer");finalize.encode(&tok2row,&probs,@@ -44,11 +45,11 @@ fn get_output<B: Backend, T: ArrayElement + Float>(input: &Input<T>) -> Vec<T> {input.t as u32,input.d_model as u32,input.k as u32,- &mut encoder,+ &mut command_buffer,);- encoder.end_encoding().submit().wait_until_completed().unwrap();+ command_buffer.end_encoding().submit().wait_until_completed().unwrap();- allocation_to_vec(&y_out)+ buffer_to_vec(&y_out)}fn test_finalize_internal(diff --git a/crates/uzu-engine/unit/backends/common/kernel/moe/moe_router_topk_test.rs b/crates/uzu-engine/unit/backends/common/kernel/moe/moe_router_topk_test.rsindex b868aa521..bd0ba06cc 100644--- a/crates/uzu-engine/unit/backends/common/kernel/moe/moe_router_topk_test.rs+++ b/crates/uzu-engine/unit/backends/common/kernel/moe/moe_router_topk_test.rs@@ -8,12 +8,13 @@ use uzu_engine_macros::uzu_test;use crate::{array::ArrayElement,backends::{- common::{Backend, Encoder, Kernels, kernel::MoeRouterTopKKernel},+ common::{+ Backend, CommandBufferEncoding, CommandBufferExecutable, CommandBufferPending, Context, Kernels,+ kernel::MoeRouterTopKKernel,+ },cpu::Cpu,},- tests::helpers::{- alloc_allocation, alloc_allocation_with_data, allocation_to_vec, create_context, for_each_non_cpu_backend,- },+ tests::helpers::{buffer_to_vec, create_buffer, create_buffer_with_data, create_context, for_each_non_cpu_backend},};#[derive(Copy, Clone, Debug)]@@ -39,33 +40,32 @@ fn get_output<B: Backend, T: ArrayElement + Float>() -> (Vec<i32>, Vec<T>) {let ctx = create_context::<B>();- let input_allocation = alloc_allocation_with_data::<B, T>(&ctx, input);- let weights_allocation = alloc_allocation_with_data::<B, T>(&ctx, weights);- let bias_allocation = bias.map(|bias| alloc_allocation_with_data::<B, T>(&ctx, bias));- let router_scale_allocation =- router_scale.map(|router_scale| alloc_allocation_with_data::<B, T>(&ctx, router_scale));- let per_expert_scale_allocation =- per_expert_scale.map(|per_expert_scale| alloc_allocation_with_data::<B, T>(&ctx, per_expert_scale));- let mut ids = alloc_allocation::<B, i32>(&ctx, t * k);- let mut probs = alloc_allocation::<B, T>(&ctx, t * k);+ let input_buffer = create_buffer_with_data::<B, T>(&ctx, input);+ let weights_buffer = create_buffer_with_data::<B, T>(&ctx, weights);+ let bias_buffer = bias.map(|bias| create_buffer_with_data::<B, T>(&ctx, bias));+ let router_scale_buffer = router_scale.map(|router_scale| create_buffer_with_data::<B, T>(&ctx, router_scale));+ let per_expert_scale_buffer =+ per_expert_scale.map(|per_expert_scale| create_buffer_with_data::<B, T>(&ctx, per_expert_scale));+ let mut ids = create_buffer::<B, i32>(&ctx, t * k);+ let mut probs = create_buffer::<B, T>(&ctx, t * k);let kernel = <<B as Backend>::Kernels as Kernels>::MoeRouterTopKKernel::new(&ctx,T::data_type(),- bias_allocation.is_some(),- router_scale_allocation.is_some(),- per_expert_scale_allocation.is_some(),+ bias_buffer.is_some(),+ router_scale_buffer.is_some(),+ per_expert_scale_buffer.is_some(),router_input_scale.is_some(),router_norm_epsilon.is_some(),).expect("kernel");- let mut encoder = Encoder::new(ctx.as_ref()).expect("Failed to create encoder");+ let mut command_buffer = ctx.create_command_buffer(None, None).expect("Failed to create command buffer");kernel.encode(- &input_allocation,- &weights_allocation,- bias_allocation.as_ref(),- router_scale_allocation.as_ref(),- per_expert_scale_allocation.as_ref(),+ &input_buffer,+ &weights_buffer,+ bias_buffer.as_ref(),+ router_scale_buffer.as_ref(),+ per_expert_scale_buffer.as_ref(),&mut ids,&mut probs,t as u32,@@ -75,11 +75,11 @@ fn get_output<B: Backend, T: ArrayElement + Float>(renorm,router_norm_epsilon,router_input_scale,- &mut encoder,+ &mut command_buffer,);- encoder.end_encoding().submit().wait_until_completed().unwrap();+ command_buffer.end_encoding().submit().wait_until_completed().unwrap();- (allocation_to_vec(&ids), allocation_to_vec(&probs))+ (buffer_to_vec(&ids), buffer_to_vec(&probs))}fn run_router_topk_once<B: Backend, T: ArrayElement + Debug + Float>(@@ -95,12 +95,13 @@ fn run_router_topk_once<B: Backend, T: ArrayElement + Debug + Float>(let mut rng = StdRng::seed_from_u64(1234);let gemma4 = matches!(router_input, RouterInput::Gemma4);let input: Vec<T> = (0..t * d_model).map(|_| T::from(rng.random_range(-1.0..1.0)).unwrap()).collect();- let weight_range = if gemma4 {- -0.4..0.4+ let weight_limit = if gemma4 {+ 0.4} else {- -1.0..1.0+ 1.0};- let weight: Vec<T> = (0..e * d_model).map(|_| T::from(rng.random_range(weight_range.clone())).unwrap()).collect();+ let weight: Vec<T> =+ (0..e * d_model).map(|_| T::from(rng.random_range(-weight_limit..weight_limit)).unwrap()).collect();let bias: Option<Vec<T>> = matches!(router_input, RouterInput::Biased).then(|| (0..e).map(|_| T::from(rng.random_range(-0.5..0.5)).unwrap()).collect());let router_scale: Option<Vec<T>> =diff --git a/crates/uzu-engine/unit/backends/common/kernel/normalization_test.rs b/crates/uzu-engine/unit/backends/common/kernel/normalization_test.rsindex 8955d6185..5869a54cf 100644--- a/crates/uzu-engine/unit/backends/common/kernel/normalization_test.rs+++ b/crates/uzu-engine/unit/backends/common/kernel/normalization_test.rs@@ -8,7 +8,7 @@ use crate::{array::ArrayElement,backends::{common::{- Allocation, Backend, Context, Encoder, Kernels,+ Backend, CommandBufferEncoding, CommandBufferExecutable, CommandBufferPending, Context, Kernels,kernel::{ActivationTransform, NormalizationKernel},},cpu::Cpu,@@ -16,9 +16,7 @@ use crate::{data_type::DataType,tests::{assert::assert_eq_float,- helpers::{- alloc_allocation, alloc_allocation_with_data, allocation_to_vec, for_each_backend, for_each_non_cpu_backend,- },+ helpers::{buffer_to_vec, create_buffer, create_buffer_with_data, for_each_backend, for_each_non_cpu_backend},},};@@ -56,30 +54,30 @@ fn get_output<).expect("Failed to create NormalizationKernel");- let input_allocation = alloc_allocation_with_data::<B, InputT>(&context, input);- let scales_allocation = scales.map(|scales| alloc_allocation_with_data::<B, AffineT>(&context, scales));- let hadamard_factors_allocation =- hadamard_factors.map(|hadamard_factors| alloc_allocation_with_data::<B, i32>(&context, hadamard_factors));- let mut output_allocation = alloc_allocation_with_data::<B, OutputT>(&context, &vec![OutputT::zero(); input.len()]);+ let input_buffer = create_buffer_with_data::<B, InputT>(&context, input);+ let scales_buffer = scales.map(|scales| create_buffer_with_data::<B, AffineT>(&context, scales));+ let hadamard_factors_buffer =+ hadamard_factors.map(|hadamard_factors| create_buffer_with_data::<B, i32>(&context, hadamard_factors));+ let mut output_buffer = create_buffer_with_data::<B, OutputT>(&context, &vec![OutputT::zero(); input.len()]);- let mut encoder = Encoder::new(context.as_ref()).expect("Failed to create encoder");+ let mut command_buffer = context.create_command_buffer(None, None).expect("Failed to create command buffer");kernel.encode(- Some((&input_allocation, 0)),- scales_allocation.as_ref(),- None::<&Allocation<B>>,- &mut output_allocation,- None::<(&mut Allocation<B>, usize)>,- hadamard_factors_allocation.as_ref(),+ Some(&input_buffer),+ scales_buffer.as_ref(),+ None::<&B::GlobalBuffer>,+ &mut output_buffer,+ None::<&mut B::GlobalBuffer>,+ hadamard_factors_buffer.as_ref(),batch_size,element_count,epsilon,0.0,1.0,- &mut encoder,+ &mut command_buffer,);- encoder.end_encoding().submit().wait_until_completed().expect("Failed to wait command buffer");+ command_buffer.end_encoding().submit().wait_until_completed().expect("Failed to wait command buffer");- allocation_to_vec::<B, OutputT>(&output_allocation)+ buffer_to_vec::<B, OutputT>(&output_buffer)}fn test_internal<@@ -175,20 +173,20 @@ fn test_hadamard<T: ArrayElement + Float + Debug + Display>() {let context = <Cpu as Backend>::Context::new().expect("Failed to create Context");let input_rht = ActivationTransform::<Cpu>::input_rht(context.as_ref(), T::data_type(), false).expect("Failed to create ActivationTransform");- let plain_allocation = alloc_allocation_with_data::<Cpu, T>(&context, &plain);- let hadamard_factors_allocation = alloc_allocation_with_data::<Cpu, i32>(&context, &hadamard_factors);- let mut expected_allocation = alloc_allocation::<Cpu, T>(&context, plain.len());- let mut encoder = Encoder::new(context.as_ref()).expect("Failed to create encoder");+ let plain_buffer = create_buffer_with_data::<Cpu, T>(&context, &plain);+ let hadamard_factors_buffer = create_buffer_with_data::<Cpu, i32>(&context, &hadamard_factors);+ let mut expected_buffer = create_buffer::<Cpu, T>(&context, plain.len());+ let mut command_buffer = context.create_command_buffer(None, None).expect("Failed to create command buffer");input_rht.encode_fp(- &plain_allocation,- &mut expected_allocation,- &hadamard_factors_allocation,+ &plain_buffer,+ &mut expected_buffer,+ &hadamard_factors_buffer,batch_size,element_count,- &mut encoder,+ &mut command_buffer,);- encoder.end_encoding().submit().wait_until_completed().expect("Failed to wait command buffer");- let expected = allocation_to_vec::<Cpu, T>(&expected_allocation);+ command_buffer.end_encoding().submit().wait_until_completed().expect("Failed to wait command buffer");+ let expected = buffer_to_vec::<Cpu, T>(&expected_buffer);let eps = if matches!(T::data_type(), DataType::F16 | DataType::BF16) {1e-2diff --git a/crates/uzu-engine/unit/backends/common/kernel/pooling/pooling_mean_test.rs b/crates/uzu-engine/unit/backends/common/kernel/pooling/pooling_mean_test.rsindex 0742e22b3..c883ec212 100644--- a/crates/uzu-engine/unit/backends/common/kernel/pooling/pooling_mean_test.rs+++ b/crates/uzu-engine/unit/backends/common/kernel/pooling/pooling_mean_test.rs@@ -7,13 +7,16 @@ use uzu_engine_macros::uzu_test;use crate::{array::ArrayElement,backends::{- common::{Backend, Context, Encoder, Kernels, kernel::PoolingMeanKernel},+ common::{+ Backend, CommandBufferEncoding, CommandBufferExecutable, CommandBufferPending, Context, Kernels,+ kernel::PoolingMeanKernel,+ },cpu::Cpu,},data_type::DataType,tests::{assert::assert_eq_float,- helpers::{alloc_allocation, alloc_allocation_with_data, allocation_to_vec, for_each_non_cpu_backend},+ helpers::{buffer_to_vec, create_buffer, create_buffer_with_data, for_each_non_cpu_backend},},};@@ -51,14 +54,14 @@ fn get_output<T: ArrayElement + Float, B: Backend>(input: &Input<T>) -> Vec<T> {let output_len = (input.batch_size * input.hidden_dim) as usize;- let input_allocation = alloc_allocation_with_data::<B, T>(&context, &input.input);- let mut output = alloc_allocation::<B, T>(&context, output_len);+ let input_buffer = create_buffer_with_data::<B, T>(&context, &input.input);+ let mut output = create_buffer::<B, T>(&context, output_len);- let mut encoder = Encoder::new(context.as_ref()).expect("Failed to create encoder");- kernel.encode(&input_allocation, &mut output, input.seq_len, input.hidden_dim, input.batch_size, &mut encoder);- encoder.end_encoding().submit().wait_until_completed().unwrap();+ let mut command_buffer = context.create_command_buffer(None, None).expect("Failed to create command buffer");+ kernel.encode(&input_buffer, &mut output, input.seq_len, input.hidden_dim, input.batch_size, &mut command_buffer);+ command_buffer.end_encoding().submit().wait_until_completed().unwrap();- allocation_to_vec(&output)+ buffer_to_vec(&output)}fn test_internal<T: ArrayElement + Float + Debug + Display>(diff --git a/crates/uzu-engine/unit/backends/common/kernel/radix_top_k_small_test.rs b/crates/uzu-engine/unit/backends/common/kernel/radix_top_k_small_test.rsindex 3645c9779..caf0f1261 100644--- a/crates/uzu-engine/unit/backends/common/kernel/radix_top_k_small_test.rs+++ b/crates/uzu-engine/unit/backends/common/kernel/radix_top_k_small_test.rs@@ -5,15 +5,16 @@ use half::bf16;use uzu_engine_macros::uzu_test;#[cfg(backend = "metal")]-use crate::backends::metal::Metal;+use crate::backends::{common::CommandBufferCompleted, metal::Metal};use crate::{backends::{- common::{Backend, Encoder, Kernels, kernel::radix_top_k_small::RadixTopKSmall},+ common::{+ Backend, CommandBufferEncoding, CommandBufferExecutable, CommandBufferPending, Context, Kernels,+ kernel::radix_top_k_small::RadixTopKSmall,+ },cpu::Cpu,},- tests::helpers::{- alloc_allocation, alloc_allocation_with_data, allocation_to_vec, create_context, for_each_non_cpu_backend,- },+ tests::helpers::{buffer_to_vec, create_buffer, create_buffer_with_data, create_context, for_each_non_cpu_backend},};const TARGET_COLUMNS: usize = 248_320;@@ -33,14 +34,14 @@ fn radix_top_k_small<B: Backend>(k: usize,) -> (Vec<u32>, Vec<f32>) {let context = create_context::<B>();- let input = alloc_allocation_with_data::<B, bf16>(&context, input);- let mut ids = alloc_allocation::<B, u32>(&context, rows * k);- let mut scores = alloc_allocation::<B, f32>(&context, rows * k);+ let input = create_buffer_with_data::<B, bf16>(&context, input);+ let mut ids = create_buffer::<B, u32>(&context, rows * k);+ let mut scores = create_buffer::<B, f32>(&context, rows * k);let kernel = <B::Kernels as Kernels>::RadixTopKSmall::new(&context, columns as u32).unwrap();- let mut encoder = Encoder::new(context.as_ref()).unwrap();- kernel.encode(&input, &mut ids, &mut scores, rows as u32, k as u32, &mut encoder).unwrap();- encoder.end_encoding().submit().wait_until_completed().unwrap();- (allocation_to_vec(&ids), allocation_to_vec(&scores))+ let mut command_buffer = context.create_command_buffer(None, None).unwrap();+ kernel.encode(&input, &mut ids, &mut scores, rows as u32, k as u32, &mut command_buffer).unwrap();+ command_buffer.end_encoding().submit().wait_until_completed().unwrap();+ (buffer_to_vec(&ids), buffer_to_vec(&scores))}fn reference(@@ -120,21 +121,21 @@ fn benchmark_radix_top_k_small() {const BATCH: u32 = 16;let context = create_context::<Metal>();- let input = alloc_allocation_with_data::<Metal, bf16>(+ let input = create_buffer_with_data::<Metal, bf16>(&context,&values(ROWS, TARGET_COLUMNS).into_iter().map(bf16::from_f32).collect::<Vec<_>>(),);- let mut ids = alloc_allocation::<Metal, u32>(&context, ROWS * TARGET_K);- let mut scores = alloc_allocation::<Metal, f32>(&context, ROWS * TARGET_K);+ let mut ids = create_buffer::<Metal, u32>(&context, ROWS * TARGET_K);+ let mut scores = create_buffer::<Metal, f32>(&context, ROWS * TARGET_K);let kernel =<<Metal as Backend>::Kernels as Kernels>::RadixTopKSmall::new(&context, TARGET_COLUMNS as u32).unwrap();let mut run = || {let start = Instant::now();- let mut encoder = Encoder::new(context.as_ref()).unwrap();+ let mut command_buffer = context.create_command_buffer(None, None).unwrap();for _ in 0..BATCH {- kernel.encode(&input, &mut ids, &mut scores, ROWS as u32, TARGET_K as u32, &mut encoder).unwrap();+ kernel.encode(&input, &mut ids, &mut scores, ROWS as u32, TARGET_K as u32, &mut command_buffer).unwrap();}- let completed = encoder.end_encoding().submit().wait_until_completed().unwrap();+ let completed = command_buffer.end_encoding().submit().wait_until_completed().unwrap();(completed.gpu_execution_time().div_f64(BATCH as f64), start.elapsed().div_f64(BATCH as f64))};for _ in 0..5 {diff --git a/crates/uzu-engine/unit/backends/common/kernel/separable_causal_conv_test.rs b/crates/uzu-engine/unit/backends/common/kernel/separable_causal_conv_test.rsindex 3cd771618..862b82951 100644--- a/crates/uzu-engine/unit/backends/common/kernel/separable_causal_conv_test.rs+++ b/crates/uzu-engine/unit/backends/common/kernel/separable_causal_conv_test.rs@@ -4,10 +4,13 @@ use uzu_engine_macros::uzu_test;use crate::{array::ArrayElement,backends::{- common::{Allocation, Backend, Context, Encoder, Kernels, kernel::SeparableCausalConvKernel},+ common::{+ Backend, CommandBufferEncoding, CommandBufferExecutable, CommandBufferPending, Context, Kernels,+ kernel::SeparableCausalConvKernel,+ },cpu::Cpu,},- tests::helpers::{alloc_allocation, alloc_allocation_with_data, allocation_to_vec, for_each_non_cpu_backend},+ tests::helpers::{buffer_to_vec, create_buffer, create_buffer_with_data, for_each_non_cpu_backend},};fn run_kernel<B: Backend>() -> Vec<bf16> {@@ -40,25 +43,25 @@ fn run_kernel<B: Backend>() -> Vec<bf16> {).expect("create separable causal convolution kernel");- let input = alloc_allocation_with_data::<B, bf16>(&context, &input);- let coefficient_deltas = alloc_allocation_with_data::<B, bf16>(&context, &coefficient_deltas);- let weights = alloc_allocation_with_data::<B, bf16>(&context, &weights);- let mut output = alloc_allocation::<B, bf16>(&context, (SEQUENCE_LENGTH * MODEL_DIM) as usize);+ let input = create_buffer_with_data::<B, bf16>(&context, &input);+ let coefficient_deltas = create_buffer_with_data::<B, bf16>(&context, &coefficient_deltas);+ let weights = create_buffer_with_data::<B, bf16>(&context, &weights);+ let mut output = create_buffer::<B, bf16>(&context, (SEQUENCE_LENGTH * MODEL_DIM) as usize);- let mut encoder = Encoder::new(context.as_ref()).expect("create encoder");+ let mut command_buffer = context.create_command_buffer(None, None).expect("command buffer");kernel.encode(&input,&coefficient_deltas,&weights,- None::<&Allocation<B>>,+ None::<&B::GlobalBuffer>,&mut output,SEQUENCE_LENGTH,COEFFICIENT_ROW_STRIDE,- &mut encoder,+ &mut command_buffer,);- encoder.end_encoding().submit().wait_until_completed().unwrap();+ command_buffer.end_encoding().submit().wait_until_completed().unwrap();- allocation_to_vec::<B, bf16>(&output)+ buffer_to_vec::<B, bf16>(&output)}#[uzu_test]diff --git a/crates/uzu-engine/unit/backends/common/kernel/short_conv/short_conv_decode_test.rs b/crates/uzu-engine/unit/backends/common/kernel/short_conv/short_conv_decode_test.rsindex db5a77e56..a0ebeb5ac 100644--- a/crates/uzu-engine/unit/backends/common/kernel/short_conv/short_conv_decode_test.rs+++ b/crates/uzu-engine/unit/backends/common/kernel/short_conv/short_conv_decode_test.rs@@ -7,13 +7,16 @@ use uzu_engine_macros::uzu_test;use crate::{array::ArrayElement,backends::{- common::{Backend, Context, Encoder, Kernels, kernel::ShortConvDecodeKernel},+ common::{+ Backend, CommandBufferEncoding, CommandBufferExecutable, CommandBufferPending, Context, Kernels,+ kernel::ShortConvDecodeKernel,+ },cpu::Cpu,},data_type::DataType,tests::{assert::assert_eq_float,- helpers::{alloc_allocation, alloc_allocation_with_data, allocation_to_vec, for_each_non_cpu_backend},+ helpers::{buffer_to_vec, create_buffer, create_buffer_with_data, for_each_non_cpu_backend},},};@@ -45,27 +48,27 @@ fn get_output<T: ArrayElement + Float, B: Backend>().expect("Failed to create ShortConvDecodeKernel");- let in_proj = alloc_allocation_with_data::<B, T>(&context, &input.in_proj);- let w = alloc_allocation_with_data::<B, f32>(&context, &input.w);- let b = input.b.as_ref().map(|b| alloc_allocation_with_data::<B, f32>(&context, b));+ let in_proj = create_buffer_with_data::<B, T>(&context, &input.in_proj);+ let w = create_buffer_with_data::<B, f32>(&context, &input.w);+ let b = input.b.as_ref().map(|b| create_buffer_with_data::<B, f32>(&context, b));let out_size = input.suffix_len as usize * input.model_dim as usize;- let mut out = alloc_allocation::<B, T>(&context, out_size);+ let mut out = create_buffer::<B, T>(&context, out_size);let state_size = input.model_dim as usize * input.state_stride as usize;- let state_allocation_size = state_size.max(1);+ let state_buffer_size = state_size.max(1);let state_data: Vec<T> =- input.state.iter().copied().chain(std::iter::repeat(T::zero())).take(state_allocation_size).collect();+ input.state.iter().copied().chain(std::iter::repeat(T::zero())).take(state_buffer_size).collect();let mut next_state = if state_in_place {- alloc_allocation_with_data::<B, T>(&context, &state_data)+ create_buffer_with_data::<B, T>(&context, &state_data)} else {- alloc_allocation::<B, T>(&context, state_allocation_size)+ create_buffer::<B, T>(&context, state_buffer_size)};- let state = (!state_in_place).then(|| alloc_allocation_with_data::<B, T>(&context, &state_data));+ let state = (!state_in_place).then(|| create_buffer_with_data::<B, T>(&context, &state_data));- let mut encoder = Encoder::new(context.as_ref()).expect("Failed to create encoder");+ let mut command_buffer = context.create_command_buffer(None, None).expect("Failed to create command buffer");kernel.encode(&in_proj,&w,@@ -78,11 +81,11 @@ fn get_output<T: ArrayElement + Float, B: Backend>(input.in_proj_stride,input.state_stride,input.model_dim,- &mut encoder,+ &mut command_buffer,);- encoder.end_encoding().submit().wait_until_completed().unwrap();+ command_buffer.end_encoding().submit().wait_until_completed().unwrap();- (allocation_to_vec(&out), allocation_to_vec(&next_state))+ (buffer_to_vec(&out), buffer_to_vec(&next_state))}fn get_test_data_basic<T: ArrayElement + Float>(diff --git a/crates/uzu-engine/unit/backends/common/kernel/short_conv/short_conv_pack_test.rs b/crates/uzu-engine/unit/backends/common/kernel/short_conv/short_conv_pack_test.rsindex 9d78a57ae..31f430b10 100644--- a/crates/uzu-engine/unit/backends/common/kernel/short_conv/short_conv_pack_test.rs+++ b/crates/uzu-engine/unit/backends/common/kernel/short_conv/short_conv_pack_test.rs@@ -7,13 +7,16 @@ use uzu_engine_macros::uzu_test;use crate::{array::ArrayElement,backends::{- common::{Backend, Context, Encoder, Kernels, kernel::ShortConvPackKernel},+ common::{+ Backend, CommandBufferEncoding, CommandBufferExecutable, CommandBufferPending, Context, Kernels,+ kernel::ShortConvPackKernel,+ },cpu::Cpu,},data_type::DataType,tests::{assert::assert_eq_float,- helpers::{alloc_allocation, alloc_allocation_with_data, allocation_to_vec, for_each_non_cpu_backend},+ helpers::{buffer_to_vec, create_buffer, create_buffer_with_data, for_each_non_cpu_backend},},};@@ -32,14 +35,14 @@ fn get_output<T: ArrayElement + Float, B: Backend>(input: &Input<T>) -> Vec<T> {let kernel = <<B as Backend>::Kernels as Kernels>::ShortConvPackKernel::new(&context, T::data_type()).expect("Failed to create ShortConvPackKernel");- let state_in = alloc_allocation_with_data::<B, T>(&context, &input.state_in);- let in_proj = alloc_allocation_with_data::<B, T>(&context, &input.in_proj);+ let state_in = create_buffer_with_data::<B, T>(&context, &input.state_in);+ let in_proj = create_buffer_with_data::<B, T>(&context, &input.in_proj);let padded_rows = (input.state_stride + input.suffix_len) as usize;let padded_size = padded_rows * input.model_dim as usize;- let mut padded = alloc_allocation::<B, T>(&context, padded_size);+ let mut padded = create_buffer::<B, T>(&context, padded_size);- let mut encoder = Encoder::new(context.as_ref()).expect("Failed to create encoder");+ let mut command_buffer = context.create_command_buffer(None, None).expect("Failed to create command buffer");kernel.encode(&state_in,&in_proj,@@ -48,11 +51,11 @@ fn get_output<T: ArrayElement + Float, B: Backend>(input: &Input<T>) -> Vec<T> {input.suffix_len,input.in_proj_stride,input.model_dim,- &mut encoder,+ &mut command_buffer,);- encoder.end_encoding().submit().wait_until_completed().unwrap();+ command_buffer.end_encoding().submit().wait_until_completed().unwrap();- allocation_to_vec(&padded)+ buffer_to_vec(&padded)}/// Build test input for ShortConvPack.diff --git a/crates/uzu-engine/unit/backends/common/kernel/short_conv/short_conv_prefill_test.rs b/crates/uzu-engine/unit/backends/common/kernel/short_conv/short_conv_prefill_test.rsindex d7d4d7793..ceaa191f2 100644--- a/crates/uzu-engine/unit/backends/common/kernel/short_conv/short_conv_prefill_test.rs+++ b/crates/uzu-engine/unit/backends/common/kernel/short_conv/short_conv_prefill_test.rs@@ -7,13 +7,16 @@ use uzu_engine_macros::uzu_test;use crate::{array::ArrayElement,backends::{- common::{Backend, Context, Encoder, Kernels, kernel::ShortConvPrefillKernel},+ common::{+ Backend, CommandBufferEncoding, CommandBufferExecutable, CommandBufferPending, Context, Kernels,+ kernel::ShortConvPrefillKernel,+ },cpu::Cpu,},data_type::DataType,tests::{assert::assert_eq_float,- helpers::{alloc_allocation, alloc_allocation_with_data, allocation_to_vec, for_each_non_cpu_backend},+ helpers::{buffer_to_vec, create_buffer, create_buffer_with_data, for_each_non_cpu_backend},},};@@ -41,18 +44,18 @@ fn get_output<T: ArrayElement + Float, B: Backend>(input: &Input<T>) -> (Vec<T>,).expect("Failed to create ShortConvPrefillKernel");- let padded = alloc_allocation_with_data::<B, T>(&context, &input.padded);- let in_proj = alloc_allocation_with_data::<B, T>(&context, &input.in_proj);- let w = alloc_allocation_with_data::<B, f32>(&context, &input.w);- let b = input.b.as_ref().map(|b| alloc_allocation_with_data::<B, f32>(&context, b));+ let padded = create_buffer_with_data::<B, T>(&context, &input.padded);+ let in_proj = create_buffer_with_data::<B, T>(&context, &input.in_proj);+ let w = create_buffer_with_data::<B, f32>(&context, &input.w);+ let b = input.b.as_ref().map(|b| create_buffer_with_data::<B, f32>(&context, b));let out_size = input.suffix_len as usize * input.model_dim as usize;- let mut out = alloc_allocation::<B, T>(&context, out_size);+ let mut out = create_buffer::<B, T>(&context, out_size);let state_out_size = input.model_dim as usize * input.state_stride as usize;- let mut state_out = alloc_allocation::<B, T>(&context, state_out_size);+ let mut state_out = create_buffer::<B, T>(&context, state_out_size);- let mut encoder = Encoder::new(context.as_ref()).expect("Failed to create encoder");+ let mut command_buffer = context.create_command_buffer(None, None).expect("Failed to create command buffer");kernel.encode(&padded,&in_proj,@@ -65,11 +68,11 @@ fn get_output<T: ArrayElement + Float, B: Backend>(input: &Input<T>) -> (Vec<T>,input.in_proj_stride,input.state_stride,input.model_dim,- &mut encoder,+ &mut command_buffer,);- encoder.end_encoding().submit().wait_until_completed().unwrap();+ command_buffer.end_encoding().submit().wait_until_completed().unwrap();- (allocation_to_vec(&out), allocation_to_vec(&state_out))+ (buffer_to_vec(&out), buffer_to_vec(&state_out))}fn get_test_data_basic<T: ArrayElement + Float>(diff --git a/crates/uzu-engine/unit/backends/common/kernel/short_conv/short_conv_trie_test.rs b/crates/uzu-engine/unit/backends/common/kernel/short_conv/short_conv_trie_test.rsindex ffd0834ad..a7a51f846 100644--- a/crates/uzu-engine/unit/backends/common/kernel/short_conv/short_conv_trie_test.rs+++ b/crates/uzu-engine/unit/backends/common/kernel/short_conv/short_conv_trie_test.rs@@ -7,13 +7,16 @@ use uzu_engine_macros::uzu_test;use crate::{array::ArrayElement,backends::{- common::{Backend, Context, Encoder, Kernels, kernel::ShortConvTrieKernel},+ common::{+ Backend, CommandBufferEncoding, CommandBufferExecutable, CommandBufferPending, Context, Kernels,+ kernel::ShortConvTrieKernel,+ },cpu::Cpu,},data_type::DataType,tests::{assert::assert_eq_float,- helpers::{alloc_allocation, alloc_allocation_with_data, allocation_to_vec, for_each_non_cpu_backend},+ helpers::{buffer_to_vec, create_buffer, create_buffer_with_data, for_each_non_cpu_backend},},};@@ -42,29 +45,29 @@ fn get_output<T: ArrayElement + Float, B: Backend>(input: &Input<T>) -> (Vec<T>,).expect("Failed to create ShortConvTrieKernel");- let in_proj = alloc_allocation_with_data::<B, T>(&context, &input.in_proj);- let w = alloc_allocation_with_data::<B, f32>(&context, &input.w);- let b = input.b.as_ref().map(|b| alloc_allocation_with_data::<B, f32>(&context, b));+ let in_proj = create_buffer_with_data::<B, T>(&context, &input.in_proj);+ let w = create_buffer_with_data::<B, f32>(&context, &input.w);+ let b = input.b.as_ref().map(|b| create_buffer_with_data::<B, f32>(&context, b));let out_size = input.suffix_len as usize * input.model_dim as usize;- let mut out = alloc_allocation::<B, T>(&context, out_size);+ let mut out = create_buffer::<B, T>(&context, out_size);let state_stride = input.state_stride as usize;let model_dim = input.model_dim as usize;let suffix_len = input.suffix_len as usize;let base_state_size = model_dim * state_stride;- let base_state_allocation_size = base_state_size.max(1);+ let base_state_buffer_size = base_state_size.max(1);let base_state_data: Vec<T> =- input.base_state.iter().copied().chain(std::iter::repeat(T::zero())).take(base_state_allocation_size).collect();- let base_state = alloc_allocation_with_data::<B, T>(&context, &base_state_data);+ input.base_state.iter().copied().chain(std::iter::repeat(T::zero())).take(base_state_buffer_size).collect();+ let base_state = create_buffer_with_data::<B, T>(&context, &base_state_data);- let parents = alloc_allocation_with_data::<B, i32>(&context, &input.parents);+ let parents = create_buffer_with_data::<B, i32>(&context, &input.parents);let suffix_state_size = suffix_len * model_dim * state_stride;- let mut suffix_state = alloc_allocation::<B, T>(&context, suffix_state_size.max(1));+ let mut suffix_state = create_buffer::<B, T>(&context, suffix_state_size.max(1));- let mut encoder = Encoder::new(context.as_ref()).expect("Failed to create encoder");+ let mut command_buffer = context.create_command_buffer(None, None).expect("Failed to create command buffer");kernel.encode(&in_proj,&w,@@ -78,11 +81,11 @@ fn get_output<T: ArrayElement + Float, B: Backend>(input: &Input<T>) -> (Vec<T>,input.in_proj_stride,input.state_stride,input.model_dim,- &mut encoder,+ &mut command_buffer,);- encoder.end_encoding().submit().wait_until_completed().unwrap();+ command_buffer.end_encoding().submit().wait_until_completed().unwrap();- (allocation_to_vec(&out), allocation_to_vec(&suffix_state))+ (buffer_to_vec(&out), buffer_to_vec(&suffix_state))}/// Linear chain: node 0 has parent -1 (root), node i has parent i-1.diff --git a/crates/uzu-engine/unit/backends/common/kernel/ssm/ssm_conv1d_decode_test.rs b/crates/uzu-engine/unit/backends/common/kernel/ssm/ssm_conv1d_decode_test.rsindex ce69cd691..7f35d292e 100644--- a/crates/uzu-engine/unit/backends/common/kernel/ssm/ssm_conv1d_decode_test.rs+++ b/crates/uzu-engine/unit/backends/common/kernel/ssm/ssm_conv1d_decode_test.rs@@ -8,14 +8,15 @@ use crate::{array::ArrayElement,backends::{common::{- Allocation, Backend, Context, Encoder, Kernels, gpu_types::ActivationType, kernel::Conv1dDecodeKernel,+ Backend, CommandBufferEncoding, CommandBufferExecutable, CommandBufferPending, Context, Kernels,+ gpu_types::ActivationType, kernel::Conv1dDecodeKernel,},cpu::Cpu,},data_type::DataType,tests::{assert::assert_eq_float,- helpers::{alloc_allocation, alloc_allocation_with_data, allocation_to_vec, for_each_non_cpu_backend},+ helpers::{buffer_to_vec, create_buffer, create_buffer_with_data, for_each_non_cpu_backend},},};@@ -105,23 +106,23 @@ fn get_output<B: Backend, T: ArrayElement + Float>(input: &Input<T>) -> Output<Tlet c_out_size = input.suffix_len as usize * input.proj_dim as usize;let state_size = input.num_channels as usize * input.state_stride as usize;- let x = alloc_allocation_with_data::<B, T>(&context, &input.x);- let w = alloc_allocation_with_data::<B, T>(&context, &input.w);- let b = input.b.as_ref().map(|b| alloc_allocation_with_data::<B, T>(&context, b));+ let x = create_buffer_with_data::<B, T>(&context, &input.x);+ let w = create_buffer_with_data::<B, T>(&context, &input.w);+ let b = input.b.as_ref().map(|b| create_buffer_with_data::<B, T>(&context, b));- let mut x_out = alloc_allocation::<B, T>(&context, x_out_size);- let mut b_out = alloc_allocation::<B, T>(&context, b_out_size);- let mut c_out = alloc_allocation::<B, T>(&context, c_out_size);+ let mut x_out = create_buffer::<B, T>(&context, x_out_size);+ let mut b_out = create_buffer::<B, T>(&context, b_out_size);+ let mut c_out = create_buffer::<B, T>(&context, c_out_size);if input.state_in_place {- let mut next_state = alloc_allocation_with_data::<B, T>(&context, &input.state);+ let mut next_state = create_buffer_with_data::<B, T>(&context, &input.state);- let mut encoder = Encoder::new(context.as_ref()).expect("Failed to create encoder");+ let mut command_buffer = context.create_command_buffer(None, None).expect("Failed to create command buffer");kernel.encode(&x,&w,b.as_ref(),- None::<&Allocation<B>>,+ None::<&B::GlobalBuffer>,&mut x_out,&mut b_out,&mut c_out,@@ -134,21 +135,21 @@ fn get_output<B: Backend, T: ArrayElement + Float>(input: &Input<T>) -> Output<Tinput.inner_dim,input.proj_dim,input.activation_type,- &mut encoder,+ &mut command_buffer,);- encoder.end_encoding().submit().wait_until_completed().expect("Failed to wait command buffer");+ command_buffer.end_encoding().submit().wait_until_completed().expect("Failed to wait command buffer");Output {- x_out: allocation_to_vec(&x_out),- b_out: allocation_to_vec(&b_out),- c_out: allocation_to_vec(&c_out),- next_state: allocation_to_vec(&next_state),+ x_out: buffer_to_vec(&x_out),+ b_out: buffer_to_vec(&b_out),+ c_out: buffer_to_vec(&c_out),+ next_state: buffer_to_vec(&next_state),}} else {- let state = alloc_allocation_with_data::<B, T>(&context, &input.state);- let mut next_state = alloc_allocation::<B, T>(&context, state_size);+ let state = create_buffer_with_data::<B, T>(&context, &input.state);+ let mut next_state = create_buffer::<B, T>(&context, state_size);- let mut encoder = Encoder::new(context.as_ref()).expect("Failed to create encoder");+ let mut command_buffer = context.create_command_buffer(None, None).expect("Failed to create command buffer");kernel.encode(&x,&w,@@ -166,15 +167,15 @@ fn get_output<B: Backend, T: ArrayElement + Float>(input: &Input<T>) -> Output<Tinput.inner_dim,input.proj_dim,input.activation_type,- &mut encoder,+ &mut command_buffer,);- encoder.end_encoding().submit().wait_until_completed().expect("Failed to wait command buffer");+ command_buffer.end_encoding().submit().wait_until_completed().expect("Failed to wait command buffer");Output {- x_out: allocation_to_vec(&x_out),- b_out: allocation_to_vec(&b_out),- c_out: allocation_to_vec(&c_out),- next_state: allocation_to_vec(&next_state),+ x_out: buffer_to_vec(&x_out),+ b_out: buffer_to_vec(&b_out),+ c_out: buffer_to_vec(&c_out),+ next_state: buffer_to_vec(&next_state),}}}diff --git a/crates/uzu-engine/unit/backends/common/kernel/ssm/ssm_conv1d_pack_test.rs b/crates/uzu-engine/unit/backends/common/kernel/ssm/ssm_conv1d_pack_test.rsindex f12a8b05f..f46798e6b 100644--- a/crates/uzu-engine/unit/backends/common/kernel/ssm/ssm_conv1d_pack_test.rs+++ b/crates/uzu-engine/unit/backends/common/kernel/ssm/ssm_conv1d_pack_test.rs@@ -7,13 +7,16 @@ use uzu_engine_macros::uzu_test;use crate::{array::ArrayElement,backends::{- common::{Backend, Context, Encoder, Kernels, kernel::Conv1dPackKernel},+ common::{+ Backend, CommandBufferEncoding, CommandBufferExecutable, CommandBufferPending, Context, Kernels,+ kernel::Conv1dPackKernel,+ },cpu::Cpu,},data_type::DataType,tests::{assert::assert_eq_float,- helpers::{alloc_allocation, alloc_allocation_with_data, allocation_to_vec, for_each_non_cpu_backend},+ helpers::{buffer_to_vec, create_buffer, create_buffer_with_data, for_each_non_cpu_backend},},};@@ -56,11 +59,11 @@ fn get_output<B: Backend, T: ArrayElement + Float>(input: &Input<T>) -> Vec<T> {let total_rows = input.state_stride as usize + input.suffix_len as usize;let padded_size = total_rows * input.row_stride as usize;- let state = alloc_allocation_with_data::<B, T>(&context, &input.state_in);- let x = alloc_allocation_with_data::<B, T>(&context, &input.x);- let mut padded = alloc_allocation::<B, T>(&context, padded_size);+ let state = create_buffer_with_data::<B, T>(&context, &input.state_in);+ let x = create_buffer_with_data::<B, T>(&context, &input.x);+ let mut padded = create_buffer::<B, T>(&context, padded_size);- let mut encoder = Encoder::new(context.as_ref()).expect("Failed to create encoder");+ let mut command_buffer = context.create_command_buffer(None, None).expect("Failed to create command buffer");kernel.encode(&state,&x,@@ -69,11 +72,11 @@ fn get_output<B: Backend, T: ArrayElement + Float>(input: &Input<T>) -> Vec<T> {input.row_stride,input.suffix_len,input.num_channels,- &mut encoder,+ &mut command_buffer,);- encoder.end_encoding().submit().wait_until_completed().expect("Failed to wait command buffer");+ command_buffer.end_encoding().submit().wait_until_completed().expect("Failed to wait command buffer");- allocation_to_vec(&padded)+ buffer_to_vec(&padded)}fn get_test_data<T: ArrayElement + Float>(diff --git a/crates/uzu-engine/unit/backends/common/kernel/ssm/ssm_conv1d_scan_test.rs b/crates/uzu-engine/unit/backends/common/kernel/ssm/ssm_conv1d_scan_test.rsindex ae7e4a1b8..2726ed554 100644--- a/crates/uzu-engine/unit/backends/common/kernel/ssm/ssm_conv1d_scan_test.rs+++ b/crates/uzu-engine/unit/backends/common/kernel/ssm/ssm_conv1d_scan_test.rs@@ -7,13 +7,16 @@ use uzu_engine_macros::uzu_test;use crate::{array::ArrayElement,backends::{- common::{Backend, Context, Encoder, Kernels, gpu_types::ActivationType, kernel::Conv1dScanKernel},+ common::{+ Backend, CommandBufferEncoding, CommandBufferExecutable, CommandBufferPending, Context, Kernels,+ gpu_types::ActivationType, kernel::Conv1dScanKernel,+ },cpu::Cpu,},data_type::DataType,tests::{assert::assert_eq_float,- helpers::{alloc_allocation, alloc_allocation_with_data, allocation_to_vec, for_each_non_cpu_backend},+ helpers::{buffer_to_vec, create_buffer, create_buffer_with_data, for_each_non_cpu_backend},},};@@ -92,16 +95,16 @@ fn get_output<B: Backend, T: ArrayElement + Float>(input: &Input<T>) -> Output<Tlet c_out_size = input.suffix_len as usize * input.proj_dim as usize;let state_size = input.num_channels as usize * input.state_stride as usize;- let padded = alloc_allocation_with_data::<B, T>(&context, &input.padded);- let w = alloc_allocation_with_data::<B, T>(&context, &input.w);- let b = input.b.as_ref().map(|b| alloc_allocation_with_data::<B, T>(&context, b));+ let padded = create_buffer_with_data::<B, T>(&context, &input.padded);+ let w = create_buffer_with_data::<B, T>(&context, &input.w);+ let b = input.b.as_ref().map(|b| create_buffer_with_data::<B, T>(&context, b));- let mut x_out = alloc_allocation::<B, T>(&context, x_out_size);- let mut b_out = alloc_allocation::<B, T>(&context, b_out_size);- let mut c_out = alloc_allocation::<B, T>(&context, c_out_size);- let mut state_out = alloc_allocation::<B, T>(&context, state_size);+ let mut x_out = create_buffer::<B, T>(&context, x_out_size);+ let mut b_out = create_buffer::<B, T>(&context, b_out_size);+ let mut c_out = create_buffer::<B, T>(&context, c_out_size);+ let mut state_out = create_buffer::<B, T>(&context, state_size);- let mut encoder = Encoder::new(context.as_ref()).expect("Failed to create encoder");+ let mut command_buffer = context.create_command_buffer(None, None).expect("Failed to create command buffer");kernel.encode(&padded,&w,@@ -118,15 +121,15 @@ fn get_output<B: Backend, T: ArrayElement + Float>(input: &Input<T>) -> Output<Tinput.inner_dim,input.proj_dim,input.activation_type,- &mut encoder,+ &mut command_buffer,);- encoder.end_encoding().submit().wait_until_completed().expect("Failed to wait command buffer");+ command_buffer.end_encoding().submit().wait_until_completed().expect("Failed to wait command buffer");Output {- x_out: allocation_to_vec(&x_out),- b_out: allocation_to_vec(&b_out),- c_out: allocation_to_vec(&c_out),- state_out: allocation_to_vec(&state_out),+ x_out: buffer_to_vec(&x_out),+ b_out: buffer_to_vec(&b_out),+ c_out: buffer_to_vec(&c_out),+ state_out: buffer_to_vec(&state_out),}}diff --git a/crates/uzu-engine/unit/backends/common/kernel/ssm/ssm_prefill_test.rs b/crates/uzu-engine/unit/backends/common/kernel/ssm/ssm_prefill_test.rsindex 6f18303ec..13a77f41e 100644--- a/crates/uzu-engine/unit/backends/common/kernel/ssm/ssm_prefill_test.rs+++ b/crates/uzu-engine/unit/backends/common/kernel/ssm/ssm_prefill_test.rs@@ -6,11 +6,14 @@ use uzu_engine_macros::uzu_test;use crate::{array::ArrayElement,- backends::common::{Backend, Context, Encoder, Kernels, gpu_types::ActivationType, kernel::SSDPrefillKernel},+ backends::common::{+ Backend, CommandBufferEncoding, CommandBufferExecutable, CommandBufferPending, Context, Kernels,+ gpu_types::ActivationType, kernel::SSDPrefillKernel,+ },data_type::DataType,tests::{assert::assert_eq_float,- helpers::{alloc_allocation, alloc_allocation_with_data, allocation_to_vec, for_each_non_cpu_backend},+ helpers::{buffer_to_vec, create_buffer, create_buffer_with_data, for_each_non_cpu_backend},},};@@ -90,21 +93,21 @@ fn get_output<B: Backend, T: ArrayElement + Float>(input: &Input<T>) -> Output<Tlet total_x = input.suffix_len * input.num_heads * input.head_dim;- let x = alloc_allocation_with_data::<B, T>(&context, &input.x);- let dt = alloc_allocation_with_data::<B, T>(&context, &input.dt);- let b = alloc_allocation_with_data::<B, T>(&context, &input.b);- let c = alloc_allocation_with_data::<B, T>(&context, &input.c);- let d = alloc_allocation_with_data::<B, T>(&context, &input.d);- let z = alloc_allocation_with_data::<B, T>(&context, &input.z);- let mut state = alloc_allocation_with_data::<B, T>(&context, &input.state);- let mut y = alloc_allocation::<B, T>(&context, total_x);+ let x = create_buffer_with_data::<B, T>(&context, &input.x);+ let dt = create_buffer_with_data::<B, T>(&context, &input.dt);+ let b = create_buffer_with_data::<B, T>(&context, &input.b);+ let c = create_buffer_with_data::<B, T>(&context, &input.c);+ let d = create_buffer_with_data::<B, T>(&context, &input.d);+ let z = create_buffer_with_data::<B, T>(&context, &input.z);+ let mut state = create_buffer_with_data::<B, T>(&context, &input.state);+ let mut y = create_buffer::<B, T>(&context, total_x);let x_strides: [u32; 3] = input.x_strides.map(|s| s as u32);let dt_strides: [u32; 2] = input.dt_strides.map(|s| s as u32);let cb_strides: [u32; 3] = input.cb_strides.map(|s| s as u32);let state_strides: [u32; 3] = input.state_strides.map(|s| s as u32);- let mut encoder = Encoder::new(context.as_ref()).expect("Failed to create encoder");+ let mut command_buffer = context.create_command_buffer(None, None).expect("Failed to create command buffer");let kernel = <<B as Backend>::Kernels as Kernels>::SSDPrefillKernel::new(&context, T::data_type()).expect("Failed to create SSDPrefillKernel");kernel.encode(@@ -125,13 +128,13 @@ fn get_output<B: Backend, T: ArrayElement + Float>(input: &Input<T>) -> Output<T&state_strides,input.num_heads as u32,input.head_dim as u32,- &mut encoder,+ &mut command_buffer,);- encoder.end_encoding().submit().wait_until_completed().expect("Failed to wait command buffer");+ command_buffer.end_encoding().submit().wait_until_completed().expect("Failed to wait command buffer");Output {- y: allocation_to_vec(&y),- state: allocation_to_vec(&state),+ y: buffer_to_vec(&y),+ state: buffer_to_vec(&state),}}diff --git a/crates/uzu-engine/unit/backends/common/kernel/ssm/ssm_split_inproj_test.rs b/crates/uzu-engine/unit/backends/common/kernel/ssm/ssm_split_inproj_test.rsindex d4e95323c..e72fc14d5 100644--- a/crates/uzu-engine/unit/backends/common/kernel/ssm/ssm_split_inproj_test.rs+++ b/crates/uzu-engine/unit/backends/common/kernel/ssm/ssm_split_inproj_test.rs@@ -7,13 +7,16 @@ use uzu_engine_macros::uzu_test;use crate::{array::ArrayElement,backends::{- common::{Backend, Context, Encoder, Kernels, kernel::SplitInProjKernel},+ common::{+ Backend, CommandBufferEncoding, CommandBufferExecutable, CommandBufferPending, Context, Kernels,+ kernel::SplitInProjKernel,+ },cpu::Cpu,},data_type::DataType,tests::{assert::assert_eq_float,- helpers::{alloc_allocation, alloc_allocation_with_data, allocation_to_vec, for_each_non_cpu_backend},+ helpers::{buffer_to_vec, create_buffer, create_buffer_with_data, for_each_non_cpu_backend},},};@@ -65,16 +68,16 @@ fn get_output<B: Backend, T: ArrayElement + Float>(input: &Input<T>) -> Output<Tlet z_out_size = input.suffix_length as usize * input.inner_dim as usize;let dt_out_size = input.suffix_length as usize * input.num_heads as usize;- let input_allocation = alloc_allocation_with_data::<B, T>(&context, &input.input);- let z_bias = alloc_allocation_with_data::<B, T>(&context, &input.z_bias);+ let input_buffer = create_buffer_with_data::<B, T>(&context, &input.input);+ let z_bias = create_buffer_with_data::<B, T>(&context, &input.z_bias);- let mut conv_out = alloc_allocation::<B, T>(&context, conv_out_size);- let mut z_out = alloc_allocation::<B, T>(&context, z_out_size);- let mut dt_out = alloc_allocation::<B, T>(&context, dt_out_size);+ let mut conv_out = create_buffer::<B, T>(&context, conv_out_size);+ let mut z_out = create_buffer::<B, T>(&context, z_out_size);+ let mut dt_out = create_buffer::<B, T>(&context, dt_out_size);- let mut encoder = Encoder::new(context.as_ref()).expect("Failed to create encoder");+ let mut command_buffer = context.create_command_buffer(None, None).expect("Failed to create command buffer");kernel.encode(- &input_allocation,+ &input_buffer,&mut conv_out,&mut z_out,&mut dt_out,@@ -84,14 +87,14 @@ fn get_output<B: Backend, T: ArrayElement + Float>(input: &Input<T>) -> Output<Tinput.conv_dim,input.inner_dim,input.num_heads,- &mut encoder,+ &mut command_buffer,);- encoder.end_encoding().submit().wait_until_completed().expect("Failed to wait command buffer");+ command_buffer.end_encoding().submit().wait_until_completed().expect("Failed to wait command buffer");Output {- conv_out: allocation_to_vec(&conv_out),- z_out: allocation_to_vec(&z_out),- dt_out: allocation_to_vec(&dt_out),+ conv_out: buffer_to_vec(&conv_out),+ z_out: buffer_to_vec(&z_out),+ dt_out: buffer_to_vec(&dt_out),}}diff --git a/crates/uzu-engine/unit/backends/common/kernel/ssm/ssm_update_test.rs b/crates/uzu-engine/unit/backends/common/kernel/ssm/ssm_update_test.rsindex 953ef55e9..f1cd7b71f 100644--- a/crates/uzu-engine/unit/backends/common/kernel/ssm/ssm_update_test.rs+++ b/crates/uzu-engine/unit/backends/common/kernel/ssm/ssm_update_test.rs@@ -7,13 +7,16 @@ use uzu_engine_macros::uzu_test;use crate::{array::ArrayElement,backends::{- common::{Allocation, Backend, Context, Encoder, Kernels, kernel::SSDUpdateKernel},+ common::{+ Backend, CommandBufferEncoding, CommandBufferExecutable, CommandBufferPending, Context, Kernels,+ kernel::SSDUpdateKernel,+ },cpu::Cpu,},data_type::DataType,tests::{assert::assert_eq_float,- helpers::{alloc_allocation, alloc_allocation_with_data, allocation_to_vec, for_each_non_cpu_backend},+ helpers::{buffer_to_vec, create_buffer, create_buffer_with_data, for_each_non_cpu_backend},},};@@ -98,19 +101,19 @@ fn get_output<B: Backend, T: ArrayElement + Float>(input: &Input<T>) -> Output<Tlet y_size = bsz * h * dh;let ns_size = bsz * h * dh * n;- let x = alloc_allocation_with_data::<B, T>(&context, &input.x);- let dt = alloc_allocation_with_data::<B, T>(&context, &input.dt);- let b = alloc_allocation_with_data::<B, T>(&context, &input.b);- let c = alloc_allocation_with_data::<B, T>(&context, &input.c);- let d = alloc_allocation_with_data::<B, T>(&context, &input.d);- let z = alloc_allocation_with_data::<B, T>(&context, &input.z);+ let x = create_buffer_with_data::<B, T>(&context, &input.x);+ let dt = create_buffer_with_data::<B, T>(&context, &input.dt);+ let b = create_buffer_with_data::<B, T>(&context, &input.b);+ let c = create_buffer_with_data::<B, T>(&context, &input.c);+ let d = create_buffer_with_data::<B, T>(&context, &input.d);+ let z = create_buffer_with_data::<B, T>(&context, &input.z);- let mut y = alloc_allocation::<B, T>(&context, y_size);+ let mut y = create_buffer::<B, T>(&context, y_size);if input.state_in_place {- let mut next_state = alloc_allocation_with_data::<B, T>(&context, &input.state);+ let mut next_state = create_buffer_with_data::<B, T>(&context, &input.state);- let mut encoder = Encoder::new(context.as_ref()).expect("Failed to create encoder");+ let mut command_buffer = context.create_command_buffer(None, None).expect("Failed to create command buffer");kernel.encode(&x,&dt,@@ -118,7 +121,7 @@ fn get_output<B: Backend, T: ArrayElement + Float>(input: &Input<T>) -> Output<T&c,&d,&z,- None::<&Allocation<B>>,+ None::<&B::GlobalBuffer>,&mut y,&mut next_state,(h / g) as u32,@@ -130,19 +133,19 @@ fn get_output<B: Backend, T: ArrayElement + Float>(input: &Input<T>) -> Output<Tinput.bsz,input.h,input.dh,- &mut encoder,+ &mut command_buffer,);- encoder.end_encoding().submit().wait_until_completed().expect("Failed to wait command buffer");+ command_buffer.end_encoding().submit().wait_until_completed().expect("Failed to wait command buffer");Output {- y: allocation_to_vec(&y),- next_state: allocation_to_vec(&next_state),+ y: buffer_to_vec(&y),+ next_state: buffer_to_vec(&next_state),}} else {- let state = alloc_allocation_with_data::<B, T>(&context, &input.state);- let mut next_state = alloc_allocation::<B, T>(&context, ns_size);+ let state = create_buffer_with_data::<B, T>(&context, &input.state);+ let mut next_state = create_buffer::<B, T>(&context, ns_size);- let mut encoder = Encoder::new(context.as_ref()).expect("Failed to create encoder");+ let mut command_buffer = context.create_command_buffer(None, None).expect("Failed to create command buffer");kernel.encode(&x,&dt,@@ -162,13 +165,13 @@ fn get_output<B: Backend, T: ArrayElement + Float>(input: &Input<T>) -> Output<Tinput.bsz,input.h,input.dh,- &mut encoder,+ &mut command_buffer,);- encoder.end_encoding().submit().wait_until_completed().expect("Failed to wait command buffer");+ command_buffer.end_encoding().submit().wait_until_completed().expect("Failed to wait command buffer");Output {- y: allocation_to_vec(&y),- next_state: allocation_to_vec(&next_state),+ y: buffer_to_vec(&y),+ next_state: buffer_to_vec(&next_state),}}}diff --git a/crates/uzu-engine/unit/backends/common/kernel/tensor_add_bias_test.rs b/crates/uzu-engine/unit/backends/common/kernel/tensor_add_bias_test.rsindex 4f9bd0a19..4b8970125 100644--- a/crates/uzu-engine/unit/backends/common/kernel/tensor_add_bias_test.rs+++ b/crates/uzu-engine/unit/backends/common/kernel/tensor_add_bias_test.rs@@ -6,8 +6,11 @@ use uzu_engine_macros::uzu_test;use crate::{array::ArrayElement,- backends::common::{Backend, Context, Encoder, Kernels, kernel::TensorAddBiasKernel},- tests::helpers::{alloc_allocation, alloc_allocation_with_data, allocation_to_vec, for_each_backend},+ backends::common::{+ Backend, CommandBufferEncoding, CommandBufferExecutable, CommandBufferPending, Context, Kernels,+ kernel::TensorAddBiasKernel,+ },+ tests::helpers::{buffer_to_vec, create_buffer, create_buffer_with_data, for_each_backend},};struct Input<T: ArrayElement + Float> {@@ -67,25 +70,25 @@ fn get_output<T: ArrayElement + Float, B: Backend>(.expect("Failed to create TensorAddBiasKernel");let size = input.length as usize;- let input_allocation = (!in_place).then(|| alloc_allocation_with_data::<B, T>(&context, &input.input));- let bias_allocation = alloc_allocation_with_data::<B, T>(&context, &input.bias);- let mut output_allocation = match in_place {- true => alloc_allocation_with_data::<B, T>(&context, &input.output),- false => alloc_allocation::<B, T>(&context, size),+ let input_buffer = (!in_place).then(|| create_buffer_with_data::<B, T>(&context, &input.input));+ let bias_buffer = create_buffer_with_data::<B, T>(&context, &input.bias);+ let mut output_buffer = match in_place {+ true => create_buffer_with_data::<B, T>(&context, &input.output),+ false => create_buffer::<B, T>(&context, size),};- let mut encoder = Encoder::new(context.as_ref()).expect("Failed to create encoder");+ let mut command_buffer = context.create_command_buffer(None, None).expect("Failed to create command buffer");kernel.encode(- input_allocation.as_ref(),- &bias_allocation,- &mut output_allocation,+ input_buffer.as_ref(),+ &bias_buffer,+ &mut output_buffer,input.num_cols,input.length,- &mut encoder,+ &mut command_buffer,);- encoder.end_encoding().submit().wait_until_completed().unwrap();+ command_buffer.end_encoding().submit().wait_until_completed().unwrap();- allocation_to_vec::<B, T>(&output_allocation)+ buffer_to_vec::<B, T>(&output_buffer)}fn test<T: ArrayElement + Float + Debug>(in_place: bool) {diff --git a/crates/uzu-engine/unit/backends/common/kernel/tensor_add_scale_test.rs b/crates/uzu-engine/unit/backends/common/kernel/tensor_add_scale_test.rsindex b4c806e06..36b50dc28 100644--- a/crates/uzu-engine/unit/backends/common/kernel/tensor_add_scale_test.rs+++ b/crates/uzu-engine/unit/backends/common/kernel/tensor_add_scale_test.rs@@ -7,13 +7,16 @@ use uzu_engine_macros::uzu_test;use crate::{array::ArrayElement,backends::{- common::{Backend, Context, Encoder, Kernels, kernel::TensorAddScaleKernel},+ common::{+ Backend, CommandBufferEncoding, CommandBufferExecutable, CommandBufferPending, Context, Kernels,+ kernel::TensorAddScaleKernel,+ },cpu::Cpu,},data_type::DataType,tests::{assert::assert_eq_float,- helpers::{alloc_allocation, alloc_allocation_with_data, allocation_to_vec, for_each_non_cpu_backend},+ helpers::{buffer_to_vec, create_buffer, create_buffer_with_data, for_each_non_cpu_backend},},};@@ -46,26 +49,26 @@ fn get_output<T: ArrayElement + Float, B: Backend>(let length = input.length as usize;let num_cols = input.num_cols as usize;- let input_allocation = (!in_place).then(|| alloc_allocation_with_data::<B, T>(&context, &input.input[..length]));- let bias_allocation = alloc_allocation_with_data::<B, T>(&context, &input.bias[..num_cols]);- let mut output_allocation = match in_place {- true => alloc_allocation_with_data::<B, T>(&context, &input.input[..length]),- false => alloc_allocation::<B, T>(&context, length),+ let input_buffer = (!in_place).then(|| create_buffer_with_data::<B, T>(&context, &input.input[..length]));+ let bias_buffer = create_buffer_with_data::<B, T>(&context, &input.bias[..num_cols]);+ let mut output_buffer = match in_place {+ true => create_buffer_with_data::<B, T>(&context, &input.input[..length]),+ false => create_buffer::<B, T>(&context, length),};- let mut encoder = Encoder::new(context.as_ref()).expect("Failed to create encoder");+ let mut command_buffer = context.create_command_buffer(None, None).expect("Failed to create command buffer");kernel.encode(- input_allocation.as_ref(),- &bias_allocation,- &mut output_allocation,+ input_buffer.as_ref(),+ &bias_buffer,+ &mut output_buffer,input.num_cols,input.length,input.scale,- &mut encoder,+ &mut command_buffer,);- encoder.end_encoding().submit().wait_until_completed().unwrap();+ command_buffer.end_encoding().submit().wait_until_completed().unwrap();- allocation_to_vec::<B, T>(&output_allocation)+ buffer_to_vec::<B, T>(&output_buffer)}fn get_test_data_basic<T: ArrayElement + Float>() -> (Input<T>, Vec<T>) {diff --git a/crates/uzu-engine/unit/backends/common/kernel/tensor_add_swap_test.rs b/crates/uzu-engine/unit/backends/common/kernel/tensor_add_swap_test.rsdeleted file mode 100644index 3b9158310..000000000--- a/crates/uzu-engine/unit/backends/common/kernel/tensor_add_swap_test.rs+++ /dev/null@@ -1,90 +0,0 @@-use std::fmt::Debug;--use half::{bf16, f16};-use num_traits::Float;-use uzu_engine_macros::uzu_test;--use crate::{- array::ArrayElement,- backends::common::{Backend, Context, Encoder, Kernels, kernel::TensorAddSwapKernel},- tests::helpers::{alloc_allocation_with_data, allocation_to_vec, for_each_backend},-};--struct Input<T: ArrayElement + Float> {- skip_buffer: Box<[T]>,- main_buffer: Box<[T]>,- length: u32,-}--fn get_test_data<T: ArrayElement + Float>() -> (Input<T>, Vec<T>) {- let length = 1025usize;-- let mut skip_buffer: Vec<T> = vec![T::zero(); length];- let mut main_buffer: Vec<T> = vec![T::zero(); length];- let mut expected: Vec<T> = vec![T::zero(); length];-- for i in 0..length {- skip_buffer[i] = T::from((i as f32).sin() * 30f32).unwrap();- main_buffer[i] = T::from((i as f32).cos() * 30f32).unwrap();- expected[i] = skip_buffer[i] + main_buffer[i];- }-- let input = Input {- skip_buffer: skip_buffer.into_boxed_slice(),- main_buffer: main_buffer.into_boxed_slice(),- length: length as u32,- };-- (input, expected)-}--fn get_output<T: ArrayElement + Float, B: Backend>(input: &Input<T>) -> (Vec<T>, Vec<T>) {- let context = B::Context::new().expect("Failed to create Context");-- let kernel = <<B as Backend>::Kernels as Kernels>::TensorAddSwapKernel::new(&context, T::data_type())- .expect("Failed to create TensorAddSwapKernel");-- let size = input.length as usize;- let mut skip_allocation = alloc_allocation_with_data::<B, T>(&context, &input.skip_buffer[..size]);- let mut main_allocation = alloc_allocation_with_data::<B, T>(&context, &input.main_buffer[..size]);-- let mut encoder = Encoder::new(context.as_ref()).expect("Failed to create encoder");- kernel.encode(&mut skip_allocation, &mut main_allocation, input.length, &mut encoder);- encoder.end_encoding().submit().wait_until_completed().unwrap();-- (allocation_to_vec::<B, T>(&skip_allocation), allocation_to_vec::<B, T>(&main_allocation))-}--fn test<T: ArrayElement + Float + Debug>() {- let (input, expected) = get_test_data::<T>();- for_each_backend!(|B| {- let (skip_output, main_output) = get_output::<T, B>(&input);- assert_eq!(- skip_output,- expected,- "skip_buffer results are not equal for backend {}",- std::any::type_name::<B>()- );- assert_eq!(- main_output,- expected,- "main_buffer results are not equal for backend {}",- std::any::type_name::<B>()- );- });-}--#[uzu_test]-fn test_f32() {- test::<f32>();-}--#[uzu_test]-fn test_f16() {- test::<f16>();-}--#[uzu_test]-fn test_bf16() {- test::<bf16>();-}diff --git a/crates/uzu-engine/unit/backends/common/kernel/tensor_copy_test.rs b/crates/uzu-engine/unit/backends/common/kernel/tensor_copy_test.rsdeleted file mode 100644index aadc7806b..000000000--- a/crates/uzu-engine/unit/backends/common/kernel/tensor_copy_test.rs+++ /dev/null@@ -1,75 +0,0 @@-use std::fmt::Debug;--use half::{bf16, f16};-use num_traits::Float;-use uzu_engine_macros::uzu_test;--use crate::{- array::ArrayElement,- backends::common::{Backend, Context, Encoder, Kernels, kernel::TensorCopyKernel},- tests::helpers::{alloc_allocation, alloc_allocation_with_data, allocation_to_vec, for_each_backend},-};--struct Input<T: ArrayElement + Float> {- src: Box<[T]>,- length: u32,-}--fn get_test_data<T: ArrayElement + Float>() -> (Input<T>, Vec<T>) {- let length = 1025usize;-- let mut src: Vec<T> = vec![T::zero(); length];- let mut expected: Vec<T> = vec![T::zero(); length];-- for i in 0..length {- src[i] = T::from((i as f32).sin() * 30f32).unwrap();- expected[i] = src[i];- }-- let input = Input {- src: src.into_boxed_slice(),- length: length as u32,- };-- (input, expected)-}--fn get_output<T: ArrayElement + Float, B: Backend>(input: &Input<T>) -> Vec<T> {- let context = B::Context::new().expect("Failed to create Context");-- let kernel = <<B as Backend>::Kernels as Kernels>::TensorCopyKernel::new(&context, T::data_type())- .expect("Failed to create TensorCopyKernel");-- let size = input.length as usize;- let src_allocation = alloc_allocation_with_data::<B, T>(&context, &input.src[..size]);- let mut dst_allocation = alloc_allocation::<B, T>(&context, size);-- let mut encoder = Encoder::new(context.as_ref()).expect("Failed to create encoder");- kernel.encode(&src_allocation, &mut dst_allocation, input.length, &mut encoder);- encoder.end_encoding().submit().wait_until_completed().unwrap();-- allocation_to_vec::<B, T>(&dst_allocation)-}--fn test<T: ArrayElement + Float + Debug>() {- let (input, expected) = get_test_data::<T>();- for_each_backend!(|B| {- let output = get_output::<T, B>(&input);- assert_eq!(output, expected, "Results are not equal for backend {}", std::any::type_name::<B>());- });-}--#[uzu_test]-fn test_f32() {- test::<f32>();-}--#[uzu_test]-fn test_f16() {- test::<f16>();-}--#[uzu_test]-fn test_bf16() {- test::<bf16>();-}diff --git a/crates/uzu-engine/unit/backends/common/kernel/weaver/weaver_frontier_test.rs b/crates/uzu-engine/unit/backends/common/kernel/weaver/weaver_frontier_test.rsindex c5a2d67de..08d9b30fe 100644--- a/crates/uzu-engine/unit/backends/common/kernel/weaver/weaver_frontier_test.rs+++ b/crates/uzu-engine/unit/backends/common/kernel/weaver/weaver_frontier_test.rs@@ -3,13 +3,13 @@ use uzu_engine_macros::uzu_test;use crate::{backends::{common::{- Backend, Encoder, Kernels,+ Backend, CommandBufferEncoding, CommandBufferExecutable, CommandBufferPending, Context, Kernels,gpu_types::weaver::{FrontierIdx, MetadataIdx, TreeIdx},kernel::{WeaverFrontierInsertChildrenKernel, WeaverFrontierSelectKernel},},cpu::Cpu,},- tests::helpers::{alloc_allocation_with_data, allocation_to_vec, create_context, for_each_non_cpu_backend},+ tests::helpers::{buffer_to_vec, create_buffer_with_data, create_context, for_each_non_cpu_backend},};fn select<B: Backend>() -> Vec<u32> {@@ -32,20 +32,20 @@ fn select<B: Backend>() -> Vec<u32> {frontier[lane * 8 + slot] = value;}}- let mut frontier = alloc_allocation_with_data::<B, u32>(&context, &frontier);- let mut tree = alloc_allocation_with_data::<B, u32>(&context, &[55; TreeIdx::COUNT * 7]);- let mut slot_ancestors = alloc_allocation_with_data::<B, u32>(&context, &(0u32..7 * 3).collect::<Vec<_>>());- let mut token = alloc_allocation_with_data::<B, u32>(&context, &[66; 4]);- let mut metadata = alloc_allocation_with_data::<B, u32>(&context, &[77; 3 * 4]);- let mut ancestors = alloc_allocation_with_data::<B, u32>(&context, &[88; 4 * 3]);- let mut valid = alloc_allocation_with_data::<B, u32>(&context, &[99; 4]);- let candidate_pool_ids = alloc_allocation_with_data::<B, u32>(&context, &(0..12).collect::<Vec<_>>());+ let mut frontier = create_buffer_with_data::<B, u32>(&context, &frontier);+ let mut tree = create_buffer_with_data::<B, u32>(&context, &[55; TreeIdx::COUNT * 7]);+ let mut slot_ancestors = create_buffer_with_data::<B, u32>(&context, &(0u32..7 * 3).collect::<Vec<_>>());+ let mut token = create_buffer_with_data::<B, u32>(&context, &[66; 4]);+ let mut metadata = create_buffer_with_data::<B, u32>(&context, &[77; 3 * 4]);+ let mut ancestors = create_buffer_with_data::<B, u32>(&context, &[88; 4 * 3]);+ let mut valid = create_buffer_with_data::<B, u32>(&context, &[99; 4]);+ let candidate_pool_ids = create_buffer_with_data::<B, u32>(&context, &(0..12).collect::<Vec<_>>());let candidate_pool_scores =- alloc_allocation_with_data::<B, f32>(&context, &(0..12).map(|value| value as f32).collect::<Vec<_>>());- let mut candidate_ids = alloc_allocation_with_data::<B, u32>(&context, &[0; 4 * 3]);- let mut candidate_scores = alloc_allocation_with_data::<B, f32>(&context, &[0.0; 4 * 3]);+ create_buffer_with_data::<B, f32>(&context, &(0..12).map(|value| value as f32).collect::<Vec<_>>());+ let mut candidate_ids = create_buffer_with_data::<B, u32>(&context, &[0; 4 * 3]);+ let mut candidate_scores = create_buffer_with_data::<B, f32>(&context, &[0.0; 4 * 3]);let kernel = <B::Kernels as Kernels>::WeaverFrontierSelectKernel::new(&context).unwrap();- let mut encoder = Encoder::new(context.as_ref()).unwrap();+ let mut command_buffer = context.create_command_buffer(None, None).unwrap();kernel.encode(&mut frontier,&mut tree,@@ -67,13 +67,13 @@ fn select<B: Backend>() -> Vec<u32> {3,4,3,- &mut encoder,+ &mut command_buffer,);- encoder.end_encoding().submit().wait_until_completed().unwrap();+ command_buffer.end_encoding().submit().wait_until_completed().unwrap();[frontier, tree, slot_ancestors, token, metadata, ancestors, valid, candidate_ids].iter()- .flat_map(allocation_to_vec)- .chain(allocation_to_vec::<B, f32>(&candidate_scores).into_iter().map(f32::to_bits))+ .flat_map(buffer_to_vec)+ .chain(buffer_to_vec::<B, f32>(&candidate_scores).into_iter().map(f32::to_bits)).collect()}@@ -87,20 +87,33 @@ fn insert_children<B: Backend>() -> Vec<u32> {tree[TreeIdx::PathLogprobBits as usize * 4..(TreeIdx::PathLogprobBits as usize + 1) * 4].copy_from_slice(&TREE_PATH_LOGPROBS.map(f32::to_bits));tree[TreeIdx::Depth as usize * 4..(TreeIdx::Depth as usize + 1) * 4].copy_from_slice(&[0, 2, 4, 6]);- let tree = alloc_allocation_with_data::<B, u32>(&context, &tree);+ let tree = create_buffer_with_data::<B, u32>(&context, &tree);let mut metadata = vec![0; MetadataIdx::COUNT * 3];metadata[MetadataIdx::TreeSlot as usize * 3..(MetadataIdx::TreeSlot as usize + 1) * 3].copy_from_slice(&[1, 3, 0]);- let metadata = alloc_allocation_with_data::<B, u32>(&context, &metadata);- let valid = alloc_allocation_with_data::<B, u32>(&context, &[1, 0, 1]);- let ids = alloc_allocation_with_data::<B, u32>(&context, &(10..19).collect::<Vec<_>>());- let scores = alloc_allocation_with_data::<B, f32>(&context, &MODEL_LOGPROBS);- let prune_scores = alloc_allocation_with_data::<B, f32>(&context, &PRUNE_LOGPROBS);- let mut frontier = alloc_allocation_with_data::<B, u32>(&context, &[42; FrontierIdx::COUNT * 16]);+ let metadata = create_buffer_with_data::<B, u32>(&context, &metadata);+ let valid = create_buffer_with_data::<B, u32>(&context, &[1, 0, 1]);+ let ids = create_buffer_with_data::<B, u32>(&context, &(10..19).collect::<Vec<_>>());+ let scores = create_buffer_with_data::<B, f32>(&context, &MODEL_LOGPROBS);+ let prune_scores = create_buffer_with_data::<B, f32>(&context, &PRUNE_LOGPROBS);+ let mut frontier = create_buffer_with_data::<B, u32>(&context, &[42; FrontierIdx::COUNT * 16]);let kernel = <B::Kernels as Kernels>::WeaverFrontierInsertChildrenKernel::new(&context).unwrap();- let mut encoder = Encoder::new(context.as_ref()).unwrap();- kernel.encode(&tree, &metadata, &valid, &ids, &scores, &prune_scores, &mut frontier, 16, 4, 3, 3, &mut encoder);- encoder.end_encoding().submit().wait_until_completed().unwrap();- allocation_to_vec(&frontier)+ let mut command_buffer = context.create_command_buffer(None, None).unwrap();+ kernel.encode(+ &tree,+ &metadata,+ &valid,+ &ids,+ &scores,+ &prune_scores,+ &mut frontier,+ 16,+ 4,+ 3,+ 3,+ &mut command_buffer,+ );+ command_buffer.end_encoding().submit().wait_until_completed().unwrap();+ buffer_to_vec(&frontier)}/// Expansion follows the model logprobs (path and its order key), final pruning reads the edge lane, which takes thediff --git a/crates/uzu-engine/unit/backends/common/kernel/weaver/weaver_top_children_test.rs b/crates/uzu-engine/unit/backends/common/kernel/weaver/weaver_top_children_test.rsindex 2e513eeb6..e507841cd 100644--- a/crates/uzu-engine/unit/backends/common/kernel/weaver/weaver_top_children_test.rs+++ b/crates/uzu-engine/unit/backends/common/kernel/weaver/weaver_top_children_test.rs@@ -3,13 +3,14 @@ use uzu_engine_macros::uzu_test;use crate::{backends::{- common::{Backend, Encoder, Kernels, gpu_types::weaver::MetadataIdx, kernel::WeaverTopChildrenKernel},+ common::{+ Backend, CommandBufferEncoding, CommandBufferExecutable, CommandBufferPending, Context, Kernels,+ gpu_types::weaver::MetadataIdx, kernel::WeaverTopChildrenKernel,+ },cpu::Cpu,},encodable_block::sampling::{gumbel_float, revidx},- tests::helpers::{- alloc_allocation, alloc_allocation_with_data, allocation_to_vec, create_context, for_each_non_cpu_backend,- },+ tests::helpers::{buffer_to_vec, create_buffer, create_buffer_with_data, create_context, for_each_non_cpu_backend},};const CANDIDATES: usize = 512;@@ -44,20 +45,20 @@ fn top_children<B: Backend>(assert_eq!(ids.len(), rows * CANDIDATES);assert!(rows <= DEPTHS.len());let context = create_context::<B>();- let residual = alloc_allocation_with_data::<B, bf16>(&context, residual);- let candidate_logits = alloc_allocation_with_data::<B, f32>(&context, candidate_logits);- let ids = alloc_allocation_with_data::<B, u32>(&context, ids);- let depth_seeds = alloc_allocation_with_data::<B, u64>(&context, &DEPTH_SEEDS);+ let residual = create_buffer_with_data::<B, bf16>(&context, residual);+ let candidate_logits = create_buffer_with_data::<B, f32>(&context, candidate_logits);+ let ids = create_buffer_with_data::<B, u32>(&context, ids);+ let depth_seeds = create_buffer_with_data::<B, u64>(&context, &DEPTH_SEEDS);let mut metadata_values = vec![0u32; rows * MetadataIdx::COUNT];for row in 0..rows {metadata_values[MetadataIdx::Depth as usize * rows + row] = DEPTHS[row];}- let node_metadata = alloc_allocation_with_data::<B, u32>(&context, &metadata_values);- let mut output_token_ids = alloc_allocation::<B, u32>(&context, rows * CHILDREN);- let mut output_model_logprobs = alloc_allocation::<B, f32>(&context, rows * CHILDREN);- let mut output_prune_logprobs = prune_noise_scale.map(|_| alloc_allocation::<B, f32>(&context, rows * CHILDREN));+ let node_metadata = create_buffer_with_data::<B, u32>(&context, &metadata_values);+ let mut output_token_ids = create_buffer::<B, u32>(&context, rows * CHILDREN);+ let mut output_model_logprobs = create_buffer::<B, f32>(&context, rows * CHILDREN);+ let mut output_prune_logprobs = prune_noise_scale.map(|_| create_buffer::<B, f32>(&context, rows * CHILDREN));let kernel = <B::Kernels as Kernels>::WeaverTopChildrenKernel::new(&context, prune_noise_scale.is_some()).unwrap();- let mut encoder = Encoder::new(context.as_ref()).unwrap();+ let mut command_buffer = context.create_command_buffer(None, None).unwrap();kernel.encode(&residual,&candidate_logits,@@ -72,13 +73,13 @@ fn top_children<B: Backend>(CHILDREN as u32,VOCAB_SIZE,prune_noise_scale,- &mut encoder,+ &mut command_buffer,);- encoder.end_encoding().submit().wait_until_completed().unwrap();+ command_buffer.end_encoding().submit().wait_until_completed().unwrap();(- allocation_to_vec(&output_token_ids),- allocation_to_vec(&output_model_logprobs),- output_prune_logprobs.as_ref().map(allocation_to_vec),+ buffer_to_vec(&output_token_ids),+ buffer_to_vec(&output_model_logprobs),+ output_prune_logprobs.as_ref().map(buffer_to_vec),)}diff --git a/crates/uzu-engine/unit/backends/metal/kernel/attention/gemm_test.rs b/crates/uzu-engine/unit/backends/metal/kernel/attention/gemm_test.rsindex ba21fe864..e820571a7 100644--- a/crates/uzu-engine/unit/backends/metal/kernel/attention/gemm_test.rs+++ b/crates/uzu-engine/unit/backends/metal/kernel/attention/gemm_test.rs@@ -8,7 +8,7 @@ use crate::{array::ArrayElement,backends::{common::{- Backend, Context, Encoder, Kernels,+ Backend, CommandBufferEncoding, CommandBufferExecutable, CommandBufferPending, Context, Kernels,kernel::{AttentionArguments, AttentionKernel, AttentionKernelConfig},},cpu::Cpu,@@ -18,7 +18,7 @@ use crate::{encodable_block::mixer::attention::KVCacheView,tests::{assert::assert_eq_float,- helpers::{alloc_allocation, alloc_allocation_with_data, allocation_to_vec},+ helpers::{buffer_to_vec, create_buffer, create_buffer_with_data},},};@@ -85,43 +85,43 @@ fn get_output<T: ArrayElement + Float, B: Backend>(input: &Input<T>) -> Vec<T> {let config = attention_config(input);- let queries_allocation = alloc_allocation_with_data::<B, T>(context.as_ref(), &input.queries);- let keys_allocation = alloc_allocation_with_data::<B, T>(context.as_ref(), &input.keys);- let values_allocation = alloc_allocation_with_data::<B, T>(context.as_ref(), &input.values);+ let queries_buffer = create_buffer_with_data::<B, T>(context.as_ref(), &input.queries);+ let keys_buffer = create_buffer_with_data::<B, T>(context.as_ref(), &input.keys);+ let values_buffer = create_buffer_with_data::<B, T>(context.as_ref(), &input.values);let segment_prefix_length = input.sequence_length - input.suffix_length;let args = AttentionArguments {- queries: &queries_allocation,- keys: &keys_allocation,- values: &values_allocation,+ queries: &queries_buffer,+ keys: &keys_buffer,+ values: &values_buffer,suffix_length: input.suffix_length as u32,- trie: None,+ trie: None::<&B::GlobalBuffer>,sinks: None,cache: KVCacheView::full(segment_prefix_length as u32),};- let mut encoder = Encoder::new(context.as_ref()).expect("Failed to create encoder");+ let mut command_buffer = context.create_command_buffer(None, None).expect("Failed to create command buffer");let kernel = <B::Kernels as Kernels>::AttentionKernel::new(context.as_ref(), config).expect("Failed to create attention kernel");- let pooled_output = kernel.encode(args, &mut encoder).expect("Failed to encode attention");- let mut output_allocation =- alloc_allocation::<B, T>(context.as_ref(), input.suffix_length * input.num_heads * input.head_dim);- encoder.encode_copy(&pooled_output, .., &mut output_allocation, ..);+ let pooled_output = kernel.encode(args, &mut command_buffer).expect("Failed to encode attention");+ let mut output_buffer =+ create_buffer::<B, T>(context.as_ref(), input.suffix_length * input.num_heads * input.head_dim);+ command_buffer.encode_copy(&pooled_output, &mut output_buffer);drop(pooled_output);- let completed = encoder.end_encoding().submit().wait_until_completed().unwrap();+ let completed = command_buffer.end_encoding().submit().wait_until_completed().unwrap();drop(completed);- allocation_to_vec::<B, T>(&output_allocation)+ buffer_to_vec::<B, T>(&output_buffer)}fn get_gemm_output<T: ArrayElement + Float>(input: &Input<T>) -> Vec<T> {let context = <Metal as Backend>::Context::new().expect("Failed to create Metal context");let config = attention_config(input);- let queries = alloc_allocation_with_data::<Metal, T>(context.as_ref(), &input.queries);- let keys = alloc_allocation_with_data::<Metal, T>(context.as_ref(), &input.keys);- let values = alloc_allocation_with_data::<Metal, T>(context.as_ref(), &input.values);+ let queries = create_buffer_with_data::<Metal, T>(context.as_ref(), &input.queries);+ let keys = create_buffer_with_data::<Metal, T>(context.as_ref(), &input.keys);+ let values = create_buffer_with_data::<Metal, T>(context.as_ref(), &input.values);let cache = KVCacheView::full((input.sequence_length - input.suffix_length) as u32);- let mut encoder = Encoder::new(context.as_ref()).expect("Failed to create encoder");+ let mut command_buffer = context.create_command_buffer(None, None).expect("Failed to create command buffer");let pooled = super::gemm::AttentionGemm::new(&config).encode(AttentionArguments {@@ -129,20 +129,20 @@ fn get_gemm_output<T: ArrayElement + Float>(input: &Input<T>) -> Vec<T> {keys: &keys,values: &values,suffix_length: input.suffix_length as u32,- trie: None,+ trie: None::<&<Metal as Backend>::GlobalBuffer>,sinks: None,cache,},- &mut encoder,+ &mut command_buffer,).expect("Failed to encode AttentionGemm");let mut output =- alloc_allocation::<Metal, T>(context.as_ref(), input.suffix_length * input.num_heads * input.head_dim);- encoder.encode_copy(&pooled, .., &mut output, ..);+ create_buffer::<Metal, T>(context.as_ref(), input.suffix_length * input.num_heads * input.head_dim);+ command_buffer.encode_copy(&pooled, &mut output);drop(pooled);- let completed = encoder.end_encoding().submit().wait_until_completed().unwrap();+ let completed = command_buffer.end_encoding().submit().wait_until_completed().unwrap();drop(completed);- allocation_to_vec::<Metal, T>(&output)+ buffer_to_vec::<Metal, T>(&output)}fn test_internal<T: ArrayElement + Float + Debug + Display>(diff --git a/crates/uzu-engine/unit/backends/metal/kernel/attention/kernel_test.rs b/crates/uzu-engine/unit/backends/metal/kernel/attention/kernel_test.rsindex 273fc8db6..6f5754056 100644--- a/crates/uzu-engine/unit/backends/metal/kernel/attention/kernel_test.rs+++ b/crates/uzu-engine/unit/backends/metal/kernel/attention/kernel_test.rs@@ -5,7 +5,7 @@ use uzu_engine_macros::uzu_test;use crate::{backends::{common::{- Allocation, Backend, Context, Encoder, Kernels,+ Backend, CommandBufferEncoding, CommandBufferExecutable, CommandBufferPending, Context, Kernels,gpu_types::trie::TrieNode as GpuTrieNode,kernel::{AttentionArguments, AttentionKernel},},@@ -15,7 +15,7 @@ use crate::{encodable_block::{mixer::attention::KVCacheView, sampling::PRng},tests::{assert::assert_eq_float,- helpers::{alloc_allocation, alloc_allocation_with_data, allocation_to_vec, submit_encoder},+ helpers::{buffer_to_vec, create_buffer, create_buffer_with_data, submit_command_buffer},},trie::TrieNode,};@@ -144,10 +144,10 @@ fn create_test_data((queries, keys, values)}-fn create_query_allocation(+fn create_query_buffer(queries: &Array4<f32>,context: &<Metal as Backend>::Context,-) -> Allocation<Metal> {+) -> <Metal as Backend>::GlobalBuffer {let (_batch_size, num_heads, sequence_length, head_dim) = queries.dim();let mut values = vec![0.0_f32; num_heads * sequence_length * head_dim];@@ -160,14 +160,14 @@ fn create_query_allocation(}}- alloc_allocation_with_data(context, &values)+ create_buffer_with_data::<Metal, _>(context, &values)}-fn create_attention_cache_allocation(+fn create_attention_cache_buffer(values: &Array4<f32>,max_sequence_length: usize,context: &<Metal as Backend>::Context,-) -> Allocation<Metal> {+) -> <Metal as Backend>::GlobalBuffer {let (_batch_size, num_kv_heads, sequence_length, head_dim) = values.dim();let mut cache = vec![0.0_f32; max_sequence_length * num_kv_heads * head_dim];@@ -180,14 +180,14 @@ fn create_attention_cache_allocation(}}- alloc_allocation_with_data(context, &cache)+ create_buffer_with_data::<Metal, _>(context, &cache)}-fn create_sinks_allocation(+fn create_sinks_buffer(sinks: &[f32],context: &<Metal as Backend>::Context,-) -> Allocation<Metal> {- alloc_allocation_with_data(context, sinks)+) -> <Metal as Backend>::GlobalBuffer {+ create_buffer_with_data::<Metal, _>(context, sinks)}fn convert_kernel_output(@@ -223,29 +223,29 @@ fn run_single_pass_attention(let (batch_size, num_heads, seq_len, head_dim) = queries.dim();let (_batch_size, _num_kv_heads, _seq_len, _head_dim) = keys.dim();- let query_buffer = create_query_allocation(queries, context);- let key_cache_buffer = create_attention_cache_allocation(keys, seq_len, context);- let value_cache_buffer = create_attention_cache_allocation(values, seq_len, context);- let sinks_buffer = sinks.map(|sinks| create_sinks_allocation(sinks, context));- let mut encoder = Encoder::new(context).expect("Failed to create encoder");+ let query_buffer = create_query_buffer(queries, context);+ let key_cache_buffer = create_attention_cache_buffer(keys, seq_len, context);+ let value_cache_buffer = create_attention_cache_buffer(values, seq_len, context);+ let sinks_buffer = sinks.map(|sinks| create_sinks_buffer(sinks, context));+ let mut command_buffer = context.create_command_buffer(None, None).expect("Failed to create command buffer");let pooled_output = kernel.encode(AttentionArguments {queries: &query_buffer,keys: &key_cache_buffer,values: &value_cache_buffer,suffix_length: seq_len as u32,- trie: None,+ trie: None::<&<Metal as Backend>::GlobalBuffer>,sinks: sinks_buffer.as_ref(),cache: KVCacheView::full(0),},- &mut encoder,+ &mut command_buffer,)?;- let mut output_buffer = alloc_allocation::<Metal, f32>(context, num_heads * seq_len * head_dim);- encoder.encode_copy(&pooled_output, .., &mut output_buffer, ..);+ let mut output_buffer = create_buffer::<Metal, f32>(context, num_heads * seq_len * head_dim);+ command_buffer.encode_copy(&pooled_output, &mut output_buffer);drop(pooled_output);- submit_encoder(encoder);+ submit_command_buffer(command_buffer);- let output_slice: Vec<f32> = allocation_to_vec(&output_buffer);+ let output_slice: Vec<f32> = buffer_to_vec(&output_buffer);let kernel_output = convert_kernel_output(&output_slice, batch_size, num_heads, seq_len, head_dim);Ok(kernel_output)@@ -291,31 +291,31 @@ fn run_gemm_attention(config.scale = Some(scale);let kernel = super::gemm::AttentionGemm::new(&config);- let query_allocation = create_query_allocation(queries, context);- let key_allocation = create_attention_cache_allocation(keys, seq_len, context);- let value_allocation = create_attention_cache_allocation(values, seq_len, context);+ let query_buffer = create_query_buffer(queries, context);+ let key_buffer = create_attention_cache_buffer(keys, seq_len, context);+ let value_buffer = create_attention_cache_buffer(values, seq_len, context);- let sinks_allocation = sinks.map(|sinks| create_sinks_allocation(sinks, context));- let mut encoder = Encoder::new(context).expect("Failed to create encoder");+ let sinks_buffer = sinks.map(|sinks| create_sinks_buffer(sinks, context));+ let mut command_buffer = context.create_command_buffer(None, None).expect("Failed to create command buffer");let args = AttentionArguments {- queries: &query_allocation,- keys: &key_allocation,- values: &value_allocation,+ queries: &query_buffer,+ keys: &key_buffer,+ values: &value_buffer,suffix_length: seq_len as u32,- trie: None,- sinks: sinks_allocation.as_ref(),+ trie: None::<&<Metal as Backend>::GlobalBuffer>,+ sinks: sinks_buffer.as_ref(),cache: KVCacheView::full(0),};- let pooled_output = kernel.encode(args, &mut encoder)?;- let mut output_allocation = alloc_allocation::<Metal, f32>(context, num_heads * seq_len * head_dim);- encoder.encode_copy(&pooled_output, .., &mut output_allocation, ..);- let completed = encoder.end_encoding().submit().wait_until_completed()?;+ let pooled_output = kernel.encode(args, &mut command_buffer)?;+ let mut output_buffer = create_buffer::<Metal, f32>(context, num_heads * seq_len * head_dim);+ command_buffer.encode_copy(&pooled_output, &mut output_buffer);+ let completed = command_buffer.end_encoding().submit().wait_until_completed()?;drop(pooled_output);drop(completed);- let output: Vec<f32> = allocation_to_vec(&output_allocation);+ let output: Vec<f32> = buffer_to_vec(&output_buffer);let kernel_output = convert_kernel_output(&output, batch_size, num_heads, seq_len, head_dim);@@ -474,11 +474,11 @@ fn run_two_pass_attention(_scale: f32,) -> Result<Array4<f32>, Box<dyn std::error::Error>> {let (batch_size, num_heads, seq_len, head_dim) = queries.dim();- let queries_buffer = create_query_allocation(queries, context);- let keys_buffer = create_attention_cache_allocation(keys, seq_len, context);- let values_buffer = create_attention_cache_allocation(values, seq_len, context);- let sinks_buffer = sinks.map(|sinks| create_sinks_allocation(sinks, context));- let mut encoder = Encoder::new(context).expect("Failed to create encoder");+ let queries_buffer = create_query_buffer(queries, context);+ let keys_buffer = create_attention_cache_buffer(keys, seq_len, context);+ let values_buffer = create_attention_cache_buffer(values, seq_len, context);+ let sinks_buffer = sinks.map(|sinks| create_sinks_buffer(sinks, context));+ let mut command_buffer = context.create_command_buffer(None, None).expect("Failed to create command buffer");let pooled_output = kernel.encode(AttentionArguments {@@ -486,18 +486,18 @@ fn run_two_pass_attention(keys: &keys_buffer,values: &values_buffer,suffix_length: seq_len as u32,- trie: None,+ trie: None::<&<Metal as Backend>::GlobalBuffer>,sinks: sinks_buffer.as_ref(),cache: KVCacheView::full(0),},- &mut encoder,+ &mut command_buffer,)?;- let mut output_buffer = alloc_allocation::<Metal, f32>(context, num_heads * seq_len * head_dim);- encoder.encode_copy(&pooled_output, .., &mut output_buffer, ..);+ let mut output_buffer = create_buffer::<Metal, f32>(context, num_heads * seq_len * head_dim);+ command_buffer.encode_copy(&pooled_output, &mut output_buffer);drop(pooled_output);- submit_encoder(encoder);+ submit_command_buffer(command_buffer);- let output_slice: Vec<f32> = allocation_to_vec(&output_buffer);+ let output_slice: Vec<f32> = buffer_to_vec(&output_buffer);let kernel_output = convert_kernel_output(&output_slice, batch_size, num_heads, seq_len, head_dim);Ok(kernel_output)@@ -597,12 +597,12 @@ fn run_attention_with_kernel<B: Backend>() -> Vec<bf16> {let (head_dim, num_q_heads, _, suffix_length, _, _) = shape;let queries =- alloc_allocation_with_data::<B, bf16>(context, &fill_attention(num_q_heads * suffix_length * head_dim, 0.5));- let keys = alloc_allocation_with_data::<B, bf16>(context, keys_data);- let values = alloc_allocation_with_data::<B, bf16>(context, values_data);+ create_buffer_with_data::<B, bf16>(context, &fill_attention(num_q_heads * suffix_length * head_dim, 0.5));+ let keys = create_buffer_with_data::<B, bf16>(context, keys_data);+ let values = create_buffer_with_data::<B, bf16>(context, values_data);let trie = trie_nodes.map(|nodes| {let words: Vec<u32> = nodes.iter().flat_map(|node| [node.trie_start, node.trie_end, node.height]).collect();- alloc_allocation_with_data::<B, u32>(context, &words)+ create_buffer_with_data::<B, u32>(context, &words)});let arguments = AttentionArguments {queries: &queries,@@ -613,14 +613,14 @@ fn run_attention_with_kernel<B: Backend>(sinks: None,cache,};- let mut encoder = Encoder::<B>::new(context).expect("encoder");- let pooled = kernel.encode(arguments, &mut encoder).expect("encode");- let mut output = alloc_allocation::<B, bf16>(context, suffix_length * num_q_heads * head_dim);- encoder.encode_copy(&pooled, .., &mut output, ..);- let completed = encoder.end_encoding().submit().wait_until_completed().expect("submit");+ let mut command_buffer = context.create_command_buffer(None, None).expect("command buffer");+ let pooled = kernel.encode(arguments, &mut command_buffer).expect("encode");+ let mut output = create_buffer::<B, bf16>(context, suffix_length * num_q_heads * head_dim);+ command_buffer.encode_copy(&pooled, &mut output);+ let completed = command_buffer.end_encoding().submit().wait_until_completed().expect("submit");drop(pooled);drop(completed);- allocation_to_vec::<B, bf16>(&output)+ buffer_to_vec::<B, bf16>(&output)}#[uzu_test]diff --git a/crates/uzu-engine/unit/backends/metal/kernel/gdn/chunked_test.rs b/crates/uzu-engine/unit/backends/metal/kernel/gdn/chunked_test.rsindex 32f7bff87..5be2ab32d 100644--- a/crates/uzu-engine/unit/backends/metal/kernel/gdn/chunked_test.rs+++ b/crates/uzu-engine/unit/backends/metal/kernel/gdn/chunked_test.rs@@ -7,12 +7,12 @@ use crate::{array::ArrayElement,backends::{common::{- Context, Kernels,+ Backend, BufferMut, CommandBufferEncoding, CommandBufferExecutable, CommandBufferPending, Context, Kernels,kernel::{DeltaNetNormGateKernel, DeltaNetPrefillKernel, DeltaNetPrefillPrepKernel},},metal::Metal,},- tests::helpers::{alloc_allocation, alloc_allocation_with_data, allocation_to_vec},+ tests::helpers::{buffer_to_vec, create_buffer, create_buffer_with_data},};type BackendKernels<B> = <B as Backend>::Kernels;@@ -63,19 +63,20 @@ fn run_prefill<T: ArrayElement>(mode: PrefillMode,) -> (Vec<f32>, Vec<f32>) {let in_proj_data: Vec<T> = case.in_proj.iter().copied().map(|value| cast(value).unwrap()).collect();- let in_proj = alloc_allocation_with_data::<Metal, T>(context, &in_proj_data);- let a_log = alloc_allocation_with_data::<Metal, f32>(context, &case.a_log);- let dt_bias = alloc_allocation_with_data::<Metal, f32>(context, &case.dt_bias);- let norm_weight = alloc_allocation_with_data::<Metal, f32>(context, &case.norm_weight);+ let mut command_buffer = context.create_command_buffer(None, None).expect("command buffer");+ let mut in_proj = command_buffer.allocate_scratch(size_of_val(in_proj_data.as_slice())).unwrap();+ in_proj.copyin(&in_proj_data);+ let a_log = create_buffer_with_data::<Metal, f32>(context, &case.a_log);+ let dt_bias = create_buffer_with_data::<Metal, f32>(context, &case.dt_bias);+ let norm_weight = create_buffer_with_data::<Metal, f32>(context, &case.norm_weight);let state_len = NUM_V_HEADS * HEAD_V_DIM * HEAD_K_DIM;- let mut state = alloc_allocation::<Metal, f32>(context, state_len);- let mut out = alloc_allocation::<Metal, T>(context, case.suffix_len * case.value_dim);- let mut q = alloc_allocation::<Metal, f32>(context, case.suffix_len * case.key_dim);- let mut k = alloc_allocation::<Metal, f32>(context, case.suffix_len * case.key_dim);- let mut beta = alloc_allocation::<Metal, f32>(context, case.suffix_len * NUM_V_HEADS);- let mut decay = alloc_allocation::<Metal, f32>(context, case.suffix_len * NUM_V_HEADS);- let mut encoder = Encoder::new(context).expect("encoder");- encoder.encode_fill(&mut state, 0);+ let mut state = create_buffer::<Metal, f32>(context, state_len);+ let mut out = command_buffer.allocate_scratch(case.suffix_len * case.value_dim * size_of::<T>()).unwrap();+ let mut q = create_buffer::<Metal, f32>(context, case.suffix_len * case.key_dim);+ let mut k = create_buffer::<Metal, f32>(context, case.suffix_len * case.key_dim);+ let mut beta = create_buffer::<Metal, f32>(context, case.suffix_len * NUM_V_HEADS);+ let mut decay = create_buffer::<Metal, f32>(context, case.suffix_len * NUM_V_HEADS);+ command_buffer.encode_fill(&mut state, 0);match mode {PrefillMode::Recurrent => {@@ -94,7 +95,7 @@ fn run_prefill<T: ArrayElement>(&dt_bias,&mut q,&mut k,- None::<&mut crate::backends::common::Allocation<Metal>>,+ None::<&mut <Metal as Backend>::GlobalBuffer>,&mut beta,&mut decay,NUM_V_HEADS as u32,@@ -102,7 +103,7 @@ fn run_prefill<T: ArrayElement>(case.key_dim as u32,case.value_dim as u32,case.suffix_len as u32,- &mut encoder,+ &mut command_buffer,);<BackendKernels<Metal> as Kernels>::DeltaNetPrefillKernel::new(context, T::data_type(), HEAD_K_DIM as u32).expect("prefill")@@ -121,7 +122,7 @@ fn run_prefill<T: ArrayElement>(case.value_dim as u32,case.suffix_len as u32,HEAD_V_DIM.div_ceil(16) as u32,- &mut encoder,+ &mut command_buffer,);},PrefillMode::Chunked => {@@ -142,7 +143,7 @@ fn run_prefill<T: ArrayElement>(value_dim: case.value_dim as u32,suffix_len: case.suffix_len as u32,},- &mut encoder,+ &mut command_buffer,).expect("chunked encode");},@@ -159,14 +160,11 @@ fn run_prefill<T: ArrayElement>(case.total_proj_dim as u32,1e-6,case.suffix_len as u32,- &mut encoder,+ &mut command_buffer,);- encoder.end_encoding().submit().wait_until_completed().unwrap();+ command_buffer.end_encoding().submit().wait_until_completed().unwrap();- (- allocation_to_vec::<Metal, T>(&out).into_iter().map(|value| cast(value).unwrap()).collect(),- allocation_to_vec(&state),- )+ (buffer_to_vec::<Metal, T>(&out).into_iter().map(|value| cast(value).unwrap()).collect(), buffer_to_vec(&state))}#[uzu_test]diff --git a/crates/uzu-engine/unit/backends/metal/sparse/sparse_buffer_test.rs b/crates/uzu-engine/unit/backends/metal/sparse/sparse_buffer_test.rsindex f4e6feff0..43f0de8e3 100644--- a/crates/uzu-engine/unit/backends/metal/sparse/sparse_buffer_test.rs+++ b/crates/uzu-engine/unit/backends/metal/sparse/sparse_buffer_test.rs@@ -1,4 +1,4 @@-use std::ops::Range;+use std::range::Range;use uzu_engine_macros::uzu_test;@@ -25,7 +25,7 @@ fn pages_for_heaps(heap_count: usize,) -> Range<usize> {let pages_per_heap = ctx.sparse_heap_pool().heap_capacity_pages();- (heap_offset * pages_per_heap)..((heap_offset + heap_count) * pages_per_heap)+ ((heap_offset * pages_per_heap)..((heap_offset + heap_count) * pages_per_heap)).into()}#[uzu_test]@@ -35,7 +35,7 @@ fn test_mapping_succeeds() {let pages = pages_for_heaps(ctx.as_ref(), 0, 4);let mut sparse_buffer = sparse_buffer_create::<Metal>(&ctx, capacity);- sparse_buffer.map(ctx.as_ref(), &pages).expect("Failed to map sparse buffer");+ sparse_buffer.map(ctx.as_ref(), pages).expect("Failed to map sparse buffer");}#[uzu_test]@@ -45,8 +45,8 @@ fn test_unmapping_succeeds() {let pages = pages_for_heaps(ctx.as_ref(), 0, 4);let mut sparse_buffer = sparse_buffer_create::<Metal>(&ctx, capacity);- sparse_buffer.map(ctx.as_ref(), &pages).expect("Failed to map sparse buffer");- sparse_buffer.unmap(ctx.as_ref(), &pages).expect("Failed to unmap sparse buffer");+ sparse_buffer.map(ctx.as_ref(), pages).expect("Failed to map sparse buffer");+ sparse_buffer.unmap(ctx.as_ref(), pages).expect("Failed to unmap sparse buffer");}#[uzu_test]@@ -57,8 +57,8 @@ fn test_partial_unmapping_succeeds() {let unmapped = pages_for_heaps(ctx.as_ref(), 1, 2);let mut sparse_buffer = sparse_buffer_create::<Metal>(&ctx, capacity);- sparse_buffer.map(ctx.as_ref(), &mapped).expect("Failed to map sparse buffer");- sparse_buffer.unmap(ctx.as_ref(), &unmapped).expect("Failed to unmap sparse buffer");+ sparse_buffer.map(ctx.as_ref(), mapped).expect("Failed to map sparse buffer");+ sparse_buffer.unmap(ctx.as_ref(), unmapped).expect("Failed to unmap sparse buffer");}#[uzu_test]@@ -69,10 +69,10 @@ fn test_mapping_uses_minimum_heaps() {let pages = pages_for_heaps(ctx.as_ref(), 0, heap_count);let mut sparse_buffer = sparse_buffer_create::<Metal>(&ctx, capacity);- sparse_buffer.map(ctx.as_ref(), &pages).expect("Failed to map sparse buffer");+ sparse_buffer.map(ctx.as_ref(), pages).expect("Failed to map sparse buffer");let heaps = ctx.sparse_heap_pool();- let expected = pages.len().div_ceil(heaps.heap_capacity_pages());+ let expected = pages.iter().len().div_ceil(heaps.heap_capacity_pages());assert_eq!(heaps.heaps_count(), expected, "mapping should allocate the minimum number of heaps");}@@ -85,11 +85,11 @@ fn test_remapping_reuses_freed_pages() {let extra_pages = pages_for_heaps(ctx.as_ref(), 4, 1);let mut sparse_buffer = sparse_buffer_create::<Metal>(&ctx, capacity);- sparse_buffer.map(ctx.as_ref(), &initial_pages).expect("Failed to map sparse buffer");+ sparse_buffer.map(ctx.as_ref(), initial_pages).expect("Failed to map sparse buffer");let initial_heaps = ctx.sparse_heap_pool().heaps_count();- sparse_buffer.unmap(ctx.as_ref(), &unmapped_pages).expect("Failed to unmap sparse buffer");- sparse_buffer.map(ctx.as_ref(), &extra_pages).expect("Failed to remap sparse buffer");+ sparse_buffer.unmap(ctx.as_ref(), unmapped_pages).expect("Failed to unmap sparse buffer");+ sparse_buffer.map(ctx.as_ref(), extra_pages).expect("Failed to remap sparse buffer");assert_eq!(ctx.sparse_heap_pool().heaps_count(),@@ -105,11 +105,11 @@ fn test_full_unmap_then_remap_reuses_heaps() {let pages = pages_for_heaps(ctx.as_ref(), 0, 4);let mut sparse_buffer = sparse_buffer_create::<Metal>(&ctx, capacity);- sparse_buffer.map(ctx.as_ref(), &pages).expect("Failed to map sparse buffer");+ sparse_buffer.map(ctx.as_ref(), pages).expect("Failed to map sparse buffer");let initial_heaps = ctx.sparse_heap_pool().heaps_count();- sparse_buffer.unmap(ctx.as_ref(), &pages).expect("Failed to unmap sparse buffer");- sparse_buffer.map(ctx.as_ref(), &pages).expect("Failed to remap sparse buffer");+ sparse_buffer.unmap(ctx.as_ref(), pages).expect("Failed to unmap sparse buffer");+ sparse_buffer.map(ctx.as_ref(), pages).expect("Failed to remap sparse buffer");assert_eq!(ctx.sparse_heap_pool().heaps_count(),@@ -125,10 +125,10 @@ fn test_remapping_same_pages_is_noop() {let pages = pages_for_heaps(ctx.as_ref(), 0, 4);let mut sparse_buffer = sparse_buffer_create::<Metal>(&ctx, capacity);- sparse_buffer.map(ctx.as_ref(), &pages).expect("Failed to map sparse buffer");+ sparse_buffer.map(ctx.as_ref(), pages).expect("Failed to map sparse buffer");let initial_heaps = ctx.sparse_heap_pool().heaps_count();- sparse_buffer.map(ctx.as_ref(), &pages).expect("Failed to remap sparse buffer");+ sparse_buffer.map(ctx.as_ref(), pages).expect("Failed to remap sparse buffer");assert_eq!(ctx.sparse_heap_pool().heaps_count(),@@ -144,8 +144,8 @@ fn test_mapping_multiple_gaps_reserves_pages_between_gaps() {let capacity = buffer_capacity(ctx.as_ref(), 2);let mut sparse_buffer = sparse_buffer_create::<Metal>(&ctx, capacity);- sparse_buffer.map(ctx.as_ref(), &(1..2)).expect("Failed to map initial page");- sparse_buffer.map(ctx.as_ref(), &(0..pages_per_heap + 1)).expect("Failed to map range with multiple gaps");+ sparse_buffer.map(ctx.as_ref(), 1..2).expect("Failed to map initial page");+ sparse_buffer.map(ctx.as_ref(), 0..pages_per_heap + 1).expect("Failed to map range with multiple gaps");assert_eq!(ctx.sparse_heap_pool().heaps_count(),@@ -164,7 +164,7 @@ fn test_drop_releases_pool_heaps() {{let mut sparse_buffer = sparse_buffer_create::<Metal>(&ctx, capacity);- sparse_buffer.map(ctx.as_ref(), &pages).expect("Failed to map sparse buffer");+ sparse_buffer.map(ctx.as_ref(), pages).expect("Failed to map sparse buffer");assert!(ctx.sparse_heap_pool().heaps_count() > 0);}@@ -184,12 +184,12 @@ fn test_drop_does_not_disturb_other_buffer_mappings() {let pages = pages_for_heaps(ctx.as_ref(), 0, 1);let mut keeper = sparse_buffer_create::<Metal>(&ctx, capacity);- keeper.map(ctx.as_ref(), &pages).expect("Failed to map keeper buffer");+ keeper.map(ctx.as_ref(), pages).expect("Failed to map keeper buffer");let baseline = ctx.sparse_heap_pool().heaps_count();{let mut transient = sparse_buffer_create::<Metal>(&ctx, capacity);- transient.map(ctx.as_ref(), &pages).expect("Failed to map transient buffer");+ transient.map(ctx.as_ref(), pages).expect("Failed to map transient buffer");}let current_heaps = ctx.sparse_heap_pool().heaps_count();@@ -204,11 +204,11 @@ fn test_sequential_mappings_are_compact() {let second = pages_for_heaps(ctx.as_ref(), 2, 2);let mut sparse_buffer = sparse_buffer_create::<Metal>(&ctx, capacity);- sparse_buffer.map(ctx.as_ref(), &first).expect("Failed to map first range");- sparse_buffer.map(ctx.as_ref(), &second).expect("Failed to map second range");+ sparse_buffer.map(ctx.as_ref(), first).expect("Failed to map first range");+ sparse_buffer.map(ctx.as_ref(), second).expect("Failed to map second range");let heaps = ctx.sparse_heap_pool();- let total_pages = first.len() + second.len();+ let total_pages = first.iter().len() + second.iter().len();let expected = total_pages.div_ceil(heaps.heap_capacity_pages());assert_eq!(heaps.heaps_count(),diff --git a/crates/uzu-engine/unit/backends/metal/sparse/sparse_heap_pool_test.rs b/crates/uzu-engine/unit/backends/metal/sparse/sparse_heap_pool_test.rsindex 648581ae3..9ddf8d350 100644--- a/crates/uzu-engine/unit/backends/metal/sparse/sparse_heap_pool_test.rs+++ b/crates/uzu-engine/unit/backends/metal/sparse/sparse_heap_pool_test.rs@@ -1,3 +1,5 @@+use std::range::Range;+use uzu_engine_macros::uzu_test;use crate::{@@ -20,7 +22,7 @@ fn test_map_empty_range_allocates_no_heaps() {let cap = ctx.sparse_heap_pool().heap_capacity_bytes();let mut sparse_buffer = sparse_buffer_create::<Metal>(ctx.as_ref(), cap);- sparse_buffer.map(&ctx, &(0..0)).expect("map empty range");+ sparse_buffer.map(&ctx, 0..0).expect("map empty range");assert_eq!(ctx.sparse_heap_pool().heaps_count(), 0);}@@ -32,7 +34,7 @@ fn test_map_single_heap_allocates_one_heap() {let cap = ctx.sparse_heap_pool().heap_capacity_bytes();let mut sparse_buffer = sparse_buffer_create::<Metal>(ctx.as_ref(), cap);- sparse_buffer.map(&ctx, &(0..pages_per_heap)).expect("map");+ sparse_buffer.map(&ctx, 0..pages_per_heap).expect("map");assert_eq!(ctx.sparse_heap_pool().heaps_count(), 1);}@@ -44,7 +46,7 @@ fn test_map_multi_heap_allocates_minimum_heaps() {let cap = 4 * ctx.sparse_heap_pool().heap_capacity_bytes();let mut sparse_buffer = sparse_buffer_create::<Metal>(ctx.as_ref(), cap);- sparse_buffer.map(&ctx, &(0..4 * pages_per_heap)).expect("map");+ sparse_buffer.map(&ctx, 0..4 * pages_per_heap).expect("map");assert_eq!(ctx.sparse_heap_pool().heaps_count(), 4);}@@ -56,7 +58,7 @@ fn test_map_partial_heap_rounds_up_heap_count() {let cap = 2 * ctx.sparse_heap_pool().heap_capacity_bytes();let mut sparse_buffer = sparse_buffer_create::<Metal>(ctx.as_ref(), cap);- sparse_buffer.map(&ctx, &(0..pages_per_heap + 1)).expect("map");+ sparse_buffer.map(&ctx, 0..pages_per_heap + 1).expect("map");assert_eq!(ctx.sparse_heap_pool().heaps_count(), 2);}@@ -69,8 +71,8 @@ fn test_sequential_mappings_pack_into_one_heap() {let cap = ctx.sparse_heap_pool().heap_capacity_bytes();let mut sparse_buffer = sparse_buffer_create::<Metal>(ctx.as_ref(), cap);- sparse_buffer.map(&ctx, &(0..half)).expect("map first");- sparse_buffer.map(&ctx, &(half..pages_per_heap)).expect("map second");+ sparse_buffer.map(&ctx, 0..half).expect("map first");+ sparse_buffer.map(&ctx, half..pages_per_heap).expect("map second");assert_eq!(ctx.sparse_heap_pool().heaps_count(), 1);}@@ -83,8 +85,8 @@ fn test_map_overflows_existing_heap_into_new_heap() {let cap = 2 * ctx.sparse_heap_pool().heap_capacity_bytes();let mut sparse_buffer = sparse_buffer_create::<Metal>(ctx.as_ref(), cap);- sparse_buffer.map(&ctx, &(0..half)).expect("map first");- sparse_buffer.map(&ctx, &(half..half + pages_per_heap)).expect("map overflow");+ sparse_buffer.map(&ctx, 0..half).expect("map first");+ sparse_buffer.map(&ctx, half..half + pages_per_heap).expect("map overflow");assert_eq!(ctx.sparse_heap_pool().heaps_count(), 2);}@@ -98,8 +100,8 @@ fn test_two_buffers_share_one_heap() {let mut sparse_buffer_a = sparse_buffer_create::<Metal>(ctx.as_ref(), cap);let mut sparse_buffer_b = sparse_buffer_create::<Metal>(ctx.as_ref(), cap);- sparse_buffer_a.map(&ctx, &(0..half)).expect("map a");- sparse_buffer_b.map(&ctx, &(0..half)).expect("map b");+ sparse_buffer_a.map(&ctx, 0..half).expect("map a");+ sparse_buffer_b.map(&ctx, 0..half).expect("map b");assert_eq!(ctx.sparse_heap_pool().heaps_count(), 1);}@@ -110,10 +112,10 @@ fn test_full_unmap_removes_heaps() {let pages_per_heap = ctx.sparse_heap_pool().heap_capacity_pages();let cap = 2 * ctx.sparse_heap_pool().heap_capacity_bytes();let mut sparse_buffer = sparse_buffer_create::<Metal>(ctx.as_ref(), cap);- let pages = 0..2 * pages_per_heap;+ let pages = Range::from(0..2 * pages_per_heap);- sparse_buffer.map(&ctx, &pages).expect("map");- sparse_buffer.unmap(&ctx, &pages).expect("unmap");+ sparse_buffer.map(&ctx, pages).expect("map");+ sparse_buffer.unmap(&ctx, pages).expect("unmap");assert_eq!(ctx.sparse_heap_pool().heaps_count(), 0);}@@ -125,8 +127,8 @@ fn test_partial_unmap_keeps_heap() {let cap = ctx.sparse_heap_pool().heap_capacity_bytes();let mut sparse_buffer = sparse_buffer_create::<Metal>(ctx.as_ref(), cap);- sparse_buffer.map(&ctx, &(0..pages_per_heap)).expect("map");- sparse_buffer.unmap(&ctx, &(0..pages_per_heap / 2)).expect("partial unmap");+ sparse_buffer.map(&ctx, 0..pages_per_heap).expect("map");+ sparse_buffer.unmap(&ctx, 0..pages_per_heap / 2).expect("partial unmap");assert_eq!(ctx.sparse_heap_pool().heaps_count(), 1);}@@ -138,10 +140,10 @@ fn test_unmap_with_other_buffer_keeps_mappings() {let cap = ctx.sparse_heap_pool().heap_capacity_bytes();let mut sparse_buffer_a = sparse_buffer_create::<Metal>(ctx.as_ref(), cap);let mut sparse_buffer_b = sparse_buffer_create::<Metal>(ctx.as_ref(), cap);- let pages = 0..pages_per_heap;+ let pages = Range::from(0..pages_per_heap);- sparse_buffer_a.map(&ctx, &pages).expect("map a");- sparse_buffer_b.unmap(&ctx, &pages).expect("unmap b");+ sparse_buffer_a.map(&ctx, pages).expect("map a");+ sparse_buffer_b.unmap(&ctx, pages).expect("unmap b");assert_eq!(ctx.sparse_heap_pool().heaps_count(), 1);}@@ -155,9 +157,9 @@ fn test_unmap_one_buffer_keeps_heap_for_other() {let mut sparse_buffer_a = sparse_buffer_create::<Metal>(ctx.as_ref(), cap);let mut sparse_buffer_b = sparse_buffer_create::<Metal>(ctx.as_ref(), cap);- sparse_buffer_a.map(&ctx, &(0..half)).expect("map a");- sparse_buffer_b.map(&ctx, &(0..half)).expect("map b");- sparse_buffer_a.unmap(&ctx, &(0..half)).expect("unmap a");+ sparse_buffer_a.map(&ctx, 0..half).expect("map a");+ sparse_buffer_b.map(&ctx, 0..half).expect("map b");+ sparse_buffer_a.unmap(&ctx, 0..half).expect("unmap a");assert_eq!(ctx.sparse_heap_pool().heaps_count(), 1);}@@ -168,12 +170,12 @@ fn test_remap_after_unmap_does_not_grow_pool() {let pages_per_heap = ctx.sparse_heap_pool().heap_capacity_pages();let cap = 2 * ctx.sparse_heap_pool().heap_capacity_bytes();let mut sparse_buffer = sparse_buffer_create::<Metal>(ctx.as_ref(), cap);- let pages = 0..2 * pages_per_heap;+ let pages = Range::from(0..2 * pages_per_heap);- sparse_buffer.map(&ctx, &pages).expect("map");+ sparse_buffer.map(&ctx, pages).expect("map");let initial = ctx.sparse_heap_pool().heaps_count();- sparse_buffer.unmap(&ctx, &pages).expect("unmap");- sparse_buffer.map(&ctx, &pages).expect("remap");+ sparse_buffer.unmap(&ctx, pages).expect("unmap");+ sparse_buffer.map(&ctx, pages).expect("remap");assert_eq!(ctx.sparse_heap_pool().heaps_count(), initial);}@@ -186,9 +188,9 @@ fn test_remap_into_freed_gap_reuses_heap() {let cap = ctx.sparse_heap_pool().heap_capacity_bytes();let mut sparse_buffer = sparse_buffer_create::<Metal>(ctx.as_ref(), cap);- sparse_buffer.map(&ctx, &(0..pages_per_heap)).expect("map full");- sparse_buffer.unmap(&ctx, &(0..half)).expect("unmap half");- sparse_buffer.map(&ctx, &(0..half)).expect("remap into gap");+ sparse_buffer.map(&ctx, 0..pages_per_heap).expect("map full");+ sparse_buffer.unmap(&ctx, 0..half).expect("unmap half");+ sparse_buffer.map(&ctx, 0..half).expect("remap into gap");assert_eq!(ctx.sparse_heap_pool().heaps_count(), 1);}@@ -204,9 +206,9 @@ fn test_sequential_partial_unmaps_release_full_heap() {let cap = ctx.sparse_heap_pool().heap_capacity_bytes();let mut sparse_buffer = sparse_buffer_create::<Metal>(ctx.as_ref(), cap);- sparse_buffer.map(&ctx, &(0..pages_per_heap)).expect("map");- sparse_buffer.unmap(&ctx, &(0..half)).expect("unmap prefix");- sparse_buffer.unmap(&ctx, &(half..pages_per_heap)).expect("unmap suffix");+ sparse_buffer.map(&ctx, 0..pages_per_heap).expect("map");+ sparse_buffer.unmap(&ctx, 0..half).expect("unmap prefix");+ sparse_buffer.unmap(&ctx, half..pages_per_heap).expect("unmap suffix");assert_eq!(ctx.sparse_heap_pool().heaps_count(), 0);}@@ -221,9 +223,9 @@ fn test_three_buffers_share_one_heap() {let mut sparse_buffer_b = sparse_buffer_create::<Metal>(ctx.as_ref(), cap);let mut sparse_buffer_c = sparse_buffer_create::<Metal>(ctx.as_ref(), cap);- sparse_buffer_a.map(&ctx, &(0..third)).expect("map a");- sparse_buffer_b.map(&ctx, &(0..third)).expect("map b");- sparse_buffer_c.map(&ctx, &(0..third)).expect("map c");+ sparse_buffer_a.map(&ctx, 0..third).expect("map a");+ sparse_buffer_b.map(&ctx, 0..third).expect("map b");+ sparse_buffer_c.map(&ctx, 0..third).expect("map c");assert_eq!(ctx.sparse_heap_pool().heaps_count(), 1);}@@ -237,8 +239,8 @@ fn test_two_buffers_exactly_fill_one_heap() {let mut sparse_buffer_a = sparse_buffer_create::<Metal>(ctx.as_ref(), cap);let mut sparse_buffer_b = sparse_buffer_create::<Metal>(ctx.as_ref(), cap);- sparse_buffer_a.map(&ctx, &(0..half)).expect("map a");- sparse_buffer_b.map(&ctx, &(0..pages_per_heap - half)).expect("map b fills heap");+ sparse_buffer_a.map(&ctx, 0..half).expect("map a");+ sparse_buffer_b.map(&ctx, 0..pages_per_heap - half).expect("map b fills heap");assert_eq!(ctx.sparse_heap_pool().heaps_count(), 1);}@@ -253,9 +255,9 @@ fn test_third_buffer_spills_when_heap_filled_by_others() {let mut sparse_buffer_b = sparse_buffer_create::<Metal>(ctx.as_ref(), cap);let mut sparse_buffer_c = sparse_buffer_create::<Metal>(ctx.as_ref(), cap);- sparse_buffer_a.map(&ctx, &(0..half)).expect("map a");- sparse_buffer_b.map(&ctx, &(0..pages_per_heap - half)).expect("map b fills heap");- sparse_buffer_c.map(&ctx, &(0..1)).expect("map c spills");+ sparse_buffer_a.map(&ctx, 0..half).expect("map a");+ sparse_buffer_b.map(&ctx, 0..pages_per_heap - half).expect("map b fills heap");+ sparse_buffer_c.map(&ctx, 0..1).expect("map c spills");assert_eq!(ctx.sparse_heap_pool().heaps_count(), 2);}@@ -270,10 +272,10 @@ fn test_unmap_buffer_frees_pages_for_another_in_same_heap() {let mut sparse_buffer_b = sparse_buffer_create::<Metal>(ctx.as_ref(), cap);let mut sparse_buffer_c = sparse_buffer_create::<Metal>(ctx.as_ref(), cap);- sparse_buffer_a.map(&ctx, &(0..half)).expect("map a");- sparse_buffer_b.map(&ctx, &(0..pages_per_heap - half)).expect("map b fills heap");- sparse_buffer_a.unmap(&ctx, &(0..half)).expect("unmap a");- sparse_buffer_c.map(&ctx, &(0..half)).expect("map c into gap");+ sparse_buffer_a.map(&ctx, 0..half).expect("map a");+ sparse_buffer_b.map(&ctx, 0..pages_per_heap - half).expect("map b fills heap");+ sparse_buffer_a.unmap(&ctx, 0..half).expect("unmap a");+ sparse_buffer_c.map(&ctx, 0..half).expect("map c into gap");assert_eq!(ctx.sparse_heap_pool().heaps_count(), 1);}@@ -288,10 +290,10 @@ fn test_unmap_middle_of_three_buffers_keeps_heap() {let mut sparse_buffer_b = sparse_buffer_create::<Metal>(ctx.as_ref(), cap);let mut sparse_buffer_c = sparse_buffer_create::<Metal>(ctx.as_ref(), cap);- sparse_buffer_a.map(&ctx, &(0..third)).expect("map a");- sparse_buffer_b.map(&ctx, &(0..third)).expect("map b");- sparse_buffer_c.map(&ctx, &(0..third)).expect("map c");- sparse_buffer_b.unmap(&ctx, &(0..third)).expect("unmap b");+ sparse_buffer_a.map(&ctx, 0..third).expect("map a");+ sparse_buffer_b.map(&ctx, 0..third).expect("map b");+ sparse_buffer_c.map(&ctx, 0..third).expect("map c");+ sparse_buffer_b.unmap(&ctx, 0..third).expect("unmap b");assert_eq!(ctx.sparse_heap_pool().heaps_count(), 1);}@@ -306,12 +308,12 @@ fn test_unmap_all_shared_buffers_releases_heap() {let mut sparse_buffer_b = sparse_buffer_create::<Metal>(ctx.as_ref(), cap);let mut sparse_buffer_c = sparse_buffer_create::<Metal>(ctx.as_ref(), cap);- sparse_buffer_a.map(&ctx, &(0..third)).expect("map a");- sparse_buffer_b.map(&ctx, &(0..third)).expect("map b");- sparse_buffer_c.map(&ctx, &(0..third)).expect("map c");- sparse_buffer_a.unmap(&ctx, &(0..third)).expect("unmap a");- sparse_buffer_b.unmap(&ctx, &(0..third)).expect("unmap b");- sparse_buffer_c.unmap(&ctx, &(0..third)).expect("unmap c");+ sparse_buffer_a.map(&ctx, 0..third).expect("map a");+ sparse_buffer_b.map(&ctx, 0..third).expect("map b");+ sparse_buffer_c.map(&ctx, 0..third).expect("map c");+ sparse_buffer_a.unmap(&ctx, 0..third).expect("unmap a");+ sparse_buffer_b.unmap(&ctx, 0..third).expect("unmap b");+ sparse_buffer_c.unmap(&ctx, 0..third).expect("unmap c");assert_eq!(ctx.sparse_heap_pool().heaps_count(), 0);}@@ -325,8 +327,8 @@ fn test_second_buffer_spans_existing_and_new_heap() {let mut sparse_buffer_a = sparse_buffer_create::<Metal>(ctx.as_ref(), cap);let mut sparse_buffer_b = sparse_buffer_create::<Metal>(ctx.as_ref(), cap);- sparse_buffer_a.map(&ctx, &(0..half)).expect("map a");- sparse_buffer_b.map(&ctx, &(0..pages_per_heap)).expect("map b spans heaps");+ sparse_buffer_a.map(&ctx, 0..half).expect("map a");+ sparse_buffer_b.map(&ctx, 0..pages_per_heap).expect("map b spans heaps");assert_eq!(ctx.sparse_heap_pool().heaps_count(), 2);}@@ -340,9 +342,9 @@ fn test_unmap_spanning_buffer_keeps_heap_with_other_buffer() {let mut sparse_buffer_a = sparse_buffer_create::<Metal>(ctx.as_ref(), cap);let mut sparse_buffer_b = sparse_buffer_create::<Metal>(ctx.as_ref(), cap);- sparse_buffer_a.map(&ctx, &(0..half)).expect("map a");- sparse_buffer_b.map(&ctx, &(0..pages_per_heap)).expect("map b spans heaps");- sparse_buffer_b.unmap(&ctx, &(0..pages_per_heap)).expect("unmap b");+ sparse_buffer_a.map(&ctx, 0..half).expect("map a");+ sparse_buffer_b.map(&ctx, 0..pages_per_heap).expect("map b spans heaps");+ sparse_buffer_b.unmap(&ctx, 0..pages_per_heap).expect("unmap b");assert_eq!(ctx.sparse_heap_pool().heaps_count(), 1);}@@ -356,13 +358,13 @@ fn test_remap_two_buffers_after_unmap_does_not_grow_pool() {let mut sparse_buffer_a = sparse_buffer_create::<Metal>(ctx.as_ref(), cap);let mut sparse_buffer_b = sparse_buffer_create::<Metal>(ctx.as_ref(), cap);- sparse_buffer_a.map(&ctx, &(0..half)).expect("map a");- sparse_buffer_b.map(&ctx, &(0..half)).expect("map b");+ sparse_buffer_a.map(&ctx, 0..half).expect("map a");+ sparse_buffer_b.map(&ctx, 0..half).expect("map b");let initial = ctx.sparse_heap_pool().heaps_count();- sparse_buffer_a.unmap(&ctx, &(0..half)).expect("unmap a");- sparse_buffer_b.unmap(&ctx, &(0..half)).expect("unmap b");- sparse_buffer_a.map(&ctx, &(0..half)).expect("remap a");- sparse_buffer_b.map(&ctx, &(0..half)).expect("remap b");+ sparse_buffer_a.unmap(&ctx, 0..half).expect("unmap a");+ sparse_buffer_b.unmap(&ctx, 0..half).expect("unmap b");+ sparse_buffer_a.map(&ctx, 0..half).expect("remap a");+ sparse_buffer_b.map(&ctx, 0..half).expect("remap b");assert_eq!(ctx.sparse_heap_pool().heaps_count(), initial);}diff --git a/crates/uzu-engine/unit/common/helpers.rs b/crates/uzu-engine/unit/common/helpers.rsindex 206784c62..dc3d98a92 100644--- a/crates/uzu-engine/unit/common/helpers.rs+++ b/crates/uzu-engine/unit/common/helpers.rs@@ -2,7 +2,10 @@ use std::{mem::size_of, sync::Arc};use crate::{array::ArrayElement,- backends::common::{Allocation, AllocationType, Backend, Context, Encoder, SparseBuffer, SparseBufferExt},+ backends::common::{+ Backend, Buffer, BufferCpuAccessible, BufferMut, BufferRef, CommandBufferEncoding, CommandBufferExecutable,+ CommandBufferPending, Context, SparseBuffer,+ },};/// Invokes `$body` once per available backend, with `$B` bound to each backend type.@@ -38,39 +41,37 @@ macro_rules! for_each_non_cpu_backend {}pub(crate) use for_each_non_cpu_backend;-pub fn allocation_size_bytes<T>(elements_count: usize) -> usize {+pub fn buffer_size_bytes<T>(elements_count: usize) -> usize {elements_count * size_of::<T>()}-pub fn alloc_allocation<B: Backend, T>(+pub fn create_buffer<B: Backend, T>(context: &B::Context,elements_count: usize,-) -> Allocation<B> {- context- .create_allocation(allocation_size_bytes::<T>(elements_count), AllocationType::Global)- .expect("Failed to create allocation")+) -> B::GlobalBuffer {+ context.create_buffer(buffer_size_bytes::<T>(elements_count)).expect("Failed to create buffer")}-pub fn alloc_allocation_with_data<B: Backend, T: ArrayElement>(+pub fn create_buffer_with_data<B: Backend, T: ArrayElement>(context: &B::Context,data: &[T],-) -> Allocation<B> {- let mut allocation = context- .create_allocation(allocation_size_bytes::<T>(data.len()), AllocationType::Global)- .expect("Failed to create allocation");- allocation.copyin(data);- allocation+) -> B::GlobalBuffer {+ let mut buffer = context.create_buffer(buffer_size_bytes::<T>(data.len())).expect("Failed to create buffer");+ buffer.copyin(data);+ buffer}-pub fn allocation_to_vec<B: Backend, T: ArrayElement>(allocation: &Allocation<B>) -> Vec<T> {- allocation.copyout()+pub fn buffer_to_vec<B: Backend, T: ArrayElement>(+ buffer: impl BufferRef<Backend = B, Buffer: BufferCpuAccessible>+) -> Vec<T> {+ buffer.copyout()}-pub fn allocation_prefix_to_vec<B: Backend, T: ArrayElement>(- allocation: &Allocation<B>,+pub fn buffer_prefix_to_vec<B: Backend, T: ArrayElement>(+ buffer: impl BufferRef<Backend = B, Buffer: BufferCpuAccessible>,elements_count: usize,) -> Vec<T> {- let mut values = allocation_to_vec::<B, T>(allocation);+ let mut values = buffer_to_vec::<B, T>(buffer);values.truncate(elements_count);values}@@ -79,8 +80,8 @@ pub fn create_context<B: Backend>() -> Arc<<B as Backend>::Context> {B::Context::new().unwrap_or_else(|_| panic!("Failed to create context for {}", std::any::type_name::<B>()))}-pub fn submit_encoder<B: Backend>(encoder: Encoder<B>) {- encoder.end_encoding().submit().wait_until_completed().unwrap();+pub fn submit_command_buffer<E: CommandBufferEncoding>(command_buffer: E) {+ command_buffer.end_encoding().submit().wait_until_completed().unwrap();}pub fn sparse_buffer_create<B: Backend>(@@ -95,7 +96,7 @@ pub fn sparse_buffer_create_and_map<B: Backend>(capacity: usize,) -> B::SparseBuffer {let mut buffer = sparse_buffer_create::<B>(context, capacity);- buffer.map(context, &(0..buffer.total_pages())).expect("Failed to map sparse buffer");+ buffer.map(context, 0..buffer.total_pages()).expect("Failed to map sparse buffer");buffer}@@ -103,46 +104,43 @@ pub fn sparse_buffer_create_with<B: Backend, T: ArrayElement>(context: &B::Context,data: &[T],) -> B::SparseBuffer {- let capacity_bytes = allocation_size_bytes::<T>(data.len());+ let capacity_bytes = buffer_size_bytes::<T>(data.len());let mut buffer = sparse_buffer_create_and_map::<B>(context, capacity_bytes);sparse_buffer_write::<B, T>(context, &mut buffer, data);buffer}-pub fn sparse_buffer_read_allocation<B: Backend>(+pub fn buffer_readback<B: Backend>(context: &B::Context,- buffer: &B::SparseBuffer,- size: usize,-) -> Allocation<B> {- let mut allocation = alloc_allocation::<B, u8>(context, size);- let range = 0..size;+ buffer: impl BufferRef<Backend = B>,+) -> B::GlobalBuffer {+ let mut output_buffer = create_buffer::<B, u8>(context, buffer.size());- let mut encoder = Encoder::new(context).expect("Failed to create encoder");- encoder.encode_copy(buffer, range.clone(), &mut allocation, range.clone());- submit_encoder(encoder);+ let mut command_buffer = context.create_command_buffer(None, None).expect("Failed to create command buffer");+ command_buffer.encode_copy(buffer, &mut output_buffer);+ submit_command_buffer(command_buffer);- allocation+ output_buffer}pub fn sparse_buffer_read_vec<B: Backend, T: ArrayElement>(context: &B::Context,- buffer: &B::SparseBuffer,+ buffer: impl BufferRef<Backend = B>,elements_count: usize,) -> Vec<T> {- let allocation =- sparse_buffer_read_allocation::<B>(context, buffer, elements_count * T::data_type().size_in_bytes());- allocation_to_vec(&allocation)+ let dense_buffer =+ buffer_readback::<B>(context, buffer.subrange(..elements_count * T::data_type().size_in_bytes()));+ buffer_to_vec(&dense_buffer)}pub fn sparse_buffer_write<B: Backend, T: ArrayElement>(context: &B::Context,- buffer: &mut B::SparseBuffer,+ buffer: impl BufferMut<Backend = B>,data: &[T],) {- let data_allocation = alloc_allocation_with_data::<B, T>(context, data);- let data_range = 0..allocation_size_bytes::<T>(data.len());+ let data_buffer = create_buffer_with_data::<B, T>(context, data);- let mut encoder = Encoder::new(context).expect("Failed to create encoder");- encoder.encode_copy(&data_allocation, data_range.clone(), buffer, data_range.clone());- submit_encoder(encoder);+ let mut command_buffer = context.create_command_buffer(None, None).expect("Failed to create command buffer");+ command_buffer.encode_copy(&data_buffer, buffer.subrange_mut(..data_buffer.size()));+ submit_command_buffer(command_buffer);}diff --git a/crates/uzu-engine/unit/common/matmul/bench.rs b/crates/uzu-engine/unit/common/matmul/bench.rsindex 35f1b6a26..daca0ee2a 100644--- a/crates/uzu-engine/unit/common/matmul/bench.rs+++ b/crates/uzu-engine/unit/common/matmul/bench.rs@@ -8,7 +8,10 @@ use std::{use criterion::Bencher;use super::super::env_vars;-use crate::backends::common::{Backend, Context, Encoder};+use crate::backends::common::{+ Backend, CommandBuffer, CommandBufferCompleted, CommandBufferEncoding, CommandBufferExecutable,+ CommandBufferPending, Context,+};static CAPTURE_TAKEN: AtomicBool = AtomicBool::new(false);@@ -46,9 +49,9 @@ pub fn iter_encode_loop<B: Backend, F>(bencher: &mut Bencher,mut encode: F,) where- F: FnMut(&mut Encoder<B>),+ F: FnMut(&mut <B::CommandBuffer as CommandBuffer>::Encoding),{- iter_encode_loop_named(context, bencher, "unnamed_benchmark", |encoder| encode(encoder));+ iter_encode_loop_named::<B, _>(context, bencher, "unnamed_benchmark", |command_buffer| encode(command_buffer));}pub fn iter_encode_loop_named<B: Backend, F>(@@ -57,15 +60,15 @@ pub fn iter_encode_loop_named<B: Backend, F>(benchmark_path: &str,mut encode: F,) where- F: FnMut(&mut Encoder<B>),+ F: FnMut(&mut <B::CommandBuffer as CommandBuffer>::Encoding),{bencher.iter_custom(|n_iters| {let capture = start_benchmark_capture::<B>(context, benchmark_path);- let mut encoder = Encoder::<B>::new(context).unwrap();+ let mut command_buffer = context.create_command_buffer(None, None).unwrap();for _ in 0..n_iters {- encode(&mut encoder);+ encode(&mut command_buffer);}- let completed = encoder.end_encoding().submit().wait_until_completed().unwrap();+ let completed = command_buffer.end_encoding().submit().wait_until_completed().unwrap();if capture {context.stop_capture().expect("failed to stop benchmark GPU capture");}diff --git a/crates/uzu-engine/unit/common/matmul/harness.rs b/crates/uzu-engine/unit/common/matmul/harness.rsindex 8bcbef52a..84878e69f 100644--- a/crates/uzu-engine/unit/common/matmul/harness.rs+++ b/crates/uzu-engine/unit/common/matmul/harness.rs@@ -7,7 +7,7 @@ use crate::{array::ArrayElement,backends::{common::{- AllocationType, Backend, Context, Encoder,+ Backend, CommandBuffer, CommandBufferEncoding, CommandBufferExecutable, CommandBufferPending, Context,kernel::{Kernels,matmul::{MatmulA, MatmulArguments, MatmulB, MatmulDOps, MatmulKernel},@@ -15,7 +15,7 @@ use crate::{},cpu::Cpu,},- tests::helpers::{alloc_allocation_with_data, allocation_to_vec},+ tests::helpers::{buffer_to_vec, create_buffer_with_data},};#[cfg(backend = "metal")]@@ -128,58 +128,59 @@ fn run<B: Backend, T: ArrayElement + Float>(context: &B::Context,kernel: &mut <B::Kernels as Kernels>::MatmulKernel,input: &Input<T>,- encode: impl for<'a> FnOnce(&mut <B::Kernels as Kernels>::MatmulKernel, MatmulArguments<'a, 'a, 'a, B>, &mut Encoder<B>),+ encode: impl for<'a> FnOnce(+ &mut <B::Kernels as Kernels>::MatmulKernel,+ MatmulArguments<'a, B, &'a B::GlobalBuffer, &'a B::GlobalBuffer, &'a mut B::GlobalBuffer, &'a B::GlobalBuffer>,+ &mut <B::CommandBuffer as CommandBuffer>::Encoding,+ ),) -> Vec<T> {let Shape {m,k,n,} = input.case.shape;- let b_allocation = alloc_allocation_with_data::<B, T>(context, &input.b);- let a_allocation = alloc_allocation_with_data::<B, T>(context, &input.a);- let mut d_allocation = if let Some(ref prefill) = input.d_prefill {- alloc_allocation_with_data::<B, T>(context, prefill)+ let b_buffer = create_buffer_with_data::<B, T>(context, &input.b);+ let a_buffer = create_buffer_with_data::<B, T>(context, &input.a);+ let mut d_buffer = if let Some(ref prefill) = input.d_prefill {+ create_buffer_with_data::<B, T>(context, prefill)} else {- context- .create_allocation(m as usize * n as usize * std::mem::size_of::<T>(), AllocationType::Global)- .expect("create d allocation")+ context.create_buffer(m as usize * n as usize * std::mem::size_of::<T>()).expect("create d buffer")};- let rht_allocation =- input.rht_factors.as_ref().map(|factors| alloc_allocation_with_data::<B, i32>(context, factors));- let bias_allocation = input.bias.as_ref().map(|bias| alloc_allocation_with_data::<B, T>(context, bias));+ let rht_buffer = input.rht_factors.as_ref().map(|factors| create_buffer_with_data::<B, i32>(context, factors));+ let bias_buffer = input.bias.as_ref().map(|bias| create_buffer_with_data::<B, T>(context, bias));let d_transform = MatmulDOps::<'_, B> {ab_scale: input.case.ab_scale,accumulate: input.case.accumulate,- bias: bias_allocation.as_ref(),- rht_factors: rht_allocation.as_ref(),+ bias: bias_buffer.as_ref(),+ rht_factors: rht_buffer.as_ref(),soft_cap: None,};- let mut encoder = Encoder::new(context).expect("encoder");+ let mut command_buffer = context.create_command_buffer(None, None).expect("command buffer");encode(kernel,MatmulArguments {a: MatmulA::FullPrecision {- values: &a_allocation,+ values: &a_buffer,offset: 0,},b: MatmulB::FullPrecision {- b: &b_allocation,+ b: &b_buffer,},b_leading_dimension: None,b_transpose: input.case.b_transpose,- d: &mut d_allocation,+ d: &mut d_buffer,d_transform,gather_indices: None,m,n,k,},- &mut encoder,+ &mut command_buffer,);- encoder.end_encoding().submit().wait_until_completed().unwrap();- allocation_to_vec::<B, T>(&d_allocation)+ command_buffer.end_encoding().submit().wait_until_completed().unwrap();+ buffer_to_vec::<B, T>(&d_buffer)}pub fn cpu_reference<T: ArrayElement + Float>(input: &Input<T>) -> Vec<T> {@@ -191,8 +192,8 @@ pub fn cpu_reference<T: ArrayElement + Float>(input: &Input<T>) -> Vec<T> {T::data_type(),).expect("CPU MatmulKernel");- run::<Cpu, T>(&context, &mut kernel, input, |kernel, args, encoder| {- kernel.encode(args, encoder).expect("encode failed");+ run::<Cpu, T>(&context, &mut kernel, input, |kernel, args, command_buffer| {+ kernel.encode(args, command_buffer).expect("encode failed");})}@@ -203,11 +204,11 @@ pub fn run_metal<T: ArrayElement + Float>(input: &Input<T>,dispatch: TestDispatch,) -> Vec<T> {- run::<Metal, T>(context, kernel, input, |kernel, args, encoder| {+ run::<Metal, T>(context, kernel, input, |kernel, args, command_buffer| {if let Some(engine) = dispatch {- kernel.encode_with_gemm_engine(args, engine, encoder).expect("forced GEMM engine encode failed");+ kernel.encode_with_gemm_engine(args, engine, command_buffer).expect("forced GEMM engine encode failed");} else {- kernel.encode(args, encoder).expect("matmul encode failed");+ kernel.encode(args, command_buffer).expect("matmul encode failed");}})}diff --git a/crates/uzu-engine/unit/common/matmul/quant.rs b/crates/uzu-engine/unit/common/matmul/quant.rsindex 987a2dcfa..482677f87 100644--- a/crates/uzu-engine/unit/common/matmul/quant.rs+++ b/crates/uzu-engine/unit/common/matmul/quant.rs@@ -11,7 +11,8 @@ use crate::{array::ArrayElement,backends::{common::{- Allocation, Backend, Context, Encoder,+ Backend, BufferMut, BufferRef, CommandBufferEncoding, CommandBufferExecutable, CommandBufferPending,+ Context,gpu_types::{QuantizationMethod, QuantizationMode},kernel::{ActivationQuantization, ActivationTransform, Kernels,@@ -24,7 +25,7 @@ use crate::{cpu::Cpu,},data_type::DataType,- tests::helpers::{alloc_allocation, alloc_allocation_with_data, allocation_to_vec},+ tests::helpers::{buffer_to_vec, create_buffer, create_buffer_with_data},};#[derive(Clone)]@@ -231,13 +232,13 @@ impl<T: ArrayElement + Float> QuantInput<T> {assert!(columns.is_multiple_of(group_size));}let context = <Cpu as Backend>::Context::new().expect("CPU context");- let input = alloc_allocation_with_data::<Cpu, T>(&context, &self.x);- let factors = alloc_allocation_with_data::<Cpu, i32>(&context, &vec![1; columns as usize]);+ let input = create_buffer_with_data::<Cpu, T>(&context, &self.x);+ let factors = create_buffer_with_data::<Cpu, i32>(&context, &vec![1; columns as usize]);let element_count = rows * columns;- let mut values = alloc_allocation::<Cpu, i8>(&context, element_count as usize);- let mut scales = alloc_allocation::<Cpu, f32>(&context, (element_count / activation_scale_group_size) as usize);- let mut group_sums = sum_group_size- .map(|group_size| alloc_allocation::<Cpu, i32>(&context, (element_count / group_size) as usize));+ let mut values = create_buffer::<Cpu, i8>(&context, element_count as usize);+ let mut scales = create_buffer::<Cpu, f32>(&context, (element_count / activation_scale_group_size) as usize);+ let mut group_sums =+ sum_group_size.map(|group_size| create_buffer::<Cpu, i32>(&context, (element_count / group_size) as usize));let quantization = ActivationQuantization::new(activation_scale_group_size,sum_group_size.unwrap_or(activation_scale_group_size),@@ -247,7 +248,7 @@ impl<T: ArrayElement + Float> QuantInput<T> {.expect("supported activation quantization");let transform = ActivationTransform::<Cpu>::quantize(&context, T::data_type(), quantization).expect("CPU activation quantization transform");- let mut encoder = Encoder::<Cpu>::new(&context).expect("CPU encoder");+ let mut command_buffer = context.create_command_buffer(None, None).expect("CPU command buffer");transform.encode_quantize(&input,&mut values,@@ -256,14 +257,14 @@ impl<T: ArrayElement + Float> QuantInput<T> {&factors,rows,columns,- &mut encoder,+ &mut command_buffer,);- encoder.end_encoding().submit().wait_until_completed().expect("CPU activation quantization");+ command_buffer.end_encoding().submit().wait_until_completed().expect("CPU activation quantization");self.prepared_a = Some(PreparedInt8A {- values: allocation_to_vec(&values),- scales: allocation_to_vec(&scales),- group_sums: group_sums.map_or_else(Vec::new, |sums| allocation_to_vec(&sums)),+ values: buffer_to_vec(&values),+ scales: buffer_to_vec(&scales),+ group_sums: group_sums.map_or_else(Vec::new, |sums| buffer_to_vec(&sums)),quantization,});self@@ -288,15 +289,15 @@ impl<T: ArrayElement + Float> QuantInput<T> {}pub struct QuantBuffers<B: Backend, T: ArrayElement + Float> {- pub w: Allocation<B>,- pub scales: Allocation<B>,- pub zp: Option<Allocation<B>>,- pub bias: Option<Allocation<B>>,- pub x: Allocation<B>,- pub prepared_a: Option<Allocation<B>>,- pub prepared_a_scales: Option<Allocation<B>>,- pub prepared_a_group_sums: Option<Allocation<B>>,- pub y: Allocation<B>,+ pub w: B::GlobalBuffer,+ pub scales: B::GlobalBuffer,+ pub zp: Option<B::GlobalBuffer>,+ pub bias: Option<B::GlobalBuffer>,+ pub x: B::GlobalBuffer,+ pub prepared_a: Option<B::GlobalBuffer>,+ pub prepared_a_scales: Option<B::GlobalBuffer>,+ pub prepared_a_group_sums: Option<B::GlobalBuffer>,+ pub y: B::GlobalBuffer,_t: std::marker::PhantomData<T>,}@@ -311,31 +312,31 @@ impl<B: Backend, T: ArrayElement + Float> QuantBuffers<B, T> {let metadata_elements = params.scale_shape().into_iter().product::<u32>() as usize;let zero_point_bytes = params.zero_point_shape(input.mode).into_iter().product::<u32>() as usize;let mut buffers = Self {- w: alloc_allocation_with_data::<B, u32>(context, &input.weights_for_upload()),- scales: alloc_allocation_with_data::<B, T>(context, &pad(&input.scales, metadata_elements)),+ w: create_buffer_with_data::<B, u32>(context, &input.weights_for_upload()),+ scales: create_buffer_with_data::<B, T>(context, &pad(&input.scales, metadata_elements)),zp: input.zero_points.as_ref()- .map(|zero_points| alloc_allocation_with_data::<B, u8>(context, &pad(zero_points, zero_point_bytes))),+ .map(|zero_points| create_buffer_with_data::<B, u8>(context, &pad(zero_points, zero_point_bytes))),bias: input.biases.as_ref()- .map(|biases| alloc_allocation_with_data::<B, T>(context, &pad(biases, metadata_elements))),- x: alloc_allocation_with_data::<B, T>(context, &input.x),+ .map(|biases| create_buffer_with_data::<B, T>(context, &pad(biases, metadata_elements))),+ x: create_buffer_with_data::<B, T>(context, &input.x),prepared_a: input.prepared_a.as_ref()- .map(|prepared| alloc_allocation_with_data::<B, i8>(context, &prepared.values)),+ .map(|prepared| create_buffer_with_data::<B, i8>(context, &prepared.values)),prepared_a_scales: input.prepared_a.as_ref()- .map(|prepared| alloc_allocation_with_data::<B, f32>(context, &prepared.scales)),+ .map(|prepared| create_buffer_with_data::<B, f32>(context, &prepared.scales)),prepared_a_group_sums: input.prepared_a.as_ref().filter(|prepared| !prepared.group_sums.is_empty())- .map(|prepared| alloc_allocation_with_data::<B, i32>(context, &prepared.group_sums)),- y: alloc_allocation::<B, T>(context, (input.m as usize) * (input.n as usize)),+ .map(|prepared| create_buffer_with_data::<B, i32>(context, &prepared.group_sums)),+ y: create_buffer::<B, T>(context, (input.m as usize) * (input.n as usize)),_t: std::marker::PhantomData,};if params_layout == QuantParamsLayout::GroupOutput {@@ -347,7 +348,7 @@ impl<B: Backend, T: ArrayElement + Float> QuantBuffers<B, T> {pub fn matmul_b<'a>(&'a self,input: &QuantInput<T>,- ) -> MatmulB<'a, B> {+ ) -> MatmulB<&'a B::GlobalBuffer> {quant_b_variant(&self.w, &self.scales, self.zp.as_ref(), self.bias.as_ref(), input.params_layout, input)}@@ -382,14 +383,14 @@ impl<B: Backend, T: ArrayElement + Float> QuantBuffers<B, T> {}}-fn quant_b_variant<'a, B: Backend, T: ArrayElement + Float>(- w: &'a Allocation<B>,- scales: &'a Allocation<B>,- zero_points: Option<&'a Allocation<B>>,- biases: Option<&'a Allocation<B>>,+fn quant_b_variant<TB: BufferRef, T: ArrayElement + Float>(+ w: TB,+ scales: TB,+ zero_points: Option<TB>,+ biases: Option<TB>,params_layout: QuantParamsLayout,input: &QuantInput<T>,-) -> MatmulB<'a, B> {+) -> MatmulB<TB> {let params = QuantParams::new(params_layout, input.n, input.k.div_ceil(input.group_size));let correction = match input.quant_method {QuantizationMethod::ScaleBias => QuantizedCorrection::Biases(biases.expect("bias buffer")),@@ -410,7 +411,7 @@ fn quant_b_variant<'a, B: Backend, T: ArrayElement + Float>(pub fn quant_arguments<'a, B: Backend, T: ArrayElement + Float>(buffers: &'a mut QuantBuffers<B, T>,input: &QuantInput<T>,-) -> MatmulArguments<'a, 'a, 'a, B> {+) -> MatmulArguments<'a, B, &'a B::GlobalBuffer, &'a B::GlobalBuffer, &'a mut B::GlobalBuffer, &'a B::GlobalBuffer> {let QuantBuffers {w,scales,@@ -435,7 +436,7 @@ pub fn quant_arguments<'a, B: Backend, T: ArrayElement + Float>(code_layout: prepared.quantization.code_layout(),},None => MatmulA::FullPrecision {- values: x,+ values: &*x,offset: 0,},};@@ -463,10 +464,10 @@ pub fn run_quant_cpu<T: ArrayElement + Float>(input: &QuantInput<T>) -> Vec<T> {T::data_type(),).expect("MatmulCpuKernel");- let mut encoder = Encoder::<Cpu>::new(&context).expect("encoder");- matmul.encode(quant_arguments(&mut buffers, input), &mut encoder).expect("encode cpu quant");- encoder.end_encoding().submit().wait_until_completed().unwrap();- allocation_to_vec::<Cpu, T>(&buffers.y)+ let mut command_buffer = context.create_command_buffer(None, None).unwrap();+ matmul.encode(quant_arguments(&mut buffers, input), &mut command_buffer).expect("encode cpu quant");+ command_buffer.end_encoding().submit().wait_until_completed().unwrap();+ buffer_to_vec::<Cpu, T>(&buffers.y)}#[cfg(backend = "metal")]@@ -483,13 +484,13 @@ pub fn run_quant_metal<T: ArrayElement + Float>(T::data_type(),).expect("MatmulMetalKernel");- let mut encoder = Encoder::<Metal>::new(context).expect("encoder");+ let mut command_buffer = context.create_command_buffer(None, None).expect("command buffer");let args = quant_arguments(&mut buffers, input);if let Some(engine) = dispatch {- matmul.encode_with_gemm_engine(args, engine, &mut encoder).expect("forced GEMM engine encode failed");+ matmul.encode_with_gemm_engine(args, engine, &mut command_buffer).expect("forced GEMM engine encode failed");} else {- matmul.encode(args, &mut encoder).expect("matmul encode failed");+ matmul.encode(args, &mut command_buffer).expect("matmul encode failed");}- encoder.end_encoding().submit().wait_until_completed().unwrap();- allocation_to_vec::<Metal, T>(&buffers.y)+ command_buffer.end_encoding().submit().wait_until_completed().unwrap();+ buffer_to_vec::<Metal, T>(&buffers.y)}diff --git a/crates/uzu-engine/unit/encodable_block/attention/qkv_norm_test.rs b/crates/uzu-engine/unit/encodable_block/attention/qkv_norm_test.rsindex fb554efe6..15a85cc3b 100644--- a/crates/uzu-engine/unit/encodable_block/attention/qkv_norm_test.rs+++ b/crates/uzu-engine/unit/encodable_block/attention/qkv_norm_test.rs@@ -2,12 +2,12 @@ use uzu_engine_macros::uzu_test;use super::QKVNorm;use crate::{- backends::common::{Backend, Encoder},+ backends::common::{Backend, CommandBufferEncoding, CommandBufferExecutable, CommandBufferPending, Context},config::normalization::{NormalizationConfig, UpcastMode},data_type::DataType,tests::{assert::assert_eq_float,- helpers::{alloc_allocation_with_data, allocation_to_vec, create_context, for_each_backend},+ helpers::{buffer_to_vec, create_buffer_with_data, create_context, for_each_backend},},};@@ -55,12 +55,12 @@ fn run_key_value_row_stride_test<B: Backend>() {}}- let mut key_value = alloc_allocation_with_data::<B, f32>(&context, &input);- let mut encoder = Encoder::new(context.as_ref()).expect("failed to create encoder");- norm.encode_key_value(&mut key_value, BATCH_SIZE, &mut encoder).expect("failed to encode key/value norm");- encoder.end_encoding().submit().wait_until_completed().expect("failed to execute key/value norm");+ let mut key_value = create_buffer_with_data::<B, f32>(&context, &input);+ let mut command_buffer = context.create_command_buffer(None, None).expect("failed to create command buffer");+ norm.encode_key_value(&mut key_value, BATCH_SIZE, &mut command_buffer).expect("failed to encode key/value norm");+ command_buffer.end_encoding().submit().wait_until_completed().expect("failed to execute key/value norm");- let output = allocation_to_vec::<B, f32>(&key_value);+ let output = buffer_to_vec::<B, f32>(&key_value);assert_eq_float(&expected, &output, 1e-5, "key/value norm row stride mismatch");}diff --git a/crates/uzu-engine/unit/encodable_block/delta_net_tree_verify_bench.rs b/crates/uzu-engine/unit/encodable_block/delta_net_tree_verify_bench.rsindex cd479a9c2..d9febdbd2 100644--- a/crates/uzu-engine/unit/encodable_block/delta_net_tree_verify_bench.rs+++ b/crates/uzu-engine/unit/encodable_block/delta_net_tree_verify_bench.rs@@ -8,12 +8,15 @@ use uzu_engine_macros::uzu_bench;use crate::{backends::{- common::{Backend, Context, Kernels, kernel::delta_net_tree_verify::DeltaNetTreeVerify},+ common::{+ Backend, BufferMut, CommandBufferEncoding, Context, Kernels,+ kernel::delta_net_tree_verify::DeltaNetTreeVerify,+ },metal::Metal,},data_type::DataType,encodable_block::mixer::delta_net::tree_verify::{TreeVerifyEncodeArguments, TreeVerifyNewArguments},- tests::{helpers::alloc_allocation_with_data, matmul::iter_encode_loop_named},+ tests::{helpers::create_buffer_with_data, matmul::iter_encode_loop_named},};#[uzu_bench]@@ -33,32 +36,27 @@ fn bench_delta_net_tree_verify(c: &mut Criterion) {let tree_verify =<<Metal as Backend>::Kernels as Kernels>::DeltaNetTreeVerify::new(context.as_ref(), &arguments).unwrap();eprintln!("GDN tree verification PSO construction: {:.2} ms", started.elapsed().as_secs_f64() * 1e3);- let h0 = alloc_allocation_with_data::<Metal, f32>(&context, &vec![0.001; V_HEADS * HEAD_DIM * HEAD_DIM]);+ let h0 = create_buffer_with_data::<Metal, f32>(&context, &vec![0.001; V_HEADS * HEAD_DIM * HEAD_DIM]);let mut group = c.benchmark_group("Metal/Kernel/GDNTreeVerify");group.sample_size(20).warm_up_time(Duration::from_millis(300)).measurement_time(Duration::from_secs(1));for tree_size in [32usize, 49, 64, 128] {- let q = alloc_allocation_with_data::<Metal, bf16>(- &context,- &vec![bf16::from_f32(0.01); tree_size * K_HEADS * HEAD_DIM],- );- let k = alloc_allocation_with_data::<Metal, bf16>(- &context,- &vec![bf16::from_f32(0.02); tree_size * K_HEADS * HEAD_DIM],- );- let v = alloc_allocation_with_data::<Metal, bf16>(- &context,- &vec![bf16::from_f32(0.03); tree_size * V_HEADS * HEAD_DIM],- );- let trie = alloc_allocation_with_data::<Metal, u32>(- &context,- &(0..tree_size as u32).flat_map(|node| [node, tree_size as u32 - 1, node]).collect::<Vec<_>>(),- );- let log_decay = alloc_allocation_with_data::<Metal, f32>(&context, &vec![-0.01; tree_size * V_HEADS]);- let beta = alloc_allocation_with_data::<Metal, f32>(&context, &vec![0.2; tree_size * V_HEADS]);+ let mut command_buffer = context.create_command_buffer(None, None).unwrap();+ let mut q = command_buffer.allocate_scratch(tree_size * K_HEADS * HEAD_DIM * size_of::<bf16>()).unwrap();+ q.copyin(&vec![bf16::from_f32(0.01); tree_size * K_HEADS * HEAD_DIM]);+ let mut k = command_buffer.allocate_scratch(tree_size * K_HEADS * HEAD_DIM * size_of::<bf16>()).unwrap();+ k.copyin(&vec![bf16::from_f32(0.02); tree_size * K_HEADS * HEAD_DIM]);+ let mut v = command_buffer.allocate_scratch(tree_size * V_HEADS * HEAD_DIM * size_of::<bf16>()).unwrap();+ v.copyin(&vec![bf16::from_f32(0.03); tree_size * V_HEADS * HEAD_DIM]);+ let trie_nodes = (0..tree_size as u32).flat_map(|node| [node, tree_size as u32 - 1, node]).collect::<Vec<_>>();+ let mut log_decay = command_buffer.allocate_scratch(tree_size * V_HEADS * size_of::<f32>()).unwrap();+ log_decay.copyin(&vec![-0.01f32; tree_size * V_HEADS]);+ let mut beta = command_buffer.allocate_scratch(tree_size * V_HEADS * size_of::<f32>()).unwrap();+ beta.copyin(&vec![0.2f32; tree_size * V_HEADS]);let benchmark_path = format!("Metal/Kernel/GDNTreeVerify/T{tree_size}");group.bench_function(format!("T{tree_size}"), |bencher| {- iter_encode_loop_named(context.as_ref(), bencher, &benchmark_path, |encoder| {+ iter_encode_loop_named::<Metal, _>(context.as_ref(), bencher, &benchmark_path, |command_buffer| {+ let trie = command_buffer.allocate_constant_from_slice(&trie_nodes).unwrap();tree_verify.encode(TreeVerifyEncodeArguments {@@ -71,7 +69,7 @@ fn bench_delta_net_tree_verify(c: &mut Criterion) {h0: &h0,tree_size: tree_size as u32,},- encoder,+ command_buffer,).unwrap();})diff --git a/crates/uzu-engine/unit/encodable_block/mamba_mixer/ssd_prefill_test.rs b/crates/uzu-engine/unit/encodable_block/mamba_mixer/ssd_prefill_test.rsindex 754430e4f..e4347cfc8 100644--- a/crates/uzu-engine/unit/encodable_block/mamba_mixer/ssd_prefill_test.rs+++ b/crates/uzu-engine/unit/encodable_block/mamba_mixer/ssd_prefill_test.rs@@ -2,12 +2,12 @@ use uzu_engine_macros::uzu_test;use crate::{backends::common::{- Backend, Context, Encoder, Kernels,+ Backend, CommandBufferEncoding, CommandBufferExecutable, CommandBufferPending, Context, Kernels,gpu_types::ActivationType,kernel::{Conv1dScanKernel, SSDPrefill64Kernel, SSDPrefillKernel},},data_type::DataType,- tests::helpers::{alloc_allocation, alloc_allocation_with_data, allocation_to_vec, for_each_non_cpu_backend},+ tests::helpers::{buffer_to_vec, create_buffer, create_buffer_with_data, for_each_non_cpu_backend},};#[derive(Debug, Clone, Copy)]@@ -146,21 +146,21 @@ fn run_prefill_kernel_mode<B: Backend>(fixture: &SSDPrefillFixture,mode: SSDPrefillMode,) -> (Vec<f32>, Vec<f32>) {- let x_buf = alloc_allocation_with_data::<B, _>(ctx, &fixture.x_data);- let dt_buf = alloc_allocation_with_data::<B, _>(ctx, &fixture.dt_data);- let b_buf = alloc_allocation_with_data::<B, _>(ctx, &fixture.b_data);- let c_buf = alloc_allocation_with_data::<B, _>(ctx, &fixture.c_data);- let d_buf = alloc_allocation_with_data::<B, _>(ctx, &fixture.d_data);- let z_buf = alloc_allocation_with_data::<B, _>(ctx, &fixture.z_data);- let mut state_buf = alloc_allocation_with_data::<B, _>(ctx, &fixture.state_init);- let mut y_buf = alloc_allocation::<B, f32>(ctx, fixture.suffix_len * fixture.num_heads * fixture.head_dim);+ let x_buf = create_buffer_with_data::<B, _>(ctx, &fixture.x_data);+ let dt_buf = create_buffer_with_data::<B, _>(ctx, &fixture.dt_data);+ let b_buf = create_buffer_with_data::<B, _>(ctx, &fixture.b_data);+ let c_buf = create_buffer_with_data::<B, _>(ctx, &fixture.c_data);+ let d_buf = create_buffer_with_data::<B, _>(ctx, &fixture.d_data);+ let z_buf = create_buffer_with_data::<B, _>(ctx, &fixture.z_data);+ let mut state_buf = create_buffer_with_data::<B, _>(ctx, &fixture.state_init);+ let mut y_buf = create_buffer::<B, f32>(ctx, fixture.suffix_len * fixture.num_heads * fixture.head_dim);let x_strides = fixture.x_strides.map(|stride| stride as u32);let dt_strides = fixture.dt_strides.map(|stride| stride as u32);let cb_strides = fixture.cb_strides.map(|stride| stride as u32);let state_strides = fixture.state_strides.map(|stride| stride as u32);- let mut encoder = Encoder::new(ctx).unwrap();+ let mut command_buffer = ctx.create_command_buffer(None, None).unwrap();match mode {SSDPrefillMode::Universal => {let kernel = <<B as Backend>::Kernels as Kernels>::SSDPrefillKernel::new(ctx, DataType::F32)@@ -183,7 +183,7 @@ fn run_prefill_kernel_mode<B: Backend>(&state_strides,fixture.num_heads as u32,fixture.head_dim as u32,- &mut encoder,+ &mut command_buffer,);},SSDPrefillMode::Special64 => {@@ -208,14 +208,14 @@ fn run_prefill_kernel_mode<B: Backend>(&state_strides,fixture.num_heads as u32,fixture.head_dim as u32,- &mut encoder,+ &mut command_buffer,);},}- let completed = encoder.end_encoding().submit().wait_until_completed().unwrap();+ let completed = command_buffer.end_encoding().submit().wait_until_completed().unwrap();- let y_vec = allocation_to_vec::<B, f32>(&y_buf);- let state_vec = allocation_to_vec::<B, f32>(&state_buf);+ let y_vec = buffer_to_vec::<B, f32>(&y_buf);+ let state_vec = buffer_to_vec::<B, f32>(&state_buf);drop(y_buf);drop(completed);(y_vec, state_vec)@@ -240,16 +240,16 @@ fn run_conv_scan_once<B: Backend>(let total_state = channels * tap_count;let mut y_buf = if alias_io {- alloc_allocation_with_data::<B, _>(ctx, x_data)+ create_buffer_with_data::<B, _>(ctx, x_data)} else {- alloc_allocation::<B, f32>(ctx, total_x)+ create_buffer::<B, f32>(ctx, total_x)};- let mut b_out_buf = alloc_allocation::<B, f32>(ctx, total_x);- let mut c_out_buf = alloc_allocation::<B, f32>(ctx, total_x);- let w_buf = alloc_allocation_with_data::<B, _>(ctx, w_data);- let b_buf = alloc_allocation_with_data::<B, _>(ctx, b_data);- let mut state_buf = alloc_allocation_with_data::<B, _>(ctx, state_init);- let mut scratch_buf = alloc_allocation::<B, f32>(ctx, total_state);+ let mut b_out_buf = create_buffer::<B, f32>(ctx, total_x);+ let mut c_out_buf = create_buffer::<B, f32>(ctx, total_x);+ let w_buf = create_buffer_with_data::<B, _>(ctx, w_data);+ let b_buf = create_buffer_with_data::<B, _>(ctx, b_data);+ let mut state_buf = create_buffer_with_data::<B, _>(ctx, state_init);+ let mut scratch_buf = create_buffer::<B, f32>(ctx, total_state);let padded_len = tap_count + suffix_len;let mut padded_host = vec![0.0f32; padded_len * channels];@@ -263,11 +263,11 @@ fn run_conv_scan_once<B: Backend>(padded_host[(tap_count + token) * channels + ch] = x_data[token * channels + ch];}}- let padded_buf = alloc_allocation_with_data::<B, _>(ctx, &padded_host);+ let padded_buf = create_buffer_with_data::<B, _>(ctx, &padded_host);- let mut encoder = Encoder::new(ctx).unwrap();+ let mut command_buffer = ctx.create_command_buffer(None, None).unwrap();if use_scratch && tap_count > 0 {- encoder.encode_fill(&mut scratch_buf, 0);+ command_buffer.encode_fill(&mut scratch_buf, 0);}kernel.encode(&padded_buf,@@ -285,18 +285,17 @@ fn run_conv_scan_once<B: Backend>(channels as u32,0u32,ActivationType::SILU,- &mut encoder,+ &mut command_buffer,);if use_scratch && tap_count > 0 {- let bytes = channels * tap_count * size_of::<f32>();- encoder.encode_copy(&scratch_buf, 0..bytes, &mut state_buf, 0..bytes);+ command_buffer.encode_copy(&scratch_buf, &mut state_buf);}- encoder.end_encoding().submit().wait_until_completed().unwrap();+ command_buffer.end_encoding().submit().wait_until_completed().unwrap();- let y_vec = allocation_to_vec::<B, f32>(&y_buf);- let state_vec = allocation_to_vec::<B, f32>(&state_buf);+ let y_vec = buffer_to_vec::<B, f32>(&y_buf);+ let state_vec = buffer_to_vec::<B, f32>(&state_buf);(y_vec, state_vec)}diff --git a/crates/uzu-engine/unit/encodable_block/moe/moe_block_e2e_test.rs b/crates/uzu-engine/unit/encodable_block/moe/moe_block_e2e_test.rsindex 8f540d37c..96137bf72 100644--- a/crates/uzu-engine/unit/encodable_block/moe/moe_block_e2e_test.rs+++ b/crates/uzu-engine/unit/encodable_block/moe/moe_block_e2e_test.rs@@ -5,7 +5,7 @@ use uzu_engine_macros::uzu_test;use super::{MoeExpertsTwoPassArguments, MoeExpertsTwoPassPrefillBlock, MoeGather};use crate::{backends::common::{- Allocation, Backend, Encoder, Kernels,+ Backend, CommandBufferEncoding, CommandBufferExecutable, CommandBufferPending, Context, Kernels,gpu_types::{ActivationType, activation_silu_alpha},kernel::{MoeBlockBasesFromPartialsKernel, MoeCountsOffsetsFusedKernel, MoeFinalizeKernel, MoeRouterTopKKernel,@@ -14,7 +14,7 @@ use crate::{},data_type::DataType,tests::helpers::{- alloc_allocation, alloc_allocation_with_data, allocation_prefix_to_vec, allocation_to_vec, create_context,+ buffer_prefix_to_vec, buffer_readback, buffer_to_vec, create_buffer, create_buffer_with_data, create_context,for_each_non_cpu_backend,},};@@ -286,34 +286,34 @@ fn run_moe_parity_test_internal<B: Backend>(let down_biases: Vec<bf16> = (0..e * d_model).map(|_| bf16::from_f32(rng.random_range(-0.1..0.1))).collect();// Create Metal buffers- let x_buf = alloc_allocation_with_data::<B, bf16>(ctx, &x);- let router_w_buf = alloc_allocation_with_data::<B, bf16>(ctx, &router_weight_bf16);- let router_b_buf = alloc_allocation_with_data::<B, bf16>(ctx, &router_bias_bf16);- let w13_buf = alloc_allocation_with_data::<B, bf16>(ctx, &w13_gpu);- let w2_buf = alloc_allocation_with_data::<B, bf16>(ctx, &w2_gpu);- let up_biases_buf = alloc_allocation_with_data::<B, bf16>(ctx, &up_biases);- let down_biases_buf = alloc_allocation_with_data::<B, bf16>(ctx, &down_biases);+ let x_buf = create_buffer_with_data::<B, bf16>(ctx, &x);+ let router_w_buf = create_buffer_with_data::<B, bf16>(ctx, &router_weight_bf16);+ let router_b_buf = create_buffer_with_data::<B, bf16>(ctx, &router_bias_bf16);+ let w13_buf = create_buffer_with_data::<B, bf16>(ctx, &w13_gpu);+ let w2_buf = create_buffer_with_data::<B, bf16>(ctx, &w2_gpu);+ let up_biases_buf = create_buffer_with_data::<B, bf16>(ctx, &up_biases);+ let down_biases_buf = create_buffer_with_data::<B, bf16>(ctx, &down_biases);// Allocate intermediate buffers (max capacity)let max_sumk = t * k;- let mut topk_ids_buf = alloc_allocation::<B, i32>(ctx, t * k);- let mut topk_probs_buf = alloc_allocation::<B, bf16>(ctx, t * k);- let mut offsets_buf = alloc_allocation::<B, u32>(ctx, e + 1);- let mut sumk_buf = alloc_allocation::<B, u32>(ctx, 1);+ let mut topk_ids_buf = create_buffer::<B, i32>(ctx, t * k);+ let mut topk_probs_buf = create_buffer::<B, bf16>(ctx, t * k);+ let mut offsets_buf = create_buffer::<B, u32>(ctx, e + 1);+ let mut sumk_buf = create_buffer::<B, u32>(ctx, 1);let num_blocks = t.div_ceil(256).max(1);let num_tiles = e.div_ceil(512).max(1);let entries = num_blocks * num_tiles * 512usize;- let mut partials_buf = alloc_allocation::<B, u32>(ctx, entries);- let mut block_bases_buf = alloc_allocation::<B, u32>(ctx, entries);- let mut block_alloc_buf = alloc_allocation::<B, u32>(ctx, entries);- let mut bucketed_ids_buf = alloc_allocation::<B, i32>(ctx, max_sumk);- let mut bucketed_probs_buf = alloc_allocation::<B, bf16>(ctx, max_sumk);- let mut tok2row_buf = alloc_allocation::<B, i32>(ctx, t * k);- let mut y_out_buf = alloc_allocation::<B, bf16>(ctx, t * d_model);+ let mut partials_buf = create_buffer::<B, u32>(ctx, entries);+ let mut block_bases_buf = create_buffer::<B, u32>(ctx, entries);+ let mut block_alloc_buf = create_buffer::<B, u32>(ctx, entries);+ let mut bucketed_ids_buf = create_buffer::<B, i32>(ctx, max_sumk);+ let mut bucketed_probs_buf = create_buffer::<B, bf16>(ctx, max_sumk);+ let mut tok2row_buf = create_buffer::<B, i32>(ctx, t * k);+ let mut y_out_buf = create_buffer::<B, bf16>(ctx, t * d_model);// Encode ALL kernels in one command buffereprintln!("[E2E] Encoding entire MoE pipeline in single command buffer...");- let mut encoder = Encoder::new(ctx).expect("Failed to create encoder");+ let mut command_buffer = ctx.create_command_buffer(None, None).expect("Failed to create command buffer");// Router + TopK (fused kernel)let router_topk =@@ -323,8 +323,8 @@ fn run_moe_parity_test_internal<B: Backend>(&x_buf,&router_w_buf,Some(&router_b_buf),- None::<&Allocation<B>>,- None::<&Allocation<B>>,+ None::<&B::GlobalBuffer>,+ None::<&B::GlobalBuffer>,&mut topk_ids_buf,&mut topk_probs_buf,t as u32,@@ -334,7 +334,7 @@ fn run_moe_parity_test_internal<B: Backend>(true,None::<f32>,None::<f32>,- &mut encoder,+ &mut command_buffer,);let fused_kernel = <B::Kernels as Kernels>::MoeCountsOffsetsFusedKernel::new(ctx).expect("fused kernel");@@ -346,7 +346,7 @@ fn run_moe_parity_test_internal<B: Backend>(t as u32,e as u32,k as u32,- &mut encoder,+ &mut command_buffer,);let scatter_bases_kernel =@@ -359,7 +359,7 @@ fn run_moe_parity_test_internal<B: Backend>(num_blocks as u32,num_tiles as u32,0u32,- &mut encoder,+ &mut command_buffer,);let scatter_map_kernel = <B::Kernels as Kernels>::MoeScatterBucketsMapKernel::new(ctx, DataType::BF16)@@ -378,12 +378,12 @@ fn run_moe_parity_test_internal<B: Backend>(num_blocks as u32,num_tiles as u32,&mut tok2row_buf,- &mut encoder,+ &mut command_buffer,);let gather = MoeGather::<B>::new(ctx, DataType::BF16).expect("gather");let x_perm_buf = gather- .encode(&x_buf, &bucketed_ids_buf, &sumk_buf, t as u32, k as u32, d_model as u32, &mut encoder)+ .encode(&x_buf, &bucketed_ids_buf, &sumk_buf, t as u32, k as u32, d_model as u32, &mut command_buffer).expect("gather");let total_rows = t * k;@@ -406,7 +406,7 @@ fn run_moe_parity_test_internal<B: Backend>(up_clip_max: up_clip.1,silu_alpha,};- let y_partial_buf = experts.encode(args, &mut encoder).expect("failed to encode MoE experts");+ let y_partial_buf = experts.encode(args, &mut command_buffer).expect("failed to encode MoE experts");let finalize = <B::Kernels as Kernels>::MoeFinalizeKernel::new(ctx, DataType::BF16).expect("finalize");finalize.encode(@@ -417,15 +417,15 @@ fn run_moe_parity_test_internal<B: Backend>(t as u32,d_model as u32,k as u32,- &mut encoder,+ &mut command_buffer,);eprintln!("[E2E] All kernels encoded. Committing ONCE and waiting...");- let completed = encoder.end_encoding().submit().wait_until_completed().unwrap();+ let completed = command_buffer.end_encoding().submit().wait_until_completed().unwrap();eprintln!("[E2E] GPU execution completed");// Read GPU output- let y_out_bf16 = allocation_prefix_to_vec::<B, bf16>(&y_out_buf, t * d_model);+ let y_out_bf16 = buffer_prefix_to_vec::<B, bf16>(&y_out_buf, t * d_model);let y_out_gpu: Vec<f32> = y_out_bf16.iter().map(|&v| f32::from(v)).collect();// Validate GPU output is finite@@ -449,12 +449,13 @@ fn run_moe_parity_test_internal<B: Backend>(f32::from(w2_cpu[0]));- let sumk_val = allocation_to_vec::<B, u32>(&sumk_buf)[0] as usize;+ let sumk_val = buffer_to_vec::<B, u32>(&sumk_buf)[0] as usize;eprintln!("[E2E] sumk={}", sumk_val);// For multi-token tests with large d_ff, verify gather output (x_perm)if t > 1 && d_ff >= 256 {- let x_perm_cpu = allocation_prefix_to_vec::<B, bf16>(&x_perm_buf, sumk_val * d_model);+ let x_perm_cpu =+ buffer_prefix_to_vec::<B, bf16>(&buffer_readback::<B>(ctx, &x_perm_buf), sumk_val * d_model);eprintln!("[E2E] x_perm diagnostics (sumk={}):", sumk_val);eprintln!("[E2E] Row 0 [0:8]: {:?}", x_perm_cpu[0..8].iter().map(|&v| f32::from(v)).collect::<Vec<_>>());if sumk_val > 1 {@@ -467,7 +468,7 @@ fn run_moe_parity_test_internal<B: Backend>(}// CRITICAL: Check tok2row mapping for multi-token tests- let tok2row_cpu = allocation_prefix_to_vec::<B, i32>(&tok2row_buf, t * k);+ let tok2row_cpu = buffer_prefix_to_vec::<B, i32>(&tok2row_buf, t * k);eprintln!("[E2E] tok2row[0..{}]: {:?}", t * k, tok2row_cpu);eprintln!("[E2E] Expected: token 0→row {}, token 1→row {}",@@ -480,7 +481,8 @@ fn run_moe_parity_test_internal<B: Backend>();// Check y_partial at specific indices where finalize reads for token 1- let y_partial_full = allocation_prefix_to_vec::<B, bf16>(&y_partial_buf, sumk_val * d_model);+ let y_partial_full =+ buffer_prefix_to_vec::<B, bf16>(&buffer_readback::<B>(ctx, &y_partial_buf), sumk_val * d_model);eprintln!("[E2E] y_partial spot check:");eprintln!("[E2E] y_partial[48] (row 0, col 48) = {:.6}", f32::from(y_partial_full[48]));if sumk_val > 1 {@@ -564,13 +566,13 @@ fn run_moe_parity_test_internal<B: Backend>(// Debug: print some sample values from intermediate bufferseprintln!("[E2E] === DEBUG: Intermediate values ===");- let topk_ids_gpu = allocation_prefix_to_vec::<B, i32>(&topk_ids_buf, t * k);- let topk_probs_gpu = allocation_prefix_to_vec::<B, bf16>(&topk_probs_buf, t * k);+ let topk_ids_gpu = buffer_prefix_to_vec::<B, i32>(&topk_ids_buf, t * k);+ let topk_probs_gpu = buffer_prefix_to_vec::<B, bf16>(&topk_probs_buf, t * k);eprintln!("[E2E] TopK IDs: {:?}", topk_ids_gpu);eprintln!("[E2E] TopK Probs: {:?}", topk_probs_gpu.iter().map(|&v| f32::from(v)).collect::<Vec<_>>());- let y_partial_gpu = allocation_prefix_to_vec::<B, bf16>(&y_partial_buf, max_sumk * d_model);- let sumk_actual = allocation_to_vec::<B, u32>(&sumk_buf)[0] as usize;+ let y_partial_gpu = buffer_prefix_to_vec::<B, bf16>(&buffer_readback::<B>(ctx, &y_partial_buf), max_sumk * d_model);+ let sumk_actual = buffer_to_vec::<B, u32>(&sumk_buf)[0] as usize;eprintln!("[E2E] sumk={}", sumk_actual);let sample_size = 16.min(sumk_actual * d_model);eprintln!(diff --git a/crates/uzu-engine/unit/encodable_block/moe/moe_experts_perf_test.rs b/crates/uzu-engine/unit/encodable_block/moe/moe_experts_perf_test.rsindex 79e04d660..d0b2acb22 100644--- a/crates/uzu-engine/unit/encodable_block/moe/moe_experts_perf_test.rs+++ b/crates/uzu-engine/unit/encodable_block/moe/moe_experts_perf_test.rs@@ -6,9 +6,9 @@ use uzu_engine_macros::uzu_test;use super::{MoeExpertsTwoPassArguments, MoeExpertsTwoPassDecodeBlock, MoeExpertsTwoPassPrefillBlock};use crate::{- backends::common::{Backend, Encoder},+ backends::common::{Backend, CommandBufferEncoding, CommandBufferExecutable, CommandBufferPending, Context},data_type::DataType,- tests::helpers::{alloc_allocation_with_data, create_context, for_each_non_cpu_backend},+ tests::helpers::{create_buffer_with_data, create_context, for_each_non_cpu_backend},};fn build_offsets(@@ -71,15 +71,15 @@ fn run_decode_case<B: Backend>(let experts_kernel = MoeExpertsTwoPassDecodeBlock::<B>::new(ctx, DataType::BF16, 2).expect("experts decode kernel");- let x_perm_buf = alloc_allocation_with_data::<B, bf16>(ctx, &x_perm);- let offsets_buf = alloc_allocation_with_data::<B, u32>(ctx, &offsets);- let w13_buf = alloc_allocation_with_data::<B, bf16>(ctx, &w13);- let w2_buf = alloc_allocation_with_data::<B, bf16>(ctx, &w2);- let up_biases_buf = alloc_allocation_with_data::<B, bf16>(ctx, &up_biases);- let down_biases_buf = alloc_allocation_with_data::<B, bf16>(ctx, &down_biases);+ let x_perm_buf = create_buffer_with_data::<B, bf16>(ctx, &x_perm);+ let offsets_buf = create_buffer_with_data::<B, u32>(ctx, &offsets);+ let w13_buf = create_buffer_with_data::<B, bf16>(ctx, &w13);+ let w2_buf = create_buffer_with_data::<B, bf16>(ctx, &w2);+ let up_biases_buf = create_buffer_with_data::<B, bf16>(ctx, &up_biases);+ let down_biases_buf = create_buffer_with_data::<B, bf16>(ctx, &down_biases);for _ in 0..warmup {- let mut encoder = Encoder::new(ctx).expect("Failed to create encoder");+ let mut command_buffer = ctx.create_command_buffer(None, None).expect("Failed to create command buffer");let output = experts_kernel.encode(MoeExpertsTwoPassArguments {@@ -99,10 +99,10 @@ fn run_decode_case<B: Backend>(up_clip_max: f32::INFINITY,silu_alpha: 1.702,},- &mut encoder,+ &mut command_buffer,).expect("failed to encode MoE experts");- let completed = encoder.end_encoding().submit().wait_until_completed().unwrap();+ let completed = command_buffer.end_encoding().submit().wait_until_completed().unwrap();drop(output);drop(completed);}@@ -110,7 +110,7 @@ fn run_decode_case<B: Backend>(let mut times = Vec::with_capacity(iters);for _ in 0..iters {let start = Instant::now();- let mut encoder = Encoder::new(ctx).expect("Failed to create encoder");+ let mut command_buffer = ctx.create_command_buffer(None, None).expect("Failed to create command buffer");let output = experts_kernel.encode(MoeExpertsTwoPassArguments {@@ -130,10 +130,10 @@ fn run_decode_case<B: Backend>(up_clip_max: f32::INFINITY,silu_alpha: 1.702,},- &mut encoder,+ &mut command_buffer,).expect("failed to encode MoE experts");- let completed = encoder.end_encoding().submit().wait_until_completed().unwrap();+ let completed = command_buffer.end_encoding().submit().wait_until_completed().unwrap();drop(output);drop(completed);times.push(start.elapsed().as_secs_f64() * 1000.0);@@ -192,15 +192,15 @@ fn run_two_pass_prefill_case<B: Backend>(let experts_kernel =MoeExpertsTwoPassPrefillBlock::<B>::new(ctx, DataType::BF16, 2).expect("experts prefill kernel");- let x_perm_buf = alloc_allocation_with_data::<B, bf16>(ctx, &x_perm);- let offsets_buf = alloc_allocation_with_data::<B, u32>(ctx, &offsets);- let w13_buf = alloc_allocation_with_data::<B, bf16>(ctx, &w13);- let w2_buf = alloc_allocation_with_data::<B, bf16>(ctx, &w2);- let up_biases_buf = alloc_allocation_with_data::<B, bf16>(ctx, &up_biases);- let down_biases_buf = alloc_allocation_with_data::<B, bf16>(ctx, &down_biases);+ let x_perm_buf = create_buffer_with_data::<B, bf16>(ctx, &x_perm);+ let offsets_buf = create_buffer_with_data::<B, u32>(ctx, &offsets);+ let w13_buf = create_buffer_with_data::<B, bf16>(ctx, &w13);+ let w2_buf = create_buffer_with_data::<B, bf16>(ctx, &w2);+ let up_biases_buf = create_buffer_with_data::<B, bf16>(ctx, &up_biases);+ let down_biases_buf = create_buffer_with_data::<B, bf16>(ctx, &down_biases);for _ in 0..warmup {- let mut encoder = Encoder::new(ctx).expect("Failed to create encoder");+ let mut command_buffer = ctx.create_command_buffer(None, None).expect("Failed to create command buffer");let args = MoeExpertsTwoPassArguments {x_perm: &x_perm_buf,expert_offsets: &offsets_buf,@@ -218,8 +218,8 @@ fn run_two_pass_prefill_case<B: Backend>(up_clip_max: f32::INFINITY,silu_alpha: 1.702,};- let output = experts_kernel.encode(args, &mut encoder).expect("failed to encode MoE experts");- let completed = encoder.end_encoding().submit().wait_until_completed().unwrap();+ let output = experts_kernel.encode(args, &mut command_buffer).expect("failed to encode MoE experts");+ let completed = command_buffer.end_encoding().submit().wait_until_completed().unwrap();drop(output);drop(completed);}@@ -227,7 +227,7 @@ fn run_two_pass_prefill_case<B: Backend>(let mut times = Vec::with_capacity(iters);for _ in 0..iters {let start = Instant::now();- let mut encoder = Encoder::new(ctx).expect("Failed to create encoder");+ let mut command_buffer = ctx.create_command_buffer(None, None).expect("Failed to create command buffer");let args = MoeExpertsTwoPassArguments {x_perm: &x_perm_buf,expert_offsets: &offsets_buf,@@ -245,8 +245,8 @@ fn run_two_pass_prefill_case<B: Backend>(up_clip_max: f32::INFINITY,silu_alpha: 1.702,};- let output = experts_kernel.encode(args, &mut encoder).expect("failed to encode MoE experts");- let completed = encoder.end_encoding().submit().wait_until_completed().unwrap();+ let output = experts_kernel.encode(args, &mut command_buffer).expect("failed to encode MoE experts");+ let completed = command_buffer.end_encoding().submit().wait_until_completed().unwrap();drop(output);drop(completed);times.push(start.elapsed().as_secs_f64() * 1000.0);diff --git a/crates/uzu-engine/unit/encodable_block/moe/moe_experts_test.rs b/crates/uzu-engine/unit/encodable_block/moe/moe_experts_test.rsindex 13af9e5d0..08e5c1f4e 100644--- a/crates/uzu-engine/unit/encodable_block/moe/moe_experts_test.rs+++ b/crates/uzu-engine/unit/encodable_block/moe/moe_experts_test.rs@@ -16,13 +16,15 @@ use super::{};use crate::{backends::common::{- Encoder,+ CommandBufferEncoding, CommandBufferExecutable, CommandBufferPending, Context,gpu_types::{ActivationType, activation_silu_alpha},},data_type::DataType,tests::{assert::assert_eq_float,- helpers::{alloc_allocation_with_data, allocation_prefix_to_vec, create_context, for_each_non_cpu_backend},+ helpers::{+ buffer_prefix_to_vec, buffer_readback, create_buffer_with_data, create_context, for_each_non_cpu_backend,+ },},};@@ -361,16 +363,16 @@ fn test_two_pass_decode_correctness() {);// Prepare GPU buffers- let x_perm_buf = alloc_allocation_with_data::<B, bf16>(&ctx, &x_perm);- let offsets_buf = alloc_allocation_with_data::<B, u32>(&ctx, &offsets);- let w13_buf = alloc_allocation_with_data::<B, bf16>(&ctx, &w13);- let w2_buf = alloc_allocation_with_data::<B, bf16>(&ctx, &w2);- let up_biases_buf = alloc_allocation_with_data::<B, bf16>(&ctx, &up_biases);- let down_biases_buf = alloc_allocation_with_data::<B, bf16>(&ctx, &down_biases);+ let x_perm_buf = create_buffer_with_data::<B, bf16>(&ctx, &x_perm);+ let offsets_buf = create_buffer_with_data::<B, u32>(&ctx, &offsets);+ let w13_buf = create_buffer_with_data::<B, bf16>(&ctx, &w13);+ let w2_buf = create_buffer_with_data::<B, bf16>(&ctx, &w2);+ let up_biases_buf = create_buffer_with_data::<B, bf16>(&ctx, &up_biases);+ let down_biases_buf = create_buffer_with_data::<B, bf16>(&ctx, &down_biases);let experts_kernel = MoeExpertsTwoPassDecodeBlock::<B>::new(&ctx, DataType::BF16, gating_code).expect("MoeExpertsTwoPassDecodeKernel::new");- let mut encoder = Encoder::new(ctx.as_ref()).expect("Failed to create encoder");+ let mut command_buffer = ctx.create_command_buffer(None, None).expect("Failed to create command buffer");let y_partial_buf = experts_kernel.encode(@@ -391,14 +393,15 @@ fn test_two_pass_decode_correctness() {up_clip_max: f32::INFINITY,silu_alpha,},- &mut encoder,+ &mut command_buffer,).expect("failed to encode MoE experts");- let completed = encoder.end_encoding().submit().wait_until_completed().unwrap();+ let completed = command_buffer.end_encoding().submit().wait_until_completed().unwrap();// Read GPU partial output and do CPU finalize (weighted sum)- let y_partial_gpu = allocation_prefix_to_vec::<B, bf16>(&y_partial_buf, sum_k * d_model);+ let y_partial_gpu =+ buffer_prefix_to_vec::<B, bf16>(&buffer_readback::<B>(&ctx, &y_partial_buf), sum_k * d_model);// Finalize: y[t] = Σ_k prob[t,k] * y_partial[t*k + k_idx]let mut y_gpu = vec![bf16::from_f32(0.0); t * d_model];@@ -485,15 +488,15 @@ fn test_two_pass_decode_multi_token() {);// GPU buffers- let x_perm_buf = alloc_allocation_with_data::<B, bf16>(&ctx, &scatter.x_perm);- let offsets_buf = alloc_allocation_with_data::<B, u32>(&ctx, &scatter.offsets);- let w13_buf = alloc_allocation_with_data::<B, bf16>(&ctx, &data.w13);- let w2_buf = alloc_allocation_with_data::<B, bf16>(&ctx, &data.w2);- let up_biases_buf = alloc_allocation_with_data::<B, bf16>(&ctx, &data.up_biases);- let down_biases_buf = alloc_allocation_with_data::<B, bf16>(&ctx, &data.down_biases);+ let x_perm_buf = create_buffer_with_data::<B, bf16>(&ctx, &scatter.x_perm);+ let offsets_buf = create_buffer_with_data::<B, u32>(&ctx, &scatter.offsets);+ let w13_buf = create_buffer_with_data::<B, bf16>(&ctx, &data.w13);+ let w2_buf = create_buffer_with_data::<B, bf16>(&ctx, &data.w2);+ let up_biases_buf = create_buffer_with_data::<B, bf16>(&ctx, &data.up_biases);+ let down_biases_buf = create_buffer_with_data::<B, bf16>(&ctx, &data.down_biases);let experts_kernel = MoeExpertsTwoPassDecodeBlock::<B>::new(&ctx, DataType::BF16, gating_code).expect("kernel");- let mut encoder = Encoder::new(ctx.as_ref()).expect("Failed to create encoder");+ let mut command_buffer = ctx.create_command_buffer(None, None).expect("Failed to create command buffer");let y_partial_buf = experts_kernel.encode(MoeExpertsTwoPassArguments {@@ -513,12 +516,13 @@ fn test_two_pass_decode_multi_token() {up_clip_max: f32::INFINITY,silu_alpha,},- &mut encoder,+ &mut command_buffer,).expect("failed to encode MoE experts");- let completed = encoder.end_encoding().submit().wait_until_completed().unwrap();+ let completed = command_buffer.end_encoding().submit().wait_until_completed().unwrap();- let y_partial_gpu = allocation_prefix_to_vec::<B, bf16>(&y_partial_buf, sum_k * d_model);+ let y_partial_gpu =+ buffer_prefix_to_vec::<B, bf16>(&buffer_readback::<B>(&ctx, &y_partial_buf), sum_k * d_model);let y_gpu = gather_and_finalize(&y_partial_gpu, &data.topk_probs, &scatter.perm_idx, t, k, d_model);assert_eq_float(&y_expected, &y_gpu, 0.02, "2-pass decode multi-token");@@ -569,16 +573,16 @@ fn test_two_pass_prefill_correctness() {);// GPU buffers- let x_perm_buf = alloc_allocation_with_data::<B, bf16>(&ctx, &scatter.x_perm);- let offsets_buf = alloc_allocation_with_data::<B, u32>(&ctx, &scatter.offsets);- let w13_buf = alloc_allocation_with_data::<B, bf16>(&ctx, &data.w13);- let w2_buf = alloc_allocation_with_data::<B, bf16>(&ctx, &data.w2);- let up_biases_buf = alloc_allocation_with_data::<B, bf16>(&ctx, &data.up_biases);- let down_biases_buf = alloc_allocation_with_data::<B, bf16>(&ctx, &data.down_biases);+ let x_perm_buf = create_buffer_with_data::<B, bf16>(&ctx, &scatter.x_perm);+ let offsets_buf = create_buffer_with_data::<B, u32>(&ctx, &scatter.offsets);+ let w13_buf = create_buffer_with_data::<B, bf16>(&ctx, &data.w13);+ let w2_buf = create_buffer_with_data::<B, bf16>(&ctx, &data.w2);+ let up_biases_buf = create_buffer_with_data::<B, bf16>(&ctx, &data.up_biases);+ let down_biases_buf = create_buffer_with_data::<B, bf16>(&ctx, &data.down_biases);let experts_kernel =MoeExpertsTwoPassPrefillBlock::<B>::new(&ctx, DataType::BF16, gating_code).expect("kernel");- let mut encoder = Encoder::new(ctx.as_ref()).expect("Failed to create encoder");+ let mut command_buffer = ctx.create_command_buffer(None, None).expect("Failed to create command buffer");let args = MoeExpertsTwoPassArguments {x_perm: &x_perm_buf,expert_offsets: &offsets_buf,@@ -596,10 +600,11 @@ fn test_two_pass_prefill_correctness() {up_clip_max: f32::INFINITY,silu_alpha,};- let y_partial_buf = experts_kernel.encode(args, &mut encoder).expect("failed to encode MoE experts");- let completed = encoder.end_encoding().submit().wait_until_completed().unwrap();+ let y_partial_buf = experts_kernel.encode(args, &mut command_buffer).expect("failed to encode MoE experts");+ let completed = command_buffer.end_encoding().submit().wait_until_completed().unwrap();- let y_partial_gpu = allocation_prefix_to_vec::<B, bf16>(&y_partial_buf, sum_k * d_model);+ let y_partial_gpu =+ buffer_prefix_to_vec::<B, bf16>(&buffer_readback::<B>(&ctx, &y_partial_buf), sum_k * d_model);let y_gpu = gather_and_finalize(&y_partial_gpu, &data.topk_probs, &scatter.perm_idx, t, k, d_model);assert_eq_float(&y_expected, &y_gpu, 0.02, "2-pass prefill");diff --git a/crates/uzu-engine/unit/encodable_block/moe/moe_gather_test.rs b/crates/uzu-engine/unit/encodable_block/moe/moe_gather_test.rsindex 3d454a413..0e94bc8c5 100644--- a/crates/uzu-engine/unit/encodable_block/moe/moe_gather_test.rs+++ b/crates/uzu-engine/unit/encodable_block/moe/moe_gather_test.rs@@ -7,12 +7,12 @@ use super::MoeGather;use crate::{array::ArrayElement,backends::{- common::{Backend, Encoder},+ common::{Backend, CommandBufferEncoding, CommandBufferExecutable, CommandBufferPending, Context},cpu::Cpu,},tests::{assert::assert_eq_float,- helpers::{alloc_allocation_with_data, allocation_to_vec, create_context, for_each_non_cpu_backend},+ helpers::{buffer_readback, buffer_to_vec, create_buffer_with_data, create_context, for_each_non_cpu_backend},},};@@ -28,26 +28,26 @@ fn get_output<B: Backend, T: ArrayElement + Float>(input: &Input<T>) -> Vec<T> {let context = create_context::<B>();let sumk_data: [u32; 1] = [input.sum_k as u32];- let x_allocation = alloc_allocation_with_data::<B, T>(&context, &input.x);- let ids_allocation = alloc_allocation_with_data::<B, i32>(&context, &input.bucket_ids);- let sumk_allocation = alloc_allocation_with_data::<B, u32>(&context, &sumk_data);+ let x_buffer = create_buffer_with_data::<B, T>(&context, &input.x);+ let ids_buffer = create_buffer_with_data::<B, i32>(&context, &input.bucket_ids);+ let sumk_buffer = create_buffer_with_data::<B, u32>(&context, &sumk_data);let gather = MoeGather::<B>::new(&context, T::data_type()).expect("MoeGather::new");- let mut encoder = Encoder::new(context.as_ref()).expect("Failed to create encoder");- let x_perm_allocation = gather+ let mut command_buffer = context.create_command_buffer(None, None).expect("Failed to create command buffer");+ let x_perm_buffer = gather.encode(- &x_allocation,- &ids_allocation,- &sumk_allocation,+ &x_buffer,+ &ids_buffer,+ &sumk_buffer,input.t as u32,(input.sum_k / input.t) as u32,input.d_model as u32,- &mut encoder,+ &mut command_buffer,).expect("Failed to encode MoE gather");- let completed = encoder.end_encoding().submit().wait_until_completed().unwrap();+ let completed = command_buffer.end_encoding().submit().wait_until_completed().unwrap();- let output = allocation_to_vec::<B, T>(&x_perm_allocation);- drop(x_perm_allocation);+ let output = buffer_to_vec::<B, T>(&buffer_readback::<B>(&context, &x_perm_buffer));+ drop(x_perm_buffer);drop(completed);output}diff --git a/crates/uzu-engine/unit/encodable_block/moe/moe_perf_test.rs b/crates/uzu-engine/unit/encodable_block/moe/moe_perf_test.rsindex 812bf04a9..2ada4cd89 100644--- a/crates/uzu-engine/unit/encodable_block/moe/moe_perf_test.rs+++ b/crates/uzu-engine/unit/encodable_block/moe/moe_perf_test.rs@@ -5,7 +5,7 @@ use uzu_engine_macros::uzu_test;use super::{MoeExpertsTwoPassArguments, MoeExpertsTwoPassDecodeBlock, MoeGather};use crate::{backends::common::{- Allocation, Backend, Encoder, Kernels,+ Backend, CommandBufferEncoding, CommandBufferExecutable, CommandBufferPending, Context, Kernels,kernel::{MoeBlockBasesFromPartialsKernel, MoeCountsOffsetsFusedKernel, MoeFinalizeKernel, MoeRouterTopKKernel,MoeScatterBucketsMapKernel,@@ -13,7 +13,7 @@ use crate::{},data_type::DataType,tests::{- helpers::{alloc_allocation, alloc_allocation_with_data, create_context, for_each_non_cpu_backend},+ helpers::{create_buffer, create_buffer_with_data, create_context, for_each_non_cpu_backend},perf::run_perf_with_warmup,},};@@ -40,11 +40,11 @@ fn test_moe_e2e_decode_perf() {let router_b: Vec<bf16> = (0..e).map(|_| bf16::from_f32(rng.random_range(-0.1..0.1))).collect();// Buffers (simplified - just key buffers for timing)- let x_buf = alloc_allocation_with_data::<B, bf16>(&ctx, &x);- let router_w_buf = alloc_allocation_with_data::<B, bf16>(&ctx, &router_w);- let router_b_buf = alloc_allocation_with_data::<B, bf16>(&ctx, &router_b);- let mut topk_ids_buf = alloc_allocation::<B, i32>(&ctx, t * k);- let mut topk_probs_buf = alloc_allocation::<B, bf16>(&ctx, t * k);+ let x_buf = create_buffer_with_data::<B, bf16>(&ctx, &x);+ let router_w_buf = create_buffer_with_data::<B, bf16>(&ctx, &router_w);+ let router_b_buf = create_buffer_with_data::<B, bf16>(&ctx, &router_b);+ let mut topk_ids_buf = create_buffer::<B, i32>(&ctx, t * k);+ let mut topk_probs_buf = create_buffer::<B, bf16>(&ctx, t * k);let router_topk = <<B as Backend>::Kernels as Kernels>::MoeRouterTopKKernel::new(&ctx,@@ -59,13 +59,14 @@ fn test_moe_e2e_decode_perf() {// Time fused Router+TopKlet fused_perf = run_perf_with_warmup("Router+TopK (FUSED)", 5, 20, || {- let mut encoder = Encoder::new(ctx.as_ref()).expect("Failed to create encoder");+ let mut command_buffer =+ ctx.create_command_buffer(None, None).expect("Failed to create command buffer");router_topk.encode(&x_buf,&router_w_buf,Some(&router_b_buf),- None::<&Allocation<B>>,- None::<&Allocation<B>>,+ None::<&<B as Backend>::GlobalBuffer>,+ None::<&<B as Backend>::GlobalBuffer>,&mut topk_ids_buf,&mut topk_probs_buf,t as u32,@@ -75,9 +76,9 @@ fn test_moe_e2e_decode_perf() {true,None::<f32>,None::<f32>,- &mut encoder,+ &mut command_buffer,);- encoder.end_encoding().submit().wait_until_completed().unwrap();+ command_buffer.end_encoding().submit().wait_until_completed().unwrap();});fused_perf.print();eprintln!(" Total: {:8.1} µs/token", fused_perf.mean_ms * 1000.0);@@ -109,11 +110,11 @@ fn test_moe_e2e_prefill_perf() {let router_b: Vec<bf16> = (0..e).map(|_| bf16::from_f32(rng.random_range(-0.1..0.1))).collect();// Buffers (simplified - just key buffers for timing)- let x_buf = alloc_allocation_with_data::<B, bf16>(&ctx, &x);- let router_w_buf = alloc_allocation_with_data::<B, bf16>(&ctx, &router_w);- let router_b_buf = alloc_allocation_with_data::<B, bf16>(&ctx, &router_b);- let mut topk_ids_buf = alloc_allocation::<B, i32>(&ctx, t * k);- let mut topk_probs_buf = alloc_allocation::<B, bf16>(&ctx, t * k);+ let x_buf = create_buffer_with_data::<B, bf16>(&ctx, &x);+ let router_w_buf = create_buffer_with_data::<B, bf16>(&ctx, &router_w);+ let router_b_buf = create_buffer_with_data::<B, bf16>(&ctx, &router_b);+ let mut topk_ids_buf = create_buffer::<B, i32>(&ctx, t * k);+ let mut topk_probs_buf = create_buffer::<B, bf16>(&ctx, t * k);let router_topk = <<B as Backend>::Kernels as Kernels>::MoeRouterTopKKernel::new(&ctx,@@ -128,13 +129,14 @@ fn test_moe_e2e_prefill_perf() {// Time fused Router+TopKlet fused_perf = run_perf_with_warmup("Router+TopK (FUSED)", 5, 20, || {- let mut encoder = Encoder::new(ctx.as_ref()).expect("Failed to create encoder");+ let mut command_buffer =+ ctx.create_command_buffer(None, None).expect("Failed to create command buffer");router_topk.encode(&x_buf,&router_w_buf,Some(&router_b_buf),- None::<&Allocation<B>>,- None::<&Allocation<B>>,+ None::<&<B as Backend>::GlobalBuffer>,+ None::<&<B as Backend>::GlobalBuffer>,&mut topk_ids_buf,&mut topk_probs_buf,t as u32,@@ -144,9 +146,9 @@ fn test_moe_e2e_prefill_perf() {true,None::<f32>,None::<f32>,- &mut encoder,+ &mut command_buffer,);- encoder.end_encoding().submit().wait_until_completed().unwrap();+ command_buffer.end_encoding().submit().wait_until_completed().unwrap();});eprintln!(" Total: {:8.3} ms", fused_perf.mean_ms);eprintln!(@@ -176,21 +178,21 @@ fn test_moe_pipeline_breakdown_decode() {let router_w: Vec<bf16> = (0..e * d_model).map(|_| bf16::from_f32(rng.random_range(-0.5..0.5))).collect();let router_b: Vec<bf16> = (0..e).map(|_| bf16::from_f32(rng.random_range(-0.1..0.1))).collect();- let x_buf = alloc_allocation_with_data::<B, bf16>(&ctx, &x);- let router_w_buf = alloc_allocation_with_data::<B, bf16>(&ctx, &router_w);- let router_b_buf = alloc_allocation_with_data::<B, bf16>(&ctx, &router_b);- let mut topk_ids_buf = alloc_allocation::<B, i32>(&ctx, t * k);- let mut topk_probs_buf = alloc_allocation::<B, bf16>(&ctx, t * k);+ let x_buf = create_buffer_with_data::<B, bf16>(&ctx, &x);+ let router_w_buf = create_buffer_with_data::<B, bf16>(&ctx, &router_w);+ let router_b_buf = create_buffer_with_data::<B, bf16>(&ctx, &router_b);+ let mut topk_ids_buf = create_buffer::<B, i32>(&ctx, t * k);+ let mut topk_probs_buf = create_buffer::<B, bf16>(&ctx, t * k);let num_blocks = t.div_ceil(256).max(1);let num_tiles = e.div_ceil(512).max(1);- let mut partials_buf = alloc_allocation::<B, i32>(&ctx, num_blocks * num_tiles * e);- let mut offsets_buf = alloc_allocation::<B, u32>(&ctx, e + 1);- let mut sumk_buf = alloc_allocation::<B, u32>(&ctx, 1);- let mut bucketed_ids_buf = alloc_allocation::<B, i32>(&ctx, t * k);+ let mut partials_buf = create_buffer::<B, i32>(&ctx, num_blocks * num_tiles * e);+ let mut offsets_buf = create_buffer::<B, u32>(&ctx, e + 1);+ let mut sumk_buf = create_buffer::<B, u32>(&ctx, 1);+ let mut bucketed_ids_buf = create_buffer::<B, i32>(&ctx, t * k);let y_partial: Vec<bf16> = (0..t * k * d_model).map(|_| bf16::from_f32(rng.random_range(-1.0..1.0))).collect();- let y_partial_buf = alloc_allocation_with_data::<B, bf16>(&ctx, &y_partial);- let mut tok2row_buf = alloc_allocation::<B, i32>(&ctx, t * k);- let mut y_out_buf = alloc_allocation::<B, bf16>(&ctx, t * d_model);+ let y_partial_buf = create_buffer_with_data::<B, bf16>(&ctx, &y_partial);+ let mut tok2row_buf = create_buffer::<B, i32>(&ctx, t * k);+ let mut y_out_buf = create_buffer::<B, bf16>(&ctx, t * d_model);// Expert weights buffers// Generate W13 in original layout [E, d_model, 2*d_ff]@@ -215,17 +217,17 @@ fn test_moe_pipeline_breakdown_decode() {let up_biases: Vec<bf16> = (0..e * 2 * d_ff).map(|_| bf16::from_f32(rng.random_range(-0.1..0.1))).collect();let down_biases: Vec<bf16> = (0..e * d_model).map(|_| bf16::from_f32(rng.random_range(-0.1..0.1))).collect();- let w13_buf = alloc_allocation_with_data::<B, bf16>(&ctx, &w13);- let w2_buf = alloc_allocation_with_data::<B, bf16>(&ctx, &w2);- let up_biases_buf = alloc_allocation_with_data::<B, bf16>(&ctx, &up_biases);- let down_biases_buf = alloc_allocation_with_data::<B, bf16>(&ctx, &down_biases);+ let w13_buf = create_buffer_with_data::<B, bf16>(&ctx, &w13);+ let w2_buf = create_buffer_with_data::<B, bf16>(&ctx, &w2);+ let up_biases_buf = create_buffer_with_data::<B, bf16>(&ctx, &up_biases);+ let down_biases_buf = create_buffer_with_data::<B, bf16>(&ctx, &down_biases);let sum_k = t * k;// Scatter block bases buffers- let mut block_bases_buf = alloc_allocation::<B, u32>(&ctx, num_blocks * num_tiles);- let mut block_alloc_buf = alloc_allocation::<B, u32>(&ctx, num_blocks * num_tiles);- let mut bucketed_probs_buf = alloc_allocation::<B, bf16>(&ctx, t * k);+ let mut block_bases_buf = create_buffer::<B, u32>(&ctx, num_blocks * num_tiles);+ let mut block_alloc_buf = create_buffer::<B, u32>(&ctx, num_blocks * num_tiles);+ let mut bucketed_probs_buf = create_buffer::<B, bf16>(&ctx, t * k);// Create kernel structs (use production-validated encoding logic)let counts_offsets_kernel =@@ -253,13 +255,13 @@ fn test_moe_pipeline_breakdown_decode() {// Testing: Router + TopK + Counts+Offsets (FUSED)let router_topk_fused_perf = run_perf_with_warmup("Router+TopK (FUSED)", 2, 5, || {- let mut encoder = Encoder::new(ctx.as_ref()).expect("Failed to create encoder");+ let mut command_buffer = ctx.create_command_buffer(None, None).expect("Failed to create command buffer");router_topk_fused_kernel.encode(&x_buf,&router_w_buf,Some(&router_b_buf),- None::<&Allocation<B>>,- None::<&Allocation<B>>,+ None::<&<B as Backend>::GlobalBuffer>,+ None::<&<B as Backend>::GlobalBuffer>,&mut topk_ids_buf,&mut topk_probs_buf,t as u32,@@ -269,13 +271,13 @@ fn test_moe_pipeline_breakdown_decode() {true,None::<f32>,None::<f32>,- &mut encoder,+ &mut command_buffer,);- encoder.end_encoding().submit().wait_until_completed().unwrap();+ command_buffer.end_encoding().submit().wait_until_completed().unwrap();});let counts_offsets_perf = run_perf_with_warmup("Counts+Offsets (FUSED)", 2, 5, || {- let mut encoder = Encoder::new(ctx.as_ref()).expect("Failed to create encoder");+ let mut command_buffer = ctx.create_command_buffer(None, None).expect("Failed to create command buffer");counts_offsets_kernel.encode(&topk_ids_buf,&mut offsets_buf,@@ -284,13 +286,13 @@ fn test_moe_pipeline_breakdown_decode() {t as u32,e as u32,k as u32,- &mut encoder,+ &mut command_buffer,);- encoder.end_encoding().submit().wait_until_completed().unwrap();+ command_buffer.end_encoding().submit().wait_until_completed().unwrap();});let scatter_perf = run_perf_with_warmup("Scatter", 2, 5, || {- let mut encoder = Encoder::new(ctx.as_ref()).expect("Failed to create encoder");+ let mut command_buffer = ctx.create_command_buffer(None, None).expect("Failed to create command buffer");scatter_bases_kernel.encode(&partials_buf,&mut block_bases_buf,@@ -299,7 +301,7 @@ fn test_moe_pipeline_breakdown_decode() {num_blocks as u32,num_tiles as u32,0u32,- &mut encoder,+ &mut command_buffer,);scatter_map_kernel.encode(&topk_ids_buf,@@ -315,32 +317,32 @@ fn test_moe_pipeline_breakdown_decode() {num_blocks as u32,num_tiles as u32,&mut tok2row_buf,- &mut encoder,+ &mut command_buffer,);- encoder.end_encoding().submit().wait_until_completed().unwrap();+ command_buffer.end_encoding().submit().wait_until_completed().unwrap();});let gather_perf = run_perf_with_warmup("Gather", 2, 5, || {- let mut encoder = Encoder::new(ctx.as_ref()).expect("Failed to create encoder");+ let mut command_buffer = ctx.create_command_buffer(None, None).expect("Failed to create command buffer");let x_perm = gather- .encode(&x_buf, &bucketed_ids_buf, &sumk_buf, t as u32, k as u32, d_model as u32, &mut encoder)+ .encode(&x_buf, &bucketed_ids_buf, &sumk_buf, t as u32, k as u32, d_model as u32, &mut command_buffer).expect("failed to encode MoE gather");- let completed = encoder.end_encoding().submit().wait_until_completed().unwrap();+ let completed = command_buffer.end_encoding().submit().wait_until_completed().unwrap();drop(x_perm);drop(completed);});let (x_perm_buf, x_perm_completed) = {- let mut encoder = Encoder::new(ctx.as_ref()).expect("Failed to create encoder");+ let mut command_buffer = ctx.create_command_buffer(None, None).expect("Failed to create command buffer");let x_perm = gather- .encode(&x_buf, &bucketed_ids_buf, &sumk_buf, t as u32, k as u32, d_model as u32, &mut encoder)+ .encode(&x_buf, &bucketed_ids_buf, &sumk_buf, t as u32, k as u32, d_model as u32, &mut command_buffer).expect("failed to encode MoE gather");- let completed = encoder.end_encoding().submit().wait_until_completed().unwrap();+ let completed = command_buffer.end_encoding().submit().wait_until_completed().unwrap();(x_perm, completed)};let experts_perf = run_perf_with_warmup("Experts (MAIN COMPUTE)", 2, 5, || {- let mut encoder = Encoder::new(ctx.as_ref()).expect("Failed to create encoder");+ let mut command_buffer = ctx.create_command_buffer(None, None).expect("Failed to create command buffer");let output = experts_kernel.encode(MoeExpertsTwoPassArguments {@@ -360,10 +362,10 @@ fn test_moe_pipeline_breakdown_decode() {up_clip_max: 21.0,silu_alpha: 1.702,},- &mut encoder,+ &mut command_buffer,).expect("failed to encode MoE experts");- let completed = encoder.end_encoding().submit().wait_until_completed().unwrap();+ let completed = command_buffer.end_encoding().submit().wait_until_completed().unwrap();drop(output);drop(completed);});@@ -371,7 +373,7 @@ fn test_moe_pipeline_breakdown_decode() {drop(x_perm_completed);let finalize_perf = run_perf_with_warmup("Finalize", 2, 5, || {- let mut encoder = Encoder::new(ctx.as_ref()).expect("Failed to create encoder");+ let mut command_buffer = ctx.create_command_buffer(None, None).expect("Failed to create command buffer");finalize_kernel.encode(&tok2row_buf,&topk_probs_buf,@@ -380,9 +382,9 @@ fn test_moe_pipeline_breakdown_decode() {t as u32,d_model as u32,k as u32,- &mut encoder,+ &mut command_buffer,);- encoder.end_encoding().submit().wait_until_completed().unwrap();+ command_buffer.end_encoding().submit().wait_until_completed().unwrap();});// Print resultsdiff --git a/crates/uzu-engine/unit/encodable_block/moe/moe_tiles_test.rs b/crates/uzu-engine/unit/encodable_block/moe/moe_tiles_test.rsindex 689b5e201..99c8018e4 100644--- a/crates/uzu-engine/unit/encodable_block/moe/moe_tiles_test.rs+++ b/crates/uzu-engine/unit/encodable_block/moe/moe_tiles_test.rs@@ -3,12 +3,12 @@ use uzu_engine_macros::uzu_test;use crate::{backends::common::{- Backend, Encoder, Kernels,+ Backend, CommandBufferEncoding, CommandBufferExecutable, CommandBufferPending, Context, Kernels,kernel::{MoeTileCountsKernel, MoeTileScanKernel},},encodable_block::mlp::moe::tests::{cpu_tile_counts, cpu_tile_scan},tests::helpers::{- alloc_allocation, alloc_allocation_with_data, allocation_prefix_to_vec, allocation_to_vec, create_context,+ buffer_prefix_to_vec, buffer_to_vec, create_buffer, create_buffer_with_data, create_context,for_each_non_cpu_backend,},};@@ -35,17 +35,17 @@ fn test_tile_counts_correctness() {let tile_counts_cpu = cpu_tile_counts(&offsets, 16);// GPU buffers- let offsets_buf = alloc_allocation_with_data::<B, u32>(&ctx, &offsets);+ let offsets_buf = create_buffer_with_data::<B, u32>(&ctx, &offsets);// Execute kernel using kernel structlet counts_kernel =<<B as Backend>::Kernels as Kernels>::MoeTileCountsKernel::new(&ctx).expect("MoeTileCountsKernel::new");- let mut encoder = Encoder::new(ctx.as_ref()).expect("Failed to create encoder");- let mut tile_counts_buf = alloc_allocation::<B, u32>(&ctx, e);- counts_kernel.encode(&offsets_buf, &mut tile_counts_buf, e as u32, &mut encoder);- let completed = encoder.end_encoding().submit().wait_until_completed().unwrap();+ let mut command_buffer = ctx.create_command_buffer(None, None).expect("Failed to create command buffer");+ let mut tile_counts_buf = create_buffer::<B, u32>(&ctx, e);+ counts_kernel.encode(&offsets_buf, &mut tile_counts_buf, e as u32, &mut command_buffer);+ let completed = command_buffer.end_encoding().submit().wait_until_completed().unwrap();- let tile_counts_gpu = allocation_prefix_to_vec::<B, u32>(&tile_counts_buf, e);+ let tile_counts_gpu = buffer_prefix_to_vec::<B, u32>(&tile_counts_buf, e);drop(tile_counts_buf);drop(completed);@@ -74,19 +74,25 @@ fn test_tile_scan_correctness() {let (tile_offsets_cpu, total_tiles_cpu) = cpu_tile_scan(&tile_counts);// GPU buffers- let tile_counts_buf = alloc_allocation_with_data::<B, u32>(&ctx, &tile_counts);+ let tile_counts_buf = create_buffer_with_data::<B, u32>(&ctx, &tile_counts);// Execute kernel using kernel structlet scan_kernel =<<B as Backend>::Kernels as Kernels>::MoeTileScanKernel::new(&ctx).expect("MoeTileScanKernel::new");- let mut encoder = Encoder::new(ctx.as_ref()).expect("Failed to create encoder");- let mut tile_offsets_buf = alloc_allocation::<B, u32>(&ctx, e + 1);- let mut total_tiles_buf = alloc_allocation::<B, u32>(&ctx, 8);- scan_kernel.encode(&tile_counts_buf, &mut tile_offsets_buf, &mut total_tiles_buf, e as u32, &mut encoder);- let completed = encoder.end_encoding().submit().wait_until_completed().unwrap();-- let tile_offsets_gpu = allocation_prefix_to_vec::<B, u32>(&tile_offsets_buf, e + 1);- let total_tiles_gpu = allocation_to_vec::<B, u32>(&total_tiles_buf)[0];+ let mut command_buffer = ctx.create_command_buffer(None, None).expect("Failed to create command buffer");+ let mut tile_offsets_buf = create_buffer::<B, u32>(&ctx, e + 1);+ let mut total_tiles_buf = create_buffer::<B, u32>(&ctx, 8);+ scan_kernel.encode(+ &tile_counts_buf,+ &mut tile_offsets_buf,+ &mut total_tiles_buf,+ e as u32,+ &mut command_buffer,+ );+ let completed = command_buffer.end_encoding().submit().wait_until_completed().unwrap();++ let tile_offsets_gpu = buffer_prefix_to_vec::<B, u32>(&tile_offsets_buf, e + 1);+ let total_tiles_gpu = buffer_to_vec::<B, u32>(&total_tiles_buf)[0];drop(tile_offsets_buf);drop(total_tiles_buf);drop(completed);@@ -111,16 +117,16 @@ fn test_tile_edge_cases() {let tile_counts_cpu = cpu_tile_counts(&offsets, 16);- let offsets_buf = alloc_allocation_with_data::<B, u32>(&ctx, &offsets);+ let offsets_buf = create_buffer_with_data::<B, u32>(&ctx, &offsets);let counts_kernel =<<B as Backend>::Kernels as Kernels>::MoeTileCountsKernel::new(&ctx).expect("MoeTileCountsKernel::new");- let mut encoder = Encoder::new(ctx.as_ref()).expect("Failed to create encoder");- let mut tile_counts_buf = alloc_allocation::<B, u32>(&ctx, e);- counts_kernel.encode(&offsets_buf, &mut tile_counts_buf, e as u32, &mut encoder);- let completed = encoder.end_encoding().submit().wait_until_completed().unwrap();+ let mut command_buffer = ctx.create_command_buffer(None, None).expect("Failed to create command buffer");+ let mut tile_counts_buf = create_buffer::<B, u32>(&ctx, e);+ counts_kernel.encode(&offsets_buf, &mut tile_counts_buf, e as u32, &mut command_buffer);+ let completed = command_buffer.end_encoding().submit().wait_until_completed().unwrap();- let tile_counts_gpu = allocation_prefix_to_vec::<B, u32>(&tile_counts_buf, e);+ let tile_counts_gpu = buffer_prefix_to_vec::<B, u32>(&tile_counts_buf, e);drop(tile_counts_buf);drop(completed);@@ -136,16 +142,16 @@ fn test_tile_edge_cases() {let tile_counts_cpu = cpu_tile_counts(&offsets, 16);- let offsets_buf = alloc_allocation_with_data::<B, u32>(&ctx, &offsets);+ let offsets_buf = create_buffer_with_data::<B, u32>(&ctx, &offsets);let counts_kernel =<<B as Backend>::Kernels as Kernels>::MoeTileCountsKernel::new(&ctx).expect("MoeTileCountsKernel::new");- let mut encoder = Encoder::new(ctx.as_ref()).expect("Failed to create encoder");- let mut tile_counts_buf = alloc_allocation::<B, u32>(&ctx, e);- counts_kernel.encode(&offsets_buf, &mut tile_counts_buf, e as u32, &mut encoder);- let completed = encoder.end_encoding().submit().wait_until_completed().unwrap();+ let mut command_buffer = ctx.create_command_buffer(None, None).expect("Failed to create command buffer");+ let mut tile_counts_buf = create_buffer::<B, u32>(&ctx, e);+ counts_kernel.encode(&offsets_buf, &mut tile_counts_buf, e as u32, &mut command_buffer);+ let completed = command_buffer.end_encoding().submit().wait_until_completed().unwrap();- let tile_counts_gpu = allocation_prefix_to_vec::<B, u32>(&tile_counts_buf, e);+ let tile_counts_gpu = buffer_prefix_to_vec::<B, u32>(&tile_counts_buf, e);drop(tile_counts_buf);drop(completed);diff --git a/crates/uzu-engine/unit/encodable_block/sampling_test.rs b/crates/uzu-engine/unit/encodable_block/sampling_test.rsindex cb3e990b5..f00b7bfff 100644--- a/crates/uzu-engine/unit/encodable_block/sampling_test.rs+++ b/crates/uzu-engine/unit/encodable_block/sampling_test.rs@@ -8,7 +8,10 @@ use uzu_engine_macros::uzu_test;use crate::{array::ArrayElement,- backends::common::{AllocationType, Backend, Context, Encoder, gpu_types::trie::TrieNode},+ backends::common::{+ Backend, BufferRef, CommandBufferEncoding, CommandBufferExecutable, CommandBufferPending, Context,+ gpu_types::trie::TrieNode,+ },data_type::DataType,dispatch_dtype,encodable_block::{@@ -41,25 +44,12 @@ fn do_sampling_backend<B: Backend, T: ArrayElement + Float>(method: &SamplingMethod,batch_size: u32,) -> Result<SamplingTestResults, TestCaseError> {- let sampling = Sampling::new(T::data_type(), vocab_size as u32);-- let mut logits_allocation =- context.create_allocation(logits.len() * T::data_type().size_in_bytes(), AllocationType::Global).unwrap();- logits_allocation.copyin(logits);- let seeds_allocation = if let Some(seeds) = seeds {- let mut seeds_allocation = context.create_allocation(seeds.len() * 8, AllocationType::Global).unwrap();- seeds_allocation.copyin(seeds);- Some(seeds_allocation)- } else {- None- };- let bitmask_allocation = if let Some(bitmask) = bitmask {- let mut bitmask_allocation = context.create_allocation(bitmask.len() * 4, AllocationType::Global).unwrap();- bitmask_allocation.copyin(bitmask);- Some(bitmask_allocation)- } else {- None- };+ let sampling = Sampling::<B>::new(T::data_type(), vocab_size as u32);++ let mut command_buffer = context.create_command_buffer(None, None).unwrap();+ let logits_buffer = command_buffer.allocate_constant_from_slice(logits).unwrap();+ let seeds_buffer = seeds.map(|seeds| command_buffer.allocate_constant_from_slice(seeds).unwrap());+ let bitmask_buffer = bitmask.map(|bitmask| command_buffer.allocate_constant_from_slice(bitmask).unwrap());let nodes = (0..batch_size).map(|index| TrieNode {@@ -70,23 +60,25 @@ fn do_sampling_backend<B: Backend, T: ArrayElement + Float>(.collect::<Box<[_]>>();let batch_topology = BatchTopology::new(&nodes, true);- let mut encoder = Encoder::new(context).unwrap();- let sampled_allocation = sampling+ let sampled_buffer = sampling.encode(- &logits_allocation,- seeds_allocation.as_ref(),- bitmask_allocation.as_ref(),- None, // TODO- None, // TODO+ &logits_buffer,+ seeds_buffer.as_ref(),+ bitmask_buffer.as_ref(),+ None::<&B::GlobalBuffer>, // TODO+ None::<&B::ConstantBuffer>, // TODOmethod,&batch_topology,- 0..batch_size,- &mut encoder,+ (0..batch_size).into(),+ &mut command_buffer,).unwrap();- encoder.end_encoding().submit().wait_until_completed().unwrap();+ drop(logits_buffer);+ drop(seeds_buffer);+ drop(bitmask_buffer);+ command_buffer.end_encoding().submit().wait_until_completed().unwrap();- let sampled = sampled_allocation.copyout::<u32>();+ let sampled = sampled_buffer.copyout::<u32>();Ok(SamplingTestResults(sampled))}diff --git a/flake.nix b/flake.nixindex 2e593803f..07ebf6d68 100644--- a/flake.nix+++ b/flake.nix@@ -116,6 +116,7 @@cargo-nextestcargo-hackcargo-expand+ samplycargo-flamegraphcargo-show-asmcritcmp