3 # Any copyright is dedicated to the Public Domain.
4 # https://creativecommons.org/publicdomain/zero/1.0/
6 # Written by Francois Fleuret <francois@fleuret.org>
13 from torch.nn import functional as F
15 ######################################################################
18 class WithResidual(nn.Module):
19 def __init__(self, *f):
21 self.f = f[0] if len(f) == 1 else nn.Sequential(*f)
23 def forward(self, bs):
24 bs.x = bs.x + self.f(bs).x
28 ######################################################################
30 # A BracketedSequence is a BxTx... tensor with a first and a nb time
33 # Modules able to process it expect that they will have to process a
34 # first bracket starting at t=0, followed by a succession of brackets
35 # that move forward in time, do not overlap, and cover the axis T with
38 # Although it is more general, for a classical prompt-conditioned
39 # auto-regressive process it will be a first bracket starting at 0 and
40 # of arbitrary length for the "prompt", followed by brackets of length
41 # 1 for the successive tokens.
43 # Modules able to process brackets may implement a cache that is
44 # resetted when the input bracket starts at t=0
47 class BracketedSequence:
48 def __init__(self, x, first=None, nb=None):
50 self.first = 0 if first is None else first
51 self.nb = x.size(1) if nb is None else nb
54 return self.x[:, self.first : self.first + self.nb]
57 ######################################################################
60 class CacheWrapper(nn.Module):
61 def __init__(self, *f):
63 self.f = f[0] if len(f) == 1 else nn.Sequential(*f)
65 def forward(self, bs):
67 y = self.f(bs.slice())
68 self.cache_y = y.new(*((y.size(0), bs.x.size(1)) + y.size()[2:]))
69 self.cache_y[:, bs.first : bs.first + bs.nb] = y
71 self.cache_y[:, bs.first : bs.first + bs.nb] = self.f(bs.slice())
78 ##############################
81 class AddPositionalEncoding(nn.Module):
82 def __init__(self, len_max):
84 self.len_max = len_max
86 # [Vaswani et al 2018] PE_{t,2i} = sin(t/(L^{2i/D})), PE_{t,2i+1} = cos(t/(L^{2i/D}))
88 def forward(self, bs):
90 t = torch.arange(bs.x.size(1), dtype=bs.x.dtype, device=bs.x.device)[
93 j = torch.arange(bs.x.size(2), dtype=bs.x.dtype, device=bs.x.device)[
98 t / (self.len_max ** ((j - k) / bs.x.size(2))) + math.pi / 2 * k
100 self.cache_y = bs.x.new(bs.x.size())
102 self.cache_y[:, bs.first : bs.first + bs.nb] = (
103 bs.slice() + self.pe[bs.first : bs.first + bs.nb]
111 ##############################
114 class QKVAttention(nn.Module):
116 self, dim_in, dim_qk, dim_v, nb_heads=1, causal=False, attention_dropout=0.0
121 return nn.Parameter(torch.randn(*d) / math.sqrt(d[-1]))
124 self.attention_dropout = attention_dropout
126 self.w_q = randw(nb_heads, dim_qk, dim_in)
127 self.w_k = randw(nb_heads, dim_qk, dim_in)
128 self.w_v = randw(nb_heads, dim_v, dim_in)
129 self.w_o = randw(dim_v * nb_heads, dim_in)
131 def forward(self, bs_q, x_kv=None):
137 self.cache_k = x_q.new_zeros(
138 x_q.size(0), self.w_k.size(0), x_kv.size(1), self.w_k.size(1)
140 self.cache_v = x_q.new_zeros(
141 x_q.size(0), self.w_v.size(0), x_kv.size(1), self.w_v.size(1)
143 self.cache_y = x_q.new_zeros(x_q.size(0), x_q.size(1), self.w_o.size(1))
146 "ntc,hdc->nhtd", x_q[:, bs_q.first : bs_q.first + bs_q.nb], self.w_q
148 self.cache_k[:, :, bs_q.first : bs_q.first + bs_q.nb] = torch.einsum(
149 "ntc,hdc->nhtd", x_kv[:, bs_q.first : bs_q.first + bs_q.nb], self.w_k
151 self.cache_v[:, :, bs_q.first : bs_q.first + bs_q.nb] = torch.einsum(
152 "ntc,hdc->nhtd", x_kv[:, bs_q.first : bs_q.first + bs_q.nb], self.w_v
156 "nhtd,nhsd->nhts", q, self.cache_k[:, :, : bs_q.first + bs_q.nb]
157 ) / math.sqrt(self.w_q.size(1))
161 self.cache_attzero = (
162 torch.arange(x_q.size(1), device=q.device)[None, None, :, None]
163 < torch.arange(x_kv.size(1), device=q.device)[None, None, None, :]
167 :, :, bs_q.first : bs_q.first + bs_q.nb, : bs_q.first + bs_q.nb
173 a = F.dropout(a, self.attention_dropout, self.training)
176 "nhts,nhsd->nthd", a, self.cache_v[:, :, : bs_q.first + bs_q.nb]
179 self.cache_y[:, bs_q.first : bs_q.first + bs_q.nb] = y @ self.w_o
181 bs_q.x = self.cache_y
186 ##############################
189 class MyGPT(nn.Module):
205 assert dim_model % nb_heads == 0
207 self.embedding = nn.Sequential(
208 CacheWrapper(nn.Embedding(vocabulary_size, dim_model), nn.Dropout(dropout)),
209 AddPositionalEncoding(len_max),
214 for b in range(nb_blocks):
217 CacheWrapper(nn.LayerNorm((dim_model,))),
221 dim_v=dim_model // nb_heads,
224 attention_dropout=dropout,
229 nn.LayerNorm((dim_model,)),
230 nn.Linear(in_features=dim_model, out_features=dim_hidden),
232 nn.Linear(in_features=dim_hidden, out_features=dim_model),
238 self.trunk = nn.Sequential(*trunk_blocks)
240 self.readout = CacheWrapper(
241 nn.Linear(in_features=dim_model, out_features=vocabulary_size)
244 with torch.no_grad():
245 for m in self.modules():
246 if isinstance(m, nn.Embedding):
247 m.weight.normal_(mean=0, std=2e-2)
248 elif isinstance(m, nn.LayerNorm):
252 def forward(self, bs):
253 bs.x = F.pad(bs.x, (1, -1))
254 bs = self.embedding(bs)
256 bs = self.readout(bs)
260 ######################################################################
262 if __name__ == "__main__":
264 print("Basic check.")
267 x = torch.randint(vocabulary_size, (9, 7))
270 vocabulary_size=vocabulary_size,
281 y1 = model(BracketedSequence(x)).x
283 y2 = torch.randn_like(y1)
284 for s in range(x.size(1)):
285 z = model(BracketedSequence(x, s, 1))
288 # print(y1.max(dim = 2).values)
289 # print(y2.max(dim = 2).values)
290 print(f"error={((y1 - y2).norm() / (y1.norm() + y2.norm())).item()}")
292 ######################################################################