numr 0.10.0

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
//! Matrix multiplication WGSL kernel launchers. F32, I32, U32.
//!
//! `matvec` stays F32-only: nothing dispatches it for an integer dtype.

use wgpu::{Buffer, Queue};

use super::pipeline::{LayoutKey, PipelineCache};
use crate::dtype::DType;
use crate::error::{Error, Result};

const MATMUL_SHADER: &str = include_str!("matmul.wgsl");
const MATMUL_BIAS_SHADER: &str = include_str!("matmul_bias_f32.wgsl");
// The integer shaders share one wide accumulator, prepended to each module that
// uses it. WGSL has no include, so this is where the single copy in the
// repository reaches them. `int_saturate.wgsl` must come first: it defines the
// `NumrI64` and range constants `int_matmul_acc.wgsl` builds on, and WGSL has no
// forward declarations.
const MATMUL_I32_SHADER: &str = concat!(
    include_str!("int_saturate.wgsl"),
    include_str!("int_matmul_acc.wgsl"),
    include_str!("matmul_i32.wgsl")
);
const MATMUL_U32_SHADER: &str = concat!(
    include_str!("int_saturate.wgsl"),
    include_str!("int_matmul_acc.wgsl"),
    include_str!("matmul_u32.wgsl")
);
const MATMUL_BIAS_I32_SHADER: &str = concat!(
    include_str!("int_saturate.wgsl"),
    include_str!("int_matmul_acc.wgsl"),
    include_str!("matmul_bias_i32.wgsl")
);
const MATMUL_BIAS_U32_SHADER: &str = concat!(
    include_str!("int_saturate.wgsl"),
    include_str!("int_matmul_acc.wgsl"),
    include_str!("matmul_bias_u32.wgsl")
);

/// Tile size for tiled matrix multiplication (must match shader constant)
const TILE_SIZE: u32 = 16;

// ============================================================================
// DType Dispatch
// ============================================================================

/// The shader module and entry points serving one matmul dtype.
struct MatmulShader {
    module_key: &'static str,
    source: &'static str,
    tiled: &'static str,
    batched: &'static str,
    simple: &'static str,
}

/// The shader module and entry points serving one fused matmul+bias dtype.
struct MatmulBiasShader {
    module_key: &'static str,
    source: &'static str,
    tiled: &'static str,
    batched: &'static str,
}

static MATMUL_F32: MatmulShader = MatmulShader {
    module_key: "matmul",
    source: MATMUL_SHADER,
    tiled: "matmul_f32",
    batched: "batched_matmul_f32",
    simple: "matmul_simple_f32",
};

static MATMUL_I32: MatmulShader = MatmulShader {
    module_key: "matmul_i32",
    source: MATMUL_I32_SHADER,
    tiled: "matmul_i32",
    batched: "batched_matmul_i32",
    simple: "matmul_simple_i32",
};

static MATMUL_U32: MatmulShader = MatmulShader {
    module_key: "matmul_u32",
    source: MATMUL_U32_SHADER,
    tiled: "matmul_u32",
    batched: "batched_matmul_u32",
    simple: "matmul_simple_u32",
};

static MATMUL_BIAS_F32: MatmulBiasShader = MatmulBiasShader {
    module_key: "matmul_bias_f32",
    source: MATMUL_BIAS_SHADER,
    tiled: "matmul_bias_f32",
    batched: "batched_matmul_bias_f32",
};

static MATMUL_BIAS_I32: MatmulBiasShader = MatmulBiasShader {
    module_key: "matmul_bias_i32",
    source: MATMUL_BIAS_I32_SHADER,
    tiled: "matmul_bias_i32",
    batched: "batched_matmul_bias_i32",
};

static MATMUL_BIAS_U32: MatmulBiasShader = MatmulBiasShader {
    module_key: "matmul_bias_u32",
    source: MATMUL_BIAS_U32_SHADER,
    tiled: "matmul_bias_u32",
    batched: "batched_matmul_bias_u32",
};

fn matmul_shader(dtype: DType, op: &'static str) -> Result<&'static MatmulShader> {
    match dtype {
        DType::F32 => Ok(&MATMUL_F32),
        DType::I32 => Ok(&MATMUL_I32),
        DType::U32 => Ok(&MATMUL_U32),
        _ => Err(Error::UnsupportedDType { dtype, op }),
    }
}

fn matmul_bias_shader(dtype: DType, op: &'static str) -> Result<&'static MatmulBiasShader> {
    match dtype {
        DType::F32 => Ok(&MATMUL_BIAS_F32),
        DType::I32 => Ok(&MATMUL_BIAS_I32),
        DType::U32 => Ok(&MATMUL_BIAS_U32),
        _ => Err(Error::UnsupportedDType { dtype, op }),
    }
}

// ============================================================================
// 2D Matrix Multiplication
// ============================================================================

/// Launch tiled matrix multiplication kernel.
///
/// Computes C = A @ B where A is [M, K] and B is [K, N].
pub fn launch_matmul(
    cache: &PipelineCache,
    queue: &Queue,
    a: &Buffer,
    b: &Buffer,
    c: &Buffer,
    params_buffer: &Buffer,
    m: usize,
    n: usize,
    dtype: DType,
) -> Result<()> {
    let shader = matmul_shader(dtype, "matmul")?;

    let module = cache.get_or_create_module(shader.module_key, shader.source);
    let layout = cache.get_or_create_layout(LayoutKey {
        num_storage_buffers: 3,
        num_uniform_buffers: 1,
        num_readonly_storage: 0,
    });
    let pipeline = cache.get_or_create_pipeline(shader.module_key, shader.tiled, &module, &layout);

    let bind_group = cache.create_bind_group(&layout, &[a, b, c, params_buffer]);

    let mut encoder = cache
        .device()
        .create_command_encoder(&wgpu::CommandEncoderDescriptor {
            label: Some("matmul"),
        });

    {
        let mut pass = encoder.begin_compute_pass(&wgpu::ComputePassDescriptor {
            label: Some("matmul"),
            timestamp_writes: None,
        });
        pass.set_pipeline(&pipeline);
        pass.set_bind_group(0, Some(&bind_group), &[]);
        let num_groups_x = (n as u32 + TILE_SIZE - 1) / TILE_SIZE;
        let num_groups_y = (m as u32 + TILE_SIZE - 1) / TILE_SIZE;
        pass.dispatch_workgroups(num_groups_x, num_groups_y, 1);
    }

    queue.submit(std::iter::once(encoder.finish()));
    Ok(())
}

/// Launch simple (non-tiled) matrix multiplication kernel.
///
/// For small matrices where tiling overhead isn't worth it.
pub fn launch_matmul_simple(
    cache: &PipelineCache,
    queue: &Queue,
    a: &Buffer,
    b: &Buffer,
    c: &Buffer,
    params_buffer: &Buffer,
    m: usize,
    n: usize,
    dtype: DType,
) -> Result<()> {
    let shader = matmul_shader(dtype, "matmul_simple")?;

    let module = cache.get_or_create_module(shader.module_key, shader.source);
    let layout = cache.get_or_create_layout(LayoutKey {
        num_storage_buffers: 3,
        num_uniform_buffers: 1,
        num_readonly_storage: 0,
    });
    let pipeline = cache.get_or_create_pipeline(shader.module_key, shader.simple, &module, &layout);

    let bind_group = cache.create_bind_group(&layout, &[a, b, c, params_buffer]);

    let mut encoder = cache
        .device()
        .create_command_encoder(&wgpu::CommandEncoderDescriptor {
            label: Some("matmul_simple"),
        });

    {
        let mut pass = encoder.begin_compute_pass(&wgpu::ComputePassDescriptor {
            label: Some("matmul_simple"),
            timestamp_writes: None,
        });
        pass.set_pipeline(&pipeline);
        pass.set_bind_group(0, Some(&bind_group), &[]);
        let total = m * n;
        let num_groups = (total as u32 + 255) / 256;
        pass.dispatch_workgroups(num_groups, 1, 1);
    }

    queue.submit(std::iter::once(encoder.finish()));
    Ok(())
}

// ============================================================================
// Batched Matrix Multiplication
// ============================================================================

/// Launch batched matrix multiplication kernel.
///
/// Computes `C[b] = A[b] @ B[b]` for each batch b.
pub fn launch_batched_matmul(
    cache: &PipelineCache,
    queue: &Queue,
    a: &Buffer,
    b: &Buffer,
    c: &Buffer,
    params_buffer: &Buffer,
    m: usize,
    n: usize,
    batch_size: usize,
    dtype: DType,
) -> Result<()> {
    let shader = matmul_shader(dtype, "batched_matmul")?;

    let module = cache.get_or_create_module(shader.module_key, shader.source);
    let layout = cache.get_or_create_layout(LayoutKey {
        num_storage_buffers: 3,
        num_uniform_buffers: 1,
        num_readonly_storage: 0,
    });
    let pipeline =
        cache.get_or_create_pipeline(shader.module_key, shader.batched, &module, &layout);

    let bind_group = cache.create_bind_group(&layout, &[a, b, c, params_buffer]);

    let mut encoder = cache
        .device()
        .create_command_encoder(&wgpu::CommandEncoderDescriptor {
            label: Some("batched_matmul"),
        });

    {
        let mut pass = encoder.begin_compute_pass(&wgpu::ComputePassDescriptor {
            label: Some("batched_matmul"),
            timestamp_writes: None,
        });
        pass.set_pipeline(&pipeline);
        pass.set_bind_group(0, Some(&bind_group), &[]);
        let num_groups_x = (n as u32 + TILE_SIZE - 1) / TILE_SIZE;
        let num_groups_y = (m as u32 + TILE_SIZE - 1) / TILE_SIZE;
        pass.dispatch_workgroups(num_groups_x, num_groups_y, batch_size as u32);
    }

    queue.submit(std::iter::once(encoder.finish()));
    Ok(())
}

// ============================================================================
// Matrix-Vector Multiplication
// ============================================================================

/// Launch matrix-vector multiplication kernel.
///
/// Computes y = A @ x where A is `[M, N]` and x is `[N]`.
pub fn launch_matvec(
    cache: &PipelineCache,
    queue: &Queue,
    a: &Buffer,
    x: &Buffer,
    y: &Buffer,
    params_buffer: &Buffer,
    m: usize,
    dtype: DType,
) -> Result<()> {
    if dtype != DType::F32 {
        return Err(Error::UnsupportedDType {
            dtype,
            op: "matvec",
        });
    }

    let module = cache.get_or_create_module("matmul", MATMUL_SHADER);
    let layout = cache.get_or_create_layout(LayoutKey {
        num_storage_buffers: 3,
        num_uniform_buffers: 1,
        num_readonly_storage: 0,
    });
    let pipeline = cache.get_or_create_pipeline("matmul", "matvec_f32", &module, &layout);

    let bind_group = cache.create_bind_group(&layout, &[a, x, y, params_buffer]);

    let mut encoder = cache
        .device()
        .create_command_encoder(&wgpu::CommandEncoderDescriptor {
            label: Some("matvec"),
        });

    {
        let mut pass = encoder.begin_compute_pass(&wgpu::ComputePassDescriptor {
            label: Some("matvec"),
            timestamp_writes: None,
        });
        pass.set_pipeline(&pipeline);
        pass.set_bind_group(0, Some(&bind_group), &[]);
        pass.dispatch_workgroups(m as u32, 1, 1);
    }

    queue.submit(std::iter::once(encoder.finish()));
    Ok(())
}

// ============================================================================
// Fused Matrix Multiplication with Bias
// ============================================================================

/// Launch tiled matrix multiplication with fused bias addition.
///
/// Computes C = A @ B + bias where bias is `[N]` (broadcast across rows).
pub fn launch_matmul_bias(
    cache: &PipelineCache,
    queue: &Queue,
    a: &Buffer,
    b: &Buffer,
    bias: &Buffer,
    c: &Buffer,
    params_buffer: &Buffer,
    m: usize,
    n: usize,
    dtype: DType,
) -> Result<()> {
    let shader = matmul_bias_shader(dtype, "matmul_bias")?;

    let module = cache.get_or_create_module(shader.module_key, shader.source);
    let layout = cache.get_or_create_layout(LayoutKey {
        num_storage_buffers: 4, // a, b, bias, c
        num_uniform_buffers: 1,
        num_readonly_storage: 0,
    });
    let pipeline = cache.get_or_create_pipeline(shader.module_key, shader.tiled, &module, &layout);

    let bind_group = cache.create_bind_group(&layout, &[a, b, bias, c, params_buffer]);

    let mut encoder = cache
        .device()
        .create_command_encoder(&wgpu::CommandEncoderDescriptor {
            label: Some("matmul_bias"),
        });

    {
        let mut pass = encoder.begin_compute_pass(&wgpu::ComputePassDescriptor {
            label: Some("matmul_bias"),
            timestamp_writes: None,
        });
        pass.set_pipeline(&pipeline);
        pass.set_bind_group(0, Some(&bind_group), &[]);
        let num_groups_x = (n as u32 + TILE_SIZE - 1) / TILE_SIZE;
        let num_groups_y = (m as u32 + TILE_SIZE - 1) / TILE_SIZE;
        pass.dispatch_workgroups(num_groups_x, num_groups_y, 1);
    }

    queue.submit(std::iter::once(encoder.finish()));
    Ok(())
}

/// Launch batched matrix multiplication with fused bias addition.
///
/// Computes `C[b] = A[b] @ B[b] + bias` for each batch b.
pub fn launch_batched_matmul_bias(
    cache: &PipelineCache,
    queue: &Queue,
    a: &Buffer,
    b: &Buffer,
    bias: &Buffer,
    c: &Buffer,
    params_buffer: &Buffer,
    m: usize,
    n: usize,
    batch_size: usize,
    dtype: DType,
) -> Result<()> {
    let shader = matmul_bias_shader(dtype, "batched_matmul_bias")?;

    let module = cache.get_or_create_module(shader.module_key, shader.source);
    let layout = cache.get_or_create_layout(LayoutKey {
        num_storage_buffers: 4, // a, b, bias, c
        num_uniform_buffers: 1,
        num_readonly_storage: 0,
    });
    let pipeline =
        cache.get_or_create_pipeline(shader.module_key, shader.batched, &module, &layout);

    let bind_group = cache.create_bind_group(&layout, &[a, b, bias, c, params_buffer]);

    let mut encoder = cache
        .device()
        .create_command_encoder(&wgpu::CommandEncoderDescriptor {
            label: Some("batched_matmul_bias"),
        });

    {
        let mut pass = encoder.begin_compute_pass(&wgpu::ComputePassDescriptor {
            label: Some("batched_matmul_bias"),
            timestamp_writes: None,
        });
        pass.set_pipeline(&pipeline);
        pass.set_bind_group(0, Some(&bind_group), &[]);
        let num_groups_x = (n as u32 + TILE_SIZE - 1) / TILE_SIZE;
        let num_groups_y = (m as u32 + TILE_SIZE - 1) / TILE_SIZE;
        pass.dispatch_workgroups(num_groups_x, num_groups_y, batch_size as u32);
    }

    queue.submit(std::iter::once(encoder.finish()));
    Ok(())
}