Getting Started Guide - ruvnet/ruv-FANN GitHub Wiki
Welcome to ruv-FANN! This comprehensive guide will take you from installation to building advanced AI systems with neural networks and swarm intelligence.
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
# 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# For web/Node.js integration
npm install ruv-swarm
# Global CLI tools
npm install -g claude-flow ruv-swarm# Test Rust installation
cargo build
# Test CLI tools
ruv-swarm --version
claude-flow --versionLet's create a neural network that learns to recognize handwritten digits.
// 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(())
}# 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"] }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)Now let's create an AI swarm that coordinates multiple agents to solve complex problems.
// 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...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%Deploy your AI to the web using WebAssembly.
# 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<!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 web demo
python -m http.server 8000
# Open http://localhost:8000 in your browseruse 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 applieduse 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 networksuse 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?;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);// 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);- Semantic Cartan Matrix - Mathematical neural architectures
- CUDA-WASM - GPU acceleration in browsers
- Neural Networks - Deep learning architectures
- Swarm Intelligence - Multi-agent coordination
- Autonomous Agents - Self-organizing systems
- Distributed Computing - Multi-node coordination
- Production Deployment - Enterprise deployment
- Monitoring & Metrics - Observability
- Security Guide - Security best practices
- Advanced Tutorials - Deep technical guides
- Use Cases - Real-world applications
- Best Practices - Professional patterns
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.