okami.mom/strata

git clone https://git.nkp.pet/okami.mom/strata

Niko1221Merge branch 'f-139b-arc' into f-139-relad33b8074

main
36.3 KiB896 linesraw
1//==---- blas_gemm_utils.hpp ----------------------*- C++ -*----------------==//
2//
3// Copyright (C) Intel Corporation
4// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
5// See https://llvm.org/LICENSE.txt for license information.
6//
7//===----------------------------------------------------------------------===//
8// This file contains the implementation of GEneral Matrix Multiplication by
9// using oneDNN. More datatype combinations and the epilogue can be supported by
10// oneDNN, which is not available in blas_utils.hpp using oneMKL.
11//===----------------------------------------------------------------------===//
12
13#ifndef __DPCT_BLAS_GEMM_UTILS_HPP__
14#define __DPCT_BLAS_GEMM_UTILS_HPP__
15
16#include "compat_service.hpp"
17#include "blas_utils.hpp"
18#include "dnnl_utils.hpp"
19
20namespace dpct::blas_gemm::experimental {
21enum class order_t : std::uint8_t {
22  col,
23  row,
24  col32,
25  col4_4r2_8c,
26  col32_2r_4r4
27};
28} // namespace dpct::blas_gemm::experimental
29
30#include "detail/blas_gemm_utils_detail.hpp"
31
32namespace dpct::blas_gemm::experimental {
33enum class pointer_mode_t {
34  host,
35  device,
36  device_vector,
37  alpha_device_vector_beta_zero,
38  alpha_device_vector_beta_host
39};
40enum class epilogue_t {
41  nop = 1,
42  relu,
43  bias,
44  gelu,
45  gelu_bias,
46  gelu_aux,
47  gelu_aux_bias,
48  dgelu,
49  bgradb
50};
51
52class descriptor;
53using descriptor_ptr = descriptor *;
54class matrix_layout_t;
55using matrix_layout_ptr = matrix_layout_t *;
56class matmul_desc_t;
57using matmul_desc_ptr = matmul_desc_t *;
58class transform_desc_t;
59using transform_desc_ptr = transform_desc_t *;
60
61class descriptor {
62public:
63  descriptor() {}
64  void init(sycl::queue *q_ptr) {
65    _engine = ::dnnl::sycl_interop::make_engine(q_ptr->get_device(),
66                                                q_ptr->get_context());
67    _engine_stream = ::dnnl::sycl_interop::make_stream(_engine, *q_ptr);
68  }
69  ::dnnl::engine get_engine() const noexcept { return _engine; }
70  ::dnnl::stream get_engine_stream() const noexcept { return _engine_stream; };
71
72private:
73  ::dnnl::engine _engine;
74  ::dnnl::stream _engine_stream;
75};
76
77class matrix_layout_t {
78public:
79  enum class attribute {
80    type,
81    order,
82    rows,
83    cols,
84    ld,
85    batch_count,
86    strided_batch_offset
87  };
88
89  matrix_layout_t(library_data_t type, std::uint64_t rows, std::uint64_t cols,
90                  std::int64_t ld)
91      : _type(type), _rows(rows), _cols(cols), _ld(ld) {}
92
93  void set_attribute(attribute attr, const void *mem) {
94    get_set_attr<true>(attr, const_cast<void *>(mem));
95  }
96  void get_attribute(attribute attr, void *mem) {
97    get_set_attr<false>(attr, mem);
98  }
99
100private:
101  template <bool is_set> void get_set_attr(attribute attr, void *mem) {
102#define CASE(tag)                                                              \
103  case attribute::tag:                                                         \
104    if constexpr (is_set) {                                                    \
105      _##tag = *static_cast<decltype(_##tag) *>(mem);                          \
106    } else {                                                                   \
107      *static_cast<decltype(_##tag) *>(mem) = _##tag;                          \
108    }                                                                          \
109    break;
110    switch (attr) {
111      CASE(type)
112      CASE(order)
113      CASE(rows)
114      CASE(cols)
115      CASE(ld)
116      CASE(batch_count)
117      CASE(strided_batch_offset)
118    }
119#undef CASE
120  }
121
122  library_data_t _type;
123  order_t _order = order_t::col;
124  std::uint64_t _rows;
125  std::uint64_t _cols;
126  std::int64_t _ld;
127  std::uint64_t _batch_count = 1;
128  std::uint64_t _strided_batch_offset = 0;
129
130  friend sycl::event matmul(descriptor_ptr handle, matmul_desc_ptr computeDesc,
131                            const void *alpha, const void *a,
132                            matrix_layout_ptr a_desc, const void *b,
133                            matrix_layout_ptr b_desc, const void *beta,
134                            const void *c, matrix_layout_ptr c_desc, void *d,
135                            matrix_layout_ptr d_desc,
136                            ::dpct::cs::queue_ptr q_ptr);
137  friend sycl::event
138  matrix_transform(transform_desc_ptr transform_desc, const void *alpha,
139                   const void *a, matrix_layout_ptr a_desc, const void *beta,
140                   const void *b, matrix_layout_ptr b_desc, void *c,
141                   matrix_layout_ptr c_desc, ::dpct::cs::queue_ptr q_ptr);
142};
143
144class matmul_desc_t {
145public:
146  enum class attribute {
147    compute_type,
148    scale_type,
149    bias_data_type,
150    bias_pointer,
151    pointer_mode,
152    trans_a,
153    trans_b,
154    trans_c,
155    epilogue,
156    epilogue_aux_ld,
157    epilogue_aux_pointer,
158    epilogue_aux_data_type,
159    a_scale_pointer,
160    b_scale_pointer,
161    d_scale_pointer,
162    absmax_d_pointer,
163    unsupport
164  };
165
166  matmul_desc_t(compute_type compute_type, library_data_t scale_type)
167      : _compute_type(compute_type), _scale_type(scale_type) {}
168
169  void set_attribute(attribute attr, const void *mem) {
170    if (attr != attribute::unsupport)
171      get_set_attr<true>(attr, const_cast<void *>(mem));
172  }
173  void get_attribute(attribute attr, void *mem) {
174    if (attr != attribute::unsupport)
175      get_set_attr<false>(attr, mem);
176  }
177
178private:
179  template <bool is_set> void get_set_attr(attribute attr, void *mem) {
180#define CASE(tag)                                                              \
181  case attribute::tag:                                                         \
182    if constexpr (is_set) {                                                    \
183      _##tag = *static_cast<decltype(_##tag) *>(mem);                          \
184    } else {                                                                   \
185      *static_cast<decltype(_##tag) *>(mem) = _##tag;                          \
186    }                                                                          \
187    break;
188    switch (attr) {
189      CASE(compute_type)
190      CASE(scale_type)
191      CASE(bias_data_type)
192      CASE(bias_pointer)
193      CASE(pointer_mode)
194      CASE(trans_a)
195      CASE(trans_b)
196      CASE(trans_c)
197      CASE(epilogue)
198      CASE(a_scale_pointer)
199      CASE(b_scale_pointer)
200      CASE(d_scale_pointer)
201      CASE(absmax_d_pointer)
202      CASE(epilogue_aux_ld)
203      CASE(epilogue_aux_pointer)
204      CASE(epilogue_aux_data_type)
205    default:
206      break;
207    }
208#undef CASE
209  }
210
211  compute_type _compute_type;
212  library_data_t _scale_type;
213  library_data_t _bias_data_type = library_data_t::real_float;
214  pointer_mode_t _pointer_mode = pointer_mode_t::host;
215  oneapi::mkl::transpose _trans_a = oneapi::mkl::transpose::nontrans;
216  oneapi::mkl::transpose _trans_b = oneapi::mkl::transpose::nontrans;
217  oneapi::mkl::transpose _trans_c = oneapi::mkl::transpose::nontrans;
218  epilogue_t _epilogue = epilogue_t::nop;
219  library_data_t _epilogue_aux_data_type = library_data_t::real_float;
220  size_t _epilogue_aux_ld = 0;
221  void *_a_scale_pointer = nullptr;
222  void *_b_scale_pointer = nullptr;
223  void *_d_scale_pointer = nullptr;
224  void *_absmax_d_pointer = nullptr;
225  void *_bias_pointer = nullptr;
226  void *_epilogue_aux_pointer = nullptr;
227
228  friend sycl::event matmul(descriptor_ptr handle, matmul_desc_ptr computeDesc,
229                            const void *alpha, const void *a,
230                            matrix_layout_ptr a_desc, const void *b,
231                            matrix_layout_ptr b_desc, const void *beta,
232                            const void *c, matrix_layout_ptr c_desc, void *d,
233                            matrix_layout_ptr d_desc,
234                            ::dpct::cs::queue_ptr q_ptr);
235};
236
237/// This function does the following operations:
238/// (1) D_temp = epilogue(alpha * scale_a * op_a(A) * scale_b * op_b(B) + beta * C)
239/// (2) Amax = absmax(D_temp) when matmul_desc_t::attribute::absmax_d_pointer is specified
240/// (3) D = scale_d * D_temp
241///   "op_a" is specified by the matmul_desc_t::attribute::trans_a
242///   (default is nontrans)
243///   "op_b" is specified by the matmul_desc_t::attribute::trans_b
244///   (default is nontrans)
245///   "scale_a" is specified by the matmul_desc_t::attribute::a_scale_pointer
246///   (default is nullptr, which behaves as 1.0)
247///   "scale_b" is specified by the matmul_desc_t::attribute::b_scale_pointer
248///   (default is nullptr, which behaves as 1.0)
249///   "scale_d" is specified by the matmul_desc_t::attribute::d_scale_pointer
250///   (default is nullptr, which behaves as 1.0)
251///   "alpha" can be a scalar value or a vector, which is specified by the
252///   matmul_desc_tattribute::::pointer_mode
253///   "epilogue" is specified by the matmul_desc_t::attribute::epilogue
254/// Currently, this function only supports the following type combinations:
255///   scale_type==int32 && a_type==int8 && b_type==int8 && c_type==int32;
256///   scale_type==float && a_type==int8 && b_type==int8 && c_type==int8;
257///   scale_type==float && a_type==int8 && b_type==int8 && c_type==int32;
258///   scale_type==float && a_type==float && b_type==float && c_type==float.
259/// Currently, this function only supports beta==0 or beta==1.
260/// Currently, this function only supports the relu, bias, gelu, gelu_bias,
261/// gelu_aux, gelu_aux_bias, dgelu and bgradb epilogue.
262/// NOTE: Non-col-major matrix will be converted to col-major matrix before.
263/// TODO: Impl row-major matmul without layout conversion.
264/// multiplication and converted back after multiplication.
265/// \param [in] handle A handle containing context info.
266/// \param [in] compute_desc Describe the computation.
267/// \param [in] alpha Scaling factor alpha.
268/// \param [in] a Input matrix A.
269/// \param [in] a_desc Describe the matrix A.
270/// \param [in] b Input matrix B.
271/// \param [in] b_desc Describe the matrix B.
272/// \param [in] beta Scaling factor beta.
273/// \param [in] c Input matrix C.
274/// \param [in] c_desc Describe the matrix C.
275/// \param [out] d Output matrix D.
276/// \param [in] d_desc Describe the matrix D.
277/// \param [in] q_ptr The queue where the routine should be executed.
278inline sycl::event matmul(descriptor_ptr handle, matmul_desc_ptr compute_desc,
279                          const void *alpha, const void *a,
280                          matrix_layout_ptr a_desc, const void *b,
281                          matrix_layout_ptr b_desc, const void *beta,
282                          const void *c, matrix_layout_ptr c_desc, void *d,
283                          matrix_layout_ptr d_desc,
284                          ::dpct::cs::queue_ptr q_ptr) {
285  const size_t m = compute_desc->_trans_a == oneapi::mkl::transpose::nontrans
286                       ? a_desc->_rows
287                       : a_desc->_cols;
288  const size_t n = d_desc->_cols;
289  const size_t k = compute_desc->_trans_b == oneapi::mkl::transpose::nontrans
290                       ? b_desc->_rows
291                       : b_desc->_cols;
292  const library_data_t a_type = a_desc->_type;
293  const library_data_t b_type = b_desc->_type;
294  const library_data_t c_type = c_desc->_type;
295  const library_data_t d_type = d_desc->_type;
296  const library_data_t scale_type = compute_desc->_scale_type;
297
298  if (!q_ptr)
299    q_ptr = &::dpct::cs::get_default_queue();
300  handle->init(q_ptr);
301  bool vector_alpha = false;
302  bool device_alpha = false;
303  if (compute_desc->_pointer_mode == pointer_mode_t::device_vector ||
304      compute_desc->_pointer_mode ==
305          pointer_mode_t::alpha_device_vector_beta_zero ||
306      compute_desc->_pointer_mode ==
307          pointer_mode_t::alpha_device_vector_beta_host) {
308    vector_alpha = true;
309    device_alpha = true;
310  } else if (compute_desc->_pointer_mode == pointer_mode_t::device) {
311    device_alpha = true;
312  }
313
314  bool beta_is_zero = true;
315  if (beta != nullptr) {
316    int beta_value = detail::type_dispatch<detail::get_beta_value_impl>(
317        compute_desc->_scale_type, beta, q_ptr);
318    if (beta_value != 0) {
319      beta_is_zero = false;
320      if (beta_value != 1)
321        throw std::runtime_error(
322            "dpct::blas_gemm::experimental::matmul() does "
323            "not support non-zero and non-one beta currently.");
324    }
325  }
326
327  if (compute_desc->_epilogue != epilogue_t::nop &&
328      compute_desc->_epilogue != epilogue_t::relu &&
329      compute_desc->_epilogue != epilogue_t::bias &&
330      compute_desc->_epilogue != epilogue_t::gelu &&
331      compute_desc->_epilogue != epilogue_t::gelu_bias &&
332      compute_desc->_epilogue != epilogue_t::gelu_aux &&
333      compute_desc->_epilogue != epilogue_t::gelu_aux_bias &&
334      compute_desc->_epilogue != epilogue_t::dgelu &&
335      compute_desc->_epilogue != epilogue_t::bgradb) {
336    throw std::runtime_error(
337        "dpct::blas_gemm::experimental::matmul() only "
338        "supports relu, bias, gelu, gelu_bias, gelu_aux, "
339        "gelu_aux_bias, dgelu and bgradb epilogue currently.");
340  }
341
342  if (!(compute_desc->_scale_type == library_data_t::real_int32 &&
343        a_desc->_type == library_data_t::real_int8 &&
344        b_desc->_type == library_data_t::real_int8 &&
345        c_desc->_type == library_data_t::real_int32) &&
346      !(compute_desc->_scale_type == library_data_t::real_float &&
347        a_desc->_type == library_data_t::real_int8 &&
348        b_desc->_type == library_data_t::real_int8 &&
349        c_desc->_type == library_data_t::real_int8) &&
350      !(compute_desc->_scale_type == library_data_t::real_float &&
351        a_desc->_type == library_data_t::real_int8 &&
352        b_desc->_type == library_data_t::real_int8 &&
353        c_desc->_type == library_data_t::real_int32) &&
354      !(compute_desc->_scale_type == library_data_t::real_float &&
355        a_desc->_type == library_data_t::real_float &&
356        b_desc->_type == library_data_t::real_float &&
357        c_desc->_type == library_data_t::real_float)) {
358    throw std::runtime_error(
359        "dpct::blas_gemm::experimental::matmul() only supports data type "
360        "combinataions:\n  scale_type==int32 && a_type==int8 && b_type==int8"
361        "&& c_type==int32,\n  scale_type==float && a_type==int8 && "
362        "b_type==int8 && c_type==int8,\n  scale_type==float && a_type==int8"
363        "&& b_type==int8 && c_type==int32 or\n  scale_type==float && "
364        "a_type==float"
365        "&& b_type==float && c_type==float.");
366  }
367
368  if (a_desc->_batch_count != b_desc->_batch_count ||
369      a_desc->_batch_count != c_desc->_batch_count ||
370      a_desc->_batch_count != d_desc->_batch_count) {
371    throw std::runtime_error("dpct::blas_gemm::experimental::matmul() does not "
372                             "support different batch count.");
373  }
374
375#ifdef DPCT_USM_LEVEL_NONE
376  if (a_desc->_batch_count != 1) {
377    throw std::runtime_error(
378        "dpct::blas_gemm::experimental::matmul() only supports "
379        "batch mode with USM enabled.");
380  }
381#endif
382
383  size_t a_elm_size = dpct::detail::library_data_size[static_cast<unsigned int>(
384                          a_desc->_type)] /
385                      8;
386  size_t b_elm_size = dpct::detail::library_data_size[static_cast<unsigned int>(
387                          b_desc->_type)] /
388                      8;
389  size_t c_elm_size = dpct::detail::library_data_size[static_cast<unsigned int>(
390                          c_desc->_type)] /
391                      8;
392  size_t d_elm_size = dpct::detail::library_data_size[static_cast<unsigned int>(
393                          d_desc->_type)] /
394                      8;
395
396  static const auto matmul_single =
397      [](descriptor_ptr handle, matmul_desc_ptr compute_desc, const void *alpha,
398         const void *a, matrix_layout_ptr a_desc, const void *b,
399         matrix_layout_ptr b_desc, const void *beta, const void *c,
400         matrix_layout_ptr c_desc, void *d, matrix_layout_ptr d_desc,
401         ::dpct::cs::queue_ptr q_ptr, const size_t m, const size_t n,
402         const size_t k, const library_data_t a_type,
403         const library_data_t b_type, const library_data_t c_type,
404         const library_data_t d_type, const library_data_t scale_type,
405         bool vector_alpha, bool device_alpha, bool beta_is_zero,
406         size_t a_elm_size, size_t b_elm_size, size_t c_elm_size,
407         size_t d_elm_size) -> sycl::event {
408    // For non-col_major matrix, convert it to col_major.
409    const void *new_a = a;
410    const void *new_b = b;
411    const void *new_c = c;
412    void *new_d = d;
413    bool new_b_allocated = false;
414    bool new_c_allocated = false;
415    bool new_d_allocated = false;
416    size_t new_lda = a_desc->_ld, new_ldb = b_desc->_ld, new_ldc = c_desc->_ld,
417           new_ldd = d_desc->_ld;
418    std::vector<sycl::event> transform_events;
419
420    if (a_desc->_order != order_t::col)
421      new_lda = a_desc->_rows;
422    new_a = ::dpct::cs::malloc(a_elm_size * a_desc->_cols * new_lda, *q_ptr);
423    sycl::event e_init;
424    if (a_desc->_order != order_t::col)
425      e_init = detail::type_dispatch<detail::matrix_transform_impl>(
426          a_desc->_type, q_ptr, a_desc->_rows, a_desc->_cols, a_desc->_ld,
427          a_desc->_order, (const std::int8_t *)a, new_lda, order_t::col,
428          (std::int8_t *)new_a, std::vector<sycl::event>{});
429    else
430      e_init = ::dpct::cs::memcpy(
431          *q_ptr, (void *)new_a, a, a_elm_size * a_desc->_cols * new_lda,
432          ::dpct::cs::memcpy_direction::device_to_device);
433
434    // alpha = alpha * scale_a * scale_b
435    sycl::event e_scale_new_a = detail::scale_new_a(
436        q_ptr, m, k, (void *)new_a, a_type, alpha, scale_type, vector_alpha,
437        device_alpha, compute_desc->_a_scale_pointer,
438        compute_desc->_b_scale_pointer, {e_init});
439
440    transform_events.push_back(e_scale_new_a);
441
442    if (b_desc->_order != order_t::col) {
443      new_ldb = b_desc->_rows;
444      new_b = ::dpct::cs::malloc(b_elm_size * b_desc->_cols * new_ldb, *q_ptr);
445      new_b_allocated = true;
446      sycl::event e = detail::type_dispatch<detail::matrix_transform_impl>(
447          b_desc->_type, q_ptr, b_desc->_rows, b_desc->_cols, b_desc->_ld,
448          b_desc->_order, b, new_ldb, order_t::col, const_cast<void *>(new_b),
449          std::vector<sycl::event>{});
450      transform_events.push_back(e);
451    }
452
453    if (!beta_is_zero && c_desc->_order != order_t::col) {
454      new_ldc = c_desc->_rows;
455      new_c = ::dpct::cs::malloc(c_elm_size * c_desc->_cols * new_ldc, *q_ptr);
456      new_c_allocated = true;
457      sycl::event e = detail::type_dispatch<detail::matrix_transform_impl>(
458          c_desc->_type, q_ptr, c_desc->_rows, c_desc->_cols, c_desc->_ld,
459          c_desc->_order, c, new_ldc, order_t::col, const_cast<void *>(new_c),
460          std::vector<sycl::event>{});
461      transform_events.push_back(e);
462    }
463
464    if (d_desc->_order != order_t::col) {
465      new_ldd = d_desc->_rows;
466      new_d = ::dpct::cs::malloc(d_elm_size * d_desc->_cols * new_ldd, *q_ptr);
467      new_d_allocated = true;
468    }
469
470    // start to call oneDNN matmul primitive
471    // a,d are col_major, b is row_major
472    const ::dnnl::memory::dim M = m;
473    const ::dnnl::memory::dim N = n;
474    const ::dnnl::memory::dim K = k;
475
476    ::dnnl::memory::dims src_dims = {M, K};
477    ::dnnl::memory::dims weights_dims = {K, N};
478    ::dnnl::memory::dims bias_dims = {M, N};
479    ::dnnl::memory::dims dst_dims = {M, N};
480
481    const ::dnnl::memory::dims src_strides =
482        compute_desc->_trans_a == oneapi::mkl::transpose::nontrans
483            ? ::dnnl::memory::dims{1, static_cast<long>(new_lda)}
484            : ::dnnl::memory::dims{static_cast<long>(new_lda), 1};
485    const ::dnnl::memory::dims weights_strides =
486        compute_desc->_trans_b == oneapi::mkl::transpose::nontrans
487            ? ::dnnl::memory::dims{1, static_cast<long>(new_ldb)}
488            : ::dnnl::memory::dims{static_cast<long>(new_ldb), 1};
489    const ::dnnl::memory::dims bias_strides =
490        ::dnnl::memory::dims{1, static_cast<long>(new_ldc)};
491    const ::dnnl::memory::dims dst_strides =
492        ::dnnl::memory::dims{1, static_cast<long>(new_ldd)};
493
494    auto src_md = ::dnnl::memory::desc(
495        src_dims, dpct::dnnl::memory_desc_ext::to_dnnl_data_type(a_type),
496        src_strides);
497    auto weights_md = ::dnnl::memory::desc(
498        weights_dims, dpct::dnnl::memory_desc_ext::to_dnnl_data_type(b_type),
499        weights_strides);
500    auto bias_md = ::dnnl::memory::desc(
501        bias_dims, dpct::dnnl::memory_desc_ext::to_dnnl_data_type(c_type),
502        bias_strides);
503    auto dst_md = ::dnnl::memory::desc(
504        dst_dims, dpct::dnnl::memory_desc_ext::to_dnnl_data_type(d_type),
505        dst_strides);
506
507    auto *src_mem =
508        new ::dnnl::memory(src_md, handle->get_engine(), DNNL_MEMORY_NONE);
509    auto *weights_mem =
510        new ::dnnl::memory(weights_md, handle->get_engine(), DNNL_MEMORY_NONE);
511    auto *bias_mem =
512        new ::dnnl::memory(bias_md, handle->get_engine(), DNNL_MEMORY_NONE);
513    auto *dst_mem =
514        new ::dnnl::memory(dst_md, handle->get_engine(), DNNL_MEMORY_NONE);
515
516#ifdef DPCT_USM_LEVEL_NONE
517    detail::type_dispatch<detail::set_buffer_impl>(a_type, src_mem, new_a);
518    detail::type_dispatch<detail::set_buffer_impl>(b_type, weights_mem, new_b);
519    if (!beta_is_zero)
520      detail::type_dispatch<detail::set_buffer_impl>(c_type, bias_mem, new_c);
521    detail::type_dispatch<detail::set_buffer_impl>(d_type, dst_mem, new_d);
522#else
523    src_mem->set_data_handle(const_cast<void *>(new_a));
524    weights_mem->set_data_handle(const_cast<void *>(new_b));
525    if (!beta_is_zero)
526      bias_mem->set_data_handle(const_cast<void *>(new_c));
527    dst_mem->set_data_handle(new_d);
528#endif
529
530    std::unordered_map<int, ::dnnl::memory> matmul_args;
531    matmul_args.insert({DNNL_ARG_SRC, *src_mem});
532    matmul_args.insert({DNNL_ARG_WEIGHTS, *weights_mem});
533    matmul_args.insert({DNNL_ARG_DST, *dst_mem});
534    ::dnnl::primitive_attr matmul_attr;
535
536    ::dnnl::post_ops matmul_ops;
537    if (!beta_is_zero) {
538      matmul_ops.append_binary(::dnnl::algorithm::binary_add, bias_md);
539      matmul_args.insert({DNNL_ARG_ATTR_MULTIPLE_POST_OP(matmul_ops.len() - 1) |
540                              DNNL_ARG_SRC_1,
541                          *bias_mem});
542    }
543
544    ::dnnl::memory *po_bias_mem = nullptr;
545    auto po_bias_md =
546        ::dnnl::memory::desc(::dnnl::memory::dims{M, 1},
547                             dpct::dnnl::memory_desc_ext::to_dnnl_data_type(
548                                 compute_desc->_bias_data_type),
549                             ::dnnl::memory::dims{1, M});
550    if (compute_desc->_epilogue == epilogue_t::bias ||
551        compute_desc->_epilogue == epilogue_t::gelu_bias ||
552        compute_desc->_epilogue == epilogue_t::gelu_aux_bias) {
553      po_bias_mem = new ::dnnl::memory(po_bias_md, handle->get_engine(),
554                                       DNNL_MEMORY_NONE);
555#ifdef DPCT_USM_LEVEL_NONE
556      detail::type_dispatch<detail::set_buffer_impl>(
557          compute_desc->_bias_data_type, po_bias_mem,
558          compute_desc->_bias_pointer);
559#else
560      po_bias_mem->set_data_handle(compute_desc->_bias_pointer);
561#endif
562    }
563
564    ::dnnl::memory *po_bias_bgradb_mem = nullptr;
565    auto po_bias_bgradb_md = ::dnnl::memory::desc(
566        compute_desc->_trans_b == oneapi::mkl::transpose::nontrans
567            ? ::dnnl::memory::dims{N, 1}
568            : ::dnnl::memory::dims{1, N},
569        dpct::dnnl::memory_desc_ext::to_dnnl_data_type(
570            compute_desc->_bias_data_type),
571        compute_desc->_trans_b == oneapi::mkl::transpose::nontrans
572            ? ::dnnl::memory::dims{1, N}
573            : ::dnnl::memory::dims{N, 1});
574    if (compute_desc->_epilogue == epilogue_t::bgradb) {
575      po_bias_bgradb_mem = new ::dnnl::memory(
576          po_bias_bgradb_md, handle->get_engine(), DNNL_MEMORY_NONE);
577#ifdef DPCT_USM_LEVEL_NONE
578      detail::type_dispatch<detail::set_buffer_impl>(
579          compute_desc->_bias_data_type, po_bias_bgradb_mem,
580          compute_desc->_bias_pointer);
581#else
582      po_bias_bgradb_mem->set_data_handle(compute_desc->_bias_pointer);
583#endif
584    }
585
586    ::dnnl::memory *po_aux_mem = nullptr;
587    auto po_aux_md = ::dnnl::memory::desc(
588        ::dnnl::memory::dims{M, N},
589        dpct::dnnl::memory_desc_ext::to_dnnl_data_type(
590            compute_desc->_epilogue_aux_data_type),
591        ::dnnl::memory::dims{
592            1, static_cast<long>(compute_desc->_epilogue_aux_ld)});
593    if (compute_desc->_epilogue == epilogue_t::dgelu) {
594      po_aux_mem =
595          new ::dnnl::memory(po_aux_md, handle->get_engine(), DNNL_MEMORY_NONE);
596#ifdef DPCT_USM_LEVEL_NONE
597      detail::type_dispatch<detail::set_buffer_impl>(
598          compute_desc->_epilogue_aux_data_type, po_aux_mem,
599          compute_desc->_epilogue_aux_pointer);
600#else
601      po_aux_mem->set_data_handle(compute_desc->_epilogue_aux_pointer);
602#endif
603    }
604
605    switch (compute_desc->_epilogue) {
606    case epilogue_t::relu:
607      matmul_ops.append_eltwise(::dnnl::algorithm::eltwise_relu, 0.f, 0.f);
608      break;
609    case epilogue_t::bias:
610    case epilogue_t::gelu_bias: {
611      matmul_ops.append_binary(::dnnl::algorithm::binary_add, po_bias_md);
612      matmul_args.insert({DNNL_ARG_ATTR_MULTIPLE_POST_OP(matmul_ops.len() - 1) |
613                              DNNL_ARG_SRC_1,
614                          *po_bias_mem});
615      if (compute_desc->_epilogue == epilogue_t::gelu_bias)
616        matmul_ops.append_eltwise(::dnnl::algorithm::eltwise_gelu_tanh, 0.f,
617                                  0.f);
618      break;
619    }
620    case epilogue_t::gelu:
621      matmul_ops.append_eltwise(::dnnl::algorithm::eltwise_gelu_tanh, 0.f, 0.f);
622      break;
623    default:
624      break;
625    }
626
627    matmul_attr.set_post_ops(matmul_ops);
628
629    auto matmul_pd = ::dnnl::matmul::primitive_desc(
630        handle->get_engine(), src_md, weights_md, dst_md, matmul_attr);
631    auto matmul_prim = ::dnnl::matmul(matmul_pd);
632    sycl::event matmul_prim_event =
633        ::dnnl::sycl_interop::execute(matmul_prim, handle->get_engine_stream(),
634                                      matmul_args, transform_events);
635
636    // post-op implemented by separate primitives
637    sycl::event post_op_prim_event;
638    if (compute_desc->_epilogue == epilogue_t::gelu_aux ||
639        compute_desc->_epilogue == epilogue_t::gelu_aux_bias) {
640      sycl::event prev_event = matmul_prim_event;
641      if (compute_desc->_epilogue == epilogue_t::gelu_aux_bias) {
642        auto po_bias_pd = ::dnnl::binary::primitive_desc(
643            handle->get_engine(), ::dnnl::algorithm::binary_add, dst_md,
644            po_bias_md, dst_md);
645        auto po_bias_prim = ::dnnl::binary(po_bias_pd);
646        std::unordered_map<int, ::dnnl::memory> po_bias_args;
647        po_bias_args.insert({DNNL_ARG_SRC_0, *dst_mem});
648        po_bias_args.insert({DNNL_ARG_SRC_1, *po_bias_mem});
649        po_bias_args.insert({DNNL_ARG_DST, *dst_mem});
650        sycl::event prev_event = ::dnnl::sycl_interop::execute(
651            po_bias_prim, handle->get_engine_stream(), po_bias_args,
652            {matmul_prim_event});
653      }
654      size_t size_of_element =
655          dpct::detail::library_data_size[static_cast<unsigned int>(
656              d_desc->_type)] /
657          8;
658      sycl::event copy_e = dpct::blas::matrix_mem_copy_async(
659          compute_desc->_epilogue_aux_pointer, new_d,
660          compute_desc->_epilogue_aux_ld, d_desc->_ld, m, n, size_of_element,
661          ::dpct::cs::memcpy_direction::automatic, *q_ptr, {prev_event});
662
663      auto gelu_pd = ::dnnl::eltwise_forward::primitive_desc(
664          handle->get_engine(), ::dnnl::prop_kind::forward_training,
665          ::dnnl::algorithm::eltwise_gelu_tanh, dst_md, dst_md);
666      auto gelu_prim = ::dnnl::eltwise_forward(gelu_pd);
667      std::unordered_map<int, ::dnnl::memory> gelu_args;
668      gelu_args.insert({DNNL_ARG_SRC, *dst_mem});
669      gelu_args.insert({DNNL_ARG_DST, *dst_mem});
670      post_op_prim_event = ::dnnl::sycl_interop::execute(
671          gelu_prim, handle->get_engine_stream(), gelu_args, {copy_e});
672    } else if (compute_desc->_epilogue == epilogue_t::dgelu) {
673      auto gelu_pd = ::dnnl::eltwise_forward::primitive_desc(
674          handle->get_engine(), ::dnnl::prop_kind::forward_training,
675          ::dnnl::algorithm::eltwise_gelu_tanh, po_aux_md, po_aux_md);
676      auto dgelu_pd = ::dnnl::eltwise_backward::primitive_desc(
677          handle->get_engine(), ::dnnl::algorithm::eltwise_gelu_tanh, dst_md,
678          dst_md, po_aux_md, gelu_pd);
679      auto dgelu_prim = ::dnnl::eltwise_backward(dgelu_pd);
680      std::unordered_map<int, ::dnnl::memory> dgelu_args;
681      dgelu_args.insert({DNNL_ARG_SRC, *po_aux_mem});
682      dgelu_args.insert({DNNL_ARG_DIFF_DST, *dst_mem});
683      dgelu_args.insert({DNNL_ARG_DIFF_SRC, *dst_mem});
684      post_op_prim_event =
685          ::dnnl::sycl_interop::execute(dgelu_prim, handle->get_engine_stream(),
686                                        dgelu_args, {matmul_prim_event});
687    } else if (compute_desc->_epilogue == epilogue_t::bgradb) {
688      auto reduction_pd = ::dnnl::reduction::primitive_desc(
689          handle->get_engine(), ::dnnl::algorithm::reduction_sum, weights_md,
690          po_bias_bgradb_md, 0.f, 0.f);
691      auto reduction_prim = ::dnnl::reduction(reduction_pd);
692      std::unordered_map<int, ::dnnl::memory> reduction_args;
693      reduction_args.insert({DNNL_ARG_SRC, *weights_mem});
694      reduction_args.insert({DNNL_ARG_DST, *po_bias_bgradb_mem});
695      post_op_prim_event = ::dnnl::sycl_interop::execute(
696          reduction_prim, handle->get_engine_stream(), reduction_args,
697          {matmul_prim_event});
698    }
699
700#ifndef DPCT_USM_LEVEL_NONE
701    // WA to avoid incorrect result on CPU with USM
702    if (q_ptr->get_device().is_cpu()) {
703      matmul_prim_event.wait();
704      post_op_prim_event.wait();
705    }
706#endif
707    // end of calling oneDNN
708
709    sycl::event absmax_d_event;
710    if (auto absmax_ptr = compute_desc->_absmax_d_pointer) {
711      absmax_d_event = detail::type_dispatch<detail::absmax_impl>(
712          d_desc->_type, absmax_ptr, new_d, new_ldd, d_desc->_rows,
713          d_desc->_cols, q_ptr,
714          std::vector<sycl::event>{matmul_prim_event, post_op_prim_event});
715    }
716
717    sycl::event scale_d_event;
718    if (auto d_scale_ptr = compute_desc->_d_scale_pointer) {
719      scale_d_event = detail::type_dispatch<detail::scale_d_impl>(
720          d_desc->_type, d_scale_ptr, new_d, new_ldd, d_desc->_rows,
721          d_desc->_cols, q_ptr, compute_desc->_scale_type,
722          std::vector<sycl::event>{matmul_prim_event, absmax_d_event,
723                                   post_op_prim_event});
724    }
725
726    sycl::event transform_d_event;
727    if (d_desc->_order != order_t::col) {
728      transform_d_event = detail::type_dispatch<detail::matrix_transform_impl>(
729          d_desc->_type, q_ptr, d_desc->_rows, d_desc->_cols, new_ldd,
730          order_t::col, new_d, d_desc->_ld, d_desc->_order, d,
731          std::vector<sycl::event>{matmul_prim_event, absmax_d_event,
732                                   post_op_prim_event});
733    }
734
735    sycl::event free_event = q_ptr->submit([&](sycl::handler &cgh) {
736      cgh.depends_on({transform_d_event, matmul_prim_event, absmax_d_event,
737                      post_op_prim_event});
738      cgh.host_task([=] {
739        delete src_mem;
740        delete weights_mem;
741        delete bias_mem;
742        delete dst_mem;
743        if (po_bias_mem)
744          delete po_bias_mem;
745        if (po_bias_bgradb_mem)
746          delete po_bias_bgradb_mem;
747        if (po_aux_mem)
748          delete po_aux_mem;
749        ::dpct::cs::free((void *)new_a, *q_ptr);
750        if (new_b_allocated)
751          ::dpct::cs::free((void *)new_b, *q_ptr);
752        if (new_c_allocated)
753          ::dpct::cs::free((void *)new_c, *q_ptr);
754        if (new_d_allocated)
755          ::dpct::cs::free((void *)new_d, *q_ptr);
756      });
757    });
758    return free_event;
759  };
760
761  std::vector<sycl::event> events;
762  const std::byte *offsetted_a = static_cast<const std::byte *>(a);
763  const std::byte *offsetted_b = static_cast<const std::byte *>(b);
764  const std::byte *offsetted_c = static_cast<const std::byte *>(c);
765  std::byte *offsetted_d = static_cast<std::byte *>(d);
766  for (std::uint64_t i = 0; i < a_desc->_batch_count; i++) {
767    sycl::event e = matmul_single(
768        handle, compute_desc, alpha, offsetted_a, a_desc, offsetted_b, b_desc,
769        beta, offsetted_c, c_desc, offsetted_d, d_desc, q_ptr, m, n, k, a_type,
770        b_type, c_type, d_type, scale_type, vector_alpha, device_alpha,
771        beta_is_zero, a_elm_size, b_elm_size, c_elm_size, d_elm_size);
772    events.push_back(e);
773
774    offsetted_a += a_elm_size * a_desc->_strided_batch_offset;
775    offsetted_b += b_elm_size * b_desc->_strided_batch_offset;
776    offsetted_c += c_elm_size * c_desc->_strided_batch_offset;
777    offsetted_d += d_elm_size * d_desc->_strided_batch_offset;
778  }
779
780  return q_ptr->single_task(events, [] {});
781}
782
783class transform_desc_t {
784public:
785  enum class attribute { scale_type, pointer_mode, trans_a, trans_b };
786
787  transform_desc_t(library_data_t scale_type) : _scale_type(scale_type) {}
788  void set_attribute(attribute attr, const void *mem) {
789    get_set_attr<true>(attr, const_cast<void *>(mem));
790  }
791  void get_attribute(attribute attr, void *mem) {
792    get_set_attr<false>(attr, mem);
793  }
794
795private:
796  template <bool is_set> void get_set_attr(attribute attr, void *mem) {
797#define CASE(tag)                                                              \
798  case attribute::tag:                                                         \
799    if constexpr (is_set) {                                                    \
800      _##tag = *static_cast<decltype(_##tag) *>(mem);                          \
801    } else {                                                                   \
802      *static_cast<decltype(_##tag) *>(mem) = _##tag;                          \
803    }                                                                          \
804    break;
805    switch (attr) {
806      CASE(scale_type)
807      CASE(pointer_mode)
808      CASE(trans_a)
809      CASE(trans_b)
810    }
811#undef CASE
812  }
813
814  library_data_t _scale_type;
815  pointer_mode_t _pointer_mode = pointer_mode_t::host;
816  oneapi::mkl::transpose _trans_a = oneapi::mkl::transpose::nontrans;
817  oneapi::mkl::transpose _trans_b = oneapi::mkl::transpose::nontrans;
818
819  friend sycl::event
820  matrix_transform(transform_desc_ptr transform_desc, const void *alpha,
821                   const void *a, matrix_layout_ptr a_desc, const void *beta,
822                   const void *b, matrix_layout_ptr b_desc, void *c,
823                   matrix_layout_ptr c_desc, ::dpct::cs::queue_ptr q_ptr);
824};
825
826/// This function does operation:
827/// C = alpha*transformation(A) + beta*transformation(B).
828/// The "transformation" includes matrix transpose and layout conversion.
829/// Currently it only supports alpha==1 && beta==0.
830/// \param [in] transform_desc Describe the transformation.
831/// \param [in] alpha Scaling factor alpha.
832/// \param [in] a Input matrix A.
833/// \param [in] a_desc Describe the matrix A.
834/// \param [in] beta Scaling factor beta.
835/// \param [in] b Input matrix B.
836/// \param [in] b_desc Describe the matrix B.
837/// \param [out] c Output matrix C.
838/// \param [in] c_desc Describe the matrix C.
839/// \param [in] q_ptr The queue where the routine should be executed.
840inline sycl::event matrix_transform(transform_desc_ptr transform_desc,
841                                    const void *alpha, const void *a,
842                                    matrix_layout_ptr a_desc, const void *beta,
843                                    const void *b, matrix_layout_ptr b_desc,
844                                    void *c, matrix_layout_ptr c_desc,
845                                    ::dpct::cs::queue_ptr q_ptr) {
846  if (!q_ptr)
847    q_ptr = &::dpct::cs::get_default_queue();
848
849  if (transform_desc->_pointer_mode != pointer_mode_t::host) {
850    throw std::runtime_error(
851        "dpct::blas_gemm::experimental::matrix_transform() "
852        "only supports pointer_mode_t::host as pointer_mode currently.");
853  }
854  if (transform_desc->_scale_type != library_data_t::real_float) {
855    throw std::runtime_error(
856        "dpct::blas_gemm::experimental::matrix_transform() "
857        "only supports library_data_t::real_float as scale_type currently.");
858  }
859
860  if (alpha != nullptr) {
861    if (1.0f != *reinterpret_cast<const float *>(alpha))
862      throw std::runtime_error(
863          "dpct::blas_gemm::experimental::matrix_transform() does not "
864          "support non-one alpha currently.");
865  }
866
867  if (beta != nullptr) {
868    if (0.0f != *reinterpret_cast<const float *>(beta))
869      throw std::runtime_error(
870          "dpct::blas_gemm::experimental::matrix_transform() does not "
871          "support non-zero beta currently.");
872  }
873
874  if (b != nullptr) {
875    throw std::runtime_error(
876        "dpct::blas_gemm::experimental::matrix_transform() does not "
877        "support matrix B currently.");
878  }
879
880  if ((a_desc->_type != library_data_t::real_int8 ||
881       c_desc->_type != library_data_t::real_int8) &&
882      (a_desc->_type != library_data_t::real_int32 ||
883       c_desc->_type != library_data_t::real_int32)) {
884    throw std::runtime_error(
885        "dpct::blas_gemm::experimental::matrix_transform() only supports "
886        "combinations of data types: a_type==real_int8&&c_type==real_int8, "
887        "a_type==real_int32&&c_type==real_int32.");
888  }
889
890  return detail::type_dispatch<detail::matrix_transform_impl>(
891      a_desc->_type, q_ptr, a_desc->_rows, a_desc->_cols, a_desc->_ld,
892      a_desc->_order, a, c_desc->_ld, c_desc->_order, c,
893      std::vector<sycl::event>{});
894}
895} // namespace dpct::blas_gemm::experimental
896#endif // __DPCT_BLAS_GEMM_UTILS_HPP__