Intrepid2
Intrepid2_PAMatrixDef.hpp
Go to the documentation of this file.
1// @HEADER
2// *****************************************************************************
3// Intrepid2 Package
4//
5// Copyright 2007 NTESS and the Intrepid2 contributors.
6// SPDX-License-Identifier: BSD-3-Clause
7// *****************************************************************************
8// @HEADER
9
14
15#ifndef __INTREPID2_PAMATRIX_DEF_HPP__
16#define __INTREPID2_PAMATRIX_DEF_HPP__
17
19
23
24#include <Teuchos_Assert.hpp>
25#include <Teuchos_BLAS.hpp>
26#include <Teuchos_TimeMonitor.hpp>
27
28#ifdef HAVE_INTREPID2_KOKKOSKERNELS
29#include <KokkosBlas3_gemm.hpp>
30#endif
31
32#include <algorithm>
33#include <cstdlib>
34#include <limits>
35#include <numeric>
36#include <string>
37#include <type_traits>
38
39namespace Intrepid2 {
40
41namespace Impl
42{
45 {
46 static bool &enabled() { static bool value = false; return value; }
47 static double &cumulativeFlops() { static double value = 0; return value; }
48 static Teuchos::RCP<Teuchos::Time> timer()
49 {
50 static const auto value = Teuchos::TimeMonitor::getNewTimer("Intrepid2::PAMatrix gemm");
51 return value;
52 }
53 };
54
57 template<typename DeviceType>
58 constexpr bool isHostDevice()
59 {
60 using ExecutionSpace = typename DeviceType::execution_space;
61 using MemorySpace = typename DeviceType::memory_space;
62 return Kokkos::SpaceAccessibility<Kokkos::HostSpace, MemorySpace>::accessible
63 && Kokkos::SpaceAccessibility<ExecutionSpace, Kokkos::HostSpace>::accessible;
64 }
65
70 template<typename DeviceType>
71 constexpr bool gemmUsesTeuchosBLAS()
72 {
74 }
75
78 template<typename DeviceType>
79 constexpr bool gemmSupported()
80 {
81#ifdef HAVE_INTREPID2_KOKKOSKERNELS
82 return true;
83#else
85#endif
86 }
87
94 template<typename DeviceType,typename Scalar>
95 void gemm(const char transA, const char transB,
96 const ordinal_type M, const ordinal_type N, const ordinal_type K,
97 const Scalar alpha, const Scalar* A, const ordinal_type LDA,
98 const Scalar* B, const Scalar beta, Scalar* C)
99 {
100 static_assert(gemmSupported<DeviceType>(), "PAMatrix on this device type requires Intrepid2 to be built with KokkosKernels");
101 INTREPID2_TEST_FOR_EXCEPTION(LDA <= 0, std::invalid_argument, "LDA must be positive");
102 if ((M == 0) || (N == 0)) return;
103
104 using ExecutionSpace = typename DeviceType::execution_space;
105 const bool recordStatistics = PAMatrixGEMMStatistics::enabled();
106 Teuchos::RCP<Teuchos::TimeMonitor> gemmTimer;
107 if (recordStatistics)
108 {
109 ExecutionSpace().fence(); // so that the timer measures only this GEMM
110 gemmTimer = Teuchos::rcp(new Teuchos::TimeMonitor(*PAMatrixGEMMStatistics::timer()));
111 }
112
113 if constexpr (gemmUsesTeuchosBLAS<DeviceType>())
114 {
115 // any outstanding kernels that produce A or B must complete before the host BLAS reads them
116 ExecutionSpace().fence();
117 const Teuchos::ETransp trA = (transA == 'T') ? Teuchos::TRANS : (transA == 'C') ? Teuchos::CONJ_TRANS : Teuchos::NO_TRANS;
118 const Teuchos::ETransp trB = (transB == 'T') ? Teuchos::TRANS : (transB == 'C') ? Teuchos::CONJ_TRANS : Teuchos::NO_TRANS;
119 const ordinal_type LDB = std::max<ordinal_type>(1, (trB == Teuchos::NO_TRANS) ? K : N);
120 const ordinal_type LDC = std::max<ordinal_type>(1, M);
121 Teuchos::BLAS<int,Scalar> blas;
122 blas.GEMM(trA, trB, M, N, K, alpha, A, LDA, B, LDB, beta, C, LDC);
123 }
124 else
125 {
126#ifdef HAVE_INTREPID2_KOKKOSKERNELS
127 using ConstView2D = Kokkos::View<const Scalar**, Kokkos::LayoutLeft, DeviceType, Kokkos::MemoryUnmanaged>;
128 using View2D = Kokkos::View< Scalar**, Kokkos::LayoutLeft, DeviceType, Kokkos::MemoryUnmanaged>;
129 using Stride2D = Kokkos::View<const Scalar**, Kokkos::LayoutStride, DeviceType, Kokkos::MemoryUnmanaged>;
130 const ordinal_type rowsA = (transA == 'N') ? M : K;
131 const ordinal_type colsA = (transA == 'N') ? K : M;
132 INTREPID2_TEST_FOR_EXCEPTION(LDA < rowsA, std::invalid_argument, "LDA must be at least the number of rows of A");
133 ConstView2D BView = (transB != 'N') ? ConstView2D(B,N,K) : ConstView2D(B,K,N);
134 View2D CView(C,M,N);
135 const char tA[] = {transA, '\0'};
136 const char tB[] = {transB, '\0'};
137 if (LDA == rowsA)
138 {
139 // KokkosBlas::gemm dispatches to the TPL BLAS (e.g., cuBLAS) only when A, B, and C are all LayoutLeft (or all
140 // LayoutRight); with a LayoutStride A it uses its native implementation, which is much slower.
141 ConstView2D AView(A, rowsA, colsA);
142 KokkosBlas::gemm(ExecutionSpace(), tA, tB, alpha, AView, BView, beta, CView);
143 }
144 else
145 {
146 Kokkos::LayoutStride layoutA(rowsA, 1, colsA, LDA);
147 Stride2D AView(A, layoutA);
148 KokkosBlas::gemm(ExecutionSpace(), tA, tB, alpha, AView, BView, beta, CView);
149 }
150#endif
151 }
152
153 if (recordStatistics)
154 {
155 ExecutionSpace().fence(); // so that the timer measures the GEMM's execution, not just its launch
156 gemmTimer = Teuchos::null;
157 PAMatrixGEMMStatistics::cumulativeFlops() += double(M) * double(N) * double(2 * K - 1);
158 }
159 }
160
162 inline double parsePositiveEnvironmentNumber(const char *name, const char *value)
163 {
164 char *end = nullptr;
165 const double result = std::strtod(value, &end);
166 TEUCHOS_TEST_FOR_EXCEPTION((end == value) || (*end != '\0') || !(result > 0) || !(result < std::numeric_limits<double>::infinity()),
167 std::invalid_argument, name << " must be a positive number; got '" << value << "'");
168 return result;
169 }
170
175 template<typename DeviceType, class Scalar>
176 void pointDataMultiply(const ordinal_type numDataCells, const ordinal_type startCell, const ordinal_type Cw,
177 const ordinal_type numPoints, const ordinal_type aSpan, const ordinal_type bSpan,
178 const Scalar* A, const Scalar *B, Scalar *C, const ordinal_type N)
179 {
180 // Limitation: only aSpan == 1 is supported. Non-trivial Da would require packing the vector index into the point component
181 // over which the left integral performs a dot product (and additional arguments describing the point components).
182 INTREPID2_TEST_FOR_EXCEPTION(aSpan != 1, std::invalid_argument, "aSpan != 1 is not yet supported");
183
184 using ExecutionSpace = typename DeviceType::execution_space;
185 // Iterate in the output's memory order (n fastest, then cell, then point, then a), so that writes to C are contiguous;
186 // MDRangePolicy's default iteration makes the last index fastest on host.
187 auto policy = Kokkos::MDRangePolicy<ExecutionSpace,Kokkos::Rank<4>>({0,0,0,0},{aSpan,numPoints,Cw,N});
188
189 Kokkos::parallel_for("pointDataMultiply", policy,
190 KOKKOS_LAMBDA(const ordinal_type &a, const ordinal_type &point, const ordinal_type &cell, const ordinal_type &n)
191 {
192 // layout left for A, B, C
193 const size_t dataCell = (numDataCells == 1) ? 0 : size_t(cell + startCell);
194 const size_t strideA = size_t(aSpan) * numPoints * numDataCells; // stride in b
195 const Scalar* entryA = A + dataCell + (point + size_t(a) * numPoints) * numDataCells; // (C,P,Da,Db)
196 const Scalar* entryB = B + point + (size_t(n) + size_t(cell) * N) * bSpan * numPoints; // (P[,Db],N,Cw)
197 Scalar value = 0;
198 for (int b=0; b<bSpan; b++)
199 {
200 value += *entryA * *entryB;
201 entryA += strideA;
202 entryB += numPoints;
203 }
204 C[n + (size_t(cell) + (point + size_t(a) * numPoints) * Cw) * N] = value; // (N,Cw,P[,Da])
205 });
206 }
207
209 template<typename DeviceType,class Scalar>
211 const TensorData<Scalar,DeviceType> &pointWeights)
212 {
213 auto cellDimInfo = composedTransform.getDimensionInfo(0); // cell dimension
214 int numTensorComponents = pointWeights.numTensorComponents();
215 if (pointWeights.separateFirstComponent())
216 {
217 auto cellDimInfo_points = pointWeights.getTensorComponent(0).getDimensionInfo(0);
218 cellDimInfo = combinedDimensionInfo(cellDimInfo, cellDimInfo_points);
219 }
220 else
221 {
222 for (int r=0; r<numTensorComponents; r++)
223 {
224 auto cellDimInfo_r = pointWeights.getTensorComponent(r).getDimensionInfo(0);
225 cellDimInfo = combinedDimensionInfo(cellDimInfo, cellDimInfo_r);
226 }
227 }
228
229 int numPoints = composedTransform.extent_int(1);
230 DimensionInfo pointDimInfo {numPoints,GENERAL,numPoints,numPoints,-1};
231
232 if (composedTransform.rank() == 2)
233 {
234 return Data<Scalar,DeviceType>({cellDimInfo,pointDimInfo});
235 }
236 else if (composedTransform.rank() == 3)
237 {
238 auto D1DimInfo = composedTransform.getDimensionInfo(2);
239 return Data<Scalar,DeviceType>({cellDimInfo,pointDimInfo,D1DimInfo});
240 }
241 else if (composedTransform.rank() == 4)
242 {
243 auto D1DimInfo = composedTransform.getDimensionInfo(2);
244 auto D2DimInfo = composedTransform.getDimensionInfo(3);
245 return Data<Scalar,DeviceType>({cellDimInfo,pointDimInfo,D1DimInfo,D2DimInfo});
246 }
247 else
248 {
249 INTREPID2_TEST_FOR_EXCEPTION(true, std::invalid_argument, "unsupported rank for composedTransform");
250 }
251 }
252
254 template<typename DeviceType, class Scalar, class OpDataType>
255 Kokkos::View<Scalar*,DeviceType> pack1DOperator(const OpDataType &opData, const bool transposeToPoints)
256 {
257 using ExecutionSpace = typename DeviceType::execution_space;
258 const int opFields = opData.extent_int(0);
259 const int opPoints = opData.extent_int(1);
260 Kokkos::View<Scalar*,DeviceType> opView(transposeToPoints ? "rightOp 1D view" : "leftOp 1D view", opData.size());
261 if (opData.rank() == 2) // (F,P)
262 {
263 auto policy = Kokkos::MDRangePolicy<ExecutionSpace,Kokkos::Rank<2>>({0,0},{opFields,opPoints});
264 Kokkos::parallel_for("pack 1D opView", policy,
265 KOKKOS_LAMBDA(const int &field, const int &pt)
266 {
267 const int idx = transposeToPoints ? pt + field * opPoints : field + pt * opFields;
268 opView(idx) = opData(field,pt);
269 });
270 }
271 else if (opData.rank() == 3) // (F,P,D)
272 {
273 const int opDim = opData.extent_int(2);
274 auto policy = Kokkos::MDRangePolicy<ExecutionSpace,Kokkos::Rank<3>>({0,0,0},{opFields,opPoints,opDim});
275 Kokkos::parallel_for("pack 1D opView", policy,
276 KOKKOS_LAMBDA(const int &field, const int &pt, const int &d)
277 {
278 const int idx = transposeToPoints ? d + (pt + field * opPoints) * opDim : field + (pt + d * opPoints) * opFields;
279 opView(idx) = opData(field,pt,d);
280 });
281 }
282 else
283 {
284 INTREPID2_TEST_FOR_EXCEPTION(true, std::invalid_argument, "PAMatrix: Unsupported component operator rank");
285 }
286 return opView;
287 }
288} // namespace Impl
289
291{
292 static const PAMatrixAssemblyOptions options = []()
293 {
295 if (const char *value = std::getenv("INTREPID2_PAMATRIX_ASSEMBLE_UNIT_COLUMNS"))
296 {
297 if (std::string(value) != "0") result.algorithm = Algorithm::UnitColumns;
298 }
299 if (const char *value = std::getenv("INTREPID2_PAMATRIX_ASSEMBLE_ALGORITHM"))
300 {
301 const std::string algorithm(value);
302 if (algorithm == "automatic") result.algorithm = Algorithm::Automatic;
303 else if (algorithm == "unit-columns") result.algorithm = Algorithm::UnitColumns;
304 else if (algorithm == "apply") result.algorithm = Algorithm::ApplyToColumns;
305 else TEUCHOS_TEST_FOR_EXCEPTION(true, std::invalid_argument,
306 "INTREPID2_PAMATRIX_ASSEMBLE_ALGORITHM must be automatic, unit-columns, or apply; got '" << algorithm << "'");
307 }
308 if (const char *value = std::getenv("INTREPID2_PAMATRIX_ASSEMBLE_WORKSPACE_MB"))
309 {
310 result.workspaceMB = Impl::parsePositiveEnvironmentNumber("INTREPID2_PAMATRIX_ASSEMBLE_WORKSPACE_MB", value);
311 }
312 if (const char *value = std::getenv("INTREPID2_PAMATRIX_ASSEMBLE_SPARSE_LAST"))
313 {
314 const std::string setting(value);
315 if (setting == "automatic") result.sparseLastStage = SparseLastStage::Automatic;
316 else if (setting == "1") result.sparseLastStage = SparseLastStage::Always;
317 else if (setting == "0") result.sparseLastStage = SparseLastStage::Never;
318 else TEUCHOS_TEST_FOR_EXCEPTION(true, std::invalid_argument,
319 "INTREPID2_PAMATRIX_ASSEMBLE_SPARSE_LAST must be automatic, 1, or 0; got '" << setting << "'");
320 }
321 return result;
322 }();
323 return options;
324}
325
327template<class Scalar>
328ordinal_type pamatrixWorksetSize(const double budgetMB, const size_t perCellEntries, const ordinal_type numCells)
329{
330 INTREPID2_TEST_FOR_EXCEPTION(!(budgetMB > 0), std::invalid_argument, "PAMatrix workspace budget must be positive");
331 const double budgetBytes = budgetMB * 1024.0 * 1024.0;
332 const double cellsInBudget = budgetBytes / (double(sizeof(Scalar)) * double(std::max<size_t>(perCellEntries, 1)));
333 const double cells = std::min(double(numCells), std::floor(cellsInBudget));
334 return std::max<ordinal_type>(1, ordinal_type(cells));
335}
336
337template<typename DeviceType,class Scalar>
340 const TransformedBasisValues<Scalar,DeviceType> basisValuesRight,
341 const ScalarView<Orientation,DeviceType> orientations,
342 const BasisPtrType basisLeft,
343 const BasisPtrType basisRight)
344:
345_cellMeasures(cellMeasures),
346_basisValuesLeft(basisValuesLeft),
347_basisValuesRight(basisValuesRight),
348_orientations(orientations),
349_basisLeft(basisLeft),
350_basisRight(basisRight)
351{
352 init(basisValuesLeft, cellMeasures, basisValuesRight, orientations);
353} // PAMatrix()
354
355template<typename DeviceType,class Scalar>
358 const ScalarView<Orientation,DeviceType> orientations,
359 const BasisPtrType basis)
360:
361PAMatrix<DeviceType,Scalar>(basisValues,cellMeasures,basisValues,orientations,basis,basis)
362{}
363
364template<typename DeviceType,class Scalar>
365void PAMatrix<DeviceType,Scalar>::init(const TransformedBasisValues<Scalar,DeviceType> basisValuesLeftInput,
366 const TensorData<Scalar,DeviceType> cellMeasures,
367 const TransformedBasisValues<Scalar,DeviceType> basisValuesRightInput,
368 const ScalarView<Orientation,DeviceType> orientations) {
369 using ExecutionSpace = typename DeviceType::execution_space;
370
371 // orientations matter only if some cell is not aligned to the reference
372 _hasNontrivialOrientations = false;
373 if (orientations.size() > 0)
374 {
375 INTREPID2_TEST_FOR_EXCEPTION(orientations.extent_int(0) != basisValuesLeftInput.numCells(), std::invalid_argument,
376 "PAMatrix: orientations must have one entry per cell");
377 int numNotAligned = 0;
378 Kokkos::parallel_reduce("PAMatrix: count non-aligned orientations", Kokkos::RangePolicy<ExecutionSpace>(0, orientations.extent_int(0)),
379 KOKKOS_LAMBDA(const int &cell, int &count) {
380 if (!orientations(cell).isAlignedToReference()) count++;
381 }, numNotAligned);
382 _hasNontrivialOrientations = (numNotAligned > 0);
383 }
384 INTREPID2_TEST_FOR_EXCEPTION(_hasNontrivialOrientations && ((_basisLeft == Teuchos::null) || (_basisRight == Teuchos::null)),
385 std::invalid_argument, "PAMatrix: the left and right bases must be provided when orientations are not aligned to the reference");
386
387 // Ordinal filters (used for Serendipity bases) select a subset of the fields of an underlying tensor basis. The
388 // component integrals below are set up for the unfiltered (full tensor) bases; the filters are applied when results are
389 // written (see assemble()).
390 leftOrdinalFilter_ = basisValuesLeftInput .basisValues().ordinalFilter();
391 rightOrdinalFilter_ = basisValuesRightInput.basisValues().ordinalFilter();
392 auto unfiltered = [](const TransformedBasisValues<Scalar,DeviceType> &values) {
393 if (values.basisValues().ordinalFilter().extent_int(0) == 0) return values;
394 BasisValues<Scalar,DeviceType> unfilteredValues = values.basisValues();
395 unfilteredValues.setOrdinalFilter(Kokkos::View<ordinal_type*,DeviceType>());
396 return values.transform().isValid() ? TransformedBasisValues<Scalar,DeviceType>(values.transform(), unfilteredValues)
397 : TransformedBasisValues<Scalar,DeviceType>(values.numCells(), unfilteredValues);
398 };
399 const TransformedBasisValues<Scalar,DeviceType> basisValuesLeft = unfiltered(basisValuesLeftInput);
400 const TransformedBasisValues<Scalar,DeviceType> basisValuesRight = unfiltered(basisValuesRightInput);
401 numUnfilteredFieldsLeft_ = basisValuesLeft .numFields();
402 numUnfilteredFieldsRight_ = basisValuesRight.numFields();
403 INTREPID2_TEST_FOR_EXCEPTION(hasOrdinalFilter() && _hasNontrivialOrientations, std::invalid_argument,
404 "PAMatrix does not yet support ordinal filters together with orientations that are not aligned to the reference");
405
406 const int spaceDim = basisValuesLeft.spaceDim();
407
408 // MARK: checks for supported construction
409 INTREPID2_TEST_FOR_EXCEPTION(basisValuesLeft.spaceDim() != basisValuesRight.spaceDim(), std::invalid_argument, "basisValuesLeft and basisValuesRight must agree on the space dimension");
410 INTREPID2_TEST_FOR_EXCEPTION(basisValuesLeft.numCells() != basisValuesRight.numCells(), std::invalid_argument, "basisValuesLeft and basisValuesRight must agree on the number of cells");
411 INTREPID2_TEST_FOR_EXCEPTION((cellMeasures.rank() != 2) || (cellMeasures.extent_int(0) != basisValuesLeft.numCells()) || (cellMeasures.extent_int(1) != basisValuesLeft.numPoints()),
412 std::invalid_argument, "cellMeasures must have shape (C,P), matching the basis values");
413 if (_hasNontrivialOrientations)
414 {
415 INTREPID2_TEST_FOR_EXCEPTION(_basisLeft ->getCardinality() != basisValuesLeft .numFields(), std::invalid_argument, "PAMatrix: basisLeft cardinality does not match basisValuesLeft");
416 INTREPID2_TEST_FOR_EXCEPTION(_basisRight->getCardinality() != basisValuesRight.numFields(), std::invalid_argument, "PAMatrix: basisRight cardinality does not match basisValuesRight");
417 }
418
419 const int leftFamilyCount = basisValuesLeft.basisValues().numFamilies();
420 const int rightFamilyCount = basisValuesRight.basisValues().numFamilies();
421
422 // we require that the number of tensor components in the vectors is the same for each vector entry
423 // this is not strictly necessary, but it makes implementation easier, and we don't at present anticipate other use cases
424 int numTensorComponentsLeft = -1;
425 const bool leftIsVectorValued = basisValuesLeft.vectorData().isValid();
426
427 if (leftIsVectorValued)
428 {
429 const auto &refVectorLeft = basisValuesLeft.vectorData();
430 int numFamiliesLeft = refVectorLeft.numFamilies();
431 int numVectorComponentsLeft = refVectorLeft.numComponents();
432 for (int familyOrdinal=0; familyOrdinal<numFamiliesLeft; familyOrdinal++)
433 {
434 for (int vectorComponent=0; vectorComponent<numVectorComponentsLeft; vectorComponent++)
435 {
436 const TensorData<Scalar,DeviceType> &tensorData = refVectorLeft.getComponent(familyOrdinal,vectorComponent);
437 if (tensorData.numTensorComponents() > 0)
438 {
439 if (numTensorComponentsLeft == -1)
440 {
441 numTensorComponentsLeft = tensorData.numTensorComponents();
442 }
443 INTREPID2_TEST_FOR_EXCEPTION(numTensorComponentsLeft != tensorData.numTensorComponents(), std::invalid_argument, "Each valid entry in basisValuesLeft must have the same number of tensor components as every other");
444 }
445 }
446 }
447 }
448 else
449 {
450 numTensorComponentsLeft = basisValuesLeft.basisValues().tensorData(0).numTensorComponents(); // family ordinal 0
451 for (int familyOrdinal = 0; familyOrdinal < leftFamilyCount; familyOrdinal++)
452 {
453 INTREPID2_TEST_FOR_EXCEPTION(basisValuesLeft.basisValues().tensorData(familyOrdinal).numTensorComponents() != numTensorComponentsLeft, std::invalid_argument, "All families must match in the number of tensor components");
454 }
455 }
456 int numTensorComponentsRight = -1;
457 const bool rightIsVectorValued = basisValuesRight.vectorData().isValid();
458
459 if (rightIsVectorValued)
460 {
461 const auto &refVectorRight = basisValuesRight.vectorData();
462 int numFamiliesRight = refVectorRight.numFamilies();
463 int numVectorComponentsRight = refVectorRight.numComponents();
464 for (int familyOrdinal=0; familyOrdinal<numFamiliesRight; familyOrdinal++)
465 {
466 for (int vectorComponent=0; vectorComponent<numVectorComponentsRight; vectorComponent++)
467 {
468 const auto &tensorData = refVectorRight.getComponent(familyOrdinal,vectorComponent);
469 if (tensorData.numTensorComponents() > 0)
470 {
471 if (numTensorComponentsRight == -1)
472 {
473 numTensorComponentsRight = tensorData.numTensorComponents();
474 }
475 INTREPID2_TEST_FOR_EXCEPTION(numTensorComponentsRight != tensorData.numTensorComponents(), std::invalid_argument, "Each valid entry in basisValuesRight must have the same number of tensor components as every other");
476 }
477 }
478 }
479 INTREPID2_TEST_FOR_EXCEPTION(numTensorComponentsRight != numTensorComponentsLeft, std::invalid_argument, "Right families must match left in the number of tensor components");
480 }
481 else
482 {
483 // check that right tensor component count agrees with left
484 for (int familyOrdinal=0; familyOrdinal< rightFamilyCount; familyOrdinal++)
485 {
486 INTREPID2_TEST_FOR_EXCEPTION(basisValuesRight.basisValues().tensorData(familyOrdinal).numTensorComponents() != numTensorComponentsLeft, std::invalid_argument, "Right families must match left in the number of tensor components");
487 }
488 }
489
490 {
491 // MARK: prepare composed transformation matrices
492 const Data<Scalar,DeviceType> & leftTransform = basisValuesLeft.transform();
493 const Data<Scalar,DeviceType> & rightTransform = basisValuesRight.transform();
494 const bool transposeLeft = true;
495 const bool transposeRight = false;
496 // transforms can be matrices -- (C,P,D,D): rank 4 -- or scalar weights -- (C,P): rank 2 -- or vector weights -- (C,P,D): rank 3
497 Data<Scalar,DeviceType> composedTransform;
498 // invalid/empty transforms are used when the identity is intended.
499 const int leftRank = leftTransform.rank();
500 const int rightRank = rightTransform.rank();
501
502 if (leftTransform.isValid() && rightTransform.isValid())
503 {
504 const bool bothRank4 = (leftRank == 4) && (rightRank == 4);
505 const bool bothRank3 = (leftRank == 3) && (rightRank == 3);
506 const bool bothRank2 = (leftRank == 2) && (rightRank == 2);
507 const bool ranks32 = ((leftRank == 3) && (rightRank == 2)) || ((leftRank == 2) && (rightRank == 3));
508 const bool ranks42 = ((leftRank == 4) && (rightRank == 2)) || ((leftRank == 2) && (rightRank == 4));
509
510 if (bothRank4) // (C,P,D,D)
511 {
512 composedTransform = Data<Scalar,DeviceType>::allocateMatMatResult(transposeLeft, leftTransform, transposeRight, rightTransform);
513 composedTransform.storeMatMat(transposeLeft, leftTransform, transposeRight, rightTransform);
514 }
515 else if (bothRank3) // (C,P,D)
516 {
517 // re-cast leftTransform as a rank 4 (C,P,1,D) object -- a 1 x D matrix at each (C,P).
518 const int newRank = 4;
519 auto extents = leftTransform.getExtents();
520 auto variationTypes = leftTransform.getVariationTypes();
521 extents[3] = extents[2];
522 extents[2] = 1;
523 variationTypes[3] = variationTypes[2];
524 variationTypes[2] = CONSTANT;
525 auto leftTransformMatrix = leftTransform.shallowCopy(newRank, extents, variationTypes);
526
527 // re-cast rightTransform as a rank 4 (C,P,1,D) object -- a 1 x D matrix at each (C,P)
528 extents = rightTransform.getExtents();
529 variationTypes = rightTransform.getVariationTypes();
530 extents[3] = extents[2];
531 extents[2] = 1;
532 variationTypes[3] = variationTypes[2];
533 variationTypes[2] = CONSTANT;
534 auto rightTransformMatrix = rightTransform.shallowCopy(newRank, extents, variationTypes);
535
536 composedTransform = Data<Scalar,DeviceType>::allocateMatMatResult(transposeLeft, leftTransformMatrix, transposeRight, rightTransformMatrix);
537 composedTransform.storeMatMat(transposeLeft, leftTransformMatrix, transposeRight, rightTransformMatrix);
538 }
539 else if (bothRank2)
540 {
541 composedTransform = leftTransform.allocateInPlaceCombinationResult(leftTransform, rightTransform);
542 composedTransform.storeInPlaceProduct(leftTransform, rightTransform);
543
544 // re-cast composedTranform as a rank 4 (C,P,1,1) object -- a 1 x 1 matrix at each (C,P).
545 const int newRank = 4;
546 auto extents = composedTransform.getExtents();
547 auto variationTypes = composedTransform.getVariationTypes();
548 composedTransform = composedTransform.shallowCopy(newRank, extents, variationTypes);
549 }
550 else if (ranks32) // rank 2 / rank 3 combination.
551 {
552 const auto & rank3Transform = (leftRank == 3) ? leftTransform : rightTransform;
553 const auto & rank2Transform = (leftRank == 2) ? leftTransform : rightTransform;
554
555 composedTransform = DataTools::multiplyByCPWeights(rank3Transform, rank2Transform);
556
557 // re-cast composedTransform as a rank 4 object:
558 // logically, the original rank-3 transform can be understood as a 1xD matrix. The composed transform is leftTransform^T * rightTransform, so:
559 // - if left has the rank-3 transform, composedTransform should be a (C,P,D,1) object -- a D x 1 matrix at each (C,P).
560 // - if right has the rank-3 transform, composedTransform should be a (C,P,1,D) object -- a 1 x D matrix at each (C,P).
561 const int newRank = 4;
562 auto extents = composedTransform.getExtents();
563 auto variationTypes = composedTransform.getVariationTypes();
564 if (leftRank != 3)
565 {
566 // (if left has the rank-3 transform, extents[3] and variationTypes[3] will already be 1 and CONSTANT)
567 extents[3] = extents[2];
568 extents[2] = 1;
569 variationTypes[3] = variationTypes[2];
570 variationTypes[2] = CONSTANT;
571 }
572 composedTransform = composedTransform.shallowCopy(newRank, extents, variationTypes);
573 }
574 else if (ranks42) // rank 4 / rank 2 combination.
575 {
576 if (leftRank == 4)
577 {
578 // want to transpose left matrix, and multiply by the values from rightTransform
579 // start with the multiplication:
580 auto composedTransformTransposed = DataTools::multiplyByCPWeights(leftTransform, rightTransform);
581 composedTransform = DataTools::transposeMatrix(composedTransformTransposed);
582 }
583 else // (leftRank == 2)
584 {
585 composedTransform = DataTools::multiplyByCPWeights(rightTransform, leftTransform);
586 }
587 }
588 else
589 {
590 INTREPID2_TEST_FOR_EXCEPTION(true, std::invalid_argument, "Unsupported transform combination");
591 }
592 }
593 else if (leftTransform.isValid())
594 {
595 // rightTransform is the identity
596 switch (leftRank)
597 {
598 case 4: composedTransform = DataTools::transposeMatrix(leftTransform); break;
599 case 3:
600 {
601 // - if left has the rank-3 transform, composedTransform should be a (C,P,D,1) object -- a D x 1 matrix at each (C,P).
602 const int newRank = 4;
603 auto extents = leftTransform.getExtents();
604 auto variationTypes = leftTransform.getVariationTypes();
605
606 composedTransform = leftTransform.shallowCopy(newRank, extents, variationTypes);
607 }
608 break;
609 case 2: composedTransform = leftTransform; break;
610 default:
611 INTREPID2_TEST_FOR_EXCEPTION(true, std::invalid_argument, "Unsupported transform combination");
612 }
613 }
614 else if (rightTransform.isValid())
615 {
616 // leftTransform is the identity
617 switch (rightRank)
618 {
619 case 4: composedTransform = rightTransform; break;
620 case 3:
621 {
622 // - if right has the rank-3 transform, composedTransform should be a (C,P,1,D) object -- a 1 x D matrix at each (C,P).
623 const int newRank = 4;
624 auto extents = rightTransform.getExtents();
625 auto variationTypes = rightTransform.getVariationTypes();
626 extents[3] = extents[2];
627 variationTypes[3] = variationTypes[2];
628 extents[2] = 1;
629 variationTypes[2] = CONSTANT;
630
631 composedTransform = rightTransform.shallowCopy(newRank, extents, variationTypes);
632 }
633 break;
634 case 2: composedTransform = rightTransform; break;
635 default:
636 INTREPID2_TEST_FOR_EXCEPTION(true, std::invalid_argument, "Unsupported transform combination");
637 }
638 }
639 else
640 {
641 // both left and right transforms are identity
642 Kokkos::Array<ordinal_type,4> extents {basisValuesLeft.numCells(),basisValuesLeft.numPoints(),spaceDim,spaceDim};
643 Kokkos::Array<DataVariationType,4> variationTypes {CONSTANT,CONSTANT,BLOCK_PLUS_DIAGONAL,BLOCK_PLUS_DIAGONAL};
644
645 Kokkos::View<Scalar*,DeviceType> identityUnderlyingView("Intrepid2::PAMatrix - identity view",spaceDim);
646 Kokkos::deep_copy(identityUnderlyingView, 1.0);
647 composedTransform = Data<Scalar,DeviceType>(identityUnderlyingView,extents,variationTypes);
648 }
649 // allocate weighted transform
650 _composedWeightedTransform = Impl::allocateComposedWeightedTransform<DeviceType,Scalar>(composedTransform,cellMeasures);
651 auto composedWeightedTransform = _composedWeightedTransform; // avoid implicit reference to this
652 // MARK: fill weighted transform container
653 int rank = composedWeightedTransform.rank();
654 int cellDataExtent = composedWeightedTransform.getDataExtent(0);
655 int numPoints = composedWeightedTransform.getDataExtent(1);
656 int d1_dim = composedWeightedTransform.getDataExtent(2);
657 int d2_dim = composedWeightedTransform.getDataExtent(3);
658 auto d1_variationType = composedWeightedTransform.getVariationTypes()[2];
659
660 if (rank == 2)
661 {
662 Kokkos::Array<int,2> lowerBounds {0,0};
663 Kokkos::Array<int,2> upperBounds {cellDataExtent,numPoints};
664 auto policy = Kokkos::MDRangePolicy<ExecutionSpace,Kokkos::Rank<2>>(lowerBounds, upperBounds);
665
666 Kokkos::parallel_for("compute weighted transform", policy,
667 KOKKOS_LAMBDA (const int &cellDataOrdinal, const int &pointOrdinal) {
668 const Scalar & w = cellMeasures(cellDataOrdinal, pointOrdinal);
669 Scalar & result = composedWeightedTransform.getWritableEntry(cellDataOrdinal,pointOrdinal);
670 result = w * composedTransform(cellDataOrdinal,pointOrdinal);
671 });
672 }
673 else if ((rank == 3) || ((rank == 4) && (d1_variationType == BLOCK_PLUS_DIAGONAL)))
674 {
675 Kokkos::Array<int,3> lowerBounds {0,0,0};
676 Kokkos::Array<int,3> upperBounds {cellDataExtent,numPoints,d1_dim};
677 bool passThroughMatrixDims = (d1_variationType == BLOCK_PLUS_DIAGONAL); // if BLOCK_PLUS_DIAGONAL, it's a matrix, but everything is packed into the D1 dimension, and we want to sidestep the logic that tries to compute the matrix entry index based on (d1,d2) arguments.
678 auto policy = Kokkos::MDRangePolicy<ExecutionSpace,Kokkos::Rank<3>>(lowerBounds, upperBounds);
679
680 Kokkos::parallel_for("compute weighted transform", policy,
681 KOKKOS_LAMBDA (const int &cellDataOrdinal, const int &pointOrdinal, const int &d1) {
682 const Scalar & w = cellMeasures(cellDataOrdinal, pointOrdinal);
683 Scalar & result = composedWeightedTransform.getWritableEntryWithPassThroughOption(passThroughMatrixDims,cellDataOrdinal,pointOrdinal,d1);
684 result = w * composedTransform.getEntryWithPassThroughOption(passThroughMatrixDims,cellDataOrdinal,pointOrdinal,d1);
685 });
686 }
687 else if (rank == 4)
688 {
689 Kokkos::Array<int,4> lowerBounds {0,0,0,0};
690 Kokkos::Array<int,4> upperBounds {cellDataExtent,numPoints,d1_dim,d2_dim};
691 auto policy = Kokkos::MDRangePolicy<ExecutionSpace,Kokkos::Rank<4>>(lowerBounds, upperBounds);
692
693 Kokkos::parallel_for("compute weighted transform", policy,
694 KOKKOS_LAMBDA (const int &cellDataOrdinal, const int &pointOrdinal, const int &d1, const int &d2) {
695 const Scalar & w = cellMeasures(cellDataOrdinal, pointOrdinal);
696 Scalar & result = composedWeightedTransform.getWritableEntry(cellDataOrdinal,pointOrdinal,d1,d2);
697 const Scalar & originalTransform = composedTransform(cellDataOrdinal,pointOrdinal,d1,d2);
698 result = w * originalTransform;
699 });
700 }
701 }
702
703 // MARK: Set up component integrations
704 const int leftComponentCount = leftIsVectorValued ? basisValuesLeft. vectorData().numComponents() : 1;
705 const int rightComponentCount = rightIsVectorValued ? basisValuesRight.vectorData().numComponents() : 1;
706
707 // The 1D operators are packed once per distinct underlying view, so that passes sharing a component operator share
708 // the packed view (assemble() groups passes by operator identity). Left operators are packed (F,P[,D]); right ones (P[,D],F).
709 std::map<std::tuple<const void*, size_t, bool>, View1D> packedOperators;
710 auto packedOperator = [&](const auto &opData, const bool isRight) -> View1D
711 {
712 const auto key = std::make_tuple(static_cast<const void*>(opData.data()), size_t(opData.size()), isRight);
713 auto entry = packedOperators.find(key);
714 if (entry != packedOperators.end()) return entry->second;
715 View1D opView = Impl::pack1DOperator<DeviceType,Scalar>(opData, isRight);
716 packedOperators[key] = opView;
717 return opView;
718 };
719
720 const int numCells = _composedWeightedTransform.extent_int(0);
721 const int numPoints = _composedWeightedTransform.extent_int(1);
722
723 int leftFieldOrdinalOffset = 0; // keeps track of the number of fields in prior families
724 for (int leftFamilyOrdinal=0; leftFamilyOrdinal<leftFamilyCount; leftFamilyOrdinal++)
725 {
726 const int leftFieldSpan = leftIsVectorValued ? basisValuesLeft.vectorData() .numFieldsInFamily(leftFamilyOrdinal)
727 : basisValuesLeft.basisValues().numFieldsInFamily(leftFamilyOrdinal);
728
729 // "a" keeps track of the spatial dimension over which we are integrating in the left vector.
730 // Components are allowed to span several dimensions; we keep track of the offset for the component in a_offset
731 int a_offset = 0;
732 for (int leftComponentOrdinal=0; leftComponentOrdinal<leftComponentCount; leftComponentOrdinal++)
733 {
734 TensorData<Scalar,DeviceType> leftComponent = leftIsVectorValued ? basisValuesLeft.vectorData().getComponent(leftFamilyOrdinal, leftComponentOrdinal)
735 : basisValuesLeft.basisValues().tensorData(leftFamilyOrdinal);
736 if (!leftComponent.isValid())
737 {
738 // represents zero
739 a_offset += basisValuesLeft.vectorData().numDimsForComponent(leftComponentOrdinal);
740 continue;
741 }
742 // left operators contract in the point (and space) dimensions
743 std::vector<OpSpec> leftOperators;
744 for (int r=0; r<leftComponent.numTensorComponents(); r++)
745 {
746 const auto opData = leftComponent.getTensorComponent(r).getUnderlyingView();
747 leftOperators.push_back({packedOperator(opData, false), opData.extent_int(0), opData.extent_int(1)});
748 }
749
750 int rightFieldOrdinalOffset = 0; // keeps track of the number of fields in prior families
751 for (int rightFamilyOrdinal=0; rightFamilyOrdinal<rightFamilyCount; rightFamilyOrdinal++)
752 {
753 const int rightFieldSpan = rightIsVectorValued ? basisValuesRight.vectorData() .numFieldsInFamily(rightFamilyOrdinal)
754 : basisValuesRight.basisValues().numFieldsInFamily(rightFamilyOrdinal);
755 // "b" keeps track of the spatial dimension over which we are integrating in the right vector
756 // components are allowed to span several dimensions; we keep track of the offset for the component in b_offset
757 int b_offset = 0;
758 for (int rightComponentOrdinal=0; rightComponentOrdinal<rightComponentCount; rightComponentOrdinal++)
759 {
760 TensorData<Scalar,DeviceType> rightComponent =
761 rightIsVectorValued ? basisValuesRight.vectorData().getComponent(rightFamilyOrdinal, rightComponentOrdinal)
762 : basisValuesRight.basisValues().tensorData(rightFamilyOrdinal);
763 if (!rightComponent.isValid())
764 {
765 // represents zero
766 b_offset += basisValuesRight.vectorData().numDimsForComponent(rightComponentOrdinal);
767 continue;
768 }
769
770 INTREPID2_TEST_FOR_EXCEPTION(leftComponent.numTensorComponents() != rightComponent.numTensorComponents(), std::invalid_argument, "left TensorData and right TensorData have different number of tensor components. This is not supported.");
771
772 // right operators contract in the field dimension
773 std::vector<OpSpec> rightOperators;
774 for (int r=0; r<rightComponent.numTensorComponents(); r++)
775 {
776 const auto opData = rightComponent.getTensorComponent(r).getUnderlyingView();
777 rightOperators.push_back({packedOperator(opData, true), opData.extent_int(1), opData.extent_int(0)});
778 }
779
780 const int aSpan = leftComponent.extent_int(2);
781 const int bSpan = rightComponent.extent_int(2);
782
783 PointDataSpec pointDataSpec{numCells, numPoints, a_offset, b_offset, aSpan, bSpan};
784
785 if (_pointDataCache.find(pointDataSpec) == _pointDataCache.end())
786 {
787 const size_t pointDataSize = size_t(numCells) * numPoints * aSpan * bSpan;
788 View1D pointDataView("pointDataView", pointDataSize);
789
790 auto composedWeightedTransform = _composedWeightedTransform;
791
792 // layout left: (C,P[,Da[,Db]])
793 if (_composedWeightedTransform.rank() == 2) // (C,P): pointwise weight
794 {
795 auto policy = Kokkos::MDRangePolicy<ExecutionSpace,Kokkos::Rank<2>>({0,0},{numCells,numPoints});
796 Kokkos::parallel_for("pack 1D pointData", policy,
797 KOKKOS_LAMBDA(const int &cell, const int &pt)
798 {
799 pointDataView(cell + size_t(pt) * numCells) = composedWeightedTransform(cell,pt);
800 });
801 }
802 else if (_composedWeightedTransform.rank() == 3) // (C,P,D): contract in b or expand in a
803 {
804 const bool contraction = (bSpan > 1);
805 const int dOffset = contraction ? b_offset : a_offset;
806 const int dSpan = contraction ? bSpan : aSpan;
807 auto policy = Kokkos::MDRangePolicy<ExecutionSpace,Kokkos::Rank<3>>({0,0,0},{numCells,numPoints,dSpan});
808 Kokkos::parallel_for("pack 1D pointData", policy,
809 KOKKOS_LAMBDA(const int &cell, const int &pt, const int &d)
810 {
811 pointDataView(cell + (pt + size_t(d) * numPoints) * numCells) = composedWeightedTransform(cell,pt,dOffset + d);
812 });
813 }
814 else if (_composedWeightedTransform.rank() == 4) // (C,P,D,D): contract in b and expand in a at each point
815 {
816 auto policy = Kokkos::MDRangePolicy<ExecutionSpace,Kokkos::Rank<4>>({0,0,0,0},{numCells,numPoints,aSpan,bSpan});
817 Kokkos::parallel_for("pack 1D pointData", policy,
818 KOKKOS_LAMBDA(const int &cell, const int &pt, const int &da, const int &db)
819 {
820 pointDataView(cell + (pt + (da + size_t(db) * aSpan) * numPoints) * numCells) = composedWeightedTransform(cell,pt,a_offset + da,b_offset + db);
821 });
822 }
823 _pointDataCache[pointDataSpec] = pointDataView;
824 }
825 {
826 const int leftGroup = leftFamilyOrdinal * leftComponentCount + leftComponentOrdinal;
827 const int rightGroup = rightFamilyOrdinal * rightComponentCount + rightComponentOrdinal;
828 componentIntegralGroups_.push_back({leftGroup, rightGroup});
829 }
830 componentIntegralsToSum_.push_back({leftOperators,pointDataSpec,rightOperators,
831 leftFieldOrdinalOffset,leftFieldSpan,rightFieldOrdinalOffset,rightFieldSpan});
832
833 b_offset += rightIsVectorValued ? basisValuesRight.vectorData().numDimsForComponent(rightComponentOrdinal) : 1;
834 }
835 rightFieldOrdinalOffset += rightFieldSpan;
836 }
837 a_offset += leftIsVectorValued ? basisValuesLeft.vectorData().numDimsForComponent(leftComponentOrdinal) : 1;
838 }
839 leftFieldOrdinalOffset += leftFieldSpan;
840 }
841 ExecutionSpace().fence();
842
843 // set maxIntermediateSize_: the per-cell size required for intermediate computations, which is used to size the workspaces
844 const size_t F2 = basisValuesRight.numFields();
845 const size_t F1 = basisValuesLeft.numFields();
846 maxIntermediateSize_ = std::max(F1,F2);
847
848 for (const auto &entry : componentIntegralsToSum_)
849 {
850 const auto & leftOps = std::get<0>(entry);
851 const auto & pointDataSpec = std::get<1>(entry);
852 const auto & rightOps = std::get<2>(entry);
853
854 // per-cell sizes of the intermediates in apply(): the right input span, then each right contraction (from the last
855 // component), the point weighting, and each left contraction
856 size_t perCellSize = std::get<6>(entry);
857 for (int r=int(rightOps.size())-1; r>=0; r--)
858 {
859 perCellSize = perCellSize / rightOps[r].N * rightOps[r].M;
860 maxIntermediateSize_ = std::max(perCellSize,maxIntermediateSize_);
861 }
862
863 perCellSize = perCellSize / pointDataSpec.bSpan * pointDataSpec.aSpan;
864 maxIntermediateSize_ = std::max(perCellSize,maxIntermediateSize_);
865
866 for (int r=int(leftOps.size())-1; r>=0; r--)
867 {
868 perCellSize = perCellSize / leftOps[r].N * leftOps[r].M;
869 maxIntermediateSize_ = std::max(perCellSize,maxIntermediateSize_);
870 }
871 INTREPID2_TEST_FOR_EXCEPTION(perCellSize != size_t(std::get<4>(entry)), std::logic_error,
872 "PAMatrix: inconsistent component operator extents");
873 }
874}
875
876template<typename DeviceType,class Scalar>
878{
879 // Allocates a (C,F,F) container for storing integral data
880
881 // With ordinal filters (e.g., Serendipity), the stored basis values report the filtered field counts, which is the
882 // size of the matrix that assemble() produces.
883
884 // determine cellDataExtent and variation type. We currently support CONSTANT, MODULAR, and GENERAL as possible output variation types, depending on the inputs.
885 // If cellMeasures has non-trivial tensor structure, the rank-1 cell Data object is the first component.
886 // If cellMeasures has trivial tensor structure, then the first and only component has the cell index in its first dimension.
887 // I.e., either way the relevant Data object is cellMeasures.getTensorComponent(0)
888 const int CELL_DIM = 0;
889 const auto cellMeasureData = _cellMeasures.getTensorComponent(0);
890
891 DimensionInfo combinedCellDimInfo = cellMeasureData.getDimensionInfo(CELL_DIM);
892 // transforms may be invalid, indicating an identity transform. If so, it will not constrain the output at all.
893 if (_basisValuesLeft.transform().isValid())
894 {
895 combinedCellDimInfo = combinedDimensionInfo(combinedCellDimInfo, _basisValuesLeft.transform().getDimensionInfo(CELL_DIM));
896 }
897 if (_basisValuesRight.transform().isValid())
898 {
899 combinedCellDimInfo = combinedDimensionInfo(combinedCellDimInfo, _basisValuesRight.transform().getDimensionInfo(CELL_DIM));
900 }
901
902 DataVariationType cellVariationType = combinedCellDimInfo.variationType;
903 int cellDataExtent = combinedCellDimInfo.dataExtent;
904
905 const int numCells = _basisValuesLeft.numCells();
906 const int numFieldsLeft = _basisValuesLeft.numFields();
907 const int numFieldsRight = _basisValuesRight.numFields();
908
909 if (_hasNontrivialOrientations)
910 {
911 // orientations make the matrix cell-dependent even when geometry and weights are otherwise constant across cells
912 cellVariationType = GENERAL;
913 cellDataExtent = numCells;
914 }
915
916 Kokkos::Array<int,3> extents {numCells, numFieldsLeft, numFieldsRight};
917 Kokkos::Array<DataVariationType,3> variationTypes {cellVariationType,GENERAL,GENERAL};
918
919 if (cellVariationType != CONSTANT)
920 {
921 Kokkos::View<Scalar***,DeviceType> data("Intrepid2::PAMatrix matrix storage",cellDataExtent,numFieldsLeft,numFieldsRight);
922 return Data<Scalar,DeviceType>(data, extents, variationTypes);
923 }
924 else
925 {
926 Kokkos::View<Scalar**,DeviceType> data("Intrepid2::PAMatrix matrix storage",numFieldsLeft,numFieldsRight);
927 return Data<Scalar,DeviceType>(data, extents, variationTypes);
928 }
929} // allocateMatrixStorage()
930
931template<typename DeviceType,class Scalar>
933{
934 const int CELL_DIM = 0;
935 const auto cellMeasureData = _cellMeasures.getTensorComponent(0);
936
937 DimensionInfo combinedCellDimInfo = cellMeasureData.getDimensionInfo(CELL_DIM);
938 if (_basisValuesLeft.transform().isValid())
939 {
940 combinedCellDimInfo = combinedDimensionInfo(combinedCellDimInfo,
941 _basisValuesLeft.transform().getDimensionInfo(CELL_DIM));
942 }
943 if (_basisValuesRight.transform().isValid())
944 {
945 combinedCellDimInfo = combinedDimensionInfo(combinedCellDimInfo,
946 _basisValuesRight.transform().getDimensionInfo(CELL_DIM));
947 }
948
949 DataVariationType cellVariationType = combinedCellDimInfo.variationType;
950 int cellDataExtent = combinedCellDimInfo.dataExtent;
951
952 const int numCells = _basisValuesLeft.numCells();
953 const int numFieldsLeft = _basisValuesLeft.numFields();
954 const int numFieldsRight = _basisValuesRight.numFields();
955 const int numDiagonalEntries = std::min(numFieldsLeft, numFieldsRight);
956
957 if (_hasNontrivialOrientations)
958 {
959 cellVariationType = GENERAL;
960 cellDataExtent = numCells;
961 }
962
963 Kokkos::Array<int,2> extents {numCells, numDiagonalEntries};
964 Kokkos::Array<DataVariationType,2> variationTypes {cellVariationType, GENERAL};
965
966 if (cellVariationType != CONSTANT)
967 {
968 Kokkos::View<Scalar**,DeviceType> data("Intrepid2::PAMatrix diagonal storage", cellDataExtent, numDiagonalEntries);
969 return Data<Scalar,DeviceType>(data, extents, variationTypes);
970 }
971 else
972 {
973 Kokkos::View<Scalar*,DeviceType> data("Intrepid2::PAMatrix diagonal storage", numDiagonalEntries);
974 return Data<Scalar,DeviceType>(data, extents, variationTypes);
975 }
976}
977
978template<typename DeviceType,class Scalar>
980{
981 if (componentIntegralsToSum_.size() == 0) return false;
982 // the grouped paths share point buffers across passes, so all passes must have the same point count, number of
983 // tensor components, and cell count
984 const int numPoints = std::get<1>(componentIntegralsToSum_[0]).P;
985 const int numTensorComponents = int(std::get<2>(componentIntegralsToSum_[0]).size());
986 const int numCells = _basisValuesLeft.numCells();
987 for (const auto &integralTuple : componentIntegralsToSum_)
988 {
989 const auto &leftOps = std::get<0>(integralTuple);
990 const PointDataSpec &pointDataSpec = std::get<1>(integralTuple);
991 const auto &rightOps = std::get<2>(integralTuple);
992 const int leftSpan = std::get<4>(integralTuple);
993 const int rightSpan = std::get<6>(integralTuple);
994
995 if ((pointDataSpec.P != numPoints) || (int(rightOps.size()) != numTensorComponents) || (pointDataSpec.C != numCells)) return false;
996 if ((leftOps.size() != rightOps.size()) || (rightOps.size() == 0) ||
997 (rightOps.size() > 8) || (pointDataSpec.aSpan != 1) || (pointDataSpec.bSpan != 1))
998 {
999 return false;
1000 }
1001
1002 size_t rightFieldProduct = 1, pointProduct = 1, leftFieldProduct = 1, leftPointProduct = 1;
1003 for (size_t r=0; r<rightOps.size(); r++)
1004 {
1005 rightFieldProduct *= rightOps[r].N;
1006 pointProduct *= rightOps[r].M;
1007 leftFieldProduct *= leftOps[r].M;
1008 leftPointProduct *= leftOps[r].N;
1009 }
1010 if ((rightFieldProduct != size_t(rightSpan)) || (leftFieldProduct != size_t(leftSpan)) ||
1011 (pointProduct != size_t(pointDataSpec.P)) || (leftPointProduct != size_t(pointDataSpec.P)))
1012 {
1013 return false;
1014 }
1015 }
1016 return true;
1017}
1018
1020template<typename DeviceType,class Scalar>
1025
1042template<typename DeviceType,class Scalar>
1044{
1045 using ExecutionSpace = typename DeviceType::execution_space;
1046 using OrdView1D = Kokkos::View<ordinal_type*,DeviceType>;
1047
1048 const ordinal_type numFieldsLeft = _basisValuesLeft.numFields();
1049 const ordinal_type numFieldsRight = _basisValuesRight.numFields();
1050 const bool hasLeftFilter = leftOrdinalFilter_ .extent_int(0) > 0;
1051 const bool hasRightFilter = rightOrdinalFilter_.extent_int(0) > 0;
1052
1053 const int outputRank = integrals.getUnderlyingViewRank();
1054 INTREPID2_TEST_FOR_EXCEPTION((outputRank != 2) && (outputRank != 3), std::invalid_argument,
1055 "PAMatrix::assemble() supports only rank-2 or rank-3 underlying matrix storage");
1056 // only the cells for which the output stores data are computed (all, for rank-3 GENERAL storage; the first
1057 // getDataExtent(0) for MODULAR; one, for rank-2 storage, which is constant in the cell)
1058 const ordinal_type numCellsComputed = (outputRank == 3) ? integrals.getDataExtent(0) : 1;
1059
1060 const auto &passes = componentIntegralsToSum_;
1061 const int numPasses = int(passes.size());
1062 const int R = int(std::get<2>(passes[0]).size());
1063
1064 // full-ordinal row/column -> output row/column (or -1 if filtered out); with family offsets, a pass's full ordinal is
1065 // offset + (tensor ordinal within the family)
1066 auto hostLeftFilter = Kokkos::create_mirror_view_and_copy(Kokkos::HostSpace(), leftOrdinalFilter_);
1067 auto hostRightFilter = Kokkos::create_mirror_view_and_copy(Kokkos::HostSpace(), rightOrdinalFilter_);
1068 const ordinal_type numFullLeft = hasLeftFilter ? numUnfilteredFieldsLeft_ : numFieldsLeft;
1069 const ordinal_type numFullRight = hasRightFilter ? numUnfilteredFieldsRight_ : numFieldsRight;
1070 std::vector<ordinal_type> rowForFull(numFullLeft, -1), colForFull(numFullRight, -1);
1071 for (ordinal_type row=0; row<numFieldsLeft; row++) rowForFull[hasLeftFilter ? hostLeftFilter(row) : row] = row;
1072 for (ordinal_type col=0; col<numFieldsRight; col++) colForFull[hasRightFilter ? hostRightFilter(col) : col] = col;
1073
1074 // group passes by (left family span/offset, right family span/offset, last-component operator pair): within a group,
1075 // the last-stage contraction is shared. (init() packs each distinct 1D operator once, so operator identity can be
1076 // compared by pointer.)
1077 struct Group { std::vector<int> passes; };
1078 std::vector<Group> groups;
1079 {
1080 auto sameOp = [](const OpSpec &a, const OpSpec &b) { return (a.opView.data() == b.opView.data()) && (a.M == b.M) && (a.N == b.N); };
1081 for (int pass=0; pass<numPasses; pass++)
1082 {
1083 const auto &t = passes[pass];
1084 int found = -1;
1085 for (int g=0; g<int(groups.size()); g++)
1086 {
1087 const auto &u = passes[groups[g].passes[0]];
1088 if ((std::get<3>(t) == std::get<3>(u)) && (std::get<5>(t) == std::get<5>(u)) &&
1089 (std::get<4>(t) == std::get<4>(u)) && (std::get<6>(t) == std::get<6>(u)) &&
1090 sameOp(std::get<0>(t)[R-1], std::get<0>(u)[R-1]) && sameOp(std::get<2>(t)[R-1], std::get<2>(u)[R-1]))
1091 {
1092 bool sameShape = true;
1093 for (int r=0; r<R-1; r++)
1094 {
1095 sameShape = sameShape && (std::get<0>(t)[r].M == std::get<0>(u)[r].M) && (std::get<2>(t)[r].N == std::get<2>(u)[r].N);
1096 }
1097 if (sameShape) { found = g; break; }
1098 }
1099 }
1100 if (found < 0) { groups.push_back(Group()); found = int(groups.size()) - 1; }
1101 groups[found].passes.push_back(pass);
1102 }
1103 }
1104 bool anyGroupHasMultiplePasses = false;
1105 for (const auto &group : groups) anyGroupHasMultiplePasses = anyGroupHasMultiplePasses || (group.passes.size() > 1);
1106
1107 // per-group geometry: extents, and row/column offset tables over the pair (i,j) index space of the first R-1
1108 // components and the last component; output row = rowForFull[leftOffset + I], I = I_prefix + i_{R-1} * strideLast
1109 struct GroupLayout
1110 {
1111 int leftOffset, rightOffset;
1112 std::vector<int> F, G, Q; // per component
1113 size_t prefixPairs = 1; // prod_{r<R-1} F_r G_r
1114 int prefixLeft = 1, prefixRight = 1;
1115 View1D pairOpLast; // (Q_{R-1}, F_{R-1} G_{R-1})
1116 OrdView1D prefixRowOffset, prefixColOffset; // per prefix pair: I_prefix, J_prefix
1117 OrdView1D rowMap, colMap; // full ordinal within the family -> output row/column (or -1)
1118 };
1119 auto pairOperator = [](const OpSpec &leftOp, const OpSpec &rightOp) -> View1D
1120 {
1121 const int F = leftOp.M, Q = leftOp.N, Gn = rightOp.N;
1122 View1D P(Kokkos::view_alloc(Kokkos::WithoutInitializing, "PAMatrix assemble pair operator"), size_t(Q) * F * Gn);
1123 const auto Lop = leftOp.opView;
1124 const auto Rop = rightOp.opView;
1125 Kokkos::parallel_for("PAMatrix::assemble(): pair operator", Kokkos::MDRangePolicy<ExecutionSpace,Kokkos::Rank<3>>({0,0,0},{Q,F,Gn}),
1126 KOKKOS_LAMBDA(const ordinal_type &q, const ordinal_type &i, const ordinal_type &j) {
1127 P(q + (i + size_t(j) * F) * Q) = Lop(i + size_t(q) * F) * Rop(q + size_t(j) * Q);
1128 });
1129 return P;
1130 };
1131
1132 std::vector<GroupLayout> layouts(groups.size());
1133 // groups that share family offsets and component shapes have identical (c, prefix pairs, (i_{R-1} j_{R-1})) layouts,
1134 // so their dense last-stage results can be accumulated (beta = 1) before a single write
1135 std::vector<int> writeFamily(groups.size(), -1);
1136 int numWriteFamilies = 0;
1137 for (int g=0; g<int(groups.size()); g++)
1138 {
1139 const auto &t = passes[groups[g].passes[0]];
1140 auto &L = layouts[g];
1141 L.leftOffset = std::get<3>(t);
1142 L.rightOffset = std::get<5>(t);
1143 for (int r=0; r<R; r++)
1144 {
1145 L.F.push_back(std::get<0>(t)[r].M);
1146 L.Q.push_back(std::get<0>(t)[r].N);
1147 L.G.push_back(std::get<2>(t)[r].N);
1148 }
1149 for (int r=0; r<R-1; r++) { L.prefixPairs *= size_t(L.F[r]) * L.G[r]; L.prefixLeft *= L.F[r]; L.prefixRight *= L.G[r]; }
1150 OrdView1D rowOffsets("PAMatrix assemble prefix row offsets", L.prefixPairs), colOffsets("PAMatrix assemble prefix col offsets", L.prefixPairs);
1151 auto rowHost = Kokkos::create_mirror_view(rowOffsets);
1152 auto colHost = Kokkos::create_mirror_view(colOffsets);
1153 for (size_t pair=0; pair<L.prefixPairs; pair++)
1154 {
1155 size_t remainder = pair;
1156 int I = 0, J = 0, leftStride = 1, rightStride = 1;
1157 for (int r=0; r<R-1; r++)
1158 {
1159 const int ij = int(remainder % (size_t(L.F[r]) * L.G[r]));
1160 remainder /= (size_t(L.F[r]) * L.G[r]);
1161 I += (ij % L.F[r]) * leftStride;
1162 J += (ij / L.F[r]) * rightStride;
1163 leftStride *= L.F[r];
1164 rightStride *= L.G[r];
1165 }
1166 rowHost(pair) = I;
1167 colHost(pair) = J;
1168 }
1169 Kokkos::deep_copy(rowOffsets, rowHost);
1170 Kokkos::deep_copy(colOffsets, colHost);
1171 L.prefixRowOffset = rowOffsets;
1172 L.prefixColOffset = colOffsets;
1173 L.pairOpLast = pairOperator(std::get<0>(t)[R-1], std::get<2>(t)[R-1]);
1174
1175 // device copies of the full->output maps, offset to this group's family
1176 L.rowMap = OrdView1D("PAMatrix assemble row map", size_t(L.prefixLeft) * L.F[R-1]);
1177 L.colMap = OrdView1D("PAMatrix assemble col map", size_t(L.prefixRight) * L.G[R-1]);
1178 auto rowMapHost = Kokkos::create_mirror_view(L.rowMap);
1179 auto colMapHost = Kokkos::create_mirror_view(L.colMap);
1180 for (int I=0; I<L.prefixLeft*L.F[R-1]; I++) rowMapHost(I) = rowForFull[L.leftOffset + I];
1181 for (int J=0; J<L.prefixRight*L.G[R-1]; J++) colMapHost(J) = colForFull[L.rightOffset + J];
1182 Kokkos::deep_copy(L.rowMap, rowMapHost);
1183 Kokkos::deep_copy(L.colMap, colMapHost);
1184 }
1185 for (int g=0; g<int(groups.size()); g++)
1186 {
1187 for (int h=0; h<g; h++)
1188 {
1189 const auto &A = layouts[g], &B = layouts[h];
1190 if ((A.leftOffset == B.leftOffset) && (A.rightOffset == B.rightOffset) && (A.F == B.F) && (A.G == B.G))
1191 {
1192 writeFamily[g] = writeFamily[h];
1193 break;
1194 }
1195 }
1196 if (writeFamily[g] < 0) writeFamily[g] = numWriteFamilies++;
1197 }
1198 {
1199 // order the groups so that each write family's groups are contiguous: their dense last-stage GEMMs accumulate into a
1200 // single buffer, which another family's GEMM (beta = 0) must not overwrite before the family's result is written
1201 std::vector<int> order(groups.size());
1202 std::iota(order.begin(), order.end(), 0);
1203 std::stable_sort(order.begin(), order.end(), [&writeFamily](const int a, const int b) { return writeFamily[a] < writeFamily[b]; });
1204 std::vector<Group> sortedGroups;
1205 std::vector<GroupLayout> sortedLayouts;
1206 std::vector<int> sortedWriteFamily;
1207 for (const int g : order)
1208 {
1209 sortedGroups.push_back(groups[g]);
1210 sortedLayouts.push_back(layouts[g]);
1211 sortedWriteFamily.push_back(writeFamily[g]);
1212 }
1213 groups = sortedGroups;
1214 layouts = sortedLayouts;
1215 writeFamily = sortedWriteFamily;
1216 }
1217
1218 // Sparse-filter path: when few (row, column) pairs survive, compute each kept entry directly at the last stage.
1219 bool useSparseLast = false;
1220 {
1221 const bool hasFilter = hasLeftFilter || hasRightFilter;
1222 const double keptFraction = double(numFieldsLeft) * numFieldsRight / (double(numFullLeft) * numFullRight);
1223 switch (options.sparseLastStage)
1224 {
1225 case PAMatrixAssemblyOptions::SparseLastStage::Automatic: useSparseLast = hasFilter && (keptFraction < 0.25); break;
1226 case PAMatrixAssemblyOptions::SparseLastStage::Always: useSparseLast = hasFilter; break;
1227 case PAMatrixAssemblyOptions::SparseLastStage::Never: useSparseLast = false; break;
1228 }
1229 }
1230
1231 // kept (prefix pair, last-component (i,j)) -> output (row, col), per group, for the sparse last stage
1232 std::vector<OrdView1D> keptPairV(groups.size()), keptIJV(groups.size()), keptRowV(groups.size()), keptColV(groups.size());
1233 if (useSparseLast)
1234 {
1235 for (int g=0; g<int(groups.size()); g++)
1236 {
1237 const auto &L = layouts[g];
1238 const int FLast = L.F[R-1], GLast = L.G[R-1];
1239 std::vector<ordinal_type> keptPair, keptIJ, keptRow, keptCol;
1240 auto rowHost = Kokkos::create_mirror_view_and_copy(Kokkos::HostSpace(), L.rowMap);
1241 auto colHost = Kokkos::create_mirror_view_and_copy(Kokkos::HostSpace(), L.colMap);
1242 auto prefixRowHost = Kokkos::create_mirror_view_and_copy(Kokkos::HostSpace(), L.prefixRowOffset);
1243 auto prefixColHost = Kokkos::create_mirror_view_and_copy(Kokkos::HostSpace(), L.prefixColOffset);
1244 for (size_t pair=0; pair<L.prefixPairs; pair++)
1245 {
1246 for (int jLast=0; jLast<GLast; jLast++)
1247 {
1248 const ordinal_type col = colHost(prefixColHost(pair) + jLast * L.prefixRight);
1249 if (col < 0) continue;
1250 for (int iLast=0; iLast<FLast; iLast++)
1251 {
1252 const ordinal_type row = rowHost(prefixRowHost(pair) + iLast * L.prefixLeft);
1253 if (row < 0) continue;
1254 keptPair.push_back(ordinal_type(pair)); keptIJ.push_back(iLast + jLast * FLast); keptRow.push_back(row); keptCol.push_back(col);
1255 }
1256 }
1257 }
1258 const int numKept = int(keptPair.size());
1259 keptPairV[g] = OrdView1D("kept pair", numKept); keptIJV[g] = OrdView1D("kept ij", numKept);
1260 keptRowV[g] = OrdView1D("kept row", numKept); keptColV[g] = OrdView1D("kept col", numKept);
1261 auto a = Kokkos::create_mirror_view(keptPairV[g]); auto b = Kokkos::create_mirror_view(keptIJV[g]);
1262 auto c = Kokkos::create_mirror_view(keptRowV[g]); auto d = Kokkos::create_mirror_view(keptColV[g]);
1263 for (int k=0; k<numKept; k++) { a(k) = keptPair[k]; b(k) = keptIJ[k]; c(k) = keptRow[k]; d(k) = keptCol[k]; }
1264 Kokkos::deep_copy(keptPairV[g], a); Kokkos::deep_copy(keptIJV[g], b); Kokkos::deep_copy(keptRowV[g], c); Kokkos::deep_copy(keptColV[g], d);
1265 }
1266 }
1267
1268 // workset size from the memory budget: the largest per-cell intermediate is max over stages of (current tensor size)
1269 size_t perCellEntries = 0;
1270 for (const auto &L : layouts)
1271 {
1272 size_t size = 1;
1273 for (int r=0; r<R; r++) size *= L.Q[r];
1274 size_t maxSize = size;
1275 for (int r=0; r<R-1; r++)
1276 {
1277 size = size / L.Q[r] * L.F[r] * L.G[r];
1278 maxSize = std::max(maxSize, size);
1279 }
1280 if (!useSparseLast) maxSize = std::max(maxSize, size / L.Q[R-1] * L.F[R-1] * L.G[R-1]);
1281 perCellEntries = std::max(perCellEntries, maxSize);
1282 }
1283 // ping and pong buffers, plus the group accumulator (if any group has more than one pass) and the dense last-stage accumulator
1284 const int numBuffers = 2 + (anyGroupHasMultiplePasses ? 1 : 0) + (useSparseLast ? 0 : 1);
1285 const ordinal_type worksetSize = pamatrixWorksetSize<Scalar>(options.workspaceMB, numBuffers * perCellEntries, numCellsComputed);
1286
1287 const size_t bufferSize = perCellEntries * size_t(worksetSize);
1288 View1D bufferA(Kokkos::view_alloc(Kokkos::WithoutInitializing, "PAMatrix assemble direct A"), bufferSize);
1289 View1D bufferB(Kokkos::view_alloc(Kokkos::WithoutInitializing, "PAMatrix assemble direct B"), bufferSize);
1290 View1D groupSumBuffer;
1291 if (anyGroupHasMultiplePasses) groupSumBuffer = View1D(Kokkos::view_alloc(Kokkos::WithoutInitializing, "PAMatrix assemble direct group sum"), bufferSize);
1292 View1D lastAccumulator;
1293 if (!useSparseLast) lastAccumulator = View1D(Kokkos::view_alloc(Kokkos::WithoutInitializing, "PAMatrix assemble direct last"), bufferSize);
1294
1295 if (outputRank == 3) Kokkos::deep_copy(integrals.template getUnderlyingView<3>(), Scalar(0));
1296 else Kokkos::deep_copy(integrals.template getUnderlyingView<2>(), Scalar(0));
1297
1298 // pair operators for the first R-1 components, per pass
1299 std::vector<std::vector<View1D>> pairOps(numPasses);
1300 for (int pass=0; pass<numPasses; pass++)
1301 {
1302 const auto &t = passes[pass];
1303 for (int r=0; r<R-1; r++) pairOps[pass].push_back(pairOperator(std::get<0>(t)[r], std::get<2>(t)[r]));
1304 }
1305
1306 for (ordinal_type cellStart=0; cellStart<numCellsComputed; cellStart+=worksetSize)
1307 {
1308 const ordinal_type Cw = std::min(worksetSize, numCellsComputed - cellStart);
1309
1310 for (int g=0; g<int(groups.size()); g++)
1311 {
1312 const auto &L = layouts[g];
1313 const int QLast = L.Q[R-1];
1314 const size_t lastInputSize = size_t(QLast) * Cw * L.prefixPairs; // (p_{R-1}, c, prefix pairs)
1315 // with a single pass, the stage-(R-1) input stays in the ping/pong buffers; otherwise, the passes' inputs are summed
1316 const bool singlePass = (groups[g].passes.size() == 1);
1317 View1D groupSum = singlePass ? View1D() : groupSumBuffer;
1318
1319 bool firstPass = true;
1320 for (int pass : groups[g].passes)
1321 {
1322 const auto &t = passes[pass];
1323 const auto &pointDataSpec = std::get<1>(t);
1324 const int numPointsTotal = pointDataSpec.P;
1325 const int C = pointDataSpec.C;
1326 const auto pointData = _pointDataCache.find(pointDataSpec)->second;
1327 // stage-0 input (p_0, ..., p_{R-1}, c) into bufferA
1328 {
1329 auto dest = bufferA;
1330 Kokkos::parallel_for("PAMatrix::assemble(): transpose point weights",
1331 Kokkos::MDRangePolicy<ExecutionSpace,Kokkos::Rank<2>>({0,0},{Cw,numPointsTotal}),
1332 KOKKOS_LAMBDA(const ordinal_type &cell, const ordinal_type &point) {
1333 const size_t dataCell = (C == 1) ? 0 : size_t(cell + cellStart);
1334 dest(point + size_t(cell) * numPointsTotal) = pointData(dataCell + size_t(point) * C);
1335 });
1336 }
1337 View1D current = bufferA, other = bufferB;
1338 size_t currentSize = size_t(numPointsTotal) * Cw;
1339 for (int r=0; r<R-1; r++)
1340 {
1341 const int Q = L.Q[r], FG = L.F[r] * L.G[r];
1342 const size_t X = currentSize / Q;
1343 INTREPID2_TEST_FOR_EXCEPTION(X > size_t(std::numeric_limits<ordinal_type>::max()), std::invalid_argument,
1344 "PAMatrix::assemble(): GEMM dimension overflow; reduce the workspace budget");
1345 const bool sumIntoGroup = (r == R-2) && !singlePass;
1346 View1D target = sumIntoGroup ? groupSum : other;
1347 const Scalar beta = (sumIntoGroup && !firstPass) ? Scalar(1) : Scalar(0);
1348 Impl::gemm<DeviceType,Scalar>('T', 'N', ordinal_type(X), FG, Q, Scalar(1), current.data(), Q,
1349 pairOps[pass][r].data(), beta, target.data());
1350 currentSize = X * FG;
1351 if (!sumIntoGroup) std::swap(current, other);
1352 }
1353 if (singlePass)
1354 {
1355 groupSum = current; // the single pass's stage-(R-1) input
1356 }
1357 else if (R == 1)
1358 {
1359 // no prefix stages: the group sum is the weights themselves
1360 auto src = bufferA; auto dst = groupSum;
1361 const bool accumulate = !firstPass;
1362 Kokkos::parallel_for("PAMatrix::assemble(): sum weights", Kokkos::RangePolicy<ExecutionSpace>(0, currentSize),
1363 KOKKOS_LAMBDA(const size_t &k) { dst(k) = accumulate ? dst(k) + src(k) : src(k); });
1364 }
1365 firstPass = false;
1366 }
1367 // groupSum: (p_{R-1}, c, prefix pairs), size lastInputSize
1368
1369 const int FLast = L.F[R-1], GLast = L.G[R-1];
1370 const int leftStrideLast = L.prefixLeft, rightStrideLast = L.prefixRight;
1371 const size_t prefixPairs = L.prefixPairs;
1372 auto prefixRow = L.prefixRowOffset;
1373 auto prefixCol = L.prefixColOffset;
1374 auto rowMap = L.rowMap;
1375 auto colMap = L.colMap;
1376
1377 if (!useSparseLast)
1378 {
1379 // last stage: (p_{R-1}, [c, prefix pairs]) -> ([c, prefix pairs], (i_{R-1} j_{R-1}))
1380 const size_t X = lastInputSize / QLast;
1381 INTREPID2_TEST_FOR_EXCEPTION(X > size_t(std::numeric_limits<ordinal_type>::max()), std::invalid_argument,
1382 "PAMatrix::assemble(): GEMM dimension overflow; reduce the workspace budget");
1383 bool firstInFamily = true, lastInFamily = true;
1384 for (int h=0; h<g; h++) if (writeFamily[h] == writeFamily[g]) firstInFamily = false;
1385 for (int h=g+1; h<int(groups.size()); h++) if (writeFamily[h] == writeFamily[g]) lastInFamily = false;
1386 Impl::gemm<DeviceType,Scalar>('T', 'N', ordinal_type(X), FLast * GLast, QLast, Scalar(1), groupSum.data(), QLast,
1387 L.pairOpLast.data(), firstInFamily ? Scalar(0) : Scalar(1), lastAccumulator.data());
1388 if (!lastInFamily) continue;
1389 auto source = lastAccumulator;
1390 // cell outermost, so that writes stay within one cell's matrix. (Separate lambdas for the two output ranks:
1391 // CUDA extended lambdas cannot be defined in generic lambdas or capture in constexpr-if contexts.)
1392 auto policy = Kokkos::MDRangePolicy<ExecutionSpace,Kokkos::Rank<3>>({0,0,0},{Cw, FLast*GLast, ordinal_type(prefixPairs)});
1393 if (outputRank == 3)
1394 {
1395 auto matrixView = integrals.template getUnderlyingView<3>();
1396 Kokkos::parallel_for("PAMatrix::assemble(): write direct contraction", policy,
1397 KOKKOS_LAMBDA(const ordinal_type &cell, const ordinal_type &ijLast, const ordinal_type &pair) {
1398 const int iLast = ijLast % FLast, jLast = ijLast / FLast;
1399 const ordinal_type row = rowMap(prefixRow(pair) + iLast * leftStrideLast);
1400 const ordinal_type col = colMap(prefixCol(pair) + jLast * rightStrideLast);
1401 if ((row < 0) || (col < 0)) return;
1402 matrixView(cell + cellStart, row, col) += source(cell + (pair + size_t(ijLast) * prefixPairs) * Cw);
1403 });
1404 }
1405 else
1406 {
1407 auto matrixView = integrals.template getUnderlyingView<2>();
1408 Kokkos::parallel_for("PAMatrix::assemble(): write direct contraction", policy,
1409 KOKKOS_LAMBDA(const ordinal_type &cell, const ordinal_type &ijLast, const ordinal_type &pair) {
1410 const int iLast = ijLast % FLast, jLast = ijLast / FLast;
1411 const ordinal_type row = rowMap(prefixRow(pair) + iLast * leftStrideLast);
1412 const ordinal_type col = colMap(prefixCol(pair) + jLast * rightStrideLast);
1413 if ((row < 0) || (col < 0)) return;
1414 matrixView(row, col) += source(cell + (pair + size_t(ijLast) * prefixPairs) * Cw);
1415 });
1416 }
1417 }
1418 else
1419 {
1420 // sparse last stage: for each kept (row, col) of this group, value(c) = sum_q groupSum(q, c, prefixPair) P(q, ij)
1421 const int numKept = keptPairV[g].extent_int(0);
1422 if (numKept == 0) continue;
1423 auto keptPair = keptPairV[g]; auto keptIJ = keptIJV[g]; auto keptRow = keptRowV[g]; auto keptCol = keptColV[g];
1424 auto source = groupSum;
1425 auto P = L.pairOpLast;
1426 auto policy = Kokkos::MDRangePolicy<ExecutionSpace,Kokkos::Rank<2>>({0,0},{numKept, Cw});
1427 if (outputRank == 3)
1428 {
1429 auto matrixView = integrals.template getUnderlyingView<3>();
1430 Kokkos::parallel_for("PAMatrix::assemble(): sparse last stage", policy,
1431 KOKKOS_LAMBDA(const ordinal_type &k, const ordinal_type &cell) {
1432 const size_t sOffset = size_t(QLast) * (cell + size_t(keptPair(k)) * Cw);
1433 const size_t pOffset = size_t(QLast) * keptIJ(k);
1434 Scalar value = 0;
1435 for (int q=0; q<QLast; q++) value += source(sOffset + q) * P(pOffset + q);
1436 matrixView(cell + cellStart, keptRow(k), keptCol(k)) += value;
1437 });
1438 }
1439 else
1440 {
1441 auto matrixView = integrals.template getUnderlyingView<2>();
1442 Kokkos::parallel_for("PAMatrix::assemble(): sparse last stage", policy,
1443 KOKKOS_LAMBDA(const ordinal_type &k, const ordinal_type &cell) {
1444 const size_t sOffset = size_t(QLast) * (cell + size_t(keptPair(k)) * Cw);
1445 const size_t pOffset = size_t(QLast) * keptIJ(k);
1446 Scalar value = 0;
1447 for (int q=0; q<QLast; q++) value += source(sOffset + q) * P(pOffset + q);
1448 matrixView(keptRow(k), keptCol(k)) += value;
1449 });
1450 }
1451 }
1452 }
1453 }
1454 ExecutionSpace().fence();
1455}
1456
1457template<typename DeviceType,class Scalar>
1459{
1460 using ExecutionSpace = typename DeviceType::execution_space;
1461 using ScratchView = Kokkos::View<Scalar*,DeviceType,Kokkos::MemoryUnmanaged>;
1462
1463 const ordinal_type numFieldsLeft = _basisValuesLeft.numFields();
1464 const ordinal_type numFieldsRight = _basisValuesRight.numFields();
1465 const int outputRank = integrals.getUnderlyingViewRank();
1466 const ordinal_type numCellsComputed = (outputRank == 3) ? integrals.getDataExtent(0) : 1;
1467
1468 // with ordinal filters, block column j is full right ordinal rightOrdinalFilter_(columnStart+j), and the left
1469 // contraction produces all numUnfilteredFieldsLeft_ rows, of which rows leftOrdinalFilter_(i) are kept
1470 const bool hasLeftFilter = leftOrdinalFilter_ .extent_int(0) > 0;
1471 const bool hasRightFilter = rightOrdinalFilter_.extent_int(0) > 0;
1472 const auto leftOrdinalFilter = leftOrdinalFilter_;
1473 const auto rightOrdinalFilter = rightOrdinalFilter_;
1474 const ordinal_type numLeftRowsComputed = hasLeftFilter ? numUnfilteredFieldsLeft_ : numFieldsLeft;
1475
1476 // Passes are grouped by their left and right (family, component). Passes with the same right group share their
1477 // right operators, so the unit columns' point values are computed once per right group; passes with the same left
1478 // group share their left operators, so their weighted point values are summed before a single left contraction.
1479 const int numIntegrationPasses = int(componentIntegralsToSum_.size());
1480 const int numTensorComponents = int(std::get<2>(componentIntegralsToSum_[0]).size());
1481 const int numPoints = std::get<1>(componentIntegralsToSum_[0]).P;
1482 int numLeftGroups = 0, numRightGroups = 0;
1483 for (const auto &groups : componentIntegralGroups_)
1484 {
1485 numLeftGroups = std::max(numLeftGroups, groups.first + 1);
1486 numRightGroups = std::max(numRightGroups, groups.second + 1);
1487 }
1488
1489 const ordinal_type maxColumnBlockSize = 64;
1490 const ordinal_type columnBlockSize = std::max<ordinal_type>(1, std::min(numFieldsRight, maxColumnBlockSize));
1491
1492 // per cell: unit-column point values for each right group, two contraction workspaces, and the output columns
1493 const size_t perCellEntries = size_t(columnBlockSize) * (size_t(numPoints) * numRightGroups + 2 * maxIntermediateSize_ + numLeftRowsComputed);
1494 const ordinal_type worksetSize = pamatrixWorksetSize<Scalar>(options.workspaceMB, perCellEntries, numCellsComputed);
1495
1496 for (ordinal_type columnStart=0; columnStart<numFieldsRight; columnStart+=columnBlockSize)
1497 {
1498 const ordinal_type blockSize = std::min(columnBlockSize, numFieldsRight - columnStart);
1499 for (ordinal_type cellStart=0; cellStart<numCellsComputed; cellStart+=worksetSize)
1500 {
1501 const ordinal_type Cw = std::min(worksetSize, numCellsComputed - cellStart);
1502 Kokkos::View<Scalar***,DeviceType> outputColumns("PAMatrix assemble output columns", Cw, numLeftRowsComputed, blockSize);
1503
1504 // point values of this block's unit columns, one buffer per right group, each with layout (P,N,Cw) as consumed by
1505 // the weighting below
1506 const size_t pointBufferSize = size_t(numPoints) * blockSize * Cw;
1507 View1D rightFills(Kokkos::view_alloc(Kokkos::WithoutInitializing, "PAMatrix assemble unit-column point values"), pointBufferSize * numRightGroups);
1508 std::vector<bool> rightGroupFilled(numRightGroups, false);
1509 for (int integrationPass=0; integrationPass<numIntegrationPasses; integrationPass++)
1510 {
1511 const int rightGroup = componentIntegralGroups_[integrationPass].second;
1512 if (rightGroupFilled[rightGroup]) continue;
1513 rightGroupFilled[rightGroup] = true;
1514
1515 const auto &integralTuple = componentIntegralsToSum_[integrationPass];
1516 const auto &rightOps = std::get<2>(integralTuple);
1517 const int rightOrdinalOffset = std::get<5>(integralTuple);
1518 const int rightInputSpan = std::get<6>(integralTuple);
1519
1520 Kokkos::Array<OpSpec,8> rightOpsArray;
1521 Kokkos::Array<int,8> rightFieldExtents;
1522 Kokkos::Array<int,8> pointExtents;
1523 for (int r=0; r<numTensorComponents; r++)
1524 {
1525 rightOpsArray[r] = rightOps[r];
1526 rightFieldExtents[r] = rightOps[r].N;
1527 pointExtents[r] = rightOps[r].M;
1528 }
1529 auto fill = Kokkos::subview(rightFills, Kokkos::make_pair(rightGroup * pointBufferSize, (rightGroup + 1) * pointBufferSize));
1530
1531 // Point values of the unit trial columns: for column (f_0,...,f_{R-1}) and point (p_0,...,p_{R-1}), the value is
1532 // prod_r op_r(p_r, f_r). Component 0 varies fastest in both column and point ordinals, so each thread handles one
1533 // (cell, column, p_1..p_{R-1}) and writes the contiguous run over p_0, after computing the product of the other
1534 // components once. (The 1D operators do not depend on the cell.)
1535 const int numPoints0 = pointExtents[0];
1536 const int numPointsOuter = numPoints / numPoints0;
1537 auto unitColumnPolicy = Kokkos::MDRangePolicy<ExecutionSpace,Kokkos::Rank<3>>({0,0,0},{Cw,blockSize,numPointsOuter});
1538 Kokkos::parallel_for("PAMatrix::assemble(): unit trial columns to points", unitColumnPolicy,
1539 KOKKOS_LAMBDA(const ordinal_type &cell, const ordinal_type &blockColumn, const ordinal_type &pointOuter)
1540 {
1541 const int globalColumn = hasRightFilter ? rightOrdinalFilter(columnStart + blockColumn) : columnStart + blockColumn;
1542 const size_t dest = size_t(numPoints0) * pointOuter + (blockColumn + size_t(cell) * blockSize) * numPoints;
1543 if ((globalColumn < rightOrdinalOffset) || (globalColumn >= rightOrdinalOffset + rightInputSpan))
1544 {
1545 for (int p0=0; p0<numPoints0; p0++) fill(dest + p0) = Scalar(0);
1546 return;
1547 }
1548 int columnRemainder = globalColumn - rightOrdinalOffset;
1549 const int field0 = columnRemainder % rightFieldExtents[0];
1550 columnRemainder /= rightFieldExtents[0];
1551 int pointRemainder = pointOuter;
1552 Scalar outerProduct = Scalar(1);
1553 for (int r=1; r<numTensorComponents; r++)
1554 {
1555 const int field = columnRemainder % rightFieldExtents[r];
1556 const int point = pointRemainder % pointExtents[r];
1557 columnRemainder /= rightFieldExtents[r];
1558 pointRemainder /= pointExtents[r];
1559 const auto op = rightOpsArray[r];
1560 outerProduct *= op.opView(point + size_t(field) * op.M);
1561 }
1562 const auto op0 = rightOpsArray[0];
1563 for (int p0=0; p0<numPoints0; p0++) fill(dest + p0) = outerProduct * op0.opView(p0 + size_t(field0) * op0.M);
1564 });
1565 }
1566
1567 const size_t workspaceSize = maxIntermediateSize_ * size_t(Cw) * blockSize;
1568 View1D workspace(Kokkos::view_alloc(Kokkos::WithoutInitializing, "PAMatrix assemble unit-column workspace"), 2 * workspaceSize);
1569 ScratchView workspace1(workspace.data(), workspaceSize);
1570 ScratchView workspace2(workspace.data() + workspaceSize, workspaceSize);
1571 // the left contraction starts from pointDataOut; keep the parity used by apply() so the GEMM chain alternates the same way
1572 ScratchView pointDataOut = (numTensorComponents % 2 == 0) ? workspace2 : workspace1;
1573
1574 for (int leftGroup=0; leftGroup<numLeftGroups; leftGroup++)
1575 {
1576 // sum, over this left group's passes, of (point weights) * (unit-column point values), in layout (N,Cw,P)
1577 int representativePass = -1;
1578 Kokkos::deep_copy(Kokkos::subview(pointDataOut, Kokkos::make_pair(size_t(0), pointBufferSize)), Scalar(0));
1579 for (int integrationPass=0; integrationPass<numIntegrationPasses; integrationPass++)
1580 {
1581 if (componentIntegralGroups_[integrationPass].first != leftGroup) continue;
1582 representativePass = integrationPass;
1583 const PointDataSpec &pointDataSpec = std::get<1>(componentIntegralsToSum_[integrationPass]);
1584 const int rightGroup = componentIntegralGroups_[integrationPass].second;
1585 auto fill = Kokkos::subview(rightFills, Kokkos::make_pair(rightGroup * pointBufferSize, (rightGroup + 1) * pointBufferSize));
1586 const auto weights = _pointDataCache.find(pointDataSpec)->second;
1587 auto accumulated = pointDataOut;
1588 const int C = pointDataSpec.C;
1589 const int P = pointDataSpec.P;
1590 const int N = blockSize;
1591 // accumulated(n,cell,point) += weights(cell,point) * fill(point,n,cell); n fastest to match the output layout
1592 auto policy = Kokkos::MDRangePolicy<ExecutionSpace,Kokkos::Rank<3>>({0,0,0},{P,Cw,N});
1593 Kokkos::parallel_for("PAMatrix::assemble(): accumulate weighted unit-column point values", policy,
1594 KOKKOS_LAMBDA(const ordinal_type &point, const ordinal_type &cell, const ordinal_type &n)
1595 {
1596 const size_t dataCell = (C == 1) ? 0 : size_t(cell + cellStart);
1597 accumulated(n + (cell + size_t(point) * Cw) * N) += weights(dataCell + size_t(point) * C) * fill(point + (n + size_t(cell) * N) * P);
1598 });
1599 }
1600 if (representativePass < 0) continue;
1601
1602 const auto &integralTuple = componentIntegralsToSum_[representativePass];
1603 const auto &leftOps = std::get<0>(integralTuple);
1604 const PointDataSpec &pointDataSpec = std::get<1>(integralTuple);
1605 const int leftOrdinalOffset = std::get<3>(integralTuple);
1606 const int leftOutputSpan = std::get<4>(integralTuple);
1607
1608 size_t Nr = size_t(pointDataSpec.P) * Cw * blockSize * pointDataSpec.aSpan;
1609 const int numLeftIntegrals = int(leftOps.size());
1610 for (int i=0; i<numLeftIntegrals; i++)
1611 {
1612 auto in = ((i+numTensorComponents+1)%2 == 0) ? workspace1 : workspace2;
1613 auto out = ((i+numTensorComponents+1)%2 == 0) ? workspace2 : workspace1;
1614
1615 const int r = numLeftIntegrals-i-1;
1616 const auto &op = leftOps[r];
1617 const ordinal_type Fr = op.M;
1618 const ordinal_type Pr = op.N;
1619 INTREPID2_TEST_FOR_EXCEPTION(Nr % Pr != 0, std::invalid_argument, "Error: Nr must be a multiple of Pr");
1620 INTREPID2_TEST_FOR_EXCEPTION(Nr / Pr > size_t(std::numeric_limits<ordinal_type>::max()), std::invalid_argument,
1621 "PAMatrix::assemble(): GEMM dimension overflow; reduce the workspace budget");
1622 Impl::gemm<DeviceType,Scalar>('N', 'T', Fr, ordinal_type(Nr/Pr), Pr, Scalar(1), op.opView.data(), Fr, in.data(), Scalar(0), out.data());
1623 Nr = (Nr / Pr) * Fr;
1624 }
1625 auto finalOut = ((numLeftIntegrals+numTensorComponents+1)%2 == 0) ? workspace1 : workspace2;
1626 auto sumPolicy = Kokkos::MDRangePolicy<ExecutionSpace,Kokkos::Rank<3>>({0,0,0},{Cw,leftOutputSpan,blockSize});
1627 Kokkos::parallel_for("PAMatrix::assemble(): sum unit-column final output", sumPolicy,
1628 KOKKOS_LAMBDA(const ordinal_type &cell, const ordinal_type &field, const ordinal_type &blockColumn)
1629 {
1630 const size_t idx = field + (blockColumn + size_t(cell) * blockSize) * leftOutputSpan;
1631 outputColumns(cell,field+leftOrdinalOffset,blockColumn) += finalOut(idx);
1632 });
1633 }
1634
1635 if (outputRank == 3)
1636 {
1637 auto matrix = integrals.template getUnderlyingView<3>();
1638 auto copyPolicy = Kokkos::MDRangePolicy<ExecutionSpace,Kokkos::Rank<3>>({0,0,0},{Cw,numFieldsLeft,blockSize});
1639 Kokkos::parallel_for("PAMatrix::assemble(): copy unit-column results", copyPolicy,
1640 KOKKOS_LAMBDA(const ordinal_type &cell, const ordinal_type &row, const ordinal_type &blockColumn)
1641 {
1642 const ordinal_type computedRow = hasLeftFilter ? leftOrdinalFilter(row) : row;
1643 matrix(cell + cellStart,row,columnStart + blockColumn) = outputColumns(cell,computedRow,blockColumn);
1644 });
1645 }
1646 else
1647 {
1648 auto matrix = integrals.template getUnderlyingView<2>();
1649 auto copyPolicy = Kokkos::MDRangePolicy<ExecutionSpace,Kokkos::Rank<2>>({0,0},{numFieldsLeft,blockSize});
1650 Kokkos::parallel_for("PAMatrix::assemble(): copy constant-cell unit-column results", copyPolicy,
1651 KOKKOS_LAMBDA(const ordinal_type &row, const ordinal_type &blockColumn)
1652 {
1653 const ordinal_type computedRow = hasLeftFilter ? leftOrdinalFilter(row) : row;
1654 matrix(row,columnStart + blockColumn) = outputColumns(0,computedRow,blockColumn);
1655 });
1656 }
1657 ExecutionSpace().fence();
1658 }
1659 }
1660}
1661
1662template<typename DeviceType,class Scalar>
1664{
1665 using ExecutionSpace = typename DeviceType::execution_space;
1666 INTREPID2_TEST_FOR_EXCEPTION(hasOrdinalFilter(), std::invalid_argument,
1667 "PAMatrix::assemble() supports ordinal filters only for structures supported by direct assembly (see supportsDirectAssembly())");
1668
1669 const ordinal_type numFieldsLeft = _basisValuesLeft.numFields();
1670 const ordinal_type numFieldsRight = _basisValuesRight.numFields();
1671 const int outputRank = integrals.getUnderlyingViewRank();
1672 const ordinal_type numCellsComputed = (outputRank == 3) ? integrals.getDataExtent(0) : 1;
1673
1674 const ordinal_type maxColumnBlockSize = 64;
1675 const ordinal_type columnBlockSize = std::max<ordinal_type>(1, std::min(numFieldsRight, maxColumnBlockSize));
1676
1677 // per cell: input and output columns, and two contraction workspaces
1678 const size_t perCellEntries = size_t(columnBlockSize) * (size_t(numFieldsRight) + numFieldsLeft + 2 * maxIntermediateSize_);
1679 const ordinal_type worksetSize = pamatrixWorksetSize<Scalar>(options.workspaceMB, perCellEntries, numCellsComputed);
1680
1681 for (ordinal_type columnStart=0; columnStart<numFieldsRight; columnStart+=columnBlockSize)
1682 {
1683 const ordinal_type blockSize = std::min(columnBlockSize, numFieldsRight - columnStart);
1684 for (ordinal_type cellStart=0; cellStart<numCellsComputed; cellStart+=worksetSize)
1685 {
1686 const ordinal_type Cw = std::min(worksetSize, numCellsComputed - cellStart);
1687 Kokkos::View<Scalar***,DeviceType> inputColumns ("PAMatrix assemble input unit columns", Cw, numFieldsRight, blockSize);
1688 Kokkos::View<Scalar***,DeviceType> outputColumns("PAMatrix assemble output columns", Cw, numFieldsLeft, blockSize);
1689 auto identityPolicy = Kokkos::MDRangePolicy<ExecutionSpace,Kokkos::Rank<2>>({0,0},{Cw,blockSize});
1690 Kokkos::parallel_for("PAMatrix::assemble(): set unit multivector", identityPolicy,
1691 KOKKOS_LAMBDA(const ordinal_type &cell, const ordinal_type &blockColumn)
1692 {
1693 inputColumns(cell,columnStart + blockColumn,blockColumn) = Scalar(1);
1694 });
1695 const size_t workspaceSize = maxIntermediateSize_ * size_t(Cw) * blockSize;
1696 View1D workspace(Kokkos::view_alloc(Kokkos::WithoutInitializing, "PAMatrix assemble apply workspace"), 2 * workspaceSize);
1697 applyUnorientedWorkset(outputColumns, 0, inputColumns, 0, cellStart, Cw, blockSize,
1698 workspace.data(), workspace.data() + workspaceSize);
1699
1700 if (outputRank == 3)
1701 {
1702 auto matrix = integrals.template getUnderlyingView<3>();
1703 auto copyPolicy = Kokkos::MDRangePolicy<ExecutionSpace,Kokkos::Rank<3>>({0,0,0},{Cw,numFieldsLeft,blockSize});
1704 Kokkos::parallel_for("PAMatrix::assemble(): copy general columns", copyPolicy,
1705 KOKKOS_LAMBDA(const ordinal_type &cell, const ordinal_type &row, const ordinal_type &blockColumn)
1706 {
1707 matrix(cell + cellStart,row,columnStart + blockColumn) = outputColumns(cell,row,blockColumn);
1708 });
1709 }
1710 else
1711 {
1712 auto matrix = integrals.template getUnderlyingView<2>();
1713 auto copyPolicy = Kokkos::MDRangePolicy<ExecutionSpace,Kokkos::Rank<2>>({0,0},{numFieldsLeft,blockSize});
1714 Kokkos::parallel_for("PAMatrix::assemble(): copy constant-cell columns", copyPolicy,
1715 KOKKOS_LAMBDA(const ordinal_type &row, const ordinal_type &blockColumn)
1716 {
1717 matrix(row,columnStart + blockColumn) = outputColumns(0,row,blockColumn);
1718 });
1719 }
1720 ExecutionSpace().fence();
1721 }
1722 }
1723}
1724
1725template<typename DeviceType,class Scalar>
1727{
1728 const bool direct = supportsDirectAssembly();
1729 INTREPID2_TEST_FOR_EXCEPTION(hasOrdinalFilter() && !direct, std::invalid_argument,
1730 "PAMatrix::assemble() supports ordinal filters only for structures supported by direct assembly (see supportsDirectAssembly())");
1731 switch (options.algorithm)
1732 {
1734 if (direct) assembleDirect(integrals, options);
1735 else assembleByApply(integrals, options);
1736 break;
1738 if (direct) assembleUnitColumns(integrals, options);
1739 else assembleByApply(integrals, options);
1740 break;
1742 assembleByApply(integrals, options);
1743 break;
1744 }
1745}
1746
1747template<typename DeviceType,class Scalar>
1749{
1750 using ExecutionSpace = typename DeviceType::execution_space;
1751 // modifyMatrixByOrientation() computes O_L M O_R^T
1752 auto matrixView = integrals.getUnderlyingView();
1753 Kokkos::DynRankView<Scalar,DeviceType> unoriented("PAMatrix unoriented matrix", matrixView.extent(0), matrixView.extent(1), matrixView.extent(2));
1754 Kokkos::deep_copy(unoriented, matrixView);
1755 OrientationTools<DeviceType>::modifyMatrixByOrientation(matrixView, unoriented, _orientations, _basisLeft.get(), _basisRight.get());
1756 ExecutionSpace().fence();
1757}
1758
1759template<typename DeviceType,class Scalar>
1761{
1762 const ordinal_type numCells = _basisValuesLeft.numCells();
1763 const ordinal_type numFieldsLeft = _basisValuesLeft.numFields();
1764 const ordinal_type numFieldsRight = _basisValuesRight.numFields();
1765
1766 INTREPID2_TEST_FOR_EXCEPTION(integrals.rank() != 3, std::invalid_argument,
1767 "PAMatrix::assemble() requires a rank-3 logical output container");
1768 INTREPID2_TEST_FOR_EXCEPTION(integrals.extent_int(0) != numCells ||
1769 integrals.extent_int(1) != numFieldsLeft ||
1770 integrals.extent_int(2) != numFieldsRight, std::invalid_argument,
1771 "PAMatrix::assemble() output container has incompatible extents");
1772 const int outputRank = integrals.getUnderlyingViewRank();
1773 INTREPID2_TEST_FOR_EXCEPTION((outputRank != 2) && (outputRank != 3), std::invalid_argument,
1774 "PAMatrix::assemble() supports only rank-2 or rank-3 underlying matrix storage");
1775 INTREPID2_TEST_FOR_EXCEPTION(_hasNontrivialOrientations && ((outputRank != 3) || (integrals.getDataExtent(0) != numCells)), std::invalid_argument,
1776 "PAMatrix::assemble() with orientations requires storage for every cell; see allocateMatrixStorage()");
1777
1778 assembleUnoriented(integrals, options);
1779 if (_hasNontrivialOrientations) orientAssembledMatrix(integrals);
1780}
1781template<typename DeviceType,class Scalar>
1783{
1784 using ExecutionSpace = typename DeviceType::execution_space;
1785 INTREPID2_TEST_FOR_EXCEPTION(hasOrdinalFilter(), std::invalid_argument, "PAMatrix::extractDiagonal() does not yet support ordinal filters");
1786
1787 const ordinal_type numCells = _basisValuesLeft.numCells();
1788 const ordinal_type numFieldsLeft = _basisValuesLeft.numFields();
1789 const ordinal_type numFieldsRight = _basisValuesRight.numFields();
1790 const ordinal_type numDiagonalEntries = std::min(numFieldsLeft, numFieldsRight);
1791
1792 INTREPID2_TEST_FOR_EXCEPTION(diagonal.rank() != 2, std::invalid_argument,
1793 "PAMatrix::extractDiagonal() requires a rank-2 logical output container");
1794 INTREPID2_TEST_FOR_EXCEPTION(diagonal.extent_int(0) != numCells ||
1795 diagonal.extent_int(1) != numDiagonalEntries, std::invalid_argument,
1796 "PAMatrix::extractDiagonal() output container has incompatible extents");
1797
1798 // fallback: assemble the full matrix (with orientations), and copy its diagonal. (Assembly uses a workspace budget, but
1799 // the assembled temporary holds the matrices of all cells for which the diagonal stores data.)
1800 const auto assembleAndCopyDiagonal = [this, numCells, numFieldsLeft, numFieldsRight, numDiagonalEntries, diagonal]()
1801 {
1802 const ordinal_type numCellsStored = (diagonal.getUnderlyingViewRank() == 2) ? diagonal.getDataExtent(0) : 1;
1803 // the matrix needs storage only for the cells for which the diagonal stores data (all cells, with orientations)
1804 Kokkos::View<Scalar***,DeviceType> matrixView("PAMatrix extractDiagonal assembled temporary", numCellsStored, numFieldsLeft, numFieldsRight);
1805 Kokkos::Array<int,3> matrixExtents {numCells, numFieldsLeft, numFieldsRight};
1806 const DataVariationType cellVariation = (numCellsStored == numCells) ? GENERAL : MODULAR;
1807 Kokkos::Array<DataVariationType,3> matrixVariationTypes {cellVariation, GENERAL, GENERAL};
1808 Data<Scalar,DeviceType> matrixData(matrixView, matrixExtents, matrixVariationTypes);
1809 this->assemble(matrixData);
1810
1811 if (diagonal.getUnderlyingViewRank() == 2)
1812 {
1813 auto diagonalView = diagonal.template getUnderlyingView<2>();
1814 auto policy = Kokkos::MDRangePolicy<ExecutionSpace,Kokkos::Rank<2>>({0,0},{numCellsStored,numDiagonalEntries});
1815 Kokkos::parallel_for("PAMatrix::extractDiagonal(): copy assembled diagonal", policy,
1816 KOKKOS_LAMBDA(const ordinal_type &cell, const ordinal_type &field)
1817 {
1818 diagonalView(cell,field) = matrixView(cell,field,field);
1819 });
1820 }
1821 else if (diagonal.getUnderlyingViewRank() == 1)
1822 {
1823 auto diagonalView = diagonal.template getUnderlyingView<1>();
1824 auto policy = Kokkos::RangePolicy<ExecutionSpace>(0,numDiagonalEntries);
1825 Kokkos::parallel_for("PAMatrix::extractDiagonal(): copy assembled constant-cell diagonal", policy,
1826 KOKKOS_LAMBDA(const ordinal_type &field)
1827 {
1828 diagonalView(field) = matrixView(0,field,field);
1829 });
1830 }
1831 else
1832 {
1833 INTREPID2_TEST_FOR_EXCEPTION(true, std::invalid_argument,
1834 "PAMatrix::extractDiagonal() supports only rank-1 or rank-2 underlying diagonal storage");
1835 }
1836 ExecutionSpace().fence();
1837 };
1838
1839 bool useSumFactorizedPath = !_hasNontrivialOrientations;
1840 for (const auto &integralTuple : componentIntegralsToSum_)
1841 {
1842 const auto &leftOps = std::get<0>(integralTuple);
1843 const PointDataSpec &pointDataSpec = std::get<1>(integralTuple);
1844 const auto &rightOps = std::get<2>(integralTuple);
1845 const int leftOffset = std::get<3>(integralTuple);
1846 const int leftSpan = std::get<4>(integralTuple);
1847 const int rightOffset = std::get<5>(integralTuple);
1848 const int rightSpan = std::get<6>(integralTuple);
1849
1850 if ((leftOps.size() != rightOps.size()) || (leftOps.size() == 0) ||
1851 (pointDataSpec.aSpan != 1) || (pointDataSpec.bSpan != 1) ||
1852 (leftOffset != rightOffset) || (leftSpan != rightSpan) ||
1853 (leftOffset + leftSpan > numDiagonalEntries))
1854 {
1855 useSumFactorizedPath = false;
1856 break;
1857 }
1858
1859 int fieldProduct = 1;
1860 int pointProduct = 1;
1861 for (size_t r=0; r<leftOps.size(); r++)
1862 {
1863 if ((leftOps[r].M != rightOps[r].N) || (leftOps[r].N != rightOps[r].M))
1864 {
1865 useSumFactorizedPath = false;
1866 break;
1867 }
1868 fieldProduct *= leftOps[r].M;
1869 pointProduct *= leftOps[r].N;
1870 }
1871 if (!useSumFactorizedPath) break;
1872 if ((fieldProduct != leftSpan) || (pointProduct != pointDataSpec.P))
1873 {
1874 useSumFactorizedPath = false;
1875 break;
1876 }
1877 }
1878
1879 if (!useSumFactorizedPath)
1880 {
1881 assembleAndCopyDiagonal();
1882 return;
1883 }
1884
1885 diagonal.clear();
1886 Data<Scalar,DeviceType> diagonalData = diagonal;
1887 const int diagonalCellDataExtent = diagonal.getDataExtent(0);
1888
1889 for (const auto &integralTuple : componentIntegralsToSum_)
1890 {
1891 const auto &leftOps = std::get<0>(integralTuple);
1892 const PointDataSpec &pointDataSpec = std::get<1>(integralTuple);
1893 const auto &rightOps = std::get<2>(integralTuple);
1894 const int diagonalOffset = std::get<3>(integralTuple);
1895 const int numTensorComponents = static_cast<int>(leftOps.size());
1896
1897 std::vector<int> fieldExtents(numTensorComponents);
1898 std::vector<int> pointExtents(numTensorComponents);
1899 int fieldProduct = 1;
1900 int pointProduct = 1;
1901 int maxScratchEntriesPerCell = 1;
1902 for (int r=0; r<numTensorComponents; r++)
1903 {
1904 fieldExtents[r] = leftOps[r].M;
1905 pointExtents[r] = leftOps[r].N;
1906 fieldProduct *= fieldExtents[r];
1907 pointProduct *= pointExtents[r];
1908 }
1909 for (int r=1; r<numTensorComponents; r++)
1910 {
1911 int prefixPointProduct = 1;
1912 for (int s=0; s<r; s++) prefixPointProduct *= pointExtents[s];
1913 int suffixFieldProduct = 1;
1914 for (int s=r; s<numTensorComponents; s++) suffixFieldProduct *= fieldExtents[s];
1915 maxScratchEntriesPerCell = std::max(maxScratchEntriesPerCell, prefixPointProduct * suffixFieldProduct);
1916 }
1917
1918 auto pointData = _pointDataCache.find(pointDataSpec)->second;
1919
1920 if (numTensorComponents == 1)
1921 {
1922 auto leftOp = leftOps[0];
1923 auto rightOp = rightOps[0];
1924 const int numFields = fieldExtents[0];
1925 const int numPoints = pointExtents[0];
1926 const int pointDataCellExtent = pointDataSpec.C;
1927 auto policy = Kokkos::MDRangePolicy<ExecutionSpace,Kokkos::Rank<2>>({0,0},{diagonalCellDataExtent,numFields});
1928 Kokkos::parallel_for("PAMatrix::extractDiagonal(): 1D sum-factorized diagonal", policy,
1929 KOKKOS_LAMBDA(const ordinal_type &cell, const ordinal_type &field)
1930 {
1931 const int pointDataCell = (pointDataCellExtent == 1) ? 0 : cell;
1932 Scalar value = 0;
1933 for (int point=0; point<numPoints; point++)
1934 {
1935 const Scalar L = leftOp.opView(field + point * leftOp.M);
1936 const Scalar R = rightOp.opView(point + field * rightOp.M);
1937 const Scalar W = pointData(pointDataCell + size_t(point) * pointDataCellExtent);
1938 value += L * R * W;
1939 }
1940 diagonalData.getWritableEntry(cell, diagonalOffset + field) += value;
1941 });
1942 ExecutionSpace().fence();
1943 continue;
1944 }
1945
1946 const size_t scratchEntries = size_t(diagonalCellDataExtent) * maxScratchEntriesPerCell;
1947 Kokkos::View<Scalar*,DeviceType> scratchA("PAMatrix diagonal scratch A", scratchEntries);
1948 Kokkos::View<Scalar*,DeviceType> scratchB("PAMatrix diagonal scratch B", scratchEntries);
1949
1950 const int lastDim = numTensorComponents - 1;
1951 {
1952 auto leftOp = leftOps[lastDim];
1953 auto rightOp = rightOps[lastDim];
1954 int prefixPointProduct = 1;
1955 for (int s=0; s<lastDim; s++) prefixPointProduct *= pointExtents[s];
1956 const int numFieldsLast = fieldExtents[lastDim];
1957 const int numPointsLast = pointExtents[lastDim];
1958 const int pointDataCellExtent = pointDataSpec.C;
1959 const size_t totalEntries = size_t(diagonalCellDataExtent) * prefixPointProduct * numFieldsLast;
1960 Kokkos::parallel_for("PAMatrix::extractDiagonal(): initialize last diagonal contraction", Kokkos::RangePolicy<ExecutionSpace,Kokkos::IndexType<size_t>>(0,totalEntries),
1961 KOKKOS_LAMBDA(const size_t &entryOrdinal)
1962 {
1963 const int cell = int(entryOrdinal % diagonalCellDataExtent);
1964 size_t remainder = entryOrdinal / diagonalCellDataExtent;
1965 const int prefixPointOrdinal = int(remainder % prefixPointProduct);
1966 const int field = int(remainder / prefixPointProduct);
1967 const int pointDataCell = (pointDataCellExtent == 1) ? 0 : cell;
1968 Scalar value = 0;
1969 for (int point=0; point<numPointsLast; point++)
1970 {
1971 const int pointOrdinal = prefixPointOrdinal + point * prefixPointProduct;
1972 const Scalar L = leftOp.opView(field + point * leftOp.M);
1973 const Scalar R = rightOp.opView(point + field * rightOp.M);
1974 const Scalar W = pointData(pointDataCell + size_t(pointOrdinal) * pointDataCellExtent);
1975 value += L * R * W;
1976 }
1977 scratchA(entryOrdinal) = value;
1978 });
1979 ExecutionSpace().fence();
1980 }
1981
1982 bool scratchAIsCurrent = true;
1983 for (int r=numTensorComponents-2; r>=1; r--)
1984 {
1985 auto inScratch = scratchAIsCurrent ? scratchA : scratchB;
1986 auto outScratch = scratchAIsCurrent ? scratchB : scratchA;
1987 auto leftOp = leftOps[r];
1988 auto rightOp = rightOps[r];
1989
1990 int prefixPointProduct = 1;
1991 for (int s=0; s<r; s++) prefixPointProduct *= pointExtents[s];
1992 const int pointExtent = pointExtents[r];
1993 const int previousPrefixPointProduct = prefixPointProduct * pointExtent;
1994 int suffixFieldProduct = 1;
1995 for (int s=r; s<numTensorComponents; s++) suffixFieldProduct *= fieldExtents[s];
1996 int suffixTailProduct = 1;
1997 for (int s=r+1; s<numTensorComponents; s++) suffixTailProduct *= fieldExtents[s];
1998 const size_t totalEntries = size_t(diagonalCellDataExtent) * prefixPointProduct * suffixFieldProduct;
1999
2000 Kokkos::parallel_for("PAMatrix::extractDiagonal(): diagonal tensor contraction stage", Kokkos::RangePolicy<ExecutionSpace,Kokkos::IndexType<size_t>>(0,totalEntries),
2001 KOKKOS_LAMBDA(const size_t &entryOrdinal)
2002 {
2003 const int cell = int(entryOrdinal % diagonalCellDataExtent);
2004 size_t remainder = entryOrdinal / diagonalCellDataExtent;
2005 const int prefixPointOrdinal = int(remainder % prefixPointProduct);
2006 const int suffixFieldOrdinal = int(remainder / prefixPointProduct);
2007 const int field = suffixFieldOrdinal % leftOp.M;
2008 const int tailFieldOrdinal = suffixFieldOrdinal / leftOp.M;
2009 Scalar value = 0;
2010 for (int point=0; point<pointExtent; point++)
2011 {
2012 const int previousPrefixPointOrdinal = prefixPointOrdinal + point * prefixPointProduct;
2013 const size_t inputIndex = cell + (previousPrefixPointOrdinal + size_t(tailFieldOrdinal) * previousPrefixPointProduct) * diagonalCellDataExtent;
2014 const Scalar L = leftOp.opView(field + point * leftOp.M);
2015 const Scalar R = rightOp.opView(point + field * rightOp.M);
2016 value += L * R * inScratch(inputIndex);
2017 }
2018 outScratch(entryOrdinal) = value;
2019 });
2020 ExecutionSpace().fence();
2021 scratchAIsCurrent = !scratchAIsCurrent;
2022 }
2023
2024 auto finalScratch = scratchAIsCurrent ? scratchA : scratchB;
2025 {
2026 auto leftOp = leftOps[0];
2027 auto rightOp = rightOps[0];
2028 const int pointExtent = pointExtents[0];
2029 int suffixTailProduct = 1;
2030 for (int s=1; s<numTensorComponents; s++) suffixTailProduct *= fieldExtents[s];
2031 const size_t totalEntries = size_t(diagonalCellDataExtent) * fieldProduct;
2032 Kokkos::parallel_for("PAMatrix::extractDiagonal(): final diagonal accumulation", Kokkos::RangePolicy<ExecutionSpace,Kokkos::IndexType<size_t>>(0,totalEntries),
2033 KOKKOS_LAMBDA(const size_t &entryOrdinal)
2034 {
2035 const int cell = int(entryOrdinal % diagonalCellDataExtent);
2036 const int fieldOrdinal = int(entryOrdinal / diagonalCellDataExtent);
2037 const int field0 = fieldOrdinal % leftOp.M;
2038 const int tailFieldOrdinal = fieldOrdinal / leftOp.M;
2039 Scalar value = 0;
2040 for (int point=0; point<pointExtent; point++)
2041 {
2042 const size_t inputIndex = cell + (point + size_t(tailFieldOrdinal) * pointExtent) * diagonalCellDataExtent;
2043 const Scalar L = leftOp.opView(field0 + point * leftOp.M);
2044 const Scalar R = rightOp.opView(point + field0 * rightOp.M);
2045 value += L * R * finalScratch(inputIndex);
2046 }
2047 diagonalData.getWritableEntry(cell, diagonalOffset + fieldOrdinal) += value;
2048 });
2049 ExecutionSpace().fence();
2050 }
2051 }
2052}
2053
2054
2055template<typename DeviceType,class Scalar>
2057{
2058 size_t size = maxIntermediateSize_ * 2;
2059 if (_hasNontrivialOrientations)
2060 {
2061 // unoriented and oriented input values, and unoriented and oriented output values
2062 size += 2 * size_t(_basisValuesRight.numFields()) + 2 * size_t(_basisValuesLeft.numFields());
2063 }
2064 return size;
2065}
2066
2067template<typename DeviceType,class Scalar>
2068Kokkos::View<Scalar*,DeviceType> PAMatrix<DeviceType,Scalar>::allocateWorkspace(const ordinal_type &worksetSize) const
2069{
2070 return allocateWorkspace(worksetSize, 1);
2071}
2072
2073template<typename DeviceType,class Scalar>
2074Kokkos::View<Scalar*,DeviceType> PAMatrix<DeviceType,Scalar>::allocateWorkspace(const ordinal_type &worksetSize,
2075 const ordinal_type &n) const
2076{
2077 return View1D("PAMatrix workspace", applyWorkspacePerCell() * size_t(worksetSize) * size_t(n));
2078}
2079
2080template<typename DeviceType,class Scalar>
2081template<typename OutputViewType, typename InputViewType>
2082void PAMatrix<DeviceType,Scalar>::applyUnorientedWorkset(const OutputViewType &outputVector, const ordinal_type outputCellOffset,
2083 const InputViewType &inputVector, const ordinal_type inputCellOffset,
2084 const ordinal_type startCell, const ordinal_type Cw, const ordinal_type N,
2085 Scalar *workspace1Data, Scalar *workspace2Data) const
2086{
2087 using ExecutionSpace = typename DeviceType::execution_space;
2088 using ScratchView = Kokkos::View<Scalar*, DeviceType, Kokkos::MemoryUnmanaged>;
2089
2090 const size_t workspaceSize = maxIntermediateSize_ * size_t(Cw) * N;
2091 ScratchView workspace1(workspace1Data, workspaceSize);
2092 ScratchView workspace2(workspace2Data, workspaceSize);
2093
2094 const Scalar alpha = 1.0;
2095 const Scalar beta = 0.0;
2096
2097 // For vector-dot-vector integrals (e.g.), we need to integrate left x components against right x components, etc., and sum.
2098 // Each of these is one pass, and we accumulate in outputVector.
2099 const int numIntegrationPasses = int(componentIntegralsToSum_.size());
2100 for (int integrationPass=0; integrationPass<numIntegrationPasses; integrationPass++)
2101 {
2102 const auto &integral_tuple = componentIntegralsToSum_[integrationPass];
2103
2104 const auto & leftIntegrals = std::get<0>(integral_tuple);
2105 const PointDataSpec & pointDataSpec = std::get<1>(integral_tuple);
2106 // right integrals: replace F2j basis coefficients with evaluations at Pj
2107 const auto & rightIntegrals = std::get<2>(integral_tuple);
2108 const int numRightIntegrals = int(rightIntegrals.size());
2109
2110 const auto leftOrdinalOffset = std::get<3>(integral_tuple);
2111 const auto leftOutputSpan = std::get<4>(integral_tuple);
2112 const auto rightOrdinalOffset = std::get<5>(integral_tuple);
2113 const auto rightInputSpan = std::get<6>(integral_tuple);
2114
2115 const int numLeftIntegrals = int(leftIntegrals.size());
2116
2117 // set workspace1 to the input data in an appropriate order
2118 // (C,F,N) arguments, where F=F_0…F_d, and the tensor ordering of these has F_0 as the fastest-moving index.
2119 // We want to start with input basis coefficients that are in a tensor product ordering with shape
2120 // (N,C,F), where the fastest-moving indices are on the left (LayoutLeft ordering).
2121 auto policy = Kokkos::MDRangePolicy<ExecutionSpace,Kokkos::Rank<3>>({0,0,0},{Cw,rightInputSpan,N});
2122 Kokkos::parallel_for("PAMatrix::apply(): copy inputVector into workspace", policy,
2123 KOKKOS_LAMBDA(const ordinal_type &c, const ordinal_type &f, const ordinal_type &n)
2124 {
2125 workspace1(n + (c + size_t(f) * Cw) * N) = inputVector.access(c + inputCellOffset,f+rightOrdinalOffset,n);
2126 });
2127
2128 // the right integrals are ordered in the natural dimension ordering: x integrals come first.
2129 // At the start, input has shape (N,C,F_0,...,F_d); we regard this as a matrix (NCF_0…F_{d-1} x F_d)
2130 // We left-multiply the transpose of this by a right-integral matrix A_d with shape (P_d,F_d), with result
2131 // of shape (P_d,N,C,F_0,...,F_{d-1}). In the next iteration, we multiply by A_{d-1} to get
2132 // (P_{d-1},P_d,N,C,F_0,...,F_{d-2}), continuing until we have (P_0,…,P_d,N,C) = (P,N,C).
2133 // We then weight with point data; as we do, we reshape to a form (N,C,P).
2134 // We then apply the transpose of left-integral matrix A_d to produce (F_d,N,C,P_0,…,P_{d-1}),
2135 // ending with (F_0,...,F_d,N,C) = (F,N,C), where now the F's belong to the left basis.
2136 // Finally, we accumulate the result into outputVector as (C,F,N), in Kokkos's layout for outputVector.
2137
2138 // define Nr to be the size of the most recent workspace data
2139 size_t Nr = size_t(Cw) * N * rightInputSpan;
2140 for (int j=0; j<numRightIntegrals; j++)
2141 {
2142 // we alternate whether we are placing intermediate results in workspace1 or workspace2
2143 auto in = (j%2 == 0) ? workspace1 : workspace2;
2144 auto out = (j%2 == 0) ? workspace2 : workspace1;
2145
2146 const int r = numRightIntegrals-j-1; // start with final component, work back to 0th component.
2147 const auto &op = rightIntegrals[r];
2148
2149 // multiply P_r x F_r matrix with transpose of (… x F_r)
2150 const ordinal_type Pr = op.M;
2151 const ordinal_type Fr = op.N;
2152 const ordinal_type LDA = Pr; // will need to revise if we ever pad our operators (for byte alignment)
2153 INTREPID2_TEST_FOR_EXCEPTION(Nr % Fr != 0, std::invalid_argument, "Error: Nr must be a multiple of Fr");
2154 INTREPID2_TEST_FOR_EXCEPTION(Nr / Fr > size_t(std::numeric_limits<ordinal_type>::max()), std::invalid_argument,
2155 "PAMatrix::apply(): GEMM dimension overflow; use a smaller workset size");
2156 Impl::gemm<DeviceType,Scalar>('N', 'T', Pr, ordinal_type(Nr/Fr), Fr, alpha, op.opView.data(), LDA, in.data(), beta, out.data());
2157 Nr = (Nr / Fr) * Pr;
2158 }
2159 auto pointDataIn = (numRightIntegrals%2 == 0) ? workspace1 : workspace2; // pointwise result from contractions so far
2160 auto pointDataOut = (numRightIntegrals%2 == 0) ? workspace2 : workspace1; // pointwise output from weighting with pointData
2161
2162 const auto &pointData = _pointDataCache.find(pointDataSpec)->second; // pointwise weights with shape (C,P[,Da[,Db]])
2163 // pointDataIn has shape (P,N,Cw); pointDataOut will have shape (N,Cw,P) (layout left).
2164 Impl::pointDataMultiply<DeviceType,Scalar>(pointDataSpec.C, startCell, Cw, pointDataSpec.P, pointDataSpec.aSpan, pointDataSpec.bSpan,
2165 pointData.data(), pointDataIn.data(), pointDataOut.data(), N);
2166
2167 Nr = Nr / pointDataSpec.bSpan * pointDataSpec.aSpan; // contracted in b, expanded in a
2168
2169 for (int i=0; i<numLeftIntegrals; i++)
2170 {
2171 // we alternate whether we are placing intermediate results in workspace1 or workspace2
2172 auto in = ((i+numRightIntegrals+1)%2 == 0) ? workspace1 : workspace2;
2173 auto out = ((i+numRightIntegrals+1)%2 == 0) ? workspace2 : workspace1;
2174
2175 const int r = numLeftIntegrals-i-1; // start with final component, work back to 0th component.
2176 const auto &op = leftIntegrals[r];
2177
2178 // multiply Fr x Pr matrix with transpose of (… x Pr): result is (Fr x …)
2179 const ordinal_type Fr = op.M;
2180 const ordinal_type Pr = op.N;
2181 const ordinal_type LDA = Fr; // will need to revise if we ever pad our operators (for byte alignment)
2182 INTREPID2_TEST_FOR_EXCEPTION(Nr % Pr != 0, std::invalid_argument, "Error: Nr must be a multiple of Pr");
2183 INTREPID2_TEST_FOR_EXCEPTION(Nr / Pr > size_t(std::numeric_limits<ordinal_type>::max()), std::invalid_argument,
2184 "PAMatrix::apply(): GEMM dimension overflow; use a smaller workset size");
2185 Impl::gemm<DeviceType,Scalar>('N', 'T', Fr, ordinal_type(Nr/Pr), Pr, alpha, op.opView.data(), LDA, in.data(), beta, out.data());
2186 Nr = (Nr / Pr) * Fr;
2187 }
2188 auto finalOut = ((numLeftIntegrals+numRightIntegrals+1)%2 == 0) ? workspace1 : workspace2;
2189 // Sum finalOut into outputVector
2190 policy = Kokkos::MDRangePolicy<ExecutionSpace,Kokkos::Rank<3>>({0,0,0},{Cw,leftOutputSpan,N});
2191 Kokkos::parallel_for("PAMatrix::apply(): sum finalOut into outputVector", policy,
2192 KOKKOS_LAMBDA(const ordinal_type &c, const ordinal_type &f, const ordinal_type &n)
2193 {
2194 const size_t idx = f + (n + size_t(c) * N) * leftOutputSpan; // (F,N,C) layout-left
2195 outputVector.access(c+outputCellOffset,f+leftOrdinalOffset,n) += finalOut(idx);
2196 });
2197 } // integrationPass for loop
2198}
2199
2200template<typename DeviceType,class Scalar>
2201template<typename OutputViewType, typename InputViewType>
2202void PAMatrix<DeviceType,Scalar>::apply(const OutputViewType &outputVector,
2203 const InputViewType & inputVector,
2204 const Kokkos::View<Scalar*,DeviceType> &workspace,
2205 const bool sumInto,
2206 const int worksetSizeIn) const
2207{
2208 INTREPID2_TEST_FOR_EXCEPTION(hasOrdinalFilter(), std::invalid_argument, "PAMatrix::apply() does not yet support ordinal filters");
2209
2210 using ExecutionSpace = typename DeviceType::execution_space;
2211
2212 INTREPID2_TEST_FOR_EXCEPTION((inputVector.rank() < 2) || (inputVector.rank() > 3) || (outputVector.rank() != inputVector.rank()),
2213 std::invalid_argument, "PAMatrix::apply(): input and output must both have shape (C,F) or (C,F,N)");
2214 const ordinal_type C = inputVector.extent_int(0); // C, F2, N
2215 const ordinal_type F2 = inputVector.extent_int(1);
2216 const ordinal_type N = (inputVector.rank() > 2) ? inputVector.extent_int(2) : 1;
2217 const ordinal_type F1 = outputVector.extent_int(1); // C, F1, N
2218 const ordinal_type outputN = (outputVector.rank() > 2) ? outputVector.extent_int(2) : 1;
2219
2220 INTREPID2_TEST_FOR_EXCEPTION(C != _basisValuesLeft.numCells(), std::invalid_argument, "PAMatrix::apply(): input cell count does not match the matrix");
2221 INTREPID2_TEST_FOR_EXCEPTION(outputVector.extent_int(0) != C, std::invalid_argument, "PAMatrix::apply(): output cell count does not match the input");
2222 INTREPID2_TEST_FOR_EXCEPTION(F2 != _basisValuesRight.numFields(), std::invalid_argument, "PAMatrix::apply(): input field count does not match the right basis");
2223 INTREPID2_TEST_FOR_EXCEPTION(F1 != _basisValuesLeft.numFields(), std::invalid_argument, "PAMatrix::apply(): output field count does not match the left basis");
2224 INTREPID2_TEST_FOR_EXCEPTION(outputN != N, std::invalid_argument, "PAMatrix::apply(): input and output vector counts differ");
2225
2226 const ordinal_type worksetSize = ((worksetSizeIn > 0) && (worksetSizeIn < C)) ? worksetSizeIn : C;
2227 INTREPID2_TEST_FOR_EXCEPTION(applyWorkspacePerCell() * size_t(worksetSize) * N > workspace.extent(0), std::invalid_argument,
2228 "PAMatrix::apply(): allocated workspace size is not sufficient; see allocateWorkspace()");
2229
2230 if (!sumInto)
2231 Kokkos::deep_copy(outputVector, Scalar(0));
2232
2233 const size_t workspaceSize = maxIntermediateSize_ * size_t(worksetSize) * N;
2234 Scalar * const workspace1 = workspace.data();
2235 Scalar * const workspace2 = workspace.data() + workspaceSize;
2236
2237 if (!_hasNontrivialOrientations)
2238 {
2239 for (ordinal_type startCell=0; startCell<C; startCell+=worksetSize)
2240 {
2241 const ordinal_type Cw = std::min(worksetSize, C - startCell);
2242 applyUnorientedWorkset(outputVector, startCell, inputVector, startCell, startCell, Cw, N, workspace1, workspace2);
2243 }
2244 ExecutionSpace().fence();
2245 return;
2246 }
2247
2248 // With orientations, the matrix is O_L M O_R^T: we apply O_R^T to the input, apply M, and apply O_L to the result.
2249 // OrientationTools treats the trailing dimension of (Cw,F,N) views as a point dimension, so that all N vectors of a
2250 // workset are oriented by one call.
2251 using DynScratchView = Kokkos::DynRankView<Scalar, DeviceType, Kokkos::MemoryUnmanaged>;
2252 for (ordinal_type startCell=0; startCell<C; startCell+=worksetSize)
2253 {
2254 const ordinal_type Cw = std::min(worksetSize, C - startCell);
2255 const std::pair<int,int> cellRange = {startCell, startCell + Cw};
2256 size_t offset = 2 * workspaceSize;
2257 DynScratchView unorientedInput (workspace.data() + offset, Cw, F2, N); offset += size_t(Cw) * F2 * N;
2258 DynScratchView orientedInput (workspace.data() + offset, Cw, F2, N); offset += size_t(Cw) * F2 * N;
2259 DynScratchView unorientedOutput(workspace.data() + offset, Cw, F1, N); offset += size_t(Cw) * F1 * N;
2260 DynScratchView orientedOutput (workspace.data() + offset, Cw, F1, N);
2261
2262 auto copyPolicy = Kokkos::MDRangePolicy<ExecutionSpace,Kokkos::Rank<3>>({0,0,0},{Cw,F2,N});
2263 Kokkos::parallel_for("PAMatrix::apply(): copy input workset", copyPolicy,
2264 KOKKOS_LAMBDA(const ordinal_type &c, const ordinal_type &f, const ordinal_type &n)
2265 {
2266 unorientedInput(c,f,n) = inputVector.access(c + startCell, f, n);
2267 });
2268
2269 auto orientationsWorkset = Kokkos::subview(_orientations, cellRange);
2270 OrientationTools<DeviceType>::modifyBasisByOrientationTranspose(orientedInput, unorientedInput, orientationsWorkset, _basisRight.get());
2271
2272 Kokkos::deep_copy(unorientedOutput, Scalar(0));
2273 applyUnorientedWorkset(unorientedOutput, 0, orientedInput, 0, startCell, Cw, N, workspace1, workspace2);
2274
2275 OrientationTools<DeviceType>::modifyBasisByOrientation(orientedOutput, unorientedOutput, orientationsWorkset, _basisLeft.get());
2276
2277 auto sumPolicy = Kokkos::MDRangePolicy<ExecutionSpace,Kokkos::Rank<3>>({0,0,0},{Cw,F1,N});
2278 Kokkos::parallel_for("PAMatrix::apply(): sum oriented output into outputVector", sumPolicy,
2279 KOKKOS_LAMBDA(const ordinal_type &c, const ordinal_type &f, const ordinal_type &n)
2280 {
2281 outputVector.access(c+startCell,f,n) += orientedOutput(c,f,n);
2282 });
2283 }
2284 ExecutionSpace().fence();
2285}
2286
2287template<typename DeviceType,class Scalar>
2289{
2290 Impl::PAMatrixGEMMStatistics::enabled() = enabled;
2291}
2292
2293template<typename DeviceType,class Scalar>
2295{
2296 return Impl::PAMatrixGEMMStatistics::enabled();
2297}
2298
2299template<typename DeviceType,class Scalar>
2301{
2302 return Impl::PAMatrixGEMMStatistics::cumulativeFlops();
2303}
2304
2305template<typename DeviceType,class Scalar>
2307{
2308 // rank-local (no communication)
2309 return Impl::PAMatrixGEMMStatistics::timer()->totalElapsedTime();
2310}
2311
2312template<typename DeviceType,class Scalar>
2313double PAMatrix<DeviceType,Scalar>::gemmThroughputGFlops(const double baseFlopCount, const double baseTimeSeconds)
2314{
2315 const double timeInSeconds = gemmTimeSeconds() - baseTimeSeconds;
2316 if (timeInSeconds > 0)
2317 {
2318 const double approximateFlopCountTotal = gemmFlopCount() - baseFlopCount;
2319 return approximateFlopCountTotal / timeInSeconds / 1.0e9;
2320 }
2321 else
2322 {
2323 return 0;
2324 }
2325}
2326
2327} // end namespace Intrepid2
2328#endif
Defines DimensionInfo struct that allows specification of a dimension within a Data object.
KOKKOS_INLINE_FUNCTION DimensionInfo combinedDimensionInfo(const DimensionInfo &myData, const DimensionInfo &otherData)
Returns DimensionInfo for a Data container that combines (through multiplication, say,...
Utility methods for manipulating Intrepid2::Data objects.
@ GENERAL
arbitrary variation
@ BLOCK_PLUS_DIAGONAL
one of two dimensions in a matrix; bottom-right part of matrix is diagonal
@ MODULAR
varies according to modulus of the index
Header file for the Intrepid2::OrientationTools and Intrepid2::Impl::OrientationTools classes.
Header file for the Intrepid2::PAMatrix class; provides support for matrix partial assembly.
constexpr bool isHostDevice()
Data< Scalar, DeviceType > allocateComposedWeightedTransform(const Data< Scalar, DeviceType > &composedTransform, const TensorData< Scalar, DeviceType > &pointWeights)
Given (C,P[,D,D]) transform and (C,P) pointwise weights, construct a suitable container for storing t...
Kokkos::View< Scalar *, DeviceType > pack1DOperator(const OpDataType &opData, const bool transposeToPoints)
Packs a (F,P) or (F,P,D) 1D operator into a 1D view; if transposeToPoints, the layout is (P[,...
constexpr bool gemmUsesTeuchosBLAS()
void pointDataMultiply(const ordinal_type numDataCells, const ordinal_type startCell, const ordinal_type Cw, const ordinal_type numPoints, const ordinal_type aSpan, const ordinal_type bSpan, const Scalar *A, const Scalar *B, Scalar *C, const ordinal_type N)
For point data A(C,P,Da,Db) and vector-valued B(P[,Db],N,Cw), computes the pointwise matrix-vector pr...
void gemm(const char transA, const char transB, const ordinal_type M, const ordinal_type N, const ordinal_type K, const Scalar alpha, const Scalar *A, const ordinal_type LDA, const Scalar *B, const Scalar beta, Scalar *C)
Column-major GEMM, C = alpha * op(A) * op(B) + beta * C, with op(A) of size M x K and op(B) of size K...
constexpr bool gemmSupported()
ordinal_type pamatrixWorksetSize(const double budgetMB, const size_t perCellEntries, const ordinal_type numCells)
the number of cells per workset that fit perCellEntries entries of Scalar per cell within budgetMB,...
double parsePositiveEnvironmentNumber(const char *name, const char *value)
Parses a positive number from an environment variable; throws if the value is not a positive number.
bool pamatrixAssembleUsesUnitColumnPath(const PAMatrix< DeviceType, Scalar > &matrix)
Deprecated: use PAMatrix::supportsDirectAssembly().
The data containers in Intrepid2 that support sum factorization and other reduced-data optimizations ...
Wrapper around a Kokkos::View that allows data that is constant or repeating in various logical dimen...
static Data< DataScalar, DeviceType > allocateMatMatResult(const bool transposeA, const Data< DataScalar, DeviceType > &A_MatData, const bool transposeB, const Data< DataScalar, DeviceType > &B_MatData)
KOKKOS_INLINE_FUNCTION enable_if_t< rank==1, const Kokkos::View< typename RankExpander< DataScalar, rank >::value_type, DeviceType > & > getUnderlyingView() const
Returns the underlying view. Throws an exception if the underlying view is not rank 1.
KOKKOS_INLINE_FUNCTION reference_type getWritableEntry(const IntArgs... intArgs) const
Returns an l-value reference to the specified logical entry in the underlying view....
KOKKOS_INLINE_FUNCTION int extent_int(const int &r) const
Returns the logical extent in the specified dimension.
void clear() const
Copies 0.0 to the underlying View.
KOKKOS_INLINE_FUNCTION int getDataExtent(const ordinal_type &d) const
returns the true extent of the data corresponding to the logical dimension provided; if the data does...
KOKKOS_INLINE_FUNCTION ordinal_type getUnderlyingViewRank() const
returns the rank of the View that stores the unique data
KOKKOS_INLINE_FUNCTION DimensionInfo getDimensionInfo(const int &dim) const
Returns an object fully specifying the indicated dimension. This is used in determining appropriate s...
KOKKOS_INLINE_FUNCTION unsigned rank() const
Returns the logical rank of the Data container.
static Data< Scalar, DeviceType > transposeMatrix(const Data< Scalar, DeviceType > &matrixDataIn)
static void multiplyByCPWeights(Data< Scalar, DeviceType > &resultMatrixData, const Data< Scalar, DeviceType > &matrixDataIn, const Data< Scalar, DeviceType > &scalarDataIn)
static void modifyBasisByOrientation(Kokkos::DynRankView< outputValueType, outputProperties... > output, const Kokkos::DynRankView< inputValueType, inputProperties... > input, const OrientationViewType orts, const BasisType *basis, const bool transpose=false)
Modify basis due to orientation.
static void modifyMatrixByOrientation(Kokkos::DynRankView< outputValueType, outputProperties... > output, const Kokkos::DynRankView< inputValueType, inputProperties... > input, const OrientationViewType orts, const BasisTypeLeft *basisLeft, const BasisTypeRight *basisRight)
Modify an assembled (C,F1,F2) matrix according to orientation of the cells.
static void modifyBasisByOrientationTranspose(Kokkos::DynRankView< outputValueType, outputProperties... > output, const Kokkos::DynRankView< inputValueType, inputProperties... > input, const OrientationViewType orts, const BasisType *basis)
Modify basis due to orientation, applying the transpose of the operator applied in modifyBasisByOrien...
Partially assembled (matrix-free) representation of element matrices for integrals of tensor-product ...
void assembleByApply(Data< Scalar, DeviceType > &integrals, const PAMatrixAssemblyOptions &options) const
assembles by apply() to blocked unit columns
Kokkos::View< Scalar *, DeviceType > allocateWorkspace(const ordinal_type &worksetSize) const
Allocates and returns workspace storage suitable for providing to apply() to a vector with a workset ...
static void setGEMMStatisticsEnabled(const bool enabled)
Enables or disables recording of GEMM statistics (off by default).
void orientAssembledMatrix(Data< Scalar, DeviceType > &integrals) const
applies orientations in place to an assembled (C,F1,F2) matrix
static double gemmFlopCount()
Returns the cumulative estimated floating-point operation count for recorded GEMM calls.
static bool gemmStatisticsEnabled()
Returns true if GEMM statistics are being recorded.
bool supportsDirectAssembly() const
True if assemble() can use direct sum factorization (or contraction of unit columns) for this matrix'...
const TensorData< Scalar, DeviceType > & cellMeasures() const
The cell measures (quadrature weights times Jacobian determinants) from which the matrix was construc...
void applyUnorientedWorkset(const OutputViewType &output, const ordinal_type outputCellOffset, const InputViewType &input, const ordinal_type inputCellOffset, const ordinal_type startCell, const ordinal_type Cw, const ordinal_type N, Scalar *workspace1, Scalar *workspace2) const
Applies the unoriented matrix to cells [startCell, startCell+Cw), accumulating into output....
Data< Scalar, DeviceType > allocateMatrixStorage() const
Allocates storage for a fully-assembled matrix.
const ScalarView< Orientation, DeviceType > & orientations() const
The cell orientations (empty if none were provided).
bool hasOrdinalFilter() const
True if the left or right basis values have an ordinal filter (e.g., for Serendipity bases).
void extractDiagonal(const Data< Scalar, DeviceType > &diagonal) const
Extracts the diagonal of the matrix, placing it in diagonal. If the matrix is not square,...
PAMatrix()=default
Constructs an empty PAMatrix, which may be assigned to from a constructed one.
size_t applyWorkspacePerCell() const
the workspace size, in entries per cell and vector, required by apply()
void assemble(Data< Scalar, DeviceType > &integrals, const PAMatrixAssemblyOptions &options=PAMatrixAssemblyOptions::defaultsWithEnvironmentOverrides()) const
Fully assembles the matrix, using sum factorization.
void assembleUnitColumns(Data< Scalar, DeviceType > &integrals, const PAMatrixAssemblyOptions &options) const
assembles by contraction of unit columns (requires supportsDirectAssembly())
void apply(const OutputViewType &outputVector, const InputViewType &inputVector, const Kokkos::View< Scalar *, DeviceType > &workspace, const bool sumInto=false, const int worksetSizeIn=0) const
Applies the matrix to inputVector, placing the result in outputVector, without explicit assembly and ...
static double gemmThroughputGFlops(const double baseFlopCount=0, const double baseTimeSeconds=0)
Returns the GEMM throughput in GFlop/s; baseFlopCount and baseTimeSeconds, if provided,...
PAMatrix(const TransformedBasisValues< Scalar, DeviceType > basisValuesLeft, const TensorData< Scalar, DeviceType > cellMeasures, const TransformedBasisValues< Scalar, DeviceType > basisValuesRight, const ScalarView< Orientation, DeviceType > orientations=ScalarView< Orientation, DeviceType >(), const BasisPtrType basisLeft=Teuchos::null, const BasisPtrType basisRight=Teuchos::null)
Constructs a PAMatrix representing the contraction of basisValuesLeft against basisValuesRight contai...
Data< Scalar, DeviceType > allocateDiagonalStorage() const
Allocates and returns a container with shape (C,F), where F=min(F1,F2).
void assembleUnoriented(Data< Scalar, DeviceType > &integrals, const PAMatrixAssemblyOptions &options) const
assembles the matrix for the unoriented bases
static double gemmTimeSeconds()
Returns the cumulative time spent in recorded GEMM calls.
void assembleDirect(Data< Scalar, DeviceType > &integrals, const PAMatrixAssemblyOptions &options) const
assembles by direct sum factorization (requires supportsDirectAssembly())
View-like interface to tensor data; tensor components are stored separately and multiplied together a...
KOKKOS_INLINE_FUNCTION bool separateFirstComponent() const
Returns true if the first component is indexed separately; false if not.
KOKKOS_INLINE_FUNCTION const Data< Scalar, DeviceType > & getTensorComponent(const ordinal_type &r) const
Returns the requested tensor component.
KOKKOS_INLINE_FUNCTION ordinal_type rank() const
Returns the rank of the container.
KOKKOS_INLINE_FUNCTION std::enable_if< std::is_integral< iType >::value, ordinal_type >::type extent_int(const iType &d) const
Returns the logical extent in the requested dimension.
KOKKOS_INLINE_FUNCTION ordinal_type numTensorComponents() const
Return the number of tensorial components.
Structure-preserving representation of transformed vector data; reference space values and transforma...
KOKKOS_INLINE_FUNCTION int numCells() const
Returns the logical extent in the cell dimension, which is the 0 dimension in this container.
Struct expressing all variation information about a Data object in a single dimension,...
process-wide GEMM statistics state for PAMatrix; see PAMatrix::setGEMMStatisticsEnabled()
Options for PAMatrix::assemble(). The defaults are appropriate in most cases; the other settings are ...
static PAMatrixAssemblyOptions defaultsWithEnvironmentOverrides()
Returns default options, overridden by any of the following environment variables (for testing and pe...
@ Automatic
direct sum factorization where the structure supports it, column-blocked unit-column contraction othe...
@ ApplyToColumns
apply() to blocked unit columns (the most general path)
@ UnitColumns
column-blocked unit-column contraction where supported, apply() to unit columns otherwise
@ Automatic
used when fewer than a quarter of the (row, column) pairs of the unfiltered matrix are kept
@ Always
used whenever there is an ordinal filter
double workspaceMB
Workspace budget, in MB, used to choose the workset size for assembly.