Eigen-Contrib  5.0.1-dev+master
 
Loading...
Searching...
No Matches
TensorBroadcasting.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_BROADCASTING_H
12#define EIGEN_TENSOR_TENSOR_BROADCASTING_H
13
14// IWYU pragma: private
15#include "./InternalHeaderCheck.h"
16
17namespace Eigen {
18
19namespace internal {
20template <typename Broadcast, typename XprType>
21struct traits<TensorBroadcastingOp<Broadcast, XprType>> : public traits<XprType> {
22 using Scalar = typename XprType::Scalar;
23 using XprTraits = traits<XprType>;
24 using StorageKind = typename XprTraits::StorageKind;
25 using Index = typename XprTraits::Index;
26 static constexpr int NumDimensions = XprTraits::NumDimensions;
27 static constexpr int Layout = XprTraits::Layout;
28 using PointerType = typename XprTraits::PointerType;
29 enum {
30 // Broadcast is read-only.
31 Flags = traits<XprType>::Flags & ~LvalueBit
32 };
33};
34
35template <typename Broadcast, typename XprType>
36struct eval<TensorBroadcastingOp<Broadcast, XprType>, Eigen::Dense> {
37 using type = const TensorBroadcastingOp<Broadcast, XprType> EIGEN_DEVICE_REF;
38};
39
40template <typename Dims>
41struct is_input_scalar : std::false_type {};
42template <>
43struct is_input_scalar<Sizes<>> : std::true_type {};
44template <std::ptrdiff_t... Indices>
45struct is_input_scalar<Sizes<Indices...>> : bool_constant<Sizes<Indices...>::total_size == 1> {};
46
47} // end namespace internal
48
52template <typename Broadcast, typename XprType>
53class TensorBroadcastingOp : public TensorBase<TensorBroadcastingOp<Broadcast, XprType>, ReadOnlyAccessors> {
54 public:
56 using Scalar = typename Eigen::internal::traits<TensorBroadcastingOp>::Scalar;
57 using RealScalar = typename Eigen::NumTraits<Scalar>::Real;
58 using CoeffReturnType = typename XprType::CoeffReturnType;
59 using Nested = typename Eigen::internal::ref_selector<TensorBroadcastingOp>::type;
60 using StorageKind = typename Eigen::internal::traits<TensorBroadcastingOp>::StorageKind;
61 using Index = typename Eigen::internal::traits<TensorBroadcastingOp>::Index;
62
63 EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE TensorBroadcastingOp(const XprType& expr, const Broadcast& broadcast)
64 : m_xpr(expr), m_broadcast(broadcast) {}
65
66 // The accessor below would otherwise hide TensorBase::broadcast(bcast), so broadcast() could not be applied twice.
67 using Base::broadcast;
68 EIGEN_DEVICE_FUNC const Broadcast& broadcast() const { return m_broadcast; }
69
70 EIGEN_DEVICE_FUNC const internal::remove_all_t<typename XprType::Nested>& expression() const { return m_xpr; }
71
72 protected:
73 typename XprType::Nested m_xpr;
74 const Broadcast m_broadcast;
75};
76
77// Eval as rvalue
78template <typename Broadcast, typename ArgType, typename Device>
79struct TensorEvaluator<const TensorBroadcastingOp<Broadcast, ArgType>, Device> {
81 using Index = typename XprType::Index;
82 static constexpr int NumDims = internal::array_size<typename TensorEvaluator<ArgType, Device>::Dimensions>::value;
83 using Dimensions = DSizes<Index, NumDims>;
84 using Scalar = typename XprType::Scalar;
85 using InputDimensions = typename TensorEvaluator<ArgType, Device>::Dimensions;
86 using CoeffReturnType = typename XprType::CoeffReturnType;
87 using PacketReturnType = typename PacketType<CoeffReturnType, Device>::type;
88 static constexpr int PacketSize = PacketType<CoeffReturnType, Device>::size;
89
90 protected: // all the non-static fields must have the same access control, otherwise the TensorEvaluator won't be
91 // standard layout;
92 bool isCopy, nByOne, oneByN;
93
94 public:
95 using Storage = StorageMemory<CoeffReturnType, Device>;
96 using EvaluatorPointerType = typename Storage::Type;
97
98 enum {
99 IsAligned = TensorEvaluator<ArgType, Device>::IsAligned,
100 PacketAccess = TensorEvaluator<ArgType, Device>::PacketAccess,
102 PreferBlockAccess = true,
103 RawAccess = false
104 };
105 static constexpr int Layout = TensorEvaluator<ArgType, Device>::Layout;
106
107 using ScalarNoConst = std::remove_const_t<Scalar>;
108
109 // We do block based broadcasting using a trick with 2x tensor rank and 0
110 // strides. See block method implementation for details.
111 using BroadcastDimensions = DSizes<Index, 2 * NumDims>;
112
113 //===- Tensor block evaluation strategy (see TensorBlock.h) -------------===//
114 using TensorBlockDesc = internal::TensorBlockDescriptor<NumDims, Index>;
115 using TensorBlockScratch = internal::TensorBlockScratchAllocator<Device>;
116
117 using ArgTensorBlock = typename TensorEvaluator<const ArgType, Device>::TensorBlock;
118
119 using TensorBlock = typename internal::TensorMaterializedBlock<ScalarNoConst, NumDims, Layout, Index>;
120 //===--------------------------------------------------------------------===//
121
122 EIGEN_STRONG_INLINE TensorEvaluator(const XprType& op, const Device& device)
123 : isCopy(false),
124 nByOne(false),
125 oneByN(false),
126 m_device(device),
127 m_broadcast(op.broadcast()),
128 m_impl(op.expression(), device) {
129 // The broadcasting op doesn't change the rank of the tensor. One can't broadcast a scalar
130 // and store the result in a scalar. Instead one should reshape the scalar into a N-D
131 // tensor with N >= 1 of 1 element first and then broadcast.
132 EIGEN_STATIC_ASSERT((NumDims > 0), YOU_MADE_A_PROGRAMMING_MISTAKE);
133 const InputDimensions& input_dims = m_impl.dimensions();
134 isCopy = true;
135 for (int i = 0; i < NumDims; ++i) {
136 eigen_assert(input_dims[i] >= 0);
137 m_dimensions[i] = input_dims[i] * m_broadcast[i];
138 if (m_broadcast[i] != 1) {
139 isCopy = false;
140 }
141 }
142
143 EIGEN_IF_CONSTEXPR (static_cast<int>(Layout) == static_cast<int>(ColMajor)) {
144 m_inputStrides[0] = 1;
145 m_outputStrides[0] = 1;
146 for (int i = 1; i < NumDims; ++i) {
147 m_inputStrides[i] = m_inputStrides[i - 1] * input_dims[i - 1];
148 m_outputStrides[i] = m_outputStrides[i - 1] * m_dimensions[i - 1];
149 }
150 } else {
151 m_inputStrides[NumDims - 1] = 1;
152 m_outputStrides[NumDims - 1] = 1;
153 for (int i = NumDims - 2; i >= 0; --i) {
154 m_inputStrides[i] = m_inputStrides[i + 1] * input_dims[i + 1];
155 m_outputStrides[i] = m_outputStrides[i + 1] * m_dimensions[i + 1];
156 }
157 }
158
159 if (input_dims[0] == 1) {
160 oneByN = true;
161 for (int i = 1; i < NumDims; ++i) {
162 if (m_broadcast[i] != 1) {
163 oneByN = false;
164 break;
165 }
166 }
167 } else if (input_dims[NumDims - 1] == 1) {
168 nByOne = true;
169 for (int i = 0; i < NumDims - 1; ++i) {
170 if (m_broadcast[i] != 1) {
171 nByOne = false;
172 break;
173 }
174 }
175 }
176
177 // Handle special format like NCHW, its input shape is '[1, N..., 1]' and
178 // broadcast shape is '[N, 1..., N]'
179 if (!oneByN && !nByOne) {
180 if (input_dims[0] == 1 && input_dims[NumDims - 1] == 1 && NumDims > 2) {
181 nByOne = true;
182 oneByN = true;
183 for (int i = 1; i < NumDims - 1; ++i) {
184 if (m_broadcast[i] != 1) {
185 nByOne = false;
186 oneByN = false;
187 break;
188 }
189 }
190 }
191 }
192 }
193
194 EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE const Dimensions& dimensions() const { return m_dimensions; }
195
196 EIGEN_STRONG_INLINE bool evalSubExprsIfNeeded(EvaluatorPointerType) {
197 m_impl.evalSubExprsIfNeeded(nullptr);
198 return true;
199 }
200
201#ifdef EIGEN_USE_THREADS
202 template <typename EvalSubExprsCallback>
203 EIGEN_STRONG_INLINE void evalSubExprsIfNeededAsync(EvaluatorPointerType, EvalSubExprsCallback done) {
204 m_impl.evalSubExprsIfNeededAsync(nullptr, [done](bool) { done(true); });
205 }
206#endif // EIGEN_USE_THREADS
207
208 EIGEN_STRONG_INLINE void cleanup() { m_impl.cleanup(); }
209
210 EIGEN_DEVICE_FUNC EIGEN_ALWAYS_INLINE CoeffReturnType coeff(Index index) const {
211 EIGEN_IF_CONSTEXPR ((internal::is_input_scalar<internal::remove_all_t<InputDimensions>>::value)) {
212 return m_impl.coeff(0);
213 }
214
215 EIGEN_IF_CONSTEXPR (static_cast<int>(Layout) == static_cast<int>(ColMajor)) {
216 if (isCopy) {
217 return m_impl.coeff(index);
218 } else {
219 return coeffColMajor(index);
220 }
221 } else {
222 if (isCopy) {
223 return m_impl.coeff(index);
224 } else {
225 return coeffRowMajor(index);
226 }
227 }
228 }
229
230 // The per-dim integer div/mod look expensive but amortize well: packet paths
231 // call this once per PacketSize outputs, and modern x86 hardware div is
232 // ~20 cycles. Prototyped replacing div/mod with TensorIntDivisor (the
233 // pattern used in TensorShuffling et al.); measured net-negative on Intel
234 // Raptor Lake across bench_broadcasting (more shapes regress 3-5% than
235 // improve). Left as hardware div.
236 EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE Index indexColMajor(Index index) const {
237 Index inputIndex = 0;
238 EIGEN_UNROLL_LOOP
239 for (int i = NumDims - 1; i > 0; --i) {
240 const Index idx = index / m_outputStrides[i];
241 if (internal::index_statically_eq<Broadcast>(i, 1)) {
242 eigen_assert(idx < m_impl.dimensions()[i]);
243 inputIndex += idx * m_inputStrides[i];
244 } else {
245 if (internal::index_statically_eq<InputDimensions>(i, 1)) {
246 eigen_assert(idx % m_impl.dimensions()[i] == 0);
247 } else {
248 inputIndex += (idx % m_impl.dimensions()[i]) * m_inputStrides[i];
249 }
250 }
251 index -= idx * m_outputStrides[i];
252 }
253 EIGEN_IF_CONSTEXPR (internal::index_statically_eq<Broadcast>(0, 1)) {
254 eigen_assert(index < m_impl.dimensions()[0]);
255 inputIndex += index;
256 } else {
257 EIGEN_IF_CONSTEXPR (internal::index_statically_eq<InputDimensions>(0, 1)) {
258 eigen_assert(index % m_impl.dimensions()[0] == 0);
259 } else {
260 inputIndex += (index % m_impl.dimensions()[0]);
261 }
262 }
263 return inputIndex;
264 }
265
266 EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE CoeffReturnType coeffColMajor(Index index) const {
267 return m_impl.coeff(indexColMajor(index));
268 }
269
270 EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE Index indexRowMajor(Index index) const {
271 Index inputIndex = 0;
272 EIGEN_UNROLL_LOOP
273 for (int i = 0; i < NumDims - 1; ++i) {
274 const Index idx = index / m_outputStrides[i];
275 if (internal::index_statically_eq<Broadcast>(i, 1)) {
276 eigen_assert(idx < m_impl.dimensions()[i]);
277 inputIndex += idx * m_inputStrides[i];
278 } else {
279 if (internal::index_statically_eq<InputDimensions>(i, 1)) {
280 eigen_assert(idx % m_impl.dimensions()[i] == 0);
281 } else {
282 inputIndex += (idx % m_impl.dimensions()[i]) * m_inputStrides[i];
283 }
284 }
285 index -= idx * m_outputStrides[i];
286 }
287 EIGEN_IF_CONSTEXPR (internal::index_statically_eq<Broadcast>(NumDims - 1, 1)) {
288 eigen_assert(index < m_impl.dimensions()[NumDims - 1]);
289 inputIndex += index;
290 } else {
291 EIGEN_IF_CONSTEXPR (internal::index_statically_eq<InputDimensions>(NumDims - 1, 1)) {
292 eigen_assert(index % m_impl.dimensions()[NumDims - 1] == 0);
293 } else {
294 inputIndex += (index % m_impl.dimensions()[NumDims - 1]);
295 }
296 }
297 return inputIndex;
298 }
299
300 EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE CoeffReturnType coeffRowMajor(Index index) const {
301 return m_impl.coeff(indexRowMajor(index));
302 }
303
304 template <int LoadMode>
305 EIGEN_DEVICE_FUNC EIGEN_ALWAYS_INLINE PacketReturnType packet(Index index) const {
306 EIGEN_IF_CONSTEXPR ((internal::is_input_scalar<internal::remove_all_t<InputDimensions>>::value)) {
307 return internal::pset1<PacketReturnType>(m_impl.coeff(0));
308 }
309
310 EIGEN_IF_CONSTEXPR (static_cast<int>(Layout) == static_cast<int>(ColMajor)) {
311 if (isCopy) {
312#ifdef EIGEN_GPU_COMPILE_PHASE
313 // See PR 437: on NVIDIA P100 and K20m we observed a x3-4 speed up by enforcing
314 // unaligned loads here. The reason is unclear though.
315 return m_impl.template packet<Unaligned>(index);
316#else
317 return m_impl.template packet<LoadMode>(index);
318#endif
319 } else if (oneByN && !nByOne) {
320 return packetNByOne<LoadMode>(index);
321 } else if (!oneByN && nByOne) {
322 return packetOneByN<LoadMode>(index);
323 } else if (oneByN && nByOne) {
324 return packetOneByNByOne<LoadMode>(index);
325 } else {
326 return packetColMajor<LoadMode>(index);
327 }
328 } else {
329 if (isCopy) {
330#ifdef EIGEN_GPU_COMPILE_PHASE
331 // See above.
332 return m_impl.template packet<Unaligned>(index);
333#else
334 return m_impl.template packet<LoadMode>(index);
335#endif
336 } else if (oneByN && !nByOne) {
337 return packetOneByN<LoadMode>(index);
338 } else if (!oneByN && nByOne) {
339 return packetNByOne<LoadMode>(index);
340 } else if (oneByN && nByOne) {
341 return packetOneByNByOne<LoadMode>(index);
342 } else {
343 return packetRowMajor<LoadMode>(index);
344 }
345 }
346 }
347
348 template <int LoadMode>
349 EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE PacketReturnType packetOneByNByOne(Index index) const {
350 eigen_assert(index + PacketSize - 1 < dimensions().TotalSize());
351
352 EIGEN_ALIGN_TO_BOUNDARY(internal::unpacket_traits<PacketReturnType>::alignment)
353 std::remove_const_t<CoeffReturnType> values[PacketSize];
354 Index startDim, endDim;
355 Index inputIndex, outputOffset, batchedIndex;
356
357 EIGEN_IF_CONSTEXPR (static_cast<int>(Layout) == static_cast<int>(ColMajor)) {
358 startDim = NumDims - 1;
359 endDim = 1;
360 } else {
361 startDim = 0;
362 endDim = NumDims - 2;
363 }
364
365 batchedIndex = index % m_outputStrides[startDim];
366 inputIndex = batchedIndex / m_outputStrides[endDim];
367 outputOffset = batchedIndex % m_outputStrides[endDim];
368
369 if (outputOffset + PacketSize <= m_outputStrides[endDim]) {
370 values[0] = m_impl.coeff(inputIndex);
371 return internal::pload1<PacketReturnType>(values);
372 } else {
373 EIGEN_UNROLL_LOOP
374 for (int i = 0, cur = 0; i < PacketSize; ++i, ++cur) {
375 if (outputOffset + cur < m_outputStrides[endDim]) {
376 values[i] = m_impl.coeff(inputIndex);
377 } else {
378 ++inputIndex;
379 inputIndex = (inputIndex == m_inputStrides[startDim] ? 0 : inputIndex);
380 values[i] = m_impl.coeff(inputIndex);
381 outputOffset = 0;
382 cur = 0;
383 }
384 }
385 return internal::pload<PacketReturnType>(values);
386 }
387 }
388
389 template <int LoadMode>
390 EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE PacketReturnType packetOneByN(Index index) const {
391 // Consider the flattened tensor [v0, ..., vN],
392 // Concatenates m_broadcast[dim] copies,
393 // [v0, ..., vN, v0, ..., vN, ... ]
394 // with dim == NumDims - 1 for col-major, dim == 0 for row-major.
395 eigen_assert(index + PacketSize - 1 < dimensions().TotalSize());
396
397 // Size of flattened tensor.
398 const Index M =
399 (static_cast<int>(Layout) == static_cast<int>(ColMajor)) ? m_inputStrides[NumDims - 1] : m_inputStrides[0];
400 Index inputIndex = index % M;
401 if (inputIndex + PacketSize <= M) {
402 return m_impl.template packet<Unaligned>(inputIndex);
403 } else {
404 EIGEN_ALIGN_TO_BOUNDARY(internal::unpacket_traits<PacketReturnType>::alignment)
405 std::remove_const_t<CoeffReturnType> values[PacketSize];
406 EIGEN_UNROLL_LOOP
407 for (int i = 0; i < PacketSize; ++i) {
408 if (inputIndex > M - 1) {
409 inputIndex = 0;
410 }
411 values[i] = m_impl.coeff(inputIndex++);
412 }
413 return internal::pload<PacketReturnType>(values);
414 }
415 }
416
417 template <int LoadMode>
418 EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE PacketReturnType packetNByOne(Index index) const {
419 // Consider the flattened tensor [v0, ..., vN],
420 // Interleaves m_broadcast[dim] copies,
421 // [v0, v0, ..., v1, v1, ..., vN, vN, ... ]
422 // with dim == 0 for col-major, dim == NumDims - 1 for row-major.
423 eigen_assert(index + PacketSize - 1 < dimensions().TotalSize());
424
425 const Index M =
426 (static_cast<int>(Layout) == static_cast<int>(ColMajor)) ? m_broadcast[0] : m_broadcast[NumDims - 1];
427
428 Index inputIndex = index / M;
429 Index outputOffset = index % M;
430 if (outputOffset + PacketSize <= M) {
431 return internal::pset1<PacketReturnType>(m_impl.coeff(inputIndex));
432 } else {
433 EIGEN_ALIGN_TO_BOUNDARY(internal::unpacket_traits<PacketReturnType>::alignment)
434 std::remove_const_t<CoeffReturnType> values[PacketSize];
435 EIGEN_UNROLL_LOOP
436 for (int i = 0; i < PacketSize; ++i) {
437 if (outputOffset < M) {
438 values[i] = m_impl.coeff(inputIndex);
439 ++outputOffset;
440 } else {
441 values[i] = m_impl.coeff(++inputIndex);
442 outputOffset = 1; // Next offset.
443 }
444 }
445 return internal::pload<PacketReturnType>(values);
446 }
447 }
448
449 // Ignore the LoadMode and always use unaligned loads since we can't guarantee
450 // the alignment at compile time.
451 template <int LoadMode>
452 EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE PacketReturnType packetColMajor(Index index) const {
453 eigen_assert(index + PacketSize - 1 < dimensions().TotalSize());
454
455 const Index originalIndex = index;
456
457 Index inputIndex = 0;
458 EIGEN_UNROLL_LOOP
459 for (int i = NumDims - 1; i > 0; --i) {
460 const Index idx = index / m_outputStrides[i];
461 if (internal::index_statically_eq<Broadcast>(i, 1)) {
462 eigen_assert(idx < m_impl.dimensions()[i]);
463 inputIndex += idx * m_inputStrides[i];
464 } else {
465 if (internal::index_statically_eq<InputDimensions>(i, 1)) {
466 eigen_assert(idx % m_impl.dimensions()[i] == 0);
467 } else {
468 inputIndex += (idx % m_impl.dimensions()[i]) * m_inputStrides[i];
469 }
470 }
471 index -= idx * m_outputStrides[i];
472 }
473 Index innermostLoc;
474 EIGEN_IF_CONSTEXPR (internal::index_statically_eq<Broadcast>(0, 1)) {
475 eigen_assert(index < m_impl.dimensions()[0]);
476 innermostLoc = index;
477 } else {
478 EIGEN_IF_CONSTEXPR (internal::index_statically_eq<InputDimensions>(0, 1)) {
479 eigen_assert(index % m_impl.dimensions()[0] == 0);
480 innermostLoc = 0;
481 } else {
482 innermostLoc = index % m_impl.dimensions()[0];
483 }
484 }
485 inputIndex += innermostLoc;
486
487 // TODO: This could be extended to the second dimension if we're not
488 // broadcasting alongside the first dimension, and so on.
489 if (innermostLoc + PacketSize <= m_impl.dimensions()[0]) {
490 return m_impl.template packet<Unaligned>(inputIndex);
491 } else {
492 EIGEN_ALIGN_TO_BOUNDARY(internal::unpacket_traits<PacketReturnType>::alignment)
493 std::remove_const_t<CoeffReturnType> values[PacketSize];
494 values[0] = m_impl.coeff(inputIndex);
495 EIGEN_UNROLL_LOOP
496 for (int i = 1; i < PacketSize; ++i) {
497 if (innermostLoc + i < m_impl.dimensions()[0]) {
498 values[i] = m_impl.coeff(inputIndex + i);
499 } else {
500 values[i] = coeffColMajor(originalIndex + i);
501 }
502 }
503 PacketReturnType rslt = internal::pload<PacketReturnType>(values);
504 return rslt;
505 }
506 }
507
508 template <int LoadMode>
509 EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE PacketReturnType packetRowMajor(Index index) const {
510 eigen_assert(index + PacketSize - 1 < dimensions().TotalSize());
511
512 const Index originalIndex = index;
513
514 Index inputIndex = 0;
515 EIGEN_UNROLL_LOOP
516 for (int i = 0; i < NumDims - 1; ++i) {
517 const Index idx = index / m_outputStrides[i];
518 if (internal::index_statically_eq<Broadcast>(i, 1)) {
519 eigen_assert(idx < m_impl.dimensions()[i]);
520 inputIndex += idx * m_inputStrides[i];
521 } else {
522 if (internal::index_statically_eq<InputDimensions>(i, 1)) {
523 eigen_assert(idx % m_impl.dimensions()[i] == 0);
524 } else {
525 inputIndex += (idx % m_impl.dimensions()[i]) * m_inputStrides[i];
526 }
527 }
528 index -= idx * m_outputStrides[i];
529 }
530 Index innermostLoc;
531 EIGEN_IF_CONSTEXPR (internal::index_statically_eq<Broadcast>(NumDims - 1, 1)) {
532 eigen_assert(index < m_impl.dimensions()[NumDims - 1]);
533 innermostLoc = index;
534 } else {
535 EIGEN_IF_CONSTEXPR (internal::index_statically_eq<InputDimensions>(NumDims - 1, 1)) {
536 eigen_assert(index % m_impl.dimensions()[NumDims - 1] == 0);
537 innermostLoc = 0;
538 } else {
539 innermostLoc = index % m_impl.dimensions()[NumDims - 1];
540 }
541 }
542 inputIndex += innermostLoc;
543
544 // TODO: This could be extended to the second dimension if we're not
545 // broadcasting alongside the first dimension, and so on.
546 if (innermostLoc + PacketSize <= m_impl.dimensions()[NumDims - 1]) {
547 return m_impl.template packet<Unaligned>(inputIndex);
548 } else {
549 EIGEN_ALIGN_TO_BOUNDARY(internal::unpacket_traits<PacketReturnType>::alignment)
550 std::remove_const_t<CoeffReturnType> values[PacketSize];
551 values[0] = m_impl.coeff(inputIndex);
552 EIGEN_UNROLL_LOOP
553 for (int i = 1; i < PacketSize; ++i) {
554 if (innermostLoc + i < m_impl.dimensions()[NumDims - 1]) {
555 values[i] = m_impl.coeff(inputIndex + i);
556 } else {
557 values[i] = coeffRowMajor(originalIndex + i);
558 }
559 }
560 PacketReturnType rslt = internal::pload<PacketReturnType>(values);
561 return rslt;
562 }
563 }
564
565 EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE TensorOpCost costPerCoeff(bool vectorized) const {
566 double compute_cost = TensorOpCost::AddCost<Index>();
567 EIGEN_IF_CONSTEXPR (NumDims > 0) {
568 if (!isCopy) {
569 EIGEN_UNROLL_LOOP
570 for (int i = NumDims - 1; i > 0; --i) {
571 compute_cost += TensorOpCost::DivCost<Index>();
572 if (internal::index_statically_eq<Broadcast>(i, 1)) {
573 compute_cost += TensorOpCost::MulCost<Index>() + TensorOpCost::AddCost<Index>();
574 } else {
575 if (!internal::index_statically_eq<InputDimensions>(i, 1)) {
576 compute_cost +=
577 TensorOpCost::MulCost<Index>() + TensorOpCost::ModCost<Index>() + TensorOpCost::AddCost<Index>();
578 }
579 }
580 compute_cost += TensorOpCost::MulCost<Index>() + TensorOpCost::AddCost<Index>();
581 }
582 }
583 }
584 return m_impl.costPerCoeff(vectorized) + TensorOpCost(0, 0, compute_cost, vectorized, PacketSize);
585 }
586
587 EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE internal::TensorBlockResourceRequirements getResourceRequirements() const {
588 // Target the L1 cache: measured ~30% faster than targeting the last-level
589 // cache on large tensors.
590 const size_t target_size = m_device.firstLevelCacheSize();
591 return internal::TensorBlockResourceRequirements::merge(
592 m_impl.getResourceRequirements(), internal::TensorBlockResourceRequirements::skewed<Scalar>(target_size));
593 }
594
595 EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE TensorBlock block(TensorBlockDesc& desc, TensorBlockScratch& scratch,
596 bool /*root_of_expr_ast*/ = false) const {
597 BlockBroadcastingParams params = blockBroadcastingParams(desc);
598
599 if (params.inner_dim_size == 0 || params.bcast_dim_size == 0) {
600 return emptyBlock();
601 }
602
603 // Prepare storage for the materialized broadcasting result.
604 const typename TensorBlock::Storage block_storage = TensorBlock::prepareStorage(desc, scratch);
605 ScalarNoConst* materialized_output = block_storage.data();
606
607 // We potentially will need to materialize input blocks.
608 size_t materialized_input_size = 0;
609 ScalarNoConst* materialized_input = nullptr;
610
611 // Initialize block broadcasting iterator state for outer dimensions (outer
612 // with regard to bcast dimension). Dimensions in this array are always in
613 // inner_most -> outer_most order (col major layout).
614 array<BlockBroadcastingIteratorState, NumDims> it;
615 int idx = 0;
616
617 for (int i = params.inner_dim_count + 1; i < NumDims; ++i) {
618 const Index dim = IsColMajor ? i : NumDims - 1 - i;
619 it[idx].size = params.output_dims[dim];
620 it[idx].count = 0;
621 it[idx].output_stride = m_outputStrides[dim];
622 it[idx].output_span = it[idx].output_stride * (it[idx].size - 1);
623 idx++;
624 }
625
626 // Write output into the beginning of `materialized_output`.
627 Index output_offset = 0;
628
629 // We will fill output block by broadcasting along the bcast dim, and
630 // iterating over outer dimension.
631 const Index output_size = NumDims == 0 ? 1 : params.output_dims.TotalSize();
632
633 for (Index num_output_coeffs = 0; num_output_coeffs < output_size;) {
634 ScalarNoConst* bcast_output = materialized_output + num_output_coeffs;
635 Index bcast_offset = desc.offset() + output_offset;
636
637 // Broadcast along the bcast dimension.
638 num_output_coeffs += BroadcastBlockAlongBcastDim(params, bcast_offset, scratch, bcast_output, &materialized_input,
639 &materialized_input_size);
640
641 // Switch to the next outer dimension.
642 for (int j = 0; j < idx; ++j) {
643 if (++it[j].count < it[j].size) {
644 output_offset += it[j].output_stride;
645 break;
646 }
647 it[j].count = 0;
648 output_offset -= it[j].output_span;
649 }
650 }
651
652 return block_storage.AsTensorMaterializedBlock();
653 }
654
655 EIGEN_DEVICE_FUNC EvaluatorPointerType data() const { return nullptr; }
656
657 const TensorEvaluator<ArgType, Device>& impl() const { return m_impl; }
658
659 Broadcast functor() const { return m_broadcast; }
660
661 private:
662 static constexpr bool IsColMajor = static_cast<int>(Layout) == static_cast<int>(ColMajor);
663
664 // We will build a general case block broadcasting on top of broadcasting
665 // primitive that will do broadcasting only for the inner dimension(s) along
666 // the first dimension smaller than the input size (it's called `bcast_dim`).
667 //
668 // Example:
669 // dim: 0 1 2 (ColMajor)
670 // input size: [9, 3, 6]
671 // block size: [9, 2, 6]
672 //
673 // We will compute broadcasted block by iterating over the outer dimensions
674 // before `bcast_dim` (only dimension `2` in this example) and computing
675 // broadcasts along the `bcast_dim` (dimension `1` in this example).
676
677 // BlockBroadcastingParams holds precomputed parameters for broadcasting a
678 // single block along the broadcasting dimension. Sizes and strides along the
679 // `bcast_dim` might be invalid, they will be adjusted later in
680 // `BroadcastBlockAlongBcastDim`.
681 struct BlockBroadcastingParams {
682 Dimensions input_dims; // input expression dimensions
683 Dimensions output_dims; // output block sizes
684 Dimensions output_strides; // output block strides
685
686 int inner_dim_count; // count inner dimensions matching in size
687 int bcast_dim; // broadcasting dimension index
688 Index bcast_dim_size; // broadcasting dimension size
689 Index inner_dim_size; // inner dimensions size
690
691 // Block sizes and strides for the input block where all dimensions before
692 // `bcast_dim` are equal to `1`.
693 Dimensions input_block_sizes;
694 Dimensions input_block_strides;
695
696 // Block sizes and strides for blocks with extra dimensions and strides `0`.
697 BroadcastDimensions bcast_block_sizes;
698 BroadcastDimensions bcast_block_strides;
699 BroadcastDimensions bcast_input_strides;
700 };
701
702 struct BlockBroadcastingIteratorState {
703 Index size;
704 Index count;
705 Index output_stride;
706 Index output_span;
707 };
708
709 EIGEN_DEVICE_FUNC EIGEN_ALWAYS_INLINE BlockBroadcastingParams blockBroadcastingParams(TensorBlockDesc& desc) const {
710 BlockBroadcastingParams params;
711
712 params.input_dims = Dimensions(m_impl.dimensions());
713
714 // Output block sizes and strides.
715 params.output_dims = desc.dimensions();
716 params.output_strides = internal::strides<Layout>(params.output_dims);
717
718 // Find the broadcasting dimension (first dimension with output size smaller
719 // than the input size).
720 params.bcast_dim = 0;
721 params.bcast_dim_size = 1;
722 params.inner_dim_size = 1;
723
724 // Count the number of inner dimensions that have the same size in the block
725 // and in the broadcast expression.
726 params.inner_dim_count = 0;
727
728 for (int i = 0; i < NumDims; ++i) {
729 const int dim = IsColMajor ? i : NumDims - i - 1;
730
731 if (params.output_dims[dim] == m_dimensions[dim]) {
732 params.inner_dim_size *= params.output_dims[dim];
733 ++params.inner_dim_count;
734 continue;
735 }
736
737 // First non-matching dimension is the broadcasting dimension.
738 eigen_assert(params.output_dims[dim] < m_dimensions[dim]);
739 params.bcast_dim = dim;
740 params.bcast_dim_size = params.output_dims[dim];
741 break;
742 }
743
744 // Calculate the input block size for looking into the input.
745 for (int i = 0; i < params.inner_dim_count; ++i) {
746 const int dim = IsColMajor ? i : NumDims - i - 1;
747 params.input_block_sizes[dim] = params.input_dims[dim];
748 }
749 for (int i = params.inner_dim_count; i < NumDims; ++i) {
750 const int dim = IsColMajor ? i : NumDims - i - 1;
751 params.input_block_sizes[dim] = 1;
752 }
753 params.input_block_strides = internal::strides<Layout>(params.input_block_sizes);
754
755 // Broadcast with the 0-stride trick: Create 1 extra dim for each
756 // broadcast, set the input stride to 0.
757 //
758 // When ColMajor:
759 //
760 // - bcast_block_sizes:
761 // [d_0, b_0, d_1, b_1, ...]
762 //
763 // - bcast_block_strides:
764 // [output_block_strides[0], output_block_strides[0] * d_0,
765 // output_block_strides[1], output_block_strides[1] * d_1,
766 // ...]
767 //
768 // - bcast_input_strides:
769 // [input_block_strides[0], 0,
770 // input_block_strides[1], 0,
771 // ...].
772 //
773 for (int i = 0; i < params.inner_dim_count; ++i) {
774 const int dim = IsColMajor ? i : NumDims - i - 1;
775
776 const int copy_dim = IsColMajor ? 2 * i : 2 * NumDims - 2 * i - 1;
777 const int broadcast_dim = IsColMajor ? copy_dim + 1 : copy_dim - 1;
778
779 params.bcast_block_sizes[copy_dim] = params.input_dims[dim];
780 params.bcast_block_sizes[broadcast_dim] = m_broadcast[dim];
781 params.bcast_block_strides[copy_dim] = params.output_strides[dim];
782 params.bcast_block_strides[broadcast_dim] = params.output_strides[dim] * params.input_dims[dim];
783 params.bcast_input_strides[copy_dim] = params.input_block_strides[dim];
784 params.bcast_input_strides[broadcast_dim] = 0;
785 }
786
787 for (int i = 2 * params.inner_dim_count; i < 2 * NumDims; ++i) {
788 const int dim = IsColMajor ? i : 2 * NumDims - i - 1;
789 params.bcast_block_sizes[dim] = 1;
790 params.bcast_block_strides[dim] = 0;
791 params.bcast_input_strides[dim] = 0;
792 }
793
794 return params;
795 }
796
797 EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE TensorBlock emptyBlock() const {
798 DSizes<Index, NumDims> dimensions;
799 for (int i = 0; i < NumDims; ++i) dimensions[i] = 0;
800 return TensorBlock(internal::TensorBlockKind::kView, nullptr, dimensions);
801 }
802
803 EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE Index BroadcastBlockAlongBcastDim(
804 BlockBroadcastingParams params, Index bcast_offset, TensorBlockScratch& scratch,
805 ScalarNoConst* materialized_output, ScalarNoConst** materialized_input, size_t* materialized_input_size) const {
806 if (params.bcast_dim_size == 1) {
807 // We just need one block read using the ready-set values above.
808 return BroadcastBlock(params.input_block_sizes, params.input_block_strides, params.bcast_block_sizes,
809 params.bcast_block_strides, params.bcast_input_strides, bcast_offset, 0, scratch,
810 materialized_output, materialized_input, materialized_input_size);
811
812 } else if (params.input_dims[params.bcast_dim] == 1) {
813 // Broadcast bcast dimension (< NumDims) by bcast_dim_size.
814 const int broadcast_bcast_dim =
815 IsColMajor ? 2 * params.inner_dim_count + 1 : 2 * NumDims - 2 * params.inner_dim_count - 2;
816
817 params.bcast_block_sizes[broadcast_bcast_dim] = params.bcast_dim_size;
818 params.bcast_input_strides[broadcast_bcast_dim] = 0;
819 params.bcast_block_strides[broadcast_bcast_dim] = params.output_strides[params.bcast_dim];
820
821 return BroadcastBlock(params.input_block_sizes, params.input_block_strides, params.bcast_block_sizes,
822 params.bcast_block_strides, params.bcast_input_strides, bcast_offset, 0, scratch,
823 materialized_output, materialized_input, materialized_input_size);
824
825 } else {
826 // Keep track of the total number of the coefficients written to the
827 // output block.
828 Index num_output_coeffs = 0;
829
830 // The general case. Let's denote the output block as
831 //
832 // x[..., a:a+bcast_dim_size, :, ..., :]
833 //
834 // where a:a+bcast_dim_size is a slice on the bcast_dim dimension
835 // (< NumDims). We need to split the a:a+bcast_dim_size into possibly 3
836 // sub-blocks:
837 //
838 // (1) a:b, where b is the smallest multiple of
839 // input_dims[bcast_dim_start] in [a, a+bcast_dim_size].
840 //
841 // (2) b:c, where c is the largest multiple of input_dims[bcast_dim_start]
842 // in [a, a+bcast_dim_size].
843 //
844 // (3) c:a+bcast_dim_size .
845 //
846 // Or, when b and c do not exist, we just need to process the whole block
847 // together.
848
849 // Find a.
850 const Index bcast_dim_left_index = bcast_offset / m_outputStrides[params.bcast_dim];
851
852 // Find b and c.
853 const Index input_bcast_dim_size = params.input_dims[params.bcast_dim];
854
855 // First multiple after a. This is b when <= bcast_dim_left_index +
856 // bcast_dim_size.
857 const Index first_multiple =
858 numext::div_ceil<Index>(bcast_dim_left_index, input_bcast_dim_size) * input_bcast_dim_size;
859
860 if (first_multiple <= bcast_dim_left_index + params.bcast_dim_size) {
861 // b exists, so does c. Find it.
862 const Index last_multiple =
863 (bcast_dim_left_index + params.bcast_dim_size) / input_bcast_dim_size * input_bcast_dim_size;
864 const int copy_bcast_dim =
865 IsColMajor ? 2 * params.inner_dim_count : 2 * NumDims - 2 * params.inner_dim_count - 1;
866 const int broadcast_bcast_dim =
867 IsColMajor ? 2 * params.inner_dim_count + 1 : 2 * NumDims - 2 * params.inner_dim_count - 2;
868
869 if (first_multiple > bcast_dim_left_index) {
870 const Index head_size = first_multiple - bcast_dim_left_index;
871 params.input_block_sizes[params.bcast_dim] = head_size;
872 params.bcast_block_sizes[copy_bcast_dim] = head_size;
873 params.bcast_input_strides[copy_bcast_dim] = params.input_block_strides[params.bcast_dim];
874 params.bcast_block_strides[copy_bcast_dim] = params.output_strides[params.bcast_dim];
875 params.bcast_block_sizes[broadcast_bcast_dim] = 1;
876 params.bcast_input_strides[broadcast_bcast_dim] = 0;
877 params.bcast_block_strides[broadcast_bcast_dim] =
878 params.output_strides[params.bcast_dim] * params.input_dims[params.bcast_dim];
879
880 num_output_coeffs +=
881 BroadcastBlock(params.input_block_sizes, params.input_block_strides, params.bcast_block_sizes,
882 params.bcast_block_strides, params.bcast_input_strides, bcast_offset, 0, scratch,
883 materialized_output, materialized_input, materialized_input_size);
884 }
885 if (first_multiple < last_multiple) {
886 params.input_block_sizes[params.bcast_dim] = input_bcast_dim_size;
887 params.bcast_block_sizes[copy_bcast_dim] = input_bcast_dim_size;
888 params.bcast_input_strides[copy_bcast_dim] = params.input_block_strides[params.bcast_dim];
889 params.bcast_block_strides[copy_bcast_dim] = params.output_strides[params.bcast_dim];
890 params.bcast_block_sizes[broadcast_bcast_dim] = (last_multiple - first_multiple) / input_bcast_dim_size;
891 params.bcast_input_strides[broadcast_bcast_dim] = 0;
892 params.bcast_block_strides[broadcast_bcast_dim] =
893 params.output_strides[params.bcast_dim] * params.input_dims[params.bcast_dim];
894 const Index offset = (first_multiple - bcast_dim_left_index) * m_outputStrides[params.bcast_dim];
895
896 num_output_coeffs +=
897 BroadcastBlock(params.input_block_sizes, params.input_block_strides, params.bcast_block_sizes,
898 params.bcast_block_strides, params.bcast_input_strides, bcast_offset, offset, scratch,
899 materialized_output, materialized_input, materialized_input_size);
900 }
901 if (last_multiple < bcast_dim_left_index + params.bcast_dim_size) {
902 const Index tail_size = bcast_dim_left_index + params.bcast_dim_size - last_multiple;
903 params.input_block_sizes[params.bcast_dim] = tail_size;
904 params.bcast_block_sizes[copy_bcast_dim] = tail_size;
905 params.bcast_input_strides[copy_bcast_dim] = params.input_block_strides[params.bcast_dim];
906 params.bcast_block_strides[copy_bcast_dim] = params.output_strides[params.bcast_dim];
907 params.bcast_block_sizes[broadcast_bcast_dim] = 1;
908 params.bcast_input_strides[broadcast_bcast_dim] = 0;
909 params.bcast_block_strides[broadcast_bcast_dim] =
910 params.output_strides[params.bcast_dim] * params.input_dims[params.bcast_dim];
911 const Index offset = (last_multiple - bcast_dim_left_index) * m_outputStrides[params.bcast_dim];
912
913 num_output_coeffs +=
914 BroadcastBlock(params.input_block_sizes, params.input_block_strides, params.bcast_block_sizes,
915 params.bcast_block_strides, params.bcast_input_strides, bcast_offset, offset, scratch,
916 materialized_output, materialized_input, materialized_input_size);
917 }
918 } else {
919 // b and c do not exist.
920 const int copy_bcast_dim =
921 IsColMajor ? 2 * params.inner_dim_count : 2 * NumDims - 2 * params.inner_dim_count - 1;
922 params.input_block_sizes[params.bcast_dim] = params.bcast_dim_size;
923 params.bcast_block_sizes[copy_bcast_dim] = params.bcast_dim_size;
924 params.bcast_input_strides[copy_bcast_dim] = params.input_block_strides[params.bcast_dim];
925 params.bcast_block_strides[copy_bcast_dim] = params.output_strides[params.bcast_dim];
926
927 num_output_coeffs +=
928 BroadcastBlock(params.input_block_sizes, params.input_block_strides, params.bcast_block_sizes,
929 params.bcast_block_strides, params.bcast_input_strides, bcast_offset, 0, scratch,
930 materialized_output, materialized_input, materialized_input_size);
931 }
932
933 return num_output_coeffs;
934 }
935 }
936
937 EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE Index BroadcastBlock(
938 const Dimensions& input_block_sizes, const Dimensions& input_block_strides,
939 const BroadcastDimensions& bcast_block_sizes, const BroadcastDimensions& bcast_block_strides,
940 const BroadcastDimensions& bcast_input_strides, Index bcast_offset, Index offset, TensorBlockScratch& scratch,
941 ScalarNoConst* materialized_output, ScalarNoConst** materialized_input, size_t* materialized_input_size) const {
942 // ---------------------------------------------------------------------- //
943 // Tensor block descriptor for reading block from the input.
944 const Index input_offset = bcast_offset + offset;
945 TensorBlockDesc input_desc(IsColMajor ? indexColMajor(input_offset) : indexRowMajor(input_offset),
946 input_block_sizes);
947
948 ArgTensorBlock input_block = m_impl.block(input_desc, scratch);
949
950 // ---------------------------------------------------------------------- //
951 // Materialize input block into a temporary memory buffer only if it's not
952 // already available in the arg block.
953 const ScalarNoConst* input_buffer = nullptr;
954
955 if (input_block.data() != nullptr) {
956 // Input block already has raw data, there is no need to materialize it.
957 input_buffer = input_block.data();
958
959 } else {
960 // Otherwise we have to do block assignment into a temporary buffer.
961
962 // Maybe reuse previously allocated buffer, or allocate a new one with a
963 // scratch allocator.
964 const size_t input_total_size = input_block_sizes.TotalSize();
965 if (*materialized_input == nullptr || *materialized_input_size < input_total_size) {
966 *materialized_input_size = input_total_size;
967 void* mem = scratch.allocate(*materialized_input_size * sizeof(Scalar));
968 *materialized_input = static_cast<ScalarNoConst*>(mem);
969 }
970
971 using TensorBlockAssignment =
972 internal::TensorBlockAssignment<ScalarNoConst, NumDims, typename ArgTensorBlock::XprType, Index>;
973
974 TensorBlockAssignment::Run(
975 TensorBlockAssignment::target(input_block_sizes, input_block_strides, *materialized_input),
976 input_block.expr());
977
978 input_buffer = *materialized_input;
979 }
980
981 // ---------------------------------------------------------------------- //
982 // Copy data from materialized input block to the materialized output, using
983 // given broadcast strides (strides with zeroes).
984 using TensorBlockIO = internal::TensorBlockIO<ScalarNoConst, Index, 2 * NumDims, Layout>;
985
986 typename TensorBlockIO::Src src(bcast_input_strides, input_buffer);
987 typename TensorBlockIO::Dst dst(bcast_block_sizes, bcast_block_strides, materialized_output + offset);
988
989 return TensorBlockIO::Copy(dst, src);
990 }
991
992 protected:
993 const Device EIGEN_DEVICE_REF m_device;
994 const std::remove_reference_t<Broadcast> m_broadcast;
995 Dimensions m_dimensions;
996 array<Index, NumDims> m_outputStrides;
997 array<Index, NumDims> m_inputStrides;
998 TensorEvaluator<ArgType, Device> m_impl;
999};
1000
1001} // end namespace Eigen
1002
1003#endif // EIGEN_TENSOR_TENSOR_BROADCASTING_H
The tensor base class.
Definition TensorForwardDeclarations.h:69
Definition TensorBroadcasting.h:53
ReadOnlyAccessors
Namespace containing all symbols from the Eigen library.
The tensor evaluator class.
Definition TensorEvaluator.h:47