ruqu_qflg/
lib.rs

1//! # ruqu-qflg - Quantum Federated Learning with Byzantine Tolerance
2//!
3//! A privacy-preserving distributed quantum machine learning framework that combines:
4//!
5//! - **Federated Learning**: Distributed training without sharing raw data
6//! - **Byzantine Tolerance**: Robust aggregation against malicious participants
7//! - **Differential Privacy**: Formal privacy guarantees for gradient updates
8//! - **Quantum Enhancement**: Quantum-inspired features for security and randomness
9//!
10//! ## Architecture
11//!
12//! ```text
13//! ┌─────────────────────────────────────────────────────────────────┐
14//! │                    Federated Coordinator                         │
15//! │  (Round management, model synchronization, aggregation)         │
16//! └───────────────────────────┬─────────────────────────────────────┘
17//!                             │
18//!     ┌───────────────────────┼───────────────────────┐
19//!     ▼                       ▼                       ▼
20//! ┌─────────┐           ┌───────────┐           ┌───────────┐
21//! │Byzantine│           │  Privacy  │           │  Quantum  │
22//! │Detection│           │ Mechanism │           │Enhancement│
23//! └─────────┘           └───────────┘           └───────────┘
24//! Krum/Median           Gaussian/DP              QRNG/PQ-Sig
25//! Bulyan/Trim           Budget Track             Bell Pairs
26//! ```
27//!
28//! ## Quick Start
29//!
30//! ```rust
31//! use ruqu_qflg::prelude::*;
32//! use ndarray::Array1;
33//!
34//! // Create coordinator
35//! let config = CoordinatorConfig::default();
36//! let coordinator = FederatedCoordinator::new(config);
37//!
38//! // Register clients
39//! let client = ClientInfo::new("client_1".to_string(), vec![0u8; 32]);
40//! coordinator.register_client(client).unwrap();
41//!
42//! // Byzantine detection on gradients (need 2f+3 clients for Krum)
43//! let detector_config = DetectorConfig::new(3, 0.2);
44//! let detector = KrumDetector::new(detector_config);
45//!
46//! let gradients = vec![
47//!     Array1::from_vec(vec![1.0, 1.0]),
48//!     Array1::from_vec(vec![1.1, 0.9]),
49//!     Array1::from_vec(vec![0.9, 1.1]),
50//!     Array1::from_vec(vec![1.0, 1.0]),
51//!     Array1::from_vec(vec![1.0, 1.0]),
52//!     Array1::from_vec(vec![100.0, -100.0]), // Byzantine!
53//! ];
54//!
55//! let (honest, byzantine) = detector.detect(&gradients).unwrap();
56//! assert!(byzantine.len() >= 1);
57//! ```
58//!
59//! ## Tier 2 Capability (Score 83)
60//!
61//! This crate enables privacy-preserving distributed quantum machine learning as
62//! a Tier 2 capability in the RuVector ecosystem. Key features:
63//!
64//! - **Two-Week Test**: Gradient aggregation compiles, Byzantine detection works
65//! - **Integration**: Works with ruQu and other quantum components
66//! - **Performance**: Designed for high-throughput federated scenarios
67//!
68//! ## Feature Flags
69//!
70//! - `simd` - SIMD acceleration for gradient operations
71//! - `wasm` - WASM-compatible mode
72//! - `parallel` - Multi-threaded aggregation
73//! - `tracing` - Observability and metrics
74//! - `full` - All features enabled (default)
75//!
76//! ## Modules
77//!
78//! - [`aggregation`] - Gradient aggregation algorithms (FedAvg, Secure, Momentum)
79//! - [`byzantine`] - Byzantine detection (Krum, Multi-Krum, Trimmed Mean, Median)
80//! - [`privacy`] - Differential privacy (Gaussian, Laplace, Budget tracking)
81//! - [`protocol`] - Federated protocol (Registration, Rounds, Sync)
82//! - [`quantum`] - Quantum features (QRNG, PQ signatures, Bell pairs)
83//! - [`error`] - Error types
84
85#![warn(missing_docs)]
86#![warn(clippy::all)]
87#![warn(clippy::pedantic)]
88#![allow(clippy::module_name_repetitions)]
89#![allow(clippy::missing_errors_doc)]
90#![allow(clippy::missing_panics_doc)]
91#![allow(clippy::cast_possible_truncation)]
92#![allow(clippy::cast_sign_loss)]
93#![allow(clippy::cast_precision_loss)]
94
95// Core modules
96pub mod aggregation;
97pub mod byzantine;
98pub mod error;
99pub mod privacy;
100pub mod protocol;
101pub mod quantum;
102
103// Re-exports for convenient access
104pub use error::{
105    AggregationError, ByzantineError, PrivacyError, ProtocolError, QflgError, QuantumError, Result,
106};
107
108pub use aggregation::{
109    AggregationStats, AggregatorConfig, GradientAggregator, MomentumAggregator, SecureAggregator,
110    WeightedAverageAggregator, gradient_norm, gradient_similarity, pairwise_distances,
111};
112
113pub use byzantine::{
114    BulyanDetector, ByzantineDetector, ByzantineStats, DetectionResult, DetectorConfig,
115    KrumDetector, MedianDetector, MultiKrumDetector, TrimmedMeanDetector,
116};
117
118pub use privacy::{
119    AdaptiveClipper, GaussianMechanism, GradientClipper, LaplaceMechanism, MomentsAccountant,
120    PrivacyBudget, PrivacyConfig, PrivacyLoss, PrivacyMechanism, PrivacyStats,
121};
122
123pub use protocol::{
124    ClientConfig, ClientInfo, CoordinatorConfig, FederatedClient, FederatedCoordinator,
125    GradientSubmission, ProtocolStats, RoundInfo, RoundState,
126};
127
128pub use quantum::{
129    BellPair, CoherenceMonitor, PostQuantumSignature, QKDSimulator, QuantumRng, QuantumState,
130};
131
132/// Crate version
133pub const VERSION: &str = env!("CARGO_PKG_VERSION");
134
135/// Crate name
136pub const NAME: &str = env!("CARGO_PKG_NAME");
137
138/// Default Byzantine tolerance fraction
139pub const DEFAULT_BYZANTINE_FRACTION: f64 = 0.3;
140
141/// Default privacy epsilon
142pub const DEFAULT_PRIVACY_EPSILON: f64 = 1.0;
143
144/// Default privacy delta
145pub const DEFAULT_PRIVACY_DELTA: f64 = 1e-5;
146
147/// Prelude module for convenient imports
148pub mod prelude {
149    //! Commonly used types for quantum federated learning.
150    //!
151    //! ```rust
152    //! use ruqu_qflg::prelude::*;
153    //! ```
154
155    // Error types
156    pub use crate::error::{QflgError, Result};
157
158    // Aggregation
159    pub use crate::aggregation::{
160        AggregatorConfig, GradientAggregator, WeightedAverageAggregator,
161        SecureAggregator, MomentumAggregator, AggregationStats,
162    };
163
164    // Byzantine detection
165    pub use crate::byzantine::{
166        DetectorConfig, ByzantineDetector, KrumDetector, MultiKrumDetector,
167        TrimmedMeanDetector, MedianDetector, BulyanDetector,
168        DetectionResult, ByzantineStats,
169    };
170
171    // Privacy
172    pub use crate::privacy::{
173        PrivacyConfig, PrivacyMechanism, GaussianMechanism, LaplaceMechanism,
174        PrivacyBudget, GradientClipper, AdaptiveClipper, MomentsAccountant,
175    };
176
177    // Protocol
178    pub use crate::protocol::{
179        CoordinatorConfig, FederatedCoordinator, ClientConfig, FederatedClient,
180        ClientInfo, RoundInfo, RoundState, GradientSubmission, ProtocolStats,
181    };
182
183    // Quantum
184    pub use crate::quantum::{
185        QuantumRng, QuantumState, BellPair, PostQuantumSignature,
186        QKDSimulator, CoherenceMonitor,
187    };
188
189    // Constants
190    pub use crate::{
191        DEFAULT_BYZANTINE_FRACTION, DEFAULT_PRIVACY_EPSILON, DEFAULT_PRIVACY_DELTA,
192    };
193}
194
195#[cfg(test)]
196mod tests {
197    use super::*;
198
199    #[test]
200    fn test_version_constant() {
201        assert!(!VERSION.is_empty());
202        assert!(!NAME.is_empty());
203        assert_eq!(NAME, "ruqu-qflg");
204    }
205
206    #[test]
207    fn test_constants() {
208        assert!((DEFAULT_BYZANTINE_FRACTION - 0.3).abs() < 1e-10);
209        assert!((DEFAULT_PRIVACY_EPSILON - 1.0).abs() < 1e-10);
210        assert!((DEFAULT_PRIVACY_DELTA - 1e-5).abs() < 1e-15);
211    }
212
213    #[test]
214    fn test_prelude_imports() {
215        use crate::prelude::*;
216
217        // Verify all prelude types are accessible
218        let _config = AggregatorConfig::default();
219        let _detector_config = DetectorConfig::default();
220        let _privacy_config = PrivacyConfig::default();
221        let _coord_config = CoordinatorConfig::default();
222        let _qrng = QuantumRng::new();
223    }
224
225    #[test]
226    fn test_integration_workflow() {
227        use ndarray::Array1;
228
229        // 1. Create detector
230        let detector_config = DetectorConfig::new(3, 0.3);
231        let detector = KrumDetector::new(detector_config);
232
233        // 2. Create aggregator
234        let agg_config = AggregatorConfig::default();
235        let aggregator = WeightedAverageAggregator::new(agg_config);
236
237        // 3. Create privacy mechanism
238        let privacy_config = PrivacyConfig::new(1.0, 1e-5, 1.0);
239        let mechanism = GaussianMechanism::new(privacy_config).unwrap();
240
241        // 4. Simulate gradients
242        let gradients = vec![
243            Array1::from_vec(vec![1.0, 1.0, 1.0]),
244            Array1::from_vec(vec![1.1, 0.9, 1.0]),
245            Array1::from_vec(vec![0.9, 1.1, 1.0]),
246            Array1::from_vec(vec![1.0, 1.0, 1.1]),
247            Array1::from_vec(vec![100.0, -100.0, 50.0]), // Byzantine
248        ];
249
250        // 5. Detect Byzantine
251        let (honest_indices, byzantine_indices) = detector.detect(&gradients).unwrap();
252        assert!(!byzantine_indices.is_empty());
253
254        // 6. Filter to honest gradients
255        let honest_gradients: Vec<_> = honest_indices
256            .iter()
257            .map(|&i| gradients[i].clone())
258            .collect();
259        let weights: Vec<f64> = honest_gradients.iter().map(|_| 1.0).collect();
260
261        // 7. Aggregate
262        let aggregate = aggregator.aggregate(&honest_gradients, &weights).unwrap();
263
264        // 8. Apply privacy
265        let private_aggregate = mechanism.apply(&aggregate).unwrap();
266
267        // Verify result
268        assert_eq!(private_aggregate.len(), 3);
269    }
270}