Andrej Karpathy on Backpropagation: Computational Graphs and Gradients

CS231n Winter 2016 Lecture 4
Video thumbnail: Andrej Karpathy on Backpropagation: Computational Graphs and Gradients
1 hr 20 min333K views across 1 upload14,932-word transcriptWatch on YouTube ↗

What Karpathy talks about

Andrej Karpathy gave CS231n Winter 2016 Lecture 4 in 2016, explaining backpropagation through computational graphs, local gradients, and their use in training neural networks.

Also known as: CS231n Winter 2016 Lecture 4; Lecture 4: Backpropagation, Neural Networks 1.

Karpathy introduces backpropagation as repeated chain rule over a computational graph, rather than as one giant symbolic derivative. He walks through tiny scalar examples first, then expands to larger circuits used in neural networks.

He emphasizes how each gate computes local gradients during the forward pass, then passes gradient information backward during training. He also shows why graph structure, caching intermediates, and adding gradients at branch points matter in practice.

Karpathy speaks throughout, with brief audience questions near the end.

In his words

“The correct thing to do is to multiply them”
at 10:55
“This process is called backpropagation”
at 14:37
“There are never any loops.”
at 31:33
“Forward, backward, update; forward, backward, update.”
at 42:03

Key points

  • Backpropagation is recursive chain rule through a computational graph.
  • Local derivatives are computed at each gate; gradients from above are multiplied through them.
  • When a value branches to multiple paths, its gradient contributions are added.
  • Analytic gradients are fast and exact, but gradient checking with numerical derivatives is used to verify them.
  • Neural network libraries are built from layers/gates plus a thin object that manages connectivity and forward/backward passes.
  • Memory matters because forward passes cache intermediates needed for the backward pass.
  • For vector-valued operations, Jacobians exist in principle, but structure usually lets you avoid forming them explicitly.

Full transcript: Andrej Karpathy, CS231n Lecture 4: Backpropagation, Neural Networks 1 (2016)

Okay, so let me dive into some administrative points first. So again, recall that Assignment 1 is due next Wednesday. You have about 150 hours left, and I use hours because there's a more imminent sense of doom. And remember that a third of those hours you'll be unconscious, so you don't have that much time. It's really running out. And, you know, you might think that you have late days and so on but the easiest time is just get harder over time, so you want to save those and so on. So start now. Let's see. So there's no office hours or anything like that on Monday. I'll hold make-up office hours on Wednesday because I want you guys to be able to talk to me about especially projects and

so on. So I'll be moving my office hours from Monday to Wednesday. Usually, I have my office hours at 6 p.m., instead I'll have them at 5 p.m., and usually it's in Gates 260 but now I'll be in Gates 259, so minus 1 on both. And yeah. And also to note, when you're going to be studying for a midterm that's coming up in a few weeks, make sure you go through the lecture notes as well, which are really part of this class. And I kind of pick and choose some of the things that I think are most valuable to present in a lecture, but there's quite a bit of, you know, more material to be aware of that might pop up in the midterm even though I'm covering some of the most important stuff usually in the lecture. So do read through those lecture notes; they're complementary to the lectures, and so the material for the midterm will be drawn from both the lectures and the notes. Ok.

So having said all that, we're going to dive into the material. So where we are right now just as a reminder, we have the score function, we've looked at several loss functions such as the SPM loss function last time, and we looked at the full loss that you achieve for any particular set of weights on over your training data. And this loss is made up of two components: there's a data loss and a regularization loss, right? And really what we want to do is we want to derive now the gradient expression of the loss function with respect to the weights, and we want to do this so that we can actually perform the optimization process. And in the optimization process, we're doing a gradient descent where we iterate evaluating the gradient on your weights, doing a parameter update, and just repeating this over and over again so that we're converging

to the low points of that loss function. And when we arrive at a low loss, that's equivalent to making good predictions over our training data in terms of the scores that come out. Now, we also saw that there are two kind of ways to evaluate the gradient: there's a numerical gradient, and this is very easy to write but it's extremely slow to evaluate, and there's analytic gradient, which is, which you obtain by using calculus and we'll be going into that in this lecture quite a bit more. And so it's fast, exact, which is great, but it's not—you can get it wrong sometimes. And so we always perform what we call gradient check, where we write all the expressions to compute the analytic gradient and then we double check its correctness with numerical gradient. And so I'm not sure if you're going to see that, you're going to see that definitely in the

assignments. Okay, so now you might be tempted to, when you see this setup—"we just want to derive the gradient of the last function with respect to the weights"—you might be tempted to just, you know, write out the full loss and just start to take the gradients as you see in your calculus class. But the point I'd like to make is that you should think much more of this in terms of computational graphs instead of, instead of just taking, thinking of one giant expression that you're going to derive on pen with pen and paper the expression for the gradient. And the reason for that—so here we're thinking about these values flow flowing through a computational graph where we have these operations along circles, and they transfer, they're basically function pieces that transform your inputs all

the way to the loss function at the end. So we start off with our data and our parameters as inputs. They feed through this computational graph, which is just an oldy series of functions along the way, and at the end, we get a single number, which is the loss. And the reason that I'd like you to think about it this way is that these expressions right now look very small, and you might be able to derive these gradients. But these expressions are, and computational graphs are about to get very big. And so, for example, convolutional neural networks will have hundreds, maybe dozens of operations, so we'll have all these images flowing through like pretty big computational graph to get our loss. And so it becomes impractical to just write out these expressions. And convolutional networks are not even the worst of it; once you actually start to, for example, do something called a Neural Turing Machine, which is a paper from DeepMind

where this is basically a differentiable Turing machine. So the whole thing differentiable, the whole procedure that the computer is performing on the tape is made smooth and is differentiable computer basically. And the computational graph of this is huge. And not only is this, this is not it, because what you end up doing—and we're going to recurrent neural networks in a bit—but what you end up doing is you end up unfolding this graph. So think about this graph copied many hundreds of time steps, and so you end up with this giant monster of hundreds of thousands of nodes and little computational units, and so it's impossible to write out, you know, "here's the loss for the Neural Turing Machine." It's just impossible; it would take like billions of pages. And so we have to think about this more in terms of data structures of little functions.

Transforming intermediate variables to get loss at the variant. Okay, so we're going to be looking specifically at computational graphs and how we can derive the gradient on the inputs with respect to the loss function at the very end. Okay, so let's start off simple and concrete. So let's consider a very small computational graph where we have three scalars as inputs to this graph: X, Y, and Z, and they take on the specific values in this example of negative 2, 5, and negative 4, and we have this very small graph or circuit. You'll hear me refer to these interchangeably, either as a graph or a circuit. So we have this graph that at the end gives us this output negative 12. Ok, so here what I've done is I've already prefilled what we'll call the forward pass of this graph where I set the inputs and then I

compute the outputs. Ok, and now what we'd like to do is we'd like to derive the gradients of the expression on the inputs, and so what we'll do now is I'll introduce this intermediate variable Q after the plus gate. So there's a plus gate and a times gate, as I'll refer to them, and this plus gate is computing this output Q, and so Q is this intermediate as a result of X plus Y. And then F is a multiplication of Q and Z, and what I've written out here is basically what we want is the gradients, the derivatives DF by DX, DF by DY, DF by DZ. And I've written out the intermediate, these little gradients for every one of these two expressions separately. So now we've performed the forward pass going from left to right, and what we'll do now is we'll derive the backward pass. We'll

go from the back to the front, computing gradients of all the intermediates in our circuit until at the very end we're going to be left with the gradients on the inputs. And so we start off at the very right, and as a base case sort of of this recursive procedure, we're considering the gradient of F with respect to F. So this is just the identity function. So what is the derivative of just the identity mapping? Where's the gradient of DF by DF? It's 1, right? So the identity has a gradient of 1. So that's our base case. We start off with 1, and now we're going to go backwards through this graph. So we want the gradient of F with respect to Z. So

what is that in this computational graph? Ok, it's Q, so we have that written out right here. And what is Q in this particular example? It's 3, right? So the gradient on Z according to this will become just 3. So I'm going to be writing the gradients under the lines in red, and the values are in green above the lines. So with the gradient on the front is 1, and now the gradient on Z is 3, and what that 3 is telling you really intuitively, keep in mind the interpretation of a gradient: what that's saying is that the influence of Z on the final value is positive and with sort of a force of 3. So if I increment Z

by a small amount H, then the output of the circuit will react by increasing, because it's a positive 3, will increase by 3H. So a small change will result in a positive change on the output. Now the gradient on Q in this case will be, so DF by DQ is said, what is that? Negative 4, okay. So we get a gradient of negative 4 on that part of the circuit, and what that's saying is that if Q were to increase, then the output of the circuit will decrease. Ok, by if you increase by H, the output of the circuit will decrease by 4H. That's the slope is negative 4. Ok, now we're going to

continue this recursive process through this plus gate, and this is where things get slightly interesting, I suppose. So we'd like to compute the gradient on F on Y with respect to Y. And so the gradient on Y with this in this particular graph will become, let's just guess and then we'll see how this gets derived properly. So I hear some murmurs of the right answer, it will be negative four. So let's see how. So there are many ways to derive it at this point because the expression is very small and you can kind of glance at it, but the way I'd like you to think about this is by applying chain rule. Okay, so the chain rule says that if you would like to derive the gradient of F

on Y, then it's equal to DF by DQ times DQ by DY. Right? And so we've computed both of those expressions. In particular, DQ by DY, we know is 1, so that's the effect of the influence of Q on F is DF by DQ, which is negative four. And now we know, we'd like to know the local influence of Y on Q, and that local influence of Y on Q is 1 because that's the local, as I'll refer to, as the local derivative of Y for the plus gate. And so the chain rule tells us that the correct thing to do to chain these two gradients, the local gradient of Y on Q and the kind of global gradient of Q on the output of the circuit, is to multiply them. So we'll get negative 4 times 1, and so this is kind

of the crux of how backpropagation works. This is very important to understand here, that we have these two pieces that we keep multiplying through when we perform this chain rule. We have Q computed as X plus Y, and the derivative on X and Y with respect to that single expression is 1 and 1. So keep in mind the interpretation of the gradient: what that's saying is that X and Y have a positive influence on Q with a slope of 1. So increasing X by H will increase Q by H. Okay, and now what we eventually like is we'd like the influence of Y on the final output of the circuit, and so the way this ends up working is you take the influence of Y on Q, and we know the influence of Q on the final loss, which is what we are recursively computing.

Here, through this graph, the correct thing to do is to multiply them so we end up with a negative 4 times 1, okay, even negative 4. And so the way this works out is basically what this is saying is that the influence of Y on the final-- but the circuit is negative 4. So increasing Y should decrease the output of the circuit by negative four times the little change that you've made. And the way that ends up working out is Y has a positive influence on Q, so increasing Y slightly increases Q, which likely decreases the output of the circuit. Okay, so chain rule is kind of giving us this correspondence. Good. Yeah, thank you. So we're going to get into

this. You'll see many, basically, Centaur classes about this. So you'll see many, many instantiations of this and I'll drill this into you by the end of this class and you'll understand it. You will not have any symbolic expressions anywhere once we compute this, once we're actually implementing this, and you'll see implementations of it later in this. In this, it will always be just vectors and numbers, row vectors, numbers. Okay, and looking at X, we have a very similar-- that happens, thing that happens: we want dF by dX, that's our final objective, but and we have to combine it. We know what the X is, what is X's influence on Q, and what excuse influence on the end of the circuit. And so that ends up being a chain rule, so you take a negative 4 times 1 and gives you negative 1, okay? So the way this works to generalize a bit from this example and the way to think about it is as follows: you are a gate embedded in a circuit and

this is a very large computational graph or circuit, and you receive some inputs, some particular numbers X and Y come in and you perform some operation on them and compute some output set Z, okay? And now this value of Z goes into computational graph and something happens to it, but you're just a gate hanging out in a circuit and you're not sure what happens. But by the end of the circuit, the loss gets computed, okay? And that's the forward pass, and then we're proceeding recursively in the reverse order backwards. But before that, actually, before I get to that part, you've really right away when I get X and Y, the thing I'd like to point out that during the forward pass, if you're this gate and you get your values X and Y, you compute your output Z, and there's another thing you can compute right away.

And that is the local gradients on X and Y. So I can compute those right away because I'm just a gate and I know what I'm performing, like, say, addition or multiplication. So I know the influence that X and Y I have on my output value. I can compute those guys right away. Okay, what but then what happens near the end, so the loss gets computed and now we're going backwards. I'll eventually learn about what is my influence on the final output of the circuit, the loss. So I'll learn what is dL by dZ, in there the gradient will flow into me and what I have to do is I have to chain that gradient through this recursive case. So I have to make sure to chain the gradient through my operation that I performed, and it turns out that the correct thing to do here by chain rule, really what it's saying is the correct thing to do is to multiply your local

gradient with that gradient and that actually gives you the dL by dX, that gives you the influence of X on the final output of the circuit. So really chain rule is just this added multiplication where we take our, what I'll call global gradient of this gate on the output, and we change it through the local gradient. And the same thing goes for Y. So it's just a multiplication of that guy, that gradient by your local gradient if you're a gate. And then remember that these X's and Y's, there are coming from different gates, right? So you end up with recursing this process through the entire computational circuit and so these gates just basically communicate to each other the influence on the final loss. So they tell each

other, okay, if this is a positive gradient that means you're positively influencing loss, and if it's a negative gradient, you're negatively influencing loss. And these just get all multiplied through the circuit by these local gradients and you end up with-- and this process is called backpropagation. It's a way of computing, through a recursive application of chain rule through computational graph, the influence of every single intermediate value in that graph on the final loss function. And so we'll see many examples of this throughout this lecture. I'll go into a specific example that is slightly larger and we'll work through it in detail. But I don't know if there are any questions at this point that anyone would like to ask? Go ahead. If Z is used by multiple nodes, I'm going to come back to that; you add the gradients, the gradient --

the correct thing to do is to add them. So if Z is being influenced in multiple places in the circuit, the backward flows will add, but we'll come back to that point. And the way you randomly initialize your weights, you end up that this is your squashing function, the value of that is somewhere on the asymptotes. Then we are computing the gradient to change. So I think I would, I would have repeated your question, but you're jumping ahead like a hundred slides, mm-hmm. So we're going to get to all of those issues and we're going to see, yeah, you're going to get what we call vanishing gradient problems and so on.

We'll see. Okay, let's go through another example to make this more concrete. So here we have another circuit. It happens to be computing a little two-dimensional signal neuron, but for now don't worry about that interpretation. Just think of this as that's an expression. So, 1 over 1 plus e to the whatever. So the number of inputs here is 5, and we're computing that function and we have a single output over there. Okay, and I translated that mathematical expression into this computational graph form. So we have to recursively from inside out compute this expression. So we first do all the little W times x's, and then we add them all up, and then we take a negative of it, and then we exponentiate that, and then we add one, and then we finally divide, and we get the result of the expression. And so

we're going to do now is we're going to back propagate through this expression. We're going to compute what the influence of every single input value is on the output of this expression. What is the gradient here? Yeah, so you're — so for now, so you're concerned about the interpretation of plus maybe in these circles. For now, let's just assume that this plus is just a binary plus, is a binary plus gate. And we have there a plus 1 gate. I'm making up these gates kind of on spot, and we'll see that what is a gator is not a gate, is kind of up to you. I'll come back to this point of it in a bit, so for now I just like we

have several more gates that we're using throughout. And so I just like to write out as we go through this example several of these derivatives. So we have exponentiation, and we know for every little local gate what these local gradients are, right? So we can derive that using calculus. So e to the x derivative is e to the x, and so on. So these are all the operations and also addition and multiplication, which I'm assuming that you have memorized in terms of what the gradients look like. So we're going to start off at the end of the circuit, and I've already filled in a 1.00 in the back because that's how we always start this recursion, whether 1, 1.0 right, because that's the gradient on the identity function. Now we're going to back propagate through this 1 over x

operation, okay? So the derivative of 1 over x, the local gradient is negative 1 over x squared. So that 1 over x gate, during the forward pass, received input 1.37 and right away that 1 over x gate could have computed what the local gradient was. The local gradient was negative 1 over x squared, and now during back propagation it has to, by chain rule, multiply that local gradient by the gradient of it on the final output of the circuit, which is easy because it happens to be at the end. So what ends up being the expression for the back propagated gradient here from the 1 over x gate, the chain will always has two

pieces: local gradient times the gradient from the top or from above. Yeah, okay, yes, that's correct. So we get minus one over x squared, which is a gradient dF by dX. So that that is the local gradient, negative one over 3.7 squared, and then multiplied by 1.0, which is the gradient from above, which is really just one because we just started. And so I'm applying chain rule right away here, and the output is negative 0.53. So that's the gradient on that piece of the wire where this value was flowing, okay, so it has a negative effect on the

output. And you might expect that, right? Because if you were to increase this value and then it goes through a gate of 1 over x, then if you increase this, then 1 over x gets smaller, so that's why you're seeing negative gradient, right? So we're going to continue back propagation here. The next gate in the circuit, it's adding a constant of one. So the local gradient, if you look at adding a constant to a value, the gradient of x is just one, right, for basic calculus. And so the chain gradient here that we continue along the wire will be: we have local gradient, which is one, times the gradient from above the gate, which it has just

learned is negative 0.53. Okay, so negative 0.53 continues along the wire unchanged and intuitively that makes sense, right? Because this value floats and it has some influence in the final circuit, and now if you're adding one then its influence, its rate of change, its slope towards the final value doesn't change. If you increase this by some amount, the effect at the end will be the same because the rate of change doesn't change through the plus one gate, it's just a constant offset. Okay, we continue derivation here. So the gradient of e to the x is e to the x. So to continue back propagation we're going to perform, so this gate saw input of negative one, it right away could have computed its local gradient and now it knows that the gradient from above is

negative 0.53. So to continue back propagation here in applying chain rule we would receive. Okay, so these are most of the rhetorical questions I'm not sure, but Mattia, basically, e to the negative one, which is e to the x input to this x gate, times the chain rule right? So the gradient from above is negative 0.53, so we keep multiplying that on. So what is the effect on me and what do I have an effect on the final end of the circuit? Those are being always multiplied, so we get negative 0. This point. So now we have a times negative one gate, so what ends up happening when you do a times negative one in the computational graph it flips

Around, right? Because we have basically a constant multiplied by an input, which happens to be a constant of negative one. So, negative one times one times negative one gave us negative one in the forward pass. And so now we have to multiply by a that's the local gradient times the gradient above, which is 0.2. So we end up with just positive 0.2 now. So, now continuing back propagation, we're back propagating plus, and this plus operation has multiple inputs here. The gradient, the local gradient for the plus gate is 1 and 1. So what ends up happening—what gradients flow along the output buyers? So the Plaskett has a local gradient on

all of its inputs always will be just one, right? Because if you just have a function, you know, x plus y, then for that function the gradient on either x or y is just 1. And so what you end up getting is just 1 times 0.2. And so in fact, for a plus gate always, you see the same effect where the local gradient of all of its inputs is 1. And so whatever gradient it gets from above, it just always distributes gradient equally to all of its inputs because, in the chain rule, they'll get multiplied. And when you multiply by 1, something remains unchanged. So a plus gate is kind of like a gradient distributor where if something flows in from the top, it will just spread out all the gradients equally to all of its children. And so we've already received one of the

inputs' gradient, 0.2 here, on the very final output of the circuit. And so this influence has been computed through a series of applications of chain rule along the way. So now let's—there was another plus gate that I've skipped over. And so this 0.2 kind of distributes to both, 0.2, 0.2 equally. So we've already done a plus gate and there's a multiply gate there. And so now we're going to back propagate through that multiply operation. And so the local grade—so what will be the gradients for W0 and X0? What will be the gradient for W0 specifically? Some let's say, 0.0, will be wrong. It will

be... so the gradient W1 will be W0, sorry. It will be negative one times 0.2, good. And the gradient on X0 will be—there's a bug, by the way, in the slide that I just noticed, like a few minutes before I actually created the class. So it created the start in the class. So you see 0.39 there; it should be 0.4. It's because of a bug in the visualization because I'm truncating at two decimal digits. Anyways, but basically that should be 0.4 because the way you get that is two times 0.2 gives you 0.4, just like I've written out over there. So that's what the output should be there. Okay, so that's—so we've back propagated this circuit here and we've back propagated through this expression. And so you might imagine, in there are actual downstream

applications, we'll have data and all the parameters as inputs, loss functions at the top at the end. So we'll do forward pass to evaluate the loss function and then we'll back propagate through every piece of computation we've done along the way and we'll back propagate through every gate to get our inputs. And back propagate just means apply chain rule many, many times and we'll see how that is implemented in a bit. Sorry, did you have a question? Oh yeah. So I'm going to skip that because it's the same, so I'm going to skip the other times gate. Any other questions? It's point process, that's right. So the cost of forward and backward propagation is roughly equal. Well, it should be. It almost always ends

up being basically equal. When you look at timings, usually the backward pass is slightly slower, but yeah. Okay, so let's see. One thing I wanted to point out before we move on is that the setting of these gates, like these gates, are arbitrary. So, one thing I could have done, for example, is—some of you may know this—I can collapse these gates into one gate if I wanted to. For example, there's something called a sigmoid function which has that particular form. So sigma, sigma of x, which is the sigmoid function, computes one over one plus e to the minus x. And so I could have rewritten that expression and I could have collapsed all of those gates that made up the sigmoid gate into a single sigmoid gate. And so there's a sigmoid gate here and I could have done that in a single

go, sort of. And what I would have had to do, if I wanted to have that gate, is I need to compute an expression for how this—so what is the local gradient for the sigmoid gate basically? So, what is the gradient on the sigmoid gate on its input? And I have to go through some math, which I'm not going to go into detail, but you end up with that expression over there. It ends up being one minus sigma of x times sigmoid of x, that's the local gradient. And that allows me to now put this piece into a computational graph because once I know how to compute the local gradient, everything else is defined just through chain rule and multiplying everything together. So we can back propagate through this sigmoid gate now. And the way that would look like is the input to the sigmoid gate was 1.0, that's what flew into the sigmoid gate, and 0.73 went out. So 0.73

is sigma of x, okay? And now we want the local gradient, which is, as we've seen from the math that I performed there, one minus sigma of x times sigma of x. So you get sigma of x as 0.73 multiplying 1 minus 0.73, that's the local gradient, and then times—well, we happen to be at the end of the circuit, so times 1.0, which I'm not even writing. So we end up with 0.2. And of course we get the same answer, 0.2, as we received before, 0.2, because calculus works. But basically, we could have broken up this expression down and did one piece at a time or we could just have a single sigmoid gate and that's kind of up to us at what level of hierarchy do we break these expressions. And so you'd like to intuitively cluster these expressions into single gates if it's very efficient or easy to derive.

The local gradients, because then those become your pieces. Yes. So the question is, do libraries typically do that? Do they worry about, you know, what’s easy to or convenience to compute? And the answer is, yeah, I would say so. So if you notice that there’s some piece of operation you’d like to do over and over again and it has a very simple local gradient, then that’s something very appealing to actually create a single unit out of. And we’ll see some of those examples actually that I think. Okay. I'd like to also point out that once you—the reason I like to think about these computational graphs is it really helps your intuition to think about how gradients flow in a neural network. It’s not just—you don’t want this to be a black box to you. You want to understand.

Intuitively how this happens and you start to develop, after a while of looking at computational graphs, intuitions about how these gradients flow. And this, by, do a lot, so helps you debug some issues like, say, the vanishing gradient problem. It’s much easier to understand exactly what’s going wrong in your optimization if you understand how gradients flow in networks. It will help you debug these networks much more efficiently. And so some intuitions, for example, we already saw that the add gate, it has a local gradient of 1 to all of its inputs. So it’s just a gradient distributor. That’s like a nice way to think about it. Whenever you have a plus operation anywhere in your score function or your ComNet or anywhere else, it just distributes gradients equally. The max gate is instead a gradient router. And the way this works is if you look at

the expression, like if we have—I'll create these markers don't work—so if we have a very simple binary expression of max of x, y. So if this is a gate, then the gradient on x and y, if you think about it, the gradient on the larger one of your inputs, whichever one is larger, the gradient on that guy is one, and on the smaller one has a gradient of zero. And intuitively, that’s because if one of these was smaller then wiggling it has no effect on the output because the other guy is larger. And that’s what ends up propagating through the gate. So you end up with a gradient of 1 on the larger one of the inputs. And so that’s why max gate is a gradient router. If I’m a max gate and I receive several inputs, one of them was largest of all of them,

and that’s the value that I propagated through the circuit. At the backpropagation time, I’m just going to receive my gradient from above, and I’m going to route it to whoever was my largest input. So it’s a gradient router. And the multiply gate is a gradient switcher. I’m not actually—I don’t think that’s a very good way to look at it, but I’m referring to the fact that it’s not actually—never mind about that part. Good. So, yeah. So your question is, what happens if the two inputs are equal when you go through max gate? Yeah, what happens? Yeah.

You pick one. Yeah. Yeah, I don’t think it’s correct to distribute it to all of them. I think you’d have to—you’d have to pick one. Yeah, but that basically never happens in actual practice. Okay, so max gradient here actually have an example. So, z here was larger than w, so only z has an influence on the output of this max gate, right? So when z flows into the max gate, it gets routed to z, and w gets a zero gradient because its effect on the circuit is nothing. There’s zero because when you change it, it doesn’t matter, when you change it, because that is the larger value going through the computational graph. I have another note that is related to the backpropagation, which we already addressed

through a question. I just wanted to briefly point out with a terribly bad looking figure that if you have these circuits and sometimes you have a value that branches out into a circuit and is used in multiple parts of the circuit, the correct thing to do by multivariate chain rule is to actually add up the contributions at the operation. So gradients add when they backpropagate backwards through the circuit. If they ever flow, they add up in this backward flow. All right, we’re going to go into implementation very soon. I’ll just take some little questions. Thank you for the question. The question is, is there ever like a loop in these graphs? There will never be loops. So there are never any loops. You might think that if you use a recurrent neural network that

there are loops in there, but there’s actually no loops because what we’ll do is we will take a recurrent neural network and will unfold it through time steps and this will all become—there will never be a loop in the unfolded graph where we’ve copy-pasted that small recurrent over time. You’ll see that more when we actually get into it, but these are always DAGs. There’s no loops. Okay, awesome. So let’s look at the implementation, how this is actually implemented in practice. And I think will help make this more concrete as well. So we always have these graphs, computational graphs. These are the best way to think about structuring neural networks. And so we end up with all these gates that we’re going to see in a bit. But on top of the gates there’s something that needs to maintain connectivity structure of this entire graph. What gates are connected to each

other? And so usually that’s handled by a graph or a net object, usually in net. And the net object has these two main pieces which has the forward and the backward piece, and this is just pseudocode, so this won’t run. But basically roughly the idea is that in the forward pass we’re iterating over all the gates in the circuit, and they’re sorted in topological order. What that means is that all the inputs must come to every node before the output can be consumed. So these are just ordered from left to right and we’re just forwarding. We’re calling a forward on every single gate along the way. So we iterate over that graph and we just go forward on every single piece. And this net object will just make sure that that happens in the proper connectivity pattern. And backward pass we’re going in the exact reverse order and we’re calling backward on

Every single gate, and these gates will end up communicating gradients to each other, and they all get chained up and compute the analytic gradient at the back. So really, a net object is a very thin wrapper around all these gates, or as well, as we'll see, they're called layers. Layers or gates, I'm going to use those interchangeably, and they're just very thin wrappers around the connectivity structure of these gates and calling a forward and backward function on them. And then let's look at a specific example of one of the gates and how this might be implemented. And this is not Justus Souter, this is actually more like a correct implementation in some sense, like this might run at the end. So, let's say a multiply gate and how it could be implemented. A multiply gate in this case is just a binary multiply. So it receives two inputs, x and y. It computes their multiplication that

is x times y and inverts instead. And all these gates must basically satisfy this API of a forward call and a backward call. How do you behave in a forward pass and how do you behave in a backward pass? And in a forward pass, we just compute whatever. In a backward pass, we eventually end up learning about what is our gradient on the final loss. So dL by dZ is what we learn. That's represented in this variable dZ. And right now, everything here is scalars, so x, y, z are numbers here. dZ is also a number telling the influence on the end of the circuit. And what this gate is in charge of in this backward pass is performing the little piece of chain rule. So what we have to compute is how do you change this gradient dZ into your inputs x and y? In other words, we have to compute dX

and dY, and we have to return those in the backward pass. And then the computational graph will make sure that these get routed properly to all the other gates. And if there are any edges that add up, the computational graph might add all those gradients together. Ok, so how would we implement the dX and dY? So for example, what is dX in this case? What would it be equal to? The implementation: y times dZ, right? And so y times dZ. Additional point to make here, by the way, note that I've added some lines in the forward pass. We have to remember these values x and y because we end up using them in a backward pass. So I'm assigning them to a cell store because I need to remember what x and y are

because I need access to them in my backward pass. In general, in backpropagation, and when we build these, when you actually do the forward pass, every single gate must remember the inputs and any kind of intermediate calculations that it has performed that it needs to do, that needs access to in the backward pass. So basically, when we end up running these networks at runtime, just always keep in mind that as you're doing this forward pass, a huge amount of stuff gets cached in your memory, and that all has to stick around because during backpropagation, you might need access to some of those variables. And so your memory ends up ballooning up during a forward pass, and then in backward pass it gets all consumed. And you need all those intermediates to actually compute the proper backward pass. So that's, yes, if you don't, if you know you don't want to do backward pass, then you can get rid

of many of these things and you don't have to compute, you're going to cache them. So you can save on memory for sure, but I don't think most implementations actually worry about that. I don't think there's a lot of logic that deals with that. Usually, we end up remembering it anyway. Oh, I see. Yeah, so I think if you're on an embedded device, for example, and you worry really about your memory constraints, this is something that you might take advantage of. If you know that a neural network only has to run at test time, then you might want to make sure to go into the code and make sure nothing gets cached in case you want to do a backward pass. Questions? Yes, you're saying if we remember the local

gradients in the forward pass, then we don't have to remember the other intermediates. I think that might only be the case in some simple expressions like this one. I'm not actually sure that's true in general, but I mean, you're in charge of remembering whatever you need to perform the backward pass. They only, gate-by-gate basis, you don't necessarily feel like it has a lower footprint and so on and you can be clever with that. Okay, so just to give you guys example of what this looks like in practice, we're going to look at a specific example, say in Torch. Torch is a deep learning framework which we might go into a bit near the end of the class that some of you might end up using for your projects. If you go into the GitHub

repo for Torch and you look at, like, basically, it's just a giant collection of these layer objects, and these are the gates, layers, gates, the same thing. So there's all these layers, that's really what a deep learning framework is: is just a whole bunch of layers and a very thin computational graph thing that keeps track of all the layer connectivity. And so really the image to have in mind is all these things are your Lego blocks, and then we're building up these computational graphs out of your Lego blocks, out of the layers. You're putting them together in various ways depending on what you want to achieve, and so you end up building all kinds of stuff. So that's how you work with neural networks. So every library is just a whole set of layers that you might want to compute, and every layer is just implementing a small piece function piece. And that function piece knows how to do a forward and it knows how to do a backward, so

Just to be the specific example, let's look at the MulConstant layer in Torch. The MulConstant layer performs just the scaling by a scalar. So it takes some tensor X. So this is not just a scalar, but it's actually like an array of numbers, basically, because when we actually work with these, we do a lot of vectorized operations. So we receive a tensor, which is really just an n-dimensional array, and we scale it by a constant. And you can see that this layer actually just has 40 lines. There's some initialization stuff. This is Lua, by the way, if this is looking some foreign to you. But there's initialization where you actually pass in that a that you want to use as your scaling, and then during the forward pass, which they call

updateOutput in a forward pass, all they do is they just multiply a X and return it. And in the backward pass, which they call updateGradInput, there's an if statement here, but really when you look at these three lines that are most important, you can see that all it's doing is it's copying into a variable gradInput, which needs to compute—that's your gradient that you're passing up. The gradInput is, you're copying gradOutput. GradOutput is your gradient on the final loss. You're copying that over into gradInput, and you're multiplying by the scalar, which is what you should be doing because your local gradient is just a. And so you take the output you have, you take the gradient from above, and you just scale it by a, which is what these three lines are doing, and that's your gradInput, and that's what you return. So that's one of the hundreds of layers that are in Torch.

We can also look at examples in Caffe. Caffe is also a deep learning framework, specifically for images that you might be working with. Again, if you go into the layers directory and GitHub, you just see all these layers. All of them implement the forward-backward API. So just to give you an example, there's a Sigmoid layer in Caffe. So the Sigmoid layer takes a blob. So Caffe likes to call these tensors blobs. So it takes a blob, which is just an n-dimensional array of numbers, and it passes it element-wise through a Sigmoid function. And so it's computing in a forward pass a Sigmoid, which you can see there. I'll use my pointer, okay, so there it's calling. So a lot of this stuff is just boilerplate getting to all the data, and then we have a bottom blob, and we're calling a Sigmoid function on the bottom, and that's just the Sigmoid function right there. So

that's what we compute, and in a backward pass, some boilerplate stuff, but really what's important is we need to compute the gradient times the chain rule here. So that's what you see in this line. That's where the magic happens, where we take the diff. So they call the gradients diffs, and you compute the bottom. This is the top diff times this piece, which is really the—that's the local gradient. So this is chain rule happening right here through that multiplication. So, and that's it. And so every single layer just a forward-backward API, and then you have a computational graph on top, or a net object that keeps track of all the connectivity. Okay, any questions about some of these implementations and so on? Go ahead. Yes, thank you. So the question is, do you

have to go through forward and backward for every update? The answer is yes, because when you want to do update, you need the gradient. And so you need to do forward on your sample mini-batch. You do it forward, you right away do a backward, and now you have your NLE gradient. And now I can do an update where I take my analytic gradient and I change my weights a tiny bit in the direction, the negative gradient direction of your gradient. So forward computes the loss, backward computes your gradient, and then the update uses the gradient to increment your weights a bit. So that's what keeps happening in loop when you train a neural network. That's all that's happening: forward, backward, update; forward, backward, update. We'll see that in a bit. Good. You're asking about the

for loop? Oh, is there for loop here? I didn't even notice. Okay, yeah, they have a for loop. Yeah, so you'd like this to be vectorized. I'm not actually sure because this is C++, so I think, yeah, they just stuff, just do it. Go for it. Yeah, yeah. So this is a CPU implementation, by the way. I should mention that this is a CPU implementation of the Sigmoid layer. There's a second file that implements the Sigmoid layer on GPU, and that's CUDA code. And so that's a separate file. It would be Sigmoid.cu or something like that. I'm not showing you that in the questions. Okay, great. So one point I'd like to make is will be, of course,

working with vectors. So these things flowing along our graphs are not just scalars. They're going to be entire vectors. And so nothing changes. The only thing that is different now, since these are vectors, X, Y, and Z are vectors, is that this local gradient, which before used to be just a scalar, now they're, in general, for general expressions, they are full Jacobian matrices. And so Jacobian matrix is just two-dimensional matrix and basically tells you what is the influence of every single element in X on every single element of Z, and that's what you could be a matrix stores. And the gradient is the same expression as before, but now say here dZ by dX is a vector, and dL by dZ is, sorry, dL by dS, that is a vector, and dZ by dX

Is an entire Jacobian matrix, so you end up with an entire matrix-vector multiply to actually change the gradient backwards. No. So I'll come, I'll come back to this point in a bit. You never actually end up forming the full Jacobian. You'll never actually do this matrix multiply most of the time. This is just a general way of looking at, you know, arbitrary function, and I need to keep track of this. And I think that these two are actually out of order because these are dY/dX is the Jacobian, which should be on the left side. So that's, I think, that's a mistake in slide because this should be a matrix-vector multiply. So I'll show you why you don't actually need to ever form those Jacobians. So let's work with a specific

example that is relatively common in neural networks. Suppose we have this non-linearity: max of 0 and X. So really, what this operation is doing is it's receiving a vector, say, of 4096 numbers, which is a typical thing you might want to do — 4096 numbers, real-valued, come in — and you're computing an element-wise threshold in a. So anything that is lower than zero gets clamped to zero, and that's your function that you're computing. And so, the vectors are the same dimension. So the question here I'd like to ask is: what is the size of the Jacobian matrix for this layer? 4,096 by 4,096, in principle. Every single

port number in here could have influenced every single number in there, but that's not the case necessarily. Right. So the second question is, so this is a huge matrix, 16 million numbers, but why would you never form it? What does the Jacobian actually look like? No Jacobian will always be a matrix because every one of these 4096 could have influenced every... It is. So the Jacobian is still a giant 4096 by 4096 matrix, but it has special structure. Right, and what is that special structure? Good. Yeah, so this Jacobian is huge, so it's 4096 by 4096 matrix, but there's

only elements on the diagonal because this is an element-wise operation. And moreover, they're not just ones, but for whichever element was less than 0, it was clamped to 0. So some of these ones actually are zeros in whichever elements had a lower than 0 value during the forward pass. And so the Jacobian would just be almost an identity matrix, but some of them are actually zero. So you never actually would want to form the full Jacobian because that's silly. And so you never actually want to carry out this operation as a matrix-vector multiply because there's special structure that we want to take advantage of. And so in particular, the gradient, the backward pass for this operation is very, very easy because you just want to look at all the dimensions where your input was less

than 0, and you want to kill the gradient in those dimensions. You want to set the gradient to 0 in those dimensions. So you take the grad output here, and whichever numbers were less than 0, just set them to 0. Set those gradients to 0, and then you continue backward pass. So very simple operations in the end in terms of efficiency. Just refer back. That's right, that's right. You could do a matrix if you needed to in your internal state, but when you actually report back, you're always just... Yeah. So the question is, the communication between the gates is always just vectors. That's right. So this Jacobian, if you wanted to, you can form that, but that's

internal to you inside the gate, and you can use that to do backprop. But what's going back to other gates, they only care about the gradient vector. Yes. So the question is, unless you end up having multiple outputs because then for each output we have to do this. And so you... Yeah. So we'll never actually run into that case because we almost always have a single output scalar value at the end because we're interested in loss functions. So we just have a single number at the end that we're interested in computing gradients with respect to. If we had multiple outputs, then we have to keep track of all of those as well in parallel when we do the back propagation. But we just have scalar-valued loss functions. So, so we don't have to worry

about that. Okay, make sense? So I want to also make the point that actually 4096 dimension is not even crazy. Usually, we use mini batches, so say mini batch of 100 elements going through at the same time. And then you end up with 100 4096-dimensional vectors that are all coming in in parallel. But all the examples in a mini batch are processed independently of each other in parallel. And so this Jacobian matrix really ends up being 400 million, 400,000 by 400,000. So huge. So you never form these basically, and you take some intake care to actually take advantage of the sparsity structure in that Jacobian, and you hand code operations. You don't actually write the fully generalized chain rule inside any gate

implementation. Okay, cool. So I'd like to point out that in your assignment you'll be writing SVMs and softmax and so on, and I just kind of wanted to give you a hint on the design of how you actually should approach this problem. What you should do is just think about it as a back propagation even if you're doing this linear classification optimization. So roughly, your structure should look something like this where again, stage your computation in units that you know the local gradient off and then do backprop when you actually evaluate these gradients in your assignment. So in the top, your code will look something like this where we don't have any graph structure because you're doing everything inline. So no crazy edges or anything like that that you

You have to do, you will do that in the second assignment. You'll actually come up with a graph object, and you'll implement your layers. But in the first assignment, you're just doing it inline, just straight up vanilla set up. And so, compute your scores based on W and X, compute these margins, which are max of zero and the score differences, compute the loss, and then do backprop. And in particular, I would really advise you to have this intermediate scores that you create as a matrix and then compute the gradient on scores before you compute the gradient on your weights. And so, chain use chain rule here. Otherwise, you might be tempted to try to just derive W, the gradient on W equals, and then implement that, and that's an unhealthy way of approaching the problem. So, stage your computation and do backprop through this course, and

they will help you out. Okay, cool. So, let's see, something's in summary so far: neural networks are hopelessly large, so we end up with these computational structures and these intermediate nodes. Forward-backward API for both the nodes and also for the graph structure. And the graph structure is usually a very thin wrapper around all these layers, and it can handle all the communication between them. And its communication is always along vectors being passed around. In practice, when we write these implementations, what we're passing around are these n-dimensional tensors. Really, what that means is just an N-dimensional array, so like a numpy array. Those are what goes between the gates, and then internally every single gate knows what to do in

the forward and backward pass. Ok, so at this point, I'm going to end with backpropagation, and I'm going to go into neural networks. So, any questions before we move on from background? Good. The summation inside Li equals blah. Yeah, so there's a sum there, so you'd want that to be a vectorized operation that you are. Yeah, so basically the challenge in your assignment almost is how do you make sure that you do all of this efficiently, nicely, with meters, vector operations in numpy, so that's going to be some of the brainteaser stuff that

you guys are going to have to do. Yeah, so it's up to you what you want your gates to be like and what you want them to be. Um, yeah, I don't think you'd want to do that. Yeah, I'm not sure, maybe that works, I don't know, but yeah, it's up to you to design this and to backprop to it. Yeah, so that's, that's fun. Okay, so we're going to go to neural networks. This is exactly what they look like, so you'll be implementing these, and this is just what happens when you search on Google Images for neural networks. This is, I think, the first results are simple like that. So, let's look at neural networks and before we dive into neural networks,

actually, I'd like to do it first without all the brain stuff. So forget that they're neural, forget that they have any relation whatsoever to a brain, they don't. But forget if you thought that they did, that they do. Let's just look at score functions, where before we saw that F equals WX is what we've been working with so far, but now, as I said, we're going to start to make that F more complex. And so, if you wanted to use a neural network, then you're going to change that equation to this. So this is a two-layer neural network, and that's what it looks like, and it's just a more complex mathematical expression of X. And so, what's happening here is you receive your input X, and you make X matrix, just like we did before. Now, what's come back? What comes next is a non-linearity or activation function.

And we're going to go into several choices that you might make for these. In this case, I'm using the threshold again, zero, as an activation function. So basically, we're doing matrix multiply, we threshold everything negative to zero, and then we do one more matrix multiply and that gives us our scores. And so if I was to draw this, say in case of C for ten, with 3,072 numbers going in, those are the pixel values. And before, we just went one thing matrix-multiply to scores. We went right away to ten numbers. But now we get to go through this intermediate representation of a hidden hidden state. We'll call them hidden players, so hidden vector H of hundred numbers, say, or whatever you want your size of their neural network to be. So this is a hyperprimer that say that hundred, and we go through this intermediate representation. So matrix

multiply gives us hundred numbers, threshold at zero, and then one more matrix multiplied to get these scores. And since we have more numbers, we have more wiggle to do more interesting things. So a more, one particular example of something interesting you might want to, what you might think that in your network could do, is going back to this example of interpreting linear classifiers on C part N. And we saw that the car class has this red car that tries to merge all the modes of different cars facing different directions. And so, in this case, one single layer, one single linear classifier had to go across all those modes, and we couldn't deal with, for example, the cars of different colors. That wasn't very natural to do. But now we have hundred numbers in this

intermediate, and so you might imagine, for example, that one of those numbers could be just picking up on the red car facing forward. It's just classifying is there a red car facing forward? Another one could be a red car facing slightly to the left, left car facing slightly to the right, and those elements of H would only become positive if they find that thing in the image, otherwise they stay at zero. And so another H might look for green cars or yellow cars or whatever else in different orientations. So now we can have a template for all these different modes, and so these neurons turn on or off if they find the thing they're looking for, a car of some specific type. And then this W2 matrix can sum across all those little car templates. So now we have like, say, 20 car templates of what

Cars could look like, and now to compute the score of car classifier, there's an additional matrix multiply. So, we have a choice of doing a weighted sum over them, and so if any one of them turns on, then through my weighted sum with positive weights, presumably, I would be adding up and getting the higher score. And so now I can have this multi-modal car classifier through this additional hidden layer in between there. So that's a hand-wavy reason for why these would do something more interesting. Was their question: the question is, if H had less than 10 units, would it be inferior to a linear classifier? I think that's a

That's actually not obvious to me. It's an interesting question. I think you could make that work. I think it could make it work. Yeah, I think that would actually work. Someone should try that for extra points on the assignment. So, you'll have a section on the assignment, "Do something fun or extra," and so you get to come up with whatever you think is an interesting experiment, and we'll give you some bonus points. So that's a good candidate for something you might want to investigate, whether that works or not. Any other questions? Good. That's right.

Nothing. I understood the question. Yep. Yep. I think so. You're really asking about the layout of the H vector and how it gets allocated over the different modes of the data set, and I don't have a good answer for that. Since we're going to train this fully with backpropagation, I think it's likely naive to think that there will be exact templates for "side left car," "facing red car," "facing left." You probably won't find that. You'll find these kind of like mixes and weird things, intermediates, and so on. So there's no let work will come in, and it will optimally find a way to truncate your data with its linear boundaries.

And these weights are all getting adjusted just to come to make it come out right. So it's really hard to say. Well, become tangled up. I think "good age" was like José Archer. That's right. So that's the size of a head and layer, and that's a hyperparameter we get to choose. So I chose 100. Usually, that's going to be... Usually, you'll see that with neural networks, we'll go into this a lot, but usually, you want them to be as big as possible as it fits in your computer, and so on. So more is better. But we'll go into that. Good. So you're asking, do we always take max of 0 and H? And we don't, and I'll get to it in like 5 slides.

That way. So I'm going to go into neural networks. I guess maybe I should preemptively just go ahead and then take questions near the end. If you wanted this to be a three-layer neural network, by the way, there's a very simple way in which we just extend this, right? So we just keep continuing the same pattern, where we have all these intermediate hidden nodes, and then we can keep making our network deeper and deeper, and you can compute more interesting functions because you're giving yourself more time to compute something interesting in a hand-wavy way. Now, one other slide I wanted to flash is that training a two-layer neural network, I mean, it's actually quite simple when it comes down to it. So this is a slide borrowed from a blog post I found, and basically, it suffices as roughly 11 lines of Python to implement a two-layer neural network doing binary classification on what is

This two-dimensional data. So you have a two-dimensional data matrix X. You have—sorry, it's three-dimensional—and you have binary labels for Y, and then sin0, sin1 are your weight matrices: weight1, way2, and so I think they're called sin for sin apps, but I'm not sure. And then this is the optimization loop here, and what you're seeing here— I should use my pointer more—what you're seeing here is we're computing the first layer activations, but this is using a sigmoid non-linearity, not a max of 0, ReLUs. And we're going to a bit of what these linked nonlinearities might be. So sigmoid is one form of computing the first layer and then computing the second layer, and then it's computing here right away the backward pass. So this is the l2 delta, is the gradient on

l2, the gradient on l1, and the gradient. And this is a matrix update here, so right away he's doing an update at the same time as doing the final piece of backprop here, where he's formulating the gradient on the W and, right, he's adding to W gradient here. And so really, 11 lines suffice to train the neural network to do a binary classification. The reason that this loss might look slightly different from what you've seen right now is that this is a logistic regression loss. So you saw a generalization of it, which is the softmax classifier into multiple dimensions, but this is basically a logistic loss being updated here, and you can go through this in more detail by yourself. But the logistic regression loss looks slightly different, and that's being—that's inside there. But otherwise,

Yes. So this is not too crazy of a computation, and very few lines of code suffice to actually train these networks. Everything else is fluff: how do you make it efficient? How do you… There's a cross-validation pipeline that you need to have and all this stuff that goes on top to actually give these large code bases. But the kernel of it is quite simple: we compute these layers, do forward pass, we do backward pass, we do an update, which isn't raining this over and over again. Good. The random function is creating your first initial random weights, so you need to start somewhere. So you generate a random W. Ok? Now, I wanted to mention that you'll also be training a two-layer neural network in this class, so you'll be doing something very similar to this, but you're not using logistic regression, and you might

Have different activation functions, but again just my advice to you when you implement this is stage your computation into these intermediate results and then do proper back propagation into every intermediate result. So you might have—you compute your, let's see, you compute—you receive these weight matrices and also the biases. I don't believe you have biases actually on your SVM, on your softmax, but here you'll have biases. So take your weight matrices and the biases, compute the first inner layer, compute your scores, compute your loss, and then do backward pass. So backprop into scores, then backprop into the weights at the second layer, and backprop into this h1 vector, and then through h1 backprop into the first weight matrices and

the first biases, okay? So do proper back propagation here. Otherwise, if you try to write away just say, "What is dW1? What is the gradient on W1?" If you just try to make it a single expression for it, it will be way too large and you'll have headaches. So do it through series of steps in back propagation. No, that's just a hint, okay? So now I'd like to—so that was the presentation of neural networks without all the brain stuff, and so it looks fairly simple. So now we're going to make it slightly more insane by folding in all kinds of, like, motivations, mostly historical, about like how this came about, that it's related to bringing it all in. And so we have neural networks and we have neurons inside these neural networks. So this is what neurons look like. This is just what happens when you search on image search

neurons. So there you go. Now, your actual biological neurons don't look like this for cuddling—they actually look more like that. And so a neuron just very briefly, just to give you an idea about where this is all coming from, you have a cell body or a soma, as people like to call it, and it's got all these dendrites that are connected to other neurons. There's a cluster of other neurons and cell bodies over here, and dendrites are really these appendages that listen to them. So this is your input to a neuron, and then it's got a single axon that comes out of a neuron that carries the output of the computation that this neuron performs. So usually, usually, this neuron receives inputs, and if many of them align, then this cell, the neuron can

choose to spike. It sends an activation potential down the axon, and then this actually diverges out to connect to dendrites of other neurons that are downstream. So there are other neurons here and their dendrites connect to the axons of these guys. So basically just neurons connected through these synapses in between, and we have these dendrites that are the input to neuron and this axon that actually carries the output of a neuron. And so basically you can come up with a very crude model of a neuron and it will look something like this. We have an axon, so this is the cell body here of a neuron, and just imagine an axon coming from a different neuron somewhere in the network, and this neuron is connected to that neuron through this synapse. And every one of these synapses

has a weight associated with it of how much this neuron likes that neuron basically. And so axon carries this x, it interacts in the synapse, and they multiply in this crude model. So you get w0 x0 floating, a flowing to the soma, and then that happens for many neurons. So you have lots of inputs, w times x flowing in, and the cell body here just performs, in some offset by bias, and then if an activation function is met here, so it passes through an activation function to actually compute the output of this axon. Now, in biological models historically, people like to use the sigmoid non-linearity to actually use for the activation function. The reason for that is because you get a number between 0 and 1, and you can

interpret that as the rate at which this neuron is firing for that particular input. So it's a rate between 0 and 1 that's going through the activation function. So if this neuron is seeing something it likes in the neurons that connect to it, it will start to spike a lot, and the rate is described by F of the input, okay? So that's the crude model of a neuron. If I want to implement this, it would look something like this. So a neuron tick function, forward pass, it receives some inputs. This is a vector and we form some at the cell body, so just a linear sum, and we put—and we compute the firing rate as a sigmoid of the cell body sum and return the firing rate. And then this can plug into different neurons, right? So you can imagine, you can actually see that this looks very similar to a linear

classifier, right? We're forming a linear sum here. A weighted sum. And we're passing that through a non-linearity. So every single neuron in this model is really like a small linear classifier. But these linear classifiers plug into each other and they can work together to do interesting things. Now, one note to make about neurons is that they're very—they're not like biological neurons. Biological neurons are super complex. So if you go around and you start saying that neural networks work like brain, people are starting to frown, and people start to frown at you. And that's because neurons are complex dynamical systems. There are many different types of neurons. They function differently. These dendrites, there, they can perform lots of interesting computation. A good review

article is a dendrite computation, which I really enjoyed. These synapses are complex dynamical systems. They're not just a single weight. And we're not really sure if the brain uses rate code to communicate. So very crude mathematical model and don't—don't push this analogy too much. But it's good for kind of like media articles. And so I suppose that's why this keeps coming up again and again as we explain that this works like your brain. But okay, I'm not going to go too deep into this. To go back to a question that was asked before, there's an entire set of nonlinearities that we can choose from. So historically, sigmoid has been used quite a bit, and we're going to go into much more detail over what these nonlinearities are, what are their trade-offs, and why you might want to use

One or the other, but for now, I just like to flash them and mention that there are many things to choose from. Historically, people use sigmoid @nh. As of 2012, ReLU became quite popular. It makes your networks converge quite a bit faster. So right now, if you wanted a default choice for a non-linearity, use ReLU. That's the current default recommendation. And then there's a few kind of hipster activation functions here, and so leaky relatives were proposed a few years ago, max-out is interesting, very recently ELU, and so you can come up with different activation functions, and you can describe why these might work better or not. And so this is an active area of research, trying to come up with these activation functions that perform or had better properties in one way or another. So we're going to go into this.

Much more detail soon in the class, but for now we have these neurons, we have a choice of activation function, and then we rank these neurons into neural networks, right? So we just connect them together so they can talk to each other. And so here's an example of a what two-layer neural, or three-layer and all that. When you want to count the number of layers in a neural net, you count the number of layers that have weights. So here, the input layer does not count as a layer because these neurons are just single values; they don't actually do any computation. So we have two layers here that could have weights, so it's a two-layer net. And we call these layers fully connected layers. And so remember that I've shown you that a single neuron computes this little weighted sum and then passes a

through non-linearity. In a neural network, the reason we arrange these into layers is because arranging them into layers allows us to perform the computation much more efficiently. So instead of having an amorphous blob of neurons, and every one of them has to be computed independently, having them in layers allows us to use vectorized operations. And so we can compute an entire set of neurons in a single hidden layer just at a single time as a matrix multiply, and that's why we arrange them in these layers where neurons inside a layer can be evaluated completely in parallel, and they all see the same input. So it's a computational trick to arrange them in layers. So this is a three-layer neural net, and this is how you would compute it: just a bunch of matrix multiplies followed by a non-activation, followed by an activation function. So now I'd like to show you a

demo of how these neural networks work. So this is a JavaScript demo that I'll show you in a bit, but basically this is an example of a two-layer neural network classifying, doing a binary classification task. So we have two classes, red and green, and so we have these points in two dimensions, and I'm drawing the decision boundaries by the neural network. And so what you can see is when I train a neural network on this data, the more hidden neurons I have in my hidden layer, the more wiggle your neural network has, right? The more it can compute crazy functions. And just to show you effect also of regularization strength, so this is the regularization of how much you penalize large Ws. So you can see that when you insist that your Ws are very small, you end up with

very smooth functions, so they don't have as much variance. So these neural networks, there's not as much wiggle that they can give you. And then as you decrease the regularization, these neural networks can do more and more complex tasks. So they can kind of get in and get these little squeezed-out points to cover them in the training data. So let me show you what this looks like joint training. Okay, so there's some stuff to explain here. I'll let me first actually want, so you can play with this because it's all in JavaScript. Okay. All right, so what we're doing here is we have six neurons, and this is a

binary classification data set with circle data. And so we have a little cluster of green dots separated by red dots, and we're training a neural network to classify this data set. So if I restart the neural network, it just started off with a random EE, and then it converges the decision boundary to actually classify the data. What I'm showing on the right, which is the cool part, is this visualization is one interpretation of the neural network here. It's what I'm taking this grid here, and I'm showing how this space gets warped by the neural network. So you can interpret what the neural network is doing is it's using its hidden layer to transform your input data in such a way that the second hidden layer can come in with a linear classifier and classify your data. So here you see that the neural network arranges your space, it

warps it such that the second layer, which is really a linear classifier on top of the first layer, is again put a plane through it. Okay, so it's warping the space so that you can put a plane through it and separate the points. So let's look at this again. So initial, okay, so you can roughly see what how this gets warped so that you can linearly classify the data. This is something that people sometimes also refer to as kernel trick—it's changing your data representation to a space where it's linearly separable. Okay, now here's a question: if we'd like to separate, so right now we have six neurons here in the intermediate layer, and it allows us to separate out these data points, so you can see actually those six neurons

Roughly, you can see these lines here, like they're kind of like these functions of one of these neurons. So, here's a question for you: what is the minimum number of neurons for which this data set is separable with the neural network? Like, if I wanted the neural network to correctly classify this, how many neurons do I need in the hidden layer as a minimum? I've heard some theories, some force and binary search, so intuitively the way this will work is... let's see, let's see. For—so what happens with four is there's...

One neuron here that went from this way to that way, this way to that way, this way to that way. There's four neurons that are cutting up this plane and then there's an additional layer that's doing a weighted sum. So, in fact, the lowest number here, which I would be, is three, which would work. So, with three neurons—oh, okay, it's going to happen. So, one plane, second plane, third plane. So, three linear functions with a non-linearity and then you can basically, with three lines, you can carve out the space so that the second layer can just combine them when their numbers are one and not zero at two, certainly. So, at two, this will break because two lines are not enough. Suppose this works something—I'm not going to...

...look very good here, yeah. So, with two, basically, it will find the optimum way of just using these two lines. They're kind of creating this tunnel and that's the best you can do. Ok, the curve, I think, which shall not only retain my using 10h. Yeah, I'm not sure exactly how that works out. If I was using ReLU, I think there would be much sorrel. Ooh, is the—so let me change to ReLU and I think you'd see sharper boundaries. Yeah, yes, this is three. Oh, you can do four, so let's do... yeah, that's because it's because in some...

...of these parts there's more than one of those ReLUs are active, and so you end up with—there are really three lines, I think, like 1, 2, 3, but then in some of the corners, two real neurons are active and so these weights will add up. It's kind of funky, you have to think about it a bit, but ok. So, let's look at, say, 20 here. So, change to 20 so we have lots of space there and let's look at different data sets, like say spiral. So, you can see how this thing, just as I'm doing this update, it will just go in there and figure that out. Or very simple data set, it's not—okay, spiral, circle, yeah. And then random...

So, it's a random data and so it kind of goes in there and it like covers up the—the green ones from the red ones and yeah. And with fewer, say like five—oh, I'm going to break this now. It's not going to—okay, so if five, yeah. So, this will start working worse and worse because you don't have enough capacity to separate out this data. So, you can play with this in your every time, okay? And so, as a summary, we arrange these neurons into neural, in neural networks, into fully connected layers. We've looked at backprop and how this gets changing computational graphs and they're not really neural and, as well, we'll see soon the...

Bigger the better and we'll go into that a lot. I want to take questions before I—and just, sorry, we're not any questions, go ahead. We have two more minutes. Sorry, always better to warn yours—or is it also like over big issues? Yeah, so thank you. So, is it always better to have more neurons in your neural network? The answer to that is yes, more. It's always better, it's usually computational constraint, so more will always work better, but then you have to be careful to regularize it properly. So the correct way to constrain your neural networks to not overfit your data is not by making the network smaller. The correct way to do it is to increase your regularization. So you always want to use as large of a...

Network as you want but then you have to make sure to properly regularize it. But most of the time, because computational reasons, you have finite amount of time, you don't want to wait forever to train your networks, you'll use smaller ones for practical reasons. Question: do you regularize each layer equally? Usually you do, as a simplification. Yeah, most often when you see networks trained in practice they will be regularized the same way throughout but you don't have to necessarily. Good. Is there any value to using second derivatives, using the Hessian in optimizing neural networks? There is value sometimes when your datasets are small. You can use things like L-BFGS which I didn't go into too much and...

That's a second order method, but usually the datasets are really large and that's when L-BFGS doesn't work very well. So when you have millions of data points you can't do L-BFGS for various reasons, yeah. And L-BFGS is not very good with mini-batch; you always have to do full batch by default. Question—yeah, so what is the trade-off between depth and size roughly? Like, how do you allocate—not a good answer for that, unfortunately. So you want depth is good, but maybe after like 10 layers, maybe if you have simple data set it's not really adding too much. We have one more minute so I can still take some questions. You...

Had a question for a while? Yeah, so the trade-off between where do I allocate my capacity? Do I want this to be deeper or do I want it to be wider? Not a very good answer to that. Yes, usually, especially with images, we find that more layers are critical but sometimes when you have simple datasets like 2D or some other things like depth is not as critical and so it's kind of slightly data dependent. With a question over there: different activation functions for different layers, does that help? Usually.

It's not done, usually just kind of pick one and go with it. So say I for comm, that's for example. We'll also see that most of them are trained just with relatives, and so you just use that throughout, and there's no real benefit to switching them around. People don't play with that too much, but in principle, there's nothing preventing you. So it is 4/20, so we're going to end here, but we'll see lots of more neural networks. So a lot of these questions, we'll go through them.

From YouTube captions, lightly punctuated for readability. Timestamps link to the video above. Errors are possible.

Cite this recording

Andrej Karpathy, “CS231n Lecture 4: Backpropagation, Neural Networks 1 (2016)”, 2016. Transcript and video: Thinkers Archive, https://thinkersarchive.com/andrej-karpathy/backpropagation-cs231n-lecture-4-2016/

Quoting a passage? Link to its exact moment: every timestamp above has its own anchor (for example https://thinkersarchive.com/andrej-karpathy/backpropagation-cs231n-lecture-4-2016/#t-134).

Search every transcript
Open the full search page →