Nektar++
Loading...
Searching...
No Matches
BlockOperator.hpp
Go to the documentation of this file.
1///////////////////////////////////////////////////////////////////////////////
2//
3// File: BlockOperator.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 BlockOperator.hpp
37 * @brief Block-level operator base class and factory machinery shared
38 * by every operator family in the MultiRegions library, plus the static
39 * per-stream workspace they share.
40 *
41 * @details
42 * BlockOperator fixes no input or output block type; it holds the
43 * block index, representative expansion and data warehouse a block
44 * operator was built with, provides the family-agnostic Create(), and
45 * gives every block operator access to a per-stream scratch buffer
46 * through GetStaticWorkSpace() so that repeated device and host
47 * allocation is avoided. Families that act element by element derive
48 * their block-operator base from ElmtBlockOp (ElmtOps/ElmtBlockOp.hpp)
49 * instead, which adds the implementation-strategy tags and device
50 * launch helpers on top of this class.
51 */
52
53#pragma once
54
57
61
63{
64
65// Forward-declare the BlockOperator base class so we can define the factory
66template <typename TData> class BlockOperator;
67
68namespace detail
69{
70// Forward-declare the homogeneous advection z-op so that BlockOperator can
71// befriend it; the default of its fourth parameter stays with the declaration
72// in AdvectionZOpImpl.hpp.
73template <typename ExecSpace, typename TData, bool APPEND, typename Enable>
75} // namespace detail
76
77/// @brief Factory of BlockOperator<TData> interface objects, keyed by
78/// `TOperator::name + execStr`.
79template <typename TData>
82 const unsigned int,
85
86/// @brief Return the process-wide singleton BlockOperatorFactory<TData>.
87template <typename TData>
89
90/**
91 * @brief Common base class of the block-operator family interfaces:
92 * holds the block index, representative expansion and data warehouse a
93 * block operator was built with, provides the family-agnostic
94 * Create(), and gives derived classes a per-stream scratch buffer
95 * through GetStaticWorkSpace().
96 *
97 * @tparam TData Floating-point type of the field data.
98 *
99 * @see ElmtBlockOp for the element-by-element specialisation that adds
100 * the implementation-strategy tags and device launch helpers;
101 * Operator for the whole-field counterpart this class is created
102 * alongside.
103 */
104template <typename TData> class BlockOperator
105{
106public:
107 virtual ~BlockOperator() = default;
108
109 /**
110 * @brief Create a concrete block-operator instance through the
111 * block-operator factory.
112 *
113 * The factory key is `TOperator::name + execStr`. The product is
114 * handed back through a static_pointer_cast to @p TOperator, so
115 * the creator registered under the key must construct that class
116 * or one derived from it.
117 *
118 * @tparam TOperator Family block-operator class supplying the
119 * static `name` string.
120 *
121 * @param block_idx Index of the block within the expansion
122 * list's Collections.
123 * @param exp Representative expansion of the block
124 * (its first element).
125 * @param dataWarehouse Data warehouse shared with the other
126 * operators on the expansion list.
127 * @param execStr Execution-space part of the factory
128 * key.
129 *
130 * @return The newly created block operator. Creation raises a
131 * fatal error (throws ErrorUtil::NekError) if no implementation is
132 * registered under the requested key.
133 */
134 template <template <typename> typename TOperator>
135 static std::shared_ptr<TOperator<TData>> Create(
136 const unsigned int block_idx,
139 const std::string &execStr)
140 {
141 std::string requestedKey = TOperator<TData>::name + execStr;
142
143 BlockOperatorFactory<TData> &factory = GetBlockOperatorFactory<TData>();
144
145 // No suitible operator was found.
146 if (!factory.ModuleExists(requestedKey))
147 {
148 std::stringstream msg;
149 msg << "No such operator: " << requestedKey << std::endl;
150 factory.PrintAvailableClasses(msg);
151 NEKERROR(ErrorUtil::efatal, msg.str());
152 }
153
154 return std::static_pointer_cast<TOperator<TData>>(
155 factory.CreateInstance(requestedKey, block_idx, exp,
156 dataWarehouse));
157 }
158
159protected:
160 /// Index of the block within the expansion list's Collections.
161 unsigned int m_block_idx;
162 /// Representative expansion of the block (its first element).
164 /// Data warehouse shared with the other operators on the expansion
165 /// list.
167
168 /**
169 * @brief Construct the interface part of a concrete block
170 * operator; called by the factory-registered creator functions.
171 *
172 * @param block_idx Index of the block within the expansion
173 * list's Collections.
174 * @param exp Representative expansion of the block.
175 * @param dataWarehouse Data warehouse shared with the other
176 * operators on the expansion list.
177 */
178 BlockOperator(const unsigned int block_idx,
181 : m_block_idx(block_idx), m_exp(exp), m_dataWarehouse(dataWarehouse)
182 {
183 }
184
185 /// The homogeneous advection z-op is not a block operator, but it runs
186 /// on the per-block streams and takes its scratch from the same buffers,
187 /// so it reaches GetStaticWorkSpace directly. The z-derivative op needs
188 /// no such access: the transform holds whatever buffer it accumulates
189 /// through.
190 template <typename ExecSpace, typename TDataZ, bool APPEND, typename Enable>
192
193 /**
194 * @brief Return a per-stream scratch buffer in @p MemSpace, sized
195 * to hold at least @p size elements of @p TData, growing and
196 * reallocating it as needed.
197 *
198 * The buffer is static: every BlockOperator instance in the
199 * process shares one buffer per stream, so repeated allocation and
200 * deallocation is avoided. Repeated device allocation in
201 * particular can be slow and fragment device memory, and one
202 * buffer per instance would hold onto large device blocks that are
203 * wasted while that instance is not using them, risking exhausting
204 * device memory. The current implementation assumes every
205 * BlockOperator instance executes on the default stream/queue,
206 * i.e. @p streamID is always 0.
207 *
208 * @tparam MemSpace NektarSpaces::HostSpace or
209 * NektarSpaces::DeviceSpace; selects which
210 * buffer and allocator are used.
211 *
212 * @param size Minimum number of @p TData elements the
213 * buffer must hold.
214 * @param streamID Stream/queue the buffer is kept for; each
215 * value gets its own buffer.
216 *
217 * @return Pointer to the (possibly just grown) buffer for
218 * @p streamID.
219 */
220 template <typename MemSpace>
221 static TData *GetStaticWorkSpace(const size_t size,
222 const unsigned int streamID = 0)
223 {
224 if constexpr (std::is_same_v<MemSpace, NektarSpaces::HostSpace>)
225 {
226 SetHostWorkSpace(size, streamID);
227 return m_hostWsp[streamID];
228 }
229 else if constexpr (std::is_same_v<MemSpace, NektarSpaces::DeviceSpace>)
230 {
231 SetDeviceWorkSpace(size, streamID);
232 return m_deviceWsp[streamID];
233 }
234 }
235
236private:
237 /**
238 * @brief Ensure the host scratch buffer for @p streamID exists and
239 * holds at least @p size elements, (re)allocating it if it is
240 * missing or too small.
241 *
242 * @param size Minimum number of @p TData elements required.
243 * @param streamID Stream the buffer is kept for.
244 */
245 static void SetHostWorkSpace(const size_t size, const unsigned int streamID)
246 {
247 if (m_hostWspSize.find(streamID) == m_hostWspSize.end())
248 {
249 TData *hostptr = nullptr;
250 hostMalloc(&hostptr, sizeof(TData) * size,
252 memset(hostptr, 0, sizeof(TData) * size);
253 m_hostWsp[streamID] = hostptr;
254 m_hostWspSize[streamID] = size;
255 }
256 else if (m_hostWspSize[streamID] < size)
257 {
258 TData *hostptr = m_hostWsp[streamID];
260 hostMalloc(&hostptr, sizeof(TData) * size,
262 memset(hostptr, 0, sizeof(TData) * size);
263 m_hostWsp[streamID] = hostptr;
264 m_hostWspSize[streamID] = size;
265 }
266 }
267
268 /**
269 * @brief Ensure the device scratch buffer for @p streamID exists
270 * and holds at least @p size elements, (re)allocating it if it is
271 * missing or too small.
272 *
273 * @param size Minimum number of @p TData elements required.
274 * @param streamID Stream the buffer is kept for.
275 */
276 static void SetDeviceWorkSpace(const size_t size,
277 const unsigned int streamID)
278 {
279 if (m_deviceWspSize.find(streamID) == m_deviceWspSize.end())
280 {
281 TData *deviceptr = nullptr;
282 deviceMalloc(&deviceptr, sizeof(TData) * size, streamID);
283 m_deviceWsp[streamID] = deviceptr;
284 m_deviceWspSize[streamID] = size;
285 }
286 else if (m_deviceWspSize[streamID] < size)
287 {
288 TData *deviceptr = m_deviceWsp[streamID];
289 deviceFree(deviceptr, sizeof(TData) * m_deviceWspSize[streamID],
290 streamID);
291 deviceMalloc(&deviceptr, sizeof(TData) * size, streamID);
292 m_deviceWsp[streamID] = deviceptr;
293 m_deviceWspSize[streamID] = size;
294 }
295 }
296
297 /// Device scratch buffer for each stream, keyed by stream ID.
298 static inline std::unordered_map<unsigned int, TData *> m_deviceWsp;
299 /// Element capacity of the buffer in #m_deviceWsp for each stream.
300 static inline std::unordered_map<unsigned int, size_t> m_deviceWspSize;
301 /// Host scratch buffer for each stream, keyed by stream ID.
302 static inline std::unordered_map<unsigned int, TData *> m_hostWsp;
303 /// Element capacity of the buffer in #m_hostWsp for each stream.
304 static inline std::unordered_map<unsigned int, size_t> m_hostWspSize;
305};
306
307} // namespace Nektar::MultiRegions
#define NEKERROR(type, msg)
Assert Level 0 – Fundamental assert which is used whether in FULLDEBUG, DEBUG or OPT compilation mode...
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...
static std::shared_ptr< TOperator< TData > > Create(const unsigned int block_idx, const LocalRegions::ExpansionSharedPtr &exp, LibUtilities::NekDataWarehouseSharedPtr dataWarehouse, const std::string &execStr)
Create a concrete block-operator instance through the block-operator factory.
static std::unordered_map< unsigned int, TData * > m_deviceWsp
Device scratch buffer for each stream, keyed by stream ID.
static void SetDeviceWorkSpace(const size_t size, const unsigned int streamID)
Ensure the device scratch buffer for streamID exists and holds at least size elements,...
static std::unordered_map< unsigned int, size_t > m_hostWspSize
Element capacity of the buffer in m_hostWsp for each stream.
unsigned int m_block_idx
Index of the block within the expansion list's Collections.
static TData * GetStaticWorkSpace(const size_t size, const unsigned int streamID=0)
Return a per-stream scratch buffer in MemSpace, sized to hold at least size elements of TData,...
static std::unordered_map< unsigned int, TData * > m_hostWsp
Host scratch buffer for each stream, keyed by stream ID.
static void SetHostWorkSpace(const size_t size, const unsigned int streamID)
Ensure the host scratch buffer for streamID exists and holds at least size elements,...
BlockOperator(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...
LocalRegions::ExpansionSharedPtr m_exp
Representative expansion of the block (its first element).
LibUtilities::NekDataWarehouseSharedPtr m_dataWarehouse
Data warehouse shared with the other operators on the expansion list.
static std::unordered_map< unsigned int, size_t > m_deviceWspSize
Element capacity of the buffer in m_deviceWsp for each stream.
The advection along the homogeneous direction, w du/dz.
std::shared_ptr< NekDataWarehouse > NekDataWarehouseSharedPtr
std::shared_ptr< Expansion > ExpansionSharedPtr
Definition Expansion.h:66
BlockOperatorFactory< TData > & GetBlockOperatorFactory()
Return the process-wide singleton BlockOperatorFactory<TData>, constructing it on first use.
static constexpr size_t host_memory_alignment
Definition Backends.hpp:178
void deviceFree(TData *src, const size_t size, const unsigned int streamID, const MemAllocType memAllocType=eHostPageable)
void hostFree(TData *src, const size_t alignment)
void deviceMalloc(TData **src, const size_t size, const unsigned int streamID, const MemAllocType memAllocType=eHostPageable)
void hostMalloc(TData **src, const size_t size, const size_t alignment)