ferrotensor 0.3.0

GPU-accelerated machine learning library for training and inference in Rust
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
489
490
491
492
493
494
495
//! Device dispatch for the primitive kernels.
//!
//! Every `*_raw` method computes a fresh tensor with no autograd node: on a
//! GPU device it dispatches the WGSL kernel, on the CPU it runs the matching
//! reference kernel in [`super::cpu`]. The public ops in `ops.rs` build on
//! these and attach backward nodes.

use wgpu::util::DeviceExt;
use wgpu::{Buffer, BufferUsages};

use super::core::{alloc, Storage};
use super::cpu;
use super::shape::{broadcast_shapes, broadcast_strides, contiguous_strides, split_at_dim};
use super::Tensor;
use crate::backend::{reduce_op, ComputeEngine};
use crate::device::{Arg, GpuBuffer, GpuContext};

/// A read-only `u32` storage buffer (at least one element).
fn u32_buffer(ctx: &GpuContext, data: &[u32]) -> Buffer {
    let padded: &[u32] = if data.is_empty() { &[0] } else { data };
    ctx.device
        .create_buffer_init(&wgpu::util::BufferInitDescriptor {
            label: Some("Meta"),
            contents: bytemuck::cast_slice(padded),
            usage: BufferUsages::STORAGE,
        })
}

fn as_u32(values: &[usize]) -> Vec<u32> {
    values
        .iter()
        .map(|&v| u32::try_from(v).expect("tensor dimension exceeds u32"))
        .collect()
}

/// Threads per workgroup of `reduce_all` and `arg_reduce`.
const GROUP: usize = 256;
/// Workgroups the first pass of a full reduction is spread over.
const FIRST_PASS_GROUPS: usize = 256;

/// Reduce the first `n` elements of `input` into `out[0]`: one pass of
/// `FIRST_PASS_GROUPS` workgroups leaves a partial per workgroup and a
/// one-workgroup pass combines them.
fn reduce_all(ctx: &GpuContext, input: &Buffer, out: &Buffer, op: u32, n: usize) {
    let params = |n: usize| Arg::Params([op, n as u32, 0, 0]);
    let groups = n.div_ceil(GROUP).min(FIRST_PASS_GROUPS);
    if groups == 1 {
        ctx.dispatch(
            "reduce_all",
            &[Arg::Buffer(input), Arg::Buffer(out), params(n)],
            (1, 1, 1),
        );
        return;
    }
    let partials = alloc(ctx, groups);
    ctx.dispatch(
        "reduce_all",
        &[Arg::Buffer(input), Arg::Buffer(&partials), params(n)],
        (groups as u32, 1, 1),
    );
    ctx.dispatch(
        "reduce_all",
        &[Arg::Buffer(&partials), Arg::Buffer(out), params(groups)],
        (1, 1, 1),
    );
}

/// The `arg_reduce` kernel over `input` viewed as `[outputs / inner, dim,
/// inner]`. Gives one `f32` index per output, or with `pairs` a (value bits,
/// index) pair per output. When there are too few outputs to fill the GPU,
/// each one is split over several workgroups and a second pass combines them.
fn arg_reduce(
    ctx: &GpuContext,
    input: &Buffer,
    smallest: bool,
    pairs: bool,
    outputs: usize,
    dim: usize,
    inner: usize,
) -> GpuBuffer {
    const MIN: u32 = 1;
    const PAIRS_IN: u32 = 2;
    const PAIRS_OUT: u32 = 4;
    let flags = if smallest { MIN } else { 0 };
    let last = if pairs { flags | PAIRS_OUT } else { flags };
    let out = alloc(ctx, if pairs { 2 * outputs } else { outputs });
    let run =
        |input: &Buffer, out: &Buffer, flags: u32, dim: usize, inner: usize, splits: usize| {
            let meta = as_u32(&[flags as usize, outputs, dim, inner, splits]);
            ctx.dispatch(
                "arg_reduce",
                &[Arg::Buffer(input), Arg::Buffer(out), Arg::Meta(&meta)],
                ComputeEngine::workgroup_grid(outputs * splits),
            );
        };
    let splits = (FIRST_PASS_GROUPS / outputs).clamp(1, dim.div_ceil(GROUP));
    if splits == 1 {
        run(input, &out, last, dim, inner, 1);
    } else {
        let partials = alloc(ctx, 2 * outputs * splits);
        run(input, &partials, flags | PAIRS_OUT, dim, inner, splits);
        run(&partials, &out, last | PAIRS_IN, splits, 1, 1);
    }
    out
}

impl Tensor {
    /// The GPU context and buffer, when this tensor lives on a GPU.
    fn gpu(&self) -> Option<(&GpuContext, &Buffer)> {
        match (self.device.gpu_ctx(), &*self.storage) {
            (Some(ctx), Storage::Gpu(buffer)) => Some((ctx, buffer)),
            _ => None,
        }
    }

    fn gpu_output(&self, buffer: GpuBuffer, shape: Vec<usize>) -> Tensor {
        Tensor::from_storage(Storage::Gpu(buffer), shape, &self.device)
    }

    /// A new tensor on this tensor's device.
    pub(crate) fn host_output(&self, data: Vec<f32>, shape: &[usize]) -> Tensor {
        Tensor::from_vec(data, shape, &self.device)
    }

    pub(crate) fn assert_same_device(&self, other: &Tensor) {
        assert!(
            self.device.same_as(&other.device),
            "tensors are on different devices ({} and {})",
            self.device.name(),
            other.device.name()
        );
    }

    /// A copy with its own storage (no autograd).
    pub fn deep_clone(&self) -> Tensor {
        match self.gpu() {
            Some((ctx, buffer)) => {
                let out = alloc(ctx, self.numel());
                ctx.copy(buffer, &out, (self.numel().max(1) * 4) as u64);
                self.gpu_output(out, self.shape.clone())
            }
            None => self.host_output(self.to_vec(), &self.shape),
        }
    }

    /// Element-wise op `op` (see `backend::unary_op`) with scalars `a`, `b`.
    pub(crate) fn unary_raw(&self, op: u32, a: f32, b: f32) -> Tensor {
        let n = self.numel();
        match self.gpu() {
            Some((ctx, input)) if n > 0 => {
                let out = alloc(ctx, n);
                let params = Arg::Params([op, n as u32, a.to_bits(), b.to_bits()]);
                ctx.dispatch(
                    "unary",
                    &[Arg::Buffer(input), Arg::Buffer(&out), params],
                    ComputeEngine::workgroups_1d(n),
                );
                self.gpu_output(out, self.shape.clone())
            }
            _ => self.host_output(cpu::unary(op, &self.to_vec(), a, b), &self.shape),
        }
    }

    /// Broadcasting binary op `op` (see `backend::binary_op`).
    ///
    /// # Panics
    /// Panics when the shapes cannot be broadcast together.
    pub(crate) fn binary_raw(&self, other: &Tensor, op: u32) -> Tensor {
        self.assert_same_device(other);
        let out_shape = broadcast_shapes(&self.shape, &other.shape).unwrap_or_else(|| {
            panic!(
                "shapes {:?} and {:?} cannot be broadcast together",
                self.shape, other.shape
            )
        });
        let sa = broadcast_strides(&self.shape, &out_shape);
        let sb = broadcast_strides(&other.shape, &out_shape);
        let n: usize = out_shape.iter().product();
        match (self.gpu(), other.gpu()) {
            (Some((ctx, a)), Some((_, b))) if n > 0 => {
                let out = alloc(ctx, n);
                let params = Arg::Params([op, n as u32, out_shape.len() as u32, 0]);
                let meta = as_u32(&[&out_shape[..], &sa, &sb].concat());
                ctx.dispatch(
                    "binary",
                    &[
                        Arg::Buffer(a),
                        Arg::Buffer(b),
                        Arg::Buffer(&out),
                        params,
                        Arg::Meta(&meta),
                    ],
                    ComputeEngine::workgroups_1d(n),
                );
                self.gpu_output(out, out_shape)
            }
            _ => {
                let data = cpu::binary(op, &self.to_vec(), &sa, &other.to_vec(), &sb, &out_shape);
                self.host_output(data, &out_shape)
            }
        }
    }

    /// Reduce over `dim` (removed from the shape) with `op` (see
    /// `backend::reduce_op`).
    pub(crate) fn reduce_raw(&self, dim: usize, op: u32) -> Tensor {
        let (outer, size, inner) = split_at_dim(&self.shape, dim);
        let mut out_shape = self.shape.clone();
        out_shape.remove(dim);
        if size == 0 {
            assert_eq!(op, reduce_op::SUM, "max/min of an empty dimension");
            return Tensor::zeros(&out_shape, &self.device);
        }
        let n = outer * inner;
        match self.gpu() {
            Some((ctx, input)) if n == 1 => {
                let out = alloc(ctx, 1);
                reduce_all(ctx, input, &out, op, size);
                self.gpu_output(out, out_shape)
            }
            Some((ctx, input)) if n > 0 => {
                let out = alloc(ctx, n);
                let params = Arg::Params([op, outer as u32, size as u32, inner as u32]);
                ctx.dispatch(
                    "reduce",
                    &[Arg::Buffer(input), Arg::Buffer(&out), params],
                    ComputeEngine::workgroups_1d(n),
                );
                self.gpu_output(out, out_shape)
            }
            _ => {
                let data = cpu::reduce(op, &self.to_vec(), outer, size, inner);
                self.host_output(data, &out_shape)
            }
        }
    }

    /// Index along `dim` (removed from the shape) of the first largest
    /// element, or with `smallest` the first smallest, as `f32`.
    pub(crate) fn arg_reduce_raw(&self, dim: usize, smallest: bool) -> Tensor {
        let (outer, size, inner) = split_at_dim(&self.shape, dim);
        let mut out_shape = self.shape.clone();
        out_shape.remove(dim);
        match self.gpu() {
            Some((ctx, input)) if outer * inner > 0 && size > 0 => {
                let out = arg_reduce(ctx, input, smallest, false, outer * inner, size, inner);
                self.gpu_output(out, out_shape)
            }
            _ => {
                let data = cpu::arg_reduce(smallest, &self.to_vec(), outer, size, inner);
                self.host_output(data, &out_shape)
            }
        }
    }

    /// Flat index of the first largest element, or with `smallest` the first
    /// smallest; 0 for an empty tensor. On a GPU only the index is read back.
    pub(crate) fn arg_index_raw(&self, smallest: bool) -> usize {
        let n = self.numel();
        match self.gpu() {
            Some((ctx, input)) if n > 0 => {
                let out = arg_reduce(ctx, input, smallest, true, 1, n, 1);
                let pair = self.gpu_output(out, vec![2]).to_vec();
                pair[1].to_bits() as usize
            }
            _ => cpu::arg_extreme(smallest, &self.to_vec()),
        }
    }

    /// Softmax (or log-softmax) over `dim`.
    pub(crate) fn softmax_raw(&self, dim: usize, log: bool) -> Tensor {
        let (outer, size, inner) = split_at_dim(&self.shape, dim);
        let n = outer * inner;
        match self.gpu() {
            Some((ctx, input)) if n > 0 && size > 0 => {
                let out = alloc(ctx, self.numel());
                let params = Arg::Params([log as u32, outer as u32, size as u32, inner as u32]);
                ctx.dispatch(
                    "softmax",
                    &[Arg::Buffer(input), Arg::Buffer(&out), params],
                    ComputeEngine::workgroups_1d(n),
                );
                self.gpu_output(out, self.shape.clone())
            }
            _ => {
                let data = cpu::softmax(&self.to_vec(), outer, size, inner, log);
                self.host_output(data, &self.shape)
            }
        }
    }

    /// Matrix product over the last two dims, with leading batch dims that
    /// are either equal or present on one side only.
    pub(crate) fn matmul_raw(&self, other: &Tensor) -> Tensor {
        self.assert_same_device(other);
        assert!(
            self.ndim() >= 2 && other.ndim() >= 2,
            "matmul needs tensors with at least 2 dims, got {:?} and {:?}",
            self.shape,
            other.shape
        );
        let (m, k) = (self.shape[self.ndim() - 2], self.shape[self.ndim() - 1]);
        let (k2, n) = (other.shape[other.ndim() - 2], other.shape[other.ndim() - 1]);
        assert_eq!(
            k, k2,
            "matmul inner dimensions differ: {:?} @ {:?}",
            self.shape, other.shape
        );
        let a_batch = &self.shape[..self.ndim() - 2];
        let b_batch = &other.shape[..other.ndim() - 2];
        let (batch_shape, a_batched, b_batched) = if a_batch == b_batch {
            (a_batch.to_vec(), true, true)
        } else if b_batch.is_empty() {
            (a_batch.to_vec(), true, false)
        } else if a_batch.is_empty() {
            (b_batch.to_vec(), false, true)
        } else {
            panic!(
                "matmul batch dims must match or be absent on one side: {:?} @ {:?}",
                self.shape, other.shape
            );
        };
        let batch: usize = batch_shape.iter().product();
        let out_shape = [&batch_shape[..], &[m, n]].concat();

        // A batched left side against a shared right matrix is one big matmul.
        let (rows, batches, a_flag, b_flag) = if a_batched && !b_batched {
            (batch * m, 1, false, false)
        } else {
            (m, batch, a_batched, b_batched)
        };

        let total = batch * m * n;
        match (self.gpu(), other.gpu()) {
            (Some((ctx, a)), Some((_, b))) if total > 0 && k > 0 => {
                let out = alloc(ctx, total);
                let flags = a_flag as u32 | ((b_flag as u32) << 1);
                let params = Arg::Params([rows as u32, k as u32, n as u32, flags]);
                ctx.dispatch(
                    "matmul",
                    &[Arg::Buffer(a), Arg::Buffer(b), Arg::Buffer(&out), params],
                    ComputeEngine::workgroups_matmul(rows, n, batches),
                );
                self.gpu_output(out, out_shape)
            }
            _ => {
                let data = cpu::matmul(
                    &self.to_vec(),
                    &other.to_vec(),
                    rows,
                    k,
                    n,
                    batches,
                    a_flag,
                    b_flag,
                );
                self.host_output(data, &out_shape)
            }
        }
    }

    /// Copy into `out_shape`, reading output dim `d` with source stride
    /// `src_strides[d]`, starting at element `offset`.
    pub(crate) fn strided_copy_raw(
        &self,
        out_shape: &[usize],
        src_strides: &[usize],
        offset: usize,
    ) -> Tensor {
        let n: usize = out_shape.iter().product();
        match self.gpu() {
            Some((ctx, input)) if n > 0 => {
                let out = alloc(ctx, n);
                let params = Arg::Params([n as u32, out_shape.len() as u32, offset as u32, 0]);
                let meta = as_u32(&[out_shape, src_strides].concat());
                ctx.dispatch(
                    "permute",
                    &[
                        Arg::Buffer(input),
                        Arg::Buffer(&out),
                        params,
                        Arg::Meta(&meta),
                    ],
                    ComputeEngine::workgroups_1d(n),
                );
                self.gpu_output(out, out_shape.to_vec())
            }
            _ => {
                let data = cpu::permute(&self.to_vec(), out_shape, src_strides, offset);
                self.host_output(data, out_shape)
            }
        }
    }

    /// Reorder dimensions: output dim `d` is input dim `perm[d]`.
    pub(crate) fn permute_raw(&self, perm: &[usize]) -> Tensor {
        let strides = contiguous_strides(&self.shape);
        let out_shape: Vec<usize> = perm.iter().map(|&p| self.shape[p]).collect();
        let src_strides: Vec<usize> = perm.iter().map(|&p| strides[p]).collect();
        self.strided_copy_raw(&out_shape, &src_strides, 0)
    }

    /// Broadcast to `shape` (materialised).
    pub(crate) fn expand_raw(&self, shape: &[usize]) -> Tensor {
        if self.shape == shape {
            return self.clone();
        }
        let strides = broadcast_strides(&self.shape, shape);
        self.strided_copy_raw(shape, &strides, 0)
    }

    /// Rows of the first dimension picked by `idx`.
    pub(crate) fn gather_rows_raw(&self, idx: &[usize]) -> Tensor {
        let rows = self.shape[0];
        let row: usize = self.shape[1..].iter().product();
        for &i in idx {
            assert!(
                i < rows,
                "index {i} out of range for dimension of size {rows}"
            );
        }
        let out_shape = [&[idx.len()][..], &self.shape[1..]].concat();
        let idx32 = as_u32(idx);
        let n = idx.len() * row;
        match self.gpu() {
            Some((ctx, table)) if n > 0 => {
                let out = alloc(ctx, n);
                let indices = u32_buffer(ctx, &idx32);
                let params = Arg::Params([idx.len() as u32, row as u32, rows as u32, 0]);
                ctx.dispatch(
                    "gather_rows",
                    &[
                        Arg::Buffer(table),
                        Arg::Buffer(&indices),
                        Arg::Buffer(&out),
                        params,
                    ],
                    ComputeEngine::workgroups_1d(n),
                );
                self.gpu_output(out, out_shape)
            }
            _ => {
                let data = cpu::gather_rows(&self.to_vec(), &idx32, row);
                self.host_output(data, &out_shape)
            }
        }
    }

    /// Rows of this `[rows, ..]` table picked by the ids stored as `f32` in
    /// `ids`; the result has shape `ids.shape + self.shape[1..]`. An id
    /// outside `[0, rows)` gives a row of zeros.
    ///
    /// On a GPU the ids are read on the device, with no copy to the host.
    pub(crate) fn gather_rows_by_ids_raw(&self, ids: &Tensor) -> Tensor {
        let rows = self.shape[0];
        let row: usize = self.shape[1..].iter().product();
        let out_shape = [&ids.shape[..], &self.shape[1..]].concat();
        let n = ids.numel() * row;
        let ids = ids.to_device(&self.device);
        match (self.gpu(), ids.gpu()) {
            (Some((ctx, table)), Some((_, idx))) if n > 0 => {
                let out = alloc(ctx, n);
                let params = Arg::Params([ids.numel() as u32, row as u32, rows as u32, 1]);
                ctx.dispatch(
                    "gather_rows",
                    &[
                        Arg::Buffer(table),
                        Arg::Buffer(idx),
                        Arg::Buffer(&out),
                        params,
                    ],
                    ComputeEngine::workgroups_1d(n),
                );
                self.gpu_output(out, out_shape)
            }
            _ => {
                let table = self.to_vec();
                let mut out = vec![0.0; n];
                for (r, id) in valid_ids(&ids.to_vec(), rows) {
                    out[r * row..][..row].copy_from_slice(&table[id * row..][..row]);
                }
                self.host_output(out, &out_shape)
            }
        }
    }
}

/// `(position, row)` of each id in `ids` that is in `[0, rows)`, matching the
/// `gather_rows` kernel's `f32` id handling.
pub(crate) fn valid_ids(ids: &[f32], rows: usize) -> impl Iterator<Item = (usize, usize)> + '_ {
    ids.iter()
        .enumerate()
        .filter(move |&(_, &v)| v >= 0.0 && v < rows as f32)
        .map(|(r, &v)| (r, v as usize))
}