ruvector/crates/ruvector-gnn-node
rUv 6c00b84e1d
feat(micro-hnsw-wasm): Add Neuromorphic HNSW v2.3 with SNN Integration (#40)
* docs: Add comprehensive GNN v2 implementation plans

Add 22 detailed planning documents for 19 advanced GNN features:

Tier 1 (Immediate - 3-6 months):
- GNN-Guided HNSW Routing (+25% QPS)
- Incremental Graph Learning/ATLAS (10-100x faster updates)
- Neuro-Symbolic Query Execution (hybrid neural + logical)

Tier 2 (Medium-Term - 6-12 months):
- Hyperbolic Embeddings (Poincaré ball model)
- Degree-Aware Adaptive Precision (2-4x memory reduction)
- Continuous-Time Dynamic GNN (concept drift detection)

Tier 3 (Research - 12+ months):
- Graph Condensation (10-100x smaller graphs)
- Native Sparse Attention (8-15x GPU speedup)
- Quantum-Inspired Attention (long-range dependencies)

Novel Innovations (10 experimental features):
- Gravitational Embedding Fields, Causal Attention Networks
- Topology-Aware Gradient Routing, Embedding Crystallization
- Semantic Holography, Entangled Subspace Attention
- Predictive Prefetch Attention, Morphological Attention
- Adversarial Robustness Layer, Consensus Attention

Includes comprehensive regression prevention strategy with:
- Feature flag system for safe rollout
- Performance baseline (186 tests + 6 search_v2 tests)
- Automated rollback mechanisms

Related to #38

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-Authored-By: Claude <noreply@anthropic.com>

* feat(micro-hnsw-wasm): Add neuromorphic HNSW v2.3 with SNN integration

## New Crate: micro-hnsw-wasm v2.3.0
- Published to crates.io: https://crates.io/crates/micro-hnsw-wasm
- 11.8KB WASM binary with 58 exported functions
- Neuromorphic vector search combining HNSW + Spiking Neural Networks

### Core Features
- HNSW graph-based approximate nearest neighbor search
- Multi-distance metrics: L2, Cosine, Dot product
- GNN extensions: typed nodes, edge weights, neighbor aggregation
- Multi-core sharding: 256 cores × 32 vectors = 8K total

### Spiking Neural Network (SNN)
- LIF (Leaky Integrate-and-Fire) neurons with membrane dynamics
- STDP (Spike-Timing Dependent Plasticity) learning
- Spike propagation through graph topology
- HNSW→SNN bridge for similarity-driven neural activation

### Novel Neuromorphic Features (v2.3)
- Spike-Timing Vector Encoding (rate-to-time conversion)
- Homeostatic Plasticity (self-stabilizing thresholds)
- Oscillatory Resonance (40Hz gamma synchronization)
- Winner-Take-All Circuits (competitive selection)
- Dendritic Computation (nonlinear branch integration)
- Temporal Pattern Recognition (spike history matching)
- Combined Neuromorphic Search pipeline

### Performance Optimizations
- 5.5x faster SNN tick (2,726ns → 499ns)
- 18% faster STDP learning
- Pre-computed reciprocal constants
- Division elimination in hot paths

### Documentation & Organization
- Reorganized docs into subdirectories (gnn/, implementation/, publishing/, status/)
- Added comprehensive README with badges, SEO, citations
- Added benchmark.js and test_wasm.js test suites
- Added DEEP_REVIEW.md with performance analysis
- Added Verilog RTL for ASIC synthesis

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-Authored-By: Claude <noreply@anthropic.com>

---------

Co-authored-by: Claude <noreply@anthropic.com>
2025-12-01 22:30:15 -05:00
..
.github/workflows feat: Add ruvector-gnn crate with GNN, compression, WASM and Node.js bindings 2025-11-26 04:50:36 +00:00
examples feat: Add ruvector-gnn crate with GNN, compression, WASM and Node.js bindings 2025-11-26 04:50:36 +00:00
npm feat(micro-hnsw-wasm): Add Neuromorphic HNSW v2.3 with SNN Integration (#40) 2025-12-01 22:30:15 -05:00
src fix(gnn-node): Use Float32Array for NAPI bindings to fix type conversion errors (#36) 2025-12-01 13:33:54 -05:00
test fix(gnn-node): Use Float32Array for NAPI bindings to fix type conversion errors (#36) 2025-12-01 13:33:54 -05:00
.npmignore feat: Add ruvector-gnn crate with GNN, compression, WASM and Node.js bindings 2025-11-26 04:50:36 +00:00
build.rs feat: Add ruvector-gnn crate with GNN, compression, WASM and Node.js bindings 2025-11-26 04:50:36 +00:00
Cargo.toml chore: Bump version to 0.1.15 with security fixes and GNN forgetting mitigation 2025-11-27 00:52:24 +00:00
package.json feat(micro-hnsw-wasm): Add Neuromorphic HNSW v2.3 with SNN Integration (#40) 2025-12-01 22:30:15 -05:00
README.md docs: Add CI badge to GNN README 2025-11-27 03:52:50 +00:00

@ruvector/gnn - Graph Neural Network Node.js Bindings

High-performance Graph Neural Network (GNN) capabilities for Ruvector, powered by Rust and NAPI-RS.

npm version CI

Features

  • GNN Layers: Multi-head attention, layer normalization, GRU cells
  • Tensor Compression: Adaptive compression with 5 levels (None, Half, PQ8, PQ4, Binary)
  • Differentiable Search: Soft attention-based search with temperature scaling
  • Hierarchical Processing: Multi-layer GNN forward pass
  • Zero-copy: Efficient data transfer between JavaScript and Rust
  • TypeScript Support: Full type definitions included

Installation

npm install @ruvector/gnn

Quick Start

Creating a GNN Layer

const { RuvectorLayer } = require('@ruvector/gnn');

// Create a GNN layer with:
// - Input dimension: 128
// - Hidden dimension: 256
// - Attention heads: 4
// - Dropout rate: 0.1
const layer = new RuvectorLayer(128, 256, 4, 0.1);

// Forward pass
const nodeEmbedding = new Array(128).fill(0).map(() => Math.random());
const neighborEmbeddings = [
  new Array(128).fill(0).map(() => Math.random()),
  new Array(128).fill(0).map(() => Math.random()),
];
const edgeWeights = [0.7, 0.3];

const output = layer.forward(nodeEmbedding, neighborEmbeddings, edgeWeights);
console.log('Output dimension:', output.length); // 256

Tensor Compression

const { TensorCompress, getCompressionLevel } = require('@ruvector/gnn');

const compressor = new TensorCompress();
const embedding = new Array(128).fill(0).map(() => Math.random());

// Adaptive compression based on access frequency
const accessFreq = 0.5; // 50% access rate
console.log('Selected level:', getCompressionLevel(accessFreq)); // "half"

const compressed = compressor.compress(embedding, accessFreq);
const decompressed = compressor.decompress(compressed);

console.log('Original size:', embedding.length);
console.log('Compression ratio:', compressed.length / JSON.stringify(embedding).length);

// Explicit compression level
const level = {
  level_type: 'pq8',
  subvectors: 8,
  centroids: 16
};
const compressedPQ = compressor.compressWithLevel(embedding, level);
const { differentiableSearch } = require('@ruvector/gnn');

const query = [1.0, 0.0, 0.0];
const candidates = [
  [1.0, 0.0, 0.0],  // Perfect match
  [0.9, 0.1, 0.0],  // Close match
  [0.0, 1.0, 0.0],  // Orthogonal
];

const result = differentiableSearch(query, candidates, 2, 1.0);
console.log('Top-2 indices:', result.indices);    // [0, 1]
console.log('Soft weights:', result.weights);     // [0.x, 0.y]

Hierarchical Forward Pass

const { hierarchicalForward, RuvectorLayer } = require('@ruvector/gnn');

const query = [1.0, 0.0];

// Layer embeddings (organized by HNSW layers)
const layerEmbeddings = [
  [[1.0, 0.0], [0.0, 1.0]],  // Layer 0 embeddings
];

// Create and serialize GNN layers
const layer1 = new RuvectorLayer(2, 2, 1, 0.0);
const layers = [layer1.toJson()];

// Hierarchical processing
const result = hierarchicalForward(query, layerEmbeddings, layers);
console.log('Final embedding:', result);

API Reference

RuvectorLayer

Constructor

new RuvectorLayer(
  inputDim: number,
  hiddenDim: number,
  heads: number,
  dropout: number
): RuvectorLayer

Methods

  • forward(nodeEmbedding: number[], neighborEmbeddings: number[][], edgeWeights: number[]): number[]
  • toJson(): string - Serialize layer to JSON
  • fromJson(json: string): RuvectorLayer - Deserialize layer from JSON

TensorCompress

Constructor

new TensorCompress(): TensorCompress

Methods

  • compress(embedding: number[], accessFreq: number): string - Adaptive compression
  • compressWithLevel(embedding: number[], level: CompressionLevelConfig): string - Explicit level
  • decompress(compressedJson: string): number[] - Decompress tensor

CompressionLevelConfig

interface CompressionLevelConfig {
  level_type: 'none' | 'half' | 'pq8' | 'pq4' | 'binary';
  scale?: number;           // For 'half'
  subvectors?: number;      // For 'pq8', 'pq4'
  centroids?: number;       // For 'pq8'
  outlier_threshold?: number; // For 'pq4'
  threshold?: number;       // For 'binary'
}

Search Functions

differentiableSearch

function differentiableSearch(
  query: number[],
  candidateEmbeddings: number[][],
  k: number,
  temperature: number
): { indices: number[], weights: number[] }

hierarchicalForward

function hierarchicalForward(
  query: number[],
  layerEmbeddings: number[][][],
  gnnLayersJson: string[]
): number[]

Utility Functions

getCompressionLevel

function getCompressionLevel(accessFreq: number): string

Returns the compression level that would be selected for the given access frequency:

  • accessFreq > 0.8: "none" (hot data)
  • accessFreq > 0.4: "half" (warm data)
  • accessFreq > 0.1: "pq8" (cool data)
  • accessFreq > 0.01: "pq4" (cold data)
  • accessFreq <= 0.01: "binary" (archive)

Compression Levels

None

Full precision, no compression. Best for frequently accessed data.

Half Precision

~50% space savings with minimal quality loss. Good for warm data.

PQ8 (8-bit Product Quantization)

~8x compression using 8-bit codes. Suitable for cool data.

PQ4 (4-bit Product Quantization)

~16x compression with outlier handling. For cold data.

Binary

~32x compression, values become +1/-1. For archival data.

Performance

  • Zero-copy operations where possible
  • SIMD optimizations for vector operations
  • Parallel processing with Rayon
  • Native performance with Rust backend

Building from Source

# Install dependencies
npm install

# Build debug
npm run build:debug

# Build release
npm run build

# Run tests
npm test

License

MIT - See LICENSE file for details

Contributing

Contributions are welcome! Please see the main Ruvector repository for guidelines.