Eigen-Contrib  5.0.1
 
Loading...
Searching...
No Matches
TensorScan.h
1// This file is part of Eigen, a lightweight C++ template library
2// for linear algebra.
3//
4// Copyright (C) 2016 Igor Babuschkin <igor@babuschk.in>
5//
6// This Source Code Form is subject to the terms of the Mozilla
7// Public License v. 2.0. If a copy of the MPL was not distributed
8// with this file, You can obtain one at http://mozilla.org/MPL/2.0/.
9// SPDX-License-Identifier: MPL-2.0
10
11#ifndef EIGEN_TENSOR_TENSOR_SCAN_H
12#define EIGEN_TENSOR_TENSOR_SCAN_H
13
14// IWYU pragma: private
15#include "./InternalHeaderCheck.h"
16
17namespace Eigen {
18
19namespace internal {
20
21template <typename Op, typename XprType>
22struct traits<TensorScanOp<Op, XprType> > : public traits<XprType> {
23 typedef typename XprType::Scalar Scalar;
24 typedef traits<XprType> XprTraits;
25 typedef typename XprTraits::StorageKind StorageKind;
26 static constexpr int NumDimensions = XprTraits::NumDimensions;
27 static constexpr int Layout = XprTraits::Layout;
28 typedef typename XprTraits::PointerType PointerType;
29};
30
31template <typename Op, typename XprType>
32struct eval<TensorScanOp<Op, XprType>, Eigen::Dense> {
33 typedef const TensorScanOp<Op, XprType>& type;
34};
35
36} // end namespace internal
37
43template <typename Op, typename XprType>
44class TensorScanOp : public TensorBase<TensorScanOp<Op, XprType>, ReadOnlyAccessors> {
45 public:
46 typedef typename Eigen::internal::traits<TensorScanOp>::Scalar Scalar;
47 typedef typename Eigen::NumTraits<Scalar>::Real RealScalar;
48 typedef typename XprType::CoeffReturnType CoeffReturnType;
49 typedef typename Eigen::internal::ref_selector<TensorScanOp>::type Nested;
50 typedef typename Eigen::internal::traits<TensorScanOp>::StorageKind StorageKind;
51 typedef typename Eigen::internal::traits<TensorScanOp>::Index Index;
52
53 EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE TensorScanOp(const XprType& expr, const Index& axis, bool exclusive = false,
54 const Op& op = Op())
55 : m_expr(expr), m_axis(axis), m_accumulator(op), m_exclusive(exclusive) {}
56
57 EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE const Index axis() const { return m_axis; }
58 EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE const XprType& expression() const { return m_expr; }
59 EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE const Op accumulator() const { return m_accumulator; }
60 EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE bool exclusive() const { return m_exclusive; }
61
62 protected:
63 typename XprType::Nested m_expr;
64 const Index m_axis;
65 const Op m_accumulator;
66 const bool m_exclusive;
67};
68
69namespace internal {
70
71template <typename Self>
72EIGEN_STRONG_INLINE void ReduceScalar(Self& self, Index offset, typename Self::CoeffReturnType* data) {
73 // Compute the scan along the axis, starting at the given offset
74 typename Self::CoeffReturnType accum = self.accumulator().initialize();
75 if (self.stride() == 1) {
76 if (self.exclusive()) {
77 for (Index curr = offset; curr < offset + self.size(); ++curr) {
78 data[curr] = self.accumulator().finalize(accum);
79 self.accumulator().reduce(self.inner().coeff(curr), &accum);
80 }
81 } else {
82 for (Index curr = offset; curr < offset + self.size(); ++curr) {
83 self.accumulator().reduce(self.inner().coeff(curr), &accum);
84 data[curr] = self.accumulator().finalize(accum);
85 }
86 }
87 } else {
88 if (self.exclusive()) {
89 for (Index idx3 = 0; idx3 < self.size(); idx3++) {
90 Index curr = offset + idx3 * self.stride();
91 data[curr] = self.accumulator().finalize(accum);
92 self.accumulator().reduce(self.inner().coeff(curr), &accum);
93 }
94 } else {
95 for (Index idx3 = 0; idx3 < self.size(); idx3++) {
96 Index curr = offset + idx3 * self.stride();
97 self.accumulator().reduce(self.inner().coeff(curr), &accum);
98 data[curr] = self.accumulator().finalize(accum);
99 }
100 }
101 }
102}
103
104template <typename Self>
105EIGEN_STRONG_INLINE void ReducePacket(Self& self, Index offset, typename Self::CoeffReturnType* data) {
106 using Scalar = typename Self::CoeffReturnType;
107 using Packet = typename Self::PacketReturnType;
108 // Compute the scan along the axis, starting at the calculated offset
109 Packet accum = self.accumulator().template initializePacket<Packet>();
110 if (self.stride() == 1) {
111 if (self.exclusive()) {
112 for (Index curr = offset; curr < offset + self.size(); ++curr) {
113 internal::pstoreu<Scalar, Packet>(data + curr, self.accumulator().finalizePacket(accum));
114 self.accumulator().reducePacket(self.inner().template packet<Unaligned>(curr), &accum);
115 }
116 } else {
117 for (Index curr = offset; curr < offset + self.size(); ++curr) {
118 self.accumulator().reducePacket(self.inner().template packet<Unaligned>(curr), &accum);
119 internal::pstoreu<Scalar, Packet>(data + curr, self.accumulator().finalizePacket(accum));
120 }
121 }
122 } else {
123 if (self.exclusive()) {
124 for (Index idx3 = 0; idx3 < self.size(); idx3++) {
125 const Index curr = offset + idx3 * self.stride();
126 internal::pstoreu<Scalar, Packet>(data + curr, self.accumulator().finalizePacket(accum));
127 self.accumulator().reducePacket(self.inner().template packet<Unaligned>(curr), &accum);
128 }
129 } else {
130 for (Index idx3 = 0; idx3 < self.size(); idx3++) {
131 const Index curr = offset + idx3 * self.stride();
132 self.accumulator().reducePacket(self.inner().template packet<Unaligned>(curr), &accum);
133 internal::pstoreu<Scalar, Packet>(data + curr, self.accumulator().finalizePacket(accum));
134 }
135 }
136 }
137}
138
139template <typename Self, bool Vectorize, bool Parallel>
140struct ReduceBlock {
141 EIGEN_STRONG_INLINE void operator()(Self& self, Index idx1, typename Self::CoeffReturnType* data) const {
142 for (Index idx2 = 0; idx2 < self.stride(); idx2++) {
143 // Calculate the starting offset for the scan
144 Index offset = idx1 + idx2;
145 ReduceScalar(self, offset, data);
146 }
147 }
148};
149
150// Specialization for vectorized reduction.
151template <typename Self>
152struct ReduceBlock<Self, /*Vectorize=*/true, /*Parallel=*/false> {
153 EIGEN_STRONG_INLINE void operator()(Self& self, Index idx1, typename Self::CoeffReturnType* data) const {
154 using Packet = typename Self::PacketReturnType;
155 const int PacketSize = internal::unpacket_traits<Packet>::size;
156 Index idx2 = 0;
157 for (; idx2 + PacketSize <= self.stride(); idx2 += PacketSize) {
158 // Calculate the starting offset for the packet scan
159 Index offset = idx1 + idx2;
160 ReducePacket(self, offset, data);
161 }
162 for (; idx2 < self.stride(); idx2++) {
163 // Calculate the starting offset for the scan
164 Index offset = idx1 + idx2;
165 ReduceScalar(self, offset, data);
166 }
167 }
168};
169
170// Single-threaded CPU implementation of scan
171template <typename Self, typename Reducer, typename Device,
172 bool Vectorize = (TensorEvaluator<typename Self::ChildTypeNoConst, Device>::PacketAccess &&
173 internal::reducer_traits<Reducer, Device>::PacketAccess)>
174struct ScanLauncher {
175 void operator()(Self& self, typename Self::CoeffReturnType* data) const {
176 Index total_size = internal::array_prod(self.dimensions());
177
178 // We fix the index along the scan axis to 0 and perform a
179 // scan per remaining entry. The iteration is split into two nested
180 // loops to avoid an integer division by keeping track of each idx1 and
181 // idx2.
182 for (Index idx1 = 0; idx1 < total_size; idx1 += self.stride() * self.size()) {
183 ReduceBlock<Self, Vectorize, /*Parallel=*/false> block_reducer;
184 block_reducer(self, idx1, data);
185 }
186 }
187};
188
189#ifdef EIGEN_USE_THREADS
190
191// Adjust block_size to avoid false sharing of cachelines among
192// threads. Currently set to twice the cache line size on Intel and ARM
193// processors.
194EIGEN_STRONG_INLINE Index AdjustBlockSize(Index item_size, Index block_size) {
195 constexpr Index kBlockAlignment = 128;
196 const Index items_per_cacheline = numext::maxi<Index>(1, kBlockAlignment / item_size);
197 return items_per_cacheline * numext::div_ceil(block_size, items_per_cacheline);
198}
199
200template <typename Self>
201struct ReduceBlock<Self, /*Vectorize=*/true, /*Parallel=*/true> {
202 EIGEN_STRONG_INLINE void operator()(Self& self, Index idx1, typename Self::CoeffReturnType* data) const {
203 using Scalar = typename Self::CoeffReturnType;
204 using Packet = typename Self::PacketReturnType;
205 const int PacketSize = internal::unpacket_traits<Packet>::size;
206 Index num_scalars = self.stride();
207 Index num_packets = 0;
208 if (self.stride() >= PacketSize) {
209 num_packets = self.stride() / PacketSize;
210 self.device().parallelFor(
211 num_packets,
212 TensorOpCost(PacketSize * self.size(), PacketSize * self.size(), 16 * PacketSize * self.size(), true,
213 PacketSize),
214 // Make the shard size large enough that two neighboring threads
215 // won't write to the same cacheline of `data`.
216 [=](Index blk_size) { return AdjustBlockSize(PacketSize * sizeof(Scalar), blk_size); },
217 [&](Index first, Index last) {
218 for (Index packet = first; packet < last; ++packet) {
219 const Index idx2 = packet * PacketSize;
220 ReducePacket(self, idx1 + idx2, data);
221 }
222 });
223 num_scalars -= num_packets * PacketSize;
224 }
225 self.device().parallelFor(
226 num_scalars, TensorOpCost(self.size(), self.size(), 16 * self.size()),
227 // Make the shard size large enough that two neighboring threads
228 // won't write to the same cacheline of `data`.
229 [=](Index blk_size) { return AdjustBlockSize(sizeof(Scalar), blk_size); },
230 [&](Index first, Index last) {
231 for (Index scalar = first; scalar < last; ++scalar) {
232 const Index idx2 = num_packets * PacketSize + scalar;
233 ReduceScalar(self, idx1 + idx2, data);
234 }
235 });
236 }
237};
238
239template <typename Self>
240struct ReduceBlock<Self, /*Vectorize=*/false, /*Parallel=*/true> {
241 EIGEN_STRONG_INLINE void operator()(Self& self, Index idx1, typename Self::CoeffReturnType* data) const {
242 using Scalar = typename Self::CoeffReturnType;
243 self.device().parallelFor(
244 self.stride(), TensorOpCost(self.size(), self.size(), 16 * self.size()),
245 // Make the shard size large enough that two neighboring threads
246 // won't write to the same cacheline of `data`.
247 [=](Index blk_size) { return AdjustBlockSize(sizeof(Scalar), blk_size); },
248 [&](Index first, Index last) {
249 for (Index idx2 = first; idx2 < last; ++idx2) {
250 ReduceScalar(self, idx1 + idx2, data);
251 }
252 });
253 }
254};
255
256// Specialization for multi-threaded execution.
257template <typename Self, typename Reducer, bool Vectorize>
258struct ScanLauncher<Self, Reducer, ThreadPoolDevice, Vectorize> {
259 void operator()(Self& self, typename Self::CoeffReturnType* data) const {
260 using Scalar = typename Self::CoeffReturnType;
261 using Packet = typename Self::PacketReturnType;
262 const int PacketSize = internal::unpacket_traits<Packet>::size;
263 const Index total_size = internal::array_prod(self.dimensions());
264 const Index inner_block_size = self.stride() * self.size();
265 bool parallelize_by_outer_blocks = (total_size >= (self.stride() * inner_block_size));
266
267 if ((parallelize_by_outer_blocks && total_size <= 4096) ||
268 (!parallelize_by_outer_blocks && self.stride() < PacketSize)) {
269 ScanLauncher<Self, Reducer, DefaultDevice, Vectorize> launcher;
270 launcher(self, data);
271 return;
272 }
273
274 if (parallelize_by_outer_blocks) {
275 // Parallelize over outer blocks.
276 const Index num_outer_blocks = total_size / inner_block_size;
277 self.device().parallelFor(
278 num_outer_blocks,
279 TensorOpCost(inner_block_size, inner_block_size, 16 * PacketSize * inner_block_size, Vectorize, PacketSize),
280 [=](Index blk_size) { return AdjustBlockSize(inner_block_size * sizeof(Scalar), blk_size); },
281 [&](Index first, Index last) {
282 for (Index idx1 = first; idx1 < last; ++idx1) {
283 ReduceBlock<Self, Vectorize, /*Parallel=*/false> block_reducer;
284 block_reducer(self, idx1 * inner_block_size, data);
285 }
286 });
287 } else {
288 // Parallelize over inner packets/scalars dimensions when the reduction
289 // axis is not an inner dimension.
290 ReduceBlock<Self, Vectorize, /*Parallel=*/true> block_reducer;
291 for (Index idx1 = 0; idx1 < total_size; idx1 += self.stride() * self.size()) {
292 block_reducer(self, idx1, data);
293 }
294 }
295 }
296};
297#endif // EIGEN_USE_THREADS
298
299#if defined(EIGEN_USE_GPU) && (defined(EIGEN_GPUCC))
300
301// GPU implementation of scan
302// TODO(ibab): This placeholder implementation performs multiple scans in
303// parallel, but it would be better to use a parallel scan algorithm and
304// optimize memory access.
305template <typename Self, typename Reducer>
306__global__ EIGEN_HIP_LAUNCH_BOUNDS_1024 void ScanKernel(Self self, Index total_size,
307 typename Self::CoeffReturnType* data) {
308 // Compute offset as in the CPU version
309 Index val = threadIdx.x + blockIdx.x * blockDim.x;
310 Index offset = (val / self.stride()) * self.stride() * self.size() + val % self.stride();
311
312 if (offset + (self.size() - 1) * self.stride() < total_size) {
313 // Compute the scan along the axis, starting at the calculated offset
314 typename Self::CoeffReturnType accum = self.accumulator().initialize();
315 for (Index idx = 0; idx < self.size(); idx++) {
316 Index curr = offset + idx * self.stride();
317 if (self.exclusive()) {
318 data[curr] = self.accumulator().finalize(accum);
319 self.accumulator().reduce(self.inner().coeff(curr), &accum);
320 } else {
321 self.accumulator().reduce(self.inner().coeff(curr), &accum);
322 data[curr] = self.accumulator().finalize(accum);
323 }
324 }
325 }
326 __syncthreads();
327}
328
329template <typename Self, typename Reducer, bool Vectorize>
330struct ScanLauncher<Self, Reducer, GpuDevice, Vectorize> {
331 void operator()(const Self& self, typename Self::CoeffReturnType* data) const {
332 Index total_size = internal::array_prod(self.dimensions());
333 Index num_blocks = (total_size / self.size() + 63) / 64;
334 Index block_size = 64;
335
336 LAUNCH_GPU_KERNEL((ScanKernel<Self, Reducer>), num_blocks, block_size, 0, self.device(), self, total_size, data);
337 }
338};
339#endif // EIGEN_USE_GPU && (EIGEN_GPUCC)
340
341} // namespace internal
342
343// Eval as rvalue
344template <typename Op, typename ArgType, typename Device>
345struct TensorEvaluator<const TensorScanOp<Op, ArgType>, Device> {
346 typedef TensorScanOp<Op, ArgType> XprType;
347 typedef typename XprType::Index Index;
348 typedef const ArgType ChildTypeNoConst;
349 typedef const ArgType ChildType;
350 static constexpr int NumDims = internal::array_size<typename TensorEvaluator<ArgType, Device>::Dimensions>::value;
351 typedef DSizes<Index, NumDims> Dimensions;
352 typedef std::remove_const_t<typename XprType::Scalar> Scalar;
353 typedef typename XprType::CoeffReturnType CoeffReturnType;
354 typedef typename PacketType<CoeffReturnType, Device>::type PacketReturnType;
355 typedef TensorEvaluator<const TensorScanOp<Op, ArgType>, Device> Self;
356 typedef StorageMemory<Scalar, Device> Storage;
357 typedef typename Storage::Type EvaluatorPointerType;
358
359 static constexpr int Layout = TensorEvaluator<ArgType, Device>::Layout;
360 enum {
361 IsAligned = false,
362 PacketAccess = (PacketType<CoeffReturnType, Device>::size > 1),
363 // Scan eagerly materializes its result into m_output; once that buffer
364 // exists, exposing block access is just a wrapper around it. Leave
365 // PreferBlockAccess false so the executor still uses the cheaper
366 // raw/packet paths by default; the flag matters only when an outer
367 // expression calls block() directly.
368 BlockAccess = (NumDims > 0),
369 PreferBlockAccess = false,
370 CoordAccess = false,
371 RawAccess = true
372 };
373
374 //===- Tensor block evaluation strategy (see TensorBlock.h) -------------===//
375 typedef internal::TensorBlockDescriptor<NumDims, Index> TensorBlockDesc;
376 typedef internal::TensorBlockScratchAllocator<Device> TensorBlockScratch;
377 typedef typename internal::TensorMaterializedBlock<Scalar, NumDims, Layout, Index> TensorBlock;
378 //===--------------------------------------------------------------------===//
379
380 EIGEN_STRONG_INLINE TensorEvaluator(const XprType& op, const Device& device)
381 : m_impl(op.expression(), device),
382 m_device(device),
383 m_exclusive(op.exclusive()),
384 m_accumulator(op.accumulator()),
385 m_size(m_impl.dimensions()[op.axis()]),
386 m_stride(1),
387 m_consume_dim(op.axis()),
388 m_output(nullptr) {
389 // Accumulating a scalar isn't supported.
390 EIGEN_STATIC_ASSERT((NumDims > 0), YOU_MADE_A_PROGRAMMING_MISTAKE);
391 eigen_assert(op.axis() >= 0 && op.axis() < NumDims);
392
393 // Compute stride of scan axis
394 const Dimensions& dims = m_impl.dimensions();
395 EIGEN_IF_CONSTEXPR (static_cast<int>(Layout) == static_cast<int>(ColMajor)) {
396 for (int i = 0; i < op.axis(); ++i) {
397 m_stride = m_stride * dims[i];
398 }
399 } else {
400 // dims can only be indexed through unsigned integers,
401 // so use an unsigned type to let the compiler know.
402 // This prevents spurious warnings: "'*((void*)(& evaluator)+64)[18446744073709551615]' may be used uninitialized
403 // in this function"
404 unsigned int axis = internal::convert_index<unsigned int>(op.axis());
405 for (unsigned int i = NumDims - 1; i > axis; --i) {
406 m_stride = m_stride * dims[i];
407 }
408 }
409 }
410
411 EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE const Dimensions& dimensions() const { return m_impl.dimensions(); }
412
413 EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE const Index& stride() const { return m_stride; }
414
415 EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE const Index& consume_dim() const { return m_consume_dim; }
416
417 EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE const Index& size() const { return m_size; }
418
419 EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE const Op& accumulator() const { return m_accumulator; }
420
421 EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE bool exclusive() const { return m_exclusive; }
422
423 EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE const TensorEvaluator<ArgType, Device>& inner() const { return m_impl; }
424
425 EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE const Device& device() const { return m_device; }
426
427 EIGEN_STRONG_INLINE bool evalSubExprsIfNeeded(EvaluatorPointerType data) {
428 m_impl.evalSubExprsIfNeeded(nullptr);
429 internal::ScanLauncher<Self, Op, Device> launcher;
430 if (data) {
431 launcher(*this, data);
432 return false;
433 }
434
435 const Index total_size = internal::array_prod(dimensions());
436 m_output =
437 static_cast<EvaluatorPointerType>(m_device.get((Scalar*)m_device.allocate_temp(total_size * sizeof(Scalar))));
438 launcher(*this, m_output);
439 return true;
440 }
441
442 template <int LoadMode>
443 EIGEN_DEVICE_FUNC PacketReturnType packet(Index index) const {
444 return internal::ploadt<PacketReturnType, LoadMode>(m_output + index);
445 }
446
447 EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE internal::TensorBlockResourceRequirements getResourceRequirements() const {
448 return internal::TensorBlockResourceRequirements::any();
449 }
450
451 EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE TensorBlock block(TensorBlockDesc& desc, TensorBlockScratch& scratch,
452 bool /*root_of_expr_ast*/ = false) const {
453 eigen_assert(m_output != nullptr);
454 return TensorBlock::materialize(m_output, m_impl.dimensions(), desc, scratch);
455 }
456
457 EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE EvaluatorPointerType data() const { return m_output; }
458
459 EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE CoeffReturnType coeff(Index index) const { return m_output[index]; }
460
461 EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE TensorOpCost costPerCoeff(bool) const {
462 return TensorOpCost(sizeof(CoeffReturnType), 0, 0);
463 }
464
465 EIGEN_STRONG_INLINE void cleanup() {
466 if (m_output) {
467 m_device.deallocate_temp(m_output);
468 m_output = nullptr;
469 }
470 m_impl.cleanup();
471 }
472
473 protected:
474 TensorEvaluator<ArgType, Device> m_impl;
475 const Device EIGEN_DEVICE_REF m_device;
476 const bool m_exclusive;
477 Op m_accumulator;
478 const Index m_size;
479 Index m_stride;
480 Index m_consume_dim;
481 EvaluatorPointerType m_output;
482};
483
484} // end namespace Eigen
485
486#endif // EIGEN_TENSOR_TENSOR_SCAN_H
The tensor base class.
Definition TensorForwardDeclarations.h:69
Namespace containing all symbols from the Eigen library.