-
Notifications
You must be signed in to change notification settings - Fork 24k
/
Copy pathSpectralOps.cpp
1304 lines (1149 loc) · 49.5 KB
/
SpectralOps.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#define TORCH_ASSERT_ONLY_METHOD_OPERATORS
#include <ATen/core/Tensor.h>
#include <ATen/Config.h>
#include <ATen/TensorSubclassLikeUtils.h>
#include <ATen/detail/CUDAHooksInterface.h>
#include <ATen/native/SpectralOpsUtils.h>
#include <ATen/TensorIterator.h>
#include <ATen/TensorOperators.h>
#include <ATen/WrapDimUtils.h>
#include <c10/util/irange.h>
#ifndef AT_PER_OPERATOR_HEADERS
#include <ATen/Functions.h>
#include <ATen/NativeFunctions.h>
#else
#include <ATen/ops/_cufft_clear_plan_cache_native.h>
#include <ATen/ops/_cufft_get_plan_cache_max_size_native.h>
#include <ATen/ops/_cufft_get_plan_cache_size_native.h>
#include <ATen/ops/_cufft_set_plan_cache_max_size_native.h>
#include <ATen/ops/_fft_c2c.h>
#include <ATen/ops/_fft_c2r.h>
#include <ATen/ops/_fft_r2c.h>
#include <ATen/ops/arange.h>
#include <ATen/ops/arange_native.h>
#include <ATen/ops/conj.h>
#include <ATen/ops/conj_physical.h>
#include <ATen/ops/constant_pad_nd.h>
#include <ATen/ops/empty.h>
#include <ATen/ops/fft_fft2_native.h>
#include <ATen/ops/fft_fft_native.h>
#include <ATen/ops/fft_fftfreq_native.h>
#include <ATen/ops/fft_fftn_native.h>
#include <ATen/ops/fft_fftshift_native.h>
#include <ATen/ops/fft_hfft2_native.h>
#include <ATen/ops/fft_hfft_native.h>
#include <ATen/ops/fft_hfftn_native.h>
#include <ATen/ops/fft_ifft2_native.h>
#include <ATen/ops/fft_ifft_native.h>
#include <ATen/ops/fft_ifftn_native.h>
#include <ATen/ops/fft_ifftshift_native.h>
#include <ATen/ops/fft_ihfft2_native.h>
#include <ATen/ops/fft_ihfft_native.h>
#include <ATen/ops/fft_ihfftn_native.h>
#include <ATen/ops/fft_irfft2_native.h>
#include <ATen/ops/fft_irfft_native.h>
#include <ATen/ops/fft_irfftn_native.h>
#include <ATen/ops/fft_rfft2_native.h>
#include <ATen/ops/fft_rfft_native.h>
#include <ATen/ops/fft_rfftfreq_native.h>
#include <ATen/ops/fft_rfftn_native.h>
#include <ATen/ops/istft_native.h>
#include <ATen/ops/ones.h>
#include <ATen/ops/pad.h>
#include <ATen/ops/roll.h>
#include <ATen/ops/stft.h>
#include <ATen/ops/stft_native.h>
#include <ATen/ops/unfold_backward.h>
#include <ATen/ops/view_as_complex.h>
#include <ATen/ops/view_as_real.h>
#include <ATen/ops/zeros.h>
#include <ATen/ops/zeros_like_ops.h>
#endif
#include <algorithm>
namespace at::native {
namespace {
// Promote inputs to FFT functions
// * Integers are promoted to the default floating type
// * If require_complex=True, all types are promoted to complex
// * Raises an error for half-precision dtypes to allow future support
ScalarType promote_type_fft(ScalarType type, bool require_complex, Device device) {
if (at::isComplexType(type)) {
return type;
}
// Promote integral to default float type
if (!at::isFloatingType(type)) {
type = c10::typeMetaToScalarType(c10::get_default_dtype());
}
const bool maybe_support_half = (
// Only CUDA supports half precision, but since meta tensors don't have a
// device we err on the side of accepting it
device.is_cuda() || device.is_meta()
);
if (maybe_support_half) {
TORCH_CHECK(type == kHalf || type == kFloat || type == kDouble, "Unsupported dtype ", type);
} else {
TORCH_CHECK(type == kFloat || type == kDouble, "Unsupported dtype ", type);
}
if (!require_complex) {
return type;
}
// Promote to complex
switch (type) {
case kHalf: return kComplexHalf;
case kFloat: return kComplexFloat;
case kDouble: return kComplexDouble;
default: TORCH_INTERNAL_ASSERT(false, "Unhandled dtype");
}
}
// Promote a tensor's dtype according to promote_type_fft
Tensor promote_tensor_fft(const Tensor& t, bool require_complex=false) {
auto cur_type = t.scalar_type();
auto new_type = promote_type_fft(cur_type, require_complex, t.device());
return (cur_type == new_type) ? t : t.to(new_type);
}
// Convert NumPy compatible normalization mode string to enum values
// NOTE: NumPy's normalization modes have direction-specific meanings. For example,
// "forward" translates to `by_n` for a forward transform and `none` for backward.
fft_norm_mode norm_from_string(std::optional<std::string_view> norm, bool forward) {
if (!norm || *norm == "backward") {
return forward ? fft_norm_mode::none : fft_norm_mode::by_n;
}
if (*norm == "forward") {
return forward ? fft_norm_mode::by_n : fft_norm_mode::none;
}
if (*norm == "ortho") {
return fft_norm_mode::by_root_n;
}
TORCH_CHECK(false, "Invalid normalization mode: \"", *norm, "\"")
}
// Fixes the shape of x such that x.size(dims[i]) == sizes[i],
// either by zero-padding, or by slicing x starting from 0.
Tensor resize_fft_input(Tensor x, IntArrayRef dims, SymIntArrayRef sizes) {
TORCH_INTERNAL_ASSERT(dims.size() == sizes.size());
bool must_copy = false;
auto x_sizes = x.sym_sizes();
SymDimVector pad_amount(x_sizes.size() * 2);
for (const auto i : c10::irange(dims.size())) {
if (sizes[i] == -1) {
continue;
}
if (x_sizes[dims[i]] < sizes[i]) {
must_copy = true;
auto pad_idx = pad_amount.size() - 2 * dims[i] - 1;
pad_amount[pad_idx] = sizes[i] - x_sizes[dims[i]];
}
if (x_sizes[dims[i]] > sizes[i]) {
x = x.slice_symint(dims[i], 0, sizes[i]);
}
}
// Only call pad if necessary since pad copies the entire tensor
return must_copy ? at::constant_pad_nd_symint(x, pad_amount) : x;
}
Tensor fft_r2c_maybe_out(
std::string_view fname, const Tensor& out, const Tensor& input,
IntArrayRef dim, int64_t norm, bool onesided) {
if (out.defined()) {
TORCH_CHECK(out.is_complex(), fname,
" expects a complex output tensor, but got ", out.scalar_type());
auto out_mut = out;
return at::_fft_r2c_outf(input, dim, norm, onesided, out_mut);
}
return at::_fft_r2c(input, dim, norm, onesided);
}
Tensor fft_c2r_maybe_out(
std::string_view fname, const Tensor& out, const Tensor& input,
IntArrayRef dim, int64_t norm, SymInt last_dim_size) {
// Support out argument if defined, otherwise call functional
// variant so autograd works properly.
if (out.defined()) {
TORCH_CHECK(out.is_floating_point(), fname,
" expects a floating point output tensor, but got ", out.scalar_type());
auto out_mut = out;
return at::_fft_c2r_symint_outf(input, dim, norm, last_dim_size, out_mut);
}
return at::_fft_c2r_symint(input, dim, norm, last_dim_size);
}
Tensor fft_c2c_maybe_out(
std::string_view fname, const Tensor& out, const Tensor& input,
IntArrayRef dim, int64_t norm, bool forward) {
if (out.defined()) {
TORCH_CHECK(out.is_complex(), fname,
" expects a complex output tensor, but got ", out.scalar_type());
auto out_mut = out;
return at::_fft_c2c_outf(input, dim, norm, forward, out_mut);
}
return at::_fft_c2c(input, dim, norm, forward);
}
// Complex to real FFT
Tensor fft_c2r(std::string_view function_name,
Tensor out, Tensor input, std::optional<SymInt> n_opt,
int64_t unwrapped_dim, std::optional<std::string_view> norm_str,
bool forward) {
TORCH_CHECK(!out.defined() || out.is_floating_point(), function_name,
" expects a floating point output tensor, but got ", out.scalar_type());
input = promote_tensor_fft(input, /*require_complex=*/true);
const auto input_dim = input.dim();
const auto dim = maybe_wrap_dim(unwrapped_dim, input_dim, /*wrap_scalar=*/false);
const auto n = n_opt.value_or(2*(input.sym_sizes()[dim] - 1));
TORCH_CHECK(n >= 1, "Invalid number of data points (", n, ") specified");
if (n_opt) {
input = resize_fft_input(input, dim, n/2 + 1);
}
const auto norm = norm_from_string(norm_str, forward);
if (forward) {
// FIXME: _fft does not support complex_output=false with inverse=false
input = input.conj();
}
return fft_c2r_maybe_out(
function_name, out, input, dim, static_cast<int64_t>(norm), n);
}
// Real to complex FFT
Tensor fft_r2c(std::string_view function_name,
Tensor out, Tensor input, std::optional<SymInt> n_opt,
int64_t unwrapped_dim, std::optional<std::string_view> norm_str,
bool forward, bool onesided) {
TORCH_CHECK(!input.is_complex(), function_name,
" expects a real input tensor, but got ", input.scalar_type());
TORCH_CHECK(!out.defined() || out.is_complex(), function_name,
" expects a complex output tensor, but got ", out.scalar_type());
input = promote_tensor_fft(input);
const auto input_dim = input.dim();
const auto dim = maybe_wrap_dim(unwrapped_dim, input_dim, /*wrap_scalar=*/false);
const auto n = n_opt.value_or(input.sym_sizes()[dim]);
TORCH_CHECK(n >= 1, "Invalid number of data points (", n, ") specified");
if (n_opt) {
input = resize_fft_input(input, dim, n);
}
const auto norm = norm_from_string(norm_str, forward);
Tensor ret;
if (out.defined() && forward) {
ret = at::_fft_r2c_out(out, input, dim, static_cast<int64_t>(norm), onesided);
} else {
ret = at::_fft_r2c(input, dim, static_cast<int64_t>(norm), onesided);
}
if (!forward) {
// FIXME: _fft_r2c doesn't support native r2c IFFT
return out.defined() ? at::conj_physical_out(out, ret) : ret.conj();
} else {
return ret;
}
}
// Complex to complex FFT
Tensor fft_c2c(std::string_view function_name,
Tensor out, Tensor input, std::optional<SymInt> n_opt,
int64_t unwrapped_dim, std::optional<std::string_view> norm_str,
bool forward) {
TORCH_CHECK(input.is_complex(), function_name,
" expects a complex input tensor, but got ", input.scalar_type());
const auto input_dim = input.dim();
const auto dim = maybe_wrap_dim(unwrapped_dim, input_dim, /*wrap_scalar=*/false);
const auto n = n_opt.value_or(input.sym_sizes()[dim]);
TORCH_CHECK(n >= 1, "Invalid number of data points (", n, ") specified");
if (n_opt) {
input = resize_fft_input(input, dim, n);
}
const auto norm = static_cast<int64_t>(norm_from_string(norm_str, forward));
return fft_c2c_maybe_out(function_name, out, input, dim, norm, forward);
}
// Dimensions to transform, and the signal shape in those dimensions
struct ShapeAndDims {
SymDimVector shape;
DimVector dim;
};
// Pre-process n-dimensional fft's `s` and `dim` arguments.
// Wraps dimensions and applies defaulting behavior.
// Also checks transform dims are unique and transform shape is non-empty.
ShapeAndDims canonicalize_fft_shape_and_dim_args(
Tensor input, at::OptionalSymIntArrayRef shape, at::OptionalIntArrayRef dim) {
const int64_t input_dim = input.dim();
const SymIntArrayRef input_sizes = input.sym_sizes();
ShapeAndDims ret;
if (dim) {
ret.dim.resize(dim->size());
std::copy(dim->begin(), dim->end(), ret.dim.begin());
maybe_wrap_dims(ret.dim, input_dim, /*wrap_scalars=*/false);
// Check dims are unique
DimVector copy = ret.dim;
std::sort(copy.begin(), copy.end());
auto duplicate = std::adjacent_find(copy.begin(), copy.end());
TORCH_CHECK(duplicate == copy.end(), "FFT dims must be unique");
}
if (shape) {
// Has shape, may have dim
TORCH_CHECK(!dim ||
dim->size() == shape->size(),
"When given, dim and shape arguments must have the same length");
TORCH_CHECK(static_cast<int64_t>(shape->size()) <= input_dim,
"Got shape with ", shape->size(), " values but input tensor "
"only has ", input_dim, " dimensions.");
const int64_t transform_ndim = shape->size();
// If shape is given, dims defaults to the last shape.size() dimensions
if (!dim) {
ret.dim.resize(transform_ndim);
std::iota(ret.dim.begin(), ret.dim.end(), input_dim - transform_ndim);
}
// Translate shape of -1 to the default length
ret.shape.resize(transform_ndim);
for (const auto i : c10::irange(transform_ndim)) {
const auto n = (*shape)[i];
ret.shape[i] = n == -1 ? input_sizes[ret.dim[i]] : n;
}
} else if (!dim) {
// No shape, no dim
ret.dim.resize(input_dim);
std::iota(ret.dim.begin(), ret.dim.end(), int64_t{0});
ret.shape.resize(input_dim);
std::copy(input_sizes.begin(), input_sizes.end(), ret.shape.begin());
} else {
// No shape, has dim
ret.shape.resize(ret.dim.size());
for (const auto i : c10::irange(ret.dim.size())) {
ret.shape[i] = input_sizes[ret.dim[i]];
}
}
for (const auto & shape : ret.shape) {
TORCH_CHECK(shape > 0,
"Invalid number of data points (", shape, ") specified");
}
return ret;
}
// Complex to complex n-dimensional fft
Tensor fftn_c2c(
std::string_view function_name,
Tensor out, const Tensor& input, SymIntArrayRef shape,
IntArrayRef dim, std::optional<std::string_view> norm_str, bool forward) {
TORCH_CHECK(input.is_complex(), function_name, " expects a complex input tensor, but got", input.scalar_type());
Tensor x = resize_fft_input(input, dim, shape);
const auto norm = static_cast<int64_t>(norm_from_string(norm_str, forward));
constexpr std::string_view fname = "fftn";
return fft_c2c_maybe_out(fname, out, x, dim, norm, forward);
}
} // namespace (anonymous)
// torch.fft.fft, analogous to NumPy's numpy.fft.fft
Tensor fft_fft_symint(const Tensor& self, std::optional<SymInt> n, int64_t dim,
std::optional<std::string_view> norm) {
return self.is_complex() ?
fft_c2c("fft", {}, self, n, dim, norm, /*forward=*/true) :
fft_r2c("fft", {}, self, n, dim, norm, /*forward=*/true, /*onesided=*/false);
}
Tensor& fft_fft_symint_out(const Tensor& self, std::optional<SymInt> n,
int64_t dim, std::optional<std::string_view> norm, Tensor& out) {
if (self.is_complex()) {
fft_c2c("fft", out, self, n, dim, norm, /*forward=*/true);
} else {
fft_r2c("fft", out, self, n, dim, norm, /*forward=*/true, /*onesided=*/false);
}
return out;
}
Tensor fft_ifft_symint(const Tensor& self, std::optional<SymInt> n, int64_t dim,
std::optional<std::string_view> norm) {
return self.is_complex() ?
fft_c2c("ifft", {}, self, n, dim, norm, /*forward=*/false) :
fft_r2c("ifft", {}, self, n, dim, norm, /*forward=*/false, /*onesided=*/false);
}
Tensor& fft_ifft_symint_out(const Tensor& self, std::optional<SymInt> n,
int64_t dim, std::optional<std::string_view> norm, Tensor& out) {
if (self.is_complex()) {
fft_c2c("ifft", out, self, n, dim, norm, /*forward=*/false);
} else {
fft_r2c("ifft", out, self, n, dim, norm, /*forward=*/false, /*onesided=*/false);
}
return out;
}
Tensor fft_rfft_symint(const Tensor& self, std::optional<SymInt> n, int64_t dim,
std::optional<std::string_view> norm) {
return fft_r2c("rfft", {}, self, n, dim, norm, /*forward=*/true, /*onesided=*/true);
}
Tensor& fft_rfft_symint_out(const Tensor& self, std::optional<SymInt> n,
int64_t dim, std::optional<std::string_view> norm, Tensor& out) {
fft_r2c("rfft", out, self, n, dim, norm, /*forward=*/true, /*onesided=*/true);
return out;
}
Tensor fft_irfft_symint(const Tensor& self, std::optional<SymInt> n, int64_t dim,
std::optional<std::string_view> norm) {
return fft_c2r("irfft", {}, self, n, dim, norm, /*forward=*/false);
}
Tensor& fft_irfft_symint_out(const Tensor& self, std::optional<SymInt> n,
int64_t dim, std::optional<std::string_view> norm, Tensor& out) {
fft_c2r("irfft", out, self, n, dim, norm, /*forward=*/false);
return out;
}
Tensor fft_hfft_symint(const Tensor& self, std::optional<SymInt> n, int64_t dim,
std::optional<std::string_view> norm) {
return fft_c2r("hfft", {}, self, n, dim, norm, /*forward=*/true);
}
Tensor& fft_hfft_symint_out(const Tensor& self, std::optional<SymInt> n,
int64_t dim, std::optional<std::string_view> norm, Tensor& out) {
fft_c2r("hfft", out, self, n, dim, norm, /*forward=*/true);
return out;
}
Tensor fft_ihfft_symint(const Tensor& self, std::optional<SymInt> n, int64_t dim,
std::optional<std::string_view> norm) {
return fft_r2c("ihfft", {}, self, n, dim, norm, /*forward=*/false, /*onesided=*/true);
}
Tensor& fft_ihfft_symint_out(const Tensor& self, std::optional<SymInt> n,
int64_t dim, std::optional<std::string_view> norm, Tensor& out) {
fft_r2c("ihfft", out, self, n, dim, norm, /*forward=*/false, /*onesided=*/true);
return out;
}
Tensor fft_fftn_symint(const Tensor& self, at::OptionalSymIntArrayRef s,
at::OptionalIntArrayRef dim,
std::optional<std::string_view> norm) {
auto desc = canonicalize_fft_shape_and_dim_args(self, s, dim);
// TODO: For real input, perform rfftn then mirror with conjugate symmetry
Tensor input = promote_tensor_fft(self, /*require_complex=*/true);
return fftn_c2c("fftn", {}, input, desc.shape, desc.dim, norm, /*forward=*/true);
}
Tensor& fft_fftn_symint_out(const Tensor& self,
at::OptionalSymIntArrayRef s,
at::OptionalIntArrayRef dim,
std::optional<std::string_view> norm, Tensor& out) {
auto desc = canonicalize_fft_shape_and_dim_args(self, s, dim);
// TODO: For real input, perform rfftn then mirror with conjugate symmetry
Tensor input = promote_tensor_fft(self, /*require_complex=*/true);
fftn_c2c("fftn", out, input, desc.shape, desc.dim, norm, /*forward=*/true);
return out;
}
Tensor fft_ifftn_symint(const Tensor& self, at::OptionalSymIntArrayRef s,
at::OptionalIntArrayRef dim,
std::optional<std::string_view> norm) {
auto desc = canonicalize_fft_shape_and_dim_args(self, s, dim);
Tensor input = promote_tensor_fft(self, /*require_complex=*/true);
return fftn_c2c("ifftn", {}, input, desc.shape, desc.dim, norm, /*forward=*/false);
}
Tensor& fft_ifftn_symint_out(const Tensor& self,
at::OptionalSymIntArrayRef s,
at::OptionalIntArrayRef dim,
std::optional<std::string_view> norm, Tensor& out) {
auto desc = canonicalize_fft_shape_and_dim_args(self, s, dim);
Tensor input = promote_tensor_fft(self, /*require_complex=*/true);
fftn_c2c("ifftn", out, input, desc.shape, desc.dim, norm, /*forward=*/false);
return out;
}
static Tensor fft_rfftn_impl(Tensor out, const Tensor& self,
at::OptionalSymIntArrayRef s,
at::OptionalIntArrayRef dim,
const std::optional<std::string_view>& norm_str) {
TORCH_CHECK(!self.is_complex(), "rfftn expects a real-valued input tensor, but got ", self.scalar_type());
auto desc = canonicalize_fft_shape_and_dim_args(self, s, dim);
TORCH_CHECK(!desc.shape.empty(), "rfftn must transform at least one axis");
Tensor input = promote_tensor_fft(self, /*require_complex=*/false);
Tensor x = resize_fft_input(input, desc.dim, desc.shape);
const auto norm = static_cast<int64_t>(norm_from_string(norm_str, /*forward=*/true));
constexpr std::string_view fname = "rfftn";
return fft_r2c_maybe_out(fname, out, x, desc.dim, norm, /*onesided=*/true);
}
Tensor fft_rfftn_symint(const Tensor& self, at::OptionalSymIntArrayRef s,
at::OptionalIntArrayRef dim,
std::optional<std::string_view> norm_str) {
return fft_rfftn_impl({}, self, s, dim, norm_str);
}
Tensor& fft_rfftn_symint_out(const Tensor& self,
at::OptionalSymIntArrayRef s,
at::OptionalIntArrayRef dim,
std::optional<std::string_view> norm_str, Tensor& out) {
fft_rfftn_impl(out, self, s, dim, norm_str);
return out;
}
static ShapeAndDims canonicalize_fft_c2r_shape_and_dim_args(
std::string_view fname, const Tensor& self,
const at::OptionalSymIntArrayRef& s,
const at::OptionalIntArrayRef& dims,
SymInt& last_dim_size) {
auto desc = canonicalize_fft_shape_and_dim_args(self, s, dims);
TORCH_CHECK(!desc.shape.empty(), fname, " must transform at least one axis");
// Expected output size of the hermitian-symmetric dimension
last_dim_size = [&] {
// Fixup default shape handling in the last dimension,
if (!s.has_value() || (s->back() == -1)) {
const auto last_dim = desc.dim.back();
return 2 * (self.sym_sizes()[last_dim] - 1);
}
return desc.shape.back();
}();
TORCH_CHECK(last_dim_size >= 1, "Invalid number of data points (", last_dim_size, ") specified");
// Expected input size of the complex-hermitian data
desc.shape.back() = last_dim_size / 2 + 1;
return desc;
}
static Tensor fft_irfftn_impl(Tensor out, const Tensor& self,
at::OptionalSymIntArrayRef s,
at::OptionalIntArrayRef dim,
const std::optional<std::string_view>& norm_str) {
SymInt last_dim_size = 0;
auto desc = canonicalize_fft_c2r_shape_and_dim_args(
"irfftn", self, s, dim, last_dim_size);
Tensor input = promote_tensor_fft(self, /*require_complex=*/true);
Tensor x = resize_fft_input(input, desc.dim, desc.shape);
const auto norm = static_cast<int64_t>(norm_from_string(norm_str, /*forward=*/false));
constexpr std::string_view fname = "irfftn";
return fft_c2r_maybe_out(fname, out, x, desc.dim, norm, last_dim_size);
}
Tensor fft_irfftn_symint(const Tensor& self,
at::OptionalSymIntArrayRef s,
at::OptionalIntArrayRef dim,
std::optional<std::string_view> norm_str) {
return fft_irfftn_impl({}, self, s, dim, norm_str);
}
Tensor& fft_irfftn_symint_out(const Tensor& self,
at::OptionalSymIntArrayRef s,
at::OptionalIntArrayRef dim,
std::optional<std::string_view> norm_str, Tensor& out) {
fft_irfftn_impl(out, self, s, dim, norm_str);
return out;
}
static Tensor fft_hfftn_impl(
const Tensor& self,
at::OptionalSymIntArrayRef s,
at::OptionalIntArrayRef dim,
std::optional<std::string_view> norm_str,
const Tensor& out) {
constexpr std::string_view fname = "hfftn";
SymInt last_dim_size = 0;
auto desc = canonicalize_fft_c2r_shape_and_dim_args(
fname, self, s, dim, last_dim_size);
auto input = promote_tensor_fft(self, /*require_complex=*/true);
auto x = resize_fft_input(input, desc.dim, desc.shape);
const auto norm = static_cast<int64_t>(
norm_from_string(norm_str, /*forward=*/true));
Tensor tmp;
if (desc.dim.size() > 1) {
auto c2c_dims = IntArrayRef(desc.dim).slice(0, desc.dim.size() - 1);
tmp = at::_fft_c2c(x, c2c_dims, norm, /*forward=*/true);
} else {
tmp = x;
}
const auto last_dim = desc.dim.back();
tmp = tmp.conj();
return fft_c2r_maybe_out(fname, out, tmp, last_dim, norm, last_dim_size);
}
Tensor fft_hfftn_symint(
const Tensor& self,
at::OptionalSymIntArrayRef s,
at::OptionalIntArrayRef dim,
std::optional<std::string_view> norm) {
return fft_hfftn_impl(self, s, dim, norm, {});
}
Tensor& fft_hfftn_symint_out(
const Tensor& self,
at::OptionalSymIntArrayRef s,
at::OptionalIntArrayRef dim, std::optional<std::string_view> norm,
Tensor& out) {
fft_hfftn_impl(self, s, dim, norm, out);
return out;
}
static Tensor fft_ihfftn_impl(
const Tensor& self,
const at::OptionalSymIntArrayRef& s,
const at::OptionalIntArrayRef& dim,
const std::optional<std::string_view>& norm_str,
const Tensor& out) {
constexpr std::string_view fname = "ihfftn";
auto desc = canonicalize_fft_shape_and_dim_args(self, s, dim);
TORCH_CHECK(!desc.shape.empty(), "ihfftn must transform at least one axis");
auto input = promote_tensor_fft(self, /*require_complex=*/false);
auto x = resize_fft_input(input, desc.dim, desc.shape);
const auto norm = static_cast<int64_t>(
norm_from_string(norm_str, /*forward=*/false));
const auto last_dim = desc.dim.back();
auto tmp = at::_fft_r2c(x, last_dim, norm, /*onesided=*/true);
if (desc.dim.size() == 1) {
return out.defined() ? at::conj_physical_out(tmp, out) : tmp.conj();
}
tmp = at::conj_physical(tmp);
auto c2c_dims = IntArrayRef(desc.dim).slice(0, desc.dim.size() - 1);
return fft_c2c_maybe_out(fname, out, tmp, c2c_dims, norm, /*forward=*/false);
}
Tensor fft_ihfftn_symint(
const Tensor& self,
at::OptionalSymIntArrayRef s,
at::OptionalIntArrayRef dim,
std::optional<std::string_view> norm) {
return fft_ihfftn_impl(self, s, dim, norm, {});
}
Tensor& fft_ihfftn_symint_out(
const Tensor& self,
at::OptionalSymIntArrayRef s,
at::OptionalIntArrayRef dim,
std::optional<std::string_view> norm,
Tensor& out) {
fft_ihfftn_impl(self, s, dim, norm, out);
return out;
}
Tensor fft_fft2_symint(const Tensor& self, at::OptionalSymIntArrayRef s,
IntArrayRef dim, std::optional<std::string_view> norm) {
return native::fft_fftn_symint(self, s, dim, std::move(norm));
}
Tensor& fft_fft2_symint_out(const Tensor& self, at::OptionalSymIntArrayRef s,
IntArrayRef dim, std::optional<std::string_view> norm, Tensor& out) {
return native::fft_fftn_symint_out(self, s, dim, std::move(norm), out);
}
Tensor fft_ifft2_symint(const Tensor& self, at::OptionalSymIntArrayRef s,
IntArrayRef dim, std::optional<std::string_view> norm) {
return native::fft_ifftn_symint(self, s, dim, std::move(norm));
}
Tensor& fft_ifft2_symint_out(const Tensor& self, at::OptionalSymIntArrayRef s,
IntArrayRef dim, std::optional<std::string_view> norm, Tensor& out) {
return native::fft_ifftn_symint_out(self, s, dim, std::move(norm), out);
}
Tensor fft_rfft2_symint(const Tensor& self, at::OptionalSymIntArrayRef s,
IntArrayRef dim, std::optional<std::string_view> norm) {
return native::fft_rfftn_symint(self, s, dim, std::move(norm));
}
Tensor& fft_rfft2_symint_out(const Tensor& self, at::OptionalSymIntArrayRef s,
IntArrayRef dim, std::optional<std::string_view> norm, Tensor& out) {
return native::fft_rfftn_symint_out(self, s, dim, std::move(norm), out);
}
Tensor fft_irfft2_symint(const Tensor& self, at::OptionalSymIntArrayRef s,
IntArrayRef dim, std::optional<std::string_view> norm) {
return native::fft_irfftn_symint(self, s, dim, std::move(norm));
}
Tensor& fft_irfft2_symint_out(const Tensor& self, at::OptionalSymIntArrayRef s,
IntArrayRef dim, std::optional<std::string_view> norm, Tensor& out) {
return native::fft_irfftn_symint_out(self, s, dim, std::move(norm), out);
}
Tensor& fft_hfft2_symint_out(
const Tensor& self, at::OptionalSymIntArrayRef s, IntArrayRef dim,
std::optional<std::string_view> norm, Tensor& out) {
return native::fft_hfftn_symint_out(self, s, dim, std::move(norm), out);
}
Tensor fft_hfft2_symint(const Tensor& self, at::OptionalSymIntArrayRef s,
IntArrayRef dim, std::optional<std::string_view> norm) {
return native::fft_hfftn_symint(self, s, dim, std::move(norm));
}
Tensor& fft_ihfft2_symint_out(
const Tensor& self, at::OptionalSymIntArrayRef s, IntArrayRef dim,
std::optional<std::string_view> norm, Tensor& out) {
return native::fft_ihfftn_symint_out(self, s, dim, std::move(norm), out);
}
Tensor fft_ihfft2_symint(const Tensor& self, at::OptionalSymIntArrayRef s,
IntArrayRef dim, std::optional<std::string_view> norm) {
return native::fft_ihfftn_symint(self, s, dim, std::move(norm));
}
Tensor& fft_fftfreq_out(int64_t n, double d, Tensor& out) {
ScalarType dtype = out.scalar_type();
TORCH_CHECK(at::isFloatingType(dtype) || at::isComplexType(dtype),
"fftfreq requires a floating point or complex dtype");
// TODO: arange doesn't have complex support
at::arange_out(out, n);
auto right_slice = out.slice(0, (n + 1) / 2, 0);
at::arange_out(right_slice, -(n/2), 0, 1);
return out.mul_(1.0 / (n * d)); // Slightly faster than div_(n*d)
}
Tensor fft_fftfreq(int64_t n, double d,
std::optional<ScalarType> dtype,
std::optional<Layout> layout,
std::optional<Device> device,
std::optional<bool> pin_memory) {
// See [Note: hacky wrapper removal for TensorOptions]
TensorOptions options = TensorOptions().dtype(dtype).layout(layout).device(device).pinned_memory(pin_memory);
auto out = at::empty({n}, options);
return native::fft_fftfreq_out(n, d, out);
}
Tensor& fft_rfftfreq_out(int64_t n, double d, Tensor& out) {
ScalarType dtype = out.scalar_type();
TORCH_CHECK(at::isFloatingType(dtype) || at::isComplexType(dtype),
"rfftfreq requires a floating point or complex dtype");
// TODO: arange doesn't have complex support
native::arange_out(n/2 + 1, out);
return out.mul_(1.0 / (n * d)); // Slightly faster than div_(n*d)
}
Tensor fft_rfftfreq(int64_t n, double d,
std::optional<ScalarType> dtype,
std::optional<Layout> layout,
std::optional<Device> device,
std::optional<bool> pin_memory) {
// See [Note: hacky wrapper removal for TensorOptions]
TensorOptions options = TensorOptions().dtype(dtype).layout(layout).device(device).pinned_memory(pin_memory);
auto out = at::empty({n/2 + 1}, options);
return native::fft_rfftfreq_out(n, d, out);
}
// If an array dim is specified, wraps them according to self.dim().
// Otherwise returns a vector of all dims.
static DimVector default_alldims(const Tensor& self, at::OptionalIntArrayRef dim_opt) {
DimVector dim;
if (dim_opt) {
IntArrayRef dim_unwrapped = *dim_opt;
dim.resize(dim_unwrapped.size());
for (const auto i : c10::irange(dim.size())) {
dim[i] = maybe_wrap_dim(dim_unwrapped[i], self.dim(), /*wrap_scalar=*/false);
}
} else {
dim.resize(self.dim());
std::iota(dim.begin(), dim.end(), 0);
}
return dim;
}
Tensor fft_fftshift(const Tensor& x, at::OptionalIntArrayRef dim_opt) {
auto dim = default_alldims(x, dim_opt);
SymIntArrayRef x_sizes = x.sym_sizes();
SymDimVector shift(dim.size());
for (const auto i : c10::irange(dim.size())) {
shift[i] = x_sizes[dim[i]] / 2;
}
return at::roll_symint(x, shift, dim);
}
Tensor fft_ifftshift(const Tensor& x, at::OptionalIntArrayRef dim_opt) {
auto dim = default_alldims(x, dim_opt);
SymIntArrayRef x_sizes = x.sym_sizes();
SymDimVector shift(dim.size());
for (const auto i : c10::irange(dim.size())) {
shift[i] = (x_sizes[dim[i]] + 1) / 2;
}
return at::roll_symint(x, shift, dim);
}
// We call the following methods via CUDA hooks because they are really only
// valid when CUDA is available. See native/cuda/CuFFTPlanCache.h for more details.
int64_t _cufft_get_plan_cache_max_size(DeviceIndex device_index) {
return detail::getCUDAHooks().cuFFTGetPlanCacheMaxSize(device_index);
}
void _cufft_set_plan_cache_max_size(DeviceIndex device_index, int64_t max_size) {
detail::getCUDAHooks().cuFFTSetPlanCacheMaxSize(device_index, max_size);
}
int64_t _cufft_get_plan_cache_size(DeviceIndex device_index) {
return detail::getCUDAHooks().cuFFTGetPlanCacheSize(device_index);
}
void _cufft_clear_plan_cache(DeviceIndex device_index) {
detail::getCUDAHooks().cuFFTClearPlanCache(device_index);
}
template <typename Stream, typename T>
static Stream& write_opt(Stream& SS, const std::optional<T>& value) {
if (value) {
SS << *value;
} else {
SS << "None";
}
return SS;
}
/* Short-time Fourier Transform, for signal analysis.
*
* This is modeled after librosa but with support for complex time-domain
* signals and complex windows.
*/
Tensor stft(const Tensor& self, const int64_t n_fft, const std::optional<int64_t> hop_lengthOpt,
const std::optional<int64_t> win_lengthOpt, const std::optional<Tensor>& window_opt,
const bool center, std::string_view mode, const bool normalized,
const std::optional<bool> onesidedOpt, const std::optional<bool> return_complexOpt, const std::optional<bool> align_to_windowOpt) {
// See [Note: hacky wrapper removal for optional tensor]
c10::MaybeOwned<Tensor> window_maybe_owned = at::borrow_from_optional_tensor(window_opt);
const Tensor& window = *window_maybe_owned;
// Warn if window is not provided
if (!window.defined()) {
TORCH_WARN_ONCE(
"A window was not provided. A rectangular window will be applied,"
"which is known to cause spectral leakage. "
"Other windows such as torch.hann_window or torch.hamming_window "
"are recommended to reduce spectral leakage."
"To suppress this warning and use a rectangular window, explicitly set "
"`window=torch.ones(n_fft, device=<device>)`.");
}
#define REPR(SS) \
SS << "stft(" << self.toString() << self.sizes() << ", n_fft=" << n_fft \
<< ", hop_length=" << hop_length << ", win_length=" << win_length \
<< ", window="; \
if (window.defined()) { \
SS << window.toString() << "{" << window.sizes() << "}"; \
} else { \
SS << "None"; \
} \
SS << ", normalized=" << normalized << ", onesided="; \
write_opt(SS, onesidedOpt) << ", return_complex="; \
write_opt(SS, return_complexOpt) << ", align_to_window="; \
write_opt(SS, align_to_windowOpt) << ") "
TORCH_CHECK(!window.defined() || window.device() == self.device(),
"stft input and window must be on the same device but got self on ",
self.device(), " and window on ", window.device())
TORCH_CHECK(!center || !align_to_windowOpt.has_value(),
"stft align_to_window should only be set when center = false.")
// default_init hop_length and win_length
auto hop_length = hop_lengthOpt.value_or(n_fft >> 2);
auto win_length = win_lengthOpt.value_or(n_fft);
const bool return_complex = return_complexOpt.value_or(
self.is_complex() || (window.defined() && window.is_complex()));
if (!return_complex) {
TORCH_CHECK(return_complexOpt.has_value(),
"stft requires the return_complex parameter be given for real inputs, "
"and will further require that return_complex=True in a future PyTorch release.");
TORCH_WARN_ONCE(
"stft with return_complex=False is deprecated. In a future pytorch "
"release, stft will return complex tensors for all inputs, and "
"return_complex=False will raise an error.\n"
"Note: you can still call torch.view_as_real on the complex output to "
"recover the old return format.");
}
if (!at::isFloatingType(self.scalar_type()) && !at::isComplexType(self.scalar_type())) {
std::ostringstream ss;
REPR(ss) << ": expected a tensor of floating point or complex values";
TORCH_CHECK(false, ss.str());
}
if (self.dim() > 2 || self.dim() < 1) {
std::ostringstream ss;
REPR(ss) << ": expected a 1D or 2D tensor";
TORCH_CHECK(false, ss.str());
}
Tensor input = self;
if (self.dim() == 1) {
input = input.unsqueeze(0);
}
if (center) {
const auto input_shape = input.sizes();
const auto input_dim = input_shape.size();
const auto extra_dims = std::max(size_t{3}, input_dim) - input_dim;
const auto pad_amount = n_fft / 2;
DimVector extended_shape(extra_dims, 1);
extended_shape.append(input_shape.begin(), input_shape.end());
input = at::pad(input.view(extended_shape), {pad_amount, pad_amount}, mode);
input = input.view(IntArrayRef(input.sizes()).slice(extra_dims));
}
int64_t batch = input.size(0);
int64_t len = input.size(1);
if (n_fft <= 0 || n_fft > len) {
std::ostringstream ss;
REPR(ss) << ": expected 0 < n_fft < " << len
<< ", but got n_fft=" << win_length;
TORCH_CHECK(false, ss.str());
}
if (hop_length <= 0) {
std::ostringstream ss;
REPR(ss) << ": expected hop_length > 0, but got hop_length=" << hop_length;
TORCH_CHECK(false, ss.str());
}
if (win_length <= 0 || win_length > n_fft) {
std::ostringstream ss;
REPR(ss) << ": expected 0 < win_length <= n_fft, but got win_length="
<< win_length;
TORCH_CHECK(false, ss.str());
}
if (window.defined() && (window.dim() != 1 || window.size(0) != win_length)) {
std::ostringstream ss;
REPR(ss) << ": expected a 1D window tensor of size equal to win_length="
<< win_length << ", but got window with size " << window.sizes();
TORCH_CHECK(false, ss.str());
}
#undef REPR
auto window_ = window;
if (win_length < n_fft) {
// pad center
auto left = (n_fft - win_length) / 2;
if (window.defined()) {
window_ = at::zeros({n_fft}, window.options());
window_.narrow(0, left, win_length).copy_(window);
} else {
window_ = at::zeros({n_fft}, self.options());
window_.narrow(0, left, win_length).fill_(1);
}
}
const bool align_to_window = align_to_windowOpt.value_or(false);
int64_t n_frames;
if (!center && align_to_window) {
// Calculate n_frames based on window length, since we are aligning start of window with t = 0.
n_frames = 1 + (len - win_length) / hop_length;
// Window-based padding.
input = at::pad(input, {(n_fft - win_length) / 2, (n_fft - win_length) / 2}, mode);
} else {
n_frames = 1 + (len - n_fft) / hop_length;
}
// time2col
input = input.as_strided(
{batch, n_frames, n_fft},
{input.stride(0), hop_length * input.stride(1), input.stride(1)}
);
if (window_.defined()) {
input = input.mul(window_);
}
// FFT and transpose to get (batch x fft_size x num_frames)
const bool complex_fft = input.is_complex();
const auto onesided = onesidedOpt.value_or(!complex_fft);
const fft_norm_mode norm = normalized ? fft_norm_mode::by_root_n : fft_norm_mode::none;
Tensor out;
if (complex_fft) {
TORCH_CHECK(!onesided, "Cannot have onesided output if window or input is complex");
out = at::_fft_c2c(input, input.dim() - 1, static_cast<int64_t>(norm), /*forward=*/true);
} else {
out = at::_fft_r2c(input, input.dim() - 1, static_cast<int64_t>(norm), onesided);
}
out.transpose_(1, 2);
if (self.dim() == 1) {
out.squeeze_(0);
}
if (return_complex) {
return out;
} else {
return at::view_as_real(out);
}
}
Tensor stft(
const Tensor& self, const int64_t n_fft, const std::optional<int64_t> hop_lengthOpt,
const std::optional<int64_t> win_lengthOpt, const std::optional<Tensor>& window_opt,
const bool normalized,
const std::optional<bool> onesidedOpt, const std::optional<bool> return_complexOpt,
const std::optional<bool> align_to_windowOpt) {
return at::stft(
self, n_fft, hop_lengthOpt, win_lengthOpt, window_opt,