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