10#ifndef EIGEN_TENSOR_TENSOR_BLOCK_H
11#define EIGEN_TENSOR_TENSOR_BLOCK_H
14#include "./InternalHeaderCheck.h"
21template <
typename Scalar,
typename IndexType,
int NumDims,
int Layout>
30template <
int Layout,
typename IndexType,
int NumDims>
31EIGEN_ALWAYS_INLINE std::enable_if_t<NumDims == 0, DSizes<IndexType, NumDims> > strides_impl(
32 const DSizes<IndexType, NumDims>& ) {
33 DSizes<IndexType, NumDims> strides;
37template <
int Layout,
typename IndexType,
int NumDims>
38EIGEN_ALWAYS_INLINE std::enable_if_t<(NumDims > 0), DSizes<IndexType, NumDims> > strides_impl(
39 const DSizes<IndexType, NumDims>& dimensions) {
40 DSizes<IndexType, NumDims> strides;
42 EIGEN_IF_CONSTEXPR (
static_cast<int>(Layout) ==
static_cast<int>(
ColMajor)) {
44 for (
int i = 1; i < NumDims; ++i) {
45 strides[i] = strides[i - 1] * dimensions[i - 1];
48 strides[NumDims - 1] = 1;
49 for (
int i = NumDims - 2; i >= 0; --i) {
50 strides[i] = strides[i + 1] * dimensions[i + 1];
57template <
int Layout,
typename IndexType,
int NumDims>
58EIGEN_ALWAYS_INLINE DSizes<IndexType, NumDims> strides(
const DSizes<IndexType, NumDims>& dimensions) {
59 return strides_impl<Layout>(dimensions);
62template <
int Layout,
typename IndexType,
size_t NumDims>
63EIGEN_ALWAYS_INLINE DSizes<IndexType, NumDims> strides(
const Eigen::array<IndexType, NumDims>& dimensions) {
64 return strides<Layout>(DSizes<IndexType, NumDims>(dimensions));
67template <
int Layout, std::ptrdiff_t... Indices>
68EIGEN_STRONG_INLINE DSizes<std::ptrdiff_t,
sizeof...(Indices)> strides(
const Sizes<Indices...>& sizes) {
69 return strides<Layout>(DSizes<std::ptrdiff_t,
sizeof...(Indices)>(sizes));
85enum class TensorBlockShapeType { kUniformAllDims, kSkewedInnerDims };
87struct TensorBlockResourceRequirements {
88 TensorBlockShapeType shape_type;
90 TensorOpCost cost_per_coeff;
96 EIGEN_DEVICE_FUNC TensorBlockResourceRequirements(TensorBlockShapeType shape_type_,
size_t size_, TensorOpCost cost_)
97 : shape_type(shape_type_), size(size_), cost_per_coeff(cost_) {}
100 template <
typename Scalar>
101 EIGEN_DEVICE_FUNC
static TensorBlockResourceRequirements withShapeAndSize(TensorBlockShapeType shape_type,
102 size_t size_in_bytes, TensorOpCost cost) {
103 const size_t size = numext::maxi(
size_t(1), size_in_bytes /
sizeof(Scalar));
104 return {shape_type, size, cost};
107 template <
typename Scalar>
108 EIGEN_DEVICE_FUNC
static TensorBlockResourceRequirements withShapeAndSize(TensorBlockShapeType shape_type,
109 size_t size_in_bytes) {
124 return withShapeAndSize<Scalar>(shape_type, size_in_bytes,
130 template <
typename Scalar>
131 EIGEN_DEVICE_FUNC
static TensorBlockResourceRequirements skewed(
size_t size_in_bytes) {
132 return withShapeAndSize<Scalar>(TensorBlockShapeType::kSkewedInnerDims, size_in_bytes);
135 template <
typename Scalar>
136 EIGEN_DEVICE_FUNC
static TensorBlockResourceRequirements uniform(
size_t size_in_bytes) {
137 return withShapeAndSize<Scalar>(TensorBlockShapeType::kUniformAllDims, size_in_bytes);
140 EIGEN_DEVICE_FUNC
static EIGEN_STRONG_INLINE TensorBlockResourceRequirements
141 merge(
const TensorBlockResourceRequirements& lhs,
const TensorBlockResourceRequirements& rhs) {
142 return {merge(lhs.shape_type, rhs.shape_type),
143 merge(lhs.size, rhs.size),
144 merge(lhs.cost_per_coeff, rhs.cost_per_coeff)};
147 EIGEN_DEVICE_FUNC TensorBlockResourceRequirements& addCostPerCoeff(TensorOpCost cost) {
148 cost_per_coeff += cost;
155 EIGEN_DEVICE_FUNC
static EIGEN_STRONG_INLINE TensorBlockResourceRequirements any() {
156 return {TensorBlockShapeType::kUniformAllDims, 1, {0, 0, 0}};
160 EIGEN_DEVICE_FUNC
static EIGEN_STRONG_INLINE
size_t merge(
size_t lhs_size,
size_t rhs_size) {
161 return numext::maxi(lhs_size, rhs_size);
164 EIGEN_DEVICE_FUNC
static EIGEN_STRONG_INLINE TensorBlockShapeType merge(TensorBlockShapeType lhs,
165 TensorBlockShapeType rhs) {
166 return (lhs == TensorBlockShapeType::kSkewedInnerDims || rhs == TensorBlockShapeType::kSkewedInnerDims)
167 ? TensorBlockShapeType::kSkewedInnerDims
168 : TensorBlockShapeType::kUniformAllDims;
171 EIGEN_DEVICE_FUNC
static EIGEN_STRONG_INLINE TensorOpCost merge(TensorOpCost lhs_cost, TensorOpCost rhs_cost) {
172 return lhs_cost + rhs_cost;
180template <
int NumDims,
typename IndexType = Eigen::Index>
181class TensorBlockDescriptor {
183 using Dimensions = DSizes<IndexType, NumDims>;
195 class DestinationBuffer {
197 enum DestinationBufferKind :
int {
227 template <
typename Scalar>
228 Scalar* data()
const {
229 eigen_assert(m_data_type_size ==
sizeof(Scalar));
230 return static_cast<Scalar*
>(m_data);
233 const Dimensions& strides()
const {
return m_strides; }
234 const DestinationBufferKind& kind()
const {
return m_kind; }
237 friend class TensorBlockDescriptor<NumDims, IndexType>;
239 DestinationBuffer() =
default;
241 template <
typename Scalar>
242 DestinationBuffer(Scalar* data,
const Dimensions& strides, DestinationBufferKind kind)
243 : m_data(static_cast<void*>(data)), m_data_type_size(sizeof(Scalar)), m_strides(strides), m_kind(kind) {}
245 template <
int Layout,
typename Scalar>
246 static DestinationBuffer make(
const TensorBlockDescriptor& desc, Scalar* data,
const Dimensions& strides) {
247 return DestinationBuffer(data, strides, kind<Layout>(desc, strides));
250 template <
int Layout>
251 static DestinationBufferKind kind(
const TensorBlockDescriptor& desc,
const Dimensions& strides) {
252 const Dimensions& desc_dims = desc.dimensions();
253 const Dimensions& desc_strides = internal::strides<Layout>(desc_dims);
254 for (
int i = 0; i < NumDims; ++i) {
255 if (desc_dims[i] == 1)
continue;
256 if (desc_strides[i] != strides[i])
return kStrided;
263 void* m_data =
nullptr;
264 size_t m_data_type_size = 0;
268 Dimensions m_strides;
270 DestinationBufferKind m_kind = kEmpty;
273 TensorBlockDescriptor(
const IndexType offset,
const Dimensions& dimensions,
const DestinationBuffer& destination)
274 : m_offset(offset), m_dimensions(dimensions), m_destination(destination) {}
276 TensorBlockDescriptor(
const IndexType offset,
const Dimensions& dimensions)
277 : m_offset(offset), m_dimensions(dimensions), m_destination(DestinationBuffer()) {}
279 IndexType offset()
const {
return m_offset; }
280 const Dimensions& dimensions()
const {
return m_dimensions; }
281 IndexType dimension(Index n)
const {
282 eigen_internal_assert(0 <= n && n < NumDims);
283 return m_dimensions[n];
285 IndexType size()
const {
return array_prod<IndexType>(m_dimensions); }
287 const DestinationBuffer& destination()
const {
return m_destination; }
289 template <
int Layout,
typename Scalar>
290 void AddDestinationBuffer(Scalar* dst_base,
const Dimensions& dst_strides) {
291 eigen_assert(dst_base !=
nullptr);
292 m_destination = DestinationBuffer::template make<Layout>(*
this, dst_base, dst_strides);
295 template <
int Layout,
typename Scalar,
typename DstStr
idesIndexType>
296 void AddDestinationBuffer(Scalar* dst_base,
const DSizes<DstStridesIndexType, NumDims>& dst_strides) {
298 AddDestinationBuffer<Layout>(dst_base, Dimensions(dst_strides));
301 TensorBlockDescriptor& DropDestinationBuffer() {
302 m_destination.m_data =
nullptr;
303 m_destination.m_kind = DestinationBuffer::kEmpty;
307 bool HasDestinationBuffer()
const {
return m_destination.kind() != DestinationBuffer::kEmpty; }
310 TensorBlockDescriptor WithOffset(IndexType offset)
const {
311 return TensorBlockDescriptor(offset, m_dimensions, m_destination);
317 const IndexType m_offset;
318 const Dimensions m_dimensions;
319 DestinationBuffer m_destination;
325template <
int NumDims,
int Layout,
typename IndexType = Eigen::Index>
326class TensorBlockMapper {
327 using BlockDescriptor = TensorBlockDescriptor<NumDims, IndexType>;
330 using Dimensions = DSizes<IndexType, NumDims>;
332 TensorBlockMapper() =
default;
333 TensorBlockMapper(
const DSizes<IndexType, NumDims>& dimensions,
const TensorBlockResourceRequirements& requirements)
334 : m_tensor_dimensions(dimensions), m_requirements(requirements) {
336 InitializeBlockDimensions();
339 EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE IndexType blockCount()
const {
return m_total_block_count; }
341 EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE IndexType blockTotalSize()
const {
return m_block_dimensions.TotalSize(); }
343 EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE
const DSizes<IndexType, NumDims>& blockDimensions()
const {
344 return m_block_dimensions;
347 EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE BlockDescriptor blockDescriptor(IndexType block_index)
const {
348 static constexpr bool isColMajor = Layout ==
static_cast<int>(
ColMajor);
350 IndexType offset = 0;
351 DSizes<IndexType, NumDims> dimensions;
353 EIGEN_IF_CONSTEXPR (NumDims == 0) return BlockDescriptor(offset, dimensions);
356 for (
int i = NumDims - 1; i >= 0; --i) {
357 const int dim = isColMajor ? i : NumDims - i - 1;
359 const IndexType idx = block_index / m_block_strides[dim];
360 block_index -= idx * m_block_strides[dim];
362 const IndexType coord = idx * m_block_dimensions[dim];
363 dimensions[dim] = numext::mini(m_tensor_dimensions[dim] - coord, m_block_dimensions[dim]);
364 offset += coord * m_tensor_strides[dim];
367 return {offset, dimensions};
371 void InitializeBlockDimensions() {
373 const TensorBlockShapeType shape_type = m_requirements.shape_type;
374 IndexType target_block_size = numext::maxi<IndexType>(1,
static_cast<IndexType
>(m_requirements.size));
376 IndexType tensor_size = m_tensor_dimensions.TotalSize();
382 if (tensor_size == 0) {
383 for (
int i = 0; i < NumDims; ++i) {
384 m_block_dimensions[i] = 1;
386 m_total_block_count = 0;
391 if (tensor_size <= target_block_size) {
392 m_block_dimensions = m_tensor_dimensions;
393 m_total_block_count = 1;
396 for (
int i = 0; i < NumDims; ++i) {
397 m_tensor_strides[i] = 0;
398 m_block_strides[i] = 1;
403 static constexpr bool isColMajor = Layout ==
static_cast<int>(
ColMajor);
406 if (shape_type == TensorBlockShapeType::kSkewedInnerDims) {
407 IndexType coeff_to_allocate = target_block_size;
409 for (
int i = 0; i < NumDims; ++i) {
410 const int dim = isColMajor ? i : NumDims - i - 1;
411 m_block_dimensions[dim] = numext::mini(coeff_to_allocate, m_tensor_dimensions[dim]);
413 numext::div_ceil(coeff_to_allocate, numext::maxi(
static_cast<IndexType
>(1), m_block_dimensions[dim]));
415 eigen_assert(coeff_to_allocate == 1);
417 }
else if (shape_type == TensorBlockShapeType::kUniformAllDims) {
420 const IndexType dim_size_target = convert_index<IndexType>(
421 numext::pow(
static_cast<float>(target_block_size), 1.0f /
static_cast<float>(m_block_dimensions.rank())));
423 for (
int i = 0; i < NumDims; ++i) {
428 m_block_dimensions[i] = numext::mini(dim_size_target, m_tensor_dimensions[i]);
432 IndexType total_size = m_block_dimensions.TotalSize();
433 for (
int i = 0; i < NumDims; ++i) {
434 const int dim = isColMajor ? i : NumDims - i - 1;
436 if (m_block_dimensions[dim] < m_tensor_dimensions[dim]) {
437 const IndexType total_size_other_dims = total_size / m_block_dimensions[dim];
438 const IndexType alloc_avail = numext::div_ceil<IndexType>(target_block_size, total_size_other_dims);
439 if (alloc_avail == m_block_dimensions[dim]) {
443 m_block_dimensions[dim] = numext::mini(m_tensor_dimensions[dim], alloc_avail);
444 total_size = total_size_other_dims * m_block_dimensions[dim];
452 eigen_assert(m_block_dimensions.TotalSize() >=
453 numext::mini<IndexType>(target_block_size, m_tensor_dimensions.TotalSize()));
456 DSizes<IndexType, NumDims> block_count;
457 for (
int i = 0; i < NumDims; ++i) {
458 block_count[i] = numext::div_ceil(m_tensor_dimensions[i], m_block_dimensions[i]);
460 m_total_block_count = array_prod(block_count);
463 m_tensor_strides = strides<Layout>(m_tensor_dimensions);
464 m_block_strides = strides<Layout>(block_count);
467 DSizes<IndexType, NumDims> m_tensor_dimensions;
468 TensorBlockResourceRequirements m_requirements;
470 DSizes<IndexType, NumDims> m_block_dimensions;
471 IndexType m_total_block_count;
473 DSizes<IndexType, NumDims> m_tensor_strides;
474 DSizes<IndexType, NumDims> m_block_strides;
486template <
typename Device>
487class TensorBlockScratchAllocator {
489 explicit TensorBlockScratchAllocator(
const Device& device) : m_device(device), m_allocation_index(0) {}
491 ~TensorBlockScratchAllocator() {
492 for (
size_t i = 0; i < m_allocations.size(); ++i) {
493 m_device.deallocate(m_allocations[i].ptr);
497 void* allocate(
size_t size) {
499 if (m_allocations.capacity() == 0) m_allocations.reserve(8);
502 const int num_allocations =
static_cast<int>(m_allocations.size());
503 const bool has_allocation = m_allocation_index < num_allocations;
506 eigen_assert(m_allocation_index <= num_allocations);
513 if (has_allocation && m_allocations[m_allocation_index].size < size) {
514 m_device.deallocate(m_allocations[m_allocation_index].ptr);
515 m_allocations[m_allocation_index].ptr = m_device.allocate(size);
516 m_allocations[m_allocation_index].size = size;
520 if (!has_allocation) {
521 Allocation allocation;
522 allocation.ptr = m_device.allocate(size);
523 allocation.size = size;
524 m_allocations.push_back(allocation);
527 eigen_assert(m_allocations[m_allocation_index].ptr !=
nullptr);
528 eigen_assert(m_allocations[m_allocation_index].size >= size);
530 return m_allocations[m_allocation_index++].ptr;
533 void reset() { m_allocation_index = 0; }
541 const Device& m_device;
542 int m_allocation_index;
544 std::vector<Allocation> m_allocations;
550enum TensorBlockKind {
562 kMaterializedInScratch,
571 kMaterializedInOutput
578class TensorBlockNotImplemented {
580 using XprType = void;
583template <
typename Scalar,
int NumDims,
int Layout,
typename IndexType>
584class TensorBlockView;
586template <
typename Scalar,
int NumDims,
int Layout,
typename IndexType>
587struct traits<TensorBlockView<Scalar, NumDims, Layout, IndexType>>
588 : traits<Tensor<Scalar, NumDims, Layout, IndexType>> {
589 static constexpr unsigned int Flags = 0;
594template <
typename Scalar_,
int NumDims,
int Layout,
typename IndexType>
595class TensorBlockView :
public TensorBase<TensorBlockView<Scalar_, NumDims, Layout, IndexType>> {
597 using Scalar = Scalar_;
598 using Index = IndexType;
599 using Dimensions = DSizes<Index, NumDims>;
600 using Nested = TensorBlockView;
601 using StorageKind = Dense;
602 using CoeffReturnType = Scalar;
604 TensorBlockView(
const Scalar* data,
const Dimensions& dimensions)
605 : TensorBlockView(data, dimensions, internal::strides<Layout>(dimensions)) {}
607 TensorBlockView(
const Scalar* data,
const Dimensions& dimensions,
const Dimensions& strides)
608 : m_data(data), m_dimensions(dimensions), m_strides(strides), m_contiguous(true) {
609 eigen_assert(NumDims == 0 || strides[Layout ==
ColMajor ? 0 : NumDims - 1] == 1);
611 for (
int i = 0; i < NumDims; ++i) {
612 const int dim = Layout ==
ColMajor ? i : NumDims - 1 - i;
613 if (dimensions[dim] > 1 && strides[dim] != stride) m_contiguous =
false;
614 stride *= dimensions[dim];
618 EIGEN_DEVICE_FUNC
const Dimensions& dimensions()
const {
return m_dimensions; }
619 EIGEN_DEVICE_FUNC
const Dimensions& strides()
const {
return m_strides; }
620 EIGEN_DEVICE_FUNC
const Scalar* data()
const {
return m_contiguous ? m_data :
nullptr; }
621 EIGEN_DEVICE_FUNC
const Scalar* rawData()
const {
return m_data; }
624 const Scalar* m_data;
625 Dimensions m_dimensions;
626 Dimensions m_strides;
632template <
typename Scalar_,
int NumDims,
int Layout_,
typename IndexType,
typename Device>
633struct TensorEvaluator<const internal::TensorBlockView<Scalar_, NumDims, Layout_, IndexType>, Device> {
634 using XprType = internal::TensorBlockView<Scalar_, NumDims, Layout_, IndexType>;
635 using Scalar = Scalar_;
636 using Index = IndexType;
637 using Dimensions = DSizes<Index, NumDims>;
638 using CoeffReturnType = Scalar;
639 using PacketReturnType =
typename PacketType<Scalar, Device>::type;
640 using EvaluatorPointerType =
const Scalar*;
641 using TensorBlock = internal::TensorBlockNotImplemented;
642 static constexpr int Layout = Layout_;
643 static constexpr bool IsAligned =
false;
644 static constexpr bool PacketAccess = internal::packet_traits<Scalar>::Vectorizable;
645 static constexpr bool BlockAccess =
false;
646 static constexpr bool PreferBlockAccess =
false;
647 static constexpr bool CoordAccess =
false;
648 static constexpr bool RawAccess =
false;
650 TensorEvaluator(
const XprType& expression,
const Device&)
651 : m_expression(expression), m_output_strides(internal::strides<Layout>(expression.dimensions())) {
652 if (!expression.data()) {
653 for (int i = 0; i < NumDims; ++i) {
654 m_divisors[i] = internal::TensorIntDivisor<Index>(numext::maxi(Index(1), m_output_strides[i]));
659 EIGEN_DEVICE_FUNC
const Dimensions& dimensions()
const {
return m_expression.dimensions(); }
660 EIGEN_DEVICE_FUNC
bool evalSubExprsIfNeeded(EvaluatorPointerType) {
return true; }
661 EIGEN_DEVICE_FUNC
void cleanup() {}
662 EIGEN_DEVICE_FUNC
const Scalar* data()
const {
return m_expression.data(); }
664 EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE Index srcCoeff(Index index)
const {
665 if (m_expression.data())
return index;
667 for (
int i = NumDims - 1; i > 0; --i) {
668 const int dim = Layout ==
ColMajor ? i : NumDims - 1 - i;
669 const Index coordinate = index / m_divisors[dim];
670 offset += coordinate * m_expression.strides()[dim];
671 index -= coordinate * m_output_strides[dim];
673 return offset + index;
676 EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE CoeffReturnType coeff(Index index)
const {
677 return m_expression.rawData()[srcCoeff(index)];
680 EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE
const Scalar* coeffAddress(Index index)
const {
681 return m_expression.rawData() + srcCoeff(index);
684 template <
int LoadMode>
685 EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE PacketReturnType packet(Index index)
const {
686 constexpr int PacketSize = PacketType<Scalar, Device>::size;
687 const Index first = srcCoeff(index);
688 if (m_expression.data() || srcCoeff(index + PacketSize - 1) == first + PacketSize - 1) {
689 return internal::ploadu<PacketReturnType>(m_expression.rawData() + first);
691 EIGEN_ALIGN_MAX Scalar values[PacketSize];
692 for (
int i = 0; i < PacketSize; ++i) values[i] = coeff(index + i);
693 return internal::ploadu<PacketReturnType>(values);
696 EIGEN_DEVICE_FUNC TensorOpCost costPerCoeff(
bool vectorized)
const {
697 return TensorOpCost(
sizeof(Scalar), 0, m_expression.data() ? 0 : NumDims, vectorized,
698 PacketType<Scalar, Device>::size);
702 XprType m_expression;
703 Dimensions m_output_strides;
704 array<internal::TensorIntDivisor<Index>, NumDims> m_divisors;
707template <
typename Scalar,
int Layout,
typename Index,
typename Device>
708struct TensorEvaluator<const internal::TensorBlockView<Scalar, 1, Layout, Index>, Device>
709 : TensorEvaluator<const TensorMap<const Tensor<Scalar, 1, Layout, Index>>, Device> {
710 using XprType = internal::TensorBlockView<Scalar, 1, Layout, Index>;
711 using MapType = TensorMap<const Tensor<Scalar, 1, Layout, Index>>;
712 using Base = TensorEvaluator<const MapType, Device>;
713 TensorEvaluator(
const XprType& expression,
const Device& device)
714 : Base(MapType(expression.rawData(), expression.dimensions()), device) {}
715 EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE
const Scalar* coeffAddress(Index index)
const {
return this->data() + index; }
725template <
typename XprType>
727 using type =
typename XprType::Scalar;
730struct XprScalar<void> {
752template <
typename Scalar,
int NumDims,
int Layout,
typename IndexType = Eigen::Index>
753class TensorMaterializedBlock {
755 using Dimensions = DSizes<IndexType, NumDims>;
756 using XprType = TensorBlockView<Scalar, NumDims, Layout, IndexType>;
758 TensorMaterializedBlock(TensorBlockKind kind,
const Scalar* data,
const Dimensions& dimensions,
759 bool valid_expr =
true)
760 : m_kind(kind), m_data(data), m_dimensions(dimensions), m_expr(m_data, m_dimensions), m_valid_expr(valid_expr) {
761 eigen_assert(m_kind == internal::TensorBlockKind::kView ||
762 m_kind == internal::TensorBlockKind::kMaterializedInScratch ||
763 m_kind == internal::TensorBlockKind::kMaterializedInOutput);
766 TensorBlockKind kind()
const {
return m_kind; }
767 const XprType& expr()
const {
768 eigen_assert(m_valid_expr);
772 const Scalar* data()
const {
return m_valid_expr ? m_expr.data() : m_data; }
775 using TensorBlockDesc = internal::TensorBlockDescriptor<NumDims, IndexType>;
787 Scalar* data()
const {
return m_data; }
788 const Dimensions& dimensions()
const {
return m_dimensions; }
789 const Dimensions& strides()
const {
return m_strides; }
791 TensorMaterializedBlock AsTensorMaterializedBlock()
const {
792 return TensorMaterializedBlock(m_materialized_in_output ? internal::TensorBlockKind::kMaterializedInOutput
793 : internal::TensorBlockKind::kMaterializedInScratch,
794 m_data, m_dimensions, !m_strided_storage);
798 friend class TensorMaterializedBlock<Scalar, NumDims, Layout, IndexType>;
800 Storage(Scalar* data,
const Dimensions& dimensions,
const Dimensions& strides,
bool materialized_in_output,
801 bool strided_storage)
803 m_dimensions(dimensions),
805 m_materialized_in_output(materialized_in_output),
806 m_strided_storage(strided_storage) {}
809 Dimensions m_dimensions;
810 Dimensions m_strides;
811 bool m_materialized_in_output;
812 bool m_strided_storage;
817 template <
typename TensorBlockScratch>
818 EIGEN_STRONG_INLINE
static Storage prepareStorage(TensorBlockDesc& desc, TensorBlockScratch& scratch,
819 bool allow_strided_storage =
false) {
821 using DestinationBuffer =
typename TensorBlockDesc::DestinationBuffer;
823 if (desc.destination().kind() == DestinationBuffer::kContiguous) {
824 Scalar* buffer = desc.destination().template data<Scalar>();
825 desc.DropDestinationBuffer();
826 return Storage(buffer, desc.dimensions(), internal::strides<Layout>(desc.dimensions()),
830 }
else if (desc.destination().kind() == DestinationBuffer::kStrided && allow_strided_storage) {
831 Scalar* buffer = desc.destination().template data<Scalar>();
832 desc.DropDestinationBuffer();
833 return Storage(buffer, desc.dimensions(), desc.destination().strides(),
837 void* mem = scratch.allocate(desc.size() *
sizeof(Scalar));
838 return Storage(
static_cast<Scalar*
>(mem), desc.dimensions(), internal::strides<Layout>(desc.dimensions()),
845 template <
typename DataDimensions,
typename TensorBlockScratch>
846 EIGEN_STRONG_INLINE
static TensorMaterializedBlock materialize(
const Scalar* data,
const DataDimensions& data_dims,
847 TensorBlockDesc& desc,
848 TensorBlockScratch& ) {
849 eigen_assert(array_size<DataDimensions>::value == desc.dimensions().size());
851 TensorMaterializedBlock block(internal::TensorBlockKind::kView, data + desc.offset(), desc.dimensions());
852 block.m_expr = XprType(data + desc.offset(), desc.dimensions(), internal::strides<Layout>(Dimensions(data_dims)));
857 TensorBlockKind m_kind;
858 const Scalar* m_data;
859 Dimensions m_dimensions;
868template <
typename UnaryOp,
typename ArgTensorBlock>
869class TensorCwiseUnaryBlock {
870 static constexpr bool NoArgBlockAccess = std::is_void<typename ArgTensorBlock::XprType>::value;
874 std::conditional_t<NoArgBlockAccess, void, TensorCwiseUnaryOp<UnaryOp, const typename ArgTensorBlock::XprType>>;
876 using Scalar =
typename XprScalar<XprType>::type;
878 TensorCwiseUnaryBlock(
const ArgTensorBlock& arg_block,
const UnaryOp& functor)
879 : m_arg_block(arg_block), m_functor(functor) {}
881 TensorBlockKind kind()
const {
return internal::TensorBlockKind::kExpr; }
883 XprType expr()
const {
return XprType(m_arg_block.expr(), m_functor); }
884 const Scalar* data()
const {
return nullptr; }
885 void cleanup() { m_arg_block.cleanup(); }
888 ArgTensorBlock m_arg_block;
896template <
typename BinaryOp,
typename LhsTensorBlock,
typename RhsTensorBlock>
897class TensorCwiseBinaryBlock {
898 static constexpr bool NoArgBlockAccess =
899 std::is_void<typename LhsTensorBlock::XprType>::value || std::is_void<typename RhsTensorBlock::XprType>::value;
902 using XprType = std::conditional_t<
903 NoArgBlockAccess, void,
904 TensorCwiseBinaryOp<BinaryOp, const typename LhsTensorBlock::XprType, const typename RhsTensorBlock::XprType>>;
906 using Scalar =
typename XprScalar<XprType>::type;
908 TensorCwiseBinaryBlock(
const LhsTensorBlock& left_block,
const RhsTensorBlock& right_block,
const BinaryOp& functor)
909 : m_left_block(left_block), m_right_block(right_block), m_functor(functor) {}
911 TensorBlockKind kind()
const {
return internal::TensorBlockKind::kExpr; }
913 XprType expr()
const {
return XprType(m_left_block.expr(), m_right_block.expr(), m_functor); }
915 const Scalar* data()
const {
return nullptr; }
918 m_left_block.cleanup();
919 m_right_block.cleanup();
923 LhsTensorBlock m_left_block;
924 RhsTensorBlock m_right_block;
933template <
typename BlockFactory,
typename ArgTensorBlock>
934class TensorUnaryExprBlock {
935 using ArgXprType =
typename ArgTensorBlock::XprType;
936 static constexpr bool NoArgBlockAccess = std::is_void<ArgXprType>::value;
939 using XprType = std::conditional_t<NoArgBlockAccess, void, typename BlockFactory::template XprType<ArgXprType>::type>;
941 using Scalar =
typename XprScalar<XprType>::type;
943 TensorUnaryExprBlock(
const ArgTensorBlock& arg_block,
const BlockFactory& factory)
944 : m_arg_block(arg_block), m_factory(factory) {}
946 TensorBlockKind kind()
const {
return internal::TensorBlockKind::kExpr; }
947 XprType expr()
const {
return m_factory.expr(m_arg_block.expr()); }
948 const Scalar* data()
const {
return nullptr; }
949 void cleanup() { m_arg_block.cleanup(); }
952 ArgTensorBlock m_arg_block;
953 BlockFactory m_factory;
960template <
typename BlockFactory,
typename Arg1TensorBlock,
typename Arg2TensorBlock,
typename Arg3TensorBlock>
961class TensorTernaryExprBlock {
962 using Arg1XprType =
typename Arg1TensorBlock::XprType;
963 using Arg2XprType =
typename Arg2TensorBlock::XprType;
964 using Arg3XprType =
typename Arg3TensorBlock::XprType;
966 static constexpr bool NoArgBlockAccess =
967 std::is_void<Arg1XprType>::value || std::is_void<Arg2XprType>::value || std::is_void<Arg3XprType>::value;
971 std::conditional_t<NoArgBlockAccess, void,
972 typename BlockFactory::template XprType<Arg1XprType, Arg2XprType, Arg3XprType>::type>;
974 using Scalar =
typename XprScalar<XprType>::type;
976 TensorTernaryExprBlock(
const Arg1TensorBlock& arg1_block,
const Arg2TensorBlock& arg2_block,
977 const Arg3TensorBlock& arg3_block,
const BlockFactory& factory)
978 : m_arg1_block(arg1_block), m_arg2_block(arg2_block), m_arg3_block(arg3_block), m_factory(factory) {}
980 TensorBlockKind kind()
const {
return internal::TensorBlockKind::kExpr; }
981 XprType expr()
const {
return m_factory.expr(m_arg1_block.expr(), m_arg2_block.expr(), m_arg3_block.expr()); }
982 const Scalar* data()
const {
return nullptr; }
984 m_arg1_block.cleanup();
985 m_arg2_block.cleanup();
986 m_arg3_block.cleanup();
990 Arg1TensorBlock m_arg1_block;
991 Arg2TensorBlock m_arg2_block;
992 Arg3TensorBlock m_arg3_block;
993 BlockFactory m_factory;
1000template <
typename Scalar,
typename IndexType>
1001class StridedLinearBufferCopy {
1002 using Packet =
typename packet_traits<Scalar>::type;
1003 using HalfPacket =
typename unpacket_traits<Packet>::half;
1005 Vectorizable = packet_traits<Scalar>::Vectorizable,
1006 PacketSize = packet_traits<Scalar>::size,
1007 HalfPacketSize = unpacket_traits<HalfPacket>::size,
1008 HasHalfPacket =
static_cast<int>(HalfPacketSize) <
static_cast<int>(PacketSize)
1026 Dst(IndexType o, IndexType s, Scalar* d) : offset(o), stride(s), data(d) {}
1034 Src(IndexType o, IndexType s,
const Scalar* d) : offset(o), stride(s), data(d) {}
1041 template <
typename Str
idedLinearBufferCopy::Kind kind>
1042 static EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE
void Run(
const Dst& dst,
const Src& src,
const size_t count) {
1043 Run<kind>(count, dst.offset, dst.stride, dst.data, src.offset, src.stride, src.data);
1047 template <
typename Str
idedLinearBufferCopy::Kind kind>
1048 static EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE
void Run(
const IndexType count,
const IndexType dst_offset,
1049 const IndexType dst_stride, Scalar* EIGEN_RESTRICT dst_data,
1050 const IndexType src_offset,
const IndexType src_stride,
1051 const Scalar* EIGEN_RESTRICT src_data) {
1052 const Scalar* src = &src_data[src_offset];
1053 Scalar* dst = &dst_data[dst_offset];
1055 EIGEN_IF_CONSTEXPR (!Vectorizable) {
1056 for (Index i = 0; i < count; ++i) {
1057 dst[i * dst_stride] = src[i * src_stride];
1062 const IndexType vectorized_size = PacketSize * (count / PacketSize);
1065 EIGEN_IF_CONSTEXPR (kind == StridedLinearBufferCopy::Kind::Linear ||
1066 kind == StridedLinearBufferCopy::Kind::ReverseBoth) {
1074 constexpr IndexType run_stride = kind == StridedLinearBufferCopy::Kind::ReverseBoth ? -1 : 1;
1075 eigen_assert(src_stride == run_stride && dst_stride == run_stride);
1076 const IndexType run_offset = run_stride == 1 ? 0 : count - 1;
1077 const Scalar* run_src = src - run_offset;
1078 Scalar* run_dst = dst - run_offset;
1079 const IndexType unrolled_size = (4 * PacketSize) * (count / (4 * PacketSize));
1080 for (; i < unrolled_size; i += 4 * PacketSize) {
1081 for (
int j = 0; j < 4; ++j) {
1082 Packet p = ploadu<Packet>(run_src + i + j * PacketSize);
1083 pstoreu<Scalar, Packet>(run_dst + i + j * PacketSize, p);
1086 for (; i < vectorized_size; i += PacketSize) {
1087 Packet p = ploadu<Packet>(run_src + i);
1088 pstoreu<Scalar, Packet>(run_dst + i, p);
1090 EIGEN_IF_CONSTEXPR (HasHalfPacket) {
1091 const IndexType vectorized_half_size = HalfPacketSize * (count / HalfPacketSize);
1092 if (i < vectorized_half_size) {
1093 HalfPacket p = ploadu<HalfPacket>(run_src + i);
1094 pstoreu<Scalar, HalfPacket>(run_dst + i, p);
1095 i += HalfPacketSize;
1098 for (; i < count; ++i) {
1099 run_dst[i] = run_src[i];
1102 }
else EIGEN_IF_CONSTEXPR (kind == StridedLinearBufferCopy::Kind::Scatter) {
1104 eigen_assert(src_stride == 1 && dst_stride != 1);
1105 for (; i < vectorized_size; i += PacketSize) {
1106 Packet p = ploadu<Packet>(src + i);
1107 pscatter<Scalar, Packet>(dst + i * dst_stride, p, dst_stride);
1109 EIGEN_IF_CONSTEXPR (HasHalfPacket) {
1110 const IndexType vectorized_half_size = HalfPacketSize * (count / HalfPacketSize);
1111 if (i < vectorized_half_size) {
1112 HalfPacket p = ploadu<HalfPacket>(src + i);
1113 pscatter<Scalar, HalfPacket>(dst + i * dst_stride, p, dst_stride);
1114 i += HalfPacketSize;
1117 for (; i < count; ++i) {
1118 dst[i * dst_stride] = src[i];
1121 }
else EIGEN_IF_CONSTEXPR (kind == StridedLinearBufferCopy::Kind::FillLinear) {
1123 eigen_assert(src_stride == 0 && dst_stride == 1);
1125 const IndexType unrolled_size = (4 * PacketSize) * (count / (4 * PacketSize));
1127 Packet p = pset1<Packet>(s);
1128 for (; i < unrolled_size; i += 4 * PacketSize) {
1129 for (
int j = 0; j < 4; ++j) {
1130 pstoreu<Scalar, Packet>(dst + i + j * PacketSize, p);
1133 for (; i < vectorized_size; i += PacketSize) {
1134 pstoreu<Scalar, Packet>(dst + i, p);
1136 EIGEN_IF_CONSTEXPR (HasHalfPacket) {
1137 const IndexType vectorized_half_size = HalfPacketSize * (count / HalfPacketSize);
1138 if (i < vectorized_half_size) {
1139 HalfPacket hp = pset1<HalfPacket>(s);
1140 pstoreu<Scalar, HalfPacket>(dst + i, hp);
1141 i += HalfPacketSize;
1144 for (; i < count; ++i) {
1148 }
else EIGEN_IF_CONSTEXPR (kind == StridedLinearBufferCopy::Kind::FillScatter) {
1150 eigen_assert(src_stride == 0 && dst_stride != 1);
1152 Packet p = pset1<Packet>(s);
1153 for (; i < vectorized_size; i += PacketSize) {
1154 pscatter<Scalar, Packet>(dst + i * dst_stride, p, dst_stride);
1156 EIGEN_IF_CONSTEXPR (HasHalfPacket) {
1157 const IndexType vectorized_half_size = HalfPacketSize * (count / HalfPacketSize);
1158 if (i < vectorized_half_size) {
1159 HalfPacket hp = pset1<HalfPacket>(s);
1160 pscatter<Scalar, HalfPacket>(dst + i * dst_stride, hp, dst_stride);
1161 i += HalfPacketSize;
1164 for (; i < count; ++i) {
1165 dst[i * dst_stride] = s;
1168 }
else EIGEN_IF_CONSTEXPR (kind == StridedLinearBufferCopy::Kind::Gather) {
1170 eigen_assert(dst_stride == 1);
1171 for (; i < vectorized_size; i += PacketSize) {
1172 Packet p = pgather<Scalar, Packet>(src + i * src_stride, src_stride);
1173 pstoreu<Scalar, Packet>(dst + i, p);
1175 EIGEN_IF_CONSTEXPR (HasHalfPacket) {
1176 const IndexType vectorized_half_size = HalfPacketSize * (count / HalfPacketSize);
1177 if (i < vectorized_half_size) {
1178 HalfPacket p = pgather<Scalar, HalfPacket>(src + i * src_stride, src_stride);
1179 pstoreu<Scalar, HalfPacket>(dst + i, p);
1180 i += HalfPacketSize;
1183 for (; i < count; ++i) {
1184 dst[i] = src[i * src_stride];
1187 }
else EIGEN_IF_CONSTEXPR (kind == StridedLinearBufferCopy::Kind::ReverseStore) {
1193 eigen_assert(src_stride == 1 && dst_stride == -1);
1194 for (; i < vectorized_size; i += PacketSize) {
1195 Packet p = ploadu<Packet>(src + i);
1196 pstoreu<Scalar, Packet>(dst - i - (PacketSize - 1), preverse(p));
1198 EIGEN_IF_CONSTEXPR (HasHalfPacket) {
1199 const IndexType vectorized_half_size = HalfPacketSize * (count / HalfPacketSize);
1200 if (i < vectorized_half_size) {
1201 HalfPacket p = ploadu<HalfPacket>(src + i);
1202 pstoreu<Scalar, HalfPacket>(dst - i - (HalfPacketSize - 1), preverse(p));
1203 i += HalfPacketSize;
1206 for (; i < count; ++i) {
1210 }
else EIGEN_IF_CONSTEXPR (kind == StridedLinearBufferCopy::Kind::ReverseLoad) {
1212 eigen_assert(src_stride == -1 && dst_stride == 1);
1213 for (; i < vectorized_size; i += PacketSize) {
1214 Packet p = ploadu<Packet>(src - i - (PacketSize - 1));
1215 pstoreu<Scalar, Packet>(dst + i, preverse(p));
1217 EIGEN_IF_CONSTEXPR (HasHalfPacket) {
1218 const IndexType vectorized_half_size = HalfPacketSize * (count / HalfPacketSize);
1219 if (i < vectorized_half_size) {
1220 HalfPacket p = ploadu<HalfPacket>(src - i - (HalfPacketSize - 1));
1221 pstoreu<Scalar, HalfPacket>(dst + i, preverse(p));
1222 i += HalfPacketSize;
1225 for (; i < count; ++i) {
1229 }
else EIGEN_IF_CONSTEXPR (kind == StridedLinearBufferCopy::Kind::Random) {
1231 for (; i < count; ++i) {
1232 dst[i * dst_stride] = src[i * src_stride];
1235 eigen_assert(
false);
1251template <
typename Scalar,
typename IndexType,
int NumDims,
int Layout>
1252class TensorBlockIO {
1253 static constexpr bool IsColMajor = Layout ==
ColMajor;
1255 using LinCopy = StridedLinearBufferCopy<Scalar, IndexType>;
1258 using Dimensions = DSizes<IndexType, NumDims>;
1259 using DimensionsMap = DSizes<int, NumDims>;
1262 Dst(
const Dimensions& dst_dims,
const Dimensions& dst_strides, Scalar* dst, IndexType dst_offset = 0)
1263 : dims(dst_dims), strides(dst_strides), data(dst), offset(dst_offset) {}
1272 Src(
const Dimensions& src_strides,
const Scalar* src, IndexType src_offset = 0)
1273 : strides(src_strides), data(src), offset(src_offset) {}
1285 static EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE IndexType Copy(
const Dst& dst,
const Src& src,
1286 const DimensionsMap& dst_to_src_dim_map) {
1288 EIGEN_IF_CONSTEXPR (NumDims == 0) {
1289 *(dst.data + dst.offset) = *(src.data + src.offset);
1294 const DimensionsMap& dim_map = dst_to_src_dim_map;
1297 int num_squeezable_dims = NumSqueezableInnerDims(dim_map);
1309 int num_size_one_inner_dims = 0;
1310 for (
int i = 0; i < num_squeezable_dims; ++i) {
1311 const int dst_dim = IsColMajor ? i : NumDims - i - 1;
1312 if (dst.dims[dst_dim] != 1)
break;
1313 num_size_one_inner_dims++;
1317 if (num_size_one_inner_dims == NumDims) {
1318 *(dst.data + dst.offset) = *(src.data + src.offset);
1324 const int dst_inner_dim = IsColMajor ? num_size_one_inner_dims : NumDims - num_size_one_inner_dims - 1;
1327 const int src_dim_for_dst_inner_dim = NumDims == 0 ? 1 : dim_map[dst_inner_dim];
1330 IndexType dst_inner_dim_size = NumDims == 0 ? 1 : dst.dims[dst_inner_dim];
1336 const IndexType output_stride = NumDims == 0 ? 1 : dst.strides[dst_inner_dim];
1337 const IndexType input_stride = NumDims == 0 ? 1 : src.strides[src_dim_for_dst_inner_dim];
1338 for (
int i = num_size_one_inner_dims + 1; i < num_squeezable_dims; ++i) {
1339 const int dst_dim = IsColMajor ? i : NumDims - i - 1;
1340 const IndexType dst_stride = dst.strides[dst_dim];
1341 const IndexType src_stride = src.strides[dim_map[dst_dim]];
1342 if (dst_stride == dst_inner_dim_size * output_stride && src_stride == dst_inner_dim_size * input_stride) {
1343 dst_inner_dim_size *= dst.dims[dst_dim];
1344 ++num_size_one_inner_dims;
1351 IndexType input_offset = src.offset;
1352 IndexType output_offset = dst.offset;
1354 constexpr int at_least_1_dim = NumDims <= 1 ? 1 : NumDims - 1;
1355 array<BlockIteratorState, at_least_1_dim> it;
1359 for (
int i = num_size_one_inner_dims; i < NumDims - 1; ++i) {
1360 const int dst_dim = IsColMajor ? i + 1 : NumDims - i - 2;
1361 if (dst.dims[dst_dim] == 1)
continue;
1363 it[idx].size = dst.dims[dst_dim];
1364 it[idx].input_stride = src.strides[dim_map[dst_dim]];
1365 it[idx].output_stride = dst.strides[dst_dim];
1367 it[idx].input_span = it[idx].input_stride * (it[idx].size - 1);
1368 it[idx].output_span = it[idx].output_stride * (it[idx].size - 1);
1374 const IndexType block_total_size = NumDims == 0 ? 1 : dst.dims.TotalSize();
1376#define COPY_INNER_DIM(KIND) \
1377 IndexType num_copied = 0; \
1378 for (num_copied = 0; num_copied < block_total_size; num_copied += dst_inner_dim_size) { \
1379 LinCopy::template Run<KIND>(typename LinCopy::Dst(output_offset, output_stride, dst.data), \
1380 typename LinCopy::Src(input_offset, input_stride, src.data), dst_inner_dim_size); \
1382 for (int j = 0; j < idx; ++j) { \
1383 if (++it[j].count < it[j].size) { \
1384 input_offset += it[j].input_stride; \
1385 output_offset += it[j].output_stride; \
1389 input_offset -= it[j].input_span; \
1390 output_offset -= it[j].output_span; \
1395 if (input_stride == 1 && output_stride == 1) {
1396 COPY_INNER_DIM(LinCopy::Kind::Linear);
1397 }
else if (input_stride == 1 && output_stride == -1) {
1398 COPY_INNER_DIM(LinCopy::Kind::ReverseStore);
1399 }
else if (input_stride == -1 && output_stride == 1) {
1400 COPY_INNER_DIM(LinCopy::Kind::ReverseLoad);
1401 }
else if (input_stride == -1 && output_stride == -1) {
1402 COPY_INNER_DIM(LinCopy::Kind::ReverseBoth);
1403 }
else if (input_stride == 1 && output_stride != 1) {
1404 COPY_INNER_DIM(LinCopy::Kind::Scatter);
1405 }
else if (input_stride == 0 && output_stride == 1) {
1406 COPY_INNER_DIM(LinCopy::Kind::FillLinear);
1407 }
else if (input_stride == 0 && output_stride != 1) {
1408 COPY_INNER_DIM(LinCopy::Kind::FillScatter);
1409 }
else if (output_stride == 1) {
1410 COPY_INNER_DIM(LinCopy::Kind::Gather);
1412 COPY_INNER_DIM(LinCopy::Kind::Random);
1415#undef COPY_INNER_DIM
1420 static EIGEN_DEVICE_FUNC EIGEN_ALWAYS_INLINE IndexType Copy(
const Dst& dst,
const Src& src) {
1421 DimensionsMap dst_to_src_map;
1422 for (
int i = 0; i < NumDims; ++i) dst_to_src_map[i] = i;
1423 return Copy(dst, src, dst_to_src_map);
1427 struct BlockIteratorState {
1428 BlockIteratorState() =
default;
1431 IndexType count = 0;
1432 IndexType input_stride = 0;
1433 IndexType output_stride = 0;
1434 IndexType input_span = 0;
1435 IndexType output_span = 0;
1441 static int NumSqueezableInnerDims(
const DimensionsMap& dim_map) {
1442 int num_squeezable_dims = 0;
1443 for (
int i = 0; i < NumDims; ++i) {
1444 const int dim = IsColMajor ? i : NumDims - i - 1;
1445 if (dim_map[dim] != dim)
break;
1446 num_squeezable_dims++;
1448 return num_squeezable_dims;
1455template <
typename XprType>
1456struct TensorBlockRead {
1457 static constexpr bool Supported =
false;
1458 using Expression = XprType;
1459 using Index =
typename XprType::Index;
1460 explicit TensorBlockRead(
const XprType& expression) : m_expression(expression) {}
1461 Index innerSize()
const {
return NumTraits<Index>::highest(); }
1462 const Expression& expr(Index, Index)
const {
return m_expression; }
1465 const XprType& m_expression;
1468template <
typename Scalar,
int NumDims,
int Layout,
typename Index>
1469struct TensorBlockRead<TensorBlockView<Scalar, NumDims, Layout, Index>> {
1470 static constexpr bool Supported =
true;
1471 using XprType = TensorBlockView<Scalar, NumDims, Layout, Index>;
1472 using Expression = TensorBlockView<Scalar, 1, Layout, Index>;
1473 explicit TensorBlockRead(
const XprType& expression) : m_evaluator(expression, m_device), m_inner_size(1) {
1474 for (
int i = 0; i < NumDims; ++i) {
1475 const int dim = Layout ==
ColMajor ? i : NumDims - 1 - i;
1476 if (expression.dimensions()[dim] > 1 && expression.strides()[dim] != m_inner_size)
break;
1477 m_inner_size *= expression.dimensions()[dim];
1480 Index innerSize()
const {
return m_inner_size; }
1481 Expression expr(Index offset, Index size)
const {
1482 return Expression(m_evaluator.coeffAddress(offset), DSizes<Index, 1>(size));
1486 DefaultDevice m_device;
1487 TensorEvaluator<const XprType, DefaultDevice> m_evaluator;
1492template <
typename Functor>
1493class TensorBlockReadFunctor {
1495 explicit TensorBlockReadFunctor(
const Functor& functor) : m_functor(&functor) {}
1496 template <
typename... Args>
1497 EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE
auto operator()(Args&&... args)
const
1498 ->
decltype(std::declval<const Functor&>()(std::forward<Args>(args)...)) {
1499 return (*m_functor)(std::forward<Args>(args)...);
1501 template <
typename... Args,
typename F = Functor>
1502 EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE
auto packetOp(Args&&... args)
const
1503 ->
decltype(std::declval<const F&>().packetOp(std::forward<Args>(args)...)) {
1504 return m_functor->packetOp(std::forward<Args>(args)...);
1508 const Functor* m_functor;
1511template <
typename Functor>
1512struct functor_traits<TensorBlockReadFunctor<Functor>> : functor_traits<Functor> {};
1514template <
typename UnaryOp,
typename Arg>
1515struct TensorBlockRead<TensorCwiseUnaryOp<UnaryOp, Arg>> {
1516 using ArgRead = TensorBlockRead<remove_all_t<Arg>>;
1517 static constexpr bool Supported = ArgRead::Supported;
1518 using XprType = TensorCwiseUnaryOp<UnaryOp, Arg>;
1519 using Expression = TensorCwiseUnaryOp<TensorBlockReadFunctor<UnaryOp>,
const typename ArgRead::Expression>;
1520 using Index =
typename XprType::Index;
1521 explicit TensorBlockRead(
const XprType& expression)
1522 : m_arg(expression.nestedExpression()), m_functor(expression.functor()) {}
1523 Index innerSize()
const {
return m_arg.innerSize(); }
1524 Expression expr(Index offset, Index size)
const {
1525 return Expression(m_arg.expr(offset, size), TensorBlockReadFunctor<UnaryOp>(m_functor));
1533template <
typename BinaryOp,
typename Left,
typename Right>
1534struct TensorBlockRead<TensorCwiseBinaryOp<BinaryOp, Left, Right>> {
1535 using LeftRead = TensorBlockRead<remove_all_t<Left>>;
1536 using RightRead = TensorBlockRead<remove_all_t<Right>>;
1537 static constexpr bool Supported = LeftRead::Supported && RightRead::Supported;
1538 using XprType = TensorCwiseBinaryOp<BinaryOp, Left, Right>;
1539 using Expression = TensorCwiseBinaryOp<TensorBlockReadFunctor<BinaryOp>,
const typename LeftRead::Expression,
1540 const typename RightRead::Expression>;
1541 using Index =
typename XprType::Index;
1542 explicit TensorBlockRead(
const XprType& expression)
1543 : m_left(expression.lhsExpression()), m_right(expression.rhsExpression()), m_functor(expression.functor()) {}
1544 Index innerSize()
const {
return numext::mini(m_left.innerSize(), m_right.innerSize()); }
1545 Expression expr(Index offset, Index size)
const {
1546 return Expression(m_left.expr(offset, size), m_right.expr(offset, size),
1547 TensorBlockReadFunctor<BinaryOp>(m_functor));
1556template <
typename NullaryOp,
typename Arg>
1557struct TensorBlockRead<TensorCwiseNullaryOp<NullaryOp, Arg>> {
1558 using XprType = TensorCwiseNullaryOp<NullaryOp, Arg>;
1559 using Evaluator = TensorEvaluator<const XprType, DefaultDevice>;
1560 static constexpr bool Supported = Evaluator::IndexIndependentFunctor;
1561 using Index =
typename XprType::Index;
1562 using RunView = TensorBlockView<typename XprType::Scalar, 1, traits<XprType>::Layout, Index>;
1563 using Expression = TensorCwiseNullaryOp<NullaryOp, const RunView>;
1564 explicit TensorBlockRead(
const XprType& expression) : m_functor(expression.functor()) {}
1565 Index innerSize()
const {
return NumTraits<Index>::highest(); }
1566 Expression expr(Index, Index size)
const {
return Expression(RunView(
nullptr, DSizes<Index, 1>(size)), m_functor); }
1569 NullaryOp m_functor;
1572template <
typename TernaryOp,
typename Arg1,
typename Arg2,
typename Arg3>
1573struct TensorBlockRead<TensorCwiseTernaryOp<TernaryOp, Arg1, Arg2, Arg3>> {
1574 using Arg1Read = TensorBlockRead<remove_all_t<Arg1>>;
1575 using Arg2Read = TensorBlockRead<remove_all_t<Arg2>>;
1576 using Arg3Read = TensorBlockRead<remove_all_t<Arg3>>;
1577 static constexpr bool Supported = Arg1Read::Supported && Arg2Read::Supported && Arg3Read::Supported;
1578 using XprType = TensorCwiseTernaryOp<TernaryOp, Arg1, Arg2, Arg3>;
1579 using Expression = TensorCwiseTernaryOp<TensorBlockReadFunctor<TernaryOp>,
const typename Arg1Read::Expression,
1580 const typename Arg2Read::Expression,
const typename Arg3Read::Expression>;
1581 using Index =
typename XprType::Index;
1582 explicit TensorBlockRead(
const XprType& expression)
1583 : m_arg1(expression.arg1Expression()),
1584 m_arg2(expression.arg2Expression()),
1585 m_arg3(expression.arg3Expression()),
1586 m_functor(expression.functor()) {}
1587 Index innerSize()
const {
1588 return numext::mini(m_arg1.innerSize(), numext::mini(m_arg2.innerSize(), m_arg3.innerSize()));
1590 Expression expr(Index offset, Index size)
const {
1591 return Expression(m_arg1.expr(offset, size), m_arg2.expr(offset, size), m_arg3.expr(offset, size),
1592 TensorBlockReadFunctor<TernaryOp>(m_functor));
1599 TernaryOp m_functor;
1602template <
typename Cond,
typename Then,
typename Else>
1603struct TensorBlockRead<TensorSelectOp<Cond, Then, Else>> {
1604 using CondRead = TensorBlockRead<remove_all_t<Cond>>;
1605 using ThenRead = TensorBlockRead<remove_all_t<Then>>;
1606 using ElseRead = TensorBlockRead<remove_all_t<Else>>;
1607 static constexpr bool Supported = CondRead::Supported && ThenRead::Supported && ElseRead::Supported;
1608 using XprType = TensorSelectOp<Cond, Then, Else>;
1609 using Expression = TensorSelectOp<
const typename CondRead::Expression,
const typename ThenRead::Expression,
1610 const typename ElseRead::Expression>;
1611 using Index =
typename XprType::Index;
1612 explicit TensorBlockRead(
const XprType& expression)
1613 : m_cond(expression.ifExpression()), m_then(expression.thenExpression()), m_else(expression.elseExpression()) {}
1614 Index innerSize()
const {
1615 return numext::mini(m_cond.innerSize(), numext::mini(m_then.innerSize(), m_else.innerSize()));
1617 Expression expr(Index offset, Index size)
const {
1618 return Expression(m_cond.expr(offset, size), m_then.expr(offset, size), m_else.expr(offset, size));
1627template <
typename Scalar,
typename Arg>
1628struct TensorBlockRead<TensorConversionOp<Scalar, Arg>> {
1629 using ArgRead = TensorBlockRead<remove_all_t<Arg>>;
1630 static constexpr bool Supported = ArgRead::Supported;
1631 using XprType = TensorConversionOp<Scalar, Arg>;
1632 using Expression = TensorConversionOp<Scalar, const typename ArgRead::Expression>;
1633 using Index =
typename XprType::Index;
1634 explicit TensorBlockRead(
const XprType& expression) : m_arg(expression.expression()) {}
1635 Index innerSize()
const {
return m_arg.innerSize(); }
1636 Expression expr(Index offset, Index size)
const {
return Expression(m_arg.expr(offset, size)); }
1660template <
typename Scalar,
int NumDims,
typename TensorBlockExpr,
typename IndexType = Eigen::Index>
1661class TensorBlockAssignment {
1663 using TensorBlockEvaluator = TensorEvaluator<const TensorBlockExpr, DefaultDevice>;
1665 using Dimensions = DSizes<IndexType, NumDims>;
1666 using BlockRead = TensorBlockRead<TensorBlockExpr>;
1668 enum { Vectorizable = packet_traits<Scalar>::Vectorizable, PacketSize = packet_traits<Scalar>::size };
1670 template <
bool Vectorizable,
typename Evaluator>
1671 struct InnerDimAssign {
1672 EIGEN_ALWAYS_INLINE
static void Run(Scalar* target, IndexType count,
const Evaluator& eval, IndexType eval_offset) {
1673 for (IndexType i = 0; i < count; ++i) {
1674 target[i] = eval.coeff(eval_offset + i);
1679 template <
typename Evaluator>
1680 struct InnerDimAssign<true, Evaluator> {
1681 EIGEN_ALWAYS_INLINE
static void Run(Scalar* target, IndexType count,
const Evaluator& eval, IndexType eval_offset) {
1682 using Packet =
typename packet_traits<Scalar>::type;
1684 const IndexType unrolled_size = (4 * PacketSize) * (count / (4 * PacketSize));
1685 const IndexType vectorized_size = PacketSize * (count / PacketSize);
1688 for (; i < unrolled_size; i += 4 * PacketSize) {
1689 for (
int j = 0; j < 4; ++j) {
1690 const IndexType idx = eval_offset + i + j * PacketSize;
1691 Packet p = eval.template packet<Unaligned>(idx);
1692 pstoreu<Scalar>(target + i + j * PacketSize, p);
1696 for (; i < vectorized_size; i += PacketSize) {
1697 Packet p = eval.template packet<Unaligned>(eval_offset + i);
1698 pstoreu<Scalar>(target + i, p);
1701 for (; i < count; ++i) {
1702 target[i] = eval.coeff(eval_offset + i);
1707 template <
typename Evaluator>
1708 static EIGEN_STRONG_INLINE
void AssignInner(Scalar* target, IndexType count,
const Evaluator& eval,
const BlockRead&,
1709 IndexType offset, std::false_type) {
1710 InnerDimAssign<Vectorizable && Evaluator::PacketAccess, Evaluator>::Run(target, count, eval, offset);
1713 static EIGEN_STRONG_INLINE
void AssignInner(Scalar* target, IndexType count,
const TensorBlockEvaluator&,
1714 const BlockRead& reader, IndexType offset, std::true_type) {
1715 const auto expression = reader.expr(offset, count);
1716 using RunEvaluator = TensorEvaluator<const typename BlockRead::Expression, DefaultDevice>;
1717 const DefaultDevice device;
1718 const RunEvaluator eval(expression, device);
1719 InnerDimAssign<Vectorizable && RunEvaluator::PacketAccess, RunEvaluator>::Run(target, count, eval, 0);
1724 Target(
const Dimensions& target_dims,
const Dimensions& target_strides, Scalar* target_data,
1725 IndexType target_offset = 0)
1726 : dims(target_dims), strides(target_strides), data(target_data), offset(target_offset) {}
1734 static Target target(
const Dimensions& target_dims,
const Dimensions& target_strides, Scalar* target_data,
1735 IndexType target_offset = 0) {
1736 return Target(target_dims, target_strides, target_data, target_offset);
1739 template <
typename TargetDimsIndexType,
typename TargetStr
idesIndexType>
1740 static Target target(
const DSizes<TargetDimsIndexType, NumDims>& target_dims,
1741 const DSizes<TargetStridesIndexType, NumDims>& target_strides, Scalar* target_data,
1742 IndexType target_offset = 0) {
1744 return Target(Dimensions(target_dims), Dimensions(target_strides), target_data, target_offset);
1747 static EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE
void Run(
const Target& target,
const TensorBlockExpr& expr) {
1749 DefaultDevice default_device;
1750 TensorBlockEvaluator eval(expr, default_device);
1751 const BlockRead reader(expr);
1754 eigen_assert(dimensions_match(target.dims, eval.dimensions()));
1756 Run(target, eval, reader, bool_constant<BlockRead::Supported>());
1760 static void Run(
const Target& target,
const TensorBlockEvaluator& eval,
const BlockRead& reader, std::false_type) {
1761 RunImpl<false>(target, eval, reader);
1764 static void Run(
const Target& target,
const TensorBlockEvaluator& eval,
const BlockRead& reader, std::true_type) {
1765 const IndexType size = NumDims == 0 ? 1 : target.dims.TotalSize();
1766 if (reader.innerSize() >= size) {
1768 const auto expression = reader.expr(0, size);
1769 using RunEvaluator = TensorEvaluator<const typename BlockRead::Expression, DefaultDevice>;
1770 const DefaultDevice device;
1771 const RunEvaluator dense_eval(expression, device);
1772 RunImpl<false>(target, dense_eval, reader);
1774 RunImpl<true>(target, eval, reader);
1778 template <
bool UseInnerRuns,
typename Evaluator>
1779 static EIGEN_STRONG_INLINE
void RunImpl(
const Target& target,
const Evaluator& eval,
const BlockRead& reader) {
1780 static constexpr int Layout = Evaluator::Layout;
1781 static constexpr bool is_col_major = Layout ==
ColMajor;
1784 const IndexType output_size = NumDims == 0 ? 1 : target.dims.TotalSize();
1785 constexpr int inner_dim_idx = NumDims == 0 ? 0 : (is_col_major ? 0 : NumDims - 1);
1786 IndexType output_inner_dim_size = NumDims == 0 ? 1 : target.dims[inner_dim_idx];
1789 EIGEN_IF_CONSTEXPR (NumDims > 0) {
1790 eigen_assert(target.strides[inner_dim_idx] == 1);
1794 IndexType num_squeezed_dims = 0;
1795 for (Index i = 1; i < NumDims; ++i) {
1796 const Index dim = is_col_major ? i : NumDims - i - 1;
1797 const IndexType target_stride = target.strides[dim];
1799 if (output_inner_dim_size == target_stride &&
1800 (!UseInnerRuns || output_inner_dim_size * target.dims[dim] <= reader.innerSize())) {
1801 output_inner_dim_size *= target.dims[dim];
1802 num_squeezed_dims++;
1810 array<BlockIteratorState, NumDims> it;
1813 for (Index i = num_squeezed_dims; i < NumDims - 1; ++i) {
1814 const Index dim = is_col_major ? i + 1 : NumDims - i - 2;
1817 it[idx].size = target.dims[dim];
1818 it[idx].output_stride = target.strides[dim];
1819 it[idx].output_span = it[idx].output_stride * (it[idx].size - 1);
1825 IndexType input_offset = 0;
1826 IndexType output_offset = target.offset;
1829 for (IndexType i = 0; i < output_size; i += output_inner_dim_size) {
1831 AssignInner(target.data + output_offset, output_inner_dim_size, eval, reader, input_offset,
1832 bool_constant<UseInnerRuns>());
1835 input_offset += output_inner_dim_size;
1838 for (
int j = 0; j < idx; ++j) {
1839 if (++it[j].count < it[j].size) {
1840 output_offset += it[j].output_stride;
1844 output_offset -= it[j].output_span;
1850 struct BlockIteratorState {
1851 BlockIteratorState() =
default;
1853 IndexType count = 0;
1855 IndexType output_stride = 0;
1856 IndexType output_span = 0;
Namespace containing all symbols from the Eigen library.
The tensor evaluator class.
Definition TensorEvaluator.h:47