chienweichang commited on
Commit
babec87
1 Parent(s): bdc2642

Upload folder using huggingface_hub

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