whisper-apr 0.3.3

WASM-first automatic speech recognition engine implementing OpenAI Whisper
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
//! GPU detection and capability queries (WAPR-123)
//!
//! Provides high-level API for detecting GPU capabilities and selecting backends.

use super::capabilities::{GpuBackend, GpuCapabilities, GpuLimits};

#[cfg(test)]
mod tests;

/// GPU detection result
#[derive(Debug, Clone)]
pub struct GpuDetectionResult {
    /// Whether a GPU was found
    pub available: bool,
    /// Detected capabilities
    pub capabilities: GpuCapabilities,
    /// Recommended backend
    pub recommended_backend: GpuBackend,
    /// Detection method used
    pub detection_method: DetectionMethod,
}

impl GpuDetectionResult {
    /// Create a result indicating no GPU available
    #[must_use]
    pub fn unavailable() -> Self {
        Self {
            available: false,
            capabilities: GpuCapabilities::default(),
            recommended_backend: GpuBackend::None,
            detection_method: DetectionMethod::NoGpu,
        }
    }

    /// Check if GPU is suitable for inference
    #[must_use]
    pub fn suitable_for_inference(&self) -> bool {
        self.available && self.capabilities.suitable_for_inference()
    }

    /// Get a human-readable summary
    #[must_use]
    pub fn summary(&self) -> String {
        if self.available {
            format!(
                "GPU Available: {} via {} ({})",
                self.capabilities.name, self.recommended_backend, self.detection_method
            )
        } else {
            "No GPU available".to_string()
        }
    }
}

/// How the GPU was detected
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum DetectionMethod {
    /// wgpu native adapter request
    WgpuNative,
    /// WebGPU browser API
    WebGpuBrowser,
    /// Simulated for testing
    Simulated,
    /// No GPU detected
    NoGpu,
}

impl std::fmt::Display for DetectionMethod {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        match self {
            Self::WgpuNative => write!(f, "wgpu native"),
            Self::WebGpuBrowser => write!(f, "WebGPU browser"),
            Self::Simulated => write!(f, "simulated"),
            Self::NoGpu => write!(f, "none"),
        }
    }
}

/// GPU detection options
#[derive(Debug, Clone)]
pub struct DetectionOptions {
    /// Prefer high-performance GPU over power-efficient
    pub prefer_high_performance: bool,
    /// Require compute shader support
    pub require_compute: bool,
    /// Minimum VRAM in bytes (0 = no minimum)
    pub min_vram: u64,
    /// Preferred backend (None = auto-select)
    pub preferred_backend: Option<GpuBackend>,
    /// Timeout for detection in milliseconds
    pub timeout_ms: u32,
}

impl Default for DetectionOptions {
    fn default() -> Self {
        Self {
            prefer_high_performance: true,
            require_compute: true,
            min_vram: 0,
            preferred_backend: None,
            timeout_ms: 5000,
        }
    }
}

impl DetectionOptions {
    /// Options for inference workloads
    #[must_use]
    pub fn for_inference() -> Self {
        Self {
            prefer_high_performance: true,
            require_compute: true,
            min_vram: 256 * 1024 * 1024, // 256 MB minimum
            preferred_backend: None,
            timeout_ms: 5000,
        }
    }

    /// Options for development/testing
    #[must_use]
    pub fn for_development() -> Self {
        Self {
            prefer_high_performance: false,
            require_compute: false,
            min_vram: 0,
            preferred_backend: None,
            timeout_ms: 10000,
        }
    }

    /// Set preferred backend
    #[must_use]
    pub fn with_backend(mut self, backend: GpuBackend) -> Self {
        self.preferred_backend = Some(backend);
        self
    }

    /// Set minimum VRAM
    #[must_use]
    pub fn with_min_vram(mut self, vram: u64) -> Self {
        self.min_vram = vram;
        self
    }

    /// Disable compute requirement
    #[must_use]
    pub fn without_compute_requirement(mut self) -> Self {
        self.require_compute = false;
        self
    }
}

/// Detect GPU capabilities
///
/// This is the main entry point for GPU detection. It queries available
/// GPU backends and returns information about the best available GPU.
pub fn detect_gpu(options: &DetectionOptions) -> GpuDetectionResult {
    // Without the webgpu feature, we can only return unavailable
    #[cfg(not(feature = "webgpu"))]
    {
        let _ = options; // Silence unused warning
        GpuDetectionResult::unavailable()
    }

    #[cfg(feature = "webgpu")]
    {
        // WebGPU detection via wgpu - see detect_gpu_wgpu for implementation
        detect_gpu_wgpu(options)
    }
}

#[cfg(feature = "webgpu")]
fn detect_gpu_wgpu(options: &DetectionOptions) -> GpuDetectionResult {
    // Use pollster to block on async wgpu operations
    // For WASM targets, this would need to be async - use detect_gpu_async instead
    #[cfg(not(target_arch = "wasm32"))]
    {
        use std::sync::mpsc;
        use std::thread;
        use std::time::Duration;

        let timeout = Duration::from_millis(options.timeout_ms as u64);
        let prefer_high_perf = options.prefer_high_performance;

        let (tx, rx) = mpsc::channel();

        thread::spawn(move || {
            let result = pollster::block_on(async {
                let instance = wgpu::Instance::new(wgpu::InstanceDescriptor {
                    backends: wgpu::Backends::all(),
                    ..Default::default()
                });

                let power_preference = if prefer_high_perf {
                    wgpu::PowerPreference::HighPerformance
                } else {
                    wgpu::PowerPreference::LowPower
                };

                if let Some(adapter) = instance
                    .request_adapter(&wgpu::RequestAdapterOptions {
                        power_preference,
                        compatible_surface: None,
                        force_fallback_adapter: false,
                    })
                    .await
                {
                    let info = adapter.get_info();
                    let limits = adapter.limits();

                    let backend = match info.backend {
                        wgpu::Backend::Vulkan => GpuBackend::Vulkan,
                        wgpu::Backend::Metal => GpuBackend::Metal,
                        wgpu::Backend::Dx12 => GpuBackend::Dx12,
                        wgpu::Backend::Gl => GpuBackend::OpenGl,
                        wgpu::Backend::BrowserWebGpu => GpuBackend::BrowserWebGpu,
                        wgpu::Backend::Empty => GpuBackend::None,
                    };

                    let capabilities = GpuCapabilities {
                        name: info.name.clone(),
                        vendor: format!("{:?}", info.vendor),
                        backend,
                        limits: GpuLimits {
                            max_buffer_size: limits.max_buffer_size,
                            max_storage_buffer_binding_size: limits.max_storage_buffer_binding_size,
                            max_uniform_buffer_binding_size: limits.max_uniform_buffer_binding_size,
                            max_compute_workgroup_size_x: limits.max_compute_workgroup_size_x,
                            max_compute_workgroup_size_y: limits.max_compute_workgroup_size_y,
                            max_compute_workgroup_size_z: limits.max_compute_workgroup_size_z,
                            max_compute_invocations_per_workgroup: limits
                                .max_compute_invocations_per_workgroup,
                            max_compute_workgroups_per_dimension: limits
                                .max_compute_workgroups_per_dimension,
                            max_bind_groups: limits.max_bind_groups,
                        },
                        supports_f16: adapter.features().contains(wgpu::Features::SHADER_F16),
                        supports_timestamp_query: adapter
                            .features()
                            .contains(wgpu::Features::TIMESTAMP_QUERY),
                        vram_bytes: 0, // Not easily available from wgpu
                    };

                    GpuDetectionResult {
                        available: true,
                        capabilities,
                        recommended_backend: backend,
                        detection_method: DetectionMethod::WgpuNative,
                    }
                } else {
                    GpuDetectionResult::unavailable()
                }
            });
            let _ = tx.send(result);
        });

        rx.recv_timeout(timeout)
            .unwrap_or_else(|_| GpuDetectionResult::unavailable())
    }

    #[cfg(target_arch = "wasm32")]
    {
        // For WASM, GPU detection must be async
        // Return unavailable in sync context - callers should use detect_gpu_async
        let _ = options;
        GpuDetectionResult::unavailable()
    }
}

/// Create a simulated GPU result for testing
#[must_use]
pub fn detect_gpu_simulated(config: SimulatedGpuConfig) -> GpuDetectionResult {
    let capabilities = GpuCapabilities {
        name: config.name,
        vendor: config.vendor,
        backend: config.backend,
        limits: config.limits,
        supports_f16: config.supports_f16,
        supports_timestamp_query: config.supports_timestamp_query,
        vram_bytes: config.vram_bytes,
    };

    GpuDetectionResult {
        available: config.backend != GpuBackend::None,
        capabilities,
        recommended_backend: config.backend,
        detection_method: DetectionMethod::Simulated,
    }
}

/// Configuration for simulated GPU
#[derive(Debug, Clone)]
pub struct SimulatedGpuConfig {
    /// GPU name
    pub name: String,
    /// GPU vendor
    pub vendor: String,
    /// Backend type
    pub backend: GpuBackend,
    /// Device limits
    pub limits: GpuLimits,
    /// F16 support
    pub supports_f16: bool,
    /// Timestamp query support
    pub supports_timestamp_query: bool,
    /// VRAM in bytes
    pub vram_bytes: u64,
}

impl Default for SimulatedGpuConfig {
    fn default() -> Self {
        Self {
            name: "Simulated GPU".to_string(),
            vendor: "Test".to_string(),
            backend: GpuBackend::Vulkan,
            limits: GpuLimits::default(),
            supports_f16: true,
            supports_timestamp_query: true,
            vram_bytes: 4 * 1024 * 1024 * 1024, // 4 GB
        }
    }
}

impl SimulatedGpuConfig {
    /// Create high-end desktop GPU config
    #[must_use]
    pub fn high_end_desktop() -> Self {
        Self {
            name: "Simulated RTX 4090".to_string(),
            vendor: "NVIDIA".to_string(),
            backend: GpuBackend::Vulkan,
            limits: GpuLimits::desktop_high_end(),
            supports_f16: true,
            supports_timestamp_query: true,
            vram_bytes: 24 * 1024 * 1024 * 1024, // 24 GB
        }
    }

    /// Create Apple Silicon GPU config
    #[must_use]
    pub fn apple_silicon() -> Self {
        Self {
            name: "Simulated Apple M2".to_string(),
            vendor: "Apple".to_string(),
            backend: GpuBackend::Metal,
            limits: GpuLimits::default(),
            supports_f16: true,
            supports_timestamp_query: false,
            vram_bytes: 16 * 1024 * 1024 * 1024, // 16 GB unified
        }
    }

    /// Create mobile GPU config
    #[must_use]
    pub fn mobile() -> Self {
        Self {
            name: "Simulated Adreno 730".to_string(),
            vendor: "Qualcomm".to_string(),
            backend: GpuBackend::Vulkan,
            limits: GpuLimits::mobile(),
            supports_f16: true,
            supports_timestamp_query: false,
            vram_bytes: 512 * 1024 * 1024, // 512 MB
        }
    }

    /// Create browser WebGPU config
    #[must_use]
    pub fn browser_webgpu() -> Self {
        Self {
            name: "Browser GPU".to_string(),
            vendor: "Unknown".to_string(),
            backend: GpuBackend::BrowserWebGpu,
            limits: GpuLimits::default(),
            supports_f16: false, // Browser might not expose this
            supports_timestamp_query: false,
            vram_bytes: 0, // Unknown in browser
        }
    }

    /// Set GPU name
    #[must_use]
    pub fn with_name(mut self, name: impl Into<String>) -> Self {
        self.name = name.into();
        self
    }

    /// Set VRAM
    #[must_use]
    pub fn with_vram(mut self, vram_bytes: u64) -> Self {
        self.vram_bytes = vram_bytes;
        self
    }

    /// Set backend
    #[must_use]
    pub fn with_backend(mut self, backend: GpuBackend) -> Self {
        self.backend = backend;
        self
    }
}

/// Query specific GPU features
#[derive(Debug, Clone, Copy, Default)]
pub struct GpuFeatureQuery {
    /// Requires compute shader support
    pub compute: bool,
    /// Requires F16 support
    pub f16: bool,
    /// Requires timestamp queries
    pub timestamp_query: bool,
    /// Minimum buffer size needed
    pub min_buffer_size: u64,
    /// Minimum VRAM needed
    pub min_vram: u64,
}

impl GpuFeatureQuery {
    /// Query for inference workloads
    #[must_use]
    pub fn for_inference() -> Self {
        Self {
            compute: true,
            f16: false, // Preferred but not required
            timestamp_query: false,
            min_buffer_size: 256 * 1024 * 1024,
            min_vram: 256 * 1024 * 1024,
        }
    }

    /// Query for profiling
    #[must_use]
    pub fn for_profiling() -> Self {
        Self {
            compute: true,
            f16: false,
            timestamp_query: true,
            min_buffer_size: 64 * 1024 * 1024,
            min_vram: 0,
        }
    }

    /// Add compute requirement
    #[must_use]
    pub fn with_compute(mut self) -> Self {
        self.compute = true;
        self
    }

    /// Add F16 requirement
    #[must_use]
    pub fn with_f16(mut self) -> Self {
        self.f16 = true;
        self
    }

    /// Add timestamp query requirement
    #[must_use]
    pub fn with_timestamp_query(mut self) -> Self {
        self.timestamp_query = true;
        self
    }

    /// Check if capabilities satisfy this query
    #[must_use]
    pub fn satisfied_by(&self, caps: &GpuCapabilities) -> bool {
        if self.compute && !caps.supports_compute() {
            return false;
        }
        if self.f16 && !caps.supports_f16 {
            return false;
        }
        if self.timestamp_query && !caps.supports_timestamp_query {
            return false;
        }
        if self.min_buffer_size > caps.limits.max_buffer_size {
            return false;
        }
        if self.min_vram > 0 && caps.vram_bytes > 0 && self.min_vram > caps.vram_bytes {
            return false;
        }
        true
    }

    /// Get list of unsatisfied requirements
    #[must_use]
    pub fn unsatisfied_requirements(&self, caps: &GpuCapabilities) -> Vec<String> {
        let mut reqs = Vec::new();

        if self.compute && !caps.supports_compute() {
            reqs.push("compute shaders".to_string());
        }
        if self.f16 && !caps.supports_f16 {
            reqs.push("F16 support".to_string());
        }
        if self.timestamp_query && !caps.supports_timestamp_query {
            reqs.push("timestamp queries".to_string());
        }
        if self.min_buffer_size > caps.limits.max_buffer_size {
            reqs.push(format!(
                "buffer size (need {} MB, have {} MB)",
                self.min_buffer_size / 1024 / 1024,
                caps.limits.max_buffer_size / 1024 / 1024
            ));
        }
        if self.min_vram > 0 && caps.vram_bytes > 0 && self.min_vram > caps.vram_bytes {
            reqs.push(format!(
                "VRAM (need {} MB, have {} MB)",
                self.min_vram / 1024 / 1024,
                caps.vram_bytes / 1024 / 1024
            ));
        }

        reqs
    }
}

/// Recommend the best backend for the current platform
#[must_use]
pub fn recommend_backend() -> GpuBackend {
    #[cfg(target_os = "macos")]
    {
        GpuBackend::Metal
    }

    #[cfg(target_os = "windows")]
    {
        GpuBackend::Dx12
    }

    #[cfg(target_os = "linux")]
    {
        GpuBackend::Vulkan
    }

    #[cfg(target_arch = "wasm32")]
    {
        GpuBackend::BrowserWebGpu
    }

    #[cfg(not(any(
        target_os = "macos",
        target_os = "windows",
        target_os = "linux",
        target_arch = "wasm32"
    )))]
    {
        GpuBackend::Vulkan // Default fallback
    }
}

/// Check if GPU should be used for given workload size
#[must_use]
pub fn should_use_gpu(caps: &GpuCapabilities, workload_elements: usize) -> GpuRecommendation {
    const GPU_THRESHOLD: usize = 10_000; // Below this, CPU is likely faster
    const GPU_STRONGLY_RECOMMENDED: usize = 100_000;

    if !caps.is_available() {
        return GpuRecommendation::CpuOnly {
            reason: "No GPU available".to_string(),
        };
    }

    if !caps.supports_compute() {
        return GpuRecommendation::CpuOnly {
            reason: "GPU doesn't support compute shaders".to_string(),
        };
    }

    if workload_elements < GPU_THRESHOLD {
        return GpuRecommendation::CpuPreferred {
            reason: format!(
                "Workload size ({workload_elements} elements) is small; CPU may be faster due to GPU overhead"
            ),
        };
    }

    if workload_elements >= GPU_STRONGLY_RECOMMENDED {
        return GpuRecommendation::GpuStronglyRecommended {
            speedup_estimate: estimate_speedup(caps, workload_elements),
        };
    }

    GpuRecommendation::GpuRecommended {
        speedup_estimate: estimate_speedup(caps, workload_elements),
    }
}

/// GPU usage recommendation
#[derive(Debug, Clone)]
pub enum GpuRecommendation {
    /// CPU only (no GPU available or suitable)
    CpuOnly {
        /// Reason for CPU-only recommendation
        reason: String,
    },
    /// CPU preferred for this workload
    CpuPreferred {
        /// Reason CPU is preferred
        reason: String,
    },
    /// GPU recommended
    GpuRecommended {
        /// Estimated speedup factor
        speedup_estimate: f32,
    },
    /// GPU strongly recommended
    GpuStronglyRecommended {
        /// Estimated speedup factor
        speedup_estimate: f32,
    },
}

impl GpuRecommendation {
    /// Check if GPU is recommended
    #[must_use]
    pub fn use_gpu(&self) -> bool {
        matches!(
            self,
            Self::GpuRecommended { .. } | Self::GpuStronglyRecommended { .. }
        )
    }

    /// Get speedup estimate if GPU is recommended
    #[must_use]
    pub fn speedup(&self) -> Option<f32> {
        match self {
            Self::GpuRecommended { speedup_estimate }
            | Self::GpuStronglyRecommended { speedup_estimate } => Some(*speedup_estimate),
            _ => None,
        }
    }
}

/// Estimate speedup from using GPU
fn estimate_speedup(caps: &GpuCapabilities, elements: usize) -> f32 {
    // Very rough heuristic estimates
    let base_speedup = if caps.backend.is_high_performance() {
        10.0
    } else {
        5.0
    };

    // Scale with workload size (diminishing returns)
    let scale = (elements as f32 / 10_000.0).ln().max(1.0);

    (base_speedup * scale).min(100.0)
}