repo
stringclasses
20 values
path
stringlengths
6
94
lang
stringclasses
5 values
n_chars
int64
81
200k
sha256
stringlengths
64
64
content
stringlengths
81
200k
eren23/synapse
synapse/crates/synapse-autograd/src/variable.rs
rs
1,138
b4a2ab18c85b9d038dcd16159cb2d5b41b10d920f55e72c5efbc83de8727ed42
use std::sync::atomic::{AtomicUsize, Ordering}; use crate::tensor::Tensor; pub type VariableId = usize; static NEXT_VARIABLE_ID: AtomicUsize = AtomicUsize::new(0); fn next_variable_id() -> VariableId { NEXT_VARIABLE_ID.fetch_add(1, Ordering::SeqCst) } /// A variable in the computation graph, wrapping a tensor ...
eren23/synapse
synapse/crates/synapse-autograd/src/tensor.rs
rs
18,430
e87d8048344a3c9b31a285ab36f311a4a8e6c2c728dc1661f88f67893fb18c4a
/// Lightweight f32 tensor for autograd operations. #[derive(Clone, Debug, PartialEq)] pub struct Tensor { pub data: Vec<f32>, pub shape: Vec<usize>, } impl Tensor { pub fn new(data: Vec<f32>, shape: Vec<usize>) -> Self { let expected: usize = shape.iter().product(); assert_eq!( ...
eren23/synapse
synapse/crates/synapse-autograd/src/backward.rs
rs
2,067
0f7e19fdeacbf88bb10a5eff231b20182afc01ab924dbfb658c523874ee11161
use std::collections::HashMap; use crate::graph::Graph; use crate::tensor::Tensor; use crate::variable::VariableId; /// Reverse-mode automatic differentiation. /// /// Walks the computation graph from `output_id` in reverse topological order, /// accumulating gradients. Fan-out is handled by summing gradients from al...
eren23/synapse
synapse/crates/synapse-autograd/src/grad_check.rs
rs
2,541
0cd44f2c215adacf95bdffbab0b63918b9efd0704758f1de6af453ae591d151f
use crate::backward::backward; use crate::graph::Graph; use crate::tensor::Tensor; use crate::variable::VariableId; /// Check analytical gradients against numerical gradients via central finite differences. /// /// `build_graph` builds a computation from input variables and returns the scalar output. /// Returns `true...
eren23/synapse
synapse/crates/synapse-autograd/src/ops/reshape.rs
rs
2,037
ea500a9e9db6256f1d5e9fc075bf1dfabe06fb2e07fe843aa5ea1ebbfad06b83
use crate::function::GradFn; use crate::graph::Graph; use crate::tensor::Tensor; use crate::variable::VariableId; // ── Reshape ──────────────────────────────────────────────────────── pub struct ReshapeBackward { input_ids: Vec<VariableId>, input_shape: Vec<usize>, } impl GradFn for ReshapeBackward { fn...
eren23/synapse
synapse/crates/synapse-autograd/src/ops/layernorm.rs
rs
6,792
1271f618a37c471f70b7ddbea6818a48dffd29c4c011fbc4203cbff2e4fd8360
use crate::function::GradFn; use crate::graph::Graph; use crate::tensor::Tensor; use crate::variable::VariableId; pub struct LayerNormBackward { input_ids: Vec<VariableId>, // [input, weight, bias] x_hat: Tensor, // normalized input, same shape as input rstd: Tensor, // reciproca...
eren23/synapse
synapse/crates/synapse-autograd/src/ops/reduce.rs
rs
5,118
7b688b31ccedf985cdbc6883157eb4c0749724a90a0455c5c8b944052a54f903
use crate::function::GradFn; use crate::graph::Graph; use crate::tensor::Tensor; use crate::variable::VariableId; // ── Sum all ──────────────────────────────────────────────────────── pub struct SumAllBackward { input_ids: Vec<VariableId>, input_shape: Vec<usize>, } impl GradFn for SumAllBackward { fn b...
eren23/synapse
synapse/crates/synapse-autograd/src/ops/batchnorm.rs
rs
3,615
cd28a0eef2bc6871f8f10651b9a3c619342a9fbdf8edeced9c384dd0347ab8b8
use crate::function::GradFn; use crate::graph::Graph; use crate::tensor::Tensor; use crate::variable::VariableId; pub struct BatchNormBackward { input_ids: Vec<VariableId>, // [input, gamma, beta] x_hat: Tensor, // normalized inv_std: Tensor, // [C] gamma_data: Tensor, /...
eren23/synapse
synapse/crates/synapse-autograd/src/ops/arithmetic.rs
rs
6,072
23d12876797824f626479fc2c450a1da7011fa64613c144b467af93b2024e6d4
use crate::function::GradFn; use crate::graph::Graph; use crate::tensor::Tensor; use crate::variable::VariableId; // ── Add (broadcasting) ───────────────────────────────────────────── pub struct AddBackward { input_ids: Vec<VariableId>, a_shape: Vec<usize>, b_shape: Vec<usize>, } impl GradFn for AddBack...
eren23/synapse
synapse/crates/synapse-autograd/src/ops/attention.rs
rs
9,804
1f807120140c67abe7c98d9575b1468d05ab6358c5357ae9881bda3904d92864
use crate::function::GradFn; use crate::graph::Graph; use crate::tensor::Tensor; use crate::variable::VariableId; // ── Scaled Dot-Product Attention ────────────────────────────────── pub struct ScaledDotProductAttentionBackward { input_ids: Vec<VariableId>, q_data: Tensor, // [B, H, Sq, D] k_data: ...
eren23/synapse
synapse/crates/synapse-autograd/src/ops/matmul.rs
rs
1,194
97a6b83808cba18634ea5d15821a8a6d4585ecbdbeb0a705c57f9da71cd2b7fc
use crate::function::GradFn; use crate::graph::Graph; use crate::tensor::Tensor; use crate::variable::VariableId; pub struct MatMulBackward { input_ids: Vec<VariableId>, a_data: Tensor, b_data: Tensor, } impl GradFn for MatMulBackward { fn backward(&self, grad_output: &Tensor) -> Vec<Option<Tensor>> {...
eren23/synapse
synapse/crates/synapse-autograd/src/ops/softmax.rs
rs
2,568
fc863c3b9d47e8e58ffc8a7471709e54e40c2055e2f231a4ae45aed57e52018c
use crate::function::GradFn; use crate::graph::Graph; use crate::tensor::Tensor; use crate::variable::VariableId; // ── Softmax ──────────────────────────────────────────────────────── pub struct SoftmaxBackward { input_ids: Vec<VariableId>, output_data: Tensor, axis: usize, } impl GradFn for SoftmaxBack...
eren23/synapse
synapse/crates/synapse-autograd/src/ops/mod.rs
rs
219
e727e5742f79486570fee780025c09926ba0766653eb3ec78a575c627f738c76
pub mod activation; pub mod arithmetic; pub mod attention; pub mod batchnorm; pub mod conv; pub mod layernorm; pub mod loss; pub mod matmul; pub mod pool; pub mod reduce; pub mod reshape; pub mod rope; pub mod softmax;
eren23/synapse
synapse/crates/synapse-autograd/src/ops/conv.rs
rs
7,990
dd6b4d361ba555275ba6730f1f4d9e2811c720628b80a1d8bfec8306076f0b79
use crate::function::GradFn; use crate::graph::Graph; use crate::tensor::Tensor; use crate::variable::VariableId; // ── im2col / col2im helpers ──────────────────────────────────────── fn im2col( input: &[f32], batch: usize, c: usize, h: usize, w: usize, kh: usize, kw: usize, stride: u...
eren23/synapse
synapse/crates/synapse-autograd/src/ops/pool.rs
rs
6,737
5bc654d2a3ac0356304359b6f7a1927076fef0c518669cd3b052371e4446cedd
use crate::function::GradFn; use crate::graph::Graph; use crate::tensor::Tensor; use crate::variable::VariableId; // ── MaxPool2d ────────────────────────────────────────────────────── pub struct MaxPool2dBackward { input_ids: Vec<VariableId>, max_indices: Vec<usize>, // flat indices into input for each outpu...
eren23/synapse
synapse/crates/synapse-autograd/src/ops/rope.rs
rs
7,350
5ab9a5733486e54c1576db0da46e47c9003539198b9b2f15dedf565da51b3043
use crate::function::GradFn; use crate::graph::Graph; use crate::tensor::Tensor; use crate::variable::VariableId; pub struct RoPEBackward { input_ids: Vec<VariableId>, // [input] cos_table: Tensor, // [S, D/2] sin_table: Tensor, // [S, D/2] } impl GradFn for RoPEBackward { fn backwar...
eren23/synapse
synapse/crates/synapse-autograd/src/ops/loss.rs
rs
3,534
24670ec4d7b819d58748162b388824322277fea706b7812e01395cbd6fa2f4c3
use crate::function::GradFn; use crate::graph::Graph; use crate::tensor::Tensor; use crate::variable::VariableId; // ── MSE Loss ─────────────────────────────────────────────────────── pub struct MseLossBackward { input_ids: Vec<VariableId>, pred_data: Tensor, target_data: Tensor, } impl GradFn for MseLo...
eren23/synapse
synapse/crates/synapse-autograd/src/ops/activation.rs
rs
4,917
2b12d4f97baabe4f76602634ba7c9b6ddda0a51846a6a2e760184e5b4d315591
use crate::function::GradFn; use crate::graph::Graph; use crate::tensor::Tensor; use crate::variable::VariableId; // ── ReLU ─────────────────────────────────────────────────────────── pub struct ReluBackward { input_ids: Vec<VariableId>, input_data: Tensor, } impl GradFn for ReluBackward { fn backward(&...
eren23/synapse
synapse/crates/synapse-optim/src/sgd.rs
rs
9,895
d211f9f545359ec3ed131e3e684e3c757b6ab43ecb534301d676862d4ce85920
use std::collections::HashMap; use crate::optimizer::{Optimizer, Param, ParamGroup, StateDict}; /// Stochastic Gradient Descent with optional momentum, dampening, weight decay, /// and Nesterov acceleration. /// /// Matches PyTorch's `torch.optim.SGD` semantics exactly. pub struct SGD { pub lr: f32, pub momen...
eren23/synapse
synapse/crates/synapse-optim/src/lib.rs
rs
4,211
5dcdff73e66b19ebc265a48e22516f2e1547d68c7a2433bbad5c1901a9b148cb
pub mod adam; pub mod grad_clip; pub mod lr_scheduler; pub mod optimizer; pub mod rmsprop; pub mod sgd; pub use adam::{adamw, Adam}; pub use grad_clip::{clip_grad_norm_, clip_grad_value_}; pub use lr_scheduler::{CosineAnnealingLR, LinearWarmup, ReduceLROnPlateau, StepLR}; pub use optimizer::{Optimizer, Param, ParamGro...
eren23/synapse
synapse/crates/synapse-optim/src/lr_scheduler.rs
rs
9,715
01dfbda074c6f57c0ac1f28b03f53ba050ab8d61080ac356d28af32c79fdc834
use std::f32::consts::PI; /// Learning rate scheduler that decays the LR by `gamma` every `step_size` epochs. /// /// Matches PyTorch's `torch.optim.lr_scheduler.StepLR`. pub struct StepLR { pub base_lr: f32, pub step_size: usize, pub gamma: f32, epoch: usize, } impl StepLR { pub fn new(base_lr: f...
eren23/synapse
synapse/crates/synapse-optim/src/rmsprop.rs
rs
10,252
dd119df59dbf7cdb80f607261b28643eba3d1d72a8c448ab07e0de4c66441e5d
use std::collections::HashMap; use crate::optimizer::{Optimizer, Param, ParamGroup, StateDict}; /// Per-parameter RMSProp state. #[derive(Clone, Debug)] struct RMSPropState { square_avg: Vec<f32>, grad_avg: Option<Vec<f32>>, momentum_buffer: Option<Vec<f32>>, } /// RMSProp optimizer with optional centeri...
eren23/synapse
synapse/crates/synapse-optim/src/grad_clip.rs
rs
6,401
29409abad209d151798a5fc15e76c5a278575260c4c20b60a49c8778d948d233
use crate::optimizer::Param; /// Clips gradient of a set of parameters by total norm in-place. /// /// Returns the total norm of all gradients before clipping. /// /// Matches PyTorch's `torch.nn.utils.clip_grad_norm_` semantics: /// - Computes the total L2 norm of all gradients concatenated /// - If total_norm > max_...
eren23/synapse
synapse/crates/synapse-optim/src/adam.rs
rs
13,377
c1e156c12320084b70f34b2ad0001637f543e6abcca6c26eb56be4ef9495b9d6
use std::collections::HashMap; use crate::optimizer::{Optimizer, Param, ParamGroup, StateDict}; /// Per-parameter Adam state. #[derive(Clone, Debug)] struct AdamState { step: usize, /// First moment estimate (m). exp_avg: Vec<f32>, /// Second moment estimate (v). exp_avg_sq: Vec<f32>, } /// Adam ...
eren23/synapse
synapse/crates/synapse-optim/src/optimizer.rs
rs
2,242
ad5a0ac92136952576960009120e66230a180b2599b4014379808ddbc5fe704c
use std::collections::HashMap; /// A trainable parameter holding data and an optional gradient. /// /// Optimizers read `.grad` and update `.data` in-place during `step()`. #[derive(Clone, Debug)] pub struct Param { pub data: Vec<f32>, pub grad: Option<Vec<f32>>, } impl Param { pub fn new(data: Vec<f32>) ...
eren23/synapse
synapse/web/pusht_server.py
py
11,025
c392afa19fc2322e442ffbf4292c0cde5d82e0d86f4c997a6e16eacd0ad199da
#!/usr/bin/env python3 """ PushT Physics Server β€” matches Diffusion Policy's PushT env EXACTLY. Reference: github.com/real-stanford/diffusion_policy/blob/main/diffusion_policy/env/pusht/pusht_env.py """ import json import math import os import sys from http.server import HTTPServer, SimpleHTTPRequestHandler import p...
eren23/synapse
synapse/web/extract_demos.py
py
2,146
6a4388abaa7702f217dbb0a7bdea7a8100123335643fa556d977e81c493e3352
#!/usr/bin/env python3 """Extract real PushT expert demonstrations from lerobot/pusht on HuggingFace.""" import json import os from huggingface_hub import hf_hub_download import pyarrow.parquet as pq import numpy as np OUT_DIR = os.path.join(os.path.dirname(__file__), "trajectories") os.makedirs(OUT_DIR, exist_ok=Tr...
eren23/synapse
synapse/tests/integration/kvcache_decode.rs
rs
11,777
7b8778f5782fd2e6768cf9913e3d2b17cef7972e8eda9670e88a3a4281dba6c3
//! KV-cache decode correctness: verify that KV-cache-based generation produces //! identical output to full-recompute generation, with K/V value validation //! and tests across varying prompt lengths. //! //! Test cases: //! 1. Generate 20 tokens via cached (forward_prefill + forward_one) vs //! full-recompute (for...
eren23/synapse
synapse/tests/integration/multi_model_validation.rs
rs
25,124
83da8ae3851397926ba89845d90f630e0776e8d8618c9f26e17fe8cb0ca78cbf
//! Multi-architecture model validation tests. //! //! Verifies that all supported model architectures (Qwen3, LLaMA, Mistral, Phi, Gemma, ViT) //! produce correct forward pass results with fake weights. Tests cover: //! - Forward pass producing finite logits with correct shape //! - Cached decode (prefill + forward_on...
eren23/synapse
synapse/tests/integration/attention_correctness.rs
rs
7,825
ec9bba483c2326eef34538844b74e49fd09d102f0b5f35574cac63c0dad67444
//! Gradient correctness for the full MultiHeadAttention module. //! //! Implements the complete MHA forward pass (Q/K/V/O projections, split heads, //! scaled dot-product attention, concat heads) through the autograd graph and //! verifies analytical gradients against numerical (central finite differences) //! for eve...
eren23/synapse
synapse/tests/integration/rwkv_hf_validation.rs
rs
5,313
85ea00c13b3e3235194b809da82baeea5c31cc21c7147f01cedafa7270fbc26d
//! Real-weight validation for RWKV-7 models against HuggingFace reference. //! //! These tests are `#[ignore]` by default β€” they require a downloaded model. //! //! To run: //! 1. Download: `huggingface-cli download RWKV/RWKV7-Goose-0.1B-HF` //! 2. Generate: `cd scripts/reference && python generate_rwkv_reference....
eren23/synapse
synapse/tests/integration/hybrid_validation.rs
rs
7,321
22318f77f4a50073869755269758bea2959b3b10ff60d1fccda95e8b3614e9bb
//! Integration tests for HybridModel (Qwen3.5-style DeltaNet + GQA). use synapse_inference::models::Model; use synapse_inference::models::{ DeltaNetDecoderLayer, GqaDecoderLayer, HybridConfig, HybridLayer, HybridModel, }; fn pseudo_random_vec(seed: u64, len: usize) -> Vec<f32> { let mut state = seed; (0....
eren23/synapse
synapse/tests/integration/quantization_accuracy.rs
rs
6,470
7866ded4aa6239c0878756f9c42e602a39a92d942d928f05d4d79ff089d32d94
//! Quantization accuracy test: INT8 vs f32 logits comparison. //! Top-1 agreement must be >= 99% across multiple input sequences. use synapse_inference::config::*; use synapse_inference::models::ModelBuilder; use synapse_inference::quantization::{quantize_model, QuantizedCausalLM}; use synapse_inference::weight_loadi...
eren23/synapse
synapse/tests/integration/code_wm_golden.rs
rs
18,954
26b72ff25e9c1e27da1f40ee38f60877aefdebc6a392fdd9a5cff9fbd0641b1b
//! Zero-drift validation: compare Synapse's Rust CodeWorldModel against a //! PyTorch reference dump stage-by-stage. //! //! Tier-1 tolerance: cosine β‰₯ 0.99999, max_abs < 1e-5 at every intermediate. //! If any stage fails, the first failing stage pinpoints the drifting kernel. //! //! Prerequisites (produced by `scrip...
eren23/synapse
synapse/tests/integration/mnist_e2e.rs
rs
7,310
7772a9a524bea66f2cfaea55c0dddb309fc77a485ac4e57d671a8d05de682cd4
//! End-to-end MNIST test: Train MLP for 3 epochs, verify accuracy > 90%. use synapse_autograd::{backward, Graph, NoGradGuard, Tensor}; use synapse_nn::init::kaiming_uniform; use synapse_optim::{Adam, Optimizer, Param}; use synapse_train::{TrainLoop, Trainer, TrainerConfig}; use rand::rngs::StdRng; use rand::{Rng, Se...
eren23/synapse
synapse/tests/integration/rwkv_validation.rs
rs
5,863
4ef9cbd7a538729a086c0f034516c4ee926ccd3c545154478410601baa525b3f
//! Integration tests for RwkvModel using the public API. use synapse_inference::models::Model; use synapse_inference::models::{RwkvBlock, RwkvConfig, RwkvModel}; fn pseudo_random_vec(seed: u64, len: usize) -> Vec<f32> { let mut state = seed; (0..len) .map(|_| { state = state ...
eren23/synapse
synapse/tests/integration/mamba_validation.rs
rs
5,268
e6fc09de278120b6b08e6ff5ba75ada13e507291d6f290709e3d6469a6781510
//! Integration tests for MambaModel using the public API. use synapse_inference::models::Model; use synapse_inference::models::{MambaBlock, MambaConfig, MambaModel}; fn pseudo_random_vec(seed: u64, len: usize) -> Vec<f32> { let mut state = seed; (0..len) .map(|_| { state = state ...
eren23/synapse
synapse/tests/integration/diffusion_validation.rs
rs
6,505
7c160ea828591d0ccf0c6988bffea5161b3171e01d4a20febd6a1d9ef93e9aa8
//! Integration tests for the Diffusion LLM module. //! //! These tests validate the end-to-end denoising generation pipeline //! using a tiny model with random weights. use synapse_inference::diffusion::{DiffusionLLMConfig, DiffusionModel, MaskSchedule}; use synapse_inference::diffusion::schedule::{tokens_per_step, u...
eren23/synapse
synapse/tests/integration/mamba_hf_validation.rs
rs
6,412
097c3307858be48077f9591cebae19853ff895f000106e5a015ccdebb147fbfb
//! Real-weight validation for Mamba models against HuggingFace reference. //! //! These tests are `#[ignore]` by default β€” they require a downloaded model. //! //! To run: //! 1. Download the model: `huggingface-cli download state-spaces/mamba-130m` //! 2. Generate reference: `cd scripts/reference && python genera...
eren23/synapse
synapse/tests/integration/transformer_e2e.rs
rs
7,890
c2d4453cedb2e82b06327da89e8e04cd022fce102fc662a3f2336634e7450147
//! End-to-end transformer test: Train 4-layer encoder on synthetic sequence //! classification. Must reach >85% accuracy in 5 epochs. //! //! Architecture: Embedding(500, 64) β†’ SinusoidalPE β†’ TransformerEncoder(4L, d=64, 4H, ff=256) //! β†’ MeanPool1d β†’ Linear(64, NUM_CLASSES) //! Only the classification hea...
eren23/synapse
synapse/tests/integration/graph_optimization.rs
rs
21,672
39aaa15ac2bba7f29723ce26270797f5e3f2867607345f241561ba55d8b45e90
use std::collections::HashMap; use std::time::Instant; use synapse_graph::*; // ── Fusion Tests ──────────────────────────────────────────────────────── #[test] fn test_matmul_bias_relu_fusion_reduces_nodes() { let mut g = Graph::new(); let a = g.add_node( NodeKind::Input("a".into()), vec![],...
eren23/synapse
synapse/tests/integration/inference_e2e.rs
rs
8,514
31436da3ff2b4fb1004d3ed5a1fbbe2552b19f2e9b79a1ccb3e15b5f7d50be62
//! E2E inference test: Build Qwen3-architecture model, generate 50 tokens greedy, //! verify coherent output (deterministic, valid tokens, top-1 self-agreement >= 95%). use std::collections::HashMap; use synapse_inference::config::*; use synapse_inference::generation::{GenerationConfig, GenerationPipeline}; use syna...
eren23/synapse
synapse/tests/integration/kvcache_correctness.rs
rs
10,103
ee1f90b8ddd53e4824a442d6bf82fa35e178f4911272a910a5f7d1f273e5ac4b
//! KV-cache correctness test: verify that incremental (decode-step) forward passes //! produce bit-exact results compared to full-context forward passes. //! //! Since the current engine recomputes the full context on each decode step //! (no KV-cache optimization yet), this test verifies the fundamental invariant: //...
eren23/synapse
synapse/tests/integration/reference_correctness.rs
rs
16,855
77dbb5ff18194f96f4c99e633a2094244fc340276ef55cacde0d09cf1b3870e3
//! Reference correctness tests for Synapse SSM kernels. //! //! Each test uses hand-computed expected values with tight tolerances to //! verify mathematical correctness of the kernel implementations. use synapse_inference::models::{ deltanet_step, selective_scan_seq, wkv7_step, MambaBlock, MambaConfig, MambaMode...
eren23/synapse
synapse/tests/integration/config_driven_assembly.rs
rs
5,478
e33ad32ac75edbdc17ce309ad86c2a1dc3bc6e4e8fcb607293f9bdd04baa4bf5
//! Config-driven assembly test: Qwen3 + LLaMA configs build different architectures //! from the same engine. Assembly must complete in <= 2 seconds. use std::time::Instant; use synapse_inference::config::*; use synapse_inference::models::ModelBuilder; const QWEN3_JSON: &str = include_str!("../../configs/qwen3_0.6b...
eren23/synapse
synapse/tests/integration/transformer_graph_opt.rs
rs
15,762
09e2949824ff36f0754c068eda199f5a611c9f2129e0fbabf2b09259fa6ec349
//! Graph optimization tests for transformer fusion passes. //! //! Builds transformer computation graphs, applies FuseAttention and //! FuseLayerNormResidual passes, and verifies: //! 1. Fused output matches unfused output within 1e-4 //! 2. Attention fusion speedup >= 1.3x vs unfused //! 3. LayerNorm+residual fusion ...
eren23/synapse
synapse/tests/benchmarks/matmul_bench.rs
rs
2,045
3205ab06c112ce01069476ad06df2e813f672afb9e6370bd80b0fd4d3b80c40b
//! Matrix multiplication benchmark at various sizes. use std::time::Instant; use synapse_autograd::Tensor; fn bench_matmul(m: usize, k: usize, n: usize, iterations: usize) -> f64 { let a_data: Vec<f32> = (0..m * k).map(|i| (i as f32 * 0.001).sin()).collect(); let b_data: Vec<f32> = (0..k * n).map(|i| (i as f...
eren23/synapse
synapse/tests/benchmarks/inference_throughput.rs
rs
5,694
da1490f5e7971c3541a0117f67bff3667bba21e6ed34d7342a9e736f2d14aacf
//! Inference throughput benchmark: measure decode tokens/sec for f32 and INT8. //! //! Thresholds: //! - f32 decode: >= 20 tok/s (debug: >= 4 tok/s) //! - INT8 decode: >= 35 tok/s (debug: >= 7 tok/s) use std::time::Instant; use synapse_inference::config::*; use synapse_inference::generation::{GenerationConfig, Gener...
eren23/synapse
synapse/tests/benchmarks/quantization_speedup.rs
rs
10,479
9725d54c734ff914c64796d6f647d9bff5c11b6af1d041b35cc516fb02893fcd
//! Quantization speedup benchmark: compare INT8 vs f32 throughput. //! Reports the speedup ratio and verifies both produce valid output. use std::time::Instant; use synapse_inference::config::*; use synapse_inference::models::ModelBuilder; use synapse_inference::quantization::quantize_model; use synapse_inference::w...
eren23/synapse
synapse/tests/benchmarks/simd_vs_naive.rs
rs
17,439
87b4bc799d2ee954bc633a546e3ce0c97becbb3a4a7ed75e5c5335fb46dc7461
//! SIMD vs naive throughput benchmark: measures speedup from wiring Zig SIMD kernels. //! //! Thresholds (release mode): //! - SGEMM [1024,1024]Γ—[1024,3072]: SIMD >= 4Γ— naive //! - RMSNorm [1,1024]: SIMD >= 4Γ— naive //! - SwiGLU [1,3072]: SIMD >= 2Γ— naive //! - Decoder layer end-to-end: ...
eren23/synapse
synapse/tests/benchmarks/kvcache_speedup.rs
rs
7,529
bfd5cdcd8d085711832bf1d8cae5c500c6593256fbbcb1dd871828198b6b06d2
//! KV-cache decode speedup benchmark. //! //! Thresholds: //! - Cached decode >= 10Γ— faster than full-recompute at 64 generated tokens //! (debug: >= 2Γ—) //! - KV-cache memory <= 50 MB for Qwen3-0.6B at 2048 ctx use std::collections::HashMap; use std::time::Instant; use synapse_inference::config::*; use synapse_in...
eren23/synapse
synapse/tests/benchmarks/memory_bench.rs
rs
3,642
a95134e7d2e36bfd8d06c74492d3d58578ed9d821392617a4005780dcb0b3ec3
//! Memory benchmark: verify training completes without excessive allocation. use synapse_autograd::{backward, Graph, Tensor}; use synapse_nn::init::kaiming_uniform; use synapse_optim::{Adam, Optimizer, Param}; #[test] fn memory_bench_mlp_training() { let input_dim = 256; let hidden = 128; let output = 10...
eren23/synapse
synapse/tests/benchmarks/attention_bench.rs
rs
7,215
becc60daf3e470f995bf68afb4f1e355160442da8cecb021b8a5ce8b49ac2e23
//! Attention benchmark: fused vs naive attention throughput through Rust+FFI layer. //! Target: fused >= 2x vs naive. //! //! Benchmarks the graph IR interpreter executing a FusedAttention node vs the //! unfused subgraph (Q/K/V projections, transpose, matmul, scale, softmax, //! attend, output projection). use std::...
eren23/synapse
synapse/tests/benchmarks/prefill_throughput.rs
rs
6,313
98c6cfb37aa99d23212a2089fbf56d05e2615307d9458a7f3df03d1ba3016ad0
//! Prefill throughput benchmark: measure tokens/sec during the prefill phase //! (single forward pass over the full prompt). //! //! Threshold: >= 500 tok/s (Qwen3 architecture, f32). //! Debug mode: >= 100 tok/s (~5x lower). use std::collections::HashMap; use std::time::Instant; use synapse_inference::config::*; us...
eren23/synapse
synapse/tests/benchmarks/training_throughput.rs
rs
4,916
fbeb980f86cbf4f9afee9da3403d01e844cb7ac9ac5dd4b1b74ae1e3bc3c2aeb
//! Training throughput benchmark: MLP (256-128-10), batch 64. //! Target: >= 5000 samples/sec. use std::time::Instant; use synapse_autograd::{backward, Graph, Tensor}; use synapse_nn::init::kaiming_uniform; use synapse_optim::{Adam, Optimizer, Param}; const INPUT_DIM: usize = 256; const HIDDEN: usize = 128; const O...
eren23/synapse
synapse/tests/benchmarks/memory_usage.rs
rs
7,527
0e709271b6db95fcadd9e654463dcbe03fce5897e89e7d9be3899df24d21f99c
//! Memory usage benchmark: verify Qwen3-0.6B model weight footprint. //! //! Thresholds: //! - f32: <= 3 GB //! - INT8: <= 1.5 GB use synapse_inference::config::*; use synapse_inference::weight_loading::AlignedBuffer; const QWEN3_JSON: &str = include_str!("../../configs/qwen3_0.6b.json"); /// Compute f32 memory foo...
eren23/synapse
synapse/tests/benchmarks/transformer_throughput.rs
rs
6,029
7598bfdb2d7735c72f85b412c4a0a0d23b37be95d82ae3d8f5db500e7516ed93
//! Transformer training throughput benchmark. //! //! End-to-end: 4-layer encoder, d=256, seq=128, batch=32. //! Measures tokens/sec through frozen backbone + trained classification head. //! Target: >= 2000 tokens/sec (release) / >= 200 tokens/sec (debug). use std::time::Instant; use synapse_autograd::{backward, Gr...
eren23/synapse
synapse/fpga/run_lewm_sim.py
py
19,386
a90c4d2808806d042d1e7883015e7219197efcbdf8868642837fa2b621ad1cef
#!/usr/bin/env python3 """ Full LeWM Predictor Simulation via Shift-Add Path. LeWM: "LeWorldModel" by Maes, Le Lidec, Scieur, LeCun, Balestriero (Mila, NYU, Samsung SAIL, Brown) β€” https://le-wm.github.io/ Runs the complete 6-layer Q4 predictor transformer using shift-add decomposition instead of multiply β€” proving th...
eren23/synapse
synapse/fpga/shift_add_proof.py
py
23,812
5b93207c472ebd33b6c4d4706111199173e961f0996d962cb7cde9c3d426d7fa
#!/usr/bin/env python3 """ Shift-and-Add Proof of Concept for Hardwired Q4 LEWM Weights. Reads an LQ40 binary (exported by Synapse's export_lewm_q4), extracts Q4 predictor layers, and proves that shift-and-add decomposition produces bit-equivalent results to standard dequant-multiply. This is Phase 1 of the hardwired...
eren23/synapse
synapse/fpga/sim/run_sim.py
py
8,662
dacd6367fb4b3a3eda73f485a1999ccf3e4e1f66ae566b28100eecc653f9a4f3
#!/usr/bin/env python3 """ Verilator cycle-accurate simulation of hardwired Q4 linear layers. Compiles generated Verilog to C++ via Verilator, drives test vectors, and validates against golden references. Reports cycle counts and theoretical latency at target clock frequencies. Usage: python run_sim.py --rtlil .....
eren23/synapse
synapse/fpga/sim/golden_vectors.py
py
6,038
a4d28175765bfb7c066cef6d4b94070b2def0c42ffec1491affe51155eebe345
#!/usr/bin/env python3 """ Generate golden test vectors for Verilator simulation. Produces input/output numpy arrays by running the Python Q4 forward pass. These become the validation dataset for cycle-accurate RTL simulation. Usage: python golden_vectors.py --bin ../../web/lewm-compress-demo/lewm-q4-pred.bin \ ...
eren23/synapse
synapse/fpga/amaranth/nonlinear.py
py
18,209
5a98e10e07ab43c8a209953bf3a794d788e6daf9aeb61ffd4ea72fa10f17a3c1
""" Non-linear operations for hardwired LEWM inference in RTL. Implements fixed-point versions of: - GELU activation (piecewise linear approximation) - LayerNorm (mean, variance, reciprocal sqrt via Newton-Raphson) - Softmax over 3 elements (exp LUT + reciprocal) - adaLN modulation: normed * (1 + scale) + shif...
eren23/synapse
synapse/fpga/amaranth/gen_from_lq40.py
py
9,685
549dca8a1b0ddab6c1d4aa7aa85b82193238b954a4537e7df47034ac3d576d87
#!/usr/bin/env python3 """ Generate synthesizable Verilog from LQ40 Q4 weights. Reads a real LEWM Q4 binary, extracts a specific weight matrix, and generates Amaranth HDL modules with the weights hardwired as shift-add trees. For the proof-of-concept, we target a single Q4 linear layer (e.g. the adaln_linear [192->11...
eren23/synapse
synapse/fpga/amaranth/testbench.py
py
5,719
13e5d40dcaaf9358a1966dd21cb9650a70c6f35c248f51423f7907ab588a7ec8
#!/usr/bin/env python3 """ Amaranth simulation testbench for hardwired Q4 linear layers. Uses Amaranth's built-in simulator to verify that the generated RTL produces the same results as the Python Q4 forward pass. Usage: python testbench.py --bin ../../web/lewm-compress-demo/lewm-q4-pred.bin \ --layer 0 -...
eren23/synapse
synapse/fpga/amaranth/q4_shift_add_mac.py
py
10,690
41f6a00cb8c3344c6d6277a8a399075697700898e634158e7f63a347ebf65343
""" Q4 Shift-and-Add MAC Unit for FPGA. A single Q4 block MAC computes the dot product of 32 input activations with 32 hardwired 4-bit weights using only shifts and adds β€” no multipliers. The weights are baked into the combinational logic at generation time. Each weight value (-8 to 7) becomes a fixed shift-add tree....
eren23/synapse
synapse/fpga/amaranth/adaln_layer.py
py
13,692
02579250288e976e623607a94265213e6c4375326d47113fdafa29c952534d06
#!/usr/bin/env python3 """ Full adaLN Transformer Layer with hardwired Q4 weights. Wires together all components into a complete LEWM predictor layer: conditioning β†’ adaln_linear[192β†’1152] β†’ split 6Γ—192 (scale1,shift1,gate1,scale2,shift2,gate2) x[3Γ—192] β†’ LayerNorm β†’ modulate(scale1,shift1) β†’ to_qkv[192β†’3072] ...
eren23/synapse
synapse/examples/mamba_generate.rs
rs
7,010
aa5a5c05d667a6357454ad78377979b22a2e26724b4594ec010f379ea499aacd
//! Text completion with a Mamba checkpoint. //! //! Usage: //! cargo run --example mamba_generate --release -- --model-dir models/mamba-130m --prompt "The capital of France is" //! cargo run --example mamba_generate --release -- --model-dir models/mamba-130m --prompt "Once upon a time" --max-tokens 100 //! cargo...
eren23/synapse
synapse/examples/code_wm_metal_bench.rs
rs
5,968
b70d4ebcdeffad6911057dd747621aa7cff320c69fd76ab2ecfc2c4f4521943b
//! Benchmark: Metal GPU vs CPU (sequential + fused Zig) for CodeWM encoder. //! //! Usage: //! cargo run --release --features metal --example code_wm_metal_bench -- \ //! models/code_wm/vicreg_promotion.safetensors \ //! configs/code_wm_vicreg_promotion.json \ //! tests/fixtures/code_wm_reference_v...
eren23/synapse
synapse/examples/bench_lewm_quantized.rs
rs
5,194
b6a30ed30a8c8ad7280688baf160e6fc4b9fef393034bb9bee8e2c73edc4d931
//! Benchmark: f32 vs FullyQuantized LEWM inference on hybrid ALAL. //! //! Usage: cargo run -p synapse --release --example bench_lewm_quantized -- /tmp/lewm-64d-variants/hybrid_alal use std::path::Path; use std::time::Instant; use synapse_inference::models::{LeWMConfig, LeWorldModel}; use synapse_inference::models::...
eren23/synapse
synapse/examples/code_wm_demo.rs
rs
5,602
8b07ed0bc75cd2e623444fe49d564f1baa1f5ba579762bb3da38dab52883887e
//! Code WM end-to-end demo: load weights, encode tokens, predict next latent. //! //! Usage: //! cargo run --release --example code_wm_demo -- \ //! models/code_wm/g8.safetensors \ //! configs/code_wm_g8.json \ //! [tests/fixtures/code_wm_reference_g8.safetensors] //! //! If a reference dump path i...
eren23/synapse
synapse/examples/code_wm_edit_pairs.rs
rs
6,125
cfeb9175a40b7868b702db8605084d718b12745b0cfa1ed6c7274a273d707337
//! Before/after edit similarity test for Code WM. //! //! Code WM was trained on CommitPackFT edits (before→after + action). For each //! pair, we encode both snippets and check that cos(before, after) is high //! (pairs cluster tighter than random snippets). //! //! Metrics: //! pair_cos — cos(before_i, after_i)...
eren23/synapse
synapse/examples/code_wm_corpus_retrieve.rs
rs
5,155
e5be1a490a1c4c7780b64295f839f851662a2e72c95e668c45376795caa83b75
//! Real-world retrieval analysis on a large Python corpus. //! //! Loads a pre-tokenized file index (from scripts/build_file_index.py), //! encodes every file with Code WM, and finds top-k nearest neighbors. //! Prints qualitative examples + summary statistics. //! //! Usage: //! cargo run --release --example code_w...
eren23/synapse
synapse/examples/code_wm_calibration_compare.rs
rs
4,043
a09dacc3c8678a1faa01e2d716868f0475ed401cf84962072bf1d38f1a930ccb
//! Compare INT8 calibration strategies: MinMax vs Percentile(99.5) vs Percentile(99.9). //! //! G1b (VICReg-trained) has wider weight distributions where MinMax over-scales //! due to outliers. Percentile clipping typically recovers 0.0001-0.001 cos. //! //! Usage: //! cargo run --release --example code_wm_calibrati...
eren23/synapse
synapse/examples/lewm_compare_variants.rs
rs
7,264
32aca295e043c7a78f68120749f62329839ce9d9c06dcd75240c7570a898b11a
//! Compare LEWM slim variant checkpoints side-by-side. //! //! Loads multiple safetensors+config pairs, runs f32 encode+rollout on the same //! test image and actions, then prints a cosine-similarity matrix. //! //! Usage: //! cargo run -p synapse --release --example lewm_compare_variants -- \ //! /tmp/lewm-64d-...
eren23/synapse
synapse/examples/model_surgeon.rs
rs
8,732
37a92a2f2da6e764ab4c805ef4046405da71b70014677295a611835c9c5b08a8
//! Model Surgeon: analyze, prune, and compress SSM models. //! //! Usage: //! # Analyze layer sensitivity //! cargo run --example model_surgeon --release -- --model-dir models/mamba-130m --analyze //! //! # Prune layers + Wanda + quantize to Q4 //! cargo run --example model_surgeon --release -- --model-dir mod...
eren23/synapse
synapse/examples/vision_transformer.rs
rs
9,584
96d394c907fc9c087437e149274eb083cef9091b88d1f1bf24356a429fc181fa
//! Vision Transformer (ViT) on synthetic CIFAR-10-like data. //! //! Pipeline: Conv2d(3, d_model, patch_size) β†’ reshape patches β†’ SinusoidalPositionalEncoding //! β†’ TransformerEncoder(2 layers) β†’ MeanPool1d β†’ Linear(d_model, num_classes) //! Uses a manual training loop with Adam optimizer. use synapse_autogra...
eren23/synapse
synapse/examples/export_mamba_int8.rs
rs
4,417
a729f20d86d67c75db63272fd46feeaecfc56334ee404595003d57ec62de9057
//! Export a Mamba model as a compact INT8 binary for WASM. //! //! Usage: //! cargo run --example export_mamba_int8 --release -- --model-dir models/mamba-130m --output web/ssm-demo/mamba-130m-int8.bin //! //! The output file contains: //! - 4 bytes: magic "SMI8" //! - JSON config (length-prefixed) //! - Binary...
eren23/synapse
synapse/examples/lewm_demo.rs
rs
5,352
345c3806e5576c116dedcfc268fdfad998c55811dd042e47e493783e9944eedb
//! LeWorldModel (LeWM) Demo //! //! Loads the PushT checkpoint and runs encode + rollout. //! //! Usage: //! cargo run --release --example lewm_demo //! //! Requires the checkpoint at /tmp/lewm-pusht/pusht/lejepa_weights.safetensors use std::path::Path; use std::time::Instant; use synapse_inference::models::{LeWMC...
eren23/synapse
synapse/examples/code_wm_fused_bench.rs
rs
3,492
e801e86820c26bfdc96689f7fd0ef6d6e2e40b0a1dab64dde8a62d284eb273f2
//! Benchmark + zero-drift verification for the fused Code WM encoder. //! //! Compares sequential encoder vs fused Zig kernel on the same golden input, //! measures latency delta, and verifies byte-level agreement. //! //! Usage: //! cargo run --release --example code_wm_fused_bench -- \ //! models/code_wm/g8....
eren23/synapse
synapse/examples/code_wm_retrieve.rs
rs
4,115
930a058cd86f5021d1af5eed1e9fb132ff8c7e0846415058b4ef932ba52f2d91
//! Code WM retrieval demo: semantic code similarity via AST embeddings. //! //! Loads a tokenized corpus (produced by scripts/tokenize_code_dir.py), //! encodes each file with Code WM, and computes cosine similarity between //! every pair. Prints the top-k most similar file for each query. //! //! Usage: //! cargo r...
eren23/synapse
synapse/examples/bench_int8_vs_f32.rs
rs
3,070
c55c1ae914680438d4f7c5deb5e30a51b026304c4720827e8730012198e79d75
//! Benchmark: INT8 GEMV vs f32 GEMV at edge-model dimensions. //! //! Usage: cargo run -p synapse --release --example bench_int8_vs_f32 use std::time::Instant; fn matmul_t(a: &[f32], b: &[f32], m: usize, k: usize, n: usize) -> Vec<f32> { #[cfg(feature = "zig-ffi")] { synapse_core::sgemm(m, n, k, a, b).expect(...
eren23/synapse
synapse/examples/code_wm_pipeline.rs
rs
4,583
60dfd6090f18be135c5e24af542de4f0dd1e2b2e52d9b6e83405df176e5bf52b
//! Fully native Code WM pipeline: walk a directory β†’ tokenize .py files in Rust //! β†’ encode with CodeWM β†’ compute pairwise cosine β†’ find top-k similar. //! //! Zero Python runtime dependency. Single binary does tokenization + encoding + retrieval. //! //! Usage: //! cargo run --release --example code_wm_pipeline --...
eren23/synapse
synapse/examples/code_wm_quant_corpus.rs
rs
6,994
c6956b02a3231296586132437af327e519f976bce3eff3be6f82bcce9de0a561
//! Real-code quantization benchmark for Code WM. //! //! Loads a Code WM variant, quantizes it to INT8 / Q4 / Q4-full, and encodes //! every file in a pre-tokenized Python corpus with all four precisions. Reports //! per-file cosine drift (f32 β†’ quantized) distribution across the corpus plus //! per-precision encode l...
eren23/synapse
synapse/examples/code_wm_q4_compare.rs
rs
5,492
725429109283b8ebd13e0ef25cc30f33e14a4b2fd6423d979c8d2f8b1784a25e
//! Compare f32, INT8, and Q4 quantized Code WM side-by-side. //! //! Usage: //! cargo run --release --example code_wm_q4_compare -- \ //! models/code_wm/g8.safetensors \ //! configs/code_wm_g8.json \ //! tests/fixtures/code_wm_reference_g8.safetensors use std::env; use std::path::Path; use synaps...
eren23/synapse
synapse/examples/world_model_rollout.rs
rs
7,473
48b0882bee25a199d764bb263a6ecca124552ed54524da63e403a02252116b34
//! World Model Rollout Benchmark //! //! Demonstrates real-time latent dynamics prediction. //! Benchmarks the hot path: state→action→state prediction. //! //! Usage: cargo run --example world_model_rollout --release use std::time::Instant; use synapse_inference::models::vision::vit::ViTConfig; use synapse_inference:...
eren23/synapse
synapse/examples/jepa_embed.rs
rs
6,039
3c06c85472e23cabcf9f9657c899b9d301ac1a7f243f053a852cf37c063b07a8
//! Load DINOv2 encoder weights into a JEPA model and run a forward pass. //! //! Usage: //! cargo run --release --example jepa_embed -- --model-dir /tmp/dinov2-base //! //! The model directory must contain `config.json` and `model.safetensors` //! from `facebook/dinov2-base`. use std::path::PathBuf; use synapse_in...
eren23/synapse
synapse/examples/mnist.rs
rs
8,167
35cf6ffd2eec2ca0819ccf931e0dc03b489420d4119fbc4caef062dc8c84d6cc
//! MNIST example: MLP trained on synthetic MNIST-like data. //! //! Demonstrates a 3-layer MLP (784 -> 256 -> 128 -> 10) with cross-entropy loss. //! Uses the Trainer API with EarlyStopping callback. use synapse_autograd::{backward, Graph, NoGradGuard, Tensor}; use synapse_nn::init::kaiming_uniform; use synapse_optim...
eren23/synapse
synapse/examples/code_wm_semantic_test.rs
rs
5,510
2b23548b5253de7e7e79488bb165e9068422d95bc41d5fb87b1543af891814ec
//! Semantic similarity sanity test for Code WM. //! //! Loads a curated set of Python snippets (created by scripts/tokenize_snippets.py) //! with known categories (sort/str/math/io/http). Encodes each with Code WM, //! then measures whether within-category cosine > between-category cosine. //! //! Strong result = the ...
eren23/synapse
synapse/examples/lewm_compress.rs
rs
25,610
b68a81536a56aaf9d2e75b00e4905c97c33b44ca985aaaa82daa0b70f48e3863
//! LEWM Compression Benchmark //! //! Systematically tests f32/INT8/Q4 + pruning combinations on the LEWM model, //! measuring quality (cosine similarity of rollout trajectories) vs model size. //! //! Usage: //! cargo run --release --example lewm_compress //! //! Requires the checkpoint at /tmp/lewm-pusht/pusht/lej...
eren23/synapse
synapse/examples/rwkv_logit_probe.rs
rs
2,882
17981f49628e888160c0c9e5179f9fcc40306d8349d617172a26ebd1f2fb69c2
//! Compare RWKV logits and tokenization against a Python/HF baseline. //! //! ```text //! cargo run --example rwkv_logit_probe --release -- \ //! --model-dir models/rwkv7-pile-0.1b --prompt "hello" //! ``` use std::path::PathBuf; use synapse_inference::engine::InferenceEngine; use synapse_inference::models::ModelS...
eren23/synapse
synapse/examples/geometric_attention_demo.rs
rs
3,075
78d97c965981a3ade696f98cc73eae08ed62ba82fec6950b25bd873c693d16d9
//! Geometric Attention Demo: distance-aware attention for 3D point clouds. //! //! Demonstrates a custom Zig SIMD kernel that PyTorch/MLX don't have. //! Shows: closer points attend more, faraway points attend less. use std::time::Instant; use synapse_inference::ops::geometric::geometric_attention; fn main() { p...
eren23/synapse
synapse/examples/cifar10.rs
rs
10,451
224c448ba996dd24788ba995a915a2c9f279ef14c17166b02b8131774201c682
//! CIFAR-10 example: Simple CNN trained on synthetic CIFAR-10-like data. //! //! Architecture: Conv2d(3,16,3) -> ReLU -> Conv2d(16,32,3) -> ReLU -> Flatten -> Linear(128) -> Linear(10) //! Demonstrates training with Module trait layers and graph-based backprop. use synapse_autograd::{backward, Graph, Tensor}; use syn...
eren23/synapse
synapse/examples/code_wm_int8_compare.rs
rs
5,238
099bb3b391575032d853560acb56374271b99054133bea1653153412c358528d
//! Compare INT8-quantized Code WM against f32 reference. //! //! Loads the f32 model, quantizes it to INT8, then compares encoder/action/ //! predictor outputs against the PyTorch goldens. Reports cosine similarity, //! max_abs_diff, and total in-memory bytes for each variant. //! //! Usage: //! cargo run --release ...
eren23/synapse
synapse/examples/lewm_slim_vs_baseline.rs
rs
14,507
cd28e8590f4b0dc005295521ad8ac09b57a74262b95e7ed4d77066f785322570
//! LEWM Slim vs Baseline Compression Benchmark //! //! Benchmarks multiple LEWM architecture variants (different latent dims, //! encoder/predictor layer counts) against the baseline, measuring quality //! (cosine similarity) and size at f32 and Q4. //! //! Usage: //! cargo run --release --example lewm_slim_vs_basel...
eren23/synapse
synapse/examples/export_browser_corpus.rs
rs
3,900
7517ec275728b0efd7a0ff129c81cd1b67619f781fcaae1dd08dd880ce71730d
//! Export a browser-ready corpus JSON: walk a dir, tokenize + encode each .py //! file, save as {files: [{path, preview, embedding: [128 f32]}]}. //! //! The browser demo loads this JSON once and runs cosine search against it. //! //! Usage: //! cargo run --release --example export_browser_corpus -- \ //! mode...
eren23/synapse
synapse/examples/clip_similarity.rs
rs
5,454
dc66a3f5e2a2ff6bde290540b253a4b97c5e6da5de8d2aeb08537bef31e9eac3
//! Compute image-text similarity using HuggingFace CLIP weights. //! //! Usage: //! cargo run --release --example clip_similarity -- --model-dir /tmp/clip-vit-base //! //! The model directory must contain `config.json` and `model.safetensors` //! from `openai/clip-vit-base-patch32`. use std::path::PathBuf; use syn...
eren23/synapse
synapse/examples/qwen3_chat.rs
rs
24,931
724bcccf31cf2a2b3b3c48ddbf18c073421d51e06092e7e6f757e16d5bfcbc9e
//! Interactive chat with either a real Qwen3 checkpoint or a tiny demo model. //! //! Usage: //! cargo run --example qwen3_chat --release -- --model-dir /path/to/Qwen3-0.6B //! cargo run --example qwen3_chat --release -- --demo use std::cell::Cell; use std::collections::HashMap; use std::io::{self, BufRead, Write...
eren23/synapse
synapse/examples/xor.rs
rs
3,668
dce8f99156ebd0875b096cf8e048f77ba9b5586c9b18daaae7dea082141e168d
//! XOR example: 2-layer MLP solving the XOR problem. //! //! Demonstrates graph-based training with Synapse. //! Target: loss < 0.01 within 1000 steps. use synapse_autograd::{backward, Graph, Tensor}; use synapse_nn::init::xavier_uniform; use synapse_optim::{Optimizer, Param, SGD}; fn main() { // XOR dataset: 4 ...
eren23/synapse
synapse/examples/export_lewm_q4.rs
rs
23,818
da9780a8cff4ed53c46cf295bbcf1dcdb6d39e4f30fc1b68426ab60aab0db3b7
//! Export LEWM models in compact Q4 binary format for WASM loading. //! //! Supports four modes: //! - `q4-pred`: Q4 predictor only, f32 encoder (~17MB) //! - `full`: INT8 encoder + Q4 predictor (~10MB) //! - `wanda20-q4`: Wanda 20% prune then Q4 (~17MB, better compressed) //! - `wanda40-q4`: Wand...
eren23/synapse
synapse/examples/tokenizer_cross_check.rs
rs
968
2dc3f361f81463cf01d98e04b90eac9d538587f7c61d04a408f1990539b5acb9
//! Validate synapse-code-tokenizer matches the Python FNV-1a reference. //! //! For each test snippet, we print Rust tokens. Then the caller compares //! against `python3 scripts/ast_tokenizer_fnv.py < snippet`. //! //! Usage: //! cargo run --release --example tokenizer_cross_check use synapse_code_tokenizer::token...