hpt 0.1.3

High Performance Tensor (HPT) - A fast, efficient, and user-friendly tensor computation library for Rust
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
use cudarc::driver::{DeviceRepr, LaunchAsync, LaunchConfig};
use hpt_allocator::{
    traits::{Allocator, AllocatorOutputRetrive},
    Cuda,
};
use hpt_common::error::{base::TensorError, shape::ShapeError};
use hpt_cudakernels::SOFTMAX;
use hpt_traits::{
    ops::creation::TensorCreator,
    tensor::{CommonBounds, TensorInfo},
};
use hpt_types::{
    dtype::CudaType,
    into_scalar::Cast,
    type_promote::{FloatOutBinary, FloatOutUnary, FloatOutUnaryPromote, NormalOut},
};

use crate::{
    backends::{
        common::reduce::rearrange_array,
        cuda::cuda_utils::{check_launch_config, load_ptx_and_get_data},
    },
    tensor_base::_Tensor,
};
use hpt_traits::ops::shape_manipulate::ShapeManipulate;

pub(crate) fn calculate_best_block_size_y_warp(kernel: &cudarc::driver::CudaFunction) -> u32 {
    let block_size_y = [1, 2, 4];
    let mut max_active_blocks = 0;
    let mut best_block_size_y = 0;
    for block_size_y in block_size_y {
        let size = 32 * block_size_y;
        let max = kernel
            .occupancy_max_active_blocks_per_multiprocessor(size, 0, None)
            .expect("occupancy failed");
        if max >= max_active_blocks {
            max_active_blocks = max;
            best_block_size_y = block_size_y;
        }
    }
    best_block_size_y
}

pub(crate) fn normalize_prepare<T: CommonBounds, O: CommonBounds, const DEVICE: usize, A>(
    a: &_Tensor<T, Cuda, DEVICE, A>,
    axis: usize,
    c: Option<_Tensor<O, Cuda, DEVICE, A>>,
) -> std::result::Result<
    (
        _Tensor<T, Cuda, DEVICE, A>,
        _Tensor<O, Cuda, DEVICE, A>,
        Vec<usize>,
    ),
    TensorError,
>
where
    A: Allocator + Send + Sync,
    A::Output: AllocatorOutputRetrive,
    T: CudaType + DeviceRepr,
    O: CudaType + DeviceRepr,
{
    // get permute order, we move to_reduce axes to the end
    let mut transposed_axis = rearrange_array(a.ndim(), &[axis]);

    // sort the transposed axis based on the stride, ordering the axis can increase the cpu cache hitting rate when we do iteration
    transposed_axis[..a.ndim() - 1].sort_by(|x, y| a.strides()[*y].cmp(&a.strides()[*x]));
    transposed_axis[a.ndim() - 1..].sort_by(|x, y| a.strides()[*y].cmp(&a.strides()[*x]));

    let res = if let Some(out) = c {
        // we need a better logic to verify the out is valid.
        // we need to get the real size and compare the real size with the res_shape
        ShapeError::check_inplace_out_layout_valid(a.shape(), out.layout())?;
        Ok(out)
    } else {
        _Tensor::<O, Cuda, DEVICE, A>::empty(a.shape())
    };
    Ok((
        a.permute(&transposed_axis)?,
        res?.permute(&transposed_axis)?,
        transposed_axis,
    ))
}

#[track_caller]
pub(crate) fn contiguous_softmax<T, O, const DEVICE: usize, A>(
    a: &_Tensor<T, Cuda, DEVICE, A>,
    axis: i64,
    c: Option<_Tensor<O, Cuda, DEVICE, A>>,
    is_log_softmax: bool,
) -> Result<_Tensor<O, Cuda, DEVICE, A>, TensorError>
where
    T: CommonBounds + Cast<O> + FloatOutUnary<Output = O> + CudaType + DeviceRepr,
    O: CommonBounds + NormalOut<T, Output = O> + FloatOutUnary<Output = O> + CudaType + DeviceRepr,
    <T as FloatOutUnaryPromote>::Intermediate: DeviceRepr,
    T::Vec: FloatOutUnary<Output = O::Vec>,
    O::Vec: FloatOutBinary<Output = O::Vec>,
    A: Allocator + Send + Sync,
    A::Output: AllocatorOutputRetrive,
{
    let axis = (if axis < 0 {
        axis + (a.ndim() as i64)
    } else {
        axis
    }) as usize;
    let (transposed_tensor, res, transposed_axis) = normalize_prepare(a, axis, c)?;

    let a_last_stride = transposed_tensor.strides()[a.ndim() - 1];
    let inner_loop_size = transposed_tensor.shape()[a.ndim() - 1] as i32;
    let outer_loop_size = transposed_tensor.shape()[..a.ndim() - 1]
        .iter()
        .product::<i64>();
    let op_name = if is_log_softmax {
        "logsoftmax"
    } else {
        "softmax"
    };
    if inner_loop_size <= 1024 {
        let (kernel, _) = load_ptx_and_get_data(
            op_name,
            &if a_last_stride == 1 {
                format!("{}_{op_name}_warp", T::STR)
            } else {
                format!("{}_{op_name}_warp_uncontiguous", T::STR)
            },
            res.device(),
            res.device_cap(),
            &SOFTMAX,
        )
        .expect("load softmax kernel failed");
        let best_block_size_y = calculate_best_block_size_y_warp(&kernel);
        let cfg = LaunchConfig {
            grid_dim: (
                1,
                ((outer_loop_size as u32 + best_block_size_y - 1) / best_block_size_y)
                    .min(u16::MAX as u32),
                1,
            ),
            block_dim: (32, best_block_size_y, 1),
            shared_mem_bytes: 0,
        };
        check_launch_config(res.device(), &cfg)?;
        if a_last_stride == 1 {
            let inp_slice = a.cuda_slice();
            let out_slice = res.cuda_slice();
            unsafe {
                kernel
                    .launch(
                        cfg,
                        (
                            inp_slice,
                            out_slice,
                            outer_loop_size as i32,
                            inner_loop_size,
                        ),
                    )
                    .expect("launch softmax kernel failed");
            }
        } else {
            let inp_slice = transposed_tensor.cuda_slice();
            let out_slice = res.cuda_slice();
            let divmod = transposed_tensor.cuda_divmod()?;
            let strides = transposed_tensor.cuda_strides_i32()?;
            let ndim = transposed_tensor.ndim() as i32;
            let out_divmod = res.cuda_divmod()?;
            let out_strides = res.cuda_strides_i32()?;
            let out_ndim = res.ndim() as i32;
            unsafe {
                kernel
                    .launch(
                        cfg,
                        (
                            inp_slice,
                            out_slice,
                            outer_loop_size as i32,
                            inner_loop_size,
                            &divmod,
                            &strides,
                            ndim,
                            &out_divmod,
                            &out_strides,
                            out_ndim,
                        ),
                    )
                    .expect("launch softmax kernel failed");
            }
        }
    } else if inner_loop_size <= 1024 * 4 {
        let (kernel, _) = load_ptx_and_get_data(
            op_name,
            &if a_last_stride == 1 {
                format!("{}_{op_name}_block", T::STR)
            } else {
                format!("{}_{op_name}_block_uncontiguous", T::STR)
            },
            res.device(),
            res.device_cap(),
            &SOFTMAX,
        )
        .expect("load softmax kernel failed");
        let cfg = LaunchConfig {
            grid_dim: (1, (outer_loop_size as u32).min(u16::MAX as u32), 1),
            block_dim: (1024, 1, 1),
            shared_mem_bytes: inner_loop_size as u32
                * std::mem::size_of::<<T as FloatOutUnaryPromote>::Intermediate>() as u32,
        };
        check_launch_config(res.device(), &cfg)?;
        if a_last_stride == 1 {
            let inp_slice = a.cuda_slice();
            let out_slice = res.cuda_slice();
            unsafe {
                kernel
                    .launch(
                        cfg,
                        (
                            inp_slice,
                            out_slice,
                            outer_loop_size as i32,
                            inner_loop_size,
                        ),
                    )
                    .expect("launch softmax kernel failed");
            }
        } else {
            let inp_slice = transposed_tensor.cuda_slice();
            let out_slice = res.cuda_slice();
            let divmod = transposed_tensor.cuda_divmod()?;
            let strides = transposed_tensor.cuda_strides_i32()?;
            let ndim = transposed_tensor.ndim() as i32;
            let out_divmod = res.cuda_divmod()?;
            let out_strides = res.cuda_strides_i32()?;
            let out_ndim = res.ndim() as i32;
            unsafe {
                kernel
                    .launch(
                        cfg,
                        (
                            inp_slice,
                            out_slice,
                            outer_loop_size as i32,
                            inner_loop_size,
                            &divmod,
                            &strides,
                            ndim,
                            &out_divmod,
                            &out_strides,
                            out_ndim,
                        ),
                    )
                    .expect("launch softmax kernel failed");
            }
        }
    } else {
        let (kernel, _) = load_ptx_and_get_data(
            op_name,
            &if a_last_stride == 1 {
                format!("{}_{op_name}_block_large", T::STR)
            } else {
                format!("{}_{op_name}_block_large_uncontiguous", T::STR)
            },
            res.device(),
            res.device_cap(),
            &SOFTMAX,
        )
        .expect("load softmax kernel failed");
        let cfg = LaunchConfig {
            grid_dim: (1, (outer_loop_size as u32).min(u16::MAX as u32), 1),
            block_dim: (1024, 1, 1),
            shared_mem_bytes: 0,
        };
        check_launch_config(res.device(), &cfg)?;
        if a_last_stride == 1 {
            let inp_slice = a.cuda_slice();
            let out_slice = res.cuda_slice();
            let buffer = unsafe {
                res.device()
                    .alloc::<<T as FloatOutUnaryPromote>::Intermediate>(
                        inner_loop_size as usize * cfg.grid_dim.1 as usize,
                    )
            }?;
            unsafe {
                kernel
                    .launch(
                        cfg,
                        (
                            inp_slice,
                            out_slice,
                            &buffer,
                            outer_loop_size as i32,
                            inner_loop_size,
                        ),
                    )
                    .expect("launch softmax kernel failed");
            }
        } else {
            let inp_slice = transposed_tensor.cuda_slice();
            let out_slice = res.cuda_slice();
            let buffer = unsafe {
                res.device()
                    .alloc::<<T as FloatOutUnaryPromote>::Intermediate>(
                        inner_loop_size as usize * cfg.grid_dim.1 as usize,
                    )
            }?;
            let divmod = transposed_tensor.cuda_divmod()?;
            let strides = transposed_tensor.cuda_strides_i32()?;
            let ndim = transposed_tensor.ndim() as i32;
            let out_divmod = res.cuda_divmod()?;
            let out_strides = res.cuda_strides_i32()?;
            let out_ndim = res.ndim() as i32;
            unsafe {
                kernel
                    .launch(
                        cfg,
                        (
                            inp_slice,
                            out_slice,
                            &buffer,
                            outer_loop_size as i32,
                            inner_loop_size,
                            &divmod,
                            &strides,
                            ndim,
                            &out_divmod,
                            &out_strides,
                            out_ndim,
                        ),
                    )
                    .expect("launch softmax kernel failed");
            }
        }
    }
    res.permute_inv(&transposed_axis)
}

#[track_caller]
pub(crate) fn uncontiguous_softmax<T, O, const DEVICE: usize, A>(
    a: &_Tensor<T, Cuda, DEVICE, A>,
    axis: i64,
    c: Option<_Tensor<O, Cuda, DEVICE, A>>,
    is_log_softmax: bool,
) -> Result<_Tensor<O, Cuda, DEVICE, A>, TensorError>
where
    T: CommonBounds + Cast<O> + FloatOutUnary<Output = O> + CudaType + DeviceRepr,
    O: CommonBounds + NormalOut<T, Output = O> + FloatOutUnary<Output = O> + CudaType + DeviceRepr,
    T::Vec: FloatOutUnary<Output = O::Vec>,
    O::Vec: FloatOutBinary<Output = O::Vec>,
    A: Allocator + Send + Sync,
    A::Output: AllocatorOutputRetrive,
{
    let axis = (if axis < 0 {
        axis + (a.ndim() as i64)
    } else {
        axis
    }) as usize;
    let (transposed_tensor, res, transposed_axis) = normalize_prepare(a, axis, c)?;

    let a_last_stride = transposed_tensor.strides()[a.ndim() - 1];
    let inner_loop_size = transposed_tensor.shape()[a.ndim() - 1] as i32;
    assert_eq!(a_last_stride, 1);
    let outer_loop_size = transposed_tensor.shape()[..a.ndim() - 1]
        .iter()
        .product::<i64>();
    let op_name = if is_log_softmax {
        "logsoftmax"
    } else {
        "softmax"
    };
    if inner_loop_size <= 1024 {
        let (kernel, _) = load_ptx_and_get_data(
            op_name,
            &format!("{}_{op_name}_warp_uncontiguous", T::STR),
            res.device(),
            res.device_cap(),
            &SOFTMAX,
        )
        .expect("load softmax kernel failed");

        let cfg = LaunchConfig {
            grid_dim: (1, (outer_loop_size as u32).min(u16::MAX as u32), 1),
            block_dim: (32, 1, 1),
            shared_mem_bytes: inner_loop_size as u32 * std::mem::size_of::<O>() as u32
                + inner_loop_size as u32 * std::mem::size_of::<T>() as u32,
        };
        check_launch_config(res.device(), &cfg)?;
        let inp_slice = a.cuda_slice();
        let out_slice = res.cuda_slice();
        let divmod = transposed_tensor.cuda_divmod()?;
        let strides = transposed_tensor.cuda_strides_i32()?;
        let ndim = transposed_tensor.ndim();
        unsafe {
            kernel
                .launch(
                    cfg,
                    (
                        inp_slice,
                        out_slice,
                        outer_loop_size as i32,
                        inner_loop_size,
                        &divmod,
                        &strides,
                        ndim as i32,
                    ),
                )
                .expect("launch softmax kernel failed");
        }
    } else if inner_loop_size <= 1024 * 4 {
        let (kernel, _) = load_ptx_and_get_data(
            op_name,
            &format!("{}_{op_name}_block_uncontiguous", T::STR),
            res.device(),
            res.device_cap(),
            &SOFTMAX,
        )
        .expect("load softmax kernel failed");
        let cfg = LaunchConfig {
            grid_dim: (1, (outer_loop_size as u32).min(u16::MAX as u32), 1),
            block_dim: (1024, 1, 1),
            shared_mem_bytes: inner_loop_size as u32 * std::mem::size_of::<O>() as u32,
        };
        check_launch_config(res.device(), &cfg)?;
        let inp_slice = a.cuda_slice();
        let out_slice = res.cuda_slice();
        let divmod = transposed_tensor.cuda_divmod()?;
        let strides = transposed_tensor.cuda_strides_i32()?;
        let ndim = transposed_tensor.ndim();
        unsafe {
            kernel
                .launch(
                    cfg,
                    (
                        inp_slice,
                        out_slice,
                        outer_loop_size as i32,
                        inner_loop_size,
                        &divmod,
                        &strides,
                        ndim as i32,
                    ),
                )
                .expect("launch softmax kernel failed");
        }
    } else {
        let (kernel, _) = load_ptx_and_get_data(
            op_name,
            &format!("{}_{op_name}_block_large_uncontiguous", T::STR),
            res.device(),
            res.device_cap(),
            &SOFTMAX,
        )
        .expect("load softmax kernel failed");
        let cfg = LaunchConfig {
            grid_dim: (1, (outer_loop_size as u32).min(u16::MAX as u32), 1),
            block_dim: (1024, 1, 1),
            shared_mem_bytes: 0,
        };
        check_launch_config(res.device(), &cfg)?;
        let inp_slice = a.cuda_slice();
        let out_slice = res.cuda_slice();
        let buffer = unsafe { res.device().alloc::<T>(inner_loop_size as usize) }?;
        let divmod = transposed_tensor.cuda_divmod()?;
        let strides = transposed_tensor.cuda_strides_i32()?;
        let ndim = transposed_tensor.ndim();
        unsafe {
            kernel
                .launch(
                    cfg,
                    (
                        inp_slice,
                        out_slice,
                        &buffer,
                        outer_loop_size as i32,
                        inner_loop_size,
                        &divmod,
                        &strides,
                        ndim as i32,
                    ),
                )
                .expect("launch softmax kernel failed");
        }
    }
    res.permute_inv(&transposed_axis)
}