Real-time collaboration for Jupyter Notebooks, Linux Terminals, LaTeX, VS Code, R IDE, and more,
all in one place. Commercial Alternative to JupyterHub.
Real-time collaboration for Jupyter Notebooks, Linux Terminals, LaTeX, VS Code, R IDE, and more,
all in one place. Commercial Alternative to JupyterHub.
Path: blob/master/Natural Language Processing with Attention Models/Week 4 - Chatbot/C4_W4_Assignment.ipynb
Views: 13373
Assignment 4: Chatbot
Welcome to the last assignment of Course 4. Before you get started, we want to congratulate you on getting here. It is your 16th programming assignment in this Specialization and we are very proud of you! In this assignment, you are going to use the Reformer, also known as the efficient Transformer, to generate a dialogue between two bots. You will feed conversations to your model and it will learn how to understand the context of each one. Not only will it learn how to answer questions but it will also know how to ask questions if it needs more info. For example, after a customer asks for a train ticket, the chatbot can ask what time the said customer wants to leave. You can use this concept to automate call centers, hotel receptions, personal trainers, or any type of customer service. By completing this assignment, you will:
Understand how the Reformer works
Explore the MultiWoz dataset
Process the data to feed it into the model
Train your model
Generate a dialogue by feeding a question to the model
Outline
Part 1: Exploring the MultiWoz dataset
You will start by exploring the MultiWoz dataset. The dataset you are about to use has more than 10,000 human annotated dialogues and spans multiple domains and topics. Some dialogues include multiple domains and others include single domains. In this section, you will load and explore this dataset, as well as develop a function to extract the dialogues.
Let's first import the modules we will be using:
INFO:tensorflow:tokens_length=568 inputs_length=512 targets_length=114 noise_density=0.15 mean_noise_span_length=3.0
trax 1.3.4
WARNING: You are using pip version 20.1.1; however, version 20.3.3 is available.
You should consider upgrading via the '/opt/conda/bin/python3 -m pip install --upgrade pip' command.
Let's also declare some constants we will be using in the exercises.
Let's now load the MultiWOZ 2.1 dataset. We have already provided it for you in your workspace. It is in JSON format so we should load it as such:
Let's see how many dialogues we have in the dictionary. 1 key-value pair is one dialogue so we can just get the dictionary's length.
The dialogues are composed of multiple files and the filenames are used as keys in our dictionary. Those with multi-domain dialogues have "MUL" in their filenames while single domain dialogues have either "SNG" or "WOZ".
As you can see from the cells above, there are 10,438 conversations, each in its own file. You will train your model on all those conversations. Each file is also loaded into a dictionary and each has two keys which are the following:
The goal
also points to a dictionary and it contains several keys pertaining to the objectives of the conversation. For example below, we can see that the conversation will be about booking a taxi.
The log
on the other hand contains the dialog. It is a list of dictionaries and each element of this list contains several descriptions as well. Let's look at an example:
For this assignment, we are only interested in the conversation which is in the text
field. The conversation goes back and forth between two persons. Let's call them 'Person 1' and 'Person 2'. This implies that data['SNG0073.json']['log'][0]['text'] is 'Person 1' and data['SNG0073.json']['log'][1]['text'] is 'Person 2' and so on. The even offsets are 'Person 1' and the odd offsets are 'Person 2'.
Exercise 01
You will now implement the get_conversation()
function that will extract the conversations from the dataset's file.
Instructions: Implement a function to extract conversations from the input file.
As described above, the conversation is in the text
field in each of the elements in the log
list of the file. If the log list has x
number of elements, then the function will get the text
entries of each of those elements. Your function should return the conversation, prepending each field with either ' Person 1: ' if 'x' is even or ' Person 2: ' if 'x' is odd. You can use the Python modulus operator '%' to help select the even/odd entries. Important note: Do not print a newline character (i.e. \n
) when generating the string. For example, in the code cell above, your function should output something like:
and not:
All tests passed
Expected Result:
We can have a utility pretty print function just so we can visually follow the conversation more easily.
Person 1: am looking for a place to to stay that has cheap price range it should be in a type of hotel
Person 2: Okay, do you have a specific area you want to stay in?
Person 1: no, i just need to make sure it's cheap. oh, and i need parking
Person 2: I found 1 cheap hotel for you that includes parking. Do you like me to book it?
Person 1: Yes, please. 6 people 3 nights starting on tuesday.
Person 2: I am sorry but I wasn't able to book that for you for Tuesday. Is there another day you would like to stay or perhaps a shorter stay?
Person 1: how about only 2 nights.
Person 2: Booking was successful.
Reference number is : 7GAWK763. Anything else I can do for you?
Person 1: No, that will be all. Good bye.
Person 2: Thank you for using our services.
For this assignment, we will just use the outputs of the calls to get_conversation
to train the model. But just to expound, there are also other information in the MultiWoz dataset that can be useful in other contexts. Each element of the log list has more information about it. For example, above, if you were to look at the other fields for the following, "am looking for a place to stay that has cheap price range it should be in a type of hotel", you will get the following.
The dataset also comes with hotel, hospital, taxi, train, police, and restaurant databases. For example, in case you need to call a doctor, or a hotel, or a taxi, this will allow you to automate the entire conversation. Take a look at the files accompanying the data set.
For more information about the multiwoz 2.1 data set, please run the cell below to read the ReadMe.txt
file. Feel free to open any other file to explore it.
As you can see, there are many other aspects of the MultiWoz dataset. Nonetheless, you'll see that even with just the conversations, your model will still be able to generate useful responses. This concludes our exploration of the dataset. In the next section, we will do some preprocessing before we feed it into our model for training.
Part 2: Processing the data for Reformer inputs
You will now use the get_conversation()
function to process the data. The Reformer expects inputs of this form:
Person 1: Why am I so happy? Person 2: Because you are learning NLP Person 1: ... Person 2: ...*
And the conversation keeps going with some text. As you can see 'Person 1' and 'Person 2' act as delimiters so the model automatically recognizes the person and who is talking. It can then come up with the corresponding text responses for each person. Let's proceed to process the text in this fashion for the Reformer. First, let's grab all the conversation strings from all dialogue files and put them in a list.
Now let us split the list to a train and eval dataset.
Now let's define our data pipeline for tokenizing and batching our data. As in the previous assignments, we will bucket by length and also have an upper bound on the token length.
Peek into the train stream.
Part 3: Reversible layers
When running large deep models, you will often run out of memory as each layer allocates memory to store activations for use in backpropagation. To save this resource, you need to be able to recompute these activations during the backward pass without storing them during the forward pass. Take a look first at the leftmost diagram below.
This is how the residual networks are implemented in the standard Transformer. It follows that, given F()
is Attention and G()
is Feed-forward(FF). :
As you can see, it requires that and be saved so it can be used during backpropagation. We want to avoid this to conserve memory and this is where reversible residual connections come in. They are shown in the middle and rightmost diagrams above. The key idea is that we will start with two copies of the input to the model and at each layer we will only update one of them. The activations that we don’t update are the ones that will be used to compute the residuals.
Now in this reversible set up you get the following instead:
To recover from
With this configuration, we’re now able to run the network fully in reverse. You'll notice that during the backward pass, and can be recomputed based solely on the values of and . No need to save it during the forward pass.
Exercise 02
Instructions: You will implement the reversible_layer_forward
function using equations 3 and 4 above. This function takes in the input vector x
and the functions f
and g
and returns the concatenation of . For this exercise, we will be splitting x
before going through the reversible residual steps. We can then use those two vectors for the reversible_layer_reverse
function. Utilize np.concatenate()
to form the output being careful to match the axis of the np.split()
.
Take note that this is just for demonstrating the concept in this exercise and there are other ways of processing the input. As you'll see in the Reformer architecture later, the initial input (i.e. x
) can instead be duplicated instead of split.
All tests passed
Exercise 03
You will now implement the reversible_layer_reverse
function which is possible because at every time step you have and and and , along with the function f
, and g
. Where f
is the attention and g
is the feedforward. This allows you to compute equations 5 and 6.
Instructions: Implement the reversible_layer_reverse
. Your function takes in the output vector from reversible_layer_forward
and functions f and g. Using equations 5 and 6 above, it computes the inputs to the layer, and . The output, x, is the concatenation of . Utilize np.concatenate()
to form the output being careful to match the axis of the np.split()
.
All tests passed
3.1 Reversible layers and randomness
This is why we were learning about fastmath's random functions and keys in Course 3 Week 1. Utilizing the same key, trax.fastmath.random.uniform()
will return the same values. This is required for the backward pass to return the correct layer inputs when random noise is introduced in the layer.
Part 4: ReformerLM Training
You will now proceed to training your model. Since you have already know the two main components that differentiates it from the standard Transformer, LSH in Course 1 and reversible layers above, you can just use the pre-built model already implemented in Trax. It will have this architecture:
Similar to the Transformer you learned earlier, you want to apply an attention and feed forward layer to your inputs. For the Reformer, we improve the memory efficiency by using reversible decoder blocks and you can picture its implementation in Trax like below:
You can see that it takes the initial inputs x1
and x2
and does the first equation of the reversible networks you learned in Part 3. As you've also learned, the reversible residual has two equations for the forward-pass so doing just one of them will just constitute half of the reversible decoder block. Before doing the second equation (i.e. second half of the reversible residual), it first needs to swap the elements to take into account the stack semantics in Trax. It simply puts x2
on top of the stack so it can be fed to the add block of the half-residual layer. It then swaps the two outputs again so it can be fed to the next layer of the network. All of these arrives at the two equations in Part 3 and it can be used to recompute the activations during the backward pass.
These are already implemented for you in Trax and in the following exercise, you'll get to practice how to call them to build your network.
Exercise 04
Instructions: Implement a wrapper function that returns a Reformer Language Model. You can use Trax's ReformerLM to do this quickly. It will have the same architecture as shown above.
All tests passed
Exercise 05
You will now write a function that takes in your model and trains it.
Instructions: Implement the training_loop
below to train the neural network above. Here is a list of things you should do:
Create
TrainTask
andEvalTask
Create the training loop
trax.supervised.training.Loop
Pass in the following depending to train_task :
labeled_data=train_gen
loss_layer=tl.CrossEntropyLoss()
optimizer=trax.optimizers.Adam(0.01)
lr_schedule=lr_schedule
n_steps_per_checkpoint=10
You will be using your CrossEntropyLoss loss function with Adam optimizer. Please read the trax documentation to get a full understanding.
Pass in the following to eval_task:
labeled_data=eval_gen
metrics=[tl.CrossEntropyLoss(), tl.Accuracy()]
This function should return a training.Loop
object. To read more about this check the docs.
All tests passed
Approximate Expected output:
Part 5: Decode from a pretrained model
We will now proceed on decoding using the model architecture you just implemented. As in the previous weeks, we will be giving you a pretrained model so you can observe meaningful output during inference. You will be using the autoregressive_sample_stream() decoding method from Trax to do fast inference. Let's define a few parameters to initialize our model.
We can now initialize our model from a file containing the pretrained weights. We will save this starting state so we can reset the model state when we generate a new conversation. This will become clearer in the generate_dialogue()
function later.
Let's define a few utility functions as well to help us tokenize and detokenize. We can use the tokenize() and detokenize() from trax.data.tf_inputs
to do this.
We are now ready to define our decoding function. This will return a generator that yields that next symbol output by the model. It will be able to predict the next words by just feeding it a starting sentence.
Expected value:
[1, 0, 4, 3, 0, 4]
Great! Now you will be able to see the model in action. The utility function below will call the generator you just implemented and will just format the output to be easier to read.
We can now feed in different starting sentences and see how the model generates the dialogue. You can even input your own starting sentence. Just remember to ask a question that covers the topics in the Multiwoz dataset so you can generate a meaningful conversation.
Congratulations! You just wrapped up the final assignment of this course and the entire specialization!