1use std::{
4 marker::PhantomData,
5 ops::{Add, Div, Mul, Neg, Sub},
6 rc::Rc,
7 sync::atomic::{AtomicU64, Ordering},
8};
9
10use crate::{
11 Error, Result, Runtime,
12 runtime::{RuntimeHandle, Storage},
13};
14
15use crate::core::{DType, Element};
16
17#[derive(Clone)]
24pub struct Matrix {
25 runtime: RuntimeHandle,
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
34pub(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 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(&Runtime::current()?, shape, values)
81 }
82
83 pub fn new_from_slice_on<T: Element>(
92 runtime: &Runtime,
93 shape: impl Into<Vec<usize>>,
94 values: &[T],
95 ) -> Result<Self> {
96 Self::new_from_slice_handle(&runtime.handle(), shape.into(), values)
97 }
98
99 pub fn new_from_slice_on_same_runtime<T: Element>(
109 &self,
110 shape: impl Into<Vec<usize>>,
111 values: &[T],
112 ) -> Result<Self> {
113 Self::new_from_slice_handle(self.runtime(), shape.into(), values)
114 }
115
116 pub fn same_runtime(&self, other: &Matrix) -> bool {
118 self.runtime().same_as(other.runtime())
119 }
120
121 pub(crate) fn new_from_slice_handle<T: Element>(
122 runtime: &RuntimeHandle,
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 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 runtime.create_storage(&padded)?
147 } else {
148 runtime.create_storage(bytes)?
149 };
150
151 let semantic = matrix_semantic(&shape, T::DTYPE, None)?;
152 Ok(Self {
153 runtime: runtime.clone(),
154 storage,
155 shape,
156 dtype: T::DTYPE,
157 element_count,
158 semantic,
159 _not_send_sync: PhantomData,
160 })
161 }
162
163 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(&Runtime::current()?, shape, values)
175 }
176 pub fn new_from_f32_on(
187 runtime: &Runtime,
188 shape: impl Into<Vec<usize>>,
189 values: &[f32],
190 ) -> Result<Self> {
191 Self::new_from_slice_on(runtime, shape, values)
192 }
193
194 pub(crate) fn filled_f32(
195 runtime: &Runtime,
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(runtime, shape, &vec![value; element_count])
202 }
203
204 pub fn shape(&self) -> &[usize] {
206 &self.shape
207 }
208
209 pub const fn dtype(&self) -> DType {
211 self.dtype
212 }
213
214 pub const fn num_elements(&self) -> usize {
216 self.element_count
217 }
218
219 pub fn flatten(&self) -> Result<Self> {
228 crate::matrix::reshape(self, vec![self.element_count])
229 }
230
231 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 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 pub fn read_f32(&self) -> Result<Vec<f32>> {
288 self.read()
289 }
290
291 pub fn try_read_f32(&self) -> Result<Vec<f32>> {
299 self.try_read()
300 }
301
302 pub fn read<T: Element>(&self) -> Result<Vec<T>> {
311 self.validate_element::<T>()?;
312 if self.storage.needs_flush() {
313 self.runtime.flush()?;
314 }
315 self.storage.wait_ready()?;
316 self.read_ready::<T>()
317 }
318
319 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 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 runtime(&self) -> &RuntimeHandle {
361 &self.runtime
362 }
363
364 pub(crate) const fn element_count(&self) -> usize {
365 self.element_count
366 }
367
368 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 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 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 runtime: self.runtime.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 runtime: self.runtime.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 pub(crate) fn allocate(
469 runtime: &RuntimeHandle,
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 = runtime.create_storage(&vec![0_u8; byte_len])?;
479 let semantic = matrix_semantic(&shape, dtype, None)?;
480 Ok(Self {
481 runtime: runtime.clone(),
482 storage,
483 shape,
484 dtype,
485 element_count,
486 semantic,
487 _not_send_sync: PhantomData,
488 })
489 }
490
491 pub(crate) fn allocate_output(
495 runtime: &RuntimeHandle,
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 runtime.create_storage(&[])?
505 } else {
506 let byte_len = byte_storage_len(logical_byte_len, dtype)?;
507 runtime.create_output_storage(byte_len)?
508 };
509 let semantic = matrix_semantic(&shape, dtype, None)?;
510 Ok(Self {
511 runtime: runtime.clone(),
512 storage,
513 shape,
514 dtype,
515 element_count,
516 semantic,
517 _not_send_sync: PhantomData,
518 })
519 }
520
521 pub(crate) fn from_runtime_storage(
523 runtime: &RuntimeHandle,
524 storage: Storage,
525 shape: Vec<usize>,
526 dtype: DType,
527 ) -> Result<Self> {
528 runtime.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 runtime: runtime.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
593impl 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
604impl 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
612impl 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
620impl 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
628impl Neg for &Matrix {
630 type Output = Result<Matrix>;
631 fn neg(self) -> Result<Matrix> {
632 crate::matrix::neg(self)
633 }
634}
635
636impl Neg for Matrix {
639 type Output = Result<Matrix>;
640 fn neg(self) -> Result<Matrix> {
641 crate::matrix::neg(&self)
642 }
643}
644
645impl 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
653impl 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
661impl 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
669impl 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
677impl 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
689impl 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}