numr 0.10.0

High-performance numerical computing with multi-backend GPU acceleration (CPU/CUDA/WebGPU)
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
//! Shared helper functions for runtime backends
//!
//! This module contains helper functions that are used across multiple backends
//! (CPU, CUDA, WebGPU) to reduce code duplication and maintain consistency.

use crate::dtype::DType;
use crate::error::{Error, Result};
use crate::ops::broadcast_shape;
use crate::runtime::Runtime;
use crate::tensor::Tensor;

// ============================================================================
// Dimension Normalization
// ============================================================================

/// Normalize a dimension index, handling negative indexing.
///
/// Converts a potentially negative dimension index to a positive index,
/// following NumPy/PyTorch conventions where -1 refers to the last dimension,
/// -2 to the second-to-last, etc.
///
/// # Arguments
///
/// * `dim` - The dimension index (can be negative)
/// * `ndim` - The number of dimensions in the tensor
///
/// # Returns
///
/// The normalized (positive) dimension index.
///
/// # Errors
///
/// Returns `Error::InvalidDimension` if the dimension is out of bounds.
#[inline]
pub fn normalize_dim(dim: isize, ndim: usize) -> Result<usize> {
    let dim_idx = if dim < 0 {
        let adjusted = ndim as isize + dim;
        if adjusted < 0 {
            return Err(Error::InvalidDimension { dim, ndim });
        }
        adjusted as usize
    } else {
        dim as usize
    };

    if dim_idx >= ndim {
        return Err(Error::InvalidDimension { dim, ndim });
    }

    Ok(dim_idx)
}

// ============================================================================
// Utility Operation Validation
// ============================================================================

/// Validate arange parameters and compute the number of elements.
///
/// # Arguments
///
/// * `start` - Start value (inclusive)
/// * `stop` - Stop value (exclusive)
/// * `step` - Step between consecutive values
///
/// # Returns
///
/// The number of elements in the resulting tensor, or an error if parameters are invalid.
///
/// # Errors
///
/// * `InvalidArgument` if step is zero
/// * `InvalidArgument` if step direction doesn't match start→stop direction
#[inline]
pub fn validate_arange(start: f64, stop: f64, step: f64) -> Result<usize> {
    // Step cannot be zero
    if step == 0.0 {
        return Err(Error::InvalidArgument {
            arg: "step",
            reason: "step cannot be zero".to_string(),
        });
    }

    // Step direction must match start→stop direction
    if (stop > start && step < 0.0) || (stop < start && step > 0.0) {
        return Err(Error::InvalidArgument {
            arg: "step",
            reason: "step sign must match direction from start to stop".to_string(),
        });
    }

    // Calculate number of elements
    let numel = if start == stop {
        0
    } else {
        ((stop - start) / step).ceil() as usize
    };

    Ok(numel)
}

/// Validate linspace parameters.
///
/// # Arguments
///
/// * `steps` - Number of points to generate
///
/// # Returns
///
/// Validate eye (identity matrix) parameters.
///
/// # Arguments
///
/// * `n` - Number of rows
/// * `m` - Number of columns (if None, defaults to n)
///
/// # Returns
///
/// The (rows, cols) dimensions of the identity matrix.
#[inline]
pub fn validate_eye(n: usize, m: Option<usize>) -> (usize, usize) {
    let cols = m.unwrap_or(n);
    (n, cols)
}

/// Split a contiguous elementwise op into `(rows, row_len)` at the last axis.
///
/// The SIMD/scalar crossover a kernel picks keys off the length it is
/// handed, so a per-row result must not depend on how many other rows ride
/// along in the same call. Callers loop `0..rows`, offsetting by
/// `row * row_len` into each buffer, and dispatch the kernel once per row.
///
/// # Arguments
///
/// * `shape` - The tensor's shape
/// * `total` - The tensor's element count (`shape.iter().product()`)
///
/// # Returns
///
/// `(rows, row_len)`, where `row_len` is the last axis (or `total` for a
/// 0-dim tensor) and `rows` is `total / row_len` (`0` when `row_len` is `0`).
#[inline]
pub fn row_layout(shape: &[usize], total: usize) -> (usize, usize) {
    let row_len = *shape.last().unwrap_or(&total);
    let rows = total.checked_div(row_len).unwrap_or(0);
    (rows, row_len)
}

/// Ensure a tensor is contiguous in memory.
///
/// If the tensor is already contiguous (elements laid out consecutively in memory),
/// returns a clone (zero-copy, just increments Arc refcount). Otherwise,
/// creates a new contiguous copy of the data by materializing the strided view.
///
/// This is typically required before passing tensors to backend kernels
/// that expect contiguous memory layout, or for operations that need
/// to work with the underlying data pointer directly.
///
/// # Parameters
///
/// * `tensor` - The input tensor which may or may not be contiguous
///
/// # Returns
///
/// A new tensor that is guaranteed to be contiguous. If the input was already
/// contiguous, this is zero-copy (just clones the Arc). Otherwise, data is copied.
#[inline]
pub fn ensure_contiguous<R: Runtime<DType = DType>>(
    tensor: &Tensor<R>,
) -> crate::error::Result<Tensor<R>> {
    if tensor.is_contiguous() {
        Ok(tensor.clone())
    } else {
        tensor.contiguous()
    }
}

// ============================================================================
// Binary Operation Validation
// ============================================================================

/// Validate that two tensors have matching dtypes for binary operations.
///
/// This is a shared helper used by CPU, CUDA, and WebGPU backends to ensure
/// consistent dtype validation across all runtimes.
///
/// # Arguments
///
/// * `a` - First tensor
/// * `b` - Second tensor
///
/// # Returns
///
/// The common dtype if both tensors have the same dtype, or an error if they differ.
///
/// # Errors
///
/// Returns `Error::DTypeMismatch` if the tensors have different dtypes.
#[inline]
pub fn validate_binary_dtypes<R: Runtime<DType = DType>>(
    a: &Tensor<R>,
    b: &Tensor<R>,
) -> Result<DType> {
    if a.dtype() != b.dtype() {
        return Err(Error::DTypeMismatch {
            lhs: a.dtype(),
            rhs: b.dtype(),
        });
    }
    Ok(a.dtype())
}

/// Output dtype of `pow_scalar` for a given input dtype and exponent.
///
/// An op's output dtype is a function of its input dtypes, never its input
/// values. `pow_scalar`'s exponent is a host-side parameter, not tensor data, so
/// it is known before launch and participates in that function.
///
/// An integer raised to a power is an integer only when the exponent is a
/// non-negative whole number. Every other exponent — negative, fractional,
/// infinite, or NaN — yields a non-integer real, so the result is F64. This is
/// why numpy promotes `int ** 0.5` while refusing an integer array exponent:
/// there the exponent is data, and dtype inference cannot read data.
///
/// Float, complex, and bool dtypes pass through unchanged.
#[inline]
pub fn pow_scalar_output_dtype(dtype: DType, scalar: f64) -> DType {
    // `fract()` is NaN for an infinite exponent and for NaN itself, so both fail
    // this test and promote, which is what their real-valued results require.
    let integral_result = scalar >= 0.0 && scalar.fract() == 0.0;
    if dtype.is_int() && !integral_result {
        DType::F64
    } else {
        dtype
    }
}

/// Cap an integer power's exponent above 1024 to preserve parity.
///
/// Above 1024, the result depends only on the base's magnitude (0, 1, or
/// saturated to the dtype bound) and the exponent's parity, since any base
/// outside `{-1, 0, 1}` has already saturated well before an exponent that
/// large. Capping to 1024 (even) or 1025 (odd) keeps the parity a negative
/// base needs while leaving the value small enough to cast losslessly into a
/// kernel's integer type. Caller must already know the exponent is a
/// non-negative whole number reaching an integer dtype — this does not
/// re-check that.
///
/// CUDA device code (`numr_ipow_scalar` in `runtime/cuda/kernels/ipow.cuh`)
/// cannot call this function, so it duplicates the cap by hand; that
/// duplicate must keep agreeing with this one.
#[inline]
pub fn cap_ipow_exponent(scalar: f64) -> f64 {
    if scalar > 1024.0 {
        1024.0 + f64::from(scalar % 2.0 != 0.0)
    } else {
        scalar
    }
}

/// Compute broadcast shape for binary operations.
///
/// Returns the output shape after broadcasting, or an error if shapes are incompatible.
/// Follows NumPy broadcasting rules.
///
/// This is a shared helper used by CPU, CUDA, and WebGPU backends to ensure
/// consistent broadcast shape computation across all runtimes.
///
/// # Arguments
///
/// * `a` - First tensor
/// * `b` - Second tensor
///
/// # Returns
///
/// The broadcast output shape, or an error if shapes are incompatible.
///
/// # Errors
///
/// Returns `Error::BroadcastError` if shapes cannot be broadcast together.
#[inline]
pub fn compute_broadcast_shape<R: Runtime<DType = DType>>(
    a: &Tensor<R>,
    b: &Tensor<R>,
) -> Result<Vec<usize>> {
    broadcast_shape(a.shape(), b.shape()).ok_or_else(|| Error::BroadcastError {
        lhs: a.shape().to_vec(),
        rhs: b.shape().to_vec(),
    })
}

/// Validate a destination-passing copy `out <- src`.
///
/// `out` must be contiguous and match `src` in dtype and shape exactly.
/// Shared by the CPU, CUDA, and WebGPU `copy_into` implementations.
///
/// # Errors
///
/// Returns `Error::DTypeMismatch` when the dtypes differ,
/// `Error::ShapeMismatch` when the shapes differ, and `Error::Backend`
/// when `out` is not contiguous.
#[inline]
pub fn validate_copy_into<R: Runtime<DType = DType>>(
    out: &Tensor<R>,
    src: &Tensor<R>,
    op_name: &'static str,
) -> Result<()> {
    if out.dtype() != src.dtype() {
        return Err(Error::DTypeMismatch {
            lhs: src.dtype(),
            rhs: out.dtype(),
        });
    }
    if out.shape() != src.shape() {
        return Err(Error::ShapeMismatch {
            expected: src.shape().to_vec(),
            got: out.shape().to_vec(),
        });
    }
    if !out.is_contiguous() {
        return Err(Error::Backend(format!(
            "{op_name}: destination tensor must be contiguous"
        )));
    }
    Ok(())
}

/// Validate a host-to-device write `out <- host slice`.
///
/// `out` must be contiguous, carry `src_dtype`, and hold exactly `src_len`
/// elements. Shared by the CPU, CUDA, and WebGPU `write_host_slice`
/// implementations.
///
/// # Errors
///
/// Returns `Error::DTypeMismatch` when the dtypes differ,
/// `Error::ShapeMismatch` when the element counts differ, and
/// `Error::Backend` when `out` is not contiguous.
#[inline]
pub fn validate_host_write<R: Runtime<DType = DType>>(
    out: &Tensor<R>,
    src_dtype: DType,
    src_len: usize,
    op_name: &'static str,
) -> Result<()> {
    if out.dtype() != src_dtype {
        return Err(Error::DTypeMismatch {
            lhs: src_dtype,
            rhs: out.dtype(),
        });
    }
    if out.numel() != src_len {
        return Err(Error::ShapeMismatch {
            expected: vec![out.numel()],
            got: vec![src_len],
        });
    }
    if !out.is_contiguous() {
        return Err(Error::Backend(format!(
            "{op_name}: destination tensor of shape {:?} with strides {:?} is not contiguous; \
             pass the owning tensor instead of a strided view",
            out.shape(),
            out.strides()
        )));
    }
    Ok(())
}

/// Validate a destination-passing random draw: `out <- random values`.
///
/// `out` must be contiguous and carry a floating-point dtype. Shared by the
/// CPU, CUDA, and WebGPU `rand_into`/`rand_seeded_into`/`randn_into`/
/// `randn_seeded_into` implementations.
///
/// # Returns
///
/// `true` when `out` has zero elements, in which case the caller must treat
/// the draw as a no-op and return `Ok(())` without touching `out` or the
/// PRNG state.
///
/// # Errors
///
/// Returns `Error::UnsupportedDType` when `out`'s dtype is not floating
/// point, and `Error::Backend` when `out` is not contiguous.
#[inline]
pub fn validate_rand_into<R: Runtime<DType = DType>>(
    out: &Tensor<R>,
    op_name: &'static str,
) -> Result<bool> {
    if !out.dtype().is_float() {
        return Err(Error::UnsupportedDType {
            dtype: out.dtype(),
            op: op_name,
        });
    }
    if !out.is_contiguous() {
        return Err(Error::Backend(format!(
            "{op_name}: destination tensor must be contiguous"
        )));
    }
    Ok(out.numel() == 0)
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn pow_scalar_output_dtype_promotes_only_non_integral_exponents() {
        // A non-negative whole exponent keeps the integer dtype.
        for scalar in [0.0, 1.0, 2.0, 63.0, 1e30] {
            assert_eq!(pow_scalar_output_dtype(DType::I64, scalar), DType::I64);
            assert_eq!(pow_scalar_output_dtype(DType::U32, scalar), DType::U32);
        }

        // Every other exponent yields a non-integer real.
        for scalar in [0.5, -1.0, -0.5, f64::INFINITY, f64::NEG_INFINITY, f64::NAN] {
            assert_eq!(pow_scalar_output_dtype(DType::I64, scalar), DType::F64);
            assert_eq!(pow_scalar_output_dtype(DType::I32, scalar), DType::F64);
        }

        // Float dtypes pass through for every exponent.
        for scalar in [0.5, -1.0, 2.0, f64::NAN] {
            assert_eq!(pow_scalar_output_dtype(DType::F32, scalar), DType::F32);
            assert_eq!(pow_scalar_output_dtype(DType::F64, scalar), DType::F64);
        }
    }

    #[test]
    fn test_normalize_dim_positive() {
        assert_eq!(normalize_dim(0, 3).unwrap(), 0);
        assert_eq!(normalize_dim(2, 3).unwrap(), 2);
    }

    #[test]
    fn test_normalize_dim_negative() {
        assert_eq!(normalize_dim(-1, 3).unwrap(), 2);
        assert_eq!(normalize_dim(-3, 3).unwrap(), 0);
    }

    #[test]
    fn test_normalize_dim_out_of_bounds() {
        assert!(normalize_dim(3, 3).is_err());
        assert!(normalize_dim(-4, 3).is_err());
    }

    #[test]
    fn test_ensure_contiguous() {
        use crate::runtime::cpu::{CpuDevice, CpuRuntime};
        use crate::tensor::Tensor;

        let device = CpuDevice::new();
        let a =
            Tensor::<CpuRuntime>::from_slice(&[1.0f32, 2.0, 3.0, 4.0], &[2, 2], &device).unwrap();
        assert!(a.is_contiguous());
        let c = ensure_contiguous(&a).unwrap();
        assert!(c.is_contiguous());
    }
}