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