Skip to main content

oa/
compute.rs

1//! Extension compute kernels for SDK and third-party workloads.
2//!
3//! [`Kernel`] compiles caller-owned SPIR-V into a device compute pipeline and
4//! [`Engine::dispatch_kernel`] records it through the same eager batching,
5//! barrier, and event machinery as built-in operations. This is the supported
6//! way to extend `oa` with custom shaders without forking the closed in-lib
7//! kernel registry; the `oa_sdk` crate builds its workload kernels on it.
8//!
9//! ## Kernel ABI
10//!
11//! Extension kernels follow the OA compute ABI: the first push-constant words
12//! are buffer descriptor indices, one per declared binding in binding order,
13//! followed by the caller's `u32`/`f32` push words. Buffer bindings are
14//! positional [`KernelBinding`] entries. The entry point is `main` and the
15//! workgroup size is declared at compile time.
16
17use std::collections::hash_map::DefaultHasher;
18use std::hash::{Hash, Hasher};
19use std::sync::Arc;
20
21use crate::runtime::{BufferBinding, Device, PushConstant};
22
23use crate::{Engine, Error, Matrix, Result};
24
25/// A compiled extension compute kernel on one engine's device.
26///
27/// Compile cost is paid once at construction; identical SPIR-V on the same
28/// device reuses the cached pipeline. The kernel may be dispatched any number
29/// of times via [`Engine::dispatch_kernel`]. It is not part of the semantic
30/// graph or fusion system: dispatches record as physical nodes with the
31/// caller-declared binding accesses.
32pub struct Kernel {
33	name: &'static str,
34	key: Vec<u8>,
35	bindings: usize,
36	push_words: usize,
37	device: Arc<Device>,
38}
39
40/// One storage binding in an extension-kernel dispatch.
41///
42/// The declared access drives barrier planning: reads may overlap, writes
43/// serialize against the storage's other recorded work. Declaring `Write`
44/// on a binding the shader also reads is a contract violation; use
45/// [`KernelBinding::ReadWrite`].
46#[derive(Clone, Copy)]
47pub enum KernelBinding<'a> {
48	/// Read-only storage binding.
49	Read(&'a Matrix),
50	/// Write-only storage binding.
51	Write(&'a Matrix),
52	/// Read-modify-write storage binding.
53	ReadWrite(&'a Matrix),
54}
55
56/// One four-byte push-constant word appended after the binding indices.
57#[derive(Clone, Copy, Debug)]
58pub enum KernelPush {
59	/// Unsigned 32-bit word.
60	U32(u32),
61	/// IEEE-754 32-bit word, bit-cast in place.
62	F32(f32),
63}
64
65impl Kernel {
66	/// Compile SPIR-V bytes into a dispatchable extension kernel.
67	///
68	/// `spirv` is the little-endian SPIR-V byte stream, exactly as produced by
69	/// `slangc`/`glslc` or embedded via the `include_bytes!` macro.
70	///
71	/// `bindings` is the number of storage-buffer slots the kernel declares;
72	/// those leading push-constant words are reserved for descriptor indices
73	/// and supplied automatically at dispatch. The remaining reflected
74	/// push-constant words are the caller's push surface — validated against
75	/// the actual SPIR-V at compile time.
76	///
77	/// `workgroup_size` must match the shader's `local_size` declaration; it
78	/// is validated against device limits here and again per dispatch.
79	///
80	/// # Errors
81	///
82	/// Returns an error when the bytes are not valid compute SPIR-V, when the
83	/// reflected push-constant range is smaller than `bindings` words, when
84	/// `workgroup_size` exceeds device limits, or when pipeline creation fails.
85	pub fn compile(
86		engine: &Engine,
87		name: &'static str,
88		spirv: &[u8],
89		bindings: u32,
90		workgroup_size: [u32; 3],
91	) -> Result<Self> {
92		let device = engine.handle().device();
93		let words = crate::runtime::decode_spirv_bytes(spirv)?;
94		let mut key = DefaultHasher::new();
95		name.hash(&mut key);
96		spirv.hash(&mut key);
97		bindings.hash(&mut key);
98		workgroup_size.hash(&mut key);
99		let key = key.finish().to_le_bytes().to_vec();
100		let pipeline = device.admit_extension_pipeline(key.clone(), &words, workgroup_size)?;
101		let push_words = usize::try_from(pipeline.push_constant_size()).map_err(|_| {
102			Error::internal(format!(
103				"extension kernel {name} push-constant size does not fit this platform"
104			))
105		})? / 4;
106		let push_words = push_words.checked_sub(bindings as usize).ok_or_else(|| {
107			Error::invalid_argument(format!(
108				"extension kernel {name} declares {bindings} buffer bindings but its \
109				 push-constant block holds fewer words"
110			))
111		})?;
112		Ok(Self {
113			name,
114			key,
115			bindings: bindings as usize,
116			push_words,
117			device,
118		})
119	}
120
121	/// The kernel's caller push-constant surface in four-byte words.
122	///
123	/// [`Engine::dispatch_kernel`] requires exactly this many
124	/// [`KernelPush`] entries.
125	pub const fn push_words(&self) -> usize {
126		self.push_words
127	}
128
129	/// The kernel's declared storage-binding count.
130	pub const fn binding_count(&self) -> usize {
131		self.bindings
132	}
133
134	pub(crate) const fn name(&self) -> &'static str {
135		self.name
136	}
137
138	pub(crate) fn key(&self) -> &[u8] {
139		&self.key
140	}
141}
142
143impl Engine {
144	/// Record one eager extension-kernel dispatch.
145	///
146	/// The dispatch joins the engine's pending batch like any eager operation:
147	/// barriers against other recorded work are derived from the declared
148	/// binding accesses, and completion is observed through
149	/// [`Engine::checkpoint`] or any host read.
150	///
151	/// # Errors
152	///
153	/// Returns `InvalidArgument` when `kernel` belongs to another engine, when
154	/// `bindings`/`push_constants` counts do not match the kernel's declared
155	/// ABI, or when `workgroups` is zero or exceeds device limits; returns the
156	/// recording errors from the underlying session otherwise.
157	pub fn dispatch_kernel(
158		&self,
159		kernel: &Kernel,
160		bindings: &[KernelBinding<'_>],
161		push_constants: &[KernelPush],
162		workgroups: [u32; 3],
163	) -> Result<()> {
164		if bindings.len() != kernel.bindings {
165			return Err(Error::invalid_argument(format!(
166				"extension kernel {} declares {} bindings, got {}",
167				kernel.name,
168				kernel.bindings,
169				bindings.len()
170			)));
171		}
172		if push_constants.len() != kernel.push_words {
173			return Err(Error::invalid_argument(format!(
174				"extension kernel {} declares {} push words, got {}",
175				kernel.name,
176				kernel.push_words,
177				push_constants.len()
178			)));
179		}
180		let resolved = bindings
181			.iter()
182			.map(|binding| match *binding {
183				KernelBinding::Read(matrix) => BufferBinding::read(matrix.storage()),
184				KernelBinding::Write(matrix) => BufferBinding::write(matrix.storage()),
185				KernelBinding::ReadWrite(matrix) => BufferBinding::read_write(matrix.storage()),
186			})
187			.collect::<Vec<_>>();
188		let pushes = push_constants
189			.iter()
190			.map(|push| match *push {
191				KernelPush::U32(value) => PushConstant::U32(value),
192				KernelPush::F32(value) => PushConstant::F32(value),
193			})
194			.collect::<Vec<_>>();
195		if !std::sync::Arc::ptr_eq(&kernel.device, &self.handle().device()) {
196			return Err(Error::invalid_argument(format!(
197				"extension kernel {} was compiled for a different engine",
198				kernel.name
199			)));
200		}
201		self
202			.handle()
203			.record_extension(kernel, &resolved, &pushes, workgroups)
204	}
205}
206
207#[cfg(test)]
208#[path = "../../../test/rs/runtime/compute_unit.rs"]
209mod tests;