Nektar++
Loading...
Searching...
No Matches
ElmtBlockOp.hpp
Go to the documentation of this file.
1///////////////////////////////////////////////////////////////////////////////
2//
3// File: ElmtBlockOp.hpp
4//
5// For more information, please see: http://www.nektar.info
6//
7// The MIT License
8//
9// Copyright (c) 2006 Division of Applied Mathematics, Brown University (USA),
10// Department of Aeronautics, Imperial College London (UK), and Scientific
11// Computing and Imaging Institute, University of Utah (USA).
12//
13// Permission is hereby granted, free of charge, to any person obtaining a
14// copy of this software and associated documentation files (the "Software"),
15// to deal in the Software without restriction, including without limitation
16// the rights to use, copy, modify, merge, publish, distribute, sublicense,
17// and/or sell copies of the Software, and to permit persons to whom the
18// Software is furnished to do so, subject to the following conditions:
19//
20// The above copyright notice and this permission notice shall be included
21// in all copies or substantial portions of the Software.
22//
23// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
24// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
25// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
26// THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
27// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
28// FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
29// DEALINGS IN THE SOFTWARE.
30//
31// Description:
32//
33///////////////////////////////////////////////////////////////////////////////
34
35/**
36 * @file ElmtBlockOp.hpp
37 * @brief Block-level base class, implementation-strategy tags and
38 * device launch helpers shared by every element-operator family.
39 *
40 * @details
41 * ### Blocks
42 * A block is a contiguous run of elements with identical shape, basis
43 * and quadrature -- one block per Collection of the expansion list.
44 * Grouping like elements lets one kernel process a whole batch: within
45 * a block every element carries the same number of data values, so the
46 * block's storage is a rectangular array of `num_data` values per
47 * element and component, padded to a whole multiple of the maximum
48 * vector width and optionally interleaved so that each vector lane
49 * owns one element (see
50 * LibUtilities::BlockAttributes and LibUtilities::BlockAccessor in
51 * LibUtilities/BasicUtils/Field/Block.hpp). ElmtBlockOp is the base
52 * class of the per-family block operators (e.g. BwdTransBlockOp) that
53 * apply one element operation to one such block; the whole-field
54 * ElmtOp (ElmtOp.hpp) holds one of them per block and drives them in
55 * its Apply loop.
56 *
57 * ### Implementation strategies
58 * The tag structs StdMat, SumFac, SumFacTOP and Generic name the
59 * block-level implementation strategies. The tag's `name` forms part
60 * of the block-operator factory key, and on the device back-ends the
61 * tag type also selects between kernel variants at compile time.
62 *
63 * ### Device launch helpers
64 * When NEKTAR_ENABLE_DEVICE is set this file additionally provides the
65 * launch-configuration helpers GetElmtsPerBlock() and
66 * GetDeviceKernelParameters(), which the device implementations call to
67 * size their kernel launches for the SumFac and SumFacTOP strategies.
68 * The kernel size-parameter types those launches take (runtime and
69 * compile-time forms of the element's mode and quadrature counts) and
70 * the launch-bounds helper detail::GetMaxThreadPerBlock() are in
71 * ElmtHelper.hpp.
72 */
73
74#pragma once
75
76#include <algorithm>
77#include <type_traits>
78
81
87
89{
90
91/// @brief Passes over its element groups each device thread block is
92/// assumed to make in the SumFacTOP grid-size heuristic (see
93/// GetDeviceKernelParameters()); tuned per vendor back-end.
94#if defined(NEKTAR_ENABLE_CUDA) || defined(SYCL_ENABLE_CUDA)
95static constexpr unsigned int defaultPassesPerBlock = 8u;
96#elif defined(NEKTAR_ENABLE_HIP) || defined(SYCL_ENABLE_HIP)
97static constexpr unsigned int defaultPassesPerBlock = 4u;
98#elif defined(SYCL_ENABLE_INTEL)
99static constexpr unsigned int defaultPassesPerBlock = 4u;
100#else
101static constexpr unsigned int defaultPassesPerBlock = 1u;
102#endif
103
104// Core implementation types.
105/**
106 * @brief Implementation tag: apply the operator as one dense
107 * standard-region matrix multiplied across all elements of the block.
108 */
109struct StdMat
110{
111 static inline const std::string name = "StdMat";
112};
113
114/**
115 * @brief Implementation tag: sum-factorised tensor-product evaluation
116 * with one element per vector lane.
117 *
118 * Element data is interleaved at the execution space's vector width so
119 * that each lane performs the full per-element evaluation on its own
120 * element while the batch progresses in lock-step.
121 */
122struct SumFac
123{
124 static inline const std::string name = "SumFac";
125};
126
127/**
128 * @brief Implementation tag: sum-factorised evaluation in which the
129 * threads of one device block cooperate on a single element.
130 *
131 * Threads are indexed over the work items (output points or modes)
132 * within an element, with intermediates staged in shared memory and
133 * synchronised between the sum-factorisation stages, rather than over
134 * elements as in SumFac. This exposes more parallelism per element;
135 * it is used by the device back-ends only.
136 */
138{
139 static inline const std::string name = "SumFacTOP";
140};
141
142/**
143 * @brief Implementation tag: strategy-agnostic implementation, used by
144 * families with a single implementation (e.g. Expression and
145 * MultiplyByElmtInvMass) and as the fall-back key when a requested
146 * implementation is not registered (see ElmtBlockOp::Create()).
147 */
149{
150 static inline const std::string name = "Generic";
151};
152
153/**
154 * @brief Base class of the per-family block operators: applies one
155 * element operation to every element of one block.
156 *
157 * @details
158 * A block operator is created per block by ElmtOp::Create and bound to
159 * the block's index, its representative expansion -- the block's first
160 * element, from which the shape, basis and quadrature shared by every
161 * element of the block are read, along with the block's geometry type
162 * (regular or deformed) and coordinate dimension -- and the expansion
163 * list's data warehouse, through which basis matrices and similar
164 * tables are built once and shared between operators. Geometric
165 * factors (Jacobians, derivative factors) are per element, not
166 * shared; implementations needing them fetch them for the whole block
167 * through the data warehouse (see
168 * LocalRegions/DataWarehouse/GeometricDataWarehouse.hpp).
169 *
170 * As with ElmtOp, this class sets the BlockAccessor states accepted
171 * by Apply() at compile time; the numerical work happens in the
172 * detail:: implementation classes (e.g. detail::BwdTransBlockOpImpl),
173 * which override v_Apply(). The sum-factorised implementations, and
174 * the Generic ones of the trace operators, dispatch from v_Apply() on
175 * the block's shape type, through ShapeSwitch(), into per-shape
176 * ShapeBlock definitions that CMake generates from
177 * LibUtilities/BasicUtils/Switch/BlockOpShapeBlock.cpp.in, one
178 * translation unit per shape; each ShapeBlock switches on the
179 * element's size counts and calls the implementation's OperatorND
180 * with a compile-time size parameter when they fall inside the
181 * configured switch range and a runtime one otherwise, warning once
182 * per block operator in the latter case (see #m_warnOnceTemplate and
183 * ElmtHelper.hpp). The StdMat and the remaining Generic
184 * implementations declare no ShapeBlock and act on the block directly.
185 *
186 * @tparam TFieldIn Field state of the input block.
187 * @tparam TFieldOut Field state of the output block.
188 * @tparam TData Floating-point type of the field data.
189 *
190 * @see BlockOperator for the static per-stream workspace shared by all
191 * block operators; ElmtOp for the whole-field loop this class is
192 * driven from.
193 */
194template <FieldState TFieldIn, FieldState TFieldOut, typename TData>
195class ElmtBlockOp : public BlockOperator<TData>
196{
197public:
198 /// @brief Accessor type of this operator's input block.
199 ///
200 /// #InBlock and #OutBlock are for the ShapeBlock declarations and
201 /// their generated definitions only. The shared ShapeBlock template
202 /// that generates the switch cannot restate each operator's field
203 /// states, so it takes them from these aliases, set once in the
204 /// operator's ElmtBlockOp base clause. Other code should name the
205 /// BlockAccessor type directly.
207 /// Accessor type of this operator's output block; see #InBlock.
209
210 /**
211 * @brief Create one block operator through the block-operator
212 * factory.
213 *
214 * The factory key is `TOperator::name + execStr + implStr`. If no
215 * implementation is registered under that key, the "Generic"
216 * implementation for the same execution space is tried before
217 * failing, so families providing only a Generic implementation
218 * (e.g. Expression) work whatever implementation is requested.
219 * The product is handed back through a static_pointer_cast to
220 * @p TOperator, so the registered creator must construct that
221 * class or one derived from it.
222 *
223 * @tparam TOperator Family block-operator class (e.g.
224 * BwdTransBlockOp) supplying the static `name`.
225 *
226 * @param block_idx Index of the block within the expansion
227 * list's Collections.
228 * @param exp Representative expansion of the block
229 * (its first element).
230 * @param dataWarehouse Data warehouse shared with the other
231 * operators on the expansion list.
232 * @param execStr Execution-space part of the factory
233 * key.
234 * @param implStr Implementation part of the factory key.
235 *
236 * @return The newly created block operator. Creation raises a
237 * fatal error (throws ErrorUtil::NekError) if neither the
238 * requested nor the Generic key is registered.
239 */
240 template <template <typename> typename TOperator>
241 static std::shared_ptr<TOperator<TData>> Create(
242 const unsigned int block_idx,
245 const std::string &execStr, const std::string &implStr)
246 {
247 std::string requestedKey = TOperator<TData>::name + execStr + implStr;
248
249 BlockOperatorFactory<TData> &factory = GetBlockOperatorFactory<TData>();
250
251 // No suitable operator was found.
252 if (!factory.ModuleExists(requestedKey))
253 {
254 // See if there is a Generic implementation.
255 auto requestedKey0 = requestedKey;
256 requestedKey = TOperator<TData>::name + execStr + "Generic";
257
258 if (!factory.ModuleExists(requestedKey))
259 {
260 std::stringstream msg;
261 msg << "No such operator: " << requestedKey0 << std::endl;
262 factory.PrintAvailableClasses(msg);
263 NEKERROR(ErrorUtil::efatal, msg.str());
264 }
265 }
266
267 return std::static_pointer_cast<TOperator<TData>>(
268 factory.CreateInstance(requestedKey, block_idx, exp,
269 dataWarehouse));
270 }
271
272 /**
273 * @brief Apply the element operation to every element of the
274 * block.
275 *
276 * @param inblock Input block accessor in state @p TFieldIn.
277 * @param outblock Output block accessor in state
278 * @p TFieldOut; must belong to the same block
279 * of a conforming field, so that element
280 * count and padding match @p inblock. Its
281 * interleave width need not match: the
282 * implementations reshape the data to the
283 * width they work at, restore it, and set the
284 * output's recorded width to the input's on
285 * return (see v_Apply()).
286 */
289 {
290 this->v_Apply(inblock, outblock);
291 }
292
293 /// @brief Call operator; equivalent to Apply().
296 {
297 this->v_Apply(inblock, outblock);
298 }
299
300protected:
301 /**
302 * @brief Set once the generated ShapeBlock switch code has warned
303 * that an element size outside the templated switch range fell
304 * back to the runtime-sized OperatorND call, so that the warning
305 * is issued only once per block operator (see the BlockOpSwitch
306 * templates in LibUtilities/BasicUtils/Switch).
307 */
308 bool m_warnOnceTemplate = false;
309
310 /**
311 * @brief Construct the interface part of a concrete block
312 * operator; called by the factory-registered creator functions.
313 *
314 * @param block_idx Index of the block within the expansion
315 * list's Collections.
316 * @param exp Representative expansion of the block.
317 * @param dataWarehouse Data warehouse shared with the other
318 * operators on the expansion list.
319 */
320 ElmtBlockOp(const unsigned int block_idx,
323 : BlockOperator<TData>(block_idx, exp, dataWarehouse)
324 {
325 }
326
327 ~ElmtBlockOp() override = default;
328
329 /**
330 * @brief Call @p func with the runtime @p shape as a compile-time
331 * constant, `std::integral_constant<LibUtilities::ShapeType, ...>`.
332 *
333 * Used by the v_Apply() overrides that dispatch to ShapeBlock.
334 *
335 * @param shape Shape of the block's elements.
336 * @param func Callable taking the shape constant.
337 */
338 template <typename TFunc>
339 static void ShapeSwitch(const LibUtilities::ShapeType shape, TFunc &&func)
340 {
342 switch (shape)
343 {
345 func(std::integral_constant<ShapeType, LibUtilities::Seg>{});
346 break;
348 func(std::integral_constant<ShapeType, LibUtilities::Quad>{});
349 break;
351 func(std::integral_constant<ShapeType, LibUtilities::Tri>{});
352 break;
354 func(std::integral_constant<ShapeType,
356 break;
358 func(std::integral_constant<ShapeType, LibUtilities::Hex>{});
359 break;
361 func(std::integral_constant<ShapeType, LibUtilities::Tet>{});
362 break;
364 func(std::integral_constant<ShapeType,
366 break;
368 func(std::integral_constant<ShapeType, LibUtilities::Pyr>{});
369 break;
371 func(std::integral_constant<ShapeType,
373 break;
375 func(std::integral_constant<ShapeType, LibUtilities::Prism>{});
376 break;
378 func(std::integral_constant<ShapeType,
380 break;
381 default:
382 NEKERROR(ErrorUtil::efatal, "Shape type not implemented");
383 }
384 }
385
386 /**
387 * @brief Call @p func with `std::true_type` if @p append and
388 * `std::false_type` otherwise.
389 *
390 * Used by the v_Apply() overrides to select a kernel's `APPEND`
391 * template parameter.
392 *
393 * @param append Add to the output rather than overwrite it.
394 * @param func Callable taking the append constant.
395 */
396 template <typename TFunc>
397 static void DispatchAppendFlag(const bool append, TFunc &&func)
398 {
399 if (append)
400 {
401 func(std::true_type{});
402 }
403 else
404 {
405 func(std::false_type{});
406 }
407 }
408
409 /**
410 * @brief Call @p func with `std::false_type` if @p scale is one and
411 * `std::true_type` otherwise.
412 *
413 * Used by the v_Apply() overrides to select a kernel's `SCALE`
414 * template parameter.
415 *
416 * @param scale Factor the output is multiplied by.
417 * @param func Callable taking the scaling constant.
418 */
419 template <typename TFunc>
420 static void DispatchScaleFlag(const TData scale, TFunc &&func)
421 {
422 if (scale == 1.0)
423 {
424 func(std::false_type{});
425 }
426 else
427 {
428 func(std::true_type{});
429 }
430 }
431
432 /**
433 * @brief Call @p func with `std::true_type` if @p deformed and
434 * `std::false_type` otherwise.
435 *
436 * Used by the v_Apply() overrides to select a kernel's `DEFORMED`
437 * template parameter.
438 *
439 * @param deformed The block's elements have deformed geometry.
440 * @param func Callable taking the deformed constant.
441 */
442 template <typename TFunc>
443 static void DispatchDeformedFlag(const bool deformed, TFunc &&func)
444 {
445 if (deformed)
446 {
447 func(std::true_type{});
448 }
449 else
450 {
451 func(std::false_type{});
452 }
453 }
454
455 /// The creators return a std::unique_ptr to this class, which the
456 /// factory converts to the shared_ptr it hands out; their deleter
457 /// destroys the operator through this destructor.
458 friend struct std::default_delete<ElmtBlockOp>;
459
460 /**
461 * @brief Implementation hook for Apply().
462 *
463 * Overrides must apply the element operation to all elements of
464 * the block, for every component of @p inblock, and leave
465 * @p outblock's recorded interleave width consistent with the
466 * layout they wrote (the implementations reshape back to the
467 * input's width and record it; see e.g.
468 * detail::BwdTransBlockOpImpl::OperatorNDImpl). Padding elements
469 * may be processed as full elements -- their storage is allocated
470 * and their results are ignored.
471 *
472 * @param inblock Input block accessor in state @p TFieldIn.
473 * @param outblock Output block accessor in state
474 * @p TFieldOut.
475 */
476 virtual void v_Apply(
479};
480
481#if defined(NEKTAR_ENABLE_DEVICE)
482/**
483 * @brief Launch geometry of a device kernel, from
484 * GetDeviceKernelParameters().
485 */
486struct DeviceKernelParameters
487{
488 /// Threads per block.
489 unsigned int blockSize = 0u;
490 /// Thread blocks.
491 unsigned int gridSize = 0u;
492 /// Dynamic shared memory per block in bytes.
493 unsigned int shmemSize = 0u;
494 /// Elements each thread block takes per pass.
495 unsigned int elmtsPerBlock = 0u;
496};
497
498/// Threads GetElmtsPerBlock() fills with whole SumFacTOP elements by default.
499constexpr unsigned int defaultPackingThreads = 128u;
500
501/**
502 * @brief Elements each thread block takes per pass.
503 *
504 * For SumFac one warp, a lane per element. For SumFacTOP as many whole
505 * elements, of @p dofsPerElmt threads rounded up to a power of two each, as
506 * fit in @p PACKING_THREADS threads, one at least, where an element takes at
507 * most half a warp; one otherwise, as more would leave as many threads idle
508 * and couple the elements' barriers, and one where @p PACKING_THREADS is zero.
509 *
510 * Pass the same @p dofsPerElmt to GetDeviceKernelParameters(), usually the
511 * GetDofsPerElmt() of the launch's size parameter.
512 *
513 * @tparam PACKING_THREADS Threads to fill with whole elements
514 * (SumFacTOP), at most the default block size,
515 * or zero for no packing.
516 * @param dofsPerElmt Degrees of freedom of one element, a thread
517 * each (SumFacTOP).
518 */
519template <typename Implementation,
520 unsigned int PACKING_THREADS = defaultPackingThreads>
521NEK_FORCE_INLINE static constexpr unsigned int GetElmtsPerBlock(
522 [[maybe_unused]] const unsigned int dofsPerElmt)
523{
524 static_assert(std::is_same_v<Implementation, MultiRegions::SumFac> ||
525 std::is_same_v<Implementation, MultiRegions::SumFacTOP>,
526 "Only SumFac and SumFacTOP kernels use GetElmtsPerBlock().");
527 // Packed elements share a block whose launch bounds
528 // (GetMaxThreadPerBlock()) are the default block size.
529 static_assert(PACKING_THREADS <= NektarSpaces::Device::defaultBlockSize,
530 "PACKING_THREADS exceeds the default block size of the "
531 "launch bounds.");
532
533 if constexpr (std::is_same_v<Implementation, MultiRegions::SumFac>)
534 {
536 }
537 else
538 {
539 if (dofsPerElmt <= NektarSpaces::Device::warpSize / 2)
540 {
541 // Round to power of two.
542 unsigned int elmtThreads = 1u;
543 while (elmtThreads < dofsPerElmt)
544 {
545 elmtThreads *= 2u;
546 }
547
548 // As many whole elements as fit, one at least.
549 return std::max(1u, PACKING_THREADS / elmtThreads);
550 }
551 else
552 {
553 return 1u;
554 }
555 }
556}
557
558/**
559 * @brief GetElmtsPerBlock() of a compile-time @p DOFS, as a
560 * `std::integral_constant`, for a templated GetDofsPerElmt().
561 */
562template <typename Implementation,
563 unsigned int PACKING_THREADS = defaultPackingThreads,
564 unsigned int DOFS>
565NEK_FORCE_INLINE static constexpr auto GetElmtsPerBlock(
566 std::integral_constant<unsigned int, DOFS>)
567{
568 return std::integral_constant<
569 unsigned int,
570 GetElmtsPerBlock<Implementation, PACKING_THREADS>(DOFS)>{};
571}
572
573/**
574 * @brief Launch geometry of a SumFac or SumFacTOP kernel.
575 *
576 * For SumFac a block is one warp of @p elmtsPerBlock lanes, one element
577 * each, and the grid covers the elements in @p passesPerBlock passes, the
578 * kernels striding over the grid. For SumFacTOP the block is the
579 * elements' threads, @p dofsPerElmt rounded up to a power of two each where
580 * it takes several, rounded up to whole warps, at most @p maxBlockSize, by
581 * default the device's default block size, and the grid follows a
582 * persistent-blocks heuristic bounded by thread and shared-memory occupancy,
583 * at most one block per group of @p elmtsPerBlock elements.
584 *
585 * @tparam Implementation SumFac or SumFacTOP.
586 *
587 * @param dofsPerElmt Degrees of freedom of one element, a thread
588 * each (SumFacTOP).
589 * @param nelmt Number of elements, including padding.
590 * @param shmemSize Dynamic shared memory per block in bytes.
591 * @param elmtsPerBlock Elements per block per pass, from
592 * GetElmtsPerBlock(); zero, the default, for a
593 * warp under SumFac and one element under
594 * SumFacTOP.
595 * @param passesPerBlock Passes, one group of elmtsPerBlock elements
596 * each, each block is assumed to make; zero, the
597 * default, for one under SumFac and
598 * defaultPassesPerBlock under SumFacTOP.
599 * @param maxBlockSize Most threads per block (SumFacTOP). The kernels
600 * stride their threads over an element's degrees
601 * of freedom, so the default block size is safe
602 * for any element; a kernel that keeps one thread
603 * on each and cannot stride passes
604 * NektarSpaces::Device::maximumBlockSize and
605 * refuses larger elements.
606 */
607template <typename Implementation>
608NEK_FORCE_INLINE static DeviceKernelParameters GetDeviceKernelParameters(
609 [[maybe_unused]] const unsigned int dofsPerElmt, const size_t nelmt,
610 const unsigned int shmemSize = 0u, const unsigned int elmtsPerBlock = 0u,
611 const unsigned int passesPerBlock = 0u,
612 [[maybe_unused]] const unsigned int maxBlockSize =
614{
615 static_assert(std::is_same_v<Implementation, MultiRegions::SumFac> ||
616 std::is_same_v<Implementation, MultiRegions::SumFacTOP>,
617 "Only SumFac and SumFacTOP kernels launch through "
618 "GetDeviceKernelParameters().");
619 constexpr size_t maxGridSize = 2147483647;
620 constexpr unsigned int persistentQueueFactor = 2u;
621
622 // UseSharedWorkSpace() sized the launch from these limits.
624
625 DeviceKernelParameters kernelParams;
626
627 if constexpr (std::is_same_v<Implementation, MultiRegions::SumFac>)
628 {
629 // Zero elmtsPerBlock defaults to a warp, one lane per element, as
630 // GetElmtsPerBlock() gives.
631 kernelParams.elmtsPerBlock =
633 ASSERTL0(kernelParams.elmtsPerBlock == NektarSpaces::Device::warpSize,
634 "SumFac kernels take one warp of elements per block.");
635
636 // Each block processes elmtsPerBlock elements per pass.
637 const size_t ngroups = (nelmt + kernelParams.elmtsPerBlock - 1u) /
638 kernelParams.elmtsPerBlock;
639
640 // Zero passesPerBlock defaults to one pass, a block per group.
641 const unsigned int passes = passesPerBlock ? passesPerBlock : 1u;
642
643 // One lane per element: elmtsPerBlock is the warp size.
644 kernelParams.blockSize = kernelParams.elmtsPerBlock;
645 kernelParams.gridSize = static_cast<unsigned int>(
646 std::min((ngroups + passes - 1u) / passes, maxGridSize));
647 kernelParams.shmemSize = shmemSize;
648 }
649 else if constexpr (std::is_same_v<Implementation, MultiRegions::SumFacTOP>)
650 {
651 // Zero elmtsPerBlock defaults to one element per block, as
652 // GetElmtsPerBlock() gives with a PACKING_THREADS of zero.
653 kernelParams.elmtsPerBlock = elmtsPerBlock ? elmtsPerBlock : 1u;
654
655 // Each block processes elmtsPerBlock elements per pass.
656 const size_t ngroups = (nelmt + kernelParams.elmtsPerBlock - 1u) /
657 kernelParams.elmtsPerBlock;
658
659 // Zero passesPerBlock defaults to defaultPassesPerBlock.
660 const unsigned int passes =
661 passesPerBlock ? passesPerBlock : defaultPassesPerBlock;
662
663 // The elements' threads, rounded up to whole warps, at most
664 // maxBlockSize.
665 unsigned int threadsPerBlock;
666 if (kernelParams.elmtsPerBlock == 1u)
667 {
668 threadsPerBlock = dofsPerElmt;
669 }
670 else
671 {
672 // Several elements of at most half a warp each, as
673 // GetElmtsPerBlock() packs them: round each up to a power of two
674 // so that a warp holds whole elements.
675 unsigned int elmtThreads = 1u;
676 while (elmtThreads < dofsPerElmt)
677 {
678 elmtThreads *= 2u;
679 }
680 threadsPerBlock = kernelParams.elmtsPerBlock * elmtThreads;
681 }
682
683 constexpr unsigned int warpsize = NektarSpaces::Device::warpSize;
684 kernelParams.blockSize =
685 std::min((threadsPerBlock + warpsize - 1u) / warpsize * warpsize,
686 maxBlockSize);
687
688 GetDeviceProperties::CheckSharedMemoryUsage(shmemSize);
689
690 const auto smCount =
691 static_cast<size_t>(GetDeviceProperties::NumMultiProcessors());
692 // Number of blocks that can achieve full occupancy on each SM
693 const size_t blocksByThreads =
694 GetDeviceProperties::MaxThreadsPerMultiprocessor() /
695 kernelParams.blockSize;
696 // Number of blocks that can fully utilize shared memory on each SM
697 const size_t blocksByShared =
698 (shmemSize == 0)
699 ? blocksByThreads
700 : GetDeviceProperties::SharedMemoryPerMultiprocessor() /
701 shmemSize;
702 const size_t residentBlocks = std::min(blocksByThreads, blocksByShared);
703 // Number of blocks to launch to keep all SMs busy, controlled by
704 // a customizable QueueFactor. This serves as a lower bound on grid size
705 const size_t launchBlocks =
706 smCount * residentBlocks * persistentQueueFactor;
707 const size_t cappedLaunchBlocks =
708 std::max<size_t>(1u, std::min(launchBlocks, maxGridSize));
709
710 // 1. If nelmt is big, then grid size is determined by ngroups
711 // over the passes to ensure each block has enough work to do;
712 // 2. If nelmt is small, then we try to ensure SMs are busy by
713 // launching enough blocks;
714 // 3. If nelmt is very small, then each block only process
715 // one group to avoid unnecessary idling.
716 kernelParams.gridSize = static_cast<unsigned int>(
717 std::min(ngroups, std::max((ngroups + passes - 1u) / passes,
718 cappedLaunchBlocks)));
719 kernelParams.shmemSize = shmemSize;
720 }
721
722 return kernelParams;
723}
724
725/**
726 * @brief Whether a kernel holds its stage intermediates in shared
727 * memory rather than in the global-memory workspace.
728 *
729 * For SumFac, true when the thread block's share of the workspace fits
730 * in the device's shared memory per block and leaves at least
731 * `1 / minOccupancyDivisor` of the multiprocessor's threads resident.
732 * For SumFacTOP, true when the thread block's whole request, workspace
733 * included, fits in the device's shared memory per block. Always false
734 * for the other implementations.
735 *
736 * The device limits are the compile-time ones of GetDeviceArchProperties()
737 * where the build's target architecture is listed, so that the result is
738 * then a constant expression for a constant @p shmemsize, and are queried
739 * from the device otherwise.
740 *
741 * @tparam Implementation Implementation tag.
742 *
743 * @param shmemsize Shared memory of one thread block in bytes with
744 * the workspace staged in it.
745 *
746 * @return Whether to place the workspace in shared memory.
747 */
748template <typename Implementation>
749NEK_FORCE_INLINE static constexpr bool UseSharedWorkSpace(
750 const size_t shmemsize)
751{
752 constexpr size_t minOccupancyDivisor = 4u;
753
754 constexpr DeviceArchProperties arch = GetDeviceArchProperties();
755 DeviceArchProperties device = arch;
756 if constexpr (!arch.known)
757 {
758 device.sharedMemoryPerBlock =
759 GetDeviceProperties::SharedMemoryPerBlock();
760 device.sharedMemoryPerMultiprocessor =
761 GetDeviceProperties::SharedMemoryPerMultiprocessor();
762 device.maxThreadsPerMultiprocessor = static_cast<size_t>(
763 GetDeviceProperties::MaxThreadsPerMultiprocessor());
764 }
765
766 if constexpr (std::is_same_v<Implementation, MultiRegions::SumFac>)
767 {
768 if (shmemsize == 0 || shmemsize > device.sharedMemoryPerBlock)
769 {
770 return false;
771 }
772 else
773 {
774 constexpr size_t warpsize = NektarSpaces::Device::warpSize;
775
776 const size_t threadsByShared =
777 device.sharedMemoryPerMultiprocessor / shmemsize * warpsize;
778
779 return threadsByShared * minOccupancyDivisor >=
780 device.maxThreadsPerMultiprocessor;
781 }
782 }
783 else if constexpr (std::is_same_v<Implementation, MultiRegions::SumFacTOP>)
784 {
785 return shmemsize <= device.sharedMemoryPerBlock;
786 }
787 else
788 {
789 return false;
790 }
791}
792
793/**
794 * @brief Elements whose workspace the global-memory workspace holds at
795 * once.
796 *
797 * Every element of the block for SumFac. For SumFacTOP the elements of
798 * one group per thread block, each block reusing its slice for the groups
799 * it takes.
800 *
801 * @tparam Implementation Implementation tag.
802 *
803 * @param nelmt Elements in the block, padding included.
804 * @param gridsize Thread blocks in the grid's first dimension.
805 * @param elmtsPerBlock Elements per thread block, from
806 * GetDeviceKernelParameters().
807 *
808 * @return Number of per-element workspaces to allocate per component.
809 */
810template <typename Implementation>
811NEK_FORCE_INLINE static size_t WorkSpaceNumElmts(
812 const size_t nelmt, const unsigned int gridsize,
813 [[maybe_unused]] const unsigned int elmtsPerBlock)
814{
815 if constexpr (std::is_same_v<Implementation, MultiRegions::SumFac>)
816 {
817 return nelmt;
818 }
819 else if constexpr (std::is_same_v<Implementation, MultiRegions::SumFacTOP>)
820 {
821 return gridsize * elmtsPerBlock;
822 }
823}
824#endif
825
826} // namespace Nektar::MultiRegions
Block-level operator base class and factory machinery shared by every operator family in the MultiReg...
#define ASSERTL0(condition, msg)
#define NEKERROR(type, msg)
Assert Level 0 – Fundamental assert which is used whether in FULLDEBUG, DEBUG or OPT compilation mode...
#define NEK_FORCE_INLINE
Definition NekInline.hpp:46
Get the BlockAttributes for a given field state from an ExpList. This method basically captures ident...
Definition Block.hpp:144
bool ModuleExists(tKey idKey)
Checks if a particular module is available.
tBasePtr CreateInstance(tKey idKey, tParam... args)
Create an instance of the class referred to by idKey.
void PrintAvailableClasses(std::ostream &pOut=std::cout)
Prints the available classes to stdout.
Common base class of the block-operator family interfaces: holds the block index, representative expa...
Base class of the per-family block operators: applies one element operation to every element of one b...
void operator()(LibUtilities::BlockAccessor< TData, TFieldIn > &inblock, LibUtilities::BlockAccessor< TData, TFieldOut > &outblock)
Call operator; equivalent to Apply().
static void DispatchAppendFlag(const bool append, TFunc &&func)
Call func with std::true_type if append and std::false_type otherwise.
static void ShapeSwitch(const LibUtilities::ShapeType shape, TFunc &&func)
Call func with the runtime shape as a compile-time constant, std::integral_constant<LibUtilities::Sha...
bool m_warnOnceTemplate
Set once the generated ShapeBlock switch code has warned that an element size outside the templated s...
ElmtBlockOp(const unsigned int block_idx, const LocalRegions::ExpansionSharedPtr &exp, LibUtilities::NekDataWarehouseSharedPtr dataWarehouse)
Construct the interface part of a concrete block operator; called by the factory-registered creator f...
static void DispatchDeformedFlag(const bool deformed, TFunc &&func)
Call func with std::true_type if deformed and std::false_type otherwise.
virtual void v_Apply(LibUtilities::BlockAccessor< TData, TFieldIn > &inblock, LibUtilities::BlockAccessor< TData, TFieldOut > &outblock)=0
Implementation hook for Apply().
static std::shared_ptr< TOperator< TData > > Create(const unsigned int block_idx, const LocalRegions::ExpansionSharedPtr &exp, LibUtilities::NekDataWarehouseSharedPtr dataWarehouse, const std::string &execStr, const std::string &implStr)
Create one block operator through the block-operator factory.
void Apply(LibUtilities::BlockAccessor< TData, TFieldIn > &inblock, LibUtilities::BlockAccessor< TData, TFieldOut > &outblock)
Apply the element operation to every element of the block.
static void DispatchScaleFlag(const TData scale, TFunc &&func)
Call func with std::false_type if scale is one and std::true_type otherwise.
std::shared_ptr< NekDataWarehouse > NekDataWarehouseSharedPtr
std::shared_ptr< Expansion > ExpansionSharedPtr
Definition Expansion.h:66
NEK_DEVICE_KERNEL void const TData *NEK_RESTRICT const TData *NEK_RESTRICT const size_t const unsigned int elmtsPerBlock
NEK_DEVICE_KERNEL void const TData *NEK_RESTRICT const TData *NEK_RESTRICT const size_t nelmt
static constexpr unsigned int defaultPassesPerBlock
Passes over its element groups each device thread block is assumed to make in the SumFacTOP grid-size...
constexpr DeviceArchProperties GetDeviceArchProperties()
Limits of the build's target architecture, known at compile time.
static void CheckDeviceArchProperties()
Check, once, that the device has the limits GetDeviceArchProperties() lists for the build's target ar...
Implementation tag: strategy-agnostic implementation, used by families with a single implementation (...
static const std::string name
Implementation tag: apply the operator as one dense standard-region matrix multiplied across all elem...
static const std::string name
Implementation tag: sum-factorised tensor-product evaluation with one element per vector lane.
static const std::string name
Implementation tag: sum-factorised evaluation in which the threads of one device block cooperate on a...
static const std::string name
static constexpr unsigned int defaultBlockSize
Definition Backends.hpp:141
static constexpr unsigned int warpSize
Definition Backends.hpp:143