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
//! GPU-accelerated FFT implementation using wgpu compute shaders.
//!
//! Implements the **Stockham autosort** Radix-4/2 FFT — a two-buffer ping-pong formulation
//! where each stage reads from one buffer and writes to the other. This eliminates the separate
//! bit-reversal pass and removes all inter-stage memory hazards.
//!
//! Also implements **Bluestein's algorithm** for arbitrary FFT sizes (not just powers of 2).
use std::any::Any;
use std::cell::RefCell;
use std::num::NonZeroU64;
use num_complex::Complex;
use crate::shaders;
/// Trait for FFT implementations that can be benchmarked.
pub trait FftExecutor {
fn name(&self) -> &str;
fn fft(
&self,
inputs: &[Vec<Complex<f32>>],
) -> Result<Vec<Vec<Complex<f32>>>, Box<dyn std::error::Error>>;
fn ifft(
&self,
inputs: &[Vec<Complex<f32>>],
) -> Result<Vec<Vec<Complex<f32>>>, Box<dyn std::error::Error>>;
/// Get a reference to the underlying type for downcasting.
fn as_any(&self) -> &dyn Any;
}
/// Trait for GPU FFT implementations that support GPU-only benchmarking.
pub trait GpuFftTrait {
/// Benchmark only the GPU compute pass and DMA operations (isolated from CPU overhead).
/// Returns duration in seconds for the GPU operations only.
fn benchmark_gpu_only(
&self,
sc: &SizeCache,
batch_size: u32,
n: usize,
warmup_iters: usize,
bench_iters: usize,
) -> Result<f64, Box<dyn std::error::Error>>;
/// Get or build size-specific GPU resources.
fn get_or_build_size_cache(&self, n: usize, log_n: u32) -> SizeCache;
/// Prepare input data for GPU processing, applying conjugation for IFFT if needed.
fn prepare_input_data(&self, input: &[Complex<f32>], inverse: bool) -> Vec<f32>;
/// Get the queue for GPU operations.
fn queue(&self) -> &wgpu::Queue;
}
/// Pre-allocated GPU resources for a specific FFT size.
#[derive(Clone)]
pub struct SizeCache {
pub buf_a: wgpu::Buffer,
pub buf_b: wgpu::Buffer,
pub staging_buf: wgpu::Buffer,
#[allow(dead_code)]
pub twiddle_buf: wgpu::Buffer,
#[allow(dead_code)]
pub data_bytes: u64,
/// R4 stages (R4 mode) or R2 stages (legacy with_shader mode).
pub stage_bgs: Vec<wgpu::BindGroup>,
/// Final R2 stage when log₂N is odd (R4 mode only).
pub stage_bg_r2: Option<wgpu::BindGroup>,
pub result_in_b: bool,
/// Workgroup count for the main-stage dispatch (N/4 in R4 mode, N/2 in legacy mode).
pub wg_n2: u32,
/// Workgroup count for R4 dispatch (N/4). 0 in legacy mode.
pub wg_r4: u32,
}
/// Uniforms passed to the compute shader (16-byte aligned).
#[repr(C)]
#[derive(Copy, Clone, bytemuck::Pod, bytemuck::Zeroable)]
pub struct FftUniforms {
pub n: u32,
pub stage: u32,
pub log_n: u32,
pub _pad: u32,
}
/// GPU-accelerated FFT engine backed by wgpu compute shaders.
///
/// Implements the Stockham autosort Radix-4 algorithm with an optional Radix-2
/// final stage for odd log₂N sizes. Use [`GpuFft::new`] for the default R4
/// pipeline or [`GpuFft::with_shader`] to supply a custom WGSL kernel.
///
/// For arbitrary FFT sizes (not powers of 2), Bluestein's algorithm is used automatically.
pub struct GpuFft {
pub device: wgpu::Device,
pub queue: wgpu::Queue,
pub pipeline: wgpu::ComputePipeline,
/// Present only when created via `new()` (R4 mode). `None` in legacy `with_shader` mode.
pub pipeline_r2: Option<wgpu::ComputePipeline>,
pub cache: RefCell<std::collections::HashMap<usize, SizeCache>>,
}
impl FftExecutor for GpuFft {
fn name(&self) -> &str {
"Baseline (Stockham Radix-4/2)"
}
fn fft(
&self,
inputs: &[Vec<Complex<f32>>],
) -> Result<Vec<Vec<Complex<f32>>>, Box<dyn std::error::Error>> {
self.transform_batch_internal(inputs, false)
}
fn ifft(
&self,
inputs: &[Vec<Complex<f32>>],
) -> Result<Vec<Vec<Complex<f32>>>, Box<dyn std::error::Error>> {
self.transform_batch_internal(inputs, true)
}
fn as_any(&self) -> &dyn Any {
self
}
}
impl GpuFftTrait for GpuFft {
fn benchmark_gpu_only(
&self,
sc: &SizeCache,
batch_size: u32,
n: usize,
warmup_iters: usize,
bench_iters: usize,
) -> Result<f64, Box<dyn std::error::Error>> {
use std::time::Instant;
// Warmup
for _ in 0..warmup_iters {
self.execute_compute_pass(sc, batch_size, n);
self.device.poll(wgpu::PollType::Wait {
submission_index: None,
timeout: None,
})?;
}
// Benchmark
let start = Instant::now();
for _ in 0..bench_iters {
self.execute_compute_pass(sc, batch_size, n);
}
self.device.poll(wgpu::PollType::Wait {
submission_index: None,
timeout: None,
})?;
let duration = start.elapsed();
Ok(duration.as_secs_f64() / bench_iters as f64)
}
fn get_or_build_size_cache(&self, n: usize, log_n: u32) -> SizeCache {
self.get_or_build_size_cache(n, log_n)
}
fn prepare_input_data(&self, input: &[Complex<f32>], inverse: bool) -> Vec<f32> {
self.prepare_input_data(input, inverse)
}
fn queue(&self) -> &wgpu::Queue {
&self.queue
}
}
impl GpuFft {
/// Access the underlying wgpu device.
pub fn device(&self) -> &wgpu::Device {
&self.device
}
/// Access the compiled compute pipeline.
pub fn compute_pipeline(&self) -> &wgpu::ComputePipeline {
&self.pipeline
}
/// Create a new [`GpuFft`] using the Radix-4/2 Stockham baseline.
///
/// Dispatches ⌊log₄N⌋ Radix-4 passes (+ one Radix-2 pass when log₂N is odd),
/// halving the pass count vs the old Radix-2 baseline.
///
/// For arbitrary FFT sizes (not powers of 2), Bluestein's algorithm is used automatically.
///
/// # Examples
///
/// ```no_run
/// use wgsl_fft::GpuFft;
///
/// let fft = GpuFft::new().expect("GPU required");
/// // Now use fft.fft() and fft.ifft()
/// ```
pub fn new() -> Result<Self, Box<dyn std::error::Error>> {
let instance = wgpu::Instance::default();
let adapter = pollster::block_on(instance.request_adapter(&wgpu::RequestAdapterOptions {
power_preference: wgpu::PowerPreference::HighPerformance,
compatible_surface: None,
force_fallback_adapter: false,
}))
.or_else(|_| {
pollster::block_on(instance.request_adapter(&wgpu::RequestAdapterOptions {
power_preference: wgpu::PowerPreference::HighPerformance,
compatible_surface: None,
force_fallback_adapter: true,
}))
})?;
let (device, queue) =
pollster::block_on(adapter.request_device(&wgpu::DeviceDescriptor {
..Default::default()
}))?;
let compile = |src: &str, label: &str| {
let shader = device.create_shader_module(wgpu::ShaderModuleDescriptor {
label: Some(label),
source: wgpu::ShaderSource::Wgsl(src.into()),
});
device.create_compute_pipeline(&wgpu::ComputePipelineDescriptor {
label: Some(&format!("{label}_pipeline")),
layout: None,
module: &shader,
entry_point: Some("main"),
compilation_options: Default::default(),
cache: None,
})
};
let pipeline = compile(shaders::R4_WGSL, "stockham_r4");
let pipeline_r2 = Some(compile(shaders::R2_WGSL, "stockham_r2"));
Ok(Self {
device,
queue,
pipeline,
pipeline_r2,
cache: RefCell::new(std::collections::HashMap::new()),
})
}
/// Create a new [`GpuFft`] with a custom WGSL shader.
/// This allows AI rivals to swap kernels easily.
pub fn with_shader(
wgsl_source: String,
label: &str,
) -> Result<Self, Box<dyn std::error::Error>> {
let instance = wgpu::Instance::default();
let adapter = pollster::block_on(instance.request_adapter(&wgpu::RequestAdapterOptions {
power_preference: wgpu::PowerPreference::HighPerformance,
compatible_surface: None,
force_fallback_adapter: false,
}))
.or_else(|_| {
pollster::block_on(instance.request_adapter(&wgpu::RequestAdapterOptions {
power_preference: wgpu::PowerPreference::HighPerformance,
compatible_surface: None,
force_fallback_adapter: true,
}))
})?;
let (device, queue) =
pollster::block_on(adapter.request_device(&wgpu::DeviceDescriptor {
..Default::default()
}))?;
let shader_mod = device.create_shader_module(wgpu::ShaderModuleDescriptor {
label: Some(label),
source: wgpu::ShaderSource::Wgsl(wgsl_source.into()),
});
let pipeline = device.create_compute_pipeline(&wgpu::ComputePipelineDescriptor {
label: Some(&format!("{}_pipeline", label)),
layout: None,
module: &shader_mod,
entry_point: Some("main"),
compilation_options: Default::default(),
cache: None,
});
Ok(Self {
device,
queue,
pipeline,
pipeline_r2: None, // legacy single-pipeline mode
cache: RefCell::new(std::collections::HashMap::new()),
})
}
/// Check if a GPU is available without creating an instance.
pub fn is_gpu_available() -> bool {
let instance = wgpu::Instance::default();
pollster::block_on(instance.request_adapter(&wgpu::RequestAdapterOptions {
power_preference: wgpu::PowerPreference::HighPerformance,
compatible_surface: None,
force_fallback_adapter: false,
}))
.is_ok()
}
/// Compute the forward FFT for a batch of input vectors.
///
/// Processes multiple FFTs efficiently. For single vector processing,
/// pass a vector containing one input vector.
/// All input vectors must have the same length.
///
/// For power-of-two sizes, uses the fast Stockham Radix-4/2 algorithm.
/// For arbitrary sizes, uses Bluestein's algorithm.
///
/// # Arguments
///
/// * `inputs` - A vector of input vectors, each containing complex samples.
///
/// # Returns
///
/// A vector of FFT results, one for each input vector.
///
/// # Panics
///
/// Panics if any input vector is empty or has a different length than others.
///
/// # Errors
///
/// Returns an error if a GPU operation fails (buffer mapping, device lost, etc.).
///
/// # Examples
///
/// ```no_run
/// use wgsl_fft::GpuFft;
/// use num_complex::Complex;
///
/// let fft = GpuFft::new().expect("GPU or CPU fallback required");
///
/// // Single FFT (pass vector with one element)
/// let single_input = vec![vec![Complex::new(1.0, 0.0); 1024]];
/// let single_spectrum = fft.fft(&single_input).expect("FFT failed");
///
/// // Batch FFT
/// let batch_inputs = vec![
/// vec![Complex::new(1.0, 0.0); 1024],
/// vec![Complex::new(0.5, 0.0); 1024],
/// ];
/// let batch_spectra = fft.fft(&batch_inputs).expect("Batch FFT failed");
///
/// // Arbitrary size FFT (not power of two)
/// let arbitrary_input = vec![vec![Complex::new(1.0, 0.0); 150]];
/// let arbitrary_spectrum = fft.fft(&arbitrary_input).expect("Arbitrary size FFT failed");
/// ```
pub fn fft(
&self,
inputs: &[Vec<Complex<f32>>],
) -> Result<Vec<Vec<Complex<f32>>>, Box<dyn std::error::Error>> {
self.transform_batch_internal(inputs, false)
}
/// Compute the inverse FFT for a batch of input vectors.
///
/// Processes multiple IFFTs efficiently. For single vector processing,
/// pass a vector containing one input vector.
/// All input vectors must have the same length.
/// The output is automatically scaled by `1/N` to maintain the unitary transform property.
///
/// For power-of-two sizes, uses the fast Stockham Radix-4/2 algorithm.
/// For arbitrary sizes, uses Bluestein's algorithm.
///
/// # Arguments
///
/// * `inputs` - A vector of input vectors, each containing complex samples.
///
/// # Returns
///
/// A vector of IFFT results, one for each input vector.
///
/// # Panics
///
/// Panics if any input vector is empty or has a different length than others.
///
/// # Errors
///
/// Returns an error if a GPU operation fails (buffer mapping, device lost, etc.).
///
/// # Examples
///
/// ```no_run
/// use wgsl_fft::GpuFft;
/// use num_complex::Complex;
///
/// let fft = GpuFft::new().expect("GPU or CPU fallback required");
///
/// // Single IFFT (pass vector with one element)
/// let single_spectrum = vec![vec![Complex::new(1.0, 0.0); 1024]];
/// let single_reconstructed = fft.ifft(&single_spectrum).expect("IFFT failed");
///
/// // Batch IFFT
/// let batch_spectra = vec![
/// vec![Complex::new(1.0, 0.0); 1024],
/// vec![Complex::new(0.5, 0.0); 1024],
/// ];
/// let batch_reconstructed = fft.ifft(&batch_spectra).expect("Batch IFFT failed");
///
/// // Arbitrary size IFFT (not power of two)
/// let arbitrary_spectrum = vec![vec![Complex::new(1.0, 0.0); 150]];
/// let arbitrary_reconstructed = fft.ifft(&arbitrary_spectrum).expect("Arbitrary size IFFT failed");
/// ```
pub fn ifft(
&self,
inputs: &[Vec<Complex<f32>>],
) -> Result<Vec<Vec<Complex<f32>>>, Box<dyn std::error::Error>> {
self.transform_batch_internal(inputs, true)
}
/// Validate that the input size is non-zero.
/// Arbitrary sizes are now supported via Bluestein's algorithm.
pub fn validate_input_size(&self, n: usize) -> Result<(), Box<dyn std::error::Error>> {
if n == 0 {
return Err("Transform length must be non-zero".into());
}
Ok(())
}
/// Check if a size is a power of two.
pub fn is_power_of_two(n: usize) -> bool {
n > 0 && (n & (n - 1)) == 0
}
/// Internal batch transform implementation that handles both FFT and IFFT for multiple inputs.
///
/// When `inverse` is true, computes IFFT (with conjugation and 1/N scaling).
/// When `inverse` is false, computes standard FFT.
///
/// For power-of-two sizes, uses the Stockham Radix-4/2 algorithm.
/// For arbitrary sizes, uses Bluestein's algorithm.
pub fn transform_batch_internal(
&self,
inputs: &[Vec<Complex<f32>>],
inverse: bool,
) -> Result<Vec<Vec<Complex<f32>>>, Box<dyn std::error::Error>> {
if inputs.is_empty() {
return Ok(Vec::new());
}
// Validate all inputs have the same size
let n = inputs[0].len();
for input in inputs.iter() {
if input.len() != n {
return Err("All input vectors in a batch must have the same length".into());
}
self.validate_input_size(input.len())?;
}
let batch_size = inputs.len() as u32;
// Route to appropriate algorithm based on size
if Self::is_power_of_two(n) {
// Use Stockham Radix-4/2 for power-of-two sizes
let log_n = n.trailing_zeros();
let sc = self.get_or_build_size_cache(n, log_n);
// Prepare all input data for parallel processing
let mut all_raw_data = Vec::with_capacity((n * 2 * batch_size as usize) as usize);
for input in inputs {
let raw = self.prepare_input_data(input, inverse);
all_raw_data.extend_from_slice(&raw);
}
// Upload entire batch to GPU
self.queue
.write_buffer(&sc.buf_a, 0, bytemuck::cast_slice(&all_raw_data));
// Execute compute pass for the entire batch
self.execute_compute_pass(&sc, batch_size, n);
// Read back all results
let mut output = self.readback_results(&sc, batch_size, n)?;
// Apply post-processing for inverse transforms
if inverse {
for chunk in output.chunks_mut(n) {
self.apply_inverse_transform_postprocessing(chunk, n);
}
}
// Split into individual results
let results: Vec<Vec<Complex<f32>>> =
output.chunks(n).map(|chunk| chunk.to_vec()).collect();
Ok(results)
} else {
// Use Bluestein's algorithm for arbitrary sizes
self.transform_batch_bluestein(inputs, inverse)
}
}
/// Transform using Bluestein's algorithm for arbitrary FFT sizes.
///
/// For non-power-of-two sizes, we use a CPU-based implementation via rustfft.
/// This provides correctness for arbitrary sizes while maintaining GPU acceleration
/// for power-of-two sizes.
///
/// Note: In the current implementation, arbitrary sizes are computed on the CPU
/// using rustfft as a fallback. Future optimizations could implement a GPU-accelerated
/// Bluestein's algorithm for full GPU support of arbitrary sizes.
///
/// The implementation matches the GPU FFT convention:
/// - Forward FFT: X[k] = Σ_n x[n] * exp(-2πi * k * n / N)
/// - Inverse FFT: x[n] = (1/N) * Σ_k X[k] * exp(2πi * k * n / N)
fn transform_batch_bluestein(
&self,
inputs: &[Vec<Complex<f32>>],
inverse: bool,
) -> Result<Vec<Vec<Complex<f32>>>, Box<dyn std::error::Error>> {
let n = inputs[0].len();
let batch_size = inputs.len();
// Use rustfft for arbitrary size FFT/IFFT on CPU
// This is a fallback implementation that ensures correctness
let mut planner = rustfft::FftPlanner::<f32>::new();
let mut results = Vec::with_capacity(batch_size);
for input in inputs {
let mut result = input.clone();
if inverse {
// rustfft's inverse FFT does NOT include scaling by default
// We need to match our GPU implementation which scales by 1/N
let ifft = planner.plan_fft_inverse(n);
ifft.process(&mut result);
// Apply 1/N scaling to match our GPU implementation
let scale = 1.0 / n as f32;
for x in &mut result {
*x = Complex::new(x.re * scale, x.im * scale);
}
} else {
let fft = planner.plan_fft_forward(n);
fft.process(&mut result);
// Forward FFT has no scaling (standard DFT convention)
}
results.push(result);
}
Ok(results)
}
/// Prepare input data for GPU processing, applying conjugation for IFFT if needed.
pub fn prepare_input_data(&self, input: &[Complex<f32>], inverse: bool) -> Vec<f32> {
if inverse {
// For IFFT: conjugate input
input.iter().flat_map(|c| [c.re, -c.im]).collect()
} else {
// For FFT: use input as-is
input.iter().flat_map(|c| [c.re, c.im]).collect()
}
}
/// Execute the compute shader pass.
pub fn execute_compute_pass(&self, sc: &SizeCache, batch_size: u32, n: usize) {
let mut enc = self
.device
.create_command_encoder(&wgpu::CommandEncoderDescriptor {
label: Some("FFT Pass"),
});
{
let mut pass = enc.begin_compute_pass(&wgpu::ComputePassDescriptor {
label: Some("FFT Compute"),
timestamp_writes: None,
});
if sc.wg_r4 > 0 {
// R4 mode: ⌊log₄N⌋ Radix-4 dispatches + optional Radix-2
pass.set_pipeline(&self.pipeline);
for bg in &sc.stage_bgs {
pass.set_bind_group(0, bg, &[]);
pass.dispatch_workgroups(sc.wg_r4, batch_size, 1);
}
if let Some(r2_bg) = &sc.stage_bg_r2 {
pass.set_pipeline(self.pipeline_r2.as_ref().unwrap());
pass.set_bind_group(0, r2_bg, &[]);
pass.dispatch_workgroups(sc.wg_n2, batch_size, 1);
}
} else {
// Legacy mode (with_shader): log₂N Radix-2 dispatches
pass.set_pipeline(&self.pipeline);
for bg in &sc.stage_bgs {
pass.set_bind_group(0, bg, &[]);
pass.dispatch_workgroups(sc.wg_n2, batch_size, 1);
}
}
}
let result_buf = if sc.result_in_b { &sc.buf_b } else { &sc.buf_a };
let single_fft_bytes = (n * 2 * std::mem::size_of::<f32>()) as u64;
enc.copy_buffer_to_buffer(
result_buf,
0,
&sc.staging_buf,
0,
single_fft_bytes * batch_size as u64,
);
self.queue.submit(std::iter::once(enc.finish()));
}
/// Read back results from GPU and convert to complex numbers.
pub fn readback_results(
&self,
sc: &SizeCache,
batch_size: u32,
n: usize,
) -> Result<Vec<Complex<f32>>, Box<dyn std::error::Error>> {
// Readback
let single_fft_bytes = (n * 2 * std::mem::size_of::<f32>()) as u64;
let total_bytes = single_fft_bytes * batch_size as u64;
let slice = sc.staging_buf.slice(0..total_bytes);
slice.map_async(wgpu::MapMode::Read, |_| {});
self.device.poll(wgpu::PollType::Wait {
submission_index: None,
timeout: None,
})?;
let mapped = slice.get_mapped_range();
let floats: &[f32] = bytemuck::cast_slice(&mapped);
let output: Vec<Complex<f32>> = floats
.chunks_exact(2)
.map(|p| Complex { re: p[0], im: p[1] })
.collect();
drop(mapped);
sc.staging_buf.unmap();
Ok(output)
}
/// Apply postprocessing for inverse transform (conjugation and 1/N scaling).
pub fn apply_inverse_transform_postprocessing(&self, output: &mut [Complex<f32>], n: usize) {
let scale = 1.0 / n as f32;
for c in output {
*c = Complex {
re: c.re * scale,
im: -c.im * scale,
};
}
}
/// Get or build size-specific GPU resources.
pub fn get_or_build_size_cache(&self, n: usize, log_n: u32) -> SizeCache {
let mut cache = self.cache.borrow_mut();
if let Some(sc) = cache.get(&n) {
return sc.clone();
}
let sc = self.build_size_cache(n, log_n);
cache.insert(n, sc.clone());
sc
}
/// Build GPU buffers and bind groups for a specific FFT size.
pub fn build_size_cache(&self, n: usize, log_n: u32) -> SizeCache {
let is_r4_mode = self.pipeline_r2.is_some();
// Stage counts
let num_r4 = if is_r4_mode { (log_n / 2) as usize } else { 0 };
let has_r2 = is_r4_mode && log_n % 2 == 1;
let total_stages = if is_r4_mode {
num_r4 + has_r2 as usize
} else {
log_n as usize
};
let single_fft_bytes = (n * 2 * std::mem::size_of::<f32>()) as u64;
// Cap at 1024 to avoid excessive pre-allocation; hardware limits are often much larger.
let max_batch_size = (self.device.limits().max_storage_buffer_binding_size as u64
/ single_fft_bytes)
.min(1024) as u32;
let data_bytes = single_fft_bytes * max_batch_size as u64;
let make_buf = |label| {
self.device.create_buffer(&wgpu::BufferDescriptor {
label: Some(label),
size: data_bytes,
usage: wgpu::BufferUsages::STORAGE
| wgpu::BufferUsages::COPY_SRC
| wgpu::BufferUsages::COPY_DST,
mapped_at_creation: false,
})
};
let buf_a = make_buf("fft_buf_a");
let buf_b = make_buf("fft_buf_b");
let staging_buf = self.device.create_buffer(&wgpu::BufferDescriptor {
label: Some("fft_staging"),
size: data_bytes,
usage: wgpu::BufferUsages::MAP_READ | wgpu::BufferUsages::COPY_DST,
mapped_at_creation: false,
});
// Twiddle table: N entries for R4 mode (max accessed index = 3N/2−5 < 2N),
// N/2 entries for legacy R2 mode (max accessed index = N−2 < N).
let twiddle_count = if is_r4_mode { n } else { n / 2 };
let twiddles: Vec<f32> = (0..twiddle_count)
.flat_map(|j| {
let angle = -std::f32::consts::TAU * j as f32 / n as f32;
[angle.cos(), angle.sin()]
})
.collect();
let twiddle_buf = self.device.create_buffer(&wgpu::BufferDescriptor {
label: Some("fft_twiddles"),
size: (twiddles.len() * std::mem::size_of::<f32>()) as u64,
usage: wgpu::BufferUsages::STORAGE | wgpu::BufferUsages::COPY_DST,
mapped_at_creation: false,
});
self.queue
.write_buffer(&twiddle_buf, 0, bytemuck::cast_slice(&twiddles));
let alignment = self.device.limits().min_uniform_buffer_offset_alignment as u64;
let entry_bytes = std::mem::size_of::<FftUniforms>() as u64;
let stride = entry_bytes.div_ceil(alignment) * alignment;
let uniform_buf = self.device.create_buffer(&wgpu::BufferDescriptor {
label: Some("fft_uniforms"),
size: stride * total_stages.max(1) as u64,
usage: wgpu::BufferUsages::UNIFORM | wgpu::BufferUsages::COPY_DST,
mapped_at_creation: false,
});
let uniform_size = NonZeroU64::new(entry_bytes);
let layout_r4 = self.pipeline.get_bind_group_layout(0);
let layout_r2_opt = self
.pipeline_r2
.as_ref()
.map(|p| p.get_bind_group_layout(0));
let make_bg_with_layout = |layout: &wgpu::BindGroupLayout,
src: &wgpu::Buffer,
dst: &wgpu::Buffer,
uniform_offset: u64| {
self.device.create_bind_group(&wgpu::BindGroupDescriptor {
label: None,
layout,
entries: &[
wgpu::BindGroupEntry {
binding: 0,
resource: wgpu::BindingResource::Buffer(wgpu::BufferBinding {
buffer: &uniform_buf,
offset: uniform_offset,
size: uniform_size,
}),
},
wgpu::BindGroupEntry {
binding: 1,
resource: src.as_entire_binding(),
},
wgpu::BindGroupEntry {
binding: 2,
resource: dst.as_entire_binding(),
},
wgpu::BindGroupEntry {
binding: 3,
resource: twiddle_buf.as_entire_binding(),
},
],
})
};
let make_bg = |src: &wgpu::Buffer, dst: &wgpu::Buffer, uniform_offset: u64| {
make_bg_with_layout(&layout_r4, src, dst, uniform_offset)
};
if is_r4_mode {
// R4 mode: ⌊log₄N⌋ Radix-4 stages + optional Radix-2
for s in 0..num_r4 {
let p = 1u32 << (s as u32 * 2);
self.queue.write_buffer(
&uniform_buf,
stride * s as u64,
bytemuck::bytes_of(&FftUniforms {
n: n as u32,
stage: p,
log_n,
_pad: 0,
}),
);
}
if has_r2 {
let p = 1u32 << (num_r4 as u32 * 2);
self.queue.write_buffer(
&uniform_buf,
stride * num_r4 as u64,
bytemuck::bytes_of(&FftUniforms {
n: n as u32,
stage: p,
log_n,
_pad: 0,
}),
);
}
let stage_bgs: Vec<wgpu::BindGroup> = (0..num_r4)
.map(|s| {
let (src, dst) = if s % 2 == 0 {
(&buf_a, &buf_b)
} else {
(&buf_b, &buf_a)
};
make_bg(src, dst, stride * s as u64)
})
.collect();
let stage_bg_r2 = if has_r2 {
let (src, dst) = if num_r4 % 2 == 0 {
(&buf_a, &buf_b)
} else {
(&buf_b, &buf_a)
};
let layout_r2 = layout_r2_opt.as_ref().unwrap();
Some(make_bg_with_layout(
layout_r2,
src,
dst,
stride * num_r4 as u64,
))
} else {
None
};
SizeCache {
buf_a,
buf_b,
staging_buf,
twiddle_buf,
data_bytes,
stage_bgs,
stage_bg_r2,
result_in_b: total_stages % 2 == 1,
wg_n2: (n as u32 / 2).div_ceil(256),
wg_r4: (n as u32 / 4).div_ceil(256),
}
} else {
// Legacy mode (with_shader): log₂N Radix-2 stages, stage-index uniforms
for stage in 0..log_n {
self.queue.write_buffer(
&uniform_buf,
stride * stage as u64,
bytemuck::bytes_of(&FftUniforms {
n: n as u32,
stage,
log_n,
_pad: 0,
}),
);
}
let stage_bgs = (0..log_n as usize)
.map(|s| {
let (src, dst) = if s % 2 == 0 {
(&buf_a, &buf_b)
} else {
(&buf_b, &buf_a)
};
make_bg(src, dst, stride * s as u64)
})
.collect();
SizeCache {
buf_a,
buf_b,
staging_buf,
twiddle_buf,
data_bytes,
stage_bgs,
stage_bg_r2: None,
result_in_b: log_n % 2 == 1,
wg_n2: (n as u32 / 2).div_ceil(256),
wg_r4: 0,
}
}
}
}
impl Default for GpuFft {
fn default() -> Self {
Self::new().expect("No GPU available for default GpuFft instance")
}
}
#[cfg(test)]
mod tests {
use super::*;
use num_complex::Complex;
#[test]
fn test_prepare_input_data_fft() {
let fft = GpuFft::new().expect("Failed to create FFT instance");
let input = vec![Complex::new(1.0, 2.0), Complex::new(3.0, 4.0)];
let result = fft.prepare_input_data(&input, false);
assert_eq!(result, vec![1.0, 2.0, 3.0, 4.0]);
}
#[test]
fn test_prepare_input_data_ifft() {
let fft = GpuFft::new().expect("Failed to create FFT instance");
let input = vec![Complex::new(1.0, 2.0), Complex::new(3.0, 4.0)];
let result = fft.prepare_input_data(&input, true);
assert_eq!(result, vec![1.0, -2.0, 3.0, -4.0]);
}
#[test]
fn test_apply_inverse_transform_postprocessing() {
let fft = GpuFft::new().expect("Failed to create FFT instance");
let mut output = vec![Complex::new(2.0, 4.0), Complex::new(6.0, 8.0)];
fft.apply_inverse_transform_postprocessing(&mut output, 2);
assert_eq!(output[0].re, 1.0);
assert_eq!(output[0].im, -2.0);
assert_eq!(output[1].re, 3.0);
assert_eq!(output[1].im, -4.0);
}
}