singe-cutensor 0.1.0-alpha.7

Safe Rust wrappers for NVIDIA cuTENSOR library.
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
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
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
use std::{
    mem::{ManuallyDrop, MaybeUninit},
    ptr,
};

use singe_cuda::memory::DeviceMemory;
use singe_cutensor_sys as sys;

use crate::{
    error::{Error, Result},
    mp::{
        context::{Context, ContextRef, validate_same_context},
        memory::WorkspaceMemory,
        tensor::TensorDescriptor,
        types::{Algorithm, PlanAttribute},
    },
    operation::ComputeDescriptor,
    try_ffi,
    types::{Mode, Operator},
    utility::modes_to_i32_vec,
};

#[derive(Debug)]
pub struct OperationDescriptor<'comm> {
    handle: sys::cutensorMpOperationDescriptor_t,
    context: ContextRef<'comm>,
}

#[derive(Debug)]
pub struct PlanPreference<'comm> {
    handle: sys::cutensorMpPlanPreference_t,
    context: ContextRef<'comm>,
    algorithm: Algorithm,
    device_workspace_limit: u64,
    host_workspace_limit: u64,
}

#[derive(Debug)]
pub struct Plan<'comm> {
    handle: sys::cutensorMpPlan_t,
    context: ContextRef<'comm>,
}

#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct Workspace {
    device_size: u64,
    host_size: u64,
}

impl<'comm> OperationDescriptor<'comm> {
    pub fn create_contraction(
        context: &Context<'comm>,
        a: &TensorDescriptor<'comm>,
        modes_a: &[Mode],
        op_a: Operator,
        b: &TensorDescriptor<'comm>,
        modes_b: &[Mode],
        op_b: Operator,
        c: &TensorDescriptor<'comm>,
        modes_c: &[Mode],
        op_c: Operator,
        d: &TensorDescriptor<'comm>,
        modes_d: &[Mode],
        compute: ComputeDescriptor,
    ) -> Result<Self> {
        let context_ref = context.as_context_ref();
        validate_same_context(&context_ref, a.context(), "a")?;
        validate_same_context(&context_ref, b.context(), "b")?;
        validate_same_context(&context_ref, c.context(), "c")?;
        validate_same_context(&context_ref, d.context(), "d")?;
        validate_modes(a, modes_a)?;
        validate_modes(b, modes_b)?;
        validate_modes(c, modes_c)?;
        validate_modes(d, modes_d)?;

        let modes_a = modes_to_i32_vec(modes_a);
        let modes_b = modes_to_i32_vec(modes_b);
        let modes_c = modes_to_i32_vec(modes_c);
        let modes_d = modes_to_i32_vec(modes_d);
        let mut handle = ptr::null_mut();
        context.bind()?;
        unsafe {
            try_ffi!(sys::cutensorMpCreateContraction(
                context.as_raw(),
                &raw mut handle,
                a.as_raw(),
                modes_a.as_ptr(),
                op_a.into(),
                b.as_raw(),
                modes_b.as_ptr(),
                op_b.into(),
                c.as_raw(),
                modes_c.as_ptr(),
                op_c.into(),
                d.as_raw(),
                modes_d.as_ptr(),
                compute.as_raw(),
            ))?;
        }

        if handle.is_null() {
            return Err(Error::NullHandle);
        }

        Ok(Self {
            handle,
            context: context.as_context_ref(),
        })
    }

    /// Wraps an existing cuTENSORMp operation descriptor.
    ///
    /// # Safety
    ///
    /// `handle` must be a valid cuTENSORMp operation descriptor associated with
    /// `context`. The returned value takes ownership of `handle` and destroys
    /// it on drop.
    pub unsafe fn from_raw(
        handle: sys::cutensorMpOperationDescriptor_t,
        context: &Context<'comm>,
    ) -> Result<Self> {
        if handle.is_null() {
            return Err(Error::NullHandle);
        }

        Ok(Self {
            handle,
            context: context.as_context_ref(),
        })
    }

    pub(crate) fn context(&self) -> &ContextRef<'comm> {
        &self.context
    }

    pub const fn as_raw(&self) -> sys::cutensorMpOperationDescriptor_t {
        self.handle
    }

    /// Consumes this descriptor and returns the owned raw cuTENSORMp operation descriptor.
    ///
    /// The caller becomes responsible for destroying the descriptor.
    pub fn into_raw(self) -> sys::cutensorMpOperationDescriptor_t {
        let this = ManuallyDrop::new(self);
        this.handle
    }
}

impl<'comm> PlanPreference<'comm> {
    pub fn create(
        context: &Context<'comm>,
        algorithm: Algorithm,
        device_workspace_limit: u64,
        host_workspace_limit: u64,
    ) -> Result<Self> {
        let mut handle = ptr::null_mut();
        context.bind()?;
        unsafe {
            try_ffi!(sys::cutensorMpCreatePlanPreference(
                context.as_raw(),
                &raw mut handle,
                algorithm.into(),
                device_workspace_limit,
                host_workspace_limit,
            ))?;
        }

        if handle.is_null() {
            return Err(Error::NullHandle);
        }

        Ok(Self {
            handle,
            context: context.as_context_ref(),
            algorithm,
            device_workspace_limit,
            host_workspace_limit,
        })
    }

    /// Wraps an existing cuTENSORMp plan preference.
    ///
    /// # Safety
    ///
    /// `handle` must be a valid cuTENSORMp plan preference associated with
    /// `context`. Metadata arguments must describe the raw preference. The
    /// returned value takes ownership of `handle` and destroys it on drop.
    pub unsafe fn from_raw(
        handle: sys::cutensorMpPlanPreference_t,
        context: &Context<'comm>,
        algorithm: Algorithm,
        device_workspace_limit: u64,
        host_workspace_limit: u64,
    ) -> Result<Self> {
        if handle.is_null() {
            return Err(Error::NullHandle);
        }

        Ok(Self {
            handle,
            context: context.as_context_ref(),
            algorithm,
            device_workspace_limit,
            host_workspace_limit,
        })
    }

    pub fn algorithm(&self) -> Algorithm {
        self.algorithm
    }

    pub fn device_workspace_limit(&self) -> u64 {
        self.device_workspace_limit
    }

    pub fn host_workspace_limit(&self) -> u64 {
        self.host_workspace_limit
    }

    pub(crate) fn context(&self) -> &ContextRef<'comm> {
        &self.context
    }

    pub const fn as_raw(&self) -> sys::cutensorMpPlanPreference_t {
        self.handle
    }

    /// Consumes this preference and returns the owned raw cuTENSORMp plan preference.
    ///
    /// The caller becomes responsible for destroying the preference.
    pub fn into_raw(self) -> sys::cutensorMpPlanPreference_t {
        let this = ManuallyDrop::new(self);
        this.handle
    }
}

impl<'comm> Plan<'comm> {
    pub fn create(
        context: &Context<'comm>,
        desc: &OperationDescriptor<'comm>,
        preference: Option<&PlanPreference<'comm>>,
    ) -> Result<Self> {
        let context_ref = context.as_context_ref();
        validate_same_context(&context_ref, desc.context(), "desc")?;
        if let Some(preference) = preference {
            validate_same_context(&context_ref, preference.context(), "preference")?;
        }

        let mut handle = ptr::null_mut();
        context.bind()?;
        unsafe {
            try_ffi!(sys::cutensorMpCreatePlan(
                context.as_raw(),
                &raw mut handle,
                desc.as_raw(),
                preference.map_or(ptr::null_mut(), |preference| preference.as_raw()),
            ))?;
        }

        if handle.is_null() {
            return Err(Error::NullHandle);
        }

        Ok(Self {
            handle,
            context: context.as_context_ref(),
        })
    }

    /// Wraps an existing cuTENSORMp plan.
    ///
    /// # Safety
    ///
    /// `handle` must be a valid cuTENSORMp plan associated with `context`. The
    /// returned value takes ownership of `handle` and destroys it on drop.
    pub unsafe fn from_raw(
        handle: sys::cutensorMpPlan_t,
        context: &Context<'comm>,
    ) -> Result<Self> {
        if handle.is_null() {
            return Err(Error::NullHandle);
        }

        Ok(Self {
            handle,
            context: context.as_context_ref(),
        })
    }

    pub fn workspace(&self) -> Result<Workspace> {
        Ok(Workspace {
            device_size: self.attribute(PlanAttribute::RequiredWorkspaceDevice)?,
            host_size: self.attribute(PlanAttribute::RequiredWorkspaceHost)?,
        })
    }

    pub fn create_workspace_memory(&self) -> Result<WorkspaceMemory> {
        WorkspaceMemory::create(self.workspace()?)
    }

    pub fn contract<TA, TB, TC, TD, TScalar>(
        &self,
        alpha: &TScalar,
        a: &DeviceMemory<TA>,
        b: &DeviceMemory<TB>,
        beta: &TScalar,
        c: &DeviceMemory<TC>,
        d: &mut DeviceMemory<TD>,
        workspace: &mut WorkspaceMemory,
    ) -> Result<()> {
        unsafe {
            self.contract_raw(
                ptr::from_ref(alpha).cast(),
                a.as_ptr().cast(),
                b.as_ptr().cast(),
                ptr::from_ref(beta).cast(),
                c.as_ptr().cast(),
                d.as_mut_ptr().cast(),
                workspace.device_mut_ptr(),
                workspace.host_mut_ptr(),
            )
        }
    }

    pub fn contract_in_place<TA, TB, TC, TScalar>(
        &self,
        alpha: &TScalar,
        a: &DeviceMemory<TA>,
        b: &DeviceMemory<TB>,
        beta: &TScalar,
        c_and_d: &mut DeviceMemory<TC>,
        workspace: &mut WorkspaceMemory,
    ) -> Result<()> {
        unsafe {
            self.contract_raw(
                ptr::from_ref(alpha).cast(),
                a.as_ptr().cast(),
                b.as_ptr().cast(),
                ptr::from_ref(beta).cast(),
                c_and_d.as_ptr().cast(),
                c_and_d.as_mut_ptr().cast(),
                workspace.device_mut_ptr(),
                workspace.host_mut_ptr(),
            )
        }
    }

    /// Executes this distributed contraction with raw local tensor pointers.
    ///
    /// # Safety
    ///
    /// Pointers must refer to the local rank's tensor shards and workspaces
    /// matching the descriptors and plan. Scalars must have the type expected by
    /// cuTENSORMp for the data-type combination. All pointers must remain valid
    /// for the duration of the launched operation, and `d`, `device_workspace`,
    /// and `host_workspace` must be writable according to the plan's workspace
    /// requirements.
    pub unsafe fn contract_raw(
        &self,
        alpha: *const (),
        a: *const (),
        b: *const (),
        beta: *const (),
        c: *const (),
        d: *mut (),
        device_workspace: *mut (),
        host_workspace: *mut (),
    ) -> Result<()> {
        self.context.bind()?;
        unsafe {
            try_ffi!(sys::cutensorMpContract(
                self.context.as_raw(),
                self.handle,
                alpha.cast(),
                a.cast(),
                b.cast(),
                beta.cast(),
                c.cast(),
                d.cast(),
                device_workspace.cast(),
                host_workspace.cast(),
            ))?;
        }
        Ok(())
    }

    pub fn as_raw(&self) -> sys::cutensorMpPlan_t {
        self.handle
    }

    /// Consumes this plan and returns the owned raw cuTENSORMp plan.
    ///
    /// The caller becomes responsible for destroying the plan.
    pub fn into_raw(self) -> sys::cutensorMpPlan_t {
        let this = ManuallyDrop::new(self);
        this.handle
    }

    fn attribute<T: Copy>(&self, attr: PlanAttribute) -> Result<T> {
        let mut value = MaybeUninit::<T>::uninit();
        self.context.bind()?;
        unsafe {
            try_ffi!(sys::cutensorMpPlanGetAttribute(
                self.context.as_raw(),
                self.handle,
                attr.into(),
                value.as_mut_ptr().cast(),
                size_of::<T>() as u64,
            ))?;
            Ok(value.assume_init())
        }
    }
}

impl Workspace {
    pub fn device_size(&self) -> u64 {
        self.device_size
    }

    pub fn host_size(&self) -> u64 {
        self.host_size
    }
}

impl Drop for OperationDescriptor<'_> {
    fn drop(&mut self) {
        if let Err(err) = self.context.bind() {
            #[cfg(debug_assertions)]
            eprintln!(
                "failed to bind cutensormp context before destroying operation descriptor: {err}"
            );
        }

        unsafe {
            if let Err(err) = try_ffi!(sys::cutensorMpDestroyOperationDescriptor(self.handle)) {
                #[cfg(debug_assertions)]
                eprintln!("failed to destroy cutensormp operation descriptor: {err}");
            }
        }
    }
}

impl Drop for PlanPreference<'_> {
    fn drop(&mut self) {
        if let Err(err) = self.context.bind() {
            #[cfg(debug_assertions)]
            eprintln!("failed to bind cutensormp context before destroying plan preference: {err}");
        }

        unsafe {
            if let Err(err) = try_ffi!(sys::cutensorMpDestroyPlanPreference(self.handle)) {
                #[cfg(debug_assertions)]
                eprintln!("failed to destroy cutensormp plan preference: {err}");
            }
        }
    }
}

impl Drop for Plan<'_> {
    fn drop(&mut self) {
        if let Err(err) = self.context.bind() {
            #[cfg(debug_assertions)]
            eprintln!("failed to bind cutensormp context before destroying plan: {err}");
        }

        unsafe {
            if let Err(err) = try_ffi!(sys::cutensorMpDestroyPlan(self.handle)) {
                #[cfg(debug_assertions)]
                eprintln!("failed to destroy cutensormp plan: {err}");
            }
        }
    }
}

fn validate_modes(desc: &TensorDescriptor<'_>, modes: &[Mode]) -> Result<()> {
    if desc.rank() as usize != modes.len() {
        return Err(Error::TensorModeMismatch {
            rank: desc.rank(),
            mode_length: modes.len(),
        });
    }
    Ok(())
}