scirs2-core 0.4.2

Core utilities and common functionality for SciRS2 (scirs2-core)
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
//! CPU-side GPU buffer abstraction for scirs2-core.
//!
//! Provides a clean API layer that simulates GPU buffer operations in pure-Rust
//! CPU-only environments. Can be backed by actual GPU later.

use std::sync::{Arc, Mutex};

use crate::error::{CoreError, CoreResult};

// ─────────────────────────────────────────────────────────────────────────────
// Device / DType
// ─────────────────────────────────────────────────────────────────────────────

/// Device type for buffer placement.
#[non_exhaustive]
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum DeviceType {
    /// CPU (host) memory.
    Cpu,
    /// GPU device.  In pure-Rust builds this is simulated on the CPU.
    Gpu {
        /// Zero-based GPU device index.
        device_id: u32,
    },
    /// WebGPU device.
    WebGpu,
}

impl Default for DeviceType {
    fn default() -> Self {
        DeviceType::Cpu
    }
}

/// Scalar data type stored in a [`GpuBuffer`].
#[non_exhaustive]
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum DType {
    /// 32-bit float.
    F32,
    /// 64-bit float.
    F64,
    /// 32-bit signed integer.
    I32,
    /// 64-bit signed integer.
    I64,
    /// Unsigned byte.
    U8,
}

impl DType {
    /// Size in bytes of a single element.
    pub fn bytes(&self) -> usize {
        match self {
            DType::F32 => 4,
            DType::F64 => 8,
            DType::I32 => 4,
            DType::I64 => 8,
            DType::U8 => 1,
        }
    }
}

// ─────────────────────────────────────────────────────────────────────────────
// GpuBuffer
// ─────────────────────────────────────────────────────────────────────────────

/// GPU buffer abstraction.
///
/// In pure-Rust builds the backing store is a heap-allocated `Vec<u8>`.
/// The API is intentionally designed so a real GPU backend can replace the
/// inner storage without touching user code.
#[derive(Clone)]
pub struct GpuBuffer {
    data: Arc<Mutex<Vec<u8>>>,
    shape: Vec<usize>,
    dtype: DType,
    device: DeviceType,
    label: Option<String>,
}

impl std::fmt::Debug for GpuBuffer {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.debug_struct("GpuBuffer")
            .field("shape", &self.shape)
            .field("dtype", &self.dtype)
            .field("device", &self.device)
            .field("label", &self.label)
            .finish()
    }
}

impl GpuBuffer {
    // ── constructors ──────────────────────────────────────────────────────

    /// Allocate a zero-filled buffer.
    pub fn zeros(shape: &[usize], dtype: DType, device: DeviceType) -> Self {
        let n = shape.iter().product::<usize>() * dtype.bytes();
        GpuBuffer {
            data: Arc::new(Mutex::new(vec![0u8; n])),
            shape: shape.to_vec(),
            dtype,
            device,
            label: None,
        }
    }

    /// Create a buffer from a `Vec<f32>`.
    ///
    /// The shape is inferred as `[data.len()]`.
    pub fn from_vec_f32(data: Vec<f32>, shape: &[usize]) -> Self {
        let raw: Vec<u8> = data.iter().flat_map(|v| v.to_ne_bytes()).collect();
        GpuBuffer {
            data: Arc::new(Mutex::new(raw)),
            shape: shape.to_vec(),
            dtype: DType::F32,
            device: DeviceType::Cpu,
            label: None,
        }
    }

    /// Create a buffer from a `Vec<f64>`.
    ///
    /// The shape is inferred as `[data.len()]`.
    pub fn from_vec_f64(data: Vec<f64>, shape: &[usize]) -> Self {
        let raw: Vec<u8> = data.iter().flat_map(|v| v.to_ne_bytes()).collect();
        GpuBuffer {
            data: Arc::new(Mutex::new(raw)),
            shape: shape.to_vec(),
            dtype: DType::F64,
            device: DeviceType::Cpu,
            label: None,
        }
    }

    // ── metadata ──────────────────────────────────────────────────────────

    /// Logical shape of the buffer.
    pub fn shape(&self) -> &[usize] {
        &self.shape
    }

    /// Element data type.
    pub fn dtype(&self) -> DType {
        self.dtype
    }

    /// Device this buffer lives on.
    pub fn device(&self) -> DeviceType {
        self.device
    }

    /// Total number of scalar elements.
    pub fn n_elements(&self) -> usize {
        self.shape.iter().product()
    }

    /// Total number of bytes.
    pub fn n_bytes(&self) -> usize {
        self.n_elements() * self.dtype.bytes()
    }

    /// Attach a human-readable label (builder style).
    pub fn with_label(mut self, label: &str) -> Self {
        self.label = Some(label.to_owned());
        self
    }

    /// Return the label if set.
    pub fn label(&self) -> Option<&str> {
        self.label.as_deref()
    }

    // ── host → device upload ──────────────────────────────────────────────

    /// Copy `f32` data from a host slice into the buffer.
    pub fn upload_f32(&self, src: &[f32]) -> CoreResult<()> {
        if self.dtype != DType::F32 {
            return Err(CoreError::InvalidArgument(
                crate::error::ErrorContext::new("upload_f32: buffer dtype is not F32"),
            ));
        }
        if src.len() != self.n_elements() {
            return Err(CoreError::ShapeError(crate::error::ErrorContext::new(
                format!(
                    "upload_f32: src len {} != buffer elements {}",
                    src.len(),
                    self.n_elements()
                ),
            )));
        }
        let raw: Vec<u8> = src.iter().flat_map(|v| v.to_ne_bytes()).collect();
        let mut guard = self
            .data
            .lock()
            .map_err(|_| CoreError::ComputationError(crate::error::ErrorContext::new("mutex poisoned")))?;
        *guard = raw;
        Ok(())
    }

    /// Copy `f64` data from a host slice into the buffer.
    pub fn upload_f64(&self, src: &[f64]) -> CoreResult<()> {
        if self.dtype != DType::F64 {
            return Err(CoreError::InvalidArgument(
                crate::error::ErrorContext::new("upload_f64: buffer dtype is not F64"),
            ));
        }
        if src.len() != self.n_elements() {
            return Err(CoreError::ShapeError(crate::error::ErrorContext::new(
                format!(
                    "upload_f64: src len {} != buffer elements {}",
                    src.len(),
                    self.n_elements()
                ),
            )));
        }
        let raw: Vec<u8> = src.iter().flat_map(|v| v.to_ne_bytes()).collect();
        let mut guard = self
            .data
            .lock()
            .map_err(|_| CoreError::ComputationError(crate::error::ErrorContext::new("mutex poisoned")))?;
        *guard = raw;
        Ok(())
    }

    // ── device → host download ────────────────────────────────────────────

    /// Download the buffer as `Vec<f32>`.
    pub fn to_vec_f32(&self) -> CoreResult<Vec<f32>> {
        if self.dtype != DType::F32 {
            return Err(CoreError::InvalidArgument(
                crate::error::ErrorContext::new("to_vec_f32: buffer dtype is not F32"),
            ));
        }
        let guard = self
            .data
            .lock()
            .map_err(|_| CoreError::ComputationError(crate::error::ErrorContext::new("mutex poisoned")))?;
        let out: Vec<f32> = guard
            .chunks_exact(4)
            .map(|c| f32::from_ne_bytes([c[0], c[1], c[2], c[3]]))
            .collect();
        Ok(out)
    }

    /// Download the buffer as `Vec<f64>`.
    pub fn to_vec_f64(&self) -> CoreResult<Vec<f64>> {
        if self.dtype != DType::F64 {
            return Err(CoreError::InvalidArgument(
                crate::error::ErrorContext::new("to_vec_f64: buffer dtype is not F64"),
            ));
        }
        let guard = self
            .data
            .lock()
            .map_err(|_| CoreError::ComputationError(crate::error::ErrorContext::new("mutex poisoned")))?;
        let out: Vec<f64> = guard
            .chunks_exact(8)
            .map(|c| f64::from_ne_bytes([c[0], c[1], c[2], c[3], c[4], c[5], c[6], c[7]]))
            .collect();
        Ok(out)
    }

    // ── compute operations (CPU simulation) ───────────────────────────────

    /// Element-wise addition.  Returns a new buffer; both inputs are unchanged.
    pub fn add(&self, other: &GpuBuffer) -> CoreResult<GpuBuffer> {
        if self.dtype != other.dtype {
            return Err(CoreError::InvalidArgument(
                crate::error::ErrorContext::new("add: dtype mismatch"),
            ));
        }
        if self.shape != other.shape {
            return Err(CoreError::ShapeError(crate::error::ErrorContext::new(
                "add: shape mismatch",
            )));
        }
        match self.dtype {
            DType::F32 => {
                let a = self.to_vec_f32()?;
                let b = other.to_vec_f32()?;
                let c: Vec<f32> = a.iter().zip(b.iter()).map(|(x, y)| x + y).collect();
                Ok(GpuBuffer::from_vec_f32(c, &self.shape))
            }
            DType::F64 => {
                let a = self.to_vec_f64()?;
                let b = other.to_vec_f64()?;
                let c: Vec<f64> = a.iter().zip(b.iter()).map(|(x, y)| x + y).collect();
                Ok(GpuBuffer::from_vec_f64(c, &self.shape))
            }
            _ => Err(CoreError::InvalidArgument(
                crate::error::ErrorContext::new("add: unsupported dtype for element-wise add"),
            )),
        }
    }

    /// Scalar multiplication.  Returns a new buffer.
    pub fn scale(&self, scalar: f64) -> CoreResult<GpuBuffer> {
        match self.dtype {
            DType::F32 => {
                let v = self.to_vec_f32()?;
                let out: Vec<f32> = v.iter().map(|x| (*x as f64 * scalar) as f32).collect();
                Ok(GpuBuffer::from_vec_f32(out, &self.shape))
            }
            DType::F64 => {
                let v = self.to_vec_f64()?;
                let out: Vec<f64> = v.iter().map(|x| x * scalar).collect();
                Ok(GpuBuffer::from_vec_f64(out, &self.shape))
            }
            _ => Err(CoreError::InvalidArgument(
                crate::error::ErrorContext::new("scale: unsupported dtype"),
            )),
        }
    }
}

// ─────────────────────────────────────────────────────────────────────────────
// ComputeDispatch
// ─────────────────────────────────────────────────────────────────────────────

/// Compute shader dispatch descriptor.
///
/// In pure-Rust builds the "shader" is executed as a closure on the CPU.
pub struct ComputeDispatch {
    /// Work-group size in X, Y, Z.
    pub workgroup_size: [u32; 3],
    /// Number of work-groups in X, Y, Z.
    pub n_workgroups: [u32; 3],
}

impl ComputeDispatch {
    /// Create a dispatch sized to cover `total_threads` threads.
    ///
    /// `workgroup_size` specifies the per-axis group sizes; the number of
    /// work-groups is rounded up so that `n_workgroups * workgroup_size >=
    /// total_threads` along the X axis.  Y and Z are set to 1.
    pub fn new(total_threads: usize, workgroup_size: [u32; 3]) -> Self {
        let wx = workgroup_size[0].max(1) as usize;
        let nx = total_threads.div_ceil(wx) as u32;
        ComputeDispatch {
            workgroup_size,
            n_workgroups: [nx, 1, 1],
        }
    }

    /// Total number of threads launched.
    pub fn total_threads(&self) -> u64 {
        let ws: u64 = self.workgroup_size.iter().map(|&x| x as u64).product();
        let ng: u64 = self.n_workgroups.iter().map(|&x| x as u64).product();
        ws * ng
    }

    /// Execute a closure as if it were a compute shader.
    ///
    /// The closure receives the global thread ID `(x, y, z)`.  In this CPU
    /// simulation the closure is called sequentially for every global thread.
    pub fn execute<F>(&self, kernel: F) -> CoreResult<()>
    where
        F: Fn(u32, u32, u32) + Sync + Send,
    {
        let gx = self.workgroup_size[0] * self.n_workgroups[0];
        let gy = self.workgroup_size[1] * self.n_workgroups[1];
        let gz = self.workgroup_size[2] * self.n_workgroups[2];
        for z in 0..gz {
            for y in 0..gy {
                for x in 0..gx {
                    kernel(x, y, z);
                }
            }
        }
        Ok(())
    }
}

// ─────────────────────────────────────────────────────────────────────────────
// Tests
// ─────────────────────────────────────────────────────────────────────────────

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

    #[test]
    fn test_buffer_creation_zeros() {
        let buf = GpuBuffer::zeros(&[4, 4], DType::F32, DeviceType::Cpu);
        assert_eq!(buf.shape(), &[4, 4]);
        assert_eq!(buf.dtype(), DType::F32);
        assert_eq!(buf.device(), DeviceType::Cpu);
        assert_eq!(buf.n_elements(), 16);
        assert_eq!(buf.n_bytes(), 64);
    }

    #[test]
    fn test_shape_queries() {
        let buf = GpuBuffer::zeros(&[2, 3, 5], DType::F64, DeviceType::Gpu { device_id: 0 });
        assert_eq!(buf.n_elements(), 30);
        assert_eq!(buf.n_bytes(), 240);
        assert_eq!(buf.device(), DeviceType::Gpu { device_id: 0 });
    }

    #[test]
    fn test_upload_download_roundtrip_f32() {
        let buf = GpuBuffer::zeros(&[4], DType::F32, DeviceType::Cpu);
        let src = vec![1.0f32, 2.0, 3.0, 4.0];
        buf.upload_f32(&src).expect("upload_f32 failed");
        let dst = buf.to_vec_f32().expect("to_vec_f32 failed");
        assert_eq!(dst, src);
    }

    #[test]
    fn test_upload_download_roundtrip_f64() {
        let buf = GpuBuffer::zeros(&[3], DType::F64, DeviceType::Cpu);
        let src = vec![1.5f64, -2.5, 3.14159];
        buf.upload_f64(&src).expect("upload_f64 failed");
        let dst = buf.to_vec_f64().expect("to_vec_f64 failed");
        for (a, b) in dst.iter().zip(src.iter()) {
            assert!((a - b).abs() < 1e-12);
        }
    }

    #[test]
    fn test_add_operation() {
        let a = GpuBuffer::from_vec_f32(vec![1.0, 2.0, 3.0], &[3]);
        let b = GpuBuffer::from_vec_f32(vec![4.0, 5.0, 6.0], &[3]);
        let c = a.add(&b).expect("add failed");
        let result = c.to_vec_f32().expect("to_vec_f32 failed");
        assert_eq!(result, vec![5.0f32, 7.0, 9.0]);
    }

    #[test]
    fn test_scale_operation() {
        let buf = GpuBuffer::from_vec_f64(vec![1.0, 2.0, 3.0], &[3]);
        let scaled = buf.scale(2.5).expect("scale failed");
        let result = scaled.to_vec_f64().expect("to_vec_f64 failed");
        assert!((result[0] - 2.5).abs() < 1e-12);
        assert!((result[1] - 5.0).abs() < 1e-12);
        assert!((result[2] - 7.5).abs() < 1e-12);
    }

    #[test]
    fn test_label() {
        let buf = GpuBuffer::zeros(&[8], DType::F32, DeviceType::Cpu)
            .with_label("my_weights");
        assert_eq!(buf.label(), Some("my_weights"));
    }

    #[test]
    fn test_compute_dispatch() {
        use std::sync::{Arc, Mutex};
        let counter = Arc::new(Mutex::new(0u32));
        let counter_clone = Arc::clone(&counter);
        let dispatch = ComputeDispatch::new(16, [8, 1, 1]);
        dispatch
            .execute(move |_x, _y, _z| {
                let mut c = counter_clone.lock().expect("lock failed");
                *c += 1;
            })
            .expect("execute failed");
        let total = *counter.lock().expect("lock failed");
        // n_workgroups[0] = ceil(16/8)=2, so total threads = 2*8 = 16
        assert_eq!(total, 16);
    }

    #[test]
    fn test_from_vec_shape_and_content() {
        let data = vec![10.0f32, 20.0, 30.0, 40.0];
        let buf = GpuBuffer::from_vec_f32(data.clone(), &[2, 2]);
        assert_eq!(buf.shape(), &[2, 2]);
        let out = buf.to_vec_f32().expect("to_vec_f32 failed");
        assert_eq!(out, data);
    }
}