Home Andrej Karpathy
Post
Cancel

Andrej Karpathy

Introduction to Neural Networks

Micrograd Overview

  • “back propagation” - an algorithm to compute the “gradient” i.e. how a model’s “loss” (error) changes as its “weights” change
  • this then allows us to iteratively tune the weights of the neural network to minimize the loss function
  • so, “neural networks” - a mathematical expression that takes inputs, and using its “weights” calculates an output, which are “predictions” / “loss”
  • what is micrograd - a very simple engine to help understand neural network. it works using scalars, e.g. b = Value(4.0). otherwise in real world, we have “tensors” or arrays of these scalar values. making them into tensors helps us take advantage of the parallelism in the computers. the underlying concepts stay the same

Manual Backpropagation

  • remember what derivatives tell us - if we slightly increase x, how does the function respond? what is its “slope” at that point. it can also be told as (f(x + h) - f(x)) / h, where limit of h approaches 0
  • value class implementation -
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    
    class Value:
          
        def __init__(self, data, children=(), _op = ''):
            self.data = data
            self._children = set(children)
            self._op = _op
          
        def __repr__(self):
            return f"Value(data={self.data})"
          
        def __add__(self, other):
            return Value(self.data + other.data, (self, other), '+')
    
        def __mul__(self, other):
            return Value(self.data * other.data, (self, other), '*')
    
    a = Value(2.0)
    b = Value(-3.0)
    c = Value(10.0)
    e = a * b
    d = e + c
    f = Value(-2.0)
    L = d * f
    L
    
  • next, we want to model “back propagation”. we calculate the “gradient”. it is basically the “derivative” of the output (for e.g. L above) wrt all the variables that come before it. L here basically represents the loss function, while a, b, c, f represent the weights of the neural network
  • e.g. based on the above expressions the gradients would be as follows -
    • dL / dL - what would be the change in L if L changes by a bit - should be 1
    • dL / df - ((d * (f + h)) - (d * f)) / h = d = 4
    • dL / dd - (((d + h) * f) - (d * f)) / h = f = -2
    • dL / dc - (dL / dd) * (dd / dc) i.e. “chain rule” in calculus. (dd / dc) is 1 (since d is simply e + c), while we found dL / dd just above. so, finally, dL / dc = -2
    • similarly, dL / de = -2
    • dL / da - (dL / de) * (de / da) = -2 * b = 6
    • dL / db - (dL / de) * (de / db) = -2 * a = -4
  • so, notice how we apply the chain rule recursively - we go backward step by step to calculate the gradient i.e. the derivatives
  • now, “optimize” the weights i.e. move it along the gradients
    1
    2
    3
    4
    5
    6
    7
    8
    9
    
    a.data += (0.01 * a.grad)
    b.data += (0.01 * b.grad)
    c.data += (0.01 * c.grad)
    f.data += (0.01 * f.grad)
    
    e = a * b
    d = e + c
    L = d * f
    L
    
  • this basically helped us “reduce the loss” from -8 to -7.28
  • this was one step (“epoch”?) of optimization

Neurons

  • “neurons” - the way of expressing them in neural networks -
    • we have some inputs (x)
    • then, we have the “weights” here (w)
    • so, we perform (w * x) for all the inputs
    • next, we sum them all and offset them using the “bias” (b)
  • finally, we have an “activation function” that gets applied on the result above. some examples include sigmoid, tanh, etc. they basically “squash” the outputs based on the inputs. see below how their values change from negative to positive x
    1
    2
    3
    4
    5
    6
    7
    
    x = np.arange(-5, 5, 0.2)
    tans = np.tanh(x)
    sigmoids = 1 / (1 + np.exp(-x))
    
    plt.plot(x, tans, label="tans")
    plt.plot(x, sigmoids, label="sigmoids")
    plt.legend()
    

  • note - two inputs means “two dimensional neurons”
  • here is how we can model them using our value class -
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    
    x1 = Value(2.0)
    x2 = Value(0.0)
    
    w1 = Value(-3.0)
    w2 = Value(1.0)
    
    b = Value(6.8813735870195432)
    
    x1w1 = x1 * w1
    x2w2 = x2 * w2
    x1w1x2w2 = x1w1 + x2w2
    n = x1w1x2w2 + b
    o = n.tanh()
    
  • now, we need to perform backpropagation, to ultimately find the derivative of this final output wrt the weights (w), as we would be changing the weights as part of the optimization
  • in reality, we would have many such interconnected neurons, and the whole neural network would have an output / loss, which would we try to optimize using the weights of the neurons throughout

Automatic Backpropagation

  • we extend the functions of the Value class to achieve this
  • we initialize it to an empty function in the init
    1
    
    self._backward = lambda: None
    
  • add -
    • assume x is a + b
    • (do / da) is (do / dx) * (dx / da)
    • (dx / da) is 1
    • (do / dx) is basically out.grad in the case below
      1
      2
      3
      4
      5
      6
      7
      8
      9
      10
      11
      
      def __add__(self, other):
      
          out = Value(self.data + other.data, (self, other), '+')
      
          def _backward():
              self.grad = out.grad * 1
              other.grad = out.grad * 1
      
          out._backward = _backward
      
          return out
      
  • mul -
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    
    def __mul__(self, other):
    
        out = Value(self.data * other.data, (self, other), '*')
    
        def _backward():
            self.grad = out.grad * other.data
            other.grad = out.grad * self.data
    
        out._backward = _backward
    
        return out
    
  • tanh - tanh(x) differentiation wrt x is 1 - (tanh(x))^2. then, we apply the chain rule for the resultant gradient
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    
    def tanh(self):
    
        t = (math.exp(2 * x) - 1) / (math.exp(2 * x) + 1)
    
        out = Value(t, (self, ), 'tanh')
    
        def _backward():
            self.grad = (1 - (t ** 2)) * out.grad
    
        out._backward = _backward
    
        return out
    
  • we can find the gradients of all the parts of the neuron like so. we set the gradient of o as 1, and then call backward on all of the nodes one by one
    1
    2
    3
    4
    5
    6
    7
    8
    9
    
    o.grad = 1.0
    
    o._backward()
    n._backward()
    
    x1w1x2w2._backward()
    
    x1w1._backward()
    x2w2._backward()
    
  • notice what we are doing - we are basically calling the backward step by step i.e. we call backward on everything that comes after the node, before we can call backward on this node. this ordering can be achieved using “topological sort”. i am skipping the code of it for now
  • bug in the current logic - for e.g. if x is a + a and the gradient of x is 0.5, the gradient of a would become 0.5 as well, when in reality it should have been 1
  • fix - wherever we were doing self.grad or other.grad = something in the backpropagation calculation, we need to change = to += i.e. “accumulate”. because otherwise, we end up overwriting instead of accumulating

Pytorch

  • we can do whatever we did till now using pytorch
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    
    x1 = torch.Tensor([2.0]).double()                ; x1.requires_grad = True
    x2 = torch.Tensor([0.0]).double()                ; x2.requires_grad = True
    w1 = torch.Tensor([-3.0]).double()               ; w1.requires_grad = True
    w2 = torch.Tensor([1.0]).double()                ; w2.requires_grad = True
    b = torch.Tensor([6.8813735870195432]).double()  ; b.requires_grad = True
    n = (x1 * w1) + (x2 * w2) + b
    o = torch.tanh(n)
    
    print(o.data.item()) # 0.7071066904050358
    o.backward()
    
    print('x2', x2.grad.item()) # x2 0.5000001283844369
    print('w2', w2.grad.item()) # w2 0.0
    print('x1', x1.grad.item()) # x1 -1.5000003851533106
    print('w1', w1.grad.item()) # w1 1.0000002567688737
    
  • the output gradients of pytorch of course match exactly with what we did manually using our own micro grad implementation

Neuron

  • so till now, we matched the auto gradient module of pytorch using our own value class / micro grad implementation
  • now, we will try to match its neural network module using our neuron class
  • nin in the code stands for “number of inputs” to the neuron
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    
    import random
    
    class Neuron:
    
        def __init__(self, nin):
            self.w = [Value(random.uniform(-1, 1)) for _ in range(nin)]
            self.b = Value(random.uniform(-1, 1))
          
        def __call__(self, x):
            dot = (wi * Value(xi) for wi, xi in zip(self.w, x))
            return sum(dot, self.b).tanh()
    
  • example of using it -
    1
    2
    
    n = Neuron(2)
    n([2.0, 3.0]) # Value(data=0.7446279840905085)
    
  • now, we define a layer of neurons - the neurons in a layer are not connected to each other, but they are fully connected to all the inputs before it / outputs after it
  • so, our layer receives a number of inputs and outputs as an arguments
    • the layer will have number of neurons = number of outputs of the layer
    • each neuron would have number of inputs = number of inputs to the layer
  • so, here is the code for the layer -
    1
    2
    3
    4
    5
    6
    7
    
    class Layer:
    
        def __init__(self, nin, nout):
            self.neurons = [Neuron(nin) for _ in range(nout)]
          
        def __call__(self, x):
            return [n(x) for n in self.neurons]
    
  • example of using it -
    1
    2
    3
    
    x = [2.0, 3.0]
    l = Layer(2, 3)
    l(x) # [Value(data=0.7059), Value(data=0.9819), Value(data=-0.8841)]
    
  • finally, remember that we define neural networks using “multilayer perceptrons”
  • so, nouts in this case would be used to model the outputs of each of the layers, e.g. in the image we saw above, it would be [3, 3, 1], while nins would simply be 4
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    
    class MLP:
    
        def __init__(self, nin, nouts):
            sizes = [nin] + nouts
            self.layers = (Layer(sizes[i], sizes[i + 1]) for i in range(len(nouts)))
          
        def __call__(self, x):
            for layer in self.layers:
                x = layer(x)
            return x
    
  • example of using it -
    1
    2
    3
    4
    
    m = MLP(4, [3, 3, 1])
    
    x = [1.0, 2.0, 3.0, 4.0]
    m(x) # [Value(data=0.6796002762723483)]
    

Example Dataset

  • this is a very simple example of a binary classifier neural network
    1
    
      
    
  • ss
This post is licensed under CC BY 4.0 by the author.
Contents

Rippling HLD Preparation

DBT Preparation