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