numr 0.17.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
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
//! Shape operations for WebGPU runtime

use crate::dtype::DType;
use crate::error::{Error, Result};
use crate::ops::impl_generic::{repeat_interleave_impl, unfold_impl};
use crate::ops::{PadMode, ShapeOps};
use crate::runtime::common::shape_ops;
use crate::runtime::common::shape_ops::{validate_cat, validate_stack};
use crate::runtime::wgpu::WgpuClient;
use crate::runtime::wgpu::WgpuRuntime;
use crate::runtime::wgpu::ops::helpers::{
    CatShaderParams, MAX_DIMS, PadParamsF32, PadParamsI32, PadParamsU32, PadReflectParams,
    RepeatParams, RollParams, alloc_output, create_params_buffer, get_tensor_buffer,
    pack_u32_array,
};
use crate::runtime::wgpu::shaders::linear_grid::element_count_u32;
use crate::runtime::wgpu::shaders::shape;
use crate::tensor::Tensor;

use super::pad_replicate::pad_replicate;

impl ShapeOps<WgpuRuntime> for WgpuClient {
    fn cat(&self, tensors: &[&Tensor<WgpuRuntime>], dim: isize) -> Result<Tensor<WgpuRuntime>> {
        let cat_params = validate_cat(tensors, dim)?;

        // Check dtype is supported by WebGPU (F32, I32, U32 are natively supported)
        if !matches!(cat_params.dtype, DType::F32 | DType::I32 | DType::U32) {
            return Err(Error::UnsupportedDType {
                dtype: cat_params.dtype,
                op: "cat",
            });
        }

        // Allocate output
        let out = alloc_output(self, &cat_params.out_shape, cat_params.dtype)?;

        // A zero-element result has nothing to copy, and `get_tensor_buffer` has no
        // buffer to return for a zero-byte allocation.
        if out.numel() == 0 {
            return Ok(out);
        }
        // The output count bounds every size and offset cast to u32 below.
        element_count_u32(out.numel(), "cat")?;

        let out_buf = get_tensor_buffer(&out)?;

        // Copy data from each tensor using WGSL kernel
        let mut cat_offset = 0usize;
        for &tensor in tensors {
            let tensor_contig = tensor.contiguous()?;
            let src_cat_size = tensor.shape()[cat_params.dim_idx];
            let total_elements = cat_params.outer_size * src_cat_size * cat_params.inner_size;

            // An empty operand contributes nothing, and has no buffer to bind.
            if total_elements == 0 {
                continue;
            }

            let src_buf = get_tensor_buffer(&tensor_contig)?;

            let shader_params = CatShaderParams {
                outer_size: cat_params.outer_size as u32,
                src_cat_size: src_cat_size as u32,
                dst_cat_size: cat_params.cat_dim_total as u32,
                cat_offset: cat_offset as u32,
                inner_size: cat_params.inner_size as u32,
                total_elements: total_elements as u32,
            };
            let params_buf = create_params_buffer(self, &shader_params);

            shape::launch_cat_copy(
                self.pipeline_cache(),
                self.wgpu_queue(),
                &src_buf,
                &out_buf,
                &params_buf,
                total_elements,
                cat_params.dtype,
            )?;

            cat_offset += src_cat_size;
        }

        Ok(out)
    }

    fn stack(&self, tensors: &[&Tensor<WgpuRuntime>], dim: isize) -> Result<Tensor<WgpuRuntime>> {
        // Validate tensors and get normalized dimension
        let _ = validate_stack(tensors, dim)?;

        // stack(tensors, dim) = cat([t.unsqueeze(dim) for t in tensors], dim)
        let unsqueezed: Vec<Tensor<WgpuRuntime>> = tensors
            .iter()
            .map(|t| t.unsqueeze(dim))
            .collect::<Result<_>>()?;

        let refs: Vec<&Tensor<WgpuRuntime>> = unsqueezed.iter().collect();
        self.cat(&refs, dim)
    }

    fn split(
        &self,
        tensor: &Tensor<WgpuRuntime>,
        split_size: usize,
        dim: isize,
    ) -> Result<Vec<Tensor<WgpuRuntime>>> {
        shape_ops::split_impl(tensor, split_size, dim)
    }

    fn chunk(
        &self,
        tensor: &Tensor<WgpuRuntime>,
        chunks: usize,
        dim: isize,
    ) -> Result<Vec<Tensor<WgpuRuntime>>> {
        shape_ops::chunk_impl(tensor, chunks, dim)
    }

    fn repeat(
        &self,
        tensor: &Tensor<WgpuRuntime>,
        repeats: &[usize],
    ) -> Result<Tensor<WgpuRuntime>> {
        let params = shape_ops::validate_repeat(tensor, repeats)?;

        // No-op if all repeats are 1
        if repeats.iter().all(|&r| r == 1) {
            return tensor.contiguous();
        }

        // Check dtype is supported by WebGPU
        if !matches!(tensor.dtype(), DType::F32 | DType::I32 | DType::U32) {
            return Err(Error::UnsupportedDType {
                dtype: tensor.dtype(),
                op: "repeat",
            });
        }

        // Check ndim doesn't exceed shader limit
        if params.out_shape.len() > MAX_DIMS {
            return Err(Error::backend_limitation(
                "WebGPU",
                "repeat",
                format!(
                    "max {} dimensions, got {}",
                    MAX_DIMS,
                    params.out_shape.len()
                ),
            ));
        }

        // `contiguous()` handles both non-contiguous strides and nonzero
        // storage offsets; a bare `is_contiguous()` check misses the latter.
        let tensor_contig = tensor.contiguous()?;

        let total_elements: usize = params.out_shape.iter().product();
        // The output is no smaller than the source, so its count bounds every cast.
        element_count_u32(total_elements, "repeat")?;

        // Allocate output
        let out = alloc_output(self, &params.out_shape, tensor.dtype())?;
        let out_buf = get_tensor_buffer(&out)?;
        let src_buf = get_tensor_buffer(&tensor_contig)?;

        // Build flat shape arrays, then pack for WGSL uniform buffer alignment
        let ndim = params.out_shape.len();
        let mut src_shape_flat = [0u32; 8];
        let mut out_shape_flat = [0u32; 8];
        for i in 0..ndim {
            src_shape_flat[i] = tensor.shape()[i] as u32;
            out_shape_flat[i] = params.out_shape[i] as u32;
        }

        let shader_params = RepeatParams {
            ndim: ndim as u32,
            total_elements: total_elements as u32,
            _pad0: 0,
            _pad1: 0,
            src_shape: pack_u32_array(&src_shape_flat),
            out_shape: pack_u32_array(&out_shape_flat),
        };
        let params_buf = create_params_buffer(self, &shader_params);

        shape::launch_repeat(
            self.pipeline_cache(),
            self.wgpu_queue(),
            &src_buf,
            &out_buf,
            &params_buf,
            total_elements,
            tensor.dtype(),
        )?;

        Ok(out)
    }

    fn pad(
        &self,
        tensor: &Tensor<WgpuRuntime>,
        padding: &[usize],
        value: f64,
    ) -> Result<Tensor<WgpuRuntime>> {
        let params = shape_ops::validate_pad(tensor, padding)?;

        // No-op if all padding is zero
        if padding.iter().all(|&p| p == 0) {
            return tensor.contiguous();
        }

        let dtype = tensor.dtype();

        // Check dtype is supported by WebGPU
        if !matches!(dtype, DType::F32 | DType::I32 | DType::U32) {
            return Err(Error::UnsupportedDType { dtype, op: "pad" });
        }

        // Check ndim doesn't exceed shader limit
        if params.out_shape.len() > MAX_DIMS {
            return Err(Error::backend_limitation(
                "WebGPU",
                "pad",
                format!(
                    "max {} dimensions, got {}",
                    MAX_DIMS,
                    params.out_shape.len()
                ),
            ));
        }

        let tensor_contig = tensor.contiguous()?;

        let total_elements: usize = params.out_shape.iter().product();
        // The output is no smaller than the source, so its count bounds every cast.
        element_count_u32(total_elements, "pad")?;

        // Allocate output
        let out = alloc_output(self, &params.out_shape, dtype)?;
        let out_buf = get_tensor_buffer(&out)?;
        let src_buf = get_tensor_buffer(&tensor_contig)?;

        // Build flat shape arrays, then pack for WGSL uniform buffer alignment
        let ndim = params.out_shape.len();
        let mut src_shape_flat = [0u32; 8];
        let mut out_shape_flat = [0u32; 8];
        let mut pad_before_flat = [0u32; 8];
        for i in 0..ndim {
            src_shape_flat[i] = tensor.shape()[i] as u32;
            out_shape_flat[i] = params.out_shape[i] as u32;
            pad_before_flat[i] = params.pad_per_dim[i].0 as u32;
        }

        // Pack arrays for WGSL uniform buffer 16-byte alignment
        let src_shape = pack_u32_array(&src_shape_flat);
        let out_shape = pack_u32_array(&out_shape_flat);
        let pad_before = pack_u32_array(&pad_before_flat);

        // Create dtype-specific params buffer
        let params_buf = match dtype {
            DType::F32 => {
                let shader_params = PadParamsF32 {
                    ndim: ndim as u32,
                    total_elements: total_elements as u32,
                    fill_value: value as f32,
                    _pad0: 0,
                    src_shape,
                    out_shape,
                    pad_before,
                };
                create_params_buffer(self, &shader_params)
            }
            DType::I32 => {
                let shader_params = PadParamsI32 {
                    ndim: ndim as u32,
                    total_elements: total_elements as u32,
                    fill_value: value as i32,
                    _pad0: 0,
                    src_shape,
                    out_shape,
                    pad_before,
                };
                create_params_buffer(self, &shader_params)
            }
            DType::U32 => {
                let shader_params = PadParamsU32 {
                    ndim: ndim as u32,
                    total_elements: total_elements as u32,
                    fill_value: value as u32,
                    _pad0: 0,
                    src_shape,
                    out_shape,
                    pad_before,
                };
                create_params_buffer(self, &shader_params)
            }
            _ => unreachable!("dtype validated above"),
        };

        shape::launch_pad(
            self.pipeline_cache(),
            self.wgpu_queue(),
            &src_buf,
            &out_buf,
            &params_buf,
            total_elements,
            dtype,
        )?;

        Ok(out)
    }

    fn pad_mode(
        &self,
        tensor: &Tensor<WgpuRuntime>,
        padding: &[usize],
        mode: PadMode,
    ) -> Result<Tensor<WgpuRuntime>> {
        match mode {
            PadMode::Constant(value) => return self.pad(tensor, padding, value),
            PadMode::Replicate => return pad_replicate(self, tensor, padding),
            PadMode::Reflect => {}
        }

        let params = shape_ops::validate_reflect_pad(tensor, padding)?;

        // No-op if all padding is zero
        if padding.iter().all(|&p| p == 0) {
            return tensor.contiguous();
        }

        let dtype = tensor.dtype();

        // Check dtype is supported by WebGPU
        if !matches!(dtype, DType::F32 | DType::I32 | DType::U32) {
            return Err(Error::UnsupportedDType {
                dtype,
                op: "pad_reflect",
            });
        }

        // Check ndim doesn't exceed shader limit
        if params.out_shape.len() > MAX_DIMS {
            return Err(Error::backend_limitation(
                "WebGPU",
                "pad_reflect",
                format!(
                    "max {} dimensions, got {}",
                    MAX_DIMS,
                    params.out_shape.len()
                ),
            ));
        }

        let tensor_contig = tensor.contiguous()?;

        let total_elements: usize = params.out_shape.iter().product();
        // The output is no smaller than the source, so its count bounds every cast.
        element_count_u32(total_elements, "pad_reflect")?;

        // Allocate output
        let out = alloc_output(self, &params.out_shape, dtype)?;
        let out_buf = get_tensor_buffer(&out)?;
        let src_buf = get_tensor_buffer(&tensor_contig)?;

        // Build flat shape arrays, then pack for WGSL uniform buffer alignment
        let ndim = params.out_shape.len();
        let mut src_shape_flat = [0u32; 8];
        let mut out_shape_flat = [0u32; 8];
        let mut pad_before_flat = [0u32; 8];
        for i in 0..ndim {
            src_shape_flat[i] = tensor.shape()[i] as u32;
            out_shape_flat[i] = params.out_shape[i] as u32;
            pad_before_flat[i] = params.pad_per_dim[i].0 as u32;
        }

        let shader_params = PadReflectParams {
            ndim: ndim as u32,
            total_elements: total_elements as u32,
            _pad0: 0,
            _pad1: 0,
            src_shape: pack_u32_array(&src_shape_flat),
            out_shape: pack_u32_array(&out_shape_flat),
            pad_before: pack_u32_array(&pad_before_flat),
        };
        let params_buf = create_params_buffer(self, &shader_params);

        shape::launch_pad_reflect(
            self.pipeline_cache(),
            self.wgpu_queue(),
            &src_buf,
            &out_buf,
            &params_buf,
            total_elements,
            dtype,
        )?;

        Ok(out)
    }

    fn roll(
        &self,
        tensor: &Tensor<WgpuRuntime>,
        shift: isize,
        dim: isize,
    ) -> Result<Tensor<WgpuRuntime>> {
        let params = shape_ops::validate_roll(tensor, shift, dim)?;

        // Zero shift is a no-op
        if params.shift == 0 {
            return tensor.contiguous();
        }

        // Check dtype is supported by WebGPU
        if !matches!(tensor.dtype(), DType::F32 | DType::I32 | DType::U32) {
            return Err(Error::UnsupportedDType {
                dtype: tensor.dtype(),
                op: "roll",
            });
        }

        let tensor_contig = tensor.contiguous()?;

        let total_elements = tensor.numel();
        let shape = tensor.shape();

        // Compute outer_size (product of dims before roll dim) and inner_size (product of dims after)
        let outer_size: usize = shape[..params.dim_idx].iter().product();
        let inner_size: usize = shape[params.dim_idx + 1..].iter().product();

        // Allocate output (same shape as input)
        let out = alloc_output(self, shape, tensor.dtype())?;

        // A zero-element tensor has nothing to roll, and `get_tensor_buffer` has no
        // buffer to return for a zero-byte allocation.
        if total_elements == 0 {
            return Ok(out);
        }
        // The element count bounds every size and the shift cast below.
        element_count_u32(total_elements, "roll")?;

        let out_buf = get_tensor_buffer(&out)?;
        let src_buf = get_tensor_buffer(&tensor_contig)?;

        // Unclamped: the guard above rules a zero extent out, and clamping would
        // tell the shader about a row the allocation does not contain.
        let shader_params = RollParams {
            outer_size: outer_size as u32,
            dim_size: params.dim_size as u32,
            inner_size: inner_size as u32,
            shift: params.shift as u32,
            total_elements: total_elements as u32,
            _pad0: 0,
            _pad1: 0,
            _pad2: 0,
        };
        let params_buf = create_params_buffer(self, &shader_params);

        shape::launch_roll(
            self.pipeline_cache(),
            self.wgpu_queue(),
            &src_buf,
            &out_buf,
            &params_buf,
            total_elements,
            tensor.dtype(),
        )?;

        Ok(out)
    }

    fn unfold(
        &self,
        tensor: &Tensor<WgpuRuntime>,
        dim: isize,
        size: usize,
        step: usize,
    ) -> Result<Tensor<WgpuRuntime>> {
        unfold_impl(self, tensor, dim, size, step)
    }

    fn repeat_interleave(
        &self,
        tensor: &Tensor<WgpuRuntime>,
        repeats: usize,
        dim: Option<isize>,
    ) -> Result<Tensor<WgpuRuntime>> {
        repeat_interleave_impl(self, tensor, repeats, dim)
    }
}