1use float8::F8E4M3;
9use fuel_backend_contract::dyn_backend::{DynBackendDevice, DynBackendStorage};
10use fuel_cpu_kernels::erf;
11use fuel_ir::conv::{ParamsConv1D, ParamsConv2D, ParamsConvTranspose1D, ParamsConvTranspose2D};
12use fuel_ir::op::{BinaryOp, CmpOp, ReduceOp, UnaryOp};
13use fuel_ir::{
14 CpuStorage as HostBuffer, DType, DeviceLocation, Error, Layout, Result, Scalar, Shape,
15};
16use half::{bf16, f16};
17use num_traits::Float as _;
18use std::any::Any;
19use std::sync::Arc;
20
21use crate::chassis::unary::{quiet_f32, quiet_f64};
22use crate::utils::{Map1, Map1Any, Map2, Map2InPlace, Map2U8, binary_map, unary_map};
23
24#[derive(Debug, Clone)]
33pub struct CpuStorage(pub HostBuffer);
34
35pub type CpuBackendStorage = CpuStorage;
37
38impl CpuStorage {
39 pub fn into_inner(self) -> HostBuffer {
41 self.0
42 }
43
44 pub fn inner(&self) -> &HostBuffer {
46 &self.0
47 }
48}
49
50impl From<HostBuffer> for CpuStorage {
51 fn from(s: HostBuffer) -> Self {
52 Self(s)
53 }
54}
55
56impl From<CpuStorage> for HostBuffer {
57 fn from(s: CpuStorage) -> Self {
58 s.0
59 }
60}
61
62impl fuel_backend_contract::backend::HostStorage for CpuStorage {
63 fn as_host_buffer_ref(&self) -> fuel_ir::Result<fuel_ir::HostBufferRef<'_>> {
64 Ok(self.0.as_ref())
65 }
66
67 fn into_host_buffer(self) -> fuel_ir::Result<fuel_ir::HostBuffer> {
70 Ok(self.0)
71 }
72}
73
74#[derive(Debug, Clone, Copy)]
80pub struct CpuBackendDevice;
81
82impl fuel_backend_contract::backend::BackendRuntime for CpuBackendDevice {
83 fn available_bytes(&self) -> Option<u64> {
89 crate::system_memory::available_bytes()
90 }
91
92 fn total_bytes(&self) -> Option<u64> {
96 crate::system_memory::total_bytes()
97 }
98}
99
100fn downcast(s: &dyn DynBackendStorage) -> Result<&CpuStorage> {
106 s.as_any().downcast_ref::<CpuStorage>().ok_or_else(|| {
107 Error::DeviceMismatchBinaryOp {
108 lhs: DeviceLocation::Cpu,
109 rhs: s.device_dyn().location_dyn(),
110 op: "dyn_backend",
111 }
112 .bt()
113 })
114}
115
116fn downcast_mut(s: &mut dyn DynBackendStorage) -> Result<&mut CpuStorage> {
118 let loc = s.device_dyn().location_dyn();
119 s.as_any_mut().downcast_mut::<CpuStorage>().ok_or_else(|| {
120 Error::DeviceMismatchBinaryOp {
121 lhs: DeviceLocation::Cpu,
122 rhs: loc,
123 op: "dyn_backend",
124 }
125 .bt()
126 })
127}
128
129fn cpu_unary_op(s: &HostBuffer, layout: &Layout, op: UnaryOp) -> Result<HostBuffer> {
135 use UnaryOp::*;
136
137 match op {
142 Exp => float_unary(
143 s,
144 layout,
145 |v: f32| quiet_f32(v.exp()),
146 |v: f64| quiet_f64(v.exp()),
147 ),
148 Log => float_unary(
149 s,
150 layout,
151 |v: f32| quiet_f32(v.ln()),
152 |v: f64| quiet_f64(v.ln()),
153 ),
154 Sin => float_unary(
155 s,
156 layout,
157 |v: f32| quiet_f32(v.sin()),
158 |v: f64| quiet_f64(v.sin()),
159 ),
160 Cos => float_unary(
161 s,
162 layout,
163 |v: f32| quiet_f32(v.cos()),
164 |v: f64| quiet_f64(v.cos()),
165 ),
166 Tanh => float_unary(
167 s,
168 layout,
169 |v: f32| quiet_f32(v.tanh()),
170 |v: f64| quiet_f64(v.tanh()),
171 ),
172 Neg => all_unary_neg(s, layout),
173 Recip => float_unary(s, layout, |v: f32| v.recip(), |v: f64| v.recip()),
174 Sqr => all_unary_sqr(s, layout),
175 Sqrt => float_unary(
176 s,
177 layout,
178 |v: f32| quiet_f32(v.sqrt()),
179 |v: f64| quiet_f64(v.sqrt()),
180 ),
181 Abs => all_unary_abs(s, layout),
182 Relu => all_unary_relu(s, layout),
183 Floor => float_unary_identity_int(
184 s,
185 layout,
186 |v: f32| quiet_f32(v.floor()),
187 |v: f64| quiet_f64(v.floor()),
188 ),
189 Ceil => float_unary_identity_int(
190 s,
191 layout,
192 |v: f32| quiet_f32(v.ceil()),
193 |v: f64| quiet_f64(v.ceil()),
194 ),
195 Round => float_unary_identity_int(
196 s,
197 layout,
198 |v: f32| quiet_f32(v.round()),
199 |v: f64| quiet_f64(v.round()),
200 ),
201 Sign => all_unary_sign(s, layout),
202 GeluTanh => float_unary(s, layout, gelu_f32, gelu_f64),
203 Gelu => float_unary(s, layout, gelu_erf_f32, gelu_erf_f64),
204 Erf => float_unary(s, layout, erf::erf_f32, erf::erf_f64),
205 Silu => float_unary(s, layout, silu_f32, silu_f64),
206 }
207}
208
209#[allow(clippy::excessive_precision)]
210fn gelu_f32(v: f32) -> f32 {
211 0.5 * v
212 * (1.0 + f32::tanh(0.79788456080286535587989211986876373 * v * (1.0 + 0.044715 * v * v)))
213}
214
215#[allow(clippy::excessive_precision)]
216fn gelu_f64(v: f64) -> f64 {
217 0.5 * v
218 * (1.0 + f64::tanh(0.79788456080286535587989211986876373 * v * (1.0 + 0.044715 * v * v)))
219}
220
221fn gelu_erf_f32(v: f32) -> f32 {
222 (erf::erf_f32(v * std::f32::consts::FRAC_1_SQRT_2) + 1.) * 0.5 * v
223}
224
225fn gelu_erf_f64(v: f64) -> f64 {
226 (erf::erf_f64(v * std::f64::consts::FRAC_1_SQRT_2) + 1.) * 0.5 * v
227}
228
229fn silu_f32(v: f32) -> f32 {
230 v / (1.0 + (-v).exp())
231}
232
233fn silu_f64(v: f64) -> f64 {
234 v / (1.0 + (-v).exp())
235}
236
237fn float_unary(
240 s: &HostBuffer,
241 layout: &Layout,
242 f32_fn: impl Fn(f32) -> f32 + Copy,
243 f64_fn: impl Fn(f64) -> f64 + Copy,
244) -> Result<HostBuffer> {
245 match s {
246 HostBuffer::BF16(data) => {
247 let out = unary_map(data, layout, |v: bf16| bf16::from_f32(f32_fn(v.to_f32())));
248 Ok(HostBuffer::BF16(out))
249 }
250 HostBuffer::F16(data) => {
251 let out = unary_map(data, layout, |v: f16| f16::from_f32(f32_fn(v.to_f32())));
252 Ok(HostBuffer::F16(out))
253 }
254 HostBuffer::F32(data) => {
255 let out = unary_map(data, layout, f32_fn);
256 Ok(HostBuffer::F32(out))
257 }
258 HostBuffer::F64(data) => {
259 let out = unary_map(data, layout, f64_fn);
260 Ok(HostBuffer::F64(out))
261 }
262 HostBuffer::F8E4M3(data) => {
263 let out = unary_map(data, layout, |v: F8E4M3| {
264 F8E4M3::from_f32(f32_fn(v.to_f32()))
265 });
266 Ok(HostBuffer::F8E4M3(out))
267 }
268 other => Err(Error::UnsupportedDTypeForOp(other.dtype(), "unary_op").bt()),
269 }
270}
271
272fn float_unary_identity_int(
274 s: &HostBuffer,
275 layout: &Layout,
276 f32_fn: impl Fn(f32) -> f32 + Copy,
277 f64_fn: impl Fn(f64) -> f64 + Copy,
278) -> Result<HostBuffer> {
279 match s {
280 HostBuffer::U8(d) => Ok(HostBuffer::U8(unary_map(d, layout, |v| v))),
281 HostBuffer::U32(d) => Ok(HostBuffer::U32(unary_map(d, layout, |v| v))),
282 HostBuffer::I16(d) => Ok(HostBuffer::I16(unary_map(d, layout, |v| v))),
283 HostBuffer::I32(d) => Ok(HostBuffer::I32(unary_map(d, layout, |v| v))),
284 HostBuffer::I64(d) => Ok(HostBuffer::I64(unary_map(d, layout, |v| v))),
285 _ => float_unary(s, layout, f32_fn, f64_fn),
286 }
287}
288
289fn all_unary_neg(s: &HostBuffer, layout: &Layout) -> Result<HostBuffer> {
290 match s {
291 HostBuffer::BF16(d) => Ok(HostBuffer::BF16(unary_map(d, layout, |v: bf16| -v))),
292 HostBuffer::F16(d) => Ok(HostBuffer::F16(unary_map(d, layout, |v: f16| -v))),
293 HostBuffer::F32(d) => Ok(HostBuffer::F32(unary_map(d, layout, |v: f32| -v))),
294 HostBuffer::F64(d) => Ok(HostBuffer::F64(unary_map(d, layout, |v: f64| -v))),
295 HostBuffer::I16(d) => Ok(HostBuffer::I16(unary_map(d, layout, |v: i16| {
300 v.wrapping_neg()
301 }))),
302 HostBuffer::I32(d) => Ok(HostBuffer::I32(unary_map(d, layout, |v: i32| {
303 v.wrapping_neg()
304 }))),
305 HostBuffer::I64(d) => Ok(HostBuffer::I64(unary_map(d, layout, |v: i64| {
306 v.wrapping_neg()
307 }))),
308 HostBuffer::F8E4M3(d) => Ok(HostBuffer::F8E4M3(unary_map(d, layout, |v: F8E4M3| -v))),
309 other => Err(Error::UnsupportedDTypeForOp(other.dtype(), "neg").bt()),
310 }
311}
312
313fn all_unary_sqr(s: &HostBuffer, layout: &Layout) -> Result<HostBuffer> {
314 match s {
315 HostBuffer::BF16(d) => Ok(HostBuffer::BF16(unary_map(d, layout, |v: bf16| v * v))),
316 HostBuffer::F16(d) => Ok(HostBuffer::F16(unary_map(d, layout, |v: f16| v * v))),
317 HostBuffer::F32(d) => Ok(HostBuffer::F32(unary_map(d, layout, |v: f32| v * v))),
318 HostBuffer::F64(d) => Ok(HostBuffer::F64(unary_map(d, layout, |v: f64| v * v))),
319 HostBuffer::U8(d) => Ok(HostBuffer::U8(unary_map(d, layout, |v: u8| v * v))),
320 HostBuffer::U32(d) => Ok(HostBuffer::U32(unary_map(d, layout, |v: u32| v * v))),
321 HostBuffer::I16(d) => Ok(HostBuffer::I16(unary_map(d, layout, |v: i16| v * v))),
322 HostBuffer::I32(d) => Ok(HostBuffer::I32(unary_map(d, layout, |v: i32| v * v))),
323 HostBuffer::I64(d) => Ok(HostBuffer::I64(unary_map(d, layout, |v: i64| v * v))),
324 HostBuffer::F8E4M3(d) => Ok(HostBuffer::F8E4M3(unary_map(d, layout, |v: F8E4M3| v * v))),
325 other => Err(Error::UnsupportedDTypeForOp(other.dtype(), "sqr").bt()),
326 }
327}
328
329fn all_unary_abs(s: &HostBuffer, layout: &Layout) -> Result<HostBuffer> {
330 match s {
331 HostBuffer::BF16(d) => Ok(HostBuffer::BF16(unary_map(d, layout, |v: bf16| {
345 bf16::from_bits(v.to_bits() & 0x7FFF)
346 }))),
347 HostBuffer::F16(d) => Ok(HostBuffer::F16(unary_map(d, layout, |v: f16| {
348 f16::from_bits(v.to_bits() & 0x7FFF)
349 }))),
350 HostBuffer::F32(d) => Ok(HostBuffer::F32(unary_map(d, layout, |v: f32| v.abs()))),
351 HostBuffer::F64(d) => Ok(HostBuffer::F64(unary_map(d, layout, |v: f64| v.abs()))),
352 HostBuffer::U8(d) => Ok(HostBuffer::U8(unary_map(d, layout, |v: u8| v))),
353 HostBuffer::U32(d) => Ok(HostBuffer::U32(unary_map(d, layout, |v: u32| v))),
354 HostBuffer::I16(d) => Ok(HostBuffer::I16(unary_map(d, layout, |v: i16| {
358 v.wrapping_abs()
359 }))),
360 HostBuffer::I32(d) => Ok(HostBuffer::I32(unary_map(d, layout, |v: i32| {
361 v.wrapping_abs()
362 }))),
363 HostBuffer::I64(d) => Ok(HostBuffer::I64(unary_map(d, layout, |v: i64| {
364 v.wrapping_abs()
365 }))),
366 HostBuffer::F8E4M3(d) => Ok(HostBuffer::F8E4M3(unary_map(d, layout, |v: F8E4M3| {
375 v.abs()
376 }))),
377 other => Err(Error::UnsupportedDTypeForOp(other.dtype(), "abs").bt()),
378 }
379}
380
381fn all_unary_relu(s: &HostBuffer, layout: &Layout) -> Result<HostBuffer> {
387 match s {
388 HostBuffer::BF16(d) => Ok(HostBuffer::BF16(unary_map(d, layout, |v: bf16| {
389 if v.is_nan() { v } else { v.max(bf16::ZERO) }
390 }))),
391 HostBuffer::F16(d) => Ok(HostBuffer::F16(unary_map(d, layout, |v: f16| {
392 if v.is_nan() { v } else { v.max(f16::ZERO) }
393 }))),
394 HostBuffer::F32(d) => Ok(HostBuffer::F32(unary_map(d, layout, |v: f32| {
395 if v.is_nan() { v } else { v.max(0.0) }
396 }))),
397 HostBuffer::F64(d) => Ok(HostBuffer::F64(unary_map(d, layout, |v: f64| {
398 if v.is_nan() { v } else { v.max(0.0) }
399 }))),
400 HostBuffer::U8(d) => Ok(HostBuffer::U8(unary_map(d, layout, |v: u8| v))),
401 HostBuffer::U32(d) => Ok(HostBuffer::U32(unary_map(d, layout, |v: u32| v))),
402 HostBuffer::I16(d) => Ok(HostBuffer::I16(unary_map(d, layout, |v: i16| v.max(0)))),
403 HostBuffer::I32(d) => Ok(HostBuffer::I32(unary_map(d, layout, |v: i32| v.max(0)))),
404 HostBuffer::I64(d) => Ok(HostBuffer::I64(unary_map(d, layout, |v: i64| v.max(0)))),
405 HostBuffer::F8E4M3(d) => Ok(HostBuffer::F8E4M3(unary_map(d, layout, |v: F8E4M3| {
406 if v.is_nan() { v } else { v.max(F8E4M3::ZERO) }
407 }))),
408 other => Err(Error::UnsupportedDTypeForOp(other.dtype(), "relu").bt()),
409 }
410}
411
412fn all_unary_sign(s: &HostBuffer, layout: &Layout) -> Result<HostBuffer> {
413 match s {
414 HostBuffer::BF16(d) => Ok(HostBuffer::BF16(unary_map(d, layout, |v: bf16| {
415 bf16::from((v > bf16::ZERO) as i8) - bf16::from((v < bf16::ZERO) as i8)
416 }))),
417 HostBuffer::F16(d) => Ok(HostBuffer::F16(unary_map(d, layout, |v: f16| {
418 f16::from((v > f16::ZERO) as i8) - f16::from((v < f16::ZERO) as i8)
419 }))),
420 HostBuffer::F32(d) => Ok(HostBuffer::F32(unary_map(d, layout, |v: f32| {
421 f32::from(v > 0.) - f32::from(v < 0.)
422 }))),
423 HostBuffer::F64(d) => Ok(HostBuffer::F64(unary_map(d, layout, |v: f64| {
424 f64::from(v > 0.) - f64::from(v < 0.)
425 }))),
426 HostBuffer::I16(d) => Ok(HostBuffer::I16(unary_map(d, layout, |v: i16| v.signum()))),
427 HostBuffer::I32(d) => Ok(HostBuffer::I32(unary_map(d, layout, |v: i32| v.signum()))),
428 HostBuffer::I64(d) => Ok(HostBuffer::I64(unary_map(d, layout, |v: i64| v.signum()))),
429 HostBuffer::F8E4M3(d) => Ok(HostBuffer::F8E4M3(unary_map(d, layout, |v: F8E4M3| {
430 let f = v.to_f32();
431 F8E4M3::from_f32(f32::from(f > 0.) - f32::from(f < 0.))
432 }))),
433 other => Err(Error::UnsupportedDTypeForOp(other.dtype(), "sign").bt()),
434 }
435}
436
437fn cpu_binary_op(
439 lhs: &HostBuffer,
440 rhs: &HostBuffer,
441 lhs_l: &Layout,
442 rhs_l: &Layout,
443 op: BinaryOp,
444) -> Result<HostBuffer> {
445 use BinaryOp::*;
446 match op {
447 Add => all_binary(
452 lhs,
453 rhs,
454 lhs_l,
455 rhs_l,
456 |a, b| a + b,
457 |a: i64, b: i64| a.wrapping_add(b),
458 "add",
459 ),
460 Sub => all_binary(
461 lhs,
462 rhs,
463 lhs_l,
464 rhs_l,
465 |a, b| a - b,
466 |a: i64, b: i64| a.wrapping_sub(b),
467 "sub",
468 ),
469 Mul => all_binary(
470 lhs,
471 rhs,
472 lhs_l,
473 rhs_l,
474 |a, b| a * b,
475 |a: i64, b: i64| a.wrapping_mul(b),
476 "mul",
477 ),
478 Div => all_binary(
485 lhs,
486 rhs,
487 lhs_l,
488 rhs_l,
489 |a, b| a / b,
490 |a: i64, b: i64| (a as f64 / b as f64) as i64,
491 "div",
492 ),
493 Maximum => all_binary(
501 lhs,
502 rhs,
503 lhs_l,
504 rhs_l,
505 |a, b| {
506 if a.is_nan() {
510 a
511 } else if b.is_nan() || a < b {
512 b
513 } else {
514 a
515 }
516 },
517 |a: i64, b: i64| a.max(b),
521 "maximum",
522 ),
523 Minimum => all_binary(
524 lhs,
525 rhs,
526 lhs_l,
527 rhs_l,
528 |a, b| {
529 if a.is_nan() {
533 a
534 } else if b.is_nan() || a > b {
535 b
536 } else {
537 a
538 }
539 },
540 |a: i64, b: i64| a.min(b),
541 "minimum",
542 ),
543 }
544}
545
546fn all_binary<F, G>(
547 lhs: &HostBuffer,
548 rhs: &HostBuffer,
549 lhs_l: &Layout,
550 rhs_l: &Layout,
551 f: F,
552 fi: G,
553 op_name: &'static str,
554) -> Result<HostBuffer>
555where
556 F: Fn(f64, f64) -> f64 + Copy,
557 G: Fn(i64, i64) -> i64 + Copy,
567{
568 macro_rules! dispatch_pair {
570 ($lhs_v:ident, $rhs_v:ident, $variant:ident, $conv_fn:expr, $result_fn:expr) => {{
571 let out = binary_map(lhs_l, rhs_l, $lhs_v, $rhs_v, |a, b| {
572 let result = f($conv_fn(a), $conv_fn(b));
573 $result_fn(result)
574 });
575 Ok(HostBuffer::$variant(out))
576 }};
577 }
578
579 match (lhs, rhs) {
580 (HostBuffer::BF16(a), HostBuffer::BF16(b)) => {
581 dispatch_pair!(a, b, BF16, |v: bf16| v.to_f64(), |v: f64| {
582 fuel_ir::round::bf16_from_f64(v)
583 })
584 }
585 (HostBuffer::F16(a), HostBuffer::F16(b)) => {
586 dispatch_pair!(a, b, F16, |v: f16| v.to_f64(), |v: f64| {
587 fuel_ir::round::f16_from_f64(v)
588 })
589 }
590 (HostBuffer::F32(a), HostBuffer::F32(b)) => {
591 let out = binary_map(lhs_l, rhs_l, a, b, |a, b| f(a as f64, b as f64) as f32);
592 Ok(HostBuffer::F32(out))
593 }
594 (HostBuffer::F64(a), HostBuffer::F64(b)) => {
595 let out = binary_map(lhs_l, rhs_l, a, b, &f);
596 Ok(HostBuffer::F64(out))
597 }
598 (HostBuffer::U8(a), HostBuffer::U8(b)) => {
599 let out = binary_map(lhs_l, rhs_l, a, b, |a, b| fi(a as i64, b as i64) as u8);
600 Ok(HostBuffer::U8(out))
601 }
602 (HostBuffer::U32(a), HostBuffer::U32(b)) => {
603 let out = binary_map(lhs_l, rhs_l, a, b, |a, b| fi(a as i64, b as i64) as u32);
604 Ok(HostBuffer::U32(out))
605 }
606 (HostBuffer::I16(a), HostBuffer::I16(b)) => {
607 let out = binary_map(lhs_l, rhs_l, a, b, |a, b| fi(a as i64, b as i64) as i16);
608 Ok(HostBuffer::I16(out))
609 }
610 (HostBuffer::I32(a), HostBuffer::I32(b)) => {
611 let out = binary_map(lhs_l, rhs_l, a, b, |a, b| fi(a as i64, b as i64) as i32);
612 Ok(HostBuffer::I32(out))
613 }
614 (HostBuffer::I64(a), HostBuffer::I64(b)) => {
615 let out = binary_map(lhs_l, rhs_l, a, b, fi);
616 Ok(HostBuffer::I64(out))
617 }
618 (HostBuffer::F8E4M3(a), HostBuffer::F8E4M3(b)) => {
619 dispatch_pair!(a, b, F8E4M3, |v: F8E4M3| v.to_f64(), |v: f64| {
620 F8E4M3::from_f64(v)
621 })
622 }
623 _ => Err(Error::DTypeMismatchBinaryOp {
624 lhs: lhs.dtype(),
625 rhs: rhs.dtype(),
626 op: op_name,
627 }
628 .bt()),
629 }
630}
631
632fn copy2d_<T: Copy>(
637 src: &[T],
638 dst: &mut [T],
639 d1: usize,
640 d2: usize,
641 src_stride1: usize,
642 dst_stride1: usize,
643 src_offset: usize,
644 dst_offset: usize,
645) {
646 for i1 in 0..d1 {
647 let dst_idx = i1 * dst_stride1 + dst_offset;
648 let src_idx = i1 * src_stride1 + src_offset;
649 dst[dst_idx..dst_idx + d2].copy_from_slice(&src[src_idx..src_idx + d2]);
650 }
651}
652
653fn copy_strided_src_<T: Copy>(src: &[T], dst: &mut [T], dst_offset: usize, src_l: &Layout) {
654 match src_l.strided_blocks() {
655 fuel_ir::StridedBlocks::SingleBlock { start_offset, len } => {
656 let to_copy = (dst.len() - dst_offset).min(len);
657 dst[dst_offset..dst_offset + to_copy]
658 .copy_from_slice(&src[start_offset..start_offset + to_copy])
659 }
660 fuel_ir::StridedBlocks::MultipleBlocks {
661 block_start_index,
662 block_len: 1,
663 } => {
664 for (dst_index, src_index) in block_start_index.enumerate() {
665 let dst_index = dst_index + dst_offset;
666 if dst_index >= dst.len() {
667 break;
668 }
669 dst[dst_index] = src[src_index];
670 }
671 }
672 fuel_ir::StridedBlocks::MultipleBlocks {
673 block_start_index,
674 block_len,
675 } => {
676 let mut dst_index = dst_offset;
677 for src_index in block_start_index {
678 let next_dst_index = dst_index + block_len;
679 if dst_index >= dst.len() {
680 break;
681 }
682 let to_copy = usize::min(block_len, dst.len() - dst_index);
683 dst[dst_index..dst_index + to_copy]
684 .copy_from_slice(&src[src_index..src_index + to_copy]);
685 dst_index = next_dst_index;
686 }
687 }
688 }
689}
690
691fn elu<T: num_traits::Float>(v: T, alpha: T) -> T {
692 if v.is_sign_positive() {
693 v
694 } else {
695 (v.exp() - T::one()) * alpha
696 }
697}
698
699impl DynBackendStorage for CpuStorage {
704 fn try_clone_dyn(&self, _layout: &Layout) -> Result<Box<dyn DynBackendStorage>> {
705 Ok(Box::new(self.clone()))
706 }
707
708 fn dtype_dyn(&self) -> DType {
709 self.0.dtype()
710 }
711
712 fn device_dyn(&self) -> &dyn DynBackendDevice {
713 &CpuBackendDevice
715 }
716
717 fn device_arc_dyn(&self) -> Arc<dyn DynBackendDevice> {
718 Arc::new(CpuBackendDevice)
719 }
720
721 fn to_host_buffer_dyn(&self) -> Result<HostBuffer> {
722 Ok(self.0.clone())
723 }
724
725 fn affine_dyn(
726 &self,
727 layout: &Layout,
728 mul: f64,
729 add: f64,
730 ) -> Result<Box<dyn DynBackendStorage>> {
731 let result = Map1::map(&crate::ops::Affine(mul, add), &self.0, layout)?;
732 Ok(Box::new(CpuStorage(result)))
733 }
734
735 fn powf_dyn(&self, layout: &Layout, e: f64) -> Result<Box<dyn DynBackendStorage>> {
736 use num_traits::Float;
737 let result = match &self.0 {
738 HostBuffer::BF16(d) => HostBuffer::BF16(unary_map(d, layout, |v: bf16| {
739 v.powf(fuel_ir::round::bf16_from_f64(e))
740 })),
741 HostBuffer::F16(d) => HostBuffer::F16(unary_map(d, layout, |v: f16| {
742 v.powf(fuel_ir::round::f16_from_f64(e))
743 })),
744 HostBuffer::F32(d) => {
745 HostBuffer::F32(unary_map(d, layout, |v: f32| quiet_f32(v.powf(e as f32))))
746 }
747 HostBuffer::F64(d) => {
748 HostBuffer::F64(unary_map(d, layout, |v: f64| quiet_f64(v.powf(e))))
749 }
750 HostBuffer::F8E4M3(d) => HostBuffer::F8E4M3(unary_map(d, layout, |v: F8E4M3| {
751 v.powf(F8E4M3::from_f64(e))
752 })),
753 other => return Err(Error::UnsupportedDTypeForOp(other.dtype(), "powf").bt()),
754 };
755 Ok(Box::new(CpuStorage(result)))
756 }
757
758 fn elu_dyn(&self, layout: &Layout, alpha: f64) -> Result<Box<dyn DynBackendStorage>> {
759 let result = match &self.0 {
760 HostBuffer::BF16(d) => HostBuffer::BF16(unary_map(d, layout, |v| {
761 elu(v, fuel_ir::round::bf16_from_f64(alpha))
762 })),
763 HostBuffer::F16(d) => HostBuffer::F16(unary_map(d, layout, |v| {
764 elu(v, fuel_ir::round::f16_from_f64(alpha))
765 })),
766 HostBuffer::F32(d) => HostBuffer::F32(unary_map(d, layout, |v| elu(v, alpha as f32))),
767 HostBuffer::F64(d) => HostBuffer::F64(unary_map(d, layout, |v| elu(v, alpha))),
768 HostBuffer::F8E4M3(d) => {
769 HostBuffer::F8E4M3(unary_map(d, layout, |v| elu(v, F8E4M3::from_f64(alpha))))
770 }
771 other => return Err(Error::UnsupportedDTypeForOp(other.dtype(), "elu").bt()),
772 };
773 Ok(Box::new(CpuStorage(result)))
774 }
775
776 fn reduce_op_dyn(
777 &self,
778 op: ReduceOp,
779 layout: &Layout,
780 axes: &[usize],
781 ) -> Result<Box<dyn DynBackendStorage>> {
782 let result = match op {
783 ReduceOp::Sum => {
784 let src_dims = layout.dims();
785 let mut dst_dims = src_dims.to_vec();
786 for &dim in axes.iter() {
787 dst_dims[dim] = 1;
788 }
789 let dst_shape = Shape::from(dst_dims);
790 let mut reduce_dims = axes.to_vec();
791 reduce_dims.sort();
792 let reduce_dims_and_stride: Vec<_> = reduce_dims
793 .iter()
794 .map(|&d| (src_dims[d], src_dims[d + 1..].iter().product::<usize>()))
795 .collect();
796 Map1::map(
797 &crate::ops::ReduceSum {
798 dst_shape: &dst_shape,
799 reduce_dims: &reduce_dims,
800 reduce_dims_and_stride,
801 },
802 &self.0,
803 layout,
804 )?
805 }
806 ReduceOp::Min | ReduceOp::ArgMin | ReduceOp::Max | ReduceOp::ArgMax => {
807 let reduce_dim_index = match axes {
808 [dim] => *dim,
809 _ => {
810 let op_name = match op {
811 ReduceOp::Min => "min",
812 ReduceOp::ArgMin => "argmin",
813 ReduceOp::Max => "max",
814 ReduceOp::ArgMax => "argmax",
815 _ => unreachable!(),
816 };
817 return Err(Error::OnlySingleDimension {
818 op: op_name,
819 dims: axes.to_vec(),
820 }
821 .bt());
822 }
823 };
824 let (use_min, return_index) = match op {
825 ReduceOp::Min => (true, false),
826 ReduceOp::ArgMin => (true, true),
827 ReduceOp::Max => (false, false),
828 ReduceOp::ArgMax => (false, true),
829 _ => unreachable!(),
830 };
831 Map1Any::map(
832 &crate::ops::ReduceIndex {
833 reduce_dim_index,
834 use_min,
835 return_index,
836 },
837 &self.0,
838 layout,
839 )?
840 }
841 };
842 Ok(Box::new(CpuStorage(result)))
843 }
844
845 fn cmp_dyn(
846 &self,
847 op: CmpOp,
848 rhs: &dyn DynBackendStorage,
849 lhs_layout: &Layout,
850 rhs_layout: &Layout,
851 ) -> Result<Box<dyn DynBackendStorage>> {
852 let rhs = downcast(rhs)?;
853 let result = Map2U8::map(
854 &crate::ops::Cmp(op),
855 &self.0,
856 lhs_layout,
857 &rhs.0,
858 rhs_layout,
859 )?;
860 Ok(Box::new(CpuStorage(result)))
861 }
862
863 fn to_dtype_dyn(&self, layout: &Layout, dtype: DType) -> Result<Box<dyn DynBackendStorage>> {
864 let result = cpu_to_dtype(&self.0, layout, dtype)?;
871 Ok(Box::new(CpuStorage(result)))
872 }
873
874 fn unary_op_dyn(&self, layout: &Layout, op: UnaryOp) -> Result<Box<dyn DynBackendStorage>> {
875 let result = cpu_unary_op(&self.0, layout, op)?;
876 Ok(Box::new(CpuStorage(result)))
877 }
878
879 fn binary_op_dyn(
880 &self,
881 rhs: &dyn DynBackendStorage,
882 lhs_layout: &Layout,
883 rhs_layout: &Layout,
884 op: BinaryOp,
885 ) -> Result<Box<dyn DynBackendStorage>> {
886 let rhs = downcast(rhs)?;
887 let result = cpu_binary_op(&self.0, &rhs.0, lhs_layout, rhs_layout, op)?;
888 Ok(Box::new(CpuStorage(result)))
889 }
890
891 fn where_cond_dyn(
892 &self,
893 cond_layout: &Layout,
894 on_true: &dyn DynBackendStorage,
895 on_true_layout: &Layout,
896 on_false: &dyn DynBackendStorage,
897 on_false_layout: &Layout,
898 ) -> Result<Box<dyn DynBackendStorage>> {
899 let t = downcast(on_true)?;
900 let f = downcast(on_false)?;
901 let result = match &self.0 {
902 HostBuffer::U8(pred) => Map2::map(
903 &crate::ops::WCond(pred, cond_layout),
904 &t.0,
905 on_true_layout,
906 &f.0,
907 on_false_layout,
908 )?,
909 HostBuffer::U32(pred) => Map2::map(
910 &crate::ops::WCond(pred, cond_layout),
911 &t.0,
912 on_true_layout,
913 &f.0,
914 on_false_layout,
915 )?,
916 HostBuffer::I16(pred) => Map2::map(
917 &crate::ops::WCond(pred, cond_layout),
918 &t.0,
919 on_true_layout,
920 &f.0,
921 on_false_layout,
922 )?,
923 HostBuffer::I32(pred) => Map2::map(
924 &crate::ops::WCond(pred, cond_layout),
925 &t.0,
926 on_true_layout,
927 &f.0,
928 on_false_layout,
929 )?,
930 HostBuffer::I64(pred) => Map2::map(
931 &crate::ops::WCond(pred, cond_layout),
932 &t.0,
933 on_true_layout,
934 &f.0,
935 on_false_layout,
936 )?,
937 HostBuffer::Bool(pred) => Map2::map(
940 &crate::ops::WCond(pred, cond_layout),
941 &t.0,
942 on_true_layout,
943 &f.0,
944 on_false_layout,
945 )?,
946 _ => return Err(Error::UnsupportedDTypeForOp(self.0.dtype(), "where-cond").bt()),
947 };
948 Ok(Box::new(CpuStorage(result)))
949 }
950
951 fn conv1d_dyn(
952 &self,
953 l: &Layout,
954 kernel: &dyn DynBackendStorage,
955 kernel_l: &Layout,
956 params: &ParamsConv1D,
957 ) -> Result<Box<dyn DynBackendStorage>> {
958 let kernel = downcast(kernel)?;
959 let l_k = params.k_size;
961 let col = Map1::map(
962 &crate::ops::Im2Col1D {
963 l_k,
964 padding: params.padding,
965 stride: params.stride,
966 dilation: params.dilation,
967 },
968 &self.0,
969 l,
970 )?;
971 let b = params.b_size;
972 let n = params.c_out;
973 let l_out = params.l_out();
974 let k = l_k * params.c_in;
975 let m = l_out;
976 let col_l = Layout::contiguous((b, m, k));
977 let kernel_l_c = if kernel_l.is_contiguous() {
978 Layout::contiguous_with_offset((1, n, k), kernel_l.start_offset())
979 .transpose(1, 2)?
980 .broadcast_as((b, k, n))?
981 } else {
982 let mut kernel_c = unsafe { cpu_alloc_uninit(kernel_l.shape(), kernel.0.dtype())? };
984 cpu_copy_strided_src(&kernel.0, &mut kernel_c, 0, kernel_l)?;
985 let new_l = Layout::contiguous_with_offset((1, n, k), kernel_l.start_offset())
986 .transpose(1, 2)?
987 .broadcast_as((b, k, n))?;
988 return {
990 let res = Map2::map(
991 &crate::ops::MatMul((b, m, n, k)),
992 &col,
993 &col_l,
994 &kernel_c,
995 &new_l,
996 )?;
997 let res_l = Layout::contiguous((b, l_out, params.c_out)).transpose(1, 2)?;
998 let mut res_t = unsafe { cpu_alloc_uninit(res_l.shape(), res.dtype())? };
999 cpu_copy_strided_src(&res, &mut res_t, 0, &res_l)?;
1000 Ok(Box::new(CpuStorage(res_t)))
1001 };
1002 };
1003 let res = Map2::map(
1004 &crate::ops::MatMul((b, m, n, k)),
1005 &col,
1006 &col_l,
1007 &kernel.0,
1008 &kernel_l_c,
1009 )?;
1010 let res_l = Layout::contiguous((b, l_out, params.c_out)).transpose(1, 2)?;
1011 let mut res_t = unsafe { cpu_alloc_uninit(res_l.shape(), res.dtype())? };
1012 cpu_copy_strided_src(&res, &mut res_t, 0, &res_l)?;
1013 Ok(Box::new(CpuStorage(res_t)))
1014 }
1015
1016 fn conv_transpose1d_dyn(
1017 &self,
1018 l: &Layout,
1019 kernel: &dyn DynBackendStorage,
1020 kernel_l: &Layout,
1021 params: &ParamsConvTranspose1D,
1022 ) -> Result<Box<dyn DynBackendStorage>> {
1023 let kernel = downcast(kernel)?;
1024 let result = Map2::map(
1025 &crate::ops::ConvTranspose1D(params),
1026 &self.0,
1027 l,
1028 &kernel.0,
1029 kernel_l,
1030 )?;
1031 Ok(Box::new(CpuStorage(result)))
1032 }
1033
1034 fn conv2d_dyn(
1035 &self,
1036 l: &Layout,
1037 kernel: &dyn DynBackendStorage,
1038 kernel_l: &Layout,
1039 params: &ParamsConv2D,
1040 ) -> Result<Box<dyn DynBackendStorage>> {
1041 let kernel = downcast(kernel)?;
1042 let result = Map2::map(
1043 &crate::conv2d::Conv2D(params),
1044 &self.0,
1045 l,
1046 &kernel.0,
1047 kernel_l,
1048 )?;
1049 Ok(Box::new(CpuStorage(result)))
1050 }
1051
1052 fn conv_transpose2d_dyn(
1053 &self,
1054 l: &Layout,
1055 kernel: &dyn DynBackendStorage,
1056 kernel_l: &Layout,
1057 params: &ParamsConvTranspose2D,
1058 ) -> Result<Box<dyn DynBackendStorage>> {
1059 let kernel = downcast(kernel)?;
1060 let result = Map2::map(
1061 &crate::ops::ConvTranspose2D(params),
1062 &self.0,
1063 l,
1064 &kernel.0,
1065 kernel_l,
1066 )?;
1067 Ok(Box::new(CpuStorage(result)))
1068 }
1069
1070 fn avg_pool2d_dyn(
1071 &self,
1072 layout: &Layout,
1073 kernel: (usize, usize),
1074 stride: (usize, usize),
1075 ) -> Result<Box<dyn DynBackendStorage>> {
1076 let result = Map1::map(&crate::ops::AvgPool2D(kernel, stride), &self.0, layout)?;
1077 Ok(Box::new(CpuStorage(result)))
1078 }
1079
1080 fn max_pool2d_dyn(
1081 &self,
1082 layout: &Layout,
1083 kernel: (usize, usize),
1084 stride: (usize, usize),
1085 ) -> Result<Box<dyn DynBackendStorage>> {
1086 let result = Map1::map(&crate::ops::MaxPool2D(kernel, stride), &self.0, layout)?;
1087 Ok(Box::new(CpuStorage(result)))
1088 }
1089
1090 fn upsample_nearest1d_dyn(
1091 &self,
1092 layout: &Layout,
1093 target_size: usize,
1094 ) -> Result<Box<dyn DynBackendStorage>> {
1095 let result = Map1::map(&crate::ops::UpsampleNearest1D(target_size), &self.0, layout)?;
1096 Ok(Box::new(CpuStorage(result)))
1097 }
1098
1099 fn upsample_nearest2d_dyn(
1100 &self,
1101 layout: &Layout,
1102 target_h: usize,
1103 target_w: usize,
1104 ) -> Result<Box<dyn DynBackendStorage>> {
1105 let result = Map1::map(
1106 &crate::ops::UpsampleNearest2D(target_h, target_w),
1107 &self.0,
1108 layout,
1109 )?;
1110 Ok(Box::new(CpuStorage(result)))
1111 }
1112
1113 fn upsample_bilinear2d_dyn(
1114 &self,
1115 layout: &Layout,
1116 target_h: usize,
1117 target_w: usize,
1118 align_corners: bool,
1119 scale_h: Option<f64>,
1120 scale_w: Option<f64>,
1121 ) -> Result<Box<dyn DynBackendStorage>> {
1122 let result = Map1::map(
1123 &crate::ops::UpsampleBilinear2D {
1124 target_h,
1125 target_w,
1126 align_corners,
1127 scale_h_factor: scale_h,
1128 scale_w_factor: scale_w,
1129 },
1130 &self.0,
1131 layout,
1132 )?;
1133 Ok(Box::new(CpuStorage(result)))
1134 }
1135
1136 fn gather_dyn(
1137 &self,
1138 src_layout: &Layout,
1139 ids: &dyn DynBackendStorage,
1140 ids_layout: &Layout,
1141 dim: usize,
1142 ) -> Result<Box<dyn DynBackendStorage>> {
1143 let ids_s = downcast(ids)?;
1144 let result = match &ids_s.0 {
1145 HostBuffer::U8(ids) => Map1::map(
1146 &crate::ops::Gather {
1147 ids,
1148 ids_l: ids_layout,
1149 dim,
1150 },
1151 &self.0,
1152 src_layout,
1153 )?,
1154 HostBuffer::U32(ids) => Map1::map(
1155 &crate::ops::Gather {
1156 ids,
1157 ids_l: ids_layout,
1158 dim,
1159 },
1160 &self.0,
1161 src_layout,
1162 )?,
1163 HostBuffer::I64(ids) => Map1::map(
1164 &crate::ops::Gather {
1165 ids,
1166 ids_l: ids_layout,
1167 dim,
1168 },
1169 &self.0,
1170 src_layout,
1171 )?,
1172 _ => return Err(Error::UnsupportedDTypeForOp(ids_s.0.dtype(), "gather").bt()),
1173 };
1174 Ok(Box::new(CpuStorage(result)))
1175 }
1176
1177 fn scatter_set_dyn(
1178 &mut self,
1179 self_layout: &Layout,
1180 src: &dyn DynBackendStorage,
1181 src_layout: &Layout,
1182 ids: &dyn DynBackendStorage,
1183 ids_layout: &Layout,
1184 dim: usize,
1185 ) -> Result<()> {
1186 let ids_s = downcast(ids)?;
1187 let src_s = downcast(src)?;
1188 match &ids_s.0 {
1189 HostBuffer::U8(ids) => Map2InPlace::map(
1190 &crate::ops::Scatter::<_, crate::ops::Set>::new(ids, ids_layout, dim),
1191 &mut self.0,
1192 self_layout,
1193 &src_s.0,
1194 src_layout,
1195 )?,
1196 HostBuffer::U32(ids) => Map2InPlace::map(
1197 &crate::ops::Scatter::<_, crate::ops::Set>::new(ids, ids_layout, dim),
1198 &mut self.0,
1199 self_layout,
1200 &src_s.0,
1201 src_layout,
1202 )?,
1203 HostBuffer::I64(ids) => Map2InPlace::map(
1204 &crate::ops::Scatter::<_, crate::ops::Set>::new(ids, ids_layout, dim),
1205 &mut self.0,
1206 self_layout,
1207 &src_s.0,
1208 src_layout,
1209 )?,
1210 _ => return Err(Error::UnsupportedDTypeForOp(ids_s.0.dtype(), "scatter").bt()),
1211 };
1212 Ok(())
1213 }
1214
1215 fn scatter_add_set_dyn(
1216 &mut self,
1217 self_layout: &Layout,
1218 src: &dyn DynBackendStorage,
1219 src_layout: &Layout,
1220 ids: &dyn DynBackendStorage,
1221 ids_layout: &Layout,
1222 dim: usize,
1223 ) -> Result<()> {
1224 let ids_s = downcast(ids)?;
1225 let src_s = downcast(src)?;
1226 match &ids_s.0 {
1227 HostBuffer::U8(ids) => Map2InPlace::map(
1228 &crate::ops::Scatter::<_, crate::ops::Add>::new(ids, ids_layout, dim),
1229 &mut self.0,
1230 self_layout,
1231 &src_s.0,
1232 src_layout,
1233 )?,
1234 HostBuffer::U32(ids) => Map2InPlace::map(
1235 &crate::ops::Scatter::<_, crate::ops::Add>::new(ids, ids_layout, dim),
1236 &mut self.0,
1237 self_layout,
1238 &src_s.0,
1239 src_layout,
1240 )?,
1241 HostBuffer::I16(ids) => Map2InPlace::map(
1242 &crate::ops::Scatter::<_, crate::ops::Add>::new(ids, ids_layout, dim),
1243 &mut self.0,
1244 self_layout,
1245 &src_s.0,
1246 src_layout,
1247 )?,
1248 HostBuffer::I32(ids) => Map2InPlace::map(
1249 &crate::ops::Scatter::<_, crate::ops::Add>::new(ids, ids_layout, dim),
1250 &mut self.0,
1251 self_layout,
1252 &src_s.0,
1253 src_layout,
1254 )?,
1255 HostBuffer::I64(ids) => Map2InPlace::map(
1256 &crate::ops::Scatter::<_, crate::ops::Add>::new(ids, ids_layout, dim),
1257 &mut self.0,
1258 self_layout,
1259 &src_s.0,
1260 src_layout,
1261 )?,
1262 _ => return Err(Error::UnsupportedDTypeForOp(ids_s.0.dtype(), "scatter-add").bt()),
1263 };
1264 Ok(())
1265 }
1266
1267 fn index_select_dyn(
1268 &self,
1269 ids: &dyn DynBackendStorage,
1270 src_layout: &Layout,
1271 ids_layout: &Layout,
1272 dim: usize,
1273 ) -> Result<Box<dyn DynBackendStorage>> {
1274 let ids_s = downcast(ids)?;
1275 let result = match &ids_s.0 {
1276 HostBuffer::U8(ids) => Map1::map(
1277 &crate::ops::IndexSelect {
1278 ids,
1279 ids_l: ids_layout,
1280 dim,
1281 },
1282 &self.0,
1283 src_layout,
1284 )?,
1285 HostBuffer::U32(ids) => Map1::map(
1286 &crate::ops::IndexSelect {
1287 ids,
1288 ids_l: ids_layout,
1289 dim,
1290 },
1291 &self.0,
1292 src_layout,
1293 )?,
1294 HostBuffer::I64(ids) => Map1::map(
1295 &crate::ops::IndexSelect {
1296 ids,
1297 ids_l: ids_layout,
1298 dim,
1299 },
1300 &self.0,
1301 src_layout,
1302 )?,
1303 _ => return Err(Error::UnsupportedDTypeForOp(ids_s.0.dtype(), "index-select").bt()),
1304 };
1305 Ok(Box::new(CpuStorage(result)))
1306 }
1307
1308 fn index_add_dyn(
1309 &self,
1310 self_layout: &Layout,
1311 ids: &dyn DynBackendStorage,
1312 ids_layout: &Layout,
1313 src: &dyn DynBackendStorage,
1314 src_layout: &Layout,
1315 dim: usize,
1316 ) -> Result<Box<dyn DynBackendStorage>> {
1317 let ids_s = downcast(ids)?;
1318 let src_s = downcast(src)?;
1319 let result = match &ids_s.0 {
1320 HostBuffer::U8(ids) => {
1321 let ids = match ids_layout.contiguous_offsets() {
1322 Some((a, b)) => &ids[a..b],
1323 None => return Err(Error::RequiresContiguous { op: "index-add" }.bt()),
1324 };
1325 Map2::map(
1326 &crate::ops::IndexAdd { ids, dim },
1327 &self.0,
1328 self_layout,
1329 &src_s.0,
1330 src_layout,
1331 )?
1332 }
1333 HostBuffer::U32(ids) => {
1334 let ids = match ids_layout.contiguous_offsets() {
1335 Some((a, b)) => &ids[a..b],
1336 None => return Err(Error::RequiresContiguous { op: "index-add" }.bt()),
1337 };
1338 Map2::map(
1339 &crate::ops::IndexAdd { ids, dim },
1340 &self.0,
1341 self_layout,
1342 &src_s.0,
1343 src_layout,
1344 )?
1345 }
1346 HostBuffer::I16(ids) => {
1347 let ids = match ids_layout.contiguous_offsets() {
1348 Some((a, b)) => &ids[a..b],
1349 None => return Err(Error::RequiresContiguous { op: "index-add" }.bt()),
1350 };
1351 Map2::map(
1352 &crate::ops::IndexAdd { ids, dim },
1353 &self.0,
1354 self_layout,
1355 &src_s.0,
1356 src_layout,
1357 )?
1358 }
1359 HostBuffer::I32(ids) => {
1360 let ids = match ids_layout.contiguous_offsets() {
1361 Some((a, b)) => &ids[a..b],
1362 None => return Err(Error::RequiresContiguous { op: "index-add" }.bt()),
1363 };
1364 Map2::map(
1365 &crate::ops::IndexAdd { ids, dim },
1366 &self.0,
1367 self_layout,
1368 &src_s.0,
1369 src_layout,
1370 )?
1371 }
1372 HostBuffer::I64(ids) => {
1373 let ids = match ids_layout.contiguous_offsets() {
1374 Some((a, b)) => &ids[a..b],
1375 None => return Err(Error::RequiresContiguous { op: "index-add" }.bt()),
1376 };
1377 Map2::map(
1378 &crate::ops::IndexAdd { ids, dim },
1379 &self.0,
1380 self_layout,
1381 &src_s.0,
1382 src_layout,
1383 )?
1384 }
1385 _ => return Err(Error::UnsupportedDTypeForOp(ids_s.0.dtype(), "index-add").bt()),
1386 };
1387 Ok(Box::new(CpuStorage(result)))
1388 }
1389
1390 fn matmul_dyn(
1391 &self,
1392 rhs: &dyn DynBackendStorage,
1393 bmnk: (usize, usize, usize, usize),
1394 lhs_layout: &Layout,
1395 rhs_layout: &Layout,
1396 ) -> Result<Box<dyn DynBackendStorage>> {
1397 let rhs = downcast(rhs)?;
1398 let result = Map2::map(
1399 &crate::ops::MatMul(bmnk),
1400 &self.0,
1401 lhs_layout,
1402 &rhs.0,
1403 rhs_layout,
1404 )?;
1405 Ok(Box::new(CpuStorage(result)))
1406 }
1407
1408 fn copy_strided_src_dyn(
1409 &self,
1410 dst: &mut dyn DynBackendStorage,
1411 dst_offset: usize,
1412 src_layout: &Layout,
1413 ) -> Result<()> {
1414 let dst = downcast_mut(dst)?;
1415 cpu_copy_strided_src(&self.0, &mut dst.0, dst_offset, src_layout)
1416 }
1417
1418 fn copy2d_dyn(
1419 &self,
1420 dst: &mut dyn DynBackendStorage,
1421 d1: usize,
1422 d2: usize,
1423 src_stride1: usize,
1424 dst_stride1: usize,
1425 src_offset: usize,
1426 dst_offset: usize,
1427 ) -> Result<()> {
1428 let dst = downcast_mut(dst)?;
1429 cpu_copy2d(
1430 &self.0,
1431 &mut dst.0,
1432 d1,
1433 d2,
1434 src_stride1,
1435 dst_stride1,
1436 src_offset,
1437 dst_offset,
1438 )
1439 }
1440
1441 fn const_set_dyn(&mut self, value: Scalar, layout: &Layout) -> Result<()> {
1442 cpu_const_set(&mut self.0, value, layout)
1443 }
1444
1445 fn as_any(&self) -> &dyn Any {
1446 self
1447 }
1448
1449 fn as_any_mut(&mut self) -> &mut dyn Any {
1450 self
1451 }
1452}
1453
1454impl DynBackendDevice for CpuBackendDevice {
1459 fn location_dyn(&self) -> DeviceLocation {
1460 DeviceLocation::Cpu
1461 }
1462
1463 fn as_backend_runtime(&self) -> Option<&dyn fuel_backend_contract::backend::BackendRuntime> {
1464 Some(self)
1465 }
1466
1467 fn same_device_dyn(&self, other: &dyn DynBackendDevice) -> bool {
1468 other.as_any().downcast_ref::<CpuBackendDevice>().is_some()
1469 }
1470
1471 fn zeros_impl_dyn(&self, shape: &Shape, dtype: DType) -> Result<Box<dyn DynBackendStorage>> {
1472 let storage = cpu_zeros(shape, dtype)?;
1473 Ok(Box::new(CpuStorage(storage)))
1474 }
1475
1476 unsafe fn alloc_uninit_dyn(
1477 &self,
1478 shape: &Shape,
1479 dtype: DType,
1480 ) -> Result<Box<dyn DynBackendStorage>> {
1481 let storage = unsafe { cpu_alloc_uninit(shape, dtype)? };
1482 Ok(Box::new(CpuStorage(storage)))
1483 }
1484
1485 fn storage_from_host_buffer_dyn(&self, buf: &HostBuffer) -> Result<Box<dyn DynBackendStorage>> {
1486 Ok(Box::new(CpuStorage(buf.clone())))
1487 }
1488
1489 fn storage_from_host_buffer_owned_dyn(
1490 &self,
1491 buf: HostBuffer,
1492 ) -> Result<Box<dyn DynBackendStorage>> {
1493 Ok(Box::new(CpuStorage(buf)))
1494 }
1495
1496 fn rand_uniform_dyn(
1497 &self,
1498 shape: &Shape,
1499 dtype: DType,
1500 lo: f64,
1501 hi: f64,
1502 ) -> Result<Box<dyn DynBackendStorage>> {
1503 let storage = cpu_rand_uniform(shape, dtype, lo, hi)?;
1504 Ok(Box::new(CpuStorage(storage)))
1505 }
1506
1507 fn rand_normal_dyn(
1508 &self,
1509 shape: &Shape,
1510 dtype: DType,
1511 mean: f64,
1512 std: f64,
1513 ) -> Result<Box<dyn DynBackendStorage>> {
1514 let storage = cpu_rand_normal(shape, dtype, mean, std)?;
1515 Ok(Box::new(CpuStorage(storage)))
1516 }
1517
1518 fn set_seed_dyn(&self, _seed: u64) -> Result<()> {
1519 Err(Error::Msg("cannot seed the CPU rng with set_seed".into()).bt())
1520 }
1521
1522 fn get_current_seed_dyn(&self) -> Result<u64> {
1523 Err(Error::Msg("cannot get the CPU rng seed with get_current_seed".into()).bt())
1524 }
1525
1526 fn synchronize_dyn(&self) -> Result<()> {
1527 Ok(())
1528 }
1529
1530 fn as_any(&self) -> &dyn Any {
1531 self
1532 }
1533
1534 fn as_quantized_kernels(
1535 &self,
1536 ) -> Option<&dyn fuel_backend_contract::quantized::QuantizedDeviceKernels> {
1537 Some(self)
1538 }
1539}
1540
1541fn cpu_zeros(shape: &Shape, dtype: DType) -> Result<HostBuffer> {
1546 let elem_count = shape.elem_count();
1547 let storage = match dtype {
1548 DType::U8 => HostBuffer::U8(vec![0u8; elem_count]),
1549 DType::I8 => HostBuffer::I8(vec![0i8; elem_count]),
1550 DType::U32 => HostBuffer::U32(vec![0u32; elem_count]),
1551 DType::I16 => HostBuffer::I16(vec![0i16; elem_count]),
1552 DType::I32 => HostBuffer::I32(vec![0i32; elem_count]),
1553 DType::I64 => HostBuffer::I64(vec![0i64; elem_count]),
1554 DType::BF16 => HostBuffer::BF16(vec![bf16::ZERO; elem_count]),
1555 DType::F16 => HostBuffer::F16(vec![f16::ZERO; elem_count]),
1556 DType::F32 => HostBuffer::F32(vec![0f32; elem_count]),
1557 DType::F64 => HostBuffer::F64(vec![0f64; elem_count]),
1558 DType::F8E4M3 => HostBuffer::F8E4M3(vec![F8E4M3::ZERO; elem_count]),
1559 DType::F8E5M2 => return Err(Error::UnsupportedDTypeForOp(dtype, "zeros").bt()),
1566 DType::Bool => HostBuffer::Bool(vec![0u8; elem_count]),
1568 DType::F6E2M3 | DType::F6E3M2 | DType::F4 | DType::F8E8M0 | DType::F8E6M2 => {
1569 return Err(Error::UnsupportedDTypeForOp(dtype, "zeros").bt());
1570 }
1571 };
1572 Ok(storage)
1573}
1574
1575#[allow(clippy::uninit_vec)]
1576unsafe fn cpu_alloc_uninit(shape: &Shape, dtype: DType) -> Result<HostBuffer> {
1577 let elem_count = shape.elem_count();
1578 let storage = match dtype {
1579 DType::U8 => {
1580 let mut v = Vec::with_capacity(elem_count);
1581 unsafe { v.set_len(elem_count) };
1582 HostBuffer::U8(v)
1583 }
1584 DType::I8 => {
1585 let mut v = Vec::with_capacity(elem_count);
1586 unsafe { v.set_len(elem_count) };
1587 HostBuffer::I8(v)
1588 }
1589 DType::U32 => {
1590 let mut v = Vec::with_capacity(elem_count);
1591 unsafe { v.set_len(elem_count) };
1592 HostBuffer::U32(v)
1593 }
1594 DType::I16 => {
1595 let mut v = Vec::with_capacity(elem_count);
1596 unsafe { v.set_len(elem_count) };
1597 HostBuffer::I16(v)
1598 }
1599 DType::I32 => {
1600 let mut v = Vec::with_capacity(elem_count);
1601 unsafe { v.set_len(elem_count) };
1602 HostBuffer::I32(v)
1603 }
1604 DType::I64 => {
1605 let mut v = Vec::with_capacity(elem_count);
1606 unsafe { v.set_len(elem_count) };
1607 HostBuffer::I64(v)
1608 }
1609 DType::BF16 => {
1610 let mut v = Vec::with_capacity(elem_count);
1611 unsafe { v.set_len(elem_count) };
1612 HostBuffer::BF16(v)
1613 }
1614 DType::F16 => {
1615 let mut v = Vec::with_capacity(elem_count);
1616 unsafe { v.set_len(elem_count) };
1617 HostBuffer::F16(v)
1618 }
1619 DType::F32 => {
1620 let mut v = Vec::with_capacity(elem_count);
1621 unsafe { v.set_len(elem_count) };
1622 HostBuffer::F32(v)
1623 }
1624 DType::F64 => {
1625 let mut v = Vec::with_capacity(elem_count);
1626 unsafe { v.set_len(elem_count) };
1627 HostBuffer::F64(v)
1628 }
1629 DType::F8E4M3 => {
1630 let mut v = Vec::with_capacity(elem_count);
1631 unsafe { v.set_len(elem_count) };
1632 HostBuffer::F8E4M3(v)
1633 }
1634 DType::F8E5M2 => return Err(Error::UnsupportedDTypeForOp(dtype, "alloc_uninit").bt()),
1641 DType::Bool => {
1643 let mut v = Vec::with_capacity(elem_count);
1644 unsafe { v.set_len(elem_count) };
1645 HostBuffer::Bool(v)
1646 }
1647 DType::F6E2M3 | DType::F6E3M2 | DType::F4 | DType::F8E8M0 | DType::F8E6M2 => {
1648 return Err(Error::UnsupportedDTypeForOp(dtype, "alloc_uninit").bt());
1649 }
1650 };
1651 Ok(storage)
1652}
1653
1654fn sample_narrow_in_range<T: Copy>(
1660 rng: &mut impl rand::Rng,
1661 uniform: rand::distr::Uniform<f32>,
1662 min: f32,
1663 max: f32,
1664 narrow: impl Fn(f32) -> T,
1665 widen: impl Fn(T) -> f32,
1666) -> T {
1667 use rand::RngExt;
1668 for _ in 0..64 {
1669 let v = narrow(rng.sample::<f32, _>(uniform));
1670 let w = widen(v);
1671 if w >= min && w < max {
1672 return v;
1673 }
1674 }
1675 narrow(min)
1676}
1677
1678fn cpu_rand_uniform(shape: &Shape, dtype: DType, min: f64, max: f64) -> Result<HostBuffer> {
1679 use rand::prelude::*;
1680 let elem_count = shape.elem_count();
1681 let mut rng = rand::rng();
1682 match dtype {
1683 DType::BF16 => {
1684 let uniform =
1685 rand::distr::Uniform::new(min as f32, max as f32).map_err(fuel_ir::Error::wrap)?;
1686 let data: Vec<_> = (0..elem_count)
1687 .map(|_| {
1688 sample_narrow_in_range(
1689 &mut rng,
1690 uniform,
1691 min as f32,
1692 max as f32,
1693 bf16::from_f32,
1694 |x| x.to_f32(),
1695 )
1696 })
1697 .collect();
1698 Ok(HostBuffer::BF16(data))
1699 }
1700 DType::F16 => {
1701 let uniform =
1702 rand::distr::Uniform::new(min as f32, max as f32).map_err(fuel_ir::Error::wrap)?;
1703 let data: Vec<_> = (0..elem_count)
1704 .map(|_| {
1705 sample_narrow_in_range(
1706 &mut rng,
1707 uniform,
1708 min as f32,
1709 max as f32,
1710 f16::from_f32,
1711 |x| x.to_f32(),
1712 )
1713 })
1714 .collect();
1715 Ok(HostBuffer::F16(data))
1716 }
1717 DType::F8E4M3 => {
1718 let uniform =
1719 rand::distr::Uniform::new(min as f32, max as f32).map_err(fuel_ir::Error::wrap)?;
1720 let data: Vec<_> = (0..elem_count)
1721 .map(|_| {
1722 sample_narrow_in_range(
1723 &mut rng,
1724 uniform,
1725 min as f32,
1726 max as f32,
1727 F8E4M3::from_f32,
1728 |x| x.to_f32(),
1729 )
1730 })
1731 .collect();
1732 Ok(HostBuffer::F8E4M3(data))
1733 }
1734 DType::F32 => {
1735 let uniform =
1736 rand::distr::Uniform::new(min as f32, max as f32).map_err(fuel_ir::Error::wrap)?;
1737 let data: Vec<_> = (0..elem_count)
1738 .map(|_| rng.sample::<f32, _>(uniform))
1739 .collect();
1740 Ok(HostBuffer::F32(data))
1741 }
1742 DType::F64 => {
1743 let uniform = rand::distr::Uniform::new(min, max).map_err(fuel_ir::Error::wrap)?;
1744 let data: Vec<_> = (0..elem_count)
1745 .map(|_| rng.sample::<f64, _>(uniform))
1746 .collect();
1747 Ok(HostBuffer::F64(data))
1748 }
1749 _ => Err(Error::UnsupportedDTypeForOp(dtype, "rand_uniform").bt()),
1750 }
1751}
1752
1753fn cpu_rand_normal(shape: &Shape, dtype: DType, mean: f64, std: f64) -> Result<HostBuffer> {
1754 use rand::prelude::*;
1755 let elem_count = shape.elem_count();
1756 let mut rng = rand::rng();
1757 match dtype {
1758 DType::BF16 => {
1759 let normal =
1760 rand_distr::Normal::new(mean as f32, std as f32).map_err(fuel_ir::Error::wrap)?;
1761 let data: Vec<_> = (0..elem_count)
1762 .map(|_| bf16::from_f32(normal.sample(&mut rng)))
1763 .collect();
1764 Ok(HostBuffer::BF16(data))
1765 }
1766 DType::F16 => {
1767 let normal =
1768 rand_distr::Normal::new(mean as f32, std as f32).map_err(fuel_ir::Error::wrap)?;
1769 let data: Vec<_> = (0..elem_count)
1770 .map(|_| f16::from_f32(normal.sample(&mut rng)))
1771 .collect();
1772 Ok(HostBuffer::F16(data))
1773 }
1774 DType::F8E4M3 => {
1775 let normal =
1776 rand_distr::Normal::new(mean as f32, std as f32).map_err(fuel_ir::Error::wrap)?;
1777 let data: Vec<_> = (0..elem_count)
1778 .map(|_| F8E4M3::from_f32(normal.sample(&mut rng)))
1779 .collect();
1780 Ok(HostBuffer::F8E4M3(data))
1781 }
1782 DType::F32 => {
1783 let normal =
1784 rand_distr::Normal::new(mean as f32, std as f32).map_err(fuel_ir::Error::wrap)?;
1785 let data: Vec<_> = (0..elem_count).map(|_| normal.sample(&mut rng)).collect();
1786 Ok(HostBuffer::F32(data))
1787 }
1788 DType::F64 => {
1789 let normal = rand_distr::Normal::new(mean, std).map_err(fuel_ir::Error::wrap)?;
1790 let data: Vec<_> = (0..elem_count).map(|_| normal.sample(&mut rng)).collect();
1791 Ok(HostBuffer::F64(data))
1792 }
1793 _ => Err(Error::UnsupportedDTypeForOp(dtype, "rand_normal").bt()),
1794 }
1795}
1796
1797fn cpu_copy_strided_src(
1802 src: &HostBuffer,
1803 dst: &mut HostBuffer,
1804 dst_offset: usize,
1805 src_l: &Layout,
1806) -> Result<()> {
1807 match (src, dst) {
1808 (HostBuffer::U8(s), HostBuffer::U8(d)) => copy_strided_src_(s, d, dst_offset, src_l),
1809 (HostBuffer::U32(s), HostBuffer::U32(d)) => copy_strided_src_(s, d, dst_offset, src_l),
1810 (HostBuffer::I16(s), HostBuffer::I16(d)) => copy_strided_src_(s, d, dst_offset, src_l),
1811 (HostBuffer::I32(s), HostBuffer::I32(d)) => copy_strided_src_(s, d, dst_offset, src_l),
1812 (HostBuffer::I64(s), HostBuffer::I64(d)) => copy_strided_src_(s, d, dst_offset, src_l),
1813 (HostBuffer::BF16(s), HostBuffer::BF16(d)) => copy_strided_src_(s, d, dst_offset, src_l),
1814 (HostBuffer::F16(s), HostBuffer::F16(d)) => copy_strided_src_(s, d, dst_offset, src_l),
1815 (HostBuffer::F32(s), HostBuffer::F32(d)) => copy_strided_src_(s, d, dst_offset, src_l),
1816 (HostBuffer::F64(s), HostBuffer::F64(d)) => copy_strided_src_(s, d, dst_offset, src_l),
1817 (HostBuffer::F8E4M3(s), HostBuffer::F8E4M3(d)) => {
1818 copy_strided_src_(s, d, dst_offset, src_l)
1819 }
1820 (_, d) => {
1821 return Err(Error::DTypeMismatchBinaryOp {
1822 lhs: src.dtype(),
1823 rhs: d.dtype(),
1824 op: "copy_strided",
1825 }
1826 .bt());
1827 }
1828 }
1829 Ok(())
1830}
1831
1832fn cpu_copy2d(
1833 src: &HostBuffer,
1834 dst: &mut HostBuffer,
1835 d1: usize,
1836 d2: usize,
1837 src_s: usize,
1838 dst_s: usize,
1839 src_o: usize,
1840 dst_o: usize,
1841) -> Result<()> {
1842 match (src, dst) {
1843 (HostBuffer::U8(s), HostBuffer::U8(d)) => copy2d_(s, d, d1, d2, src_s, dst_s, src_o, dst_o),
1844 (HostBuffer::U32(s), HostBuffer::U32(d)) => {
1845 copy2d_(s, d, d1, d2, src_s, dst_s, src_o, dst_o)
1846 }
1847 (HostBuffer::I16(s), HostBuffer::I16(d)) => {
1848 copy2d_(s, d, d1, d2, src_s, dst_s, src_o, dst_o)
1849 }
1850 (HostBuffer::I32(s), HostBuffer::I32(d)) => {
1851 copy2d_(s, d, d1, d2, src_s, dst_s, src_o, dst_o)
1852 }
1853 (HostBuffer::I64(s), HostBuffer::I64(d)) => {
1854 copy2d_(s, d, d1, d2, src_s, dst_s, src_o, dst_o)
1855 }
1856 (HostBuffer::BF16(s), HostBuffer::BF16(d)) => {
1857 copy2d_(s, d, d1, d2, src_s, dst_s, src_o, dst_o)
1858 }
1859 (HostBuffer::F16(s), HostBuffer::F16(d)) => {
1860 copy2d_(s, d, d1, d2, src_s, dst_s, src_o, dst_o)
1861 }
1862 (HostBuffer::F32(s), HostBuffer::F32(d)) => {
1863 copy2d_(s, d, d1, d2, src_s, dst_s, src_o, dst_o)
1864 }
1865 (HostBuffer::F64(s), HostBuffer::F64(d)) => {
1866 copy2d_(s, d, d1, d2, src_s, dst_s, src_o, dst_o)
1867 }
1868 (HostBuffer::F8E4M3(s), HostBuffer::F8E4M3(d)) => {
1869 copy2d_(s, d, d1, d2, src_s, dst_s, src_o, dst_o)
1870 }
1871 (_, d) => {
1872 return Err(Error::DTypeMismatchBinaryOp {
1873 lhs: src.dtype(),
1874 rhs: d.dtype(),
1875 op: "copy2d",
1876 }
1877 .bt());
1878 }
1879 }
1880 Ok(())
1881}
1882
1883fn cpu_const_set(storage: &mut HostBuffer, s: Scalar, l: &Layout) -> Result<()> {
1884 use fuel_ir::Scalar as S;
1885 fn set<T: fuel_ir::WithDType + Copy>(src: &mut [T], l: &Layout, s: T) {
1886 match l.strided_blocks() {
1887 fuel_ir::StridedBlocks::SingleBlock { start_offset, len } => {
1888 src[start_offset..start_offset + len].fill(s)
1889 }
1890 fuel_ir::StridedBlocks::MultipleBlocks {
1891 block_start_index,
1892 block_len: 1,
1893 } => {
1894 for src_index in block_start_index {
1895 src[src_index] = s;
1896 }
1897 }
1898 fuel_ir::StridedBlocks::MultipleBlocks {
1899 block_start_index,
1900 block_len,
1901 } => {
1902 for src_index in block_start_index {
1903 src[src_index..src_index + block_len].fill(s);
1904 }
1905 }
1906 }
1907 }
1908 match (storage, s) {
1909 (HostBuffer::BF16(d), S::BF16(v)) => set(d, l, v),
1910 (HostBuffer::F16(d), S::F16(v)) => set(d, l, v),
1911 (HostBuffer::F32(d), S::F32(v)) => set(d, l, v),
1912 (HostBuffer::F64(d), S::F64(v)) => set(d, l, v),
1913 (HostBuffer::U8(d), S::U8(v)) => set(d, l, v),
1914 (HostBuffer::U32(d), S::U32(v)) => set(d, l, v),
1915 (HostBuffer::I16(d), S::I16(v)) => set(d, l, v),
1916 (HostBuffer::I32(d), S::I32(v)) => set(d, l, v),
1917 (HostBuffer::I64(d), S::I64(v)) => set(d, l, v),
1918 (HostBuffer::F8E4M3(d), S::F8E4M3(v)) => set(d, l, v),
1919 (st, s) => {
1920 return Err(Error::Msg(format!(
1921 "const_set dtype mismatch, expected {:?} but got {:?}",
1922 st.dtype(),
1923 s
1924 ))
1925 .bt());
1926 }
1927 }
1928 Ok(())
1929}
1930
1931fn cpu_to_dtype(src: &HostBuffer, layout: &Layout, dtype: DType) -> Result<HostBuffer> {
1934 if src.dtype() == dtype {
1936 return match src {
1938 HostBuffer::U8(d) => Ok(HostBuffer::U8(unary_map(d, layout, |v: u8| v))),
1939 HostBuffer::U32(d) => Ok(HostBuffer::U32(unary_map(d, layout, |v: u32| v))),
1940 HostBuffer::I16(d) => Ok(HostBuffer::I16(unary_map(d, layout, |v: i16| v))),
1941 HostBuffer::I32(d) => Ok(HostBuffer::I32(unary_map(d, layout, |v: i32| v))),
1942 HostBuffer::I64(d) => Ok(HostBuffer::I64(unary_map(d, layout, |v: i64| v))),
1943 HostBuffer::BF16(d) => Ok(HostBuffer::BF16(unary_map(d, layout, |v: bf16| v))),
1944 HostBuffer::F16(d) => Ok(HostBuffer::F16(unary_map(d, layout, |v: f16| v))),
1945 HostBuffer::F32(d) => Ok(HostBuffer::F32(unary_map(d, layout, |v: f32| v))),
1946 HostBuffer::F64(d) => Ok(HostBuffer::F64(unary_map(d, layout, |v: f64| v))),
1947 HostBuffer::F8E4M3(d) => Ok(HostBuffer::F8E4M3(unary_map(d, layout, |v: F8E4M3| v))),
1948 HostBuffer::Bool(d) => Ok(HostBuffer::Bool(unary_map(d, layout, |v: u8| v))),
1950 _ => Err(Error::UnsupportedDTypeForOp(src.dtype(), "to_dtype").bt()),
1951 };
1952 }
1953
1954 let as_f64: Vec<f64> = match src {
1957 HostBuffer::U8(d) => unary_map(d, layout, |v: u8| v as f64),
1958 HostBuffer::U32(d) => unary_map(d, layout, |v: u32| v as f64),
1959 HostBuffer::I16(d) => unary_map(d, layout, |v: i16| v as f64),
1960 HostBuffer::I32(d) => unary_map(d, layout, |v: i32| v as f64),
1961 HostBuffer::I64(d) => unary_map(d, layout, |v: i64| v as f64),
1962 HostBuffer::BF16(d) => unary_map(d, layout, |v: bf16| v.to_f64()),
1963 HostBuffer::F16(d) => unary_map(d, layout, |v: f16| v.to_f64()),
1964 HostBuffer::F32(d) => unary_map(d, layout, |v: f32| v as f64),
1965 HostBuffer::F64(d) => unary_map(d, layout, |v: f64| v),
1966 HostBuffer::F8E4M3(d) => unary_map(d, layout, |v: F8E4M3| v.to_f64()),
1967 HostBuffer::Bool(d) => unary_map(d, layout, |v: u8| v as f64),
1970 _ => return Err(Error::UnsupportedDTypeForOp(src.dtype(), "to_dtype").bt()),
1971 };
1972
1973 match dtype {
1974 DType::U8 => Ok(HostBuffer::U8(
1975 as_f64.into_iter().map(|v| v as u8).collect(),
1976 )),
1977 DType::U32 => Ok(HostBuffer::U32(
1978 as_f64.into_iter().map(|v| v as u32).collect(),
1979 )),
1980 DType::I16 => Ok(HostBuffer::I16(
1981 as_f64.into_iter().map(|v| v as i16).collect(),
1982 )),
1983 DType::I32 => Ok(HostBuffer::I32(
1984 as_f64.into_iter().map(|v| v as i32).collect(),
1985 )),
1986 DType::I64 => Ok(HostBuffer::I64(
1987 as_f64.into_iter().map(|v| v as i64).collect(),
1988 )),
1989 DType::BF16 => Ok(HostBuffer::BF16(
1990 as_f64
1991 .into_iter()
1992 .map(fuel_ir::round::bf16_from_f64)
1993 .collect(),
1994 )),
1995 DType::F16 => Ok(HostBuffer::F16(
1996 as_f64
1997 .into_iter()
1998 .map(fuel_ir::round::f16_from_f64)
1999 .collect(),
2000 )),
2001 DType::F32 => Ok(HostBuffer::F32(
2002 as_f64.into_iter().map(|v| v as f32).collect(),
2003 )),
2004 DType::F64 => Ok(HostBuffer::F64(as_f64)),
2005 DType::F8E4M3 => Ok(HostBuffer::F8E4M3(
2006 as_f64.into_iter().map(F8E4M3::from_f64).collect(),
2007 )),
2008 DType::Bool => Ok(HostBuffer::Bool(
2013 as_f64
2014 .into_iter()
2015 .map(|v| if v != 0.0 { 1u8 } else { 0u8 })
2016 .collect(),
2017 )),
2018 _ => Err(Error::UnsupportedDTypeForOp(dtype, "to_dtype").bt()),
2019 }
2020}
2021
2022#[cfg(test)]
2025mod gap_275_e5m2_tripwire {
2026 use super::*;
2027
2028 #[test]
2060 fn f8e5m2_zeros_declines_until_someone_wires_it() {
2061 let shape = Shape::from_dims(&[4]);
2062
2063 assert!(
2068 cpu_zeros(&shape, DType::F8E4M3).is_ok(),
2069 "CONTROL FAILED: cpu_zeros declined F8E4M3, which IS wired. The F8E5M2 assertion below is therefore vacuous and this test proves nothing -- fix the control before reading the tripwire."
2070 );
2071
2072 assert!(
2073 cpu_zeros(&shape, DType::F8E5M2).is_err(),
2074 "GAP-275 TRIPWIRE FIRED: cpu_zeros now ACCEPTS DType::F8E5M2, so the E5M2 storage path has been wired. E5M2 conversions have NO boundary coverage, and float8 0.7.0 is_infinite returns true for 0x7E (the FINITE 448) on both f8 types. Add boundary tests modelled on cast_f32_f8e4m3_boundary_saturates_and_preserves_nan in byte_kernels.rs, then delete this test. See GAP-275."
2075 );
2076 }
2077}
2078
2079#[cfg(test)]
2080mod backend_runtime_tests {
2081 use super::*;
2082 use fuel_backend_contract::backend::BackendRuntime;
2083 use fuel_ir::backend::FitStatus;
2084
2085 #[test]
2090 fn cpu_backend_device_implements_backend_runtime() {
2091 let dev = CpuBackendDevice;
2092 let avail = dev.available_bytes();
2093 let total = dev.total_bytes();
2094 match (avail, total) {
2097 (Some(a), Some(t)) => {
2098 assert!(t > 0);
2099 assert!(a <= t);
2100 }
2101 (None, None) => {
2102 }
2104 mixed => panic!("inconsistent availability report: {mixed:?}"),
2105 }
2106 }
2107
2108 #[test]
2113 fn cpu_backend_device_would_fit_smoke() {
2114 let dev = CpuBackendDevice;
2115 let status = dev.would_fit(1);
2116 match (dev.available_bytes(), status) {
2117 (Some(_), FitStatus::Comfortable | FitStatus::Tight) => {
2118 }
2120 (None, FitStatus::Unknown) => {
2121 }
2123 other => panic!("unexpected (signal, status) pair: {other:?}"),
2124 }
2125 }
2126}
2127
2128#[cfg(test)]
2129mod binary_op_nan_tests {
2130 use super::*;
2137
2138 fn f32_buf(v: &[f32]) -> HostBuffer {
2139 HostBuffer::F32(v.to_vec())
2140 }
2141
2142 #[test]
2156 fn cpu_unary_abs_moves_a_signalling_nan_without_quieting_it() {
2157 const QUIET: u16 = 0x0040;
2158 let s = bf16::from_bits(0x7F81);
2159 assert_eq!(s.to_bits() & QUIET, 0, "fixture must be SIGNALLING");
2160
2161 assert_ne!(
2164 bf16::from_f32(s.to_f32().abs()).to_bits() & QUIET,
2165 0,
2166 "control failed: the promoting form no longer quiets, so the dyn-path assertion below is vacuous"
2167 );
2168
2169 let buf = HostBuffer::BF16(vec![s]);
2170 let l = Layout::contiguous(Shape::from_dims(&[1]));
2171 let out = cpu_unary_op(&buf, &l, UnaryOp::Abs).expect("abs");
2172 let HostBuffer::BF16(got) = out else {
2173 panic!("expected BF16 output");
2174 };
2175 assert_eq!(
2176 got[0].to_bits(),
2177 s.to_bits() & 0x7FFF,
2178 "dyn-path abs must clear the sign bit and PRESERVE the rest (0x{:04X} -> 0x{:04X}); it bound to the promoting `Float::abs` and quieted the NaN. See KISS-OPS-6.16-0009.",
2179 s.to_bits(),
2180 got[0].to_bits()
2181 );
2182 assert_eq!(
2183 got[0].to_bits() & QUIET,
2184 0,
2185 "dyn-path abs QUIETED a signalling NaN"
2186 );
2187 }
2188
2189 #[test]
2190 fn cpu_binary_op_maximum_minimum_propagate_nan() {
2191 let n = f32::NAN;
2192 let a = f32_buf(&[1.0, n, 3.0, n]);
2195 let b = f32_buf(&[n, 2.0, n, 4.0]);
2196 let l = Layout::contiguous(Shape::from_dims(&[4]));
2197
2198 for op in [BinaryOp::Maximum, BinaryOp::Minimum] {
2199 let out = cpu_binary_op(&a, &b, &l, &l, op).expect("binary op");
2200 let HostBuffer::F32(got) = out else {
2201 panic!("expected F32 output for {op:?}");
2202 };
2203 for (i, &g) in got.iter().enumerate() {
2204 assert!(
2205 g.is_nan(),
2206 "{op:?} at {i}: NaN must propagate (torch convention), got {g}"
2207 );
2208 }
2209 }
2210 }
2211
2212 #[test]
2213 fn cpu_binary_op_maximum_minimum_basic() {
2214 let a = f32_buf(&[1.0, 5.0]);
2217 let b = f32_buf(&[2.0, 3.0]);
2218 let l = Layout::contiguous(Shape::from_dims(&[2]));
2219
2220 let HostBuffer::F32(max) = cpu_binary_op(&a, &b, &l, &l, BinaryOp::Maximum).expect("max")
2221 else {
2222 panic!("expected F32");
2223 };
2224 assert_eq!(max, vec![2.0, 5.0]);
2225
2226 let HostBuffer::F32(min) = cpu_binary_op(&a, &b, &l, &l, BinaryOp::Minimum).expect("min")
2227 else {
2228 panic!("expected F32");
2229 };
2230 assert_eq!(min, vec![1.0, 3.0]);
2231 }
2232
2233 #[test]
2239 fn cpu_binary_op_integer_add_sub_mul_wrap_mod_2n() {
2240 let l = Layout::contiguous(Shape::from_dims(&[1]));
2241
2242 let a = HostBuffer::U8(vec![200]);
2243 let b = HostBuffer::U8(vec![100]);
2244 let HostBuffer::U8(sum) = cpu_binary_op(&a, &b, &l, &l, BinaryOp::Add).expect("add") else {
2245 panic!("expected U8");
2246 };
2247 assert_eq!(
2248 sum,
2249 vec![44],
2250 "200u8 + 100u8 must wrap to 44 (300 mod 256), not saturate"
2251 );
2252
2253 let a = HostBuffer::U8(vec![10]);
2254 let b = HostBuffer::U8(vec![20]);
2255 let HostBuffer::U8(diff) = cpu_binary_op(&a, &b, &l, &l, BinaryOp::Sub).expect("sub")
2256 else {
2257 panic!("expected U8");
2258 };
2259 assert_eq!(
2260 diff,
2261 vec![246],
2262 "10u8 - 20u8 must wrap to 246, not saturate to 0"
2263 );
2264
2265 let a = HostBuffer::I32(vec![i32::MAX]);
2266 let b = HostBuffer::I32(vec![1]);
2267 let HostBuffer::I32(sum) = cpu_binary_op(&a, &b, &l, &l, BinaryOp::Add).expect("add")
2268 else {
2269 panic!("expected I32");
2270 };
2271 assert_eq!(
2272 sum,
2273 vec![i32::MIN],
2274 "i32::MAX + 1 must wrap to i32::MIN, not saturate to i32::MAX"
2275 );
2276
2277 let a = HostBuffer::I32(vec![100_000]);
2278 let b = HostBuffer::I32(vec![100_000]);
2279 let HostBuffer::I32(prod) = cpu_binary_op(&a, &b, &l, &l, BinaryOp::Mul).expect("mul")
2280 else {
2281 panic!("expected I32");
2282 };
2283 assert_eq!(
2284 prod,
2285 vec![100_000i32.wrapping_mul(100_000)],
2286 "100_000 * 100_000 (exceeds i32 range) must wrap, not saturate"
2287 );
2288
2289 let a = HostBuffer::I32(vec![5]);
2292 let b = HostBuffer::I32(vec![9]);
2293 let HostBuffer::I32(max) = cpu_binary_op(&a, &b, &l, &l, BinaryOp::Maximum).expect("max")
2294 else {
2295 panic!("expected I32");
2296 };
2297 assert_eq!(
2298 max,
2299 vec![9],
2300 "positive control: Maximum still correct on integers"
2301 );
2302 }
2303
2304 #[test]
2311 fn cpu_unary_neg_abs_on_int_min_wraps_to_int_min_without_panicking() {
2312 let l = Layout::contiguous(Shape::from_dims(&[1]));
2313
2314 for dtype_buf in [
2315 HostBuffer::I16(vec![i16::MIN]),
2316 HostBuffer::I32(vec![i32::MIN]),
2317 HostBuffer::I64(vec![i64::MIN]),
2318 ] {
2319 let neg = cpu_unary_op(&dtype_buf, &l, UnaryOp::Neg).expect("neg must not panic");
2320 let abs = cpu_unary_op(&dtype_buf, &l, UnaryOp::Abs).expect("abs must not panic");
2321 match (&dtype_buf, &neg, &abs) {
2322 (HostBuffer::I16(_), HostBuffer::I16(n), HostBuffer::I16(a)) => {
2323 assert_eq!(n[0], i16::MIN, "neg(i16::MIN) must wrap to i16::MIN");
2324 assert_eq!(a[0], i16::MIN, "abs(i16::MIN) must wrap to i16::MIN");
2325 }
2326 (HostBuffer::I32(_), HostBuffer::I32(n), HostBuffer::I32(a)) => {
2327 assert_eq!(n[0], i32::MIN, "neg(i32::MIN) must wrap to i32::MIN");
2328 assert_eq!(a[0], i32::MIN, "abs(i32::MIN) must wrap to i32::MIN");
2329 }
2330 (HostBuffer::I64(_), HostBuffer::I64(n), HostBuffer::I64(a)) => {
2331 assert_eq!(n[0], i64::MIN, "neg(i64::MIN) must wrap to i64::MIN");
2332 assert_eq!(a[0], i64::MIN, "abs(i64::MIN) must wrap to i64::MIN");
2333 }
2334 _ => panic!("dtype mismatch in neg/abs output"),
2335 }
2336 }
2337
2338 let buf = HostBuffer::I32(vec![-5]);
2341 let HostBuffer::I32(n) = cpu_unary_op(&buf, &l, UnaryOp::Neg).expect("neg") else {
2342 panic!("expected I32");
2343 };
2344 assert_eq!(n, vec![5], "positive control: neg(-5) is still 5");
2345 }
2346}
2347
2348#[cfg(test)]
2349mod rand_bounds_tests {
2350 use super::*;
2351
2352 #[test]
2356 fn low_precision_uniform_stays_inside_half_open_range() {
2357 let shape = Shape::from((200_000,));
2358 match cpu_rand_uniform(&shape, DType::BF16, 0.0, 1.0).unwrap() {
2359 HostBuffer::BF16(v) => assert!(v.iter().all(|x| (0.0..1.0).contains(&x.to_f32()))),
2360 _ => panic!("wrong buffer"),
2361 }
2362 match cpu_rand_uniform(&shape, DType::F16, 0.0, 1.0).unwrap() {
2363 HostBuffer::F16(v) => assert!(v.iter().all(|x| (0.0..1.0).contains(&x.to_f32()))),
2364 _ => panic!("wrong buffer"),
2365 }
2366 }
2367
2368 #[test]
2371 fn naive_narrowing_escapes_the_range() {
2372 use rand::RngExt;
2373 let mut rng = rand::rng();
2374 let u = rand::distr::Uniform::new(0.0f32, 1.0).unwrap();
2375 let escaped = (0..200_000)
2376 .filter(|_| bf16::from_f32(rng.sample::<f32, _>(u)).to_f32() >= 1.0)
2377 .count();
2378 assert!(escaped > 0, "control found no escape in 200k draws");
2379 }
2380}