Guanzheng commited on
Commit
47de81f
1 Parent(s): e8a9549

Upload 3 files

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