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