Muennighoff commited on
Commit
36e9dee
1 Parent(s): 4d093c0

Create modeling_gritlm7b.py

Browse files
Files changed (1) hide show
  1. modeling_gritlm7b.py +1419 -0
modeling_gritlm7b.py ADDED
@@ -0,0 +1,1419 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # coding=utf-8
2
+ # Copyright 2023 Mistral AI 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 Mistral model."""
21
+ import inspect
22
+ import math
23
+ import os
24
+ import warnings
25
+ from typing import List, Optional, Tuple, Union
26
+
27
+ import torch
28
+ import torch.nn.functional as F
29
+ import torch.utils.checkpoint
30
+ from torch import nn
31
+ from torch.nn import BCEWithLogitsLoss, CrossEntropyLoss, MSELoss
32
+
33
+ from ...activations import ACT2FN
34
+ from ...cache_utils import Cache, DynamicCache
35
+ from ...modeling_attn_mask_utils import _prepare_4d_causal_attention_mask, _prepare_4d_causal_attention_mask_for_sdpa, _prepare_4d_attention_mask, _prepare_4d_attention_mask_for_sdpa
36
+ from ...modeling_outputs import BaseModelOutputWithPast, CausalLMOutputWithPast, SequenceClassifierOutputWithPast
37
+ from ...modeling_utils import PreTrainedModel
38
+ from ...utils import (
39
+ add_start_docstrings,
40
+ add_start_docstrings_to_model_forward,
41
+ is_flash_attn_2_available,
42
+ is_flash_attn_greater_or_equal_2_10,
43
+ logging,
44
+ replace_return_docstrings,
45
+ )
46
+ from .configuration_mistral import MistralConfig
47
+
48
+
49
+ if is_flash_attn_2_available():
50
+ from flash_attn import flash_attn_func, flash_attn_varlen_func
51
+ from flash_attn.bert_padding import index_first_axis, pad_input, unpad_input # noqa
52
+
53
+ _flash_supports_window_size = "window_size" in list(inspect.signature(flash_attn_func).parameters)
54
+
55
+
56
+ logger = logging.get_logger(__name__)
57
+
58
+ _CONFIG_FOR_DOC = "MistralConfig"
59
+
60
+
61
+ # Copied from transformers.models.llama.modeling_llama._get_unpad_data
62
+ def _get_unpad_data(attention_mask):
63
+ seqlens_in_batch = attention_mask.sum(dim=-1, dtype=torch.int32)
64
+ indices = torch.nonzero(attention_mask.flatten(), as_tuple=False).flatten()
65
+ max_seqlen_in_batch = seqlens_in_batch.max().item()
66
+ cu_seqlens = F.pad(torch.cumsum(seqlens_in_batch, dim=0, dtype=torch.torch.int32), (1, 0))
67
+ return (
68
+ indices,
69
+ cu_seqlens,
70
+ max_seqlen_in_batch,
71
+ )
72
+
73
+
74
+ # Copied from transformers.models.llama.modeling_llama.LlamaRMSNorm with Llama->Mistral
75
+ class MistralRMSNorm(nn.Module):
76
+ def __init__(self, hidden_size, eps=1e-6):
77
+ """
78
+ MistralRMSNorm is equivalent to T5LayerNorm
79
+ """
80
+ super().__init__()
81
+ self.weight = nn.Parameter(torch.ones(hidden_size))
82
+ self.variance_epsilon = eps
83
+
84
+ def forward(self, hidden_states):
85
+ input_dtype = hidden_states.dtype
86
+ hidden_states = hidden_states.to(torch.float32)
87
+ variance = hidden_states.pow(2).mean(-1, keepdim=True)
88
+ hidden_states = hidden_states * torch.rsqrt(variance + self.variance_epsilon)
89
+ return self.weight * hidden_states.to(input_dtype)
90
+
91
+
92
+ # Copied from transformers.models.llama.modeling_llama.LlamaRotaryEmbedding with Llama->Mistral
93
+ class MistralRotaryEmbedding(nn.Module):
94
+ def __init__(self, dim, max_position_embeddings=2048, base=10000, device=None):
95
+ super().__init__()
96
+
97
+ self.dim = dim
98
+ self.max_position_embeddings = max_position_embeddings
99
+ self.base = base
100
+ inv_freq = 1.0 / (self.base ** (torch.arange(0, self.dim, 2).float().to(device) / self.dim))
101
+ self.register_buffer("inv_freq", inv_freq, persistent=False)
102
+
103
+ # Build here to make `torch.jit.trace` work.
104
+ self._set_cos_sin_cache(
105
+ seq_len=max_position_embeddings, device=self.inv_freq.device, dtype=torch.get_default_dtype()
106
+ )
107
+
108
+ def _set_cos_sin_cache(self, seq_len, device, dtype):
109
+ self.max_seq_len_cached = seq_len
110
+ t = torch.arange(self.max_seq_len_cached, device=device, dtype=self.inv_freq.dtype)
111
+
112
+ freqs = torch.outer(t, self.inv_freq)
113
+ # Different from paper, but it uses a different permutation in order to obtain the same calculation
114
+ emb = torch.cat((freqs, freqs), dim=-1)
115
+ self.register_buffer("cos_cached", emb.cos().to(dtype), persistent=False)
116
+ self.register_buffer("sin_cached", emb.sin().to(dtype), persistent=False)
117
+
118
+ def forward(self, x, seq_len=None):
119
+ # x: [bs, num_attention_heads, seq_len, head_size]
120
+ if seq_len > self.max_seq_len_cached:
121
+ self._set_cos_sin_cache(seq_len=seq_len, device=x.device, dtype=x.dtype)
122
+
123
+ return (
124
+ self.cos_cached[:seq_len].to(dtype=x.dtype),
125
+ self.sin_cached[:seq_len].to(dtype=x.dtype),
126
+ )
127
+
128
+
129
+ # Copied from transformers.models.llama.modeling_llama.rotate_half
130
+ def rotate_half(x):
131
+ """Rotates half the hidden dims of the input."""
132
+ x1 = x[..., : x.shape[-1] // 2]
133
+ x2 = x[..., x.shape[-1] // 2 :]
134
+ return torch.cat((-x2, x1), dim=-1)
135
+
136
+
137
+ # Copied from transformers.models.llama.modeling_llama.apply_rotary_pos_emb
138
+ def apply_rotary_pos_emb(q, k, cos, sin, position_ids, unsqueeze_dim=1):
139
+ """Applies Rotary Position Embedding to the query and key tensors.
140
+
141
+ Args:
142
+ q (`torch.Tensor`): The query tensor.
143
+ k (`torch.Tensor`): The key tensor.
144
+ cos (`torch.Tensor`): The cosine part of the rotary embedding.
145
+ sin (`torch.Tensor`): The sine part of the rotary embedding.
146
+ position_ids (`torch.Tensor`):
147
+ The position indices of the tokens corresponding to the query and key tensors. For example, this can be
148
+ used to pass offsetted position ids when working with a KV-cache.
149
+ unsqueeze_dim (`int`, *optional*, defaults to 1):
150
+ The 'unsqueeze_dim' argument specifies the dimension along which to unsqueeze cos[position_ids] and
151
+ sin[position_ids] so that they can be properly broadcasted to the dimensions of q and k. For example, note
152
+ that cos[position_ids] and sin[position_ids] have the shape [batch_size, seq_len, head_dim]. Then, if q and
153
+ k have the shape [batch_size, heads, seq_len, head_dim], then setting unsqueeze_dim=1 makes
154
+ cos[position_ids] and sin[position_ids] broadcastable to the shapes of q and k. Similarly, if q and k have
155
+ the shape [batch_size, seq_len, heads, head_dim], then set unsqueeze_dim=2.
156
+ Returns:
157
+ `tuple(torch.Tensor)` comprising of the query and key tensors rotated using the Rotary Position Embedding.
158
+ """
159
+ cos = cos[position_ids].unsqueeze(unsqueeze_dim)
160
+ sin = sin[position_ids].unsqueeze(unsqueeze_dim)
161
+ q_embed = (q * cos) + (rotate_half(q) * sin)
162
+ k_embed = (k * cos) + (rotate_half(k) * sin)
163
+ return q_embed, k_embed
164
+
165
+
166
+ class MistralMLP(nn.Module):
167
+ def __init__(self, config):
168
+ super().__init__()
169
+ self.config = config
170
+ self.hidden_size = config.hidden_size
171
+ self.intermediate_size = config.intermediate_size
172
+ self.gate_proj = nn.Linear(self.hidden_size, self.intermediate_size, bias=False)
173
+ self.up_proj = nn.Linear(self.hidden_size, self.intermediate_size, bias=False)
174
+ self.down_proj = nn.Linear(self.intermediate_size, self.hidden_size, bias=False)
175
+ self.act_fn = ACT2FN[config.hidden_act]
176
+
177
+ def forward(self, x):
178
+ return self.down_proj(self.act_fn(self.gate_proj(x)) * self.up_proj(x))
179
+
180
+
181
+ # Copied from transformers.models.llama.modeling_llama.repeat_kv
182
+ def repeat_kv(hidden_states: torch.Tensor, n_rep: int) -> torch.Tensor:
183
+ """
184
+ This is the equivalent of torch.repeat_interleave(x, dim=1, repeats=n_rep). The hidden states go from (batch,
185
+ num_key_value_heads, seqlen, head_dim) to (batch, num_attention_heads, seqlen, head_dim)
186
+ """
187
+ batch, num_key_value_heads, slen, head_dim = hidden_states.shape
188
+ if n_rep == 1:
189
+ return hidden_states
190
+ hidden_states = hidden_states[:, :, None, :, :].expand(batch, num_key_value_heads, n_rep, slen, head_dim)
191
+ return hidden_states.reshape(batch, num_key_value_heads * n_rep, slen, head_dim)
192
+
193
+
194
+ class MistralAttention(nn.Module):
195
+ """
196
+ Multi-headed attention from 'Attention Is All You Need' paper. Modified to use sliding window attention: Longformer
197
+ and "Generating Long Sequences with Sparse Transformers".
198
+ """
199
+
200
+ def __init__(self, config: MistralConfig, layer_idx: Optional[int] = None):
201
+ super().__init__()
202
+ self.config = config
203
+ self.layer_idx = layer_idx
204
+ if layer_idx is None:
205
+ logger.warning_once(
206
+ f"Instantiating {self.__class__.__name__} without passing `layer_idx` is not recommended and will "
207
+ "to errors during the forward call, if caching is used. Please make sure to provide a `layer_idx` "
208
+ "when creating this class."
209
+ )
210
+
211
+ self.hidden_size = config.hidden_size
212
+ self.num_heads = config.num_attention_heads
213
+ self.head_dim = self.hidden_size // self.num_heads
214
+ self.num_key_value_heads = config.num_key_value_heads
215
+ self.num_key_value_groups = self.num_heads // self.num_key_value_heads
216
+ self.max_position_embeddings = config.max_position_embeddings
217
+ self.rope_theta = config.rope_theta
218
+ self.attention_dropout = config.attention_dropout
219
+
220
+ if (self.head_dim * self.num_heads) != self.hidden_size:
221
+ raise ValueError(
222
+ f"hidden_size must be divisible by num_heads (got `hidden_size`: {self.hidden_size}"
223
+ f" and `num_heads`: {self.num_heads})."
224
+ )
225
+ self.q_proj = nn.Linear(self.hidden_size, self.num_heads * self.head_dim, bias=False)
226
+ self.k_proj = nn.Linear(self.hidden_size, self.num_key_value_heads * self.head_dim, bias=False)
227
+ self.v_proj = nn.Linear(self.hidden_size, self.num_key_value_heads * self.head_dim, bias=False)
228
+ self.o_proj = nn.Linear(self.num_heads * self.head_dim, self.hidden_size, bias=False)
229
+
230
+ self.rotary_emb = MistralRotaryEmbedding(
231
+ self.head_dim,
232
+ max_position_embeddings=self.max_position_embeddings,
233
+ base=self.rope_theta,
234
+ )
235
+
236
+ def _shape(self, tensor: torch.Tensor, seq_len: int, bsz: int):
237
+ return tensor.view(bsz, seq_len, self.num_heads, self.head_dim).transpose(1, 2).contiguous()
238
+
239
+ def forward(
240
+ self,
241
+ hidden_states: torch.Tensor,
242
+ attention_mask: Optional[torch.Tensor] = None,
243
+ position_ids: Optional[torch.LongTensor] = None,
244
+ past_key_value: Optional[Cache] = None,
245
+ output_attentions: bool = False,
246
+ use_cache: bool = False,
247
+ **kwargs,
248
+ ) -> Tuple[torch.Tensor, Optional[torch.Tensor], Optional[Tuple[torch.Tensor]]]:
249
+ if "padding_mask" in kwargs:
250
+ warnings.warn(
251
+ "Passing `padding_mask` is deprecated and will be removed in v4.37. Please make sure use `attention_mask` instead.`"
252
+ )
253
+ bsz, q_len, _ = hidden_states.size()
254
+
255
+ query_states = self.q_proj(hidden_states)
256
+ key_states = self.k_proj(hidden_states)
257
+ value_states = self.v_proj(hidden_states)
258
+
259
+ query_states = query_states.view(bsz, q_len, self.num_heads, self.head_dim).transpose(1, 2)
260
+ key_states = key_states.view(bsz, q_len, self.num_key_value_heads, self.head_dim).transpose(1, 2)
261
+ value_states = value_states.view(bsz, q_len, self.num_key_value_heads, self.head_dim).transpose(1, 2)
262
+
263
+ kv_seq_len = key_states.shape[-2]
264
+ if past_key_value is not None:
265
+ if self.layer_idx is None:
266
+ raise ValueError(
267
+ f"The cache structure has changed since version v4.36. If you are using {self.__class__.__name__} "
268
+ "for auto-regressive decoding with k/v caching, please make sure to initialize the attention class "
269
+ "with a layer index."
270
+ )
271
+ kv_seq_len += past_key_value.get_usable_length(kv_seq_len, self.layer_idx)
272
+ cos, sin = self.rotary_emb(value_states, seq_len=kv_seq_len)
273
+ query_states, key_states = apply_rotary_pos_emb(query_states, key_states, cos, sin, position_ids)
274
+
275
+ if past_key_value is not None:
276
+ cache_kwargs = {"sin": sin, "cos": cos} # Specific to RoPE models
277
+ key_states, value_states = past_key_value.update(key_states, value_states, self.layer_idx, cache_kwargs)
278
+
279
+ # repeat k/v heads if n_kv_heads < n_heads
280
+ key_states = repeat_kv(key_states, self.num_key_value_groups)
281
+ value_states = repeat_kv(value_states, self.num_key_value_groups)
282
+
283
+ attn_weights = torch.matmul(query_states, key_states.transpose(2, 3)) / math.sqrt(self.head_dim)
284
+
285
+ if attn_weights.size() != (bsz, self.num_heads, q_len, kv_seq_len):
286
+ raise ValueError(
287
+ f"Attention weights should be of size {(bsz, self.num_heads, q_len, kv_seq_len)}, but is"
288
+ f" {attn_weights.size()}"
289
+ )
290
+
291
+ if attention_mask is not None:
292
+ if attention_mask.size() != (bsz, 1, q_len, kv_seq_len):
293
+ raise ValueError(
294
+ f"Attention mask should be of size {(bsz, 1, q_len, kv_seq_len)}, but is {attention_mask.size()}"
295
+ )
296
+
297
+ attn_weights = attn_weights + attention_mask
298
+
299
+ # upcast attention to fp32
300
+ attn_weights = nn.functional.softmax(attn_weights, dim=-1, dtype=torch.float32).to(query_states.dtype)
301
+ attn_weights = nn.functional.dropout(attn_weights, p=self.attention_dropout, training=self.training)
302
+ attn_output = torch.matmul(attn_weights, value_states)
303
+
304
+ if attn_output.size() != (bsz, self.num_heads, q_len, self.head_dim):
305
+ raise ValueError(
306
+ f"`attn_output` should be of size {(bsz, self.num_heads, q_len, self.head_dim)}, but is"
307
+ f" {attn_output.size()}"
308
+ )
309
+
310
+ attn_output = attn_output.transpose(1, 2).contiguous()
311
+ attn_output = attn_output.reshape(bsz, q_len, self.hidden_size)
312
+
313
+ attn_output = self.o_proj(attn_output)
314
+
315
+ if not output_attentions:
316
+ attn_weights = None
317
+
318
+ return attn_output, attn_weights, past_key_value
319
+
320
+
321
+ class MistralFlashAttention2(MistralAttention):
322
+ """
323
+ Mistral flash attention module. This module inherits from `MistralAttention` as the weights of the module stays
324
+ untouched. The only required change would be on the forward pass where it needs to correctly call the public API of
325
+ flash attention and deal with padding tokens in case the input contains any of them.
326
+ """
327
+
328
+ # Copied from transformers.models.llama.modeling_llama.LlamaFlashAttention2.__init__
329
+ def __init__(self, *args, **kwargs):
330
+ super().__init__(*args, **kwargs)
331
+
332
+ # TODO: Should be removed once Flash Attention for RoCm is bumped to 2.1.
333
+ # flash_attn<2.1 generates top-left aligned causal mask, while what is needed here is bottom-right alignement, that was made default for flash_attn>=2.1. This attribute is used to handle this difference. Reference: https://github.com/Dao-AILab/flash-attention/releases/tag/v2.1.0.
334
+ # Beware that with flash_attn<2.1, using q_seqlen != k_seqlen (except for the case q_seqlen == 1) produces a wrong mask (top-left).
335
+ self._flash_attn_uses_top_left_mask = not is_flash_attn_greater_or_equal_2_10()
336
+
337
+ def forward(
338
+ self,
339
+ hidden_states: torch.Tensor,
340
+ attention_mask: Optional[torch.Tensor] = None,
341
+ position_ids: Optional[torch.LongTensor] = None,
342
+ past_key_value: Optional[Cache] = None,
343
+ output_attentions: bool = False,
344
+ use_cache: bool = False,
345
+ is_causal: bool = True,
346
+ **kwargs,
347
+ ):
348
+ if "padding_mask" in kwargs:
349
+ warnings.warn(
350
+ "Passing `padding_mask` is deprecated and will be removed in v4.37. Please make sure use `attention_mask` instead.`"
351
+ )
352
+
353
+ # overwrite attention_mask with padding_mask
354
+ attention_mask = kwargs.pop("padding_mask")
355
+ bsz, q_len, _ = hidden_states.size()
356
+
357
+ query_states = self.q_proj(hidden_states)
358
+ key_states = self.k_proj(hidden_states)
359
+ value_states = self.v_proj(hidden_states)
360
+
361
+ query_states = query_states.view(bsz, q_len, self.num_heads, self.head_dim).transpose(1, 2)
362
+ key_states = key_states.view(bsz, q_len, self.num_key_value_heads, self.head_dim).transpose(1, 2)
363
+ value_states = value_states.view(bsz, q_len, self.num_key_value_heads, self.head_dim).transpose(1, 2)
364
+
365
+ kv_seq_len = key_states.shape[-2]
366
+ if past_key_value is not None:
367
+ if self.layer_idx is None:
368
+ raise ValueError(
369
+ f"The cache structure has changed since version v4.36. If you are using {self.__class__.__name__} "
370
+ "for auto-regressive decoding with k/v caching, please make sure to initialize the attention class "
371
+ "with a layer index."
372
+ )
373
+ kv_seq_len += past_key_value.get_usable_length(kv_seq_len, self.layer_idx)
374
+
375
+ # Because the input can be padded, the absolute sequence length depends on the max position id.
376
+ rotary_seq_len = max(kv_seq_len, position_ids[:, -1].max().item()) + 1
377
+ cos, sin = self.rotary_emb(value_states, seq_len=rotary_seq_len)
378
+
379
+ query_states, key_states = apply_rotary_pos_emb(query_states, key_states, cos, sin, position_ids)
380
+
381
+ use_sliding_windows = (
382
+ _flash_supports_window_size
383
+ and getattr(self.config, "sliding_window", None) is not None
384
+ and kv_seq_len > self.config.sliding_window
385
+ )
386
+
387
+ if not _flash_supports_window_size:
388
+ logger.warning_once(
389
+ "The current flash attention version does not support sliding window attention, for a more memory efficient implementation"
390
+ " make sure to upgrade flash-attn library."
391
+ )
392
+
393
+ if past_key_value is not None:
394
+ # Activate slicing cache only if the config has a value `sliding_windows` attribute
395
+ cache_has_contents = past_key_value.get_seq_length(self.layer_idx) > 0
396
+ if (
397
+ getattr(self.config, "sliding_window", None) is not None
398
+ and kv_seq_len > self.config.sliding_window
399
+ and cache_has_contents
400
+ ):
401
+ slicing_tokens = 1 - self.config.sliding_window
402
+
403
+ past_key = past_key_value[self.layer_idx][0]
404
+ past_value = past_key_value[self.layer_idx][1]
405
+
406
+ past_key = past_key[:, :, slicing_tokens:, :].contiguous()
407
+ past_value = past_value[:, :, slicing_tokens:, :].contiguous()
408
+
409
+ if past_key.shape[-2] != self.config.sliding_window - 1:
410
+ raise ValueError(
411
+ f"past key must have a shape of (`batch_size, num_heads, self.config.sliding_window-1, head_dim`), got"
412
+ f" {past_key.shape}"
413
+ )
414
+
415
+ if attention_mask is not None:
416
+ attention_mask = attention_mask[:, slicing_tokens:]
417
+ attention_mask = torch.cat([attention_mask, torch.ones_like(attention_mask[:, -1:])], dim=-1)
418
+
419
+ cache_kwargs = {"sin": sin, "cos": cos} # Specific to RoPE models
420
+ key_states, value_states = past_key_value.update(key_states, value_states, self.layer_idx, cache_kwargs)
421
+
422
+ # repeat k/v heads if n_kv_heads < n_heads
423
+ key_states = repeat_kv(key_states, self.num_key_value_groups)
424
+ value_states = repeat_kv(value_states, self.num_key_value_groups)
425
+ dropout_rate = 0.0 if not self.training else self.attention_dropout
426
+
427
+ # In PEFT, usually we cast the layer norms in float32 for training stability reasons
428
+ # therefore the input hidden states gets silently casted in float32. Hence, we need
429
+ # cast them back in float16 just to be sure everything works as expected.
430
+ input_dtype = query_states.dtype
431
+ if input_dtype == torch.float32:
432
+ if torch.is_autocast_enabled():
433
+ target_dtype = torch.get_autocast_gpu_dtype()
434
+ # Handle the case where the model is quantized
435
+ elif hasattr(self.config, "_pre_quantization_dtype"):
436
+ target_dtype = self.config._pre_quantization_dtype
437
+ else:
438
+ target_dtype = self.q_proj.weight.dtype
439
+
440
+ logger.warning_once(
441
+ f"The input hidden states seems to be silently casted in float32, this might be related to"
442
+ f" the fact you have upcasted embedding or layer norm layers in float32. We will cast back the input in"
443
+ f" {target_dtype}."
444
+ )
445
+
446
+ query_states = query_states.to(target_dtype)
447
+ key_states = key_states.to(target_dtype)
448
+ value_states = value_states.to(target_dtype)
449
+
450
+ # Reashape to the expected shape for Flash Attention
451
+ query_states = query_states.transpose(1, 2)
452
+ key_states = key_states.transpose(1, 2)
453
+ value_states = value_states.transpose(1, 2)
454
+
455
+ attn_output = self._flash_attention_forward(
456
+ query_states,
457
+ key_states,
458
+ value_states,
459
+ attention_mask,
460
+ q_len,
461
+ dropout=dropout_rate,
462
+ use_sliding_windows=use_sliding_windows,
463
+ is_causal=is_causal,
464
+ )
465
+
466
+ attn_output = attn_output.reshape(bsz, q_len, self.hidden_size).contiguous()
467
+ attn_output = self.o_proj(attn_output)
468
+
469
+ if not output_attentions:
470
+ attn_weights = None
471
+
472
+ return attn_output, attn_weights, past_key_value
473
+
474
+ def _flash_attention_forward(
475
+ self,
476
+ query_states,
477
+ key_states,
478
+ value_states,
479
+ attention_mask,
480
+ query_length,
481
+ dropout=0.0,
482
+ softmax_scale=None,
483
+ use_sliding_windows=False,
484
+ is_causal=True,
485
+ ):
486
+ """
487
+ Calls the forward method of Flash Attention - if the input hidden states contain at least one padding token
488
+ first unpad the input, then computes the attention scores and pad the final attention scores.
489
+
490
+ Args:
491
+ query_states (`torch.Tensor`):
492
+ Input query states to be passed to Flash Attention API
493
+ key_states (`torch.Tensor`):
494
+ Input key states to be passed to Flash Attention API
495
+ value_states (`torch.Tensor`):
496
+ Input value states to be passed to Flash Attention API
497
+ attention_mask (`torch.Tensor`):
498
+ The padding mask - corresponds to a tensor of size `(batch_size, seq_len)` where 0 stands for the
499
+ position of padding tokens and 1 for the position of non-padding tokens.
500
+ dropout (`int`, *optional*):
501
+ Attention dropout
502
+ softmax_scale (`float`, *optional*):
503
+ The scaling of QK^T before applying softmax. Default to 1 / sqrt(head_dim)
504
+ use_sliding_windows (`bool`, *optional*):
505
+ Whether to activate sliding window attention.
506
+ """
507
+ if not self._flash_attn_uses_top_left_mask:
508
+ causal = is_causal
509
+ else:
510
+ # TODO: Remove the `query_length != 1` check once Flash Attention for RoCm is bumped to 2.1. For details, please see the comment in LlamaFlashAttention2 __init__.
511
+ causal = is_causal and query_length != 1
512
+
513
+ # Contains at least one padding token in the sequence
514
+ if attention_mask is not None:
515
+ batch_size = query_states.shape[0]
516
+ query_states, key_states, value_states, indices_q, cu_seq_lens, max_seq_lens = self._upad_input(
517
+ query_states, key_states, value_states, attention_mask, query_length
518
+ )
519
+
520
+ cu_seqlens_q, cu_seqlens_k = cu_seq_lens
521
+ max_seqlen_in_batch_q, max_seqlen_in_batch_k = max_seq_lens
522
+
523
+ if not use_sliding_windows:
524
+ attn_output_unpad = flash_attn_varlen_func(
525
+ query_states,
526
+ key_states,
527
+ value_states,
528
+ cu_seqlens_q=cu_seqlens_q,
529
+ cu_seqlens_k=cu_seqlens_k,
530
+ max_seqlen_q=max_seqlen_in_batch_q,
531
+ max_seqlen_k=max_seqlen_in_batch_k,
532
+ dropout_p=dropout,
533
+ softmax_scale=softmax_scale,
534
+ causal=causal,
535
+ )
536
+ else:
537
+ attn_output_unpad = flash_attn_varlen_func(
538
+ query_states,
539
+ key_states,
540
+ value_states,
541
+ cu_seqlens_q=cu_seqlens_q,
542
+ cu_seqlens_k=cu_seqlens_k,
543
+ max_seqlen_q=max_seqlen_in_batch_q,
544
+ max_seqlen_k=max_seqlen_in_batch_k,
545
+ dropout_p=dropout,
546
+ softmax_scale=softmax_scale,
547
+ causal=causal,
548
+ window_size=(self.config.sliding_window, self.config.sliding_window),
549
+ )
550
+
551
+ attn_output = pad_input(attn_output_unpad, indices_q, batch_size, query_length)
552
+ else:
553
+ if not use_sliding_windows:
554
+ attn_output = flash_attn_func(
555
+ query_states,
556
+ key_states,
557
+ value_states,
558
+ dropout,
559
+ softmax_scale=softmax_scale,
560
+ causal=causal,
561
+ )
562
+ else:
563
+ attn_output = flash_attn_func(
564
+ query_states,
565
+ key_states,
566
+ value_states,
567
+ dropout,
568
+ softmax_scale=softmax_scale,
569
+ causal=causal,
570
+ window_size=(self.config.sliding_window, self.config.sliding_window),
571
+ )
572
+
573
+ return attn_output
574
+
575
+ def _upad_input(self, query_layer, key_layer, value_layer, attention_mask, query_length):
576
+ batch_size, kv_seq_len, num_heads, head_dim = key_layer.shape
577
+
578
+ # On the first iteration we need to properly re-create the padding mask
579
+ # by slicing it on the proper place
580
+ if kv_seq_len != attention_mask.shape[-1]:
581
+ attention_mask_num_tokens = attention_mask.shape[-1]
582
+ attention_mask = attention_mask[:, attention_mask_num_tokens - kv_seq_len :]
583
+
584
+ indices_k, cu_seqlens_k, max_seqlen_in_batch_k = _get_unpad_data(attention_mask)
585
+
586
+ key_layer = index_first_axis(key_layer.reshape(batch_size * kv_seq_len, num_heads, head_dim), indices_k)
587
+ value_layer = index_first_axis(value_layer.reshape(batch_size * kv_seq_len, num_heads, head_dim), indices_k)
588
+
589
+ if query_length == kv_seq_len:
590
+ query_layer = index_first_axis(
591
+ query_layer.reshape(batch_size * kv_seq_len, num_heads, head_dim), indices_k
592
+ )
593
+ cu_seqlens_q = cu_seqlens_k
594
+ max_seqlen_in_batch_q = max_seqlen_in_batch_k
595
+ indices_q = indices_k
596
+ elif query_length == 1:
597
+ max_seqlen_in_batch_q = 1
598
+ cu_seqlens_q = torch.arange(
599
+ batch_size + 1, dtype=torch.int32, device=query_layer.device
600
+ ) # There is a memcpy here, that is very bad.
601
+ indices_q = cu_seqlens_q[:-1]
602
+ query_layer = query_layer.squeeze(1)
603
+ else:
604
+ # The -q_len: slice assumes left padding.
605
+ attention_mask = attention_mask[:, -query_length:]
606
+ query_layer, indices_q, cu_seqlens_q, max_seqlen_in_batch_q = unpad_input(query_layer, attention_mask)
607
+
608
+ return (
609
+ query_layer,
610
+ key_layer,
611
+ value_layer,
612
+ indices_q,
613
+ (cu_seqlens_q, cu_seqlens_k),
614
+ (max_seqlen_in_batch_q, max_seqlen_in_batch_k),
615
+ )
616
+
617
+
618
+ # Copied from transformers.models.llama.modeling_llama.LlamaSdpaAttention with Llama->Mistral
619
+ class MistralSdpaAttention(MistralAttention):
620
+ """
621
+ Mistral attention module using torch.nn.functional.scaled_dot_product_attention. This module inherits from
622
+ `MistralAttention` as the weights of the module stays untouched. The only changes are on the forward pass to adapt to
623
+ SDPA API.
624
+ """
625
+
626
+ # Adapted from MistralAttention.forward
627
+ def forward(
628
+ self,
629
+ hidden_states: torch.Tensor,
630
+ attention_mask: Optional[torch.Tensor] = None,
631
+ position_ids: Optional[torch.LongTensor] = None,
632
+ past_key_value: Optional[Cache] = None,
633
+ output_attentions: bool = False,
634
+ use_cache: bool = False,
635
+ is_causal: bool = True,
636
+ ) -> Tuple[torch.Tensor, Optional[torch.Tensor], Optional[Tuple[torch.Tensor]]]:
637
+ if output_attentions:
638
+ # TODO: Improve this warning with e.g. `model.config.attn_implementation = "manual"` once this is implemented.
639
+ logger.warning_once(
640
+ "MistralModel is using MistralSdpaAttention, but `torch.nn.functional.scaled_dot_product_attention` does not support `output_attentions=True`. Falling back to the manual attention implementation, "
641
+ 'but specifying the manual implementation will be required from Transformers version v5.0.0 onwards. This warning can be removed using the argument `attn_implementation="eager"` when loading the model.'
642
+ )
643
+ return super().forward(
644
+ hidden_states=hidden_states,
645
+ attention_mask=attention_mask,
646
+ position_ids=position_ids,
647
+ past_key_value=past_key_value,
648
+ output_attentions=output_attentions,
649
+ use_cache=use_cache,
650
+ is_causal=is_causal,
651
+ )
652
+
653
+ bsz, q_len, _ = hidden_states.size()
654
+
655
+ query_states = self.q_proj(hidden_states)
656
+ key_states = self.k_proj(hidden_states)
657
+ value_states = self.v_proj(hidden_states)
658
+
659
+ query_states = query_states.view(bsz, q_len, self.num_heads, self.head_dim).transpose(1, 2)
660
+ key_states = key_states.view(bsz, q_len, self.num_key_value_heads, self.head_dim).transpose(1, 2)
661
+ value_states = value_states.view(bsz, q_len, self.num_key_value_heads, self.head_dim).transpose(1, 2)
662
+
663
+ kv_seq_len = key_states.shape[-2]
664
+ if past_key_value is not None:
665
+ kv_seq_len += past_key_value.get_usable_length(kv_seq_len, self.layer_idx)
666
+ cos, sin = self.rotary_emb(value_states, seq_len=kv_seq_len)
667
+
668
+ query_states, key_states = apply_rotary_pos_emb(query_states, key_states, cos, sin, position_ids)
669
+
670
+ if past_key_value is not None:
671
+ cache_kwargs = {"sin": sin, "cos": cos} # Specific to RoPE models
672
+ key_states, value_states = past_key_value.update(key_states, value_states, self.layer_idx, cache_kwargs)
673
+
674
+ key_states = repeat_kv(key_states, self.num_key_value_groups)
675
+ value_states = repeat_kv(value_states, self.num_key_value_groups)
676
+
677
+ if attention_mask is not None:
678
+ if attention_mask.size() != (bsz, 1, q_len, kv_seq_len):
679
+ raise ValueError(
680
+ f"Attention mask should be of size {(bsz, 1, q_len, kv_seq_len)}, but is {attention_mask.size()}"
681
+ )
682
+
683
+ # SDPA with memory-efficient backend is currently (torch==2.1.2) bugged with non-contiguous inputs with custom attn_mask,
684
+ # Reference: https://github.com/pytorch/pytorch/issues/112577.
685
+ if query_states.device.type == "cuda" and attention_mask is not None:
686
+ query_states = query_states.contiguous()
687
+ key_states = key_states.contiguous()
688
+ value_states = value_states.contiguous()
689
+
690
+ attn_output = torch.nn.functional.scaled_dot_product_attention(
691
+ query_states,
692
+ key_states,
693
+ value_states,
694
+ attn_mask=attention_mask,
695
+ dropout_p=self.attention_dropout if self.training else 0.0,
696
+ # The q_len > 1 is necessary to match with AttentionMaskConverter.to_causal_4d that does not create a causal mask in case q_len == 1.
697
+ is_causal=is_causal and attention_mask is None and q_len > 1,
698
+ )
699
+
700
+ attn_output = attn_output.transpose(1, 2).contiguous()
701
+ attn_output = attn_output.reshape(bsz, q_len, self.hidden_size)
702
+
703
+ attn_output = self.o_proj(attn_output)
704
+
705
+ return attn_output, None, past_key_value
706
+
707
+
708
+ MISTRAL_ATTENTION_CLASSES = {
709
+ "eager": MistralAttention,
710
+ "flash_attention_2": MistralFlashAttention2,
711
+ "sdpa": MistralSdpaAttention,
712
+ }
713
+
714
+
715
+ class MistralDecoderLayer(nn.Module):
716
+ def __init__(self, config: MistralConfig, layer_idx: int):
717
+ super().__init__()
718
+ self.hidden_size = config.hidden_size
719
+
720
+ self.self_attn = MISTRAL_ATTENTION_CLASSES[config._attn_implementation](config, layer_idx)
721
+
722
+ self.mlp = MistralMLP(config)
723
+ self.input_layernorm = MistralRMSNorm(config.hidden_size, eps=config.rms_norm_eps)
724
+ self.post_attention_layernorm = MistralRMSNorm(config.hidden_size, eps=config.rms_norm_eps)
725
+
726
+ def forward(
727
+ self,
728
+ hidden_states: torch.Tensor,
729
+ attention_mask: Optional[torch.Tensor] = None,
730
+ position_ids: Optional[torch.LongTensor] = None,
731
+ past_key_value: Optional[Tuple[torch.Tensor]] = None,
732
+ output_attentions: Optional[bool] = False,
733
+ use_cache: Optional[bool] = False,
734
+ is_causal: Optional[bool] = True,
735
+ **kwargs,
736
+ ) -> Tuple[torch.FloatTensor, Optional[Tuple[torch.FloatTensor, torch.FloatTensor]]]:
737
+ if "padding_mask" in kwargs:
738
+ warnings.warn(
739
+ "Passing `padding_mask` is deprecated and will be removed in v4.37. Please make sure use `attention_mask` instead.`"
740
+ )
741
+ """
742
+ Args:
743
+ hidden_states (`torch.FloatTensor`): input to the layer of shape `(batch, seq_len, embed_dim)`
744
+ attention_mask (`torch.FloatTensor`, *optional*): attention mask of size
745
+ `(batch, sequence_length)` where padding elements are indicated by 0.
746
+ output_attentions (`bool`, *optional*):
747
+ Whether or not to return the attentions tensors of all attention layers. See `attentions` under
748
+ returned tensors for more detail.
749
+ use_cache (`bool`, *optional*):
750
+ If set to `True`, `past_key_values` key value states are returned and can be used to speed up decoding
751
+ (see `past_key_values`).
752
+ past_key_value (`Tuple(torch.FloatTensor)`, *optional*): cached past key and value projection states
753
+ """
754
+
755
+ residual = hidden_states
756
+
757
+ hidden_states = self.input_layernorm(hidden_states)
758
+
759
+ # Self Attention
760
+ hidden_states, self_attn_weights, present_key_value = self.self_attn(
761
+ hidden_states=hidden_states,
762
+ attention_mask=attention_mask,
763
+ position_ids=position_ids,
764
+ past_key_value=past_key_value,
765
+ output_attentions=output_attentions,
766
+ use_cache=use_cache,
767
+ is_causal=is_causal,
768
+ )
769
+ hidden_states = residual + hidden_states
770
+
771
+ # Fully Connected
772
+ residual = hidden_states
773
+ hidden_states = self.post_attention_layernorm(hidden_states)
774
+ hidden_states = self.mlp(hidden_states)
775
+ hidden_states = residual + hidden_states
776
+
777
+ outputs = (hidden_states,)
778
+
779
+ if output_attentions:
780
+ outputs += (self_attn_weights,)
781
+
782
+ if use_cache:
783
+ outputs += (present_key_value,)
784
+
785
+ return outputs
786
+
787
+
788
+ MISTRAL_START_DOCSTRING = r"""
789
+ This model inherits from [`PreTrainedModel`]. Check the superclass documentation for the generic methods the
790
+ library implements for all its model (such as downloading or saving, resizing the input embeddings, pruning heads
791
+ etc.)
792
+
793
+ This model is also a PyTorch [torch.nn.Module](https://pytorch.org/docs/stable/nn.html#torch.nn.Module) subclass.
794
+ Use it as a regular PyTorch Module and refer to the PyTorch documentation for all matter related to general usage
795
+ and behavior.
796
+
797
+ Parameters:
798
+ config ([`MistralConfig`]):
799
+ Model configuration class with all the parameters of the model. Initializing with a config file does not
800
+ load the weights associated with the model, only the configuration. Check out the
801
+ [`~PreTrainedModel.from_pretrained`] method to load the model weights.
802
+ """
803
+
804
+
805
+ @add_start_docstrings(
806
+ "The bare Mistral Model outputting raw hidden-states without any specific head on top.",
807
+ MISTRAL_START_DOCSTRING,
808
+ )
809
+ class MistralPreTrainedModel(PreTrainedModel):
810
+ config_class = MistralConfig
811
+ base_model_prefix = "model"
812
+ supports_gradient_checkpointing = True
813
+ _no_split_modules = ["MistralDecoderLayer"]
814
+ _skip_keys_device_placement = "past_key_values"
815
+ _supports_flash_attn_2 = True
816
+ _supports_sdpa = True
817
+ _supports_cache_class = True
818
+
819
+ def _init_weights(self, module):
820
+ std = self.config.initializer_range
821
+ if isinstance(module, nn.Linear):
822
+ module.weight.data.normal_(mean=0.0, std=std)
823
+ if module.bias is not None:
824
+ module.bias.data.zero_()
825
+ elif isinstance(module, nn.Embedding):
826
+ module.weight.data.normal_(mean=0.0, std=std)
827
+ if module.padding_idx is not None:
828
+ module.weight.data[module.padding_idx].zero_()
829
+
830
+
831
+ MISTRAL_INPUTS_DOCSTRING = r"""
832
+ Args:
833
+ input_ids (`torch.LongTensor` of shape `(batch_size, sequence_length)`):
834
+ Indices of input sequence tokens in the vocabulary. Padding will be ignored by default should you provide
835
+ it.
836
+
837
+ Indices can be obtained using [`AutoTokenizer`]. See [`PreTrainedTokenizer.encode`] and
838
+ [`PreTrainedTokenizer.__call__`] for details.
839
+
840
+ [What are input IDs?](../glossary#input-ids)
841
+ attention_mask (`torch.Tensor` of shape `(batch_size, sequence_length)`, *optional*):
842
+ Mask to avoid performing attention on padding token indices. Mask values selected in `[0, 1]`:
843
+
844
+ - 1 for tokens that are **not masked**,
845
+ - 0 for tokens that are **masked**.
846
+
847
+ [What are attention masks?](../glossary#attention-mask)
848
+
849
+ Indices can be obtained using [`AutoTokenizer`]. See [`PreTrainedTokenizer.encode`] and
850
+ [`PreTrainedTokenizer.__call__`] for details.
851
+
852
+ If `past_key_values` is used, optionally only the last `decoder_input_ids` have to be input (see
853
+ `past_key_values`).
854
+
855
+ If you want to change padding behavior, you should read [`modeling_opt._prepare_decoder_attention_mask`]
856
+ and modify to your needs. See diagram 1 in [the paper](https://arxiv.org/abs/1910.13461) for more
857
+ information on the default strategy.
858
+
859
+ - 1 indicates the head is **not masked**,
860
+ - 0 indicates the head is **masked**.
861
+ position_ids (`torch.LongTensor` of shape `(batch_size, sequence_length)`, *optional*):
862
+ Indices of positions of each input sequence tokens in the position embeddings. Selected in the range `[0,
863
+ config.n_positions - 1]`.
864
+
865
+ [What are position IDs?](../glossary#position-ids)
866
+ past_key_values (`Cache` or `tuple(tuple(torch.FloatTensor))`, *optional*):
867
+ Pre-computed hidden-states (key and values in the self-attention blocks and in the cross-attention
868
+ blocks) that can be used to speed up sequential decoding. This typically consists in the `past_key_values`
869
+ returned by the model at a previous stage of decoding, when `use_cache=True` or `config.use_cache=True`.
870
+
871
+ Two formats are allowed:
872
+ - a [`~cache_utils.Cache`] instance;
873
+ - Tuple of `tuple(torch.FloatTensor)` of length `config.n_layers`, with each tuple having 2 tensors of
874
+ shape `(batch_size, num_heads, sequence_length, embed_size_per_head)`). This is also known as the legacy
875
+ cache format.
876
+
877
+ The model will output the same cache format that is fed as input. If no `past_key_values` are passed, the
878
+ legacy cache format will be returned.
879
+
880
+ If `past_key_values` are used, the user can optionally input only the last `input_ids` (those that don't
881
+ have their past key value states given to this model) of shape `(batch_size, 1)` instead of all `input_ids`
882
+ of shape `(batch_size, sequence_length)`.
883
+ inputs_embeds (`torch.FloatTensor` of shape `(batch_size, sequence_length, hidden_size)`, *optional*):
884
+ Optionally, instead of passing `input_ids` you can choose to directly pass an embedded representation. This
885
+ is useful if you want more control over how to convert `input_ids` indices into associated vectors than the
886
+ model's internal embedding lookup matrix.
887
+ use_cache (`bool`, *optional*):
888
+ If set to `True`, `past_key_values` key value states are returned and can be used to speed up decoding (see
889
+ `past_key_values`).
890
+ output_attentions (`bool`, *optional*):
891
+ Whether or not to return the attentions tensors of all attention layers. See `attentions` under returned
892
+ tensors for more detail.
893
+ output_hidden_states (`bool`, *optional*):
894
+ Whether or not to return the hidden states of all layers. See `hidden_states` under returned tensors for
895
+ more detail.
896
+ return_dict (`bool`, *optional*):
897
+ Whether or not to return a [`~utils.ModelOutput`] instead of a plain tuple.
898
+ """
899
+
900
+
901
+ @add_start_docstrings(
902
+ "The bare Mistral Model outputting raw hidden-states without any specific head on top.",
903
+ MISTRAL_START_DOCSTRING,
904
+ )
905
+ class MistralModel(MistralPreTrainedModel):
906
+ """
907
+ Transformer decoder consisting of *config.num_hidden_layers* layers. Each layer is a [`MistralDecoderLayer`]
908
+
909
+ Args:
910
+ config: MistralConfig
911
+ """
912
+
913
+ def __init__(self, config: MistralConfig):
914
+ super().__init__(config)
915
+ self.padding_idx = config.pad_token_id
916
+ self.vocab_size = config.vocab_size
917
+
918
+ self.embed_tokens = nn.Embedding(config.vocab_size, config.hidden_size, self.padding_idx)
919
+ self.layers = nn.ModuleList(
920
+ [MistralDecoderLayer(config, layer_idx) for layer_idx in range(config.num_hidden_layers)]
921
+ )
922
+ self._attn_implementation = config._attn_implementation
923
+ self.norm = MistralRMSNorm(config.hidden_size, eps=config.rms_norm_eps)
924
+
925
+ self.gradient_checkpointing = False
926
+ # Initialize weights and apply final processing
927
+ self.post_init()
928
+
929
+ def get_input_embeddings(self):
930
+ return self.embed_tokens
931
+
932
+ def set_input_embeddings(self, value):
933
+ self.embed_tokens = value
934
+
935
+ @add_start_docstrings_to_model_forward(MISTRAL_INPUTS_DOCSTRING)
936
+ def forward(
937
+ self,
938
+ input_ids: torch.LongTensor = None,
939
+ attention_mask: Optional[torch.Tensor] = None,
940
+ position_ids: Optional[torch.LongTensor] = None,
941
+ past_key_values: Optional[List[torch.FloatTensor]] = None,
942
+ inputs_embeds: Optional[torch.FloatTensor] = None,
943
+ use_cache: Optional[bool] = None,
944
+ output_attentions: Optional[bool] = None,
945
+ output_hidden_states: Optional[bool] = None,
946
+ return_dict: Optional[bool] = None,
947
+ labels: Optional[torch.LongTensor] = None,
948
+ instruction_lens=None,
949
+ is_causal: Optional[bool] = True,
950
+ ) -> Union[Tuple, BaseModelOutputWithPast]:
951
+ output_attentions = output_attentions if output_attentions is not None else self.config.output_attentions
952
+ output_hidden_states = (
953
+ output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states
954
+ )
955
+ use_cache = use_cache if use_cache is not None else self.config.use_cache
956
+
957
+ return_dict = return_dict if return_dict is not None else self.config.use_return_dict
958
+
959
+ # retrieve input_ids and inputs_embeds
960
+ if input_ids is not None and inputs_embeds is not None:
961
+ raise ValueError("You cannot specify both decoder_input_ids and decoder_inputs_embeds at the same time")
962
+ elif input_ids is not None:
963
+ batch_size, seq_length = input_ids.shape
964
+ elif inputs_embeds is not None:
965
+ batch_size, seq_length, _ = inputs_embeds.shape
966
+ else:
967
+ raise ValueError("You have to specify either decoder_input_ids or decoder_inputs_embeds")
968
+
969
+ if self.gradient_checkpointing and self.training:
970
+ if use_cache:
971
+ logger.warning_once(
972
+ "`use_cache=True` is incompatible with gradient checkpointing. Setting `use_cache=False`..."
973
+ )
974
+ use_cache = False
975
+
976
+ past_key_values_length = 0
977
+
978
+ if use_cache:
979
+ use_legacy_cache = not isinstance(past_key_values, Cache)
980
+ if use_legacy_cache:
981
+ past_key_values = DynamicCache.from_legacy_cache(past_key_values)
982
+ past_key_values_length = past_key_values.get_usable_length(seq_length)
983
+
984
+ if position_ids is None:
985
+ device = input_ids.device if input_ids is not None else inputs_embeds.device
986
+ position_ids = torch.arange(
987
+ past_key_values_length, seq_length + past_key_values_length, dtype=torch.long, device=device
988
+ )
989
+ position_ids = position_ids.unsqueeze(0).view(-1, seq_length)
990
+ else:
991
+ position_ids = position_ids.view(-1, seq_length).long()
992
+
993
+ if inputs_embeds is None:
994
+ inputs_embeds = self.embed_tokens(input_ids)
995
+
996
+ if attention_mask is not None and self._attn_implementation == "flash_attention_2" and use_cache:
997
+ is_padding_right = attention_mask[:, -1].sum().item() != batch_size
998
+ if is_padding_right:
999
+ raise ValueError(
1000
+ "You are attempting to perform batched generation with padding_side='right'"
1001
+ " this may lead to unexpected behaviour for Flash Attention version of Mistral. Make sure to "
1002
+ " call `tokenizer.padding_side = 'left'` before tokenizing the input. "
1003
+ )
1004
+
1005
+ if self._attn_implementation == "flash_attention_2":
1006
+ attention_mask = attention_mask if (attention_mask is not None and 0 in attention_mask) else None
1007
+ elif self._attn_implementation == "sdpa" and not output_attentions:
1008
+ # output_attentions=True can not be supported when using SDPA, and we fall back on
1009
+ # the manual implementation that requires a 4D causal mask in all cases.
1010
+ if is_causal:
1011
+ attention_mask = _prepare_4d_causal_attention_mask_for_sdpa(
1012
+ attention_mask,
1013
+ (batch_size, seq_length),
1014
+ inputs_embeds,
1015
+ past_key_values_length,
1016
+ )
1017
+ else:
1018
+ attention_mask = _prepare_4d_attention_mask_for_sdpa(
1019
+ attention_mask, inputs_embeds.dtype
1020
+ )
1021
+ else:
1022
+ # 4d mask is passed through the layers
1023
+ if is_causal:
1024
+ # Causal mask with -3.3895e+38 where no attention should be
1025
+ attention_mask = _prepare_4d_causal_attention_mask(
1026
+ attention_mask,
1027
+ (batch_size, seq_length),
1028
+ inputs_embeds,
1029
+ past_key_values_length,
1030
+ sliding_window=self.config.sliding_window,
1031
+ )
1032
+ else:
1033
+ # Shape: batch_size, 1, query_length, key_value_length
1034
+ attention_mask = _prepare_4d_attention_mask(
1035
+ attention_mask, inputs_embeds.dtype
1036
+ )
1037
+
1038
+ hidden_states = inputs_embeds
1039
+
1040
+ # decoder layers
1041
+ all_hidden_states = () if output_hidden_states else None
1042
+ all_self_attns = () if output_attentions else None
1043
+ next_decoder_cache = None
1044
+
1045
+ for decoder_layer in self.layers:
1046
+ if output_hidden_states:
1047
+ all_hidden_states += (hidden_states,)
1048
+
1049
+ if self.gradient_checkpointing and self.training:
1050
+ layer_outputs = self._gradient_checkpointing_func(
1051
+ decoder_layer.__call__,
1052
+ hidden_states,
1053
+ attention_mask,
1054
+ position_ids,
1055
+ past_key_values,
1056
+ output_attentions,
1057
+ use_cache,
1058
+ is_causal,
1059
+ )
1060
+ else:
1061
+ layer_outputs = decoder_layer(
1062
+ hidden_states,
1063
+ attention_mask=attention_mask,
1064
+ position_ids=position_ids,
1065
+ past_key_value=past_key_values,
1066
+ output_attentions=output_attentions,
1067
+ use_cache=use_cache,
1068
+ is_causal=is_causal,
1069
+ )
1070
+
1071
+ hidden_states = layer_outputs[0]
1072
+
1073
+ if use_cache:
1074
+ next_decoder_cache = layer_outputs[2 if output_attentions else 1]
1075
+
1076
+ if output_attentions:
1077
+ all_self_attns += (layer_outputs[1],)
1078
+
1079
+ hidden_states = self.norm(hidden_states)
1080
+
1081
+ # add hidden states from the last decoder layer
1082
+ if output_hidden_states:
1083
+ all_hidden_states += (hidden_states,)
1084
+
1085
+ next_cache = None
1086
+ if use_cache:
1087
+ next_cache = next_decoder_cache.to_legacy_cache() if use_legacy_cache else next_decoder_cache
1088
+
1089
+ if not return_dict:
1090
+ return tuple(v for v in [hidden_states, next_cache, all_hidden_states, all_self_attns] if v is not None)
1091
+ return BaseModelOutputWithPast(
1092
+ last_hidden_state=hidden_states,
1093
+ past_key_values=next_cache,
1094
+ hidden_states=all_hidden_states,
1095
+ attentions=all_self_attns,
1096
+ )
1097
+
1098
+
1099
+ class MistralForCausalLM(MistralPreTrainedModel):
1100
+ _tied_weights_keys = ["lm_head.weight"]
1101
+
1102
+ def __init__(self, config):
1103
+ super().__init__(config)
1104
+ self.model = MistralModel(config)
1105
+ self.vocab_size = config.vocab_size
1106
+ self.lm_head = nn.Linear(config.hidden_size, config.vocab_size, bias=False)
1107
+
1108
+ # Initialize weights and apply final processing
1109
+ self.post_init()
1110
+
1111
+ def get_input_embeddings(self):
1112
+ return self.model.embed_tokens
1113
+
1114
+ def set_input_embeddings(self, value):
1115
+ self.model.embed_tokens = value
1116
+
1117
+ def get_output_embeddings(self):
1118
+ return self.lm_head
1119
+
1120
+ def set_output_embeddings(self, new_embeddings):
1121
+ self.lm_head = new_embeddings
1122
+
1123
+ def set_decoder(self, decoder):
1124
+ self.model = decoder
1125
+
1126
+ def get_decoder(self):
1127
+ return self.model
1128
+
1129
+ @add_start_docstrings_to_model_forward(MISTRAL_INPUTS_DOCSTRING)
1130
+ @replace_return_docstrings(output_type=CausalLMOutputWithPast, config_class=_CONFIG_FOR_DOC)
1131
+ def forward(
1132
+ self,
1133
+ input_ids: torch.LongTensor = None,
1134
+ attention_mask: Optional[torch.Tensor] = None,
1135
+ position_ids: Optional[torch.LongTensor] = None,
1136
+ past_key_values: Optional[List[torch.FloatTensor]] = None,
1137
+ inputs_embeds: Optional[torch.FloatTensor] = None,
1138
+ labels: Optional[torch.LongTensor] = None,
1139
+ use_cache: Optional[bool] = None,
1140
+ output_attentions: Optional[bool] = None,
1141
+ output_hidden_states: Optional[bool] = None,
1142
+ return_dict: Optional[bool] = None,
1143
+ ) -> Union[Tuple, CausalLMOutputWithPast]:
1144
+ r"""
1145
+ Args:
1146
+ labels (`torch.LongTensor` of shape `(batch_size, sequence_length)`, *optional*):
1147
+ Labels for computing the masked language modeling loss. Indices should either be in `[0, ...,
1148
+ config.vocab_size]` or -100 (see `input_ids` docstring). Tokens with indices set to `-100` are ignored
1149
+ (masked), the loss is only computed for the tokens with labels in `[0, ..., config.vocab_size]`.
1150
+
1151
+ Returns:
1152
+
1153
+ Example:
1154
+
1155
+ ```python
1156
+ >>> from transformers import AutoTokenizer, MistralForCausalLM
1157
+
1158
+ >>> model = MistralForCausalLM.from_pretrained(PATH_TO_CONVERTED_WEIGHTS)
1159
+ >>> tokenizer = AutoTokenizer.from_pretrained(PATH_TO_CONVERTED_TOKENIZER)
1160
+
1161
+ >>> prompt = "Hey, are you conscious? Can you talk to me?"
1162
+ >>> inputs = tokenizer(prompt, return_tensors="pt")
1163
+
1164
+ >>> # Generate
1165
+ >>> generate_ids = model.generate(inputs.input_ids, max_length=30)
1166
+ >>> tokenizer.batch_decode(generate_ids, skip_special_tokens=True, clean_up_tokenization_spaces=False)[0]
1167
+ "Hey, are you conscious? Can you talk to me?\nI'm not conscious, but I can talk to you."
1168
+ ```"""
1169
+
1170
+ output_attentions = output_attentions if output_attentions is not None else self.config.output_attentions
1171
+ output_hidden_states = (
1172
+ output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states
1173
+ )
1174
+ return_dict = return_dict if return_dict is not None else self.config.use_return_dict
1175
+
1176
+ # decoder outputs consists of (dec_features, layer_state, dec_hidden, dec_attn)
1177
+ outputs = self.model(
1178
+ input_ids=input_ids,
1179
+ attention_mask=attention_mask,
1180
+ position_ids=position_ids,
1181
+ past_key_values=past_key_values,
1182
+ inputs_embeds=inputs_embeds,
1183
+ use_cache=use_cache,
1184
+ output_attentions=output_attentions,
1185
+ output_hidden_states=output_hidden_states,
1186
+ return_dict=return_dict,
1187
+ labels=labels,
1188
+ )
1189
+
1190
+ hidden_states = outputs[0]
1191
+ logits = self.lm_head(hidden_states)
1192
+ logits = logits.float()
1193
+
1194
+ loss = None
1195
+ if (labels is not None) and (input_ids.shape[1] > 1):
1196
+ # Shift so that tokens < n predict n
1197
+ shift_logits = logits[..., :-1, :].contiguous()
1198
+ shift_labels = labels[..., 1:].contiguous()
1199
+ # Flatten the tokens
1200
+ loss_fct = CrossEntropyLoss()
1201
+ # For deterministic loss w/ gradacc:
1202
+ #loss_fct = CrossEntropyLoss(reduction="none")
1203
+ loss_fct = CrossEntropyLoss(reduction="sum")
1204
+ shift_logits = shift_logits.view(-1, self.config.vocab_size)
1205
+ shift_labels = shift_labels.view(-1)
1206
+ # Enable model parallelism
1207
+ shift_labels = shift_labels.to(shift_logits.device)
1208
+ loss = loss_fct(shift_logits, shift_labels)
1209
+ # For deterministic loss w/ gradacc:
1210
+ #loss = loss_fct(shift_logits, shift_labels).sum() / input_ids.shape[0]
1211
+ # Problem with below is
1212
+ # e.g. if we have 30 tokens, now we split them in two batches with 20 & 10
1213
+ # Then we get the losses 60 and 40 and average them
1214
+ # We get (3 + 4)/2 = 3.5
1215
+ # Meanwhile if we did it in one we would be doing 100 / 30 = 3.333
1216
+ loss = loss_fct(shift_logits, shift_labels) / attention_mask.sum()
1217
+
1218
+ if not return_dict:
1219
+ output = (logits,) + outputs[1:]
1220
+ return (loss,) + output if loss is not None else output
1221
+
1222
+ return CausalLMOutputWithPast(
1223
+ loss=loss,
1224
+ logits=logits,
1225
+ past_key_values=outputs.past_key_values,
1226
+ hidden_states=outputs.hidden_states,
1227
+ attentions=outputs.attentions,
1228
+ )
1229
+
1230
+ def prepare_inputs_for_generation(
1231
+ self, input_ids, past_key_values=None, attention_mask=None, inputs_embeds=None, **kwargs
1232
+ ):
1233
+ # Omit tokens covered by past_key_values
1234
+ if past_key_values is not None:
1235
+ if isinstance(past_key_values, Cache):
1236
+ cache_length = past_key_values.get_seq_length()
1237
+ past_length = past_key_values.seen_tokens
1238
+ max_cache_length = past_key_values.get_max_length()
1239
+ else:
1240
+ cache_length = past_length = past_key_values[0][0].shape[2]
1241
+ max_cache_length = None
1242
+
1243
+ # Keep only the unprocessed tokens:
1244
+ # 1 - If the length of the attention_mask exceeds the length of input_ids, then we are in a setting where
1245
+ # some of the inputs are exclusivelly passed as part of the cache (e.g. when passing input_embeds as
1246
+ # input)
1247
+ if attention_mask is not None and attention_mask.shape[1] > input_ids.shape[1]:
1248
+ input_ids = input_ids[:, -(attention_mask.shape[1] - past_length) :]
1249
+ # 2 - If the past_length is smaller than input_ids', then input_ids holds all input tokens. We can discard
1250
+ # input_ids based on the past_length.
1251
+ elif past_length < input_ids.shape[1]:
1252
+ input_ids = input_ids[:, past_length:]
1253
+ # 3 - Otherwise (past_length >= input_ids.shape[1]), let's assume input_ids only has unprocessed tokens.
1254
+
1255
+ # If we are about to go beyond the maximum cache length, we need to crop the input attention mask.
1256
+ if (
1257
+ max_cache_length is not None
1258
+ and attention_mask is not None
1259
+ and cache_length + input_ids.shape[1] > max_cache_length
1260
+ ):
1261
+ attention_mask = attention_mask[:, -max_cache_length:]
1262
+
1263
+ position_ids = kwargs.get("position_ids", None)
1264
+ if attention_mask is not None and position_ids is None:
1265
+ # create position_ids on the fly for batch generation
1266
+ position_ids = attention_mask.long().cumsum(-1) - 1
1267
+ position_ids.masked_fill_(attention_mask == 0, 1)
1268
+ if past_key_values:
1269
+ position_ids = position_ids[:, -input_ids.shape[1] :]
1270
+
1271
+ # if `inputs_embeds` are passed, we only want to use them in the 1st generation step
1272
+ if inputs_embeds is not None and past_key_values is None:
1273
+ model_inputs = {"inputs_embeds": inputs_embeds}
1274
+ else:
1275
+ model_inputs = {"input_ids": input_ids}
1276
+
1277
+ model_inputs.update(
1278
+ {
1279
+ "position_ids": position_ids,
1280
+ "past_key_values": past_key_values,
1281
+ "use_cache": kwargs.get("use_cache"),
1282
+ "attention_mask": attention_mask,
1283
+ "labels": kwargs.get("labels"),
1284
+ }
1285
+ )
1286
+ return model_inputs
1287
+
1288
+ @staticmethod
1289
+ def _reorder_cache(past_key_values, beam_idx):
1290
+ reordered_past = ()
1291
+ for layer_past in past_key_values:
1292
+ reordered_past += (
1293
+ tuple(past_state.index_select(0, beam_idx.to(past_state.device)) for past_state in layer_past),
1294
+ )
1295
+ return reordered_past
1296
+
1297
+
1298
+ @add_start_docstrings(
1299
+ """
1300
+ The Mistral Model transformer with a sequence classification head on top (linear layer).
1301
+
1302
+ [`MistralForSequenceClassification`] uses the last token in order to do the classification, as other causal models
1303
+ (e.g. GPT-2) do.
1304
+
1305
+ Since it does classification on the last token, it requires to know the position of the last token. If a
1306
+ `pad_token_id` is defined in the configuration, it finds the last token that is not a padding token in each row. If
1307
+ no `pad_token_id` is defined, it simply takes the last value in each row of the batch. Since it cannot guess the
1308
+ padding tokens when `inputs_embeds` are passed instead of `input_ids`, it does the same (take the last value in
1309
+ each row of the batch).
1310
+ """,
1311
+ MISTRAL_START_DOCSTRING,
1312
+ )
1313
+ # Copied from transformers.models.llama.modeling_llama.LlamaForSequenceClassification with Llama->Mistral, LLAMA->MISTRAL
1314
+ class MistralForSequenceClassification(MistralPreTrainedModel):
1315
+ def __init__(self, config):
1316
+ super().__init__(config)
1317
+ self.num_labels = config.num_labels
1318
+ self.model = MistralModel(config)
1319
+ self.score = nn.Linear(config.hidden_size, self.num_labels, bias=False)
1320
+
1321
+ # Initialize weights and apply final processing
1322
+ self.post_init()
1323
+
1324
+ def get_input_embeddings(self):
1325
+ return self.model.embed_tokens
1326
+
1327
+ def set_input_embeddings(self, value):
1328
+ self.model.embed_tokens = value
1329
+
1330
+ @add_start_docstrings_to_model_forward(MISTRAL_INPUTS_DOCSTRING)
1331
+ def forward(
1332
+ self,
1333
+ input_ids: torch.LongTensor = None,
1334
+ attention_mask: Optional[torch.Tensor] = None,
1335
+ position_ids: Optional[torch.LongTensor] = None,
1336
+ past_key_values: Optional[List[torch.FloatTensor]] = None,
1337
+ inputs_embeds: Optional[torch.FloatTensor] = None,
1338
+ labels: Optional[torch.LongTensor] = None,
1339
+ use_cache: Optional[bool] = None,
1340
+ output_attentions: Optional[bool] = None,
1341
+ output_hidden_states: Optional[bool] = None,
1342
+ return_dict: Optional[bool] = None,
1343
+ ) -> Union[Tuple, SequenceClassifierOutputWithPast]:
1344
+ r"""
1345
+ labels (`torch.LongTensor` of shape `(batch_size,)`, *optional*):
1346
+ Labels for computing the sequence classification/regression loss. Indices should be in `[0, ...,
1347
+ config.num_labels - 1]`. If `config.num_labels == 1` a regression loss is computed (Mean-Square loss), If
1348
+ `config.num_labels > 1` a classification loss is computed (Cross-Entropy).
1349
+ """
1350
+ return_dict = return_dict if return_dict is not None else self.config.use_return_dict
1351
+
1352
+ transformer_outputs = self.model(
1353
+ input_ids,
1354
+ attention_mask=attention_mask,
1355
+ position_ids=position_ids,
1356
+ past_key_values=past_key_values,
1357
+ inputs_embeds=inputs_embeds,
1358
+ use_cache=use_cache,
1359
+ output_attentions=output_attentions,
1360
+ output_hidden_states=output_hidden_states,
1361
+ return_dict=return_dict,
1362
+ )
1363
+ hidden_states = transformer_outputs[0]
1364
+ logits = self.score(hidden_states)
1365
+
1366
+ if input_ids is not None:
1367
+ batch_size = input_ids.shape[0]
1368
+ else:
1369
+ batch_size = inputs_embeds.shape[0]
1370
+
1371
+ if self.config.pad_token_id is None and batch_size != 1:
1372
+ raise ValueError("Cannot handle batch sizes > 1 if no padding token is defined.")
1373
+ if self.config.pad_token_id is None:
1374
+ sequence_lengths = -1
1375
+ else:
1376
+ if input_ids is not None:
1377
+ # if no pad token found, use modulo instead of reverse indexing for ONNX compatibility
1378
+ sequence_lengths = torch.eq(input_ids, self.config.pad_token_id).int().argmax(-1) - 1
1379
+ sequence_lengths = sequence_lengths % input_ids.shape[-1]
1380
+ sequence_lengths = sequence_lengths.to(logits.device)
1381
+ else:
1382
+ sequence_lengths = -1
1383
+
1384
+ pooled_logits = logits[torch.arange(batch_size, device=logits.device), sequence_lengths]
1385
+
1386
+ loss = None
1387
+ if labels is not None:
1388
+ labels = labels.to(logits.device)
1389
+ if self.config.problem_type is None:
1390
+ if self.num_labels == 1:
1391
+ self.config.problem_type = "regression"
1392
+ elif self.num_labels > 1 and (labels.dtype == torch.long or labels.dtype == torch.int):
1393
+ self.config.problem_type = "single_label_classification"
1394
+ else:
1395
+ self.config.problem_type = "multi_label_classification"
1396
+
1397
+ if self.config.problem_type == "regression":
1398
+ loss_fct = MSELoss()
1399
+ if self.num_labels == 1:
1400
+ loss = loss_fct(pooled_logits.squeeze(), labels.squeeze())
1401
+ else:
1402
+ loss = loss_fct(pooled_logits, labels)
1403
+ elif self.config.problem_type == "single_label_classification":
1404
+ loss_fct = CrossEntropyLoss()
1405
+ loss = loss_fct(pooled_logits.view(-1, self.num_labels), labels.view(-1))
1406
+ elif self.config.problem_type == "multi_label_classification":
1407
+ loss_fct = BCEWithLogitsLoss()
1408
+ loss = loss_fct(pooled_logits, labels)
1409
+ if not return_dict:
1410
+ output = (pooled_logits,) + transformer_outputs[1:]
1411
+ return ((loss,) + output) if loss is not None else output
1412
+
1413
+ return SequenceClassifierOutputWithPast(
1414
+ loss=loss,
1415
+ logits=pooled_logits,
1416
+ past_key_values=transformer_outputs.past_key_values,
1417
+ hidden_states=transformer_outputs.hidden_states,
1418
+ attentions=transformer_outputs.attentions,
1419
+ )