Contributing - ruvnet/ruv-FANN GitHub Wiki

Contributing to ruv-FANN

Welcome to the ruv-FANN Neural Intelligence Framework! We're excited that you're interested in contributing to our project. This guide will help you get started with contributing to any of our three core components: ruv-FANN Core, Neuro-Divergent, and ruv-swarm.

Table of Contents

Code of Conduct

We are committed to providing a welcoming and inclusive environment for all contributors. By participating in this project, you agree to abide by our code of conduct:

  • Be respectful: Treat all community members with respect and kindness
  • Be inclusive: Welcome newcomers and encourage diverse perspectives
  • Be constructive: Provide helpful feedback and criticism
  • Be collaborative: Work together to achieve common goals
  • Be professional: Maintain professionalism in all interactions

Getting Started

Prerequisites

Before contributing, ensure you have the following installed:

  • Rust 1.81+: Install via rustup
  • Node.js 18+: For JavaScript/NPM components
  • Git: For version control
  • wasm-pack: For WebAssembly builds
    curl https://rustwasm.github.io/wasm-pack/installer/init.sh -sSf | sh

Quick Start

  1. Fork the Repository

    # Fork the repo on GitHub, then clone your fork
    git clone https://github.com/your-username/ruv-FANN.git
    cd ruv-FANN
  2. Set Up Remote

    git remote add upstream https://github.com/ruvnet/ruv-FANN.git
  3. Initialize ruv-swarm (Recommended)

    # Use our swarm-based contribution system
    npx ruv-swarm@latest init --github-swarm
    npx ruv-swarm contribute --type "feature|bug|docs"

Development Setup

Core ruv-FANN Setup

# Build the main library
cargo build --workspace
cargo test --workspace

# Run with different feature flags
cargo build --features "gpu,parallel,wasm"
cargo test --features "test-all"

Neuro-Divergent Setup

cd neuro-divergent
cargo build --release
cargo test --release

# Run benchmarks
cargo bench

ruv-swarm Setup

cd ruv-swarm

# Rust components
cargo build --workspace
cargo test --workspace

# NPM components
cd npm
npm install
npm test
npm run build:wasm

IDE Configuration

VS Code Extensions (Recommended):

  • rust-analyzer
  • CodeLLDB (debugging)
  • Better TOML
  • crates
  • Error Lens

Settings for optimal development:

{
  "rust-analyzer.cargo.features": ["default", "gpu", "parallel"],
  "rust-analyzer.check.command": "clippy",
  "editor.formatOnSave": true
}

Code Style Guidelines

Rust Style Guide

We follow the official Rust style guide with project-specific conventions:

1. Documentation

/// Calculates attention weights using Cartan matrix semantics.
/// 
/// This function implements the core semantic attention mechanism
/// that enables neural networks to understand mathematical structures.
/// 
/// # Arguments
/// * `input` - Input tensor with shape [batch_size, seq_len, dim]
/// * `cartan_matrix` - Cartan matrix defining the root system
/// 
/// # Returns
/// Attention weights tensor with shape [batch_size, heads, seq_len, seq_len]
/// 
/// # Example
/// ```
/// use ruv_fann::attention::semantic_attention;
/// let weights = semantic_attention(&input, &cartan_matrix)?;
/// ```
pub fn semantic_attention(
    input: &Tensor,
    cartan_matrix: &CartanMatrix,
) -> Result<Tensor, AttentionError> {
    // Implementation...
}

2. Error Handling

// Use proper error types
#[derive(Debug, thiserror::Error)]
pub enum NeuralError {
    #[error("Invalid tensor dimensions: expected {expected}, got {actual}")]
    InvalidDimensions { expected: usize, actual: usize },
    
    #[error("WASM module failed to load: {0}")]
    WasmLoadError(#[from] wasmtime::Error),
    
    #[error("GPU memory allocation failed")]
    GpuMemoryError,
}

// Use Result types consistently
fn train_network(data: &TrainingData) -> Result<Network, NeuralError> {
    let weights = initialize_weights(data.input_size())?;
    let network = Network::new(weights)?;
    Ok(network)
}

3. Performance Patterns

// Use SIMD when available
#[cfg(target_feature = "simd128")]
fn vectorized_operation(data: &[f32]) -> Vec<f32> {
    use std::simd::*;
    // SIMD implementation
}

#[cfg(not(target_feature = "simd128"))]
fn vectorized_operation(data: &[f32]) -> Vec<f32> {
    // Fallback implementation
}

// Prefer rayon for parallelization
use rayon::prelude::*;

fn parallel_training(batches: &[TrainingBatch]) -> Vec<ModelUpdate> {
    batches
        .par_iter()
        .map(|batch| train_batch(batch))
        .collect()
}

4. Memory Management

// Use appropriate data structures
use std::collections::HashMap;
use indexmap::IndexMap; // For ordered maps
use smallvec::SmallVec; // For small vectors

// Manage GPU memory carefully
struct GpuBuffer {
    buffer: wgpu::Buffer,
    size: u64,
}

impl Drop for GpuBuffer {
    fn drop(&mut self) {
        // Ensure proper cleanup
        self.buffer.destroy();
    }
}

Code Formatting

Always run before committing:

# Format all code
cargo fmt --all

# Check lints
cargo clippy --workspace --all-targets -- -D warnings

# Fix common issues
cargo fix --workspace --allow-dirty

Pull Request Process

1. Planning Phase

For Significant Changes:

  1. Create or find a related issue
  2. Discuss your approach in the issue
  3. Get approval from maintainers for large features

For Bug Fixes:

  1. Reproduce the bug and document steps
  2. Create a failing test that demonstrates the issue
  3. Implement the fix
  4. Verify the test now passes

2. Implementation Phase

Branch Naming:

# Feature branches
git checkout -b feature/semantic-cartan-attention
git checkout -b feature/gpu-memory-optimization

# Bug fixes
git checkout -b fix/wasm-loading-error
git checkout -b fix/memory-leak-in-swarm

# Documentation
git checkout -b docs/api-reference-update
git checkout -b docs/contributing-guide

Commit Message Format:

We use Conventional Commits:

type(scope): description

[optional body]

[optional footer]

Types:

  • feat: New features
  • fix: Bug fixes
  • docs: Documentation changes
  • style: Code style changes
  • refactor: Code refactoring
  • perf: Performance improvements
  • test: Test additions/changes
  • chore: Maintenance tasks

Examples:

feat(attention): implement semantic Cartan matrix attention

Add new attention mechanism based on Cartan matrix semantics.
This enables neural networks to understand mathematical structures
in the input data.

- Implements CartanAttentionHead struct
- Adds comprehensive tests for all root systems
- Includes benchmarks showing 15% speed improvement
- Updates documentation with usage examples

Closes #123
fix(wasm): resolve module loading race condition

Fix race condition in WASM module initialization that caused
intermittent failures in multi-threaded environments.

The issue occurred when multiple threads tried to initialize
the same module simultaneously. Added proper synchronization
using Arc<Mutex<>> around the module cache.

Fixes #456

3. Testing Phase

Before Submitting PR:

# Run all tests
cargo test --workspace --all-features

# Run specific component tests
cargo test -p ruv-fann --features "gpu,parallel"
cargo test -p neuro-divergent --release
cd ruv-swarm && npm test

# Run benchmarks to check performance
cargo bench

# Build documentation
cargo doc --workspace --no-deps

# Check WASM builds
wasm-pack build --target web

4. PR Submission

PR Template:

## Description
Brief description of the changes and their purpose.

## Type of Change
- [ ] Bug fix (non-breaking change that fixes an issue)
- [ ] New feature (non-breaking change that adds functionality)
- [ ] Breaking change (fix or feature that causes existing functionality to not work as expected)
- [ ] Performance improvement
- [ ] Documentation update

## Component(s) Affected
- [ ] ruv-FANN Core
- [ ] Neuro-Divergent
- [ ] ruv-swarm
- [ ] Semantic Cartan Matrix
- [ ] Documentation

## Testing
- [ ] Unit tests pass
- [ ] Integration tests pass
- [ ] Performance benchmarks run
- [ ] WASM builds successfully
- [ ] Manual testing completed

## Performance Impact
- [ ] No performance impact
- [ ] Performance improved (include benchmark results)
- [ ] Performance regression (justified and documented)

## Breaking Changes
List any breaking changes and migration steps.

## Checklist
- [ ] Code follows style guidelines
- [ ] Self-review completed
- [ ] Documentation updated
- [ ] Tests added for new functionality
- [ ] All CI checks pass
- [ ] Linked to relevant issues

Closes #(issue number)

5. Review Process

  1. Automated Checks: CI/CD pipeline runs all tests
  2. Code Review: Maintainers review code quality and design
  3. Testing: QA testing for significant features
  4. Documentation Review: Ensure docs are updated
  5. Performance Review: Check benchmark impacts
  6. Final Approval: Maintainer approval for merge

Testing Requirements

Test Organization

tests/
├── unit/                 # Unit tests for individual components
│   ├── neural/           # Neural network core tests
│   ├── attention/        # Attention mechanism tests
│   ├── swarm/           # Swarm coordination tests
│   └── wasm/            # WASM-specific tests
├── integration/          # Cross-component integration tests
├── benchmarks/          # Performance benchmarks
├── property/            # Property-based tests with proptest
└── fixtures/            # Test data and utilities

Testing Standards

1. Unit Tests

#[cfg(test)]
mod tests {
    use super::*;
    use approx::assert_relative_eq;
    use proptest::prelude::*;

    #[test]
    fn test_semantic_attention_basic() {
        let input = Tensor::zeros(&[2, 10, 64]);
        let cartan = CartanMatrix::a_series(3);
        
        let result = semantic_attention(&input, &cartan).unwrap();
        assert_eq!(result.shape(), &[2, 8, 10, 10]);
    }

    #[test]
    fn test_attention_weights_sum_to_one() {
        let input = Tensor::random(&[1, 5, 32]);
        let cartan = CartanMatrix::b_series(2);
        
        let weights = semantic_attention(&input, &cartan).unwrap();
        let sums = weights.sum_dim(-1);
        
        for &sum in sums.iter() {
            assert_relative_eq!(sum, 1.0, epsilon = 1e-6);
        }
    }

    proptest! {
        #[test]
        fn test_attention_properties(
            batch_size in 1..10usize,
            seq_len in 1..50usize,
            dim in 16..128usize,
        ) {
            let input = Tensor::random(&[batch_size, seq_len, dim]);
            let cartan = CartanMatrix::a_series(3);
            
            let result = semantic_attention(&input, &cartan);
            prop_assert!(result.is_ok());
            
            let weights = result.unwrap();
            prop_assert_eq!(weights.shape()[0], batch_size);
            prop_assert_eq!(weights.shape()[2], seq_len);
        }
    }
}

2. Integration Tests

// tests/integration/neural_pipeline.rs
use ruv_fann::prelude::*;

#[tokio::test]
async fn test_full_training_pipeline() {
    let config = NetworkConfig::default()
        .with_layers(&[784, 128, 64, 10])
        .with_activation(ActivationFunction::ReLU)
        .with_cartan_attention(true);
    
    let mut network = Network::new(config).unwrap();
    let training_data = load_test_dataset().unwrap();
    
    // Train the network
    let trainer = Trainer::new()
        .with_learning_rate(0.001)
        .with_batch_size(32);
    
    let metrics = trainer.train(&mut network, &training_data).await.unwrap();
    
    assert!(metrics.final_accuracy > 0.8);
    assert!(metrics.convergence_epochs < 100);
}

3. Benchmark Tests

// benches/attention_benchmarks.rs
use criterion::{black_box, criterion_group, criterion_main, Criterion, BenchmarkId};
use ruv_fann::attention::*;

fn benchmark_semantic_attention(c: &mut Criterion) {
    let mut group = c.benchmark_group("semantic_attention");
    
    for seq_len in [32, 64, 128, 256].iter() {
        group.bench_with_input(
            BenchmarkId::new("cartan_attention", seq_len),
            seq_len,
            |b, &seq_len| {
                let input = Tensor::random(&[1, seq_len, 64]);
                let cartan = CartanMatrix::a_series(4);
                
                b.iter(|| {
                    semantic_attention(black_box(&input), black_box(&cartan))
                });
            },
        );
    }
    group.finish();
}

criterion_group!(benches, benchmark_semantic_attention);
criterion_main!(benches);

Test Coverage Requirements

  • Minimum Coverage: 80% line coverage
  • Critical Paths: 95% coverage for core algorithms
  • Public APIs: 100% coverage for all public functions
  • Error Paths: All error conditions must be tested

Community Guidelines

Communication Channels

  • GitHub Issues: Bug reports, feature requests, and technical discussions
  • GitHub Discussions: General questions, ideas, and community chat
  • Discord: Real-time collaboration and support (if available)
  • Twitter/X: Project updates and announcements

Getting Help

  1. Check Documentation: Review the wiki and API docs
  2. Search Issues: Look for existing discussions on your topic
  3. Ask in Discussions: Use GitHub Discussions for questions
  4. Join Discord: Get real-time help from the community

Reporting Issues

Bug Reports:

**Bug Description**
Clear, concise description of the bug.

**Steps to Reproduce**
1. Step one
2. Step two
3. See error

**Expected Behavior**
What you expected to happen.

**Actual Behavior**
What actually happened.

**Environment**
- OS: [e.g., Ubuntu 22.04]
- Rust version: [e.g., 1.81]
- ruv-FANN version: [e.g., 0.1.6]
- GPU: [if applicable]

**Additional Context**
Any other relevant information.

Feature Requests:

**Feature Description**
What feature would you like to see added?

**Use Case**
Why is this feature needed? What problem does it solve?

**Proposed Implementation**
If you have ideas about implementation, share them here.

**Alternatives Considered**
What alternatives have you considered?

Project Structure

Repository Organization

ruv-FANN/
├── src/                          # Core ruv-FANN library
│   ├── neural/                   # Neural network implementations
│   ├── activation/               # Activation functions
│   ├── training/                 # Training algorithms
│   ├── io/                       # Input/output utilities
│   └── webgpu/                   # GPU acceleration
├── neuro-divergent/              # Advanced forecasting models
│   ├── src/                      # Model implementations
│   ├── examples/                 # Usage examples
│   └── tests/                    # Model-specific tests
├── ruv-swarm/                    # Distributed swarm intelligence
│   ├── src/                      # Rust implementation
│   ├── npm/                      # NPM package
│   └── docs/                     # Swarm documentation
├── Semantic_Cartan_Matrix/       # Mathematical foundation
│   ├── micro_cartan_attn/        # Attention mechanisms
│   ├── micro_core/               # Core operations
│   ├── micro_swarm/              # Swarm coordination
│   └── micro_routing/            # Routing algorithms
├── cuda-wasm/                    # CUDA to WASM transpiler
├── simulator/                    # Neural chip simulation
└── examples/                     # Cross-project examples

Contribution Areas

1. Core Neural Networks (ruv-FANN)

What to work on:

  • Activation functions
  • Training algorithms
  • Network architectures
  • GPU acceleration
  • WASM bindings

Skills needed:

  • Rust programming
  • Neural network theory
  • GPU programming (optional)
  • WebAssembly (optional)

2. Forecasting Models (Neuro-Divergent)

What to work on:

  • LSTM implementations
  • Transformer models
  • Time series analysis
  • Model optimization
  • Python compatibility

Skills needed:

  • Rust programming
  • Machine learning
  • Time series analysis
  • Mathematical modeling

3. Swarm Intelligence (ruv-swarm)

What to work on:

  • Agent coordination
  • Topology optimization
  • Distributed algorithms
  • CLI tools
  • MCP integration

Skills needed:

  • Rust programming
  • JavaScript/TypeScript
  • Distributed systems
  • Graph theory

4. Mathematical Foundation (Semantic Cartan Matrix)

What to work on:

  • Lie algebra implementations
  • Root system computations
  • Orthogonalization algorithms
  • Mathematical optimizations

Skills needed:

  • Advanced mathematics
  • Rust programming
  • Linear algebra
  • Group theory

5. Documentation and Examples

What to work on:

  • API documentation
  • Tutorials and guides
  • Code examples
  • Performance benchmarks

Skills needed:

  • Technical writing
  • Programming in Rust/JS
  • Understanding of the domain

Performance Guidelines

Optimization Principles

  1. Measure First: Always profile before optimizing
  2. Focus on Hot Paths: Optimize the most frequently called code
  3. Memory Efficiency: Minimize allocations in critical paths
  4. Vectorization: Use SIMD instructions where possible
  5. Parallelization: Leverage multi-core processing with rayon

Benchmarking Standards

// Always include benchmarks for performance-critical code
use criterion::{criterion_group, criterion_main, Criterion};

fn benchmark_critical_function(c: &mut Criterion) {
    let data = setup_benchmark_data();
    
    c.bench_function("critical_function", |b| {
        b.iter(|| {
            critical_function(black_box(&data))
        });
    });
}

Performance Targets

  • Training Speed: >1000 samples/second on CPU
  • Inference Speed: <1ms per sample for small networks
  • Memory Usage: <100MB for typical use cases
  • WASM Performance: Within 2x of native performance

Documentation Standards

Code Documentation

All public APIs must be documented with rustdoc:

/// Computes semantic attention using Cartan matrix structure.
/// 
/// This function implements attention mechanisms that understand
/// the underlying mathematical structure of the data through
/// Cartan matrices from Lie algebra theory.
/// 
/// # Parameters
/// 
/// * `query` - Query tensor with shape [batch, seq_len, d_model]
/// * `key` - Key tensor with shape [batch, seq_len, d_model]  
/// * `value` - Value tensor with shape [batch, seq_len, d_model]
/// * `cartan_matrix` - Cartan matrix defining the root system
/// 
/// # Returns
/// 
/// Returns the attention output tensor with shape [batch, seq_len, d_model]
/// 
/// # Errors
/// 
/// Returns `AttentionError` if:
/// - Input tensors have incompatible shapes
/// - Cartan matrix has invalid dimensions
/// - Memory allocation fails
/// 
/// # Examples
/// 
/// ```rust
/// use ruv_fann::attention::{semantic_attention, CartanMatrix};
/// use ruv_fann::tensor::Tensor;
/// 
/// let query = Tensor::random(&[2, 10, 64]);
/// let key = Tensor::random(&[2, 10, 64]);
/// let value = Tensor::random(&[2, 10, 64]);
/// let cartan = CartanMatrix::a_series(3);
/// 
/// let output = semantic_attention(&query, &key, &value, &cartan)?;
/// assert_eq!(output.shape(), &[2, 10, 64]);
/// ```
/// 
/// # Performance
/// 
/// This function is optimized for:
/// - SIMD vectorization on x86_64
/// - Parallel computation across attention heads
/// - Memory-efficient implementation with minimal allocations
/// 
/// Typical performance: ~50 Ξs for sequence length 128 on modern CPUs.

User Documentation

  • Clear Examples: Every feature should have working examples
  • Common Patterns: Document typical usage patterns
  • Troubleshooting: Address common issues and solutions
  • Migration Guides: Help users upgrade between versions

Advanced Topics

Adding New Components

When adding major new components:

  1. Design Document: Create a detailed design in issues
  2. API Discussion: Get feedback on proposed APIs
  3. Prototype: Implement a minimal working version
  4. Testing: Comprehensive test suite
  5. Documentation: Full documentation and examples
  6. Integration: Ensure compatibility with existing code

Performance Optimization

For performance-critical contributions:

  1. Baseline Benchmarks: Establish current performance
  2. Optimization Implementation: Make targeted improvements
  3. Measurement: Verify improvements with benchmarks
  4. Regression Tests: Ensure no performance regressions
  5. Documentation: Document the optimization techniques

Breaking Changes

For changes that break existing APIs:

  1. Deprecation Period: Mark old APIs as deprecated
  2. Migration Guide: Provide clear upgrade instructions
  3. Compatibility Layer: Maintain compatibility when possible
  4. Version Bump: Follow semantic versioning
  5. Communication: Announce changes to the community

Thank You!

Contributing to ruv-FANN means joining a community dedicated to making neural intelligence accessible, composable, and precise. Whether you're fixing a typo, implementing a new feature, or optimizing performance, every contribution matters.

Ready to contribute? Start by exploring our open issues or join our community discussions!


Built with âĪïļ and ðŸĶ€ by the rUv community

⚠ïļ **GitHub.com Fallback** ⚠ïļ