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