larzneural
Autodiff and a tiny neural net, from scratch.
Every number is a Value node that remembers how it was computed - build any expression from add()/mul()/tanh()/relu(), call backward(), and every input's real partial derivative fills in. The same reverse-mode automatic differentiation every deep learning framework runs, shown at the scalar level where you can watch it happen.
larzscript pkg install neural
What you get
- Reverse-mode autodiff (real backward())
- Value graph: add/mul/pow/tanh/relu
- A tiny trainable MLP built on it
- Watch gradients flow, node by node
Try it
import "neural" as nn
import "random" as rng
let a = nn.value(-4.0)
let b = nn.value(2.0)
let c = nn.add(nn.mul(a, b), nn.tanh_(b))
nn.backward(c)
print("c =", round(c["data"], 4), "dc/da =", round(a["grad"], 4), "dc/db =", round(b["grad"], 4))
rng.seed(1)
let m = nn.mlp(2, [4, 1])
let xs = [[-1.0,-1.0],[-1.0,1.0],[1.0,-1.0],[1.0,1.0]]
let ys = [-1.0, 1.0, 1.0, -1.0]
fn loss_for(m, xs, ys) {
let total = nn.value(0.0)
let i = 0
while i < len(xs) {
let out = nn.mlp_call(m, [nn.value(xs[i][0]), nn.value(xs[i][1])])[0]
let diff = nn.sub(out, nn.value(ys[i]))
total = nn.add(total, nn.mul(diff, diff))
i = i + 1
}
return total
}
print("loss before training:", round(loss_for(m, xs, ys)["data"], 3))
let step_i = 0
while step_i < 100 {
let params = nn.parameters(m)
nn.zero_grad(params)
nn.backward(loss_for(m, xs, ys))
nn.step(params, 0.1)
step_i = step_i + 1
}
print("loss after training:", round(loss_for(m, xs, ys)["data"], 3))Output
c = -7.036 dc/da = 2 dc/db = -3.9293 loss before training: 4.107 loss after training: 0
Why it's in the Larz Stack
larzneural is a real Larzscript package (larzscript pkg install neural) - money-native, zero dependencies, the same language as the rest of the estate, not a separate Python runtime. It composes with the rest of the Larz Stack and the Larz framework.