PXL
launcher.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 <pxl/v3_api_guard.hpp>
11 #include <string>
12 #include <type_traits>
13 #include <vector>
14 #include <xpti/xpti.hpp>
15 
16 #include "pxl/direction.hpp"
17 #include "pxl/launch_result.hpp"
18 #include "pxl/map.hpp"
19 #include "pxl/module.hpp"
20 #include "pxl/ndarray.hpp"
21 #include "pxl/stage_builder.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 LaunchBuilderImpl;
32 class LaunchBuilderTestAccess;
33 class DeviceHandle;
34 } // namespace impl
35 
53 // [[nodiscard]] catches the most common new-user mistake — building the chain
54 // and forgetting `.run()`. Without it, the temporary is silently destroyed,
55 // the kernel never executes, and there is no runtime signal.
56 class [[nodiscard]] LaunchBuilder
57 {
58 public:
67  LaunchBuilder& reserve(uint32_t n);
68 
79  LaunchBuilder& tasks(uint32_t taskCount);
80 
88  LaunchBuilder& batchSize(uint32_t n);
89 
101  LaunchBuilder& clusterBitmap(uint32_t bitmap);
102 
110 
127 
142  LaunchBuilder& onMessage(Map::MessageCallback cb, void* arg = nullptr);
143 
153  LaunchBuilder& onError(Map::ErrorCallback cb, void* arg = nullptr);
154 
171 
182  LaunchBuilder& enableProfile(const xpti::ProfileConfig& config);
183 
202 
236  std::future<LaunchResult> runAsync();
237 
239  LaunchBuilder(LaunchBuilder&& other) noexcept;
241 
242  LaunchBuilder(const LaunchBuilder&) = delete;
244 
245 private:
246  LaunchBuilder(std::unique_ptr<impl::LaunchBuilderImpl> impl);
247 
248  std::unique_ptr<impl::LaunchBuilderImpl> impl_;
249  // Atomic so concurrent run()/runAsync() races on the same builder are
250  // diagnosed (returned as the "already called" failure) rather than UB.
251  // The builder is not designed to be shared across threads, but the guard
252  // is cheap and protects users from accidental sharing patterns.
253  std::atomic<bool> started_{false};
254 
255  friend class Launcher;
256  friend class impl::LaunchBuilderTestAccess;
257 };
258 
278 class Launcher
279 {
280 public:
308 
326  explicit Launcher(uint32_t deviceId);
327 
329 
330  Launcher(const Launcher&) = delete;
331  Launcher& operator=(const Launcher&) = delete;
332  Launcher(Launcher&&) noexcept;
333  Launcher& operator=(Launcher&&) noexcept;
334 
353  template <auto Func, typename... Args,
354  detail::EnableCompatibleKernelArguments<Func, Args...> = 0>
355  LaunchBuilder execute(uint32_t taskCount, Args&&... args)
356  {
357  const char* kernelName = nullptr;
358 
359 #if defined(__PXCC_ANALYSIS__)
360  kernelName = "__pxcc_placeholder__";
361 #else
362  static_assert(sizeof(pxl::KernelTraits<Func>) > 0,
363  "Kernel function not found in KernelTraits — was it compiled with pxcc?");
364  kernelName = pxl::KernelTraits<Func>::name;
365 #endif
366 
367  std::vector<ArgInfo_t> argList;
368  std::vector<std::shared_ptr<void>> storage;
369  std::vector<std::pair<void*, size_t>> syncTargets;
370  auto directions = detail::MakeKernelDirections<Func>();
371  argList.reserve(sizeof...(Args));
372  if constexpr (sizeof...(Args) > 0)
373  {
374  buildArgList(argList, storage, syncTargets, std::forward<Args>(args)...);
375  }
376 
377  if (impl_ == nullptr)
378  {
379  initFromArgs(argList, syncTargets);
380  }
381  if (!isValid())
382  {
383  return makeEmptyBuilder();
384  }
385 
386  return execute(kernelName, taskCount,
387  std::move(argList), std::move(storage), std::move(syncTargets),
388  std::move(directions));
389  }
390 
401  template <auto Func, typename... Args,
402  detail::EnableCompatibleKernelArguments<Func, Args...> = 0>
404  {
406  execute<Func>(uint32_t{0}, std::forward<Args>(args)...));
407  }
408 
425  template <auto Func, typename... Args,
426  detail::EnableCompatibleKernelArguments<Func, Args...> = 0>
427  StageBuilder stage(uint32_t taskCount, Args&&... args)
428  {
429  if (impl_ == nullptr)
430  {
431  std::vector<ArgInfo_t> tempArgList;
432  std::vector<std::shared_ptr<void>> tempStorage;
433  std::vector<std::pair<void*, size_t>> tempSyncTargets;
434  tempArgList.reserve(sizeof...(Args));
435  if constexpr (sizeof...(Args) > 0)
436  {
437  buildArgList(tempArgList, tempStorage, tempSyncTargets, std::forward<Args>(args)...);
438  }
439  initFromArgs(tempArgList, tempSyncTargets);
440  }
441  StageBuilder builder(impl_);
442  // Call returns StageBuilder& to the local; discard ref and return the
443  // local by value to enable NRVO (StageBuilder is move-only).
444  builder.stage<Func>(taskCount, std::forward<Args>(args)...);
445  return builder;
446  }
447 
455  template <auto Func, typename... Args,
456  detail::EnableCompatibleKernelArguments<Func, Args...> = 0>
458  {
460  stage<Func>(uint32_t{0}, std::forward<Args>(args)...));
461  }
462 
479  {
480  // Allocate the parent StageBuilder on the heap and transfer ownership
481  // to the returned StageGroupBuilder. Without owning the parent here,
482  // the StageGroupBuilder would hold a reference into this stack frame
483  // and dangle as soon as the function returns.
484  return StageGroupBuilder(std::make_unique<StageBuilder>(impl_));
485  }
486 
490  uint32_t deviceId() const;
491 
495  bool isValid() const;
496 
497 private:
498  LaunchBuilder execute(const char* kernelName, uint32_t taskCount,
499  std::vector<ArgInfo_t> argList,
500  std::vector<std::shared_ptr<void>> storage,
501  std::vector<std::pair<void*, size_t>> syncTargets);
502 
503  LaunchBuilder execute(const char* kernelName, uint32_t taskCount,
504  std::vector<ArgInfo_t> argList,
505  std::vector<std::shared_ptr<void>> storage,
506  std::vector<std::pair<void*, size_t>> syncTargets,
507  ArgDirections directions);
508 
509  void initFromArgs(const std::vector<ArgInfo_t>& argList,
510  const std::vector<std::pair<void*, size_t>>& syncTargets);
511  LaunchBuilder makeEmptyBuilder();
512 
513  template <typename T, typename... Rest>
514  void buildArgList(std::vector<ArgInfo_t>& argList, std::vector<std::shared_ptr<void>>& storage,
515  std::vector<std::pair<void*, size_t>>& syncTargets, T&& arg, Rest&&... rest)
516  {
517  addArg(argList, storage, syncTargets, std::forward<T>(arg));
518  if constexpr (sizeof...(rest) > 0)
519  {
520  buildArgList(argList, storage, syncTargets, std::forward<Rest>(rest)...);
521  }
522  }
523 
524  template <typename T>
525  std::enable_if_t<std::is_pointer_v<std::decay_t<T>>>
526  addArg(std::vector<ArgInfo_t>& argList, std::vector<std::shared_ptr<void>>&,
527  std::vector<std::pair<void*, size_t>>&, T&& ptr)
528  {
529  argList.emplace_back(ArgInfo_t{ArgType::DeviceMemory, static_cast<const void*>(ptr), 0});
530  }
531 
532  template <typename T>
533  std::enable_if_t<std::is_arithmetic_v<std::decay_t<T>> && !std::is_pointer_v<std::decay_t<T>> &&
534  !std::is_same_v<std::decay_t<T>, bool>>
535  addArg(std::vector<ArgInfo_t>& argList, std::vector<std::shared_ptr<void>>& storage,
536  std::vector<std::pair<void*, size_t>>&, T&& value)
537  {
538  auto stored = std::make_shared<std::decay_t<T>>(std::forward<T>(value));
539  argList.emplace_back(ArgInfo_t{ArgType::Constant, stored.get(), sizeof(std::decay_t<T>)});
540  storage.push_back(stored);
541  }
542 
543  template <typename T>
544  void addArg(std::vector<ArgInfo_t>& argList, std::vector<std::shared_ptr<void>>& storage,
545  std::vector<std::pair<void*, size_t>>& syncTargets,
546  const pxl::NDArray<T>& ndarrayArg)
547  {
548  // Copy the NDArray descriptor into heap storage so runAsync's worker
549  // thread never reads a dead caller stack frame. The data buffer behind
550  // ndarrayArg.data() is owned by pxl::allocateMemory and outlives the
551  // builder; only the descriptor needs heap-stable storage.
552  //
553  // On a device without hardware Back-Invalidate the launch synchronizes
554  // this view's host cache lines, and that works at cache-line
555  // granularity: a view sharing a line with host-written data outside it
556  // can have those host bytes written back over the kernel's output.
557  // Views that start at the allocation base, or are cache-line aligned
558  // and sized, are unaffected. The same holds for a pointer argument
559  // that points into the middle of an allocation.
560  auto storedNdarray = std::make_shared<pxl::NDArray<T>>(ndarrayArg);
561  argList.emplace_back(ArgInfo_t{ArgType::NDArray, storedNdarray.get(), sizeof(pxl::NDArray<T>)});
562  storage.push_back(storedNdarray);
563  // NDArray::size() returns int64_t; guard against negative values before casting to size_t.
564  const auto byteSize = ndarrayArg.size();
565  syncTargets.emplace_back(const_cast<void*>(static_cast<const void*>(ndarrayArg.data())),
566  byteSize > 0 ? static_cast<size_t>(byteSize) : 0);
567  }
568 
569  std::shared_ptr<impl::DeviceHandle> impl_;
570 };
571 
572 } // namespace pxl
Configurable kernel execution request.
Definition: launcher.hpp:57
LaunchBuilder & enableProfile(const xpti::ProfileConfig &config)
Enables profiling for this kernel.
LaunchBuilder(LaunchBuilder &&other) noexcept
LaunchBuilder & clusterBitmap(uint32_t bitmap)
Sets the cluster bitmap (0 = use all clusters).
LaunchBuilder & tasks(uint32_t taskCount)
Sets how many tasks invoke the kernel.
LaunchBuilder & operator=(const LaunchBuilder &)=delete
LaunchBuilder & batchSize(uint32_t n)
Sets per-task batch size for kernel execution. If not called, the runtime uses an implementation-defi...
LaunchBuilder & onError(Map::ErrorCallback cb, void *arg=nullptr)
Registers an error callback for execution failure.
LaunchBuilder & operator=(LaunchBuilder &&other) noexcept
LaunchResult run()
Executes the kernel and waits for completion.
LaunchBuilder & stream(Stream *s)
Routes the kernel through a user-managed stream.
LaunchBuilder & onComplete(Map::CompletionCallback cb, void *arg=nullptr)
Registers a completion callback for successful execution.
LaunchBuilder(const LaunchBuilder &)=delete
LaunchBuilder & reserve(uint32_t n)
Sets the number of Sub resources to reserve (Mid-Level).
LaunchBuilder & locality(LocalityMode mode)
Sets the locality mode for this kernel. If not called, the runtime uses an implementation-defined def...
LaunchBuilder & onMessage(Map::MessageCallback cb, void *arg=nullptr)
Registers a message callback for device-originated messages.
std::future< LaunchResult > runAsync()
Executes the kernel asynchronously.
Execution context for kernel launches on XCENA devices.
Definition: launcher.hpp:279
uint32_t deviceId() const
Returns the device ID.
StageGroupBuilder stage()
Begins a parallel stage group.
Definition: launcher.hpp:478
Launcher(uint32_t deviceId)
Constructs a Launcher for an explicit device ID.
StageBuilder stage(uint32_t taskCount, Args &&... args)
Begins a stage chain with a sequential kernel stage.
Definition: launcher.hpp:427
Launcher(Launcher &&) noexcept
LaunchBuilder execute(uint32_t taskCount, Args &&... args)
Launches a kernel for deferred execution.
Definition: launcher.hpp:355
Launcher & operator=(const Launcher &)=delete
Launcher(const Launcher &)=delete
detail::TaskCountRequired< LaunchBuilder > execute(Args &&... args)
Launches a kernel with only the kernel's own arguments.
Definition: launcher.hpp:403
bool isValid() const
Returns whether the launcher was initialized successfully.
detail::TaskCountRequired< StageBuilder > stage(Args &&... args)
Begins a stage chain with only the kernel's own arguments.
Definition: launcher.hpp:457
Launcher()
Constructs a Launcher with deferred device detection.
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 & stage(uint32_t taskCount, Args &&... args)
StageBuilder & reserve(uint32_t n)
Collects parallel kernels within a single stage group.
An asynchronous work queue for device operations.
Definition: stream.hpp:26
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