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-inference/src/models/vision/jepa.rs
rs
22,327
e8cec783427848d244067d28d92e5b7ce270aa6670901ad720246e06ee2a3a15
//! JEPA (Joint Embedding Predictive Architecture) model. //! //! Architecture: ViT encoder + narrow predictor transformer. //! The predictor takes context embeddings and predicts target embeddings //! in embedding space β€” no decoder, no token sampling. use std::collections::HashMap; use crate::config::{AttentionConf...
eren23/synapse
synapse/crates/synapse-inference/src/models/vision/vit.rs
rs
26,952
8c7ad265b9705a45d1dae180d97c78e3217c2169ea772fed03a89be694dc1f94
//! Vision Transformer (ViT) model for image classification and embedding extraction. //! //! Implements the standard ViT architecture: //! patch_embed β†’ prepend CLS β†’ add pos_embed β†’ N Γ— EncoderLayer β†’ final norm β†’ optional classifier. use std::collections::{HashMap, HashSet}; use crate::ops::activation::gelu; use c...
eren23/synapse
synapse/crates/synapse-inference/src/diffusion/unet.rs
rs
2,306
ce6552d7b2b2cd191af80939ffeeb8a8d382dc769d8537851587a8d050ff16e8
//! UNet denoising backbone for diffusion models. //! //! The UNet takes a noisy latent tensor and a timestep, and predicts the noise //! to be removed. In Stable Diffusion, the UNet also receives text embeddings //! from a CLIP text encoder via cross-attention. /// UNet denoising model. /// /// Architecture: encoder ...
eren23/synapse
synapse/crates/synapse-inference/src/diffusion/config.rs
rs
1,349
fe78c3602d849be013b286fd869f1d44b45a493914e9337f634a94b09e473fbb
//! Configuration for Diffusion LLM (non-autoregressive text generation). /// Configuration for a bidirectional diffusion language model. /// /// Unlike autoregressive models, diffusion LLMs generate all tokens /// simultaneously by iteratively denoising a fully masked sequence. #[derive(Debug, Clone)] pub struct Diff...
eren23/synapse
synapse/crates/synapse-inference/src/diffusion/mod.rs
rs
991
15e00c1b34c59c5a6887052cfb05b08cc4bed19492c83e731e8ead4273e98e20
//! Diffusion model support. //! //! Two flavours: //! //! ## Image diffusion (UNet-based) //! Scaffolding for image generation via Stable Diffusion, SDXL, Flux, etc. //! Types compile and are importable but forward methods are unimplemented. //! //! ## Diffusion LLM (text) //! Non-autoregressive text generation via it...
eren23/synapse
synapse/crates/synapse-inference/src/diffusion/schedule.rs
rs
6,837
064e3208d8cbff1cce05a1adebee4eeadfd81b035b20d37774889db49c8dd9ea
//! Denoising mask schedules for diffusion LLM generation. //! //! Controls which tokens to unmask at each denoising step. /// Mask schedule strategy for diffusion denoising. #[derive(Debug, Clone, Copy)] pub enum MaskSchedule { /// Unmask tokens with highest confidence, spread evenly across steps. Confidence,...
eren23/synapse
synapse/crates/synapse-inference/src/diffusion/scheduler.rs
rs
3,663
5f78b4a0a66c3e1769b87dfe259e4764cd88f0d55426366e57938ccdc2908fce
//! Noise schedulers for the diffusion denoising process. //! //! A scheduler controls how noise is added and removed across timesteps. //! Different schedulers trade off quality vs speed: //! - DDPM: original, 1000 steps, high quality //! - DDIM: deterministic, 20-50 steps, faster //! - Euler/DPM: modern, 20-30 steps,...
eren23/synapse
synapse/crates/synapse-inference/src/diffusion/pipeline.rs
rs
2,659
d91f2aca04fb670d0728f4c8a4430d4d059b37ac50024f9f626679081c9a172e
//! Diffusion inference pipeline. //! //! Orchestrates the text-to-image generation process: //! 1. Encode text prompt via CLIP text encoder //! 2. Generate initial random noise in latent space //! 3. Iteratively denoise using UNet + scheduler //! 4. Decode latent to pixel space via VAE decoder use super::scheduler::N...
eren23/synapse
synapse/crates/synapse-inference/src/diffusion/model.rs
rs
14,127
46af9971415b0fee58d35ae2230b4c437bee0c06d2584e56509030978762db22
//! Diffusion LLM model with iterative denoising generation. //! //! Implements a bidirectional transformer that generates text by //! iteratively unmasking tokens from a fully masked sequence. use crate::diffusion::config::DiffusionLLMConfig; use crate::diffusion::schedule::{unmask_by_confidence, tokens_per_step, Mas...
eren23/synapse
synapse/crates/synapse-inference/src/quantization/mod.rs
rs
216
9a190cc6cedd5441f9b8a6ef06bef48d5bfb5125818c2f21cdacbfe3db0b3f9e
pub mod lm; pub mod primitives; pub mod ssm; pub mod vision; // Flatten sub-modules into the `quantization::` namespace (public API surface). pub use primitives::*; pub use lm::*; pub use ssm::*; pub use vision::*;
eren23/synapse
synapse/crates/synapse-inference/src/quantization/ssm/mod.rs
rs
213
55ceb48b0ef1a59ead46f2a363a97a4313af6d5e379ead97c1a2ddea79595cc1
pub mod int8_mamba; pub mod q4_mamba; pub mod q4_rwkv; pub use int8_mamba::{QuantizedMambaBlock, QuantizedMambaModel}; pub use q4_mamba::{Q4MambaBlock, Q4MambaModel}; pub use q4_rwkv::{Q4RwkvBlock, Q4RwkvModel};
eren23/synapse
synapse/crates/synapse-inference/src/quantization/ssm/int8_mamba.rs
rs
13,028
e6eefc06ce41e00dea9123f77d3d2e507bb354e0a963906847030ee90e2b4fbf
//! INT8-quantized Mamba model. //! //! Quantizes the large linear projections (in_proj, out_proj) to INT8 while //! keeping SSM-specific ops (conv1d, selective scan, A_log, D) in f32. //! This reduces model size by ~4x with minimal quality loss. use std::cell::RefCell; use crate::config::ModelConfig; use crate::mode...
eren23/synapse
synapse/crates/synapse-inference/src/quantization/ssm/q4_mamba.rs
rs
14,739
54ab49fa4f11318b8e86ad25be95d3952dab24b1f345aa2563517bcac631349e
//! Q4-quantized Mamba model. //! //! Quantizes the large linear projections (in_proj, out_proj) to Q4_0 (4-bit) //! while keeping SSM-specific ops (conv1d, selective scan, A_log, D) in f32. //! This reduces model size by ~6.4x, making Mamba-130M fit in ~32MB for ESP32/WASM. use std::cell::RefCell; use crate::config:...
eren23/synapse
synapse/crates/synapse-inference/src/quantization/ssm/q4_rwkv.rs
rs
28,511
792adc8f25030943a8f9f91c13f3d1c455d441436521e971dd91238a16d1ff5e
//! Q4-quantized RWKV-7 model. //! //! Quantizes the 6 large linear projections (r_proj, k_proj, v_proj, o_proj, //! ffn_key_weight, ffn_value_weight) to Q4_0 (4-bit) while keeping SSM-specific //! parameters (token shift lerps, low-rank matrices, norms) in f32. //! This reduces model size by ~6.4x for ESP32/WASM deplo...
eren23/synapse
synapse/crates/synapse-inference/src/quantization/lm/int8.rs
rs
35,070
ff5a9bf99a6f7e2034d24dc522f4ba99b17da706b3f21c5a7521dd3c8c6421d3
use std::mem; use std::sync::atomic::{AtomicBool, Ordering}; use std::sync::OnceLock; use std::time::Instant; use crate::config::position::RoPEStyle; use crate::config::ModelConfig; use crate::kv_cache::{KVCache, KVCacheLayer}; use crate::models::lm::causal_lm::ModelOutput; use crate::models::lm::CausalLM; use crate::...
eren23/synapse
synapse/crates/synapse-inference/src/quantization/lm/mod.rs
rs
211
855270aaba4973b3df07acf833a3009f67b1f2ecde3813bbc4b513568ad56c31
pub mod int8; pub mod ternary; pub use int8::{f32_model_memory_bytes, quantize_model, QuantizedCausalLM, QuantizedDecoderLayer}; pub use ternary::{quantize_model_ternary, TernaryCausalLM, TernaryDecoderLayer};
eren23/synapse
synapse/crates/synapse-inference/src/quantization/lm/ternary.rs
rs
21,417
f1d39959cec384836ea3ed8cd19eccd1a33e3c664ab4154bae524bde0b09afad
//! Ternary (2-bit) quantized causal language model. //! //! Mirrors the INT8 [`QuantizedCausalLM`](super::QuantizedCausalLM) but uses //! [`TernaryLinear`] for all projection weights. This gives ~16x weight //! compression (2 bits/weight vs 32 bits/weight) at the cost of higher //! approximation error compared to INT8...
eren23/synapse
synapse/crates/synapse-inference/src/quantization/vision/q4_code_wm.rs
rs
13,054
8f78e4fed914380df3f5b35f8f98e995283a38422dbc3eed8da42ffa144a160b
//! Q4 quantization for Code WM (CWM). //! //! Only the 4 Linear weight matrices per transformer block are quantized //! (attn in/out projections + MLP up/down). These are ~92% of the model's //! matmul weights. Embeddings, positional encoding, LayerNorm params, //! biases, and the tiny action encoder stay f32 β€” quanti...
eren23/synapse
synapse/crates/synapse-inference/src/quantization/vision/int8_code_wm.rs
rs
16,369
fe7051117bd24954b4f2059b0dcf1d2567cc739291ed2fb38deaa942fc2851dd
//! INT8 quantization for Code WM (CWM). //! //! Only the 4 Linear weight matrices per transformer block are quantized //! (attn in/out projections + MLP up/down). These are ~92% of the model's //! matmul weights. Embeddings, positional encoding, LayerNorm params, //! biases, and the tiny action encoder stay f32 β€” quan...
eren23/synapse
synapse/crates/synapse-inference/src/quantization/vision/q4_code_wm_full.rs
rs
13,940
8509395d82f5ac39d082b823c1dc60f0eb3eae56900f4f5a2dbc87f576759383
//! Full-model quantization for Code WM: Q4 matmul layers + INT8 per-row //! token_embedding + pos_enc. Biases, layernorms, and the tiny action encoder //! stay f32. //! //! Q4 alone leaves ~660 KB of f32 weights (embedding 336 KB + PE 257 KB + //! action 68 KB); quantizing the two big tables shrinks the model further....
eren23/synapse
synapse/crates/synapse-inference/src/quantization/vision/mod.rs
rs
1,940
1bdddb12b835475a30bf53c3ea2b004355c05cd876fdb99493bfbf58d0aafef9
pub mod full_q_lewm; pub mod int8_code_wm; pub mod int8_lewm; pub mod q4_code_wm; pub mod q4_code_wm_full; pub mod q4_lewm; pub mod ternary_lewm; pub use full_q_lewm::{FullyQuantizedLeWM, quantize_lewm_full, Q4FullLeWM, quantize_lewm_q4_full}; pub use int8_code_wm::{load_and_quantize as load_and_quantize_code_wm, quan...
eren23/synapse
synapse/crates/synapse-inference/src/quantization/vision/ternary_lewm.rs
rs
17,884
bb11e0f4759d70952ad096f69bb8a6758c2184dcdb43b97f19aa5311c39c527e
//! Ternary (2-bit) quantized LEWM predictor with TerDiT RMSNorm stabilization. //! //! The key insight from TerDiT (2025): ternary DiT models require adding RMSNorm //! after the adaLN modulation MLP to stabilize the scale/shift/gate values. //! Without this, large modulation values destabilize the ternary forward pas...
eren23/synapse
synapse/crates/synapse-inference/src/quantization/vision/full_q_lewm.rs
rs
44,455
7571fb69ac2321003239ba8a32a03021ccfc3f5419f58ff71a1f29ee9029cfd4
//! Fully quantized LEWM: INT8 ViT encoder + Q4 predictor. //! //! This is the most aggressive practical compression for LEWM: //! - ViT encoder: INT8 projections (~4x compression on ~2.8M params) //! - Predictor: Q4 projections (~6.4x compression on ~10.8M params) //! - Total: ~9MB (from ~52MB f32) //! //! Target depl...
eren23/synapse
synapse/crates/synapse-inference/src/quantization/vision/int8_lewm.rs
rs
29,113
75dd7ca620240b29615c35be753b70e76c75089814b400cb9ffe5b3a39795794
//! INT8 quantization for the LeWorldModel (LeWM). //! //! Only the predictor's adaLN transformer layers are quantized β€” they account //! for ~10.8M of the model's ~14M parameters. The ViT encoder (~2.8M params), //! action encoder, and projection heads remain f32. use crate::models::vision::lewm::{LeWMConfig, LeWorld...
eren23/synapse
synapse/crates/synapse-inference/src/quantization/vision/q4_lewm.rs
rs
62,827
f8afa0276b0d44f76c9b1ba0b75dd02a4f26873e13715bf4e533d4a5313908a6
//! Q4_0-quantized LeWorldModel variants. use crate::models::vision::lewm::{AdaLNTransformerLayer, LeWMConfig, LeWorldModel, ProjectionHead}; use crate::models::vision::vit::ViTModel; use crate::ops::activation::gelu; use crate::ops::attention::bidirectional_attention; use crate::ops::norm::layernorm; use crate::quan...
eren23/synapse
synapse/crates/synapse-inference/src/quantization/primitives/q4_linear.rs
rs
14,700
57ae58126c349278a2741f14724467041e54ecdcb244c489591102e4f855a17b
//! Q4_0 (4-bit) quantization primitives. //! //! Q4_0 block format: 32 elements per block, each block stores 1 f32 scale + //! 16 bytes of nibble pairs = 20 bytes per block. This gives ~6.4x compression //! vs f32. Predictor weights shrink from ~43MB (f32) to ~7MB (Q4), fitting in //! ESP32-P4's 32MB PSRAM. /// Conve...
eren23/synapse
synapse/crates/synapse-inference/src/quantization/primitives/int8_linear.rs
rs
11,983
044389c0e7f96a8a714fbf8fe6eb8dd99716dc51620e6ac979a6d0f9f5bc5674
use std::mem; use super::calibration::MinMaxCalibration; /// A linear layer with INT8 quantized weights and f32 per-channel scales. /// /// Weights are stored in transposed layout `[in_features, out_features]` for /// direct use by the SIMD GEMM kernel. Forward pass quantizes activations /// on-the-fly and dispatches...
eren23/synapse
synapse/crates/synapse-inference/src/quantization/primitives/mod.rs
rs
284
99e845260c9c7785e5750f8c1780d5e0c5cccdf431a29d973e5f34ec0f879d75
pub mod calibration; pub mod int8_linear; pub mod q4_linear; pub mod ternary_linear; pub use calibration::{MinMaxCalibration, PercentileCalibration}; pub use int8_linear::QuantizedLinear; pub use q4_linear::{Q4Block, Q4Linear}; pub use ternary_linear::{TernaryBlock, TernaryLinear};
eren23/synapse
synapse/crates/synapse-inference/src/quantization/primitives/calibration.rs
rs
2,647
731eabf83fffc74e0426f3b6fd4048d3576ac08f166b9028b52ad37d2127d27b
/// Per-channel min/max calibration. /// /// Computes `scale[ch] = max(|w[ch, :]|) / 127` for each output channel. pub struct MinMaxCalibration; impl MinMaxCalibration { /// Compute per-channel scale factors from weight values. /// /// `weights` is `[channels, channel_size]` row-major. /// Returns one ...
eren23/synapse
synapse/crates/synapse-inference/src/quantization/primitives/ternary_linear.rs
rs
14,075
6c40bf3a54cdd296a1d176835f2ea3c076c9db0efc68cf0b72cb183cf2e6ebb2
//! Ternary (2-bit) quantization for linear layers. //! //! Each weight is quantized to {-1, 0, +1} * scale, where the scale is computed //! per-row as the mean absolute value of the non-zero weights. Two bits per weight //! are packed into u8 bytes, giving 4 weights per byte and 16 weights per block. //! //! Encoding:...
eren23/synapse
synapse/crates/synapse-inference/src/pruning/sensitivity.rs
rs
16,616
35285b64df9e1b0d579ccdc0e1ccb30908a4739f00c928c0138153b7dda1b3c8
//! Sensitivity analysis: measure layer importance by output divergence. //! //! For each layer, we compare the model's output with that layer active vs. //! skipped. Layers whose removal causes minimal divergence are candidates for //! pruning or removal. use crate::models::lm::causal_lm::ModelOutput; use crate::ops:...
eren23/synapse
synapse/crates/synapse-inference/src/pruning/layer_removal.rs
rs
15,618
7407d1fdb392298ca3eeb5a1f88b35703a133a9f92c8ac6ac6d68c3f9a79917d
//! Layer removal: drop near-identity layers from SSM models. //! //! Based on ShortGPT/Block Influence Score: layers where cos(input, output) β‰ˆ 1.0 //! are near-identity transforms and can be removed with minimal quality loss. use crate::models::ssm::mamba::block::MambaBlock; use crate::models::ssm::mamba::model::Mam...
eren23/synapse
synapse/crates/synapse-inference/src/pruning/ssm_pruning.rs
rs
19,879
c46a412f0000c1ddfbae36dcc8366144bc4bf78318eeed92c939e0c9989a7f20
//! SSM-aware structured pruning for Mamba and RWKV models. //! //! Inspired by Mamba-Shedder (NAACL 2025): //! - Channel pruning: reduce d_inner by removing low-importance channels //! - Head pruning: reduce num_heads in RWKV by importance //! //! These are structured pruning methods that actually reduce matrix dimens...
eren23/synapse
synapse/crates/synapse-inference/src/pruning/mod.rs
rs
1,012
6bf2ff2db35b5213aff7710ceca9fa6b1ab117ee9841986cb47373d80b766822
//! Model surgery: sensitivity analysis, layer removal, weight pruning, and SSM-aware pruning. //! //! The pruning pipeline follows a principled order: //! 1. **Sensitivity analysis** β€” measure layer importance via output divergence //! 2. **Layer removal** β€” drop near-identity layers (ShortGPT-style) //! 3. **Weight p...
eren23/synapse
synapse/crates/synapse-inference/src/pruning/pipeline.rs
rs
12,486
74fa77a0fd219733e35799cb4db3e62697baec90e0206180aeb281e2b99ad5e2
//! Surgery pipeline: orchestrates analyze β†’ prune β†’ validate β†’ export. //! //! Combines sensitivity analysis, layer removal, Wanda weight pruning, //! and SSM-aware channel pruning into a single configurable pipeline. use crate::models::traits::Model; use crate::models::ssm::mamba::model::MambaModel; use super::layer...
eren23/synapse
synapse/crates/synapse-inference/src/pruning/wanda.rs
rs
10,151
7b3148ee22fd484537c5dc9416b16c6feea81f014ef2cec11e9d380255ab2457
//! Wanda (Weights and Activations) pruning. //! //! One-shot pruning: importance[i,j] = |W[i,j]| * ||X[:,j]||_2 //! Prunes bottom-p% weights per output row. No retraining required. //! //! Ref: Sun et al., "A Simple and Effective Pruning Approach for Large Language Models" (ICLR 2024) /// Prune a weight matrix using ...
eren23/synapse
synapse/crates/synapse-inference/src/kv_cache/cache.rs
rs
15,830
c372d3d62da44713746ca992e842f279c82d80cda07bd305602c010f6802b5f1
// ── FFI-based KV cache (zig-ffi feature) ───────────────────────────── #[cfg(feature = "zig-ffi")] mod imp { use std::ptr; use synapse_core::SynapseError; use synapse_sys as ffi; fn check_status(status: ffi::syn_status_t) -> Result<(), SynapseError> { match status { ffi::SYN_OK =...
eren23/synapse
synapse/crates/synapse-inference/src/registry/factory.rs
rs
7,468
6f90f17326ba5099a73132513f2154d1e9fc6ce8e041544d91fb47932e2e3291
use super::{AttentionVariant, FFNVariant, NormVariant, PositionVariant}; use crate::config::{AttentionConfig, FFNConfig, NormConfig, PositionConfig}; // ── Attention concrete types ──────────────────────────────────────── #[derive(Debug)] struct GQAAttention { num_heads: usize, num_kv_heads: usize, head_d...
eren23/synapse
synapse/crates/synapse-inference/src/registry/norm.rs
rs
14,079
c7ce198ef38e23620279c08b79dff3bd23a092998feb456ae3bb03ffe7f5af80
use super::NormVariant; /// RMSNorm: output = gamma * x * rsqrt(mean(x^2) + eps) /// /// The production forward path calls Zig `syn_rmsnorm_forward` via FFI. /// A pure-Rust reference forward is provided for testing. #[derive(Debug, Clone)] pub struct RMSNorm { eps: f64, hidden_size: usize, gamma: Vec<f32>...
eren23/synapse
synapse/crates/synapse-inference/src/registry/ffn.rs
rs
19,837
0f13b9b88710aac8e99925bff5cc3f0beec77f4806a4fc82d31102e7206b75ba
use super::FFNVariant; /// Activation function variants for StandardFFN. #[derive(Debug, Clone, Copy, PartialEq, Eq)] pub enum Activation { ReLU, GeLU, SiLU, } impl Activation { fn apply(&self, x: f32) -> f32 { match self { Activation::ReLU => x.max(0.0), Activation::Ge...
eren23/synapse
synapse/crates/synapse-inference/src/registry/attention.rs
rs
29,372
821b7ce6d45f612a0405ca58cdae8a100a7f746245785e9372bc965f4ee809bb
//! Attention mechanism implementations with GQA and sliding window support. //! //! GQA (Grouped-Query Attention) is the general form that subsumes: //! - **MHA** (Multi-Head Attention): `num_kv_heads == num_heads` β€” no KV sharing //! - **MQA** (Multi-Query Attention): `num_kv_heads == 1` β€” all heads share one KV use...
eren23/synapse
synapse/crates/synapse-inference/src/registry/mod.rs
rs
1,111
d0a6b0ba3a9545fab72ad93f4f48e567a29382ec9212957b967b74d4a5983f24
pub mod attention; pub mod factory; pub mod ffn; pub mod norm; pub mod position; use std::fmt::Debug; /// Trait for attention mechanism variants instantiated from config. pub trait AttentionVariant: Send + Sync + Debug { fn num_heads(&self) -> usize; fn head_dim(&self) -> usize; fn num_kv_heads(&self) -> ...
eren23/synapse
synapse/crates/synapse-inference/src/registry/position.rs
rs
9,097
bb23be7662df80d38f6a0a0781a4eab251756ccf07b81c4bd31a337729a1fc8f
//! Positional encoding implementations: RoPE and Learned embeddings. use super::PositionVariant; #[cfg(feature = "zig-ffi")] use synapse_core::{SynapseError, Tensor}; // ── RoPE ───────────────────────────────────────────────────────────── /// Rotary Positional Embedding (RoPE). /// /// Precomputes cos/sin caches f...
eren23/synapse
synapse/crates/synapse-inference/src/ops/norm.rs
rs
5,733
bab74cca5112505ab15bd559c84dfa603a70cc1f1f10bd09aef7043513c54462
use crate::registry::NormVariant; /// RMS normalization over the last dimension (SIMD via Zig FFI). /// /// Uses `syn_vmul` / `syn_vreduce_sum` for zero-copy SIMD on each row, /// avoiding tensor-handle allocation overhead that dominates at small sizes. #[cfg(feature = "zig-ffi")] pub(crate) fn rmsnorm(x: &[f32], weig...
eren23/synapse
synapse/crates/synapse-inference/src/ops/geometric.rs
rs
4,541
712c34d6290e1b478564c6cd93966e67f294d9494ea8bede974739a7ff800267
//! Geometric attention: distance-aware attention for 3D point clouds and molecules. //! //! An op that PyTorch/MLX don't have optimized SIMD kernels for. //! Hand-tuned in Zig with NEON/AVX2 vectorization. //! //! ```text //! score[i,j] = softmax(Q[i]Β·K[j]/√d + exp(-||pos_i - pos_j||Β² / 2σ²)) //! out[i] = Ξ£_j score[i,...
eren23/synapse
synapse/crates/synapse-inference/src/ops/vector.rs
rs
1,474
21675a51d89bf14ddc3b2cd3974441e4624c63ee19feb0f3693de8ad3a2b7244
pub(crate) fn add_vecs(a: &[f32], b: &[f32]) -> Vec<f32> { a.iter().zip(b.iter()).map(|(x, y)| x + y).collect() } pub(crate) fn add_vecs_inplace(a: &mut [f32], b: &[f32]) { for (x, y) in a.iter_mut().zip(b.iter()) { *x += *y; } } #[cfg(test)] mod tests { use super::*; #[test] fn add_v...
eren23/synapse
synapse/crates/synapse-inference/src/ops/pure_rust_ops.rs
rs
18,460
00f6cd928196624029288a0b1b53e9a6bbf7ea69282bcfbec9ebb06d97f978f8
//! Pure-Rust fallback ops for WASM and embedded targets. //! These are correctness-first, not performance-optimized. /// Matrix multiply: C[m,n] = A[m,k] * B^T[n,k] pub fn matmul_t(a: &[f32], b: &[f32], m: usize, k: usize, n: usize) -> Vec<f32> { let mut out = vec![0.0f32; m * n]; for i in 0..m { for ...
eren23/synapse
synapse/crates/synapse-inference/src/ops/fused_ops.rs
rs
23,945
2af6ea1282673627591d0e90c11144af195040d448e152e5111e046cce32b2ad
//! Fused kernels for edge inference on memory-constrained targets (ESP32, WASM). //! //! Each fused kernel eliminates intermediate buffer allocations by combining //! multiple operations into a single pass. This is critical on ESP32 (32MB) //! where every allocation counts, and on WASM where bandwidth is limited. //! ...
eren23/synapse
synapse/crates/synapse-inference/src/ops/attention.rs
rs
16,390
97b06aad68cf314f8bfd9f6055b589cfd4190ed1b45bd4858cc6475de630d986
//! Shared attention computations used by both f32 and quantized inference paths. //! //! These functions operate on **pre-projected** Q, K, V tensors: the caller //! handles the linear projections (f32 matmul_t vs QuantizedLinear::forward), //! then delegates the core attention logic here. use crate::config::position...
eren23/synapse
synapse/crates/synapse-inference/src/ops/matmul.rs
rs
6,619
693f1cbd1a79033dba2f3f848f53ad2c289d33488b0c7a54a021a6035e5972d6
// ── Apple Accelerate BLAS (macOS) ───────────────────────────────── // cblas_sgemm from Accelerate.framework β€” hand-tuned by Apple for all // Apple Silicon matrix sizes. Significantly faster than our Zig kernel // for small M (LEWM predict) and competitive for large M (LLM prefill). #[cfg(target_os = "macos")] mod ac...
eren23/synapse
synapse/crates/synapse-inference/src/ops/mod.rs
rs
276
dbaa0cae0b7f05be84045d3a626c828c1cad1699c8891a2b5b608cb38a5cec22
//! Shared math operations used across f32 and quantized inference paths. pub mod activation; pub mod attention; pub mod fused_ops; pub mod geometric; pub mod matmul; pub mod norm; pub mod patch_embed; pub mod projection; pub mod pure_rust_ops; pub mod rope; pub mod vector;
eren23/synapse
synapse/crates/synapse-inference/src/ops/projection.rs
rs
4,693
6f93cef86932a979f89c86ce944e26fdb2af37da313669942633144338099afa
//! Projection GEMV with fused bias for small-K linear layers. //! //! Dispatch: Zig SIMD FFI when available, pure-Rust fallback otherwise. //! Optimized for LEWM input_proj/cond_proj: M in {1,3}, N=192, K in [48,192]. /// Projection GEMV: output[m,n] = input[m,k] * weight[n,k]^T + bias[n] /// /// `input` is `[m * k]`...
eren23/synapse
synapse/crates/synapse-inference/src/ops/rope.rs
rs
5,456
63490a90a9173cceb38d3b26d4df0ff0c367302d777a496a6b34c5fb57435f13
pub use crate::config::position::RoPEStyle; /// Apply RoPE rotation to Q or K vectors in-place (rotate-half convention). /// /// `qk` layout: `[seq_len, num_heads * head_dim]` (flat, heads contiguous). /// Uses the HuggingFace "rotate_half" convention: pairs dimension `i` with /// dimension `i + head_dim/2` (first-ha...
eren23/synapse
synapse/crates/synapse-inference/src/ops/patch_embed.rs
rs
3,613
2482f566a41b480d271cbe1195cdd4a33a0a4d63f1995df499fb44c2769269dc
//! Patch embedding: convert images to sequences of patch embeddings for ViT. use super::matmul::matmul_t; /// Convert image [H, W, C] to patch embeddings [num_patches, embed_dim]. /// /// Extracts PΓ—P patches, flattens each to [P*P*C], and projects via linear layer. /// Returns [num_patches, embed_dim] where num_pat...
eren23/synapse
synapse/crates/synapse-inference/src/ops/activation.rs
rs
8,216
69bb1df856aacedbf7bd118bd9db033baac0be2649c9b99cf03ecd9f3e351d7f
//! Activation functions, elementwise ops, and softmax. //! //! Priority rule: always prefer batched/vectorized calls over scalar loops. //! - For slices: use `*_inplace` or `batched_*` to amortise call overhead. //! - Scalar versions exist only for single-value calls or non-`zig-ffi` fallbacks. /// In-place SiLU: `x ...
eren23/synapse
synapse/crates/synapse-inference/src/engine/loading.rs
rs
15,668
aaf392872cb389994163d8be96276b41932df745b9eb630ab42101344cb585a1
use std::path::Path; use super::InferenceEngine; use super::config_parsers::{ detect_model_type, find_checkpoint_file, minimal_config_for_hybrid, minimal_config_for_rwkv, minimal_config_for_ssm, parse_hybrid_config, parse_mamba_config, parse_rwkv_config, }; use crate::chat_template::ChatTemplate; use crate::c...
eren23/synapse
synapse/crates/synapse-inference/src/engine/mod.rs
rs
21,793
86d84f81e780619d8af90b1e5bebb3c50e8081e47a274266a32f89a006eeac7b
mod loading; pub(crate) mod config_parsers; use crate::capabilities::CapabilityReport; use crate::chat_template::{ChatMessage, ChatTemplate}; use crate::config::ModelConfig; use crate::generation::{GenerationConfig, GenerationOutput, GenerationPipeline}; use crate::kv_cache::KVCache; use crate::models::traits::Model; ...
eren23/synapse
synapse/crates/synapse-inference/src/engine/config_parsers.rs
rs
14,325
cda7a6013271b52054a2fce38a9c08a77f4ae6eebf314fc3ef2020dca7d17337
use std::path::{Path, PathBuf}; use crate::config::ModelConfig; use crate::models::ssm::mamba::config::MambaConfig; use crate::models::ssm::rwkv::config::RwkvConfig; use crate::models::ssm::hybrid::config::{HybridConfig, LayerKind}; use crate::weight_loading::WeightError; /// Detect the `model_type` field from a Hugg...
eren23/synapse
synapse/crates/synapse-inference/src/generation/mod.rs
rs
383
a4fc82f55e8ebded6293f15bd1214bdb92d146aee9758f7bd796d4820cc3293d
pub mod output; pub mod pipeline; pub mod sampler; pub mod stopping; pub use output::GenerationOutput; pub use pipeline::{GenerationConfig, GenerationPipeline}; pub use sampler::{ argmax, softmax_inplace, CombinedSampler, GreedySampler, RepetitionPenalty, RngAdapter, Sampler, TemperatureSampler, TopKSampler, T...
eren23/synapse
synapse/crates/synapse-inference/src/generation/output.rs
rs
1,794
f504f8dd282b2d6c8562ffb5a0e113b035d6aad4b561d3a19cffcda209d00148
use std::time::Duration; /// Result of a generation run. pub struct GenerationOutput { /// The generated text (empty if no detokenizer is available). pub text: String, /// All token IDs: prompt tokens followed by generated tokens. pub token_ids: Vec<u32>, /// Number of tokens generated (excludes pr...
eren23/synapse
synapse/crates/synapse-inference/src/generation/sampler.rs
rs
14,761
a9566673119e96cfb7ca50568b15cce5094144a1247743fbeda12a377bd8b7d1
use rand::Rng; /// Trait for token sampling strategies. /// /// Implementations receive a mutable logits slice and return a sampled token index. /// Samplers may modify the logits in-place (e.g., applying temperature, masking). pub trait Sampler: Send + Sync { /// Sample a single token index from the logits distri...
eren23/synapse
synapse/crates/synapse-inference/src/generation/pipeline.rs
rs
33,423
f7fe02a476561531b2c055996d640c3fc40382e16b07cb96b654f8382dc53843
#[cfg(target_arch = "wasm32")] use std::time::Duration; use rand::rngs::StdRng; use rand::SeedableRng; // WASM doesn't support std::time::Instant. Use a shim that returns zero durations. #[cfg(not(target_arch = "wasm32"))] use std::time::Instant; #[cfg(target_arch = "wasm32")] #[derive(Clone, Copy)] struct Instant; ...
eren23/synapse
synapse/crates/synapse-inference/src/generation/stopping.rs
rs
3,315
bd95d73f9ecc703fd5d3dc3b803d190e52531660f0bccade9e1e352e067eba43
/// Conditions that terminate token generation. pub enum StopCondition { /// Stop when a specific EOS token is generated. EosToken(u32), /// Stop after generating this many tokens (excludes prompt). MaxLength(usize), /// Stop when the generated token sequence contains any of these token-ID subsequen...
eren23/synapse
synapse/crates/synapse-core/src/lib.rs
rs
56,277
77494fc919febd7f8ebcf804c8795e69017f0068569e9341396b909a44095593
//! Safe Rust wrappers around the Zig-backed Synapse FFI tensor library. //! //! Provides RAII-managed [`Tensor`] handles and [`Result`]-based error handling //! over the raw C ABI in `synapse-sys`. use std::fmt; use std::ptr; use synapse_sys as ffi; // ---------------------------------------------------------------...
eren23/synapse
synapse/crates/synapse-sys/build.rs
rs
4,472
c29d85362d7d27fe3be203368170784113e99b2db6f8f8ebe4131cf4e7e11df7
use std::env; use std::path::PathBuf; use std::process::Command; fn main() { let manifest_dir = env::var("CARGO_MANIFEST_DIR").unwrap(); let zig_dir: PathBuf = [&manifest_dir, "..", "..", "zig"].iter().collect(); let zig_dir = zig_dir .canonicalize() .expect("synapse/zig/ directory not foun...
eren23/synapse
synapse/crates/synapse-sys/src/lib.rs
rs
22,277
927525ab11bdc1fd94e16786f0479a233fefae8bb9df4788071eb8417deb0bd7
//! Raw FFI bindings to the Zig-backed Synapse tensor library (`libsynapse_zig.a`). //! //! All functions return `syn_status_t` (i32) error codes. //! Handles are opaque pointers β€” do not dereference or free them directly; //! use the corresponding release/destroy functions. #![allow(non_camel_case_types)] use std::o...
eren23/synapse
synapse/crates/synapse-nn/tests/nn_tests.rs
rs
27,040
6abdf4263ddf7edba060a67b07a452e520c26503e4d3503a180819bc4a4cb397
//! Comprehensive tests for synapse-nn. use synapse_autograd::Tensor; use synapse_nn::module::Module; use synapse_nn::*; // ═══════════════════════════════════════════════════════════════════════ // Init tests // ═══════════════════════════════════════════════════════════════════════ #[test] fn test_xavier_uniform_s...
eren23/synapse
synapse/crates/synapse-nn/benches/cnn_forward.rs
rs
1,535
dbaa95fe1ef340e03fd13bd3ee78101045e5dc08c7743e416717616d3b342396
//! Benchmark: Forward pass of a 5-layer CNN on 32x32x3 input. use criterion::{criterion_group, criterion_main, Criterion}; use synapse_autograd::Tensor; use synapse_nn::module::Module; use synapse_nn::*; fn build_5_layer_cnn() -> Sequential { Sequential::new() .add(Box::new(Conv2d::new(3, 16, (3, 3), (1,...
eren23/synapse
synapse/crates/synapse-nn/src/linear.rs
rs
2,565
ed0e1f43806fdf04061e5715536f40f684706433d220932d96b285526621338a
//! Fully-connected (dense) linear layer: y = xW^T + b use synapse_autograd::Tensor; use crate::init::xavier_uniform; use crate::module::Module; pub struct Linear { pub weight: Tensor, // [out_features, in_features] pub bias: Option<Tensor>, // [out_features] training: bool, } impl Linear { //...
eren23/synapse
synapse/crates/synapse-nn/src/flatten.rs
rs
1,890
bca4bc091e9077d5e68af7705d6e6e3ba839d19c7a99c9084efaf3b926c91c1f
//! Flatten layer: reshapes a contiguous range of dimensions into one. use synapse_autograd::Tensor; use crate::module::Module; pub struct Flatten { pub start_dim: usize, pub end_dim: isize, // -1 means last dim training: bool, } impl Flatten { /// Create a Flatten layer that flattens dimensions [st...
eren23/synapse
synapse/crates/synapse-nn/src/layernorm.rs
rs
7,957
1fa0f723b6d506461b25c482d7e1386c6bbafbf1be5d07408844e9a125f32f62
//! Layer normalization module. use synapse_autograd::Tensor; use crate::module::Module; /// Layer normalization over the last N dimensions. /// /// Normalizes input over the dimensions specified by `normalized_shape`, /// then applies an affine transform: `output = gamma * normalized + beta`. pub struct LayerNorm {...
eren23/synapse
synapse/crates/synapse-nn/src/embedding.rs
rs
2,311
69242a1ab33d01ba4d6e2bbccee86d9277c026d6700571a960389406e664cdd0
//! Embedding layer: lookup table for dense vectors. use synapse_autograd::Tensor; use crate::init::randn; use crate::module::Module; pub struct Embedding { pub weight: Tensor, // [num_embeddings, embedding_dim] pub num_embeddings: usize, pub embedding_dim: usize, /// Indices accessed in the last for...
eren23/synapse
synapse/crates/synapse-nn/src/lib.rs
rs
1,062
794735394c052883c6877c77eee8dd8ebe1bf214b29d22908681f0392034b0f4
pub mod activation; pub mod attention; pub mod batchnorm; pub mod conv; pub mod dropout; pub mod embedding; pub mod flatten; pub mod init; pub mod layernorm; pub mod linear; pub mod module; pub mod pool; pub mod positional; pub mod rnn; pub mod sequential; pub mod transformer; pub use activation::{ReLU, Sigmoid, Softm...
eren23/synapse
synapse/crates/synapse-nn/src/batchnorm.rs
rs
6,594
992c393c33210bcb36f45166a3117b8553399b2ca83ef9d6a750d83bf3cbb877
//! Batch normalization layers: BatchNorm1d, BatchNorm2d. use synapse_autograd::Tensor; use crate::module::Module; // ── BatchNorm1d ─────────────────────────────────────────────────────── /// Batch normalization over a 2D input [N, C] or 3D input [N, C, L]. /// Normalizes over the batch (and spatial) dimensions, p...
eren23/synapse
synapse/crates/synapse-nn/src/attention.rs
rs
20,076
163988d5680eb0e9543b4384a1ed61c095cb92123f8b792eaea28aeeee828a8e
//! Multi-head attention module. use synapse_autograd::Tensor; use crate::dropout::Dropout; use crate::linear::Linear; use crate::module::Module; use crate::positional::RotaryPositionalEmbedding; pub struct MultiHeadAttention { pub d_model: usize, pub n_heads: usize, pub d_head: usize, pub w_q: Linea...
eren23/synapse
synapse/crates/synapse-nn/src/rnn.rs
rs
8,207
eb49a2a1ef3444ba3f41f3787355e27243cf4c7dec66cb8f462218e146c38413
//! Recurrent cells: LSTMCell, GRUCell. use synapse_autograd::Tensor; use crate::init::xavier_uniform; use crate::module::Module; // ── Helper: slice rows from a 2D tensor ────────────────────────────── fn slice_rows(t: &Tensor, row_start: usize, row_end: usize) -> Tensor { let cols = t.shape[1]; let data =...
eren23/synapse
synapse/crates/synapse-nn/src/positional.rs
rs
19,816
1069695454f39195182bdd5e448278b618130042371e6534a0fa633cbb569141
//! Positional encoding modules for sequence models. use synapse_autograd::Tensor; use crate::embedding::Embedding; use crate::module::Module; // ═══════════════════════════════════════════════════════════════════════ // SinusoidalPositionalEncoding // ════════════════════════════════════════════════════════════════...
eren23/synapse
synapse/crates/synapse-nn/src/conv.rs
rs
5,541
426c7582f6173e9868ce9861f0d6092d933a9f5275ff69c539052696a6d68c19
//! 2D Convolution layer with Kaiming initialization. use synapse_autograd::Tensor; use crate::init::kaiming_uniform; use crate::module::Module; pub struct Conv2d { pub weight: Tensor, // [out_channels, in_channels, kernel_h, kernel_w] pub bias: Option<Tensor>, // [out_channels] pub stride: (usize,...
eren23/synapse
synapse/crates/synapse-nn/src/dropout.rs
rs
1,542
c236d4fa16ec96d5344919a8e87fe3d2f3875c235df36e33095830f7ded37b83
//! Dropout layer: randomly zeros elements during training. use rand::Rng; use synapse_autograd::Tensor; use crate::module::Module; pub struct Dropout { pub p: f32, // probability of dropping training: bool, } impl Dropout { /// Create a Dropout layer with drop probability `p`. pub fn new(p: f32) ->...
eren23/synapse
synapse/crates/synapse-nn/src/module.rs
rs
2,433
02fc644a3d774f353817a8a5974034f334e399a02f55b328d9bed4548361fc5f
//! Module trait and ModuleList container. use synapse_autograd::Tensor; /// Core trait for all neural network layers. pub trait Module { /// Compute the forward pass. fn forward(&self, input: &Tensor) -> Tensor; /// Return references to all learnable parameters. fn parameters(&self) -> Vec<&Tensor>;...
eren23/synapse
synapse/crates/synapse-nn/src/pool.rs
rs
8,639
9d0be4b3bc9fbaee20429b71c79cedd1583b465f304f7e820c4f40972ab94bdb
//! Pooling layers: MaxPool2d, AvgPool2d, AdaptiveAvgPool2d. use synapse_autograd::Tensor; use crate::module::Module; // ── MaxPool2d ───────────────────────────────────────────────────────── pub struct MaxPool2d { pub kernel_size: (usize, usize), pub stride: (usize, usize), pub padding: (usize, usize),...
eren23/synapse
synapse/crates/synapse-nn/src/init.rs
rs
3,470
953c03d7f7be90b6b6cd0e848be7b0ec5189084e364f0e6f1b52783f3f5ff88f
//! Weight initialization strategies (Xavier/Glorot, Kaiming/He). use rand::Rng; use rand_distr::{Distribution, Normal, Uniform}; use synapse_autograd::Tensor; /// Calculate fan_in and fan_out from a weight tensor shape. /// For 2D [out, in]: fan_in=in, fan_out=out /// For 4D [out, in, kH, kW]: fan_in=in*kH*kW, fan_o...
eren23/synapse
synapse/crates/synapse-nn/src/transformer.rs
rs
29,618
fcec01e076659ca92573d45e65faaffcca0ad495d2a8874bb7bdc87f72b27aee
//! Transformer encoder and decoder blocks (pre-norm architecture). use synapse_autograd::Tensor; use crate::attention::MultiHeadAttention; use crate::dropout::Dropout; use crate::layernorm::LayerNorm; use crate::linear::Linear; use crate::module::Module; // ── Activation enum ───────────────────────────────────────...
eren23/synapse
synapse/crates/synapse-nn/src/sequential.rs
rs
1,677
e6378e115866d77e74795c9365f41887361afc7d243ec2edd007082b583b351b
//! Sequential container: chains modules in order. use synapse_autograd::Tensor; use crate::module::Module; pub struct Sequential { layers: Vec<Box<dyn Module>>, training: bool, } impl Sequential { pub fn new() -> Self { Sequential { layers: Vec::new(), training: true, ...
eren23/synapse
synapse/crates/synapse-nn/src/activation.rs
rs
3,803
8f6468cd715bd65ae2b470f3307bf207fcfb14a23afcdb96870347b7cf62022e
//! Activation function modules: ReLU, Sigmoid, Tanh, GELU, Softmax. use synapse_autograd::Tensor; use crate::module::Module; // ── ReLU ────────────────────────────────────────────────────────────── pub struct ReLU { training: bool, } impl ReLU { pub fn new() -> Self { ReLU { training: true } ...
eren23/synapse
synapse/crates/synapse-graph/tests/graph_optimization.rs
rs
35,360
ea50f35f7dc77578ab42a2d77c4fdd5914919028cf29269f985b70fa7fb1bbb8
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/crates/synapse-graph/src/ir.rs
rs
27,547
30b72009b2e3d9e276ec818bab4a7850783c9e45d93cbf6e2e3d4ea37d71f70a
use std::collections::{HashMap, HashSet}; use std::fmt; /// Unique identifier for a node in the graph. #[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, PartialOrd, Ord)] pub struct NodeId(pub usize); /// Data types supported by the graph IR. #[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)] pub enum DType { F32...
eren23/synapse
synapse/crates/synapse-graph/src/constant_fold.rs
rs
6,723
cb4aa82641c96fd496af834b0bbe08103e64ff01d6471cf61a353c8707d3d099
use std::collections::HashMap; use crate::ir::{Graph, NodeId, NodeKind}; use crate::pass::OptimizationPass; /// Folds subgraphs where all inputs are constants into a single Constant node. pub struct ConstantFolding; impl ConstantFolding { pub fn new() -> Self { Self } /// Check if all inputs to ...
eren23/synapse
synapse/crates/synapse-graph/src/pass.rs
rs
1,152
8917d330ee555b1eaff341007687c03d53d81a8195004a254eed499e7eac4498
use crate::ir::Graph; /// Trait for optimization passes that transform a graph. pub trait OptimizationPass { /// A human-readable name for this pass. fn name(&self) -> &str; /// Apply the pass to the graph, returning true if the graph was modified. fn run(&self, graph: &mut Graph) -> bool; } /// Run ...
eren23/synapse
synapse/crates/synapse-graph/src/lib.rs
rs
587
854a20880c6198501f7648a5eddf503ea2f2a1c37cd64f4ff4b28327dec43643
pub mod constant_fold; pub mod dead_code; pub mod fuse_attention; pub mod fuse_layernorm_residual; pub mod fusion; pub mod ir; pub mod pass; pub mod scheduler; pub use constant_fold::ConstantFolding; pub use dead_code::DeadCodeElimination; pub use fuse_attention::FuseAttention; pub use fuse_layernorm_residual::FuseLay...
eren23/synapse
synapse/crates/synapse-graph/src/dead_code.rs
rs
4,628
e8c14a602e108766502e0a121a6c94843d4af15d55e3b83f1f6a7b70172aaa72
use std::collections::HashSet; use crate::ir::{Graph, NodeId}; use crate::pass::OptimizationPass; /// Removes nodes that are not reachable from any graph output. pub struct DeadCodeElimination; impl DeadCodeElimination { pub fn new() -> Self { Self } /// Collect all node ids reachable from the g...
eren23/synapse
synapse/crates/synapse-graph/src/scheduler.rs
rs
14,753
0e75f10992a1200f27a056e05d383beec4307a389721070a363ac40cc7ca50eb
use std::collections::{HashMap, HashSet}; use crate::ir::{Graph, NodeId}; use crate::pass::OptimizationPass; /// Schedules nodes in a memory-optimal execution order using liveness analysis. /// /// The scheduler produces a valid topological ordering that minimizes peak memory /// by preferring to schedule nodes whose...
eren23/synapse
synapse/crates/synapse-graph/src/fusion.rs
rs
19,858
71c5c25e78e799aaf501de135b325d0efc8addfa24dd321b35526c012042fe01
use crate::ir::{Graph, NodeId, NodeKind, NodeMeta, OpKind}; use crate::pass::OptimizationPass; // ── MatMul + Bias + ReLU Fusion ──────────────────────────────────────── /// Fuses a MatMul -> Add (bias) -> ReLU pattern into FusedMatMulBiasRelu. pub struct FuseMatMulBiasRelu; impl FuseMatMulBiasRelu { pub fn new(...
eren23/synapse
synapse/crates/synapse-graph/src/fuse_layernorm_residual.rs
rs
8,234
c3cf12d625c709468ad668c18bf05528c004ea61289dcbd35b1c9eb329289eea
use crate::ir::{Graph, NodeId, NodeKind, OpKind}; use crate::pass::OptimizationPass; /// Fuses Add(x, residual) -> LayerNorm into a single FusedLayerNormResidual node. /// /// Detected pattern: /// sum = Add(x, residual) /// output = LayerNorm(sum, gamma, beta) /// /// Replaces with: FusedLayerNormResidual(x, resi...
eren23/synapse
synapse/crates/synapse-graph/src/fuse_attention.rs
rs
13,354
d9bd9e839f26ce45b8ff47892327ba61382ed621c959e00d5fa6fb246089e531
use crate::ir::{Graph, NodeId, NodeKind, OpKind}; use crate::pass::OptimizationPass; /// Fuses the multi-head attention pattern into a single FusedAttention node. /// /// Detected pattern: /// q = MatMul(input, W_q) /// k = MatMul(input, W_k) /// k_t = Transpose(k) /// scores = MatMul(q, k_t) /// scaled = Mu...
eren23/synapse
synapse/crates/synapse-autograd/tests/autograd_correctness.rs
rs
13,860
1e2e1bc75ed29c6d22b42e54a303dbd6125563d2ce2a950440c54fd83f6699c1
use std::time::Instant; use synapse_autograd::{backward, grad_check, Graph, NoGradGuard, Tensor}; // ── Helper: deterministic pseudo-random data ─────────────────────── fn pseudo_rand(n: usize, offset: usize) -> Vec<f32> { (0..n) .map(|i| { let v = ((i + offset) * 2654435761) as f32; // Knuth ...
eren23/synapse
synapse/crates/synapse-autograd/src/graph.rs
rs
3,962
e416449ab9f689395c595029c5e696b04c2556221c020d4cc3206f34c964176d
use std::collections::HashMap; use crate::function::GradFn; use crate::no_grad::is_grad_enabled; use crate::tensor::Tensor; use crate::variable::{Variable, VariableId}; /// A node in the computation graph. pub struct Node { /// Backward function (None for leaf variables). pub grad_fn: Option<Box<dyn GradFn>>,...
eren23/synapse
synapse/crates/synapse-autograd/src/lib.rs
rs
5,022
ba294e9941681f25a8d0717a2350d5c8761bfb2700100752061df1956cdf3a60
pub mod backward; pub mod function; pub mod grad_check; pub mod graph; pub mod no_grad; pub mod ops; pub mod tensor; pub mod variable; pub use backward::backward; pub use function::GradFn; pub use grad_check::grad_check; pub use graph::Graph; pub use no_grad::{is_grad_enabled, NoGradGuard}; pub use tensor::Tensor; pub...
eren23/synapse
synapse/crates/synapse-autograd/src/no_grad.rs
rs
816
63860c1c6d0c5c6a9196d96494ba64841810de1a1b3204fd02d4964e3d9d4a37
use std::cell::Cell; thread_local! { static GRAD_ENABLED: Cell<bool> = const { Cell::new(true) }; } /// Returns whether gradient tracking is currently enabled. pub fn is_grad_enabled() -> bool { GRAD_ENABLED.with(|f| f.get()) } /// RAII guard that disables gradient tracking for its lifetime. /// /// Supports...
eren23/synapse
synapse/crates/synapse-autograd/src/function.rs
rs
374
fc357deeba19dd7e22632a704c3167e667aca095641fa93e808611159fe96bee
use crate::tensor::Tensor; use crate::variable::VariableId; /// Backward function for a computation graph node. pub trait GradFn { /// Compute gradients w.r.t. each input given the output gradient. fn backward(&self, grad_output: &Tensor) -> Vec<Option<Tensor>>; /// Return the variable IDs of inputs to thi...