Blue Q boxes are questions for you to answer by hand, in a notebook, with a pen. Not because I am old fashioned. Writing something down by hand is slow, and slow is the point: it is very hard to write an explanation you do not actually understand. You are welcome to use AI in this class for the mechanics of code, but these boxes are the part where you do the thinking yourself. Bring your written notes to class, I will ask to see them.
Green You Try boxes are optional code for you to work through. Nothing is collected and nothing is graded. They are there because you will learn more from changing a number and rerunning than from watching me do it.
Every code cell begins with a tag that tells you what to do with it.
# RUN THIS. Setup, loading data, a plot. Copy it, run it, move on. You do not need to be able to write it from memory.
# LEARN TO WRITE THIS. The pattern of the day. The homework will ask you for it, and so will the exam. Type it out yourself at least once rather than pasting it.
# DEMO ONLY. Code that exists to show one idea. You do not need to be able to write it yourself.
# UNDERSTAND THESE STEPS. Code that shows how something works inside, one small step at a time. Read it and make sure you understand what each line does. You do not need to memorize it or be able to write it from scratch.
Reading: Geron chapter 13, the sections LSTMs and GRUs, and chapter 14, the section Embeddings (inside “Generating Shakespearean Text Using a Character RNN”).
So far our networks have looked at one row of a table (Days 9 to 13) or one picture (Day 14). Today we are going to work with a sequence: words in a sentence, one after the other. Here the ORDER matters! “not good, loved it” and “good, not loved” use almost the same words, but they mean very different things.
So how do we deal with text in machine learning? There are a few issues we need to think about:
A network needs numbers, and words are not numbers. We will learn about something called an embedding that turns words into numbers.
Reviews have different lengths and the important word can be anywhere. A recurrent neural network (RNN) reads the words one at a time and keeps a memory as it goes.
Here is the plan for today:
Make some movie reviews where we know exactly where the important word is.
Turn words into numbers with nn.Embedding.
See how an RNN reads one word at a time.
Train an RNN on short reviews (it works) and on long reviews (it fails).
Figure out why it fails: the gradient for the early words vanishes.
Fix it with a GRU, an RNN with a gate on its memory.
Next class (Day 16) is attention, and the problem we find today is the reason attention was invented.
The Data - Made Up Movie Reviews
Real review data sets (like the IMDB reviews in the reading) are big and messy, and we would have no idea which words the network is actually using. So today we will make our own reviews! Each review is a string of random filler words (“the”, “movie”, “popcorn”, …) with one feeling word dropped in at a random spot. If the feeling word is positive (“great”, “loved”, …) the review is positive, and if it is negative (“boring”, “hated”, …) the review is negative.
Because we made the data, we know a perfect network could get 100% accuracy, and we can make the reviews as long as we want. So we can ask a really specific question: how far back can the network remember?
# RUN THIS. Imports, the words, and a function that makes reviews.import numpy as npimport matplotlib.pyplot as pltimport torchimport torch.nn as nnfrom torch.utils.data import TensorDataset, DataLoaderfeeling_words = ["great", "good", "fun", "loved", "wonderful", # positive, ids 0 to 4"bad", "boring", "awful", "hated", "terrible"] # negative, ids 5 to 9filler_words = ["the", "movie", "was", "and", "a", "plot", "actors", "it", "story", "long","music", "ending", "i", "saw", "with", "my", "friends", "on", "friday", "popcorn"]vocab = feeling_words + filler_words # every word gets an id: its spot in this listvocab_size =len(vocab)def make_reviews(n_reviews, n_words, seed): generator = torch.Generator().manual_seed(seed) # so we get the same reviews every time# Start with all filler words (ids 10 to 29) X = torch.randint(10, vocab_size, (n_reviews, n_words), generator=generator)# Pick one feeling word (ids 0 to 9) and one spot for it, for every review feeling = torch.randint(0, 10, (n_reviews,), generator=generator) spot = torch.randint(0, n_words, (n_reviews,), generator=generator) X[torch.arange(n_reviews), spot] = feeling # drop the feeling word into its spot# Positive (ids 0 to 4) is label 1, negative (ids 5 to 9) is label 0 y = (feeling <5).long()return X, ydef to_words(review): words = []for word_id in review: words.append(vocab[word_id])return" ".join(words)print("vocabulary size:", vocab_size)
vocabulary size: 30
# RUN THIS. 4,000 short reviews to train on and 1,000 to validate on, 10 words each.X_train, y_train = make_reviews(4000, n_words=10, seed=0)X_valid, y_valid = make_reviews(1000, n_words=10, seed=1)print("X_train:", X_train.shape)print("the first review as ids:", X_train[0])for i inrange(5):print(y_train[i].item(), " ", to_words(X_train[i]))
X_train: torch.Size([4000, 10])
the first review as ids: tensor([14, 29, 23, 10, 7, 29, 17, 13, 27, 13])
0 a popcorn saw the awful popcorn it and on and
0 movie actors friends popcorn friday friends friends story boring saw
0 actors popcorn ending with terrible movie long long long the
1 movie wonderful and the my plot was popcorn ending story
0 friday hated friends long ending on and my was ending
Each review is a row of 10 word ids, and the label is 1 for positive and 0 for negative. They do not read like real sentences, we did that on purpose. The only word that matters is the feeling word. This will let us really explore what the network is doing.
Words to Numbers - Embeddings
So how do we turn words into numbers? Could we just hand the network the word ids? No! The ids are only names. “great” is 0 and “good” is 1 and “popcorn” is 29, but that does not mean “popcorn” is 29 times more of anything. We made up the order of the vocabulary list. Se we need to create a smart way to capture the meaning of the words.
One fix is one-hot encoding (aka get dummies), the same thing we did to categorical variables in DATA 101/201 and in our pipelines. Every word becomes a row of 30 numbers, all 0 except for a 1 in that word’s spot. That works for a vocabulary with only 30 words, but with a real vocabulary of 50,000 words every word would be a row of 50,000 numbers that are almost all 0. This is very cumbersome and we are using up a lot of data to keep track of zeros!
An embedding is a better fix. It is a table with one row for each word in the vocabulary. Each row is a short list of numbers, here 8 of them, and those numbers are weights.
An embedding is a lookup table. Each word id picks out its own row of 8 numbers.
So where do those 8 numbers come from? They start out RANDOM, just like the weights in an nn.Linear layer or the filter numbers in a CNN. Then the network learns them with gradient descent:
A batch of reviews goes through the network and we compute the loss.
The backward pass finds a gradient for every weight, including the rows of the words that were in those reviews.
Adam nudges those rows a little bit so the loss goes down.
Words that help predict the same answer (like “great” and “loved”) get nudged in the same direction, over and over, so by the end of training their rows look alike. The numbers do not mean anything on their own, what matters is which words end up close together. We will see this at the end of today’s notes!
In PyTorch the table is called nn.Embedding.
# UNDERSTAND THESE STEPS. An embedding is a table you look rows up in.torch.manual_seed(42)embed = nn.Embedding( num_embeddings=vocab_size, # one row for every word in the vocabulary (vocab_size=30) embedding_dim=8) # every word becomes 8 numbers - this is small!review = torch.tensor([3, 10, 29]) # [3, 10, 29] = "loved the popcorn"vectors = embed(review)print("going in: ", review.shape)print("coming out:", vectors.shape)
# UNDERSTAND THESE STEPS. What is inside these objects?!?!print('The first word in the review = loved. Here is its vector:')print(vectors[0])print('----------------')print('The word loved is row four in the table, so all embedding does is look up the weights in the table! Here are the weights:')print(embed.weight[3])
The first word in the review = loved. Here is its vector:
tensor([ 1.2791, 1.2964, 0.6105, 1.3347, -0.2316, 0.0418, -0.2516, 0.8599],
grad_fn=<SelectBackward0>)
----------------
The word loved is row four in the table, so all embedding does is look up the weights in the table! Here are the weights:
tensor([ 1.2791, 1.2964, 0.6105, 1.3347, -0.2316, 0.0418, -0.2516, 0.8599],
grad_fn=<SelectBackward0>)
Notice that the two rows are exactly the same. nn.Embedding just looks up the row in the embedding corresponding to the word. The numbers start out random, and during training they change.
NoteQ1. Write this one out by hand
a. Why is it a bad idea to hand the network the word ids (0, 1, 2, …) as numbers?
b. How many numbers does nn.Embedding(30, 8) have to learn? How many would nn.Embedding(50000, 300) have to learn?
Reading in Order - The Recurrent Neural Network
Now that our words are numbers, how do we read a review in order? An MLP takes in one row of variables and a CNN takes in one picture a 2D matrix, all at once. An RNN reads a sequence one step at a time and combines the data. At every step it takes in two things:
The embedding of the next word.
The hidden state of the RNN, which is a list of numbers that acts as its memory of everything it has read so far.
Inside the RNN box there is nothing new, it is built from pieces you already know:
The word’s 8 embedding numbers go through a Linear layer that turns them into 32 numbers.
The memory (32 numbers) goes through a second Linear layer that turns it into 32 new numbers.
We add the two results together.
We send the sum through an activation function, \tanh, which squashes every number to be between -1 and 1.
What comes out is the new memory, and it gets handed to the next step along with the next word.
Inside one step of the RNN. Two Linear layers, add them up, then an activation function.
Unrolling the RNN
Here is the part that can be confusing. There is only ONE RNN box, with one set of weights. We use it over and over, once for each word, and the memory loops back into the same box each time. When we draw that loop as a row of boxes, one per word, we call it unrolling the RNN. The boxes in the unrolled picture are not different layers, they are the SAME box with the SAME weights, drawn once for every word so we can see the order.
An RNN reading “loved the popcorn”, unrolled. The red arrows carry the memory from word to word.
NOTE: This is different from a CNN or an MLP, where every layer has its own weights. An RNN reading a 100 word review uses the same box, same weights, 100 times and adds them together.
When the RNN gets to the end of the review, the last memory is a summary of the whole review. Then one more nn.Linear layer turns it into 2 scores, negative and positive.
Here is the same step written as math. With x_t the embedding of word t and h_{t-1} the memory coming in:
h_t = \tanh(W_x x_t + W_h h_{t-1} + b)
This is just a linear layer and an activation function, like Day 10, with the memory fed back in. The same weights W_x, W_h and b are used at every step, the same way a CNN uses the same filter at every spot in a picture. This means one RNN can read a review of any length!
Here is what \tanh looks like. No matter how big or small the number that goes in, what comes out is between -1 and 1. That keeps the memory from blowing up as it gets fed back in, word after word.
The tanh function.
# UNDERSTAND THESE STEPS. nn.RNN outputstorch.manual_seed(42)rnn = nn.RNN(input_size=8, hidden_size=32, batch_first=True) # 8 numbers in for each word, a memory of 32 numbersone_review = vectors.reshape(1, 3, 8) # SEND IN (1 review, 3 words, 8 numbers in the embedding)all_hidden, last_hidden = rnn(one_review) # Send the review through the RNN --> TWO THINGS pop out.print("all_hidden: ", all_hidden.shape) # the memory after every wordprint("last_hidden:", last_hidden.shape) # the memory after the last wordprint(last_hidden)
The last memory from nn.RNN is what will be sent forward to the Linear layer next. BEWARE: nn.RNN gives back TWO things, the memory after every word and the memory after the last word. Today we only use the last one. (We will use all_hidden later in class! Know the difference.)
NoteQ2. Write this one out by hand
a. In your own words, what is the hidden state after the RNN has read the third word of a review?
b. The RNN uses the same weights for every word. What did a CNN use at every spot in the picture? Why is this a good idea for both?
An RNN Review Classifier - Our First nn.Module
Up to now every network fit inside nn.Sequential, where each layer hands one thing to the next. But nn.RNN hands back two things, so it does not fit into this framework. So today we are going to learn how to write a neural network as a class. Many people do this for CNNs too! A Python class has two parts:
__init__ makes/edfines the layers. It runs once, when we initalize/instantiate the network.
forward is a function/method says what happens to a batch of reviews going forward through the network, in order. PyTorch calls .forward() for us when we write model(X_batch) to send things through the network.
NOTE: You will see this pattern for every network from here on, including the transformer at the end of the semester, so it is worth getting comfortable with it now!
# LEARN TO WRITE THIS. A network for reviews: embedding, then RNN, then a Linear layer.class ReviewNet(nn.Module):def__init__(self): ## NOTICE the double __ around init!!!super().__init__() # always the first line, it sets up nn.Module first when we call it laterself.embed = nn.Embedding(vocab_size, 8) # every word becomes 8 numbersself.memory = nn.RNN(8, 32, batch_first=True) # 8 numbers in, a memory of 32 numbersself.out = nn.Linear(32, 2) # go from 32 to 2 scores: negative, positivedef forward(self, X):# GOING FORWARD THROUGH THE NETWORK vectors =self.embed(X) # X = (reviews, words) -> vector = (reviews, words, 8) all_hidden, last_hidden =self.memory(vectors) # read every review word by word - notice the two outputs! scores =self.out(last_hidden[0]) # last_hidden has a size of (1, reviews, 32), [0] makes it just contain (reviews, 32)return scorestorch.manual_seed(42)model = ReviewNet()print(model)
Now we can train it! The training loop is the one from Day 14, put inside a function. It still uses nn.CrossEntropyLoss() and .argmax(dim=1), now with 2 classes instead of 10. The one change is a bigger learning rate, lr=0.01. LOOK THROUGH THE CODE BELOW – THIS SHOULD BE FAMILIAR!
# RUN THIS. The mini-batch training loop from Day 14. It returns the validation accuracy after every epoch.def train_model(model, X_train, y_train, X_valid, y_valid, n_epochs): torch.manual_seed(42) train_loader = DataLoader(TensorDataset(X_train, y_train), batch_size=32, shuffle=True) loss_fn = nn.CrossEntropyLoss() optimizer = torch.optim.Adam(model.parameters(), lr=0.01) valid_accuracy = []for epoch inrange(n_epochs): model.train()for X_batch, y_batch in train_loader: optimizer.zero_grad() scores = model(X_batch) loss = loss_fn(scores, y_batch) loss.backward() optimizer.step() model.eval()with torch.no_grad(): y_pred = model(X_valid).argmax(dim=1) accuracy = (y_pred == y_valid).float().mean().item() valid_accuracy.append(accuracy)print("epoch", epoch +1, " valid accuracy:", round(accuracy, 4))return valid_accuracy
# LEARN TO WRITE THIS. Train the RNN on the short reviews.torch.manual_seed(42)rnn_model = ReviewNet()accuracy_short = train_model(rnn_model, X_train, y_train, X_valid, y_valid, n_epochs=5)
The RNN gets 1.0 of the validation reviews right, every single one, starting in the first epoch. In a 10 word review the feeling word is never more than 9 words from the end, so the RNN does not have to remember very far back.
Try It on Your Own Review
Now that the RNN is trained, let’s use it! We can write our own 10 word review, turn the words into ids, and ask the network what it thinks. We use torch.softmax to turn the 2 scores into probabilities, just like the cross entropy example on Day 14.
# If you need to remember what words we have#vocab
# UNDERSTAND THESE STEPS. Use the trained RNN on reviews we write ourselves.def predict_review(model, sentence): word_ids = [vocab.index(word) for word in sentence.split()] # each word -> its id X = torch.tensor([word_ids]) # shape (1 review, words) model.eval() # prediction modewith torch.no_grad(): scores = model(X) # 2 scores: negative, positive probs = torch.softmax(scores, dim=1)[0] # turn the scores into probabilitiesprint(sentence)print(" probability negative:", round(probs[0].item(), 3), " probability positive:", round(probs[1].item(), 3))predict_review(rnn_model, "the movie was long and i loved the popcorn ending")predict_review(rnn_model, "the story was boring and i saw it on friday")predict_review(rnn_model, "loved the popcorn boring movie")
the movie was long and i loved the popcorn ending
probability negative: 0.0 probability positive: 1.0
the story was boring and i saw it on friday
probability negative: 1.0 probability positive: 0.0
loved the popcorn boring movie
probability negative: 0.999 probability positive: 0.001
Notice that the feeling word can be at the start, in the middle or at the end. The RNN reads the whole review one word at a time, and its memory still has the feeling word in it when it gets to the end.
NOTE: Our network only knows the 30 words in vocab. If you try a word that is not in the list, vocab.index(word) gives an error. A real model has a much bigger vocabulary, plus a special id for unknown words.
Long Reviews - Where the RNN Fails
What happens if the reviews are longer? Let’s try reviews that are 100 words long. There is still exactly one feeling word, somewhere in the review. Nothing else changes.
# RUN THIS. 100 word reviews.X_train_long, y_train_long = make_reviews(4000, n_words=100, seed=0)X_valid_long, y_valid_long = make_reviews(1000, n_words=100, seed=1)print("X_train_long:", X_train_long.shape)
X_train_long: torch.Size([4000, 100])
# LEARN TO WRITE THIS. The same RNN on the long reviews.torch.manual_seed(42)rnn_model_long = ReviewNet()accuracy_long = train_model(rnn_model_long, X_train_long, y_train_long, X_valid_long, y_valid_long, n_epochs=5)
The accuracy stays near 0.5. It is the same network, the same training and the same kind of review. The only thing we changed is the length, and the RNN did no better than guessing! Any guesses as to why the network is not learning? What were some reasons our network didnt learn in our other classes?
NoteQ3. Write this one out by hand
a. Half of the reviews are positive. What accuracy would you get by flipping a coin? Compare that to the RNN on the long reviews.
b. Why did we make up our own reviews today, instead of using real ones? What does it let us find out?
Why - The Gradient Vanishes Through Time
So what went wrong? Remember Day 11? In a deep network the gradient gets multiplied by a number at every layer on the way back. If those numbers are less than 1 the gradient shrinks layer after layer, and the first layers barely learn. That was the vanishing gradient problem.
An RNN reading 100 words is like a network that is 100 layers deep, one layer per word and all layers with the same weights. To learn something about word 1, the gradient has to travel back through all 100 steps and not vanish.
We can measure this! The cell below sends a batch of long reviews through a brand new RNN, does the backward pass, and looks at the size of the gradient for each word’s embedding.
# DEMO ONLY. How big is the gradient for each word in a 100 word review?torch.manual_seed(42)new_model = ReviewNet() # Just so we have an untrained model to start withvectors = new_model.embed(X_train_long[:500]) # the embeddings of 500 long reviewsvectors.retain_grad() # ask PyTorch to keep the gradient for theseall_hidden, last_hidden = new_model.memory(vectors)scores = new_model.out(last_hidden[0])loss = nn.CrossEntropyLoss()(scores, y_train_long[:500])loss.backward()# one number per word: the average size of its gradientgradient_size = vectors.grad.norm(dim=2).mean(dim=0)print("last word: ", gradient_size[99].item())print("word 90: ", gradient_size[89].item())print("word 50: ", gradient_size[49].item())print("first word: ", gradient_size[0].item())
last word: 0.0001374386192765087
word 90: 2.3904539148134063e-07
word 50: 1.499050124165344e-17
first word: 0.0
# DEMO ONLY. The same numbers as a picture, on a log scale.g = gradient_size.detach().numpy()zero_words = (g ==0).sum() # how many of the first words got a gradient of exactly 0plt.figure(figsize=(8, 4))plt.semilogy(range(1, 101), np.maximum(g, 1e-30)) # a log scale can not show 0, so we draw those at 1e-30plt.axvspan(0.5, zero_words +0.5, color="red", alpha=0.12)plt.text(zero_words /2, 1e-27, f"words 1 to {zero_words}:\ngradient rounded\nto exactly 0", ha="center", fontsize=9, color="darkred")plt.ylim(1e-31, 1e-2)plt.xlabel("word location in the review")plt.ylabel("size of the gradient (log scale)")plt.title("Gradients in a new RNN on 100 word reviews")plt.grid()plt.show()
The last word gets a gradient of about 0.00014. Ten words back (word 90) it is about 0.00000024, roughly 600 times smaller. For the first 25 words it is so small that the computer rounds it to exactly 0.
This means the RNN only learns from the last few words of the review. If the feeling word is far from the end, closer to the beginning, its gradient is close to 0, and the weights barely change because of it.
NoteQ4. Write this one out by hand
a. Suppose every step back multiplies the gradient by 0.5. How much smaller is the gradient after 10 steps back? After 50? (Use a calculator for 50.)
b. Use your answer to explain why the RNN does fine on 10 word reviews and fails on 100 word reviews.
The Fix - A GRU, an RNN With a Gate
NOTE: Be patient going through this idea. We are layering more complexity over an brand new topic so give yourself time to absorb these ideas!
So how do we fix it? The RNN mixes EVERY word into its memory, even the filler words like “the” and “popcorn”. By the time it gets to the end of a long review, the feeling word has been mixed away. What if we let the network decide, for every word, how much of its memory to keep? Let’s let the network decide which words are important!
That is what a GRU (gated recurrent unit) does. It adds a gate, represented by z_t. The gate is a list of numbers between 0 and 1, one for every neuron/number in the memory. At every word the GRU does this:
It makes a new candidate memory \tilde{h}_t, the same way the RNN did (two Linear layers, add, apply tanh).
It computes the gate z_t from the word and the old memory, using its own weights.
It mixes the old memory and the new candidate, using the gate:
NOTE: The \cdot here is NOT a dot product. It means multiply spot by spot: the first number in z_t times the first number in the memory, the second times the second, and so on. So the GRU can keep one part of its memory and rewrite another part at the same time.
z_t is like a little logistic regression that looks at the incoming information (8 –linear–> 32 numbers here) and the memory the GRU has so far (32 numbers here). For each of the 32 spots in the memory it outputs a value between 0 and 1 telling the network whether to keep the memory and ignore the new incoming information, or throw away the memory and use the new incoming information, or something in between, a mix.
Let’s look at the two extremes:
If z_t is close to 1, the GRU keeps the OLD memory and mostly ignores the new word. This is how it can skip over filler words like “the”.
If z_t is close to 0, the GRU throws out the old memory and uses the new candidate.
The network learns its gate weights with gradient descent, just like everything else, so it learns WHEN to keep its memory and when to change it. And here is the part that fixes our problem: when the GRU keeps its memory, the gradient on the way back gets multiplied by about 1 at that step, not by something small. So the gradient does not vanish, and the early words can still be learned from!
Why Does the GRU Have a Second Gate?
The update gate z_t decides how much of the new candidate goes into the memory. But the candidate itself is built from the word AND the old memory, just like the RNN step. Sometimes the old memory is not helpful for understanding the new word, for example when a new sentence starts or the topic changes. So the GRU has a second little logistic regression, the reset gater_t, that decides how much of the old memory to use when it MAKES the candidate:
If r_t is close to 1, the candidate is built from the word and the old memory, exactly like the RNN step.
If r_t is close to 0, the old memory is mostly ignored, and the candidate is built from the new word alone. The GRU “starts fresh.”
So the two gates answer two different questions:
Gate
The question it answers
reset gate r_t
When I make the new candidate, how much should I look at the old memory?
update gate z_t
How much of that new candidate should replace my memory?
In our made up reviews the reset gate does not matter much, the job is just to find the one feeling word. That is why we focused on the update gate. But it is part of every GRU, and it is one reason the GRU has more numbers to learn than the RNN: the candidate, the update gate and the reset gate each have their own weights.
Here is a picture of what happens inside one GRU step. It uses the same colors as the RNN pictures above: the word is blue, the memory is red, the update gate is green, the reset gate is purple, and the candidate and the mix are orange.
Inside one GRU step. The word and the memory go into all three parts. The old memory also goes straight to the mix.
Notice the red line along the bottom. The old memory goes STRAIGHT to the mix. When the update gate z_t is close to 1, the memory passes through almost unchanged, and so does the gradient on the way back.
NOTE: The reading also covers the LSTM (long short-term memory). It is an older version of the same idea, with three gates and a second memory. The GRU is simpler and usually works just as well.
In PyTorch the GRU is nn.GRU, and we use it exactly like nn.RNN. So we make a copy of our class and change ONE line: nn.RNN becomes nn.GRU.
# LEARN TO WRITE THIS. The same class with nn.GRU instead of nn.RNN, trained on the long reviews.class ReviewGRU(nn.Module):def__init__(self):super().__init__()self.embed = nn.Embedding(vocab_size, 8) # every word becomes 8 numbersself.memory = nn.GRU(8, 32, batch_first=True) # THE ONE CHANGE: a GRU instead of an RNNself.out = nn.Linear(32, 2) # 2 scores: negative, positivedef forward(self, X): vectors =self.embed(X) all_hidden, last_hidden =self.memory(vectors) # a GRU also gives back TWO things scores =self.out(last_hidden[0])return scorestorch.manual_seed(42)gru_model_long = ReviewGRU()accuracy_gru = train_model(gru_model_long, X_train_long, y_train_long, X_valid_long, y_valid_long, n_epochs=5)
# RUN THIS. The three learning curves.epochs =range(1, 6)plt.figure(figsize=(6, 4))plt.plot(epochs, accuracy_short, marker="o", label="RNN, 10 word reviews")plt.plot(epochs, accuracy_long, marker="o", label="RNN, 100 word reviews")plt.plot(epochs, accuracy_gru, marker="o", label="GRU, 100 word reviews")plt.xlabel("epoch")plt.xticks(epochs) # only whole epochs on the x axisplt.ylabel("validation accuracy")plt.ylim(0.4, 1.05)plt.legend()plt.grid()plt.show()
# RUN THIS. How many numbers does each network have to learn?n_rnn =0for p in rnn_model_long.parameters(): n_rnn = n_rnn + p.numel()n_gru =0for p in gru_model_long.parameters(): n_gru = n_gru + p.numel()print("RNN:", n_rnn)print("GRU:", n_gru)
RNN: 1650
GRU: 4338
Look at that! The GRU sits at 0.508 for two epochs, then jumps to 1.0 in epoch 3 and stays there. These are the same long reviews where the RNN ended at 0.493. The GRU does have more numbers to learn, 4,338 compared to 1,650 for the RNN. The extra numbers are the weights for the gate, and they make the memory layer exactly three times as big.
So why do we need anything else?
The GRU solved our made up problem, so why is the rest of the semester about attention and transformers? There are two problems you can already see from today:
Everything has to fit in 32 numbers. By the end of the review, the whole review has to fit in one memory. That is fine for “was there a positive word?”, but a real paragraph has names, places, who did what to whom… and the network has to keep ALL of it in that one list of numbers.
It reads one word at a time. Step 50 can not start until step 49 is done, so RNNs are slow to train on long text, even on a big GPU.
Attention helps with both of these issues. Instead of only keeping a memory, the network gets to look back at every word directly. We will see how on Day 16!
NoteQ5. Write this one out by hand
a. What does the gate in a GRU let it do that a plain RNN can not? Use the words “keep” and “memory”.
b. At the end of a 100 word review the GRU has to summarize everything in its last hidden state. Why could that be a problem for a long, real paragraph?
A Look Back at the Embedding
Remember the embedding table from the start of today? Now that the GRU is trained, let’s see what it learned. Each word is 8 numbers, which is too many to plot, so we squeeze the 8 numbers down to 2 with PCA (from DATA 201) and plot every word as a point. On the left is a brand new network, on the right is our trained GRU.
# DEMO ONLY. Every word's 8 embedding numbers squeezed down to 2 with PCA, before and after training.from sklearn.decomposition import PCAfig, axes = plt.subplots(1, 2, figsize=(11, 4.5))for ax, net, title in [(axes[0], new_model, "a brand new network (random)"), (axes[1], gru_model_long, "after training the GRU")]: table = net.embed.weight.detach().numpy() # the table: 30 words, 8 numbers each points = PCA(n_components=2).fit_transform(table) # 8 numbers -> 2 numbers for each wordfor word_id, word inenumerate(vocab):if word_id <5: color ="green"# positive feeling wordselif word_id <10: color ="red"# negative feeling wordselse: color ="gray"# filler words ax.scatter(points[word_id, 0], points[word_id, 1], color=color) ax.annotate(word, (points[word_id, 0], points[word_id, 1]), fontsize=8) ax.set_title(title)plt.show()
On the left the words are scattered randomly, the network has not learned anything yet. On the right the green positive words moved off to one side, most of the red negative words moved off to the other side, and the gray filler words are bunched together. (One negative word, “hated”, is still sitting with the filler words. It did not get pushed as far, can you think of why that might happen?) Nobody told the network which words were positive! It figured out that “great” and “loved” do the same job because they both push the review toward the positive answer.
This is what an embedding learns: words that do the same job end up close together. In a big language model the table has tens of thousands of words and hundreds of numbers per word, but it is the SAME idea.
Putting It Together
What this looks like in real life - The Whole Process in One Cell
Here is everything in one cell, with no helper function. The comments show the places you could change things.
# LEARN TO WRITE THIS.# A GRU review classifier from start to finish.# It uses vocab_size, X_train_long, y_train_long, X_valid_long, y_valid_long from above.# 1. The model. Here you could change the embedding size (8), the memory size (32),# or swap nn.GRU for nn.RNNclass ReviewGRU(nn.Module):def__init__(self):super().__init__()self.embed = nn.Embedding(vocab_size, 8)self.memory = nn.GRU(8, 32, batch_first=True)self.out = nn.Linear(32, 2)def forward(self, X): vectors =self.embed(X) all_hidden, last_hidden =self.memory(vectors) scores =self.out(last_hidden[0])return scorestorch.manual_seed(42)model = ReviewGRU()# 2. The batches, the loss and the optimizer. Here you could change the batch size or the learning ratetrain_loader = DataLoader(TensorDataset(X_train_long, y_train_long), batch_size=32, shuffle=True)loss_fn = nn.CrossEntropyLoss()optimizer = torch.optim.Adam(model.parameters(), lr=0.01)# 3. The training loopn_epochs =5for epoch inrange(n_epochs): model.train() # training modefor X_batch, y_batch in train_loader: optimizer.zero_grad() # clear the old gradients scores = model(X_batch) # forward pass: 2 scores per review loss = loss_fn(scores, y_batch) # how far off are we? loss.backward() # backward pass, back through every word optimizer.step() # one step of Adam# 4. After every epoch, check the validation accuracy model.eval() # prediction modewith torch.no_grad(): y_pred = model(X_valid_long).argmax(dim=1) accuracy = (y_pred == y_valid_long).float().mean().item()print("epoch", epoch +1, " valid accuracy:", round(accuracy, 4))
Words become ids, and ids become vectors with an embedding, a table of learned numbers with one row per word.
An RNN reads a sequence one step at a time and carries a hidden state, its memory. It uses the same weights at every step.
When a network does not fit in nn.Sequential, we write it as a class with an __init__ method and a forward method.
On long sequences the gradient for the early words vanishes, so a plain RNN only learns from the last few words.
A GRU (or an LSTM) has a gate that lets it keep its memory, so the gradient can reach early words.
Even a GRU has to fit the whole sequence into one memory, and it still reads one word at a time. Next class we will see how attention helps with both!
New Commands Today
Command
What it does
The thing that trips people up
nn.Embedding(vocab_size, 8)
a table with one row of 8 learned numbers per word
it takes word ids (whole numbers), not one-hot rows
nn.RNN(8, 32, batch_first=True)
reads a sequence one step at a time, memory of 32 numbers
without batch_first=True it expects (words, reviews, numbers)
all_hidden, last_hidden = rnn(vectors)
the memory after every word, and after the last word
it gives back TWO things, and last_hidden has an extra 1 in front, so use last_hidden[0]
nn.GRU(8, 32, batch_first=True)
an RNN with a gate on its memory
used exactly like nn.RNN
class Net(nn.Module): with __init__ and forward
a network that does not fit in nn.Sequential
super().__init__() has to be the first line of __init__
tensor.retain_grad()
keeps the gradient of an in between result
only for looking, you do not need it to train
TipYou Try: optional code
Nothing here is collected. Work through it if you want the idea to stick.
1. Find where the RNN breaks. Train ReviewNet() on reviews with 20, 40 and 60 words. Where does the accuracy drop?
2. In the real life cell, change the memory size from 32 to 4 (two places). Does the GRU still learn the 100 word reviews?
3. Try an LSTM. Use nn.LSTM(8, 32, batch_first=True). It gives back the memory after every word and a pair (last_hidden, last_cell), so the forward line becomes all_hidden, (last_hidden, last_cell) = self.memory(vectors).
Before Next Class
In your lecture notes notebook, add your handwritten notes and answers to the questions.
Do the Day 15 practice problems in HW_day15.ipynb. They are practice, not graded, and the solutions are in the same folder.
Weekly Homework 7 is due Wednesday 11/11 at 11:59pm.
Exam 2 is released after class today. It is due Monday 11/9 at 11:59pm.
Final project: your team is due Tuesday 11/10 at 11:59pm, and the proposal is due Tuesday 11/17 at 11:59pm.
Next class is Day 16 on Tuesday 11/10: attention from scratch!
Answers to the Q Boxes
Try every one of these by hand first. These are short summaries, not full answers, and the writing out is the part that does the work.
NoteQ1. Embeddings
a. The ids are only names, and we made up their order. The network would treat “popcorn” (29) as 29 times “good” (1), and that does not make any sense.
b.30 \times 8 = 240. For a real vocabulary, 50{,}000 \times 300 = 15{,}000{,}000.
NoteQ2. The RNN
a. A list of numbers (32 in our model) that summarizes the first three words. It was made from the third word and the memory of the first two.
b. A CNN uses the same filter at every spot in the picture. Reusing weights means far fewer numbers to learn, and the network can handle a feature (or a word) wherever it shows up. For an RNN it also means one network can read a review of any length.
NoteQ3. Short and long reviews
a. About 0.5. The RNN on the long reviews got between 0.476 and 0.521, so it did no better than flipping a coin.
b. With made up data we know exactly where the important word is, and we know 100% is possible. So if the RNN fails, we know the problem is the network and not the data. We can also change the length of the reviews and keep everything else the same.
NoteQ4. Vanishing gradients
a.0.5^{10} \approx 0.001, about 1,000 times smaller. 0.5^{50} \approx 0.000000000000001 (8.9 \times 10^{-16}).
b. In a 10 word review the feeling word is at most 9 steps from the end, so its gradient is still big enough to learn from. In a 100 word review it is usually many more steps back, and the gradient that reaches it is close to 0, so the weights barely change because of it.
NoteQ5. The GRU
a. The gate lets the GRU keep its memory unchanged when a word does not matter, instead of mixing every word into the memory. Because the memory can pass through a step unchanged, the gradient can also pass back through it without shrinking.
b. A real paragraph has lots of things to remember, and ALL of them have to fit in one list of 32 (or a few hundred) numbers. New words can overwrite what was there before. Attention lets the network look back at every word instead.