Getting Started Guide - ruvnet/ruv-FANN GitHub Wiki

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.

โš ๏ธ **GitHub.com Fallback** โš ๏ธ