Eigen-Contrib  5.0.1-dev+master
 
Loading...
Searching...
No Matches
TensorConcatenation.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_CONCATENATION_H
12#define EIGEN_TENSOR_TENSOR_CONCATENATION_H
13
14// IWYU pragma: private
15#include "./InternalHeaderCheck.h"
16
17namespace Eigen {
18
19namespace internal {
20template <typename Axis, typename LhsXprType, typename RhsXprType>
21struct traits<TensorConcatenationOp<Axis, LhsXprType, RhsXprType>> {
22 // Type promotion to handle the case where the types of the lhs and the rhs are different.
23 using Scalar = typename promote_storage_type<typename LhsXprType::Scalar, typename RhsXprType::Scalar>::ret;
24 using StorageKind = typename promote_storage_type<typename traits<LhsXprType>::StorageKind,
25 typename traits<RhsXprType>::StorageKind>::ret;
26 using Index =
27 typename promote_index_type<typename traits<LhsXprType>::Index, typename traits<RhsXprType>::Index>::type;
28 static constexpr int NumDimensions = traits<LhsXprType>::NumDimensions;
29 static constexpr int Layout = traits<LhsXprType>::Layout;
30 enum { Flags = 0 };
31 using PointerType =
32 std::conditional_t<Pointer_type_promotion<typename LhsXprType::Scalar, Scalar>::val,
33 typename traits<LhsXprType>::PointerType, typename traits<RhsXprType>::PointerType>;
34};
35
36template <typename Axis, typename LhsXprType, typename RhsXprType>
37struct eval<TensorConcatenationOp<Axis, LhsXprType, RhsXprType>, Eigen::Dense> {
38 using type = const TensorConcatenationOp<Axis, LhsXprType, RhsXprType>&;
39};
40
41} // end namespace internal
42
48template <typename Axis, typename LhsXprType, typename RhsXprType>
49class TensorConcatenationOp : public TensorBase<TensorConcatenationOp<Axis, LhsXprType, RhsXprType>, WriteAccessors> {
50 public:
52 using Scalar = typename internal::traits<TensorConcatenationOp>::Scalar;
53 using StorageKind = typename internal::traits<TensorConcatenationOp>::StorageKind;
54 using Index = typename internal::traits<TensorConcatenationOp>::Index;
55 using Nested = typename internal::ref_selector<TensorConcatenationOp>::type;
56 using CoeffReturnType = typename internal::promote_storage_type<typename LhsXprType::CoeffReturnType,
57 typename RhsXprType::CoeffReturnType>::ret;
58 using RealScalar = typename NumTraits<Scalar>::Real;
59
60 EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE TensorConcatenationOp(const LhsXprType& lhs, const RhsXprType& rhs, Axis axis)
61 : m_lhs_xpr(lhs), m_rhs_xpr(rhs), m_axis(axis) {}
62
63 EIGEN_DEVICE_FUNC const internal::remove_all_t<typename LhsXprType::Nested>& lhsExpression() const {
64 return m_lhs_xpr;
65 }
66
67 EIGEN_DEVICE_FUNC const internal::remove_all_t<typename RhsXprType::Nested>& rhsExpression() const {
68 return m_rhs_xpr;
69 }
70
71 EIGEN_DEVICE_FUNC const Axis& axis() const { return m_axis; }
72
73 EIGEN_INHERIT_ASSIGNMENT_OPERATORS(TensorConcatenationOp)
74 protected:
75 typename LhsXprType::Nested m_lhs_xpr;
76 typename RhsXprType::Nested m_rhs_xpr;
77 const Axis m_axis;
78};
79
80// Eval as rvalue
81template <typename Axis, typename LeftArgType, typename RightArgType, typename Device>
82struct TensorEvaluator<const TensorConcatenationOp<Axis, LeftArgType, RightArgType>, Device> {
84 using Index = typename XprType::Index;
85 static constexpr int NumDims = internal::array_size<typename TensorEvaluator<LeftArgType, Device>::Dimensions>::value;
86 static constexpr int RightNumDims =
87 internal::array_size<typename TensorEvaluator<RightArgType, Device>::Dimensions>::value;
88 using Dimensions = DSizes<Index, NumDims>;
89 using Scalar = typename XprType::Scalar;
90 using CoeffReturnType = typename XprType::CoeffReturnType;
91 using PacketReturnType = typename PacketType<CoeffReturnType, Device>::type;
92 using Storage = StorageMemory<CoeffReturnType, Device>;
93 using EvaluatorPointerType = typename Storage::Type;
94 static constexpr int Layout = TensorEvaluator<LeftArgType, Device>::Layout;
95 enum {
96 IsAligned = false,
97 PacketAccess =
98 TensorEvaluator<LeftArgType, Device>::PacketAccess && TensorEvaluator<RightArgType, Device>::PacketAccess,
99 // block() reads each operand's data() pointer directly, so both must
100 // expose raw storage. Scalar-changing block consumers
101 // (TensorCwiseUnaryOp, TensorConversionOp) drop the forwarded destination
102 // buffer before reaching us, so prepareStorage always sees either a
103 // matching-Scalar buffer or no buffer at all.
105 // Matches TensorShuffling / TensorBroadcasting / TensorPadding: bulk copy
106 // wins over the per-element coeff/packet path (which pays div/mod per
107 // access) at every size we benchmarked, so always prefer block.
108 PreferBlockAccess = true,
109 RawAccess = false
110 };
111
112 using ScalarNoConst = std::remove_const_t<Scalar>;
113
114 //===- Tensor block evaluation strategy (see TensorBlock.h) -------------===//
115 using TensorBlockDesc = internal::TensorBlockDescriptor<NumDims, Index>;
116 using TensorBlockScratch = internal::TensorBlockScratchAllocator<Device>;
117
118 using TensorBlock = typename internal::TensorMaterializedBlock<ScalarNoConst, NumDims, Layout, Index>;
119 //===--------------------------------------------------------------------===//
120
121 EIGEN_STRONG_INLINE TensorEvaluator(const XprType& op, const Device& device)
122 : m_leftImpl(op.lhsExpression(), device),
123 m_rightImpl(op.rhsExpression(), device),
124 m_device(device),
125 m_axis(op.axis()) {
126 EIGEN_STATIC_ASSERT((static_cast<int>(TensorEvaluator<LeftArgType, Device>::Layout) ==
127 static_cast<int>(TensorEvaluator<RightArgType, Device>::Layout) ||
128 NumDims == 1),
129 YOU_MADE_A_PROGRAMMING_MISTAKE);
130 // TensorConcatenationOp requires both operands to have the same static
131 // rank. Reshape the lower-rank operand explicitly if you need to mix
132 // ranks; see the concatenate() entry in contrib/Eigen/src/Tensor/README.md.
133 EIGEN_STATIC_ASSERT((NumDims == RightNumDims), YOU_MADE_A_PROGRAMMING_MISTAKE);
134 EIGEN_STATIC_ASSERT((NumDims > 0), YOU_MADE_A_PROGRAMMING_MISTAKE);
135
136 eigen_assert(0 <= m_axis && m_axis < NumDims);
137 m_leftAxisSize = m_leftImpl.dimensions()[m_axis];
138 const Dimensions& lhs_dims = m_leftImpl.dimensions();
139 const Dimensions& rhs_dims = m_rightImpl.dimensions();
140 {
141 int i = 0;
142 for (; i < m_axis; ++i) {
143 eigen_assert(lhs_dims[i] >= 0);
144 eigen_assert(lhs_dims[i] == rhs_dims[i]);
145 m_dimensions[i] = lhs_dims[i];
146 }
147 eigen_assert(lhs_dims[i] >= 0); // Now i == m_axis.
148 eigen_assert(rhs_dims[i] >= 0);
149 m_dimensions[i] = lhs_dims[i] + rhs_dims[i];
150 for (++i; i < NumDims; ++i) {
151 eigen_assert(lhs_dims[i] >= 0);
152 eigen_assert(lhs_dims[i] == rhs_dims[i]);
153 m_dimensions[i] = lhs_dims[i];
154 }
155 }
156
157 EIGEN_IF_CONSTEXPR (static_cast<int>(Layout) == static_cast<int>(ColMajor)) {
158 m_leftStrides[0] = 1;
159 m_rightStrides[0] = 1;
160 m_outputStrides[0] = 1;
161
162 for (int j = 1; j < NumDims; ++j) {
163 m_leftStrides[j] = m_leftStrides[j - 1] * lhs_dims[j - 1];
164 m_rightStrides[j] = m_rightStrides[j - 1] * rhs_dims[j - 1];
165 m_outputStrides[j] = m_outputStrides[j - 1] * m_dimensions[j - 1];
166 }
167 } else {
168 m_leftStrides[NumDims - 1] = 1;
169 m_rightStrides[NumDims - 1] = 1;
170 m_outputStrides[NumDims - 1] = 1;
171
172 for (int j = NumDims - 2; j >= 0; --j) {
173 m_leftStrides[j] = m_leftStrides[j + 1] * lhs_dims[j + 1];
174 m_rightStrides[j] = m_rightStrides[j + 1] * rhs_dims[j + 1];
175 m_outputStrides[j] = m_outputStrides[j + 1] * m_dimensions[j + 1];
176 }
177 }
178 }
179
180 EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE const Dimensions& dimensions() const { return m_dimensions; }
181
182 // TODO(phli): Add short-circuit memcpy evaluation if underlying data are linear.
183#ifdef EIGEN_USE_THREADS
184 template <typename EvalSubExprsCallback>
185 EIGEN_STRONG_INLINE void evalSubExprsIfNeededAsync(EvaluatorPointerType, EvalSubExprsCallback done) {
186 m_leftImpl.evalSubExprsIfNeededAsync(
187 nullptr, [this, done](bool) { m_rightImpl.evalSubExprsIfNeededAsync(nullptr, [done](bool) { done(true); }); });
188 }
189#endif // EIGEN_USE_THREADS
190
191 EIGEN_STRONG_INLINE bool evalSubExprsIfNeeded(EvaluatorPointerType) {
192 m_leftImpl.evalSubExprsIfNeeded(nullptr);
193 // The executor does not call cleanup() when evaluation throws, so release the operand evaluated first.
194 EIGEN_TRY { m_rightImpl.evalSubExprsIfNeeded(nullptr); }
195 EIGEN_CATCH(...) {
196 m_leftImpl.cleanup();
197 EIGEN_THROW;
198 }
199 return true;
200 }
201
202 EIGEN_STRONG_INLINE void cleanup() {
203 m_leftImpl.cleanup();
204 m_rightImpl.cleanup();
205 }
206
207 EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE internal::TensorBlockResourceRequirements getResourceRequirements() const {
208 // Target the L1 cache. A block straddling the concat axis is materialized
209 // into a merged scratch slab that the cwise consumer reads straight back;
210 // sizing the block to L1 keeps that round-trip out of the last-level
211 // cache. It also splits an otherwise cache-resident output into many
212 // blocks, so the off-axis ones qualify for the zero-copy view path in
213 // block(). Matches TensorBroadcasting, which likewise targets L1 for its
214 // materialized block path.
215 const size_t target_size = m_device.firstLevelCacheSize();
216 return internal::TensorBlockResourceRequirements::merge(
217 internal::TensorBlockResourceRequirements::skewed<Scalar>(target_size),
218 internal::TensorBlockResourceRequirements::merge(m_leftImpl.getResourceRequirements(),
219 m_rightImpl.getResourceRequirements()));
220 }
221
222 // True when a block of shape `block_dims` is a contiguous run of an operand
223 // whose shape is `operand_dims` -- i.e. it can be addressed as a plain
224 // pointer offset with no per-row stride walk. Mirrors the direct-access test
225 // in TensorMaterializedBlock::materialize().
226 EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE bool isContiguousOperandSlab(const Dimensions& operand_dims,
227 const Dimensions& block_dims) const {
228 static constexpr bool IsColMajor = Layout == static_cast<int>(ColMajor);
229 int matching_inner_dims = 0;
230 for (int i = 0; i < NumDims; ++i) {
231 const int dim = IsColMajor ? i : NumDims - i - 1;
232 if (operand_dims[dim] != block_dims[dim]) break;
233 ++matching_inner_dims;
234 }
235 // Every dimension above the single partial dimension must be of size 1.
236 for (int i = matching_inner_dims + 1; i < NumDims; ++i) {
237 const int dim = IsColMajor ? i : NumDims - i - 1;
238 if (block_dims[dim] != 1) return false;
239 }
240 return true;
241 }
242
243 // Returns a zero-copy view when the block lies within a single operand and
244 // is contiguous there; otherwise materializes the slab(s) with
245 // TensorBlockIO::Copy, which collapses to a memcpy per contiguous slab.
246 EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE TensorBlock block(TensorBlockDesc& desc, TensorBlockScratch& scratch,
247 bool root_of_expr_ast = false) const {
248 static constexpr bool IsColMajor = Layout == static_cast<int>(ColMajor);
249
250 if (desc.size() == 0) {
251 return TensorBlock(internal::TensorBlockKind::kView, nullptr, desc.dimensions());
252 }
253
254 Index remaining = desc.offset();
255 DSizes<Index, NumDims> out_coords;
256 EIGEN_IF_CONSTEXPR (IsColMajor) {
257 for (int i = NumDims - 1; i > 0; --i) {
258 out_coords[i] = remaining / m_outputStrides[i];
259 remaining -= out_coords[i] * m_outputStrides[i];
260 }
261 out_coords[0] = remaining;
262 } else {
263 for (int i = 0; i < NumDims - 1; ++i) {
264 out_coords[i] = remaining / m_outputStrides[i];
265 remaining -= out_coords[i] * m_outputStrides[i];
266 }
267 out_coords[NumDims - 1] = remaining;
268 }
269
270 const Index axis_start = out_coords[m_axis];
271 const Index axis_size = desc.dimension(static_cast<int>(m_axis));
272 const Index axis_end = axis_start + axis_size;
273
274 // Fast path: a block that lies entirely within one operand and forms a
275 // contiguous run of its storage needs no copy at all -- return a view
276 // straight into A / B. This is what keeps a cwise expression that reads
277 // the concatenation (e.g. `(A.concatenate(B, axis) + C)`) streaming: a
278 // cwise consumer drops our destination buffer before calling block() (see
279 // TensorCwiseBinaryOp::block), so without the view the slab would be
280 // bounced through a scratch buffer and read straight back, doubling cache
281 // traffic. Straddling blocks still need the merged buffer materialized
282 // below.
283 if (axis_end <= m_leftAxisSize) {
284 if (isContiguousOperandSlab(m_leftImpl.dimensions(), desc.dimensions())) {
285 Index left_src_offset = 0;
286 for (int i = 0; i < NumDims; ++i) {
287 left_src_offset += out_coords[i] * m_leftStrides[i];
288 }
289 return TensorBlock(internal::TensorBlockKind::kView, m_leftImpl.data() + left_src_offset, desc.dimensions());
290 }
291 } else if (axis_start >= m_leftAxisSize) {
292 if (isContiguousOperandSlab(m_rightImpl.dimensions(), desc.dimensions())) {
293 Index right_src_offset = (axis_start - m_leftAxisSize) * m_rightStrides[m_axis];
294 for (int i = 0; i < NumDims; ++i) {
295 if (i != m_axis) {
296 right_src_offset += out_coords[i] * m_rightStrides[i];
297 }
298 }
299 return TensorBlock(internal::TensorBlockKind::kView, m_rightImpl.data() + right_src_offset, desc.dimensions());
300 }
301 }
302
303 using TensorBlockIO = internal::TensorBlockIO<ScalarNoConst, Index, NumDims, Layout>;
304 using TensorBlockIODst = typename TensorBlockIO::Dst;
305 using TensorBlockIOSrc = typename TensorBlockIO::Src;
306
307 // Strided destination buffers are safe here because we only ever write
308 // dense slabs into them; allowing strided storage lets a root-of-AST
309 // assignment materialize directly into the output tensor.
310 typename TensorBlock::Storage block_storage =
311 TensorBlock::prepareStorage(desc, scratch, /*allow_strided_storage=*/root_of_expr_ast);
312
313 if (axis_start < m_leftAxisSize) {
314 const Index left_rows_in_block = numext::mini(m_leftAxisSize, axis_end) - axis_start;
315 DSizes<Index, NumDims> left_sub_dims = desc.dimensions();
316 left_sub_dims[m_axis] = left_rows_in_block;
317
318 Index left_src_offset = 0;
319 for (int i = 0; i < NumDims; ++i) {
320 left_src_offset += out_coords[i] * m_leftStrides[i];
321 }
322
323 typename TensorBlockIO::Dimensions left_strides(m_leftStrides);
324 TensorBlockIOSrc src(left_strides, m_leftImpl.data(), left_src_offset);
325 TensorBlockIODst dst(left_sub_dims, block_storage.strides(), block_storage.data(),
326 /*dst_offset=*/0);
327 TensorBlockIO::Copy(dst, src);
328 }
329
330 if (axis_end > m_leftAxisSize) {
331 const Index right_rows_in_block = axis_end - numext::maxi(m_leftAxisSize, axis_start);
332 DSizes<Index, NumDims> right_sub_dims = desc.dimensions();
333 right_sub_dims[m_axis] = right_rows_in_block;
334
335 // Right operand has the same per-dim coords as out_coords except along
336 // the concat axis, where it starts at max(0, axis_start - left_size).
337 const Index right_axis_start = numext::maxi(Index(0), axis_start - m_leftAxisSize);
338 Index right_src_offset = right_axis_start * m_rightStrides[m_axis];
339 for (int i = 0; i < NumDims; ++i) {
340 if (i != m_axis) {
341 right_src_offset += out_coords[i] * m_rightStrides[i];
342 }
343 }
344
345 // Offset within the materialized buffer where the right-side slab starts.
346 const Index dst_axis_offset = numext::maxi(Index(0), m_leftAxisSize - axis_start);
347 const Index dst_offset = dst_axis_offset * block_storage.strides()[m_axis];
348
349 typename TensorBlockIO::Dimensions right_strides(m_rightStrides);
350 TensorBlockIOSrc src(right_strides, m_rightImpl.data(), right_src_offset);
351 TensorBlockIODst dst(right_sub_dims, block_storage.strides(), block_storage.data(), dst_offset);
352 TensorBlockIO::Copy(dst, src);
353 }
354
355 return block_storage.AsTensorMaterializedBlock();
356 }
357
358 // The per-dim integer div/mod in this loop are the obvious "slow" candidates,
359 // but the same TensorIntDivisor substitution was measured net-negative on
360 // Intel Raptor Lake when prototyped for TensorBroadcasting (see the comment
361 // on TensorBroadcasting::indexColMajor). Modern x86 hardware div (~20
362 // cycles) amortizes well and the mul+shifts don't win back the added state.
363 EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE CoeffReturnType coeff(Index index) const {
364 // Collect dimension-wise indices (subs).
365 array<Index, NumDims> subs;
366 EIGEN_IF_CONSTEXPR (static_cast<int>(Layout) == static_cast<int>(ColMajor)) {
367 for (int i = NumDims - 1; i > 0; --i) {
368 subs[i] = index / m_outputStrides[i];
369 index -= subs[i] * m_outputStrides[i];
370 }
371 subs[0] = index;
372 } else {
373 for (int i = 0; i < NumDims - 1; ++i) {
374 subs[i] = index / m_outputStrides[i];
375 index -= subs[i] * m_outputStrides[i];
376 }
377 subs[NumDims - 1] = index;
378 }
379
380 const Dimensions& left_dims = m_leftImpl.dimensions();
381 if (subs[m_axis] < left_dims[m_axis]) {
382 Index left_index;
383 EIGEN_IF_CONSTEXPR (static_cast<int>(Layout) == static_cast<int>(ColMajor)) {
384 left_index = subs[0];
385 EIGEN_UNROLL_LOOP
386 for (int i = 1; i < NumDims; ++i) {
387 left_index += (subs[i] % left_dims[i]) * m_leftStrides[i];
388 }
389 } else {
390 left_index = subs[NumDims - 1];
391 EIGEN_UNROLL_LOOP
392 for (int i = NumDims - 2; i >= 0; --i) {
393 left_index += (subs[i] % left_dims[i]) * m_leftStrides[i];
394 }
395 }
396 return m_leftImpl.coeff(left_index);
397 } else {
398 subs[m_axis] -= left_dims[m_axis];
399 const Dimensions& right_dims = m_rightImpl.dimensions();
400 Index right_index;
401 EIGEN_IF_CONSTEXPR (static_cast<int>(Layout) == static_cast<int>(ColMajor)) {
402 right_index = subs[0];
403 EIGEN_UNROLL_LOOP
404 for (int i = 1; i < NumDims; ++i) {
405 right_index += (subs[i] % right_dims[i]) * m_rightStrides[i];
406 }
407 } else {
408 right_index = subs[NumDims - 1];
409 EIGEN_UNROLL_LOOP
410 for (int i = NumDims - 2; i >= 0; --i) {
411 right_index += (subs[i] % right_dims[i]) * m_rightStrides[i];
412 }
413 }
414 return m_rightImpl.coeff(right_index);
415 }
416 }
417
418 // When the packet sits entirely on one side of the concat boundary, delegate
419 // to that operand's packet<>() rather than assembling PacketSize coeff()
420 // calls. The packet stays on one side iff only the innermost dim varies
421 // across the packet -- i.e. all other subs match between the first and last
422 // index. When that holds, subs[m_axis] is either constant (m_axis is not
423 // innermost) or monotonic non-decreasing (m_axis is innermost), so checking
424 // just the endpoints decides the side. Otherwise subs[m_axis] can wrap back
425 // through the boundary mid-packet (as when the inner dim has fewer than
426 // PacketSize elements and the packet spills past the concat axis), so fall
427 // back to scalars.
428 template <int LoadMode>
429 EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE PacketReturnType packet(Index index) const {
430 const int packetSize = PacketType<CoeffReturnType, Device>::size;
431 EIGEN_STATIC_ASSERT((packetSize > 1), YOU_MADE_A_PROGRAMMING_MISTAKE)
432 eigen_assert(index + packetSize - 1 < dimensions().TotalSize());
433
434 array<Index, NumDims> subs;
435 array<Index, NumDims> subs_end;
436 Index remaining = index;
437 Index remaining_end = index + packetSize - 1;
438 EIGEN_IF_CONSTEXPR (static_cast<int>(Layout) == static_cast<int>(ColMajor)) {
439 for (int i = NumDims - 1; i > 0; --i) {
440 subs[i] = remaining / m_outputStrides[i];
441 remaining -= subs[i] * m_outputStrides[i];
442 subs_end[i] = remaining_end / m_outputStrides[i];
443 remaining_end -= subs_end[i] * m_outputStrides[i];
444 }
445 subs[0] = remaining;
446 subs_end[0] = remaining_end;
447 } else {
448 for (int i = 0; i < NumDims - 1; ++i) {
449 subs[i] = remaining / m_outputStrides[i];
450 remaining -= subs[i] * m_outputStrides[i];
451 subs_end[i] = remaining_end / m_outputStrides[i];
452 remaining_end -= subs_end[i] * m_outputStrides[i];
453 }
454 subs[NumDims - 1] = remaining;
455 subs_end[NumDims - 1] = remaining_end;
456 }
457
458 const Dimensions& left_dims = m_leftImpl.dimensions();
459 const Index left_axis_size = left_dims[m_axis];
460
461 constexpr int innermost = (static_cast<int>(Layout) == static_cast<int>(ColMajor)) ? 0 : NumDims - 1;
462 bool packet_in_single_inner_row = true;
463 EIGEN_UNROLL_LOOP
464 for (int i = 0; i < NumDims; ++i) {
465 if (i != innermost && subs[i] != subs_end[i]) {
466 packet_in_single_inner_row = false;
467 }
468 }
469
470 const bool on_left =
471 packet_in_single_inner_row && subs[m_axis] < left_axis_size && subs_end[m_axis] < left_axis_size;
472 const bool on_right =
473 packet_in_single_inner_row && subs[m_axis] >= left_axis_size && subs_end[m_axis] >= left_axis_size;
474
475 if (on_left) {
476 Index left_index;
477 EIGEN_IF_CONSTEXPR (static_cast<int>(Layout) == static_cast<int>(ColMajor)) {
478 left_index = subs[0];
479 EIGEN_UNROLL_LOOP
480 for (int i = 1; i < NumDims; ++i) {
481 left_index += subs[i] * m_leftStrides[i];
482 }
483 } else {
484 left_index = subs[NumDims - 1];
485 EIGEN_UNROLL_LOOP
486 for (int i = NumDims - 2; i >= 0; --i) {
487 left_index += subs[i] * m_leftStrides[i];
488 }
489 }
490 return m_leftImpl.template packet<LoadMode>(left_index);
491 }
492 if (on_right) {
493 subs[m_axis] -= left_axis_size;
494 Index right_index;
495 EIGEN_IF_CONSTEXPR (static_cast<int>(Layout) == static_cast<int>(ColMajor)) {
496 right_index = subs[0];
497 EIGEN_UNROLL_LOOP
498 for (int i = 1; i < NumDims; ++i) {
499 right_index += subs[i] * m_rightStrides[i];
500 }
501 } else {
502 right_index = subs[NumDims - 1];
503 EIGEN_UNROLL_LOOP
504 for (int i = NumDims - 2; i >= 0; --i) {
505 right_index += subs[i] * m_rightStrides[i];
506 }
507 }
508 return m_rightImpl.template packet<LoadMode>(right_index);
509 }
510
511 // The packet straddles the boundary or spans multiple inner rows: fall
512 // back to assembling scalars.
513 EIGEN_ALIGN_TO_BOUNDARY(internal::unpacket_traits<PacketReturnType>::alignment) CoeffReturnType values[packetSize];
514 EIGEN_UNROLL_LOOP
515 for (int i = 0; i < packetSize; ++i) {
516 values[i] = coeff(index + i);
517 }
518 PacketReturnType rslt = internal::pload<PacketReturnType>(values);
519 return rslt;
520 }
521
522 EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE TensorOpCost costPerCoeff(bool vectorized) const {
523 const double compute_cost = NumDims * (2 * TensorOpCost::AddCost<Index>() + 2 * TensorOpCost::MulCost<Index>() +
524 TensorOpCost::DivCost<Index>() + TensorOpCost::ModCost<Index>());
525 const double lhs_size = m_leftImpl.dimensions().TotalSize();
526 const double rhs_size = m_rightImpl.dimensions().TotalSize();
527 return (lhs_size / (lhs_size + rhs_size)) * m_leftImpl.costPerCoeff(vectorized) +
528 (rhs_size / (lhs_size + rhs_size)) * m_rightImpl.costPerCoeff(vectorized) + TensorOpCost(0, 0, compute_cost);
529 }
530
531 EIGEN_DEVICE_FUNC EvaluatorPointerType data() const { return nullptr; }
532
533 protected:
534 Dimensions m_dimensions;
535 array<Index, NumDims> m_outputStrides;
536 array<Index, NumDims> m_leftStrides;
537 array<Index, NumDims> m_rightStrides;
538 TensorEvaluator<LeftArgType, Device> m_leftImpl;
539 TensorEvaluator<RightArgType, Device> m_rightImpl;
540 const Device EIGEN_DEVICE_REF m_device;
541 const Axis m_axis;
542 Index m_leftAxisSize;
543};
544
545// Eval as lvalue
546template <typename Axis, typename LeftArgType, typename RightArgType, typename Device>
547struct TensorEvaluator<TensorConcatenationOp<Axis, LeftArgType, RightArgType>, Device>
548 : public TensorEvaluator<const TensorConcatenationOp<Axis, LeftArgType, RightArgType>, Device> {
549 using Base = TensorEvaluator<const TensorConcatenationOp<Axis, LeftArgType, RightArgType>, Device>;
550 using XprType = TensorConcatenationOp<Axis, LeftArgType, RightArgType>;
551 using Dimensions = typename Base::Dimensions;
552 static constexpr int NumDims = Base::NumDims;
553 static constexpr int Layout = TensorEvaluator<LeftArgType, Device>::Layout;
554 enum {
555 IsAligned = false,
556 PacketAccess =
557 TensorEvaluator<LeftArgType, Device>::PacketAccess && TensorEvaluator<RightArgType, Device>::PacketAccess,
558 // writeBlock() splits the block at the concat axis and copies each piece
559 // straight into the operand's buffer, so both must expose raw storage.
560 BlockAccess = TensorEvaluator<LeftArgType, Device>::RawAccess && TensorEvaluator<RightArgType, Device>::RawAccess,
561 // The coeff/packet write path pays a div/mod cascade plus a per-dim mod
562 // for every scalar; the block path is a pair of bulk copies. Mirrors the
563 // rvalue evaluator.
564 PreferBlockAccess = true,
565 RawAccess = false
566 };
567
568 using ScalarNoConst = std::remove_const_t<typename XprType::Scalar>;
569
570 //===- Tensor block evaluation strategy (see TensorBlock.h) -------------===//
571 using TensorBlockDesc = internal::TensorBlockDescriptor<NumDims, typename XprType::Index>;
572 //===--------------------------------------------------------------------===//
573
574 // The ColMajor-only static_assert lives in coeffRef/writePacket rather than
575 // here so that passthrough evaluators (e.g. TensorSlicingOp's) can
576 // instantiate this type for RowMajor concat operands without ever calling
577 // its lvalue methods. writeBlock() below is layout-generic, so tiled
578 // assignments through a RowMajor concatenation are supported.
579 EIGEN_STRONG_INLINE TensorEvaluator(const XprType& op, const Device& device) : Base(op, device) {}
580
581 using Index = typename XprType::Index;
582 using Scalar = typename XprType::Scalar;
583 using CoeffReturnType = typename XprType::CoeffReturnType;
584 using PacketReturnType = typename PacketType<CoeffReturnType, Device>::type;
585
586 EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE CoeffReturnType& coeffRef(Index index) const {
587 EIGEN_STATIC_ASSERT((static_cast<int>(Layout) == static_cast<int>(ColMajor)), YOU_MADE_A_PROGRAMMING_MISTAKE);
588 // Collect dimension-wise indices (subs).
589 array<Index, Base::NumDims> subs;
590 for (int i = Base::NumDims - 1; i > 0; --i) {
591 subs[i] = index / this->m_outputStrides[i];
592 index -= subs[i] * this->m_outputStrides[i];
593 }
594 subs[0] = index;
595
596 const Dimensions& left_dims = this->m_leftImpl.dimensions();
597 if (subs[this->m_axis] < left_dims[this->m_axis]) {
598 Index left_index = subs[0];
599 for (int i = 1; i < Base::NumDims; ++i) {
600 left_index += (subs[i] % left_dims[i]) * this->m_leftStrides[i];
601 }
602 return this->m_leftImpl.coeffRef(left_index);
603 } else {
604 subs[this->m_axis] -= left_dims[this->m_axis];
605 const Dimensions& right_dims = this->m_rightImpl.dimensions();
606 Index right_index = subs[0];
607 for (int i = 1; i < Base::NumDims; ++i) {
608 right_index += (subs[i] % right_dims[i]) * this->m_rightStrides[i];
609 }
610 return this->m_rightImpl.coeffRef(right_index);
611 }
612 }
613
614 template <int StoreMode>
615 EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE void writePacket(Index index, const PacketReturnType& x) const {
616 EIGEN_STATIC_ASSERT((static_cast<int>(Layout) == static_cast<int>(ColMajor)), YOU_MADE_A_PROGRAMMING_MISTAKE);
617 const int packetSize = PacketType<CoeffReturnType, Device>::size;
618 EIGEN_STATIC_ASSERT((packetSize > 1), YOU_MADE_A_PROGRAMMING_MISTAKE)
619 eigen_assert(index + packetSize - 1 < this->dimensions().TotalSize());
620
621 EIGEN_ALIGN_TO_BOUNDARY(internal::unpacket_traits<PacketReturnType>::alignment) CoeffReturnType values[packetSize];
622 internal::pstore<CoeffReturnType, PacketReturnType>(values, x);
623 for (int i = 0; i < packetSize; ++i) {
624 coeffRef(index + i) = values[i];
625 }
626 }
627
628 // Mirror of the rvalue block(): split the block at the concat axis and copy
629 // each piece into the corresponding operand's buffer.
630 template <typename TensorBlock>
631 EIGEN_STRONG_INLINE void writeBlock(const TensorBlockDesc& desc, const TensorBlock& block) {
632 if (desc.size() == 0) return;
633 eigen_assert(this->m_leftImpl.data() != nullptr && this->m_rightImpl.data() != nullptr);
634
635 const DSizes<Index, NumDims> block_strides = internal::strides<Layout>(desc.dimensions());
636
637 // Materialize the block into a temporary buffer if it is lazy.
638 const ScalarNoConst* block_buffer = block.data();
639 void* mem = nullptr;
640 if (block_buffer == nullptr) {
641 mem = this->m_device.allocate(desc.size() * sizeof(Scalar));
642 ScalarNoConst* buf = static_cast<ScalarNoConst*>(mem);
643
644 using TensorBlockAssignment =
645 internal::TensorBlockAssignment<ScalarNoConst, NumDims, typename TensorBlock::XprType, Index>;
646 TensorBlockAssignment::Run(TensorBlockAssignment::target(desc.dimensions(), block_strides, buf), block.expr());
647
648 block_buffer = buf;
649 }
650
651 // Decompose the block's offset into output coordinates.
652 Index remaining = desc.offset();
653 DSizes<Index, NumDims> out_coords;
654 EIGEN_IF_CONSTEXPR (static_cast<int>(Layout) == static_cast<int>(ColMajor)) {
655 for (int i = NumDims - 1; i > 0; --i) {
656 out_coords[i] = remaining / this->m_outputStrides[i];
657 remaining -= out_coords[i] * this->m_outputStrides[i];
658 }
659 out_coords[0] = remaining;
660 } else {
661 for (int i = 0; i < NumDims - 1; ++i) {
662 out_coords[i] = remaining / this->m_outputStrides[i];
663 remaining -= out_coords[i] * this->m_outputStrides[i];
664 }
665 out_coords[NumDims - 1] = remaining;
666 }
667
668 const Index axis_start = out_coords[this->m_axis];
669 const Index axis_size = desc.dimension(static_cast<int>(this->m_axis));
670 const Index axis_end = axis_start + axis_size;
671 const Index left_axis_size = this->m_leftAxisSize;
672
673 using TensorBlockIO = internal::TensorBlockIO<ScalarNoConst, Index, NumDims, Layout>;
674 using TensorBlockIODst = typename TensorBlockIO::Dst;
675 using TensorBlockIOSrc = typename TensorBlockIO::Src;
676
677 if (axis_start < left_axis_size) {
678 DSizes<Index, NumDims> left_sub_dims = desc.dimensions();
679 left_sub_dims[this->m_axis] = numext::mini(left_axis_size, axis_end) - axis_start;
680
681 Index left_dst_offset = 0;
682 for (int i = 0; i < NumDims; ++i) {
683 left_dst_offset += out_coords[i] * this->m_leftStrides[i];
684 }
685
686 TensorBlockIOSrc src(block_strides, block_buffer, /*src_offset=*/0);
687 TensorBlockIODst dst(left_sub_dims, typename TensorBlockIO::Dimensions(this->m_leftStrides),
688 this->m_leftImpl.data(), left_dst_offset);
689 TensorBlockIO::Copy(dst, src);
690 }
691
692 if (axis_end > left_axis_size) {
693 DSizes<Index, NumDims> right_sub_dims = desc.dimensions();
694 right_sub_dims[this->m_axis] = axis_end - numext::maxi(left_axis_size, axis_start);
695
696 const Index right_axis_start = numext::maxi(Index(0), axis_start - left_axis_size);
697 Index right_dst_offset = right_axis_start * this->m_rightStrides[this->m_axis];
698 for (int i = 0; i < NumDims; ++i) {
699 if (i != this->m_axis) {
700 right_dst_offset += out_coords[i] * this->m_rightStrides[i];
701 }
702 }
703
704 // Offset within the block buffer where the right-side piece starts.
705 const Index src_offset = numext::maxi(Index(0), left_axis_size - axis_start) * block_strides[this->m_axis];
706
707 TensorBlockIOSrc src(block_strides, block_buffer, src_offset);
708 TensorBlockIODst dst(right_sub_dims, typename TensorBlockIO::Dimensions(this->m_rightStrides),
709 this->m_rightImpl.data(), right_dst_offset);
710 TensorBlockIO::Copy(dst, src);
711 }
712
713 // Deallocate temporary buffer used for the block materialization.
714 if (mem != nullptr) this->m_device.deallocate(mem);
715 }
716};
717
718} // end namespace Eigen
719
720#endif // EIGEN_TENSOR_TENSOR_CONCATENATION_H
The tensor base class.
Definition TensorForwardDeclarations.h:69
Tensor concatenation class.
Definition TensorConcatenation.h:49
WriteAccessors
Namespace containing all symbols from the Eigen library.
The tensor evaluator class.
Definition TensorEvaluator.h:47