I note that word-level models work better than character-level models, but this is surely a temporary thing.
I describe RNN applications in NLP and speech as including transcribing speech to text, generating handwritten text, and language modeling at both the character and word levels.
I list frame-level video classification, image captioning, video captioning, and visual question answering as computer-vision applications of RNNs.
I say vanilla RNNs can memorize sequences extremely well without necessarily showing convincing signs of generalizing in the correct way.
I would like models to maintain a huge representation or memory while keeping computation per time step fixed.
I call attention the most interesting recent architectural innovation in neural networks.
I point to Neural Machine Translation by Jointly Learning to Align and Translate and Memory Networks as examples of soft attention, including for toy question answering.
I say hard attention calls for techniques from reinforcement learning such as REINFORCE because it samples a particular memory chunk and is non-differentiable.
I recommend David Silver’s class and Pieter Abbeel’s classes for learning about REINFORCE, reinforcement learning, and policy-gradient methods.
I recommend Keras and Passage for Theano, as well as the Torch code released with this post, for working with RNNs.
I point to my raw NumPy code implementing an efficient, batched LSTM forward and backward pass, and to NeuralTalk, my NumPy-based RNN/LSTM image-captioning project.
I gave a talk on this work at the London Deep Learning meetup and shared a video of it.
I expect a hybrid CNN for raw perception and an RNN glance policy to will become pervasive in perception, especially for more complex tasks that go beyond classifying some objects in plain view.
I note that if you double the size of the hidden state vector you’d quadruple the amount of FLOPS at each step, due to the matrix multiplication.
I describe Neural Turing Machines as enabling read/write operations between large, external memory arrays and a smaller set of memory registers, where computation happens.
I say a soft attention scheme for memory addressing keeps the model fully-differentiable, though efficiency is sacrificed because everything that can be attended to is attended to, but softly.
I describe hard attention as significantly more philosophically appealing, scalable and efficient, but unfortunately it is also non-differentiable.
I recommend theses from Alex Graves, Ilya Sutskever, and Tomas Mikolov for reading up on RNNs.
I point to Keras and Passage for Theano, the Torch code released with this post, a raw NumPy gist for an efficient batched LSTM forward and backward pass, and my NumPy-based NeuralTalk project for image captioning.
I trained an RNN on the source file of this blog post, but at about 46K characters I haven’t written enough data to properly feed the RNN.
I've the RNN with and works, but the computed with program of the
RNN with and the computed of the RNN with with and the code
I believe RNNs will become a pervasive and critical component to intelligent systems.
I see training character-level language models as a fun exercise. With my released char-rnn code, I can train on a large text file and sample from the resulting model; when readers get fun results from their own data, I invite them to let me know. If the Torch/Lua code is hard to follow, I point to a simpler 100-line gist.
I released char-rnn on Github under the MIT license.
char-rnn takes one large text file and trains a character-level model that you can then sample from.
Training on CPU will be about a factor of 10x slower than using a GPU.
When readers get lost in the Torch/Lua codebase, I point them to a more fancy version of this 100-line gist.
I say Torch 7 has recently become my favorite deep learning framework.
I had only started working with Torch/LUA over the last few months and it hasn’t been easy.
To get things done, I spent a good amount of time digging through the raw Torch code on Github and asking questions on their gitter.
Once I got a hang of Torch, I found that it offers a lot of flexibility and speed.
I had also worked with Caffe and Theano in the past.
I believe Torch, while not perfect, gets its levels of abstraction and philosophy right better than others.
My framework-design preferences emphasize separating general-purpose Tensor operations from deep-learning code, making pretrained models easy to share, and avoiding mandatory compilation during development. The four desired features are recorded individually below.
My first desired feature is a CPU/GPU transparent Tensor library with a lot of functionality (slicing, array/matrix operations, etc. ).
My second desired feature is an entirely separate code base in a scripting language (ideally Python) that operates over Tensors and implements all Deep Learning stuff (forward/backward, computation graphs, etc).
My third desired feature is to easily share pretrained models (Caffe does this well, others don’t).
My fourth desired feature is NO compilation step (or at least not as currently done in Theano).
As networks become larger and more complex, time-unrolled in complex graphs, it is critical that these do not compile for a long time or development time greatly suffers.
I believe that by compiling one gives up interpretability and the ability to log/debug effectively.
I consider compilation acceptable as an optional production-efficiency step once a graph has been developed; I do not want it to obstruct iterative development.
I use generated samples as evidence of what a character-level LSTM learns during training, not as polished text. In my War and Peace demonstration, I compare samples at intervals; a separate Wikipedia RNN visualization lets me inspect next-character predictions and selected hidden-state activations.
I trained an LSTM on Leo Tolstoy’s War and Peace and generated samples every 100 iterations of training.
At iteration 100, the model samples random jumbles, but it is starting to get an idea about words separated by spaces.
At iteration 100, it sometimes inserts two spaces and doesn’t know that comma is amost always followed by a space.
At 300 iterations, the model starts to get an idea about quotes and periods; the words are now also separated with spaces, and periods begin appearing at sentence ends.
At iteration 500, the model has learned to spell the shortest and most common words such as “we”, “He”, “His”, “Which”, “and”.
At iteration 700, I’m starting to see more and more English-like text emerge.
At iteration 1200, I’m seeing use of quotations and question/exclamation marks.
At iteration 1200, longer words have now been learned as well.
By about iteration 2000, the samples contain properly spelled words, quotations, names, and so on.
The progression suggests the model first discovers the general word-space structure and then rapidly starts to learn the words.
I describe word learning as starting with short words and then eventually the longer ones.
Topics and themes that span multiple words, and longer-term dependencies in general, start to emerge only much later.
The demonstration compares samples at iterations 100, 300, 500, 700, 1200, and 2000. It does not specify the training configuration, model size, dataset preprocessing, or quantitative evaluation, and it does not define when a word, topic, theme, or longer-term dependency counts as learned.
I feed a Wikipedia RNN model character data from the validation set and visualize its next-character predictions.
Under every input character, the visualization shows the top 5 guesses the model assigns for the next character.
The guesses are colored by probability: dark red = judged as very likely, white = not very likely.
The input character sequence is colored based on the firing of a randomly chosen neuron in the hidden representation of the RNN; green = very excited and blue = not very excited.
For LSTMs, the activation values are between [-1,1] in the hidden state vector, which is the gated and tanh’d LSTM cell state.
The model is very confident about characters during the http://www. sequence.
I look at 4 different ones that I found and thought were interesting or interpretable, while noting that many neurons are not interpretable.
I suggest that different neurons might be looking for different patterns.
One highlighted neuron seems to get very excited about URLs and turns off outside of the URLs; I think the LSTM is likely using it to remember if it is inside a URL or not.
Another highlighted neuron gets very excited when the RNN is inside the markdown environment and turns off outside of it.
The markdown-scope neuron must wait for the second [ and then activate; another neuron likely handles counting whether the model has seen one or two [ characters.
A highlighted neuron varies seemingly linearly across the environment; its activation is giving the RNN a time-aligned coordinate system across the scope.
The RNN can use this information to make different characters more or less likely depending on how early/late it is in the scope (perhaps?).
A neuron is relatively silent but sharply turns off right after the first "w" in the "www" sequence.
The RNN might use this neuron to count up how far in the "www" sequence it is, so it can know whether it should emit another "w", or if it should start the URL.
I say a lot of these conclusions are slightly hand-wavy because the hidden state of the RNN is a huge, high-dimensional and largely distributed representation.
I produced these visualizations with custom HTML/CSS/Javascript and linked a sketch of what’s involved at http://cs.stanford.edu/people/karpathy/viscode.zip.
I can condense the visualization by excluding the most likely predictions and only visualize the text, colored by activations of a cell.
I describe a large portion of cells that do not do anything interpretible, while about 5% of them turn out to have learned quite interesting and interpretible algorithms.
I say we didn’t have to hardcode at any point that tracking whether the model is inside or outside of a quote would be useful for next-character prediction.
I trained the LSTM on raw data, and one of its cells gradually tuned itself during training to become a quote detection cell since this helps it better perform the final task.
I call this one of the cleanest and most compelling examples of where the power in Deep Learning models (and more generally end-to-end training) is coming from.
The visualization shows patterns that may be functionally useful, but the proposed interpretations are tentative: the passage does not identify the neurons, quantify their activations, establish that the interpretations are correct, or specify the dataset size, architecture, or training details.
For a final challenge, I used character-level RNNs to generate Linux source code, then tried a separate experiment generating baby names. I chose code to push structured data to its limit; the samples were exploratory outputs, not verified programs.
I concatenated all source and header files from the Linux repository into a single file of 474MB of C code; I had considered training only on the kernel, which was only ~16MB.
I trained several 3-layer LSTMs over a period of a few days; they were sized as large as would fit on my GPU.
These Linux models had about 10 million parameters, which I described as still on the lower end for RNN models.
I don’t think it compiles; the generated output felt very much like a giant C code base, but I presented it as sampled code rather than verified software.
When I scrolled through the generated code, it felt very much like a giant C code base.
The generated Linux code was very good at making very few syntactic errors; for example, it used strings properly and handled pointer notation.
The generated code was very good at making very few syntactic errors: it used strings and pointer notation properly, opens and closes brackets {[ correctly and learns to indent its code very well.
The RNN peppers its code with comments here and there at random.
A common error was that the model can’t keep track of variable names: it used undefined variables, declared variables it never used, or returned nonexistent variables.
Examples of variable-tracking failures included using undefined variables such as rw, declaring unused variables such as int error, and returning nonexistent variables.
Other errors included tty == tty, which is vacuously true, and returning values from functions declared void. A later void function correctly returned nothing; I called the inconsistencies a common mistake due to long-term interactions.
When sampling a new file, the model recites the GNU license character by character, samples a few includes, generates some macros, and then dives into code.
Sometimes the model decided that it was time to sample a new file.
I linked 1MB of sampled Linux code at http://cs.stanford.edu/people/karpathy/char-rnn/linux.txt.
I cut short the Linux examples, saying I could probably write an entire blog post on just this part.
For another experiment, I trained an RNN on baby names and sampled names absent from the training data. I suggested the results might be useful as creative prompts.
I fed the RNN a large text file that contains 8000 baby names listed out, one per line.
I obtained the names from the Carnegie Mellon University NLP corpora page at http://www.cs.cmu.edu/afs/cs/project/ai-repository/ai/areas/nlp/corpora/names/.
I showed only names that do not occur in the training data; 90% don’t occur there.
I linked more generated names at http://cs.stanford.edu/people/karpathy/namesGenUnique.txt.
- Some of my favorite generated names were “Baby”, “Killie”, “Char”, “R”, “More”, “Mars”, “Hi”, “Saddie”, “With” and “Ahbort”.
I suggested the generated names could be inspiration when writing a novel, or naming a new startup.
I trained all five example character models with the released char-rnn code.
For each model, I use a single text file and train an RNN to predict the next character in the sequence.
I used concatenated Paul Graham essays as a small English-language sanity-check dataset.
I described Paul Graham as a relatively slow generator and imagined sampling startup wisdom on demand.
The Paul Graham corpus concatenates essays from roughly the last five years into an approximately 1MB file, or about 1 million characters; I considered this a very small dataset.
For the Paul Graham experiment, I trained a 2-layer LSTM with 512 hidden nodes and approximately 3.5 million parameters, using dropout of 0.5 after each layer.
I trained the Paul Graham model with batches of 100 examples and truncated backpropagation through time of length 100 characters.
With those settings, one batch took about 0.46 seconds on a TITAN Z GPU; using 50-character BPTT cut the time in half at negligible performance cost.
The Paul Graham samples were not going to replace Paul Graham anytime soon; the RNN had to learn English from scratch using a small dataset, including where to put commas, apostrophes, and spaces.
I liked that the generated Paul Graham text learned to support its own arguments with a reference-like marker such as [2].
One generated Paul Graham line that seemed occasionally insightful was “a company is a meeting to think to investors”.
I linked a 50K-character sample of the Paul Graham model’s output.
I adjust the Softmax temperature during sampling: reducing it below 1 makes the RNN more confident and conservative, while higher temperatures increase diversity at the cost of more mistakes, including spelling mistakes.
At temperature very near zero, the Paul Graham model repeatedly generated “that was a startup,” creating what I called an infinite loop about startups.
To test whether a character-level model could learn more structure and style than English spelling, I downloaded all of Shakespeare’s works and concatenated them into a single 4.4MB file.
For the Shakespeare experiment, I trained a 3-layer RNN with 512 hidden nodes on each layer for a few hours.
The Shakespeare RNN knows only characters, so it samples both speaker names and dialogue.
Some Shakespeare samples included relatively extended monologue passages, but I said I could barely recognize them as actual Shakespeare.
I linked a 100,000-character Shakespeare sample and noted that the provided code can generate an infinite amount of samples at different temperatures.
To increase the difficulty beyond spelling words and copying general syntactic structures, I trained an LSTM on structured markdown using the Hutter Prize 100MB dataset of raw Wikipedia.
Following Graves et al., I used the first 96MB of the Wikipedia dataset for training and the remainder for validation, and ran a few models overnight.
The model hallucinated a Yahoo URL that did not actually exist, while learning to open and close parentheses correctly.
In one sample, the Wikipedia model generated apparently valid XML and closed tags in the correct nested order, despite making up the timestamp, ID, and other details.
I linked 100,000 characters of sampled Wikipedia output.
After results suggested the model could learn complex syntactic structures, my labmate Justin Johnson and I pushed into more structured material by training on raw LaTeX from a book about algebraic stacks and geometry.
We downloaded a 16MB raw LaTeX source file and trained a multilayer LSTM on it.
The sampled LaTeX almost compiled; we manually fixed a few issues, after which it produced plausible-looking mathematics.
The LaTeX model sometimes tried to generate diagrams without figuring them out, and one sample skipped a proof with “Proof omitted.”
I said LaTeX has a relatively difficult structured syntactic format that I had not fully mastered myself.
In an unedited LaTeX sample, the model opened a proof environment but ended it with \end{lemma}, and opened an enumerate environment without closing it.
I attributed mismatched LaTeX environment closures to long-term dependencies: by the end of a proof, the model may have forgotten whether it was writing a proof or a lemma.
We observed that LaTeX environment-closing mistakes became less common with larger or better models, though they remained among the kinds of mistakes that occurred.
I train a character-level RNN to model the probability distribution of the next character given previous characters, which lets me generate new text one character at a time.
For the training sequence “hello”, I get 4 separate training examples: “h” predicts “e”, “he” predicts “l”, “hel” predicts “l”, and “hell” predicts “o”.
I use 1-of-k encoding; feed characters one at a time with the step function. Each character becomes an all-zero vector except for a one at its vocabulary index.
My example RNN has 4-dimensional input and output; hidden layer of 3 units; vocabulary h,e,l,o. Each output vector has one dimension per character and represents the confidence assigned to each possible next character.
In the first time step, the example RNN scores the next characters h=1.0; e=2.2; l=-3.0; o=4.1. The correct next character is “e”, so training should raise its score and lower the scores for the others.
After a parameter update, the example gives the correct first-step “e” score as 2.3 instead of 2.2.
I aimed for the short Python/NumPy example to be a concise, concrete summary for readers who are better at reading code than text.
I apply a Softmax classifier (cross-entropy loss) on every output vector simultaneously, using a target character at each of the 4 time steps.
I use backpropagation is a recursive application of the chain rule to determine how to adjust weights to increase scores for the correct targets; a parameter update nudges the weights in that gradient direction.
I repeat training until the network converges and its predictions become consistent with the training data, with correct characters predicted next.
I train with mini-batch Stochastic Gradient Descent; RMSProp or Adam to stabilize updates. I like these per-parameter adaptive learning-rate methods for stabilizing the updates.
In “hello”, the first l target is l; second l target is o. The RNN therefore cannot rely on the input alone and must use its recurrent connection to keep track of context.
At test time, I sample a next character from the distribution and feed it back in repeatedly, generating text one character at a time.
I wrote a minimal character-level RNN language model in Python/NumPy for educational purposes; it is only about 100 lines long. The example results that follow are produced with the more efficient Lua/Torch codebase.
I explain recurrent neural networks (RNNs) through sequence processing and character-by-character text generation. My first image-captioning RNN began producing descriptions that looked very good and were close to making sense after a short training period; that result challenged the common belief that RNNs were difficult to train.
I remember that my first image-captioning model started generating descriptions “Within a few dozen minutes” of training, using rather arbitrarily chosen hyperparameters.
With more experience, I reached the opposite conclusion about RNNs’ difficulty: about a year later I was training them regularly and had seen their power and robustness many times.
I released char-rnn, code for training character-level language models based on multi-layer LSTMs; given a large chunk of text, it learns to generate text like it one character at a time.
- I contrast fixed-size neural-network interfaces with recurrent networks, which repeatedly apply a fixed learned transformation and so do not require sequence lengths to be specified in advance. The five input/output patterns I describe are: fixed-sized input to fixed-sized output (image classification); fixed-sized input to sequence output (image captioning); sequence input to fixed-sized output (sentiment analysis); sequence input to sequence output (English-to-French translation); and synchronized sequence input and output (labeling each video frame).
I describe an RNN as combining its input vector with its state vector through a fixed, learned function to produce a new state vector; in programming terms, this resembles running a fixed program with inputs and internal variables.
I note that RNNs are Turing-complete and can simulate arbitrary programs with proper weights, but caution that this claim should not be overinterpreted.
If training vanilla neural nets is optimization over functions, training recurrent nets is optimization over programs.
I describe a recurrent attention policy that learns to read out house numbers from left to right.
I describe a recurrent network that generates digit images by learning to sequentially add color to a canvas; these examples show how recurrent models can process fixed-sized data sequentially.
In my simple RNN interface, each step accepts an input vector x and returns an output vector y. The output depends on the current input and the history of prior inputs. The network maintains internal state, represented in the simplest case by a hidden vector h, which is updated on each call.
self.h = np.tanh(np.dot(self.W_hh, self.h) + np.dot(self.W_xh, x))
y = np.dot(self.W_hy, self.h)
The vanilla RNN uses the parameter matrices W_hh, W_xh, and W_hy; its hidden state starts as a zero vector. np.dot performs matrix multiplication, and np.tanh squashes activations into [-1, 1]. The source’s alternate displayed math notation for the hidden-state update is incomplete.
I initialize the RNN matrices with random numbers and use a loss function to express which outputs y I want in response to input sequences x.
y1 = rnn1.step(x)
y = rnn2.step(y1)
This two-layer example passes the first recurrent module’s output into the second module as its input; gradients flow through the modules during backpropagation.
I say that an LSTM is a particular type of recurrent network that works slightly better in practice because of its more powerful update equation and appealing backpropagation dynamics.
I use the terms “RNN/LSTM” interchangeably from this point in the post, and all experiments in this post use an LSTM.
The post focuses on generating text one character at a time to demonstrate recurrent networks. It introduces the question “how is that even possible?” and does not provide the detailed LSTM update equation.
I say that RNNs essentially describe programs.
I say that even fixed-vector inputs and outputs can be processed sequentially with recurrent networks.
I initialize the hidden state self.h with the zero vector.