reduce.h 1.27 KB
Newer Older
1
2
3
4
5
6
7
#pragma once

#include "common.h"

namespace tl {

struct SumOp {
8
  template <typename T> TL_DEVICE T operator()(T const &x, T const &y) {
9
10
11
12
13
    return x + y;
  }
};

struct MaxOp {
14
  template <typename T> TL_DEVICE T operator()(T const &x, T const &y) {
15
16
17
18
19
    return ck_tile::max(x, y);
  }
};

struct MinOp {
20
  template <typename T> TL_DEVICE T operator()(T const &x, T const &y) {
21
22
23
24
    return ck_tile::min(x, y);
  }
};

25
26
27
28
template <class Reducer, int threads, int scale> struct AllReduce {
  static_assert(threads == 1024 || threads == 512 || threads == 256 ||
                threads == 128 || threads == 64 || threads == 32 ||
                threads == 16 || threads == 8 || threads == 4 || threads == 2);
29
30
  static_assert(threads % scale == 0);

31
  template <typename T> static __device__ T run(T x, T *red_buf = nullptr) {
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
    constexpr int offset = threads / 2;
    constexpr int warpSize = 64;

    if constexpr (offset >= warpSize) {
      __syncthreads();
      red_buf[threadIdx.x] = x;
      __syncthreads();
      x = Reducer()(x, red_buf[threadIdx.x ^ offset]);
    } else {
      x = Reducer()(x, __shfl_xor(x, offset));
    }
    if constexpr (offset == scale) {
      return x;
    } else {
      return AllReduce<Reducer, offset, scale>::run(x, red_buf);
    }
  }
};

51
} // namespace tl