aboutsummaryrefslogtreecommitdiff
path: root/src/scalar.py
blob: 42a58ef45c63a61afebb8217f469b837be86f0af (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
import math

class Scalar:
    def __init__(self, data, _children=(), _op='', label='') -> None:
        self.label = label

        self.data = float(data)
        self.grad = 0.0

        self._prev = set(_children)
        self._op = _op
        
        self._backward = lambda: None
    
    def __add__(self, y):
        y = y if isinstance(y, Scalar) else Scalar(y)
        result = Scalar(self.data + y.data, (self, y), _op='+')

        def _backward():
            self.grad += result.grad
            y.grad += result.grad

        result._backward = _backward

        return result

    def __mul__(self, y):
        y = y if isinstance(y, Scalar) else Scalar(y)
        result = Scalar(self.data * y.data, (self, y), _op='*')

        def _backward():
            self.grad += y.data * result.grad
            y.grad += self.data * result.grad

        result._backward = _backward

        return result

    def __pow__(self, y):
        assert isinstance(y, (int, float))
        result = Scalar(self.data ** y, (self, ), _op=f'** {y}')

        def _backward():
            self.grad += (y * self.data ** (y - 1)) * result.grad

        result._backward = _backward

        return result

    def exp(self):
        x = self.data
        e = math.exp(x)
        result = Scalar(e, (self, ), 'exp')

        def _backward():
            self.grad += result.data * result.grad

        result._backward = _backward

        return result

    def tanh(self):
        x = self.data
        t = (math.exp(2 * x) - 1) / (math.exp(2 * x) + 1)
        result = Scalar(t, (self, ), 'tanh')

        def _backward():
            self.grad += (1 - t ** 2) * result.grad

        result._backward = _backward

        return result

    def build_children(self):
        result = []
        visited = set()

        def build(v):
            if v not in visited:
                visited.add(v)
                for child in v._prev:
                    build(child)
                result.append(v)

        build(self)
        return result

    def backward(self):
        self.grad = 1.0
        children = self.build_children()

        for child in reversed(children):
            child._backward()

    def zero_grad(self):
        self.grad = 0.0
        children = self.build_children()

        for child in children:
            child.grad = 0.0

    def __truediv__(self, y):
        return self * y ** -1

    def __rtruediv__(self, y):
        return self * y ** -1

    def __neg__(self):
        return self * -1

    def __sub__(self, y):
        return self + (-y)

    def __rsub__(self, y):
        return self + (-y)

    def __radd__(self, y):
        return self + y

    def __rmul__(self, y):
        return self * y

    def __repr__(self) -> str:
        return f'Scalar({self.data})'