Eigen-Contrib  5.0.1
 
Loading...
Searching...
No Matches
TensorFFT.h
1// This file is part of Eigen, a lightweight C++ template library
2// for linear algebra.
3//
4// Copyright (C) 2015 Jianwei Cui <thucjw@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_FFT_H
12#define EIGEN_TENSOR_TENSOR_FFT_H
13
14// IWYU pragma: private
15#include "./InternalHeaderCheck.h"
16
17namespace Eigen {
18
19template <bool IsReal>
20struct MakeComplex {
21 template <typename T>
22 EIGEN_DEVICE_FUNC T operator()(const T& val) const {
23 return val;
24 }
25};
26
27template <>
28struct MakeComplex<true> {
29 template <typename T>
30 EIGEN_DEVICE_FUNC internal::make_complex_t<T> operator()(const T& val) const {
31 return internal::make_complex_t<T>(val, T(0));
32 }
33};
34
35template <int ResultType>
36struct PartOf {
37 template <typename T>
38 T operator()(const T& val) const {
39 return val;
40 }
41};
42
43template <>
44struct PartOf<RealPart> {
45 template <typename T, typename EnableIf = std::enable_if_t<NumTraits<T>::IsComplex>>
46 typename NumTraits<T>::Real operator()(const T& val) const {
47 return Eigen::numext::real(val);
48 }
49};
50
51template <>
52struct PartOf<ImagPart> {
53 template <typename T, typename EnableIf = std::enable_if_t<NumTraits<T>::IsComplex>>
54 typename NumTraits<T>::Real operator()(const T& val) const {
55 return Eigen::numext::imag(val);
56 }
57};
58
59namespace internal {
60template <typename FFT, typename XprType, int FFTResultType, int FFTDir>
61struct traits<TensorFFTOp<FFT, XprType, FFTResultType, FFTDir>> : public traits<XprType> {
62 typedef traits<XprType> XprTraits;
63 typedef typename XprTraits::Scalar Scalar;
64 typedef typename NumTraits<Scalar>::Real RealScalar;
65 typedef make_complex_t<Scalar> ComplexScalar;
66 typedef typename XprTraits::Scalar InputScalar;
67 typedef std::conditional_t<FFTResultType == RealPart || FFTResultType == ImagPart, RealScalar, ComplexScalar>
68 OutputScalar;
69 typedef typename XprTraits::StorageKind StorageKind;
70 typedef typename XprTraits::Index Index;
71 static constexpr int NumDimensions = XprTraits::NumDimensions;
72 static constexpr int Layout = XprTraits::Layout;
73 typedef typename traits<XprType>::PointerType PointerType;
74};
75
76template <typename FFT, typename XprType, int FFTResultType, int FFTDirection>
77struct eval<TensorFFTOp<FFT, XprType, FFTResultType, FFTDirection>, Eigen::Dense> {
78 typedef const TensorFFTOp<FFT, XprType, FFTResultType, FFTDirection>& type;
79};
80
81} // end namespace internal
82
99template <typename FFT, typename XprType, int FFTResultType, int FFTDir>
100class TensorFFTOp : public TensorBase<TensorFFTOp<FFT, XprType, FFTResultType, FFTDir>, ReadOnlyAccessors> {
101 public:
102 typedef typename Eigen::internal::traits<TensorFFTOp>::Scalar Scalar;
103 typedef typename Eigen::NumTraits<Scalar>::Real RealScalar;
104 typedef internal::make_complex_t<Scalar> ComplexScalar;
105 typedef std::conditional_t<FFTResultType == RealPart || FFTResultType == ImagPart, RealScalar, ComplexScalar>
106 OutputScalar;
107 typedef OutputScalar CoeffReturnType;
108 typedef typename Eigen::internal::ref_selector<TensorFFTOp>::type Nested;
109 typedef typename Eigen::internal::traits<TensorFFTOp>::StorageKind StorageKind;
110 typedef typename Eigen::internal::traits<TensorFFTOp>::Index Index;
111
112 EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE TensorFFTOp(const XprType& expr, const FFT& fft) : m_xpr(expr), m_fft(fft) {}
113
114 EIGEN_DEVICE_FUNC const FFT& fft() const { return m_fft; }
115
116 EIGEN_DEVICE_FUNC const internal::remove_all_t<typename XprType::Nested>& expression() const { return m_xpr; }
117
118 protected:
119 typename XprType::Nested m_xpr;
120 const FFT m_fft;
121};
122
123// Eval as rvalue
124template <typename FFT, typename ArgType, typename Device, int FFTResultType, int FFTDir>
125struct TensorEvaluator<const TensorFFTOp<FFT, ArgType, FFTResultType, FFTDir>, Device> {
127 typedef typename XprType::Index Index;
128 static constexpr int NumDims = internal::array_size<typename TensorEvaluator<ArgType, Device>::Dimensions>::value;
129 typedef DSizes<Index, NumDims> Dimensions;
130 typedef typename XprType::Scalar Scalar;
131 typedef typename Eigen::NumTraits<Scalar>::Real RealScalar;
132 typedef internal::make_complex_t<Scalar> ComplexScalar;
133 typedef typename TensorEvaluator<ArgType, Device>::Dimensions InputDimensions;
134 typedef internal::traits<XprType> XprTraits;
135 typedef typename XprTraits::Scalar InputScalar;
136 typedef std::conditional_t<FFTResultType == RealPart || FFTResultType == ImagPart, RealScalar, ComplexScalar>
137 OutputScalar;
138 typedef OutputScalar CoeffReturnType;
139 typedef typename PacketType<OutputScalar, Device>::type PacketReturnType;
140 static constexpr int PacketSize = internal::unpacket_traits<PacketReturnType>::size;
141 typedef StorageMemory<CoeffReturnType, Device> Storage;
142 typedef typename Storage::Type EvaluatorPointerType;
143
144 static constexpr int Layout = TensorEvaluator<ArgType, Device>::Layout;
145 enum {
146 IsAligned = false,
147 PacketAccess = true,
148 // FFT eagerly materializes its result into m_data; once that buffer
149 // exists, exposing block access is just a wrapper around it. Leave
150 // PreferBlockAccess false so the executor still uses the cheaper
151 // packet path by default; this only matters when an outer expression
152 // calls block() directly.
153 BlockAccess = (NumDims > 0),
154 PreferBlockAccess = false,
155 CoordAccess = false,
156 RawAccess = false
157 };
158
159 //===- Tensor block evaluation strategy (see TensorBlock.h) -------------===//
160 typedef internal::TensorBlockDescriptor<NumDims, Index> TensorBlockDesc;
161 typedef internal::TensorBlockScratchAllocator<Device> TensorBlockScratch;
162 typedef typename internal::TensorMaterializedBlock<std::remove_const_t<CoeffReturnType>, NumDims, Layout, Index>
163 TensorBlock;
164 //===--------------------------------------------------------------------===//
165
166 EIGEN_STRONG_INLINE TensorEvaluator(const XprType& op, const Device& device)
167 : m_fft(op.fft()), m_impl(op.expression(), device), m_data(nullptr), m_device(device) {
168 const typename TensorEvaluator<ArgType, Device>::Dimensions& input_dims = m_impl.dimensions();
169 for (int i = 0; i < NumDims; ++i) {
170 eigen_assert(input_dims[i] > 0);
171 m_dimensions[i] = input_dims[i];
172 }
173
174 EIGEN_IF_CONSTEXPR (static_cast<int>(Layout) == static_cast<int>(ColMajor)) {
175 m_strides[0] = 1;
176 for (int i = 1; i < NumDims; ++i) {
177 m_strides[i] = m_strides[i - 1] * m_dimensions[i - 1];
178 }
179 } else {
180 m_strides[NumDims - 1] = 1;
181 for (int i = NumDims - 2; i >= 0; --i) {
182 m_strides[i] = m_strides[i + 1] * m_dimensions[i + 1];
183 }
184 }
185 m_size = m_dimensions.TotalSize();
186 }
187
188 EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE const Dimensions& dimensions() const { return m_dimensions; }
189
190 EIGEN_STRONG_INLINE bool evalSubExprsIfNeeded(EvaluatorPointerType data) {
191 m_impl.evalSubExprsIfNeeded(nullptr);
192 if (data) {
193 evalToBuf(data);
194 return false;
195 } else {
196 m_data = (EvaluatorPointerType)m_device.get(
197 (CoeffReturnType*)(m_device.allocate_temp(sizeof(CoeffReturnType) * m_size)));
198 evalToBuf(m_data);
199 return true;
200 }
201 }
202
203 EIGEN_STRONG_INLINE void cleanup() {
204 if (m_data) {
205 m_device.deallocate(m_data);
206 m_data = nullptr;
207 }
208 m_impl.cleanup();
209 }
210
211 EIGEN_DEVICE_FUNC EIGEN_ALWAYS_INLINE CoeffReturnType coeff(Index index) const { return m_data[index]; }
212
213 template <int LoadMode>
214 EIGEN_DEVICE_FUNC EIGEN_ALWAYS_INLINE PacketReturnType packet(Index index) const {
215 return internal::ploadt<PacketReturnType, LoadMode>(m_data + index);
216 }
217
218 EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE TensorOpCost costPerCoeff(bool vectorized) const {
219 return TensorOpCost(sizeof(CoeffReturnType), 0, 0, vectorized, PacketSize);
220 }
221
222 EIGEN_DEVICE_FUNC EvaluatorPointerType data() const { return m_data; }
223
224 EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE internal::TensorBlockResourceRequirements getResourceRequirements() const {
225 return internal::TensorBlockResourceRequirements::any();
226 }
227
228 EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE TensorBlock block(TensorBlockDesc& desc, TensorBlockScratch& scratch,
229 bool /*root_of_expr_ast*/ = false) const {
230 eigen_assert(m_data != nullptr);
231 return TensorBlock::materialize(m_data, m_dimensions, desc, scratch);
232 }
233
234 private:
235 EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE void evalToBuf(EvaluatorPointerType data) {
236 const bool write_to_out = std::is_same<OutputScalar, ComplexScalar>::value;
237 ComplexScalar* buf =
238 write_to_out ? (ComplexScalar*)data : (ComplexScalar*)m_device.allocate(sizeof(ComplexScalar) * m_size);
239
240 constexpr bool is_real_input = std::is_same<InputScalar, RealScalar>::value;
241 if (!is_real_input && m_impl.data() != nullptr) {
242 // Contiguous complex input — copy in one shot instead of N coeff() calls.
243 // `x = x.fft(...)` aliases input and output onto the same storage; in
244 // that case the data is already in `buf` and a memcpy would be self-
245 // overlapping (UB).
246 if (static_cast<const void*>(m_impl.data()) != static_cast<const void*>(buf)) {
247 m_device.memcpy(buf, m_impl.data(), m_size * sizeof(ComplexScalar));
248 }
249 } else {
250 for (Index i = 0; i < m_size; ++i) {
251 buf[i] = MakeComplex<is_real_input>()(m_impl.coeff(i));
252 }
253 }
254
255 for (size_t i = 0; i < m_fft.size(); ++i) {
256 Index dim = m_fft[i];
257 eigen_assert(dim >= 0 && dim < NumDims);
258 Index line_len = m_dimensions[dim];
259 eigen_assert(line_len >= 1);
260 if (line_len == 1) continue;
261 const Index stride = m_strides[dim];
262 const bool is_power_of_two = isPowerOfTwo(line_len);
263 const Index good_composite = is_power_of_two ? 0 : findGoodComposite(line_len);
264 const Index log_len = is_power_of_two ? getLog2(line_len) : getLog2(good_composite);
265 // Real, not ComplexScalar(s, 0): the latter would dispatch through
266 // libgcc __mulsc3/__muldc3 and re-introduce the NaN-check branch.
267 const RealScalar div_factor = (FFTDir == FFT_REVERSE) ? RealScalar(1) / RealScalar(line_len) : RealScalar(1);
268
269 // Scratch line buffer is only needed when we have to gather/scatter
270 // (stride != 1); for stride == 1 the FFT runs in place on `buf`.
271 ComplexScalar* line_buf =
272 (stride == 1) ? nullptr : (ComplexScalar*)m_device.allocate(sizeof(ComplexScalar) * line_len);
273
274 ComplexScalar* a =
275 is_power_of_two ? nullptr : (ComplexScalar*)m_device.allocate(sizeof(ComplexScalar) * good_composite);
276 ComplexScalar* b_fft =
277 is_power_of_two ? nullptr : (ComplexScalar*)m_device.allocate(sizeof(ComplexScalar) * good_composite);
278 ComplexScalar* pos_j_base_powered =
279 is_power_of_two ? nullptr : (ComplexScalar*)m_device.allocate(sizeof(ComplexScalar) * (line_len + 1));
280 if (!is_power_of_two) {
281 // Bluestein chirp factors t_n = exp(sqrt(-1) * pi * n^2 / line_len),
282 // n = 0..line_len. Computed in double for accuracy and cast down.
283 for (Index j = 0; j < line_len + 1; ++j) {
284 double arg = ((EIGEN_PI * j) * j) / line_len;
285 std::complex<double> tmp(numext::cos(arg), numext::sin(arg));
286 pos_j_base_powered[j] = static_cast<ComplexScalar>(tmp);
287 }
288 // The b-sequence and its forward FFT depend only on n, m, and the
289 // FFT direction — compute once and reuse for every line.
290 precompute_bluestein_b(b_fft, line_len, good_composite, log_len, pos_j_base_powered);
291 }
292
293 for (Index partial_index = 0; partial_index < m_size / line_len; ++partial_index) {
294 const Index base_offset = getBaseOffsetFromIndex(partial_index, dim);
295 ComplexScalar* line_ptr = (stride == 1) ? &buf[base_offset] : line_buf;
296
297 if (stride != 1) {
298 Index offset = base_offset;
299 for (Index j = 0; j < line_len; ++j, offset += stride) {
300 line_buf[j] = buf[offset];
301 }
302 }
303
304 if (is_power_of_two) {
305 processDataLineCooleyTukey(line_ptr, line_len, log_len);
306 } else {
307 processDataLineBluestein(line_ptr, line_len, good_composite, log_len, a, b_fft, pos_j_base_powered);
308 }
309
310 if (stride == 1) {
311 if (FFTDir == FFT_REVERSE) {
312 for (Index j = 0; j < line_len; ++j) {
313 line_ptr[j] *= div_factor;
314 }
315 }
316 } else {
317 Index offset = base_offset;
318 for (Index j = 0; j < line_len; ++j, offset += stride) {
319 buf[offset] = (FFTDir == FFT_FORWARD) ? line_buf[j] : line_buf[j] * div_factor;
320 }
321 }
322 }
323 if (line_buf) m_device.deallocate(line_buf);
324 if (!is_power_of_two) {
325 m_device.deallocate(a);
326 m_device.deallocate(b_fft);
327 m_device.deallocate(pos_j_base_powered);
328 }
329 }
330
331 if (!write_to_out) {
332 for (Index i = 0; i < m_size; ++i) {
333 data[i] = PartOf<FFTResultType>()(buf[i]);
334 }
335 m_device.deallocate(buf);
336 }
337 }
338
339 EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE static bool isPowerOfTwo(Index x) {
340 eigen_assert(x > 0);
341 return !(x & (x - 1));
342 }
343
344 // The composite number for padding, used in Bluestein's FFT algorithm
345 EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE static Index findGoodComposite(Index n) {
346 Index i = 2;
347 while (i < 2 * n - 1) i *= 2;
348 return i;
349 }
350
351 EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE static Index getLog2(Index m) {
352 Index log2m = 0;
353 while (m >>= 1) log2m++;
354 return log2m;
355 }
356
357 // Build the b-sequence and forward-FFT it once per dim. It depends only on
358 // (line_len, good_composite, FFTDir), so the result is shared across all
359 // lines — the main win for batched non-power-of-two transforms.
360 EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE void precompute_bluestein_b(ComplexScalar* b_fft, Index n, Index m, Index log_m,
361 const ComplexScalar* pos_j_base_powered) {
362 internal::conj_if<FFTDir == FFT_REVERSE> cj;
363 for (Index i = 0; i < n; ++i) {
364 b_fft[i] = cj(pos_j_base_powered[i]);
365 }
366 for (Index i = n; i < m - n; ++i) {
367 b_fft[i] = ComplexScalar(0, 0);
368 }
369 for (Index i = m - n; i < m; ++i) {
370 b_fft[i] = cj(pos_j_base_powered[m - i]);
371 }
372 scramble_FFT(b_fft, m);
373 compute_1D_Butterfly<FFT_FORWARD>(b_fft, m, log_m);
374 }
375
376 // Call Cooley Tukey algorithm directly; line_len must be a power of 2.
377 EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE void processDataLineCooleyTukey(ComplexScalar* line_buf, Index line_len,
378 Index log_len) {
379 eigen_assert(isPowerOfTwo(line_len));
380 scramble_FFT(line_buf, line_len);
381 compute_1D_Butterfly<FFTDir>(line_buf, line_len, log_len);
382 }
383
384 // Bluestein's algorithm: turn an arbitrary-length transform into three
385 // length-m power-of-two transforms (m = good_composite >= 2*line_len). The
386 // forward-FFT of b is taken as input (precomputed once per dim).
387 EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE void processDataLineBluestein(ComplexScalar* line_buf, Index line_len,
388 Index good_composite, Index log_m,
389 ComplexScalar* a, const ComplexScalar* b_fft,
390 const ComplexScalar* pos_j_base_powered) {
391 const Index n = line_len;
392 const Index m = good_composite;
393 // Data-side chirp is conjugated for forward, not for reverse — opposite
394 // of the b-sequence conjugation in precompute_bluestein_b.
395 internal::conj_if<FFTDir == FFT_FORWARD> cj;
396
397 for (Index i = 0; i < n; ++i) {
398 a[i] = internal::pmul(line_buf[i], cj(pos_j_base_powered[i]));
399 }
400 for (Index i = n; i < m; ++i) {
401 a[i] = ComplexScalar(0, 0);
402 }
403
404 scramble_FFT(a, m);
405 compute_1D_Butterfly<FFT_FORWARD>(a, m, log_m);
406
407 for (Index i = 0; i < m; ++i) {
408 a[i] = internal::pmul(a[i], b_fft[i]);
409 }
410
411 scramble_FFT(a, m);
412 compute_1D_Butterfly<FFT_REVERSE>(a, m, log_m);
413
414 const RealScalar inv_m = RealScalar(1) / RealScalar(m);
415 for (Index i = 0; i < n; ++i) {
416 line_buf[i] = internal::pmul(a[i] * inv_m, cj(pos_j_base_powered[i]));
417 }
418 }
419
420 EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE static void scramble_FFT(ComplexScalar* data, Index n) {
421 eigen_assert(isPowerOfTwo(n));
422 Index j = 1;
423 for (Index i = 1; i < n; ++i) {
424 if (j > i) {
425 std::swap(data[j - 1], data[i - 1]);
426 }
427 Index m = n >> 1;
428 while (m >= 2 && j > m) {
429 j -= m;
430 m >>= 1;
431 }
432 j += m;
433 }
434 }
435
436 template <int Dir>
437 EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE void butterfly_2(ComplexScalar* data) {
438 ComplexScalar tmp = data[1];
439 data[1] = data[0] - data[1];
440 data[0] += tmp;
441 }
442
443 // Closed-form ±i multiplications: (re, im) * (0, ±1) without a generic
444 // complex multiply. Dispatched via mul_pm_i<Dir> at the radix-{4,8} leaves.
445 EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE static ComplexScalar mul_neg_i(const ComplexScalar& c) {
446 return ComplexScalar(c.imag(), -c.real());
447 }
448 EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE static ComplexScalar mul_pos_i(const ComplexScalar& c) {
449 return ComplexScalar(-c.imag(), c.real());
450 }
451 template <int Dir>
452 EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE static ComplexScalar mul_pm_i(const ComplexScalar& c) {
453 return (Dir == FFT_FORWARD) ? mul_neg_i(c) : mul_pos_i(c);
454 }
455
456 template <int Dir>
457 EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE void butterfly_4(ComplexScalar* data) {
458 ComplexScalar tmp[4];
459 tmp[0] = data[0] + data[1];
460 tmp[1] = data[0] - data[1];
461 tmp[2] = data[2] + data[3];
462 tmp[3] = mul_pm_i<Dir>(data[2] - data[3]);
463 data[0] = tmp[0] + tmp[2];
464 data[1] = tmp[1] + tmp[3];
465 data[2] = tmp[0] - tmp[2];
466 data[3] = tmp[1] - tmp[3];
467 }
468
469 template <int Dir>
470 EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE void butterfly_8(ComplexScalar* data) {
471 ComplexScalar tmp_1[8];
472 ComplexScalar tmp_2[8];
473
474 tmp_1[0] = data[0] + data[1];
475 tmp_1[1] = data[0] - data[1];
476 tmp_1[2] = data[2] + data[3];
477 tmp_1[3] = mul_pm_i<Dir>(data[2] - data[3]);
478 tmp_1[4] = data[4] + data[5];
479 tmp_1[5] = data[4] - data[5];
480 tmp_1[6] = data[6] + data[7];
481 tmp_1[7] = mul_pm_i<Dir>(data[6] - data[7]);
482 tmp_2[0] = tmp_1[0] + tmp_1[2];
483 tmp_2[1] = tmp_1[1] + tmp_1[3];
484 tmp_2[2] = tmp_1[0] - tmp_1[2];
485 tmp_2[3] = tmp_1[1] - tmp_1[3];
486 tmp_2[4] = tmp_1[4] + tmp_1[6];
487 // omega_8^1 = (sqrt(2)/2, -sqrt(2)/2) for forward.
488 constexpr RealScalar kSqrt2Div2 = RealScalar(0.7071067811865476);
489 if (Dir == FFT_FORWARD) {
490 tmp_2[5] = internal::pmul(tmp_1[5] + tmp_1[7], ComplexScalar(kSqrt2Div2, -kSqrt2Div2));
491 tmp_2[6] = mul_neg_i(tmp_1[4] - tmp_1[6]);
492 tmp_2[7] = internal::pmul(tmp_1[5] - tmp_1[7], ComplexScalar(-kSqrt2Div2, -kSqrt2Div2));
493 } else {
494 tmp_2[5] = internal::pmul(tmp_1[5] + tmp_1[7], ComplexScalar(kSqrt2Div2, kSqrt2Div2));
495 tmp_2[6] = mul_pos_i(tmp_1[4] - tmp_1[6]);
496 tmp_2[7] = internal::pmul(tmp_1[5] - tmp_1[7], ComplexScalar(-kSqrt2Div2, kSqrt2Div2));
497 }
498 data[0] = tmp_2[0] + tmp_2[4];
499 data[1] = tmp_2[1] + tmp_2[5];
500 data[2] = tmp_2[2] + tmp_2[6];
501 data[3] = tmp_2[3] + tmp_2[7];
502 data[4] = tmp_2[0] - tmp_2[4];
503 data[5] = tmp_2[1] - tmp_2[5];
504 data[6] = tmp_2[2] - tmp_2[6];
505 data[7] = tmp_2[3] - tmp_2[7];
506 }
507
508 template <int Dir>
509 EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE void butterfly_1D_merge(ComplexScalar* data, Index n, Index n_power_of_2) {
510 // Original code:
511 // RealScalar wtemp = std::sin(EIGEN_PI/n);
512 // RealScalar wpi = -std::sin(2 * EIGEN_PI/n);
513 const RealScalar wtemp = m_sin_PI_div_n_LUT[n_power_of_2];
514 const RealScalar wpi =
515 (Dir == FFT_FORWARD) ? m_minus_sin_2_PI_div_n_LUT[n_power_of_2] : -m_minus_sin_2_PI_div_n_LUT[n_power_of_2];
516
517 const ComplexScalar wp(wtemp, wpi);
518 const ComplexScalar wp_one = wp + ComplexScalar(1, 0);
519 const Index n2 = n / 2;
520
521#if !defined(EIGEN_GPU_COMPILE_PHASE)
522 // The class-level PacketReturnType keys off OutputScalar, which can be
523 // real for RealPart/ImagPart modes; resolve the complex packet here so
524 // the merge always vectorizes regardless of the output reduction.
525 using CPacket = typename internal::packet_traits<ComplexScalar>::type;
526 constexpr Index CPacketSize = internal::unpacket_traits<CPacket>::size;
527 // A batch's twiddles are a broadcast of the running factor times a
528 // precomputed ramp wp_one^{0..kBatch-1}: one vector pmul per packet
529 // instead of a scalar cmul per lane plus a round-trip through scratch. The
530 // running factor advances by wp_one^kBatch per batch; kBatch >= 4 keeps
531 // that recurrence at the same stride — and thus the same accumulated
532 // rounding — as the original scalar code.
533 //
534 // Two cases fall through to the scalar loop. A 1-wide complex packet
535 // (CPacketSize == 1: Packet1cd, i.e. SSE2 std::complex<double>) carries no
536 // SIMD parallelism — the "vector" path is then scalar dressed in packet
537 // ops and loses to the hand-unrolled scalar fallback. Packets wider than
538 // kMaxBatch (e.g. RVV with VLEN >= 1024 gives CPacketSize == 16 for
539 // std::complex<float>) overflow the ramp.
540 constexpr Index kMaxBatch = 8;
541 constexpr Index kBatch = (CPacketSize >= 4) ? CPacketSize : Index(4);
542 if (CPacketSize >= 2 && CPacketSize <= kMaxBatch && kBatch <= n2) {
543 // ramp[k] = wp_one^k — built once, reused for every batch and every line.
544 alignas(alignof(CPacket)) ComplexScalar ramp[kMaxBatch];
545 ramp[0] = ComplexScalar(1, 0);
546 for (Index k = 1; k < kBatch; ++k) ramp[k] = internal::pmul(ramp[k - 1], wp_one);
547 const ComplexScalar wp_one_batch = internal::pmul(ramp[kBatch - 1], wp_one);
548 const ComplexScalar wp_one_2batch = internal::pmul(wp_one_batch, wp_one_batch);
549
550 // Two batches are processed per iteration with two independent running
551 // factors, so the w recurrence (one complex pmul of latency) is no
552 // longer the serial bottleneck — each chain advances only once per two
553 // batches and overlaps the butterfly work of the other.
554 ComplexScalar w(1, 0);
555 Index i = 0;
556 for (; i + 2 * kBatch <= n2; i += 2 * kBatch) {
557 const CPacket wv0 = internal::pset1<CPacket>(w);
558 const CPacket wv1 = internal::pset1<CPacket>(internal::pmul(w, wp_one_batch));
559 for (Index k = 0; k < kBatch; k += CPacketSize) {
560 const CPacket rk = internal::pload<CPacket>(ramp + k);
561 const CPacket pa0 = internal::ploadu<CPacket>(data + i + k);
562 const CPacket pb0 = internal::ploadu<CPacket>(data + i + n2 + k);
563 const CPacket pa1 = internal::ploadu<CPacket>(data + i + kBatch + k);
564 const CPacket pb1 = internal::ploadu<CPacket>(data + i + kBatch + n2 + k);
565 const CPacket pt0 = internal::pmul(internal::pmul(wv0, rk), pb0);
566 const CPacket pt1 = internal::pmul(internal::pmul(wv1, rk), pb1);
567 internal::pstoreu(data + i + k, internal::padd(pa0, pt0));
568 internal::pstoreu(data + i + n2 + k, internal::psub(pa0, pt0));
569 internal::pstoreu(data + i + kBatch + k, internal::padd(pa1, pt1));
570 internal::pstoreu(data + i + kBatch + n2 + k, internal::psub(pa1, pt1));
571 }
572 w = internal::pmul(w, wp_one_2batch);
573 }
574 // n2 is a power of two >= kBatch, so this tail runs at most once.
575 for (; i < n2; i += kBatch) {
576 const CPacket wv = internal::pset1<CPacket>(w);
577 for (Index k = 0; k < kBatch; k += CPacketSize) {
578 const CPacket pw = internal::pmul(wv, internal::pload<CPacket>(ramp + k));
579 const CPacket pa = internal::ploadu<CPacket>(data + i + k);
580 const CPacket pb = internal::ploadu<CPacket>(data + i + n2 + k);
581 const CPacket pt = internal::pmul(pw, pb);
582 internal::pstoreu(data + i + k, internal::padd(pa, pt));
583 internal::pstoreu(data + i + n2 + k, internal::psub(pa, pt));
584 }
585 }
586 return;
587 }
588#endif
589
590 // Scalar fallback (GPU build, or RVV with VLEN >= 1024 → CPacketSize > 8).
591 const ComplexScalar wp_one_2 = internal::pmul(wp_one, wp_one);
592 const ComplexScalar wp_one_3 = internal::pmul(wp_one_2, wp_one);
593 const ComplexScalar wp_one_4 = internal::pmul(wp_one_3, wp_one);
594 ComplexScalar w(1.0, 0.0);
595 for (Index i = 0; i < n2; i += 4) {
596 const ComplexScalar w1 = internal::pmul(w, wp_one);
597 const ComplexScalar w2 = internal::pmul(w, wp_one_2);
598 const ComplexScalar w3 = internal::pmul(w, wp_one_3);
599 const ComplexScalar temp0 = internal::pmul(data[i + n2], w);
600 const ComplexScalar temp1 = internal::pmul(data[i + 1 + n2], w1);
601 const ComplexScalar temp2 = internal::pmul(data[i + 2 + n2], w2);
602 const ComplexScalar temp3 = internal::pmul(data[i + 3 + n2], w3);
603 w = internal::pmul(w, wp_one_4);
604
605 data[i + n2] = data[i] - temp0;
606 data[i] += temp0;
607
608 data[i + 1 + n2] = data[i + 1] - temp1;
609 data[i + 1] += temp1;
610
611 data[i + 2 + n2] = data[i + 2] - temp2;
612 data[i + 2] += temp2;
613
614 data[i + 3 + n2] = data[i + 3] - temp3;
615 data[i + 3] += temp3;
616 }
617 }
618
619 template <int Dir>
620 EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE void compute_1D_Butterfly(ComplexScalar* data, Index n, Index n_power_of_2) {
621 eigen_assert(isPowerOfTwo(n));
622 if (n > 8) {
623 compute_1D_Butterfly<Dir>(data, n / 2, n_power_of_2 - 1);
624 compute_1D_Butterfly<Dir>(data + n / 2, n / 2, n_power_of_2 - 1);
625 butterfly_1D_merge<Dir>(data, n, n_power_of_2);
626 } else if (n == 8) {
627 butterfly_8<Dir>(data);
628 } else if (n == 4) {
629 butterfly_4<Dir>(data);
630 } else if (n == 2) {
631 butterfly_2<Dir>(data);
632 }
633 }
634
635 EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE Index getBaseOffsetFromIndex(Index index, Index omitted_dim) const {
636 Index result = 0;
637
638 EIGEN_IF_CONSTEXPR (static_cast<int>(Layout) == static_cast<int>(ColMajor)) {
639 for (int i = NumDims - 1; i > omitted_dim; --i) {
640 const Index partial_m_stride = m_strides[i] / m_dimensions[omitted_dim];
641 const Index idx = index / partial_m_stride;
642 index -= idx * partial_m_stride;
643 result += idx * m_strides[i];
644 }
645 result += index;
646 } else {
647 for (Index i = 0; i < omitted_dim; ++i) {
648 const Index partial_m_stride = m_strides[i] / m_dimensions[omitted_dim];
649 const Index idx = index / partial_m_stride;
650 index -= idx * partial_m_stride;
651 result += idx * m_strides[i];
652 }
653 result += index;
654 }
655 // Value of index_coords[omitted_dim] is not determined to this step
656 return result;
657 }
658
659 protected:
660 Index m_size;
661 const FFT EIGEN_DEVICE_REF m_fft;
662 Dimensions m_dimensions;
663 array<Index, NumDims> m_strides;
665 EvaluatorPointerType m_data;
666 const Device EIGEN_DEVICE_REF m_device;
667
668 // This will support a maximum FFT size of 2^32 for each dimension
669 // m_sin_PI_div_n_LUT[i] = (-2) * std::sin(EIGEN_PI / std::pow(2,i)) ^ 2;
670 const RealScalar m_sin_PI_div_n_LUT[32] = {RealScalar(0.0),
671 RealScalar(-2),
672 RealScalar(-0.999999999999999),
673 RealScalar(-0.292893218813453),
674 RealScalar(-0.0761204674887130),
675 RealScalar(-0.0192147195967696),
676 RealScalar(-0.00481527332780311),
677 RealScalar(-0.00120454379482761),
678 RealScalar(-3.01181303795779e-04),
679 RealScalar(-7.52981608554592e-05),
680 RealScalar(-1.88247173988574e-05),
681 RealScalar(-4.70619042382852e-06),
682 RealScalar(-1.17654829809007e-06),
683 RealScalar(-2.94137117780840e-07),
684 RealScalar(-7.35342821488550e-08),
685 RealScalar(-1.83835707061916e-08),
686 RealScalar(-4.59589268710903e-09),
687 RealScalar(-1.14897317243732e-09),
688 RealScalar(-2.87243293150586e-10),
689 RealScalar(-7.18108232902250e-11),
690 RealScalar(-1.79527058227174e-11),
691 RealScalar(-4.48817645568941e-12),
692 RealScalar(-1.12204411392298e-12),
693 RealScalar(-2.80511028480785e-13),
694 RealScalar(-7.01277571201985e-14),
695 RealScalar(-1.75319392800498e-14),
696 RealScalar(-4.38298482001247e-15),
697 RealScalar(-1.09574620500312e-15),
698 RealScalar(-2.73936551250781e-16),
699 RealScalar(-6.84841378126949e-17),
700 RealScalar(-1.71210344531737e-17),
701 RealScalar(-4.28025861329343e-18)};
702
703 // m_minus_sin_2_PI_div_n_LUT[i] = -std::sin(2 * EIGEN_PI / std::pow(2,i));
704 const RealScalar m_minus_sin_2_PI_div_n_LUT[32] = {RealScalar(0.0),
705 RealScalar(0.0),
706 RealScalar(-1.00000000000000e+00),
707 RealScalar(-7.07106781186547e-01),
708 RealScalar(-3.82683432365090e-01),
709 RealScalar(-1.95090322016128e-01),
710 RealScalar(-9.80171403295606e-02),
711 RealScalar(-4.90676743274180e-02),
712 RealScalar(-2.45412285229123e-02),
713 RealScalar(-1.22715382857199e-02),
714 RealScalar(-6.13588464915448e-03),
715 RealScalar(-3.06795676296598e-03),
716 RealScalar(-1.53398018628477e-03),
717 RealScalar(-7.66990318742704e-04),
718 RealScalar(-3.83495187571396e-04),
719 RealScalar(-1.91747597310703e-04),
720 RealScalar(-9.58737990959773e-05),
721 RealScalar(-4.79368996030669e-05),
722 RealScalar(-2.39684498084182e-05),
723 RealScalar(-1.19842249050697e-05),
724 RealScalar(-5.99211245264243e-06),
725 RealScalar(-2.99605622633466e-06),
726 RealScalar(-1.49802811316901e-06),
727 RealScalar(-7.49014056584716e-07),
728 RealScalar(-3.74507028292384e-07),
729 RealScalar(-1.87253514146195e-07),
730 RealScalar(-9.36267570730981e-08),
731 RealScalar(-4.68133785365491e-08),
732 RealScalar(-2.34066892682746e-08),
733 RealScalar(-1.17033446341373e-08),
734 RealScalar(-5.85167231706864e-09),
735 RealScalar(-2.92583615853432e-09)};
736};
737
738} // end namespace Eigen
739
740#endif // EIGEN_TENSOR_TENSOR_FFT_H
The tensor base class.
Definition TensorForwardDeclarations.h:69
Tensor FFT class.
Definition TensorFFT.h:100
Namespace containing all symbols from the Eigen library.
The tensor evaluator class.
Definition TensorEvaluator.h:47