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