reduce API#
GPU (CUDA) and CPU (OpenMP) parallel reductions. The two engines live in the
device namespaces as eagle::cuda::Reduction and eagle::cpu::Reduction;
eagle::reduce keeps the shared kernels and the native graph node.
eagle::cuda::Reduction#
-
struct Reduction
GPU parallel reduction over aether scalar arrays.
All overloads of
reduceBlockingsynchronise the CUDA stream before returning the result on the host. For graph-based (non-blocking) variants, use the overloads that accept acuda::Graph&.Note
Available only when
EAGLE_CPU_ONLYis not defined.Public Static Functions
-
template<typename T>
static inline aether::Array<T> makeBuffer(const idx_t &size) Generate a work buffer for use with
reduceBlocking, of the appropriate size to perform a reduction overarr.Note: the returned array is only allocated on the host. You will need to call
oarr.uploadbefore invokingreduceBlocking.
-
template<typename T>
static inline aether::Array<T> makeBuffer(const aether::Array<T> &arr) Generate a work buffer for use with
reduceBlocking, of the appropriate size to perform a reduction overarr.Note: the returned array is only allocated on the host. You will need to call
oarr.uploadbefore invokingreduceBlocking.
-
template<typename T, typename OP>
static inline T reduceBlocking(aether::Array<T> &arr, aether::Array<T> &oarr, const T &init = 0, const cudaStream_t &stream = 0) Perform a reduction over a GPU-allocated array using a pre-allocated work buffer.
Note: causes a blocking synchronization of the given stream.
- Template Parameters:
T – Data type of the elements
OP – Reduction operator to use. Must be callable as
OP{}(a, b)(aether’s functor shape). Example:aether::SumOp<T>
- Parameters:
arr – Input scalar array. The reduction will be performed over the device copy, but it will not be modified. Must be already allocated on the device.
oarr – Output array. Used for intermediate copies. Must be allocated on host and device. Its values on both host and device will be overwritten. It is recommended to generate it via
makeBufferto ensure it has the appropriate size. Must be distinct fromarr.init – Initial value for the accumulation.
stream – CUDA stream to use.
-
template<typename T, typename OP>
static inline T reduceBlocking(aether::Array<T> &arr, const T &init = 0, const cudaStream_t &stream = 0) Perform a reduction over a GPU-allocated array, allocating a work buffer ad-hoc.
Note: causes a blocking synchronization of the given stream.
Note that this will allocate a new, temporary work buffer on host and device. If performing multiple reductions with same-sized arrays, it may be more efficient to generate the buffer once with
makeBufferand reuse it with the overloaded version of this function.- Template Parameters:
T – Data type of the elements
OP – Reduction operator to use. Must be callable as
OP{}(a, b)(aether’s functor shape). Example:aether::SumOp<T>
- Parameters:
arr – Input scalar array. The reduction will be performed over the device copy, but it will not be modified. Must be already allocated on the device.
init – Initial value for the accumulation.
stream – CUDA stream to use.
-
template<typename T, typename OP>
static inline T reduceBlocking(const CRefArrT<T> &arr, aether::Array<T> &oarr, const T &init = 0, const cudaStream_t &stream = 0) Perform a reduction over a GPU-allocated array using a pre-allocated work buffer.
Note: causes a blocking synchronization of the given stream.
- Template Parameters:
T – Data type of the elements
OP – Reduction operator to use. Must be callable as
OP{}(a, b)(aether’s functor shape). Example:aether::SumOp<T>
- Parameters:
arr – Input scalar array. The reduction will be performed over the device copy, but it will not be modified. Must be already allocated on the device.
oarr – Output array. Used for intermediate copies. Must be allocated on host and device. Its values on both host and device will be overwritten. It is recommended to generate it via
makeBufferto ensure it has the appropriate size. Must be distinct fromarr.init – Initial value for the accumulation.
stream – CUDA stream to use.
-
template<typename T, typename OP, bool DirectCopy = false>
static inline void reduceBlocking(cuda::Graph &graph, T *result, const CRefArrT<T> &arr, aether::Array<T> &oarr, const idx_t N, const T &init = 0, const cudaStream_t &stream = 0) Build a graph to perform a reduction over a GPU-allocated array using a pre-allocated work buffer.
Note: causes a blocking synchronization of the given stream.
- Template Parameters:
T – Data type of the elements
OP – Reduction operator to use. Must be callable as
OP{}(a, b)(aether’s functor shape). Example:aether::SumOp<T>
- Parameters:
graph – Graph the reduction nodes are added to.
result – Pointer to the reduction result
arr – Input scalar array. The reduction will be performed over the device copy, but it will not be modified. Must be already allocated on the device.
oarr – Output array. Used for intermediate copies. Must be allocated on host and device. Its values on both host and device will be overwritten. It is recommended to generate it via
makeBufferto ensure it has the appropriate size. Must be distinct fromarr.N – Number of elements to reduce.
init – Initial value for the accumulation.
stream – CUDA stream to use.
-
template<typename T, typename OP, bool DirectCopy = false>
static inline void reduceBlocking(cuda::Graph &graph, T *result, const CRefArrT<T> &arr, aether::Array<T> &oarr, const T &init = 0, const cudaStream_t &stream = 0) As the sized overload, reducing over every sample of
arr.- Template Parameters:
T – Data type of the elements
OP – Reduction operator to use.
- Parameters:
graph – Graph the reduction nodes are added to.
result – Pointer to the reduction result
arr – Input scalar array, already allocated on the device.
oarr – Work buffer; see the sized overload.
init – Initial value for the accumulation.
stream – CUDA stream to use.
-
template<typename T, typename OP>
static inline cuda::Graph reduceBlocking(T *result, const CRefArrT<T> &arr, aether::Array<T> &oarr, const T &init = 0, const cudaStream_t &stream = 0) As the sized overload, building and returning a new graph.
- Template Parameters:
T – Data type of the elements
OP – Reduction operator to use.
- Parameters:
result – Pointer to the reduction result
arr – Input scalar array, already allocated on the device.
oarr – Work buffer; see the sized overload.
init – Initial value for the accumulation.
stream – CUDA stream to use.
- Returns:
The graph holding the reduction.
-
template<typename T, typename OP>
static inline T reduceBlocking(const CRefArrT<T> arr, const T &init = 0, const cudaStream_t &stream = 0) Perform a reduction over a GPU-allocated array, allocating a work buffer ad-hoc.
Note: causes a blocking synchronization of the given stream.
Note that this will allocate a new, temporary work buffer on host and device. If performing multiple reductions with same-sized arrays, it may be more efficient to generate the buffer once with
makeBufferand reuse it with the overloaded version of this function.- Template Parameters:
T – Data type of the elements
OP – Reduction operator to use. Must be callable as
OP{}(a, b)(aether’s functor shape). Example:aether::SumOp<T>
- Parameters:
arr – Input scalar array. The reduction will be performed over the device copy, but it will not be modified. Must be already allocated on the device.
init – Initial value for the accumulation.
stream – CUDA stream to use.
-
template<typename T>
eagle::cpu::Reduction#
-
template<typename T, typename OP>
struct Reduction# CPU parallel reduction over aether scalar arrays using OpenMP.
Cache-line padding (
alignas(64)onPaddedT) prevents false sharing across threads in the per-thread accumulator buffer.- Template Parameters:
T – Element type of the array being reduced.
OP – Reduction operator; must be CALLABLE as
OP{}(a, b)(aether’s functor shape — there is no staticOP::eval), or be one ofaether::SumOp<T>,aether::MaxOp<T>oraether::LogicalAndOp(which use native OpenMP reduction clauses for better performance).
Public Static Functions
-
static inline T reduce(const CRefArrT<T> &in, std::vector<PaddedT> &buffer, const T &init = 0)#
Run the OpenMP based reduction.
Integer sums,
MaxOpandLogicalAndOpuse native OpenMP reduction clauses (exactly associative, so any schedule gives the same value). A floating-point sum and any other operator use the canonical tree (eagle/reduce/canonical.h): the result is bitwise identical for every OpenMP thread count.
-
struct PaddedT#
Canonical tree — eagle::reduce::canonical#
The fixed-order tree (leaf blocks of 256, then pairwise levels) with a host and a
device face; see Same bits, every time. Its members are listed under the
eagle::reduce namespace below.
Namespace eagle::reduce#
-
namespace reduce#
Enums
-
template<typename T, typename OP>
class ReductionNode# - #include <ReductionNode.h>
A reduction as a native node — the arena-backed twin of
cuda::Reduction::reduceBlocking, with both a CUDA and a host face.Reduces the input array into a single result. The CUDA face (
buildInto,EAGLE_CPU_ONLYundefined) captures the same multi-leveldetail::reduceOncechain the free builder uses; the host face (runHost, always compiled) runs the OpenMP twincpu::Reduction. Both sharereserveScratch.Contributed transparently with
graph.addNative(ReductionNode{...}, deps)(CUDAGraph) orhostGraph.addNative(ReductionNode{...}, deps)(cpu::Graph). The node holds only PODs (result pointer, input handle, size, init, stream, scratch handle), so it is copyable — asaddNativerequires.- Template Parameters:
T – element type.
OP – reduction operator (as
reduceOnce/cpu::Reduction).
Public Types
-
using StreamT = nativeStream_t#
Mode-agnostic stream type (
cudaStream_tunder CUDA,intinEAGLE_CPU_ONLY).
Public Functions
-
inline ReductionNode(T *result, const HandleT &input, idx_t n, T init = 0, const StreamT &stream = 0)#
- Parameters:
result – Host pointer the single reduced value is copied into.
input – Read-only device view over the array to reduce (e.g.
arr.deviceRef().as_const()); must outlive the launch.n – Element count of
input.init – Initial accumulator value.
stream – Stream the reduce chain is captured on.
-
inline void reserveScratch(ScratchArena &arena)#
Phase 1: reserve the reduction work buffer (sized like
cuda::Reduction::makeBuffer— at leastnBlockselements).
-
inline idx_t buildInto(cuda::Graph &g, const std::vector<idx_t> &deps)#
Phase 2 (CUDA): capture the multi-level reduce chain (first node depends on
deps, the rest auto-chain) plus the D2H result copy, using the committed arena’s pointer as the work buffer. Returns the last node.
-
inline void runHost(cpu::Graph&)#
Host face: run the OpenMP reduction twin over
input_and store the result.cpu::Reductionowns its own per-thread padded accumulators (outer thread loop over samples), so no arena scratch is touched — the reserved slot simply stays unused on the host path.
-
namespace canonical#
Functions
-
inline bool isAlignedChunk(idx_t chunk)#
True iff
chunkisleafSize * 2^qfor someq >= 0(the only chunk sizes that are bitwise-neutral).
-
inline bool fixedLeaf(int fp32PerFp64)#
True when a device with FP32:FP64 throughput ratio
fp32PerFp64reduces double sums on the fixed-point path.
-
template<typename P, typename In, typename Cin>
inline void fold(P &p, bool first, const In &in, const Cin &cin, idx_t i)# Fold sample
i(and its companion, if any) intop.
-
template<typename T, typename OP, typename P = Partial<T, OP>, typename In, typename Cin = NoComp>
inline P leaf(const In &in, idx_t base, idx_t cnt, const Cin &cin = {})# Reduce one leaf:
cntsamplesin(base) .. in(base + cnt - 1),1 <= cnt <= leafSize, to its partial.
-
template<typename P>
inline P pairwise(P *v, idx_t m)# Level-by-level pairwise reduction of
v[0..m)(m >= 1), in place; returns the root. An odd last node is carried.
-
template<typename P>
inline P combine(std::vector<P> partials)# Pairwise-combine partials (e.g. chunk results, in chunk order).
-
template<typename T, typename OP, typename P = Partial<T, OP>, typename In, typename Cin = NoComp>
inline P partialRange(const In &in, idx_t begin, idx_t n, const Cin &cin = {})# Host canonical partial of
in(begin) .. in(begin + n - 1),n >= 1. OpenMP over leaves; bitwise independent of the thread count.
-
template<typename T, typename OP, typename In>
inline T reduceRange(const In &in, idx_t begin, idx_t n)# Host canonical reduction of
in(begin) .. in(begin + n - 1).
-
template<typename T, typename OP, typename In>
inline T reduce(const In &in, idx_t n)# Host canonical reduction of
in(0) .. in(n-1).
-
template<typename T, typename OP, typename In>
inline T reduceChunked(const In &in, idx_t n, idx_t chunk)# The same reduction processed in chunks of
chunksamples (chunk = leafSize * 2^q; the last chunk may be ragged), chunk partials combined by the pairwise levels. Bitwise equal toreduce.
-
template<typename T, typename OP, typename P, typename In, typename Cin>
void leafKernel(In in, Cin cin, idx_t rows, idx_t cols, idx_t col0, P *out, P *acc)# Device leaf: block
(l, y)reduces leaflof columncol0 + yof a row-major(rows, cols)plane with the slot walk and the in-leaf tree of the definition.acc == nullptr: writes the partial toout[col * leafCount(rows) + l](ordered); otherwise commits it intoacc[col]with two-sum atomics (compensated). Launch withslotsthreads.
-
template<typename P>
void levelsKernel(const P *src, P *dst, idx_t m, idx_t col0)# Nine pairwise levels of every column: block
(g, y)reduces source nodes[g * levelGroup, ...)of columncol0 + y(mper column) to destination nodeg(gridDim.xper column). A group is an aligned subtree of the levels, so the bits are those of level-by-level pairwise (an odd last node is carried). Launch withslotsthreads.
-
template<typename P>
inline P *enqueueLevels(P *src, P *dst, idx_t m, idx_t cols, cudaStream_t stream)# Enqueue the pairwise levels of
mnodes per column, ping-pongingsrc/dst; returns the buffer holding thecolsroots.
-
template<typename P>
void zeroKernel(P *acc, idx_t cols)# Zero the
cols(hi, comp) accumulators ofcompensated.
-
template<typename T, typename P>
void storeKernel(const P *root, T *out, idx_t cols, bool pairOut)# Write the
colsroots:out[j] = valueor, withpairOut,out[j] = hiandout[cols + j] = comp.
-
inline idx_t deviceWorkElems(idx_t rows, idx_t cols = 1)#
Elements of
Teach of the two device work buffers must hold forrowssamples in each ofcolscolumns (room for aFixedPartialper leaf, three doubles).
-
inline bool fixedLeafDevice(int device)#
fixedLeafof CUDA devicedevice.
-
template<typename T, typename OP, typename P, typename In, typename Cin>
inline void enqueueWith(const In &in, const Cin &cin, idx_t rows, idx_t cols, bool atomic, T *workA, T *workB, T *out, bool pairOut, cudaStream_t stream)# enqueueTowith the partial typePfixed.
-
template<typename T, typename OP, typename In, typename Cin = NoComp>
inline void enqueueTo(const In &in, const Cin &cin, idx_t rows, idx_t cols, Policy policy, T *workA, T *workB, T *out, bool pairOut, cudaStream_t stream, bool fixed = false)# Enqueue the reduction of each column of the row-major device plane
in(rows >= 1bycols >= 1) onstreamintoout[0, cols)(2 * colselements, hi then comp, withpairOut).cinis the companion plane (NoCompfor none).fixed: a double sum withoutpairOutruns the fixed-point leaf (FixedPartial) and the pairwise levels under every policy. Two device work buffers ofdeviceWorkElems(rows, cols)elements each. Capturable.
Variables
-
template<typename T, typename OP>
bool compensated_v = std::is_floating_point_v<T> && std::is_same_v<OP, aether::SumOp<T>># True when
OPoverTis a floating-point sum (compensated partials).
-
int fixedLeafRatio = 8#
FP32:FP64 throughput ratio from which a device takes the fixed-point f64 leaf (1:32 and 1:64 parts; 1:2 parts keep (hi, comp)).
-
template<typename T>
struct MinOp# - #include <canonical.h>
min(a, b), the exact fold besideaether::MaxOp(a < b ? a : b).
-
template<typename T, typename OP, bool C = compensated_v<T, OP>>
struct Partial# - #include <canonical.h>
A partial of an exact operator: one plain value.
-
template<typename T, typename OP>
struct Partial<T, OP, true># - #include <canonical.h>
A partial of a floating-point sum: (hi, comp). A non-finite
hidropscomp, so the value then follows IEEE throughhi.
-
struct FixedPartial#
- #include <canonical.h>
A partial of a double sum on the fixed-point path: the value is
v * 2^uwithva signed 128-bit integer (hi:lo).A term’s least significant bit is placed at most 53 bits above the unit, so the unit sits 106 bits (u^2) below the largest term seen: a term (or a partial, when two units are aligned) loses at most one unit, which keeps every sum within the (1 + n*k*u) ULP contract and exact whenever the terms span fewer than 2^53 in magnitude. A slot folds at most 2 *
termsterms of at most 2^106 units (no overflow);joinhalves both operands and raises the unit when either reaches 2^125, so a partial never overflows. Infinities and NaN set sticky flags and the value follows IEEE.Public Functions
-
inline void add(double x)#
Add one term exactly (truncated only below the unit).
-
inline double value() const#
The value rounded once to nearest-even (subnormals included).
Public Static Functions
-
static inline I shr(I v, std::int32_t d)#
v >> d(floor), anyd >= 0.
-
static inline FixedPartial join(const FixedPartial &a, const FixedPartial &b)#
Align the units and add; symmetric in its operands.
-
inline void add(double x)#
-
struct NoComp#
- #include <canonical.h>
“No companion input”: the terms are plain values.
-
template<typename In>
struct Column# - #include <canonical.h>
Column
jof a row-major(rows, cols)host plane asin(i).
-
template<typename T>
struct DevicePtr# - #include <canonical.h>
A raw device pointer as an
in(i)accessor for the kernels.
-
inline bool isAlignedChunk(idx_t chunk)#
-
namespace detail#
Functions
-
template<typename T, typename OP, unsigned int blockSize_>
void reduceOnce(CRefArrT<T> g_idata, GRefArrT<T> g_odata, unsigned int n, const T init)# Run a single reduction.
Block size is FIXED by the warp-shuffle reduction layout: the recursive
sdata[threadIdx.x + offset]pattern is only valid when blockDim equals the templatedblockSize_exactly. NEVER feed this kernel throughLauncher::setLogicalSize(which mutates blockDim). SASS register footprint: ~8 regs (sm_61).
-
struct Core#
- #include <detail.h>
Reductions.
-
template<typename T, typename OP, unsigned int blockSize_>
-
template<typename T, typename OP>