softmax_fast.h 27 KB
Newer Older
Guolin Ke's avatar
Guolin Ke committed
1
2
3
4
5
6
7
8
#pragma once
#include <iostream>
#include <type_traits>
#include <limits>
#include <cuda.h>
#include <cuda_fp16.h>
#include <cuda_bf16.h>
#include <curand_kernel.h>
9
#include <cub/cub.cuh>
Guolin Ke's avatar
Guolin Ke committed
10
11
12
#include "util.h"

template <int N>
13
14
15
16
using IntegerBits = typename std::conditional<N <= 8, uint8_t,
                                              typename std::conditional<N <= 16, uint16_t,
                                                                        typename std::conditional<N <= 32, uint32_t,
                                                                                                  typename std::conditional<N <= 64, uint64_t, void>::type>::type>::type>::type;
Guolin Ke's avatar
Guolin Ke committed
17
18

template <int LogElements>
19
20
struct SoftmaxParameters
{
Guolin Ke's avatar
Guolin Ke committed
21
22
23
24
25
26
27
28
29
    static_assert(LogElements <= 11, "");
    static constexpr int Elements = 1 << LogElements;
    static constexpr int WarpBatch = Elements <= 128 ? 2 : 1;
    static constexpr int WarpIterations = Elements <= 32 ? 1 : Elements / 32;
    using MaskType = IntegerBits<WarpIterations>;
    static constexpr int WarpSize = Elements <= 32 ? Elements : 32;
    static constexpr int MaskStride = WarpSize;
};

30
31
inline int log2_ceil(int value)
{
Guolin Ke's avatar
Guolin Ke committed
32
    int log2_value = 0;
33
34
    while ((1 << log2_value) < value)
        ++log2_value;
Guolin Ke's avatar
Guolin Ke committed
35
36
37
    return log2_value;
}

38
39
40
41
inline at::ScalarType softmax_mask_dtype(int elements)
{
    if (elements > 1024)
    {
Guolin Ke's avatar
Guolin Ke committed
42
        return torch::kInt64;
43
44
45
    }
    else if (elements > 512)
    {
Guolin Ke's avatar
Guolin Ke committed
46
        return torch::kInt32;
47
48
49
    }
    else if (elements > 256)
    {
Guolin Ke's avatar
Guolin Ke committed
50
51
52
53
54
        return torch::kInt16;
    }
    return torch::kInt8;
}

55
56
inline int softmax_mask_size(int batch_size, int elements)
{
Guolin Ke's avatar
Guolin Ke committed
57
58
59
60
61
62
    int log2_elements = log2_ceil(elements);
    int e = 1 << log2_elements;
    int warp_size = e < 32 ? e : 32;
    return batch_size * warp_size;
}

63
64
inline int softmax_rng_delta_offset(int elements)
{
Guolin Ke's avatar
Guolin Ke committed
65
66
67
68
69
70
71
    int log2_elements = log2_ceil(elements);
    int e = 1 << log2_elements;
    int warp_iterations = e <= 32 ? 1 : e / 32;
    int warp_batch = e <= 128 ? 2 : 1;
    return warp_iterations * warp_batch;
}

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

inline cudaError_t GetNumBlocks(int64_t block_size, int64_t max_blocks, int64_t waves,
                                int *num_blocks) {
    int dev;
    {
        cudaError_t err = cudaGetDevice(&dev);
        if (err != cudaSuccess) {
            return err;
        }
    }
    int sm_count;
    {
        cudaError_t err = cudaDeviceGetAttribute(&sm_count, cudaDevAttrMultiProcessorCount, dev);
        if (err != cudaSuccess) {
            return err;
        }
    }
    int tpm;
    {
        cudaError_t err = cudaDeviceGetAttribute(&tpm, cudaDevAttrMaxThreadsPerMultiProcessor, dev);
        if (err != cudaSuccess) {
            return err;
        }
    }
    *num_blocks =
        std::max<int>(1, std::min<int64_t>(max_blocks, sm_count * tpm / block_size * waves));
    return cudaSuccess;
}

template <typename T>
struct SumOp {
    __device__ __forceinline__ T operator()(const T &a, const T &b) const { return a + b; }
};

template <typename T>
struct MaxOp {
    __device__ __forceinline__ T operator()(const T &a, const T &b) const { return max(a, b); }
};

template <template <typename> class ReductionOp, typename T, int block_size>
__inline__ __device__ T BlockAllReduce(T val) {
    typedef cub::BlockReduce<T, block_size> BlockReduce;
    __shared__ typename BlockReduce::TempStorage temp_storage;
    __shared__ T result_broadcast;
    T result = BlockReduce(temp_storage).Reduce(val, ReductionOp<T>());
    if (threadIdx.x == 0) {
        result_broadcast = result;
    }
    __syncthreads();
    return result_broadcast;
}

// modified from https://github.com/Oneflow-Inc/oneflow/blob/5d74efa4d07adfd0acbc8e0074778687f1006b86/oneflow/core/cuda/softmax.cuh#L480-L529
// Copyright 2020 The OneFlow Authors. All rights reserved.
template <typename input_t, typename output_t, typename acc_t, int block_size, bool NeedBias, bool NeedAttnMask>
__global__ void softmax_block_forward(const input_t *input, output_t *output, const input_t *attn_mask, const input_t *bias,
        int64_t rows, int cols, int64_t attn_inner_skip_batch, int64_t bias_batch_size) {
    extern __shared__ __align__(sizeof(double)) unsigned char shared_buf[];
    auto *buf = reinterpret_cast<acc_t *>(shared_buf);
    const int tid = threadIdx.x;
    auto element_count = cols;
    int64_t bias_mod_size = bias_batch_size * cols;
    int64_t attn_mask_div_size = element_count;
    if IF_CONSTEXPR (NeedAttnMask)
    {
        attn_mask_div_size = attn_inner_skip_batch * element_count;
    }
    for (int64_t row = blockIdx.x; row < rows; row += gridDim.x) {
        acc_t thread_max = -std::numeric_limits<acc_t>::infinity();
        int64_t idx_offset = row * cols;
        const input_t* input_ptr = input + idx_offset;
        output_t* output_ptr = output + idx_offset;
        const input_t* attn_mask_ptr = nullptr;
        if IF_CONSTEXPR (NeedAttnMask){
            attn_mask_ptr = attn_mask + static_cast<int64_t>(idx_offset / attn_mask_div_size) * element_count ;
        }
        const input_t* bias_ptr = nullptr;
        if IF_CONSTEXPR (NeedBias) {
            bias_ptr = bias + idx_offset % bias_mod_size;
        }
        // TODO: enable pack as oneflow 
        for (int col = tid; col < cols; col += block_size) {
            buf[col] = static_cast<acc_t>(input_ptr[col]);
            if IF_CONSTEXPR (NeedAttnMask)
            {
                buf[col] += attn_mask_ptr[col];
            }
            if IF_CONSTEXPR (NeedBias)
            {
                buf[col] += bias_ptr[col];
            }
            thread_max = max(thread_max, buf[col]);
        }

        const acc_t row_max = BlockAllReduce<MaxOp, acc_t, block_size>(thread_max);

        acc_t thread_sum = 0;
        for (int col = tid; col < cols; col += block_size) {
            buf[col] = std::exp(buf[col] - row_max);
            thread_sum += buf[col];
        }

        const acc_t row_sum = BlockAllReduce<SumOp, acc_t, block_size>(thread_sum);
        for (int col = tid; col < cols; col += block_size) {
            output_ptr[col] = static_cast<output_t>(buf[col] / row_sum);
        }
    }
}

template<typename input_t, typename output_t, typename acc_t, int block_size>
__global__ void softmax_block_backward(output_t* store, const input_t* dy, const input_t* y,
                                    const int64_t rows, const int64_t cols) {
  extern __shared__ __align__(sizeof(double)) unsigned char grad_shared_buf[];
  auto* dy_buf = reinterpret_cast<acc_t*>(grad_shared_buf);
  auto* y_buf = reinterpret_cast<input_t*>(dy_buf + cols);
  const int tid = threadIdx.x;
  for (int64_t row = blockIdx.x; row < rows; row += gridDim.x) {
    acc_t thread_sum = 0;
    auto dy_ptr = dy + row * cols;
    auto y_ptr = y + row * cols;
    auto store_ptr = store + row * cols;
    for (int col = tid; col < cols; col += block_size) {
        y_buf[col] = y_ptr[col];
        dy_buf[col] = dy_ptr[col] * (acc_t)y_ptr[col];
    }
    for (int col = tid; col < cols; col += block_size) {
        thread_sum += dy_buf[col];
    }
    const acc_t row_sum = BlockAllReduce<SumOp, acc_t, block_size>(thread_sum);
    for (int col = tid; col < cols; col += block_size) {
        store_ptr[col] = static_cast<output_t>(dy_buf[col] - y_buf[col] * row_sum);
    }
  }
}

Guolin Ke's avatar
Guolin Ke committed
207
208
template <
    typename input_t, typename output_t, typename acc_t,
209
210
211
212
    typename Parameters, bool NeedMask, bool NeedBias, bool NeedAttnMask>
__global__ void softmax_warp_forward(input_t *dst, input_t *dst_orig, const output_t *src, const input_t *attn_mask, const input_t *bias,
                                     typename Parameters::MaskType *mask, acc_t p, int64_t batch_size, int64_t attn_inner_skip_batch, int64_t bias_batch_size, int element_count, uint64_t seed, uint64_t rand_offset)
{
Guolin Ke's avatar
Guolin Ke committed
213
214
215
216
217
218
    using MaskType = typename Parameters::MaskType;
    curandStatePhilox4_32_10_t state;
    int64_t first_batch = (static_cast<int64_t>(blockDim.y) * static_cast<int64_t>(blockIdx.x) + threadIdx.y) * Parameters::WarpBatch;
    // there might be multiple batches per warp. compute the index within the batch
    int64_t local_idx = threadIdx.x;
    const int64_t thread_offset = first_batch * element_count + local_idx;
219
220
    if IF_CONSTEXPR (NeedMask)
    {
Guolin Ke's avatar
Guolin Ke committed
221
222
        curand_init(seed, thread_offset, rand_offset, &state);
    }
223

Guolin Ke's avatar
Guolin Ke committed
224
225
226
227
228
    // batch_size might not be a multiple of Parameters::WarpBatch. Check how
    // many batches have to computed within this WARP.
    int local_batches = batch_size - first_batch;
    if (local_batches > Parameters::WarpBatch)
        local_batches = Parameters::WarpBatch;
229

Guolin Ke's avatar
Guolin Ke committed
230
231
    src += thread_offset;
    dst += thread_offset;
232
233
    if IF_CONSTEXPR (NeedMask)
    {
Guolin Ke's avatar
Guolin Ke committed
234
235
236
        dst_orig += thread_offset;
        mask += first_batch * Parameters::MaskStride;
    }
237
238
239
240
241
242
243
244
245

    int64_t bias_mod_size = bias_batch_size * element_count;

    int64_t attn_mask_div_size = element_count;
    if IF_CONSTEXPR (NeedAttnMask)
    {
        attn_mask_div_size = attn_inner_skip_batch * element_count;
    }

Guolin Ke's avatar
Guolin Ke committed
246
247
    // load data from global memory
    input_t elements_input[Parameters::WarpBatch][Parameters::WarpIterations];
248
249
250
#pragma unroll
    for (int i = 0; i < Parameters::WarpBatch; ++i)
    {
Guolin Ke's avatar
Guolin Ke committed
251
        int batch_element_count = (i >= local_batches) ? 0 : element_count;
252
        auto src_ptr = src + i * element_count;
253
254
255
#pragma unroll
        for (int it = 0; it < Parameters::WarpIterations; ++it)
        {
Guolin Ke's avatar
Guolin Ke committed
256
257
            int element_index = local_idx + it * Parameters::WarpSize;
            elements_input[i][it] = -std::numeric_limits<float>::infinity();
258
259
260

            if (element_index < batch_element_count)
            {
261
                elements_input[i][it] = src_ptr[it * Parameters::WarpSize];
Guolin Ke's avatar
Guolin Ke committed
262
263
264
            }
        }
    }
265

Guolin Ke's avatar
Guolin Ke committed
266
267
    // convert input_t to acc_t
    acc_t elements[Parameters::WarpBatch][Parameters::WarpIterations];
268
269
270
271
#pragma unroll
    for (int i = 0; i < Parameters::WarpBatch; ++i)
    {
        int batch_element_count = (i >= local_batches) ? 0 : element_count;
272
273
274
275
276
277
278
279
280
        int64_t idx_offset = (first_batch + i) * element_count;
        const input_t* attn_mask_ptr = nullptr;
        if IF_CONSTEXPR (NeedAttnMask){
            attn_mask_ptr = attn_mask + static_cast<int64_t>(idx_offset / attn_mask_div_size) * element_count  + local_idx;
        }
        const input_t* bias_ptr = nullptr;
        if IF_CONSTEXPR (NeedBias){
            bias_ptr = bias + idx_offset % bias_mod_size + local_idx;
        }
281
282
283
#pragma unroll
        for (int it = 0; it < Parameters::WarpIterations; ++it)
        {
Guolin Ke's avatar
Guolin Ke committed
284
            elements[i][it] = elements_input[i][it];
285
286
287
288
289
            int element_index = local_idx + it * Parameters::WarpSize;
            if (element_index < batch_element_count)
            {
                if IF_CONSTEXPR (NeedAttnMask)
                {
290
                    elements[i][it] += attn_mask_ptr[it * Parameters::WarpSize];
291
292
293
                }
                if IF_CONSTEXPR (NeedBias)
                {
294
                    elements[i][it] += bias_ptr[it * Parameters::WarpSize];
295
296
                }
            }
Guolin Ke's avatar
Guolin Ke committed
297
298
        }
    }
299

Guolin Ke's avatar
Guolin Ke committed
300
    // compute local max_value
301

Guolin Ke's avatar
Guolin Ke committed
302
303
    // take the max_value of the first element to avoid one max call
    acc_t max_value[Parameters::WarpBatch];
304
305
306
#pragma unroll
    for (int i = 0; i < Parameters::WarpBatch; ++i)
    {
Guolin Ke's avatar
Guolin Ke committed
307
308
        max_value[i] = elements[i][0];
    }
309
310
311
312
313
314
315

#pragma unroll
    for (int it = 1; it < Parameters::WarpIterations; ++it)
    {
#pragma unroll
        for (int i = 0; i < Parameters::WarpBatch; ++i)
        {
Guolin Ke's avatar
Guolin Ke committed
316
317
318
319
            max_value[i] = (max_value[i] > elements[i][it]) ? max_value[i] : elements[i][it];
        }
    }

320
321
322
323
// reduction max_value
#pragma unroll
    for (int offset = Parameters::WarpSize / 2; offset > 0; offset /= 2)
    {
Guolin Ke's avatar
Guolin Ke committed
324
        float val[Parameters::WarpBatch];
325
326
327
#pragma unroll
        for (int i = 0; i < Parameters::WarpBatch; ++i)
        {
Guolin Ke's avatar
Guolin Ke committed
328
329
            val[i] = SHFL_XOR(max_value[i], offset, Parameters::WarpSize);
        }
330
331
332
#pragma unroll
        for (int i = 0; i < Parameters::WarpBatch; ++i)
        {
Guolin Ke's avatar
Guolin Ke committed
333
334
335
            max_value[i] = max_value[i] > val[i] ? max_value[i] : val[i];
        }
    }
336

Guolin Ke's avatar
Guolin Ke committed
337
    // compute local sum
338
339
340
341
342
343
344
345
    acc_t sum[Parameters::WarpBatch]{0.0f};

#pragma unroll
    for (int i = 0; i < Parameters::WarpBatch; ++i)
    {
#pragma unroll
        for (int it = 0; it < Parameters::WarpIterations; ++it)
        {
Guolin Ke's avatar
Guolin Ke committed
346
347
348
349
            elements[i][it] = std::exp(elements[i][it] - max_value[i]);
            sum[i] += elements[i][it];
        }
    }
350
351
352
353
354
355
356
357

// reduction sum
#pragma unroll
    for (int offset = Parameters::WarpSize / 2; offset > 0; offset /= 2)
    {
#pragma unroll
        for (int i = 0; i < Parameters::WarpBatch; ++i)
        {
Guolin Ke's avatar
Guolin Ke committed
358
359
360
361
362
            sum[i] += SHFL_XOR(sum[i], offset, Parameters::WarpSize);
        }
    }

    // store result
363
364
    if IF_CONSTEXPR (NeedMask)
    {
Guolin Ke's avatar
Guolin Ke committed
365
        const acc_t pinv = 1.0 / p;
366
367
368
#pragma unroll
        for (int i = 0; i < Parameters::WarpBatch; ++i)
        {
Guolin Ke's avatar
Guolin Ke committed
369
370
371
            if (i >= local_batches)
                break;
            MaskType m = 0;
372
373
            if IF_CONSTEXPR (Parameters::WarpIterations == 1)
            {
Guolin Ke's avatar
Guolin Ke committed
374
375
                float rand = curand_uniform(&state);
                m = rand < p;
376
377
378
            }
            else if IF_CONSTEXPR (Parameters::WarpIterations == 2)
            {
Guolin Ke's avatar
Guolin Ke committed
379
380
                m = curand_uniform(&state) < p;
                m |= (curand_uniform(&state) < p) << 1;
381
382
383
384
385
386
            }
            else
            {
#pragma unroll
                for (int j = 0; j < DIV_CELL(Parameters::WarpIterations, 4); ++j)
                {
Guolin Ke's avatar
Guolin Ke committed
387
                    float4 rand4 = curand_uniform4(&state);
388
                    m |= (((MaskType)(rand4.x < p)) << (j * 4)) | (((MaskType)(rand4.y < p)) << (j * 4 + 1)) | (((MaskType)(rand4.z < p)) << (j * 4 + 2)) | (((MaskType)(rand4.w < p)) << (j * 4 + 3));
Guolin Ke's avatar
Guolin Ke committed
389
390
391
                }
            }
            mask[i * Parameters::MaskStride + local_idx] = m;
392
393
            auto dst_ptr = dst + i * element_count;
            auto dst_orig_ptr = dst_orig + i * element_count;
394
395
396
#pragma unroll
            for (int it = 0; it < Parameters::WarpIterations; ++it)
            {
Guolin Ke's avatar
Guolin Ke committed
397
                int element_index = local_idx + it * Parameters::WarpSize;
398
399
                if (element_index < element_count)
                {
Guolin Ke's avatar
Guolin Ke committed
400
                    const output_t d = elements[i][it] / sum[i];
401
402
                    dst_ptr[it * Parameters::WarpSize] = (acc_t)d * ((acc_t)((m >> it) & 1) * pinv);
                    dst_orig_ptr[it * Parameters::WarpSize] = d;
Guolin Ke's avatar
Guolin Ke committed
403
                }
404
405
                else
                {
Guolin Ke's avatar
Guolin Ke committed
406
407
408
409
                    break;
                }
            }
        }
410
411
412
413
414
415
    }
    else
    {
#pragma unroll
        for (int i = 0; i < Parameters::WarpBatch; ++i)
        {
416
            auto dst_ptr = dst + i * element_count;
Guolin Ke's avatar
Guolin Ke committed
417
418
            if (i >= local_batches)
                break;
419
420
421
#pragma unroll
            for (int it = 0; it < Parameters::WarpIterations; ++it)
            {
Guolin Ke's avatar
Guolin Ke committed
422
                int element_index = local_idx + it * Parameters::WarpSize;
423
424
                if (element_index < element_count)
                {
425
                    dst_ptr[it * Parameters::WarpSize] = elements[i][it] / sum[i];
Guolin Ke's avatar
Guolin Ke committed
426
                }
427
428
                else
                {
Guolin Ke's avatar
Guolin Ke committed
429
430
431
432
433
434
435
                    break;
                }
            }
        }
    }
}

436
437
438
439
440
441
442
443
444
445
#define LAUNCH_FORWARD_KERNEL(l)                                                                           \
    softmax_warp_forward<input_t, output_t, acc_t, SoftmaxParameters<l>, NeedMask, NeedBias, NeedAttnMask> \
        <<<blocks, threads, 0, at::cuda::getCurrentCUDAStream()>>>(                                        \
            dst, dst_orig, src, attn_mask, bias, (typename SoftmaxParameters<l>::MaskType *)mask, p,       \
            batch_count, attn_inner_skip_batch, bias_batch_count, softmax_elements, seed, offset);         \
    return true;

template <typename input_t, typename output_t, typename acc_t, bool NeedMask, bool NeedBias, bool NeedAttnMask>
bool dispatch_softmax_forward(output_t *dst, output_t *dst_orig, const input_t *src, const input_t *attn_mask, const input_t *bias, void *mask, acc_t p,
                              int softmax_elements, int64_t batch_count, int64_t attn_inner_skip_batch, int64_t bias_batch_count, uint64_t seed, uint64_t offset)
Guolin Ke's avatar
Guolin Ke committed
446
{
447
448
449
450
451
452
453
    TORCH_INTERNAL_ASSERT(softmax_elements >= 0 && softmax_elements <= 2048);
    if (softmax_elements == 0)
    {
        return false;
    }
    else
    {
Guolin Ke's avatar
Guolin Ke committed
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
        int log2_elements = log2_ceil(softmax_elements);
        const int next_power_of_two = 1 << log2_elements;

        // This value must match the Parameters::WarpSize constexpr value computed inside softmax_warp_backward.
        int warp_size = (next_power_of_two < 32) ? next_power_of_two : 32;

        // This value must match the Parameters::WarpBatch constexpr value computed inside softmax_warp_backward.
        int batches_per_warp = (next_power_of_two <= 128) ? 2 : 1;

        // use 128 threads per block to maximimize gpu utilization
        constexpr int threads_per_block = 128;

        int warps_per_block = (threads_per_block / warp_size);
        int batches_per_block = warps_per_block * batches_per_warp;
        int blocks = (batch_count + batches_per_block - 1) / batches_per_block;
        dim3 threads(warp_size, warps_per_block, 1);
        // Launch code would be more elegant if C++ supported FOR CONSTEXPR
471
472
        switch (log2_elements)
        {
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
            case 0:
                LAUNCH_FORWARD_KERNEL(0)
            case 1:
                LAUNCH_FORWARD_KERNEL(1)
            case 2:
                LAUNCH_FORWARD_KERNEL(2)
            case 3:
                LAUNCH_FORWARD_KERNEL(3)
            case 4:
                LAUNCH_FORWARD_KERNEL(4)
            case 5:
                LAUNCH_FORWARD_KERNEL(5)
            case 6:
                LAUNCH_FORWARD_KERNEL(6)
            case 7:
                LAUNCH_FORWARD_KERNEL(7)
            case 8:
                LAUNCH_FORWARD_KERNEL(8)
            case 9:
                LAUNCH_FORWARD_KERNEL(9)
            case 10:
                LAUNCH_FORWARD_KERNEL(10)
            default:
            {
                int grid_dim;
                constexpr int block_size = 128;
                constexpr int waves = 32;
                auto cols = softmax_elements;
                auto rows = batch_count;
                GetNumBlocks(block_size, rows, waves, &grid_dim);
                dim3 block(block_size);
                const size_t smem = cols * sizeof(acc_t);
                softmax_block_forward<input_t, output_t, acc_t,  block_size, NeedAttnMask, NeedBias><<<grid_dim, block, smem>>>(
                    src, dst, attn_mask, bias, rows, cols, attn_inner_skip_batch, bias_batch_count);
                return true;
            }
Guolin Ke's avatar
Guolin Ke committed
509
510
511
512
513
514
515
        }
    }
    return false;
}

template <
    typename input_t, typename output_t, typename acc_t, typename Parameters,
516
    bool IsLogSoftmax, bool NeedMask>
Guolin Ke's avatar
Guolin Ke committed
517
__global__ void softmax_warp_backward(output_t *gradInput, const input_t *grad, const input_t *output,
518
                                      const typename Parameters::MaskType *mask, acc_t p, int64_t batch_size, int element_count)
Guolin Ke's avatar
Guolin Ke committed
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
{
    using MaskType = typename Parameters::MaskType;
    int64_t first_batch = (static_cast<int64_t>(blockDim.y) * static_cast<int64_t>(blockIdx.x) + threadIdx.y) * Parameters::WarpBatch;

    // batch_size might not be a multiple of Parameters::WarpBatch. Check how
    // many batches have to computed within this WARP.
    int local_batches = batch_size - first_batch;
    if (local_batches > Parameters::WarpBatch)
        local_batches = Parameters::WarpBatch;

    // there might be multiple batches per warp. compute the index within the batch
    int64_t local_idx = threadIdx.x;

    // the first element to process by the current thread
    int64_t thread_offset = first_batch * element_count + local_idx;
    grad += thread_offset;
    output += thread_offset;
    gradInput += thread_offset;
537
538
    if IF_CONSTEXPR (NeedMask)
    {
Guolin Ke's avatar
Guolin Ke committed
539
540
541
542
543
544
545
546
547
548
        mask += first_batch * Parameters::MaskStride;
    }

    // The nested loops over Parameters::WarpBatch and then Parameters::WarpIterations can be simplified to one loop,
    // but I think doing so would obfuscate the logic of the algorithm, thus I chose to keep
    // the nested loops.
    // This should have no impact on performance because the loops are unrolled anyway.

    // load data from global memory
    acc_t grad_reg[Parameters::WarpBatch][Parameters::WarpIterations];
549
    input_t output_reg[Parameters::WarpBatch][Parameters::WarpIterations];
550
551
    if IF_CONSTEXPR (NeedMask)
    {
Guolin Ke's avatar
Guolin Ke committed
552
        MaskType mask_reg[Parameters::WarpBatch];
553
554
555
#pragma unroll
        for (int i = 0; i < Parameters::WarpBatch; ++i)
        {
Guolin Ke's avatar
Guolin Ke committed
556
557
558
559
            if (i >= local_batches)
                break;
            mask_reg[i] = mask[i * Parameters::MaskStride + local_idx];
        }
560

Guolin Ke's avatar
Guolin Ke committed
561
        const acc_t pinv = 1.0 / p;
562
563
564
565

#pragma unroll
        for (int i = 0; i < Parameters::WarpBatch; ++i)
        {
Guolin Ke's avatar
Guolin Ke committed
566
567
            int batch_element_count = (i >= local_batches) ? 0 : element_count;
            MaskType m = mask_reg[i];
568
569
            auto output_ptr = output + i * element_count;
            auto grad_ptr = grad + i * element_count;
570
571
572
#pragma unroll
            for (int it = 0; it < Parameters::WarpIterations; ++it)
            {
Guolin Ke's avatar
Guolin Ke committed
573
                int element_index = local_idx + it * Parameters::WarpSize;
574
575
                if (element_index < batch_element_count)
                {
Guolin Ke's avatar
Guolin Ke committed
576
                    grad_reg[i][it] =
577
578
579
580
581
                        (acc_t)((m >> it) & 1) *
                                  (acc_t)grad_ptr[it * Parameters::WarpSize] *
                                  pinv *
                        output_ptr[it * Parameters::WarpSize];
                    output_reg[i][it] = output_ptr[it * Parameters::WarpSize];
582
583
584
                }
                else
                {
Guolin Ke's avatar
Guolin Ke committed
585
                    grad_reg[i][it] = acc_t(0);
586
                    output_reg[i][it] = input_t(0);
Guolin Ke's avatar
Guolin Ke committed
587
588
589
                }
            }
        }
590
591
592
593
594
595
    }
    else
    {
#pragma unroll
        for (int i = 0; i < Parameters::WarpBatch; ++i)
        {
Guolin Ke's avatar
Guolin Ke committed
596
            int batch_element_count = (i >= local_batches) ? 0 : element_count;
597
598
            auto output_ptr = output + i * element_count;
            auto grad_ptr = grad + i * element_count;
599
600
601
#pragma unroll
            for (int it = 0; it < Parameters::WarpIterations; ++it)
            {
Guolin Ke's avatar
Guolin Ke committed
602
                int element_index = local_idx + it * Parameters::WarpSize;
603
604
                if (element_index < batch_element_count)
                {
605
606
607
                    output_reg[i][it] = output_ptr[it * Parameters::WarpSize];
                    grad_reg[i][it] = grad_ptr[it * Parameters::WarpSize] *
                                      (acc_t)output_ptr[it * Parameters::WarpSize];
608
609
610
                }
                else
                {
Guolin Ke's avatar
Guolin Ke committed
611
                    grad_reg[i][it] = acc_t(0);
612
                    output_reg[i][it] = output_t(0);
Guolin Ke's avatar
Guolin Ke committed
613
614
615
616
617
618
                }
            }
        }
    }

    acc_t sum[Parameters::WarpBatch];
619
620
621
622
623
624
625
#pragma unroll
    for (int i = 0; i < Parameters::WarpBatch; ++i)
    {
        sum[i] = grad_reg[i][0];
#pragma unroll
        for (int it = 1; it < Parameters::WarpIterations; ++it)
        {
Guolin Ke's avatar
Guolin Ke committed
626
627
628
629
            sum[i] += grad_reg[i][it];
        }
    }

630
631
632
633
634
635
#pragma unroll
    for (int offset = Parameters::WarpSize / 2; offset > 0; offset /= 2)
    {
#pragma unroll
        for (int i = 0; i < Parameters::WarpBatch; ++i)
        {
Guolin Ke's avatar
Guolin Ke committed
636
637
638
639
            sum[i] += SHFL_XOR(sum[i], offset, Parameters::WarpSize);
        }
    }

640
641
642
643
// store result
#pragma unroll
    for (int i = 0; i < Parameters::WarpBatch; ++i)
    {
Guolin Ke's avatar
Guolin Ke committed
644
645
        if (i >= local_batches)
            break;
646
        auto gradInput_ptr = gradInput + i * element_count;
647
648
649
#pragma unroll
        for (int it = 0; it < Parameters::WarpIterations; ++it)
        {
Guolin Ke's avatar
Guolin Ke committed
650
            int element_index = local_idx + it * Parameters::WarpSize;
651
652
            if (element_index < element_count)
            {
Guolin Ke's avatar
Guolin Ke committed
653
                // compute gradients
654
655
                if IF_CONSTEXPR (IsLogSoftmax)
                {
656
657
                    gradInput_ptr[it * Parameters::WarpSize] =
                        (grad_reg[i][it] - std::exp((acc_t)output_reg[i][it]) * sum[i]);
658
659
660
                }
                else
                {
661
                    gradInput_ptr[it * Parameters::WarpSize] =
Guolin Ke's avatar
Guolin Ke committed
662
663
664
665
666
667
668
                        (grad_reg[i][it] - output_reg[i][it] * sum[i]);
                }
            }
        }
    }
}

669
670
671
672
673
674
#define LAUNCH_BACKWARD_KERNEL(l)                                                                 \
    softmax_warp_backward<input_t, output_t, acc_t, SoftmaxParameters<l>, IsLogSoftmax, NeedMask> \
        <<<blocks, threads, 0, at::cuda::getCurrentCUDAStream()>>>(                               \
            grad_input, grad, output, (const typename SoftmaxParameters<l>::MaskType *)mask, p,   \
            batch_count, softmax_elements);                                                       \
    break;
Guolin Ke's avatar
Guolin Ke committed
675

676
template <typename input_t, typename output_t, typename acc_t, bool IsLogSoftmax, bool NeedMask>
Guolin Ke's avatar
Guolin Ke committed
677
void dispatch_softmax_backward(output_t *grad_input, const input_t *grad, const input_t *output,
678
                               const void *mask, acc_t p, int softmax_elements, int64_t batch_count)
Guolin Ke's avatar
Guolin Ke committed
679
{
680
681
682
683
684
685
686
    TORCH_INTERNAL_ASSERT(softmax_elements >= 0 && softmax_elements <= 2048);
    if (softmax_elements == 0)
    {
        return;
    }
    else
    {
Guolin Ke's avatar
Guolin Ke committed
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
        int log2_elements = log2_ceil(softmax_elements);
        const int next_power_of_two = 1 << log2_elements;

        // This value must match the WARP_SIZE constexpr value computed inside softmax_warp_backward.
        int warp_size = (next_power_of_two < 32) ? next_power_of_two : 32;

        // This value must match the WARP_BATCH constexpr value computed inside softmax_warp_backward.
        int batches_per_warp = (next_power_of_two <= 128) ? 2 : 1;

        // use 128 threads per block to maximimize gpu utilization
        constexpr int threads_per_block = 128;

        int warps_per_block = (threads_per_block / warp_size);
        int batches_per_block = warps_per_block * batches_per_warp;
        int blocks = (batch_count + batches_per_block - 1) / batches_per_block;
        dim3 threads(warp_size, warps_per_block, 1);
        // Launch code would be more elegant if C++ supported FOR CONSTEXPR
704
705
        switch (log2_elements)
        {
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
            case 0:
                LAUNCH_BACKWARD_KERNEL(0)
            case 1:
                LAUNCH_BACKWARD_KERNEL(1)
            case 2:
                LAUNCH_BACKWARD_KERNEL(2)
            case 3:
                LAUNCH_BACKWARD_KERNEL(3)
            case 4:
                LAUNCH_BACKWARD_KERNEL(4)
            case 5:
                LAUNCH_BACKWARD_KERNEL(5)
            case 6:
                LAUNCH_BACKWARD_KERNEL(6)
            case 7:
                LAUNCH_BACKWARD_KERNEL(7)
            case 8:
                LAUNCH_BACKWARD_KERNEL(8)
            case 9:
                LAUNCH_BACKWARD_KERNEL(9)
            case 10:
                LAUNCH_BACKWARD_KERNEL(10)
            default:
            {
                int grid_dim;
                constexpr int block_size = 128;
                constexpr int waves = 32;
                auto cols = softmax_elements;
                auto rows = batch_count;
                GetNumBlocks(block_size, rows, waves, &grid_dim);
                dim3 block(block_size);
                const size_t smem = cols * sizeof(acc_t) + cols * sizeof(input_t) ;
                softmax_block_backward<input_t, output_t, acc_t,  block_size><<<grid_dim, block, smem>>>(
                    grad_input, grad, output, rows, cols);
            }
Guolin Ke's avatar
Guolin Ke committed
741
742
743
        }
    }
}