Skip to main content

yscv_tensor/ops/
mod.rs

1use super::aligned::AlignedVec;
2use super::error::TensorError;
3use super::shape::{
4    broadcast_offset, broadcast_shape, compute_strides, increment_coords, shape_element_count,
5};
6use super::simd;
7use super::tensor::Tensor;
8
9impl Tensor {
10    // ── Cumulative operations ──────────────────────────────────────────
11
12    /// Cumulative sum along an axis.
13    pub fn cumsum(&self, axis: usize) -> Result<Self, TensorError> {
14        if axis >= self.rank() {
15            return Err(TensorError::InvalidAxis {
16                axis,
17                rank: self.rank(),
18            });
19        }
20        let shape = self.shape();
21        let outer: usize = shape[..axis].iter().product();
22        let axis_len = shape[axis];
23        let inner: usize = shape[axis + 1..].iter().product();
24        let mut out = self.data().to_vec();
25
26        for o in 0..outer {
27            for i in 0..inner {
28                let mut acc = 0.0f32;
29                for d in 0..axis_len {
30                    let idx = (o * axis_len + d) * inner + i;
31                    acc += out[idx];
32                    out[idx] = acc;
33                }
34            }
35        }
36        Tensor::from_vec(shape.to_vec(), out)
37    }
38
39    /// Cumulative product along an axis.
40    pub fn cumprod(&self, axis: usize) -> Result<Self, TensorError> {
41        if axis >= self.rank() {
42            return Err(TensorError::InvalidAxis {
43                axis,
44                rank: self.rank(),
45            });
46        }
47        let shape = self.shape();
48        let outer: usize = shape[..axis].iter().product();
49        let axis_len = shape[axis];
50        let inner: usize = shape[axis + 1..].iter().product();
51        let mut out = self.data().to_vec();
52
53        for o in 0..outer {
54            for i in 0..inner {
55                let mut acc = 1.0f32;
56                for d in 0..axis_len {
57                    let idx = (o * axis_len + d) * inner + i;
58                    acc *= out[idx];
59                    out[idx] = acc;
60                }
61            }
62        }
63        Tensor::from_vec(shape.to_vec(), out)
64    }
65
66    // ── FP16 conversion ────────────────────────────────────────────────
67
68    /// Convert all elements to IEEE 754 half-precision (FP16) bytes.
69    /// Returns `Vec<u16>` where each u16 is an FP16 bit pattern.
70    pub fn to_fp16(&self) -> Vec<u16> {
71        self.data().iter().map(|&v| f32_to_fp16(v)).collect()
72    }
73
74    /// Create a tensor from FP16 bit patterns.
75    pub fn from_fp16(shape: Vec<usize>, fp16_data: &[u16]) -> Result<Self, TensorError> {
76        let data: Vec<f32> = fp16_data.iter().map(|&v| fp16_to_f32(v)).collect();
77        Tensor::from_vec(shape, data)
78    }
79
80    // ── Internal helpers ────────────────────────────────────────────────
81
82    #[allow(unsafe_code)]
83    fn unary_op<F>(&self, op: F) -> Self
84    where
85        F: Fn(f32) -> f32,
86    {
87        let src = self.data();
88        let len = src.len();
89        // SAFETY: `uninitialized` allocates without zeroing.  The loop below
90        // writes every element before we ever read from `out_data`.
91        // SAFETY: every element is written by the operation before the tensor is read.
92        let mut out_data = unsafe { AlignedVec::<f32>::uninitialized(len) };
93        let inp = src.as_ptr();
94        let outp = out_data.as_mut_ptr();
95        unsafe {
96            for i in 0..len {
97                *outp.add(i) = op(*inp.add(i));
98            }
99        }
100        Tensor::from_raw_parts(self.shape(), self.strides(), out_data)
101    }
102
103    #[allow(unsafe_code)]
104    fn unary_simd_op(&self, kind: simd::UnaryKind) -> Self {
105        let len = self.len();
106        // SAFETY: `uninitialized` allocates without zeroing.  `unary_dispatch`
107        // writes every element before we ever read from `out`.
108        // SAFETY: every element is written by the operation before the tensor is read.
109        let mut out = unsafe { AlignedVec::<f32>::uninitialized(len) };
110        simd::unary_dispatch(self.data(), &mut out, kind);
111        Tensor::from_raw_parts(self.shape(), self.strides(), out)
112    }
113
114    fn reduce_axis<F>(&self, axis: usize, init: f32, combine: F) -> Result<Self, TensorError>
115    where
116        F: Fn(f32, f32) -> f32,
117    {
118        if axis >= self.rank() {
119            return Err(TensorError::InvalidAxis {
120                axis,
121                rank: self.rank(),
122            });
123        }
124
125        let mut out_shape = self.shape().to_vec();
126        out_shape.remove(axis);
127        let out_count =
128            shape_element_count(&out_shape).ok_or_else(|| TensorError::SizeOverflow {
129                shape: out_shape.clone(),
130            })?;
131        let out_strides = compute_strides(&out_shape).ok_or_else(|| TensorError::SizeOverflow {
132            shape: out_shape.clone(),
133        })?;
134        let mut out_data = vec![init; out_count];
135
136        let mut in_coords = vec![0usize; self.rank()];
137        for input in self.data().iter().copied() {
138            let mut out_offset = 0usize;
139            for (src_axis, coord) in in_coords.iter().copied().enumerate() {
140                if src_axis == axis {
141                    continue;
142                }
143                let dst_axis = if src_axis < axis {
144                    src_axis
145                } else {
146                    src_axis - 1
147                };
148                if !out_shape.is_empty() {
149                    out_offset += coord * out_strides[dst_axis];
150                }
151            }
152            out_data[out_offset] = combine(out_data[out_offset], input);
153            increment_coords(&mut in_coords, self.shape());
154        }
155
156        Tensor::from_vec(out_shape, out_data)
157    }
158
159    /// SIMD fast path for broadcasting a last-dim vector across all rows.
160    ///
161    /// Matches patterns like `[N, C] + [C]`, `[N, H, W, C] + [1, C]`, etc.
162    /// Returns `None` if the pattern doesn't match, so the caller falls through
163    /// to the generic broadcast loop.
164    #[allow(unsafe_code)]
165    fn binary_broadcast_lastdim_simd(
166        &self,
167        rhs: &Self,
168        kind: simd::BinaryKind,
169    ) -> Option<Result<Self, TensorError>> {
170        let lhs_shape = self.shape();
171        let rhs_shape = rhs.shape();
172
173        // Detect: rhs is a 1-D vector whose length equals lhs's last dim,
174        // or rhs shape is all-1 except the last dim which matches lhs's last dim.
175        let lhs_last = *lhs_shape.last()?;
176        if lhs_last == 0 {
177            return None;
178        }
179
180        let rhs_last = *rhs_shape.last()?;
181
182        // Check rhs is effectively a 1-D vector of size lhs_last:
183        // either shape [C] or shape [1, 1, ..., C]
184        let rhs_is_lastdim_vec =
185            rhs_last == lhs_last && rhs_shape.iter().rev().skip(1).all(|&d| d == 1);
186        // Also handle the symmetric case: lhs is the vector, rhs is the big tensor
187        let lhs_is_lastdim_vec =
188            lhs_last == rhs_last && lhs_shape.iter().rev().skip(1).all(|&d| d == 1);
189
190        // The fast path is safe only when the "row vector" side (all-1
191        // except possibly the last dim) ALSO has rank ≤ the other side
192        // and its 1-padding doesn't introduce extra dims. Otherwise the
193        // broadcast result has a higher rank than the big tensor, and
194        // we fall through to the general path so the output shape
195        // matches numpy semantics.
196        if rhs_is_lastdim_vec && !lhs_is_lastdim_vec {
197            // rhs is the row-vector. Safe iff rhs_shape is rank-1 OR
198            // rhs's rank is ≤ lhs's rank (otherwise rhs's leading 1s
199            // would still expand the broadcast rank past lhs's).
200            if rhs_shape.len() > lhs_shape.len() {
201                return None;
202            }
203            let lhs_data = self.data();
204            let rhs_data = rhs.data();
205            let row_len = lhs_last;
206            let num_rows = lhs_data.len() / row_len;
207            // SAFETY: every element is written by the operation before the tensor is read.
208            let mut out_data = unsafe { AlignedVec::<f32>::uninitialized(lhs_data.len()) };
209
210            for i in 0..num_rows {
211                let start = i * row_len;
212                let end = start + row_len;
213                simd::binary_dispatch(
214                    &lhs_data[start..end],
215                    &rhs_data[..row_len],
216                    &mut out_data[start..end],
217                    kind,
218                );
219            }
220
221            let out_strides = compute_strides(lhs_shape).expect("valid shape for strides");
222            Some(Ok(Tensor::from_raw_parts(
223                lhs_shape,
224                &out_strides,
225                out_data,
226            )))
227        } else if lhs_is_lastdim_vec && !rhs_is_lastdim_vec {
228            if lhs_shape.len() > rhs_shape.len() {
229                return None;
230            }
231            let lhs_data = self.data();
232            let rhs_data = rhs.data();
233            let row_len = rhs_last;
234            let num_rows = rhs_data.len() / row_len;
235            // SAFETY: every element is written by the operation before the tensor is read.
236            let mut out_data = unsafe { AlignedVec::<f32>::uninitialized(rhs_data.len()) };
237
238            for i in 0..num_rows {
239                let start = i * row_len;
240                let end = start + row_len;
241                simd::binary_dispatch(
242                    &lhs_data[..row_len],
243                    &rhs_data[start..end],
244                    &mut out_data[start..end],
245                    kind,
246                );
247            }
248
249            let out_strides = compute_strides(rhs_shape).expect("valid shape for strides");
250            Some(Ok(Tensor::from_raw_parts(
251                rhs_shape,
252                &out_strides,
253                out_data,
254            )))
255        } else {
256            None
257        }
258    }
259
260    /// Ternary `where` with NumPy-style broadcasting:
261    /// `out[i] = if cond[i] != 0 { x[i] } else { y[i] }`, where each
262    /// operand is broadcast to the common shape derived from all three.
263    /// Mirrors ONNX's `Where` op (and `np.where` semantics).
264    pub fn where_select(cond: &Self, x: &Self, y: &Self) -> Result<Self, TensorError> {
265        // Same-shape fast path — no broadcasting work needed.
266        if cond.shape() == x.shape() && cond.shape() == y.shape() {
267            let cd = cond.data();
268            let xd = x.data();
269            let yd = y.data();
270            let data: Vec<f32> = cd
271                .iter()
272                .zip(xd.iter().zip(yd.iter()))
273                .map(|(&c, (&xv, &yv))| if c != 0.0 { xv } else { yv })
274                .collect();
275            return Tensor::from_vec(cond.shape().to_vec(), data);
276        }
277        let cx_shape = broadcast_shape(cond.shape(), x.shape()).ok_or_else(|| {
278            TensorError::BroadcastIncompatible {
279                left: cond.shape().to_vec(),
280                right: x.shape().to_vec(),
281            }
282        })?;
283        let out_shape = broadcast_shape(&cx_shape, y.shape()).ok_or_else(|| {
284            TensorError::BroadcastIncompatible {
285                left: cx_shape.clone(),
286                right: y.shape().to_vec(),
287            }
288        })?;
289        let out_count =
290            shape_element_count(&out_shape).ok_or_else(|| TensorError::SizeOverflow {
291                shape: out_shape.clone(),
292            })?;
293        let mut out_data = vec![0.0_f32; out_count];
294        let mut coords = vec![0_usize; out_shape.len()];
295        let cd = cond.data();
296        let xd = x.data();
297        let yd = y.data();
298        for value in &mut out_data {
299            let c_off = broadcast_offset(cond.shape(), cond.strides(), &coords);
300            let x_off = broadcast_offset(x.shape(), x.strides(), &coords);
301            let y_off = broadcast_offset(y.shape(), y.strides(), &coords);
302            *value = if cd[c_off] != 0.0 {
303                xd[x_off]
304            } else {
305                yd[y_off]
306            };
307            increment_coords(&mut coords, &out_shape);
308        }
309        Tensor::from_vec(out_shape, out_data)
310    }
311
312    fn binary_broadcast_op<F>(&self, rhs: &Self, op: F) -> Result<Self, TensorError>
313    where
314        F: Fn(f32, f32) -> f32,
315    {
316        let out_shape = broadcast_shape(self.shape(), rhs.shape()).ok_or_else(|| {
317            TensorError::BroadcastIncompatible {
318                left: self.shape().to_vec(),
319                right: rhs.shape().to_vec(),
320            }
321        })?;
322
323        let out_count =
324            shape_element_count(&out_shape).ok_or_else(|| TensorError::SizeOverflow {
325                shape: out_shape.clone(),
326            })?;
327        let mut out_data = vec![0.0; out_count];
328        let mut coords = vec![0usize; out_shape.len()];
329
330        for value in &mut out_data {
331            let left_offset = broadcast_offset(self.shape(), self.strides(), &coords);
332            let right_offset = broadcast_offset(rhs.shape(), rhs.strides(), &coords);
333            *value = op(self.data()[left_offset], rhs.data()[right_offset]);
334            increment_coords(&mut coords, &out_shape);
335        }
336
337        Tensor::from_vec(out_shape, out_data)
338    }
339
340    /// SIMD-accelerated binary op for same-shape tensors (add/sub/mul/div).
341    #[allow(unsafe_code)]
342    #[allow(unsafe_code)]
343    fn binary_same_shape_simd(
344        &self,
345        rhs: &Self,
346        kind: simd::BinaryKind,
347    ) -> Result<Self, TensorError> {
348        let len = self.len();
349        // SAFETY: every element is written by the operation before the tensor is read.
350        let mut out_data = unsafe { AlignedVec::<f32>::uninitialized(len) };
351
352        // Multi-threaded for large tensors. Cross-platform:
353        // macOS → GCD dispatch_apply, others → rayon thread pool.
354        if len >= 100_000 {
355            let n = std::thread::available_parallelism()
356                .map(|p| p.get())
357                .unwrap_or(4);
358            let chunk = len.div_ceil(n);
359            let lp = self.data().as_ptr() as usize;
360            let rp = rhs.data().as_ptr() as usize;
361            let op = out_data.as_mut_ptr() as usize;
362
363            #[cfg(target_os = "macos")]
364            {
365                use std::ffi::c_void;
366                #[allow(unsafe_code)]
367                unsafe extern "C" {
368                    fn dispatch_get_global_queue(id: isize, flags: usize) -> *const c_void;
369                    fn dispatch_apply_f(
370                        n: usize,
371                        q: *const c_void,
372                        ctx: *mut c_void,
373                        work: unsafe extern "C" fn(*mut c_void, usize),
374                    );
375                }
376                struct Ctx {
377                    lp: usize,
378                    rp: usize,
379                    op: usize,
380                    chunk: usize,
381                    len: usize,
382                    kind: simd::BinaryKind,
383                }
384                let ctx = Ctx {
385                    lp,
386                    rp,
387                    op,
388                    chunk,
389                    len,
390                    kind,
391                };
392                unsafe extern "C" fn work(raw: *mut c_void, t: usize) {
393                    let c = unsafe { &*(raw as *const Ctx) };
394                    let start = t * c.chunk;
395                    let end = (start + c.chunk).min(c.len);
396                    if start >= end {
397                        return;
398                    }
399                    let l = unsafe {
400                        std::slice::from_raw_parts((c.lp as *const f32).add(start), end - start)
401                    };
402                    let r = unsafe {
403                        std::slice::from_raw_parts((c.rp as *const f32).add(start), end - start)
404                    };
405                    let o = unsafe {
406                        std::slice::from_raw_parts_mut((c.op as *mut f32).add(start), end - start)
407                    };
408                    simd::binary_dispatch(l, r, o, c.kind);
409                }
410                let q = unsafe { dispatch_get_global_queue(0, 0) };
411                unsafe {
412                    dispatch_apply_f(n, q, &ctx as *const Ctx as *mut c_void, work);
413                }
414            }
415
416            #[cfg(not(target_os = "macos"))]
417            {
418                // Rayon global thread pool — threads pre-spawned, ~0.5µs dispatch.
419                use rayon::prelude::*;
420                (0..n).into_par_iter().for_each(|t| {
421                    let start = t * chunk;
422                    let end = (start + chunk).min(len);
423                    if start >= end {
424                        return;
425                    }
426                    let l = unsafe {
427                        std::slice::from_raw_parts((lp as *const f32).add(start), end - start)
428                    };
429                    let r = unsafe {
430                        std::slice::from_raw_parts((rp as *const f32).add(start), end - start)
431                    };
432                    let o = unsafe {
433                        std::slice::from_raw_parts_mut((op as *mut f32).add(start), end - start)
434                    };
435                    simd::binary_dispatch(l, r, o, kind);
436                });
437            }
438
439            return Ok(Tensor::from_raw_parts(
440                self.shape(),
441                self.strides(),
442                out_data,
443            ));
444        }
445
446        simd::binary_dispatch(self.data(), rhs.data(), &mut out_data, kind);
447        Ok(Tensor::from_raw_parts(
448            self.shape(),
449            self.strides(),
450            out_data,
451        ))
452    }
453
454    #[allow(unsafe_code)]
455    fn binary_same_shape<F>(&self, rhs: &Self, op: F) -> Result<Self, TensorError>
456    where
457        F: Fn(f32, f32) -> f32,
458    {
459        let len = self.len();
460        // SAFETY: `uninitialized` allocates without zeroing.  The loop below
461        // writes every element before we ever read from `out_data`.
462        // SAFETY: every element is written by the operation before the tensor is read.
463        let mut out_data = unsafe { AlignedVec::<f32>::uninitialized(len) };
464
465        let lhs_ptr = self.data().as_ptr();
466        let rhs_ptr = rhs.data().as_ptr();
467        let out_ptr = out_data.as_mut_ptr();
468
469        // SAFETY:
470        // - Pointers originate from valid slices/vectors of length `len`.
471        // - Loop bounds guarantee all pointer arithmetic remains in-bounds.
472        // - `out_data` is uniquely mutable and does not alias with input buffers.
473        unsafe {
474            let mut index = 0usize;
475            while index + 4 <= len {
476                *out_ptr.add(index) = op(*lhs_ptr.add(index), *rhs_ptr.add(index));
477                *out_ptr.add(index + 1) = op(*lhs_ptr.add(index + 1), *rhs_ptr.add(index + 1));
478                *out_ptr.add(index + 2) = op(*lhs_ptr.add(index + 2), *rhs_ptr.add(index + 2));
479                *out_ptr.add(index + 3) = op(*lhs_ptr.add(index + 3), *rhs_ptr.add(index + 3));
480                index += 4;
481            }
482            while index < len {
483                *out_ptr.add(index) = op(*lhs_ptr.add(index), *rhs_ptr.add(index));
484                index += 1;
485            }
486        }
487
488        Ok(Tensor::from_raw_parts(
489            self.shape(),
490            self.strides(),
491            out_data,
492        ))
493    }
494
495    // ── In-place operations ──────────────────────────────────────────────
496
497    /// In-place ReLU: clamp negative values to zero.
498    pub fn relu_inplace(&mut self) {
499        simd::relu_inplace_dispatch(self.data_mut());
500    }
501
502    /// In-place element-wise add from another tensor (must have same shape).
503    pub fn add_inplace(&mut self, rhs: &Self) {
504        debug_assert_eq!(self.len(), rhs.len());
505        simd::add_inplace_dispatch(self.data_mut(), rhs.data());
506    }
507
508    /// In-place add scalar to all elements.
509    pub fn add_scalar_inplace(&mut self, s: f32) {
510        simd::add_scalar_inplace_dispatch(self.data_mut(), s);
511    }
512
513    /// In-place multiply all elements by scalar.
514    pub fn mul_scalar_inplace(&mut self, s: f32) {
515        simd::mul_scalar_inplace_dispatch(self.data_mut(), s);
516    }
517
518    // ── Binary-into operations (write into pre-allocated output) ─────
519
520    /// Element-wise addition writing into a pre-allocated output tensor.
521    /// `output`, `lhs`, and `rhs` must all have the same shape.
522    pub fn add_into(output: &mut Self, lhs: &Self, rhs: &Self) {
523        debug_assert_eq!(lhs.shape(), rhs.shape());
524        debug_assert_eq!(lhs.shape(), output.shape());
525        simd::binary_dispatch(
526            lhs.data(),
527            rhs.data(),
528            output.data_mut(),
529            simd::BinaryKind::Add,
530        );
531    }
532
533    /// Element-wise subtraction writing into a pre-allocated output tensor.
534    /// `output`, `lhs`, and `rhs` must all have the same shape.
535    pub fn sub_into(output: &mut Self, lhs: &Self, rhs: &Self) {
536        debug_assert_eq!(lhs.shape(), rhs.shape());
537        debug_assert_eq!(lhs.shape(), output.shape());
538        simd::binary_dispatch(
539            lhs.data(),
540            rhs.data(),
541            output.data_mut(),
542            simd::BinaryKind::Sub,
543        );
544    }
545
546    /// Element-wise multiplication writing into a pre-allocated output tensor.
547    /// `output`, `lhs`, and `rhs` must all have the same shape.
548    pub fn mul_into(output: &mut Self, lhs: &Self, rhs: &Self) {
549        debug_assert_eq!(lhs.shape(), rhs.shape());
550        debug_assert_eq!(lhs.shape(), output.shape());
551        simd::binary_dispatch(
552            lhs.data(),
553            rhs.data(),
554            output.data_mut(),
555            simd::BinaryKind::Mul,
556        );
557    }
558}
559
560// ── atan2 helper ───────────────────────────────────────────────────
561
562/// Scalar atan2(y, x) using Cephes-style range reduction of atan.
563///
564/// Range-reduces the argument to [0, tan(pi/12)] ≈ [0, 0.268] using:
565///   - If z > tan(3*pi/8) ≈ 2.414: atan(z) = pi/2 - atan(1/z)
566///   - If z > tan(pi/8) ≈ 0.414: atan(z) = pi/4 + atan((z-1)/(z+1))
567///
568/// Then uses a degree-7 polynomial on the reduced argument.
569/// Max error < 4e-7 across all inputs.
570#[allow(clippy::excessive_precision)]
571#[inline(always)]
572pub(super) fn fast_atan2_scalar(y: f32, x: f32) -> f32 {
573    const PI: f32 = std::f32::consts::PI;
574    const FRAC_PI_2: f32 = std::f32::consts::FRAC_PI_2;
575    const FRAC_PI_4: f32 = std::f32::consts::FRAC_PI_4;
576    const TAN_3PI_8: f32 = 2.414_213_6; // tan(3*pi/8) = 1 + sqrt(2)
577    const TAN_PI_8: f32 = 0.414_213_57; // tan(pi/8) = sqrt(2) - 1
578
579    let ax = x.abs();
580    let ay = y.abs();
581
582    // Compute atan(|y|/|x|) with range reduction
583    let (num, den, swap) = if ax >= ay {
584        (ay, ax, false)
585    } else {
586        (ax, ay, true)
587    };
588    let z = if den > 0.0 { num / den } else { 0.0 };
589
590    // Range reduction for atan(z), z >= 0
591    let (z_red, bias) = if z > TAN_3PI_8 {
592        // Should not happen since z <= 1 from our swap, but just in case
593        (-1.0 / z, FRAC_PI_2)
594    } else if z > TAN_PI_8 {
595        ((z - 1.0) / (z + 1.0), FRAC_PI_4)
596    } else {
597        (z, 0.0)
598    };
599
600    // Polynomial: atan(z) ≈ z + z³·P(z²) for small z
601    // Coefficients from Cephes atanf.c (S. Moshier), reordered for Horner.
602    let z2 = z_red * z_red;
603    let p: f32 = 8.054_666e-02;
604    let p = p.mul_add(z2, -1.384_895_1e-01);
605    let p = p.mul_add(z2, 1.997_075_8e-01);
606    let p = p.mul_add(z2, -3.333_129_8e-01);
607    let atan_z = z_red.mul_add(z2 * p, z_red) + bias;
608
609    // If we swapped: atan(|y|/|x|) = pi/2 - atan(|x|/|y|)
610    let mut result = if swap { FRAC_PI_2 - atan_z } else { atan_z };
611
612    // Quadrant correction
613    if x < 0.0 {
614        result = PI - result;
615    }
616    if y < 0.0 {
617        result = -result;
618    }
619
620    result
621}
622
623// ── FP16 conversion utilities ──────────────────────────────────────
624
625/// Convert f32 to IEEE 754 half-precision (FP16) bit pattern.
626const fn f32_to_fp16(val: f32) -> u16 {
627    let bits = val.to_bits();
628    let sign = ((bits >> 16) & 0x8000) as u16;
629    let exponent = ((bits >> 23) & 0xFF) as i32;
630    let mantissa = bits & 0x007F_FFFF;
631
632    if exponent == 255 {
633        // Inf or NaN
634        return sign | 0x7C00 | if mantissa != 0 { 0x0200 } else { 0 };
635    }
636
637    let unbiased = exponent - 127;
638    if unbiased > 15 {
639        return sign | 0x7C00; // overflow -> Inf
640    }
641    if unbiased < -24 {
642        return sign; // underflow -> zero
643    }
644    if unbiased < -14 {
645        // subnormal FP16
646        let shift = -1 - unbiased;
647        let m = (mantissa | 0x0080_0000) >> (shift + 13);
648        return sign | m as u16;
649    }
650
651    let fp16_exp = ((unbiased + 15) as u16) << 10;
652    let fp16_man = (mantissa >> 13) as u16;
653    sign | fp16_exp | fp16_man
654}
655
656mod compare;
657mod create;
658mod elementwise;
659mod indexing;
660mod reduce;
661mod shape;
662
663mod advanced;
664
665/// Convert IEEE 754 half-precision (FP16) bit pattern to f32.
666const fn fp16_to_f32(half: u16) -> f32 {
667    let sign = ((half & 0x8000) as u32) << 16;
668    let exponent = (half >> 10) & 0x1F;
669    let mantissa = (half & 0x03FF) as u32;
670
671    if exponent == 0 {
672        if mantissa == 0 {
673            return f32::from_bits(sign); // zero
674        }
675        // subnormal
676        let mut m = mantissa;
677        let mut e = 0i32;
678        while m & 0x0400 == 0 {
679            m <<= 1;
680            e += 1;
681        }
682        m &= 0x03FF;
683        let f32_exp = ((127 - 15 - e) as u32) << 23;
684        let f32_man = m << 13;
685        return f32::from_bits(sign | f32_exp | f32_man);
686    }
687    if exponent == 31 {
688        let f32_exp = 0xFF << 23;
689        let f32_man = mantissa << 13;
690        return f32::from_bits(sign | f32_exp | f32_man);
691    }
692
693    let f32_exp = ((exponent as i32 - 15 + 127) as u32 & 0xFF) << 23;
694    let f32_man = mantissa << 13;
695    f32::from_bits(sign | f32_exp | f32_man)
696}