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
#[allow(unused_imports)]
use crate::error::ErrorCode;
use std::{ffi::CString, ptr, sync::Arc};
use singe_cuda_sys::driver;
use crate::{
context::Context,
error::{Error, Result},
graph::{ExecutableGraph, Graph, GraphNode},
kernel::{self, LibraryKernelHandle},
module::{KernelFunction, KernelParameters, LaunchConfig, Module},
try_cuda,
types::{DeviceFunction, FunctionAttribute, FunctionCache},
};
#[derive(Debug)]
pub struct Library {
handle: driver::CUlibrary,
ctx: Arc<Context>,
}
#[derive(Debug, Clone, Copy)]
pub struct LibraryGlobal<'a> {
ptr: *mut (),
size: usize,
_library: &'a Library,
}
#[derive(Debug, Clone, Copy)]
pub struct LibraryKernel<'a> {
handle: driver::CUkernel,
library: &'a Library,
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct KernelParamInfo {
pub offset: usize,
pub size: usize,
}
impl Library {
pub const unsafe fn from_raw(handle: driver::CUlibrary, ctx: Arc<Context>) -> Self {
Self { handle, ctx }
}
/// Returns the handle of the kernel with the given name located in this library.
/// If kernel handle is not found, the call returns [`ErrorCode::NotFound`].
pub fn kernel(&self, name: &str) -> Result<LibraryKernel<'_>> {
let c_name = CString::new(name)?;
let mut handle = ptr::null_mut();
self.ctx.bind()?;
unsafe {
try_cuda!(driver::cuLibraryGetKernel(
&raw mut handle,
self.handle,
c_name.as_ptr(),
))?;
}
if handle.is_null() {
return Err(Error::NullHandle);
}
Ok(LibraryKernel {
handle,
library: self,
})
}
/// Returns the number of kernels in this library.
pub fn kernel_count(&self) -> Result<usize> {
let mut count = 0;
self.ctx.bind()?;
unsafe {
try_cuda!(driver::cuLibraryGetKernelCount(&raw mut count, self.handle))?;
}
Ok(count as usize)
}
/// Returns the module handle associated with the current context located in this library.
/// If module handle is not found, the call returns [`ErrorCode::NotFound`].
pub fn module(&self) -> Result<Module> {
let mut handle = ptr::null_mut();
self.ctx.bind()?;
unsafe {
try_cuda!(driver::cuLibraryGetModule(&raw mut handle, self.handle))?;
}
if handle.is_null() {
return Err(Error::NullHandle);
}
Ok(unsafe { Module::from_borrowed_raw(handle, Arc::clone(&self.ctx)) })
}
/// Returns the base pointer and size of the global with the given name for the requested library and the current context.
/// If no global for the requested name exists, the call returns [`ErrorCode::NotFound`].
pub fn global(&self, name: &str) -> Result<LibraryGlobal<'_>> {
let c_name = CString::new(name)?;
let mut ptr = 0;
let mut size = 0;
self.ctx.bind()?;
unsafe {
try_cuda!(driver::cuLibraryGetGlobal(
&raw mut ptr,
&raw mut size,
self.handle,
c_name.as_ptr(),
))?;
}
Ok(LibraryGlobal {
ptr: ptr as *mut (),
size: size as usize,
_library: self,
})
}
/// Returns the base pointer and size of the managed memory with the given name for the requested library.
/// If no managed memory with the requested name exists, the call returns [`ErrorCode::NotFound`].
/// Note that managed memory for library library is shared across devices and is registered when the library is loaded into atleast one context.
pub fn managed(&self, name: &str) -> Result<LibraryGlobal<'_>> {
let c_name = CString::new(name)?;
let mut ptr = 0;
let mut size = 0;
self.ctx.bind()?;
unsafe {
try_cuda!(driver::cuLibraryGetManaged(
&raw mut ptr,
&raw mut size,
self.handle,
c_name.as_ptr(),
))?;
}
Ok(LibraryGlobal {
ptr: ptr as *mut (),
size: size as usize,
_library: self,
})
}
/// Returns the function pointer to a unified function denoted by symbol.
/// If no unified function with name symbol exists, the call returns [`ErrorCode::NotFound`].
/// If no device in the system supports unified function pointers, the call may return [`ErrorCode::NotFound`].
pub fn unified_function(&self, symbol: &str) -> Result<*mut ()> {
let c_symbol = CString::new(symbol)?;
let mut ptr = ptr::null_mut();
self.ctx.bind()?;
unsafe {
try_cuda!(driver::cuLibraryGetUnifiedFunction(
&raw mut ptr,
self.handle,
c_symbol.as_ptr(),
))?;
}
if ptr.is_null() {
return Err(Error::NullHandle);
}
Ok(ptr.cast())
}
pub const unsafe fn as_raw(&self) -> driver::CUlibrary {
self.handle
}
}
impl Drop for Library {
fn drop(&mut self) {
if let Err(err) = self.ctx.bind() {
#[cfg(debug_assertions)]
eprintln!("failed to bind context before unloading library: {err}");
return;
}
unsafe {
if let Err(err) = try_cuda!(driver::cuLibraryUnload(self.handle)) {
#[cfg(debug_assertions)]
eprintln!("failed to unload cuda library: {err}");
}
}
}
}
impl LibraryGlobal<'_> {
pub const fn as_ptr(&self) -> *mut () {
self.ptr
}
pub const fn size(&self) -> usize {
self.size
}
}
impl LibraryKernel<'_> {
pub fn name(&self) -> Result<String> {
kernel::name::<LibraryKernelHandle>(self.library.ctx.as_ref(), self.handle)
}
/// Returns the handle of the function for this kernel and the current context.
/// If function handle is not found, the call returns [`ErrorCode::NotFound`].
pub fn function(&self) -> Result<DeviceFunction> {
self.library.ctx.bind()?;
let mut handle = ptr::null_mut();
unsafe {
try_cuda!(driver::cuKernelGetFunction(&raw mut handle, self.handle))?;
}
if handle.is_null() {
return Err(Error::NullHandle);
}
Ok(handle.into())
}
pub fn add_to_graph(
&self,
graph: &mut Graph,
dependencies: &[GraphNode],
config: &LaunchConfig,
params: &mut KernelParameters,
) -> Result<GraphNode> {
let function = self.function()?;
let module = self.library.module()?;
let function = unsafe { KernelFunction::from_raw(function, &module) };
function.add_to_graph(graph, dependencies, config, params)
}
pub fn set_graph_node_params(
&self,
executable: &mut ExecutableGraph,
node: GraphNode,
config: &LaunchConfig,
params: &mut KernelParameters,
) -> Result<()> {
let function = self.function()?;
let module = self.library.module()?;
let function = unsafe { KernelFunction::from_raw(function, &module) };
function.set_graph_node_params(executable, node, config, params)
}
pub fn attribute(&self, attribute: FunctionAttribute) -> Result<i32> {
kernel::attribute::<LibraryKernelHandle>(self.library.ctx.as_ref(), self.handle, attribute)
}
pub fn set_attribute(&self, attribute: FunctionAttribute, value: i32) -> Result<()> {
kernel::set_attribute::<LibraryKernelHandle>(
self.library.ctx.as_ref(),
self.handle,
attribute,
value,
)
}
/// On devices where the L1 cache and shared memory use the same hardware resources, this sets through config the preferred cache configuration for the device kernel kernel on the requested device dev.
/// This is only a preference.
/// The driver will use the requested configuration if possible, but it is free to choose a different configuration if required to execute kernel.
/// Any context-wide preference set via [`sys::cuCtxSetCacheConfig`](singe_cuda_sys::driver::cuCtxSetCacheConfig) will be overridden by this per-kernel setting.
///
/// Note that attributes set using [`sys::cuFuncSetCacheConfig`](singe_cuda_sys::driver::cuFuncSetCacheConfig) will override the attribute set by this API irrespective of whether the call to [`sys::cuFuncSetCacheConfig`](singe_cuda_sys::driver::cuFuncSetCacheConfig) is made before or after this API call.
///
/// This setting does nothing on devices where the size of the L1 cache and shared memory are fixed.
///
/// Launching a kernel with a different preference than the most recent preference setting may insert a device-side synchronization point.
///
/// The supported cache configurations are:
///
/// * [`FunctionCache::PreferNone`]: no preference for shared memory or L1 (default)
/// * [`FunctionCache::PreferShared`]: prefer larger shared memory and smaller L1 cache
/// * [`FunctionCache::PreferL1`]: prefer larger L1 cache and smaller shared memory
/// * [`FunctionCache::PreferEqual`]: prefer equal sized L1 cache and shared memory
///
/// Note:
///
/// The API has stricter locking requirements in comparison to its legacy counterpart [`sys::cuFuncSetCacheConfig`](singe_cuda_sys::driver::cuFuncSetCacheConfig) due to device-wide semantics.
/// If multiple threads are trying to set a config on the same device simultaneously, the cache config setting will depend on the interleavings chosen by the OS scheduler and memory consistency.
pub fn set_cache_config(&self, config: FunctionCache) -> Result<()> {
self.library.ctx.bind()?;
unsafe {
try_cuda!(driver::cuKernelSetCacheConfig(
self.handle,
config.into(),
self.library.ctx.device().id() as _,
))?;
}
Ok(())
}
/// Queries the kernel parameter at the given index, returning the offset and size where the parameter will reside in the device-side parameter layout.
/// This information can be used to update kernel node parameters from the device. The index must be less than the number of parameters that the kernel takes.
///
/// Note:
///
/// Note that this function may also return error codes from previous, asynchronous launches.
pub fn param_info(&self, index: usize) -> Result<KernelParamInfo> {
self.library.ctx.bind()?;
let mut offset = 0;
let mut size = 0;
unsafe {
try_cuda!(driver::cuKernelGetParamInfo(
self.handle,
index as _,
&raw mut offset,
&raw mut size,
))?;
}
Ok(KernelParamInfo {
offset: offset as usize,
size: size as usize,
})
}
pub const unsafe fn as_raw(&self) -> driver::CUkernel {
self.handle
}
}