Skip to content

Commit 3bfa46d

Browse files
committed
Merge branch 'main' into webgl
2 parents 3327757 + 896849a commit 3bfa46d

12 files changed

Lines changed: 138 additions & 53 deletions

File tree

src/cache/borrow_cache.rs

Lines changed: 20 additions & 15 deletions
Original file line numberDiff line numberDiff line change
@@ -65,7 +65,7 @@ impl BorrowCache {
6565

6666
pub fn add_or_get_mut<'a, T, D, S>(
6767
&mut self,
68-
device: &D,
68+
device: &'a D,
6969
id: Id,
7070
new_buf: &mut bool,
7171
) -> &mut Buffer<'a, T, D, S>
@@ -75,7 +75,7 @@ impl BorrowCache {
7575
S: Shape,
7676
{
7777
self.add_buf_once::<T, D, S>(device, id, new_buf);
78-
self.get_buf_mut(id).unwrap()
78+
unsafe { self.get_buf_mut(id).unwrap() }
7979
}
8080

8181
pub fn add_buf_once<T, D, S>(&mut self, device: &D, id: Id, new_buf: &mut bool)
@@ -91,7 +91,7 @@ impl BorrowCache {
9191
self.add_buf::<T, D, S>(device, id)
9292
}
9393

94-
pub fn add_buf<T, D, S>(&mut self, device: &D, id: Id)
94+
pub fn add_buf<'a, T, D, S>(&'a mut self, device: &'a D, id: Id)
9595
where
9696
T: Unit + 'static,
9797
D: Alloc<T> + 'static,
@@ -123,7 +123,7 @@ impl BorrowCache {
123123
}
124124

125125
#[inline]
126-
pub fn get_buf<'a, T, D, S>(&self, id: Id) -> Result<&Buffer<'a, T, D, S>, CachingError>
126+
pub unsafe fn get_buf<'a, T, D, S>(&self, id: Id) -> Result<&Buffer<'a, T, D, S>, CachingError>
127127
where
128128
T: Unit + 'static,
129129
D: Device + 'static,
@@ -137,7 +137,7 @@ impl BorrowCache {
137137
}
138138

139139
#[inline]
140-
pub fn get_buf_mut<'a, T, D, S>(
140+
pub unsafe fn get_buf_mut<'a, T, D, S>(
141141
&mut self,
142142
id: Id,
143143
) -> Result<&mut Buffer<'a, T, D, S>, CachingError>
@@ -161,16 +161,21 @@ impl BorrowCache {
161161
#[cfg(test)]
162162
mod tests {
163163

164-
/*#[test]
165-
fn test_comp_error() {
166-
let device = CPU::<Base>::new();
164+
// #[test]
165+
// #[cfg(feature = "cpu")]
166+
// fn test_comp_error() {
167+
// use crate::{Base, BorrowCache, Id, CPU};
167168

169+
// let mut cache = BorrowCache::default();
168170

169-
let a = {
170-
let mut cache = BorrowingCache::default();
171-
cache.add_or_get::<f32, CPU, ()>(&device, Id::new(10))
172-
};
173-
}*/
171+
172+
// let a = {
173+
// let device = CPU::<Base>::new();
174+
// // drop(device);
175+
// let mut new_buf = false;
176+
// // cache.add_or_get::<f32, CPU, ()>(&device, Id { id: 0, len: 10}, &mut new_buf)
177+
// };
178+
// }
174179

175180
#[cfg(feature = "cpu")]
176181
#[test]
@@ -190,8 +195,8 @@ mod tests {
190195
cache.add_buf_once::<f32, _, ()>(&device, sid, &mut false);
191196
cache.add_buf_once::<f32, _, ()>(&device, tid, &mut false);
192197

193-
let a: &Buffer = cache.get_buf::<f32, _, ()>(fid).unwrap();
194-
let b: &Buffer = cache.get_buf::<f32, _, ()>(fid).unwrap();
198+
let a: &Buffer = unsafe { cache.get_buf::<f32, _, ()>(fid).unwrap() };
199+
let b: &Buffer = unsafe { cache.get_buf::<f32, _, ()>(fid).unwrap() };
195200

196201
assert_eq!(a.ptr, b.ptr);
197202
}

src/devices/opencl/cl_device.rs

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -3,7 +3,7 @@ use min_cl::CLDevice;
33
use min_cl::api::{create_buffer, enqueue_full_copy_buffer, MemFlags};
44

55
use super::{enqueue_kernel, AsClCvoidPtr, CLPtr};
6-
use crate::flag::AllocFlag;
6+
use crate::{flag::AllocFlag, opencl::KernelLaunch};
77
use crate::{impl_device_traits, Shape, Unit};
88
use crate::{
99
pass_down_use_gpu_or_cpu, Alloc, Base, Buffer, Cached, CachedCPU, CloneBuf, Device,
@@ -160,7 +160,7 @@ impl<Mods> OpenCL<Mods> {
160160
lws: Option<[usize; 3]>,
161161
args: &[&dyn AsClCvoidPtr],
162162
) -> crate::Result<()> {
163-
enqueue_kernel(self, src, gws, lws, args)
163+
self.device.launch_kernel(src, gws, lws, args)
164164
}
165165
}
166166

src/devices/opencl/kernel_enqueue.rs

Lines changed: 23 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -115,6 +115,29 @@ impl<T> AsClCvoidPtr for CLPtr<T> {
115115
}
116116
}
117117

118+
pub trait KernelLaunch {
119+
fn launch_kernel(
120+
&self,
121+
src: &str,
122+
gws: [usize; 3],
123+
lws: Option<[usize; 3]>,
124+
args: &[&dyn AsClCvoidPtr],
125+
) -> crate::Result<()>;
126+
}
127+
128+
impl KernelLaunch for CLDevice {
129+
#[inline]
130+
fn launch_kernel(
131+
&self,
132+
src: &str,
133+
gws: [usize; 3],
134+
lws: Option<[usize; 3]>,
135+
args: &[&dyn AsClCvoidPtr],
136+
) -> crate::Result<()> {
137+
enqueue_kernel(self, src, gws, lws, args)
138+
}
139+
}
140+
118141
/// Executes a cached OpenCL kernel.
119142
/// # Example
120143
///

src/devices/untyped/dummy_cuda.rs

Lines changed: 7 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -16,7 +16,7 @@ impl<Mods: OnDropBuffer> Device for CUDA<Mods> {
1616
}
1717

1818
#[cfg(feature = "std")]
19-
Err(crate::DeviceError::CPUDeviceNotAvailable.into())
19+
Err(crate::DeviceError::CPUDeviceNotAvailable)
2020
}
2121

2222
fn base_to_data<T: Unit, S: Shape>(&self, base: Self::Base<T, S>) -> Self::Data<T, S> {
@@ -30,15 +30,15 @@ impl<Mods: OnDropBuffer> Device for CUDA<Mods> {
3030
wrap
3131
}
3232

33-
fn data_as_wrap<'a, T: Unit, S: Shape>(
34-
data: &'a Self::Data<T, S>,
35-
) -> &'a Self::Wrap<T, Self::Base<T, S>> {
33+
fn data_as_wrap<T: Unit, S: Shape>(
34+
data: &Self::Data<T, S>,
35+
) -> &Self::Wrap<T, Self::Base<T, S>> {
3636
data
3737
}
3838

39-
fn data_as_wrap_mut<'a, T: Unit, S: Shape>(
40-
data: &'a mut Self::Data<T, S>,
41-
) -> &'a mut Self::Wrap<T, Self::Base<T, S>> {
39+
fn data_as_wrap_mut<T: Unit, S: Shape>(
40+
data: &mut Self::Data<T, S>,
41+
) -> &mut Self::Wrap<T, Self::Base<T, S>> {
4242
data
4343
}
4444
}

src/devices/untyped/untyped_device.rs

Lines changed: 6 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -42,16 +42,16 @@ impl Device for Untyped {
4242
}
4343

4444
#[inline]
45-
fn data_as_wrap<'a, T: Unit, S: crate::Shape>(
46-
data: &'a Self::Data<T, S>,
47-
) -> &'a Self::Wrap<T, Self::Base<T, S>> {
45+
fn data_as_wrap<T: Unit, S: crate::Shape>(
46+
data: &Self::Data<T, S>,
47+
) -> &Self::Wrap<T, Self::Base<T, S>> {
4848
data
4949
}
5050

5151
#[inline]
52-
fn data_as_wrap_mut<'a, T: Unit, S: crate::Shape>(
53-
data: &'a mut Self::Data<T, S>,
54-
) -> &'a mut Self::Wrap<T, Self::Base<T, S>> {
52+
fn data_as_wrap_mut<T: Unit, S: crate::Shape>(
53+
data: &mut Self::Data<T, S>,
54+
) -> &mut Self::Wrap<T, Self::Base<T, S>> {
5555
data
5656
}
5757

src/exec_on_cpu.rs

Lines changed: 60 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -322,7 +322,19 @@ mod tests {
322322
out
323323
}
324324
);
325-
assert_eq!(a.read(), vec![2, 4, 6, 8])
325+
326+
assert_eq!(a.read(), vec![2, 4, 6, 8]);
327+
let cpu = crate::CPU::<Base>::new();
328+
let other_a: crate::Buffer<i32, crate::OpenCL> = cpu_exec!(
329+
&device, &cpu, lhs, rhs; {
330+
let mut out = cpu.retrieve(lhs.len(), (&lhs, &rhs)).unwrap();
331+
for ((lhs, rhs), out) in lhs.iter().zip(rhs.iter()).zip(out.iter_mut()) {
332+
*out = lhs + rhs;
333+
}
334+
out
335+
}
336+
);
337+
assert_eq!(other_a.read(), vec![2, 4, 6, 8]);
326338
}
327339

328340
#[cfg(feature = "opencl")]
@@ -421,4 +433,51 @@ mod tests {
421433

422434
Ok(())
423435
}
436+
437+
pub trait AddEw<T, D: crate::Device = Self>: crate::Device {
438+
fn add(&self, lhs: &crate::Buffer<T, D>, rhs: &crate::Buffer<T, D>) -> crate::Buffer<T, D>;
439+
}
440+
441+
impl<Mods, T> AddEw<T> for crate::CPU<Mods>
442+
where
443+
Mods: crate::hooks::OnDropBuffer + crate::Retrieve<Self, T> + 'static,
444+
Self::Base<T, ()>: core::ops::Deref<Target = [T]>,
445+
T: core::ops::Add<Output = T> + Copy,
446+
{
447+
fn add(
448+
&self,
449+
lhs: &crate::Buffer<T, Self>,
450+
rhs: &crate::Buffer<T, Self>,
451+
) -> crate::Buffer<T, Self> {
452+
use crate::Retriever;
453+
let mut out = self.retrieve(lhs.len(), (lhs, rhs)).unwrap();
454+
for idx in 0..lhs.len() {
455+
out[idx] = lhs[idx] + rhs[idx]
456+
}
457+
out
458+
}
459+
}
460+
461+
#[cfg(feature = "opencl")]
462+
#[test]
463+
fn test_cpu_exec_macro() -> crate::Result<()> {
464+
use crate::{prelude::chosen_cl_idx, Base, Cached, Device, OpenCL, CPU};
465+
466+
let device = OpenCL::<Cached<Base>>::new(chosen_cl_idx())?;
467+
let cpu = CPU::<Cached<Base>>::new();
468+
469+
let lhs = device.buffer([1, 2, 3, 4, 5]);
470+
let rhs = device.buffer([-1, -4, -1, -8, -1]);
471+
472+
let out1 = crate::cpu_exec!(&device, &cpu, lhs, rhs; cpu.add(&lhs, &rhs));
473+
474+
let out = {
475+
let lhs = crate::Buffer::<_, _>::from(((&cpu), lhs. read_to_vec()));
476+
let rhs = crate::Buffer::<_, _>::from(((&cpu), rhs. read_to_vec()));
477+
let cpu_out = cpu.add(&lhs, &rhs);
478+
crate::Buffer::from((&device, cpu_out))
479+
};
480+
assert_eq!(out1.read(), out.read());
481+
Ok(())
482+
}
424483
}

src/exec_on_cpu/cl_may_unified.rs

Lines changed: 7 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -103,16 +103,21 @@ where
103103
/// This is way faster than [cpu_exec_reduce], as new memory is not allocated.
104104
///
105105
/// `cpu_exec_binary_may_unified` can be used interchangeably with [cpu_exec_reduce].
106-
pub fn cpu_exec_reduce_may_unified<T, F>(device: &OpenCL, x: &Buffer<T, OpenCL>, f: F) -> T
106+
pub fn cpu_exec_reduce_may_unified<T, F, Mods>(
107+
device: &min_cl::CLDevice,
108+
x: &Buffer<T, OpenCL<Mods>>,
109+
f: F,
110+
) -> T
107111
where
108112
T: Unit + Default + Clone,
109113
F: Fn(&CPU, &Buffer<T, CPU>) -> T,
114+
Mods: OnDropBuffer + 'static,
110115
{
111116
let cpu = CPU::<crate::Base>::new();
112117

113118
if device.unified_mem() {
114119
return f(&cpu, &unsafe {
115-
Buffer::from_raw_host(x.data.host_ptr, x.len())
120+
Buffer::from_raw_host(x.base().host_ptr, x.len())
116121
});
117122
}
118123
cpu_exec_reduce(x, f)

src/modules/autograd/gradients.rs

Lines changed: 8 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -12,7 +12,7 @@ const INVALID_ID: &str = "A matching Buffer does not exist.";
1212
/// The cache is populated by `get_ref`, `get_like` or `get_mut_ref` calls.
1313
#[derive(Default)]
1414
pub struct Gradients {
15-
pub grads_pool: BorrowCache,
15+
pub(crate) grads_pool: BorrowCache,
1616
pub no_grads_pool: Buffers<Box<dyn BoxedShallowCopy>>,
1717
pub zero_grad_cbs: Vec<(Id, fn(&mut dyn Any))>,
1818
pub buf_requires_grad: HashMap<UniqueId, bool, BuildHasherDefault<NoHasher>>,
@@ -27,8 +27,6 @@ impl core::fmt::Debug for Gradients {
2727
}
2828

2929
impl Gradients {
30-
/// Clears the cache.
31-
#[inline]
3230
pub fn zero_grad(&mut self) {
3331
for (id, cb) in &self.zero_grad_cbs {
3432
let grad_buf = self.grads_pool.cache.get_mut(id).unwrap();
@@ -42,6 +40,7 @@ impl Gradients {
4240
// self.grads_pool.cache.clear();
4341
}
4442

43+
#[inline]
4544
pub fn add_zero_grad_cb<T, D, S>(&mut self, id: &Id)
4645
where
4746
T: Unit + 'static,
@@ -57,18 +56,18 @@ impl Gradients {
5756

5857
/// May get a reference to a gradient [`Buffer`].
5958
#[inline]
60-
pub fn may_get_ref<'a, T, S, D>(&self, ident: Id) -> Result<&Buffer<'a, T, D, S>, CachingError>
59+
pub(crate) unsafe fn may_get_ref<'a, T, S, D>(&self, ident: Id) -> Result<&Buffer<'a, T, D, S>, CachingError>
6160
where
6261
T: Unit + 'static,
6362
S: Shape,
6463
D: Alloc<T> + 'static,
6564
{
66-
self.grads_pool.get_buf(ident)
65+
unsafe { self.grads_pool.get_buf(ident) }
6766
}
6867

6968
/// May get a mutable reference to a gradient [`Buffer`].
7069
#[inline]
71-
pub fn may_get_mut<'a, T, S, D>(
70+
pub(crate) unsafe fn may_get_mut<'a, T, S, D>(
7271
&mut self,
7372
id: Id,
7473
) -> Result<&mut Buffer<'a, T, D, S>, CachingError>
@@ -77,7 +76,7 @@ impl Gradients {
7776
S: Shape,
7877
D: Alloc<T> + 'static,
7978
{
80-
self.grads_pool.get_buf_mut(id)
79+
unsafe { self.grads_pool.get_buf_mut(id) }
8180
}
8281

8382
/// Returns a reference to a gradient [`Buffer`].
@@ -97,7 +96,7 @@ impl Gradients {
9796
if new_buf {
9897
self.add_zero_grad_cb::<T, D, S>(&id);
9998
}
100-
self.grads_pool.get_buf(id).unwrap()
99+
unsafe { self.grads_pool.get_buf(id).unwrap() }
101100
}
102101

103102
/// Returns a mutable reference to a gradient [`Buffer`].
@@ -116,7 +115,7 @@ impl Gradients {
116115
if new_buf {
117116
self.add_zero_grad_cb::<T, D, S>(&id);
118117
}
119-
self.grads_pool.get_buf_mut(id).unwrap()
118+
unsafe { self.grads_pool.get_buf_mut(id).unwrap() }
120119
}
121120

122121
/// Returns a reference to a gradient [`Buffer`] using information from `buf`.

src/modules/lazy.rs

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -752,7 +752,7 @@ mod tests {
752752
.unwrap();
753753
}
754754

755-
if let Ok(_) = unsafe { device.run() } {
755+
if unsafe { device.run() }.is_ok() {
756756
panic!()
757757
}
758758
}

src/modules/lazy/lazy_graph.rs

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -55,7 +55,7 @@ impl<B: AsAny, T> LazyGraph<B, T> {
5555
args: Args,
5656
op: fn(&mut Args) -> crate::Result<()>,
5757
) -> Operation<B, T> {
58-
// store ids and test if buffers are still in cache
58+
// store ids and test if buffers are still in cache afterwards
5959
let arg_ids = args
6060
.maybe_ids()
6161
.into_iter()

0 commit comments

Comments
 (0)