numr 1.0.0

Numerical computing and tensor library for Rust, in the role of NumPy: n-dimensional arrays, linear algebra, FFT, statistics and autograd on CPU, CUDA and 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
//! CPU implementation of distance operations.
//!
//! cdist and pdist split their output into units of work that depend on the
//! shape alone: a fixed-width block of columns of one cdist row, or one pdist
//! row. The units run on the client's pool when the work is large enough. Each
//! output element comes from one distance call on fixed inputs, so the result
//! is bit-identical for every thread count and chunk size.
//!
//! F16, BF16 and FP8 inputs convert once to F32, run the F32 path, and convert
//! the F32 output back once.

use super::distance_units::{cdist_units, pdist_units};
use crate::dtype::DType;
use crate::error::{Error, Result};
#[cfg(any(feature = "fp8", feature = "f16"))]
use crate::ops::TypeConversionOps;
use crate::ops::distance_common::*;
use crate::ops::{DistanceMetric, DistanceOps};
use crate::runtime::cpu::{CpuClient, CpuRuntime, helpers::ensure_contiguous, kernels};
use crate::tensor::Tensor;

/// Length of the condensed distance vector for `n` points: `n * (n - 1) / 2`.
///
/// Returns an error when `n * (n - 1)` overflows `usize`. A wrapped length
/// would size the output below the number of pairs the kernel writes.
fn condensed_len(n: usize) -> Result<usize> {
    n.checked_mul(n.saturating_sub(1))
        .map(|pairs| pairs / 2)
        .ok_or_else(|| Error::InvalidArgument {
            arg: "n",
            reason: format!("pair count for {n} points overflows usize"),
        })
}

/// True for the dtypes that run as F32: F16 and BF16 (feature `f16`), FP8
/// (feature `fp8`).
#[cfg(any(feature = "fp8", feature = "f16"))]
fn runs_as_f32(dtype: DType) -> bool {
    match dtype {
        #[cfg(feature = "f16")]
        DType::F16 | DType::BF16 => true,
        #[cfg(feature = "fp8")]
        DType::FP8E4M3 | DType::FP8E5M2 => true,
        _ => false,
    }
}

/// Dispatch to distance kernel for float types only
macro_rules! dispatch_float_dtype {
    ($dtype:expr, $T:ident => $body:block, $op:expr) => {
        match $dtype {
            DType::F32 => {
                type $T = f32;
                $body
            }
            DType::F64 => {
                type $T = f64;
                $body
            }
            #[cfg(feature = "f16")]
            DType::F16 => {
                type $T = half::f16;
                $body
            }
            #[cfg(feature = "f16")]
            DType::BF16 => {
                type $T = half::bf16;
                $body
            }
            _ => {
                return Err(Error::UnsupportedDType {
                    dtype: $dtype,
                    op: $op,
                })
            }
        }
    };
}

impl DistanceOps<CpuRuntime> for CpuClient {
    fn cdist(
        &self,
        x: &Tensor<CpuRuntime>,
        y: &Tensor<CpuRuntime>,
        metric: DistanceMetric,
    ) -> Result<Tensor<CpuRuntime>> {
        let x_shape = x.shape();
        let y_shape = y.shape();

        // Validate inputs using shared validators
        validate_2d_tensor(x_shape, "x", "cdist")?;
        validate_2d_tensor(y_shape, "y", "cdist")?;
        validate_same_dimension(x_shape, y_shape, "cdist")?;

        let dtype = x.dtype();
        validate_float_dtype(dtype, "cdist")?;
        validate_same_dtype(dtype, y.dtype(), "cdist")?;

        let n = x_shape[0];
        let m = y_shape[0];
        let d = x_shape[1];

        // Handle empty tensors
        if n == 0 || m == 0 {
            return Tensor::<CpuRuntime>::empty(&[n, m], dtype, &self.device);
        }

        #[cfg(any(feature = "fp8", feature = "f16"))]
        if runs_as_f32(dtype) {
            let x_f32 = self.cast(x, DType::F32)?;
            let y_f32 = self.cast(y, DType::F32)?;
            let out_f32 = self.cdist(&x_f32, &y_f32, metric)?;
            return self.cast(&out_f32, dtype);
        }

        let x = ensure_contiguous(x)?;
        let y = ensure_contiguous(y)?;
        let out = Tensor::<CpuRuntime>::empty(&[n, m], dtype, &self.device)?;
        let (x_ptr, y_ptr, out_ptr) = (x.ptr(), y.ptr(), out.ptr());

        // SAFETY: the buffers are contiguous with the validated shapes, and
        // `out` is a fresh allocation.
        match dtype {
            DType::F32 => unsafe {
                cdist_units::<f32>(self, x_ptr as _, y_ptr as _, out_ptr as _, n, m, d, metric);
            },
            DType::F64 => unsafe {
                cdist_units::<f64>(self, x_ptr as _, y_ptr as _, out_ptr as _, n, m, d, metric);
            },
            _ => return Err(Error::UnsupportedDType { dtype, op: "cdist" }),
        }

        Ok(out)
    }

    fn pdist(&self, x: &Tensor<CpuRuntime>, metric: DistanceMetric) -> Result<Tensor<CpuRuntime>> {
        let x_shape = x.shape();

        // Validate inputs using shared validators
        validate_2d_tensor(x_shape, "x", "pdist")?;

        let n = x_shape[0];
        let d = x_shape[1];

        validate_min_points(n, 2, "x", "pdist")?;

        let dtype = x.dtype();
        validate_float_dtype(dtype, "pdist")?;

        // Output size: n*(n-1)/2
        let out_size = condensed_len(n)?;

        #[cfg(any(feature = "fp8", feature = "f16"))]
        if runs_as_f32(dtype) {
            let x_f32 = self.cast(x, DType::F32)?;
            let out_f32 = self.pdist(&x_f32, metric)?;
            return self.cast(&out_f32, dtype);
        }

        let x = ensure_contiguous(x)?;
        let out = Tensor::<CpuRuntime>::empty(&[out_size], dtype, &self.device)?;
        let (x_ptr, out_ptr) = (x.ptr(), out.ptr());

        // SAFETY: the buffers are contiguous with the validated shapes, and
        // `out` is a fresh allocation.
        match dtype {
            DType::F32 => unsafe {
                pdist_units::<f32>(self, x_ptr as _, out_ptr as _, n, d, metric);
            },
            DType::F64 => unsafe {
                pdist_units::<f64>(self, x_ptr as _, out_ptr as _, n, d, metric);
            },
            _ => return Err(Error::UnsupportedDType { dtype, op: "pdist" }),
        }

        Ok(out)
    }

    fn squareform(&self, condensed: &Tensor<CpuRuntime>, n: usize) -> Result<Tensor<CpuRuntime>> {
        let cond_shape = condensed.shape();

        // Validate inputs using shared validators
        validate_1d_tensor(cond_shape, "condensed", "squareform")?;
        validate_condensed_length(cond_shape[0], n, "condensed", "squareform")?;

        let dtype = condensed.dtype();
        validate_float_dtype(dtype, "squareform")?;

        // Handle edge case
        if n == 0 {
            return Tensor::<CpuRuntime>::empty(&[0, 0], dtype, &self.device);
        }
        if n == 1 {
            return Tensor::<CpuRuntime>::zeros(&[1, 1], dtype, &self.device);
        }

        // Make contiguous
        let condensed = ensure_contiguous(condensed)?;

        let out = Tensor::<CpuRuntime>::empty(&[n, n], dtype, &self.device)?;
        let cond_ptr = condensed.ptr();
        let out_ptr = out.ptr();

        dispatch_float_dtype!(dtype, T => {
            unsafe {
                kernels::squareform_kernel::<T>(
                    cond_ptr as *const T,
                    out_ptr as *mut T,
                    n,
                );
            }
        }, "squareform");

        Ok(out)
    }

    fn squareform_inverse(&self, square: &Tensor<CpuRuntime>) -> Result<Tensor<CpuRuntime>> {
        let sq_shape = square.shape();

        // Validate inputs using shared validators
        validate_2d_tensor(sq_shape, "square", "squareform_inverse")?;
        validate_square_matrix(sq_shape, "square", "squareform_inverse")?;

        let n = sq_shape[0];
        let dtype = square.dtype();
        validate_float_dtype(dtype, "squareform_inverse")?;

        // Handle edge cases
        if n == 0 {
            return Tensor::<CpuRuntime>::empty(&[0], dtype, &self.device);
        }
        if n == 1 {
            return Tensor::<CpuRuntime>::empty(&[0], dtype, &self.device);
        }

        // Make contiguous
        let square = ensure_contiguous(square)?;

        let out_size = condensed_len(n)?;
        let out = Tensor::<CpuRuntime>::empty(&[out_size], dtype, &self.device)?;
        let sq_ptr = square.ptr();
        let out_ptr = out.ptr();

        dispatch_float_dtype!(dtype, T => {
            unsafe {
                kernels::squareform_inverse_kernel::<T>(
                    sq_ptr as *const T,
                    out_ptr as *mut T,
                    n,
                );
            }
        }, "squareform_inverse");

        Ok(out)
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::runtime::Runtime;
    use crate::runtime::cpu::CpuDevice;

    fn setup() -> (CpuDevice, CpuClient) {
        let device = CpuDevice::new();
        let client = CpuRuntime::default_client(&device);
        (device, client)
    }

    #[test]
    fn test_cdist_euclidean() {
        let (device, client) = setup();

        // X = [[0, 0], [1, 1]]
        // Y = [[1, 0], [2, 2]]
        let x =
            Tensor::<CpuRuntime>::from_slice(&[0.0f32, 0.0, 1.0, 1.0], &[2, 2], &device).unwrap();
        let y =
            Tensor::<CpuRuntime>::from_slice(&[1.0f32, 0.0, 2.0, 2.0], &[2, 2], &device).unwrap();

        let dist = client.cdist(&x, &y, DistanceMetric::Euclidean).unwrap();
        assert_eq!(dist.shape(), &[2, 2]);

        let data: Vec<f32> = dist.to_vec();
        // d(x0, y0) = 1.0
        // d(x0, y1) = sqrt(8) = 2.828...
        // d(x1, y0) = 1.0
        // d(x1, y1) = sqrt(2) = 1.414...
        assert!((data[0] - 1.0).abs() < 1e-5);
        assert!((data[1] - 8.0f32.sqrt()).abs() < 1e-5);
        assert!((data[2] - 1.0).abs() < 1e-5);
        assert!((data[3] - 2.0f32.sqrt()).abs() < 1e-5);
    }

    #[test]
    fn test_pdist_euclidean() {
        let (device, client) = setup();

        // X = [[0, 0], [1, 0], [0, 1]] - 3 points
        let x =
            Tensor::<CpuRuntime>::from_slice(&[0.0f32, 0.0, 1.0, 0.0, 0.0, 1.0], &[3, 2], &device)
                .unwrap();

        let dist = client.pdist(&x, DistanceMetric::Euclidean).unwrap();
        assert_eq!(dist.shape(), &[3]); // n*(n-1)/2 = 3

        let data: Vec<f32> = dist.to_vec();
        // d(0,1) = 1.0, d(0,2) = 1.0, d(1,2) = sqrt(2)
        assert!((data[0] - 1.0).abs() < 1e-5);
        assert!((data[1] - 1.0).abs() < 1e-5);
        assert!((data[2] - 2.0f32.sqrt()).abs() < 1e-5);
    }

    #[test]
    fn test_squareform_roundtrip() {
        let (device, client) = setup();

        // Create condensed form: [d(0,1), d(0,2), d(1,2)]
        let condensed =
            Tensor::<CpuRuntime>::from_slice(&[1.0f32, 2.0, 3.0], &[3], &device).unwrap();

        // Convert to square
        let square = client.squareform(&condensed, 3).unwrap();
        assert_eq!(square.shape(), &[3, 3]);

        // Convert back to condensed
        let condensed2 = client.squareform_inverse(&square).unwrap();
        assert_eq!(condensed2.shape(), &[3]);

        let data: Vec<f32> = condensed2.to_vec();
        assert!((data[0] - 1.0).abs() < 1e-5);
        assert!((data[1] - 2.0).abs() < 1e-5);
        assert!((data[2] - 3.0).abs() < 1e-5);
    }

    #[test]
    fn test_cdist_cosine() {
        let (device, client) = setup();

        // Same direction vectors have cosine distance 0
        let x = Tensor::<CpuRuntime>::from_slice(&[1.0f32, 0.0], &[1, 2], &device).unwrap();
        let y = Tensor::<CpuRuntime>::from_slice(&[2.0f32, 0.0], &[1, 2], &device).unwrap();

        let dist = client.cdist(&x, &y, DistanceMetric::Cosine).unwrap();
        let data: Vec<f32> = dist.to_vec();
        assert!(data[0].abs() < 1e-5);

        // Orthogonal vectors have cosine distance 1
        let y2 = Tensor::<CpuRuntime>::from_slice(&[0.0f32, 1.0], &[1, 2], &device).unwrap();
        let dist2 = client.cdist(&x, &y2, DistanceMetric::Cosine).unwrap();
        let data2: Vec<f32> = dist2.to_vec();
        assert!((data2[0] - 1.0).abs() < 1e-5);
    }

    #[test]
    fn test_cdist_manhattan() {
        let (device, client) = setup();

        let x = Tensor::<CpuRuntime>::from_slice(&[0.0f32, 0.0, 0.0], &[1, 3], &device).unwrap();
        let y = Tensor::<CpuRuntime>::from_slice(&[1.0f32, 2.0, 3.0], &[1, 3], &device).unwrap();

        let dist = client.cdist(&x, &y, DistanceMetric::Manhattan).unwrap();
        let data: Vec<f32> = dist.to_vec();
        assert!((data[0] - 6.0).abs() < 1e-5); // |1| + |2| + |3| = 6
    }

    #[test]
    fn test_cdist_chebyshev() {
        let (device, client) = setup();

        let x = Tensor::<CpuRuntime>::from_slice(&[0.0f32, 0.0, 0.0], &[1, 3], &device).unwrap();
        let y = Tensor::<CpuRuntime>::from_slice(&[1.0f32, 5.0, 3.0], &[1, 3], &device).unwrap();

        let dist = client.cdist(&x, &y, DistanceMetric::Chebyshev).unwrap();
        let data: Vec<f32> = dist.to_vec();
        assert!((data[0] - 5.0).abs() < 1e-5); // max(|1|, |5|, |3|) = 5
    }

    #[test]
    fn test_error_on_non_2d() {
        let (device, client) = setup();

        let x = Tensor::<CpuRuntime>::from_slice(&[1.0f32, 2.0, 3.0], &[3], &device).unwrap();
        let y = Tensor::<CpuRuntime>::from_slice(&[1.0f32, 2.0, 3.0], &[3], &device).unwrap();

        let result = client.cdist(&x, &y, DistanceMetric::Euclidean);
        assert!(result.is_err());
    }

    #[test]
    fn test_error_on_dimension_mismatch() {
        let (device, client) = setup();

        let x = Tensor::<CpuRuntime>::from_slice(&[1.0f32, 2.0, 3.0], &[1, 3], &device).unwrap();
        let y = Tensor::<CpuRuntime>::from_slice(&[1.0f32, 2.0], &[1, 2], &device).unwrap();

        let result = client.cdist(&x, &y, DistanceMetric::Euclidean);
        assert!(result.is_err());
    }

    #[test]
    fn test_pdist_requires_at_least_2_points() {
        let (device, client) = setup();

        let x = Tensor::<CpuRuntime>::from_slice(&[1.0f32, 2.0], &[1, 2], &device).unwrap();

        let result = client.pdist(&x, DistanceMetric::Euclidean);
        assert!(result.is_err());
    }
}