iamPi commited on
Commit
d7ea461
·
verified ·
1 Parent(s): c81570f

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
chat_template.jinja ADDED
@@ -0,0 +1,154 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {%- set image_count = namespace(value=0) %}
2
+ {%- set video_count = namespace(value=0) %}
3
+ {%- macro render_content(content, do_vision_count, is_system_content=false) %}
4
+ {%- if content is string %}
5
+ {{- content }}
6
+ {%- elif content is iterable and content is not mapping %}
7
+ {%- for item in content %}
8
+ {%- if 'image' in item or 'image_url' in item or item.type == 'image' %}
9
+ {%- if is_system_content %}
10
+ {{- raise_exception('System message cannot contain images.') }}
11
+ {%- endif %}
12
+ {%- if do_vision_count %}
13
+ {%- set image_count.value = image_count.value + 1 %}
14
+ {%- endif %}
15
+ {%- if add_vision_id %}
16
+ {{- 'Picture ' ~ image_count.value ~ ': ' }}
17
+ {%- endif %}
18
+ {{- '<|vision_start|><|image_pad|><|vision_end|>' }}
19
+ {%- elif 'video' in item or item.type == 'video' %}
20
+ {%- if is_system_content %}
21
+ {{- raise_exception('System message cannot contain videos.') }}
22
+ {%- endif %}
23
+ {%- if do_vision_count %}
24
+ {%- set video_count.value = video_count.value + 1 %}
25
+ {%- endif %}
26
+ {%- if add_vision_id %}
27
+ {{- 'Video ' ~ video_count.value ~ ': ' }}
28
+ {%- endif %}
29
+ {{- '<|vision_start|><|video_pad|><|vision_end|>' }}
30
+ {%- elif 'text' in item %}
31
+ {{- item.text }}
32
+ {%- else %}
33
+ {{- raise_exception('Unexpected item type in content.') }}
34
+ {%- endif %}
35
+ {%- endfor %}
36
+ {%- elif content is none or content is undefined %}
37
+ {{- '' }}
38
+ {%- else %}
39
+ {{- raise_exception('Unexpected content type.') }}
40
+ {%- endif %}
41
+ {%- endmacro %}
42
+ {%- if not messages %}
43
+ {{- raise_exception('No messages provided.') }}
44
+ {%- endif %}
45
+ {%- if tools and tools is iterable and tools is not mapping %}
46
+ {{- '<|im_start|>system\n' }}
47
+ {{- "# Tools\n\nYou have access to the following functions:\n\n<tools>" }}
48
+ {%- for tool in tools %}
49
+ {{- "\n" }}
50
+ {{- tool | tojson }}
51
+ {%- endfor %}
52
+ {{- "\n</tools>" }}
53
+ {{- '\n\nIf you choose to call a function ONLY reply in the following format with NO suffix:\n\n<tool_call>\n<function=example_function_name>\n<parameter=example_parameter_1>\nvalue_1\n</parameter>\n<parameter=example_parameter_2>\nThis is the value for the second parameter\nthat can span\nmultiple lines\n</parameter>\n</function>\n</tool_call>\n\n<IMPORTANT>\nReminder:\n- Function calls MUST follow the specified format: an inner <function=...></function> block must be nested within <tool_call></tool_call> XML tags\n- Required parameters MUST be specified\n- You may provide optional reasoning for your function call in natural language BEFORE the function call, but NOT after\n- If there is no function call available, answer the question like normal with your current knowledge and do not tell the user about function calls\n</IMPORTANT>' }}
54
+ {%- if messages[0].role == 'system' %}
55
+ {%- set content = render_content(messages[0].content, false, true)|trim %}
56
+ {%- if content %}
57
+ {{- '\n\n' + content }}
58
+ {%- endif %}
59
+ {%- endif %}
60
+ {{- '<|im_end|>\n' }}
61
+ {%- else %}
62
+ {%- if messages[0].role == 'system' %}
63
+ {%- set content = render_content(messages[0].content, false, true)|trim %}
64
+ {{- '<|im_start|>system\n' + content + '<|im_end|>\n' }}
65
+ {%- endif %}
66
+ {%- endif %}
67
+ {%- set ns = namespace(multi_step_tool=true, last_query_index=messages|length - 1) %}
68
+ {%- for message in messages[::-1] %}
69
+ {%- set index = (messages|length - 1) - loop.index0 %}
70
+ {%- if ns.multi_step_tool and message.role == "user" %}
71
+ {%- set content = render_content(message.content, false)|trim %}
72
+ {%- if not(content.startswith('<tool_response>') and content.endswith('</tool_response>')) %}
73
+ {%- set ns.multi_step_tool = false %}
74
+ {%- set ns.last_query_index = index %}
75
+ {%- endif %}
76
+ {%- endif %}
77
+ {%- endfor %}
78
+ {%- if ns.multi_step_tool %}
79
+ {{- raise_exception('No user query found in messages.') }}
80
+ {%- endif %}
81
+ {%- for message in messages %}
82
+ {%- set content = render_content(message.content, true)|trim %}
83
+ {%- if message.role == "system" %}
84
+ {%- if not loop.first %}
85
+ {{- raise_exception('System message must be at the beginning.') }}
86
+ {%- endif %}
87
+ {%- elif message.role == "user" %}
88
+ {{- '<|im_start|>' + message.role + '\n' + content + '<|im_end|>' + '\n' }}
89
+ {%- elif message.role == "assistant" %}
90
+ {%- set reasoning_content = '' %}
91
+ {%- if message.reasoning_content is string %}
92
+ {%- set reasoning_content = message.reasoning_content %}
93
+ {%- else %}
94
+ {%- if '</think>' in content %}
95
+ {%- set reasoning_content = content.split('</think>')[0].rstrip('\n').split('<think>')[-1].lstrip('\n') %}
96
+ {%- set content = content.split('</think>')[-1].lstrip('\n') %}
97
+ {%- endif %}
98
+ {%- endif %}
99
+ {%- set reasoning_content = reasoning_content|trim %}
100
+ {%- if loop.index0 > ns.last_query_index %}
101
+ {{- '<|im_start|>' + message.role + '\n<think>\n' + reasoning_content + '\n</think>\n\n' + content }}
102
+ {%- else %}
103
+ {{- '<|im_start|>' + message.role + '\n' + content }}
104
+ {%- endif %}
105
+ {%- if message.tool_calls and message.tool_calls is iterable and message.tool_calls is not mapping %}
106
+ {%- for tool_call in message.tool_calls %}
107
+ {%- if tool_call.function is defined %}
108
+ {%- set tool_call = tool_call.function %}
109
+ {%- endif %}
110
+ {%- if loop.first %}
111
+ {%- if content|trim %}
112
+ {{- '\n\n<tool_call>\n<function=' + tool_call.name + '>\n' }}
113
+ {%- else %}
114
+ {{- '<tool_call>\n<function=' + tool_call.name + '>\n' }}
115
+ {%- endif %}
116
+ {%- else %}
117
+ {{- '\n<tool_call>\n<function=' + tool_call.name + '>\n' }}
118
+ {%- endif %}
119
+ {%- if tool_call.arguments is defined %}
120
+ {%- for args_name, args_value in tool_call.arguments|items %}
121
+ {{- '<parameter=' + args_name + '>\n' }}
122
+ {%- set args_value = args_value | tojson | safe if args_value is mapping or (args_value is sequence and args_value is not string) else args_value | string %}
123
+ {{- args_value }}
124
+ {{- '\n</parameter>\n' }}
125
+ {%- endfor %}
126
+ {%- endif %}
127
+ {{- '</function>\n</tool_call>' }}
128
+ {%- endfor %}
129
+ {%- endif %}
130
+ {{- '<|im_end|>\n' }}
131
+ {%- elif message.role == "tool" %}
132
+ {%- if loop.previtem and loop.previtem.role != "tool" %}
133
+ {{- '<|im_start|>user' }}
134
+ {%- endif %}
135
+ {{- '\n<tool_response>\n' }}
136
+ {{- content }}
137
+ {{- '\n</tool_response>' }}
138
+ {%- if not loop.last and loop.nextitem.role != "tool" %}
139
+ {{- '<|im_end|>\n' }}
140
+ {%- elif loop.last %}
141
+ {{- '<|im_end|>\n' }}
142
+ {%- endif %}
143
+ {%- else %}
144
+ {{- raise_exception('Unexpected message role.') }}
145
+ {%- endif %}
146
+ {%- endfor %}
147
+ {%- if add_generation_prompt %}
148
+ {{- '<|im_start|>assistant\n' }}
149
+ {%- if enable_thinking is defined and enable_thinking is false %}
150
+ {{- '<think>\n\n</think>\n\n' }}
151
+ {%- else %}
152
+ {{- '<think>\n' }}
153
+ {%- endif %}
154
+ {%- endif %}
config.json ADDED
@@ -0,0 +1,126 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "allow_neg_eigval": false,
3
+ "architectures": [
4
+ "QuasarForCausalLM"
5
+ ],
6
+ "attn_mode": "chunk",
7
+ "auto_map": {
8
+ "AutoConfig": "configuration_quasar.QuasarConfig",
9
+ "AutoModelForCausalLM": "modeling_quasar.QuasarForCausalLM"
10
+ },
11
+ "bigmac_r": 0.25,
12
+ "bos_token_id": null,
13
+ "conv_bias": false,
14
+ "conv_size": 4,
15
+ "d_ff": 4096,
16
+ "d_model": 1536,
17
+ "dense_input_layers": 4,
18
+ "dropout": 0.0,
19
+ "dtype": "bfloat16",
20
+ "eos_token_id": 248044,
21
+ "expand_k": 0.5,
22
+ "expand_v": 1.0,
23
+ "fuse_cross_entropy": true,
24
+ "fuse_norm": true,
25
+ "fuse_swiglu": true,
26
+ "gated_layers": 2,
27
+ "gla_mode": "chunk",
28
+ "gradient_checkpointing": false,
29
+ "head_dim": 128,
30
+ "hidden_act": "silu",
31
+ "hidden_ratio": 4,
32
+ "hidden_size": 1536,
33
+ "hybrid_layer_types": [
34
+ "quasar",
35
+ "quasar",
36
+ "quasar",
37
+ "quasar",
38
+ "gla",
39
+ "gla",
40
+ "quasar",
41
+ "quasar",
42
+ "quasar",
43
+ "quasar",
44
+ "gla",
45
+ "gla",
46
+ "quasar",
47
+ "quasar",
48
+ "quasar",
49
+ "quasar",
50
+ "gla",
51
+ "gla",
52
+ "quasar",
53
+ "quasar",
54
+ "quasar",
55
+ "quasar",
56
+ "gla",
57
+ "gla"
58
+ ],
59
+ "initializer_range": 0.02,
60
+ "intermediate_size": 4096,
61
+ "layer_types": [
62
+ "linear_attention",
63
+ "linear_attention",
64
+ "linear_attention",
65
+ "linear_attention",
66
+ "linear_attention",
67
+ "linear_attention",
68
+ "linear_attention",
69
+ "linear_attention",
70
+ "linear_attention",
71
+ "linear_attention",
72
+ "linear_attention",
73
+ "linear_attention",
74
+ "linear_attention",
75
+ "linear_attention",
76
+ "linear_attention",
77
+ "linear_attention",
78
+ "linear_attention",
79
+ "linear_attention",
80
+ "linear_attention",
81
+ "linear_attention",
82
+ "linear_attention",
83
+ "linear_attention",
84
+ "linear_attention",
85
+ "linear_attention"
86
+ ],
87
+ "looped_injection_init": 0.1,
88
+ "max_position_embeddings": 16384,
89
+ "max_seq_len": 16384,
90
+ "memory_dim": 128,
91
+ "memory_slots": 128,
92
+ "model_type": "quasar",
93
+ "moe_aux_loss_coeff": 0.0001,
94
+ "moe_type": "bigmac",
95
+ "moe_z_loss_coeff": 0.0001,
96
+ "n_heads": 12,
97
+ "n_layers": 24,
98
+ "norm_eps": 1e-06,
99
+ "num_attention_heads": 12,
100
+ "num_heads": 12,
101
+ "num_hidden_layers": 24,
102
+ "num_key_value_heads": 12,
103
+ "num_loops": 1,
104
+ "num_routed_experts": 64,
105
+ "num_shared_experts": 1,
106
+ "num_v_heads": null,
107
+ "pad_token_id": 248044,
108
+ "quasar_layers": 4,
109
+ "residual_scale": 0.1,
110
+ "rms_norm_eps": 1e-06,
111
+ "rope_theta": 1000000.0,
112
+ "routed_expert_size": 256,
113
+ "shared_expert_size": 3072,
114
+ "smebu_beta": 0.5,
115
+ "smebu_kappa": 2.0,
116
+ "smebu_lambda": 0.002,
117
+ "tie_word_embeddings": false,
118
+ "top_k": 4,
119
+ "transformers_version": "5.7.0",
120
+ "use_cache": false,
121
+ "use_gla_first": false,
122
+ "use_l2warp": false,
123
+ "use_looped_injection": false,
124
+ "use_short_conv": true,
125
+ "vocab_size": 248320
126
+ }
configuration_quasar.py ADDED
@@ -0,0 +1,197 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Quasar model configuration — HuggingFace compatible.
2
+
3
+ """
4
+
5
+ from transformers.configuration_utils import PreTrainedConfig
6
+
7
+
8
+ class QuasarConfig(PreTrainedConfig):
9
+ model_type = "quasar"
10
+ keys_to_ignore_at_inference = ["past_key_values"]
11
+
12
+ def __init__(
13
+ self,
14
+ # Core dimensions
15
+ vocab_size: int = 248320,
16
+ d_model: int = 1536,
17
+ n_layers: int = 24,
18
+ n_heads: int = 12,
19
+ d_ff: int = 4096,
20
+ head_dim: int = 128,
21
+ max_seq_len: int = 16384,
22
+ dropout: float = 0.0,
23
+ rms_norm_eps: float = 1e-6,
24
+ initializer_range: float = 0.02,
25
+ use_cache: bool = True,
26
+ tie_word_embeddings: bool = False,
27
+ # HF aliases (set automatically)
28
+ # hidden_size = d_model, num_hidden_layers = n_layers, etc.
29
+ # Hybrid layer config
30
+ quasar_layers: int = 4,
31
+ gated_layers: int = 2,
32
+ use_gla_first: bool = False,
33
+ # QuasarAttention params
34
+ use_short_conv: bool = True,
35
+ conv_size: int = 4,
36
+ conv_bias: bool = False,
37
+ allow_neg_eigval: bool = False,
38
+ attn_mode: str = "chunk",
39
+ # GLA params
40
+ expand_k: float = 0.5,
41
+ expand_v: float = 1.0,
42
+ gla_mode: str = "chunk",
43
+ # Latent Memory params
44
+ memory_slots: int = 128,
45
+ memory_dim: int = 128,
46
+ # MoE params
47
+ moe_type: str = "bigmac",
48
+ num_shared_experts: int = 1,
49
+ num_routed_experts: int = 64,
50
+ top_k: int = 4,
51
+ shared_expert_size: int = 3072,
52
+ routed_expert_size: int = 256,
53
+ dense_input_layers: int = 4,
54
+ bigmac_r: float = 0.25,
55
+ # MoE stability (SMEBU)
56
+ moe_z_loss_coeff: float = 1e-4,
57
+ moe_aux_loss_coeff: float = 1e-4,
58
+ smebu_kappa: float = 2.0,
59
+ smebu_lambda: float = 2e-3,
60
+ smebu_beta: float = 0.5,
61
+ # Looped transformer
62
+ num_loops: int = 1,
63
+ use_looped_injection: bool = False,
64
+ looped_injection_init: float = 0.1,
65
+ # RoPE
66
+ rope_theta: float = 1000000.0,
67
+ # Training
68
+ gradient_checkpointing: bool = False,
69
+ residual_scale: float = 0.1,
70
+ # FLA compatibility
71
+ fuse_norm: bool = True,
72
+ fuse_swiglu: bool = True,
73
+ fuse_cross_entropy: bool = True,
74
+ use_l2warp: bool = False,
75
+ hidden_act: str = "silu",
76
+ hidden_ratio: int | None = 4,
77
+ # Token ids
78
+ pad_token_id: int | None = None,
79
+ bos_token_id: int = 1,
80
+ eos_token_id: int = 2,
81
+ **kwargs,
82
+ ):
83
+ self.vocab_size = vocab_size
84
+ self.d_model = d_model
85
+ self.hidden_size = d_model
86
+ self.n_layers = n_layers
87
+ self.num_hidden_layers = n_layers
88
+ self.n_heads = n_heads
89
+ self.num_attention_heads = n_heads
90
+ self.num_heads = n_heads # FLA alias
91
+ self.d_ff = d_ff
92
+ self.intermediate_size = d_ff
93
+ self.head_dim = head_dim
94
+ self.max_seq_len = max_seq_len
95
+ self.max_position_embeddings = max_seq_len
96
+ self.dropout = dropout
97
+ self.rms_norm_eps = rms_norm_eps
98
+ self.norm_eps = rms_norm_eps # FLA alias
99
+ self.initializer_range = initializer_range
100
+ self.use_cache = use_cache
101
+ self.tie_word_embeddings = tie_word_embeddings
102
+
103
+ # Hybrid layer config
104
+ self.quasar_layers = quasar_layers
105
+ self.gated_layers = gated_layers
106
+ self.use_gla_first = use_gla_first
107
+
108
+ # layer_types uses HF-allowed values only (for validation)
109
+ # hybrid_layer_types stores the actual quasar/gla distinction
110
+ # Always force layer_types to HF-safe values, even if quasar/gla passed in
111
+ self.hybrid_layer_types = self._build_hybrid_layer_types()
112
+ self.layer_types = ["linear_attention"] * self.n_layers
113
+
114
+ # QuasarAttention params
115
+ self.use_short_conv = use_short_conv
116
+ self.conv_size = conv_size
117
+ self.conv_bias = conv_bias
118
+ self.allow_neg_eigval = allow_neg_eigval
119
+ self.attn_mode = attn_mode
120
+
121
+ # GLA params
122
+ self.expand_k = expand_k
123
+ self.expand_v = expand_v
124
+ self.gla_mode = gla_mode
125
+
126
+ # Latent Memory
127
+ self.memory_slots = memory_slots
128
+ self.memory_dim = memory_dim
129
+
130
+ # MoE
131
+ self.moe_type = moe_type
132
+ self.num_shared_experts = num_shared_experts
133
+ self.num_routed_experts = num_routed_experts
134
+ self.top_k = top_k
135
+ self.shared_expert_size = shared_expert_size
136
+ self.routed_expert_size = routed_expert_size
137
+ self.dense_input_layers = dense_input_layers
138
+ self.bigmac_r = bigmac_r
139
+
140
+ # SMEBU
141
+ self.moe_z_loss_coeff = moe_z_loss_coeff
142
+ self.moe_aux_loss_coeff = moe_aux_loss_coeff
143
+ self.smebu_kappa = smebu_kappa
144
+ self.smebu_lambda = smebu_lambda
145
+ self.smebu_beta = smebu_beta
146
+
147
+ # Looped transformer
148
+ self.num_loops = num_loops
149
+ self.use_looped_injection = use_looped_injection
150
+ self.looped_injection_init = looped_injection_init
151
+
152
+ # RoPE
153
+ self.rope_theta = rope_theta
154
+
155
+ # Training
156
+ self.gradient_checkpointing = gradient_checkpointing
157
+ self.residual_scale = residual_scale
158
+
159
+ # FLA compatibility
160
+ self.fuse_norm = fuse_norm
161
+ self.fuse_swiglu = fuse_swiglu
162
+ self.fuse_cross_entropy = fuse_cross_entropy
163
+ self.use_l2warp = use_l2warp
164
+ self.hidden_act = hidden_act
165
+ self.hidden_ratio = hidden_ratio
166
+
167
+ # KV heads (for HF compatibility)
168
+ self.num_key_value_heads = kwargs.get("num_key_value_heads", n_heads)
169
+ self.num_v_heads = kwargs.get("num_v_heads", None)
170
+
171
+ # Pop layer_types from kwargs to prevent PreTrainedConfig from overriding
172
+ # our HF-safe value with quasar/gla from config.json
173
+ kwargs.pop("layer_types", None)
174
+
175
+ super().__init__(
176
+ pad_token_id=pad_token_id,
177
+ bos_token_id=bos_token_id,
178
+ eos_token_id=eos_token_id,
179
+ tie_word_embeddings=tie_word_embeddings,
180
+ **kwargs,
181
+ )
182
+
183
+ def _build_hybrid_layer_types(self) -> list[str]:
184
+ """Internal quasar/gla distinction — not validated by HF."""
185
+ cycle_len = self.quasar_layers + self.gated_layers
186
+ types = []
187
+ for i in range(self.n_layers):
188
+ pos_in_cycle = i % cycle_len
189
+ if self.use_gla_first:
190
+ is_quasar = pos_in_cycle >= self.gated_layers
191
+ else:
192
+ is_quasar = pos_in_cycle < self.quasar_layers
193
+ types.append("quasar" if is_quasar else "gla")
194
+ return types
195
+
196
+
197
+ __all__ = ["QuasarConfig"]
generation_config.json ADDED
@@ -0,0 +1,13 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "_from_model_config": true,
3
+ "do_sample": true,
4
+ "eos_token_id": [
5
+ 248044,
6
+ 248044,
7
+ 2
8
+ ],
9
+ "pad_token_id": 248044,
10
+ "top_k": 4,
11
+ "transformers_version": "5.7.0",
12
+ "use_cache": true
13
+ }
model.safetensors ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:201c223993cf74d730433565a53660c689aadd37c849f94a4fb45fb97e1e909b
3
+ size 5879960192
modeling_quasar.py ADDED
@@ -0,0 +1,1102 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Quasar hybrid transformer — HuggingFace compatible.
2
+
3
+ """
4
+
5
+ import math
6
+ from dataclasses import dataclass
7
+
8
+ import torch
9
+ import torch.nn as nn
10
+ import torch.nn.functional as F
11
+ import torch.utils.checkpoint
12
+ from transformers import GenerationMixin
13
+ from transformers.cache_utils import Cache
14
+ from transformers.modeling_outputs import BaseModelOutputWithPast, CausalLMOutputWithPast
15
+ from transformers.modeling_utils import PreTrainedModel
16
+ from transformers.utils import logging
17
+
18
+ from .configuration_quasar import QuasarConfig
19
+
20
+ logger = logging.get_logger(__name__)
21
+
22
+ # FLA layer imports — required
23
+ from fla.layers.quasar import QuasarAttention
24
+ from fla.layers.gla import GatedLinearAttention
25
+ from fla.models.utils import Cache as FlaCache, FLAGenerationMixin
26
+
27
+ # Fused triton kernels (speed + VRAM). Optional — fall back to eager paths if a
28
+ # given fla build does not ship them, so the model still loads everywhere.
29
+ try:
30
+ from fla.modules import FusedLinearCrossEntropyLoss as _FusedLinearCE
31
+ except Exception:
32
+ _FusedLinearCE = None
33
+ try:
34
+ from fla.modules import RMSNorm as _FusedRMSNorm
35
+ except Exception:
36
+ _FusedRMSNorm = None
37
+ try:
38
+ from fla.modules.activations import swiglu_linear as _swiglu_linear
39
+ except Exception:
40
+ _swiglu_linear = None
41
+
42
+
43
+ # ===================================================================
44
+ # RMSNorm (standalone — weight name: .weight, no bias)
45
+ # ===================================================================
46
+ class _EagerRMSNorm(nn.Module):
47
+ def __init__(self, hidden_size, eps=1e-6):
48
+ super().__init__()
49
+ self.weight = nn.Parameter(torch.ones(hidden_size))
50
+ self.variance_epsilon = eps
51
+
52
+ def forward(self, hidden_states):
53
+ input_dtype = hidden_states.dtype
54
+ hidden_states = hidden_states.to(torch.float32)
55
+ variance = hidden_states.pow(2).mean(-1, keepdim=True)
56
+ hidden_states = hidden_states * torch.rsqrt(variance + self.variance_epsilon)
57
+ return self.weight * hidden_states.to(input_dtype)
58
+
59
+
60
+ if _FusedRMSNorm is not None:
61
+ class RMSNorm(_FusedRMSNorm):
62
+ """Fused (triton) RMSNorm. Keeps the ``(hidden_size, eps)`` ctor and the
63
+ ``.weight`` parameter name so every call-site and checkpoint key is
64
+ unchanged — it is a drop-in for the eager implementation above."""
65
+
66
+ def __init__(self, hidden_size, eps=1e-6):
67
+ super().__init__(hidden_size=hidden_size, elementwise_affine=True,
68
+ bias=False, eps=eps)
69
+ else:
70
+ RMSNorm = _EagerRMSNorm
71
+
72
+
73
+ # ===================================================================
74
+ # Rotary Embedding (persistent inv_freq to match checkpoint)
75
+ # ===================================================================
76
+ class RotaryEmbedding(nn.Module):
77
+ def __init__(self, dim, max_position_embeddings=4096, base=100000, device=None):
78
+ super().__init__()
79
+ self.dim = dim
80
+ self.max_position_embeddings = max_position_embeddings
81
+ self.base = base
82
+ inv_freq = 1.0 / (base ** (torch.arange(0, dim, 2).float().to(device) / dim))
83
+ self.register_buffer("inv_freq", inv_freq, persistent=False)
84
+ # Pre-compute cos/sin cache
85
+ t = torch.arange(max_position_embeddings + 1, device=device, dtype=inv_freq.dtype)
86
+ freqs = torch.einsum("i,j->ij", t, inv_freq)
87
+ emb = torch.cat((freqs, freqs), dim=-1)
88
+ self.register_buffer("_cos_cached", emb.cos()[None, None, :, :], persistent=False)
89
+ self.register_buffer("_sin_cached", emb.sin()[None, None, :, :], persistent=False)
90
+
91
+ def forward(self, x, seq_len=None):
92
+ if seq_len is not None and seq_len > self._cos_cached.shape[2]:
93
+ t = torch.arange(seq_len + 1024, device=x.device, dtype=self.inv_freq.dtype)
94
+ freqs = torch.einsum("i,j->ij", t, self.inv_freq)
95
+ emb = torch.cat((freqs, freqs), dim=-1)
96
+ self.register_buffer("_cos_cached", emb.cos()[None, None, :, :].to(self._cos_cached.dtype), persistent=False)
97
+ self.register_buffer("_sin_cached", emb.sin()[None, None, :, :].to(self._sin_cached.dtype), persistent=False)
98
+ return (
99
+ self._cos_cached[:, :, :seq_len, ...].to(dtype=x.dtype),
100
+ self._sin_cached[:, :, :seq_len, ...].to(dtype=x.dtype),
101
+ )
102
+
103
+
104
+ # ===================================================================
105
+ # Latent Memory Module (use_triton=False — PyTorch bmm is faster)
106
+ # ===================================================================
107
+ class LatentMemoryModule(nn.Module):
108
+ """Persistent Latent Parameter Memory — weight names match checkpoint."""
109
+
110
+ def __init__(self, hidden_size, memory_slots=128, memory_dim=128, use_triton=False):
111
+ super().__init__()
112
+ self.K = memory_slots
113
+ self.D = memory_dim
114
+
115
+ self.W_eta = nn.Linear(hidden_size, 1, bias=True)
116
+ nn.init.zeros_(self.W_eta.weight)
117
+ nn.init.constant_(self.W_eta.bias, -5.0)
118
+
119
+ self.segment_len = 64
120
+ self.summary_query = nn.Parameter(torch.randn(1, 1, memory_dim))
121
+ self.summary_proj = nn.Linear(hidden_size, memory_dim, bias=True)
122
+ self.eta_channels = nn.Parameter(torch.ones(1, 1, memory_dim))
123
+ self.temperature = nn.Parameter(torch.ones(1))
124
+ self.hidden_size = hidden_size
125
+ self.use_triton = False
126
+ self.input_norm = nn.LayerNorm(hidden_size)
127
+ self.compress_z = nn.Sequential(
128
+ nn.Linear(hidden_size, memory_dim * 2, bias=False),
129
+ nn.SiLU(),
130
+ nn.Linear(memory_dim * 2, memory_dim, bias=False),
131
+ )
132
+ self.W_qkv_mem = nn.Linear(hidden_size, memory_dim * 3, bias=False)
133
+ self.scale = 1.0 / math.sqrt(memory_dim)
134
+
135
+ def get_diversity_loss(self, M):
136
+ B, K, D = M.shape
137
+ M_norm = F.normalize(M, p=2, dim=-1)
138
+ sim = torch.bmm(M_norm, M_norm.transpose(1, 2))
139
+ mask = torch.eye(K, device=M.device).unsqueeze(0)
140
+ sim = sim * (1 - mask)
141
+ return sim.pow(2).mean()
142
+
143
+ def write_memory(self, H, M, chunk_idx=0):
144
+ H = self.input_norm(H)
145
+ B, T, _ = H.shape
146
+ H_mem = self.summary_proj(H)
147
+ eta_tokens = self.W_eta(H).squeeze(-1)
148
+
149
+ L = self.segment_len
150
+ if T % L != 0:
151
+ pad_len = L - (T % L)
152
+ H_padded = F.pad(H_mem, (0, 0, 0, pad_len))
153
+ eta_padded = F.pad(eta_tokens, (0, pad_len), value=-10.0)
154
+ else:
155
+ H_padded = H_mem
156
+ eta_padded = eta_tokens
157
+
158
+ T_pad = H_padded.shape[1]
159
+ num_segments = T_pad // L
160
+ H_segs = H_padded.view(B * num_segments, L, self.D)
161
+
162
+ summary_scores = torch.bmm(
163
+ self.summary_query.expand(B * num_segments, -1, -1),
164
+ H_segs.transpose(1, 2),
165
+ )
166
+ summary_weights = F.softmax(summary_scores * self.scale, dim=-1)
167
+ Z_seg = torch.bmm(summary_weights, H_segs).view(B, num_segments, self.D)
168
+
169
+ eta_raw_sig = torch.sigmoid(eta_tokens)
170
+ eta_seg_sig = torch.max(
171
+ torch.sigmoid(eta_padded.view(B, num_segments, L)), dim=-1, keepdim=True
172
+ )[0]
173
+
174
+ scores = torch.bmm(Z_seg, M.transpose(-1, -2)) * self.scale * torch.exp(self.temperature)
175
+ A = F.softmax(scores, dim=-1)
176
+ DeltaM_seg = torch.bmm(A.transpose(1, 2), Z_seg * eta_seg_sig)
177
+ eta_avg = eta_seg_sig.mean(dim=1, keepdim=True)
178
+ gate = eta_avg * torch.sigmoid(self.eta_channels)
179
+ M_new = (1.0 - gate) * M + DeltaM_seg / num_segments
180
+ norm_sq = torch.sum(DeltaM_seg ** 2) / num_segments
181
+ div_loss = self.get_diversity_loss(M_new)
182
+ return M_new, norm_sq * 0.01 + div_loss * 0.1, eta_raw_sig
183
+
184
+ def read_memory(self, H, M, memory_scale=1.0):
185
+ H = self.input_norm(H)
186
+ qkv_mem = self.W_qkv_mem(H)
187
+ _, _, Q_r = torch.split(qkv_mem, [self.D, self.D, self.D], dim=-1)
188
+ scores = torch.bmm(Q_r, M.transpose(-1, -2))
189
+ if M.shape[1] > 1024:
190
+ top_k = 64
191
+ top_vals, top_idx = torch.topk(scores, top_k, dim=-1)
192
+ mask = torch.full_like(scores, float('-inf'))
193
+ mask.scatter_(-1, top_idx, top_vals)
194
+ scores = mask
195
+ A = F.softmax(scores * 2.0, dim=-1)
196
+ C = torch.bmm(A, M)
197
+ return C * memory_scale
198
+
199
+
200
+ # ===================================================================
201
+ # FFN Components
202
+ # ===================================================================
203
+ class SwiGLUBlock(nn.Module):
204
+ """Dense FFN — weight names: gate.weight, up.weight, down.weight"""
205
+
206
+ def __init__(self, d_model, d_ff):
207
+ super().__init__()
208
+ self.gate = nn.Linear(d_model, d_ff, bias=False)
209
+ self.up = nn.Linear(d_model, d_ff, bias=False)
210
+ self.down = nn.Linear(d_ff, d_model, bias=False)
211
+
212
+ def forward(self, x):
213
+ if _swiglu_linear is not None:
214
+ # Fuses silu(gate)*up *and* the down projection in one triton kernel,
215
+ # discarding the [*, d_ff] intermediate. down.bias is None (bias=False).
216
+ return _swiglu_linear(self.gate(x), self.up(x), self.down.weight, self.down.bias)
217
+ return self.down(F.silu(self.gate(x)) * self.up(x))
218
+
219
+
220
+ class SigmoidRouter(nn.Module):
221
+ """Router with router_weights Parameter — weight name: router.router_weights"""
222
+
223
+ def __init__(self, d_model, num_experts):
224
+ super().__init__()
225
+ self.router_weights = nn.Parameter(torch.zeros(num_experts, d_model))
226
+ nn.init.kaiming_uniform_(self.router_weights, a=math.sqrt(5))
227
+
228
+ def forward(self, x):
229
+ logits = F.linear(x, self.router_weights)
230
+ scores = torch.sigmoid(logits)
231
+ return scores, logits
232
+
233
+
234
+ class BigMacMoE(nn.Module):
235
+ """BigMac MoE with DCCA bottleneck — matches checkpoint weight names exactly.
236
+
237
+ Weights: w_down_proj, w_up_proj, experts_w12, experts_w3,
238
+ router.router_weights, shared_experts.{i}.{gate,up,down}.weight,
239
+ max_vio
240
+ """
241
+
242
+ def __init__(self, config, layer_idx=None):
243
+ super().__init__()
244
+ self.d_model = config.d_model
245
+ self.bigmac_r = getattr(config, 'bigmac_r', 0.25)
246
+ self.bottle_dim = int(self.d_model * self.bigmac_r)
247
+
248
+ self.num_shared_experts = getattr(config, 'num_shared_experts', 1)
249
+ self.num_routed_experts = getattr(config, 'num_routed_experts', 64)
250
+ self.top_k = getattr(config, 'top_k', 4)
251
+
252
+ default_routed_size = int(getattr(config, 'routed_expert_size', 768) / self.bigmac_r)
253
+ self.routed_expert_size = getattr(config, 'bigmac_expert_size', default_routed_size)
254
+ self.shared_expert_size = getattr(config, 'shared_expert_size', config.d_ff)
255
+ self.layer_idx = layer_idx
256
+
257
+ self.shared_experts = nn.ModuleList([
258
+ SwiGLUBlock(self.d_model, self.shared_expert_size)
259
+ for _ in range(self.num_shared_experts)
260
+ ])
261
+
262
+ # BigMac DCCA Projections
263
+ self.w_down_proj = nn.Linear(self.d_model, self.bottle_dim, bias=False)
264
+ self.w_up_proj = nn.Linear(self.bottle_dim, self.d_model, bias=False)
265
+
266
+ # BigMac Experts (fused gate+up W12, down W3)
267
+ self.experts_w12 = nn.Parameter(torch.zeros(self.num_routed_experts, self.bottle_dim, 2 * self.routed_expert_size))
268
+ self.experts_w3 = nn.Parameter(torch.zeros(self.num_routed_experts, self.routed_expert_size, self.bottle_dim))
269
+
270
+ self.router = SigmoidRouter(self.d_model, self.num_routed_experts)
271
+
272
+ self.expert_bias = None
273
+ self.expert_momentum = None
274
+ self.smebu_kappa = getattr(config, 'smebu_kappa', 2.0)
275
+ self.smebu_lambda = getattr(config, 'smebu_lambda', 2e-3)
276
+ self.smebu_beta = getattr(config, 'smebu_beta', 0.5)
277
+
278
+ self.z_loss_weight = getattr(config, 'moe_z_loss_coeff', 1e-4)
279
+ self.aux_loss_weight = getattr(config, 'moe_aux_loss_coeff', 1e-4)
280
+ self.register_buffer("max_vio", torch.tensor(0.0))
281
+ self.route_scale = math.sqrt(self.top_k)
282
+ self.moe_scale = 1.0 / (1.0 + float(self.num_shared_experts > 0))
283
+
284
+ # Buffers for padded BMM dispatch
285
+ self.register_buffer("_dummy_token", torch.zeros(1, self.bottle_dim, dtype=torch.bfloat16), persistent=False)
286
+ self.register_buffer("_dummy_out", torch.zeros(1, self.bottle_dim, dtype=torch.bfloat16), persistent=False)
287
+ self._cached_N = -1
288
+ self._cached_K = -1
289
+ self._cached_indices = None
290
+
291
+ def _init_weights(self, std=0.011):
292
+ nn.init.normal_(self.w_down_proj.weight, std=std)
293
+ nn.init.normal_(self.w_up_proj.weight, std=std)
294
+ nn.init.normal_(self.experts_w12, std=std)
295
+ nn.init.normal_(self.experts_w3, std=std)
296
+ for expert in self.shared_experts:
297
+ nn.init.normal_(expert.gate.weight, std=std)
298
+ nn.init.normal_(expert.up.weight, std=std)
299
+ nn.init.normal_(expert.down.weight, std=std)
300
+
301
+ def forward(self, x, expert_bias=None):
302
+ batch_size, seq_len, d_model = x.shape
303
+ hidden_states = x.view(-1, d_model)
304
+ N, D = hidden_states.shape
305
+ K = self.top_k
306
+ num_tokens_total = N * K
307
+
308
+ # 1. Routing & Gating
309
+ with torch.autocast(device_type=x.device.type, dtype=torch.float32):
310
+ scores, logits = self.router(hidden_states)
311
+ z_loss = torch.mean(logits.nan_to_num() ** 2) * self.z_loss_weight
312
+
313
+ bias = expert_bias if expert_bias is not None else torch.zeros(self.num_routed_experts, device=x.device)
314
+ selection_scores = scores + bias
315
+ _, topk_indices = torch.topk(selection_scores, K, dim=-1)
316
+ topk_indices = topk_indices.clamp(0, logits.shape[1] - 1)
317
+
318
+ topk_logits = torch.gather(logits, 1, topk_indices)
319
+ gating_scores = F.softmax(topk_logits, dim=-1).to(torch.bfloat16)
320
+
321
+ # 2. Aux loss
322
+ if self.training:
323
+ flat_topk_idx = topk_indices.view(-1)
324
+ expert_counts = torch.bincount(flat_topk_idx, minlength=self.num_routed_experts)
325
+ fi = expert_counts.float() / num_tokens_total
326
+ Pi = scores.nan_to_num().mean(dim=0)
327
+ aux_loss = torch.sum(fi * Pi) * self.aux_loss_weight
328
+ else:
329
+ aux_loss = torch.tensor(0.0, device=x.device)
330
+ expert_counts = None
331
+
332
+ # 3. Shared experts
333
+ shared_out = 0
334
+ if self.num_shared_experts > 0:
335
+ for expert in self.shared_experts:
336
+ shared_out = shared_out + expert(hidden_states)
337
+
338
+ # 4. Bottleneck projection
339
+ down_proj_hidden = self.w_down_proj(hidden_states)
340
+
341
+ # 5. Routed experts (padded BMM dispatch)
342
+ flat_topk_idx = topk_indices.view(-1).clamp(0, self.num_routed_experts - 1)
343
+ sorted_experts, permutation = torch.sort(flat_topk_idx)
344
+
345
+ if self._cached_N == N and self._cached_K == K:
346
+ token_indices, global_rel_idx = self._cached_indices
347
+ else:
348
+ token_indices = torch.arange(N, device=x.device).repeat_interleave(K)
349
+ global_rel_idx = torch.arange(num_tokens_total, device=x.device)
350
+ self._cached_N, self._cached_K = N, K
351
+ self._cached_indices = (token_indices, global_rel_idx)
352
+
353
+ max_load = ((num_tokens_total // self.num_routed_experts) // 8 + 6) * 8
354
+ used_counts = expert_counts if expert_counts is not None else torch.bincount(flat_topk_idx, minlength=self.num_routed_experts)
355
+ expert_ptr = torch.cumsum(used_counts, dim=0) - used_counts
356
+
357
+ local_idx = global_rel_idx - expert_ptr.index_select(0, sorted_experts)
358
+ capacity_mask = local_idx < max_load
359
+ valid_slots = sorted_experts[capacity_mask] * max_load + local_idx[capacity_mask]
360
+ num_slots = self.num_routed_experts * max_load
361
+
362
+ hidden_with_dummy = torch.cat([down_proj_hidden, self._dummy_token], dim=0)
363
+ reverse_map = torch.full((num_slots,), N, device=x.device, dtype=torch.long)
364
+ reverse_map.scatter_(0, valid_slots.long(), token_indices[permutation][capacity_mask])
365
+
366
+ padding = hidden_with_dummy.index_select(0, reverse_map).view(self.num_routed_experts, max_load, self.bottle_dim)
367
+
368
+ h12 = torch.bmm(padding, self.experts_w12)
369
+ h1, h2 = h12.chunk(2, dim=-1)
370
+ padded_out = torch.bmm(F.silu(h1) * h2, self.experts_w3)
371
+
372
+ padded_out_flat = padded_out.view(-1, self.bottle_dim)
373
+ padded_out_with_dummy = torch.cat([padded_out_flat, self._dummy_out], dim=0)
374
+
375
+ gather_map = torch.full((num_tokens_total,), num_slots, device=x.device, dtype=torch.long)
376
+ gather_map.scatter_(0, permutation[capacity_mask], valid_slots)
377
+
378
+ gathered_out = padded_out_with_dummy.index_select(0, gather_map).view(N, K, self.bottle_dim)
379
+
380
+ routed_out_bottle = torch.bmm(gating_scores.to(gathered_out.dtype).unsqueeze(1), gathered_out).squeeze(1)
381
+ routed_out = self.w_up_proj(routed_out_bottle)
382
+
383
+ if self.training:
384
+ mean_load = num_tokens_total / self.num_routed_experts
385
+ self._pending_violation = (mean_load - used_counts.float()) / (mean_load + 1e-6)
386
+
387
+ route_scale = math.sqrt(self.top_k) if self.training else 1.0
388
+ out = (shared_out + routed_out * route_scale) * self.moe_scale
389
+ out = out.view(batch_size, seq_len, d_model).to(x.dtype)
390
+
391
+ return out, z_loss + aux_loss
392
+
393
+ def update_bias(self, counts, num_tokens):
394
+ expert_counts = counts.float()
395
+ mean_load = num_tokens * self.top_k / self.num_routed_experts
396
+ violation = (mean_load - expert_counts) / (mean_load + 1e-6)
397
+ clamped_update = torch.tanh(self.smebu_kappa * violation)
398
+ delta_bi = self.smebu_lambda * clamped_update
399
+ delta_bi = delta_bi - delta_bi.mean()
400
+ self.expert_momentum.data = self.smebu_beta * self.expert_momentum.data + (1 - self.smebu_beta) * delta_bi
401
+ self.expert_bias.data = (self.expert_bias.data + self.expert_momentum.data).nan_to_num_().clamp(-10.0, 10.0)
402
+ self.expert_bias.data -= self.expert_bias.data.mean()
403
+ current_max_vio = -violation.min()
404
+ self.max_vio.copy_(0.99 * self.max_vio + 0.01 * current_max_vio)
405
+
406
+
407
+ class GroupedMoE(nn.Module):
408
+ """Grouped MoE fallback — for non-BigMac configs."""
409
+
410
+ def __init__(self, config, layer_idx=None):
411
+ super().__init__()
412
+ self.d_model = config.d_model
413
+ self.num_shared_experts = getattr(config, 'num_shared_experts', 1)
414
+ self.num_routed_experts = getattr(config, 'num_routed_experts', 64)
415
+ self.top_k = getattr(config, 'top_k', 6)
416
+ self.shared_expert_size = getattr(config, 'shared_expert_size', config.d_ff)
417
+ self.routed_expert_size = getattr(config, 'routed_expert_size', 1408)
418
+ self.layer_idx = layer_idx
419
+
420
+ self.shared_experts = nn.ModuleList([
421
+ SwiGLUBlock(self.d_model, self.shared_expert_size)
422
+ for _ in range(self.num_shared_experts)
423
+ ])
424
+ self.experts_w12 = nn.Parameter(torch.zeros(self.num_routed_experts, self.d_model, 2 * self.routed_expert_size))
425
+ self.experts_w3 = nn.Parameter(torch.zeros(self.num_routed_experts, self.routed_expert_size, self.d_model))
426
+ self.router = nn.Linear(config.d_model, config.num_routed_experts, bias=False)
427
+ with torch.no_grad():
428
+ nn.init.normal_(self.router.weight, std=0.01)
429
+ self.z_loss_weight = getattr(config, 'moe_z_loss_coeff', 1e-6)
430
+ self.aux_loss_weight = getattr(config, 'moe_aux_loss_coeff', 1e-4)
431
+ self.smebu_kappa = getattr(config, 'smebu_kappa', 2.0)
432
+ self.smebu_lambda = getattr(config, 'smebu_lambda', 5e-4)
433
+ self.smebu_beta = getattr(config, 'smebu_beta', 0.5)
434
+ self.register_buffer("max_vio", torch.tensor(0.0))
435
+ self.moe_scale = 1.0 / (1.0 + float(self.num_shared_experts > 0))
436
+
437
+ def _init_weights(self, std=0.011):
438
+ nn.init.normal_(self.experts_w12, std=std)
439
+ nn.init.normal_(self.experts_w3, std=std)
440
+ for expert in self.shared_experts:
441
+ nn.init.normal_(expert.gate.weight, std=std)
442
+ nn.init.normal_(expert.up.weight, std=std)
443
+ nn.init.normal_(expert.down.weight, std=std)
444
+
445
+ def forward(self, x, expert_bias=None):
446
+ batch_size, seq_len, d_model = x.shape
447
+ hidden_states = x.view(-1, d_model)
448
+ N, D = hidden_states.shape
449
+ K = self.top_k
450
+
451
+ with torch.autocast(device_type=x.device.type, dtype=torch.float32):
452
+ logits = self.router(hidden_states)
453
+ scores = torch.sigmoid(logits)
454
+ z_loss = torch.mean(logits.nan_to_num() ** 2) * self.z_loss_weight
455
+ bias = expert_bias if expert_bias is not None else torch.zeros(self.num_routed_experts, device=x.device)
456
+ selection_scores = scores + bias
457
+ _, topk_indices = torch.topk(selection_scores, K, dim=-1)
458
+ topk_indices = topk_indices.clamp(0, logits.shape[1] - 1)
459
+ topk_logits = torch.gather(logits, 1, topk_indices)
460
+ gating_scores = F.softmax(topk_logits, dim=-1).to(torch.bfloat16)
461
+
462
+ if self.training:
463
+ flat_topk_idx = topk_indices.view(-1)
464
+ expert_counts = torch.bincount(flat_topk_idx, minlength=self.num_routed_experts)
465
+ fi = expert_counts.float() / (N * K)
466
+ Pi = scores.nan_to_num().mean(dim=0)
467
+ aux_loss = torch.sum(fi * Pi) * self.aux_loss_weight
468
+ self._pending_violation = fi.detach() - (1.0 / self.num_routed_experts)
469
+ else:
470
+ aux_loss = torch.tensor(0.0, device=x.device)
471
+ expert_counts = None
472
+ self._pending_violation = torch.zeros(self.num_routed_experts, device=x.device)
473
+
474
+ shared_out = 0
475
+ if self.num_shared_experts > 0:
476
+ for expert in self.shared_experts:
477
+ shared_out = shared_out + expert(hidden_states)
478
+
479
+ # Padded BMM dispatch
480
+ num_experts = self.num_routed_experts
481
+ flat_topk_idx = topk_indices.view(-1)
482
+ tokens_per_expert = torch.bincount(flat_topk_idx, minlength=num_experts)
483
+ max_tokens = tokens_per_expert.max().item()
484
+
485
+ if max_tokens == 0:
486
+ out = shared_out * self.moe_scale
487
+ return out.view(batch_size, seq_len, d_model).to(x.dtype), aux_loss
488
+
489
+ sorted_indices = torch.argsort(flat_topk_idx)
490
+ token_indices = torch.arange(N, device=x.device).repeat_interleave(K)[sorted_indices]
491
+ grouped_x = hidden_states[token_indices]
492
+ padded_x = torch.zeros(num_experts, max_tokens, D, device=x.device, dtype=x.dtype)
493
+ expert_starts = torch.cat([torch.tensor([0], device=x.device), tokens_per_expert[:-1].cumsum(0)])
494
+ intra_offsets = torch.arange(N * K, device=x.device) - expert_starts.repeat_interleave(tokens_per_expert)
495
+ expert_idx = flat_topk_idx[sorted_indices]
496
+ padded_x_flat = padded_x.view(-1, D)
497
+ flat_dest_indices = expert_idx * max_tokens + intra_offsets
498
+ padded_x_flat.index_put_((flat_dest_indices,), grouped_x)
499
+ h12 = torch.bmm(padded_x, self.experts_w12)
500
+ h1, h2 = h12.chunk(2, dim=-1)
501
+ h = F.silu(h1) * h2
502
+ expert_out_padded = torch.bmm(h, self.experts_w3)
503
+ full_expert_out = expert_out_padded.view(-1, D)[flat_dest_indices]
504
+ gating_flat = gating_scores.view(-1)
505
+ sorted_gating = gating_flat[sorted_indices].unsqueeze(1)
506
+ weighted_out = full_expert_out * sorted_gating
507
+ routed_out = torch.zeros_like(hidden_states)
508
+ routed_out.index_add_(0, token_indices, weighted_out)
509
+
510
+ route_scale = math.sqrt(self.top_k) if self.training else 1.0
511
+ out = (shared_out + routed_out * route_scale) * self.moe_scale
512
+ out = out.view(batch_size, seq_len, d_model).to(x.dtype)
513
+ return out, z_loss + aux_loss
514
+
515
+
516
+ # ===================================================================
517
+ # HybridBlock — one transformer layer
518
+ # Weight names: ln1.weight, ln1_out.weight, ln2.weight, ln2_out.weight,
519
+ # attn.*, memory.*, W_alpha.*, C_to_hidden.*,
520
+ # ffn.*, injection_gate
521
+ # ===================================================================
522
+ class HybridBlock(nn.Module):
523
+ def __init__(self, config: QuasarConfig, layer_idx: int):
524
+ super().__init__()
525
+ self.hidden_size = config.d_model
526
+ self.layer_idx = layer_idx
527
+ self.n_layers = config.n_layers
528
+ self.config = config
529
+ self.gradient_checkpointing = False
530
+
531
+ # Looped Transformer injection gate (checkpoint always has it)
532
+ self.use_looped_injection = config.use_looped_injection
533
+ self.injection_gate = nn.Parameter(torch.tensor([-2.197]))
534
+
535
+ # Determine layer type (use hybrid_layer_types for quasar/gla distinction)
536
+ self.layer_type = config.hybrid_layer_types[layer_idx]
537
+
538
+ # Attention layer
539
+ if self.layer_type == "quasar":
540
+ self.attn = QuasarAttention(
541
+ mode=config.attn_mode,
542
+ hidden_size=config.d_model,
543
+ expand_v=config.expand_v,
544
+ head_dim=config.head_dim,
545
+ num_heads=config.n_heads,
546
+ num_v_heads=config.num_v_heads,
547
+ use_short_conv=config.use_short_conv,
548
+ allow_neg_eigval=config.allow_neg_eigval,
549
+ conv_size=config.conv_size,
550
+ norm_eps=config.rms_norm_eps,
551
+ layer_idx=layer_idx,
552
+ )
553
+ elif self.layer_type == "gla":
554
+ self.attn = GatedLinearAttention(
555
+ mode=config.gla_mode,
556
+ hidden_size=config.d_model,
557
+ expand_k=config.expand_k,
558
+ expand_v=config.expand_v,
559
+ num_heads=config.n_heads,
560
+ layer_idx=layer_idx,
561
+ )
562
+ # Latent Memory Module
563
+ self.memory = LatentMemoryModule(
564
+ hidden_size=config.d_model,
565
+ memory_slots=config.memory_slots,
566
+ memory_dim=config.memory_dim,
567
+ use_triton=False,
568
+ )
569
+ nn.init.constant_(self.memory.W_eta.bias, -1.0)
570
+ self.W_alpha = nn.Linear(config.d_model, 1)
571
+ self.C_to_hidden = nn.Linear(config.memory_dim, config.d_model, bias=False)
572
+ else:
573
+ raise ValueError(f"Unknown layer_type: {self.layer_type}")
574
+
575
+ # Sandwich norms
576
+ self.ln1 = RMSNorm(config.d_model, eps=config.rms_norm_eps)
577
+ self.ln1_out = RMSNorm(config.d_model, eps=config.rms_norm_eps)
578
+ self.ln2 = RMSNorm(config.d_model, eps=config.rms_norm_eps)
579
+ self.ln2_out = RMSNorm(config.d_model, eps=config.rms_norm_eps)
580
+
581
+ # FFN vs MoE
582
+ dense_layers = config.dense_input_layers
583
+ num_routed = config.num_routed_experts
584
+
585
+ if layer_idx < dense_layers or num_routed == 0:
586
+ self.is_moe = False
587
+ self.ffn = SwiGLUBlock(config.d_model, config.d_ff)
588
+ else:
589
+ self.is_moe = True
590
+ if config.moe_type == "bigmac":
591
+ self.ffn = BigMacMoE(config, layer_idx=layer_idx)
592
+ elif config.moe_type == "deepseek":
593
+ # DeepSeekMoE could be added here if needed
594
+ self.ffn = BigMacMoE(config, layer_idx=layer_idx)
595
+ else:
596
+ self.ffn = GroupedMoE(config, layer_idx=layer_idx)
597
+
598
+ self.dropout = nn.Dropout(config.dropout)
599
+ self.scale_factor = 1.0 / math.sqrt(2 * self.n_layers)
600
+ self.residual_scale = config.residual_scale
601
+
602
+ self._init_weights()
603
+
604
+ def _init_weights(self):
605
+ trinity_std = 0.5 / math.sqrt(self.hidden_size)
606
+
607
+ if self.layer_type == "gla":
608
+ nn.init.constant_(self.W_alpha.bias, -10.0)
609
+ nn.init.zeros_(self.W_alpha.weight)
610
+ nn.init.normal_(self.C_to_hidden.weight, std=trinity_std)
611
+
612
+ def apply_deep_init(m):
613
+ if hasattr(m, 'down') and isinstance(m.down, nn.Linear):
614
+ nn.init.normal_(m.down.weight, mean=0.0, std=trinity_std * self.scale_factor)
615
+
616
+ if not self.is_moe:
617
+ nn.init.normal_(self.ffn.gate.weight, mean=0.0, std=trinity_std)
618
+ nn.init.normal_(self.ffn.up.weight, mean=0.0, std=trinity_std)
619
+ apply_deep_init(self.ffn)
620
+ else:
621
+ self.ffn._init_weights(std=trinity_std)
622
+ for expert in self.ffn.shared_experts:
623
+ apply_deep_init(expert)
624
+ nn.init.normal_(self.ffn.experts_w3, mean=0.0, std=trinity_std)
625
+
626
+ nn.init.constant_(self.ln1_out.weight, 1.0)
627
+ nn.init.constant_(self.ln2_out.weight, 1.0)
628
+
629
+ if hasattr(self.attn, 'o_proj') and isinstance(self.attn.o_proj, nn.Linear):
630
+ nn.init.normal_(self.attn.o_proj.weight, mean=0.0, std=trinity_std * self.scale_factor)
631
+ for proj_name in ['q_proj', 'k_proj', 'v_proj', 'g_proj']:
632
+ if hasattr(self.attn, proj_name):
633
+ m = getattr(self.attn, proj_name)
634
+ if isinstance(m, nn.Linear):
635
+ nn.init.normal_(m.weight, mean=0.0, std=trinity_std)
636
+ elif isinstance(m, nn.Sequential):
637
+ for subm in m:
638
+ if isinstance(subm, nn.Linear):
639
+ nn.init.normal_(subm.weight, mean=0.0, std=trinity_std)
640
+
641
+ def forward(self, x, cos=None, sin=None, expert_bias=None,
642
+ memory_state=None, lambda_reg=0.01, **kwargs):
643
+ if self.use_looped_injection:
644
+ P = kwargs.get('P')
645
+ if P is not None:
646
+ x = x + (torch.sigmoid(self.injection_gate) * P)
647
+
648
+ if self.gradient_checkpointing and self.training:
649
+ return torch.utils.checkpoint.checkpoint(
650
+ self._forward, x, cos, sin, expert_bias, memory_state, lambda_reg,
651
+ use_reentrant=False, **kwargs,
652
+ )
653
+ return self._forward(x, cos, sin, expert_bias, memory_state, lambda_reg, **kwargs)
654
+
655
+ def _forward(self, x, cos=None, sin=None, expert_bias=None,
656
+ memory_state=None, lambda_reg=0.01, **kwargs):
657
+ # 1. Attention block
658
+ residual = x
659
+ x = self.ln1(x)
660
+
661
+ # Build attention kwargs
662
+ attn_kwargs = {}
663
+ if cos is not None and sin is not None:
664
+ attn_kwargs['cos'] = cos
665
+ attn_kwargs['sin'] = sin
666
+
667
+ # Pass past_key_values for FLA cache support
668
+ if 'past_key_values' in kwargs and kwargs['past_key_values'] is not None:
669
+ attn_kwargs['past_key_values'] = kwargs['past_key_values']
670
+ if 'use_cache' in kwargs:
671
+ attn_kwargs['use_cache'] = kwargs['use_cache']
672
+
673
+ attn_out = self.attn(x, **attn_kwargs)
674
+ if isinstance(attn_out, tuple):
675
+ attn_out = attn_out[0]
676
+
677
+ new_memory_state = None
678
+ mem_loss = torch.tensor(0.0, device=x.device)
679
+
680
+ # GLA layers: read/write latent memory
681
+ if self.layer_type == "gla" and memory_state is not None:
682
+ new_memory_state, total_mem_loss, _ = self.memory.write_memory(x, memory_state)
683
+ C = self.memory.read_memory(x, new_memory_state)
684
+ alpha = torch.sigmoid(self.W_alpha(x))
685
+ C_proj = self.C_to_hidden(C)
686
+ attn_out = attn_out + (alpha * C_proj)
687
+ mem_loss = total_mem_loss
688
+
689
+ # Sandwich norm + residual scaling
690
+ x = residual + self.residual_scale * self.dropout(self.ln1_out(attn_out))
691
+
692
+ # 2. FFN / MoE block
693
+ residual = x
694
+ x = self.ln2(x)
695
+ if self.is_moe:
696
+ block_out, aux_loss = self.ffn(x, expert_bias=expert_bias)
697
+ else:
698
+ block_out = self.ffn(x)
699
+ aux_loss = torch.tensor(0.0, device=x.device)
700
+
701
+ x = residual + self.residual_scale * self.dropout(self.ln2_out(block_out))
702
+ return x, aux_loss, new_memory_state, mem_loss
703
+
704
+
705
+ # ===================================================================
706
+ # Output dataclasses
707
+ # ===================================================================
708
+ @dataclass
709
+ class QuasarModelOutputWithPast(BaseModelOutputWithPast):
710
+ memory_states: dict | None = None
711
+ memory_loss: torch.Tensor | None = None
712
+
713
+
714
+ @dataclass
715
+ class QuasarCausalLMOutputWithPast(CausalLMOutputWithPast):
716
+ memory_states: dict | None = None
717
+ memory_loss: torch.Tensor | None = None
718
+ aux_loss: torch.Tensor | None = None
719
+
720
+
721
+ # ===================================================================
722
+ # PreTrainedModel base
723
+ # ===================================================================
724
+ class QuasarPreTrainedModel(PreTrainedModel):
725
+ config_class = QuasarConfig
726
+ base_model_prefix = "model"
727
+ supports_gradient_checkpointing = True
728
+ _no_split_modules = ["HybridBlock"]
729
+ _supports_cache_class = True
730
+
731
+ def _init_weights(self, module):
732
+ std = getattr(self.config, "initializer_range", 0.02)
733
+ if isinstance(module, nn.Linear):
734
+ nn.init.normal_(module.weight, mean=0.0, std=std)
735
+ if module.bias is not None:
736
+ nn.init.zeros_(module.bias)
737
+ elif isinstance(module, nn.Embedding):
738
+ nn.init.normal_(module.weight, mean=0.0, std=0.02)
739
+ if module.padding_idx is not None:
740
+ module.weight.data[module.padding_idx].zero_()
741
+
742
+
743
+ # ===================================================================
744
+ # QuasarModel — base transformer (no LM head)
745
+ # Weight prefix: model.* (embed_tokens, embed_norm, layers, norm, rotary_emb, all_moe_*)
746
+ # ===================================================================
747
+ class QuasarModel(QuasarPreTrainedModel):
748
+ config: QuasarConfig
749
+
750
+ def __init__(self, config: QuasarConfig):
751
+ super().__init__(config)
752
+ self.config = config
753
+ d_model = config.d_model
754
+ n_heads = config.n_heads
755
+ n_layers = config.n_layers
756
+ vocab_size = config.vocab_size
757
+ max_seq_len = config.max_seq_len
758
+
759
+ self.embed_tokens = nn.Embedding(vocab_size, d_model)
760
+ self.embed_norm = RMSNorm(d_model, eps=config.rms_norm_eps)
761
+ self.layers = nn.ModuleList([
762
+ HybridBlock(config, i) for i in range(n_layers)
763
+ ])
764
+ self.norm = RMSNorm(d_model, eps=config.rms_norm_eps)
765
+ self.rotary_emb = RotaryEmbedding(
766
+ d_model // n_heads, max_seq_len, base=config.rope_theta,
767
+ )
768
+
769
+ # SMEBU global buffers — sized [num_moe, num_experts] to match checkpoint
770
+ self.moe_layer_ffns = [l.ffn for l in self.layers if getattr(l, 'is_moe', False)]
771
+ self.num_moe = len(self.moe_layer_ffns)
772
+ num_experts = config.num_routed_experts
773
+ if self.num_moe > 0 and num_experts > 0:
774
+ self.register_buffer("all_moe_bias", torch.zeros(self.num_moe, num_experts))
775
+ self.register_buffer("all_moe_momentum", torch.zeros(self.num_moe, num_experts))
776
+ self.register_buffer("all_moe_max_vio", torch.zeros(self.num_moe))
777
+
778
+ self.gradient_checkpointing = False
779
+ self.post_init()
780
+
781
+ def get_input_embeddings(self):
782
+ return self.embed_tokens
783
+
784
+ def set_input_embeddings(self, value):
785
+ self.embed_tokens = value
786
+
787
+ def init_memory(self, batch_size, device, dtype=torch.float32):
788
+ memory_states = {}
789
+ for i, layer in enumerate(self.layers):
790
+ if layer.layer_type == "gla":
791
+ m = torch.zeros(batch_size, layer.memory.K, layer.memory.D, device=device, dtype=dtype)
792
+ memory_states[i] = m
793
+ return memory_states
794
+
795
+ def forward(
796
+ self,
797
+ input_ids: torch.LongTensor | None = None,
798
+ attention_mask: torch.Tensor | None = None,
799
+ position_ids: torch.LongTensor | None = None,
800
+ past_key_values: Cache | None = None,
801
+ inputs_embeds: torch.FloatTensor | None = None,
802
+ use_cache: bool | None = None,
803
+ output_hidden_states: bool | None = None,
804
+ memory_states: dict | None = None,
805
+ lambda_reg: float = 0.01,
806
+ **kwargs,
807
+ ):
808
+ output_hidden_states = output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states
809
+ use_cache = use_cache if use_cache is not None else self.config.use_cache
810
+
811
+ if (input_ids is None) ^ (inputs_embeds is not None):
812
+ raise ValueError("Specify exactly one of input_ids or inputs_embeds")
813
+
814
+ if inputs_embeds is None:
815
+ inputs_embeds = self.embed_tokens(input_ids)
816
+
817
+ # Embed norm for stability
818
+ hidden_states = self.embed_norm(inputs_embeds)
819
+ batch_size, seq_len, _ = hidden_states.shape
820
+
821
+ # Position ids
822
+ if position_ids is None:
823
+ past_seen_tokens = 0
824
+ if past_key_values is not None:
825
+ try:
826
+ past_seen_tokens = past_key_values.get_seq_length()
827
+ except Exception:
828
+ past_seen_tokens = 0
829
+ position_ids = torch.arange(past_seen_tokens, past_seen_tokens + seq_len, device=hidden_states.device)
830
+
831
+ # RoPE
832
+ max_pos = int(position_ids.max().item() + 1) if position_ids.numel() > 0 else seq_len
833
+ cos_full, sin_full = self.rotary_emb(hidden_states, seq_len=max_pos)
834
+ if position_ids.dim() == 1:
835
+ cos = cos_full[:, :, position_ids]
836
+ sin = sin_full[:, :, position_ids]
837
+ else:
838
+ cos = cos_full[:, :, position_ids[0]]
839
+ sin = sin_full[:, :, position_ids[0]]
840
+
841
+ # Memory states
842
+ if memory_states is None:
843
+ memory_states = self.init_memory(batch_size, hidden_states.device, hidden_states.dtype)
844
+
845
+ all_hidden_states = () if output_hidden_states else None
846
+ aux_losses = []
847
+ mem_losses = []
848
+ new_memory_states = {}
849
+
850
+ # Looped transformer anchor
851
+ P = hidden_states
852
+ num_loops = self.config.num_loops
853
+ current_memory_states = memory_states
854
+
855
+ # Snapshot expert bias for gradient checkpointing consistency
856
+ if self.num_moe > 0:
857
+ bias_snapshot = self.all_moe_bias.detach().clone()
858
+ else:
859
+ bias_snapshot = None
860
+
861
+ for loop_idx in range(num_loops):
862
+ moe_idx = 0
863
+ iteration_new_memory_states = {}
864
+ for layer in self.layers:
865
+ if output_hidden_states:
866
+ all_hidden_states += (hidden_states,)
867
+
868
+ bias = bias_snapshot[moe_idx] if (getattr(layer, 'is_moe', False) and bias_snapshot is not None) else None
869
+
870
+ layer_out = layer(
871
+ hidden_states,
872
+ cos=cos, sin=sin,
873
+ expert_bias=bias,
874
+ memory_state=current_memory_states.get(layer.layer_idx),
875
+ lambda_reg=lambda_reg,
876
+ P=P if self.config.use_looped_injection else None,
877
+ past_key_values=past_key_values,
878
+ use_cache=use_cache,
879
+ **kwargs,
880
+ )
881
+ hidden_states, aux_loss, new_m, m_loss = layer_out
882
+ if new_m is not None:
883
+ iteration_new_memory_states[layer.layer_idx] = new_m
884
+ mem_losses.append(m_loss)
885
+ if bias is not None:
886
+ moe_idx += 1
887
+ aux_losses.append(aux_loss)
888
+
889
+ current_memory_states = iteration_new_memory_states
890
+ new_memory_states = iteration_new_memory_states
891
+
892
+ # SMEBU bias update (no_grad to avoid checkpointing issues)
893
+ if self.training and self.num_moe > 0:
894
+ with torch.no_grad():
895
+ self._update_all_moe_biases()
896
+
897
+ hidden_states = self.norm(hidden_states)
898
+
899
+ if output_hidden_states:
900
+ all_hidden_states += (hidden_states,)
901
+
902
+ total_aux = torch.stack(aux_losses).sum() if aux_losses else torch.tensor(0.0, device=hidden_states.device)
903
+ total_mem = torch.stack(mem_losses).sum() if mem_losses else torch.tensor(0.0, device=hidden_states.device)
904
+
905
+ return QuasarModelOutputWithPast(
906
+ last_hidden_state=hidden_states,
907
+ past_key_values=past_key_values,
908
+ hidden_states=all_hidden_states,
909
+ memory_states=new_memory_states,
910
+ memory_loss=total_mem,
911
+ ), total_aux
912
+
913
+ def _update_all_moe_biases(self):
914
+ violations = torch.stack([m._pending_violation for m in self.moe_layer_ffns])
915
+ m0 = self.moe_layer_ffns[0]
916
+ kappa, lamb, beta = m0.smebu_kappa, m0.smebu_lambda, m0.smebu_beta
917
+ clamped_update = torch.tanh(kappa * violations)
918
+ delta_bi = lamb * clamped_update
919
+ delta_bi = delta_bi - delta_bi.mean(dim=-1, keepdim=True)
920
+ self.all_moe_momentum.mul_(beta).add_(delta_bi, alpha=1 - beta)
921
+ self.all_moe_bias.add_(self.all_moe_momentum).nan_to_num_().clamp_(-10.0, 10.0)
922
+ self.all_moe_bias.sub_(self.all_moe_bias.mean(dim=-1, keepdim=True))
923
+ current_max_vios = -violations.min(dim=-1).values
924
+ self.all_moe_max_vio.mul_(0.99).add_(current_max_vios, alpha=0.01)
925
+ for i, moe in enumerate(self.moe_layer_ffns):
926
+ moe.max_vio.copy_(self.all_moe_max_vio[i])
927
+ del moe._pending_violation
928
+
929
+
930
+ # ===================================================================
931
+ # QuasarForCausalLM — with LM head + generation support
932
+ # Weight prefix: lm_head.* (top-level), model.* (from QuasarModel)
933
+ # ===================================================================
934
+ class QuasarForCausalLM(QuasarPreTrainedModel, FLAGenerationMixin):
935
+ config: QuasarConfig
936
+ _tied_weights_keys = {}
937
+
938
+ def __init__(self, config: QuasarConfig):
939
+ super().__init__(config)
940
+ self.model = QuasarModel(config)
941
+ self.vocab_size = config.vocab_size
942
+ self.lm_head = nn.Linear(config.d_model, config.vocab_size, bias=False)
943
+ # Fused linear cross-entropy: never materialises the [N, vocab_size]
944
+ # logits (vocab=248k here). No parameters/buffers -> no checkpoint keys.
945
+ self.criterion = (
946
+ _FusedLinearCE(ignore_index=-100, reduction="mean", use_l2warp=config.use_l2warp)
947
+ if _FusedLinearCE is not None else None
948
+ )
949
+ self.post_init()
950
+
951
+ def get_input_embeddings(self):
952
+ return self.model.embed_tokens
953
+
954
+ def set_input_embeddings(self, value):
955
+ self.model.embed_tokens = value
956
+
957
+ def get_output_embeddings(self):
958
+ return self.lm_head
959
+
960
+ def set_output_embeddings(self, new_embeddings):
961
+ self.lm_head = new_embeddings
962
+
963
+ def tie_weights(self, missing_keys=None, recompute_mapping=False):
964
+ pass # Don't tie — crashes FSDP
965
+
966
+ def forward(
967
+ self,
968
+ input_ids: torch.LongTensor | None = None,
969
+ attention_mask: torch.Tensor | None = None,
970
+ position_ids: torch.LongTensor | None = None,
971
+ past_key_values: Cache | None = None,
972
+ inputs_embeds: torch.FloatTensor | None = None,
973
+ labels: torch.LongTensor | None = None,
974
+ use_cache: bool | None = None,
975
+ output_hidden_states: bool | None = None,
976
+ memory_states: dict | None = None,
977
+ lambda_reg: float = 0.01,
978
+ return_dict: bool | None = None,
979
+ **kwargs,
980
+ ):
981
+ return_dict = return_dict if return_dict is not None else self.config.use_return_dict
982
+
983
+ model_outputs, total_aux = self.model(
984
+ input_ids=input_ids,
985
+ attention_mask=attention_mask,
986
+ position_ids=position_ids,
987
+ past_key_values=past_key_values,
988
+ inputs_embeds=inputs_embeds,
989
+ use_cache=use_cache,
990
+ output_hidden_states=output_hidden_states,
991
+ memory_states=memory_states,
992
+ lambda_reg=lambda_reg,
993
+ **kwargs,
994
+ )
995
+
996
+ hidden_states = model_outputs.last_hidden_state
997
+
998
+ loss = None
999
+ if labels is not None:
1000
+ shift_hidden = hidden_states[..., :-1, :].contiguous().view(-1, self.config.d_model)
1001
+ shift_labels = labels[..., 1:].contiguous().view(-1)
1002
+ if self.criterion is not None:
1003
+ # Fused path: reduction='mean' over non-ignored tokens == old
1004
+ # (sum / num_active). ignore_index handles -100; never builds
1005
+ # the full [N, vocab] logits. lm_head.bias is None.
1006
+ loss = self.criterion(shift_hidden, shift_labels,
1007
+ self.lm_head.weight, self.lm_head.bias)
1008
+ loss = loss + total_aux + model_outputs.memory_loss
1009
+ else:
1010
+ # Eager fallback: chunked CE (chunk bumped 256 -> 4096 to cut
1011
+ # Python/kernel-launch overhead) so we still avoid a giant logits.
1012
+ mask = shift_labels != -100
1013
+ if mask.any():
1014
+ active_hidden = shift_hidden[mask]
1015
+ active_labels = shift_labels[mask]
1016
+ chunk_size = 4096
1017
+ total_loss = 0.0
1018
+ total_tokens = active_labels.numel()
1019
+ for i in range(0, total_tokens, chunk_size):
1020
+ end = min(i + chunk_size, total_tokens)
1021
+ chunk_logits = self.lm_head(active_hidden[i:end])
1022
+ chunk_loss = F.cross_entropy(chunk_logits.float(), active_labels[i:end], reduction='sum')
1023
+ total_loss += chunk_loss
1024
+ loss = total_loss / total_tokens
1025
+ loss = loss + total_aux + model_outputs.memory_loss
1026
+ else:
1027
+ loss = torch.tensor(0.0, device=hidden_states.device, requires_grad=True)
1028
+ logits = None
1029
+ else:
1030
+ logits = self.lm_head(hidden_states)
1031
+
1032
+ if not return_dict:
1033
+ output = (logits,) + model_outputs[1:]
1034
+ return ((loss,) + output) if loss is not None else output
1035
+
1036
+ return QuasarCausalLMOutputWithPast(
1037
+ loss=loss,
1038
+ logits=logits,
1039
+ past_key_values=model_outputs.past_key_values,
1040
+ hidden_states=model_outputs.hidden_states,
1041
+ memory_states=model_outputs.memory_states,
1042
+ memory_loss=model_outputs.memory_loss,
1043
+ aux_loss=total_aux,
1044
+ )
1045
+
1046
+ def prepare_inputs_for_generation(
1047
+ self,
1048
+ input_ids,
1049
+ past_key_values=None,
1050
+ attention_mask=None,
1051
+ inputs_embeds=None,
1052
+ memory_states=None,
1053
+ cache_position=None,
1054
+ use_cache=True,
1055
+ **kwargs,
1056
+ ):
1057
+ if past_key_values is not None:
1058
+ if input_ids is not None:
1059
+ input_ids = input_ids[:, -1:]
1060
+ if inputs_embeds is not None:
1061
+ inputs_embeds = inputs_embeds[:, -1:]
1062
+
1063
+ if inputs_embeds is not None and past_key_values is None:
1064
+ model_inputs = {"inputs_embeds": inputs_embeds}
1065
+ else:
1066
+ model_inputs = {"input_ids": input_ids}
1067
+
1068
+ if memory_states is None and past_key_values is not None:
1069
+ memory_states = getattr(past_key_values, "memory_states", None)
1070
+
1071
+ model_inputs.update({
1072
+ "past_key_values": past_key_values,
1073
+ "use_cache": use_cache,
1074
+ "attention_mask": attention_mask,
1075
+ "cache_position": cache_position,
1076
+ "memory_states": memory_states,
1077
+ })
1078
+ return model_inputs
1079
+
1080
+ def update_model_kwargs_for_generation(self, outputs, model_kwargs, is_seq2seq=False, num_new_tokens=1):
1081
+ model_kwargs = super().update_model_kwargs_for_generation(
1082
+ outputs=outputs, model_kwargs=model_kwargs,
1083
+ is_seq2seq=is_seq2seq, num_new_tokens=num_new_tokens,
1084
+ )
1085
+ if getattr(outputs, "memory_states", None) is not None:
1086
+ model_kwargs["memory_states"] = outputs.memory_states
1087
+ return model_kwargs
1088
+
1089
+ def _reorder_cache(self, past_key_values, beam_idx):
1090
+ if past_key_values is None:
1091
+ return None
1092
+ return past_key_values.reorder_cache(beam_idx)
1093
+
1094
+
1095
+ __all__ = [
1096
+ "QuasarConfig",
1097
+ "QuasarPreTrainedModel",
1098
+ "QuasarModel",
1099
+ "QuasarForCausalLM",
1100
+ "QuasarModelOutputWithPast",
1101
+ "QuasarCausalLMOutputWithPast",
1102
+ ]
tokenizer.json ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:06b9509352d2af50381ab2247e083b80d32d5c0aba91c272ca9ff729b6a0e523
3
+ size 19989325
tokenizer_config.json ADDED
@@ -0,0 +1,32 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "add_prefix_space": false,
3
+ "audio_bos_token": "<|audio_start|>",
4
+ "audio_eos_token": "<|audio_end|>",
5
+ "audio_token": "<|audio_pad|>",
6
+ "backend": "tokenizers",
7
+ "bos_token": null,
8
+ "clean_up_tokenization_spaces": false,
9
+ "eos_token": "<|endoftext|>",
10
+ "errors": "replace",
11
+ "image_token": "<|image_pad|>",
12
+ "is_local": false,
13
+ "local_files_only": false,
14
+ "model_max_length": 262144,
15
+ "model_specific_special_tokens": {
16
+ "audio_bos_token": "<|audio_start|>",
17
+ "audio_eos_token": "<|audio_end|>",
18
+ "audio_token": "<|audio_pad|>",
19
+ "image_token": "<|image_pad|>",
20
+ "video_token": "<|video_pad|>",
21
+ "vision_bos_token": "<|vision_start|>",
22
+ "vision_eos_token": "<|vision_end|>"
23
+ },
24
+ "pad_token": "<|endoftext|>",
25
+ "pretokenize_regex": "(?i:'s|'t|'re|'ve|'m|'ll|'d)|[^\\r\\n\\p{L}\\p{N}]?[\\p{L}\\p{M}]+|\\p{N}| ?[^\\s\\p{L}\\p{M}\\p{N}]+[\\r\\n]*|\\s*[\\r\\n]+|\\s+(?!\\S)|\\s+",
26
+ "split_special_tokens": false,
27
+ "tokenizer_class": "Qwen2Tokenizer",
28
+ "unk_token": null,
29
+ "video_token": "<|video_pad|>",
30
+ "vision_bos_token": "<|vision_start|>",
31
+ "vision_eos_token": "<|vision_end|>"
32
+ }
trainer_state.json ADDED
The diff for this file is too large to render. See raw diff
 
training_args.bin ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:4cdb1ed267028349a87170d20b30e61615f02c6cbee9387353da80fcdfa995dd
3
+ size 6033