HyperAccel commited on
Commit
6f6cc97
·
verified ·
1 Parent(s): 7d053b5

Upload tiny-random minimax_m1 model

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