Eigen-Contrib  5.0.1
 
Loading...
Searching...
No Matches
TensorRoll.h
1// This file is part of Eigen, a lightweight C++ template library
2// for linear algebra.
3//
4// Copyright (C) 2024 Tobias Wood tobias@spinicist.org.uk
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_ROLL_H
12#define EIGEN_TENSOR_TENSOR_ROLL_H
13// IWYU pragma: private
14#include "./InternalHeaderCheck.h"
15
16namespace Eigen {
17
18namespace internal {
19template <typename RollDimensions, typename XprType>
20struct traits<TensorRollOp<RollDimensions, XprType> > : public traits<XprType> {
21 typedef typename XprType::Scalar Scalar;
22 typedef traits<XprType> XprTraits;
23 typedef typename XprTraits::StorageKind StorageKind;
24 typedef typename XprTraits::Index Index;
25 static constexpr int NumDimensions = XprTraits::NumDimensions;
26 static constexpr int Layout = XprTraits::Layout;
27 typedef typename XprTraits::PointerType PointerType;
28};
29
30template <typename RollDimensions, typename XprType>
31struct eval<TensorRollOp<RollDimensions, XprType>, Eigen::Dense> {
32 typedef const TensorRollOp<RollDimensions, XprType>& type;
33};
34
35} // end namespace internal
36
43template <typename RollDimensions, typename XprType>
44class TensorRollOp : public TensorBase<TensorRollOp<RollDimensions, XprType>, WriteAccessors> {
45 public:
47 typedef typename Eigen::internal::traits<TensorRollOp>::Scalar Scalar;
48 typedef typename Eigen::NumTraits<Scalar>::Real RealScalar;
49 typedef typename XprType::CoeffReturnType CoeffReturnType;
50 typedef typename Eigen::internal::ref_selector<TensorRollOp>::type Nested;
51 typedef typename Eigen::internal::traits<TensorRollOp>::StorageKind StorageKind;
52 typedef typename Eigen::internal::traits<TensorRollOp>::Index Index;
53
54 EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE TensorRollOp(const XprType& expr, const RollDimensions& roll_dims)
55 : m_xpr(expr), m_roll_dims(roll_dims) {}
56
57 EIGEN_DEVICE_FUNC const RollDimensions& roll() const { return m_roll_dims; }
58
59 EIGEN_DEVICE_FUNC const internal::remove_all_t<typename XprType::Nested>& expression() const { return m_xpr; }
60
61 EIGEN_INHERIT_ASSIGNMENT_OPERATORS(TensorRollOp)
62
63 protected:
64 typename XprType::Nested m_xpr;
65 const RollDimensions m_roll_dims;
66};
67
68// Eval as rvalue
69template <typename RollDimensions, typename ArgType, typename Device>
70struct TensorEvaluator<const TensorRollOp<RollDimensions, ArgType>, Device> {
72 typedef typename XprType::Index Index;
73 static constexpr int NumDims = internal::array_size<RollDimensions>::value;
74 typedef DSizes<Index, NumDims> Dimensions;
75 typedef typename XprType::Scalar Scalar;
76 typedef typename XprType::CoeffReturnType CoeffReturnType;
77 typedef typename PacketType<CoeffReturnType, Device>::type PacketReturnType;
78 static constexpr int PacketSize = PacketType<CoeffReturnType, Device>::size;
79 typedef StorageMemory<CoeffReturnType, Device> Storage;
80 typedef typename Storage::Type EvaluatorPointerType;
81
82 static constexpr int Layout = TensorEvaluator<ArgType, Device>::Layout;
83 enum {
84 IsAligned = false,
85 PacketAccess = TensorEvaluator<ArgType, Device>::PacketAccess,
86 BlockAccess = NumDims > 0,
87 PreferBlockAccess = true,
88 CoordAccess = false, // to be implemented
89 RawAccess = false
90 };
91
92 typedef internal::TensorIntDivisor<Index> IndexDivisor;
93
94 //===- Tensor block evaluation strategy (see TensorBlock.h) -------------===//
95 using TensorBlockDesc = internal::TensorBlockDescriptor<NumDims, Index>;
96 using TensorBlockScratch = internal::TensorBlockScratchAllocator<Device>;
97 using ArgTensorBlock = typename TensorEvaluator<const ArgType, Device>::TensorBlock;
98 using TensorBlock = typename internal::TensorMaterializedBlock<CoeffReturnType, NumDims, Layout, Index>;
99 //===--------------------------------------------------------------------===//
100
101 EIGEN_STRONG_INLINE TensorEvaluator(const XprType& op, const Device& device)
102 : m_impl(op.expression(), device), m_rolls(op.roll()), m_device(device) {
103 EIGEN_STATIC_ASSERT((NumDims > 0), Must_Have_At_Least_One_Dimension_To_Roll);
104
105 // Compute strides
106 m_dimensions = m_impl.dimensions();
107 EIGEN_IF_CONSTEXPR (static_cast<int>(Layout) == static_cast<int>(ColMajor)) {
108 m_strides[0] = 1;
109 for (int i = 1; i < NumDims; ++i) {
110 m_strides[i] = m_strides[i - 1] * m_dimensions[i - 1];
111 if (m_strides[i] > 0) m_fast_strides[i] = IndexDivisor(m_strides[i]);
112 }
113 } else {
114 m_strides[NumDims - 1] = 1;
115 for (int i = NumDims - 2; i >= 0; --i) {
116 m_strides[i] = m_strides[i + 1] * m_dimensions[i + 1];
117 if (m_strides[i] > 0) m_fast_strides[i] = IndexDivisor(m_strides[i]);
118 }
119 }
120 }
121
122 EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE const Dimensions& dimensions() const { return m_dimensions; }
123
124 EIGEN_STRONG_INLINE bool evalSubExprsIfNeeded(EvaluatorPointerType) {
125 m_impl.evalSubExprsIfNeeded(nullptr);
126 return true;
127 }
128
129#ifdef EIGEN_USE_THREADS
130 template <typename EvalSubExprsCallback>
131 EIGEN_STRONG_INLINE void evalSubExprsIfNeededAsync(EvaluatorPointerType, EvalSubExprsCallback done) {
132 m_impl.evalSubExprsIfNeededAsync(nullptr, [done](bool) { done(true); });
133 }
134#endif // EIGEN_USE_THREADS
135
136 EIGEN_STRONG_INLINE void cleanup() { m_impl.cleanup(); }
137
138 EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE Index roll(Index const i, Index const r, Index const n) const {
139 auto const tmp = (i + r) % n;
140 if (tmp < 0) {
141 return tmp + n;
142 } else {
143 return tmp;
144 }
145 }
146
147 EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE array<Index, NumDims> rollCoords(array<Index, NumDims> const& coords) const {
148 array<Index, NumDims> rolledCoords;
149 for (int id = 0; id < NumDims; id++) {
150 eigen_assert(coords[id] < m_dimensions[id]);
151 rolledCoords[id] = roll(coords[id], m_rolls[id], m_dimensions[id]);
152 }
153 return rolledCoords;
154 }
155
156 EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE Index rollIndex(Index index) const {
157 eigen_assert(index < dimensions().TotalSize());
158 Index rolledIndex = 0;
159 EIGEN_IF_CONSTEXPR (static_cast<int>(Layout) == static_cast<int>(ColMajor)) {
160 EIGEN_UNROLL_LOOP
161 for (int i = NumDims - 1; i > 0; --i) {
162 Index idx = index / m_fast_strides[i];
163 index -= idx * m_strides[i];
164 rolledIndex += roll(idx, m_rolls[i], m_dimensions[i]) * m_strides[i];
165 }
166 rolledIndex += roll(index, m_rolls[0], m_dimensions[0]);
167 } else {
168 EIGEN_UNROLL_LOOP
169 for (int i = 0; i < NumDims - 1; ++i) {
170 Index idx = index / m_fast_strides[i];
171 index -= idx * m_strides[i];
172 rolledIndex += roll(idx, m_rolls[i], m_dimensions[i]) * m_strides[i];
173 }
174 rolledIndex += roll(index, m_rolls[NumDims - 1], m_dimensions[NumDims - 1]);
175 }
176 return rolledIndex;
177 }
178
179 EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE CoeffReturnType coeff(Index index) const {
180 return m_impl.coeff(rollIndex(index));
181 }
182
183 template <int LoadMode>
184 EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE PacketReturnType packet(Index index) const {
185 eigen_assert(index + PacketSize - 1 < dimensions().TotalSize());
186
187 // Fast path: when the entire packet stays inside one inner-most slice
188 // of both the output and the rolled input (no modular wrap on the
189 // inner dim), the PacketSize coeff() calls collapse to a single
190 // contiguous packet load from the underlying tensor.
191 constexpr int inner_dim = (static_cast<int>(Layout) == static_cast<int>(ColMajor)) ? 0 : NumDims - 1;
192 const Index inner_size = m_dimensions[inner_dim];
193 const Index inner_pos = index - (index / inner_size) * inner_size;
194 if (inner_pos + PacketSize <= inner_size) {
195 const Index rolled_inner_pos = roll(inner_pos, m_rolls[inner_dim], inner_size);
196 if (rolled_inner_pos + PacketSize <= inner_size) {
197 return m_impl.template packet<Unaligned>(rollIndex(index));
198 }
199 }
200
201 // Slow path: the packet straddles a slice boundary on either side.
202 EIGEN_ALIGN_TO_BOUNDARY(internal::unpacket_traits<PacketReturnType>::alignment)
203 std::remove_const_t<CoeffReturnType> values[PacketSize];
204 EIGEN_UNROLL_LOOP
205 for (int i = 0; i < PacketSize; ++i) {
206 values[i] = coeff(index + i);
207 }
208 return internal::pload<PacketReturnType>(values);
209 }
210
211 EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE internal::TensorBlockResourceRequirements getResourceRequirements() const {
212 const size_t target_size = m_device.lastLevelCacheSize();
213 return internal::TensorBlockResourceRequirements::skewed<Scalar>(target_size).addCostPerCoeff({0, 0, 24});
214 }
215
216 struct BlockIteratorState {
217 Index stride;
218 Index span;
219 Index size;
220 Index count;
221 };
222
223 EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE TensorBlock block(TensorBlockDesc& desc, TensorBlockScratch& scratch,
224 bool /*root_of_expr_ast*/ = false) const {
225 static const bool is_col_major = static_cast<int>(Layout) == static_cast<int>(ColMajor);
226
227 // Compute spatial coordinates for the first block element.
228 array<Index, NumDims> coords;
229 extract_coordinates(desc.offset(), coords);
230 array<Index, NumDims> initial_coords = coords;
231 Index offset = 0; // Offset in the output block buffer.
232
233 // Initialize output block iterator state. Dimensions in this array are
234 // always in inner_most -> outer_most order (col major layout).
235 array<BlockIteratorState, NumDims> it;
236 for (int i = 0; i < NumDims; ++i) {
237 const int dim = is_col_major ? i : NumDims - 1 - i;
238 it[i].size = desc.dimension(dim);
239 it[i].stride = i == 0 ? 1 : (it[i - 1].size * it[i - 1].stride);
240 it[i].span = it[i].stride * (it[i].size - 1);
241 it[i].count = 0;
242 }
243 eigen_assert(it[0].stride == 1);
244
245 // Prepare storage for the materialized generator result.
246 const typename TensorBlock::Storage block_storage = TensorBlock::prepareStorage(desc, scratch);
247 CoeffReturnType* block_buffer = block_storage.data();
248
249 static constexpr int inner_dim = is_col_major ? 0 : NumDims - 1;
250 const Index inner_dim_size = it[0].size;
251
252 while (it[NumDims - 1].count < it[NumDims - 1].size) {
253 Index i = 0;
254 for (; i < inner_dim_size; ++i) {
255 auto const rolled = rollCoords(coords);
256 auto const index = is_col_major ? m_dimensions.IndexOfColMajor(rolled) : m_dimensions.IndexOfRowMajor(rolled);
257 *(block_buffer + offset + i) = m_impl.coeff(index);
258 coords[inner_dim]++;
259 }
260 coords[inner_dim] = initial_coords[inner_dim];
261
262 EIGEN_IF_CONSTEXPR (NumDims == 1) break; // For the 1d tensor we need to generate only one inner-most dimension.
263
264 // Update offset.
265 for (i = 1; i < NumDims; ++i) {
266 if (++it[i].count < it[i].size) {
267 offset += it[i].stride;
268 coords[is_col_major ? i : NumDims - 1 - i]++;
269 break;
270 }
271 if (i != NumDims - 1) it[i].count = 0;
272 coords[is_col_major ? i : NumDims - 1 - i] = initial_coords[is_col_major ? i : NumDims - 1 - i];
273 offset -= it[i].span;
274 }
275 }
276
277 return block_storage.AsTensorMaterializedBlock();
278 }
279
280 EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE TensorOpCost costPerCoeff(bool vectorized) const {
281 double compute_cost = NumDims * (2 * TensorOpCost::AddCost<Index>() + 2 * TensorOpCost::MulCost<Index>() +
282 TensorOpCost::DivCost<Index>());
283 for (int i = 0; i < NumDims; ++i) {
284 compute_cost += 2 * TensorOpCost::AddCost<Index>();
285 }
286 // The inner-slice fast path runs the per-coeff index math once per packet,
287 // so the amortized compute cost matches the vectorized convention.
288 return m_impl.costPerCoeff(vectorized) + TensorOpCost(0, 0, compute_cost, vectorized, PacketSize);
289 }
290
291 EIGEN_DEVICE_FUNC typename Storage::Type data() const { return nullptr; }
292
293 protected:
294 Dimensions m_dimensions;
295 array<Index, NumDims> m_strides;
296 array<IndexDivisor, NumDims> m_fast_strides;
297 TensorEvaluator<ArgType, Device> m_impl;
298 RollDimensions m_rolls;
299 const Device EIGEN_DEVICE_REF m_device;
300
301 EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE void extract_coordinates(Index index, array<Index, NumDims>& coords) const {
302 EIGEN_IF_CONSTEXPR (static_cast<int>(Layout) == static_cast<int>(ColMajor)) {
303 for (int i = NumDims - 1; i > 0; --i) {
304 const Index idx = index / m_fast_strides[i];
305 index -= idx * m_strides[i];
306 coords[i] = idx;
307 }
308 coords[0] = index;
309 } else {
310 for (int i = 0; i < NumDims - 1; ++i) {
311 const Index idx = index / m_fast_strides[i];
312 index -= idx * m_strides[i];
313 coords[i] = idx;
314 }
315 coords[NumDims - 1] = index;
316 }
317 }
318};
319
320// Eval as lvalue
321
322template <typename RollDimensions, typename ArgType, typename Device>
323struct TensorEvaluator<TensorRollOp<RollDimensions, ArgType>, Device>
324 : public TensorEvaluator<const TensorRollOp<RollDimensions, ArgType>, Device> {
325 typedef TensorEvaluator<const TensorRollOp<RollDimensions, ArgType>, Device> Base;
326 typedef TensorRollOp<RollDimensions, ArgType> XprType;
327 typedef typename XprType::Index Index;
328 static constexpr int NumDims = internal::array_size<RollDimensions>::value;
329 typedef DSizes<Index, NumDims> Dimensions;
330
331 static constexpr int Layout = TensorEvaluator<ArgType, Device>::Layout;
332 enum {
333 IsAligned = false,
334 PacketAccess = TensorEvaluator<ArgType, Device>::PacketAccess,
335 // writeBlock() scatters the block into the argument's buffer as bulk
336 // copies of the wrap-around pieces, so it needs raw storage underneath.
337 BlockAccess = TensorEvaluator<ArgType, Device>::RawAccess,
338 // The coeff/packet write path pays a full div/mod index walk per scalar;
339 // the block path is a handful of bulk copies. Mirrors the rvalue side.
340 PreferBlockAccess = true,
341 CoordAccess = false,
342 RawAccess = false
343 };
344 EIGEN_STRONG_INLINE TensorEvaluator(const XprType& op, const Device& device) : Base(op, device) {}
345
346 typedef typename XprType::Scalar Scalar;
347 typedef typename XprType::CoeffReturnType CoeffReturnType;
348 typedef typename PacketType<CoeffReturnType, Device>::type PacketReturnType;
349 static constexpr int PacketSize = PacketType<CoeffReturnType, Device>::size;
350 typedef std::remove_const_t<Scalar> ScalarNoConst;
351
352 //===- Tensor block evaluation strategy (see TensorBlock.h) -------------===//
353 using TensorBlockDesc = internal::TensorBlockDescriptor<NumDims, Index>;
354 //===--------------------------------------------------------------------===//
355
356 EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE const Dimensions& dimensions() const { return this->m_dimensions; }
357
358 EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE Scalar& coeffRef(Index index) const {
359 return this->m_impl.coeffRef(this->rollIndex(index));
360 }
361
362 template <int StoreMode>
363 EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE void writePacket(Index index, const PacketReturnType& x) const {
364 eigen_assert(index + PacketSize - 1 < dimensions().TotalSize());
365 EIGEN_ALIGN_TO_BOUNDARY(internal::unpacket_traits<PacketReturnType>::alignment) CoeffReturnType values[PacketSize];
366 internal::pstore<CoeffReturnType, PacketReturnType>(values, x);
367 EIGEN_UNROLL_LOOP
368 for (int i = 0; i < PacketSize; ++i) {
369 this->coeffRef(index + i) = values[i];
370 }
371 }
372
373 template <typename TensorBlock>
374 EIGEN_STRONG_INLINE void writeBlock(const TensorBlockDesc& desc, const TensorBlock& block) {
375 if (desc.size() == 0) return;
376 eigen_assert(this->m_impl.data() != nullptr);
377
378 const DSizes<Index, NumDims> block_strides = internal::strides<Layout>(desc.dimensions());
379
380 // Materialize the block into a temporary buffer if it is lazy.
381 const ScalarNoConst* block_buffer = block.data();
382 void* mem = nullptr;
383 if (block_buffer == nullptr) {
384 mem = this->m_device.allocate(desc.size() * sizeof(Scalar));
385 ScalarNoConst* buf = static_cast<ScalarNoConst*>(mem);
386
387 typedef internal::TensorBlockAssignment<ScalarNoConst, NumDims, typename TensorBlock::XprType, Index>
388 TensorBlockAssignment;
389 TensorBlockAssignment::Run(TensorBlockAssignment::target(desc.dimensions(), block_strides, buf), block.expr());
390
391 block_buffer = buf;
392 }
393
394 // Output coordinates of the block's corner.
395 array<Index, NumDims> coords;
396 this->extract_coordinates(desc.offset(), coords);
397
398 // On each dimension the output range [o, o + e) maps to the input range
399 // starting at (o + r) mod n, wrapping around at most once.
400 struct Segment {
401 Index block_start;
402 Index input_start;
403 Index length;
404 };
405 Segment segments[NumDims][2];
406 int num_segments[NumDims];
407 for (int i = 0; i < NumDims; ++i) {
408 const Index n = this->m_dimensions[i];
409 const Index e = desc.dimension(i);
410 const Index start = this->roll(coords[i], this->m_rolls[i], n);
411 if (start + e <= n) {
412 segments[i][0] = {0, start, e};
413 num_segments[i] = 1;
414 } else {
415 segments[i][0] = {0, start, n - start};
416 segments[i][1] = {n - start, 0, e - (n - start)};
417 num_segments[i] = 2;
418 }
419 }
420
421 typedef internal::TensorBlockIO<ScalarNoConst, Index, NumDims, Layout> TensorBlockIO;
422 typedef typename TensorBlockIO::Dst TensorBlockIODst;
423 typedef typename TensorBlockIO::Src TensorBlockIOSrc;
424
425 const typename TensorBlockIO::Dimensions input_strides(this->m_strides);
426
427 // Copy every wrap-around piece (the cartesian product of the per-dim
428 // segments) into its destination box.
429 int seg_index[NumDims] = {0};
430 for (;;) {
431 DSizes<Index, NumDims> piece_dims;
432 Index src_offset = 0;
433 Index dst_offset = 0;
434 for (int i = 0; i < NumDims; ++i) {
435 const Segment& seg = segments[i][seg_index[i]];
436 piece_dims[i] = seg.length;
437 src_offset += seg.block_start * block_strides[i];
438 dst_offset += seg.input_start * this->m_strides[i];
439 }
440
441 TensorBlockIOSrc src(block_strides, block_buffer, src_offset);
442 TensorBlockIODst dst(piece_dims, input_strides, this->m_impl.data(), dst_offset);
443 TensorBlockIO::Copy(dst, src);
444
445 int d = 0;
446 while (d < NumDims && ++seg_index[d] == num_segments[d]) {
447 seg_index[d] = 0;
448 ++d;
449 }
450 if (d == NumDims) break;
451 }
452
453 // Deallocate temporary buffer used for the block materialization.
454 if (mem != nullptr) this->m_device.deallocate(mem);
455 }
456};
457
458} // end namespace Eigen
459
460#endif // EIGEN_TENSOR_TENSOR_ROLL_H
The tensor base class.
Definition TensorForwardDeclarations.h:69
Tensor roll (circular shift) elements class.
Definition TensorRoll.h:44
WriteAccessors
Namespace containing all symbols from the Eigen library.
The tensor evaluator class.
Definition TensorEvaluator.h:47