Update.
[mygpt.git] / mygpt.py
1 #!/usr/bin/env python
2
3 # Any copyright is dedicated to the Public Domain.
4 # https://creativecommons.org/publicdomain/zero/1.0/
5
6 # Written by Francois Fleuret <francois@fleuret.org>
7
8 import math
9
10 import torch
11
12 from torch import nn
13 from torch.nn import functional as F
14
15 ##############################
16
17 class Residual(nn.Module):
18     def __init__(self, *f):
19         super().__init__()
20         self.f = f[0] if len(f) == 1 else nn.Sequential(*f)
21
22     def forward(self, x):
23         return x + self.f(x)
24
25 ##############################
26
27 class PositionalEncoding(nn.Module):
28     def __init__(self, len_max):
29         super().__init__()
30         self.len_max = len_max
31
32     # From Vaswani et al 2018
33     # PE_{t,2i}   = sin(t/(L^{2i/D}))
34     # PE_{t,2i+1} = cos(t/(L^{2i/D}))
35     def forward(self, x):
36         t = torch.arange(x.size(1), dtype = x.dtype, device = x.device)[:, None]
37         j = torch.arange(x.size(2), dtype = x.dtype, device = x.device)[None, :]
38         k = j%2
39         return x + torch.sin(t / (self.len_max ** ((j - k) / x.size(2))) + math.pi/2 * k)[None, :, :]
40
41 ##############################
42
43 class QKVAttention(nn.Module):
44     def __init__(self, dim_in, dim_qk, dim_v,
45                  nb_heads = 1, causal = False, attention_dropout = 0.0):
46         super().__init__()
47
48         def randw(*d):
49             return nn.Parameter(torch.empty(*d).normal_(0, 1 / math.sqrt(d[-1])))
50
51         self.w_q = randw(nb_heads, dim_qk, dim_in)
52         self.w_k = randw(nb_heads, dim_qk, dim_in)
53         self.w_v = randw(nb_heads, dim_v, dim_in)
54         self.w_o = randw(nb_heads, dim_in, dim_v)
55         self.causal = causal
56         self.attention_dropout = attention_dropout
57
58     def forward(self, x_q, x_kv = None):
59         if x_kv is None: x_kv = x_q
60         q = torch.einsum('ntc,hdc->nhtd', x_q, self.w_q)
61         k = torch.einsum('ntc,hdc->nhtd', x_kv, self.w_k)
62         v = torch.einsum('ntc,hdc->nhtd', x_kv, self.w_v)
63         a = torch.einsum('nhtd,nhsd->nhts', q, k) / math.sqrt(q.size(3))
64         if self.causal:
65             mask = torch.arange(a.size(2), device = q.device)[None, None, :, None] \
66                    < torch.arange(a.size(3), device = q.device)[None, None, None, :]
67             a = a.masked_fill(mask, float('-inf'))
68         a = a.softmax(dim = 3)
69         a = F.dropout(a, self.attention_dropout, self.training)
70         y = torch.einsum('nhts,nhsd->nhtd', a, v)
71         y = torch.einsum('nhtd,hcd->ntc', y, self.w_o)
72
73         return y
74
75 ##############################
76
77 class MyGPT(nn.Module):
78     def __init__(self,
79                  vocabulary_size,
80                  dim_model, dim_keys, dim_hidden,
81                  nb_heads, nb_blocks, dropout = 0.):
82
83         super().__init__()
84
85         assert dim_model % nb_heads == 0
86
87         self.embedding = nn.Sequential(
88             nn.Embedding(vocabulary_size, dim_model),
89             nn.Dropout(dropout),
90             PositionalEncoding(len_max = 1e5),
91         )
92
93         trunk_blocks = [ ]
94
95         for _ in range(nb_blocks):
96             trunk_blocks += [
97                 Residual(
98                     nn.LayerNorm(dim_model),
99                     QKVAttention(
100                         dim_in = dim_model,
101                         dim_qk = dim_keys, dim_v = dim_model // nb_heads,
102                         nb_heads = nb_heads,
103                         causal = True, attention_dropout = dropout
104                     ),
105                     nn.Linear(in_features = dim_model, out_features = dim_model),
106                 ),
107                 Residual(
108                     nn.LayerNorm(dim_model),
109                     nn.Linear(in_features = dim_model, out_features = dim_hidden),
110                     nn.ReLU(),
111                     nn.Linear(in_features = dim_hidden, out_features = dim_model),
112                     nn.Dropout(dropout),
113                 ),
114             ]
115
116         self.trunk = nn.Sequential(*trunk_blocks)
117
118         self.readout = nn.Linear(in_features = dim_model, out_features = vocabulary_size)
119
120     def forward(self, x):
121         x = self.embedding(x)
122         x = self.trunk(x)
123         x = self.readout(x)
124         return x
125
126 ######################################################################
127
128 if __name__ == '__main__':
129     print('Basic check.')
130
131     vocabulary_size = 10
132     x = torch.randint(vocabulary_size, (25, 100))
133
134     model = MyGPT(
135         vocabulary_size = vocabulary_size,
136         dim_model = 16, dim_keys = 50, dim_hidden = 100,
137         nb_heads = 2, nb_blocks = 3,
138         dropout = 0.1
139     )
140
141     y = model(x)
142
143 ######################################################################