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
//! WGSL compute pipeline infrastructure
//!
//! Provides pipeline caching and dispatch utilities for WGSL compute shaders.
//! Follows the same pattern as CUDA kernel launchers for DRY consistency.

use parking_lot::Mutex;
use std::collections::HashMap;
use std::num::NonZeroU64;
use std::sync::Arc;
use wgpu::{
    BindGroup, BindGroupDescriptor, BindGroupEntry, BindGroupLayout, BindGroupLayoutDescriptor,
    BindGroupLayoutEntry, BindingResource, BindingType, Buffer, BufferBinding, BufferBindingType,
    BufferUsages, ComputePipeline, ComputePipelineDescriptor, Device, PipelineLayoutDescriptor,
    Queue, ShaderModule, ShaderModuleDescriptor, ShaderSource, ShaderStages,
};

use super::binding_limits::{BIND_GROUP_OP, binding_range_size, check_binding_size};

use crate::dtype::DType;
use crate::error::{Error, Result};

/// Workgroup size for compute shaders (matches CUDA BLOCK_SIZE)
pub const WORKGROUP_SIZE: u32 = 256;

// ============================================================================
// Pipeline Cache
// ============================================================================

/// Cache for compute pipelines keyed by (shader_name, dtype)
pub struct PipelineCache {
    device: Arc<Device>,
    #[allow(dead_code)]
    queue: Arc<Queue>,
    /// Cached shader modules by name
    modules: Mutex<HashMap<&'static str, Arc<ShaderModule>>>,
    /// Cached shader modules by dynamic name (for generated shaders)
    dynamic_modules: Mutex<HashMap<String, Arc<ShaderModule>>>,
    /// Cached pipelines by (shader_name, entry_point)
    pipelines: Mutex<HashMap<(&'static str, &'static str), Arc<ComputePipeline>>>,
    /// Cached pipelines with dynamic keys (for generated shaders)
    dynamic_pipelines: Mutex<HashMap<(String, String), Arc<ComputePipeline>>>,
    /// Cached bind group layouts by layout key
    layouts: Mutex<HashMap<LayoutKey, Arc<BindGroupLayout>>>,
    /// Layouts whose final uniform binding uses a dynamic offset.
    dynamic_uniform_layouts: Mutex<HashMap<(u32, u32), Arc<BindGroupLayout>>>,
}

/// Key for bind group layout cache
#[derive(Clone, Copy, PartialEq, Eq, Hash)]
pub struct LayoutKey {
    /// Number of storage buffers in the layout
    pub num_storage_buffers: u32,
    /// Number of uniform buffers in the layout
    pub num_uniform_buffers: u32,
    /// Number of leading storage buffers that are read-only.
    /// Bindings 0..num_readonly_storage are read-only,
    /// bindings num_readonly_storage..num_storage_buffers are read-write.
    /// Default: 0 (all read-write, backwards compatible).
    pub num_readonly_storage: u32,
}

impl PipelineCache {
    /// Create a new pipeline cache
    pub fn new(device: Arc<Device>, queue: Arc<Queue>) -> Self {
        Self {
            device,
            queue,
            modules: Mutex::new(HashMap::new()),
            dynamic_modules: Mutex::new(HashMap::new()),
            pipelines: Mutex::new(HashMap::new()),
            dynamic_pipelines: Mutex::new(HashMap::new()),
            layouts: Mutex::new(HashMap::new()),
            dynamic_uniform_layouts: Mutex::new(HashMap::new()),
        }
    }

    /// Get or create a shader module
    pub fn get_or_create_module(&self, name: &'static str, source: &str) -> Arc<ShaderModule> {
        let mut modules = self.modules.lock();
        if let Some(module) = modules.get(name) {
            return module.clone();
        }

        let module = self.device.create_shader_module(ShaderModuleDescriptor {
            label: Some(name),
            source: ShaderSource::Wgsl(source.into()),
        });

        let module = Arc::new(module);
        modules.insert(name, module.clone());
        module
    }

    /// Get or create a shader module from dynamically generated source
    ///
    /// This variant accepts owned strings for cases where shader source is generated
    /// at runtime (e.g., multi-dtype shader generation).
    pub fn get_or_create_module_from_source(&self, name: &str, source: &str) -> Arc<ShaderModule> {
        let mut modules = self.dynamic_modules.lock();
        if let Some(module) = modules.get(name) {
            return module.clone();
        }

        let module = self.device.create_shader_module(ShaderModuleDescriptor {
            label: Some(name),
            source: ShaderSource::Wgsl(source.into()),
        });

        let module = Arc::new(module);
        modules.insert(name.to_string(), module.clone());
        module
    }

    /// Get or create a compute pipeline
    pub fn get_or_create_pipeline(
        &self,
        shader_name: &'static str,
        entry_point: &'static str,
        module: &ShaderModule,
        layout: &BindGroupLayout,
    ) -> Arc<ComputePipeline> {
        let key = (shader_name, entry_point);
        let mut pipelines = self.pipelines.lock();

        if let Some(pipeline) = pipelines.get(&key) {
            return pipeline.clone();
        }

        let pipeline_layout = self
            .device
            .create_pipeline_layout(&PipelineLayoutDescriptor {
                label: Some(&format!("{}_layout", shader_name)),
                bind_group_layouts: &[Some(layout)],
                immediate_size: 0, // Not using push constants
            });

        let pipeline = self
            .device
            .create_compute_pipeline(&ComputePipelineDescriptor {
                label: Some(&format!("{}_{}", shader_name, entry_point)),
                layout: Some(&pipeline_layout),
                module,
                entry_point: Some(entry_point),
                compilation_options: Default::default(),
                cache: None,
            });

        let pipeline = Arc::new(pipeline);
        pipelines.insert(key, pipeline.clone());
        pipeline
    }

    /// Get or create a compute pipeline from dynamically named shader
    ///
    /// This variant accepts owned strings for cases where shader/entry point names
    /// are generated at runtime (e.g., multi-dtype shader generation).
    pub fn get_or_create_dynamic_pipeline(
        &self,
        shader_name: &str,
        entry_point: &str,
        module: &ShaderModule,
        layout: &BindGroupLayout,
    ) -> Arc<ComputePipeline> {
        let key = (shader_name.to_string(), entry_point.to_string());
        let mut pipelines = self.dynamic_pipelines.lock();

        if let Some(pipeline) = pipelines.get(&key) {
            return pipeline.clone();
        }

        let pipeline_layout = self
            .device
            .create_pipeline_layout(&PipelineLayoutDescriptor {
                label: Some(&format!("{}_layout", shader_name)),
                bind_group_layouts: &[Some(layout)],
                immediate_size: 0,
            });

        let pipeline = self
            .device
            .create_compute_pipeline(&ComputePipelineDescriptor {
                label: Some(&format!("{}_{}", shader_name, entry_point)),
                layout: Some(&pipeline_layout),
                module,
                entry_point: Some(entry_point),
                compilation_options: Default::default(),
                cache: None,
            });

        let pipeline = Arc::new(pipeline);
        pipelines.insert(key, pipeline.clone());
        pipeline
    }

    /// Get or create a bind group layout for storage buffers
    pub fn get_or_create_layout(&self, key: LayoutKey) -> Arc<BindGroupLayout> {
        let mut layouts = self.layouts.lock();

        if let Some(layout) = layouts.get(&key) {
            return layout.clone();
        }

        let mut entries = Vec::new();

        // Storage buffers: first num_readonly_storage are read-only, rest are read-write
        for i in 0..key.num_storage_buffers {
            let read_only = i < key.num_readonly_storage;
            entries.push(BindGroupLayoutEntry {
                binding: i,
                visibility: ShaderStages::COMPUTE,
                ty: BindingType::Buffer {
                    ty: BufferBindingType::Storage { read_only },
                    has_dynamic_offset: false,
                    min_binding_size: None,
                },
                count: None,
            });
        }

        // Uniform buffers (read-only params)
        for i in 0..key.num_uniform_buffers {
            entries.push(BindGroupLayoutEntry {
                binding: key.num_storage_buffers + i,
                visibility: ShaderStages::COMPUTE,
                ty: BindingType::Buffer {
                    ty: BufferBindingType::Uniform,
                    has_dynamic_offset: false,
                    min_binding_size: None,
                },
                count: None,
            });
        }

        let layout = self
            .device
            .create_bind_group_layout(&BindGroupLayoutDescriptor {
                label: Some("linalg_layout"),
                entries: &entries,
            });

        let layout = Arc::new(layout);
        layouts.insert(key, layout.clone());
        layout
    }

    /// Create a bind group from buffers
    ///
    /// # Errors
    ///
    /// `BackendLimitation` when a buffer exceeds the device's binding size limit.
    pub fn create_bind_group(
        &self,
        layout: &BindGroupLayout,
        buffers: &[&Buffer],
    ) -> Result<BindGroup> {
        let limits = self.device.limits();
        for (i, buffer) in buffers.iter().enumerate() {
            check_binding_size(
                &limits,
                BIND_GROUP_OP,
                i as u32,
                buffer.usage(),
                buffer.size(),
            )?;
        }
        let entries: Vec<BindGroupEntry> = buffers
            .iter()
            .enumerate()
            .map(|(i, buffer)| BindGroupEntry {
                binding: i as u32,
                resource: buffer.as_entire_binding(),
            })
            .collect();

        Ok(self.device.create_bind_group(&BindGroupDescriptor {
            label: Some("compute_bind_group"),
            layout,
            entries: &entries,
        }))
    }

    /// Create a bind group from buffer windows, one per binding in order.
    ///
    /// # Errors
    ///
    /// `BackendLimitation` when a window exceeds the device's binding size limit.
    pub fn create_bind_group_from_bindings(
        &self,
        layout: &BindGroupLayout,
        bindings: &[BufferBinding<'_>],
    ) -> Result<BindGroup> {
        let limits = self.device.limits();
        for (i, binding) in bindings.iter().enumerate() {
            check_binding_size(
                &limits,
                BIND_GROUP_OP,
                i as u32,
                binding.buffer.usage(),
                binding_range_size(binding),
            )?;
        }
        let entries: Vec<BindGroupEntry> = bindings
            .iter()
            .enumerate()
            .map(|(i, binding)| BindGroupEntry {
                binding: i as u32,
                resource: BindingResource::Buffer(binding.clone()),
            })
            .collect();

        Ok(self.device.create_bind_group(&BindGroupDescriptor {
            label: Some("windowed_compute_bind_group"),
            layout,
            entries: &entries,
        }))
    }

    /// Get or create a storage-buffer layout followed by one dynamic uniform.
    pub fn get_or_create_dynamic_uniform_layout(
        &self,
        num_storage_buffers: u32,
        num_readonly_storage: u32,
    ) -> Arc<BindGroupLayout> {
        let key = (num_storage_buffers, num_readonly_storage);
        let mut layouts = self.dynamic_uniform_layouts.lock();
        if let Some(layout) = layouts.get(&key) {
            return layout.clone();
        }

        let mut entries = Vec::with_capacity(num_storage_buffers as usize + 1);
        for binding in 0..num_storage_buffers {
            entries.push(BindGroupLayoutEntry {
                binding,
                visibility: ShaderStages::COMPUTE,
                ty: BindingType::Buffer {
                    ty: BufferBindingType::Storage {
                        read_only: binding < num_readonly_storage,
                    },
                    has_dynamic_offset: false,
                    min_binding_size: None,
                },
                count: None,
            });
        }
        entries.push(BindGroupLayoutEntry {
            binding: num_storage_buffers,
            visibility: ShaderStages::COMPUTE,
            ty: BindingType::Buffer {
                ty: BufferBindingType::Uniform,
                has_dynamic_offset: true,
                min_binding_size: None,
            },
            count: None,
        });

        let layout = Arc::new(
            self.device
                .create_bind_group_layout(&BindGroupLayoutDescriptor {
                    label: Some("dynamic_uniform_compute_layout"),
                    entries: &entries,
                }),
        );
        layouts.insert(key, layout.clone());
        layout
    }

    /// Create a bind group whose final binding is a dynamically offset uniform.
    pub fn create_bind_group_with_dynamic_uniform(
        &self,
        layout: &BindGroupLayout,
        storage_buffers: &[&Buffer],
        uniform: &Buffer,
        uniform_binding_size: u64,
    ) -> Result<BindGroup> {
        let limits = self.device.limits();
        for (i, buffer) in storage_buffers.iter().enumerate() {
            check_binding_size(
                &limits,
                BIND_GROUP_OP,
                i as u32,
                buffer.usage(),
                buffer.size(),
            )?;
        }
        check_binding_size(
            &limits,
            BIND_GROUP_OP,
            storage_buffers.len() as u32,
            BufferUsages::UNIFORM,
            uniform_binding_size,
        )?;
        let mut entries: Vec<BindGroupEntry<'_>> = storage_buffers
            .iter()
            .enumerate()
            .map(|(binding, buffer)| BindGroupEntry {
                binding: binding as u32,
                resource: buffer.as_entire_binding(),
            })
            .collect();
        entries.push(BindGroupEntry {
            binding: storage_buffers.len() as u32,
            resource: BindingResource::Buffer(BufferBinding {
                buffer: uniform,
                offset: 0,
                size: NonZeroU64::new(uniform_binding_size),
            }),
        });

        Ok(self.device.create_bind_group(&BindGroupDescriptor {
            label: Some("dynamic_uniform_compute_bind_group"),
            layout,
            entries: &entries,
        }))
    }

    /// Get device reference
    pub fn device(&self) -> &Device {
        &self.device
    }
}

// ============================================================================
// Dispatch Helpers
// ============================================================================

/// Compute number of workgroups for n elements
#[inline]
pub fn workgroup_count(n: usize) -> u32 {
    ((n as u32) + WORKGROUP_SIZE - 1) / WORKGROUP_SIZE
}

/// Map DType to WGSL entry point suffix
#[allow(dead_code)]
pub fn dtype_suffix(dtype: DType) -> Result<&'static str> {
    match dtype {
        DType::F32 => Ok("f32"),
        DType::F64 => Err(Error::UnsupportedDType {
            dtype,
            op: "WGSL (f64 not supported in WebGPU)",
        }),
        _ => Err(Error::UnsupportedDType {
            dtype,
            op: "linalg",
        }),
    }
}

/// Get entry point name for operation and dtype
#[allow(dead_code)]
pub fn entry_point(op: &str, dtype: DType) -> Result<String> {
    let suffix = dtype_suffix(dtype)?;
    Ok(format!("{}_{}", op, suffix))
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn test_oversized_storage_binding_returns_backend_limitation() {
        let limits = wgpu::Limits::default();
        let size = limits.max_storage_buffer_binding_size + 4;
        let err =
            check_binding_size(&limits, BIND_GROUP_OP, 2, BufferUsages::STORAGE, size).unwrap_err();
        match err {
            Error::BackendLimitation {
                backend,
                operation,
                reason,
            } => {
                assert_eq!(backend, "wgpu");
                assert_eq!(operation, BIND_GROUP_OP);
                assert!(reason.contains("storage binding 2"));
                assert!(reason.contains("too large for one binding"));
            }
            other => panic!("expected BackendLimitation, got {other:?}"),
        }
    }

    #[test]
    fn test_oversized_uniform_binding_uses_uniform_limit() {
        let limits = wgpu::Limits::default();
        let size = limits.max_uniform_buffer_binding_size + 4;
        let usage = BufferUsages::UNIFORM | BufferUsages::COPY_DST;
        assert!(matches!(
            check_binding_size(&limits, BIND_GROUP_OP, 0, usage, size),
            Err(Error::BackendLimitation { .. })
        ));
        // The same size is fine as a storage binding.
        assert!(check_binding_size(&limits, BIND_GROUP_OP, 0, BufferUsages::STORAGE, size).is_ok());
    }

    #[test]
    fn test_binding_within_limit_is_accepted() {
        let limits = wgpu::Limits::default();
        let size = limits.max_storage_buffer_binding_size;
        assert!(check_binding_size(&limits, BIND_GROUP_OP, 0, BufferUsages::STORAGE, size).is_ok());
    }
}