ruqu-neural-decoder

Crates.ioruqu-neural-decoder
lib.rsruqu-neural-decoder
version0.1.32
created_at2026-01-18 00:55:13.609636+00
updated_at2026-01-18 00:55:13.609636+00
descriptionNeural Quantum Error Decoder (NQED) - GNN-based decoder with O(d^2) Mamba state-space architecture
homepagehttps://ruv.io
repositoryhttps://github.com/ruvnet/ruvector
max_upload_size
id2051534
size269,608
rUv (ruvnet)

documentation

https://docs.rs/ruqu-neural-decoder

README

ruvector-neural-decoder

Crates.io Documentation License

Neural Quantum Error Decoder (NQED) - GNN-based quantum error correction with O(d²) Mamba architecture

Overview

ruvector-neural-decoder implements a neural network-based quantum error decoder that combines Graph Neural Networks (GNN) with Mamba state-space models for efficient syndrome decoding on surface codes.

Key Features

  • Graph Attention Encoder: Multi-head attention over syndrome graphs with learned positional encodings
  • Mamba O(d²) Decoder: Linear-time sequence modeling via selective state spaces (vs O(d⁴) transformers)
  • Min-Cut Feature Fusion: Integrates structural coherence signals from ruvector-mincut
  • Pure Rust: No external ML frameworks - uses ndarray for tensor operations
  • WASM Compatible: Designed for browser and edge deployment

Installation

Add to your Cargo.toml:

[dependencies]
ruvector-neural-decoder = "0.1"

Quick Start

use ruqu_neural_decoder::{NeuralDecoder, DecoderConfig};

// Create decoder for distance-5 surface code
let config = DecoderConfig {
    distance: 5,
    embed_dim: 64,
    hidden_dim: 128,
    num_gnn_layers: 3,
    num_heads: 4,
    ..Default::default()
};

let mut decoder = NeuralDecoder::new(config);

// Decode a syndrome (9 stabilizers for d=5 rotated surface code)
let syndrome = vec![true, false, true, false, false, false, false, false, true];
let correction = decoder.decode(&syndrome)?;

println!("X corrections: {:?}", correction.x_corrections);
println!("Confidence: {:.2}%", correction.confidence * 100.0);

Architecture

┌─────────────────────────────────────────────────────────────┐
│                     NQED Pipeline                           │
├─────────────────────────────────────────────────────────────┤
│                                                             │
│  Syndrome    ┌──────────────┐    ┌──────────────┐          │
│  Round ────► │ Syndrome→    │───►│ GNN Encoder  │          │
│              │ DetectorGraph│    │ (GraphRoPE)  │          │
│              └──────────────┘    └──────┬───────┘          │
│                                         │                   │
│                                         ▼                   │
│              ┌──────────────┐    ┌──────────────┐          │
│              │ Min-Cut      │───►│ Feature      │          │
│              │ Engine       │    │ Fusion       │          │
│              └──────────────┘    └──────┬───────┘          │
│                                         │                   │
│                                         ▼                   │
│                                  ┌──────────────┐  ┌──────┐│
│                                  │ Mamba        │─►│Corr- ││
│                                  │ Decoder      │  │ection││
│                                  └──────────────┘  └──────┘│
└─────────────────────────────────────────────────────────────┘

Module Overview

Module Description
graph Syndrome → DetectorGraph construction for surface codes
gnn Graph attention encoder with multi-head attention
mamba O(d²) state-space decoder with selective scan
fusion Feature fusion with min-cut structural signals
error Comprehensive error types

📖 Tutorial: Building a Custom Decoder

Step 1: Configure the Decoder

use ruqu_neural_decoder::{DecoderConfig, NeuralDecoder};

let config = DecoderConfig {
    distance: 7,              // Surface code distance
    embed_dim: 128,           // Node embedding dimension
    hidden_dim: 256,          // Hidden layer dimension
    num_gnn_layers: 4,        // Number of GNN layers
    num_heads: 8,             // Attention heads
    mamba_state_dim: 64,      // Mamba hidden state size
    use_mincut_fusion: true,  // Enable min-cut features
    dropout: 0.1,             // Training dropout rate
};

let mut decoder = NeuralDecoder::new(config);

Step 2: Build a Detector Graph Manually

use ruqu_neural_decoder::{GraphBuilder, NodeType};

// Create a d=3 surface code graph
let graph = GraphBuilder::new()
    .with_distance(3)
    .add_node(0, 0, NodeType::XStabilizer)?
    .add_node(0, 1, NodeType::ZStabilizer)?
    .add_node(1, 0, NodeType::ZStabilizer)?
    .add_node(1, 1, NodeType::XStabilizer)?
    .connect_grid()?  // Auto-connect adjacent stabilizers
    .build()?;

println!("Graph has {} nodes, {} edges", graph.num_nodes(), graph.num_edges());

Step 3: Process Multiple Syndrome Rounds

// Sequential decoding for time-series syndromes
let syndromes = vec![
    vec![false, true, false, false],   // Round 1
    vec![true, true, false, false],    // Round 2
    vec![true, false, false, false],   // Round 3
];

for (round, syndrome) in syndromes.iter().enumerate() {
    let correction = decoder.decode(syndrome)?;
    println!("Round {}: {} corrections, confidence {:.1}%",
        round,
        correction.x_corrections.len(),
        correction.confidence * 100.0
    );

    // Reset state between rounds if needed
    decoder.reset();
}

Step 4: Access Intermediate Representations

use ruqu_neural_decoder::GNNEncoder;

let gnn = GNNEncoder::new(gnn_config);
let graph = GraphBuilder::from_surface_code(5)
    .with_syndrome(&syndrome)?
    .build()?;

// Get node embeddings before Mamba decoding
let embeddings = gnn.encode(&graph)?;
println!("Embedding shape: {:?}", embeddings.shape());

// Get attention weights from last layer
let attention_weights = gnn.last_attention_weights();

🔬 Tutorial: Integrating with ruQu

Enable ruQu Integration

[dependencies]
ruvector-neural-decoder = { version = "0.1", features = ["ruqu-integration"] }

Use with QuantumFabric

use ruqu::{QuantumFabric, SyndromeRound};
use ruqu_neural_decoder::NeuralDecoder;

// Create fabric with neural decoder backend
let fabric = QuantumFabric::new()
    .with_neural_decoder(NeuralDecoder::new(config))?;

// Process syndrome cycle with coherence assessment
let syndrome_round = SyndromeRound::from_measurements(&measurements)?;
let decision = fabric.process_cycle_neural(&syndrome_round)?;

match decision.gate {
    GateDecision::Permit => apply_correction(decision.correction),
    GateDecision::Defer => request_human_review(),
    GateDecision::Deny => abort_computation(),
}

⚡ Performance Benchmarks

Benchmark Results (AMD Ryzen 9, 64GB RAM)

Operation d=5 d=7 d=11 Target
GNN Forward 2.8μs 4.8μs 9.8μs <100μs
Mamba Decode 1.2μs 2.1μs 3.9μs <50μs
Full Pipeline 4.5μs 7.2μs 14.1μs <150μs

vs Classical Decoders

Decoder d=11 Latency Accuracy (p=0.005)
MWPM 45μs 98.2%
Union-Find 12μs 97.8%
NQED 14μs 98.7%*

*Projected based on AlphaQubit scaling

Run Benchmarks

cargo bench --package ruvector-neural-decoder --bench neural_decoder_bench

🧪 Testing

Run All Tests

cargo test -p ruvector-neural-decoder

Test Categories

  • Unit tests: 61 tests covering all modules
  • Property tests: 14 proptest-based invariant checks
  • Integration tests: End-to-end pipeline validation

Key Test Coverage

Module Tests Coverage
graph 18 Graph construction, adjacency, syndrome mapping
gnn 16 Attention, normalization, forward pass
mamba 15 State updates, sequential decode, reset
fusion 12 Feature fusion, boundary computation

API Reference

Core Types

/// Decoder configuration
pub struct DecoderConfig {
    pub distance: usize,
    pub embed_dim: usize,
    pub hidden_dim: usize,
    pub num_gnn_layers: usize,
    pub num_heads: usize,
    pub mamba_state_dim: usize,
    pub use_mincut_fusion: bool,
    pub dropout: f32,
}

/// Correction output
pub struct Correction {
    pub x_corrections: Vec<usize>,  // Bit flip locations
    pub z_corrections: Vec<usize>,  // Phase flip locations
    pub confidence: f64,            // 0.0 to 1.0
    pub decode_time_ns: u64,        // Latency
}

Error Handling

All operations return Result<T, NeuralDecoderError>:

pub enum NeuralDecoderError {
    DimensionMismatch { expected: usize, got: usize },
    EmptyGraph,
    InvalidSyndrome(String),
    EncodingError(String),
    DecodingError(String),
}

References

  1. AlphaQubit: Neural decoders for quantum error correction
  2. Mamba: Linear-Time Sequence Modeling
  3. GNNs for Quantum Error Correction

License

Licensed under either of Apache License, Version 2.0 or MIT license at your option.

Commit count: 729

cargo fmt