PXL
stage_builder.hpp
Go to the documentation of this file.
1 // SPDX-License-Identifier: Apache-2.0
2 // Copyright 2024 XCENA Inc.
3 
4 #pragma once
5 
6 #include <atomic>
7 #include <cstdint>
8 #include <future>
9 #include <memory>
10 #include <optional>
11 #include <pxl/v3_api_guard.hpp>
12 #include <string>
13 #include <type_traits>
14 #include <vector>
15 #include <xpti/xpti.hpp>
16 
17 #include "pxl/direction.hpp"
18 #include "pxl/launch_result.hpp"
19 #include "pxl/map.hpp"
20 #include "pxl/module.hpp"
21 #include "pxl/ndarray.hpp"
22 #include "pxl/stream.hpp"
23 #include "pxl/task_count.hpp"
24 #include "pxl/type.hpp"
25 
26 namespace pxl
27 {
28 
29 namespace impl
30 {
31 class DeviceHandle;
32 
52 // Member ABI tags do not propagate to enclosing types. Keep the by-value
53 // ProfileConfig layout change visible in all stage container/builder symbols.
54 // Applications using StageBuilder/StageGroupBuilder must be rebuilt.
55 struct [[gnu::abi_tag("xpti_" XPTI_ABI_TAG)]] KnobConfig
56 {
57  std::optional<uint32_t> batchSize;
58  std::optional<uint32_t> clusterBitmap;
59  std::optional<pxl::LocalityMode> locality;
60 
61  std::optional<pxl::Map::CompletionCallback> onComplete;
62  void* onCompleteArg = nullptr;
63  std::optional<pxl::Map::MessageCallback> onMessage;
64  void* onMessageArg = nullptr;
65  std::optional<pxl::Map::ErrorCallback> onError;
66  void* onErrorArg = nullptr;
67 
68  // stream knob — 3-state semantics:
69  // unset (nullopt): leave Map's default stream untouched
70  // set, non-null: route through user-supplied Stream
71  // set, null: explicitly reset Map back to its default stream
72  // (Without this distinction, stream(nullptr) was a silent no-op and there
73  // was no way to opt back out of a previously set user stream.)
74  std::optional<pxl::Stream*> stream; // nullopt = leave default; non-null = user stream; null = reset to default
75  std::optional<xpti::ProfileConfig> profileConfig;
76 };
77 
78 struct [[gnu::abi_tag("xpti_" XPTI_ABI_TAG)]] StageEntry
79 {
80  std::string kernelName;
81  uint32_t taskCount = 0;
82  std::vector<ArgInfo_t> argList;
83  std::vector<std::shared_ptr<void>> constStorage;
84  std::vector<std::pair<void*, size_t>> syncTargets;
85  KnobConfig knobs;
86 };
87 
88 struct StageDirectionMetadata
89 {
90  ArgDirections directions;
91 
92  // The shared_ptr control block owns the directions; there is no pointee.
93  void operator()(void*) const noexcept
94  {
95  }
96 };
97 
98 inline void attachStageDirections(StageEntry& entry, ArgDirections directions)
99 {
100  if (directions.args.empty())
101  {
102  return;
103  }
104  entry.constStorage.emplace_back(nullptr, StageDirectionMetadata{std::move(directions)});
105 }
106 
107 inline const ArgDirections& stageDirections(const StageEntry& entry)
108 {
109  static const ArgDirections LegacyDirections;
110  for (auto it = entry.constStorage.rbegin(); it != entry.constStorage.rend(); ++it)
111  {
112  if (const auto* metadata = std::get_deleter<StageDirectionMetadata>(*it))
113  {
114  return metadata->directions;
115  }
116  }
117  return LegacyDirections;
118 }
119 
120 struct [[gnu::abi_tag("xpti_" XPTI_ABI_TAG)]] StageGroup
121 {
122  std::vector<StageEntry> entries;
123 };
124 
125 } // namespace impl
126 
127 class [[gnu::abi_tag("xpti_" XPTI_ABI_TAG)]] StageGroupBuilder;
128 
153 // [[nodiscard]] guards against building a stage chain and forgetting `.run()`.
154 class [[nodiscard, gnu::abi_tag("xpti_" XPTI_ABI_TAG)]] StageBuilder
155 {
156 public:
157  StageBuilder(std::shared_ptr<impl::DeviceHandle> device);
159 
161  StageBuilder& operator=(StageBuilder&&) noexcept;
162  StageBuilder(const StageBuilder&) = delete;
163  StageBuilder& operator=(const StageBuilder&) = delete;
164 
165  template <auto Func, typename... Args,
166  detail::EnableCompatibleKernelArguments<Func, Args...> = 0>
167  StageBuilder& stage(uint32_t taskCount, Args&&... args)
168  {
169  const char* kernelName = nullptr;
170 #if defined(__PXCC_ANALYSIS__)
171  kernelName = "__pxcc_placeholder__";
172 #else
173  static_assert(sizeof(pxl::KernelTraits<Func>) > 0,
174  "Kernel function not found in KernelTraits — was it compiled with pxcc?");
175  kernelName = pxl::KernelTraits<Func>::name;
176 #endif
177 
178  impl::StageEntry entry;
179  entry.kernelName = kernelName;
180  entry.taskCount = taskCount;
181  entry.argList.reserve(sizeof...(Args));
182  if constexpr (sizeof...(Args) > 0)
183  {
184  buildArgList(entry.argList, entry.constStorage, entry.syncTargets, std::forward<Args>(args)...);
185  }
186  impl::attachStageDirections(entry, detail::MakeKernelDirections<Func>());
187 
188  impl::StageGroup group;
189  group.entries.push_back(std::move(entry));
190  stages_.push_back(std::move(group));
191  return *this;
192  }
193 
200  template <auto Func, typename... Args,
201  detail::EnableCompatibleKernelArguments<Func, Args...> = 0>
203 
204  template <auto Func, typename... Args,
205  detail::EnableCompatibleKernelArguments<Func, Args...> = 0>
206  detail::TaskCountRequired<StageBuilder> stage(Args&&... args) & = delete;
207 
209  StageBuilder& reserve(uint32_t n);
210 
213  StageBuilder& tasks(uint32_t taskCount);
214 
220  StageBuilder& batchSize(uint32_t n);
221 
224  StageBuilder& clusterBitmap(uint32_t bitmap);
225 
228 
231 
233  StageBuilder& onMessage(Map::MessageCallback cb, void* arg = nullptr);
234 
236  StageBuilder& onError(Map::ErrorCallback cb, void* arg = nullptr);
237 
240 
243  StageBuilder& enableProfile(const xpti::ProfileConfig& config);
244 
249  std::future<LaunchResult> runAsync();
250 
251 private:
252  template <typename T, typename... Rest>
253  void buildArgList(std::vector<ArgInfo_t>& argList, std::vector<std::shared_ptr<void>>& storage,
254  std::vector<std::pair<void*, size_t>>& syncTargets, T&& arg, Rest&&... rest)
255  {
256  addArg(argList, storage, syncTargets, std::forward<T>(arg));
257  if constexpr (sizeof...(rest) > 0)
258  {
259  buildArgList(argList, storage, syncTargets, std::forward<Rest>(rest)...);
260  }
261  }
262 
263  template <typename T>
264  std::enable_if_t<std::is_pointer_v<std::decay_t<T>>>
265  addArg(std::vector<ArgInfo_t>& argList, std::vector<std::shared_ptr<void>>&,
266  std::vector<std::pair<void*, size_t>>&, T&& ptr)
267  {
268  argList.emplace_back(ArgInfo_t{ArgType::DeviceMemory, static_cast<const void*>(ptr), 0});
269  }
270 
271  template <typename T>
272  std::enable_if_t<std::is_arithmetic_v<std::decay_t<T>> && !std::is_pointer_v<std::decay_t<T>> &&
273  !std::is_same_v<std::decay_t<T>, bool>>
274  addArg(std::vector<ArgInfo_t>& argList, std::vector<std::shared_ptr<void>>& storage,
275  std::vector<std::pair<void*, size_t>>&, T&& value)
276  {
277  auto stored = std::make_shared<std::decay_t<T>>(std::forward<T>(value));
278  argList.emplace_back(ArgInfo_t{ArgType::Constant, stored.get(), sizeof(std::decay_t<T>)});
279  storage.push_back(stored);
280  }
281 
282  template <typename T>
283  void addArg(std::vector<ArgInfo_t>& argList, std::vector<std::shared_ptr<void>>& storage,
284  std::vector<std::pair<void*, size_t>>& syncTargets,
285  const pxl::NDArray<T>& ndarrayArg)
286  {
287  // Copy the NDArray descriptor into heap storage so we don't stash the
288  // caller's stack address into argList. The caller's NDArray may be a
289  // function-local rvalue that dies before runAsync's worker reads it;
290  // without this copy the worker would dereference a dead stack frame.
291  // The underlying data buffer (the device-memory pointer behind data())
292  // must remain valid until execution completes.
293  auto storedNdarray = std::make_shared<pxl::NDArray<T>>(ndarrayArg);
294  argList.emplace_back(ArgInfo_t{ArgType::NDArray, storedNdarray.get(), sizeof(pxl::NDArray<T>)});
295  storage.push_back(storedNdarray);
296  const auto byteSize = ndarrayArg.size();
297  syncTargets.emplace_back(const_cast<void*>(static_cast<const void*>(ndarrayArg.data())),
298  byteSize > 0 ? static_cast<size_t>(byteSize) : 0);
299  }
300 
301  std::shared_ptr<impl::DeviceHandle> device_;
302  std::vector<impl::StageGroup> stages_;
303  uint32_t reserveCount_ = 0;
304  // Atomic: same rationale as LaunchBuilder::started_ — guard against
305  // accidental cross-thread reuse, return the documented "already called"
306  // error rather than UB.
307  std::atomic<bool> started_{false};
308 
309  StageGroupBuilder takeStageGroup() &&;
310 
311  friend class StageGroupBuilder;
312  template <typename>
314 };
315 
332 class [[nodiscard, gnu::abi_tag("xpti_" XPTI_ABI_TAG)]] StageGroupBuilder
333 {
334 public:
335  template <auto Func, typename... Args,
336  detail::EnableCompatibleKernelArguments<Func, Args...> = 0>
337  StageGroupBuilder& add(uint32_t taskCount, Args&&... args)
338  {
339  const char* kernelName = nullptr;
340 #if defined(__PXCC_ANALYSIS__)
341  kernelName = "__pxcc_placeholder__";
342 #else
343  static_assert(sizeof(pxl::KernelTraits<Func>) > 0,
344  "Kernel function not found in KernelTraits — was it compiled with pxcc?");
345  kernelName = pxl::KernelTraits<Func>::name;
346 #endif
347 
348  impl::StageEntry entry;
349  entry.kernelName = kernelName;
350  entry.taskCount = taskCount;
351  entry.argList.reserve(sizeof...(Args));
352  if constexpr (sizeof...(Args) > 0)
353  {
354  parent_.buildArgList(entry.argList, entry.constStorage, entry.syncTargets,
355  std::forward<Args>(args)...);
356  }
357  impl::attachStageDirections(entry, detail::MakeKernelDirections<Func>());
358  currentGroup_.entries.push_back(std::move(entry));
359  return *this;
360  }
361 
367  template <auto Func, typename... Args,
368  detail::EnableCompatibleKernelArguments<Func, Args...> = 0>
370 
371  template <auto Func, typename... Args,
372  detail::EnableCompatibleKernelArguments<Func, Args...> = 0>
374 
376  StageGroupBuilder& tasks(uint32_t taskCount);
377 
378  template <auto Func, typename... Args,
379  detail::EnableCompatibleKernelArguments<Func, Args...> = 0>
380  StageBuilder& stage(uint32_t taskCount, Args&&... args)
381  {
382  flush();
383  return parent_.stage<Func>(taskCount, std::forward<Args>(args)...);
384  }
385 
388  template <auto Func, typename... Args,
389  detail::EnableCompatibleKernelArguments<Func, Args...> = 0>
391 
392  template <auto Func, typename... Args,
393  detail::EnableCompatibleKernelArguments<Func, Args...> = 0>
394  detail::TaskCountRequired<StageBuilder> stage(Args&&... args) & = delete;
395 
397  {
398  flush();
399  return parent_.stage();
400  }
401 
403  {
404  flush();
405  return parent_.run();
406  }
407 
408  std::future<LaunchResult> runAsync()
409  {
410  flush();
411  return parent_.runAsync();
412  }
413 
415  {
416  parent_.reserve(n);
417  return *this;
418  }
419 
426 
429  StageGroupBuilder& clusterBitmap(uint32_t bitmap);
430 
433 
436 
439 
441  StageGroupBuilder& onError(Map::ErrorCallback cb, void* arg = nullptr);
442 
445 
448  StageGroupBuilder& enableProfile(const xpti::ProfileConfig& config);
449 
452 
453 private:
455  // Owning constructor: takes a heap-allocated StageBuilder when the group
456  // is created from a temporary parent (e.g. Launcher::stage() no-arg).
457  // Without this, parent_ would dangle once the temporary expires.
458  StageGroupBuilder(std::unique_ptr<StageBuilder> owned);
459  void flush();
460  StageGroupBuilder takeStageGroup() &&;
461 
462  // Heap-owned parent for the owning construction path; nullptr when the
463  // group is bound to an externally-owned StageBuilder.
464  std::unique_ptr<StageBuilder> owned_;
465  // Always-valid reference to the active parent (owned_.get() when owning,
466  // or the externally-supplied StageBuilder otherwise).
467  StageBuilder& parent_;
468  impl::StageGroup currentGroup_;
469  bool flushed_ = false;
470 
471  friend class StageBuilder;
472  friend class Launcher;
473  template <typename>
474  friend class detail::TaskCountConfigured;
475 };
476 
477 inline StageGroupBuilder StageBuilder::takeStageGroup() &&
478 {
479  return StageGroupBuilder(std::make_unique<StageBuilder>(std::move(*this)));
480 }
481 
482 inline StageGroupBuilder StageGroupBuilder::takeStageGroup() &&
483 {
484  flush();
485  if (owned_)
486  {
487  return StageGroupBuilder(std::move(owned_));
488  }
489  return StageGroupBuilder(std::make_unique<StageBuilder>(std::move(parent_)));
490 }
491 
492 template <auto Func, typename... Args,
495 {
496  stage<Func>(uint32_t{0}, std::forward<Args>(args)...);
497  return detail::TaskCountRequired<StageBuilder>(std::move(*this));
498 }
499 
500 template <auto Func, typename... Args,
503 {
504  add<Func>(uint32_t{0}, std::forward<Args>(args)...);
505  return detail::TaskCountRequired<StageGroupBuilder>(std::move(*this));
506 }
507 
508 template <auto Func, typename... Args,
511 {
512  auto& parent = stage<Func>(uint32_t{0}, std::forward<Args>(args)...);
513  return detail::TaskCountRequired<StageBuilder>(std::move(parent));
514 }
515 
516 } // namespace pxl
Execution context for kernel launches on XCENA devices.
Definition: launcher.hpp:279
std::function< void(void *message, void *arg)> MessageCallback
Callback function type for task message.
Definition: map.hpp:71
std::function< void(void *arg)> ErrorCallback
Callback function type for task error.
Definition: map.hpp:80
std::function< void(void *arg)> CompletionCallback
Callback function type for task completion.
Definition: map.hpp:61
NDArray is a class that can be used in both host and device code. NDArray is automatically divided in...
Definition: ndarray.hpp:27
T * data()
Definition: ndarray.hpp:93
std::int64_t size() const
Definition: ndarray.hpp:123
Builds a chain of kernel stages for sequential/parallel execution.
StageBuilder(StageBuilder &&) noexcept
StageBuilder & onMessage(Map::MessageCallback cb, void *arg=nullptr)
Registers a message callback on the most-recently-added stage.
StageBuilder & onError(Map::ErrorCallback cb, void *arg=nullptr)
Registers an error callback on the most-recently-added stage.
StageBuilder & batchSize(uint32_t n)
Sets per-task batch size for the most-recently-added stage. Affects only the last entry added via sta...
detail::TaskCountRequired< StageBuilder > stage(Args &&... args) &=delete
StageBuilder & reserve(uint32_t n)
StageBuilder(std::shared_ptr< impl::DeviceHandle > device)
StageBuilder & locality(LocalityMode mode)
Sets locality mode for the most-recently-added stage.
LaunchResult run()
detail::TaskCountRequired< StageBuilder > stage(Args &&... args) &&
StageBuilder & stream(Stream *s)
Routes the most-recently-added stage through a user-managed stream.
StageBuilder & clusterBitmap(uint32_t bitmap)
Sets cluster bitmap for the most-recently-added stage. A bit beyond the device's clusters per Sub fai...
std::future< LaunchResult > runAsync()
StageBuilder & onComplete(Map::CompletionCallback cb, void *arg=nullptr)
Registers a completion callback on the most-recently-added stage.
StageBuilder & enableProfile(const xpti::ProfileConfig &config)
Enables profiling for the most-recently-added stage. enableProfiling failures are logged but not prop...
StageBuilder & tasks(uint32_t taskCount)
StageGroupBuilder stage()
Collects parallel kernels within a single stage group.
StageGroupBuilder & add(uint32_t taskCount, Args &&... args)
StageGroupBuilder & onComplete(Map::CompletionCallback cb, void *arg=nullptr)
Registers a completion callback on the most-recently-added kernel.
std::future< LaunchResult > runAsync()
StageGroupBuilder & reserve(uint32_t n)
StageGroupBuilder(StageGroupBuilder &&) noexcept
StageGroupBuilder & clusterBitmap(uint32_t bitmap)
Sets cluster bitmap for the most-recently-added kernel in the active group. A bit beyond the device's...
StageGroupBuilder & onError(Map::ErrorCallback cb, void *arg=nullptr)
Registers an error callback on the most-recently-added kernel.
StageGroupBuilder stage()
detail::TaskCountRequired< StageBuilder > stage(Args &&... args) &=delete
detail::TaskCountRequired< StageGroupBuilder > add(Args &&... args) &=delete
StageGroupBuilder & tasks(uint32_t taskCount)
Sets the task count of the most recently added kernel in this group.
StageGroupBuilder & stream(Stream *s)
Routes the most-recently-added kernel through a user-managed stream.
StageBuilder & stage(uint32_t taskCount, Args &&... args)
StageGroupBuilder & locality(LocalityMode mode)
Sets locality mode for the most-recently-added kernel in the active group.
StageGroupBuilder & onMessage(Map::MessageCallback cb, void *arg=nullptr)
Registers a message callback on the most-recently-added kernel.
detail::TaskCountRequired< StageGroupBuilder > add(Args &&... args) &&
StageGroupBuilder & batchSize(uint32_t n)
Sets per-task batch size for the most-recently-added kernel within the active parallel group....
detail::TaskCountRequired< StageBuilder > stage(Args &&... args) &&
StageGroupBuilder & enableProfile(const xpti::ProfileConfig &config)
Enables profiling for the most-recently-added kernel. enableProfiling failures are logged but not pro...
An asynchronous work queue for device operations.
Definition: stream.hpp:26
Runnable builder that preserves the value category of settings.
Definition: task_count.hpp:25
Holds a launch request that still needs its task count.
Definition: task_count.hpp:104
std::enable_if_t< KernelArgumentsCompatibleV< Func, Actual... >, int > EnableCompatibleKernelArguments
Definition: direction.hpp:185
Definition: config.hpp:13
LocalityMode
Definition: type.hpp:107
Traits class that maps a kernel function pointer to its name string.
Definition: module.hpp:32