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
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
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
//! Native WGPU GEMM epilogue operations.

use super::helpers::*;
use super::matmul_broadcast::promote_rank1_operands;
use crate::error::{Error, Result};
use crate::ops::matmul::matmul_mkn;
use crate::ops::{
    ActivationOps, BinaryOps, GemmActivation, UnaryOps, matmul_bias_output_shape,
    validate_gemm_epilogue_dtypes,
};
use crate::runtime::ensure_contiguous;
use crate::runtime::traits::client::RuntimeClient;
use crate::runtime::wgpu::shaders::gemm_epilogue;
use crate::runtime::wgpu::shaders::gemm_epilogue_bwd::{
    GemmEpilogueBwdBuffers, launch_gemm_bias_activation_bwd,
};
use crate::runtime::wgpu::{WgpuClient, WgpuRuntime};
use crate::tensor::Tensor;

/// `act(bias)` broadcast over `out_shape`, for a contraction with no terms.
///
/// `A @ B` over `k == 0` sums nothing, so the pre-activation value is the bias
/// alone. The `a` and `b` allocations are zero-byte here and have no buffer to
/// bind, so the epilogue shader cannot run; the same result is built from ops
/// that do have buffers. This is what CPU answers for `k == 0`.
fn bias_only_activation(
    client: &WgpuClient,
    bias: &Tensor<WgpuRuntime>,
    out_shape: &[usize],
    activation: GemmActivation,
) -> Result<Tensor<WgpuRuntime>> {
    let pre = bias.broadcast_to(out_shape)?.contiguous()?;
    match activation {
        GemmActivation::None => Ok(pre),
        GemmActivation::ReLU => client.relu(&pre),
        GemmActivation::GELU => client.gelu(&pre),
        GemmActivation::SiLU => client.silu(&pre),
        GemmActivation::Sigmoid => client.sigmoid(&pre),
        GemmActivation::Tanh => client.tanh(&pre),
    }
}

pub(crate) fn native_gemm_bias_activation(
    client: &WgpuClient,
    a: &Tensor<WgpuRuntime>,
    b: &Tensor<WgpuRuntime>,
    bias: &Tensor<WgpuRuntime>,
    activation: GemmActivation,
) -> Result<Tensor<WgpuRuntime>> {
    let dtype = validate_gemm_epilogue_dtypes(
        a.dtype(),
        b.dtype(),
        bias.dtype(),
        "matmul_bias_activation",
    )?;
    let out_shape = matmul_bias_output_shape(a.shape(), b.shape(), bias.shape())
        .ok_or_else(|| Error::shape_mismatch(a.shape(), b.shape()))?;

    // A rank-1 operand is the matrix the output shape already treats it as.
    if let Some((a2, b2)) = promote_rank1_operands(a, b)? {
        return native_gemm_bias_activation(client, &a2, &b2, bias, activation);
    }

    let a_shape = a.shape();
    let b_shape = b.shape();

    if a_shape.len() == 2 && b_shape.len() == 2 {
        let (m, k, n) = matmul_mkn(a_shape, b_shape);

        let a_c = ensure_contiguous(a)?;
        let b_c = ensure_contiguous(b)?;
        let bias_c = ensure_contiguous(bias)?;
        let out = alloc_output(client, &out_shape, dtype)?;

        // A zero-element output has nothing to compute, and `get_tensor_buffer` has
        // no buffer to return for a zero-byte allocation.
        if out.numel() == 0 {
            return Ok(out);
        }

        // A contraction with no terms over a NON-empty output: `act(bias)`, built
        // without a dispatch because `a` and `b` have no buffer to bind.
        if k == 0 {
            return bias_only_activation(client, &bias_c, &out_shape, activation);
        }

        let a_buf = get_tensor_buffer(&a_c)?;
        let b_buf = get_tensor_buffer(&b_c)?;
        let bias_buf = get_tensor_buffer(&bias_c)?;
        let out_buf = get_tensor_buffer(&out)?;

        let params_buf = gemm_epilogue::create_epilogue_params_buffer(
            client.pipeline_cache(),
            m as u32,
            k as u32,
            n as u32,
            1,
            activation,
        );

        gemm_epilogue::launch_gemm_bias_act(
            client.pipeline_cache(),
            client.wgpu_queue(),
            &a_buf,
            &b_buf,
            &bias_buf,
            &out_buf,
            &params_buf,
            m,
            n,
            dtype,
        )?;

        return Ok(out);
    }

    if a_shape.len() == 3 && b_shape.len() == 3 {
        let batch_size = a_shape[0];
        let (m, k, n) = matmul_mkn(a_shape, b_shape);

        if b_shape[0] != batch_size {
            return Err(Error::ShapeMismatch {
                expected: vec![batch_size, m, k],
                got: b_shape.to_vec(),
            });
        }

        let a_c = ensure_contiguous(a)?;
        let b_c = ensure_contiguous(b)?;
        let bias_c = ensure_contiguous(bias)?;
        let out = alloc_output(client, &out_shape, dtype)?;

        // A zero-element output has nothing to compute, and `get_tensor_buffer` has
        // no buffer to return for a zero-byte allocation.
        if out.numel() == 0 {
            return Ok(out);
        }

        // A contraction with no terms over a NON-empty output: `act(bias)`, built
        // without a dispatch because `a` and `b` have no buffer to bind.
        if k == 0 {
            return bias_only_activation(client, &bias_c, &out_shape, activation);
        }

        let a_buf = get_tensor_buffer(&a_c)?;
        let b_buf = get_tensor_buffer(&b_c)?;
        let bias_buf = get_tensor_buffer(&bias_c)?;
        let out_buf = get_tensor_buffer(&out)?;

        let params_buf = gemm_epilogue::create_epilogue_params_buffer(
            client.pipeline_cache(),
            m as u32,
            k as u32,
            n as u32,
            batch_size as u32,
            activation,
        );

        gemm_epilogue::launch_gemm_bias_act_batched(
            client.pipeline_cache(),
            client.wgpu_queue(),
            &a_buf,
            &b_buf,
            &bias_buf,
            &out_buf,
            &params_buf,
            m,
            n,
            batch_size,
            dtype,
        )?;

        return Ok(out);
    }

    Err(Error::BackendLimitation {
        backend: "WebGPU",
        operation: "gemm_bias_activation",
        reason: format!(
            "only supports 2D and 3D tensors, got shapes {:?} and {:?}",
            a.shape(),
            b.shape()
        ),
    })
}

pub(crate) fn native_gemm_bias_residual(
    client: &WgpuClient,
    a: &Tensor<WgpuRuntime>,
    b: &Tensor<WgpuRuntime>,
    bias: &Tensor<WgpuRuntime>,
    residual: &Tensor<WgpuRuntime>,
) -> Result<Tensor<WgpuRuntime>> {
    let dtype =
        validate_gemm_epilogue_dtypes(a.dtype(), b.dtype(), bias.dtype(), "matmul_bias_residual")?;
    if residual.dtype() != dtype {
        return Err(Error::DTypeMismatch {
            lhs: dtype,
            rhs: residual.dtype(),
        });
    }

    let out_shape = matmul_bias_output_shape(a.shape(), b.shape(), bias.shape())
        .ok_or_else(|| Error::shape_mismatch(a.shape(), b.shape()))?;

    if residual.shape() != out_shape.as_slice() {
        return Err(Error::ShapeMismatch {
            expected: out_shape.clone(),
            got: residual.shape().to_vec(),
        });
    }

    // A rank-1 operand is the matrix the output shape already treats it as.
    if let Some((a2, b2)) = promote_rank1_operands(a, b)? {
        return native_gemm_bias_residual(client, &a2, &b2, bias, residual);
    }

    let a_shape = a.shape();
    let b_shape = b.shape();

    if a_shape.len() == 2 && b_shape.len() == 2 {
        let (m, k, n) = matmul_mkn(a_shape, b_shape);

        let a_c = ensure_contiguous(a)?;
        let b_c = ensure_contiguous(b)?;
        let bias_c = ensure_contiguous(bias)?;
        let res_c = ensure_contiguous(residual)?;
        let out = alloc_output(client, &out_shape, dtype)?;

        // A zero-element output has nothing to compute, and `get_tensor_buffer` has
        // no buffer to return for a zero-byte allocation.
        if out.numel() == 0 {
            return Ok(out);
        }

        // A contraction with no terms over a NON-empty output: the result is
        // `bias + residual`, built without a dispatch because `a` and `b` have no
        // buffer to bind.
        if k == 0 {
            let pre = bias_c.broadcast_to(&out_shape)?.contiguous()?;
            return client.add(&pre, &res_c);
        }

        let a_buf = get_tensor_buffer(&a_c)?;
        let b_buf = get_tensor_buffer(&b_c)?;
        let bias_buf = get_tensor_buffer(&bias_c)?;
        let res_buf = get_tensor_buffer(&res_c)?;
        let out_buf = get_tensor_buffer(&out)?;

        let params_buf = gemm_epilogue::create_residual_params_buffer(
            client.pipeline_cache(),
            m as u32,
            k as u32,
            n as u32,
            1,
        );

        gemm_epilogue::launch_gemm_bias_residual(
            client.pipeline_cache(),
            client.wgpu_queue(),
            &a_buf,
            &b_buf,
            &bias_buf,
            &res_buf,
            &out_buf,
            &params_buf,
            m,
            n,
            dtype,
        )?;

        return Ok(out);
    }

    if a_shape.len() == 3 && b_shape.len() == 3 {
        let batch_size = a_shape[0];
        let (m, k, n) = matmul_mkn(a_shape, b_shape);

        if b_shape[0] != batch_size {
            return Err(Error::ShapeMismatch {
                expected: vec![batch_size, m, k],
                got: b_shape.to_vec(),
            });
        }

        let a_c = ensure_contiguous(a)?;
        let b_c = ensure_contiguous(b)?;
        let bias_c = ensure_contiguous(bias)?;
        let res_c = ensure_contiguous(residual)?;
        let out = alloc_output(client, &out_shape, dtype)?;

        // A zero-element output has nothing to compute, and `get_tensor_buffer` has
        // no buffer to return for a zero-byte allocation.
        if out.numel() == 0 {
            return Ok(out);
        }

        // A contraction with no terms over a NON-empty output: the result is
        // `bias + residual`, built without a dispatch because `a` and `b` have no
        // buffer to bind.
        if k == 0 {
            let pre = bias_c.broadcast_to(&out_shape)?.contiguous()?;
            return client.add(&pre, &res_c);
        }

        let a_buf = get_tensor_buffer(&a_c)?;
        let b_buf = get_tensor_buffer(&b_c)?;
        let bias_buf = get_tensor_buffer(&bias_c)?;
        let res_buf = get_tensor_buffer(&res_c)?;
        let out_buf = get_tensor_buffer(&out)?;

        let params_buf = gemm_epilogue::create_residual_params_buffer(
            client.pipeline_cache(),
            m as u32,
            k as u32,
            n as u32,
            batch_size as u32,
        );

        gemm_epilogue::launch_gemm_bias_residual_batched(
            client.pipeline_cache(),
            client.wgpu_queue(),
            &a_buf,
            &b_buf,
            &bias_buf,
            &res_buf,
            &out_buf,
            &params_buf,
            m,
            n,
            batch_size,
            dtype,
        )?;

        return Ok(out);
    }

    Err(Error::BackendLimitation {
        backend: "WebGPU",
        operation: "gemm_bias_residual",
        reason: format!(
            "only supports 2D and 3D tensors, got shapes {:?} and {:?}",
            a.shape(),
            b.shape()
        ),
    })
}

pub(crate) fn native_gemm_bias_activation_bwd(
    client: &WgpuClient,
    grad: &Tensor<WgpuRuntime>,
    a: &Tensor<WgpuRuntime>,
    b: &Tensor<WgpuRuntime>,
    bias: &Tensor<WgpuRuntime>,
    activation: GemmActivation,
) -> Result<(
    Tensor<WgpuRuntime>,
    Tensor<WgpuRuntime>,
    Tensor<WgpuRuntime>,
)> {
    let dtype = validate_gemm_epilogue_dtypes(
        a.dtype(),
        b.dtype(),
        bias.dtype(),
        "matmul_bias_activation_bwd",
    )?;
    if grad.dtype() != dtype {
        return Err(Error::DTypeMismatch {
            lhs: dtype,
            rhs: grad.dtype(),
        });
    }

    // A rank-1 operand is the matrix the forward treated it as; its gradient
    // comes back in the operand's own shape.
    if let Some((a2, b2)) = promote_rank1_operands(a, b)? {
        let (d_a, d_b, d_bias) =
            native_gemm_bias_activation_bwd(client, grad, &a2, &b2, bias, activation)?;
        return Ok((d_a.reshape(a.shape())?, d_b.reshape(b.shape())?, d_bias));
    }

    let a_shape = a.shape();
    let b_shape = b.shape();

    let (m, k, n) = matmul_mkn(a_shape, b_shape);
    let batch_size = match (a_shape.len(), b_shape.len()) {
        (2, 2) => 1usize,
        (3, 3) => {
            if b_shape[0] != a_shape[0] {
                return Err(Error::ShapeMismatch {
                    expected: vec![a_shape[0], k, n],
                    got: b_shape.to_vec(),
                });
            }
            a_shape[0]
        }
        _ => {
            return Err(Error::BackendLimitation {
                backend: "WebGPU",
                operation: "gemm_bias_activation_bwd",
                reason: format!(
                    "only supports 2D and 3D tensors, got shapes {:?} and {:?}",
                    a_shape, b_shape
                ),
            });
        }
    };

    if b_shape[b_shape.len() - 2] != k {
        return Err(Error::shape_mismatch(a_shape, b_shape));
    }
    // The shaders read `grad` as `[batch, M, N]`, so its shape is checked, not
    // assumed.
    let mut out_shape = a_shape[..a_shape.len() - 2].to_vec();
    out_shape.extend([m, n]);
    if grad.shape() != out_shape.as_slice() {
        return Err(Error::ShapeMismatch {
            expected: out_shape,
            got: grad.shape().to_vec(),
        });
    }

    // No gradient element contributes: `d_a` and `d_b` are either empty or sum
    // over nothing, and `d_bias` sums nothing, so every gradient is zero. The
    // `[batch, M, N]` scratch below is a zero-byte allocation with no buffer to
    // bind, so this must answer first. CPU and CUDA give the same zeros.
    if grad.numel() == 0 {
        return Ok((
            Tensor::<WgpuRuntime>::zeros(a_shape, dtype, RuntimeClient::device(client))?,
            Tensor::<WgpuRuntime>::zeros(b_shape, dtype, RuntimeClient::device(client))?,
            Tensor::<WgpuRuntime>::zeros(&[n], dtype, RuntimeClient::device(client))?,
        ));
    }

    // A contraction with no terms over a NON-empty gradient. `d_a`/`d_b` are
    // empty, but `d_bias` is a REAL reduction of `grad * act'(bias)`: `A @ B`
    // adds nothing, so the pre-activation is the bias alone, as CPU computes.
    // `a`/`b` are zero-byte allocations no dispatch can bind, so substitute a
    // zero-filled `k == 1` contraction — same shader, plus exactly `0.0`, same
    // `d_bias`; it recurses once. Keep after the `grad.numel() == 0` guard.
    if k == 0 {
        let dev = RuntimeClient::device(client);
        let zeros = |s: &[usize]| Tensor::<WgpuRuntime>::zeros(s, dtype, dev);
        let (a1, b1) = if a_shape.len() == 3 {
            (vec![batch_size, m, 1], vec![batch_size, 1, n])
        } else {
            (vec![m, 1], vec![1, n])
        };
        let (_, _, d_bias) = native_gemm_bias_activation_bwd(
            client,
            grad,
            &zeros(&a1)?,
            &zeros(&b1)?,
            bias,
            activation,
        )?;
        return Ok((zeros(a_shape)?, zeros(b_shape)?, d_bias));
    }

    let a_c = ensure_contiguous(a)?;
    let b_c = ensure_contiguous(b)?;
    let bias_c = ensure_contiguous(bias)?;
    let grad_c = ensure_contiguous(grad)?;

    let d_a = alloc_output(client, a_shape, dtype)?;
    // The db shader writes one `[K, N]` slice per batch, so `d_b` is fully
    // written and needs no seeding.
    let d_b = alloc_output(client, b_shape, dtype)?;
    let d_bias = alloc_output(client, &[n], dtype)?;
    // grad_pre scratch has the same shape as grad/output: [batch, M, N].
    let grad_pre = alloc_output(client, grad.shape(), dtype)?;

    let a_buf = get_tensor_buffer(&a_c)?;
    let b_buf = get_tensor_buffer(&b_c)?;
    let bias_buf = get_tensor_buffer(&bias_c)?;
    let grad_buf = get_tensor_buffer(&grad_c)?;
    let grad_pre_buf = get_tensor_buffer(&grad_pre)?;
    let d_a_buf = get_tensor_buffer(&d_a)?;
    let d_b_buf = get_tensor_buffer(&d_b)?;
    let d_bias_buf = get_tensor_buffer(&d_bias)?;

    let params_buf = gemm_epilogue::create_epilogue_params_buffer(
        client.pipeline_cache(),
        m as u32,
        k as u32,
        n as u32,
        batch_size as u32,
        activation,
    );

    let buffers = GemmEpilogueBwdBuffers {
        a: &a_buf,
        b: &b_buf,
        bias: &bias_buf,
        grad: &grad_buf,
        grad_pre: &grad_pre_buf,
        d_a: &d_a_buf,
        d_b: &d_b_buf,
        d_bias: &d_bias_buf,
    };

    launch_gemm_bias_activation_bwd(
        client.pipeline_cache(),
        client.wgpu_queue(),
        &buffers,
        &params_buf,
        m,
        n,
        k,
        batch_size,
        dtype,
    )?;

    Ok((d_a, d_b, d_bias))
}