Eigen-unsupported  5.0.1-dev+284dcc12
 
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
11#ifndef EIGEN_CXX11_TENSOR_TENSOR_REVERSE_H
12#define EIGEN_CXX11_TENSOR_TENSOR_REVERSE_H
13// IWYU pragma: private
14#include "./InternalHeaderCheck.h"
15
16namespace Eigen {
17
18namespace internal {
19template <typename ReverseDimensions, typename XprType>
20struct traits<TensorReverseOp<ReverseDimensions, 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 typedef typename XprType::Nested Nested;
26 typedef std::remove_reference_t<Nested> Nested_;
27 static constexpr int NumDimensions = XprTraits::NumDimensions;
28 static constexpr int Layout = XprTraits::Layout;
29 typedef typename XprTraits::PointerType PointerType;
30};
31
32template <typename ReverseDimensions, typename XprType>
33struct eval<TensorReverseOp<ReverseDimensions, XprType>, Eigen::Dense> {
34 typedef const TensorReverseOp<ReverseDimensions, XprType>& type;
35};
36
37template <typename ReverseDimensions, typename XprType>
38struct nested<TensorReverseOp<ReverseDimensions, XprType>, 1,
39 typename eval<TensorReverseOp<ReverseDimensions, XprType> >::type> {
40 typedef TensorReverseOp<ReverseDimensions, XprType> type;
41};
42
43} // end namespace internal
44
51template <typename ReverseDimensions, typename XprType>
52class TensorReverseOp : public TensorBase<TensorReverseOp<ReverseDimensions, XprType>, WriteAccessors> {
53 public:
55 typedef typename Eigen::internal::traits<TensorReverseOp>::Scalar Scalar;
56 typedef typename Eigen::NumTraits<Scalar>::Real RealScalar;
57 typedef typename XprType::CoeffReturnType CoeffReturnType;
58 typedef typename Eigen::internal::nested<TensorReverseOp>::type Nested;
59 typedef typename Eigen::internal::traits<TensorReverseOp>::StorageKind StorageKind;
60 typedef typename Eigen::internal::traits<TensorReverseOp>::Index Index;
61
62 EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE TensorReverseOp(const XprType& expr, const ReverseDimensions& reverse_dims)
63 : m_xpr(expr), m_reverse_dims(reverse_dims) {}
64
65 EIGEN_DEVICE_FUNC const ReverseDimensions& reverse() const { return m_reverse_dims; }
66
67 EIGEN_DEVICE_FUNC const internal::remove_all_t<typename XprType::Nested>& expression() const { return m_xpr; }
68
69 EIGEN_TENSOR_INHERIT_ASSIGNMENT_OPERATORS(TensorReverseOp)
70
71 protected:
72 typename XprType::Nested m_xpr;
73 const ReverseDimensions m_reverse_dims;
74};
75
76// Eval as rvalue
77template <typename ReverseDimensions, typename ArgType, typename Device>
78struct TensorEvaluator<const TensorReverseOp<ReverseDimensions, ArgType>, Device> {
80 typedef typename XprType::Index Index;
81 static constexpr int NumDims = internal::array_size<ReverseDimensions>::value;
82 typedef DSizes<Index, NumDims> Dimensions;
83 typedef typename XprType::Scalar Scalar;
84 typedef typename XprType::CoeffReturnType CoeffReturnType;
85 typedef typename PacketType<CoeffReturnType, Device>::type PacketReturnType;
86 static constexpr int PacketSize = PacketType<CoeffReturnType, Device>::size;
87 typedef StorageMemory<CoeffReturnType, Device> Storage;
88 typedef typename Storage::Type EvaluatorPointerType;
89
90 static constexpr int Layout = TensorEvaluator<ArgType, Device>::Layout;
91 enum {
92 IsAligned = false,
93 PacketAccess = TensorEvaluator<ArgType, Device>::PacketAccess,
94 BlockAccess = NumDims > 0,
95 PreferBlockAccess = true,
96 CoordAccess = false, // to be implemented
97 RawAccess = false
98 };
99
100 typedef internal::TensorIntDivisor<Index> IndexDivisor;
101
102 //===- Tensor block evaluation strategy (see TensorBlock.h) -------------===//
103 typedef internal::TensorBlockDescriptor<NumDims, Index> TensorBlockDesc;
104 typedef internal::TensorBlockScratchAllocator<Device> TensorBlockScratch;
105
106 typedef typename TensorEvaluator<const ArgType, Device>::TensorBlock ArgTensorBlock;
107
108 typedef typename internal::TensorMaterializedBlock<CoeffReturnType, NumDims, Layout, Index> TensorBlock;
109 //===--------------------------------------------------------------------===//
110
111 EIGEN_STRONG_INLINE TensorEvaluator(const XprType& op, const Device& device)
112 : m_impl(op.expression(), device), m_reverse(op.reverse()), m_device(device) {
113 // Reversing a scalar isn't supported yet. It would be a no-op anyway.
114 EIGEN_STATIC_ASSERT((NumDims > 0), YOU_MADE_A_PROGRAMMING_MISTAKE);
115
116 // Compute strides
117 m_dimensions = m_impl.dimensions();
118 if (static_cast<int>(Layout) == static_cast<int>(ColMajor)) {
119 m_strides[0] = 1;
120 for (int i = 1; i < NumDims; ++i) {
121 m_strides[i] = m_strides[i - 1] * m_dimensions[i - 1];
122 if (m_strides[i] > 0) m_fastStrides[i] = IndexDivisor(m_strides[i]);
123 }
124 } else {
125 m_strides[NumDims - 1] = 1;
126 for (int i = NumDims - 2; i >= 0; --i) {
127 m_strides[i] = m_strides[i + 1] * m_dimensions[i + 1];
128 if (m_strides[i] > 0) m_fastStrides[i] = IndexDivisor(m_strides[i]);
129 }
130 }
131 }
132
133 EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE const Dimensions& dimensions() const { return m_dimensions; }
134
135 EIGEN_STRONG_INLINE bool evalSubExprsIfNeeded(EvaluatorPointerType) {
136 m_impl.evalSubExprsIfNeeded(NULL);
137 return true;
138 }
139
140#ifdef EIGEN_USE_THREADS
141 template <typename EvalSubExprsCallback>
142 EIGEN_STRONG_INLINE void evalSubExprsIfNeededAsync(EvaluatorPointerType, EvalSubExprsCallback done) {
143 m_impl.evalSubExprsIfNeededAsync(nullptr, [done](bool) { done(true); });
144 }
145#endif // EIGEN_USE_THREADS
146
147 EIGEN_STRONG_INLINE void cleanup() { m_impl.cleanup(); }
148
149 EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE Index reverseIndex(Index index) const {
150 eigen_assert(index < dimensions().TotalSize());
151 Index inputIndex = 0;
152 if (static_cast<int>(Layout) == static_cast<int>(ColMajor)) {
153 EIGEN_UNROLL_LOOP
154 for (int i = NumDims - 1; i > 0; --i) {
155 Index idx = index / m_fastStrides[i];
156 index -= idx * m_strides[i];
157 if (m_reverse[i]) {
158 idx = m_dimensions[i] - idx - 1;
159 }
160 inputIndex += idx * m_strides[i];
161 }
162 if (m_reverse[0]) {
163 inputIndex += (m_dimensions[0] - index - 1);
164 } else {
165 inputIndex += index;
166 }
167 } else {
168 EIGEN_UNROLL_LOOP
169 for (int i = 0; i < NumDims - 1; ++i) {
170 Index idx = index / m_fastStrides[i];
171 index -= idx * m_strides[i];
172 if (m_reverse[i]) {
173 idx = m_dimensions[i] - idx - 1;
174 }
175 inputIndex += idx * m_strides[i];
176 }
177 if (m_reverse[NumDims - 1]) {
178 inputIndex += (m_dimensions[NumDims - 1] - index - 1);
179 } else {
180 inputIndex += index;
181 }
182 }
183 return inputIndex;
184 }
185
186 EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE CoeffReturnType coeff(Index index) const {
187 return m_impl.coeff(reverseIndex(index));
188 }
189
190 template <int LoadMode>
191 EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE PacketReturnType packet(Index index) const {
192 eigen_assert(index + PacketSize - 1 < dimensions().TotalSize());
193
194 // TODO(ndjaitly): write a better packing routine that uses
195 // local structure.
196 EIGEN_ALIGN_MAX std::remove_const_t<CoeffReturnType> values[PacketSize];
197 EIGEN_UNROLL_LOOP
198 for (int i = 0; i < PacketSize; ++i) {
199 values[i] = coeff(index + i);
200 }
201 PacketReturnType rslt = internal::pload<PacketReturnType>(values);
202 return rslt;
203 }
204
205 EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE internal::TensorBlockResourceRequirements getResourceRequirements() const {
206 const size_t target_size = m_device.lastLevelCacheSize();
207 // Block evaluation reads underlying memory in reverse order, and default
208 // cost model does not properly catch this in bytes stored/loaded.
209 return internal::TensorBlockResourceRequirements::skewed<Scalar>(target_size).addCostPerCoeff({0, 0, 24});
210 }
211
212 EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE TensorBlock block(TensorBlockDesc& desc, TensorBlockScratch& scratch,
213 bool /*root_of_expr_ast*/ = false) const {
214 // TODO(ezhulenev): If underlying tensor expression supports and prefers
215 // block evaluation we must use it. Currently we use coeff and packet
216 // access into the underlying tensor expression.
217 // static const bool useBlockAccessForArgType =
218 // TensorEvaluator<ArgType, Device>::BlockAccess &&
219 // TensorEvaluator<ArgType, Device>::PreferBlockAccess;
220
221 static const bool isColMajor = static_cast<int>(Layout) == static_cast<int>(ColMajor);
222
223 static const Index inner_dim_idx = isColMajor ? 0 : NumDims - 1;
224 const bool inner_dim_reversed = m_reverse[inner_dim_idx];
225
226 // Offset in the output block.
227 Index block_offset = 0;
228
229 // Offset in the input Tensor.
230 Index input_offset = reverseIndex(desc.offset());
231
232 // Initialize output block iterator state. Dimension in this array are
233 // always in inner_most -> outer_most order (col major layout).
234 array<BlockIteratorState, NumDims> it;
235 for (int i = 0; i < NumDims; ++i) {
236 const int dim = isColMajor ? i : NumDims - 1 - i;
237 it[i].size = desc.dimension(dim);
238 it[i].count = 0;
239 it[i].reverse = m_reverse[dim];
240
241 it[i].block_stride = i == 0 ? 1 : (it[i - 1].size * it[i - 1].block_stride);
242 it[i].block_span = it[i].block_stride * (it[i].size - 1);
243
244 it[i].input_stride = m_strides[dim];
245 it[i].input_span = it[i].input_stride * (it[i].size - 1);
246
247 if (it[i].reverse) {
248 it[i].input_stride = -1 * it[i].input_stride;
249 it[i].input_span = -1 * it[i].input_span;
250 }
251 }
252
253 // If multiple inner dimensions have the same reverse flag, check if we can
254 // merge them into a single virtual inner dimension.
255 int effective_inner_dim = 0;
256 for (int i = 1; i < NumDims; ++i) {
257 if (it[i].reverse != it[effective_inner_dim].reverse) break;
258 if (it[i].block_stride != it[effective_inner_dim].size) break;
259 if (it[i].block_stride != numext::abs(it[i].input_stride)) break;
260
261 it[i].size = it[effective_inner_dim].size * it[i].size;
262
263 it[i].block_stride = 1;
264 it[i].input_stride = (inner_dim_reversed ? -1 : 1);
265
266 it[i].block_span = it[i].block_stride * (it[i].size - 1);
267 it[i].input_span = it[i].input_stride * (it[i].size - 1);
268
269 effective_inner_dim = i;
270 }
271
272 eigen_assert(it[effective_inner_dim].block_stride == 1);
273 eigen_assert(it[effective_inner_dim].input_stride == (inner_dim_reversed ? -1 : 1));
274
275 const Index inner_dim_size = it[effective_inner_dim].size;
276
277 // Prepare storage for the materialized reverse result.
278 const typename TensorBlock::Storage block_storage = TensorBlock::prepareStorage(desc, scratch);
279 CoeffReturnType* block_buffer = block_storage.data();
280
281 while (it[NumDims - 1].count < it[NumDims - 1].size) {
282 // Copy inner-most dimension data from reversed location in input.
283 Index dst = block_offset;
284 Index src = input_offset;
285
286 // NOTE(ezhulenev): Adding vectorized path with internal::preverse showed
287 // worse results in benchmarks than a simple coefficient loop.
288 if (inner_dim_reversed) {
289 for (Index i = 0; i < inner_dim_size; ++i) {
290 block_buffer[dst] = m_impl.coeff(src);
291 ++dst;
292 --src;
293 }
294 } else {
295 for (Index i = 0; i < inner_dim_size; ++i) {
296 block_buffer[dst] = m_impl.coeff(src);
297 ++dst;
298 ++src;
299 }
300 }
301
302 // For the 1d tensor we need to generate only one inner-most dimension.
303 if ((NumDims - effective_inner_dim) == 1) break;
304
305 // Update offset.
306 for (Index i = effective_inner_dim + 1; i < NumDims; ++i) {
307 if (++it[i].count < it[i].size) {
308 block_offset += it[i].block_stride;
309 input_offset += it[i].input_stride;
310 break;
311 }
312 if (i != NumDims - 1) it[i].count = 0;
313 block_offset -= it[i].block_span;
314 input_offset -= it[i].input_span;
315 }
316 }
317
318 return block_storage.AsTensorMaterializedBlock();
319 }
320
321 EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE TensorOpCost costPerCoeff(bool vectorized) const {
322 double compute_cost = NumDims * (2 * TensorOpCost::AddCost<Index>() + 2 * TensorOpCost::MulCost<Index>() +
323 TensorOpCost::DivCost<Index>());
324 for (int i = 0; i < NumDims; ++i) {
325 if (m_reverse[i]) {
326 compute_cost += 2 * TensorOpCost::AddCost<Index>();
327 }
328 }
329 return m_impl.costPerCoeff(vectorized) + TensorOpCost(0, 0, compute_cost, false /* vectorized */, PacketSize);
330 }
331
332 EIGEN_DEVICE_FUNC typename Storage::Type data() const { return NULL; }
333
334 protected:
335 Dimensions m_dimensions;
336 array<Index, NumDims> m_strides;
337 array<IndexDivisor, NumDims> m_fastStrides;
338 TensorEvaluator<ArgType, Device> m_impl;
339 ReverseDimensions m_reverse;
340 const Device EIGEN_DEVICE_REF m_device;
341
342 private:
343 struct BlockIteratorState {
344 BlockIteratorState()
345 : size(0), count(0), reverse(false), block_stride(0), block_span(0), input_stride(0), input_span(0) {}
346
347 Index size;
348 Index count;
349 bool reverse;
350 Index block_stride;
351 Index block_span;
352 Index input_stride;
353 Index input_span;
354 };
355};
356
357// Eval as lvalue
358
359template <typename ReverseDimensions, typename ArgType, typename Device>
360struct TensorEvaluator<TensorReverseOp<ReverseDimensions, ArgType>, Device>
361 : public TensorEvaluator<const TensorReverseOp<ReverseDimensions, ArgType>, Device> {
362 typedef TensorEvaluator<const TensorReverseOp<ReverseDimensions, ArgType>, Device> Base;
363 typedef TensorReverseOp<ReverseDimensions, ArgType> XprType;
364 typedef typename XprType::Index Index;
365 static constexpr int NumDims = internal::array_size<ReverseDimensions>::value;
366 typedef DSizes<Index, NumDims> Dimensions;
367
368 static constexpr int Layout = TensorEvaluator<ArgType, Device>::Layout;
369 enum {
370 IsAligned = false,
371 PacketAccess = TensorEvaluator<ArgType, Device>::PacketAccess,
372 BlockAccess = false,
373 PreferBlockAccess = false,
374 CoordAccess = false, // to be implemented
375 RawAccess = false
376 };
377 EIGEN_STRONG_INLINE TensorEvaluator(const XprType& op, const Device& device) : Base(op, device) {}
378
379 typedef typename XprType::Scalar Scalar;
380 typedef typename XprType::CoeffReturnType CoeffReturnType;
381 typedef typename PacketType<CoeffReturnType, Device>::type PacketReturnType;
382 static constexpr int PacketSize = PacketType<CoeffReturnType, Device>::size;
383
384 //===- Tensor block evaluation strategy (see TensorBlock.h) -------------===//
385 typedef internal::TensorBlockNotImplemented TensorBlock;
386 //===--------------------------------------------------------------------===//
387
388 EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE const Dimensions& dimensions() const { return this->m_dimensions; }
389
390 EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE Scalar& coeffRef(Index index) const {
391 return this->m_impl.coeffRef(this->reverseIndex(index));
392 }
393
394 template <int StoreMode>
395 EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE void writePacket(Index index, const PacketReturnType& x) const {
396 eigen_assert(index + PacketSize - 1 < dimensions().TotalSize());
397
398 // This code is pilfered from TensorMorphing.h
399 EIGEN_ALIGN_MAX CoeffReturnType values[PacketSize];
400 internal::pstore<CoeffReturnType, PacketReturnType>(values, x);
401 EIGEN_UNROLL_LOOP
402 for (int i = 0; i < PacketSize; ++i) {
403 this->coeffRef(index + i) = values[i];
404 }
405 }
406};
407
408} // end namespace Eigen
409
410#endif // EIGEN_CXX11_TENSOR_TENSOR_REVERSE_H
The tensor base class.
Definition TensorForwardDeclarations.h:68
Tensor reverse elements class.
Definition TensorReverse.h:52
WriteAccessors
Namespace containing all symbols from the Eigen library.
EIGEN_DEFAULT_DENSE_INDEX_TYPE Index
The tensor evaluator class.
Definition TensorEvaluator.h:30