{
"cells": [
{
"cell_type": "markdown",
"metadata": {},
"source": [
"# Recurrent Neural Networks\n",
"\n",
"Last time, before the midterm, we discussed using recurrent neural networks\n",
"to make predictions about sequences. In particular, we treated tweets\n",
"as a **sequence** of words. Since tweets can have a variable number of words,\n",
"we needed an architecture that can take variable-sized sequences as input.\n",
"\n",
"This time, we will use recurrent neural networks to **generate** sequences.\n",
"Generating sequences is more involved comparing to making predictions about\n",
"sequences. However, it is a very interesting task, and many students chose\n",
"sequence-generation tasks for their projects.\n",
"\n",
"Much of today's content is an adaptation of the \"Practical PyTorch\" github \n",
"repository [1].\n",
"\n",
"[1] https://github.com/spro/practical-pytorch/blob/master/char-rnn-generation/char-rnn-generation.ipynb"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"import torch\n",
"import torch.nn as nn\n",
"import torch.nn.functional as F\n",
"import torch.optim as optim"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"## Review\n",
"\n",
"The recurrent neural network architecture from last time \n",
"looked something like this:\n",
"\n",
"\n",
"\n",
"The input sequence is broken down into tokens. We could choose whether to\n",
"tokenize based on words, or based on characters. The representation\n",
"of each token (GloVe or one-hot) is processed by the RNN one step at a time\n",
"to update the hidden (or context) state.\n",
"\n",
"In a predictive RNN, the value of the\n",
"hidden states is a representation of **all the text that was processed thus far**.\n",
"Similarly, in a generative RNN, The value of the hidden\n",
"state will be a representation of **all the text that still needs to be generated**.\n",
"We will use this hidden state to produce the sequence, one token at a time.\n",
"\n",
"Similar to last class we will break up the problem of generating text\n",
"to generating one token at a time.\n",
"\n",
"We will do so with the help of two functions:\n",
"\n",
"1. We need to be able to generate the *next* token, given the current \n",
" hidden state. In practice, we get a probability distribution over \n",
" the next token, and sample from that probability distribution.\n",
"2. We need to be able to update the hidden state somehow. To do so,\n",
" we need two piece of information: the old hidden state, and the actual\n",
" token that was generated in the previous step. The actual token generated\n",
" will inform the subsequent tokens.\n",
"\n",
"We will repeat both functions until a special \"END OF SEQUENCE\" token is\n",
"generated. Here is a pictorial representation of what we will do:\n",
"\n",
"\n",
"\n",
"\n",
"Note that there are several tricky things that we will have to figure out.\n",
"For example, how do we actually sample the actual token from the probability\n",
"distribution over tokens? What would we do during training, and how might \n",
"that be different from during testing/evaluation? We will answer those\n",
"questions as we implement the RNN.\n",
"\n",
"For now, let's start with our training data.\n",
"\n",
"## Data: Donald Trump's Tweets from 2018\n",
"\n",
"The training set we use is a collection of Donald Trump's tweets from 2018.\n",
"We will only use tweets that are 140 characters or shorter, and tweets\n",
"that contains more than just a URL.\n",
"Since tweets often contain creative spelling and numbers, and upper vs lower\n",
"case characters are read very differently, we will use a character-level RNN."
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"import csv\n",
"tweets = list(line[0] for line in csv.reader(open('trump.csv')))\n",
"len(tweets)"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"There are over 20000 tweets in this collection.\n",
"Let's look at a few of them, just to get a sense of the kind of text\n",
"we're dealing with:"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"print(tweets[100])\n",
"print(tweets[1000])\n",
"print(tweets[10000])"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"## Generating One Tweet\n",
"\n",
"Normally, when we build a new machine learn model, we want to make sure\n",
"that our model can overfit. To that end, we will first build a neural network\n",
"that can generate _one_ tweet really well. We can choose any tweet (or any other text)\n",
"we want. Let's choose to build an RNN that generates `tweet[100]`."
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"tweet = tweets[100]\n",
"tweet"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"First, we will need to encode this tweet using a one-hot encoding.\n",
"We'll build dictionary mappings\n",
"from the character to the index of that character (a unique integer identifier),\n",
"and from the index to the character. We'll use the same naming scheme that `torchtext`\n",
"uses (`stoi` and `itos`).\n",
"\n",
"For simplicity, we'll work with a limited vocabulary containing\n",
"just the characters in `tweet[100]`, plus two special tokens:\n",
"\n",
"- `` represents \"End of String\", which we'll append to the end of our tweet.\n",
" Since tweets are variable-length, this is a way for the RNN to signal\n",
" that the entire sequence has been generated.\n",
"- `` represents \"Beginning of String\", which we'll prepend to the beginning of \n",
" our tweet. This is the first token that we will feed into the RNN.\n",
"\n",
"The way we use these special tokens will become more clear as we build the model."
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"vocab = list(set(tweet)) + [\"\", \"\"]\n",
"vocab_stoi = {s: i for i, s in enumerate(vocab)}\n",
"vocab_itos = {i: s for i, s in enumerate(vocab)}\n",
"vocab_size = len(vocab)"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"Now that we have our vocabulary, we can build the PyTorch model\n",
"for this problem.\n",
"The actual model is not as complex as you might think. We actually\n",
"already learned about all the components that we need. (Using and training\n",
"the model is the hard part)"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"class TextGenerator(nn.Module):\n",
" def __init__(self, vocab_size, hidden_size, n_layers=1):\n",
" super(TextGenerator, self).__init__()\n",
"\n",
" # identiy matrix for generating one-hot vectors\n",
" self.ident = torch.eye(vocab_size)\n",
"\n",
" # recurrent neural network\n",
" self.rnn = nn.GRU(vocab_size, hidden_size, n_layers, batch_first=True)\n",
"\n",
" # a fully-connect layer that outputs a distribution over\n",
" # the next token, given the RNN output\n",
" self.decoder = nn.Linear(hidden_size, vocab_size)\n",
" \n",
" def forward(self, inp, hidden=None):\n",
" inp = self.ident[inp] # generate one-hot vectors of input\n",
" output, hidden = self.rnn(inp, hidden) # get the next output and hidden state\n",
" output = self.decoder(output) # predict distribution over next tokens\n",
" return output, hidden\n",
"\n",
"model = TextGenerator(vocab_size, 64)"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"## Training with Teacher Forcing\n",
"\n",
"At a very high level, we want our RNN model to have a high probability\n",
"of generating the tweet. An RNN model generates text\n",
"one character at a time based on the hidden state value.\n",
"At each time step, we will check whether the mdoel generated the\n",
"correct character. That is, at each time step,\n",
"we are trying to select the correct next character out of all the \n",
"characters in our vocabulary. Recall that this problem is a multi-class\n",
"classification problem, and we can use Cross-Entropy loss to train our\n",
"network to become better at this type of problem."
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"criterion = nn.CrossEntropyLoss()"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"However, we don't just have a single multi-class classification problem.\n",
"Instead, we have **one classification problem per time-step** (per token)!\n",
"So, how do we predict the first token in the sequence? \n",
"How do we predict the second token in the sequence? \n",
"\n",
"To help you understand what happens durign RNN training, we'll start with a\n",
"inefficient training code that shows you what happens step-by-step. We'll\n",
"start with computing the loss for the first token generated, then the second token,\n",
"and so on.\n",
"Later on, we'll switch to a simpler and more performant version of the code.\n",
"\n",
"So, let's start with the first classification problem: the problem of generating\n",
"the **first** token (`tweet[0]`).\n",
"\n",
"\n",
"\n",
"To generate the first token, we'll feed the RNN network (with an initial, empty\n",
"hidden state) the \"\" token. Then, the output"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"bos_input = torch.Tensor([vocab_stoi[\"\"]]).long().unsqueeze(0)\n",
"output, hidden = model(bos_input, hidden=None)\n",
"output # distribution over the first token"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"We can compute the loss using `criterion`. Since the model is untrained,\n",
"the loss is expected to be high. (For now, we won't do anything\n",
"with this loss, and omit the backward pass.)"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"target = torch.Tensor([vocab_stoi[tweet[0]]]).long().unsqueeze(0)\n",
"criterion(output.reshape(-1, vocab_size), # reshape to 2D tensor\n",
" target.reshape(-1)) # reshape to 1D tensor"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"Now, we need to update the hidden state and generate a prediction\n",
"for the next token. To do so, we need to provide the current token to\n",
"the RNN. We already said that during test time, we'll need to sample\n",
"from the predicted probabilty over tokens that the neural network\n",
"just generated. \n",
"\n",
"Right now, we can do something better: we can **use the ground-truth,\n",
"actual target token**. This technique is called **teacher-forcing**, \n",
"and generally speeds up training. The reason is that right now, \n",
"since our model does not perform well, the predicted probability\n",
"distribution is pretty far from the ground truth. So, it is very,\n",
"very difficult for the neural network to get back on track given bad\n",
"input data."
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"# Use teacher-forcing: we pass in the ground truth `target`,\n",
"# rather than using the NN predicted distribution\n",
"output, hidden = model(target, hidden)\n",
"output # distribution over the second token"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"Similar to the first step, we can compute the loss, quantifying the\n",
"difference between the predicted distribution and the actual next\n",
"token. This loss can be used to adjust the weights of the neural\n",
"network (which we are not doing yet)."
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"target = torch.Tensor([vocab_stoi[tweet[1]]]).long().unsqueeze(0)\n",
"criterion(output.reshape(-1, vocab_size), # reshape to 2D tensor\n",
" target.reshape(-1)) # reshape to 1D tensor"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"We can continue this process of:\n",
"\n",
"- feeding the previous ground-truth token to the RNN,\n",
"- obtaining the prediction distribution over the next token, and\n",
"- computing the loss,\n",
"\n",
"for as many steps as there are tokens in the ground-truth tweet."
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"for i in range(2, len(tweet)):\n",
" output, hidden = model(target, hidden)\n",
" target = torch.Tensor([vocab_stoi[tweet[1]]]).long().unsqueeze(0)\n",
" loss = criterion(output.reshape(-1, vocab_size), # reshape to 2D tensor\n",
" target.reshape(-1)) # reshape to 1D tensor\n",
" print(i, output, loss)"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"Finally, with our final token, we should expect to output the \"\"\n",
"token, so that our RNN learns when to stop generating characters."
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"output, hidden = model(target, hidden)\n",
"target = torch.Tensor([vocab_stoi[\"\"]]).long().unsqueeze(0)\n",
"loss = criterion(output.reshape(-1, vocab_size), # reshape to 2D tensor\n",
" target.reshape(-1)) # reshape to 1D tensor\n",
"print(i, output, loss)"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"In practice, we don't really need a loop. Recall that in a predictive RNN,\n",
"the `nn.RNN` module can take an entire sequence as input. We can do the\n",
"same thing here:"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"tweet_ch = [\"\"] + list(tweet) + [\"\"]\n",
"tweet_indices = [vocab_stoi[ch] for ch in tweet_ch]\n",
"tweet_tensor = torch.Tensor(tweet_indices).long().unsqueeze(0)\n",
"\n",
"print(tweet_tensor.shape)\n",
"\n",
"output, hidden = model(tweet_tensor[:,:-1]) # is never an input token\n",
"target = tweet_tensor[:,1:] # is never a target token\n",
"loss = criterion(output.reshape(-1, vocab_size), # reshape to 2D tensor\n",
" target.reshape(-1)) # reshape to 1D tensor"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"Here, the input to our neural network model is the *entire*\n",
"sequence of input tokens (everything from \"\" to the\n",
"last character of the tweet). The neural network generates a prediction distribution\n",
"of the next token at each step. We can compare each of these with the ground-truth\n",
"`target`.\n",
"\n",
"\n",
"Our training loop (for learning to generate the single `tweet`) will therefore\n",
"look something like this:"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"optimizer = torch.optim.Adam(model.parameters(), lr=0.001)\n",
"criterion = nn.CrossEntropyLoss()\n",
"for it in range(500):\n",
" optimizer.zero_grad()\n",
" output, _ = model(tweet_tensor[:,:-1])\n",
" loss = criterion(output.reshape(-1, vocab_size),\n",
" target.reshape(-1))\n",
" loss.backward()\n",
" optimizer.step()\n",
"\n",
" if (it+1) % 100 == 0:\n",
" print(\"[Iter %d] Loss %f\" % (it+1, float(loss)))"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"The training loss is decreasing with training, which is what we expect.\n",
"\n",
"## Generating a Token\n",
"\n",
"At this point, we want to see whether our model is actually learning\n",
"something. So, we need to talk about how to\n",
"actually use the RNN model to generate text. If we can \n",
"generate text, we can make a qualitative asssessment of how well\n",
"our RNN is performing.\n",
"\n",
"The main difference between training and test-time (generation time)\n",
"is that we don't have the ground-truth tokens to feed as inputs\n",
"to the RNN. Instead, we need to actually **sample** a token based\n",
"on the neural network's prediction distribution.\n",
"\n",
"But how can we sample a token from a distribution?\n",
"\n",
"On one extreme, we can always take\n",
"the token with the largest probability (argmax). This has been our\n",
"go-to technique in other classification tasks. However, this idea\n",
"will fail here. The reason is that in practice, \n",
"**we want to be able to generate a variety of different sequences from\n",
"the same model**. An RNN that can only generate a single new Trump Tweet\n",
"is fairly useless.\n",
"\n",
"In short, we want some randomness. We can do so by using the logit\n",
"outputs from our model to construct a multinomial distribution over\n",
"the tokens, then and sample a random token from that multinomial distribution.\n",
"\n",
"One natural multinomial distribution we can choose is the \n",
"distribution we get after applying the softmax on the outputs.\n",
"However, we will do one more thing: we will add a **temperature**\n",
"parameter to manipulate the softmax outputs. We can set a\n",
"**higher temperature** to make the probability of each token\n",
"**more even** (more random), or a **lower temperature** to assighn\n",
"more probability to the tokens with a higher logit (output).\n",
"A **higher temperature** means that we will get a more diverse sample,\n",
"with potentially more mistakes. A **lower temperature** means that we\n",
"may see repetitions of the same high probability sequence."
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"def sample_sequence(model, max_len=100, temperature=0.8):\n",
" generated_sequence = \"\"\n",
" \n",
" inp = torch.Tensor([vocab_stoi[\"\"]]).long()\n",
" hidden = None\n",
" for p in range(max_len):\n",
" output, hidden = model(inp.unsqueeze(0), hidden)\n",
" # Sample from the network as a multinomial distribution\n",
" output_dist = output.data.view(-1).div(temperature).exp()\n",
" top_i = int(torch.multinomial(output_dist, 1)[0])\n",
" # Add predicted character to string and use as next input\n",
" predicted_char = vocab_itos[top_i]\n",
" \n",
" if predicted_char == \"\":\n",
" break\n",
" generated_sequence += predicted_char \n",
" inp = torch.Tensor([top_i]).long()\n",
" return generated_sequence\n",
"\n",
"print(sample_sequence(model, temperature=0.8))\n",
"print(sample_sequence(model, temperature=1.0))\n",
"print(sample_sequence(model, temperature=1.5))\n",
"print(sample_sequence(model, temperature=2.0))\n",
"print(sample_sequence(model, temperature=5.0))"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"Since we only trained the model on a single sequence, we won't see\n",
"the effect of the temperature parameter yet. \n",
"\n",
"For now, the output of the calls to the `sample_sequence` function\n",
"assures us that our training code looks reasonable, and we can\n",
"proceed to training on our full dataset!\n",
"\n",
"## Training the Trump Tweet Generator\n",
"\n",
"For the actual training, let's use `torchtext` so that we can use\n",
"the `BucketIterator` to make batches. Like in Lab 5, we'll create a \n",
"`torchtext.data.Field` to use `torchtext` to read the CSV file, and convert\n",
"characters into indices. The object has convient parameters to specify\n",
"the BOS and EOS tokens."
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"import torchtext\n",
"\n",
"text_field = torchtext.data.Field(sequential=True, # text sequence\n",
" tokenize=lambda x: x, # because are building a character-RNN\n",
" include_lengths=True, # to track the length of sequences, for batching\n",
" batch_first=True,\n",
" use_vocab=True, # to turn each character into an integer index\n",
" init_token=\"\", # BOS token\n",
" eos_token=\"\") # EOS token\n",
"\n",
"fields = [('text', text_field), ('created_at', None), ('id_str', None)]\n",
"trump_tweets = torchtext.data.TabularDataset(\"trump.csv\", \"csv\", fields)\n",
"len(trump_tweets) # should be >20,000 like before"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"text_field.build_vocab(trump_tweets)\n",
"vocab_stoi = text_field.vocab.stoi # so we don't have to rewrite sample_sequence\n",
"vocab_itos = text_field.vocab.itos # so we don't have to rewrite sample_sequence\n",
"vocab_size = len(text_field.vocab.itos)\n",
"vocab_size"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"Let's just verify that the `BucketIterator` works as expected, but start with batch_size of 1."
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"data_iter = torchtext.data.BucketIterator(trump_tweets, \n",
" batch_size=1,\n",
" sort_key=lambda x: len(x.text),\n",
" sort_within_batch=True)\n",
"for (tweet, lengths), label in data_iter:\n",
" print(label) # should be None\n",
" print(lengths) # contains the length of the tweet(s) in batch\n",
" print(tweet.shape) # should be [1, max(length)]\n",
" break"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"To account for batching, our actual training code will change, but just a little bit.\n",
"In fact, our training code from before will work with a batch size larger than one!"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"def train(model, data, batch_size=1, num_epochs=1, lr=0.001, print_every=100):\n",
" optimizer = torch.optim.Adam(model.parameters(), lr=lr)\n",
" criterion = nn.CrossEntropyLoss()\n",
" it = 0\n",
" \n",
" data_iter = torchtext.data.BucketIterator(data,\n",
" batch_size=batch_size,\n",
" sort_key=lambda x: len(x.text),\n",
" sort_within_batch=True)\n",
" for e in range(num_epochs):\n",
" # get training set\n",
" avg_loss = 0\n",
" for (tweet, lengths), label in data_iter:\n",
" target = tweet[:, 1:]\n",
" inp = tweet[:, :-1]\n",
" # cleanup\n",
" optimizer.zero_grad()\n",
" # forward pass\n",
" output, _ = model(inp)\n",
" loss = criterion(output.reshape(-1, vocab_size), target.reshape(-1))\n",
" # backward pass\n",
" loss.backward()\n",
" optimizer.step()\n",
"\n",
" avg_loss += loss\n",
" it += 1 # increment iteration count\n",
" if it % print_every == 0:\n",
" print(\"[Iter %d] Loss %f\" % (it+1, float(avg_loss/print_every)))\n",
" print(\" \" + sample_sequence(model, 140, 0.8))\n",
" avg_loss = 0\n",
"\n",
"model = TextGenerator(vocab_size, 64)\n",
"#train(model, trump_tweets, batch_size=1, num_epochs=1, lr=0.004, print_every=100)\n",
"#train(model, trump_tweets, batch_size=32, num_epochs=1, lr=0.004, print_every=100)\n",
"#print(sample_sequence(model, temperature=0.8))\n",
"#print(sample_sequence(model, temperature=0.8))\n",
"#print(sample_sequence(model, temperature=1.0))\n",
"#print(sample_sequence(model, temperature=1.0))\n",
"#print(sample_sequence(model, temperature=1.5))\n",
"#print(sample_sequence(model, temperature=1.5))\n",
"#print(sample_sequence(model, temperature=2.0))\n",
"#print(sample_sequence(model, temperature=2.0))\n",
"#print(sample_sequence(model, temperature=5.0))\n",
"#print(sample_sequence(model, temperature=5.0))"
]
}
],
"metadata": {},
"nbformat": 4,
"nbformat_minor": 2
}