Eigen-Contrib  5.0.1-dev+master
 
Loading...
Searching...
No Matches
TensorRef.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_REF_H
12#define EIGEN_TENSOR_TENSOR_REF_H
13
14// IWYU pragma: private
15#include "./InternalHeaderCheck.h"
16
17namespace Eigen {
18
19namespace internal {
20
21template <typename Dimensions, typename Scalar>
22class TensorLazyBaseEvaluator {
23 public:
24 TensorLazyBaseEvaluator() = default;
25 virtual ~TensorLazyBaseEvaluator() = default;
26
27 EIGEN_DEVICE_FUNC virtual const Dimensions& dimensions() const = 0;
28 EIGEN_DEVICE_FUNC virtual const Scalar* data() const = 0;
29
30 EIGEN_DEVICE_FUNC virtual const Scalar coeff(DenseIndex index) const = 0;
31 EIGEN_DEVICE_FUNC virtual Scalar& coeffRef(DenseIndex index) = 0;
32
33 // The count is shared by the TensorRef copies that a ThreadPoolDevice evaluator makes on each worker.
34 void incrRefCount() { m_refcount.fetch_add(1, std::memory_order_relaxed); }
35 // Returns true if the caller dropped the last reference and must delete the evaluator.
36 bool decrRefCount() { return m_refcount.fetch_sub(1, std::memory_order_acq_rel) == 1; }
37 int refCount() const { return m_refcount.load(std::memory_order_relaxed); }
38
39 private:
40 TensorLazyBaseEvaluator(const TensorLazyBaseEvaluator& other) = delete;
41 TensorLazyBaseEvaluator& operator=(const TensorLazyBaseEvaluator& other) = delete;
42
43 std::atomic<int> m_refcount{0};
44};
45
46template <typename Dimensions, typename Expr, typename Device>
47class TensorLazyEvaluatorReadOnly
48 : public TensorLazyBaseEvaluator<Dimensions, typename TensorEvaluator<Expr, Device>::Scalar> {
49 public:
50 EIGEN_MAKE_ALIGNED_OPERATOR_NEW
51 using Scalar = typename TensorEvaluator<Expr, Device>::Scalar;
52 using Storage = StorageMemory<Scalar, Device>;
53 using EvaluatorPointerType = typename Storage::Type;
54 using EvalType = TensorEvaluator<Expr, Device>;
55
56 TensorLazyEvaluatorReadOnly(const Expr& expr, const Device& device) : m_impl(expr, device), m_dummy() {
57 EIGEN_STATIC_ASSERT(
58 internal::array_size<Dimensions>::value == internal::array_size<typename EvalType::Dimensions>::value,
59 "Dimension sizes must match.");
60 const auto& other_dims = m_impl.dimensions();
61 for (std::size_t i = 0; i < m_dims.size(); ++i) {
62 m_dims[i] = other_dims[i];
63 }
64 m_impl.evalSubExprsIfNeeded(nullptr);
65 }
66 virtual ~TensorLazyEvaluatorReadOnly() { m_impl.cleanup(); }
67
68 EIGEN_DEVICE_FUNC virtual const Dimensions& dimensions() const { return m_dims; }
69 EIGEN_DEVICE_FUNC virtual const Scalar* data() const { return m_impl.data(); }
70
71 EIGEN_DEVICE_FUNC virtual const Scalar coeff(DenseIndex index) const {
72 return m_impl.coeff(internal::convert_index<typename EvalType::Index>(index));
73 }
74 EIGEN_DEVICE_FUNC virtual Scalar& coeffRef(DenseIndex /*index*/) {
75 eigen_assert(false && "can't reference the coefficient of a rvalue");
76 return m_dummy;
77 }
78
79 protected:
80 TensorEvaluator<Expr, Device> m_impl;
81 Dimensions m_dims;
82 Scalar m_dummy;
83};
84
85template <typename Dimensions, typename Expr, typename Device>
86class TensorLazyEvaluatorWritable : public TensorLazyEvaluatorReadOnly<Dimensions, Expr, Device> {
87 public:
88 using Base = TensorLazyEvaluatorReadOnly<Dimensions, Expr, Device>;
89 using Scalar = typename Base::Scalar;
90 using Storage = StorageMemory<Scalar, Device>;
91 using EvaluatorPointerType = typename Storage::Type;
92
93 TensorLazyEvaluatorWritable(const Expr& expr, const Device& device) : Base(expr, device) {}
94 virtual ~TensorLazyEvaluatorWritable() = default;
95
96 EIGEN_DEVICE_FUNC virtual Scalar& coeffRef(DenseIndex index) {
97 return this->m_impl.coeffRef(internal::convert_index<typename Base::EvalType::Index>(index));
98 }
99};
100
101template <typename Dimensions, typename Expr, typename Device, bool IsWritable>
102class TensorLazyEvaluator : public std::conditional_t<IsWritable, TensorLazyEvaluatorWritable<Dimensions, Expr, Device>,
103 TensorLazyEvaluatorReadOnly<Dimensions, const Expr, Device>> {
104 public:
105 using Base = std::conditional_t<IsWritable, TensorLazyEvaluatorWritable<Dimensions, Expr, Device>,
106 TensorLazyEvaluatorReadOnly<Dimensions, const Expr, Device>>;
107 using Scalar = typename Base::Scalar;
108
109 TensorLazyEvaluator(const Expr& expr, const Device& device) : Base(expr, device) {}
110 virtual ~TensorLazyEvaluator() = default;
111};
112
113template <typename Derived>
114class TensorRefBase : public TensorBase<Derived> {
115 public:
116 using PlainObjectType = typename traits<Derived>::PlainObjectType;
117 using Base = typename PlainObjectType::Base;
118 using Nested = typename Eigen::internal::ref_selector<Derived>::type;
119 using StorageKind = typename traits<PlainObjectType>::StorageKind;
120 using Index = typename traits<PlainObjectType>::Index;
121 using Scalar = typename traits<PlainObjectType>::Scalar;
122 using RealScalar = typename NumTraits<Scalar>::Real;
123 using CoeffReturnType = typename Base::CoeffReturnType;
124 using PointerType = Scalar*;
125 using PointerArgType = PointerType;
126
127 static constexpr Index NumIndices = PlainObjectType::NumIndices;
128 using Dimensions = typename PlainObjectType::Dimensions;
129
130 static constexpr int Layout = PlainObjectType::Layout;
131 enum {
132 IsAligned = false,
133 PacketAccess = false,
134 BlockAccess = false,
135 PreferBlockAccess = false,
136 CoordAccess = false, // to be implemented
137 RawAccess = false
138 };
139
140 //===- Tensor block evaluation strategy (see TensorBlock.h) -----------===//
141 using TensorBlock = TensorBlockNotImplemented;
142 //===------------------------------------------------------------------===//
143
144 EIGEN_STRONG_INLINE TensorRefBase() = default;
145
146 TensorRefBase(const TensorRefBase& other) : TensorBase<Derived>(other), m_evaluator(other.m_evaluator) {
147 if (m_evaluator) {
148 eigen_assert(m_evaluator->refCount() > 0);
149 m_evaluator->incrRefCount();
150 }
151 }
152
153 TensorRefBase& operator=(const TensorRefBase& other) {
154 if (this != &other) {
155 unrefEvaluator();
156 m_evaluator = other.m_evaluator;
157 if (m_evaluator) {
158 eigen_assert(m_evaluator->refCount() > 0);
159 m_evaluator->incrRefCount();
160 }
161 }
162 return *this;
163 }
164
165 template <typename Expression,
166 typename EnableIf = std::enable_if_t<!std::is_same<std::decay_t<Expression>, Derived>::value>>
167 EIGEN_STRONG_INLINE TensorRefBase(const Expression& expr)
168 : m_evaluator(new TensorLazyEvaluator<Dimensions, Expression, DefaultDevice,
169 /*IsWritable=*/!std::is_const<PlainObjectType>::value &&
170 bool(is_lvalue<Expression>::value)>(expr, DefaultDevice())) {
171 m_evaluator->incrRefCount();
172 }
173
174 template <typename Expression,
175 typename EnableIf = std::enable_if_t<!std::is_same<std::decay_t<Expression>, Derived>::value>>
176 EIGEN_STRONG_INLINE TensorRefBase& operator=(const Expression& expr) {
177 unrefEvaluator();
178 m_evaluator = new TensorLazyEvaluator < Dimensions, Expression, DefaultDevice,
179 /*IsWritable=*/!std::is_const<PlainObjectType>::value&& bool(is_lvalue<Expression>::value) >
180 (expr, DefaultDevice());
181 m_evaluator->incrRefCount();
182 return *this;
183 }
184
185 ~TensorRefBase() { unrefEvaluator(); }
186
187 EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE Index rank() const { return m_evaluator->dimensions().size(); }
188 template <Index N>
189 EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE Index dimension() const {
190 EIGEN_STATIC_ASSERT(0 <= N && N < NumIndices, INVALID_DIMENSION);
191 return m_evaluator->dimensions()[N];
192 }
193 EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE Index dimension(Index n) const {
194 eigen_assert(0 <= n && n < NumIndices);
195 return m_evaluator->dimensions()[n];
196 }
197 EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE const Dimensions& dimensions() const { return m_evaluator->dimensions(); }
198 EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE Index size() const { return m_evaluator->dimensions().TotalSize(); }
199 EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE const Scalar* data() const { return m_evaluator->data(); }
200
201 EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE const Scalar operator()(Index index) const { return m_evaluator->coeff(index); }
202
203 template <typename... IndexTypes>
204 EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE const Scalar operator()(Index firstIndex, IndexTypes... otherIndices) const {
205 eigen_assert(internal::indices_fit<Index>(otherIndices...));
206 const std::size_t num_indices = sizeof...(otherIndices) + 1;
207 const array<Index, num_indices> indices{{firstIndex, static_cast<Index>(otherIndices)...}};
208 return coeff(indices);
209 }
210
211 template <std::size_t NumIndices>
212 EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE const Scalar coeff(const array<Index, NumIndices>& indices) const {
213 const Dimensions& dims = this->dimensions();
214 Index index = 0;
215 EIGEN_IF_CONSTEXPR (PlainObjectType::Options & RowMajor) {
216 index += indices[0];
217 for (size_t i = 1; i < NumIndices; ++i) {
218 index = index * dims[i] + indices[i];
219 }
220 } else {
221 index += indices[NumIndices - 1];
222 for (int i = NumIndices - 2; i >= 0; --i) {
223 index = index * dims[i] + indices[i];
224 }
225 }
226 return m_evaluator->coeff(index);
227 }
228
229 EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE const Scalar coeff(Index index) const { return m_evaluator->coeff(index); }
230
231 EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE Scalar& coeffRef(Index index) { return m_evaluator->coeffRef(index); }
232
233 protected:
234 TensorLazyBaseEvaluator<Dimensions, Scalar>* evaluator() { return m_evaluator; }
235
236 private:
237 EIGEN_STRONG_INLINE void unrefEvaluator() {
238 if (m_evaluator) {
239 if (m_evaluator->decrRefCount()) {
240 delete m_evaluator;
241 }
242 }
243 }
244
245 TensorLazyBaseEvaluator<Dimensions, Scalar>* m_evaluator = nullptr;
246};
247
248#if EIGEN_COMP_CXXVER < 17
249template <typename Derived>
250constexpr typename TensorRefBase<Derived>::Index TensorRefBase<Derived>::NumIndices;
251template <typename Derived>
252constexpr int TensorRefBase<Derived>::Layout;
253#endif
254
255} // namespace internal
256
264template <typename PlainObjectType>
265class TensorRef : public internal::TensorRefBase<TensorRef<PlainObjectType>> {
266 using Base = internal::TensorRefBase<TensorRef<PlainObjectType>>;
267
268 public:
269 using Scalar = typename Base::Scalar;
270 using Dimensions = typename Base::Dimensions;
271 // Without this, unqualified Index below does not find the dependent base's typedef and resolves to Eigen::Index,
272 // giving the accessors a different index type than the rest of the class.
273 using Index = typename Base::Index;
274
275 EIGEN_STRONG_INLINE TensorRef() = default;
276
277 EIGEN_STRONG_INLINE TensorRef(const TensorRef& other) = default;
278
279 template <typename Expression>
280 EIGEN_STRONG_INLINE TensorRef(const Expression& expr) : Base(expr) {
281 EIGEN_STATIC_ASSERT(internal::is_lvalue<Expression>::value,
282 "Expression must be mutable to create a mutable TensorRef<Expression>. Did you mean "
283 "TensorRef<const Expression>?)");
284 }
285
286 TensorRef& operator=(const TensorRef& other) { return Base::operator=(other).derived(); }
287
288 template <typename Expression>
289 EIGEN_STRONG_INLINE TensorRef& operator=(const Expression& expr) {
290 EIGEN_STATIC_ASSERT(internal::is_lvalue<Expression>::value,
291 "Expression must be mutable to create a mutable TensorRef<Expression>. Did you mean "
292 "TensorRef<const Expression>?)");
293 return Base::operator=(expr).derived();
294 }
295
296 template <typename... IndexTypes>
297 EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE Scalar& coeffRef(Index firstIndex, IndexTypes... otherIndices) {
298 eigen_assert(internal::indices_fit<Index>(otherIndices...));
299 const std::size_t num_indices = sizeof...(otherIndices) + 1;
300 const array<Index, num_indices> indices{{firstIndex, static_cast<Index>(otherIndices)...}};
301 return coeffRef(indices);
302 }
303
304 template <std::size_t NumIndices>
305 EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE Scalar& coeffRef(const array<Index, NumIndices>& indices) {
306 const Dimensions& dims = this->dimensions();
307 Index index = 0;
308 EIGEN_IF_CONSTEXPR (PlainObjectType::Options & RowMajor) {
309 index += indices[0];
310 for (size_t i = 1; i < NumIndices; ++i) {
311 index = index * dims[i] + indices[i];
312 }
313 } else {
314 index += indices[NumIndices - 1];
315 for (int i = NumIndices - 2; i >= 0; --i) {
316 index = index * dims[i] + indices[i];
317 }
318 }
319 return Base::evaluator()->coeffRef(index);
320 }
321
322 EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE Scalar& coeffRef(Index index) { return Base::evaluator()->coeffRef(index); }
323};
324
332template <typename PlainObjectType>
333class TensorRef<const PlainObjectType> : public internal::TensorRefBase<TensorRef<const PlainObjectType>> {
334 using Base = internal::TensorRefBase<TensorRef<const PlainObjectType>>;
335
336 public:
337 EIGEN_STRONG_INLINE TensorRef() = default;
338
339 EIGEN_STRONG_INLINE TensorRef(const TensorRef& other) = default;
340
341 template <typename Expression>
342 EIGEN_STRONG_INLINE TensorRef(const Expression& expr) : Base(expr) {}
343
344 TensorRef& operator=(const TensorRef& other) { return Base::operator=(other).derived(); }
345
346 template <typename Expression>
347 EIGEN_STRONG_INLINE TensorRef& operator=(const Expression& expr) {
348 return Base::operator=(expr).derived();
349 }
350};
351
352// evaluator for rvalues
353template <typename Derived, typename Device>
354struct TensorEvaluator<const TensorRef<Derived>, Device> {
355 using Index = typename Derived::Index;
356 using Scalar = typename Derived::Scalar;
357 using CoeffReturnType = typename Derived::Scalar;
358 using PacketReturnType = typename PacketType<CoeffReturnType, Device>::type;
359 using Dimensions = typename Derived::Dimensions;
360 using Storage = StorageMemory<CoeffReturnType, Device>;
361 using EvaluatorPointerType = typename Storage::Type;
362
363 static constexpr int Layout = TensorRef<Derived>::Layout;
364 enum {
365 IsAligned = false,
366 PacketAccess = false,
367 BlockAccess = false,
368 PreferBlockAccess = false,
369 CoordAccess = false, // to be implemented
370 RawAccess = false
371 };
372
373 //===- Tensor block evaluation strategy (see TensorBlock.h) -------------===//
374 using TensorBlock = internal::TensorBlockNotImplemented;
375 //===--------------------------------------------------------------------===//
376
377 EIGEN_STRONG_INLINE TensorEvaluator(const TensorRef<Derived>& m, const Device&) : m_ref(m) {}
378
379 EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE const Dimensions& dimensions() const { return m_ref.dimensions(); }
380
381#ifdef EIGEN_USE_THREADS
382 template <typename EvalSubExprsCallback>
383 EIGEN_STRONG_INLINE void evalSubExprsIfNeededAsync(EvaluatorPointerType, EvalSubExprsCallback done) {
384 done(true);
385 }
386#endif // EIGEN_USE_THREADS
387
388 EIGEN_STRONG_INLINE bool evalSubExprsIfNeeded(EvaluatorPointerType) { return true; }
389
390 EIGEN_STRONG_INLINE void cleanup() {}
391
392 // The cost of the evaluator behind the reference is not known here; charge one coefficient load.
393 EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE TensorOpCost costPerCoeff(bool /*vectorized*/) const {
394 return TensorOpCost(sizeof(CoeffReturnType), 0, 0);
395 }
396
397 EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE CoeffReturnType coeff(Index index) const { return m_ref.coeff(index); }
398
399 EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE Scalar& coeffRef(Index index) { return m_ref.coeffRef(index); }
400
401 EIGEN_DEVICE_FUNC const Scalar* data() const { return m_ref.data(); }
402
403 protected:
404 TensorRef<Derived> m_ref;
405};
406
407// evaluator for lvalues
408template <typename Derived, typename Device>
409struct TensorEvaluator<TensorRef<Derived>, Device> : public TensorEvaluator<const TensorRef<Derived>, Device> {
410 using Index = typename Derived::Index;
411 using Scalar = typename Derived::Scalar;
412 using CoeffReturnType = typename Derived::Scalar;
413 using PacketReturnType = typename PacketType<CoeffReturnType, Device>::type;
414 using Dimensions = typename Derived::Dimensions;
415
416 using Base = TensorEvaluator<const TensorRef<Derived>, Device>;
417
418 enum { IsAligned = false, PacketAccess = false, BlockAccess = false, PreferBlockAccess = false, RawAccess = false };
419
420 //===- Tensor block evaluation strategy (see TensorBlock.h) -------------===//
421 using TensorBlock = internal::TensorBlockNotImplemented;
422 //===--------------------------------------------------------------------===//
423
424 EIGEN_STRONG_INLINE TensorEvaluator(TensorRef<Derived>& m, const Device& d) : Base(m, d) {}
425
426 EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE Scalar& coeffRef(Index index) { return this->m_ref.coeffRef(index); }
427};
428
429} // end namespace Eigen
430
431#endif // EIGEN_TENSOR_TENSOR_REF_H
A reference to a tensor expression The expression will be evaluated lazily (as much as possible).
Definition TensorRef.h:265
Namespace containing all symbols from the Eigen library.
The tensor evaluator class.
Definition TensorEvaluator.h:47