Andrej Karpathy: Recurrent Neural Networks & Long Short-Term Memory

On RNNs and LSTMs: Text and Image Generation

Conference/meetup talk, February 2017
Video thumbnail: Andrej Karpathy on RNNs and LSTMs: Text and Image Generation
16 mintalk21K views across 1 upload3,346-word transcriptWatch on YouTube ↗

What Karpathy talks about

Andrej Karpathy gave this conference talk in February 2017, explaining recurrent neural networks and LSTMs through text generation demos and image captioning examples.

Also known as: RNNs and LSTMs; Recurrent Neural Networks and Long Short-Term Memory; Text and Image Generation.

Karpathy explains recurrent neural networks from first principles, focusing on how their state lets them process sequences and predict the next element. He uses character-level language models to show how RNNs learn statistical structure in text, code, poetry, and other sequences.

He then shows how the same sequence model can be combined with a convolutional neural network for image captioning, and extended further into dense image captioning and image-region description. The talk emphasizes practical intuition, surprising emergent behavior, and how simple code can produce powerful results.

Karpathy speaks throughout.

In his words

“The RNN starts to discover that okay this input data is actually made up of words”
at 3:58
“You can generate infinite poetry like this”
at 5:40
“The model also has a very good idea of object parts”
at 13:35
“We are teaching currently a class at Stanford called CS231n”
at 14:44

Key points

  • RNNs are flexible sequence models that can map sequences to sequences, images to text, or text to text.
  • A simple recurrent step updates hidden state from the previous state and current input.
  • Character-level RNNs learn next-character prediction from raw text and can generate Shakespeare, code, math, and recipes.
  • The model discovers interpretable internal cells, such as quote detectors and line-length trackers, without being explicitly programmed.
  • Image captioning combines a CNN for visual features with an RNN for sentence generation.
  • Dense image captioning extends the idea to detect and describe multiple regions in one image.
  • The same model can also search image databases by text queries over regions.

Full transcript: Andrej Karpathy, Recurrent Neural Networks & Long Short-Term Memory (2017)

Thank you for the introduction. So I'll be talking about Recurrent Neural Network (RNN) Language models especially in the context of Dense Image Captioning and I'll show you what that means by the end of the talk. Now Recurrent Neural Networks (RNN) are wonderful models to work with because they offer a lot of flexibility in how you can design your Recurrent Neural Network architectures. So, normally when you're working with neural networks you're in the case in the very left where you have at some kind of a fixed sized input vector shown in red then you process it with some hidden layers shown in green and then you predict a fixed size output vector in blue and so an example of this setting is say image classification. So with Recurrent Neural Networks you can set up other kinds of architectures for example you can operate over sequences in input/output or both. So in a case of image captioning we're taking a single fixed sized image and we're producing a sequence of words that are part of the caption of that image.

In a setting of Sentiment Classification we are taking a sequence of words and we're trying to predict whether or not the sentiment is positive or negative. In the case of image in Machine Translation we can take a sequence of words in English and we can produce a sequence of words in French that consists of the translation, or we can be in the setting of video classification where we have a sequence of video frames and we'll try to classify every one of them but crucially we want every single frames predictions to not be just a function of that frame but every frame that has come before it in the video. Now, it turns out that recurrent neural networks actually have a very simple API they basically consist of a single step function and the step function takes a vector X and it produces a vector Y but crucially the RNN has a state that it gets to update every time it sees a vector X come in and so one specific implementation of this in a vanilla Recurrent Neural Network (RNN) might look as follows. In this case the Recurrent Neural Network (RNN) state is made up of a single hidden state vector and the step function takes a vector X and then it gets to update its state vector according to the recurrence formula shown in both code, tech form and in mathematical form below.

So we get to update our head and state based on the previous hidden state and based on the current input X that has fed into the RNN and then we get to predict the vector Y based on the hidden state age and so these matrices here w, w_hh, w_xh & w_hy those are the parameters of a recurrent neural network and as you change these parameters of course you're going to get a different behavior of the recurrent neural network and now we'd like some specific kind of behavior from the RN and so we feed it a lot of data and we tune these parameters over time. So for example one way to endow semantics on top of the vectors x and y is to work in the context of character level language models and before I dive into the example I'd just like to point out that in my own work on these models I've worked on top of a lot of previous work from Alex Graves, Ilya Sutskever, Tomáš Mikolov and Yoshua Bengio and the way this will work is in a character level RNN model we are going to consume a sequence of characters and then we're trying to predict the next character in the sequence. So, suppose we're working with this simple example of a string [h,e,l,o] that we'd like to train on what we're going to do is we're going to feed the characters [h,e,l,l] into the RNN one step at a time so we have four distinct time steps here and we're feeding the characters into the RNN and the RNN can only process vectors so we have to encode them in some ways such as for example one of K encoding and at every single time step the RNN will update its hidden state based on the recurrence formula that I've shown you so we have three numbers in hidden state in this case and we're using that formula to compute the hints the hidden vector at every single time step and now the RN is trying to predict the next character in a sequence at every single time step since we have four characters in our example vocabulary here the RNN has to produce at every time step four numbers that gives scores or log probabilities for every single next

character in a sequence so for example in the very first time step we fed in the letter H and with the current setting of weights in the RNN and right now the RNN assigns the letters [h-e-l & o] log probabilities 1, 2.2, -3 and 4.1 respectively. In particular we know that in this training sequence the letter [e] should follow [h] and so we know that the score 2.2 we'd like that to be higher and the scores of all the other characters in red should be lower and so every single time step what this amounts to is we want the green numbers to be higher and the red numbers to be lower that's what you encode in your gradient signal and back propagate through the network and the back propagation signal then tells you the gradients on the weights and that tells you how to adjust your weights so that the predictions are more consistent with your training data. What we can do now is we can take an entire set of documents and we can feed it into the recurrent neural network and it will learn how to predict these sequences so for example as a specific example we can feed in a poem of William Shakespeare and for our purposes is just a giant string of characters that we plug into the RNN one at a time and that we train on. Then we train the recurrent network on this and what we can do then is use the RNN to generate or sample or hallucinate these kinds of sequences that it has seen in training data one character at a time. Now when you train the RNN what you'll see is that in the beginning we just start off with random weights right so the predictions that it produces are just complete gibberish in the very first box there but then when you train a bit the RNN starts to discover that okay this input data is actually made up of words - it starts to use spaces, it starts to use quotes and periods at the end of sentences and so on and as you train more and more it discovers more and more long term statistical structure in your data and eventually it's producing samples of poems that are nearly indistinguishable at least

on a low-level statistical level to two points from Shakespeare and so you can generate entire poetry infinite poetry from Shakespeare so I'll just read one paragraph for example: 'Alas I think he shall become approached and the day when little strain would be attained into being never fed and who is but a chain and subject of his death I should not sleep' and so you can generate infinite poetry like this. Of course we can feed in any kind of character sequence that we like, and we have. So for example we found this open source book on algebraic geometry so we just take all source code for this book and we feed it one character at a time into the RNN and then the RNN learns to generate mathematics that almost compiles (we have to fix it a tiny bit) but what it comes up with is basically it starts to create its own lemmas, it starts to prove them, it puts little rectangles at the ends of its proofs and just kind of samples all of this. I can barely distinguish it from the actual data, sometimes it tries to create diagrams so in this case it has almost succeeded. My favorite part is on the top left the proof is omitted for some lemma so you can feed in any kind of character data we also tried feeding in a code so I went on the Linux repository and I downloaded all source code of Linux, this turns out to be about 16 megabytes (or was it 600?) a lot of megabytes of text and it's a C code and then you feed it into the RNN and then it can just create code and so this is a function that was generated by the RNN and you can see that it takes some arguments it has some variables it creates loops, if statements, it creates its own bogus comments and syntactically there's very few mistakes in tactically in what the RNN does some of the mistakes you'll notice

by the way is that it uses variables that were not declared or it declares variables and never uses them those are the kinds of mistakes you'll see. Sometimes the RNN decides that it's time to start a new c file and what it does then is it recites character by character the blue gpl-licensed (it has learned it by heart) and then it creates some includes and then sample some macros and then dives into code and so it has a very good idea of these statistical patterns in the data and how they should just be created there. Everything I've described so far by the way can be implemented in about 200 lines of Python code with the only dependency is numpy and so this is a gist that you can look up on github and this is an entire character level language RNN model in these hundred lines. Now of course if you'd like to actually be more serious and you'd like to use GPUs and so on then you might be interested in my other project called char-RNN and this is a more serious implementation but it's basically the exact same thing.

Now many people have taken this code and they've kind of run it on very different things so we can sample cooking recipes, this one is for a basic cheese wings, and you know there's a whole bunch of ingredients you preheat the oven to 350 degrees Fahrenheit and so on and so forth so you can look at these people have also created all kinds of twitter BOTS so this char 9 was in the Bible and now it's sampling verses, you can feed it music, it can generate magic cards and so on so basically it's quite powerful and it's very simple code base. Now in my own work at Stanford with my equal co-author on this paper Justin Johnson my adviser Fei-Fei Li we were more interested in kind of studying exactly how this works so we went through character level RNNs and we're studying the statistical patterns how this works where the kinds of errors that it's still making and how they change as you scale up the model and so one of the experiments I'd like to highlight for you is we were looking at interpretable cells in the RNNs and so in these experiments we get to pretend that we are neuroscientists and we get the RNN to read some text in this case some piece of code and we're looking at a particular cell in the RNN a particular hidden state vector and we're looking at what excites it as it's reading this text and so this hidden state neuron does not really have an interpretable sequence that it responds to but as you go through many neurons you find several that are quite interpretable so for example we found a quote detection cell in the RNN it basically is off but then when it sees a quote it turns on and then it stays on until the quote ends and so what's remarkable about this is that we of course didn't specify this but in the process of the RNN trying to predict the next character it has decided that it's useful to allocate some space in its hidden state to keeping

track of the quotes and so it just developed this little algorithm internally you know through back propagation. We also found some cells that keep track of line lengths so in this data set here there's a newline character after roughly every 80 characters there's a newline character that starts a new line and the RNN has therefore decided that it's a good idea to actually create a small counter for how far along you are in the sequence and so there's a cell that basically turns on and then slowly decays over time and this might help you predict the next newline character. There are these cells that only respond in F statements in code or cells that only respond inside comments or strings or cells that get more excited as you indent your code and you're deeper in the nested expression and so basically the RNN just truncates your data in all these different patterns so that it can perform this prediction.

Now in my own work roughly a year ago I realized that these RNN models were extremely powerful and I was specifically interested in applying them in a case of visual recognition and so we're going to look at image captioning where we take an image and then were using an RNN to predict a sentence for it and this model is made up of two components: there's a convolutional neural network which we know is very good at seeing images and then there's a recurrent neural network which we know is very good at modelling sequences in this case sequences of words that make up a sentence and then I like to use the analogy of playing with neural networks is kind of playing with Lego blocks and so what we do is we just kind of stick these two components together that corresponds to the arrow in between the two modules so just to give you an idea about how this would work and how we could caption a test image, we take a test image and we feed it through a Convolutional Neural Network (CNN) now normally at the end of a Convolutional Network you have a classifier that would predict one of 1,000 categories for this image but in this case we're going to get rid of that classifier and instead we're going to redirect the representation on the top layer of the Convolutional Network into the Recurrent Neural Network so we begin the generation with a special start token and we forward the Recurrent Neural Network to give us the probability distribution over the first word in the description in y0 and critically this prediction is also a function of the image through that added interaction into the RNN and so you might imagine for example that the presence of the straw textures in this man's hat can positively influence the probability of sampling the word straw in this context at the first time stem. So we sample from that distribution at the very first time step suppose that the word that was sampled is indeed straw and we feed it back into the RNN and we forward again to get a parallel distribution over the second word in a sequence and we sample from it again and suppose

that it gives us the word hat and we continue in this fashion just plugging in the words and it's generating a new word for this image until it samples a special end token and that's the period I did that the sentence and at this point the RNN would have described that image as a straw hat period, one word at a time. So we train these data we train these models and to end on image sentence data sets one popular example right now that people are using often is Microsoft cocoa it consists of roughly hundred thousand images and they are described with five sentences each and this is data from Amazon Mechanical Turk and so there's an example of a training image with some of its captions and when we train this the RNN learns to describe these images and so here are some examples: so in the top row for example we have a man in a black shirt playing guitar or a construction worker in an orange safety vest working on the road and so on. On the bottom row I have some of my favorite failure cases we have a young boy holding a baseball bat or a cat sitting on the couch with the remote control or a woman holding a teddy bear in front of a mirror I'm guessing that these lock texture on the man's sweater or we have just a complete failure case of a horse in the middle of a road but I can't see any horse so not sure what happened there.

Now in my most recent work again was Justin Johnson my eco caught on this paper and my advisor Fei-Fei Li we've extended this basic model into this monster on the bottom and effectively what this amounts to is what we had right now the image sentence captioning model is it takes a full image and it describes of the single sentence what we're doing now in this new model is we're tackling the joint task of both detection and description so we can take an image and forward it through this model and in a single forward pass of a network we can both detect and describe everything in the image and so here in this example you have detected a trunk of an elephant, or that whole elephant, or the ball is white, or there are large green trees in the background, or the roof of the building, the leg of an elephant and so on. So everything is described in the image. Here's another example; we have light on a wall or sign on the wall, a man sitting on a table, you know, white laptop on the table and so on. And so there are hundreds of descriptions that this RNN produces for this image but I'm only showing some of the top 20 because it's way too dense otherwise. The model also has a very good idea of object parts for example it knows that there's a tail of a plane or an engine of a plane or the nose of a plane and so on.

We can also run this task conversely and what we can do is we can query with a small piece of text and then we can get the model to look through a database of images for regions in your images that are compatible with that text snippet. So, for example, when the query is 'head of a giraffe' we go off and we find all these little heads of giraffes, or legs of zebra, or red and white signs, or white tennis shoes and so on so we can search for arbitrary little text snippets in large collections of datasets and it's relatively efficient. Now if you'd like to learn much more about these topics we are teaching currently a class at Stanford called CS231n and Justin and Fei-Fei are my co instructors and lecture video slides notes and assignments everything is available so you can learn much more about the topic and I think this is the last slide so I'm done. Thank you.

From the video's published captions. Timestamps link to the video above. Errors are possible.

Cite this recording

Andrej Karpathy, “Recurrent Neural Networks & Long Short-Term Memory (2017)”, Conference/meetup talk, February 2017. Transcript and video: Thinkers Archive, https://thinkersarchive.com/andrej-karpathy/rnns-lstms-talk-2017/

Quoting a passage? Link to its exact moment: every timestamp above has its own anchor (for example https://thinkersarchive.com/andrej-karpathy/rnns-lstms-talk-2017/#t-238).

Search every transcript
Open the full search page →