Daniel Voigt Godoy - Deep Learning with PyTorch Step-by-Step A Beginner’s Guide-leanpub
"Why would I want to force it to do that?"Padding comes to mind—you likely don’t want to pay attention to stuffed datapoints in a sequence, right? Let’s try out an example. Pretend we have a sourcesequence with one real and one padded data point, and that it went through anencoder to generate the corresponding "keys":source_seq = torch.tensor([[[-1., 1.], [0., 0.]]])# pretend there's an encoder here...keys = torch.tensor([[[-.38, .44], [.85, -.05]]])query = torch.tensor([[[-1., 1.]]])The source mask should be False for every padded data point,and its shape should be (N, 1, L), where L is the length of thesource sequence.source_mask = (source_seq != 0).all(axis=2).unsqueeze(1)source_mask # N, 1, LOutputtensor([[[ True, False]]])The mask will make the attention score equal to zero for the padded data points.If we use the "keys" we’ve just made up to initialize an instance of the attentionmechanism and call it using the source mask above, we’ll see the following result:torch.manual_seed(11)attnh = Attention(2)attnh.init_keys(keys)context = attnh(query, mask=source_mask)attnh.alphasOutputtensor([[[1., 0.]]])Attention | 727
The attention score of the second data point, as expected, was set to zero, leavingthe whole attention on the first data point.DecoderWe also need to make some small adjustments to the decoder:Decoder + Attention1 class DecoderAttn(nn.Module):2 def __init__(self, n_features, hidden_dim):3 super().__init__()4 self.hidden_dim = hidden_dim5 self.n_features = n_features6 self.hidden = None7 self.basic_rnn = nn.GRU(self.n_features,8 self.hidden_dim,9 batch_first=True)10 self.attn = Attention(self.hidden_dim) 111 self.regression = nn.Linear(2 * self.hidden_dim,12 self.n_features) 11314 def init_hidden(self, hidden_seq):15 # the output of the encoder is N, L, H16 # and init_keys expects batch-first as well17 self.attn.init_keys(hidden_seq) 218 hidden_final = hidden_seq[:, -1:]19 self.hidden = hidden_final.permute(1, 0, 2) # L, N, H2021 def forward(self, X, mask=None):22 # X is N, 1, F23 batch_first_output, self.hidden = \24 self.basic_rnn(X, self.hidden)25 query = batch_first_output[:, -1:]26 # Attention27 context = self.attn(query, mask=mask) 328 concatenated = torch.cat([context, query],29 axis=-1) 330 out = self.regression(concatenated)3132 # N, 1, F33 return out.view(-1, 1, self.n_features)728 | Chapter 9 — Part I: Sequence-to-Sequence
- Page 702 and 703: Model Configuration1 torch.manual_s
- Page 704 and 705: We can actually find an expression
- Page 706 and 707: Data Preparation1 def pack_collate(
- Page 708 and 709: and variable-length sequences.Model
- Page 710 and 711: • generating variable-length sequ
- Page 712 and 713: import copyimport numpy as npimport
- Page 714 and 715: Figure 9.3 - Sequence datasetThe co
- Page 716 and 717: coordinates of a "perfect" square a
- Page 718 and 719: Let’s pretend for a moment that t
- Page 720 and 721: to initialize the hidden state and
- Page 722 and 723: predictions in previous steps have
- Page 724 and 725: the second set of predicted coordin
- Page 726 and 727: Let’s create an instance of the m
- Page 728 and 729: Model Configuration & TrainingThe m
- Page 730 and 731: Sure, we can!AttentionHere is a (no
- Page 732 and 733: based on "the" and "zone," I’ve j
- Page 734 and 735: Figure 9.12 - Matching a query to t
- Page 736 and 737: Outputtensor([[[ 0.0832, -0.0356],[
- Page 738 and 739: utmost importance for the correct i
- Page 740 and 741: Its formula is:Equation 9.3 - Cosin
- Page 742 and 743: second hidden state contributes to
- Page 744 and 745: Outputtensor([[[ 0.5475, 0.0875, -1
- Page 746 and 747: alphas = F.softmax(scaled_products,
- Page 748 and 749: Outputtensor([[[ 0.2138, -0.3175]]]
- Page 750 and 751: Attention Mechanism1 class Attentio
- Page 754 and 755: 1 Sets attention module and adjusts
- Page 756 and 757: encdec = EncoderDecoder(encoder, de
- Page 758 and 759: fig = sbs_seq_attn.plot_losses()Fig
- Page 760 and 761: Figure 9.20 - Attention scoresSee?
- Page 762 and 763: Wide vs Narrow AttentionThis mechan
- Page 764 and 765: "What’s so special about it?"Even
- Page 766 and 767: Once again, the affine transformati
- Page 768 and 769: Next, we shift our focus to the sel
- Page 770 and 771: Encoder + Self-Attention1 class Enc
- Page 772 and 773: Figure 9.27 - Encoder with self- an
- Page 774 and 775: The figure below depicts the self-a
- Page 776 and 777: shifted_seq = torch.cat([source_seq
- Page 778 and 779: Equation 9.17 - Decoder’s (masked
- Page 780 and 781: At evaluation / prediction time we
- Page 782 and 783: Outputtensor([[[0.4132, 0.3728],[0.
- Page 784 and 785: Figure 9.33 - Encoder + decoder + a
- Page 786 and 787: 64 return outputsThe encoder-decode
- Page 788 and 789: Figure 9.34 - Losses—encoder + de
- Page 790 and 791: curse. On the one hand, it makes co
- Page 792 and 793: "Are we done now? Is this good enou
- Page 794 and 795: Figure 9.46 - Consistent distancesA
- Page 796 and 797: Let’s recap what we’ve already
- Page 798 and 799: Let’s see it in code:max_len = 10
- Page 800 and 801: Let’s put it all together into a
The attention score of the second data point, as expected, was set to zero, leaving
the whole attention on the first data point.
Decoder
We also need to make some small adjustments to the decoder:
Decoder + Attention
1 class DecoderAttn(nn.Module):
2 def __init__(self, n_features, hidden_dim):
3 super().__init__()
4 self.hidden_dim = hidden_dim
5 self.n_features = n_features
6 self.hidden = None
7 self.basic_rnn = nn.GRU(self.n_features,
8 self.hidden_dim,
9 batch_first=True)
10 self.attn = Attention(self.hidden_dim) 1
11 self.regression = nn.Linear(2 * self.hidden_dim,
12 self.n_features) 1
13
14 def init_hidden(self, hidden_seq):
15 # the output of the encoder is N, L, H
16 # and init_keys expects batch-first as well
17 self.attn.init_keys(hidden_seq) 2
18 hidden_final = hidden_seq[:, -1:]
19 self.hidden = hidden_final.permute(1, 0, 2) # L, N, H
20
21 def forward(self, X, mask=None):
22 # X is N, 1, F
23 batch_first_output, self.hidden = \
24 self.basic_rnn(X, self.hidden)
25 query = batch_first_output[:, -1:]
26 # Attention
27 context = self.attn(query, mask=mask) 3
28 concatenated = torch.cat([context, query],
29 axis=-1) 3
30 out = self.regression(concatenated)
31
32 # N, 1, F
33 return out.view(-1, 1, self.n_features)
728 | Chapter 9 — Part I: Sequence-to-Sequence