ionian_core/tensor/
mod.rs1pub mod dtype;
2pub mod shape;
3pub mod random;
4
5use crate::hardware::buffer::Buffer;
6use crate::hardware::device::DeviceType;
7pub use crate::tensor::dtype::DType;
8pub use crate::tensor::shape::Shape;
9
10pub struct Tensor {
11 buffer: Buffer,
12 shape: Shape,
13 dtype: DType,
14}
15
16impl Tensor {
17 pub fn new(shape: Shape, dtype: DType, device: DeviceType) -> Result<Self, String> {
18 let size_bytes = shape.num_elements() * dtype.size_of();
19 let buffer = Buffer::new(device, size_bytes)?;
20
21 Ok(Tensor {
22 buffer,
23 shape,
24 dtype,
25 })
26 }
27
28 pub fn shape(&self) -> &Shape {
29 &self.shape
30 }
31
32 pub fn dtype(&self) -> DType {
33 self.dtype
34 }
35
36 pub fn device(&self) -> DeviceType {
37 self.buffer.device_type()
38 }
39
40 pub fn fill_random(&mut self, seed: u64) {
41 if self.device() != DeviceType::Cpu {
42 return;
44 }
45
46 use crate::tensor::random::XorShift64;
47 let mut rng = XorShift64::new(seed);
48
49 match self.dtype {
50 DType::F32 => {
51 let count = self.shape.num_elements();
52 let mut data = Vec::with_capacity(count);
53 for _ in 0..count {
54 data.push(rng.next_f32());
55 }
56 unsafe {
57 let _ = self.buffer.write(&data);
58 }
59 }
60 _ => {
61 }
63 }
64 }
65
66 pub fn write_data<T: Copy>(&mut self, data: &[T]) -> Result<(), String> {
67 unsafe {
69 self.buffer.write(data)
70 }
71 }
72
73 pub fn read_data<T: Copy>(&self) -> Result<Vec<T>, String> {
74 let count = self.shape.num_elements();
76 unsafe {
77 self.buffer.read(count)
78 }
79 }
80}