Register
Login
Resources
Docs Blog Datasets Glossary Case Studies Tutorials & Webinars
Product
Data Engine LLMs Platform Enterprise
Pricing Explore
Connect to our Discord channel

transformer.py 22 KB

You have to be logged in to leave a comment. Sign In
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
  1. import copy
  2. import numbers
  3. from functools import partial
  4. from typing import Any, Callable, List, Optional, Tuple, Union
  5. import torch
  6. from torch import Tensor, nn
  7. from torch.nn import functional as F
  8. from .activation import MultiheadAttention
  9. from .scaling import ActivationBalancer, BalancedDoubleSwish
  10. from .scaling import BasicNorm as _BasicNorm
  11. _shape_t = Union[int, List[int], torch.Size]
  12. class LayerNorm(nn.Module):
  13. __constants__ = ["normalized_shape", "eps", "elementwise_affine"]
  14. normalized_shape: Tuple[int, ...]
  15. eps: float
  16. elementwise_affine: bool
  17. def __init__(
  18. self,
  19. normalized_shape: _shape_t,
  20. eps: float = 1e-5,
  21. elementwise_affine: bool = True,
  22. device=None,
  23. dtype=None,
  24. ) -> None:
  25. factory_kwargs = {"device": device, "dtype": dtype}
  26. super(LayerNorm, self).__init__()
  27. if isinstance(normalized_shape, numbers.Integral):
  28. # mypy error: incompatible types in assignment
  29. normalized_shape = (normalized_shape,) # type: ignore[assignment]
  30. self.normalized_shape = tuple(normalized_shape) # type: ignore[arg-type]
  31. self.eps = eps
  32. self.elementwise_affine = elementwise_affine
  33. if self.elementwise_affine:
  34. self.weight = nn.Parameter(
  35. torch.empty(self.normalized_shape, **factory_kwargs)
  36. )
  37. self.bias = nn.Parameter(
  38. torch.empty(self.normalized_shape, **factory_kwargs)
  39. )
  40. else:
  41. self.register_parameter("weight", None)
  42. self.register_parameter("bias", None)
  43. self.reset_parameters()
  44. def reset_parameters(self) -> None:
  45. if self.elementwise_affine:
  46. nn.init.ones_(self.weight)
  47. nn.init.zeros_(self.bias)
  48. def forward(self, input: Tensor, embedding: Any = None) -> Tensor:
  49. if isinstance(input, tuple):
  50. input, embedding = input
  51. return (
  52. F.layer_norm(
  53. input,
  54. self.normalized_shape,
  55. self.weight,
  56. self.bias,
  57. self.eps,
  58. ),
  59. embedding,
  60. )
  61. assert embedding is None
  62. return F.layer_norm(
  63. input, self.normalized_shape, self.weight, self.bias, self.eps
  64. )
  65. def extra_repr(self) -> str:
  66. return (
  67. "{normalized_shape}, eps={eps}, "
  68. "elementwise_affine={elementwise_affine}".format(**self.__dict__)
  69. )
  70. class AdaptiveLayerNorm(nn.Module):
  71. r"""Adaptive Layer Normalization"""
  72. def __init__(self, d_model, norm) -> None:
  73. super(AdaptiveLayerNorm, self).__init__()
  74. self.project_layer = nn.Linear(d_model, 2 * d_model)
  75. self.norm = norm
  76. self.d_model = d_model
  77. self.eps = self.norm.eps
  78. def forward(self, input: Tensor, embedding: Tensor = None) -> Tensor:
  79. if isinstance(input, tuple):
  80. input, embedding = input
  81. weight, bias = torch.split(
  82. self.project_layer(embedding),
  83. split_size_or_sections=self.d_model,
  84. dim=-1,
  85. )
  86. return (weight * self.norm(input) + bias, embedding)
  87. weight, bias = torch.split(
  88. self.project_layer(embedding),
  89. split_size_or_sections=self.d_model,
  90. dim=-1,
  91. )
  92. return weight * self.norm(input) + bias
  93. class BasicNorm(_BasicNorm):
  94. def __init__(
  95. self,
  96. d_model: int,
  97. eps: float = 1e-5,
  98. device=None,
  99. dtype=None,
  100. ):
  101. super(BasicNorm, self).__init__(d_model, eps=eps)
  102. def forward(self, input: Tensor, embedding: Any = None) -> Tensor:
  103. if isinstance(input, tuple):
  104. input, embedding = input
  105. return (
  106. super(BasicNorm, self).forward(input),
  107. embedding,
  108. )
  109. assert embedding is None
  110. return super(BasicNorm, self).forward(input)
  111. class BalancedBasicNorm(nn.Module):
  112. def __init__(
  113. self,
  114. d_model: int,
  115. eps: float = 1e-5,
  116. device=None,
  117. dtype=None,
  118. ):
  119. super(BalancedBasicNorm, self).__init__()
  120. self.balancer = ActivationBalancer(
  121. d_model,
  122. channel_dim=-1,
  123. min_positive=0.45,
  124. max_positive=0.55,
  125. max_abs=6.0,
  126. )
  127. self.norm = BasicNorm(d_model, eps, device=device, dtype=dtype)
  128. def forward(self, input: Tensor, embedding: Any = None) -> Tensor:
  129. if isinstance(input, tuple):
  130. input, embedding = input
  131. return self.norm((self.balancer(input), embedding))
  132. assert embedding is None
  133. return self.norm(self.balancer(input))
  134. class IdentityNorm(nn.Module):
  135. def __init__(
  136. self,
  137. d_model: int,
  138. eps: float = 1e-5,
  139. device=None,
  140. dtype=None,
  141. ) -> None:
  142. super(IdentityNorm, self).__init__()
  143. def forward(self, input: Tensor, embedding: Any = None) -> Tensor:
  144. if isinstance(input, tuple):
  145. return input
  146. assert embedding is None
  147. return input
  148. class TransformerEncoderLayer(nn.Module):
  149. __constants__ = ["batch_first", "norm_first"]
  150. def __init__(
  151. self,
  152. d_model: int,
  153. nhead: int,
  154. dim_feedforward: int = 2048,
  155. dropout: float = 0.1,
  156. activation: Union[str, Callable[[Tensor], Tensor]] = F.relu,
  157. batch_first: bool = False,
  158. norm_first: bool = False,
  159. device=None,
  160. dtype=None,
  161. linear1_self_attention_cls: nn.Module = nn.Linear,
  162. linear2_self_attention_cls: nn.Module = nn.Linear,
  163. linear1_feedforward_cls: nn.Module = nn.Linear,
  164. linear2_feedforward_cls: nn.Module = nn.Linear,
  165. layer_norm_cls: nn.Module = LayerNorm,
  166. layer_norm_eps: float = 1e-5,
  167. adaptive_layer_norm=False,
  168. ) -> None:
  169. factory_kwargs = {"device": device, "dtype": dtype}
  170. super(TransformerEncoderLayer, self).__init__()
  171. self.self_attn = MultiheadAttention(
  172. d_model,
  173. nhead,
  174. dropout=dropout,
  175. batch_first=batch_first,
  176. linear1_cls=linear1_self_attention_cls,
  177. linear2_cls=linear2_self_attention_cls,
  178. **factory_kwargs,
  179. )
  180. # Implementation of Feedforward model
  181. self.linear1 = linear1_feedforward_cls(
  182. d_model, dim_feedforward, **factory_kwargs
  183. )
  184. self.dropout = nn.Dropout(dropout)
  185. self.linear2 = linear2_feedforward_cls(
  186. dim_feedforward, d_model, **factory_kwargs
  187. )
  188. self.norm_first = norm_first
  189. self.dropout1 = nn.Dropout(dropout)
  190. self.dropout2 = nn.Dropout(dropout)
  191. # Legacy string support for activation function.
  192. if isinstance(activation, str):
  193. activation = _get_activation_fn(activation)
  194. elif isinstance(activation, partial):
  195. activation = activation(d_model)
  196. elif activation == BalancedDoubleSwish:
  197. activation = BalancedDoubleSwish(d_model)
  198. # # We can't test self.activation in forward() in TorchScript,
  199. # # so stash some information about it instead.
  200. # if activation is F.relu or isinstance(activation, torch.nn.ReLU):
  201. # self.activation_relu_or_gelu = 1
  202. # elif activation is F.gelu or isinstance(activation, torch.nn.GELU):
  203. # self.activation_relu_or_gelu = 2
  204. # else:
  205. # self.activation_relu_or_gelu = 0
  206. self.activation = activation
  207. norm1 = layer_norm_cls(d_model, eps=layer_norm_eps, **factory_kwargs)
  208. if layer_norm_cls == IdentityNorm:
  209. norm2 = BalancedBasicNorm(
  210. d_model, eps=layer_norm_eps, **factory_kwargs
  211. )
  212. else:
  213. norm2 = layer_norm_cls(
  214. d_model, eps=layer_norm_eps, **factory_kwargs
  215. )
  216. if adaptive_layer_norm:
  217. self.norm1 = AdaptiveLayerNorm(d_model, norm1)
  218. self.norm2 = AdaptiveLayerNorm(d_model, norm2)
  219. else:
  220. self.norm1 = norm1
  221. self.norm2 = norm2
  222. def __setstate__(self, state):
  223. super(TransformerEncoderLayer, self).__setstate__(state)
  224. if not hasattr(self, "activation"):
  225. self.activation = F.relu
  226. def forward(
  227. self,
  228. src: Tensor,
  229. src_mask: Optional[Tensor] = None,
  230. src_key_padding_mask: Optional[Tensor] = None,
  231. ) -> Tensor:
  232. r"""Pass the input through the encoder layer.
  233. Args:
  234. src: the sequence to the encoder layer (required).
  235. src_mask: the mask for the src sequence (optional).
  236. src_key_padding_mask: the mask for the src keys per batch (optional).
  237. Shape:
  238. see the docs in Transformer class.
  239. """
  240. x, stage_embedding = src, None
  241. is_src_tuple = False
  242. if isinstance(src, tuple):
  243. x, stage_embedding = src
  244. is_src_tuple = True
  245. if src_key_padding_mask is not None:
  246. _skpm_dtype = src_key_padding_mask.dtype
  247. if _skpm_dtype != torch.bool and not torch.is_floating_point(
  248. src_key_padding_mask
  249. ):
  250. raise AssertionError(
  251. "only bool and floating types of key_padding_mask are supported"
  252. )
  253. if self.norm_first:
  254. x = x + self._sa_block(
  255. self.norm1(x, stage_embedding),
  256. src_mask,
  257. src_key_padding_mask,
  258. )
  259. x = x + self._ff_block(self.norm2(x, stage_embedding))
  260. else:
  261. x = self.norm1(
  262. x + self._sa_block(x, src_mask, src_key_padding_mask),
  263. stage_embedding,
  264. )
  265. x = self.norm2(x + self._ff_block(x), stage_embedding)
  266. if is_src_tuple:
  267. return (x, stage_embedding)
  268. return x
  269. def infer(
  270. self,
  271. src: Tensor,
  272. src_mask: Optional[Tensor] = None,
  273. src_key_padding_mask: Optional[Tensor] = None,
  274. past_kv: Optional[Tensor] = None,
  275. use_cache: bool = False,
  276. ):
  277. x, stage_embedding = src, None
  278. is_src_tuple = False
  279. if isinstance(src, tuple):
  280. x, stage_embedding = src
  281. is_src_tuple = True
  282. if src_key_padding_mask is not None:
  283. _skpm_dtype = src_key_padding_mask.dtype
  284. if _skpm_dtype != torch.bool and not torch.is_floating_point(
  285. src_key_padding_mask
  286. ):
  287. raise AssertionError(
  288. "only bool and floating types of key_padding_mask are supported"
  289. )
  290. if self.norm_first:
  291. x_attn_out, kv = self.self_attn.infer(
  292. self.norm1(x, stage_embedding),
  293. attn_mask=src_mask,
  294. key_padding_mask=src_key_padding_mask,
  295. need_weights=False,
  296. past_kv=past_kv,
  297. use_cache=use_cache,
  298. )
  299. x = x + x_attn_out
  300. x = x + self._ff_block(self.norm2(x, stage_embedding))
  301. if is_src_tuple:
  302. return (x, stage_embedding)
  303. return (x, kv)
  304. # self-attention block
  305. def _sa_block(
  306. self,
  307. x: Tensor,
  308. attn_mask: Optional[Tensor],
  309. key_padding_mask: Optional[Tensor],
  310. ) -> Tensor:
  311. x = self.self_attn(
  312. x,
  313. x,
  314. x,
  315. attn_mask=attn_mask,
  316. key_padding_mask=key_padding_mask,
  317. need_weights=False,
  318. )[0]
  319. return self.dropout1(x)
  320. # feed forward block
  321. def _ff_block(self, x: Tensor) -> Tensor:
  322. x = self.linear2(self.dropout(self.activation(self.linear1(x))))
  323. return self.dropout2(x)
  324. class TransformerEncoder(nn.Module):
  325. r"""TransformerEncoder is a stack of N encoder layers. Users can build the
  326. BERT(https://arxiv.org/abs/1810.04805) model with corresponding parameters.
  327. Args:
  328. encoder_layer: an instance of the TransformerEncoderLayer() class (required).
  329. num_layers: the number of sub-encoder-layers in the encoder (required).
  330. norm: the layer normalization component (optional).
  331. enable_nested_tensor: if True, input will automatically convert to nested tensor
  332. (and convert back on output). This will improve the overall performance of
  333. TransformerEncoder when padding rate is high. Default: ``True`` (enabled).
  334. Examples::
  335. >>> encoder_layer = TransformerEncoderLayer(d_model=512, nhead=8)
  336. >>> transformer_encoder = TransformerEncoder(encoder_layer, num_layers=6)
  337. >>> src = torch.rand(10, 32, 512)
  338. >>> out = transformer_encoder(src)
  339. """
  340. __constants__ = ["norm"]
  341. def __init__(self, encoder_layer, num_layers, norm=None):
  342. super(TransformerEncoder, self).__init__()
  343. self.layers = _get_clones(encoder_layer, num_layers)
  344. self.num_layers = num_layers
  345. self.norm = norm
  346. def forward(
  347. self,
  348. src: Tensor,
  349. mask: Optional[Tensor] = None,
  350. src_key_padding_mask: Optional[Tensor] = None,
  351. return_layer_states: bool = False,
  352. ) -> Tensor:
  353. r"""Pass the input through the encoder layers in turn.
  354. Args:
  355. src: the sequence to the encoder (required).
  356. mask: the mask for the src sequence (optional).
  357. src_key_padding_mask: the mask for the src keys per batch (optional).
  358. return_layer_states: return layers' state (optional).
  359. Shape:
  360. see the docs in Transformer class.
  361. """
  362. if return_layer_states:
  363. layer_states = [] # layers' output
  364. output = src
  365. for mod in self.layers:
  366. output = mod(
  367. output,
  368. src_mask=mask,
  369. src_key_padding_mask=src_key_padding_mask,
  370. )
  371. layer_states.append(output[0])
  372. if self.norm is not None:
  373. output = self.norm(output)
  374. return layer_states, output
  375. output = src
  376. for mod in self.layers:
  377. output = mod(
  378. output, src_mask=mask, src_key_padding_mask=src_key_padding_mask
  379. )
  380. if self.norm is not None:
  381. output = self.norm(output)
  382. return output
  383. def infer(
  384. self,
  385. src: Tensor,
  386. mask: Optional[Tensor] = None,
  387. src_key_padding_mask: Optional[Tensor] = None,
  388. return_layer_states: bool = False,
  389. past_kv: Optional[Tensor] = None,
  390. use_cache: bool = False,
  391. ):
  392. if past_kv is None:
  393. past_length = 0
  394. past_kv = tuple([None] * self.num_layers)
  395. else:
  396. past_length = past_kv[0][0].size(-2)
  397. new_kv = () if use_cache else None
  398. output = src
  399. for mod, past_layer_kv in zip(self.layers, past_kv):
  400. output, kv = mod.infer(
  401. output, src_mask=mask, src_key_padding_mask=src_key_padding_mask, past_kv=past_layer_kv, use_cache=use_cache
  402. )
  403. if use_cache:
  404. new_kv = new_kv + (kv,)
  405. if self.norm is not None:
  406. output = self.norm(output)
  407. return output, new_kv
  408. class TransformerDecoderLayer(nn.Module):
  409. __constants__ = ["batch_first", "norm_first"]
  410. def __init__(
  411. self,
  412. d_model: int,
  413. nhead: int,
  414. dim_feedforward: int = 2048,
  415. dropout: float = 0.1,
  416. activation: Union[str, Callable[[Tensor], Tensor]] = F.relu,
  417. linear1_self_attention_cls: nn.Module = nn.Linear,
  418. linear2_self_attention_cls: nn.Module = nn.Linear,
  419. linear1_feedforward_cls: nn.Module = nn.Linear,
  420. linear2_feedforward_cls: nn.Module = nn.Linear,
  421. batch_first: bool = False,
  422. norm_first: bool = False,
  423. device=None,
  424. dtype=None,
  425. layer_norm_cls: nn.Module = LayerNorm,
  426. layer_norm_eps: float = 1e-5,
  427. adaptive_layer_norm=False,
  428. ) -> None:
  429. factory_kwargs = {"device": device, "dtype": dtype}
  430. super(TransformerDecoderLayer, self).__init__()
  431. self.self_attn = MultiheadAttention(
  432. d_model,
  433. nhead,
  434. dropout=dropout,
  435. batch_first=batch_first,
  436. linear1_cls=linear1_self_attention_cls,
  437. linear2_cls=linear2_self_attention_cls,
  438. **factory_kwargs,
  439. )
  440. self.multihead_attn = MultiheadAttention(
  441. d_model,
  442. nhead,
  443. dropout=dropout,
  444. batch_first=batch_first,
  445. linear1_cls=linear1_self_attention_cls,
  446. linear2_cls=linear2_self_attention_cls,
  447. **factory_kwargs,
  448. )
  449. # Implementation of Feedforward model
  450. self.linear1 = linear1_feedforward_cls(
  451. d_model, dim_feedforward, **factory_kwargs
  452. )
  453. self.dropout = nn.Dropout(dropout)
  454. self.linear2 = linear2_feedforward_cls(
  455. dim_feedforward, d_model, **factory_kwargs
  456. )
  457. self.norm_first = norm_first
  458. self.dropout1 = nn.Dropout(dropout)
  459. self.dropout2 = nn.Dropout(dropout)
  460. self.dropout3 = nn.Dropout(dropout)
  461. # Legacy string support for activation function.
  462. if isinstance(activation, str):
  463. self.activation = _get_activation_fn(activation)
  464. elif isinstance(activation, partial):
  465. self.activation = activation(d_model)
  466. elif activation == BalancedDoubleSwish:
  467. self.activation = BalancedDoubleSwish(d_model)
  468. else:
  469. self.activation = activation
  470. if adaptive_layer_norm:
  471. norm1 = layer_norm_cls(
  472. d_model, eps=layer_norm_eps, **factory_kwargs
  473. )
  474. norm2 = layer_norm_cls(
  475. d_model, eps=layer_norm_eps, **factory_kwargs
  476. )
  477. norm3 = layer_norm_cls(
  478. d_model, eps=layer_norm_eps, **factory_kwargs
  479. )
  480. self.norm1 = AdaptiveLayerNorm(d_model, norm1)
  481. self.norm2 = AdaptiveLayerNorm(d_model, norm2)
  482. self.norm3 = AdaptiveLayerNorm(d_model, norm3)
  483. else:
  484. self.norm1 = layer_norm_cls(
  485. d_model, eps=layer_norm_eps, **factory_kwargs
  486. )
  487. self.norm2 = layer_norm_cls(
  488. d_model, eps=layer_norm_eps, **factory_kwargs
  489. )
  490. if layer_norm_cls == IdentityNorm:
  491. self.norm3 = BalancedBasicNorm(
  492. d_model, eps=layer_norm_eps, **factory_kwargs
  493. )
  494. else:
  495. self.norm3 = layer_norm_cls(
  496. d_model, eps=layer_norm_eps, **factory_kwargs
  497. )
  498. def forward(
  499. self,
  500. tgt: Tensor,
  501. memory: Tensor,
  502. tgt_mask: Optional[Tensor] = None,
  503. memory_mask: Optional[Tensor] = None,
  504. tgt_key_padding_mask: Optional[Tensor] = None,
  505. memory_key_padding_mask: Optional[Tensor] = None,
  506. ) -> Tensor:
  507. r"""Pass the inputs (and mask) through the decoder layer.
  508. Args:
  509. tgt: the sequence to the decoder layer (required).
  510. memory: the sequence from the last layer of the encoder (required).
  511. tgt_mask: the mask for the tgt sequence (optional).
  512. memory_mask: the mask for the memory sequence (optional).
  513. tgt_key_padding_mask: the mask for the tgt keys per batch (optional).
  514. memory_key_padding_mask: the mask for the memory keys per batch (optional).
  515. Shape:
  516. see the docs in Transformer class.
  517. """
  518. tgt_is_tuple = False
  519. if isinstance(tgt, tuple):
  520. x, stage_embedding = tgt
  521. tgt_is_tuple = True
  522. else:
  523. x, stage_embedding = tgt, None
  524. if self.norm_first:
  525. x = x + self._sa_block(
  526. self.norm1(x, stage_embedding), tgt_mask, tgt_key_padding_mask
  527. )
  528. x = x + self._mha_block(
  529. self.norm2(x, stage_embedding),
  530. memory,
  531. memory_mask,
  532. memory_key_padding_mask,
  533. )
  534. x = x + self._ff_block(self.norm3(x, stage_embedding))
  535. else:
  536. x = self.norm1(
  537. x + self._sa_block(x, tgt_mask, tgt_key_padding_mask),
  538. stage_embedding,
  539. )
  540. x = self.norm2(
  541. x
  542. + self._mha_block(
  543. x, memory, memory_mask, memory_key_padding_mask
  544. ),
  545. stage_embedding,
  546. )
  547. x = self.norm3(x + self._ff_block(x), stage_embedding)
  548. if tgt_is_tuple:
  549. return (x, stage_embedding)
  550. return x
  551. # self-attention block
  552. def _sa_block(
  553. self,
  554. x: Tensor,
  555. attn_mask: Optional[Tensor],
  556. key_padding_mask: Optional[Tensor],
  557. ) -> Tensor:
  558. x = self.self_attn(
  559. x,
  560. x,
  561. x,
  562. attn_mask=attn_mask,
  563. key_padding_mask=key_padding_mask,
  564. need_weights=False,
  565. )[0]
  566. return self.dropout1(x)
  567. # multihead attention block
  568. def _mha_block(
  569. self,
  570. x: Tensor,
  571. mem: Tensor,
  572. attn_mask: Optional[Tensor],
  573. key_padding_mask: Optional[Tensor],
  574. ) -> Tensor:
  575. x = self.multihead_attn(
  576. x,
  577. mem,
  578. mem,
  579. attn_mask=attn_mask,
  580. key_padding_mask=key_padding_mask,
  581. need_weights=False,
  582. )[0]
  583. return self.dropout2(x)
  584. # feed forward block
  585. def _ff_block(self, x: Tensor) -> Tensor:
  586. x = self.linear2(self.dropout(self.activation(self.linear1(x))))
  587. return self.dropout3(x)
  588. def _get_clones(module, N):
  589. return nn.ModuleList([copy.deepcopy(module) for i in range(N)])
  590. def _get_activation_fn(activation: str) -> Callable[[Tensor], Tensor]:
  591. if activation == "relu":
  592. return F.relu
  593. elif activation == "gelu":
  594. return F.gelu
  595. raise RuntimeError(
  596. "activation should be relu/gelu, not {}".format(activation)
  597. )
Tip!

Press p or to see the previous file or, n or to see the next file

Comments

Loading...