惯性聚合 高效追踪和阅读你感兴趣的博客、新闻、科技资讯
阅读原文 在惯性聚合中打开

推荐订阅源

AI
AI
OSCHINA 社区最新新闻
OSCHINA 社区最新新闻
D
Docker
Last Week in AI
Last Week in AI
Apple Machine Learning Research
Apple Machine Learning Research
WordPress大学
WordPress大学
F
Full Disclosure
博客园 - 【当耐特】
博客园 - 司徒正美
V
Visual Studio Blog
F
Fortinet All Blogs
T
Tor Project blog
T
Threatpost
Blog — PlanetScale
Blog — PlanetScale
月光博客
月光博客
C
Cyber Attacks, Cyber Crime and Cyber Security
阮一峰的网络日志
阮一峰的网络日志
GbyAI
GbyAI
cs.CL updates on arXiv.org
cs.CL updates on arXiv.org
T
Tenable Blog
M
MIT News - Artificial intelligence
L
Lohrmann on Cybersecurity
P
Palo Alto Networks Blog
I
Intezer
Stack Overflow Blog
Stack Overflow Blog
The Register - Security
The Register - Security
The Last Watchdog
The Last Watchdog
S
Securelist
T
Tailwind CSS Blog
V
Vulnerabilities – Threatpost
U
Unit 42
博客园 - 叶小钗
P
Proofpoint News Feed
C
Cybersecurity and Infrastructure Security Agency CISA
H
Help Net Security
Cyber Security Advisories - MS-ISAC
Cyber Security Advisories - MS-ISAC
酷 壳 – CoolShell
酷 壳 – CoolShell
Hacker News - Newest:
Hacker News - Newest: "LLM"
NISL@THU
NISL@THU
J
Java Code Geeks
H
Hackread – Cybersecurity News, Data Breaches, AI and More
SecWiki News
SecWiki News
www.infosecurity-magazine.com
www.infosecurity-magazine.com
Project Zero
Project Zero
T
The Exploit Database - CXSecurity.com
TaoSecurity Blog
TaoSecurity Blog
A
Arctic Wolf
Martin Fowler
Martin Fowler
T
Threat Research - Cisco Blogs
N
News | PayPal Newsroom

DEV Community

Authentication Security Deep Dive: From Brute Force to Salted Hashing (With Java Examples) Why AI Systems Don’t Fail — They Drift Spilling beans for how i learn for exam😁"Reinforcement Learning Cheat Sheet" I Replaced Chrome with Safari for AI Browser Automation. Here's What Broke (and What Finally Worked) How Python Borrows Other People's Work The $40 Architecture: Processing 1 Billion API Requests with 99.99% Uptime Vibe Coding: A Workflow Guide (From Zero to SaaS) Most webhook security guides protect the wrong side. The scary part is delivery. Headless CMS for TanStack Start: Build a Blog with Cosmic EU Age Verification App "Hacked in 2 Minutes" — What Actually Happened Comfy Cloud’s delete function does not actually remove files Running AI Models on GPU Cloud Servers: A Beginner Guide Event-driven media intelligence with AWS Step Functions and Bedrock I scored 500 AI prompts across 8 quality dimensions — here's what broke How to Call Google Gemini API from Next.js (Free Tier, No Backend Needed) The Portal Protocol: Reclaiming Human Connection in the Age of AI How to Fix Your Team's Scattered Knowledge Problem With a Self-Hosted Forum Intro to tc Cloud Functors: A Graph-First Mental Model for the Modern Cloud Designing Multi-Tenant Backends With Both Ownership and Team Access I Built a Neumorphic CSS Library with 77+ Components — Here's What I Learned PostgreSQL Performance Optimization: Why Connection Pooling Is Critical at Scale Cómo construí un SaaS multi-rubro para gestionar expensas en Argentina con FastAPI + Vue 3 🚀 I Built an Ethical Hacking Scanner Tool – Open Source Project I Replaced /usage and /context in Claude Code With a Single Statusline A Pythonic Way to Handle Emails (IMAP/SMTP) with Auto-Discovery and AI-Ready Design I Collected 8.9 Million Polymarket Price Points — Here's What I Found About How Markets Really Move EcoTrack AI — Carbon Footprint Tracker & Dashboard Everyone's Using AI. No One Agrees How. 5 self-hosted ebook managers worth trying in 2026 Building Your First AI Agent with LangChain: From Chatbot to Autonomous Assistant Common SOC 2 Failures (Real World) Stop Vibe-Checking Your AI App: A Practical Guide to Evals How to Use SonarQube and SonarScanner Locally to Level Up Your Code Quality Your Next To-Do App Is Dead — I Replaced Mine with an OpenClaw AI Sign a Nostr event in 60 lines of Python using coincurve — no nostr-sdk, no nbxplorer, no rust toolchain ITGC Audit Explained Like You’re in Big 4 Patch Tuesday abril 2026: Microsoft parcha 163 vulnerabilidades y un zero-day en SharePoint Stop scraping everything: a better way to track competitor price changes Listing on MCPize + the Official MCP Registry while routing payments OUTSIDE the marketplace — how I kept 100% of my x402 revenue Building an AI-Powered Risk Intelligence System Using Serverless Architecture Why We Ripped Function Overloading Out of Our AI Toolchain Testing AI-Generated Code: How to Actually Know If It Works SaaS Churn Is Killing Your Business. Here Is What to Do About It (Without a Support Team) The Speed of AI Is No Longer Linear - And Self-Improving Models Are Why How to Implement RBAC for MCP Tools: A Practical Guide for Engineering Teams From Standard Quote to Persuasive Proposal: AI Automation for Arborists I built a CLI that scaffolds complete multi-tenant SaaS apps Axios CVE-2025–62718: The Silent SSRF Bug That Could Be Hiding in Your Node.js App Right Now The dashboard that ended our friendship Data Pipelines Explained Simply (and How to Build Them with Python) The Hidden Cost of AI Systems Nobody Talks About. undefined vs undeclared, and how typeof behaves Switching from file-based jobs to NATS/Kafka in Rust without changing code io_uring Adventures: Rust Servers That Love Syscalls Why Agentic AI is Killing the Traditional Database The POUR principles of web accessibility for developers and designers Quantum Neural Network 3D — A Deep Dive into Interactive WebGL Visualization How To Install Caveman In Codex On macOS And Windows Automation Pipeline Reliability: Why Your Workflow Breaks When Nobody Is Watching I Built an 'Open World' AI Coding Agent — It Works From ANY Folder From Freelancing to Product: A Tech Service Company's SaaS Transformation China's AI Giants: Adding Tencent Hunyuan & ByteDance Doubao to AI University (74 Providers) On the Vibe Coders and Their Lies clerk: Auto-Summarize Your Claude Code Sessions AI Weekly — 2026/04/10–04/17 | The Model Lockdown Is Here, but the Toolchain Is the Real Battleground AI 週報 — 2026/04/10–2026/04/17 模型封鎖潮來了,但工具鏈才是真戰場 Maybe this is how Open-Source apps are born... 🚀 Fine-Tune LLMs with LoRA and QLoRA: 2026 Guide tRPC v11 + Next.js App Router: End-to-End Type Safety Without the Boilerplate ShadCN UI in 2026: Why I Stopped Installing Component Libraries and Started Owning My Components SaaS Billing in React Server Components: Stripe + Supabase Without a Single `useEffect` Join our DEV Weekend Challenge — $1,000 in Prizes Across TEN winners! Submissions Due April 20 at 6:59 AM UTC. Implementing FSRS Spaced Repetition in Flutter + Supabase — Adding Memory Science to an AI Learning App "I Texted My Localhost From the Train — Claude Code Fixed the Bug Before I Got Home" I Built a Sales Prep AI and It Went Deeper Than Expected Design to Code #2: One JSON, Eleven Outputs Solving the 100M-Row Problem: A Summary Table Pattern for High-Volume Push Notification Logs Flutter Web With Wasm: What Actually Changes For Developers I Built 50 Royalty-Free Soundtracks for My Side Project in a Weekend Using AI Music Generation The Vibe Coding Security Checklist: 7 Things to Check Before You Ship Stop Letting Googlebot Guess Fix Your React App's SEO Right Desconstruindo o Streaming do LinkedIn: Como Criar um Engine de Extração de Vídeo de Alta Performance com HLS e FFmpeg (EDA Part-1) EDA (Exploratory Data Analysis) Explained With Real Life — Why Looking at Your Data Is the Most Important Step in Machine Learning Brand Relationship Management at Scale: Our 4-Touch Outreach System for 200+ Brands Why String.fromEnvironment() Might Return an Empty String in Dart JGuardrails 1.0.0 — Hardening Java LLM Apps Against Jailbreaks, Toxicity, and Prompt Injection Plan and Schedule a Full Week of Threads Content From One Claude Conversation Coding Cat Oran Ep3, Five Tables Changed Everything Updated: BFF Pattern I'm done watching freelancers get buried by 200 proposals. So I'm building the alternative. This is my first post BFS Algorithm in Java Step by Step Tutorial with Examples Tracking LLM Pricing Monthly: An Open Dataset for 22 AI Models How We Measure Content ROI on a Comparison Site: Revenue Attribution Without Perfect Data Introducing Nova AI Ops: The AI-Native Operating System for SRE Teams I built a free desktop video downloader for Windows — Grabbit How Talkie OCR Helps Vision-Impaired & Dyslexic Users Read the World Around Them VRCFaceTracking安装和iPhone面捕配置教程,有bug Even CrowdStrike Can't See Your Agents The Automation Gold Rush: What n8n Workflows and Claude Are Opening Up for Developers Right Now
I Built a Neural Network from Scratch in Rust — Then Compiled It to WebAssembly
Thomas Cheri · 2026-05-29 · via DEV Community

A complete ML pipeline: engine, backprop, binary format, and a live browser demo. Zero dependencies. Under 200 KB total.


If you have built machine-learning projects before, you have probably done it by importing PyTorch, TensorFlow, or scikit-learn and calling .fit(). Those are excellent libraries. This article is about what happens when you deliberately do not use them — when you build every piece of the pipeline yourself, in a language that compiles to WebAssembly, and the result runs live in the browser with no server, no Python, and no cloud bill.

Here is the live demo: move four sliders, watch the predicted Iris species update in real time. The model is running entirely inside your browser tab, loaded from a 1.1 KB binary file, powered by ~100 KB of WebAssembly compiled from pure Rust.

This is the story of how I built it and why the engineering choices made it work.


Why Rust? Why WebAssembly? Why zero dependencies?

Three constraints drove every design decision.

WASM requires no_std or a carefully limited std. The wasm32-unknown-unknown target has no operating system, no file system, and no libc. A crate that links against rand, ndarray, or any library that makes OS calls will not compile to it without significant plumbing. An engine built from nothing but the Rust standard library compiles cleanly to every target, including WASM.

A zero-dependency std-only crate is uniquely auditable. There are no transitive dependency trees to vet, no supply-chain risks, no version conflicts. Every line of code that runs in the user's browser lives in this repository.

The deployment story becomes the technical story. A 100 KB WASM blob that runs locally in the browser is not just a cost optimisation — it is a privacy guarantee (user inputs never leave the machine) and a latency guarantee (inference is microseconds, not a round trip to a cloud API). That story is only possible because the engine has no external dependencies that would bloat the binary.


The architecture: eight modules, strictly layered

The engine is a Cargo workspace with four crates. The core library, ferrum_core, contains twelve modules arranged in a strict dependency stack — each module imports only from those above it. There are no cycles, no forward references.

error      ← single InferError enum, Result<T> alias
tensor     ← Tensor: flat Vec<f32> + shape, row-major
ops        ← matmul (i-k-j order), bias-add, transpose, argmax, softmax
activation ← ReLU, Sigmoid, Tanh, Softmax, Identity (serialisable enum)
layer      ← Layer trait, Linear (y = xW+b), ActivationLayer
model      ← Sequential: Vec<Box<dyn Layer>>, forward()
rng        ← seeded xorshift64* PRNG, Box-Muller normal samples
loss       ← fused softmax cross-entropy + analytic gradient
optim      ← SGD with momentum, stateless over parameters
csv        ← numeric CSV parser, z-score Normalizer, train/val split
train      ← DenseT, ReluT, Net (trainable MLP), backpropagation
loader     ← FINF v2 binary format: weights + normalizer in one file

Enter fullscreen mode Exit fullscreen mode

You can read these files in order and the entire engine unfolds with no surprises.


The tensor: deliberately minimal

pub struct Tensor {
    pub shape: Vec<usize>,
    pub data:  Vec<f32>,
}

Enter fullscreen mode Exit fullscreen mode

That is the whole data model. A 3×4 matrix is twelve contiguous floats. A vector is the same thing with a one-element shape. There is no broadcasting, no views, no strides, no GPU. Every operation returns a new Tensor rather than mutating in place. This costs allocations and buys clarity: the data flow through the network is always explicit.

The key primitive is map:

pub fn map<F: Fn(f32) -> f32>(&self, f: F) -> Tensor {
    Tensor {
        shape: self.shape.clone(),
        data: self.data.iter().copied().map(f).collect(),
    }
}

Enter fullscreen mode Exit fullscreen mode

This single method is the entire mechanism behind ReLU, Sigmoid, and Tanh.


The matmul: cache-friendly loop order

The matrix multiply is the performance-critical operation and the one place where a single implementation choice makes a real difference.

The textbook i-j-k loop order — for each output element (i,j), dot the i-th row of A with the j-th column of B — reads B in column-major order, which is cache-unfriendly for a row-major matrix.

The i-k-j order walks both B and the output buffer contiguously in the innermost loop:

for i in 0..m {
    let a_row = i * ka;
    let o_row = i * n;
    for k in 0..ka {
        let a_ik = a.data[a_row + k];
        let b_row = k * n;
        for j in 0..n {
            out[o_row + j] += a_ik * b.data[b_row + j];
        }
    }
}

Enter fullscreen mode Exit fullscreen mode

Same FLOP count. Meaningfully better cache behaviour. This is not BLAS — it is still naive single-threaded loops — but it is the right naive implementation.


The loss function: why fusion matters

For a classifier, the natural loss is cross-entropy applied to a softmax output. Most introductions compute them separately. There is a strong reason not to.

If p = softmax(z) and the true class is t, the gradient of cross-entropy loss with respect to the logits z is:

dL/dz = (p - onehot(t)) / batch_size

Enter fullscreen mode Exit fullscreen mode

That is it. No chain rule composition, no softmax Jacobian, no numerical instability from computing log(softmax(z)) via two separate steps. The gradient is the predicted probabilities minus the one-hot target, scaled by batch size. This is why every layer below the loss in the network never needs to know what a softmax derivative looks like.

The implementation computes the stable softmax (max-subtracted before exponentiating), the negative log-likelihood of the true class, and this gradient in a single pass over the batch.

The correctness of this gradient is verified by a finite-difference check in the test suite: every logit is perturbed by ε, the actual change in loss is measured, and the result is compared to the analytic gradient element-by-element.


Backpropagation by hand

The trainable network is a separate set of types from the inference engine. DenseT and ReluT mirror their inference counterparts but cache intermediate values for the backward pass.

For a dense layer y = xW + b, the backward pass is three expressions:

self.grad_w = matmul(&transpose(x)?, dy)?;   // dL/dW = x^T · dy
self.grad_b = sum_axis0(dy)?;                 // dL/db = Σ_rows(dy)
// return:
matmul(dy, &transpose(&self.weight)?)         // dL/dx = dy · W^T

Enter fullscreen mode Exit fullscreen mode

For a ReLU layer, the backward pass is one expression. The forward pass caches a 0/1 mask of which inputs were positive — that mask is exactly ReLU's local derivative:

ops::mul(dy, mask)  // gate the gradient

Enter fullscreen mode Exit fullscreen mode

The gradient check test perturbs individual weights by ε = 0.001, measures (L(w+ε) - L(w-ε)) / 2ε, and confirms it matches the analytic gradient to within 0.01. If the calculus were wrong, this test would catch it.


The model file: a custom binary format

Real engines use GGUF, SafeTensors, or ONNX. To stay dependency-free, I defined a minimal binary format called FINF (version 2) and serialised it by hand.

The key design choice: the normalizer statistics (per-column mean and standard deviation) are embedded in the same file as the model weights. Inference requires normalising input features with the exact statistics used during training. A model that was trained on standardised data but receives raw values at inference will silently produce wrong predictions. Embedding both in one file makes this mistake structurally impossible: there is nothing to forget to load separately.

4 bytes  b"FINF"                  ← magic number
u32      version = 2
u32      normalizer_byte_length
[bytes]  "mean0,std0;mean1,std1;…" ← normalizer stats
u32      num_layers
per layer:
  u8     tag: 0=Linear, 1=Activation
  ...    layer parameters

Enter fullscreen mode Exit fullscreen mode

The reader is a forward-only bounds-checked cursor. Truncated or corrupt files return a Format error rather than panicking or reading out of bounds.


The WASM bindings

The deployment crate, iris_wasm, exposes a single class to JavaScript:

#[wasm_bindgen]
pub struct IrisClassifier {
    model: Sequential,
    norm:  Normalizer,
}

#[wasm_bindgen]
impl IrisClassifier {
    #[wasm_bindgen(constructor)]
    pub fn new(model_bytes: &[u8]) -> Result<IrisClassifier, JsValue> { ... }

    pub fn predict(&self, sl: f32, sw: f32, pl: f32, pw: f32) -> Result<String, JsValue> { ... }
}

Enter fullscreen mode Exit fullscreen mode

new takes the raw bytes of the FINF file (fetched via fetch() in JavaScript) and deserialises them. predict normalises the four slider values using the embedded statistics, runs a forward pass, and returns a JSON string with the predicted class index, name, and all three probabilities.

The JavaScript side is equally minimal — an ES module, no bundler, no framework:

import init, { IrisClassifier } from './pkg/iris_wasm.js';

await init();
const bytes = new Uint8Array(await (await fetch('model.bin')).arrayBuffer());
const classifier = new IrisClassifier(bytes);

slider.addEventListener('input', () => {
    const result = JSON.parse(classifier.predict(sl, sw, pl, pw));
    updateUI(result);
});

Enter fullscreen mode Exit fullscreen mode


The numbers

Property Value
Architecture 4 → 32 (ReLU) → 3 (Softmax)
Trainable parameters 259
Dataset UCI Iris, 150 examples
Full-dataset accuracy 99.3%
Training time ~2 seconds, single-threaded
Model file size 1,161 bytes
WASM binary ~100 KB
Total page weight ~118 KB (less than one JPEG)
External dependencies 0
Tests 110 (0 failures)

What the test suite covers

The 110-test suite is worth describing because it covers correctness at every level:

Unit tests (84) — every module tested in isolation. Highlights: the finite-difference gradient check proves the loss function's calculus is correct; the tag_roundtrips_all_variants test proves the serialisation enum never silently mis-maps; the normalizer_zero_mean_unit_std test verifies that fit-and-transform produces genuinely standardised data.

WASM glue tests (5) — the bindings layer tested natively: load from bytes, infer, verify probability distribution, check argmax range, reject corrupt input.

Integration tests (21) — the complete pipeline: parse the real UCI Iris CSV, normalise, train from scratch, serialise, deserialise, infer on known samples. These tests include setosa_textbook_sample and virginica_textbook_sample which assert that specific well-known Iris measurements produce the correct predicted species.


Deployment in three commands

# Train (produces model.bin in ~2 seconds)
cargo run -p train --release

# Compile to WASM
cargo build -p iris_wasm --target wasm32-unknown-unknown --release
wasm-bindgen target/wasm32-unknown-unknown/release/iris_wasm.wasm \
  --out-dir web/pkg --target web --no-typescript

# Copy model and serve
cp model.bin web/model.bin
cd web && python3 -m http.server 8080

Enter fullscreen mode Exit fullscreen mode

GitHub Pages deployment is three more steps: push the web/ directory, enable Pages, get a permanent HTTPS URL. The included DEPLOYMENT.md has the full GitHub Actions workflow for continuous deployment.


The engineering lessons

Separation of concerns is testable. Because every arithmetic operation lives in ops.rs, every activation in activation.rs, and the loss gradient in loss.rs, the finite-difference gradient check can verify the math without touching any other module.

Embedding the normalizer in the model file eliminates a whole class of bugs. This seems like a small detail. It is not. Preprocessing statistics are the most commonly forgotten artifact when deploying a model, and a model that receives un-normalised inputs fails silently.

The i-k-j loop order for matmul is a free speedup. It is the same code length as the naive order, just with the k and j loops swapped. Any ML engine that does its own matrix multiply should use it.

WASM deployment is simpler than it looks. The hard part is not the WASM compilation — cargo build --target wasm32-unknown-unknown is one command. The hard part is having a codebase that compiles to that target in the first place, which requires zero OS dependencies. The architectural constraint and the deployment story are the same constraint.


What's next

The engine is designed so each kind of extension touches exactly one module:

  • New activationactivation.rs (add variant, tag, apply arm)
  • New layerlayer.rs + loader.rs (tag bytes)
  • New lossloss.rs (return (scalar, gradient))
  • New optimizeroptim.rs (Adam, RMSProp)
  • Faster kernelsops.rs only (SIMD, rayon, BLAS)
  • Bigger modelcsv.rs for a new featurizer, everything else unchanged

The repository will soon be on GitHub. I will update the link here once it goes live. The web/ directory is self-contained: copy it to any static host and you have a live demo immediately.


Built with Rust 1.95, wasm-bindgen 0.2.122, and the UCI Iris dataset from UC Irvine Machine Learning Repository.