$darkmode
Eigen-unsupported  5.0.1-dev
TensorChipping.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 
10 #ifndef EIGEN_CXX11_TENSOR_TENSOR_CHIPPING_H
11 #define EIGEN_CXX11_TENSOR_TENSOR_CHIPPING_H
12 
13 // IWYU pragma: private
14 #include "./InternalHeaderCheck.h"
15 
16 namespace Eigen {
17 
18 namespace internal {
19 template <DenseIndex DimId, typename XprType>
20 struct traits<TensorChippingOp<DimId, 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 - 1;
28  static constexpr int Layout = XprTraits::Layout;
29  typedef typename XprTraits::PointerType PointerType;
30 };
31 
32 template <DenseIndex DimId, typename XprType>
33 struct eval<TensorChippingOp<DimId, XprType>, Eigen::Dense> {
34  typedef const TensorChippingOp<DimId, XprType> EIGEN_DEVICE_REF type;
35 };
36 
37 template <DenseIndex DimId, typename XprType>
38 struct nested<TensorChippingOp<DimId, XprType>, 1, typename eval<TensorChippingOp<DimId, XprType> >::type> {
39  typedef TensorChippingOp<DimId, XprType> type;
40 };
41 
42 template <DenseIndex DimId>
43 struct DimensionId {
44  EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE DimensionId(DenseIndex dim) {
45  EIGEN_UNUSED_VARIABLE(dim);
46  eigen_assert(dim == DimId);
47  }
48  EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE DenseIndex actualDim() const { return DimId; }
49 };
50 template <>
51 struct DimensionId<Dynamic> {
52  EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE DimensionId(DenseIndex dim) : actual_dim(dim) { eigen_assert(dim >= 0); }
53  EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE DenseIndex actualDim() const { return actual_dim; }
54 
55  private:
56  const DenseIndex actual_dim;
57 };
58 
59 } // end namespace internal
60 
64 template <DenseIndex DimId, typename XprType>
65 class TensorChippingOp : public TensorBase<TensorChippingOp<DimId, XprType> > {
66  public:
68  typedef typename Eigen::internal::traits<TensorChippingOp>::Scalar Scalar;
69  typedef typename Eigen::NumTraits<Scalar>::Real RealScalar;
70  typedef typename XprType::CoeffReturnType CoeffReturnType;
71  typedef typename Eigen::internal::nested<TensorChippingOp>::type Nested;
72  typedef typename Eigen::internal::traits<TensorChippingOp>::StorageKind StorageKind;
73  typedef typename Eigen::internal::traits<TensorChippingOp>::Index Index;
74 
75  EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE TensorChippingOp(const XprType& expr, const Index offset, const Index dim)
76  : m_xpr(expr), m_offset(offset), m_dim(dim) {
77  eigen_assert(dim < XprType::NumDimensions && dim >= 0 && "Chip_Dim_out_of_range");
78  }
79 
80  EIGEN_DEVICE_FUNC const Index offset() const { return m_offset; }
81  EIGEN_DEVICE_FUNC const Index dim() const { return m_dim.actualDim(); }
82 
83  EIGEN_DEVICE_FUNC const internal::remove_all_t<typename XprType::Nested>& expression() const { return m_xpr; }
84 
85  EIGEN_TENSOR_INHERIT_ASSIGNMENT_OPERATORS(TensorChippingOp)
86 
87  protected:
88  typename XprType::Nested m_xpr;
89  const Index m_offset;
90  const internal::DimensionId<DimId> m_dim;
91 };
92 
93 // Eval as rvalue
94 template <DenseIndex DimId, typename ArgType, typename Device>
95 struct TensorEvaluator<const TensorChippingOp<DimId, ArgType>, Device> {
96  typedef TensorChippingOp<DimId, ArgType> XprType;
97  static constexpr int NumInputDims =
98  internal::array_size<typename TensorEvaluator<ArgType, Device>::Dimensions>::value;
99  static constexpr int NumDims = NumInputDims - 1;
100  typedef typename XprType::Index Index;
101  typedef DSizes<Index, NumDims> Dimensions;
102  typedef typename XprType::Scalar Scalar;
103  typedef typename XprType::CoeffReturnType CoeffReturnType;
104  typedef typename PacketType<CoeffReturnType, Device>::type PacketReturnType;
105  static constexpr int PacketSize = PacketType<CoeffReturnType, Device>::size;
106  typedef StorageMemory<CoeffReturnType, Device> Storage;
107  typedef typename Storage::Type EvaluatorPointerType;
108  static constexpr int Layout = TensorEvaluator<ArgType, Device>::Layout;
109 
110  enum {
111  // Alignment can't be guaranteed at compile time since it depends on the
112  // slice offsets.
113  IsAligned = false,
116  // Chipping of outer-most dimension is a trivial operation, because we can
117  // read and write directly from the underlying tensor using single offset.
118  IsOuterChipping = (Layout == ColMajor && DimId == NumInputDims - 1) || (Layout == RowMajor && DimId == 0),
119  // Chipping inner-most dimension.
120  IsInnerChipping = (Layout == ColMajor && DimId == 0) || (Layout == RowMajor && DimId == NumInputDims - 1),
121  // Prefer block access if the underlying expression prefers it, otherwise
122  // only if chipping is not trivial.
123  PreferBlockAccess = TensorEvaluator<ArgType, Device>::PreferBlockAccess || !IsOuterChipping,
124  CoordAccess = false, // to be implemented
125  RawAccess = false
126  };
127 
128  typedef std::remove_const_t<Scalar> ScalarNoConst;
129 
130  //===- Tensor block evaluation strategy (see TensorBlock.h) -------------===//
131  typedef internal::TensorBlockDescriptor<NumDims, Index> TensorBlockDesc;
132  typedef internal::TensorBlockScratchAllocator<Device> TensorBlockScratch;
133 
134  typedef internal::TensorBlockDescriptor<NumInputDims, Index> ArgTensorBlockDesc;
135  typedef typename TensorEvaluator<const ArgType, Device>::TensorBlock ArgTensorBlock;
136 
137  typedef typename internal::TensorMaterializedBlock<ScalarNoConst, NumDims, Layout, Index> TensorBlock;
138  //===--------------------------------------------------------------------===//
139 
140  EIGEN_STRONG_INLINE TensorEvaluator(const XprType& op, const Device& device)
141  : m_impl(op.expression(), device), m_dim(op.dim()), m_device(device) {
142  EIGEN_STATIC_ASSERT((NumInputDims >= 1), YOU_MADE_A_PROGRAMMING_MISTAKE);
143  eigen_assert(NumInputDims > m_dim.actualDim());
144 
145  const typename TensorEvaluator<ArgType, Device>::Dimensions& input_dims = m_impl.dimensions();
146  eigen_assert(op.offset() < input_dims[m_dim.actualDim()]);
147 
148  int j = 0;
149  for (int i = 0; i < NumInputDims; ++i) {
150  if (i != m_dim.actualDim()) {
151  m_dimensions[j] = input_dims[i];
152  ++j;
153  }
154  }
155 
156  m_stride = 1;
157  m_inputStride = 1;
158  if (static_cast<int>(Layout) == static_cast<int>(ColMajor)) {
159  for (int i = 0; i < m_dim.actualDim(); ++i) {
160  m_stride *= input_dims[i];
161  m_inputStride *= input_dims[i];
162  }
163  } else {
164  for (int i = NumInputDims - 1; i > m_dim.actualDim(); --i) {
165  m_stride *= input_dims[i];
166  m_inputStride *= input_dims[i];
167  }
168  }
169  m_inputStride *= input_dims[m_dim.actualDim()];
170  m_inputOffset = m_stride * op.offset();
171 
172  // Check if chipping is effectively inner or outer: products of dimensions
173  // before or after the chipped dimension is `1`.
174  Index after_chipped_dim_product = 1;
175  for (int i = static_cast<int>(m_dim.actualDim()) + 1; i < NumInputDims; ++i) {
176  after_chipped_dim_product *= input_dims[i];
177  }
178 
179  Index before_chipped_dim_product = 1;
180  for (int i = 0; i < m_dim.actualDim(); ++i) {
181  before_chipped_dim_product *= input_dims[i];
182  }
183 
184  if (static_cast<int>(Layout) == static_cast<int>(ColMajor)) {
185  m_isEffectivelyInnerChipping = before_chipped_dim_product == 1;
186  m_isEffectivelyOuterChipping = after_chipped_dim_product == 1;
187  } else {
188  m_isEffectivelyInnerChipping = after_chipped_dim_product == 1;
189  m_isEffectivelyOuterChipping = before_chipped_dim_product == 1;
190  }
191  }
192 
193  EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE const Dimensions& dimensions() const { return m_dimensions; }
194 
195  EIGEN_STRONG_INLINE bool evalSubExprsIfNeeded(EvaluatorPointerType) {
196  m_impl.evalSubExprsIfNeeded(NULL);
197  return true;
198  }
199 
200 #ifdef EIGEN_USE_THREADS
201  template <typename EvalSubExprsCallback>
202  EIGEN_STRONG_INLINE void evalSubExprsIfNeededAsync(EvaluatorPointerType /*data*/, EvalSubExprsCallback done) {
203  m_impl.evalSubExprsIfNeededAsync(nullptr, [done](bool) { done(true); });
204  }
205 #endif // EIGEN_USE_THREADS
206 
207  EIGEN_STRONG_INLINE void cleanup() { m_impl.cleanup(); }
208 
209  EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE CoeffReturnType coeff(Index index) const {
210  return m_impl.coeff(srcCoeff(index));
211  }
212 
213  template <int LoadMode>
214  EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE PacketReturnType packet(Index index) const {
215  eigen_assert(index + PacketSize - 1 < dimensions().TotalSize());
216 
217  if (isInnerChipping()) {
218  // m_stride is equal to 1, so let's avoid the integer division.
219  eigen_assert(m_stride == 1);
220  Index inputIndex = index * m_inputStride + m_inputOffset;
221  EIGEN_ALIGN_MAX std::remove_const_t<CoeffReturnType> values[PacketSize];
222  EIGEN_UNROLL_LOOP
223  for (int i = 0; i < PacketSize; ++i) {
224  values[i] = m_impl.coeff(inputIndex);
225  inputIndex += m_inputStride;
226  }
227  PacketReturnType rslt = internal::pload<PacketReturnType>(values);
228  return rslt;
229  } else if (isOuterChipping()) {
230  // m_stride is always greater than index, so let's avoid the integer division.
231  eigen_assert(m_stride > index);
232  return m_impl.template packet<LoadMode>(index + m_inputOffset);
233  } else {
234  const Index idx = index / m_stride;
235  const Index rem = index - idx * m_stride;
236  if (rem + PacketSize <= m_stride) {
237  Index inputIndex = idx * m_inputStride + m_inputOffset + rem;
238  return m_impl.template packet<LoadMode>(inputIndex);
239  } else {
240  // Cross the stride boundary. Fallback to slow path.
241  EIGEN_ALIGN_MAX std::remove_const_t<CoeffReturnType> values[PacketSize];
242  EIGEN_UNROLL_LOOP
243  for (int i = 0; i < PacketSize; ++i) {
244  values[i] = coeff(index);
245  ++index;
246  }
247  PacketReturnType rslt = internal::pload<PacketReturnType>(values);
248  return rslt;
249  }
250  }
251  }
252 
253  EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE TensorOpCost costPerCoeff(bool vectorized) const {
254  double cost = 0;
255  if ((static_cast<int>(Layout) == static_cast<int>(ColMajor) && m_dim.actualDim() == 0) ||
256  (static_cast<int>(Layout) == static_cast<int>(RowMajor) && m_dim.actualDim() == NumInputDims - 1)) {
257  cost += TensorOpCost::MulCost<Index>() + TensorOpCost::AddCost<Index>();
258  } else if ((static_cast<int>(Layout) == static_cast<int>(ColMajor) && m_dim.actualDim() == NumInputDims - 1) ||
259  (static_cast<int>(Layout) == static_cast<int>(RowMajor) && m_dim.actualDim() == 0)) {
260  cost += TensorOpCost::AddCost<Index>();
261  } else {
262  cost += 3 * TensorOpCost::MulCost<Index>() + TensorOpCost::DivCost<Index>() + 3 * TensorOpCost::AddCost<Index>();
263  }
264 
265  return m_impl.costPerCoeff(vectorized) + TensorOpCost(0, 0, cost, vectorized, PacketSize);
266  }
267 
268  EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE internal::TensorBlockResourceRequirements getResourceRequirements() const {
269  const size_t target_size = m_device.lastLevelCacheSize();
270  return internal::TensorBlockResourceRequirements::merge(
271  internal::TensorBlockResourceRequirements::skewed<Scalar>(target_size), m_impl.getResourceRequirements());
272  }
273 
274  EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE TensorBlock block(TensorBlockDesc& desc, TensorBlockScratch& scratch,
275  bool root_of_expr_ast = false) const {
276  const Index chip_dim = m_dim.actualDim();
277 
278  DSizes<Index, NumInputDims> input_block_dims;
279  for (int i = 0; i < NumInputDims; ++i) {
280  input_block_dims[i] = i < chip_dim ? desc.dimension(i) : i > chip_dim ? desc.dimension(i - 1) : 1;
281  }
282 
283  ArgTensorBlockDesc arg_desc(srcCoeff(desc.offset()), input_block_dims);
284 
285  // Try to reuse destination buffer for materializing argument block.
286  if (desc.HasDestinationBuffer()) {
287  DSizes<Index, NumInputDims> arg_destination_strides;
288  for (int i = 0; i < NumInputDims; ++i) {
289  arg_destination_strides[i] = i < chip_dim ? desc.destination().strides()[i]
290  : i > chip_dim ? desc.destination().strides()[i - 1]
291  : 0; // for dimensions of size `1` stride should never be used.
292  }
293 
294  arg_desc.template AddDestinationBuffer<Layout>(desc.destination().template data<ScalarNoConst>(),
295  arg_destination_strides);
296  }
297 
298  ArgTensorBlock arg_block = m_impl.block(arg_desc, scratch, root_of_expr_ast);
299  if (!arg_desc.HasDestinationBuffer()) desc.DropDestinationBuffer();
300 
301  if (arg_block.data() != NULL) {
302  // Forward argument block buffer if possible.
303  return TensorBlock(arg_block.kind(), arg_block.data(), desc.dimensions());
304 
305  } else {
306  // Assign argument block expression to a buffer.
307 
308  // Prepare storage for the materialized chipping result.
309  const typename TensorBlock::Storage block_storage = TensorBlock::prepareStorage(desc, scratch);
310 
311  typedef internal::TensorBlockAssignment<ScalarNoConst, NumInputDims, typename ArgTensorBlock::XprType, Index>
312  TensorBlockAssignment;
313 
314  TensorBlockAssignment::Run(
315  TensorBlockAssignment::target(arg_desc.dimensions(), internal::strides<Layout>(arg_desc.dimensions()),
316  block_storage.data()),
317  arg_block.expr());
318 
319  return block_storage.AsTensorMaterializedBlock();
320  }
321  }
322 
323  EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE typename Storage::Type data() const {
324  typename Storage::Type result = constCast(m_impl.data());
325  if (isOuterChipping() && result) {
326  return result + m_inputOffset;
327  } else {
328  return NULL;
329  }
330  }
331 
332  protected:
333  EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE Index srcCoeff(Index index) const {
334  Index inputIndex;
335  if (isInnerChipping()) {
336  // m_stride is equal to 1, so let's avoid the integer division.
337  eigen_assert(m_stride == 1);
338  inputIndex = index * m_inputStride + m_inputOffset;
339  } else if (isOuterChipping()) {
340  // m_stride is always greater than index, so let's avoid the integer
341  // division.
342  eigen_assert(m_stride > index);
343  inputIndex = index + m_inputOffset;
344  } else {
345  const Index idx = index / m_stride;
346  inputIndex = idx * m_inputStride + m_inputOffset;
347  index -= idx * m_stride;
348  inputIndex += index;
349  }
350  return inputIndex;
351  }
352 
353  EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE bool isInnerChipping() const {
354  return IsInnerChipping || m_isEffectivelyInnerChipping;
355  }
356 
357  EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE bool isOuterChipping() const {
358  return IsOuterChipping || m_isEffectivelyOuterChipping;
359  }
360 
361  Dimensions m_dimensions;
362  Index m_stride;
363  Index m_inputOffset;
364  Index m_inputStride;
365  TensorEvaluator<ArgType, Device> m_impl;
366  const internal::DimensionId<DimId> m_dim;
367  const Device EIGEN_DEVICE_REF m_device;
368 
369  // If product of all dimensions after or before the chipped dimension is `1`,
370  // it is effectively the same as chipping innermost or outermost dimension.
371  bool m_isEffectivelyInnerChipping;
372  bool m_isEffectivelyOuterChipping;
373 };
374 
375 // Eval as lvalue
376 template <DenseIndex DimId, typename ArgType, typename Device>
377 struct TensorEvaluator<TensorChippingOp<DimId, ArgType>, Device>
378  : public TensorEvaluator<const TensorChippingOp<DimId, ArgType>, Device> {
379  typedef TensorEvaluator<const TensorChippingOp<DimId, ArgType>, Device> Base;
380  typedef TensorChippingOp<DimId, ArgType> XprType;
381  static constexpr int NumInputDims =
382  internal::array_size<typename TensorEvaluator<ArgType, Device>::Dimensions>::value;
383  static constexpr int NumDims = NumInputDims - 1;
384  typedef typename XprType::Index Index;
385  typedef DSizes<Index, NumDims> Dimensions;
386  typedef typename XprType::Scalar Scalar;
387  typedef typename XprType::CoeffReturnType CoeffReturnType;
388  typedef typename PacketType<CoeffReturnType, Device>::type PacketReturnType;
389  static constexpr int PacketSize = PacketType<CoeffReturnType, Device>::size;
390 
391  enum {
392  IsAligned = false,
393  PacketAccess = TensorEvaluator<ArgType, Device>::PacketAccess,
394  BlockAccess = TensorEvaluator<ArgType, Device>::RawAccess,
395  Layout = TensorEvaluator<ArgType, Device>::Layout,
396  RawAccess = false
397  };
398 
399  //===- Tensor block evaluation strategy (see TensorBlock.h) -------------===//
400  typedef internal::TensorBlockDescriptor<NumDims, Index> TensorBlockDesc;
401  //===--------------------------------------------------------------------===//
402 
403  EIGEN_STRONG_INLINE TensorEvaluator(const XprType& op, const Device& device) : Base(op, device) {}
404 
405  EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE CoeffReturnType& coeffRef(Index index) const {
406  return this->m_impl.coeffRef(this->srcCoeff(index));
407  }
408 
409  template <int StoreMode>
410  EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE void writePacket(Index index, const PacketReturnType& x) const {
411  if (this->isInnerChipping()) {
412  // m_stride is equal to 1, so let's avoid the integer division.
413  eigen_assert(this->m_stride == 1);
414  EIGEN_ALIGN_MAX std::remove_const_t<CoeffReturnType> values[PacketSize];
415  internal::pstore<CoeffReturnType, PacketReturnType>(values, x);
416  Index inputIndex = index * this->m_inputStride + this->m_inputOffset;
417  EIGEN_UNROLL_LOOP
418  for (int i = 0; i < PacketSize; ++i) {
419  this->m_impl.coeffRef(inputIndex) = values[i];
420  inputIndex += this->m_inputStride;
421  }
422  } else if (this->isOuterChipping()) {
423  // m_stride is always greater than index, so let's avoid the integer division.
424  eigen_assert(this->m_stride > index);
425  this->m_impl.template writePacket<StoreMode>(index + this->m_inputOffset, x);
426  } else {
427  const Index idx = index / this->m_stride;
428  const Index rem = index - idx * this->m_stride;
429  if (rem + PacketSize <= this->m_stride) {
430  const Index inputIndex = idx * this->m_inputStride + this->m_inputOffset + rem;
431  this->m_impl.template writePacket<StoreMode>(inputIndex, x);
432  } else {
433  // Cross stride boundary. Fallback to slow path.
434  EIGEN_ALIGN_MAX std::remove_const_t<CoeffReturnType> values[PacketSize];
435  internal::pstore<CoeffReturnType, PacketReturnType>(values, x);
436  EIGEN_UNROLL_LOOP
437  for (int i = 0; i < PacketSize; ++i) {
438  this->coeffRef(index) = values[i];
439  ++index;
440  }
441  }
442  }
443  }
444 
445  template <typename TensorBlock>
446  EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE void writeBlock(const TensorBlockDesc& desc, const TensorBlock& block) {
447  eigen_assert(this->m_impl.data() != NULL);
448 
449  const Index chip_dim = this->m_dim.actualDim();
450 
451  DSizes<Index, NumInputDims> input_block_dims;
452  for (int i = 0; i < NumInputDims; ++i) {
453  input_block_dims[i] = i < chip_dim ? desc.dimension(i) : i > chip_dim ? desc.dimension(i - 1) : 1;
454  }
455 
456  typedef TensorReshapingOp<const DSizes<Index, NumInputDims>, const typename TensorBlock::XprType> TensorBlockExpr;
457 
458  typedef internal::TensorBlockAssignment<Scalar, NumInputDims, TensorBlockExpr, Index> TensorBlockAssign;
459 
460  TensorBlockAssign::Run(
461  TensorBlockAssign::target(input_block_dims, internal::strides<Layout>(this->m_impl.dimensions()),
462  this->m_impl.data(), this->srcCoeff(desc.offset())),
463  block.expr().reshape(input_block_dims));
464  }
465 };
466 
467 } // end namespace Eigen
468 
469 #endif // EIGEN_CXX11_TENSOR_TENSOR_CHIPPING_H
Namespace containing all symbols from the Eigen library.
The tensor evaluator class.
Definition: TensorEvaluator.h:30
Definition: TensorChipping.h:65
EIGEN_DEFAULT_DENSE_INDEX_TYPE Index
The tensor base class.
Definition: TensorForwardDeclarations.h:68
const int Dynamic