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