Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

pow leaking memory #1

Open
ivanstepanovftw opened this issue Sep 5, 2024 · 2 comments
Open

pow leaking memory #1

ivanstepanovftw opened this issue Sep 5, 2024 · 2 comments

Comments

@ivanstepanovftw
Copy link

out.op = try std.fmt.allocPrint(self.allocator, "**{d}", .{exponent});
@ivanstepanovftw
Copy link
Author

It is obviously better to create enum Op:

const Op = enum {
    None,
    Add,
    Mul,
    Pow,
    ReLU,
};

use it like this:

op: Op,
...

pub fn add(self: *Self, other: *Self) !*Self {
    const out = try Self.init(self.allocator, self.data + other.data);
    try out.prev.appendSlice(&[_]*Self{ self, other });
    out.op = .Add;
    return out;
}


fn backwardOp(self: *Self) !void {
    switch (self.op) {
        .None => {},
        .Add => {
            self.prev.items[0].grad += self.grad;
            self.prev.items[1].grad += self.grad;
        },
        .Mul => {
            self.prev.items[0].grad += self.prev.items[1].data * self.grad;
            self.prev.items[1].grad += self.prev.items[0].data * self.grad;
        },
        .Pow => {
            const base = self.prev.items[0].data;
            const exponent = self.prev.items[1].data;
            self.prev.items[0].grad += exponent * std.math.pow(T, base, exponent - 1) * self.grad;
        },
        .ReLU => {
            self.prev.items[0].grad += if (self.data > 0) self.grad else 0;
        },
    }
}

@mattzcarey
Copy link
Owner

Thanks. I'm super new to zig so appreciated.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants