okami.mom/strata

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

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

main
83.6 KiB1838 linesraw
1//==---- sparse_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_SPARSE_UTILS_HPP__
10#define __DPCT_SPARSE_UTILS_HPP__
11
12#include "compat_service.hpp"
13#include "lib_common_utils.hpp"
14
15namespace dpct::sparse {
16class matrix_info {
17public:
18  /// Matrix types are:
19  /// ge: General matrix
20  /// sy: Symmetric matrix
21  /// he: Hermitian matrix
22  /// tr: Triangular matrix
23  enum class matrix_type : int { ge = 0, sy, he, tr };
24
25  auto get_matrix_type() const { return _matrix_type; }
26  auto get_diag() const { return _diag; }
27  auto get_uplo() const { return _uplo; }
28  auto get_index_base() const { return _index_base; }
29  void set_matrix_type(matrix_type mt) { _matrix_type = mt; }
30  void set_diag(oneapi::mkl::diag d) { _diag = d; }
31  void set_uplo(oneapi::mkl::uplo u) { _uplo = u; }
32  void set_index_base(oneapi::mkl::index_base ib) { _index_base = ib; }
33
34private:
35  matrix_type _matrix_type = matrix_type::ge;
36  oneapi::mkl::diag _diag = oneapi::mkl::diag::nonunit;
37  oneapi::mkl::uplo _uplo = oneapi::mkl::uplo::upper;
38  oneapi::mkl::index_base _index_base = oneapi::mkl::index_base::zero;
39};
40
41/// Sparse matrix data format
42enum matrix_format : int { csr = 1, coo = 2 };
43
44/// Sparse matrix attribute
45enum matrix_attribute : int { uplo = 0, diag };
46
47enum class conversion_scope : int { index = 0, index_and_value };
48
49#ifdef __INTEL_MKL__ // The oneMKL Interfaces Project does not support this.
50// Forward declaration
51namespace detail {
52template <typename T> struct optimize_csrsv_impl;
53template <typename T> struct optimize_csrsm_impl;
54}
55
56/// Saving the optimization information for solving a system of linear
57/// equations.
58class optimize_info {
59public:
60  /// Constructor
61  optimize_info() { oneapi::mkl::sparse::init_matrix_handle(&_matrix_handle); }
62  /// Destructor
63  ~optimize_info() {
64    oneapi::mkl::sparse::release_matrix_handle(::dpct::cs::get_default_queue(),
65                                               &_matrix_handle, _deps)
66        .wait();
67  }
68  /// Add dependency for the destructor.
69  /// \param [in] e The event which the destructor depends on.
70  void add_dependency(sycl::event e) { _deps.push_back(e); }
71  /// Get the internal saved matrix handle.
72  /// \return Returns the matrix handle.
73  oneapi::mkl::sparse::matrix_handle_t get_matrix_handle() const noexcept {
74    return _matrix_handle;
75  }
76#ifdef DPCT_USM_LEVEL_NONE
77  template <typename T> friend struct detail::optimize_csrsv_impl;
78  template <typename T> friend struct detail::optimize_csrsm_impl;
79#endif
80
81private:
82  oneapi::mkl::sparse::matrix_handle_t _matrix_handle = nullptr;
83  std::vector<sycl::event> _deps;
84#ifdef DPCT_USM_LEVEL_NONE
85  static constexpr size_t _max_data_variable_size =
86      (std::max)({sizeof(sycl::buffer<float>), sizeof(sycl::buffer<double>),
87                  sizeof(sycl::buffer<std::complex<float>>),
88                  sizeof(sycl::buffer<std::complex<double>>)});
89  using value_buf_t =
90      std::variant<std::array<std::byte, _max_data_variable_size>,
91                   sycl::buffer<float>, sycl::buffer<double>,
92                   sycl::buffer<std::complex<float>>,
93                   sycl::buffer<std::complex<double>>>;
94  sycl::buffer<int> _row_ptr_buf = sycl::buffer<int>(0);
95  sycl::buffer<int> _col_ind_buf = sycl::buffer<int>(0);
96  value_buf_t _val_buf;
97#endif
98};
99
100/// Structure for describe a sparse matrix
101class sparse_matrix_desc {
102public:
103  /// Constructor
104  /// \param [out] desc The descriptor to be created
105  /// \param [in] row_num Number of rows of the sparse matrix.
106  /// \param [in] col_num Number of colums of the sparse matrix.
107  /// \param [in] nnz Non-zero elements in the sparse matrix.
108  /// \param [in] row_ptr An array of length \p row_num + 1. If the \p row_ptr is
109  /// NULL, the sparse_matrix_desc will allocate internal memory for it. This
110  /// internal memory can be gotten from get_shadow_row_ptr().
111  /// \param [in] col_ind An array containing the column indices in index-based
112  /// numbering.
113  /// \param [in] value An array containing the non-zero elements of the sparse matrix.
114  /// \param [in] row_ptr_type Data type of the \p row_ptr .
115  /// \param [in] col_ind_type Data type of the \p col_ind .
116  /// \param [in] base Indicates how input arrays are indexed.
117  /// \param [in] value_type Data type of the \p value .
118  /// \param [in] data_format The matrix data format.
119  sparse_matrix_desc(std::int64_t row_num, std::int64_t col_num,
120                     std::int64_t nnz, void *row_ptr, void *col_ind,
121                     void *value, library_data_t row_ptr_type,
122                     library_data_t col_ind_type, oneapi::mkl::index_base base,
123                     library_data_t value_type, matrix_format data_format)
124      : _row_num(row_num), _col_num(col_num), _nnz(nnz), _row_ptr(row_ptr),
125        _col_ind(col_ind), _value(value), _row_ptr_type(row_ptr_type),
126        _col_ind_type(col_ind_type), _base(base), _value_type(value_type),
127        _data_format(data_format) {
128    if (_data_format != matrix_format::csr &&
129        _data_format != matrix_format::coo) {
130      throw std::runtime_error("the sparse matrix data format is unsupported");
131    }
132    oneapi::mkl::sparse::init_matrix_handle(&_matrix_handle);
133    set_data();
134  }
135  /// Destructor
136  ~sparse_matrix_desc() {
137    oneapi::mkl::sparse::release_matrix_handle(::dpct::cs::get_default_queue(),
138                                               &_matrix_handle, _deps)
139        .wait();
140  }
141
142  /// Add dependency for the destroy method.
143  /// \param [in] e The event which the destroy method depends on.
144  void add_dependency(sycl::event e) { _deps.push_back(e); }
145  /// Get the internal saved matrix handle.
146  /// \return Returns the matrix handle.
147  oneapi::mkl::sparse::matrix_handle_t get_matrix_handle() const noexcept {
148    return _matrix_handle;
149  }
150  /// Get the values saved in the descriptor
151  /// \param [out] row_num Number of rows of the sparse matrix.
152  /// \param [out] col_num Number of colums of the sparse matrix.
153  /// \param [out] nnz Non-zero elements in the sparse matrix.
154  /// \param [out] row_ptr An array of length \p row_num + 1.
155  /// \param [out] col_ind An array containing the column indices in index-based
156  /// numbering.
157  /// \param [out] value An array containing the non-zero elements of the sparse matrix.
158  /// \param [out] row_ptr_type Data type of the \p row_ptr .
159  /// \param [out] col_ind_type Data type of the \p col_ind .
160  /// \param [out] base Indicates how input arrays are indexed.
161  /// \param [out] value_type Data type of the \p value .
162  void get_desc(int64_t *row_num, int64_t *col_num, int64_t *nnz,
163                void **row_ptr, void **col_ind, void **value,
164                library_data_t *row_ptr_type, library_data_t *col_ind_type,
165                oneapi::mkl::index_base *base,
166                library_data_t *value_type) const noexcept {
167    *row_num = _row_num;
168    *col_num = _col_num;
169    *nnz = _nnz;
170    *row_ptr = _row_ptr;
171    *col_ind = _col_ind;
172    *value = _value;
173    *row_ptr_type = _row_ptr_type;
174    *col_ind_type = _col_ind_type;
175    *base = _base;
176    *value_type = _value_type;
177  }
178  /// Get the sparse matrix data format of this descriptor
179  /// \param [out] format The matrix data format result
180  void get_format(matrix_format *data_format) const noexcept {
181    *data_format = _data_format;
182  }
183  /// Get the index base of this descriptor
184  /// \param [out] base The index base result
185  void get_base(oneapi::mkl::index_base *base) const noexcept { *base = _base; }
186  /// Get the value pointer of this descriptor
187  /// \param [out] value The value pointer result
188  void get_value(void **value) const noexcept { *value = _value; }
189  /// Set the value pointer of this descriptor
190  /// \param [in] value The input value pointer
191  void set_value(void *value) {
192    if (!value) {
193      throw std::runtime_error(
194          "dpct::sparse::sparse_matrix_desc::set_value(): The value "
195          "pointer is NULL.");
196    }
197    if (_value && (_value != value)) {
198      throw std::runtime_error(
199          "dpct::sparse::sparse_matrix_desc::set_value(): "
200          "The _value pointer is not NULL. It cannot be reset.");
201    }
202    _value = value;
203    set_data();
204  }
205  /// Get the size of the sparse matrix
206  /// \param [out] row_num Number of rows of the sparse matrix.
207  /// \param [out] col_num Number of colums of the sparse matrix.
208  /// \param [out] nnz Non-zero elements in the sparse matrix.
209  void get_size(int64_t *row_num, int64_t *col_num,
210                int64_t *nnz) const noexcept {
211    *row_num = _row_num;
212    *col_num = _col_num;
213    *nnz = _nnz;
214  }
215  /// Set the sparse matrix attribute
216  /// \param [in] attribute The attribute type
217  /// \param [in] data The attribute value
218  /// \param [in] data_size The data size of the attribute value
219  void set_attribute(matrix_attribute attribute, const void *data,
220                     size_t data_size) {
221    if (attribute == matrix_attribute::diag) {
222      const oneapi::mkl::diag *diag_ptr =
223          reinterpret_cast<const oneapi::mkl::diag *>(data);
224      if (*diag_ptr == oneapi::mkl::diag::unit) {
225        _diag = oneapi::mkl::diag::unit;
226      } else if (*diag_ptr == oneapi::mkl::diag::nonunit) {
227        _diag = oneapi::mkl::diag::nonunit;
228      } else {
229        throw std::runtime_error("unsupported diag value");
230      }
231    } else if (attribute == matrix_attribute::uplo) {
232      const oneapi::mkl::uplo *uplo_ptr =
233          reinterpret_cast<const oneapi::mkl::uplo *>(data);
234      if (*uplo_ptr == oneapi::mkl::uplo::upper) {
235        _uplo = oneapi::mkl::uplo::upper;
236      } else if (*uplo_ptr == oneapi::mkl::uplo::lower) {
237        _uplo = oneapi::mkl::uplo::lower;
238      } else {
239        throw std::runtime_error("unsupported uplo value");
240      }
241    } else {
242      throw std::runtime_error("unsupported attribute");
243    }
244  }
245  /// Get the sparse matrix attribute
246  /// \param [out] attribute The attribute type
247  /// \param [out] data The attribute value
248  /// \param [out] data_size The data size of the attribute value
249  void get_attribute(matrix_attribute attribute, void *data,
250                     size_t data_size) const {
251    if (attribute == matrix_attribute::diag) {
252      oneapi::mkl::diag *diag_ptr = reinterpret_cast<oneapi::mkl::diag *>(data);
253      if (_diag.has_value()) {
254        *diag_ptr = _diag.value();
255      } else {
256        *diag_ptr = oneapi::mkl::diag::nonunit;
257      }
258    } else if (attribute == matrix_attribute::uplo) {
259      oneapi::mkl::uplo *uplo_ptr = reinterpret_cast<oneapi::mkl::uplo *>(data);
260      if (_uplo.has_value()) {
261        *uplo_ptr = _uplo.value();
262      } else {
263        *uplo_ptr = oneapi::mkl::uplo::lower;
264      }
265    } else {
266      throw std::runtime_error("unsupported attribute");
267    }
268  }
269  /// Set the pointers for describing the sparse matrix
270  /// \param [in] row_ptr An array of length \p row_num + 1.
271  /// \param [in] col_ind An array containing the column indices in index-based
272  /// numbering.
273  /// \param [in] value An array containing the non-zero elements of the sparse matrix.
274  void set_pointers(void *row_ptr, void *col_ind, void *value) {
275    if (!row_ptr) {
276      throw std::runtime_error(
277          "dpct::sparse::sparse_matrix_desc::set_pointers(): The "
278          "row_ptr pointer is NULL.");
279    }
280    if (!col_ind) {
281      throw std::runtime_error(
282          "dpct::sparse::sparse_matrix_desc::set_pointers(): The "
283          "col_ind pointer is NULL.");
284    }
285    if (_row_ptr && (_row_ptr != row_ptr)) {
286      throw std::runtime_error("dpct::sparse::sparse_matrix_desc::set_pointers("
287                               "): The _row_ptr pointer is "
288                               "not NULL. It cannot be reset.");
289    }
290    if (_col_ind && (_col_ind != col_ind)) {
291      throw std::runtime_error("dpct::sparse::sparse_matrix_desc::set_pointers("
292                               "): The _col_ind pointer is "
293                               "not NULL. It cannot be reset.");
294    }
295    _row_ptr = row_ptr;
296    _col_ind = col_ind;
297
298    // The descriptor will be updated in the set_value function
299    set_value(value);
300  }
301
302  /// Get the diag attribute
303  /// \return diag value
304  std::optional<oneapi::mkl::diag> get_diag() const noexcept { return _diag; }
305  /// Get the uplo attribute
306  /// \return uplo value
307  std::optional<oneapi::mkl::uplo> get_uplo() const noexcept { return _uplo; }
308  /// Set the number of non-zero elements
309  /// \param nnz [in] The number of non-zero elements.
310  void set_nnz(std::int64_t nnz) noexcept { _nnz = nnz; }
311  /// Get the type of the value pointer.
312  /// \return The type of the value pointer.
313  library_data_t get_value_type() const noexcept { return _value_type; }
314  /// Get the row_ptr.
315  /// \return The row_ptr.
316  void *get_row_ptr() const noexcept { return _row_ptr; }
317  /// If the internal _row_ptr is NULL, the sparse_matrix_desc will allocate
318  /// internal memory for it in the constructor. The internal memory can be gotten
319  /// from this interface.
320  /// \return The shadow row_ptr.
321  void *get_shadow_row_ptr() const noexcept { return _shadow_row_ptr.get(); }
322  /// Get the type of the col_ind pointer.
323  /// \return The type of the col_ind pointer.
324  library_data_t get_col_ind_type() const noexcept { return _col_ind_type; }
325  /// Get the row_num.
326  /// \return The row_num.
327  std::int64_t get_row_num() const noexcept { return _row_num; }
328
329private:
330  inline static const std::function<void(void *)> _shadow_row_ptr_deleter =
331      [](void *ptr) { ::dpct::cs::free(ptr, ::dpct::cs::get_default_queue()); };
332  template <typename index_t, typename value_t> void set_data() {
333    void *row_ptr = nullptr;
334    if (_shadow_row_ptr) {
335      row_ptr = _shadow_row_ptr.get();
336    } else if (_row_ptr) {
337      row_ptr = _row_ptr;
338    } else {
339      row_ptr = ::dpct::cs::malloc(sizeof(index_t) * (_row_num + 1),
340                                   ::dpct::cs::get_default_queue());
341      _shadow_row_ptr.reset(row_ptr);
342    }
343#ifdef DPCT_USM_LEVEL_NONE
344    using data_index_t = sycl::buffer<index_t>;
345    using data_value_t = sycl::buffer<value_t>;
346#else
347    using data_index_t = index_t *;
348    using data_value_t = value_t *;
349#endif
350    _data_row_ptr = dpct::detail::get_memory<index_t>(row_ptr);
351    _data_col_ind = dpct::detail::get_memory<index_t>(_col_ind);
352    _data_value = dpct::detail::get_memory<value_t>(_value);
353    if (_data_format == matrix_format::csr)
354      oneapi::mkl::sparse::set_csr_data(
355          ::dpct::cs::get_default_queue(), _matrix_handle, _row_num, _col_num,
356          _base, std::get<data_index_t>(_data_row_ptr),
357          std::get<data_index_t>(_data_col_ind),
358          std::get<data_value_t>(_data_value));
359    else
360      oneapi::mkl::sparse::set_coo_data(
361          ::dpct::cs::get_default_queue(), _matrix_handle, _row_num, _col_num,
362          _nnz, _base, std::get<data_index_t>(_data_row_ptr),
363          std::get<data_index_t>(_data_col_ind),
364          std::get<data_value_t>(_data_value));
365    ::dpct::cs::get_default_queue().wait();
366  }
367
368  void set_data() {
369    std::uint64_t key = dpct::detail::get_type_combination_id(
370        _row_ptr_type, _col_ind_type, _value_type);
371    switch (key) {
372    case dpct::detail::get_type_combination_id(library_data_t::real_int32,
373                                               library_data_t::real_int32,
374                                               library_data_t::real_float): {
375      set_data<std::int32_t, float>();
376      break;
377    }
378    case dpct::detail::get_type_combination_id(library_data_t::real_int32,
379                                               library_data_t::real_int32,
380                                               library_data_t::real_double): {
381      set_data<std::int32_t, double>();
382      break;
383    }
384    case dpct::detail::get_type_combination_id(library_data_t::real_int32,
385                                               library_data_t::real_int32,
386                                               library_data_t::complex_float): {
387      set_data<std::int32_t, std::complex<float>>();
388      break;
389    }
390    case dpct::detail::get_type_combination_id(
391        library_data_t::real_int32, library_data_t::real_int32,
392        library_data_t::complex_double): {
393      set_data<std::int32_t, std::complex<double>>();
394      break;
395    }
396    case dpct::detail::get_type_combination_id(library_data_t::real_int64,
397                                               library_data_t::real_int64,
398                                               library_data_t::real_float): {
399      set_data<std::int64_t, float>();
400      break;
401    }
402    case dpct::detail::get_type_combination_id(library_data_t::real_int64,
403                                               library_data_t::real_int64,
404                                               library_data_t::real_double): {
405      set_data<std::int64_t, double>();
406      break;
407    }
408    case dpct::detail::get_type_combination_id(library_data_t::real_int64,
409                                               library_data_t::real_int64,
410                                               library_data_t::complex_float): {
411      set_data<std::int64_t, std::complex<float>>();
412      break;
413    }
414    case dpct::detail::get_type_combination_id(
415        library_data_t::real_int64, library_data_t::real_int64,
416        library_data_t::complex_double): {
417      set_data<std::int64_t, std::complex<double>>();
418      break;
419    }
420    default:
421      throw std::runtime_error("the combination of data type is unsupported");
422    }
423  }
424
425  std::int64_t _row_num;
426  std::int64_t _col_num;
427  std::int64_t _nnz;
428  void *_row_ptr;
429  void *_col_ind;
430  void *_value;
431  library_data_t _row_ptr_type;
432  library_data_t _col_ind_type;
433  oneapi::mkl::index_base _base;
434  library_data_t _value_type;
435  oneapi::mkl::sparse::matrix_handle_t _matrix_handle = nullptr;
436  std::vector<sycl::event> _deps;
437  matrix_format _data_format;
438  std::optional<oneapi::mkl::uplo> _uplo;
439  std::optional<oneapi::mkl::diag> _diag;
440  std::unique_ptr<void, std::function<void(void *)>> _shadow_row_ptr =
441      std::unique_ptr<void, std::function<void(void *)>>(
442          nullptr, _shadow_row_ptr_deleter);
443
444  static constexpr size_t _max_data_variable_size = (std::max)(
445      {sizeof(sycl::buffer<std::int32_t>), sizeof(sycl::buffer<std::int64_t>),
446       sizeof(sycl::buffer<float>), sizeof(sycl::buffer<double>),
447       sizeof(sycl::buffer<std::complex<float>>),
448       sizeof(sycl::buffer<std::complex<double>>), sizeof(void *)});
449  using index_variant_t =
450      std::variant<std::array<std::byte, _max_data_variable_size>,
451                   sycl::buffer<std::int32_t>, sycl::buffer<std::int64_t>,
452                   std::int32_t *, std::int64_t *>;
453  using value_variant_t =
454      std::variant<std::array<std::byte, _max_data_variable_size>,
455                   sycl::buffer<float>, sycl::buffer<double>,
456                   sycl::buffer<std::complex<float>>,
457                   sycl::buffer<std::complex<double>>, float *, double *,
458                   std::complex<float> *, std::complex<double> *>;
459  index_variant_t _data_row_ptr;
460  index_variant_t _data_col_ind;
461  value_variant_t _data_value;
462};
463#endif
464
465class sparse_matrix_desc;
466using sparse_matrix_desc_t = std::shared_ptr<sparse_matrix_desc>;
467
468/// Structure for describe a dense vector
469class dense_vector_desc {
470public:
471  dense_vector_desc(std::int64_t ele_num, void *value,
472                    library_data_t value_type)
473      : _ele_num(ele_num), _value(value), _value_type(value_type) {}
474  void get_desc(std::int64_t *ele_num, const void **value,
475                library_data_t *value_type) const noexcept {
476    *ele_num = _ele_num;
477    *value = _value;
478    *value_type = _value_type;
479  }
480  void get_desc(std::int64_t *ele_num, void **value,
481                library_data_t *value_type) const noexcept {
482    get_desc(ele_num, const_cast<const void **>(value), value_type);
483  }
484  void *get_value() const noexcept { return _value; }
485  void set_value(void *value) { _value = value; }
486  library_data_t get_value_type() const noexcept { return _value_type; }
487  std::int64_t get_ele_num() const noexcept { return _ele_num; }
488
489private:
490  std::int64_t _ele_num;
491  void *_value;
492  library_data_t _value_type;
493};
494
495/// Structure for describe a dense matrix
496class dense_matrix_desc {
497public:
498  dense_matrix_desc(std::int64_t row_num, std::int64_t col_num,
499                    std::int64_t leading_dim, void *value,
500                    library_data_t value_type, oneapi::mkl::layout layout)
501      : _row_num(row_num), _col_num(col_num), _leading_dim(leading_dim),
502        _value(value), _value_type(value_type), _layout(layout) {}
503  void get_desc(std::int64_t *row_num, std::int64_t *col_num,
504                std::int64_t *leading_dim, void **value,
505                library_data_t *value_type,
506                oneapi::mkl::layout *layout) const noexcept {
507    *row_num = _row_num;
508    *col_num = _col_num;
509    *leading_dim = _leading_dim;
510    *value = _value;
511    *value_type = _value_type;
512    *layout = _layout;
513  }
514  void *get_value() const noexcept { return _value; }
515  void set_value(void *value) { _value = value; }
516  std::int64_t get_col_num() const noexcept { return _col_num; }
517  std::int64_t get_leading_dim() const noexcept { return _leading_dim; }
518  oneapi::mkl::layout get_layout() const noexcept { return _layout; }
519
520private:
521  std::int64_t _row_num;
522  std::int64_t _col_num;
523  std::int64_t _leading_dim;
524  void *_value;
525  library_data_t _value_type;
526  oneapi::mkl::layout _layout;
527};
528} // namespace dpct::sparse
529
530#include "detail/sparse_utils_detail.hpp"
531
532namespace dpct::sparse {
533class descriptor {
534public:
535  descriptor() {}
536  void set_queue(::dpct::cs::queue_ptr q_ptr) noexcept { _queue_ptr = q_ptr; }
537  sycl::queue &get_queue() const noexcept { return *_queue_ptr; }
538
539private:
540#ifdef __INTEL_MKL__
541  struct matmat_info {
542    detail::matrix_handle_manager matrix_handle_a;
543    detail::matrix_handle_manager matrix_handle_b;
544    detail::matrix_handle_manager matrix_handle_c;
545    detail::handle_manager<oneapi::mkl::sparse::matmat_descr_t> matmat_desc;
546    bool is_empty() { return matmat_desc.is_empty(); }
547    void init(sycl::queue *q_ptr) {
548      matmat_desc.init(q_ptr);
549      matrix_handle_a.init(q_ptr);
550      matrix_handle_b.init(q_ptr);
551      matrix_handle_c.init(q_ptr);
552    }
553  };
554  std::unordered_map<detail::csrgemm_args_info, matmat_info,
555                     detail::csrgemm_args_info_hash> &
556  get_csrgemm_info_map() {
557    return _csrgemm_info_map;
558  }
559
560  std::unordered_map<detail::csrgemm_args_info, matmat_info,
561                     detail::csrgemm_args_info_hash>
562      _csrgemm_info_map;
563
564  template <typename T>
565  friend void
566  csrgemm_nnz(descriptor *desc, oneapi::mkl::transpose trans_a,
567              oneapi::mkl::transpose trans_b, int m, int n, int k,
568              const std::shared_ptr<matrix_info> info_a, int nnz_a,
569              const T *val_a, const int *row_ptr_a, const int *col_ind_a,
570              const std::shared_ptr<matrix_info> info_b, int nnz_b,
571              const T *val_b, const int *row_ptr_b, const int *col_ind_b,
572              const std::shared_ptr<matrix_info> info_c, int *row_ptr_c,
573              int *nnz_host_ptr);
574  template <typename T>
575  friend void csrgemm(descriptor *desc, oneapi::mkl::transpose trans_a,
576                      oneapi::mkl::transpose trans_b, int m, int n, int k,
577                      const std::shared_ptr<matrix_info> info_a, const T *val_a,
578                      const int *row_ptr_a, const int *col_ind_a,
579                      const std::shared_ptr<matrix_info> info_b, const T *val_b,
580                      const int *row_ptr_b, const int *col_ind_b,
581                      const std::shared_ptr<matrix_info> info_c, T *val_c,
582                      const int *row_ptr_c, int *col_ind_c);
583#endif
584  ::dpct::cs::queue_ptr _queue_ptr = &::dpct::cs::get_default_queue();
585};
586
587using descriptor_ptr = descriptor *;
588
589/// Computes a CSR format sparse matrix-dense vector product.
590/// y = alpha * op(A) * x + beta * y
591/// \param [in] queue The queue where the routine should be executed. It must
592/// have the in_order property when using the USM mode.
593/// \param [in] trans The operation applied to the matrix A.
594/// \param [in] num_rows Number of rows of the matrix A.
595/// \param [in] num_cols Number of columns of the matrix A.
596/// \param [in] alpha Scaling factor for the matrix A.
597/// \param [in] info Matrix info of the matrix A.
598/// \param [in] val An array containing the non-zero elements of the matrix A.
599/// \param [in] row_ptr An array of length \p num_rows + 1.
600/// \param [in] col_ind An array containing the column indices in index-based
601/// numbering.
602/// \param [in] x Data of the vector x.
603/// \param [in] beta Scaling factor for the vector x.
604/// \param [in, out] y Data of the vector y.
605template <typename T>
606void csrmv(sycl::queue &queue, oneapi::mkl::transpose trans, int num_rows,
607           int num_cols, const T *alpha,
608           const std::shared_ptr<matrix_info> info, const T *val,
609           const int *row_ptr, const int *col_ind, const T *x, const T *beta,
610           T *y) {
611  detail::csrmv_impl<T>()(queue, trans, num_rows, num_cols, alpha, info, val,
612                          row_ptr, col_ind, x, beta, y);
613}
614
615/// Computes a CSR format sparse matrix-dense vector product. y = A * x
616///
617/// \param [in] queue The queue where the routine should be executed. It must
618/// have the in_order property when using the USM mode.
619/// \param [in] values An array containing the non-zero elements of the matrix.
620/// \param [in] row_offsets An array of length \p num_rows + 1.
621/// \param [in] column_indices An array containing the column indices in
622/// index-based numbering.
623/// \param [in] vector_x Data of the vector x.
624/// \param [in, out] vector_y Data of the vector y.
625/// \param [in] num_rows Number of rows of the matrix A.
626/// \param [in] num_cols Number of columns of the matrix A.
627template <typename T>
628void csrmv(sycl::queue &queue, const T *values, const int *row_offsets,
629           const int *column_indices, const T *vector_x, T *vector_y,
630           int num_rows, int num_cols) {
631  T alpha{1}, beta{0};
632  auto matrix_info = std::make_shared<dpct::sparse::matrix_info>();
633  matrix_info->set_index_base(oneapi::mkl::index_base::zero);
634  matrix_info->set_matrix_type(dpct::sparse::matrix_info::matrix_type::ge);
635  detail::csrmv_impl<T>()(queue, oneapi::mkl::transpose::nontrans, num_rows,
636                          num_cols, &alpha, matrix_info, values, row_offsets,
637                          column_indices, vector_x, &beta, vector_y);
638}
639
640/// Computes a CSR format sparse matrix-dense vector product.
641/// y = alpha * op(A) * x + beta * y
642/// \param [in] queue The queue where the routine should be executed. It must
643/// have the in_order property when using the USM mode.
644/// \param [in] trans The operation applied to the matrix A.
645/// \param [in] num_rows Number of rows of the matrix A.
646/// \param [in] num_cols Number of columns of the matrix A.
647/// \param [in] alpha Scaling factor for the matrix A.
648/// \param [in] alpha_type Data type of \p alpha .
649/// \param [in] info Matrix info of the matrix A.
650/// \param [in] val An array containing the non-zero elements of the matrix A.
651/// \param [in] val_type Data type of \p val .
652/// \param [in] row_ptr An array of length \p num_rows + 1.
653/// \param [in] col_ind An array containing the column indices in index-based
654/// numbering.
655/// \param [in] x Data of the vector x.
656/// \param [in] x_type Data type of \p x .
657/// \param [in] beta Scaling factor for the vector x.
658/// \param [in] beta_type Data type of \p beta .
659/// \param [in, out] y Data of the vector y.
660/// \param [in] y_type Data type of \p y .
661inline void csrmv(sycl::queue &queue, oneapi::mkl::transpose trans,
662                  int num_rows, int num_cols, const void *alpha,
663                  library_data_t alpha_type,
664                  const std::shared_ptr<matrix_info> info, const void *val,
665                  library_data_t val_type, const int *row_ptr,
666                  const int *col_ind, const void *x, library_data_t x_type,
667                  const void *beta, library_data_t beta_type, void *y,
668                  library_data_t y_type) {
669  detail::spblas_shim<detail::csrmv_impl>(val_type, queue, trans, num_rows,
670                                          num_cols, alpha, info, val, row_ptr,
671                                          col_ind, x, beta, y);
672}
673
674/// Computes a CSR format sparse matrix-dense matrix product.
675/// C = alpha * op(A) * op(B) + beta * C
676/// \param [in] queue The queue where the routine should be executed. It must
677/// have the in_order property when using the USM mode.
678/// \param [in] trans_a The operation applied to the matrix A.
679/// \param [in] trans_b The operation applied to the matrix B.
680/// \param [in] sparse_rows Number of rows of the matrix A.
681/// \param [in] dense_cols Number of columns of the matrix B or C.
682/// \param [in] sparse_cols Number of columns of the matrix A.
683/// \param [in] alpha Scaling factor for the matrix A.
684/// \param [in] info Matrix info of the matrix A.
685/// \param [in] val An array containing the non-zero elements of the matrix A.
686/// \param [in] row_ptr An array of length \p num_rows + 1.
687/// \param [in] col_ind An array containing the column indices in index-based
688/// numbering.
689/// \param [in] b Data of the matrix B.
690/// \param [in] ldb Leading dimension of the matrix B.
691/// \param [in] beta Scaling factor for the matrix B.
692/// \param [in, out] c Data of the matrix C.
693/// \param [in] ldc Leading dimension of the matrix C.
694template <typename T>
695void csrmm(sycl::queue &queue, oneapi::mkl::transpose trans_a,
696           oneapi::mkl::transpose trans_b, int sparse_rows, int dense_cols,
697           int sparse_cols, const T *alpha,
698           const std::shared_ptr<matrix_info> info, const T *val,
699           const int *row_ptr, const int *col_ind, const T *b, int ldb,
700           const T *beta, T *c, int ldc) {
701#ifndef __INTEL_MKL__
702  throw std::runtime_error("The oneAPI Math Kernel Library (oneMKL) Interfaces "
703                           "Project does not support this API.");
704#else
705  using Ty = typename ::dpct::detail::lib_data_traits_t<T>;
706  auto alpha_value =
707      dpct::detail::get_value(reinterpret_cast<const Ty *>(alpha), queue);
708  auto beta_value =
709      dpct::detail::get_value(reinterpret_cast<const Ty *>(beta), queue);
710
711  oneapi::mkl::sparse::matrix_handle_t *sparse_matrix_handle =
712      new oneapi::mkl::sparse::matrix_handle_t;
713  oneapi::mkl::sparse::init_matrix_handle(sparse_matrix_handle);
714  auto data_row_ptr = dpct::detail::get_memory<int>(row_ptr);
715  auto data_col_ind = dpct::detail::get_memory<int>(col_ind);
716  auto data_val = dpct::detail::get_memory<Ty>(val);
717  oneapi::mkl::sparse::set_csr_data(queue, *sparse_matrix_handle, sparse_rows,
718                                    sparse_cols, info->get_index_base(),
719                                    data_row_ptr, data_col_ind, data_val);
720
721  auto data_b = dpct::detail::get_memory<Ty>(b);
722  auto data_c = dpct::detail::get_memory<Ty>(c);
723  sycl::event gemm_event;
724  switch (info->get_matrix_type()) {
725  case matrix_info::matrix_type::ge: {
726#ifndef DPCT_USM_LEVEL_NONE
727    gemm_event =
728#endif
729        oneapi::mkl::sparse::gemm(queue, oneapi::mkl::layout::col_major,
730                                  trans_a, trans_b, alpha_value,
731                                  *sparse_matrix_handle, data_b, dense_cols,
732                                  ldb, beta_value, data_c, ldc);
733    break;
734  }
735  default:
736    throw std::runtime_error(
737        "the csrmm does not support matrix_info::matrix_type::sy, "
738        "matrix_info::matrix_type::tr and matrix_info::matrix_type::he");
739  }
740#ifdef DPCT_USM_LEVEL_NONE
741  queue.wait();
742#endif
743  sycl::event e = oneapi::mkl::sparse::release_matrix_handle(
744      queue, sparse_matrix_handle, {gemm_event});
745  queue.submit([&](sycl::handler &cgh) {
746    cgh.depends_on(e);
747    cgh.host_task([=] { delete sparse_matrix_handle; });
748  });
749#endif
750}
751
752/// Computes a CSR format sparse matrix-dense matrix product.
753/// C = alpha * op(A) * B + beta * C
754/// \param [in] queue The queue where the routine should be executed. It must
755/// have the in_order property when using the USM mode.
756/// \param [in] trans The operation applied to the matrix A.
757/// \param [in] sparse_rows Number of rows of the matrix A.
758/// \param [in] dense_cols Number of columns of the matrix op(B) or C.
759/// \param [in] sparse_cols Number of columns of the matrix A.
760/// \param [in] alpha Scaling factor for the matrix A.
761/// \param [in] info Matrix info of the matrix A.
762/// \param [in] val An array containing the non-zero elements of the matrix A.
763/// \param [in] row_ptr An array of length \p num_rows + 1.
764/// \param [in] col_ind An array containing the column indices in index-based
765/// numbering.
766/// \param [in] b Data of the matrix B.
767/// \param [in] ldb Leading dimension of the matrix B.
768/// \param [in] beta Scaling factor for the matrix B.
769/// \param [in, out] c Data of the matrix C.
770/// \param [in] ldc Leading dimension of the matrix C.
771template <typename T>
772void csrmm(sycl::queue &queue, oneapi::mkl::transpose trans, int sparse_rows,
773           int dense_cols, int sparse_cols, const T *alpha,
774           const std::shared_ptr<matrix_info> info, const T *val,
775           const int *row_ptr, const int *col_ind, const T *b, int ldb,
776           const T *beta, T *c, int ldc) {
777  csrmm<T>(queue, trans, oneapi::mkl::transpose::nontrans, sparse_rows,
778           dense_cols, sparse_cols, alpha, info, val, row_ptr, col_ind, b, ldb,
779           beta, c, ldc);
780}
781
782#ifdef __INTEL_MKL__ // The oneMKL Interfaces Project does not support this.
783/// Performs internal optimizations for solving a system of linear equations for
784/// a CSR format sparse matrix.
785/// \param [in] queue The queue where the routine should be executed. It must
786/// have the in_order property when using the USM mode.
787/// \param [in] trans The operation applied to the sparse matrix.
788/// \param [in] row_col Number of rows of the sparse matrix.
789/// \param [in] info Matrix info of the sparse matrix.
790/// \param [in] val An array containing the non-zero elements of the sparse matrix.
791/// \param [in] row_ptr An array of length \p num_rows + 1.
792/// \param [in] col_ind An array containing the column indices in index-based
793/// numbering.
794/// \param [out] optimize_info The result of the optimizations.
795template <typename T>
796void optimize_csrsv(sycl::queue &queue, oneapi::mkl::transpose trans,
797                    int row_col, const std::shared_ptr<matrix_info> info,
798                    const T *val, const int *row_ptr, const int *col_ind,
799                    std::shared_ptr<optimize_info> optimize_info) {
800  detail::optimize_csrsv_impl<T>()(queue, trans, row_col, info, val, row_ptr,
801                                   col_ind, optimize_info);
802}
803
804inline void optimize_csrsv(sycl::queue &queue, oneapi::mkl::transpose trans,
805                           int row_col, const std::shared_ptr<matrix_info> info,
806                           const void *val, library_data_t val_type,
807                           const int *row_ptr, const int *col_ind,
808                           std::shared_ptr<optimize_info> optimize_info) {
809  detail::spblas_shim<detail::optimize_csrsv_impl>(
810      val_type, queue, trans, row_col, info, val, row_ptr, col_ind,
811      optimize_info);
812}
813
814template <typename T>
815void csrsv(sycl::queue &queue, oneapi::mkl::transpose trans, int row_col,
816           const T *alpha, const std::shared_ptr<matrix_info> info,
817           const T *val, const int *row_ptr, const int *col_ind,
818           std::shared_ptr<optimize_info> optimize_info, const T *x, T *y) {
819  detail::csrsv_impl<T>()(queue, trans, row_col, alpha, info, val, row_ptr,
820                          col_ind, optimize_info, x, y);
821}
822
823inline void csrsv(sycl::queue &queue, oneapi::mkl::transpose trans, int row_col,
824                  const void *alpha, library_data_t alpha_type,
825                  const std::shared_ptr<matrix_info> info, const void *val,
826                  library_data_t val_type, const int *row_ptr,
827                  const int *col_ind,
828                  std::shared_ptr<optimize_info> optimize_info, const void *x,
829                  library_data_t x_type, void *y, library_data_t y_type) {
830  detail::spblas_shim<detail::csrsv_impl>(val_type, queue, trans, row_col,
831                                          alpha, info, val, row_ptr, col_ind,
832                                          optimize_info, x, y);
833}
834
835/// Performs internal optimizations for dpct::sparse::csrsm by analyzing
836/// the provided matrix structure and operation parameters. The matrix A must be
837/// a triangular sparse matrix with the CSR format.
838/// \param [in] queue The queue where the routine should be executed. It must
839/// have the in_order property when using the USM mode.
840/// \param [in] transa The operation applied to A.
841/// \param [in] transb The operation applied to B and X.
842/// \param [in] row_col Number of rows and columns of A.
843/// \param [in] nrhs Number of columns op_b(B).
844/// \param [in] info Matrix info of A.
845/// \param [in] val An array containing the non-zero elements of A.
846/// \param [in] row_ptr An array of length \p num_rows + 1.
847/// \param [in] col_ind An array containing the column indices in index-based
848/// numbering.
849/// \param [out] optimize_info The result of the optimizations.
850template <typename T>
851void optimize_csrsm(sycl::queue &queue, oneapi::mkl::transpose transa,
852                    oneapi::mkl::transpose transb, int row_col, int nrhs,
853                    const std::shared_ptr<matrix_info> info, const T *val,
854                    const int *row_ptr, const int *col_ind,
855                    std::shared_ptr<optimize_info> optimize_info) {
856  detail::optimize_csrsm_impl<T>()(queue, transa, transb, row_col, nrhs, info,
857                                   val, row_ptr, col_ind, optimize_info);
858}
859
860/// Solves the sparse triangular system op_a(A) * op_b(X) = alpha * op_b(B).
861/// A is a sparse triangular matrix with the CSR format of size \p row_col
862/// by \p row_col .
863/// B is a dense matrix of size \p row_col by \p nrhs ( \p transb is nontrans)
864/// or \p nrhs by \p row_col ( \p transb isn't nontrans).
865/// X is the solution dense matrix.
866/// \param [in] queue The queue where the routine should be executed. It must
867/// have the in_order property when using the USM mode.
868/// \param [in] transa The operation applied to A.
869/// \param [in] transb The operation applied to B and X.
870/// \param [in] row_col Number of rows and columns of A.
871/// \param [in] nrhs Number of columns op_b(B).
872/// \param [in] alpha Specifies the scalar.
873/// \param [in] info Matrix info of A.
874/// \param [in] val An array containing the non-zero elements of A.
875/// \param [in] row_ptr An array of length \p num_rows + 1.
876/// \param [in] col_ind An array containing the column indices in index-based
877/// numbering.
878/// \param [in, out] b The RHS matrix. It will be overwritten by the X.
879/// \param [in] ldb The leading dimension of B and X.
880/// \param [in] optimize_info The result of the optimizations.
881template <typename T>
882void csrsm(sycl::queue &queue, oneapi::mkl::transpose transa,
883           oneapi::mkl::transpose transb, int row_col, int nrhs, const T *alpha,
884           const std::shared_ptr<matrix_info> info, const T *val,
885           const int *row_ptr, const int *col_ind, T *b, int ldb,
886           std::shared_ptr<optimize_info> optimize_info) {
887  detail::csrsm_impl<T>()(queue, transa, transb, row_col, nrhs, alpha, info,
888                          val, row_ptr, col_ind, b, ldb, optimize_info);
889}
890
891/// Computes a sparse matrix-dense vector product: y = alpha * op(a) * x + beta * y.
892/// \param [in] queue The queue where the routine should be executed. It must
893/// have the in_order property when using the USM mode.
894/// \param [in] trans Specifies operation on input matrix.
895/// \param [in] alpha Specifies the scalar alpha.
896/// \param [in] a Specifies the sparse matrix a.
897/// \param [in] x Specifies the dense vector x.
898/// \param [in] beta Specifies the scalar beta.
899/// \param [in, out] y Specifies the dense vector y.
900/// \param [in] data_type Specifies the data type of \param a, \param x and \param y .
901inline void spmv(sycl::queue queue, oneapi::mkl::transpose trans,
902                 const void *alpha, sparse_matrix_desc_t a,
903                 std::shared_ptr<dense_vector_desc> x, const void *beta,
904                 std::shared_ptr<dense_vector_desc> y,
905                 library_data_t data_type) {
906  detail::spblas_shim<detail::spmv_impl>(data_type, queue, trans, alpha, a, x,
907                                         beta, y);
908}
909
910/// Computes a sparse matrix-dense matrix product: c = alpha * op(a) * op(b) + beta * c.
911/// \param [in] queue The queue where the routine should be executed. It must
912/// have the in_order property when using the USM mode.
913/// \param [in] trans_a Specifies operation on input matrix a.
914/// \param [in] trans_b Specifies operation on input matrix b.
915/// \param [in] alpha Specifies the scalar alpha.
916/// \param [in] a Specifies the sparse matrix a.
917/// \param [in] b Specifies the dense matrix b.
918/// \param [in] beta Specifies the scalar beta.
919/// \param [in, out] c Specifies the dense matrix c.
920/// \param [in] data_type Specifies the data type of \param a, \param b and \param c .
921inline void spmm(sycl::queue queue, oneapi::mkl::transpose trans_a,
922                 oneapi::mkl::transpose trans_b, const void *alpha,
923                 sparse_matrix_desc_t a, std::shared_ptr<dense_matrix_desc> b,
924                 const void *beta, std::shared_ptr<dense_matrix_desc> c,
925                 library_data_t data_type) {
926  if (b->get_layout() != c->get_layout())
927    throw std::runtime_error("the layout of b and c are different");
928  detail::spblas_shim<detail::spmm_impl>(data_type, queue, trans_a, trans_b,
929                                         alpha, a, b, beta, c);
930}
931
932/// Do initial estimation of work and load balancing of computing a sparse
933/// matrix-sparse matrix product.
934/// \param [in] queue The queue where the routine should be executed. It must
935/// have the in_order property when using the USM mode.
936/// \param [in] trans_a Specifies operation on input matrix a.
937/// \param [in] trans_b Specifies operation on input matrix b.
938/// \param [in] alpha Specifies the scalar alpha.
939/// \param [in] a Specifies the sparse matrix a.
940/// \param [in] b Specifies the sparse matrix b.
941/// \param [in] beta Specifies the scalar beta.
942/// \param [in, out] c Specifies the sparse matrix c.
943/// \param [in] matmat_descr Describes the sparse matrix-sparse matrix operation
944/// to be executed.
945/// \param [in, out] size_temp_buffer Specifies the size of workspace.
946/// \param [in] temp_buffer Specifies the memory of the workspace.
947inline void
948spgemm_work_estimation(sycl::queue queue, oneapi::mkl::transpose trans_a,
949                       oneapi::mkl::transpose trans_b, const void *alpha,
950                       sparse_matrix_desc_t a, sparse_matrix_desc_t b,
951                       const void *beta, sparse_matrix_desc_t c,
952                       oneapi::mkl::sparse::matmat_descr_t matmat_descr,
953                       size_t *size_temp_buffer, void *temp_buffer) {
954  if (temp_buffer) {
955    detail::temp_memory<std::int64_t, true, size_t> size_memory(
956        queue, size_temp_buffer);
957    detail::temp_memory<std::uint8_t, false> work_memory(queue, temp_buffer);
958    oneapi::mkl::sparse::matmat(
959        queue, a->get_matrix_handle(), b->get_matrix_handle(),
960        c->get_matrix_handle(),
961        oneapi::mkl::sparse::matmat_request::work_estimation, matmat_descr,
962        size_memory.get_memory_ptr(), work_memory.get_memory_ptr()
963#ifndef DPCT_USM_LEVEL_NONE
964        , {}
965#endif
966    );
967  } else {
968    oneapi::mkl::sparse::set_matmat_data(
969        matmat_descr, oneapi::mkl::sparse::matrix_view_descr::general, trans_a,
970        oneapi::mkl::sparse::matrix_view_descr::general, trans_b,
971        oneapi::mkl::sparse::matrix_view_descr::general);
972    detail::temp_memory<std::int64_t, true, size_t> size_memory(
973        queue, size_temp_buffer);
974    oneapi::mkl::sparse::matmat(
975        queue, a->get_matrix_handle(), b->get_matrix_handle(),
976        c->get_matrix_handle(),
977        oneapi::mkl::sparse::matmat_request::get_work_estimation_buf_size,
978        matmat_descr, size_memory.get_memory_ptr(), nullptr
979#ifndef DPCT_USM_LEVEL_NONE
980        , {}
981#endif
982    );
983  }
984}
985
986/// Do internal products for computing the C matrix of computing a sparse
987/// matrix-sparse matrix product.
988/// \param [in] queue The queue where the routine should be executed. It must
989/// have the in_order property when using the USM mode.
990/// \param [in] trans_a Specifies operation on input matrix a.
991/// \param [in] trans_b Specifies operation on input matrix b.
992/// \param [in] alpha Specifies the scalar alpha.
993/// \param [in] a Specifies the sparse matrix a.
994/// \param [in] b Specifies the sparse matrix b.
995/// \param [in] beta Specifies the scalar beta.
996/// \param [in, out] c Specifies the sparse matrix c.
997/// \param [in] matmat_descr Describes the sparse matrix-sparse matrix operation
998/// to be executed.
999/// \param [in, out] size_temp_buffer Specifies the size of workspace.
1000/// \param [in] temp_buffer Specifies the memory of the workspace.
1001inline void spgemm_compute(sycl::queue queue, oneapi::mkl::transpose trans_a,
1002                           oneapi::mkl::transpose trans_b, const void *alpha,
1003                           sparse_matrix_desc_t a, sparse_matrix_desc_t b,
1004                           const void *beta, sparse_matrix_desc_t c,
1005                           oneapi::mkl::sparse::matmat_descr_t matmat_descr,
1006                           size_t *size_temp_buffer, void *temp_buffer) {
1007  if (temp_buffer) {
1008    std::int64_t nnz_value = 0;
1009    {
1010      detail::temp_memory<std::int64_t, true, size_t> size_memory(
1011          queue, size_temp_buffer);
1012      detail::temp_memory<std::uint8_t, false> work_memory(queue, temp_buffer);
1013      detail::temp_memory<std::int64_t, true, std::int64_t> nnz_memory(
1014          queue, &nnz_value);
1015      oneapi::mkl::sparse::matmat(
1016          queue, a->get_matrix_handle(), b->get_matrix_handle(),
1017          c->get_matrix_handle(), oneapi::mkl::sparse::matmat_request::compute,
1018          matmat_descr, size_memory.get_memory_ptr(),
1019          work_memory.get_memory_ptr()
1020#ifndef DPCT_USM_LEVEL_NONE
1021          , {}
1022#endif
1023      );
1024      oneapi::mkl::sparse::matmat(
1025          queue, a->get_matrix_handle(), b->get_matrix_handle(),
1026          c->get_matrix_handle(), oneapi::mkl::sparse::matmat_request::get_nnz,
1027          matmat_descr, nnz_memory.get_memory_ptr(), nullptr
1028#ifndef DPCT_USM_LEVEL_NONE
1029          , {}
1030#endif
1031      );
1032    }
1033    c->set_nnz(nnz_value);
1034  } else {
1035    detail::temp_memory<std::int64_t, true, size_t> size_memory(
1036        queue, size_temp_buffer);
1037    oneapi::mkl::sparse::matmat(
1038        queue, a->get_matrix_handle(), b->get_matrix_handle(),
1039        c->get_matrix_handle(),
1040        oneapi::mkl::sparse::matmat_request::get_compute_buf_size, matmat_descr,
1041        size_memory.get_memory_ptr(), nullptr
1042#ifndef DPCT_USM_LEVEL_NONE
1043        , {}
1044#endif
1045    );
1046  }
1047}
1048
1049/// Do any remaining internal products and accumulation and transfer into final
1050/// C matrix arrays of computing a sparse matrix-sparse matrix product.
1051/// \param [in] queue The queue where the routine should be executed. It must
1052/// have the in_order property when using the USM mode.
1053/// \param [in] trans_a Specifies operation on input matrix a.
1054/// \param [in] trans_b Specifies operation on input matrix b.
1055/// \param [in] alpha Specifies the scalar alpha.
1056/// \param [in] a Specifies the sparse matrix a.
1057/// \param [in] b Specifies the sparse matrix b.
1058/// \param [in] beta Specifies the scalar beta.
1059/// \param [in, out] c Specifies the sparse matrix c.
1060/// \param [in] matmat_descr Describes the sparse matrix-sparse matrix operation
1061/// to be executed.
1062inline void spgemm_finalize(sycl::queue queue, oneapi::mkl::transpose trans_a,
1063                            oneapi::mkl::transpose trans_b, const void *alpha,
1064                            sparse_matrix_desc_t a, sparse_matrix_desc_t b,
1065                            const void *beta, sparse_matrix_desc_t c,
1066                            oneapi::mkl::sparse::matmat_descr_t matmat_descr) {
1067  oneapi::mkl::sparse::matmat(queue, a->get_matrix_handle(),
1068                              b->get_matrix_handle(), c->get_matrix_handle(),
1069                              oneapi::mkl::sparse::matmat_request::finalize,
1070                              matmat_descr, nullptr, nullptr
1071#ifdef DPCT_USM_LEVEL_NONE
1072  );
1073#else
1074  , {}).wait();
1075#endif
1076  if (c->get_shadow_row_ptr()) {
1077    switch (c->get_col_ind_type()) {
1078    case library_data_t::real_int32: {
1079      ::dpct::cs::memcpy(::dpct::cs::get_default_queue(), c->get_row_ptr(),
1080                         c->get_shadow_row_ptr(),
1081                         sizeof(std::int32_t) * (c->get_row_num() + 1))
1082          .wait();
1083      break;
1084    }
1085    case library_data_t::real_int64: {
1086      ::dpct::cs::memcpy(::dpct::cs::get_default_queue(), c->get_row_ptr(),
1087                         c->get_shadow_row_ptr(),
1088                         sizeof(std::int64_t) * (c->get_row_num() + 1))
1089          .wait();
1090      break;
1091    }
1092    default:
1093      throw std::runtime_error("dpct::sparse::spgemm_finalize(): The data type "
1094                               "of the col_ind in matrix c is unsupported.");
1095    }
1096  }
1097}
1098
1099/// Performs internal optimizations for spsv by analyzing the provided matrix
1100/// structure and operation parameters.
1101/// \param [in] queue The queue where the routine should be executed. It must
1102/// have the in_order property when using the USM mode.
1103/// \param [in] trans_a Specifies operation on input matrix a.
1104/// \param [in] a Specifies the sparse matrix a.
1105inline void spsv_optimize(sycl::queue queue, oneapi::mkl::transpose trans_a,
1106                          sparse_matrix_desc_t a) {
1107  if (!a->get_uplo() || !a->get_diag()) {
1108    throw std::runtime_error(
1109        "dpct::sparse::spsv_optimize(): oneapi::mkl::sparse::optimize_trsv "
1110        "needs uplo and diag attributes to be specified.");
1111  }
1112  oneapi::mkl::sparse::optimize_trsv(
1113      queue, a->get_uplo().value(), oneapi::mkl::transpose::nontrans,
1114      a->get_diag().value(), a->get_matrix_handle());
1115}
1116
1117/// Solves a system of linear equations for a sparse matrix.
1118/// \param [in] queue The queue where the routine should be executed. It must
1119/// have the in_order property when using the USM mode.
1120/// \param [in] trans_a Specifies operation on input matrix a.
1121/// \param [in] alpha Specifies the scalar alpha.
1122/// \param [in] a Specifies the sparse matrix a.
1123/// \param [in] x Specifies the dense vector x.
1124/// \param [in, out] y Specifies the dense vector y.
1125/// \param [in] data_type Specifies the data type of \param a, \param x and
1126/// \param y .
1127inline void spsv(sycl::queue queue, oneapi::mkl::transpose trans_a,
1128                 const void *alpha, sparse_matrix_desc_t a,
1129                 std::shared_ptr<dense_vector_desc> x,
1130                 std::shared_ptr<dense_vector_desc> y,
1131                 library_data_t data_type) {
1132  if (!a->get_uplo() || !a->get_diag()) {
1133    throw std::runtime_error(
1134        "dpct::sparse::spsv(): oneapi::mkl::sparse::trsv needs uplo and diag "
1135        "attributes to be specified.");
1136  }
1137  oneapi::mkl::uplo uplo = a->get_uplo().value();
1138  oneapi::mkl::diag diag = a->get_diag().value();
1139  detail::spblas_shim<detail::spsv_impl>(a->get_value_type(), queue, uplo, diag,
1140                                         trans_a, alpha, a, x, y);
1141}
1142
1143/// Performs internal optimizations for spsm by analyzing the provided matrix
1144/// structure and operation parameters.
1145/// \param [in] queue The queue where the routine should be executed. It must
1146/// have the in_order property when using the USM mode.
1147/// \param [in] trans_a Specifies operation on input matrix a.
1148/// \param [in] a Specifies the sparse matrix a.
1149/// \param [in] a Specifies the dense matrix b.
1150/// \param [in] a Specifies the dense matrix c.
1151inline void spsm_optimize(sycl::queue queue, oneapi::mkl::transpose trans_a,
1152                          sparse_matrix_desc_t a,
1153                          std::shared_ptr<dense_matrix_desc> b,
1154                          std::shared_ptr<dense_matrix_desc> c) {
1155  if (!a->get_uplo() || !a->get_diag()) {
1156    throw std::runtime_error(
1157        "dpct::sparse::spsm_optimize(): oneapi::mkl::sparse::optimize_trsm "
1158        "needs uplo and diag attributes to be specified.");
1159  }
1160  oneapi::mkl::sparse::optimize_trsm(
1161      queue, b->get_layout(), a->get_uplo().value(), trans_a,
1162      a->get_diag().value(), a->get_matrix_handle(), c->get_col_num());
1163}
1164
1165/// Solves a system of linear equations with multiple right-hand sides (RHS)
1166/// for a triangular sparse matrix.
1167/// \param [in] queue The queue where the routine should be executed. It must
1168/// have the in_order property when using the USM mode.
1169/// \param [in] trans_a Specifies operation on input matrix a.
1170/// \param [in] trans_b Specifies operation on input matrix b.
1171/// \param [in] alpha Specifies the scalar alpha.
1172/// \param [in] a Specifies the sparse matrix a.
1173/// \param [in] b Specifies the dense matrix b.
1174/// \param [in, out] c Specifies the dense matrix c.
1175/// \param [in] data_type Specifies the data type of \param a, \param b and
1176/// \param c .
1177inline void spsm(sycl::queue queue, oneapi::mkl::transpose trans_a,
1178                 oneapi::mkl::transpose trans_b, const void *alpha,
1179                 sparse_matrix_desc_t a, std::shared_ptr<dense_matrix_desc> b,
1180                 std::shared_ptr<dense_matrix_desc> c,
1181                 library_data_t data_type) {
1182  if (!a->get_uplo() || !a->get_diag()) {
1183    throw std::runtime_error(
1184        "dpct::sparse::spsm(): oneapi::mkl::sparse::trsm needs uplo and diag "
1185        "attributes to be specified.");
1186  }
1187  oneapi::mkl::uplo uplo = a->get_uplo().value();
1188  oneapi::mkl::diag diag = a->get_diag().value();
1189  detail::spblas_shim<detail::spsm_impl>(data_type, queue, trans_a, trans_b,
1190                                         uplo, diag, alpha, a, b, c);
1191}
1192
1193/// Convert a CSR sparse matrix to a CSC sparse matrix.
1194/// \param [in] queue The queue where the routine should be executed. It must
1195/// have the in_order property when using the USM mode.
1196/// \param [in] m Number of rows of the matrix.
1197/// \param [in] n Number of columns of the matrix.
1198/// \param [in] nnz Number of non-zero elements.
1199/// \param [in] from_val An array containing the non-zero elements of the input
1200/// matrix.
1201/// \param [in] from_row_ptr An array of length \p m + 1.
1202/// \param [in] from_col_ind An array containing the column indices in
1203/// index-based numbering.
1204/// \param [out] to_val An array containing the non-zero elements of the output
1205/// matrix.
1206/// \param [out] to_col_ptr An array of length \p n + 1.
1207/// \param [out] to_row_ind An array containing the row indices in index-based
1208/// numbering.
1209/// \param [in] range Specifies the conversion scope.
1210/// \param [in] base Specifies the index base.
1211template <typename T>
1212inline void csr2csc(sycl::queue queue, int m, int n, int nnz, const T *from_val,
1213                    const int *from_row_ptr, const int *from_col_ind, T *to_val,
1214                    int *to_col_ptr, int *to_row_ind, conversion_scope range,
1215                    oneapi::mkl::index_base base) {
1216  detail::csr2csc_impl<T>()(queue, m, n, nnz, from_val, from_row_ptr,
1217                            from_col_ind, to_val, to_col_ptr, to_row_ind, range,
1218                            base);
1219}
1220
1221/// Convert a CSR sparse matrix to a CSC sparse matrix.
1222/// \param [in] queue The queue where the routine should be executed. It must
1223/// have the in_order property when using the USM mode.
1224/// \param [in] m Number of rows of the matrix.
1225/// \param [in] n Number of columns of the matrix.
1226/// \param [in] nnz Number of non-zero elements.
1227/// \param [in] from_val An array containing the non-zero elements of the input
1228/// matrix.
1229/// \param [in] from_row_ptr An array of length \p m + 1.
1230/// \param [in] from_col_ind An array containing the column indices in
1231/// index-based numbering.
1232/// \param [out] to_val An array containing the non-zero elements of the output
1233/// matrix.
1234/// \param [out] to_col_ptr An array of length \p n + 1.
1235/// \param [out] to_row_ind An array containing the row indices in index-based
1236/// numbering.
1237/// \param [in] value_type Data type of \p from_val and \p to_val .
1238/// \param [in] range Specifies the conversion scope.
1239/// \param [in] base Specifies the index base.
1240inline void csr2csc(sycl::queue queue, int m, int n, int nnz,
1241                    const void *from_val, const int *from_row_ptr,
1242                    const int *from_col_ind, void *to_val, int *to_col_ptr,
1243                    int *to_row_ind, library_data_t value_type,
1244                    conversion_scope range, oneapi::mkl::index_base base) {
1245  detail::spblas_shim<detail::csr2csc_impl>(
1246      value_type, queue, m, n, nnz, from_val, from_row_ptr, from_col_ind,
1247      to_val, to_col_ptr, to_row_ind, range, base);
1248}
1249
1250/// Calculate the non-zero elements number of the result of a
1251/// sparse matrix (CSR format)-sparse matrix (CSR format) product:
1252/// C = op(A) * op(B)
1253/// \param [in] desc The descriptor of this calculation.
1254/// \param [in] trans_a The operation applied to the matrix A.
1255/// \param [in] trans_b The operation applied to the matrix B.
1256/// \param [in] m The rows number of op(A) and C.
1257/// \param [in] n The columns number of op(B) and C.
1258/// \param [in] k The columns number of op(A) and rows number of op(B).
1259/// \param [in] info_a Matrix info of the matrix A.
1260/// \param [in] nnz_a Non-zero elements number of matrix A.
1261/// \param [in] val_a An array containing the non-zero elements of the matrix A.
1262/// \param [in] row_ptr_a An array of length row number + 1.
1263/// \param [in] col_ind_a An array containing the column indices in index-based
1264/// numbering.
1265/// \param [in] info_b Matrix info of the matrix B.
1266/// \param [in] nnz_b Non-zero elements number of matrix B.
1267/// \param [in] val_b An array containing the non-zero elements of the matrix B.
1268/// \param [in] row_ptr_b An array of length row number + 1.
1269/// \param [in] col_ind_b An array containing the column indices in index-based
1270/// numbering.
1271/// \param [in] info_c Matrix info of the matrix C.
1272/// \param [in] row_ptr_c An array of length row number + 1.
1273/// \param [out] nnz_host_ptr Non-zero elements number of matrix C.
1274template <typename T>
1275void csrgemm_nnz(descriptor_ptr desc, oneapi::mkl::transpose trans_a,
1276                 oneapi::mkl::transpose trans_b, int m, int n, int k,
1277                 const std::shared_ptr<matrix_info> info_a, int nnz_a,
1278                 const T *val_a, const int *row_ptr_a, const int *col_ind_a,
1279                 const std::shared_ptr<matrix_info> info_b, int nnz_b,
1280                 const T *val_b, const int *row_ptr_b, const int *col_ind_b,
1281                 const std::shared_ptr<matrix_info> info_c, int *row_ptr_c,
1282                 int *nnz_host_ptr) {
1283  using Ty = typename ::dpct::detail::lib_data_traits_t<T>;
1284  sycl::queue &queue = desc->get_queue();
1285  detail::csrgemm_args_info args(trans_a, trans_b, m, n, k, info_a, val_a,
1286                                 row_ptr_a, col_ind_a, info_b, val_b, row_ptr_b,
1287                                 col_ind_b, info_c, row_ptr_c);
1288  auto &info = desc->get_csrgemm_info_map()[args];
1289
1290  if (info.is_empty()) {
1291    info.init(&queue);
1292
1293    int rows_c = m;
1294    int cols_c = n;
1295    int rows_a = (trans_a == oneapi::mkl::transpose::nontrans) ? m : k;
1296    int cols_a = (trans_a == oneapi::mkl::transpose::nontrans) ? k : m;
1297    int rows_b = (trans_b == oneapi::mkl::transpose::nontrans) ? k : n;
1298    int cols_b = (trans_b == oneapi::mkl::transpose::nontrans) ? n : k;
1299
1300    info.matrix_handle_a.set_matrix_data<Ty>(
1301        rows_a, cols_a, info_a->get_index_base(), row_ptr_a, col_ind_a, val_a);
1302    info.matrix_handle_b.set_matrix_data<Ty>(
1303        rows_b, cols_b, info_b->get_index_base(), row_ptr_b, col_ind_b, val_b);
1304    // In the future, oneMKL will allow nullptr to be passed in for row_ptr_c in
1305    // the initial calls before matmat. But currently, it needs an array of
1306    // length row_number + 1.
1307    info.matrix_handle_c.set_matrix_data<Ty>(
1308        rows_c, cols_c, info_c->get_index_base(), row_ptr_c, nullptr, nullptr);
1309
1310    oneapi::mkl::sparse::set_matmat_data(
1311        info.matmat_desc.get_handle(),
1312        oneapi::mkl::sparse::matrix_view_descr::general, trans_a,
1313        oneapi::mkl::sparse::matrix_view_descr::general, trans_b,
1314        oneapi::mkl::sparse::matrix_view_descr::general);
1315  }
1316
1317#ifdef DPCT_USM_LEVEL_NONE
1318#define __MATMAT(STEP, NNZ_C)                                                  \
1319  oneapi::mkl::sparse::matmat(queue, info.matrix_handle_a.get_handle(),        \
1320                              info.matrix_handle_b.get_handle(),               \
1321                              info.matrix_handle_c.get_handle(), STEP,         \
1322                              info.matmat_desc.get_handle(), NNZ_C, nullptr)
1323#else
1324#define __MATMAT(STEP, NNZ_C)                                                  \
1325  oneapi::mkl::sparse::matmat(                                                 \
1326      queue, info.matrix_handle_a.get_handle(),                                \
1327      info.matrix_handle_b.get_handle(), info.matrix_handle_c.get_handle(),    \
1328      STEP, info.matmat_desc.get_handle(), NNZ_C, nullptr, {})
1329#endif
1330
1331  __MATMAT(oneapi::mkl::sparse::matmat_request::work_estimation, nullptr);
1332  queue.wait();
1333
1334  __MATMAT(oneapi::mkl::sparse::matmat_request::compute, nullptr);
1335
1336  int nnz_c_int = 0;
1337#ifdef DPCT_USM_LEVEL_NONE
1338  sycl::buffer<std::int64_t, 1> nnz_buf_c(1);
1339  __MATMAT(oneapi::mkl::sparse::matmat_request::get_nnz, &nnz_buf_c);
1340  nnz_c_int = nnz_buf_c.get_host_access(sycl::read_only)[0];
1341#else
1342  std::int64_t *nnz_c = sycl::malloc_host<std::int64_t>(1, queue);
1343  __MATMAT(oneapi::mkl::sparse::matmat_request::get_nnz, nnz_c);
1344  queue.wait();
1345  nnz_c_int = *nnz_c;
1346#endif
1347
1348  if (nnz_host_ptr) {
1349    *nnz_host_ptr = nnz_c_int;
1350  }
1351}
1352
1353/// Computes a sparse matrix (CSR format)-sparse matrix (CSR format) product:
1354/// C = op(A) * op(B)
1355/// \param [in] desc The descriptor of this calculation.
1356/// \param [in] trans_a The operation applied to the matrix A.
1357/// \param [in] trans_b The operation applied to the matrix B.
1358/// \param [in] m The rows number of op(A) and C.
1359/// \param [in] n The columns number of op(B) and C.
1360/// \param [in] k The columns number of op(A) and rows number of op(B).
1361/// \param [in] info_a Matrix info of the matrix A.
1362/// \param [in] val_a An array containing the non-zero elements of the matrix A.
1363/// \param [in] row_ptr_a An array of length row number + 1.
1364/// \param [in] col_ind_a An array containing the column indices in index-based
1365/// numbering.
1366/// \param [in] info_b Matrix info of the matrix B.
1367/// \param [in] val_b An array containing the non-zero elements of the matrix B.
1368/// \param [in] row_ptr_b An array of length row number + 1.
1369/// \param [in] col_ind_b An array containing the column indices in index-based
1370/// numbering.
1371/// \param [in] info_c Matrix info of the matrix C.
1372/// \param [out] val_c An array containing the non-zero elements of the matrix
1373/// C.
1374/// \param [in] row_ptr_c An array of length row number + 1.
1375/// \param [out] col_ind_c An array containing the column indices in index-based
1376/// numbering.
1377template <typename T>
1378void csrgemm(descriptor_ptr desc, oneapi::mkl::transpose trans_a,
1379             oneapi::mkl::transpose trans_b, int m, int n, int k,
1380             const std::shared_ptr<matrix_info> info_a, const T *val_a,
1381             const int *row_ptr_a, const int *col_ind_a,
1382             const std::shared_ptr<matrix_info> info_b, const T *val_b,
1383             const int *row_ptr_b, const int *col_ind_b,
1384             const std::shared_ptr<matrix_info> info_c, T *val_c,
1385             const int *row_ptr_c, int *col_ind_c) {
1386  using Ty = typename ::dpct::detail::lib_data_traits_t<T>;
1387  sycl::queue &queue = desc->get_queue();
1388  detail::csrgemm_args_info args(trans_a, trans_b, m, n, k, info_a, val_a,
1389                                 row_ptr_a, col_ind_a, info_b, val_b, row_ptr_b,
1390                                 col_ind_b, info_c, row_ptr_c);
1391  auto &info = desc->get_csrgemm_info_map()[args];
1392  if (info.is_empty()) {
1393    throw std::runtime_error("csrgemm_nnz is not invoked previously.");
1394  }
1395
1396  int rows_c = m;
1397  int cols_c = n;
1398  info.matrix_handle_c.set_matrix_data<Ty>(
1399      rows_c, cols_c, info_c->get_index_base(), row_ptr_c, col_ind_c, val_c);
1400  sycl::event e;
1401#ifndef DPCT_USM_LEVEL_NONE
1402  e =
1403#endif
1404      __MATMAT(oneapi::mkl::sparse::matmat_request::finalize, nullptr);
1405#undef __MATMAT
1406
1407  info.matrix_handle_a.add_dependency(e);
1408  info.matrix_handle_b.add_dependency(e);
1409  info.matrix_handle_c.add_dependency(e);
1410  info.matmat_desc.add_dependency(e);
1411  desc->get_csrgemm_info_map().erase(args);
1412}
1413
1414/// Contains internal information for csrgemm2 by analyzing the provided
1415/// matrix structure and operation parameters.
1416class csrgemm2_info {
1417  detail::matrix_handle_manager matrix_handle_a;
1418  detail::matrix_handle_manager matrix_handle_b;
1419  detail::matrix_handle_manager matrix_handle_axb;
1420  detail::matrix_handle_manager matrix_handle_d;
1421  detail::matrix_handle_manager matrix_handle_c;
1422  detail::handle_manager<oneapi::mkl::sparse::matmat_descr_t> matmat_desc;
1423  detail::handle_manager<oneapi::mkl::sparse::omatadd_descr_t> omatadd_desc;
1424  void *row_ptr_axb = nullptr;
1425  void *col_ind_axb = nullptr;
1426  void *val_axb = nullptr;
1427#ifdef DPCT_USM_LEVEL_NONE
1428  sycl::buffer<std::int64_t, 1> *temp_buffer_1_size;
1429  sycl::buffer<std::int64_t, 1> *temp_buffer_2_size;
1430  sycl::buffer<std::uint8_t, 1> *temp_buffer_1;
1431  sycl::buffer<std::uint8_t, 1> *temp_buffer_2;
1432#else
1433  std::int64_t *temp_buffer_1_size;
1434  std::int64_t *temp_buffer_2_size;
1435  std::uint8_t *temp_buffer_1;
1436  std::uint8_t *temp_buffer_2;
1437#endif
1438  enum matrix_c_datatype_t {
1439    mcd_float,
1440    mcd_double,
1441    mcd_float2,
1442    mcd_double2,
1443  };
1444  template <typename T> void set_matrix_c_datatype() {
1445    if constexpr (std::is_same_v<T, float>) {
1446      matrix_c_datatype = matrix_c_datatype_t::mcd_float;
1447    } else if constexpr (std::is_same_v<T, double>) {
1448      matrix_c_datatype = matrix_c_datatype_t::mcd_double;
1449    } else if constexpr (std::is_same_v<T, std::complex<float>>) {
1450      matrix_c_datatype = matrix_c_datatype_t::mcd_float2;
1451    } else {
1452      matrix_c_datatype = matrix_c_datatype_t::mcd_double2;
1453    }
1454  }
1455  matrix_c_datatype_t matrix_c_datatype;
1456  void init(sycl::queue *q_ptr) {
1457    matrix_handle_a.init(q_ptr);
1458    matrix_handle_b.init(q_ptr);
1459    matrix_handle_axb.init(q_ptr);
1460    matrix_handle_d.init(q_ptr);
1461    matrix_handle_c.init(q_ptr);
1462    matmat_desc.init(q_ptr);
1463    omatadd_desc.init(q_ptr);
1464  }
1465  sycl::event release(sycl::queue q, sycl::event dep) {
1466    matrix_handle_a.add_dependency(dep);
1467    matrix_handle_b.add_dependency(dep);
1468    matrix_handle_axb.add_dependency(dep);
1469    matrix_handle_d.add_dependency(dep);
1470    matrix_handle_c.add_dependency(dep);
1471    matmat_desc.add_dependency(dep);
1472    omatadd_desc.add_dependency(dep);
1473    std::vector<sycl::event> events;
1474    events.push_back(matrix_handle_a.release());
1475    events.push_back(matrix_handle_b.release());
1476    events.push_back(matrix_handle_axb.release());
1477    events.push_back(matrix_handle_d.release());
1478    events.push_back(matrix_handle_c.release());
1479    events.push_back(matmat_desc.release());
1480    events.push_back(omatadd_desc.release());
1481    return q.single_task(events, [] {});
1482  }
1483  template <typename T>
1484  friend void csrgemm2_get_buffer_size(
1485      descriptor_ptr desc, int m, int n, int k, const T *alpha,
1486      const std::shared_ptr<matrix_info> info_a, int nnz_a,
1487      const int *row_ptr_a, const int *col_ind_a,
1488      const std::shared_ptr<matrix_info> info_b, int nnz_b,
1489      const int *row_ptr_b, const int *col_ind_b, const T *beta,
1490      const std::shared_ptr<matrix_info> info_d, int nnz_d,
1491      const int *row_ptr_d, const int *col_ind_d,
1492      std::shared_ptr<csrgemm2_info> info, size_t *buffer_size_in_bytes);
1493  friend void csrgemm2_nnz(descriptor_ptr desc, int m, int n, int k,
1494                           const std::shared_ptr<matrix_info> info_a, int nnz_a,
1495                           const int *row_ptr_a, const int *col_ind_a,
1496                           const std::shared_ptr<matrix_info> info_b, int nnz_b,
1497                           const int *row_ptr_b, const int *col_ind_b,
1498                           const std::shared_ptr<matrix_info> info_d, int nnz_d,
1499                           const int *row_ptr_d, const int *col_ind_d,
1500                           const std::shared_ptr<matrix_info> info_c,
1501                           int *row_ptr_c, int *nnz_ptr,
1502                           std::shared_ptr<csrgemm2_info> info, void *buffer);
1503  template <typename T>
1504  friend void
1505  csrgemm2(descriptor_ptr desc, int m, int n, int k, const T *alpha,
1506           const std::shared_ptr<matrix_info> info_a, int nnz_a, const T *val_a,
1507           const int *row_ptr_a, const int *col_ind_a,
1508           const std::shared_ptr<matrix_info> info_b, int nnz_b, const T *val_b,
1509           const int *row_ptr_b, const int *col_ind_b, const T *beta,
1510           const std::shared_ptr<matrix_info> info_d, int nnz_d, const T *val_d,
1511           const int *row_ptr_d, const int *col_ind_d,
1512           const std::shared_ptr<matrix_info> info_c, T *val_c,
1513           const int *row_ptr_c, int *col_ind_c,
1514           std::shared_ptr<csrgemm2_info> info, void *buffer);
1515};
1516
1517/// Calculate the required workspace size of the following operation:
1518/// C = alpha * A * B + beta * D
1519/// \param [in] desc The descriptor of this calculation.
1520/// \param [in] m The rows number of A, D and C.
1521/// \param [in] n The columns number of B, D and C.
1522/// \param [in] k The columns number of A and rows number of B.
1523/// \param [in] alpha Scaling factor.
1524/// \param [in] info_a Matrix info of the matrix A.
1525/// \param [in] nnz_a Non-zero elements number of matrix A.
1526/// \param [in] row_ptr_a An array of length \p m + 1.
1527/// \param [in] col_ind_a An array containing the column indices in index-based
1528/// numbering.
1529/// \param [in] info_b Matrix info of the matrix B.
1530/// \param [in] nnz_b Non-zero elements number of matrix B.
1531/// \param [in] row_ptr_b An array of length \p k + 1.
1532/// \param [in] col_ind_b An array containing the column indices in index-based
1533/// numbering.
1534/// \param [in] beta Scaling factor.
1535/// \param [in] info_d Matrix info of the matrix D.
1536/// \param [in] nnz_d Non-zero elements number of matrix D.
1537/// \param [in] row_ptr_d An array of length \p m + 1.
1538/// \param [in] col_ind_d An array containing the column indices in index-based
1539/// numbering.
1540/// \param [in, out] info The information of csrgemm2 operation.
1541/// \param [out] buffer_size_in_bytes Workspace memory size in bytes.
1542template <typename T>
1543void csrgemm2_get_buffer_size(
1544    descriptor_ptr desc, int m, int n, int k, const T *alpha,
1545    const std::shared_ptr<matrix_info> info_a, int nnz_a, const int *row_ptr_a,
1546    const int *col_ind_a, const std::shared_ptr<matrix_info> info_b, int nnz_b,
1547    const int *row_ptr_b, const int *col_ind_b, const T *beta,
1548    const std::shared_ptr<matrix_info> info_d, int nnz_d, const int *row_ptr_d,
1549    const int *col_ind_d, std::shared_ptr<csrgemm2_info> info,
1550    size_t *buffer_size_in_bytes) {
1551  using Ty = typename ::dpct::detail::lib_data_traits_t<T>;
1552  sycl::queue &queue = desc->get_queue();
1553  info->set_matrix_c_datatype<Ty>();
1554
1555  info->row_ptr_axb = (int *)::dpct::cs::malloc((m + 1) * sizeof(int), queue);
1556  info->init(&queue);
1557
1558  info->matrix_handle_a.set_matrix_data<Ty>(m, k, info_a->get_index_base(),
1559                                            row_ptr_a, col_ind_a, nullptr);
1560  info->matrix_handle_b.set_matrix_data<Ty>(k, n, info_b->get_index_base(),
1561                                            row_ptr_b, col_ind_b, nullptr);
1562  info->matrix_handle_axb.set_matrix_data<Ty>(
1563      m, n, oneapi::mkl::index_base::zero, info->row_ptr_axb, nullptr, nullptr);
1564  info->matrix_handle_d.set_matrix_data<Ty>(m, n, info_d->get_index_base(),
1565                                            row_ptr_d, col_ind_d, nullptr);
1566  info->matrix_handle_c.set_matrix_data<Ty>(m, n, oneapi::mkl::index_base::zero,
1567                                            nullptr, nullptr, nullptr);
1568
1569  oneapi::mkl::sparse::set_matmat_data(
1570      info->matmat_desc.get_handle(),
1571      oneapi::mkl::sparse::matrix_view_descr::general,
1572      oneapi::mkl::transpose::nontrans,
1573      oneapi::mkl::sparse::matrix_view_descr::general,
1574      oneapi::mkl::transpose::nontrans,
1575      oneapi::mkl::sparse::matrix_view_descr::general);
1576
1577#ifdef DPCT_USM_LEVEL_NONE
1578#define __MATMAT(STEP, PTR1, PTR2)                                             \
1579  oneapi::mkl::sparse::matmat(queue, info->matrix_handle_a.get_handle(),       \
1580                              info->matrix_handle_b.get_handle(),              \
1581                              info->matrix_handle_axb.get_handle(),            \
1582                              oneapi::mkl::sparse::matmat_request::STEP,       \
1583                              info->matmat_desc.get_handle(), PTR1, PTR2)
1584#else
1585#define __MATMAT(STEP, PTR1, PTR2)                                             \
1586  oneapi::mkl::sparse::matmat(queue, info->matrix_handle_a.get_handle(),       \
1587                              info->matrix_handle_b.get_handle(),              \
1588                              info->matrix_handle_axb.get_handle(),            \
1589                              oneapi::mkl::sparse::matmat_request::STEP,       \
1590                              info->matmat_desc.get_handle(), PTR1, PTR2, {})
1591#endif
1592
1593  std::int64_t nnz_axb = 0;
1594#ifdef DPCT_USM_LEVEL_NONE
1595  info->temp_buffer_1_size = new sycl::buffer<std::int64_t, 1>(1);
1596  __MATMAT(get_work_estimation_buf_size, info->temp_buffer_1_size, nullptr);
1597  info->temp_buffer_1 = new sycl::buffer<std::uint8_t, 1>(
1598      info->temp_buffer_1_size->get_host_access(sycl::read_only)[0]);
1599  __MATMAT(work_estimation, info->temp_buffer_1_size, info->temp_buffer_1);
1600  info->temp_buffer_2_size = new sycl::buffer<std::int64_t, 1>(1);
1601  __MATMAT(get_compute_structure_buf_size, info->temp_buffer_2_size, nullptr);
1602  info->temp_buffer_2 = new sycl::buffer<std::uint8_t, 1>(
1603      info->temp_buffer_2_size->get_host_access(sycl::read_only)[0]);
1604  __MATMAT(compute_structure, info->temp_buffer_2_size, info->temp_buffer_2);
1605  sycl::buffer<std::int64_t, 1> nnz_axb_buf(1);
1606  __MATMAT(get_nnz, &nnz_axb_buf, nullptr);
1607  nnz_axb = nnz_axb_buf.get_host_access(sycl::read_only)[0];
1608#else
1609  info->temp_buffer_1_size = sycl::malloc_host<std::int64_t>(1, queue);
1610  __MATMAT(get_work_estimation_buf_size, info->temp_buffer_1_size, nullptr);
1611  queue.wait();
1612  info->temp_buffer_1 =
1613      sycl::malloc_device<std::uint8_t>(info->temp_buffer_1_size[0], queue);
1614  __MATMAT(work_estimation, info->temp_buffer_1_size, info->temp_buffer_1);
1615  info->temp_buffer_2_size = sycl::malloc_host<std::int64_t>(1, queue);
1616  __MATMAT(get_compute_structure_buf_size, info->temp_buffer_2_size, nullptr);
1617  queue.wait();
1618  info->temp_buffer_2 =
1619      sycl::malloc_device<std::uint8_t>(info->temp_buffer_2_size[0], queue);
1620  __MATMAT(compute_structure, info->temp_buffer_2_size, info->temp_buffer_2);
1621  std::int64_t *nnz_axb_ptr = sycl::malloc_host<std::int64_t>(1, queue);
1622  __MATMAT(get_nnz, nnz_axb_ptr, nullptr);
1623  queue.wait();
1624  nnz_axb = *nnz_axb_ptr;
1625  sycl::free(nnz_axb_ptr, queue);
1626#endif
1627
1628  info->col_ind_axb = (int *)::dpct::cs::malloc(nnz_axb * sizeof(int), queue);
1629  info->val_axb = (Ty *)::dpct::cs::malloc(nnz_axb * sizeof(Ty), queue);
1630  info->matrix_handle_axb.set_matrix_data<Ty>(
1631      m, n, oneapi::mkl::index_base::zero, info->row_ptr_axb, info->col_ind_axb,
1632      info->val_axb);
1633
1634  __MATMAT(finalize_structure, nullptr, nullptr);
1635
1636  std::int64_t ws_size = 0;
1637  oneapi::mkl::sparse::omatadd_buffer_size(
1638      queue, oneapi::mkl::transpose::nontrans, oneapi::mkl::transpose::nontrans,
1639      info->matrix_handle_axb.get_handle(), info->matrix_handle_d.get_handle(),
1640      info->matrix_handle_c.get_handle(),
1641      oneapi::mkl::sparse::omatadd_alg::default_alg,
1642      info->omatadd_desc.get_handle(), ws_size);
1643  *buffer_size_in_bytes = ws_size;
1644}
1645
1646/// Calculate the non-zero elements number of the matrix C in following operation:
1647/// C = alpha * A * B + beta * D
1648/// \param [in] desc The descriptor of this calculation.
1649/// \param [in] m The rows number of A, D and C.
1650/// \param [in] n The columns number of B, D and C.
1651/// \param [in] k The columns number of A and rows number of B.
1652/// \param [in] info_a Matrix info of the matrix A.
1653/// \param [in] nnz_a Non-zero elements number of matrix A.
1654/// \param [in] row_ptr_a An array of length \p m + 1.
1655/// \param [in] col_ind_a An array containing the column indices in index-based
1656/// numbering.
1657/// \param [in] info_b Matrix info of the matrix B.
1658/// \param [in] nnz_b Non-zero elements number of matrix B.
1659/// \param [in] row_ptr_b An array of length \p k + 1.
1660/// \param [in] col_ind_b An array containing the column indices in index-based
1661/// numbering.
1662/// \param [in] info_d Matrix info of the matrix D.
1663/// \param [in] nnz_d Non-zero elements number of matrix D.
1664/// \param [in] row_ptr_d An array of length \p m + 1.
1665/// \param [in] col_ind_d An array containing the column indices in index-based
1666/// numbering.
1667/// \param [in] info_c Matrix info of the matrix C.
1668/// \param [in] row_ptr_c An array of length \p m + 1.
1669/// \param [out] nnz_ptr Non-zero elements number of matrix C.
1670/// \param [in] info The information of csrgemm2 operation.
1671/// \param [in] buffer Workspace memory.
1672inline void csrgemm2_nnz(descriptor_ptr desc, int m, int n, int k,
1673                         const std::shared_ptr<matrix_info> info_a, int nnz_a,
1674                         const int *row_ptr_a, const int *col_ind_a,
1675                         const std::shared_ptr<matrix_info> info_b, int nnz_b,
1676                         const int *row_ptr_b, const int *col_ind_b,
1677                         const std::shared_ptr<matrix_info> info_d, int nnz_d,
1678                         const int *row_ptr_d, const int *col_ind_d,
1679                         const std::shared_ptr<matrix_info> info_c,
1680                         int *row_ptr_c, int *nnz_ptr,
1681                         std::shared_ptr<csrgemm2_info> info, void *buffer) {
1682  sycl::queue &queue = desc->get_queue();
1683  if (info->matrix_c_datatype ==
1684      csrgemm2_info::matrix_c_datatype_t::mcd_float) {
1685    info->matrix_handle_c.set_matrix_data<float>(m, n, info_c->get_index_base(),
1686                                                 nullptr, nullptr, nullptr);
1687  } else if (info->matrix_c_datatype ==
1688             csrgemm2_info::matrix_c_datatype_t::mcd_double) {
1689    info->matrix_handle_c.set_matrix_data<double>(
1690        m, n, info_c->get_index_base(), nullptr, nullptr, nullptr);
1691  } else if (info->matrix_c_datatype ==
1692             csrgemm2_info::matrix_c_datatype_t::mcd_float2) {
1693    info->matrix_handle_c.set_matrix_data<std::complex<float>>(
1694        m, n, info_c->get_index_base(), nullptr, nullptr, nullptr);
1695  } else {
1696    info->matrix_handle_c.set_matrix_data<std::complex<double>>(
1697        m, n, info_c->get_index_base(), nullptr, nullptr, nullptr);
1698  }
1699  auto data_buffer = dpct::detail::get_memory<std::uint8_t>(buffer);
1700  oneapi::mkl::sparse::omatadd_analyze(
1701      queue, oneapi::mkl::transpose::nontrans, oneapi::mkl::transpose::nontrans,
1702      info->matrix_handle_axb.get_handle(), info->matrix_handle_d.get_handle(),
1703      info->matrix_handle_c.get_handle(),
1704      oneapi::mkl::sparse::omatadd_alg::default_alg,
1705      info->omatadd_desc.get_handle(),
1706#ifdef DPCT_USM_LEVEL_NONE
1707      &data_buffer
1708#else
1709      data_buffer
1710#endif
1711  );
1712  std::int64_t nnz_c = 0;
1713  oneapi::mkl::sparse::omatadd_get_nnz(
1714      queue, oneapi::mkl::transpose::nontrans, oneapi::mkl::transpose::nontrans,
1715      info->matrix_handle_axb.get_handle(), info->matrix_handle_d.get_handle(),
1716      info->matrix_handle_c.get_handle(),
1717      oneapi::mkl::sparse::omatadd_alg::default_alg,
1718      info->omatadd_desc.get_handle(), nnz_c);
1719
1720  assert((nnz_c >= INT_MIN && nnz_c <= INT_MAX) && "nnz_c is out of range.");
1721  int nnz_c_int = nnz_c;
1722  if (nnz_ptr)
1723    ::dpct::cs::memcpy(queue, nnz_ptr, &nnz_c_int, sizeof(int)).wait();
1724  int row_ptr_c_0 =
1725      (info_c->get_index_base() == oneapi::mkl::index_base::zero) ? 0 : 1;
1726  nnz_c_int += row_ptr_c_0;
1727  ::dpct::cs::memcpy(queue, row_ptr_c + m, &nnz_c_int, sizeof(int));
1728  ::dpct::cs::memcpy(queue, row_ptr_c, &row_ptr_c_0, sizeof(int)).wait();
1729}
1730
1731/// Computes the matrix C in the following operation:
1732/// C = alpha * A * B + beta * D
1733/// \param [in] desc The descriptor of this calculation.
1734/// \param [in] m The rows number of A, D and C.
1735/// \param [in] n The columns number of B, D and C.
1736/// \param [in] k The columns number of A and rows number of B.
1737/// \param [in] alpha Scaling factor.
1738/// \param [in] info_a Matrix info of the matrix A.
1739/// \param [in] nnz_a Non-zero elements number of matrix A.
1740/// \param [in] val_a An array containing the non-zero elements of the matrix A.
1741/// \param [in] row_ptr_a An array of length \p m + 1.
1742/// \param [in] col_ind_a An array containing the column indices in index-based
1743/// numbering.
1744/// \param [in] info_b Matrix info of the matrix B.
1745/// \param [in] nnz_b Non-zero elements number of matrix B.
1746/// \param [in] val_b An array containing the non-zero elements of the matrix B.
1747/// \param [in] row_ptr_b An array of length \p k + 1.
1748/// \param [in] col_ind_b An array containing the column indices in index-based
1749/// numbering.
1750/// \param [in] beta Scaling factor.
1751/// \param [in] info_d Matrix info of the matrix D.
1752/// \param [in] nnz_d Non-zero elements number of matrix D.
1753/// \param [in] val_d An array containing the non-zero elements of the matrix D.
1754/// \param [in] row_ptr_d An array of length \p m + 1.
1755/// \param [in] col_ind_d An array containing the column indices in index-based
1756/// numbering.
1757/// \param [in] info_c Matrix info of the matrix C.
1758/// \param [out] val_c An array containing the non-zero elements of the matrix
1759/// C.
1760/// \param [in] row_ptr_c An array of length \p m + 1.
1761/// \param [out] col_ind_c An array containing the column indices in index-based
1762/// numbering.
1763/// \param [in] info The information of csrgemm2 operation.
1764/// \param [in] buffer Workspace memory.
1765template <typename T>
1766void csrgemm2(descriptor_ptr desc, int m, int n, int k, const T *alpha,
1767              const std::shared_ptr<matrix_info> info_a, int nnz_a,
1768              const T *val_a, const int *row_ptr_a, const int *col_ind_a,
1769              const std::shared_ptr<matrix_info> info_b, int nnz_b,
1770              const T *val_b, const int *row_ptr_b, const int *col_ind_b,
1771              const T *beta, const std::shared_ptr<matrix_info> info_d,
1772              int nnz_d, const T *val_d, const int *row_ptr_d,
1773              const int *col_ind_d, const std::shared_ptr<matrix_info> info_c,
1774              T *val_c, const int *row_ptr_c, int *col_ind_c,
1775              std::shared_ptr<csrgemm2_info> info, void *buffer) {
1776  using Ty = typename ::dpct::detail::lib_data_traits_t<T>;
1777  sycl::queue &queue = desc->get_queue();
1778  auto alpha_value =
1779      dpct::detail::get_value(reinterpret_cast<const Ty *>(alpha), queue);
1780  auto beta_value =
1781      dpct::detail::get_value(reinterpret_cast<const Ty *>(beta), queue);
1782
1783  info->matrix_handle_a.set_matrix_data<Ty>(m, k, info_a->get_index_base(),
1784                                            row_ptr_a, col_ind_a, val_a);
1785  info->matrix_handle_b.set_matrix_data<Ty>(k, n, info_b->get_index_base(),
1786                                            row_ptr_b, col_ind_b, val_b);
1787  __MATMAT(compute, nullptr, nullptr);
1788  __MATMAT(finalize, nullptr, nullptr);
1789
1790  info->matrix_handle_d.set_matrix_data<Ty>(m, n, info_d->get_index_base(),
1791                                            row_ptr_d, col_ind_d, val_d);
1792  info->matrix_handle_c.set_matrix_data<Ty>(m, n, info_c->get_index_base(),
1793                                            row_ptr_c, col_ind_c, val_c);
1794
1795  sycl::event e;
1796#ifndef DPCT_USM_LEVEL_NONE
1797  e =
1798#endif
1799      oneapi::mkl::sparse::omatadd(
1800          queue, oneapi::mkl::transpose::nontrans,
1801          oneapi::mkl::transpose::nontrans, alpha_value,
1802          info->matrix_handle_axb.get_handle(), beta_value,
1803          info->matrix_handle_d.get_handle(),
1804          info->matrix_handle_c.get_handle(),
1805          oneapi::mkl::sparse::omatadd_alg::default_alg,
1806          info->omatadd_desc.get_handle());
1807
1808  std::vector<sycl::event> events;
1809  events.push_back(e);
1810  events.push_back(info->release(queue, e));
1811  queue.submit([&](sycl::handler &cgh) {
1812    cgh.depends_on(events);
1813    cgh.host_task([_p1 = info->row_ptr_axb, _p2 = info->col_ind_axb,
1814                   _p3 = info->val_axb, _p4 = info->temp_buffer_1_size,
1815                   _p5 = info->temp_buffer_1, _p6 = info->temp_buffer_2_size,
1816                   _p7 = info->temp_buffer_2, _q = queue] {
1817      ::dpct::cs::free(_p1, _q);
1818      ::dpct::cs::free(_p2, _q);
1819      ::dpct::cs::free(_p3, _q);
1820#ifdef DPCT_USM_LEVEL_NONE
1821      delete _p4;
1822      delete _p5;
1823      delete _p6;
1824      delete _p7;
1825#else
1826      sycl::free(_p4, _q);
1827      sycl::free(_p5, _q);
1828      sycl::free(_p6, _q);
1829      sycl::free(_p7, _q);
1830#endif
1831    });
1832  });
1833}
1834
1835#endif
1836} // namespace dpct::sparse
1837
1838#endif // __DPCT_SPARSE_UTILS_HPP__