okami.mom/strata

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

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

main
214.6 KiB4854 linesraw
1//==---- dnnl_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
9#ifndef __DPCT_DNNL_UTILS_HPP__
10#define __DPCT_DNNL_UTILS_HPP__
11
12#include "compat_service.hpp"
13#include "lib_common_utils.hpp"
14
15#include <oneapi/dnnl/dnnl.hpp>
16#include <oneapi/dnnl/dnnl_sycl.hpp>
17
18#if defined(__has_include) && __has_include(<oneapi/math/rng/device.hpp>)
19#include <oneapi/math/rng/device.hpp>
20#elif defined(__has_include) && __has_include(<oneapi/mkl/rng/device.hpp>)
21#include <oneapi/mkl/rng/device.hpp>
22#elif defined(__has_include)
23#error "SYCLomatic runtime requires oneMath/oneMKL support"
24#else
25#error "SYCLomatic runtime requires __has_include support"
26#endif
27
28#include <algorithm>
29#include <list>
30#include <unordered_map>
31
32#include "detail/dnnl_utils_detail.hpp"
33
34namespace dpct {
35namespace dnnl {
36/// Get concatenated library version as an integer.
37static inline size_t get_version() {
38  const ::dnnl::version_t *ver = ::dnnl::version();
39  return ver->major * 1000 + ver->minor * 100 + ver->patch;
40}
41class engine_ext;
42typedef oneapi::mkl::rng::philox4x32x10 rng_engine_t;
43/// An enum class representing memory layout. Used by
44/// memory_desc_ext to create a memory with pre-defined layout.
45enum class memory_format_tag { nchw, nhwc, nchw_blocked };
46
47/// An enum class representing RNN data memory layout. Used by
48/// memory_desc_ext to create a memory with pre-defined layout.
49enum class rnn_memory_format_tag { tnc, ntc };
50
51/// A class holding the description of an N-dimensions memory.
52class memory_desc_ext {
53  ::dnnl::memory::desc _desc;
54public:
55  /// Convert dpct::library_data_t to dnnl::memory::data_type.
56  static ::dnnl::memory::data_type to_dnnl_data_type(dpct::library_data_t dt);
57  /// Convert dnnl::memory::data_type to dpct::library_data_t.
58  static dpct::library_data_t
59  to_dpct_library_data_t(::dnnl::memory::data_type dt, unsigned block_size);
60  /// Convert dpct::dnnl::memory_format_tag to dnnl::memory::format_tag.
61  static ::dnnl::memory::format_tag to_dnnl_format_tag(dpct::library_data_t dt,
62                                                       memory_format_tag tag);
63  memory_desc_ext() = default;
64  memory_desc_ext(::dnnl::memory::desc &desc) : _desc(desc) {}
65  memory_desc_ext(::dnnl::memory::desc &&desc) : _desc(std::move(desc)) {}
66  /// Setting a 4D memory with given parameters.
67  /// \param [in] tag Format tag.
68  /// \param [in] dt Data type.
69  /// \param [in] n Number of images.
70  /// \param [in] c Number of channels.
71  /// \param [in] h Height of images.
72  /// \param [in] w Width of images.
73  void set(memory_format_tag tag, dpct::library_data_t dt, int n, int c, int h,
74           int w);
75  /// Setting a 3D RNN data memory with given parameters.
76  /// \param [in] tag RNN data format tag.
77  /// \param [in] dt Data type.
78  /// \param [in] t Number of sequence length.
79  /// \param [in] n Number of batch.
80  /// \param [in] c Height of input channel.
81  void set(rnn_memory_format_tag tag, dpct::library_data_t dt, int t, int n, int c);
82  /// Setting a 4D memory with given parameters.
83  /// \param [in] dt Data type.
84  /// \param [in] n Number of images.
85  /// \param [in] c Number of channels.
86  /// \param [in] h Height of images.
87  /// \param [in] w Width of images.
88  /// \param [in] n_stride Stride between two continuous images.
89  /// \param [in] c_stride Stride between two continuous channels.
90  /// \param [in] h_stride Stride between two continuous rows.
91  /// \param [in] w_stride Stride between two continuous columns.
92  void set(dpct::library_data_t dt, int n, int c, int h, int w, int n_stride,
93           int c_stride, int h_stride, int w_stride);
94  /// Setting a ND memory with given parameters.
95  /// \param [in] dt Data type.
96  /// \param [in] ndims Dimension of the memory.
97  /// \param [in] dims Array of dimension ndims that contain the size of each
98  /// memory dimension. \param [in] strides Array of dimension ndims that
99  /// contain the stride of each memory dimension.
100  void set(dpct::library_data_t dt, int ndims, const int dims[],
101           const int strides[]);
102  /// Setting a ND memory with given parameters.
103  /// \param [in] tag Format tag.
104  /// \param [in] dt Data type.
105  /// \param [in] ndims Dimension of the memory.
106  /// \param [in] dims Array of dimension ndims that contain the size of each
107  /// memory dimension.
108  void set(memory_format_tag tag, dpct::library_data_t dt, int ndims,
109           const int dims[]);
110  /// Getting a ::dnnl::memory::desc from a memory_desc_ext.
111  /// \returns The ::dnnl::memory::desc.
112  const ::dnnl::memory::desc &get_desc() const { return _desc; }
113  /// Setting holding desc with given dnnl memory descriptor.
114  void set_desc(::dnnl::memory::desc desc) { _desc = desc; }
115  /// Getting a size of a memory_desc_ext in bytes.
116  /// \returns The size.
117  size_t get_size() const { return _desc.get_size(); }
118  /// Getting parameters from a 4D memory.
119  /// \param [out] dt Data type.
120  /// \param [out] n Number of images.
121  /// \param [out] c Number of channels.
122  /// \param [out] h Height of images.
123  /// \param [out] w Width of images.
124  /// \param [out] n_stride Stride between two continuous images.
125  /// \param [out] c_stride Stride between two continuous channels.
126  /// \param [out] h_stride Stride between two continuous rows.
127  /// \param [out] w_stride Stride between two continuous columns.
128  void get(dpct::library_data_t *dt, int *n, int *c, int *h, int *w,
129           int *n_stride, int *c_stride, int *h_stride, int *w_stride) const;
130  /// Getting parameters from a 4D memory.
131  /// \param [out] dt Data type.
132  /// \param [out] tag Format tag.
133  /// \param [out] n Number of images.
134  /// \param [out] c Number of channels.
135  /// \param [out] h Height of images.
136  /// \param [out] w Width of images.
137  void get(dpct::library_data_t *dt, memory_format_tag *tag, int *n, int *c,
138           int *h, int *w) const;
139  /// Getting parameters from a 3D RNN data memory.
140  /// \param [out] dt Data type.
141  /// \param [out] tag RNN data format tag.
142  /// \param [out] t Number of sequence length.
143  /// \param [out] n Number of batch.
144  /// \param [out] c Height of input channel.
145  void get(dpct::library_data_t *dt, rnn_memory_format_tag *tag, int *t, int *n,
146           int *c) const;
147  /// Getting parameters from a ND memory.
148  /// \param [in] requested_ndims Requested number of dimensions to get from a
149  /// given memory descriptor.
150  /// \param [out] dt Data type.
151  /// \param [out] ndims Dimension of the memory.
152  /// \param [out] dims Array of dimension requested_ndims that contain the 
153  /// size of each memory dimension.
154  /// \param [out] strides Array of dimension requested_ndims that contain the
155  /// stride of each memory dimension.
156  void get(int requested_ndims, dpct::library_data_t *dt, int *ndims,
157           int dims[], int strides[]) const;
158  /// Getting parameters from a ND memory.
159  /// \param [in] requested_ndims Requested number of dimensions to get from a
160  /// given memory descriptor.
161  /// \param [out] dt Data type.
162  /// \param [out] tag Format tag.
163  /// \param [out] ndims Dimension of the memory.
164  /// \param [out] dims Array of dimension requested_ndims that contain the 
165  /// size of each memory dimension.
166  void get(int requested_ndims, dpct::library_data_t *dt,
167           memory_format_tag *tag, int *ndims, int dims[]) const;
168  /// Getting dims from a ND memory.
169  /// \return The dims.
170  std::vector<int64_t> get_dims() const { return _desc.get_dims(); }
171  /// Getting strides from a ND memory.
172  /// \return The strides.
173  std::vector<int64_t> get_strides() const {
174    return _desc.get_strides();
175  }
176  /// Getting element num from a ND memory.
177  /// \return The element number.
178  size_t get_element_num() const {
179    auto dims = _desc.get_dims();
180    if (dims.empty()) {
181      return 0;
182    }
183    size_t result = 1;
184    for (auto &dim : dims) {
185      result *= dim;
186    }
187    return result;
188  }
189
190  operator bool() const {
191    return bool(_desc);
192  }
193
194  memory_desc_ext &operator=(std::nullptr_t) {
195    _desc.reset(nullptr);
196    return *this;
197  }
198};
199
200/// A class holding description for an activation operation.
201class activation_desc {
202  ::dnnl::algorithm _alg;
203  float _alpha;
204  float _beta;
205
206public:
207  /// Setting an activation descriptor with given parameters.
208  /// \param [in] alg Activation algorithm.
209  /// \param [in] alpha Value of alpha parameter.
210  void set(::dnnl::algorithm alg, float alpha) {
211    _alg = alg;
212    if(alg == ::dnnl::algorithm::eltwise_clip) {
213      _alpha = 0;
214      _beta = alpha;
215    } else {
216      _alpha = alpha;
217    }
218  }
219  /// Getting parameters form an activation descriptor.
220  /// \param [out] alg Activation algorithm.
221  /// \param [out] alpha Value of alpha parameter.
222  void get(::dnnl::algorithm *alg, float *alpha) const {
223    *alg = _alg;
224    if(_alg == ::dnnl::algorithm::eltwise_clip) {
225      *alpha = _beta;
226    } else {
227      *alpha = _alpha;
228    }
229  }
230  /// Setting the alpha parameter of an activation descriptor.
231  /// \param [in] alpha Value of alpha parameter.
232  void set_alpha(float alpha) { _alpha = alpha; }
233  /// Setting the beta parameter of an activation descriptor.
234  /// \param [in] beta Value of beta parameter.
235  void set_beta(float beta) { _beta = beta; }
236  /// Setting the algorithm parameter of an activation descriptor.
237  /// \param [in] alg Activation algorithm.
238  void set_algorithm(::dnnl::algorithm alg) { _alg = alg; }
239  /// Getting the alpha parameter from an activation descriptor.
240  /// \param [out] alpha Value of alpha parameter.
241  float get_alpha() const { return _alpha; }
242  /// Getting the beta parameter from an activation descriptor.
243  /// \param [out] beta Value of beta parameter.
244  float get_beta() const { return _beta; }
245  /// Getting the algorithm parameter from an activation descriptor.
246  /// \param [out] alg Activation algorithm.
247  ::dnnl::algorithm get_algorithm() const { return _alg; }
248};
249
250/// A class holding description for a local response normalization operation.
251class lrn_desc {
252  unsigned int _local_size;
253  float _alpha;
254  float _beta;
255  float _k;
256
257public:
258  /// Setting a local response normalization descriptor with given parameters.
259  /// \param [in] local_size Value of local_size parameter.
260  /// \param [in] alpha Value of alpha parameter.
261  /// \param [in] beta Value of beta parameter.
262  /// \param [in] k Value of k parameter.
263  void set(unsigned int local_size, float alpha, float beta, float k) {
264    _local_size = local_size;
265    _alpha = alpha;
266    _beta = beta;
267    _k = k;
268  }
269  /// Getting parameters form a local response normalization descriptor.
270  /// \param [out] local_size Value of local_size parameter.
271  /// \param [out] alpha Value of alpha parameter.
272  /// \param [out] beta Value of beta parameter.
273  /// \param [out] k Value of k parameter.
274  void get(unsigned int *local_size, float *alpha, float *beta,
275           float *k) const {
276    *local_size = _local_size;
277    *alpha = _alpha;
278    *beta = _beta;
279    *k = _k;
280  }
281  /// Setting the local size parameter of a local response normalization
282  /// descriptor.
283  /// \param [in] local_size Value of local_size parameter.
284  void set_local_size(unsigned int local_size) { _local_size = local_size; }
285  /// Setting the alpha parameter of a local response normalization descriptor.
286  /// \param [in] alpha Value of alpha parameter.
287  void set_alpha(float alpha) { _alpha = alpha; }
288  /// Setting the beta parameter of a local response normalization descriptor.
289  /// \param [in] beta Value of beta parameter.
290  void set_beta(float beta) { _beta = beta; }
291  /// Setting the k parameter of a local response normalization descriptor.
292  /// \param [in] k Value of k parameter.
293  void set_k(float k) { _k = k; }
294  /// Getting the local size parameter from a local response normalization
295  /// descriptor.
296  /// \param [out] local_size Value of local_size parameter.
297  unsigned int get_local_size() const { return _local_size; }
298  /// Getting the alpha parameter from a local response normalization
299  /// descriptor.
300  /// \param [out] alpha Value of alpha parameter.
301  float get_alpha() const { return _alpha; }
302  /// Getting the beta parameter from a local response normalization descriptor.
303  /// \param [out] beta Value of beta parameter.
304  float get_beta() const { return _beta; }
305  /// Getting the k parameter from a local response normalization descriptor.
306  /// \param [out] k Value of k parameter.
307  float get_k() const { return _k; }
308};
309
310/// An enum class representing softmax algorithm.
311enum class softmax_algorithm { normal, log };
312/// An enum class representing softmax mode.
313enum class softmax_mode { instance, channel };
314
315/// A class holding description for a pooling operation.
316class pooling_desc {
317  ::dnnl::algorithm _alg;
318  std::vector<int64_t> _stride;
319  std::vector<int64_t> _kernel;
320  std::vector<int64_t> _padding;
321
322public:
323  /// Setting a 2D pooling descriptor with given parameters.
324  /// \param [in] alg Pooling algorithm.
325  /// \param [in] kernel_h Value of height of kernel.
326  /// \param [in] kernel_w Value of width of kernel.
327  /// \param [in] padding_h Value of height of padding.
328  /// \param [in] padding_w Value of width of padding.
329  /// \param [in] stride_h Value of height of stride.
330  /// \param [in] stride_w Value of width of stride.
331  void set(::dnnl::algorithm alg, int kernel_h, int kernel_w, int padding_h,
332           int padding_w, int stride_h, int stride_w) {
333    _alg = alg;
334    _stride = {stride_h, stride_w};
335    _kernel = {kernel_h, kernel_w};
336    _padding = {padding_h, padding_w};
337  }
338  /// Setting a ND pooling descriptor with given parameters.
339  /// \param [in] alg Pooling algorithm.
340  /// \param [in] ndims Dimension of the pooling operation.
341  /// \param [in] kernel Array of dimension ndims containing the kernel size of
342  /// each dimension.
343  /// \param [in] padding Array of dimension ndims containing the padding size of
344  /// each dimension.
345  /// \param [in] stride Array of dimension ndims containing the stride size of
346  /// each dimension.
347  void set(::dnnl::algorithm alg, int ndims, int kernel[], int padding[],
348           int stride[]) {
349    _alg = alg;
350    _stride = std::vector<int64_t>(stride, stride + ndims);
351    _kernel = std::vector<int64_t>(kernel, kernel + ndims);
352    _padding = std::vector<int64_t>(padding, padding + ndims);
353  }
354  /// Getting parameters from a 2D pooling descriptor.
355  /// \param [out] alg Pooling algorithm.
356  /// \param [out] kernel_h Value of height of kernel.
357  /// \param [out] kernel_w Value of width of kernel.
358  /// \param [out] padding_h Value of height of padding.
359  /// \param [out] padding_w Value of width of padding.
360  /// \param [out] stride_h Value of height of stride.
361  /// \param [out] stride_w Value of width of stride.
362  void get(::dnnl::algorithm *alg, int *kernel_h, int *kernel_w, int *padding_h,
363           int *padding_w, int *stride_h, int *stride_w) const {
364    *alg = _alg;
365    *kernel_h = _kernel[0];
366    *kernel_w = _kernel[1];
367    *padding_h = _padding[0];
368    *padding_w = _padding[1];
369    *stride_h = _stride[0];
370    *stride_w = _stride[1];
371  }
372  /// Getting parameters from a ND pooling descriptor.
373  /// \param [in] requested_ndims Requested number of dimensions to get from a
374  /// given pooling descriptor.
375  /// \param [out] alg Pooling algorithm.
376  /// \param [out] ndims Dimension of the pooling operation.
377  /// \param [out] kernel Array of dimension ndims containing the kernel size of
378  /// each dimension.
379  /// \param [out] padding Array of dimension ndims containing the padding size
380  /// of each dimension.
381  /// \param [out] stride Array of dimension ndims containing the stride size of
382  /// each dimension.
383  void get(int requested_ndims, ::dnnl::algorithm *alg, int *ndims,
384           int kernel[], int padding[], int stride[]) const {
385    *alg = _alg;
386    *ndims = _stride.size();
387    for (int i = 0; i < requested_ndims; i++) {
388      kernel[i] = _kernel[i];
389      padding[i] = _padding[i];
390      stride[i] = _stride[i];
391    }
392  }
393  /// Setting the algorithm parameter of a pooling descriptor.
394  /// \param [in] alg Pooling algorithm.
395  void set_algorithm(::dnnl::algorithm alg) { _alg = alg; }
396  /// Setting the stride parameter of a pooling descriptor.
397  /// \param [in] stride Array of dimension ndims containing the stride size of
398  /// each dimension.
399  void set_stride(const std::vector<int64_t> &stride) { _stride = stride; }
400  /// Setting the kernel parameter of a pooling descriptor.
401  /// \param [in] kernel Array of dimension ndims containing the kernel size of
402  /// each dimension.
403  void set_kernel(const std::vector<int64_t> &kernel) { _kernel = kernel; }
404  /// Setting the padding parameter of a pooling descriptor.
405  /// \param [in] padding Array of dimension ndims containing the padding size
406  /// of each dimension.
407  void set_padding(const std::vector<int64_t> &padding) { _padding = padding; }
408
409  /// Getting the algorithm parameter from a pooling descriptor.
410  /// \param [out] alg Pooling algorithm.
411  ::dnnl::algorithm get_algorithm() const { return _alg; }
412  /// Getting the stride parameter from a pooling descriptor.
413  /// \returns Array of dimension ndims containing the stride size of each
414  /// dimension.
415  const std::vector<int64_t> &get_stride() const { return _stride; }
416  /// Getting the kernel parameter from a pooling descriptor.
417  /// \returns Array of dimension ndims containing the kernel size of each
418  /// dimension.
419  const std::vector<int64_t> &get_kernel() const { return _kernel; }
420  /// Getting the padding parameter from a pooling descriptor.
421  /// \returns Array of dimension ndims containing the padding size of each
422  /// dimension.
423  const std::vector<int64_t> &get_padding() const { return _padding; }
424  /// Getting the output dimensions of a memory after 2D pooling has been
425  /// applied.
426  /// \param [in] desc Input memory descriptor.
427  /// \param [out] out_n Number of images.
428  /// \param [out] out_c Number of channels.
429  /// \param [out] out_h Height of images.
430  /// \param [out] out_w Width of images.
431  void get_forward_output_dim(const memory_desc_ext &desc, int *out_n,
432                              int *out_c, int *out_h, int *out_w) const {
433    auto dims = desc.get_dims();
434    *out_n = dims[0];
435    *out_c = dims[1];
436    *out_h = 1 + (dims[2] + 2 * _padding[0] - _kernel[0]) / _stride[0];
437    *out_w = 1 + (dims[3] + 2 * _padding[1] - _kernel[1]) / _stride[1];
438  }
439  /// Getting the output dimensions of a memory after ND pooling has been
440  /// applied.
441  /// \param [in] desc Input memory descriptor.
442  /// \param [out] ndims Dimension of the memory.
443  /// \param [out] out_dims Array of dimension requested_ndims that contain
444  /// the size of each memory dimension.
445  void get_forward_output_dim(const memory_desc_ext &desc, int ndims,
446                              int out_dims[]) const {
447    assert(ndims >= 4 && "ndims is at least 4.");
448    auto dims = desc.get_dims();
449    out_dims[0] = dims[0];
450    out_dims[1] = dims[1];
451    for (int i = 2; i < ndims; i++) {
452      out_dims[i] =
453          1 + (dims[i] + 2 * _padding[i - 2] - _kernel[i - 2]) / _stride[i - 2];
454    }
455  }
456};
457
458/// An enum class representing reduction operations.
459enum class reduction_op {
460  max,
461  min,
462  sum,
463  mul,
464  mean,
465  amax,
466  mul_no_zeros,
467  norm1,
468  norm2
469};
470
471/// An enum class representing batch normalization mode.
472enum class batch_normalization_mode { per_activation, spatial };
473
474/// An enum class representing batch normalization operations.
475enum class batch_normalization_ops { none, activation, add_activation };
476
477/// An enum class representing binary operations.
478enum class binary_op { add, sub, mul, div, min, max, sqrt, neg };
479
480/// An struct representing convolution algorithm infomation.
481struct convolution_algorithm_info {
482  ::dnnl::algorithm algo = ::dnnl::algorithm::convolution_auto;
483  int status = 0;
484};
485
486/// A class holding description for a convolution operation.
487class convolution_desc {
488  std::vector<int64_t> _strides;
489  std::vector<int64_t> _dilates;
490  std::vector<int64_t> _paddings;
491  int _group_count = 1;
492  ::dnnl::fpmath_mode _math_mode = ::dnnl::fpmath_mode::strict;
493public:
494  /// Setting a group count to be used in the convolution.
495  /// \param [in] group_count Value of group count.
496  void set_group_count(int group_count) { _group_count = group_count; }
497  /// Getting a group count specified in the given convolution descriptor.
498  /// \returns Value of group count.
499  int get_group_count() { return _group_count; }
500  /// Setting floating point math mode to be used in the convolution.
501  /// \param [in] math_mode Value of math_mode.
502  void set_math_mode(::dnnl::fpmath_mode math_mode) { _math_mode = math_mode; }
503  /// Getting floating point math mode specified in the given convolution descriptor.
504  /// \returns Value of math mode.
505  ::dnnl::fpmath_mode get_math_mode() { return _math_mode; }
506  /// Setting a 2D convolution descriptor with given parameters.
507  /// \param [in] padding_h Value of height of padding.
508  /// \param [in] padding_w Value of width of padding.
509  /// \param [in] stride_h Value of height of stride.
510  /// \param [in] stride_w Value of width of stride.
511  /// \param [in] dilate_h Value of height of dilate.
512  /// \param [in] dilate_w Value of width of dilate.
513  void set(int padding_h, int padding_w, int stride_h, int stride_w,
514           int dilate_h, int dilate_w) {
515    _strides = {stride_h, stride_w};
516    _dilates = {dilate_h - 1, dilate_w - 1};
517    _paddings = {padding_h, padding_w};
518  }
519  /// Setting a ND convolution descriptor with given parameters.
520  /// \param [in] ndims Dimension of the convolution operation.
521  /// \param [in] paddings Array of dimension ndims containing the padding size of
522  /// each dimension.
523  /// \param [in] strides Array of dimension ndims containing the stride size of
524  /// each dimension.
525  /// \param [in] dilates Array of dimension ndims containing the kernel size of
526  /// each dimension.
527  void set(int ndims, int paddings[], int strides[], int dilates[]) {
528    _strides = std::vector<int64_t>(strides, strides + ndims);
529    _paddings = std::vector<int64_t>(paddings, paddings + ndims);
530    _dilates = std::vector<int64_t>(dilates, dilates + ndims);
531    for (auto &dilate : _dilates) {
532      dilate--;
533    }
534  }
535  /// Getting parameters from a 2D convolution descriptor.
536  /// \param [out] padding_h Value of height of padding.
537  /// \param [out] padding_w Value of width of padding.
538  /// \param [out] stride_h Value of height of stride.
539  /// \param [out] stride_w Value of width of stride.
540  /// \param [out] dilate_h Value of height of dilate.
541  /// \param [out] dilate_w Value of width of dilate.
542  void get(int *padding_h, int *padding_w, int *stride_h, int *stride_w,
543           int *dilate_h, int *dilate_w) const {
544    *dilate_h = _dilates[0];
545    *dilate_w = _dilates[1];
546    *padding_h = _paddings[0];
547    *padding_w = _paddings[1];
548    *stride_h = _strides[0];
549    *stride_w = _strides[1];
550  }
551  /// Getting parameters from a ND convolution descriptor.
552  /// \param [in] requested_ndims Requested number of dimensions to get from a
553  /// given convolution descriptor.
554  /// \param [out] ndims Dimension of the pooling operation.
555  /// \param [out] paddings Array of dimension ndims containing the padding size
556  /// of each dimension.
557  /// \param [out] strides Array of dimension ndims containing the stride size of
558  /// each dimension.
559  /// \param [out] dilates Array of dimension ndims containing the dilate size of
560  /// each dimension.
561  void get(int requested_ndims, int *ndims, int paddings[], int strides[],
562           int dilates[]) const {
563    *ndims = _strides.size();
564    for (int i = 0; i < requested_ndims; i++) {
565      dilates[i] = _dilates[i];
566      paddings[i] = _paddings[i];
567      strides[i] = _strides[i];
568    }
569  }
570  /// Getting the stride parameter from a convolution descriptor.
571  /// \returns Array of dimension ndims containing the stride size of each
572  /// dimension.
573  const std::vector<int64_t> &get_stride() const { return _strides; }
574  /// Getting the kernel parameter from a convolution descriptor.
575  /// \returns Array of dimension ndims containing the dilate size of each
576  /// dimension.
577  const std::vector<int64_t> &get_dilate() const { return _dilates; }
578  /// Getting the padding parameter from a convolution descriptor.
579  /// \returns Array of dimension ndims containing the padding size of each
580  /// dimension.
581  const std::vector<int64_t> &get_padding() const { return _paddings; }
582  /// Getting the output dimensions of a memory after 2D convolution has been
583  /// applied.
584  /// \param [in] desc Input memory descriptor.
585  /// \param [in] weight_desc Input weight memory descriptor.
586  /// \param [out] out_n Number of images.
587  /// \param [out] out_c Number of channels.
588  /// \param [out] out_h Height of images.
589  /// \param [out] out_w Width of images.
590  void get_forward_output_dim(const memory_desc_ext &desc,
591                              const memory_desc_ext &weight_desc, int *out_n,
592                              int *out_c, int *out_h, int *out_w) const {
593    auto dims = desc.get_dims();
594    auto weight_dims = weight_desc.get_dims();
595    *out_n = dims[0];
596    *out_c = weight_dims[0];
597    *out_h = 1 + (dims[2] + 2 * _paddings[0] -
598                  (1 + ((_dilates[0] + 1) * (weight_dims[2] - 1)))) /
599                     _strides[0];
600    *out_w = 1 + (dims[3] + 2 * _paddings[1] -
601                  (1 + ((_dilates[1] + 1) * (weight_dims[3] - 1)))) /
602                     _strides[1];
603  }
604  /// Getting the output dimensions of a memory after ND convolution has been
605  /// applied.
606  /// \param [in] desc Input memory descriptor.
607  /// \param [in] weight_desc Input weight memory descriptor.
608  /// \param [out] ndims Dimension of the memory.
609  /// \param [out] out_dims Array of dimension requested_ndims that contain
610  /// the size of each memory dimension.
611  void get_forward_output_dim(const memory_desc_ext &desc,
612                              const memory_desc_ext &weight_desc, int ndims,
613                              int out_dims[]) const {
614    assert(ndims >= 4 && "ndims is at least 4.");
615    auto dims = desc.get_dims();
616    auto weight_dims = weight_desc.get_dims();
617    out_dims[0] = dims[0];
618    out_dims[1] = weight_dims[1];
619    for (int i = 2; i < ndims; i++) {
620      out_dims[i] = 1 + (dims[i] + 2 * _paddings[i - 2] -
621                         (1 + ((_dilates[i - 2] + 1) * (weight_dims[i] - 1)))) /
622                            _strides[i - 2];
623    }
624  }
625
626  convolution_desc &operator=(std::nullptr_t) {
627    return *this = convolution_desc();
628  }
629
630  operator bool() const {
631    return !(_strides.size() == 0
632             && _dilates.size() == 0
633             && _paddings.size() == 0);
634  }
635};
636
637/// An enum class representing rnn mode.
638enum class rnn_mode { vanilla_relu, vanilla_tanh, lstm, gru };
639
640/// An enum class representing rnn bias mode.
641enum class rnn_bias_mode { none, single };
642
643/// An enum class representing rnn direction.
644enum class rnn_direction {unidirectional, bidirectional};
645
646/// A class holding description for a RNN operation.
647class rnn_desc {
648  rnn_mode _mode;
649  rnn_bias_mode _bias_mode;
650  rnn_direction _direction;
651  dpct::library_data_t _dt;
652  int _input_size;
653  int _hidden_size;
654  int _projection_size;
655  int _layer_size;
656
657public:
658  void set(rnn_mode mode, rnn_bias_mode bias_mode, rnn_direction direction,
659           dpct::library_data_t dt, int input_size, int hidden_size,
660           int projection_size, int layer_size) {
661    _mode = mode;
662    _bias_mode = bias_mode;
663    _direction = direction;
664    _input_size = input_size;
665    _hidden_size = hidden_size;
666    _projection_size = projection_size;
667    _layer_size = layer_size;
668    _dt = dt;
669  }
670  void get(rnn_mode *mode, rnn_bias_mode *bias_mode, rnn_direction *direction,
671           dpct::library_data_t *dt, int *input_size, int *hidden_size,
672           int *projection_size, int *layer_size) const {
673    *mode = _mode;
674    *bias_mode = _bias_mode;
675    *direction = _direction;
676    *input_size = _input_size;
677    *hidden_size = _hidden_size;
678    *projection_size = _projection_size;
679    *layer_size = _layer_size;
680    *dt = _dt;
681  }
682};
683
684/// A class holding description for a Dropout operation.
685class dropout_desc {
686  struct dropout_desc_imp {
687    float _p = 0.5f;
688    unsigned long long _seed = 1;
689    void *_state = nullptr;
690    std::vector<std::uint8_t> _host_state;
691    rng_engine_t _rng_engine;
692    dropout_desc_imp() : _rng_engine(::dpct::cs::get_default_queue(), 1) {}
693  };
694  std::shared_ptr<dropout_desc_imp> _imp;
695
696  void generate(sycl::queue *q, std::int64_t required_state_size,
697                std::int64_t num, void *buffer) {
698#ifndef __INTEL_MKL__
699    throw std::runtime_error("The oneAPI Math Kernel Library (oneMKL) "
700                             "Interfaces Project does not support this API.");
701#else
702    sycl::event e_gen = oneapi::mkl::rng::generate(
703        oneapi::mkl::rng::bernoulli<std::int32_t>(1.f - _imp->_p),
704        _imp->_rng_engine, num, (std::int32_t *)buffer);
705    sycl::event e_save = q->submit([&](sycl::handler &cgh) {
706      cgh.depends_on(e_gen);
707      cgh.host_task([=] {
708        oneapi::mkl::rng::save_state(_imp->_rng_engine,
709                                     _imp->_host_state.data());
710      });
711    });
712    q->memcpy(_imp->_state, _imp->_host_state.data(), required_state_size,
713              e_save);
714#endif
715  }
716public:
717  operator bool() const {
718    return bool(_imp);
719  }
720  dropout_desc &operator=(std::nullptr_t) {
721    _imp.reset();
722    return *this;
723  }
724  /// Initializing a dropout descriptor.
725  void init(){
726    _imp = std::make_shared<dropout_desc_imp>();
727  }
728  /// Setting a dropout descriptor with given parameters.
729  /// \param [in] engine Engine of the dropout operation.
730  /// \param [in] p Probability of value set to zero.
731  /// \param [in] state Memory that store random generator state.
732  /// \param [in] state_size Required size to store random generator state.
733  /// \param [in] seed Seed to initialize conditions of the generator state.
734  void set(engine_ext &engine, float p, void *state, size_t state_size,
735           unsigned long long seed);
736  /// Getting parameters from a dropout descriptor.
737  /// \param [in] engine Engine of the dropout operation.
738  /// \param [in] p Probability of value set to zero.
739  /// \param [in] state Memory that store random generator state.
740  /// \param [in] seed Seed to initialize conditions of the generator state.
741  void get(float *p, void **states, unsigned long long *seed) const noexcept {
742    *seed = _imp->_seed;
743    *states = _imp->_state;
744    *p = _imp->_p;
745  }
746  /// Getting the probability of value set to zero.
747  /// \returns Probability.
748  float get_probability() const noexcept { return _imp->_p; }
749  /// Restoreing a dropout descriptor from stored state.
750  /// \param [in] engine Engine of the dropout operation.
751  /// \param [in] p Probability of value set to zero.
752  /// \param [in] state Memory that store random generator state.
753  /// \param [in] state_size Required size to store random generator state.
754  /// \param [in] seed Seed to initialize conditions of the generator state.
755  void restore(engine_ext &engine, float p, void *state, size_t state_size,
756               unsigned long long seed);
757  friend class engine_ext;
758};
759
760/// A class holding the oneDNN engine.
761class engine_ext {
762  struct output_argument_info {
763    float _alpha;
764    float _beta;
765    int _name;
766    memory_desc_ext _desc;
767    void *_data;
768    output_argument_info(float alpha, float beta, int name,
769                         memory_desc_ext desc, void *data)
770        : _alpha(alpha), _beta(beta), _name(name), _desc(desc), _data(data) {}
771    output_argument_info(float alpha, float beta, memory_desc_ext desc,
772                         void *data)
773        : _alpha(alpha), _beta(beta), _name(0), _desc(desc), _data(data) {}
774  };
775  struct buffer_info {
776    size_t capacity = 0;
777    uint8_t *buffer = nullptr;
778    size_t usage = 0;
779    sycl::queue q;
780    sycl::event deps;
781    size_t primitive_depth = 0;
782  };
783  struct internal_resource {
784    std::int64_t random_engine_state_size = -1;
785    buffer_info binfo;
786  };
787  std::shared_ptr<::dnnl::engine> _eng = nullptr;
788  std::shared_ptr<::dnnl::stream> _s = nullptr;
789  sycl::queue *_q = nullptr;
790  unsigned int _engine_id = 0;
791  static thread_local unsigned int _engine_count;
792  static thread_local std::map<void *, ::dnnl::memory> _workspace_map;
793  static thread_local std::map<sycl::queue *,
794                               std::shared_ptr<internal_resource>>
795      _internal_resource_cache;
796  static thread_local detail::primitive_cache _primitive_cache;
797  ::dnnl::memory &get_workspace(void *key) { return _workspace_map[key]; }
798  void insert_workspace(void *key, ::dnnl::memory workspace) {
799    _workspace_map[key] = workspace;
800  }
801  const ::dnnl::stream &get_stream() const { return *_s; }
802  const ::dnnl::engine &get_engine() const { return *_eng; }
803
804  void *allocate(const memory_desc_ext &desc, int count = 1);
805  void *allocate(size_t size);
806  std::shared_ptr<internal_resource> get_internal_resource(sycl::queue *q){
807    auto it = _internal_resource_cache.find(_q);
808    if (it == _internal_resource_cache.end()) {
809      return _internal_resource_cache[_q] = std::make_shared<internal_resource>();
810    }
811    return it->second;
812  }
813  void enter_primitive(size_t request_buffer_size = 0) {
814    auto &info = get_internal_resource(_q)->binfo;
815    if (info.primitive_depth == 0) {
816      info.usage = 0;
817      if (request_buffer_size > info.capacity) {
818        if (info.buffer && (info.capacity != 0)) {
819          auto ainfo = info;
820          ainfo.q.submit([=](sycl::handler &cgh) {
821            cgh.depends_on(ainfo.deps);
822            cgh.host_task([=] { sycl::free(ainfo.buffer, ainfo.q); });
823          });
824        }
825        size_t new_buffer_capacity =
826            (std::max)(request_buffer_size, info.capacity * 2);
827        info.capacity = new_buffer_capacity;
828        info.buffer = (uint8_t *)sycl::malloc_device(new_buffer_capacity, *_q);
829        info.q = *_q;
830        info.deps = sycl::event();
831      }
832    }
833    info.primitive_depth++;
834  }
835  sycl::event exit_primitive(const sycl::event &e) {
836    auto &info = get_internal_resource(_q)->binfo;
837    info.primitive_depth--;
838    if ((info.primitive_depth == 0) && info.usage) {
839      info.deps = e;
840    }
841    return e;
842  }
843  ::dnnl::memory::desc
844  compress_spatial_dimensions_to_channel(const ::dnnl::memory::desc &desc);
845  ::dnnl::memory::desc
846  get_bn_scale_bias_mean_var_desc(const ::dnnl::memory::desc &desc,
847                                  batch_normalization_mode mode);
848  sycl::event batch_normalization_backward_internal(
849      batch_normalization_mode mode, float epsilon, float alpha_data,
850      const memory_desc_ext &src_desc, void *src,
851      const memory_desc_ext &diff_dst_desc, void *diff_dst, float beta_data,
852      const memory_desc_ext &diff_src_desc, void *diff_src, float alpha_param,
853      const memory_desc_ext &diff_scale_bias_desc, void *scale, void *bias,
854      float beta_param, void *diff_scale, void *diff_bias,
855      const memory_desc_ext &mean_var_desc, void *saved_mean, void *saved_var);
856  sycl::event batch_normalization_forward_internal(
857      bool is_infer, batch_normalization_mode mode, float epsilon, float factor,
858      float alpha, const memory_desc_ext &src_desc, void *src, float beta,
859      const memory_desc_ext &dst_desc, void *dst,
860      const memory_desc_ext &scale_bias_desc, void *scale, void *bias,
861      const memory_desc_ext &mean_var_desc, void *saved_mean, void *saved_var,
862      void *running_mean, void *running_var);
863  ::dnnl::memory::desc
864  transfer_memory_desc_to_channel_major_format(const ::dnnl::memory::desc &desc);
865  ::dnnl::memory::desc
866  bn_reorder_memory_to_channel_major_format(
867      bool is_input, ::dnnl::memory::desc &desc, void *src, void **cache);
868  ::dnnl::memory::desc
869  transfer_memory_desc_to_format_tag_any(const ::dnnl::memory::desc &desc){
870    return ::dnnl::memory::desc(desc.get_dims(), desc.get_data_type(),
871                                ::dnnl::memory::format_tag::any);
872  }
873  void allocate_and_reorder_memory_to_optimal(::dnnl::memory::desc &from_desc,
874                                              void *&from,
875                                              ::dnnl::memory::desc &to_desc,
876                                              void *&to) {
877    if (from_desc != to_desc) {
878      to = allocate(to_desc);
879      async_reorder(1.f, from_desc, from, 0.f, to_desc, to);
880    }
881  }
882  template <typename primitive_type, typename... args_type>
883  std::pair<detail::primitive_cache_key_type, detail::primitive_and_args>
884  create_primitive_args_or_get(args_type &&...args);
885  template <typename primitive_type>
886  typename primitive_type::primitive_desc
887  get_primitive_desc(::dnnl::primitive *p);
888  template <typename primitive_type, typename... args_type>
889  typename primitive_type::primitive_desc
890  create_primitive_desc(args_type &&...args);
891  template <typename T>
892  void generate_cache_key(std::string &key_buffer, const T &arg);
893  template <typename T, typename... args_type>
894  void generate_cache_key(std::string &key_buffer, const T &first_arg,
895                          const args_type &...args);
896  void insert_arg(std::unordered_map<int, ::dnnl::memory> *args, int name,
897                  const ::dnnl::memory::desc &desc, void *data) {
898    auto it = args->find(name);
899    if (it != args->end()) {
900      it->second.set_data_handle(data);
901    } else {
902      args->insert({name, ::dnnl::memory(desc, *_eng, data)});
903    }
904  }
905  void insert_arg(std::unordered_map<int, ::dnnl::memory> *args, int name,
906                  const ::dnnl::memory &mem) {
907    (*args)[name] = mem;
908  }
909  sycl::event execute_rnn_forward_primitive(
910      rnn_mode mode, ::dnnl::prop_kind kind, ::dnnl::rnn_direction direction,
911      rnn_bias_mode bias_mode, ::dnnl::memory::data_type dt,
912      ::dnnl::memory::format_tag tag, int seq_length, int batch_size, int src_c,
913      int dst_c, int layer_size, int direction_num, int hidden_size,
914      int gate_num, int projection_size, std::vector<void *> &data,
915      std::vector<int> &offset, int iter_num, size_t *weight_size = nullptr,
916      size_t *workspace_size = nullptr, size_t *scratchpad_size = nullptr);
917
918  sycl::event rnn_forward_internal(
919      const rnn_desc &desc, ::dnnl::prop_kind kind,
920      const memory_desc_ext &src_desc, void *src,
921      const memory_desc_ext &dst_desc, void *dst,
922      const memory_desc_ext &iter_desc, void *src_iter, void *dst_iter,
923      const memory_desc_ext &iter_c_desc, void *src_iter_c, void *dst_iter_c,
924      size_t weight_size, void *weight, size_t workspace_size, void *workspace,
925      size_t scratchpad_size, void *scratchpad, bool is_get_execution_args,
926      size_t *weight_size_query, size_t *workspace_size_query,
927      size_t *scratchpad_size_query);
928
929  sycl::event execute_rnn_backward_primitive(
930      rnn_mode mode, ::dnnl::rnn_direction direction, rnn_bias_mode bias_mode,
931      ::dnnl::memory::data_type dt, ::dnnl::memory::format_tag tag,
932      int seq_length, int batch_size, int src_c, int dst_c, int layer_size,
933      int direction_num, int hidden_size, int gate_num, int projection_size,
934      std::vector<void *> &data, std::vector<int> &offset, int iter_num);
935  bool
936  scale_parameter_preprocess(const std::vector<output_argument_info> &args);
937  template <typename primitive_type>
938  sycl::event
939  execute_primitive(const std::pair<detail::primitive_cache_key_type,
940                                    detail::primitive_and_args> &primitive,
941                    const std::vector<output_argument_info> &extra_args = {});
942  template <typename T>
943  sycl::event fill_with_type(sycl::queue *q, void *src, const void *value,
944                             size_t size_with_byte) {
945    return q->fill<T>(static_cast<T *>(src), *static_cast<const T *>(value),
946                      size_with_byte / sizeof(T));
947  }
948  template <typename T>
949  void transform_no_zero_with_type(sycl::queue *q, void *src, void *dst,
950                                   size_t num) {
951    q->submit([&](sycl::handler &cgh) {
952      cgh.parallel_for<::dpct::cs::kernel_name<class zero_to_one, T>>(
953          sycl::range<1>(num), [=](sycl::id<1> idx) {
954            T *src_ptr = static_cast<T *>(src) + idx[0];
955            T *dst_ptr = static_cast<T *>(dst) + idx[0];
956            if (*src_ptr) {
957              *dst_ptr = *src_ptr;
958            } else {
959              *dst_ptr = 1;
960            }
961          });
962    });
963  }
964  void transform_no_zero(const memory_desc_ext &desc, void *src, void *dst);
965  ::dnnl::memory::desc get_group_weight_desc(int group_count,
966                                             const memory_desc_ext &weight_desc);
967  void get_rnn_configuration(const ::dnnl::memory::desc &desc,
968                             rnn_direction direction, rnn_mode mode,
969                             dpct::library_data_t dt, int hidden_size,
970                             ::dnnl::memory::data_type *dnnl_dt,
971                             ::dnnl::memory::format_tag *tag,
972                             int *projection_size, int *output_size,
973                             int *seq_length, int *batch_size,
974                             int *direction_num, int *gate_num);
975public:
976  engine_ext() {}
977  engine_ext(std::nullptr_t) {
978    _eng = nullptr;
979    _s = nullptr;
980    _q = nullptr;
981  }
982  operator bool() const {
983    return bool(_eng) && bool(_s) && bool(_q);
984  }
985  engine_ext &operator=(std::nullptr_t) {
986    _eng = nullptr;
987    _s = nullptr;
988    _q = nullptr;
989    return *this;
990  }
991  /// Creating oneDNN engine.
992  void create_engine() {
993#if USE_DPCT_HELPER
994    _q = &::dpct::cs::get_current_device().default_queue();
995#else
996    _q = ::dpct::cs::get_current_device().default_queue();
997#endif
998    _eng = std::make_shared<::dnnl::engine>(::dnnl::sycl_interop::make_engine(
999        ::dpct::cs::get_current_device(),
1000        ::dpct::cs::get_current_device().get_context()));
1001    _s = std::make_shared<::dnnl::stream>(
1002        ::dnnl::sycl_interop::make_stream(*_eng, *_q));
1003    _engine_id = _engine_count++;
1004  }
1005  /// Setting the user's SYCL queue for an oneDNN engine.
1006  /// \param [in] q Pointer to the SYCL queue.
1007  void set_queue(sycl::queue *q) {
1008    if (!q) {
1009      throw std::runtime_error("set_queue: pointer must not be nullptr.");
1010    }
1011    if (!_eng) {
1012      throw std::runtime_error("set_queue: current engine is invalid.");
1013    }
1014    if (q->get_context() != ::dnnl::sycl_interop::get_context(*_eng)) {
1015      throw std::runtime_error(
1016          "set_queue: queue is mismatch with current engine context.");
1017    }
1018    _q = q;
1019    _s = std::make_shared<::dnnl::stream>(
1020        ::dnnl::sycl_interop::make_stream(*_eng, *_q));
1021  }
1022  /// Retrieving the user's SYCL queue set in the oneDNN engine.
1023  /// \returns Pointer to the SYCL queue.
1024  sycl::queue *get_queue() const { return _q; }
1025  /// Setting all elements of a memory to a given value.
1026  /// \param [in] src_desc Source memory descriptor.
1027  /// \param [in] src Pointer to source data.
1028  /// \param [in] valuePtr Pointer to a single value.
1029  void fill(const memory_desc_ext &src_desc, void *src,
1030                   const void *valuePtr);
1031  /// Coping the scaled data from a memory to another memory with a different
1032  /// description.
1033  /// \param [in] alpha Value to scaling factors used to scale the computed
1034  /// value.
1035  /// \param [in] src_desc Source memory descriptor.
1036  /// \param [in] src Pointer to source data.
1037  /// \param [in] beta Value to scaling factors used to scale the prior value
1038  /// in the destination memory.
1039  /// \param [in] dst_desc Destination memory descriptor.
1040  /// \param [out] dst Pointer to destination data.
1041  void reorder(float alpha, const memory_desc_ext &src_desc, void *src,
1042                      float beta, const memory_desc_ext &dst_desc, void *dst);
1043  /// Scaling all the elements of a memory by a given factor.
1044  /// \param [in] alpha Value to scaling factors.
1045  /// \param [in] src_desc Source memory descriptor.
1046  /// \param [out] src Pointer to source data.
1047  void scale(float alpha, const memory_desc_ext &src_desc, void *src);
1048  /// Adding the scaled values of a memory to another memory.
1049  /// \param [in] alpha Value to scaling factors used to scale the computed
1050  /// value.
1051  /// \param [in] src_desc Source memory descriptor.
1052  /// \param [in] src Pointer to source data.
1053  /// \param [in] beta Value to scaling factors used to scale the prior value
1054  /// in the destination memory.
1055  /// \param [in] dst_desc Destination memory descriptor.
1056  /// \param [out] dst Pointer to destination data.
1057  void sum(float alpha, const memory_desc_ext &src_desc, void *src,
1058                  float beta, const memory_desc_ext &dst_desc, void *dst);
1059  /// Computing a specified activation function value.
1060  /// \param [in] desc Activation descriptor.
1061  /// \param [in] alpha Value to scaling factors used to scale the computed
1062  /// value.
1063  /// \param [in] src_desc Source memory descriptor.
1064  /// \param [in] src Pointer to source data.
1065  /// \param [in] beta Value to scaling factors used to scale the prior value
1066  /// in the destination memory.
1067  /// \param [in] dst_desc Destination memory descriptor.
1068  /// \param [out] dst Pointer to destination data.
1069  void activation_forward(activation_desc &desc, float alpha,
1070                                 const memory_desc_ext &src_desc, void *src,
1071                                 float beta, const memory_desc_ext &dst_desc,
1072                                 void *dst);
1073  /// Computing the gradient of a specified activation function.
1074  /// \param [in] desc Activation descriptor.
1075  /// \param [in] alpha Value to scaling factors used to scale the computed
1076  /// value.
1077  /// \param [in] dst_desc Destination memory descriptor.
1078  /// \param [in] dst Pointer to destination data.
1079  /// \param [in] diff_dst_desc Differential destination memory descriptor.
1080  /// \param [in] diff_dst Pointer to differential destination data.
1081  /// \param [in] src_desc Source memory descriptor.
1082  /// \param [in] src Pointer to source data.
1083  /// \param [in] beta Value to scaling factors used to scale the prior value
1084  /// in the differential destination memory.
1085  /// \param [in] diff_src_desc Differential source memory descriptor.
1086  /// \param [out] diff_src Pointer to differential source data.
1087  void
1088  activation_backward(activation_desc &desc, float alpha,
1089                      const memory_desc_ext &dst_desc, void *dst,
1090                      const memory_desc_ext &diff_dst_desc, void *diff_dst,
1091                      const memory_desc_ext &src_desc, void *src, float beta,
1092                      const memory_desc_ext &diff_src_desc, void *diff_src);
1093  /// Computing a specified pooling function value.
1094  /// \param [in] desc Pooling descriptor.
1095  /// \param [in] alpha Value to scaling factors used to scale the computed
1096  /// value.
1097  /// \param [in] src_desc Source memory descriptor.
1098  /// \param [in] src Pointer to source data.
1099  /// \param [in] beta Value to scaling factors used to scale the prior value
1100  /// in the destination memory.
1101  /// \param [in] dst_desc Destination memory descriptor.
1102  /// \param [out] dst Pointer to destination data.
1103  /// \param [out] workspace Pointer to workspace generated from forward propagation.
1104  void pooling_forward(pooling_desc &desc, float alpha,
1105                              const memory_desc_ext &src_desc, void *src,
1106                              float beta, const memory_desc_ext &dst_desc,
1107                              void *dst, ::dnnl::memory *workspace = nullptr);
1108  /// Computing the gradient of a specified pooling function.
1109  /// \param [in] desc Activation descriptor.
1110  /// \param [in] alpha Value to scaling factors used to scale the computed
1111  /// value.
1112  /// \param [in] dst_desc Destination memory descriptor.
1113  /// \param [in] dst Pointer to destination data.
1114  /// \param [in] diff_dst_desc Differential destination memory descriptor.
1115  /// \param [in] diff_dst Pointer to differential destination data.
1116  /// \param [in] src_desc Source memory descriptor.
1117  /// \param [in] src Pointer to source data.
1118  /// \param [in] beta Value to scaling factors used to scale the prior value
1119  /// in the differential destination memory.
1120  /// \param [in] diff_src_desc Differential source memory descriptor.
1121  /// \param [out] diff_src Pointer to differential
1122  /// source data. 
1123  /// \param [in] workspace Pointer to workspace used for backward
1124  /// propagation.
1125  void pooling_backward(pooling_desc &desc, float alpha,
1126                               const memory_desc_ext &dst_desc, void *dst,
1127                               const memory_desc_ext &diff_dst_desc,
1128                               void *diff_dst, const memory_desc_ext &src_desc,
1129                               void *src, float beta,
1130                               const memory_desc_ext &diff_src_desc,
1131                               void *diff_src,
1132                               ::dnnl::memory *workspace = nullptr);
1133  /// Computing a specified softmax function value.
1134  /// \param [in] alg Softmax algorithm.
1135  /// \param [in] mode Softmax mode.
1136  /// \param [in] alpha Value to scaling factors used to scale the computed
1137  /// value. 
1138  /// \param [in] src_desc Source memory descriptor.
1139  /// \param [in] src Pointer to source data. 
1140  /// \param [in] beta Value to scaling factors used to scale the prior value
1141  /// in the destination memory.
1142  /// \param [in] dst_desc Destination memory descriptor.
1143  /// \param [out] dst Pointer to destination data.
1144  void softmax_forward(softmax_algorithm alg, softmax_mode mode,
1145                              float alpha, const memory_desc_ext &src_desc,
1146                              void *src, float beta,
1147                              const memory_desc_ext &dst_desc, void *dst);
1148  /// Computing the gradient of a specified softmax function.
1149  /// \param [in] alg Softmax algorithm.
1150  /// \param [in] mode Softmax mode.
1151  /// \param [in] alpha Value to scaling factors used to scale the computed
1152  /// value. 
1153  /// \param [in] dst_desc Destination memory descriptor.
1154  /// \param [in] dst Pointer to destination data.
1155  /// \param [in] diff_dst_desc Differential destination memory descriptor.
1156  /// \param [in] diff_dst Pointer to differential destination data.
1157  /// \param [in] beta Value to scaling factors used to scale the prior value
1158  /// in the differential destination memory.
1159  /// \param [in] diff_src_desc Differential source memory descriptor.
1160  /// \param [out] diff_src Pointer to differential source data.
1161  void softmax_backward(softmax_algorithm alg, softmax_mode mode,
1162                               float alpha, const memory_desc_ext &dst_desc,
1163                               void *dst, const memory_desc_ext &diff_dst_desc,
1164                               void *diff_dst, float beta,
1165                               const memory_desc_ext &diff_src_desc,
1166                               void *diff_src);
1167  /// Computing a specified local response normalization function value.
1168  /// \param [in] desc Local response normalization descriptor.
1169  /// \param [in] alpha Value to scaling factors used to scale the computed
1170  /// value.
1171  /// \param [in] src_desc Source memory descriptor.
1172  /// \param [in] src Pointer to source data.
1173  /// \param [in] beta Value to scaling factors used to scale the prior value
1174  /// in the destination memory.
1175  /// \param [in] dst_desc Destination memory descriptor.
1176  /// \param [out] dst Pointer to destination data.
1177  /// \param [out] workspace Pointer to workspace generated from forward
1178  /// propagation.
1179  void lrn_forward(lrn_desc &desc, float alpha,
1180                          const memory_desc_ext &src_desc, void *src,
1181                          float beta, const memory_desc_ext &dst_desc,
1182                          void *dst, ::dnnl::memory *workspace = nullptr);
1183  /// Computing the gradient of a specified local response normalization
1184  /// function.
1185  /// \param [in] desc Local response normalization descriptor.
1186  /// \param [in] alpha Value to scaling factors used to scale the computed value.
1187  /// \param [in] dst_desc Destination memory descriptor.
1188  /// \param [in] dst Pointer to destination data.
1189  /// \param [in] diff_dst_desc Differential destination memory descriptor.
1190  /// \param [in] diff_dst Pointer to differential destination data.
1191  /// \param [in] src_desc Source memory descriptor.
1192  /// \param [in] src Pointer to source data.
1193  /// \param [in] beta Value to scaling factors used to scale the prior value
1194  /// in the differential destination memory.
1195  /// \param [in] diff_src_desc Differential source memory descriptor.
1196  /// \param [out] diff_src Pointer to differential source data.
1197  /// \param [in] workspace Pointer to workspace used for backward propagation.
1198  void lrn_backward(lrn_desc &desc, float alpha,
1199                           const memory_desc_ext &dst_desc, void *dst,
1200                           const memory_desc_ext &diff_dst_desc, void *diff_dst,
1201                           const memory_desc_ext &src_desc, void *src,
1202                           float beta, const memory_desc_ext &diff_src_desc,
1203                           void *diff_src, ::dnnl::memory *workspace = nullptr);
1204  /// Setting all elements of a memory to a given value asynchronously.
1205  /// \param [in] src_desc Source memory descriptor.
1206  /// \param [in] src Pointer to source data.
1207  /// \param [in] valuePtr Pointer to a single value.
1208  /// \returns An event representing the fill operations.
1209  sycl::event async_fill(const memory_desc_ext &src_desc, void *src,
1210                   const void *valuePtr);
1211  /// Coping the scaled data from a memory to another memory with a different
1212  /// description asynchronously.
1213  /// \param [in] alpha Value to scaling factors used to scale the computed
1214  /// value.
1215  /// \param [in] src_desc Source memory descriptor.
1216  /// \param [in] src Pointer to source data.
1217  /// \param [in] beta Value to scaling factors used to scale the prior value
1218  /// in the destination memory.
1219  /// \param [in] dst_desc Destination memory descriptor.
1220  /// \param [out] dst Pointer to destination data.
1221  /// \returns An event representing the reorder operations.
1222  sycl::event async_reorder(float alpha, const memory_desc_ext &src_desc, void *src,
1223                      float beta, const memory_desc_ext &dst_desc, void *dst);
1224  /// Scaling all the elements of a memory by a given factor asynchronously.
1225  /// \param [in] alpha Value to scaling factors.
1226  /// \param [in] src_desc Source memory descriptor.
1227  /// \param [out] src Pointer to source data.
1228  /// \returns An event representing the scale operations.
1229  sycl::event async_scale(float alpha, const memory_desc_ext &src_desc, void *src);
1230  /// Adding the scaled values of a memory to another memory asynchronously.
1231  /// \param [in] alpha Value to scaling factors used to scale the computed
1232  /// value.
1233  /// \param [in] src_desc Source memory descriptor.
1234  /// \param [in] src Pointer to source data.
1235  /// \param [in] beta Value to scaling factors used to scale the prior value
1236  /// in the destination memory.
1237  /// \param [in] dst_desc Destination memory descriptor.
1238  /// \param [out] dst Pointer to destination data.
1239  /// \returns An event representing the sum operations.
1240  sycl::event async_sum(float alpha, const memory_desc_ext &src_desc, void *src,
1241                  float beta, const memory_desc_ext &dst_desc, void *dst);
1242
1243  /// Perform specified binary operation asynchronously.
1244  /// \param [in] op Specified binary operation.
1245  /// \param [in] alpha_0 Value to scaling factors used to scale the src_0
1246  /// value.
1247  /// \param [in] src_desc_0 Source 0 memory descriptor.
1248  /// \param [in] src_0 Pointer to source 0 data.
1249  /// \param [in] alpha_1 Value to scaling factors used to scale the src_1
1250  /// value.
1251  /// \param [in] src_desc_1 Source 1 memory descriptor.
1252  /// \param [in] src_1 Pointer to source 1 data.
1253  /// \param [in] beta Value to scaling factors used to scale the prior value
1254  /// in the destination memory.
1255  /// \param [in] dst_desc Destination memory descriptor.
1256  /// \param [out] dst Pointer to destination data.
1257  /// \returns An event representing the binary operations.
1258  sycl::event async_binary(binary_op op, float alpha_0,
1259                     const memory_desc_ext &src_desc_0, void *src_0,
1260                     float alpha_1, const memory_desc_ext &src_desc_1,
1261                     void *src_1, float beta, const memory_desc_ext &dst_desc,
1262                     void *dst);
1263
1264  /// Perform specified binary operation asynchronously.
1265  /// \param [in] op Specified reduction operation.
1266  /// \param [in] alpha Value to scaling factors used to scale the data
1267  /// value.
1268  /// \param [in] src_desc Source memory descriptor.
1269  /// \param [in] src Pointer to source data.
1270  /// \param [in] beta Value to scaling factors used to scale the prior value
1271  /// in the destination memory.
1272  /// \param [in] dst_desc Destination memory descriptor.
1273  /// \param [out] dst Pointer to destination data.
1274  /// \returns An event representing the reduction operations.
1275  sycl::event async_reduction(reduction_op op, float alpha,
1276                        const memory_desc_ext &src_desc, void *src, float beta,
1277                        const memory_desc_ext &dst_desc, void *dst);
1278  /// Computing a specified activation function value asynchronously.
1279  /// \param [in] desc Activation descriptor.
1280  /// \param [in] alpha Value to scaling factors used to scale the computed
1281  /// value.
1282  /// \param [in] src_desc Source memory descriptor.
1283  /// \param [in] src Pointer to source data.
1284  /// \param [in] beta Value to scaling factors used to scale the prior value
1285  /// in the destination memory.
1286  /// \param [in] dst_desc Destination memory descriptor.
1287  /// \param [out] dst Pointer to destination data.
1288  /// \returns An event representing the activation forward operations.
1289  sycl::event async_activation_forward(activation_desc &desc, float alpha,
1290                                 const memory_desc_ext &src_desc, void *src,
1291                                 float beta, const memory_desc_ext &dst_desc,
1292                                 void *dst);
1293  /// Computing the gradient of a specified activation function asynchronously.
1294  /// \param [in] desc Activation descriptor.
1295  /// \param [in] alpha Value to scaling factors used to scale the computed
1296  /// value.
1297  /// \param [in] dst_desc Destination memory descriptor.
1298  /// \param [in] dst Pointer to destination data.
1299  /// \param [in] diff_dst_desc Differential destination memory descriptor.
1300  /// \param [in] diff_dst Pointer to differential destination data.
1301  /// \param [in] src_desc Source memory descriptor.
1302  /// \param [in] src Pointer to source data.
1303  /// \param [in] beta Value to scaling factors used to scale the prior value
1304  /// in the differential destination memory.
1305  /// \param [in] diff_src_desc Differential source memory descriptor.
1306  /// \param [out] diff_src Pointer to differential source data.
1307  /// \returns An event representing the activation backward operations.
1308  sycl::event
1309  async_activation_backward(activation_desc &desc, float alpha,
1310                      const memory_desc_ext &dst_desc, void *dst,
1311                      const memory_desc_ext &diff_dst_desc, void *diff_dst,
1312                      const memory_desc_ext &src_desc, void *src, float beta,
1313                      const memory_desc_ext &diff_src_desc, void *diff_src);
1314  /// Computing a specified pooling function value asynchronously.
1315  /// \param [in] desc Pooling descriptor.
1316  /// \param [in] alpha Value to scaling factors used to scale the computed
1317  /// value.
1318  /// \param [in] src_desc Source memory descriptor.
1319  /// \param [in] src Pointer to source data.
1320  /// \param [in] beta Value to scaling factors used to scale the prior value
1321  /// in the destination memory.
1322  /// \param [in] dst_desc Destination memory descriptor.
1323  /// \param [out] dst Pointer to destination data.
1324  /// \param [out] workspace Pointer to workspace generated from forward propagation.
1325  /// \returns An event representing the pooling forward operations.
1326  sycl::event async_pooling_forward(pooling_desc &desc, float alpha,
1327                              const memory_desc_ext &src_desc, void *src,
1328                              float beta, const memory_desc_ext &dst_desc,
1329                              void *dst, ::dnnl::memory *workspace = nullptr);
1330  /// Computing the gradient of a specified pooling function asynchronously.
1331  /// \param [in] desc Activation descriptor.
1332  /// \param [in] alpha Value to scaling factors used to scale the computed
1333  /// value.
1334  /// \param [in] dst_desc Destination memory descriptor.
1335  /// \param [in] dst Pointer to destination data.
1336  /// \param [in] diff_dst_desc Differential destination memory descriptor.
1337  /// \param [in] diff_dst Pointer to differential destination data.
1338  /// \param [in] src_desc Source memory descriptor.
1339  /// \param [in] src Pointer to source data.
1340  /// \param [in] beta Value to scaling factors used to scale the prior value
1341  /// in the differential destination memory.
1342  /// \param [in] diff_src_desc Differential source memory descriptor.
1343  /// \param [out] diff_src Pointer to differential
1344  /// source data. 
1345  /// \param [in] workspace Pointer to workspace used for backward
1346  /// propagation.
1347  /// \returns An event representing the pooling backward operations.
1348  sycl::event async_pooling_backward(pooling_desc &desc, float alpha,
1349                               const memory_desc_ext &dst_desc, void *dst,
1350                               const memory_desc_ext &diff_dst_desc,
1351                               void *diff_dst, const memory_desc_ext &src_desc,
1352                               void *src, float beta,
1353                               const memory_desc_ext &diff_src_desc,
1354                               void *diff_src,
1355                               ::dnnl::memory *workspace = nullptr);
1356  /// Computing a specified softmax function value asynchronously.
1357  /// \param [in] alg Softmax algorithm.
1358  /// \param [in] mode Softmax mode.
1359  /// \param [in] alpha Value to scaling factors used to scale the computed
1360  /// value. 
1361  /// \param [in] src_desc Source memory descriptor.
1362  /// \param [in] src Pointer to source data. 
1363  /// \param [in] beta Value to scaling factors used to scale the prior value
1364  /// in the destination memory.
1365  /// \param [in] dst_desc Destination memory descriptor.
1366  /// \param [out] dst Pointer to destination data.
1367  /// \returns An event representing the softmax forward operations.
1368  sycl::event async_softmax_forward(softmax_algorithm alg, softmax_mode mode,
1369                              float alpha, const memory_desc_ext &src_desc,
1370                              void *src, float beta,
1371                              const memory_desc_ext &dst_desc, void *dst);
1372  /// Computing the gradient of a specified softmax function asynchronously.
1373  /// \param [in] alg Softmax algorithm.
1374  /// \param [in] mode Softmax mode.
1375  /// \param [in] alpha Value to scaling factors used to scale the computed
1376  /// value. 
1377  /// \param [in] dst_desc Destination memory descriptor.
1378  /// \param [in] dst Pointer to destination data.
1379  /// \param [in] diff_dst_desc Differential destination memory descriptor.
1380  /// \param [in] diff_dst Pointer to differential destination data.
1381  /// \param [in] beta Value to scaling factors used to scale the prior value
1382  /// in the differential destination memory.
1383  /// \param [in] diff_src_desc Differential source memory descriptor.
1384  /// \param [out] diff_src Pointer to differential source data.
1385  /// \returns An event representing the softmax backward operations.
1386  sycl::event async_softmax_backward(softmax_algorithm alg, softmax_mode mode,
1387                               float alpha, const memory_desc_ext &dst_desc,
1388                               void *dst, const memory_desc_ext &diff_dst_desc,
1389                               void *diff_dst, float beta,
1390                               const memory_desc_ext &diff_src_desc,
1391                               void *diff_src);
1392  /// Computing a specified local response normalization function value
1393  /// asynchronously.
1394  /// \param [in] desc Local response normalization descriptor.
1395  /// \param [in] alpha Value to scaling factors used to scale the computed
1396  /// value.
1397  /// \param [in] src_desc Source memory descriptor.
1398  /// \param [in] src Pointer to source data.
1399  /// \param [in] beta Value to scaling factors used to scale the prior value
1400  /// in the destination memory.
1401  /// \param [in] dst_desc Destination memory descriptor.
1402  /// \param [out] dst Pointer to destination data.
1403  /// \param [out] workspace Pointer to workspace generated from forward
1404  /// propagation.
1405  /// \returns An event representing the lrn forward operations.
1406  sycl::event async_lrn_forward(lrn_desc &desc, float alpha,
1407                          const memory_desc_ext &src_desc, void *src,
1408                          float beta, const memory_desc_ext &dst_desc,
1409                          void *dst, ::dnnl::memory *workspace = nullptr);
1410  /// Computing the gradient of a specified local response normalization
1411  /// function asynchronously.
1412  /// \param [in] desc Local response normalization descriptor.
1413  /// \param [in] alpha Value to scaling factors used to scale the computed value.
1414  /// \param [in] dst_desc Destination memory descriptor.
1415  /// \param [in] dst Pointer to destination data.
1416  /// \param [in] diff_dst_desc Differential destination memory descriptor.
1417  /// \param [in] diff_dst Pointer to differential destination data.
1418  /// \param [in] src_desc Source memory descriptor.
1419  /// \param [in] src Pointer to source data.
1420  /// \param [in] beta Value to scaling factors used to scale the prior value
1421  /// in the differential destination memory.
1422  /// \param [in] diff_src_desc Differential source memory descriptor.
1423  /// \param [out] diff_src Pointer to differential source data.
1424  /// \param [in] workspace Pointer to workspace used for backward propagation.
1425  /// \returns An event representing the lrn backward operations.
1426  sycl::event async_lrn_backward(lrn_desc &desc, float alpha,
1427                           const memory_desc_ext &dst_desc, void *dst,
1428                           const memory_desc_ext &diff_dst_desc, void *diff_dst,
1429                           const memory_desc_ext &src_desc, void *src,
1430                           float beta, const memory_desc_ext &diff_src_desc,
1431                           void *diff_src, ::dnnl::memory *workspace = nullptr);
1432
1433  /// Derives a memory descriptor for the batch normalization scale, bias, mean,
1434  /// variance from the source memory descriptor and batch normalization mode.
1435  /// \param [out] desc Derived memory descriptor.
1436  /// \param [in] src_desc Source memory descriptor.
1437  /// \param [in] mode Batch normalization mode.
1438  static void derive_batch_normalization_memory_desc(memory_desc_ext &desc,
1439                                              const memory_desc_ext &src_desc,
1440                                              batch_normalization_mode mode);
1441
1442  /// Derives a memory descriptor for the batch normalization scale, bias, mean,
1443  /// variance from the source memory descriptor and batch normalization mode.
1444  /// \param [out] scale_bias_desc Derived scale and bias memory descriptor.
1445  /// \param [out] mean_var_desc Derived mean and var memory descriptor.
1446  /// \param [in] src_desc Source memory descriptor.
1447  /// \param [in] mode Batch normalization mode.
1448  static void derive_batch_normalization_memory_desc(memory_desc_ext &scale_bias_desc,
1449                                             memory_desc_ext &mean_var_desc,
1450                                             const memory_desc_ext &src_desc,
1451                                             batch_normalization_mode mode);
1452
1453  /// Get the size of workspace that needed by batch normalization. The data stored
1454  /// in workspace must be preserved between forward and backward.
1455  /// \param [in] ops Batch normalization operation mode. This mode can set to
1456  /// perform only batch normalization, or batch normalization followed by
1457  /// activation, or batch normalization followed by element-wise addition and
1458  /// activation.
1459  /// \param [in] src_desc Source memory descriptor.
1460  /// \returns Size of workspace.
1461  size_t get_batch_normalization_workspace_size(
1462    batch_normalization_ops ops, const memory_desc_ext &src_desc);
1463
1464  /// Computing a specified batch normalization inference stage function value
1465  /// asynchronously.
1466  /// \param [in] mode Batch normalization mode.
1467  /// \param [in] epsilon Epsilon value used in computation.
1468  /// \param [in] alpha Value to scaling factors used to scale the computed
1469  /// value.
1470  /// \param [in] src_desc Source memory descriptor.
1471  /// \param [in] src Pointer to source data.
1472  /// \param [in] beta Value to scaling factors used to scale the prior value
1473  /// in the destination memory.
1474  /// \param [in] dst_desc Destination memory descriptor.
1475  /// \param [out] dst Pointer to destination data.
1476  /// \param [in] scale_bias_mean_var_desc Scale, bias, mean, variance memory
1477  /// descriptor.
1478  /// \param [in] scale Pointer to scale data.
1479  /// \param [in] bias Pointer to bias data.
1480  /// \param [in] mean Pointer to mean data.
1481  /// \param [in] var Pointer to variance data.
1482  /// \returns An event representing the batch normalization forward operations.
1483  sycl::event async_batch_normalization_forward_inference(
1484      batch_normalization_mode mode, float epsilon, float alpha,
1485      const memory_desc_ext &src_desc, void *src, float beta,
1486      const memory_desc_ext &dst_desc, void *dst,
1487      const memory_desc_ext &scale_bias_mean_var_desc, void *scale, void *bias,
1488      void *mean, void *var);
1489
1490  /// Computing a specified batch normalization inference stage function value
1491  /// asynchronously.
1492  /// \param [in] mode Batch normalization mode.
1493  /// \param [in] ops Batch normalization operation mode. This mode can set to
1494  /// perform only batch normalization, or batch normalization followed by
1495  /// activation, or batch normalization followed by element-wise addition and
1496  /// activation.
1497  /// \param [in] adesc Activation operation descriptor.
1498  /// \param [in] epsilon Epsilon value used in computation.
1499  /// \param [in] alpha Value to scaling factors used to scale the computed
1500  /// value.
1501  /// \param [in] src_desc Source memory descriptor.
1502  /// \param [in] src Pointer to source data.
1503  /// \param [in] beta Value to scaling factors used to scale the prior value
1504  /// in the destination memory.
1505  /// \param [in] dst_desc Destination memory descriptor.
1506  /// \param [out] dst Pointer to destination data.
1507  /// \param [in] summand_desc Summand memory descriptor.
1508  /// \param [in] summand Pointer to summand data.
1509  /// \param [in] scale_bias_desc Scale, bias memory descriptor.
1510  /// \param [in] scale Pointer to scale data.
1511  /// \param [in] bias Pointer to bias data.
1512  /// \param [in] mean_var_desc Mean, variance memory descriptor.
1513  /// \param [in] mean Pointer to mean data.
1514  /// \param [in] var Pointer to variance data.
1515  /// \returns An event representing the batch normalization forward operations.
1516  sycl::event async_batch_normalization_forward_inference(
1517      batch_normalization_mode mode, batch_normalization_ops ops,
1518      activation_desc &adesc, float epsilon, float alpha,
1519      const memory_desc_ext &src_desc, void *src, float beta,
1520      const memory_desc_ext &dst_desc, void *dst,
1521      const memory_desc_ext &summand_desc, void *summand,
1522      const memory_desc_ext &scale_bias_desc, void *scale, void *bias,
1523      const memory_desc_ext &mean_var_desc, void *mean, void *var);
1524
1525  /// Computing a specified batch normalization training stage function value
1526  /// asynchronously.
1527  /// \param [in] mode Batch normalization mode.
1528  /// \param [in] epsilon Epsilon value used in computation.
1529  /// \param [in] factor Factor value used in running mean and variance
1530  /// computation.
1531  /// \param [in] alpha Value to scaling factors used to scale the computed
1532  /// value.
1533  /// \param [in] src_desc Source memory descriptor.
1534  /// \param [in] src Pointer to source data.
1535  /// \param [in] beta Value to scaling factors used to scale the prior value
1536  /// in the destination memory.
1537  /// \param [in] dst_desc Destination memory descriptor.
1538  /// \param [out] dst Pointer to destination data.
1539  /// \param [in] scale_bias_mean_var_desc Scale, bias, mean, variance memory
1540  /// descriptor.
1541  /// \param [in] scale Pointer to scale data.
1542  /// \param [in] bias Pointer to bias data.
1543  /// \param [out] running_mean Pointer to running mean data.
1544  /// \param [out] running_var Pointer to running variance data.
1545  /// \param [out] saved_mean Pointer to optional cache to save mean data.
1546  /// \param [out] saved_var Pointer to optional cache to save variance data.
1547  /// \returns An event representing the batch normalization forward operations.
1548  sycl::event async_batch_normalization_forward_training(
1549      batch_normalization_mode mode, float epsilon, float factor, float alpha,
1550      const memory_desc_ext &src_desc, void *src, float beta,
1551      const memory_desc_ext &dst_desc, void *dst,
1552      const memory_desc_ext &scale_bias_mean_var_desc, void *scale, void *bias,
1553      void *running_mean, void *running_var, void *saved_mean, void *saved_var);
1554
1555  /// Computing a specified batch normalization training stage function value
1556  /// asynchronously.
1557  /// \param [in] mode Batch normalization mode.
1558  /// \param [in] ops Batch normalization operation mode. This mode can set to
1559  /// perform only batch normalization, or batch normalization followed by
1560  /// activation, or batch normalization followed by element-wise addition and
1561  /// activation.
1562  /// \param [in] adesc Activation operation descriptor.
1563  /// \param [in] epsilon Epsilon value used in computation.
1564  /// \param [in] factor Factor value used in running mean and variance
1565  /// computation.
1566  /// \param [in] alpha Value to scaling factors used to scale the computed
1567  /// value.
1568  /// \param [in] src_desc Source memory descriptor.
1569  /// \param [in] src Pointer to source data.
1570  /// \param [in] beta Value to scaling factors used to scale the prior value
1571  /// in the destination memory.
1572  /// \param [in] dst_desc Destination memory descriptor.
1573  /// \param [out] dst Pointer to destination data.
1574  /// \param [in] summand_desc Summand memory descriptor.
1575  /// \param [in] summand Pointer to summand data.
1576  /// \param [in] scale_bias_mean_var_desc Scale, bias, mean, variance memory
1577  /// descriptor.
1578  /// \param [in] scale Pointer to scale data.
1579  /// \param [in] bias Pointer to bias data.
1580  /// \param [out] running_mean Pointer to running mean data.
1581  /// \param [out] running_var Pointer to running variance data.
1582  /// \param [out] saved_mean Pointer to optional cache to save mean data.
1583  /// \param [out] saved_var Pointer to optional cache to save variance data.
1584  /// \param [in] workspace_size Size of workspace.
1585  /// \param [out] workspace Pointer to workspace generated from forward
1586  /// propagation.
1587  /// \returns An event representing the batch normalization forward operations.
1588  sycl::event async_batch_normalization_forward_training(
1589      batch_normalization_mode mode, batch_normalization_ops ops,
1590      activation_desc &adesc, float epsilon, float factor, float alpha,
1591      const memory_desc_ext &src_desc, void *src, float beta,
1592      const memory_desc_ext &dst_desc, void *dst,
1593      const memory_desc_ext &summand_desc, void *summand,
1594      const memory_desc_ext &scale_bias_mean_var_desc, void *scale, void *bias,
1595      void *running_mean, void *running_var, void *saved_mean, void *saved_var,
1596      size_t workspace_size, void *workspace);
1597
1598  /// Computing a specified batch normalization training stage function value
1599  /// asynchronously.
1600  /// \param [in] mode Batch normalization mode.
1601  /// \param [in] ops Batch normalization operation mode. This mode can set to
1602  /// perform only batch normalization, or batch normalization followed by
1603  /// activation, or batch normalization followed by element-wise addition and
1604  /// activation.
1605  /// \param [in] adesc Activation operation descriptor.
1606  /// \param [in] epsilon Epsilon value used in computation.
1607  /// \param [in] factor Factor value used in running mean and variance
1608  /// computation.
1609  /// \param [in] alpha Value to scaling factors used to scale the computed
1610  /// value.
1611  /// \param [in] src_desc Source memory descriptor.
1612  /// \param [in] src Pointer to source data.
1613  /// \param [in] beta Value to scaling factors used to scale the prior value
1614  /// in the destination memory.
1615  /// \param [in] dst_desc Destination memory descriptor.
1616  /// \param [out] dst Pointer to destination data.
1617  /// \param [in] summand_desc Summand memory descriptor.
1618  /// \param [in] summand Pointer to summand data.
1619  /// \param [in] scale_bias_desc Scale, bias memory descriptor.
1620  /// \param [in] scale Pointer to scale data.
1621  /// \param [in] bias Pointer to bias data.
1622  /// \param [in] mean_var_desc Mean, variance memory descriptor.
1623  /// \param [out] running_mean Pointer to running mean data.
1624  /// \param [out] running_var Pointer to running variance data.
1625  /// \param [out] saved_mean Pointer to optional cache to save mean data.
1626  /// \param [out] saved_var Pointer to optional cache to save variance data.
1627  /// \param [in] workspace_size Size of workspace.
1628  /// \param [out] workspace Pointer to workspace generated from forward
1629  /// propagation.
1630  /// \returns An event representing the batch normalization forward operations.
1631  sycl::event async_batch_normalization_forward_training(
1632      batch_normalization_mode mode, batch_normalization_ops ops,
1633      activation_desc &adesc, float epsilon, float factor, float alpha,
1634      const memory_desc_ext &src_desc, void *src, float beta,
1635      const memory_desc_ext &dst_desc, void *dst,
1636      const memory_desc_ext &summand_desc, void *summand,
1637      const memory_desc_ext &scale_bias_desc, void *scale, void *bias,
1638      const memory_desc_ext &mean_var_desc, void *running_mean, void *running_var,
1639      void *saved_mean, void *saved_var, size_t workspace_size, void *workspace);
1640
1641  /// Computing the gradient of a specified batch normalization function asynchronously.
1642  /// \param [in] mode Batch normalization mode.
1643  /// \param [in] epsilon Epsilon value used in computation.
1644  /// \param [in] alpha_data Value to scaling factors used to scale the computed
1645  /// data value.
1646  /// \param [in] src_desc Source memory descriptor.
1647  /// \param [in] src Pointer to source data.
1648  /// \param [in] diff_dst_desc Differential destination memory descriptor.
1649  /// \param [in] diff_dst Pointer to differential destination data.
1650  /// \param [in] beta_data Value to scaling factors used to scale the prior value
1651  /// in the data memory.
1652  /// \param [in] diff_src_desc Differential source memory descriptor.
1653  /// \param [out] diff_src Pointer to differential source data.
1654  /// \param [in] alpha_param Value to scaling factors used to scale the computed
1655  /// parameter value.
1656  /// \param [in] diff_scale_bias_mean_var_desc Differential scale, bias, mean,
1657  /// variance memory descriptor.
1658  /// \param [in] scale Pointer to scale data.
1659  /// \param [in] beta_param Value to scaling factors used to scale the prior value
1660  /// in the parameter memory.
1661  /// \param [in] diff_scale Pointer to differential scale data.
1662  /// \param [in] diff_bias Pointer to differential bias data.
1663  /// \param [in] saved_mean Pointer to optional cache saved mean data in forward.
1664  /// \param [in] saved_var Pointer to optional cache saved variance data in forward.
1665  /// \returns An event representing the batch normalization backward operations.
1666  sycl::event async_batch_normalization_backward(
1667      batch_normalization_mode mode, float epsilon, float alpha_data,
1668      const memory_desc_ext &src_desc, void *src,
1669      const memory_desc_ext &diff_dst_desc, void *diff_dst, float beta_data,
1670      const memory_desc_ext &diff_src_desc, void *diff_src, float alpha_param,
1671      const memory_desc_ext &diff_scale_bias_mean_var_desc, void *scale,
1672      float beta_param, void *diff_scale, void *diff_bias, void *saved_mean,
1673      void *saved_var);
1674
1675  /// Computing the gradient of a specified batch normalization function
1676  /// asynchronously.
1677  /// \param [in] mode Batch normalization mode.
1678  /// \param [in] ops Batch normalization operation mode. This mode can set to
1679  /// perform only batch normalization, or batch normalization followed by
1680  /// activation, or batch normalization followed by element-wise addition and
1681  /// activation.
1682  /// \param [in] adesc Activation operation descriptor.
1683  /// \param [in] epsilon Epsilon value used in computation.
1684  /// \param [in] alpha_data Value to scaling factors used to scale the computed
1685  /// data value.
1686  /// \param [in] src_desc Source memory descriptor.
1687  /// \param [in] src Pointer to source data.
1688  /// \param [in] dst_desc Destination memory descriptor.
1689  /// \param [in] dst Pointer to destination data.
1690  /// \param [in] diff_dst_desc Differential destination memory descriptor.
1691  /// \param [in] diff_dst Pointer to differential destination data.
1692  /// \param [in] beta_data Value to scaling factors used to scale the prior value
1693  /// in the data memory.
1694  /// \param [in] diff_src_desc Differential source memory descriptor.
1695  /// \param [out] diff_src Pointer to differential source data.
1696  /// \param [in] diff_summand_desc Differential summand memory descriptor.
1697  /// \param [out] diff_summand Pointer to differential summand data.
1698  /// \param [in] alpha_param Value to scaling factors used to scale the computed
1699  /// parameter value.
1700  /// \param [in] diff_scale_bias_mean_var_desc Differential scale, bias, mean,
1701  /// variance memory descriptor.
1702  /// \param [in] scale Pointer to scale data.
1703  /// \param [in] bias Pointer to bias data.
1704  /// \param [in] beta_param Value to scaling factors used to scale the prior value
1705  /// in the parameter memory.
1706  /// \param [out] diff_scale Pointer to differential scale data.
1707  /// \param [out] diff_bias Pointer to differential bias data.
1708  /// \param [in] saved_mean Pointer to optional cache saved mean data in forward.
1709  /// \param [in] saved_var Pointer to optional cache saved variance data in forward.
1710  /// \param [in] workspace_size Size of workspace.
1711  /// \param [in] workspace Pointer to workspace used for backward propagation.
1712  /// \returns An event representing the batch normalization backward operations.
1713  sycl::event async_batch_normalization_backward(
1714      batch_normalization_mode mode, batch_normalization_ops ops,
1715      activation_desc &adesc, float epsilon, float alpha_data,
1716      const memory_desc_ext &src_desc, void *src,
1717      const memory_desc_ext &dst_desc, void *dst,
1718      const memory_desc_ext &diff_dst_desc, void *diff_dst, float beta_data,
1719      const memory_desc_ext &diff_src_desc, void *diff_src,
1720      const memory_desc_ext &diff_summand_desc, void *diff_summand,
1721      float alpha_param, const memory_desc_ext &diff_scale_bias_mean_var_desc,
1722      void *scale, void *bias, float beta_param, void *diff_scale,
1723      void *diff_bias, void *saved_mean, void *saved_var,
1724      size_t workspace_size, void *workspace);
1725
1726  /// Computing the gradient of a specified batch normalization function
1727  /// asynchronously.
1728  /// \param [in] mode Batch normalization mode.
1729  /// \param [in] ops Batch normalization operation mode. This mode can set to
1730  /// perform only batch normalization, or batch normalization followed by
1731  /// activation, or batch normalization followed by element-wise addition and
1732  /// activation.
1733  /// \param [in] adesc Activation operation descriptor.
1734  /// \param [in] epsilon Epsilon value used in computation.
1735  /// \param [in] alpha_data Value to scaling factors used to scale the computed
1736  /// data value.
1737  /// \param [in] src_desc Source memory descriptor.
1738  /// \param [in] src Pointer to source data.
1739  /// \param [in] dst_desc Destination memory descriptor.
1740  /// \param [in] dst Pointer to destination data.
1741  /// \param [in] diff_dst_desc Differential destination memory descriptor.
1742  /// \param [in] diff_dst Pointer to differential destination data.
1743  /// \param [in] beta_data Value to scaling factors used to scale the prior value
1744  /// in the data memory.
1745  /// \param [in] diff_src_desc Differential source memory descriptor.
1746  /// \param [out] diff_src Pointer to differential source data.
1747  /// \param [in] diff_summand_desc Differential summand memory descriptor.
1748  /// \param [out] diff_summand Pointer to differential summand data.
1749  /// \param [in] alpha_param Value to scaling factors used to scale the computed
1750  /// parameter value.
1751  /// \param [in] diff_scale_bias_desc Differential scale, bias memory descriptor.
1752  /// \param [in] scale Pointer to scale data.
1753  /// \param [in] bias Pointer to bias data.
1754  /// \param [in] beta_param Value to scaling factors used to scale the prior value
1755  /// in the parameter memory.
1756  /// \param [out] diff_scale Pointer to differential scale data.
1757  /// \param [out] diff_bias Pointer to differential bias data.
1758  /// \param [in] mean_var_desc Differential mean, variance memory descriptor.
1759  /// \param [in] saved_mean Pointer to optional cache saved mean data in forward.
1760  /// \param [in] saved_var Pointer to optional cache saved variance data in forward.
1761  /// \param [in] workspace_size Size of workspace.
1762  /// \param [in] workspace Pointer to workspace used for backward propagation.
1763  /// \returns An event representing the batch normalization backward operations.
1764  sycl::event async_batch_normalization_backward(
1765      batch_normalization_mode mode, batch_normalization_ops ops,
1766      activation_desc &adesc, float epsilon, float alpha_data,
1767      const memory_desc_ext &src_desc, void *src, const memory_desc_ext &dst_desc,
1768      void *dst, const memory_desc_ext &diff_dst_desc, void *diff_dst,
1769      float beta_data, const memory_desc_ext &diff_src_desc, void *diff_src,
1770      const memory_desc_ext &diff_summand_desc, void *diff_summand,
1771      float alpha_param, const memory_desc_ext &diff_scale_bias_desc, void *scale,
1772      void *bias, float beta_param, void *diff_scale, void *diff_bias,
1773      const memory_desc_ext &mean_var_desc, void *saved_mean, void *saved_var,
1774      size_t workspace_size, void *workspace);
1775
1776  /// Computing a specified convolution function value asynchronously.
1777  /// \param [in] desc Convolution descriptor.
1778  /// \param [in] alg Convolution algorithm.
1779  /// \param [in] alpha Value to scaling factors used to scale the computed
1780  /// value.
1781  /// \param [in] src_desc Source memory descriptor.
1782  /// \param [in] src Pointer to source data.
1783  /// \param [in] weight_desc Weight memory descriptor.
1784  /// \param [in] weight Pointer to weight data.
1785  /// \param [in] beta Value to scaling factors used to scale the prior value
1786  /// in the destination memory.
1787  /// \param [in] dst_desc Destination memory descriptor.
1788  /// \param [out] dst Pointer to destination data.
1789  /// \returns An event representing the convolution forward operations.
1790  sycl::event async_convolution_forward(convolution_desc &desc, ::dnnl::algorithm alg,
1791                                  float alpha, const memory_desc_ext &src_desc,
1792                                  void *src, const memory_desc_ext &weight_desc,
1793                                  void *weight, float beta,
1794                                  const memory_desc_ext &dst_desc, void *dst);
1795
1796  /// Computing a specified convolution function value asynchronously.
1797  /// \param [in] desc Convolution descriptor.
1798  /// \param [in] alg Convolution algorithm.
1799  /// \param [in] adesc Activation operation descriptor.
1800  /// \param [in] alpha_0 Value to scaling factors used to scale the data
1801  /// value.
1802  /// \param [in] src_desc Source memory descriptor.
1803  /// \param [in] src Pointer to source data.
1804  /// \param [in] weight_desc Weight memory descriptor.
1805  /// \param [in] weight Pointer to weight data.
1806  /// \param [in] alpha_1 Value to scaling factors used to scale the summand
1807  /// value.
1808  /// \param [in] summand_desc Summand memory descriptor.
1809  /// \param [in] summand Pointer to summand data.
1810  /// \param [in] bias_desc Bias memory descriptor.
1811  /// \param [in] bias Pointer to bias data.
1812  /// \param [in] dst_desc Destination memory descriptor.
1813  /// \param [out] dst Pointer to destination data.
1814  /// \returns An event representing the convolution forward operations.
1815  sycl::event async_convolution_forward(
1816      convolution_desc &desc, ::dnnl::algorithm alg, activation_desc &adesc,
1817      float alpha_0, const memory_desc_ext &src_desc, void *src,
1818      const memory_desc_ext &weight_desc, void *weight, float alpha_1,
1819      const memory_desc_ext &summand_desc, void *summand,
1820      const memory_desc_ext &bias_desc, void *bias,
1821      const memory_desc_ext &dst_desc, void *dst);
1822
1823  /// Computing the data gradient of a specified convolution function asynchronously.
1824  /// \param [in] desc Convolution descriptor.
1825  /// \param [in] alg Convolution algorithm.
1826  /// \param [in] alpha Value to scaling factors used to scale the computed
1827  /// value.
1828  /// \param [in] weight_desc Weight memory descriptor.
1829  /// \param [in] weight Pointer to weight data.
1830  /// \param [in] diff_dst_desc Differential destination memory descriptor.
1831  /// \param [in] diff_dst Pointer to differential destination data.
1832  /// \param [in] beta Value to scaling factors used to scale the prior value
1833  /// in the destination memory.
1834  /// \param [in] diff_src_desc Differential source memory descriptor.
1835  /// \param [out] diff_src Pointer to differential source data.
1836  /// \returns An event representing the convolution backward data operations.
1837  sycl::event async_convolution_backward_data(
1838      convolution_desc &desc, ::dnnl::algorithm alg, float alpha,
1839      const memory_desc_ext &weight_desc, void *weight,
1840      const memory_desc_ext &diff_dst_desc, void *diff_dst, float beta,
1841      const memory_desc_ext &diff_src_desc, void *diff_src);
1842
1843  /// Computing the weight gradient of a specified convolution function
1844  /// asynchronously.
1845  /// \param [in] desc Convolution descriptor.
1846  /// \param [in] alg Convolution algorithm.
1847  /// \param [in] alpha Value to scaling factors used to scale the computed
1848  /// value.
1849  /// \param [in] src_desc Source memory descriptor.
1850  /// \param [in] src Pointer to source data.
1851  /// \param [in] diff_dst_desc Differential destination memory descriptor.
1852  /// \param [in] diff_dst Pointer to differential destination data.
1853  /// \param [in] beta Value to scaling factors used to scale the prior value
1854  /// in the destination memory.
1855  /// \param [in] diff_weight_desc Differential weight memory descriptor.
1856  /// \param [out] diff_weight Pointer to differential weight data.
1857  /// \returns An event representing the convolution backward weight operations.
1858  sycl::event async_convolution_backward_weight(
1859      convolution_desc &desc, ::dnnl::algorithm alg, float alpha,
1860      const memory_desc_ext &src_desc, void *src,
1861      const memory_desc_ext &diff_dst_desc, void *diff_dst, float beta,
1862      const memory_desc_ext &diff_weight_desc, void *diff_weight);
1863
1864  /// Computing the bias gradient of a specified convolution function
1865  /// asynchronously.
1866  /// \param [in] alpha Value to scaling factors used to scale the computed
1867  /// value.
1868  /// \param [in] diff_dst_desc Differential destination memory descriptor.
1869  /// \param [in] diff_dst Pointer to differential destination data.
1870  /// \param [in] beta Value to scaling factors used to scale the prior value
1871  /// in the destination memory.
1872  /// \param [in] diff_bias_desc Differential bias memory descriptor.
1873  /// \param [out] diff_bias Pointer to differential bias data.
1874  /// \returns An event representing the convolution backward bias operations.
1875  sycl::event async_convolution_backward_bias(float alpha,
1876                                        const memory_desc_ext &diff_dst_desc,
1877                                        void *diff_dst, float beta,
1878                                        const memory_desc_ext &diff_bias_desc,
1879                                        void *diff_bias);
1880
1881  /// Getting the required weight space size for specified rnn operation.  
1882  /// \param [in] desc RNN descriptor.
1883  /// \param [out] weight_space_size Size of required weight space.
1884  void rnn_get_weight_space_size(const rnn_desc &desc,
1885                                 size_t *weight_space_size);
1886
1887  /// Getting the required scratchpad size and workspace size for specified rnn operation.  
1888  /// \param [in] desc RNN descriptor.
1889  /// \param [in] kind Propagation kind.
1890  /// \param [in] src_desc Source memory descriptor.
1891  /// \param [out] scratchpad_size Size of required scratchpad.
1892  /// \param [out] workspace_size Size of required workspace.
1893  void rnn_get_scratchpad_workspace_size(const rnn_desc &desc, ::dnnl::prop_kind kind,
1894                              const memory_desc_ext &src_desc,
1895                              size_t *scratchpad_size, size_t *workspace_size);
1896
1897  /// Computing a specified rnn function value asynchronously.
1898  /// \param [in] desc RNN descriptor.
1899  /// \param [in] kind Propagation kind.
1900  /// \param [in] src_desc Source memory descriptor.
1901  /// \param [in] src Pointer to source data.
1902  /// \param [in] dst_desc Destination memory descriptor.
1903  /// \param [out] dst Pointer to destination data.
1904  /// \param [in] iter_desc Recurrent hidden state data memory descriptor.
1905  /// \param [in] src_iter Pointer to input recurrent hidden state data.
1906  /// \param [in] dst_iter Pointer to output recurrent hidden state data.
1907  /// \param [in] iter_c_desc Recurrent cell state data memory descriptor.
1908  /// \param [in] src_c_iter Pointer to input recurrent cell state data.
1909  /// \param [in] dst_c_iter Pointer to output recurrent cell state data.
1910  /// \param [in] weight_size Size of weight memory.
1911  /// \param [in] weight Pointer to weight data.
1912  /// \param [in] scratchpad_size Size of scratchpad memory.
1913  /// \param [in] scratchpad Pointer to scratchpad data.
1914  /// \param [in] workspace_size Size of workspace memory.
1915  /// \param [in] workspace Pointer to workspace data.
1916  /// \returns An event representing the status of rnn forward operations.
1917  sycl::event async_rnn_forward(const rnn_desc &desc, ::dnnl::prop_kind kind,
1918                               const memory_desc_ext &src_desc, void *src,
1919                               const memory_desc_ext &dst_desc, void *dst,
1920                               const memory_desc_ext &iter_desc, void *src_iter,
1921                               void *dst_iter,
1922                               const memory_desc_ext &iter_c_desc,
1923                               void *src_iter_c, void *dst_iter_c,
1924                               size_t weight_size, void *weight,
1925                               size_t scratchpad_size, void *scratchpad,
1926                               size_t workspace_size, void *workspace);
1927
1928  /// Computing the data and weight gradient of a specified rnn function
1929  /// asynchronously.
1930  /// \param [in] desc RNN descriptor.
1931  /// \param [in] dst_desc Destination memory descriptor.
1932  /// \param [in] dst Pointer to destination data.
1933  /// \param [in] diff_dst Pointer to differential destination data.
1934  /// \param [in] src_desc Source memory descriptor.
1935  /// \param [in] src Pointer to source data.
1936  /// \param [out] diff_src Pointer to differential source data.
1937  /// \param [in] iter_desc Recurrent hidden state data memory descriptor.
1938  /// \param [in] src_iter Pointer to input recurrent hidden state data.
1939  /// \param [in] diff_dst_iter Pointer to differential output recurrent hidden state data.
1940  /// \param [out] diff_src_iter Pointer to differential input recurrent hidden state data.
1941  /// \param [in] iter_c_desc Recurrent cell state data memory descriptor.
1942  /// \param [in] src_c_iter Pointer to input recurrent cell state data.
1943  /// \param [in] diff_dst_c_iter Pointer to differential output recurrent cell state data.
1944  /// \param [out] diff_src_c_iter Pointer to differential input recurrent cell state data.
1945  /// \param [in] weight_size Size of weight memory.
1946  /// \param [in] weight Pointer to weight data.
1947  /// \param [out] diff_weight Pointer to differential weight data.
1948  /// \param [in] scratchpad_size Size of scratchpad memory.
1949  /// \param [in] scratchpad Pointer to scratchpad data.
1950  /// \param [in] workspace_size Size of workspace memory.
1951  /// \param [in] workspace Pointer to workspace data.
1952  /// \returns An event representing the status of rnn backward operations.
1953  sycl::event async_rnn_backward(
1954      const rnn_desc &desc, const memory_desc_ext &dst_desc, void *dst,
1955      void *diff_dst, const memory_desc_ext &src_desc, void *src,
1956      void *diff_src, const memory_desc_ext &iter_desc, void *src_iter,
1957      void *diff_dst_iter, void *diff_src_iter,
1958      const memory_desc_ext &iter_c_desc, void *src_iter_c,
1959      void *diff_dst_iter_c, void *diff_src_iter_c, size_t weight_size,
1960      void *weight, void *diff_weight, size_t scratchpad_size, void *scratchpad,
1961      size_t workspace_size, void *workspace);
1962
1963  /// Getting the required state size for specified dropout operation.
1964  /// \param [in] src_desc Source memory descriptor.
1965  /// \returns Required size of state.
1966  size_t get_dropout_state_size();
1967
1968  /// Getting the required workspace size for dropout operation.
1969  /// \param [in] src_desc Source memory descriptor.
1970  /// \returns Required size of workspace.
1971  static size_t get_dropout_workspace_size(const memory_desc_ext &src_desc);
1972
1973  /// Computing a specified dropout function value asynchronously.
1974  /// \param [in] desc Dropout descriptor.
1975  /// \param [in] src_desc Source memory descriptor.
1976  /// \param [in] src Pointer to source data.
1977  /// \param [in] dst_desc Destination memory descriptor.
1978  /// \param [out] dst Pointer to destination data.
1979  /// \param [in] workspace Pointer to workspace data.
1980  /// \param [in] workspace_size Size of workspace memory.
1981  /// \returns An event representing the dropout forward operations.
1982  sycl::event async_dropout_forward(dropout_desc &desc,
1983                                    const memory_desc_ext &src_desc, void *src,
1984                                    const memory_desc_ext &dst_desc, void *dst,
1985                                    void *workspace, size_t workspace_size);
1986
1987  /// Computing the gradient of a specified dropout function asynchronously.
1988  /// \param [in] desc Dropout descriptor.
1989  /// \param [in] diff_dst_desc Differential destination memory descriptor.
1990  /// \param [in] diff_dst Pointer to differential destination data.
1991  /// \param [in] diff_src_desc Differential source memory descriptor.
1992  /// \param [out] diff_src Pointer to differential source data.
1993  /// \param [in] workspace Pointer to workspace data.
1994  /// \param [in] workspace_size Size of workspace memory.
1995  /// \returns An event representing the dropout backward operations.
1996  sycl::event async_dropout_backward(dropout_desc &desc,
1997                                     const memory_desc_ext &diff_dst_desc,
1998                                     void *diff_dst,
1999                                     const memory_desc_ext &diff_src_desc,
2000                                     void *diff_src, void *workspace,
2001                                     size_t workspace_size);
2002};
2003
2004inline thread_local unsigned int engine_ext::_engine_count;
2005inline thread_local detail::primitive_cache engine_ext::_primitive_cache;
2006inline thread_local std::map<void *, ::dnnl::memory> engine_ext::_workspace_map;
2007inline thread_local std::map<sycl::queue *,
2008                             std::shared_ptr<engine_ext::internal_resource>>
2009    engine_ext::_internal_resource_cache;
2010
2011inline
2012void dropout_desc::restore(engine_ext &engine, float p, void *state,
2013                                  size_t state_size, unsigned long long seed) {
2014#ifndef __INTEL_MKL__
2015    throw std::runtime_error("The oneAPI Math Kernel Library (oneMKL) "
2016                             "Interfaces Project does not support this API.");
2017#else
2018  if (state) {
2019    std::int64_t required_state_size = engine.get_dropout_state_size();
2020    if (state_size < required_state_size) {
2021      throw std::runtime_error("restore: state_size less than required state size.");
2022    }
2023    sycl::queue *q = engine.get_queue();
2024    _imp->_p = p;
2025    _imp->_seed = seed;
2026    _imp->_state = state;
2027    _imp->_host_state = std::vector<std::uint8_t>(required_state_size);
2028    q->memcpy(_imp->_host_state.data(), _imp->_state, required_state_size).wait();
2029    _imp->_rng_engine =
2030        oneapi::mkl::rng::load_state<rng_engine_t>(
2031            *q, _imp->_host_state.data());
2032  }
2033#endif
2034}
2035
2036inline
2037void dropout_desc::set(engine_ext &engine, float p, void *state,
2038                              size_t state_size, unsigned long long seed) {
2039#ifndef __INTEL_MKL__
2040    throw std::runtime_error("The oneAPI Math Kernel Library (oneMKL) "
2041                             "Interfaces Project does not support this API.");
2042#else
2043  _imp->_p = p;
2044  if (state) {
2045    std::int64_t required_state_size = engine.get_dropout_state_size();
2046    if (state_size < required_state_size) {
2047      throw std::runtime_error("set: no sufficient memory to save states.");
2048    }
2049    sycl::queue *q = engine.get_queue();
2050    _imp->_seed = seed;
2051    _imp->_state = state;
2052    _imp->_host_state = std::vector<std::uint8_t>(required_state_size);
2053    _imp->_rng_engine = rng_engine_t(*q, seed);
2054    oneapi::mkl::rng::save_state(_imp->_rng_engine, _imp->_host_state.data());
2055    q->memcpy(_imp->_state, _imp->_host_state.data(), required_state_size).wait();
2056  }
2057#endif
2058}
2059
2060inline
2061::dnnl::memory::data_type
2062memory_desc_ext::to_dnnl_data_type(dpct::library_data_t dt) {
2063  using dnnl_dt = ::dnnl::memory::data_type;
2064  switch (dt) {
2065  case dpct::library_data_t::real_half:
2066    return dnnl_dt::f16;
2067  case dpct::library_data_t::real_bfloat16:
2068    return dnnl_dt::bf16;
2069  case dpct::library_data_t::real_float:
2070    return dnnl_dt::f32;
2071  case dpct::library_data_t::real_double:
2072    return dnnl_dt::f64;
2073  case dpct::library_data_t::real_int32:
2074    return dnnl_dt::s32;
2075  case dpct::library_data_t::real_int8:
2076    return dnnl_dt::s8;
2077  case dpct::library_data_t::real_uint8:
2078    return dnnl_dt::u8;
2079  case dpct::library_data_t::real_int8_4:
2080    return dnnl_dt::s8;
2081  case dpct::library_data_t::real_int8_32:
2082    return dnnl_dt::s8;
2083  case dpct::library_data_t::real_uint8_4:
2084    return dnnl_dt::u8;
2085  default:
2086    throw std::runtime_error("to_dnnl_data_type: unsupported data type.");
2087  }
2088}
2089
2090inline
2091dpct::library_data_t
2092memory_desc_ext::to_dpct_library_data_t(::dnnl::memory::data_type dt,
2093                                        unsigned block_size) {
2094  using dpct_dt = dpct::library_data_t;
2095  using dnnl_dt = ::dnnl::memory::data_type;
2096  switch (dt) {
2097  case dnnl_dt::f16:
2098    return dpct_dt::real_half;
2099  case dnnl_dt::bf16:
2100    return dpct_dt::real_bfloat16;
2101  case dnnl_dt::f32:
2102    return dpct_dt::real_float;
2103  case dnnl_dt::f64:
2104    return dpct_dt::real_double;
2105  case dnnl_dt::s32:
2106    return dpct_dt::real_int32;
2107  case dnnl_dt::s8:
2108    if (block_size == 4) {
2109      return dpct_dt::real_int8_4;
2110    } else if (block_size == 32) {
2111      return dpct_dt::real_int8_32;
2112    } else {
2113      return dpct_dt::real_int8;
2114    }
2115  case dnnl_dt::u8:
2116    if (block_size == 4) {
2117      return dpct_dt::real_uint8_4;
2118    } else {
2119      return dpct_dt::real_uint8;
2120    }
2121  default:
2122    throw std::runtime_error("to_dpct_library_data_t: unsupported data type "
2123                             "dnnl::memory::data_type::undef.");
2124  }
2125}
2126
2127inline
2128::dnnl::memory::format_tag
2129memory_desc_ext::to_dnnl_format_tag(dpct::library_data_t dt,
2130                                    memory_format_tag tag) {
2131  using dpct_dt = dpct::library_data_t;
2132  using dpct_tag = memory_format_tag;
2133  using dnnl_tag = ::dnnl::memory::format_tag;
2134  switch (tag) {
2135  case dpct_tag::nchw:
2136    return dnnl_tag::nchw;
2137  case dpct_tag::nhwc:
2138    return dnnl_tag::nhwc;
2139  default:
2140    if (dt == dpct_dt::real_int8_32) {
2141      return dnnl_tag::nChw32c;
2142    } else {
2143      return dnnl_tag::nChw4c;
2144    }
2145  }
2146}
2147
2148inline
2149void memory_desc_ext::set(memory_format_tag tag, dpct::library_data_t dt, int n,
2150                          int c, int h, int w) {
2151  _desc = ::dnnl::memory::desc({n, c, h, w}, to_dnnl_data_type(dt),
2152                               to_dnnl_format_tag(dt, tag));
2153}
2154
2155inline
2156void memory_desc_ext::set(dpct::library_data_t dt, int n, int c, int h, int w,
2157                          int n_stride, int c_stride, int h_stride,
2158                          int w_stride) {
2159  _desc = ::dnnl::memory::desc({n, c, h, w}, to_dnnl_data_type(dt),
2160                               {n_stride, c_stride, h_stride, w_stride});
2161}
2162
2163inline
2164void memory_desc_ext::set(dpct::library_data_t dt, int ndims, const int dims[],
2165                          const int strides[]) {
2166  _desc = ::dnnl::memory::desc({dims, dims + ndims}, to_dnnl_data_type(dt),
2167                               {strides, strides + ndims});
2168}
2169
2170inline
2171void memory_desc_ext::set(memory_format_tag tag, dpct::library_data_t dt,
2172                          int ndims, const int dims[]) {
2173  _desc = ::dnnl::memory::desc({dims, dims + ndims}, to_dnnl_data_type(dt),
2174                               to_dnnl_format_tag(dt, tag));
2175}
2176
2177inline
2178void memory_desc_ext::set(rnn_memory_format_tag tag, dpct::library_data_t dt,
2179                          int t, int n, int c) {
2180  if (tag == rnn_memory_format_tag::tnc) {
2181    _desc = ::dnnl::memory::desc({t, n, c}, to_dnnl_data_type(dt),
2182                                 ::dnnl::memory::format_tag::tnc);
2183  } else if(tag == rnn_memory_format_tag::ntc) {
2184    _desc = ::dnnl::memory::desc({t, n, c}, to_dnnl_data_type(dt),
2185                                 ::dnnl::memory::format_tag::ntc);
2186  } else {
2187    throw std::runtime_error("set: unsupported memory format tag.");
2188  }
2189}
2190
2191inline
2192void memory_desc_ext::get(dpct::library_data_t *dt, int *n, int *c, int *h,
2193                          int *w, int *n_stride, int *c_stride, int *h_stride,
2194                          int *w_stride) const {
2195  unsigned block_size = 1;
2196  auto dims = _desc.get_dims();
2197  auto inner_blks = _desc.get_inner_blks();
2198  auto strides = _desc.get_strides();
2199  if (!inner_blks.empty()) {
2200    block_size = inner_blks[0];
2201  }
2202
2203  *dt = to_dpct_library_data_t(_desc.get_data_type(), block_size);
2204  *n = dims[0];
2205  *c = dims[1];
2206  *h = dims[2];
2207  *w = dims[3];
2208  *n_stride = strides[0] / block_size;
2209  *c_stride = strides[1] / block_size;
2210  *h_stride = strides[2] / block_size;
2211  *w_stride = strides[3] / block_size;
2212}
2213
2214inline
2215void memory_desc_ext::get(dpct::library_data_t *dt, memory_format_tag *tag,
2216                          int *n, int *c, int *h, int *w) const {
2217  unsigned block_size = 1;
2218  *tag = memory_format_tag::nchw;
2219  auto dims = _desc.get_dims();
2220  auto strides = _desc.get_strides();
2221  auto inner_blks = _desc.get_inner_blks();
2222  if (!inner_blks.empty()) {
2223    block_size = inner_blks[0];
2224    *tag = memory_format_tag::nchw_blocked;
2225  }
2226  if (strides[1] == 1 && dims[1] != 1) {
2227    *tag = memory_format_tag::nhwc;
2228  }
2229  *dt = to_dpct_library_data_t(_desc.get_data_type(), block_size);
2230  *n = dims[0];
2231  *c = dims[1];
2232  *h = dims[2];
2233  *w = dims[3];
2234}
2235
2236inline
2237void memory_desc_ext::get(dpct::library_data_t *dt, rnn_memory_format_tag *tag,
2238                          int *t, int *n, int *c) const {
2239  auto dims = _desc.get_dims();
2240  auto strides = _desc.get_strides();
2241
2242  if (strides[0] >= strides[1]) {
2243    *tag = rnn_memory_format_tag::tnc;
2244  } else {
2245    *tag = rnn_memory_format_tag::ntc;
2246  }
2247
2248  *dt = to_dpct_library_data_t(_desc.get_data_type(), 1);
2249  *t = dims[0];
2250  *n = dims[1];
2251  *c = dims[2];
2252}
2253
2254inline
2255void memory_desc_ext::get(int requested_ndims, dpct::library_data_t *dt,
2256                          int *ndims, int dims[], int strides[]) const {
2257  unsigned block_size = 1;
2258  auto inner_blks = _desc.get_inner_blks();
2259  auto adims = _desc.get_dims();
2260  auto astrides = _desc.get_strides();
2261  if (!inner_blks.empty()) {
2262    block_size = inner_blks[0];
2263  }
2264  *dt = to_dpct_library_data_t(_desc.get_data_type(), block_size);
2265  *ndims = _desc.get_ndims();
2266  for (int index = 0; index < requested_ndims; index++) {
2267    dims[index] = adims[index];
2268    strides[index] =
2269        astrides[index] / block_size;
2270  }
2271}
2272
2273inline
2274void memory_desc_ext::get(int requested_ndims, dpct::library_data_t *dt,
2275                          memory_format_tag *tag, int *ndims,
2276                          int dims[]) const {
2277  unsigned block_size = 1;
2278  *tag = memory_format_tag::nchw;
2279  auto inner_blks = _desc.get_inner_blks();
2280  auto adims = _desc.get_dims();
2281  auto astrides = _desc.get_strides();
2282  if (!inner_blks.empty()) {
2283    block_size = inner_blks[0];
2284    *tag = memory_format_tag::nchw_blocked;
2285  }
2286  if (astrides[1] == 1 &&
2287      adims[1] != 1) {
2288    *tag = memory_format_tag::nhwc;
2289  }
2290  *dt = to_dpct_library_data_t(_desc.get_data_type(), block_size);
2291  *ndims = _desc.get_ndims();
2292  for (int index = 0; index < requested_ndims; index++) {
2293    dims[index] = adims[index];
2294  }
2295}
2296
2297inline
2298void engine_ext::get_rnn_configuration(const ::dnnl::memory::desc &desc,
2299                                       rnn_direction direction, rnn_mode mode,
2300                                       dpct::library_data_t dt, int hidden_size,
2301                                       ::dnnl::memory::data_type *dnnl_dt,
2302                                       ::dnnl::memory::format_tag *tag,
2303                                       int *projection_size, int *output_size,
2304                                       int *seq_length, int *batch_size,
2305                                       int *direction_num, int *gate_num) {
2306  if (!desc.is_zero()) {
2307    auto dims = desc.get_dims();
2308    auto strides = desc.get_strides();
2309    if (strides[0] >= strides[1]) {
2310      *tag = ::dnnl::memory::format_tag::tnc;
2311      *seq_length = dims[0];
2312      *batch_size = dims[1];
2313    } else {
2314      *tag = ::dnnl::memory::format_tag::ntc;
2315      *seq_length = dims[1];
2316      *batch_size = dims[0];
2317    }
2318  }
2319  if (direction == rnn_direction::bidirectional) {
2320    *direction_num = 2;
2321  } else {
2322    *direction_num = 1;
2323  }
2324  if (mode == rnn_mode::lstm) {
2325    *gate_num = 4;
2326  } else if (mode == rnn_mode::gru) {
2327    *gate_num = 3;
2328  } else {
2329    *gate_num = 1;
2330  }
2331  if (*projection_size != hidden_size) {
2332    *output_size = *projection_size;
2333  } else {
2334    *projection_size = 0;
2335    *output_size = hidden_size;
2336  }
2337  *dnnl_dt = memory_desc_ext::to_dnnl_data_type(dt);
2338}
2339
2340inline
2341void *engine_ext::allocate(const memory_desc_ext &data_desc, int count) {
2342  return allocate(data_desc.get_size() * count);
2343}
2344
2345inline
2346void *engine_ext::allocate(size_t size) {
2347  auto &Info = get_internal_resource(_q)->binfo;
2348  uint8_t *result = Info.buffer + Info.usage;
2349  Info.usage += size;
2350  return result;
2351}
2352
2353inline
2354void engine_ext::transform_no_zero(const memory_desc_ext &desc, void *src, void *dst) {
2355  ::dnnl::memory::data_type dt = desc.get_desc().get_data_type();
2356  size_t element_num = desc.get_element_num();
2357  switch (dt) {
2358  case ::dnnl::memory::data_type::f32:
2359    transform_no_zero_with_type<float>(_q, src, dst, element_num);
2360    break;
2361  case ::dnnl::memory::data_type::f16:
2362    transform_no_zero_with_type<sycl::half>(_q, src, dst, element_num);
2363    break;
2364  case ::dnnl::memory::data_type::s32:
2365    transform_no_zero_with_type<int32_t>(_q, src, dst, element_num);
2366    break;
2367  case ::dnnl::memory::data_type::s8:
2368    transform_no_zero_with_type<int8_t>(_q, src, dst, element_num);
2369    break;
2370  case ::dnnl::memory::data_type::u8:
2371    transform_no_zero_with_type<uint8_t>(_q, src, dst, element_num);
2372    break;
2373  default:
2374    throw std::runtime_error("transform_no_zero: unsupported data type.");
2375  }
2376}
2377
2378inline
2379::dnnl::memory::desc
2380engine_ext::get_group_weight_desc(int group_count,
2381                                  const memory_desc_ext &weight_desc) {
2382  if (group_count == 1) {
2383    return weight_desc.get_desc();
2384  }
2385  auto help_weight_desc = weight_desc.get_desc();
2386  int ndims = help_weight_desc.get_ndims();
2387  if (!help_weight_desc.get_inner_blks().empty()) {
2388    throw std::runtime_error("get_group_weight_desc: group convolution with "
2389                             "blocked weight memory unimplemented.");
2390  }
2391  std::vector<int64_t> new_size;
2392  auto old_size = weight_desc.get_dims();
2393  new_size.push_back(group_count);
2394  new_size.push_back(old_size[0] / group_count);
2395  for (int index = 1; index < old_size.size(); index++) {
2396    new_size.push_back(old_size[index]);
2397  }
2398  std::vector<int64_t> strides = help_weight_desc.get_strides();
2399  ::dnnl::memory::format_tag tag;
2400  bool is_nhwc = (strides[1] == 1 && old_size[1] != 1);
2401
2402  if (ndims == 4) {
2403    if (is_nhwc) {
2404      tag = ::dnnl::memory::format_tag::gohwi;
2405    } else {
2406      tag = ::dnnl::memory::format_tag::goihw;
2407    }
2408  } else if (ndims == 5) {
2409    if (is_nhwc) {
2410      tag = ::dnnl::memory::format_tag::godhwi;
2411    } else {
2412      tag = ::dnnl::memory::format_tag::goidhw;
2413    }
2414  }
2415
2416  help_weight_desc =
2417      ::dnnl::memory::desc(new_size, weight_desc.get_desc().get_data_type(), tag);
2418  return help_weight_desc;
2419}
2420
2421inline
2422::dnnl::memory::desc engine_ext::compress_spatial_dimensions_to_channel(
2423    const ::dnnl::memory::desc &desc) {
2424  int ndims = desc.get_ndims();
2425  auto dims = desc.get_dims();
2426  auto inner_blks = desc.get_inner_blks();
2427  assert(ndims >= 4 && "ndims is at least 4.");
2428  std::vector<int64_t> compressed_dims(ndims);
2429  compressed_dims[0] = dims[0];
2430  compressed_dims[1] = dims[1];
2431  for (int index = 2; index < ndims; index++) {
2432    compressed_dims[1] = compressed_dims[1] * dims[index];
2433    compressed_dims[index] = 1;
2434  }
2435  if (!inner_blks.empty() && inner_blks[0] == 4) {
2436    return ::dnnl::memory::desc(compressed_dims, desc.get_data_type(),
2437                                ::dnnl::memory::format_tag::nChw4c);
2438  } else if (!inner_blks.empty() && inner_blks[0] == 32) {
2439    return ::dnnl::memory::desc(compressed_dims, desc.get_data_type(),
2440                                ::dnnl::memory::format_tag::nChw32c);
2441  }
2442  std::vector<int64_t> strides(ndims, 1);
2443  strides[0] = compressed_dims[1];
2444
2445  return ::dnnl::memory::desc(compressed_dims, desc.get_data_type(), strides);
2446}
2447
2448inline
2449::dnnl::memory::desc
2450engine_ext::get_bn_scale_bias_mean_var_desc(const ::dnnl::memory::desc &desc,
2451                                            batch_normalization_mode mode) {
2452  int ndims = desc.get_ndims();
2453  auto dims = desc.get_dims();
2454  assert(ndims >= 4 && "ndims is at least 4.");
2455  int channel_num = 1;
2456  if (mode == batch_normalization_mode::spatial) {
2457    channel_num = dims[1];
2458  } else {
2459    for (int index = 1; index < ndims; index++) {
2460      channel_num = channel_num * dims[index];
2461    }
2462  }
2463  return ::dnnl::memory::desc({channel_num}, desc.get_data_type(),
2464                              ::dnnl::memory::format_tag::a);
2465}
2466
2467inline
2468::dnnl::memory::desc engine_ext::transfer_memory_desc_to_channel_major_format(
2469    const ::dnnl::memory::desc &desc) {
2470  if (!desc.get_inner_blks().empty()) {
2471    return desc;
2472  }
2473  int ndims = desc.get_ndims();
2474  auto dims = desc.get_dims();
2475  if (ndims == 4) {
2476    return ::dnnl::memory::desc(dims, desc.get_data_type(),
2477                                ::dnnl::memory::format_tag::nchw);
2478  }
2479  return ::dnnl::memory::desc(dims, desc.get_data_type(),
2480                              ::dnnl::memory::format_tag::ncdhw);
2481}
2482
2483/// If the alpha = 0 and beta = 1, then the destination (dst = alpha * out +
2484/// beta * prior_dst) have no change. In this case this function returns true
2485/// means the operation can exit directly.
2486inline
2487bool engine_ext::scale_parameter_preprocess(
2488    const std::vector<output_argument_info> &args) {
2489  bool direct_exit = true;
2490  for (auto &arg : args) {
2491    if (arg._alpha == 0.f) {
2492      if (arg._beta != 1.f) {
2493        async_scale(arg._beta, arg._desc, arg._data);
2494      }
2495    } else {
2496      direct_exit = false;
2497    }
2498  }
2499  return direct_exit;
2500}
2501
2502inline
2503void engine_ext::derive_batch_normalization_memory_desc(
2504    memory_desc_ext &scale_bias_desc, memory_desc_ext &mean_var_desc,
2505    const memory_desc_ext &src_desc, batch_normalization_mode mode) {
2506    derive_batch_normalization_memory_desc(scale_bias_desc, src_desc, mode);
2507    derive_batch_normalization_memory_desc(mean_var_desc, src_desc, mode);
2508}
2509
2510inline
2511void engine_ext::derive_batch_normalization_memory_desc(
2512    memory_desc_ext &desc, const memory_desc_ext &src_desc,
2513    batch_normalization_mode mode) {
2514  int src_ndims = src_desc.get_desc().get_ndims();
2515  auto inner_blks = src_desc.get_desc().get_inner_blks();
2516  if (src_desc.get_desc().get_ndims() != 4 ||
2517      src_desc.get_desc().get_ndims() != 5) {
2518    throw std::runtime_error("derive_batch_normalization_memory_desc: only 4d "
2519                             "and 5d memory descriptor supported.");
2520  }
2521  std::vector<int64_t> dims = src_desc.get_dims();
2522  dims[0] = 1;
2523  if (mode == batch_normalization_mode::spatial) {
2524    dims[2] = 1;
2525    dims[3] = 1;
2526    if (src_ndims == 5) {
2527      dims[4] = 1;
2528    }
2529  }
2530  auto data_type = src_desc.get_desc().get_data_type();
2531  if (data_type == ::dnnl::memory::data_type::f16) {
2532    data_type = ::dnnl::memory::data_type::f32;
2533  }
2534  if (!inner_blks.empty() && inner_blks[0] == 4) {
2535    desc.set_desc(::dnnl::memory::desc(dims, data_type,
2536                                       ::dnnl::memory::format_tag::nChw4c));
2537  } else if (!inner_blks.empty() && inner_blks[0] == 32) {
2538    desc.set_desc(::dnnl::memory::desc(dims, data_type,
2539                                       ::dnnl::memory::format_tag::nChw32c));
2540  } else {
2541    if (src_ndims == 4) {
2542      desc.set_desc(::dnnl::memory::desc(dims, data_type,
2543                                         ::dnnl::memory::format_tag::nchw));
2544    } else {
2545      desc.set_desc(::dnnl::memory::desc(dims, data_type,
2546                                         ::dnnl::memory::format_tag::ncdhw));
2547    }
2548  }
2549}
2550
2551template <typename primitive_type>
2552sycl::event engine_ext::execute_primitive(
2553    const std::pair<detail::primitive_cache_key_type, detail::primitive_and_args>
2554        &primitive,
2555    const std::vector<output_argument_info> &output_args) {
2556  std::vector<void *> caches;
2557  int output_arg_num = output_args.size();
2558  for (int i = 0; i < output_arg_num; i++) {
2559    if (output_args[i]._beta != 0.f) {
2560      auto cache = allocate(output_args[i]._desc);
2561      caches.push_back(cache);
2562      (*primitive.second.args)[output_args[i]._name].set_data_handle(cache);
2563    }
2564  }
2565
2566  auto e = ::dnnl::sycl_interop::execute(
2567      *(static_cast<primitive_type *>(primitive.second.primitive)), *_s,
2568      *primitive.second.args);
2569  _primitive_cache.put(
2570      primitive.first, primitive.second.primitive, primitive.second.args,
2571      [](::dnnl::primitive *p) { delete static_cast<primitive_type *>(p); }, e,
2572      _q);
2573  int cache_index = 0;
2574  for (int i = 0; i < output_arg_num; i++) {
2575    if (output_args[i]._beta != 0.f) {
2576      e = async_sum(output_args[i]._alpha, output_args[i]._desc,
2577                    caches[cache_index++], output_args[i]._beta,
2578                    output_args[i]._desc, output_args[i]._data);
2579    } else {
2580      if (output_args[i]._alpha != 1.f) {
2581        e = async_scale(output_args[i]._alpha, output_args[i]._desc,
2582                        output_args[i]._data);
2583      }
2584    }
2585  }
2586  return e;
2587}
2588
2589inline
2590::dnnl::memory::desc engine_ext::bn_reorder_memory_to_channel_major_format(
2591    bool is_input, ::dnnl::memory::desc &desc, void *src, void **cache) {
2592  ::dnnl::memory::desc result;
2593  result = transfer_memory_desc_to_channel_major_format(desc);
2594  if ((result != desc) || !src) {
2595    *cache = allocate(desc);
2596    if (is_input && src) {
2597      async_reorder(1.f, desc, src, 0.f, result, *cache);
2598    }
2599  }
2600  return result;
2601}
2602
2603inline
2604sycl::event engine_ext::batch_normalization_backward_internal(
2605    batch_normalization_mode mode, float epsilon, float alpha_data,
2606    const memory_desc_ext &src_desc, void *src,
2607    const memory_desc_ext &diff_dst_desc, void *diff_dst, float beta_data,
2608    const memory_desc_ext &diff_src_desc, void *diff_src, float alpha_param,
2609    const memory_desc_ext &diff_scale_bias_desc, void *scale, void *bias,
2610    float beta_param, void *diff_scale, void *diff_bias,
2611    const memory_desc_ext &mean_var_desc, void *saved_mean, void *saved_var) {
2612  if (scale_parameter_preprocess(
2613          {{alpha_data, beta_data, diff_src_desc, diff_src},
2614           {alpha_param, beta_param, diff_scale_bias_desc, diff_scale},
2615           {alpha_param, beta_param, diff_scale_bias_desc, diff_bias}})) {
2616    return sycl::event();
2617  }
2618
2619  void *reordered_src = nullptr, *reordered_diff_dst = nullptr,
2620       *reordered_diff_src = nullptr, *reordered_scale = nullptr,
2621       *reordered_bias = nullptr, *reordered_diff_scale = nullptr,
2622       *reordered_diff_bias = nullptr, *reordered_saved_mean = nullptr,
2623       *reordered_saved_var = nullptr;
2624
2625  ::dnnl::memory::desc help_src_desc = src_desc.get_desc();
2626  ::dnnl::memory::desc help_diff_dst_desc = diff_dst_desc.get_desc();
2627  ::dnnl::memory::desc help_diff_src_desc = diff_src_desc.get_desc();
2628  ::dnnl::memory::desc help_diff_scale_bias_desc =
2629      diff_scale_bias_desc.get_desc();
2630  ::dnnl::memory::desc help_mean_var_desc = mean_var_desc.get_desc();
2631  ::dnnl::memory::desc actual_diff_src_desc = help_diff_src_desc;
2632  ::dnnl::memory::desc actual_diff_scale_bias_desc = help_diff_scale_bias_desc;
2633  enter_primitive(
2634      help_diff_scale_bias_desc.get_size() * 14 + help_src_desc.get_size() * 2 +
2635      help_diff_dst_desc.get_size() * 7 + help_diff_src_desc.get_size() * 5 +
2636      help_mean_var_desc.get_size() * 13);
2637  if (mode == batch_normalization_mode::per_activation) {
2638    help_src_desc = bn_reorder_memory_to_channel_major_format(true, help_src_desc, src,
2639                                                       &reordered_src);
2640    help_diff_dst_desc = bn_reorder_memory_to_channel_major_format(
2641        true, help_diff_dst_desc, diff_dst, &reordered_diff_dst);
2642    help_diff_src_desc = bn_reorder_memory_to_channel_major_format(
2643        false, help_diff_src_desc, diff_src, &reordered_diff_src);
2644    actual_diff_src_desc = help_diff_src_desc;
2645    help_diff_scale_bias_desc = bn_reorder_memory_to_channel_major_format(
2646        true, help_diff_scale_bias_desc, scale, &reordered_scale);
2647    actual_diff_scale_bias_desc = help_diff_scale_bias_desc;
2648    if (bias) {
2649      bn_reorder_memory_to_channel_major_format(true, help_diff_scale_bias_desc, bias,
2650                                         &reordered_bias);
2651    }
2652    bn_reorder_memory_to_channel_major_format(false, help_diff_scale_bias_desc,
2653                                       diff_scale, &reordered_diff_scale);
2654    bn_reorder_memory_to_channel_major_format(false, help_diff_scale_bias_desc,
2655                                       diff_bias, &reordered_diff_bias);
2656
2657    help_mean_var_desc = bn_reorder_memory_to_channel_major_format(
2658        true, help_mean_var_desc, saved_mean, &reordered_saved_mean);
2659    bn_reorder_memory_to_channel_major_format(true, help_mean_var_desc, saved_var,
2660                                       &reordered_saved_var);
2661    help_src_desc = compress_spatial_dimensions_to_channel(help_src_desc);
2662    help_diff_src_desc =
2663        compress_spatial_dimensions_to_channel(help_diff_src_desc);
2664    help_diff_dst_desc =
2665        compress_spatial_dimensions_to_channel(help_diff_dst_desc);
2666  } else {
2667    if ((help_src_desc != help_diff_dst_desc) ||
2668        (help_src_desc != help_diff_src_desc) ||
2669        (help_diff_dst_desc != help_diff_src_desc)) {
2670      help_src_desc = bn_reorder_memory_to_channel_major_format(
2671          true, help_src_desc, src, &reordered_src);
2672      help_diff_dst_desc = bn_reorder_memory_to_channel_major_format(
2673          true, help_diff_dst_desc, diff_dst, &reordered_diff_dst);
2674      help_diff_src_desc = bn_reorder_memory_to_channel_major_format(
2675          false, help_diff_src_desc, diff_src, &reordered_diff_src);
2676      actual_diff_src_desc = help_diff_src_desc;
2677    }
2678  }
2679
2680  help_diff_scale_bias_desc =
2681      get_bn_scale_bias_mean_var_desc(help_diff_scale_bias_desc, mode);
2682  help_mean_var_desc =
2683      get_bn_scale_bias_mean_var_desc(help_mean_var_desc, mode);
2684
2685  auto forward_primitive =
2686      create_primitive_desc<::dnnl::batch_normalization_forward>(
2687          ::dnnl::prop_kind::forward_training, help_src_desc,
2688          help_diff_dst_desc, epsilon,
2689          ::dnnl::normalization_flags::use_scale |
2690              ::dnnl::normalization_flags::use_shift);
2691  auto primitive_args =
2692      create_primitive_args_or_get<::dnnl::batch_normalization_backward>(
2693          ::dnnl::prop_kind::backward, help_diff_src_desc, help_diff_dst_desc,
2694          help_src_desc, epsilon,
2695          ::dnnl::normalization_flags::use_scale |
2696              ::dnnl::normalization_flags::use_shift, forward_primitive);
2697
2698  void *dst_cache = nullptr;
2699  if (!saved_mean && !saved_var) {
2700    dst_cache = allocate(diff_dst_desc);
2701    if (!reordered_saved_mean) {
2702      reordered_saved_mean = allocate(mean_var_desc);
2703    }
2704    if (!reordered_saved_var) {
2705      reordered_saved_var = allocate(mean_var_desc);
2706    }
2707    if (!bias) {
2708      _q->fill(reordered_bias, 0, diff_scale_bias_desc.get_size());
2709    }
2710
2711    batch_normalization_forward_internal(
2712        true, mode, epsilon, 0.f, 1.f, src_desc, src, 0.f, diff_dst_desc,
2713        dst_cache, diff_scale_bias_desc, scale, bias ? bias : reordered_bias,
2714        mean_var_desc, reordered_saved_mean, reordered_saved_var, nullptr,
2715        nullptr);
2716  }
2717
2718  insert_arg(primitive_args.second.args, DNNL_ARG_SRC, help_src_desc,
2719             reordered_src ? reordered_src : src);
2720  insert_arg(primitive_args.second.args, DNNL_ARG_SCALE,
2721             help_diff_scale_bias_desc,
2722             reordered_scale ? reordered_scale : scale);
2723  insert_arg(primitive_args.second.args, DNNL_ARG_MEAN, help_mean_var_desc,
2724             reordered_saved_mean ? reordered_saved_mean : saved_mean);
2725  insert_arg(primitive_args.second.args, DNNL_ARG_VARIANCE, help_mean_var_desc,
2726             reordered_saved_var ? reordered_saved_var : saved_var);
2727  insert_arg(primitive_args.second.args, DNNL_ARG_DIFF_DST, help_diff_src_desc,
2728             reordered_diff_dst ? reordered_diff_dst : diff_dst);
2729  insert_arg(primitive_args.second.args, DNNL_ARG_DIFF_SRC, help_diff_src_desc,
2730             reordered_diff_src ? reordered_diff_src : diff_src);
2731  insert_arg(primitive_args.second.args, DNNL_ARG_DIFF_SCALE,
2732             help_diff_scale_bias_desc,
2733             reordered_diff_scale ? reordered_diff_scale : diff_scale);
2734  insert_arg(primitive_args.second.args, DNNL_ARG_DIFF_SHIFT,
2735             help_diff_scale_bias_desc,
2736             reordered_diff_bias ? reordered_diff_bias : diff_bias);
2737
2738  sycl::event e = execute_primitive<::dnnl::batch_normalization_backward>(
2739      primitive_args,
2740      {{alpha_data, beta_data, DNNL_ARG_DIFF_SRC, help_diff_src_desc,
2741        reordered_diff_src ? reordered_diff_src : diff_src},
2742       {alpha_param, beta_param, DNNL_ARG_DIFF_SCALE, help_diff_scale_bias_desc,
2743        reordered_diff_scale ? reordered_diff_scale : diff_scale},
2744       {alpha_param, beta_param, DNNL_ARG_DIFF_SHIFT, help_diff_scale_bias_desc,
2745        reordered_diff_bias ? reordered_diff_bias : diff_bias}});
2746  if (actual_diff_src_desc != diff_src_desc.get_desc() && reordered_diff_src) {
2747    e = async_reorder(1.f, actual_diff_src_desc, reordered_diff_src, 0.f,
2748                diff_src_desc, diff_src);
2749  }
2750  if (actual_diff_scale_bias_desc != diff_scale_bias_desc.get_desc() &&
2751      reordered_diff_scale && reordered_diff_bias) {
2752    async_reorder(1.f, actual_diff_scale_bias_desc, reordered_diff_scale, 0.f,
2753            diff_scale_bias_desc, diff_scale);
2754    e = async_reorder(1.f, actual_diff_scale_bias_desc, reordered_diff_bias, 0.f,
2755                diff_scale_bias_desc, diff_bias);
2756  }
2757  return exit_primitive(e);
2758}
2759
2760inline
2761sycl::event engine_ext::batch_normalization_forward_internal(
2762    bool is_infer, batch_normalization_mode mode, float epsilon, float factor,
2763    float alpha, const memory_desc_ext &src_desc, void *src, float beta,
2764    const memory_desc_ext &dst_desc, void *dst,
2765    const memory_desc_ext &scale_bias_desc, void *scale, void *bias,
2766    const memory_desc_ext &mean_var_desc, void *saved_mean, void *saved_var,
2767    void *running_mean, void *running_var) {
2768  if (scale_parameter_preprocess({{alpha, beta, dst_desc, dst}})) {
2769    return sycl::event();
2770  }
2771  enter_primitive(src_desc.get_size() + 5 * dst_desc.get_size() +
2772                  scale_bias_desc.get_size() * 2 +
2773                  mean_var_desc.get_size() * 9);
2774  void *reordered_src = nullptr, *reordered_dst = nullptr,
2775       *reordered_scale = nullptr, *reordered_bias = nullptr,
2776       *reordered_saved_mean = nullptr, *reordered_saved_var = nullptr;
2777  ::dnnl::memory::desc help_src_desc = src_desc.get_desc();
2778  ::dnnl::memory::desc help_dst_desc = dst_desc.get_desc();
2779  ::dnnl::memory::desc help_scale_bias_desc = scale_bias_desc.get_desc();
2780  ::dnnl::memory::desc help_mean_var_desc = mean_var_desc.get_desc();
2781  ::dnnl::memory::desc actual_dst_desc = help_dst_desc;
2782  ::dnnl::memory::desc actual_mean_var_desc = help_mean_var_desc;
2783
2784  if (mode == batch_normalization_mode::per_activation) {
2785    help_src_desc = bn_reorder_memory_to_channel_major_format(true, help_src_desc, src,
2786                                                       &reordered_src);
2787    help_dst_desc = bn_reorder_memory_to_channel_major_format(
2788        false, help_dst_desc, dst, &reordered_dst);
2789    actual_dst_desc = help_dst_desc;
2790    help_scale_bias_desc = bn_reorder_memory_to_channel_major_format(
2791        true, help_scale_bias_desc, scale, &reordered_scale);
2792    bn_reorder_memory_to_channel_major_format(true, help_scale_bias_desc, bias,
2793                                       &reordered_bias);
2794    help_mean_var_desc = bn_reorder_memory_to_channel_major_format(
2795        is_infer, help_mean_var_desc, saved_mean,
2796        &reordered_saved_mean);
2797    actual_mean_var_desc = help_mean_var_desc;
2798    bn_reorder_memory_to_channel_major_format(is_infer,
2799                                       help_mean_var_desc, saved_var,
2800                                       &reordered_saved_var);
2801    help_src_desc = compress_spatial_dimensions_to_channel(help_src_desc);
2802    help_dst_desc = compress_spatial_dimensions_to_channel(help_dst_desc);
2803  } else {
2804    if (help_src_desc != help_dst_desc) {
2805      help_src_desc = bn_reorder_memory_to_channel_major_format(
2806          true, help_src_desc, src, &reordered_src);
2807      help_dst_desc = bn_reorder_memory_to_channel_major_format(
2808          false, help_dst_desc, dst, &reordered_dst);
2809      actual_dst_desc = help_dst_desc;
2810    }
2811  }
2812  help_scale_bias_desc =
2813      get_bn_scale_bias_mean_var_desc(help_scale_bias_desc, mode);
2814  help_mean_var_desc =
2815      get_bn_scale_bias_mean_var_desc(help_mean_var_desc, mode);
2816
2817  ::dnnl::prop_kind kind;
2818  ::dnnl::normalization_flags flag = ::dnnl::normalization_flags::use_scale |
2819                                     ::dnnl::normalization_flags::use_shift;
2820  if (is_infer) {
2821    kind = ::dnnl::prop_kind::forward_inference;
2822    flag = ::dnnl::normalization_flags::use_global_stats | flag;
2823  } else {
2824    kind = ::dnnl::prop_kind::forward_training;
2825  }
2826  auto primitive_args =
2827      create_primitive_args_or_get<::dnnl::batch_normalization_forward>(
2828          kind, help_src_desc, help_dst_desc, epsilon, flag);
2829
2830  insert_arg(primitive_args.second.args, DNNL_ARG_SRC, help_src_desc,
2831             reordered_src ? reordered_src : src);
2832  insert_arg(primitive_args.second.args, DNNL_ARG_SCALE, help_scale_bias_desc,
2833             reordered_scale ? reordered_scale : scale);
2834  insert_arg(primitive_args.second.args, DNNL_ARG_SHIFT, help_scale_bias_desc,
2835             reordered_bias ? reordered_bias : bias);
2836  insert_arg(primitive_args.second.args, DNNL_ARG_MEAN, help_mean_var_desc,
2837             reordered_saved_mean ? reordered_saved_mean
2838                                            : saved_mean);
2839  insert_arg(primitive_args.second.args, DNNL_ARG_VARIANCE, help_mean_var_desc,
2840             reordered_saved_var ? reordered_saved_var
2841                                           : saved_var);
2842  insert_arg(primitive_args.second.args, DNNL_ARG_DST, help_dst_desc,
2843             reordered_dst ? reordered_dst : dst);
2844  sycl::event e = execute_primitive<::dnnl::batch_normalization_forward>(primitive_args,
2845                                    {{alpha, beta, DNNL_ARG_DST, help_dst_desc,
2846                                      reordered_dst ? reordered_dst : dst}});
2847
2848  if (!is_infer && running_var) {
2849    auto src_ndim = src_desc.get_desc().get_ndims();
2850    auto src_dims = src_desc.get_dims();
2851    int element_num = src_dims[0];
2852    if (mode == batch_normalization_mode::spatial) {
2853      for (int index = 2; index < src_ndim; index++) {
2854        element_num *= src_dims[index];
2855      }
2856    }
2857    float unbias_factor = element_num / (element_num - 1.f);
2858    async_scale(1.f - factor, mean_var_desc, running_var);
2859    e = async_sum(factor * unbias_factor, mean_var_desc,
2860            reordered_saved_var ? reordered_saved_var : saved_var,
2861            1.f, mean_var_desc, running_var);
2862  }
2863  if (!is_infer && running_mean) {
2864    e = async_sum(factor, mean_var_desc,
2865            reordered_saved_mean ? reordered_saved_mean : saved_mean,
2866            (1.f - factor), mean_var_desc, running_mean);
2867  }
2868  if (reordered_dst && (actual_dst_desc != dst_desc.get_desc())) {
2869    e = async_reorder(1.f, actual_dst_desc, reordered_dst, 0.f, dst_desc, dst);
2870  }
2871  if (!is_infer && reordered_saved_mean && reordered_saved_var && saved_mean &&
2872      saved_var && (actual_mean_var_desc != mean_var_desc.get_desc())) {
2873    e = async_reorder(1.f, actual_mean_var_desc, reordered_saved_mean, 0.f,
2874                mean_var_desc, saved_mean);
2875    e = async_reorder(1.f, actual_mean_var_desc, reordered_saved_var, 0.f,
2876                mean_var_desc, saved_var);
2877  }
2878  return exit_primitive(e);
2879}
2880
2881inline
2882sycl::event engine_ext::rnn_forward_internal(
2883    const rnn_desc &desc, ::dnnl::prop_kind kind,
2884    const memory_desc_ext &src_desc, void *src, const memory_desc_ext &dst_desc,
2885    void *dst, const memory_desc_ext &iter_desc, void *src_iter, void *dst_iter,
2886    const memory_desc_ext &iter_c_desc, void *src_iter_c, void *dst_iter_c,
2887    size_t weight_size, void *weight, size_t workspace_size, void *workspace,
2888    size_t scratchpad_size, void *scratchpad, bool is_get_execution_args,
2889    size_t *weight_size_query, size_t *workspace_size_query,
2890    size_t *scratchpad_size_query) {
2891  ::dnnl::memory::data_type src_dt;
2892  ::dnnl::memory::format_tag src_format_tag;
2893  rnn_mode mode;
2894  rnn_bias_mode bias_mode;
2895  rnn_direction direction;
2896  dpct::library_data_t dt;
2897  int direction_num = 1, input_size = 0, hidden_size = 0, projection_size = 0,
2898      layer_size = 0, gate_num = 1, output_size = 0, data_type_size = 0,
2899      seq_length = 1, batch_size = 1;
2900  std::vector<void *> data = {src,        dst,        src_iter, dst_iter,
2901                              src_iter_c, dst_iter_c, weight,   workspace,
2902                              scratchpad};
2903  std::vector<int> offset(6, 0);
2904  void *input_layer_cache = nullptr, *hidden_layer_cache = nullptr;
2905  sycl::event e;
2906  enter_primitive(src_desc.get_size() * 2);
2907  desc.get(&mode, &bias_mode, &direction, &dt, &input_size, &hidden_size,
2908           &projection_size, &layer_size);
2909
2910  get_rnn_configuration(src_desc.get_desc(), direction, mode, dt, hidden_size,
2911                        &src_dt, &src_format_tag, &projection_size,
2912                        &output_size, &seq_length, &batch_size, &direction_num,
2913                        &gate_num);
2914
2915  if (direction == rnn_direction::bidirectional) {
2916    // Here to combine the oneDNN bidirectional_sum and 
2917    // bidirectional_concat config, so call execute_rnn_forward_primitive
2918    // twice.
2919    if (layer_size > 1) {
2920      if (!is_get_execution_args) {
2921        input_layer_cache = allocate(src_desc);
2922        hidden_layer_cache = allocate(src_desc);
2923        _q->memcpy(input_layer_cache, src, src_desc.get_size());
2924      }
2925      data[0] = input_layer_cache;
2926      data[1] = hidden_layer_cache;
2927      e = execute_rnn_forward_primitive(
2928          mode, kind, ::dnnl::rnn_direction::bidirectional_sum, bias_mode,
2929          src_dt, src_format_tag, seq_length, batch_size, output_size,
2930          output_size, 1, direction_num, hidden_size, gate_num, projection_size,
2931          data, offset, layer_size - 1, weight_size_query, workspace_size_query,
2932          scratchpad_size_query);
2933      data[0] =
2934          ((layer_size - 1) % 2 == 0) ? input_layer_cache : hidden_layer_cache;
2935      data[1] = dst;
2936    }
2937    e = execute_rnn_forward_primitive(
2938        mode, kind, ::dnnl::rnn_direction::bidirectional_concat, bias_mode,
2939        src_dt, src_format_tag, seq_length, batch_size, output_size,
2940        2 * output_size, 1, direction_num, hidden_size, gate_num,
2941        projection_size, data, offset, 1, weight_size_query,
2942        workspace_size_query, scratchpad_size_query);
2943  } else {
2944    e = execute_rnn_forward_primitive(
2945        mode, kind, ::dnnl::rnn_direction::unidirectional_left2right, bias_mode,
2946        src_dt, src_format_tag, seq_length, batch_size, output_size,
2947        output_size, layer_size, direction_num, hidden_size, gate_num,
2948        projection_size, data, offset, 1, weight_size_query,
2949        workspace_size_query, scratchpad_size_query);
2950  }
2951
2952  return exit_primitive(e);
2953}
2954
2955inline
2956sycl::event engine_ext::execute_rnn_forward_primitive(
2957    rnn_mode mode, ::dnnl::prop_kind kind, ::dnnl::rnn_direction direction,
2958    rnn_bias_mode bias_mode, ::dnnl::memory::data_type dt,
2959    ::dnnl::memory::format_tag tag, int seq_length, int batch_size, int src_c,
2960    int dst_c, int layer_size, int direction_num, int hidden_size, int gate_num,
2961    int projection_size, std::vector<void *> &data, std::vector<int> &offset,
2962    int iter_num, size_t *weight_size, size_t *workspace_size,
2963    size_t *scratchpad_size) {
2964
2965  sycl::event e;
2966  ::dnnl::primitive *p = nullptr;
2967  std::unordered_map<int, ::dnnl::memory> *args = nullptr;
2968  detail::primitive_cache_key_type key;
2969  std::unordered_map<int, ::dnnl::memory> *execution_args;
2970  ::dnnl::memory::desc bias_desc(
2971      {layer_size, direction_num, gate_num, hidden_size}, dt,
2972      ::dnnl::memory::format_tag::ldgo);
2973  ::dnnl::memory::desc weight_layer_desc(
2974      {layer_size, direction_num,
2975       projection_size ? projection_size : hidden_size, gate_num, hidden_size},
2976      dt, ::dnnl::memory::format_tag::ldigo);
2977  ::dnnl::memory::desc weight_iter_desc(
2978      {layer_size, direction_num,
2979       projection_size ? projection_size : hidden_size, gate_num, hidden_size},
2980      dt, ::dnnl::memory::format_tag::ldigo);
2981  ::dnnl::memory::desc projection_desc;
2982  if (projection_size) {
2983    projection_desc = ::dnnl::memory::desc(
2984        {layer_size, direction_num, hidden_size, projection_size}, dt,
2985        ::dnnl::memory::format_tag::ldio);
2986  }
2987
2988  if (weight_size) {
2989    *weight_size +=
2990        (weight_layer_desc.get_size() + weight_iter_desc.get_size() +
2991         projection_desc.get_size() + bias_desc.get_size()) *
2992        iter_num;
2993    return e;
2994  }
2995
2996  ::dnnl::memory::desc src_desc({seq_length, batch_size, src_c}, dt, tag);
2997  ::dnnl::memory::desc dst_desc({seq_length, batch_size, dst_c}, dt, tag);
2998  ::dnnl::memory::desc iter_desc(
2999      {layer_size, direction_num, batch_size,
3000       projection_size ? projection_size : hidden_size},
3001      dt, ::dnnl::memory::format_tag::ldnc);
3002  ::dnnl::memory::desc iter_c_desc(
3003      {layer_size, direction_num, batch_size, hidden_size}, dt,
3004      ::dnnl::memory::format_tag::ldnc);
3005
3006  ::dnnl::memory::desc workspace_desc;
3007  ::dnnl::memory::desc scratchpad_desc;
3008  ::dnnl::primitive_attr attr;
3009  attr.set_scratchpad_mode(::dnnl::scratchpad_mode::user);
3010
3011  if (mode == rnn_mode::vanilla_relu || mode == rnn_mode::vanilla_tanh) {
3012    auto primitive = create_primitive_args_or_get<::dnnl::vanilla_rnn_forward>(
3013        kind,
3014        mode == rnn_mode::vanilla_relu ? ::dnnl::algorithm::eltwise_relu
3015                                       : ::dnnl::algorithm::eltwise_tanh,
3016        direction, src_desc, iter_desc, weight_layer_desc, weight_iter_desc,
3017        bias_desc, dst_desc, iter_desc, attr);
3018
3019    auto pd = get_primitive_desc<::dnnl::vanilla_rnn_forward>(
3020        primitive.second.primitive);
3021
3022    workspace_desc = pd.workspace_desc();
3023    scratchpad_desc = pd.scratchpad_desc();
3024    if (workspace_size && scratchpad_size) {
3025      *workspace_size += workspace_desc.get_size() * iter_num;
3026      *scratchpad_size = scratchpad_desc.get_size() > *scratchpad_size
3027                             ? scratchpad_desc.get_size()
3028                             : *scratchpad_size;
3029    } else {
3030      key = primitive.first;
3031      p = primitive.second.primitive;
3032      args = primitive.second.args;
3033    }
3034  } else if (mode == rnn_mode::gru) {
3035    auto primitive = create_primitive_args_or_get<::dnnl::gru_forward>(
3036        kind, direction, src_desc, iter_desc, weight_layer_desc,
3037        weight_iter_desc, bias_desc, dst_desc, iter_desc, attr);
3038
3039    auto pd =
3040        get_primitive_desc<::dnnl::gru_forward>(primitive.second.primitive);
3041
3042    workspace_desc = pd.workspace_desc();
3043    scratchpad_desc = pd.scratchpad_desc();
3044    if (workspace_size && scratchpad_size) {
3045      *workspace_size += workspace_desc.get_size() * iter_num;
3046      *scratchpad_size = scratchpad_desc.get_size() > *scratchpad_size
3047                             ? scratchpad_desc.get_size()
3048                             : *scratchpad_size;
3049    } else {
3050      key = primitive.first;
3051      p = primitive.second.primitive;
3052      args = primitive.second.args;
3053    }
3054  } else if (mode == rnn_mode::lstm) {
3055    auto primitive = create_primitive_args_or_get<::dnnl::lstm_forward>(
3056        kind, direction, src_desc, iter_desc, iter_c_desc, weight_layer_desc,
3057        weight_iter_desc, ::dnnl::memory::desc(), projection_desc, bias_desc,
3058        dst_desc, iter_desc, iter_c_desc, attr);
3059
3060    auto pd =
3061        get_primitive_desc<::dnnl::lstm_forward>(primitive.second.primitive);
3062
3063    workspace_desc = pd.workspace_desc();
3064    scratchpad_desc = pd.scratchpad_desc();
3065    if (workspace_size && scratchpad_size) {
3066      *workspace_size += workspace_desc.get_size() * iter_num;
3067      *scratchpad_size = scratchpad_desc.get_size() > *scratchpad_size
3068                             ? scratchpad_desc.get_size()
3069                             : *scratchpad_size;
3070    } else {
3071      key = primitive.first;
3072      p = primitive.second.primitive;
3073      args = primitive.second.args;
3074    }
3075  }
3076
3077  for (int i = 0; i < iter_num; i++) {
3078    void *in_cache = data[0], *out_cache = data[1], *dst_iter_c_cache = nullptr,
3079         *dst_iter_cache = ((uint8_t *)(data[3]) + offset[1]);
3080    if (mode == rnn_mode::lstm) {
3081      dst_iter_c_cache = (uint8_t *)(data[4]) + offset[2];
3082    }
3083    if (!workspace_size) {
3084      insert_arg(args, DNNL_ARG_SRC_LAYER, src_desc, data[0]);
3085      insert_arg(args, DNNL_ARG_DST_LAYER, dst_desc, data[1]);
3086      insert_arg(args, DNNL_ARG_SCRATCHPAD, scratchpad_desc, data[8]);
3087      auto insert_rnn_arg = [&](int arg_name, ::dnnl::memory::desc &d, void *data,
3088                             int &offset) {
3089        insert_arg(args, arg_name, d, (uint8_t *)data + offset);
3090        offset += d.get_size();
3091      };
3092      insert_rnn_arg(DNNL_ARG_SRC_ITER, iter_desc, data[2], offset[0]);
3093      insert_rnn_arg(DNNL_ARG_DST_ITER, iter_desc, data[3], offset[1]);
3094
3095      if (mode == rnn_mode::lstm) {
3096        insert_rnn_arg(DNNL_ARG_SRC_ITER_C, iter_c_desc, data[4], offset[2]);
3097        insert_rnn_arg(DNNL_ARG_DST_ITER_C, iter_c_desc, data[5], offset[3]);
3098      }
3099      insert_rnn_arg(DNNL_ARG_WEIGHTS_LAYER, weight_layer_desc, data[6],
3100                  offset[4]);
3101      insert_rnn_arg(DNNL_ARG_WEIGHTS_ITER, weight_iter_desc, data[6], offset[4]);
3102      if (projection_size) {
3103        insert_rnn_arg(DNNL_ARG_WEIGHTS_PROJECTION, projection_desc, data[6],
3104                    offset[4]);
3105      }
3106      if (bias_mode == rnn_bias_mode::none) {
3107        _q->memset((uint8_t *)(data[6]) + offset[4], 0, bias_desc.get_size());
3108      }
3109      insert_rnn_arg(DNNL_ARG_BIAS, bias_desc, data[6], offset[4]);
3110      if (kind == ::dnnl::prop_kind::forward_training) {
3111        insert_rnn_arg(DNNL_ARG_WORKSPACE, workspace_desc, data[7], offset[5]);
3112      }
3113      if (mode == rnn_mode::vanilla_relu || mode == rnn_mode::vanilla_tanh) {
3114        execute_primitive<::dnnl::vanilla_rnn_forward>(
3115            {key, {static_cast<::dnnl::vanilla_rnn_forward *>(p), args}});
3116      } else if (mode == rnn_mode::gru) {
3117        execute_primitive<::dnnl::gru_forward>(
3118            {key, {static_cast<::dnnl::gru_forward *>(p), args}});
3119      } else if (mode == rnn_mode::lstm) {
3120        execute_primitive<::dnnl::lstm_forward>(
3121            {key, {static_cast<::dnnl::lstm_forward *>(p), args}});
3122      }
3123      if (i != iter_num - 1) {
3124        std::swap(data[0], data[1]);
3125      }
3126    }
3127    if (kind == ::dnnl::prop_kind::forward_training) {
3128      if (workspace_size) {
3129        *workspace_size +=
3130            (src_desc.get_size() + dst_desc.get_size() + iter_desc.get_size());
3131        if (mode == rnn_mode::lstm) {
3132          *workspace_size += iter_c_desc.get_size();
3133        }
3134      } else {
3135        _q->memcpy((uint8_t *)(data[7]) + offset[5], in_cache,
3136                   src_desc.get_size());
3137        offset[5] += src_desc.get_size();
3138        _q->memcpy((uint8_t *)(data[7]) + offset[5], out_cache,
3139                   dst_desc.get_size());
3140        offset[5] += dst_desc.get_size();
3141        _q->memcpy((uint8_t *)(data[7]) + offset[5], dst_iter_cache,
3142                   iter_desc.get_size());
3143        offset[5] += iter_desc.get_size();
3144        if (mode == rnn_mode::lstm) {
3145          _q->memcpy((uint8_t *)(data[7]) + offset[5], dst_iter_c_cache,
3146                     iter_c_desc.get_size());
3147          offset[5] += iter_c_desc.get_size();
3148        }
3149      }
3150    }
3151  }
3152  return e;
3153}
3154
3155inline
3156sycl::event engine_ext::execute_rnn_backward_primitive(
3157    rnn_mode mode, ::dnnl::rnn_direction direction, rnn_bias_mode bias_mode,
3158    ::dnnl::memory::data_type dt, ::dnnl::memory::format_tag tag,
3159    int seq_length, int batch_size, int src_c, int dst_c, int layer_size,
3160    int direction_num, int hidden_size, int gate_num, int projection_size,
3161    std::vector<void *> &data, std::vector<int> &offset, int iter_num) {
3162
3163  sycl::event e;
3164  ::dnnl::primitive *p = nullptr;
3165  std::unordered_map<int, ::dnnl::memory> *args = nullptr;
3166  detail::primitive_cache_key_type key;
3167  ::dnnl::prop_kind fkind = ::dnnl::prop_kind::forward_training;
3168  ::dnnl::prop_kind bkind = ::dnnl::prop_kind::backward;
3169  ::dnnl::memory::desc bias_desc(
3170      {layer_size, direction_num, gate_num, hidden_size}, dt,
3171      ::dnnl::memory::format_tag::ldgo);
3172  ::dnnl::memory::desc weight_layer_desc(
3173      {layer_size, direction_num,
3174       projection_size ? projection_size : hidden_size, gate_num, hidden_size},
3175      dt, ::dnnl::memory::format_tag::ldigo);
3176  ::dnnl::memory::desc weight_iter_desc(
3177      {layer_size, direction_num,
3178       projection_size ? projection_size : hidden_size, gate_num, hidden_size},
3179      dt, ::dnnl::memory::format_tag::ldigo);
3180  ::dnnl::memory::desc diff_weight_layer_desc(
3181      {layer_size, direction_num,
3182       projection_size ? projection_size : hidden_size, gate_num, hidden_size},
3183      dt, ::dnnl::memory::format_tag::ldgoi);
3184  ::dnnl::memory::desc diff_weight_iter_desc(
3185      {layer_size, direction_num,
3186       projection_size ? projection_size : hidden_size, gate_num, hidden_size},
3187      dt, ::dnnl::memory::format_tag::ldgoi);
3188  ::dnnl::memory::desc projection_desc, diff_projection_desc;
3189  if (projection_size) {
3190    projection_desc = ::dnnl::memory::desc(
3191        {layer_size, direction_num, hidden_size, projection_size}, dt,
3192        ::dnnl::memory::format_tag::ldio);
3193    diff_projection_desc = ::dnnl::memory::desc(
3194        {layer_size, direction_num, hidden_size, projection_size}, dt,
3195        ::dnnl::memory::format_tag::ldoi);
3196  }
3197
3198  ::dnnl::memory::desc src_desc({seq_length, batch_size, src_c}, dt, tag);
3199  ::dnnl::memory::desc dst_desc({seq_length, batch_size, dst_c}, dt, tag);
3200  ::dnnl::memory::desc iter_desc(
3201      {layer_size, direction_num, batch_size,
3202       projection_size ? projection_size : hidden_size},
3203      dt, ::dnnl::memory::format_tag::ldnc);
3204  ::dnnl::memory::desc iter_c_desc(
3205      {layer_size, direction_num, batch_size, hidden_size}, dt,
3206      ::dnnl::memory::format_tag::ldnc);
3207
3208  ::dnnl::memory::desc workspace_desc;
3209  ::dnnl::memory::desc scratchpad_desc;
3210  ::dnnl::primitive_attr attr;
3211  attr.set_scratchpad_mode(::dnnl::scratchpad_mode::user);
3212
3213  if (mode == rnn_mode::vanilla_relu || mode == rnn_mode::vanilla_tanh) {
3214    auto fpd = create_primitive_desc<::dnnl::vanilla_rnn_forward>(
3215        fkind,
3216        mode == rnn_mode::vanilla_relu ? ::dnnl::algorithm::eltwise_relu
3217                                       : ::dnnl::algorithm::eltwise_tanh,
3218        direction, src_desc, iter_desc, weight_layer_desc, weight_iter_desc,
3219        bias_desc, dst_desc, iter_desc, attr);
3220    auto primitive = create_primitive_args_or_get<::dnnl::vanilla_rnn_backward>(
3221        bkind,
3222        mode == rnn_mode::vanilla_relu ? ::dnnl::algorithm::eltwise_relu
3223                                       : ::dnnl::algorithm::eltwise_tanh,
3224        direction, src_desc, iter_desc, diff_weight_layer_desc,
3225        diff_weight_iter_desc, bias_desc, dst_desc, iter_desc, src_desc,
3226        iter_desc, weight_layer_desc, weight_iter_desc, bias_desc, dst_desc,
3227        iter_desc, fpd, attr);
3228    auto pd = get_primitive_desc<::dnnl::vanilla_rnn_backward>(
3229        primitive.second.primitive);
3230    workspace_desc = pd.workspace_desc();
3231    scratchpad_desc = pd.scratchpad_desc();
3232    key = primitive.first;
3233    p = primitive.second.primitive;
3234    args = primitive.second.args;
3235  } else if (mode == rnn_mode::gru) {
3236    auto fpd = create_primitive_desc<::dnnl::gru_forward>(
3237        fkind, direction, src_desc, iter_desc, weight_layer_desc,
3238        weight_iter_desc, bias_desc, dst_desc, iter_desc, attr);
3239    auto primitive = create_primitive_args_or_get<::dnnl::gru_backward>(
3240        bkind, direction, src_desc, iter_desc, diff_weight_layer_desc,
3241        diff_weight_iter_desc, bias_desc, dst_desc, iter_desc, src_desc,
3242        iter_desc, weight_layer_desc, weight_iter_desc, bias_desc, dst_desc,
3243        iter_desc, fpd, attr);
3244    auto pd =
3245        get_primitive_desc<::dnnl::gru_backward>(primitive.second.primitive);
3246    workspace_desc = pd.workspace_desc();
3247    scratchpad_desc = pd.scratchpad_desc();
3248    key = primitive.first;
3249    p = primitive.second.primitive;
3250    args = primitive.second.args;
3251  } else if (mode == rnn_mode::lstm) {
3252    auto fpd = create_primitive_desc<::dnnl::lstm_forward>(
3253        fkind, direction, src_desc, iter_desc, iter_c_desc, weight_layer_desc,
3254        weight_iter_desc, ::dnnl::memory::desc(), projection_desc, bias_desc,
3255        dst_desc, iter_desc, iter_c_desc, attr);
3256    auto primitive = create_primitive_args_or_get<::dnnl::lstm_backward>(
3257        bkind, direction, src_desc, iter_desc, iter_c_desc,
3258        diff_weight_layer_desc, diff_weight_iter_desc, ::dnnl::memory::desc(),
3259        diff_projection_desc, bias_desc, dst_desc, iter_desc, iter_c_desc,
3260        src_desc, iter_desc, iter_c_desc, weight_layer_desc, weight_iter_desc,
3261        ::dnnl::memory::desc(), projection_desc, bias_desc, dst_desc, iter_desc,
3262        iter_c_desc, fpd, attr);
3263    auto pd =
3264        get_primitive_desc<::dnnl::lstm_backward>(primitive.second.primitive);
3265    workspace_desc = pd.workspace_desc();
3266    scratchpad_desc = pd.scratchpad_desc();
3267    key = primitive.first;
3268    p = primitive.second.primitive;
3269    args = primitive.second.args;
3270  }
3271
3272  for (int i = 0; i < iter_num; i++) {
3273    insert_arg(args, DNNL_ARG_DIFF_SRC_LAYER, src_desc, data[8]);
3274    insert_arg(args, DNNL_ARG_DIFF_DST_LAYER, dst_desc, data[9]);
3275    insert_arg(args, DNNL_ARG_SCRATCHPAD, scratchpad_desc, data[15]);
3276    auto insert_rnn_arg = [&](int arg_name, ::dnnl::memory::desc &d, void *data,
3277                           int &offset) {
3278      offset += d.get_size();
3279      insert_arg(args, arg_name, d, (uint8_t *)data - offset);
3280    };
3281    if (mode == rnn_mode::lstm) {
3282      insert_rnn_arg(DNNL_ARG_DST_ITER_C, iter_c_desc, data[7], offset[0]);
3283      insert_rnn_arg(DNNL_ARG_SRC_ITER_C, iter_c_desc, data[4], offset[2]);
3284    }
3285    insert_rnn_arg(DNNL_ARG_DST_ITER, iter_desc, data[7], offset[0]);
3286    insert_rnn_arg(DNNL_ARG_DST_LAYER, dst_desc, data[7], offset[0]);
3287    insert_rnn_arg(DNNL_ARG_SRC_LAYER, src_desc, data[7], offset[0]);
3288    insert_rnn_arg(DNNL_ARG_WORKSPACE, workspace_desc, data[7], offset[0]);
3289    insert_rnn_arg(DNNL_ARG_SRC_ITER, iter_desc, data[2], offset[1]);
3290    insert_rnn_arg(DNNL_ARG_BIAS, bias_desc, data[6], offset[3]);
3291    if (projection_size) {
3292      insert_rnn_arg(DNNL_ARG_WEIGHTS_PROJECTION, diff_projection_desc, data[6],
3293                  offset[3]);
3294    }
3295    insert_rnn_arg(DNNL_ARG_WEIGHTS_ITER, diff_weight_iter_desc, data[6],
3296                offset[3]);
3297    insert_rnn_arg(DNNL_ARG_WEIGHTS_LAYER, diff_weight_layer_desc, data[6],
3298                offset[3]);
3299    insert_rnn_arg(DNNL_ARG_DIFF_SRC_ITER, iter_desc, data[10], offset[4]);
3300    insert_rnn_arg(DNNL_ARG_DIFF_DST_ITER, iter_desc, data[11], offset[5]);
3301    if (mode == rnn_mode::lstm) {
3302      insert_rnn_arg(DNNL_ARG_DIFF_SRC_ITER_C, iter_c_desc, data[12], offset[6]);
3303      insert_rnn_arg(DNNL_ARG_DIFF_DST_ITER_C, iter_c_desc, data[13], offset[7]);
3304    }
3305    insert_rnn_arg(DNNL_ARG_DIFF_BIAS, bias_desc, data[14], offset[8]);
3306    if (bias_mode == rnn_bias_mode::none) {
3307      _q->memset((uint8_t *)(data[14]) - offset[8], 0, bias_desc.get_size());
3308    }
3309    if (projection_size) {
3310      insert_rnn_arg(DNNL_ARG_DIFF_WEIGHTS_PROJECTION, projection_desc, data[14],
3311                  offset[8]);
3312    }
3313    insert_rnn_arg(DNNL_ARG_DIFF_WEIGHTS_ITER, weight_iter_desc, data[14],
3314                offset[8]);
3315    insert_rnn_arg(DNNL_ARG_DIFF_WEIGHTS_LAYER, weight_layer_desc, data[14],
3316                offset[8]);
3317    if (mode == rnn_mode::vanilla_relu || mode == rnn_mode::vanilla_tanh) {
3318      e = execute_primitive<::dnnl::vanilla_rnn_backward>(
3319          {key, {static_cast<::dnnl::vanilla_rnn_backward *>(p), args}});
3320    } else if (mode == rnn_mode::gru) {
3321      e = execute_primitive<::dnnl::gru_backward>(
3322          {key, {static_cast<::dnnl::gru_backward *>(p), args}});
3323    } else if (mode == rnn_mode::lstm) {
3324      e = execute_primitive<::dnnl::lstm_backward>(
3325          {key, {static_cast<::dnnl::lstm_backward *>(p), args}});
3326    }
3327    if (i != iter_num - 1) {
3328      std::swap(data[8], data[9]);
3329    }
3330  }
3331  return e;
3332}
3333
3334#define EMPTY_CACHE_KEY(type)                                                  \
3335  template <>                                                                  \
3336  inline void engine_ext::generate_cache_key<type>(std::string & key_buffer,   \
3337                                                   const type &arg) {}
3338
3339EMPTY_CACHE_KEY(::dnnl::engine)
3340EMPTY_CACHE_KEY(::dnnl::convolution_forward::primitive_desc)
3341EMPTY_CACHE_KEY(::dnnl::eltwise_forward::primitive_desc)
3342EMPTY_CACHE_KEY(::dnnl::softmax_forward::primitive_desc)
3343EMPTY_CACHE_KEY(::dnnl::pooling_forward::primitive_desc)
3344EMPTY_CACHE_KEY(::dnnl::lrn_forward::primitive_desc)
3345EMPTY_CACHE_KEY(::dnnl::batch_normalization_forward::primitive_desc)
3346EMPTY_CACHE_KEY(::dnnl::vanilla_rnn_forward::primitive_desc)
3347EMPTY_CACHE_KEY(::dnnl::lstm_forward::primitive_desc)
3348EMPTY_CACHE_KEY(::dnnl::gru_forward::primitive_desc)
3349#undef EMPTY_CACHE_KEY
3350
3351template <>
3352inline void engine_ext::generate_cache_key<std::vector<float>>(
3353    std::string &key_buffer, const std::vector<float> &vec) {
3354  key_buffer.append((char *)vec.data(), vec.size() * sizeof(float));
3355}
3356
3357template <>
3358inline void engine_ext::generate_cache_key<::dnnl::primitive_attr>(
3359    std::string &key_buffer, const ::dnnl::primitive_attr &attr) {
3360  if (!attr) {
3361    return;
3362  }
3363  auto math_mode = (uint8_t)attr.get_fpmath_mode();
3364  key_buffer.append((char *)&math_mode, sizeof(uint8_t));
3365}
3366
3367template <>
3368inline void engine_ext::generate_cache_key<::dnnl::memory::dims>(
3369    std::string &key_buffer, const ::dnnl::memory::dims &dims) {
3370  key_buffer.append((char *)dims.data(), dims.size() * sizeof(int64_t));
3371}
3372
3373template <>
3374inline void engine_ext::generate_cache_key<::dnnl::memory::desc>(
3375    std::string &key_buffer, const ::dnnl::memory::desc &desc) {
3376  uint8_t params[3] = {(uint8_t)desc.get_format_kind(),
3377                       (uint8_t)desc.get_ndims(),
3378                       (uint8_t)desc.get_data_type()};
3379  generate_cache_key(key_buffer, desc.get_inner_blks());
3380  generate_cache_key(key_buffer, desc.get_dims());
3381  generate_cache_key(key_buffer, desc.get_strides());
3382}
3383
3384template <typename T>
3385void engine_ext::generate_cache_key(std::string &key_buffer, const T &arg) {
3386  key_buffer.append((char *)&arg, sizeof(T));
3387}
3388
3389template <typename T, typename... args_type>
3390void engine_ext::generate_cache_key(std::string &key_buffer, const T &first_arg,
3391                                    const args_type &...args) {
3392  generate_cache_key(key_buffer, first_arg);
3393  generate_cache_key(key_buffer, args...);
3394}
3395
3396template <typename primitive_type, typename... args_type>
3397std::pair<detail::primitive_cache_key_type, detail::primitive_and_args>
3398engine_ext::create_primitive_args_or_get(args_type &&...args) {
3399  std::string buffer;
3400  buffer.reserve(512);
3401  generate_cache_key(buffer, std::forward<args_type>(args)...);
3402  buffer.append(std::to_string(_engine_id));
3403  auto value = _primitive_cache.get(buffer);
3404  primitive_type *p = nullptr;
3405  std::unordered_map<int, ::dnnl::memory> *a = nullptr;
3406  if (value) {
3407    p = (primitive_type *)value->_primitive;
3408    a = value->_args;
3409  } else {
3410    p = new primitive_type(create_primitive_desc<primitive_type>(
3411        std::forward<args_type>(args)...));
3412    a = new std::unordered_map<int, ::dnnl::memory>();
3413  }
3414  return {buffer, {p, a}};
3415}
3416
3417template <typename primitive_type>
3418typename primitive_type::primitive_desc
3419engine_ext::get_primitive_desc(::dnnl::primitive *p) {
3420  return typename primitive_type::primitive_desc(
3421      const_cast<dnnl_primitive_desc_t>(p->get_primitive_desc()));
3422}
3423
3424template <typename primitive_type, typename... args_type>
3425typename primitive_type::primitive_desc
3426engine_ext::create_primitive_desc(args_type &&...args) {
3427  return typename primitive_type::primitive_desc(
3428      *_eng, std::forward<args_type>(args)...);
3429}
3430
3431inline
3432void engine_ext::fill(const memory_desc_ext &src_desc, void *src,
3433                      const void *valuePtr) {
3434  async_fill(src_desc, src, valuePtr).wait();
3435}
3436
3437inline
3438void engine_ext::reorder(float alpha, const memory_desc_ext &src_desc,
3439                         void *src, float beta, const memory_desc_ext &dst_desc,
3440                         void *dst) {
3441  async_reorder(alpha, src_desc, src, beta, dst_desc, dst).wait();
3442}
3443
3444inline
3445void engine_ext::scale(float alpha, const memory_desc_ext &src_desc,
3446                       void *src) {
3447  async_scale(alpha, src_desc, src).wait();
3448}
3449inline
3450void engine_ext::sum(float alpha, const memory_desc_ext &src_desc, void *src,
3451                     float beta, const memory_desc_ext &dst_desc, void *dst) {
3452  async_sum(alpha, src_desc, src, beta, dst_desc, dst).wait();
3453}
3454inline
3455void engine_ext::activation_forward(activation_desc &desc, float alpha,
3456                                    const memory_desc_ext &src_desc, void *src,
3457                                    float beta, const memory_desc_ext &dst_desc,
3458                                    void *dst) {
3459  async_activation_forward(desc, alpha, src_desc, src, beta, dst_desc, dst)
3460      .wait();
3461}
3462inline
3463void engine_ext::activation_backward(
3464    activation_desc &desc, float alpha, const memory_desc_ext &dst_desc,
3465    void *dst, const memory_desc_ext &diff_dst_desc, void *diff_dst,
3466    const memory_desc_ext &src_desc, void *src, float beta,
3467    const memory_desc_ext &diff_src_desc, void *diff_src) {
3468  async_activation_backward(desc, alpha, dst_desc, dst, diff_dst_desc, diff_dst,
3469                            src_desc, src, beta, diff_src_desc, diff_src)
3470      .wait();
3471}
3472inline
3473void engine_ext::pooling_forward(pooling_desc &desc, float alpha,
3474                                 const memory_desc_ext &src_desc, void *src,
3475                                 float beta, const memory_desc_ext &dst_desc,
3476                                 void *dst,
3477                                 ::dnnl::memory *workspace) {
3478  async_pooling_forward(desc, alpha, src_desc, src, beta, dst_desc, dst,
3479                        workspace).wait();
3480}
3481
3482inline
3483void engine_ext::pooling_backward(
3484    pooling_desc &desc, float alpha, const memory_desc_ext &dst_desc, void *dst,
3485    const memory_desc_ext &diff_dst_desc, void *diff_dst,
3486    const memory_desc_ext &src_desc, void *src, float beta,
3487    const memory_desc_ext &diff_src_desc, void *diff_src,
3488    ::dnnl::memory *workspace) {
3489  async_pooling_backward(desc, alpha, dst_desc, dst, diff_dst_desc, diff_dst,
3490                         src_desc, src, beta, diff_src_desc, diff_src,
3491                         workspace)
3492      .wait();
3493}
3494
3495inline
3496void engine_ext::softmax_forward(softmax_algorithm alg, softmax_mode mode,
3497                                 float alpha, const memory_desc_ext &src_desc,
3498                                 void *src, float beta,
3499                                 const memory_desc_ext &dst_desc, void *dst) {
3500  async_softmax_forward(alg, mode, alpha, src_desc, src, beta, dst_desc, dst)
3501      .wait();
3502}
3503
3504inline
3505void engine_ext::softmax_backward(softmax_algorithm alg, softmax_mode mode,
3506                                  float alpha, const memory_desc_ext &dst_desc,
3507                                  void *dst,
3508                                  const memory_desc_ext &diff_dst_desc,
3509                                  void *diff_dst, float beta,
3510                                  const memory_desc_ext &diff_src_desc,
3511                                  void *diff_src) {
3512  async_softmax_backward(alg, mode, alpha, dst_desc, dst, diff_dst_desc,
3513                         diff_dst, beta, diff_src_desc, diff_src)
3514      .wait();
3515}
3516
3517inline
3518void engine_ext::lrn_forward(lrn_desc &desc, float alpha,
3519                             const memory_desc_ext &src_desc, void *src,
3520                             float beta, const memory_desc_ext &dst_desc,
3521                             void *dst, ::dnnl::memory *workspace) {
3522  async_lrn_forward(desc, alpha, src_desc, src, beta, dst_desc, dst, workspace)
3523      .wait();
3524}
3525
3526inline
3527void engine_ext::lrn_backward(lrn_desc &desc, float alpha,
3528                              const memory_desc_ext &dst_desc, void *dst,
3529                              const memory_desc_ext &diff_dst_desc,
3530                              void *diff_dst, const memory_desc_ext &src_desc,
3531                              void *src, float beta,
3532                              const memory_desc_ext &diff_src_desc,
3533                              void *diff_src,
3534                              ::dnnl::memory *workspace) {
3535  async_lrn_backward(desc, alpha, dst_desc, dst, diff_dst_desc, diff_dst,
3536                     src_desc, src, beta, diff_src_desc, diff_src, workspace)
3537      .wait();
3538}
3539
3540inline
3541sycl::event engine_ext::async_fill(const memory_desc_ext &src_desc, void *src,
3542                             const void *valuePtr) {
3543  ::dnnl::memory::data_type dt = src_desc.get_desc().get_data_type();
3544  unsigned mem_size = src_desc.get_size();
3545  switch (dt) {
3546  case ::dnnl::memory::data_type::f32:
3547    return fill_with_type<float>(_q, src, valuePtr, mem_size);
3548  case ::dnnl::memory::data_type::f16:
3549    return fill_with_type<sycl::half>(_q, src, valuePtr, mem_size);
3550  case ::dnnl::memory::data_type::s32:
3551    return fill_with_type<int32_t>(_q, src, valuePtr, mem_size);
3552  case ::dnnl::memory::data_type::s8:
3553    return fill_with_type<int8_t>(_q, src, valuePtr, mem_size);
3554  case ::dnnl::memory::data_type::u8:
3555    return fill_with_type<uint8_t>(_q, src, valuePtr, mem_size);
3556  default:
3557    throw std::runtime_error("async_fill: unsupported data type.");
3558  }
3559}
3560
3561inline
3562sycl::event engine_ext::async_reorder(float alpha, const memory_desc_ext &src_desc,
3563                                void *src, float beta,
3564                                const memory_desc_ext &dst_desc, void *dst) {
3565  if (scale_parameter_preprocess({{alpha, beta, dst_desc, dst}})) {
3566    return sycl::event();
3567  }
3568  enter_primitive(2 * dst_desc.get_size());
3569
3570  auto primitive_args = create_primitive_args_or_get<::dnnl::reorder>(
3571      src_desc.get_desc(), *_eng, dst_desc.get_desc());
3572
3573  insert_arg(primitive_args.second.args, DNNL_ARG_SRC, src_desc.get_desc(),
3574             src);
3575  insert_arg(primitive_args.second.args, DNNL_ARG_DST, dst_desc.get_desc(),
3576             dst);
3577
3578  return exit_primitive(execute_primitive<::dnnl::reorder>(
3579      primitive_args, {{alpha, beta, DNNL_ARG_DST, dst_desc, dst}}));
3580}
3581
3582inline
3583sycl::event engine_ext::async_scale(float alpha, const memory_desc_ext &src_desc,
3584                              void *src) {
3585  if (alpha == 1.f) {
3586    return sycl::event();
3587  }
3588  size_t cache_size = src_desc.get_size();
3589  enter_primitive(cache_size);
3590  void *src_cache = allocate(cache_size);
3591  _q->memcpy(src_cache, src, cache_size);
3592  auto primitive_args = create_primitive_args_or_get<::dnnl::eltwise_forward>(
3593      ::dnnl::prop_kind::forward_inference, ::dnnl::algorithm::eltwise_linear,
3594      src_desc.get_desc(), src_desc.get_desc(), alpha, 0.f);
3595
3596  insert_arg(primitive_args.second.args, DNNL_ARG_SRC, src_desc.get_desc(),
3597             src_cache);
3598  insert_arg(primitive_args.second.args, DNNL_ARG_DST, src_desc.get_desc(),
3599             src);
3600
3601  return exit_primitive(
3602      execute_primitive<::dnnl::eltwise_forward>(primitive_args));
3603}
3604
3605inline sycl::event
3606engine_ext::async_sum(float alpha, const memory_desc_ext &src_desc, void *src,
3607                      float beta, const memory_desc_ext &dst_desc, void *dst) {
3608  if (alpha == 0.f && beta == 1.f) {
3609    return sycl::event();
3610  }
3611  size_t cache_size = dst_desc.get_size();
3612  enter_primitive(cache_size);
3613  void *dst_cache = allocate(dst_desc);
3614  _q->memcpy(dst_cache, dst, cache_size);
3615
3616  auto primitive_args = create_primitive_args_or_get<::dnnl::sum>(
3617      std::vector<float>{alpha, beta},
3618      std::vector<::dnnl::memory::desc>{src_desc.get_desc(),
3619                                        dst_desc.get_desc()});
3620  insert_arg(primitive_args.second.args, DNNL_ARG_DST, dst_desc.get_desc(),
3621             dst);
3622  insert_arg(primitive_args.second.args, DNNL_ARG_MULTIPLE_SRC,
3623             src_desc.get_desc(), src);
3624  insert_arg(primitive_args.second.args, DNNL_ARG_MULTIPLE_SRC + 1,
3625             dst_desc.get_desc(), dst_cache);
3626
3627  return exit_primitive(execute_primitive<::dnnl::sum>(primitive_args));
3628}
3629
3630inline
3631sycl::event engine_ext::async_binary(binary_op op, float alpha_0,
3632                               const memory_desc_ext &src_desc_0, void *src_0,
3633                               float alpha_1, const memory_desc_ext &src_desc_1,
3634                               void *src_1, float beta,
3635                               const memory_desc_ext &dst_desc, void *dst) {
3636  ::dnnl::algorithm onednn_algorithm;
3637  switch (op) {
3638  case binary_op::max:
3639    onednn_algorithm = ::dnnl::algorithm::binary_max;
3640    break;
3641  case binary_op::min:
3642    onednn_algorithm = ::dnnl::algorithm::binary_min;
3643    break;
3644  case binary_op::add:
3645    onednn_algorithm = ::dnnl::algorithm::binary_add;
3646    break;
3647  case binary_op::sub:
3648    onednn_algorithm = ::dnnl::algorithm::binary_sub;
3649    break;
3650  case binary_op::mul:
3651    onednn_algorithm = ::dnnl::algorithm::binary_mul;
3652    break;
3653  case binary_op::div:
3654    onednn_algorithm = ::dnnl::algorithm::binary_div;
3655    break;
3656  case binary_op::sqrt:
3657    onednn_algorithm = ::dnnl::algorithm::eltwise_sqrt;
3658    break;
3659  case binary_op::neg:
3660    onednn_algorithm = ::dnnl::algorithm::eltwise_linear;
3661    break;
3662  }
3663  size_t src0_cache_size = src_desc_0.get_size();
3664  size_t src1_cache_size = src_desc_1.get_size();
3665  size_t dst_cache_size = dst_desc.get_size();
3666  enter_primitive(2 * src0_cache_size + 2 * src1_cache_size +
3667                  5 * dst_cache_size);
3668  if (onednn_algorithm == ::dnnl::algorithm::eltwise_sqrt ||
3669      onednn_algorithm == ::dnnl::algorithm::eltwise_linear) {
3670    void *src_cache = nullptr, *dst_cache = nullptr;
3671    src_cache = allocate(src0_cache_size);
3672    dst_cache = allocate(dst_cache_size);
3673    _q->memcpy(src_cache, src_0, src0_cache_size);
3674    _q->memcpy(dst_cache, dst, dst_cache_size);
3675    async_scale(alpha_0, src_desc_0, src_cache);
3676    async_scale(beta, dst_desc, dst_cache);
3677
3678    // Let the output = 1 - input to simulate the behavior of neg.
3679    auto primitive_args = create_primitive_args_or_get<::dnnl::eltwise_forward>(
3680        ::dnnl::prop_kind::forward_inference, onednn_algorithm,
3681        src_desc_0.get_desc(), dst_desc.get_desc(), -1.f, 1.f);
3682
3683    insert_arg(primitive_args.second.args, DNNL_ARG_SRC, src_desc_0.get_desc(),
3684               src_cache);
3685    insert_arg(primitive_args.second.args, DNNL_ARG_DST, dst_desc.get_desc(),
3686               dst);
3687
3688    execute_primitive<::dnnl::eltwise_forward>(
3689        primitive_args, {{1.f, 0.f, DNNL_ARG_DST, dst_desc, dst}});
3690    return exit_primitive(
3691        async_sum(1.f, dst_desc, dst_cache, 1.f, dst_desc, dst));
3692  }
3693
3694  void *src_0_cache = nullptr, *src_1_cache = nullptr, *dst_cache = nullptr;
3695
3696  src_0_cache = allocate(src0_cache_size);
3697  src_1_cache = allocate(src1_cache_size);
3698  dst_cache = allocate(dst_cache_size);
3699
3700  _q->memcpy(src_0_cache, src_0, src0_cache_size);
3701  _q->memcpy(src_1_cache, src_1, src1_cache_size);
3702  _q->memcpy(dst_cache, dst, dst_cache_size);
3703
3704  async_scale(alpha_0, src_desc_0, src_0_cache);
3705  async_scale(alpha_1, src_desc_1, src_1_cache);
3706  async_scale(beta, dst_desc, dst_cache);
3707
3708  auto primitive_args = create_primitive_args_or_get<::dnnl::binary>(
3709      onednn_algorithm, src_desc_0.get_desc(), src_desc_1.get_desc(),
3710      dst_desc.get_desc());
3711
3712  insert_arg(primitive_args.second.args, DNNL_ARG_SRC_0, src_desc_0.get_desc(),
3713             src_0_cache);
3714  insert_arg(primitive_args.second.args, DNNL_ARG_SRC_1, src_desc_1.get_desc(),
3715             src_1_cache);
3716  insert_arg(primitive_args.second.args, DNNL_ARG_DST, dst_desc.get_desc(),
3717             dst);
3718
3719  execute_primitive<::dnnl::binary>(primitive_args,
3720                                    {{1.f, 0.f, DNNL_ARG_DST, dst_desc, dst}});
3721  return exit_primitive(
3722      async_sum(1.f, dst_desc, dst_cache, 1.f, dst_desc, dst));
3723}
3724
3725inline
3726sycl::event engine_ext::async_reduction(reduction_op op, float alpha,
3727                                  const memory_desc_ext &src_desc, void *src,
3728                                  float beta, const memory_desc_ext &dst_desc,
3729                                  void *dst) {
3730  if (alpha == 0.f && beta == 1.f) {
3731    return sycl::event();
3732  }
3733  size_t src_cache_size = src_desc.get_size();
3734  size_t dst_cache_size = dst_desc.get_size();
3735  enter_primitive(3 * src_cache_size + 2 * dst_cache_size);
3736  float p = 2.f;
3737  ::dnnl::algorithm onednn_algorithm;
3738  void *cache = nullptr;
3739  switch (op) {
3740  case reduction_op::amax:
3741    cache = allocate(src_cache_size);
3742    activation_desc adesc;
3743    adesc.set_algorithm(::dnnl::algorithm::eltwise_abs);
3744    async_activation_forward(adesc, 1.f, src_desc, src, 0.f, src_desc, cache);
3745    onednn_algorithm = ::dnnl::algorithm::reduction_max;
3746    src = cache;
3747    break;
3748  case reduction_op::max:
3749    onednn_algorithm = ::dnnl::algorithm::reduction_max;
3750    break;
3751  case reduction_op::min:
3752    onednn_algorithm = ::dnnl::algorithm::reduction_min;
3753    break;
3754  case reduction_op::sum:
3755    onednn_algorithm = ::dnnl::algorithm::reduction_sum;
3756    break;
3757  case reduction_op::mean:
3758    onednn_algorithm = ::dnnl::algorithm::reduction_mean;
3759    break;
3760  case reduction_op::mul:
3761    onednn_algorithm = ::dnnl::algorithm::reduction_mul;
3762    break;
3763  case reduction_op::mul_no_zeros:
3764    cache = allocate(src_cache_size);
3765    transform_no_zero(src_desc, src, cache);
3766    onednn_algorithm = ::dnnl::algorithm::reduction_mul;
3767    src = cache;
3768    break;
3769  case reduction_op::norm1:
3770    p = 1.f;
3771    onednn_algorithm = ::dnnl::algorithm::reduction_norm_lp_power_p_sum;
3772    break;
3773  case reduction_op::norm2:
3774    onednn_algorithm = ::dnnl::algorithm::reduction_norm_lp_sum;
3775    break;
3776  }
3777  auto primitive_args = create_primitive_args_or_get<::dnnl::reduction>(
3778      onednn_algorithm, src_desc.get_desc(), dst_desc.get_desc(), p, 0.f);
3779
3780  insert_arg(primitive_args.second.args, DNNL_ARG_SRC, src_desc.get_desc(),
3781             src);
3782  insert_arg(primitive_args.second.args, DNNL_ARG_DST, dst_desc.get_desc(),
3783             dst);
3784
3785  return exit_primitive(execute_primitive<::dnnl::reduction>(
3786      primitive_args, {{alpha, beta, DNNL_ARG_DST, dst_desc, dst}}));
3787}
3788
3789inline
3790sycl::event engine_ext::async_activation_forward(activation_desc &desc, float alpha,
3791                                           const memory_desc_ext &src_desc,
3792                                           void *src, float beta,
3793                                           const memory_desc_ext &dst_desc,
3794                                           void *dst) {
3795  if (scale_parameter_preprocess({{alpha, beta, dst_desc, dst}})) {
3796    return sycl::event();
3797  }
3798  enter_primitive(2 * dst_desc.get_size());
3799  auto primitive_args = create_primitive_args_or_get<::dnnl::eltwise_forward>(
3800      ::dnnl::prop_kind::forward, desc.get_algorithm(), src_desc.get_desc(),
3801      dst_desc.get_desc(), desc.get_alpha(), desc.get_beta());
3802
3803  insert_arg(primitive_args.second.args, DNNL_ARG_SRC, src_desc.get_desc(),
3804             src);
3805  insert_arg(primitive_args.second.args, DNNL_ARG_DST, dst_desc.get_desc(),
3806             dst);
3807
3808  return exit_primitive(execute_primitive<::dnnl::eltwise_forward>(
3809      primitive_args, {{alpha, beta, DNNL_ARG_DST, dst_desc, dst}}));
3810}
3811
3812inline
3813sycl::event engine_ext::async_activation_backward(
3814    activation_desc &desc, float alpha, const memory_desc_ext &dst_desc,
3815    void *dst, const memory_desc_ext &diff_dst_desc, void *diff_dst,
3816    const memory_desc_ext &src_desc, void *src, float beta,
3817    const memory_desc_ext &diff_src_desc, void *diff_src) {
3818
3819  if (scale_parameter_preprocess({{alpha, beta, diff_src_desc, diff_src}})) {
3820    return sycl::event();
3821  }
3822  enter_primitive(2 * diff_src_desc.get_size());
3823  ::dnnl::memory::desc data_desc = dst_desc.get_desc();
3824  auto alg = desc.get_algorithm();
3825  if ((alg == ::dnnl::algorithm::eltwise_clip) ||
3826      (alg == ::dnnl::algorithm::eltwise_linear) ||
3827      (alg == ::dnnl::algorithm::eltwise_swish)) {
3828    data_desc = src_desc.get_desc();
3829  }
3830  auto primitive_args = create_primitive_args_or_get<::dnnl::eltwise_backward>(
3831      alg, diff_src_desc.get_desc(), diff_dst_desc.get_desc(), data_desc,
3832      desc.get_alpha(), desc.get_beta(),
3833      create_primitive_desc<::dnnl::eltwise_forward>(
3834          ::dnnl::prop_kind::forward, alg, src_desc.get_desc(),
3835          dst_desc.get_desc(), desc.get_alpha(), desc.get_beta()));
3836
3837  insert_arg(primitive_args.second.args, DNNL_ARG_DST, dst_desc.get_desc(),
3838             dst);
3839  insert_arg(primitive_args.second.args, DNNL_ARG_SRC, src_desc.get_desc(),
3840             src);
3841  insert_arg(primitive_args.second.args, DNNL_ARG_DIFF_DST,
3842             diff_dst_desc.get_desc(), diff_dst);
3843  insert_arg(primitive_args.second.args, DNNL_ARG_DIFF_SRC,
3844             diff_src_desc.get_desc(), diff_src);
3845
3846  return exit_primitive(execute_primitive<::dnnl::eltwise_backward>(
3847      primitive_args,
3848      {{alpha, beta, DNNL_ARG_DIFF_SRC, diff_src_desc, diff_src}}));
3849}
3850
3851inline
3852sycl::event engine_ext::async_pooling_forward(pooling_desc &desc, float alpha,
3853                                        const memory_desc_ext &src_desc,
3854                                        void *src, float beta,
3855                                        const memory_desc_ext &dst_desc,
3856                                        void *dst, ::dnnl::memory *workspace) {
3857  if (scale_parameter_preprocess({{alpha, beta, dst_desc, dst}})) {
3858    return sycl::event();
3859  }
3860  enter_primitive(2 * dst_desc.get_size());
3861  int pooling_dim = desc.get_stride().size();
3862  std::vector<int64_t> dilation(pooling_dim, 0);
3863  auto primitive_args =
3864      create_primitive_args_or_get<::dnnl::pooling_forward>(
3865          ::dnnl::prop_kind::forward_training, desc.get_algorithm(),
3866          src_desc.get_desc(), dst_desc.get_desc(), desc.get_stride(),
3867          desc.get_kernel(), dilation, desc.get_padding(), desc.get_padding());
3868  auto pd = get_primitive_desc<::dnnl::pooling_forward>(
3869      primitive_args.second.primitive);
3870  ::dnnl::memory ws_mem(pd.workspace_desc(), *_eng);
3871  if (workspace) {
3872    *workspace = ws_mem;
3873  } else {
3874    insert_workspace(src, ws_mem);
3875  }
3876  insert_arg(primitive_args.second.args, DNNL_ARG_SRC, src_desc.get_desc(),
3877             src);
3878  insert_arg(primitive_args.second.args, DNNL_ARG_WORKSPACE, ws_mem);
3879  insert_arg(primitive_args.second.args, DNNL_ARG_DST, dst_desc.get_desc(),
3880             dst);
3881
3882  return exit_primitive(execute_primitive<::dnnl::pooling_forward>(
3883      primitive_args, {{alpha, beta, DNNL_ARG_DST, dst_desc, dst}}));
3884}
3885
3886inline
3887sycl::event engine_ext::async_pooling_backward(
3888    pooling_desc &desc, float alpha, const memory_desc_ext &dst_desc, void *dst,
3889    const memory_desc_ext &diff_dst_desc, void *diff_dst,
3890    const memory_desc_ext &src_desc, void *src, float beta,
3891    const memory_desc_ext &diff_src_desc, void *diff_src,
3892    ::dnnl::memory *workspace) {
3893  if (scale_parameter_preprocess({{alpha, beta, diff_src_desc, diff_src}})) {
3894    return sycl::event();
3895  }
3896  enter_primitive(2 * diff_src_desc.get_size());
3897  int pooling_dim = desc.get_stride().size();
3898  std::vector<int64_t> dilation(pooling_dim, 0);
3899  auto primitive_args = create_primitive_args_or_get<::dnnl::pooling_backward>(
3900      desc.get_algorithm(), diff_src_desc.get_desc(), diff_dst_desc.get_desc(),
3901      desc.get_stride(), desc.get_kernel(), dilation, desc.get_padding(),
3902      desc.get_padding(),
3903      create_primitive_desc<::dnnl::pooling_forward>(
3904          ::dnnl::prop_kind::forward_training, desc.get_algorithm(),
3905          src_desc.get_desc(), dst_desc.get_desc(), desc.get_stride(),
3906          desc.get_kernel(), dilation, desc.get_padding(), desc.get_padding()));
3907
3908  insert_arg(primitive_args.second.args, DNNL_ARG_DST, dst_desc.get_desc(),
3909             dst);
3910  insert_arg(primitive_args.second.args, DNNL_ARG_SRC, src_desc.get_desc(),
3911             src);
3912  insert_arg(primitive_args.second.args, DNNL_ARG_DIFF_DST,
3913             diff_dst_desc.get_desc(), diff_dst);
3914  insert_arg(primitive_args.second.args, DNNL_ARG_DIFF_SRC,
3915             diff_src_desc.get_desc(), diff_src);
3916
3917  if (workspace) {
3918    insert_arg(primitive_args.second.args, DNNL_ARG_WORKSPACE, *workspace);
3919  } else {
3920    insert_arg(primitive_args.second.args, DNNL_ARG_WORKSPACE,
3921               get_workspace(src));
3922  }
3923
3924  return exit_primitive(execute_primitive<::dnnl::pooling_backward>(
3925      primitive_args,
3926      {{alpha, beta, DNNL_ARG_DIFF_SRC, diff_src_desc, diff_src}}));
3927}
3928
3929inline
3930sycl::event engine_ext::async_softmax_forward(softmax_algorithm alg,
3931                                        softmax_mode mode, float alpha,
3932                                        const memory_desc_ext &src_desc,
3933                                        void *src, float beta,
3934                                        const memory_desc_ext &dst_desc,
3935                                        void *dst) {
3936  if (scale_parameter_preprocess({{alpha, beta, dst_desc, dst}})) {
3937    return sycl::event();
3938  }
3939
3940  ::dnnl::memory::desc help_src_desc = src_desc.get_desc();
3941  ::dnnl::memory::desc help_dst_desc = dst_desc.get_desc();
3942  if (mode == softmax_mode::instance) {
3943    help_src_desc = compress_spatial_dimensions_to_channel(help_src_desc);
3944    help_dst_desc = compress_spatial_dimensions_to_channel(help_dst_desc);
3945  }
3946  enter_primitive(2 * help_dst_desc.get_size());
3947
3948  ::dnnl::algorithm softmax_alg = ::dnnl::algorithm::softmax_accurate;
3949  if (alg == softmax_algorithm::log) {
3950    softmax_alg = ::dnnl::algorithm::softmax_log;
3951  }
3952  auto primitive_args = create_primitive_args_or_get<::dnnl::softmax_forward>(
3953      ::dnnl::prop_kind::forward, softmax_alg, help_src_desc, 
3954      help_dst_desc, 1);
3955
3956  insert_arg(primitive_args.second.args, DNNL_ARG_DST, help_dst_desc, dst);
3957  insert_arg(primitive_args.second.args, DNNL_ARG_SRC, help_src_desc, src);
3958
3959  return exit_primitive(execute_primitive<::dnnl::softmax_forward>(
3960      primitive_args,
3961      {{alpha, beta, DNNL_ARG_DST, memory_desc_ext(help_dst_desc), dst}}));
3962}
3963
3964inline
3965sycl::event engine_ext::async_softmax_backward(
3966    softmax_algorithm alg, softmax_mode mode, float alpha,
3967    const memory_desc_ext &dst_desc, void *dst,
3968    const memory_desc_ext &diff_dst_desc, void *diff_dst, float beta,
3969    const memory_desc_ext &diff_src_desc, void *diff_src) {
3970  if (scale_parameter_preprocess({{alpha, beta, diff_src_desc, diff_src}})) {
3971    return sycl::event();
3972  }
3973  ::dnnl::memory::desc help_diff_src_desc = diff_src_desc.get_desc();
3974  ::dnnl::memory::desc help_dst_desc = dst_desc.get_desc();
3975  ::dnnl::memory::desc help_diff_dst_desc = diff_dst_desc.get_desc();
3976  if (mode == softmax_mode::instance) {
3977    help_diff_src_desc =
3978        compress_spatial_dimensions_to_channel(help_diff_src_desc);
3979    help_dst_desc = compress_spatial_dimensions_to_channel(help_dst_desc);
3980    help_diff_dst_desc =
3981        compress_spatial_dimensions_to_channel(help_diff_dst_desc);
3982  }
3983  enter_primitive(2 * help_diff_src_desc.get_size());
3984
3985  ::dnnl::algorithm softmax_alg = ::dnnl::algorithm::softmax_accurate;
3986  if (alg == softmax_algorithm::log) {
3987    softmax_alg = ::dnnl::algorithm::softmax_log;
3988  }
3989
3990  auto primitive_args = create_primitive_args_or_get<::dnnl::softmax_backward>(
3991      softmax_alg, help_diff_src_desc, help_diff_dst_desc, help_dst_desc, 1,
3992      create_primitive_desc<::dnnl::softmax_forward>(
3993          ::dnnl::prop_kind::forward, softmax_alg, help_diff_src_desc,
3994          help_dst_desc, 1));
3995  insert_arg(primitive_args.second.args, DNNL_ARG_DST, help_dst_desc, dst);
3996  insert_arg(primitive_args.second.args, DNNL_ARG_DIFF_DST, help_diff_dst_desc,
3997             diff_dst);
3998  insert_arg(primitive_args.second.args, DNNL_ARG_DIFF_SRC, help_diff_src_desc,
3999             diff_src);
4000
4001  return exit_primitive(execute_primitive<::dnnl::softmax_backward>(
4002      primitive_args, {{alpha, beta, DNNL_ARG_DIFF_SRC,
4003                        memory_desc_ext(help_diff_src_desc), diff_src}}));
4004}
4005
4006inline
4007sycl::event engine_ext::async_lrn_forward(lrn_desc &desc, float alpha,
4008                                    const memory_desc_ext &src_desc, void *src,
4009                                    float beta, const memory_desc_ext &dst_desc,
4010                                    void *dst, ::dnnl::memory *workspace) {
4011
4012  if (scale_parameter_preprocess({{alpha, beta, dst_desc, dst}})) {
4013    return sycl::event();
4014  }
4015  enter_primitive(2 * dst_desc.get_size());
4016  auto primitive_args = create_primitive_args_or_get<::dnnl::lrn_forward>(
4017      ::dnnl::prop_kind::forward_training,
4018      ::dnnl::algorithm::lrn_across_channels, src_desc.get_desc(),
4019      dst_desc.get_desc(), desc.get_local_size(), desc.get_alpha(),
4020      desc.get_beta(), desc.get_k());
4021  auto pd =
4022      get_primitive_desc<::dnnl::lrn_forward>(primitive_args.second.primitive);
4023  ::dnnl::memory ws_mem(pd.workspace_desc(), *_eng);
4024  if (workspace) {
4025    *workspace = ws_mem;
4026  } else {
4027    insert_workspace(src, ws_mem);
4028  }
4029
4030  insert_arg(primitive_args.second.args, DNNL_ARG_SRC, src_desc.get_desc(),
4031             src);
4032  insert_arg(primitive_args.second.args, DNNL_ARG_DST, dst_desc.get_desc(),
4033             dst);
4034  insert_arg(primitive_args.second.args, DNNL_ARG_WORKSPACE, ws_mem);
4035
4036  return exit_primitive(execute_primitive<::dnnl::lrn_forward>(
4037      primitive_args, {{alpha, beta, DNNL_ARG_DST, dst_desc, dst}}));
4038}
4039
4040inline
4041sycl::event
4042engine_ext::async_lrn_backward(lrn_desc &desc, float alpha,
4043                         const memory_desc_ext &dst_desc, void *dst,
4044                         const memory_desc_ext &diff_dst_desc, void *diff_dst,
4045                         const memory_desc_ext &src_desc, void *src, float beta,
4046                         const memory_desc_ext &diff_src_desc, void *diff_src,
4047                         ::dnnl::memory *workspace) {
4048
4049  if (scale_parameter_preprocess({{alpha, beta, diff_src_desc, diff_src}})) {
4050    return sycl::event();
4051  }
4052  enter_primitive(2 * diff_src_desc.get_size());
4053  auto primitive_args = create_primitive_args_or_get<::dnnl::lrn_backward>(
4054      ::dnnl::algorithm::lrn_across_channels, diff_src_desc.get_desc(),
4055      diff_dst_desc.get_desc(), src_desc.get_desc(), desc.get_local_size(),
4056      desc.get_alpha(), desc.get_beta(), desc.get_k(),
4057      create_primitive_desc<::dnnl::lrn_forward>(
4058          ::dnnl::prop_kind::forward_training,
4059          ::dnnl::algorithm::lrn_across_channels, src_desc.get_desc(),
4060          dst_desc.get_desc(), desc.get_local_size(), desc.get_alpha(),
4061          desc.get_beta(), desc.get_k()));
4062
4063  insert_arg(primitive_args.second.args, DNNL_ARG_SRC, src_desc.get_desc(),
4064             src);
4065  insert_arg(primitive_args.second.args, DNNL_ARG_DST, dst_desc.get_desc(),
4066             dst);
4067  insert_arg(primitive_args.second.args, DNNL_ARG_DIFF_DST,
4068             diff_dst_desc.get_desc(), diff_dst);
4069  insert_arg(primitive_args.second.args, DNNL_ARG_DIFF_SRC,
4070             diff_src_desc.get_desc(), diff_src);
4071
4072  if (workspace) {
4073    insert_arg(primitive_args.second.args, DNNL_ARG_WORKSPACE, *workspace);
4074  } else {
4075    insert_arg(primitive_args.second.args, DNNL_ARG_WORKSPACE,
4076               get_workspace(src));
4077  }
4078
4079  return exit_primitive(execute_primitive<::dnnl::lrn_backward>(
4080      primitive_args,
4081      {{alpha, beta, DNNL_ARG_DIFF_SRC, diff_src_desc, diff_src}}));
4082}
4083
4084inline
4085size_t engine_ext::get_batch_normalization_workspace_size(
4086    batch_normalization_ops ops, const memory_desc_ext &src_desc) {
4087  if(ops == batch_normalization_ops::none) {
4088    return 0;
4089  }
4090  return src_desc.get_size();
4091}
4092
4093inline
4094sycl::event engine_ext::async_batch_normalization_forward_inference(
4095    batch_normalization_mode mode, float epsilon, float alpha,
4096    const memory_desc_ext &src_desc, void *src, float beta,
4097    const memory_desc_ext &dst_desc, void *dst,
4098    const memory_desc_ext &scale_bias_mean_var_desc, void *scale, void *bias,
4099    void *mean, void *var) {
4100
4101  return batch_normalization_forward_internal(
4102      true, mode, epsilon, 0.f, alpha, src_desc, src, beta, dst_desc, dst,
4103      scale_bias_mean_var_desc, scale, bias, scale_bias_mean_var_desc, mean,
4104      var, nullptr, nullptr);
4105}
4106
4107inline
4108sycl::event engine_ext::async_batch_normalization_forward_inference(
4109    batch_normalization_mode mode, batch_normalization_ops ops,
4110    activation_desc &adesc, float epsilon, float alpha,
4111    const memory_desc_ext &src_desc, void *src, float beta,
4112    const memory_desc_ext &dst_desc, void *dst,
4113    const memory_desc_ext &summand_desc, void *summand,
4114    const memory_desc_ext &scale_bias_desc, void *scale, void *bias,
4115    const memory_desc_ext &mean_var_desc, void *mean, void *var) {
4116
4117  bool has_post_op = (ops != batch_normalization_ops::none);
4118  sycl::event e;
4119  enter_primitive(src_desc.get_size() + dst_desc.get_size() * 4 +
4120                  scale_bias_desc.get_size() * 2 +
4121                  mean_var_desc.get_size() * 5);
4122  if (has_post_op) {
4123    void *dst_cache = allocate(dst_desc);
4124    batch_normalization_forward_internal(
4125        true, mode, epsilon, 0.f, 1.f, src_desc, src, 0.f, dst_desc, dst_cache,
4126        scale_bias_desc, scale, bias, mean_var_desc, mean, var, nullptr,
4127        nullptr);
4128
4129    if (ops == batch_normalization_ops::add_activation) {
4130      async_sum(1.f, summand_desc, summand, 1.f, dst_desc, dst_cache);
4131    }
4132    async_activation_forward(adesc, 1.f, dst_desc, dst_cache, 0.f, dst_desc,
4133                       dst_cache);
4134    return exit_primitive(
4135        async_sum(alpha, dst_desc, dst_cache, beta, dst_desc, dst));
4136  }
4137  return exit_primitive(batch_normalization_forward_internal(
4138      true, mode, epsilon, 0.f, alpha, src_desc, src, beta, dst_desc, dst,
4139      scale_bias_desc, scale, bias, mean_var_desc, mean, var, nullptr,
4140      nullptr));
4141}
4142
4143inline
4144sycl::event engine_ext::async_batch_normalization_forward_training(
4145    batch_normalization_mode mode, float epsilon, float factor, float alpha,
4146    const memory_desc_ext &src_desc, void *src, float beta,
4147    const memory_desc_ext &dst_desc, void *dst,
4148    const memory_desc_ext &scale_bias_mean_var_desc, void *scale, void *bias,
4149    void *running_mean, void *running_var, void *saved_mean, void *saved_var) {
4150  return batch_normalization_forward_internal(
4151      false, mode, epsilon, factor, alpha, src_desc, src, beta, dst_desc, dst,
4152      scale_bias_mean_var_desc, scale, bias, scale_bias_mean_var_desc,
4153      saved_mean, saved_var, running_mean, running_var);
4154}
4155
4156inline
4157sycl::event engine_ext::async_batch_normalization_forward_training(
4158    batch_normalization_mode mode, batch_normalization_ops ops,
4159    activation_desc &adesc, float epsilon, float factor, float alpha,
4160    const memory_desc_ext &src_desc, void *src, float beta,
4161    const memory_desc_ext &dst_desc, void *dst,
4162    const memory_desc_ext &summand_desc, void *summand,
4163    const memory_desc_ext &scale_bias_desc, void *scale, void *bias,
4164    const memory_desc_ext &mean_var_desc, void *running_mean, void *running_var,
4165    void *saved_mean, void *saved_var, size_t workspace_size,
4166    void *workspace) {
4167  enter_primitive(src_desc.get_size() + dst_desc.get_size() * 3 +
4168                  mean_var_desc.get_size() * 5 +
4169                  scale_bias_desc.get_size() * 2);
4170  bool has_post_op = (ops != batch_normalization_ops::none);
4171  sycl::event e;
4172  if (has_post_op) {
4173    if(workspace_size < dst_desc.get_desc().get_size()) {
4174      throw std::runtime_error("async_batch_normalization_forward_training_ex: "
4175        "no sufficient workspace.");
4176    }
4177    batch_normalization_forward_internal(
4178        false, mode, epsilon, factor, 1.f, src_desc, src, 0.f, dst_desc,
4179        workspace, scale_bias_desc, scale, bias, mean_var_desc,
4180        saved_mean, saved_var, running_mean, running_var);
4181    if (ops == batch_normalization_ops::add_activation) {
4182      async_sum(1.f, summand_desc, summand, 1.f, dst_desc,
4183          workspace);
4184    }
4185    return exit_primitive(async_activation_forward(
4186        adesc, alpha, dst_desc, workspace, beta, dst_desc, dst));
4187  }
4188  return exit_primitive(batch_normalization_forward_internal(
4189      false, mode, epsilon, factor, alpha, src_desc, src, beta, dst_desc, dst,
4190      scale_bias_desc, scale, bias, mean_var_desc, saved_mean, saved_var,
4191      running_mean, running_var));
4192}
4193
4194inline
4195sycl::event engine_ext::async_batch_normalization_forward_training(
4196    batch_normalization_mode mode, batch_normalization_ops ops,
4197    activation_desc &adesc, float epsilon, float factor, float alpha,
4198    const memory_desc_ext &src_desc, void *src, float beta,
4199    const memory_desc_ext &dst_desc, void *dst,
4200    const memory_desc_ext &summand_desc, void *summand,
4201    const memory_desc_ext &scale_bias_mean_var_desc, void *scale, void *bias,
4202    void *running_mean, void *running_var, void *saved_mean, void *saved_var,
4203    size_t workspace_size, void *workspace) {
4204  return async_batch_normalization_forward_training(
4205      mode, ops, adesc, epsilon, factor, alpha, src_desc, src, beta, dst_desc,
4206      dst, summand_desc, summand, scale_bias_mean_var_desc, scale, bias,
4207      scale_bias_mean_var_desc, running_mean, running_var, saved_mean,
4208      saved_var, workspace_size, workspace);
4209}
4210
4211inline
4212sycl::event engine_ext::async_batch_normalization_backward(
4213    batch_normalization_mode mode, float epsilon, float alpha_data,
4214    const memory_desc_ext &src_desc, void *src,
4215    const memory_desc_ext &diff_dst_desc, void *diff_dst, float beta_data,
4216    const memory_desc_ext &diff_src_desc, void *diff_src, float alpha_param,
4217    const memory_desc_ext &diff_scale_bias_mean_var_desc, void *scale,
4218    float beta_param, void *diff_scale, void *diff_bias, void *saved_mean,
4219    void *saved_var) {
4220
4221  return batch_normalization_backward_internal(
4222      mode, epsilon, alpha_data, src_desc, src, diff_dst_desc, diff_dst,
4223      beta_data, diff_src_desc, diff_src, alpha_param,
4224      diff_scale_bias_mean_var_desc, scale, nullptr, beta_param, diff_scale,
4225      diff_bias, diff_scale_bias_mean_var_desc, saved_mean, saved_var);
4226}
4227
4228inline
4229sycl::event engine_ext::async_batch_normalization_backward(
4230    batch_normalization_mode mode, batch_normalization_ops ops,
4231    activation_desc &adesc, float epsilon, float alpha_data,
4232    const memory_desc_ext &src_desc, void *src, const memory_desc_ext &dst_desc,
4233    void *dst, const memory_desc_ext &diff_dst_desc, void *diff_dst,
4234    float beta_data, const memory_desc_ext &diff_src_desc, void *diff_src,
4235    const memory_desc_ext &diff_summand_desc, void *diff_summand,
4236    float alpha_param, const memory_desc_ext &diff_scale_bias_desc, void *scale,
4237    void *bias, float beta_param, void *diff_scale, void *diff_bias,
4238    const memory_desc_ext &mean_var_desc, void *saved_mean, void *saved_var,
4239    size_t workspace_size, void *workspace) {
4240  std::vector<void *> caches;
4241  ::dnnl::memory::desc real_diff_dst_desc = diff_dst_desc.get_desc();
4242  void *real_diff_dst = diff_dst;
4243
4244  if (ops != batch_normalization_ops::none &&
4245      workspace_size < dst_desc.get_desc().get_size()) {
4246    throw std::runtime_error("async_batch_normalization_backward_ex: "
4247                             "no sufficient workspace.");
4248  }
4249  enter_primitive(diff_scale_bias_desc.get_size() * 8 +
4250                  src_desc.get_size() * 3 + diff_dst_desc.get_size() * 5 +
4251                  diff_src_desc.get_size() + mean_var_desc.get_size() * 9 +
4252                  diff_summand_desc.get_size());
4253  if (ops == batch_normalization_ops::add_activation) {
4254    void *diff_summand_cache = allocate(diff_summand_desc);
4255    async_activation_backward(adesc, 1.f, dst_desc, dst, diff_dst_desc, diff_dst,
4256                        dst_desc, workspace, 0.f,
4257                        diff_summand_desc, diff_summand_cache);
4258    async_sum(alpha_data, diff_summand_desc, diff_summand_cache, beta_data,
4259        diff_summand_desc, diff_summand);
4260    real_diff_dst_desc = diff_summand_desc.get_desc();
4261    real_diff_dst = diff_summand_cache;
4262  } else if (ops == batch_normalization_ops::activation) {
4263    void *diff_dst_cache = allocate(diff_dst_desc);
4264    async_activation_backward(adesc, 1.f, dst_desc, dst, diff_dst_desc,
4265                        diff_dst, dst_desc, workspace,
4266                        0.f, diff_dst_desc, diff_dst_cache);
4267    real_diff_dst = diff_dst_cache;
4268  }
4269
4270  return exit_primitive(batch_normalization_backward_internal(
4271      mode, epsilon, alpha_data, src_desc, src, real_diff_dst_desc,
4272      real_diff_dst, beta_data, diff_src_desc, diff_src, alpha_param,
4273      diff_scale_bias_desc, scale, bias, beta_param, diff_scale, diff_bias,
4274      mean_var_desc, saved_mean, saved_var));
4275}
4276
4277inline
4278sycl::event engine_ext::async_batch_normalization_backward(
4279    batch_normalization_mode mode, batch_normalization_ops ops,
4280    activation_desc &adesc, float epsilon, float alpha_data,
4281    const memory_desc_ext &src_desc, void *src, const memory_desc_ext &dst_desc,
4282    void *dst, const memory_desc_ext &diff_dst_desc, void *diff_dst,
4283    float beta_data, const memory_desc_ext &diff_src_desc, void *diff_src,
4284    const memory_desc_ext &diff_summand_desc, void *diff_summand,
4285    float alpha_param, const memory_desc_ext &diff_scale_bias_mean_var_desc,
4286    void *scale, void *bias, float beta_param, void *diff_scale,
4287    void *diff_bias, void *saved_mean, void *saved_var,
4288    size_t workspace_size, void *workspace) {
4289
4290  return async_batch_normalization_backward(
4291      mode, ops, adesc, epsilon, alpha_data, src_desc, src, dst_desc, dst,
4292      diff_dst_desc, diff_dst, beta_data, diff_src_desc, diff_src,
4293      diff_summand_desc, diff_summand, alpha_param,
4294      diff_scale_bias_mean_var_desc, scale, bias, beta_param, diff_scale,
4295      diff_bias, diff_scale_bias_mean_var_desc, saved_mean, saved_var,
4296      workspace_size, workspace);
4297}
4298
4299inline
4300sycl::event
4301engine_ext::async_convolution_forward(convolution_desc &desc, ::dnnl::algorithm alg,
4302                                float alpha, const memory_desc_ext &src_desc,
4303                                void *src, const memory_desc_ext &weight_desc,
4304                                void *weight, float beta,
4305                                const memory_desc_ext &dst_desc, void *dst) {
4306  if (scale_parameter_preprocess({{alpha, beta, dst_desc, dst}})) {
4307    return sycl::event();
4308  }
4309  auto help_weight_desc =
4310      get_group_weight_desc(desc.get_group_count(), weight_desc);
4311
4312  ::dnnl::primitive_attr attr;
4313  attr.set_fpmath_mode(desc.get_math_mode());
4314
4315  auto origin_src_md = src_desc.get_desc();
4316  auto origin_dst_md = dst_desc.get_desc();
4317  auto origin_weight_md = help_weight_desc;
4318  auto src_md = transfer_memory_desc_to_format_tag_any(origin_src_md);
4319  auto dst_md = transfer_memory_desc_to_format_tag_any(origin_dst_md);
4320  auto weight_md = transfer_memory_desc_to_format_tag_any(origin_weight_md);
4321
4322  auto primitive_args =
4323      create_primitive_args_or_get<::dnnl::convolution_forward>(
4324          ::dnnl::prop_kind::forward_training, alg, src_md, weight_md, dst_md,
4325          desc.get_stride(), desc.get_dilate(), desc.get_padding(),
4326          desc.get_padding(), attr);
4327
4328  auto pd = get_primitive_desc<::dnnl::convolution_forward>(
4329      primitive_args.second.primitive);
4330  auto optimal_src_md = pd.src_desc();
4331  auto optimal_dst_md = pd.dst_desc();
4332  auto optimal_weight_md = pd.weights_desc();
4333
4334  enter_primitive(
4335      optimal_src_md.get_size() * 3 + optimal_dst_md.get_size() * 5 +
4336      optimal_weight_md.get_size() * 3 + origin_dst_md.get_size() * 2);
4337
4338  void *optimal_src = src, *optimal_dst = dst, *optimal_weight = weight;
4339  allocate_and_reorder_memory_to_optimal(origin_src_md, src, optimal_src_md,
4340                                         optimal_src);
4341  allocate_and_reorder_memory_to_optimal(origin_weight_md, weight,
4342                                         optimal_weight_md, optimal_weight);
4343
4344  if (beta == 0.f) {
4345    if(origin_dst_md != optimal_dst_md) {
4346      optimal_dst = allocate(optimal_dst_md);
4347    }
4348  } else {
4349    allocate_and_reorder_memory_to_optimal(origin_dst_md, dst, optimal_dst_md,
4350                                           optimal_dst);
4351  }
4352
4353  insert_arg(primitive_args.second.args, DNNL_ARG_SRC, optimal_src_md,
4354             optimal_src);
4355  insert_arg(primitive_args.second.args, DNNL_ARG_WEIGHTS, optimal_weight_md,
4356             optimal_weight);
4357  insert_arg(primitive_args.second.args, DNNL_ARG_DST, optimal_dst_md,
4358             optimal_dst);
4359
4360  auto e = execute_primitive<::dnnl::convolution_forward>(
4361      primitive_args,
4362      {{alpha, beta, DNNL_ARG_DST, optimal_dst_md, optimal_dst}});
4363
4364  if (origin_dst_md != optimal_dst_md) {
4365    e = async_reorder(1.f, optimal_dst_md, optimal_dst, 0.f, origin_dst_md,
4366                      dst);
4367  }
4368  return exit_primitive(e);
4369}
4370
4371inline
4372sycl::event engine_ext::async_convolution_forward(
4373    convolution_desc &desc, ::dnnl::algorithm alg, activation_desc &adesc,
4374    float alpha_0, const memory_desc_ext &src_desc, void *src,
4375    const memory_desc_ext &weight_desc, void *weight, float alpha_1,
4376    const memory_desc_ext &summand_desc, void *summand,
4377    const memory_desc_ext &bias_desc, void *bias,
4378    const memory_desc_ext &dst_desc, void *dst) {
4379
4380  int channel_num = bias_desc.get_element_num();
4381  auto help_weight_desc =
4382      get_group_weight_desc(desc.get_group_count(), weight_desc);
4383  ::dnnl::memory::desc help_bias_desc = {{channel_num},
4384                                         bias_desc.get_desc().get_data_type(),
4385                                         ::dnnl::memory::format_tag::a};
4386  auto origin_weight_md = help_weight_desc;
4387  auto origin_bias_md = help_bias_desc;
4388  auto origin_src_md = src_desc.get_desc();
4389  auto origin_dst_md = dst_desc.get_desc();
4390  auto src_md = transfer_memory_desc_to_format_tag_any(origin_src_md);
4391  auto dst_md = transfer_memory_desc_to_format_tag_any(origin_dst_md);
4392  auto weight_md = transfer_memory_desc_to_format_tag_any(origin_weight_md);
4393  auto bias_md = transfer_memory_desc_to_format_tag_any(origin_bias_md);
4394
4395  ::dnnl::primitive_attr attr;
4396  attr.set_fpmath_mode(desc.get_math_mode());
4397
4398  auto primitive_args =
4399      create_primitive_args_or_get<::dnnl::convolution_forward>(
4400          ::dnnl::prop_kind::forward_training, alg, src_md, weight_md, bias_md,
4401          dst_md, desc.get_stride(), desc.get_dilate(), desc.get_padding(),
4402          desc.get_padding(), attr);
4403
4404  auto pd = get_primitive_desc<::dnnl::convolution_forward>(
4405      primitive_args.second.primitive);
4406  auto optimal_src_md = pd.src_desc();
4407  auto optimal_dst_md = pd.dst_desc();
4408  auto optimal_weight_md = pd.weights_desc();
4409  auto optimal_bias_md = pd.bias_desc();
4410
4411  enter_primitive(optimal_src_md.get_size() + 3 * optimal_weight_md.get_size() +
4412                  optimal_bias_md.get_size() + 7 * optimal_dst_md.get_size() +
4413                  summand_desc.get_size());
4414
4415  void *optimal_src = src, *optimal_dst = dst, *optimal_weight = weight,
4416       *optimal_bias = bias;
4417  allocate_and_reorder_memory_to_optimal(origin_src_md, src, optimal_src_md,
4418                                         optimal_src);
4419  allocate_and_reorder_memory_to_optimal(origin_weight_md, weight,
4420                                         optimal_weight_md, optimal_weight);
4421  allocate_and_reorder_memory_to_optimal(origin_bias_md, bias, optimal_bias_md,
4422                                         optimal_bias);
4423  if (origin_dst_md != optimal_dst_md) {
4424    optimal_dst = allocate(optimal_dst_md);
4425  }
4426
4427  insert_arg(primitive_args.second.args, DNNL_ARG_SRC, optimal_src_md,
4428             optimal_src);
4429  insert_arg(primitive_args.second.args, DNNL_ARG_BIAS, optimal_bias_md,
4430             optimal_bias);
4431  insert_arg(primitive_args.second.args, DNNL_ARG_DST, optimal_dst_md,
4432             optimal_dst);
4433
4434  void *cache = nullptr;
4435  if (alpha_0 != 1.f) {
4436    cache = allocate(optimal_weight_md);
4437    _q->memcpy(cache, optimal_weight, optimal_weight_md.get_size());
4438    async_scale(alpha_0, optimal_weight_md, cache);
4439    insert_arg(primitive_args.second.args, DNNL_ARG_WEIGHTS, optimal_weight_md,
4440               cache);
4441    execute_primitive<::dnnl::convolution_forward>(
4442        primitive_args,
4443        {{1.f, 0.f, DNNL_ARG_DST, optimal_dst_md, optimal_dst}});
4444  } else {
4445    insert_arg(primitive_args.second.args, DNNL_ARG_WEIGHTS, optimal_weight_md,
4446               optimal_weight);
4447    execute_primitive<::dnnl::convolution_forward>(
4448        primitive_args,
4449        {{1.f, 0.f, DNNL_ARG_DST, optimal_dst_md, optimal_dst}});
4450  }
4451  if (origin_dst_md != optimal_dst_md) {
4452    async_reorder(1.f, optimal_dst_md, optimal_dst, 0.f, origin_dst_md, dst);
4453  }
4454  async_sum(alpha_1, summand_desc, summand, 1.f, dst_desc, dst);
4455  return exit_primitive(
4456      async_activation_forward(adesc, 1.f, dst_desc, dst, 0.f, dst_desc, dst));
4457}
4458
4459inline
4460sycl::event engine_ext::async_convolution_backward_data(
4461    convolution_desc &desc, ::dnnl::algorithm alg, float alpha,
4462    const memory_desc_ext &weight_desc, void *weight,
4463    const memory_desc_ext &diff_dst_desc, void *diff_dst, float beta,
4464    const memory_desc_ext &diff_src_desc, void *diff_src) {
4465
4466  if (scale_parameter_preprocess({{alpha, beta, diff_dst_desc, diff_dst}})) {
4467    return sycl::event();
4468  }
4469
4470  auto help_weight_desc =
4471      get_group_weight_desc(desc.get_group_count(), weight_desc);
4472
4473  auto origin_weight_md = help_weight_desc;
4474  auto origin_diff_src_md = diff_src_desc.get_desc();
4475  auto origin_diff_dst_md = diff_dst_desc.get_desc();
4476  auto diff_src_md = transfer_memory_desc_to_format_tag_any(origin_diff_src_md);
4477  auto diff_dst_md = transfer_memory_desc_to_format_tag_any(origin_diff_dst_md);
4478  auto weight_md = transfer_memory_desc_to_format_tag_any(origin_weight_md);
4479
4480  ::dnnl::primitive_attr attr;
4481  attr.set_fpmath_mode(desc.get_math_mode());
4482
4483  auto forward_primitive = create_primitive_desc<::dnnl::convolution_forward>(
4484      ::dnnl::prop_kind::forward_training, ::dnnl::algorithm::convolution_auto,
4485      diff_src_md, weight_md, diff_dst_md, desc.get_stride(), desc.get_dilate(),
4486      desc.get_padding(), desc.get_padding(), attr);
4487
4488  auto primitive_args =
4489      create_primitive_args_or_get<::dnnl::convolution_backward_data>(
4490          ::dnnl::algorithm::convolution_auto, diff_src_md, weight_md,
4491          diff_dst_md, desc.get_stride(), desc.get_dilate(), desc.get_padding(),
4492          desc.get_padding(), forward_primitive, attr);
4493
4494  auto pd = get_primitive_desc<::dnnl::convolution_backward_data>(
4495      primitive_args.second.primitive);
4496  auto optimal_diff_src_md = pd.diff_src_desc();
4497  auto optimal_diff_dst_md = pd.diff_dst_desc();
4498  auto optimal_weight_md = pd.weights_desc();
4499
4500  enter_primitive(5 * optimal_diff_src_md.get_size() +
4501                  optimal_diff_dst_md.get_size() +
4502                  optimal_weight_md.get_size());
4503
4504  void *optimal_diff_src = diff_src, *optimal_diff_dst = diff_dst,
4505       *optimal_weight = weight;
4506  allocate_and_reorder_memory_to_optimal(origin_diff_dst_md, diff_dst,
4507                                         optimal_diff_dst_md, optimal_diff_dst);
4508  allocate_and_reorder_memory_to_optimal(origin_weight_md, weight,
4509                                         optimal_weight_md, optimal_weight);
4510  if (beta == 0.f) {
4511    if (origin_diff_src_md != optimal_diff_src_md) {
4512      optimal_diff_src = allocate(optimal_diff_src_md);
4513    }
4514  } else {
4515    allocate_and_reorder_memory_to_optimal(
4516        origin_diff_src_md, diff_src, optimal_diff_src_md, optimal_diff_src);
4517  }
4518
4519  insert_arg(primitive_args.second.args, DNNL_ARG_DIFF_DST, optimal_diff_dst_md,
4520             optimal_diff_dst);
4521  insert_arg(primitive_args.second.args, DNNL_ARG_WEIGHTS, optimal_weight_md,
4522             optimal_weight);
4523  insert_arg(primitive_args.second.args, DNNL_ARG_DIFF_SRC, optimal_diff_src_md,
4524             optimal_diff_src);
4525
4526  auto e = execute_primitive<::dnnl::convolution_backward_data>(
4527      primitive_args,
4528      {{alpha, beta, DNNL_ARG_DIFF_SRC, optimal_diff_src_md, optimal_diff_src}});
4529
4530  if (origin_diff_src_md != optimal_diff_src_md) {
4531    e = async_reorder(1.f, optimal_diff_src_md, optimal_diff_src, 0.f,
4532                      origin_diff_src_md, diff_src);
4533  }
4534  return exit_primitive(e);
4535}
4536
4537inline
4538sycl::event engine_ext::async_convolution_backward_weight(
4539    convolution_desc &desc, ::dnnl::algorithm alg, float alpha,
4540    const memory_desc_ext &src_desc, void *src,
4541    const memory_desc_ext &diff_dst_desc, void *diff_dst, float beta,
4542    const memory_desc_ext &diff_weight_desc, void *diff_weight) {
4543
4544  if (scale_parameter_preprocess(
4545          {{alpha, beta, diff_weight_desc, diff_weight}})) {
4546    return sycl::event();
4547  }
4548
4549  auto help_diff_weight_desc =
4550      get_group_weight_desc(desc.get_group_count(), diff_weight_desc);
4551
4552  ::dnnl::primitive_attr attr;
4553  attr.set_fpmath_mode(desc.get_math_mode());
4554
4555  auto origin_diff_weight_md = help_diff_weight_desc;
4556  auto origin_src_md = src_desc.get_desc();
4557  auto origin_diff_dst_md = diff_dst_desc.get_desc();
4558  auto src_md = transfer_memory_desc_to_format_tag_any(origin_src_md);
4559  auto diff_dst_md = transfer_memory_desc_to_format_tag_any(origin_diff_dst_md);
4560  auto diff_weight_md =
4561      transfer_memory_desc_to_format_tag_any(origin_diff_weight_md);
4562
4563  auto forward_primitive = create_primitive_desc<::dnnl::convolution_forward>(
4564      ::dnnl::prop_kind::forward_training, ::dnnl::algorithm::convolution_auto,
4565      src_md, diff_weight_md, diff_dst_md, desc.get_stride(), desc.get_dilate(),
4566      desc.get_padding(), desc.get_padding(), attr);
4567
4568  auto primitive_args =
4569      create_primitive_args_or_get<::dnnl::convolution_backward_weights>(
4570          ::dnnl::algorithm::convolution_auto, src_md, diff_weight_md,
4571          diff_dst_md, desc.get_stride(), desc.get_dilate(), desc.get_padding(),
4572          desc.get_padding(), forward_primitive, attr);
4573
4574  auto pd = get_primitive_desc<::dnnl::convolution_backward_weights>(
4575      primitive_args.second.primitive);
4576  auto optimal_src_md = pd.src_desc();
4577  auto optimal_diff_dst_md = pd.diff_dst_desc();
4578  auto optimal_diff_weight_md = pd.diff_weights_desc();
4579
4580  enter_primitive(optimal_diff_weight_md.get_size() * 5 +
4581                  optimal_diff_dst_md.get_size() + optimal_src_md.get_size());
4582
4583  void *optimal_src = src, *optimal_diff_dst = diff_dst,
4584       *optimal_diff_weight = diff_weight;
4585  allocate_and_reorder_memory_to_optimal(origin_diff_dst_md, diff_dst,
4586                                         optimal_diff_dst_md, optimal_diff_dst);
4587  allocate_and_reorder_memory_to_optimal(origin_src_md, src, optimal_src_md,
4588                                         optimal_src);
4589  if (beta == 0.f) {
4590    if (origin_diff_weight_md != optimal_diff_weight_md) {
4591      optimal_diff_weight = allocate(optimal_diff_weight_md);
4592    }
4593  } else {
4594    allocate_and_reorder_memory_to_optimal(origin_diff_weight_md, diff_weight,
4595                                           optimal_diff_weight_md,
4596                                           optimal_diff_weight);
4597  }
4598
4599  insert_arg(primitive_args.second.args, DNNL_ARG_SRC, optimal_src_md,
4600             optimal_src);
4601  insert_arg(primitive_args.second.args, DNNL_ARG_DIFF_DST, optimal_diff_dst_md,
4602             optimal_diff_dst);
4603  insert_arg(primitive_args.second.args, DNNL_ARG_DIFF_WEIGHTS,
4604             optimal_diff_weight_md, optimal_diff_weight);
4605
4606  auto e = execute_primitive<::dnnl::convolution_backward_weights>(
4607      primitive_args, {{alpha, beta, DNNL_ARG_DIFF_WEIGHTS,
4608                        optimal_diff_weight_md, optimal_diff_weight}});
4609
4610  if (origin_diff_weight_md != optimal_diff_weight_md) {
4611    e = async_reorder(1.f, optimal_diff_weight_md, optimal_diff_weight, 0.f,
4612                      origin_diff_weight_md, diff_weight);
4613  }
4614  return exit_primitive(e);
4615}
4616
4617inline
4618sycl::event engine_ext::async_convolution_backward_bias(
4619    float alpha, const memory_desc_ext &diff_dst_desc, void *diff_dst,
4620    float beta, const memory_desc_ext &diff_bias_desc, void *diff_bias) {
4621  return async_reduction(reduction_op::sum, alpha, diff_dst_desc, diff_dst, beta,
4622                   diff_bias_desc, diff_bias);
4623}
4624
4625inline
4626void engine_ext::rnn_get_weight_space_size(const rnn_desc &desc,
4627                                           size_t *weight_space_size) {
4628  *weight_space_size = 0;
4629  rnn_forward_internal(desc, ::dnnl::prop_kind::forward_inference,
4630                       memory_desc_ext(), nullptr, memory_desc_ext(), nullptr,
4631                       memory_desc_ext(), nullptr, nullptr, memory_desc_ext(),
4632                       nullptr, nullptr, 0, nullptr, 0, nullptr, 0, nullptr, true,
4633                       weight_space_size, nullptr, nullptr);
4634  return;
4635}
4636
4637inline
4638void engine_ext::rnn_get_scratchpad_workspace_size(
4639    const rnn_desc &desc, ::dnnl::prop_kind kind,
4640    const memory_desc_ext &src_desc, size_t *scratchpad_size,
4641    size_t *workspace_size) {
4642  *workspace_size = 0;
4643  *scratchpad_size = 0;
4644  rnn_forward_internal(desc, kind, src_desc, nullptr, memory_desc_ext(),
4645                       nullptr, memory_desc_ext(), nullptr, nullptr,
4646                       memory_desc_ext(), nullptr, nullptr, 0, nullptr, 0,
4647                       nullptr, 0, nullptr, true, nullptr, workspace_size,
4648                       scratchpad_size);
4649  return;
4650}
4651
4652inline
4653sycl::event engine_ext::async_rnn_forward(
4654    const rnn_desc &desc, ::dnnl::prop_kind kind,
4655    const memory_desc_ext &src_desc, void *src, const memory_desc_ext &dst_desc,
4656    void *dst, const memory_desc_ext &iter_desc, void *src_iter, void *dst_iter,
4657    const memory_desc_ext &iter_c_desc, void *src_iter_c, void *dst_iter_c,
4658    size_t weight_size, void *weight, size_t scratchpad_size, void *scratchpad,
4659    size_t workspace_size, void *workspace) {
4660
4661  return rnn_forward_internal(
4662      desc, kind, src_desc, src, dst_desc, dst, iter_desc, src_iter, dst_iter,
4663      iter_c_desc, src_iter_c, dst_iter_c, weight_size, weight, workspace_size,
4664      workspace, scratchpad_size, scratchpad, false, nullptr, nullptr,
4665      nullptr);
4666}
4667
4668inline
4669sycl::event engine_ext::async_rnn_backward(
4670    const rnn_desc &desc, const memory_desc_ext &dst_desc, void *dst,
4671    void *diff_dst, const memory_desc_ext &src_desc, void *src, void *diff_src,
4672    const memory_desc_ext &iter_desc, void *src_iter, void *diff_dst_iter,
4673    void *diff_src_iter, const memory_desc_ext &iter_c_desc, void *src_iter_c,
4674    void *diff_dst_iter_c, void *diff_src_iter_c, size_t weight_size,
4675    void *weight, void *diff_weight, size_t scratchpad_size, void *scratchpad,
4676    size_t workspace_size, void *workspace) {
4677  ::dnnl::memory::data_type src_dt;
4678  ::dnnl::memory::format_tag src_format_tag;
4679  rnn_mode mode;
4680  rnn_memory_format_tag format_tag;
4681  rnn_bias_mode bias_mode;
4682  rnn_direction direction;
4683  dpct::library_data_t dt;
4684  int direction_num = 1, input_size = 0, hidden_size = 0, projection_size = 0,
4685      layer_size = 0, gate_num = 1, output_size = 0, data_type_size = 0,
4686      seq_length = 1, batch_size = 1;
4687  void *last_layer_cache = nullptr;
4688  void *hidden_layer_cache = nullptr;
4689  sycl::event e;
4690  enter_primitive(src_desc.get_size() * 2);
4691  std::vector<int> offset(9, 0);
4692  std::vector<void *> data = {
4693      src,
4694      dst,
4695      (uint8_t *)src_iter + iter_desc.get_size(),
4696      nullptr,
4697      (uint8_t *)src_iter_c + iter_c_desc.get_size(),
4698      nullptr,
4699      (uint8_t *)weight + weight_size,
4700      (uint8_t *)workspace + workspace_size,
4701      diff_src,
4702      diff_dst,
4703      (uint8_t *)diff_src_iter + iter_desc.get_size(),
4704      (uint8_t *)diff_dst_iter + iter_desc.get_size(),
4705      (uint8_t *)diff_src_iter_c + iter_c_desc.get_size(),
4706      (uint8_t *)diff_dst_iter_c + iter_c_desc.get_size(),
4707      (uint8_t *)diff_weight + weight_size,
4708      scratchpad};
4709
4710  desc.get(&mode, &bias_mode, &direction, &dt, &input_size, &hidden_size,
4711           &projection_size, &layer_size);
4712
4713  get_rnn_configuration(src_desc.get_desc(), direction, mode, dt, hidden_size,
4714                        &src_dt, &src_format_tag, &projection_size,
4715                        &output_size, &seq_length, &batch_size, &direction_num,
4716                        &gate_num);
4717
4718  if (direction == rnn_direction::bidirectional) {
4719    if (layer_size > 1) {
4720      last_layer_cache = allocate(src_desc);
4721      hidden_layer_cache = allocate(src_desc);
4722      data[8] = last_layer_cache;
4723    }
4724    e = execute_rnn_backward_primitive(
4725        mode, ::dnnl::rnn_direction::bidirectional_concat, bias_mode, src_dt,
4726        src_format_tag, seq_length, batch_size, output_size, 2 * output_size, 1,
4727        direction_num, hidden_size, gate_num, projection_size, data, offset, 1);
4728    if (layer_size > 1) {
4729      data[8] = hidden_layer_cache;
4730      data[9] = last_layer_cache;
4731      e = execute_rnn_backward_primitive(
4732          mode, ::dnnl::rnn_direction::bidirectional_sum, bias_mode, src_dt,
4733          src_format_tag, seq_length, batch_size, output_size, output_size, 1,
4734          direction_num, hidden_size, gate_num, projection_size, data, offset,
4735          layer_size - 1);
4736      _q->memcpy(diff_src,
4737                 ((layer_size - 1) % 2 == 0) ? last_layer_cache
4738                                             : hidden_layer_cache,
4739                 src_desc.get_size());
4740    }
4741  } else {
4742    e = execute_rnn_backward_primitive(
4743        mode, ::dnnl::rnn_direction::unidirectional_left2right, bias_mode,
4744        src_dt, src_format_tag, seq_length, batch_size, output_size,
4745        output_size, layer_size, direction_num, hidden_size, gate_num,
4746        projection_size, data, offset, 1);
4747  }
4748
4749  return exit_primitive(e);
4750}
4751
4752inline
4753size_t engine_ext::get_dropout_state_size(){
4754#ifndef __INTEL_MKL__
4755  throw std::runtime_error("The oneAPI Math Kernel Library (oneMKL) "
4756                           "Interfaces Project does not support this API.");
4757#else
4758  auto r = get_internal_resource(_q);
4759  if(r->random_engine_state_size == -1){
4760    auto rand_engine = rng_engine_t(*_q, 0);
4761    r->random_engine_state_size =
4762        oneapi::mkl::rng::get_state_size(rand_engine);
4763  }
4764  return r->random_engine_state_size;
4765#endif
4766}
4767
4768inline size_t
4769engine_ext::get_dropout_workspace_size(const memory_desc_ext &src_desc) {
4770  return src_desc.get_size();
4771}
4772
4773inline
4774sycl::event engine_ext::async_dropout_forward(dropout_desc &desc,
4775                                              const memory_desc_ext &src_desc,
4776                                              void *src,
4777                                              const memory_desc_ext &dst_desc,
4778                                              void *dst, void *workspace,
4779                                              size_t workspace_size) {
4780  if (workspace_size < src_desc.get_size()) {
4781    throw std::runtime_error("async_dropout_forward: no sufficient workspace.");
4782  }
4783  enter_primitive(src_desc.get_size() * 2 + dst_desc.get_size() * 2);
4784  float p = desc.get_probability();
4785  if (p == 1.f) {
4786    return _q->memset(dst, 0, dst_desc.get_size());
4787  } else if (p == 0.f) {
4788    return async_reorder(1.f, src_desc, src, 0.f, dst_desc, dst);
4789  }
4790
4791  float scale_factor = 1.f / (1.f - p);
4792  void *cache = workspace;
4793
4794  memory_desc_ext rng_data_desc(
4795      ::dnnl::memory::desc(src_desc.get_dims(), ::dnnl::memory::data_type::s32,
4796                           src_desc.get_strides()));
4797  if (src_desc.get_desc().get_data_type() != ::dnnl::memory::data_type::s32) {
4798    cache = allocate(rng_data_desc);
4799  }
4800
4801  desc.generate(_q, get_dropout_state_size(), rng_data_desc.get_element_num(),
4802                (std::int32_t *)cache);
4803
4804  if (cache == workspace) {
4805    async_scale(scale_factor, src_desc, workspace);
4806  } else {
4807    async_reorder(scale_factor, rng_data_desc, cache, 0.f, src_desc, workspace);
4808  }
4809
4810  auto primitive_args = create_primitive_args_or_get<::dnnl::binary>(
4811      ::dnnl::algorithm::binary_mul, src_desc.get_desc(), src_desc.get_desc(),
4812      dst_desc.get_desc());
4813
4814  insert_arg(primitive_args.second.args, DNNL_ARG_SRC_0, src_desc.get_desc(),
4815             src);
4816  insert_arg(primitive_args.second.args, DNNL_ARG_SRC_1, src_desc.get_desc(),
4817             workspace);
4818  insert_arg(primitive_args.second.args, DNNL_ARG_DST, dst_desc.get_desc(),
4819             dst);
4820
4821  return exit_primitive(execute_primitive<::dnnl::binary>(primitive_args));
4822}
4823
4824inline
4825sycl::event engine_ext::async_dropout_backward(
4826    dropout_desc &desc, const memory_desc_ext &diff_dst_desc,
4827    void *diff_dst, const memory_desc_ext &diff_src_desc, void *diff_src,
4828    void *workspace, size_t workspace_size) {
4829  enter_primitive(2 * diff_src_desc.get_size());
4830  float p = desc.get_probability();
4831  if (p == 1.f) {
4832    return _q->memset(diff_src, 0, diff_src_desc.get_size());
4833  } else if (p == 0.f) {
4834    return async_reorder(1.f, diff_dst_desc, diff_dst, 0.f, diff_src_desc,
4835                         diff_src);
4836  }
4837
4838  auto primitive_args = create_primitive_args_or_get<::dnnl::binary>(
4839      ::dnnl::algorithm::binary_mul, diff_dst_desc.get_desc(),
4840      diff_dst_desc.get_desc(), diff_src_desc.get_desc());
4841
4842  insert_arg(primitive_args.second.args, DNNL_ARG_SRC_0,
4843             diff_dst_desc.get_desc(), diff_dst);
4844  insert_arg(primitive_args.second.args, DNNL_ARG_SRC_1,
4845             diff_dst_desc.get_desc(), workspace);
4846  insert_arg(primitive_args.second.args, DNNL_ARG_DST, diff_src_desc.get_desc(),
4847             diff_src);
4848
4849  return exit_primitive(execute_primitive<::dnnl::binary>(primitive_args));
4850}
4851} // namespace dnnl
4852} // namespace dpct
4853
4854#endif // __DPCT_DNNL_UTILS_HPP__