Eigen-Contrib  5.0.1
 
Loading...
Searching...
No Matches
TensorReverse.h
1// This file is part of Eigen, a lightweight C++ template library
2// for linear algebra.
3//
4// Copyright (C) 2014 Navdeep Jaitly <ndjaitly@google.com>
5// Benoit Steiner <benoit.steiner.goog@gmail.com>
6//
7// This Source Code Form is subject to the terms of the Mozilla
8// Public License v. 2.0. If a copy of the MPL was not distributed
9// with this file, You can obtain one at http://mozilla.org/MPL/2.0/.
10// SPDX-License-Identifier: MPL-2.0
11
12#ifndef EIGEN_TENSOR_TENSOR_REVERSE_H
13#define EIGEN_TENSOR_TENSOR_REVERSE_H
14// IWYU pragma: private
15#include "./InternalHeaderCheck.h"
16
17namespace Eigen {
18
19namespace internal {
20template <typename ReverseDimensions, typename XprType>
21struct traits<TensorReverseOp<ReverseDimensions, XprType> > : public traits<XprType> {
22 typedef typename XprType::Scalar Scalar;
23 typedef traits<XprType> XprTraits;
24 typedef typename XprTraits::StorageKind StorageKind;
25 typedef typename XprTraits::Index Index;
26 static constexpr int NumDimensions = XprTraits::NumDimensions;
27 static constexpr int Layout = XprTraits::Layout;
28 typedef typename XprTraits::PointerType PointerType;
29};
30
31template <typename ReverseDimensions, typename XprType>
32struct eval<TensorReverseOp<ReverseDimensions, XprType>, Eigen::Dense> {
33 typedef const TensorReverseOp<ReverseDimensions, XprType>& type;
34};
35
36} // end namespace internal
37
44template <typename ReverseDimensions, typename XprType>
45class TensorReverseOp : public TensorBase<TensorReverseOp<ReverseDimensions, XprType>, WriteAccessors> {
46 public:
48 typedef typename Eigen::internal::traits<TensorReverseOp>::Scalar Scalar;
49 typedef typename Eigen::NumTraits<Scalar>::Real RealScalar;
50 typedef typename XprType::CoeffReturnType CoeffReturnType;
51 typedef typename Eigen::internal::ref_selector<TensorReverseOp>::type Nested;
52 typedef typename Eigen::internal::traits<TensorReverseOp>::StorageKind StorageKind;
53 typedef typename Eigen::internal::traits<TensorReverseOp>::Index Index;
54
55 EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE TensorReverseOp(const XprType& expr, const ReverseDimensions& reverse_dims)
56 : m_xpr(expr), m_reverse_dims(reverse_dims) {}
57
58 EIGEN_DEVICE_FUNC const ReverseDimensions& reverse() const { return m_reverse_dims; }
59
60 EIGEN_DEVICE_FUNC const internal::remove_all_t<typename XprType::Nested>& expression() const { return m_xpr; }
61
62 EIGEN_INHERIT_ASSIGNMENT_OPERATORS(TensorReverseOp)
63
64 protected:
65 typename XprType::Nested m_xpr;
66 const ReverseDimensions m_reverse_dims;
67};
68
69// Eval as rvalue
70template <typename ReverseDimensions, typename ArgType, typename Device>
71struct TensorEvaluator<const TensorReverseOp<ReverseDimensions, ArgType>, Device> {
73 typedef typename XprType::Index Index;
74 static constexpr int NumDims = internal::array_size<ReverseDimensions>::value;
75 typedef DSizes<Index, NumDims> Dimensions;
76 typedef typename XprType::Scalar Scalar;
77 typedef typename XprType::CoeffReturnType CoeffReturnType;
78 typedef typename PacketType<CoeffReturnType, Device>::type PacketReturnType;
79 static constexpr int PacketSize = PacketType<CoeffReturnType, Device>::size;
80 typedef StorageMemory<CoeffReturnType, Device> Storage;
81 typedef typename Storage::Type EvaluatorPointerType;
82
83 static constexpr int Layout = TensorEvaluator<ArgType, Device>::Layout;
84 enum {
85 IsAligned = false,
86 PacketAccess = TensorEvaluator<ArgType, Device>::PacketAccess,
87 BlockAccess = NumDims > 0,
88 PreferBlockAccess = true,
89 CoordAccess = false, // to be implemented
90 RawAccess = false
91 };
92
93 typedef internal::TensorIntDivisor<Index> IndexDivisor;
94
95 //===- Tensor block evaluation strategy (see TensorBlock.h) -------------===//
96 typedef internal::TensorBlockDescriptor<NumDims, Index> TensorBlockDesc;
97 typedef internal::TensorBlockScratchAllocator<Device> TensorBlockScratch;
98
99 typedef typename TensorEvaluator<const ArgType, Device>::TensorBlock ArgTensorBlock;
100
101 typedef typename internal::TensorMaterializedBlock<CoeffReturnType, NumDims, Layout, Index> TensorBlock;
102 //===--------------------------------------------------------------------===//
103
104 EIGEN_STRONG_INLINE TensorEvaluator(const XprType& op, const Device& device)
105 : m_impl(op.expression(), device), m_reverse(op.reverse()), m_device(device) {
106 // Reversing a scalar isn't supported yet. It would be a no-op anyway.
107 EIGEN_STATIC_ASSERT((NumDims > 0), YOU_MADE_A_PROGRAMMING_MISTAKE);
108
109 // Compute strides
110 m_dimensions = m_impl.dimensions();
111 EIGEN_IF_CONSTEXPR (static_cast<int>(Layout) == static_cast<int>(ColMajor)) {
112 m_strides[0] = 1;
113 for (int i = 1; i < NumDims; ++i) {
114 m_strides[i] = m_strides[i - 1] * m_dimensions[i - 1];
115 if (m_strides[i] > 0) m_fastStrides[i] = IndexDivisor(m_strides[i]);
116 }
117 } else {
118 m_strides[NumDims - 1] = 1;
119 for (int i = NumDims - 2; i >= 0; --i) {
120 m_strides[i] = m_strides[i + 1] * m_dimensions[i + 1];
121 if (m_strides[i] > 0) m_fastStrides[i] = IndexDivisor(m_strides[i]);
122 }
123 }
124 }
125
126 EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE const Dimensions& dimensions() const { return m_dimensions; }
127
128 EIGEN_STRONG_INLINE bool evalSubExprsIfNeeded(EvaluatorPointerType) {
129 m_impl.evalSubExprsIfNeeded(nullptr);
130 return true;
131 }
132
133#ifdef EIGEN_USE_THREADS
134 template <typename EvalSubExprsCallback>
135 EIGEN_STRONG_INLINE void evalSubExprsIfNeededAsync(EvaluatorPointerType, EvalSubExprsCallback done) {
136 m_impl.evalSubExprsIfNeededAsync(nullptr, [done](bool) { done(true); });
137 }
138#endif // EIGEN_USE_THREADS
139
140 EIGEN_STRONG_INLINE void cleanup() { m_impl.cleanup(); }
141
142 EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE Index reverseIndex(Index index) const {
143 eigen_assert(index < dimensions().TotalSize());
144 Index inputIndex = 0;
145 EIGEN_IF_CONSTEXPR (static_cast<int>(Layout) == static_cast<int>(ColMajor)) {
146 EIGEN_UNROLL_LOOP
147 for (int i = NumDims - 1; i > 0; --i) {
148 Index idx = index / m_fastStrides[i];
149 index -= idx * m_strides[i];
150 if (m_reverse[i]) {
151 idx = m_dimensions[i] - idx - 1;
152 }
153 inputIndex += idx * m_strides[i];
154 }
155 if (m_reverse[0]) {
156 inputIndex += m_dimensions[0] - index - 1;
157 } else {
158 inputIndex += index;
159 }
160 } else {
161 EIGEN_UNROLL_LOOP
162 for (int i = 0; i < NumDims - 1; ++i) {
163 Index idx = index / m_fastStrides[i];
164 index -= idx * m_strides[i];
165 if (m_reverse[i]) {
166 idx = m_dimensions[i] - idx - 1;
167 }
168 inputIndex += idx * m_strides[i];
169 }
170 if (m_reverse[NumDims - 1]) {
171 inputIndex += m_dimensions[NumDims - 1] - index - 1;
172 } else {
173 inputIndex += index;
174 }
175 }
176 return inputIndex;
177 }
178
179 EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE CoeffReturnType coeff(Index index) const {
180 return m_impl.coeff(reverseIndex(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 whole packet stays inside a single inner-most
188 // slice of the input, replace PacketSize coeff() calls with one packet
189 // load (plus a preverse when the inner dim is reversed).
190 constexpr int inner_dim = (static_cast<int>(Layout) == static_cast<int>(ColMajor)) ? 0 : NumDims - 1;
191 const Index inner_size = m_dimensions[inner_dim];
192 const Index inner_pos = index % inner_size;
193 if (inner_pos + PacketSize <= inner_size) {
194 if (m_reverse[inner_dim]) {
195 const Index input_index = reverseIndex(index + PacketSize - 1);
196 return internal::preverse(m_impl.template packet<Unaligned>(input_index));
197 }
198 return m_impl.template packet<Unaligned>(reverseIndex(index));
199 }
200
201 // Slow path: the packet crosses an inner-slice boundary, so the
202 // contiguous-load trick does not apply.
203 EIGEN_ALIGN_TO_BOUNDARY(internal::unpacket_traits<PacketReturnType>::alignment)
204 std::remove_const_t<CoeffReturnType> values[PacketSize];
205 EIGEN_UNROLL_LOOP
206 for (int i = 0; i < PacketSize; ++i) {
207 values[i] = coeff(index + i);
208 }
209 return internal::pload<PacketReturnType>(values);
210 }
211
212 EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE internal::TensorBlockResourceRequirements getResourceRequirements() const {
213 const size_t target_size = m_device.lastLevelCacheSize();
214 // Block evaluation reads underlying memory in reverse order, and default
215 // cost model does not properly catch this in bytes stored/loaded.
216 return internal::TensorBlockResourceRequirements::skewed<Scalar>(target_size).addCostPerCoeff({0, 0, 24});
217 }
218
219 EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE TensorBlock block(TensorBlockDesc& desc, TensorBlockScratch& scratch,
220 bool /*root_of_expr_ast*/ = false) const {
221 // TODO(ezhulenev): If underlying tensor expression supports and prefers
222 // block evaluation we must use it. Currently we use coeff and packet
223 // access into the underlying tensor expression.
224 static const bool isColMajor = static_cast<int>(Layout) == static_cast<int>(ColMajor);
225
226 static constexpr Index inner_dim_idx = isColMajor ? 0 : NumDims - 1;
227 const bool inner_dim_reversed = m_reverse[inner_dim_idx];
228
229 // Offset in the output block.
230 Index block_offset = 0;
231
232 // Offset in the input Tensor.
233 Index input_offset = reverseIndex(desc.offset());
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 = isColMajor ? i : NumDims - 1 - i;
240 it[i].size = desc.dimension(dim);
241 it[i].count = 0;
242 it[i].reverse = m_reverse[dim];
243
244 it[i].block_stride = i == 0 ? 1 : (it[i - 1].size * it[i - 1].block_stride);
245 it[i].block_span = it[i].block_stride * (it[i].size - 1);
246
247 it[i].input_stride = m_strides[dim];
248 it[i].input_span = it[i].input_stride * (it[i].size - 1);
249
250 if (it[i].reverse) {
251 it[i].input_stride = -1 * it[i].input_stride;
252 it[i].input_span = -1 * it[i].input_span;
253 }
254 }
255
256 // If multiple inner dimensions have the same reverse flag, check if we can
257 // merge them into a single virtual inner dimension.
258 int effective_inner_dim = 0;
259 for (int i = 1; i < NumDims; ++i) {
260 if (it[i].reverse != it[effective_inner_dim].reverse) break;
261 if (it[i].block_stride != it[effective_inner_dim].size) break;
262 if (it[i].block_stride != numext::abs(it[i].input_stride)) break;
263
264 it[i].size = it[effective_inner_dim].size * it[i].size;
265
266 it[i].block_stride = 1;
267 it[i].input_stride = (inner_dim_reversed ? -1 : 1);
268
269 it[i].block_span = it[i].block_stride * (it[i].size - 1);
270 it[i].input_span = it[i].input_stride * (it[i].size - 1);
271
272 effective_inner_dim = i;
273 }
274
275 eigen_assert(it[effective_inner_dim].block_stride == 1);
276 eigen_assert(it[effective_inner_dim].input_stride == (inner_dim_reversed ? -1 : 1));
277
278 const Index inner_dim_size = it[effective_inner_dim].size;
279
280 // Prepare storage for the materialized reverse result.
281 const typename TensorBlock::Storage block_storage = TensorBlock::prepareStorage(desc, scratch);
282 CoeffReturnType* block_buffer = block_storage.data();
283
284 while (it[NumDims - 1].count < it[NumDims - 1].size) {
285 // Copy inner-most dimension data from reversed location in input.
286 Index dst = block_offset;
287 Index src = input_offset;
288
289 // NOTE(ezhulenev): Adding vectorized path with internal::preverse showed
290 // worse results in benchmarks than a simple coefficient loop.
291 if (inner_dim_reversed) {
292 for (Index i = 0; i < inner_dim_size; ++i) {
293 block_buffer[dst] = m_impl.coeff(src);
294 ++dst;
295 --src;
296 }
297 } else {
298 for (Index i = 0; i < inner_dim_size; ++i) {
299 block_buffer[dst] = m_impl.coeff(src);
300 ++dst;
301 ++src;
302 }
303 }
304
305 // For the 1d tensor we need to generate only one inner-most dimension.
306 if ((NumDims - effective_inner_dim) == 1) break;
307
308 // Update offset.
309 for (Index i = effective_inner_dim + 1; i < NumDims; ++i) {
310 if (++it[i].count < it[i].size) {
311 block_offset += it[i].block_stride;
312 input_offset += it[i].input_stride;
313 break;
314 }
315 if (i != NumDims - 1) it[i].count = 0;
316 block_offset -= it[i].block_span;
317 input_offset -= it[i].input_span;
318 }
319 }
320
321 return block_storage.AsTensorMaterializedBlock();
322 }
323
324 EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE TensorOpCost costPerCoeff(bool vectorized) const {
325 double compute_cost = NumDims * (2 * TensorOpCost::AddCost<Index>() + 2 * TensorOpCost::MulCost<Index>() +
326 TensorOpCost::DivCost<Index>());
327 for (int i = 0; i < NumDims; ++i) {
328 if (m_reverse[i]) {
329 compute_cost += 2 * TensorOpCost::AddCost<Index>();
330 }
331 }
332 // The inner-slice fast path runs the per-coeff index math once per packet,
333 // so the amortized compute cost matches the vectorized convention.
334 return m_impl.costPerCoeff(vectorized) + TensorOpCost(0, 0, compute_cost, vectorized, PacketSize);
335 }
336
337 EIGEN_DEVICE_FUNC typename Storage::Type data() const { return nullptr; }
338
339 protected:
340 Dimensions m_dimensions;
341 array<Index, NumDims> m_strides;
342 array<IndexDivisor, NumDims> m_fastStrides;
343 TensorEvaluator<ArgType, Device> m_impl;
344 ReverseDimensions m_reverse;
345 const Device EIGEN_DEVICE_REF m_device;
346
347 private:
348 struct BlockIteratorState {
349 BlockIteratorState()
350 : size(0), count(0), reverse(false), block_stride(0), block_span(0), input_stride(0), input_span(0) {}
351
352 Index size;
353 Index count;
354 bool reverse;
355 Index block_stride;
356 Index block_span;
357 Index input_stride;
358 Index input_span;
359 };
360};
361
362// Eval as lvalue
363
364template <typename ReverseDimensions, typename ArgType, typename Device>
365struct TensorEvaluator<TensorReverseOp<ReverseDimensions, ArgType>, Device>
366 : public TensorEvaluator<const TensorReverseOp<ReverseDimensions, ArgType>, Device> {
367 typedef TensorEvaluator<const TensorReverseOp<ReverseDimensions, ArgType>, Device> Base;
368 typedef TensorReverseOp<ReverseDimensions, ArgType> XprType;
369 typedef typename XprType::Index Index;
370 static constexpr int NumDims = internal::array_size<ReverseDimensions>::value;
371 typedef DSizes<Index, NumDims> Dimensions;
372
373 static constexpr int Layout = TensorEvaluator<ArgType, Device>::Layout;
374 enum {
375 IsAligned = false,
376 PacketAccess = TensorEvaluator<ArgType, Device>::PacketAccess,
377 // writeBlock() assigns the re-reversed block expression straight into the
378 // argument's buffer, so it needs raw storage underneath.
379 BlockAccess = TensorEvaluator<ArgType, Device>::RawAccess,
380 // Unlike the rvalue side there is no preference: the reversal cost moves
381 // to the block-expression reads, so writing blocks only pays off when the
382 // right-hand side prefers block evaluation anyway.
383 PreferBlockAccess = false,
384 CoordAccess = false, // to be implemented
385 RawAccess = false
386 };
387 EIGEN_STRONG_INLINE TensorEvaluator(const XprType& op, const Device& device) : Base(op, device) {}
388
389 typedef typename XprType::Scalar Scalar;
390 typedef typename XprType::CoeffReturnType CoeffReturnType;
391 typedef typename PacketType<CoeffReturnType, Device>::type PacketReturnType;
392 static constexpr int PacketSize = PacketType<CoeffReturnType, Device>::size;
393 typedef std::remove_const_t<Scalar> ScalarNoConst;
394
395 //===- Tensor block evaluation strategy (see TensorBlock.h) -------------===//
396 typedef internal::TensorBlockDescriptor<NumDims, Index> TensorBlockDesc;
397 //===--------------------------------------------------------------------===//
398
399 EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE const Dimensions& dimensions() const { return this->m_dimensions; }
400
401 EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE Scalar& coeffRef(Index index) const {
402 return this->m_impl.coeffRef(this->reverseIndex(index));
403 }
404
405 EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE internal::TensorBlockResourceRequirements getResourceRequirements() const {
406 // Deliberately not the rvalue evaluator's requirements. Reading a block
407 // reverses memory as it materializes it straight into the output, which is
408 // why that side asks for a last-level-cache sized, inner-dim-skewed block.
409 // As a write destination we have no such preference: writeBlock() only
410 // copies the block into a strided box. Since merge() lets kSkewedInnerDims
411 // win over kUniformAllDims and keeps the larger size, inheriting them would
412 // silently override the shape the right-hand side asked for -- a shuffle
413 // that permutes the inner dimension requests small uniform tiles precisely
414 // because that is what keeps a transpose cache-resident, and turning those
415 // into one cache-sized skewed strip costs more than the block path wins.
416 // Only impose a lower bound on the block size, so that a right-hand side
417 // without any preference still gets sensibly sized blocks.
418 return internal::TensorBlockResourceRequirements::merge(
419 this->m_impl.getResourceRequirements(),
420 internal::TensorBlockResourceRequirements::uniform<Scalar>(this->m_device.firstLevelCacheSize()));
421 }
422
423 template <int StoreMode>
424 EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE void writePacket(Index index, const PacketReturnType& x) const {
425 eigen_assert(index + PacketSize - 1 < dimensions().TotalSize());
426
427 // Fast path, mirroring packet() in the rvalue evaluator: when the whole
428 // packet stays inside a single inner-most slice of the input, replace
429 // PacketSize coeffRef() calls (each paying a full reverseIndex walk) with
430 // one packet store (plus a preverse when the inner dim is reversed).
431 constexpr int inner_dim = (static_cast<int>(Layout) == static_cast<int>(ColMajor)) ? 0 : NumDims - 1;
432 const Index inner_size = this->m_dimensions[inner_dim];
433 const Index inner_pos = index % inner_size;
434 if (inner_pos + PacketSize <= inner_size) {
435 if (this->m_reverse[inner_dim]) {
436 const Index input_index = this->reverseIndex(index + PacketSize - 1);
437 this->m_impl.template writePacket<Unaligned>(input_index, internal::preverse(x));
438 } else {
439 this->m_impl.template writePacket<Unaligned>(this->reverseIndex(index), x);
440 }
441 return;
442 }
443
444 // Slow path: the packet crosses an inner-slice boundary.
445 EIGEN_ALIGN_TO_BOUNDARY(internal::unpacket_traits<PacketReturnType>::alignment) CoeffReturnType values[PacketSize];
446 internal::pstore<CoeffReturnType, PacketReturnType>(values, x);
447 EIGEN_UNROLL_LOOP
448 for (int i = 0; i < PacketSize; ++i) {
449 this->coeffRef(index + i) = values[i];
450 }
451 }
452
453 template <typename TensorBlock>
454 EIGEN_STRONG_INLINE void writeBlock(const TensorBlockDesc& desc, const TensorBlock& block) {
455 eigen_assert(this->m_impl.data() != nullptr);
456
457 // The destination of a block is a box in the underlying tensor: on a
458 // reversed dimension the output range [o, o + e) maps to the input range
459 // [n - o - e, n - o), whose corner sits (e - 1) strides below the image of
460 // the block's origin.
461 Index input_corner = this->reverseIndex(desc.offset());
462 for (int i = 0; i < NumDims; ++i) {
463 if (this->m_reverse[i]) input_corner -= (desc.dimension(i) - 1) * this->m_strides[i];
464 }
465
466 // Assigning the block expression reversed along the reversed dimensions
467 // into that box cancels the reversal; the reversed reads vectorize via
468 // the rvalue evaluator's inner-slice fast path while the stores stay
469 // contiguous.
470 typedef TensorReverseOp<const ReverseDimensions, const typename TensorBlock::XprType> RevBlockExpr;
471 const RevBlockExpr reversed_block(block.expr(), this->m_reverse);
472
473 typedef internal::TensorBlockAssignment<ScalarNoConst, NumDims, RevBlockExpr, Index> TensorBlockAssign;
474 TensorBlockAssign::Run(TensorBlockAssign::target(desc.dimensions(), DSizes<Index, NumDims>(this->m_strides),
475 this->m_impl.data(), input_corner),
476 reversed_block);
477 }
478};
479
480} // end namespace Eigen
481
482#endif // EIGEN_TENSOR_TENSOR_REVERSE_H
The tensor base class.
Definition TensorForwardDeclarations.h:69
Tensor reverse elements class.
Definition TensorReverse.h:45
WriteAccessors
Namespace containing all symbols from the Eigen library.
The tensor evaluator class.
Definition TensorEvaluator.h:47