1use alloc::string::String;
2use core::marker::PhantomData;
3
4use ruda_tensor::{Backend, BackendTypes, DType, DTypeUsage, DTypeUsageSet, DeviceId, DeviceOps};
5use ruda_tensor::graph::{BackendIr, HandleKind, TensorHandle};
6use ruda_core::device::Device;
7
8use crate::qtensor::HostQTensor;
9use crate::tensor::HostTensor;
10
11pub use rurand_host::HostRng as HostRng;
12
13#[derive(Clone, Copy, Default, PartialEq, Eq, Hash)]
17pub struct HostDevice;
18
19impl Device for HostDevice {
20 fn to_id(&self) -> DeviceId {
21 DeviceId::new(0, 0)
22 }
23
24 fn from_id(_id: DeviceId) -> Self {
25 Self
26 }
27}
28
29impl DeviceOps for HostDevice {}
30
31impl core::fmt::Display for HostDevice {
32 fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
33 write!(f, "Cpu")
34 }
35}
36
37impl core::fmt::Debug for HostDevice {
38 fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
39 core::fmt::Display::fmt(self, f)
40 }
41}
42
43#[derive(Clone, Copy, Default)]
81pub struct Host<E = f32, I = i32> {
82 _e: PhantomData<E>,
83 _i: PhantomData<I>,
84}
85
86impl<E: core::fmt::Debug, I: core::fmt::Debug> core::fmt::Debug for Host<E, I> {
87 fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
88 f.debug_struct("Flex")
89 .field("_e", &self._e)
90 .field("_i", &self._i)
91 .finish()
92 }
93}
94
95impl BackendTypes for Host {
96 type Device = HostDevice;
97
98 type FloatTensorPrimitive = HostTensor;
99 type FloatElem = f32;
103
104 type IntTensorPrimitive = HostTensor;
105 type IntElem = i32;
110
111 type BoolTensorPrimitive = HostTensor;
112 type BoolElem = bool;
113
114 type QuantizedTensorPrimitive = HostQTensor;
115}
116
117impl Backend for Host {
118 fn name(_device: &Self::Device) -> String {
119 "flex".into()
120 }
121
122 fn seed(_device: &Self::Device, seed: u64) {
123 rurand_host::seed(seed)
124 }
125
126 fn device_count(_type_id: u16) -> usize {
127 1
128 }
129
130 fn dtype_usage(_device: &Self::Device, dtype: DType) -> DTypeUsageSet {
131 match dtype {
132 DType::F64 | DType::F32 | DType::F16 | DType::BF16 => {
134 DTypeUsage::Storage | DTypeUsage::Arithmetic
135 }
136 DType::I64 | DType::I32 | DType::I16 | DType::I8 => {
137 DTypeUsage::Storage | DTypeUsage::Arithmetic
138 }
139 DType::U64 | DType::U32 | DType::U16 | DType::U8 => {
140 DTypeUsage::Storage | DTypeUsage::Arithmetic
141 }
142 DType::Bool(ruda_tensor::BoolStore::Native | ruda_tensor::BoolStore::U8) => {
147 DTypeUsage::Storage | DTypeUsage::Arithmetic
148 }
149 DType::Bool(ruda_tensor::BoolStore::U32) => DTypeUsageSet::empty(),
150 DType::QFloat(_) => DTypeUsage::Storage.into(),
152 _ => DTypeUsageSet::empty(),
153 }
154 }
155}
156
157impl BackendIr for Host {
158 type Handle = HandleKind<Self>;
159
160 fn float_tensor(handle: TensorHandle<Self::Handle>) -> HostTensor {
161 match handle.handle {
162 HandleKind::Float(t) => t,
163 _ => panic!("Expected float handle, got {}", handle.handle.name()),
164 }
165 }
166
167 fn int_tensor(handle: TensorHandle<Self::Handle>) -> HostTensor {
168 match handle.handle {
169 HandleKind::Int(t) => t,
170 _ => panic!("Expected int handle, got {}", handle.handle.name()),
171 }
172 }
173
174 fn bool_tensor(handle: TensorHandle<Self::Handle>) -> HostTensor {
175 match handle.handle {
176 HandleKind::Bool(t) => t,
177 _ => panic!("Expected bool handle, got {}", handle.handle.name()),
178 }
179 }
180
181 fn quantized_tensor(handle: TensorHandle<Self::Handle>) -> HostQTensor {
182 match handle.handle {
183 HandleKind::Quantized(t) => t,
184 _ => panic!("Expected quantized handle, got {}", handle.handle.name()),
185 }
186 }
187
188 fn float_tensor_handle(tensor: HostTensor) -> Self::Handle {
189 HandleKind::Float(tensor)
190 }
191
192 fn int_tensor_handle(tensor: HostTensor) -> Self::Handle {
193 HandleKind::Int(tensor)
194 }
195
196 fn bool_tensor_handle(tensor: HostTensor) -> Self::Handle {
197 HandleKind::Bool(tensor)
198 }
199
200 fn quantized_tensor_handle(tensor: HostQTensor) -> Self::Handle {
201 HandleKind::Quantized(tensor)
202 }
203}
204
205#[cfg(test)]
208mod tests {
209 use ruda_tensor::{Backend, DType};
210 use ruda_tensor::BoolStore;
211
212 use super::*;
213
214 #[test]
215 fn supports_bool_native() {
216 let device = HostDevice;
217 assert!(Host::supports_dtype(
218 &device,
219 DType::Bool(BoolStore::Native)
220 ));
221 }
222
223 #[test]
224 fn supports_bool_u8() {
225 let device = HostDevice;
226 assert!(Host::supports_dtype(&device, DType::Bool(BoolStore::U8)));
227 }
228
229 #[test]
230 fn does_not_support_bool_u32() {
231 let device = HostDevice;
232 assert!(
233 !Host::supports_dtype(&device, DType::Bool(BoolStore::U32)),
234 "Bool(U32) should not be supported: flex stores bools as 1 byte per element"
235 );
236 }
237
238 #[test]
239 fn bool_empty_preserves_native_dtype() {
240 use ruda_tensor::ops::BoolTensorOps;
241 let shape = ruda_tensor::Shape::from(alloc::vec![3]);
242 let t = Host::bool_empty(shape, &HostDevice, ruda_tensor::BoolDType::Native);
243 assert_eq!(t.dtype(), DType::Bool(BoolStore::Native));
244 }
245
246 #[test]
247 fn bool_empty_preserves_u8_dtype() {
248 use ruda_tensor::ops::BoolTensorOps;
249 let shape = ruda_tensor::Shape::from(alloc::vec![3]);
250 let t = Host::bool_empty(shape, &HostDevice, ruda_tensor::BoolDType::U8);
251 assert_eq!(t.dtype(), DType::Bool(BoolStore::U8));
252 }
253
254 #[test]
255 fn device_prints_as_cpu() {
256 use alloc::format;
257 assert_eq!(format!("{:?}", HostDevice), "Cpu");
258 assert_eq!(format!("{}", HostDevice), "Cpu");
259 }
260
261 #[test]
262 fn comparison_preserves_out_dtype_native() {
263 let lhs = HostTensor::from_data(ruda_tensor::TensorData::from([1.0f32, 2.0, 3.0]));
264 let rhs = HostTensor::from_data(ruda_tensor::TensorData::from([2.0f32, 2.0, 1.0]));
265 let result = crate::ops::comparison::greater(lhs, rhs, ruda_tensor::BoolDType::Native);
266 assert_eq!(result.dtype(), DType::Bool(BoolStore::Native));
267 }
268
269 #[test]
270 fn comparison_preserves_out_dtype_u8() {
271 let lhs = HostTensor::from_data(ruda_tensor::TensorData::from([1.0f32, 2.0, 3.0]));
272 let rhs = HostTensor::from_data(ruda_tensor::TensorData::from([2.0f32, 2.0, 1.0]));
273 let result = crate::ops::comparison::greater(lhs, rhs, ruda_tensor::BoolDType::U8);
274 assert_eq!(result.dtype(), DType::Bool(BoolStore::U8));
275 }
276
277 #[test]
278 #[should_panic(expected = "Bool(U32)")]
279 fn comparison_u32_panics() {
280 let lhs = HostTensor::from_data(ruda_tensor::TensorData::from([1.0f32, 2.0]));
281 let rhs = HostTensor::from_data(ruda_tensor::TensorData::from([2.0f32, 1.0]));
282 let _ = crate::ops::comparison::greater(lhs, rhs, ruda_tensor::BoolDType::U32);
283 }
284
285 #[test]
286 fn bool_not_preserves_u8_dtype() {
287 use ruda_tensor::ops::BoolTensorOps;
288 let t_u8 = crate::ops::comparison::make_bool_tensor(
292 alloc::vec![1, 0, 1],
293 ruda_tensor::Shape::from(alloc::vec![3]),
294 ruda_tensor::BoolDType::U8,
295 );
296 let result = Host::bool_not(t_u8);
297 assert_eq!(result.dtype(), DType::Bool(BoolStore::U8));
298 let data: &[u8] = result.bytes();
299 assert_eq!(&data[..3], &[0, 1, 0]);
300 }
301}