add Backprop

This commit is contained in:
Bogdan Buduroiu 2026-06-09 18:19:07 +03:00
commit eab7825fed
Signed by: bogdan
GPG key ID: F71EF75A4C09A095
2 changed files with 110 additions and 37 deletions

View file

@ -68,7 +68,7 @@ pub fn Value(comptime T: type) type {
return v;
}
fn backprop_value(self: *Self) *Self {
fn backprop_value(self: *Self) void {
switch (self.expr) {
.nop => {},
.unary => |u| {
@ -90,22 +90,22 @@ pub fn Value(comptime T: type) type {
}
fn unary(value: T, op: UnaryType, arg0: *Self) *Self {
create(value, Expr{ .unary = .{
return create(value, Expr{ .unary = .{
.op = op,
.args = [1]*Self{arg0},
} });
}
fn binary(value: T, op: BinaryType, arg0: *Self, arg1: *Self) *Self {
create(value, Expr{
return create(value, Expr{ .binary = .{
.op = op,
.args = [2]*Self{ arg0, arg1 },
});
} });
}
pub fn add(self: *Self, other: anytype) *Self {
switch (@TypeOf(other)) {
*Self => binary(self.data + other.data, .add, self, other),
*Self => return binary(self.data + other.data, .add, self, other),
else => {
const o = new(other);
return binary(self.data + o.data, .add, self, o);
@ -113,13 +113,13 @@ pub fn Value(comptime T: type) type {
}
}
fn add_back(self: *Self) void {
self.expr.binary.args[0].data += self.grad;
self.expr.binary.args[1].data += self.grad;
self.expr.binary.args[0].grad += self.grad;
self.expr.binary.args[1].grad += self.grad;
}
pub fn sub(self: *Self, other: anytype) *Self {
switch (@TypeOf(other)) {
*Self => binary(self.data - other.data, .sub, self, other),
*Self => return binary(self.data - other.data, .sub, self, other),
else => {
const o = new(other);
return binary(self.data - o.data, .sub, self, o);
@ -127,11 +127,11 @@ pub fn Value(comptime T: type) type {
}
}
fn sub_back(self: *Self) void {
self.expr.binary.args[0].data += self.grad;
self.expr.binary.args[1].data -= self.grad;
self.expr.binary.args[0].grad += self.grad;
self.expr.binary.args[1].grad -= self.grad;
}
pub fn mul(self: *Self, other: anytype) !void {
pub fn mul(self: *Self, other: anytype) *Self {
switch (@TypeOf(other)) {
*Self => return binary(self.data * other.data, .mul, self, other),
else => {
@ -140,15 +140,15 @@ pub fn Value(comptime T: type) type {
},
}
}
fn mul_back(self: *Self) *Self {
self.expr.binary.args[0].data = self.grad * self.expr.binary.args[1].data;
self.expr.binary.args[1].data = self.grad * self.expr.binary.args[0].data;
fn mul_back(self: *Self) void {
self.expr.binary.args[0].grad += self.grad * self.expr.binary.args[1].data;
self.expr.binary.args[1].grad += self.grad * self.expr.binary.args[0].data;
}
pub fn div(self: *Self, other: anytype) *Self {
switch (@TypeOf(other)) {
*Self => self.mul(other.pow(-1)),
else => self.mul(new(other).pow(-1)),
*Self => return self.mul(other.pow(-1)),
else => return self.mul(new(other).pow(-1)),
}
}
@ -156,7 +156,7 @@ pub fn Value(comptime T: type) type {
switch (@TypeOf(other)) {
*Self => {
switch (other.expr) {
.nop => binary(std.math.pow(T, self.data, other.data), .pow, self, other),
.nop => return binary(std.math.pow(T, self.data, other.data), .pow, self, other),
else => {
@panic("Only Values with nop type are supported as exponents.");
},
@ -176,17 +176,17 @@ pub fn Value(comptime T: type) type {
}
}
fn pow_back(self: *Self) void {
const self_data = self.expr.binary.args[0];
const other_data = self.expr.binary.args[1];
const base = self.expr.binary.args[0].data;
const exponent = self.expr.binary.args[1].data;
self.expr.binary.args[0].grad += other_data * std.math.pow(T, self_data, other_data - 1) * self.grad;
self.expr.binary.args[0].grad += exponent * std.math.pow(T, base, exponent - 1) * self.grad;
}
pub fn tanh(self: *Self) *Self {
return unary((@exp(self.data * 2) - 1) / (@exp(self.data * 2) + 1), .tanh, self);
}
fn tanh_back(self: *Self) void {
self.expr.unary.args[0].grad = (1 - self.data * self.data) * self.grad;
self.expr.unary.args[0].grad += (1 - self.data * self.data) * self.grad;
}
pub fn exp(self: *Self) *Self {
@ -205,3 +205,57 @@ pub fn Value(comptime T: type) type {
}
};
}
pub fn Backprop(comptime T: type) type {
return struct {
const Self = @This();
topo: std.ArrayList(*T),
visited: std.AutoHashMap(*const T, void),
alloc: std.mem.Allocator,
pub fn init(alloc: std.mem.Allocator) Self {
return Self{
.topo = .empty,
.visited = std.AutoHashMap(*const T, void).init(alloc),
.alloc = alloc,
};
}
pub fn deinit(self: *Self) void {
self.topo.deinit(self.alloc);
self.visited.deinit();
}
pub fn backprop(self: *Self, root: *T) void {
self.topo.clearRetainingCapacity();
self.visited.clearRetainingCapacity();
self.backwards_rec(root);
root.grad = 1;
const top = self.topo.items;
for (self.topo.items, 0..) |_, idx| {
top[top.len - idx - 1].backprop_value();
}
}
fn backwards_rec(self: *Self, root: *T) void {
const res = self.visited.getOrPut(root) catch unreachable;
if (!res.found_existing) {
switch (root.expr) {
.nop => {},
.unary => |u| {
backwards_rec(self, u.args[0]);
},
.binary => |b| {
backwards_rec(self, b.args[0]);
backwards_rec(self, b.args[1]);
},
}
self.topo.append(self.alloc, root) catch unreachable;
}
}
};
}

View file

@ -1,28 +1,47 @@
const std = @import("std");
const print = std.debug.print;
// import Value and Backprop
const ValueType = @import("engine.zig").Value;
const BackpropType = @import("engine.zig").Backprop;
pub fn main() !void {
var gpa = std.heap.DebugAllocator(.{}){};
const alloc = gpa.allocator();
defer _ = gpa.deinit();
const Value = ValueType(f64);
_ = Value.init(alloc);
// Create the Value pool with a specific float type
const Value = ValueType(f32);
Value.init(alloc); // init with an allocator, arena is used internally
defer Value.deinit();
const inputs = [4][3]*Value{
[_]*Value{ Value.new(2), Value.new(4), Value.new(-1) },
[_]*Value{ Value.new(2), Value.new(4), Value.new(-1) },
[_]*Value{ Value.new(2), Value.new(4), Value.new(-1) },
[_]*Value{ Value.new(2), Value.new(4), Value.new(-1) },
};
// Create a reusable Backprop instance that operates on Value
var Backprop = BackpropType(Value).init(alloc); // init with an allocator
defer Backprop.deinit();
for (inputs) |row| {
for (row) |val| {
print("{any} ", .{val});
}
print("\n", .{});
}
var a = Value.new(-4);
var b = Value.new(2);
var c = a.add(b);
var d = a.mul(b).add(b.pow(3));
// c += c + 1
c = c.add(c.add(1));
// c += 1 + c + (-a)
c = c.add(c.add(1).sub(a));
// d += d * 2 + (b + a).relu()
d = d.add(d.mul(2).add(b.add(a).relu()));
// d += 3 * d + (b - a).relu()
d = d.add(d.mul(3).add(b.sub(a).relu()));
var e = c.sub(d);
var f = e.pow(2);
var g = f.div(2);
// g += 10.0 / f
g = g.add(Value.new(10).div(f));
print("g.data: {d:.4}\n", .{g.data}); // 24.7041
// run backprop on `g`
Backprop.backprop(g);
print("a.grad: {d:.4}\n", .{a.grad}); // 138.8338
print("b.grad: {d:.4}\n", .{b.grad}); // 645.5773
}