Eigen-Contrib  5.0.1-dev+master
 
Loading...
Searching...
No Matches
TensorStriding.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_STRIDING_H
12#define EIGEN_TENSOR_TENSOR_STRIDING_H
13
14// IWYU pragma: private
15#include "./InternalHeaderCheck.h"
16
17namespace Eigen {
18
19namespace internal {
20template <typename Strides, typename XprType>
21struct traits<TensorStridingOp<Strides, 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 Strides, typename XprType>
32struct eval<TensorStridingOp<Strides, XprType>, Eigen::Dense> {
33 using type = const TensorStridingOp<Strides, XprType> EIGEN_DEVICE_REF;
34};
35
36} // end namespace internal
37
43template <typename Strides, typename XprType>
44class TensorStridingOp : public TensorBase<TensorStridingOp<Strides, XprType> > {
45 public:
47 using Scalar = typename Eigen::internal::traits<TensorStridingOp>::Scalar;
48 using RealScalar = typename Eigen::NumTraits<Scalar>::Real;
49 using CoeffReturnType = typename XprType::CoeffReturnType;
50 using Nested = typename Eigen::internal::ref_selector<TensorStridingOp>::type;
51 using StorageKind = typename Eigen::internal::traits<TensorStridingOp>::StorageKind;
52 using Index = typename Eigen::internal::traits<TensorStridingOp>::Index;
53
54 EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE TensorStridingOp(const XprType& expr, const Strides& dims)
55 : m_xpr(expr), m_dims(dims) {}
56
57 EIGEN_DEVICE_FUNC const Strides& strides() const { return m_dims; }
58
59 EIGEN_DEVICE_FUNC const internal::remove_all_t<typename XprType::Nested>& expression() const { return m_xpr; }
60
61 EIGEN_INHERIT_ASSIGNMENT_OPERATORS(TensorStridingOp)
62
63 protected:
64 typename XprType::Nested m_xpr;
65 const Strides m_dims;
66};
67
68// Eval as rvalue
69template <typename Strides, typename ArgType, typename Device>
70struct TensorEvaluator<const TensorStridingOp<Strides, ArgType>, Device> {
72 using Index = typename XprType::Index;
73 static constexpr int NumDims = internal::array_size<typename TensorEvaluator<ArgType, Device>::Dimensions>::value;
74 using Dimensions = DSizes<Index, NumDims>;
75 using Scalar = typename XprType::Scalar;
76 using CoeffReturnType = typename XprType::CoeffReturnType;
77 using PacketReturnType = typename PacketType<CoeffReturnType, Device>::type;
78 static constexpr int PacketSize = PacketType<CoeffReturnType, Device>::size;
79 using Storage = StorageMemory<CoeffReturnType, Device>;
80 using EvaluatorPointerType = typename Storage::Type;
81
82 static constexpr int Layout = TensorEvaluator<ArgType, Device>::Layout;
83 // Inner-most dimension in storage order: the one a packet runs along.
84 static constexpr int kInnerDim = (static_cast<int>(Layout) == static_cast<int>(ColMajor)) ? 0 : NumDims - 1;
85 // Tag selecting whether the argument can be asked for whole packets.
86 using ImplHasPacket = std::integral_constant<bool, TensorEvaluator<ArgType, Device>::PacketAccess>;
87 enum {
88 IsAligned = false,
89 // Packets are assembled from inner runs even when the nested evaluator
90 // only exposes coefficient access.
91 PacketAccess = (PacketSize > 1),
92 BlockAccess = false,
94 CoordAccess = false, // to be implemented
95 RawAccess = false
96 };
97
98 //===- Tensor block evaluation strategy (see TensorBlock.h) -------------===//
99 using TensorBlock = internal::TensorBlockNotImplemented;
100 //===--------------------------------------------------------------------===//
101
102 EIGEN_STRONG_INLINE TensorEvaluator(const XprType& op, const Device& device) : m_impl(op.expression(), device) {
103 m_dimensions = m_impl.dimensions();
104 m_is_identity = true;
105 for (int i = 0; i < NumDims; ++i) {
106 eigen_assert(op.strides()[i] > 0);
107 m_dimensions[i] = numext::div_ceil<Index>(m_dimensions[i], op.strides()[i]);
108 if (op.strides()[i] != 1) m_is_identity = false;
109 }
110
111 const typename TensorEvaluator<ArgType, Device>::Dimensions& input_dims = m_impl.dimensions();
112 EIGEN_IF_CONSTEXPR (static_cast<int>(Layout) == static_cast<int>(ColMajor)) {
113 m_outputStrides[0] = 1;
114 m_inputStrides[0] = 1;
115 for (int i = 1; i < NumDims; ++i) {
116 m_outputStrides[i] = m_outputStrides[i - 1] * m_dimensions[i - 1];
117 m_inputStrides[i] = m_inputStrides[i - 1] * input_dims[i - 1];
118 m_inputStrides[i - 1] *= op.strides()[i - 1];
119 }
120 m_inputStrides[NumDims - 1] *= op.strides()[NumDims - 1];
121 } else { // RowMajor
122 m_outputStrides[NumDims - 1] = 1;
123 m_inputStrides[NumDims - 1] = 1;
124 for (int i = NumDims - 2; i >= 0; --i) {
125 m_outputStrides[i] = m_outputStrides[i + 1] * m_dimensions[i + 1];
126 m_inputStrides[i] = m_inputStrides[i + 1] * input_dims[i + 1];
127 m_inputStrides[i + 1] *= op.strides()[i + 1];
128 }
129 m_inputStrides[0] *= op.strides()[0];
130 }
131 }
132
133 EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE const Dimensions& dimensions() const { return m_dimensions; }
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 bool evalSubExprsIfNeeded(EvaluatorPointerType /*data*/) {
143 m_impl.evalSubExprsIfNeeded(nullptr);
144 return true;
145 }
146 EIGEN_STRONG_INLINE void cleanup() { m_impl.cleanup(); }
147
148 EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE CoeffReturnType coeff(Index index) const {
149 if (m_is_identity) {
150 return m_impl.coeff(index);
151 }
152 return m_impl.coeff(srcCoeff(index));
153 }
154
155 // Reads PacketSize coefficients of the argument starting at `base` and
156 // stepping by `inner_stride`. Callers guarantee those lanes lie in a single
157 // inner-most run, which is what makes the input indices an arithmetic
158 // progression and lets the index mapping be computed once per packet
159 // instead of once per coefficient. The argument's packet() must not be
160 // instantiated when it has no packet access, hence the tag-dispatched pair
161 // rather than a plain branch (C++14 has no if constexpr).
162 EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE PacketReturnType loadInnerRun(Index base, Index inner_stride,
163 std::false_type) const {
164 EIGEN_ALIGN_TO_BOUNDARY(internal::unpacket_traits<PacketReturnType>::alignment)
165 std::remove_const_t<CoeffReturnType> values[PacketSize];
166 EIGEN_UNROLL_LOOP
167 for (int i = 0; i < PacketSize; ++i) {
168 values[i] = m_impl.coeff(base + i * inner_stride);
169 }
170 return internal::pload<PacketReturnType>(values);
171 }
172
173 EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE PacketReturnType loadInnerRun(Index base, Index inner_stride,
174 std::true_type) const {
175 if (inner_stride == 1) return m_impl.template packet<Unaligned>(base);
176 return loadInnerRun(base, inner_stride, std::false_type());
177 }
178
179 template <int LoadMode>
180 EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE PacketReturnType packet(Index index) const {
181 eigen_assert(index + PacketSize - 1 < dimensions().TotalSize());
182 // Identity striding is just the inner-run case with step one: srcCoeff is
183 // then the identity and the inner input stride is 1.
184 if (m_is_identity) return loadInnerRun(index, 1, ImplHasPacket());
185 Index base;
186 if (packetStaysInInnerRun(index, base)) return loadInnerRun(base, m_inputStrides[kInnerDim], ImplHasPacket());
187
188 // The packet crosses an inner-run boundary, so every lane needs its own
189 // index mapping.
190 EIGEN_ALIGN_TO_BOUNDARY(internal::unpacket_traits<PacketReturnType>::alignment)
191 std::remove_const_t<CoeffReturnType> values[PacketSize];
192 EIGEN_UNROLL_LOOP
193 for (int i = 0; i < PacketSize; ++i) {
194 values[i] = coeff(index + i);
195 }
196 return internal::pload<PacketReturnType>(values);
197 }
198
199 EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE TensorOpCost costPerCoeff(bool vectorized) const {
200 const double compute_cost = m_is_identity
201 ? TensorOpCost::AddCost<Index>()
202 : (NumDims - 1) * (TensorOpCost::AddCost<Index>() + TensorOpCost::MulCost<Index>() +
203 TensorOpCost::DivCost<Index>()) +
204 TensorOpCost::MulCost<Index>();
205 // The nested evaluator is served whole packets only when it has packet
206 // access at all, and the inner runs are packet-aligned with an unstrided
207 // inner dimension; everywhere else it is driven coefficient by coefficient
208 // and must be charged at scalar rates. Likewise the once-per-packet index
209 // mapping amortizes only while packets stay inside one inner run; the
210 // cross-run fallback recomputes it per lane. Identity striding satisfies
211 // both conditions, so it needs no special case here.
212 const bool packets_stay_in_inner =
213 m_is_identity || (m_dimensions[kInnerDim] > 0 && m_dimensions[kInnerDim] % PacketSize == 0);
214 const bool packetizes_arg =
215 TensorEvaluator<ArgType, Device>::PacketAccess && packets_stay_in_inner && m_inputStrides[kInnerDim] == 1;
216 return m_impl.costPerCoeff(vectorized && packetizes_arg) +
217 TensorOpCost(0, 0, compute_cost, vectorized && packets_stay_in_inner, PacketSize);
218 }
219
220 EIGEN_DEVICE_FUNC typename Storage::Type data() const { return nullptr; }
221
222 protected:
223 // Computes the input index of output index `index` and, as a by-product of
224 // the same walk, the output's inner-dimension coordinate. The packet paths
225 // use the latter to test whether a whole packet stays inside one inner-most
226 // run without spending an extra division on it.
227 EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE Index srcCoeffInner(Index index, Index& inner_pos) const {
228 Index inputIndex = 0;
229 EIGEN_IF_CONSTEXPR (static_cast<int>(Layout) == static_cast<int>(ColMajor)) {
230 EIGEN_UNROLL_LOOP
231 for (int i = NumDims - 1; i > 0; --i) {
232 const Index idx = index / m_outputStrides[i];
233 inputIndex += idx * m_inputStrides[i];
234 index -= idx * m_outputStrides[i];
235 }
236 inner_pos = index;
237 inputIndex += index * m_inputStrides[0];
238 } else { // RowMajor
239 EIGEN_UNROLL_LOOP
240 for (int i = 0; i < NumDims - 1; ++i) {
241 const Index idx = index / m_outputStrides[i];
242 inputIndex += idx * m_inputStrides[i];
243 index -= idx * m_outputStrides[i];
244 }
245 inner_pos = index;
246 inputIndex += index * m_inputStrides[NumDims - 1];
247 }
248 return inputIndex;
249 }
250
251 EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE Index srcCoeff(Index index) const {
252 Index inner_pos;
253 return srcCoeffInner(index, inner_pos);
254 }
255
256 // True when the whole packet at output `index` stays inside one inner-most
257 // run; sets `base` to the input index of its first lane either way.
258 EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE bool packetStaysInInnerRun(Index index, Index& base) const {
259 Index inner_pos;
260 base = srcCoeffInner(index, inner_pos);
261 return inner_pos + PacketSize <= m_dimensions[kInnerDim];
262 }
263
264 Dimensions m_dimensions;
265 bool m_is_identity;
266 array<Index, NumDims> m_outputStrides;
267 array<Index, NumDims> m_inputStrides;
268 TensorEvaluator<ArgType, Device> m_impl;
269};
270
271// Eval as lvalue
272template <typename Strides, typename ArgType, typename Device>
273struct TensorEvaluator<TensorStridingOp<Strides, ArgType>, Device>
274 : public TensorEvaluator<const TensorStridingOp<Strides, ArgType>, Device> {
275 using XprType = TensorStridingOp<Strides, ArgType>;
276 using Base = TensorEvaluator<const XprType, Device>;
277 static constexpr int NumDims = internal::array_size<typename TensorEvaluator<ArgType, Device>::Dimensions>::value;
278
279 using Index = typename XprType::Index;
280 using Scalar = typename XprType::Scalar;
281 using CoeffReturnType = typename XprType::CoeffReturnType;
282 using PacketReturnType = typename PacketType<CoeffReturnType, Device>::type;
283 static constexpr int PacketSize = PacketType<CoeffReturnType, Device>::size;
284 static constexpr int Layout = TensorEvaluator<ArgType, Device>::Layout;
285 enum {
286 IsAligned = false,
287 // Packets are scattered into inner runs even when the nested evaluator
288 // only exposes coefficient access.
289 PacketAccess = Base::PacketAccess,
290 PreferBlockAccess = false,
291 CoordAccess = false, // to be implemented
292 RawAccess = false
293 };
294
295 EIGEN_STRONG_INLINE TensorEvaluator(const XprType& op, const Device& device) : Base(op, device) {}
296
297 EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE Scalar& coeffRef(Index index) const {
298 if (this->m_is_identity) return this->m_impl.coeffRef(index);
299 return this->m_impl.coeffRef(this->srcCoeff(index));
300 }
301
302 // Mirror of the rvalue loadInnerRun: scatters a packet across PacketSize
303 // coefficients starting at `base` and stepping by `inner_stride`.
304 EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE void storeInnerRun(Index base, Index inner_stride, const PacketReturnType& x,
305 std::false_type) const {
306 EIGEN_ALIGN_TO_BOUNDARY(internal::unpacket_traits<PacketReturnType>::alignment) Scalar values[PacketSize];
307 internal::pstore<Scalar, PacketReturnType>(values, x);
308 EIGEN_UNROLL_LOOP
309 for (int i = 0; i < PacketSize; ++i) {
310 this->m_impl.coeffRef(base + i * inner_stride) = values[i];
311 }
312 }
313
314 EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE void storeInnerRun(Index base, Index inner_stride, const PacketReturnType& x,
315 std::true_type) const {
316 if (inner_stride == 1) {
317 this->m_impl.template writePacket<Unaligned>(base, x);
318 return;
319 }
320 storeInnerRun(base, inner_stride, x, std::false_type());
321 }
322
323 template <int StoreMode>
324 EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE void writePacket(Index index, const PacketReturnType& x) const {
325 eigen_assert(index + PacketSize - 1 < this->dimensions().TotalSize());
326 using ImplHasPacket = typename Base::ImplHasPacket;
327 if (this->m_is_identity) {
328 storeInnerRun(index, 1, x, ImplHasPacket());
329 return;
330 }
331 Index base;
332 if (this->packetStaysInInnerRun(index, base)) {
333 storeInnerRun(base, this->m_inputStrides[Base::kInnerDim], x, ImplHasPacket());
334 return;
335 }
336
337 // The packet crosses an inner-run boundary, so every lane needs its own
338 // index mapping.
339 EIGEN_ALIGN_TO_BOUNDARY(internal::unpacket_traits<PacketReturnType>::alignment) Scalar values[PacketSize];
340 internal::pstore<Scalar, PacketReturnType>(values, x);
341 EIGEN_UNROLL_LOOP
342 for (int i = 0; i < PacketSize; ++i) {
343 this->coeffRef(index + i) = values[i];
344 }
345 }
346};
347
348} // end namespace Eigen
349
350#endif // EIGEN_TENSOR_TENSOR_STRIDING_H
The tensor base class.
Definition TensorForwardDeclarations.h:69
Tensor striding class.
Definition TensorStriding.h:44
Namespace containing all symbols from the Eigen library.
The tensor evaluator class.
Definition TensorEvaluator.h:47