theblackcat102 commited on
Commit
2c6056f
1 Parent(s): 95583b8

Upload 2 files

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