15#ifndef __INTREPID2_PAMATRIX_DEF_HPP__
16#define __INTREPID2_PAMATRIX_DEF_HPP__
24#include <Teuchos_Assert.hpp>
25#include <Teuchos_BLAS.hpp>
26#include <Teuchos_TimeMonitor.hpp>
28#ifdef HAVE_INTREPID2_KOKKOSKERNELS
29#include <KokkosBlas3_gemm.hpp>
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()
50 static const auto value = Teuchos::TimeMonitor::getNewTimer(
"Intrepid2::PAMatrix gemm");
57 template<
typename DeviceType>
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;
70 template<
typename DeviceType>
78 template<
typename DeviceType>
81#ifdef HAVE_INTREPID2_KOKKOSKERNELS
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)
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;
104 using ExecutionSpace =
typename DeviceType::execution_space;
105 const bool recordStatistics = PAMatrixGEMMStatistics::enabled();
106 Teuchos::RCP<Teuchos::TimeMonitor> gemmTimer;
107 if (recordStatistics)
109 ExecutionSpace().fence();
110 gemmTimer = Teuchos::rcp(
new Teuchos::TimeMonitor(*PAMatrixGEMMStatistics::timer()));
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);
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);
135 const char tA[] = {transA,
'\0'};
136 const char tB[] = {transB,
'\0'};
141 ConstView2D AView(A, rowsA, colsA);
142 KokkosBlas::gemm(ExecutionSpace(), tA, tB, alpha, AView, BView, beta, CView);
146 Kokkos::LayoutStride layoutA(rowsA, 1, colsA, LDA);
147 Stride2D AView(A, layoutA);
148 KokkosBlas::gemm(ExecutionSpace(), tA, tB, alpha, AView, BView, beta, CView);
153 if (recordStatistics)
155 ExecutionSpace().fence();
156 gemmTimer = Teuchos::null;
157 PAMatrixGEMMStatistics::cumulativeFlops() += double(M) * double(N) * double(2 * K - 1);
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 <<
"'");
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)
182 INTREPID2_TEST_FOR_EXCEPTION(aSpan != 1, std::invalid_argument,
"aSpan != 1 is not yet supported");
184 using ExecutionSpace =
typename DeviceType::execution_space;
187 auto policy = Kokkos::MDRangePolicy<ExecutionSpace,Kokkos::Rank<4>>({0,0,0,0},{aSpan,numPoints,Cw,N});
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)
193 const size_t dataCell = (numDataCells == 1) ? 0 : size_t(cell + startCell);
194 const size_t strideA = size_t(aSpan) * numPoints * numDataCells;
195 const Scalar* entryA = A + dataCell + (point + size_t(a) * numPoints) * numDataCells;
196 const Scalar* entryB = B + point + (size_t(n) + size_t(cell) * N) * bSpan * numPoints;
198 for (
int b=0; b<bSpan; b++)
200 value += *entryA * *entryB;
204 C[n + (size_t(cell) + (point + size_t(a) * numPoints) * Cw) * N] = value;
209 template<
typename DeviceType,
class Scalar>
222 for (
int r=0; r<numTensorComponents; r++)
229 int numPoints = composedTransform.
extent_int(1);
232 if (composedTransform.
rank() == 2)
236 else if (composedTransform.
rank() == 3)
241 else if (composedTransform.
rank() == 4)
249 INTREPID2_TEST_FOR_EXCEPTION(
true, std::invalid_argument,
"unsupported rank for composedTransform");
254 template<
typename DeviceType,
class Scalar,
class OpDataType>
255 Kokkos::View<Scalar*,DeviceType>
pack1DOperator(
const OpDataType &opData,
const bool transposeToPoints)
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)
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)
267 const int idx = transposeToPoints ? pt + field * opPoints : field + pt * opFields;
268 opView(idx) = opData(field,pt);
271 else if (opData.rank() == 3)
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)
278 const int idx = transposeToPoints ? d + (pt + field * opPoints) * opDim : field + (pt + d * opPoints) * opFields;
279 opView(idx) = opData(field,pt,d);
284 INTREPID2_TEST_FOR_EXCEPTION(
true, std::invalid_argument,
"PAMatrix: Unsupported component operator rank");
295 if (
const char *value = std::getenv(
"INTREPID2_PAMATRIX_ASSEMBLE_UNIT_COLUMNS"))
299 if (
const char *value = std::getenv(
"INTREPID2_PAMATRIX_ASSEMBLE_ALGORITHM"))
301 const std::string algorithm(value);
305 else TEUCHOS_TEST_FOR_EXCEPTION(
true, std::invalid_argument,
306 "INTREPID2_PAMATRIX_ASSEMBLE_ALGORITHM must be automatic, unit-columns, or apply; got '" << algorithm <<
"'");
308 if (
const char *value = std::getenv(
"INTREPID2_PAMATRIX_ASSEMBLE_WORKSPACE_MB"))
312 if (
const char *value = std::getenv(
"INTREPID2_PAMATRIX_ASSEMBLE_SPARSE_LAST"))
314 const std::string setting(value);
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 <<
"'");
327template<
class Scalar>
328ordinal_type
pamatrixWorksetSize(
const double budgetMB,
const size_t perCellEntries,
const ordinal_type numCells)
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));
337template<
typename DeviceType,
class Scalar>
342 const BasisPtrType basisLeft,
343 const BasisPtrType basisRight)
346_basisValuesLeft(basisValuesLeft),
347_basisValuesRight(basisValuesRight),
349_basisLeft(basisLeft),
350_basisRight(basisRight)
355template<
typename DeviceType,
class Scalar>
359 const BasisPtrType basis)
364template<
typename DeviceType,
class Scalar>
368 const ScalarView<Orientation,DeviceType> orientations) {
369 using ExecutionSpace =
typename DeviceType::execution_space;
372 _hasNontrivialOrientations =
false;
373 if (orientations.size() > 0)
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++;
382 _hasNontrivialOrientations = (numNotAligned > 0);
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");
390 leftOrdinalFilter_ = basisValuesLeftInput .basisValues().ordinalFilter();
391 rightOrdinalFilter_ = basisValuesRightInput.basisValues().ordinalFilter();
393 if (values.basisValues().ordinalFilter().extent_int(0) == 0)
return values;
395 unfilteredValues.setOrdinalFilter(Kokkos::View<ordinal_type*,DeviceType>());
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");
406 const int spaceDim = basisValuesLeft.spaceDim();
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)
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");
419 const int leftFamilyCount = basisValuesLeft.basisValues().numFamilies();
420 const int rightFamilyCount = basisValuesRight.basisValues().numFamilies();
424 int numTensorComponentsLeft = -1;
425 const bool leftIsVectorValued = basisValuesLeft.vectorData().isValid();
427 if (leftIsVectorValued)
429 const auto &refVectorLeft = basisValuesLeft.vectorData();
430 int numFamiliesLeft = refVectorLeft.numFamilies();
431 int numVectorComponentsLeft = refVectorLeft.numComponents();
432 for (
int familyOrdinal=0; familyOrdinal<numFamiliesLeft; familyOrdinal++)
434 for (
int vectorComponent=0; vectorComponent<numVectorComponentsLeft; vectorComponent++)
437 if (tensorData.numTensorComponents() > 0)
439 if (numTensorComponentsLeft == -1)
441 numTensorComponentsLeft = tensorData.numTensorComponents();
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");
450 numTensorComponentsLeft = basisValuesLeft.basisValues().tensorData(0).numTensorComponents();
451 for (
int familyOrdinal = 0; familyOrdinal < leftFamilyCount; familyOrdinal++)
453 INTREPID2_TEST_FOR_EXCEPTION(basisValuesLeft.basisValues().tensorData(familyOrdinal).numTensorComponents() != numTensorComponentsLeft, std::invalid_argument,
"All families must match in the number of tensor components");
456 int numTensorComponentsRight = -1;
457 const bool rightIsVectorValued = basisValuesRight.vectorData().isValid();
459 if (rightIsVectorValued)
461 const auto &refVectorRight = basisValuesRight.vectorData();
462 int numFamiliesRight = refVectorRight.numFamilies();
463 int numVectorComponentsRight = refVectorRight.numComponents();
464 for (
int familyOrdinal=0; familyOrdinal<numFamiliesRight; familyOrdinal++)
466 for (
int vectorComponent=0; vectorComponent<numVectorComponentsRight; vectorComponent++)
468 const auto &tensorData = refVectorRight.getComponent(familyOrdinal,vectorComponent);
469 if (tensorData.numTensorComponents() > 0)
471 if (numTensorComponentsRight == -1)
473 numTensorComponentsRight = tensorData.numTensorComponents();
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");
479 INTREPID2_TEST_FOR_EXCEPTION(numTensorComponentsRight != numTensorComponentsLeft, std::invalid_argument,
"Right families must match left in the number of tensor components");
484 for (
int familyOrdinal=0; familyOrdinal< rightFamilyCount; familyOrdinal++)
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");
494 const bool transposeLeft =
true;
495 const bool transposeRight =
false;
499 const int leftRank = leftTransform.
rank();
500 const int rightRank = rightTransform.rank();
502 if (leftTransform.isValid() && rightTransform.isValid())
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));
513 composedTransform.storeMatMat(transposeLeft, leftTransform, transposeRight, rightTransform);
518 const int newRank = 4;
519 auto extents = leftTransform.getExtents();
520 auto variationTypes = leftTransform.getVariationTypes();
521 extents[3] = extents[2];
523 variationTypes[3] = variationTypes[2];
525 auto leftTransformMatrix = leftTransform.shallowCopy(newRank, extents, variationTypes);
528 extents = rightTransform.getExtents();
529 variationTypes = rightTransform.getVariationTypes();
530 extents[3] = extents[2];
532 variationTypes[3] = variationTypes[2];
534 auto rightTransformMatrix = rightTransform.shallowCopy(newRank, extents, variationTypes);
537 composedTransform.storeMatMat(transposeLeft, leftTransformMatrix, transposeRight, rightTransformMatrix);
541 composedTransform = leftTransform.allocateInPlaceCombinationResult(leftTransform, rightTransform);
542 composedTransform.storeInPlaceProduct(leftTransform, rightTransform);
545 const int newRank = 4;
546 auto extents = composedTransform.getExtents();
547 auto variationTypes = composedTransform.getVariationTypes();
548 composedTransform = composedTransform.shallowCopy(newRank, extents, variationTypes);
552 const auto & rank3Transform = (leftRank == 3) ? leftTransform : rightTransform;
553 const auto & rank2Transform = (leftRank == 2) ? leftTransform : rightTransform;
561 const int newRank = 4;
562 auto extents = composedTransform.getExtents();
563 auto variationTypes = composedTransform.getVariationTypes();
567 extents[3] = extents[2];
569 variationTypes[3] = variationTypes[2];
572 composedTransform = composedTransform.shallowCopy(newRank, extents, variationTypes);
590 INTREPID2_TEST_FOR_EXCEPTION(
true, std::invalid_argument,
"Unsupported transform combination");
593 else if (leftTransform.isValid())
602 const int newRank = 4;
603 auto extents = leftTransform.getExtents();
604 auto variationTypes = leftTransform.getVariationTypes();
606 composedTransform = leftTransform.shallowCopy(newRank, extents, variationTypes);
609 case 2: composedTransform = leftTransform;
break;
611 INTREPID2_TEST_FOR_EXCEPTION(
true, std::invalid_argument,
"Unsupported transform combination");
614 else if (rightTransform.isValid())
619 case 4: composedTransform = rightTransform;
break;
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];
631 composedTransform = rightTransform.shallowCopy(newRank, extents, variationTypes);
634 case 2: composedTransform = rightTransform;
break;
636 INTREPID2_TEST_FOR_EXCEPTION(
true, std::invalid_argument,
"Unsupported transform combination");
642 Kokkos::Array<ordinal_type,4> extents {basisValuesLeft.numCells(),basisValuesLeft.numPoints(),spaceDim,spaceDim};
645 Kokkos::View<Scalar*,DeviceType> identityUnderlyingView(
"Intrepid2::PAMatrix - identity view",spaceDim);
646 Kokkos::deep_copy(identityUnderlyingView, 1.0);
651 auto composedWeightedTransform = _composedWeightedTransform;
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];
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);
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);
675 Kokkos::Array<int,3> lowerBounds {0,0,0};
676 Kokkos::Array<int,3> upperBounds {cellDataExtent,numPoints,d1_dim};
678 auto policy = Kokkos::MDRangePolicy<ExecutionSpace,Kokkos::Rank<3>>(lowerBounds, upperBounds);
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);
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);
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;
704 const int leftComponentCount = leftIsVectorValued ? basisValuesLeft. vectorData().numComponents() : 1;
705 const int rightComponentCount = rightIsVectorValued ? basisValuesRight.vectorData().numComponents() : 1;
709 std::map<std::tuple<const void*, size_t, bool>, View1D> packedOperators;
710 auto packedOperator = [&](
const auto &opData,
const bool isRight) -> View1D
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;
716 packedOperators[key] = opView;
720 const int numCells = _composedWeightedTransform.extent_int(0);
721 const int numPoints = _composedWeightedTransform.extent_int(1);
723 int leftFieldOrdinalOffset = 0;
724 for (
int leftFamilyOrdinal=0; leftFamilyOrdinal<leftFamilyCount; leftFamilyOrdinal++)
726 const int leftFieldSpan = leftIsVectorValued ? basisValuesLeft.vectorData() .numFieldsInFamily(leftFamilyOrdinal)
727 : basisValuesLeft.basisValues().numFieldsInFamily(leftFamilyOrdinal);
732 for (
int leftComponentOrdinal=0; leftComponentOrdinal<leftComponentCount; leftComponentOrdinal++)
734 TensorData<Scalar,DeviceType> leftComponent = leftIsVectorValued ? basisValuesLeft.vectorData().getComponent(leftFamilyOrdinal, leftComponentOrdinal)
735 : basisValuesLeft.basisValues().tensorData(leftFamilyOrdinal);
736 if (!leftComponent.isValid())
739 a_offset += basisValuesLeft.vectorData().numDimsForComponent(leftComponentOrdinal);
743 std::vector<OpSpec> leftOperators;
744 for (
int r=0; r<leftComponent.numTensorComponents(); r++)
746 const auto opData = leftComponent.getTensorComponent(r).getUnderlyingView();
747 leftOperators.push_back({packedOperator(opData,
false), opData.extent_int(0), opData.extent_int(1)});
750 int rightFieldOrdinalOffset = 0;
751 for (
int rightFamilyOrdinal=0; rightFamilyOrdinal<rightFamilyCount; rightFamilyOrdinal++)
753 const int rightFieldSpan = rightIsVectorValued ? basisValuesRight.vectorData() .numFieldsInFamily(rightFamilyOrdinal)
754 : basisValuesRight.basisValues().numFieldsInFamily(rightFamilyOrdinal);
758 for (
int rightComponentOrdinal=0; rightComponentOrdinal<rightComponentCount; rightComponentOrdinal++)
761 rightIsVectorValued ? basisValuesRight.vectorData().getComponent(rightFamilyOrdinal, rightComponentOrdinal)
762 : basisValuesRight.basisValues().tensorData(rightFamilyOrdinal);
763 if (!rightComponent.isValid())
766 b_offset += basisValuesRight.vectorData().numDimsForComponent(rightComponentOrdinal);
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.");
773 std::vector<OpSpec> rightOperators;
774 for (
int r=0; r<rightComponent.numTensorComponents(); r++)
776 const auto opData = rightComponent.getTensorComponent(r).getUnderlyingView();
777 rightOperators.push_back({packedOperator(opData,
true), opData.extent_int(1), opData.extent_int(0)});
780 const int aSpan = leftComponent.extent_int(2);
781 const int bSpan = rightComponent.extent_int(2);
783 PointDataSpec pointDataSpec{numCells, numPoints, a_offset, b_offset, aSpan, bSpan};
785 if (_pointDataCache.find(pointDataSpec) == _pointDataCache.end())
787 const size_t pointDataSize = size_t(numCells) * numPoints * aSpan * bSpan;
788 View1D pointDataView(
"pointDataView", pointDataSize);
790 auto composedWeightedTransform = _composedWeightedTransform;
793 if (_composedWeightedTransform.rank() == 2)
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)
799 pointDataView(cell +
size_t(pt) * numCells) = composedWeightedTransform(cell,pt);
802 else if (_composedWeightedTransform.rank() == 3)
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)
811 pointDataView(cell + (pt +
size_t(d) * numPoints) * numCells) = composedWeightedTransform(cell,pt,dOffset + d);
814 else if (_composedWeightedTransform.rank() == 4)
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)
820 pointDataView(cell + (pt + (da +
size_t(db) * aSpan) * numPoints) * numCells) = composedWeightedTransform(cell,pt,a_offset + da,b_offset + db);
823 _pointDataCache[pointDataSpec] = pointDataView;
826 const int leftGroup = leftFamilyOrdinal * leftComponentCount + leftComponentOrdinal;
827 const int rightGroup = rightFamilyOrdinal * rightComponentCount + rightComponentOrdinal;
828 componentIntegralGroups_.push_back({leftGroup, rightGroup});
830 componentIntegralsToSum_.push_back({leftOperators,pointDataSpec,rightOperators,
831 leftFieldOrdinalOffset,leftFieldSpan,rightFieldOrdinalOffset,rightFieldSpan});
833 b_offset += rightIsVectorValued ? basisValuesRight.vectorData().numDimsForComponent(rightComponentOrdinal) : 1;
835 rightFieldOrdinalOffset += rightFieldSpan;
837 a_offset += leftIsVectorValued ? basisValuesLeft.vectorData().numDimsForComponent(leftComponentOrdinal) : 1;
839 leftFieldOrdinalOffset += leftFieldSpan;
841 ExecutionSpace().fence();
844 const size_t F2 = basisValuesRight.numFields();
845 const size_t F1 = basisValuesLeft.numFields();
846 maxIntermediateSize_ = std::max(F1,F2);
848 for (
const auto &entry : componentIntegralsToSum_)
850 const auto & leftOps = std::get<0>(entry);
851 const auto & pointDataSpec = std::get<1>(entry);
852 const auto & rightOps = std::get<2>(entry);
856 size_t perCellSize = std::get<6>(entry);
857 for (
int r=
int(rightOps.size())-1; r>=0; r--)
859 perCellSize = perCellSize / rightOps[r].N * rightOps[r].M;
860 maxIntermediateSize_ = std::max(perCellSize,maxIntermediateSize_);
863 perCellSize = perCellSize / pointDataSpec.bSpan * pointDataSpec.aSpan;
864 maxIntermediateSize_ = std::max(perCellSize,maxIntermediateSize_);
866 for (
int r=
int(leftOps.size())-1; r>=0; r--)
868 perCellSize = perCellSize / leftOps[r].N * leftOps[r].M;
869 maxIntermediateSize_ = std::max(perCellSize,maxIntermediateSize_);
871 INTREPID2_TEST_FOR_EXCEPTION(perCellSize !=
size_t(std::get<4>(entry)), std::logic_error,
872 "PAMatrix: inconsistent component operator extents");
876template<
typename DeviceType,
class Scalar>
888 const int CELL_DIM = 0;
889 const auto cellMeasureData = _cellMeasures.getTensorComponent(0);
891 DimensionInfo combinedCellDimInfo = cellMeasureData.getDimensionInfo(CELL_DIM);
893 if (_basisValuesLeft.transform().isValid())
895 combinedCellDimInfo =
combinedDimensionInfo(combinedCellDimInfo, _basisValuesLeft.transform().getDimensionInfo(CELL_DIM));
897 if (_basisValuesRight.transform().isValid())
899 combinedCellDimInfo =
combinedDimensionInfo(combinedCellDimInfo, _basisValuesRight.transform().getDimensionInfo(CELL_DIM));
903 int cellDataExtent = combinedCellDimInfo.dataExtent;
905 const int numCells = _basisValuesLeft.numCells();
906 const int numFieldsLeft = _basisValuesLeft.numFields();
907 const int numFieldsRight = _basisValuesRight.numFields();
909 if (_hasNontrivialOrientations)
913 cellDataExtent = numCells;
916 Kokkos::Array<int,3> extents {numCells, numFieldsLeft, numFieldsRight};
917 Kokkos::Array<DataVariationType,3> variationTypes {cellVariationType,
GENERAL,
GENERAL};
921 Kokkos::View<Scalar***,DeviceType> data(
"Intrepid2::PAMatrix matrix storage",cellDataExtent,numFieldsLeft,numFieldsRight);
926 Kokkos::View<Scalar**,DeviceType> data(
"Intrepid2::PAMatrix matrix storage",numFieldsLeft,numFieldsRight);
931template<
typename DeviceType,
class Scalar>
934 const int CELL_DIM = 0;
935 const auto cellMeasureData = _cellMeasures.getTensorComponent(0);
937 DimensionInfo combinedCellDimInfo = cellMeasureData.getDimensionInfo(CELL_DIM);
938 if (_basisValuesLeft.transform().isValid())
941 _basisValuesLeft.transform().getDimensionInfo(CELL_DIM));
943 if (_basisValuesRight.transform().isValid())
946 _basisValuesRight.transform().getDimensionInfo(CELL_DIM));
950 int cellDataExtent = combinedCellDimInfo.dataExtent;
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);
957 if (_hasNontrivialOrientations)
960 cellDataExtent = numCells;
963 Kokkos::Array<int,2> extents {numCells, numDiagonalEntries};
964 Kokkos::Array<DataVariationType,2> variationTypes {cellVariationType,
GENERAL};
968 Kokkos::View<Scalar**,DeviceType> data(
"Intrepid2::PAMatrix diagonal storage", cellDataExtent, numDiagonalEntries);
973 Kokkos::View<Scalar*,DeviceType> data(
"Intrepid2::PAMatrix diagonal storage", numDiagonalEntries);
978template<
typename DeviceType,
class Scalar>
981 if (componentIntegralsToSum_.size() == 0)
return false;
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_)
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);
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))
1002 size_t rightFieldProduct = 1, pointProduct = 1, leftFieldProduct = 1, leftPointProduct = 1;
1003 for (
size_t r=0; r<rightOps.size(); r++)
1005 rightFieldProduct *= rightOps[r].N;
1006 pointProduct *= rightOps[r].M;
1007 leftFieldProduct *= leftOps[r].M;
1008 leftPointProduct *= leftOps[r].N;
1010 if ((rightFieldProduct !=
size_t(rightSpan)) || (leftFieldProduct !=
size_t(leftSpan)) ||
1011 (pointProduct !=
size_t(pointDataSpec.P)) || (leftPointProduct !=
size_t(pointDataSpec.P)))
1020template<
typename DeviceType,
class Scalar>
1042template<
typename DeviceType,
class Scalar>
1045 using ExecutionSpace =
typename DeviceType::execution_space;
1046 using OrdView1D = Kokkos::View<ordinal_type*,DeviceType>;
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;
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");
1058 const ordinal_type numCellsComputed = (outputRank == 3) ? integrals.
getDataExtent(0) : 1;
1060 const auto &passes = componentIntegralsToSum_;
1061 const int numPasses = int(passes.size());
1062 const int R = int(std::get<2>(passes[0]).size());
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;
1077 struct Group { std::vector<int> passes; };
1078 std::vector<Group> groups;
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++)
1083 const auto &t = passes[pass];
1085 for (
int g=0; g<int(groups.size()); g++)
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]))
1092 bool sameShape =
true;
1093 for (
int r=0; r<R-1; r++)
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);
1097 if (sameShape) { found = g;
break; }
1100 if (found < 0) { groups.push_back(Group()); found = int(groups.size()) - 1; }
1101 groups[found].passes.push_back(pass);
1104 bool anyGroupHasMultiplePasses =
false;
1105 for (
const auto &group : groups) anyGroupHasMultiplePasses = anyGroupHasMultiplePasses || (group.passes.size() > 1);
1111 int leftOffset, rightOffset;
1112 std::vector<int> F, G, Q;
1113 size_t prefixPairs = 1;
1114 int prefixLeft = 1, prefixRight = 1;
1116 OrdView1D prefixRowOffset, prefixColOffset;
1117 OrdView1D rowMap, colMap;
1119 auto pairOperator = [](
const OpSpec &leftOp,
const OpSpec &rightOp) -> View1D
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);
1132 std::vector<GroupLayout> layouts(groups.size());
1135 std::vector<int> writeFamily(groups.size(), -1);
1136 int numWriteFamilies = 0;
1137 for (
int g=0; g<int(groups.size()); g++)
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++)
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);
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++)
1155 size_t remainder = pair;
1156 int I = 0, J = 0, leftStride = 1, rightStride = 1;
1157 for (
int r=0; r<R-1; r++)
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];
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]);
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);
1185 for (
int g=0; g<int(groups.size()); g++)
1187 for (
int h=0; h<g; h++)
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))
1192 writeFamily[g] = writeFamily[h];
1196 if (writeFamily[g] < 0) writeFamily[g] = numWriteFamilies++;
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)
1209 sortedGroups.push_back(groups[g]);
1210 sortedLayouts.push_back(layouts[g]);
1211 sortedWriteFamily.push_back(writeFamily[g]);
1213 groups = sortedGroups;
1214 layouts = sortedLayouts;
1215 writeFamily = sortedWriteFamily;
1219 bool useSparseLast =
false;
1221 const bool hasFilter = hasLeftFilter || hasRightFilter;
1222 const double keptFraction = double(numFieldsLeft) * numFieldsRight / (double(numFullLeft) * numFullRight);
1223 switch (options.sparseLastStage)
1227 case PAMatrixAssemblyOptions::SparseLastStage::Never: useSparseLast =
false;
break;
1232 std::vector<OrdView1D> keptPairV(groups.size()), keptIJV(groups.size()), keptRowV(groups.size()), keptColV(groups.size());
1235 for (
int g=0; g<int(groups.size()); g++)
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++)
1246 for (
int jLast=0; jLast<GLast; jLast++)
1248 const ordinal_type col = colHost(prefixColHost(pair) + jLast * L.prefixRight);
1249 if (col < 0)
continue;
1250 for (
int iLast=0; iLast<FLast; iLast++)
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);
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);
1269 size_t perCellEntries = 0;
1270 for (
const auto &L : layouts)
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++)
1277 size = size / L.Q[r] * L.F[r] * L.G[r];
1278 maxSize = std::max(maxSize, size);
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);
1284 const int numBuffers = 2 + (anyGroupHasMultiplePasses ? 1 : 0) + (useSparseLast ? 0 : 1);
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);
1295 if (outputRank == 3) Kokkos::deep_copy(integrals.template getUnderlyingView<3>(), Scalar(0));
1296 else Kokkos::deep_copy(integrals.template getUnderlyingView<2>(), Scalar(0));
1299 std::vector<std::vector<View1D>> pairOps(numPasses);
1300 for (
int pass=0; pass<numPasses; pass++)
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]));
1306 for (ordinal_type cellStart=0; cellStart<numCellsComputed; cellStart+=worksetSize)
1308 const ordinal_type Cw = std::min(worksetSize, numCellsComputed - cellStart);
1310 for (
int g=0; g<int(groups.size()); g++)
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;
1316 const bool singlePass = (groups[g].passes.size() == 1);
1317 View1D groupSum = singlePass ? View1D() : groupSumBuffer;
1319 bool firstPass =
true;
1320 for (
int pass : groups[g].passes)
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;
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);
1337 View1D current = bufferA, other = bufferB;
1338 size_t currentSize = size_t(numPointsTotal) * Cw;
1339 for (
int r=0; r<R-1; r++)
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);
1349 pairOps[pass][r].data(), beta, target.data());
1350 currentSize = X * FG;
1351 if (!sumIntoGroup) std::swap(current, other);
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); });
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;
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;
1387 L.pairOpLast.data(), firstInFamily ? Scalar(0) : Scalar(1), lastAccumulator.data());
1388 if (!lastInFamily)
continue;
1389 auto source = lastAccumulator;
1392 auto policy = Kokkos::MDRangePolicy<ExecutionSpace,Kokkos::Rank<3>>({0,0,0},{Cw, FLast*GLast, ordinal_type(prefixPairs)});
1393 if (outputRank == 3)
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);
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);
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)
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);
1435 for (
int q=0; q<QLast; q++) value += source(sOffset + q) * P(pOffset + q);
1436 matrixView(cell + cellStart, keptRow(k), keptCol(k)) += value;
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);
1447 for (
int q=0; q<QLast; q++) value += source(sOffset + q) * P(pOffset + q);
1448 matrixView(keptRow(k), keptCol(k)) += value;
1454 ExecutionSpace().fence();
1457template<
typename DeviceType,
class Scalar>
1460 using ExecutionSpace =
typename DeviceType::execution_space;
1461 using ScratchView = Kokkos::View<Scalar*,DeviceType,Kokkos::MemoryUnmanaged>;
1463 const ordinal_type numFieldsLeft = _basisValuesLeft.numFields();
1464 const ordinal_type numFieldsRight = _basisValuesRight.numFields();
1466 const ordinal_type numCellsComputed = (outputRank == 3) ? integrals.
getDataExtent(0) : 1;
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;
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_)
1485 numLeftGroups = std::max(numLeftGroups, groups.first + 1);
1486 numRightGroups = std::max(numRightGroups, groups.second + 1);
1489 const ordinal_type maxColumnBlockSize = 64;
1490 const ordinal_type columnBlockSize = std::max<ordinal_type>(1, std::min(numFieldsRight, maxColumnBlockSize));
1493 const size_t perCellEntries = size_t(columnBlockSize) * (size_t(numPoints) * numRightGroups + 2 * maxIntermediateSize_ + numLeftRowsComputed);
1496 for (ordinal_type columnStart=0; columnStart<numFieldsRight; columnStart+=columnBlockSize)
1498 const ordinal_type blockSize = std::min(columnBlockSize, numFieldsRight - columnStart);
1499 for (ordinal_type cellStart=0; cellStart<numCellsComputed; cellStart+=worksetSize)
1501 const ordinal_type Cw = std::min(worksetSize, numCellsComputed - cellStart);
1502 Kokkos::View<Scalar***,DeviceType> outputColumns(
"PAMatrix assemble output columns", Cw, numLeftRowsComputed, blockSize);
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++)
1511 const int rightGroup = componentIntegralGroups_[integrationPass].second;
1512 if (rightGroupFilled[rightGroup])
continue;
1513 rightGroupFilled[rightGroup] =
true;
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);
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++)
1525 rightOpsArray[r] = rightOps[r];
1526 rightFieldExtents[r] = rightOps[r].N;
1527 pointExtents[r] = rightOps[r].M;
1529 auto fill = Kokkos::subview(rightFills, Kokkos::make_pair(rightGroup * pointBufferSize, (rightGroup + 1) * pointBufferSize));
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)
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))
1545 for (
int p0=0; p0<numPoints0; p0++) fill(dest + p0) = Scalar(0);
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++)
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);
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);
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);
1572 ScratchView pointDataOut = (numTensorComponents % 2 == 0) ? workspace2 : workspace1;
1574 for (
int leftGroup=0; leftGroup<numLeftGroups; leftGroup++)
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++)
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;
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)
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);
1600 if (representativePass < 0)
continue;
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);
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++)
1612 auto in = ((i+numTensorComponents+1)%2 == 0) ? workspace1 : workspace2;
1613 auto out = ((i+numTensorComponents+1)%2 == 0) ? workspace2 : workspace1;
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;
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)
1630 const size_t idx = field + (blockColumn + size_t(cell) * blockSize) * leftOutputSpan;
1631 outputColumns(cell,field+leftOrdinalOffset,blockColumn) += finalOut(idx);
1635 if (outputRank == 3)
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)
1642 const ordinal_type computedRow = hasLeftFilter ? leftOrdinalFilter(row) : row;
1643 matrix(cell + cellStart,row,columnStart + blockColumn) = outputColumns(cell,computedRow,blockColumn);
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)
1653 const ordinal_type computedRow = hasLeftFilter ? leftOrdinalFilter(row) : row;
1654 matrix(row,columnStart + blockColumn) = outputColumns(0,computedRow,blockColumn);
1657 ExecutionSpace().fence();
1662template<
typename DeviceType,
class Scalar>
1665 using ExecutionSpace =
typename DeviceType::execution_space;
1667 "PAMatrix::assemble() supports ordinal filters only for structures supported by direct assembly (see supportsDirectAssembly())");
1669 const ordinal_type numFieldsLeft = _basisValuesLeft.numFields();
1670 const ordinal_type numFieldsRight = _basisValuesRight.numFields();
1672 const ordinal_type numCellsComputed = (outputRank == 3) ? integrals.
getDataExtent(0) : 1;
1674 const ordinal_type maxColumnBlockSize = 64;
1675 const ordinal_type columnBlockSize = std::max<ordinal_type>(1, std::min(numFieldsRight, maxColumnBlockSize));
1678 const size_t perCellEntries = size_t(columnBlockSize) * (size_t(numFieldsRight) + numFieldsLeft + 2 * maxIntermediateSize_);
1681 for (ordinal_type columnStart=0; columnStart<numFieldsRight; columnStart+=columnBlockSize)
1683 const ordinal_type blockSize = std::min(columnBlockSize, numFieldsRight - columnStart);
1684 for (ordinal_type cellStart=0; cellStart<numCellsComputed; cellStart+=worksetSize)
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)
1693 inputColumns(cell,columnStart + blockColumn,blockColumn) = Scalar(1);
1695 const size_t workspaceSize = maxIntermediateSize_ * size_t(Cw) * blockSize;
1696 View1D workspace(Kokkos::view_alloc(Kokkos::WithoutInitializing,
"PAMatrix assemble apply workspace"), 2 * workspaceSize);
1698 workspace.data(), workspace.data() + workspaceSize);
1700 if (outputRank == 3)
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)
1707 matrix(cell + cellStart,row,columnStart + blockColumn) = outputColumns(cell,row,blockColumn);
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)
1717 matrix(row,columnStart + blockColumn) = outputColumns(0,row,blockColumn);
1720 ExecutionSpace().fence();
1725template<
typename DeviceType,
class Scalar>
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)
1747template<
typename DeviceType,
class Scalar>
1750 using ExecutionSpace =
typename DeviceType::execution_space;
1753 Kokkos::DynRankView<Scalar,DeviceType> unoriented(
"PAMatrix unoriented matrix", matrixView.extent(0), matrixView.extent(1), matrixView.extent(2));
1754 Kokkos::deep_copy(unoriented, matrixView);
1756 ExecutionSpace().fence();
1759template<
typename DeviceType,
class Scalar>
1762 const ordinal_type numCells = _basisValuesLeft.numCells();
1763 const ordinal_type numFieldsLeft = _basisValuesLeft.numFields();
1764 const ordinal_type numFieldsRight = _basisValuesRight.numFields();
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 ||
1770 integrals.
extent_int(2) != numFieldsRight, std::invalid_argument,
1771 "PAMatrix::assemble() output container has incompatible extents");
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()");
1781template<
typename DeviceType,
class Scalar>
1784 using ExecutionSpace =
typename DeviceType::execution_space;
1785 INTREPID2_TEST_FOR_EXCEPTION(
hasOrdinalFilter(), std::invalid_argument,
"PAMatrix::extractDiagonal() does not yet support ordinal filters");
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);
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");
1800 const auto assembleAndCopyDiagonal = [
this, numCells, numFieldsLeft, numFieldsRight, numDiagonalEntries, diagonal]()
1804 Kokkos::View<Scalar***,DeviceType> matrixView(
"PAMatrix extractDiagonal assembled temporary", numCellsStored, numFieldsLeft, numFieldsRight);
1805 Kokkos::Array<int,3> matrixExtents {numCells, numFieldsLeft, numFieldsRight};
1807 Kokkos::Array<DataVariationType,3> matrixVariationTypes {cellVariation,
GENERAL,
GENERAL};
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)
1818 diagonalView(cell,field) = matrixView(cell,field,field);
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)
1828 diagonalView(field) = matrixView(0,field,field);
1833 INTREPID2_TEST_FOR_EXCEPTION(
true, std::invalid_argument,
1834 "PAMatrix::extractDiagonal() supports only rank-1 or rank-2 underlying diagonal storage");
1836 ExecutionSpace().fence();
1839 bool useSumFactorizedPath = !_hasNontrivialOrientations;
1840 for (
const auto &integralTuple : componentIntegralsToSum_)
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);
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))
1855 useSumFactorizedPath =
false;
1859 int fieldProduct = 1;
1860 int pointProduct = 1;
1861 for (
size_t r=0; r<leftOps.size(); r++)
1863 if ((leftOps[r].M != rightOps[r].N) || (leftOps[r].N != rightOps[r].M))
1865 useSumFactorizedPath =
false;
1868 fieldProduct *= leftOps[r].M;
1869 pointProduct *= leftOps[r].N;
1871 if (!useSumFactorizedPath)
break;
1872 if ((fieldProduct != leftSpan) || (pointProduct != pointDataSpec.P))
1874 useSumFactorizedPath =
false;
1879 if (!useSumFactorizedPath)
1881 assembleAndCopyDiagonal();
1887 const int diagonalCellDataExtent = diagonal.
getDataExtent(0);
1889 for (
const auto &integralTuple : componentIntegralsToSum_)
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());
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++)
1904 fieldExtents[r] = leftOps[r].M;
1905 pointExtents[r] = leftOps[r].N;
1906 fieldProduct *= fieldExtents[r];
1907 pointProduct *= pointExtents[r];
1909 for (
int r=1; r<numTensorComponents; r++)
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);
1918 auto pointData = _pointDataCache.find(pointDataSpec)->second;
1920 if (numTensorComponents == 1)
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)
1931 const int pointDataCell = (pointDataCellExtent == 1) ? 0 : cell;
1933 for (
int point=0; point<numPoints; point++)
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);
1942 ExecutionSpace().fence();
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);
1950 const int lastDim = numTensorComponents - 1;
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)
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;
1969 for (
int point=0; point<numPointsLast; point++)
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);
1977 scratchA(entryOrdinal) = value;
1979 ExecutionSpace().fence();
1982 bool scratchAIsCurrent =
true;
1983 for (
int r=numTensorComponents-2; r>=1; r--)
1985 auto inScratch = scratchAIsCurrent ? scratchA : scratchB;
1986 auto outScratch = scratchAIsCurrent ? scratchB : scratchA;
1987 auto leftOp = leftOps[r];
1988 auto rightOp = rightOps[r];
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;
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)
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;
2010 for (
int point=0; point<pointExtent; point++)
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);
2018 outScratch(entryOrdinal) = value;
2020 ExecutionSpace().fence();
2021 scratchAIsCurrent = !scratchAIsCurrent;
2024 auto finalScratch = scratchAIsCurrent ? scratchA : scratchB;
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)
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;
2040 for (
int point=0; point<pointExtent; point++)
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);
2047 diagonalData.
getWritableEntry(cell, diagonalOffset + fieldOrdinal) += value;
2049 ExecutionSpace().fence();
2055template<
typename DeviceType,
class Scalar>
2058 size_t size = maxIntermediateSize_ * 2;
2059 if (_hasNontrivialOrientations)
2062 size += 2 * size_t(_basisValuesRight.numFields()) + 2 * size_t(_basisValuesLeft.numFields());
2067template<
typename DeviceType,
class Scalar>
2073template<
typename DeviceType,
class Scalar>
2075 const ordinal_type &n)
const
2080template<
typename DeviceType,
class Scalar>
2081template<
typename OutputViewType,
typename InputViewType>
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
2087 using ExecutionSpace =
typename DeviceType::execution_space;
2088 using ScratchView = Kokkos::View<Scalar*, DeviceType, Kokkos::MemoryUnmanaged>;
2090 const size_t workspaceSize = maxIntermediateSize_ * size_t(Cw) * N;
2091 ScratchView workspace1(workspace1Data, workspaceSize);
2092 ScratchView workspace2(workspace2Data, workspaceSize);
2094 const Scalar alpha = 1.0;
2095 const Scalar beta = 0.0;
2099 const int numIntegrationPasses = int(componentIntegralsToSum_.size());
2100 for (
int integrationPass=0; integrationPass<numIntegrationPasses; integrationPass++)
2102 const auto &integral_tuple = componentIntegralsToSum_[integrationPass];
2104 const auto & leftIntegrals = std::get<0>(integral_tuple);
2105 const PointDataSpec & pointDataSpec = std::get<1>(integral_tuple);
2107 const auto & rightIntegrals = std::get<2>(integral_tuple);
2108 const int numRightIntegrals = int(rightIntegrals.size());
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);
2115 const int numLeftIntegrals = int(leftIntegrals.size());
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)
2125 workspace1(n + (c +
size_t(f) * Cw) * N) = inputVector.access(c + inputCellOffset,f+rightOrdinalOffset,n);
2139 size_t Nr = size_t(Cw) * N * rightInputSpan;
2140 for (
int j=0; j<numRightIntegrals; j++)
2143 auto in = (j%2 == 0) ? workspace1 : workspace2;
2144 auto out = (j%2 == 0) ? workspace2 : workspace1;
2146 const int r = numRightIntegrals-j-1;
2147 const auto &op = rightIntegrals[r];
2150 const ordinal_type Pr = op.M;
2151 const ordinal_type Fr = op.N;
2152 const ordinal_type LDA = Pr;
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;
2159 auto pointDataIn = (numRightIntegrals%2 == 0) ? workspace1 : workspace2;
2160 auto pointDataOut = (numRightIntegrals%2 == 0) ? workspace2 : workspace1;
2162 const auto &pointData = _pointDataCache.find(pointDataSpec)->second;
2165 pointData.data(), pointDataIn.data(), pointDataOut.data(), N);
2167 Nr = Nr / pointDataSpec.bSpan * pointDataSpec.aSpan;
2169 for (
int i=0; i<numLeftIntegrals; i++)
2172 auto in = ((i+numRightIntegrals+1)%2 == 0) ? workspace1 : workspace2;
2173 auto out = ((i+numRightIntegrals+1)%2 == 0) ? workspace2 : workspace1;
2175 const int r = numLeftIntegrals-i-1;
2176 const auto &op = leftIntegrals[r];
2179 const ordinal_type Fr = op.M;
2180 const ordinal_type Pr = op.N;
2181 const ordinal_type LDA = Fr;
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;
2188 auto finalOut = ((numLeftIntegrals+numRightIntegrals+1)%2 == 0) ? workspace1 : workspace2;
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)
2194 const size_t idx = f + (n + size_t(c) * N) * leftOutputSpan;
2195 outputVector.access(c+outputCellOffset,f+leftOrdinalOffset,n) += finalOut(idx);
2200template<
typename DeviceType,
class Scalar>
2201template<
typename OutputViewType,
typename InputViewType>
2203 const InputViewType & inputVector,
2204 const Kokkos::View<Scalar*,DeviceType> &workspace,
2206 const int worksetSizeIn)
const
2208 INTREPID2_TEST_FOR_EXCEPTION(
hasOrdinalFilter(), std::invalid_argument,
"PAMatrix::apply() does not yet support ordinal filters");
2210 using ExecutionSpace =
typename DeviceType::execution_space;
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);
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);
2218 const ordinal_type outputN = (outputVector.rank() > 2) ? outputVector.extent_int(2) : 1;
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");
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()");
2231 Kokkos::deep_copy(outputVector, Scalar(0));
2233 const size_t workspaceSize = maxIntermediateSize_ * size_t(worksetSize) * N;
2234 Scalar *
const workspace1 = workspace.data();
2235 Scalar *
const workspace2 = workspace.data() + workspaceSize;
2237 if (!_hasNontrivialOrientations)
2239 for (ordinal_type startCell=0; startCell<C; startCell+=worksetSize)
2241 const ordinal_type Cw = std::min(worksetSize, C - startCell);
2242 applyUnorientedWorkset(outputVector, startCell, inputVector, startCell, startCell, Cw, N, workspace1, workspace2);
2244 ExecutionSpace().fence();
2251 using DynScratchView = Kokkos::DynRankView<Scalar, DeviceType, Kokkos::MemoryUnmanaged>;
2252 for (ordinal_type startCell=0; startCell<C; startCell+=worksetSize)
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);
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)
2266 unorientedInput(c,f,n) = inputVector.access(c + startCell, f, n);
2269 auto orientationsWorkset = Kokkos::subview(_orientations, cellRange);
2272 Kokkos::deep_copy(unorientedOutput, Scalar(0));
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)
2281 outputVector.access(c+startCell,f,n) += orientedOutput(c,f,n);
2284 ExecutionSpace().fence();
2287template<
typename DeviceType,
class Scalar>
2290 Impl::PAMatrixGEMMStatistics::enabled() = enabled;
2293template<
typename DeviceType,
class Scalar>
2296 return Impl::PAMatrixGEMMStatistics::enabled();
2299template<
typename DeviceType,
class Scalar>
2302 return Impl::PAMatrixGEMMStatistics::cumulativeFlops();
2305template<
typename DeviceType,
class Scalar>
2309 return Impl::PAMatrixGEMMStatistics::timer()->totalElapsedTime();
2312template<
typename DeviceType,
class Scalar>
2316 if (timeInSeconds > 0)
2318 const double approximateFlopCountTotal =
gemmFlopCount() - baseFlopCount;
2319 return approximateFlopCountTotal / timeInSeconds / 1.0e9;
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,...
@ 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::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.
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.
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.