numr 0.15.1

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
//! `Communicator` for NCCL: collectives and point-to-point calls.
//!
//! Every call goes through raw `nccl::result` FFI, because numr picks the
//! `DType` at run time and cudarc's safe API needs it at compile time.

use std::ffi::c_void;

use cudarc::nccl::{result as nccl_result, sys as nccl_sys};

use super::comm::NcclCommunicator;
use super::convert::{dtype_to_nccl, reduce_op_to_nccl, to_nccl_int};
use crate::dtype::DType;
use crate::error::Result;
use crate::runtime::communicator::{Communicator, ReduceOp, StreamSyncOps};

impl Communicator for NcclCommunicator {
    fn world_size(&self) -> usize {
        self.world_size
    }

    fn rank(&self) -> usize {
        self.rank
    }

    unsafe fn all_reduce(&self, ptr: u64, count: usize, dtype: DType, op: ReduceOp) -> Result<()> {
        let nccl_dtype = dtype_to_nccl(dtype)?;
        let nccl_op = reduce_op_to_nccl(op);
        // In place: sendbuff == recvbuff.
        // SAFETY: the caller guarantees `ptr` holds `count` elements of `dtype`
        // on this rank's device. `comm` is live while `with_comm` holds the lock.
        self.with_comm("ncclAllReduce", |comm, stream| unsafe {
            nccl_result::all_reduce(
                ptr as *const c_void,
                ptr as *mut c_void,
                count,
                nccl_dtype,
                nccl_op,
                comm,
                stream,
            )
        })
    }

    unsafe fn broadcast(&self, ptr: u64, count: usize, dtype: DType, root: usize) -> Result<()> {
        let nccl_dtype = dtype_to_nccl(dtype)?;
        let root = to_nccl_int("root", root)?;
        // In place: sendbuff == recvbuff.
        // SAFETY: the caller guarantees `ptr` holds `count` elements of `dtype`
        // on this rank's device. `comm` is live while `with_comm` holds the lock.
        self.with_comm("ncclBroadcast", |comm, stream| unsafe {
            nccl_result::broadcast(
                ptr as *const c_void,
                ptr as *mut c_void,
                count,
                nccl_dtype,
                root,
                comm,
                stream,
            )
        })
    }

    unsafe fn all_gather(
        &self,
        send_ptr: u64,
        recv_ptr: u64,
        count: usize,
        dtype: DType,
    ) -> Result<()> {
        let nccl_dtype = dtype_to_nccl(dtype)?;
        // SAFETY: the caller guarantees `send_ptr` holds `count` elements and
        // `recv_ptr` holds `count * world_size` elements of `dtype`. `comm` is live
        // while `with_comm` holds the lock.
        self.with_comm("ncclAllGather", |comm, stream| unsafe {
            nccl_result::all_gather(
                send_ptr as *const c_void,
                recv_ptr as *mut c_void,
                count,
                nccl_dtype,
                comm,
                stream,
            )
        })
    }

    unsafe fn reduce_scatter(
        &self,
        send_ptr: u64,
        recv_ptr: u64,
        count: usize,
        dtype: DType,
        op: ReduceOp,
    ) -> Result<()> {
        let nccl_dtype = dtype_to_nccl(dtype)?;
        let nccl_op = reduce_op_to_nccl(op);
        // SAFETY: the caller guarantees `send_ptr` holds `count * world_size`
        // elements and `recv_ptr` holds `count` elements of `dtype`. `comm` is live
        // while `with_comm` holds the lock.
        self.with_comm("ncclReduceScatter", |comm, stream| unsafe {
            nccl_result::reduce_scatter(
                send_ptr as *const c_void,
                recv_ptr as *mut c_void,
                count,
                nccl_dtype,
                nccl_op,
                comm,
                stream,
            )
        })
    }

    unsafe fn send(
        &self,
        ptr: u64,
        count: usize,
        dtype: DType,
        dest: usize,
        _tag: u32,
    ) -> Result<()> {
        let nccl_dtype = dtype_to_nccl(dtype)?;
        let dest = to_nccl_int("dest", dest)?;
        // SAFETY: the caller guarantees `ptr` holds `count` elements of `dtype`.
        // `comm` is live while `with_comm` holds the lock.
        self.with_comm("ncclSend", |comm, stream| unsafe {
            nccl_result::send(ptr as *const c_void, count, nccl_dtype, dest, comm, stream)
        })
    }

    unsafe fn recv(
        &self,
        ptr: u64,
        count: usize,
        dtype: DType,
        src: usize,
        _tag: u32,
    ) -> Result<()> {
        let nccl_dtype = dtype_to_nccl(dtype)?;
        let src = to_nccl_int("src", src)?;
        // SAFETY: the caller guarantees `ptr` has room for `count` elements of
        // `dtype`. `comm` is live while `with_comm` holds the lock.
        self.with_comm("ncclRecv", |comm, stream| unsafe {
            nccl_result::recv(ptr as *mut c_void, count, nccl_dtype, src, comm, stream)
        })
    }

    /// Wait for queued work on the communicator stream.
    ///
    /// Polls NCCL for asynchronous errors while it waits. An error NCCL reports
    /// aborts the communicator and returns the error.
    /// [`NcclCommunicator::abort`] from another thread also ends the wait with an error.
    fn sync(&self) -> Result<()> {
        self.wait_stream()
    }

    fn as_stream_sync(&self) -> Option<&dyn StreamSyncOps> {
        Some(self)
    }

    fn barrier(&self) -> Result<()> {
        // NCCL has no barrier. A zero-element all-reduce between two syncs acts as one.
        self.sync()?;
        // SAFETY: a zero-element all-reduce reads and writes no memory.
        // `comm` is live while `with_comm` holds the lock.
        self.with_comm("ncclAllReduce (barrier)", |comm, stream| unsafe {
            nccl_result::all_reduce(
                std::ptr::null(),
                std::ptr::null_mut(),
                0,
                nccl_sys::ncclDataType_t::ncclFloat32,
                nccl_sys::ncclRedOp_t::ncclSum,
                comm,
                stream,
            )
        })?;
        self.sync()
    }
}

#[cfg(test)]
mod tests {
    use std::sync::Arc;

    use cudarc::driver::{CudaContext, CudaStream, DevicePtr};
    use cudarc::nccl::result as nr;

    use super::*;
    use crate::runtime::cuda::communicator::NcclId;

    // Helper: get raw device pointer from a CudaSlice for test use
    fn slice_ptr<T>(slice: &cudarc::driver::CudaSlice<T>, stream: &Arc<CudaStream>) -> u64 {
        let (ptr, _guard) = slice.device_ptr(stream);
        ptr as u64
    }

    /// Default streams on the first two devices, or `None` with a skip message.
    fn two_streams(test: &str) -> Option<Vec<Arc<CudaStream>>> {
        let n = CudaContext::device_count().map_or(0, |n| n.max(0) as usize);
        if n < 2 {
            eprintln!("skipping {test}: NCCL multi-rank tests need 2 CUDA devices, found {n}");
            return None;
        }
        Some(
            (0..2)
                .map(|i| CudaContext::new(i).unwrap().default_stream())
                .collect(),
        )
    }

    // ── Multi-GPU tests (require 2+ GPUs) ──────────────────────────────

    #[test]
    fn test_nccl_metadata() {
        let Some(streams) = two_streams("test_nccl_metadata") else {
            return;
        };
        let comms = NcclCommunicator::from_streams(streams).unwrap();
        assert_eq!(comms.len(), 2);
        assert_eq!(comms[0].world_size(), 2);
        assert_eq!(comms[1].world_size(), 2);
        assert_eq!(comms[0].rank(), 0);
        assert_eq!(comms[1].rank(), 1);
    }

    #[test]
    fn test_nccl_all_reduce_f32() {
        let Some(streams) = two_streams("test_nccl_all_reduce_f32") else {
            return;
        };
        let n = 4;
        let n_devices = streams.len();
        let comms = NcclCommunicator::from_streams(streams.clone()).unwrap();

        // Each rank has [rank+1, rank+1, rank+1, rank+1]
        let mut slices = Vec::new();
        for (i, stream) in streams.iter().enumerate() {
            slices.push(stream.clone_htod(&vec![(i + 1) as f32; n]).unwrap());
        }

        nr::group_start().unwrap();
        for (i, comm) in comms.iter().enumerate() {
            unsafe {
                comm.all_reduce(
                    slice_ptr(&slices[i], &streams[i]),
                    n,
                    DType::F32,
                    ReduceOp::Sum,
                )
                .unwrap();
            }
        }
        nr::group_end().unwrap();

        for (i, comm) in comms.iter().enumerate() {
            comm.sync().unwrap();
            let out = streams[i].clone_dtoh(&slices[i]).unwrap();
            let expected = (n_devices * (n_devices + 1)) as f32 / 2.0;
            for v in &out {
                assert!(
                    (*v - expected).abs() < 1e-5,
                    "rank {i}: expected {expected}, got {v}"
                );
            }
        }
    }

    #[test]
    fn test_nccl_from_rank_all_reduce_across_threads() {
        let Some(streams) = two_streams("test_nccl_from_rank_all_reduce_across_threads") else {
            return;
        };
        // One thread per rank stands in for one process per rank.
        let id = NcclId::from_bytes(NcclId::new().unwrap().bytes());
        let handles: Vec<_> = streams
            .into_iter()
            .enumerate()
            .map(|(rank, stream)| {
                std::thread::spawn(move || {
                    let comm = NcclCommunicator::from_rank(stream.clone(), rank, 2, id).unwrap();
                    let slice = stream.clone_htod(&[(rank + 1) as f32; 4]).unwrap();
                    unsafe {
                        comm.all_reduce(slice_ptr(&slice, &stream), 4, DType::F32, ReduceOp::Sum)
                            .unwrap();
                    }
                    comm.sync().unwrap();
                    comm.async_error().unwrap();
                    stream.clone_dtoh(&slice).unwrap()
                })
            })
            .collect();
        for handle in handles {
            assert_eq!(handle.join().unwrap(), vec![3.0f32; 4]);
        }
    }

    #[test]
    fn test_nccl_broadcast() {
        let Some(streams) = two_streams("test_nccl_broadcast") else {
            return;
        };
        let n = 4;
        let comms = NcclCommunicator::from_streams(streams.clone()).unwrap();

        let mut slices = Vec::new();
        for (i, stream) in streams.iter().enumerate() {
            let value = if i == 0 { 42.0f32 } else { 0.0f32 };
            slices.push(stream.clone_htod(&vec![value; n]).unwrap());
        }

        nr::group_start().unwrap();
        for (i, comm) in comms.iter().enumerate() {
            unsafe {
                comm.broadcast(slice_ptr(&slices[i], &streams[i]), n, DType::F32, 0)
                    .unwrap();
            }
        }
        nr::group_end().unwrap();

        for (i, comm) in comms.iter().enumerate() {
            comm.sync().unwrap();
            let out = streams[i].clone_dtoh(&slices[i]).unwrap();
            assert_eq!(out, vec![42.0f32; n], "rank {i} broadcast mismatch");
        }
    }

    #[test]
    fn test_nccl_all_gather() {
        let Some(streams) = two_streams("test_nccl_all_gather") else {
            return;
        };
        let n = 2; // elements per rank
        let n_devices = streams.len();
        let comms = NcclCommunicator::from_streams(streams.clone()).unwrap();

        let mut send_slices = Vec::new();
        let mut recv_slices = Vec::new();
        for (i, stream) in streams.iter().enumerate() {
            send_slices.push(stream.clone_htod(&vec![(i + 1) as f32; n]).unwrap());
            recv_slices.push(stream.alloc_zeros::<f32>(n * n_devices).unwrap());
        }

        nr::group_start().unwrap();
        for (i, comm) in comms.iter().enumerate() {
            unsafe {
                comm.all_gather(
                    slice_ptr(&send_slices[i], &streams[i]),
                    slice_ptr(&recv_slices[i], &streams[i]),
                    n,
                    DType::F32,
                )
                .unwrap();
            }
        }
        nr::group_end().unwrap();

        for (i, comm) in comms.iter().enumerate() {
            comm.sync().unwrap();
            let out = streams[i].clone_dtoh(&recv_slices[i]).unwrap();
            // Expected: [1.0, 1.0, 2.0, 2.0] for 2 devices
            let mut expected = Vec::new();
            for rank in 0..n_devices {
                expected.extend(std::iter::repeat_n((rank + 1) as f32, n));
            }
            assert_eq!(out, expected, "rank {i} all_gather mismatch");
        }
    }

    #[test]
    fn test_nccl_send_recv() {
        let Some(streams) = two_streams("test_nccl_send_recv") else {
            return;
        };
        let n = 4;
        let comms = NcclCommunicator::from_streams(streams.clone()).unwrap();

        let send_slice = streams[0].clone_htod(&vec![99.0f32; n]).unwrap();
        let recv_slice = streams[1].alloc_zeros::<f32>(n).unwrap();

        nr::group_start().unwrap();
        unsafe {
            comms[0]
                .send(slice_ptr(&send_slice, &streams[0]), n, DType::F32, 1, 0)
                .unwrap();
            comms[1]
                .recv(slice_ptr(&recv_slice, &streams[1]), n, DType::F32, 0, 0)
                .unwrap();
        }
        nr::group_end().unwrap();

        comms[0].sync().unwrap();
        comms[1].sync().unwrap();
        let out = streams[1].clone_dtoh(&recv_slice).unwrap();
        assert_eq!(out, vec![99.0f32; n]);
    }

    #[test]
    fn test_nccl_sync_barrier() {
        let Some(streams) = two_streams("test_nccl_sync_barrier") else {
            return;
        };
        let comms = NcclCommunicator::from_streams(streams).unwrap();

        for comm in &comms {
            comm.sync().unwrap();
        }
        // barrier requires all ranks to participate
        nr::group_start().unwrap();
        for comm in &comms {
            comm.barrier().unwrap();
        }
        nr::group_end().unwrap();
    }
}