Daniel Voigt Godoy - Deep Learning with PyTorch Step-by-Step A Beginner’s Guide-leanpub
Outputtensor([[[ 1.4636, 2.3663],[ 1.9806, -0.7564]]])Next, we normalize it:norm = nn.LayerNorm(2)norm(source_seq_enc)Outputtensor([[[-1.0000, 1.0000],[ 1.0000, -1.0000]]], grad_fn=<NativeLayerNormBackward>)"Wait, what happened here?"That’s what happens when one tries to normalize two features only: They becomeeither minus one or one. Even worse, it will be the same for every data point. Thesevalues won’t get us anywhere, that’s for sure.We need to do better, we need…Projections or EmbeddingsSometimes projections and embeddings are usedinterchangeably. Here, though, we’re sticking with embeddingsfor categorical values and projections for numerical values.In Chapter 11, we’ll be using embeddings to get a numerical representation (avector) for a given word or token. Since words or tokens are categorical values,the embedding layer works like a large lookup table: It will look up a given word ortoken in its keys and return the corresponding tensor. But, since we’re dealing withcoordinates, that is, numerical values, we are using projections instead. A simplelinear layer is all that it takes to project our pair of coordinates into a higherdimensionalfeature space:Layer Normalization | 829
torch.manual_seed(11)proj_dim = 6linear_proj = nn.Linear(2, proj_dim)pe = PositionalEncoding(2, proj_dim)source_seq_proj = linear_proj(source_seq)source_seq_proj_enc = pe(source_seq_proj)source_seq_proj_encOutputtensor([[[-2.0934, 1.5040, 1.8742, 0.0628, 0.3034, 2.0190],[-0.8853, 2.8213, 0.5911, 2.4193, -2.5230, 0.3599]]],grad_fn=<AddBackward0>)See? Now each data point in our source sequence has six features (the projecteddimensions), and they are positionally-encoded too. Sure, this particular projectionis totally random, but that won’t be the case once we add the corresponding linearlayer to our model. It will learn a meaningful projection that, after beingpositionally-encoded, will be normalized:norm = nn.LayerNorm(proj_dim)norm(source_seq_proj_enc)Outputtensor([[[-1.9061, 0.6287, 0.8896, -0.3868, -0.2172, 0.9917],[-0.7362, 1.2864, 0.0694, 1.0670, -1.6299, -0.0568]]],grad_fn=<NativeLayerNormBackward>)Problem solved! Finally, we have everything we need to build a full-blownTransformer!In Chapter 9, we used affine transformations inside the attentionheads to map from input dimensions to hidden (or model)dimensions. Now, this change in dimensionality is beingperformed using projections directly on the input sequencesbefore they are passed to the encoder and the decoder.830 | Chapter 10: Transform and Roll Out
- Page 804 and 805: Decoder with Positional Encoding1 c
- Page 806 and 807: Visualizing PredictionsLet’s plot
- Page 808 and 809: Next, we’re moving on to the thre
- Page 810 and 811: Data Generation & Preparation1 # Tr
- Page 812 and 813: 59 self.trg_masks)60 else:61 # Deco
- Page 814 and 815: Model Configuration1 class EncoderS
- Page 816 and 817: 1617 @property18 def alphas(self):1
- Page 818 and 819: Output(0.016193246061448008, 0.0341
- Page 820 and 821: sequential order of the data• fig
- Page 822 and 823: following imports:import copyimport
- Page 824 and 825: Figure 10.2 - Chunking: the wrong a
- Page 826 and 827: chunks to compute the other half of
- Page 828 and 829: 67 # N, L, n_heads, d_k68 context =
- Page 830 and 831: dummy_points = torch.randn(16, 2, 4
- Page 832 and 833: Stacking Encoders and DecodersLet
- Page 834 and 835: "… with great depth comes great c
- Page 836 and 837: Transformer EncoderWe’ll be repre
- Page 838 and 839: Let’s see it in code, starting wi
- Page 840 and 841: Transformer Encoder1 class EncoderT
- Page 842 and 843: of the encoder-decoder (or Transfor
- Page 844 and 845: In PyTorch, the decoder "layer" is
- Page 846 and 847: In PyTorch, the decoder is implemen
- Page 848 and 849: Equation 10.7 - Data points' means
- Page 850 and 851: layer_norm = nn.LayerNorm(d_model)n
- Page 852 and 853: Figure 10.10 - Layer norm vs batch
- Page 856 and 857: The TransformerLet’s start with t
- Page 858 and 859: "values") in the decoder.• decode
- Page 860 and 861: Data Preparation1 # Generating trai
- Page 862 and 863: Figure 10.15 - Losses—Transformer
- Page 864 and 865: • First, and most important, PyTo
- Page 866 and 867: decode(), with a single one, encode
- Page 868 and 869: 46 for i in range(self.target_len):
- Page 870 and 871: Figure 10.18 - Losses - PyTorch’s
- Page 872 and 873: Figure 10.20 - Sample image—label
- Page 874 and 875: 4041 # Builds a weighted random sam
- Page 876 and 877: Figure 10.23 - Sample image—split
- Page 878 and 879: Einops"There is more than one way t
- Page 880 and 881: Figure 10.26 - Two patch embeddings
- Page 882 and 883: Now each sequence has ten elements,
- Page 884 and 885: It takes an instance of a Transform
- Page 886 and 887: Putting It All TogetherIn this chap
- Page 888 and 889: 1. Encoder-DecoderThe encoder-decod
- Page 890 and 891: This is the actual encoder-decoder
- Page 892 and 893: 3. DecoderThe Transformer decoder h
- Page 894 and 895: 5. Encoder "Layer"The encoder "laye
- Page 896 and 897: 7. "Sub-Layer" WrapperThe "sub-laye
- Page 898 and 899: 8. Multi-Headed AttentionThe multi-
- Page 900 and 901: Model Configuration & TrainingModel
- Page 902 and 903: • training the Transformer to tac
torch.manual_seed(11)
proj_dim = 6
linear_proj = nn.Linear(2, proj_dim)
pe = PositionalEncoding(2, proj_dim)
source_seq_proj = linear_proj(source_seq)
source_seq_proj_enc = pe(source_seq_proj)
source_seq_proj_enc
Output
tensor([[[-2.0934, 1.5040, 1.8742, 0.0628, 0.3034, 2.0190],
[-0.8853, 2.8213, 0.5911, 2.4193, -2.5230, 0.3599]]],
grad_fn=<AddBackward0>)
See? Now each data point in our source sequence has six features (the projected
dimensions), and they are positionally-encoded too. Sure, this particular projection
is totally random, but that won’t be the case once we add the corresponding linear
layer to our model. It will learn a meaningful projection that, after being
positionally-encoded, will be normalized:
norm = nn.LayerNorm(proj_dim)
norm(source_seq_proj_enc)
Output
tensor([[[-1.9061, 0.6287, 0.8896, -0.3868, -0.2172, 0.9917],
[-0.7362, 1.2864, 0.0694, 1.0670, -1.6299, -0.0568]]],
grad_fn=<NativeLayerNormBackward>)
Problem solved! Finally, we have everything we need to build a full-blown
Transformer!
In Chapter 9, we used affine transformations inside the attention
heads to map from input dimensions to hidden (or model)
dimensions. Now, this change in dimensionality is being
performed using projections directly on the input sequences
before they are passed to the encoder and the decoder.
830 | Chapter 10: Transform and Roll Out