ndrs 0.3.0

A tensor library with GPU support
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
//! 具体视图类型:RcTensorView 和 ArcTensorView
use super::slice::{SliceArg, SliceInfo};
use super::trait_def::TensorViewOps;
use crate::cuda;
use crate::cuda::Stream;
use crate::dtype::{get_dtype_info, DType};
use crate::kernel::*;
use crate::tensor::{ArcTensor, DataPtr, RcTensor, Tensor};
use crate::Device;
use cudarc::driver::DevicePtr;
use parking_lot::ReentrantMutexGuard;
use std::cell::RefCell;
use std::cell::{Ref, RefMut};
use std::ops::{Deref, DerefMut};
use std::rc::Rc;
use std::sync::{Arc, Mutex};

// Rc<RefCell<Tensor>> 的锁:返回 &RefCell<Tensor>
fn lock_rc(handle: &RcTensor) -> &RefCell<Tensor> {
    &*handle.0
}

// Arc<ReentrantMutex<RefCell<Tensor>>> 的锁:返回 ReentrantMutexGuard<RefCell<Tensor>>
fn lock_arc(handle: &ArcTensor) -> parking_lot::ReentrantMutexGuard<RefCell<Tensor>> {
    handle.0.lock()
}

fn into_rc(t: Tensor) -> RcTensor {
    RcTensor::from(t)
}
fn into_arc(t: Tensor) -> ArcTensor {
    ArcTensor::from(t)
}

macro_rules! impl_tensor_view {
    ($name:ident, $handle:ty, $lock:ident, $into_handle:expr) => {
        #[derive(Clone)]
        pub struct $name {
            handle: $handle,
            offset: usize,
            shape: Vec<usize>,
            strides: Vec<usize>,
            dtype: DType,
            device: Device,
        }

        impl $name {
            pub fn new(handle: $handle) -> Self {
                let (shape, strides, dtype, device) = {
                    let cell = $lock(&handle);
                    let tensor = cell.borrow(); // 只读借用
                    (
                        tensor.shape().to_vec(),
                        tensor.strides().to_vec(),
                        tensor.dtype(),
                        tensor.device(),
                    )
                };
                $name {
                    handle,
                    offset: 0,
                    shape,
                    strides,
                    dtype,
                    device,
                }
            }

            pub fn into_handle(self) -> $handle {
                self.handle
            }

            pub fn handle(&self) -> &$handle {
                &self.handle
            }

            fn create_output(&self) -> Result<Self, String> {
                self.create_output_on_device(self.device)
            }

            fn create_output_on_device(&self, device: Device) -> Result<Self, String> {
                let elem_size = get_dtype_info(self.dtype).unwrap().size;
                let total_bytes = self.size() * elem_size;
                let shape = self.shape().to_vec();
                let dtype = self.dtype;

                let new_tensor = match device {
                    Device::Cpu => {
                        let bytes = vec![0u8; total_bytes].into_boxed_slice();
                        Tensor::new_cpu_from_bytes(bytes, shape, dtype)?
                    }
                    Device::Cuda(dev_id) => {
                        let stream = cuda::get_stream().map_err(|e| e.to_string())?;
                        if stream.device_id != dev_id {
                            return Err(format!(
                                "Stream device {} does not match target device {}",
                                stream.device_id, dev_id
                            ));
                        }
                        let gpu_mem = stream
                            .inner()
                            .alloc_zeros::<u8>(total_bytes)
                            .map_err(|e| e.to_string())?;
                        let strides = Tensor::compute_row_major_strides(&shape, elem_size);
                        Tensor {
                            data: DataPtr::Gpu(gpu_mem),
                            shape,
                            strides,
                            dtype,
                            device,
                        }
                    }
                };
                Ok($name::new($into_handle(new_tensor)))
            }
        }

        impl TensorViewOps for $name {
            type Handle = $handle;

            fn new(handle: $handle) -> Self {
                Self::new(handle)
            }

            fn as_strided(
                &self,
                new_shape: Vec<usize>,
                new_strides: Vec<usize>,
                offset: usize,
            ) -> Self {
                assert_eq!(new_shape.len(), new_strides.len());
                $name {
                    handle: self.handle.clone(),
                    offset: self.offset + offset,
                    shape: new_shape,
                    strides: new_strides,
                    dtype: self.dtype,
                    device: self.device,
                }
            }

            fn is_contiguous(&self) -> bool {
                let elem_size = get_dtype_info(self.dtype).unwrap().size;
                let expected = Tensor::compute_row_major_strides(&self.shape, elem_size);
                self.strides == expected
            }

            fn shape(&self) -> &[usize] {
                &self.shape
            }

            fn strides(&self) -> &[usize] {
                &self.strides
            }

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

            fn dtype(&self) -> DType {
                self.dtype
            }

            fn size(&self) -> usize {
                self.shape.iter().product()
            }

            fn assign(&mut self, src: &Self) -> Result<(), String> {
                if self.shape != src.shape {
                    return Err("Shape mismatch".into());
                }
                src.strided_copy_to(self)
            }

            // 其他宏展开
            $crate::impl_device_transfer!($name, $lock, $into_handle);
            $crate::impl_broadcast_to!($name, $lock, $into_handle);
            $crate::impl_transpose!($name, $lock, $into_handle);
            $crate::impl_slice!($name, $lock, $into_handle);
            $crate::impl_concat_split!($name, $lock, $into_handle);
            $crate::impl_strided_copy_to!($name, $lock, $into_handle);
            $crate::impl_contiguous!($name, $lock, $into_handle);
            $crate::impl_matmul_with_out!($name, $lock, $into_handle);
            $crate::impl_matmul!($name, $lock, $into_handle);
        }

        // 加法操作宏也需要修改
        $crate::impl_add_for_view!($name, $lock, $into_handle);
    };
}
impl_tensor_view!(RcTensorView, RcTensor, lock_rc, into_rc);
impl_tensor_view!(ArcTensorView, ArcTensor, lock_arc, into_arc);

pub trait AsView {
    type View: TensorViewOps;
    fn as_view(&self) -> Self::View;
}

macro_rules! define_view_to_vec {
    ($func_name:ident, $view_type:ident, $into_handle:expr, $lock:ident) => {
        fn $func_name<T: bytemuck::Pod + crate::dtype::DTypeMapping>(view: &$view_type) -> Vec<T> {
            let cpu_view = view.to_cpu().expect("Failed to copy to CPU");
            let cell = $lock(&cpu_view.handle);
            let tensor = cell.borrow(); // 添加 .borrow()
            let bytes = tensor.as_bytes().expect("Failed to get bytes");
            let result = unsafe {
                std::slice::from_raw_parts(bytes.as_ptr() as *const T, view.size()).to_vec()
            };
            result
        }
    };
}

define_view_to_vec!(rc_view_to_vec, RcTensorView, into_rc, lock_rc);
define_view_to_vec!(arc_view_to_vec, ArcTensorView, into_arc, lock_arc);

pub fn rc_view_to_vec_f32(view: &RcTensorView) -> Vec<f32> {
    rc_view_to_vec(view)
}
pub fn arc_view_to_vec_f32(view: &ArcTensorView) -> Vec<f32> {
    arc_view_to_vec(view)
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::cuda::{
        self, get_device_count as get_cuda_device_count, is_available as cuda_available,
        set_device as set_current_device,
    };
    use crate::s;
    use crate::tensor::Tensor;
    use crate::view::trait_def::TensorViewOps;
    use crate::DTYPE_FLOAT32;

    // ---------- RcTensorView 测试 ----------
    #[test]
    fn test_rc_view_creation() {
        let t = Tensor::new_cpu_from_f32(vec![1.0, 2.0, 3.0, 4.0], vec![2, 2]);
        let view = t.into_rc().as_view();
        assert_eq!(view.shape(), &[2, 2]);
        assert_eq!(view.strides(), &[8, 4]);
        assert_eq!(view.offset(), 0);
    }

    // ---------- ArcTensorView 测试 ----------
    #[test]
    fn test_arc_view_creation() {
        let t = Tensor::new_cpu_from_f32(vec![1.0, 2.0, 3.0, 4.0], vec![2, 2]);
        let view = t.into_arc().as_view();
        assert_eq!(view.shape(), &[2, 2]);
        assert_eq!(view.strides(), &[8, 4]);
        assert_eq!(view.offset(), 0);
    }

    #[test]
    fn test_rc_contiguous() {
        let t = Tensor::new_cpu_from_f32((0..6).map(|x| x as f32).collect(), vec![2, 3]);
        let view = t.into_rc().as_view();
        let transposed = view.as_strided(vec![3, 2], vec![4, 12], 0);
        let out_tensor = Tensor::new_cpu_from_bytes(
            vec![0u8; 6 * 4].into_boxed_slice(),
            vec![3, 2],
            DTYPE_FLOAT32,
        )
        .unwrap();
        let out_handle = out_tensor.into_rc();
        let mut out_view = RcTensorView::new(out_handle);
        transposed.contiguous(&mut out_view).unwrap();
        assert_eq!(
            rc_view_to_vec_f32(&out_view),
            vec![0.0, 3.0, 1.0, 4.0, 2.0, 5.0]
        );
    }

    #[test]
    fn test_arc_contiguous() {
        let t = Tensor::new_cpu_from_f32((0..6).map(|x| x as f32).collect(), vec![2, 3]);
        let view = t.into_arc().as_view();
        let transposed = view.as_strided(vec![3, 2], vec![4, 12], 0);
        let out_tensor = Tensor::new_cpu_from_bytes(
            vec![0u8; 6 * 4].into_boxed_slice(),
            vec![3, 2],
            DTYPE_FLOAT32,
        )
        .unwrap();
        let out_handle = out_tensor.into_arc();
        let mut out_view = ArcTensorView::new(out_handle);
        transposed.contiguous(&mut out_view).unwrap();
        assert_eq!(
            arc_view_to_vec_f32(&out_view),
            vec![0.0, 3.0, 1.0, 4.0, 2.0, 5.0]
        );
    }

    #[test]
    fn test_arc_slice_add_assign() {
        let a = Tensor::new_cpu_from_f32(vec![1.0, 2.0, 3.0, 4.0], vec![2, 2]);
        let b = Tensor::new_cpu_from_f32(vec![5.0, 6.0], vec![1, 2]);
        let mut a_view = a.into_arc().as_view();
        let b_view = b.into_arc().as_view();
        let mut sub = a_view.slice(&s![1..2, ..]).unwrap();
        sub += b_view;
        assert_eq!(arc_view_to_vec_f32(&a_view), vec![1.0, 2.0, 8.0, 10.0]);
    }

    #[test]
    fn test_stream_wait_event() {
        if !cuda::is_available() {
            return;
        }
        cuda::set_device(0).unwrap();

        let stream1 = cuda::Stream::new(None).unwrap(); // 使用 cuda::Stream
        let stream2 = cuda::Stream::new(None).unwrap();

        // 创建 CPU 数据并上传到 GPU
        let a_cpu = Tensor::new_cpu_from_f32(vec![1.0, 2.0], vec![2]);
        let b_cpu = Tensor::new_cpu_from_f32(vec![3.0, 4.0], vec![2]);

        let a_gpu = a_cpu.into_arc().as_view().to_gpu(0).unwrap();
        let b_gpu = b_cpu.into_arc().as_view().to_gpu(0).unwrap();

        // 创建输出张量(全零) - 需要两个独立的零张量,因为 into_arc 消耗所有权
        let zero_cpu1 = Tensor::new_contiguous(vec![2], DTYPE_FLOAT32).unwrap();
        let mut out_gpu = zero_cpu1.into_arc().as_view().to_gpu(0).unwrap();

        // 异步加法(使用默认流)
        ArcTensorView::add(&a_gpu, &b_gpu, &mut out_gpu).unwrap();

        let event = stream1.record().unwrap();
        stream2.wait_event(&event).unwrap();

        // 第二个输出张量
        let zero_cpu2 = Tensor::new_contiguous(vec![2], DTYPE_FLOAT32).unwrap();
        let mut out2_gpu = zero_cpu2.into_arc().as_view().to_gpu(0).unwrap();
        ArcTensorView::add(&out_gpu, &out_gpu, &mut out2_gpu).unwrap();

        stream2.synchronize().unwrap();
        let result = arc_view_to_vec_f32(&out2_gpu);
        assert_eq!(result, vec![8.0, 12.0]);
    }

    #[test]
    fn test_device_context_switch() {
        if !cuda::is_available() {
            return;
        }
        let dev_count = get_cuda_device_count().unwrap();
        if dev_count < 2 {
            return;
        }

        cuda::set_device(0).unwrap();
        let a = Tensor::new_cpu_from_f32(vec![1.0, 2.0], vec![2]);
        let a_view = a.into_arc().as_view();
        let a_gpu = a_view.to_gpu(0).unwrap();

        cuda::set_device(1);
        let b = Tensor::new_cpu_from_f32(vec![3.0, 4.0], vec![2]);
        let b_view = b.into_arc().as_view();
        let b_gpu = b_view.to_gpu(1).unwrap();

        // 不能直接跨设备加法,应该报错
        let zero_cpu = Tensor::new_contiguous(vec![2], DTYPE_FLOAT32).unwrap();
        let mut out_gpu = zero_cpu.into_arc().as_view().to_gpu(0).unwrap();
        let result = ArcTensorView::add(&a_gpu, &b_gpu, &mut out_gpu);
        assert!(result.is_err());
    }

    #[test]
    fn test_event_timing_and_wait() {
        if !cuda::is_available() {
            eprintln!("CUDA not available, skipping test");
            return;
        }
        cuda::set_device(0).unwrap();

        let stream1 = cuda::Stream::new(Some(0)).unwrap();
        let stream2 = cuda::Stream::new(Some(0)).unwrap();

        let size = 1024 * 1024;
        let shape = vec![1024, 1024];

        // 在 stream1 上执行加法
        cuda::set_stream(stream1.clone()).unwrap();
        let a = Tensor::new_cpu_from_f32(vec![1.0; size], shape.clone());
        let b = Tensor::new_cpu_from_f32(vec![2.0; size], shape.clone());
        let a_gpu = a.into_arc().as_view().to_gpu(0).unwrap();
        let b_gpu = b.into_arc().as_view().to_gpu(0).unwrap();
        let mut out1 = Tensor::new_contiguous(shape.clone(), DTYPE_FLOAT32)
            .unwrap()
            .into_arc()
            .as_view()
            .to_gpu(0)
            .unwrap();
        ArcTensorView::add(&a_gpu, &b_gpu, &mut out1).unwrap();

        // 在 stream1 上记录事件
        let event = stream1.record().unwrap();

        // 切换到 stream2,等待事件后执行加法
        cuda::set_stream(stream2.clone()).unwrap();
        stream2.wait_event(&event).unwrap();

        let mut out2 = Tensor::new_contiguous(shape, DTYPE_FLOAT32)
            .unwrap()
            .into_arc()
            .as_view()
            .to_gpu(0)
            .unwrap();
        ArcTensorView::add(&out1, &out1, &mut out2).unwrap();

        stream2.synchronize().unwrap();

        let result = arc_view_to_vec_f32(&out2);
        let expected: Vec<f32> = vec![6.0; size];
        assert_eq!(result, expected);
    }
    #[test]
    fn test_event_elapsed_custom_stream() {
        if !cuda::is_available() {
            return;
        }
        cuda::set_device(0).unwrap();
        let stream = cuda::Stream::new(Some(0)).unwrap();
        cuda::set_stream(stream.clone()).unwrap();

        let a = Tensor::new_cpu_from_f32(vec![1.0; 1024 * 1024], vec![1024, 1024])
            .into_arc()
            .as_view()
            .to_gpu(0)
            .unwrap();
        let b = Tensor::new_cpu_from_f32(vec![2.0; 1024 * 1024], vec![1024, 1024])
            .into_arc()
            .as_view()
            .to_gpu(0)
            .unwrap();
        let mut out = Tensor::new_cpu_from_f32(vec![0.0; 1024 * 1024], vec![1024, 1024])
            .into_arc()
            .as_view()
            .to_gpu(0)
            .unwrap();

        let start = stream.record().unwrap();
        ArcTensorView::add(&a, &b, &mut out).unwrap();
        let end = stream.record().unwrap();
        stream.synchronize().unwrap();

        let elapsed = end.elapsed_since(&start).unwrap();
        println!("Elapsed: {:?}", elapsed);
    }
}