Hzfinfdu commited on
Commit
54a6a36
1 Parent(s): fce8747

Upload modeling_moss.py with huggingface_hub

Browse files
Files changed (1) hide show
  1. modeling_moss.py +734 -0
modeling_moss.py ADDED
@@ -0,0 +1,734 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """ PyTorch Moss model."""
2
+
3
+ from typing import Optional, Tuple, Union
4
+
5
+ import torch
6
+ import torch.utils.checkpoint
7
+ from torch import nn
8
+ from torch.nn import CrossEntropyLoss
9
+ import transformers
10
+ from transformers.activations import ACT2FN
11
+ from transformers.modeling_utils import PreTrainedModel
12
+ from transformers.modeling_outputs import BaseModelOutputWithPast, CausalLMOutputWithPast
13
+ from transformers.utils import (
14
+ add_code_sample_docstrings,
15
+ add_start_docstrings,
16
+ add_start_docstrings_to_model_forward,
17
+ logging
18
+ )
19
+
20
+ from .configuration_moss import MossConfig
21
+
22
+ logger = logging.get_logger(__name__)
23
+
24
+ _CHECKPOINT_FOR_DOC = "fnlp/moss-moon-003-base"
25
+ _CONFIG_FOR_DOC = "MossConfig"
26
+
27
+
28
+ MOSS_PRETRAINED_MODEL_ARCHIVE_LIST = [
29
+ "fnlp/moss-moon-003-base",
30
+ "fnlp/moss-moon-003-sft",
31
+ "fnlp/moss-moon-003-sft-plugin",
32
+ "fnlp/moss-moon-003-sft-int4",
33
+ "fnlp/moss-moon-003-sft-plugin-int4",
34
+ "fnlp/moss-moon-003-sft-int8",
35
+ "fnlp/moss-moon-003-sft-plugin-int8",
36
+ ]
37
+
38
+
39
+ # Copied from transformers.models.gptj.modeling_gptj.create_sinusoidal_positions
40
+ def create_sinusoidal_positions(num_pos: int, dim: int) -> torch.Tensor:
41
+ inv_freq = 1.0 / (10000 ** (torch.arange(0, dim, 2) / dim))
42
+ sinusoid_inp = torch.einsum("i , j -> i j", torch.arange(num_pos, dtype=torch.float), inv_freq).float()
43
+ return torch.cat((torch.sin(sinusoid_inp), torch.cos(sinusoid_inp)), dim=1)
44
+
45
+
46
+ # Copied from transformers.models.gptj.modeling_gptj.rotate_every_two
47
+ def rotate_every_two(x: torch.Tensor) -> torch.Tensor:
48
+ x1 = x[:, :, :, ::2]
49
+ x2 = x[:, :, :, 1::2]
50
+ x = torch.stack((-x2, x1), dim=-1)
51
+ return x.flatten(-2) # in einsum notation: rearrange(x, '... d j -> ... (d j)')
52
+
53
+
54
+ # Copied from transformers.models.gptj.modeling_gptj.apply_rotary_pos_emb
55
+ def apply_rotary_pos_emb(tensor: torch.Tensor, sin: torch.Tensor, cos: torch.Tensor) -> torch.Tensor:
56
+ sin = torch.repeat_interleave(sin[:, :, None, :], 2, 3)
57
+ cos = torch.repeat_interleave(cos[:, :, None, :], 2, 3)
58
+ return (tensor * cos) + (rotate_every_two(tensor) * sin)
59
+
60
+
61
+ class MossAttention(nn.Module):
62
+ def __init__(self, config):
63
+ super().__init__()
64
+
65
+ max_positions = config.max_position_embeddings
66
+ self.register_buffer(
67
+ "causal_mask",
68
+ torch.tril(torch.ones((max_positions, max_positions), dtype=torch.bool)).view(
69
+ 1, 1, max_positions, max_positions
70
+ ),
71
+ )
72
+
73
+ self.attn_dropout = nn.Dropout(config.attn_pdrop)
74
+ self.resid_dropout = nn.Dropout(config.resid_pdrop)
75
+
76
+ self.embed_dim = config.hidden_size
77
+ self.num_attention_heads = config.num_attention_heads
78
+ self.head_dim = self.embed_dim // self.num_attention_heads
79
+ if self.head_dim * self.num_attention_heads != self.embed_dim:
80
+ raise ValueError(
81
+ f"embed_dim must be divisible by num_attention_heads (got `embed_dim`: {self.embed_dim} and"
82
+ f" `num_attention_heads`: {self.num_attention_heads})."
83
+ )
84
+ self.scale_attn = torch.sqrt(torch.tensor(self.head_dim, dtype=torch.float32)).to(torch.get_default_dtype())
85
+ self.qkv_proj = nn.Linear(self.embed_dim, self.embed_dim * 3, bias=False)
86
+
87
+ self.out_proj = nn.Linear(self.embed_dim, self.embed_dim, bias=False)
88
+ self.rotary_dim = config.rotary_dim
89
+ pos_embd_dim = self.rotary_dim or self.embed_dim
90
+ self.embed_positions = create_sinusoidal_positions(max_positions, pos_embd_dim)
91
+
92
+ def _split_heads(self, x, n_head, dim_head, mp_num):
93
+ reshaped = x.reshape(x.shape[:-1] + (n_head // mp_num, dim_head))
94
+ reshaped = reshaped.reshape(x.shape[:-2] + (-1,) + reshaped.shape[-1:])
95
+ return reshaped
96
+
97
+ def _merge_heads(self, tensor, num_attention_heads, attn_head_size):
98
+ """
99
+ Merges attn_head_size dim and num_attn_heads dim into n_ctx
100
+ """
101
+ if len(tensor.shape) == 5:
102
+ tensor = tensor.permute(0, 1, 3, 2, 4).contiguous()
103
+ elif len(tensor.shape) == 4:
104
+ tensor = tensor.permute(0, 2, 1, 3).contiguous()
105
+ else:
106
+ raise ValueError(f"Input tensor rank should be one of [4, 5], but is: {len(tensor.shape)}")
107
+ new_shape = tensor.size()[:-2] + (num_attention_heads * attn_head_size,)
108
+ return tensor.view(new_shape)
109
+
110
+ def _attn(
111
+ self,
112
+ query,
113
+ key,
114
+ value,
115
+ attention_mask=None,
116
+ head_mask=None,
117
+ ):
118
+ # compute causal mask from causal mask buffer
119
+ query_length, key_length = query.size(-2), key.size(-2)
120
+ causal_mask = self.causal_mask[:, :, key_length - query_length : key_length, :key_length]
121
+
122
+ # Keep the attention weights computation in fp32 to avoid overflow issues
123
+ query = query.to(torch.float32)
124
+ key = key.to(torch.float32)
125
+
126
+ attn_weights = torch.matmul(query, key.transpose(-1, -2))
127
+
128
+ attn_weights = attn_weights / self.scale_attn
129
+ mask_value = torch.finfo(attn_weights.dtype).min
130
+ # Need to be a tensor, otherwise we get error: `RuntimeError: expected scalar type float but found double`.
131
+ # Need to be on the same device, otherwise `RuntimeError: ..., x and y to be on the same device`
132
+ mask_value = torch.tensor(mask_value, dtype=attn_weights.dtype).to(attn_weights.device)
133
+ attn_weights = torch.where(causal_mask, attn_weights, mask_value)
134
+
135
+ if attention_mask is not None:
136
+ # Apply the attention mask
137
+ attn_weights = attn_weights + attention_mask
138
+
139
+ attn_weights = nn.Softmax(dim=-1)(attn_weights)
140
+ attn_weights = attn_weights.to(value.dtype)
141
+ attn_weights = self.attn_dropout(attn_weights)
142
+
143
+ # Mask heads if we want to
144
+ if head_mask is not None:
145
+ attn_weights = attn_weights * head_mask
146
+
147
+ attn_output = torch.matmul(attn_weights, value)
148
+
149
+ return attn_output, attn_weights
150
+
151
+ def forward(
152
+ self,
153
+ hidden_states: Optional[torch.FloatTensor],
154
+ layer_past: Optional[Tuple[torch.Tensor]] = None,
155
+ attention_mask: Optional[torch.FloatTensor] = None,
156
+ position_ids: Optional[torch.LongTensor] = None,
157
+ head_mask: Optional[torch.FloatTensor] = None,
158
+ use_cache: Optional[bool] = False,
159
+ output_attentions: Optional[bool] = False,
160
+ ) -> Union[
161
+ Tuple[torch.Tensor, Tuple[torch.Tensor]],
162
+ Optional[Tuple[torch.Tensor, Tuple[torch.Tensor], Tuple[torch.Tensor, ...]]],
163
+ ]:
164
+ qkv = self.qkv_proj(hidden_states)
165
+ # TODO(enijkamp): factor out number of logical TPU-v4 cores or make forward pass agnostic
166
+ mp_num = 4
167
+ qkv_split = qkv.reshape(qkv.shape[:-1] + (mp_num, -1))
168
+
169
+ local_dim = self.head_dim * self.num_attention_heads // mp_num
170
+ query, value, key = torch.split(qkv_split, local_dim, dim=-1)
171
+ query = self._split_heads(query, self.num_attention_heads, self.head_dim, mp_num=mp_num)
172
+ key = self._split_heads(key, self.num_attention_heads, self.head_dim, mp_num=mp_num)
173
+
174
+ value = self._split_heads(value, self.num_attention_heads, self.head_dim, mp_num=mp_num)
175
+ value = value.permute(0, 2, 1, 3)
176
+
177
+ embed_positions = self.embed_positions
178
+ if embed_positions.device != position_ids.device:
179
+ embed_positions = embed_positions.to(position_ids.device)
180
+ self.embed_positions = embed_positions
181
+
182
+ sincos = embed_positions[position_ids]
183
+ sin, cos = torch.split(sincos, sincos.shape[-1] // 2, dim=-1)
184
+
185
+ if self.rotary_dim is not None:
186
+ k_rot = key[:, :, :, : self.rotary_dim]
187
+ k_pass = key[:, :, :, self.rotary_dim :]
188
+
189
+ q_rot = query[:, :, :, : self.rotary_dim]
190
+ q_pass = query[:, :, :, self.rotary_dim :]
191
+
192
+ k_rot = apply_rotary_pos_emb(k_rot, sin, cos)
193
+ q_rot = apply_rotary_pos_emb(q_rot, sin, cos)
194
+
195
+ key = torch.cat([k_rot, k_pass], dim=-1)
196
+ query = torch.cat([q_rot, q_pass], dim=-1)
197
+ else:
198
+ key = apply_rotary_pos_emb(key, sin, cos)
199
+ query = apply_rotary_pos_emb(query, sin, cos)
200
+
201
+ key = key.permute(0, 2, 1, 3)
202
+ query = query.permute(0, 2, 1, 3)
203
+
204
+ if layer_past is not None:
205
+ past_key = layer_past[0]
206
+ past_value = layer_past[1]
207
+ key = torch.cat((past_key, key), dim=-2)
208
+ value = torch.cat((past_value, value), dim=-2)
209
+
210
+ if use_cache is True:
211
+ present = (key, value)
212
+ else:
213
+ present = None
214
+
215
+ # compute self-attention: V x Softmax(QK^T)
216
+ attn_output, attn_weights = self._attn(query, key, value, attention_mask, head_mask)
217
+
218
+ attn_output = self._merge_heads(attn_output, self.num_attention_heads, self.head_dim)
219
+ attn_output = self.out_proj(attn_output)
220
+ attn_output = self.resid_dropout(attn_output)
221
+
222
+ outputs = (attn_output, present)
223
+ if output_attentions:
224
+ outputs += (attn_weights,)
225
+
226
+ return outputs # a, present, (attentions)
227
+
228
+
229
+ # Copied from transformers.models.gptj.modeling_gptj.GPTJMLP with GPTJ->Moss
230
+ class MossMLP(nn.Module):
231
+ def __init__(self, intermediate_size, config): # in MLP: intermediate_size= 4 * embed_dim
232
+ super().__init__()
233
+ embed_dim = config.n_embd
234
+
235
+ self.fc_in = nn.Linear(embed_dim, intermediate_size)
236
+ self.fc_out = nn.Linear(intermediate_size, embed_dim)
237
+
238
+ self.act = ACT2FN[config.activation_function]
239
+ self.dropout = nn.Dropout(config.resid_pdrop)
240
+
241
+ def forward(self, hidden_states: Optional[torch.FloatTensor]) -> torch.FloatTensor:
242
+ hidden_states = self.fc_in(hidden_states)
243
+ hidden_states = self.act(hidden_states)
244
+ hidden_states = self.fc_out(hidden_states)
245
+ hidden_states = self.dropout(hidden_states)
246
+ return hidden_states
247
+
248
+
249
+ # Copied from transformers.models.gptj.modeling_gptj.GPTJBlock with GPTJ->Moss
250
+ class MossBlock(nn.Module):
251
+ def __init__(self, config):
252
+ super().__init__()
253
+ inner_dim = config.n_inner if config.n_inner is not None else 4 * config.n_embd
254
+ self.ln_1 = nn.LayerNorm(config.n_embd, eps=config.layer_norm_epsilon)
255
+ self.attn = MossAttention(config)
256
+ self.mlp = MossMLP(inner_dim, config)
257
+
258
+ def forward(
259
+ self,
260
+ hidden_states: Optional[torch.FloatTensor],
261
+ layer_past: Optional[Tuple[torch.Tensor]] = None,
262
+ attention_mask: Optional[torch.FloatTensor] = None,
263
+ position_ids: Optional[torch.LongTensor] = None,
264
+ head_mask: Optional[torch.FloatTensor] = None,
265
+ use_cache: Optional[bool] = False,
266
+ output_attentions: Optional[bool] = False,
267
+ ) -> Union[Tuple[torch.Tensor], Optional[Tuple[torch.Tensor, Tuple[torch.FloatTensor, ...]]]]:
268
+ residual = hidden_states
269
+ hidden_states = self.ln_1(hidden_states)
270
+ attn_outputs = self.attn(
271
+ hidden_states=hidden_states,
272
+ layer_past=layer_past,
273
+ attention_mask=attention_mask,
274
+ position_ids=position_ids,
275
+ head_mask=head_mask,
276
+ use_cache=use_cache,
277
+ output_attentions=output_attentions,
278
+ )
279
+ attn_output = attn_outputs[0] # output_attn: a, present, (attentions)
280
+ outputs = attn_outputs[1:]
281
+
282
+ feed_forward_hidden_states = self.mlp(hidden_states)
283
+ hidden_states = attn_output + feed_forward_hidden_states + residual
284
+
285
+ if use_cache:
286
+ outputs = (hidden_states,) + outputs
287
+ else:
288
+ outputs = (hidden_states,) + outputs[1:]
289
+
290
+ return outputs # hidden_states, present, (attentions)
291
+
292
+
293
+ class MossPreTrainedModel(PreTrainedModel):
294
+ """
295
+ An abstract class to handle weights initialization and a simple interface for downloading and loading pretrained
296
+ models.
297
+ """
298
+
299
+ config_class = MossConfig
300
+ base_model_prefix = "transformer"
301
+ supports_gradient_checkpointing = True
302
+ _no_split_modules = ["MossBlock"]
303
+
304
+ def __init__(self, *inputs, **kwargs):
305
+ super().__init__(*inputs, **kwargs)
306
+
307
+ def _init_weights(self, module):
308
+ """Initialize the weights."""
309
+ if isinstance(module, (nn.Linear,)):
310
+ # Slightly different from Mesh Transformer JAX which uses truncated_normal for initialization
311
+ # cf https://github.com/pytorch/pytorch/pull/5617
312
+ module.weight.data.normal_(mean=0.0, std=self.config.initializer_range)
313
+ if module.bias is not None:
314
+ module.bias.data.zero_()
315
+ elif isinstance(module, nn.Embedding):
316
+ module.weight.data.normal_(mean=0.0, std=self.config.initializer_range)
317
+ if module.padding_idx is not None:
318
+ module.weight.data[module.padding_idx].zero_()
319
+ elif isinstance(module, nn.LayerNorm):
320
+ module.bias.data.zero_()
321
+ module.weight.data.fill_(1.0)
322
+
323
+ def _set_gradient_checkpointing(self, module, value=False):
324
+ if isinstance(module, MossModel):
325
+ module.gradient_checkpointing = value
326
+
327
+
328
+ MOSS_START_DOCSTRING = r"""
329
+ This model is a PyTorch [torch.nn.Module](https://pytorch.org/docs/stable/nn.html#torch.nn.Module) sub-class. Use
330
+ it as a regular PyTorch Module and refer to the PyTorch documentation for all matter related to general usage and
331
+ behavior.
332
+
333
+ Parameters:
334
+ config ([`MossConfig`]): Model configuration class with all the parameters of the model.
335
+ Initializing with a config file does not load the weights associated with the model, only the
336
+ configuration. Check out the [`~PreTrainedModel.from_pretrained`] method to load the model weights.
337
+ """
338
+
339
+ MOSS_INPUTS_DOCSTRING = r"""
340
+ Args:
341
+ input_ids (`torch.LongTensor` of shape `({0})`):
342
+ Indices of input sequence tokens in the vocabulary.
343
+
344
+ Indices can be obtained using [`AutoProcenizer`]. See [`PreTrainedTokenizer.encode`] and
345
+ [`PreTrainedTokenizer.__call__`] for details.
346
+
347
+ [What are input IDs?](../glossary#input-ids)
348
+ attention_mask (`torch.FloatTensor` of shape `({0})`, *optional*):
349
+ Mask to avoid performing attention on padding token indices. Mask values selected in `[0, 1]`:
350
+
351
+ - 1 for tokens that are **not masked**,
352
+ - 0 for tokens that are **masked**.
353
+
354
+ [What are attention masks?](../glossary#attention-mask)
355
+ token_type_ids (`torch.LongTensor` of shape `({0})`, *optional*):
356
+ Segment token indices to indicate first and second portions of the inputs. Indices are selected in `[0,
357
+ 1]`:
358
+
359
+ - 0 corresponds to a *sentence A* token,
360
+ - 1 corresponds to a *sentence B* token.
361
+
362
+ [What are token type IDs?](../glossary#token-type-ids)
363
+ position_ids (`torch.LongTensor` of shape `({0})`, *optional*):
364
+ Indices of positions of each input sequence tokens in the position embeddings. Selected in the range `[0,
365
+ config.n_positions - 1]`.
366
+
367
+ [What are position IDs?](../glossary#position-ids)
368
+ head_mask (`torch.FloatTensor` of shape `(num_attention_heads,)` or `(n_layer, num_attention_heads)`, *optional*):
369
+ Mask to nullify selected heads of the self-attention modules. Mask values selected in `[0, 1]`:
370
+
371
+ - 1 indicates the head is **not masked**,
372
+ - 0 indicates the head is **masked**.
373
+
374
+ inputs_embeds (`torch.FloatTensor` of shape `({0}, hidden_dim)`, *optional*):
375
+ Optionally, instead of passing `input_ids` you can choose to directly pass an embedded representation. This
376
+ is useful if you want more control over how to convert *input_ids* indices into associated vectors than the
377
+ model's internal embedding lookup matrix.
378
+ output_attentions (`bool`, *optional*):
379
+ Whether or not to return the attentions tensors of all attention layers. See `attentions` under returned
380
+ tensors for more detail.
381
+ output_hidden_states (`bool`, *optional*):
382
+ Whether or not to return the hidden states of all layers. See `hidden_states` under returned tensors for
383
+ more detail.
384
+ return_dict (`bool`, *optional*):
385
+ Whether or not to return a [`~utils.ModelOutput`] instead of a plain tuple.
386
+ """
387
+
388
+
389
+ @add_start_docstrings(
390
+ "The bare Moss Model transformer outputting raw hidden-states without any specific head on top.",
391
+ MOSS_START_DOCSTRING,
392
+ )
393
+ class MossModel(MossPreTrainedModel):
394
+ def __init__(self, config):
395
+ super().__init__(config)
396
+
397
+ self.embed_dim = config.n_embd
398
+ self.vocab_size = config.vocab_size
399
+ self.wte = nn.Embedding(config.vocab_size, self.embed_dim)
400
+ self.drop = nn.Dropout(config.embd_pdrop)
401
+ self.h = nn.ModuleList([MossBlock(config) for _ in range(config.n_layer)])
402
+ self.ln_f = nn.LayerNorm(self.embed_dim, eps=config.layer_norm_epsilon)
403
+ self.rotary_dim = min(config.rotary_dim, config.n_ctx // config.num_attention_heads)
404
+
405
+ self.gradient_checkpointing = False
406
+
407
+ # Initialize weights and apply final processing
408
+ self.post_init()
409
+
410
+ def get_input_embeddings(self):
411
+ return self.wte
412
+
413
+ def set_input_embeddings(self, new_embeddings):
414
+ self.wte = new_embeddings
415
+
416
+ @add_start_docstrings_to_model_forward(MOSS_INPUTS_DOCSTRING.format("batch_size, sequence_length"))
417
+ @add_code_sample_docstrings(
418
+ checkpoint=_CHECKPOINT_FOR_DOC,
419
+ output_type=BaseModelOutputWithPast,
420
+ config_class=_CONFIG_FOR_DOC,
421
+ )
422
+ def forward(
423
+ self,
424
+ input_ids: Optional[torch.LongTensor] = None,
425
+ past_key_values: Optional[Tuple[Tuple[torch.Tensor]]] = None,
426
+ attention_mask: Optional[torch.FloatTensor] = None,
427
+ token_type_ids: Optional[torch.LongTensor] = None,
428
+ position_ids: Optional[torch.LongTensor] = None,
429
+ head_mask: Optional[torch.FloatTensor] = None,
430
+ inputs_embeds: Optional[torch.FloatTensor] = None,
431
+ use_cache: Optional[bool] = None,
432
+ output_attentions: Optional[bool] = None,
433
+ output_hidden_states: Optional[bool] = None,
434
+ return_dict: Optional[bool] = None,
435
+ ) -> Union[Tuple, BaseModelOutputWithPast]:
436
+ output_attentions = output_attentions if output_attentions is not None else self.config.output_attentions
437
+ output_hidden_states = (
438
+ output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states
439
+ )
440
+ use_cache = use_cache if use_cache is not None else self.config.use_cache
441
+ return_dict = return_dict if return_dict is not None else self.config.use_return_dict
442
+
443
+ if input_ids is not None and inputs_embeds is not None:
444
+ raise ValueError("You cannot specify both input_ids and inputs_embeds at the same time")
445
+ elif input_ids is not None:
446
+ input_shape = input_ids.size()
447
+ input_ids = input_ids.view(-1, input_shape[-1])
448
+ batch_size = input_ids.shape[0]
449
+ elif inputs_embeds is not None:
450
+ input_shape = inputs_embeds.size()[:-1]
451
+ batch_size = inputs_embeds.shape[0]
452
+ else:
453
+ raise ValueError("You have to specify either input_ids or inputs_embeds")
454
+
455
+ device = input_ids.device if input_ids is not None else inputs_embeds.device
456
+
457
+ if token_type_ids is not None:
458
+ token_type_ids = token_type_ids.view(-1, input_shape[-1])
459
+
460
+ if position_ids is not None:
461
+ position_ids = position_ids.view(-1, input_shape[-1]).long()
462
+
463
+ if past_key_values is None:
464
+ past_length = 0
465
+ past_key_values = tuple([None] * len(self.h))
466
+ else:
467
+ past_length = past_key_values[0][0].size(-2)
468
+
469
+ if position_ids is None:
470
+ position_ids = torch.arange(past_length, input_shape[-1] + past_length, dtype=torch.long, device=device)
471
+ position_ids = position_ids.unsqueeze(0).view(-1, input_shape[-1])
472
+
473
+ # Attention mask.
474
+ if attention_mask is not None:
475
+ if batch_size <= 0:
476
+ raise ValueError("batch_size has to be defined and > 0")
477
+ attention_mask = attention_mask.view(batch_size, -1)
478
+ # We create a 3D attention mask from a 2D tensor mask.
479
+ # Sizes are [batch_size, 1, 1, to_seq_length]
480
+ # So we can broadcast to [batch_size, num_heads, from_seq_length, to_seq_length]
481
+ # this attention mask is more simple than the triangular masking of causal attention
482
+ # used in OpenAI GPT, we just need to prepare the broadcast dimension here.
483
+ attention_mask = attention_mask[:, None, None, :]
484
+
485
+ # Since attention_mask is 1.0 for positions we want to attend and 0.0 for
486
+ # masked positions, this operation will create a tensor which is 0.0 for
487
+ # positions we want to attend and the dtype's smallest value for masked positions.
488
+ # Since we are adding it to the raw scores before the softmax, this is
489
+ # effectively the same as removing these entirely.
490
+ attention_mask = attention_mask.to(dtype=self.dtype) # fp16 compatibility
491
+ attention_mask = (1.0 - attention_mask) * torch.finfo(self.dtype).min
492
+
493
+ # Prepare head mask if needed
494
+ # 1.0 in head_mask indicate we keep the head
495
+ # attention_probs has shape bsz x num_attention_heads x N x N
496
+ # head_mask has shape n_layer x batch x num_attention_heads x N x N
497
+ head_mask = self.get_head_mask(head_mask, self.config.n_layer)
498
+
499
+ if inputs_embeds is None:
500
+ inputs_embeds = self.wte(input_ids)
501
+
502
+ hidden_states = inputs_embeds
503
+
504
+ if token_type_ids is not None:
505
+ token_type_embeds = self.wte(token_type_ids)
506
+ hidden_states = hidden_states + token_type_embeds
507
+
508
+ hidden_states = self.drop(hidden_states)
509
+
510
+ output_shape = input_shape + (hidden_states.size(-1),)
511
+
512
+ if self.gradient_checkpointing and self.training:
513
+ if use_cache:
514
+ logger.warning_once(
515
+ "`use_cache=True` is incompatible with `config.gradient_checkpointing=True`. Setting "
516
+ "`use_cache=False`..."
517
+ )
518
+ use_cache = False
519
+
520
+ presents = () if use_cache else None
521
+ all_self_attentions = () if output_attentions else None
522
+ all_hidden_states = () if output_hidden_states else None
523
+ for i, (block, layer_past) in enumerate(zip(self.h, past_key_values)):
524
+ if output_hidden_states:
525
+ all_hidden_states = all_hidden_states + (hidden_states,)
526
+
527
+ if self.gradient_checkpointing and self.training:
528
+
529
+ def create_custom_forward(module):
530
+ def custom_forward(*inputs):
531
+ # None for past_key_value
532
+ return module(*inputs, use_cache, output_attentions)
533
+
534
+ return custom_forward
535
+
536
+ outputs = torch.utils.checkpoint.checkpoint(
537
+ create_custom_forward(block),
538
+ hidden_states,
539
+ None,
540
+ attention_mask,
541
+ position_ids,
542
+ head_mask[i],
543
+ )
544
+ else:
545
+ outputs = block(
546
+ hidden_states=hidden_states,
547
+ layer_past=layer_past,
548
+ attention_mask=attention_mask,
549
+ position_ids=position_ids,
550
+ head_mask=head_mask[i],
551
+ use_cache=use_cache,
552
+ output_attentions=output_attentions,
553
+ )
554
+
555
+ hidden_states = outputs[0]
556
+ if use_cache is True:
557
+ presents = presents + (outputs[1],)
558
+
559
+ if output_attentions:
560
+ all_self_attentions = all_self_attentions + (outputs[2 if use_cache else 1],)
561
+
562
+ hidden_states = self.ln_f(hidden_states)
563
+
564
+ hidden_states = hidden_states.view(output_shape)
565
+ # Add last hidden state
566
+ if output_hidden_states:
567
+ all_hidden_states = all_hidden_states + (hidden_states,)
568
+
569
+ if not return_dict:
570
+ return tuple(v for v in [hidden_states, presents, all_hidden_states, all_self_attentions] if v is not None)
571
+
572
+ return BaseModelOutputWithPast(
573
+ last_hidden_state=hidden_states,
574
+ past_key_values=presents,
575
+ hidden_states=all_hidden_states,
576
+ attentions=all_self_attentions,
577
+ )
578
+
579
+
580
+ @add_start_docstrings(
581
+ """
582
+ The Moss Model transformer with a language modeling head on top.
583
+ """,
584
+ MOSS_START_DOCSTRING,
585
+ )
586
+ class MossForCausalLM(MossPreTrainedModel):
587
+ _keys_to_ignore_on_load_missing = [r"h\.\d+\.attn\.causal_mask"]
588
+
589
+ def __init__(self, config):
590
+ super().__init__(config)
591
+ if config.wbits not in [4, 8, 32]:
592
+ logger.warning(f'Specify `wbits` with 4, 8 or 32 to load the model. ')
593
+ if config.wbits in [4, 8]:
594
+ def noop(*args, **kwargs):
595
+ pass
596
+ torch.nn.init.kaiming_uniform_ = noop
597
+ torch.nn.init.uniform_ = noop
598
+ torch.nn.init.normal_ = noop
599
+
600
+ torch.set_default_dtype(torch.half)
601
+ transformers.modeling_utils._init_weights = False
602
+ torch.set_default_dtype(torch.half)
603
+ self.transformer = MossModel(config)
604
+ self.lm_head = nn.Linear(config.n_embd, config.vocab_size)
605
+ if config.wbits in [4, 8]:
606
+ torch.set_default_dtype(torch.float)
607
+ transformers.modeling_utils._init_weights = True
608
+ self.quantize(config.wbits, config.groupsize)
609
+ # Initialize weights and apply final processing
610
+ self.post_init()
611
+
612
+ def get_output_embeddings(self):
613
+ return self.lm_head
614
+
615
+ def set_output_embeddings(self, new_embeddings):
616
+ self.lm_head = new_embeddings
617
+
618
+ def prepare_inputs_for_generation(self, input_ids, past_key_values=None, **kwargs):
619
+ token_type_ids = kwargs.get("token_type_ids", None)
620
+ # only last token for inputs_ids if past is defined in kwargs
621
+ if past_key_values:
622
+ input_ids = input_ids[:, -1].unsqueeze(-1)
623
+ if token_type_ids is not None:
624
+ token_type_ids = token_type_ids[:, -1].unsqueeze(-1)
625
+
626
+ attention_mask = kwargs.get("attention_mask", None)
627
+ position_ids = kwargs.get("position_ids", None)
628
+
629
+ if attention_mask is not None and position_ids is None:
630
+ # create position_ids on the fly for batch generation
631
+ position_ids = attention_mask.long().cumsum(-1) - 1
632
+ position_ids.masked_fill_(attention_mask == 0, 1)
633
+ if past_key_values:
634
+ position_ids = position_ids[:, -1].unsqueeze(-1)
635
+
636
+ return {
637
+ "input_ids": input_ids,
638
+ "past_key_values": past_key_values,
639
+ "use_cache": kwargs.get("use_cache"),
640
+ "position_ids": position_ids,
641
+ "attention_mask": attention_mask,
642
+ "token_type_ids": token_type_ids,
643
+ }
644
+
645
+ @add_start_docstrings_to_model_forward(MOSS_INPUTS_DOCSTRING.format("batch_size, sequence_length"))
646
+ @add_code_sample_docstrings(
647
+ checkpoint=_CHECKPOINT_FOR_DOC,
648
+ output_type=CausalLMOutputWithPast,
649
+ config_class=_CONFIG_FOR_DOC,
650
+ )
651
+ def forward(
652
+ self,
653
+ input_ids: Optional[torch.LongTensor] = None,
654
+ past_key_values: Optional[Tuple[Tuple[torch.Tensor]]] = None,
655
+ attention_mask: Optional[torch.FloatTensor] = None,
656
+ token_type_ids: Optional[torch.LongTensor] = None,
657
+ position_ids: Optional[torch.LongTensor] = None,
658
+ head_mask: Optional[torch.FloatTensor] = None,
659
+ inputs_embeds: Optional[torch.FloatTensor] = None,
660
+ labels: Optional[torch.LongTensor] = None,
661
+ use_cache: Optional[bool] = None,
662
+ output_attentions: Optional[bool] = None,
663
+ output_hidden_states: Optional[bool] = None,
664
+ return_dict: Optional[bool] = None,
665
+ ) -> Union[Tuple, CausalLMOutputWithPast]:
666
+ r"""
667
+ labels (`torch.LongTensor` of shape `(batch_size, sequence_length)`, *optional*):
668
+ Labels for language modeling. Note that the labels **are shifted** inside the model, i.e. you can set
669
+ `labels = input_ids` Indices are selected in `[-100, 0, ..., config.vocab_size]` All labels set to `-100`
670
+ are ignored (masked), the loss is only computed for labels in `[0, ..., config.vocab_size]`
671
+ """
672
+ return_dict = return_dict if return_dict is not None else self.config.use_return_dict
673
+
674
+ transformer_outputs = self.transformer(
675
+ input_ids,
676
+ past_key_values=past_key_values,
677
+ attention_mask=attention_mask,
678
+ token_type_ids=token_type_ids,
679
+ position_ids=position_ids,
680
+ head_mask=head_mask,
681
+ inputs_embeds=inputs_embeds,
682
+ use_cache=use_cache,
683
+ output_attentions=output_attentions,
684
+ output_hidden_states=output_hidden_states,
685
+ return_dict=return_dict,
686
+ )
687
+ hidden_states = transformer_outputs[0]
688
+
689
+ # make sure sampling in fp16 works correctly and
690
+ # compute loss in fp32 to match with mesh-tf version
691
+ # https://github.com/EleutherAI/gpt-neo/blob/89ce74164da2fb16179106f54e2269b5da8db333/models/gpt2/gpt2.py#L179
692
+ lm_logits = self.lm_head(hidden_states).to(torch.float32)
693
+
694
+ loss = None
695
+ if labels is not None:
696
+ # Shift so that tokens < n predict n
697
+ shift_logits = lm_logits[..., :-1, :].contiguous()
698
+ shift_labels = labels[..., 1:].contiguous()
699
+ # Flatten the tokens
700
+ loss_fct = CrossEntropyLoss()
701
+ loss = loss_fct(shift_logits.view(-1, shift_logits.size(-1)), shift_labels.view(-1))
702
+
703
+ loss = loss.to(hidden_states.dtype)
704
+
705
+ if not return_dict:
706
+ output = (lm_logits,) + transformer_outputs[1:]
707
+ return ((loss,) + output) if loss is not None else output
708
+
709
+ return CausalLMOutputWithPast(
710
+ loss=loss,
711
+ logits=lm_logits,
712
+ past_key_values=transformer_outputs.past_key_values,
713
+ hidden_states=transformer_outputs.hidden_states,
714
+ attentions=transformer_outputs.attentions,
715
+ )
716
+
717
+ @staticmethod
718
+ def _reorder_cache(
719
+ past_key_values: Tuple[Tuple[torch.Tensor]], beam_idx: torch.Tensor
720
+ ) -> Tuple[Tuple[torch.Tensor]]:
721
+ """
722
+ This function is used to re-order the `past_key_values` cache if [`~PretrainedModel.beam_search`] or
723
+ [`~PretrainedModel.beam_sample`] is called. This is required to match `past_key_values` with the correct
724
+ beam_idx at every generation step.
725
+ """
726
+ return tuple(
727
+ tuple(past_state.index_select(0, beam_idx.to(past_state.device)) for past_state in layer_past)
728
+ for layer_past in past_key_values
729
+ )
730
+
731
+ def quantize(self, wbits, groupsize):
732
+ from .quantization import quantize_with_gptq
733
+ return quantize_with_gptq(self, wbits, groupsize)
734
+