llvm-project
397 строк · 15.1 Кб
1//===-- runtime/matmul-transpose.cpp --------------------------------------===//
2//
3// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4// See https://llvm.org/LICENSE.txt for license information.
5// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6//
7//===----------------------------------------------------------------------===//
8
9// Implements a fused matmul-transpose operation
10//
11// There are two main entry points; one establishes a descriptor for the
12// result and allocates it, and the other expects a result descriptor that
13// points to existing storage.
14//
15// This implementation must handle all combinations of numeric types and
16// kinds (100 - 165 cases depending on the target), plus all combinations
17// of logical kinds (16). A single template undergoes many instantiations
18// to cover all of the valid possibilities.
19//
20// The usefulness of this optimization should be reviewed once Matmul is swapped
21// to use the faster BLAS routines.
22
23#include "flang/Runtime/matmul-transpose.h"
24#include "terminator.h"
25#include "tools.h"
26#include "flang/Common/optional.h"
27#include "flang/Runtime/c-or-cpp.h"
28#include "flang/Runtime/cpp-type.h"
29#include "flang/Runtime/descriptor.h"
30#include <cstring>
31
32namespace {
33using namespace Fortran::runtime;
34
35// Suppress the warnings about calling __host__-only std::complex operators,
36// defined in C++ STD header files, from __device__ code.
37RT_DIAG_PUSH
38RT_DIAG_DISABLE_CALL_HOST_FROM_DEVICE_WARN
39
40// Contiguous numeric TRANSPOSE(matrix)*matrix multiplication
41// TRANSPOSE(matrix(n, rows)) * matrix(n,cols) ->
42// matrix(rows, n) * matrix(n,cols) -> matrix(rows,cols)
43// The transpose is implemented by swapping the indices of accesses into the LHS
44//
45// Straightforward algorithm:
46// DO 1 I = 1, NROWS
47// DO 1 J = 1, NCOLS
48// RES(I,J) = 0
49// DO 1 K = 1, N
50// 1 RES(I,J) = RES(I,J) + X(K,I)*Y(K,J)
51//
52// With loop distribution and transposition to avoid the inner sum
53// reduction and to avoid non-unit strides:
54// DO 1 I = 1, NROWS
55// DO 1 J = 1, NCOLS
56// 1 RES(I,J) = 0
57// DO 2 J = 1, NCOLS
58// DO 2 I = 1, NROWS
59// DO 2 K = 1, N
60// 2 RES(I,J) = RES(I,J) + X(K,I)*Y(K,J) ! loop-invariant last term
61template <TypeCategory RCAT, int RKIND, typename XT, typename YT,
62bool X_HAS_STRIDED_COLUMNS, bool Y_HAS_STRIDED_COLUMNS>
63inline static RT_API_ATTRS void MatrixTransposedTimesMatrix(
64CppTypeFor<RCAT, RKIND> *RESTRICT product, SubscriptValue rows,
65SubscriptValue cols, const XT *RESTRICT x, const YT *RESTRICT y,
66SubscriptValue n, std::size_t xColumnByteStride = 0,
67std::size_t yColumnByteStride = 0) {
68using ResultType = CppTypeFor<RCAT, RKIND>;
69
70std::memset(product, 0, rows * cols * sizeof *product);
71for (SubscriptValue j{0}; j < cols; ++j) {
72for (SubscriptValue i{0}; i < rows; ++i) {
73for (SubscriptValue k{0}; k < n; ++k) {
74ResultType x_ki;
75if constexpr (!X_HAS_STRIDED_COLUMNS) {
76x_ki = static_cast<ResultType>(x[i * n + k]);
77} else {
78x_ki = static_cast<ResultType>(reinterpret_cast<const XT *>(
79reinterpret_cast<const char *>(x) + i * xColumnByteStride)[k]);
80}
81ResultType y_kj;
82if constexpr (!Y_HAS_STRIDED_COLUMNS) {
83y_kj = static_cast<ResultType>(y[j * n + k]);
84} else {
85y_kj = static_cast<ResultType>(reinterpret_cast<const YT *>(
86reinterpret_cast<const char *>(y) + j * yColumnByteStride)[k]);
87}
88product[j * rows + i] += x_ki * y_kj;
89}
90}
91}
92}
93
94RT_DIAG_POP
95
96template <TypeCategory RCAT, int RKIND, typename XT, typename YT>
97inline static RT_API_ATTRS void MatrixTransposedTimesMatrixHelper(
98CppTypeFor<RCAT, RKIND> *RESTRICT product, SubscriptValue rows,
99SubscriptValue cols, const XT *RESTRICT x, const YT *RESTRICT y,
100SubscriptValue n, Fortran::common::optional<std::size_t> xColumnByteStride,
101Fortran::common::optional<std::size_t> yColumnByteStride) {
102if (!xColumnByteStride) {
103if (!yColumnByteStride) {
104MatrixTransposedTimesMatrix<RCAT, RKIND, XT, YT, false, false>(
105product, rows, cols, x, y, n);
106} else {
107MatrixTransposedTimesMatrix<RCAT, RKIND, XT, YT, false, true>(
108product, rows, cols, x, y, n, 0, *yColumnByteStride);
109}
110} else {
111if (!yColumnByteStride) {
112MatrixTransposedTimesMatrix<RCAT, RKIND, XT, YT, true, false>(
113product, rows, cols, x, y, n, *xColumnByteStride);
114} else {
115MatrixTransposedTimesMatrix<RCAT, RKIND, XT, YT, true, true>(
116product, rows, cols, x, y, n, *xColumnByteStride, *yColumnByteStride);
117}
118}
119}
120
121RT_DIAG_PUSH
122RT_DIAG_DISABLE_CALL_HOST_FROM_DEVICE_WARN
123
124// Contiguous numeric matrix*vector multiplication
125// matrix(rows,n) * column vector(n) -> column vector(rows)
126// Straightforward algorithm:
127// DO 1 I = 1, NROWS
128// RES(I) = 0
129// DO 1 K = 1, N
130// 1 RES(I) = RES(I) + X(K,I)*Y(K)
131// With loop distribution and transposition to avoid the inner
132// sum reduction and to avoid non-unit strides:
133// DO 1 I = 1, NROWS
134// 1 RES(I) = 0
135// DO 2 I = 1, NROWS
136// DO 2 K = 1, N
137// 2 RES(I) = RES(I) + X(K,I)*Y(K)
138template <TypeCategory RCAT, int RKIND, typename XT, typename YT,
139bool X_HAS_STRIDED_COLUMNS>
140inline static RT_API_ATTRS void MatrixTransposedTimesVector(
141CppTypeFor<RCAT, RKIND> *RESTRICT product, SubscriptValue rows,
142SubscriptValue n, const XT *RESTRICT x, const YT *RESTRICT y,
143std::size_t xColumnByteStride = 0) {
144using ResultType = CppTypeFor<RCAT, RKIND>;
145std::memset(product, 0, rows * sizeof *product);
146for (SubscriptValue i{0}; i < rows; ++i) {
147for (SubscriptValue k{0}; k < n; ++k) {
148ResultType x_ki;
149if constexpr (!X_HAS_STRIDED_COLUMNS) {
150x_ki = static_cast<ResultType>(x[i * n + k]);
151} else {
152x_ki = static_cast<ResultType>(reinterpret_cast<const XT *>(
153reinterpret_cast<const char *>(x) + i * xColumnByteStride)[k]);
154}
155ResultType y_k = static_cast<ResultType>(y[k]);
156product[i] += x_ki * y_k;
157}
158}
159}
160
161RT_DIAG_POP
162
163template <TypeCategory RCAT, int RKIND, typename XT, typename YT>
164inline static RT_API_ATTRS void MatrixTransposedTimesVectorHelper(
165CppTypeFor<RCAT, RKIND> *RESTRICT product, SubscriptValue rows,
166SubscriptValue n, const XT *RESTRICT x, const YT *RESTRICT y,
167Fortran::common::optional<std::size_t> xColumnByteStride) {
168if (!xColumnByteStride) {
169MatrixTransposedTimesVector<RCAT, RKIND, XT, YT, false>(
170product, rows, n, x, y);
171} else {
172MatrixTransposedTimesVector<RCAT, RKIND, XT, YT, true>(
173product, rows, n, x, y, *xColumnByteStride);
174}
175}
176
177RT_DIAG_PUSH
178RT_DIAG_DISABLE_CALL_HOST_FROM_DEVICE_WARN
179
180// Implements an instance of MATMUL for given argument types.
181template <bool IS_ALLOCATING, TypeCategory RCAT, int RKIND, typename XT,
182typename YT>
183inline static RT_API_ATTRS void DoMatmulTranspose(
184std::conditional_t<IS_ALLOCATING, Descriptor, const Descriptor> &result,
185const Descriptor &x, const Descriptor &y, Terminator &terminator) {
186int xRank{x.rank()};
187int yRank{y.rank()};
188int resRank{xRank + yRank - 2};
189if (xRank * yRank != 2 * resRank) {
190terminator.Crash(
191"MATMUL-TRANSPOSE: bad argument ranks (%d * %d)", xRank, yRank);
192}
193SubscriptValue extent[2]{x.GetDimension(1).Extent(),
194resRank == 2 ? y.GetDimension(1).Extent() : 0};
195if constexpr (IS_ALLOCATING) {
196result.Establish(
197RCAT, RKIND, nullptr, resRank, extent, CFI_attribute_allocatable);
198for (int j{0}; j < resRank; ++j) {
199result.GetDimension(j).SetBounds(1, extent[j]);
200}
201if (int stat{result.Allocate()}) {
202terminator.Crash(
203"MATMUL-TRANSPOSE: could not allocate memory for result; STAT=%d",
204stat);
205}
206} else {
207RUNTIME_CHECK(terminator, resRank == result.rank());
208RUNTIME_CHECK(
209terminator, result.ElementBytes() == static_cast<std::size_t>(RKIND));
210RUNTIME_CHECK(terminator, result.GetDimension(0).Extent() == extent[0]);
211RUNTIME_CHECK(terminator,
212resRank == 1 || result.GetDimension(1).Extent() == extent[1]);
213}
214SubscriptValue n{x.GetDimension(0).Extent()};
215if (n != y.GetDimension(0).Extent()) {
216terminator.Crash(
217"MATMUL-TRANSPOSE: unacceptable operand shapes (%jdx%jd, %jdx%jd)",
218static_cast<std::intmax_t>(x.GetDimension(0).Extent()),
219static_cast<std::intmax_t>(x.GetDimension(1).Extent()),
220static_cast<std::intmax_t>(y.GetDimension(0).Extent()),
221static_cast<std::intmax_t>(y.GetDimension(1).Extent()));
222}
223using WriteResult =
224CppTypeFor<RCAT == TypeCategory::Logical ? TypeCategory::Integer : RCAT,
225RKIND>;
226const SubscriptValue rows{extent[0]};
227const SubscriptValue cols{extent[1]};
228if constexpr (RCAT != TypeCategory::Logical) {
229if (x.IsContiguous(1) && y.IsContiguous(1) &&
230(IS_ALLOCATING || result.IsContiguous())) {
231// Contiguous numeric matrices (maybe with columns
232// separated by a stride).
233Fortran::common::optional<std::size_t> xColumnByteStride;
234if (!x.IsContiguous()) {
235// X's columns are strided.
236SubscriptValue xAt[2]{};
237x.GetLowerBounds(xAt);
238xAt[1]++;
239xColumnByteStride = x.SubscriptsToByteOffset(xAt);
240}
241Fortran::common::optional<std::size_t> yColumnByteStride;
242if (!y.IsContiguous()) {
243// Y's columns are strided.
244SubscriptValue yAt[2]{};
245y.GetLowerBounds(yAt);
246yAt[1]++;
247yColumnByteStride = y.SubscriptsToByteOffset(yAt);
248}
249if (resRank == 2) { // M*M -> M
250// TODO: use BLAS-3 GEMM for supported types.
251MatrixTransposedTimesMatrixHelper<RCAT, RKIND, XT, YT>(
252result.template OffsetElement<WriteResult>(), rows, cols,
253x.OffsetElement<XT>(), y.OffsetElement<YT>(), n, xColumnByteStride,
254yColumnByteStride);
255return;
256}
257if (xRank == 2) { // M*V -> V
258// TODO: use BLAS-2 GEMM for supported types.
259MatrixTransposedTimesVectorHelper<RCAT, RKIND, XT, YT>(
260result.template OffsetElement<WriteResult>(), rows, n,
261x.OffsetElement<XT>(), y.OffsetElement<YT>(), xColumnByteStride);
262return;
263}
264// else V*M -> V (not allowed because TRANSPOSE() is only defined for rank
265// 1 matrices
266terminator.Crash(
267"MATMUL-TRANSPOSE: unacceptable operand shapes (%jdx%jd, %jdx%jd)",
268static_cast<std::intmax_t>(x.GetDimension(0).Extent()),
269static_cast<std::intmax_t>(n),
270static_cast<std::intmax_t>(y.GetDimension(0).Extent()),
271static_cast<std::intmax_t>(y.GetDimension(1).Extent()));
272return;
273}
274}
275// General algorithms for LOGICAL and noncontiguity
276SubscriptValue xLB[2], yLB[2], resLB[2];
277x.GetLowerBounds(xLB);
278y.GetLowerBounds(yLB);
279result.GetLowerBounds(resLB);
280using ResultType = CppTypeFor<RCAT, RKIND>;
281if (resRank == 2) { // M*M -> M
282for (SubscriptValue i{0}; i < rows; ++i) {
283for (SubscriptValue j{0}; j < cols; ++j) {
284ResultType res_ij;
285if constexpr (RCAT == TypeCategory::Logical) {
286res_ij = false;
287} else {
288res_ij = 0;
289}
290
291for (SubscriptValue k{0}; k < n; ++k) {
292SubscriptValue xAt[2]{k + xLB[0], i + xLB[1]};
293SubscriptValue yAt[2]{k + yLB[0], j + yLB[1]};
294if constexpr (RCAT == TypeCategory::Logical) {
295ResultType x_ki = IsLogicalElementTrue(x, xAt);
296ResultType y_kj = IsLogicalElementTrue(y, yAt);
297res_ij = res_ij || (x_ki && y_kj);
298} else {
299ResultType x_ki = static_cast<ResultType>(*x.Element<XT>(xAt));
300ResultType y_kj = static_cast<ResultType>(*y.Element<YT>(yAt));
301res_ij += x_ki * y_kj;
302}
303}
304SubscriptValue resAt[2]{i + resLB[0], j + resLB[1]};
305*result.template Element<WriteResult>(resAt) = res_ij;
306}
307}
308} else if (xRank == 2) { // M*V -> V
309for (SubscriptValue i{0}; i < rows; ++i) {
310ResultType res_i;
311if constexpr (RCAT == TypeCategory::Logical) {
312res_i = false;
313} else {
314res_i = 0;
315}
316
317for (SubscriptValue k{0}; k < n; ++k) {
318SubscriptValue xAt[2]{k + xLB[0], i + xLB[1]};
319SubscriptValue yAt[1]{k + yLB[0]};
320if constexpr (RCAT == TypeCategory::Logical) {
321ResultType x_ki = IsLogicalElementTrue(x, xAt);
322ResultType y_k = IsLogicalElementTrue(y, yAt);
323res_i = res_i || (x_ki && y_k);
324} else {
325ResultType x_ki = static_cast<ResultType>(*x.Element<XT>(xAt));
326ResultType y_k = static_cast<ResultType>(*y.Element<YT>(yAt));
327res_i += x_ki * y_k;
328}
329}
330SubscriptValue resAt[1]{i + resLB[0]};
331*result.template Element<WriteResult>(resAt) = res_i;
332}
333} else { // V*M -> V
334// TRANSPOSE(V) not allowed by fortran standard
335terminator.Crash(
336"MATMUL-TRANSPOSE: unacceptable operand shapes (%jdx%jd, %jdx%jd)",
337static_cast<std::intmax_t>(x.GetDimension(0).Extent()),
338static_cast<std::intmax_t>(n),
339static_cast<std::intmax_t>(y.GetDimension(0).Extent()),
340static_cast<std::intmax_t>(y.GetDimension(1).Extent()));
341}
342}
343
344RT_DIAG_POP
345
346template <bool IS_ALLOCATING, TypeCategory XCAT, int XKIND, TypeCategory YCAT,
347int YKIND>
348struct MatmulTransposeHelper {
349using ResultDescriptor =
350std::conditional_t<IS_ALLOCATING, Descriptor, const Descriptor>;
351RT_API_ATTRS void operator()(ResultDescriptor &result, const Descriptor &x,
352const Descriptor &y, const char *sourceFile, int line) const {
353Terminator terminator{sourceFile, line};
354auto xCatKind{x.type().GetCategoryAndKind()};
355auto yCatKind{y.type().GetCategoryAndKind()};
356RUNTIME_CHECK(terminator, xCatKind.has_value() && yCatKind.has_value());
357RUNTIME_CHECK(terminator, xCatKind->first == XCAT);
358RUNTIME_CHECK(terminator, yCatKind->first == YCAT);
359if constexpr (constexpr auto resultType{
360GetResultType(XCAT, XKIND, YCAT, YKIND)}) {
361return DoMatmulTranspose<IS_ALLOCATING, resultType->first,
362resultType->second, CppTypeFor<XCAT, XKIND>, CppTypeFor<YCAT, YKIND>>(
363result, x, y, terminator);
364}
365terminator.Crash("MATMUL-TRANSPOSE: bad operand types (%d(%d), %d(%d))",
366static_cast<int>(XCAT), XKIND, static_cast<int>(YCAT), YKIND);
367}
368};
369} // namespace
370
371namespace Fortran::runtime {
372extern "C" {
373RT_EXT_API_GROUP_BEGIN
374
375#define MATMUL_INSTANCE(XCAT, XKIND, YCAT, YKIND) \
376void RTDEF(MatmulTranspose##XCAT##XKIND##YCAT##YKIND)(Descriptor & result, \
377const Descriptor &x, const Descriptor &y, const char *sourceFile, \
378int line) { \
379MatmulTransposeHelper<true, TypeCategory::XCAT, XKIND, TypeCategory::YCAT, \
380YKIND>{}(result, x, y, sourceFile, line); \
381}
382
383#define MATMUL_DIRECT_INSTANCE(XCAT, XKIND, YCAT, YKIND) \
384void RTDEF(MatmulTransposeDirect##XCAT##XKIND##YCAT##YKIND)( \
385Descriptor & result, const Descriptor &x, const Descriptor &y, \
386const char *sourceFile, int line) { \
387MatmulTransposeHelper<false, TypeCategory::XCAT, XKIND, \
388TypeCategory::YCAT, YKIND>{}(result, x, y, sourceFile, line); \
389}
390
391#define MATMUL_FORCE_ALL_TYPES 0
392
393#include "flang/Runtime/matmul-instances.inc"
394
395RT_EXT_API_GROUP_END
396} // extern "C"
397} // namespace Fortran::runtime
398