Loading...
Searching...
No Matches
CanonicalTileKernels.cpp
Go to the documentation of this file.
1// SPDX-License-Identifier: MIT
2// Copyright (c) gpridge developers
4
5#include <Eigen/Cholesky>
6#include <Eigen/Core>
7#include <algorithm>
8#include <type_traits>
9#include <vector>
10
11#include "TileProduct.h"
12
13#if defined(EIGEN_USE_BLAS) || defined(EIGEN_USE_LAPACKE) || \
14 defined(EIGEN_USE_MKL_ALL)
15#error "Canonical tile kernels require private, compiled Eigen arithmetic"
16#endif
17
18#if defined(_OPENMP) || !defined(EIGEN_DONT_PARALLELIZE)
19#error "Canonical tile kernels must compile without Eigen OpenMP dispatch"
20#endif
21
23namespace {
24
25using Index = Eigen::Index;
26using Traits = Eigen::internal::gebp_traits<double, double>;
27using DenseRef = Eigen::Ref<Eigen::MatrixXd>;
28using DenseBlock = Eigen::Block<DenseRef, Eigen::Dynamic, Eigen::Dynamic>;
29
30// Upper bound on the items one call splits into. The partitions below do
31// not depend on the thread count, only on the operand shapes.
32constexpr Index kMaxItems = 64;
33// Narrower ranges re-read the triangle more often than they save.
34constexpr Index kMinRangeBlocks = 4;
35// Below this order Eigen's coefficient-based product can replace the
36// blocked kernels, and that choice follows the operand shapes.
37constexpr Index kMinParallelOrder = 48;
38
39class Items {
40public:
41 Items(ParallelItems run, void* context) : run_(run), context_(context) { }
42
43 [[nodiscard]] bool parallel() const noexcept
44 {
45 return run_ != nullptr;
46 }
47
48 template <class F>
49 void operator()(Index count, F& fn) const
50 {
51 if (count <= 0) return;
52 if (run_ == nullptr || count == 1) {
53 for (Index i = 0; i < count; ++i)
54 fn(i);
55 return;
56 }
57 run_(
58 context_, count,
59 [](void* f, std::ptrdiff_t i) { (*static_cast<F*>(f))(i); }, &fn);
60 }
61
62private:
63 ParallelItems run_;
64 void* context_;
65};
66
67// Starts of ranges over extent entries: multiples of unit, the remainder
68// folded into the last range, and no range shorter than two units unless
69// the extent is. Eigen's packed kernels assign a row (column) its register
70// block by its offset modulo mr (nr) and by the extent modulo mr (nr), and
71// all block boundaries the blocking heuristic draws are multiples of those,
72// so a range sees each entry with the micro-kernel of the full call.
73std::vector<Index> alignedStarts(Index extent, Index unit)
74{
75 const Index units = (extent + unit - 1) / unit;
76 const Index per_range =
77 std::max<Index>(kMinRangeBlocks, (units + kMaxItems - 1) / kMaxItems);
78 const Index width = per_range * unit;
79 std::vector<Index> starts;
80 for (Index start = 0; start == 0 || start + width <= extent; start += width)
81 starts.push_back(start);
82 starts.push_back(extent);
83 return starts;
84}
85
86// A21 := A21 L11^-T, the panel solve of Eigen's blocked LLT, on row ranges.
87void solvePanelRows(const DenseBlock& A11, DenseBlock& A21, const Items& items)
88{
89 const auto solve = [&](auto&& rows) {
90 A11.adjoint()
91 .template triangularView<Eigen::Upper>()
92 .template solveInPlace<Eigen::OnTheRight>(rows);
93 };
94 if (!items.parallel() || A21.rows() < 2 * kMinRangeBlocks * Traits::mr) {
95 solve(A21);
96 return;
97 }
98 const std::vector<Index> starts = alignedStarts(A21.rows(), Traits::mr);
99 auto item = [&](Index i) {
100 auto rows = A21.middleRows(starts[i], starts[i + 1] - starts[i]);
101 solve(rows);
102 };
103 items(static_cast<Index>(starts.size()) - 1, item);
104}
105
106// A22 -= A21 A21^T on and below the diagonal. This is Eigen's
107// general_matrix_matrix_triangular_product (Lower) for that call, with the
108// same blocking, packing and kernel calls; the column blocks of its
109// diagonal kernel, and the rectangle left of each row block, are items.
110void rankUpdateLower(DenseBlock& A22, const DenseBlock& A21, const Items& items)
111{
112 namespace ei = Eigen::internal;
113 using LhsMapper =
114 ei::const_blas_data_mapper<double, Index, Eigen::ColMajor>;
115 using RhsMapper =
116 ei::const_blas_data_mapper<double, Index, Eigen::RowMajor>;
117 using ResMapper = ei::blas_data_mapper<double, Index, Eigen::ColMajor,
118 Eigen::Unaligned, 1>;
119 using BufferMapper =
120 ei::blas_data_mapper<double, Index, Eigen::ColMajor, Eigen::Unaligned>;
121 using Aligned = std::vector<double, Eigen::aligned_allocator<double>>;
122 enum {
123 BlockSize = ei::meta_least_common_multiple<
124 EIGEN_PLAIN_ENUM_MAX(Traits::mr, Traits::nr),
125 EIGEN_PLAIN_ENUM_MIN(Traits::mr, Traits::nr)>::ret
126 };
127
128 const Index size = A22.cols();
129 const Index depth = A21.cols();
130 ei::gemm_blocking_space<Eigen::ColMajor, double, double, Eigen::Dynamic,
131 Eigen::Dynamic, Eigen::Dynamic>
132 blocking(size, size, depth, 1, false);
133 const Index kc = blocking.kc();
134 Index mc = std::min(size, blocking.mc());
135 if (mc > Traits::nr) mc = (mc / Traits::nr) * Traits::nr;
136
137 const LhsMapper lhs(A21.data(), A21.outerStride());
138 const RhsMapper rhs(A21.data(), A21.outerStride());
139 const ResMapper res(A22.data(), A22.outerStride());
140 ei::gemm_pack_lhs<double, Index, LhsMapper, Traits::mr, Traits::LhsProgress,
141 typename Traits::LhsPacket4Packing, Eigen::ColMajor>
142 pack_lhs;
143 ei::gemm_pack_rhs<double, Index, RhsMapper, Traits::nr, Eigen::RowMajor>
144 pack_rhs;
145 ei::gebp_kernel<double, double, Index, ResMapper, Traits::mr, Traits::nr,
146 false, false>
147 gebp;
148 ei::gebp_kernel<double, double, Index, BufferMapper, Traits::mr, Traits::nr,
149 false, false>
150 gebp_buffer;
151 const double alpha = -1.0;
152
153 const Index row_blocks = (size + mc - 1) / mc;
154 Aligned blockB(static_cast<std::size_t>(kc * size));
155 Aligned blockA(static_cast<std::size_t>(kc * mc * row_blocks));
156 struct Task {
157 Index i2, mc, j; // j < 0: the rectangle left of the row block
158 };
159 std::vector<Task> tasks;
160
161 for (Index k2 = 0; k2 < depth; k2 += kc) {
162 const Index actual_kc = std::min(k2 + kc, depth) - k2;
163 pack_rhs(blockB.data(), rhs.getSubMapper(k2, 0), actual_kc, size);
164 tasks.clear();
165 for (Index b = 0; b < row_blocks; ++b) {
166 const Index i2 = b * mc;
167 const Index actual_mc = std::min(i2 + mc, size) - i2;
168 pack_lhs(blockA.data() + b * kc * mc, lhs.getSubMapper(i2, k2),
169 actual_kc, actual_mc);
170 if (i2 > 0) tasks.push_back({i2, actual_mc, -1});
171 for (Index j = 0; j < actual_mc; j += BlockSize)
172 tasks.push_back({i2, actual_mc, j});
173 }
174 auto item = [&](Index t) {
175 const Task& task = tasks[static_cast<std::size_t>(t)];
176 const double* packed_a = blockA.data() + (task.i2 / mc) * kc * mc;
177 if (task.j < 0) {
178 gebp(res.getSubMapper(task.i2, 0), packed_a, blockB.data(),
179 task.mc, actual_kc, std::min(size, task.i2), alpha, -1, -1,
180 0, 0);
181 return;
182 }
183 // tribb_kernel, one column block of the diagonal block.
184 const Index j = task.j;
185 const Index width = std::min<Index>(BlockSize, task.mc - j);
186 const double* actual_b =
187 blockB.data() + actual_kc * task.i2 + j * actual_kc;
188 const ResMapper diagonal = res.getSubMapper(task.i2, task.i2);
189 Eigen::Matrix<double, BlockSize, BlockSize, Eigen::ColMajor> buffer;
190 buffer.setZero();
191 gebp_buffer(BufferMapper(buffer.data(), BlockSize),
192 packed_a + actual_kc * j, actual_b, width, actual_kc,
193 width, alpha, -1, -1, 0, 0);
194 for (Index j1 = 0; j1 < width; ++j1) {
195 auto r = diagonal.getLinearMapper(j, j + j1);
196 for (Index i1 = j1; i1 < width; ++i1)
197 r(i1) += buffer(i1, j1);
198 }
199 const Index i = j + width;
200 gebp(diagonal.getSubMapper(i, j), packed_a + actual_kc * i,
201 actual_b, task.mc - i, actual_kc, width, alpha, -1, -1, 0, 0);
202 };
203 items(static_cast<Index>(tasks.size()), item);
204 }
205}
206
207// Eigen's llt_inplace<double, Lower>::blocked on the same matrix type.
208Index blockedLowerLLT(DenseRef& m, const Items& items)
209{
210 using Llt = Eigen::internal::llt_inplace<double, Eigen::Lower>;
211 const Index size = m.rows();
212 if (size < 32) return Llt::unblocked(m);
213
214 Index blockSize = size / 8;
215 blockSize = (blockSize / 16) * 16;
216 blockSize = std::min(std::max(blockSize, Index(8)), Index(128));
217
218 for (Index k = 0; k < size; k += blockSize) {
219 const Index bs = std::min(blockSize, size - k);
220 const Index rs = size - k - bs;
221 DenseBlock A11(m, k, k, bs, bs);
222 DenseBlock A21(m, k + bs, k, rs, bs);
223 DenseBlock A22(m, k + bs, k + bs, rs, rs);
224
225 const Index ret = Llt::unblocked(A11);
226 if (ret >= 0) return k + ret;
227 if (rs > 0) solvePanelRows(A11, A21, items);
228 if (rs > 0) rankUpdateLower(A22, A21, items);
229 }
230 return -1;
231}
232
233template <class Triangular, class Rhs>
234void solveColumns(const Triangular& triangular, Rhs& result, const Items& items)
235{
236 if (!items.parallel() || triangular.rows() < kMinParallelOrder ||
237 result.cols() < 2 * kMinRangeBlocks * Traits::nr) {
238 triangular.solveInPlace(result);
239 return;
240 }
241 const std::vector<Index> starts = alignedStarts(result.cols(), Traits::nr);
242 auto item = [&](Index i) {
243 auto columns = result.middleCols(starts[i], starts[i + 1] - starts[i]);
244 triangular.solveInPlace(columns);
245 };
246 items(static_cast<Index>(starts.size()) - 1, item);
247}
248
249} // namespace
250
252{
254}
255
256void subtract(double* out, std::ptrdiff_t out_stride, const double* left,
257 std::ptrdiff_t left_stride, const double* right,
258 std::ptrdiff_t right_stride, std::ptrdiff_t rows,
259 std::ptrdiff_t columns, std::ptrdiff_t depth,
260 bool transpose_right)
261{
262 using Stride = Eigen::OuterStride<>;
263 using ConstMap = Eigen::Map<const Eigen::MatrixXd, 0, Stride>;
264 Eigen::Map<Eigen::MatrixXd, 0, Stride> result(out, rows, columns,
265 Stride(out_stride));
266 const ConstMap a(left, rows, depth, Stride(left_stride));
267 if (transpose_right) {
268 const ConstMap b(right, columns, depth, Stride(right_stride));
270 } else {
271 const ConstMap b(right, depth, columns, Stride(right_stride));
272 canonical::subtractTileProduct(result, a, b);
273 }
274}
275
276void addTransposeProduct(double* out, const double* left, const double* right,
277 std::ptrdiff_t rows, std::ptrdiff_t columns,
278 std::ptrdiff_t depth)
279{
280 using ConstMap = Eigen::Map<const Eigen::MatrixXd, Eigen::Aligned64>;
281 Eigen::Map<Eigen::MatrixXd, Eigen::Aligned64> result(out, rows, columns);
282 const ConstMap a(left, depth, rows), b(right, depth, columns);
283 result.noalias() += a.transpose() * b;
284}
285
286bool factorLower(double* matrix, std::ptrdiff_t order)
287{
288 Eigen::Map<Eigen::MatrixXd, Eigen::Aligned64> block(matrix, order, order);
289 Eigen::LLT<Eigen::Ref<Eigen::MatrixXd>> factor(block);
290 return factor.info() == Eigen::Success;
291}
292
293void solveLeft(const double* factor, double* rhs, std::ptrdiff_t order,
294 std::ptrdiff_t columns, bool lower)
295{
296 const Eigen::Map<const Eigen::MatrixXd, Eigen::Aligned64> diagonal(
297 factor, order, order);
298 Eigen::Map<Eigen::MatrixXd, Eigen::Aligned64> result(rhs, order, columns);
299 if (lower)
300 diagonal.triangularView<Eigen::Lower>().solveInPlace(result);
301 else
302 diagonal.triangularView<Eigen::Upper>().solveInPlace(result);
303}
304
305bool factorLowerGeneral(double* matrix, std::ptrdiff_t stride,
306 std::ptrdiff_t order, ParallelItems run,
307 void* run_context)
308{
309 if (order < 0 || (order > 0 && (matrix == nullptr || stride < order)))
310 return false;
311 if (order == 0) return true;
312 const auto factorise = [&](DenseRef lower) {
313 if (run == nullptr) {
314 Eigen::LLT<DenseRef, Eigen::Lower> factor(lower);
315 return factor.info() == Eigen::Success;
316 }
317 return blockedLowerLLT(lower, Items(run, run_context)) == -1;
318 };
319 // A contiguous column-major buffer is factored in place. Eigen's lower
320 // LLT reads and writes only that triangle, so a zero-filled copy is the
321 // same factor and an extra allocation.
322 if (stride == order) {
323 Eigen::Map<Eigen::MatrixXd> mapped(matrix, order, order);
324 return factorise(mapped);
325 }
326 using Stride = Eigen::OuterStride<>;
327 Eigen::Map<Eigen::MatrixXd, 0, Stride> mapped(matrix, order, order,
328 Stride(stride));
329 thread_local Eigen::MatrixXd dense;
330 dense.resize(order, order);
331 dense.setZero();
332 dense.triangularView<Eigen::Lower>() =
333 mapped.triangularView<Eigen::Lower>();
334 if (!factorise(dense)) return false;
335 mapped.triangularView<Eigen::Lower>() =
336 dense.triangularView<Eigen::Lower>();
337 return true;
338}
339
340void solveLeftGeneral(const double* factor, std::ptrdiff_t factor_stride,
341 bool lower_factor, double* rhs, std::ptrdiff_t rhs_stride,
342 std::ptrdiff_t order, std::ptrdiff_t columns,
343 ParallelItems run, void* run_context)
344{
345 if (order <= 0 || columns <= 0 || factor == nullptr || rhs == nullptr)
346 return;
347 using Stride = Eigen::OuterStride<>;
348 const Eigen::Map<const Eigen::MatrixXd, 0, Stride> triangular(
349 factor, order, order, Stride(factor_stride));
350 Eigen::Map<Eigen::MatrixXd, 0, Stride> result(rhs, order, columns,
351 Stride(rhs_stride));
352 const Items items(run, run_context);
353 if (lower_factor)
354 solveColumns(triangular.triangularView<Eigen::Lower>(), result, items);
355 else
356 solveColumns(triangular.transpose().triangularView<Eigen::Upper>(),
357 result, items);
358}
359
360void solveVectorGeneral(const double* factor, std::ptrdiff_t factor_stride,
361 bool lower_factor, double* rhs, std::ptrdiff_t order)
362{
363 if (order <= 0 || factor == nullptr || rhs == nullptr) return;
364 using Stride = Eigen::OuterStride<>;
365 const Eigen::Map<const Eigen::MatrixXd, 0, Stride> triangular(
366 factor, order, order, Stride(factor_stride));
367 Eigen::Map<Eigen::VectorXd> result(rhs, order);
368 if (lower_factor)
369 triangular.triangularView<Eigen::Lower>().solveInPlace(result);
370 else
371 triangular.transpose().triangularView<Eigen::Upper>().solveInPlace(
372 result);
373}
374
375void assignTransposeGram(const double* b, std::ptrdiff_t b_stride, double* c,
376 std::ptrdiff_t c_stride, std::ptrdiff_t order,
377 ParallelItems run, void* run_context)
378{
379 if (order <= 0 || b == nullptr || c == nullptr) return;
380 using Stride = Eigen::OuterStride<>;
381 const Eigen::Map<const Eigen::MatrixXd, 0, Stride> left(b, order, order,
382 Stride(b_stride));
383 Eigen::Map<Eigen::MatrixXd, 0, Stride> gram(c, order, order,
384 Stride(c_stride));
385 if (run == nullptr || order < kMinParallelOrder) {
386 gram.noalias() = left.transpose() * left;
387 return;
388 }
389 // Column ranges of one product: a range of two or more columns stays on
390 // the blocked kernel (one column would take the matrix-vector path).
391 const std::vector<Index> starts = alignedStarts(order, Traits::nr);
392 auto item = [&](Index i) {
393 const Index first = starts[i], width = starts[i + 1] - starts[i];
394 gram.middleCols(first, width).noalias() =
395 left.transpose() * left.middleCols(first, width);
396 };
397 Items(run, run_context)(static_cast<Index>(starts.size()) - 1, item);
398}
399
400void solveRightUpper(const double* factor, double* rhs, std::ptrdiff_t rows,
401 std::ptrdiff_t order)
402{
403 const Eigen::Map<const Eigen::MatrixXd, Eigen::Aligned64> diagonal(
404 factor, order, order);
405 Eigen::Map<Eigen::MatrixXd, Eigen::Aligned64> result(rhs, rows, order);
406 diagonal.triangularView<Eigen::Upper>().solveInPlace<Eigen::OnTheRight>(
407 result);
408}
409
410void addMatrixProduct(double* out, std::ptrdiff_t out_stride,
411 const double* left, std::ptrdiff_t left_stride,
412 const double* right, std::ptrdiff_t right_stride,
413 std::ptrdiff_t rows, std::ptrdiff_t columns,
414 std::ptrdiff_t depth, double scale, bool transpose_left,
415 bool transpose_right)
416{
417 if (rows <= 0 || columns <= 0 || depth <= 0 || scale == 0.0 ||
418 out == nullptr || left == nullptr || right == nullptr)
419 return;
420 using Stride = Eigen::OuterStride<>;
421 using ConstMap = Eigen::Map<const Eigen::MatrixXd, 0, Stride>;
422 Eigen::Map<Eigen::MatrixXd, 0, Stride> result(out, rows, columns,
423 Stride(out_stride));
424 const auto accumulate = [&](const auto& product) {
425 if (scale == 1.0)
426 result.noalias() += product;
427 else if (scale == -1.0)
428 result.noalias() -= product;
429 else
430 result.noalias() += scale * product;
431 };
432 if (transpose_left && transpose_right) {
433 const ConstMap a(left, depth, rows, Stride(left_stride));
434 const ConstMap b(right, columns, depth, Stride(right_stride));
435 accumulate(a.transpose() * b.transpose());
436 } else if (transpose_left) {
437 const ConstMap a(left, depth, rows, Stride(left_stride));
438 const ConstMap b(right, depth, columns, Stride(right_stride));
439 accumulate(a.transpose() * b);
440 } else if (transpose_right) {
441 const ConstMap a(left, rows, depth, Stride(left_stride));
442 const ConstMap b(right, columns, depth, Stride(right_stride));
443 accumulate(a * b.transpose());
444 } else {
445 const ConstMap a(left, rows, depth, Stride(left_stride));
446 const ConstMap b(right, depth, columns, Stride(right_stride));
447 accumulate(a * b);
448 }
449}
450
451} // namespace gpr::linalg::portable_tiles
eon_relax_band_t eon_relax_surface_fn void eon_relax_outcome_t * out
bool wideTileProductAvailable() noexcept
Definition TileProduct.h:17
void subtractTileProduct(Target &&out, const Left &left, const Right &right)
void subtract(double *out, std::ptrdiff_t out_stride, const double *left, std::ptrdiff_t left_stride, const double *right, std::ptrdiff_t right_stride, std::ptrdiff_t rows, std::ptrdiff_t columns, std::ptrdiff_t depth, bool transpose_right)
void(*)(void *context, std::ptrdiff_t count, void(*item)(void *, std::ptrdiff_t), void *item_context) ParallelItems
void addTransposeProduct(double *out, const double *left, const double *right, std::ptrdiff_t rows, std::ptrdiff_t columns, std::ptrdiff_t depth)
void solveLeftGeneral(const double *factor, std::ptrdiff_t factor_stride, bool lower_factor, double *rhs, std::ptrdiff_t rhs_stride, std::ptrdiff_t order, std::ptrdiff_t columns, ParallelItems run, void *run_context)
bool factorLower(double *matrix, std::ptrdiff_t order)
void solveVectorGeneral(const double *factor, std::ptrdiff_t factor_stride, bool lower_factor, double *rhs, std::ptrdiff_t order)
void solveLeft(const double *factor, double *rhs, std::ptrdiff_t order, std::ptrdiff_t columns, bool lower)
void addMatrixProduct(double *out, std::ptrdiff_t out_stride, const double *left, std::ptrdiff_t left_stride, const double *right, std::ptrdiff_t right_stride, std::ptrdiff_t rows, std::ptrdiff_t columns, std::ptrdiff_t depth, double scale, bool transpose_left, bool transpose_right)
void assignTransposeGram(const double *b, std::ptrdiff_t b_stride, double *c, std::ptrdiff_t c_stride, std::ptrdiff_t order, ParallelItems run, void *run_context)
void solveRightUpper(const double *factor, double *rhs, std::ptrdiff_t rows, std::ptrdiff_t order)
bool factorLowerGeneral(double *matrix, std::ptrdiff_t stride, std::ptrdiff_t order, ParallelItems run, void *run_context)