numr 0.5.2

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
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
//! Convenience methods on Tensor that delegate to Client ops
//!
//! These methods provide ergonomic `tensor.add(&other)` style calls
//! that internally get the client and delegate to the appropriate trait.

use crate::dtype::DType;
use crate::error::Result;
use crate::ops::traits::{
    ActivationOps, BinaryOps, CompareOps, ConvOps, CumulativeOps, IndexingOps, MatmulOps,
    NormalizationOps, PaddingMode, ReduceOps, ScalarOps, ShapeOps, TypeConversionOps, UnaryOps,
    UtilityOps,
};
use crate::runtime::Runtime;
use crate::tensor::Tensor;

// ============================================================================
// Binary arithmetic
// ============================================================================

impl<R: Runtime> Tensor<R>
where
    R::Client: BinaryOps<R>,
{
    /// Element-wise addition: self + other
    pub fn add(&self, other: &Tensor<R>) -> Result<Tensor<R>> {
        let client = R::default_client(self.device());
        client.add(self, other)
    }

    /// Element-wise subtraction: self - other
    pub fn sub(&self, other: &Tensor<R>) -> Result<Tensor<R>> {
        let client = R::default_client(self.device());
        client.sub(self, other)
    }

    /// Element-wise multiplication: self * other
    pub fn mul(&self, other: &Tensor<R>) -> Result<Tensor<R>> {
        let client = R::default_client(self.device());
        client.mul(self, other)
    }

    /// Element-wise division: self / other
    pub fn div(&self, other: &Tensor<R>) -> Result<Tensor<R>> {
        let client = R::default_client(self.device());
        client.div(self, other)
    }

    /// Element-wise power: self ^ other
    pub fn pow(&self, other: &Tensor<R>) -> Result<Tensor<R>> {
        let client = R::default_client(self.device());
        client.pow(self, other)
    }

    /// Element-wise maximum: max(self, other)
    pub fn maximum(&self, other: &Tensor<R>) -> Result<Tensor<R>> {
        let client = R::default_client(self.device());
        client.maximum(self, other)
    }

    /// Element-wise minimum: min(self, other)
    pub fn minimum(&self, other: &Tensor<R>) -> Result<Tensor<R>> {
        let client = R::default_client(self.device());
        client.minimum(self, other)
    }
}

// ============================================================================
// Unary operations
// ============================================================================

impl<R: Runtime> Tensor<R>
where
    R::Client: UnaryOps<R>,
{
    /// Element-wise negation
    pub fn neg(&self) -> Result<Tensor<R>> {
        let client = R::default_client(self.device());
        client.neg(self)
    }

    /// Element-wise absolute value
    pub fn abs(&self) -> Result<Tensor<R>> {
        let client = R::default_client(self.device());
        client.abs(self)
    }

    /// Element-wise square root
    pub fn sqrt(&self) -> Result<Tensor<R>> {
        let client = R::default_client(self.device());
        client.sqrt(self)
    }

    /// Element-wise exponential
    pub fn exp(&self) -> Result<Tensor<R>> {
        let client = R::default_client(self.device());
        client.exp(self)
    }

    /// Element-wise natural log
    pub fn log(&self) -> Result<Tensor<R>> {
        let client = R::default_client(self.device());
        client.log(self)
    }

    /// Element-wise sine
    pub fn sin(&self) -> Result<Tensor<R>> {
        let client = R::default_client(self.device());
        client.sin(self)
    }

    /// Element-wise cosine
    pub fn cos(&self) -> Result<Tensor<R>> {
        let client = R::default_client(self.device());
        client.cos(self)
    }

    /// Element-wise tangent
    pub fn tan(&self) -> Result<Tensor<R>> {
        let client = R::default_client(self.device());
        client.tan(self)
    }

    /// Element-wise hyperbolic tangent
    pub fn tanh(&self) -> Result<Tensor<R>> {
        let client = R::default_client(self.device());
        client.tanh(self)
    }

    /// Element-wise reciprocal (1/x)
    pub fn recip(&self) -> Result<Tensor<R>> {
        let client = R::default_client(self.device());
        client.recip(self)
    }

    /// Element-wise floor
    pub fn floor(&self) -> Result<Tensor<R>> {
        let client = R::default_client(self.device());
        client.floor(self)
    }

    /// Element-wise ceil
    pub fn ceil(&self) -> Result<Tensor<R>> {
        let client = R::default_client(self.device());
        client.ceil(self)
    }

    /// Element-wise round
    pub fn round(&self) -> Result<Tensor<R>> {
        let client = R::default_client(self.device());
        client.round(self)
    }
}

// ============================================================================
// Scalar operations
// ============================================================================

impl<R: Runtime> Tensor<R>
where
    R::Client: ScalarOps<R>,
{
    /// Add scalar: self + scalar
    pub fn add_scalar(&self, scalar: f64) -> Result<Tensor<R>> {
        let client = R::default_client(self.device());
        client.add_scalar(self, scalar)
    }

    /// Multiply by scalar: self * scalar
    pub fn mul_scalar(&self, scalar: f64) -> Result<Tensor<R>> {
        let client = R::default_client(self.device());
        client.mul_scalar(self, scalar)
    }

    /// Scale alias for mul_scalar
    pub fn scale(&self, scalar: f64) -> Result<Tensor<R>> {
        self.mul_scalar(scalar)
    }
}

// ============================================================================
// Activation functions
// ============================================================================

impl<R: Runtime> Tensor<R>
where
    R::Client: ActivationOps<R>,
{
    /// ReLU activation: max(0, x)
    pub fn relu(&self) -> Result<Tensor<R>> {
        let client = R::default_client(self.device());
        client.relu(self)
    }

    /// Sigmoid activation: 1 / (1 + exp(-x))
    pub fn sigmoid(&self) -> Result<Tensor<R>> {
        let client = R::default_client(self.device());
        client.sigmoid(self)
    }

    /// GELU activation
    pub fn gelu(&self) -> Result<Tensor<R>> {
        let client = R::default_client(self.device());
        client.gelu(self)
    }

    /// SiLU/Swish activation: x * sigmoid(x)
    pub fn silu(&self) -> Result<Tensor<R>> {
        let client = R::default_client(self.device());
        client.silu(self)
    }

    /// Softmax along dimension
    pub fn softmax(&self, dim: isize) -> Result<Tensor<R>> {
        let client = R::default_client(self.device());
        client.softmax(self, dim)
    }

    /// Log-softmax along dimension: log(softmax(x, dim))
    pub fn log_softmax(&self, dim: isize) -> Result<Tensor<R>> {
        let client = R::default_client(self.device());
        client.log_softmax(self, dim)
    }

    /// Dropout: randomly zero elements with probability `p` during training
    pub fn dropout(&self, p: f64, training: bool) -> Result<Tensor<R>> {
        let client = R::default_client(self.device());
        client.dropout(self, p, training)
    }
}

// ============================================================================
// Reduction operations
// ============================================================================

impl<R: Runtime> Tensor<R>
where
    R::Client: ReduceOps<R>,
{
    /// Sum along dimensions
    pub fn sum(&self, dims: &[usize], keepdim: bool) -> Result<Tensor<R>> {
        let client = R::default_client(self.device());
        client.sum(self, dims, keepdim)
    }

    /// Mean along dimensions
    pub fn mean(&self, dims: &[usize], keepdim: bool) -> Result<Tensor<R>> {
        let client = R::default_client(self.device());
        client.mean(self, dims, keepdim)
    }

    /// Max along dimensions
    pub fn max(&self, dims: &[usize], keepdim: bool) -> Result<Tensor<R>> {
        let client = R::default_client(self.device());
        client.max(self, dims, keepdim)
    }

    /// Min along dimensions
    pub fn min(&self, dims: &[usize], keepdim: bool) -> Result<Tensor<R>> {
        let client = R::default_client(self.device());
        client.min(self, dims, keepdim)
    }
}

// ============================================================================
// Matrix operations
// ============================================================================

impl<R: Runtime> Tensor<R>
where
    R::Client: MatmulOps<R>,
{
    /// Matrix multiplication: self @ other
    pub fn matmul(&self, other: &Tensor<R>) -> Result<Tensor<R>> {
        let client = R::default_client(self.device());
        client.matmul(self, other)
    }
}

// ============================================================================
// Normalization
// ============================================================================

impl<R: Runtime> Tensor<R>
where
    R::Client: NormalizationOps<R>,
{
    /// RMS normalization: x / RMS(x) * weight
    pub fn rms_norm(&self, weight: &Tensor<R>, eps: f32) -> Result<Tensor<R>> {
        let client = R::default_client(self.device());
        client.rms_norm(self, weight, eps)
    }

    /// Layer normalization: (x - mean) / sqrt(var + eps) * weight + bias
    pub fn layer_norm(&self, weight: &Tensor<R>, bias: &Tensor<R>, eps: f32) -> Result<Tensor<R>> {
        let client = R::default_client(self.device());
        client.layer_norm(self, weight, bias, eps)
    }
}

// ============================================================================
// Comparison operations
// ============================================================================

impl<R: Runtime> Tensor<R>
where
    R::Client: CompareOps<R>,
{
    /// Element-wise equality
    pub fn eq(&self, other: &Tensor<R>) -> Result<Tensor<R>> {
        let client = R::default_client(self.device());
        client.eq(self, other)
    }

    /// Element-wise greater than
    pub fn gt(&self, other: &Tensor<R>) -> Result<Tensor<R>> {
        let client = R::default_client(self.device());
        client.gt(self, other)
    }

    /// Element-wise less than
    pub fn lt(&self, other: &Tensor<R>) -> Result<Tensor<R>> {
        let client = R::default_client(self.device());
        client.lt(self, other)
    }
}

// ============================================================================
// Indexing operations
// ============================================================================

impl<R: Runtime> Tensor<R>
where
    R::Client: IndexingOps<R>,
{
    /// Select elements along a dimension using indices
    pub fn index_select(&self, dim: usize, indices: &Tensor<R>) -> Result<Tensor<R>> {
        let client = R::default_client(self.device());
        client.index_select(self, dim, indices)
    }

    /// Argmax along a dimension
    pub fn argmax(&self, dim: usize, keepdim: bool) -> Result<Tensor<R>> {
        let client = R::default_client(self.device());
        client.argmax(self, dim, keepdim)
    }

    /// Argmin along a dimension
    pub fn argmin(&self, dim: usize, keepdim: bool) -> Result<Tensor<R>> {
        let client = R::default_client(self.device());
        client.argmin(self, dim, keepdim)
    }

    /// Fill tensor with value where mask is true
    pub fn masked_fill(&self, mask: &Tensor<R>, value: f64) -> Result<Tensor<R>> {
        let client = R::default_client(self.device());
        client.masked_fill(self, mask, value)
    }

    /// Assign `src` into a slice of `self` along `dim` starting at `start`.
    ///
    /// Returns a new tensor with the slice region replaced by `src`.
    pub fn slice_assign(&self, src: &Tensor<R>, dim: usize, start: usize) -> Result<Tensor<R>> {
        let client = R::default_client(self.device());
        client.slice_assign(self, src, dim, start)
    }
}

// ============================================================================
// Shape operations
// ============================================================================

impl<R: Runtime> Tensor<R>
where
    R::Client: ShapeOps<R>,
{
    /// Concatenate tensors along a dimension
    pub fn cat(tensors: &[&Tensor<R>], dim: isize) -> Result<Tensor<R>> {
        if tensors.is_empty() {
            return Err(crate::error::Error::InvalidArgument {
                arg: "tensors",
                reason: "cannot concatenate empty list".into(),
            });
        }
        let client = R::default_client(tensors[0].device());
        client.cat(tensors, dim)
    }

    /// Stack tensors along a new dimension
    pub fn stack(tensors: &[&Tensor<R>], dim: isize) -> Result<Tensor<R>> {
        if tensors.is_empty() {
            return Err(crate::error::Error::InvalidArgument {
                arg: "tensors",
                reason: "cannot stack empty list".into(),
            });
        }
        let client = R::default_client(tensors[0].device());
        client.stack(tensors, dim)
    }
}

// ============================================================================
// Cumulative operations
// ============================================================================

impl<R: Runtime> Tensor<R>
where
    R::Client: CumulativeOps<R>,
{
    /// Cumulative sum along a dimension
    pub fn cumsum(&self, dim: isize) -> Result<Tensor<R>> {
        let client = R::default_client(self.device());
        client.cumsum(self, dim)
    }

    /// Cumulative product along a dimension
    pub fn cumprod(&self, dim: isize) -> Result<Tensor<R>> {
        let client = R::default_client(self.device());
        client.cumprod(self, dim)
    }

    /// Log-sum-exp along specified dimensions (numerically stable)
    ///
    /// Computes `log(sum(exp(x)))` in a numerically stable way:
    /// `logsumexp(x) = max(x) + log(sum(exp(x - max(x))))`
    pub fn logsumexp(&self, dims: &[usize], keepdim: bool) -> Result<Tensor<R>> {
        let client = R::default_client(self.device());
        client.logsumexp(self, dims, keepdim)
    }
}

// ============================================================================
// Type conversion
// ============================================================================

impl<R: Runtime> Tensor<R>
where
    R::Client: TypeConversionOps<R>,
{
    /// Convert tensor to a different dtype
    pub fn to_dtype(&self, dtype: DType) -> Result<Tensor<R>> {
        let client = R::default_client(self.device());
        client.cast(self, dtype)
    }
}

// ============================================================================
// Utility operations
// ============================================================================

impl<R: Runtime> Tensor<R>
where
    R::Client: UtilityOps<R>,
{
    /// Clamp values to [min, max]
    pub fn clamp(&self, min: f64, max: f64) -> Result<Tensor<R>> {
        let client = R::default_client(self.device());
        client.clamp(self, min, max)
    }

    /// One-hot encode indices
    pub fn one_hot(&self, num_classes: usize) -> Result<Tensor<R>> {
        let client = R::default_client(self.device());
        client.one_hot(self, num_classes)
    }
}

// ============================================================================
// Convolution operations
// ============================================================================

impl<R: Runtime> Tensor<R>
where
    R::Client: ConvOps<R>,
{
    /// 1D convolution
    pub fn conv1d(
        &self,
        weight: &Tensor<R>,
        bias: Option<&Tensor<R>>,
        stride: usize,
        padding: PaddingMode,
        dilation: usize,
        groups: usize,
    ) -> Result<Tensor<R>> {
        let client = R::default_client(self.device());
        client.conv1d(self, weight, bias, stride, padding, dilation, groups)
    }
}