Eigen-Contrib  5.0.1-dev+master
 
Loading...
Searching...
No Matches
TensorPatch.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_PATCH_H
12#define EIGEN_TENSOR_TENSOR_PATCH_H
13
14// IWYU pragma: private
15#include "./InternalHeaderCheck.h"
16
17namespace Eigen {
18
19namespace internal {
20template <typename PatchDim, typename XprType>
21struct traits<TensorPatchOp<PatchDim, XprType> > : 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 + 1;
27 static constexpr int Layout = XprTraits::Layout;
28 using PointerType = typename XprTraits::PointerType;
29};
30
31template <typename PatchDim, typename XprType>
32struct eval<TensorPatchOp<PatchDim, XprType>, Eigen::Dense> {
33 using type = const TensorPatchOp<PatchDim, XprType>&;
34};
35
36} // end namespace internal
37
43template <typename PatchDim, typename XprType>
44class TensorPatchOp : public TensorBase<TensorPatchOp<PatchDim, XprType>, ReadOnlyAccessors> {
45 public:
46 using Scalar = typename Eigen::internal::traits<TensorPatchOp>::Scalar;
47 using RealScalar = typename Eigen::NumTraits<Scalar>::Real;
48 using CoeffReturnType = typename XprType::CoeffReturnType;
49 using Nested = typename Eigen::internal::ref_selector<TensorPatchOp>::type;
50 using StorageKind = typename Eigen::internal::traits<TensorPatchOp>::StorageKind;
51 using Index = typename Eigen::internal::traits<TensorPatchOp>::Index;
52
53 EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE TensorPatchOp(const XprType& expr, const PatchDim& patch_dims)
54 : m_xpr(expr), m_patch_dims(patch_dims) {}
55
56 EIGEN_DEVICE_FUNC const PatchDim& patch_dims() const { return m_patch_dims; }
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 PatchDim m_patch_dims;
63};
64
65// Eval as rvalue
66template <typename PatchDim, typename ArgType, typename Device>
67struct TensorEvaluator<const TensorPatchOp<PatchDim, ArgType>, Device> {
69 using Index = typename XprType::Index;
70 static constexpr int NumDims = internal::array_size<typename TensorEvaluator<ArgType, Device>::Dimensions>::value + 1;
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 = false,
82 PacketAccess = TensorEvaluator<ArgType, Device>::PacketAccess,
83 // block() reads the argument one coefficient at a time through coeff() --
84 // the contract the scalar executors already rely on for every evaluator --
85 // so it requires no capability bit from the argument (same as
86 // TensorReverse).
87 BlockAccess = NumDims > 1,
88 // The coeff/packet path pays a div/mod cascade per element; the block
89 // path copies whole in-bounds boxes patch by patch.
90 PreferBlockAccess = true,
91 CoordAccess = false,
92 RawAccess = false
93 };
94
95 //===- Tensor block evaluation strategy (see TensorBlock.h) -------------===//
96 using TensorBlockDesc = internal::TensorBlockDescriptor<NumDims, Index>;
97 using TensorBlockScratch = internal::TensorBlockScratchAllocator<Device>;
98 using TensorBlock = typename internal::TensorMaterializedBlock<CoeffReturnType, NumDims, Layout, Index>;
99 //===--------------------------------------------------------------------===//
100
101 EIGEN_STRONG_INLINE TensorEvaluator(const XprType& op, const Device& device)
102 : m_impl(op.expression(), device), m_device(device) {
103 Index num_patches = 1;
104 const typename TensorEvaluator<ArgType, Device>::Dimensions& input_dims = m_impl.dimensions();
105 const PatchDim& patch_dims = op.patch_dims();
106 EIGEN_IF_CONSTEXPR (static_cast<int>(Layout) == static_cast<int>(ColMajor)) {
107 for (int i = 0; i < NumDims - 1; ++i) {
108 m_dimensions[i] = patch_dims[i];
109 num_patches *= (input_dims[i] - patch_dims[i] + 1);
110 }
111 m_dimensions[NumDims - 1] = num_patches;
112
113 m_inputStrides[0] = 1;
114 m_patchStrides[0] = 1;
115 for (int i = 1; i < NumDims - 1; ++i) {
116 m_inputStrides[i] = m_inputStrides[i - 1] * input_dims[i - 1];
117 m_patchStrides[i] = m_patchStrides[i - 1] * (input_dims[i - 1] - patch_dims[i - 1] + 1);
118 }
119 m_outputStrides[0] = 1;
120 for (int i = 1; i < NumDims; ++i) {
121 m_outputStrides[i] = m_outputStrides[i - 1] * m_dimensions[i - 1];
122 }
123 } else {
124 for (int i = 0; i < NumDims - 1; ++i) {
125 m_dimensions[i + 1] = patch_dims[i];
126 num_patches *= (input_dims[i] - patch_dims[i] + 1);
127 }
128 m_dimensions[0] = num_patches;
129
130 m_inputStrides[NumDims - 2] = 1;
131 m_patchStrides[NumDims - 2] = 1;
132 for (int i = NumDims - 3; i >= 0; --i) {
133 m_inputStrides[i] = m_inputStrides[i + 1] * input_dims[i + 1];
134 m_patchStrides[i] = m_patchStrides[i + 1] * (input_dims[i + 1] - patch_dims[i + 1] + 1);
135 }
136 m_outputStrides[NumDims - 1] = 1;
137 for (int i = NumDims - 2; i >= 0; --i) {
138 m_outputStrides[i] = m_outputStrides[i + 1] * m_dimensions[i + 1];
139 }
140 }
141 }
142
143 EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE const Dimensions& dimensions() const { return m_dimensions; }
144
145#ifdef EIGEN_USE_THREADS
146 template <typename EvalSubExprsCallback>
147 EIGEN_STRONG_INLINE void evalSubExprsIfNeededAsync(EvaluatorPointerType, EvalSubExprsCallback done) {
148 m_impl.evalSubExprsIfNeededAsync(nullptr, [done](bool) { done(true); });
149 }
150#endif // EIGEN_USE_THREADS
151
152 EIGEN_STRONG_INLINE bool evalSubExprsIfNeeded(EvaluatorPointerType /*data*/) {
153 m_impl.evalSubExprsIfNeeded(nullptr);
154 return true;
155 }
156
157 EIGEN_STRONG_INLINE void cleanup() { m_impl.cleanup(); }
158
159 EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE CoeffReturnType coeff(Index index) const {
160 Index output_stride_index = (static_cast<int>(Layout) == static_cast<int>(ColMajor)) ? NumDims - 1 : 0;
161 // Find the location of the first element of the patch.
162 Index patchIndex = index / m_outputStrides[output_stride_index];
163 // Find the offset of the element wrt the location of the first element.
164 Index patchOffset = index - patchIndex * m_outputStrides[output_stride_index];
165 Index inputIndex = 0;
166 EIGEN_IF_CONSTEXPR (static_cast<int>(Layout) == static_cast<int>(ColMajor)) {
167 EIGEN_UNROLL_LOOP
168 for (int i = NumDims - 2; i > 0; --i) {
169 const Index patchIdx = patchIndex / m_patchStrides[i];
170 patchIndex -= patchIdx * m_patchStrides[i];
171 const Index offsetIdx = patchOffset / m_outputStrides[i];
172 patchOffset -= offsetIdx * m_outputStrides[i];
173 inputIndex += (patchIdx + offsetIdx) * m_inputStrides[i];
174 }
175 } else {
176 EIGEN_UNROLL_LOOP
177 for (int i = 0; i < NumDims - 2; ++i) {
178 const Index patchIdx = patchIndex / m_patchStrides[i];
179 patchIndex -= patchIdx * m_patchStrides[i];
180 const Index offsetIdx = patchOffset / m_outputStrides[i + 1];
181 patchOffset -= offsetIdx * m_outputStrides[i + 1];
182 inputIndex += (patchIdx + offsetIdx) * m_inputStrides[i];
183 }
184 }
185 inputIndex += (patchIndex + patchOffset);
186 return m_impl.coeff(inputIndex);
187 }
188
189 template <int LoadMode>
190 EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE PacketReturnType packet(Index index) const {
191 eigen_assert(index + PacketSize - 1 < dimensions().TotalSize());
192
193 // Same index decomposition as coeff(). On exit patchOffset == index % inner_size, because the last reduction is
194 // modulo the stride of the inner patch dimension (m_outputStrides[1] in ColMajor, [NumDims - 2] in RowMajor, or
195 // the initial modulus itself when NumDims == 2).
196 Index output_stride_index = (static_cast<int>(Layout) == static_cast<int>(ColMajor)) ? NumDims - 1 : 0;
197 Index patchIndex = index / m_outputStrides[output_stride_index];
198 Index patchOffset = index - patchIndex * m_outputStrides[output_stride_index];
199 Index inputIndex = 0;
200 EIGEN_IF_CONSTEXPR (static_cast<int>(Layout) == static_cast<int>(ColMajor)) {
201 EIGEN_UNROLL_LOOP
202 for (int i = NumDims - 2; i > 0; --i) {
203 const Index patchIdx = patchIndex / m_patchStrides[i];
204 patchIndex -= patchIdx * m_patchStrides[i];
205 const Index offsetIdx = patchOffset / m_outputStrides[i];
206 patchOffset -= offsetIdx * m_outputStrides[i];
207 inputIndex += (patchIdx + offsetIdx) * m_inputStrides[i];
208 }
209 } else {
210 EIGEN_UNROLL_LOOP
211 for (int i = 0; i < NumDims - 2; ++i) {
212 const Index patchIdx = patchIndex / m_patchStrides[i];
213 patchIndex -= patchIdx * m_patchStrides[i];
214 const Index offsetIdx = patchOffset / m_outputStrides[i + 1];
215 patchOffset -= offsetIdx * m_outputStrides[i + 1];
216 inputIndex += (patchIdx + offsetIdx) * m_inputStrides[i];
217 }
218 }
219 inputIndex += (patchIndex + patchOffset);
220
221 // The input is contiguous only along the inner patch dimension; a packet that crosses into the next patch row
222 // is gathered, even if its first and last coefficients happen to be PacketSize - 1 apart.
223 const Index inner_size = m_dimensions[static_cast<int>(Layout) == static_cast<int>(ColMajor) ? 0 : NumDims - 1];
224 if (patchOffset + PacketSize <= inner_size) {
225 return m_impl.template packet<Unaligned>(inputIndex);
226 } else {
227 EIGEN_ALIGN_TO_BOUNDARY(internal::unpacket_traits<PacketReturnType>::alignment)
228 CoeffReturnType values[PacketSize];
229 values[0] = m_impl.coeff(inputIndex);
230 EIGEN_UNROLL_LOOP
231 for (int i = 1; i < PacketSize; ++i) {
232 values[i] = coeff(index + i);
233 }
234 return internal::pload<PacketReturnType>(values);
235 }
236 }
237
238 EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE internal::TensorBlockResourceRequirements getResourceRequirements() const {
239 const size_t target_size = m_device.firstLevelCacheSize();
240 // Every output coefficient is read once from the argument and stored
241 // once. Pass the full cost explicitly rather than adding to skewed()'s
242 // default load+store seed, which would double-count the baseline byte
243 // traffic and halve the tile size.
244 const TensorOpCost cost_per_coeff =
245 m_impl.costPerCoeff(/*vectorized=*/false) + TensorOpCost(0, sizeof(CoeffReturnType), 0);
246 return internal::TensorBlockResourceRequirements::withShapeAndSize<Scalar>(
247 internal::TensorBlockShapeType::kSkewedInnerDims, target_size, cost_per_coeff);
248 }
249
250 EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE TensorBlock block(TensorBlockDesc& desc, TensorBlockScratch& scratch,
251 bool /*root_of_expr_ast*/ = false) const {
252 constexpr bool is_col_major = static_cast<int>(Layout) == static_cast<int>(ColMajor);
253
254 if (desc.size() == 0) {
255 return TensorBlock(internal::TensorBlockKind::kView, nullptr, desc.dimensions());
256 }
257
258 typename TensorBlock::Storage block_storage = TensorBlock::prepareStorage(desc, scratch);
259 CoeffReturnType* block_buffer = block_storage.data();
260
261 // Output coordinates of the block's corner.
262 array<Index, NumDims> coords;
263 Index remaining = desc.offset();
264 EIGEN_IF_CONSTEXPR (is_col_major) {
265 for (int i = NumDims - 1; i > 0; --i) {
266 coords[i] = remaining / m_outputStrides[i];
267 remaining -= coords[i] * m_outputStrides[i];
268 }
269 coords[0] = remaining;
270 } else {
271 for (int i = 0; i < NumDims - 1; ++i) {
272 coords[i] = remaining / m_outputStrides[i];
273 remaining -= coords[i] * m_outputStrides[i];
274 }
275 coords[NumDims - 1] = remaining;
276 }
277
278 const int patch_dim = is_col_major ? NumDims - 1 : 0;
279 const int inner_dim = is_col_major ? 0 : NumDims - 1;
280
281 const Index num_patches_in_block = desc.dimension(patch_dim);
282 // The input's inner-most stride is 1 by construction, so the inner run is
283 // contiguous on both sides.
284 const Index inner_size = desc.dimension(inner_dim);
285
286 // The within-patch dimensions between the inner-most one and the patch
287 // index, ordered inner-most to outer-most, plus the input offset the
288 // block's corner contributes on every within-patch dimension.
289 array<Index, NumDims> mid_sizes;
290 array<Index, NumDims> mid_src_stride;
291 array<Index, NumDims> mid_count;
292 int num_mid = 0;
293 Index src_corner = 0;
294 for (int k = 0; k < NumDims - 1; ++k) {
295 const int d = is_col_major ? k : NumDims - 1 - k; // output dimension
296 const int in_d = is_col_major ? d : d - 1; // input-strides index
297 src_corner += coords[d] * m_inputStrides[in_d];
298 if (k > 0) {
299 mid_sizes[num_mid] = desc.dimension(d);
300 mid_src_stride[num_mid] = m_inputStrides[in_d];
301 ++num_mid;
302 }
303 }
304
305 // The loop nest below visits the block in exactly its memory order (the
306 // storage returned by prepareStorage() is dense with the block's own
307 // layout-order strides), so the destination is one running cursor.
308 Index dst = 0;
309 for (Index p = 0; p < num_patches_in_block; ++p) {
310 // Input offset of this patch's first element.
311 Index patch_index = coords[patch_dim] + p;
312 Index src_patch = 0;
313 EIGEN_IF_CONSTEXPR (is_col_major) {
314 for (int i = NumDims - 2; i > 0; --i) {
315 const Index idx = patch_index / m_patchStrides[i];
316 patch_index -= idx * m_patchStrides[i];
317 src_patch += idx * m_inputStrides[i];
318 }
319 } else {
320 for (int i = 0; i < NumDims - 2; ++i) {
321 const Index idx = patch_index / m_patchStrides[i];
322 patch_index -= idx * m_patchStrides[i];
323 src_patch += idx * m_inputStrides[i];
324 }
325 }
326 src_patch += patch_index;
327
328 Index src = src_patch + src_corner;
329 for (int k = 0; k < num_mid; ++k) mid_count[k] = 0;
330 for (;;) {
331 for (Index j = 0; j < inner_size; ++j) {
332 block_buffer[dst + j] = m_impl.coeff(src + j);
333 }
334 dst += inner_size;
335 int k = 0;
336 for (; k < num_mid; ++k) {
337 if (++mid_count[k] < mid_sizes[k]) {
338 src += mid_src_stride[k];
339 break;
340 }
341 mid_count[k] = 0;
342 src -= mid_src_stride[k] * (mid_sizes[k] - 1);
343 }
344 if (k == num_mid) break;
345 }
346 }
347 eigen_assert(dst == desc.size());
348
349 return block_storage.AsTensorMaterializedBlock();
350 }
351
352 EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE TensorOpCost costPerCoeff(bool vectorized) const {
353 const double compute_cost = NumDims * (TensorOpCost::DivCost<Index>() + TensorOpCost::MulCost<Index>() +
354 2 * TensorOpCost::AddCost<Index>());
355 return m_impl.costPerCoeff(vectorized) + TensorOpCost(0, 0, compute_cost, vectorized, PacketSize);
356 }
357
358 EIGEN_DEVICE_FUNC EvaluatorPointerType data() const { return nullptr; }
359
360 protected:
361 Dimensions m_dimensions;
362 array<Index, NumDims> m_outputStrides;
363 array<Index, NumDims - 1> m_inputStrides;
364 array<Index, NumDims - 1> m_patchStrides;
365
366 TensorEvaluator<ArgType, Device> m_impl;
367 const Device EIGEN_DEVICE_REF m_device;
368};
369
370} // end namespace Eigen
371
372#endif // EIGEN_TENSOR_TENSOR_PATCH_H
The tensor base class.
Definition TensorForwardDeclarations.h:69
Tensor patch class.
Definition TensorPatch.h:44
Namespace containing all symbols from the Eigen library.
The tensor evaluator class.
Definition TensorEvaluator.h:47