numr 0.15.0

High-performance numerical computing with multi-backend GPU acceleration (CPU/CUDA/WebGPU)
Documentation
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
//! CUDA implementation of FFT algorithms
//!
//! This module implements the [`FftAlgorithms`] trait for CUDA using native
//! Stockham FFT kernels. All algorithms follow the exact specification in
//! the trait documentation to ensure backend parity with CPU implementations.
//!
//! Native CUDA kernels are used - NO cuFFT dependency.

use super::CudaRuntime;
use super::client::CudaClient;
use super::fft_bluestein::{BluesteinInput, bluestein_transform};
use super::kernels;
use crate::algorithm::fft::{
    FftAlgorithms, FftDirection, FftNormalization, complex_dtype_for_real, real_dtype_for_complex,
    validate_fft_complex_dtype, validate_rfft_real_dtype,
};
use crate::dtype::DType;
use crate::error::{Error, Result};
use crate::runtime::{AllocGuard, Runtime, RuntimeClient};
use crate::tensor::{Layout, Storage, Tensor};

impl FftAlgorithms<CudaRuntime> for CudaClient {
    fn fft(
        &self,
        input: &Tensor<CudaRuntime>,
        direction: FftDirection,
        norm: FftNormalization,
    ) -> Result<Tensor<CudaRuntime>> {
        // Validate input
        let dtype = input.dtype();
        validate_fft_complex_dtype(dtype, "fft")?;

        let ndim = input.ndim();
        if ndim == 0 {
            return Err(Error::InvalidArgument {
                arg: "input",
                reason: "FFT requires at least 1D input".to_string(),
            });
        }

        let n = input.shape()[ndim - 1];
        if n == 0 {
            return Err(Error::InvalidArgument {
                arg: "input",
                reason: "FFT requires size >= 1 along the last dim, got 0".to_string(),
            });
        }

        // Ensure contiguous input
        let input_contig = if input.is_contiguous() {
            input.clone()
        } else {
            input.contiguous()?
        };

        // Calculate batch size and scale factor
        // Unclamped: rank-1 already products to 1, a zero batch dim must stay 0.
        let batch_size: usize = input_contig.shape()[..ndim - 1].iter().product();

        // No row to transform. `n >= 1` is validated above, so every kernel below
        // would read a full row out of the empty input allocation.
        if batch_size == 0 {
            return Tensor::<CudaRuntime>::empty(input_contig.shape(), dtype, self.device());
        }

        let scale = norm.factor(direction, n);
        let inverse = direction == FftDirection::Inverse;

        // Non-power-of-two lengths go through Bluestein, which reduces them to a
        // power-of-two convolution the Stockham kernels below can run.
        if !n.is_power_of_two() {
            let guard = bluestein_transform(
                self,
                dtype,
                BluesteinInput::Complex,
                input_contig.ptr(),
                n,
                n,
                batch_size,
                inverse,
                scale,
            )?;
            return Ok(unsafe {
                Self::tensor_from_raw(guard.release(), input_contig.shape(), dtype, self.device())
            });
        }

        let device = self.device();
        let total_elements = batch_size * n;

        // Allocate output
        let output_size = total_elements * dtype.size_in_bytes();
        let output_guard = AllocGuard::new(self.allocator(), output_size)?;
        let output_ptr = output_guard.ptr();

        let input_ptr = input_contig.ptr();

        // Choose small FFT (shared memory) or large FFT (multi-stage) based on size
        if n <= kernels::MAX_SHARED_MEM_FFT_SIZE {
            // Small FFT: single kernel with shared memory
            unsafe {
                kernels::launch_stockham_fft_batched(
                    self.context(),
                    self.stream(),
                    device.index,
                    dtype,
                    input_ptr,
                    output_ptr,
                    n,
                    batch_size,
                    inverse,
                    scale,
                )?;
            }
        } else {
            // Large FFT: multi-stage with ping-pong buffers
            let log_n = (n as f64).log2() as usize;

            // Allocate temp buffer for ping-pong
            let temp_guard = AllocGuard::new(self.allocator(), output_size)?;
            let temp_ptr = temp_guard.ptr();

            // Copy input to one buffer
            CudaRuntime::copy_within_device(input_ptr, output_ptr, output_size, device)?;

            let mut src_ptr = output_ptr;
            let mut dst_ptr = temp_ptr;

            // Run all stages
            for stage in 0..log_n {
                unsafe {
                    kernels::launch_stockham_fft_stage(
                        self.context(),
                        self.stream(),
                        device.index,
                        dtype,
                        src_ptr,
                        dst_ptr,
                        n,
                        stage,
                        batch_size,
                        inverse,
                    )?;
                }
                std::mem::swap(&mut src_ptr, &mut dst_ptr);
            }

            // Apply scale if needed
            if (scale - 1.0).abs() > 1e-10 {
                unsafe {
                    kernels::launch_scale_complex(
                        self.context(),
                        self.stream(),
                        device.index,
                        dtype,
                        src_ptr,
                        scale,
                        total_elements,
                    )?;
                }
            }

            // If result is in temp buffer, copy to output
            if src_ptr == temp_ptr {
                CudaRuntime::copy_within_device(temp_ptr, output_ptr, output_size, device)?;
            }
        }

        self.synchronize();

        // Create output tensor
        let output = unsafe {
            Self::tensor_from_raw(output_guard.release(), input_contig.shape(), dtype, device)
        };

        Ok(output)
    }

    fn fft_dim(
        &self,
        input: &Tensor<CudaRuntime>,
        dim: isize,
        direction: FftDirection,
        norm: FftNormalization,
    ) -> Result<Tensor<CudaRuntime>> {
        let dtype = input.dtype();
        validate_fft_complex_dtype(dtype, "fft_dim")?;

        let ndim = input.ndim();
        if ndim == 0 {
            return Err(Error::InvalidArgument {
                arg: "input",
                reason: "FFT requires at least 1D input".to_string(),
            });
        }

        // Normalize dimension
        let dim_usize = if dim < 0 {
            (ndim as isize + dim) as usize
        } else {
            dim as usize
        };

        if dim_usize >= ndim {
            return Err(Error::InvalidDimension { dim, ndim });
        }

        // If dim is already the last dimension, use regular fft
        if dim_usize == ndim - 1 {
            return self.fft(input, direction, norm);
        }

        // Otherwise, permute to move target dim to last, compute FFT, permute back
        let mut perm: Vec<usize> = (0..ndim).collect();
        perm.remove(dim_usize);
        perm.push(dim_usize);

        let permuted = input.permute(&perm)?;
        let fft_result = self.fft(&permuted, direction, norm)?;

        // Inverse permutation
        let mut inv_perm = vec![0; ndim];
        for (i, &p) in perm.iter().enumerate() {
            inv_perm[p] = i;
        }

        fft_result.permute(&inv_perm)
    }

    fn rfft(
        &self,
        input: &Tensor<CudaRuntime>,
        norm: FftNormalization,
    ) -> Result<Tensor<CudaRuntime>> {
        let dtype = input.dtype();
        validate_rfft_real_dtype(dtype, "rfft")?;

        let ndim = input.ndim();
        if ndim == 0 {
            return Err(Error::InvalidArgument {
                arg: "input",
                reason: "rfft requires at least 1D input".to_string(),
            });
        }

        let n = input.shape()[ndim - 1];
        if n == 0 {
            return Err(Error::InvalidArgument {
                arg: "input",
                reason: "rfft requires size >= 1 along the last dim, got 0".to_string(),
            });
        }

        let input_contig = if input.is_contiguous() {
            input.clone()
        } else {
            input.contiguous()?
        };

        let complex_dtype = complex_dtype_for_real(dtype)?;
        let device = self.device();

        // Unclamped: rank-1 already products to 1, a zero batch dim must stay 0.
        let batch_size: usize = input_contig.shape()[..ndim - 1].iter().product();

        // No row to transform. `n >= 1` is validated above, so every kernel below
        // would read a full row out of the empty input allocation.
        if batch_size == 0 {
            let mut out_shape = input_contig.shape().to_vec();
            out_shape[ndim - 1] = n / 2 + 1;
            return Tensor::<CudaRuntime>::empty(&out_shape, complex_dtype, device);
        }

        // Bluestein for non-power-of-two. `out_n` keeps the Hermitian half
        // directly, so no separate truncate pass is needed.
        if !n.is_power_of_two() {
            let out_n = n / 2 + 1;
            let guard = bluestein_transform(
                self,
                complex_dtype,
                BluesteinInput::Real,
                input_contig.ptr(),
                n,
                out_n,
                batch_size,
                false,
                norm.factor(FftDirection::Forward, n),
            )?;
            let mut out_shape = input_contig.shape().to_vec();
            out_shape[ndim - 1] = out_n;
            return Ok(unsafe {
                Self::tensor_from_raw(guard.release(), &out_shape, complex_dtype, device)
            });
        }

        // Allocate complex buffer for full FFT
        let complex_size = batch_size * n * complex_dtype.size_in_bytes();
        let complex_guard = AllocGuard::new(self.allocator(), complex_size)?;
        let complex_ptr = complex_guard.ptr();

        // Pack real to complex (zero imaginary parts)
        unsafe {
            kernels::launch_rfft_pack(
                self.context(),
                self.stream(),
                device.index,
                dtype,
                input_contig.ptr(),
                complex_ptr,
                n,
                batch_size,
            )?;
        }

        // Compute full complex FFT
        let scale = norm.factor(FftDirection::Forward, n);

        if n <= kernels::MAX_SHARED_MEM_FFT_SIZE {
            // In-place for small FFTs
            let temp_guard = AllocGuard::new(self.allocator(), complex_size)?;
            let temp_ptr = temp_guard.ptr();
            unsafe {
                kernels::launch_stockham_fft_batched(
                    self.context(),
                    self.stream(),
                    device.index,
                    complex_dtype,
                    complex_ptr,
                    temp_ptr,
                    n,
                    batch_size,
                    false,
                    scale,
                )?;
            }
            CudaRuntime::copy_within_device(temp_ptr, complex_ptr, complex_size, device)?;
        } else {
            // Multi-stage for large FFTs
            let log_n = (n as f64).log2() as usize;
            let temp_guard = AllocGuard::new(self.allocator(), complex_size)?;
            let temp_ptr = temp_guard.ptr();

            let mut src_ptr = complex_ptr;
            let mut dst_ptr = temp_ptr;

            for stage in 0..log_n {
                unsafe {
                    kernels::launch_stockham_fft_stage(
                        self.context(),
                        self.stream(),
                        device.index,
                        complex_dtype,
                        src_ptr,
                        dst_ptr,
                        n,
                        stage,
                        batch_size,
                        false,
                    )?;
                }
                std::mem::swap(&mut src_ptr, &mut dst_ptr);
            }

            if (scale - 1.0).abs() > 1e-10 {
                unsafe {
                    kernels::launch_scale_complex(
                        self.context(),
                        self.stream(),
                        device.index,
                        complex_dtype,
                        src_ptr,
                        scale,
                        batch_size * n,
                    )?;
                }
            }

            if src_ptr != complex_ptr {
                CudaRuntime::copy_within_device(src_ptr, complex_ptr, complex_size, device)?;
            }
        }

        // Truncate to N/2 + 1 elements (Hermitian symmetry)
        let output_n = n / 2 + 1;
        let output_size = batch_size * output_n * complex_dtype.size_in_bytes();
        let output_guard = AllocGuard::new(self.allocator(), output_size)?;
        let output_ptr = output_guard.ptr();

        unsafe {
            kernels::launch_rfft_truncate(
                self.context(),
                self.stream(),
                device.index,
                complex_dtype,
                complex_ptr,
                output_ptr,
                n,
                output_n,
                batch_size,
            )?;
        }
        self.synchronize();

        // Build output shape
        let mut out_shape = input_contig.shape().to_vec();
        out_shape[ndim - 1] = output_n;

        let output = unsafe {
            Self::tensor_from_raw(output_guard.release(), &out_shape, complex_dtype, device)
        };

        Ok(output)
    }

    fn irfft(
        &self,
        input: &Tensor<CudaRuntime>,
        n: Option<usize>,
        norm: FftNormalization,
    ) -> Result<Tensor<CudaRuntime>> {
        let dtype = input.dtype();
        validate_fft_complex_dtype(dtype, "irfft")?;

        let ndim = input.ndim();
        if ndim == 0 {
            return Err(Error::InvalidArgument {
                arg: "input",
                reason: "irfft requires at least 1D input".to_string(),
            });
        }

        let input_n = input.shape()[ndim - 1];
        if input_n == 0 {
            return Err(Error::InvalidArgument {
                arg: "input",
                reason: "irfft requires size >= 1 along the last dim, got 0".to_string(),
            });
        }
        let output_n = n.unwrap_or_else(|| 2 * (input_n - 1));
        // Matching the CPU backend: the Hermitian half must be exactly the size
        // the requested output implies, whatever `output_n` is.
        if output_n / 2 + 1 != input_n {
            return Err(Error::InvalidArgument {
                arg: "n",
                reason: format!(
                    "For irfft with n={}, input must have size {}, got {}",
                    output_n,
                    output_n / 2 + 1,
                    input_n
                ),
            });
        }
        if output_n == 0 {
            return Err(Error::InvalidArgument {
                arg: "n",
                reason: "irfft requires output size >= 1, got 0".to_string(),
            });
        }

        let input_contig = if input.is_contiguous() {
            input.clone()
        } else {
            input.contiguous()?
        };

        let device = self.device();
        let real_dtype = real_dtype_for_complex(dtype)?;

        // Unclamped: rank-1 already products to 1, a zero batch dim must stay 0.
        let batch_size: usize = input_contig.shape()[..ndim - 1].iter().product();

        // No row to transform. `output_n >= 1` is validated above, so every kernel
        // below would read a full row out of the empty input allocation.
        if batch_size == 0 {
            let mut out_shape = input_contig.shape().to_vec();
            out_shape[ndim - 1] = output_n;
            return Tensor::<CudaRuntime>::empty(&out_shape, real_dtype, device);
        }

        // Non-power-of-two: extend the Hermitian half to a full spectrum, run
        // the inverse transform through Bluestein, then drop the (zero)
        // imaginary parts. This is the path NeuCodec's n_fft = 1920 vocoder
        // iSTFT takes.
        if !output_n.is_power_of_two() {
            let full_bytes = batch_size * output_n * dtype.size_in_bytes();
            let full_guard = AllocGuard::new(self.allocator(), full_bytes)?;
            unsafe {
                kernels::launch_hermitian_extend(
                    self.context(),
                    self.stream(),
                    device.index,
                    dtype,
                    input_contig.ptr(),
                    full_guard.ptr(),
                    input_n,
                    output_n,
                    batch_size,
                )?;
            }

            let scale = norm.factor(FftDirection::Inverse, output_n);
            let complex_guard = bluestein_transform(
                self,
                dtype,
                BluesteinInput::Complex,
                full_guard.ptr(),
                output_n,
                output_n,
                batch_size,
                true,
                scale,
            )?;

            let real_bytes = batch_size * output_n * real_dtype.size_in_bytes();
            let real_guard = AllocGuard::new(self.allocator(), real_bytes)?;
            unsafe {
                kernels::launch_irfft_unpack(
                    self.context(),
                    self.stream(),
                    device.index,
                    real_dtype,
                    complex_guard.ptr(),
                    real_guard.ptr(),
                    output_n,
                    // Normalization already applied by the Bluestein postmultiply.
                    1.0,
                    batch_size,
                )?;
            }
            self.synchronize();

            let mut out_shape = input_contig.shape().to_vec();
            out_shape[ndim - 1] = output_n;
            return Ok(unsafe {
                Self::tensor_from_raw(real_guard.release(), &out_shape, real_dtype, device)
            });
        }

        // Extend Hermitian spectrum to full spectrum
        let full_complex_size = batch_size * output_n * dtype.size_in_bytes();
        let full_complex_guard = AllocGuard::new(self.allocator(), full_complex_size)?;
        let full_complex_ptr = full_complex_guard.ptr();

        unsafe {
            kernels::launch_hermitian_extend(
                self.context(),
                self.stream(),
                device.index,
                dtype,
                input_contig.ptr(),
                full_complex_ptr,
                input_n,
                output_n,
                batch_size,
            )?;
        }

        // Compute inverse FFT (scale handled separately)
        if output_n <= kernels::MAX_SHARED_MEM_FFT_SIZE {
            let temp_guard = AllocGuard::new(self.allocator(), full_complex_size)?;
            let temp_ptr = temp_guard.ptr();
            unsafe {
                kernels::launch_stockham_fft_batched(
                    self.context(),
                    self.stream(),
                    device.index,
                    dtype,
                    full_complex_ptr,
                    temp_ptr,
                    output_n,
                    batch_size,
                    true,
                    1.0, // Scale applied in unpack
                )?;
            }
            CudaRuntime::copy_within_device(temp_ptr, full_complex_ptr, full_complex_size, device)?;
        } else {
            let log_n = (output_n as f64).log2() as usize;
            let temp_guard = AllocGuard::new(self.allocator(), full_complex_size)?;
            let temp_ptr = temp_guard.ptr();

            let mut src_ptr = full_complex_ptr;
            let mut dst_ptr = temp_ptr;

            for stage in 0..log_n {
                unsafe {
                    kernels::launch_stockham_fft_stage(
                        self.context(),
                        self.stream(),
                        device.index,
                        dtype,
                        src_ptr,
                        dst_ptr,
                        output_n,
                        stage,
                        batch_size,
                        true,
                    )?;
                }
                std::mem::swap(&mut src_ptr, &mut dst_ptr);
            }

            if src_ptr != full_complex_ptr {
                CudaRuntime::copy_within_device(
                    src_ptr,
                    full_complex_ptr,
                    full_complex_size,
                    device,
                )?;
            }
        }

        // Unpack to real with scaling
        let scale = norm.factor(FftDirection::Inverse, output_n);
        let output_size = batch_size * output_n * real_dtype.size_in_bytes();
        let output_guard = AllocGuard::new(self.allocator(), output_size)?;
        let output_ptr = output_guard.ptr();

        unsafe {
            kernels::launch_irfft_unpack(
                self.context(),
                self.stream(),
                device.index,
                real_dtype,
                full_complex_ptr,
                output_ptr,
                output_n,
                scale,
                batch_size,
            )?;
        }
        self.synchronize();

        // Build output shape
        let mut out_shape = input_contig.shape().to_vec();
        out_shape[ndim - 1] = output_n;

        let output = unsafe {
            Self::tensor_from_raw(output_guard.release(), &out_shape, real_dtype, device)
        };

        Ok(output)
    }

    fn fft2(
        &self,
        input: &Tensor<CudaRuntime>,
        direction: FftDirection,
        norm: FftNormalization,
    ) -> Result<Tensor<CudaRuntime>> {
        let ndim = input.ndim();
        if ndim < 2 {
            return Err(Error::InvalidArgument {
                arg: "input",
                reason: "fft2 requires at least 2D input".to_string(),
            });
        }

        // FFT along last two dimensions (dim=-1, then dim=-2)
        // Apply normalization to both dimensions
        let result = self.fft_dim(input, -1, direction, norm)?;
        self.fft_dim(&result, -2, direction, norm)
    }

    fn rfft2(
        &self,
        input: &Tensor<CudaRuntime>,
        norm: FftNormalization,
    ) -> Result<Tensor<CudaRuntime>> {
        let ndim = input.ndim();
        if ndim < 2 {
            return Err(Error::InvalidArgument {
                arg: "input",
                reason: "rfft2 requires at least 2D input".to_string(),
            });
        }

        // rfft along last dimension, then fft along second-to-last
        let result = self.rfft(input, norm)?;
        self.fft_dim(&result, -2, FftDirection::Forward, norm)
    }

    fn irfft2(
        &self,
        input: &Tensor<CudaRuntime>,
        s: Option<(usize, usize)>,
        norm: FftNormalization,
    ) -> Result<Tensor<CudaRuntime>> {
        let ndim = input.ndim();
        if ndim < 2 {
            return Err(Error::InvalidArgument {
                arg: "input",
                reason: "irfft2 requires at least 2D input".to_string(),
            });
        }

        // Inverse FFT along second-to-last dimension first
        let result = self.fft_dim(input, -2, FftDirection::Inverse, norm)?;

        // Then irfft along last dimension
        let n = s.map(|(_, n)| n);
        self.irfft(&result, n, norm)
    }

    fn fftshift(&self, input: &Tensor<CudaRuntime>) -> Result<Tensor<CudaRuntime>> {
        let dtype = input.dtype();
        validate_fft_complex_dtype(dtype, "fftshift")?;

        let ndim = input.ndim();
        if ndim == 0 {
            return Ok(input.clone());
        }

        let n = input.shape()[ndim - 1];
        let input_contig = if input.is_contiguous() {
            input.clone()
        } else {
            input.contiguous()?
        };

        let device = self.device();
        // Unclamped: rank-1 already products to 1, a zero batch dim must stay 0.
        let batch_size: usize = input_contig.shape()[..ndim - 1].iter().product();

        // Nothing to shift. The kernel is launched over `batch_size * n` without
        // flooring, and reads the input row by row out of an empty allocation.
        if batch_size == 0 || n == 0 {
            return Tensor::<CudaRuntime>::empty(input_contig.shape(), dtype, device);
        }

        let total_elements = batch_size * n;
        let output_size = total_elements * dtype.size_in_bytes();
        let output_guard = AllocGuard::new(self.allocator(), output_size)?;
        let output_ptr = output_guard.ptr();

        unsafe {
            kernels::launch_fftshift(
                self.context(),
                self.stream(),
                device.index,
                dtype,
                input_contig.ptr(),
                output_ptr,
                n,
                batch_size,
            )?;
        }

        self.synchronize();

        let output = unsafe {
            Self::tensor_from_raw(output_guard.release(), input_contig.shape(), dtype, device)
        };

        Ok(output)
    }

    fn ifftshift(&self, input: &Tensor<CudaRuntime>) -> Result<Tensor<CudaRuntime>> {
        let dtype = input.dtype();
        validate_fft_complex_dtype(dtype, "ifftshift")?;

        let ndim = input.ndim();
        if ndim == 0 {
            return Ok(input.clone());
        }

        let n = input.shape()[ndim - 1];
        let input_contig = if input.is_contiguous() {
            input.clone()
        } else {
            input.contiguous()?
        };

        let device = self.device();
        // Unclamped: rank-1 already products to 1, a zero batch dim must stay 0.
        let batch_size: usize = input_contig.shape()[..ndim - 1].iter().product();

        // Nothing to shift. The kernel is launched over `batch_size * n` without
        // flooring, and reads the input row by row out of an empty allocation.
        if batch_size == 0 || n == 0 {
            return Tensor::<CudaRuntime>::empty(input_contig.shape(), dtype, device);
        }

        let total_elements = batch_size * n;
        let output_size = total_elements * dtype.size_in_bytes();
        let output_guard = AllocGuard::new(self.allocator(), output_size)?;
        let output_ptr = output_guard.ptr();

        unsafe {
            kernels::launch_ifftshift(
                self.context(),
                self.stream(),
                device.index,
                dtype,
                input_contig.ptr(),
                output_ptr,
                n,
                batch_size,
            )?;
        }

        self.synchronize();

        let output = unsafe {
            Self::tensor_from_raw(output_guard.release(), input_contig.shape(), dtype, device)
        };

        Ok(output)
    }

    fn fftfreq(
        &self,
        n: usize,
        d: f64,
        dtype: DType,
        device: &super::CudaDevice,
    ) -> Result<Tensor<CudaRuntime>> {
        validate_rfft_real_dtype(dtype, "fftfreq")?;

        // Generate frequencies on CPU and transfer
        // [0, 1, 2, ..., N/2-1, -N/2, ..., -1] / (d*N)
        let factor = 1.0 / (d * n as f64);
        let half = (n + 1) / 2;

        let freqs: Vec<f64> = (0..n)
            .map(|i| {
                if i < half {
                    i as f64 * factor
                } else {
                    (i as isize - n as isize) as f64 * factor
                }
            })
            .collect();

        match dtype {
            DType::F32 => {
                let freqs_f32: Vec<f32> = freqs.iter().map(|&x| x as f32).collect();
                Tensor::<CudaRuntime>::from_slice(&freqs_f32, &[n], device)
            }
            DType::F64 => Tensor::<CudaRuntime>::from_slice(&freqs, &[n], device),
            _ => Err(Error::UnsupportedDType {
                dtype,
                op: "fftfreq",
            }),
        }
    }

    fn rfftfreq(
        &self,
        n: usize,
        d: f64,
        dtype: DType,
        device: &super::CudaDevice,
    ) -> Result<Tensor<CudaRuntime>> {
        validate_rfft_real_dtype(dtype, "rfftfreq")?;

        // Generate frequencies on CPU and transfer
        // [0, 1, 2, ..., N/2] / (d*N)
        let factor = 1.0 / (d * n as f64);
        let out_n = n / 2 + 1;

        let freqs: Vec<f64> = (0..out_n).map(|i| i as f64 * factor).collect();

        match dtype {
            DType::F32 => {
                let freqs_f32: Vec<f32> = freqs.iter().map(|&x| x as f32).collect();
                Tensor::<CudaRuntime>::from_slice(&freqs_f32, &[out_n], device)
            }
            DType::F64 => Tensor::<CudaRuntime>::from_slice(&freqs, &[out_n], device),
            _ => Err(Error::UnsupportedDType {
                dtype,
                op: "rfftfreq",
            }),
        }
    }
}

// Helper method - reuse from linalg.rs pattern
impl CudaClient {
    /// Create a tensor from a raw CUDA GPU pointer for FFT operations.
    ///
    /// This wraps the tensor_from_raw helper defined in linalg.rs.
    #[allow(dead_code)]
    unsafe fn fft_tensor_from_raw(
        ptr: u64,
        shape: &[usize],
        dtype: DType,
        device: &super::CudaDevice,
    ) -> Tensor<CudaRuntime> {
        let len = if shape.is_empty() {
            1
        } else {
            shape.iter().product()
        };
        let storage = unsafe { Storage::<CudaRuntime>::from_ptr(ptr, len, dtype, device) };
        let layout = Layout::contiguous(shape);
        Tensor::from_parts(storage, layout)
    }
}