Richard commited on
Commit
2f68ae0
·
verified ·
1 Parent(s): 6fbbfed

Upload folder using huggingface_hub

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