ruv-fann

Library Listed

A pure Rust implementation of the Fast Artificial Neural Network (FANN) library

Checked · Sources

Downloads
270
Dependents
7
Stars
388
Forks
108
Contributors
6
Commits
340
Latest release
0.2.1 ·

About

From the project README ·

Rust libraries for neural networks, time-series forecasting, agent coordination, GPU compute, and image processing.

Start with ruv-fann if you need a small feedforward neural network in Rust. It provides generic floating-point networks, training algorithms, and model I/O inspired by FANN. Other directories contain separate libraries and tools with their own build requirements.

Repository map: five independent Rust workspaces for neural networks, agent tools, forecasting, CUDA source translation and image processing.

Read the full README

Choose a package

LocationAvailable behaviorCandidate versions / guide
Repository rootruv-fann: train feedforward networks, prepare immutable CPU inference snapshots, and use optional WebGPU operations0.2.2 · Core example · API
ruv-swarm/Fourteen Rust packages for scheduling, persistence, transport, MCP, CLI, and WASM1.0.6–1.0.8; unified WASM 2.0.0 · Rust guide
ruv-swarm/npm/Node CLI/MCP, SQLite state, prepared WASM inference, historical forecast intervals, and capability assignmentruv-swarm 2.0.0 · npm guide
neuro-divergent/Six Rust packages: RNN training, baselines, chronological evaluation, residual-calibrated intervals, and checkpoints0.2.0 · Forecasting guide
cuda-wasm/Translate a CUDA subset to Rust or WGSL source; Node wrapper requires the external cuda2rust compilerRust 0.2.0; npm 2.0.0 · Translator guide
opencv-rust/Portable Rust matrices, browser image operations, a small SDK, and native OpenCV C++ bindingsPortable/SDK 4.9.0; native opencv-sys 0.2.0 · Image-processing guide

These are five independent Cargo workspaces with 26 Rust packages and two public npm distributions. Running cargo test at the repository root tests the core crate; use the verification driver below to cover the other workspaces. Versions in this checkout are unpublished release candidates. The release inventory records their exact identities and separate registry observations.

Each family has a defined scope. Forecasting currently implements a univariate RNN and simple baselines; LSTM/GRU forecasting architectures return unsupported errors. Agent assignment records scheduling decisions; external task execution depends on the integration you supply. CUDA translation emits source and does not execute a GPU kernel. The native OpenCV bridge calls an installed C++ library, while the portable packages implement a smaller set of operations.

Try the neural-network core

Install Rust, then run the included example:

git clone https://github.com/ruvnet/ruv-FANN.git
cd ruv-FANN
cargo run --locked --example basic_usage

For the published crate, run cargo add ruv-fann in your application. To try changes from this checkout, use cargo add ruv-fann --path /path/to/ruv-FANN instead. Published API documentation describes the published version; new checkout APIs become available after a release.

This example uses explicit weights so you can check the result without training:

use ruv_fann::{ActivationFunction, NetworkBuilder};

fn main() -> Result<(), Box<dyn std::error::Error>> {
    let mut network = NetworkBuilder::<f32>::new()
        .input_layer(2)
        .output_layer_with_activation(1, ActivationFunction::Linear, 1.0)
        .build();

    // Two input weights, followed by the bias weight.
    network.set_weights(&[0.5, -0.25, 0.1])?;
    let outputs = network.run(&[1.0, 2.0])?;
    assert!((outputs[0] - 0.1).abs() < 1e-6);
    println!("Output: {}", outputs[0]);

    Ok(())
}

The calculation is 0.5 × 1.0 − 0.25 × 2.0 + 0.1 = 0.1. A real task needs suitable data and trained weights. Training examples and algorithms include backpropagation, RPROP, Quickprop, Adam, and AdamW.

Forward-pass diagram: input numbers pass through weighted connections and activation functions; run returns a vector, while run_into writes to a caller-provided output slice.

For repeated inference, the checkout adds Network::run_into(inputs, outputs). Pass a mutable output slice whose length equals num_outputs(). It reuses that buffer and the network's stored neuron values. run() remains the convenient API that returns a vector. Check input and output lengths through the returned Result.

Prepare a network for repeated inference

Prepare parameters once, reuse private inference workspaces, and calibrate forecast intervals only from past errors.

After training, network.prepare() copies validated parameters into an immutable snapshot. Give each caller its own reusable workspace; several threads can share the same prepared network without sharing mutable neuron caches:

let prepared = network.prepare()?;
let mut workspace = prepared.workspace()?;
let mut output = vec![0.0; prepared.num_outputs()];
prepared.run_into(&[1.0, 2.0], &mut output, &mut workspace)?;

Hot calls allocate no memory. Changing the original network does not change the snapshot; prepare a new one after training or editing weights. Preparation rejects invalid graph indices, non-finite parameters and noncanonical bias state. The default estimated allocation budget is 64 MiB, including one workspace; this is not a process-memory limit. A failed call leaves the output slice unchanged.

Dense rows use contiguous scalar arithmetic; sparse and reordered connections retain their order. This path adds no external inference engine or quantization. Run the complete example with cargo run --locked --example prepared_inference. The current research review explains adoption choices and separate benchmark/evaluation requirements.

Run the same engines in WebAssembly

The ruv-swarm JavaScript package includes prepared inference and historical forecast intervals in its ordinary and SIMD WASM binaries. In Node.js 22.13+:

import { RuvSwarm } from 'ruv-swarm';
const runtime = await RuvSwarm.initialize();
const network = runtime.createNeuralNetwork([2, 1], 'Linear');
network.set_weights(Float64Array.of(2, -1));
const prepared = network.prepare();
network.free();
const output = new Float64Array(1);
prepared.run_into(Float64Array.of(3, 4), output); // [2]
prepared.free();

runtime.createPreparedNetwork(networkJson) also imports native Rust Network<f64> JSON, retaining sparse connection order and all native activations. runtime.createConformalCalibrator(config) fits the shared residual engine with explicit past observations. Its timestamps are safe-integer Unix milliseconds. See the JavaScript guide for formats and limits, or serve the browser example over HTTP. The browser imports the generated WASM bindings directly.

run_into reuses Rust numeric buffers and the output array; JavaScript boundary checks and copies still have a cost. The native f32 benchmark below does not measure browser or Node.js latency. Historical intervals retain their documented time-series coverage limitations. The WASM results show measured timings and the tradeoff for very small networks.

For many samples, create a fixed-capacity batch workspace. Native Rust supports both f32 and f64; input and output slices contain one row after another:

let mut batch = prepared.batch_workspace(2, 1024 * 1024)?;
let inputs = [1.0, 2.0, 3.0, 4.0]; // two rows for a two-input network
let mut outputs = vec![0.0; 2 * prepared.num_outputs()];
prepared.run_batch_into(&inputs, &mut outputs, 2, &mut batch)?;

The JavaScript API exposes prepared.create_batch(capacity) and batch.run_into(inputs, outputs, rows). It reuses numeric buffers and can keep running after the original prepared handle is freed. The SIMD build processes independent samples in parallel without reordering any sample's weighted sum.

Input rows cross one checked boundary, reuse shared weights in independent SIMD sample lanes, and commit output rows after full success.

Pick the features you need

FeaturePurpose and limits
Default featuresEnable model I/O, serialization, compression, logging, and parallel-related utilities. CPU inference does not require a GPU.
ioEnables file formats and training-data I/O. Keep bounds on bytes, decompressed data, and declared model dimensions when loading external data.
simd / parallelExpose CPU optimization utilities. A feature being enabled does not mean every network or training operation uses vector instructions or multiple threads. Measure the path you call.
gpuEnables the native Rust WGPU backend with checked matrix/batch dispatch, f32 activations, and managed device buffers. It needs a compatible device and driver. f64 compute uses the CPU to preserve precision. It does not route every network or trainer through a GPU.
webgpu / wasm-gpuOn wasm32, expose the async WasmGpuBridge for f32 matrix multiplication and activations in a browser with WebGPU. Buffers are limited to 64 MiB and device limits; matrix calls have a work budget. GPU unavailability returns an error. These features do not enable the native gpu backend.
wasmEnables WASM-related bindings and dependencies. Browser execution has a separate test gate; target compilation alone does not establish browser behavior.
no_stdCurrently a feature marker. The core still uses the Rust standard library; this is not a supported bare-metal #![no_std] build.

See Cargo.toml for the precise feature dependency graph. Native Rust gpu tests use software Vulkan. Browser tests load the built Rust WASM bridge and verify matrix results, all 21 activations, invalid inputs, and device lifecycle with Chromium/SwiftShader. A separate harness directly checks all seven WGSL modules and Adam/AdamW updates. These checks establish numerical behavior on software adapters. Physical GPU throughput and every experimental training combination remain unevaluated. See the core review for limits, tolerances, and commands.

Build and test

Use a current stable Rust toolchain for full-repository development. The core declares Rust 1.81; the swarm and all four OpenCV packages declare Rust 1.88. Python 3.11 or newer runs the verification tools. Node 22.13 or newer covers the root tooling and swarm distribution; the standalone CUDA wrapper requires Node 22.12 or newer.

The full OpenCV workspace also needs a C++17 compiler, pkg-config, libclang, and OpenCV 4.4 or newer development files. On Debian/Ubuntu these are typically g++, pkg-config, libclang-dev, and libopencv-dev. See the native setup guide for a checked user-owned prefix option. Portable OpenCV packages can be tested with --exclude opencv-sys. Swarm's SQLite npm addon may also need a C++ build toolchain.

# Inventory every Cargo workspace and npm distribution.
python3 scripts/verify-packages.py --inventory

# Check and test registered libraries, binaries, tests, examples, and benchmarks.
# Install the native OpenCV prerequisites first.
python3 scripts/verify-packages.py --check
python3 scripts/verify-packages.py --test

# Audit all five Cargo lockfiles (requires cargo-audit).
python3 scripts/verify-packages.py --audit

# Validate README links and the SVG diagram sources.
python3 scripts/verify-packages.py --docs

The driver uses --workspace --all-targets, enables all features for swarm and forecasting, and selects CUDA's portable serde configuration. It also runs the targeted safety regressions and reports every failed command. GPU/browser execution, npm consumers, and Cargo archive verification have separate gates recorded in the modernization report. An inventory or successful metadata resolution is not a passing test suite.

For work on the core alone:

cargo test --locked --lib
cargo test --locked --doc
cargo check --locked --no-default-features
cargo bench --locked --bench neural_network

To build and test the Rust browser GPU bridge, install wasm-pack, the root npm dependencies, and Playwright's Chromium, then run node scripts/verify-rust-browser-gpu.cjs --build. This checks generated Rust WASM through the public browser API. The bridge accepts Float32Array inputs and implements compute rather than canvas rendering or browser agent orchestration.

For a single family, pass --workspace neuro-divergent to the verification driver or use its manifest directly. The family guide explains optional features and native libraries. Run JavaScript commands from the relevant npm directory; the repository root is an integration harness. See each npm guide for a clean install, genuine artifact build, tests, and packed-consumer validation.

Performance and research

Measure the workload you intend to deploy. Record the commit, compiler, CPU or GPU, target features, model shape, batch size, thread count, warm-up, and numeric tolerance. Compare identical inputs and weights, and include allocation and transfer costs in end-to-end results. Criterion output is written under target/criterion/.

The latest comparison uses actual Float64 WASM in Node and Chromium. A 128-row SIMD batch produced these mean per-row latencies, including JavaScript validation and copies. Speed ratios compare repeated prepared single calls in the same binary; setup and compilation are outside the timings.

Linear networkNode 24Chromium 156Chromium speed ratio
5 → 7 → 383.3 ns87.6 ns25.96×
100 → 50 → 25 → 102.11 µs2.22 µs3.07×
784 → 128 → 64 → 1029.38 µs29.02 µs3.35×

Measured batch throughput across model and batch sizes.

These single-host results are workload-specific. One-row batches can be slower; the native f32/f64 comparison also shows small-batch regressions. Release WASM uses optimization level 3 and checked arithmetic: compared with the size profile, the binaries grow by about 65 KB each. All measured inference outputs match, and old/new calibration JSON is byte-identical. The full results include raw samples, confidence intervals, native calibration results, and reproduction commands. See the research review for adoption choices and the earlier modernization report for package verification.

Verify frozen builds with Rune

Rune now checks a runnable product built from this repository's actual core. The integration pins Rune's source revision and lockfile, builds it locally, then freezes a plan, replays it and rebuilds in a fresh target directory. The digest-bound executable exercises f32/f64 batches and historical calibration; separate release tests cover the core library.

python3 scripts/rune.py plan --repo .
python3 scripts/rune.py --help

Setup and dependency fetching are explicit steps. Verification uses Cargo offline, records zero model calls, and rejects stale source, a changed plan or a corrupted stored artifact. It copies source into an isolated directory and leaves project files and existing locks intact. This is build provenance and correctness evidence; it does not measure a performance gain or provide an OS sandbox. The setup guide explains the commands and scope. The Rune workflow runs on relevant pushes/PRs and is also part of the full release acceptance gate.

Tune WASM batching with MetaHarness

The private MetaHarness tool uses the real Darwin numeric optimizer to search batch sizes for the shipped WASM. Every candidate processes the same rows and must reproduce every reference output. A fresh paired measurement checks the candidate after search; a faster search sample alone is not enough for a recommendation.

npm ci --prefix tools/metaharness --ignore-scripts --omit=optional
node tools/metaharness/src/cli.mjs plan --repo .
node tools/metaharness/src/cli.mjs optimize --repo . --variant simd --model medium --baseline-batch-rows 128 --output /tmp/ruv-fann-tuning

Use POSIX (Linux or macOS) and Node 22.13+. Set the baseline to your current batch size (the default is one row). Use a new output directory for each run. The loop bounds evaluations, time and output, reuses identical observations, and records raw timings and confidence intervals. It changes batch configuration inside the experiment, without editing source or applying the result to production. The optional score command is a static metadata assessment, separate from runtime tests.

Bounded search measures real WASM, checks outputs, and confirms a candidate before recommending it.

The detailed workflow explains installation, presets, receipts and limits. The CI gate executes real core/SIMD trials on supported Node versions without requiring a speedup on shared runners. No model service or provider key is needed.

The measured results include the 128-row control: no confirmed gain over that existing setting, which the loop correctly retained.

Contribute

Choose a package, reproduce the issue, and add a regression test for a behavior change. Run that package's checks and the relevant integration checks before opening a pull request. Include the commands and results so another contributor can reproduce them.

Model files, training data, plugins, and network messages cross trust boundaries. Changes to those inputs should validate dimensions and resource use before allocating, return useful errors, and preserve format compatibility or document a migration. See the deserialization decision and migration notes.

Credits and license

Thanks to the contributors listed in CONTRIBUTORS.md, including Ocean (@ohdearquant), Bron (@syndicate604), Jed (@jedarden), and Shep (@elsheppo), and to the FANN, Rust, NeuralForecast, Tokio, Serde, and WebAssembly communities.

See the repository LICENSE and each package's manifest for licensing information.

Runs on
CUDA, WebGPU
What shows it
  • CUDA: geometric-langlands feature cuda, ruv-swarm-daa feature neural-networks (dependency tch)
  • WebGPU: ruv-fann feature webgpu (dependency wgpu)
Native code
Required
  • Binds native code: libsqlite3-sys, win-sys, torch-sys (feature neural-networks)
  • Build uses a native toolchain: cc
Python bindings
Has Python bindings
  • opencv-sdk needs Python only with feature python
License
Apache-2.0 OR MIT

Compare with similar projects

Order: strongest tier first, then most downloads, then name, with unmeasured values last. A library counts downloads over 30 days. An app counts binary downloads per release. An app with none counts its crate downloads over 30 days. ML Rust runs this catalogue, so its closest project always gets a row.

ruv-fann beside the projects that share a topic with it
ProjectDownloadsDependentsStarsLatest releaseRuns on (GPU)Native codeLicense
ruv-fann This page Listed

A pure Rust implementation of the Fast Artificial Neural Network (FANN) library

Python bindings

270 downloads over 30 days 7 388 0.2.1 CUDA, WebGPU Binds native code: libsqlite3-sys, win-sys, torch-sys (feature neural-networks). Build uses a native toolchain: cc Apache-2.0 OR MIT
aprender Listed

Next-generation ML framework in pure Rust — `cargo install aprender` for the `apr` CLI

15,442 downloads over 30 days 31 140 0.72.3 CUDA, WebGPU Binds native code: libsqlite3-sys, zstd-sys, tree-sitter (feature full), alsa-sys (feature audio-alsa), nvml-wrapper-sys (feature nvml) and 1 more. Build uses a native toolchain: bindgen (feature bindgen) MIT
web-rwkv Listed

An implementation of the RWKV language model in pure WebGPU.

444 downloads over 30 days 3 360 0.10.20 WebGPU Binds native code: tracy-client-sys (feature trace) Apache-2.0 OR MIT
neuroflow Listed Dormant

The neural network library implemented in Rust

96 downloads over 30 days 0 121 0.2.0 GPU support unknown No native code found MIT
prophet Listed Dormant

A neural network implementation with a focus on cache-efficiency and sequential performance.

87 downloads over 30 days 0 41 0.4.2 GPU support unknown No native code found Apache-2.0 OR MIT
oxidizr App Listed

Trains GPT-style language models from a YAML config and a tokenized dataset: dense GQA transformers, Mamba 1, 2 and 3, MLA and MoE layers on CPU or CUDA. Runs the training loop, optimizer, checkpoints, evaluation and metrics on boostr, and builds speech corpora through voxr.

27 downloads over 30 days Not applicable 8 0.1.1 CUDA Binds native code: nvml-wrapper-sys (feature cuda) Apache-2.0
fann-rs Listed Dormant

Wrapper for the Fast Artificial Neural Networks library

10 downloads over 30 days 0 16 0.1.8 GPU support unknown Binds native code: fann-sys LGPL-3.0
Why ListedNo archive, New or Featured rule places it, so it is Listed.

What it lacks for Featured

  • It has 0 active dependents and 0 new dependents in 365 days. Featured needs 11 active dependents or 9 new dependents in 365 days. The repository route reads 388 stars, 108 forks and 6 contributors. It needs 4,539 stars, 434 forks and 79 contributors together.

What else the check found

Exact rules: Listed, Featured library. The check on applied thresholds version 9.

Every rule outcome, as the check records it
  • expected-interval: version 0.2.1 base 300, raised to the 365-day floor: E = 365 days
  • dormancy: last activity 2026-11-09, 0 days ago, E = 365: active
  • rot: deprecated requirement `bincode (RUSTSEC-2025-0141, https://rustsec.org/advisories/RUSTSEC-2025-0141.html)`
  • featured: not featured: active_users 0 < 11 and new_adopters 0 < 9 and repository route stars 388 (needs 4539), forks 108 (needs 434), contributors 6 (needs 79)
  • listed: listed: no archive, new or featured rule applies
Crates23 crates

Measurements and sources

Each signal row shows the raw value, its source and the fetch date. The Sources list gathers every distinct source on this page. Movement needs more history.

Sources6 sources
Adoption0 active dependents, 0 new dependents in 365 days1 not measured
Adoption measurements
SignalValueSourceFetchedCounts
Active dependents0crates.io database dumpYes
New dependents (365 days)0crates.io database dumpYes
Peak active dependents0crates.io database dumpYes
Active dependents as a share of the peak1crates.io database dumpYes
Binary downloads per releaseNot measuredYes
MaintenanceLatest human commit: on the check date3 not measured
Maintenance measurements
SignalValueSourceFetchedCounts
Latest human commit2026-11-09GitHub repositoryYes
Latest release2026-05-23crates.io database dumpYes
First release2025-06-26crates.io database dumpYes
Latest version0.2.1crates.io database dumpYes
Days the oldest outside issue waits for a reply489GitHub repositoryYes
Maintainer replies over 365 days3GitHub repositoryYes
Repository archivedfalseGitHub repositoryYes
Repository gonefalseGitHub repositoryYes
Release commit or manifest in the repotruecrates.io packageYes
Published docstruecrates.io database dumpYes
Latest release fails cargo checkNot measuredYes
Build check dateNot measuredYes
Build check toolchainNot measuredYes
SecurityUnpatched vulnerabilities: none
Security measurements
SignalValueSourceFetchedCounts
Unpatched vulnerabilities past the grace windownoneRustSec advisory databaseYes
RustSec unmaintained advisorynoneRustSec advisory databaseYes
Deprecation noticenonecrates.io database dumpYes
Deprecated requirementbincode (RUSTSEC-2025-0141, https://rustsec.org/advisories/RUSTSEC-2025-0141.html)crates.io database dumpYes
Distribution8 releases, 270 downloads over 30 days5 not measured
Distribution measurements
SignalValueSourceFetchedCounts
Releases8crates.io database dumpYes
Downloads over 30 days270crates.io database dumpYes
Binary downloads over the last 3 releasesNot measuredYes
Homebrew installs on request over 365 daysNot measuredYes
Repology repository familiesNot measuredYes
Docker pull growth over 90 daysNot measuredYes
Docker pulls at the growth baselineNot measuredYes
Every version a prereleasefalsecrates.io database dumpYes
Every version 0.0.xfalsecrates.io database dumpYes
Every version yankedfalsecrates.io database dumpYes
Crate deleted from crates.iofalsecrates.io database dumpYes
Repository388 stars, 108 forks, 6 contributors, 340 commits. Stars alone never qualify a project.
Repository measurements
SignalValueSourceFetchedCounts
GitHub stars388GitHub repositoryYes — one part of the repository route
GitHub forks108GitHub repositoryYes — one part of the repository route
Contributors with a GitHub account6GitHub contributorsYes — one part of the repository route
Commits on the default branch340GitHub repositoryNo
Repository's main crate left out of the entrynonecrates.io database dumpYes
Facts that never count
Facts that never count measurements
SignalValueSourceFetchedCounts
LicenseApache-2.0 OR MITcrates.io database dumpNo
Runs on, from listed crates and their direct dependenciesCUDA, WebGPUcrates.io database dumpNo
What shows each backendCUDA: geometric-langlands feature cuda, ruv-swarm-daa feature neural-networks (dependency tch); WebGPU: ruv-fann feature webgpu (dependency wgpu)crates.io database dumpNo
Native code, from listed crates and their dependenciesBinds native code: libsqlite3-sys, win-sys, torch-sys (feature neural-networks). Build uses a native toolchain: cccrates.io database dumpNo
Python bindings, from direct dependencies of listed cratesHas Python bindings: opencv-sdk needs Python only with feature pythoncrates.io database dumpNo
Crates that depend on a listed crate directly7crates.io database dumpNo

Corrections and review history

Report a correction

No correction applies to this entry.

Judgments

A judgment enters only through an approved issue and a merged pull request.

No judgment applies to this entry.