Skip to main content

barracuda/
lib.rs

1// SPDX-License-Identifier: AGPL-3.0-or-later
2//! # barraCuda: Hardware-Agnostic Tensor Compute
3//!
4//! **Deep Debt Excellence**: Zero duplication, pure capability-based compute
5//!
6//! ## Philosophy
7//!
8//! - ✅ **Hardware-Agnostic**: One API, works on any device (GPU/CPU/NPU/TPU)
9//! - ✅ **Pure WGSL**: WGSL shaders ONLY (wgpu handles all backends)
10//! - ✅ **Automatic Fallback**: wgpu uses CPU when GPU unavailable
11//! - ✅ **Zero Duplication**: Single WGSL implementation per operation
12//! - ✅ **Runtime Discovery**: wgpu selects best available backend
13//! - ✅ **Simple**: No separate CPU code, no trait abstractions
14//! - **Zero unsafe**: `#![forbid(unsafe_code)]` — all former FFI evolved to safe Rust
15//!
16//! ## Architecture
17//!
18//! ```text
19//! User Code: Tensor<f32>
20//!     ↓
21//! Operation (WGSL shader)
22//!     ↓
23//! WgpuDevice
24//!     ↓
25//! wgpu Backend Selection (automatic):
26//! ├── Vulkan (NVIDIA, AMD, Intel GPU)
27//! ├── Metal (Apple GPU)
28//! ├── DX12 (Windows GPU)
29//! └── Software Rasterizer (CPU fallback)
30//!
31//! Same WGSL code runs on ALL backends!
32//! ```
33//!
34//! ## Example
35//!
36//! ```rust,ignore
37//! use barracuda::prelude::*;
38//!
39//! // Auto-discovers best device (GPU if available, CPU fallback)
40//! let x = Tensor::randn([128, 256])?;
41//! let y = Tensor::randn([256, 512])?;
42//!
43//! // Operations execute on discovered device (WGSL on GPU, Rayon on CPU)
44//! let z = x.matmul(&y)?;
45//! let activated = z.relu()?;
46//! let normalized = activated.softmax(0)?;
47//!
48//! tracing::info!("Device: {}", x.device().name());
49//! // "NVIDIA GeForce RTX 4090" or "AMD Radeon RX 7900" or "CPU (16 cores)"
50//! ```
51//!
52//! ## Deep Debt Elimination
53//!
54//! **Before** (architectural debt):
55//! - Separate CPU and GPU implementations
56//! - User must choose backend explicitly
57//! - WGSL shaders existed but weren't used by operations
58//! - Duplication: Same logic in CPU and WGSL
59//!
60//! **After** (unified):
61//! - Single Tensor API works everywhere
62//! - Automatic device discovery and fallback
63//! - All WGSL shaders properly utilized
64//! - Zero duplication: One implementation per op
65
66#![forbid(unsafe_code)]
67// ── Domain-specific expectations ────────────────────────────────────────────
68// Compile-time verified: #[expect] warns if the suppression becomes unnecessary.
69#![expect(
70    clippy::cast_possible_truncation,
71    clippy::cast_sign_loss,
72    clippy::cast_precision_loss,
73    clippy::cast_lossless,
74    clippy::cast_possible_wrap,
75    reason = "GPU APIs require u32 for dimensions/indices; scientific computing uses f64/f32 for counts/sizes"
76)]
77#![expect(
78    clippy::similar_names,
79    clippy::many_single_char_names,
80    clippy::unreadable_literal,
81    reason = "scientific/physics code uses single-char variables (x, y, z, r, θ), similar bindings (pos_x vs pos_y), and physical constants"
82)]
83#![expect(
84    clippy::items_after_statements,
85    clippy::float_cmp,
86    reason = "compute kernels declare buffers close to use; float equality is intentional for exact comparisons (0.0, NaN, sentinels)"
87)]
88#![expect(
89    clippy::module_name_repetitions,
90    reason = "intentional for clarity in a large API (e.g. tensor::TensorError, device::DeviceSelection)"
91)]
92#![expect(
93    clippy::default_trait_access,
94    reason = "wgpu's Default::default() pattern is idiomatic when type is inferred (ComputePassDescriptor, CommandEncoderDescriptor)"
95)]
96#![expect(
97    clippy::unnecessary_wraps,
98    reason = "GPU ops return Result for future error paths (device lost, validation) without breaking callers"
99)]
100#![expect(
101    clippy::match_same_arms,
102    reason = "GPU dispatch routes multiple precision variants to the same kernel"
103)]
104#![expect(
105    clippy::missing_fields_in_debug,
106    reason = "Debug impls intentionally omit large buffer fields"
107)]
108#![expect(
109    clippy::match_wildcard_for_single_variants,
110    reason = "wildcard matching is intentional for forward compatibility — new variants caught at compile time"
111)]
112#![expect(
113    clippy::pub_underscore_fields,
114    reason = "GPU uniform structs use pub _padding fields for repr(C) alignment with bytemuck::Pod"
115)]
116#![expect(
117    clippy::unused_async,
118    reason = "async signatures required by trait even when implementation is synchronous"
119)]
120#![expect(
121    clippy::too_many_lines,
122    reason = "GPU pipeline functions set up multiple bind groups, encoders, and staging buffers"
123)]
124#![expect(
125    clippy::unused_self,
126    reason = "trait implementations require &self even when unused"
127)]
128#![expect(
129    clippy::struct_field_names,
130    reason = "struct field name patterns are intentional for domain clarity"
131)]
132#![expect(
133    clippy::needless_pass_by_value,
134    reason = "GPU ops take tensors/configs by value for ownership transfer"
135)]
136#![expect(
137    clippy::struct_excessive_bools,
138    reason = "booleans in config structs are intentional (enable_bias, use_cache)"
139)]
140#![expect(
141    clippy::trivially_copy_pass_by_ref,
142    reason = "passing single bytes by reference is acceptable for trait consistency"
143)]
144#![cfg_attr(
145    test,
146    expect(clippy::unwrap_used, reason = "test code uses unwrap for brevity")
147)]
148#![expect(
149    rustdoc::broken_intra_doc_links,
150    reason = "cross-crate links to barracuda-core types"
151)]
152
153// ── CPU-only modules (always available, no GPU dependency) ────────────────────
154pub mod activations;
155pub mod cast;
156pub mod discovery;
157/// Named constants for environment variable keys.
158pub mod env_keys;
159pub mod error;
160pub mod health;
161pub mod linalg;
162pub mod nautilus;
163pub mod numerical;
164pub mod rng;
165pub mod runtime;
166pub mod special;
167pub mod tolerances;
168pub mod validation;
169
170// ── GPU-dependent modules (require the "gpu" feature) ────────────────────────
171#[cfg(feature = "gpu")]
172pub mod auto_tensor;
173#[cfg(feature = "gpu")]
174pub mod benchmarks;
175#[cfg(feature = "gpu")]
176pub mod compute_graph;
177#[cfg(feature = "gpu")]
178pub mod cpu_conv_pool;
179#[cfg(feature = "gpu")]
180pub mod cpu_executor;
181#[cfg(feature = "gpu")]
182pub mod device;
183#[cfg(feature = "gpu")]
184pub mod dispatch;
185#[cfg(all(feature = "gpu", feature = "domain-esn"))]
186pub mod esn_v2;
187#[cfg(all(feature = "gpu", feature = "domain-genomics"))]
188pub mod genomics;
189#[cfg(feature = "gpu")]
190pub mod gpu_executor;
191#[cfg(feature = "gpu")]
192pub mod interpolate;
193#[cfg(feature = "gpu")]
194pub mod multi_gpu;
195#[cfg(all(feature = "gpu", feature = "domain-nn"))]
196pub mod nn;
197#[cfg(feature = "gpu")]
198pub mod npu;
199#[cfg(feature = "gpu")]
200pub mod npu_executor;
201#[cfg(feature = "gpu")]
202pub mod ops;
203#[cfg(feature = "gpu")]
204pub mod optimize;
205#[cfg(all(feature = "gpu", feature = "domain-pde"))]
206pub mod pde;
207#[cfg(feature = "gpu")]
208pub mod pipeline;
209#[cfg(feature = "gpu")]
210pub mod provenance;
211#[cfg(feature = "gpu")]
212pub mod resource_quota;
213pub mod sample;
214#[cfg(feature = "gpu")]
215pub mod scheduler;
216#[cfg(feature = "gpu")]
217pub mod session;
218#[cfg(feature = "gpu")]
219pub mod shaders;
220#[cfg(all(feature = "gpu", feature = "domain-snn"))]
221pub mod snn;
222pub mod spectral;
223#[cfg(feature = "gpu")]
224pub mod tensor;
225#[cfg(all(feature = "gpu", feature = "domain-timeseries"))]
226pub mod timeseries;
227#[cfg(feature = "gpu")]
228pub mod utils;
229#[cfg(all(feature = "gpu", feature = "domain-vision"))]
230pub mod vision;
231#[cfg(feature = "gpu")]
232pub mod workload;
233
234/// CPU-only math functions (convenience alias for `special`).
235///
236/// Re-exports the most commonly needed special functions so Springs
237/// can `use barracuda::math::{erf, ln_gamma, regularized_gamma_p}`.
238pub mod math {
239    pub use crate::special::erf::{erf_batch, erfc_batch};
240    pub use crate::special::{
241        beta, digamma, erf, erfc, gamma, ln_beta, ln_gamma, lower_incomplete_gamma,
242        regularized_gamma_p, regularized_gamma_q,
243    };
244    pub use crate::stats::metrics::{dot, l2_norm};
245    pub use crate::stats::normal::norm_cdf;
246}
247pub mod stats;
248
249#[cfg(feature = "gpu")]
250pub mod staging;
251#[cfg(feature = "gpu")]
252pub mod surrogate;
253#[cfg(feature = "gpu")]
254pub mod unified_hardware;
255#[cfg(feature = "gpu")]
256pub mod unified_math;
257
258#[cfg(feature = "gpu")]
259pub use ops::sparse_matmul_quantized::sparse_matmul_quantized;
260
261#[cfg(all(feature = "gpu", feature = "domain-genomics"))]
262pub use ops::bio::{
263    AniBatchF64, BatchFitnessGpu, Dada2Buffers, Dada2Dimensions, Dada2DispatchArgs, Dada2EStepGpu,
264    DnDsBatchF64, FelsensteinGpu, FelsensteinResult, FlatForest, FlatTree, GillespieConfig,
265    GillespieGpu, GillespieModel, GillespieResult, HillGateGpu, HmmBatchForwardF64, HmmForwardArgs,
266    KmerHistogramGpu, LocusVarianceGpu, MultiObjFitnessGpu, PairwiseHammingGpu, PairwiseJaccardGpu,
267    PairwiseL2Gpu, PangenomeClassifyGpu, PhyloTree, QualityConfig, QualityFilterGpu,
268    RfBatchInferenceGpu, SmithWatermanGpu, SnpCallingF64, SpatialPayoffGpu, SwConfig, SwResult,
269    SwarmNnGpu, TaxonomyFcGpu, TreeInferenceGpu, UniFracConfig, UniFracPropagateGpu,
270};
271
272#[cfg(feature = "gpu")]
273pub use device::driver_profile::PrecisionRoutingAdvice;
274
275#[cfg(feature = "gpu")]
276pub use ops::rk45_adaptive::Rk45DispatchArgs;
277
278/// Prelude: Common imports for using barracuda.
279///
280/// `use barracuda::prelude::*` brings in `Tensor`, `Device`, `Result`, and domain-specific
281/// types (ESN, genomics, NN, SNN) when their features are enabled. Use this for application
282/// code; use explicit paths when you need to avoid name collisions.
283pub mod prelude {
284    pub use crate::error::{BarracudaError, Result};
285
286    #[cfg(feature = "gpu")]
287    pub use crate::compute_graph::ComputeGraph;
288    #[cfg(feature = "gpu")]
289    pub use crate::device::{
290        Auto, AutoTuner, Capability, Device, DeviceCapabilities, DeviceContext, DeviceInfo,
291        DiscoveredDevice, GLOBAL_TUNER, GpuCalibration, WgpuDevice, WorkloadHint,
292    };
293    #[cfg(feature = "gpu")]
294    pub use crate::dispatch::{
295        DispatchConfig, DispatchTarget, batch_fitness_substrate, dispatch_for,
296        dispatch_with_transfer_cost, hmm_substrate, ode_substrate, pairwise_substrate,
297        spatial_substrate,
298    };
299    #[cfg(all(feature = "gpu", feature = "domain-esn"))]
300    pub use crate::esn_v2::{ESN, ESNConfig};
301    #[cfg(all(feature = "gpu", feature = "domain-genomics"))]
302    pub use crate::genomics::{
303        CompositionReport, MotifMatch, QualityReport, SequenceAnalyzer, SequenceConfig,
304    };
305    #[cfg(feature = "gpu")]
306    pub use crate::multi_gpu::DeviceInfo as GpuDeviceInfo;
307    #[cfg(feature = "gpu")]
308    pub use crate::multi_gpu::{
309        DeviceClass, DeviceLease, DeviceRequirements, GpuPool, MultiDevicePool, WorkloadConfig,
310    };
311    #[cfg(all(feature = "gpu", feature = "domain-nn"))]
312    pub use crate::nn::{Layer, LossFunction, Optimizer};
313    #[cfg(feature = "gpu")]
314    pub use crate::npu::EventCodec;
315    #[cfg(feature = "gpu")]
316    pub use crate::resource_quota::{QuotaTracker, ResourceQuota, presets as quota_presets};
317    #[cfg(feature = "gpu")]
318    pub use crate::session::{AttentionDims, SessionTensor, TensorSession};
319    #[cfg(all(feature = "gpu", feature = "domain-snn"))]
320    pub use crate::snn::{SNNConfig, SNNLayer, SpikingNetwork};
321    #[cfg(feature = "gpu")]
322    pub use crate::staging::{
323        BufferDirection, GpuRingBuffer, PipelineBuilder, PipelineStats, RingBufferConfig, Stage,
324        StageLink, StreamingPipeline, UnidirectionalConfig, UnidirectionalPipeline, WorkHandle,
325        WriteHandle,
326    };
327    #[cfg(feature = "gpu")]
328    pub use crate::tensor::Tensor;
329    #[cfg(feature = "gpu")]
330    pub use crate::workload::{
331        ComputeDevice, DeviceHint, DeviceSelector, Priority, SparsityAnalyzer, WorkloadClassifier,
332        WorkloadType,
333    };
334}