avlp12 commited on
Commit
0c90f52
·
verified ·
1 Parent(s): ee782ef

Add files using upload-large-folder tool

Browse files
.gitattributes CHANGED
@@ -33,3 +33,4 @@ saved_model/**/* filter=lfs diff=lfs merge=lfs -text
33
  *.zip filter=lfs diff=lfs merge=lfs -text
34
  *.zst filter=lfs diff=lfs merge=lfs -text
35
  *tfevents* filter=lfs diff=lfs merge=lfs -text
 
 
33
  *.zip filter=lfs diff=lfs merge=lfs -text
34
  *.zst filter=lfs diff=lfs merge=lfs -text
35
  *tfevents* filter=lfs diff=lfs merge=lfs -text
36
+ tokenizer.json filter=lfs diff=lfs merge=lfs -text
README.md ADDED
@@ -0,0 +1,7 @@
 
 
 
 
 
 
 
 
1
+ ---
2
+ language: en
3
+ tags:
4
+ - mlx
5
+ pipeline_tag: text-generation
6
+ library_name: mlx
7
+ ---
chat_template.jinja ADDED
@@ -0,0 +1,157 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {%- macro visible_text(content) -%}
2
+ {%- if content is string -%}
3
+ {{- content -}}
4
+ {%- elif content is iterable and content is not mapping -%}
5
+ {%- for item in content -%}
6
+ {%- if item is mapping and item.type == 'text' -%}
7
+ {{- item.text -}}
8
+ {%- elif item is string -%}
9
+ {{- item -}}
10
+ {%- endif -%}
11
+ {%- endfor -%}
12
+ {%- else -%}
13
+ {{- content -}}
14
+ {%- endif -%}
15
+ {%- endmacro -%}
16
+
17
+ {{- '<|beginoftext|>' -}}
18
+
19
+ {%- set ns = namespace(has_system=false, last_user_index=-1, last_assistant_index=-1) -%}
20
+ {%- if messages | length > 0 and messages[0].role == 'system' -%}
21
+ {%- set ns.has_system = true -%}
22
+ {%- endif -%}
23
+ {%- for m in messages -%}
24
+ {%- if m.role == 'user' -%}
25
+ {%- set ns.last_user_index = loop.index0 -%}
26
+ {%- elif m.role == 'assistant' -%}
27
+ {%- set ns.last_assistant_index = loop.index0 -%}
28
+ {%- endif -%}
29
+ {%- endfor -%}
30
+
31
+ {#- ── System / Tools block ── -#}
32
+ {%- if tools is iterable and tools | length > 0 -%}
33
+ {{- '<|startofturn|><|system|>' -}}
34
+ {{- '# Tools\n\nYou may call one or more functions to assist with the user query.\n\n' -}}
35
+ {{- 'You are provided with function signatures within <tools></tools> XML tags:\n\n<tools>' -}}
36
+ {%- for tool in tools -%}
37
+ {%- if tool.function is defined -%}
38
+ {%- set tool = tool.function -%}
39
+ {%- endif -%}
40
+ {{- '\n' ~ (tool | tojson) -}}
41
+ {%- endfor -%}
42
+ {{- '\n</tools>' -}}
43
+ {{- '\n\nFor each function call, output in JSON within <tool_call> tags:\n' -}}
44
+ {%- for tool in tools -%}
45
+ {%- if tool.function is defined -%}
46
+ {%- set tool = tool.function -%}
47
+ {%- endif -%}
48
+ {%- set _props = tool.parameters.properties if (tool.parameters is defined and tool.parameters.properties is defined) else {} -%}
49
+ {{- '\n<tool_call>{"name": "' ~ tool.name ~ '", "arguments": {' -}}
50
+ {%- set _keys = _props | list -%}
51
+ {%- for k in _keys -%}
52
+ {{- '"' ~ k ~ '": <' ~ k ~ '>' -}}
53
+ {%- if not loop.last -%}{{- ', ' -}}{%- endif -%}
54
+ {%- endfor -%}
55
+ {{- '}}</tool_call>' -}}
56
+ {%- endfor -%}
57
+ {%- if ns.has_system -%}
58
+ {{- '\n\n' ~ visible_text(messages[0].content) -}}
59
+ {%- endif -%}
60
+ {{- '<|endofturn|>' -}}
61
+ {%- elif ns.has_system -%}
62
+ {{- '<|startofturn|><|system|>' ~ visible_text(messages[0].content) ~ '<|endofturn|>' -}}
63
+ {%- endif -%}
64
+
65
+ {#- ── Conversation turns ── -#}
66
+ {%- for m in messages -%}
67
+
68
+ {#- [Fix 1] continue 대신 if/elif 체인으로 첫 system 스킵 -#}
69
+ {%- if loop.index0 == 0 and m.role == 'system' -%}
70
+ {#- already rendered above, skip -#}
71
+
72
+ {#- [Fix 2] 중간에 나오는 system 메시지도 처리 -#}
73
+ {%- elif m.role == 'system' -%}
74
+ {{- '<|startofturn|><|system|>' ~ visible_text(m.content) ~ '<|endofturn|>' -}}
75
+
76
+ {%- elif m.role == 'user' -%}
77
+ {{- '<|startofturn|><|user|>' -}}
78
+ {%- if m.references is defined and m.references -%}
79
+ {{- '<|reference|>' ~ m.references ~ '\n' -}}
80
+ {%- endif -%}
81
+ {{- visible_text(m.content) -}}
82
+ {{- '<|endofturn|>' -}}
83
+
84
+ {%- elif m.role == 'assistant' -%}
85
+ {{- '<|startofturn|><|assistant|>' -}}
86
+
87
+ {#- [순서 정책] think → plan → content → tool_calls -#}
88
+
89
+ {#- Reasoning block -#}
90
+ {%- set _content = visible_text(m.content) -%}
91
+ {%- set _reasoning = '' -%}
92
+ {%- if m.reasoning_content is string -%}
93
+ {%- set _reasoning = m.reasoning_content -%}
94
+ {%- elif '</think>' in _content -%}
95
+ {%- set _reasoning = _content.split('</think>')[0].split('<think>')[-1].strip() -%}
96
+ {%- set _content = _content.split('</think>', 1)[-1].lstrip('\n') -%}
97
+ {%- endif -%}
98
+ {%- set _has_tools = (tools is defined and tools is iterable and tools | length > 0) -%}
99
+ {%- set _emit_think = _reasoning and (_has_tools or loop.index0 == ns.last_assistant_index) -%}
100
+ {%- if _emit_think -%}
101
+ {{- '<think>' ~ _reasoning.strip() ~ '</think>' -}}
102
+ {%- endif -%}
103
+
104
+ {#- Text content -#}
105
+ {%- if _content.strip() -%}
106
+ {{- _content.strip() -}}
107
+ {%- endif -%}
108
+
109
+ {#- Tool calls — IDs are rendered for intermediate assistant turns
110
+ (context for call↔response correlation) but omitted for the last
111
+ assistant turn (prediction target — model should not learn to
112
+ generate IDs). After multi-turn data expansion, intermediate turns
113
+ become GRAY context and the last turn is GREEN. -#}
114
+ {%- if m.tool_calls is defined and m.tool_calls -%}
115
+ {%- set _is_last_assistant = (loop.index0 == ns.last_assistant_index) and not add_generation_prompt -%}
116
+ {%- for tc in m.tool_calls -%}
117
+ {%- set _tc_id = tc.id if (tc.id is defined and not _is_last_assistant) else none -%}
118
+ {%- if tc.function is defined -%}
119
+ {%- set tc = tc.function -%}
120
+ {%- endif -%}
121
+ {%- set _id_suffix = ', "id": ' ~ (_tc_id | tojson) if _tc_id is not none else '' -%}
122
+ {%- if tc.arguments is not defined or not tc.arguments or tc.arguments == "" -%}
123
+ {{- '\n<tool_call>' ~ '{"name": "' ~ tc.name ~ '", "arguments": ' ~ null ~ _id_suffix ~ '}' ~ '</tool_call>' -}}
124
+ {%- elif tc.arguments is string -%}
125
+ {{- '\n<tool_call>' ~ '{"name": "' ~ tc.name ~ '", "arguments": ' ~ tc.arguments ~ _id_suffix ~ '}' ~ '</tool_call>' -}}
126
+ {%- else -%}
127
+ {{- '\n<tool_call>' ~ '{"name": "' ~ tc.name ~ '", "arguments": ' ~ (tc.arguments | tojson) ~ _id_suffix ~ '}' ~ '</tool_call>' -}}
128
+ {%- endif -%}
129
+ {%- endfor -%}
130
+ {%- endif -%}
131
+
132
+ {{- '<|endofturn|>' -}}
133
+
134
+ {%- elif m.role == 'tool' -%}
135
+ {#- [Fix 3] loop.previtem/nextitem으로 인덱스 오버플로 제거 -#}
136
+ {%- if loop.first or loop.previtem.role != 'tool' -%}
137
+ {{- '<|startofturn|><|tool|>' -}}
138
+ {%- endif -%}
139
+ {{- '<tool_response>' ~ ({"tool_call_id": m.tool_call_id, "content": m.content} | tojson) ~ '</tool_response>' -}}
140
+ {%- if loop.last or loop.nextitem.role != 'tool' -%}
141
+ {{- '<|endofturn|>' -}}
142
+ {%- endif -%}
143
+
144
+ {%- endif -%}
145
+ {%- endfor -%}
146
+
147
+ {#- ── Generation prompt ── -#}
148
+ {%- if add_generation_prompt -%}
149
+ {{- '<|startofturn|><|assistant|>' -}}
150
+ {%- if enable_thinking is defined and not enable_thinking -%}
151
+ {{- '<think></think>' -}}
152
+ {%- else -%}
153
+ {{- '<think>' -}}
154
+ {%- endif -%}
155
+ {%- else -%}
156
+ {{- '<|endoftext|>' -}}
157
+ {%- endif -%}
config.json ADDED
The diff for this file is too large to render. See raw diff
 
configuration_motif.py ADDED
@@ -0,0 +1,294 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import torch
2
+ from transformers.configuration_utils import PretrainedConfig
3
+ from transformers.utils import logging
4
+
5
+ logger = logging.get_logger(__name__)
6
+
7
+
8
+ class MotifConfig(PretrainedConfig):
9
+ r"""
10
+ This is the configuration class to store the configuration of a [`MotifModel`]. It is used to instantiate a
11
+ Motif model according to the specified arguments, defining the model architecture.
12
+ Configuration objects inherit from [`PretrainedConfig`] and can be used to control the model outputs. Read the
13
+ documentation from [`PretrainedConfig`] for more information.
14
+ Args:
15
+ vocab_size (`int`, *optional*, defaults to 151936):
16
+ Vocabulary size of the Motif model. Defines the number of different tokens that can be represented by the
17
+ `inputs_ids` passed when calling [`MotifModel`]
18
+ hidden_size (`int`, *optional*, defaults to 4096):
19
+ Dimension of the hidden representations.
20
+ intermediate_size (`int`, *optional*, defaults to 22016):
21
+ Dimension of the MLP representations.
22
+ num_hidden_layers (`int`, *optional*, defaults to 32):
23
+ Number of hidden layers in the Transformer encoder.
24
+ num_attention_heads (`int`, *optional*, defaults to 32):
25
+ Number of attention heads for each attention layer in the Transformer encoder.
26
+ num_key_value_heads (`int`, *optional*, defaults to 32):
27
+ This is the number of key_value heads that should be used to implement Grouped Query Attention. If
28
+ `num_key_value_heads=num_attention_heads`, the model will use Multi Head Attention (MHA), if
29
+ `num_key_value_heads=1` the model will use Multi Query Attention (MQA) otherwise GQA is used. When
30
+ converting a multi-head checkpoint to a GQA checkpoint, each group key and value head should be constructed
31
+ by meanpooling all the original heads within that group. For more details checkout [this
32
+ paper](https://arxiv.org/pdf/2305.13245.pdf). If it is not specified, will default to `32`.
33
+ hidden_act (`str` or `function`, *optional*, defaults to `"silu"`):
34
+ The non-linear activation function (function or string) in the decoder.
35
+ max_position_embeddings (`int`, *optional*, defaults to 32768):
36
+ The maximum sequence length that this model might ever be used with.
37
+ initializer_range (`float`, *optional*, defaults to 0.02):
38
+ The standard deviation of the truncated_normal_initializer for initializing all weight matrices.
39
+ rms_norm_eps (`float`, *optional*, defaults to 1e-06):
40
+ The epsilon used by the rms normalization layers.
41
+ use_cache (`bool`, *optional*, defaults to `True`):
42
+ Whether or not the model should return the last key/values attentions (not used by all models). Only
43
+ relevant if `config.is_decoder=True`.
44
+ tie_word_embeddings (`bool`, *optional*, defaults to `False`):
45
+ Whether the model's input and output word embeddings should be tied.
46
+ rope_theta (`float`, *optional*, defaults to 1000000.0):
47
+ The base period of the RoPE embeddings.
48
+ rope_scaling (`Dict`, *optional*):
49
+ Dictionary containing the scaling configuration for the RoPE embeddings. NOTE: if you apply new rope type
50
+ and you expect the model to work on longer `max_position_embeddings`, we recommend you to update this value
51
+ accordingly.
52
+ Expected contents:
53
+ `rope_type` (`str`):
54
+ The sub-variant of RoPE to use. Can be one of ['default', 'linear', 'dynamic', 'yarn', 'longrope',
55
+ 'llama3'], with 'default' being the original RoPE implementation.
56
+ `factor` (`float`, *optional*):
57
+ Used with all rope types except 'default'. The scaling factor to apply to the RoPE embeddings. In
58
+ most scaling types, a `factor` of x will enable the model to handle sequences of length x *
59
+ original maximum pre-trained length.
60
+ `original_max_position_embeddings` (`int`, *optional*):
61
+ Used with 'dynamic', 'longrope' and 'llama3'. The original max position embeddings used during
62
+ pretraining.
63
+ `attention_factor` (`float`, *optional*):
64
+ Used with 'yarn' and 'longrope'. The scaling factor to be applied on the attention
65
+ computation. If unspecified, it defaults to value recommended by the implementation, using the
66
+ `factor` field to infer the suggested value.
67
+ `beta_fast` (`float`, *optional*):
68
+ Only used with 'yarn'. Parameter to set the boundary for extrapolation (only) in the linear
69
+ ramp function. If unspecified, it defaults to 32.
70
+ `beta_slow` (`float`, *optional*):
71
+ Only used with 'yarn'. Parameter to set the boundary for interpolation (only) in the linear
72
+ ramp function. If unspecified, it defaults to 1.
73
+ `short_factor` (`List[float]`, *optional*):
74
+ Only used with 'longrope'. The scaling factor to be applied to short contexts (<
75
+ `original_max_position_embeddings`). Must be a list of numbers with the same length as the hidden
76
+ size divided by the number of attention heads divided by 2
77
+ `long_factor` (`List[float]`, *optional*):
78
+ Only used with 'longrope'. The scaling factor to be applied to long contexts (<
79
+ `original_max_position_embeddings`). Must be a list of numbers with the same length as the hidden
80
+ size divided by the number of attention heads divided by 2
81
+ `low_freq_factor` (`float`, *optional*):
82
+ Only used with 'llama3'. Scaling factor applied to low frequency components of the RoPE
83
+ `high_freq_factor` (`float`, *optional*):
84
+ Only used with 'llama3'. Scaling factor applied to high frequency components of the RoPE
85
+ use_sliding_window (`bool`, *optional*, defaults to `False`):
86
+ Whether to use sliding window attention.
87
+ sliding_window (`int`, *optional*, defaults to 4096):
88
+ Sliding window attention (SWA) window size. If not specified, will default to `4096`.
89
+ max_window_layers (`int`, *optional*, defaults to 28):
90
+ The number of layers that use SWA (Sliding Window Attention). The bottom layers use SWA while the top use full attention.
91
+ attention_dropout (`float`, *optional*, defaults to 0.0):
92
+ The dropout ratio for the attention probabilities.
93
+ ```python
94
+ >>> from transformers import MotifModel, MotifConfig
95
+ >>> # Initializing a Motif style configuration
96
+ >>> configuration = MotifConfig()
97
+ >>> # Initializing a model from the Motif-102B style configuration
98
+ >>> model = MotifModel(configuration)
99
+ >>> # Accessing the model configuration
100
+ >>> configuration = model.config
101
+ ```"""
102
+
103
+ model_type = "Motif"
104
+ keys_to_ignore_at_inference = ["past_key_values"]
105
+
106
+ base_model_tp_plan = {
107
+ # Attention
108
+ "layers.*.self_attn.q_proj": "colwise",
109
+ "layers.*.self_attn.k_proj": "colwise",
110
+ "layers.*.self_attn.v_proj": "colwise",
111
+ "layers.*.self_attn.o_proj": "rowwise",
112
+ # Dense MLP
113
+ "layers.*.mlp.gate_proj": "colwise",
114
+ "layers.*.mlp.up_proj": "colwise",
115
+ "layers.*.mlp.down_proj": "rowwise",
116
+ # MoE experts (fused gate+up)
117
+ "layers.*.moe.experts.gate_up_proj": "packed_colwise",
118
+ "layers.*.moe.experts.down_proj": "rowwise",
119
+ # Shared experts
120
+ "layers.*.moe.shared_experts.gate_proj": "colwise",
121
+ "layers.*.moe.shared_experts.up_proj": "colwise",
122
+ "layers.*.moe.shared_experts.down_proj": "rowwise",
123
+ }
124
+
125
+ base_model_pp_plan = {
126
+ "embed_tokens": (["input_ids"], ["inputs_embeds"]),
127
+ "layers": (["hidden_states", "attention_mask"], ["hidden_states"]),
128
+ "norm": (["hidden_states"], ["hidden_states"]),
129
+ }
130
+
131
+ def __init__(
132
+ self,
133
+ vocab_size=151936,
134
+ hidden_size=4096,
135
+ intermediate_size=22016,
136
+ num_hidden_layers=32,
137
+ num_attention_heads=32,
138
+ num_key_value_heads=32,
139
+ hidden_act="silu",
140
+ max_position_embeddings=32768,
141
+ initializer_range=0.02,
142
+ rms_norm_eps=1e-6,
143
+ use_cache=True,
144
+ tie_word_embeddings=False,
145
+ rope_theta=1000000.0,
146
+ rope_scaling=None,
147
+ use_sliding_window=False,
148
+ sliding_window=4096,
149
+ max_window_layers=28,
150
+ sliding_window_pattern="interleave",
151
+ sliding_window_period=2,
152
+ attention_dropout=0.0,
153
+ # Differential Attention parameters
154
+ head_dim=None,
155
+ num_noise_heads=0,
156
+ k_ratio=1,
157
+ # MoE parameters
158
+ num_experts=0,
159
+ experts_top_k=2,
160
+ num_shared_experts=0,
161
+ interleave_moe_layer_step=0,
162
+ moe_intermediate_size=None,
163
+ score_func="softmax",
164
+ route_norm=False,
165
+ route_scale=1.0,
166
+ load_balance_coeff=None,
167
+ score_before_experts=False,
168
+ _debug_force_load_balance=False,
169
+ output_router_logits=False,
170
+ router_aux_loss_coef=0.0,
171
+ # MHC (Manifold-constrained Hyper-Connections) parameters
172
+ mhc_enabled=False,
173
+ mhc_expansion_rate=4,
174
+ mhc_identity_init=False,
175
+ mhc_sinkhorn_iters=20,
176
+ # DiffAttention V2 / Attention class
177
+ diff_v2=False,
178
+ attention_cls="basic",
179
+ # GDLA (Grouped Differential Latent Attention) parameters
180
+ q_lora_rank=0,
181
+ kv_lora_rank=0,
182
+ qk_rope_head_dim=None,
183
+ v_head_dim=None,
184
+ original_seq_len=32768,
185
+ rope_factor=1.0,
186
+ mscale=1.0,
187
+ swa_rope_theta=None,
188
+ # Attention output gating
189
+ headwise_attn_output_gate=False,
190
+ elementwise_attn_output_gate=False,
191
+ # MoE: first N layers always dense (no MoE), regardless of interleave schedule
192
+ n_dense_first_layers=0,
193
+ # MTP (Multi-Token Prediction) speculative decoding
194
+ num_nextn_predict_layers=0,
195
+ **kwargs,
196
+ ):
197
+ self.vocab_size = vocab_size
198
+ self.max_position_embeddings = max_position_embeddings
199
+ self.hidden_size = hidden_size
200
+ self.intermediate_size = intermediate_size
201
+ self.num_hidden_layers = num_hidden_layers
202
+ self.num_attention_heads = num_attention_heads
203
+ self.use_sliding_window = use_sliding_window
204
+ self.sliding_window = sliding_window if use_sliding_window else None
205
+ self.max_window_layers = max_window_layers
206
+ self.sliding_window_pattern = sliding_window_pattern
207
+ self.sliding_window_period = sliding_window_period
208
+
209
+ # for backward compatibility
210
+ if num_key_value_heads is None:
211
+ num_key_value_heads = num_attention_heads
212
+
213
+ self.num_key_value_heads = num_key_value_heads
214
+ self.hidden_act = hidden_act
215
+ self.initializer_range = initializer_range
216
+ self.rms_norm_eps = rms_norm_eps
217
+ self.use_cache = use_cache
218
+ self.rope_theta = rope_theta
219
+ self.rope_scaling = rope_scaling
220
+ self.attention_dropout = attention_dropout
221
+
222
+ # Differential Attention configuration
223
+ self.head_dim = head_dim
224
+ self.num_noise_heads = num_noise_heads
225
+ self.k_ratio = k_ratio
226
+
227
+ # MoE configuration
228
+ self.num_experts = num_experts
229
+ self.experts_top_k = experts_top_k
230
+ self.num_shared_experts = num_shared_experts
231
+ self.interleave_moe_layer_step = interleave_moe_layer_step
232
+ self.moe_intermediate_size = moe_intermediate_size if moe_intermediate_size is not None else intermediate_size
233
+ self.score_func = score_func
234
+ self.route_norm = route_norm
235
+ self.route_scale = route_scale
236
+ self.load_balance_coeff = load_balance_coeff
237
+ self.score_before_experts = score_before_experts
238
+ self._debug_force_load_balance = _debug_force_load_balance
239
+ self.output_router_logits = output_router_logits
240
+ self.router_aux_loss_coef = router_aux_loss_coef
241
+
242
+ # MHC configuration
243
+ self.mhc_enabled = mhc_enabled
244
+ self.mhc_expansion_rate = mhc_expansion_rate
245
+ self.mhc_identity_init = mhc_identity_init
246
+ self.mhc_sinkhorn_iters = mhc_sinkhorn_iters
247
+
248
+ # DiffAttention V2 / Attention class
249
+ self.diff_v2 = diff_v2
250
+ self.attention_cls = attention_cls
251
+
252
+ # GDLA parameters
253
+ self.q_lora_rank = q_lora_rank
254
+ self.kv_lora_rank = kv_lora_rank
255
+ self.qk_rope_head_dim = qk_rope_head_dim
256
+ self.v_head_dim = v_head_dim
257
+ self.original_seq_len = original_seq_len
258
+ self.rope_factor = rope_factor
259
+ self.mscale = mscale
260
+ self.swa_rope_theta = swa_rope_theta
261
+
262
+ # Attention output gating
263
+ self.headwise_attn_output_gate = headwise_attn_output_gate
264
+ self.elementwise_attn_output_gate = elementwise_attn_output_gate
265
+
266
+ # MoE dense-first layers
267
+ self.n_dense_first_layers = n_dense_first_layers
268
+
269
+ # MTP speculative decoding
270
+ self.num_nextn_predict_layers = num_nextn_predict_layers
271
+
272
+ # Validate the correctness of rotary position embeddings parameters
273
+ # BC: if there is a 'type' field, move it to 'rope_type'.
274
+ if self.rope_scaling is not None and "type" in self.rope_scaling:
275
+ self.rope_scaling["rope_type"] = self.rope_scaling["type"]
276
+ if callable(getattr(type(self), "validate_rope", None)):
277
+ self.validate_rope()
278
+
279
+ # On ROCm, torch._grouped_mm is not supported at runtime even though
280
+ # transformers auto-selects the grouped_mm expert backend for torch>=2.9.
281
+ # Force eager (for-loop) dispatch so MoE models work on ROCm.
282
+ if (
283
+ self.num_experts > 0
284
+ and hasattr(torch.version, "hip")
285
+ and torch.version.hip is not None
286
+ and "experts_implementation" not in kwargs
287
+ ):
288
+ kwargs["experts_implementation"] = "eager"
289
+
290
+ super().__init__(
291
+ tie_word_embeddings=tie_word_embeddings,
292
+ **kwargs,
293
+ )
294
+ logger.info(f" kwargs : {kwargs}")
generation_config.json ADDED
@@ -0,0 +1,13 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "_from_model_config": true,
3
+ "bos_token_id": 1,
4
+ "pad_token_id": 0,
5
+ "eos_token_id": [0, 3, 6],
6
+ "output_attentions": false,
7
+ "output_hidden_states": false,
8
+ "transformers_version": "5.7.0",
9
+ "use_cache": true,
10
+ "do_sample": true,
11
+ "temperature": 1.0,
12
+ "top_p": 0.95
13
+ }
model-00001-of-00018.safetensors ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:27351e5ce2a8f87c3b58f376ab877f72d033f01381116a991cee59291c6a8ab7
3
+ size 5095036671
model-00002-of-00018.safetensors ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:7a3ccc916df9a9c3a95c7322756336b8a14305bc4fa4bcb6c63a99920a556722
3
+ size 5254098018
model-00003-of-00018.safetensors ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:9dec39afaea6b4ec8874f92300de38b6101cb6bcaf245fbb0096b074e6b94439
3
+ size 5254098194
model-00004-of-00018.safetensors ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:5b505e32190537c81e02b50fe56d08292c72e852addecc382d1836122cc4c416
3
+ size 5254098351
model-00005-of-00018.safetensors ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:09d665bb8295e70b61c61d2616bb78921d617cadcd3ceedc9b05009ac5b96a2e
3
+ size 5254098443
model-00006-of-00018.safetensors ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:4789eb3bd8c42eb2f6bdfb69936ec29d661c5a463f848088d905cc5c9aacb04a
3
+ size 5254098445
model-00007-of-00018.safetensors ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:46e365c83c0b30788b326024f3b3c7db4711d958b9455dcd73b2927ea3b4aa0e
3
+ size 5254098267
model-00008-of-00018.safetensors ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:60f88393402825e5a37a9c385e19c1e620a1982acd1831791b60b304d6fea193
3
+ size 5254098409
model-00009-of-00018.safetensors ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:a9f28c11fd91a683f2f4060810bf712f20adf34480d516a47da01d428c178592
3
+ size 5254098365
model-00010-of-00018.safetensors ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:abafe01255985c6b4e490ecbbf831425614d6f841169803823e8a973b1adbb74
3
+ size 5254098345
model-00011-of-00018.safetensors ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:b6de9066232e77b88cb391d8041b2cde7b97030ab6f682ad61230cf5e739ebda
3
+ size 5254098353
model-00012-of-00018.safetensors ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:e5780d0eb6aa806a72cc2809c6eabe40711769587bd24ff39200ac5a72b87d69
3
+ size 5254098279
model-00013-of-00018.safetensors ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:f4cac16ea63627aa25646a72dfab950c1f51d1c9e4acc5c8b900f8af613fba79
3
+ size 5254098375
model-00014-of-00018.safetensors ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:a292cdf6443e01294850b710eb1fe7710dd06b870be6d778ff7f7e1853122fb9
3
+ size 5254098417
model-00015-of-00018.safetensors ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:7826cb0aab92144dd617037416bb2cdf59873d8eaa1b3749795a0366373b93f9
3
+ size 5254098363
model-00016-of-00018.safetensors ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:324c92c5c35ca5031a9b659d422cd0c19fc6ce6e50ff11edc9471fbe901d0a9c
3
+ size 5254098397
model-00017-of-00018.safetensors ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:78bb5a4c8078ea9d1b2c31c72af2027c42a4678c5ee4f925f1273d6ae9aab7a0
3
+ size 5254098285
model-00018-of-00018.safetensors ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:e09a7c08d20e15cf94ccbb27aac7be4eba6a1f9a8ca56925fb7d7ba9bb06a0a1
3
+ size 1875673230
model.safetensors.index.json ADDED
The diff for this file is too large to render. See raw diff
 
modeling_motif.py ADDED
@@ -0,0 +1,1943 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import math
2
+ from typing import Callable, Literal, Optional, Tuple
3
+
4
+ import einops
5
+ import torch
6
+ import torch.nn.functional as F
7
+ import torch.utils.checkpoint
8
+ from torch import nn
9
+ from torch.nn import CrossEntropyLoss
10
+ from transformers.activations import ACT2CLS as _ACT2CLS
11
+ from transformers.activations import ClassInstantier
12
+ from transformers.cache_utils import Cache, DynamicCache, StaticCache
13
+ from transformers.generation import GenerationMixin
14
+ from transformers.integrations import use_experts_implementation
15
+ from transformers.modeling_attn_mask_utils import AttentionMaskConverter
16
+ from transformers.modeling_layers import GradientCheckpointingLayer
17
+ from transformers.modeling_outputs import MoeCausalLMOutputWithPast, MoeModelOutputWithPast
18
+ from transformers.modeling_rope_utils import ROPE_INIT_FUNCTIONS
19
+ from transformers.modeling_utils import ALL_ATTENTION_FUNCTIONS, PreTrainedModel
20
+ from transformers.utils import auto_docstring, can_return_tuple, logging
21
+
22
+ from .configuration_motif import MotifConfig
23
+
24
+ logger = logging.get_logger(__name__)
25
+
26
+ if hasattr(torch.version, "hip") and torch.version.hip is not None:
27
+ activation = None
28
+ logger.warning_once("Using HIP")
29
+ logger.warning_once("Due to the HIP, we do not utilize the kernel ops for precision.")
30
+ logger.warning_once("Using torch ops")
31
+ kernelRMSNorm = None
32
+ PolyNormKernel = None
33
+ else:
34
+ logger.warning_once("Using CUDA")
35
+ try:
36
+ import kernels
37
+
38
+ activation = kernels.get_kernel("Motif-Technologies/activation")
39
+ kernelRMSNorm = activation.layers.RMSNorm
40
+ PolyNormKernel = activation.layers.PolyNorm
41
+ except Exception as e:
42
+ activation = None
43
+ kernelRMSNorm = None
44
+ PolyNormKernel = None
45
+ logger.warning_once(f"Failed to import kernel ops: {e}")
46
+ logger.warning_once("Using torch ops")
47
+
48
+
49
+ class PolyNormTorch(torch.nn.Module):
50
+ """
51
+ A trainable activation function introduced in https://arxiv.org/html/2411.03884v1.
52
+ The code is copied from https://github.com/BryceZhuo/PolyCom?tab=readme-ov-file/README.md,
53
+ with the change `* torch.rsqrt` => `/ torch.sqrt`.
54
+ """
55
+
56
+ def __init__(self, eps=1e-6):
57
+ super(PolyNormTorch, self).__init__()
58
+ self.weight = torch.nn.Parameter(torch.ones(3) / 3)
59
+ self.bias = torch.nn.Parameter(torch.zeros(1))
60
+ self.eps = eps
61
+
62
+ def _norm(self, x):
63
+ return x / torch.sqrt(x.pow(2).mean(-1, keepdim=True) + self.eps)
64
+
65
+ def forward(self, x):
66
+ return (
67
+ self.weight[0] * self._norm(x**3)
68
+ + self.weight[1] * self._norm(x**2)
69
+ + self.weight[2] * self._norm(x)
70
+ + self.bias
71
+ )
72
+
73
+
74
+ PolyNorm = PolyNormKernel if PolyNormKernel is not None else PolyNormTorch
75
+
76
+
77
+ class GroupedPolyNorm(nn.Module):
78
+ """Per-expert PolyNorm: weight [num_experts, 3], bias [num_experts, 1].
79
+
80
+ Mirrors titan's GroupedExpertsPolyNorm — each expert has independent
81
+ polynomial normalization coefficients.
82
+ """
83
+
84
+ def __init__(self, num_experts: int, eps: float = 1e-6):
85
+ super().__init__()
86
+ self.num_experts = num_experts
87
+ self.eps = eps
88
+ self.weight = nn.Parameter(torch.ones(num_experts, 3) / 3)
89
+ self.bias = nn.Parameter(torch.zeros(num_experts, 1))
90
+
91
+ def _norm(self, x: torch.Tensor) -> torch.Tensor:
92
+ return x / torch.sqrt(x.pow(2).mean(-1, keepdim=True) + self.eps)
93
+
94
+ def forward_single(self, x: torch.Tensor, expert_idx: int) -> torch.Tensor:
95
+ w = self.weight[expert_idx] # [3]
96
+ b = self.bias[expert_idx] # [1]
97
+ return w[0] * self._norm(x**3) + w[1] * self._norm(x**2) + w[2] * self._norm(x) + b
98
+
99
+
100
+ CUSTOM_ACT2CLS = {"poly_norm": PolyNorm}
101
+ ACT2CLS = {**_ACT2CLS, **CUSTOM_ACT2CLS}
102
+ ACT2FN = ClassInstantier(ACT2CLS)
103
+
104
+
105
+ class MotifRMSNorm(nn.Module):
106
+ def __init__(self, hidden_size, eps=1e-6):
107
+ """
108
+ MotifRMSNorm is equivalent to T5LayerNorm
109
+ """
110
+ super().__init__()
111
+ self.weight = nn.Parameter(torch.ones(hidden_size))
112
+ self.variance_epsilon = eps
113
+
114
+ def forward(self, hidden_states):
115
+ input_dtype = hidden_states.dtype
116
+ hidden_states = hidden_states.to(torch.float32)
117
+ variance = hidden_states.pow(2).mean(-1, keepdim=True)
118
+ hidden_states = hidden_states * torch.rsqrt(variance + self.variance_epsilon)
119
+ return self.weight * hidden_states.to(input_dtype)
120
+
121
+ def extra_repr(self):
122
+ return f"{tuple(self.weight.shape)}, eps={self.variance_epsilon}"
123
+
124
+
125
+ class MHCLayer(nn.Module):
126
+ """Manifold-constrained Hyper-Connections (MHC) layer.
127
+
128
+ Written inline in the HF model (no llm_training.layers.mhc dependency).
129
+ apply_h_res uses a pure-PyTorch einsum instead of the Triton kernel.
130
+
131
+ Reference: https://arxiv.org/abs/2512.24880
132
+ """
133
+
134
+ def __init__(
135
+ self,
136
+ expansion_rate: int,
137
+ num_dim: int,
138
+ identity_init: bool = False,
139
+ sinkhorn_iters: int = 20,
140
+ ):
141
+ super().__init__()
142
+ self.expansion_rate = expansion_rate
143
+ self.num_dim = num_dim
144
+ self.sinkhorn_iters = sinkhorn_iters
145
+
146
+ E, D = expansion_rate, num_dim
147
+ self.proj_pre = nn.Linear(E * D, E, bias=False)
148
+ self.proj_post = nn.Linear(E * D, E, bias=False)
149
+ self.proj_res = nn.Linear(E * D, E * E, bias=False)
150
+
151
+ RMSNorm = kernelRMSNorm if kernelRMSNorm is not None else MotifRMSNorm
152
+ self.rms_norm = RMSNorm(E * D, eps=1e-6)
153
+
154
+ self.bias_pre = nn.Parameter(torch.empty(E))
155
+ self.bias_post = nn.Parameter(torch.empty(E))
156
+ self.bias_res = nn.Parameter(torch.empty(E, E))
157
+ self.alpha_pre = nn.Parameter(torch.empty(1))
158
+ self.alpha_post = nn.Parameter(torch.empty(1))
159
+ self.alpha_res = nn.Parameter(torch.empty(1))
160
+
161
+ self._init_weights(identity_init)
162
+
163
+ def _init_weights(self, identity_init: bool) -> None:
164
+ if hasattr(self.rms_norm, "reset_parameters"):
165
+ self.rms_norm.reset_parameters()
166
+ if identity_init:
167
+ nn.init.zeros_(self.alpha_pre)
168
+ nn.init.zeros_(self.alpha_post)
169
+ nn.init.zeros_(self.alpha_res)
170
+ nn.init.xavier_uniform_(self.proj_pre.weight)
171
+ nn.init.xavier_uniform_(self.proj_post.weight)
172
+ nn.init.xavier_uniform_(self.proj_res.weight)
173
+ uniform_weight = 1.0 / self.expansion_rate
174
+ bias_pre_value = math.log(uniform_weight / (1 - uniform_weight)) if 0 < uniform_weight < 1 else 0.0
175
+ nn.init.constant_(self.bias_pre, bias_pre_value)
176
+ nn.init.zeros_(self.bias_post)
177
+ nn.init.constant_(self.bias_res, -10.0)
178
+ self.bias_res.data.fill_diagonal_(0.0)
179
+ else:
180
+ nn.init.normal_(self.alpha_pre, mean=0.0, std=0.1)
181
+ nn.init.normal_(self.alpha_post, mean=0.0, std=0.1)
182
+ nn.init.normal_(self.alpha_res, mean=0.0, std=0.1)
183
+ nn.init.xavier_uniform_(self.proj_pre.weight)
184
+ nn.init.xavier_uniform_(self.proj_post.weight)
185
+ nn.init.xavier_uniform_(self.proj_res.weight)
186
+ nn.init.zeros_(self.bias_pre)
187
+ nn.init.zeros_(self.bias_post)
188
+ nn.init.normal_(self.bias_res, mean=0.0, std=0.1)
189
+
190
+ def _sinkhorn_knopp_batch(self, matrix: torch.Tensor) -> torch.Tensor:
191
+ orig_dtype = matrix.dtype
192
+ # Run Sinkhorn-Knopp in float32 (bf16/fp16 exp() is numerically unstable)
193
+ m = matrix.float().clamp(-20.0, 20.0).exp()
194
+ for _ in range(self.sinkhorn_iters):
195
+ m = m / m.sum(dim=-1, keepdim=True).clamp(min=1e-8)
196
+ m = m / m.sum(dim=-2, keepdim=True).clamp(min=1e-8)
197
+ return m.to(orig_dtype)
198
+
199
+ def forward(self, x: torch.Tensor):
200
+ batch_size, seq_len, expansion_rate, dim = x.shape
201
+ x_reshaped = x.reshape(batch_size, seq_len, expansion_rate * dim)
202
+ x_norm = self.rms_norm(x_reshaped)
203
+
204
+ # Cast projection outputs to float32 (paper §4.3.1)
205
+ proj_pre_out = self.proj_pre(x_norm).float()
206
+ proj_post_out = self.proj_post(x_norm).float()
207
+ proj_res_out = self.proj_res(x_norm).float().reshape(batch_size, seq_len, expansion_rate, expansion_rate)
208
+
209
+ h_pre = torch.sigmoid((self.alpha_pre * proj_pre_out + self.bias_pre).clamp(-10.0, 10.0))
210
+ h_post = 2 * torch.sigmoid((self.alpha_post * proj_post_out + self.bias_post).clamp(-10.0, 10.0))
211
+ h_res = self._sinkhorn_knopp_batch(self.alpha_res * proj_res_out + self.bias_res)
212
+
213
+ return h_pre, h_post, h_res
214
+
215
+ @classmethod
216
+ def apply_h_res(cls, x: torch.Tensor, h_res: torch.Tensor) -> torch.Tensor:
217
+ """h_res: (B, S, E, E), x: (B, S, E, D) -> (B, S, E, D)."""
218
+ return torch.einsum("bsij,bsjd->bsid", h_res, x.float()).to(x.dtype)
219
+
220
+ @classmethod
221
+ def apply_h_pre(cls, x: torch.Tensor, h_pre: torch.Tensor) -> torch.Tensor:
222
+ """Weighted sum over expansion dim: (B, S, E, D) -> (B, S, D)."""
223
+ return (x * h_pre.unsqueeze(-1)).sum(dim=2).to(x.dtype)
224
+
225
+ @classmethod
226
+ def apply_h_post(cls, x: torch.Tensor, h_post: torch.Tensor) -> torch.Tensor:
227
+ """Expand: (B, S, D) -> (B, S, E, D)."""
228
+ return (h_post.unsqueeze(-1) * x.unsqueeze(2)).to(x.dtype)
229
+
230
+ def extra_repr(self) -> str:
231
+ return f"expansion_rate={self.expansion_rate}, sinkhorn_iters={self.sinkhorn_iters}"
232
+
233
+
234
+ class MotifRotaryEmbedding(nn.Module):
235
+ inv_freq: torch.Tensor
236
+
237
+ def __init__(self, config: MotifConfig, device=None, rope_head_dim: Optional[int] = None):
238
+ super().__init__()
239
+ # BC: "rope_type" was originally "type"
240
+ if hasattr(config, "rope_scaling") and isinstance(config.rope_scaling, dict):
241
+ self.rope_type = config.rope_scaling.get("rope_type", config.rope_scaling.get("type"))
242
+ else:
243
+ self.rope_type = "default"
244
+ self.max_seq_len_cached = config.max_position_embeddings
245
+ self.original_max_seq_len = config.max_position_embeddings
246
+
247
+ self.config = config
248
+ # Use rope_head_dim if provided (e.g. for GDLA which only applies RoPE to qk_rope_head_dim dims)
249
+ effective_head_dim = (
250
+ rope_head_dim
251
+ if rope_head_dim is not None
252
+ else (config.head_dim if config.head_dim is not None else config.hidden_size // config.num_attention_heads)
253
+ )
254
+ if self.rope_type == "default":
255
+ self.rope_init_fn = None
256
+ inv_freq = 1.0 / (
257
+ config.rope_theta
258
+ ** (torch.arange(0, effective_head_dim, 2, dtype=torch.int64).float().to(device) / effective_head_dim)
259
+ )
260
+ self.attention_scaling = 1.0
261
+
262
+ else:
263
+ self.rope_init_fn = ROPE_INIT_FUNCTIONS[self.rope_type]
264
+ inv_freq, self.attention_scaling = self.rope_init_fn(self.config, device)
265
+ self.register_buffer("inv_freq", inv_freq, persistent=False)
266
+ self.original_inv_freq = self.inv_freq
267
+
268
+ def _dynamic_frequency_update(self, position_ids, device):
269
+ seq_len = torch.max(position_ids) + 1
270
+ if seq_len > self.max_seq_len_cached:
271
+ if self.rope_init_fn is not None:
272
+ inv_freq, self.attention_scaling = self.rope_init_fn(self.config, device, seq_len=seq_len)
273
+ self.register_buffer("inv_freq", inv_freq, persistent=False)
274
+ self.max_seq_len_cached = seq_len
275
+
276
+ if seq_len < self.original_max_seq_len and self.max_seq_len_cached > self.original_max_seq_len:
277
+ self.register_buffer("inv_freq", self.original_inv_freq, persistent=False)
278
+ self.max_seq_len_cached = self.original_max_seq_len
279
+
280
+ @torch.no_grad()
281
+ def forward(self, x, position_ids):
282
+ if "dynamic" in self.rope_type:
283
+ self._dynamic_frequency_update(position_ids, device=x.device)
284
+
285
+ inv_freq_expanded = self.inv_freq[None, :, None].float().expand(position_ids.shape[0], -1, 1).to(x.device)
286
+ position_ids_expanded = position_ids[:, None, :].float()
287
+
288
+ device_type = x.device.type if isinstance(x.device.type, str) and x.device.type != "mps" else "cpu"
289
+ with torch.autocast(device_type=device_type, enabled=False):
290
+ freqs = (inv_freq_expanded.float() @ position_ids_expanded.float()).transpose(1, 2)
291
+ emb = torch.cat((freqs, freqs), dim=-1)
292
+ cos = emb.cos() * self.attention_scaling
293
+ sin = emb.sin() * self.attention_scaling
294
+
295
+ return cos.to(dtype=x.dtype), sin.to(dtype=x.dtype)
296
+
297
+
298
+ def rotate_half(x):
299
+ """
300
+ Rotates half of the dimensions of the input tensor using torch.roll and in-place negation.
301
+
302
+ Args:
303
+ x (torch.Tensor): The input tensor.
304
+
305
+ Returns:
306
+ torch.Tensor: A tensor where the latter half of the dimensions are negated
307
+ and moved before the first half.
308
+ """
309
+ half_size = x.shape[-1] // 2
310
+ rotated_tensor = torch.roll(x, shifts=-half_size, dims=-1)
311
+ rotated_tensor[..., :half_size] *= -1
312
+
313
+ return rotated_tensor
314
+
315
+
316
+ def apply_rotary_pos_emb(q, k, cos, sin, position_ids=None, unsqueeze_dim=1):
317
+ """
318
+ Applies rotary position embeddings to the input tensors.
319
+ Args:
320
+ q (torch.Tensor): Query tensor of shape (B, NH, S, D_KV).
321
+ k (torch.Tensor): Key tensor of shape (B, NH, S, D_KV).
322
+ cos (torch.Tensor): Cosine values for rotary embedding, shape (B, S, D) from MotifRotaryEmbedding.
323
+ sin (torch.Tensor): Sine values for rotary embedding, shape (B, S, D) from MotifRotaryEmbedding.
324
+ position_ids: Unused, kept for API compatibility.
325
+ unsqueeze_dim (int, optional): Dimension along which `cos` and `sin` are unsqueezed.
326
+ Defaults to 1 (head dimension).
327
+ Returns:
328
+ Tuple[torch.Tensor, torch.Tensor]: Transformed query and key tensors.
329
+ """
330
+ # cos/sin shape: (B, S, D) -> unsqueeze to (B, 1, S, D) for broadcasting with (B, NH, S, D)
331
+ cos = cos.unsqueeze(unsqueeze_dim)
332
+ sin = sin.unsqueeze(unsqueeze_dim)
333
+ q_embed = (q * cos) + (rotate_half(q) * sin)
334
+ k_embed = (k * cos) + (rotate_half(k) * sin)
335
+ return q_embed, k_embed
336
+
337
+
338
+ def apply_rotary_pos_emb_single(
339
+ x: torch.Tensor,
340
+ cos: torch.Tensor,
341
+ sin: torch.Tensor,
342
+ ) -> torch.Tensor:
343
+ """Apply RoPE to a single tensor in (B, S, NH, D) format.
344
+
345
+ Used by GDLA to apply positional encoding only to the rope portion of Q/K.
346
+ cos/sin shape: (B, S, D) — broadcast over NH dimension.
347
+ """
348
+ cos = cos.unsqueeze(2) # (B, S, 1, D)
349
+ sin = sin.unsqueeze(2) # (B, S, 1, D)
350
+ return x * cos + rotate_half(x) * sin
351
+
352
+
353
+ class MotifMLP(nn.Module):
354
+ def __init__(self, config, intermediate_size: int | None = None):
355
+ super().__init__()
356
+ self.hidden_size = config.hidden_size
357
+ self.intermediate_size = intermediate_size if intermediate_size is not None else config.intermediate_size
358
+
359
+ self.gate_proj = nn.Linear(self.hidden_size, self.intermediate_size, bias=False)
360
+ self.up_proj = nn.Linear(self.hidden_size, self.intermediate_size, bias=False)
361
+ self.down_proj = nn.Linear(self.intermediate_size, self.hidden_size, bias=False)
362
+ self.act_fn = ACT2FN[config.hidden_act]
363
+
364
+ def forward(self, hidden_state):
365
+ hidden_state = self.act_fn(self.gate_proj(hidden_state)) * self.up_proj(hidden_state)
366
+ return self.down_proj(hidden_state)
367
+
368
+
369
+ def repeat_kv(hidden_states: torch.Tensor, dim: int, n_rep: int) -> torch.Tensor:
370
+ return torch.repeat_interleave(hidden_states, dim=dim, repeats=n_rep)
371
+
372
+
373
+ def eager_attention_forward(
374
+ module: nn.Module,
375
+ query: torch.Tensor,
376
+ key: torch.Tensor,
377
+ value: torch.Tensor,
378
+ attention_mask: Optional[torch.Tensor],
379
+ scaling: float,
380
+ dropout: float = 0.0,
381
+ **kwargs,
382
+ ):
383
+ """Eager attention forward compatible with ALL_ATTENTION_FUNCTIONS interface.
384
+ Expects query/key/value in [batch, num_heads, seq_len, head_dim] format.
385
+ """
386
+ attn_weights = torch.matmul(query, key.transpose(2, 3)) * scaling
387
+ if attention_mask is not None:
388
+ causal_mask = attention_mask[:, :, :, : key.shape[-2]]
389
+ attn_weights = attn_weights + causal_mask
390
+
391
+ attn_weights = nn.functional.softmax(attn_weights, dim=-1, dtype=torch.float32).to(query.dtype)
392
+ attn_weights = nn.functional.dropout(attn_weights, p=dropout, training=module.training)
393
+ attn_output = torch.matmul(attn_weights, value)
394
+ attn_output = attn_output.transpose(1, 2).contiguous()
395
+
396
+ return attn_output, attn_weights
397
+
398
+
399
+ class MotifAttention(nn.Module):
400
+ """
401
+ Grouped Differential Attention module.
402
+
403
+ Implements Grouped Differential Attention (https://arxiv.org/pdf/2510.06949)
404
+ with support for eager, Flash Attention, and SDPA backends via the attention
405
+ function registry.
406
+ """
407
+
408
+ def __init__(self, config: MotifConfig, layer_idx: Optional[int] = None):
409
+ super().__init__()
410
+ self.config = config
411
+ self.layer_idx = layer_idx
412
+ if layer_idx is None:
413
+ logger.warning_once(
414
+ f"Instantiating {self.__class__.__name__} without passing `layer_idx` is not recommended and will "
415
+ "lead to errors during the forward call, if caching is used. Please make sure to provide a `layer_idx` "
416
+ "when creating this class."
417
+ )
418
+
419
+ self.hidden_size = config.hidden_size
420
+ self.num_heads = config.num_attention_heads
421
+ self.head_dim = self.hidden_size // self.num_heads if config.head_dim is None else config.head_dim
422
+ self.num_key_value_heads = config.num_key_value_heads
423
+ self.is_causal = True
424
+ self.attention_dropout = config.attention_dropout
425
+ self.scaling = 1.0 / math.sqrt(self.head_dim)
426
+
427
+ # Grouped Differential Transformer
428
+ self.num_noise_heads = config.num_noise_heads
429
+ self.grouped_ratio = (self.num_heads - self.num_noise_heads) // self.num_noise_heads
430
+ self.q_heads = (self.grouped_ratio + 1) * self.num_noise_heads
431
+ self.n_signal_heads = self.grouped_ratio * self.num_noise_heads # = q_heads - noise_heads
432
+ self.expanded = getattr(config, "expanded", False)
433
+
434
+ self.diff_v2 = getattr(config, "diff_v2", False)
435
+ self.elementwise_attn_output_gate = getattr(config, "elementwise_attn_output_gate", False)
436
+ self.headwise_attn_output_gate = getattr(config, "headwise_attn_output_gate", False)
437
+
438
+ if (self.head_dim * self.num_heads) != self.hidden_size and not self.expanded:
439
+ raise ValueError(
440
+ f"hidden_size must be divisible by num_heads (got `hidden_size`: {self.hidden_size}"
441
+ f" and `num_heads`: {self.num_heads})."
442
+ )
443
+
444
+ # q_proj size depends on gating mode
445
+ if self.elementwise_attn_output_gate:
446
+ self.q_proj = nn.Linear(
447
+ self.hidden_size, (self.num_heads + self.n_signal_heads * 2) * self.head_dim, bias=False
448
+ )
449
+ elif self.headwise_attn_output_gate:
450
+ self.q_proj = nn.Linear(self.hidden_size, self.num_heads * self.head_dim + self.n_signal_heads, bias=False)
451
+ else:
452
+ self.q_proj = nn.Linear(self.hidden_size, self.q_heads * self.head_dim, bias=False)
453
+
454
+ self.k_proj = nn.Linear(self.hidden_size, self.num_key_value_heads * self.head_dim, bias=False)
455
+
456
+ if self.diff_v2:
457
+ # V2: single V projection, smaller O projection, lambda from projection
458
+ self.v_proj = nn.Linear(self.hidden_size, self.num_key_value_heads * self.head_dim, bias=False)
459
+ self.o_proj = nn.Linear(self.n_signal_heads * self.head_dim, self.hidden_size, bias=False)
460
+ self.lambda_proj = nn.Linear(self.hidden_size, self.n_signal_heads, bias=False)
461
+ else:
462
+ # V1: split V projection, subln, learnable lambda scalars
463
+ self.k_ratio = config.k_ratio
464
+ k_noise_heads = self.num_key_value_heads // (self.k_ratio + 1)
465
+ self.kv_repeat = self.num_noise_heads // k_noise_heads
466
+ self.v_proj = nn.Linear(self.hidden_size, 2 * k_noise_heads * self.head_dim, bias=False)
467
+ self.o_proj = nn.Linear(
468
+ 2 * self.grouped_ratio * self.num_noise_heads * self.head_dim, self.hidden_size, bias=False
469
+ )
470
+ self.lambda_proj = None
471
+ for name in ["lambda_q1", "lambda_k1", "lambda_q2", "lambda_k2"]:
472
+ setattr(self, name, nn.Parameter(torch.zeros(self.head_dim, dtype=torch.float32)))
473
+ getattr(self, name).data.normal_(mean=0.0, std=0.1)
474
+ RMSNorm = kernelRMSNorm if kernelRMSNorm is not None else MotifRMSNorm
475
+ self.subln = RMSNorm(2 * self.head_dim, eps=1e-5)
476
+ self.lambda_init = 0.8 - 0.6 * math.exp(-0.3 * (layer_idx - 1))
477
+
478
+ # Sliding window config for this layer (interleave pattern matching Titan)
479
+ if config.use_sliding_window and getattr(config, "sliding_window", None) is not None:
480
+ pattern = getattr(config, "sliding_window_pattern", "interleave")
481
+ period = getattr(config, "sliding_window_period", 2)
482
+ # +1 to match torchtitan convention: torchtitan passes window_size=(W, 0)
483
+ # directly to flash_attn (right=0 since attention is causal), but HF
484
+ # converts sliding_window=X to window_size=(X-1, X-1). Adding 1
485
+ # compensates the left side so X+1 → (X, X). The right side differs
486
+ # (W vs 0) but is irrelevant because causal masking already prevents
487
+ # attending to future tokens.
488
+ effective_window = config.sliding_window + 1
489
+ if pattern == "all":
490
+ self.sliding_window = effective_window
491
+ elif pattern == "interleave" and layer_idx % period != 0:
492
+ self.sliding_window = effective_window
493
+ else:
494
+ self.sliding_window = None
495
+ else:
496
+ self.sliding_window = None
497
+
498
+ def _reshape_heads(self, tensor, grouped_ratio, num_groups):
499
+ """2-way head split tensor reshape"""
500
+ tensor = einops.rearrange(
501
+ tensor,
502
+ "... (num_groups group_size) D -> ... num_groups group_size D",
503
+ num_groups=num_groups,
504
+ group_size=grouped_ratio + 1,
505
+ )
506
+ tensor1 = tensor[..., :grouped_ratio, :]
507
+ tensor2 = tensor[..., grouped_ratio:, :]
508
+ return tensor1.contiguous(), tensor2.contiguous()
509
+
510
+ def _restore_shape(self, tensor, batch_size, seq_len):
511
+ """restore tensor"""
512
+ return tensor.reshape(batch_size, seq_len, -1, self.head_dim)
513
+
514
+ def _compute_attention_via_interface(
515
+ self,
516
+ attention_interface: Callable,
517
+ query_states,
518
+ key_states,
519
+ value_states,
520
+ attention_mask,
521
+ dropout_rate,
522
+ **kwargs,
523
+ ):
524
+ """Compute attention via the registered attention interface."""
525
+ # Transpose to [batch, num_heads, seq_len, head_dim] for attention interface
526
+ q = query_states.transpose(1, 2)
527
+ k = key_states.transpose(1, 2)
528
+ v = value_states.transpose(1, 2)
529
+
530
+ attn_output, _ = attention_interface(
531
+ self,
532
+ q,
533
+ k,
534
+ v,
535
+ attention_mask,
536
+ dropout=dropout_rate,
537
+ scaling=self.scaling,
538
+ sliding_window=self.sliding_window,
539
+ is_causal=self.is_causal,
540
+ **kwargs,
541
+ )
542
+
543
+ # attn_output from interface is [batch, seq_len, num_heads, head_dim] (already transposed)
544
+ # But some interfaces return [batch, num_heads, seq_len, head_dim] - handle both
545
+ if attn_output.dim() == 4 and attn_output.shape[1] != query_states.shape[1]:
546
+ attn_output = attn_output.transpose(1, 2)
547
+ return attn_output
548
+
549
+ def forward(
550
+ self,
551
+ hidden_states: torch.Tensor,
552
+ attention_mask: Optional[torch.Tensor] = None,
553
+ position_ids: Optional[torch.LongTensor] = None,
554
+ past_key_value: Optional[Cache] = None,
555
+ output_attentions: bool = False,
556
+ use_cache: bool = False,
557
+ cache_position: Optional[torch.LongTensor] = None,
558
+ position_embeddings: Optional[Tuple[torch.Tensor, torch.Tensor]] = None,
559
+ **kwargs,
560
+ ) -> Tuple[torch.Tensor, Optional[torch.Tensor], Optional[Tuple[torch.Tensor]]]:
561
+ bsz, q_len, _ = hidden_states.size()
562
+
563
+ # Lambda for V2 (input-dependent)
564
+ lambda_full = None
565
+ if self.diff_v2:
566
+ lambda_full = self.lambda_proj(hidden_states) # (bsz, q_len, n_signal_heads)
567
+
568
+ # Project Q, K, V
569
+ query_states = self.q_proj(hidden_states)
570
+ key_states = self.k_proj(hidden_states)
571
+ value_states = self.v_proj(hidden_states)
572
+
573
+ # Extract gate score from Q if gating is enabled
574
+ gate_score = None
575
+ if self.headwise_attn_output_gate:
576
+ q_flat = query_states[..., : self.num_heads * self.head_dim]
577
+ gate_flat = query_states[..., self.num_heads * self.head_dim :] # (bsz, q_len, n_signal_heads)
578
+ query_states = q_flat.view(bsz, q_len, self.num_heads, self.head_dim)
579
+ gate_score = gate_flat.unsqueeze(-1) # (bsz, q_len, n_signal_heads, 1)
580
+ elif self.elementwise_attn_output_gate:
581
+ query_states = query_states.view(bsz, q_len, -1, self.head_dim)
582
+ q_main = query_states[:, :, : self.num_heads, :]
583
+ gate_heads = query_states[:, :, self.num_heads :, :] # (bsz, q_len, n_signal_heads*2, head_dim)
584
+ gate_score = gate_heads.view(bsz, q_len, self.n_signal_heads, self.head_dim * 2)
585
+ query_states = q_main
586
+ else:
587
+ query_states = query_states.view(bsz, q_len, self.num_heads, self.head_dim)
588
+
589
+ key_states = key_states.view(bsz, q_len, self.num_key_value_heads, self.head_dim)
590
+ value_states = value_states.view(bsz, q_len, -1, self.head_dim)
591
+
592
+ # Transpose to [batch, num_heads, seq_len, head_dim] for RoPE
593
+ query_states = query_states.transpose(1, 2)
594
+ key_states = key_states.transpose(1, 2)
595
+ value_states = value_states.transpose(1, 2)
596
+
597
+ # Apply RoPE
598
+ cos, sin = position_embeddings
599
+ query_states, key_states = apply_rotary_pos_emb(query_states, key_states, cos, sin, position_ids=position_ids)
600
+
601
+ # Handle KV cache
602
+ if past_key_value is not None:
603
+ cache_kwargs = {"sin": sin, "cos": cos, "cache_position": cache_position}
604
+ key_states, value_states = past_key_value.update(key_states, value_states, self.layer_idx, cache_kwargs)
605
+
606
+ kv_seq_len = key_states.shape[-2]
607
+ dropout_rate = 0.0 if not self.training else self.attention_dropout
608
+
609
+ # Cast dtype if needed (PEFT float32 workaround)
610
+ input_dtype = query_states.dtype
611
+ if input_dtype == torch.float32:
612
+ if torch.is_autocast_enabled():
613
+ target_dtype = torch.get_autocast_gpu_dtype()
614
+ elif hasattr(self.config, "_pre_quantization_dtype"):
615
+ target_dtype = self.config._pre_quantization_dtype
616
+ else:
617
+ target_dtype = self.q_proj.weight.dtype
618
+ logger.warning_once(
619
+ f"The input hidden states seems to be silently casted in float32, this might be related to"
620
+ f" the fact you have upcasted embedding or layer norm layers in float32. We will cast back the input in"
621
+ f" {target_dtype}."
622
+ )
623
+ query_states = query_states.to(target_dtype)
624
+ key_states = key_states.to(target_dtype)
625
+ value_states = value_states.to(target_dtype)
626
+
627
+ attention_interface: Callable = ALL_ATTENTION_FUNCTIONS.get_interface(
628
+ self.config._attn_implementation, eager_attention_forward
629
+ )
630
+
631
+ if self.diff_v2:
632
+ attn_output = self._forward_v2(
633
+ attention_interface,
634
+ query_states,
635
+ key_states,
636
+ value_states,
637
+ lambda_full,
638
+ gate_score,
639
+ attention_mask,
640
+ dropout_rate,
641
+ bsz,
642
+ q_len,
643
+ **kwargs,
644
+ )
645
+ else:
646
+ attn_output = self._forward_v1(
647
+ attention_interface,
648
+ query_states,
649
+ key_states,
650
+ value_states,
651
+ gate_score,
652
+ attention_mask,
653
+ dropout_rate,
654
+ bsz,
655
+ q_len,
656
+ kv_seq_len,
657
+ **kwargs,
658
+ )
659
+
660
+ attn_output = attn_output.reshape(bsz, q_len, -1)
661
+ attn_output = self.o_proj(attn_output)
662
+ return attn_output, None, past_key_value
663
+
664
+ def _forward_v1(
665
+ self,
666
+ attention_interface,
667
+ query_states,
668
+ key_states,
669
+ value_states,
670
+ gate_score,
671
+ attention_mask,
672
+ dropout_rate,
673
+ bsz,
674
+ q_len,
675
+ kv_seq_len,
676
+ **kwargs,
677
+ ):
678
+ """Differential Attention V1: two flash-attn calls with learnable scalar lambda."""
679
+ # forward() transposes to [B, H, S, D] for RoPE; undo to [B, S, H, D]
680
+ # so _reshape_heads (splits H) and _compute_attention_via_interface work correctly.
681
+ query_states = query_states.transpose(1, 2)
682
+ key_states = key_states.transpose(1, 2)
683
+ value_states = value_states.transpose(1, 2)
684
+ num_groups = self.q_heads // (self.grouped_ratio + 1)
685
+ q1, q2 = self._reshape_heads(query_states, self.grouped_ratio, num_groups)
686
+
687
+ num_kv_groups = self.num_key_value_heads // (self.k_ratio + 1)
688
+ k1, k2 = self._reshape_heads(key_states, self.k_ratio, num_kv_groups)
689
+ v1, v2 = self._reshape_heads(value_states, 1, num_kv_groups)
690
+
691
+ q1, q2 = self._restore_shape(q1, bsz, q_len), self._restore_shape(q2, bsz, q_len)
692
+ k1, k2 = self._restore_shape(k1, bsz, kv_seq_len), self._restore_shape(k2, bsz, kv_seq_len)
693
+ v1, v2 = self._restore_shape(v1, bsz, kv_seq_len), self._restore_shape(v2, bsz, kv_seq_len)
694
+
695
+ q_f = torch.cat([q1, q2], dim=2)
696
+
697
+ k1 = repeat_kv(k1, 2, self.kv_repeat)
698
+ k2 = repeat_kv(k2, 2, self.kv_repeat)
699
+ v1 = repeat_kv(v1, 2, self.kv_repeat)
700
+ v2 = repeat_kv(v2, 2, self.kv_repeat)
701
+
702
+ if self.k_ratio == 1:
703
+ k_f = torch.cat([repeat_kv(k1, 2, self.grouped_ratio), k2], dim=2)
704
+ else:
705
+ k_f = torch.cat([k1, k2], dim=2)
706
+ v1_f = torch.cat([repeat_kv(v1, 2, self.grouped_ratio), v1], dim=2)
707
+ v2_f = torch.cat([repeat_kv(v2, 2, self.grouped_ratio), v2], dim=2)
708
+
709
+ attn_1 = self._compute_attention_via_interface(
710
+ attention_interface, q_f, k_f, v1_f, attention_mask, dropout_rate, **kwargs
711
+ )
712
+ attn_2 = self._compute_attention_via_interface(
713
+ attention_interface, q_f, k_f, v2_f, attention_mask, dropout_rate, **kwargs
714
+ )
715
+
716
+ merged_attn = torch.cat([attn_1, attn_2], dim=-1)
717
+ attn_o = merged_attn[..., :-num_kv_groups, :]
718
+ attn_n_group = merged_attn[..., -num_kv_groups:, :]
719
+ attn_n = repeat_kv(attn_n_group, 2, self.grouped_ratio)
720
+
721
+ lambda_q1 = self.lambda_q1.unsqueeze(0).expand([bsz, self.lambda_q1.shape[0]])
722
+ lambda_q2 = self.lambda_q2.unsqueeze(0).expand([bsz, self.lambda_q2.shape[0]])
723
+ lambda_1 = torch.exp(torch.sum(lambda_q1 * self.lambda_k1, dim=-1).float()).type_as(attn_o)
724
+ lambda_2 = torch.exp(torch.sum(lambda_q2 * self.lambda_k2, dim=-1).float()).type_as(attn_n)
725
+ lambda_full = lambda_1 - lambda_2 + self.lambda_init
726
+
727
+ attn_output = attn_o - lambda_full.view([bsz, 1, 1, 1]) * attn_n
728
+ attn_output = self.subln(attn_output)
729
+ attn_output = attn_output * (1 - self.lambda_init)
730
+
731
+ if gate_score is not None:
732
+ attn_output = attn_output * torch.sigmoid(gate_score)
733
+
734
+ expected = (bsz, q_len, self.grouped_ratio * self.num_noise_heads, self.head_dim * 2)
735
+ if attn_output.size() != expected:
736
+ raise ValueError(f"`attn_output` should be of size {expected}, but is {attn_output.size()}")
737
+ return attn_output
738
+
739
+ def _forward_v2(
740
+ self,
741
+ attention_interface,
742
+ query_states,
743
+ key_states,
744
+ value_states,
745
+ lambda_full,
746
+ gate_score,
747
+ attention_mask,
748
+ dropout_rate,
749
+ bsz,
750
+ q_len,
751
+ **kwargs,
752
+ ):
753
+ """Differential Attention V2: single attention call with input-dependent lambda."""
754
+ # forward() transposes to [B, H, S, D] for RoPE; undo to [B, S, H, D]
755
+ # so _compute_attention_via_interface and einops rearrange work correctly.
756
+ query_states = query_states.transpose(1, 2)
757
+ key_states = key_states.transpose(1, 2)
758
+ value_states = value_states.transpose(1, 2)
759
+ attn_output = self._compute_attention_via_interface(
760
+ attention_interface,
761
+ query_states,
762
+ key_states,
763
+ value_states,
764
+ attention_mask,
765
+ dropout_rate,
766
+ **kwargs,
767
+ )
768
+ # attn_output: (bsz, q_len, n_heads, head_dim)
769
+
770
+ # Split heads into signal and noise groups
771
+ num_groups = self.num_noise_heads # n_heads // (grouped_ratio + 1)
772
+ attn_reshaped = einops.rearrange(
773
+ attn_output,
774
+ "b s (g gs) d -> b s g gs d",
775
+ g=num_groups,
776
+ gs=self.grouped_ratio + 1,
777
+ )
778
+ attn1 = attn_reshaped[:, :, :, : self.grouped_ratio, :].reshape(bsz, q_len, -1, self.head_dim)
779
+ attn2_group = attn_reshaped[:, :, :, self.grouped_ratio :, :].reshape(bsz, q_len, num_groups, self.head_dim)
780
+ attn2 = repeat_kv(attn2_group, 2, self.grouped_ratio) # (bsz, q_len, n_signal_heads, head_dim)
781
+
782
+ # Differential: signal - sigmoid(lambda) * noise
783
+ attn_output = attn1 - torch.sigmoid(lambda_full).unsqueeze(-1) * attn2
784
+
785
+ if gate_score is not None:
786
+ attn_output = attn_output * torch.sigmoid(gate_score)
787
+
788
+ return attn_output
789
+
790
+
791
+ class MotifGDLAttention(nn.Module):
792
+ """Grouped Differential Latent Attention (GDLA) for HF Transformers.
793
+
794
+ Ports GDLAttention from torchtitan. Uses low-rank Q and KV projections
795
+ (MLA-style) with RoPE applied only to the qk_rope_head_dim dimensions.
796
+ Only diff_v2=True is fully supported (the motif3 configuration).
797
+ """
798
+
799
+ def __init__(self, config: MotifConfig, layer_idx: Optional[int] = None):
800
+ super().__init__()
801
+ self.config = config
802
+ self.layer_idx = layer_idx
803
+
804
+ self.hidden_size = config.hidden_size
805
+ self.num_heads = config.num_attention_heads
806
+ self.num_key_value_heads = config.num_key_value_heads
807
+ self.head_dim = config.head_dim if config.head_dim is not None else self.hidden_size // self.num_heads
808
+ self.is_causal = True
809
+ self.attention_dropout = config.attention_dropout
810
+
811
+ # Head split
812
+ self.num_noise_heads = config.num_noise_heads
813
+ self.grouped_ratio = (self.num_heads - self.num_noise_heads) // self.num_noise_heads
814
+ self.n_signal_heads = self.grouped_ratio * self.num_noise_heads
815
+
816
+ # GDLA dimensions
817
+ self.q_lora_rank = config.q_lora_rank
818
+ self.kv_lora_rank = config.kv_lora_rank
819
+ self.qk_rope_head_dim = config.qk_rope_head_dim if config.qk_rope_head_dim is not None else self.head_dim // 2
820
+ self.qk_nope_head_dim = self.head_dim - self.qk_rope_head_dim
821
+ self.v_head_dim = config.v_head_dim if config.v_head_dim is not None else self.head_dim
822
+ self.diff_v2 = getattr(config, "diff_v2", True)
823
+
824
+ # Softmax scaling with optional mscale correction (DeepSeek-style)
825
+ self.scaling = self.head_dim**-0.5
826
+ original_seq_len = getattr(config, "original_seq_len", 32768)
827
+ rope_factor = getattr(config, "rope_factor", 1.0)
828
+ mscale = getattr(config, "mscale", 1.0)
829
+ if config.max_position_embeddings > original_seq_len:
830
+ mscale_val = 0.1 * mscale * math.log(rope_factor) + 1.0
831
+ self.scaling = self.scaling * mscale_val * mscale_val
832
+
833
+ # Output gating
834
+ self.elementwise_attn_output_gate = getattr(config, "elementwise_attn_output_gate", False)
835
+ self.headwise_attn_output_gate = getattr(config, "headwise_attn_output_gate", False)
836
+
837
+ # Required by transformers SDPA interface for GQA repeat_kv dispatch
838
+ self.num_key_value_groups = self.num_heads // self.num_key_value_heads
839
+
840
+ RMSNorm = kernelRMSNorm if kernelRMSNorm is not None else MotifRMSNorm
841
+
842
+ # Query LoRA
843
+ self.wq_a = nn.Linear(self.hidden_size, self.q_lora_rank, bias=False)
844
+ self.q_norm = RMSNorm(self.q_lora_rank, eps=config.rms_norm_eps)
845
+
846
+ if self.elementwise_attn_output_gate:
847
+ # Separate gate projection; for V2: n_signal_heads gates; for V1: n_signal_heads*2
848
+ gate_extra = self.n_signal_heads if self.diff_v2 else self.n_signal_heads * 2
849
+ self.wq_b = nn.Linear(self.q_lora_rank, self.num_heads * self.head_dim, bias=False)
850
+ self.wq_b_gate = nn.Linear(self.q_lora_rank, gate_extra * self.v_head_dim, bias=False)
851
+ else:
852
+ self.wq_b = nn.Linear(self.q_lora_rank, self.num_heads * self.head_dim, bias=False)
853
+ self.wq_b_gate = None
854
+
855
+ # KV LoRA: output kv_lora_rank + qk_rope_head_dim
856
+ self.wkv_a = nn.Linear(self.hidden_size, self.kv_lora_rank + self.qk_rope_head_dim, bias=False)
857
+
858
+ if self.diff_v2:
859
+ self.kv_norm = RMSNorm(self.kv_lora_rank, eps=config.rms_norm_eps)
860
+ self.wkv_b = nn.Linear(
861
+ self.kv_lora_rank,
862
+ self.num_key_value_heads * (self.qk_nope_head_dim + self.v_head_dim),
863
+ bias=False,
864
+ )
865
+ self.lambda_proj = nn.Linear(self.hidden_size, self.n_signal_heads, bias=False)
866
+ self.wo = nn.Linear(self.n_signal_heads * self.v_head_dim, self.hidden_size, bias=False)
867
+ else:
868
+ raise NotImplementedError(
869
+ "GDLA V1 (diff_v2=False) is not yet implemented in HF. Use attention_cls='gdla' only with diff_v2=True."
870
+ )
871
+
872
+ # Sliding window (same interleave pattern as basic Attention)
873
+ self.sliding_window = None
874
+ if config.use_sliding_window and getattr(config, "sliding_window", None) is not None:
875
+ pattern = getattr(config, "sliding_window_pattern", "interleave")
876
+ period = getattr(config, "sliding_window_period", 2)
877
+ effective_window = config.sliding_window + 1
878
+ if pattern == "all":
879
+ self.sliding_window = effective_window
880
+ elif pattern == "interleave" and (layer_idx + 1) % period != 0:
881
+ self.sliding_window = effective_window
882
+
883
+ def forward(
884
+ self,
885
+ hidden_states: torch.Tensor,
886
+ attention_mask: Optional[torch.Tensor] = None,
887
+ position_ids: Optional[torch.LongTensor] = None,
888
+ past_key_value: Optional[Cache] = None,
889
+ output_attentions: bool = False,
890
+ use_cache: bool = False,
891
+ cache_position: Optional[torch.LongTensor] = None,
892
+ position_embeddings: Optional[Tuple[torch.Tensor, torch.Tensor]] = None,
893
+ **kwargs,
894
+ ) -> Tuple[torch.Tensor, Optional[torch.Tensor], Optional[Tuple[torch.Tensor]]]:
895
+ bsz, q_len, _ = hidden_states.size()
896
+
897
+ # Q path: down-project -> norm -> up-project
898
+ q_latent = self.q_norm(self.wq_a(hidden_states)) # (bsz, q_len, q_lora_rank)
899
+ q = self.wq_b(q_latent).view(bsz, q_len, self.num_heads, self.head_dim)
900
+
901
+ # Gate score (elementwise)
902
+ gate_score = None
903
+ if self.elementwise_attn_output_gate and self.wq_b_gate is not None:
904
+ gate_score = self.wq_b_gate(q_latent).view(bsz, q_len, -1, self.v_head_dim)
905
+
906
+ # Split Q into nope (no-positional) and rope parts
907
+ q_nope, q_pe = torch.split(q, [self.qk_nope_head_dim, self.qk_rope_head_dim], dim=-1)
908
+
909
+ # KV path: project to kv_lora_rank + qk_rope_head_dim, then split
910
+ kv_raw = self.wkv_a(hidden_states) # (bsz, q_len, kv_lora_rank + qk_rope_head_dim)
911
+ kv_latent, k_pe = torch.split(kv_raw, [self.kv_lora_rank, self.qk_rope_head_dim], dim=-1)
912
+
913
+ # Apply RoPE only to the rope parts (qk_rope_head_dim dims)
914
+ # position_embeddings were computed with qk_rope_head_dim by MotifModel
915
+ cos, sin = position_embeddings # (bsz, q_len, qk_rope_head_dim)
916
+ q_pe = apply_rotary_pos_emb_single(q_pe, cos, sin)
917
+ # k_pe: (bsz, q_len, qk_rope_head_dim) -> add head dim for apply_rotary_pos_emb_single
918
+ k_pe = apply_rotary_pos_emb_single(k_pe.unsqueeze(2), cos, sin) # (bsz, q_len, 1, qk_rope_head_dim)
919
+
920
+ # Reconstruct full Q with nope + rope
921
+ q_total = torch.cat([q_nope, q_pe], dim=-1) # (bsz, q_len, n_heads, head_dim)
922
+
923
+ # KV projection: norm -> project -> split k_nope and v
924
+ kv_latent = kv_latent.contiguous()
925
+ kv_proj = self.wkv_b(self.kv_norm(kv_latent))
926
+ kv_proj = kv_proj.view(bsz, q_len, self.num_key_value_heads, self.qk_nope_head_dim + self.v_head_dim)
927
+ k_nope, v = torch.split(kv_proj, [self.qk_nope_head_dim, self.v_head_dim], dim=-1)
928
+
929
+ # Assemble full K: k_nope + k_pe (broadcast shared rope over all kv heads)
930
+ k_full = torch.cat([k_nope, k_pe.expand(-1, -1, self.num_key_value_heads, -1)], dim=-1)
931
+
932
+ # Lambda (input-dependent for V2)
933
+ lambda_full = self.lambda_proj(hidden_states) # (bsz, q_len, n_signal_heads)
934
+
935
+ # Transpose to (B, H, S, D) before cache (DynamicCache expects this format)
936
+ k_full = k_full.transpose(1, 2) # (bsz, n_kv_heads, q_len, head_dim)
937
+ v = v.transpose(1, 2) # (bsz, n_kv_heads, q_len, v_head_dim)
938
+
939
+ # KV cache
940
+ if past_key_value is not None:
941
+ cache_kwargs = {"cache_position": cache_position}
942
+ k_full, v = past_key_value.update(k_full, v, self.layer_idx, cache_kwargs)
943
+
944
+ dropout_rate = 0.0 if not self.training else self.attention_dropout
945
+
946
+ # Cast dtype if needed
947
+ input_dtype = q_total.dtype
948
+ if input_dtype == torch.float32:
949
+ if torch.is_autocast_enabled():
950
+ target_dtype = torch.get_autocast_gpu_dtype()
951
+ elif hasattr(self.config, "_pre_quantization_dtype"):
952
+ target_dtype = self.config._pre_quantization_dtype
953
+ else:
954
+ target_dtype = self.wq_b.weight.dtype
955
+ q_total = q_total.to(target_dtype)
956
+ k_full = k_full.to(target_dtype)
957
+ v = v.to(target_dtype)
958
+
959
+ # Attention: pad v to head_dim if v_head_dim != head_dim (flash_attn compatibility)
960
+ need_v_pad = self.v_head_dim != self.head_dim
961
+
962
+ attention_interface: Callable = ALL_ATTENTION_FUNCTIONS.get_interface(
963
+ self.config._attn_implementation, eager_attention_forward
964
+ )
965
+
966
+ # k_full and v are already (B, H, S, D); transpose q for interface
967
+ q_t = q_total.transpose(1, 2) # (bsz, n_heads, q_len, head_dim)
968
+ # q_t = q_total
969
+ k_t = k_full # (bsz, n_kv_heads, kv_seq_len, head_dim)
970
+ v_t = v # (bsz, n_kv_heads, kv_seq_len, v_head_dim)
971
+
972
+ if need_v_pad:
973
+ v_t = F.pad(v_t, [0, self.head_dim - self.v_head_dim])
974
+
975
+ # Truncate mask to actual kv length (sliding window cache may return fewer tokens than target_length)
976
+ if attention_mask is not None:
977
+ attention_mask = attention_mask[:, -k_t.shape[-2] :]
978
+
979
+ attn_out, _ = attention_interface(
980
+ self,
981
+ q_t,
982
+ k_t,
983
+ v_t,
984
+ attention_mask,
985
+ dropout=dropout_rate,
986
+ scaling=self.scaling,
987
+ sliding_window=self.sliding_window,
988
+ is_causal=self.is_causal,
989
+ **kwargs,
990
+ )
991
+
992
+ # Normalize to (B, S, H, D)
993
+ if attn_out.shape[1] == self.num_heads: # (B, H, S, D) from SDPA
994
+ attn_out = attn_out.transpose(1, 2)
995
+ # Now (B, S, H, D)
996
+
997
+ if need_v_pad:
998
+ attn_out = attn_out[..., : self.v_head_dim].contiguous()
999
+
1000
+ # Split heads into signal and noise groups
1001
+ num_groups = self.num_noise_heads # n_heads // (grouped_ratio + 1)
1002
+ attn_reshaped = einops.rearrange(
1003
+ attn_out,
1004
+ "b s (g gs) d -> b s g gs d",
1005
+ g=num_groups,
1006
+ gs=self.grouped_ratio + 1,
1007
+ )
1008
+ attn1 = attn_reshaped[:, :, :, : self.grouped_ratio, :].reshape(bsz, q_len, -1, self.v_head_dim)
1009
+ attn2_group = attn_reshaped[:, :, :, self.grouped_ratio :, :].reshape(bsz, q_len, num_groups, self.v_head_dim)
1010
+ attn2 = repeat_kv(attn2_group, 2, self.grouped_ratio) # (bsz, q_len, n_signal_heads, v_head_dim)
1011
+
1012
+ # Differential combination: signal - sigmoid(lambda) * noise
1013
+ attn_output = attn1 - torch.sigmoid(lambda_full).unsqueeze(-1) * attn2
1014
+
1015
+ if gate_score is not None:
1016
+ attn_output = attn_output * torch.sigmoid(gate_score)
1017
+
1018
+ # Output projection
1019
+ attn_output = attn_output.reshape(bsz, q_len, -1)
1020
+ attn_output = self.wo(attn_output)
1021
+
1022
+ return attn_output, None, past_key_value
1023
+
1024
+
1025
+ class TokenChoiceTopKRouter(nn.Module):
1026
+ """This class implements token-choice routing. In token-choice top-K routing, each token is
1027
+ routed to top K experts based on the router scores.
1028
+
1029
+ Args:
1030
+ dim (int): Dimension of input tokens.
1031
+ num_experts (int): Number of experts in each moe layer.
1032
+ experts_top_k (int): Number of experts each token will be routed to in token-choice routing.
1033
+ score_func (Literal["softmax", "sigmoid"]): Whether to use sigmoid or softmax for router scores.
1034
+ route_norm (bool): Whether to normalize the routing scores when using sigmoid.
1035
+ route_scale (float): Scaling factor applied to the routing scores.
1036
+ """
1037
+
1038
+ def __init__(
1039
+ self,
1040
+ hidden_size: int,
1041
+ num_experts: int,
1042
+ experts_top_k: int,
1043
+ score_func: Literal["softmax", "sigmoid"],
1044
+ route_norm: bool,
1045
+ route_scale: float,
1046
+ _debug_force_load_balance: bool = False,
1047
+ ):
1048
+ super().__init__()
1049
+ self.gate = nn.Linear(hidden_size, num_experts, bias=False)
1050
+ self.num_experts = num_experts
1051
+ self.experts_top_k = experts_top_k
1052
+ self.score_func = score_func
1053
+ self.route_norm = route_norm
1054
+ self.route_scale = route_scale
1055
+ self._debug_force_load_balance = _debug_force_load_balance
1056
+
1057
+ def _debug_force_load_balance_routing(self, scores: torch.Tensor) -> tuple[torch.Tensor, torch.Tensor]:
1058
+ """Balanced round-robin expert assignment.
1059
+ Returns (selected_experts_indices [N, K] LongTensor, top_scores [N, K] FloatTensor).
1060
+ """
1061
+ n_tokens = scores.size(0)
1062
+ # Round-robin indices with exact balance
1063
+ selected_experts_indices = (
1064
+ torch.arange(n_tokens * self.experts_top_k, device=scores.device, dtype=torch.int64).reshape(
1065
+ n_tokens, self.experts_top_k
1066
+ )
1067
+ % self.num_experts
1068
+ )
1069
+ top_scores = scores.gather(dim=1, index=selected_experts_indices) # [N,K]
1070
+ return selected_experts_indices, top_scores
1071
+
1072
+ def forward(
1073
+ self, x: torch.Tensor, expert_bias: torch.Tensor | None = None
1074
+ ) -> tuple[torch.Tensor, torch.Tensor, torch.Tensor]:
1075
+ """
1076
+ Args:
1077
+ x (torch.Tensor): Input tensor with shape ``(bs*slen, dim)``.
1078
+ expert_bias (torch.Tensor | None, optional): Optional bias tensor for experts with shape ``(num_experts,)``.
1079
+ Used for load balancing. Defaults to None.
1080
+
1081
+ Returns:
1082
+ tuple[torch.Tensor, torch.Tensor, torch.Tensor]:
1083
+ - top_scores (torch.Tensor):
1084
+ Routing scores for selected experts with shape ``(bs*slen, experts_top_k)``.
1085
+ - selected_experts_indices (torch.Tensor):
1086
+ Expert indices selected for each token with shape ``(bs*slen, experts_top_k)``.
1087
+ - num_tokens_per_expert (torch.Tensor):
1088
+ Number of tokens assigned to each expert with shape ``(num_experts,)``.
1089
+ """
1090
+ # scores shape (bs*slen, num_experts)
1091
+ scores = self.gate(x)
1092
+
1093
+ # By default, sigmoid or softmax is performed in float32 to avoid loss explosion
1094
+ if self.score_func == "sigmoid":
1095
+ scores = torch.sigmoid(scores.to(torch.float32))
1096
+ elif self.score_func == "softmax":
1097
+ scores = F.softmax(scores.to(torch.float32), dim=1)
1098
+ else:
1099
+ raise NotImplementedError(f"Unknown score function {self.score_func}")
1100
+
1101
+ # top scores shape (bs*slen, experts_top_k)
1102
+ # NOTE: The expert_bias is only used for routing. The gating value
1103
+ # top_scores is still derived from the original scores.
1104
+
1105
+ if expert_bias is not None:
1106
+ _, selected_experts_indices = torch.topk(scores + expert_bias, k=self.experts_top_k, dim=1)
1107
+ top_scores = scores.gather(dim=1, index=selected_experts_indices)
1108
+ else:
1109
+ top_scores, selected_experts_indices = torch.topk(scores, k=self.experts_top_k, dim=1)
1110
+
1111
+ # debug override: balanced round-robin routing
1112
+ if self._debug_force_load_balance:
1113
+ (
1114
+ selected_experts_indices,
1115
+ top_scores,
1116
+ ) = self._debug_force_load_balance_routing(scores)
1117
+
1118
+ if self.route_norm:
1119
+ denominator = top_scores.sum(dim=-1, keepdim=True) + 1e-20
1120
+ top_scores = top_scores / denominator
1121
+ top_scores = top_scores * self.route_scale
1122
+
1123
+ num_tokens_per_expert = torch.bincount(selected_experts_indices.view(-1).long(), minlength=self.num_experts).to(
1124
+ dtype=torch.float32
1125
+ )
1126
+
1127
+ return top_scores, selected_experts_indices, num_tokens_per_expert
1128
+
1129
+ def init_weights(self, init_std: float):
1130
+ nn.init.trunc_normal_(self.gate.weight, mean=0.0, std=init_std)
1131
+
1132
+
1133
+ @use_experts_implementation
1134
+ class MotifExperts(nn.Module):
1135
+ """Collection of expert weights stored as fused 3D tensors."""
1136
+
1137
+ def __init__(self, config):
1138
+ super().__init__()
1139
+ self.num_experts = config.num_experts
1140
+ self.hidden_size = config.hidden_size
1141
+ moe_intermediate = getattr(config, "moe_intermediate_size", config.intermediate_size)
1142
+ self.intermediate_dim = moe_intermediate
1143
+
1144
+ # Fused gate+up: [num_experts, 2*intermediate, hidden_size]
1145
+ self.gate_up_proj = nn.Parameter(torch.empty(self.num_experts, 2 * self.intermediate_dim, self.hidden_size))
1146
+ # Down projection: [num_experts, hidden_size, intermediate]
1147
+ self.down_proj = nn.Parameter(torch.empty(self.num_experts, self.hidden_size, self.intermediate_dim))
1148
+ # Per-expert poly norm (grouped) or shared activation
1149
+ if config.hidden_act == "poly_norm":
1150
+ self.act_fn = GroupedPolyNorm(self.num_experts)
1151
+ else:
1152
+ self.act_fn = ACT2FN[config.hidden_act]
1153
+
1154
+ def forward(
1155
+ self,
1156
+ hidden_states: torch.Tensor,
1157
+ top_k_index: torch.Tensor,
1158
+ top_k_weights: torch.Tensor,
1159
+ ) -> torch.Tensor:
1160
+ """Eager expert dispatch (loops over experts).
1161
+
1162
+ Args:
1163
+ hidden_states: [total_tokens, hidden_size]
1164
+ top_k_index: [total_tokens, top_k] expert indices
1165
+ top_k_weights: [total_tokens, top_k] routing weights
1166
+
1167
+ Returns:
1168
+ [total_tokens, hidden_size]
1169
+ """
1170
+ final_hidden_states = torch.zeros_like(hidden_states)
1171
+ expert_mask = F.one_hot(top_k_index, num_classes=self.num_experts).permute(2, 1, 0)
1172
+
1173
+ for expert_idx in range(self.num_experts):
1174
+ top_k_pos, token_idx = torch.where(expert_mask[expert_idx])
1175
+ if token_idx.shape[0] == 0:
1176
+ continue
1177
+
1178
+ current_state = hidden_states[token_idx]
1179
+ gate_up = current_state @ self.gate_up_proj[expert_idx].T # [T, 2*I]
1180
+ current_hidden = self._apply_gate(gate_up, expert_idx) @ self.down_proj[expert_idx].T # [T, H]
1181
+
1182
+ current_hidden = current_hidden * top_k_weights[token_idx, top_k_pos, None]
1183
+ final_hidden_states.index_add_(0, token_idx, current_hidden.to(final_hidden_states.dtype))
1184
+
1185
+ return final_hidden_states
1186
+
1187
+ def _apply_gate(self, gate_up_output: torch.Tensor, expert_idx: int = 0) -> torch.Tensor:
1188
+ gate, up = gate_up_output.chunk(2, dim=-1)
1189
+ # .chunk() returns non-contiguous views; kernel act_fn requires contiguous input
1190
+ gate = gate.contiguous()
1191
+ if isinstance(self.act_fn, GroupedPolyNorm):
1192
+ return self.act_fn.forward_single(gate, expert_idx) * up
1193
+ return self.act_fn(gate) * up
1194
+
1195
+
1196
+ class MoE(nn.Module):
1197
+ def __init__(self, config):
1198
+ super().__init__()
1199
+
1200
+ self.num_experts = config.num_experts
1201
+ self.experts_top_k = config.experts_top_k
1202
+
1203
+ self.experts = MotifExperts(config)
1204
+
1205
+ self.router = TokenChoiceTopKRouter(
1206
+ hidden_size=config.hidden_size,
1207
+ num_experts=config.num_experts,
1208
+ experts_top_k=config.experts_top_k,
1209
+ score_func=config.score_func,
1210
+ route_norm=config.route_norm,
1211
+ route_scale=config.route_scale,
1212
+ _debug_force_load_balance=config._debug_force_load_balance,
1213
+ )
1214
+
1215
+ moe_intermediate = getattr(config, "moe_intermediate_size", config.intermediate_size)
1216
+ self.shared_experts = (
1217
+ MotifMLP(config, intermediate_size=moe_intermediate) if config.num_shared_experts > 0 else None
1218
+ )
1219
+ self.score_before_experts = config.score_before_experts
1220
+
1221
+ # Auxiliary-loss-free load balancing (https://arxiv.org/abs/2408.15664)
1222
+ self.load_balance_coeff = config.load_balance_coeff
1223
+ if self.load_balance_coeff is not None:
1224
+ assert self.load_balance_coeff > 0.0
1225
+ self.expert_bias = nn.Parameter(torch.zeros(config.num_experts, dtype=torch.float32), requires_grad=False)
1226
+ else:
1227
+ self.expert_bias = None
1228
+
1229
+ def forward(self, x: torch.Tensor) -> tuple[torch.Tensor, torch.Tensor]:
1230
+ """
1231
+ Args:
1232
+ x (torch.Tensor): Input tensor with shape ``(bs, slen, dim)``.
1233
+
1234
+ Returns:
1235
+ tuple: (output tensor (bs, slen, dim), router_logits (bs*slen, num_experts))
1236
+ """
1237
+ bs, slen, dim = x.shape
1238
+ x = x.view(-1, dim)
1239
+
1240
+ # Route tokens
1241
+ top_scores, selected_experts_indices, num_tokens_per_expert = self.router(x, self.expert_bias)
1242
+
1243
+ # Track expert usage for load balancing
1244
+
1245
+ # Dispatch to experts
1246
+ if self.score_before_experts:
1247
+ final_hidden_states = self._score_before_forward(x, selected_experts_indices, top_scores)
1248
+ else:
1249
+ final_hidden_states = self.experts(x, selected_experts_indices, top_scores)
1250
+
1251
+ # Shared experts
1252
+ if self.shared_experts is not None:
1253
+ final_hidden_states = final_hidden_states + self.shared_experts(x)
1254
+
1255
+ # Return router logits for auxiliary loss computation
1256
+ router_logits = self.router.gate(x.view(-1, dim)) if hasattr(self.router, "gate") else None
1257
+
1258
+ return final_hidden_states.reshape(bs, slen, dim), router_logits
1259
+
1260
+ def _score_before_forward(
1261
+ self,
1262
+ hidden_states: torch.Tensor,
1263
+ top_k_index: torch.Tensor,
1264
+ top_k_weights: torch.Tensor,
1265
+ ) -> torch.Tensor:
1266
+ """Custom dispatch for score_before_experts mode.
1267
+
1268
+ Pre-weights inputs by routing scores before expert computation,
1269
+ rather than weighting expert outputs (the standard approach).
1270
+ """
1271
+ final_hidden_states = torch.zeros_like(hidden_states)
1272
+ expert_mask = F.one_hot(top_k_index, num_classes=self.num_experts).permute(2, 1, 0)
1273
+
1274
+ for expert_idx in range(self.num_experts):
1275
+ top_k_pos, token_idx = torch.where(expert_mask[expert_idx])
1276
+ if token_idx.shape[0] == 0:
1277
+ continue
1278
+
1279
+ current_state = hidden_states[token_idx]
1280
+ weights = top_k_weights[token_idx, top_k_pos, None]
1281
+ # Pre-weight input
1282
+ current_state = (current_state.to(torch.float32) * weights).to(hidden_states.dtype)
1283
+
1284
+ gate_up = current_state @ self.experts.gate_up_proj[expert_idx].T # [T, 2*I]
1285
+ current_hidden = self.experts._apply_gate(gate_up) @ self.experts.down_proj[expert_idx].T # [T, H]
1286
+
1287
+ final_hidden_states.index_add_(0, token_idx, current_hidden.to(final_hidden_states.dtype))
1288
+
1289
+ return final_hidden_states
1290
+
1291
+ def init_weights(self, init_std: float, buffer_device: torch.device):
1292
+ nn.init.trunc_normal_(self.experts.gate_up_proj, mean=0.0, std=0.02)
1293
+ nn.init.trunc_normal_(self.experts.down_proj, mean=0.0, std=init_std)
1294
+ self.router.init_weights(init_std)
1295
+ if self.shared_experts is not None:
1296
+ nn.init.trunc_normal_(self.shared_experts.gate_proj.weight, mean=0.0, std=0.02)
1297
+ nn.init.trunc_normal_(self.shared_experts.up_proj.weight, mean=0.0, std=init_std)
1298
+ nn.init.trunc_normal_(self.shared_experts.down_proj.weight, mean=0.0, std=init_std)
1299
+ nn.init.zeros_(self.expert_bias)
1300
+
1301
+
1302
+ class MotifDecoderLayer(GradientCheckpointingLayer):
1303
+ _ATTN_CLS = {
1304
+ "basic": MotifAttention,
1305
+ "gdla": MotifGDLAttention,
1306
+ }
1307
+
1308
+ def __init__(self, config: MotifConfig, layer_idx: int):
1309
+ super().__init__()
1310
+ self.hidden_size = config.hidden_size
1311
+
1312
+ attention_cls_name = getattr(config, "attention_cls", "basic")
1313
+ attn_cls = self._ATTN_CLS.get(attention_cls_name)
1314
+ if attn_cls is None:
1315
+ raise ValueError(f"Unknown attention_cls={attention_cls_name!r}, expected one of {list(self._ATTN_CLS)}")
1316
+ self.self_attn = attn_cls(config, layer_idx)
1317
+
1318
+ # n_dense_first_layers: first N layers always dense (no MoE)
1319
+ n_dense_first = getattr(config, "n_dense_first_layers", 0)
1320
+ self.moe_enabled = (
1321
+ layer_idx >= n_dense_first and (layer_idx + 1) % config.interleave_moe_layer_step == 0
1322
+ if config.interleave_moe_layer_step != 0
1323
+ else False
1324
+ )
1325
+
1326
+ if self.moe_enabled:
1327
+ self.moe = MoE(config)
1328
+ else:
1329
+ self.mlp = MotifMLP(config)
1330
+
1331
+ RMSNorm = kernelRMSNorm if kernelRMSNorm is not None else MotifRMSNorm
1332
+ self.input_layernorm = RMSNorm(config.hidden_size, eps=config.rms_norm_eps)
1333
+ self.post_attention_layernorm = RMSNorm(config.hidden_size, eps=config.rms_norm_eps)
1334
+
1335
+ # MHC (Manifold-constrained Hyper-Connections) layers
1336
+ self.mhc_enabled = getattr(config, "mhc_enabled", False)
1337
+ if self.mhc_enabled:
1338
+ mhc_expansion_rate = config.mhc_expansion_rate
1339
+ self.mhc_attn = MHCLayer(
1340
+ expansion_rate=mhc_expansion_rate,
1341
+ num_dim=config.hidden_size,
1342
+ identity_init=getattr(config, "mhc_identity_init", False),
1343
+ sinkhorn_iters=getattr(config, "mhc_sinkhorn_iters", 20),
1344
+ )
1345
+ self.mhc_ffn = MHCLayer(
1346
+ expansion_rate=mhc_expansion_rate,
1347
+ num_dim=config.hidden_size,
1348
+ identity_init=getattr(config, "mhc_identity_init", False),
1349
+ sinkhorn_iters=getattr(config, "mhc_sinkhorn_iters", 20),
1350
+ )
1351
+
1352
+ def forward(
1353
+ self,
1354
+ hidden_states: torch.Tensor,
1355
+ attention_mask: Optional[torch.Tensor] = None,
1356
+ position_ids: Optional[torch.LongTensor] = None,
1357
+ past_key_value: Optional[Tuple[torch.Tensor]] = None,
1358
+ output_attentions: Optional[bool] = False,
1359
+ use_cache: Optional[bool] = False,
1360
+ cache_position: Optional[torch.LongTensor] = None,
1361
+ position_embeddings: Optional[Tuple[torch.Tensor, torch.Tensor]] = None, # will become mandatory in v4.46
1362
+ **kwargs,
1363
+ ) -> Tuple[torch.FloatTensor, Optional[Tuple[torch.FloatTensor, torch.FloatTensor]]]:
1364
+ """
1365
+ Args:
1366
+ hidden_states (`torch.FloatTensor`): input to the layer of shape `(batch, seq_len, embed_dim)`
1367
+ attention_mask (`torch.FloatTensor`, *optional*): attention mask of size
1368
+ `(batch, sequence_length)` where padding elements are indicated by 0.
1369
+ output_attentions (`bool`, *optional*):
1370
+ Whether or not to return the attentions tensors of all attention layers. See `attentions` under
1371
+ returned tensors for more detail.
1372
+ use_cache (`bool`, *optional*):
1373
+ If set to `True`, `past_key_values` key value states are returned and can be used to speed up decoding
1374
+ (see `past_key_values`).
1375
+ past_key_value (`Tuple(torch.FloatTensor)`, *optional*): cached past key and value projection states
1376
+ cache_position (`torch.LongTensor` of shape `(sequence_length)`, *optional*):
1377
+ Indices depicting the position of the input sequence tokens in the sequence.
1378
+ position_embeddings (`Tuple[torch.FloatTensor, torch.FloatTensor]`, *optional*):
1379
+ Tuple containing the cosine and sine positional embeddings of shape `(batch_size, seq_len, head_dim)`,
1380
+ with `head_dim` being the embedding dimension of each attention head.
1381
+ kwargs (`dict`, *optional*):
1382
+ Arbitrary kwargs to be ignored, used for FSDP and other methods that injects code
1383
+ into the model
1384
+ """
1385
+
1386
+ if self.mhc_enabled:
1387
+ return self._forward_with_mhc(
1388
+ hidden_states,
1389
+ attention_mask=attention_mask,
1390
+ position_ids=position_ids,
1391
+ past_key_value=past_key_value,
1392
+ output_attentions=output_attentions,
1393
+ use_cache=use_cache,
1394
+ cache_position=cache_position,
1395
+ position_embeddings=position_embeddings,
1396
+ )
1397
+
1398
+ residual = hidden_states
1399
+
1400
+ hidden_states = self.input_layernorm(hidden_states)
1401
+
1402
+ # Self Attention
1403
+ hidden_states, self_attn_weights, present_key_value = self.self_attn(
1404
+ hidden_states=hidden_states,
1405
+ attention_mask=attention_mask,
1406
+ position_ids=position_ids,
1407
+ past_key_value=past_key_value,
1408
+ output_attentions=output_attentions,
1409
+ use_cache=use_cache,
1410
+ cache_position=cache_position,
1411
+ position_embeddings=position_embeddings,
1412
+ )
1413
+ hidden_states = residual + hidden_states
1414
+
1415
+ # Fully Connected
1416
+ residual = hidden_states
1417
+ hidden_states = self.post_attention_layernorm(hidden_states)
1418
+
1419
+ router_logits = None
1420
+ if self.moe_enabled:
1421
+ hidden_states, router_logits = self.moe(hidden_states)
1422
+ else:
1423
+ hidden_states = self.mlp(hidden_states)
1424
+ hidden_states = residual + hidden_states
1425
+
1426
+ outputs = (hidden_states,)
1427
+
1428
+ if output_attentions:
1429
+ outputs += (self_attn_weights,)
1430
+
1431
+ if use_cache:
1432
+ outputs += (present_key_value,)
1433
+
1434
+ outputs += (router_logits,)
1435
+
1436
+ return outputs
1437
+
1438
+ def _forward_with_mhc(
1439
+ self,
1440
+ hidden_states: torch.Tensor,
1441
+ attention_mask: Optional[torch.Tensor] = None,
1442
+ position_ids: Optional[torch.LongTensor] = None,
1443
+ past_key_value: Optional[Tuple[torch.Tensor]] = None,
1444
+ output_attentions: Optional[bool] = False,
1445
+ use_cache: Optional[bool] = False,
1446
+ cache_position: Optional[torch.LongTensor] = None,
1447
+ position_embeddings: Optional[Tuple[torch.Tensor, torch.Tensor]] = None,
1448
+ ) -> Tuple:
1449
+ """MHC residual path. hidden_states: (batch, seq_len, expansion_rate, dim)."""
1450
+ x = hidden_states
1451
+
1452
+ # === Attention sublayer with MHC ===
1453
+ h_pre_attn, h_post_attn, h_res_attn = self.mhc_attn(x)
1454
+
1455
+ # Reduce for attention input: (B, S, E, D) -> (B, S, D)
1456
+ x_reduced = MHCLayer.apply_h_pre(x, h_pre_attn)
1457
+
1458
+ attn_in = self.input_layernorm(x_reduced)
1459
+ attn_out, self_attn_weights, present_key_value = self.self_attn(
1460
+ hidden_states=attn_in,
1461
+ attention_mask=attention_mask,
1462
+ position_ids=position_ids,
1463
+ past_key_value=past_key_value,
1464
+ output_attentions=output_attentions,
1465
+ use_cache=use_cache,
1466
+ cache_position=cache_position,
1467
+ position_embeddings=position_embeddings,
1468
+ )
1469
+
1470
+ # Expand attention output: (B, S, D) -> (B, S, E, D)
1471
+ attn_expanded = MHCLayer.apply_h_post(attn_out, h_post_attn)
1472
+ # Apply H_res to residual stream
1473
+ x_res_attn = MHCLayer.apply_h_res(x, h_res_attn)
1474
+ h = x_res_attn + attn_expanded
1475
+
1476
+ # === FFN sublayer with MHC ===
1477
+ h_pre_ffn, h_post_ffn, h_res_ffn = self.mhc_ffn(h)
1478
+
1479
+ # Reduce for FFN input: (B, S, E, D) -> (B, S, D)
1480
+ h_reduced = MHCLayer.apply_h_pre(h, h_pre_ffn)
1481
+ n_out = self.post_attention_layernorm(h_reduced)
1482
+
1483
+ router_logits = None
1484
+ if self.moe_enabled:
1485
+ ffn_out, router_logits = self.moe(n_out)
1486
+ else:
1487
+ ffn_out = self.mlp(n_out)
1488
+
1489
+ # Expand FFN output: (B, S, D) -> (B, S, E, D)
1490
+ ffn_expanded = MHCLayer.apply_h_post(ffn_out, h_post_ffn)
1491
+ h_res_ffn_out = MHCLayer.apply_h_res(h, h_res_ffn)
1492
+ out = h_res_ffn_out + ffn_expanded
1493
+
1494
+ outputs = (out,)
1495
+
1496
+ if output_attentions:
1497
+ outputs += (self_attn_weights,)
1498
+
1499
+ if use_cache:
1500
+ outputs += (present_key_value,)
1501
+
1502
+ outputs += (router_logits,)
1503
+
1504
+ return outputs
1505
+
1506
+
1507
+ @auto_docstring
1508
+ class MotifPreTrainedModel(PreTrainedModel):
1509
+ config_class = MotifConfig
1510
+ base_model_prefix = "model"
1511
+ supports_gradient_checkpointing = True
1512
+ _no_split_modules = ["MotifDecoderLayer"]
1513
+ _skip_keys_device_placement = "past_key_values"
1514
+ _supports_flash_attn = True
1515
+ _supports_sdpa = True
1516
+ _supports_flex_attn = True
1517
+ _supports_attention_backend = True
1518
+ _supports_cache_class = True
1519
+ _supports_quantized_cache = True
1520
+ _supports_static_cache = True
1521
+
1522
+ def _init_weights(self, module):
1523
+ std = self.config.initializer_range
1524
+ if isinstance(module, nn.Linear):
1525
+ module.weight.data = torch.where(abs(module.weight.data) > 3 * std, 0, module.weight.data)
1526
+ if module.bias is not None:
1527
+ module.bias.data.zero_()
1528
+ elif isinstance(module, nn.Embedding):
1529
+ module.weight.data = torch.where(abs(module.weight.data) > 3 * std, 0, module.weight.data)
1530
+ if module.padding_idx is not None:
1531
+ module.weight.data[module.padding_idx].zero_()
1532
+ elif isinstance(module, MoE):
1533
+ module.init_weights(std, buffer_device=torch.device("cpu"))
1534
+ elif isinstance(module, MotifRotaryEmbedding):
1535
+ effective_head_dim = module.inv_freq.shape[0] * 2
1536
+ inv_freq = 1.0 / (
1537
+ self.config.rope_theta
1538
+ ** (torch.arange(0, effective_head_dim, 2, dtype=torch.int64).float() / effective_head_dim)
1539
+ )
1540
+ module.register_buffer("inv_freq", inv_freq, persistent=False)
1541
+
1542
+
1543
+ @auto_docstring
1544
+ class MotifModel(MotifPreTrainedModel):
1545
+ """
1546
+ Transformer decoder consisting of *config.num_hidden_layers* layers. Each layer is a [`MotifDecoderLayer`]
1547
+
1548
+ Args:
1549
+ config: MotifConfig
1550
+ """
1551
+
1552
+ def __init__(self, config: MotifConfig):
1553
+ super().__init__(config)
1554
+ self.padding_idx = getattr(config, "pad_token_id", None)
1555
+ self.vocab_size = config.vocab_size
1556
+
1557
+ self.embed_tokens = nn.Embedding(config.vocab_size, config.hidden_size, self.padding_idx)
1558
+ self.layers = nn.ModuleList(
1559
+ [MotifDecoderLayer(config, layer_idx) for layer_idx in range(config.num_hidden_layers)]
1560
+ )
1561
+ self._attn_implementation = config._attn_implementation
1562
+ RMSNorm = kernelRMSNorm if kernelRMSNorm is not None else MotifRMSNorm
1563
+ self.norm = RMSNorm(config.hidden_size, eps=config.rms_norm_eps)
1564
+ # GDLA applies RoPE only to qk_rope_head_dim dimensions
1565
+ rope_head_dim = (
1566
+ getattr(config, "qk_rope_head_dim", None) if getattr(config, "attention_cls", "basic") == "gdla" else None
1567
+ )
1568
+ self.rotary_emb = MotifRotaryEmbedding(config=config, rope_head_dim=rope_head_dim)
1569
+
1570
+ self.mhc_enabled = getattr(config, "mhc_enabled", False)
1571
+ self.mhc_expansion_rate = getattr(config, "mhc_expansion_rate", 4)
1572
+
1573
+ self.gradient_checkpointing = False
1574
+ # Initialize weights and apply final processing
1575
+ self.post_init()
1576
+
1577
+ def get_input_embeddings(self):
1578
+ return self.embed_tokens
1579
+
1580
+ def set_input_embeddings(self, value):
1581
+ self.embed_tokens = value
1582
+
1583
+ @can_return_tuple
1584
+ @auto_docstring
1585
+ def forward(
1586
+ self,
1587
+ input_ids: torch.LongTensor = None,
1588
+ attention_mask: Optional[torch.Tensor] = None,
1589
+ position_ids: Optional[torch.LongTensor] = None,
1590
+ past_key_values: Optional[Cache] = None,
1591
+ inputs_embeds: Optional[torch.FloatTensor] = None,
1592
+ use_cache: Optional[bool] = None,
1593
+ output_attentions: Optional[bool] = None,
1594
+ output_hidden_states: Optional[bool] = None,
1595
+ output_router_logits: Optional[bool] = None,
1596
+ return_dict: Optional[bool] = None,
1597
+ cache_position: Optional[torch.LongTensor] = None,
1598
+ ) -> MoeModelOutputWithPast:
1599
+ output_attentions = output_attentions if output_attentions is not None else self.config.output_attentions
1600
+ output_hidden_states = (
1601
+ output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states
1602
+ )
1603
+ output_router_logits = (
1604
+ output_router_logits
1605
+ if output_router_logits is not None
1606
+ else getattr(self.config, "output_router_logits", False)
1607
+ )
1608
+ use_cache = use_cache if use_cache is not None else self.config.use_cache
1609
+
1610
+ if (input_ids is None) ^ (inputs_embeds is not None):
1611
+ raise ValueError("You must specify exactly one of input_ids or inputs_embeds")
1612
+
1613
+ if self.gradient_checkpointing and self.training:
1614
+ if use_cache:
1615
+ logger.warning_once(
1616
+ "`use_cache=True` is incompatible with gradient checkpointing. Setting `use_cache=False`..."
1617
+ )
1618
+ use_cache = False
1619
+
1620
+ if use_cache and past_key_values is None:
1621
+ past_key_values = DynamicCache()
1622
+
1623
+ if inputs_embeds is None:
1624
+ inputs_embeds = self.embed_tokens(input_ids)
1625
+
1626
+ if cache_position is None:
1627
+ past_seen_tokens = past_key_values.get_seq_length() if past_key_values is not None else 0
1628
+ cache_position = torch.arange(
1629
+ past_seen_tokens, past_seen_tokens + inputs_embeds.shape[1], device=inputs_embeds.device
1630
+ )
1631
+ if position_ids is None:
1632
+ position_ids = cache_position.unsqueeze(0)
1633
+
1634
+ causal_mask = self._update_causal_mask(
1635
+ attention_mask, inputs_embeds, cache_position, past_key_values, output_attentions
1636
+ )
1637
+
1638
+ hidden_states = inputs_embeds
1639
+
1640
+ # Create position embeddings BEFORE MHC expansion (uses (B, S, D) for dtype/device)
1641
+ position_embeddings = self.rotary_emb(hidden_states, position_ids)
1642
+
1643
+ # Expand to (B, S, E, D) for MHC
1644
+ if self.mhc_enabled:
1645
+ hidden_states = hidden_states.unsqueeze(2).expand(-1, -1, self.mhc_expansion_rate, -1).contiguous()
1646
+
1647
+ # Decoder layers
1648
+ all_hidden_states = () if output_hidden_states else None
1649
+ all_self_attns = () if output_attentions else None
1650
+ all_router_logits = () if output_router_logits else None
1651
+ next_decoder_cache = None
1652
+
1653
+ for decoder_layer in self.layers:
1654
+ if output_hidden_states:
1655
+ all_hidden_states += (hidden_states,)
1656
+
1657
+ layer_outputs = decoder_layer(
1658
+ hidden_states,
1659
+ attention_mask=causal_mask,
1660
+ position_ids=position_ids,
1661
+ past_key_value=past_key_values,
1662
+ output_attentions=output_attentions,
1663
+ use_cache=use_cache,
1664
+ cache_position=cache_position,
1665
+ position_embeddings=position_embeddings,
1666
+ )
1667
+
1668
+ hidden_states = layer_outputs[0]
1669
+
1670
+ if use_cache:
1671
+ next_decoder_cache = layer_outputs[2 if output_attentions else 1]
1672
+
1673
+ if output_attentions:
1674
+ all_self_attns += (layer_outputs[1],)
1675
+
1676
+ # Router logits are always the last element
1677
+ if output_router_logits:
1678
+ all_router_logits += (layer_outputs[-1],)
1679
+
1680
+ # Reduce from (B, S, E, D) back to (B, S, D) for MHC
1681
+ if self.mhc_enabled:
1682
+ hidden_states = hidden_states.mean(dim=2)
1683
+
1684
+ hidden_states = self.norm(hidden_states)
1685
+
1686
+ # Add hidden states from the last decoder layer
1687
+ if output_hidden_states:
1688
+ all_hidden_states += (hidden_states,)
1689
+
1690
+ next_cache = next_decoder_cache if use_cache else None
1691
+
1692
+ return MoeModelOutputWithPast(
1693
+ last_hidden_state=hidden_states,
1694
+ past_key_values=next_cache,
1695
+ hidden_states=all_hidden_states,
1696
+ attentions=all_self_attns,
1697
+ router_logits=all_router_logits,
1698
+ )
1699
+
1700
+ def _update_causal_mask(
1701
+ self,
1702
+ attention_mask: torch.Tensor,
1703
+ input_tensor: torch.Tensor,
1704
+ cache_position: torch.Tensor,
1705
+ past_key_values: Cache,
1706
+ output_attentions: bool,
1707
+ ):
1708
+ if self.config._attn_implementation == "flash_attention_2":
1709
+ if attention_mask is not None and 0.0 in attention_mask:
1710
+ return attention_mask
1711
+ return None
1712
+
1713
+ # For SDPA, when possible, we will rely on its `is_causal` argument instead of its `attn_mask` argument, in
1714
+ # order to dispatch on Flash Attention 2. This feature is not compatible with static cache, as SDPA will fail
1715
+ # to infer the attention mask.
1716
+ past_seen_tokens = past_key_values.get_seq_length() if past_key_values is not None else 0
1717
+ using_static_cache = isinstance(past_key_values, StaticCache)
1718
+
1719
+ # When output attentions is True, sdpa implementation's forward method calls the eager implementation's forward
1720
+ if self.config._attn_implementation == "sdpa" and not using_static_cache and not output_attentions:
1721
+ if AttentionMaskConverter._ignore_causal_mask_sdpa(
1722
+ attention_mask,
1723
+ inputs_embeds=input_tensor,
1724
+ past_key_values_length=past_seen_tokens,
1725
+ sliding_window=self.config.sliding_window,
1726
+ is_training=self.training,
1727
+ ):
1728
+ return None
1729
+
1730
+ dtype, device = input_tensor.dtype, input_tensor.device
1731
+ min_dtype = torch.finfo(dtype).min
1732
+ sequence_length = input_tensor.shape[1]
1733
+ # StaticCache
1734
+ if using_static_cache:
1735
+ target_length = past_key_values.get_max_cache_shape()
1736
+ # DynamicCache or no cache
1737
+ else:
1738
+ target_length = (
1739
+ attention_mask.shape[-1]
1740
+ if isinstance(attention_mask, torch.Tensor)
1741
+ else past_seen_tokens + sequence_length
1742
+ )
1743
+
1744
+ # In case the provided `attention` mask is 2D, we generate a causal mask here (4D).
1745
+ causal_mask = self._prepare_4d_causal_attention_mask_with_cache_position(
1746
+ attention_mask,
1747
+ sequence_length=sequence_length,
1748
+ target_length=target_length,
1749
+ dtype=dtype,
1750
+ device=device,
1751
+ cache_position=cache_position,
1752
+ batch_size=input_tensor.shape[0],
1753
+ config=self.config,
1754
+ past_key_values=past_key_values,
1755
+ )
1756
+
1757
+ if (
1758
+ self.config._attn_implementation == "sdpa"
1759
+ and attention_mask is not None
1760
+ and attention_mask.device.type == "cuda"
1761
+ and not output_attentions
1762
+ ):
1763
+ # Attend to all tokens in fully masked rows in the causal_mask, for example the relevant first rows when
1764
+ # using left padding. This is required by F.scaled_dot_product_attention memory-efficient attention path.
1765
+ # Details: https://github.com/pytorch/pytorch/issues/110213
1766
+ causal_mask = AttentionMaskConverter._unmask_unattended(causal_mask, min_dtype)
1767
+
1768
+ return causal_mask
1769
+
1770
+ @staticmethod
1771
+ def _prepare_4d_causal_attention_mask_with_cache_position(
1772
+ attention_mask: torch.Tensor,
1773
+ sequence_length: int,
1774
+ target_length: int,
1775
+ dtype: torch.dtype,
1776
+ device: torch.device,
1777
+ cache_position: torch.Tensor,
1778
+ batch_size: int,
1779
+ config: MotifConfig,
1780
+ past_key_values: Cache,
1781
+ ):
1782
+ """
1783
+ Creates a causal 4D mask of shape `(batch_size, 1, query_length, key_value_length)` from a 2D mask of shape
1784
+ `(batch_size, key_value_length)`, or if the input `attention_mask` is already 4D, do nothing.
1785
+
1786
+ Args:
1787
+ attention_mask (`torch.Tensor`):
1788
+ A 2D attention mask of shape `(batch_size, key_value_length)` or a 4D attention mask of shape `(batch_size, 1, query_length, key_value_length)`.
1789
+ sequence_length (`int`):
1790
+ The sequence length being processed.
1791
+ target_length (`int`):
1792
+ The target length: when generating with static cache, the mask should be as long as the static cache, to account for the 0 padding, the part of the cache that is not filled yet.
1793
+ dtype (`torch.dtype`):
1794
+ The dtype to use for the 4D attention mask.
1795
+ device (`torch.device`):
1796
+ The device to plcae the 4D attention mask on.
1797
+ cache_position (`torch.Tensor`):
1798
+ Indices depicting the position of the input sequence tokens in the sequence.
1799
+ batch_size (`torch.Tensor`):
1800
+ Batch size.
1801
+ config (`MotifConfig`):
1802
+ The model's configuration class
1803
+ past_key_values (`Cache`):
1804
+ The cache class that is being used currently to generate
1805
+ """
1806
+ if attention_mask is not None and attention_mask.dim() == 4:
1807
+ # In this case we assume that the mask comes already in inverted form and requires no inversion or slicing.
1808
+ causal_mask = attention_mask
1809
+ else:
1810
+ min_dtype = torch.finfo(dtype).min
1811
+ causal_mask = torch.full(
1812
+ (sequence_length, target_length), fill_value=min_dtype, dtype=dtype, device=cache_position.device
1813
+ )
1814
+ diagonal_attend_mask = torch.arange(target_length, device=cache_position.device) > cache_position.reshape(
1815
+ -1, 1
1816
+ )
1817
+ if config.sliding_window is not None:
1818
+ # if we have sliding window, we should not attend to tokens beyond sliding window length, so we mask them out also
1819
+ # the check is needed to verify is current checkpoint was trained with sliding window or not
1820
+ if sequence_length > target_length:
1821
+ sliding_attend_mask = torch.arange(target_length, device=device) <= (
1822
+ cache_position.reshape(-1, 1) - config.sliding_window
1823
+ )
1824
+ diagonal_attend_mask.bitwise_or_(sliding_attend_mask)
1825
+ causal_mask *= diagonal_attend_mask
1826
+ causal_mask = causal_mask[None, None, :, :].expand(batch_size, 1, -1, -1)
1827
+ if attention_mask is not None:
1828
+ causal_mask = causal_mask.clone() # copy to contiguous memory for in-place edit
1829
+ if attention_mask.shape[-1] > target_length:
1830
+ attention_mask = attention_mask[:, :target_length]
1831
+ mask_length = attention_mask.shape[-1]
1832
+ padding_mask = causal_mask[:, :, :, :mask_length] + attention_mask[:, None, None, :]
1833
+ padding_mask = padding_mask == 0
1834
+ causal_mask[:, :, :, :mask_length] = causal_mask[:, :, :, :mask_length].masked_fill(
1835
+ padding_mask, min_dtype
1836
+ )
1837
+ return causal_mask
1838
+
1839
+
1840
+ class MotifForCausalLM(MotifPreTrainedModel, GenerationMixin):
1841
+ _tied_weights_keys = {"lm_head.weight": "model.embed_tokens.weight"}
1842
+ _tp_plan = {"lm_head": "colwise_gather_output"}
1843
+ _pp_plan = {"lm_head": (["hidden_states"], ["logits"])}
1844
+
1845
+ def __init__(self, config):
1846
+ super().__init__(config)
1847
+ self.model = MotifModel(config)
1848
+ self.vocab_size = config.vocab_size
1849
+ self.lm_head = nn.Linear(config.hidden_size, config.vocab_size, bias=False)
1850
+
1851
+ # Initialize weights and apply final processing
1852
+ self.post_init()
1853
+
1854
+ if config.tie_word_embeddings:
1855
+ self.tie_weights()
1856
+
1857
+ def get_input_embeddings(self):
1858
+ return self.model.embed_tokens
1859
+
1860
+ def set_input_embeddings(self, value):
1861
+ self.model.embed_tokens = value
1862
+
1863
+ def get_output_embeddings(self):
1864
+ return self.lm_head
1865
+
1866
+ def set_output_embeddings(self, new_embeddings):
1867
+ self.lm_head = new_embeddings
1868
+
1869
+ def set_decoder(self, decoder):
1870
+ self.model = decoder
1871
+
1872
+ def get_decoder(self):
1873
+ return self.model
1874
+
1875
+ @can_return_tuple
1876
+ @auto_docstring
1877
+ def forward(
1878
+ self,
1879
+ input_ids: torch.LongTensor = None,
1880
+ attention_mask: Optional[torch.Tensor] = None,
1881
+ position_ids: Optional[torch.LongTensor] = None,
1882
+ past_key_values: Optional[Cache] = None,
1883
+ inputs_embeds: Optional[torch.FloatTensor] = None,
1884
+ labels: Optional[torch.LongTensor] = None,
1885
+ use_cache: Optional[bool] = None,
1886
+ output_attentions: Optional[bool] = None,
1887
+ output_hidden_states: Optional[bool] = None,
1888
+ output_router_logits: Optional[bool] = None,
1889
+ return_dict: Optional[bool] = None,
1890
+ cache_position: Optional[torch.LongTensor] = None,
1891
+ logits_to_keep: int = 0,
1892
+ **kwargs,
1893
+ ) -> MoeCausalLMOutputWithPast:
1894
+ output_attentions = output_attentions if output_attentions is not None else self.config.output_attentions
1895
+ output_hidden_states = (
1896
+ output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states
1897
+ )
1898
+ output_router_logits = (
1899
+ output_router_logits
1900
+ if output_router_logits is not None
1901
+ else getattr(self.config, "output_router_logits", False)
1902
+ )
1903
+
1904
+ # decoder outputs consists of (dec_features, layer_state, dec_hidden, dec_attn)
1905
+ outputs = self.model(
1906
+ input_ids=input_ids,
1907
+ attention_mask=attention_mask,
1908
+ position_ids=position_ids,
1909
+ past_key_values=past_key_values,
1910
+ inputs_embeds=inputs_embeds,
1911
+ use_cache=use_cache,
1912
+ output_attentions=output_attentions,
1913
+ output_hidden_states=output_hidden_states,
1914
+ output_router_logits=output_router_logits,
1915
+ cache_position=cache_position,
1916
+ )
1917
+
1918
+ hidden_states = outputs[0]
1919
+ # Only compute necessary logits, and do not upcast them to float if we are not computing the loss
1920
+ logits = self.lm_head(hidden_states[:, -logits_to_keep:, :])
1921
+ logits = logits.float()
1922
+
1923
+ loss = None
1924
+ if labels is not None:
1925
+ # Shift so that tokens < n predict n
1926
+ shift_logits = logits[..., :-1, :].contiguous()
1927
+ shift_labels = labels[..., 1:].contiguous()
1928
+ # Flatten the tokens
1929
+ loss_fct = CrossEntropyLoss()
1930
+ shift_logits = shift_logits.view(-1, self.config.vocab_size)
1931
+ shift_labels = shift_labels.view(-1)
1932
+ # Enable model parallelism
1933
+ shift_labels = shift_labels.to(shift_logits.device)
1934
+ loss = loss_fct(shift_logits, shift_labels)
1935
+
1936
+ return MoeCausalLMOutputWithPast(
1937
+ loss=loss,
1938
+ logits=logits,
1939
+ past_key_values=outputs.past_key_values,
1940
+ hidden_states=outputs.hidden_states,
1941
+ attentions=outputs.attentions,
1942
+ router_logits=outputs.router_logits,
1943
+ )
tokenizer.json ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:5dc7fe0e557b116bd25eb0185aeaa7672a19368def3e10630a83d48f08447df5
3
+ size 17548406
tokenizer_config.json ADDED
@@ -0,0 +1,29 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "backend": "tokenizers",
3
+ "bos_token": "<|beginoftext|>",
4
+ "eos_token": "<|endoftext|>",
5
+ "extra_special_tokens": [
6
+ "<|system|>",
7
+ "<|user|>",
8
+ "<|assistant|>",
9
+ "<|startofturn|>",
10
+ "<|endofturn|>",
11
+ "<|tool|>",
12
+ "<|reference|>",
13
+ "<|plan|>",
14
+ "<|endofplan|>",
15
+ "<tool_response>",
16
+ "</tool_response>",
17
+ "<latent>",
18
+ "<latent_pad>",
19
+ "</latent>"
20
+ ],
21
+ "is_local": true,
22
+ "local_files_only": false,
23
+ "model_max_length": 1000000000000000019884624838656,
24
+ "pad_token": "<|endoftext|>",
25
+ "padding_side": "left",
26
+ "split_special_tokens": false,
27
+ "tokenizer_class": "TokenizersBackend",
28
+ "truncation_side": "left"
29
+ }