Skip to content

armgit / uzu

Public Imported from GitHub
0

A high-performance inference engine for AI models

Remove event (#431)

Aleksandr Golokoz26d23f9073f5
diff --git a/crates/backend-uzu/src/backends/common/backend.rs b/crates/backend-uzu/src/backends/common/backend.rs
index 3bb337516..e8f8ab550 100644
--- a/crates/backend-uzu/src/backends/common/backend.rs
+++ b/crates/backend-uzu/src/backends/common/backend.rs
@@ -1,13 +1,12 @@
use std::{error::Error, fmt::Debug};
-use super::{CommandBuffer, Context, DenseBuffer, Event, Kernels, SparseBuffer, kernel::ManualKernels};
+use super::{CommandBuffer, Context, DenseBuffer, Kernels, SparseBuffer, kernel::ManualKernels};
pub trait Backend: Debug + Clone + 'static {
type Context: Context<Backend = Self>;
type CommandBuffer: CommandBuffer<Backend = Self>;
type DenseBuffer: DenseBuffer<Backend = Self>;
type SparseBuffer: SparseBuffer<Backend = Self>;
- type Event: Event<Backend = Self>;
type Kernels: Kernels<Backend = Self> + ManualKernels;
type Error: Error + Debug;
diff --git a/crates/backend-uzu/src/backends/common/command_buffer.rs b/crates/backend-uzu/src/backends/common/command_buffer.rs
index 7d6f9dd25..2702dbdb7 100644
--- a/crates/backend-uzu/src/backends/common/command_buffer.rs
+++ b/crates/backend-uzu/src/backends/common/command_buffer.rs
@@ -88,18 +88,6 @@ pub trait CommandBufferEncoding {
before: AccessFlags,
);
- fn encode_wait_for_event(
- &mut self,
- event: &<<Self::CommandBuffer as CommandBuffer>::Backend as Backend>::Event,
- value: u64,
- );
-
- fn encode_signal_event(
- &mut self,
- event: &<<Self::CommandBuffer as CommandBuffer>::Backend as Backend>::Event,
- value: u64,
- );
-
fn add_completion_handler(
&mut self,
handler: impl FnOnce(
diff --git a/crates/backend-uzu/src/backends/common/context.rs b/crates/backend-uzu/src/backends/common/context.rs
index 22901dd27..8c2d47326 100644
--- a/crates/backend-uzu/src/backends/common/context.rs
+++ b/crates/backend-uzu/src/backends/common/context.rs
@@ -36,8 +36,6 @@ pub trait Context: Sized {
reusable: bool,
) -> AllocationPool<Self::Backend>;
- fn create_event(&self) -> Result<<Self::Backend as Backend>::Event, <Self::Backend as Backend>::Error>;
-
fn create_sparse_buffer(
&self,
capacity: usize,
diff --git a/crates/backend-uzu/src/backends/common/encoder.rs b/crates/backend-uzu/src/backends/common/encoder.rs
index 25018ebd9..a791ab952 100644
--- a/crates/backend-uzu/src/backends/common/encoder.rs
+++ b/crates/backend-uzu/src/backends/common/encoder.rs
@@ -131,22 +131,6 @@ impl<'encoding, B: Backend> Encoder<'encoding, B> {
}
}
- pub fn encode_wait_for_event(
- &mut self,
- event: &B::Event,
- value: u64,
- ) {
- self.command_buffer.encode_wait_for_event(event, value);
- }
-
- pub fn encode_signal_event(
- &mut self,
- event: &B::Event,
- value: u64,
- ) {
- self.command_buffer.encode_signal_event(event, value);
- }
-
pub fn add_completion_handler(
&mut self,
handler: impl FnOnce(Result<&<B::CommandBuffer as CommandBuffer>::Completed, B::Error>) + Send + 'static,
diff --git a/crates/backend-uzu/src/backends/common/event.rs b/crates/backend-uzu/src/backends/common/event.rs
deleted file mode 100644
index 776b143cb..000000000
--- a/crates/backend-uzu/src/backends/common/event.rs
+++ /dev/null
@@ -1,5 +0,0 @@
-use super::Backend;
-
-pub trait Event {
- type Backend: Backend<Event = Self>;
-}
diff --git a/crates/backend-uzu/src/backends/common/mod.rs b/crates/backend-uzu/src/backends/common/mod.rs
index e0a2de665..e25acdfc9 100644
--- a/crates/backend-uzu/src/backends/common/mod.rs
+++ b/crates/backend-uzu/src/backends/common/mod.rs
@@ -8,7 +8,6 @@ mod command_buffer;
mod context;
mod dense_buffer;
mod encoder;
-mod event;
pub mod gpu_types;
mod hazard_tracker;
pub mod kernel;
@@ -29,7 +28,6 @@ pub use command_buffer::{
pub use context::Context;
pub use dense_buffer::DenseBuffer;
pub use encoder::{Completed, Encoder, Executable, Pending};
-pub use event::Event;
pub use hazard_tracker::Access;
pub use kernel::Kernels;
pub use sparse_buffer::SparseBuffer;
diff --git a/crates/backend-uzu/src/backends/cpu/backend.rs b/crates/backend-uzu/src/backends/cpu/backend.rs
index aeb1caa63..d8f96544a 100644
--- a/crates/backend-uzu/src/backends/cpu/backend.rs
+++ b/crates/backend-uzu/src/backends/cpu/backend.rs
@@ -1,4 +1,4 @@
-use std::{cell::UnsafeCell, pin::Pin, sync::atomic::AtomicU64};
+use std::{cell::UnsafeCell, pin::Pin};
use super::{
command_buffer::CpuCommandBuffer, context::CpuContext, error::CpuError, kernel::CpuKernels, sparse::CpuSparseBuffer,
@@ -13,7 +13,6 @@ impl Backend for Cpu {
type CommandBuffer = CpuCommandBuffer;
type DenseBuffer = UnsafeCell<Pin<Box<[u8]>>>;
type SparseBuffer = CpuSparseBuffer;
- type Event = Pin<Box<AtomicU64>>;
type Kernels = CpuKernels;
type Error = CpuError;
diff --git a/crates/backend-uzu/src/backends/cpu/command_buffer.rs b/crates/backend-uzu/src/backends/cpu/command_buffer.rs
index f2056e35e..dd32ab9cd 100644
--- a/crates/backend-uzu/src/backends/cpu/command_buffer.rs
+++ b/crates/backend-uzu/src/backends/cpu/command_buffer.rs
@@ -1,10 +1,5 @@
use std::{
- pin::Pin,
- sync::{
- atomic::{AtomicU64, Ordering},
- mpsc,
- },
- thread,
+ sync::mpsc,
time::{Duration, Instant},
};
@@ -110,30 +105,6 @@ impl CommandBufferEncoding for CpuCommandBufferEncoding {
) {
}
- fn encode_wait_for_event(
- &mut self,
- event: &Pin<Box<AtomicU64>>,
- value: u64,
- ) {
- let event = SendPtr(event.as_ref().get_ref() as *const AtomicU64);
- self.push_command(move || unsafe {
- while (&*event.as_ptr()).load(Ordering::Acquire) < value {
- thread::yield_now();
- }
- })
- }
-
- fn encode_signal_event(
- &mut self,
- event: &Pin<Box<AtomicU64>>,
- value: u64,
- ) {
- let event = SendPtr(event.as_ref().get_ref() as *const AtomicU64);
- self.push_command(Box::new(move || unsafe {
- (&*event.as_ptr()).store(value, Ordering::Release);
- }))
- }
-
fn add_completion_handler(
&mut self,
handler: impl FnOnce(Result<&CpuCommandBufferCompleted, CpuError>) + Send + 'static,
diff --git a/crates/backend-uzu/src/backends/cpu/context.rs b/crates/backend-uzu/src/backends/cpu/context.rs
index 7842ffeb4..2d208e349 100644
--- a/crates/backend-uzu/src/backends/cpu/context.rs
+++ b/crates/backend-uzu/src/backends/cpu/context.rs
@@ -1,11 +1,4 @@
-use std::{
- cell::UnsafeCell,
- path::Path,
- pin::Pin,
- rc::Rc,
- sync::{atomic::AtomicU64, mpsc},
- thread,
-};
+use std::{cell::UnsafeCell, path::Path, pin::Pin, rc::Rc, sync::mpsc, thread};
use crate::backends::{
common::{Allocation, AllocationPool, AllocationType, Allocator, Backend, Context},
@@ -77,10 +70,6 @@ impl Context for CpuContext {
Ok(CpuCommandBufferInitial::new(self.command_queue.clone()))
}
- fn create_event(&self) -> Result<Pin<Box<AtomicU64>>, CpuError> {
- Ok(Box::pin(AtomicU64::new(0)))
- }
-
fn create_sparse_buffer(
&self,
_capacity: usize,
diff --git a/crates/backend-uzu/src/backends/cpu/event.rs b/crates/backend-uzu/src/backends/cpu/event.rs
deleted file mode 100644
index 346f7af0f..000000000
--- a/crates/backend-uzu/src/backends/cpu/event.rs
+++ /dev/null
@@ -1,7 +0,0 @@
-use std::{pin::Pin, sync::atomic::AtomicU64};
-
-use crate::backends::{common::Event, cpu::Cpu};
-
-impl Event for Pin<Box<AtomicU64>> {
- type Backend = Cpu;
-}
diff --git a/crates/backend-uzu/src/backends/cpu/mod.rs b/crates/backend-uzu/src/backends/cpu/mod.rs
index cb5e6b374..2f3f6086d 100644
--- a/crates/backend-uzu/src/backends/cpu/mod.rs
+++ b/crates/backend-uzu/src/backends/cpu/mod.rs
@@ -4,7 +4,6 @@ mod command_buffer;
mod context;
mod dense_buffer;
mod error;
-mod event;
mod kernel;
mod sparse;
diff --git a/crates/backend-uzu/src/backends/metal/backend.rs b/crates/backend-uzu/src/backends/metal/backend.rs
index b7cb72365..5dd2a1da9 100644
--- a/crates/backend-uzu/src/backends/metal/backend.rs
+++ b/crates/backend-uzu/src/backends/metal/backend.rs
@@ -1,4 +1,4 @@
-use metal::{MTLBuffer, MTLEvent};
+use metal::MTLBuffer;
use objc2::{rc::Retained, runtime::ProtocolObject};
use super::{command_buffer::MetalCommandBuffer, context::MetalContext, error::MetalError, kernel::MetalKernels};
@@ -12,7 +12,6 @@ impl Backend for Metal {
type CommandBuffer = MetalCommandBuffer;
type DenseBuffer = Retained<ProtocolObject<dyn MTLBuffer>>;
type SparseBuffer = MetalSparseBuffer;
- type Event = Retained<ProtocolObject<dyn MTLEvent>>;
type Kernels = MetalKernels;
type Error = MetalError;
diff --git a/crates/backend-uzu/src/backends/metal/command_buffer.rs b/crates/backend-uzu/src/backends/metal/command_buffer.rs
index 37258d949..ad276fca7 100644
--- a/crates/backend-uzu/src/backends/metal/command_buffer.rs
+++ b/crates/backend-uzu/src/backends/metal/command_buffer.rs
@@ -1,18 +1,21 @@
-use std::{cell::Cell, time::Duration};
+use std::{cell::Cell, rc::Rc, time::Duration};
use metal::{
MTLBlitCommandEncoder, MTLBlitCommandEncoderExt, MTLCommandBuffer, MTLCommandBufferExt, MTLCommandBufferHandler,
- MTLCommandBufferStatus, MTLCommandEncoder, MTLComputeCommandEncoder, MTLEvent,
+ MTLCommandBufferStatus, MTLCommandEncoder, MTLCommandQueue, MTLComputeCommandEncoder,
};
use objc2::{Message, rc::Retained, runtime::ProtocolObject};
use super::Metal;
-use crate::backends::{
- common::{
- AccessFlags, Backend, BufferRangeMut, BufferRangeRef, CommandBuffer, CommandBufferCompleted,
- CommandBufferEncoding, CommandBufferExecutable, CommandBufferInitial, CommandBufferPending,
+use crate::{
+ backends::{
+ common::{
+ AccessFlags, Backend, BufferRangeMut, BufferRangeRef, CommandBuffer, CommandBufferCompleted,
+ CommandBufferEncoding, CommandBufferExecutable, CommandBufferInitial, CommandBufferPending,
+ },
+ metal::error::MetalError,
},
- metal::error::MetalError,
+ prelude::MetalContext,
};
pub struct MetalCommandBuffer;
@@ -37,12 +40,17 @@ fn command_buffer_result(command_buffer: &ProtocolObject<dyn MTLCommandBuffer>)
pub struct MetalCommandBufferInitial {
command_buffer: Retained<ProtocolObject<dyn MTLCommandBuffer>>,
+ context: Rc<MetalContext>,
}
impl MetalCommandBufferInitial {
- pub fn new(command_buffer: Retained<ProtocolObject<dyn MTLCommandBuffer>>) -> Self {
+ pub fn new(
+ command_buffer: Retained<ProtocolObject<dyn MTLCommandBuffer>>,
+ context: Rc<MetalContext>,
+ ) -> Self {
Self {
command_buffer,
+ context,
}
}
}
@@ -54,6 +62,7 @@ impl CommandBufferInitial for MetalCommandBufferInitial {
MetalCommandBufferEncoding {
command_buffer: self.command_buffer,
encoding_state: MetalCommandBufferEncodingEncodingState::None,
+ context: self.context,
}
}
}
@@ -67,6 +76,7 @@ enum MetalCommandBufferEncodingEncodingState {
pub struct MetalCommandBufferEncoding {
command_buffer: Retained<ProtocolObject<dyn MTLCommandBuffer>>,
encoding_state: MetalCommandBufferEncodingEncodingState,
+ context: Rc<MetalContext>,
}
impl MetalCommandBufferEncoding {
@@ -150,24 +160,6 @@ impl CommandBufferEncoding for MetalCommandBufferEncoding {
) {
}
- fn encode_wait_for_event(
- &mut self,
- event: &Retained<ProtocolObject<dyn MTLEvent>>,
- value: u64,
- ) {
- self.ensure_none();
- self.command_buffer.encode_wait_for_event_value(event, value);
- }
-
- fn encode_signal_event(
- &mut self,
- event: &Retained<ProtocolObject<dyn MTLEvent>>,
- value: u64,
- ) {
- self.ensure_none();
- self.command_buffer.encode_signal_event_value(event, value);
- }
-
fn add_completion_handler(
&mut self,
handler: impl FnOnce(Result<&MetalCommandBufferCompleted, MetalError>) + Send + 'static,
@@ -188,20 +180,37 @@ impl CommandBufferEncoding for MetalCommandBufferEncoding {
MetalCommandBufferExecutable {
command_buffer: self.command_buffer.clone(),
+ context: self.context.clone(),
}
}
}
pub struct MetalCommandBufferExecutable {
command_buffer: Retained<ProtocolObject<dyn MTLCommandBuffer>>,
+ context: Rc<MetalContext>,
}
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.encode_wait_for_event_value(self.context.timeline_event(), wait_value);
+ cmd_buffer.commit();
+ }
+
self.command_buffer.commit();
+ {
+ let cmd_buffer = cmd_queue.command_buffer().expect("Failed to create command buffer");
+ cmd_buffer.encode_signal_event_value(self.context.timeline_event(), wait_value + 1);
+ cmd_buffer.commit();
+ }
+
MetalCommandBufferPending {
command_buffer: self.command_buffer,
}
diff --git a/crates/backend-uzu/src/backends/metal/context.rs b/crates/backend-uzu/src/backends/metal/context.rs
index 2f6f5909b..82142170f 100644
--- a/crates/backend-uzu/src/backends/metal/context.rs
+++ b/crates/backend-uzu/src/backends/metal/context.rs
@@ -5,6 +5,7 @@ use std::{
collections::HashMap,
path::Path,
rc::{Rc, Weak},
+ sync::atomic::{AtomicU64, Ordering},
};
use metal::{
@@ -37,6 +38,8 @@ pub struct MetalContext {
pub device: Retained<ProtocolObject<dyn MTLDevice>>,
pub command_queue: Retained<ProtocolObject<dyn MTLCommandQueue>>,
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>,
device_capabilities: MetalDeviceCapabilities,
@@ -76,6 +79,14 @@ impl MetalContext {
pub(super) fn sparse_heap_pool_mut(&self) -> RefMut<'_, MetalSparseHeapPool> {
self.sparse_heap_pool.borrow_mut()
}
+
+ 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
+ }
}
impl Context for MetalContext {
@@ -99,11 +110,14 @@ impl Context for MetalContext {
let page_size = MTLSparsePageSize::KB256;
let heap_capacity = 64 * 4 * page_size.in_bytes();
let sparse_pool = MetalSparseHeapPool::new(page_size, heap_capacity);
+ let timeline_event = device.new_event().ok_or(MetalError::CannotCreateEvent)?;
Ok(Rc::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),
device_capabilities,
@@ -172,13 +186,10 @@ impl Context for MetalContext {
fn create_command_buffer(&self) -> Result<MetalCommandBufferInitial, MetalError> {
Ok(MetalCommandBufferInitial::new(
self.command_queue.command_buffer().ok_or(MetalError::CannotCreateCommandBuffer)?,
+ self.weak_self.upgrade().unwrap(), // never fails
))
}
- fn create_event(&self) -> Result<Retained<ProtocolObject<dyn MTLEvent>>, MetalError> {
- self.device.new_event().ok_or(MetalError::CannotCreateEvent)
- }
-
fn create_sparse_buffer(
&self,
capacity: usize,
diff --git a/crates/backend-uzu/src/backends/metal/event.rs b/crates/backend-uzu/src/backends/metal/event.rs
deleted file mode 100644
index 8a4e5329a..000000000
--- a/crates/backend-uzu/src/backends/metal/event.rs
+++ /dev/null
@@ -1,9 +0,0 @@
-use metal::MTLEvent;
-use objc2::{rc::Retained, runtime::ProtocolObject};
-
-use super::Metal;
-use crate::backends::common::Event;
-
-impl Event for Retained<ProtocolObject<dyn MTLEvent>> {
- type Backend = Metal;
-}
diff --git a/crates/backend-uzu/src/backends/metal/mod.rs b/crates/backend-uzu/src/backends/metal/mod.rs
index 507be72b2..478f2add5 100644
--- a/crates/backend-uzu/src/backends/metal/mod.rs
+++ b/crates/backend-uzu/src/backends/metal/mod.rs
@@ -5,7 +5,6 @@ mod context;
mod dense_buffer;
mod device_capabilities;
mod error;
-mod event;
mod kernel;
mod metal_extensions;
mod sparse;
diff --git a/crates/backend-uzu/src/language_model/language_model_generator.rs b/crates/backend-uzu/src/language_model/language_model_generator.rs
index 84ba67760..f9e0b38f2 100644
--- a/crates/backend-uzu/src/language_model/language_model_generator.rs
+++ b/crates/backend-uzu/src/language_model/language_model_generator.rs
@@ -499,9 +499,6 @@ impl<B: Backend> LanguageModelGeneratorTrait for LanguageModelGenerator<B> {
let token_inputs = self.build_token_inputs(task, token_ids_array, None);
let mut encoder = Encoder::<B>::new(self.context.context.as_ref())
.map_err(|e| Error::UnableToCreateCommandBuffer(e.into()))?;
- if is_continuation {
- encoder.encode_wait_for_event(&self.context.async_buffers.event, current_counter);
- }
let resources = Self::encode_forward_pass_on(
&self.context,
&mut encoder,
@@ -543,11 +540,6 @@ impl<B: Backend> LanguageModelGeneratorTrait for LanguageModelGenerator<B> {
);
self.context.cache_layers.borrow_mut().register_accepted_tokens(1);
- // Signal event for next pass
- let next_counter = current_counter + 1;
- encoder.encode_signal_event(&self.context.async_buffers.event, next_counter);
- self.context.async_buffers.counter.set(next_counter);
-
// Add completion handler
let handler = move |result: Result<&<B::CommandBuffer as CommandBuffer>::Completed, B::Error>| {
result.expect("async decoding forward pass completed with error");
diff --git a/crates/backend-uzu/src/language_model/language_model_generator_context.rs b/crates/backend-uzu/src/language_model/language_model_generator_context.rs
index e331444c9..adad1a3e5 100644
--- a/crates/backend-uzu/src/language_model/language_model_generator_context.rs
+++ b/crates/backend-uzu/src/language_model/language_model_generator_context.rs
@@ -33,8 +33,6 @@ pub struct AsyncBuffers<B: Backend> {
/// Seeds array: [max_tokens] u64
/// Pre-populated with deterministic seed sequence
pub seeds: Array<B>,
- /// Event for GPU-side synchronization between passes
- pub event: B::Event,
/// Current event counter (pass N waits on N, signals N+1)
pub counter: Cell<u64>,
/// Number of tokens after prefill (base for position calculation)
@@ -51,12 +49,10 @@ impl<B: Backend> AsyncBuffers<B> {
) -> Self {
let positions = context.create_array_uninitialized(&[max_tokens], DataType::I32);
let seeds = context.create_array_uninitialized(&[max_tokens], DataType::U64);
- let event = context.create_event().expect("Failed to create event");
Self {
positions,
seeds,
- event,
counter: Cell::new(0),
prefill_count: Cell::new(0),
batch_size,