Abstraction over compute backends (CPU, CUDA, Metal, Vulkan). Each method has a CPU-based default via [`CpuBackend`]. GPU backends override specific methods for acceleration while falling back to CPU for unimplemented ops.
| 38 | /// Each method has a CPU-based default via [`CpuBackend`]. GPU backends override |
| 39 | /// specific methods for acceleration while falling back to CPU for unimplemented ops. |
| 40 | pub trait ComputeBackend: Send + Sync + std::fmt::Debug { |
| 41 | /// Human-readable backend name for logging. |
| 42 | fn name(&self) -> &str; |
| 43 | |
| 44 | /// The candle device this backend operates on. |
| 45 | fn device(&self) -> &Device; |
| 46 | |
| 47 | // ── Attention ──────────────────────────────────────────────────── |
| 48 | |
| 49 | /// Scaled dot-product attention. |
| 50 | /// |
| 51 | /// Backends may use flash-attn (CUDA), fused SDPA (Metal), wgpu matmul (Vulkan), |
| 52 | /// or manual matmul + softmax (CPU). |
| 53 | /// |
| 54 | /// Input layout: `(batch, heads, seq_len, head_dim)`. |
| 55 | fn attention( |
| 56 | &self, |
| 57 | q: &Tensor, |
| 58 | k: &Tensor, |
| 59 | v: &Tensor, |
| 60 | scale: f32, |
| 61 | causal: bool, |
| 62 | ) -> Result<Tensor>; |
| 63 | |
| 64 | /// Fused scaled dot-product attention (Metal SDPA, Flash-Attn style). |
| 65 | /// Returns `softmax(Q @ K^T * scale + mask) @ V`. |
| 66 | /// Default: delegates to `candle_nn::ops::sdpa`. |
| 67 | fn sdpa( |
| 68 | &self, |
| 69 | q: &Tensor, |
| 70 | k: &Tensor, |
| 71 | v: &Tensor, |
| 72 | mask: Option<&Tensor>, |
| 73 | causal: bool, |
| 74 | scale: f32, |
| 75 | ) -> Result<Tensor> { |
| 76 | candle_nn::ops::sdpa(q, k, v, mask, causal, scale, 1.0) |
| 77 | } |
| 78 | |
| 79 | // ── Fused activations ──────────────────────────────────────────── |
| 80 | |
| 81 | /// `silu(gate) * up` — MLP activation gate. |
| 82 | fn silu_mul(&self, gate: &Tensor, up: &Tensor) -> Result<Tensor>; |
| 83 | |
| 84 | /// `ln(1 + exp(clamp(x, -inf, 88)))` with `max(x, result)` — GDN gate. |
| 85 | fn stable_softplus(&self, x: &Tensor) -> Result<Tensor>; |
| 86 | |
| 87 | // ── Fused normalization ────────────────────────────────────────── |
| 88 | |
| 89 | /// `rms_norm(x, weight, eps) * silu(z)` — GDN output gating. |
| 90 | fn rms_norm_gated( |
| 91 | &self, |
| 92 | x: &Tensor, |
| 93 | z: &Tensor, |
| 94 | weight: &Tensor, |
| 95 | eps: f32, |
| 96 | ) -> Result<Tensor>; |
| 97 |
no outgoing calls
no test coverage detected