A high-performance inference engine for AI models
Burn unsafe and unsound impl Send + Sync in bridge (#615)
uuuvn0f7f0e707894
diff --git a/Cargo.lock b/Cargo.lockindex e82d20b00..6a98b9a8e 100644--- a/Cargo.lock+++ b/Cargo.lock@@ -498,6 +498,7 @@ dependencies = ["obfstr","objc2","objc2-foundation",+ "parking_lot","prettyplease","proc-macro2","proc-macros",@@ -1952,9 +1953,6 @@ name = "esaxx-rs"version = "0.1.10"source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "d817e038c30374a4bcb22f94d0a8a0e216958d4c3dcde369b1439fec4bdda6e6"-dependencies = [- "cc",-][[package]]name = "etcetera"@@ -3757,9 +3755,9 @@ dependencies = [[[package]]name = "mtl-rs"-version = "0.1.13"+version = "0.1.14"source = "registry+https://github.com/rust-lang/crates.io-index"-checksum = "eb19a6103808f1af363f96d845bd734c49df73eda4ada4177d118560cd4cf0ba"+checksum = "6365d3a49e40c611ee28aa0f1bc90abc69b3b3a38172f63b1fdb0061809cba91"dependencies = ["bitflags 2.13.0","block2",@@ -4310,28 +4308,6 @@ version = "1.70.2"source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "384b8ab6d37215f3c5301a95a4accb5d64aa607f1fcb26a11b5303878451b4fe"-[[package]]-name = "onig"-version = "6.5.3"-source = "registry+https://github.com/rust-lang/crates.io-index"-checksum = "0cc3cbf698f9438986c11a880c90a6d04b9de27575afd28bbf45b154b6c709e2"-dependencies = [- "bitflags 2.13.0",- "libc",- "once_cell",- "onig_sys",-]--[[package]]-name = "onig_sys"-version = "69.9.3"-source = "registry+https://github.com/rust-lang/crates.io-index"-checksum = "1e68317604e77e53b85896388e1a803c1d21b74c899ec9e5e1112db90735edd7"-dependencies = [- "cc",- "pkg-config",-]-[[package]]name = "oorandom"version = "11.1.5"@@ -6922,12 +6898,10 @@ dependencies = ["esaxx-rs","fancy-regex 0.14.0","getrandom 0.3.4",- "indicatif","itertools 0.14.0","log","macro_rules_attribute","monostate",- "onig","paste","rand 0.9.4","rayon",@@ -7999,6 +7973,15 @@ dependencies = ["wezterm-dynamic",]+[[package]]+name = "which"+version = "8.0.5"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "8f3ef584124b911bcc3875c2f1472e80f24361ceb789bd1c62b3e9a3df9ff43c"+dependencies = [+ "libc",+]+[[package]]name = "winapi"version = "0.3.9"@@ -8429,15 +8412,17 @@ checksum = "1ffae5123b2d3fc086436f8834ae3ab053a283cfac8fe0a0b8eaae044768a4c4"[[package]]name = "xgrammar-rs"-version = "0.2.2"-source = "git+https://github.com/trymirai/xgrammar-rs.git?tag=0.2.2#d55d5bb1403f443d6a379c5acc7191a28bbcbb92"+version = "0.2.3"+source = "git+https://github.com/trymirai/xgrammar-rs.git?tag=0.2.3#e1e0f27df369c5d6027cc89ba4801fcda10e7b9e"dependencies = [+ "cc","cmake","cxx","cxx-build","serde_json","tokenizers","walkdir",+ "which",][[package]]diff --git a/Cargo.toml b/Cargo.tomlindex 04f93085c..39571b6d9 100644--- a/Cargo.toml+++ b/Cargo.toml@@ -62,7 +62,7 @@ keisoku = { path = "crates/keisoku", default-features = false }kanka = { path = "crates/kanka", default-features = false }kiban = { path = "crates/kiban", default-features = false }uzu = { path = "crates/uzu", default-features = false }-xgrammar = { package = "xgrammar-rs", git = "https://github.com/trymirai/xgrammar-rs.git", tag = "0.2.2", features = ["tokenizers"] }+xgrammar = { package = "xgrammar-rs", git = "https://github.com/trymirai/xgrammar-rs.git", tag = "0.2.3", features = ["tokenizers"] }half = { version = "2.7", features = ["bytemuck", "num-traits"] }ndarray = "0.17"serde = { version = "1.0", features = ["derive"] }@@ -78,7 +78,7 @@ objc2-core-foundation = "0.3.2"objc2-io-kit = { version = "0.3.2", default-features = false, features = ["libc", "ps"] }objc2-security = "0.3.2"obfstr = "0.4.4"-metal = { package = "mtl-rs", version = "0.1.12" }+metal = { package = "mtl-rs", version = "0.1.14" }block2 = "0.6"bytemuck = "1.23"bytesize = "2"@@ -108,6 +108,7 @@ depfile = "0.1"tempfile = "3.24"clang-ast = "0.1"rangemap = "1.7.1"+parking_lot = "0.12"futures = "0.3"async-stream = "0.3"tokio = "1.49"diff --git a/crates/backend-uzu/Cargo.toml b/crates/backend-uzu/Cargo.tomlindex c986973da..cccee27d9 100644--- a/crates/backend-uzu/Cargo.toml+++ b/crates/backend-uzu/Cargo.toml@@ -38,6 +38,7 @@ itertools.workspace = trueschemars.workspace = truerustix.workspace = truefutures.workspace = true+parking_lot = { workspace = true, features = ["send_guard"] }async-stream.workspace = truetokio-util.workspace = truediff --git a/crates/backend-uzu/build/common/traitgen.rs b/crates/backend-uzu/build/common/traitgen.rsindex 9acdab424..69af15127 100644--- a/crates/backend-uzu/build/common/traitgen.rs+++ b/crates/backend-uzu/build/common/traitgen.rs@@ -70,7 +70,7 @@ pub fn traitgen(kernel: &Kernel) -> (TokenStream, TokenStream) {let kernel_trait = quote! {#[allow(clippy::style, clippy::complexity, clippy::perf)]- pub trait #trait_name: Sized {+ pub trait #trait_name: Sized + Send + Sync {type Backend: crate::backends::common::Backend<Kernels: Kernels<#trait_name = Self>>;#[allow(non_snake_case)]diff --git a/crates/backend-uzu/src/backends/common/allocator/allocator.rs b/crates/backend-uzu/src/backends/common/allocator/allocator.rsindex 8d97cf26d..ec2c4d815 100644--- a/crates/backend-uzu/src/backends/common/allocator/allocator.rs+++ b/crates/backend-uzu/src/backends/common/allocator/allocator.rs@@ -1,11 +1,13 @@use std::{- cell::RefCell,ops::Range,- pin::Pin,- rc::{Rc, Weak},+ 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,@@ -13,8 +15,8 @@ use crate::backends::common::{};pub struct Allocation<B: Backend> {- allocator: Rc<Allocator<B>>,- buffer: *const B::DenseBuffer,+ allocator: Arc<Allocator<B>>,+ buffer: Arc<B::DenseBuffer>,range: Range<usize>,allocation_type: RangeAllocationType,}@@ -58,19 +60,14 @@ impl<B: Backend> AsBufferRangeRef for Allocation<B> {type Buffer = B::DenseBuffer;fn as_buffer_range_ref<'a>(&'a self) -> BufferRangeRef<'a, B::DenseBuffer> {- // SAFETY: we keep a strong ref to the allocator that owns the bufs and won't deallocate them while we're alive- let buffer = unsafe { &*self.buffer };-- BufferRangeRef::new(buffer, self.range.clone())+ 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: we keep a strong ref to the allocator that owns the bufs and won't deallocate them while we're alive- let buffer = unsafe { &*self.buffer };// 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(buffer, self.range.clone()) }+ unsafe { BufferRangeMut::new_shared(self.buffer.as_ref(), self.range.clone()) }}}@@ -82,7 +79,7 @@ impl<B: Backend> Drop for Allocation<B> {pub struct AllocationPool<B: Backend> {reusable: bool,- allocator: Rc<Allocator<B>>,+ allocator: Arc<Allocator<B>>,pool_number: usize,}@@ -101,29 +98,29 @@ pub enum AllocationType<'a, B: Backend> {}struct AllocatorBuffer<B: Backend> {- buffer: Pin<Box<B::DenseBuffer>>,+ buffer: Arc<B::DenseBuffer>,range_allocator: RangeAllocator,}pub struct Allocator<B: Backend> {context: Weak<B::Context>,- allocator_buffers: RefCell<Vec<AllocatorBuffer<B>>>,- next_pool_number: RefCell<usize>,- peak_memory_usage: RefCell<usize>,+ 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>) -> Rc<Self> {- Rc::new(Self {+ pub fn new(context: Weak<B::Context>) -> Arc<Self> {+ Arc::new(Self {context,- allocator_buffers: RefCell::new(Vec::new()),- next_pool_number: RefCell::new(0),- peak_memory_usage: RefCell::new(0),+ allocator_buffers: Mutex::new(Vec::new()),+ next_pool_number: AtomicUsize::new(0),+ peak_memory_usage: AtomicUsize::new(0),})}pub fn allocate(- self: &Rc<Self>,+ self: &Arc<Self>,size: usize,allocation_type: AllocationType<B>,) -> Result<Allocation<B>, B::Error> {@@ -142,13 +139,12 @@ impl<B: Backend> Allocator<B> {},};- let mut allocator_buffers = self.allocator_buffers.borrow_mut();+ 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)?;- let buffer = allocator_buffer.buffer.as_ref().get_ref() as *const B::DenseBuffer;- Some((allocator_buffer_index, buffer, range))+ Some((allocator_buffer_index, allocator_buffer.buffer.clone(), range))});let (buffer, range) = if let Some((allocator_buffer_index, buffer, range)) = found {@@ -159,11 +155,11 @@ impl<B: Backend> Allocator<B> {let new_allocator_buffer_size = usize::max(size, B::ALLOCATION_GRANULARITY);let mut allocator_buffer = AllocatorBuffer::<B> {- buffer: Box::pin(self.context.upgrade().unwrap().create_buffer(new_allocator_buffer_size)?), // Upgrade can never fail+ buffer: Arc::new(self.context.upgrade().unwrap().create_buffer(new_allocator_buffer_size)?), // Upgrade can never failrange_allocator: RangeAllocator::new(0..new_allocator_buffer_size),};- let buffer = allocator_buffer.buffer.as_ref().get_ref() as *const B::DenseBuffer;+ let buffer = allocator_buffer.buffer.clone();let range =allocator_buffer.range_allocator.allocate_range_aligned(size, alignment, allocation_type).unwrap(); // Can never fail@@ -171,8 +167,10 @@ impl<B: Backend> Allocator<B> {let allocator_buffer_index = allocator_buffers.len() - 1;Self::restore_buffer_order(&mut allocator_buffers, allocator_buffer_index);- *self.peak_memory_usage.borrow_mut() =- allocator_buffers.iter().map(|allocator_buffer| allocator_buffer.buffer.size()).sum();+ self.peak_memory_usage.store(+ allocator_buffers.iter().map(|allocator_buffer| allocator_buffer.buffer.size()).sum(),+ Ordering::Relaxed,+ );(buffer, range)};@@ -186,12 +184,10 @@ impl<B: Backend> Allocator<B> {}pub fn create_pool(- self: &Rc<Self>,+ self: &Arc<Self>,reusable: bool,) -> AllocationPool<B> {- let pool_number = *self.next_pool_number.borrow();-- *self.next_pool_number.borrow_mut() += 1;+ let pool_number = self.next_pool_number.fetch_add(1, Ordering::Relaxed);AllocationPool {reusable,@@ -200,21 +196,21 @@ impl<B: Backend> Allocator<B> {}}- pub fn peak_memory_usage(self: Rc<Self>) -> usize {- *self.peak_memory_usage.borrow()+ pub fn peak_memory_usage(&self) -> usize {+ self.peak_memory_usage.load(Ordering::Relaxed)}// TODO: Maybe hysteresis in free/free_pool?fn free(- self: &Rc<Self>,+ self: &Arc<Self>,allocation: &Allocation<B>,) {- let mut allocator_buffers = self.allocator_buffers.borrow_mut();+ let mut allocator_buffers = self.allocator_buffers.lock();let allocator_buffer_index = allocator_buffers.iter()- .position(|allocator_buffer| std::ptr::eq(allocator_buffer.buffer.as_ref().get_ref(), allocation.buffer))+ .position(|allocator_buffer| Arc::ptr_eq(&allocator_buffer.buffer, &allocation.buffer)).unwrap(); // Can never failallocator_buffers[allocator_buffer_index]@@ -229,10 +225,10 @@ impl<B: Backend> Allocator<B> {}fn free_pool(- self: &Rc<Self>,+ self: &Arc<Self>,pool: &AllocationPool<B>,) {- let mut allocator_buffers = self.allocator_buffers.borrow_mut();+ let mut allocator_buffers = self.allocator_buffers.lock();allocator_buffers.retain_mut(|allocation_buffer| {allocation_buffer.range_allocator.free_pool(pool.pool_number);diff --git a/crates/backend-uzu/src/backends/common/backend.rs b/crates/backend-uzu/src/backends/common/backend.rsindex 70ea34230..94f344e19 100644--- a/crates/backend-uzu/src/backends/common/backend.rs+++ b/crates/backend-uzu/src/backends/common/backend.rs@@ -2,7 +2,7 @@ use std::{error::Error, fmt::Debug};use super::{CommandBuffer, Context, DenseBuffer, Kernels, SparseBuffer};-pub trait Backend: Debug + Clone + 'static {+pub trait Backend: Debug + Clone + Send + Sync + 'static {type Context: Context<Backend = Self>;type CommandBuffer: CommandBuffer<Backend = Self>;type DenseBuffer: DenseBuffer<Backend = Self>;diff --git a/crates/backend-uzu/src/backends/common/buffer/mod.rs b/crates/backend-uzu/src/backends/common/buffer/mod.rsindex b9130c339..b9e2fd07c 100644--- a/crates/backend-uzu/src/backends/common/buffer/mod.rs+++ b/crates/backend-uzu/src/backends/common/buffer/mod.rs@@ -8,7 +8,7 @@ pub mod sparse;pub mod arg;pub mod range;-pub trait Buffer: Any + Debug {+pub trait Buffer: Any + Debug + Send + Sync {type Backend: Backend;fn gpu_ptr(&self) -> usize;diff --git a/crates/backend-uzu/src/backends/common/command_buffer.rs b/crates/backend-uzu/src/backends/common/command_buffer.rsindex 41da4cecb..d0f7b72d5 100644--- a/crates/backend-uzu/src/backends/common/command_buffer.rs+++ b/crates/backend-uzu/src/backends/common/command_buffer.rs@@ -12,7 +12,7 @@ pub trait CommandBuffer {type Completed: CommandBufferCompleted<CommandBuffer = Self>;}-pub trait CommandBufferInitial {+pub trait CommandBufferInitial: Send {type CommandBuffer: CommandBuffer<Initial = Self>;fn start_encoding(self) -> <Self::CommandBuffer as CommandBuffer>::Encoding;@@ -94,13 +94,13 @@ pub trait CommandBufferEncoding {fn end_encoding(self) -> <Self::CommandBuffer as CommandBuffer>::Executable;}-pub trait CommandBufferExecutable {+pub trait CommandBufferExecutable: Send {type CommandBuffer: CommandBuffer<Executable = Self>;fn submit(self) -> <Self::CommandBuffer as CommandBuffer>::Pending;}-pub trait CommandBufferPending {+pub trait CommandBufferPending: Send {type CommandBuffer: CommandBuffer<Pending = Self>;fn wait_until_completed(@@ -111,7 +111,7 @@ pub trait CommandBufferPending {>;}-pub trait CommandBufferCompleted {+pub trait CommandBufferCompleted: Send {type CommandBuffer: CommandBuffer<Completed = Self>;fn gpu_execution_time(&self) -> Duration;diff --git a/crates/backend-uzu/src/backends/common/context.rs b/crates/backend-uzu/src/backends/common/context.rsindex bb8fbd67a..9dadfcf0b 100644--- a/crates/backend-uzu/src/backends/common/context.rs+++ b/crates/backend-uzu/src/backends/common/context.rs@@ -1,11 +1,11 @@-use std::{path::Path, rc::Rc};+use std::{path::Path, sync::Arc};use crate::backends::common::{Allocation, AllocationPool, AllocationType, Backend, CommandBuffer};-pub trait Context: Sized {+pub trait Context: Sized + Send + Sync {type Backend: Backend<Context = Self>;- fn new() -> Result<Rc<Self>, <Self::Backend as Backend>::Error>;+ fn new() -> Result<Arc<Self>, <Self::Backend as Backend>::Error>;fn create_command_buffer(&selfdiff --git a/crates/backend-uzu/src/backends/common/encoder.rs b/crates/backend-uzu/src/backends/common/encoder.rsindex 343a985a5..41bd7ee75 100644--- a/crates/backend-uzu/src/backends/common/encoder.rs+++ b/crates/backend-uzu/src/backends/common/encoder.rs@@ -1,6 +1,6 @@use std::{ops::{Bound, Range, RangeBounds},- rc::Rc,+ sync::Arc,time::Duration,};@@ -34,18 +34,18 @@ fn resolve_copy_range(pub struct Encoder<'encoding, B: Backend> {context: &'encoding B::Context,command_buffer: <B::CommandBuffer as CommandBuffer>::Encoding,- allocation_pool: Rc<AllocationPool<B>>,+ 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_pool(context, Rc::new(context.create_allocation_pool(false)))+ Self::new_with_pool(context, Arc::new(context.create_allocation_pool(false)))}pub fn new_with_pool(context: &'encoding B::Context,- allocation_pool: Rc<AllocationPool<B>>,+ allocation_pool: Arc<AllocationPool<B>>,) -> Result<Self, B::Error> {let command_buffer = context.create_command_buffer()?.start_encoding();let hazard_tracker = HazardTracker::new();@@ -159,7 +159,7 @@ impl<'encoding, B: Backend> Encoder<'encoding, B> {pub struct Executable<B: Backend> {command_buffer: <B::CommandBuffer as CommandBuffer>::Executable,- allocation_pool: Rc<AllocationPool<B>>,+ allocation_pool: Arc<AllocationPool<B>>,}impl<B: Backend> Executable<B> {@@ -173,7 +173,7 @@ impl<B: Backend> Executable<B> {pub struct Pending<B: Backend> {command_buffer: <B::CommandBuffer as CommandBuffer>::Pending,- allocation_pool: Rc<AllocationPool<B>>,+ allocation_pool: Arc<AllocationPool<B>>,}impl<B: Backend> Pending<B> {@@ -188,7 +188,7 @@ impl<B: Backend> Pending<B> {pub struct Completed<B: Backend> {command_buffer: <B::CommandBuffer as CommandBuffer>::Completed,#[allow(unused)]- allocation_pool: Rc<AllocationPool<B>>,+ allocation_pool: Arc<AllocationPool<B>>,}impl<B: Backend> Completed<B> {diff --git a/crates/backend-uzu/src/backends/common/kernel/attention_gemm/kernel.rs b/crates/backend-uzu/src/backends/common/kernel/attention_gemm/kernel.rsindex e30499d1e..44a1d0911 100644--- a/crates/backend-uzu/src/backends/common/kernel/attention_gemm/kernel.rs+++ b/crates/backend-uzu/src/backends/common/kernel/attention_gemm/kernel.rs@@ -5,7 +5,7 @@ use crate::{encodable_block::mixer::attention::core::{AttentionCoreEncodeArguments, AttentionCoreNewArguments},};-pub trait AttentionGemmCore<B: Backend<Kernels: Kernels<AttentionGemmCore = Self>>>: Sized {+pub trait AttentionGemmCore<B: Backend<Kernels: Kernels<AttentionGemmCore = Self>>>: Sized + Send + Sync {fn is_supported(arguments: &AttentionCoreNewArguments,context: &B::Context,diff --git a/crates/backend-uzu/src/backends/common/kernel/delta_net_chunked_prefill.rs b/crates/backend-uzu/src/backends/common/kernel/delta_net_chunked_prefill.rsindex d6de4bd5f..28ec0a2df 100644--- a/crates/backend-uzu/src/backends/common/kernel/delta_net_chunked_prefill.rs+++ b/crates/backend-uzu/src/backends/common/kernel/delta_net_chunked_prefill.rs@@ -19,7 +19,7 @@ pub struct DeltaNetChunkedPrefillArgs<'a, B: Backend> {pub suffix_len: usize,}-pub trait DeltaNetChunkedPrefill<B: Backend>: Sized {+pub trait DeltaNetChunkedPrefill<B: Backend>: Sized + Send + Sync {fn new(context: &B::Context,outer_data_type: DataType,diff --git a/crates/backend-uzu/src/backends/common/kernel/delta_net_tree_verify.rs b/crates/backend-uzu/src/backends/common/kernel/delta_net_tree_verify.rsindex e9d14bae9..c9de6f3bf 100644--- a/crates/backend-uzu/src/backends/common/kernel/delta_net_tree_verify.rs+++ b/crates/backend-uzu/src/backends/common/kernel/delta_net_tree_verify.rs@@ -5,7 +5,7 @@ use crate::{encodable_block::mixer::delta_net::tree_verify::{TreeVerifyEncodeArguments, TreeVerifyNewArguments},};-pub trait DeltaNetTreeVerify<B: Backend<Kernels: Kernels<DeltaNetTreeVerify = Self>>>: Sized {+pub trait DeltaNetTreeVerify<B: Backend<Kernels: Kernels<DeltaNetTreeVerify = Self>>>: Sized + Send + Sync {fn is_supported(context: &B::Context) -> bool;fn new(diff --git a/crates/backend-uzu/src/backends/common/kernel/matmul/kernel.rs b/crates/backend-uzu/src/backends/common/kernel/matmul/kernel.rsindex 7e02d73d4..0c4a6359f 100644--- a/crates/backend-uzu/src/backends/common/kernel/matmul/kernel.rs+++ b/crates/backend-uzu/src/backends/common/kernel/matmul/kernel.rs@@ -3,7 +3,7 @@ use crate::{data_type::DataType,};-pub trait MatmulKernel: Sized {+pub trait MatmulKernel: Sized + Send + Sync {type Backend: Backend<Kernels: Kernels<MatmulKernel = Self>>;fn new(diff --git a/crates/backend-uzu/src/backends/cpu/backend.rs b/crates/backend-uzu/src/backends/cpu/backend.rsindex 71e654465..9da2a5495 100644--- a/crates/backend-uzu/src/backends/cpu/backend.rs+++ b/crates/backend-uzu/src/backends/cpu/backend.rs@@ -1,7 +1,6 @@-use std::{cell::UnsafeCell, pin::Pin};-use super::{- command_buffer::CpuCommandBuffer, context::CpuContext, error::CpuError, kernel::CpuKernels, sparse::CpuSparseBuffer,+ command_buffer::CpuCommandBuffer, context::CpuContext, dense_buffer::CpuBuffer, error::CpuError,+ kernel::CpuKernels, sparse::CpuSparseBuffer,};use crate::backends::common::Backend;@@ -11,7 +10,7 @@ pub struct Cpu;impl Backend for Cpu {type Context = CpuContext;type CommandBuffer = CpuCommandBuffer;- type DenseBuffer = UnsafeCell<Pin<Box<[u8]>>>;+ type DenseBuffer = CpuBuffer;type SparseBuffer = CpuSparseBuffer;type Kernels = CpuKernels;type Error = CpuError;diff --git a/crates/backend-uzu/src/backends/cpu/buffer.rs b/crates/backend-uzu/src/backends/cpu/buffer.rsindex 24a771d95..ff19e3008 100644--- a/crates/backend-uzu/src/backends/cpu/buffer.rs+++ b/crates/backend-uzu/src/backends/cpu/buffer.rs@@ -1,12 +1,12 @@-use std::{any::Any, cell::UnsafeCell, pin::Pin};+use std::any::Any;use crate::backends::{common::{Backend, Buffer},- cpu::Cpu,+ cpu::{Cpu, dense_buffer::CpuBuffer},};impl dyn Buffer<Backend = Cpu> {- pub fn downcast(&self) -> &UnsafeCell<Pin<Box<[u8]>>> {+ pub fn downcast(&self) -> &CpuBuffer {let buffer = self as &dyn Any;if let Some(buffer) = buffer.downcast_ref::<<Cpu as Backend>::DenseBuffer>() {bufferdiff --git a/crates/backend-uzu/src/backends/cpu/context.rs b/crates/backend-uzu/src/backends/cpu/context.rsindex 7541c9797..31203ae91 100644--- a/crates/backend-uzu/src/backends/cpu/context.rs+++ b/crates/backend-uzu/src/backends/cpu/context.rs@@ -1,19 +1,23 @@-use std::{cell::UnsafeCell, path::Path, pin::Pin, rc::Rc, sync::mpsc, thread};+use std::{+ path::Path,+ sync::{Arc, mpsc},+ thread,+};use crate::backends::{common::{Allocation, AllocationPool, AllocationType, Allocator, Backend, Context},- cpu::{Cpu, command_buffer::CpuCommandBufferInitial, error::CpuError},+ cpu::{Cpu, command_buffer::CpuCommandBufferInitial, dense_buffer::CpuBuffer, error::CpuError},};pub struct CpuContext {- allocator: Rc<Allocator<Cpu>>,+ allocator: Arc<Allocator<Cpu>>,command_queue: mpsc::Sender<Box<dyn FnOnce() + Send>>,}impl Context for CpuContext {type Backend = Cpu;- fn new() -> Result<Rc<Self>, CpuError> {+ fn new() -> Result<Arc<Self>, CpuError> {let (command_queue_sender, command_queue_receiever) = mpsc::channel::<Box<dyn FnOnce() + Send>>();thread::spawn(|| {@@ -22,7 +26,7 @@ impl Context for CpuContext {}});- Ok(Rc::new_cyclic(|weak_self| CpuContext {+ Ok(Arc::new_cyclic(|weak_self| CpuContext {allocator: Allocator::new(weak_self.clone()),command_queue: command_queue_sender,}))@@ -31,8 +35,8 @@ impl Context for CpuContext {fn create_buffer(&self,size: usize,- ) -> Result<UnsafeCell<Pin<Box<[u8]>>>, CpuError> {- Ok(UnsafeCell::new(Pin::new(vec![0; size].into_boxed_slice())))+ ) -> Result<CpuBuffer, CpuError> {+ Ok(CpuBuffer::new(size))}fn create_allocation(diff --git a/crates/backend-uzu/src/backends/cpu/dense_buffer.rs b/crates/backend-uzu/src/backends/cpu/dense_buffer.rsindex a285f7b4e..3c4154c5d 100644--- a/crates/backend-uzu/src/backends/cpu/dense_buffer.rs+++ b/crates/backend-uzu/src/backends/cpu/dense_buffer.rs@@ -3,20 +3,40 @@ use std::{cell::UnsafeCell, os::raw::c_void, pin::Pin, ptr::NonNull};use super::Cpu;use crate::backends::common::{Buffer, DenseBuffer};-impl Buffer for UnsafeCell<Pin<Box<[u8]>>> {+#[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.get() }.as_ptr().addr()+ unsafe { &*self.0.get() }.as_ptr().addr()}fn size(&self) -> usize {- unsafe { &*self.get() }.len()+ unsafe { &*self.0.get() }.len()}}-impl DenseBuffer for UnsafeCell<Pin<Box<[u8]>>> {+impl DenseBuffer for CpuBuffer {fn cpu_ptr(&self) -> NonNull<c_void> {- unsafe { NonNull::new_unchecked((&*self.get()).as_ptr() as *mut c_void) }+ unsafe { NonNull::new_unchecked((&*self.0.get()).as_ptr() as *mut c_void) }}}diff --git a/crates/backend-uzu/src/backends/metal/command_buffer.rs b/crates/backend-uzu/src/backends/metal/command_buffer.rsindex 2bf91d8b8..a46c71430 100644--- a/crates/backend-uzu/src/backends/metal/command_buffer.rs+++ b/crates/backend-uzu/src/backends/metal/command_buffer.rs@@ -1,4 +1,4 @@-use std::{rc::Rc, time::Duration};+use std::{sync::Arc, time::Duration};use metal::{MTLBlitCommandEncoder, MTLBlitCommandEncoderExt, MTLCommandBuffer, MTLCommandBufferExt, MTLCommandBufferStatus,@@ -28,13 +28,13 @@ impl CommandBuffer for MetalCommandBuffer {pub struct MetalCommandBufferInitial {command_buffer: Retained<ProtocolObject<dyn MTLCommandBuffer>>,- context: Rc<MetalContext>,+ context: Arc<MetalContext>,}impl MetalCommandBufferInitial {pub fn new(command_buffer: Retained<ProtocolObject<dyn MTLCommandBuffer>>,- context: Rc<MetalContext>,+ context: Arc<MetalContext>,) -> Self {Self {command_buffer,@@ -64,7 +64,7 @@ enum MetalCommandBufferEncodingEncodingState {pub struct MetalCommandBufferEncoding {command_buffer: Retained<ProtocolObject<dyn MTLCommandBuffer>>,encoding_state: MetalCommandBufferEncodingEncodingState,- context: Rc<MetalContext>,+ context: Arc<MetalContext>,}impl MetalCommandBufferEncoding {@@ -169,7 +169,7 @@ impl CommandBufferEncoding for MetalCommandBufferEncoding {pub struct MetalCommandBufferExecutable {command_buffer: Retained<ProtocolObject<dyn MTLCommandBuffer>>,- context: Rc<MetalContext>,+ context: Arc<MetalContext>,}impl CommandBufferExecutable for MetalCommandBufferExecutable {diff --git a/crates/backend-uzu/src/backends/metal/context.rs b/crates/backend-uzu/src/backends/metal/context.rsindex b9871e838..8d0dc33b4 100644--- a/crates/backend-uzu/src/backends/metal/context.rs+++ b/crates/backend-uzu/src/backends/metal/context.rs@@ -1,9 +1,10 @@use std::{- cell::{Ref, RefCell, RefMut},collections::HashMap,path::Path,- rc::{Rc, Weak},- sync::atomic::{AtomicU64, Ordering},+ sync::{+ Arc, Weak,+ atomic::{AtomicU64, AtomicUsize, Ordering},+ },};#[cfg(test)]@@ -14,6 +15,7 @@ use metal::{MTLFunctionConstantValues, MTLLibrary, MTLResourceOptions, MTLSparsePageSize,};use objc2::{rc::Retained, runtime::ProtocolObject};+use parking_lot::{Mutex, MutexGuard};use super::{Metal,@@ -36,11 +38,11 @@ pub struct MetalContext {pub command_queue4: Retained<ProtocolObject<dyn MTL4CommandQueue>>,timeline_event: Retained<ProtocolObject<dyn MTLEvent>>,timeline_value: AtomicU64,- allocator: Rc<Allocator<Metal>>,- peak_memory_usage: RefCell<usize>,+ allocator: Arc<Allocator<Metal>>,+ peak_memory_usage: AtomicUsize,library: Retained<ProtocolObject<dyn MTLLibrary>>,- pipeline_cache: RefCell<HashMap<String, Retained<ProtocolObject<dyn MTLComputePipelineState>>>>,- sparse_heap_pool: RefCell<MetalSparseHeapPool>,+ pipeline_cache: Mutex<HashMap<String, Retained<ProtocolObject<dyn MTLComputePipelineState>>>>,+ sparse_heap_pool: Mutex<MetalSparseHeapPool>,device_tier: DeviceTier,weak_self: Weak<MetalContext>,#[cfg(test)]@@ -57,8 +59,7 @@ impl MetalContext {}pub(super) fn update_peak_memory_usage(&self) {- let mut peak_memory_usage_borrow = self.peak_memory_usage.borrow_mut();- *peak_memory_usage_borrow = peak_memory_usage_borrow.max(self.device.current_allocated_size());+ self.peak_memory_usage.fetch_max(self.device.current_allocated_size(), Ordering::Relaxed);}pub fn compute_pipeline_state(@@ -67,22 +68,18 @@ impl MetalContext {function_name: &str,constants: Option<&MTLFunctionConstantValues>,) -> Result<Retained<ProtocolObject<dyn MTLComputePipelineState>>, MetalError> {- if let Some(pipeline) = self.pipeline_cache.borrow().get(cache_key) {+ if let Some(pipeline) = self.pipeline_cache.lock().get(cache_key) {return Ok(pipeline.clone());}let pipeline = self.library.compute_pipeline_state(function_name, constants)?;- self.pipeline_cache.borrow_mut().insert(cache_key.to_string(), pipeline.clone());+ self.pipeline_cache.lock().insert(cache_key.to_string(), pipeline.clone());Ok(pipeline)}- pub(super) fn sparse_heap_pool(&self) -> Ref<'_, MetalSparseHeapPool> {- self.sparse_heap_pool.borrow()- }-- pub(super) fn sparse_heap_pool_mut(&self) -> RefMut<'_, MetalSparseHeapPool> {- self.sparse_heap_pool.borrow_mut()+ pub(super) fn sparse_heap_pool(&self) -> MutexGuard<'_, MetalSparseHeapPool> {+ self.sparse_heap_pool.lock()}pub(super) fn sparse_update_mappings(@@ -96,7 +93,7 @@ impl MetalContext {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.borrow().heap()), &op.mtl_operations);+ self.command_queue4.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);@@ -117,7 +114,7 @@ impl MetalContext {impl Context for MetalContext {type Backend = Metal;- fn new() -> Result<Rc<Self>, MetalError> {+ fn new() -> Result<Arc<Self>, MetalError> {let device: Retained<ProtocolObject<dyn MTLDevice>> =<dyn MTLDevice>::system_default().ok_or(MetalError::CannotOpenDevice)?;@@ -139,17 +136,17 @@ impl Context for MetalContext {#[cfg(test)]let timeline_shared_event = device.new_shared_event().ok_or(MetalError::CannotCreateEvent)?;- Ok(Rc::new_cyclic(|weak_self| Self {+ Ok(Arc::new_cyclic(|weak_self| Self {device,command_queue,command_queue4,timeline_event,timeline_value: AtomicU64::new(0),allocator: Allocator::new(weak_self.clone()),- peak_memory_usage: RefCell::new(0),+ peak_memory_usage: AtomicUsize::new(0),library,- pipeline_cache: RefCell::new(HashMap::new()),- sparse_heap_pool: RefCell::new(sparse_pool),+ pipeline_cache: Mutex::new(HashMap::new()),+ sparse_heap_pool: Mutex::new(sparse_pool),device_tier,weak_self: weak_self.clone(),#[cfg(test)]@@ -197,13 +194,13 @@ impl Context for MetalContext {&self,capacity: usize,) -> Result<<Self::Backend as Backend>::SparseBuffer, <Self::Backend as Backend>::Error> {- let sparse_page_size = self.sparse_heap_pool.borrow().page_size();+ let sparse_page_size = self.sparse_heap_pool.lock().page_size();let context = self.weak_self.upgrade().ok_or(MetalError::CannotCreateBuffer)?;MetalSparseBuffer::new(context, capacity, sparse_page_size)}fn peak_memory_usage(&self) -> Option<usize> {- Some(*self.peak_memory_usage.borrow())+ Some(self.peak_memory_usage.load(Ordering::Relaxed))}fn enable_capture() {diff --git a/crates/backend-uzu/src/backends/metal/kernel/attention.rs b/crates/backend-uzu/src/backends/metal/kernel/attention.rsindex 46a1864ea..cb48dcffb 100644--- a/crates/backend-uzu/src/backends/metal/kernel/attention.rs+++ b/crates/backend-uzu/src/backends/metal/kernel/attention.rs@@ -1,7 +1,6 @@-use std::{- cell::{RefCell, RefMut},- collections::{HashMap, hash_map::Entry},-};+use std::collections::{HashMap, hash_map::Entry};++use parking_lot::{MappedMutexGuard, Mutex, MutexGuard};use crate::{array::size_for_shape,@@ -14,7 +13,7 @@ use crate::{};pub struct AttentionGemmMetalCore {- kernels: RefCell<HashMap<AttentionGemmKey, AttentionGemmMetalKernel>>,+ kernels: Mutex<HashMap<AttentionGemmKey, AttentionGemmMetalKernel>>,head_dim: usize,num_groups: usize,num_q_heads: usize,@@ -54,8 +53,8 @@ impl AttentionGemmMetalCore {&self,context: &MetalContext,key: AttentionGemmKey,- ) -> Result<RefMut<'_, AttentionGemmMetalKernel>, MetalError> {- let mut kernels = self.kernels.borrow_mut();+ ) -> Result<MappedMutexGuard<'_, AttentionGemmMetalKernel>, MetalError> {+ let mut kernels = self.kernels.lock();if let Entry::Vacant(entry) = kernels.entry(key) {let bk = if key.use_mxu {32@@ -78,7 +77,7 @@ impl AttentionGemmMetalCore {)?;entry.insert(kernel);}- Ok(RefMut::map(kernels, |kernels| kernels.get_mut(&key).expect("kernel was just initialized")))+ Ok(MutexGuard::map(kernels, |kernels| kernels.get_mut(&key).expect("kernel was just initialized")))}}@@ -101,7 +100,7 @@ impl AttentionGemmCore<Metal> for AttentionGemmMetalCore {};Ok(Self {- kernels: RefCell::new(HashMap::new()),+ kernels: Mutex::new(HashMap::new()),head_dim: arguments.head_dim,num_groups: arguments.num_groups,num_q_heads: arguments.num_q_heads,diff --git a/crates/backend-uzu/src/backends/metal/sparse/sparse_buffer.rs b/crates/backend-uzu/src/backends/metal/sparse/sparse_buffer.rsindex 868d71a99..6776a0ff1 100644--- a/crates/backend-uzu/src/backends/metal/sparse/sparse_buffer.rs+++ b/crates/backend-uzu/src/backends/metal/sparse/sparse_buffer.rs@@ -2,7 +2,7 @@ use std::{cmp::{max, min},fmt::Debug,ops::Range,- rc::Rc,+ sync::Arc,};use metal::{MTLBuffer, MTLDeviceExt, MTLResourceOptions, MTLSparsePageSize};@@ -19,13 +19,13 @@ use crate::backends::{pub struct MetalSparseBuffer {buffer: Retained<ProtocolObject<dyn MTLBuffer>>,mapped_pages: RangeSet<usize>,- context: Rc<MetalContext>,+ context: Arc<MetalContext>,page_size: MTLSparsePageSize,}impl MetalSparseBuffer {pub(crate) fn new(- context: Rc<MetalContext>,+ context: Arc<MetalContext>,capacity: usize,page_size: MTLSparsePageSize,) -> Result<Self, MetalError> {@@ -97,10 +97,10 @@ impl SparseBuffer for MetalSparseBuffer {let 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();- context.sparse_heap_pool_mut().ensure_enough_free_pages(context, pages_to_map)?;+ context.sparse_heap_pool().ensure_enough_free_pages(context, pages_to_map)?;for gap in gaps.iter() {- let mut pool = context.sparse_heap_pool_mut();+ let mut pool = context.sparse_heap_pool();let operations = pool.create_map_operations(context, &self.buffer, gap)?;pool.apply_map_operations(&operations);all_batches.extend(operations);@@ -133,7 +133,7 @@ impl SparseBuffer for MetalSparseBuffer {.collect::<Vec<_>>();for mapped_range in mapped_ranges.iter() {let batches = context.sparse_heap_pool().create_unmap_operations(&self.buffer, mapped_range);- context.sparse_heap_pool_mut().apply_map_operations(&batches);+ context.sparse_heap_pool().apply_map_operations(&batches);all_batches.extend(batches);}diff --git a/crates/backend-uzu/src/backends/metal/sparse/sparse_heap_pool.rs b/crates/backend-uzu/src/backends/metal/sparse/sparse_heap_pool.rsindex bdbf8386d..ff6b25487 100644--- a/crates/backend-uzu/src/backends/metal/sparse/sparse_heap_pool.rs+++ b/crates/backend-uzu/src/backends/metal/sparse/sparse_heap_pool.rs@@ -1,12 +1,12 @@use std::{- cell::RefCell,cmp::{max, min},ops::Range,- rc::Rc,+ sync::Arc,};use metal::{MTL4UpdateSparseBufferMappingOperation, MTLBuffer, MTLSparsePageSize, MTLSparseTextureMappingMode};use objc2::{rc::Retained, runtime::ProtocolObject};+use parking_lot::Mutex;use crate::backends::metal::{MetalContext,@@ -16,7 +16,7 @@ use crate::backends::metal::{};pub struct MetalSparseHeapPool {- heaps: Vec<Rc<RefCell<MetalSparseHeap>>>,+ heaps: Vec<Arc<Mutex<MetalSparseHeap>>>,heap_capacity: usize,page_size: MTLSparsePageSize,}@@ -40,7 +40,7 @@ impl MetalSparseHeapPool {) -> Result<(), MetalError> {let mut pages_to_alloc = pages;for heap in self.heaps.iter() {- for free_pages_range in heap.borrow().free_pages().iter() {+ for free_pages_range in heap.lock().free_pages().iter() {pages_to_alloc -= min(free_pages_range.len(), pages_to_alloc);}}@@ -52,7 +52,7 @@ impl MetalSparseHeapPool {for _ in 0..new_heaps_count {let heap = MetalSparseHeap::new(context, self.heap_capacity, self.page_size)?;context.update_peak_memory_usage();- self.heaps.push(Rc::new(RefCell::new(heap)));+ self.heaps.push(Arc::new(Mutex::new(heap)));}Ok(())@@ -70,7 +70,7 @@ impl MetalSparseHeapPool {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.borrow().free_pages().iter() {+ 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());if map_pages_count == 0 {break;@@ -110,7 +110,7 @@ impl MetalSparseHeapPool {for heap in self.heaps.iter() {let mut heap_mtl_operations: Vec<MTL4UpdateSparseBufferMappingOperation> = Vec::new();- for (heap_range, mapping) in heap.borrow().mappings_for(buffer_address) {+ for (heap_range, mapping) in heap.lock().mappings_for(buffer_address) {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);@@ -144,13 +144,13 @@ impl MetalSparseHeapPool {) {for batch in batches.iter() {for sparse_heap in self.heaps.iter() {- if sparse_heap.borrow().heap() == batch.heap.borrow().heap() {- sparse_heap.borrow_mut().apply_mapping_operations(batch);+ if Arc::ptr_eq(sparse_heap, &batch.heap) {+ sparse_heap.lock().apply_mapping_operations(batch);}}}- self.heaps.retain(|heap| !heap.borrow().is_empty());+ self.heaps.retain(|heap| !heap.lock().is_empty());}#[cfg(test)]diff --git a/crates/backend-uzu/src/backends/metal/sparse/sparse_utils.rs b/crates/backend-uzu/src/backends/metal/sparse/sparse_utils.rsindex 5e5fecd4b..370fdbe8d 100644--- a/crates/backend-uzu/src/backends/metal/sparse/sparse_utils.rs+++ b/crates/backend-uzu/src/backends/metal/sparse/sparse_utils.rs@@ -1,7 +1,8 @@-use std::{cell::RefCell, ops::Range, rc::Rc};+use std::{ops::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;@@ -37,6 +38,6 @@ impl MetalSparseHeapBufferMapping {pub(crate) struct MetalSparseMappingOpsBatch {pub buffer: Retained<ProtocolObject<dyn MTLBuffer>>,- pub heap: Rc<RefCell<MetalSparseHeap>>,+ pub heap: Arc<Mutex<MetalSparseHeap>>,pub mtl_operations: Box<[MTL4UpdateSparseBufferMappingOperation]>,}diff --git a/crates/backend-uzu/src/bridge/chat_token_backend.rs b/crates/backend-uzu/src/bridge/chat_token_backend.rsindex cabb0a093..653eefa33 100644--- a/crates/backend-uzu/src/bridge/chat_token_backend.rs+++ b/crates/backend-uzu/src/bridge/chat_token_backend.rs@@ -2,11 +2,12 @@ use std::{any::Any,path::PathBuf,pin::Pin,- sync::MutexGuard,+ sync::Arc,task::{Context, Poll},};use futures::Stream;+use parking_lot::{Mutex, MutexGuard};use shoji::{traits::{State,@@ -28,7 +29,6 @@ use crate::{bridge::{chat_token_state::UzuChatTokenBackendInstanceState,helpers::{error_stream, get_grammar, get_max_context_length, get_sampling_method, get_speculator},- sync_shared::SyncShared,},engine::{Engine,@@ -42,8 +42,8 @@ use crate::{};pub struct UzuChatTokenBackendInstance<B: Backend> {- engine: SyncShared<Engine<B>>,- model: SyncShared<LanguageModel<B>>,+ engine: Arc<Mutex<Engine<B>>>,+ model: Arc<Mutex<LanguageModel<B>>>,config: ChatConfig,tokenizer: Tokenizer,stop_token_ids: Vec<i32>,@@ -72,8 +72,8 @@ impl<B: Backend> UzuChatTokenBackendInstance<B> {let max_context_length = get_max_context_length(&model, config.context_length.clone());Ok(Self {- engine: SyncShared::new(engine),- model: SyncShared::new(model),+ engine: Arc::new(Mutex::new(engine)),+ model: Arc::new(Mutex::new(model)),config,tokenizer: tokenizer.clone(),stop_token_ids,@@ -91,7 +91,7 @@ impl<B: Backend> BackendInstance for UzuChatTokenBackendInstance<B> {fn state(&self) -> Pin<Box<dyn Future<Output = Result<Box<dyn State>, BackendError>> + Send + '_>> {Box::pin(async move {- let model = self.model.lock().map_err(|err| BackendError::from(err.to_string()))?;+ let model = self.model.lock();let max_context_length = get_max_context_length(&model, self.config.context_length.clone());model.create_empty_state(max_context_length)@@ -114,11 +114,11 @@ impl<B: Backend> BackendInstance for UzuChatTokenBackendInstance<B> {>,> {let model = self.model.clone();- let model_guard = Box::pin(model.lock().unwrap());+ let model_guard = Box::pin(model.lock());let state =(state as &mut dyn Any).downcast_mut::<UzuChatTokenBackendInstanceState<B>>().unwrap().value.clone();- let mut state_guard = Box::pin(state.lock().unwrap());+ let mut state_guard = Box::pin(state.lock());let token_limit = config.token_limit.map(|count| count as usize);@@ -173,7 +173,7 @@ impl<B: Backend> BackendInstance for UzuChatTokenBackendInstance<B> {}fn peak_memory_usage(&self) -> Option<usize> {- self.engine.lock().ok().and_then(|engine| engine.peak_memory_usage())+ self.engine.lock().peak_memory_usage()}}@@ -195,9 +195,9 @@ struct UzuChatTokenStream<'a, B: Backend> {tokens_generated: usize,token_limit: Option<usize>,_state_guard: Pin<Box<MutexGuard<'a, LanguageModelState<B>>>>,- _state: SyncShared<LanguageModelState<B>>,+ _state: Arc<Mutex<LanguageModelState<B>>>,_model_guard: Pin<Box<MutexGuard<'a, LanguageModel<B>>>>,- _model: SyncShared<LanguageModel<B>>,+ _model: Arc<Mutex<LanguageModel<B>>>,}impl<'a, B: Backend> UzuChatTokenStream<'a, B> {@@ -248,5 +248,3 @@ impl<'a, B: Backend> InstanceStream for UzuChatTokenStream<'a, B> {Some(self.stream.metrics().clone())}}--unsafe impl<'a, B: Backend> Send for UzuChatTokenStream<'a, B> {}diff --git a/crates/backend-uzu/src/bridge/chat_token_state.rs b/crates/backend-uzu/src/bridge/chat_token_state.rsindex 0b5caa52f..855d35a29 100644--- a/crates/backend-uzu/src/bridge/chat_token_state.rs+++ b/crates/backend-uzu/src/bridge/chat_token_state.rs@@ -1,17 +1,18 @@+use std::sync::Arc;++use parking_lot::Mutex;use shoji::traits::State as LlmInstanceState;-use crate::{- backends::common::Backend, bridge::sync_shared::SyncShared, engine::language_model::state::LanguageModelState,-};+use crate::{backends::common::Backend, engine::language_model::state::LanguageModelState};pub struct UzuChatTokenBackendInstanceState<B: Backend> {- pub value: SyncShared<LanguageModelState<B>>,+ pub value: Arc<Mutex<LanguageModelState<B>>>,}impl<B: Backend> UzuChatTokenBackendInstanceState<B> {pub fn new(value: LanguageModelState<B>) -> Self {Self {- value: SyncShared::new(value),+ value: Arc::new(Mutex::new(value)),}}}diff --git a/crates/backend-uzu/src/bridge/classification_backend.rs b/crates/backend-uzu/src/bridge/classification_backend.rsindex 18d0cff79..c516bd694 100644--- a/crates/backend-uzu/src/bridge/classification_backend.rs+++ b/crates/backend-uzu/src/bridge/classification_backend.rs@@ -1,6 +1,7 @@-use std::{path::PathBuf, pin::Pin};+use std::{path::PathBuf, pin::Pin, sync::Arc};use futures::{StreamExt, stream};+use parking_lot::Mutex;use shoji::traits::{State as ShojiState,backend::{@@ -15,12 +16,11 @@ use tokio_util::sync::CancellationToken;use crate::{backends::common::Backend,- bridge::sync_shared::SyncShared,engine::{Engine, classifier_model::ClassifierModel},};pub struct UzuClassificationBackendInstance<B: Backend> {- model: SyncShared<ClassifierModel<B>>,+ model: Arc<Mutex<ClassifierModel<B>>>,}impl<B: Backend> UzuClassificationBackendInstance<B> {@@ -29,7 +29,7 @@ impl<B: Backend> UzuClassificationBackendInstance<B> {let model_path = PathBuf::from(model_path);let model = engine.load_classifier_model(&model_path).map_err(|err| err.to_string())?;Ok(Self {- model: SyncShared::new(model),+ model: Arc::new(Mutex::new(model)),})}}@@ -59,7 +59,7 @@ impl<B: Backend> BackendInstance for UzuClassificationBackendInstance<B> {> {Box::pin(NoMetricsStream::new(stream::once(async move {- let model_guard = self.model.lock().map_err(|err| err.to_string())?;+ let model_guard = self.model.lock();model_guard.classify(input).map_err(|err| BackendError::from(err.to_string()))}).take_until(cancel_token.cancelled_owned()),diff --git a/crates/backend-uzu/src/bridge/mod.rs b/crates/backend-uzu/src/bridge/mod.rsindex 78539ab9b..3bcbc87e5 100644--- a/crates/backend-uzu/src/bridge/mod.rs+++ b/crates/backend-uzu/src/bridge/mod.rs@@ -4,7 +4,6 @@ mod chat_token_state;mod classification_backend;mod helpers;mod model_metadata;-mod sync_shared;pub use backend::UzuLlmBackend;pub use model_metadata::resolve_model_specialization;diff --git a/crates/backend-uzu/src/bridge/sync_shared.rs b/crates/backend-uzu/src/bridge/sync_shared.rsdeleted file mode 100644index 6227cb241..000000000--- a/crates/backend-uzu/src/bridge/sync_shared.rs+++ /dev/null@@ -1,29 +0,0 @@-use std::sync::{Arc, LockResult, Mutex, MutexGuard};--pub struct SyncShared<T> {- value: Arc<Mutex<T>>,-}--impl<T> SyncShared<T> {- pub fn new(value: T) -> Self {- Self {- value: Arc::new(Mutex::new(value)),- }- }-- pub fn lock(&self) -> LockResult<MutexGuard<'_, T>> {- self.value.lock()- }-}--impl<T> Clone for SyncShared<T> {- fn clone(&self) -> Self {- Self {- value: self.value.clone(),- }- }-}--unsafe impl<T> Send for SyncShared<T> {}--unsafe impl<T> Sync for SyncShared<T> {}diff --git a/crates/backend-uzu/src/encodable_block/embedding.rs b/crates/backend-uzu/src/encodable_block/embedding.rsindex 51564462c..ae7f9790d 100644--- a/crates/backend-uzu/src/encodable_block/embedding.rs+++ b/crates/backend-uzu/src/encodable_block/embedding.rs@@ -1,5 +1,4 @@-use std::cell::RefCell;-+use parking_lot::Mutex;use thiserror::Error;use crate::{@@ -46,7 +45,7 @@ enum TiedEmbeddingType<B: Backend> {FullPrecision {weights: Allocation<B>,lookup: <B::Kernels as Kernels>::FullPrecisionEmbeddingLookupKernel,- readout: RefCell<<B::Kernels as Kernels>::MatmulKernel>,+ readout: Mutex<<B::Kernels as Kernels>::MatmulKernel>,},Quantized {weights: Allocation<B>,@@ -55,7 +54,7 @@ enum TiedEmbeddingType<B: Backend> {quantization_method: QuantizationMethod,output_hadamard_factors: Option<Allocation<B>>,lookup: <B::Kernels as Kernels>::QuantizedEmbeddingLookupKernel,- readout: RefCell<<B::Kernels as Kernels>::MatmulKernel>,+ readout: Mutex<<B::Kernels as Kernels>::MatmulKernel>,readout_config: ReadoutQuantConfig,},}@@ -78,13 +77,13 @@ enum UntiedEmbeddingLookupType<B: Backend> {enum UntiedEmbeddingReadoutType<B: Backend> {FullPrecision {weights: Allocation<B>,- readout: RefCell<<B::Kernels as Kernels>::MatmulKernel>,+ readout: Mutex<<B::Kernels as Kernels>::MatmulKernel>,},Quantized {weights: Allocation<B>,scales: Allocation<B>,zero_points_or_biases: Option<Allocation<B>>,- readout: RefCell<<B::Kernels as Kernels>::MatmulKernel>,+ readout: Mutex<<B::Kernels as Kernels>::MatmulKernel>,readout_config: ReadoutQuantConfig,},}@@ -145,7 +144,7 @@ impl<B: Backend> Embedding<B> {let readout_kernel =<B::Kernels as Kernels>::MatmulKernel::new(context, data_type, data_type, data_type).map_err(EmbeddingError::BackendError)?;- let readout = RefCell::new(readout_kernel);+ let readout = Mutex::new(readout_kernel);(TiedEmbeddingType::FullPrecision {@@ -347,7 +346,7 @@ impl<B: Backend> Embedding<B> {let readout_kernel =<B::Kernels as Kernels>::MatmulKernel::new(context, data_type, data_type, data_type).map_err(EmbeddingError::BackendError)?;- let readout = RefCell::new(readout_kernel);+ let readout = Mutex::new(readout_kernel);UntiedEmbeddingReadoutType::FullPrecision {weights,@@ -536,7 +535,7 @@ impl<B: Backend> Embedding<B> {},} => {readout- .borrow_mut()+ .lock().encode(MatmulArguments {a: input_allocation,@@ -605,7 +604,7 @@ impl<B: Backend> Embedding<B> {},};readout- .borrow_mut()+ .lock().encode(MatmulArguments {a: input_allocation,@@ -753,11 +752,11 @@ fn quantized_readout<B: Backend>(mode: QuantizationMode,method: QuantizationMethod,group_size: usize,-) -> Result<(RefCell<<B::Kernels as Kernels>::MatmulKernel>, ReadoutQuantConfig), EmbeddingError<B>> {+) -> Result<(Mutex<<B::Kernels as Kernels>::MatmulKernel>, ReadoutQuantConfig), EmbeddingError<B>> {let readout = <B::Kernels as Kernels>::MatmulKernel::new(context, data_type, data_type, data_type).map_err(EmbeddingError::BackendError)?;Ok((- RefCell::new(readout),+ Mutex::new(readout),ReadoutQuantConfig {method,mode,diff --git a/crates/backend-uzu/src/encodable_block/linear/matmul.rs b/crates/backend-uzu/src/encodable_block/linear/matmul.rsindex 2960e5fad..9ddacb2f6 100644--- a/crates/backend-uzu/src/encodable_block/linear/matmul.rs+++ b/crates/backend-uzu/src/encodable_block/linear/matmul.rs@@ -1,5 +1,4 @@-use std::cell::RefCell;-+use parking_lot::Mutex;use thiserror::Error;use crate::{@@ -43,7 +42,7 @@ enum Mode<B: Backend> {}pub struct LinearMatmul<B: Backend> {- kernel: RefCell<<B::Kernels as Kernels>::MatmulKernel>,+ kernel: Mutex<<B::Kernels as Kernels>::MatmulKernel>,weights: Allocation<B>,biases: Option<Allocation<B>>,input_dim: usize,@@ -81,7 +80,7 @@ impl<B: Backend> LinearMatmul<B> {.map_err(LinearMatmulError::BackendError)?;Ok(Self {- kernel: RefCell::new(kernel),+ kernel: Mutex::new(kernel),weights,biases,input_dim,@@ -175,7 +174,7 @@ impl<B: Backend> LinearMatmul<B> {.map_err(LinearMatmulError::BackendError)?;Ok(Self {- kernel: RefCell::new(kernel),+ kernel: Mutex::new(kernel),weights,biases,input_dim,@@ -270,7 +269,7 @@ impl<B: Backend> Linear<B> for LinearMatmul<B> {rht_factors,};- self.kernel.borrow_mut().encode(+ self.kernel.lock().encode(MatmulArguments {a: &input,a_offset: 0,diff --git a/crates/backend-uzu/src/encodable_block/linear/mod.rs b/crates/backend-uzu/src/encodable_block/linear/mod.rsindex dabd877fe..009999b64 100644--- a/crates/backend-uzu/src/encodable_block/linear/mod.rs+++ b/crates/backend-uzu/src/encodable_block/linear/mod.rs@@ -18,7 +18,7 @@ use crate::{parameters::{ParameterLoaderError, ParameterTree},};-pub trait Linear<B: Backend> {+pub trait Linear<B: Backend>: Send + Sync {fn encode(&self,input: Allocation<B>,diff --git a/crates/backend-uzu/src/encodable_block/linear/qlora_wrapper.rs b/crates/backend-uzu/src/encodable_block/linear/qlora_wrapper.rsindex 41475d5ec..b194b5d9b 100644--- a/crates/backend-uzu/src/encodable_block/linear/qlora_wrapper.rs+++ b/crates/backend-uzu/src/encodable_block/linear/qlora_wrapper.rs@@ -1,5 +1,4 @@-use std::cell::RefCell;-+use parking_lot::Mutex;use thiserror::Error;use crate::{@@ -34,8 +33,8 @@ pub struct QLoRALinearWrapper<B: Backend> {base_linear: LinearMatmul<B>,input_hadamard: Option<(<B::Kernels as Kernels>::HadamardTransformKernel, Allocation<B>)>,output_hadamard: Option<(<B::Kernels as Kernels>::HadamardTransformKernel, Allocation<B>)>,- adapter_down_kernel: RefCell<<B::Kernels as Kernels>::MatmulKernel>,- adapter_up_kernel: RefCell<<B::Kernels as Kernels>::MatmulKernel>,+ 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>,input_dim: usize,@@ -116,7 +115,7 @@ impl<B: Backend> QLoRALinearWrapper<B> {(None, None)};- let adapter_down_kernel = RefCell::new(+ let adapter_down_kernel = Mutex::new(<<B::Kernels as Kernels>::MatmulKernel as MatmulKernel>::new(context,weights_data_type,@@ -125,7 +124,7 @@ impl<B: Backend> QLoRALinearWrapper<B> {).map_err(QLoRALinearWrapperError::BackendError)?,);- let adapter_up_kernel = RefCell::new(+ let adapter_up_kernel = Mutex::new(<<B::Kernels as Kernels>::MatmulKernel as MatmulKernel>::new(context,weights_data_type,@@ -173,7 +172,7 @@ impl<B: Backend> Linear<B> for QLoRALinearWrapper<B> {encoder.allocate_scratch(size_for_shape(&[batch_dim, self.lora_rank], self.weights_data_type))?;{- let mut adapter_kernel = self.adapter_down_kernel.borrow_mut();+ let mut adapter_kernel = self.adapter_down_kernel.lock();adapter_kernel.encode(MatmulArguments {a: &input,@@ -212,7 +211,7 @@ impl<B: Backend> Linear<B> for QLoRALinearWrapper<B> {let mut output = self.base_linear.encode(base_input, batch_dim, encoder)?;{- let mut adapter_kernel = self.adapter_up_kernel.borrow_mut();+ let mut adapter_kernel = self.adapter_up_kernel.lock();adapter_kernel.encode(MatmulArguments {a: &intermediate,diff --git a/crates/backend-uzu/src/encodable_block/mixer/attention/core/fallback.rs b/crates/backend-uzu/src/encodable_block/mixer/attention/core/fallback.rsindex ef05bcc7a..38a0db774 100644--- a/crates/backend-uzu/src/encodable_block/mixer/attention/core/fallback.rs+++ b/crates/backend-uzu/src/encodable_block/mixer/attention/core/fallback.rs@@ -1,4 +1,4 @@-use std::cell::RefCell;+use parking_lot::Mutex;use crate::{array::size_for_shape,@@ -23,7 +23,7 @@ pub struct AttentionFallbackCore<B: Backend> {scatter_scores: <B::Kernels as Kernels>::AttentionFallbackScatterScoresKernel,scatter_values: <B::Kernels as Kernels>::AttentionFallbackScatterValuesKernel,softmax: <B::Kernels as Kernels>::SoftmaxKernel,- matmul: RefCell<<B::Kernels as Kernels>::MatmulKernel>,+ matmul: Mutex<<B::Kernels as Kernels>::MatmulKernel>,}impl<B: Backend> AttentionFallbackCore<B> {@@ -44,7 +44,7 @@ impl<B: Backend> AttentionFallbackCore<B> {let scatter_values =<B::Kernels as Kernels>::AttentionFallbackScatterValuesKernel::new(context, arguments.data_type)?;let softmax = <B::Kernels as Kernels>::SoftmaxKernel::new(context, arguments.data_type, arguments.has_sinks)?;- let matmul = RefCell::new(<B::Kernels as Kernels>::MatmulKernel::new(+ let matmul = Mutex::new(<B::Kernels as Kernels>::MatmulKernel::new(context,arguments.data_type,arguments.data_type,@@ -89,7 +89,7 @@ impl<B: Backend> AttentionFallbackCore<B> {))?;for group_index in 0..self.num_groups {- self.matmul.borrow_mut().encode(+ self.matmul.lock().encode(MatmulArguments {a: arguments.queries,a_offset: group_index * gqa_factor * arguments.suffix_length * self.head_dim * dt_bytes,@@ -139,7 +139,7 @@ impl<B: Backend> AttentionFallbackCore<B> {.allocate_scratch(size_for_shape(&[gqa_factor * arguments.suffix_length, self.head_dim], self.data_type))?;for group_index in 0..self.num_groups {- self.matmul.borrow_mut().encode(+ self.matmul.lock().encode(MatmulArguments {a: &scores,a_offset: group_index * gqa_factor * arguments.suffix_length * sequence_length * dt_bytes,diff --git a/crates/backend-uzu/src/encodable_block/mixer/mod.rs b/crates/backend-uzu/src/encodable_block/mixer/mod.rsindex fd73c1360..ba2e3b555 100644--- a/crates/backend-uzu/src/encodable_block/mixer/mod.rs+++ b/crates/backend-uzu/src/encodable_block/mixer/mod.rs@@ -24,7 +24,7 @@ pub mod delta_net;pub mod mamba2;pub mod short_conv;-pub trait MixerState<B: Backend>: Any {+pub trait MixerState<B: Backend>: Any + Send {fn prepare(&mut self,context_length: usize,@@ -48,7 +48,7 @@ impl<'a, B: Backend> MaybeMut<'a, dyn MixerState<B>> {}}-pub trait Mixer<B: Backend> {+pub trait Mixer<B: Backend>: Send + Sync {fn speculation_supported(&self) -> bool;fn max_context_length(&self) -> Option<usize>;diff --git a/crates/backend-uzu/src/encodable_block/mlp/mod.rs b/crates/backend-uzu/src/encodable_block/mlp/mod.rsindex 37c76fbb0..6ec605081 100644--- a/crates/backend-uzu/src/encodable_block/mlp/mod.rs+++ b/crates/backend-uzu/src/encodable_block/mlp/mod.rs@@ -15,7 +15,7 @@ use crate::{parameters::{ParameterLoaderError, ParameterTree},};-pub trait Mlp<B: Backend> {+pub trait Mlp<B: Backend>: Send + Sync {fn encode(&self,input: Allocation<B>,diff --git a/crates/backend-uzu/src/encodable_block/sampling/mod.rs b/crates/backend-uzu/src/encodable_block/sampling/mod.rsindex 0932ed8df..01cd80bfa 100644--- a/crates/backend-uzu/src/encodable_block/sampling/mod.rs+++ b/crates/backend-uzu/src/encodable_block/sampling/mod.rs@@ -1,10 +1,11 @@use std::{- cell::RefCell,collections::{HashMap, hash_map::Entry},mem::size_of,ops::Range,};+use parking_lot::Mutex;+use crate::{backends::common::{Allocation, AllocationType, AsBufferRangeRef, Backend, Context, Encoder, Kernels,@@ -23,7 +24,7 @@ pub use prng::PRng;pub struct Sampling<B: Backend> {vocab_size: usize,data_type: DataType,- unified_kernels: RefCell<HashMap<UnifiedSamplingKey, <B::Kernels as Kernels>::UnifiedSamplingKernel>>,+ unified_kernels: Mutex<HashMap<UnifiedSamplingKey, <B::Kernels as Kernels>::UnifiedSamplingKernel>>,}impl<B: Backend> Sampling<B> {@@ -34,7 +35,7 @@ impl<B: Backend> Sampling<B> {Self {vocab_size,data_type,- unified_kernels: RefCell::new(HashMap::new()),+ unified_kernels: Mutex::new(HashMap::new()),}}}@@ -143,7 +144,7 @@ impl<B: Backend> Sampling<B> {};let logits = penalized_logits.as_ref().unwrap_or(logits);- let mut unified_kernels = self.unified_kernels.borrow_mut();+ let mut unified_kernels = self.unified_kernels.lock();let entry = unified_kernels.entry(key);let kernel = match entry {Entry::Occupied(occupied) => occupied.into_mut(),diff --git a/crates/backend-uzu/src/engine/classifier_model.rs b/crates/backend-uzu/src/engine/classifier_model.rsindex 478e82945..4073cd254 100644--- a/crates/backend-uzu/src/engine/classifier_model.rs+++ b/crates/backend-uzu/src/engine/classifier_model.rs@@ -4,7 +4,7 @@ use std::{fs::File,io::{self, BufReader},path::Path,- rc::Rc,+ sync::Arc,};use half::bf16;@@ -21,7 +21,7 @@ use crate::{};pub struct ClassifierModel<B: Backend> {- context: Rc<B::Context>,+ context: Arc<B::Context>,classifier: ClassifierEncodable<B>,output_labels: Box<[String]>,data_type: DataType,diff --git a/crates/backend-uzu/src/engine/language_model/grammar/mod.rs b/crates/backend-uzu/src/engine/language_model/grammar/mod.rsindex 85257a32e..a59fc0fce 100644--- a/crates/backend-uzu/src/engine/language_model/grammar/mod.rs+++ b/crates/backend-uzu/src/engine/language_model/grammar/mod.rs@@ -108,7 +108,7 @@ pub struct NoGrammarBackend;// TODO: jumpforward?-pub trait Grammar {+pub trait Grammar: Send {fn next_bitmask(&mut self,bitmask: &mut [u32],diff --git a/crates/backend-uzu/src/engine/language_model/grammar/xgrammar.rs b/crates/backend-uzu/src/engine/language_model/grammar/xgrammar.rsindex f47e99dd9..99fa5715a 100644--- a/crates/backend-uzu/src/engine/language_model/grammar/xgrammar.rs+++ b/crates/backend-uzu/src/engine/language_model/grammar/xgrammar.rs@@ -115,6 +115,7 @@ impl XGrammar {*strict_mode,None,false,+ false,).map_err(XGrammarError::XGrammar)?},diff --git a/crates/backend-uzu/src/engine/language_model/mod.rs b/crates/backend-uzu/src/engine/language_model/mod.rsindex f8d59c340..4f9f0835c 100644--- a/crates/backend-uzu/src/engine/language_model/mod.rs+++ b/crates/backend-uzu/src/engine/language_model/mod.rs@@ -1,4 +1,4 @@-use std::{fs::File, io, io::BufReader, path::Path, rc::Rc};+use std::{fs::File, io, io::BufReader, path::Path, sync::Arc};use thiserror::Error;@@ -22,7 +22,7 @@ pub mod state;pub mod stream;pub struct LanguageModel<B: Backend> {- context: Rc<B::Context>,+ context: Arc<B::Context>,decoder: Decoder<B>,sampling: Sampling<B>,token_copy: <B::Kernels as Kernels>::TokenCopySampledKernel,diff --git a/crates/backend-uzu/src/engine/language_model/stream/stream.rs b/crates/backend-uzu/src/engine/language_model/stream/stream.rsindex d9f6b590d..a2a9da7ab 100644--- a/crates/backend-uzu/src/engine/language_model/stream/stream.rs+++ b/crates/backend-uzu/src/engine/language_model/stream/stream.rs@@ -1,7 +1,7 @@use std::{iter::{once, repeat_n},mem::replace,- rc::Rc,+ sync::Arc,};use shoji::traits::backend::chat_token::TokenStreamMetrics;@@ -92,7 +92,7 @@ pub struct LanguageModelStream<'a, B: Backend> {model: &'a LanguageModel<B>,model_state: &'a mut LanguageModelState<B>,options: LanguageModelStreamOptions<'a>,- allocation_pool: Rc<AllocationPool<B>>,+ allocation_pool: Arc<AllocationPool<B>>,context_ring: Option<Allocation<B>>,decoding_state: DecodingState<B>,metrics: TokenStreamMetrics,@@ -120,7 +120,7 @@ impl<'a, B: Backend> LanguageModelStream<'a, B> {return Err(LanguageModelStreamError::ContextOverflow);}- let allocation_pool = Rc::new(model.context.create_allocation_pool(false));+ let allocation_pool = Arc::new(model.context.create_allocation_pool(false));let mut context_ring =if let Some(suffix_repetition_length) = options.sampling_method.suffix_repetition_length() {@@ -628,5 +628,3 @@ impl<'a, B: Backend> Drop for LanguageModelStream<'a, B> {self.model_state.last_output_token = last_output_token;}}--unsafe impl<'a, B: Backend> Send for LanguageModelStream<'a, B> {} // TODO: this should be done properlydiff --git a/crates/backend-uzu/src/engine/mod.rs b/crates/backend-uzu/src/engine/mod.rsindex 7c514ef52..b8cc6667a 100644--- a/crates/backend-uzu/src/engine/mod.rs+++ b/crates/backend-uzu/src/engine/mod.rs@@ -1,4 +1,4 @@-use std::rc::Rc;+use std::sync::Arc;use thiserror::Error;@@ -9,7 +9,7 @@ pub mod dflash_speculator;pub mod language_model;pub struct Engine<B: Backend> {- context: Rc<B::Context>,+ context: Arc<B::Context>,}#[derive(Debug, Error)]diff --git a/crates/backend-uzu/src/tests/helpers.rs b/crates/backend-uzu/src/tests/helpers.rsindex fa489d58b..6c446a31c 100644--- a/crates/backend-uzu/src/tests/helpers.rs+++ b/crates/backend-uzu/src/tests/helpers.rs@@ -1,4 +1,4 @@-use std::{mem::size_of, rc::Rc};+use std::{mem::size_of, sync::Arc};use crate::{array::ArrayElement,@@ -62,7 +62,7 @@ pub fn write_allocation<B: Backend, T: ArrayElement>(destination[..bytes.len()].copy_from_slice(bytes);}-pub fn create_context<B: Backend>() -> Rc<<B as Backend>::Context> {+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>()))}diff --git a/crates/backend-uzu/src/tests/mod.rs b/crates/backend-uzu/src/tests/mod.rsindex f3bec61b5..3a8f30611 100644--- a/crates/backend-uzu/src/tests/mod.rs+++ b/crates/backend-uzu/src/tests/mod.rs@@ -1,5 +1,5 @@#![cfg(test)]-#![allow(dead_code, unused_imports, unused_macros)]+#![allow(dead_code)]pub extern crate test;diff --git a/crates/backend-uzu/src/tests/proptest.rs b/crates/backend-uzu/src/tests/proptest.rsindex a34939191..23fea6d07 100644--- a/crates/backend-uzu/src/tests/proptest.rs+++ b/crates/backend-uzu/src/tests/proptest.rs@@ -1,4 +1,4 @@-use std::rc::Rc;+use std::sync::Arc;use proptest::prelude::*;@@ -17,9 +17,9 @@ pub fn kernel_data_type() -> impl Strategy<Value = DataType> {}pub struct TestContextes {- pub cpu: Rc<<Cpu as Backend>::Context>,+ pub cpu: Arc<<Cpu as Backend>::Context>,#[cfg(metal_backend)]- pub metal: Rc<<Metal as Backend>::Context>,+ pub metal: Arc<<Metal as Backend>::Context>,}impl TestContextes {diff --git a/crates/backend-uzu/src/tests/util.rs b/crates/backend-uzu/src/tests/util.rsindex 904e22ea6..e757dc02a 100644--- a/crates/backend-uzu/src/tests/util.rs+++ b/crates/backend-uzu/src/tests/util.rs@@ -1,10 +1,13 @@-use test_runner::env_vars;+#[cfg(metal_backend)]+use std::{cell::OnceCell, sync::Arc};++#[cfg(metal_backend)]+use crate::backends::{common::Context, metal::MetalContext};#[cfg(metal_backend)]-pub fn shared_metal_context() -> std::rc::Rc<crate::backends::metal::MetalContext> {- use crate::backends::{common::Context, metal::MetalContext};+pub fn shared_metal_context() -> Arc<MetalContext> {thread_local! {- static CTX: std::cell::OnceCell<std::rc::Rc<MetalContext>> = const { std::cell::OnceCell::new() };+ static CTX: OnceCell<Arc<MetalContext>> = const { OnceCell::new() };}CTX.with(|cell| cell.get_or_init(|| MetalContext::new().expect("Metal context")).clone())}diff --git a/crates/backend-uzu/unit/backends/common/allocator/allocator.rs b/crates/backend-uzu/unit/backends/common/allocator/allocator.rsindex a9d00f340..e7e193182 100644--- a/crates/backend-uzu/unit/backends/common/allocator/allocator.rs+++ b/crates/backend-uzu/unit/backends/common/allocator/allocator.rs@@ -2,7 +2,7 @@ use std::{collections::{HashMap, hash_map::Entry},fs::File,io::BufReader,- rc::Rc,+ sync::Arc,time::Instant,};@@ -60,7 +60,7 @@ fn bench_allocator_generation_trace() {let context = <<Metal as Backend>::Context as Context>::new().unwrap();- let mut allocators: HashMap<usize, Rc<Allocator<Metal>>> = HashMap::new();+ 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();@@ -73,7 +73,7 @@ fn bench_allocator_generation_trace() {panic!("Duplicate allocator id: {}", event.allocator_id);};- vacant.insert(Allocator::new(Rc::downgrade(&context)));+ vacant.insert(Allocator::new(Arc::downgrade(&context)));},TraceEventType::CreatePool {reusable,