# Getting Started Guide Welcome to ruv-FANN! This comprehensive guide will take you from installation to building advanced AI systems with neural networks and swarm intelligence. ## ๐ŸŽฏ What You'll Learn By the end of this guide, you'll be able to: - โœ… Create and train neural networks with ruv-FANN - โœ… Orchestrate AI swarms for distributed problem-solving - โœ… Deploy AI systems across multiple platforms - โœ… Integrate with existing machine learning workflows - โœ… Optimize performance with SIMD and GPU acceleration ## ๐Ÿš€ Step 1: Installation & Setup (5 minutes) ### Install Rust & ruv-FANN ```bash # Install Rust (skip if already installed) curl --proto '=https' --tlsv1.2 -sSf https://sh.rustup.rs | sh source ~/.cargo/env # Create new project cargo new my-ai-project cd my-ai-project # Add ruv-FANN dependencies cargo add ruv-fann semantic-cartan-matrix ruv-swarm ``` ### Install JavaScript SDK (Optional) ```bash # For web/Node.js integration npm install ruv-swarm # Global CLI tools npm install -g claude-flow ruv-swarm ``` ### Verify Installation ```bash # Test Rust installation cargo build # Test CLI tools ruv-swarm --version claude-flow --version ``` ## ๐Ÿง  Step 2: Your First Neural Network (10 minutes) Let's create a neural network that learns to recognize handwritten digits. ### Basic Neural Network ```rust // src/main.rs use ruv_fann::prelude::*; use std::error::Error; fn main() -> Result<(), Box> { println!("๐Ÿง  Creating MNIST digit classifier..."); // Network architecture: 784 -> 128 -> 64 -> 10 let mut network = NeuralNetwork::builder() .input_size(784) // 28x28 pixel images .hidden_layers(&[128, 64]) .output_size(10) // 10 digit classes (0-9) .activation(Activation::ReLU) .learning_rate(0.001) .build()?; println!("โœ… Network created with {} parameters", network.parameter_count()); // Generate sample training data (simplified) let training_data = generate_sample_data(1000); println!("๐Ÿ‹๏ธ Training network on {} samples...", training_data.len()); // Train the network let start_time = std::time::Instant::now(); network.train(&training_data, 100, 0.01)?; let training_time = start_time.elapsed(); println!("โœ… Training completed in {:.2}s", training_time.as_secs_f32()); // Test the network test_network(&mut network)?; Ok(()) } fn generate_sample_data(count: usize) -> Vec<(Vec, Vec)> { use rand::Rng; let mut rng = rand::thread_rng(); (0..count).map(|_| { // Generate random 28x28 image (simplified) let image: Vec = (0..784).map(|_| rng.gen::()).collect(); // Random label (0-9) let label = rng.gen_range(0..10); let mut target = vec![0.0; 10]; target[label] = 1.0; (image, target) }).collect() } fn test_network(network: &mut NeuralNetwork) -> Result<(), Box> { println!("\n๐Ÿงช Testing network..."); let test_data = generate_sample_data(100); let mut correct = 0; for (input, expected) in test_data.iter() { let output = network.run(input)?; // Find predicted class (highest output) let predicted = output.iter() .enumerate() .max_by(|a, b| a.1.partial_cmp(b.1).unwrap()) .unwrap().0; // Find actual class let actual = expected.iter() .enumerate() .max_by(|a, b| a.1.partial_cmp(b.1).unwrap()) .unwrap().0; if predicted == actual { correct += 1; } } let accuracy = (correct as f32 / test_data.len() as f32) * 100.0; println!("๐Ÿ“Š Test accuracy: {:.1}% ({}/{})", accuracy, correct, test_data.len()); Ok(()) } ``` ### Add Dependencies ```toml # Cargo.toml [dependencies] ruv-fann = { version = "0.3", features = ["std", "simd"] } semantic-cartan-matrix = "0.2" ruv-swarm = "1.0" rand = "0.8" tokio = { version = "1.0", features = ["full"] } ``` ### Run Your Network ```bash cargo run --release # Expected output: # ๐Ÿง  Creating MNIST digit classifier... # โœ… Network created with 109,386 parameters # ๐Ÿ‹๏ธ Training network on 1000 samples... # โœ… Training completed in 2.34s # ๐Ÿ“Š Test accuracy: 62.0% (62/100) ``` ## ๐Ÿ Step 3: AI Swarm Coordination (15 minutes) Now let's create an AI swarm that coordinates multiple agents to solve complex problems. ### Swarm Orchestration ```rust // src/swarm_example.rs use ruv_swarm::prelude::*; use semantic_cartan_matrix::prelude::*; use tokio; #[tokio::main] async fn main() -> Result<(), Box> { println!("๐Ÿ Initializing AI swarm..."); // Create swarm orchestrator let mut orchestrator = SwarmOrchestrator::new(SwarmConfig { max_agents: 5, topology: Topology::Hierarchical, strategy: CoordinationStrategy::Balanced, neural_acceleration: true, })?; println!("๐Ÿ‘ฅ Spawning specialized agents..."); // Spawn different types of agents spawn_research_agent(&mut orchestrator).await?; spawn_analysis_agent(&mut orchestrator).await?; spawn_synthesis_agent(&mut orchestrator).await?; println!("โœ… Swarm initialized with {} agents", orchestrator.agent_count()); // Execute coordinated task execute_research_task(&mut orchestrator).await?; // Get performance metrics display_swarm_metrics(&orchestrator).await?; Ok(()) } async fn spawn_research_agent(orchestrator: &mut SwarmOrchestrator) -> Result<(), Box> { let agent_config = AgentConfig { name: "Researcher Alpha".to_string(), agent_type: AgentType::Researcher, capabilities: vec![ "data_analysis".to_string(), "pattern_recognition".to_string(), "information_synthesis".to_string(), ], neural_config: Some(NeuralConfig { architecture: NeuralArchitecture { input_size: 256, hidden_layers: vec![128, 64], output_size: 32, activation: "relu".to_string(), }, learning_rate: 0.001, use_simd: true, }), }; let agent = ResearchAgent::new(agent_config); orchestrator.register_agent(Box::new(agent)).await?; Ok(()) } async fn spawn_analysis_agent(orchestrator: &mut SwarmOrchestrator) -> Result<(), Box> { let agent_config = AgentConfig { name: "Data Analyst".to_string(), agent_type: AgentType::Analyst, capabilities: vec![ "statistical_analysis".to_string(), "trend_detection".to_string(), "visualization".to_string(), ], neural_config: Some(NeuralConfig { architecture: NeuralArchitecture { input_size: 512, hidden_layers: vec![256, 128, 64], output_size: 64, activation: "gelu".to_string(), }, learning_rate: 0.0005, use_simd: true, }), }; let agent = AnalysisAgent::new(agent_config); orchestrator.register_agent(Box::new(agent)).await?; Ok(()) } async fn spawn_synthesis_agent(orchestrator: &mut SwarmOrchestrator) -> Result<(), Box> { let agent_config = AgentConfig { name: "Synthesis Engine".to_string(), agent_type: AgentType::Synthesizer, capabilities: vec![ "information_fusion".to_string(), "report_generation".to_string(), "insight_extraction".to_string(), ], neural_config: Some(NeuralConfig { architecture: NeuralArchitecture { input_size: 128, hidden_layers: vec![256, 128], output_size: 16, activation: "tanh".to_string(), }, learning_rate: 0.01, use_simd: true, }), }; let agent = SynthesisAgent::new(agent_config); orchestrator.register_agent(Box::new(agent)).await?; Ok(()) } async fn execute_research_task(orchestrator: &mut SwarmOrchestrator) -> Result<(), Box> { println!("\n๐ŸŽฏ Executing coordinated research task..."); let task = Task::new( "comprehensive_market_analysis".to_string(), TaskPriority::High, serde_json::json!({ "domain": "artificial_intelligence", "timeframe": "2024", "focus_areas": ["neural_networks", "swarm_intelligence", "performance_optimization"], "output_format": "comprehensive_report" }), ); let start_time = std::time::Instant::now(); let result = orchestrator.orchestrate(task).await?; let execution_time = start_time.elapsed(); println!("โœ… Task completed in {:.2}s", execution_time.as_secs_f32()); println!("๐Ÿ“Š Result summary:"); println!(" - Status: {}", result.status); println!(" - Agents involved: {}", result.agents_used.len()); println!(" - Output size: {} bytes", result.output.len()); println!(" - Confidence: {:.1}%", result.confidence * 100.0); Ok(()) } async fn display_swarm_metrics(orchestrator: &SwarmOrchestrator) -> Result<(), Box> { println!("\n๐Ÿ“ˆ Swarm Performance Metrics:"); let metrics = orchestrator.get_metrics().await?; println!(" ๐Ÿ“Š Task Metrics:"); println!(" - Tasks completed: {}", metrics.tasks_completed); println!(" - Success rate: {:.1}%", metrics.success_rate * 100.0); println!(" - Avg execution time: {:.1}ms", metrics.avg_execution_time); println!(" ๐Ÿง  Neural Metrics:"); println!(" - Total parameters: {}", metrics.total_parameters); println!(" - Training iterations: {}", metrics.training_iterations); println!(" - Model accuracy: {:.1}%", metrics.model_accuracy * 100.0); println!(" ๐Ÿ”ง System Metrics:"); println!(" - Memory usage: {:.1}MB", metrics.memory_usage_mb); println!(" - CPU utilization: {:.1}%", metrics.cpu_utilization * 100.0); println!(" - Network latency: {:.1}ms", metrics.network_latency_ms); Ok(()) } // Agent implementations struct ResearchAgent { config: AgentConfig, neural_net: Option, } impl ResearchAgent { fn new(config: AgentConfig) -> Self { Self { config, neural_net: None, } } } #[async_trait::async_trait] impl Agent for ResearchAgent { async fn initialize(&mut self) -> Result<(), AgentError> { // Initialize neural network if let Some(neural_config) = &self.config.neural_config { let mut net = NeuralNetwork::builder() .input_size(neural_config.architecture.input_size) .hidden_layers(&neural_config.architecture.hidden_layers) .output_size(neural_config.architecture.output_size) .learning_rate(neural_config.learning_rate) .build() .map_err(|e| AgentError::InitializationFailed(e.to_string()))?; self.neural_net = Some(net); } Ok(()) } async fn process_task(&mut self, task: &Task) -> Result { // Simulate research processing tokio::time::sleep(tokio::time::Duration::from_millis(500)).await; Ok(TaskResult { agent_id: self.config.name.clone(), output: "Research analysis completed".to_string(), metadata: serde_json::json!({ "processing_time_ms": 500, "confidence": 0.85, "insights_found": 42 }), }) } } // Similar implementations for AnalysisAgent and SynthesisAgent... ``` ### Run the Swarm ```bash cargo run --bin swarm_example --release # Expected output: # ๐Ÿ Initializing AI swarm... # ๐Ÿ‘ฅ Spawning specialized agents... # โœ… Swarm initialized with 3 agents # ๐ŸŽฏ Executing coordinated research task... # โœ… Task completed in 1.84s # ๐Ÿ“Š Result summary: # - Status: Completed # - Agents involved: 3 # - Output size: 1247 bytes # - Confidence: 91.3% ``` ## ๐ŸŒ Step 4: Web Deployment with WASM (10 minutes) Deploy your AI to the web using WebAssembly. ### Build for Web ```bash # Install wasm-pack curl https://rustwasm.github.io/wasm-pack/installer/init.sh -sSf | sh # Build WASM package wasm-pack build --target web --features wasm,simd ``` ### Create Web Interface ```html ruv-FANN Web Demo

๐Ÿง  ruv-FANN Web Demo

Neural Network Training

AI Swarm Coordination

Ready to run AI demos...
``` ### Serve the Demo ```bash # Serve the web demo python -m http.server 8000 # Open http://localhost:8000 in your browser ``` ## ๐Ÿš€ Step 5: Advanced Features (15 minutes) ### SIMD Acceleration ```rust use ruv_fann::simd::*; // Enable SIMD optimizations let mut config = NetworkConfig::default(); config.use_simd = true; config.simd_width = 8; // AVX2 let network = NeuralNetwork::with_config(config)?; // 2-4x performance improvement automatically applied ``` ### GPU Acceleration ```rust use ruv_fann::gpu::*; // Enable GPU acceleration let gpu_config = GpuConfig { device_type: GpuDevice::CUDA, memory_pool_size: 1024 * 1024 * 1024, // 1GB use_tensor_cores: true, }; let network = NeuralNetwork::with_gpu(gpu_config)?; // 5-10x performance improvement for large networks ``` ### Distributed Training ```rust use ruv_swarm::distributed::*; // Distributed training across multiple nodes let trainer = DistributedTrainer::new(DistributedConfig { nodes: vec!["192.168.1.10:8000", "192.168.1.11:8000"], strategy: TrainingStrategy::DataParallel, communication: CommunicationBackend::NCCL, })?; let result = trainer.train(&network, &dataset).await?; ``` ## ๐Ÿ“Š Step 6: Performance Monitoring ### Built-in Metrics ```rust use ruv_fann::metrics::*; // Enable comprehensive metrics let mut network = NeuralNetwork::builder() .enable_metrics(true) .metric_collection_interval(100) // Every 100 iterations .build()?; // Train with monitoring network.train(&training_data, 1000, 0.01)?; // Get performance report let metrics = network.get_metrics(); println!("Training speed: {:.2} samples/sec", metrics.samples_per_second); println!("Memory usage: {:.1}MB", metrics.memory_usage_mb); println!("SIMD utilization: {:.1}%", metrics.simd_utilization * 100.0); ``` ### Swarm Analytics ```rust // Monitor swarm performance let analytics = swarm.get_analytics().await?; println!("๐Ÿ“Š Swarm Analytics:"); println!(" - Task throughput: {} tasks/min", analytics.tasks_per_minute); println!(" - Agent efficiency: {:.1}%", analytics.efficiency * 100.0); println!(" - Communication overhead: {:.1}%", analytics.comm_overhead * 100.0); ``` ## ๐ŸŽฏ Next Steps & Advanced Topics ### ๐Ÿง  Advanced Neural Networks - **[Semantic Cartan Matrix](Semantic-Cartan-Matrix)** - Mathematical neural architectures - **[CUDA-WASM](CUDA-WASM)** - GPU acceleration in browsers - **[Neural Networks](Neural-Networks)** - Deep learning architectures ### ๐Ÿ Swarm Intelligence - **[Swarm Intelligence](Swarm-Intelligence)** - Multi-agent coordination - **[Autonomous Agents](Autonomous-Agents)** - Self-organizing systems - **[Distributed Computing](Distributed-Computing)** - Multi-node coordination ### ๐Ÿš€ Production Deployment - **[Production Deployment](Production-Deployment)** - Enterprise deployment - **[Monitoring & Metrics](Monitoring-Metrics)** - Observability - **[Security Guide](Security-Guide)** - Security best practices ### ๐Ÿ“š Learning Resources - **[Advanced Tutorials](Advanced-Tutorials)** - Deep technical guides - **[Use Cases](Use-Cases)** - Real-world applications - **[Best Practices](Best-Practices)** - Professional patterns ## ๐ŸŽ‰ Congratulations! You've successfully: - โœ… Built and trained neural networks with ruv-FANN - โœ… Created AI swarms for distributed problem-solving - โœ… Deployed AI to the web with WASM - โœ… Optimized performance with SIMD and GPU acceleration - โœ… Monitored system performance and metrics You're now ready to build production AI systems with ruv-FANN! ๐Ÿš€ --- **Ready for more?** Explore the [Advanced Tutorials](Advanced-Tutorials) or dive into specific components in the [Component Overview](Component-Overview).