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
use super::{
api::{
create_command_queue, create_context, enqueue_full_copy_buffer, enqueue_read_buffer,
enqueue_write_buffer, unified_ptr, wait_for_event, CLIntDevice, CommandQueue, Context,
},
cl_clear, KernelCacheCL, RawCL, CL_DEVICES,
};
use crate::{
cache::{Cache, CacheReturn},
devices::opencl::api::{create_buffer, MemFlags},
Alloc, AsDev, Buffer, CDatatype, CacheBuf, CachedLeaf, ClearBuf, CloneBuf, Device, DeviceType,
Error, Graph, GraphReturn, VecRead, WriteBuf, CPU,
};
use std::{
cell::{Ref, RefCell},
ffi::c_void,
fmt::Debug,
};
pub struct CLDevice {
pub kernel_cache: RefCell<KernelCacheCL>,
pub cache: RefCell<Cache<RawCL>>,
pub inner: RefCell<InternCLDevice>,
pub graph: RefCell<Graph>,
pub cpu: CPU,
}
unsafe impl Sync for InternCLDevice {}
impl CLDevice {
pub fn new(device_idx: usize) -> Result<CLDevice, Error> {
let inner = RefCell::new(CL_DEVICES.current(device_idx)?);
Ok(CLDevice {
kernel_cache: RefCell::new(KernelCacheCL::default()),
cache: RefCell::new(Cache::default()),
inner,
graph: RefCell::new(Graph::new()),
cpu: CPU::new(),
})
}
#[inline]
pub fn ctx(&self) -> Ref<Context> {
let borrow = self.inner.borrow();
Ref::map(borrow, |device| &device.ctx)
}
#[inline]
pub fn queue(&self) -> Ref<CommandQueue> {
let borrow = self.inner.borrow();
Ref::map(borrow, |device| &device.queue)
}
#[inline]
pub fn device(&self) -> CLIntDevice {
self.inner.borrow().device
}
pub fn global_mem_size_in_gb(&self) -> Result<f64, Error> {
Ok(self.device().get_global_mem()? as f64 * 10f64.powi(-9))
}
pub fn max_mem_alloc_in_gb(&self) -> Result<f64, Error> {
Ok(self.device().get_max_mem_alloc()? as f64 * 10f64.powi(-9))
}
pub fn name(&self) -> Result<String, Error> {
self.device().get_name()
}
pub fn version(&self) -> Result<String, Error> {
self.device().get_version()
}
#[inline]
pub fn unified_mem(&self) -> bool {
self.inner.borrow().unified_mem
}
pub fn set_unified_mem(&self, unified_mem: bool) {
self.inner.borrow_mut().unified_mem = unified_mem;
}
}
impl Debug for CLDevice {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
write!(
f,
"CLDevice {{
name: {name:?},
version: {version:?},
max_mem_alloc_in_gb: {max_mem:?},
unified_mem: {unified_mem},
}}",
name = self.name(),
version = self.version(),
unified_mem = self.unified_mem(),
max_mem = self.max_mem_alloc_in_gb()
)
}
}
impl<T> Alloc<T> for CLDevice {
fn alloc(&self, len: usize) -> (*mut T, *mut c_void, u64) {
let ptr =
create_buffer::<T>(&self.ctx(), MemFlags::MemReadWrite as u64, len, None).unwrap();
let cpu_ptr = if self.unified_mem() {
unified_ptr::<T>(&self.queue(), ptr, len).unwrap()
} else {
std::ptr::null_mut()
};
(cpu_ptr, ptr, 0)
}
fn with_data(&self, data: &[T]) -> (*mut T, *mut c_void, u64) {
let ptr = create_buffer::<T>(
&self.ctx(),
MemFlags::MemReadWrite | MemFlags::MemCopyHostPtr,
data.len(),
Some(data),
)
.unwrap();
let cpu_ptr = if self.unified_mem() {
unified_ptr::<T>(&self.queue(), ptr, data.len()).unwrap()
} else {
std::ptr::null_mut()
};
(cpu_ptr, ptr, 0)
}
fn as_dev(&self) -> Device {
Device {
device_type: DeviceType::CL,
device: self as *const CLDevice as *mut u8,
}
}
}
impl<'a, T> CloneBuf<'a, T> for CLDevice {
fn clone_buf(&'a self, buf: &Buffer<'a, T>) -> Buffer<'a, T> {
let cloned = Buffer::new(self, buf.len);
enqueue_full_copy_buffer::<T>(&self.queue(), buf.ptr.1, cloned.ptr.1, buf.len).unwrap();
cloned
}
}
impl<'a, T> CacheBuf<'a, T> for CLDevice {
#[inline]
fn cached(&'a self, len: usize) -> Buffer<'a, T> {
Cache::get(self, len, CachedLeaf)
}
}
impl CacheReturn<RawCL> for CLDevice {
#[inline]
fn cache(&self) -> std::cell::RefMut<Cache<RawCL>> {
self.cache.borrow_mut()
}
}
impl GraphReturn for CLDevice {
#[inline]
fn graph(&self) -> std::cell::RefMut<Graph> {
self.graph.borrow_mut()
}
}
#[cfg(feature = "opt-cache")]
impl crate::GraphOpt for CLDevice {}
#[inline]
pub fn cl_cached<T>(device: &CLDevice, len: usize) -> Buffer<T> {
device.cached(len)
}
impl<T: CDatatype> ClearBuf<T> for CLDevice {
#[inline]
fn clear(&self, buf: &mut Buffer<T>) {
cl_clear(self, buf).unwrap()
}
}
impl<T> WriteBuf<T> for CLDevice {
fn write(&self, buf: &mut Buffer<T>, data: &[T]) {
let event = unsafe { enqueue_write_buffer(&self.queue(), buf.ptr.1, data, false).unwrap() };
wait_for_event(event).unwrap();
}
}
impl<T: Clone + Default> VecRead<T> for CLDevice {
fn read(&self, buf: &crate::Buffer<T>) -> Vec<T> {
assert!(
!buf.ptr.1.is_null(),
"called VecRead::read(..) on a non OpenCL buffer (this would read out a null pointer)"
);
let mut read = vec![T::default(); buf.len];
let event =
unsafe { enqueue_read_buffer(&self.queue(), buf.ptr.1, &mut read, false).unwrap() };
wait_for_event(event).unwrap();
read
}
}
impl AsDev for CLDevice {}
#[derive(Debug, Clone)]
pub struct InternCLDevice {
pub ptrs: Vec<*mut c_void>,
device: CLIntDevice,
ctx: Context,
queue: CommandQueue,
unified_mem: bool,
}
impl InternCLDevice {
pub fn new(device: CLIntDevice) -> crate::Result<InternCLDevice> {
let ctx = create_context(&[device])?;
let queue = create_command_queue(&ctx, device)?;
let unified_mem = device.unified_mem()?;
Ok(InternCLDevice {
ptrs: Vec::new(),
device,
ctx,
queue,
unified_mem,
})
}
}