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/C5 - Sequence Models/Week 4/C5_W4_A1_Transformer_Subclass_v1.py
Views: 4818
#!/usr/bin/env python1# coding: utf-823# # Transformer Network4#5# Welcome to Week 4's assignment, the last assignment of Course 5 of the Deep Learning Specialization! And congratulations on making it to the last assignment of the entire Deep Learning Specialization - you're almost done!6#7# Ealier in the course, you've implemented sequential neural networks such as RNNs, GRUs, and LSTMs. In this notebook you'll explore the Transformer architecture, a neural network that takes advantage of parallel processing and allows you to substantially speed up the training process.8#9# **After this assignment you'll be able to**:10#11# * Create positional encodings to capture sequential relationships in data12# * Calculate scaled dot-product self-attention with word embeddings13# * Implement masked multi-head attention14# * Build and train a Transformer model15#16# For the last time, let's get started!1718# ## Table of Contents19#20# - [Packages](#0)21# - [1 - Positional Encoding](#1)22# - [1.1 - Sine and Cosine Angles](#1-1)23# - [Exercise 1 - get_angles](#ex-1)24# - [1.2 - Sine and Cosine Positional Encodings](#1-2)25# - [Exercise 2 - positional_encoding](#ex-2)26# - [2 - Masking](#2)27# - [2.1 - Padding Mask](#2-1)28# - [2.2 - Look-ahead Mask](#2-2)29# - [3 - Self-Attention](#3)30# - [Exercise 3 - scaled_dot_product_attention](#ex-3)31# - [4 - Encoder](#4)32# - [4.1 Encoder Layer](#4-1)33# - [Exercise 4 - EncoderLayer](#ex-4)34# - [4.2 - Full Encoder](#4-2)35# - [Exercise 5 - Encoder](#ex-5)36# - [5 - Decoder](#5)37# - [5.1 - Decoder Layer](#5-1)38# - [Exercise 6 - DecoderLayer](#ex-6)39# - [5.2 - Full Decoder](#5-2)40# - [Exercise 7 - Decoder](#ex-7)41# - [6 - Transformer](#6)42# - [Exercise 8 - Transformer](#ex-8)43# - [7 - References](#7)4445# <a name='0'></a>46# ## Packages47#48# Run the following cell to load the packages you'll need.4950# In[ ]:515253import tensorflow as tf54import pandas as pd55import time56import numpy as np57import matplotlib.pyplot as plt5859from tensorflow.keras.layers import Embedding, MultiHeadAttention, Dense, Input, Dropout, LayerNormalization60from transformers import DistilBertTokenizerFast #, TFDistilBertModel61from transformers import TFDistilBertForTokenClassification62from tqdm import tqdm_notebook as tqdm636465# <a name='1'></a>66# ## 1 - Positional Encoding67#68# In sequence to sequence tasks, the relative order of your data is extremely important to its meaning. When you were training sequential neural networks such as RNNs, you fed your inputs into the network in order. Information about the order of your data was automatically fed into your model. However, when you train a Transformer network using multi-head attention, you feed your data into the model all at once. While this dramatically reduces training time, there is no information about the order of your data. This is where positional encoding is useful - you can specifically encode the positions of your inputs and pass them into the network using these sine and cosine formulas:69#70# $$71# PE_{(pos, 2i)}= sin\left(\frac{pos}{{10000}^{\frac{2i}{d}}}\right)72# \tag{1}$$73# <br>74# $$75# PE_{(pos, 2i+1)}= cos\left(\frac{pos}{{10000}^{\frac{2i}{d}}}\right)76# \tag{2}$$77#78# * $d$ is the dimension of the word embedding and positional encoding79# * $pos$ is the position of the word.80# * $i$ refers to each of the different dimensions of the positional encoding.81#82# To develop some intuition about positional encodings, you can think of them broadly as a feature that contains the information about the relative positions of words. The sum of the positional encoding and word embedding is ultimately what is fed into the model. If you just hard code the positions in, say by adding a matrix of 1's or whole numbers to the word embedding, the semantic meaning is distorted. Conversely, the values of the sine and cosine equations are small enough (between -1 and 1) that when you add the positional encoding to a word embedding, the word embedding is not significantly distorted, and is instead enriched with positional information. Using a combination of these two equations helps your Transformer network attend to the relative positions of your input data. This was a short discussion on positional encodings, but develop further intuition, check out the *Positional Encoding Ungraded Lab*.83#84# **Note:** In the lectures Andrew uses vertical vectors, but in this assignment all vectors are horizontal. All matrix multiplications should be adjusted accordingly.85#86# <a name='1-1'></a>87# ### 1.1 - Sine and Cosine Angles88#89# Notice that even though the sine and cosine positional encoding equations take in different arguments (`2i` versus `2i+1`, or even versus odd numbers) the inner terms for both equations are the same: $$\theta(pos, i, d) = \frac{pos}{10000^{\frac{2i}{d}}} \tag{3}$$90#91# Consider the inner term as you calculate the positional encoding for a word in a sequence.<br>92# $PE_{(pos, 0)}= sin\left(\frac{pos}{{10000}^{\frac{0}{d}}}\right)$, since solving `2i = 0` gives `i = 0` <br>93# $PE_{(pos, 1)}= cos\left(\frac{pos}{{10000}^{\frac{0}{d}}}\right)$, since solving `2i + 1 = 1` gives `i = 0`94#95# The angle is the same for both! The angles for $PE_{(pos, 2)}$ and $PE_{(pos, 3)}$ are the same as well, since for both, `i = 1` and therefore the inner term is $\left(\frac{pos}{{10000}^{\frac{1}{d}}}\right)$. This relationship holds true for all paired sine and cosine curves:96#97# | k | <code> 0 </code>|<code> 1 </code>|<code> 2 </code>|<code> 3 </code>| <code> ... </code> |<code> d - 2 </code>|<code> d - 1 </code>|98# | ---------------- | :------: | ----------------- | ----------------- | ----------------- | ----- | ----------------- | ----------------- |99# | encoding(0) = |[$sin(\theta(0, 0, d))$| $cos(\theta(0, 0, d))$| $sin(\theta(0, 1, d))$| $cos(\theta(0, 1, d))$|... |$sin(\theta(0, d//2, d))$| $cos(\theta(0, d//2, d))$]|100# | encoding(1) = | [$sin(\theta(1, 0, d))$| $cos(\theta(1, 0, d))$| $sin(\theta(1, 1, d))$| $cos(\theta(1, 1, d))$|... |$sin(\theta(1, d//2, d))$| $cos(\theta(1, d//2, d))$]|101# ...102# | encoding(pos) = | [$sin(\theta(pos, 0, d))$| $cos(\theta(pos, 0, d))$| $sin(\theta(pos, 1, d))$| $cos(\theta(pos, 1, d))$|... |$sin(\theta(pos, d//2, d))$| $cos(\theta(pos, d//2, d))]$|103#104#105# <a name='ex-1'></a>106# ### Exercise 1 - get_angles107#108# Implement the function `get_angles()` to calculate the possible angles for the sine and cosine positional encodings109#110# **Hints**111#112# - If `k = [0, 1, 2, 3, 4, 5]`, then, `i` must be `i = [0, 0, 1, 1, 2, 2]`113# - `i = k//2`114115# In[ ]:116117118# UNQ_C1 (UNIQUE CELL IDENTIFIER, DO NOT EDIT)119# GRADED FUNCTION get_angles120def get_angles(pos, k, d):121"""122Get the angles for the positional encoding123124Arguments:125pos -- Column vector containing the positions [[0], [1], ...,[N-1]]126k -- Row vector containing the dimension span [[0, 1, 2, ..., d-1]]127d(integer) -- Encoding size128129Returns:130angles -- (pos, d) numpy array131"""132133# START CODE HERE134135136137i = k // 2138# Calculate the angles using pos, i and d139angles = pos / np.power(10000, 2 * i / d)140141# END CODE HERE142143return angles144145146# In[ ]:147148149from public_tests import *150151get_angles_test(get_angles)152153# Example154position = 4155d_model = 8156pos_m = np.arange(position)[:, np.newaxis]157dims = np.arange(d_model)[np.newaxis, :]158get_angles(pos_m, dims, d_model)159160161# <a name='1-2'></a>162# ### 1.2 - Sine and Cosine Positional Encodings163#164# Now you can use the angles you computed to calculate the sine and cosine positional encodings.165#166# $$167# PE_{(pos, 2i)}= sin\left(\frac{pos}{{10000}^{\frac{2i}{d}}}\right)168# $$169# <br>170# $$171# PE_{(pos, 2i+1)}= cos\left(\frac{pos}{{10000}^{\frac{2i}{d}}}\right)172# $$173#174# <a name='ex-2'></a>175# ### Exercise 2 - positional_encoding176#177# Implement the function `positional_encoding()` to calculate the sine and cosine positional encodings178#179# **Reminder:** Use the sine equation when $i$ is an even number and the cosine equation when $i$ is an odd number.180#181# #### Additional Hints182# * You may find183# [np.newaxis](https://numpy.org/doc/stable/reference/arrays.indexing.html) useful depending on the implementation you choose.184185# In[ ]:186187188# UNQ_C2 (UNIQUE CELL IDENTIFIER, DO NOT EDIT)189# GRADED FUNCTION positional_encoding190def positional_encoding(positions, d):191"""192Precomputes a matrix with all the positional encodings193194Arguments:195positions (int) -- Maximum number of positions to be encoded196d (int) -- Encoding size197198Returns:199pos_encoding -- (1, position, d_model) A matrix with the positional encodings200"""201# START CODE HERE202# initialize a matrix angle_rads of all the angles203angle_rads = get_angles(np.arange(positions)[:, np.newaxis],204np.arange(d)[np.newaxis, :],205d)206207# apply sin to even indices in the array; 2i208angle_rads[:, 0::2] = np.sin(angle_rads[:, 0::2])209210# apply cos to odd indices in the array; 2i+1211angle_rads[:, 1::2] = np.cos(angle_rads[:, 1::2])212# END CODE HERE213214pos_encoding = angle_rads[np.newaxis, ...]215216return tf.cast(pos_encoding, dtype=tf.float32)217218219# In[ ]:220221222# UNIT TEST223positional_encoding_test(positional_encoding, get_angles)224225226# Nice work calculating the positional encodings! Now you can visualize them.227228# In[ ]:229230231pos_encoding = positional_encoding(50, 512)232233print (pos_encoding.shape)234235plt.pcolormesh(pos_encoding[0], cmap='RdBu')236plt.xlabel('d')237plt.xlim((0, 512))238plt.ylabel('Position')239plt.colorbar()240plt.show()241242243# Each row represents a positional encoding - notice how none of the rows are identical! You have created a unique positional encoding for each of the words.244245# <a name='2'></a>246# ## 2 - Masking247#248# There are two types of masks that are useful when building your Transformer network: the *padding mask* and the *look-ahead mask*. Both help the softmax computation give the appropriate weights to the words in your input sentence.249#250# <a name='2-1'></a>251# ### 2.1 - Padding Mask252#253# Oftentimes your input sequence will exceed the maximum length of a sequence your network can process. Let's say the maximum length of your model is five, it is fed the following sequences:254#255# [["Do", "you", "know", "when", "Jane", "is", "going", "to", "visit", "Africa"],256# ["Jane", "visits", "Africa", "in", "September" ],257# ["Exciting", "!"]258# ]259#260# which might get vectorized as:261#262# [[ 71, 121, 4, 56, 99, 2344, 345, 1284, 15],263# [ 56, 1285, 15, 181, 545],264# [ 87, 600]265# ]266#267# When passing sequences into a transformer model, it is important that they are of uniform length. You can achieve this by padding the sequence with zeros, and truncating sentences that exceed the maximum length of your model:268#269# [[ 71, 121, 4, 56, 99],270# [ 2344, 345, 1284, 15, 0],271# [ 56, 1285, 15, 181, 545],272# [ 87, 600, 0, 0, 0],273# ]274#275# Sequences longer than the maximum length of five will be truncated, and zeros will be added to the truncated sequence to achieve uniform length. Similarly, for sequences shorter than the maximum length, they zeros will also be added for padding. However, these zeros will affect the softmax calculation - this is when a padding mask comes in handy! You will need to define a boolean mask that specifies which elements you must attend(1) and which elements you must ignore(0). Later you will use that mask to set all the zeros in the sequence to a value close to negative infinity (-1e9). We'll implement this for you so you can get to the fun of building the Transformer network! 😇 Just make sure you go through the code so you can correctly implement padding when building your model.276#277# After masking, your input should go from `[87, 600, 0, 0, 0]` to `[87, 600, -1e9, -1e9, -1e9]`, so that when you take the softmax, the zeros don't affect the score.278#279# The [MultiheadAttention](https://keras.io/api/layers/attention_layers/multi_head_attention/) layer implemented in Keras, use this masking logic.280281# In[ ]:282283284def create_padding_mask(decoder_token_ids):285"""286Creates a matrix mask for the padding cells287288Arguments:289decoder_token_ids -- (n, m) matrix290291Returns:292mask -- (n, 1, 1, m) binary tensor293"""294seq = 1 - tf.cast(tf.math.equal(decoder_token_ids, 0), tf.float32)295296# add extra dimensions to add the padding297# to the attention logits.298return seq[:, tf.newaxis, :]299300301# In[ ]:302303304x = tf.constant([[7., 6., 0., 0., 1.], [1., 2., 3., 0., 0.], [0., 0., 0., 4., 5.]])305print(create_padding_mask(x))306307308# If we multiply (1 - mask) by -1e9 and add it to the sample input sequences, the zeros are essentially set to negative infinity. Notice the difference when taking the softmax of the original sequence and the masked sequence:309310# In[ ]:311312313print(tf.keras.activations.softmax(x))314print(tf.keras.activations.softmax(x + (1 - create_padding_mask(x)) * -1.0e9))315316317# <a name='2-2'></a>318# ### 2.2 - Look-ahead Mask319#320# The look-ahead mask follows similar intuition. In training, you will have access to the complete correct output of your training example. The look-ahead mask helps your model pretend that it correctly predicted a part of the output and see if, *without looking ahead*, it can correctly predict the next output.321#322# For example, if the expected correct output is `[1, 2, 3]` and you wanted to see if given that the model correctly predicted the first value it could predict the second value, you would mask out the second and third values. So you would input the masked sequence `[1, -1e9, -1e9]` and see if it could generate `[1, 2, -1e9]`.323#324# Just because you've worked so hard, we'll also implement this mask for you 😇😇. Again, take a close look at the code so you can effictively implement it later.325326# In[ ]:327328329def create_look_ahead_mask(sequence_length):330"""331Returns an upper triangular matrix filled with ones332333Arguments:334sequence_length -- matrix size335336Returns:337mask -- (size, size) tensor338"""339mask = tf.linalg.band_part(tf.ones((1, sequence_length, sequence_length)), -1, 0)340return mask341342343# In[ ]:344345346x = tf.random.uniform((1, 3))347temp = create_look_ahead_mask(x.shape[1])348temp349350351# <a name='3'></a>352# ## 3 - Self-Attention353#354# As the authors of the Transformers paper state, "Attention is All You Need".355#356# <img src="self-attention.png" alt="Encoder" width="600"/>357# <caption><center><font color='purple'><b>Figure 1: Self-Attention calculation visualization</font></center></caption>358#359# The use of self-attention paired with traditional convolutional networks allows for the parallization which speeds up training. You will implement **scaled dot product attention** which takes in a query, key, value, and a mask as inputs to returns rich, attention-based vector representations of the words in your sequence. This type of self-attention can be mathematically expressed as:360# $$361# \text { Attention }(Q, K, V)=\operatorname{softmax}\left(\frac{Q K^{T}}{\sqrt{d_{k}}}+{M}\right) V\tag{4}\362# $$363#364# * $Q$ is the matrix of queries365# * $K$ is the matrix of keys366# * $V$ is the matrix of values367# * $M$ is the optional mask you choose to apply368# * ${d_k}$ is the dimension of the keys, which is used to scale everything down so the softmax doesn't explode369#370# <a name='ex-3'></a>371# ### Exercise 3 - scaled_dot_product_attention372#373# Implement the function `scaled_dot_product_attention()` to create attention-based representations374# **Reminder**: The boolean mask parameter can be passed in as `none` or as either padding or look-ahead.375#376# Multiply (1. - mask) by -1e9 before applying the softmax.377#378# **Additional Hints**379# * You may find [tf.matmul](https://www.tensorflow.org/api_docs/python/tf/linalg/matmul) useful for matrix multiplication.380381# In[ ]:382383384# UNQ_C3 (UNIQUE CELL IDENTIFIER, DO NOT EDIT)385# GRADED FUNCTION scaled_dot_product_attention386def scaled_dot_product_attention(q, k, v, mask):387"""388Calculate the attention weights.389q, k, v must have matching leading dimensions.390k, v must have matching penultimate dimension, i.e.: seq_len_k = seq_len_v.391The mask has different shapes depending on its type(padding or look ahead)392but it must be broadcastable for addition.393394Arguments:395q -- query shape == (..., seq_len_q, depth)396k -- key shape == (..., seq_len_k, depth)397v -- value shape == (..., seq_len_v, depth_v)398mask: Float tensor with shape broadcastable399to (..., seq_len_q, seq_len_k). Defaults to None.400401Returns:402output -- attention_weights403"""404# START CODE HERE405406matmul_qk = tf.matmul(q, k, transpose_b = True) # (..., seq_len_q, seq_len_k)407408# scale matmul_qk409dk = tf.cast(tf.shape(k)[-1], tf.float32)410scaled_attention_logits = matmul_qk / tf.math.sqrt(dk)411412# add the mask to the scaled tensor.413if mask is not None: # Don't replace this None414scaled_attention_logits += ((1 - mask) * -1e9)415416# softmax is normalized on the last axis (seq_len_k) so that the scores417# add up to 1.418attention_weights = tf.nn.softmax(scaled_attention_logits, axis = -1) # (..., seq_len_q, seq_len_k)419420output = tf.matmul(attention_weights, v) # (..., seq_len_q, depth_v)421422# END CODE HERE423return output, attention_weights424425426# In[ ]:427428429# UNIT TEST430scaled_dot_product_attention_test(scaled_dot_product_attention)431432433# Excellent work! You can now implement self-attention. With that, you can start building the encoder block!434435# <a name='4'></a>436# ## 4 - Encoder437#438# The Transformer Encoder layer pairs self-attention and convolutional neural network style of processing to improve the speed of training and passes K and V matrices to the Decoder, which you'll build later in the assignment. In this section of the assignment, you will implement the Encoder by pairing multi-head attention and a feed forward neural network (Figure 2a).439# <img src="encoder_layer.png" alt="Encoder" width="250"/>440# <caption><center><font color='purple'><b>Figure 2a: Transformer encoder layer</font></center></caption>441#442# * `MultiHeadAttention` you can think of as computing the self-attention several times to detect different features.443# * Feed forward neural network contains two Dense layers which we'll implement as the function `FullyConnected`444#445# Your input sentence first passes through a *multi-head attention layer*, where the encoder looks at other words in the input sentence as it encodes a specific word. The outputs of the multi-head attention layer are then fed to a *feed forward neural network*. The exact same feed forward network is independently applied to each position.446#447# * For the `MultiHeadAttention` layer, you will use the [Keras implementation](https://www.tensorflow.org/api_docs/python/tf/keras/layers/MultiHeadAttention). If you're curious about how to split the query matrix Q, key matrix K, and value matrix V into different heads, you can look through the implementation.448# * You will also use the [Sequential API](https://keras.io/api/models/sequential/) with two dense layers to built the feed forward neural network layers.449450# In[ ]:451452453def FullyConnected(embedding_dim, fully_connected_dim):454return tf.keras.Sequential([455tf.keras.layers.Dense(fully_connected_dim, activation='relu'), # (batch_size, seq_len, dff)456tf.keras.layers.Dense(embedding_dim) # (batch_size, seq_len, d_model)457])458459460# <a name='4-1'></a>461# ### 4.1 Encoder Layer462#463# Now you can pair multi-head attention and feed forward neural network together in an encoder layer! You will also use residual connections and layer normalization to help speed up training (Figure 2a).464#465# <a name='ex-4'></a>466# ### Exercise 4 - EncoderLayer467#468# Implement `EncoderLayer()` using the `call()` method469#470# In this exercise, you will implement one encoder block (Figure 2) using the `call()` method. The function should perform the following steps:471# 1. You will pass the Q, V, K matrices and a boolean mask to a multi-head attention layer. Remember that to compute *self*-attention Q, V and K should be the same. Let the default values for `return_attention_scores` and `training`. You will also perform Dropout in this multi-head attention layer during training.472# 2. Now add a skip connection by adding your original input `x` and the output of the your multi-head attention layer.473# 3. After adding the skip connection, pass the output through the first normalization layer.474# 4. Finally, repeat steps 1-3 but with the feed forward neural network with a dropout layer instead of the multi-head attention layer.475#476# <details>477# <summary><font size="2" color="darkgreen"><b>Additional Hints (Click to expand)</b></font></summary>478#479# * The `__init__` method creates all the layers that will be accesed by the the `call` method. Wherever you want to use a layer defined inside the `__init__` method you will have to use the syntax `self.[insert layer name]`.480# * You will find the documentation of [MultiHeadAttention](https://www.tensorflow.org/api_docs/python/tf/keras/layers/MultiHeadAttention) helpful. *Note that if query, key and value are the same, then this function performs self-attention.*481# * The call arguments for `self.mha` are (Where B is for batch_size, T is for target sequence shapes, and S is output_shape):482# - `query`: Query Tensor of shape (B, T, dim).483# - `value`: Value Tensor of shape (B, S, dim).484# - `key`: Optional key Tensor of shape (B, S, dim). If not given, will use value for both key and value, which is the most common case.485# - `attention_mask`: a boolean mask of shape (B, T, S), that prevents attention to certain positions. The boolean mask specifies which query elements can attend to which key elements, 1 indicates attention and 0 indicates no attention. Broadcasting can happen for the missing batch dimensions and the head dimension.486# - `return_attention_scores`: A boolean to indicate whether the output should be attention output if True, or (attention_output, attention_scores) if False. Defaults to False.487# - `training`: Python boolean indicating whether the layer should behave in training mode (adding dropout) or in inference mode (no dropout). Defaults to either using the training mode of the parent layer/model, or False (inference) if there is no parent layer.488489# In[ ]:490491492# UNQ_C4 (UNIQUE CELL IDENTIFIER, DO NOT EDIT)493# GRADED FUNCTION EncoderLayer494class EncoderLayer(tf.keras.layers.Layer):495"""496The encoder layer is composed by a multi-head self-attention mechanism,497followed by a simple, positionwise fully connected feed-forward network.498This archirecture includes a residual connection around each of the two499sub-layers, followed by layer normalization.500"""501def __init__(self, embedding_dim, num_heads, fully_connected_dim,502dropout_rate=0.1, layernorm_eps=1e-6):503super(EncoderLayer, self).__init__()504505self.mha = MultiHeadAttention(num_heads=num_heads,506key_dim=embedding_dim,507dropout=dropout_rate)508509self.ffn = FullyConnected(embedding_dim=embedding_dim,510fully_connected_dim=fully_connected_dim)511512self.layernorm1 = LayerNormalization(epsilon=layernorm_eps)513self.layernorm2 = LayerNormalization(epsilon=layernorm_eps)514515self.dropout_ffn = Dropout(dropout_rate)516517def call(self, x, training, mask):518"""519Forward pass for the Encoder Layer520521Arguments:522x -- Tensor of shape (batch_size, input_seq_len, fully_connected_dim)523training -- Boolean, set to true to activate524the training mode for dropout layers525mask -- Boolean mask to ensure that the padding is not526treated as part of the input527Returns:528encoder_layer_out -- Tensor of shape (batch_size, input_seq_len, fully_connected_dim)529"""530# START CODE HERE531# calculate self-attention using mha(~1 line). Dropout will be applied during training532attn_output = self.mha(x, x, x, mask) # Self attention (batch_size, input_seq_len, fully_connected_dim)533534# apply layer normalization on sum of the input and the attention output to get the535# output of the multi-head attention layer (~1 line)536out1 = self.layernorm1(x + attn_output) # (batch_size, input_seq_len, fully_connected_dim)537538# pass the output of the multi-head attention layer through a ffn (~1 line)539ffn_output = self.ffn(out1) # (batch_size, input_seq_len, fully_connected_dim)540541# apply dropout layer to ffn output during training (~1 line)542ffn_output = self.dropout_ffn(ffn_output, training=training)543544# apply layer normalization on sum of the output from multi-head attention and ffn output to get the545# output of the encoder layer (~1 line)546encoder_layer_out = self.layernorm2(out1 + ffn_output) # (batch_size, input_seq_len, fully_connected_dim)547# END CODE HERE548549return encoder_layer_out550551552553# In[ ]:554555556# UNIT TEST557EncoderLayer_test(EncoderLayer)558559560# <a name='4-2'></a>561# ### 4.2 - Full Encoder562#563# Awesome job! You have now successfully implemented positional encoding, self-attention, and an encoder layer - give yourself a pat on the back. Now you're ready to build the full Transformer Encoder (Figure 2b), where you will embedd your input and add the positional encodings you calculated. You will then feed your encoded embeddings to a stack of Encoder layers.564#565# <img src="encoder.png" alt="Encoder" width="330"/>566# <caption><center><font color='purple'><b>Figure 2b: Transformer Encoder</font></center></caption>567#568#569# <a name='ex-5'></a>570# ### Exercise 5 - Encoder571#572# Complete the `Encoder()` function using the `call()` method to embed your input, add positional encoding, and implement multiple encoder layers573#574# In this exercise, you will initialize your Encoder with an Embedding layer, positional encoding, and multiple EncoderLayers. Your `call()` method will perform the following steps:575# 1. Pass your input through the Embedding layer.576# 2. Scale your embedding by multiplying it by the square root of your embedding dimension. Remember to cast the embedding dimension to data type `tf.float32` before computing the square root.577# 3. Add the position encoding: self.pos_encoding `[:, :seq_len, :]` to your embedding.578# 4. Pass the encoded embedding through a dropout layer, remembering to use the `training` parameter to set the model training mode.579# 5. Pass the output of the dropout layer through the stack of encoding layers using a for loop.580581# In[ ]:582583584# UNQ_C5 (UNIQUE CELL IDENTIFIER, DO NOT EDIT)585# GRADED FUNCTION586class Encoder(tf.keras.layers.Layer):587"""588The entire Encoder starts by passing the input to an embedding layer589and using positional encoding to then pass the output through a stack of590encoder Layers591592"""593def __init__(self, num_layers, embedding_dim, num_heads, fully_connected_dim, input_vocab_size,594maximum_position_encoding, dropout_rate=0.1, layernorm_eps=1e-6):595super(Encoder, self).__init__()596597self.embedding_dim = embedding_dim598self.num_layers = num_layers599600self.embedding = Embedding(input_vocab_size, self.embedding_dim)601self.pos_encoding = positional_encoding(maximum_position_encoding,602self.embedding_dim)603604605self.enc_layers = [EncoderLayer(embedding_dim=self.embedding_dim,606num_heads=num_heads,607fully_connected_dim=fully_connected_dim,608dropout_rate=dropout_rate,609layernorm_eps=layernorm_eps)610for _ in range(self.num_layers)]611612self.dropout = Dropout(dropout_rate)613614def call(self, x, training, mask):615"""616Forward pass for the Encoder617618Arguments:619x -- Tensor of shape (batch_size, input_seq_len)620training -- Boolean, set to true to activate621the training mode for dropout layers622mask -- Boolean mask to ensure that the padding is not623treated as part of the input624Returns:625out2 -- Tensor of shape (batch_size, input_seq_len, fully_connected_dim)626"""627#mask = create_padding_mask(x)628seq_len = tf.shape(x)[1]629630# START CODE HERE631# Pass input through the Embedding layer632x = self.embedding(x) # (batch_size, input_seq_len, fully_connected_dim)633# Scale embedding by multiplying it by the square root of the embedding dimension634x *= tf.math.sqrt(tf.cast(self.embedding_dim, tf.float32))635# Add the position encoding to embedding636x += self.pos_encoding[:, :seq_len, :]637# Pass the encoded embedding through a dropout layer638x = self.dropout(x, training = training)639# Pass the output through the stack of encoding layers640for i in range(self.num_layers):641x = self.enc_layers[i](x, training, mask)642# END CODE HERE643644return x # (batch_size, input_seq_len, fully_connected_dim)645646647# In[ ]:648649650# UNIT TEST651Encoder_test(Encoder)652653654# <a name='5'></a>655# ## 5 - Decoder656#657# The Decoder layer takes the K and V matrices generated by the Encoder and in computes the second multi-head attention layer with the Q matrix from the output (Figure 3a).658#659# <img src="decoder_layer.png" alt="Encoder" width="250"/>660# <caption><center><font color='purple'><b>Figure 3a: Transformer Decoder layer</font></center></caption>661#662# <a name='5-1'></a>663# ### 5.1 - Decoder Layer664# Again, you'll pair multi-head attention with a feed forward neural network, but this time you'll implement two multi-head attention layers. You will also use residual connections and layer normalization to help speed up training (Figure 3a).665#666# <a name='ex-6'></a>667# ### Exercise 6 - DecoderLayer668#669# Implement `DecoderLayer()` using the `call()` method670#671# 1. Block 1 is a multi-head attention layer with a residual connection, and look-ahead mask. Like in the `EncoderLayer`, Dropout is defined within the multi-head attention layer.672# 2. Block 2 will take into account the output of the Encoder, so the multi-head attention layer will receive K and V from the encoder, and Q from the Block 1. You will then apply a normalization layer and a residual connection, just like you did before with the `EncoderLayer`.673# 3. Finally, Block 3 is a feed forward neural network with dropout and normalization layers and a residual connection.674#675# **Additional Hints:**676# * The first two blocks are fairly similar to the EncoderLayer except you will return `attention_scores` when computing self-attention677678# In[ ]:679680681# UNQ_C6 (UNIQUE CELL IDENTIFIER, DO NOT EDIT)682# GRADED FUNCTION DecoderLayer683class DecoderLayer(tf.keras.layers.Layer):684"""685The decoder layer is composed by two multi-head attention blocks,686one that takes the new input and uses self-attention, and the other687one that combines it with the output of the encoder, followed by a688fully connected block.689"""690def __init__(self, embedding_dim, num_heads, fully_connected_dim, dropout_rate=0.1, layernorm_eps=1e-6):691super(DecoderLayer, self).__init__()692693self.mha1 = MultiHeadAttention(num_heads=num_heads,694key_dim=embedding_dim,695dropout=dropout_rate)696697self.mha2 = MultiHeadAttention(num_heads=num_heads,698key_dim=embedding_dim,699dropout=dropout_rate)700701self.ffn = FullyConnected(embedding_dim=embedding_dim,702fully_connected_dim=fully_connected_dim)703704self.layernorm1 = LayerNormalization(epsilon=layernorm_eps)705self.layernorm2 = LayerNormalization(epsilon=layernorm_eps)706self.layernorm3 = LayerNormalization(epsilon=layernorm_eps)707708self.dropout_ffn = Dropout(dropout_rate)709710def call(self, x, enc_output, training, look_ahead_mask, padding_mask):711"""712Forward pass for the Decoder Layer713714Arguments:715x -- Tensor of shape (batch_size, target_seq_len, fully_connected_dim)716enc_output -- Tensor of shape(batch_size, input_seq_len, fully_connected_dim)717training -- Boolean, set to true to activate718the training mode for dropout layers719look_ahead_mask -- Boolean mask for the target_input720padding_mask -- Boolean mask for the second multihead attention layer721Returns:722out3 -- Tensor of shape (batch_size, target_seq_len, fully_connected_dim)723attn_weights_block1 -- Tensor of shape(batch_size, num_heads, target_seq_len, input_seq_len)724attn_weights_block2 -- Tensor of shape(batch_size, num_heads, target_seq_len, input_seq_len)725"""726727# START CODE HERE728# enc_output.shape == (batch_size, input_seq_len, fully_connected_dim)729730# BLOCK 1731# calculate self-attention and return attention scores as attn_weights_block1.732# Dropout will be applied during training (~1 line).733mult_attn_out1, attn_weights_block1 = self.mha1(x, x, x, look_ahead_mask, return_attention_scores=True) # (batch_size, target_seq_len, d_model)734735# apply layer normalization (layernorm1) to the sum of the attention output and the input (~1 line)736Q1 = self.layernorm1(mult_attn_out1 + x)737738# BLOCK 2739# calculate self-attention using the Q from the first block and K and V from the encoder output.740# Dropout will be applied during training741# Return attention scores as attn_weights_block2 (~1 line)742mult_attn_out2, attn_weights_block2 = self.mha2(Q1, enc_output, enc_output, padding_mask, return_attention_scores=True) # (batch_size, target_seq_len, d_model)743744# apply layer normalization (layernorm2) to the sum of the attention output and the output of the first block (~1 line)745mult_attn_out2 = self.layernorm2(mult_attn_out2 + Q1) # (batch_size, target_seq_len, fully_connected_dim)746747#BLOCK 3748# pass the output of the second block through a ffn749ffn_output = self.ffn(mult_attn_out2) # (batch_size, target_seq_len, fully_connected_dim)750751# apply a dropout layer to the ffn output752ffn_output = self.dropout_ffn(ffn_output, training = training)753754# apply layer normalization (layernorm3) to the sum of the ffn output and the output of the second block755out3 = self.layernorm3(ffn_output + mult_attn_out2) # (batch_size, target_seq_len, fully_connected_dim)756# END CODE HERE757758return out3, attn_weights_block1, attn_weights_block2759760761762# In[ ]:763764765# UNIT TEST766DecoderLayer_test(DecoderLayer, create_look_ahead_mask)767768769# <a name='5-2'></a>770# ### 5.2 - Full Decoder771# You're almost there! Time to use your Decoder layer to build a full Transformer Decoder (Figure 3b). You will embedd your output and add positional encodings. You will then feed your encoded embeddings to a stack of Decoder layers.772#773#774# <img src="decoder.png" alt="Encoder" width="300"/>775# <caption><center><font color='purple'><b>Figure 3b: Transformer Decoder</font></center></caption>776#777# <a name='ex-7'></a>778# ### Exercise 7 - Decoder779#780# Implement `Decoder()` using the `call()` method to embed your output, add positional encoding, and implement multiple decoder layers781#782# In this exercise, you will initialize your Decoder with an Embedding layer, positional encoding, and multiple DecoderLayers. Your `call()` method will perform the following steps:783# 1. Pass your generated output through the Embedding layer.784# 2. Scale your embedding by multiplying it by the square root of your embedding dimension. Remember to cast the embedding dimension to data type `tf.float32` before computing the square root.785# 3. Add the position encoding: self.pos_encoding `[:, :seq_len, :]` to your embedding.786# 4. Pass the encoded embedding through a dropout layer, remembering to use the `training` parameter to set the model training mode.787# 5. Pass the output of the dropout layer through the stack of Decoding layers using a for loop.788789# In[ ]:790791792# UNQ_C7 (UNIQUE CELL IDENTIFIER, DO NOT EDIT)793# GRADED FUNCTION Decoder794class Decoder(tf.keras.layers.Layer):795"""796The entire Encoder is starts by passing the target input to an embedding layer797and using positional encoding to then pass the output through a stack of798decoder Layers799800"""801def __init__(self, num_layers, embedding_dim, num_heads, fully_connected_dim, target_vocab_size,802maximum_position_encoding, dropout_rate=0.1, layernorm_eps=1e-6):803super(Decoder, self).__init__()804805self.embedding_dim = embedding_dim806self.num_layers = num_layers807808self.embedding = Embedding(target_vocab_size, self.embedding_dim)809self.pos_encoding = positional_encoding(maximum_position_encoding, self.embedding_dim)810811self.dec_layers = [DecoderLayer(embedding_dim=self.embedding_dim,812num_heads=num_heads,813fully_connected_dim=fully_connected_dim,814dropout_rate=dropout_rate,815layernorm_eps=layernorm_eps)816for _ in range(self.num_layers)]817self.dropout = Dropout(dropout_rate)818819def call(self, x, enc_output, training,820look_ahead_mask, padding_mask):821"""822Forward pass for the Decoder823824Arguments:825x -- Tensor of shape (batch_size, target_seq_len, fully_connected_dim)826enc_output -- Tensor of shape(batch_size, input_seq_len, fully_connected_dim)827training -- Boolean, set to true to activate828the training mode for dropout layers829look_ahead_mask -- Boolean mask for the target_input830padding_mask -- Boolean mask for the second multihead attention layer831Returns:832x -- Tensor of shape (batch_size, target_seq_len, fully_connected_dim)833attention_weights - Dictionary of tensors containing all the attention weights834each of shape Tensor of shape (batch_size, num_heads, target_seq_len, input_seq_len)835"""836837seq_len = tf.shape(x)[1]838attention_weights = {}839840# START CODE HERE841# create word embeddings842x = self.embedding(x) # (batch_size, target_seq_len, fully_connected_dim)843844# scale embeddings by multiplying by the square root of their dimension845x *= tf.math.sqrt(tf.cast(self.embedding_dim, tf.float32))846847# calculate positional encodings and add to word embedding848x += self.pos_encoding[:, :seq_len, :]849850# apply a dropout layer to x851x = self.dropout(x, training = training)852853# use a for loop to pass x through a stack of decoder layers and update attention_weights (~4 lines total)854for i in range(self.num_layers):855# pass x and the encoder output through a stack of decoder layers and save the attention weights856# of block 1 and 2 (~1 line)857x, block1, block2 = self.dec_layers[i](x, enc_output, training,858look_ahead_mask, padding_mask)859860#update attention_weights dictionary with the attention weights of block 1 and block 2861attention_weights['decoder_layer{}_block1_self_att'.format(i+1)] = block1862attention_weights['decoder_layer{}_block2_decenc_att'.format(i+1)] = block2863# END CODE HERE864865866# x.shape == (batch_size, target_seq_len, fully_connected_dim)867return x, attention_weights868869870# In[ ]:871872873# UNIT TEST874Decoder_test(Decoder, create_look_ahead_mask, create_padding_mask)875876877# <a name='6'></a>878# ## 6 - Transformer879#880# Phew! This has been quite the assignment, and now you've made it to your last exercise of the Deep Learning Specialization. Congratulations! You've done all the hard work, now it's time to put it all together.881#882# <img src="transformer.png" alt="Transformer" width="550"/>883# <caption><center><font color='purple'><b>Figure 4: Transformer</font></center></caption>884#885# The flow of data through the Transformer Architecture is as follows:886# * First your input passes through an Encoder, which is just repeated Encoder layers that you implemented:887# - embedding and positional encoding of your input888# - multi-head attention on your input889# - feed forward neural network to help detect features890# * Then the predicted output passes through a Decoder, consisting of the decoder layers that you implemented:891# - embedding and positional encoding of the output892# - multi-head attention on your generated output893# - multi-head attention with the Q from the first multi-head attention layer and the K and V from the Encoder894# - a feed forward neural network to help detect features895# * Finally, after the Nth Decoder layer, two dense layers and a softmax are applied to generate prediction for the next output in your sequence.896#897# <a name='ex-8'></a>898# ### Exercise 8 - Transformer899#900# Implement `Transformer()` using the `call()` method901# 1. Pass the input through the Encoder with the appropiate mask.902# 2. Pass the encoder output and the target through the Decoder with the appropiate mask.903# 3. Apply a linear transformation and a softmax to get a prediction.904905# In[ ]:906907908# UNQ_C8 (UNIQUE CELL IDENTIFIER, DO NOT EDIT)909# GRADED FUNCTION Transformer910class Transformer(tf.keras.Model):911"""912Complete transformer with an Encoder and a Decoder913"""914def __init__(self, num_layers, embedding_dim, num_heads, fully_connected_dim, input_vocab_size,915target_vocab_size, max_positional_encoding_input,916max_positional_encoding_target, dropout_rate=0.1, layernorm_eps=1e-6):917super(Transformer, self).__init__()918919self.encoder = Encoder(num_layers=num_layers,920embedding_dim=embedding_dim,921num_heads=num_heads,922fully_connected_dim=fully_connected_dim,923input_vocab_size=input_vocab_size,924maximum_position_encoding=max_positional_encoding_input,925dropout_rate=dropout_rate,926layernorm_eps=layernorm_eps)927928self.decoder = Decoder(num_layers=num_layers,929embedding_dim=embedding_dim,930num_heads=num_heads,931fully_connected_dim=fully_connected_dim,932target_vocab_size=target_vocab_size,933maximum_position_encoding=max_positional_encoding_target,934dropout_rate=dropout_rate,935layernorm_eps=layernorm_eps)936937self.final_layer = Dense(target_vocab_size, activation='softmax')938939def call(self, input_sentence, output_sentence, training, enc_padding_mask, look_ahead_mask, dec_padding_mask):940"""941Forward pass for the entire Transformer942Arguments:943input_sentence -- Tensor of shape (batch_size, input_seq_len, fully_connected_dim)944An array of the indexes of the words in the input sentence945output_sentence -- Tensor of shape (batch_size, target_seq_len, fully_connected_dim)946An array of the indexes of the words in the output sentence947training -- Boolean, set to true to activate948the training mode for dropout layers949enc_padding_mask -- Boolean mask to ensure that the padding is not950treated as part of the input951look_ahead_mask -- Boolean mask for the target_input952dec_padding_mask -- Boolean mask for the second multihead attention layer953Returns:954final_output -- Describe me955attention_weights - Dictionary of tensors containing all the attention weights for the decoder956each of shape Tensor of shape (batch_size, num_heads, target_seq_len, input_seq_len)957958"""959# START CODE HERE960# call self.encoder with the appropriate arguments to get the encoder output961enc_output = self.encoder(input_sentence, training, enc_padding_mask) # (batch_size, inp_seq_len, fully_connected_dim)962963# call self.decoder with the appropriate arguments to get the decoder output964# dec_output.shape == (batch_size, tar_seq_len, fully_connected_dim)965dec_output, attention_weights = self.decoder(output_sentence, enc_output, training, look_ahead_mask, dec_padding_mask)966967# pass decoder output through a linear layer and softmax (~2 lines)968final_output = self.final_layer(dec_output) # (batch_size, tar_seq_len, target_vocab_size)969# START CODE HERE970971return final_output, attention_weights972973974# In[ ]:975976977# UNIT TEST978Transformer_test(Transformer, create_look_ahead_mask, create_padding_mask)979980981# ## Conclusion982#983# You've come to the end of the graded portion of the assignment. By now, you've:984#985# * Create positional encodings to capture sequential relationships in data986# * Calculate scaled dot-product self-attention with word embeddings987# * Implement masked multi-head attention988# * Build and train a Transformer model989990# <font color='blue'>991# <b>What you should remember</b>:992#993# - The combination of self-attention and convolutional network layers allows of parallization of training and *faster training*.994# - Self-attention is calculated using the generated query Q, key K, and value V matrices.995# - Adding positional encoding to word embeddings is an effective way of include sequence information in self-attention calculations.996# - Multi-head attention can help detect multiple features in your sentence.997# - Masking stops the model from 'looking ahead' during training, or weighting zeroes too much when processing cropped sentences.998999# Now that you have completed the Transformer assignment, make sure you check out the ungraded labs to apply the Transformer model to practical use cases such as Name Entity Recogntion (NER) and Question Answering (QA).1000#1001#1002# # Congratulations on finishing the Deep Learning Specialization!!!!!! 🎉🎉🎉🎉🎉1003#1004# This was the last graded assignment of the specialization. It is now time to celebrate all your hard work and dedication!1005#1006# <a name='7'></a>1007# ## 7 - References1008#1009# The Transformer algorithm was due to Vaswani et al. (2017).1010#1011# - Ashish Vaswani, Noam Shazeer, Niki Parmar, Jakob Uszkoreit, Llion Jones, Aidan N. Gomez, Lukasz Kaiser, Illia Polosukhin (2017). [Attention Is All You Need](https://arxiv.org/abs/1706.03762)10121013# In[ ]:1014101510161017101810191020