Hzfinfdu commited on
Commit
f350120
1 Parent(s): 9828061

Upload modeling_moss.py with huggingface_hub

Browse files
Files changed (1) hide show
  1. modeling_moss.py +888 -0
modeling_moss.py ADDED
@@ -0,0 +1,888 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # coding=utf-8
2
+ # Copyright 2022 EleutherAI and the HuggingFace Inc. team. All rights reserved.
3
+ #
4
+ # This code is based on EleutherAI's GPT-NeoX library and the GPT-NeoX
5
+ # and OPT implementations in this library. It has been modified from its
6
+ # original forms to accommodate minor architectural differences compared
7
+ # to GPT-NeoX and OPT used by the Meta AI team that trained the model.
8
+ #
9
+ # Licensed under the Apache License, Version 2.0 (the "License");
10
+ # you may not use this file except in compliance with the License.
11
+ # You may obtain a copy of the License at
12
+ #
13
+ # http://www.apache.org/licenses/LICENSE-2.0
14
+ #
15
+ # Unless required by applicable law or agreed to in writing, software
16
+ # distributed under the License is distributed on an "AS IS" BASIS,
17
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
18
+ # See the License for the specific language governing permissions and
19
+ # limitations under the License.
20
+ """ PyTorch Moss model."""
21
+ import math
22
+ from typing import List, Optional, Tuple, Union
23
+
24
+ from typing import List, Optional, Tuple, Union
25
+
26
+ import torch
27
+ import torch.utils.checkpoint
28
+ from torch import nn
29
+ from torch.nn import BCEWithLogitsLoss, CrossEntropyLoss, MSELoss
30
+
31
+ from transformers.activations import ACT2FN
32
+ from transformers.modeling_outputs import BaseModelOutputWithPast, CausalLMOutputWithPast, SequenceClassifierOutputWithPast
33
+ from transformers.modeling_utils import PreTrainedModel
34
+ from transformers.generation.streamers import BaseStreamer
35
+ from transformers.utils import add_start_docstrings, add_start_docstrings_to_model_forward, logging, replace_return_docstrings
36
+ from .configuration_moss import MossConfig
37
+
38
+
39
+ logger = logging.get_logger(__name__)
40
+
41
+ _CONFIG_FOR_DOC = "MossConfig"
42
+
43
+
44
+ # Copied from transformers.models.bart.modeling_bart._make_causal_mask
45
+ def _make_causal_mask(
46
+ input_ids_shape: torch.Size, dtype: torch.dtype, device: torch.device, past_key_values_length: int = 0
47
+ ):
48
+ """
49
+ Make causal mask used for bi-directional self-attention.
50
+ """
51
+ bsz, tgt_len = input_ids_shape
52
+ mask = torch.full((tgt_len, tgt_len), torch.tensor(torch.finfo(dtype).min, device=device), device=device)
53
+ mask_cond = torch.arange(mask.size(-1), device=device)
54
+ mask.masked_fill_(mask_cond < (mask_cond + 1).view(mask.size(-1), 1), 0)
55
+ mask = mask.to(dtype)
56
+
57
+ if past_key_values_length > 0:
58
+ mask = torch.cat([torch.zeros(tgt_len, past_key_values_length, dtype=dtype, device=device), mask], dim=-1)
59
+ return mask[None, None, :, :].expand(bsz, 1, tgt_len, tgt_len + past_key_values_length)
60
+
61
+
62
+ # Copied from transformers.models.bart.modeling_bart._expand_mask
63
+ def _expand_mask(mask: torch.Tensor, dtype: torch.dtype, tgt_len: Optional[int] = None):
64
+ """
65
+ Expands attention_mask from `[bsz, seq_len]` to `[bsz, 1, tgt_seq_len, src_seq_len]`.
66
+ """
67
+ bsz, src_len = mask.size()
68
+ tgt_len = tgt_len if tgt_len is not None else src_len
69
+
70
+ expanded_mask = mask[:, None, None, :].expand(bsz, 1, tgt_len, src_len).to(dtype)
71
+
72
+ inverted_mask = 1.0 - expanded_mask
73
+
74
+ return inverted_mask.masked_fill(inverted_mask.to(torch.bool), torch.finfo(dtype).min)
75
+
76
+
77
+ class RMSNorm(nn.Module):
78
+ def __init__(self, hidden_size, eps=1e-6):
79
+ """
80
+ RMSNorm is equivalent to T5LayerNorm
81
+ """
82
+ super().__init__()
83
+ self.weight = nn.Parameter(torch.ones(hidden_size))
84
+ self.variance_epsilon = eps
85
+
86
+ def forward(self, hidden_states):
87
+ input_dtype = hidden_states.dtype
88
+ variance = hidden_states.to(torch.float32).pow(2).mean(-1, keepdim=True)
89
+ hidden_states = hidden_states * torch.rsqrt(variance + self.variance_epsilon)
90
+
91
+ return (self.weight * hidden_states).to(input_dtype)
92
+
93
+
94
+ class RotaryEmbedding(torch.nn.Module):
95
+ def __init__(self, dim, max_position_embeddings=2048, base=10000, device=None):
96
+ super().__init__()
97
+ inv_freq = 1.0 / (base ** (torch.arange(0, dim, 2).float().to(device) / dim))
98
+ self.register_buffer("inv_freq", inv_freq)
99
+
100
+ # Build here to make `torch.jit.trace` work.
101
+ self.max_seq_len_cached = max_position_embeddings
102
+ t = torch.arange(self.max_seq_len_cached, device=self.inv_freq.device, dtype=self.inv_freq.dtype)
103
+ freqs = torch.einsum("i,j->ij", t, self.inv_freq)
104
+ # Different from paper, but it uses a different permutation in order to obtain the same calculation
105
+ emb = torch.cat((freqs, freqs), dim=-1)
106
+ self.register_buffer("cos_cached", emb.cos()[None, None, :, :], persistent=False)
107
+ self.register_buffer("sin_cached", emb.sin()[None, None, :, :], persistent=False)
108
+
109
+ def forward(self, x, seq_len=None):
110
+ # x: [bs, num_attention_heads, seq_len, head_size]
111
+ # This `if` block is unlikely to be run after we build sin/cos in `__init__`. Keep the logic here just in case.
112
+ if seq_len > self.max_seq_len_cached:
113
+ self.max_seq_len_cached = seq_len
114
+ t = torch.arange(self.max_seq_len_cached, device=x.device, dtype=self.inv_freq.dtype)
115
+ freqs = torch.einsum("i,j->ij", t, self.inv_freq)
116
+ # Different from paper, but it uses a different permutation in order to obtain the same calculation
117
+ emb = torch.cat((freqs, freqs), dim=-1).to(x.device)
118
+ self.register_buffer("cos_cached", emb.cos()[None, None, :, :], persistent=False)
119
+ self.register_buffer("sin_cached", emb.sin()[None, None, :, :], persistent=False)
120
+ return (
121
+ self.cos_cached[:, :, :seq_len, ...].to(dtype=x.dtype),
122
+ self.sin_cached[:, :, :seq_len, ...].to(dtype=x.dtype),
123
+ )
124
+
125
+
126
+ def rotate_half(x):
127
+ """Rotates half the hidden dims of the input."""
128
+ x1 = x[..., : x.shape[-1] // 2]
129
+ x2 = x[..., x.shape[-1] // 2 :]
130
+ return torch.cat((-x2, x1), dim=-1)
131
+
132
+
133
+ def apply_rotary_pos_emb(q, k, cos, sin, position_ids):
134
+ # The first two dimensions of cos and sin are always 1, so we can `squeeze` them.
135
+ cos = cos.squeeze(1).squeeze(0) # [seq_len, dim]
136
+ sin = sin.squeeze(1).squeeze(0) # [seq_len, dim]
137
+ cos = cos[position_ids].unsqueeze(1) # [bs, 1, seq_len, dim]
138
+ sin = sin[position_ids].unsqueeze(1) # [bs, 1, seq_len, dim]
139
+ q_embed = (q * cos) + (rotate_half(q) * sin)
140
+ k_embed = (k * cos) + (rotate_half(k) * sin)
141
+ return q_embed, k_embed
142
+
143
+
144
+ class MLP(nn.Module):
145
+ def __init__(
146
+ self,
147
+ hidden_size: int,
148
+ intermediate_size: int,
149
+ hidden_act: str,
150
+ ):
151
+ super().__init__()
152
+ self.gate_proj = nn.Linear(hidden_size, intermediate_size, bias=False)
153
+ self.down_proj = nn.Linear(intermediate_size, hidden_size, bias=False)
154
+ self.up_proj = nn.Linear(hidden_size, intermediate_size, bias=False)
155
+ self.act_fn = ACT2FN[hidden_act]
156
+
157
+ def forward(self, x):
158
+ return self.down_proj(self.act_fn(self.gate_proj(x)) * self.up_proj(x))
159
+
160
+
161
+ class Attention(nn.Module):
162
+ """Multi-headed attention from 'Attention Is All You Need' paper"""
163
+
164
+ def __init__(self, config: MossConfig):
165
+ super().__init__()
166
+ self.config = config
167
+ self.hidden_size = config.hidden_size
168
+ self.num_heads = config.num_attention_heads
169
+ self.head_dim = self.hidden_size // self.num_heads
170
+ self.max_position_embeddings = config.max_position_embeddings
171
+
172
+ if (self.head_dim * self.num_heads) != self.hidden_size:
173
+ raise ValueError(
174
+ f"hidden_size must be divisible by num_heads (got `hidden_size`: {self.hidden_size}"
175
+ f" and `num_heads`: {self.num_heads})."
176
+ )
177
+ self.q_proj = nn.Linear(self.hidden_size, self.num_heads * self.head_dim, bias=False)
178
+ self.k_proj = nn.Linear(self.hidden_size, self.num_heads * self.head_dim, bias=False)
179
+ self.v_proj = nn.Linear(self.hidden_size, self.num_heads * self.head_dim, bias=False)
180
+ self.o_proj = nn.Linear(self.num_heads * self.head_dim, self.hidden_size, bias=False)
181
+ self.rotary_emb = RotaryEmbedding(self.head_dim, max_position_embeddings=self.max_position_embeddings)
182
+
183
+ def _shape(self, tensor: torch.Tensor, seq_len: int, bsz: int):
184
+ return tensor.view(bsz, seq_len, self.num_heads, self.head_dim).transpose(1, 2).contiguous()
185
+
186
+ def forward(
187
+ self,
188
+ hidden_states: torch.Tensor,
189
+ attention_mask: Optional[torch.Tensor] = None,
190
+ position_ids: Optional[torch.LongTensor] = None,
191
+ past_key_value: Optional[Tuple[torch.Tensor]] = None,
192
+ output_attentions: bool = False,
193
+ use_cache: bool = False,
194
+ ) -> Tuple[torch.Tensor, Optional[torch.Tensor], Optional[Tuple[torch.Tensor]]]:
195
+ bsz, q_len, _ = hidden_states.size()
196
+
197
+ query_states = self.q_proj(hidden_states).view(bsz, q_len, self.num_heads, self.head_dim).transpose(1, 2)
198
+ key_states = self.k_proj(hidden_states).view(bsz, q_len, self.num_heads, self.head_dim).transpose(1, 2)
199
+ value_states = self.v_proj(hidden_states).view(bsz, q_len, self.num_heads, self.head_dim).transpose(1, 2)
200
+
201
+ kv_seq_len = key_states.shape[-2]
202
+ if past_key_value is not None:
203
+ kv_seq_len += past_key_value[0].shape[-2]
204
+ cos, sin = self.rotary_emb(value_states, seq_len=kv_seq_len)
205
+ query_states, key_states = apply_rotary_pos_emb(query_states, key_states, cos, sin, position_ids)
206
+ # [bsz, nh, t, hd]
207
+
208
+ if past_key_value is not None:
209
+ # reuse k, v, self_attention
210
+ key_states = torch.cat([past_key_value[0], key_states], dim=2)
211
+ value_states = torch.cat([past_key_value[1], value_states], dim=2)
212
+
213
+ past_key_value = (key_states, value_states) if use_cache else None
214
+
215
+ attn_weights = torch.matmul(query_states, key_states.transpose(2, 3)) / math.sqrt(self.head_dim)
216
+
217
+ if attn_weights.size() != (bsz, self.num_heads, q_len, kv_seq_len):
218
+ raise ValueError(
219
+ f"Attention weights should be of size {(bsz, self.num_heads, q_len, kv_seq_len)}, but is"
220
+ f" {attn_weights.size()}"
221
+ )
222
+
223
+ if attention_mask is not None:
224
+ if attention_mask.size() != (bsz, 1, q_len, kv_seq_len):
225
+ raise ValueError(
226
+ f"Attention mask should be of size {(bsz, 1, q_len, kv_seq_len)}, but is {attention_mask.size()}"
227
+ )
228
+ attn_weights = attn_weights + attention_mask
229
+ attn_weights = torch.max(
230
+ attn_weights, torch.tensor(torch.finfo(attn_weights.dtype).min, device=attn_weights.device)
231
+ )
232
+
233
+ # upcast attention to fp32
234
+ attn_weights = nn.functional.softmax(attn_weights, dim=-1, dtype=torch.float32).to(query_states.dtype)
235
+ attn_output = torch.matmul(attn_weights, value_states)
236
+
237
+ if attn_output.size() != (bsz, self.num_heads, q_len, self.head_dim):
238
+ raise ValueError(
239
+ f"`attn_output` should be of size {(bsz, self.num_heads, q_len, self.head_dim)}, but is"
240
+ f" {attn_output.size()}"
241
+ )
242
+
243
+ attn_output = attn_output.transpose(1, 2)
244
+ attn_output = attn_output.reshape(bsz, q_len, self.hidden_size)
245
+
246
+ attn_output = self.o_proj(attn_output)
247
+
248
+ if not output_attentions:
249
+ attn_weights = None
250
+
251
+ return attn_output, attn_weights, past_key_value
252
+
253
+
254
+ class DecoderLayer(nn.Module):
255
+ def __init__(self, config: MossConfig):
256
+ super().__init__()
257
+ self.hidden_size = config.hidden_size
258
+ self.self_attn = Attention(config=config)
259
+ self.mlp = MLP(
260
+ hidden_size=self.hidden_size,
261
+ intermediate_size=config.intermediate_size,
262
+ hidden_act=config.hidden_act,
263
+ )
264
+ self.input_layernorm = RMSNorm(config.hidden_size, eps=config.rms_norm_eps)
265
+ self.post_attention_layernorm = RMSNorm(config.hidden_size, eps=config.rms_norm_eps)
266
+
267
+ def forward(
268
+ self,
269
+ hidden_states: torch.Tensor,
270
+ attention_mask: Optional[torch.Tensor] = None,
271
+ position_ids: Optional[torch.LongTensor] = None,
272
+ past_key_value: Optional[Tuple[torch.Tensor]] = None,
273
+ output_attentions: Optional[bool] = False,
274
+ use_cache: Optional[bool] = False,
275
+ ) -> Tuple[torch.FloatTensor, Optional[Tuple[torch.FloatTensor, torch.FloatTensor]]]:
276
+ """
277
+ Args:
278
+ hidden_states (`torch.FloatTensor`): input to the layer of shape `(batch, seq_len, embed_dim)`
279
+ attention_mask (`torch.FloatTensor`, *optional*): attention mask of size
280
+ `(batch, 1, tgt_len, src_len)` where padding elements are indicated by very large negative values.
281
+ output_attentions (`bool`, *optional*):
282
+ Whether or not to return the attentions tensors of all attention layers. See `attentions` under
283
+ returned tensors for more detail.
284
+ use_cache (`bool`, *optional*):
285
+ If set to `True`, `past_key_values` key value states are returned and can be used to speed up decoding
286
+ (see `past_key_values`).
287
+ past_key_value (`Tuple(torch.FloatTensor)`, *optional*): cached past key and value projection states
288
+ """
289
+
290
+ residual = hidden_states
291
+
292
+ hidden_states = self.input_layernorm(hidden_states)
293
+
294
+ # Self Attention
295
+ hidden_states, self_attn_weights, present_key_value = self.self_attn(
296
+ hidden_states=hidden_states,
297
+ attention_mask=attention_mask,
298
+ position_ids=position_ids,
299
+ past_key_value=past_key_value,
300
+ output_attentions=output_attentions,
301
+ use_cache=use_cache,
302
+ )
303
+ hidden_states = residual + hidden_states
304
+
305
+ # Fully Connected
306
+ residual = hidden_states
307
+ hidden_states = self.post_attention_layernorm(hidden_states)
308
+ hidden_states = self.mlp(hidden_states)
309
+ hidden_states = residual + hidden_states
310
+
311
+ outputs = (hidden_states,)
312
+
313
+ if output_attentions:
314
+ outputs += (self_attn_weights,)
315
+
316
+ if use_cache:
317
+ outputs += (present_key_value,)
318
+
319
+ return outputs
320
+
321
+
322
+ MOSS_START_DOCSTRING = r"""
323
+ This model inherits from [`PreTrainedModel`]. Check the superclass documentation for the generic methods the
324
+ library implements for all its model (such as downloading or saving, resizing the input embeddings, pruning heads
325
+ etc.)
326
+
327
+ This model is also a PyTorch [torch.nn.Module](https://pytorch.org/docs/stable/nn.html#torch.nn.Module) subclass.
328
+ Use it as a regular PyTorch Module and refer to the PyTorch documentation for all matter related to general usage
329
+ and behavior.
330
+
331
+ Parameters:
332
+ config ([`MossConfig`]):
333
+ Model configuration class with all the parameters of the model. Initializing with a config file does not
334
+ load the weights associated with the model, only the configuration. Check out the
335
+ [`~PreTrainedModel.from_pretrained`] method to load the model weights.
336
+ """
337
+
338
+
339
+ @add_start_docstrings(
340
+ "The bare Moss Model outputting raw hidden-states without any specific head on top.",
341
+ MOSS_START_DOCSTRING,
342
+ )
343
+ class MossPreTrainedModel(PreTrainedModel):
344
+ config_class = MossConfig
345
+ base_model_prefix = "model"
346
+ supports_gradient_checkpointing = True
347
+ _no_split_modules = ["DecoderLayer"]
348
+ _skip_keys_device_placement = "past_key_values"
349
+ _keys_to_ignore_on_load_unexpected = [r"decoder\.version"]
350
+
351
+ def _init_weights(self, module):
352
+ std = self.config.initializer_range
353
+ if isinstance(module, nn.Linear):
354
+ module.weight.data.normal_(mean=0.0, std=std)
355
+ if module.bias is not None:
356
+ module.bias.data.zero_()
357
+ elif isinstance(module, nn.Embedding):
358
+ module.weight.data.normal_(mean=0.0, std=std)
359
+ if module.padding_idx is not None:
360
+ module.weight.data[module.padding_idx].zero_()
361
+
362
+ def _set_gradient_checkpointing(self, module, value=False):
363
+ if isinstance(module, MossModel):
364
+ module.gradient_checkpointing = value
365
+
366
+
367
+ MOSS_INPUTS_DOCSTRING = r"""
368
+ Args:
369
+ input_ids (`torch.LongTensor` of shape `(batch_size, sequence_length)`):
370
+ Indices of input sequence tokens in the vocabulary. Padding will be ignored by default should you provide
371
+ it.
372
+
373
+ Indices can be obtained using [`AutoTokenizer`]. See [`PreTrainedTokenizer.encode`] and
374
+ [`PreTrainedTokenizer.__call__`] for details.
375
+
376
+ [What are input IDs?](../glossary#input-ids)
377
+ attention_mask (`torch.Tensor` of shape `(batch_size, sequence_length)`, *optional*):
378
+ Mask to avoid performing attention on padding token indices. Mask values selected in `[0, 1]`:
379
+
380
+ - 1 for tokens that are **not masked**,
381
+ - 0 for tokens that are **masked**.
382
+
383
+ [What are attention masks?](../glossary#attention-mask)
384
+
385
+ Indices can be obtained using [`AutoTokenizer`]. See [`PreTrainedTokenizer.encode`] and
386
+ [`PreTrainedTokenizer.__call__`] for details.
387
+
388
+ If `past_key_values` is used, optionally only the last `decoder_input_ids` have to be input (see
389
+ `past_key_values`).
390
+
391
+ If you want to change padding behavior, you should read [`modeling_opt._prepare_decoder_attention_mask`]
392
+ and modify to your needs. See diagram 1 in [the paper](https://arxiv.org/abs/1910.13461) for more
393
+ information on the default strategy.
394
+
395
+ - 1 indicates the head is **not masked**,
396
+ - 0 indicates the head is **masked**.
397
+ position_ids (`torch.LongTensor` of shape `(batch_size, sequence_length)`, *optional*):
398
+ Indices of positions of each input sequence tokens in the position embeddings. Selected in the range `[0,
399
+ config.n_positions - 1]`.
400
+
401
+ [What are position IDs?](../glossary#position-ids)
402
+ past_key_values (`tuple(tuple(torch.FloatTensor))`, *optional*, returned when `use_cache=True` is passed or when `config.use_cache=True`):
403
+ Tuple of `tuple(torch.FloatTensor)` of length `config.n_layers`, with each tuple having 2 tensors of shape
404
+ `(batch_size, num_heads, sequence_length, embed_size_per_head)`) and 2 additional tensors of shape
405
+ `(batch_size, num_heads, encoder_sequence_length, embed_size_per_head)`.
406
+
407
+ Contains pre-computed hidden-states (key and values in the self-attention blocks and in the cross-attention
408
+ blocks) that can be used (see `past_key_values` input) to speed up sequential decoding.
409
+
410
+ If `past_key_values` are used, the user can optionally input only the last `decoder_input_ids` (those that
411
+ don't have their past key value states given to this model) of shape `(batch_size, 1)` instead of all
412
+ `decoder_input_ids` of shape `(batch_size, sequence_length)`.
413
+ inputs_embeds (`torch.FloatTensor` of shape `(batch_size, sequence_length, hidden_size)`, *optional*):
414
+ Optionally, instead of passing `input_ids` you can choose to directly pass an embedded representation. This
415
+ is useful if you want more control over how to convert `input_ids` indices into associated vectors than the
416
+ model's internal embedding lookup matrix.
417
+ use_cache (`bool`, *optional*):
418
+ If set to `True`, `past_key_values` key value states are returned and can be used to speed up decoding (see
419
+ `past_key_values`).
420
+ output_attentions (`bool`, *optional*):
421
+ Whether or not to return the attentions tensors of all attention layers. See `attentions` under returned
422
+ tensors for more detail.
423
+ output_hidden_states (`bool`, *optional*):
424
+ Whether or not to return the hidden states of all layers. See `hidden_states` under returned tensors for
425
+ more detail.
426
+ return_dict (`bool`, *optional*):
427
+ Whether or not to return a [`~utils.ModelOutput`] instead of a plain tuple.
428
+ """
429
+
430
+
431
+ @add_start_docstrings(
432
+ "The bare Moss Model outputting raw hidden-states without any specific head on top.",
433
+ MOSS_START_DOCSTRING,
434
+ )
435
+ class MossModel(MossPreTrainedModel):
436
+ """
437
+ Transformer decoder consisting of *config.num_hidden_layers* layers. Each layer is a [`DecoderLayer`]
438
+
439
+ Args:
440
+ config: MossConfig
441
+ """
442
+
443
+ def __init__(self, config: MossConfig):
444
+ super().__init__(config)
445
+ self.padding_idx = config.pad_token_id
446
+ self.vocab_size = config.vocab_size
447
+
448
+ self.embed_tokens = nn.Embedding(config.vocab_size, config.hidden_size, self.padding_idx)
449
+ self.layers = nn.ModuleList([DecoderLayer(config) for _ in range(config.num_hidden_layers)])
450
+ self.norm = RMSNorm(config.hidden_size, eps=config.rms_norm_eps)
451
+
452
+ self.gradient_checkpointing = False
453
+ # Initialize weights and apply final processing
454
+ self.post_init()
455
+
456
+ def get_input_embeddings(self):
457
+ return self.embed_tokens
458
+
459
+ def set_input_embeddings(self, value):
460
+ self.embed_tokens = value
461
+
462
+ # Copied from transformers.models.bart.modeling_bart.BartDecoder._prepare_decoder_attention_mask
463
+ def _prepare_decoder_attention_mask(self, attention_mask, input_shape, inputs_embeds, past_key_values_length):
464
+ # create causal mask
465
+ # [bsz, seq_len] -> [bsz, 1, tgt_seq_len, src_seq_len]
466
+ combined_attention_mask = None
467
+ if input_shape[-1] > 1:
468
+ combined_attention_mask = _make_causal_mask(
469
+ input_shape,
470
+ inputs_embeds.dtype,
471
+ device=inputs_embeds.device,
472
+ past_key_values_length=past_key_values_length,
473
+ )
474
+
475
+ if attention_mask is not None:
476
+ # [bsz, seq_len] -> [bsz, 1, tgt_seq_len, src_seq_len]
477
+ expanded_attn_mask = _expand_mask(attention_mask, inputs_embeds.dtype, tgt_len=input_shape[-1]).to(
478
+ inputs_embeds.device
479
+ )
480
+ combined_attention_mask = (
481
+ expanded_attn_mask if combined_attention_mask is None else expanded_attn_mask + combined_attention_mask
482
+ )
483
+
484
+ return combined_attention_mask
485
+
486
+ @add_start_docstrings_to_model_forward(MOSS_INPUTS_DOCSTRING)
487
+ def forward(
488
+ self,
489
+ input_ids: torch.LongTensor = None,
490
+ attention_mask: Optional[torch.Tensor] = None,
491
+ position_ids: Optional[torch.LongTensor] = None,
492
+ past_key_values: Optional[List[torch.FloatTensor]] = None,
493
+ inputs_embeds: Optional[torch.FloatTensor] = None,
494
+ use_cache: Optional[bool] = None,
495
+ output_attentions: Optional[bool] = None,
496
+ output_hidden_states: Optional[bool] = None,
497
+ return_dict: Optional[bool] = None,
498
+ ) -> Union[Tuple, BaseModelOutputWithPast]:
499
+ output_attentions = output_attentions if output_attentions is not None else self.config.output_attentions
500
+ output_hidden_states = (
501
+ output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states
502
+ )
503
+ use_cache = use_cache if use_cache is not None else self.config.use_cache
504
+
505
+ return_dict = return_dict if return_dict is not None else self.config.use_return_dict
506
+
507
+ # retrieve input_ids and inputs_embeds
508
+ if input_ids is not None and inputs_embeds is not None:
509
+ raise ValueError("You cannot specify both decoder_input_ids and decoder_inputs_embeds at the same time")
510
+ elif input_ids is not None:
511
+ batch_size, seq_length = input_ids.shape
512
+ elif inputs_embeds is not None:
513
+ batch_size, seq_length, _ = inputs_embeds.shape
514
+ else:
515
+ raise ValueError("You have to specify either decoder_input_ids or decoder_inputs_embeds")
516
+
517
+ seq_length_with_past = seq_length
518
+ past_key_values_length = 0
519
+
520
+ if past_key_values is not None:
521
+ past_key_values_length = past_key_values[0][0].shape[2]
522
+ seq_length_with_past = seq_length_with_past + past_key_values_length
523
+
524
+ if position_ids is None:
525
+ device = input_ids.device if input_ids is not None else inputs_embeds.device
526
+ position_ids = torch.arange(
527
+ past_key_values_length, seq_length + past_key_values_length, dtype=torch.long, device=device
528
+ )
529
+ position_ids = position_ids.unsqueeze(0).view(-1, seq_length)
530
+ else:
531
+ position_ids = position_ids.view(-1, seq_length).long()
532
+
533
+ if inputs_embeds is None:
534
+ inputs_embeds = self.embed_tokens(input_ids)
535
+ # embed positions
536
+ if attention_mask is None:
537
+ attention_mask = torch.ones(
538
+ (batch_size, seq_length_with_past), dtype=torch.bool, device=inputs_embeds.device
539
+ )
540
+ attention_mask = self._prepare_decoder_attention_mask(
541
+ attention_mask, (batch_size, seq_length), inputs_embeds, past_key_values_length
542
+ )
543
+
544
+ hidden_states = inputs_embeds
545
+
546
+ if self.gradient_checkpointing and self.training:
547
+ if use_cache:
548
+ logger.warning_once(
549
+ "`use_cache=True` is incompatible with gradient checkpointing. Setting `use_cache=False`..."
550
+ )
551
+ use_cache = False
552
+
553
+ # decoder layers
554
+ all_hidden_states = () if output_hidden_states else None
555
+ all_self_attns = () if output_attentions else None
556
+ next_decoder_cache = () if use_cache else None
557
+
558
+ for idx, decoder_layer in enumerate(self.layers):
559
+ if output_hidden_states:
560
+ all_hidden_states += (hidden_states,)
561
+
562
+ past_key_value = past_key_values[idx] if past_key_values is not None else None
563
+
564
+ if self.gradient_checkpointing and self.training:
565
+
566
+ def create_custom_forward(module):
567
+ def custom_forward(*inputs):
568
+ # None for past_key_value
569
+ return module(*inputs, output_attentions, None)
570
+
571
+ return custom_forward
572
+
573
+ layer_outputs = torch.utils.checkpoint.checkpoint(
574
+ create_custom_forward(decoder_layer),
575
+ hidden_states,
576
+ attention_mask,
577
+ position_ids,
578
+ None,
579
+ )
580
+ else:
581
+ layer_outputs = decoder_layer(
582
+ hidden_states,
583
+ attention_mask=attention_mask,
584
+ position_ids=position_ids,
585
+ past_key_value=past_key_value,
586
+ output_attentions=output_attentions,
587
+ use_cache=use_cache,
588
+ )
589
+
590
+ hidden_states = layer_outputs[0]
591
+
592
+ if use_cache:
593
+ next_decoder_cache += (layer_outputs[2 if output_attentions else 1],)
594
+
595
+ if output_attentions:
596
+ all_self_attns += (layer_outputs[1],)
597
+
598
+ hidden_states = self.norm(hidden_states)
599
+
600
+ # add hidden states from the last decoder layer
601
+ if output_hidden_states:
602
+ all_hidden_states += (hidden_states,)
603
+
604
+ next_cache = next_decoder_cache if use_cache else None
605
+ if not return_dict:
606
+ return tuple(v for v in [hidden_states, next_cache, all_hidden_states, all_self_attns] if v is not None)
607
+ return BaseModelOutputWithPast(
608
+ last_hidden_state=hidden_states,
609
+ past_key_values=next_cache,
610
+ hidden_states=all_hidden_states,
611
+ attentions=all_self_attns,
612
+ )
613
+
614
+
615
+ class MossForCausalLM(MossPreTrainedModel):
616
+ def __init__(self, config):
617
+ super().__init__(config)
618
+ self.model = MossModel(config)
619
+
620
+ self.lm_head = nn.Linear(config.hidden_size, config.vocab_size, bias=False)
621
+
622
+ # Initialize weights and apply final processing
623
+ self.post_init()
624
+
625
+ def get_input_embeddings(self):
626
+ return self.model.embed_tokens
627
+
628
+ def set_input_embeddings(self, value):
629
+ self.model.embed_tokens = value
630
+
631
+ def get_output_embeddings(self):
632
+ return self.lm_head
633
+
634
+ def set_output_embeddings(self, new_embeddings):
635
+ self.lm_head = new_embeddings
636
+
637
+ def set_decoder(self, decoder):
638
+ self.model = decoder
639
+
640
+ def get_decoder(self):
641
+ return self.model
642
+
643
+ @add_start_docstrings_to_model_forward(MOSS_INPUTS_DOCSTRING)
644
+ @replace_return_docstrings(output_type=CausalLMOutputWithPast, config_class=_CONFIG_FOR_DOC)
645
+ def forward(
646
+ self,
647
+ input_ids: torch.LongTensor = None,
648
+ attention_mask: Optional[torch.Tensor] = None,
649
+ position_ids: Optional[torch.LongTensor] = None,
650
+ past_key_values: Optional[List[torch.FloatTensor]] = None,
651
+ inputs_embeds: Optional[torch.FloatTensor] = None,
652
+ labels: Optional[torch.LongTensor] = None,
653
+ use_cache: Optional[bool] = None,
654
+ output_attentions: Optional[bool] = None,
655
+ output_hidden_states: Optional[bool] = None,
656
+ return_dict: Optional[bool] = None,
657
+ ) -> Union[Tuple, CausalLMOutputWithPast]:
658
+ r"""
659
+ Args:
660
+ labels (`torch.LongTensor` of shape `(batch_size, sequence_length)`, *optional*):
661
+ Labels for computing the masked language modeling loss. Indices should either be in `[0, ...,
662
+ config.vocab_size]` or -100 (see `input_ids` docstring). Tokens with indices set to `-100` are ignored
663
+ (masked), the loss is only computed for the tokens with labels in `[0, ..., config.vocab_size]`.
664
+
665
+ Returns:
666
+
667
+ Example:
668
+
669
+ ```python
670
+ >>> from transformers import AutoTokenizer, MossForCausalLM
671
+
672
+ >>> model = MossForCausalLM.from_pretrained(PATH_TO_CONVERTED_WEIGHTS)
673
+ >>> tokenizer = AutoTokenizer.from_pretrained(PATH_TO_CONVERTED_TOKENIZER)
674
+
675
+ >>> prompt = "Hey, are you consciours? Can you talk to me?"
676
+ >>> inputs = tokenizer(prompt, return_tensors="pt")
677
+
678
+ >>> # Generate
679
+ >>> generate_ids = model.generate(inputs.input_ids, max_length=30)
680
+ >>> tokenizer.batch_decode(generate_ids, skip_special_tokens=True, clean_up_tokenization_spaces=False)[0]
681
+ "Hey, are you consciours? Can you talk to me?\nI'm not consciours, but I can talk to you."
682
+ ```"""
683
+
684
+ output_attentions = output_attentions if output_attentions is not None else self.config.output_attentions
685
+ output_hidden_states = (
686
+ output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states
687
+ )
688
+ return_dict = return_dict if return_dict is not None else self.config.use_return_dict
689
+
690
+ # decoder outputs consists of (dec_features, layer_state, dec_hidden, dec_attn)
691
+ outputs = self.model(
692
+ input_ids=input_ids,
693
+ attention_mask=attention_mask,
694
+ position_ids=position_ids,
695
+ past_key_values=past_key_values,
696
+ inputs_embeds=inputs_embeds,
697
+ use_cache=use_cache,
698
+ output_attentions=output_attentions,
699
+ output_hidden_states=output_hidden_states,
700
+ return_dict=return_dict,
701
+ )
702
+
703
+ hidden_states = outputs[0]
704
+ logits = self.lm_head(hidden_states)
705
+
706
+ loss = None
707
+ if labels is not None:
708
+ # Shift so that tokens < n predict n
709
+ shift_logits = logits[..., :-1, :].contiguous()
710
+ shift_labels = labels[..., 1:].contiguous()
711
+ # Flatten the tokens
712
+ loss_fct = CrossEntropyLoss()
713
+ shift_logits = shift_logits.view(-1, self.config.vocab_size)
714
+ shift_labels = shift_labels.view(-1)
715
+ # Enable model parallelism
716
+ shift_labels = shift_labels.to(shift_logits.device)
717
+ loss = loss_fct(shift_logits, shift_labels)
718
+
719
+ if not return_dict:
720
+ output = (logits,) + outputs[1:]
721
+ return (loss,) + output if loss is not None else output
722
+
723
+ return CausalLMOutputWithPast(
724
+ loss=loss,
725
+ logits=logits,
726
+ past_key_values=outputs.past_key_values,
727
+ hidden_states=outputs.hidden_states,
728
+ attentions=outputs.attentions,
729
+ )
730
+
731
+ def prepare_inputs_for_generation(
732
+ self, input_ids, past_key_values=None, attention_mask=None, inputs_embeds=None, **kwargs
733
+ ):
734
+ if past_key_values:
735
+ input_ids = input_ids[:, -1:]
736
+
737
+ position_ids = kwargs.get("position_ids", None)
738
+ if attention_mask is not None and position_ids is None:
739
+ # create position_ids on the fly for batch generation
740
+ position_ids = attention_mask.long().cumsum(-1) - 1
741
+ position_ids.masked_fill_(attention_mask == 0, 1)
742
+ if past_key_values:
743
+ position_ids = position_ids[:, -1].unsqueeze(-1)
744
+
745
+ # if `inputs_embeds` are passed, we only want to use them in the 1st generation step
746
+ if inputs_embeds is not None and past_key_values is None:
747
+ model_inputs = {"inputs_embeds": inputs_embeds}
748
+ else:
749
+ model_inputs = {"input_ids": input_ids}
750
+
751
+ model_inputs.update(
752
+ {
753
+ "position_ids": position_ids,
754
+ "past_key_values": past_key_values,
755
+ "use_cache": kwargs.get("use_cache"),
756
+ "attention_mask": attention_mask,
757
+ }
758
+ )
759
+ return model_inputs
760
+
761
+ @staticmethod
762
+ def _reorder_cache(past_key_values, beam_idx):
763
+ reordered_past = ()
764
+ for layer_past in past_key_values:
765
+ reordered_past += (tuple(past_state.index_select(0, beam_idx) for past_state in layer_past),)
766
+ return reordered_past
767
+
768
+
769
+ @add_start_docstrings(
770
+ """
771
+ The Moss Model transformer with a sequence classification head on top (linear layer).
772
+
773
+ [`MossForSequenceClassification`] uses the last token in order to do the classification, as other causal models
774
+ (e.g. GPT-2) do.
775
+
776
+ Since it does classification on the last token, it requires to know the position of the last token. If a
777
+ `pad_token_id` is defined in the configuration, it finds the last token that is not a padding token in each row. If
778
+ no `pad_token_id` is defined, it simply takes the last value in each row of the batch. Since it cannot guess the
779
+ padding tokens when `inputs_embeds` are passed instead of `input_ids`, it does the same (take the last value in
780
+ each row of the batch).
781
+ """,
782
+ MOSS_START_DOCSTRING,
783
+ )
784
+ class MossForSequenceClassification(MossPreTrainedModel):
785
+ _keys_to_ignore_on_load_missing = [r"lm_head.weight"]
786
+
787
+ def __init__(self, config):
788
+ super().__init__(config)
789
+ self.num_labels = config.num_labels
790
+ self.model = MossModel(config)
791
+ self.score = nn.Linear(config.hidden_size, self.num_labels, bias=False)
792
+
793
+ # Initialize weights and apply final processing
794
+ self.post_init()
795
+
796
+ def get_input_embeddings(self):
797
+ return self.model.embed_tokens
798
+
799
+ def set_input_embeddings(self, value):
800
+ self.model.embed_tokens = value
801
+
802
+ @add_start_docstrings_to_model_forward(MOSS_INPUTS_DOCSTRING)
803
+ def forward(
804
+ self,
805
+ input_ids: torch.LongTensor = None,
806
+ attention_mask: Optional[torch.Tensor] = None,
807
+ position_ids: Optional[torch.LongTensor] = None,
808
+ past_key_values: Optional[List[torch.FloatTensor]] = None,
809
+ inputs_embeds: Optional[torch.FloatTensor] = None,
810
+ labels: Optional[torch.LongTensor] = None,
811
+ use_cache: Optional[bool] = None,
812
+ output_attentions: Optional[bool] = None,
813
+ output_hidden_states: Optional[bool] = None,
814
+ return_dict: Optional[bool] = None,
815
+ ) -> Union[Tuple, SequenceClassifierOutputWithPast]:
816
+ r"""
817
+ labels (`torch.LongTensor` of shape `(batch_size,)`, *optional*):
818
+ Labels for computing the sequence classification/regression loss. Indices should be in `[0, ...,
819
+ config.num_labels - 1]`. If `config.num_labels == 1` a regression loss is computed (Mean-Square loss), If
820
+ `config.num_labels > 1` a classification loss is computed (Cross-Entropy).
821
+ """
822
+ return_dict = return_dict if return_dict is not None else self.config.use_return_dict
823
+
824
+ transformer_outputs = self.model(
825
+ input_ids,
826
+ attention_mask=attention_mask,
827
+ position_ids=position_ids,
828
+ past_key_values=past_key_values,
829
+ inputs_embeds=inputs_embeds,
830
+ use_cache=use_cache,
831
+ output_attentions=output_attentions,
832
+ output_hidden_states=output_hidden_states,
833
+ return_dict=return_dict,
834
+ )
835
+ hidden_states = transformer_outputs[0]
836
+ logits = self.score(hidden_states)
837
+
838
+ if input_ids is not None:
839
+ batch_size = input_ids.shape[0]
840
+ else:
841
+ batch_size = inputs_embeds.shape[0]
842
+
843
+ if self.config.pad_token_id is None and batch_size != 1:
844
+ raise ValueError("Cannot handle batch sizes > 1 if no padding token is defined.")
845
+ if self.config.pad_token_id is None:
846
+ sequence_lengths = -1
847
+ else:
848
+ if input_ids is not None:
849
+ sequence_lengths = (torch.ne(input_ids, self.config.pad_token_id).sum(-1) - 1).to(logits.device)
850
+ else:
851
+ sequence_lengths = -1
852
+
853
+ pooled_logits = logits[torch.arange(batch_size, device=logits.device), sequence_lengths]
854
+
855
+ loss = None
856
+ if labels is not None:
857
+ labels = labels.to(logits.device)
858
+ if self.config.problem_type is None:
859
+ if self.num_labels == 1:
860
+ self.config.problem_type = "regression"
861
+ elif self.num_labels > 1 and (labels.dtype == torch.long or labels.dtype == torch.int):
862
+ self.config.problem_type = "single_label_classification"
863
+ else:
864
+ self.config.problem_type = "multi_label_classification"
865
+
866
+ if self.config.problem_type == "regression":
867
+ loss_fct = MSELoss()
868
+ if self.num_labels == 1:
869
+ loss = loss_fct(pooled_logits.squeeze(), labels.squeeze())
870
+ else:
871
+ loss = loss_fct(pooled_logits, labels)
872
+ elif self.config.problem_type == "single_label_classification":
873
+ loss_fct = CrossEntropyLoss()
874
+ loss = loss_fct(pooled_logits.view(-1, self.num_labels), labels.view(-1))
875
+ elif self.config.problem_type == "multi_label_classification":
876
+ loss_fct = BCEWithLogitsLoss()
877
+ loss = loss_fct(pooled_logits, labels)
878
+ if not return_dict:
879
+ output = (pooled_logits,) + transformer_outputs[1:]
880
+ return ((loss,) + output) if loss is not None else output
881
+
882
+ return SequenceClassifierOutputWithPast(
883
+ loss=loss,
884
+ logits=pooled_logits,
885
+ past_key_values=transformer_outputs.past_key_values,
886
+ hidden_states=transformer_outputs.hidden_states,
887
+ attentions=transformer_outputs.attentions,
888
+ )