numr 0.13.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
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
516
517
518
519
520
//! CUDA runtime implementation

use super::allocator::CudaAllocator;
use super::cache::{
    get_or_create_client, is_cuda_context_valid, log_cuda_memory_error, try_get_cached_client,
    try_get_cached_stream,
};
use super::client::CudaClient;
use super::device::CudaDevice;
use super::kernels;
use crate::runtime::Runtime;
use crate::runtime::common::Allocator;

/// CUDA Runtime adapter
///
/// Implements the generic Runtime trait for CUDA backend.
/// Uses cudarc for direct GPU control.
#[derive(Clone, Debug, Default)]
pub struct CudaRuntime;

impl Runtime for CudaRuntime {
    type Device = CudaDevice;
    type Client = CudaClient;
    type Allocator = CudaAllocator;
    type Graph = super::CudaGraph;
    type RawHandle = super::CudaRawHandle;
    type DType = crate::dtype::DType;

    fn name() -> &'static str {
        "cuda"
    }

    fn supports_graph_capture() -> bool {
        true // CUDA supports graph capture
    }

    fn capture_graph_into<F>(
        client: &Self::Client,
        inputs: &[&crate::tensor::Tensor<Self>],
        outputs: &[&crate::tensor::Tensor<Self>],
        f: F,
    ) -> crate::error::Result<crate::runtime::CapturedGraph<Self>>
    where
        F: FnOnce(&Self::Client) -> crate::error::Result<()>,
    {
        super::capture::entry::capture_graph_into(client, inputs, outputs, f)
    }

    /// Allocate GPU memory.
    ///
    /// Routes through the client's caching allocator (free-list pool) to avoid
    /// cuMemAllocAsync driver round-trips for repeated same-size allocations.
    fn allocate(size_bytes: usize, device: &Self::Device) -> crate::error::Result<u64> {
        if size_bytes == 0 {
            return Ok(0);
        }

        let client = get_or_create_client(device);
        client.allocator.allocate(size_bytes)
    }

    /// Deallocate GPU memory.
    ///
    /// Routes through the client's caching allocator — buffers are returned to
    /// the free-list for reuse instead of calling cuMemFreeAsync.
    fn deallocate(ptr: u64, size_bytes: usize, device: &Self::Device) {
        if ptr == 0 {
            return;
        }

        // Try to use the client's caching allocator (returns to free-list)
        if let Some(client) = try_get_cached_client(device.index) {
            client.allocator.deallocate(ptr, size_bytes);
            return;
        }

        // Client not available (shutdown) — free directly
        unsafe {
            if !is_cuda_context_valid() {
                return;
            }

            let result = if let Some(stream) = try_get_cached_stream(device.index) {
                cudarc::driver::sys::cuMemFreeAsync(ptr, stream)
            } else {
                cudarc::driver::sys::cuMemFree_v2(ptr)
            };

            if result != cudarc::driver::sys::CUresult::CUDA_SUCCESS
                && result != cudarc::driver::sys::CUresult::CUDA_ERROR_ILLEGAL_ADDRESS
            {
                log_cuda_memory_error("cuMemFree", ptr, result);
            }
        }
    }

    /// Copy data from host to device.
    ///
    /// Returns an error if the CUDA copy operation fails.
    fn copy_to_device(src: &[u8], dst: u64, device: &Self::Device) -> crate::error::Result<()> {
        if src.is_empty() || dst == 0 {
            return Ok(());
        }

        let client = get_or_create_client(device);
        // The copy is an enqueue on the shared compute stream: hold the
        // device's capture lock for it so it cannot land in another thread's
        // graph.
        let _permit = client.stream.enqueue_permit()?;

        unsafe {
            let result = cudarc::driver::sys::cuMemcpyHtoDAsync_v2(
                dst,
                src.as_ptr() as *const std::ffi::c_void,
                src.len(),
                client.stream.raw().cu_stream(),
            );

            if result != cudarc::driver::sys::CUresult::CUDA_SUCCESS {
                return Err(crate::error::Error::Backend(format!(
                    "CUDA host-to-device copy failed: {} bytes ({:?})",
                    src.len(),
                    result
                )));
            }

            // No explicit sync needed: with pageable (non-pinned) host memory,
            // cuMemcpyHtoDAsync is synchronous w.r.t. the host buffer — the call
            // returns only after the copy is complete. An explicit stream.synchronize()
            // here would also drain ALL pending GPU work, destroying pipeline throughput.
        }
        Ok(())
    }

    /// Copy data from device to host.
    ///
    /// Returns an error if the CUDA copy operation fails.
    fn copy_from_device(
        src: u64,
        dst: &mut [u8],
        device: &Self::Device,
    ) -> crate::error::Result<()> {
        if dst.is_empty() || src == 0 {
            return Ok(());
        }

        let client = get_or_create_client(device);
        // The copy and the synchronization both touch the shared compute
        // stream; one permit covers them so no capture opens between them.
        let _permit = client.stream.enqueue_permit()?;

        unsafe {
            let result = cudarc::driver::sys::cuMemcpyDtoHAsync_v2(
                dst.as_mut_ptr() as *mut std::ffi::c_void,
                src,
                dst.len(),
                client.stream.raw().cu_stream(),
            );

            if result != cudarc::driver::sys::CUresult::CUDA_SUCCESS {
                return Err(crate::error::Error::Backend(format!(
                    "[numr::cuda] Device-to-host copy failed: {} bytes ({:?})",
                    dst.len(),
                    result
                )));
            }

            // With pageable host memory, cuMemcpyDtoHAsync blocks the host until
            // the copy completes. However, we still need to synchronize the stream
            // to ensure all prior GPU kernels have finished producing the data.
            //
            // A capturing thread must not synchronize: that would invalidate
            // its own capture. Reading a device value back is not recordable
            // work in any case, so the copy stands alone there.
            //
            // The permit taken above already covers this wait, so it goes
            // through the bare stream: `GuardedStream::synchronize` would
            // take a second read side on this thread.
            if !client.is_capturing() {
                client.stream.raw().synchronize().map_err(|e| {
                    crate::error::Error::Backend(format!(
                        "[numr::cuda] Device-to-host copy of {} bytes: stream synchronize \
                         failed ({e:?}); the copied bytes are not valid",
                        dst.len()
                    ))
                })?;
            }
        }
        Ok(())
    }

    /// Record an event on the compute stream.
    fn record_compute_event(device: &Self::Device) -> crate::error::Result<u64> {
        let client = get_or_create_client(device);
        // Recording an event enqueues on the shared compute stream.
        let _permit = client.stream.enqueue_permit()?;
        client
            .record_event_on_compute()
            .map_err(|e| crate::error::Error::Backend(format!("Event record failed: {}", e)))
    }

    /// Pipelined D2H copy: copy stream waits on the provided event, copies,
    /// and syncs only the copy stream. Compute stream continues concurrently.
    fn copy_from_device_pipelined(
        src: u64,
        dst: &mut [u8],
        device: &Self::Device,
        event: u64,
    ) -> crate::error::Result<()> {
        if dst.is_empty() || src == 0 {
            return Ok(());
        }

        let client = get_or_create_client(device);
        // The event being waited on was recorded on the shared compute
        // stream; hold the capture lock while the copy stream is tied to it.
        let _permit = client.stream.enqueue_permit().inspect_err(|_| {
            client.destroy_event(event);
        })?;

        unsafe {
            // 1. Copy stream waits for event (waits for argmax to finish)
            client.copy_stream_wait_event(event).map_err(|e| {
                client.destroy_event(event);
                crate::error::Error::Backend(format!("Stream wait event failed: {}", e))
            })?;

            // 2. Launch D2H copy on copy stream
            let result = cudarc::driver::sys::cuMemcpyDtoHAsync_v2(
                dst.as_mut_ptr() as *mut std::ffi::c_void,
                src,
                dst.len(),
                client.copy_stream.cu_stream(),
            );

            if result != cudarc::driver::sys::CUresult::CUDA_SUCCESS {
                client.destroy_event(event);
                return Err(crate::error::Error::Backend(format!(
                    "[numr::cuda] Pipelined D2H copy failed: {} bytes ({:?})",
                    dst.len(),
                    result
                )));
            }

            // 3. Sync ONLY the copy stream (compute stream keeps running)
            let synced = client.copy_stream.synchronize();

            client.destroy_event(event);
            synced.map_err(|e| {
                crate::error::Error::Backend(format!(
                    "[numr::cuda] Pipelined D2H copy of {} bytes: copy stream synchronize \
                     failed ({e:?}); the copied bytes are not valid",
                    dst.len()
                ))
            })?;
        }
        Ok(())
    }

    /// Copy data within device memory.
    ///
    /// Returns an error if the CUDA copy operation fails.
    fn copy_within_device(
        src: u64,
        dst: u64,
        size_bytes: usize,
        device: &Self::Device,
    ) -> crate::error::Result<()> {
        if size_bytes == 0 || src == 0 || dst == 0 {
            return Ok(());
        }

        let client = get_or_create_client(device);
        // Enqueue on the shared compute stream. Consumers call this from
        // inside capture closures, where the permit is a no-op because the
        // capturing thread already owns the device.
        let _permit = client.stream.enqueue_permit()?;

        unsafe {
            let result = cudarc::driver::sys::cuMemcpyDtoDAsync_v2(
                dst,
                src,
                size_bytes,
                client.stream.raw().cu_stream(),
            );

            if result != cudarc::driver::sys::CUresult::CUDA_SUCCESS {
                return Err(crate::error::Error::Backend(format!(
                    "[numr::cuda] Device-to-device copy failed: {} bytes ({:?})",
                    size_bytes, result
                )));
            }
        }
        Ok(())
    }

    fn copy_strided(
        src_handle: u64,
        src_byte_offset: usize,
        dst_handle: u64,
        shape: &[usize],
        strides: &[isize],
        elem_size: usize,
        device: &Self::Device,
    ) -> crate::error::Result<()> {
        if src_handle == 0 || dst_handle == 0 || shape.is_empty() {
            return Ok(());
        }

        let numel: usize = shape.iter().product();
        if numel == 0 {
            return Ok(());
        }

        let ndim = shape.len();
        let client = get_or_create_client(device);

        // The only enqueue here is the kernel launch, which takes the device's
        // capture lock itself. Taking a permit here as well would hold the
        // read side twice on one thread.
        //
        // Shape and strides are passed as kernel arguments (by value), not device
        // memory pointers.  This is critical for CUDA graph capture compatibility:
        // H2D copies of temporary host data create graph memcpy nodes that re-read
        // from stale host addresses on replay, causing CUDA_ERROR_ILLEGAL_ADDRESS.
        unsafe {
            let kernel_result = kernels::launch_strided_copy(
                &client.context,
                &client.stream,
                device.index,
                src_handle,
                dst_handle,
                shape,
                strides,
                numel,
                ndim,
                elem_size,
                src_byte_offset,
            );

            if let Err(e) = kernel_result {
                return Err(crate::error::Error::Backend(format!(
                    "[numr::cuda] Strided copy kernel failed: {} bytes ({} elements × {} bytes/elem) from {} to {} on device {}: {:?}",
                    numel * elem_size,
                    numel,
                    elem_size,
                    src_handle,
                    dst_handle,
                    device.index,
                    e
                )));
            }
        }
        Ok(())
    }

    fn default_device() -> Self::Device {
        CudaDevice::new(0)
    }

    fn default_client(device: &Self::Device) -> Self::Client {
        get_or_create_client(device)
    }

    fn raw_handle(client: &Self::Client) -> &Self::RawHandle {
        &client.raw_handle
    }
}

// ============================================================================
// Arena-enabled graph capture
// ============================================================================

impl CudaRuntime {
    /// Capture a CUDA graph with a dedicated bump-pointer arena for all
    /// graph-internal intermediate allocations.
    ///
    /// # Why this exists
    ///
    /// During normal graph capture (`capture_graph_into`), intermediate tensors
    /// allocated inside the closure via `cuMemAllocAsync` produce graph-managed
    /// memory that is subject to `AUTO_FREE_ON_LAUNCH`.  On the **first** replay
    /// `cuGraphLaunch` frees those addresses; on the **second** replay the
    /// graph's kernel nodes dereference the now-freed addresses and the driver
    /// raises `CUDA_ERROR_ILLEGAL_ADDRESS`.
    ///
    /// This variant pre-allocates an `arena_bytes`-sized device buffer
    /// **outside** the capture region and redirects every frozen `allocate()`
    /// call into a bump-pointer offset inside that buffer.  Because the buffer
    /// was not allocated during capture, it is NOT subject to
    /// `AUTO_FREE_ON_LAUNCH`; its address is stable across all replays for the
    /// lifetime of the returned `CapturedGraph`.
    ///
    /// # Arguments
    ///
    /// * `client` — the CUDA client to capture on.
    /// * `inputs` / `outputs` — tensors whose device addresses are passed to
    ///   the closure and encoded in the graph (same semantics as
    ///   `capture_graph_into`).
    /// * `arena_bytes` — size in bytes of the pre-allocated scratch arena.
    ///   Must be large enough to hold all intermediate tensors created inside
    ///   `f`.  When the arena is exhausted the closure fails with a `Backend`
    ///   error naming the requested bytes, the bytes used and `arena_bytes`;
    ///   the graph is not produced in that case.
    ///
    /// The returned graph reports the peak arena footprint through
    /// [`CapturedGraph::arena_bytes_used`](crate::runtime::CapturedGraph::arena_bytes_used),
    /// so a caller can recapture with a tighter arena.
    /// * `f` — the closure to capture.  Same contract as `capture_graph_into`.
    ///
    /// # Errors
    ///
    /// Returns an error if:
    /// - The arena device allocation fails (device OOM).
    /// - The closure returns an error (including arena OOM for intermediates).
    /// - The CUDA stream capture API fails.
    ///
    /// # Drop ordering
    ///
    /// The returned `CapturedGraph` holds the arena tensor in its `arena` field,
    /// which drops AFTER `graph`, `inputs`, and `outputs` (declaration order).
    /// This guarantees the arena buffer outlives the compiled graph handle.
    pub fn capture_graph_into_with_arena<F>(
        client: &CudaClient,
        inputs: &[&crate::tensor::Tensor<CudaRuntime>],
        outputs: &[&crate::tensor::Tensor<CudaRuntime>],
        arena_bytes: usize,
        f: F,
    ) -> crate::error::Result<crate::runtime::CapturedGraph<CudaRuntime>>
    where
        F: FnOnce(&CudaClient) -> crate::error::Result<()>,
    {
        super::capture::entry::capture_graph_into_with_arena(
            client,
            inputs,
            outputs,
            arena_bytes,
            f,
        )
    }
}

/// Get the default CUDA device (device 0)
pub fn cuda_device() -> CudaDevice {
    CudaDevice::new(0)
}

/// Get a specific CUDA device by ID
pub fn cuda_device_id(device_id: usize) -> CudaDevice {
    CudaDevice::new(device_id)
}

/// Check if CUDA is available on this system
pub fn is_cuda_available() -> bool {
    std::panic::catch_unwind(|| {
        let device = CudaDevice::new(0);
        let _client = get_or_create_client(&device);
    })
    .is_ok()
}

#[cfg(test)]
mod tests {
    use crate::dtype::DType;
    use crate::ops::BinaryOps;
    use crate::runtime::Runtime;
    use crate::runtime::cuda::{CudaDevice, CudaRuntime};
    use crate::runtime::traits::client::RuntimeClient;
    use crate::tensor::Tensor;

    /// Full `capture_graph_into` integration test using the destination-passing
    /// `add_into` primitive.
    ///
    /// Captures `c = a + b` into a graph where `a`, `b`, `c` are all allocated
    /// OUTSIDE the closure (so their device addresses are stable and not subject
    /// to `AUTO_FREE_ON_LAUNCH`), then verifies the captured graph replays
    /// correctly after the inputs are overwritten in place.
    #[ignore = "requires a live CUDA GPU"]
    #[test]
    fn test_capture_graph_into_add() {
        let device = CudaDevice::new(0);
        let client = CudaRuntime::default_client(&device);

        // Inputs and output allocated OUTSIDE the closure.
        let a = Tensor::<CudaRuntime>::from_slice(&[1.0f32, 2.0, 3.0, 4.0], &[4], &device).unwrap();
        let b =
            Tensor::<CudaRuntime>::from_slice(&[10.0f32, 20.0, 30.0, 40.0], &[4], &device).unwrap();
        let c = Tensor::<CudaRuntime>::zeros(&[4], DType::F32, &device).unwrap();

        // Capture: c = a + b (destination-passing, no allocation inside).
        let captured = CudaRuntime::capture_graph_into(&client, &[&a, &b], &[&c], |cc| {
            cc.add_into(&c, &a, &b)
        })
        .expect("capture_graph_into failed");

        // First replay.
        captured.launch().expect("launch failed");
        client.synchronize();
        assert_eq!(c.to_vec::<f32>(), vec![11.0, 22.0, 33.0, 44.0]);

        // Overwrite `a` in place (stable address) and replay again — the graph
        // must pick up the new input values since it reads from the same buffer.
        CudaRuntime::copy_to_device(
            bytemuck::cast_slice(&[5.0f32, 6.0, 7.0, 8.0]),
            a.ptr(),
            &device,
        )
        .expect("H2D copy failed");
        captured.launch().expect("relaunch failed");
        client.synchronize();
        assert_eq!(c.to_vec::<f32>(), vec![15.0, 26.0, 37.0, 48.0]);

        // Drop the captured graph and confirm a subsequent normal allocation
        // does not hit CUDA_ERROR_ILLEGAL_ADDRESS (clean teardown).
        drop(captured);
        let fresh = Tensor::<CudaRuntime>::zeros(&[4], DType::F32, &device).unwrap();
        client.synchronize();
        assert_eq!(fresh.to_vec::<f32>(), vec![0.0, 0.0, 0.0, 0.0]);
    }
}