Feature Extraction
Transformers
Safetensors
English
bamboo
custom_code
yixinsong commited on
Commit
c4f70ae
1 Parent(s): 4739ad2

add config

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