Goekdeniz-Guelmez commited on
Commit
231c747
·
verified ·
1 Parent(s): d246698

Upload 10 files

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