Eigen-Contrib  5.0.1-dev+master
 
Loading...
Searching...
No Matches
TensorReduction.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// Copyright (C) 2016 Mehdi Goli, Codeplay Software Ltd <eigen@codeplay.com>
6//
7// This Source Code Form is subject to the terms of the Mozilla
8// Public License v. 2.0. If a copy of the MPL was not distributed
9// with this file, You can obtain one at http://mozilla.org/MPL/2.0/.
10// SPDX-License-Identifier: MPL-2.0
11
12#ifndef EIGEN_TENSOR_TENSOR_REDUCTION_H
13#define EIGEN_TENSOR_TENSOR_REDUCTION_H
14
15// clang is incompatible with the CUDA syntax wrt making a kernel a class friend,
16// so we'll use a macro to make clang happy.
17#ifndef KERNEL_FRIEND
18#if defined(__clang__) && (defined(__CUDA__) || defined(__HIP__))
19#define KERNEL_FRIEND friend __global__ EIGEN_HIP_LAUNCH_BOUNDS_1024
20#else
21#define KERNEL_FRIEND friend
22#endif
23#endif
24
25// IWYU pragma: private
26#include "./InternalHeaderCheck.h"
27
28namespace Eigen {
29
30namespace internal {
31template <typename Op, typename Dims, typename XprType, template <class> class MakePointer_>
32struct traits<TensorReductionOp<Op, Dims, XprType, MakePointer_> > : traits<XprType> {
33 using XprTraits = traits<XprType>;
34 using Scalar = typename XprTraits::Scalar;
35 using StorageKind = typename XprTraits::StorageKind;
36 using Index = typename XprTraits::Index;
37 static constexpr int NumDimensions = XprTraits::NumDimensions - array_size<Dims>::value;
38 static constexpr int Layout = XprTraits::Layout;
39 using PointerType = typename XprTraits::PointerType;
40
41 template <class T>
42 struct MakePointer {
43 using Type = typename MakePointer_<T>::Type;
44 };
45};
46
47template <typename Op, typename Dims, typename XprType, template <class> class MakePointer_>
48struct eval<TensorReductionOp<Op, Dims, XprType, MakePointer_>, Eigen::Dense> {
49 using type = const TensorReductionOp<Op, Dims, XprType, MakePointer_>&;
50};
51
52template <typename OutputDims>
53struct DimInitializer {
54 template <typename InputDims, typename ReducedDims>
55 EIGEN_DEVICE_FUNC static void run(const InputDims& input_dims,
56 const array<bool, internal::array_size<InputDims>::value>& reduced,
57 OutputDims* output_dims, ReducedDims* reduced_dims) {
58 const int NumInputDims = internal::array_size<InputDims>::value;
59 int outputIndex = 0;
60 int reduceIndex = 0;
61 for (int i = 0; i < NumInputDims; ++i) {
62 if (reduced[i]) {
63 (*reduced_dims)[reduceIndex] = input_dims[i];
64 ++reduceIndex;
65 } else {
66 (*output_dims)[outputIndex] = input_dims[i];
67 ++outputIndex;
68 }
69 }
70 }
71};
72
73template <>
74struct DimInitializer<Sizes<> > {
75 template <typename InputDims, typename Index, size_t Rank>
76 EIGEN_DEVICE_FUNC static void run(const InputDims& input_dims, const array<bool, Rank>&, Sizes<>*,
77 array<Index, Rank>* reduced_dims) {
78 const int NumInputDims = internal::array_size<InputDims>::value;
79 for (int i = 0; i < NumInputDims; ++i) {
80 (*reduced_dims)[i] = input_dims[i];
81 }
82 }
83};
84
85template <typename ReducedDims, int NumTensorDims, int Layout>
86struct are_inner_most_dims {
87 static constexpr bool value = false;
88};
89template <typename ReducedDims, int NumTensorDims, int Layout>
90struct preserve_inner_most_dims {
91 static constexpr bool value = false;
92};
93
94template <typename ReducedDims, int NumTensorDims>
95struct are_inner_most_dims<ReducedDims, NumTensorDims, ColMajor> {
96 static constexpr bool tmp1 = indices_statically_known_to_increase<ReducedDims>();
97 static constexpr bool tmp2 = index_statically_eq<ReducedDims>(0, 0);
98 static constexpr bool tmp3 =
99 index_statically_eq<ReducedDims>(array_size<ReducedDims>::value - 1, array_size<ReducedDims>::value - 1);
100 static constexpr bool value = tmp1 & tmp2 & tmp3;
101};
102template <typename ReducedDims, int NumTensorDims>
103struct are_inner_most_dims<ReducedDims, NumTensorDims, RowMajor> {
104 static constexpr bool tmp1 = indices_statically_known_to_increase<ReducedDims>();
105 static constexpr bool tmp2 = index_statically_eq<ReducedDims>(0, NumTensorDims - array_size<ReducedDims>::value);
106 static constexpr bool tmp3 = index_statically_eq<ReducedDims>(array_size<ReducedDims>::value - 1, NumTensorDims - 1);
107 static constexpr bool value = tmp1 & tmp2 & tmp3;
108};
109template <typename ReducedDims, int NumTensorDims>
110struct preserve_inner_most_dims<ReducedDims, NumTensorDims, ColMajor> {
111 static constexpr bool tmp1 = indices_statically_known_to_increase<ReducedDims>();
112 static constexpr bool tmp2 = index_statically_gt<ReducedDims>(0, 0);
113 static constexpr bool value = tmp1 & tmp2;
114};
115template <typename ReducedDims, int NumTensorDims>
116struct preserve_inner_most_dims<ReducedDims, NumTensorDims, RowMajor> {
117 static constexpr bool tmp1 = indices_statically_known_to_increase<ReducedDims>();
118 static constexpr bool tmp2 = index_statically_lt<ReducedDims>(array_size<ReducedDims>::value - 1, NumTensorDims - 1);
119 static constexpr bool value = tmp1 & tmp2;
120};
121
122template <int DimIndex, typename Self, typename Op>
123struct GenericDimReducer {
124 static EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE void reduce(const Self& self, typename Self::Index firstIndex,
125 Op& reducer, typename Self::CoeffReturnType* accum) {
126 EIGEN_STATIC_ASSERT((DimIndex > 0), YOU_MADE_A_PROGRAMMING_MISTAKE);
127 for (int j = 0; j < self.m_reducedDims[DimIndex]; ++j) {
128 const typename Self::Index input = firstIndex + j * self.m_reducedStrides[DimIndex];
129 GenericDimReducer<DimIndex - 1, Self, Op>::reduce(self, input, reducer, accum);
130 }
131 }
132};
133template <typename Self, typename Op>
134struct GenericDimReducer<0, Self, Op> {
135 static EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE void reduce(const Self& self, typename Self::Index firstIndex,
136 Op& reducer, typename Self::CoeffReturnType* accum) {
137 for (int j = 0; j < self.m_reducedDims[0]; ++j) {
138 const typename Self::Index input = firstIndex + j * self.m_reducedStrides[0];
139 reducer.reduce(self.m_impl.coeff(input), accum);
140 }
141 }
142};
143template <typename Self, typename Op>
144struct GenericDimReducer<-1, Self, Op> {
145 static EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE void reduce(const Self& self, typename Self::Index index, Op& reducer,
146 typename Self::CoeffReturnType* accum) {
147 reducer.reduce(self.m_impl.coeff(index), accum);
148 }
149};
150
151template <typename Self, typename Op,
152 bool Vectorizable = (Self::InputPacketAccess && Self::ReducerTraits::PacketAccess),
153 bool UseTreeReduction = (!Self::ReducerTraits::IsStateful && !Self::ReducerTraits::IsExactlyAssociative &&
154 // GPU threads can quickly run out of stack space
155 // for moderately sized inputs.
156 !Self::RunningOnGPU)>
157struct InnerMostDimReducer {
158 static EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE typename Self::CoeffReturnType reduce(
159 const Self& self, typename Self::Index firstIndex, typename Self::Index numValuesToReduce, Op& reducer) {
160 using Index = typename Self::Index;
161 typename Self::CoeffReturnType accum0 = reducer.initialize();
162 Index j = 0;
163 // The accumulators take interleaved operands and are merged by feeding one back through
164 // reduce(), so this needs a pure combine that is also associative and commutative;
165 // reducer_can_reorder_accumulators marks the reducers that guarantee both.
166 EIGEN_IF_CONSTEXPR (reducer_can_reorder_accumulators<Op>::value) {
167 if (numValuesToReduce >= 8) {
168 typename Self::CoeffReturnType accum1 = reducer.initialize(), accum2 = reducer.initialize();
169 typename Self::CoeffReturnType accum3 = reducer.initialize(), accum4 = reducer.initialize();
170 typename Self::CoeffReturnType accum5 = reducer.initialize(), accum6 = reducer.initialize();
171 typename Self::CoeffReturnType accum7 = reducer.initialize();
172 const Index unrolledEnd = numValuesToReduce - numValuesToReduce % 8;
173 for (; j < unrolledEnd; j += 8) {
174 reducer.reduce(self.m_impl.coeff(firstIndex + j + 0), &accum0);
175 reducer.reduce(self.m_impl.coeff(firstIndex + j + 1), &accum1);
176 reducer.reduce(self.m_impl.coeff(firstIndex + j + 2), &accum2);
177 reducer.reduce(self.m_impl.coeff(firstIndex + j + 3), &accum3);
178 reducer.reduce(self.m_impl.coeff(firstIndex + j + 4), &accum4);
179 reducer.reduce(self.m_impl.coeff(firstIndex + j + 5), &accum5);
180 reducer.reduce(self.m_impl.coeff(firstIndex + j + 6), &accum6);
181 reducer.reduce(self.m_impl.coeff(firstIndex + j + 7), &accum7);
182 }
183 reducer.reduce(accum1, &accum0);
184 reducer.reduce(accum2, &accum0);
185 reducer.reduce(accum3, &accum0);
186 reducer.reduce(accum4, &accum0);
187 reducer.reduce(accum5, &accum0);
188 reducer.reduce(accum6, &accum0);
189 reducer.reduce(accum7, &accum0);
190 }
191 }
192 for (; j < numValuesToReduce; ++j) {
193 reducer.reduce(self.m_impl.coeff(firstIndex + j), &accum0);
194 }
195 return reducer.finalize(accum0);
196 }
197};
198
199template <typename Self, typename Op>
200struct InnerMostDimReducer<Self, Op, true, false> {
201 static EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE typename Self::CoeffReturnType reduce(
202 const Self& self, typename Self::Index firstIndex, typename Self::Index numValuesToReduce, Op& reducer0) {
203 using Index = typename Self::Index;
204 constexpr Index packetSize = internal::unpacket_traits<typename Self::PacketReturnType>::size;
205 Index start = 0;
206 typename Self::PacketReturnType paccum0 = reducer0.template initializePacket<typename Self::PacketReturnType>();
207 EIGEN_IF_CONSTEXPR (reducer_can_reorder_accumulators<Op>::value) {
208 if (numValuesToReduce >= 4 * packetSize) {
209 const Index VectorizedSize4 = (numValuesToReduce / (4 * packetSize)) * (4 * packetSize);
210 typename Self::PacketReturnType paccum1 = reducer0.template initializePacket<typename Self::PacketReturnType>();
211 typename Self::PacketReturnType paccum2 = reducer0.template initializePacket<typename Self::PacketReturnType>();
212 typename Self::PacketReturnType paccum3 = reducer0.template initializePacket<typename Self::PacketReturnType>();
213 const Index offset0 = firstIndex;
214 const Index offset1 = firstIndex + packetSize;
215 const Index offset2 = firstIndex + 2 * packetSize;
216 const Index offset3 = firstIndex + 3 * packetSize;
217 for (Index j = 0; j < VectorizedSize4; j += 4 * packetSize) {
218 reducer0.reducePacket(self.m_impl.template packet<Unaligned>(offset0 + j), &paccum0);
219 reducer0.reducePacket(self.m_impl.template packet<Unaligned>(offset1 + j), &paccum1);
220 reducer0.reducePacket(self.m_impl.template packet<Unaligned>(offset2 + j), &paccum2);
221 reducer0.reducePacket(self.m_impl.template packet<Unaligned>(offset3 + j), &paccum3);
222 }
223 reducer0.reducePacket(paccum1, &paccum0);
224 reducer0.reducePacket(paccum2, &paccum0);
225 reducer0.reducePacket(paccum3, &paccum0);
226 start = VectorizedSize4;
227 }
228 }
229 if (start <= (numValuesToReduce - packetSize)) {
230 const Index VectorizedSize = (numValuesToReduce / packetSize) * packetSize;
231 for (Index j = start; j < VectorizedSize; j += packetSize) {
232 reducer0.reducePacket(self.m_impl.template packet<Unaligned>(firstIndex + j), &paccum0);
233 }
234 start = VectorizedSize;
235 }
236 typename Self::CoeffReturnType accum = reducer0.initialize();
237 for (Index j = start; j < numValuesToReduce; ++j) {
238 reducer0.reduce(self.m_impl.coeff(firstIndex + j), &accum);
239 }
240 return reducer0.finalizeBoth(accum, paccum0);
241 }
242};
243
244#if !defined(EIGEN_HIPCC)
245
246// The following implements tree-based reduction, which improves the accuracy
247// of sum reductions, since each of the n inputs only participates in
248// O(log n) additions. It is used only when UseTreeReduction holds (stateless,
249// not exactly associative reducers): mean() does not qualify because MeanReducer
250// is stateful (it counts its inputs), so it accumulates linearly.
251template <typename T>
252EIGEN_DEVICE_FUNC inline Index LeafSize() {
253 return 1024;
254}
255template <>
256EIGEN_DEVICE_FUNC inline Index LeafSize<half>() {
257 return 200;
258}
259template <>
260EIGEN_DEVICE_FUNC inline Index LeafSize<bfloat16>() {
261 return 128;
262}
263
264template <typename Self, typename Op>
265struct InnerMostDimReducer<Self, Op, false, true> {
266 static EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE typename Self::CoeffReturnType reduce(
267 const Self& self, typename Self::Index firstIndex, typename Self::Index numValuesToReduce, Op& reducer) {
268 const Index kLeafSize = LeafSize<typename Self::CoeffReturnType>();
269 typename Self::CoeffReturnType accum = reducer.initialize();
270 if (numValuesToReduce > kLeafSize) {
271 const typename Self::Index half = numValuesToReduce / 2;
272 // Recursively reduce the two halves.
273 reducer.reduce(reduce(self, firstIndex, half, reducer), &accum);
274 reducer.reduce(reduce(self, firstIndex + half, numValuesToReduce - half, reducer), &accum);
275 return reducer.finalize(accum);
276 } else {
277 return InnerMostDimReducer<Self, Op, false, false>::reduce(self, firstIndex, numValuesToReduce, reducer);
278 }
279 }
280};
281
282template <typename Self, typename Op>
283struct InnerMostDimReducer<Self, Op, true, true> {
284 static EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE typename Self::CoeffReturnType reduce(
285 const Self& self, typename Self::Index firstIndex, typename Self::Index numValuesToReduce, Op& reducer) {
286 const Index kLeafSize = LeafSize<typename Self::CoeffReturnType>();
287 const typename Self::Index packetSize = internal::unpacket_traits<typename Self::PacketReturnType>::size;
288 typename Self::CoeffReturnType accum = reducer.initialize();
289 if (numValuesToReduce > packetSize * kLeafSize) {
290 // Make sure the split point is aligned on a packet boundary.
291 const typename Self::Index split =
292 packetSize *
293 numext::div_ceil(firstIndex + numext::div_ceil(numValuesToReduce, typename Self::Index(2)), packetSize);
294 const typename Self::Index num_left = numext::mini(split - firstIndex, numValuesToReduce);
295 reducer.reduce(reduce(self, firstIndex, num_left, reducer), &accum);
296 if (num_left < numValuesToReduce) {
297 reducer.reduce(reduce(self, split, numValuesToReduce - num_left, reducer), &accum);
298 }
299 return reducer.finalize(accum);
300 } else {
301 return InnerMostDimReducer<Self, Op, true, false>::reduce(self, firstIndex, numValuesToReduce, reducer);
302 }
303 }
304};
305#endif
306
307template <int DimIndex, typename Self, typename Op,
308 bool vectorizable = (Self::InputPacketAccess && Self::ReducerTraits::PacketAccess)>
309struct InnerMostDimPreserver {
310 static EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE void reduce(const Self&, typename Self::Index, Op&,
311 typename Self::PacketReturnType*) {
312 eigen_assert(false && "should never be called");
313 }
314};
315
316template <int DimIndex, typename Self, typename Op>
317struct InnerMostDimPreserver<DimIndex, Self, Op, true> {
318 static EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE void reduce(const Self& self, typename Self::Index firstIndex,
319 Op& reducer, typename Self::PacketReturnType* accum) {
320 EIGEN_STATIC_ASSERT((DimIndex > 0), YOU_MADE_A_PROGRAMMING_MISTAKE);
321 for (typename Self::Index j = 0; j < self.m_reducedDims[DimIndex]; ++j) {
322 const typename Self::Index input = firstIndex + j * self.m_reducedStrides[DimIndex];
323 InnerMostDimPreserver<DimIndex - 1, Self, Op>::reduce(self, input, reducer, accum);
324 }
325 }
326};
327
328template <typename Self, typename Op>
329struct InnerMostDimPreserver<0, Self, Op, true> {
330 static EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE void reduce(const Self& self, typename Self::Index firstIndex,
331 Op& reducer0, typename Self::PacketReturnType* accum0) {
332 using Index = typename Self::Index;
333 const Index stride = self.m_reducedStrides[0];
334 const Index size = self.m_reducedDims[0];
335 EIGEN_IF_CONSTEXPR (reducer_can_reorder_accumulators<Op>::value) {
336 if (size >= 16) {
337 const Index unrolled_size4 = (size / 4) * 4;
338 typename Self::PacketReturnType accum1 = reducer0.template initializePacket<typename Self::PacketReturnType>();
339 typename Self::PacketReturnType accum2 = reducer0.template initializePacket<typename Self::PacketReturnType>();
340 typename Self::PacketReturnType accum3 = reducer0.template initializePacket<typename Self::PacketReturnType>();
341 for (Index j = 0; j < unrolled_size4; j += 4) {
342 const Index input0 = firstIndex + j * stride;
343 reducer0.reducePacket(self.m_impl.template packet<Unaligned>(input0), accum0);
344 const Index input1 = firstIndex + (j + 1) * stride;
345 reducer0.reducePacket(self.m_impl.template packet<Unaligned>(input1), &accum1);
346 const Index input2 = firstIndex + (j + 2) * stride;
347 reducer0.reducePacket(self.m_impl.template packet<Unaligned>(input2), &accum2);
348 const Index input3 = firstIndex + (j + 3) * stride;
349 reducer0.reducePacket(self.m_impl.template packet<Unaligned>(input3), &accum3);
350 }
351 reducer0.reducePacket(accum1, accum0);
352 reducer0.reducePacket(accum2, accum0);
353 reducer0.reducePacket(accum3, accum0);
354 for (Index j = unrolled_size4; j < size; ++j) {
355 Index input = firstIndex + j * stride;
356 reducer0.reducePacket(self.m_impl.template packet<Unaligned>(input), accum0);
357 }
358 return;
359 }
360 }
361 for (Index j = 0; j < size; ++j) {
362 Index input = firstIndex + j * stride;
363 reducer0.reducePacket(self.m_impl.template packet<Unaligned>(input), accum0);
364 }
365 }
366};
367template <typename Self, typename Op>
368struct InnerMostDimPreserver<-1, Self, Op, true> {
369 static EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE void reduce(const Self&, typename Self::Index, Op&,
370 typename Self::PacketReturnType*) {
371 eigen_assert(false && "should never be called");
372 }
373};
374
375// Default full reducer
376template <typename Self, typename Op, typename Device,
377 bool Vectorizable = (Self::InputPacketAccess && Self::ReducerTraits::PacketAccess)>
378struct FullReducer {
379 static constexpr bool HasOptimizedImplementation = false;
380
381 static EIGEN_DEVICE_FUNC void run(const Self& self, Op& reducer, const Device&,
382 typename Self::EvaluatorPointerType output) {
383 const typename Self::Index num_coeffs = array_prod(self.m_impl.dimensions());
384 *output = InnerMostDimReducer<Self, Op, Vectorizable>::reduce(self, 0, num_coeffs, reducer);
385 }
386};
387
388#ifdef EIGEN_USE_THREADS
389// Multithreaded full reducer
390template <typename Self, typename Op, bool Vectorizable>
391struct FullReducer<Self, Op, ThreadPoolDevice, Vectorizable> {
392 // Shards are merged by feeding them back through reduce(), which needs a pure, reorderable combine.
393 static constexpr bool HasOptimizedImplementation =
394 !Self::ReducerTraits::IsStateful && reducer_can_reorder_accumulators<Op>::value;
395 static constexpr Index PacketSize = unpacket_traits<typename Self::PacketReturnType>::size;
396
397 // launch one reducer per thread and accumulate the result.
398 static void run(const Self& self, Op& reducer, const ThreadPoolDevice& device,
399 typename Self::CoeffReturnType* output) {
400 using Index = typename Self::Index;
401 const Index num_coeffs = array_prod(self.m_impl.dimensions());
402 if (num_coeffs == 0) {
403 *output = reducer.finalize(reducer.initialize());
404 return;
405 }
406 const TensorOpCost cost = self.m_impl.costPerCoeff(Vectorizable) +
407 TensorOpCost(0, 0, internal::functor_traits<Op>::Cost, Vectorizable, PacketSize);
408 const Index num_threads = TensorCostModel<ThreadPoolDevice>::numThreads(num_coeffs, cost, device.numThreads());
409 if (num_threads == 1) {
410 *output = InnerMostDimReducer<Self, Op, Vectorizable>::reduce(self, 0, num_coeffs, reducer);
411 return;
412 }
413 const Index blocksize = num_coeffs / num_threads;
414 const Index numblocks = blocksize > 0 ? num_coeffs / blocksize : 0;
415 eigen_assert(num_coeffs >= numblocks * blocksize);
416
417 Barrier barrier(internal::convert_index<unsigned int>(numblocks));
418 MaxSizeVector<typename Self::CoeffReturnType> shards(numblocks, reducer.initialize());
419 for (Index i = 0; i < numblocks; ++i) {
420 auto run_shard = [i, blocksize, &self, &barrier, &shards, &reducer]() {
421 shards[i] = InnerMostDimReducer<Self, Op, Vectorizable>::reduce(self, i * blocksize, blocksize, reducer);
422 barrier.Notify();
423 };
424 device.enqueue(std::move(run_shard));
425 }
426 typename Self::CoeffReturnType finalShard;
427 if (numblocks * blocksize < num_coeffs) {
428 finalShard = InnerMostDimReducer<Self, Op, Vectorizable>::reduce(self, numblocks * blocksize,
429 num_coeffs - numblocks * blocksize, reducer);
430 } else {
431 finalShard = reducer.initialize();
432 }
433 barrier.Wait();
434
435 for (Index i = 0; i < numblocks; ++i) {
436 reducer.reduce(shards[i], &finalShard);
437 }
438 *output = reducer.finalize(finalShard);
439 }
440};
441
442#endif
443
444// Default inner reducer
445template <typename Self, typename Op, typename Device>
446struct InnerReducer {
447 static constexpr bool HasOptimizedImplementation = false;
448
449 EIGEN_DEVICE_FUNC static bool run(const Self&, Op&, const Device&, typename Self::CoeffReturnType*,
450 typename Self::Index, typename Self::Index) {
451 eigen_assert(false && "Not implemented");
452 return true;
453 }
454};
455
456// Default outer reducer
457template <typename Self, typename Op, typename Device>
458struct OuterReducer {
459 static constexpr bool HasOptimizedImplementation = false;
460
461 EIGEN_DEVICE_FUNC static bool run(const Self&, Op&, const Device&, typename Self::CoeffReturnType*,
462 typename Self::Index, typename Self::Index) {
463 eigen_assert(false && "Not implemented");
464 return true;
465 }
466};
467
468#ifdef EIGEN_USE_SYCL
469// Default Generic reducer
470template <typename Self, typename Op, typename Device>
471struct GenericReducer {
472 static constexpr bool HasOptimizedImplementation = false;
473
474 EIGEN_DEVICE_FUNC static bool run(const Self&, Op&, const Device&, typename Self::CoeffReturnType*,
475 typename Self::Index, typename Self::Index) {
476 eigen_assert(false && "Not implemented");
477 return true;
478 }
479};
480#endif
481
482#if defined(EIGEN_USE_GPU) && (defined(EIGEN_GPUCC))
483template <int B, int N, typename S, typename R, typename I_>
484__global__ EIGEN_HIP_LAUNCH_BOUNDS_1024 void FullReductionKernel(R, const S, I_, typename S::CoeffReturnType*,
485 unsigned int*);
486
487#if defined(EIGEN_GPUCC)
488// The scratch parameter is half* as in the definitions (TensorReductionGpu.h): declared as
489// packet_traits<half>::type*, it is Packet4h2* in the device pass, which makes the name denote two templates there.
490template <typename S, typename R, typename I_>
491__global__ EIGEN_HIP_LAUNCH_BOUNDS_1024 void ReductionInitFullReduxKernelHalfFloat(R, const S, I_, half*);
492template <int B, int N, typename S, typename R, typename I_>
493__global__ EIGEN_HIP_LAUNCH_BOUNDS_1024 void FullReductionKernelHalfFloat(R, const S, I_, half*, half*);
494template <int NPT, typename S, typename R, typename I_>
495__global__ EIGEN_HIP_LAUNCH_BOUNDS_1024 void InnerReductionKernelHalfFloat(R, const S, I_, I_, half*);
496
497#endif
498
499template <int NPT, typename S, typename R, typename I_>
500__global__ EIGEN_HIP_LAUNCH_BOUNDS_1024 void InnerReductionKernel(R, const S, I_, I_, typename S::CoeffReturnType*);
501
502template <int NPT, typename S, typename R, typename I_>
503__global__ EIGEN_HIP_LAUNCH_BOUNDS_1024 void OuterReductionKernel(R, const S, I_, I_, typename S::CoeffReturnType*);
504#endif
505
514template <typename Op, typename CoeffReturnType>
516#if defined(EIGEN_USE_SYCL)
517 using type = std::remove_const_t<decltype(std::declval<Op>().initialize())>;
518#else
519 using type = std::remove_const_t<CoeffReturnType>;
520#endif
521};
522
523} // end namespace internal
524
531template <typename Op, typename Dims, typename XprType, template <class> class MakePointer_>
532class TensorReductionOp : public TensorBase<TensorReductionOp<Op, Dims, XprType, MakePointer_>, ReadOnlyAccessors> {
533 public:
534 using Scalar = typename Eigen::internal::traits<TensorReductionOp>::Scalar;
535 using RealScalar = typename Eigen::NumTraits<Scalar>::Real;
536 using CoeffReturnType = std::remove_const_t<typename XprType::CoeffReturnType>;
537 using Nested = typename Eigen::internal::ref_selector<TensorReductionOp>::type;
538 using StorageKind = typename Eigen::internal::traits<TensorReductionOp>::StorageKind;
539 using Index = typename Eigen::internal::traits<TensorReductionOp>::Index;
540
541 EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE TensorReductionOp(const XprType& expr, const Dims& dims)
542 : m_expr(expr), m_dims(dims) {}
543 EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE TensorReductionOp(const XprType& expr, const Dims& dims, const Op& reducer)
544 : m_expr(expr), m_dims(dims), m_reducer(reducer) {}
545
546 EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE const XprType& expression() const { return m_expr; }
547 EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE const Dims& dims() const { return m_dims; }
548 EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE const Op& reducer() const { return m_reducer; }
549
550 // Rank 0 guarantees one coefficient, so only rank-0 reductions convert directly to a scalar.
551 template <int NumDims = internal::traits<TensorReductionOp>::NumDimensions, EIGEN_SFINAE_ENABLE_IF(NumDims == 0)>
552 EIGEN_STRONG_INLINE operator CoeffReturnType() const {
553 TensorEvaluator<const TensorReductionOp, DefaultDevice> evaluator(*this, DefaultDevice());
554 evaluator.evalSubExprsIfNeeded(nullptr);
555 const CoeffReturnType result = evaluator.coeff(0);
556 evaluator.cleanup();
557 return result;
558 }
559
560#if !defined(EIGEN_PARSED_BY_DOXYGEN)
561 // Exact-match friends keep mixed-scalar arithmetic from being ambiguous between the tensor
562 // operators and built-in arithmetic on the scalar conversion above. is_scalar_operand keeps
563 // reduction-with-reduction arithmetic on the tensor-tensor path, which the conversion to
564 // Scalar would otherwise make ambiguous as well.
565#define EIGEN_TENSOR_REDUCTION_SCALAR_BINOP(op, name) \
566 template <typename T, EIGEN_SFINAE_ENABLE_IF((internal::is_scalar_operand<T, Scalar>::value))> \
567 EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE friend const TensorCwiseUnaryOp< \
568 internal::bind1st_op<internal::scalar_##name##_op<Scalar> >, const TensorReductionOp> \
569 op(const T& lhs, const TensorReductionOp& rhs) { \
570 return rhs.unaryExpr(internal::bind1st_op<internal::scalar_##name##_op<Scalar> >(static_cast<Scalar>(lhs))); \
571 } \
572 template <typename T, EIGEN_SFINAE_ENABLE_IF((internal::is_scalar_operand<T, Scalar>::value))> \
573 EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE friend const TensorCwiseUnaryOp< \
574 internal::bind2nd_op<internal::scalar_##name##_op<Scalar> >, const TensorReductionOp> \
575 op(const TensorReductionOp& lhs, const T& rhs) { \
576 return lhs.unaryExpr(internal::bind2nd_op<internal::scalar_##name##_op<Scalar> >(static_cast<Scalar>(rhs))); \
577 }
578
579 EIGEN_TENSOR_REDUCTION_SCALAR_BINOP(operator+, sum)
580 EIGEN_TENSOR_REDUCTION_SCALAR_BINOP(operator-, difference)
581 EIGEN_TENSOR_REDUCTION_SCALAR_BINOP(operator*, product)
582 EIGEN_TENSOR_REDUCTION_SCALAR_BINOP(operator/, quotient)
583#undef EIGEN_TENSOR_REDUCTION_SCALAR_BINOP
584#endif
585
586 protected:
587 typename XprType::Nested m_expr;
588 const Dims m_dims;
589 const Op m_reducer;
590};
591
592template <typename ArgType, typename Device>
593struct TensorReductionEvaluatorBase;
594
595// Eval as rvalue
596template <typename Op, typename Dims, typename ArgType, template <class> class MakePointer_, typename Device>
597struct TensorReductionEvaluatorBase<const TensorReductionOp<Op, Dims, ArgType, MakePointer_>, Device> {
598 using ReducerTraits = internal::reducer_traits<Op, Device>;
599 using ReducedDims = Dims;
601 using Index = typename XprType::Index;
602 using ChildType = ArgType;
603 using InputDimensions = typename TensorEvaluator<ArgType, Device>::Dimensions;
604 static constexpr int NumInputDims = internal::array_size<InputDimensions>::value;
605 static constexpr int NumReducedDims = internal::array_size<Dims>::value;
606 static constexpr int NumOutputDims = NumInputDims - NumReducedDims;
607 using Dimensions = std::conditional_t<NumOutputDims == 0, Sizes<>, DSizes<Index, NumOutputDims> >;
608 using Scalar = typename XprType::Scalar;
609 using Self = TensorReductionEvaluatorBase<const TensorReductionOp<Op, Dims, ArgType, MakePointer_>, Device>;
610 static constexpr bool InputPacketAccess = TensorEvaluator<ArgType, Device>::PacketAccess;
611 using CoeffReturnType = typename internal::ReductionReturnType<Op, typename XprType::CoeffReturnType>::type;
612 using PacketReturnType = typename PacketType<CoeffReturnType, Device>::type;
613 static constexpr Index PacketSize = PacketType<CoeffReturnType, Device>::size;
614
615 using TensorPointerType = typename Eigen::internal::traits<XprType>::PointerType;
616 using Storage = StorageMemory<CoeffReturnType, Device>;
617 using EvaluatorPointerType = typename Storage::Type;
618
619 // Subset of strides of the input tensor for the non-reduced dimensions.
620 // Indexed by output dimensions.
621 static constexpr int NumPreservedStrides = max_n_1<NumOutputDims>::size;
622
623 // For full reductions
624#if defined(EIGEN_USE_GPU) && (defined(EIGEN_GPUCC))
625 static constexpr bool RunningOnGPU = std::is_same<Device, Eigen::GpuDevice>::value;
626 static constexpr bool RunningOnSycl = false;
627#elif defined(EIGEN_USE_SYCL)
628 static constexpr bool RunningOnSycl = std::is_same<internal::remove_all_t<Device>, Eigen::SyclDevice>::value;
629 static constexpr bool RunningOnGPU = false;
630#else
631 static constexpr bool RunningOnGPU = false;
632 static constexpr bool RunningOnSycl = false;
633#endif
634
635 static constexpr int Layout = TensorEvaluator<ArgType, Device>::Layout;
636 enum {
637 IsAligned = false,
638 PacketAccess = Self::InputPacketAccess && ReducerTraits::PacketAccess,
639 BlockAccess = false,
640 PreferBlockAccess = true,
641 CoordAccess = false, // to be implemented
642 RawAccess = false
643 };
644
645 using ScalarNoConst = std::remove_const_t<Scalar>;
646
647 //===- Tensor block evaluation strategy (see TensorBlock.h) -------------===//
648 using TensorBlock = internal::TensorBlockNotImplemented;
649 //===--------------------------------------------------------------------===//
650
651 static constexpr bool ReducingInnerMostDims = internal::are_inner_most_dims<Dims, NumInputDims, Layout>::value;
652 static constexpr bool PreservingInnerMostDims = internal::preserve_inner_most_dims<Dims, NumInputDims, Layout>::value;
653 static constexpr bool RunningFullReduction = (NumOutputDims == 0);
654
655 EIGEN_STRONG_INLINE TensorReductionEvaluatorBase(const XprType& op, const Device& device)
656 : m_impl(op.expression(), device), m_reducer(op.reducer()), m_result(nullptr), m_device(device) {
657 EIGEN_STATIC_ASSERT((NumInputDims >= NumReducedDims), YOU_MADE_A_PROGRAMMING_MISTAKE);
658 EIGEN_STATIC_ASSERT((!ReducingInnerMostDims | !PreservingInnerMostDims | (NumReducedDims == NumInputDims)),
659 YOU_MADE_A_PROGRAMMING_MISTAKE);
660
661 // Build the bitmap indicating if an input dimension is reduced or not.
662 for (int i = 0; i < NumInputDims; ++i) {
663 m_reduced[i] = false;
664 }
665 for (int i = 0; i < NumReducedDims; ++i) {
666 eigen_assert(op.dims()[i] >= 0);
667 eigen_assert(op.dims()[i] < NumInputDims);
668 m_reduced[op.dims()[i]] = true;
669 }
670
671 const typename TensorEvaluator<ArgType, Device>::Dimensions& input_dims = m_impl.dimensions();
672 internal::DimInitializer<Dimensions>::run(input_dims, m_reduced, &m_dimensions, &m_reducedDims);
673
674 // Precompute output strides.
675 EIGEN_IF_CONSTEXPR (NumOutputDims > 0) {
676 EIGEN_IF_CONSTEXPR (static_cast<int>(Layout) == static_cast<int>(ColMajor)) {
677 m_outputStrides[0] = 1;
678 for (int i = 1; i < NumOutputDims; ++i) {
679 m_outputStrides[i] = m_outputStrides[i - 1] * m_dimensions[i - 1];
680 m_fastOutputStrides[i] = internal::TensorIntDivisor<Index>(m_outputStrides[i] > 0 ? m_outputStrides[i] : 1);
681 }
682 } else {
683 m_outputStrides[static_cast<size_t>(NumOutputDims - 1)] = 1;
684 for (int i = NumOutputDims - 2; i >= 0; --i) {
685 m_outputStrides[i] = m_outputStrides[i + 1] * m_dimensions[i + 1];
686 m_fastOutputStrides[i] = internal::TensorIntDivisor<Index>(m_outputStrides[i] > 0 ? m_outputStrides[i] : 1);
687 }
688 }
689 }
690
691 // Precompute input strides.
692 EIGEN_IF_CONSTEXPR (NumInputDims > 0) {
693 array<Index, NumInputDims> input_strides;
694 EIGEN_IF_CONSTEXPR (static_cast<int>(Layout) == static_cast<int>(ColMajor)) {
695 input_strides[0] = 1;
696 for (int i = 1; i < NumInputDims; ++i) {
697 input_strides[i] = input_strides[i - 1] * input_dims[i - 1];
698 }
699 } else {
700 input_strides.back() = 1;
701 for (int i = NumInputDims - 2; i >= 0; --i) {
702 input_strides[i] = input_strides[i + 1] * input_dims[i + 1];
703 }
704 }
705
706 int outputIndex = 0;
707 int reduceIndex = 0;
708 for (int i = 0; i < NumInputDims; ++i) {
709 if (m_reduced[i]) {
710 m_reducedStrides[reduceIndex] = input_strides[i];
711 ++reduceIndex;
712 } else {
713 m_preservedStrides[outputIndex] = input_strides[i];
714 m_output_to_input_dim_map[outputIndex] = i;
715 ++outputIndex;
716 }
717 }
718 }
719
720 // Special case for full reductions
721 EIGEN_IF_CONSTEXPR (NumOutputDims == 0) {
722 m_preservedStrides[0] = internal::array_prod(input_dims);
723 }
724
725 m_numValuesToReduce = NumOutputDims == 0 ? internal::array_prod(input_dims)
726 : (static_cast<int>(Layout) == static_cast<int>(ColMajor))
727 ? m_preservedStrides[0]
728 : m_preservedStrides[static_cast<size_t>(NumOutputDims - 1)];
729
730 // Runtime mirror of the static `ReducingInnerMostDims` predicate, set when
731 // the reduce dims aren't statically known (e.g. a plain std::array).
732 m_reducingInnerMostDims = (NumReducedDims > 0);
733 for (int i = 0; i < NumReducedDims && m_reducingInnerMostDims; ++i) {
734 const int axis = (static_cast<int>(Layout) == static_cast<int>(ColMajor)) ? i : NumInputDims - 1 - i;
735 if (!m_reduced[axis]) m_reducingInnerMostDims = false;
736 }
737 }
738
739 EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE const Dimensions& dimensions() const { return m_dimensions; }
740
741 EIGEN_STRONG_INLINE bool evalSubExprsIfNeededCommon(EvaluatorPointerType data) {
742 // Use the FullReducer if possible.
743 EIGEN_IF_CONSTEXPR (RunningFullReduction) {
744 if (RunningOnSycl || (internal::FullReducer<Self, Op, Device>::HasOptimizedImplementation &&
745 ((RunningOnGPU && (m_device.majorDeviceVersion() >= 3)) || !RunningOnGPU))) {
746 bool need_assign = false;
747 if (!data) {
748 m_result = static_cast<EvaluatorPointerType>(
749 m_device.get((CoeffReturnType*)m_device.allocate_temp(sizeof(CoeffReturnType))));
750 data = m_result;
751 need_assign = true;
752 }
753 Op reducer(m_reducer);
754 internal::FullReducer<Self, Op, Device>::run(*this, reducer, m_device, data);
755 return need_assign;
756 }
757 }
758
759 // Attempt to use an optimized reduction.
760 EIGEN_IF_CONSTEXPR (RunningOnGPU || RunningOnSycl) {
761 if ((RunningOnGPU && (m_device.majorDeviceVersion() >= 3)) || (RunningOnSycl)) {
762 bool reducing_inner_dims = true;
763 for (int i = 0; i < NumReducedDims; ++i) {
764 EIGEN_IF_CONSTEXPR (static_cast<int>(Layout) == static_cast<int>(ColMajor)) {
765 reducing_inner_dims &= m_reduced[i];
766 } else {
767 reducing_inner_dims &= m_reduced[NumInputDims - 1 - i];
768 }
769 }
770 EIGEN_IF_CONSTEXPR ((internal::InnerReducer<Self, Op, Device>::HasOptimizedImplementation)) {
771 if (reducing_inner_dims || ReducingInnerMostDims) {
772 const Index num_values_to_reduce = internal::array_prod(m_reducedDims);
773 const Index num_coeffs_to_preserve = static_cast<Index>(internal::array_prod(m_dimensions));
774 if (!data) {
775 if ((num_coeffs_to_preserve < 1024 && num_values_to_reduce > num_coeffs_to_preserve &&
776 num_values_to_reduce > 128) ||
777 (RunningOnSycl)) {
778 data = static_cast<EvaluatorPointerType>(m_device.get(
779 (CoeffReturnType*)m_device.allocate_temp(sizeof(CoeffReturnType) * num_coeffs_to_preserve)));
780 m_result = data;
781 } else {
782 return true;
783 }
784 }
785 Op reducer(m_reducer);
786 // For SYCL, this always returns false.
787 if (internal::InnerReducer<Self, Op, Device>::run(*this, reducer, m_device, data, num_values_to_reduce,
788 num_coeffs_to_preserve)) {
789 if (m_result) {
790 m_device.deallocate_temp(m_result);
791 m_result = nullptr;
792 }
793 return true;
794 } else {
795 return (m_result != nullptr);
796 }
797 }
798 }
799
800 bool preserving_inner_dims = true;
801 for (int i = 0; i < NumReducedDims; ++i) {
802 EIGEN_IF_CONSTEXPR (static_cast<int>(Layout) == static_cast<int>(ColMajor)) {
803 preserving_inner_dims &= m_reduced[NumInputDims - 1 - i];
804 } else {
805 preserving_inner_dims &= m_reduced[i];
806 }
807 }
808 EIGEN_IF_CONSTEXPR ((internal::OuterReducer<Self, Op, Device>::HasOptimizedImplementation)) {
809 if (preserving_inner_dims) {
810 const Index num_values_to_reduce = internal::array_prod(m_reducedDims);
811 const Index num_coeffs_to_preserve = static_cast<Index>(internal::array_prod(m_dimensions));
812 if (!data) {
813 if ((num_coeffs_to_preserve < 1024 && num_values_to_reduce > num_coeffs_to_preserve &&
814 num_values_to_reduce > 32) ||
815 (RunningOnSycl)) {
816 data = static_cast<EvaluatorPointerType>(m_device.get(
817 (CoeffReturnType*)m_device.allocate_temp(sizeof(CoeffReturnType) * num_coeffs_to_preserve)));
818 m_result = data;
819 } else {
820 return true;
821 }
822 }
823 Op reducer(m_reducer);
824 // For SYCL, this always returns false.
825 if (internal::OuterReducer<Self, Op, Device>::run(*this, reducer, m_device, data, num_values_to_reduce,
826 num_coeffs_to_preserve)) {
827 if (m_result) {
828 m_device.deallocate_temp(m_result);
829 m_result = nullptr;
830 }
831 return true;
832 } else {
833 return (m_result != nullptr);
834 }
835 }
836 }
837#if defined(EIGEN_USE_SYCL)
838 // If there is no Optimised version for SYCL, the reduction expression
839 // must break into two subexpression and use the SYCL generic Reducer on the device.
840 EIGEN_IF_CONSTEXPR (RunningOnSycl) {
841 const Index num_values_to_reduce = internal::array_prod(m_reducedDims);
842 const Index num_coeffs_to_preserve = static_cast<Index>(internal::array_prod(m_dimensions));
843 if (!data) {
844 data = static_cast<EvaluatorPointerType>(m_device.get(
845 (CoeffReturnType*)m_device.allocate_temp(sizeof(CoeffReturnType) * num_coeffs_to_preserve)));
846 m_result = data;
847 }
848 Op reducer(m_reducer);
849 internal::GenericReducer<Self, Op, Device>::run(*this, reducer, m_device, data, num_values_to_reduce,
850 num_coeffs_to_preserve);
851 return (m_result != nullptr);
852 }
853#endif
854 }
855 }
856 return true;
857 }
858
859#ifdef EIGEN_USE_THREADS
860 template <typename EvalSubExprsCallback>
861 EIGEN_STRONG_INLINE void evalSubExprsIfNeededAsync(EvaluatorPointerType data, EvalSubExprsCallback done) {
862 m_impl.evalSubExprsIfNeededAsync(nullptr, [this, data, done](bool) { done(evalSubExprsIfNeededCommon(data)); });
863 }
864#endif
865
866 EIGEN_STRONG_INLINE bool evalSubExprsIfNeeded(EvaluatorPointerType data) {
867 m_impl.evalSubExprsIfNeeded(nullptr);
868 return evalSubExprsIfNeededCommon(data);
869 }
870
871 EIGEN_STRONG_INLINE void cleanup() {
872 m_impl.cleanup();
873 if (m_result) {
874 m_device.deallocate_temp(m_result);
875 m_result = nullptr;
876 }
877 }
878
879 EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE CoeffReturnType coeff(Index index) const {
880 EIGEN_IF_CONSTEXPR (RunningFullReduction || RunningOnGPU) {
881 if (m_result) {
882 return *(m_result + index);
883 }
884 }
885 Op reducer(m_reducer);
886 EIGEN_IF_CONSTEXPR (ReducingInnerMostDims || RunningFullReduction) {
887 const Index num_values_to_reduce = (static_cast<int>(Layout) == static_cast<int>(ColMajor))
888 ? m_preservedStrides[0]
889 : m_preservedStrides[NumPreservedStrides - 1];
890 return internal::InnerMostDimReducer<Self, Op>::reduce(*this, firstInput(index), num_values_to_reduce, reducer);
891 } else if (m_reducingInnerMostDims) {
892 return internal::InnerMostDimReducer<Self, Op>::reduce(*this, index * m_numValuesToReduce, m_numValuesToReduce,
893 reducer);
894 } else {
895 typename Self::CoeffReturnType accum = reducer.initialize();
896 internal::GenericDimReducer<NumReducedDims - 1, Self, Op>::reduce(*this, firstInput(index), reducer, &accum);
897 return reducer.finalize(accum);
898 }
899 }
900
901 // TODO(bsteiner): provide a more efficient implementation.
902 template <int LoadMode>
903 EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE PacketReturnType packet(Index index) const {
904 eigen_assert(index + PacketSize - 1 < Index(internal::array_prod(dimensions())));
905
906 EIGEN_IF_CONSTEXPR (RunningOnGPU) {
907 if (m_result) {
908 return internal::pload<PacketReturnType>(m_result + index);
909 }
910 }
911
912 EIGEN_ALIGN_TO_BOUNDARY(internal::unpacket_traits<PacketReturnType>::alignment)
913 std::remove_const_t<CoeffReturnType> values[PacketSize];
914 // Materializing reduction results before storing them avoids a GCC ICE in emit_move_insn. Fixed in GCC 6.5, 7.4,
915 // and 8.1. See issue #1647 and https://gcc.gnu.org/bugzilla/show_bug.cgi?id=85496.
916 EIGEN_IF_CONSTEXPR (ReducingInnerMostDims) {
917 const Index num_values_to_reduce = (static_cast<int>(Layout) == static_cast<int>(ColMajor))
918 ? m_preservedStrides[0]
919 : m_preservedStrides[NumPreservedStrides - 1];
920 const Index firstIndex = firstInput(index);
921 for (Index i = 0; i < PacketSize; ++i) {
922 Op reducer(m_reducer);
923 const CoeffReturnType value = internal::InnerMostDimReducer<Self, Op>::reduce(
924 *this, firstIndex + i * num_values_to_reduce, num_values_to_reduce, reducer);
925 values[i] = value;
926 }
927 } else EIGEN_IF_CONSTEXPR (PreservingInnerMostDims) {
928 const Index firstIndex = firstInput(index);
929 constexpr int innermost_dim = (static_cast<int>(Layout) == static_cast<int>(ColMajor)) ? 0 : NumOutputDims - 1;
930 // TBD: extend this to the n innermost dimensions that we preserve.
931 if (((firstIndex % m_dimensions[innermost_dim]) + PacketSize - 1) < m_dimensions[innermost_dim]) {
932 Op reducer(m_reducer);
933 typename Self::PacketReturnType accum = reducer.template initializePacket<typename Self::PacketReturnType>();
934 internal::InnerMostDimPreserver<NumReducedDims - 1, Self, Op>::reduce(*this, firstIndex, reducer, &accum);
935 return reducer.finalizePacket(accum);
936 } else {
937 for (int i = 0; i < PacketSize; ++i) {
938 values[i] = coeff(index + i);
939 }
940 }
941 } else if (m_reducingInnerMostDims) {
942 // Mirror the static `ReducingInnerMostDims` packet path so we don't fall
943 // back to PS coeff() calls that route through the scalar GenericDimReducer.
944 const Index firstIndex = index * m_numValuesToReduce;
945 for (Index i = 0; i < PacketSize; ++i) {
946 Op reducer(m_reducer);
947 const CoeffReturnType value = internal::InnerMostDimReducer<Self, Op>::reduce(
948 *this, firstIndex + i * m_numValuesToReduce, m_numValuesToReduce, reducer);
949 values[i] = value;
950 }
951 } else {
952 for (int i = 0; i < PacketSize; ++i) {
953 values[i] = coeff(index + i);
954 }
955 }
956 PacketReturnType rslt = internal::pload<PacketReturnType>(values);
957 return rslt;
958 }
959
960 // Must be called after evalSubExprsIfNeeded().
961 EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE TensorOpCost costPerCoeff(bool vectorized) const {
962 EIGEN_IF_CONSTEXPR (RunningFullReduction) {
963 if (m_result) {
964 return TensorOpCost(sizeof(CoeffReturnType), 0, 0, vectorized, PacketSize);
965 }
966 }
967 const Index num_values_to_reduce = internal::array_prod(m_reducedDims);
968 const double compute_cost = num_values_to_reduce * internal::functor_traits<Op>::Cost;
969 return m_impl.costPerCoeff(vectorized) * num_values_to_reduce +
970 TensorOpCost(0, 0, compute_cost, vectorized, PacketSize);
971 }
972
973 EIGEN_DEVICE_FUNC EvaluatorPointerType data() const { return m_result; }
974 EIGEN_DEVICE_FUNC const TensorEvaluator<ArgType, Device>& impl() const { return m_impl; }
975 EIGEN_DEVICE_FUNC const Device& device() const { return m_device; }
976
977 private:
978 template <int, typename, typename>
979 friend struct internal::GenericDimReducer;
980 template <typename, typename, bool, bool>
981 friend struct internal::InnerMostDimReducer;
982 template <int, typename, typename, bool>
983 friend struct internal::InnerMostDimPreserver;
984 template <typename S, typename O, typename D, bool V>
985 friend struct internal::FullReducer;
986#if defined(EIGEN_USE_GPU) && (defined(EIGEN_GPUCC))
987 template <int B, int N, typename S, typename R, typename I_>
988 KERNEL_FRIEND void internal::FullReductionKernel(R, const S, I_, typename S::CoeffReturnType*, unsigned int*);
989#if defined(EIGEN_GPUCC)
990 template <typename S, typename R, typename I_>
991 KERNEL_FRIEND void internal::ReductionInitFullReduxKernelHalfFloat(R, const S, I_, half*);
992 template <int B, int N, typename S, typename R, typename I_>
993 KERNEL_FRIEND void internal::FullReductionKernelHalfFloat(R, const S, I_, half*, half*);
994 template <int NPT, typename S, typename R, typename I_>
995 KERNEL_FRIEND void internal::InnerReductionKernelHalfFloat(R, const S, I_, I_, half*);
996#endif
997 template <int NPT, typename S, typename R, typename I_>
998 KERNEL_FRIEND void internal::InnerReductionKernel(R, const S, I_, I_, typename S::CoeffReturnType*);
999
1000 template <int NPT, typename S, typename R, typename I_>
1001 KERNEL_FRIEND void internal::OuterReductionKernel(R, const S, I_, I_, typename S::CoeffReturnType*);
1002#endif
1003
1004#if defined(EIGEN_USE_SYCL)
1005 template <typename Evaluator_, typename Op__>
1006 friend class TensorSycl::internal::GenericNondeterministicReducer;
1007 // SYCL needs the generic reducer when the reduction is neither inner, outer, nor full.
1008 template <typename, typename, typename>
1009 friend struct internal::GenericReducer;
1010#endif
1011
1012 template <typename S, typename O, typename D>
1013 friend struct internal::InnerReducer;
1014
1015 // Returns the Index in the input tensor of the first value that needs to be
1016 // used to compute the reduction at output index "index".
1017 EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE Index firstInput(Index index) const {
1018 EIGEN_IF_CONSTEXPR (ReducingInnerMostDims) {
1019 EIGEN_IF_CONSTEXPR (static_cast<int>(Layout) == static_cast<int>(ColMajor)) {
1020 return index * m_preservedStrides[0];
1021 } else {
1022 return index * m_preservedStrides[NumPreservedStrides - 1];
1023 }
1024 }
1025 // TBD: optimize the case where we preserve the innermost dimensions.
1026 Index startInput = 0;
1027 EIGEN_IF_CONSTEXPR (static_cast<int>(Layout) == static_cast<int>(ColMajor)) {
1028 for (int i = NumOutputDims - 1; i > 0; --i) {
1029 // This is index_i in the output tensor.
1030 const Index idx = index / m_outputStrides[i];
1031 startInput += idx * m_preservedStrides[i];
1032 index -= idx * m_outputStrides[i];
1033 }
1034 EIGEN_IF_CONSTEXPR (PreservingInnerMostDims) {
1035 eigen_assert(m_preservedStrides[0] == 1);
1036 startInput += index;
1037 } else {
1038 startInput += index * m_preservedStrides[0];
1039 }
1040 } else {
1041 for (int i = 0; i < NumOutputDims - 1; ++i) {
1042 // This is index_i in the output tensor.
1043 const Index idx = index / m_outputStrides[i];
1044 startInput += idx * m_preservedStrides[i];
1045 index -= idx * m_outputStrides[i];
1046 }
1047 EIGEN_IF_CONSTEXPR (PreservingInnerMostDims) {
1048 eigen_assert(m_preservedStrides[NumPreservedStrides - 1] == 1);
1049 startInput += index;
1050 } else {
1051 startInput += index * m_preservedStrides[NumPreservedStrides - 1];
1052 }
1053 }
1054 return startInput;
1055 }
1056
1057 // Bitmap indicating if an input dimension is reduced or not.
1058 array<bool, NumInputDims> m_reduced;
1059 // Dimensions of the output of the operation.
1060 Dimensions m_dimensions;
1061 // Precomputed strides for the output tensor.
1062 // Avoid zero-sized arrays, since element access fails to compile on GPU.
1063 array<Index, (std::max)(NumOutputDims, 1)> m_outputStrides;
1064 array<internal::TensorIntDivisor<Index>, (std::max)(NumOutputDims, 1)> m_fastOutputStrides;
1065 array<Index, (std::max)(NumPreservedStrides, 1)> m_preservedStrides;
1066 // Map from output to input dimension index.
1067 array<Index, (std::max)(NumOutputDims, 1)> m_output_to_input_dim_map;
1068 // How many values go into each reduction
1069 Index m_numValuesToReduce;
1070
1071 // Runtime mirror of `ReducingInnerMostDims` (set when Dims is non-static).
1072 bool m_reducingInnerMostDims;
1073
1074 // Subset of strides of the input tensor for the reduced dimensions.
1075 // Indexed by reduced dimensions.
1076 array<Index, NumReducedDims> m_reducedStrides;
1077 // Size of the input dimensions that are reduced.
1078 // Indexed by reduced dimensions.
1079 array<Index, NumReducedDims> m_reducedDims;
1080
1081 // Evaluator for the input expression.
1082 TensorEvaluator<ArgType, Device> m_impl;
1083
1084 // Operation to apply for computing the reduction.
1085 Op m_reducer;
1086
1087 EvaluatorPointerType m_result;
1088
1089 const Device EIGEN_DEVICE_REF m_device;
1090};
1091
1092template <typename Op, typename Dims, typename ArgType, template <class> class MakePointer_, typename Device>
1093struct TensorEvaluator<const TensorReductionOp<Op, Dims, ArgType, MakePointer_>, Device>
1094 : public TensorReductionEvaluatorBase<const TensorReductionOp<Op, Dims, ArgType, MakePointer_>, Device> {
1095 using Base = TensorReductionEvaluatorBase<const TensorReductionOp<Op, Dims, ArgType, MakePointer_>, Device>;
1096 EIGEN_STRONG_INLINE TensorEvaluator(const typename Base::XprType& op, const Device& device) : Base(op, device) {}
1097};
1098
1099template <typename Op, typename Dims, typename ArgType, template <class> class MakePointer_>
1100struct TensorEvaluator<const TensorReductionOp<Op, Dims, ArgType, MakePointer_>, Eigen::SyclDevice>
1101 : public TensorReductionEvaluatorBase<const TensorReductionOp<Op, Dims, ArgType, MakePointer_>, Eigen::SyclDevice> {
1102 using Base =
1103 TensorReductionEvaluatorBase<const TensorReductionOp<Op, Dims, ArgType, MakePointer_>, Eigen::SyclDevice>;
1104 EIGEN_STRONG_INLINE TensorEvaluator(const typename Base::XprType& op, const Eigen::SyclDevice& device)
1105 : Base(op, device) {}
1106 // The base coeff function uses a recursive method that is not standard layout and cannot be used in
1107 // SYCL kernels, so it must be overridden.
1108 EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE typename Base::CoeffReturnType coeff(typename Base::Index index) const {
1109 return *(this->data() + index);
1110 }
1111 // The base packet function uses a recursive method that is not standard layout and cannot be used in
1112 // SYCL kernels, so it must be overridden.
1113 template <int LoadMode>
1114 EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE typename Base::PacketReturnType packet(typename Base::Index index) const {
1115 return internal::pload<typename Base::PacketReturnType>(this->data() + index);
1116 }
1117};
1118
1119} // end namespace Eigen
1120
1121#endif // EIGEN_TENSOR_TENSOR_REDUCTION_H
The tensor base class.
Definition TensorForwardDeclarations.h:69
Tensor reduction class.
Definition TensorReduction.h:532
Namespace containing all symbols from the Eigen library.
The tensor evaluator class.
Definition TensorEvaluator.h:47
Definition TensorReduction.h:515