Eigen-Contrib  5.0.1-dev+master
 
Loading...
Searching...
No Matches
TensorInflation.h
1// This file is part of Eigen, a lightweight C++ template library
2// for linear algebra.
3//
4// Copyright (C) 2015 Ke Yang <yangke@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_INFLATION_H
12#define EIGEN_TENSOR_TENSOR_INFLATION_H
13
14// IWYU pragma: private
15#include "./InternalHeaderCheck.h"
16
17namespace Eigen {
18
19namespace internal {
20template <typename Strides, typename XprType>
21struct traits<TensorInflationOp<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<TensorInflationOp<Strides, XprType>, Eigen::Dense> {
33 using type = const TensorInflationOp<Strides, XprType>&;
34};
35
36} // end namespace internal
37
43template <typename Strides, typename XprType>
44class TensorInflationOp : public TensorBase<TensorInflationOp<Strides, XprType>, ReadOnlyAccessors> {
45 public:
46 using Scalar = typename Eigen::internal::traits<TensorInflationOp>::Scalar;
47 using RealScalar = typename Eigen::NumTraits<Scalar>::Real;
48 using CoeffReturnType = typename XprType::CoeffReturnType;
49 using Nested = typename Eigen::internal::ref_selector<TensorInflationOp>::type;
50 using StorageKind = typename Eigen::internal::traits<TensorInflationOp>::StorageKind;
51 using Index = typename Eigen::internal::traits<TensorInflationOp>::Index;
52
53 EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE TensorInflationOp(const XprType& expr, const Strides& strides)
54 : m_xpr(expr), m_strides(strides) {}
55
56 EIGEN_DEVICE_FUNC const Strides& strides() const { return m_strides; }
57
58 EIGEN_DEVICE_FUNC const internal::remove_all_t<typename XprType::Nested>& expression() const { return m_xpr; }
59
60 protected:
61 typename XprType::Nested m_xpr;
62 const Strides m_strides;
63};
64
65// Eval as rvalue
66template <typename Strides, typename ArgType, typename Device>
67struct TensorEvaluator<const TensorInflationOp<Strides, ArgType>, Device> {
69 using Index = typename XprType::Index;
70 static constexpr int NumDims = internal::array_size<typename TensorEvaluator<ArgType, Device>::Dimensions>::value;
71 using Dimensions = DSizes<Index, NumDims>;
72 using Scalar = typename XprType::Scalar;
73 using CoeffReturnType = typename XprType::CoeffReturnType;
74 using PacketReturnType = typename PacketType<CoeffReturnType, Device>::type;
75 static constexpr int PacketSize = PacketType<CoeffReturnType, Device>::size;
76 using Storage = StorageMemory<CoeffReturnType, Device>;
77 using EvaluatorPointerType = typename Storage::Type;
78
79 static constexpr int Layout = TensorEvaluator<ArgType, Device>::Layout;
80 enum {
81 IsAligned = /*TensorEvaluator<ArgType, Device>::IsAligned*/ false,
82 PacketAccess = TensorEvaluator<ArgType, Device>::PacketAccess,
83 // block() reads the argument through coeff(), and under a ThreadPool the
84 // tiled executor shares this evaluator across concurrent block tasks, so
85 // the argument must be safe to read repeatedly and concurrently. Either bit
86 // establishes that: BlockAccess is what a nullary functor that carries
87 // state between calls clears (the built-in random generators are pure in
88 // seed and index and keep it), and RawAccess means coeff() is a plain
89 // buffer read. Requiring BlockAccess alone would needlessly exclude raw
90 // arguments whose scalar is not arithmetic, such as complex tensors.
91 BlockAccess =
93 // The coeff/packet path pays a div/mod walk plus a hole check per output
94 // scalar; the block path is a zero-fill plus a sparse copy of the stride
95 // lattice.
96 PreferBlockAccess = true,
97 CoordAccess = false, // to be implemented
98 RawAccess = false
99 };
100
101 //===- Tensor block evaluation strategy (see TensorBlock.h) -------------===//
102 using TensorBlockDesc = internal::TensorBlockDescriptor<NumDims, Index>;
103 using TensorBlockScratch = internal::TensorBlockScratchAllocator<Device>;
104 using TensorBlock = internal::TensorMaterializedBlock<CoeffReturnType, NumDims, Layout, Index>;
105 //===--------------------------------------------------------------------===//
106
107 EIGEN_STRONG_INLINE TensorEvaluator(const XprType& op, const Device& device)
108 : m_impl(op.expression(), device), m_strides(op.strides()), m_device(device) {
109 m_dimensions = m_impl.dimensions();
110 // Expand each dimension to the inflated dimension.
111 for (int i = 0; i < NumDims; ++i) {
112 m_dimensions[i] = m_dimensions[i] > 0 ? (m_dimensions[i] - 1) * op.strides()[i] + 1 : 0;
113 }
114
115 // Remember the strides for fast division.
116 for (int i = 0; i < NumDims; ++i) {
117 m_fastStrides[i] = internal::TensorIntDivisor<Index>(m_strides[i]);
118 }
119
120 const typename TensorEvaluator<ArgType, Device>::Dimensions& input_dims = m_impl.dimensions();
121 EIGEN_IF_CONSTEXPR (static_cast<int>(Layout) == static_cast<int>(ColMajor)) {
122 m_outputStrides[0] = 1;
123 m_inputStrides[0] = 1;
124 for (int i = 1; i < NumDims; ++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 }
128 } else { // RowMajor
129 m_outputStrides[NumDims - 1] = 1;
130 m_inputStrides[NumDims - 1] = 1;
131 for (int i = NumDims - 2; i >= 0; --i) {
132 m_outputStrides[i] = m_outputStrides[i + 1] * m_dimensions[i + 1];
133 m_inputStrides[i] = m_inputStrides[i + 1] * input_dims[i + 1];
134 }
135 }
136 }
137
138 EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE const Dimensions& dimensions() const { return m_dimensions; }
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 bool evalSubExprsIfNeeded(EvaluatorPointerType /*data*/) {
148 m_impl.evalSubExprsIfNeeded(nullptr);
149 return true;
150 }
151 EIGEN_STRONG_INLINE void cleanup() { m_impl.cleanup(); }
152
153 // Computes the input index given the output index. Returns true if the output
154 // index doesn't fall into a hole.
155 EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE bool getInputIndex(Index index, Index* inputIndex) const {
156 eigen_assert(index < dimensions().TotalSize());
157 *inputIndex = 0;
158 EIGEN_IF_CONSTEXPR (static_cast<int>(Layout) == static_cast<int>(ColMajor)) {
159 EIGEN_UNROLL_LOOP
160 for (int i = NumDims - 1; i > 0; --i) {
161 const Index idx = index / m_outputStrides[i];
162 if (idx != idx / m_fastStrides[i] * m_strides[i]) {
163 return false;
164 }
165 *inputIndex += idx / m_strides[i] * m_inputStrides[i];
166 index -= idx * m_outputStrides[i];
167 }
168 if (index != index / m_fastStrides[0] * m_strides[0]) {
169 return false;
170 }
171 *inputIndex += index / m_strides[0];
172 return true;
173 } else {
174 EIGEN_UNROLL_LOOP
175 for (int i = 0; i < NumDims - 1; ++i) {
176 const Index idx = index / m_outputStrides[i];
177 if (idx != idx / m_fastStrides[i] * m_strides[i]) {
178 return false;
179 }
180 *inputIndex += idx / m_strides[i] * m_inputStrides[i];
181 index -= idx * m_outputStrides[i];
182 }
183 if (index != index / m_fastStrides[NumDims - 1] * m_strides[NumDims - 1]) {
184 return false;
185 }
186 *inputIndex += index / m_strides[NumDims - 1];
187 }
188 return true;
189 }
190
191 EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE CoeffReturnType coeff(Index index) const {
192 Index inputIndex = 0;
193 if (getInputIndex(index, &inputIndex)) {
194 return m_impl.coeff(inputIndex);
195 } else {
196 return Scalar(0);
197 }
198 }
199
200 // TODO(yangke): optimize this function so that we can detect and produce
201 // all-zero packets
202 template <int LoadMode>
203 EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE PacketReturnType packet(Index index) const {
204 EIGEN_STATIC_ASSERT((PacketSize > 1), YOU_MADE_A_PROGRAMMING_MISTAKE)
205 eigen_assert(index + PacketSize - 1 < dimensions().TotalSize());
206
207 EIGEN_ALIGN_TO_BOUNDARY(internal::unpacket_traits<PacketReturnType>::alignment)
208 std::remove_const_t<CoeffReturnType> values[PacketSize];
209 EIGEN_UNROLL_LOOP
210 for (int i = 0; i < PacketSize; ++i) {
211 values[i] = coeff(index + i);
212 }
213 PacketReturnType rslt = internal::pload<PacketReturnType>(values);
214 return rslt;
215 }
216
217 EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE internal::TensorBlockResourceRequirements getResourceRequirements() const {
218 const size_t target_size = m_device.lastLevelCacheSize();
219 // One store per output coefficient for the zero fill, plus a
220 // lattice-density-weighted argument read and overwrite store, so that
221 // ThreadPool scheduling sees the true cost of expensive arguments.
222 const double density = latticeDensity();
223 const TensorOpCost cost_per_coeff =
224 density * m_impl.costPerCoeff(/*vectorized=*/false) +
225 TensorOpCost(/*bytes_loaded=*/0, /*bytes_stored=*/(1.0 + density) * sizeof(CoeffReturnType),
226 /*compute_cycles=*/0);
227 // withShapeAndSize rather than skewed(), because skewed() seeds a load and
228 // a store per coefficient that this model already accounts for.
229 return internal::TensorBlockResourceRequirements::withShapeAndSize<Scalar>(
230 internal::TensorBlockShapeType::kSkewedInnerDims, target_size, cost_per_coeff);
231 }
232
233 EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE TensorBlock block(TensorBlockDesc& desc, TensorBlockScratch& scratch,
234 bool /*root_of_expr_ast*/ = false) const {
235 constexpr bool is_col_major = static_cast<int>(Layout) == static_cast<int>(ColMajor);
236
237 // If one of the dimensions is zero, return empty block view.
238 if (desc.size() == 0) {
239 return TensorBlock(internal::TensorBlockKind::kView, nullptr, desc.dimensions());
240 }
241
242 // Everything outside the stride lattice is a hole, so zero-fill first and
243 // then copy the covered input values onto the lattice.
244 typename TensorBlock::Storage block_storage = TensorBlock::prepareStorage(desc, scratch);
245 CoeffReturnType* block_buffer = block_storage.data();
246
247 // Output coordinates of the block's corner.
248 array<Index, NumDims> coords;
249 extract_coordinates(desc.offset(), coords);
250
251 // First lattice point inside the block and the lattice extent, per dim.
252 const DSizes<Index, NumDims>& block_strides = block_storage.strides();
253 array<Index, NumDims> lattice_count;
254 Index dst_offset = 0;
255 Index src_offset = 0;
256 for (int i = 0; i < NumDims; ++i) {
257 const Index stride = m_strides[i];
258 const Index first_input = numext::div_ceil(coords[i], stride);
259 const Index first = first_input * stride; // output coordinate
260 const Index end = coords[i] + desc.dimension(i); // exclusive
261 if (first >= end) {
262 // No lattice point along this dimension: the block is all holes.
263 Map<ArrayX<CoeffReturnType>>(block_buffer, desc.size()).setZero();
264 return block_storage.AsTensorMaterializedBlock();
265 }
266 lattice_count[i] = numext::div_ceil(end - first, stride);
267 dst_offset += (first - coords[i]) * block_strides[i];
268 src_offset += first_input * m_inputStrides[i];
269 }
270
271 // The fill is pure waste when the lattice covers every coefficient, which
272 // is the whole block for identity striding.
273 bool dense = true;
274 for (int i = 0; i < NumDims; ++i) dense = dense && (lattice_count[i] == desc.dimension(i));
275 if (!dense) Map<ArrayX<CoeffReturnType>>(block_buffer, desc.size()).setZero();
276
277 // Iterate the lattice (dimensions ordered inner-most to outer-most).
278 array<BlockIteratorState, NumDims> it;
279 for (int i = 0; i < NumDims; ++i) {
280 const int dim = is_col_major ? i : NumDims - 1 - i;
281 const Index size = lattice_count[dim];
282 const Index dst_stride = block_strides[dim] * m_strides[dim];
283 const Index src_stride = m_inputStrides[dim];
284 it[i] = {/*size=*/size,
285 /*count=*/0,
286 /*dst_stride=*/dst_stride,
287 /*dst_span=*/dst_stride * (size - 1),
288 /*src_stride=*/src_stride,
289 /*src_span=*/src_stride * (size - 1)};
290 }
291
292 const Index inner_size = it[0].size;
293 const Index inner_dst_stride = it[0].dst_stride;
294 // m_inputStrides is 1 on the inner dimension in both layouts, so the
295 // argument is read as a contiguous run.
296 eigen_assert(it[0].src_stride == 1);
297 Index dst = dst_offset;
298 Index src = src_offset;
299 while (it[NumDims - 1].count < it[NumDims - 1].size) {
300 for (Index j = 0; j < inner_size; ++j) {
301 block_buffer[dst + j * inner_dst_stride] = m_impl.coeff(src + j);
302 }
303
304 EIGEN_IF_CONSTEXPR (NumDims == 1) break;
305
306 for (int i = 1; i < NumDims; ++i) {
307 if (++it[i].count < it[i].size) {
308 dst += it[i].dst_stride;
309 src += it[i].src_stride;
310 break;
311 }
312 if (i != NumDims - 1) it[i].count = 0;
313 dst -= it[i].dst_span;
314 src -= it[i].src_span;
315 }
316 }
317
318 return block_storage.AsTensorMaterializedBlock();
319 }
320
321 EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE TensorOpCost costPerCoeff(bool vectorized) const {
322 const double compute_cost = NumDims * (3 * TensorOpCost::DivCost<Index>() + 3 * TensorOpCost::MulCost<Index>() +
323 2 * TensorOpCost::AddCost<Index>());
324 if (m_dimensions.TotalSize() == 0) return TensorOpCost();
325 return m_impl.costPerCoeff(vectorized) +
326 TensorOpCost(sizeof(CoeffReturnType) * latticeDensity(), 0, compute_cost, vectorized, PacketSize);
327 }
328
329 EIGEN_DEVICE_FUNC EvaluatorPointerType data() const { return nullptr; }
330
331 protected:
332 // Fraction of output coefficients that fall on the stride lattice.
333 EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE double latticeDensity() const {
334 const double output_size = static_cast<double>(m_dimensions.TotalSize());
335 if (output_size == 0) return 0.0;
336 return static_cast<double>(internal::array_prod(m_impl.dimensions())) / output_size;
337 }
338
339 EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE void extract_coordinates(Index index, array<Index, NumDims>& coords) const {
340 EIGEN_IF_CONSTEXPR (static_cast<int>(Layout) == static_cast<int>(ColMajor)) {
341 for (int i = NumDims - 1; i > 0; --i) {
342 const Index idx = index / m_outputStrides[i];
343 index -= idx * m_outputStrides[i];
344 coords[i] = idx;
345 }
346 coords[0] = index;
347 } else {
348 for (int i = 0; i < NumDims - 1; ++i) {
349 const Index idx = index / m_outputStrides[i];
350 index -= idx * m_outputStrides[i];
351 coords[i] = idx;
352 }
353 coords[NumDims - 1] = index;
354 }
355 }
356
357 Dimensions m_dimensions;
358 array<Index, NumDims> m_outputStrides;
359 array<Index, NumDims> m_inputStrides;
360 TensorEvaluator<ArgType, Device> m_impl;
361 const Strides m_strides;
362 array<internal::TensorIntDivisor<Index>, NumDims> m_fastStrides;
363 const Device EIGEN_DEVICE_REF m_device;
364
365 private:
366 struct BlockIteratorState {
367 Index size;
368 Index count;
369 Index dst_stride;
370 Index dst_span;
371 Index src_stride;
372 Index src_span;
373 };
374};
375
376} // end namespace Eigen
377
378#endif // EIGEN_TENSOR_TENSOR_INFLATION_H
The tensor base class.
Definition TensorForwardDeclarations.h:69
Tensor inflation class.
Definition TensorInflation.h:44
Namespace containing all symbols from the Eigen library.
The tensor evaluator class.
Definition TensorEvaluator.h:47