zhihan1996 commited on
Commit
3b35654
·
verified ·
1 Parent(s): 6ba2d64

Upload 10 files

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