ToastyPigeon commited on
Commit
2a7a6c6
·
verified ·
1 Parent(s): 7c03ed2

Upload folder using huggingface_hub

Browse files
config.json ADDED
@@ -0,0 +1,53 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "architectures": [
3
+ "ScatterbrainMoonlightForCausalLM"
4
+ ],
5
+ "attention_bias": false,
6
+ "attention_dropout": 0.0,
7
+ "auto_map": {
8
+ "AutoConfig": "configuration_scatterbrain_moonlight.ScatterbrainMoonlightConfig",
9
+ "AutoModel": "modeling_scatterbrain_moonlight.ScatterbrainMoonlightModel",
10
+ "AutoModelForCausalLM": "modeling_scatterbrain_moonlight.ScatterbrainMoonlightForCausalLM"
11
+ },
12
+ "aux_loss_alpha": 0.001,
13
+ "bos_token_id": 163584,
14
+ "eos_token_id": 163585,
15
+ "ep_size": 1,
16
+ "first_k_dense_replace": 1,
17
+ "hidden_act": "silu",
18
+ "hidden_size": 2048,
19
+ "initializer_range": 0.02,
20
+ "intermediate_size": 11264,
21
+ "kv_lora_rank": 512,
22
+ "max_position_embeddings": 8192,
23
+ "model_type": "scatterbrain_moonlight",
24
+ "moe_intermediate_size": 1408,
25
+ "moe_layer_freq": 1,
26
+ "n_group": 1,
27
+ "n_routed_experts": 64,
28
+ "n_shared_experts": 2,
29
+ "norm_topk_prob": true,
30
+ "num_attention_heads": 16,
31
+ "num_experts_per_tok": 6,
32
+ "num_hidden_layers": 3,
33
+ "num_loop_iterations": 25,
34
+ "num_key_value_heads": 16,
35
+ "num_nextn_predict_layers": 0,
36
+ "pretraining_tp": 1,
37
+ "q_lora_rank": null,
38
+ "qk_nope_head_dim": 128,
39
+ "qk_rope_head_dim": 64,
40
+ "rms_norm_eps": 1e-05,
41
+ "rope_theta": 50000.0,
42
+ "routed_scaling_factor": 2.446,
43
+ "scoring_func": "sigmoid",
44
+ "seq_aux": true,
45
+ "tie_word_embeddings": false,
46
+ "topk_group": 1,
47
+ "topk_method": "noaux_tc",
48
+ "torch_dtype": "bfloat16",
49
+ "transformers_version": "4.46.3",
50
+ "use_cache": true,
51
+ "v_head_dim": 128,
52
+ "vocab_size": 163840
53
+ }
configuration_scatterbrain_moonlight.py ADDED
@@ -0,0 +1,214 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Configuration for scatterbrain-moonlight
2
+ # Based on DeepseekV3Config with layer looping support
3
+
4
+ from transformers.configuration_utils import PretrainedConfig
5
+ from transformers.utils import logging
6
+
7
+ logger = logging.get_logger(__name__)
8
+
9
+ class ScatterbrainMoonlightConfig(PretrainedConfig):
10
+ r"""
11
+ This is the configuration class to store the configuration of a [`DeepseekV3Model`]. It is used to instantiate an DeepSeek
12
+ model according to the specified arguments, defining the model architecture. Instantiating a configuration with the
13
+ defaults will yield a similar configuration to that of the DeepSeek-V3.
14
+
15
+ Configuration objects inherit from [`PretrainedConfig`] and can be used to control the model outputs. Read the
16
+ documentation from [`PretrainedConfig`] for more information.
17
+
18
+
19
+ Args:
20
+ vocab_size (`int`, *optional*, defaults to 129280):
21
+ Vocabulary size of the Deep model. Defines the number of different tokens that can be represented by the
22
+ `inputs_ids` passed when calling [`DeepseekV3Model`]
23
+ hidden_size (`int`, *optional*, defaults to 4096):
24
+ Dimension of the hidden representations.
25
+ intermediate_size (`int`, *optional*, defaults to 11008):
26
+ Dimension of the MLP representations.
27
+ moe_intermediate_size (`int`, *optional*, defaults to 1407):
28
+ Dimension of the MoE representations.
29
+ num_hidden_layers (`int`, *optional*, defaults to 32):
30
+ Number of hidden layers in the Transformer decoder.
31
+ num_nextn_predict_layers (`int`, *optional*, defaults to 1):
32
+ Number of nextn predict layers in the DeepSeekV3 Model.
33
+ num_attention_heads (`int`, *optional*, defaults to 32):
34
+ Number of attention heads for each attention layer in the Transformer decoder.
35
+ n_shared_experts (`int`, *optional*, defaults to None):
36
+ Number of shared experts, None means dense model.
37
+ n_routed_experts (`int`, *optional*, defaults to None):
38
+ Number of routed experts, None means dense model.
39
+ routed_scaling_factor (`float`, *optional*, defaults to 1.0):
40
+ Scaling factor or routed experts.
41
+ topk_method (`str`, *optional*, defaults to `gready`):
42
+ Topk method used in routed gate.
43
+ n_group (`int`, *optional*, defaults to None):
44
+ Number of groups for routed experts.
45
+ topk_group (`int`, *optional*, defaults to None):
46
+ Number of selected groups for each token(for each token, ensuring the selected experts is only within `topk_group` groups).
47
+ num_experts_per_tok (`int`, *optional*, defaults to None):
48
+ Number of selected experts, None means dense model.
49
+ moe_layer_freq (`int`, *optional*, defaults to 1):
50
+ The frequency of the MoE layer: one expert layer for every `moe_layer_freq - 1` dense layers.
51
+ first_k_dense_replace (`int`, *optional*, defaults to 0):
52
+ Number of dense layers in shallow layers(embed->dense->dense->...->dense->moe->moe...->lm_head).
53
+ \--k dense layers--/
54
+ norm_topk_prob (`bool`, *optional*, defaults to False):
55
+ Whether to normalize the weights of the routed experts.
56
+ scoring_func (`str`, *optional*, defaults to 'softmax'):
57
+ Method of computing expert weights.
58
+ aux_loss_alpha (`float`, *optional*, defaults to 0.001):
59
+ Auxiliary loss weight coefficient.
60
+ seq_aux = (`bool`, *optional*, defaults to True):
61
+ Whether to compute the auxiliary loss for each individual sample.
62
+ num_key_value_heads (`int`, *optional*):
63
+ This is the number of key_value heads that should be used to implement Grouped Query Attention. If
64
+ `num_key_value_heads=num_attention_heads`, the model will use Multi Head Attention (MHA), if
65
+ `num_key_value_heads=1 the model will use Multi Query Attention (MQA) otherwise GQA is used. When
66
+ converting a multi-head checkpoint to a GQA checkpoint, each group key and value head should be constructed
67
+ by meanpooling all the original heads within that group. For more details checkout [this
68
+ paper](https://arxiv.org/pdf/2305.13245.pdf). If it is not specified, will default to
69
+ `num_attention_heads`.
70
+ hidden_act (`str` or `function`, *optional*, defaults to `"silu"`):
71
+ The non-linear activation function (function or string) in the decoder.
72
+ max_position_embeddings (`int`, *optional*, defaults to 2048):
73
+ The maximum sequence length that this model might ever be used with.
74
+ initializer_range (`float`, *optional*, defaults to 0.02):
75
+ The standard deviation of the truncated_normal_initializer for initializing all weight matrices.
76
+ rms_norm_eps (`float`, *optional*, defaults to 1e-06):
77
+ The epsilon used by the rms normalization layers.
78
+ use_cache (`bool`, *optional*, defaults to `True`):
79
+ Whether or not the model should return the last key/values attentions (not used by all models). Only
80
+ relevant if `config.is_decoder=True`.
81
+ pad_token_id (`int`, *optional*):
82
+ Padding token id.
83
+ bos_token_id (`int`, *optional*, defaults to 1):
84
+ Beginning of stream token id.
85
+ eos_token_id (`int`, *optional*, defaults to 2):
86
+ End of stream token id.
87
+ pretraining_tp (`int`, *optional*, defaults to 1):
88
+ Experimental feature. Tensor parallelism rank used during pretraining. Please refer to [this
89
+ document](https://huggingface.co/docs/transformers/parallelism) to understand more about it. This value is
90
+ necessary to ensure exact reproducibility of the pretraining results. Please refer to [this
91
+ issue](https://github.com/pytorch/pytorch/issues/76232).
92
+ tie_word_embeddings (`bool`, *optional*, defaults to `False`):
93
+ Whether to tie weight embeddings
94
+ rope_theta (`float`, *optional*, defaults to 10000.0):
95
+ The base period of the RoPE embeddings.
96
+ rope_scaling (`Dict`, *optional*):
97
+ Dictionary containing the scaling configuration for the RoPE embeddings. Currently supports two scaling
98
+ strategies: linear and dynamic. Their scaling factor must be a float greater than 1. The expected format is
99
+ `{"type": strategy name, "factor": scaling factor}`. When using this flag, don't update
100
+ `max_position_embeddings` to the expected new maximum.
101
+ attention_bias (`bool`, defaults to `False`, *optional*, defaults to `False`):
102
+ Whether to use a bias in the query, key, value and output projection layers during self-attention.
103
+ attention_dropout (`float`, *optional*, defaults to 0.0):
104
+ The dropout ratio for the attention probabilities.
105
+
106
+ ```python
107
+ >>> from transformers import DeepseekV3Model, DeepseekV3Config
108
+
109
+ >>> # Initializing a Deepseek-V3 style configuration
110
+ >>> configuration = DeepseekV3Config()
111
+
112
+ >>> # Accessing the model configuration
113
+ >>> configuration = model.config
114
+ ```"""
115
+
116
+ model_type = "scatterbrain_moonlight"
117
+ keys_to_ignore_at_inference = ["past_key_values"]
118
+
119
+ def __init__(
120
+ self,
121
+ vocab_size=163840,
122
+ hidden_size=2048,
123
+ intermediate_size=11264,
124
+ moe_intermediate_size=1408,
125
+ num_hidden_layers=3,
126
+ num_loop_iterations=25, # Number of times to loop the middle layer (layer 1)
127
+ num_nextn_predict_layers=0,
128
+ num_attention_heads=16,
129
+ num_key_value_heads=16,
130
+ n_shared_experts=2,
131
+ n_routed_experts=64,
132
+ ep_size=1,
133
+ routed_scaling_factor=2.446,
134
+ kv_lora_rank=512,
135
+ q_lora_rank=None,
136
+ qk_rope_head_dim=64,
137
+ v_head_dim=128,
138
+ qk_nope_head_dim=128,
139
+ topk_method='noaux_tc',
140
+ n_group=1,
141
+ topk_group=1,
142
+ num_experts_per_tok=6,
143
+ moe_layer_freq=1,
144
+ first_k_dense_replace=1,
145
+ norm_topk_prob=True,
146
+ scoring_func='sigmoid',
147
+ aux_loss_alpha=0.001,
148
+ seq_aux=True,
149
+ hidden_act="silu",
150
+ max_position_embeddings=8192,
151
+ initializer_range=0.02,
152
+ rms_norm_eps=1e-5,
153
+ use_cache=True,
154
+ pad_token_id=None,
155
+ bos_token_id=163584,
156
+ eos_token_id=163585,
157
+ pretraining_tp=1,
158
+ tie_word_embeddings=False,
159
+ rope_theta=50000.0,
160
+ rope_scaling=None,
161
+ attention_bias=False,
162
+ attention_dropout=0.0,
163
+ **kwargs,
164
+ ):
165
+ self.vocab_size = vocab_size
166
+ self.max_position_embeddings = max_position_embeddings
167
+ self.hidden_size = hidden_size
168
+ self.intermediate_size = intermediate_size
169
+ self.moe_intermediate_size = moe_intermediate_size
170
+ self.num_hidden_layers = num_hidden_layers
171
+ self.num_loop_iterations = num_loop_iterations
172
+ self.num_nextn_predict_layers = num_nextn_predict_layers
173
+ self.num_attention_heads = num_attention_heads
174
+ self.n_shared_experts = n_shared_experts
175
+ self.n_routed_experts = n_routed_experts
176
+ self.ep_size = ep_size
177
+ self.routed_scaling_factor = routed_scaling_factor
178
+ self.kv_lora_rank = kv_lora_rank
179
+ self.q_lora_rank = q_lora_rank
180
+ self.qk_rope_head_dim = qk_rope_head_dim
181
+ self.v_head_dim = v_head_dim
182
+ self.qk_nope_head_dim = qk_nope_head_dim
183
+ self.topk_method = topk_method
184
+ self.n_group = n_group
185
+ self.topk_group = topk_group
186
+ self.num_experts_per_tok = num_experts_per_tok
187
+ self.moe_layer_freq = moe_layer_freq
188
+ self.first_k_dense_replace = first_k_dense_replace
189
+ self.norm_topk_prob = norm_topk_prob
190
+ self.scoring_func = scoring_func
191
+ self.aux_loss_alpha = aux_loss_alpha
192
+ self.seq_aux = seq_aux
193
+ # for backward compatibility
194
+ if num_key_value_heads is None:
195
+ num_key_value_heads = num_attention_heads
196
+
197
+ self.num_key_value_heads = num_key_value_heads
198
+ self.hidden_act = hidden_act
199
+ self.initializer_range = initializer_range
200
+ self.rms_norm_eps = rms_norm_eps
201
+ self.pretraining_tp = pretraining_tp
202
+ self.use_cache = use_cache
203
+ self.rope_theta = rope_theta
204
+ self.rope_scaling = rope_scaling
205
+ self.attention_bias = attention_bias
206
+ self.attention_dropout = attention_dropout
207
+
208
+ super().__init__(
209
+ pad_token_id=pad_token_id,
210
+ bos_token_id=bos_token_id,
211
+ eos_token_id=eos_token_id,
212
+ tie_word_embeddings=tie_word_embeddings,
213
+ **kwargs,
214
+ )
generation_config.json ADDED
@@ -0,0 +1,6 @@
 
 
 
 
 
 
 
1
+ {
2
+ "max_length": 8192,
3
+ "eos_token_id": [
4
+ 163585
5
+ ]
6
+ }
model.safetensors ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:c268f600656b9e2ac7e2952374937b4b3946451eb2d93b167eff52063e172238
3
+ size 3847525272
modeling_scatterbrain_moonlight.py ADDED
@@ -0,0 +1,1627 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # coding=utf-8
2
+ # Copy from https://huggingface.co/deepseek-ai/DeepSeek-V3/blob/main/modeling_deepseek.py
3
+ # Modified to use ScatterMoE for optimized expert computation
4
+ # Copyright 2023 DeepSeek-AI and The HuggingFace Inc. team. All rights reserved.
5
+ #
6
+ # Licensed under the Apache License, Version 2.0 (the "License");
7
+ # you may not use this file except in compliance with the License.
8
+ # You may obtain a copy of the License at
9
+ #
10
+ # http://www.apache.org/licenses/LICENSE-2.0
11
+ #
12
+ # Unless required by applicable law or agreed to in writing, software
13
+ # distributed under the License is distributed on an "AS IS" BASIS,
14
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
15
+ # See the License for the specific language governing permissions and
16
+ # limitations under the License.
17
+ """ PyTorch DeepSeek model with ScatterMoE optimization."""
18
+ import math
19
+ import warnings
20
+ from typing import Any, Dict, List, Optional, Tuple, Union
21
+
22
+ import torch
23
+ import torch.nn.functional as F
24
+ import torch.utils.checkpoint
25
+ from torch import nn
26
+ from torch.nn import BCEWithLogitsLoss, CrossEntropyLoss, MSELoss
27
+
28
+ from transformers.activations import ACT2FN
29
+ from transformers.cache_utils import Cache, DynamicCache
30
+ from transformers.modeling_attn_mask_utils import (
31
+ AttentionMaskConverter,
32
+ _prepare_4d_attention_mask,
33
+ _prepare_4d_causal_attention_mask,
34
+ )
35
+ from transformers.modeling_outputs import (
36
+ BaseModelOutputWithPast,
37
+ CausalLMOutputWithPast,
38
+ SequenceClassifierOutputWithPast,
39
+ )
40
+ from transformers.modeling_utils import PreTrainedModel
41
+ from transformers.pytorch_utils import (
42
+ ALL_LAYERNORM_LAYERS,
43
+ is_torch_greater_or_equal_than_1_13,
44
+ )
45
+ from transformers.utils import (
46
+ add_start_docstrings,
47
+ add_start_docstrings_to_model_forward,
48
+ is_flash_attn_2_available,
49
+ is_flash_attn_greater_or_equal_2_10,
50
+ logging,
51
+ replace_return_docstrings,
52
+ )
53
+ from transformers.utils.import_utils import is_torch_fx_available
54
+ from .configuration_scatterbrain_moonlight import ScatterbrainMoonlightConfig
55
+ import torch.distributed as dist
56
+ import numpy as np
57
+
58
+ # Import ScatterMoE
59
+ try:
60
+ from scattermoe import flatten_sort_count, parallel_linear
61
+ SCATTERMOE_AVAILABLE = True
62
+ except ImportError:
63
+ SCATTERMOE_AVAILABLE = False
64
+ warnings.warn("ScatterMoE not available. Install with: pip install scattermoe")
65
+
66
+ if is_flash_attn_2_available():
67
+ from flash_attn import flash_attn_func, flash_attn_varlen_func
68
+ from flash_attn.bert_padding import index_first_axis, pad_input, unpad_input # noqa
69
+
70
+
71
+ # This makes `_prepare_4d_causal_attention_mask` a leaf function in the FX graph.
72
+ if is_torch_fx_available():
73
+ if not is_torch_greater_or_equal_than_1_13:
74
+ import torch.fx
75
+
76
+ _prepare_4d_causal_attention_mask = torch.fx.wrap(_prepare_4d_causal_attention_mask)
77
+
78
+
79
+ logger = logging.get_logger(__name__)
80
+
81
+ _CONFIG_FOR_DOC = "ScatterbrainMoonlightConfig"
82
+
83
+
84
+ def _get_cache_length(cache, seq_length, layer_idx=None):
85
+ """Helper to get cache length, compatible with both old and new transformers API."""
86
+ if hasattr(cache, 'get_usable_length'):
87
+ if layer_idx is not None:
88
+ return cache.get_usable_length(seq_length, layer_idx)
89
+ return cache.get_usable_length(seq_length)
90
+ elif hasattr(cache, 'get_seq_length'):
91
+ if layer_idx is not None:
92
+ return cache.get_seq_length(layer_idx)
93
+ return cache.get_seq_length()
94
+ return 0
95
+
96
+
97
+ class ExpandedDynamicCache(Cache):
98
+ """Dynamic cache that supports arbitrary layer indices for virtual layers."""
99
+
100
+ def __init__(self, num_hidden_layers: int = None):
101
+ self._num_hidden_layers = num_hidden_layers or 128
102
+ self.key_cache: List[Optional[torch.Tensor]] = []
103
+ self.value_cache: List[Optional[torch.Tensor]] = []
104
+ self._seen_tokens = 0
105
+ self.layers = None
106
+ self.layer_class_to_replicate = None
107
+ self.offloading = False
108
+
109
+ def update(
110
+ self,
111
+ key_states: torch.Tensor,
112
+ value_states: torch.Tensor,
113
+ layer_idx: int,
114
+ cache_kwargs: Optional[dict] = None,
115
+ ) -> Tuple[torch.Tensor, torch.Tensor]:
116
+ while len(self.key_cache) <= layer_idx:
117
+ self.key_cache.append(None)
118
+ self.value_cache.append(None)
119
+
120
+ if self.key_cache[layer_idx] is None:
121
+ self.key_cache[layer_idx] = key_states
122
+ self.value_cache[layer_idx] = value_states
123
+ if layer_idx == 0:
124
+ self._seen_tokens += key_states.shape[-2]
125
+ else:
126
+ self.key_cache[layer_idx] = torch.cat([self.key_cache[layer_idx], key_states], dim=-2)
127
+ self.value_cache[layer_idx] = torch.cat([self.value_cache[layer_idx], value_states], dim=-2)
128
+ if layer_idx == 0:
129
+ self._seen_tokens += key_states.shape[-2]
130
+
131
+ return self.key_cache[layer_idx], self.value_cache[layer_idx]
132
+
133
+ def get_seq_length(self, layer_idx: int = 0) -> int:
134
+ if layer_idx < len(self.key_cache) and self.key_cache[layer_idx] is not None:
135
+ return self.key_cache[layer_idx].shape[-2]
136
+ return 0
137
+
138
+ def get_max_cache_shape(self) -> Optional[int]:
139
+ return None
140
+
141
+ def get_max_length(self) -> Optional[int]:
142
+ return None
143
+
144
+ @property
145
+ def seen_tokens(self) -> int:
146
+ return self._seen_tokens
147
+
148
+ def __len__(self) -> int:
149
+ return len(self.key_cache)
150
+
151
+ def __iter__(self):
152
+ for layer_idx in range(len(self)):
153
+ if layer_idx < len(self.key_cache) and self.key_cache[layer_idx] is not None:
154
+ yield (self.key_cache[layer_idx], self.value_cache[layer_idx])
155
+ else:
156
+ yield (None, None)
157
+
158
+ def __getitem__(self, layer_idx: int):
159
+ if layer_idx < len(self.key_cache) and self.key_cache[layer_idx] is not None:
160
+ return (self.key_cache[layer_idx], self.value_cache[layer_idx])
161
+ return (None, None)
162
+
163
+ def to_legacy_cache(self):
164
+ legacy_cache = ()
165
+ for layer_idx in range(len(self)):
166
+ if layer_idx < len(self.key_cache) and self.key_cache[layer_idx] is not None:
167
+ legacy_cache += ((self.key_cache[layer_idx], self.value_cache[layer_idx]),)
168
+ else:
169
+ legacy_cache += ((None, None),)
170
+ return legacy_cache
171
+
172
+ def reorder_cache(self, beam_idx: torch.LongTensor):
173
+ for layer_idx in range(len(self.key_cache)):
174
+ if self.key_cache[layer_idx] is not None:
175
+ device = self.key_cache[layer_idx].device
176
+ self.key_cache[layer_idx] = self.key_cache[layer_idx].index_select(0, beam_idx.to(device))
177
+ self.value_cache[layer_idx] = self.value_cache[layer_idx].index_select(0, beam_idx.to(device))
178
+
179
+
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(
185
+ torch.cumsum(seqlens_in_batch, dim=0, dtype=torch.torch.int32), (1, 0)
186
+ )
187
+ return (
188
+ indices,
189
+ cu_seqlens,
190
+ max_seqlen_in_batch,
191
+ )
192
+
193
+
194
+ class ScatterbrainMoonlightRMSNorm(nn.Module):
195
+ def __init__(self, hidden_size, eps=1e-6):
196
+ super().__init__()
197
+ self.weight = nn.Parameter(torch.ones(hidden_size))
198
+ self.variance_epsilon = eps
199
+
200
+ def forward(self, hidden_states):
201
+ input_dtype = hidden_states.dtype
202
+ hidden_states = hidden_states.to(torch.float32)
203
+ variance = hidden_states.pow(2).mean(-1, keepdim=True)
204
+ hidden_states = hidden_states * torch.rsqrt(variance + self.variance_epsilon)
205
+ return self.weight * hidden_states.to(input_dtype)
206
+
207
+
208
+ ALL_LAYERNORM_LAYERS.append(ScatterbrainMoonlightRMSNorm)
209
+
210
+
211
+ class ScatterbrainMoonlightRotaryEmbedding(nn.Module):
212
+ def __init__(self, dim, max_position_embeddings=2048, base=10000, device=None):
213
+ super().__init__()
214
+
215
+ self.dim = dim
216
+ self.max_position_embeddings = max_position_embeddings
217
+ self.base = base
218
+ inv_freq = 1.0 / (
219
+ self.base ** (torch.arange(0, self.dim, 2).float().to(device) / self.dim)
220
+ )
221
+ self.register_buffer("inv_freq", inv_freq, persistent=False)
222
+
223
+ self._set_cos_sin_cache(
224
+ seq_len=max_position_embeddings,
225
+ device=self.inv_freq.device,
226
+ dtype=torch.get_default_dtype(),
227
+ )
228
+ self.max_seq_len_cached = None
229
+
230
+ def _set_cos_sin_cache(self, seq_len, device, dtype):
231
+ self.max_seq_len_cached = seq_len
232
+ t = torch.arange(
233
+ self.max_seq_len_cached, device=device, dtype=self.inv_freq.dtype
234
+ )
235
+
236
+ freqs = torch.outer(t, self.inv_freq.to(t.device))
237
+ emb = torch.cat((freqs, freqs), dim=-1)
238
+ self.register_buffer("cos_cached", emb.cos().to(dtype), persistent=False)
239
+ self.register_buffer("sin_cached", emb.sin().to(dtype), persistent=False)
240
+
241
+ def forward(self, x, seq_len=None):
242
+ if self.max_seq_len_cached is None or seq_len > self.max_seq_len_cached:
243
+ self._set_cos_sin_cache(seq_len=seq_len, device=x.device, dtype=x.dtype)
244
+
245
+ return (
246
+ self.cos_cached[:seq_len].to(dtype=x.dtype),
247
+ self.sin_cached[:seq_len].to(dtype=x.dtype),
248
+ )
249
+
250
+
251
+ class ScatterbrainMoonlightLinearScalingRotaryEmbedding(ScatterbrainMoonlightRotaryEmbedding):
252
+
253
+ def __init__(
254
+ self,
255
+ dim,
256
+ max_position_embeddings=2048,
257
+ base=10000,
258
+ device=None,
259
+ scaling_factor=1.0,
260
+ ):
261
+ self.scaling_factor = scaling_factor
262
+ super().__init__(dim, max_position_embeddings, base, device)
263
+
264
+ def _set_cos_sin_cache(self, seq_len, device, dtype):
265
+ self.max_seq_len_cached = seq_len
266
+ t = torch.arange(
267
+ self.max_seq_len_cached, device=device, dtype=self.inv_freq.dtype
268
+ )
269
+ t = t / self.scaling_factor
270
+
271
+ freqs = torch.outer(t, self.inv_freq)
272
+ emb = torch.cat((freqs, freqs), dim=-1)
273
+ self.register_buffer("cos_cached", emb.cos().to(dtype), persistent=False)
274
+ self.register_buffer("sin_cached", emb.sin().to(dtype), persistent=False)
275
+
276
+
277
+ class ScatterbrainMoonlightDynamicNTKScalingRotaryEmbedding(ScatterbrainMoonlightRotaryEmbedding):
278
+
279
+ def __init__(
280
+ self,
281
+ dim,
282
+ max_position_embeddings=2048,
283
+ base=10000,
284
+ device=None,
285
+ scaling_factor=1.0,
286
+ ):
287
+ self.scaling_factor = scaling_factor
288
+ super().__init__(dim, max_position_embeddings, base, device)
289
+
290
+ def _set_cos_sin_cache(self, seq_len, device, dtype):
291
+ self.max_seq_len_cached = seq_len
292
+
293
+ if seq_len > self.max_position_embeddings:
294
+ base = self.base * (
295
+ (self.scaling_factor * seq_len / self.max_position_embeddings)
296
+ - (self.scaling_factor - 1)
297
+ ) ** (self.dim / (self.dim - 2))
298
+ inv_freq = 1.0 / (
299
+ base ** (torch.arange(0, self.dim, 2).float().to(device) / self.dim)
300
+ )
301
+ self.register_buffer("inv_freq", inv_freq, persistent=False)
302
+
303
+ t = torch.arange(
304
+ self.max_seq_len_cached, device=device, dtype=self.inv_freq.dtype
305
+ )
306
+
307
+ freqs = torch.outer(t, self.inv_freq)
308
+ emb = torch.cat((freqs, freqs), dim=-1)
309
+ self.register_buffer("cos_cached", emb.cos().to(dtype), persistent=False)
310
+ self.register_buffer("sin_cached", emb.sin().to(dtype), persistent=False)
311
+
312
+
313
+ def yarn_find_correction_dim(
314
+ num_rotations, dim, base=10000, max_position_embeddings=2048
315
+ ):
316
+ return (dim * math.log(max_position_embeddings / (num_rotations * 2 * math.pi))) / (
317
+ 2 * math.log(base)
318
+ )
319
+
320
+
321
+ def yarn_find_correction_range(
322
+ low_rot, high_rot, dim, base=10000, max_position_embeddings=2048
323
+ ):
324
+ low = math.floor(
325
+ yarn_find_correction_dim(low_rot, dim, base, max_position_embeddings)
326
+ )
327
+ high = math.ceil(
328
+ yarn_find_correction_dim(high_rot, dim, base, max_position_embeddings)
329
+ )
330
+ return max(low, 0), min(high, dim - 1)
331
+
332
+
333
+ def yarn_get_mscale(scale=1, mscale=1):
334
+ if scale <= 1:
335
+ return 1.0
336
+ return 0.1 * mscale * math.log(scale) + 1.0
337
+
338
+
339
+ def yarn_linear_ramp_mask(min, max, dim):
340
+ if min == max:
341
+ max += 0.001
342
+
343
+ linear_func = (torch.arange(dim, dtype=torch.float32) - min) / (max - min)
344
+ ramp_func = torch.clamp(linear_func, 0, 1)
345
+ return ramp_func
346
+
347
+
348
+ class ScatterbrainMoonlightYarnRotaryEmbedding(ScatterbrainMoonlightRotaryEmbedding):
349
+
350
+ def __init__(
351
+ self,
352
+ dim,
353
+ max_position_embeddings=2048,
354
+ base=10000,
355
+ device=None,
356
+ scaling_factor=1.0,
357
+ original_max_position_embeddings=4096,
358
+ beta_fast=32,
359
+ beta_slow=1,
360
+ mscale=1,
361
+ mscale_all_dim=0,
362
+ ):
363
+ self.scaling_factor = scaling_factor
364
+ self.original_max_position_embeddings = original_max_position_embeddings
365
+ self.beta_fast = beta_fast
366
+ self.beta_slow = beta_slow
367
+ self.mscale = mscale
368
+ self.mscale_all_dim = mscale_all_dim
369
+ super().__init__(dim, max_position_embeddings, base, device)
370
+
371
+ def _set_cos_sin_cache(self, seq_len, device, dtype):
372
+ self.max_seq_len_cached = seq_len
373
+ dim = self.dim
374
+
375
+ freq_extra = 1.0 / (
376
+ self.base
377
+ ** (torch.arange(0, dim, 2, dtype=torch.float32, device=device) / dim)
378
+ )
379
+ freq_inter = 1.0 / (
380
+ self.scaling_factor
381
+ * self.base
382
+ ** (torch.arange(0, dim, 2, dtype=torch.float32, device=device) / dim)
383
+ )
384
+
385
+ low, high = yarn_find_correction_range(
386
+ self.beta_fast,
387
+ self.beta_slow,
388
+ dim,
389
+ self.base,
390
+ self.original_max_position_embeddings,
391
+ )
392
+ inv_freq_mask = 1.0 - yarn_linear_ramp_mask(low, high, dim // 2).to(
393
+ device=device, dtype=torch.float32
394
+ )
395
+ inv_freq = freq_inter * (1 - inv_freq_mask) + freq_extra * inv_freq_mask
396
+ self.register_buffer("inv_freq", inv_freq, persistent=False)
397
+
398
+ t = torch.arange(seq_len, device=device, dtype=torch.float32)
399
+
400
+ freqs = torch.outer(t, inv_freq)
401
+
402
+ _mscale = float(
403
+ yarn_get_mscale(self.scaling_factor, self.mscale)
404
+ / yarn_get_mscale(self.scaling_factor, self.mscale_all_dim)
405
+ )
406
+
407
+ emb = torch.cat((freqs, freqs), dim=-1)
408
+ self.register_buffer(
409
+ "cos_cached", (emb.cos() * _mscale).to(dtype), persistent=False
410
+ )
411
+ self.register_buffer(
412
+ "sin_cached", (emb.sin() * _mscale).to(dtype), persistent=False
413
+ )
414
+
415
+
416
+ def rotate_half(x):
417
+ """Rotates half the hidden dims of the input."""
418
+ x1 = x[..., : x.shape[-1] // 2]
419
+ x2 = x[..., x.shape[-1] // 2 :]
420
+ return torch.cat((-x2, x1), dim=-1)
421
+
422
+
423
+ def apply_rotary_pos_emb(q, k, cos, sin, position_ids, unsqueeze_dim=1):
424
+ cos = cos[position_ids].unsqueeze(unsqueeze_dim)
425
+ sin = sin[position_ids].unsqueeze(unsqueeze_dim)
426
+
427
+ b, h, s, d = q.shape
428
+ q = q.view(b, h, s, d // 2, 2).transpose(4, 3).reshape(b, h, s, d)
429
+
430
+ b, h, s, d = k.shape
431
+ k = k.view(b, h, s, d // 2, 2).transpose(4, 3).reshape(b, h, s, d)
432
+
433
+ q_embed = (q * cos) + (rotate_half(q) * sin)
434
+ k_embed = (k * cos) + (rotate_half(k) * sin)
435
+ return q_embed, k_embed
436
+
437
+
438
+ class ScatterbrainMoonlightMLP(nn.Module):
439
+ def __init__(self, config, hidden_size=None, intermediate_size=None):
440
+ super().__init__()
441
+ self.config = config
442
+ self.hidden_size = config.hidden_size if hidden_size is None else hidden_size
443
+ self.intermediate_size = (
444
+ config.intermediate_size if intermediate_size is None else intermediate_size
445
+ )
446
+
447
+ self.gate_proj = nn.Linear(self.hidden_size, self.intermediate_size, bias=False)
448
+ self.up_proj = nn.Linear(self.hidden_size, self.intermediate_size, bias=False)
449
+ self.down_proj = nn.Linear(self.intermediate_size, self.hidden_size, bias=False)
450
+ self.act_fn = ACT2FN[config.hidden_act]
451
+
452
+ def forward(self, x):
453
+ down_proj = self.down_proj(self.act_fn(self.gate_proj(x)) * self.up_proj(x))
454
+ return down_proj
455
+
456
+
457
+ class ScatterbrainMoonlightMoEGate(nn.Module):
458
+ def __init__(self, config):
459
+ super().__init__()
460
+ self.config = config
461
+ self.top_k = config.num_experts_per_tok
462
+ self.n_routed_experts = config.n_routed_experts
463
+ self.routed_scaling_factor = config.routed_scaling_factor
464
+ self.scoring_func = config.scoring_func
465
+ self.seq_aux = config.seq_aux
466
+ self.topk_method = config.topk_method
467
+ self.n_group = config.n_group
468
+ self.topk_group = config.topk_group
469
+
470
+ self.norm_topk_prob = config.norm_topk_prob
471
+ self.gating_dim = config.hidden_size
472
+ self.weight = nn.Parameter(
473
+ torch.empty((self.n_routed_experts, self.gating_dim))
474
+ )
475
+ if self.topk_method == "noaux_tc":
476
+ self.e_score_correction_bias = nn.Parameter(
477
+ torch.empty((self.n_routed_experts))
478
+ )
479
+ self.reset_parameters()
480
+
481
+ def reset_parameters(self) -> None:
482
+ import torch.nn.init as init
483
+
484
+ init.kaiming_uniform_(self.weight, a=math.sqrt(5))
485
+
486
+ def forward(self, hidden_states):
487
+ bsz, seq_len, h = hidden_states.shape
488
+ hidden_states = hidden_states.view(-1, h)
489
+ logits = F.linear(
490
+ hidden_states.type(torch.float32), self.weight.type(torch.float32), None
491
+ )
492
+ if self.scoring_func == "sigmoid":
493
+ scores = logits.sigmoid()
494
+ else:
495
+ raise NotImplementedError(
496
+ f"insupportable scoring function for MoE gating: {self.scoring_func}"
497
+ )
498
+
499
+ if self.topk_method == "noaux_tc":
500
+ assert not self.training
501
+ scores_for_choice = scores.view(bsz * seq_len, -1) + self.e_score_correction_bias.unsqueeze(0)
502
+ group_scores = (
503
+ scores_for_choice.view(bsz * seq_len, self.n_group, -1).topk(2, dim=-1)[0].sum(dim = -1)
504
+ )
505
+ group_idx = torch.topk(
506
+ group_scores, k=self.topk_group, dim=-1, sorted=False
507
+ )[1]
508
+ group_mask = torch.zeros_like(group_scores)
509
+ group_mask.scatter_(1, group_idx, 1)
510
+ score_mask = (
511
+ group_mask.unsqueeze(-1)
512
+ .expand(
513
+ bsz * seq_len, self.n_group, self.n_routed_experts // self.n_group
514
+ )
515
+ .reshape(bsz * seq_len, -1)
516
+ )
517
+ tmp_scores = scores_for_choice.masked_fill(~score_mask.bool(), 0.0)
518
+ _, topk_idx = torch.topk(
519
+ tmp_scores, k=self.top_k, dim=-1, sorted=False
520
+ )
521
+ topk_weight = scores.gather(1, topk_idx)
522
+ else:
523
+ raise NotImplementedError(
524
+ f"insupportable TopK function for MoE gating: {self.topk_method}"
525
+ )
526
+
527
+ if self.top_k > 1 and self.norm_topk_prob:
528
+ denominator = topk_weight.sum(dim=-1, keepdim=True) + 1e-20
529
+ topk_weight = topk_weight / denominator
530
+ topk_weight = topk_weight * self.routed_scaling_factor
531
+
532
+ return topk_idx, topk_weight
533
+
534
+
535
+ class ScatterbrainMoonlightMoE(nn.Module):
536
+ """
537
+ A mixed expert module using ScatterMoE for optimized expert computation.
538
+
539
+ Uses stacked expert weights and ScatterMoE's parallel_linear for efficient
540
+ GPU computation instead of nn.ModuleList with sequential expert calls.
541
+ """
542
+
543
+ def __init__(self, config):
544
+ super().__init__()
545
+ self.config = config
546
+ self.num_experts_per_tok = config.num_experts_per_tok
547
+ self.n_routed_experts = config.n_routed_experts
548
+ self.hidden_size = config.hidden_size
549
+ self.moe_intermediate_size = config.moe_intermediate_size
550
+
551
+ # Stacked expert weights as Parameters
552
+ # Shape: [num_experts, out_features, in_features]
553
+ self.expert_gate_proj = nn.Parameter(
554
+ torch.empty(config.n_routed_experts, config.moe_intermediate_size, config.hidden_size)
555
+ )
556
+ self.expert_up_proj = nn.Parameter(
557
+ torch.empty(config.n_routed_experts, config.moe_intermediate_size, config.hidden_size)
558
+ )
559
+ self.expert_down_proj = nn.Parameter(
560
+ torch.empty(config.n_routed_experts, config.hidden_size, config.moe_intermediate_size)
561
+ )
562
+
563
+ # Initialize weights
564
+ for param in [self.expert_gate_proj, self.expert_up_proj, self.expert_down_proj]:
565
+ nn.init.kaiming_uniform_(param, a=5**0.5)
566
+
567
+ self.gate = ScatterbrainMoonlightMoEGate(config)
568
+
569
+ if config.n_shared_experts is not None:
570
+ intermediate_size = config.moe_intermediate_size * config.n_shared_experts
571
+ self.shared_experts = ScatterbrainMoonlightMLP(
572
+ config=config, intermediate_size=intermediate_size
573
+ )
574
+
575
+ def forward(self, hidden_states):
576
+ identity = hidden_states
577
+ orig_shape = hidden_states.shape
578
+ topk_idx, topk_weight = self.gate(hidden_states)
579
+ hidden_states = hidden_states.view(-1, hidden_states.shape[-1])
580
+
581
+ if SCATTERMOE_AVAILABLE:
582
+ y = self._forward_scattermoe(hidden_states, topk_idx, topk_weight)
583
+ else:
584
+ y = self._forward_loop(hidden_states, topk_idx, topk_weight)
585
+
586
+ y = y.view(*orig_shape)
587
+
588
+ if self.config.n_shared_experts is not None:
589
+ y = y + self.shared_experts(identity)
590
+ return y
591
+
592
+ def _forward_scattermoe(
593
+ self,
594
+ hidden_states: torch.Tensor,
595
+ selected_experts: torch.Tensor,
596
+ routing_weights: torch.Tensor,
597
+ ) -> torch.Tensor:
598
+ """Forward pass using ScatterMoE Triton kernels."""
599
+ sorted_expert_idxs, sorted_scattered_idxs, expert_offsets = flatten_sort_count(
600
+ selected_experts, num_experts=self.n_routed_experts
601
+ )
602
+
603
+ # First pass: gate and up projections (hidden -> intermediate)
604
+ gate_out = parallel_linear(
605
+ inputs=hidden_states,
606
+ expert_weights=self.expert_gate_proj.permute(0, 2, 1),
607
+ k=self.num_experts_per_tok,
608
+ sorted_expert_idxs=sorted_expert_idxs,
609
+ sorted_scattered_idxs=sorted_scattered_idxs,
610
+ expert_offsets=expert_offsets,
611
+ grouped_out=True,
612
+ )
613
+
614
+ up_out = parallel_linear(
615
+ inputs=hidden_states,
616
+ expert_weights=self.expert_up_proj.permute(0, 2, 1),
617
+ k=self.num_experts_per_tok,
618
+ sorted_expert_idxs=sorted_expert_idxs,
619
+ sorted_scattered_idxs=sorted_scattered_idxs,
620
+ expert_offsets=expert_offsets,
621
+ grouped_out=True,
622
+ )
623
+
624
+ # Apply SiLU activation (SwiGLU)
625
+ activated = F.silu(gate_out) * up_out
626
+
627
+ # Second pass: down projection with routing weights
628
+ # Convert gates to match expert weight dtype (scattermoe requires consistent dtypes)
629
+ output = parallel_linear(
630
+ inputs=activated,
631
+ expert_weights=self.expert_down_proj.permute(0, 2, 1),
632
+ k=1,
633
+ sorted_expert_idxs=sorted_expert_idxs,
634
+ sorted_scattered_idxs=sorted_scattered_idxs,
635
+ expert_offsets=expert_offsets,
636
+ gates=routing_weights.to(self.expert_down_proj.dtype),
637
+ grouped_in=True,
638
+ grouped_out=False,
639
+ )
640
+
641
+ return output
642
+
643
+ def _forward_loop(
644
+ self,
645
+ hidden_states: torch.Tensor,
646
+ selected_experts: torch.Tensor,
647
+ routing_weights: torch.Tensor,
648
+ ) -> torch.Tensor:
649
+ """Fallback forward pass using Python loop."""
650
+ num_tokens = hidden_states.shape[0]
651
+
652
+ flat_expert_indices = selected_experts.view(-1)
653
+ flat_token_indices = torch.arange(num_tokens, device=hidden_states.device).unsqueeze(1).expand(-1, self.num_experts_per_tok).reshape(-1)
654
+ flat_routing_weights = routing_weights.view(-1)
655
+
656
+ sorted_indices = torch.argsort(flat_expert_indices, stable=True)
657
+ sorted_expert_indices = flat_expert_indices[sorted_indices]
658
+ sorted_token_indices = flat_token_indices[sorted_indices]
659
+ sorted_routing_weights = flat_routing_weights[sorted_indices]
660
+ sorted_hidden = hidden_states[sorted_token_indices]
661
+
662
+ expert_counts = torch.bincount(sorted_expert_indices, minlength=self.n_routed_experts)
663
+ expert_offsets = torch.zeros(self.n_routed_experts + 1, dtype=torch.long, device=hidden_states.device)
664
+ expert_offsets[1:] = torch.cumsum(expert_counts, dim=0)
665
+
666
+ final_hidden_states = torch.zeros_like(hidden_states)
667
+
668
+ for expert_idx in range(self.n_routed_experts):
669
+ start = expert_offsets[expert_idx].item()
670
+ end = expert_offsets[expert_idx + 1].item()
671
+
672
+ if start == end:
673
+ continue
674
+
675
+ expert_tokens = sorted_hidden[start:end]
676
+ expert_weights = sorted_routing_weights[start:end].unsqueeze(-1)
677
+ token_indices = sorted_token_indices[sorted_indices[start:end]]
678
+
679
+ gate = self.expert_gate_proj[expert_idx]
680
+ up = self.expert_up_proj[expert_idx]
681
+ down = self.expert_down_proj[expert_idx]
682
+
683
+ gate_out = F.linear(expert_tokens, gate)
684
+ up_out = F.linear(expert_tokens, up)
685
+ expert_out = F.linear(F.silu(gate_out) * up_out, down)
686
+
687
+ final_hidden_states.index_add_(0, token_indices, expert_out * expert_weights)
688
+
689
+ return final_hidden_states
690
+
691
+
692
+ def repeat_kv(hidden_states: torch.Tensor, n_rep: int) -> torch.Tensor:
693
+ batch, num_key_value_heads, slen, head_dim = hidden_states.shape
694
+ if n_rep == 1:
695
+ return hidden_states
696
+ hidden_states = hidden_states[:, :, None, :, :].expand(
697
+ batch, num_key_value_heads, n_rep, slen, head_dim
698
+ )
699
+ return hidden_states.reshape(batch, num_key_value_heads * n_rep, slen, head_dim)
700
+
701
+
702
+ class ScatterbrainMoonlightAttention(nn.Module):
703
+ """Multi-headed attention from 'Attention Is All You Need' paper"""
704
+
705
+ def __init__(self, config: ScatterbrainMoonlightConfig, layer_idx: Optional[int] = None):
706
+ super().__init__()
707
+ self.config = config
708
+ self.layer_idx = layer_idx
709
+ if layer_idx is None:
710
+ logger.warning_once(
711
+ f"Instantiating {self.__class__.__name__} without passing `layer_idx` is not recommended and will "
712
+ "to errors during the forward call, if caching is used. Please make sure to provide a `layer_idx` "
713
+ "when creating this class."
714
+ )
715
+
716
+ self.attention_dropout = config.attention_dropout
717
+ self.hidden_size = config.hidden_size
718
+ self.num_heads = config.num_attention_heads
719
+
720
+ self.max_position_embeddings = config.max_position_embeddings
721
+ self.rope_theta = config.rope_theta
722
+ self.q_lora_rank = config.q_lora_rank
723
+ self.qk_rope_head_dim = config.qk_rope_head_dim
724
+ self.kv_lora_rank = config.kv_lora_rank
725
+ self.v_head_dim = config.v_head_dim
726
+ self.qk_nope_head_dim = config.qk_nope_head_dim
727
+ self.q_head_dim = config.qk_nope_head_dim + config.qk_rope_head_dim
728
+
729
+ self.is_causal = True
730
+
731
+ if self.q_lora_rank is None:
732
+ self.q_proj = nn.Linear(
733
+ self.hidden_size, self.num_heads * self.q_head_dim, bias=False
734
+ )
735
+ else:
736
+ self.q_a_proj = nn.Linear(
737
+ self.hidden_size, config.q_lora_rank, bias=config.attention_bias
738
+ )
739
+ self.q_a_layernorm = ScatterbrainMoonlightRMSNorm(config.q_lora_rank)
740
+ self.q_b_proj = nn.Linear(
741
+ config.q_lora_rank, self.num_heads * self.q_head_dim, bias=False
742
+ )
743
+
744
+ self.kv_a_proj_with_mqa = nn.Linear(
745
+ self.hidden_size,
746
+ config.kv_lora_rank + config.qk_rope_head_dim,
747
+ bias=config.attention_bias,
748
+ )
749
+ self.kv_a_layernorm = ScatterbrainMoonlightRMSNorm(config.kv_lora_rank)
750
+ self.kv_b_proj = nn.Linear(
751
+ config.kv_lora_rank,
752
+ self.num_heads
753
+ * (self.q_head_dim - self.qk_rope_head_dim + self.v_head_dim),
754
+ bias=False,
755
+ )
756
+
757
+ self.o_proj = nn.Linear(
758
+ self.num_heads * self.v_head_dim,
759
+ self.hidden_size,
760
+ bias=config.attention_bias,
761
+ )
762
+ self._init_rope()
763
+
764
+ self.softmax_scale = self.q_head_dim ** (-0.5)
765
+ if self.config.rope_scaling is not None:
766
+ mscale_all_dim = self.config.rope_scaling.get("mscale_all_dim", 0)
767
+ scaling_factor = self.config.rope_scaling["factor"]
768
+ if mscale_all_dim:
769
+ mscale = yarn_get_mscale(scaling_factor, mscale_all_dim)
770
+ self.softmax_scale = self.softmax_scale * mscale * mscale
771
+
772
+ def _init_rope(self):
773
+ if self.config.rope_scaling is None:
774
+ self.rotary_emb = ScatterbrainMoonlightRotaryEmbedding(
775
+ self.qk_rope_head_dim,
776
+ max_position_embeddings=self.max_position_embeddings,
777
+ base=self.rope_theta,
778
+ )
779
+ else:
780
+ scaling_type = self.config.rope_scaling["type"]
781
+ scaling_factor = self.config.rope_scaling["factor"]
782
+ if scaling_type == "linear":
783
+ self.rotary_emb = ScatterbrainMoonlightLinearScalingRotaryEmbedding(
784
+ self.qk_rope_head_dim,
785
+ max_position_embeddings=self.max_position_embeddings,
786
+ scaling_factor=scaling_factor,
787
+ base=self.rope_theta,
788
+ )
789
+ elif scaling_type == "dynamic":
790
+ self.rotary_emb = ScatterbrainMoonlightDynamicNTKScalingRotaryEmbedding(
791
+ self.qk_rope_head_dim,
792
+ max_position_embeddings=self.max_position_embeddings,
793
+ scaling_factor=scaling_factor,
794
+ base=self.rope_theta,
795
+ )
796
+ elif scaling_type == "yarn":
797
+ kwargs = {
798
+ key: self.config.rope_scaling[key]
799
+ for key in [
800
+ "original_max_position_embeddings",
801
+ "beta_fast",
802
+ "beta_slow",
803
+ "mscale",
804
+ "mscale_all_dim",
805
+ ]
806
+ if key in self.config.rope_scaling
807
+ }
808
+ self.rotary_emb = ScatterbrainMoonlightYarnRotaryEmbedding(
809
+ self.qk_rope_head_dim,
810
+ max_position_embeddings=self.max_position_embeddings,
811
+ scaling_factor=scaling_factor,
812
+ base=self.rope_theta,
813
+ **kwargs,
814
+ )
815
+ else:
816
+ raise ValueError(f"Unknown RoPE scaling type {scaling_type}")
817
+
818
+ def _shape(self, tensor: torch.Tensor, seq_len: int, bsz: int):
819
+ return (
820
+ tensor.view(bsz, seq_len, self.num_heads, self.v_head_dim)
821
+ .transpose(1, 2)
822
+ .contiguous()
823
+ )
824
+
825
+ def forward(
826
+ self,
827
+ hidden_states: torch.Tensor,
828
+ attention_mask: Optional[torch.Tensor] = None,
829
+ position_ids: Optional[torch.LongTensor] = None,
830
+ past_key_value: Optional[Cache] = None,
831
+ output_attentions: bool = False,
832
+ use_cache: bool = False,
833
+ **kwargs,
834
+ ) -> Tuple[torch.Tensor, Optional[torch.Tensor], Optional[Tuple[torch.Tensor]]]:
835
+ if "padding_mask" in kwargs:
836
+ warnings.warn(
837
+ "Passing `padding_mask` is deprecated and will be removed in v4.37. Please make sure use `attention_mask` instead.`"
838
+ )
839
+ bsz, q_len, _ = hidden_states.size()
840
+
841
+ if self.q_lora_rank is None:
842
+ q = self.q_proj(hidden_states)
843
+ else:
844
+ q = self.q_b_proj(self.q_a_layernorm(self.q_a_proj(hidden_states)))
845
+ q = q.view(bsz, q_len, self.num_heads, self.q_head_dim).transpose(1, 2)
846
+ q_nope, q_pe = torch.split(
847
+ q, [self.qk_nope_head_dim, self.qk_rope_head_dim], dim=-1
848
+ )
849
+
850
+ compressed_kv = self.kv_a_proj_with_mqa(hidden_states)
851
+ compressed_kv, k_pe = torch.split(
852
+ compressed_kv, [self.kv_lora_rank, self.qk_rope_head_dim], dim=-1
853
+ )
854
+ k_pe = k_pe.view(bsz, q_len, 1, self.qk_rope_head_dim).transpose(1, 2)
855
+ kv = (
856
+ self.kv_b_proj(self.kv_a_layernorm(compressed_kv))
857
+ .view(bsz, q_len, self.num_heads, self.qk_nope_head_dim + self.v_head_dim)
858
+ .transpose(1, 2)
859
+ )
860
+
861
+ k_nope, value_states = torch.split(
862
+ kv, [self.qk_nope_head_dim, self.v_head_dim], dim=-1
863
+ )
864
+ kv_seq_len = value_states.shape[-2]
865
+ if past_key_value is not None:
866
+ if self.layer_idx is None:
867
+ raise ValueError(
868
+ f"The cache structure has changed since version v4.36. If you are using {self.__class__.__name__} "
869
+ "for auto-regressive decoding with k/v caching, please make sure to initialize the attention class "
870
+ "with a layer index."
871
+ )
872
+ kv_seq_len += _get_cache_length(past_key_value, kv_seq_len, self.layer_idx)
873
+ cos, sin = self.rotary_emb(value_states, seq_len=kv_seq_len)
874
+
875
+ q_pe, k_pe = apply_rotary_pos_emb(q_pe, k_pe, cos, sin, position_ids)
876
+
877
+ query_states = k_pe.new_empty(bsz, self.num_heads, q_len, self.q_head_dim)
878
+ query_states[:, :, :, : self.qk_nope_head_dim] = q_nope
879
+ query_states[:, :, :, self.qk_nope_head_dim :] = q_pe
880
+
881
+ key_states = k_pe.new_empty(bsz, self.num_heads, q_len, self.q_head_dim)
882
+ key_states[:, :, :, : self.qk_nope_head_dim] = k_nope
883
+ key_states[:, :, :, self.qk_nope_head_dim :] = k_pe
884
+ if past_key_value is not None:
885
+ cache_kwargs = {"sin": sin, "cos": cos}
886
+ key_states, value_states = past_key_value.update(
887
+ key_states, value_states, self.layer_idx, cache_kwargs
888
+ )
889
+
890
+ attn_weights = (
891
+ torch.matmul(query_states, key_states.transpose(2, 3)) * self.softmax_scale
892
+ )
893
+
894
+ if attn_weights.size() != (bsz, self.num_heads, q_len, kv_seq_len):
895
+ raise ValueError(
896
+ f"Attention weights should be of size {(bsz, self.num_heads, q_len, kv_seq_len)}, but is"
897
+ f" {attn_weights.size()}"
898
+ )
899
+ if attention_mask is not None:
900
+ if attention_mask.size() != (bsz, 1, q_len, kv_seq_len):
901
+ raise ValueError(
902
+ f"Attention mask should be of size {(bsz, 1, q_len, kv_seq_len)}, but is {attention_mask.size()}"
903
+ )
904
+ attn_weights = attn_weights + attention_mask
905
+
906
+ attn_weights = nn.functional.softmax(
907
+ attn_weights, dim=-1, dtype=torch.float32
908
+ ).to(query_states.dtype)
909
+ attn_weights = nn.functional.dropout(
910
+ attn_weights, p=self.attention_dropout, training=self.training
911
+ )
912
+ attn_output = torch.matmul(attn_weights, value_states)
913
+
914
+ if attn_output.size() != (bsz, self.num_heads, q_len, self.v_head_dim):
915
+ raise ValueError(
916
+ f"`attn_output` should be of size {(bsz, self.num_heads, q_len, self.v_head_dim)}, but is"
917
+ f" {attn_output.size()}"
918
+ )
919
+
920
+ attn_output = attn_output.transpose(1, 2).contiguous()
921
+
922
+ attn_output = attn_output.reshape(bsz, q_len, self.num_heads * self.v_head_dim)
923
+
924
+ attn_output = self.o_proj(attn_output)
925
+
926
+ if not output_attentions:
927
+ attn_weights = None
928
+
929
+ return attn_output, attn_weights, past_key_value
930
+
931
+
932
+ class ScatterbrainMoonlightFlashAttention2(ScatterbrainMoonlightAttention):
933
+ """Flash Attention 2 implementation."""
934
+
935
+ def __init__(self, *args, **kwargs):
936
+ super().__init__(*args, **kwargs)
937
+ self._flash_attn_uses_top_left_mask = not is_flash_attn_greater_or_equal_2_10()
938
+
939
+ def forward(
940
+ self,
941
+ hidden_states: torch.Tensor,
942
+ attention_mask: Optional[torch.LongTensor] = None,
943
+ position_ids: Optional[torch.LongTensor] = None,
944
+ past_key_value: Optional[Cache] = None,
945
+ output_attentions: bool = False,
946
+ use_cache: bool = False,
947
+ **kwargs,
948
+ ) -> Tuple[torch.Tensor, Optional[torch.Tensor], Optional[Tuple[torch.Tensor]]]:
949
+ if "padding_mask" in kwargs:
950
+ warnings.warn(
951
+ "Passing `padding_mask` is deprecated and will be removed in v4.37. Please make sure use `attention_mask` instead.`"
952
+ )
953
+ attention_mask = kwargs.pop("padding_mask")
954
+
955
+ output_attentions = False
956
+
957
+ bsz, q_len, _ = hidden_states.size()
958
+
959
+ if self.q_lora_rank is None:
960
+ q = self.q_proj(hidden_states)
961
+ else:
962
+ q = self.q_b_proj(self.q_a_layernorm(self.q_a_proj(hidden_states)))
963
+ q = q.view(bsz, q_len, self.num_heads, self.q_head_dim).transpose(1, 2)
964
+ q_nope, q_pe = torch.split(
965
+ q, [self.qk_nope_head_dim, self.qk_rope_head_dim], dim=-1
966
+ )
967
+
968
+ compressed_kv = self.kv_a_proj_with_mqa(hidden_states)
969
+ compressed_kv, k_pe = torch.split(
970
+ compressed_kv, [self.kv_lora_rank, self.qk_rope_head_dim], dim=-1
971
+ )
972
+ k_pe = k_pe.view(bsz, q_len, 1, self.qk_rope_head_dim).transpose(1, 2)
973
+ kv = (
974
+ self.kv_b_proj(self.kv_a_layernorm(compressed_kv))
975
+ .view(bsz, q_len, self.num_heads, self.qk_nope_head_dim + self.v_head_dim)
976
+ .transpose(1, 2)
977
+ )
978
+
979
+ k_nope, value_states = torch.split(
980
+ kv, [self.qk_nope_head_dim, self.v_head_dim], dim=-1
981
+ )
982
+ kv_seq_len = value_states.shape[-2]
983
+
984
+ if past_key_value is not None:
985
+ kv_seq_len += _get_cache_length(past_key_value, kv_seq_len, self.layer_idx)
986
+
987
+ cos, sin = self.rotary_emb(value_states, seq_len=kv_seq_len)
988
+ q_pe, k_pe = apply_rotary_pos_emb(q_pe, k_pe, cos, sin, position_ids)
989
+
990
+ query_states = k_pe.new_empty(bsz, self.num_heads, q_len, self.q_head_dim)
991
+ query_states[:, :, :, : self.qk_nope_head_dim] = q_nope
992
+ query_states[:, :, :, self.qk_nope_head_dim :] = q_pe
993
+
994
+ key_states = k_pe.new_empty(bsz, self.num_heads, q_len, self.q_head_dim)
995
+ key_states[:, :, :, : self.qk_nope_head_dim] = k_nope
996
+ key_states[:, :, :, self.qk_nope_head_dim :] = k_pe
997
+
998
+ if self.q_head_dim != self.v_head_dim:
999
+ value_states = F.pad(value_states, [0, self.q_head_dim - self.v_head_dim])
1000
+
1001
+ if past_key_value is not None:
1002
+ cache_kwargs = {"sin": sin, "cos": cos}
1003
+ key_states, value_states = past_key_value.update(
1004
+ key_states, value_states, self.layer_idx, cache_kwargs
1005
+ )
1006
+
1007
+ query_states = query_states.transpose(1, 2)
1008
+ key_states = key_states.transpose(1, 2)
1009
+ value_states = value_states.transpose(1, 2)
1010
+
1011
+ dropout_rate = self.attention_dropout if self.training else 0.0
1012
+
1013
+ input_dtype = query_states.dtype
1014
+ if input_dtype == torch.float32:
1015
+ if hasattr(self.config, "_pre_quantization_dtype"):
1016
+ target_dtype = self.config._pre_quantization_dtype
1017
+ elif torch.is_autocast_enabled():
1018
+ target_dtype = torch.get_autocast_gpu_dtype()
1019
+ else:
1020
+ target_dtype = (
1021
+ self.q_proj.weight.dtype
1022
+ if self.q_lora_rank is None
1023
+ else self.q_a_proj.weight.dtype
1024
+ )
1025
+
1026
+ logger.warning_once(
1027
+ f"The input hidden states seems to be silently casted in float32, this might be related to"
1028
+ f" the fact you have upcasted embedding or layer norm layers in float32. We will cast back the input in"
1029
+ f" {target_dtype}."
1030
+ )
1031
+
1032
+ query_states = query_states.to(target_dtype)
1033
+ key_states = key_states.to(target_dtype)
1034
+ value_states = value_states.to(target_dtype)
1035
+
1036
+ attn_output = self._flash_attention_forward(
1037
+ query_states,
1038
+ key_states,
1039
+ value_states,
1040
+ attention_mask,
1041
+ q_len,
1042
+ dropout=dropout_rate,
1043
+ softmax_scale=self.softmax_scale,
1044
+ )
1045
+ if self.q_head_dim != self.v_head_dim:
1046
+ attn_output = attn_output[:, :, :, : self.v_head_dim]
1047
+
1048
+ attn_output = attn_output.reshape(
1049
+ bsz, q_len, self.num_heads * self.v_head_dim
1050
+ ).contiguous()
1051
+ attn_output = self.o_proj(attn_output)
1052
+
1053
+ if not output_attentions:
1054
+ attn_weights = None
1055
+
1056
+ return attn_output, attn_weights, past_key_value
1057
+
1058
+ def _flash_attention_forward(
1059
+ self,
1060
+ query_states,
1061
+ key_states,
1062
+ value_states,
1063
+ attention_mask,
1064
+ query_length,
1065
+ dropout=0.0,
1066
+ softmax_scale=None,
1067
+ ):
1068
+ if not self._flash_attn_uses_top_left_mask:
1069
+ causal = self.is_causal
1070
+ else:
1071
+ causal = self.is_causal and query_length != 1
1072
+
1073
+ if attention_mask is not None:
1074
+ batch_size = query_states.shape[0]
1075
+ (
1076
+ query_states,
1077
+ key_states,
1078
+ value_states,
1079
+ indices_q,
1080
+ cu_seq_lens,
1081
+ max_seq_lens,
1082
+ ) = self._upad_input(
1083
+ query_states, key_states, value_states, attention_mask, query_length
1084
+ )
1085
+
1086
+ cu_seqlens_q, cu_seqlens_k = cu_seq_lens
1087
+ max_seqlen_in_batch_q, max_seqlen_in_batch_k = max_seq_lens
1088
+
1089
+ attn_output_unpad = flash_attn_varlen_func(
1090
+ query_states,
1091
+ key_states,
1092
+ value_states,
1093
+ cu_seqlens_q=cu_seqlens_q,
1094
+ cu_seqlens_k=cu_seqlens_k,
1095
+ max_seqlen_q=max_seqlen_in_batch_q,
1096
+ max_seqlen_k=max_seqlen_in_batch_k,
1097
+ dropout_p=dropout,
1098
+ softmax_scale=softmax_scale,
1099
+ causal=causal,
1100
+ )
1101
+
1102
+ attn_output = pad_input(
1103
+ attn_output_unpad, indices_q, batch_size, query_length
1104
+ )
1105
+ else:
1106
+ attn_output = flash_attn_func(
1107
+ query_states,
1108
+ key_states,
1109
+ value_states,
1110
+ dropout,
1111
+ softmax_scale=softmax_scale,
1112
+ causal=causal,
1113
+ )
1114
+
1115
+ return attn_output
1116
+
1117
+ def _upad_input(
1118
+ self, query_layer, key_layer, value_layer, attention_mask, query_length
1119
+ ):
1120
+ indices_k, cu_seqlens_k, max_seqlen_in_batch_k = _get_unpad_data(attention_mask)
1121
+ batch_size, kv_seq_len, num_key_value_heads, head_dim = key_layer.shape
1122
+
1123
+ key_layer = index_first_axis(
1124
+ key_layer.reshape(batch_size * kv_seq_len, num_key_value_heads, head_dim),
1125
+ indices_k,
1126
+ )
1127
+ value_layer = index_first_axis(
1128
+ value_layer.reshape(batch_size * kv_seq_len, num_key_value_heads, head_dim),
1129
+ indices_k,
1130
+ )
1131
+ if query_length == kv_seq_len:
1132
+ query_layer = index_first_axis(
1133
+ query_layer.reshape(batch_size * kv_seq_len, self.num_heads, head_dim),
1134
+ indices_k,
1135
+ )
1136
+ cu_seqlens_q = cu_seqlens_k
1137
+ max_seqlen_in_batch_q = max_seqlen_in_batch_k
1138
+ indices_q = indices_k
1139
+ elif query_length == 1:
1140
+ max_seqlen_in_batch_q = 1
1141
+ cu_seqlens_q = torch.arange(
1142
+ batch_size + 1, dtype=torch.int32, device=query_layer.device
1143
+ )
1144
+ indices_q = cu_seqlens_q[:-1]
1145
+ query_layer = query_layer.squeeze(1)
1146
+ else:
1147
+ attention_mask = attention_mask[:, -query_length:]
1148
+ query_layer, indices_q, cu_seqlens_q, max_seqlen_in_batch_q = unpad_input(
1149
+ query_layer, attention_mask
1150
+ )
1151
+
1152
+ return (
1153
+ query_layer,
1154
+ key_layer,
1155
+ value_layer,
1156
+ indices_q,
1157
+ (cu_seqlens_q, cu_seqlens_k),
1158
+ (max_seqlen_in_batch_q, max_seqlen_in_batch_k),
1159
+ )
1160
+
1161
+
1162
+ ATTENTION_CLASSES = {
1163
+ "eager": ScatterbrainMoonlightAttention,
1164
+ "flash_attention_2": ScatterbrainMoonlightFlashAttention2,
1165
+ }
1166
+
1167
+
1168
+ class ScatterbrainMoonlightDecoderLayer(nn.Module):
1169
+ def __init__(self, config: ScatterbrainMoonlightConfig, layer_idx: int):
1170
+ super().__init__()
1171
+ self.hidden_size = config.hidden_size
1172
+
1173
+ self.self_attn = ATTENTION_CLASSES[config._attn_implementation](
1174
+ config=config, layer_idx=layer_idx
1175
+ )
1176
+
1177
+ self.mlp = (
1178
+ ScatterbrainMoonlightMoE(config)
1179
+ if (
1180
+ config.n_routed_experts is not None
1181
+ and layer_idx >= config.first_k_dense_replace
1182
+ and layer_idx % config.moe_layer_freq == 0
1183
+ )
1184
+ else ScatterbrainMoonlightMLP(config)
1185
+ )
1186
+ self.input_layernorm = ScatterbrainMoonlightRMSNorm(
1187
+ config.hidden_size, eps=config.rms_norm_eps
1188
+ )
1189
+ self.post_attention_layernorm = ScatterbrainMoonlightRMSNorm(
1190
+ config.hidden_size, eps=config.rms_norm_eps
1191
+ )
1192
+
1193
+ def forward(
1194
+ self,
1195
+ hidden_states: torch.Tensor,
1196
+ attention_mask: Optional[torch.Tensor] = None,
1197
+ position_ids: Optional[torch.LongTensor] = None,
1198
+ past_key_value: Optional[Tuple[torch.Tensor]] = None,
1199
+ output_attentions: Optional[bool] = False,
1200
+ use_cache: Optional[bool] = False,
1201
+ **kwargs,
1202
+ ) -> Tuple[
1203
+ torch.FloatTensor, Optional[Tuple[torch.FloatTensor, torch.FloatTensor]]
1204
+ ]:
1205
+ if "padding_mask" in kwargs:
1206
+ warnings.warn(
1207
+ "Passing `padding_mask` is deprecated and will be removed in v4.37. Please make sure use `attention_mask` instead.`"
1208
+ )
1209
+ residual = hidden_states
1210
+
1211
+ hidden_states = self.input_layernorm(hidden_states)
1212
+
1213
+ hidden_states, self_attn_weights, present_key_value = self.self_attn(
1214
+ hidden_states=hidden_states,
1215
+ attention_mask=attention_mask,
1216
+ position_ids=position_ids,
1217
+ past_key_value=past_key_value,
1218
+ output_attentions=output_attentions,
1219
+ use_cache=use_cache,
1220
+ **kwargs,
1221
+ )
1222
+ hidden_states = residual + hidden_states
1223
+
1224
+ residual = hidden_states
1225
+ hidden_states = self.post_attention_layernorm(hidden_states)
1226
+ hidden_states = self.mlp(hidden_states)
1227
+ hidden_states = residual + hidden_states
1228
+
1229
+ outputs = (hidden_states,)
1230
+
1231
+ if output_attentions:
1232
+ outputs += (self_attn_weights,)
1233
+
1234
+ if use_cache:
1235
+ outputs += (present_key_value,)
1236
+
1237
+ return outputs
1238
+
1239
+
1240
+ DeepseekV3_START_DOCSTRING = r"""
1241
+ This model inherits from [`PreTrainedModel`]. Check the superclass documentation for the generic methods the
1242
+ library implements for all its model (such as downloading or saving, resizing the input embeddings, pruning heads
1243
+ etc.)
1244
+ """
1245
+
1246
+
1247
+ class ScatterbrainMoonlightPreTrainedModel(PreTrainedModel):
1248
+ config_class = ScatterbrainMoonlightConfig
1249
+ base_model_prefix = "model"
1250
+ supports_gradient_checkpointing = True
1251
+ _no_split_modules = ["ScatterbrainMoonlightDecoderLayer"]
1252
+ _skip_keys_device_placement = "past_key_values"
1253
+ _supports_flash_attn_2 = True
1254
+ _supports_cache_class = True
1255
+
1256
+ def _init_weights(self, module):
1257
+ std = self.config.initializer_range
1258
+ if isinstance(module, nn.Linear):
1259
+ module.weight.data.normal_(mean=0.0, std=std)
1260
+ if module.bias is not None:
1261
+ module.bias.data.zero_()
1262
+ elif isinstance(module, nn.Embedding):
1263
+ module.weight.data.normal_(mean=0.0, std=std)
1264
+ if module.padding_idx is not None:
1265
+ module.weight.data[module.padding_idx].zero_()
1266
+
1267
+
1268
+ class ScatterbrainMoonlightModel(ScatterbrainMoonlightPreTrainedModel):
1269
+ def __init__(self, config: ScatterbrainMoonlightConfig):
1270
+ super().__init__(config)
1271
+ self.padding_idx = config.pad_token_id
1272
+ self.vocab_size = config.vocab_size
1273
+
1274
+ self.embed_tokens = nn.Embedding(
1275
+ config.vocab_size, config.hidden_size, self.padding_idx
1276
+ )
1277
+ self.layers = nn.ModuleList(
1278
+ [
1279
+ ScatterbrainMoonlightDecoderLayer(config, layer_idx)
1280
+ for layer_idx in range(config.num_hidden_layers)
1281
+ ]
1282
+ )
1283
+ self._attn_implementation = config._attn_implementation
1284
+ self.norm = ScatterbrainMoonlightRMSNorm(config.hidden_size, eps=config.rms_norm_eps)
1285
+
1286
+ self.gradient_checkpointing = False
1287
+
1288
+ self.num_loop_iterations = getattr(config, 'num_loop_iterations', 1)
1289
+ self._num_virtual_layers = 1 + self.num_loop_iterations + 1
1290
+
1291
+ self.post_init()
1292
+
1293
+ def get_input_embeddings(self):
1294
+ return self.embed_tokens
1295
+
1296
+ def set_input_embeddings(self, value):
1297
+ self.embed_tokens = value
1298
+
1299
+ def _prepare_decoder_attention_mask(
1300
+ self, attention_mask, input_shape, inputs_embeds, past_key_values_length
1301
+ ):
1302
+ combined_attention_mask = None
1303
+ if input_shape[-1] > 1:
1304
+ combined_attention_mask = _prepare_4d_causal_attention_mask(
1305
+ attention_mask,
1306
+ input_shape,
1307
+ inputs_embeds,
1308
+ past_key_values_length,
1309
+ )
1310
+
1311
+ if attention_mask is not None and combined_attention_mask is not None:
1312
+ combined_attention_mask = combined_attention_mask.to(attention_mask.device)
1313
+
1314
+ return combined_attention_mask
1315
+
1316
+ def forward(
1317
+ self,
1318
+ input_ids: torch.LongTensor = None,
1319
+ attention_mask: Optional[torch.Tensor] = None,
1320
+ position_ids: Optional[torch.LongTensor] = None,
1321
+ past_key_values: Optional[List[torch.FloatTensor]] = None,
1322
+ inputs_embeds: Optional[torch.FloatTensor] = None,
1323
+ use_cache: Optional[bool] = None,
1324
+ output_attentions: Optional[bool] = None,
1325
+ output_hidden_states: Optional[bool] = None,
1326
+ return_dict: Optional[bool] = None,
1327
+ ) -> Union[Tuple, BaseModelOutputWithPast]:
1328
+ output_attentions = (
1329
+ output_attentions
1330
+ if output_attentions is not None
1331
+ else self.config.output_attentions
1332
+ )
1333
+ output_hidden_states = (
1334
+ output_hidden_states
1335
+ if output_hidden_states is not None
1336
+ else self.config.output_hidden_states
1337
+ )
1338
+ use_cache = use_cache if use_cache is not None else self.config.use_cache
1339
+
1340
+ return_dict = (
1341
+ return_dict if return_dict is not None else self.config.use_return_dict
1342
+ )
1343
+
1344
+ if input_ids is not None and inputs_embeds is not None:
1345
+ raise ValueError(
1346
+ "You cannot specify both input_ids and inputs_embeds at the same time"
1347
+ )
1348
+ elif input_ids is not None:
1349
+ batch_size, seq_length = input_ids.shape[:2]
1350
+ elif inputs_embeds is not None:
1351
+ batch_size, seq_length = inputs_embeds.shape[:2]
1352
+ else:
1353
+ raise ValueError("You have to specify either input_ids or inputs_embeds")
1354
+
1355
+ if self.gradient_checkpointing and self.training:
1356
+ if use_cache:
1357
+ logger.warning_once(
1358
+ "`use_cache=True` is incompatible with gradient checkpointing. Setting `use_cache=False`..."
1359
+ )
1360
+ use_cache = False
1361
+
1362
+ past_key_values_length = 0
1363
+
1364
+ if use_cache:
1365
+ if past_key_values is None:
1366
+ past_key_values = ExpandedDynamicCache(self._num_virtual_layers)
1367
+ elif not isinstance(past_key_values, ExpandedDynamicCache):
1368
+ past_key_values = ExpandedDynamicCache(self._num_virtual_layers)
1369
+ past_key_values_length = past_key_values.get_seq_length(0)
1370
+
1371
+ if position_ids is None:
1372
+ device = input_ids.device if input_ids is not None else inputs_embeds.device
1373
+ position_ids = torch.arange(
1374
+ past_key_values_length,
1375
+ seq_length + past_key_values_length,
1376
+ dtype=torch.long,
1377
+ device=device,
1378
+ )
1379
+ position_ids = position_ids.unsqueeze(0)
1380
+
1381
+ if inputs_embeds is None:
1382
+ inputs_embeds = self.embed_tokens(input_ids)
1383
+
1384
+ if self._attn_implementation == "flash_attention_2":
1385
+ attention_mask = (
1386
+ attention_mask
1387
+ if (attention_mask is not None and 0 in attention_mask)
1388
+ else None
1389
+ )
1390
+ else:
1391
+ attention_mask = self._prepare_decoder_attention_mask(
1392
+ attention_mask,
1393
+ (batch_size, seq_length),
1394
+ inputs_embeds,
1395
+ past_key_values_length,
1396
+ )
1397
+
1398
+ hidden_states = inputs_embeds
1399
+
1400
+ all_hidden_states = () if output_hidden_states else None
1401
+ all_self_attns = () if output_attentions else None
1402
+ next_decoder_cache = past_key_values if use_cache else None
1403
+
1404
+ virtual_layer_idx = 0
1405
+
1406
+ # Layer 0 (first layer, dense)
1407
+ if output_hidden_states:
1408
+ all_hidden_states += (hidden_states,)
1409
+
1410
+ layer = self.layers[0]
1411
+ layer.self_attn.layer_idx = virtual_layer_idx
1412
+
1413
+ layer_outputs = layer(
1414
+ hidden_states,
1415
+ attention_mask=attention_mask,
1416
+ position_ids=position_ids,
1417
+ past_key_value=past_key_values,
1418
+ output_attentions=output_attentions,
1419
+ use_cache=use_cache,
1420
+ )
1421
+ hidden_states = layer_outputs[0]
1422
+
1423
+ if output_attentions:
1424
+ all_self_attns += (layer_outputs[1],)
1425
+
1426
+ virtual_layer_idx += 1
1427
+
1428
+ # Layer 1 (middle layer, MoE) - looped num_loop_iterations times
1429
+ for loop_iter in range(self.num_loop_iterations):
1430
+ if output_hidden_states:
1431
+ all_hidden_states += (hidden_states,)
1432
+
1433
+ layer = self.layers[1]
1434
+ layer.self_attn.layer_idx = virtual_layer_idx
1435
+
1436
+ layer_outputs = layer(
1437
+ hidden_states,
1438
+ attention_mask=attention_mask,
1439
+ position_ids=position_ids,
1440
+ past_key_value=past_key_values,
1441
+ output_attentions=output_attentions,
1442
+ use_cache=use_cache,
1443
+ )
1444
+ hidden_states = layer_outputs[0]
1445
+
1446
+ if output_attentions:
1447
+ all_self_attns += (layer_outputs[1],)
1448
+
1449
+ virtual_layer_idx += 1
1450
+
1451
+ # Layer 2 (last layer, MoE)
1452
+ if output_hidden_states:
1453
+ all_hidden_states += (hidden_states,)
1454
+
1455
+ layer = self.layers[2]
1456
+ layer.self_attn.layer_idx = virtual_layer_idx
1457
+
1458
+ layer_outputs = layer(
1459
+ hidden_states,
1460
+ attention_mask=attention_mask,
1461
+ position_ids=position_ids,
1462
+ past_key_value=past_key_values,
1463
+ output_attentions=output_attentions,
1464
+ use_cache=use_cache,
1465
+ )
1466
+ hidden_states = layer_outputs[0]
1467
+
1468
+ if output_attentions:
1469
+ all_self_attns += (layer_outputs[1],)
1470
+
1471
+ hidden_states = self.norm(hidden_states)
1472
+
1473
+ if output_hidden_states:
1474
+ all_hidden_states += (hidden_states,)
1475
+
1476
+ if not return_dict:
1477
+ return tuple(
1478
+ v
1479
+ for v in [hidden_states, next_decoder_cache, all_hidden_states, all_self_attns]
1480
+ if v is not None
1481
+ )
1482
+ return BaseModelOutputWithPast(
1483
+ last_hidden_state=hidden_states,
1484
+ past_key_values=next_decoder_cache,
1485
+ hidden_states=all_hidden_states,
1486
+ attentions=all_self_attns,
1487
+ )
1488
+
1489
+
1490
+ class ScatterbrainMoonlightForCausalLM(ScatterbrainMoonlightPreTrainedModel):
1491
+ _tied_weights_keys = ["lm_head.weight"]
1492
+
1493
+ def __init__(self, config):
1494
+ super().__init__(config)
1495
+ self.model = ScatterbrainMoonlightModel(config)
1496
+ self.vocab_size = config.vocab_size
1497
+ self.lm_head = nn.Linear(config.hidden_size, config.vocab_size, bias=False)
1498
+
1499
+ self.post_init()
1500
+
1501
+ def get_input_embeddings(self):
1502
+ return self.model.embed_tokens
1503
+
1504
+ def set_input_embeddings(self, value):
1505
+ self.model.embed_tokens = value
1506
+
1507
+ def get_output_embeddings(self):
1508
+ return self.lm_head
1509
+
1510
+ def set_output_embeddings(self, new_embeddings):
1511
+ self.lm_head = new_embeddings
1512
+
1513
+ def set_decoder(self, decoder):
1514
+ self.model = decoder
1515
+
1516
+ def get_decoder(self):
1517
+ return self.model
1518
+
1519
+ def forward(
1520
+ self,
1521
+ input_ids: torch.LongTensor = None,
1522
+ attention_mask: Optional[torch.Tensor] = None,
1523
+ position_ids: Optional[torch.LongTensor] = None,
1524
+ past_key_values: Optional[List[torch.FloatTensor]] = None,
1525
+ inputs_embeds: Optional[torch.FloatTensor] = None,
1526
+ labels: Optional[torch.LongTensor] = None,
1527
+ use_cache: Optional[bool] = None,
1528
+ output_attentions: Optional[bool] = None,
1529
+ output_hidden_states: Optional[bool] = None,
1530
+ return_dict: Optional[bool] = None,
1531
+ ) -> Union[Tuple, CausalLMOutputWithPast]:
1532
+ output_attentions = (
1533
+ output_attentions
1534
+ if output_attentions is not None
1535
+ else self.config.output_attentions
1536
+ )
1537
+ output_hidden_states = (
1538
+ output_hidden_states
1539
+ if output_hidden_states is not None
1540
+ else self.config.output_hidden_states
1541
+ )
1542
+ return_dict = (
1543
+ return_dict if return_dict is not None else self.config.use_return_dict
1544
+ )
1545
+
1546
+ outputs = self.model(
1547
+ input_ids=input_ids,
1548
+ attention_mask=attention_mask,
1549
+ position_ids=position_ids,
1550
+ past_key_values=past_key_values,
1551
+ inputs_embeds=inputs_embeds,
1552
+ use_cache=use_cache,
1553
+ output_attentions=output_attentions,
1554
+ output_hidden_states=output_hidden_states,
1555
+ return_dict=return_dict,
1556
+ )
1557
+
1558
+ hidden_states = outputs[0]
1559
+ logits = self.lm_head(hidden_states)
1560
+ logits = logits.float()
1561
+
1562
+ loss = None
1563
+ if labels is not None:
1564
+ shift_logits = logits[..., :-1, :].contiguous()
1565
+ shift_labels = labels[..., 1:].contiguous()
1566
+ loss_fct = CrossEntropyLoss()
1567
+ shift_logits = shift_logits.view(-1, self.config.vocab_size)
1568
+ shift_labels = shift_labels.view(-1)
1569
+ shift_labels = shift_labels.to(shift_logits.device)
1570
+ loss = loss_fct(shift_logits, shift_labels)
1571
+
1572
+ if not return_dict:
1573
+ output = (logits,) + outputs[1:]
1574
+ return (loss,) + output if loss is not None else output
1575
+
1576
+ return CausalLMOutputWithPast(
1577
+ loss=loss,
1578
+ logits=logits,
1579
+ past_key_values=outputs.past_key_values,
1580
+ hidden_states=outputs.hidden_states,
1581
+ attentions=outputs.attentions,
1582
+ )
1583
+
1584
+ def prepare_inputs_for_generation(
1585
+ self,
1586
+ input_ids,
1587
+ past_key_values=None,
1588
+ attention_mask=None,
1589
+ inputs_embeds=None,
1590
+ **kwargs,
1591
+ ):
1592
+ if past_key_values is not None:
1593
+ past_length = past_key_values.get_seq_length(0)
1594
+
1595
+ if input_ids.shape[1] > past_length:
1596
+ remove_prefix_length = past_length
1597
+ else:
1598
+ remove_prefix_length = input_ids.shape[1] - 1
1599
+
1600
+ input_ids = input_ids[:, remove_prefix_length:]
1601
+
1602
+ position_ids = kwargs.get("position_ids", None)
1603
+ if attention_mask is not None and position_ids is None:
1604
+ position_ids = attention_mask.long().cumsum(-1) - 1
1605
+ position_ids.masked_fill_(attention_mask == 0, 1)
1606
+ if past_key_values is not None:
1607
+ position_ids = position_ids[:, -input_ids.shape[1] :]
1608
+
1609
+ if inputs_embeds is not None and past_key_values is None:
1610
+ model_inputs = {"inputs_embeds": inputs_embeds}
1611
+ else:
1612
+ model_inputs = {"input_ids": input_ids}
1613
+
1614
+ model_inputs.update(
1615
+ {
1616
+ "position_ids": position_ids,
1617
+ "past_key_values": past_key_values,
1618
+ "use_cache": kwargs.get("use_cache"),
1619
+ "attention_mask": attention_mask,
1620
+ }
1621
+ )
1622
+ return model_inputs
1623
+
1624
+ @staticmethod
1625
+ def _reorder_cache(past_key_values, beam_idx):
1626
+ past_key_values.reorder_cache(beam_idx)
1627
+ return past_key_values
tiktoken.model ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:b6c497a7469b33ced9c38afb1ad6e47f03f5e5dc05f15930799210ec050c5103
3
+ size 2795286
tokenization_moonshot.py ADDED
@@ -0,0 +1,301 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import os
2
+ import tiktoken
3
+
4
+ from logging import getLogger
5
+ from pathlib import Path
6
+ from typing import (
7
+ cast,
8
+ Tuple,
9
+ Dict,
10
+ Iterator,
11
+ List,
12
+ Union,
13
+ Optional,
14
+ )
15
+ from shutil import copyfile
16
+ import numpy as np
17
+ from tiktoken.load import load_tiktoken_bpe
18
+ from tokenizers import AddedToken
19
+ from transformers import PreTrainedTokenizerFast
20
+ from transformers.tokenization_utils import PreTrainedTokenizer
21
+ from transformers.models.gpt2.tokenization_gpt2 import bytes_to_unicode
22
+
23
+
24
+
25
+ logger = getLogger(__name__)
26
+ VOCAB_FILES_NAMES = {"vocab_file": "tiktoken.model"}
27
+ SPIECE_UNDERLINE = "▁"
28
+
29
+ class TikTokenTokenizer(PreTrainedTokenizer):
30
+ """
31
+ Tokenizing and encoding/decoding text using the Tiktoken tokenizer. See megatron/tokenizer/tiktoken_tokenizer.py.
32
+
33
+ This tokenizer inherits from [`PreTrainedTokenizer`] which contains most of the main methods. Users should refer to
34
+ this superclass for more information regarding those methods.
35
+
36
+ Args:
37
+ vocab_file (`str`):
38
+ The path to the Tiktoken model file.
39
+ bos_token (`str` or `tokenizers.AddedToken`, *optional*, defaults to `"<|begin_of_text|>",`):
40
+ The beginning of sequence token that was used during pretraining. Can be used a sequence classifier token.
41
+ eos_token (`str` or `tokenizers.AddedToken`, *optional*, defaults to `"<|end_of_text|>"`):
42
+ The end of sequence token.
43
+ unk_token (`str` or `tokenizers.AddedToken`, *optional*, defaults to `"<|reserved_special_token_249|>"`):
44
+ The unknown token. A token that is not in the vocabulary cannot be converted to an ID and is set to be this
45
+ token instead. The second to last item in special_tokens.
46
+ pad_token (`str` or `tokenizers.AddedToken`, *optional*, defaults to `"<|reserved_special_token_250|>"`):
47
+ The token used for padding, for example when batching sequences of different lengths.
48
+ additional_special_tokens (list of `str`, *optional*):
49
+ A tuple or a list of additional tokens, which will be marked as `special`, meaning that they will be
50
+ skipped when decoding if `skip_special_tokens` is set to `True`.
51
+ """
52
+
53
+ vocab_files_names = VOCAB_FILES_NAMES
54
+
55
+ model_input_names = ["input_ids", "attention_mask"]
56
+
57
+ special_tokens: Dict[str, int]
58
+
59
+ num_reserved_special_tokens = 256
60
+
61
+ pat_str = "|".join(
62
+ [
63
+ r"""[\p{Han}]+""",
64
+ r"""[^\r\n\p{L}\p{N}]?[\p{Lu}\p{Lt}\p{Lm}\p{Lo}\p{M}&&[^\p{Han}]]*[\p{Ll}\p{Lm}\p{Lo}\p{M}&&[^\p{Han}]]+(?i:'s|'t|'re|'ve|'m|'ll|'d)?""",
65
+ r"""[^\r\n\p{L}\p{N}]?[\p{Lu}\p{Lt}\p{Lm}\p{Lo}\p{M}&&[^\p{Han}]]+[\p{Ll}\p{Lm}\p{Lo}\p{M}&&[^\p{Han}]]*(?i:'s|'t|'re|'ve|'m|'ll|'d)?""",
66
+ r"""\p{N}{1,3}""",
67
+ r""" ?[^\s\p{L}\p{N}]+[\r\n]*""",
68
+ r"""\s*[\r\n]+""",
69
+ r"""\s+(?!\S)""",
70
+ r"""\s+""",
71
+ ]
72
+ )
73
+
74
+ def __init__(
75
+ self,
76
+ vocab_file,
77
+ bos_token: Union[str, AddedToken]="[BOS]",
78
+ eos_token: Union[str, AddedToken]="[EOS]",
79
+ unk_token: Union[str, AddedToken]="[UNK]",
80
+ pad_token: Union[str, AddedToken]="[PAD]",
81
+ additional_special_tokens: Optional[List[str]] = None,
82
+ added_tokens_decoder: Optional[dict] = None,
83
+ **kwargs,
84
+ ):
85
+ assert os.path.isfile(vocab_file), vocab_file
86
+ if additional_special_tokens is None:
87
+ additional_special_tokens = [
88
+ "<|im_end|>",
89
+ "<|im_middle|>",
90
+ "<|im_user|>",
91
+ "<|im_assistant|>",
92
+ "<|im_system|>"
93
+ ]
94
+ special_tokens_mapping = {i: added_tokens_decoder[i].content for i in added_tokens_decoder}
95
+
96
+ special_tokens = [str(bos_token), str(eos_token)] + additional_special_tokens + [str(unk_token), str(pad_token)]
97
+
98
+ self.vocab_file = vocab_file
99
+ mergeable_ranks = load_tiktoken_bpe(vocab_file)
100
+ num_base_tokens = len(mergeable_ranks)
101
+ self.special_tokens = {
102
+ special_tokens_mapping.get(i, f"<|reserved_token_{i}|>"): i \
103
+ for i in range(num_base_tokens, num_base_tokens + self.num_reserved_special_tokens + 2)
104
+ }
105
+
106
+ self.model = tiktoken.Encoding(
107
+ name=Path(vocab_file).name,
108
+ pat_str=self.pat_str,
109
+ mergeable_ranks=mergeable_ranks,
110
+ special_tokens=self.special_tokens,
111
+ )
112
+ logger.info(f"Reloaded tiktoken model from {vocab_file}")
113
+
114
+ self.n_words: int = self.model.n_vocab
115
+ # BOS / EOS token IDs
116
+ self.bos_id: int = self.special_tokens[str(bos_token)]
117
+ self.eos_id: int = self.special_tokens[str(eos_token)]
118
+ logger.info(
119
+ f"#words: {self.n_words} - BOS ID: {self.bos_id} - EOS ID: {self.eos_id}"
120
+ )
121
+
122
+ self.pad_id: int = self.special_tokens[str(pad_token)]
123
+ self.unk_id: int = self.special_tokens[str(unk_token)]
124
+
125
+ self.byte_encoder = bytes_to_unicode()
126
+ self.byte_decoder = {v: k for k, v in self.byte_encoder.items()}
127
+
128
+ self.decoder = {}
129
+ for i in range(self.n_words):
130
+ # Taken from https://gist.github.com/xenova/a452a6474428de0182b17605a98631ee
131
+ decoding = ''.join([
132
+ self.byte_encoder[ord(char)] for char in
133
+ self.model.decode_single_token_bytes(i).decode('latin-1')
134
+ ])
135
+ self.decoder[i] = decoding
136
+
137
+ self.encoder = {}
138
+ for i in range(self.n_words):
139
+ if i in self.decoder:
140
+ self.encoder[self.decoder[i]] = i
141
+
142
+ super().__init__(
143
+ bos_token=bos_token,
144
+ eos_token=eos_token,
145
+ unk_token=unk_token,
146
+ pad_token=pad_token,
147
+ additional_special_tokens=additional_special_tokens,
148
+ **kwargs,
149
+ )
150
+ self.all_special_ids_set = set(self.all_special_ids)
151
+
152
+ def encode(
153
+ self,
154
+ text: str,
155
+ allow_special_tokens: bool = True,
156
+ **kwargs
157
+ ) -> List[int]:
158
+ """
159
+ Encodes a string into a list of token IDs.
160
+
161
+ Args:
162
+ text (str): The input string to be encoded.
163
+
164
+ Returns:
165
+ list[int]: A list of token IDs.
166
+ """
167
+ # If there are other args, we should call super().encode because there are a lot of code
168
+ # to handle those args. supper().encode finally will call _tokenize and _convert_token_to_id.
169
+ if len(kwargs) > 0:
170
+ return super().encode(text, **kwargs)
171
+
172
+ assert type(text) is str
173
+
174
+ # The tiktoken tokenizer can handle <=400k chars without
175
+ # pyo3_runtime.PanicException.
176
+ TIKTOKEN_MAX_ENCODE_CHARS = 400_000
177
+
178
+ # https://github.com/openai/tiktoken/issues/195
179
+ # Here we iterate over subsequences and split if we exceed the limit
180
+ # of max consecutive non-whitespace or whitespace characters.
181
+ MAX_NO_WHITESPACES_CHARS = 25_000
182
+
183
+ substrs = (
184
+ substr
185
+ for i in range(0, len(text), TIKTOKEN_MAX_ENCODE_CHARS)
186
+ for substr in self._split_whitespaces_or_nonwhitespaces(
187
+ text[i : i + TIKTOKEN_MAX_ENCODE_CHARS], MAX_NO_WHITESPACES_CHARS
188
+ )
189
+ )
190
+ t: List[int] = []
191
+ for substr in substrs:
192
+ if allow_special_tokens:
193
+ t.extend(
194
+ # we should consider special token as a common token
195
+ self.model.encode(
196
+ substr,
197
+ allowed_special="all",
198
+ )
199
+ )
200
+ else:
201
+ t.extend(
202
+ # we should consider special token as a common token
203
+ self.model.encode(
204
+ substr,
205
+ disallowed_special=(),
206
+ )
207
+ )
208
+ return t
209
+
210
+ def decode(
211
+ self,
212
+ token_ids: Union[int, List[int]],
213
+ **kwargs
214
+ ) -> str:
215
+ """
216
+ Decodes a list of token IDs into a string.
217
+
218
+ Args:
219
+ t (List[int]): The list of token IDs to be decoded.
220
+
221
+ Returns:
222
+ str: The decoded string.
223
+ """
224
+ # If there are other args, we should call super().decode because there are a lot of code
225
+ # to handle those args. supper().encode finally will call convert_tokens_to_string and _convert_id_to_token.
226
+ if len(kwargs) > 0:
227
+ return super().decode(token_ids, **kwargs)
228
+
229
+ if type(token_ids) is int:
230
+ token_ids = [token_ids]
231
+
232
+ return self.model.decode(cast(List[int], token_ids))
233
+
234
+ @staticmethod
235
+ def _split_whitespaces_or_nonwhitespaces(
236
+ s: str, max_consecutive_slice_len: int
237
+ ) -> Iterator[str]:
238
+ """
239
+ Splits the string `s` so that each substring contains no more than `max_consecutive_slice_len`
240
+ consecutive whitespaces or consecutive non-whitespaces.
241
+ """
242
+ current_slice_len = 0
243
+ current_slice_is_space = s[0].isspace() if len(s) > 0 else False
244
+ slice_start = 0
245
+
246
+ for i in range(len(s)):
247
+ is_now_space = s[i].isspace()
248
+
249
+ if current_slice_is_space ^ is_now_space:
250
+ current_slice_len = 1
251
+ current_slice_is_space = is_now_space
252
+ else:
253
+ current_slice_len += 1
254
+ if current_slice_len > max_consecutive_slice_len:
255
+ yield s[slice_start:i]
256
+ slice_start = i
257
+ current_slice_len = 1
258
+ yield s[slice_start:]
259
+
260
+
261
+ """ ----- Below are the abstract methods required by PreTrainedTokenizer ----- """
262
+ @property
263
+ def vocab_size(self) -> int:
264
+ return self.n_words
265
+
266
+ def get_vocab(self) -> Dict[str, int]:
267
+ return self.encoder
268
+
269
+ def _tokenize(self, text: str, **kwargs) -> List[str]:
270
+ return [
271
+ self.decoder[t]
272
+ for t in self.encode(text)
273
+ ]
274
+
275
+ def _convert_token_to_id(self, token: str) -> int:
276
+ return self.encoder.get(token, self.unk_id)
277
+
278
+ def _convert_id_to_token(self, index: int) -> str:
279
+ return self.decoder.get(index)
280
+
281
+ @staticmethod
282
+ def clean_up_tokenization(out_string: str) -> str:
283
+ return out_string
284
+
285
+ def convert_tokens_to_string(self, tokens: List[str]) -> str:
286
+ text = ''.join(tokens).replace(SPIECE_UNDERLINE, '')
287
+ text = bytearray([self.byte_decoder[c] for c in text]).decode('utf-8', 'replace')
288
+ return text
289
+
290
+ def save_vocabulary(self, save_directory: str, filename_prefix: Optional[str] = None) -> Tuple[str]:
291
+ if not os.path.isdir(save_directory):
292
+ logger.error(f"Vocabulary path ({save_directory}) should be a directory")
293
+ return
294
+ out_vocab_file = os.path.join(
295
+ save_directory, (filename_prefix + "-" if filename_prefix else "") + VOCAB_FILES_NAMES["vocab_file"]
296
+ )
297
+
298
+ if os.path.abspath(self.vocab_file) != os.path.abspath(out_vocab_file) and os.path.isfile(self.vocab_file):
299
+ copyfile(self.vocab_file, out_vocab_file)
300
+
301
+ return (out_vocab_file,)
tokenizer_config.json ADDED
@@ -0,0 +1,98 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "added_tokens_decoder": {
3
+ "163584": {
4
+ "content": "[BOS]",
5
+ "lstrip": false,
6
+ "normalized": false,
7
+ "rstrip": false,
8
+ "single_word": false,
9
+ "special": true
10
+ },
11
+ "163585": {
12
+ "content": "[EOS]",
13
+ "lstrip": false,
14
+ "normalized": false,
15
+ "rstrip": false,
16
+ "single_word": false,
17
+ "special": true
18
+ },
19
+ "163586": {
20
+ "content": "<|im_end|>",
21
+ "lstrip": false,
22
+ "normalized": false,
23
+ "rstrip": false,
24
+ "single_word": false,
25
+ "special": true
26
+ },
27
+ "163601": {
28
+ "content": "<|im_middle|>",
29
+ "lstrip": false,
30
+ "normalized": false,
31
+ "rstrip": false,
32
+ "single_word": false,
33
+ "special": true
34
+ },
35
+ "163587": {
36
+ "content": "<|im_user|>",
37
+ "lstrip": false,
38
+ "normalized": false,
39
+ "rstrip": false,
40
+ "single_word": false,
41
+ "special": true
42
+ },
43
+ "163588": {
44
+ "content": "<|im_assistant|>",
45
+ "lstrip": false,
46
+ "normalized": false,
47
+ "rstrip": false,
48
+ "single_word": false,
49
+ "special": true
50
+ },
51
+ "163594": {
52
+ "content": "<|im_system|>",
53
+ "lstrip": false,
54
+ "normalized": false,
55
+ "rstrip": false,
56
+ "single_word": false,
57
+ "special": true
58
+ },
59
+ "163838": {
60
+ "content": "[PAD]",
61
+ "lstrip": false,
62
+ "normalized": false,
63
+ "rstrip": false,
64
+ "single_word": false,
65
+ "special": true
66
+ },
67
+ "163839": {
68
+ "content": "[UNK]",
69
+ "lstrip": false,
70
+ "normalized": false,
71
+ "rstrip": false,
72
+ "single_word": false,
73
+ "special": true
74
+ }
75
+ },
76
+ "additional_special_tokens": [
77
+ "<|im_end|>",
78
+ "<|im_user|>",
79
+ "<|im_assistant|>",
80
+ "<|im_system|>",
81
+ "<|im_middle|>"
82
+ ],
83
+ "bos_token": "[BOS]",
84
+ "clean_up_tokenization_spaces": false,
85
+ "eos_token": "[EOS]",
86
+ "extra_special_tokens": {},
87
+ "model_max_length": 1048576,
88
+ "pad_token": "[PAD]",
89
+ "unk_token": "[UNK]",
90
+ "tokenizer_class": "TikTokenTokenizer",
91
+ "chat_template":"{%- for message in messages -%}{%- if loop.first and messages[0]['role'] != 'system' -%}<|im_system|>system<|im_middle|>You are a helpful assistant<|im_end|>{%- endif -%}{%- if message['role'] == 'system' -%}<|im_system|>{%- endif -%}{%- if message['role'] == 'user' -%}<|im_user|>{%- endif -%}{%- if message['role'] == 'assistant' -%}<|im_assistant|>{%- endif -%}{{ message['role'] }}<|im_middle|>{{message['content']}}<|im_end|>{%- endfor -%}{%- if add_generation_prompt -%}<|im_assistant|>assistant<|im_middle|>{%- endif -%}",
92
+ "auto_map": {
93
+ "AutoTokenizer": [
94
+ "tokenization_moonshot.TikTokenTokenizer",
95
+ null
96
+ ]
97
+ }
98
+ }