TensorChipping.h
Go to the documentation of this file.
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 #include "./InternalHeaderCheck.h"
14 
15 namespace Eigen {
16 
25 namespace internal {
26 template<DenseIndex DimId, typename XprType>
27 struct traits<TensorChippingOp<DimId, XprType> > : public traits<XprType>
28 {
29  typedef typename XprType::Scalar Scalar;
30  typedef traits<XprType> XprTraits;
31  typedef typename XprTraits::StorageKind StorageKind;
32  typedef typename XprTraits::Index Index;
33  typedef typename XprType::Nested Nested;
34  typedef std::remove_reference_t<Nested> Nested_;
35  static constexpr int NumDimensions = XprTraits::NumDimensions - 1;
36  static constexpr int Layout = XprTraits::Layout;
37  typedef typename XprTraits::PointerType PointerType;
38 };
39 
40 template<DenseIndex DimId, typename XprType>
41 struct eval<TensorChippingOp<DimId, XprType>, Eigen::Dense>
42 {
43  typedef const TensorChippingOp<DimId, XprType> EIGEN_DEVICE_REF type;
44 };
45 
46 template<DenseIndex DimId, typename XprType>
47 struct nested<TensorChippingOp<DimId, XprType>, 1, typename eval<TensorChippingOp<DimId, XprType> >::type>
48 {
49  typedef TensorChippingOp<DimId, XprType> type;
50 };
51 
52 template <DenseIndex DimId>
53 struct DimensionId
54 {
55  EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE DimensionId(DenseIndex dim) {
57  eigen_assert(dim == DimId);
58  }
59  EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE DenseIndex actualDim() const {
60  return DimId;
61  }
62 };
63 template <>
64 struct DimensionId<Dynamic>
65 {
66  EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE DimensionId(DenseIndex dim) : actual_dim(dim) {
67  eigen_assert(dim >= 0);
68  }
69  EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE DenseIndex actualDim() const {
70  return actual_dim;
71  }
72  private:
73  const DenseIndex actual_dim;
74 };
75 
76 
77 } // end namespace internal
78 
79 
80 
81 template<DenseIndex DimId, typename XprType>
82 class TensorChippingOp : public TensorBase<TensorChippingOp<DimId, XprType> >
83 {
84  public:
86  typedef typename Eigen::internal::traits<TensorChippingOp>::Scalar Scalar;
88  typedef typename XprType::CoeffReturnType CoeffReturnType;
89  typedef typename Eigen::internal::nested<TensorChippingOp>::type Nested;
90  typedef typename Eigen::internal::traits<TensorChippingOp>::StorageKind StorageKind;
91  typedef typename Eigen::internal::traits<TensorChippingOp>::Index Index;
92 
93  EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE TensorChippingOp(const XprType& expr, const Index offset, const Index dim)
94  : m_xpr(expr), m_offset(offset), m_dim(dim) {
95  }
96 
98  const Index offset() const { return m_offset; }
100  const Index dim() const { return m_dim.actualDim(); }
101 
104  expression() const { return m_xpr; }
105 
107 
108  protected:
109  typename XprType::Nested m_xpr;
111  const internal::DimensionId<DimId> m_dim;
112 };
113 
114 
115 // Eval as rvalue
116 template<DenseIndex DimId, typename ArgType, typename Device>
117 struct TensorEvaluator<const TensorChippingOp<DimId, ArgType>, Device>
118 {
120  static constexpr int NumInputDims = internal::array_size<typename TensorEvaluator<ArgType, Device>::Dimensions>::value;
121  static constexpr int NumDims = NumInputDims-1;
122  typedef typename XprType::Index Index;
124  typedef typename XprType::Scalar Scalar;
131 
132  enum {
133  // Alignment can't be guaranteed at compile time since it depends on the
134  // slice offsets.
135  IsAligned = false,
138  // Chipping of outer-most dimension is a trivial operation, because we can
139  // read and write directly from the underlying tensor using single offset.
140  IsOuterChipping = (Layout == ColMajor && DimId == NumInputDims - 1) ||
141  (Layout == RowMajor && DimId == 0),
142  // Chipping inner-most dimension.
143  IsInnerChipping = (Layout == ColMajor && DimId == 0) ||
144  (Layout == RowMajor && DimId == NumInputDims - 1),
145  // Prefer block access if the underlying expression prefers it, otherwise
146  // only if chipping is not trivial.
148  !IsOuterChipping,
149  CoordAccess = false, // to be implemented
150  RawAccess = false
151  };
152 
153  typedef std::remove_const_t<Scalar> ScalarNoConst;
154 
155  //===- Tensor block evaluation strategy (see TensorBlock.h) -------------===//
156  typedef internal::TensorBlockDescriptor<NumDims, Index> TensorBlockDesc;
157  typedef internal::TensorBlockScratchAllocator<Device> TensorBlockScratch;
158 
159  typedef internal::TensorBlockDescriptor<NumInputDims, Index>
163 
164  typedef typename internal::TensorMaterializedBlock<ScalarNoConst, NumDims,
165  Layout, Index>
167  //===--------------------------------------------------------------------===//
168 
169  EIGEN_STRONG_INLINE TensorEvaluator(const XprType& op, const Device& device)
170  : m_impl(op.expression(), device), m_dim(op.dim()), m_device(device)
171  {
172  EIGEN_STATIC_ASSERT((NumInputDims >= 1), YOU_MADE_A_PROGRAMMING_MISTAKE);
173  eigen_assert(NumInputDims > m_dim.actualDim());
174 
175  const typename TensorEvaluator<ArgType, Device>::Dimensions& input_dims = m_impl.dimensions();
176  eigen_assert(op.offset() < input_dims[m_dim.actualDim()]);
177 
178  int j = 0;
179  for (int i = 0; i < NumInputDims; ++i) {
180  if (i != m_dim.actualDim()) {
181  m_dimensions[j] = input_dims[i];
182  ++j;
183  }
184  }
185 
186  m_stride = 1;
187  m_inputStride = 1;
188  if (static_cast<int>(Layout) == static_cast<int>(ColMajor)) {
189  for (int i = 0; i < m_dim.actualDim(); ++i) {
190  m_stride *= input_dims[i];
191  m_inputStride *= input_dims[i];
192  }
193  } else {
194  for (int i = NumInputDims-1; i > m_dim.actualDim(); --i) {
195  m_stride *= input_dims[i];
196  m_inputStride *= input_dims[i];
197  }
198  }
199  m_inputStride *= input_dims[m_dim.actualDim()];
200  m_inputOffset = m_stride * op.offset();
201  }
202 
203  EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE const Dimensions& dimensions() const { return m_dimensions; }
204 
205  EIGEN_STRONG_INLINE bool evalSubExprsIfNeeded(EvaluatorPointerType) {
206  m_impl.evalSubExprsIfNeeded(NULL);
207  return true;
208  }
209 
210  EIGEN_STRONG_INLINE void cleanup() {
211  m_impl.cleanup();
212  }
213 
214  EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE CoeffReturnType coeff(Index index) const
215  {
216  return m_impl.coeff(srcCoeff(index));
217  }
218 
219  template<int LoadMode>
220  EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE PacketReturnType packet(Index index) const
221  {
222  eigen_assert(index+PacketSize-1 < dimensions().TotalSize());
223 
224  if (isInnerChipping()) {
225  // m_stride is equal to 1, so let's avoid the integer division.
226  eigen_assert(m_stride == 1);
227  Index inputIndex = index * m_inputStride + m_inputOffset;
228  EIGEN_ALIGN_MAX std::remove_const_t<CoeffReturnType> values[PacketSize];
230  for (int i = 0; i < PacketSize; ++i) {
231  values[i] = m_impl.coeff(inputIndex);
232  inputIndex += m_inputStride;
233  }
234  PacketReturnType rslt = internal::pload<PacketReturnType>(values);
235  return rslt;
236  } else if (isOuterChipping()) {
237  // m_stride is always greater than index, so let's avoid the integer division.
238  eigen_assert(m_stride > index);
239  return m_impl.template packet<LoadMode>(index + m_inputOffset);
240  } else {
241  const Index idx = index / m_stride;
242  const Index rem = index - idx * m_stride;
243  if (rem + PacketSize <= m_stride) {
244  Index inputIndex = idx * m_inputStride + m_inputOffset + rem;
245  return m_impl.template packet<LoadMode>(inputIndex);
246  } else {
247  // Cross the stride boundary. Fallback to slow path.
248  EIGEN_ALIGN_MAX std::remove_const_t<CoeffReturnType> values[PacketSize];
250  for (int i = 0; i < PacketSize; ++i) {
251  values[i] = coeff(index);
252  ++index;
253  }
254  PacketReturnType rslt = internal::pload<PacketReturnType>(values);
255  return rslt;
256  }
257  }
258  }
259 
260  EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE TensorOpCost
261  costPerCoeff(bool vectorized) const {
262  double cost = 0;
263  if ((static_cast<int>(Layout) == static_cast<int>(ColMajor) &&
264  m_dim.actualDim() == 0) ||
265  (static_cast<int>(Layout) == static_cast<int>(RowMajor) &&
266  m_dim.actualDim() == NumInputDims - 1)) {
267  cost += TensorOpCost::MulCost<Index>() + TensorOpCost::AddCost<Index>();
268  } else if ((static_cast<int>(Layout) == static_cast<int>(ColMajor) &&
269  m_dim.actualDim() == NumInputDims - 1) ||
270  (static_cast<int>(Layout) == static_cast<int>(RowMajor) &&
271  m_dim.actualDim() == 0)) {
272  cost += TensorOpCost::AddCost<Index>();
273  } else {
274  cost += 3 * TensorOpCost::MulCost<Index>() + TensorOpCost::DivCost<Index>() +
275  3 * TensorOpCost::AddCost<Index>();
276  }
277 
278  return m_impl.costPerCoeff(vectorized) +
279  TensorOpCost(0, 0, cost, vectorized, PacketSize);
280  }
281 
282  EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE
283  internal::TensorBlockResourceRequirements getResourceRequirements() const {
284  const size_t target_size = m_device.lastLevelCacheSize();
285  return internal::TensorBlockResourceRequirements::merge(
286  internal::TensorBlockResourceRequirements::skewed<Scalar>(target_size),
287  m_impl.getResourceRequirements());
288  }
289 
290  EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE TensorBlock
292  bool root_of_expr_ast = false) const {
293  const Index chip_dim = m_dim.actualDim();
294 
295  DSizes<Index, NumInputDims> input_block_dims;
296  for (int i = 0; i < NumInputDims; ++i) {
297  input_block_dims[i]
298  = i < chip_dim ? desc.dimension(i)
299  : i > chip_dim ? desc.dimension(i - 1)
300  : 1;
301  }
302 
303  ArgTensorBlockDesc arg_desc(srcCoeff(desc.offset()), input_block_dims);
304 
305  // Try to reuse destination buffer for materializing argument block.
306  if (desc.HasDestinationBuffer()) {
307  DSizes<Index, NumInputDims> arg_destination_strides;
308  for (int i = 0; i < NumInputDims; ++i) {
309  arg_destination_strides[i]
310  = i < chip_dim ? desc.destination().strides()[i]
311  : i > chip_dim ? desc.destination().strides()[i - 1]
312  : 0; // for dimensions of size `1` stride should never be used.
313  }
314 
315  arg_desc.template AddDestinationBuffer<Layout>(
316  desc.destination().template data<ScalarNoConst>(),
317  arg_destination_strides);
318  }
319 
320  ArgTensorBlock arg_block = m_impl.block(arg_desc, scratch, root_of_expr_ast);
321  if (!arg_desc.HasDestinationBuffer()) desc.DropDestinationBuffer();
322 
323  if (arg_block.data() != NULL) {
324  // Forward argument block buffer if possible.
325  return TensorBlock(arg_block.kind(), arg_block.data(),
326  desc.dimensions());
327 
328  } else {
329  // Assign argument block expression to a buffer.
330 
331  // Prepare storage for the materialized chipping result.
332  const typename TensorBlock::Storage block_storage =
333  TensorBlock::prepareStorage(desc, scratch);
334 
335  typedef internal::TensorBlockAssignment<
336  ScalarNoConst, NumInputDims, typename ArgTensorBlock::XprType, Index>
337  TensorBlockAssignment;
338 
339  TensorBlockAssignment::Run(
340  TensorBlockAssignment::target(
341  arg_desc.dimensions(),
342  internal::strides<Layout>(arg_desc.dimensions()),
343  block_storage.data()),
344  arg_block.expr());
345 
346  return block_storage.AsTensorMaterializedBlock();
347  }
348  }
349 
350  EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE typename Storage::Type data() const {
351  typename Storage::Type result = constCast(m_impl.data());
352  if (isOuterChipping() && result) {
353  return result + m_inputOffset;
354  } else {
355  return NULL;
356  }
357  }
358 
359  protected:
360  EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE Index srcCoeff(Index index) const
361  {
362  Index inputIndex;
363  if (isInnerChipping()) {
364  // m_stride is equal to 1, so let's avoid the integer division.
365  eigen_assert(m_stride == 1);
366  inputIndex = index * m_inputStride + m_inputOffset;
367  } else if (isOuterChipping()) {
368  // m_stride is always greater than index, so let's avoid the integer
369  // division.
370  eigen_assert(m_stride > index);
371  inputIndex = index + m_inputOffset;
372  } else {
373  const Index idx = index / m_stride;
374  inputIndex = idx * m_inputStride + m_inputOffset;
375  index -= idx * m_stride;
376  inputIndex += index;
377  }
378  return inputIndex;
379  }
380 
381  EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE bool isInnerChipping() const {
382  return IsInnerChipping ||
383  (static_cast<int>(Layout) == ColMajor && m_dim.actualDim() == 0) ||
384  (static_cast<int>(Layout) == RowMajor && m_dim.actualDim() == NumInputDims - 1);
385  }
386 
387  EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE bool isOuterChipping() const {
388  return IsOuterChipping ||
389  (static_cast<int>(Layout) == ColMajor && m_dim.actualDim() == NumInputDims-1) ||
390  (static_cast<int>(Layout) == RowMajor && m_dim.actualDim() == 0);
391  }
392 
398  const internal::DimensionId<DimId> m_dim;
400 };
401 
402 
403 // Eval as lvalue
404 template<DenseIndex DimId, typename ArgType, typename Device>
405 struct TensorEvaluator<TensorChippingOp<DimId, ArgType>, Device>
406  : public TensorEvaluator<const TensorChippingOp<DimId, ArgType>, Device>
407 {
410  static constexpr int NumInputDims = internal::array_size<typename TensorEvaluator<ArgType, Device>::Dimensions>::value;
411  static constexpr int NumDims = NumInputDims-1;
412  typedef typename XprType::Index Index;
414  typedef typename XprType::Scalar Scalar;
418 
419  enum {
420  IsAligned = false,
424  RawAccess = false
425  };
426 
427  //===- Tensor block evaluation strategy (see TensorBlock.h) -------------===//
428  typedef internal::TensorBlockDescriptor<NumDims, Index> TensorBlockDesc;
429  //===--------------------------------------------------------------------===//
430 
431  EIGEN_STRONG_INLINE TensorEvaluator(const XprType& op, const Device& device)
432  : Base(op, device)
433  { }
434 
435  EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE CoeffReturnType& coeffRef(Index index) const
436  {
437  return this->m_impl.coeffRef(this->srcCoeff(index));
438  }
439 
440  template <int StoreMode> EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE
441  void writePacket(Index index, const PacketReturnType& x) const
442  {
443  if (this->isInnerChipping()) {
444  // m_stride is equal to 1, so let's avoid the integer division.
445  eigen_assert(this->m_stride == 1);
446  EIGEN_ALIGN_MAX std::remove_const_t<CoeffReturnType> values[PacketSize];
447  internal::pstore<CoeffReturnType, PacketReturnType>(values, x);
448  Index inputIndex = index * this->m_inputStride + this->m_inputOffset;
450  for (int i = 0; i < PacketSize; ++i) {
451  this->m_impl.coeffRef(inputIndex) = values[i];
452  inputIndex += this->m_inputStride;
453  }
454  } else if (this->isOuterChipping()) {
455  // m_stride is always greater than index, so let's avoid the integer division.
456  eigen_assert(this->m_stride > index);
457  this->m_impl.template writePacket<StoreMode>(index + this->m_inputOffset, x);
458  } else {
459  const Index idx = index / this->m_stride;
460  const Index rem = index - idx * this->m_stride;
461  if (rem + PacketSize <= this->m_stride) {
462  const Index inputIndex = idx * this->m_inputStride + this->m_inputOffset + rem;
463  this->m_impl.template writePacket<StoreMode>(inputIndex, x);
464  } else {
465  // Cross stride boundary. Fallback to slow path.
466  EIGEN_ALIGN_MAX std::remove_const_t<CoeffReturnType> values[PacketSize];
467  internal::pstore<CoeffReturnType, PacketReturnType>(values, x);
469  for (int i = 0; i < PacketSize; ++i) {
470  this->coeffRef(index) = values[i];
471  ++index;
472  }
473  }
474  }
475  }
476 
477  template <typename TensorBlock>
478  EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE void writeBlock(
479  const TensorBlockDesc& desc, const TensorBlock& block) {
480  eigen_assert(this->m_impl.data() != NULL);
481 
482  const Index chip_dim = this->m_dim.actualDim();
483 
484  DSizes<Index, NumInputDims> input_block_dims;
485  for (int i = 0; i < NumInputDims; ++i) {
486  input_block_dims[i] = i < chip_dim ? desc.dimension(i)
487  : i > chip_dim ? desc.dimension(i - 1)
488  : 1;
489  }
490 
492  const typename TensorBlock::XprType>
493  TensorBlockExpr;
494 
495  typedef internal::TensorBlockAssignment<Scalar, NumInputDims,
496  TensorBlockExpr, Index>
497  TensorBlockAssign;
498 
499  TensorBlockAssign::Run(
500  TensorBlockAssign::target(
501  input_block_dims,
502  internal::strides<Layout>(this->m_impl.dimensions()),
503  this->m_impl.data(), this->srcCoeff(desc.offset())),
504  block.expr().reshape(input_block_dims));
505  }
506 };
507 
508 
509 } // end namespace Eigen
510 
511 #endif // EIGEN_CXX11_TENSOR_TENSOR_CHIPPING_H
int i
#define EIGEN_ALIGN_MAX
#define EIGEN_UNROLL_LOOP
#define EIGEN_UNUSED_VARIABLE(var)
#define EIGEN_DEVICE_FUNC
#define eigen_assert(x)
#define EIGEN_STATIC_ASSERT(X, MSG)
#define EIGEN_TENSOR_INHERIT_ASSIGNMENT_OPERATORS(Derived)
Definition: TensorMacros.h:80
#define EIGEN_DEVICE_REF
Definition: TensorMacros.h:36
The tensor base class.
Eigen::internal::traits< TensorChippingOp >::Index Index
TensorBase< TensorChippingOp< DimId, XprType > > Base
Eigen::internal::traits< TensorChippingOp >::StorageKind StorageKind
Eigen::internal::nested< TensorChippingOp >::type Nested
const Index dim() const
Eigen::internal::traits< TensorChippingOp >::Scalar Scalar
const internal::DimensionId< DimId > m_dim
Eigen::NumTraits< Scalar >::Real RealScalar
const internal::remove_all_t< typename XprType::Nested > & expression() const
const Index offset() const
TensorChippingOp(const XprType &expr, const Index offset, const Index dim)
XprType::CoeffReturnType CoeffReturnType
A tensor expression mapping an existing array of data.
Definition: TensorMap.h:32
typename remove_all< T >::type remove_all_t
: TensorContractionSycl.h, provides various tensor contraction kernel for SYCL backend
T * constCast(const T *data)
EIGEN_DEFAULT_DENSE_INDEX_TYPE Index
EIGEN_DEFAULT_DENSE_INDEX_TYPE DenseIndex
const int Dynamic
internal::packet_traits< Scalar >::type type
Definition: TensorMeta.h:55
TensorEvaluator< const TensorChippingOp< DimId, ArgType >, Device > Base
PacketType< CoeffReturnType, Device >::type PacketReturnType
internal::TensorBlockDescriptor< NumDims, Index > TensorBlockDesc
void writeBlock(const TensorBlockDesc &desc, const TensorBlock &block)
void writePacket(Index index, const PacketReturnType &x) const
TensorEvaluator< const ArgType, Device >::TensorBlock ArgTensorBlock
internal::TensorBlockDescriptor< NumDims, Index > TensorBlockDesc
internal::TensorBlockScratchAllocator< Device > TensorBlockScratch
internal::TensorBlockResourceRequirements getResourceRequirements() const
internal::TensorMaterializedBlock< ScalarNoConst, NumDims, Layout, Index > TensorBlock
internal::TensorBlockDescriptor< NumInputDims, Index > ArgTensorBlockDesc
TensorBlock block(TensorBlockDesc &desc, TensorBlockScratch &scratch, bool root_of_expr_ast=false) const
A cost model used to limit the number of threads used for evaluating tensor expression.
const Dimensions & dimensions() const
static constexpr int Layout
Derived::Scalar Scalar
const Device EIGEN_DEVICE_REF m_device
TensorBlock block(TensorBlockDesc &desc, TensorBlockScratch &scratch, bool=false) const
CoeffReturnType coeff(Index index) const
CoeffReturnType & coeffRef(Index index) const
static constexpr int PacketSize
internal::TensorMaterializedBlock< ScalarNoConst, NumCoords, Layout, Index > TensorBlock
std::remove_const_t< Scalar > ScalarNoConst
std::ptrdiff_t j