lucifertrj commited on
Commit
22488f3
1 Parent(s): e06a404

Upload folder using huggingface_hub

Browse files
config.json ADDED
@@ -0,0 +1,37 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "_name_or_path": "/home/a100/aiplanet/gpt4_model_v2/model",
3
+ "architectures": [
4
+ "MistralForCausalLM"
5
+ ],
6
+ "attention_dropout": 0.0,
7
+ "auto_map": {
8
+ "AutoConfig": "configuration_mistral.MistralConfig",
9
+ "AutoModelForCausalLM": "modeling_mistral_yarn.MistralForCausalLM"
10
+ },
11
+ "bos_token_id": 1,
12
+ "eos_token_id": 2,
13
+ "hidden_act": "silu",
14
+ "hidden_size": 4096,
15
+ "initializer_range": 0.02,
16
+ "intermediate_size": 14336,
17
+ "max_position_embeddings": 131072,
18
+ "model_type": "mistral",
19
+ "num_attention_heads": 32,
20
+ "num_hidden_layers": 32,
21
+ "num_key_value_heads": 8,
22
+ "pad_token_id": 2,
23
+ "rms_norm_eps": 1e-05,
24
+ "rope_scaling": {
25
+ "factor": 4.0,
26
+ "finetuned": true,
27
+ "original_max_position_embeddings": 32768,
28
+ "type": "yarn"
29
+ },
30
+ "rope_theta": 1000000.0,
31
+ "sliding_window": null,
32
+ "tie_word_embeddings": false,
33
+ "torch_dtype": "bfloat16",
34
+ "transformers_version": "4.39.2",
35
+ "use_cache": true,
36
+ "vocab_size": 32000
37
+ }
configuration_mistral.py ADDED
@@ -0,0 +1,187 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
+ """ Mistral model configuration"""
16
+
17
+ from transformers.configuration_utils import PretrainedConfig
18
+ from transformers.utils import logging
19
+
20
+
21
+ logger = logging.get_logger(__name__)
22
+
23
+ MISTRAL_PRETRAINED_CONFIG_ARCHIVE_MAP = {
24
+ "mistralai/Mistral-7B-v0.1": "https://huggingface.co/mistralai/Mistral-7B-v0.1/resolve/main/config.json",
25
+ "mistralai/Mistral-7B-Instruct-v0.1": "https://huggingface.co/mistralai/Mistral-7B-Instruct-v0.1/resolve/main/config.json",
26
+ }
27
+
28
+
29
+ class MistralConfig(PretrainedConfig):
30
+ r"""
31
+ This is the configuration class to store the configuration of a [`MistralModel`]. It is used to instantiate an
32
+ Mistral model according to the specified arguments, defining the model architecture. Instantiating a configuration
33
+ with the defaults will yield a similar configuration to that of the Mistral-7B-v0.1 or Mistral-7B-Instruct-v0.1.
34
+
35
+ [mistralai/Mistral-7B-v0.1](https://huggingface.co/mistralai/Mistral-7B-v0.1)
36
+ [mistralai/Mistral-7B-Instruct-v0.1](https://huggingface.co/mistralai/Mistral-7B-Instruct-v0.1)
37
+
38
+ Configuration objects inherit from [`PretrainedConfig`] and can be used to control the model outputs. Read the
39
+ documentation from [`PretrainedConfig`] for more information.
40
+
41
+
42
+ Args:
43
+ vocab_size (`int`, *optional*, defaults to 32000):
44
+ Vocabulary size of the Mistral model. Defines the number of different tokens that can be represented by the
45
+ `inputs_ids` passed when calling [`MistralModel`]
46
+ hidden_size (`int`, *optional*, defaults to 4096):
47
+ Dimension of the hidden representations.
48
+ intermediate_size (`int`, *optional*, defaults to 14336):
49
+ Dimension of the MLP representations.
50
+ num_hidden_layers (`int`, *optional*, defaults to 32):
51
+ Number of hidden layers in the Transformer encoder.
52
+ num_attention_heads (`int`, *optional*, defaults to 32):
53
+ Number of attention heads for each attention layer in the Transformer encoder.
54
+ num_key_value_heads (`int`, *optional*, defaults to 8):
55
+ This is the number of key_value heads that should be used to implement Grouped Query Attention. If
56
+ `num_key_value_heads=num_attention_heads`, the model will use Multi Head Attention (MHA), if
57
+ `num_key_value_heads=1 the model will use Multi Query Attention (MQA) otherwise GQA is used. When
58
+ converting a multi-head checkpoint to a GQA checkpoint, each group key and value head should be constructed
59
+ by meanpooling all the original heads within that group. For more details checkout [this
60
+ paper](https://arxiv.org/pdf/2305.13245.pdf). If it is not specified, will default to `8`.
61
+ hidden_act (`str` or `function`, *optional*, defaults to `"silu"`):
62
+ The non-linear activation function (function or string) in the decoder.
63
+ max_position_embeddings (`int`, *optional*, defaults to `4096*32`):
64
+ The maximum sequence length that this model might ever be used with. Mistral's sliding window attention
65
+ allows sequence of up to 4096*32 tokens.
66
+ initializer_range (`float`, *optional*, defaults to 0.02):
67
+ The standard deviation of the truncated_normal_initializer for initializing all weight matrices.
68
+ rms_norm_eps (`float`, *optional*, defaults to 1e-06):
69
+ The epsilon used by the rms normalization layers.
70
+ use_cache (`bool`, *optional*, defaults to `True`):
71
+ Whether or not the model should return the last key/values attentions (not used by all models). Only
72
+ relevant if `config.is_decoder=True`.
73
+ pad_token_id (`int`, *optional*):
74
+ The id of the padding token.
75
+ bos_token_id (`int`, *optional*, defaults to 1):
76
+ The id of the "beginning-of-sequence" token.
77
+ eos_token_id (`int`, *optional*, defaults to 2):
78
+ The id of the "end-of-sequence" token.
79
+ tie_word_embeddings (`bool`, *optional*, defaults to `False`):
80
+ Whether the model's input and output word embeddings should be tied.
81
+ rope_scaling (`Dict`, *optional*):
82
+ Dictionary containing the scaling configuration for the RoPE embeddings. Currently supports three scaling
83
+ strategies: linear and dynamic. Their scaling factor must be an float greater than 1. The expected format
84
+ is `{"type": strategy name, "factor": scaling factor}`.
85
+ rope_theta (`float`, *optional*, defaults to 10000.0):
86
+ The base period of the RoPE embeddings.
87
+ sliding_window (`int`, *optional*, defaults to 4096):
88
+ Sliding window attention window size. If not specified, will default to `4096`.
89
+
90
+
91
+ ```python
92
+ >>> from transformers import MistralModel, MistralConfig
93
+
94
+ >>> # Initializing a Mistral 7B style configuration
95
+ >>> configuration = MistralConfig()
96
+
97
+ >>> # Initializing a model from the Mistral 7B style configuration
98
+ >>> model = MistralModel(configuration)
99
+
100
+ >>> # Accessing the model configuration
101
+ >>> configuration = model.config
102
+ ```"""
103
+
104
+ model_type = "mistral"
105
+ keys_to_ignore_at_inference = ["past_key_values"]
106
+
107
+ def __init__(
108
+ self,
109
+ vocab_size=32000,
110
+ hidden_size=4096,
111
+ intermediate_size=14336,
112
+ num_hidden_layers=32,
113
+ num_attention_heads=32,
114
+ num_key_value_heads=8,
115
+ hidden_act="silu",
116
+ max_position_embeddings=4096 * 32,
117
+ initializer_range=0.02,
118
+ rms_norm_eps=1e-6,
119
+ use_cache=True,
120
+ pad_token_id=None,
121
+ bos_token_id=1,
122
+ eos_token_id=2,
123
+ tie_word_embeddings=False,
124
+ rope_scaling={
125
+ "factor": 16.0,
126
+ "finetuned": True,
127
+ "original_max_position_embeddings": 8192,
128
+ "type": "dynamic-yarn"},
129
+ rope_theta=10000.0,
130
+ sliding_window=4096,
131
+ attention_dropout=0.0,
132
+ **kwargs,
133
+ ):
134
+ self.vocab_size = vocab_size
135
+ self.max_position_embeddings = max_position_embeddings
136
+ self.hidden_size = hidden_size
137
+ self.intermediate_size = intermediate_size
138
+ self.num_hidden_layers = num_hidden_layers
139
+ self.num_attention_heads = num_attention_heads
140
+ self.sliding_window = sliding_window
141
+
142
+ # for backward compatibility
143
+ if num_key_value_heads is None:
144
+ num_key_value_heads = num_attention_heads
145
+
146
+ self.num_key_value_heads = num_key_value_heads
147
+ self.hidden_act = hidden_act
148
+ self.initializer_range = initializer_range
149
+ self.rms_norm_eps = rms_norm_eps
150
+ self.use_cache = use_cache
151
+ self.rope_scaling = rope_scaling
152
+ self.attention_dropout = attention_dropout
153
+ self.rope_theta = rope_theta
154
+ self._rope_scaling_validation()
155
+
156
+ super().__init__(
157
+ pad_token_id=pad_token_id,
158
+ bos_token_id=bos_token_id,
159
+ eos_token_id=eos_token_id,
160
+ tie_word_embeddings=tie_word_embeddings,
161
+ **kwargs,
162
+ )
163
+
164
+ def _rope_scaling_validation(self):
165
+ """
166
+ Validate the `rope_scaling` configuration.
167
+ """
168
+ if self.rope_scaling is None:
169
+ return
170
+
171
+ if not isinstance(self.rope_scaling, dict):
172
+ raise ValueError(
173
+ "`rope_scaling` must be a dictionary, "
174
+ f"got {self.rope_scaling}"
175
+ )
176
+ rope_scaling_type = self.rope_scaling.get("type", None)
177
+ rope_scaling_factor = self.rope_scaling.get("factor", None)
178
+ if rope_scaling_type is None or rope_scaling_type not in ["linear", "dynamic", "yarn", "dynamic-yarn"]:
179
+ raise ValueError(
180
+ f"`rope_scaling`'s name field must be one of ['linear', 'dynamic', 'yarn', 'dynamic-yarn'], got {rope_scaling_type}"
181
+ )
182
+ if rope_scaling_factor is None or not isinstance(rope_scaling_factor, float) or rope_scaling_factor <= 1.0:
183
+ raise ValueError(f"`rope_scaling`'s factor field must be an float > 1, got {rope_scaling_factor}")
184
+ if rope_scaling_type == "yarn" or rope_scaling_type == "dynamic-yarn":
185
+ original_max_position_embeddings = self.rope_scaling.get("original_max_position_embeddings", None)
186
+ if original_max_position_embeddings is None or not isinstance(original_max_position_embeddings, int):
187
+ raise ValueError(f"`rope_scaling.original_max_position_embeddings` must be set to an int when using yarn, and dynamic-yarn")
generation_config.json ADDED
@@ -0,0 +1,6 @@
 
 
 
 
 
 
 
1
+ {
2
+ "_from_model_config": true,
3
+ "bos_token_id": 1,
4
+ "eos_token_id": 2,
5
+ "transformers_version": "4.39.2"
6
+ }
model-00001-of-00003.safetensors ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:2a943387922f9aaed6acbb5a65f5faa1b9b6699d6024fc4a30a500558b17f9d1
3
+ size 4943162336
model-00002-of-00003.safetensors ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:d954d2cfd147440423ae9450874a6727e70c7d2a43c094b0542860a0a55934e8
3
+ size 4999819336
model-00003-of-00003.safetensors ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:9750f2739f3487b7d8b0e35b9b51e87a2181f7168eec2144c4c46afcffe64e9f
3
+ size 4540516344
model.safetensors.index.json ADDED
@@ -0,0 +1,298 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "metadata": {
3
+ "total_size": 14483464192
4
+ },
5
+ "weight_map": {
6
+ "lm_head.weight": "model-00003-of-00003.safetensors",
7
+ "model.embed_tokens.weight": "model-00001-of-00003.safetensors",
8
+ "model.layers.0.input_layernorm.weight": "model-00001-of-00003.safetensors",
9
+ "model.layers.0.mlp.down_proj.weight": "model-00001-of-00003.safetensors",
10
+ "model.layers.0.mlp.gate_proj.weight": "model-00001-of-00003.safetensors",
11
+ "model.layers.0.mlp.up_proj.weight": "model-00001-of-00003.safetensors",
12
+ "model.layers.0.post_attention_layernorm.weight": "model-00001-of-00003.safetensors",
13
+ "model.layers.0.self_attn.k_proj.weight": "model-00001-of-00003.safetensors",
14
+ "model.layers.0.self_attn.o_proj.weight": "model-00001-of-00003.safetensors",
15
+ "model.layers.0.self_attn.q_proj.weight": "model-00001-of-00003.safetensors",
16
+ "model.layers.0.self_attn.v_proj.weight": "model-00001-of-00003.safetensors",
17
+ "model.layers.1.input_layernorm.weight": "model-00001-of-00003.safetensors",
18
+ "model.layers.1.mlp.down_proj.weight": "model-00001-of-00003.safetensors",
19
+ "model.layers.1.mlp.gate_proj.weight": "model-00001-of-00003.safetensors",
20
+ "model.layers.1.mlp.up_proj.weight": "model-00001-of-00003.safetensors",
21
+ "model.layers.1.post_attention_layernorm.weight": "model-00001-of-00003.safetensors",
22
+ "model.layers.1.self_attn.k_proj.weight": "model-00001-of-00003.safetensors",
23
+ "model.layers.1.self_attn.o_proj.weight": "model-00001-of-00003.safetensors",
24
+ "model.layers.1.self_attn.q_proj.weight": "model-00001-of-00003.safetensors",
25
+ "model.layers.1.self_attn.v_proj.weight": "model-00001-of-00003.safetensors",
26
+ "model.layers.10.input_layernorm.weight": "model-00002-of-00003.safetensors",
27
+ "model.layers.10.mlp.down_proj.weight": "model-00002-of-00003.safetensors",
28
+ "model.layers.10.mlp.gate_proj.weight": "model-00001-of-00003.safetensors",
29
+ "model.layers.10.mlp.up_proj.weight": "model-00001-of-00003.safetensors",
30
+ "model.layers.10.post_attention_layernorm.weight": "model-00002-of-00003.safetensors",
31
+ "model.layers.10.self_attn.k_proj.weight": "model-00001-of-00003.safetensors",
32
+ "model.layers.10.self_attn.o_proj.weight": "model-00001-of-00003.safetensors",
33
+ "model.layers.10.self_attn.q_proj.weight": "model-00001-of-00003.safetensors",
34
+ "model.layers.10.self_attn.v_proj.weight": "model-00001-of-00003.safetensors",
35
+ "model.layers.11.input_layernorm.weight": "model-00002-of-00003.safetensors",
36
+ "model.layers.11.mlp.down_proj.weight": "model-00002-of-00003.safetensors",
37
+ "model.layers.11.mlp.gate_proj.weight": "model-00002-of-00003.safetensors",
38
+ "model.layers.11.mlp.up_proj.weight": "model-00002-of-00003.safetensors",
39
+ "model.layers.11.post_attention_layernorm.weight": "model-00002-of-00003.safetensors",
40
+ "model.layers.11.self_attn.k_proj.weight": "model-00002-of-00003.safetensors",
41
+ "model.layers.11.self_attn.o_proj.weight": "model-00002-of-00003.safetensors",
42
+ "model.layers.11.self_attn.q_proj.weight": "model-00002-of-00003.safetensors",
43
+ "model.layers.11.self_attn.v_proj.weight": "model-00002-of-00003.safetensors",
44
+ "model.layers.12.input_layernorm.weight": "model-00002-of-00003.safetensors",
45
+ "model.layers.12.mlp.down_proj.weight": "model-00002-of-00003.safetensors",
46
+ "model.layers.12.mlp.gate_proj.weight": "model-00002-of-00003.safetensors",
47
+ "model.layers.12.mlp.up_proj.weight": "model-00002-of-00003.safetensors",
48
+ "model.layers.12.post_attention_layernorm.weight": "model-00002-of-00003.safetensors",
49
+ "model.layers.12.self_attn.k_proj.weight": "model-00002-of-00003.safetensors",
50
+ "model.layers.12.self_attn.o_proj.weight": "model-00002-of-00003.safetensors",
51
+ "model.layers.12.self_attn.q_proj.weight": "model-00002-of-00003.safetensors",
52
+ "model.layers.12.self_attn.v_proj.weight": "model-00002-of-00003.safetensors",
53
+ "model.layers.13.input_layernorm.weight": "model-00002-of-00003.safetensors",
54
+ "model.layers.13.mlp.down_proj.weight": "model-00002-of-00003.safetensors",
55
+ "model.layers.13.mlp.gate_proj.weight": "model-00002-of-00003.safetensors",
56
+ "model.layers.13.mlp.up_proj.weight": "model-00002-of-00003.safetensors",
57
+ "model.layers.13.post_attention_layernorm.weight": "model-00002-of-00003.safetensors",
58
+ "model.layers.13.self_attn.k_proj.weight": "model-00002-of-00003.safetensors",
59
+ "model.layers.13.self_attn.o_proj.weight": "model-00002-of-00003.safetensors",
60
+ "model.layers.13.self_attn.q_proj.weight": "model-00002-of-00003.safetensors",
61
+ "model.layers.13.self_attn.v_proj.weight": "model-00002-of-00003.safetensors",
62
+ "model.layers.14.input_layernorm.weight": "model-00002-of-00003.safetensors",
63
+ "model.layers.14.mlp.down_proj.weight": "model-00002-of-00003.safetensors",
64
+ "model.layers.14.mlp.gate_proj.weight": "model-00002-of-00003.safetensors",
65
+ "model.layers.14.mlp.up_proj.weight": "model-00002-of-00003.safetensors",
66
+ "model.layers.14.post_attention_layernorm.weight": "model-00002-of-00003.safetensors",
67
+ "model.layers.14.self_attn.k_proj.weight": "model-00002-of-00003.safetensors",
68
+ "model.layers.14.self_attn.o_proj.weight": "model-00002-of-00003.safetensors",
69
+ "model.layers.14.self_attn.q_proj.weight": "model-00002-of-00003.safetensors",
70
+ "model.layers.14.self_attn.v_proj.weight": "model-00002-of-00003.safetensors",
71
+ "model.layers.15.input_layernorm.weight": "model-00002-of-00003.safetensors",
72
+ "model.layers.15.mlp.down_proj.weight": "model-00002-of-00003.safetensors",
73
+ "model.layers.15.mlp.gate_proj.weight": "model-00002-of-00003.safetensors",
74
+ "model.layers.15.mlp.up_proj.weight": "model-00002-of-00003.safetensors",
75
+ "model.layers.15.post_attention_layernorm.weight": "model-00002-of-00003.safetensors",
76
+ "model.layers.15.self_attn.k_proj.weight": "model-00002-of-00003.safetensors",
77
+ "model.layers.15.self_attn.o_proj.weight": "model-00002-of-00003.safetensors",
78
+ "model.layers.15.self_attn.q_proj.weight": "model-00002-of-00003.safetensors",
79
+ "model.layers.15.self_attn.v_proj.weight": "model-00002-of-00003.safetensors",
80
+ "model.layers.16.input_layernorm.weight": "model-00002-of-00003.safetensors",
81
+ "model.layers.16.mlp.down_proj.weight": "model-00002-of-00003.safetensors",
82
+ "model.layers.16.mlp.gate_proj.weight": "model-00002-of-00003.safetensors",
83
+ "model.layers.16.mlp.up_proj.weight": "model-00002-of-00003.safetensors",
84
+ "model.layers.16.post_attention_layernorm.weight": "model-00002-of-00003.safetensors",
85
+ "model.layers.16.self_attn.k_proj.weight": "model-00002-of-00003.safetensors",
86
+ "model.layers.16.self_attn.o_proj.weight": "model-00002-of-00003.safetensors",
87
+ "model.layers.16.self_attn.q_proj.weight": "model-00002-of-00003.safetensors",
88
+ "model.layers.16.self_attn.v_proj.weight": "model-00002-of-00003.safetensors",
89
+ "model.layers.17.input_layernorm.weight": "model-00002-of-00003.safetensors",
90
+ "model.layers.17.mlp.down_proj.weight": "model-00002-of-00003.safetensors",
91
+ "model.layers.17.mlp.gate_proj.weight": "model-00002-of-00003.safetensors",
92
+ "model.layers.17.mlp.up_proj.weight": "model-00002-of-00003.safetensors",
93
+ "model.layers.17.post_attention_layernorm.weight": "model-00002-of-00003.safetensors",
94
+ "model.layers.17.self_attn.k_proj.weight": "model-00002-of-00003.safetensors",
95
+ "model.layers.17.self_attn.o_proj.weight": "model-00002-of-00003.safetensors",
96
+ "model.layers.17.self_attn.q_proj.weight": "model-00002-of-00003.safetensors",
97
+ "model.layers.17.self_attn.v_proj.weight": "model-00002-of-00003.safetensors",
98
+ "model.layers.18.input_layernorm.weight": "model-00002-of-00003.safetensors",
99
+ "model.layers.18.mlp.down_proj.weight": "model-00002-of-00003.safetensors",
100
+ "model.layers.18.mlp.gate_proj.weight": "model-00002-of-00003.safetensors",
101
+ "model.layers.18.mlp.up_proj.weight": "model-00002-of-00003.safetensors",
102
+ "model.layers.18.post_attention_layernorm.weight": "model-00002-of-00003.safetensors",
103
+ "model.layers.18.self_attn.k_proj.weight": "model-00002-of-00003.safetensors",
104
+ "model.layers.18.self_attn.o_proj.weight": "model-00002-of-00003.safetensors",
105
+ "model.layers.18.self_attn.q_proj.weight": "model-00002-of-00003.safetensors",
106
+ "model.layers.18.self_attn.v_proj.weight": "model-00002-of-00003.safetensors",
107
+ "model.layers.19.input_layernorm.weight": "model-00002-of-00003.safetensors",
108
+ "model.layers.19.mlp.down_proj.weight": "model-00002-of-00003.safetensors",
109
+ "model.layers.19.mlp.gate_proj.weight": "model-00002-of-00003.safetensors",
110
+ "model.layers.19.mlp.up_proj.weight": "model-00002-of-00003.safetensors",
111
+ "model.layers.19.post_attention_layernorm.weight": "model-00002-of-00003.safetensors",
112
+ "model.layers.19.self_attn.k_proj.weight": "model-00002-of-00003.safetensors",
113
+ "model.layers.19.self_attn.o_proj.weight": "model-00002-of-00003.safetensors",
114
+ "model.layers.19.self_attn.q_proj.weight": "model-00002-of-00003.safetensors",
115
+ "model.layers.19.self_attn.v_proj.weight": "model-00002-of-00003.safetensors",
116
+ "model.layers.2.input_layernorm.weight": "model-00001-of-00003.safetensors",
117
+ "model.layers.2.mlp.down_proj.weight": "model-00001-of-00003.safetensors",
118
+ "model.layers.2.mlp.gate_proj.weight": "model-00001-of-00003.safetensors",
119
+ "model.layers.2.mlp.up_proj.weight": "model-00001-of-00003.safetensors",
120
+ "model.layers.2.post_attention_layernorm.weight": "model-00001-of-00003.safetensors",
121
+ "model.layers.2.self_attn.k_proj.weight": "model-00001-of-00003.safetensors",
122
+ "model.layers.2.self_attn.o_proj.weight": "model-00001-of-00003.safetensors",
123
+ "model.layers.2.self_attn.q_proj.weight": "model-00001-of-00003.safetensors",
124
+ "model.layers.2.self_attn.v_proj.weight": "model-00001-of-00003.safetensors",
125
+ "model.layers.20.input_layernorm.weight": "model-00002-of-00003.safetensors",
126
+ "model.layers.20.mlp.down_proj.weight": "model-00002-of-00003.safetensors",
127
+ "model.layers.20.mlp.gate_proj.weight": "model-00002-of-00003.safetensors",
128
+ "model.layers.20.mlp.up_proj.weight": "model-00002-of-00003.safetensors",
129
+ "model.layers.20.post_attention_layernorm.weight": "model-00002-of-00003.safetensors",
130
+ "model.layers.20.self_attn.k_proj.weight": "model-00002-of-00003.safetensors",
131
+ "model.layers.20.self_attn.o_proj.weight": "model-00002-of-00003.safetensors",
132
+ "model.layers.20.self_attn.q_proj.weight": "model-00002-of-00003.safetensors",
133
+ "model.layers.20.self_attn.v_proj.weight": "model-00002-of-00003.safetensors",
134
+ "model.layers.21.input_layernorm.weight": "model-00002-of-00003.safetensors",
135
+ "model.layers.21.mlp.down_proj.weight": "model-00002-of-00003.safetensors",
136
+ "model.layers.21.mlp.gate_proj.weight": "model-00002-of-00003.safetensors",
137
+ "model.layers.21.mlp.up_proj.weight": "model-00002-of-00003.safetensors",
138
+ "model.layers.21.post_attention_layernorm.weight": "model-00002-of-00003.safetensors",
139
+ "model.layers.21.self_attn.k_proj.weight": "model-00002-of-00003.safetensors",
140
+ "model.layers.21.self_attn.o_proj.weight": "model-00002-of-00003.safetensors",
141
+ "model.layers.21.self_attn.q_proj.weight": "model-00002-of-00003.safetensors",
142
+ "model.layers.21.self_attn.v_proj.weight": "model-00002-of-00003.safetensors",
143
+ "model.layers.22.input_layernorm.weight": "model-00003-of-00003.safetensors",
144
+ "model.layers.22.mlp.down_proj.weight": "model-00003-of-00003.safetensors",
145
+ "model.layers.22.mlp.gate_proj.weight": "model-00003-of-00003.safetensors",
146
+ "model.layers.22.mlp.up_proj.weight": "model-00003-of-00003.safetensors",
147
+ "model.layers.22.post_attention_layernorm.weight": "model-00003-of-00003.safetensors",
148
+ "model.layers.22.self_attn.k_proj.weight": "model-00002-of-00003.safetensors",
149
+ "model.layers.22.self_attn.o_proj.weight": "model-00002-of-00003.safetensors",
150
+ "model.layers.22.self_attn.q_proj.weight": "model-00002-of-00003.safetensors",
151
+ "model.layers.22.self_attn.v_proj.weight": "model-00002-of-00003.safetensors",
152
+ "model.layers.23.input_layernorm.weight": "model-00003-of-00003.safetensors",
153
+ "model.layers.23.mlp.down_proj.weight": "model-00003-of-00003.safetensors",
154
+ "model.layers.23.mlp.gate_proj.weight": "model-00003-of-00003.safetensors",
155
+ "model.layers.23.mlp.up_proj.weight": "model-00003-of-00003.safetensors",
156
+ "model.layers.23.post_attention_layernorm.weight": "model-00003-of-00003.safetensors",
157
+ "model.layers.23.self_attn.k_proj.weight": "model-00003-of-00003.safetensors",
158
+ "model.layers.23.self_attn.o_proj.weight": "model-00003-of-00003.safetensors",
159
+ "model.layers.23.self_attn.q_proj.weight": "model-00003-of-00003.safetensors",
160
+ "model.layers.23.self_attn.v_proj.weight": "model-00003-of-00003.safetensors",
161
+ "model.layers.24.input_layernorm.weight": "model-00003-of-00003.safetensors",
162
+ "model.layers.24.mlp.down_proj.weight": "model-00003-of-00003.safetensors",
163
+ "model.layers.24.mlp.gate_proj.weight": "model-00003-of-00003.safetensors",
164
+ "model.layers.24.mlp.up_proj.weight": "model-00003-of-00003.safetensors",
165
+ "model.layers.24.post_attention_layernorm.weight": "model-00003-of-00003.safetensors",
166
+ "model.layers.24.self_attn.k_proj.weight": "model-00003-of-00003.safetensors",
167
+ "model.layers.24.self_attn.o_proj.weight": "model-00003-of-00003.safetensors",
168
+ "model.layers.24.self_attn.q_proj.weight": "model-00003-of-00003.safetensors",
169
+ "model.layers.24.self_attn.v_proj.weight": "model-00003-of-00003.safetensors",
170
+ "model.layers.25.input_layernorm.weight": "model-00003-of-00003.safetensors",
171
+ "model.layers.25.mlp.down_proj.weight": "model-00003-of-00003.safetensors",
172
+ "model.layers.25.mlp.gate_proj.weight": "model-00003-of-00003.safetensors",
173
+ "model.layers.25.mlp.up_proj.weight": "model-00003-of-00003.safetensors",
174
+ "model.layers.25.post_attention_layernorm.weight": "model-00003-of-00003.safetensors",
175
+ "model.layers.25.self_attn.k_proj.weight": "model-00003-of-00003.safetensors",
176
+ "model.layers.25.self_attn.o_proj.weight": "model-00003-of-00003.safetensors",
177
+ "model.layers.25.self_attn.q_proj.weight": "model-00003-of-00003.safetensors",
178
+ "model.layers.25.self_attn.v_proj.weight": "model-00003-of-00003.safetensors",
179
+ "model.layers.26.input_layernorm.weight": "model-00003-of-00003.safetensors",
180
+ "model.layers.26.mlp.down_proj.weight": "model-00003-of-00003.safetensors",
181
+ "model.layers.26.mlp.gate_proj.weight": "model-00003-of-00003.safetensors",
182
+ "model.layers.26.mlp.up_proj.weight": "model-00003-of-00003.safetensors",
183
+ "model.layers.26.post_attention_layernorm.weight": "model-00003-of-00003.safetensors",
184
+ "model.layers.26.self_attn.k_proj.weight": "model-00003-of-00003.safetensors",
185
+ "model.layers.26.self_attn.o_proj.weight": "model-00003-of-00003.safetensors",
186
+ "model.layers.26.self_attn.q_proj.weight": "model-00003-of-00003.safetensors",
187
+ "model.layers.26.self_attn.v_proj.weight": "model-00003-of-00003.safetensors",
188
+ "model.layers.27.input_layernorm.weight": "model-00003-of-00003.safetensors",
189
+ "model.layers.27.mlp.down_proj.weight": "model-00003-of-00003.safetensors",
190
+ "model.layers.27.mlp.gate_proj.weight": "model-00003-of-00003.safetensors",
191
+ "model.layers.27.mlp.up_proj.weight": "model-00003-of-00003.safetensors",
192
+ "model.layers.27.post_attention_layernorm.weight": "model-00003-of-00003.safetensors",
193
+ "model.layers.27.self_attn.k_proj.weight": "model-00003-of-00003.safetensors",
194
+ "model.layers.27.self_attn.o_proj.weight": "model-00003-of-00003.safetensors",
195
+ "model.layers.27.self_attn.q_proj.weight": "model-00003-of-00003.safetensors",
196
+ "model.layers.27.self_attn.v_proj.weight": "model-00003-of-00003.safetensors",
197
+ "model.layers.28.input_layernorm.weight": "model-00003-of-00003.safetensors",
198
+ "model.layers.28.mlp.down_proj.weight": "model-00003-of-00003.safetensors",
199
+ "model.layers.28.mlp.gate_proj.weight": "model-00003-of-00003.safetensors",
200
+ "model.layers.28.mlp.up_proj.weight": "model-00003-of-00003.safetensors",
201
+ "model.layers.28.post_attention_layernorm.weight": "model-00003-of-00003.safetensors",
202
+ "model.layers.28.self_attn.k_proj.weight": "model-00003-of-00003.safetensors",
203
+ "model.layers.28.self_attn.o_proj.weight": "model-00003-of-00003.safetensors",
204
+ "model.layers.28.self_attn.q_proj.weight": "model-00003-of-00003.safetensors",
205
+ "model.layers.28.self_attn.v_proj.weight": "model-00003-of-00003.safetensors",
206
+ "model.layers.29.input_layernorm.weight": "model-00003-of-00003.safetensors",
207
+ "model.layers.29.mlp.down_proj.weight": "model-00003-of-00003.safetensors",
208
+ "model.layers.29.mlp.gate_proj.weight": "model-00003-of-00003.safetensors",
209
+ "model.layers.29.mlp.up_proj.weight": "model-00003-of-00003.safetensors",
210
+ "model.layers.29.post_attention_layernorm.weight": "model-00003-of-00003.safetensors",
211
+ "model.layers.29.self_attn.k_proj.weight": "model-00003-of-00003.safetensors",
212
+ "model.layers.29.self_attn.o_proj.weight": "model-00003-of-00003.safetensors",
213
+ "model.layers.29.self_attn.q_proj.weight": "model-00003-of-00003.safetensors",
214
+ "model.layers.29.self_attn.v_proj.weight": "model-00003-of-00003.safetensors",
215
+ "model.layers.3.input_layernorm.weight": "model-00001-of-00003.safetensors",
216
+ "model.layers.3.mlp.down_proj.weight": "model-00001-of-00003.safetensors",
217
+ "model.layers.3.mlp.gate_proj.weight": "model-00001-of-00003.safetensors",
218
+ "model.layers.3.mlp.up_proj.weight": "model-00001-of-00003.safetensors",
219
+ "model.layers.3.post_attention_layernorm.weight": "model-00001-of-00003.safetensors",
220
+ "model.layers.3.self_attn.k_proj.weight": "model-00001-of-00003.safetensors",
221
+ "model.layers.3.self_attn.o_proj.weight": "model-00001-of-00003.safetensors",
222
+ "model.layers.3.self_attn.q_proj.weight": "model-00001-of-00003.safetensors",
223
+ "model.layers.3.self_attn.v_proj.weight": "model-00001-of-00003.safetensors",
224
+ "model.layers.30.input_layernorm.weight": "model-00003-of-00003.safetensors",
225
+ "model.layers.30.mlp.down_proj.weight": "model-00003-of-00003.safetensors",
226
+ "model.layers.30.mlp.gate_proj.weight": "model-00003-of-00003.safetensors",
227
+ "model.layers.30.mlp.up_proj.weight": "model-00003-of-00003.safetensors",
228
+ "model.layers.30.post_attention_layernorm.weight": "model-00003-of-00003.safetensors",
229
+ "model.layers.30.self_attn.k_proj.weight": "model-00003-of-00003.safetensors",
230
+ "model.layers.30.self_attn.o_proj.weight": "model-00003-of-00003.safetensors",
231
+ "model.layers.30.self_attn.q_proj.weight": "model-00003-of-00003.safetensors",
232
+ "model.layers.30.self_attn.v_proj.weight": "model-00003-of-00003.safetensors",
233
+ "model.layers.31.input_layernorm.weight": "model-00003-of-00003.safetensors",
234
+ "model.layers.31.mlp.down_proj.weight": "model-00003-of-00003.safetensors",
235
+ "model.layers.31.mlp.gate_proj.weight": "model-00003-of-00003.safetensors",
236
+ "model.layers.31.mlp.up_proj.weight": "model-00003-of-00003.safetensors",
237
+ "model.layers.31.post_attention_layernorm.weight": "model-00003-of-00003.safetensors",
238
+ "model.layers.31.self_attn.k_proj.weight": "model-00003-of-00003.safetensors",
239
+ "model.layers.31.self_attn.o_proj.weight": "model-00003-of-00003.safetensors",
240
+ "model.layers.31.self_attn.q_proj.weight": "model-00003-of-00003.safetensors",
241
+ "model.layers.31.self_attn.v_proj.weight": "model-00003-of-00003.safetensors",
242
+ "model.layers.4.input_layernorm.weight": "model-00001-of-00003.safetensors",
243
+ "model.layers.4.mlp.down_proj.weight": "model-00001-of-00003.safetensors",
244
+ "model.layers.4.mlp.gate_proj.weight": "model-00001-of-00003.safetensors",
245
+ "model.layers.4.mlp.up_proj.weight": "model-00001-of-00003.safetensors",
246
+ "model.layers.4.post_attention_layernorm.weight": "model-00001-of-00003.safetensors",
247
+ "model.layers.4.self_attn.k_proj.weight": "model-00001-of-00003.safetensors",
248
+ "model.layers.4.self_attn.o_proj.weight": "model-00001-of-00003.safetensors",
249
+ "model.layers.4.self_attn.q_proj.weight": "model-00001-of-00003.safetensors",
250
+ "model.layers.4.self_attn.v_proj.weight": "model-00001-of-00003.safetensors",
251
+ "model.layers.5.input_layernorm.weight": "model-00001-of-00003.safetensors",
252
+ "model.layers.5.mlp.down_proj.weight": "model-00001-of-00003.safetensors",
253
+ "model.layers.5.mlp.gate_proj.weight": "model-00001-of-00003.safetensors",
254
+ "model.layers.5.mlp.up_proj.weight": "model-00001-of-00003.safetensors",
255
+ "model.layers.5.post_attention_layernorm.weight": "model-00001-of-00003.safetensors",
256
+ "model.layers.5.self_attn.k_proj.weight": "model-00001-of-00003.safetensors",
257
+ "model.layers.5.self_attn.o_proj.weight": "model-00001-of-00003.safetensors",
258
+ "model.layers.5.self_attn.q_proj.weight": "model-00001-of-00003.safetensors",
259
+ "model.layers.5.self_attn.v_proj.weight": "model-00001-of-00003.safetensors",
260
+ "model.layers.6.input_layernorm.weight": "model-00001-of-00003.safetensors",
261
+ "model.layers.6.mlp.down_proj.weight": "model-00001-of-00003.safetensors",
262
+ "model.layers.6.mlp.gate_proj.weight": "model-00001-of-00003.safetensors",
263
+ "model.layers.6.mlp.up_proj.weight": "model-00001-of-00003.safetensors",
264
+ "model.layers.6.post_attention_layernorm.weight": "model-00001-of-00003.safetensors",
265
+ "model.layers.6.self_attn.k_proj.weight": "model-00001-of-00003.safetensors",
266
+ "model.layers.6.self_attn.o_proj.weight": "model-00001-of-00003.safetensors",
267
+ "model.layers.6.self_attn.q_proj.weight": "model-00001-of-00003.safetensors",
268
+ "model.layers.6.self_attn.v_proj.weight": "model-00001-of-00003.safetensors",
269
+ "model.layers.7.input_layernorm.weight": "model-00001-of-00003.safetensors",
270
+ "model.layers.7.mlp.down_proj.weight": "model-00001-of-00003.safetensors",
271
+ "model.layers.7.mlp.gate_proj.weight": "model-00001-of-00003.safetensors",
272
+ "model.layers.7.mlp.up_proj.weight": "model-00001-of-00003.safetensors",
273
+ "model.layers.7.post_attention_layernorm.weight": "model-00001-of-00003.safetensors",
274
+ "model.layers.7.self_attn.k_proj.weight": "model-00001-of-00003.safetensors",
275
+ "model.layers.7.self_attn.o_proj.weight": "model-00001-of-00003.safetensors",
276
+ "model.layers.7.self_attn.q_proj.weight": "model-00001-of-00003.safetensors",
277
+ "model.layers.7.self_attn.v_proj.weight": "model-00001-of-00003.safetensors",
278
+ "model.layers.8.input_layernorm.weight": "model-00001-of-00003.safetensors",
279
+ "model.layers.8.mlp.down_proj.weight": "model-00001-of-00003.safetensors",
280
+ "model.layers.8.mlp.gate_proj.weight": "model-00001-of-00003.safetensors",
281
+ "model.layers.8.mlp.up_proj.weight": "model-00001-of-00003.safetensors",
282
+ "model.layers.8.post_attention_layernorm.weight": "model-00001-of-00003.safetensors",
283
+ "model.layers.8.self_attn.k_proj.weight": "model-00001-of-00003.safetensors",
284
+ "model.layers.8.self_attn.o_proj.weight": "model-00001-of-00003.safetensors",
285
+ "model.layers.8.self_attn.q_proj.weight": "model-00001-of-00003.safetensors",
286
+ "model.layers.8.self_attn.v_proj.weight": "model-00001-of-00003.safetensors",
287
+ "model.layers.9.input_layernorm.weight": "model-00001-of-00003.safetensors",
288
+ "model.layers.9.mlp.down_proj.weight": "model-00001-of-00003.safetensors",
289
+ "model.layers.9.mlp.gate_proj.weight": "model-00001-of-00003.safetensors",
290
+ "model.layers.9.mlp.up_proj.weight": "model-00001-of-00003.safetensors",
291
+ "model.layers.9.post_attention_layernorm.weight": "model-00001-of-00003.safetensors",
292
+ "model.layers.9.self_attn.k_proj.weight": "model-00001-of-00003.safetensors",
293
+ "model.layers.9.self_attn.o_proj.weight": "model-00001-of-00003.safetensors",
294
+ "model.layers.9.self_attn.q_proj.weight": "model-00001-of-00003.safetensors",
295
+ "model.layers.9.self_attn.v_proj.weight": "model-00001-of-00003.safetensors",
296
+ "model.norm.weight": "model-00003-of-00003.safetensors"
297
+ }
298
+ }
modeling_mistral_yarn.py ADDED
@@ -0,0 +1,1638 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # coding=utf-8
2
+ # Copyright 2023 Mistral AI and the HuggingFace Inc. team. All rights reserved.
3
+ #
4
+ # This code is based on EleutherAI's GPT-NeoX library and the GPT-NeoX
5
+ # and OPT implementations in this library. It has been modified from its
6
+ # original forms to accommodate minor architectural differences compared
7
+ # to GPT-NeoX and OPT used by the Meta AI team that trained the model.
8
+ #
9
+ # Licensed under the Apache License, Version 2.0 (the "License");
10
+ # you may not use this file except in compliance with the License.
11
+ # You may obtain a copy of the License at
12
+ #
13
+ # http://www.apache.org/licenses/LICENSE-2.0
14
+ #
15
+ # Unless required by applicable law or agreed to in writing, software
16
+ # distributed under the License is distributed on an "AS IS" BASIS,
17
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
18
+ # See the License for the specific language governing permissions and
19
+ # limitations under the License.
20
+ """ PyTorch Mistral model."""
21
+ import inspect
22
+ import math
23
+ import 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
+ from transformers.cache_utils import Cache, DynamicCache
34
+ from transformers.modeling_attn_mask_utils import _prepare_4d_causal_attention_mask, _prepare_4d_causal_attention_mask_for_sdpa
35
+ from transformers.modeling_outputs import BaseModelOutputWithPast, CausalLMOutputWithPast, SequenceClassifierOutputWithPast
36
+ from transformers.modeling_utils import PreTrainedModel
37
+ from transformers.utils import (
38
+ add_start_docstrings,
39
+ add_start_docstrings_to_model_forward,
40
+ is_flash_attn_2_available,
41
+ is_flash_attn_greater_or_equal_2_10,
42
+ logging,
43
+ replace_return_docstrings,
44
+ )
45
+ from .configuration_mistral import MistralConfig
46
+
47
+
48
+ if is_flash_attn_2_available():
49
+ from flash_attn import flash_attn_func, flash_attn_varlen_func
50
+ from flash_attn.bert_padding import index_first_axis, pad_input, unpad_input # noqa
51
+
52
+ _flash_supports_window_size = "window_size" in list(inspect.signature(flash_attn_func).parameters)
53
+
54
+
55
+ logger = logging.get_logger(__name__)
56
+
57
+ _CONFIG_FOR_DOC = "MistralConfig"
58
+
59
+
60
+ # Copied from transformers.models.llama.modeling_llama._get_unpad_data
61
+ def _get_unpad_data(attention_mask):
62
+ seqlens_in_batch = attention_mask.sum(dim=-1, dtype=torch.int32)
63
+ indices = torch.nonzero(attention_mask.flatten(), as_tuple=False).flatten()
64
+ max_seqlen_in_batch = seqlens_in_batch.max().item()
65
+ cu_seqlens = F.pad(torch.cumsum(seqlens_in_batch, dim=0, dtype=torch.int32), (1, 0))
66
+ return (
67
+ indices,
68
+ cu_seqlens,
69
+ max_seqlen_in_batch,
70
+ )
71
+
72
+ # Newly Added For YARN
73
+
74
+ def _yarn_find_correction_dim(num_rotations, dim, base=10000, max_position_embeddings=2048):
75
+ return (dim * math.log(max_position_embeddings/(num_rotations * 2 * math.pi)))/(2 * math.log(base))
76
+
77
+ # Find dim range bounds based on rotations
78
+ def _yarn_find_correction_range(low_rot, high_rot, dim, base=10000, max_position_embeddings=2048):
79
+ low = math.floor(_yarn_find_correction_dim(
80
+ low_rot, dim, base, max_position_embeddings))
81
+ high = math.ceil(_yarn_find_correction_dim(
82
+ high_rot, dim, base, max_position_embeddings))
83
+ return max(low, 0), min(high, dim-1) # Clamp values just in case
84
+
85
+ def _yarn_linear_ramp_mask(min, max, dim):
86
+ if min == max:
87
+ max += 0.001 # Prevent singularity
88
+
89
+ linear_func = (torch.arange(dim, dtype=torch.float32) - min) / (max - min)
90
+ ramp_func = torch.clamp(linear_func, 0, 1)
91
+ return ramp_func
92
+
93
+ def _yarn_get_mscale(scale=1):
94
+ if scale <= 1:
95
+ return 1.0
96
+ return 0.07 * math.log(scale) + 1.0
97
+
98
+
99
+
100
+ # Copied from transformers.models.llama.modeling_llama.LlamaRMSNorm with Llama->Mistral
101
+ class MistralRMSNorm(nn.Module):
102
+ def __init__(self, hidden_size, eps=1e-6):
103
+ """
104
+ MistralRMSNorm is equivalent to T5LayerNorm
105
+ """
106
+ super().__init__()
107
+ self.weight = nn.Parameter(torch.ones(hidden_size))
108
+ self.variance_epsilon = eps
109
+
110
+ def forward(self, hidden_states):
111
+ input_dtype = hidden_states.dtype
112
+ hidden_states = hidden_states.to(torch.float32)
113
+ variance = hidden_states.pow(2).mean(-1, keepdim=True)
114
+ hidden_states = hidden_states * torch.rsqrt(variance + self.variance_epsilon)
115
+ return self.weight * hidden_states.to(input_dtype)
116
+
117
+
118
+ # copied from transformers.models.llama.modeling_llama.LlamaRotaryEmbedding with Llama->Mistral
119
+ # TODO @Arthur no longer copied from LLama after static cache
120
+ class MistralRotaryEmbedding(nn.Module):
121
+ def __init__(self, dim, max_position_embeddings=2048, base=10000, device=None):
122
+ super().__init__()
123
+
124
+ self.dim = dim
125
+ self.max_position_embeddings = max_position_embeddings
126
+ self.base = base
127
+ inv_freq = 1.0 / (self.base ** (torch.arange(0, self.dim, 2, dtype=torch.int64).float().to(device) / self.dim))
128
+ self.register_buffer("inv_freq", inv_freq, persistent=False)
129
+
130
+ # Build here to make `torch.jit.trace` work.
131
+ self._set_cos_sin_cache(
132
+ seq_len=max_position_embeddings, device=self.inv_freq.device, dtype=torch.get_default_dtype()
133
+ )
134
+
135
+ def _set_cos_sin_cache(self, seq_len, device, dtype):
136
+ self.max_seq_len_cached = seq_len
137
+ t = torch.arange(self.max_seq_len_cached, device=device, dtype=torch.int64).type_as(self.inv_freq)
138
+
139
+ freqs = torch.outer(t, self.inv_freq)
140
+ # Different from paper, but it uses a different permutation in order to obtain the same calculation
141
+ emb = torch.cat((freqs, freqs), dim=-1)
142
+ self.register_buffer("cos_cached", emb.cos().to(dtype), persistent=False)
143
+ self.register_buffer("sin_cached", emb.sin().to(dtype), persistent=False)
144
+
145
+ def forward(self, x, seq_len=None):
146
+ # x: [bs, num_attention_heads, seq_len, head_size]
147
+ if seq_len > self.max_seq_len_cached:
148
+ self._set_cos_sin_cache(seq_len=seq_len, device=x.device, dtype=x.dtype)
149
+
150
+ return (
151
+ self.cos_cached[:seq_len].to(dtype=x.dtype),
152
+ self.sin_cached[:seq_len].to(dtype=x.dtype),
153
+ )
154
+
155
+
156
+ # Newly Added For YARN
157
+ class MistralLinearScalingRotaryEmbedding(MistralRotaryEmbedding): #Positional Interpolation
158
+ """MistralRotaryEmbedding extended with linear scaling. Credits to the Reddit user /u/kaiokendev"""
159
+
160
+ def __init__(self, dim, max_position_embeddings=2048, base=10000, device=None, scaling_factor=1.0):
161
+ self.scaling_factor = scaling_factor
162
+ super().__init__(dim, max_position_embeddings, base, device)
163
+
164
+ def _set_cos_sin_cache(self, seq_len, device, dtype):
165
+ self.max_seq_len_cached = seq_len
166
+ t = torch.arange(self.max_seq_len_cached, device=device, dtype=self.inv_freq.dtype)
167
+ t = t / self.scaling_factor
168
+
169
+ freqs = torch.einsum("i,j->ij", t, self.inv_freq)
170
+ # Different from paper, but it uses a different permutation in order to obtain the same calculation
171
+ emb = torch.cat((freqs, freqs), dim=-1)
172
+ self.register_buffer("cos_cached", emb.cos().to(dtype), persistent=False)
173
+ self.register_buffer("sin_cached", emb.cos().to(dtype), persistent=False)
174
+
175
+
176
+ # Newly Added For YARN
177
+ class MistralDynamicNTKScalingRotaryEmbedding(MistralRotaryEmbedding):
178
+ """MistralRotaryEmbedding extended with Dynamic NTK scaling. Credits to the Reddit users /u/bloc97 and /u/emozilla"""
179
+
180
+ def __init__(self, dim, max_position_embeddings=2048, base=10000, device=None, scaling_factor=1.0):
181
+ self.scaling_factor = scaling_factor
182
+ super().__init__(dim, max_position_embeddings, base, device)
183
+
184
+ def _set_cos_sin_cache(self, seq_len, device, dtype):
185
+ self.max_seq_len_cached = seq_len
186
+
187
+ if seq_len > self.max_position_embeddings:
188
+ base = self.base * ((self.scaling_factor * seq_len / self.max_position_embeddings) - (self.scaling_factor - 1)) ** (self.dim / (self.dim - 2))
189
+ inv_freq = 1.0 / (base ** (torch.arange(0, self.dim, 2).float().to(device) / self.dim))
190
+ self.register_buffer("inv_freq", inv_freq, persistent=False)
191
+
192
+ t = torch.arange(self.max_seq_len_cached, device=device, dtype=self.inv_freq.dtype)
193
+
194
+ freqs = torch.einsum("i,j->ij", t, self.inv_freq)
195
+ # Different from paper, but it uses a different permutation in order to obtain the same calculation
196
+ emb = torch.cat((freqs, freqs), dim=-1)
197
+ self.register_buffer("cos_cached", emb.cos().to(dtype), persistent=False)
198
+ self.register_buffer("sin_cached", emb.sin().to(dtype), persistent=False)
199
+
200
+
201
+ # Newly Added For YARN
202
+ class MistralYaRNScaledRotaryEmbedding(torch.nn.Module):
203
+ """MistralRotaryEmbedding extended with YaRN. See: https://arxiv.org/abs/2309.00071"""
204
+ def __init__(self, dim, max_position_embeddings=2048, base=10000, scale=1, original_max_position_embeddings=2048,
205
+ extrapolation_factor=1, attn_factor=1, beta_fast=128, beta_slow=2, finetuned=False, device=None):
206
+ super().__init__()
207
+
208
+ self.dim = dim
209
+ self.max_position_embeddings = max_position_embeddings
210
+ self.base = base
211
+ self.scale = scale
212
+ self.original_max_position_embeddings = original_max_position_embeddings
213
+ self.extrapolation_factor = extrapolation_factor
214
+ self.attn_factor = attn_factor
215
+ self.beta_fast = beta_fast
216
+ self.beta_slow = beta_slow
217
+
218
+ self.yarn(device)
219
+
220
+ # Build here to make `torch.jit.trace` work.
221
+ self.max_seq_len_cached = max_position_embeddings
222
+ t = torch.arange(self.max_seq_len_cached, device=self.inv_freq.device, dtype=self.inv_freq.dtype)
223
+ freqs = torch.einsum("i,j->ij", t, self.inv_freq)
224
+ # Different from paper, but it uses a different permutation in order to obtain the same calculation
225
+ emb = torch.cat((freqs, freqs), dim=-1)
226
+ dtype = torch.get_default_dtype()
227
+
228
+ self.register_buffer("cos_cached", (emb.cos() * self.mscale).to(dtype), persistent=False)
229
+ self.register_buffer("sin_cached", (emb.sin() * self.mscale).to(dtype), persistent=False)
230
+
231
+ def forward(self, x, seq_len=None):
232
+ # x: [bs, num_attention_heads, seq_len, head_size]
233
+ # This `if` block is unlikely to be run after we build sin/cos in `__init__`. Keep the logic here just in case.
234
+ if seq_len > self.max_seq_len_cached:
235
+ self.max_seq_len_cached = seq_len
236
+
237
+ t = torch.arange(self.max_seq_len_cached, device=x.device, dtype=self.inv_freq.dtype)
238
+ freqs = torch.einsum("i,j->ij", t, self.inv_freq)
239
+ # Different from paper, but it uses a different permutation in order to obtain the same calculation
240
+ emb = torch.cat((freqs, freqs), dim=-1).to(x.device)
241
+
242
+ self.register_buffer("cos_cached", (emb.cos() * self.mscale).to(x.dtype), persistent=False)
243
+ self.register_buffer("sin_cached", (emb.sin() * self.mscale).to(x.dtype), persistent=False)
244
+ return (
245
+ self.cos_cached[:seq_len].to(dtype=x.dtype),
246
+ self.sin_cached[:seq_len].to(dtype=x.dtype),
247
+ )
248
+
249
+ def yarn(self, device):
250
+ pos_freqs = self.base ** (torch.arange(0, self.dim, 2).float().to(device) / self.dim)
251
+ inv_freq_extrapolation = 1.0 / pos_freqs
252
+ inv_freq_interpolation = 1.0 / (self.scale * pos_freqs)
253
+
254
+ low, high = _yarn_find_correction_range(self.beta_fast, self.beta_slow, self.dim, self.base, self.original_max_position_embeddings)
255
+ inv_freq_mask = (1 - _yarn_linear_ramp_mask(low, high, self.dim // 2).float().to(device)) * self.extrapolation_factor # Get n-d rotational scaling corrected for extrapolation
256
+ inv_freq = inv_freq_interpolation * (1 - inv_freq_mask) + inv_freq_extrapolation * inv_freq_mask
257
+
258
+ self.register_buffer("inv_freq", inv_freq, persistent=False)
259
+ self.mscale = float(_yarn_get_mscale(self.scale) * self.attn_factor) # Get n-d magnitude scaling corrected for interpolation
260
+
261
+
262
+ # Newly Added For YARN
263
+ class MistralDynamicYaRNScaledRotaryEmbedding(torch.nn.Module):
264
+ """MistralRotaryEmbedding extended with Dynamic YaRN. See: https://arxiv.org/abs/2309.00071"""
265
+ def __init__(
266
+ self,
267
+ dim,
268
+ max_position_embeddings=2048,
269
+ base=10000,
270
+ original_max_position_embeddings=2048,
271
+ extrapolation_factor=1,
272
+ attn_factor=1,
273
+ beta_fast=128,
274
+ beta_slow=2,
275
+ finetuned=False,
276
+ device=None
277
+ ):
278
+ super().__init__()
279
+
280
+ self.dim = dim
281
+ self.max_position_embeddings = max_position_embeddings
282
+ self.base = base
283
+ self.original_max_position_embeddings = original_max_position_embeddings
284
+ self.extrapolation_factor = extrapolation_factor
285
+ self.attn_factor = attn_factor
286
+ self.beta_fast = beta_fast
287
+ self.beta_slow = beta_slow
288
+
289
+ if finetuned:
290
+ self.yarn(self.max_position_embeddings / self.original_max_position_embeddings, device)
291
+ else:
292
+ inv_freq = 1.0 / (base ** (torch.arange(0, dim, 2).float().to(device) / dim))
293
+ self.register_buffer("inv_freq", inv_freq, persistent=False)
294
+ self.mscale = 1
295
+
296
+ # Build here to make `torch.jit.trace` work.
297
+ self.max_seq_len_cached = max_position_embeddings
298
+ t = torch.arange(self.max_seq_len_cached, device=self.inv_freq.device, dtype=torch.float32)
299
+ freqs = torch.einsum("i,j->ij", t, self.inv_freq)
300
+ # Different from paper, but it uses a different permutation in order to obtain the same calculation
301
+ emb = torch.cat((freqs, freqs), dim=-1)
302
+ dtype = torch.get_default_dtype()
303
+
304
+ self.register_buffer("cos_cached", (emb.cos() * self.mscale).to(dtype), persistent=False)
305
+ self.register_buffer("sin_cached", (emb.sin() * self.mscale).to(dtype), persistent=False)
306
+
307
+ def forward(self, x, seq_len=None):
308
+ # x: [bs, num_attention_heads, seq_len, head_size]
309
+ # This `if` block is unlikely to be run after we build sin/cos in `__init__`. Keep the logic here just in case.
310
+ if seq_len > self.max_seq_len_cached:
311
+ self.max_seq_len_cached = seq_len
312
+
313
+ self.yarn(seq_len / self.max_position_embeddings, x.device)
314
+
315
+ t = torch.arange(self.max_seq_len_cached, device=x.device, dtype=self.inv_freq.dtype)
316
+ freqs = torch.einsum("i,j->ij", t, self.inv_freq)
317
+ # Different from paper, but it uses a different permutation in order to obtain the same calculation
318
+ emb = torch.cat((freqs, freqs), dim=-1).to(x.device)
319
+
320
+ self.register_buffer("cos_cached", (emb.cos() * self.mscale).to(x.dtype), persistent=False)
321
+ self.register_buffer("sin_cached", (emb.sin() * self.mscale).to(x.dtype), persistent=False)
322
+ return (
323
+ self.cos_cached[:seq_len].to(dtype=x.dtype),
324
+ self.sin_cached[:seq_len].to(dtype=x.dtype),
325
+ )
326
+
327
+ def yarn(self, scale, device):
328
+ pos_freqs = self.base ** (torch.arange(0, self.dim, 2).float().to(device) / self.dim)
329
+ inv_freq_extrapolation = 1.0 / pos_freqs
330
+ inv_freq_interpolation = 1.0 / (scale * pos_freqs)
331
+
332
+ low, high = _yarn_find_correction_range(self.beta_fast, self.beta_slow, self.dim, self.base, self.original_max_position_embeddings)
333
+ inv_freq_mask = (1 - _yarn_linear_ramp_mask(low, high, self.dim // 2).float().to(device)) * self.extrapolation_factor # Get n-d rotational scaling corrected for extrapolation
334
+ inv_freq = inv_freq_interpolation * (1 - inv_freq_mask) + inv_freq_extrapolation * inv_freq_mask
335
+
336
+ self.register_buffer("inv_freq", inv_freq, persistent=False)
337
+ self.mscale = float(_yarn_get_mscale(scale) * self.attn_factor) # Get n-d magnitude scaling corrected for interpolation
338
+
339
+
340
+
341
+ # Copied from transformers.models.llama.modeling_llama.rotate_half
342
+ def rotate_half(x):
343
+ """Rotates half the hidden dims of the input."""
344
+ x1 = x[..., : x.shape[-1] // 2]
345
+ x2 = x[..., x.shape[-1] // 2 :]
346
+ return torch.cat((-x2, x1), dim=-1)
347
+
348
+
349
+ # copied from transformers.models.llama.modeling_llama.apply_rotary_pos_emb
350
+ # TODO @Arthur no longer copied from LLama after static cache
351
+ def apply_rotary_pos_emb(q, k, cos, sin, position_ids, unsqueeze_dim=1):
352
+ """Applies Rotary Position Embedding to the query and key tensors.
353
+
354
+ Args:
355
+ q (`torch.Tensor`): The query tensor.
356
+ k (`torch.Tensor`): The key tensor.
357
+ cos (`torch.Tensor`): The cosine part of the rotary embedding.
358
+ sin (`torch.Tensor`): The sine part of the rotary embedding.
359
+ position_ids (`torch.Tensor`):
360
+ The position indices of the tokens corresponding to the query and key tensors. For example, this can be
361
+ used to pass offsetted position ids when working with a KV-cache.
362
+ unsqueeze_dim (`int`, *optional*, defaults to 1):
363
+ The 'unsqueeze_dim' argument specifies the dimension along which to unsqueeze cos[position_ids] and
364
+ sin[position_ids] so that they can be properly broadcasted to the dimensions of q and k. For example, note
365
+ that cos[position_ids] and sin[position_ids] have the shape [batch_size, seq_len, head_dim]. Then, if q and
366
+ k have the shape [batch_size, heads, seq_len, head_dim], then setting unsqueeze_dim=1 makes
367
+ cos[position_ids] and sin[position_ids] broadcastable to the shapes of q and k. Similarly, if q and k have
368
+ the shape [batch_size, seq_len, heads, head_dim], then set unsqueeze_dim=2.
369
+ Returns:
370
+ `tuple(torch.Tensor)` comprising of the query and key tensors rotated using the Rotary Position Embedding.
371
+ """
372
+ cos = cos[position_ids].unsqueeze(unsqueeze_dim)
373
+ sin = sin[position_ids].unsqueeze(unsqueeze_dim)
374
+ q_embed = (q * cos) + (rotate_half(q) * sin)
375
+ k_embed = (k * cos) + (rotate_half(k) * sin)
376
+ return q_embed, k_embed
377
+
378
+
379
+ class MistralMLP(nn.Module):
380
+ def __init__(self, config):
381
+ super().__init__()
382
+ self.config = config
383
+ self.hidden_size = config.hidden_size
384
+ self.intermediate_size = config.intermediate_size
385
+ self.gate_proj = nn.Linear(self.hidden_size, self.intermediate_size, bias=False)
386
+ self.up_proj = nn.Linear(self.hidden_size, self.intermediate_size, bias=False)
387
+ self.down_proj = nn.Linear(self.intermediate_size, self.hidden_size, bias=False)
388
+ self.act_fn = ACT2FN[config.hidden_act]
389
+
390
+ def forward(self, x):
391
+ return self.down_proj(self.act_fn(self.gate_proj(x)) * self.up_proj(x))
392
+
393
+
394
+ # Copied from transformers.models.llama.modeling_llama.repeat_kv
395
+ def repeat_kv(hidden_states: torch.Tensor, n_rep: int) -> torch.Tensor:
396
+ """
397
+ This is the equivalent of torch.repeat_interleave(x, dim=1, repeats=n_rep). The hidden states go from (batch,
398
+ num_key_value_heads, seqlen, head_dim) to (batch, num_attention_heads, seqlen, head_dim)
399
+ """
400
+ batch, num_key_value_heads, slen, head_dim = hidden_states.shape
401
+ if n_rep == 1:
402
+ return hidden_states
403
+ hidden_states = hidden_states[:, :, None, :, :].expand(batch, num_key_value_heads, n_rep, slen, head_dim)
404
+ return hidden_states.reshape(batch, num_key_value_heads * n_rep, slen, head_dim)
405
+
406
+
407
+ class MistralAttention(nn.Module):
408
+ """
409
+ Multi-headed attention from 'Attention Is All You Need' paper. Modified to use sliding window attention: Longformer
410
+ and "Generating Long Sequences with Sparse Transformers".
411
+ """
412
+
413
+ def __init__(self, config: MistralConfig, layer_idx: Optional[int] = None):
414
+ super().__init__()
415
+ self.config = config
416
+ self.layer_idx = layer_idx
417
+ if layer_idx is None:
418
+ logger.warning_once(
419
+ f"Instantiating {self.__class__.__name__} without passing a `layer_idx` is not recommended and will "
420
+ "lead to errors during the forward call if caching is used. Please make sure to provide a `layer_idx` "
421
+ "when creating this class."
422
+ )
423
+
424
+ self.hidden_size = config.hidden_size
425
+ self.num_heads = config.num_attention_heads
426
+ self.head_dim = self.hidden_size // self.num_heads
427
+ self.num_key_value_heads = config.num_key_value_heads
428
+ self.num_key_value_groups = self.num_heads // self.num_key_value_heads
429
+ self.max_position_embeddings = config.max_position_embeddings
430
+ self.rope_theta = config.rope_theta
431
+ self.is_causal = True
432
+ self.attention_dropout = config.attention_dropout
433
+
434
+ if (self.head_dim * self.num_heads) != self.hidden_size:
435
+ raise ValueError(
436
+ f"hidden_size must be divisible by num_heads (got `hidden_size`: {self.hidden_size}"
437
+ f" and `num_heads`: {self.num_heads})."
438
+ )
439
+ self.q_proj = nn.Linear(self.hidden_size, self.num_heads * self.head_dim, bias=False)
440
+ self.k_proj = nn.Linear(self.hidden_size, self.num_key_value_heads * self.head_dim, bias=False)
441
+ self.v_proj = nn.Linear(self.hidden_size, self.num_key_value_heads * self.head_dim, bias=False)
442
+ self.o_proj = nn.Linear(self.num_heads * self.head_dim, self.hidden_size, bias=False)
443
+
444
+ # self.rotary_emb = MistralRotaryEmbedding(
445
+ # self.head_dim,
446
+ # max_position_embeddings=self.max_position_embeddings,
447
+ # base=self.rope_theta,
448
+ # )
449
+
450
+ self._init_rope()
451
+
452
+ def _init_rope(self):
453
+ if self.config.rope_scaling is None:
454
+ self.rotary_emb = MistralRotaryEmbedding(self.head_dim, max_position_embeddings=self.max_position_embeddings, base=self.rope_theta)
455
+ else:
456
+ scaling_type = self.config.rope_scaling["type"]
457
+ scaling_factor = self.config.rope_scaling["factor"]
458
+ finetuned = self.config.rope_scaling['finetuned']
459
+ if scaling_type == "linear":
460
+ self.rotary_emb = MistralLinearScalingRotaryEmbedding(
461
+ self.head_dim, max_position_embeddings=self.max_position_embeddings,
462
+ scaling_factor=scaling_factor, base=self.rope_theta,
463
+ )
464
+ elif scaling_type == "dynamic":
465
+ self.rotary_emb = MistralDynamicNTKScalingRotaryEmbedding(
466
+ self.head_dim, max_position_embeddings=self.max_position_embeddings, scaling_factor=scaling_factor,
467
+ base=self.rope_theta,
468
+ )
469
+ elif scaling_type == "yarn":
470
+ original_max_position_embeddings = self.config.rope_scaling["original_max_position_embeddings"]
471
+ self.rotary_emb = MistralYaRNScaledRotaryEmbedding(
472
+ self.head_dim, max_position_embeddings=self.max_position_embeddings, scale=scaling_factor,
473
+ original_max_position_embeddings=original_max_position_embeddings, base=self.rope_theta,
474
+ )
475
+ elif scaling_type == "dynamic-yarn":
476
+ original_max_position_embeddings = self.config.rope_scaling["original_max_position_embeddings"]
477
+ self.rotary_emb = MistralDynamicYaRNScaledRotaryEmbedding(
478
+ self.head_dim, max_position_embeddings=self.max_position_embeddings,
479
+ original_max_position_embeddings=original_max_position_embeddings, base=self.rope_theta, finetuned=finetuned
480
+ )
481
+ else:
482
+ raise ValueError(f"Unknown RoPE scaling type {scaling_type}")
483
+
484
+ def _shape(self, tensor: torch.Tensor, seq_len: int, bsz: int):
485
+ return tensor.view(bsz, seq_len, self.num_heads, self.head_dim).transpose(1, 2).contiguous()
486
+
487
+ def forward(
488
+ self,
489
+ hidden_states: torch.Tensor,
490
+ attention_mask: Optional[torch.Tensor] = None,
491
+ position_ids: Optional[torch.LongTensor] = None,
492
+ past_key_value: Optional[Cache] = None,
493
+ output_attentions: bool = False,
494
+ use_cache: bool = False,
495
+ **kwargs,
496
+ ) -> Tuple[torch.Tensor, Optional[torch.Tensor], Optional[Tuple[torch.Tensor]]]:
497
+
498
+ if "padding_mask" in kwargs:
499
+ warnings.warn(
500
+ "Passing `padding_mask` is deprecated and will be removed in v4.37. Please make sure use `attention_mask` instead.`"
501
+ )
502
+
503
+ bsz, q_len, _ = hidden_states.size()
504
+
505
+ query_states = self.q_proj(hidden_states)
506
+ key_states = self.k_proj(hidden_states)
507
+ value_states = self.v_proj(hidden_states)
508
+
509
+ query_states = query_states.view(bsz, q_len, self.num_heads, self.head_dim).transpose(1, 2)
510
+ key_states = key_states.view(bsz, q_len, self.num_key_value_heads, self.head_dim).transpose(1, 2)
511
+ value_states = value_states.view(bsz, q_len, self.num_key_value_heads, self.head_dim).transpose(1, 2)
512
+
513
+ kv_seq_len = key_states.shape[-2]
514
+ if past_key_value is not None:
515
+ if self.layer_idx is None:
516
+ raise ValueError(
517
+ f"The cache structure has changed since version v4.36. If you are using {self.__class__.__name__} "
518
+ "for auto-regressive decoding with k/v caching, please make sure to initialize the attention class "
519
+ "with a layer index."
520
+ )
521
+ kv_seq_len += past_key_value.get_usable_length(kv_seq_len, self.layer_idx)
522
+
523
+ cos, sin = self.rotary_emb(value_states, seq_len=kv_seq_len)
524
+ query_states, key_states = apply_rotary_pos_emb(query_states, key_states, cos, sin, position_ids)
525
+
526
+ if past_key_value is not None:
527
+ cache_kwargs = {"sin": sin, "cos": cos} # Specific to RoPE models
528
+ key_states, value_states = past_key_value.update(key_states, value_states, self.layer_idx, cache_kwargs)
529
+
530
+ # repeat k/v heads if n_kv_heads < n_heads
531
+ key_states = repeat_kv(key_states, self.num_key_value_groups)
532
+ value_states = repeat_kv(value_states, self.num_key_value_groups)
533
+
534
+ attn_weights = torch.matmul(query_states, key_states.transpose(2, 3)) / math.sqrt(self.head_dim)
535
+
536
+ if attn_weights.size() != (bsz, self.num_heads, q_len, kv_seq_len):
537
+ raise ValueError(
538
+ f"Attention weights should be of size {(bsz, self.num_heads, q_len, kv_seq_len)}, but is"
539
+ f" {attn_weights.size()}"
540
+ )
541
+
542
+ if attention_mask is not None:
543
+ if attention_mask.size() != (bsz, 1, q_len, kv_seq_len):
544
+ raise ValueError(
545
+ f"Attention mask should be of size {(bsz, 1, q_len, kv_seq_len)}, but is {attention_mask.size()}"
546
+ )
547
+
548
+ attn_weights = attn_weights + attention_mask
549
+
550
+ # upcast attention to fp32
551
+ attn_weights = nn.functional.softmax(attn_weights, dim=-1, dtype=torch.float32).to(query_states.dtype)
552
+ attn_weights = nn.functional.dropout(attn_weights, p=self.attention_dropout, training=self.training)
553
+ attn_output = torch.matmul(attn_weights, value_states)
554
+
555
+ if attn_output.size() != (bsz, self.num_heads, q_len, self.head_dim):
556
+ raise ValueError(
557
+ f"`attn_output` should be of size {(bsz, self.num_heads, q_len, self.head_dim)}, but is"
558
+ f" {attn_output.size()}"
559
+ )
560
+
561
+ attn_output = attn_output.transpose(1, 2).contiguous()
562
+ attn_output = attn_output.reshape(bsz, q_len, self.hidden_size)
563
+
564
+ attn_output = self.o_proj(attn_output)
565
+
566
+ if not output_attentions:
567
+ attn_weights = None
568
+
569
+ return attn_output, attn_weights, past_key_value
570
+
571
+
572
+ class MistralFlashAttention2(MistralAttention):
573
+ """
574
+ Mistral flash attention module. This module inherits from `MistralAttention` as the weights of the module stays
575
+ untouched. The only required change would be on the forward pass where it needs to correctly call the public API of
576
+ flash attention and deal with padding tokens in case the input contains any of them.
577
+ """
578
+
579
+ # Copied from transformers.models.llama.modeling_llama.LlamaFlashAttention2.__init__
580
+ def __init__(self, *args, **kwargs):
581
+ super().__init__(*args, **kwargs)
582
+
583
+ # TODO: Should be removed once Flash Attention for RoCm is bumped to 2.1.
584
+ # 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.
585
+ # 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).
586
+ self._flash_attn_uses_top_left_mask = not is_flash_attn_greater_or_equal_2_10()
587
+
588
+ def forward(
589
+ self,
590
+ hidden_states: torch.Tensor,
591
+ attention_mask: Optional[torch.Tensor] = None,
592
+ position_ids: Optional[torch.LongTensor] = None,
593
+ past_key_value: Optional[Cache] = None,
594
+ output_attentions: bool = False,
595
+ use_cache: bool = False,
596
+ **kwargs,
597
+ ):
598
+ if "padding_mask" in kwargs:
599
+ warnings.warn(
600
+ "Passing `padding_mask` is deprecated and will be removed in v4.37. Please make sure to use `attention_mask` instead.`"
601
+ )
602
+
603
+ # overwrite attention_mask with padding_mask
604
+ attention_mask = kwargs.pop("padding_mask")
605
+ bsz, q_len, _ = hidden_states.size()
606
+
607
+ query_states = self.q_proj(hidden_states)
608
+ key_states = self.k_proj(hidden_states)
609
+ value_states = self.v_proj(hidden_states)
610
+
611
+ query_states = query_states.view(bsz, q_len, self.num_heads, self.head_dim).transpose(1, 2)
612
+ key_states = key_states.view(bsz, q_len, self.num_key_value_heads, self.head_dim).transpose(1, 2)
613
+ value_states = value_states.view(bsz, q_len, self.num_key_value_heads, self.head_dim).transpose(1, 2)
614
+
615
+ kv_seq_len = key_states.shape[-2]
616
+ if past_key_value is not None:
617
+ if self.layer_idx is None:
618
+ raise ValueError(
619
+ f"The cache structure has changed since version v4.36. If you are using {self.__class__.__name__} "
620
+ "for auto-regressive decoding with k/v caching, please make sure to initialize the attention class "
621
+ "with a layer index."
622
+ )
623
+ kv_seq_len += past_key_value.get_usable_length(kv_seq_len, self.layer_idx)
624
+
625
+ # Because the input can be padded, the absolute sequence length depends on the max position id.
626
+ rotary_seq_len = max(kv_seq_len, position_ids[:, -1].max().item()) + 1
627
+ cos, sin = self.rotary_emb(value_states, seq_len=rotary_seq_len)
628
+
629
+ query_states, key_states = apply_rotary_pos_emb(query_states, key_states, cos, sin, position_ids)
630
+
631
+ use_sliding_windows = (
632
+ _flash_supports_window_size
633
+ and getattr(self.config, "sliding_window", None) is not None
634
+ and kv_seq_len > self.config.sliding_window
635
+ )
636
+
637
+ if not _flash_supports_window_size:
638
+ logger.warning_once(
639
+ "The current flash attention version does not support sliding window attention, for a more memory efficient implementation"
640
+ " make sure to upgrade flash-attn library."
641
+ )
642
+
643
+ if past_key_value is not None:
644
+ # Activate slicing cache only if the config has a value `sliding_windows` attribute
645
+ cache_has_contents = past_key_value.get_seq_length(self.layer_idx) > 0
646
+ if (
647
+ getattr(self.config, "sliding_window", None) is not None
648
+ and kv_seq_len > self.config.sliding_window
649
+ and cache_has_contents
650
+ ):
651
+ slicing_tokens = 1 - self.config.sliding_window
652
+
653
+ past_key = past_key_value[self.layer_idx][0]
654
+ past_value = past_key_value[self.layer_idx][1]
655
+
656
+ past_key = past_key[:, :, slicing_tokens:, :].contiguous()
657
+ past_value = past_value[:, :, slicing_tokens:, :].contiguous()
658
+
659
+ if past_key.shape[-2] != self.config.sliding_window - 1:
660
+ raise ValueError(
661
+ f"past key must have a shape of (`batch_size, num_heads, self.config.sliding_window-1, head_dim`), got"
662
+ f" {past_key.shape}"
663
+ )
664
+
665
+ if attention_mask is not None:
666
+ attention_mask = attention_mask[:, slicing_tokens:]
667
+ attention_mask = torch.cat([attention_mask, torch.ones_like(attention_mask[:, -1:])], dim=-1)
668
+
669
+ cache_kwargs = {"sin": sin, "cos": cos} # Specific to RoPE models
670
+ key_states, value_states = past_key_value.update(key_states, value_states, self.layer_idx, cache_kwargs)
671
+
672
+ # repeat k/v heads if n_kv_heads < n_heads
673
+ key_states = repeat_kv(key_states, self.num_key_value_groups)
674
+ value_states = repeat_kv(value_states, self.num_key_value_groups)
675
+ dropout_rate = 0.0 if not self.training else self.attention_dropout
676
+
677
+ # In PEFT, usually we cast the layer norms in float32 for training stability reasons
678
+ # therefore the input hidden states gets silently casted in float32. Hence, we need
679
+ # cast them back in float16 just to be sure everything works as expected.
680
+ input_dtype = query_states.dtype
681
+ if input_dtype == torch.float32:
682
+ if torch.is_autocast_enabled():
683
+ target_dtype = torch.get_autocast_gpu_dtype()
684
+ # Handle the case where the model is quantized
685
+ elif hasattr(self.config, "_pre_quantization_dtype"):
686
+ target_dtype = self.config._pre_quantization_dtype
687
+ else:
688
+ target_dtype = self.q_proj.weight.dtype
689
+
690
+ logger.warning_once(
691
+ f"The input hidden states seems to be silently casted in float32, this might be related to"
692
+ f" the fact you have upcasted embedding or layer norm layers in float32. We will cast back the input in"
693
+ f" {target_dtype}."
694
+ )
695
+
696
+ query_states = query_states.to(target_dtype)
697
+ key_states = key_states.to(target_dtype)
698
+ value_states = value_states.to(target_dtype)
699
+
700
+ # Reashape to the expected shape for Flash Attention
701
+ query_states = query_states.transpose(1, 2)
702
+ key_states = key_states.transpose(1, 2)
703
+ value_states = value_states.transpose(1, 2)
704
+
705
+ attn_output = self._flash_attention_forward(
706
+ query_states,
707
+ key_states,
708
+ value_states,
709
+ attention_mask,
710
+ q_len,
711
+ dropout=dropout_rate,
712
+ use_sliding_windows=use_sliding_windows,
713
+ )
714
+
715
+ attn_output = attn_output.reshape(bsz, q_len, self.hidden_size).contiguous()
716
+ attn_output = self.o_proj(attn_output)
717
+
718
+ if not output_attentions:
719
+ attn_weights = None
720
+
721
+ return attn_output, attn_weights, past_key_value
722
+
723
+ def _flash_attention_forward(
724
+ self,
725
+ query_states,
726
+ key_states,
727
+ value_states,
728
+ attention_mask,
729
+ query_length,
730
+ dropout=0.0,
731
+ softmax_scale=None,
732
+ use_sliding_windows=False,
733
+ ):
734
+ """
735
+ Calls the forward method of Flash Attention - if the input hidden states contain at least one padding token
736
+ first unpad the input, then computes the attention scores and pad the final attention scores.
737
+
738
+ Args:
739
+ query_states (`torch.Tensor`):
740
+ Input query states to be passed to Flash Attention API
741
+ key_states (`torch.Tensor`):
742
+ Input key states to be passed to Flash Attention API
743
+ value_states (`torch.Tensor`):
744
+ Input value states to be passed to Flash Attention API
745
+ attention_mask (`torch.Tensor`):
746
+ The padding mask - corresponds to a tensor of size `(batch_size, seq_len)` where 0 stands for the
747
+ position of padding tokens and 1 for the position of non-padding tokens.
748
+ dropout (`int`, *optional*):
749
+ Attention dropout
750
+ softmax_scale (`float`, *optional*):
751
+ The scaling of QK^T before applying softmax. Default to 1 / sqrt(head_dim)
752
+ use_sliding_windows (`bool`, *optional*):
753
+ Whether to activate sliding window attention.
754
+ """
755
+ if not self._flash_attn_uses_top_left_mask:
756
+ causal = self.is_causal
757
+ else:
758
+ # 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__.
759
+ causal = self.is_causal and query_length != 1
760
+
761
+ # Contains at least one padding token in the sequence
762
+ if attention_mask is not None:
763
+ batch_size = query_states.shape[0]
764
+ query_states, key_states, value_states, indices_q, cu_seq_lens, max_seq_lens = self._upad_input(
765
+ query_states, key_states, value_states, attention_mask, query_length
766
+ )
767
+
768
+ cu_seqlens_q, cu_seqlens_k = cu_seq_lens
769
+ max_seqlen_in_batch_q, max_seqlen_in_batch_k = max_seq_lens
770
+
771
+ if not use_sliding_windows:
772
+ attn_output_unpad = flash_attn_varlen_func(
773
+ query_states,
774
+ key_states,
775
+ value_states,
776
+ cu_seqlens_q=cu_seqlens_q,
777
+ cu_seqlens_k=cu_seqlens_k,
778
+ max_seqlen_q=max_seqlen_in_batch_q,
779
+ max_seqlen_k=max_seqlen_in_batch_k,
780
+ dropout_p=dropout,
781
+ softmax_scale=softmax_scale,
782
+ causal=causal,
783
+ )
784
+ else:
785
+ attn_output_unpad = flash_attn_varlen_func(
786
+ query_states,
787
+ key_states,
788
+ value_states,
789
+ cu_seqlens_q=cu_seqlens_q,
790
+ cu_seqlens_k=cu_seqlens_k,
791
+ max_seqlen_q=max_seqlen_in_batch_q,
792
+ max_seqlen_k=max_seqlen_in_batch_k,
793
+ dropout_p=dropout,
794
+ softmax_scale=softmax_scale,
795
+ causal=causal,
796
+ window_size=(self.config.sliding_window, self.config.sliding_window),
797
+ )
798
+
799
+ attn_output = pad_input(attn_output_unpad, indices_q, batch_size, query_length)
800
+ else:
801
+ if not use_sliding_windows:
802
+ attn_output = flash_attn_func(
803
+ query_states,
804
+ key_states,
805
+ value_states,
806
+ dropout,
807
+ softmax_scale=softmax_scale,
808
+ causal=causal,
809
+ )
810
+ else:
811
+ attn_output = flash_attn_func(
812
+ query_states,
813
+ key_states,
814
+ value_states,
815
+ dropout,
816
+ softmax_scale=softmax_scale,
817
+ causal=causal,
818
+ window_size=(self.config.sliding_window, self.config.sliding_window),
819
+ )
820
+
821
+ return attn_output
822
+
823
+ def _upad_input(self, query_layer, key_layer, value_layer, attention_mask, query_length):
824
+ batch_size, kv_seq_len, num_heads, head_dim = key_layer.shape
825
+
826
+ # On the first iteration we need to properly re-create the padding mask
827
+ # by slicing it on the proper place
828
+ if kv_seq_len != attention_mask.shape[-1]:
829
+ attention_mask_num_tokens = attention_mask.shape[-1]
830
+ attention_mask = attention_mask[:, attention_mask_num_tokens - kv_seq_len :]
831
+
832
+ indices_k, cu_seqlens_k, max_seqlen_in_batch_k = _get_unpad_data(attention_mask)
833
+
834
+ key_layer = index_first_axis(key_layer.reshape(batch_size * kv_seq_len, num_heads, head_dim), indices_k)
835
+ value_layer = index_first_axis(value_layer.reshape(batch_size * kv_seq_len, num_heads, head_dim), indices_k)
836
+
837
+ if query_length == kv_seq_len:
838
+ query_layer = index_first_axis(
839
+ query_layer.reshape(batch_size * kv_seq_len, num_heads, head_dim), indices_k
840
+ )
841
+ cu_seqlens_q = cu_seqlens_k
842
+ max_seqlen_in_batch_q = max_seqlen_in_batch_k
843
+ indices_q = indices_k
844
+ elif query_length == 1:
845
+ max_seqlen_in_batch_q = 1
846
+ cu_seqlens_q = torch.arange(
847
+ batch_size + 1, dtype=torch.int32, device=query_layer.device
848
+ ) # There is a memcpy here, that is very bad.
849
+ indices_q = cu_seqlens_q[:-1]
850
+ query_layer = query_layer.squeeze(1)
851
+ else:
852
+ # The -q_len: slice assumes left padding.
853
+ attention_mask = attention_mask[:, -query_length:]
854
+ query_layer, indices_q, cu_seqlens_q, max_seqlen_in_batch_q = unpad_input(query_layer, attention_mask)
855
+
856
+ return (
857
+ query_layer,
858
+ key_layer,
859
+ value_layer,
860
+ indices_q,
861
+ (cu_seqlens_q, cu_seqlens_k),
862
+ (max_seqlen_in_batch_q, max_seqlen_in_batch_k),
863
+ )
864
+
865
+
866
+ # copied from transformers.models.llama.modeling_llama.LlamaSdpaAttention with Llama->Mistral
867
+ # TODO @Arthur no longer copied from LLama after static cache
868
+ class MistralSdpaAttention(MistralAttention):
869
+ """
870
+ Mistral attention module using torch.nn.functional.scaled_dot_product_attention. This module inherits from
871
+ `MistralAttention` as the weights of the module stays untouched. The only changes are on the forward pass to adapt to
872
+ SDPA API.
873
+ """
874
+
875
+ # Adapted from MistralAttention.forward
876
+ def forward(
877
+ self,
878
+ hidden_states: torch.Tensor,
879
+ attention_mask: Optional[torch.Tensor] = None,
880
+ position_ids: Optional[torch.LongTensor] = None,
881
+ past_key_value: Optional[Cache] = None,
882
+ output_attentions: bool = False,
883
+ use_cache: bool = False,
884
+ ) -> Tuple[torch.Tensor, Optional[torch.Tensor], Optional[Tuple[torch.Tensor]]]:
885
+ if output_attentions:
886
+ # TODO: Improve this warning with e.g. `model.config.attn_implementation = "manual"` once this is implemented.
887
+ logger.warning_once(
888
+ "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, "
889
+ '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.'
890
+ )
891
+ return super().forward(
892
+ hidden_states=hidden_states,
893
+ attention_mask=attention_mask,
894
+ position_ids=position_ids,
895
+ past_key_value=past_key_value,
896
+ output_attentions=output_attentions,
897
+ use_cache=use_cache,
898
+ )
899
+
900
+ bsz, q_len, _ = hidden_states.size()
901
+
902
+ query_states = self.q_proj(hidden_states)
903
+ key_states = self.k_proj(hidden_states)
904
+ value_states = self.v_proj(hidden_states)
905
+
906
+ query_states = query_states.view(bsz, q_len, self.num_heads, self.head_dim).transpose(1, 2)
907
+ key_states = key_states.view(bsz, q_len, self.num_key_value_heads, self.head_dim).transpose(1, 2)
908
+ value_states = value_states.view(bsz, q_len, self.num_key_value_heads, self.head_dim).transpose(1, 2)
909
+
910
+ kv_seq_len = key_states.shape[-2]
911
+ if past_key_value is not None:
912
+ kv_seq_len += past_key_value.get_usable_length(kv_seq_len, self.layer_idx)
913
+ cos, sin = self.rotary_emb(value_states, seq_len=kv_seq_len)
914
+
915
+ query_states, key_states = apply_rotary_pos_emb(query_states, key_states, cos, sin, position_ids)
916
+
917
+ if past_key_value is not None:
918
+ cache_kwargs = {"sin": sin, "cos": cos} # Specific to RoPE models
919
+ key_states, value_states = past_key_value.update(key_states, value_states, self.layer_idx, cache_kwargs)
920
+
921
+ key_states = repeat_kv(key_states, self.num_key_value_groups)
922
+ value_states = repeat_kv(value_states, self.num_key_value_groups)
923
+
924
+ if attention_mask is not None:
925
+ if attention_mask.size() != (bsz, 1, q_len, kv_seq_len):
926
+ raise ValueError(
927
+ f"Attention mask should be of size {(bsz, 1, q_len, kv_seq_len)}, but is {attention_mask.size()}"
928
+ )
929
+
930
+ # SDPA with memory-efficient backend is currently (torch==2.1.2) bugged with non-contiguous inputs with custom attn_mask,
931
+ # Reference: https://github.com/pytorch/pytorch/issues/112577.
932
+ if query_states.device.type == "cuda" and attention_mask is not None:
933
+ query_states = query_states.contiguous()
934
+ key_states = key_states.contiguous()
935
+ value_states = value_states.contiguous()
936
+
937
+ attn_output = torch.nn.functional.scaled_dot_product_attention(
938
+ query_states,
939
+ key_states,
940
+ value_states,
941
+ attn_mask=attention_mask,
942
+ dropout_p=self.attention_dropout if self.training else 0.0,
943
+ # 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.
944
+ is_causal=self.is_causal and attention_mask is None and q_len > 1,
945
+ )
946
+
947
+ attn_output = attn_output.transpose(1, 2).contiguous()
948
+ attn_output = attn_output.view(bsz, q_len, self.hidden_size)
949
+
950
+ attn_output = self.o_proj(attn_output)
951
+
952
+ return attn_output, None, past_key_value
953
+
954
+
955
+ MISTRAL_ATTENTION_CLASSES = {
956
+ "eager": MistralAttention,
957
+ "flash_attention_2": MistralFlashAttention2,
958
+ "sdpa": MistralSdpaAttention,
959
+ }
960
+
961
+
962
+ class MistralDecoderLayer(nn.Module):
963
+ def __init__(self, config: MistralConfig, layer_idx: int):
964
+ super().__init__()
965
+ self.hidden_size = config.hidden_size
966
+
967
+ if config._attn_implementation:
968
+ self.self_attn = MISTRAL_ATTENTION_CLASSES[config._attn_implementation](config, layer_idx)
969
+ else:
970
+ self.self_attn = MISTRAL_ATTENTION_CLASSES['flash_attention_2'](config, layer_idx)
971
+
972
+ self.mlp = MistralMLP(config)
973
+ self.input_layernorm = MistralRMSNorm(config.hidden_size, eps=config.rms_norm_eps)
974
+ self.post_attention_layernorm = MistralRMSNorm(config.hidden_size, eps=config.rms_norm_eps)
975
+
976
+ def forward(
977
+ self,
978
+ hidden_states: torch.Tensor,
979
+ attention_mask: Optional[torch.Tensor] = None,
980
+ position_ids: Optional[torch.LongTensor] = None,
981
+ past_key_value: Optional[Tuple[torch.Tensor]] = None,
982
+ output_attentions: Optional[bool] = False,
983
+ use_cache: Optional[bool] = False,
984
+ **kwargs,
985
+ ) -> Tuple[torch.FloatTensor, Optional[Tuple[torch.FloatTensor, torch.FloatTensor]]]:
986
+ if "padding_mask" in kwargs:
987
+ warnings.warn(
988
+ "Passing `padding_mask` is deprecated and will be removed in v4.37. Please make sure use `attention_mask` instead.`"
989
+ )
990
+ """
991
+ Args:
992
+ hidden_states (`torch.FloatTensor`): input to the layer of shape `(batch, seq_len, embed_dim)`
993
+ attention_mask (`torch.FloatTensor`, *optional*): attention mask of size
994
+ `(batch, sequence_length)` where padding elements are indicated by 0.
995
+ output_attentions (`bool`, *optional*):
996
+ Whether or not to return the attentions tensors of all attention layers. See `attentions` under
997
+ returned tensors for more detail.
998
+ use_cache (`bool`, *optional*):
999
+ If set to `True`, `past_key_values` key value states are returned and can be used to speed up decoding
1000
+ (see `past_key_values`).
1001
+ past_key_value (`Tuple(torch.FloatTensor)`, *optional*): cached past key and value projection states
1002
+ """
1003
+
1004
+ residual = hidden_states
1005
+
1006
+ hidden_states = self.input_layernorm(hidden_states)
1007
+
1008
+ # Self Attention
1009
+ hidden_states, self_attn_weights, present_key_value = self.self_attn(
1010
+ hidden_states=hidden_states,
1011
+ attention_mask=attention_mask,
1012
+ position_ids=position_ids,
1013
+ past_key_value=past_key_value,
1014
+ output_attentions=output_attentions,
1015
+ use_cache=use_cache,
1016
+ )
1017
+ hidden_states = residual + hidden_states
1018
+
1019
+ # Fully Connected
1020
+ residual = hidden_states
1021
+ hidden_states = self.post_attention_layernorm(hidden_states)
1022
+ hidden_states = self.mlp(hidden_states)
1023
+ hidden_states = residual + hidden_states
1024
+
1025
+ outputs = (hidden_states,)
1026
+
1027
+ if output_attentions:
1028
+ outputs += (self_attn_weights,)
1029
+
1030
+ if use_cache:
1031
+ outputs += (present_key_value,)
1032
+
1033
+ return outputs
1034
+
1035
+
1036
+ MISTRAL_START_DOCSTRING = r"""
1037
+ This model inherits from [`PreTrainedModel`]. Check the superclass documentation for the generic methods the
1038
+ library implements for all its model (such as downloading or saving, resizing the input embeddings, pruning heads
1039
+ etc.)
1040
+
1041
+ This model is also a PyTorch [torch.nn.Module](https://pytorch.org/docs/stable/nn.html#torch.nn.Module) subclass.
1042
+ Use it as a regular PyTorch Module and refer to the PyTorch documentation for all matter related to general usage
1043
+ and behavior.
1044
+
1045
+ Parameters:
1046
+ config ([`MistralConfig`]):
1047
+ Model configuration class with all the parameters of the model. Initializing with a config file does not
1048
+ load the weights associated with the model, only the configuration. Check out the
1049
+ [`~PreTrainedModel.from_pretrained`] method to load the model weights.
1050
+ """
1051
+
1052
+
1053
+ @add_start_docstrings(
1054
+ "The bare Mistral Model outputting raw hidden-states without any specific head on top.",
1055
+ MISTRAL_START_DOCSTRING,
1056
+ )
1057
+ class MistralPreTrainedModel(PreTrainedModel):
1058
+ config_class = MistralConfig
1059
+ base_model_prefix = "model"
1060
+ supports_gradient_checkpointing = True
1061
+ _no_split_modules = ["MistralDecoderLayer"]
1062
+ _skip_keys_device_placement = "past_key_values"
1063
+ _supports_flash_attn_2 = True
1064
+ _supports_sdpa = True
1065
+ _supports_cache_class = True
1066
+
1067
+ def _init_weights(self, module):
1068
+ std = self.config.initializer_range
1069
+ if isinstance(module, nn.Linear):
1070
+ module.weight.data.normal_(mean=0.0, std=std)
1071
+ if module.bias is not None:
1072
+ module.bias.data.zero_()
1073
+ elif isinstance(module, nn.Embedding):
1074
+ module.weight.data.normal_(mean=0.0, std=std)
1075
+ if module.padding_idx is not None:
1076
+ module.weight.data[module.padding_idx].zero_()
1077
+
1078
+
1079
+ MISTRAL_INPUTS_DOCSTRING = r"""
1080
+ Args:
1081
+ input_ids (`torch.LongTensor` of shape `(batch_size, sequence_length)`):
1082
+ Indices of input sequence tokens in the vocabulary. Padding will be ignored by default should you provide
1083
+ it.
1084
+
1085
+ Indices can be obtained using [`AutoTokenizer`]. See [`PreTrainedTokenizer.encode`] and
1086
+ [`PreTrainedTokenizer.__call__`] for details.
1087
+
1088
+ [What are input IDs?](../glossary#input-ids)
1089
+ attention_mask (`torch.Tensor` of shape `(batch_size, sequence_length)`, *optional*):
1090
+ Mask to avoid performing attention on padding token indices. Mask values selected in `[0, 1]`:
1091
+
1092
+ - 1 for tokens that are **not masked**,
1093
+ - 0 for tokens that are **masked**.
1094
+
1095
+ [What are attention masks?](../glossary#attention-mask)
1096
+
1097
+ Indices can be obtained using [`AutoTokenizer`]. See [`PreTrainedTokenizer.encode`] and
1098
+ [`PreTrainedTokenizer.__call__`] for details.
1099
+
1100
+ If `past_key_values` is used, optionally only the last `decoder_input_ids` have to be input (see
1101
+ `past_key_values`).
1102
+
1103
+ If you want to change padding behavior, you should read [`modeling_opt._prepare_decoder_attention_mask`]
1104
+ and modify to your needs. See diagram 1 in [the paper](https://arxiv.org/abs/1910.13461) for more
1105
+ information on the default strategy.
1106
+
1107
+ - 1 indicates the head is **not masked**,
1108
+ - 0 indicates the head is **masked**.
1109
+ position_ids (`torch.LongTensor` of shape `(batch_size, sequence_length)`, *optional*):
1110
+ Indices of positions of each input sequence tokens in the position embeddings. Selected in the range `[0,
1111
+ config.n_positions - 1]`.
1112
+
1113
+ [What are position IDs?](../glossary#position-ids)
1114
+ past_key_values (`Cache` or `tuple(tuple(torch.FloatTensor))`, *optional*):
1115
+ Pre-computed hidden-states (key and values in the self-attention blocks and in the cross-attention
1116
+ blocks) that can be used to speed up sequential decoding. This typically consists in the `past_key_values`
1117
+ returned by the model at a previous stage of decoding, when `use_cache=True` or `config.use_cache=True`.
1118
+
1119
+ Two formats are allowed:
1120
+ - a [`~cache_utils.Cache`] instance;
1121
+ - Tuple of `tuple(torch.FloatTensor)` of length `config.n_layers`, with each tuple having 2 tensors of
1122
+ shape `(batch_size, num_heads, sequence_length, embed_size_per_head)`). This is also known as the legacy
1123
+ cache format.
1124
+
1125
+ The model will output the same cache format that is fed as input. If no `past_key_values` are passed, the
1126
+ legacy cache format will be returned.
1127
+
1128
+ If `past_key_values` are used, the user can optionally input only the last `input_ids` (those that don't
1129
+ have their past key value states given to this model) of shape `(batch_size, 1)` instead of all `input_ids`
1130
+ of shape `(batch_size, sequence_length)`.
1131
+ inputs_embeds (`torch.FloatTensor` of shape `(batch_size, sequence_length, hidden_size)`, *optional*):
1132
+ Optionally, instead of passing `input_ids` you can choose to directly pass an embedded representation. This
1133
+ is useful if you want more control over how to convert `input_ids` indices into associated vectors than the
1134
+ model's internal embedding lookup matrix.
1135
+ use_cache (`bool`, *optional*):
1136
+ If set to `True`, `past_key_values` key value states are returned and can be used to speed up decoding (see
1137
+ `past_key_values`).
1138
+ output_attentions (`bool`, *optional*):
1139
+ Whether or not to return the attentions tensors of all attention layers. See `attentions` under returned
1140
+ tensors for more detail.
1141
+ output_hidden_states (`bool`, *optional*):
1142
+ Whether or not to return the hidden states of all layers. See `hidden_states` under returned tensors for
1143
+ more detail.
1144
+ return_dict (`bool`, *optional*):
1145
+ Whether or not to return a [`~utils.ModelOutput`] instead of a plain tuple.
1146
+ """
1147
+
1148
+
1149
+ @add_start_docstrings(
1150
+ "The bare Mistral Model outputting raw hidden-states without any specific head on top.",
1151
+ MISTRAL_START_DOCSTRING,
1152
+ )
1153
+ class MistralModel(MistralPreTrainedModel):
1154
+ """
1155
+ Transformer decoder consisting of *config.num_hidden_layers* layers. Each layer is a [`MistralDecoderLayer`]
1156
+
1157
+ Args:
1158
+ config: MistralConfig
1159
+ """
1160
+
1161
+ def __init__(self, config: MistralConfig):
1162
+ super().__init__(config)
1163
+ self.padding_idx = config.pad_token_id
1164
+ self.vocab_size = config.vocab_size
1165
+
1166
+ self.embed_tokens = nn.Embedding(config.vocab_size, config.hidden_size, self.padding_idx)
1167
+ self.layers = nn.ModuleList(
1168
+ [MistralDecoderLayer(config, layer_idx) for layer_idx in range(config.num_hidden_layers)]
1169
+ )
1170
+ self._attn_implementation = config._attn_implementation
1171
+ self.norm = MistralRMSNorm(config.hidden_size, eps=config.rms_norm_eps)
1172
+
1173
+ self.gradient_checkpointing = False
1174
+ # Initialize weights and apply final processing
1175
+ self.post_init()
1176
+
1177
+ def get_input_embeddings(self):
1178
+ return self.embed_tokens
1179
+
1180
+ def set_input_embeddings(self, value):
1181
+ self.embed_tokens = value
1182
+
1183
+ @add_start_docstrings_to_model_forward(MISTRAL_INPUTS_DOCSTRING)
1184
+ def forward(
1185
+ self,
1186
+ input_ids: torch.LongTensor = None,
1187
+ attention_mask: Optional[torch.Tensor] = None,
1188
+ position_ids: Optional[torch.LongTensor] = None,
1189
+ past_key_values: Optional[List[torch.FloatTensor]] = None,
1190
+ inputs_embeds: Optional[torch.FloatTensor] = None,
1191
+ use_cache: Optional[bool] = None,
1192
+ output_attentions: Optional[bool] = None,
1193
+ output_hidden_states: Optional[bool] = None,
1194
+ return_dict: Optional[bool] = None,
1195
+ ) -> Union[Tuple, BaseModelOutputWithPast]:
1196
+ output_attentions = output_attentions if output_attentions is not None else self.config.output_attentions
1197
+ output_hidden_states = (
1198
+ output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states
1199
+ )
1200
+ use_cache = use_cache if use_cache is not None else self.config.use_cache
1201
+
1202
+ return_dict = return_dict if return_dict is not None else self.config.use_return_dict
1203
+
1204
+ # retrieve input_ids and inputs_embeds
1205
+ if input_ids is not None and inputs_embeds is not None:
1206
+ raise ValueError("You cannot specify both decoder_input_ids and decoder_inputs_embeds at the same time")
1207
+ elif input_ids is not None:
1208
+ batch_size, seq_length = input_ids.shape
1209
+ elif inputs_embeds is not None:
1210
+ batch_size, seq_length, _ = inputs_embeds.shape
1211
+ else:
1212
+ raise ValueError("You have to specify either decoder_input_ids or decoder_inputs_embeds")
1213
+
1214
+ if self.gradient_checkpointing and self.training:
1215
+ if use_cache:
1216
+ logger.warning_once(
1217
+ "`use_cache=True` is incompatible with gradient checkpointing. Setting `use_cache=False`..."
1218
+ )
1219
+ use_cache = False
1220
+
1221
+ past_key_values_length = 0
1222
+
1223
+ if use_cache:
1224
+ use_legacy_cache = not isinstance(past_key_values, Cache)
1225
+ if use_legacy_cache:
1226
+ past_key_values = DynamicCache.from_legacy_cache(past_key_values)
1227
+ past_key_values_length = past_key_values.get_usable_length(seq_length)
1228
+
1229
+ if position_ids is None:
1230
+ device = input_ids.device if input_ids is not None else inputs_embeds.device
1231
+ position_ids = torch.arange(
1232
+ past_key_values_length, seq_length + past_key_values_length, dtype=torch.long, device=device
1233
+ )
1234
+ position_ids = position_ids.unsqueeze(0).view(-1, seq_length)
1235
+ else:
1236
+ position_ids = position_ids.view(-1, seq_length).long()
1237
+
1238
+ if inputs_embeds is None:
1239
+ inputs_embeds = self.embed_tokens(input_ids)
1240
+
1241
+ if attention_mask is not None and self._attn_implementation == "flash_attention_2" and use_cache:
1242
+ is_padding_right = attention_mask[:, -1].sum().item() != batch_size
1243
+ if is_padding_right:
1244
+ raise ValueError(
1245
+ "You are attempting to perform batched generation with padding_side='right'"
1246
+ " this may lead to unexpected behaviour for Flash Attention version of Mistral. Make sure to "
1247
+ " call `tokenizer.padding_side = 'left'` before tokenizing the input. "
1248
+ )
1249
+
1250
+ if self._attn_implementation == "flash_attention_2":
1251
+ # 2d mask is passed through the layers
1252
+ attention_mask = attention_mask if (attention_mask is not None and 0 in attention_mask) else None
1253
+ elif self._attn_implementation == "sdpa" and not output_attentions:
1254
+ # output_attentions=True can not be supported when using SDPA, and we fall back on
1255
+ # the manual implementation that requires a 4D causal mask in all cases.
1256
+ attention_mask = _prepare_4d_causal_attention_mask_for_sdpa(
1257
+ attention_mask,
1258
+ (batch_size, seq_length),
1259
+ inputs_embeds,
1260
+ past_key_values_length,
1261
+ )
1262
+ else:
1263
+ # 4d mask is passed through the layers
1264
+ attention_mask = _prepare_4d_causal_attention_mask(
1265
+ attention_mask,
1266
+ (batch_size, seq_length),
1267
+ inputs_embeds,
1268
+ past_key_values_length,
1269
+ sliding_window=self.config.sliding_window,
1270
+ )
1271
+
1272
+ hidden_states = inputs_embeds
1273
+
1274
+ # decoder layers
1275
+ all_hidden_states = () if output_hidden_states else None
1276
+ all_self_attns = () if output_attentions else None
1277
+ next_decoder_cache = None
1278
+
1279
+ for decoder_layer in self.layers:
1280
+ if output_hidden_states:
1281
+ all_hidden_states += (hidden_states,)
1282
+
1283
+ if self.gradient_checkpointing and self.training:
1284
+ layer_outputs = self._gradient_checkpointing_func(
1285
+ decoder_layer.__call__,
1286
+ hidden_states,
1287
+ attention_mask,
1288
+ position_ids,
1289
+ past_key_values,
1290
+ output_attentions,
1291
+ use_cache,
1292
+ )
1293
+ else:
1294
+ layer_outputs = decoder_layer(
1295
+ hidden_states,
1296
+ attention_mask=attention_mask,
1297
+ position_ids=position_ids,
1298
+ past_key_value=past_key_values,
1299
+ output_attentions=output_attentions,
1300
+ use_cache=use_cache,
1301
+ )
1302
+
1303
+ hidden_states = layer_outputs[0]
1304
+
1305
+ if use_cache:
1306
+ next_decoder_cache = layer_outputs[2 if output_attentions else 1]
1307
+
1308
+ if output_attentions:
1309
+ all_self_attns += (layer_outputs[1],)
1310
+
1311
+ hidden_states = self.norm(hidden_states)
1312
+
1313
+ # add hidden states from the last decoder layer
1314
+ if output_hidden_states:
1315
+ all_hidden_states += (hidden_states,)
1316
+
1317
+ next_cache = None
1318
+ if use_cache:
1319
+ next_cache = next_decoder_cache.to_legacy_cache() if use_legacy_cache else next_decoder_cache
1320
+
1321
+ if not return_dict:
1322
+ return tuple(v for v in [hidden_states, next_cache, all_hidden_states, all_self_attns] if v is not None)
1323
+ return BaseModelOutputWithPast(
1324
+ last_hidden_state=hidden_states,
1325
+ past_key_values=next_cache,
1326
+ hidden_states=all_hidden_states,
1327
+ attentions=all_self_attns,
1328
+ )
1329
+
1330
+
1331
+ class MistralForCausalLM(MistralPreTrainedModel):
1332
+ _tied_weights_keys = ["lm_head.weight"]
1333
+
1334
+ def __init__(self, config):
1335
+ super().__init__(config)
1336
+ self.model = MistralModel(config)
1337
+ self.vocab_size = config.vocab_size
1338
+ self.lm_head = nn.Linear(config.hidden_size, config.vocab_size, bias=False)
1339
+
1340
+ # Initialize weights and apply final processing
1341
+ self.post_init()
1342
+
1343
+ def get_input_embeddings(self):
1344
+ return self.model.embed_tokens
1345
+
1346
+ def set_input_embeddings(self, value):
1347
+ self.model.embed_tokens = value
1348
+
1349
+ def get_output_embeddings(self):
1350
+ return self.lm_head
1351
+
1352
+ def set_output_embeddings(self, new_embeddings):
1353
+ self.lm_head = new_embeddings
1354
+
1355
+ def set_decoder(self, decoder):
1356
+ self.model = decoder
1357
+
1358
+ def get_decoder(self):
1359
+ return self.model
1360
+
1361
+ @add_start_docstrings_to_model_forward(MISTRAL_INPUTS_DOCSTRING)
1362
+ @replace_return_docstrings(output_type=CausalLMOutputWithPast, config_class=_CONFIG_FOR_DOC)
1363
+ def forward(
1364
+ self,
1365
+ input_ids: torch.LongTensor = None,
1366
+ attention_mask: Optional[torch.Tensor] = None,
1367
+ position_ids: Optional[torch.LongTensor] = None,
1368
+ past_key_values: Optional[List[torch.FloatTensor]] = None,
1369
+ inputs_embeds: Optional[torch.FloatTensor] = None,
1370
+ labels: Optional[torch.LongTensor] = None,
1371
+ use_cache: Optional[bool] = None,
1372
+ output_attentions: Optional[bool] = None,
1373
+ output_hidden_states: Optional[bool] = None,
1374
+ return_dict: Optional[bool] = None,
1375
+ ) -> Union[Tuple, CausalLMOutputWithPast]:
1376
+ r"""
1377
+ Args:
1378
+ labels (`torch.LongTensor` of shape `(batch_size, sequence_length)`, *optional*):
1379
+ Labels for computing the masked language modeling loss. Indices should either be in `[0, ...,
1380
+ config.vocab_size]` or -100 (see `input_ids` docstring). Tokens with indices set to `-100` are ignored
1381
+ (masked), the loss is only computed for the tokens with labels in `[0, ..., config.vocab_size]`.
1382
+
1383
+ Returns:
1384
+
1385
+ Example:
1386
+
1387
+ ```python
1388
+ >>> from transformers import AutoTokenizer, MistralForCausalLM
1389
+
1390
+ >>> model = MistralForCausalLM.from_pretrained("mistralai/Mistral-7B-v0.1")
1391
+ >>> tokenizer = AutoTokenizer.from_pretrained("mistralai/Mistral-7B-v0.1")
1392
+
1393
+ >>> prompt = "Hey, are you conscious? Can you talk to me?"
1394
+ >>> inputs = tokenizer(prompt, return_tensors="pt")
1395
+
1396
+ >>> # Generate
1397
+ >>> generate_ids = model.generate(inputs.input_ids, max_length=30)
1398
+ >>> tokenizer.batch_decode(generate_ids, skip_special_tokens=True, clean_up_tokenization_spaces=False)[0]
1399
+ "Hey, are you conscious? Can you talk to me?\nI'm not conscious, but I can talk to you."
1400
+ ```"""
1401
+
1402
+ output_attentions = output_attentions if output_attentions is not None else self.config.output_attentions
1403
+ output_hidden_states = (
1404
+ output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states
1405
+ )
1406
+ return_dict = return_dict if return_dict is not None else self.config.use_return_dict
1407
+
1408
+ # decoder outputs consists of (dec_features, layer_state, dec_hidden, dec_attn)
1409
+ outputs = self.model(
1410
+ input_ids=input_ids,
1411
+ attention_mask=attention_mask,
1412
+ position_ids=position_ids,
1413
+ past_key_values=past_key_values,
1414
+ inputs_embeds=inputs_embeds,
1415
+ use_cache=use_cache,
1416
+ output_attentions=output_attentions,
1417
+ output_hidden_states=output_hidden_states,
1418
+ return_dict=return_dict,
1419
+ )
1420
+
1421
+ hidden_states = outputs[0]
1422
+ logits = self.lm_head(hidden_states)
1423
+ logits = logits.float()
1424
+
1425
+ loss = None
1426
+ if labels is not None:
1427
+ # Shift so that tokens < n predict n
1428
+ shift_logits = logits[..., :-1, :].contiguous()
1429
+ shift_labels = labels[..., 1:].contiguous()
1430
+ # Flatten the tokens
1431
+ shift_logits = shift_logits.view(-1, self.config.vocab_size)
1432
+ shift_labels = shift_labels.view(-1)
1433
+ # Ensure tensors are on the same device
1434
+ shift_labels = shift_labels.to(shift_logits.device)
1435
+ loss_fct = CrossEntropyLoss()
1436
+ loss = loss_fct(shift_logits, shift_labels)
1437
+
1438
+ if not return_dict:
1439
+ output = (logits,) + outputs[1:]
1440
+ return (loss,) + output if loss is not None else output
1441
+
1442
+ return CausalLMOutputWithPast(
1443
+ loss=loss,
1444
+ logits=logits,
1445
+ past_key_values=outputs.past_key_values,
1446
+ hidden_states=outputs.hidden_states,
1447
+ attentions=outputs.attentions,
1448
+ )
1449
+
1450
+ def prepare_inputs_for_generation(
1451
+ self, input_ids, past_key_values=None, attention_mask=None, inputs_embeds=None, **kwargs
1452
+ ):
1453
+ # Omit tokens covered by past_key_values
1454
+ if past_key_values is not None:
1455
+ if isinstance(past_key_values, Cache):
1456
+ cache_length = past_key_values.get_seq_length()
1457
+ past_length = past_key_values.seen_tokens
1458
+ max_cache_length = past_key_values.get_max_length()
1459
+ else:
1460
+ cache_length = past_length = past_key_values[0][0].shape[2]
1461
+ max_cache_length = None
1462
+
1463
+ # Keep only the unprocessed tokens:
1464
+ # 1 - If the length of the attention_mask exceeds the length of input_ids, then we are in a setting where
1465
+ # some of the inputs are exclusively passed as part of the cache (e.g. when passing input_embeds as
1466
+ # input)
1467
+ if attention_mask is not None and attention_mask.shape[1] > input_ids.shape[1]:
1468
+ input_ids = input_ids[:, -(attention_mask.shape[1] - past_length) :]
1469
+ # 2 - If the past_length is smaller than input_ids', then input_ids holds all input tokens. We can discard
1470
+ # input_ids based on the past_length.
1471
+ elif past_length < input_ids.shape[1]:
1472
+ input_ids = input_ids[:, past_length:]
1473
+ # 3 - Otherwise (past_length >= input_ids.shape[1]), let's assume input_ids only has unprocessed tokens.
1474
+
1475
+ # If we are about to go beyond the maximum cache length, we need to crop the input attention mask.
1476
+ if (
1477
+ max_cache_length is not None
1478
+ and attention_mask is not None
1479
+ and cache_length + input_ids.shape[1] > max_cache_length
1480
+ ):
1481
+ attention_mask = attention_mask[:, -max_cache_length:]
1482
+
1483
+ position_ids = kwargs.get("position_ids", None)
1484
+ if attention_mask is not None and position_ids is None:
1485
+ # create position_ids on the fly for batch generation
1486
+ position_ids = attention_mask.long().cumsum(-1) - 1
1487
+ position_ids.masked_fill_(attention_mask == 0, 1)
1488
+ if past_key_values:
1489
+ position_ids = position_ids[:, -input_ids.shape[1] :]
1490
+
1491
+ # if `inputs_embeds` are passed, we only want to use them in the 1st generation step
1492
+ if inputs_embeds is not None and past_key_values is None:
1493
+ model_inputs = {"inputs_embeds": inputs_embeds}
1494
+ else:
1495
+ model_inputs = {"input_ids": input_ids}
1496
+
1497
+ model_inputs.update(
1498
+ {
1499
+ "position_ids": position_ids,
1500
+ "past_key_values": past_key_values,
1501
+ "use_cache": kwargs.get("use_cache"),
1502
+ "attention_mask": attention_mask,
1503
+ }
1504
+ )
1505
+ return model_inputs
1506
+
1507
+ @staticmethod
1508
+ def _reorder_cache(past_key_values, beam_idx):
1509
+ reordered_past = ()
1510
+ for layer_past in past_key_values:
1511
+ reordered_past += (
1512
+ tuple(past_state.index_select(0, beam_idx.to(past_state.device)) for past_state in layer_past),
1513
+ )
1514
+ return reordered_past
1515
+
1516
+
1517
+ @add_start_docstrings(
1518
+ """
1519
+ The Mistral Model transformer with a sequence classification head on top (linear layer).
1520
+
1521
+ [`MistralForSequenceClassification`] uses the last token in order to do the classification, as other causal models
1522
+ (e.g. GPT-2) do.
1523
+
1524
+ Since it does classification on the last token, it requires to know the position of the last token. If a
1525
+ `pad_token_id` is defined in the configuration, it finds the last token that is not a padding token in each row. If
1526
+ no `pad_token_id` is defined, it simply takes the last value in each row of the batch. Since it cannot guess the
1527
+ padding tokens when `inputs_embeds` are passed instead of `input_ids`, it does the same (take the last value in
1528
+ each row of the batch).
1529
+ """,
1530
+ MISTRAL_START_DOCSTRING,
1531
+ )
1532
+ # Copied from transformers.models.llama.modeling_llama.LlamaForSequenceClassification with Llama->Mistral, LLAMA->MISTRAL
1533
+ class MistralForSequenceClassification(MistralPreTrainedModel):
1534
+ def __init__(self, config):
1535
+ super().__init__(config)
1536
+ self.num_labels = config.num_labels
1537
+ self.model = MistralModel(config)
1538
+ self.score = nn.Linear(config.hidden_size, self.num_labels, bias=False)
1539
+
1540
+ # Initialize weights and apply final processing
1541
+ self.post_init()
1542
+
1543
+ def get_input_embeddings(self):
1544
+ return self.model.embed_tokens
1545
+
1546
+ def set_input_embeddings(self, value):
1547
+ self.model.embed_tokens = value
1548
+
1549
+ @add_start_docstrings_to_model_forward(MISTRAL_INPUTS_DOCSTRING)
1550
+ def forward(
1551
+ self,
1552
+ input_ids: torch.LongTensor = None,
1553
+ attention_mask: Optional[torch.Tensor] = None,
1554
+ position_ids: Optional[torch.LongTensor] = None,
1555
+ past_key_values: Optional[List[torch.FloatTensor]] = None,
1556
+ inputs_embeds: Optional[torch.FloatTensor] = None,
1557
+ labels: Optional[torch.LongTensor] = None,
1558
+ use_cache: Optional[bool] = None,
1559
+ output_attentions: Optional[bool] = None,
1560
+ output_hidden_states: Optional[bool] = None,
1561
+ return_dict: Optional[bool] = None,
1562
+ ) -> Union[Tuple, SequenceClassifierOutputWithPast]:
1563
+ r"""
1564
+ labels (`torch.LongTensor` of shape `(batch_size,)`, *optional*):
1565
+ Labels for computing the sequence classification/regression loss. Indices should be in `[0, ...,
1566
+ config.num_labels - 1]`. If `config.num_labels == 1` a regression loss is computed (Mean-Square loss), If
1567
+ `config.num_labels > 1` a classification loss is computed (Cross-Entropy).
1568
+ """
1569
+ return_dict = return_dict if return_dict is not None else self.config.use_return_dict
1570
+
1571
+ transformer_outputs = self.model(
1572
+ input_ids,
1573
+ attention_mask=attention_mask,
1574
+ position_ids=position_ids,
1575
+ past_key_values=past_key_values,
1576
+ inputs_embeds=inputs_embeds,
1577
+ use_cache=use_cache,
1578
+ output_attentions=output_attentions,
1579
+ output_hidden_states=output_hidden_states,
1580
+ return_dict=return_dict,
1581
+ )
1582
+ hidden_states = transformer_outputs[0]
1583
+ logits = self.score(hidden_states)
1584
+
1585
+ if input_ids is not None:
1586
+ batch_size = input_ids.shape[0]
1587
+ else:
1588
+ batch_size = inputs_embeds.shape[0]
1589
+
1590
+ if self.config.pad_token_id is None and batch_size != 1:
1591
+ raise ValueError("Cannot handle batch sizes > 1 if no padding token is defined.")
1592
+ if self.config.pad_token_id is None:
1593
+ sequence_lengths = -1
1594
+ else:
1595
+ if input_ids is not None:
1596
+ # if no pad token found, use modulo instead of reverse indexing for ONNX compatibility
1597
+ sequence_lengths = torch.eq(input_ids, self.config.pad_token_id).int().argmax(-1) - 1
1598
+ sequence_lengths = sequence_lengths % input_ids.shape[-1]
1599
+ sequence_lengths = sequence_lengths.to(logits.device)
1600
+ else:
1601
+ sequence_lengths = -1
1602
+
1603
+ pooled_logits = logits[torch.arange(batch_size, device=logits.device), sequence_lengths]
1604
+
1605
+ loss = None
1606
+ if labels is not None:
1607
+ labels = labels.to(logits.device)
1608
+ if self.config.problem_type is None:
1609
+ if self.num_labels == 1:
1610
+ self.config.problem_type = "regression"
1611
+ elif self.num_labels > 1 and (labels.dtype == torch.long or labels.dtype == torch.int):
1612
+ self.config.problem_type = "single_label_classification"
1613
+ else:
1614
+ self.config.problem_type = "multi_label_classification"
1615
+
1616
+ if self.config.problem_type == "regression":
1617
+ loss_fct = MSELoss()
1618
+ if self.num_labels == 1:
1619
+ loss = loss_fct(pooled_logits.squeeze(), labels.squeeze())
1620
+ else:
1621
+ loss = loss_fct(pooled_logits, labels)
1622
+ elif self.config.problem_type == "single_label_classification":
1623
+ loss_fct = CrossEntropyLoss()
1624
+ loss = loss_fct(pooled_logits.view(-1, self.num_labels), labels.view(-1))
1625
+ elif self.config.problem_type == "multi_label_classification":
1626
+ loss_fct = BCEWithLogitsLoss()
1627
+ loss = loss_fct(pooled_logits, labels)
1628
+ if not return_dict:
1629
+ output = (pooled_logits,) + transformer_outputs[1:]
1630
+ return ((loss,) + output) if loss is not None else output
1631
+
1632
+ return SequenceClassifierOutputWithPast(
1633
+ loss=loss,
1634
+ logits=pooled_logits,
1635
+ past_key_values=transformer_outputs.past_key_values,
1636
+ hidden_states=transformer_outputs.hidden_states,
1637
+ attentions=transformer_outputs.attentions,
1638
+ )
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": "</s>",
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.json ADDED
The diff for this file is too large to render. See raw diff
 
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,44 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "add_bos_token": true,
3
+ "add_eos_token": false,
4
+ "added_tokens_decoder": {
5
+ "0": {
6
+ "content": "<unk>",
7
+ "lstrip": false,
8
+ "normalized": false,
9
+ "rstrip": false,
10
+ "single_word": false,
11
+ "special": true
12
+ },
13
+ "1": {
14
+ "content": "<s>",
15
+ "lstrip": false,
16
+ "normalized": false,
17
+ "rstrip": false,
18
+ "single_word": false,
19
+ "special": true
20
+ },
21
+ "2": {
22
+ "content": "</s>",
23
+ "lstrip": false,
24
+ "normalized": false,
25
+ "rstrip": false,
26
+ "single_word": false,
27
+ "special": true
28
+ }
29
+ },
30
+ "additional_special_tokens": [],
31
+ "bos_token": "<s>",
32
+ "chat_template": "{{ bos_token }}{% for message in messages %}{% if (message['role'] == 'user') != (loop.index0 % 2 == 0) %}{{ raise_exception('Conversation roles must alternate user/assistant/user/assistant/...') }}{% endif %}{% if message['role'] == 'user' %}{{ '[INST] ' + message['content'] + ' [/INST]' }}{% elif message['role'] == 'assistant' %}{{ message['content'] + eos_token}}{% else %}{{ raise_exception('Only user and assistant roles are supported!') }}{% endif %}{% endfor %}",
33
+ "clean_up_tokenization_spaces": false,
34
+ "eos_token": "</s>",
35
+ "legacy": true,
36
+ "model_max_length": 131072,
37
+ "pad_token": "</s>",
38
+ "padding_side": "right",
39
+ "sp_model_kwargs": {},
40
+ "spaces_between_special_tokens": false,
41
+ "tokenizer_class": "LlamaTokenizer",
42
+ "unk_token": "<unk>",
43
+ "use_default_system_prompt": false
44
+ }