sonithoiningombam commited on
Commit
94ac172
·
verified ·
1 Parent(s): 29be0d7

Add files using upload-large-folder tool

Browse files
Files changed (20) hide show
  1. .zshrc +115 -0
  2. bart/data/mni_dev_tokenise.txt +0 -0
  3. bart/data/mni_test_tokenise.txt +0 -0
  4. data/fairseq/fairseq/model_parallel/models/__pycache__/__init__.cpython-38.pyc +0 -0
  5. data/fairseq/fairseq/model_parallel/models/__pycache__/transformer.cpython-38.pyc +0 -0
  6. data/fairseq/fairseq/model_parallel/models/__pycache__/transformer_lm.cpython-38.pyc +0 -0
  7. data/fairseq/fairseq/model_parallel/models/pipeline_parallel_transformer/__init__.py +6 -0
  8. data/fairseq/fairseq/model_parallel/models/pipeline_parallel_transformer/__pycache__/__init__.cpython-38.pyc +0 -0
  9. data/fairseq/fairseq/model_parallel/models/pipeline_parallel_transformer/__pycache__/layers.cpython-38.pyc +0 -0
  10. data/fairseq/fairseq/model_parallel/models/pipeline_parallel_transformer/__pycache__/model.cpython-38.pyc +0 -0
  11. data/fairseq/fairseq/model_parallel/models/pipeline_parallel_transformer/layers.py +600 -0
  12. data/fairseq/fairseq/model_parallel/models/pipeline_parallel_transformer/model.py +779 -0
  13. data/fairseq/fairseq/model_parallel/models/roberta/__init__.py +6 -0
  14. data/fairseq/fairseq/model_parallel/models/roberta/__pycache__/__init__.cpython-38.pyc +0 -0
  15. data/fairseq/fairseq/model_parallel/models/roberta/__pycache__/model.cpython-38.pyc +0 -0
  16. data/fairseq/fairseq/model_parallel/models/roberta/model.py +225 -0
  17. data/fairseq/fairseq/model_parallel/modules/__init__.py +17 -0
  18. data/fairseq/fairseq/model_parallel/modules/multihead_attention.py +349 -0
  19. data/fairseq/fairseq/model_parallel/modules/transformer_layer.py +78 -0
  20. ipft.ipynb +551 -0
.zshrc ADDED
@@ -0,0 +1,115 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Set the encoding for SSH since ssh can't inherit the ENV
2
+ export LC_ALL=C.UTF-8
3
+ export LANG=C.UTF-8
4
+
5
+ # Set HOME
6
+ export HOME="/teamspace/studios/this_studio"
7
+
8
+ # Path to your oh-my-zsh installation.
9
+ export ZSH=$HOME/.oh-my-zsh
10
+
11
+ # Set auto-completion dumpfile location.
12
+ export ZSH_COMPDUMP="/settings/.zcompdump-${HOST}"
13
+
14
+ # Don't care about permissions on autocomplete files
15
+ ZSH_DISABLE_COMPFIX=true
16
+
17
+ # Set name of the theme to load --- if set to "random", it will
18
+ # load a random theme each time oh-my-zsh is loaded, in which case,
19
+ # to know which specific one was loaded, run: echo $RANDOM_THEME
20
+ # See https://github.com/ohmyzsh/ohmyzsh/wiki/Themes
21
+ ZSH_THEME="robbyrussell"
22
+
23
+ # Set list of themes to pick from when loading at random
24
+ # Setting this variable when ZSH_THEME=random will cause zsh to load
25
+ # a theme from this variable instead of looking in $ZSH/themes/
26
+ # If set to an empty array, this variable will have no effect.
27
+ # ZSH_THEME_RANDOM_CANDIDATES=( "robbyrussell" "agnoster" )
28
+
29
+ # Uncomment the following line to use case-sensitive completion.
30
+ # CASE_SENSITIVE="true"
31
+
32
+ # Uncomment the following line to use hyphen-insensitive completion.
33
+ # Case-sensitive completion must be off. _ and - will be interchangeable.
34
+ # HYPHEN_INSENSITIVE="true"
35
+
36
+ # Uncomment one of the following lines to change the auto-update behavior
37
+ zstyle ':omz:update' mode disabled # disable automatic updates
38
+ # zstyle ':omz:update' mode auto # update automatically without asking
39
+ # zstyle ':omz:update' mode reminder # just remind me to update when it's time
40
+
41
+ # Uncomment the following line to change how often to auto-update (in days).
42
+ # zstyle ':omz:update' frequency 13
43
+
44
+ # Uncomment the following line if pasting URLs and other text is messed up.
45
+ # DISABLE_MAGIC_FUNCTIONS="true"
46
+
47
+ # Uncomment the following line to disable colors in ls.
48
+ # DISABLE_LS_COLORS="true"
49
+
50
+ # Uncomment the following line to disable auto-setting terminal title.
51
+ # DISABLE_AUTO_TITLE="true"
52
+
53
+ # Uncomment the following line to enable command auto-correction.
54
+ # ENABLE_CORRECTION="true"
55
+
56
+ # Uncomment the following line to display red dots whilst waiting for completion.
57
+ # You can also set it to another string to have that shown instead of the default red dots.
58
+ # e.g. COMPLETION_WAITING_DOTS="%F{yellow}waiting...%f"
59
+ # Caution: this setting can cause issues with multiline prompts in zsh < 5.7.1 (see #5765)
60
+ # COMPLETION_WAITING_DOTS="true"
61
+
62
+ # Uncomment the following line if you want to disable marking untracked files
63
+ # under VCS as dirty. This makes repository status check for large repositories
64
+ # much, much faster.
65
+ DISABLE_UNTRACKED_FILES_DIRTY="true"
66
+
67
+ # Uncomment the following line if you want to change the command execution time
68
+ # stamp shown in the history command output.
69
+ # You can set one of the optional three formats:
70
+ # "mm/dd/yyyy"|"dd.mm.yyyy"|"yyyy-mm-dd"
71
+ # or set a custom format using the strftime function format specifications,
72
+ # see 'man strftime' for details.
73
+ # HIST_STAMPS="mm/dd/yyyy"
74
+
75
+ # Would you like to use another custom folder than $ZSH/custom?
76
+ # ZSH_CUSTOM=/path/to/new-custom-folder
77
+
78
+ # Which plugins would you like to load?
79
+ # Standard plugins can be found in $ZSH/plugins/
80
+ # Custom plugins may be added to $ZSH_CUSTOM/plugins/
81
+ # Example format: plugins=(rails git textmate ruby lighthouse)
82
+ # Add wisely, as too many plugins slow down shell startup.
83
+ plugins=()
84
+
85
+ source $ZSH/oh-my-zsh.sh
86
+
87
+ # User configuration
88
+
89
+ # export MANPATH="/usr/local/man:$MANPATH"
90
+
91
+ # You may need to manually set your language environment
92
+ # export LANG=en_US.UTF-8
93
+
94
+ # Preferred editor for local and remote sessions
95
+ # if [[ -n $SSH_CONNECTION ]]; then
96
+ # export EDITOR='vim'
97
+ # else
98
+ # export EDITOR='mvim'
99
+ # fi
100
+
101
+ # Compilation flags
102
+ # export ARCHFLAGS="-arch x86_64"
103
+
104
+ # Set personal aliases, overriding those provided by oh-my-zsh libs,
105
+ # plugins, and themes. Aliases can be placed here, though oh-my-zsh
106
+ # users are encouraged to define aliases within the ZSH_CUSTOM folder.
107
+ # For a full list of active aliases, run `alias`.
108
+ #
109
+ # Example aliases
110
+ # alias zshconfig="mate ~/.zshrc"
111
+ # alias ohmyzsh="mate ~/.oh-my-zsh"
112
+
113
+ # >>> lightning managed. do not modify >>>
114
+ [ -f /settings/.lightningrc ] && source /settings/.lightningrc zsh
115
+ # <<< lightning managed. do not modify <<<
bart/data/mni_dev_tokenise.txt ADDED
The diff for this file is too large to render. See raw diff
 
bart/data/mni_test_tokenise.txt ADDED
The diff for this file is too large to render. See raw diff
 
data/fairseq/fairseq/model_parallel/models/__pycache__/__init__.cpython-38.pyc ADDED
Binary file (538 Bytes). View file
 
data/fairseq/fairseq/model_parallel/models/__pycache__/transformer.cpython-38.pyc ADDED
Binary file (4.25 kB). View file
 
data/fairseq/fairseq/model_parallel/models/__pycache__/transformer_lm.cpython-38.pyc ADDED
Binary file (5.25 kB). View file
 
data/fairseq/fairseq/model_parallel/models/pipeline_parallel_transformer/__init__.py ADDED
@@ -0,0 +1,6 @@
 
 
 
 
 
 
 
1
+ # Copyright (c) Facebook, Inc. and its affiliates.
2
+ #
3
+ # This source code is licensed under the MIT license found in the
4
+ # LICENSE file in the root directory of this source tree.
5
+
6
+ from .model import * # noqa
data/fairseq/fairseq/model_parallel/models/pipeline_parallel_transformer/__pycache__/__init__.cpython-38.pyc ADDED
Binary file (228 Bytes). View file
 
data/fairseq/fairseq/model_parallel/models/pipeline_parallel_transformer/__pycache__/layers.cpython-38.pyc ADDED
Binary file (15.6 kB). View file
 
data/fairseq/fairseq/model_parallel/models/pipeline_parallel_transformer/__pycache__/model.cpython-38.pyc ADDED
Binary file (23.6 kB). View file
 
data/fairseq/fairseq/model_parallel/models/pipeline_parallel_transformer/layers.py ADDED
@@ -0,0 +1,600 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright (c) Facebook, Inc. and its affiliates.
2
+ #
3
+ # This source code is licensed under the MIT license found in the
4
+ # LICENSE file in the root directory of this source tree.
5
+
6
+ import math
7
+ from collections import namedtuple
8
+
9
+ import torch
10
+ import torch.nn as nn
11
+ import torch.nn.functional as F
12
+
13
+ from fairseq import options, utils
14
+ from fairseq.modules import (
15
+ AdaptiveSoftmax,
16
+ LayerNorm,
17
+ MultiheadAttention,
18
+ PositionalEmbedding,
19
+ )
20
+
21
+ EncoderOut = namedtuple(
22
+ "TransformerEncoderOut",
23
+ [
24
+ "encoder_out", # T x B x C
25
+ "encoder_padding_mask", # B x T
26
+ "encoder_embedding", # B x T x C
27
+ "encoder_states", # List[T x B x C]
28
+ ],
29
+ )
30
+
31
+
32
+ class TransformerEncoderEmbedding(nn.Module):
33
+ """Encoder Embedding + Positional Embedding"""
34
+
35
+ def __init__(self, args, embed_tokens):
36
+ super().__init__()
37
+ self.dropout = args.dropout
38
+ self.max_source_positions = args.max_source_positions
39
+ self.embed_tokens = embed_tokens
40
+ if isinstance(embed_tokens, nn.ModuleList):
41
+ self.padding_idx = embed_tokens[0].padding_idx
42
+ embed_dim = sum(e.embedding_dim for e in embed_tokens)
43
+ else:
44
+ self.padding_idx = embed_tokens.padding_idx
45
+ embed_dim = embed_tokens.embedding_dim
46
+ self.embed_scale = math.sqrt(embed_dim)
47
+ self.embed_positions = (
48
+ PositionalEmbedding(
49
+ args.max_source_positions,
50
+ embed_dim,
51
+ self.padding_idx,
52
+ learned=args.encoder_learned_pos,
53
+ )
54
+ if not args.no_token_positional_embeddings
55
+ else None
56
+ )
57
+ if getattr(args, "layernorm_embedding", False):
58
+ self.layernorm_embedding = LayerNorm(embed_dim)
59
+ else:
60
+ self.layernorm_embedding = None
61
+
62
+ def forward(self, input):
63
+ # embed tokens and positions
64
+ src_tokens = input[0]
65
+ prev_output_tokens = input[2]
66
+ if isinstance(self.embed_tokens, nn.ModuleList):
67
+ x_embed_list = []
68
+ for embed_tokens_part in self.embed_tokens:
69
+ x_embed_list.append(embed_tokens_part(src_tokens))
70
+
71
+ embedded = torch.cat(x_embed_list, dim=-1)
72
+ else:
73
+ embedded = self.embed_tokens(src_tokens)
74
+ x = embed = self.embed_scale * embedded
75
+ if self.embed_positions is not None:
76
+ x = embed + self.embed_positions(src_tokens)
77
+ if self.layernorm_embedding:
78
+ x = self.layernorm_embedding(x)
79
+ x = F.dropout(x, p=self.dropout, training=self.training)
80
+ # B x T x C -> T x B x C
81
+ x = x.transpose(0, 1)
82
+
83
+ # compute padding mask
84
+ encoder_padding_mask = src_tokens.eq(self.padding_idx)
85
+ return (x, encoder_padding_mask, prev_output_tokens)
86
+
87
+
88
+ class TransformerEncoderLayerNorm(nn.Module):
89
+ """
90
+ Layer norm at the the end of all encoder layers if
91
+ args.encoder_enormalize_before = True
92
+ """
93
+
94
+ def __init__(self, args, embed_dim):
95
+ super().__init__()
96
+ if args.encoder_normalize_before:
97
+ self.layer_norm = LayerNorm(embed_dim)
98
+ else:
99
+ self.layer_norm = None
100
+
101
+ def forward(self, input):
102
+ x = input[0]
103
+ encoder_padding_mask = input[1]
104
+ prev_output_tokens = input[2]
105
+ if self.layer_norm:
106
+ x = self.layer_norm(x)
107
+ # keeping track of the incremental_state is not supported yet
108
+ return (x, encoder_padding_mask, prev_output_tokens)
109
+
110
+
111
+ class TransformerDecoderEmbedding(nn.Module):
112
+ """Decoder Embedding + Positional Embedding"""
113
+
114
+ def __init__(self, args, embed_tokens):
115
+ super().__init__()
116
+ self.dropout = args.dropout
117
+ self.share_input_output_embed = args.share_decoder_input_output_embed
118
+ input_embed_dim = (
119
+ sum(e.embedding_dim for e in embed_tokens)
120
+ if isinstance(embed_tokens, nn.ModuleList)
121
+ else embed_tokens.embedding_dim
122
+ )
123
+ embed_dim = args.decoder_embed_dim
124
+ self.output_embed_dim = args.decoder_output_dim
125
+
126
+ padding_idx = (
127
+ embed_tokens[0].padding_idx
128
+ if isinstance(embed_tokens, nn.ModuleList)
129
+ else embed_tokens.padding_idx
130
+ )
131
+ self.max_target_positions = args.max_target_positions
132
+
133
+ self.embed_tokens = embed_tokens
134
+ self.embed_scale = math.sqrt(embed_dim) # todo: try with input_embed_dim
135
+
136
+ self.project_in_dim = (
137
+ Linear(input_embed_dim, embed_dim, bias=False)
138
+ if embed_dim != input_embed_dim
139
+ else None
140
+ )
141
+
142
+ self.embed_positions = (
143
+ PositionalEmbedding(
144
+ args.max_target_positions,
145
+ embed_dim,
146
+ padding_idx,
147
+ learned=args.decoder_learned_pos,
148
+ )
149
+ if not args.no_token_positional_embeddings
150
+ else None
151
+ )
152
+
153
+ def forward(self, input):
154
+ mt_task = False
155
+ if isinstance(input, tuple):
156
+ if len(input) == 3:
157
+ encoder_out = input[0]
158
+ encoder_padding_mask = input[1]
159
+ prev_output_tokens = input[2]
160
+ incremental_state = None # Hardcoding to avoid passing of None objects
161
+ mt_task = True
162
+ else:
163
+ # HACK for now, need to fix (TODO sidgoyal)
164
+ prev_output_tokens = input[0]
165
+ # discard "src_lengths"
166
+ encoder_out = None
167
+ encoder_padding_mask = None
168
+ incremental_state = None
169
+
170
+ else:
171
+ prev_output_tokens = input
172
+ encoder_out = None
173
+ encoder_padding_mask = None
174
+ incremental_state = None
175
+
176
+ positions = (
177
+ self.embed_positions(
178
+ prev_output_tokens,
179
+ incremental_state=incremental_state,
180
+ )
181
+ if self.embed_positions is not None
182
+ else None
183
+ )
184
+
185
+ if incremental_state is not None:
186
+ prev_output_tokens = prev_output_tokens[:, -1:]
187
+ if positions is not None:
188
+ positions = positions[:, -1:]
189
+
190
+ # embed tokens and positions
191
+
192
+ if isinstance(self.embed_tokens, nn.ModuleList):
193
+ x_embed_list = []
194
+ for embed_tokens_part in self.embed_tokens:
195
+ x_embed_list.append(embed_tokens_part(prev_output_tokens))
196
+
197
+ x = self.embed_scale * torch.cat(x_embed_list, dim=-1)
198
+ else:
199
+ x = self.embed_scale * self.embed_tokens(prev_output_tokens)
200
+
201
+ if self.project_in_dim is not None:
202
+ x = self.project_in_dim(x)
203
+
204
+ if positions is not None:
205
+ x += positions
206
+ x = F.dropout(x, p=self.dropout, training=self.training)
207
+
208
+ # B x T x C -> T x B x C
209
+ x = x.transpose(0, 1)
210
+ if mt_task:
211
+ return (x, encoder_out, encoder_padding_mask)
212
+ return x
213
+
214
+
215
+ class TransformerDecoderOutputLayer(nn.Module):
216
+ def __init__(self, args, embed_tokens, dictionary):
217
+ super().__init__()
218
+ self.share_input_output_embed = args.share_decoder_input_output_embed
219
+ self.embed_tokens = embed_tokens
220
+ self.output_embed_dim = args.decoder_output_dim
221
+ embed_dim = args.decoder_embed_dim
222
+
223
+ self.project_out_dim = (
224
+ Linear(embed_dim, self.output_embed_dim, bias=False)
225
+ if embed_dim != self.output_embed_dim and not args.tie_adaptive_weights
226
+ else None
227
+ )
228
+ self.adaptive_softmax = None
229
+ if args.adaptive_softmax_cutoff is not None:
230
+ assert not isinstance(embed_tokens, nn.ModuleList)
231
+ self.adaptive_softmax = AdaptiveSoftmax(
232
+ len(dictionary),
233
+ self.output_embed_dim,
234
+ options.eval_str_list(args.adaptive_softmax_cutoff, type=int),
235
+ dropout=args.adaptive_softmax_dropout,
236
+ adaptive_inputs=embed_tokens if args.tie_adaptive_weights else None,
237
+ factor=args.adaptive_softmax_factor,
238
+ tie_proj=args.tie_adaptive_proj,
239
+ )
240
+ elif not self.share_input_output_embed:
241
+ self.embed_tokens = nn.Parameter(
242
+ torch.Tensor(len(dictionary), self.output_embed_dim)
243
+ )
244
+ nn.init.normal_(
245
+ self.embed_tokens, mean=0, std=self.output_embed_dim**-0.5
246
+ )
247
+
248
+ if args.decoder_normalize_before and not getattr(
249
+ args, "no_decoder_final_norm", False
250
+ ):
251
+ self.layer_norm = LayerNorm(embed_dim)
252
+ else:
253
+ self.layer_norm = None
254
+
255
+ def forward(self, input, apply_final_proj=True):
256
+ if isinstance(input, tuple):
257
+ x = input[0]
258
+ else:
259
+ x = input
260
+
261
+ if self.layer_norm:
262
+ x = self.layer_norm(x)
263
+
264
+ # T x B x C -> B x T x C
265
+ x = x.transpose(0, 1)
266
+
267
+ if self.project_out_dim is not None:
268
+ x = self.project_out_dim(x)
269
+ if apply_final_proj:
270
+ x = self.output_layer(x)
271
+ return x
272
+
273
+ def output_layer(self, features, **kwargs):
274
+ """Project features to the vocabulary size."""
275
+ if self.adaptive_softmax is None:
276
+ # project back to size of vocabulary
277
+ if self.share_input_output_embed:
278
+ if isinstance(self.embed_tokens, nn.ModuleList):
279
+ output = None
280
+ for i, emb in enumerate(self.embed_tokens):
281
+ sidx = i * emb.embedding_dim
282
+ eidx = (i + 1) * emb.embedding_dim
283
+ if output is None:
284
+ output = F.linear(features[:, :, sidx:eidx], emb.weight)
285
+ else:
286
+ output += F.linear(features[:, :, sidx:eidx], emb.weight)
287
+
288
+ return output
289
+ else:
290
+ return F.linear(features, self.embed_tokens.weight)
291
+ else:
292
+ return F.linear(features, self.embed_tokens)
293
+ else:
294
+ return features
295
+
296
+
297
+ class TransformerEncoderLayer(nn.Module):
298
+ """Encoder layer block.
299
+ In the original paper each operation (multi-head attention or FFN) is
300
+ postprocessed with: `dropout -> add residual -> layernorm`. In the
301
+ tensor2tensor code they suggest that learning is more robust when
302
+ preprocessing each layer with layernorm and postprocessing with:
303
+ `dropout -> add residual`. We default to the approach in the paper, but the
304
+ tensor2tensor approach can be enabled by setting
305
+ *args.encoder_normalize_before* to ``True``.
306
+
307
+ Args:
308
+ args (argparse.Namespace): parsed command-line arguments
309
+ """
310
+
311
+ def __init__(self, args):
312
+ super().__init__()
313
+ self.embed_dim = args.encoder_embed_dim
314
+ self.self_attn = MultiheadAttention(
315
+ self.embed_dim,
316
+ args.encoder_attention_heads,
317
+ dropout=args.attention_dropout,
318
+ self_attention=True,
319
+ )
320
+ self.self_attn_layer_norm = LayerNorm(self.embed_dim)
321
+ self.dropout = args.dropout
322
+ self.activation_fn = utils.get_activation_fn(
323
+ activation=getattr(args, "activation_fn", "relu")
324
+ )
325
+ self.activation_dropout = getattr(args, "activation_dropout", 0)
326
+ if self.activation_dropout == 0:
327
+ # for backwards compatibility with models that use args.relu_dropout
328
+ self.activation_dropout = getattr(args, "relu_dropout", 0)
329
+ self.normalize_before = args.encoder_normalize_before
330
+ self.fc1 = Linear(self.embed_dim, args.encoder_ffn_embed_dim)
331
+ self.fc2 = Linear(args.encoder_ffn_embed_dim, self.embed_dim)
332
+ self.final_layer_norm = LayerNorm(self.embed_dim)
333
+
334
+ def upgrade_state_dict_named(self, state_dict, name):
335
+ """
336
+ Rename layer norm states from `...layer_norms.0.weight` to
337
+ `...self_attn_layer_norm.weight` and `...layer_norms.1.weight` to
338
+ `...final_layer_norm.weight`
339
+ """
340
+ layer_norm_map = {"0": "self_attn_layer_norm", "1": "final_layer_norm"}
341
+ for old, new in layer_norm_map.items():
342
+ for m in ("weight", "bias"):
343
+ k = "{}.layer_norms.{}.{}".format(name, old, m)
344
+ if k in state_dict:
345
+ state_dict["{}.{}.{}".format(name, new, m)] = state_dict[k]
346
+ del state_dict[k]
347
+
348
+ def forward(self, input):
349
+ """
350
+ Args:
351
+ input (Tuple):
352
+ input[0] (Tensor): input to the layer of shape `(seq_len, batch, embed_dim)`
353
+ input[1] (ByteTensor/FloatTensor): encoder padding mask -
354
+ binary ByteTensor of shape `(batch, src_len)` where padding elements
355
+ are indicated by ``1``.
356
+ input[2] (LongTensor): previous decoder outputs of shape
357
+ `(batch, tgt_len)`, for teacher forcing)
358
+ Returns:
359
+ output (Tuple):
360
+ output[0] (Tensor): encoded output of shape `(batch, src_len, embed_dim)`
361
+ output[1] (ByteTensor/FloatTensor): encoder padding mask
362
+ output[2] (LongTensor): previous decoder outputs
363
+ """
364
+ x = input[0]
365
+ encoder_padding_mask = input[1]
366
+ prev_output_tokens = input[2]
367
+ residual = x
368
+ x = self.maybe_layer_norm(self.self_attn_layer_norm, x, before=True)
369
+ x, _ = self.self_attn(
370
+ query=x, key=x, value=x, key_padding_mask=encoder_padding_mask
371
+ )
372
+ x = F.dropout(x, p=self.dropout, training=self.training)
373
+ x = residual + x
374
+ x = self.maybe_layer_norm(self.self_attn_layer_norm, x, after=True)
375
+
376
+ residual = x
377
+ x = self.maybe_layer_norm(self.final_layer_norm, x, before=True)
378
+ x = self.activation_fn(self.fc1(x))
379
+ x = F.dropout(x, p=self.activation_dropout, training=self.training)
380
+ x = self.fc2(x)
381
+ x = F.dropout(x, p=self.dropout, training=self.training)
382
+ x = residual + x
383
+ x = self.maybe_layer_norm(self.final_layer_norm, x, after=True)
384
+ return (x, encoder_padding_mask, prev_output_tokens)
385
+
386
+ def maybe_layer_norm(self, layer_norm, x, before=False, after=False):
387
+ assert before ^ after
388
+ if after ^ self.normalize_before:
389
+ return layer_norm(x)
390
+ else:
391
+ return x
392
+
393
+
394
+ class TransformerDecoderLayer(nn.Module):
395
+ """Decoder layer block.
396
+
397
+ In the original paper each operation (multi-head attention, encoder
398
+ attention or FFN) is postprocessed with: `dropout -> add residual ->
399
+ layernorm`. In the tensor2tensor code they suggest that learning is more
400
+ robust when preprocessing each layer with layernorm and postprocessing with:
401
+ `dropout -> add residual`. We default to the approach in the paper, but the
402
+ tensor2tensor approach can be enabled by setting
403
+ *args.decoder_normalize_before* to ``True``.
404
+
405
+ Args:
406
+ args (argparse.Namespace): parsed command-line arguments
407
+ no_encoder_attn (bool, optional): whether to attend to encoder outputs
408
+ (default: False).
409
+ """
410
+
411
+ def __init__(
412
+ self, args, no_encoder_attn=False, add_bias_kv=False, add_zero_attn=False
413
+ ):
414
+ super().__init__()
415
+ self.embed_dim = args.decoder_embed_dim
416
+ self.self_attn = MultiheadAttention(
417
+ embed_dim=self.embed_dim,
418
+ num_heads=args.decoder_attention_heads,
419
+ dropout=args.attention_dropout,
420
+ add_bias_kv=add_bias_kv,
421
+ add_zero_attn=add_zero_attn,
422
+ self_attention=True,
423
+ )
424
+ self.dropout = args.dropout
425
+ self.activation_fn = utils.get_activation_fn(
426
+ activation=getattr(args, "activation_fn", "relu")
427
+ )
428
+ self.activation_dropout = getattr(args, "activation_dropout", 0)
429
+ if self.activation_dropout == 0:
430
+ # for backwards compatibility with models that use args.relu_dropout
431
+ self.activation_dropout = getattr(args, "relu_dropout", 0)
432
+ self.normalize_before = args.decoder_normalize_before
433
+
434
+ # use layerNorm rather than FusedLayerNorm for exporting.
435
+ # char_inputs can be used to determint this.
436
+ # TODO remove this once we update apex with the fix
437
+ export = getattr(args, "char_inputs", False)
438
+ self.self_attn_layer_norm = LayerNorm(self.embed_dim, export=export)
439
+
440
+ if no_encoder_attn:
441
+ self.encoder_attn = None
442
+ self.encoder_attn_layer_norm = None
443
+ else:
444
+ self.encoder_attn = MultiheadAttention(
445
+ self.embed_dim,
446
+ args.decoder_attention_heads,
447
+ kdim=getattr(args, "encoder_embed_dim", None),
448
+ vdim=getattr(args, "encoder_embed_dim", None),
449
+ dropout=args.attention_dropout,
450
+ encoder_decoder_attention=True,
451
+ )
452
+ self.encoder_attn_layer_norm = LayerNorm(self.embed_dim, export=export)
453
+
454
+ self.fc1 = Linear(self.embed_dim, args.decoder_ffn_embed_dim)
455
+ self.fc2 = Linear(args.decoder_ffn_embed_dim, self.embed_dim)
456
+
457
+ self.final_layer_norm = LayerNorm(self.embed_dim, export=export)
458
+ self.need_attn = True
459
+
460
+ self.onnx_trace = False
461
+
462
+ def prepare_for_onnx_export_(self):
463
+ self.onnx_trace = True
464
+
465
+ def forward(self, input):
466
+ """
467
+ Args:
468
+ input (Tuple):
469
+ input[0] (Tensor): input to the layer of shape `(seq_len, batch, embed_dim)`
470
+ input[1] (Tensor): encoder output of shape `(batch, src_len, embed_dim)`
471
+ input[2] (ByteTensor/FloatTensor): encoder padding mask -
472
+ binary ByteTensor of shape `(batch, src_len)` where padding elements
473
+ are indicated by ``1``.
474
+ Returns:
475
+ output (Tuple):
476
+ output[0] (Tensor): encoded output of shape `(batch, src_len, embed_dim)`
477
+ output[1] (ByteTensor/FloatTensor): encoder padding mask
478
+ output[2] (LongTensor): previous decoder outputs
479
+ """
480
+ # Note: incremental state is not yet supported
481
+ mt_task = False
482
+ if isinstance(input, tuple):
483
+ x = input[0]
484
+ encoder_out = input[1]
485
+ encoder_padding_mask = input[2]
486
+ incremental_state = None
487
+ mt_task = True
488
+ else:
489
+ x = input
490
+ encoder_out = None
491
+ encoder_padding_mask = None
492
+ incremental_state = None
493
+
494
+ if incremental_state is None:
495
+ self_attn_mask = self.buffered_future_mask(x)
496
+ else:
497
+ self_attn_mask = None
498
+
499
+ # TODO: add back prev_self_attn_state, prev_attn_state,
500
+ # self_attn_padding_mask
501
+ prev_self_attn_state = None
502
+ prev_attn_state = None
503
+ self_attn_padding_mask = None
504
+
505
+ residual = x
506
+ x = self.maybe_layer_norm(self.self_attn_layer_norm, x, before=True)
507
+ if prev_self_attn_state is not None:
508
+ if incremental_state is None:
509
+ incremental_state = {}
510
+ prev_key, prev_value = prev_self_attn_state
511
+ saved_state = {"prev_key": prev_key, "prev_value": prev_value}
512
+ self.self_attn._set_input_buffer(incremental_state, saved_state)
513
+ x, attn = self.self_attn(
514
+ query=x,
515
+ key=x,
516
+ value=x,
517
+ key_padding_mask=self_attn_padding_mask,
518
+ incremental_state=incremental_state,
519
+ need_weights=False,
520
+ attn_mask=self_attn_mask,
521
+ )
522
+ x = F.dropout(x, p=self.dropout, training=self.training)
523
+ x = residual + x
524
+ x = self.maybe_layer_norm(self.self_attn_layer_norm, x, after=True)
525
+
526
+ if self.encoder_attn is not None:
527
+ residual = x
528
+ x = self.maybe_layer_norm(self.encoder_attn_layer_norm, x, before=True)
529
+ if prev_attn_state is not None:
530
+ if incremental_state is None:
531
+ incremental_state = {}
532
+ prev_key, prev_value = prev_attn_state
533
+ saved_state = {"prev_key": prev_key, "prev_value": prev_value}
534
+ self.encoder_attn._set_input_buffer(incremental_state, saved_state)
535
+ x, attn = self.encoder_attn(
536
+ query=x,
537
+ key=encoder_out,
538
+ value=encoder_out,
539
+ key_padding_mask=encoder_padding_mask,
540
+ incremental_state=incremental_state,
541
+ static_kv=True,
542
+ need_weights=(not self.training and self.need_attn),
543
+ )
544
+ x = F.dropout(x, p=self.dropout, training=self.training)
545
+ x = residual + x
546
+ x = self.maybe_layer_norm(self.encoder_attn_layer_norm, x, after=True)
547
+
548
+ residual = x
549
+ x = self.maybe_layer_norm(self.final_layer_norm, x, before=True)
550
+ x = self.activation_fn(self.fc1(x))
551
+ x = F.dropout(x, p=self.activation_dropout, training=self.training)
552
+ x = self.fc2(x)
553
+ x = F.dropout(x, p=self.dropout, training=self.training)
554
+ x = residual + x
555
+ x = self.maybe_layer_norm(self.final_layer_norm, x, after=True)
556
+
557
+ if mt_task:
558
+ return (x, encoder_out, encoder_padding_mask)
559
+ return x
560
+
561
+ def buffered_future_mask(self, tensor):
562
+ dim = tensor.size(0)
563
+ if (
564
+ not hasattr(self, "_future_mask")
565
+ or self._future_mask is None
566
+ or self._future_mask.device != tensor.device
567
+ ):
568
+ self._future_mask = torch.triu(
569
+ utils.fill_with_neg_inf(tensor.new(dim, dim)), 1
570
+ )
571
+ if self._future_mask.size(0) < dim:
572
+ self._future_mask = torch.triu(
573
+ utils.fill_with_neg_inf(self._future_mask.resize_(dim, dim)), 1
574
+ )
575
+ return self._future_mask[:dim, :dim]
576
+
577
+ def maybe_layer_norm(self, layer_norm, x, before=False, after=False):
578
+ assert before ^ after
579
+ if after ^ self.normalize_before:
580
+ return layer_norm(x)
581
+ else:
582
+ return x
583
+
584
+ def make_generation_fast_(self, need_attn=False, **kwargs):
585
+ self.need_attn = need_attn
586
+
587
+
588
+ def Embedding(num_embeddings, embedding_dim, padding_idx):
589
+ m = nn.Embedding(num_embeddings, embedding_dim, padding_idx=padding_idx)
590
+ nn.init.normal_(m.weight, mean=0, std=embedding_dim**-0.5)
591
+ nn.init.constant_(m.weight[padding_idx], 0)
592
+ return m
593
+
594
+
595
+ def Linear(in_features, out_features, bias=True):
596
+ m = nn.Linear(in_features, out_features, bias)
597
+ nn.init.xavier_uniform_(m.weight)
598
+ if bias:
599
+ nn.init.constant_(m.bias, 0.0)
600
+ return m
data/fairseq/fairseq/model_parallel/models/pipeline_parallel_transformer/model.py ADDED
@@ -0,0 +1,779 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright (c) Facebook, Inc. and its affiliates.
2
+ #
3
+ # This source code is licensed under the MIT license found in the
4
+ # LICENSE file in the root directory of this source tree.
5
+
6
+ import logging
7
+
8
+ import torch
9
+ import torch.nn as nn
10
+ import torch.nn.functional as F
11
+ from fairseq import utils
12
+ from fairseq.model_parallel.models.pipeline_parallel_transformer.layers import (
13
+ Embedding,
14
+ TransformerDecoderEmbedding,
15
+ TransformerDecoderLayer,
16
+ TransformerDecoderOutputLayer,
17
+ TransformerEncoderEmbedding,
18
+ TransformerEncoderLayer,
19
+ TransformerEncoderLayerNorm,
20
+ )
21
+ from fairseq.models import (
22
+ BaseFairseqModel,
23
+ FairseqDecoder,
24
+ FairseqEncoder,
25
+ register_model,
26
+ register_model_architecture,
27
+ )
28
+ from fairseq.models.fairseq_encoder import EncoderOut
29
+ from fairseq.models.transformer import (
30
+ base_architecture,
31
+ transformer_iwslt_de_en,
32
+ transformer_wmt_en_de_big,
33
+ )
34
+ from fairseq.modules import SinusoidalPositionalEmbedding
35
+
36
+
37
+ logger = logging.getLogger(__name__)
38
+
39
+
40
+ DEFAULT_MAX_SOURCE_POSITIONS = 1024
41
+ DEFAULT_MAX_TARGET_POSITIONS = 1024
42
+ TORCH_PIPE = False
43
+ RPC_INIT = False
44
+
45
+
46
+ def import_pipe():
47
+ global TORCH_PIPE
48
+ global RPC_INIT
49
+ try:
50
+ from torch.distributed.pipeline.sync import Pipe # noqa
51
+
52
+ global Pipe
53
+ from torch.distributed.pipeline.sync.utils import partition_model
54
+
55
+ global partition_model
56
+ from torch.distributed import rpc
57
+ import tempfile
58
+
59
+ TORCH_PIPE = True
60
+ # Initialize single process RPC agent since TORCH_PIPE requires
61
+ # RRef. RRef depends on RPC being initialized and as a result we initialize
62
+ # RPC with a single node.
63
+ tmpfile = tempfile.NamedTemporaryFile()
64
+ if not RPC_INIT:
65
+ rpc.init_rpc(
66
+ name="worker",
67
+ rank=0,
68
+ world_size=1,
69
+ rpc_backend_options=rpc.TensorPipeRpcBackendOptions(
70
+ init_method="file://{}".format(tmpfile.name),
71
+ ),
72
+ )
73
+ RPC_INIT = True
74
+ logger.info("Using torch pipe")
75
+ except ImportError:
76
+ try:
77
+ from fairscale.nn import Pipe # noqa
78
+
79
+ logger.info("Using fairscale pipe")
80
+ except ImportError:
81
+ raise ImportError("Please install fairscale with: pip install fairscale")
82
+
83
+
84
+ @register_model("pipeline_parallel_transformer")
85
+ class PipelineParallelTransformerModel(BaseFairseqModel):
86
+ def __init__(self, encoder, decoder, balance, devices, chunks, checkpoint):
87
+ import_pipe()
88
+ super().__init__()
89
+ assert isinstance(encoder, FairseqEncoder)
90
+ assert isinstance(decoder, FairseqDecoder)
91
+ encoder_module_list = (
92
+ [encoder.embedding_layer]
93
+ + list(encoder.encoder_layers)
94
+ + [encoder.final_layer_norm]
95
+ )
96
+ self.num_encoder_modules = len(encoder_module_list)
97
+ decoder_module_list = (
98
+ [decoder.embedding_layer]
99
+ + list(decoder.decoder_layers)
100
+ + [decoder.decoder_output_layer]
101
+ )
102
+ self.num_decoder_modules = len(decoder_module_list)
103
+ module_list = encoder_module_list + decoder_module_list
104
+ self.devices = devices
105
+ if TORCH_PIPE:
106
+ self.model = Pipe(
107
+ partition_model(nn.Sequential(*module_list), balance, devices),
108
+ chunks=chunks,
109
+ checkpoint=checkpoint,
110
+ )
111
+ else:
112
+ self.model = Pipe(
113
+ nn.Sequential(*module_list),
114
+ balance=balance,
115
+ devices=devices,
116
+ chunks=chunks,
117
+ checkpoint=checkpoint,
118
+ )
119
+ self.encoder_max_positions = self.max_positions_helper(
120
+ encoder.embedding_layer, "max_source_positions"
121
+ )
122
+ self.decoder_max_positions = self.max_positions_helper(
123
+ decoder.embedding_layer, "max_target_positions"
124
+ )
125
+ self.adaptive_softmax = getattr(decoder, "adaptive_softmax", None)
126
+ # Note: To be populated during inference
127
+ self.encoder = None
128
+ self.decoder = None
129
+
130
+ def forward(self, src_tokens, src_lengths, prev_output_tokens):
131
+ if self.training:
132
+ input_lst = [src_tokens, src_lengths, prev_output_tokens]
133
+ input = tuple(i.to(self.devices[0], non_blocking=True) for i in input_lst)
134
+ if TORCH_PIPE:
135
+ return self.model(input).local_value()
136
+ else:
137
+ return self.model(input)
138
+ else:
139
+ assert self.encoder is not None and self.decoder is not None, (
140
+ "encoder and decoder need to be initialized by "
141
+ + "calling the `prepare_for_inference_()` method"
142
+ )
143
+ encoder_output_tuple = self.encoder(input)
144
+ return self.decoder(encoder_output_tuple)
145
+
146
+ def prepare_for_inference_(self, cfg):
147
+ if self.encoder is not None and self.decoder is not None:
148
+ logger.info("Encoder and Decoder already initialized")
149
+ return
150
+ encoder_module_list = []
151
+ decoder_module_list = []
152
+ module_count = 0
153
+ for partition in self.model.partitions:
154
+ for module in partition:
155
+ if module_count < self.num_encoder_modules:
156
+ encoder_module_list.append(module)
157
+ else:
158
+ decoder_module_list.append(module)
159
+ module_count += 1
160
+ self.model = None
161
+ self.encoder = TransformerEncoder(
162
+ cfg.distributed_training, None, None, encoder_module_list
163
+ )
164
+ self.decoder = TransformerDecoder(
165
+ cfg.distributed_training,
166
+ None,
167
+ None,
168
+ decoder_module_list=decoder_module_list,
169
+ )
170
+
171
+ @staticmethod
172
+ def add_args(parser):
173
+ """Add model-specific arguments to the parser."""
174
+ # fmt: off
175
+ parser.add_argument('--activation-fn',
176
+ choices=utils.get_available_activation_fns(),
177
+ help='activation function to use')
178
+ parser.add_argument('--dropout', type=float, metavar='D',
179
+ help='dropout probability')
180
+ parser.add_argument('--attention-dropout', type=float, metavar='D',
181
+ help='dropout probability for attention weights')
182
+ parser.add_argument('--activation-dropout', '--relu-dropout', type=float, metavar='D',
183
+ help='dropout probability after activation in FFN.')
184
+ parser.add_argument('--encoder-embed-path', type=str, metavar='STR',
185
+ help='path to pre-trained encoder embedding')
186
+ parser.add_argument('--encoder-embed-dim', type=int, metavar='N',
187
+ help='encoder embedding dimension')
188
+ parser.add_argument('--encoder-ffn-embed-dim', type=int, metavar='N',
189
+ help='encoder embedding dimension for FFN')
190
+ parser.add_argument('--encoder-layers', type=int, metavar='N',
191
+ help='num encoder layers')
192
+ parser.add_argument('--encoder-attention-heads', type=int, metavar='N',
193
+ help='num encoder attention heads')
194
+ parser.add_argument('--encoder-normalize-before', action='store_true',
195
+ help='apply layernorm before each encoder block')
196
+ parser.add_argument('--encoder-learned-pos', action='store_true',
197
+ help='use learned positional embeddings in the encoder')
198
+ parser.add_argument('--decoder-embed-path', type=str, metavar='STR',
199
+ help='path to pre-trained decoder embedding')
200
+ parser.add_argument('--decoder-embed-dim', type=int, metavar='N',
201
+ help='decoder embedding dimension')
202
+ parser.add_argument('--decoder-ffn-embed-dim', type=int, metavar='N',
203
+ help='decoder embedding dimension for FFN')
204
+ parser.add_argument('--decoder-layers', type=int, metavar='N',
205
+ help='num decoder layers')
206
+ parser.add_argument('--decoder-attention-heads', type=int, metavar='N',
207
+ help='num decoder attention heads')
208
+ parser.add_argument('--decoder-learned-pos', action='store_true',
209
+ help='use learned positional embeddings in the decoder')
210
+ parser.add_argument('--decoder-normalize-before', action='store_true',
211
+ help='apply layernorm before each decoder block')
212
+ parser.add_argument('--share-decoder-input-output-embed', action='store_true',
213
+ help='share decoder input and output embeddings')
214
+ parser.add_argument('--share-all-embeddings', action='store_true',
215
+ help='share encoder, decoder and output embeddings'
216
+ ' (requires shared dictionary and embed dim)')
217
+ parser.add_argument('--no-token-positional-embeddings', default=False, action='store_true',
218
+ help='if set, disables positional embeddings (outside self attention)')
219
+ parser.add_argument('--adaptive-softmax-cutoff', metavar='EXPR',
220
+ help='comma separated list of adaptive softmax cutoff points. '
221
+ 'Must be used with adaptive_loss criterion'),
222
+ parser.add_argument('--adaptive-softmax-dropout', type=float, metavar='D',
223
+ help='sets adaptive softmax dropout for the tail projections')
224
+ parser.add_argument('--num-embedding-chunks', type=int, metavar='N', default=1,
225
+ help='Number of embedding layer chunks (enables more even distribution'
226
+ 'of optimizer states across data parallel nodes'
227
+ 'when using optimizer state sharding and'
228
+ 'a big embedding vocabulary)')
229
+ # fmt: on
230
+
231
+ @classmethod
232
+ def build_model_base(cls, args, task):
233
+ """Build a new model instance."""
234
+
235
+ # make sure all arguments are present in older models
236
+ base_architecture(args)
237
+
238
+ if not hasattr(args, "max_source_positions"):
239
+ args.max_source_positions = DEFAULT_MAX_SOURCE_POSITIONS
240
+ if not hasattr(args, "max_target_positions"):
241
+ args.max_target_positions = DEFAULT_MAX_TARGET_POSITIONS
242
+
243
+ src_dict, tgt_dict = task.source_dictionary, task.target_dictionary
244
+
245
+ def build_embedding(dictionary, embed_dim, path=None, num_embed_chunks=1):
246
+ assert embed_dim % num_embed_chunks == 0, (
247
+ f"Number of embedding chunks = {num_embed_chunks} should be "
248
+ + f"divisible by the embedding dimension = {embed_dim}"
249
+ )
250
+ assert path is None or num_embed_chunks == 1, (
251
+ "Loading embedding from a path with number of embedding chunks > 1"
252
+ + " is not yet supported"
253
+ )
254
+ num_embeddings = len(dictionary)
255
+ padding_idx = dictionary.pad()
256
+ # if provided, load from preloaded dictionaries
257
+ if path:
258
+ emb = Embedding(num_embeddings, embed_dim, padding_idx)
259
+ embed_dict = utils.parse_embedding(path)
260
+ utils.load_embedding(embed_dict, dictionary, emb)
261
+ else:
262
+ embed_chunk_dim = embed_dim // num_embed_chunks
263
+ emb = nn.ModuleList()
264
+ for i in range(num_embed_chunks):
265
+ emb.append(Embedding(num_embeddings, embed_chunk_dim, padding_idx))
266
+ return emb
267
+
268
+ num_embed_chunks = args.num_embedding_chunks
269
+ if args.share_all_embeddings:
270
+ if src_dict != tgt_dict:
271
+ raise ValueError("--share-all-embeddings requires a joined dictionary")
272
+ if args.encoder_embed_dim != args.decoder_embed_dim:
273
+ raise ValueError(
274
+ "--share-all-embeddings requires --encoder-embed-dim to match --decoder-embed-dim"
275
+ )
276
+ if args.decoder_embed_path and (
277
+ args.decoder_embed_path != args.encoder_embed_path
278
+ ):
279
+ raise ValueError(
280
+ "--share-all-embeddings not compatible with --decoder-embed-path"
281
+ )
282
+ encoder_embed_tokens = build_embedding(
283
+ src_dict,
284
+ args.encoder_embed_dim,
285
+ args.encoder_embed_path,
286
+ num_embed_chunks,
287
+ )
288
+ decoder_embed_tokens = encoder_embed_tokens
289
+ args.share_decoder_input_output_embed = True
290
+ else:
291
+ assert args.share_decoder_input_output_embed or num_embed_chunks == 1, (
292
+ "Not sharing decoder I/O embeddings is not yet supported with number of "
293
+ + "embedding chunks > 1"
294
+ )
295
+ encoder_embed_tokens = build_embedding(
296
+ src_dict,
297
+ args.encoder_embed_dim,
298
+ args.encoder_embed_path,
299
+ num_embed_chunks,
300
+ )
301
+ decoder_embed_tokens = build_embedding(
302
+ tgt_dict,
303
+ args.decoder_embed_dim,
304
+ args.decoder_embed_path,
305
+ num_embed_chunks,
306
+ )
307
+
308
+ encoder = cls.build_encoder(args, src_dict, encoder_embed_tokens)
309
+ decoder = cls.build_decoder(args, tgt_dict, decoder_embed_tokens)
310
+ return (encoder, decoder)
311
+
312
+ @classmethod
313
+ def build_encoder(cls, args, src_dict, embed_tokens):
314
+ return TransformerEncoder(args, src_dict, embed_tokens)
315
+
316
+ @classmethod
317
+ def build_decoder(cls, args, tgt_dict, embed_tokens):
318
+ return TransformerDecoder(args, tgt_dict, embed_tokens)
319
+
320
+ @classmethod
321
+ def build_model(cls, args, task):
322
+ encoder, decoder = cls.build_model_base(args, task)
323
+ return PipelineParallelTransformerModel(
324
+ encoder=encoder,
325
+ decoder=decoder,
326
+ balance=utils.eval_str_list(args.pipeline_balance, type=int),
327
+ devices=utils.eval_str_list(args.pipeline_devices, type=int),
328
+ chunks=args.pipeline_chunks,
329
+ checkpoint=args.pipeline_checkpoint,
330
+ )
331
+
332
+ def output_layer(self, features, **kwargs):
333
+ """Project features to the default output size (typically vocabulary size)."""
334
+ return self.decoder.output_layer(features, **kwargs)
335
+
336
+ def max_positions(self):
337
+ """Maximum length supported by the model."""
338
+ return (self.encoder_max_positions, self.decoder_max_positions)
339
+
340
+ def max_positions_helper(
341
+ self, embedding_layer, max_positions_field="max_source_positions"
342
+ ):
343
+ """Maximum input length supported by the encoder or decoder."""
344
+ if embedding_layer.embed_positions is None:
345
+ return getattr(embedding_layer, max_positions_field)
346
+ return min(
347
+ getattr(embedding_layer, max_positions_field),
348
+ embedding_layer.embed_positions.max_positions,
349
+ )
350
+
351
+ def get_normalized_probs(self, net_output, log_probs, sample=None):
352
+ """Get normalized probabilities (or log probs) from a net's output."""
353
+
354
+ if hasattr(self, "adaptive_softmax") and self.adaptive_softmax is not None:
355
+ if sample is not None:
356
+ assert "target" in sample
357
+ target = sample["target"]
358
+ else:
359
+ target = None
360
+ out = self.adaptive_softmax.get_log_prob(net_output, target=target)
361
+ return out.exp_() if not log_probs else out
362
+
363
+ # A Pipe() module returns a tuple of tensors as the output.
364
+ # In this case, the tuple has one element - the output tensor of logits
365
+ logits = net_output if isinstance(net_output, torch.Tensor) else net_output[0]
366
+ if log_probs:
367
+ return utils.log_softmax(logits, dim=-1, onnx_trace=False)
368
+ else:
369
+ return utils.softmax(logits, dim=-1, onnx_trace=False)
370
+
371
+ def max_decoder_positions(self):
372
+ """Maximum length supported by the decoder."""
373
+ return self.decoder_max_positions
374
+
375
+ def load_state_dict(self, state_dict, strict=True, model_cfg=None):
376
+ """Copies parameters and buffers from *state_dict* into this module and
377
+ its descendants.
378
+
379
+ Overrides the method in :class:`nn.Module`. Compared with that method
380
+ this additionally "upgrades" *state_dicts* from old checkpoints.
381
+ """
382
+ self.upgrade_state_dict(state_dict)
383
+ is_regular_transformer = not any("model.partitions" in k for k in state_dict)
384
+ if is_regular_transformer:
385
+ state_dict = self.convert_to_pipeline_parallel_state_dict(state_dict)
386
+ return super().load_state_dict(state_dict, strict)
387
+
388
+ def convert_to_pipeline_parallel_state_dict(self, state_dict):
389
+ new_state_dict = self.state_dict()
390
+ encoder_layer_idx = 0
391
+ decoder_layer_idx = 0
392
+ encoder_key_suffixes = [
393
+ "self_attn.k_proj.weight",
394
+ "self_attn.k_proj.bias",
395
+ "self_attn.v_proj.weight",
396
+ "self_attn.v_proj.bias",
397
+ "self_attn.q_proj.weight",
398
+ "self_attn.q_proj.bias",
399
+ "self_attn.out_proj.weight",
400
+ "self_attn.out_proj.bias",
401
+ "self_attn_layer_norm.weight",
402
+ "self_attn_layer_norm.bias",
403
+ "fc1.weight",
404
+ "fc1.bias",
405
+ "fc2.weight",
406
+ "fc2.bias",
407
+ "final_layer_norm.weight",
408
+ "final_layer_norm.bias",
409
+ ]
410
+ decoder_key_suffixes = [
411
+ "self_attn.k_proj.weight",
412
+ "self_attn.k_proj.bias",
413
+ "self_attn.v_proj.weight",
414
+ "self_attn.v_proj.bias",
415
+ "self_attn.q_proj.weight",
416
+ "self_attn.q_proj.bias",
417
+ "self_attn.out_proj.weight",
418
+ "self_attn.out_proj.bias",
419
+ "self_attn_layer_norm.weight",
420
+ "self_attn_layer_norm.bias",
421
+ "encoder_attn.k_proj.weight",
422
+ "encoder_attn.k_proj.bias",
423
+ "encoder_attn.v_proj.weight",
424
+ "encoder_attn.v_proj.bias",
425
+ "encoder_attn.q_proj.weight",
426
+ "encoder_attn.q_proj.bias",
427
+ "encoder_attn.out_proj.weight",
428
+ "encoder_attn.out_proj.bias",
429
+ "encoder_attn_layer_norm.weight",
430
+ "encoder_attn_layer_norm.bias",
431
+ "fc1.weight",
432
+ "fc1.bias",
433
+ "fc2.weight",
434
+ "fc2.bias",
435
+ "final_layer_norm.weight",
436
+ "final_layer_norm.bias",
437
+ ]
438
+ for pid, partition in enumerate(self.model.partitions):
439
+ logger.info(f"Begin Partition {pid}")
440
+ for mid, module in enumerate(partition):
441
+ # fmt: off
442
+ if isinstance(module, TransformerEncoderEmbedding):
443
+ new_state_dict[f'model.partitions.{pid}.{mid}.embed_tokens.weight'] = state_dict['encoder.embed_tokens.weight']
444
+ if isinstance(module, TransformerEncoderLayer):
445
+ for suffix in encoder_key_suffixes:
446
+ new_state_dict[f'model.partitions.{pid}.{mid}.{suffix}'] = state_dict[f'encoder.layers.{encoder_layer_idx}.{suffix}']
447
+ encoder_layer_idx += 1
448
+ if isinstance(module, TransformerDecoderLayer):
449
+ for suffix in decoder_key_suffixes:
450
+ new_state_dict[f'model.partitions.{pid}.{mid}.{suffix}'] = state_dict[f'decoder.layers.{decoder_layer_idx}.{suffix}']
451
+ decoder_layer_idx += 1
452
+ if isinstance(module, TransformerEncoderLayerNorm):
453
+ if 'encoder.layer_norm.weight' in state_dict:
454
+ new_state_dict[f'model.partitions.{pid}.{mid}.layer_norm.weight'] = state_dict['encoder.layer_norm.weight']
455
+ new_state_dict[f'model.partitions.{pid}.{mid}.layer_norm.bias'] = state_dict['encoder.layer_norm.bias']
456
+ if isinstance(module, TransformerDecoderEmbedding):
457
+ new_state_dict[f'model.partitions.{pid}.{mid}.embed_tokens.weight'] = state_dict['decoder.embed_tokens.weight']
458
+ if isinstance(module, TransformerDecoderOutputLayer):
459
+ new_state_dict[f'model.partitions.{pid}.{mid}.output_projection.weight'] = state_dict['decoder.output_projection.weight']
460
+ # fmt: on
461
+ return new_state_dict
462
+
463
+
464
+ class TransformerEncoder(FairseqEncoder):
465
+ """
466
+ Transformer encoder consisting of *args.encoder_layers* layers. Each layer
467
+ is a :class:`TransformerEncoderLayer`.
468
+
469
+ Args:
470
+ args (argparse.Namespace): parsed command-line arguments
471
+ dictionary (~fairseq.data.Dictionary): encoding dictionary
472
+ embed_tokens (torch.nn.Embedding): input embedding
473
+ """
474
+
475
+ def __init__(self, args, dictionary, embed_tokens, encoder_module_list=None):
476
+ super().__init__(dictionary)
477
+ self.register_buffer("version", torch.Tensor([3]))
478
+ import_pipe()
479
+ self.use_pipeline = encoder_module_list is not None
480
+ if not self.use_pipeline:
481
+ self.embedding_layer = TransformerEncoderEmbedding(args, embed_tokens)
482
+ self.encoder_layers = nn.Sequential(
483
+ *[TransformerEncoderLayer(args) for i in range(args.encoder_layers)]
484
+ )
485
+ if isinstance(embed_tokens, nn.ModuleList):
486
+ emb_dim = sum(e.embedding_dim for e in embed_tokens)
487
+ else:
488
+ emb_dim = embed_tokens.embedding_dim
489
+ self.final_layer_norm = TransformerEncoderLayerNorm(args, emb_dim)
490
+ else:
491
+ encoder_balance = utils.eval_str_list(
492
+ args.pipeline_encoder_balance, type=int
493
+ )
494
+ encoder_devices = utils.eval_str_list(
495
+ args.pipeline_encoder_devices, type=int
496
+ )
497
+ assert sum(encoder_balance) == len(encoder_module_list), (
498
+ f"Sum of encoder_balance={encoder_balance} is not equal "
499
+ + f"to num_encoder_modules={len(encoder_module_list)}"
500
+ )
501
+ if TORCH_PIPE:
502
+ self.model = Pipe(
503
+ module=partition_model(
504
+ nn.Sequential(*encoder_module_list),
505
+ encoder_balance,
506
+ encoder_devices,
507
+ ),
508
+ chunks=args.pipeline_chunks,
509
+ checkpoint=args.pipeline_checkpoint,
510
+ )
511
+ else:
512
+ self.model = Pipe(
513
+ module=nn.Sequential(*encoder_module_list),
514
+ balance=encoder_balance,
515
+ devices=encoder_devices,
516
+ chunks=args.pipeline_chunks,
517
+ checkpoint=args.pipeline_checkpoint,
518
+ )
519
+
520
+ def forward(self, src_tokens, src_lengths):
521
+ """
522
+ Args:
523
+ input_tuple(
524
+ src_tokens (LongTensor): tokens in the source language of shape
525
+ `(batch, src_len)`
526
+ src_lengths (torch.LongTensor): lengths of each source sentence of
527
+ shape `(batch)`
528
+ )
529
+
530
+ Returns:
531
+ output_tuple(
532
+ - **encoder_out** (Tensor): the last encoder layer's output of
533
+ shape `(src_len, batch, embed_dim)`
534
+ - **encoder_padding_mask** (ByteTensor): the positions of
535
+ padding elements of shape `(batch, src_len)`
536
+ - prev_output_tokens
537
+ - **encoder_states** (List[Tensor]): all intermediate
538
+ hidden states of shape `(src_len, batch, embed_dim)`.
539
+ Only populated if *return_all_hiddens* is True.
540
+ )
541
+ """
542
+ dummy_prev_output_tokens = torch.zeros(
543
+ 1, dtype=src_tokens.dtype, device=src_tokens.device
544
+ )
545
+ input_tuple = (src_tokens, src_lengths, dummy_prev_output_tokens)
546
+ if self.use_pipeline:
547
+ input_tuple = tuple(i.to(self.model.devices[0]) for i in input_tuple)
548
+ if TORCH_PIPE:
549
+ encoder_out = self.model(input_tuple).local_value()
550
+ else:
551
+ encoder_out = self.model(input_tuple)
552
+ else:
553
+ encoder_embed_output_tuple = self.embedding_layer(input_tuple)
554
+ encoder_layers_output = self.encoder_layers(encoder_embed_output_tuple)
555
+ encoder_out = self.final_layer_norm(encoder_layers_output)
556
+ # first element is the encoder output
557
+ # second element is the encoder padding mask
558
+ # the remaining elements of EncoderOut are not computed by
559
+ # the PipelineParallelTransformer
560
+ return EncoderOut(encoder_out[0], encoder_out[1], None, None, None, None)
561
+
562
+ def reorder_encoder_out(self, encoder_out, new_order):
563
+ """
564
+ Reorder encoder output according to *new_order*.
565
+
566
+ Args:
567
+ encoder_out: output from the ``forward()`` method
568
+ new_order (LongTensor): desired order
569
+
570
+ Returns:
571
+ *encoder_out* rearranged according to *new_order*
572
+ """
573
+ if encoder_out.encoder_out is not None:
574
+ encoder_out = encoder_out._replace(
575
+ encoder_out=encoder_out.encoder_out.index_select(1, new_order)
576
+ )
577
+ if encoder_out.encoder_padding_mask is not None:
578
+ encoder_out = encoder_out._replace(
579
+ encoder_padding_mask=encoder_out.encoder_padding_mask.index_select(
580
+ 0, new_order
581
+ )
582
+ )
583
+ if encoder_out.encoder_embedding is not None:
584
+ encoder_out = encoder_out._replace(
585
+ encoder_embedding=encoder_out.encoder_embedding.index_select(
586
+ 0, new_order
587
+ )
588
+ )
589
+ if encoder_out.encoder_states is not None:
590
+ for idx, state in enumerate(encoder_out.encoder_states):
591
+ encoder_out.encoder_states[idx] = state.index_select(1, new_order)
592
+ return encoder_out
593
+
594
+ def max_positions(self):
595
+ """Maximum input length supported by the encoder."""
596
+ if self.embedding_layer.embed_positions is None:
597
+ return self.embedding_layer.max_source_positions
598
+ return min(
599
+ self.embedding_layer.max_source_positions,
600
+ self.embedding_layer.embed_positions.max_positions,
601
+ )
602
+
603
+
604
+ class TransformerDecoder(FairseqDecoder):
605
+ """
606
+ Transformer decoder consisting of *args.decoder_layers* layers. Each layer
607
+ is a :class:`TransformerDecoderLayer`.
608
+
609
+ Args:
610
+ args (argparse.Namespace): parsed command-line arguments
611
+ dictionary (~fairseq.data.Dictionary): decoding dictionary
612
+ embed_tokens (torch.nn.Embedding): output embedding
613
+ no_encoder_attn (bool, optional): whether to attend to encoder outputs
614
+ (default: False).
615
+ """
616
+
617
+ def __init__(
618
+ self,
619
+ args,
620
+ dictionary,
621
+ embed_tokens,
622
+ no_encoder_attn=False,
623
+ decoder_module_list=None,
624
+ ):
625
+ super().__init__(dictionary)
626
+ self.register_buffer("version", torch.Tensor([3]))
627
+ import_pipe()
628
+ self.use_pipeline = decoder_module_list is not None
629
+ if not self.use_pipeline:
630
+ self.embedding_layer = TransformerDecoderEmbedding(args, embed_tokens)
631
+ self.decoder_layers = nn.Sequential(
632
+ *[
633
+ TransformerDecoderLayer(args, no_encoder_attn)
634
+ for _ in range(args.decoder_layers)
635
+ ]
636
+ )
637
+ self.decoder_output_layer = TransformerDecoderOutputLayer(
638
+ args, embed_tokens, dictionary
639
+ )
640
+ else:
641
+ decoder_balance = utils.eval_str_list(
642
+ args.pipeline_decoder_balance, type=int
643
+ )
644
+ decoder_devices = utils.eval_str_list(
645
+ args.pipeline_decoder_devices, type=int
646
+ )
647
+ assert sum(decoder_balance) == len(decoder_module_list), (
648
+ f"Sum of decoder_balance={decoder_balance} is not equal "
649
+ + f"to num_decoder_modules={len(decoder_module_list)}"
650
+ )
651
+ if TORCH_PIPE:
652
+ self.model = Pipe(
653
+ module=partition_model(
654
+ nn.Sequential(*decoder_module_list),
655
+ decoder_balance,
656
+ decoder_devices,
657
+ ),
658
+ chunks=args.pipeline_chunks,
659
+ checkpoint=args.pipeline_checkpoint,
660
+ )
661
+ else:
662
+ self.model = Pipe(
663
+ module=nn.Sequential(*decoder_module_list),
664
+ balance=decoder_balance,
665
+ devices=decoder_devices,
666
+ chunks=args.pipeline_chunks,
667
+ checkpoint=args.pipeline_checkpoint,
668
+ )
669
+
670
+ def forward(
671
+ self,
672
+ prev_output_tokens,
673
+ encoder_out=None,
674
+ ):
675
+ """
676
+ Args:
677
+ prev_output_tokens (LongTensor): previous decoder outputs of shape
678
+ `(batch, tgt_len)`, for teacher forcing
679
+ encoder_out (optional): output from the encoder, used for
680
+ encoder-side attention
681
+ incremental_state (dict): dictionary used for storing state during
682
+ :ref:`Incremental decoding`
683
+ features_only (bool, optional): only return features without
684
+ applying output layer (default: False).
685
+
686
+ Returns:
687
+ tuple:
688
+ - the decoder's output of shape `(batch, tgt_len, vocab)`
689
+ - a dictionary with any model-specific outputs
690
+ """
691
+ input_tuple = (
692
+ encoder_out.encoder_out,
693
+ encoder_out.encoder_padding_mask,
694
+ prev_output_tokens,
695
+ )
696
+ if self.use_pipeline:
697
+ input_tuple = tuple(i.to(self.model.devices[0]) for i in input_tuple)
698
+ if TORCH_PIPE:
699
+ return (self.model(input_tuple).local_value(),)
700
+ else:
701
+ return (self.model(input_tuple),)
702
+ else:
703
+ embed_layer_output = self.embedding_layer(input_tuple)
704
+ state = self.decoder_layers(embed_layer_output)
705
+ return (self.decoder_output_layer(state),)
706
+
707
+ def output_layer(self, features, **kwargs):
708
+ """Project features to the vocabulary size."""
709
+ if self.adaptive_softmax is None:
710
+ # project back to size of vocabulary
711
+ if self.share_input_output_embed:
712
+ return F.linear(features, self.embed_tokens.weight)
713
+ else:
714
+ return F.linear(features, self.embed_out)
715
+ else:
716
+ return features
717
+
718
+ def max_positions(self):
719
+ """Maximum output length supported by the decoder."""
720
+ if self.embedding_layer.embed_positions is None:
721
+ return self.embedding_layer.max_target_positions
722
+ return min(
723
+ self.embedding_layer.max_target_positions,
724
+ self.embedding_layer.embed_positions.max_positions,
725
+ )
726
+
727
+ def buffered_future_mask(self, tensor):
728
+ dim = tensor.size(0)
729
+ if (
730
+ not hasattr(self, "_future_mask")
731
+ or self._future_mask is None
732
+ or self._future_mask.device != tensor.device
733
+ or self._future_mask.size(0) < dim
734
+ ):
735
+ self._future_mask = torch.triu(
736
+ utils.fill_with_neg_inf(tensor.new(dim, dim)), 1
737
+ )
738
+ return self._future_mask[:dim, :dim]
739
+
740
+ def upgrade_state_dict_named(self, state_dict, name):
741
+ """Upgrade a (possibly old) state dict for new versions of fairseq."""
742
+ for i in range(len(self.layers)):
743
+ # update layer norms
744
+ layer_norm_map = {
745
+ "0": "self_attn_layer_norm",
746
+ "1": "encoder_attn_layer_norm",
747
+ "2": "final_layer_norm",
748
+ }
749
+ for old, new in layer_norm_map.items():
750
+ for m in ("weight", "bias"):
751
+ k = "{}.layers.{}.layer_norms.{}.{}".format(name, i, old, m)
752
+ if k in state_dict:
753
+ state_dict[
754
+ "{}.layers.{}.{}.{}".format(name, i, new, m)
755
+ ] = state_dict[k]
756
+ del state_dict[k]
757
+
758
+ version_key = "{}.version".format(name)
759
+ if utils.item(state_dict.get(version_key, torch.Tensor([1]))[0]) <= 2:
760
+ # earlier checkpoints did not normalize after the stack of layers
761
+ self.layer_norm = None
762
+ self.normalize = False
763
+ state_dict[version_key] = torch.Tensor([1])
764
+
765
+ return state_dict
766
+
767
+
768
+ @register_model_architecture(
769
+ "pipeline_parallel_transformer", "transformer_iwslt_de_en_pipeline_parallel"
770
+ )
771
+ def transformer_iwslt_de_en_dist(args):
772
+ transformer_iwslt_de_en(args)
773
+
774
+
775
+ @register_model_architecture(
776
+ "pipeline_parallel_transformer", "transformer_wmt_en_de_big_pipeline_parallel"
777
+ )
778
+ def transformer_wmt_en_de_big_dist(args):
779
+ transformer_wmt_en_de_big(args)
data/fairseq/fairseq/model_parallel/models/roberta/__init__.py ADDED
@@ -0,0 +1,6 @@
 
 
 
 
 
 
 
1
+ # Copyright (c) Facebook, Inc. and its affiliates.
2
+ #
3
+ # This source code is licensed under the MIT license found in the
4
+ # LICENSE file in the root directory of this source tree.
5
+
6
+ from .model import * # noqa
data/fairseq/fairseq/model_parallel/models/roberta/__pycache__/__init__.cpython-38.pyc ADDED
Binary file (206 Bytes). View file
 
data/fairseq/fairseq/model_parallel/models/roberta/__pycache__/model.cpython-38.pyc ADDED
Binary file (7.41 kB). View file
 
data/fairseq/fairseq/model_parallel/models/roberta/model.py ADDED
@@ -0,0 +1,225 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright (c) Facebook, Inc. and its affiliates.
2
+ #
3
+ # This source code is licensed under the MIT license found in the
4
+ # LICENSE file in the root directory of this source tree.
5
+ """
6
+ RoBERTa: A Robustly Optimized BERT Pretraining Approach.
7
+ """
8
+
9
+ import logging
10
+
11
+ import torch
12
+ import torch.nn as nn
13
+ import torch.nn.functional as F
14
+ from fairseq import utils
15
+ from fairseq.model_parallel.models.transformer import ModelParallelTransformerEncoder
16
+ from fairseq.models import register_model, register_model_architecture
17
+ from fairseq.models.roberta import (
18
+ roberta_base_architecture,
19
+ roberta_prenorm_architecture,
20
+ RobertaEncoder,
21
+ RobertaModel,
22
+ )
23
+ from fairseq.modules import LayerNorm
24
+
25
+
26
+ try:
27
+ from fairseq.model_parallel.megatron.mpu import (
28
+ copy_to_model_parallel_region,
29
+ gather_from_model_parallel_region,
30
+ ColumnParallelLinear,
31
+ VocabParallelEmbedding,
32
+ )
33
+
34
+ has_megatron_submodule = True
35
+ except (ImportError, ModuleNotFoundError):
36
+ has_megatron_submodule = False
37
+
38
+ logger = logging.getLogger(__name__)
39
+
40
+
41
+ @register_model("model_parallel_roberta")
42
+ class ModelParallelRobertaModel(RobertaModel):
43
+ def __init__(self, args, encoder):
44
+ super().__init__(args, encoder)
45
+
46
+ self.classification_heads = nn.ModuleDict()
47
+
48
+ @staticmethod
49
+ def add_args(parser):
50
+ RobertaModel.add_args(parser)
51
+ parser.add_argument(
52
+ "--no-final-layer-norm",
53
+ action="store_true",
54
+ help=(
55
+ "don't add final layernorm (only applicable when "
56
+ "--encoder-normalize-before=True"
57
+ ),
58
+ )
59
+
60
+ @classmethod
61
+ def build_model(cls, args, task):
62
+ """Build a new model instance."""
63
+
64
+ # make sure all arguments are present
65
+ base_architecture(args)
66
+
67
+ task.source_dictionary.pad_to_multiple_(args.model_parallel_size * 8)
68
+ task.target_dictionary.pad_to_multiple_(args.model_parallel_size * 8)
69
+
70
+ if not hasattr(args, "max_positions"):
71
+ args.max_positions = args.tokens_per_sample
72
+
73
+ if getattr(args, "untie_weights_roberta", False):
74
+ raise NotImplementedError(
75
+ "--untie-weights-roberta is not supported in model parallel mode"
76
+ )
77
+
78
+ encoder = ModelParallelRobertaEncoder(args, task.source_dictionary)
79
+ return cls(args, encoder)
80
+
81
+ def forward(
82
+ self,
83
+ src_tokens,
84
+ features_only=False,
85
+ return_all_hiddens=False,
86
+ classification_head_name=None,
87
+ **kwargs
88
+ ):
89
+ if classification_head_name is not None:
90
+ features_only = True
91
+
92
+ x, extra = self.encoder(src_tokens, features_only, return_all_hiddens, **kwargs)
93
+
94
+ if classification_head_name is not None:
95
+ x = self.classification_heads[classification_head_name](x)
96
+ return x, extra
97
+
98
+ def register_classification_head(
99
+ self, name, num_classes=None, inner_dim=None, **kwargs
100
+ ):
101
+ """Register a classification head."""
102
+ if name in self.classification_heads:
103
+ prev_num_classes = self.classification_heads[name].out_proj.out_features
104
+ prev_inner_dim = self.classification_heads[name].dense.out_features
105
+ if num_classes != prev_num_classes or inner_dim != prev_inner_dim:
106
+ logger.warning(
107
+ 're-registering head "{}" with num_classes {} (prev: {}) '
108
+ "and inner_dim {} (prev: {})".format(
109
+ name, num_classes, prev_num_classes, inner_dim, prev_inner_dim
110
+ )
111
+ )
112
+ self.classification_heads[name] = ModelParallelRobertaClassificationHead(
113
+ self.args.encoder_embed_dim,
114
+ inner_dim or self.args.encoder_embed_dim,
115
+ num_classes,
116
+ self.args.pooler_activation_fn,
117
+ self.args.pooler_dropout,
118
+ )
119
+
120
+
121
+ class ModelParallelRobertaLMHead(nn.Module):
122
+ """Head for masked language modeling."""
123
+
124
+ def __init__(self, embed_dim, output_dim, activation_fn, weight=None):
125
+ super().__init__()
126
+ self.dense = ColumnParallelLinear(embed_dim, embed_dim, gather_output=True)
127
+ self.activation_fn = utils.get_activation_fn(activation_fn)
128
+ self.layer_norm = LayerNorm(embed_dim)
129
+
130
+ if weight is None:
131
+ weight = nn.Linear(embed_dim, output_dim, bias=False).weight
132
+ self.weight = weight
133
+ self.bias = nn.Parameter(torch.zeros(output_dim))
134
+
135
+ def forward(self, features, masked_tokens=None, **kwargs):
136
+ # Only project the unmasked tokens while training,
137
+ # saves both memory and computation
138
+ if masked_tokens is not None:
139
+ features = features[masked_tokens, :]
140
+
141
+ x = self.dense(features)
142
+ x = self.activation_fn(x)
143
+ x = self.layer_norm(x)
144
+
145
+ x = copy_to_model_parallel_region(x)
146
+ # project back to size of vocabulary with bias
147
+ x = F.linear(x, self.weight)
148
+ x = gather_from_model_parallel_region(x).contiguous()
149
+ x = x + self.bias
150
+ return x
151
+
152
+
153
+ class ModelParallelRobertaClassificationHead(nn.Module):
154
+ """Head for sentence-level classification tasks."""
155
+
156
+ def __init__(
157
+ self, input_dim, inner_dim, num_classes, activation_fn, pooler_dropout
158
+ ):
159
+ super().__init__()
160
+ self.dense = ColumnParallelLinear(input_dim, inner_dim, gather_output=True)
161
+ self.activation_fn = utils.get_activation_fn(activation_fn)
162
+ self.dropout = nn.Dropout(p=pooler_dropout)
163
+ self.out_proj = nn.Linear(inner_dim, num_classes)
164
+
165
+ def forward(self, features, **kwargs):
166
+ x = features[:, 0, :] # take <s> token (equiv. to [CLS])
167
+ x = self.dropout(x)
168
+ x = self.dense(x)
169
+ x = self.activation_fn(x)
170
+ x = self.dropout(x)
171
+ x = self.out_proj(x)
172
+ return x
173
+
174
+
175
+ class ModelParallelRobertaEncoder(RobertaEncoder):
176
+ """RoBERTa encoder."""
177
+
178
+ def __init__(self, args, dictionary):
179
+ super().__init__(args, dictionary)
180
+ assert not self.args.untie_weights_roberta
181
+
182
+ def build_embedding(self, vocab_size, embedding_dim, padding_idx):
183
+ return VocabParallelEmbedding(vocab_size, embedding_dim, padding_idx)
184
+
185
+ def build_encoder(self, args, dictionary, embed_tokens):
186
+ return ModelParallelTransformerEncoder(args, dictionary, embed_tokens)
187
+
188
+ def build_lm_head(self, embed_dim, output_dim, activation_fn, weight):
189
+ return ModelParallelRobertaLMHead(embed_dim, output_dim, activation_fn, weight)
190
+
191
+
192
+ @register_model_architecture("model_parallel_roberta", "model_parallel_roberta")
193
+ def base_architecture(args):
194
+ args.no_final_layer_norm = getattr(args, "no_final_layer_norm", False)
195
+ # model parallel RoBERTa defaults to "Pre-LN" formulation
196
+ roberta_prenorm_architecture(args)
197
+
198
+
199
+ # earlier versions of model parallel RoBERTa removed the final layer norm
200
+ @register_model_architecture("model_parallel_roberta", "model_parallel_roberta_v1")
201
+ def model_parallel_roberta_v1_architecture(args):
202
+ args.no_final_layer_norm = getattr(args, "no_final_layer_norm", True)
203
+ base_architecture(args)
204
+
205
+
206
+ @register_model_architecture(
207
+ "model_parallel_roberta", "model_parallel_roberta_postnorm"
208
+ )
209
+ def model_parallel_roberta_postnorm_architecture(args):
210
+ # the original BERT/RoBERTa uses the "Post-LN" formulation
211
+ roberta_base_architecture(args)
212
+
213
+
214
+ @register_model_architecture("model_parallel_roberta", "model_parallel_roberta_base")
215
+ def model_parallel_roberta_base_architecture(args):
216
+ base_architecture(args)
217
+
218
+
219
+ @register_model_architecture("model_parallel_roberta", "model_parallel_roberta_large")
220
+ def model_parallel_roberta_large_architecture(args):
221
+ args.encoder_layers = getattr(args, "encoder_layers", 24)
222
+ args.encoder_embed_dim = getattr(args, "encoder_embed_dim", 1024)
223
+ args.encoder_ffn_embed_dim = getattr(args, "encoder_ffn_embed_dim", 4096)
224
+ args.encoder_attention_heads = getattr(args, "encoder_attention_heads", 16)
225
+ base_architecture(args)
data/fairseq/fairseq/model_parallel/modules/__init__.py ADDED
@@ -0,0 +1,17 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright (c) Facebook, Inc. and its affiliates.
2
+ #
3
+ # This source code is licensed under the MIT license found in the
4
+ # LICENSE file in the root directory of this source tree.
5
+ """isort:skip_file"""
6
+
7
+ from .multihead_attention import ModelParallelMultiheadAttention
8
+ from .transformer_layer import (
9
+ ModelParallelTransformerEncoderLayer,
10
+ ModelParallelTransformerDecoderLayer,
11
+ )
12
+
13
+ __all__ = [
14
+ "ModelParallelMultiheadAttention",
15
+ "ModelParallelTransformerEncoderLayer",
16
+ "ModelParallelTransformerDecoderLayer",
17
+ ]
data/fairseq/fairseq/model_parallel/modules/multihead_attention.py ADDED
@@ -0,0 +1,349 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright (c) Facebook, Inc. and its affiliates.
2
+ #
3
+ # This source code is licensed under the MIT license found in the
4
+ # LICENSE file in the root directory of this source tree.
5
+
6
+ from typing import Dict, Optional, Tuple
7
+
8
+ import torch
9
+ import torch.nn.functional as F
10
+ from torch import Tensor, nn
11
+
12
+ from fairseq import utils
13
+ from fairseq.incremental_decoding_utils import with_incremental_state
14
+ from fairseq.modules.fairseq_dropout import FairseqDropout
15
+
16
+ try:
17
+ from fairseq.model_parallel.megatron.mpu import (
18
+ ColumnParallelLinear,
19
+ RowParallelLinear,
20
+ get_cuda_rng_tracker,
21
+ get_model_parallel_world_size,
22
+ )
23
+
24
+ has_megatron_submodule = True
25
+ except (ImportError, ModuleNotFoundError):
26
+ has_megatron_submodule = False
27
+
28
+
29
+ @with_incremental_state
30
+ class ModelParallelMultiheadAttention(nn.Module):
31
+ """Model parallel Multi-headed attention.
32
+ This performs the Multi-headed attention over multiple gpus.
33
+
34
+ See "Megatron-LM: https://arxiv.org/pdf/1909.08053.pdf" for more details.
35
+ """
36
+
37
+ def __init__(
38
+ self,
39
+ embed_dim,
40
+ num_heads,
41
+ kdim=None,
42
+ vdim=None,
43
+ dropout=0.0,
44
+ bias=True,
45
+ self_attention=False,
46
+ encoder_decoder_attention=False,
47
+ ):
48
+ super().__init__()
49
+ if not has_megatron_submodule:
50
+ raise ImportError(
51
+ "\n\nPlease install the megatron submodule:"
52
+ "\n\n git submodule update --init "
53
+ "fairseq/model_parallel/megatron"
54
+ )
55
+ self.embed_dim = embed_dim
56
+ self.kdim = kdim if kdim is not None else embed_dim
57
+ self.vdim = vdim if vdim is not None else embed_dim
58
+ self.qkv_same_dim = self.kdim == embed_dim and self.vdim == embed_dim
59
+
60
+ self.model_parallel_size = get_model_parallel_world_size()
61
+
62
+ self.num_heads_partition = num_heads // self.model_parallel_size
63
+ assert (
64
+ self.num_heads_partition * self.model_parallel_size == num_heads
65
+ ), "Number of heads must be divisible by model parallel size"
66
+
67
+ self.dropout_module = FairseqDropout(
68
+ dropout, module_name=self.__class__.__name__
69
+ )
70
+ self.head_dim = embed_dim // num_heads
71
+ assert (
72
+ self.head_dim * num_heads == self.embed_dim
73
+ ), "embed_dim must be divisible by num_heads"
74
+ self.scaling = self.head_dim**-0.5
75
+
76
+ self.self_attention = self_attention
77
+ self.encoder_decoder_attention = encoder_decoder_attention
78
+
79
+ assert (
80
+ not self.self_attention or self.qkv_same_dim
81
+ ), "Self-attention requires query, key and value to be of the same size"
82
+
83
+ self.k_proj = ColumnParallelLinear(
84
+ self.kdim, embed_dim, bias=bias, gather_output=False
85
+ )
86
+ self.v_proj = ColumnParallelLinear(
87
+ self.vdim, embed_dim, bias=bias, gather_output=False
88
+ )
89
+ self.q_proj = ColumnParallelLinear(
90
+ embed_dim, embed_dim, bias=bias, gather_output=False
91
+ )
92
+ self.out_proj = RowParallelLinear(
93
+ embed_dim, embed_dim, bias=bias, input_is_parallel=True
94
+ )
95
+
96
+ def forward(
97
+ self,
98
+ query,
99
+ key: Optional[Tensor],
100
+ value: Optional[Tensor],
101
+ key_padding_mask: Optional[Tensor] = None,
102
+ incremental_state: Optional[Dict[str, Dict[str, Optional[Tensor]]]] = None,
103
+ static_kv: bool = False,
104
+ attn_mask: Optional[Tensor] = None,
105
+ **unused_kwargs,
106
+ ) -> Tuple[Tensor, Optional[Tensor]]:
107
+ """Input shape: Time x Batch x Channel
108
+
109
+ Args:
110
+ key_padding_mask (ByteTensor, optional): mask to exclude
111
+ keys that are pads, of shape `(batch, src_len)`, where
112
+ padding elements are indicated by 1s.
113
+ attn_mask (ByteTensor, optional): typically used to
114
+ implement causal attention, where the mask prevents the
115
+ attention from looking forward in time (default: None).
116
+ """
117
+ tgt_len, bsz, embed_dim = query.size()
118
+ assert embed_dim == self.embed_dim
119
+ assert list(query.size()) == [tgt_len, bsz, embed_dim]
120
+
121
+ is_tpu = query.device.type == "xla"
122
+
123
+ if incremental_state is not None:
124
+ saved_state = self._get_input_buffer(incremental_state)
125
+ if saved_state is not None and "prev_key" in saved_state:
126
+ # previous time steps are cached - no need to recompute
127
+ # key and value if they are static
128
+ if static_kv:
129
+ assert self.encoder_decoder_attention and not self.self_attention
130
+ key = value = None
131
+ else:
132
+ saved_state = None
133
+
134
+ if self.self_attention:
135
+ q = self.q_proj(query)
136
+ k = self.k_proj(query)
137
+ v = self.v_proj(query)
138
+ elif self.encoder_decoder_attention:
139
+ # encoder-decoder attention
140
+ q = self.q_proj(query)
141
+ if key is None:
142
+ assert value is None
143
+ k = v = None
144
+ else:
145
+ k = self.k_proj(key)
146
+ v = self.v_proj(key)
147
+
148
+ else:
149
+ assert key is not None and value is not None
150
+ q = self.q_proj(query)
151
+ k = self.k_proj(key)
152
+ v = self.v_proj(value)
153
+ q *= self.scaling
154
+
155
+ q = (
156
+ q.contiguous()
157
+ .view(tgt_len, bsz * self.num_heads_partition, self.head_dim)
158
+ .transpose(0, 1)
159
+ )
160
+ if k is not None:
161
+ k = (
162
+ k.contiguous()
163
+ .view(-1, bsz * self.num_heads_partition, self.head_dim)
164
+ .transpose(0, 1)
165
+ )
166
+ if v is not None:
167
+ v = (
168
+ v.contiguous()
169
+ .view(-1, bsz * self.num_heads_partition, self.head_dim)
170
+ .transpose(0, 1)
171
+ )
172
+
173
+ if saved_state is not None:
174
+ # saved states are stored with shape (bsz, num_heads_partition, seq_len, head_dim)
175
+ if "prev_key" in saved_state:
176
+ _prev_key = saved_state["prev_key"]
177
+ assert _prev_key is not None
178
+ prev_key = _prev_key.view(
179
+ bsz * self.num_heads_partition, -1, self.head_dim
180
+ )
181
+ if static_kv:
182
+ k = prev_key
183
+ else:
184
+ assert k is not None
185
+ k = torch.cat([prev_key, k], dim=1)
186
+ if "prev_value" in saved_state:
187
+ _prev_value = saved_state["prev_value"]
188
+ assert _prev_value is not None
189
+ prev_value = _prev_value.view(
190
+ bsz * self.num_heads_partition, -1, self.head_dim
191
+ )
192
+ if static_kv:
193
+ v = prev_value
194
+ else:
195
+ assert v is not None
196
+ v = torch.cat([prev_value, v], dim=1)
197
+ prev_key_padding_mask: Optional[Tensor] = None
198
+ if "prev_key_padding_mask" in saved_state:
199
+ prev_key_padding_mask = saved_state["prev_key_padding_mask"]
200
+ assert k is not None and v is not None
201
+ key_padding_mask = (
202
+ ModelParallelMultiheadAttention._append_prev_key_padding_mask(
203
+ key_padding_mask=key_padding_mask,
204
+ prev_key_padding_mask=prev_key_padding_mask,
205
+ batch_size=bsz,
206
+ src_len=k.size(1),
207
+ static_kv=static_kv,
208
+ )
209
+ )
210
+
211
+ saved_state["prev_key"] = k.view(
212
+ bsz, self.num_heads_partition, -1, self.head_dim
213
+ )
214
+ saved_state["prev_value"] = v.view(
215
+ bsz, self.num_heads_partition, -1, self.head_dim
216
+ )
217
+ saved_state["prev_key_padding_mask"] = key_padding_mask
218
+ # In this branch incremental_state is never None
219
+ assert incremental_state is not None
220
+ incremental_state = self._set_input_buffer(incremental_state, saved_state)
221
+ assert k is not None
222
+ src_len = k.size(1)
223
+
224
+ # This is part of a workaround to get around fork/join parallelism
225
+ # not supporting Optional types.
226
+ if key_padding_mask is not None and key_padding_mask.dim() == 0:
227
+ key_padding_mask = None
228
+
229
+ if key_padding_mask is not None:
230
+ assert key_padding_mask.size(0) == bsz
231
+ assert key_padding_mask.size(1) == src_len
232
+
233
+ attn_weights = torch.bmm(q, k.transpose(1, 2))
234
+
235
+ assert list(attn_weights.size()) == [
236
+ bsz * self.num_heads_partition,
237
+ tgt_len,
238
+ src_len,
239
+ ]
240
+
241
+ if attn_mask is not None:
242
+ attn_mask = attn_mask.unsqueeze(0)
243
+ attn_weights += attn_mask
244
+
245
+ if key_padding_mask is not None:
246
+ # don't attend to padding symbols
247
+ attn_weights = attn_weights.view(
248
+ bsz, self.num_heads_partition, tgt_len, src_len
249
+ )
250
+ if not is_tpu:
251
+ attn_weights = attn_weights.masked_fill(
252
+ key_padding_mask.unsqueeze(1).unsqueeze(2).to(torch.bool),
253
+ float("-inf"),
254
+ )
255
+ else:
256
+ attn_weights = attn_weights.transpose(0, 2)
257
+ attn_weights = attn_weights.masked_fill(key_padding_mask, float("-inf"))
258
+ attn_weights = attn_weights.transpose(0, 2)
259
+ attn_weights = attn_weights.view(
260
+ bsz * self.num_heads_partition, tgt_len, src_len
261
+ )
262
+
263
+ attn_weights_float = utils.softmax(attn_weights, dim=-1)
264
+ attn_weights = attn_weights_float.type_as(attn_weights)
265
+
266
+ with get_cuda_rng_tracker().fork():
267
+ attn_probs = self.dropout_module(attn_weights)
268
+
269
+ assert v is not None
270
+ attn = torch.bmm(attn_probs, v)
271
+ assert list(attn.size()) == [
272
+ bsz * self.num_heads_partition,
273
+ tgt_len,
274
+ self.head_dim,
275
+ ]
276
+ embed_dim_partition = embed_dim // self.model_parallel_size
277
+ attn = attn.transpose(0, 1).contiguous().view(tgt_len, bsz, embed_dim_partition)
278
+ attn = self.out_proj(attn)
279
+ # return attn_weights None to keep the return type same as single gpu multihead attention
280
+ # This will be deprecated.
281
+ attn_weights: Optional[Tensor] = None
282
+
283
+ return attn, attn_weights
284
+
285
+ @staticmethod
286
+ def _append_prev_key_padding_mask(
287
+ key_padding_mask: Optional[Tensor],
288
+ prev_key_padding_mask: Optional[Tensor],
289
+ batch_size: int,
290
+ src_len: int,
291
+ static_kv: bool,
292
+ ) -> Optional[Tensor]:
293
+ # saved key padding masks have shape (bsz, seq_len)
294
+ if prev_key_padding_mask is not None and static_kv:
295
+ new_key_padding_mask = prev_key_padding_mask
296
+ elif prev_key_padding_mask is not None and key_padding_mask is not None:
297
+ new_key_padding_mask = torch.cat(
298
+ [prev_key_padding_mask.float(), key_padding_mask.float()], dim=1
299
+ )
300
+ # During incremental decoding, as the padding token enters and
301
+ # leaves the frame, there will be a time when prev or current
302
+ # is None
303
+ elif prev_key_padding_mask is not None:
304
+
305
+ filler = torch.zeros(batch_size, src_len - prev_key_padding_mask.size(1))
306
+ if prev_key_padding_mask.is_cuda:
307
+ filler = filler.cuda()
308
+ new_key_padding_mask = torch.cat(
309
+ [prev_key_padding_mask.float(), filler.float()], dim=1
310
+ )
311
+ elif key_padding_mask is not None:
312
+ filler = torch.zeros(batch_size, src_len - key_padding_mask.size(1))
313
+ if key_padding_mask.is_cuda:
314
+ filler = filler.cuda()
315
+ new_key_padding_mask = torch.cat(
316
+ [filler.float(), key_padding_mask.float()], dim=1
317
+ )
318
+ else:
319
+ new_key_padding_mask = prev_key_padding_mask
320
+ return new_key_padding_mask
321
+
322
+ def reorder_incremental_state(
323
+ self, incremental_state: Dict[str, Dict[str, Optional[Tensor]]], new_order
324
+ ):
325
+ """Reorder buffered internal state (for incremental generation)."""
326
+ input_buffer = self._get_input_buffer(incremental_state)
327
+ if input_buffer is not None:
328
+ for k in input_buffer.keys():
329
+ if input_buffer[k] is not None:
330
+ input_buffer[k] = input_buffer[k].index_select(0, new_order)
331
+ incremental_state = self._set_input_buffer(incremental_state, input_buffer)
332
+ return incremental_state
333
+
334
+ def _get_input_buffer(
335
+ self, incremental_state: Optional[Dict[str, Dict[str, Optional[Tensor]]]]
336
+ ) -> Dict[str, Optional[Tensor]]:
337
+ result = self.get_incremental_state(incremental_state, "attn_state")
338
+ if result is not None:
339
+ return result
340
+ else:
341
+ empty_result: Dict[str, Optional[Tensor]] = {}
342
+ return empty_result
343
+
344
+ def _set_input_buffer(
345
+ self,
346
+ incremental_state: Dict[str, Dict[str, Optional[Tensor]]],
347
+ buffer: Dict[str, Optional[Tensor]],
348
+ ):
349
+ return self.set_incremental_state(incremental_state, "attn_state", buffer)
data/fairseq/fairseq/model_parallel/modules/transformer_layer.py ADDED
@@ -0,0 +1,78 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright (c) Facebook, Inc. and its affiliates.
2
+ #
3
+ # This source code is licensed under the MIT license found in the
4
+ # LICENSE file in the root directory of this source tree.
5
+
6
+ from fairseq.model_parallel.modules import ModelParallelMultiheadAttention
7
+ from fairseq.modules import TransformerDecoderLayer, TransformerEncoderLayer
8
+
9
+
10
+ try:
11
+ from fairseq.model_parallel.megatron.mpu import (
12
+ ColumnParallelLinear,
13
+ RowParallelLinear,
14
+ )
15
+
16
+ has_megatron_submodule = True
17
+ except (ImportError, ModuleNotFoundError):
18
+ has_megatron_submodule = False
19
+
20
+
21
+ class ModelParallelTransformerEncoderLayer(TransformerEncoderLayer):
22
+ """Encoder layer block over multiple gpus.
23
+
24
+ See "Megatron-LM: https://arxiv.org/pdf/1909.08053.pdf" for more details.
25
+ """
26
+
27
+ def build_fc1(self, input_dim, output_dim, q_noise, qn_block_size):
28
+ if q_noise > 0:
29
+ raise NotImplementedError
30
+ return ColumnParallelLinear(input_dim, output_dim, gather_output=False)
31
+
32
+ def build_fc2(self, input_dim, output_dim, q_noise, qn_block_size):
33
+ if q_noise > 0:
34
+ raise NotImplementedError
35
+ return RowParallelLinear(input_dim, output_dim, input_is_parallel=True)
36
+
37
+ def build_self_attention(self, embed_dim, args, **unused_kwargs):
38
+ return ModelParallelMultiheadAttention(
39
+ embed_dim,
40
+ args.encoder_attention_heads,
41
+ dropout=args.attention_dropout,
42
+ self_attention=True,
43
+ )
44
+
45
+
46
+ class ModelParallelTransformerDecoderLayer(TransformerDecoderLayer):
47
+ """Decoder layer block.
48
+
49
+ See "Megatron-LM: https://arxiv.org/pdf/1909.08053.pdf" for more details.
50
+ """
51
+
52
+ def build_fc1(self, input_dim, output_dim, q_noise, qn_block_size):
53
+ if q_noise > 0:
54
+ raise NotImplementedError
55
+ return ColumnParallelLinear(input_dim, output_dim, gather_output=False)
56
+
57
+ def build_fc2(self, input_dim, output_dim, q_noise, qn_block_size):
58
+ if q_noise > 0:
59
+ raise NotImplementedError
60
+ return RowParallelLinear(input_dim, output_dim, input_is_parallel=True)
61
+
62
+ def build_self_attention(self, embed_dim, args, **unused_kwargs):
63
+ return ModelParallelMultiheadAttention(
64
+ embed_dim=embed_dim,
65
+ num_heads=args.decoder_attention_heads,
66
+ dropout=args.attention_dropout,
67
+ self_attention=not getattr(args, "cross_self_attention", False),
68
+ )
69
+
70
+ def build_encoder_attention(self, embed_dim, args, **unused_kwargs):
71
+ return ModelParallelMultiheadAttention(
72
+ embed_dim=embed_dim,
73
+ num_heads=args.decoder_attention_heads,
74
+ kdim=getattr(args, "encoder_embed_dim", None),
75
+ vdim=getattr(args, "encoder_embed_dim", None),
76
+ dropout=args.attention_dropout,
77
+ encoder_decoder_attention=True,
78
+ )
ipft.ipynb ADDED
@@ -0,0 +1,551 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "cells": [
3
+ {
4
+ "cell_type": "code",
5
+ "execution_count": null,
6
+ "id": "42a0da24-c70a-4b68-8790-7f93e0e37990",
7
+ "metadata": {},
8
+ "outputs": [],
9
+ "source": [
10
+ "pwd"
11
+ ]
12
+ },
13
+ {
14
+ "cell_type": "code",
15
+ "execution_count": null,
16
+ "id": "c595f8f0-2e4a-442b-bde8-b48dfe762355",
17
+ "metadata": {},
18
+ "outputs": [],
19
+ "source": [
20
+ "!pip install evaluate"
21
+ ]
22
+ },
23
+ {
24
+ "cell_type": "code",
25
+ "execution_count": null,
26
+ "id": "4958f755-f0fc-40ca-b8b3-e625811d4d79",
27
+ "metadata": {},
28
+ "outputs": [],
29
+ "source": [
30
+ "!pip install transformers"
31
+ ]
32
+ },
33
+ {
34
+ "cell_type": "code",
35
+ "execution_count": 9,
36
+ "id": "8cd636d6-84cf-4d10-826f-258c6e1646d6",
37
+ "metadata": {},
38
+ "outputs": [
39
+ {
40
+ "name": "stdout",
41
+ "output_type": "stream",
42
+ "text": [
43
+ "Collecting peft\n",
44
+ " Downloading peft-0.13.2-py3-none-any.whl.metadata (13 kB)\n",
45
+ "Requirement already satisfied: numpy>=1.17 in /system/conda/miniconda3/envs/cloudspace/lib/python3.8/site-packages (from peft) (1.24.4)\n",
46
+ "Requirement already satisfied: packaging>=20.0 in /system/conda/miniconda3/envs/cloudspace/lib/python3.8/site-packages (from peft) (24.1)\n",
47
+ "Requirement already satisfied: psutil in /system/conda/miniconda3/envs/cloudspace/lib/python3.8/site-packages (from peft) (7.2.2)\n",
48
+ "Requirement already satisfied: pyyaml in /system/conda/miniconda3/envs/cloudspace/lib/python3.8/site-packages (from peft) (6.0.3)\n",
49
+ "Requirement already satisfied: torch>=1.13.0 in /system/conda/miniconda3/envs/cloudspace/lib/python3.8/site-packages (from peft) (2.4.1)\n",
50
+ "Requirement already satisfied: transformers in /system/conda/miniconda3/envs/cloudspace/lib/python3.8/site-packages (from peft) (4.46.3)\n",
51
+ "Requirement already satisfied: tqdm in /system/conda/miniconda3/envs/cloudspace/lib/python3.8/site-packages (from peft) (4.67.3)\n",
52
+ "Collecting accelerate>=0.21.0 (from peft)\n",
53
+ " Downloading accelerate-1.0.1-py3-none-any.whl.metadata (19 kB)\n",
54
+ "Requirement already satisfied: safetensors in /system/conda/miniconda3/envs/cloudspace/lib/python3.8/site-packages (from peft) (0.5.3)\n",
55
+ "Requirement already satisfied: huggingface-hub>=0.17.0 in /system/conda/miniconda3/envs/cloudspace/lib/python3.8/site-packages (from peft) (0.36.2)\n",
56
+ "Requirement already satisfied: filelock in /system/conda/miniconda3/envs/cloudspace/lib/python3.8/site-packages (from huggingface-hub>=0.17.0->peft) (3.16.1)\n",
57
+ "Requirement already satisfied: fsspec>=2023.5.0 in /system/conda/miniconda3/envs/cloudspace/lib/python3.8/site-packages (from huggingface-hub>=0.17.0->peft) (2024.9.0)\n",
58
+ "Requirement already satisfied: hf-xet<2.0.0,>=1.1.3 in /system/conda/miniconda3/envs/cloudspace/lib/python3.8/site-packages (from huggingface-hub>=0.17.0->peft) (1.4.3)\n",
59
+ "Requirement already satisfied: requests in /system/conda/miniconda3/envs/cloudspace/lib/python3.8/site-packages (from huggingface-hub>=0.17.0->peft) (2.32.4)\n",
60
+ "Requirement already satisfied: typing-extensions>=3.7.4.3 in /system/conda/miniconda3/envs/cloudspace/lib/python3.8/site-packages (from huggingface-hub>=0.17.0->peft) (4.13.2)\n",
61
+ "Requirement already satisfied: sympy in /system/conda/miniconda3/envs/cloudspace/lib/python3.8/site-packages (from torch>=1.13.0->peft) (1.13.3)\n",
62
+ "Requirement already satisfied: networkx in /system/conda/miniconda3/envs/cloudspace/lib/python3.8/site-packages (from torch>=1.13.0->peft) (3.1)\n",
63
+ "Requirement already satisfied: jinja2 in /system/conda/miniconda3/envs/cloudspace/lib/python3.8/site-packages (from torch>=1.13.0->peft) (3.1.6)\n",
64
+ "Requirement already satisfied: nvidia-cuda-nvrtc-cu12==12.1.105 in /system/conda/miniconda3/envs/cloudspace/lib/python3.8/site-packages (from torch>=1.13.0->peft) (12.1.105)\n",
65
+ "Requirement already satisfied: nvidia-cuda-runtime-cu12==12.1.105 in /system/conda/miniconda3/envs/cloudspace/lib/python3.8/site-packages (from torch>=1.13.0->peft) (12.1.105)\n",
66
+ "Requirement already satisfied: nvidia-cuda-cupti-cu12==12.1.105 in /system/conda/miniconda3/envs/cloudspace/lib/python3.8/site-packages (from torch>=1.13.0->peft) (12.1.105)\n",
67
+ "Requirement already satisfied: nvidia-cudnn-cu12==9.1.0.70 in /system/conda/miniconda3/envs/cloudspace/lib/python3.8/site-packages (from torch>=1.13.0->peft) (9.1.0.70)\n",
68
+ "Requirement already satisfied: nvidia-cublas-cu12==12.1.3.1 in /system/conda/miniconda3/envs/cloudspace/lib/python3.8/site-packages (from torch>=1.13.0->peft) (12.1.3.1)\n",
69
+ "Requirement already satisfied: nvidia-cufft-cu12==11.0.2.54 in /system/conda/miniconda3/envs/cloudspace/lib/python3.8/site-packages (from torch>=1.13.0->peft) (11.0.2.54)\n",
70
+ "Requirement already satisfied: nvidia-curand-cu12==10.3.2.106 in /system/conda/miniconda3/envs/cloudspace/lib/python3.8/site-packages (from torch>=1.13.0->peft) (10.3.2.106)\n",
71
+ "Requirement already satisfied: nvidia-cusolver-cu12==11.4.5.107 in /system/conda/miniconda3/envs/cloudspace/lib/python3.8/site-packages (from torch>=1.13.0->peft) (11.4.5.107)\n",
72
+ "Requirement already satisfied: nvidia-cusparse-cu12==12.1.0.106 in /system/conda/miniconda3/envs/cloudspace/lib/python3.8/site-packages (from torch>=1.13.0->peft) (12.1.0.106)\n",
73
+ "Requirement already satisfied: nvidia-nccl-cu12==2.20.5 in /system/conda/miniconda3/envs/cloudspace/lib/python3.8/site-packages (from torch>=1.13.0->peft) (2.20.5)\n",
74
+ "Requirement already satisfied: nvidia-nvtx-cu12==12.1.105 in /system/conda/miniconda3/envs/cloudspace/lib/python3.8/site-packages (from torch>=1.13.0->peft) (12.1.105)\n",
75
+ "Requirement already satisfied: triton==3.0.0 in /system/conda/miniconda3/envs/cloudspace/lib/python3.8/site-packages (from torch>=1.13.0->peft) (3.0.0)\n",
76
+ "Requirement already satisfied: nvidia-nvjitlink-cu12 in /system/conda/miniconda3/envs/cloudspace/lib/python3.8/site-packages (from nvidia-cusolver-cu12==11.4.5.107->torch>=1.13.0->peft) (12.9.86)\n",
77
+ "Requirement already satisfied: regex!=2019.12.17 in /system/conda/miniconda3/envs/cloudspace/lib/python3.8/site-packages (from transformers->peft) (2024.11.6)\n",
78
+ "Requirement already satisfied: tokenizers<0.21,>=0.20 in /system/conda/miniconda3/envs/cloudspace/lib/python3.8/site-packages (from transformers->peft) (0.20.3)\n",
79
+ "Requirement already satisfied: MarkupSafe>=2.0 in /system/conda/miniconda3/envs/cloudspace/lib/python3.8/site-packages (from jinja2->torch>=1.13.0->peft) (2.1.5)\n",
80
+ "Requirement already satisfied: charset_normalizer<4,>=2 in /system/conda/miniconda3/envs/cloudspace/lib/python3.8/site-packages (from requests->huggingface-hub>=0.17.0->peft) (3.4.7)\n",
81
+ "Requirement already satisfied: idna<4,>=2.5 in /system/conda/miniconda3/envs/cloudspace/lib/python3.8/site-packages (from requests->huggingface-hub>=0.17.0->peft) (3.13)\n",
82
+ "Requirement already satisfied: urllib3<3,>=1.21.1 in /system/conda/miniconda3/envs/cloudspace/lib/python3.8/site-packages (from requests->huggingface-hub>=0.17.0->peft) (2.2.3)\n",
83
+ "Requirement already satisfied: certifi>=2017.4.17 in /system/conda/miniconda3/envs/cloudspace/lib/python3.8/site-packages (from requests->huggingface-hub>=0.17.0->peft) (2026.4.22)\n",
84
+ "Requirement already satisfied: mpmath<1.4,>=1.1.0 in /system/conda/miniconda3/envs/cloudspace/lib/python3.8/site-packages (from sympy->torch>=1.13.0->peft) (1.3.0)\n",
85
+ "Downloading peft-0.13.2-py3-none-any.whl (320 kB)\n",
86
+ "\u001b[2K \u001b[90m━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━\u001b[0m \u001b[32m320.7/320.7 kB\u001b[0m \u001b[31m9.5 MB/s\u001b[0m eta \u001b[36m0:00:00\u001b[0m\n",
87
+ "\u001b[?25hDownloading accelerate-1.0.1-py3-none-any.whl (330 kB)\n",
88
+ "\u001b[2K \u001b[90m━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━\u001b[0m \u001b[32m330.9/330.9 kB\u001b[0m \u001b[31m48.8 MB/s\u001b[0m eta \u001b[36m0:00:00\u001b[0m\n",
89
+ "\u001b[?25h\u001b[33mDEPRECATION: omegaconf 2.0.6 has a non-standard dependency specifier PyYAML>=5.1.*. pip 24.1 will enforce this behaviour change. A possible replacement is to upgrade to a newer version of omegaconf or contact the author to suggest that they release a version with a conforming dependency specifiers. Discussion can be found at https://github.com/pypa/pip/issues/12063\u001b[0m\u001b[33m\n",
90
+ "\u001b[0mInstalling collected packages: accelerate, peft\n",
91
+ "Successfully installed accelerate-1.0.1 peft-0.13.2\n",
92
+ "\n",
93
+ "\u001b[1m[\u001b[0m\u001b[34;49mnotice\u001b[0m\u001b[1;39;49m]\u001b[0m\u001b[39;49m A new release of pip is available: \u001b[0m\u001b[31;49m24.0\u001b[0m\u001b[39;49m -> \u001b[0m\u001b[32;49m25.0.1\u001b[0m\n",
94
+ "\u001b[1m[\u001b[0m\u001b[34;49mnotice\u001b[0m\u001b[1;39;49m]\u001b[0m\u001b[39;49m To update, run: \u001b[0m\u001b[32;49mpip install --upgrade pip\u001b[0m\n"
95
+ ]
96
+ }
97
+ ],
98
+ "source": [
99
+ "!pip install peft"
100
+ ]
101
+ },
102
+ {
103
+ "cell_type": "code",
104
+ "execution_count": 1,
105
+ "id": "42e90884-c40b-46b4-9067-529725bc208d",
106
+ "metadata": {},
107
+ "outputs": [
108
+ {
109
+ "name": "stdout",
110
+ "output_type": "stream",
111
+ "text": [
112
+ "Loading local datasets...\n",
113
+ "Tokenizing data...\n"
114
+ ]
115
+ },
116
+ {
117
+ "data": {
118
+ "application/vnd.jupyter.widget-view+json": {
119
+ "model_id": "3a61e1d780f442bf84f1f07e7297663c",
120
+ "version_major": 2,
121
+ "version_minor": 0
122
+ },
123
+ "text/plain": [
124
+ "Map: 0%| | 0/139266 [00:00<?, ? examples/s]"
125
+ ]
126
+ },
127
+ "metadata": {},
128
+ "output_type": "display_data"
129
+ },
130
+ {
131
+ "data": {
132
+ "application/vnd.jupyter.widget-view+json": {
133
+ "model_id": "317e41ddb2bc4db8b6ca8fe82b1bf598",
134
+ "version_major": 2,
135
+ "version_minor": 0
136
+ },
137
+ "text/plain": [
138
+ "Map: 0%| | 0/2404 [00:00<?, ? examples/s]"
139
+ ]
140
+ },
141
+ "metadata": {},
142
+ "output_type": "display_data"
143
+ },
144
+ {
145
+ "data": {
146
+ "application/vnd.jupyter.widget-view+json": {
147
+ "model_id": "9754734338f14749b74c734cb24bf8db",
148
+ "version_major": 2,
149
+ "version_minor": 0
150
+ },
151
+ "text/plain": [
152
+ "Map: 0%| | 0/1183 [00:00<?, ? examples/s]"
153
+ ]
154
+ },
155
+ "metadata": {},
156
+ "output_type": "display_data"
157
+ },
158
+ {
159
+ "data": {
160
+ "application/vnd.jupyter.widget-view+json": {
161
+ "model_id": "2ed4906d44f54e33b0da8c5a0ef58cfd",
162
+ "version_major": 2,
163
+ "version_minor": 0
164
+ },
165
+ "text/plain": [
166
+ "pytorch_model.bin: 0%| | 0.00/2.46G [00:00<?, ?B/s]"
167
+ ]
168
+ },
169
+ "metadata": {},
170
+ "output_type": "display_data"
171
+ },
172
+ {
173
+ "data": {
174
+ "application/vnd.jupyter.widget-view+json": {
175
+ "model_id": "f033726ad0c64c6f876322d4f9dcf501",
176
+ "version_major": 2,
177
+ "version_minor": 0
178
+ },
179
+ "text/plain": [
180
+ "generation_config.json: 0%| | 0.00/189 [00:00<?, ?B/s]"
181
+ ]
182
+ },
183
+ "metadata": {},
184
+ "output_type": "display_data"
185
+ },
186
+ {
187
+ "name": "stdout",
188
+ "output_type": "stream",
189
+ "text": [
190
+ "trainable params: 4,718,592 || all params: 619,792,384 || trainable%: 0.7613\n"
191
+ ]
192
+ }
193
+ ],
194
+ "source": [
195
+ "import torch\n",
196
+ "import os\n",
197
+ "import numpy as np\n",
198
+ "import evaluate\n",
199
+ "from datasets import Dataset, DatasetDict\n",
200
+ "from transformers import (\n",
201
+ " AutoModelForSeq2SeqLM, \n",
202
+ " AutoTokenizer, \n",
203
+ " Seq2SeqTrainingArguments, \n",
204
+ " Seq2SeqTrainer, \n",
205
+ " DataCollatorForSeq2Seq\n",
206
+ ")\n",
207
+ "from peft import LoraConfig, get_peft_model, TaskType\n",
208
+ "\n",
209
+ "# ==========================================\n",
210
+ "# 1. DATA LOADING (Local Files)\n",
211
+ "# ==========================================\n",
212
+ "def load_local_data(en_path, mni_path):\n",
213
+ " if not os.path.exists(en_path) or not os.path.exists(mni_path):\n",
214
+ " raise FileNotFoundError(f\"Ensure {en_path} and {mni_path} exist in this folder.\")\n",
215
+ " \n",
216
+ " with open(en_path, \"r\", encoding=\"utf-8\") as f_en, \\\n",
217
+ " open(mni_path, \"r\", encoding=\"utf-8\") as f_mni:\n",
218
+ " en_lines = [l.strip() for l in f_en if l.strip()]\n",
219
+ " mni_lines = [l.strip() for l in f_mni if l.strip()]\n",
220
+ " \n",
221
+ " # Align lengths to prevent index errors\n",
222
+ " length = min(len(en_lines), len(mni_lines))\n",
223
+ " return Dataset.from_dict({\n",
224
+ " \"english\": en_lines[:length], \n",
225
+ " \"manipuri\": mni_lines[:length]\n",
226
+ " })\n",
227
+ "\n",
228
+ "print(\"Loading local datasets...\")\n",
229
+ "dataset = DatasetDict({\n",
230
+ " \"train\": load_local_data(\"data/train.eng_Latn\", \"data/train.mni_Beng\"),\n",
231
+ " \"validation\": load_local_data(\"data/dev.eng_Latn\", \"data/dev.mni_Beng\"),\n",
232
+ " \"test\": load_local_data(\"data/test.eng_Latn\", \"data/test.mni_Beng\")\n",
233
+ "})\n",
234
+ "\n",
235
+ "# ==========================================\n",
236
+ "# 2. MODEL & TOKENIZER SETUP\n",
237
+ "# ==========================================\n",
238
+ "model_id = \"facebook/nllb-200-distilled-600M\"\n",
239
+ "# We explicitly set the language tags for NLLB\n",
240
+ "tokenizer = AutoTokenizer.from_pretrained(\n",
241
+ " model_id, \n",
242
+ " src_lang=\"eng_Latn\", \n",
243
+ " tgt_lang=\"mni_Beng\"\n",
244
+ ")\n",
245
+ "\n",
246
+ "def preprocess_function(examples):\n",
247
+ " model_inputs = tokenizer(\n",
248
+ " examples[\"english\"], \n",
249
+ " text_target=examples[\"manipuri\"], \n",
250
+ " max_length=128, \n",
251
+ " truncation=True\n",
252
+ " )\n",
253
+ " return model_inputs\n",
254
+ "\n",
255
+ "print(\"Tokenizing data...\")\n",
256
+ "tokenized_ds = dataset.map(\n",
257
+ " preprocess_function, \n",
258
+ " batched=True, \n",
259
+ " remove_columns=[\"english\", \"manipuri\"]\n",
260
+ ")\n",
261
+ "\n",
262
+ "# Load model in FP16 to avoid bitsandbytes/quantization issues\n",
263
+ "model = AutoModelForSeq2SeqLM.from_pretrained(\n",
264
+ " model_id, \n",
265
+ " torch_dtype=torch.float16, \n",
266
+ " device_map=\"auto\"\n",
267
+ ")\n",
268
+ "\n",
269
+ "# LSFTL Framework: Low-Rank Adaptation (LoRA)\n",
270
+ "peft_config = LoraConfig(\n",
271
+ " task_type=TaskType.SEQ_2_SEQ_LM,\n",
272
+ " r=16, \n",
273
+ " lora_alpha=32, \n",
274
+ " target_modules=[\"q_proj\", \"v_proj\", \"k_proj\", \"out_proj\"],\n",
275
+ " lora_dropout=0.05\n",
276
+ ")\n",
277
+ "model = get_peft_model(model, peft_config)\n",
278
+ "model.print_trainable_parameters()\n",
279
+ "\n"
280
+ ]
281
+ },
282
+ {
283
+ "cell_type": "code",
284
+ "execution_count": null,
285
+ "id": "651bce1c-34e5-4951-b887-4d114bbecd10",
286
+ "metadata": {},
287
+ "outputs": [],
288
+ "source": []
289
+ },
290
+ {
291
+ "cell_type": "code",
292
+ "execution_count": null,
293
+ "id": "bf6a71f5-a65e-4884-84c5-02f35b3ff47d",
294
+ "metadata": {},
295
+ "outputs": [],
296
+ "source": []
297
+ },
298
+ {
299
+ "cell_type": "code",
300
+ "execution_count": null,
301
+ "id": "2bac2437-48f1-401f-ba6a-c7b5152c45b4",
302
+ "metadata": {},
303
+ "outputs": [
304
+ {
305
+ "data": {
306
+ "application/vnd.jupyter.widget-view+json": {
307
+ "model_id": "c6fded3a5ffb4343a3495b31194f18a2",
308
+ "version_major": 2,
309
+ "version_minor": 0
310
+ },
311
+ "text/plain": [
312
+ "Downloading builder script: 0.00B [00:00, ?B/s]"
313
+ ]
314
+ },
315
+ "metadata": {},
316
+ "output_type": "display_data"
317
+ },
318
+ {
319
+ "name": "stderr",
320
+ "output_type": "stream",
321
+ "text": [
322
+ "/home/zeus/miniconda3/envs/cloudspace/lib/python3.8/site-packages/transformers/training_args.py:1568: FutureWarning: `evaluation_strategy` is deprecated and will be removed in version 4.46 of 🤗 Transformers. Use `eval_strategy` instead\n",
323
+ " warnings.warn(\n",
324
+ "huggingface/tokenizers: The current process just got forked, after parallelism has already been used. Disabling parallelism to avoid deadlocks...\n",
325
+ "To disable this warning, you can either:\n",
326
+ "\t- Avoid using `tokenizers` before the fork if possible\n",
327
+ "\t- Explicitly set the environment variable TOKENIZERS_PARALLELISM=(true | false)\n",
328
+ "/tmp/ipykernel_4611/2745601905.py:45: FutureWarning: `tokenizer` is deprecated and will be removed in version 5.0.0 for `Seq2SeqTrainer.__init__`. Use `processing_class` instead.\n",
329
+ " trainer = Seq2SeqTrainer(\n"
330
+ ]
331
+ },
332
+ {
333
+ "name": "stdout",
334
+ "output_type": "stream",
335
+ "text": [
336
+ "Starting Fine-tuning...\n"
337
+ ]
338
+ },
339
+ {
340
+ "data": {
341
+ "text/html": [
342
+ "\n",
343
+ " <div>\n",
344
+ " \n",
345
+ " <progress value='86' max='26112' style='width:300px; height:20px; vertical-align: middle;'></progress>\n",
346
+ " [ 86/26112 01:35 < 8:10:42, 0.88 it/s, Epoch 0.01/3]\n",
347
+ " </div>\n",
348
+ " <table border=\"1\" class=\"dataframe\">\n",
349
+ " <thead>\n",
350
+ " <tr style=\"text-align: left;\">\n",
351
+ " <th>Epoch</th>\n",
352
+ " <th>Training Loss</th>\n",
353
+ " <th>Validation Loss</th>\n",
354
+ " </tr>\n",
355
+ " </thead>\n",
356
+ " <tbody>\n",
357
+ " </tbody>\n",
358
+ "</table><p>"
359
+ ],
360
+ "text/plain": [
361
+ "<IPython.core.display.HTML object>"
362
+ ]
363
+ },
364
+ "metadata": {},
365
+ "output_type": "display_data"
366
+ }
367
+ ],
368
+ "source": [
369
+ "# ==========================================\n",
370
+ "# 3. METRIC CALCULATION (SacreBLEU)\n",
371
+ "# ==========================================\n",
372
+ "metric = evaluate.load(\"sacrebleu\")\n",
373
+ "\n",
374
+ "def compute_metrics(eval_preds):\n",
375
+ " preds, labels = eval_preds\n",
376
+ " if isinstance(preds, tuple):\n",
377
+ " preds = preds[0]\n",
378
+ " \n",
379
+ " # Decode predictions\n",
380
+ " decoded_preds = tokenizer.batch_decode(preds, skip_special_tokens=True)\n",
381
+ "\n",
382
+ " # Replace -100 (ignored index) in labels\n",
383
+ " labels = np.where(labels != -100, labels, tokenizer.pad_token_id)\n",
384
+ " decoded_labels = tokenizer.batch_decode(labels, skip_special_tokens=True)\n",
385
+ "\n",
386
+ " # Post-processing for SacreBLEU\n",
387
+ " decoded_preds = [pred.strip() for pred in decoded_preds]\n",
388
+ " decoded_labels = [[label.strip()] for label in decoded_labels]\n",
389
+ "\n",
390
+ " result = metric.compute(predictions=decoded_preds, references=decoded_labels)\n",
391
+ " return {\"bleu\": result[\"score\"]}\n",
392
+ "\n",
393
+ "# ==========================================\n",
394
+ "# 4. TRAINING CONFIGURATION\n",
395
+ "# ==========================================\n",
396
+ "training_args = Seq2SeqTrainingArguments(\n",
397
+ " output_dir=\"./nllb-mni-lsftl\",\n",
398
+ " evaluation_strategy=\"epoch\",\n",
399
+ " save_strategy=\"epoch\",\n",
400
+ " learning_rate=2e-4,\n",
401
+ " per_device_train_batch_size=4,\n",
402
+ " gradient_accumulation_steps=4,\n",
403
+ " weight_decay=0.01,\n",
404
+ " num_train_epochs=3,\n",
405
+ " predict_with_generate=True, # Critical for BLEU calculation\n",
406
+ " fp16=True,\n",
407
+ " optim=\"adamw_torch\", # Forcing standard PyTorch optimizer\n",
408
+ " logging_steps=10,\n",
409
+ " save_total_limit=1,\n",
410
+ " load_best_model_at_end=True\n",
411
+ ")\n",
412
+ "\n",
413
+ "trainer = Seq2SeqTrainer(\n",
414
+ " model=model,\n",
415
+ " args=training_args,\n",
416
+ " train_dataset=tokenized_ds[\"train\"],\n",
417
+ " eval_dataset=tokenized_ds[\"validation\"],\n",
418
+ " tokenizer=tokenizer,\n",
419
+ " data_collator=DataCollatorForSeq2Seq(tokenizer, model=model),\n",
420
+ " compute_metrics=compute_metrics,\n",
421
+ ")\n",
422
+ "\n",
423
+ "# ==========================================\n",
424
+ "# 5. EXECUTION: TRAIN & TEST\n",
425
+ "# ==========================================\n",
426
+ "print(\"Starting Fine-tuning...\")\n",
427
+ "trainer.train()\n",
428
+ "\n",
429
+ "print(\"\\n--- Final Evaluation on Test Set ---\")\n",
430
+ "test_results = trainer.evaluate(eval_dataset=tokenized_ds[\"test\"])\n",
431
+ "print(f\"Test BLEU Score: {test_results['eval_bleu']:.2f}\")\n",
432
+ "\n",
433
+ "# ==========================================\n",
434
+ "# 6. SAMPLE INFERENCE CHECK\n",
435
+ "# ==========================================\n",
436
+ "print(\"\\n--- Sample Predictions from Test Set ---\")\n",
437
+ "model.eval()\n",
438
+ "mni_id = tokenizer.convert_tokens_to_ids(\"mni_Beng\")\n",
439
+ "\n",
440
+ "for i in range(5):\n",
441
+ " input_text = dataset[\"test\"][\"english\"][i]\n",
442
+ " inputs = tokenizer(input_text, return_tensors=\"pt\").to(model.device)\n",
443
+ " \n",
444
+ " with torch.no_grad():\n",
445
+ " generated_tokens = model.generate(\n",
446
+ " **inputs, \n",
447
+ " forced_bos_token_id=mni_id, \n",
448
+ " max_length=128\n",
449
+ " )\n",
450
+ " \n",
451
+ " prediction = tokenizer.decode(generated_tokens[0], skip_special_tokens=True)\n",
452
+ " reference = dataset[\"test\"][\"manipuri\"][i]\n",
453
+ " \n",
454
+ " print(f\"Input: {input_text}\")\n",
455
+ " print(f\"Pred: {prediction}\")\n",
456
+ " print(f\"Truth: {reference}\\n\")"
457
+ ]
458
+ },
459
+ {
460
+ "cell_type": "code",
461
+ "execution_count": 4,
462
+ "id": "4b8abf64-f671-49f6-9fed-006c875a8485",
463
+ "metadata": {},
464
+ "outputs": [
465
+ {
466
+ "data": {
467
+ "text/plain": [
468
+ "'/teamspace/studios/this_studio'"
469
+ ]
470
+ },
471
+ "execution_count": 4,
472
+ "metadata": {},
473
+ "output_type": "execute_result"
474
+ }
475
+ ],
476
+ "source": [
477
+ "pwd"
478
+ ]
479
+ },
480
+ {
481
+ "cell_type": "code",
482
+ "execution_count": 3,
483
+ "id": "f4b05fb0-0738-4370-9686-6f1df42314a5",
484
+ "metadata": {},
485
+ "outputs": [
486
+ {
487
+ "name": "stdout",
488
+ "output_type": "stream",
489
+ "text": [
490
+ "\u001b[0m\u001b[01;32mcheckpoint1.pt\u001b[0m* \u001b[01;32mcheckpoint15.pt\u001b[0m* \u001b[01;32mcheckpoint20.pt\u001b[0m* \u001b[01;32mcheckpoint8.pt\u001b[0m*\n",
491
+ "\u001b[01;32mcheckpoint10.pt\u001b[0m* \u001b[01;32mcheckpoint16.pt\u001b[0m* \u001b[01;32mcheckpoint3.pt\u001b[0m* \u001b[01;32mcheckpoint9.pt\u001b[0m*\n",
492
+ "\u001b[01;32mcheckpoint11.pt\u001b[0m* \u001b[01;32mcheckpoint17.pt\u001b[0m* \u001b[01;32mcheckpoint4.pt\u001b[0m* \u001b[01;32mcheckpoint_best.pt\u001b[0m*\n",
493
+ "\u001b[01;32mcheckpoint12.pt\u001b[0m* \u001b[01;32mcheckpoint18.pt\u001b[0m* \u001b[01;32mcheckpoint5.pt\u001b[0m* \u001b[01;32mcheckpoint_last.pt\u001b[0m*\n",
494
+ "\u001b[01;32mcheckpoint13.pt\u001b[0m* \u001b[01;32mcheckpoint19.pt\u001b[0m* \u001b[01;32mcheckpoint6.pt\u001b[0m*\n",
495
+ "\u001b[01;32mcheckpoint14.pt\u001b[0m* \u001b[01;32mcheckpoint2.pt\u001b[0m* \u001b[01;32mcheckpoint7.pt\u001b[0m*\n"
496
+ ]
497
+ }
498
+ ],
499
+ "source": [
500
+ "ls\n"
501
+ ]
502
+ },
503
+ {
504
+ "cell_type": "code",
505
+ "execution_count": 2,
506
+ "id": "5b279caa-ceed-483c-b174-bb3eede61772",
507
+ "metadata": {},
508
+ "outputs": [
509
+ {
510
+ "name": "stdout",
511
+ "output_type": "stream",
512
+ "text": [
513
+ "/teamspace/studios/this_studio/checkpoints\n"
514
+ ]
515
+ }
516
+ ],
517
+ "source": [
518
+ "cd checkpoints"
519
+ ]
520
+ },
521
+ {
522
+ "cell_type": "code",
523
+ "execution_count": null,
524
+ "id": "cc0f8abd-63e9-4de0-8c5b-ea9ff61d71c3",
525
+ "metadata": {},
526
+ "outputs": [],
527
+ "source": []
528
+ }
529
+ ],
530
+ "metadata": {
531
+ "kernelspec": {
532
+ "display_name": "Python 3",
533
+ "language": "python",
534
+ "name": "python3"
535
+ },
536
+ "language_info": {
537
+ "codemirror_mode": {
538
+ "name": "ipython",
539
+ "version": 3
540
+ },
541
+ "file_extension": ".py",
542
+ "mimetype": "text/x-python",
543
+ "name": "python",
544
+ "nbconvert_exporter": "python",
545
+ "pygments_lexer": "ipython3",
546
+ "version": "3.8.20"
547
+ }
548
+ },
549
+ "nbformat": 4,
550
+ "nbformat_minor": 5
551
+ }