Eigen-Contrib  5.0.1
 
Loading...
Searching...
No Matches
TensorLayoutSwap.h
1// This file is part of Eigen, a lightweight C++ template library
2// for linear algebra.
3//
4// Copyright (C) 2014 Benoit Steiner <benoit.steiner.goog@gmail.com>
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_LAYOUT_SWAP_H
12#define EIGEN_TENSOR_TENSOR_LAYOUT_SWAP_H
13
14// IWYU pragma: private
15#include "./InternalHeaderCheck.h"
16
17namespace Eigen {
18
19namespace internal {
20template <typename XprType>
21struct traits<TensorLayoutSwapOp<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 = traits<XprType>::NumDimensions;
27 static constexpr int Layout = (traits<XprType>::Layout == ColMajor) ? RowMajor : ColMajor;
28 typedef typename XprTraits::PointerType PointerType;
29};
30
31template <typename XprType>
32struct eval<TensorLayoutSwapOp<XprType>, Eigen::Dense> {
33 typedef const TensorLayoutSwapOp<XprType>& type;
34};
35
36} // end namespace internal
37
60template <typename XprType>
61class TensorLayoutSwapOp : public TensorBase<TensorLayoutSwapOp<XprType>, WriteAccessors> {
62 public:
63 typedef TensorBase<TensorLayoutSwapOp<XprType>, WriteAccessors> Base;
64 typedef typename Eigen::internal::traits<TensorLayoutSwapOp>::Scalar Scalar;
65 typedef typename Eigen::NumTraits<Scalar>::Real RealScalar;
66 typedef std::remove_const_t<typename XprType::CoeffReturnType> CoeffReturnType;
67 typedef typename Eigen::internal::ref_selector<TensorLayoutSwapOp>::type Nested;
68 typedef typename Eigen::internal::traits<TensorLayoutSwapOp>::StorageKind StorageKind;
69 typedef typename Eigen::internal::traits<TensorLayoutSwapOp>::Index Index;
70
71 EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE TensorLayoutSwapOp(const XprType& expr) : m_xpr(expr) {}
72
73 EIGEN_DEVICE_FUNC const internal::remove_all_t<typename XprType::Nested>& expression() const { return m_xpr; }
74
75 EIGEN_INHERIT_ASSIGNMENT_OPERATORS(TensorLayoutSwapOp)
76 protected:
77 typename XprType::Nested m_xpr;
78};
79
80// Eval as rvalue
81template <typename ArgType, typename Device>
82struct TensorEvaluator<const TensorLayoutSwapOp<ArgType>, Device> {
83 typedef TensorLayoutSwapOp<ArgType> XprType;
84 typedef typename XprType::Index Index;
85 static constexpr int NumDims = internal::array_size<typename TensorEvaluator<ArgType, Device>::Dimensions>::value;
86 typedef DSizes<Index, NumDims> Dimensions;
87
88 static constexpr int Layout =
89 (TensorEvaluator<ArgType, Device>::Layout == static_cast<int>(ColMajor)) ? RowMajor : ColMajor;
90 enum {
91 IsAligned = TensorEvaluator<ArgType, Device>::IsAligned,
92 PacketAccess = TensorEvaluator<ArgType, Device>::PacketAccess,
93 // Layout swap is a no-op at the flat-memory level: serve blocks from the
94 // argument's raw data pointer when it has one, and otherwise forward the
95 // block request to the argument with reversed dimensions.
96 BlockAccess =
97 (TensorEvaluator<ArgType, Device>::RawAccess || TensorEvaluator<ArgType, Device>::BlockAccess) && NumDims > 0,
98 PreferBlockAccess = TensorEvaluator<ArgType, Device>::PreferBlockAccess,
99 CoordAccess = false, // to be implemented
100 RawAccess = TensorEvaluator<ArgType, Device>::RawAccess
101 };
102
103 // Blocks are forwarded to the argument only when it cannot hand out a flat
104 // buffer directly (the raw fast path below is cheaper).
105 static constexpr bool ForwardBlocksToArg =
106 TensorEvaluator<ArgType, Device>::BlockAccess && !TensorEvaluator<ArgType, Device>::RawAccess;
107 static constexpr int ArgLayout = TensorEvaluator<ArgType, Device>::Layout;
108
109 typedef typename XprType::Scalar Scalar;
110 typedef typename XprType::CoeffReturnType CoeffReturnType;
111 typedef typename PacketType<CoeffReturnType, Device>::type PacketReturnType;
112 typedef StorageMemory<CoeffReturnType, Device> Storage;
113 typedef typename Storage::Type EvaluatorPointerType;
114
115 typedef std::remove_const_t<Scalar> ScalarNoConst;
116
117 //===- Tensor block evaluation strategy (see TensorBlock.h) -------------===//
118 typedef internal::TensorBlockDescriptor<NumDims, Index> TensorBlockDesc;
119 typedef internal::TensorBlockScratchAllocator<Device> TensorBlockScratch;
120 typedef typename internal::TensorMaterializedBlock<ScalarNoConst, NumDims, Layout, Index> TensorBlock;
121 typedef typename TensorEvaluator<ArgType, Device>::TensorBlock ArgTensorBlock;
122 //===--------------------------------------------------------------------===//
123
124 EIGEN_STRONG_INLINE TensorEvaluator(const XprType& op, const Device& device) : m_impl(op.expression(), device) {
125 for (int i = 0; i < NumDims; ++i) {
126 m_dimensions[i] = m_impl.dimensions()[NumDims - 1 - i];
127 }
128 }
129
130 EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE const Dimensions& dimensions() const { return m_dimensions; }
131
132 EIGEN_STRONG_INLINE bool evalSubExprsIfNeeded(EvaluatorPointerType data) { return m_impl.evalSubExprsIfNeeded(data); }
133 EIGEN_STRONG_INLINE void cleanup() { m_impl.cleanup(); }
134
135 EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE CoeffReturnType coeff(Index index) const { return m_impl.coeff(index); }
136
137 template <int LoadMode>
138 EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE PacketReturnType packet(Index index) const {
139 return m_impl.template packet<LoadMode>(index);
140 }
141
142 EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE TensorOpCost costPerCoeff(bool vectorized) const {
143 return m_impl.costPerCoeff(vectorized);
144 }
145
146 EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE internal::TensorBlockResourceRequirements getResourceRequirements() const {
147 return getResourceRequirementsImpl(std::integral_constant<bool, ForwardBlocksToArg>());
148 }
149
150 EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE TensorBlock block(TensorBlockDesc& desc, TensorBlockScratch& scratch,
151 bool root_of_expr_ast = false) const {
152 return blockImpl(desc, scratch, root_of_expr_ast, std::integral_constant<bool, ForwardBlocksToArg>());
153 }
154
155 EIGEN_DEVICE_FUNC typename Storage::Type data() const { return constCast(m_impl.data()); }
156
157 const TensorEvaluator<ArgType, Device>& impl() const { return m_impl; }
158
159 protected:
160 // Sizes or strides of this expression in the argument's index order.
161 EIGEN_DEVICE_FUNC static EIGEN_STRONG_INLINE DSizes<Index, NumDims> reversed(const DSizes<Index, NumDims>& sizes) {
162 DSizes<Index, NumDims> result;
163 for (int i = 0; i < NumDims; ++i) result[i] = sizes[NumDims - 1 - i];
164 return result;
165 }
166
167 EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE internal::TensorBlockResourceRequirements getResourceRequirementsImpl(
168 std::true_type /*forward_to_arg*/) const {
169 return m_impl.getResourceRequirements();
170 }
171
172 EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE internal::TensorBlockResourceRequirements getResourceRequirementsImpl(
173 std::false_type /*forward_to_arg*/) const {
174 return internal::TensorBlockResourceRequirements::any();
175 }
176
177 // The argument owns a flat buffer this expression is a plain view of.
178 EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE TensorBlock blockImpl(TensorBlockDesc& desc, TensorBlockScratch& scratch,
179 bool /*root_of_expr_ast*/,
180 std::false_type /*forward_to_arg*/) const {
181 eigen_assert(m_impl.data() != nullptr);
182 return TensorBlock::materialize(m_impl.data(), m_dimensions, desc, scratch);
183 }
184
185 // Forward the block request to the argument: reversing the descriptor's
186 // dimensions maps this block exactly onto an argument block at the same
187 // flat offset, and the swapped layout makes the two flat buffers identical.
188 EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE TensorBlock blockImpl(TensorBlockDesc& desc, TensorBlockScratch& scratch,
189 bool root_of_expr_ast,
190 std::true_type /*forward_to_arg*/) const {
191 const DSizes<Index, NumDims> arg_dims = reversed(desc.dimensions());
192 TensorBlockDesc arg_desc(desc.offset(), arg_dims);
193
194 // A destination buffer describes flat memory, which the layout swap leaves
195 // alone: reversing its strides alongside the dimensions hands the argument
196 // the very same bytes. A strided destination carries no valid dense
197 // expression, so it is only passed on at the root of the expression tree,
198 // where the block is written once and never read back through expr().
199 typedef typename TensorBlockDesc::DestinationBuffer DestinationBuffer;
200 const bool strided_destination = desc.destination().kind() == DestinationBuffer::kStrided;
201 if (desc.destination().kind() == DestinationBuffer::kContiguous || (strided_destination && root_of_expr_ast)) {
202 arg_desc.template AddDestinationBuffer<ArgLayout>(desc.destination().template data<ScalarNoConst>(),
203 reversed(desc.destination().strides()));
204 }
205
206 ArgTensorBlock arg_block = m_impl.block(arg_desc, scratch, root_of_expr_ast);
207
208 if (arg_block.data() != NULL) {
209 // A materialized argument block already stores this block's values in
210 // this block's flat order; re-wrap the buffer with reversed dimensions.
211 const bool materialized_in_output = arg_block.kind() == internal::TensorBlockKind::kMaterializedInOutput;
212 if (materialized_in_output) desc.DropDestinationBuffer();
213 return TensorBlock(arg_block.kind(), arg_block.data(), desc.dimensions(),
214 /*valid_expr=*/!(materialized_in_output && strided_destination));
215 }
216
217 // A lazy argument block has no buffer to share: materialize it into this
218 // block's storage, evaluating in the argument's (flat-identical) layout.
219 // The storage strides carry whichever destination prepareStorage accepted.
220 typedef internal::TensorBlockAssignment<ScalarNoConst, NumDims, typename ArgTensorBlock::XprType, Index>
221 ArgBlockAssign;
222 typename TensorBlock::Storage storage =
223 TensorBlock::prepareStorage(desc, scratch, /*allow_strided_storage=*/root_of_expr_ast);
224 ArgBlockAssign::Run(ArgBlockAssign::target(arg_dims, reversed(storage.strides()), storage.data()),
225 arg_block.expr());
226 arg_block.cleanup();
227 return storage.AsTensorMaterializedBlock();
228 }
229
230 TensorEvaluator<ArgType, Device> m_impl;
231 Dimensions m_dimensions;
232};
233
234// Eval as lvalue
235template <typename ArgType, typename Device>
236struct TensorEvaluator<TensorLayoutSwapOp<ArgType>, Device>
237 : public TensorEvaluator<const TensorLayoutSwapOp<ArgType>, Device> {
238 typedef TensorEvaluator<const TensorLayoutSwapOp<ArgType>, Device> Base;
239 typedef TensorLayoutSwapOp<ArgType> XprType;
240
241 static constexpr int NumDims = Base::NumDims;
242 static constexpr int Layout = Base::Layout;
243 enum {
244 IsAligned = TensorEvaluator<ArgType, Device>::IsAligned,
245 PacketAccess = TensorEvaluator<ArgType, Device>::PacketAccess,
246 // Writing a block only needs the argument's flat buffer: layout swap does
247 // not touch flat memory, so the block is assigned straight into it. The
248 // argument cannot be forwarded to as it is on the read side, because
249 // TensorBlockAssignment takes the inner dimension from the block
250 // expression's layout but the strides from the target.
251 BlockAccess = TensorEvaluator<ArgType, Device>::RawAccess && NumDims > 0,
252 PreferBlockAccess = TensorEvaluator<ArgType, Device>::PreferBlockAccess,
253 CoordAccess = false // to be implemented
254 };
255
256 typedef typename XprType::Index Index;
257 typedef typename XprType::Scalar Scalar;
258 typedef typename XprType::CoeffReturnType CoeffReturnType;
259 typedef typename PacketType<CoeffReturnType, Device>::type PacketReturnType;
260
261 //===- Tensor block evaluation strategy (see TensorBlock.h) -------------===//
262 typedef typename Base::TensorBlockDesc TensorBlockDesc;
263 //===--------------------------------------------------------------------===//
264
265 EIGEN_STRONG_INLINE TensorEvaluator(const XprType& op, const Device& device) : Base(op, device) {}
266
267 EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE CoeffReturnType& coeffRef(Index index) const {
268 return this->m_impl.coeffRef(index);
269 }
270 template <int StoreMode>
271 EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE void writePacket(Index index, const PacketReturnType& x) const {
272 this->m_impl.template writePacket<StoreMode>(index, x);
273 }
274
275 template <typename TensorBlock>
276 EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE void writeBlock(const TensorBlockDesc& desc, const TensorBlock& block) {
277 eigen_assert(this->m_impl.data() != NULL);
278
279 // Dense strides of the swapped dimensions in this layout are exactly the
280 // argument's flat strides, so the block expression can be assigned
281 // directly into the argument's buffer at the block's flat offset.
282 typedef typename TensorBlock::XprType TensorBlockExpr;
283 typedef internal::TensorBlockAssignment<Scalar, NumDims, TensorBlockExpr, Index> TensorBlockAssign;
284
285 TensorBlockAssign::Run(TensorBlockAssign::target(desc.dimensions(), internal::strides<Layout>(this->dimensions()),
286 this->m_impl.data(), desc.offset()),
287 block.expr());
288 }
289};
290
291} // end namespace Eigen
292
293#endif // EIGEN_TENSOR_TENSOR_LAYOUT_SWAP_H
The tensor base class.
Definition TensorForwardDeclarations.h:69
WriteAccessors
Namespace containing all symbols from the Eigen library.
The tensor evaluator class.
Definition TensorEvaluator.h:47