Skip to main content

oa/matrix/
matrix.rs

1//! Numeric dtype, shape, and runtime storage.
2
3use std::{
4	marker::PhantomData,
5	ops::{Add, Div, Mul, Neg, Sub},
6	rc::Rc,
7	sync::atomic::{AtomicU64, Ordering},
8};
9
10use crate::{
11	Engine, Error, Result,
12	runtime::{EngineHandle, Storage},
13};
14
15use crate::core::{DType, Element};
16
17/// Device-visible numeric storage with explicit shape and dtype semantics.
18///
19/// Arithmetic operators delegate to [`crate::matrix`] and return `Result<Matrix>`:
20/// use `let sum = (&left + &right)?;`. They preserve validation, allocation, and
21/// recording failures without panicking. Multiplication is elementwise; use
22/// [`crate::matrix::mat_mul_nt`] for matrix multiplication.
23#[derive(Clone)]
24pub struct Matrix {
25	engine: EngineHandle,
26	storage: Storage,
27	shape: Vec<usize>,
28	dtype: DType,
29	element_count: usize,
30	semantic: Rc<MatrixSemantic>,
31	_not_send_sync: PhantomData<Rc<()>>,
32}
33
34/// Persistent handle-free provenance shared by clones of one Matrix value.
35pub(crate) struct MatrixSemantic {
36	id: u64,
37	shape: Vec<usize>,
38	dtype: DType,
39	view_source: Option<Rc<Self>>,
40	view_byte_offset: i64,
41}
42
43impl MatrixSemantic {
44	pub(crate) const fn id(&self) -> u64 {
45		self.id
46	}
47
48	pub(crate) fn shape(&self) -> &[usize] {
49		&self.shape
50	}
51
52	pub(crate) const fn dtype(&self) -> DType {
53		self.dtype
54	}
55
56	pub(crate) fn view_source(&self) -> Option<&Rc<Self>> {
57		self.view_source.as_ref()
58	}
59
60	pub(crate) const fn view_byte_offset(&self) -> i64 {
61		self.view_byte_offset
62	}
63}
64
65impl Matrix {
66	/// Create a dense matrix from an admitted Rust scalar slice.
67	///
68	/// The element type selects the matrix dtype exactly; this function performs
69	/// no numeric conversion.
70	///
71	/// # Errors
72	///
73	/// Returns an error when the shape overflows, its element count differs from
74	/// `values`, or storage allocation/upload fails.
75	///
76	/// This variant uploads on this thread's default engine. An engine
77	/// initialization failure is returned before the upload starts.
78	pub fn new_from_slice<T: Element>(shape: impl Into<Vec<usize>>, values: &[T]) -> Result<Self> {
79		let shape = shape.into();
80		Self::new_from_slice_on(&Engine::current()?, shape, values)
81	}
82
83	/// Create a dense matrix on a particular engine.
84	///
85	/// This is the [`new_from_slice`](Self::new_from_slice) contract evaluated
86	/// on `engine` instead of this thread's default engine.
87	///
88	/// # Errors
89	///
90	/// Returns the same errors as [`new_from_slice`](Self::new_from_slice).
91	pub fn new_from_slice_on<T: Element>(
92		engine: &Engine,
93		shape: impl Into<Vec<usize>>,
94		values: &[T],
95	) -> Result<Self> {
96		Self::new_from_slice_handle(&engine.handle(), shape.into(), values)
97	}
98
99	/// Create a dense matrix on the engine that owns `self`.
100	///
101	/// The element type selects the matrix dtype exactly; this function performs
102	/// no numeric conversion.
103	///
104	/// # Errors
105	///
106	/// Returns an error when the shape overflows, its element count differs from
107	/// `values`, or storage allocation/upload fails.
108	pub fn new_from_slice_on_same_engine<T: Element>(
109		&self,
110		shape: impl Into<Vec<usize>>,
111		values: &[T],
112	) -> Result<Self> {
113		Self::new_from_slice_handle(self.engine_handle(), shape.into(), values)
114	}
115
116	/// Return whether `other` is owned by the same engine as `self`.
117	pub fn same_engine(&self, other: &Matrix) -> bool {
118		self.engine_handle().same_as(other.engine_handle())
119	}
120
121	pub(crate) fn new_from_slice_handle<T: Element>(
122		engine: &EngineHandle,
123		shape: Vec<usize>,
124		values: &[T],
125	) -> Result<Self> {
126		let element_count = checked_element_count(&shape)?;
127		if element_count != values.len() {
128			return Err(Error::invalid_argument(format!(
129				"matrix shape contains {element_count} elements but {} values were provided",
130				values.len()
131			)));
132		}
133
134		let byte_len = element_count
135			.checked_mul(size_of::<T>())
136			.ok_or_else(|| Error::invalid_argument("matrix byte size overflows usize"))?;
137		debug_assert_eq!(size_of::<T>(), T::DTYPE.size_bytes());
138		// SAFETY: `Element` is sealed to OA-owned implementations whose values have
139		// no padding, every bit pattern is valid, and storage width equals
140		// `DType::size_bytes`. `values` is an initialized contiguous slice, and the
141		// checked calculation proves its exact byte extent.
142		let bytes = unsafe { std::slice::from_raw_parts(values.as_ptr().cast(), byte_len) };
143		let storage = if T::DTYPE == DType::U8 {
144			let mut padded = vec![0_u8; byte_storage_len(byte_len, T::DTYPE)?];
145			padded[..byte_len].copy_from_slice(bytes);
146			engine.create_storage(&padded)?
147		} else {
148			engine.create_storage(bytes)?
149		};
150
151		let semantic = matrix_semantic(&shape, T::DTYPE, None)?;
152		Ok(Self {
153			engine: engine.clone(),
154			storage,
155			shape,
156			dtype: T::DTYPE,
157			element_count,
158			semantic,
159			_not_send_sync: PhantomData,
160		})
161	}
162
163	/// Create an FP32 matrix and initialize its device-visible storage.
164	///
165	/// # Errors
166	///
167	/// Returns an error when the shape overflows, its element count differs from
168	/// `values`, or storage allocation/upload fails.
169	///
170	/// This variant uploads on this thread's default engine. An engine
171	/// initialization failure is returned before the upload starts.
172	pub fn new_from_f32(shape: impl Into<Vec<usize>>, values: &[f32]) -> Result<Self> {
173		let shape = shape.into();
174		Self::new_from_f32_on(&Engine::current()?, shape, values)
175	}
176	/// Create an FP32 matrix and initialize its device-visible storage on a
177	/// particular engine.
178	///
179	/// This is the [`new_from_f32`](Self::new_from_f32) contract evaluated on
180	/// `engine` instead of this thread's default engine.
181	///
182	/// # Errors
183	///
184	/// Returns an error when the shape overflows, its element count differs from
185	/// `values`, or storage allocation/upload fails.
186	pub fn new_from_f32_on(
187		engine: &Engine,
188		shape: impl Into<Vec<usize>>,
189		values: &[f32],
190	) -> Result<Self> {
191		Self::new_from_slice_on(engine, shape, values)
192	}
193
194	pub(crate) fn filled_f32(
195		engine: &Engine,
196		shape: impl Into<Vec<usize>>,
197		value: f32,
198	) -> Result<Self> {
199		let shape = shape.into();
200		let element_count = checked_element_count(&shape)?;
201		Self::new_from_f32_on(engine, shape, &vec![value; element_count])
202	}
203
204	/// Return the matrix shape.
205	pub fn shape(&self) -> &[usize] {
206		&self.shape
207	}
208
209	/// Return the matrix scalar representation.
210	pub const fn dtype(&self) -> DType {
211		self.dtype
212	}
213
214	/// Return the number of logical dense elements.
215	pub const fn num_elements(&self) -> usize {
216		self.element_count
217	}
218
219	/// Return a zero-copy one-dimensional view over all elements.
220	///
221	/// Equivalent to `self.reshape([self.num_elements()])`.
222	///
223	/// # Errors
224	///
225	/// Returns an error when the element count overflows or storage allocation
226	/// fails.
227	pub fn flatten(&self) -> Result<Self> {
228		crate::matrix::reshape(self, vec![self.element_count])
229	}
230
231	/// Return a zero-copy view with a new size-one axis inserted at `dim`.
232	///
233	/// `dim` must be in `0..=self.shape().len()`. Negative indices are not
234	/// supported; use `self.shape().len()` to append at the end.
235	///
236	/// # Errors
237	///
238	/// Returns an error when `dim` is out of range.
239	pub fn unsqueeze(&self, dim: usize) -> Result<Self> {
240		let rank = self.shape.len();
241		if dim > rank {
242			return Err(Error::invalid_argument(format!(
243				"unsqueeze dim {dim} is out of range for rank-{rank} matrix"
244			)));
245		}
246		let mut shape = self.shape.clone();
247		shape.insert(dim, 1);
248		crate::matrix::reshape(self, shape)
249	}
250
251	/// Return a zero-copy view with one size-one axis removed.
252	///
253	/// `dim` must be in `0..self.shape().len()` and the selected axis must have
254	/// extent one. Negative indices are not supported.
255	///
256	/// # Errors
257	///
258	/// Returns an error when `dim` is out of range or the selected axis is not
259	/// size one.
260	pub fn squeeze(&self, dim: usize) -> Result<Self> {
261		let rank = self.shape.len();
262		if dim >= rank {
263			return Err(Error::invalid_argument(format!(
264				"squeeze dim {dim} is out of range for rank-{rank} matrix"
265			)));
266		}
267		if self.shape[dim] != 1 {
268			return Err(Error::invalid_argument(format!(
269				"squeeze dim {dim} has extent {}; only size-one axes may be squeezed",
270				self.shape[dim]
271			)));
272		}
273		let mut shape = self.shape.clone();
274		shape.remove(dim);
275		crate::matrix::reshape(self, shape)
276	}
277
278	/// Read all FP32 values back to host memory.
279	///
280	/// # Errors
281	///
282	/// This is an explicit host-observation boundary: it submits the pending eager
283	/// batch when this matrix is still recorded, then waits for the exact GPU event
284	/// that produced it before mapping its storage. Returns an error when this is
285	/// not an FP32 matrix or when submission, completion, mapping, or cache
286	/// invalidation fails.
287	pub fn read_f32(&self) -> Result<Vec<f32>> {
288		self.read()
289	}
290
291	/// Attempt to read all FP32 values without waiting for pending GPU work.
292	///
293	/// # Errors
294	///
295	/// Returns an error when this is not an FP32 matrix,
296	/// [`crate::ErrorKind::NotReady`] when GPU production is pending, or an error
297	/// when mapping or cache invalidation fails.
298	pub fn try_read_f32(&self) -> Result<Vec<f32>> {
299		self.try_read()
300	}
301
302	/// Read all values into their exact admitted Rust scalar representation.
303	///
304	/// # Errors
305	///
306	/// Returns an error before submission or waiting when `T` does not match this
307	/// matrix's dtype. Otherwise this submits its pending eager batch when needed,
308	/// waits for the exact producing event, and returns an error when submission,
309	/// completion, mapping, or cache invalidation fails.
310	pub fn read<T: Element>(&self) -> Result<Vec<T>> {
311		self.validate_element::<T>()?;
312		if self.storage.needs_flush() {
313			self.engine.flush()?;
314		}
315		self.storage.wait_ready()?;
316		self.read_ready::<T>()
317	}
318
319	/// Attempt typed readback without waiting for pending GPU work.
320	///
321	/// # Errors
322	///
323	/// Returns an error when `T` does not match this matrix's dtype,
324	/// [`crate::ErrorKind::NotReady`] when production is pending, or an error
325	/// when mapping or cache invalidation fails.
326	pub fn try_read<T: Element>(&self) -> Result<Vec<T>> {
327		self.validate_element::<T>()?;
328		self.storage.ensure_ready()?;
329		self.read_ready::<T>()
330	}
331
332	fn validate_element<T: Element>(&self) -> Result<()> {
333		if self.dtype != T::DTYPE {
334			return Err(Error::invalid_argument(format!(
335				"matrix dtype {} cannot be read as {}",
336				self.dtype.token(),
337				T::DTYPE.token()
338			)));
339		}
340		Ok(())
341	}
342
343	fn read_ready<T: Element>(&self) -> Result<Vec<T>> {
344		let byte_len = self
345			.element_count
346			.checked_mul(size_of::<T>())
347			.ok_or_else(|| Error::invalid_argument("matrix byte size overflows usize"))?;
348		debug_assert_eq!(size_of::<T>(), self.dtype.size_bytes());
349		let mut output = vec![T::default(); self.element_count];
350		// SAFETY: `Element` is sealed to OA-owned no-padding scalar types for which
351		// every bit pattern is valid. `output` is initialized contiguous storage with
352		// exactly `byte_len` bytes; the mutable byte view weakens alignment and does
353		// not exceed the vector's initialized extent.
354		let output_bytes =
355			unsafe { std::slice::from_raw_parts_mut(output.as_mut_ptr().cast::<u8>(), byte_len) };
356		self.storage.read_prefix(output_bytes)?;
357		Ok(output)
358	}
359
360	pub(crate) const fn engine_handle(&self) -> &EngineHandle {
361		&self.engine
362	}
363
364	pub(crate) const fn element_count(&self) -> usize {
365		self.element_count
366	}
367
368	/// Stable identity of this value for plan-validity comparisons.
369	///
370	/// Two matrices constructed independently never share an id; views and
371	/// clones of one allocation do. Compiled-plan owners (OA-CC-20) compare
372	/// identities to reject replaying a captured plan against different
373	/// storage.
374	pub fn value_id(&self) -> u64 {
375		self.semantic.id
376	}
377
378	pub(crate) fn same_value_as(&self, other: &Self) -> bool {
379		self.semantic.id == other.semantic.id
380	}
381
382	pub(crate) fn semantic(&self) -> &Rc<MatrixSemantic> {
383		&self.semantic
384	}
385
386	pub(crate) fn storage(&self) -> &Storage {
387		&self.storage
388	}
389
390	pub(crate) fn write_values<T: Element>(&self, values: &[T]) -> Result<()> {
391		self.validate_element::<T>()?;
392		if values.len() != self.element_count {
393			return Err(Error::invalid_argument(format!(
394				"matrix upload requires {} elements; received {}",
395				self.element_count,
396				values.len()
397			)));
398		}
399		let byte_len = self
400			.element_count
401			.checked_mul(size_of::<T>())
402			.ok_or_else(|| Error::invalid_argument("matrix byte size overflows usize"))?;
403		// SAFETY: `Element` is sealed to initialized, no-padding OA scalar types and
404		// the checked length covers exactly the supplied slice.
405		let bytes = unsafe { std::slice::from_raw_parts(values.as_ptr().cast(), byte_len) };
406		let result = if self.dtype == DType::U8 {
407			let padded_len = byte_storage_len(byte_len, self.dtype)?;
408			if padded_len == byte_len {
409				// RGBA capture is already word-aligned. Preserve the padding
410				// contract without allocating/copying a second complete frame.
411				self.storage.write(bytes)
412			} else {
413				let mut padded = vec![0_u8; padded_len];
414				padded[..byte_len].copy_from_slice(bytes);
415				self.storage.write(&padded)
416			}
417		} else {
418			self.storage.write(bytes)
419		};
420		if result.is_ok() {
421			self.storage.mark_host_initialized();
422		}
423		result
424	}
425
426	pub(crate) fn reshape_view(&self, shape: Vec<usize>) -> Result<Self> {
427		let element_count = checked_element_count(&shape)?;
428		if element_count != self.element_count {
429			return Err(Error::invalid_argument(format!(
430				"matrix reshape requires {} elements; requested shape {:?} contains {element_count}",
431				self.element_count, shape
432			)));
433		}
434		let semantic = matrix_semantic(&shape, self.dtype, Some(self.semantic.clone()))?;
435		Ok(Self {
436			engine: self.engine.clone(),
437			storage: self.storage.clone(),
438			shape,
439			dtype: self.dtype,
440			element_count,
441			semantic,
442			_not_send_sync: PhantomData,
443		})
444	}
445
446	pub(crate) fn reshape_semantic_output(&self, shape: Vec<usize>) -> Result<Self> {
447		let element_count = checked_element_count(&shape)?;
448		if element_count != self.element_count {
449			return Err(Error::invalid_argument(format!(
450				"matrix reshape requires {} elements; requested shape {:?} contains {element_count}",
451				self.element_count, shape
452			)));
453		}
454		let semantic = matrix_semantic(&shape, self.dtype, None)?;
455		Ok(Self {
456			engine: self.engine.clone(),
457			storage: self.storage.clone(),
458			shape,
459			dtype: self.dtype,
460			element_count,
461			semantic,
462			_not_send_sync: PhantomData,
463		})
464	}
465
466	/// Allocate initialized zero storage for persistent state or producers that
467	/// intentionally depend on a zeroed destination.
468	pub(crate) fn allocate(
469		engine: &EngineHandle,
470		shape: Vec<usize>,
471		element_count: usize,
472		dtype: DType,
473	) -> Result<Self> {
474		let logical_byte_len = element_count
475			.checked_mul(dtype.size_bytes())
476			.ok_or_else(|| Error::invalid_argument("matrix byte size overflows usize"))?;
477		let byte_len = byte_storage_len(logical_byte_len, dtype)?;
478		let storage = engine.create_storage(&vec![0_u8; byte_len])?;
479		let semantic = matrix_semantic(&shape, dtype, None)?;
480		Ok(Self {
481			engine: engine.clone(),
482			storage,
483			shape,
484			dtype,
485			element_count,
486			semantic,
487			_not_send_sync: PhantomData,
488		})
489	}
490
491	/// Allocate a Matrix that must be fully produced by recorded GPU work.
492	/// No host placeholder is uploaded; readiness rejects observation and GPU
493	/// reads until a producer dispatch has been recorded and completed.
494	pub(crate) fn allocate_output(
495		engine: &EngineHandle,
496		shape: Vec<usize>,
497		element_count: usize,
498		dtype: DType,
499	) -> Result<Self> {
500		let logical_byte_len = element_count
501			.checked_mul(dtype.size_bytes())
502			.ok_or_else(|| Error::invalid_argument("matrix byte size overflows usize"))?;
503		let storage = if logical_byte_len == 0 {
504			engine.create_storage(&[])?
505		} else {
506			let byte_len = byte_storage_len(logical_byte_len, dtype)?;
507			engine.create_output_storage(byte_len)?
508		};
509		let semantic = matrix_semantic(&shape, dtype, None)?;
510		Ok(Self {
511			engine: engine.clone(),
512			storage,
513			shape,
514			dtype,
515			element_count,
516			semantic,
517			_not_send_sync: PhantomData,
518		})
519	}
520
521	/// Construct a semantic value over checked, retained runtime storage.
522	pub(crate) fn from_runtime_storage(
523		engine: &EngineHandle,
524		storage: Storage,
525		shape: Vec<usize>,
526		dtype: DType,
527	) -> Result<Self> {
528		engine.validate_storage_owner(&storage)?;
529		let element_count = checked_element_count(&shape)?;
530		let logical_bytes = element_count
531			.checked_mul(dtype.size_bytes())
532			.ok_or_else(|| Error::invalid_argument("matrix byte extent overflows usize"))?;
533		if byte_storage_len(logical_bytes, dtype)? != storage.byte_len() {
534			return Err(Error::invalid_argument(
535				"runtime output extent does not match Matrix metadata",
536			));
537		}
538		let semantic = matrix_semantic(&shape, dtype, None)?;
539		Ok(Self {
540			engine: engine.clone(),
541			storage,
542			shape,
543			dtype,
544			element_count,
545			semantic,
546			_not_send_sync: PhantomData,
547		})
548	}
549}
550
551pub(crate) fn byte_storage_len(logical_byte_len: usize, dtype: DType) -> Result<usize> {
552	if dtype != DType::U8 && dtype != DType::F16 {
553		return Ok(logical_byte_len);
554	}
555	logical_byte_len
556		.max(1)
557		.checked_add(3)
558		.map(|length| length & !3)
559		.ok_or_else(|| Error::invalid_argument("byte matrix storage size overflows usize"))
560}
561
562fn matrix_semantic(
563	shape: &[usize],
564	dtype: DType,
565	view_source: Option<Rc<MatrixSemantic>>,
566) -> Result<Rc<MatrixSemantic>> {
567	Ok(Rc::new(MatrixSemantic {
568		id: next_value_id()?,
569		shape: shape.to_vec(),
570		dtype,
571		view_source,
572		view_byte_offset: 0,
573	}))
574}
575
576fn next_value_id() -> Result<u64> {
577	static NEXT_VALUE_ID: AtomicU64 = AtomicU64::new(1);
578	NEXT_VALUE_ID
579		.try_update(Ordering::Relaxed, Ordering::Relaxed, |value| {
580			value.checked_add(1)
581		})
582		.map_err(|_| Error::resource_exhausted("matrix semantic value identity exhausted"))
583}
584
585fn checked_element_count(shape: &[usize]) -> Result<usize> {
586	shape.iter().copied().try_fold(1_usize, |count, extent| {
587		count
588			.checked_mul(extent)
589			.ok_or_else(|| Error::invalid_argument("matrix element count overflows usize"))
590	})
591}
592
593// Operators delegate to the same fallible semantic operations. Result preserves
594// validation, allocation, capability, and recording errors without hidden panics.
595
596/// `&mat_a + &mat_b` — elementwise add with broadcasting.
597impl Add for &Matrix {
598	type Output = Result<Matrix>;
599	fn add(self, rhs: &Matrix) -> Result<Matrix> {
600		crate::matrix::add(self, rhs)
601	}
602}
603
604/// `&mat_a - &mat_b` — elementwise subtract with broadcasting.
605impl Sub for &Matrix {
606	type Output = Result<Matrix>;
607	fn sub(self, rhs: &Matrix) -> Result<Matrix> {
608		crate::matrix::sub(self, rhs)
609	}
610}
611
612/// `&mat_a * &mat_b` — elementwise multiply (not matmul).
613impl Mul for &Matrix {
614	type Output = Result<Matrix>;
615	fn mul(self, rhs: &Matrix) -> Result<Matrix> {
616		crate::matrix::mul(self, rhs)
617	}
618}
619
620/// `&mat_a / &mat_b` — elementwise divide with broadcasting.
621impl Div for &Matrix {
622	type Output = Result<Matrix>;
623	fn div(self, rhs: &Matrix) -> Result<Matrix> {
624		crate::matrix::div(self, rhs)
625	}
626}
627
628/// `-&mat` — elementwise negate.
629impl Neg for &Matrix {
630	type Output = Result<Matrix>;
631	fn neg(self) -> Result<Matrix> {
632		crate::matrix::neg(self)
633	}
634}
635
636/// `-mat` — elementwise negate of an owned matrix (avoids a `&` at call sites
637/// where the value is already a temporary, e.g. `-(&a * &b)?`).
638impl Neg for Matrix {
639	type Output = Result<Matrix>;
640	fn neg(self) -> Result<Matrix> {
641		crate::matrix::neg(&self)
642	}
643}
644
645/// `&mat + scalar` — add a scalar to every element.
646impl Add<f32> for &Matrix {
647	type Output = Result<Matrix>;
648	fn add(self, rhs: f32) -> Result<Matrix> {
649		crate::matrix::add_scalar(self, rhs)
650	}
651}
652
653/// `&mat - scalar` — subtract a scalar from every element.
654impl Sub<f32> for &Matrix {
655	type Output = Result<Matrix>;
656	fn sub(self, rhs: f32) -> Result<Matrix> {
657		crate::matrix::sub_scalar(self, rhs)
658	}
659}
660
661/// `&mat * scalar` — scale every element.
662impl Mul<f32> for &Matrix {
663	type Output = Result<Matrix>;
664	fn mul(self, rhs: f32) -> Result<Matrix> {
665		crate::matrix::scale(self, rhs)
666	}
667}
668
669/// `&mat / scalar` — divide every element by a scalar.
670impl Div<f32> for &Matrix {
671	type Output = Result<Matrix>;
672	fn div(self, rhs: f32) -> Result<Matrix> {
673		crate::matrix::div_scalar(self, rhs)
674	}
675}
676
677// scalar-on-left variants: `2.0_f32 * &mat`, `2.0_f32 + &mat`
678// Rust does not automatically reverse binary operators, so these need
679// explicit impls to match C++ implicit-conversion behaviour.
680
681/// `scalar * &mat` — scale every element (left-hand scalar form).
682impl Mul<&Matrix> for f32 {
683	type Output = Result<Matrix>;
684	fn mul(self, rhs: &Matrix) -> Result<Matrix> {
685		crate::matrix::scale(rhs, self)
686	}
687}
688
689/// `scalar + &mat` — add a scalar to every element (left-hand scalar form).
690impl Add<&Matrix> for f32 {
691	type Output = Result<Matrix>;
692	fn add(self, rhs: &Matrix) -> Result<Matrix> {
693		crate::matrix::add_scalar(rhs, self)
694	}
695}