Skip to main content

cyanea_align/gpu/
mod.rs

1//! GPU-accelerated batch alignment.
2//!
3//! Provides banded affine-gap alignment on Metal (macOS) and CUDA (NVIDIA) GPUs.
4//! Pairs that exceed the bandwidth or when no GPU is available fall back to CPU.
5
6pub mod common;
7
8#[cfg(feature = "metal")]
9pub mod metal_align;
10
11#[cfg(feature = "cuda")]
12pub mod cuda_align;
13
14pub use common::GpuAlignConfig;
15
16use crate::scoring::ScoringScheme;
17use crate::types::{AlignmentMode, AlignmentResult};
18use cyanea_core::{CyaneaError, Result};
19
20/// Available GPU backend for alignment.
21#[derive(Debug, Clone, Copy, PartialEq, Eq)]
22pub enum GpuBackend {
23    /// Apple Metal (macOS / Apple Silicon).
24    Metal,
25    /// NVIDIA CUDA.
26    Cuda,
27}
28
29/// Detect which GPU backends are available at runtime.
30pub fn available_backends() -> Vec<GpuBackend> {
31    #[allow(unused_mut)]
32    let mut backends = Vec::new();
33
34    #[cfg(feature = "metal")]
35    {
36        if metal_align::MetalAligner::new().is_ok() {
37            backends.push(GpuBackend::Metal);
38        }
39    }
40
41    #[cfg(feature = "cuda")]
42    {
43        if cuda_align::CudaAligner::new().is_ok() {
44            backends.push(GpuBackend::Cuda);
45        }
46    }
47
48    backends
49}
50
51/// Batch-align sequence pairs on the GPU with default configuration.
52///
53/// Automatically selects the best available GPU backend (Metal on macOS,
54/// CUDA on NVIDIA). Falls back to CPU alignment if no GPU is available
55/// or the batch is too small.
56///
57/// # Errors
58///
59/// Returns an error if any alignment fails.
60pub fn align_batch_gpu(
61    pairs: &[(&[u8], &[u8])],
62    mode: AlignmentMode,
63    scoring: &ScoringScheme,
64) -> Result<Vec<AlignmentResult>> {
65    align_batch_gpu_with_config(pairs, mode, scoring, &GpuAlignConfig::default())
66}
67
68/// Batch-align sequence pairs on the GPU with explicit configuration.
69///
70/// # Errors
71///
72/// Returns an error if any alignment fails.
73pub fn align_batch_gpu_with_config(
74    pairs: &[(&[u8], &[u8])],
75    mode: AlignmentMode,
76    scoring: &ScoringScheme,
77    config: &GpuAlignConfig,
78) -> Result<Vec<AlignmentResult>> {
79    if pairs.is_empty() {
80        return Ok(Vec::new());
81    }
82
83    // Below threshold: CPU is faster
84    if pairs.len() < config.min_pairs_for_gpu {
85        return cpu_fallback(pairs, mode, scoring);
86    }
87
88    // Try GPU backends in preference order
89    #[cfg(feature = "metal")]
90    {
91        match metal_align::MetalAligner::new() {
92            Ok(aligner) => return aligner.align_batch(pairs, mode, scoring, config),
93            Err(_) => {} // fall through
94        }
95    }
96
97    #[cfg(feature = "cuda")]
98    {
99        match cuda_align::CudaAligner::new() {
100            Ok(aligner) => return aligner.align_batch(pairs, mode, scoring, config),
101            Err(_) => {} // fall through
102        }
103    }
104
105    // No GPU available
106    cpu_fallback(pairs, mode, scoring)
107}
108
109/// Batch-align on a specific GPU backend.
110///
111/// # Errors
112///
113/// Returns an error if the requested backend is not available or any alignment fails.
114pub fn align_batch_on(
115    pairs: &[(&[u8], &[u8])],
116    mode: AlignmentMode,
117    scoring: &ScoringScheme,
118    backend: GpuBackend,
119    config: &GpuAlignConfig,
120) -> Result<Vec<AlignmentResult>> {
121    if pairs.is_empty() {
122        return Ok(Vec::new());
123    }
124
125    // Suppress unused-variable warnings when no GPU features are enabled.
126    let _ = (mode, scoring, config);
127
128    match backend {
129        GpuBackend::Metal => {
130            #[cfg(feature = "metal")]
131            {
132                let aligner = metal_align::MetalAligner::new()?;
133                return aligner.align_batch(pairs, mode, scoring, config);
134            }
135            #[cfg(not(feature = "metal"))]
136            Err(CyaneaError::Other("Metal feature not enabled".into()))
137        }
138        GpuBackend::Cuda => {
139            #[cfg(feature = "cuda")]
140            {
141                let aligner = cuda_align::CudaAligner::new()?;
142                return aligner.align_batch(pairs, mode, scoring, config);
143            }
144            #[cfg(not(feature = "cuda"))]
145            Err(CyaneaError::Other("CUDA feature not enabled".into()))
146        }
147    }
148}
149
150/// CPU fallback: align each pair using the standard CPU implementation.
151fn cpu_fallback(
152    pairs: &[(&[u8], &[u8])],
153    mode: AlignmentMode,
154    scoring: &ScoringScheme,
155) -> Result<Vec<AlignmentResult>> {
156    pairs
157        .iter()
158        .map(|(q, t)| crate::align(q, t, mode, scoring))
159        .collect()
160}
161
162#[cfg(test)]
163mod tests {
164    use super::*;
165    use crate::scoring::ScoringMatrix;
166
167    fn dna_scheme() -> ScoringScheme {
168        ScoringScheme::Simple(ScoringMatrix::dna_default())
169    }
170
171    #[test]
172    fn gpu_fallback_empty() {
173        let pairs: Vec<(&[u8], &[u8])> = vec![];
174        let results = align_batch_gpu(&pairs, AlignmentMode::Global, &dna_scheme()).unwrap();
175        assert!(results.is_empty());
176    }
177
178    #[test]
179    fn gpu_fallback_small_batch() {
180        // Below min_pairs_for_gpu threshold → CPU fallback
181        let pairs: Vec<(&[u8], &[u8])> = vec![(b"ACGT", b"ACGT"), (b"AAA", b"TTT")];
182        let results = align_batch_gpu(&pairs, AlignmentMode::Global, &dna_scheme()).unwrap();
183        assert_eq!(results.len(), 2);
184        assert_eq!(results[0].score, 8);
185    }
186
187    #[test]
188    fn available_backends_returns_list() {
189        let backends = available_backends();
190        // Regardless of hardware, this should not panic
191        assert!(backends.len() <= 2);
192    }
193
194    #[test]
195    fn config_default() {
196        let cfg = GpuAlignConfig::default();
197        assert_eq!(cfg.max_bandwidth, 128);
198        assert_eq!(cfg.min_pairs_for_gpu, 64);
199    }
200
201    #[test]
202    fn cpu_fallback_correctness() {
203        let pairs: Vec<(&[u8], &[u8])> =
204            vec![(b"ACGT", b"ACGT"), (b"AAAA", b"TTTT"), (b"ACGT", b"ACT")];
205        let results = cpu_fallback(&pairs, AlignmentMode::Global, &dna_scheme()).unwrap();
206        assert_eq!(results.len(), 3);
207        assert_eq!(results[0].score, 8);
208    }
209}