Skip to content

Getting Started Guide

ruvnet edited this page Aug 1, 2025 · 1 revision

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

# 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)

# For web/Node.js integration
npm install ruv-swarm

# Global CLI tools
npm install -g claude-flow ruv-swarm

Verify Installation

# 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

// src/main.rs
use ruv_fann::prelude::*;
use std::error::Error;

fn main() -> Result<(), Box<dyn Error>> {
    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<f32>, Vec<f32>)> {
    use rand::Rng;
    let mut rng = rand::thread_rng();
    
    (0..count).map(|_| {
        // Generate random 28x28 image (simplified)
        let image: Vec<f32> = (0..784).map(|_| rng.gen::<f32>()).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<dyn Error>> {
    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

# 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

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

// src/swarm_example.rs
use ruv_swarm::prelude::*;
use semantic_cartan_matrix::prelude::*;
use tokio;

#[tokio::main]
async fn main() -> Result<(), Box<dyn std::error::Error>> {
    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<dyn std::error::Error>> {
    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<dyn std::error::Error>> {
    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<dyn std::error::Error>> {
    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<dyn std::error::Error>> {
    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<dyn std::error::Error>> {
    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<NeuralNetwork>,
}

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<TaskResult, AgentError> {
        // 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

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

# 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

<!DOCTYPE html>
<html>
<head>
    <title>ruv-FANN Web Demo</title>
    <style>
        body { font-family: Arial, sans-serif; margin: 20px; }
        .container { max-width: 800px; margin: 0 auto; }
        .output { background: #f5f5f5; padding: 15px; margin: 10px 0; border-radius: 5px; }
        button { padding: 10px 20px; margin: 5px; background: #007acc; color: white; border: none; border-radius: 3px; cursor: pointer; }
        button:hover { background: #005999; }
    </style>
</head>
<body>
    <div class="container">
        <h1>🧠 ruv-FANN Web Demo</h1>
        
        <h2>Neural Network Training</h2>
        <button onclick="trainNetwork()">Train XOR Network</button>
        <button onclick="testNetwork()">Test Network</button>
        
        <h2>AI Swarm Coordination</h2>
        <button onclick="initializeSwarm()">Initialize Swarm</button>
        <button onclick="orchestrateTask()">Execute Task</button>
        
        <div id="output" class="output">
            Ready to run AI demos...
        </div>
    </div>

    <script type="module">
        import init, { NeuralNetwork, SwarmOrchestrator } from './pkg/ruv_fann.js';
        
        let network = null;
        let swarm = null;
        
        async function initWasm() {
            await init();
            updateOutput('🚀 WASM runtime initialized');
        }
        
        window.trainNetwork = async function() {
            try {
                updateOutput('🧠 Creating and training neural network...');
                
                network = new NeuralNetwork(3, [4, 2], 1);
                
                // XOR training data
                const trainingData = [
                    { input: [0, 0, 1], output: [0] },
                    { input: [0, 1, 1], output: [1] },
                    { input: [1, 0, 1], output: [1] },
                    { input: [1, 1, 1], output: [0] },
                ];
                
                const startTime = performance.now();
                await network.train(trainingData, 1000);
                const trainingTime = performance.now() - startTime;
                
                updateOutput(`✅ Network trained in ${trainingTime.toFixed(1)}ms`);
            } catch (error) {
                updateOutput(`❌ Training failed: ${error.message}`);
            }
        };
        
        window.testNetwork = async function() {
            if (!network) {
                updateOutput('❌ Please train network first');
                return;
            }
            
            try {
                updateOutput('🧪 Testing XOR function...');
                
                const tests = [
                    [0, 0], [0, 1], [1, 0], [1, 1]
                ];
                
                let results = 'XOR Test Results:\n';
                for (const [a, b] of tests) {
                    const output = await network.run([a, b, 1]);
                    const result = output[0] > 0.5 ? 1 : 0;
                    results += `XOR(${a}, ${b}) = ${output[0].toFixed(3)} → ${result}\n`;
                }
                
                updateOutput(results);
            } catch (error) {
                updateOutput(`❌ Testing failed: ${error.message}`);
            }
        };
        
        window.initializeSwarm = async function() {
            try {
                updateOutput('🐝 Initializing AI swarm...');
                
                swarm = new SwarmOrchestrator({
                    maxAgents: 3,
                    topology: 'hierarchical',
                    strategy: 'balanced'
                });
                
                await swarm.spawnAgent('researcher', 'Research Agent');
                await swarm.spawnAgent('analyst', 'Analysis Agent');
                await swarm.spawnAgent('synthesizer', 'Synthesis Agent');
                
                updateOutput('✅ Swarm initialized with 3 agents');
            } catch (error) {
                updateOutput(`❌ Swarm initialization failed: ${error.message}`);
            }
        };
        
        window.orchestrateTask = async function() {
            if (!swarm) {
                updateOutput('❌ Please initialize swarm first');
                return;
            }
            
            try {
                updateOutput('🎯 Orchestrating collaborative task...');
                
                const task = {
                    description: 'Analyze web AI trends',
                    priority: 'high',
                    parameters: {
                        domain: 'web_ai',
                        timeframe: '2024'
                    }
                };
                
                const startTime = performance.now();
                const result = await swarm.orchestrate(task);
                const executionTime = performance.now() - startTime;
                
                updateOutput(`✅ Task completed in ${executionTime.toFixed(1)}ms
📊 Results:
   - Status: ${result.status}
   - Agents: ${result.agentsUsed}
   - Confidence: ${(result.confidence * 100).toFixed(1)}%`);
            } catch (error) {
                updateOutput(`❌ Task execution failed: ${error.message}`);
            }
        };
        
        function updateOutput(text) {
            document.getElementById('output').innerText = text;
        }
        
        // Initialize WASM on page load
        initWasm().catch(console.error);
    </script>
</body>
</html>

Serve the Demo

# Serve the web demo
python -m http.server 8000

# Open http://localhost:8000 in your browser

🚀 Step 5: Advanced Features (15 minutes)

SIMD Acceleration

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

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

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

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

// 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

🐝 Swarm Intelligence

🚀 Production Deployment

📚 Learning Resources

🎉 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 or dive into specific components in the Component Overview.

Clone this wiki locally