summaryrefslogtreecommitdiff
path: root/src/routines/levelx/xgemmbatched.cpp
blob: 8ce2dedc972a85b593fa25f0f5632dad88ac5459 (plain)
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
// =================================================================================================
// This file is part of the CLBlast project. The project is licensed under Apache Version 2.0. This
// project loosely follows the Google C++ styleguide and uses a tab-size of two spaces and a max-
// width of 100 characters per line.
//
// Author(s):
//   Cedric Nugteren <www.cedricnugteren.nl>
//
// This file implements the XgemmBatched class (see the header for information about the class).
//
// =================================================================================================

#include "routines/levelx/xgemmbatched.hpp"

#include <string>
#include <vector>

namespace clblast {
// =================================================================================================

// Constructor: forwards to base class constructor
template <typename T>
XgemmBatched<T>::XgemmBatched(Queue &queue, EventPointer event, const std::string &name):
    Routine(queue, event, name,
            {"Copy","Pad","Transpose","Padtranspose","Xgemm","XgemmDirect","GemmRoutine"},
            PrecisionValue<T>(), {}, {
    #include "../../kernels/level3/level3.opencl"
    #include "../../kernels/level3/copy_fast.opencl"
    #include "../../kernels/level3/copy_pad.opencl"
    #include "../../kernels/level3/transpose_fast.opencl"
    #include "../../kernels/level3/transpose_pad.opencl"
    , // separated in multiple parts to prevent C1091 in MSVC 2013
    #include "../../kernels/level3/xgemm_direct_part1.opencl"
    #include "../../kernels/level3/xgemm_direct_part2.opencl"
    #include "../../kernels/level3/xgemm_direct_part3.opencl"
    , // separated in multiple parts to prevent C1091 in MSVC 2013
    #include "../../kernels/level3/xgemm_part1.opencl"
    #include "../../kernels/level3/xgemm_part2.opencl"
    #include "../../kernels/level3/xgemm_part3.opencl"
    #include "../../kernels/level3/xgemm_part4.opencl"
    , // separated in multiple parts to prevent C1091 in MSVC 2013
    #include "../../kernels/level3/xgemm_batched.opencl"
    #include "../../kernels/level3/xgemm_direct_batched.opencl"
    }) {
}

// =================================================================================================

// The main routine
template <typename T>
void XgemmBatched<T>::DoGemmBatched(const Layout layout, const Transpose a_transpose, const Transpose b_transpose,
                                    const size_t m, const size_t n, const size_t k,
                                    const std::vector<T> &alphas,
                                    const Buffer<T> & a_buffer, const std::vector<size_t> &a_offsets, const size_t a_ld,
                                    const Buffer<T> & b_buffer, const std::vector<size_t> &b_offsets, const size_t b_ld,
                                    const std::vector<T> &betas,
                                    const Buffer<T> & c_buffer, const std::vector<size_t> &c_offsets, const size_t c_ld,
                                    const size_t batch_count) {

  // Tests for a valid batch count
  if ((batch_count < 1) || (alphas.size() != batch_count) || (betas.size() != batch_count) ||
      (a_offsets.size() != batch_count) || (b_offsets.size() != batch_count) || (c_offsets.size() != batch_count)) {
    throw BLASError(StatusCode::kInvalidBatchCount);
  }

  // Makes sure all dimensions are larger than zero
  if ((m == 0) || (n == 0) || (k == 0)) { throw BLASError(StatusCode::kInvalidDimension); }

  // Computes whether or not the matrices are transposed in memory. See GEMM routine for details.
  const auto a_rotated = (layout == Layout::kColMajor && a_transpose != Transpose::kNo) ||
                         (layout == Layout::kRowMajor && a_transpose == Transpose::kNo);
  const auto b_rotated = (layout == Layout::kColMajor && b_transpose != Transpose::kNo) ||
                         (layout == Layout::kRowMajor && b_transpose == Transpose::kNo);
  const auto c_rotated = (layout == Layout::kRowMajor);
  static const auto a_want_rotated = false;
  static const auto b_want_rotated = true;
  static const auto c_want_rotated = false;
  const auto a_do_transpose = a_rotated != a_want_rotated;
  const auto b_do_transpose = b_rotated != b_want_rotated;
  const auto c_do_transpose = c_rotated != c_want_rotated;

  // In case of complex data-types, the transpose can also become a conjugate transpose
  const auto a_conjugate = (a_transpose == Transpose::kConjugate);
  const auto b_conjugate = (b_transpose == Transpose::kConjugate);

  // Computes the first and second dimensions of the 3 matrices taking into account whether the
  // matrices are rotated or not
  const auto a_one = (a_rotated) ? k : m;
  const auto a_two = (a_rotated) ? m : k;
  const auto b_one = (b_rotated) ? n : k;
  const auto b_two = (b_rotated) ? k : n;
  const auto c_one = (c_rotated) ? n : m;
  const auto c_two = (c_rotated) ? m : n;

  // Tests the matrices for validity
  for (auto batch = size_t{0}; batch < batch_count; ++batch) {
    TestMatrixA(a_one, a_two, a_buffer, a_offsets[batch], a_ld, false); // don't test for invalid LD
    TestMatrixB(b_one, b_two, b_buffer, b_offsets[batch], b_ld, false); // don't test for invalid LD
    TestMatrixC(c_one, c_two, c_buffer, c_offsets[batch], c_ld);
  }

  // Upload the scalar arguments to the device
  auto alphas_device = Buffer<T>(context_, BufferAccess::kReadWrite, batch_count);
  auto betas_device = Buffer<T>(context_, BufferAccess::kReadWrite, batch_count);
  alphas_device.Write(queue_, batch_count, alphas);
  betas_device.Write(queue_, batch_count, betas);

  // Converts the offset to integers
  auto a_offsets_int = std::vector<int>(batch_count);
  auto b_offsets_int = std::vector<int>(batch_count);
  auto c_offsets_int = std::vector<int>(batch_count);
  for (auto batch = size_t{ 0 }; batch < batch_count; ++batch) {
    a_offsets_int[batch] = static_cast<int>(a_offsets[batch]);
    b_offsets_int[batch] = static_cast<int>(b_offsets[batch]);
    c_offsets_int[batch] = static_cast<int>(c_offsets[batch]);
  }

  // Selects which version of the batched GEMM to run
  const auto do_gemm_direct = true;
  if (do_gemm_direct) { // single generic kernel
    BatchedGemmDirect(m, n, k, alphas_device,
                      a_buffer, a_offsets_int, a_ld, b_buffer, b_offsets_int, b_ld,
                      betas_device, c_buffer, c_offsets_int, c_ld,
                      a_do_transpose, b_do_transpose, c_do_transpose, a_conjugate, b_conjugate,
                      batch_count);
  }
  else { // pre/post-processing plus a very fast kernel
    BatchedGemmIndirect(m, n, k, alphas_device,
                        a_buffer, a_offsets_int, a_ld, b_buffer, b_offsets_int, b_ld,
                        betas_device, c_buffer, c_offsets_int, c_ld,
                        a_do_transpose, b_do_transpose, c_do_transpose, a_conjugate, b_conjugate,
                        a_one, a_two, a_want_rotated,
                        b_one, b_two, b_want_rotated,
                        c_one, c_two, c_want_rotated,
                        batch_count);
  }
}


// =================================================================================================

// The indirect version of batched GEMM. This uses the faster but non-general kernel. It has specific
// requirements, but several pre and post-processing kernels take care of those. However, the
// overhead of these extra kernels might not be ideal for certain devices/arguments.
template <typename T>
void XgemmBatched<T>::BatchedGemmIndirect(const size_t m, const size_t n, const size_t k,
                                          const Buffer<T> &alphas,
                                          const Buffer<T> &a_buffer, const std::vector<int> &a_offsets, const size_t a_ld,
                                          const Buffer<T> &b_buffer, const std::vector<int> &b_offsets, const size_t b_ld,
                                          const Buffer<T> &betas,
                                          const Buffer<T> &c_buffer, const std::vector<int> &c_offsets, const size_t c_ld,
                                          const bool a_do_transpose, const bool b_do_transpose, const bool c_do_transpose,
                                          const bool a_conjugate, const bool b_conjugate,
                                          const size_t a_one, const size_t a_two, const bool a_want_rotated,
                                          const size_t b_one, const size_t b_two, const bool b_want_rotated,
                                          const size_t c_one, const size_t c_two, const bool c_want_rotated,
                                          const size_t batch_count) {
  // Calculates the ceiled versions of m, n, and k
  const auto m_ceiled = Ceil(Ceil(m, db_["MWG"]), db_["VWM"]);
  const auto n_ceiled = Ceil(Ceil(n, db_["NWG"]), db_["VWN"]);
  const auto k_ceiled = Ceil(Ceil(k, db_["KWG"]), db_["VWM"]);

  // Computes the first and second "internal" (ceiled) dimensions of the 3 matrices taking into account
  // whether the matrices need to be rotated or not for the kernel.
  const auto a_one_i = (a_want_rotated) ? k_ceiled : m_ceiled;
  const auto a_two_i = (a_want_rotated) ? m_ceiled : k_ceiled;
  const auto b_one_i = (b_want_rotated) ? n_ceiled : k_ceiled;
  const auto b_two_i = (b_want_rotated) ? k_ceiled : n_ceiled;
  const auto c_one_i = (c_want_rotated) ? n_ceiled : m_ceiled;
  const auto c_two_i = (c_want_rotated) ? m_ceiled : n_ceiled;

  // Sets the "internal" offsets, i.e. the perfect offsets
  auto a_offsets_i = std::vector<int>(batch_count);
  auto b_offsets_i = std::vector<int>(batch_count);
  auto c_offsets_i = std::vector<int>(batch_count);
  for (auto batch = size_t{0}; batch < batch_count; ++batch) {
    a_offsets_i[batch] = static_cast<int>(batch * a_one_i * a_two_i);
    b_offsets_i[batch] = static_cast<int>(batch * b_one_i * b_two_i);
    c_offsets_i[batch] = static_cast<int>(batch * c_one_i * c_two_i);
  }

  // Determines whether or not temporary matrices are needed
  auto a_no_temp = a_one == a_one_i && a_two == a_two_i && a_ld == a_one && a_offsets == a_offsets_i &&
                   a_do_transpose == false && a_conjugate == false;
  auto b_no_temp = b_one == b_one_i && b_two == b_two_i && b_ld == b_one && b_offsets == b_offsets_i &&
                   b_do_transpose == false && b_conjugate == false;
  auto c_no_temp = c_one == c_one_i && c_two == c_two_i && c_ld == c_one && c_offsets == c_offsets_i &&
                   c_do_transpose == false;

  // Creates the temporary matrices
  const auto a_temp = (a_no_temp) ? a_buffer : Buffer<T>(context_, batch_count * a_one_i * a_two_i);
  const auto b_temp = (b_no_temp) ? b_buffer : Buffer<T>(context_, batch_count * b_one_i * b_two_i);
  const auto c_temp = (c_no_temp) ? c_buffer : Buffer<T>(context_, batch_count * c_one_i * c_two_i);

  // Events of all kernels (including pre/post processing kernels)
  auto eventWaitList = std::vector<Event>();
  auto emptyEventList = std::vector<Event>();

  // Runs the pre-processing kernel for matrix A. This transposes the matrix, but also pads zeros
  // to fill it up until it reaches a certain multiple of size (kernel parameter dependent). In
  // case nothing has to be done, these kernels can be skipped.
  if (!a_no_temp) {
    auto a_offsets_device = Buffer<int>(context_, BufferAccess::kReadWrite, batch_count);
    auto a_offsets_i_device = Buffer<int>(context_, BufferAccess::kReadWrite, batch_count);
    a_offsets_device.Write(queue_, batch_count, a_offsets);
    a_offsets_i_device.Write(queue_, batch_count, a_offsets_i);
    auto eventProcessA = Event();
    PadCopyTransposeMatrixBatched(queue_, device_, db_, eventProcessA.pointer(), emptyEventList,
                                  a_one, a_two, a_ld, a_offsets_device, a_buffer,
                                  a_one_i, a_two_i, a_one_i, a_offsets_i_device, a_temp,
                                  program_, true, a_do_transpose, a_conjugate, batch_count);
    eventWaitList.push_back(eventProcessA);
  }

  // As above, but now for matrix B
  if (!b_no_temp) {
    auto b_offsets_device = Buffer<int>(context_, BufferAccess::kReadWrite, batch_count);
    auto b_offsets_i_device = Buffer<int>(context_, BufferAccess::kReadWrite, batch_count);
    b_offsets_device.Write(queue_, batch_count, b_offsets);
    b_offsets_i_device.Write(queue_, batch_count, b_offsets_i);
    auto eventProcessB = Event();
    PadCopyTransposeMatrixBatched(queue_, device_, db_, eventProcessB.pointer(), emptyEventList,
                                  b_one, b_two, b_ld, b_offsets_device, b_buffer,
                                  b_one_i, b_two_i, b_one_i, b_offsets_i_device, b_temp,
                                  program_, true, b_do_transpose, b_conjugate, batch_count);
    eventWaitList.push_back(eventProcessB);
  }

  // As above, but now for matrix C
  auto c_offsets_device = Buffer<int>(context_, BufferAccess::kReadWrite, batch_count);
  auto c_offsets_i_device = Buffer<int>(context_, BufferAccess::kReadWrite, batch_count);
  if (!c_no_temp) {
    c_offsets_device.Write(queue_, batch_count, c_offsets);
    c_offsets_i_device.Write(queue_, batch_count, c_offsets_i);
    auto eventProcessC = Event();
    PadCopyTransposeMatrixBatched(queue_, device_, db_, eventProcessC.pointer(), emptyEventList,
                                  c_one, c_two, c_ld, c_offsets_device, c_buffer,
                                  c_one_i, c_two_i, c_one_i, c_offsets_i_device, c_temp,
                                  program_, true, c_do_transpose, false, batch_count);
    eventWaitList.push_back(eventProcessC);
  }

  // Retrieves the Xgemm kernel from the compiled binary
  auto kernel = Kernel(program_, "XgemmBatched");

  // Sets the kernel arguments
  kernel.SetArgument(0, static_cast<int>(m_ceiled));
  kernel.SetArgument(1, static_cast<int>(n_ceiled));
  kernel.SetArgument(2, static_cast<int>(k_ceiled));
  kernel.SetArgument(3, alphas());
  kernel.SetArgument(4, betas());
  kernel.SetArgument(5, a_temp());
  kernel.SetArgument(6, static_cast<int>(a_one_i));
  kernel.SetArgument(7, static_cast<int>(a_two_i));
  kernel.SetArgument(8, b_temp());
  kernel.SetArgument(9, static_cast<int>(b_one_i));
  kernel.SetArgument(10, static_cast<int>(b_two_i));
  kernel.SetArgument(11, c_temp());
  kernel.SetArgument(12, static_cast<int>(c_one_i));
  kernel.SetArgument(13, static_cast<int>(c_two_i));

  // Computes the global and local thread sizes
  const auto global = std::vector<size_t>{
    (c_one_i * db_["MDIMC"]) / db_["MWG"],
    (c_two_i * db_["NDIMC"]) / db_["NWG"],
    batch_count
  };
  const auto local = std::vector<size_t>{db_["MDIMC"], db_["NDIMC"], 1};

  // Launches the kernel
  auto eventKernel = Event();
  auto eventPointer = eventKernel.pointer();
  RunKernel(kernel, queue_, device_, global, local, eventPointer, eventWaitList);

  // Runs the post-processing kernel if needed
  if (!c_no_temp) {
    eventWaitList.push_back(eventKernel);
    PadCopyTransposeMatrixBatched(queue_, device_, db_, event_, eventWaitList,
                                  c_one_i, c_two_i, c_one_i, c_offsets_i_device, c_temp,
                                  c_one, c_two, c_ld, c_offsets_device, c_buffer,
                                  program_, false, c_do_transpose, false, batch_count);
  }
}

// =================================================================================================

// The direct version of batched GEMM, requiring just one kernel, no pre or post-processing kernels.
template <typename T>
void XgemmBatched<T>::BatchedGemmDirect(const size_t m, const size_t n, const size_t k,
                                        const Buffer<T> &alphas,
                                        const Buffer<T> &a_buffer, const std::vector<int> &a_offsets, const size_t a_ld,
                                        const Buffer<T> &b_buffer, const std::vector<int> &b_offsets, const size_t b_ld,
                                        const Buffer<T> &betas,
                                        const Buffer<T> &c_buffer, const std::vector<int> &c_offsets, const size_t c_ld,
                                        const bool a_do_transpose, const bool b_do_transpose, const bool c_do_transpose,
                                        const bool a_conjugate, const bool b_conjugate,
                                        const size_t batch_count) {

  // Uploads the offsets to the device
  auto a_offsets_device = Buffer<int>(context_, BufferAccess::kReadWrite, batch_count);
  auto b_offsets_device = Buffer<int>(context_, BufferAccess::kReadWrite, batch_count);
  auto c_offsets_device = Buffer<int>(context_, BufferAccess::kReadWrite, batch_count);
  a_offsets_device.Write(queue_, batch_count, a_offsets);
  b_offsets_device.Write(queue_, batch_count, b_offsets);
  c_offsets_device.Write(queue_, batch_count, c_offsets);

  // Retrieves the proper XgemmDirect kernel from the compiled binary
  const auto name = (a_do_transpose) ? (b_do_transpose ? "XgemmDirectBatchedTT" : "XgemmDirectBatchedTN") :
                                       (b_do_transpose ? "XgemmDirectBatchedNT" : "XgemmDirectBatchedNN");
  auto kernel = Kernel(program_, name);

  // Sets the kernel arguments
  kernel.SetArgument(0, static_cast<int>(m));
  kernel.SetArgument(1, static_cast<int>(n));
  kernel.SetArgument(2, static_cast<int>(k));
  kernel.SetArgument(3, alphas());
  kernel.SetArgument(4, betas());
  kernel.SetArgument(5, a_buffer());
  kernel.SetArgument(6, a_offsets_device());
  kernel.SetArgument(7, static_cast<int>(a_ld));
  kernel.SetArgument(8, b_buffer());
  kernel.SetArgument(9, b_offsets_device());
  kernel.SetArgument(10, static_cast<int>(b_ld));
  kernel.SetArgument(11, c_buffer());
  kernel.SetArgument(12, c_offsets_device());
  kernel.SetArgument(13, static_cast<int>(c_ld));
  kernel.SetArgument(14, static_cast<int>(c_do_transpose));
  kernel.SetArgument(15, static_cast<int>(a_conjugate));
  kernel.SetArgument(16, static_cast<int>(b_conjugate));

  // Computes the global and local thread sizes
  const auto m_ceiled = Ceil(m, db_["WGD"]);
  const auto n_ceiled = Ceil(n, db_["WGD"]);
  const auto global = std::vector<size_t>{
    (m_ceiled * db_["MDIMCD"]) / db_["WGD"],
    (n_ceiled * db_["NDIMCD"]) / db_["WGD"],
    batch_count
  };
  const auto local = std::vector<size_t>{db_["MDIMCD"], db_["NDIMCD"], 1};

  // Launches the kernel
  RunKernel(kernel, queue_, device_, global, local, event_);
}

// =================================================================================================

// Compiles the templated class
template class XgemmBatched<half>;
template class XgemmBatched<float>;
template class XgemmBatched<double>;
template class XgemmBatched<float2>;
template class XgemmBatched<double2>;

// =================================================================================================
} // namespace clblast